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
robinandeer/puzzle
puzzle/server/blueprints/variants/views.py
https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/server/blueprints/variants/views.py#L16-L54
def variants(case_id): """Show all variants for a case.""" filters = parse_filters() values = [value for key, value in iteritems(filters) if not isinstance(value, dict) and key != 'skip'] is_active = any(values) variants, nr_of_variants = app.db.variants( case_id, skip=filters['skip'], filters={ 'gene_ids': filters['gene_symbols'], 'frequency': filters.get('frequency'), 'cadd': filters.get('cadd'), 'sv_len': filters.get('sv_len'), 'consequence': filters['selected_consequences'], 'genetic_models': filters['selected_models'], 'sv_types': filters['selected_sv_types'], 'gene_lists': filters['gene_lists'], 'impact_severities': filters['impact_severities'], 'gemini_query': filters['gemini_query'], 'range': filters['range'], } ) gene_lists = ([gene_list.list_id for gene_list in app.db.gene_lists()] if app.config['STORE_ENABLED'] else []) queries = ([(query.name or query.query, query.query) for query in app.db.gemini_queries()] if app.config['STORE_ENABLED'] else []) kwargs = dict(variants=variants, case_id=case_id, db=app.db, filters=filters, consequences=SO_TERMS, inheritance_models=INHERITANCE_MODELS_SHORT, gene_lists=gene_lists, impact_severities=IMPACT_LEVELS, is_active=is_active, nr_of_variants=nr_of_variants, queries=queries) if app.db.variant_type == 'sv': return render_template('sv_variants.html', sv_types=SV_TYPES, **kwargs) else: return render_template('variants.html', **kwargs)
[ "def", "variants", "(", "case_id", ")", ":", "filters", "=", "parse_filters", "(", ")", "values", "=", "[", "value", "for", "key", ",", "value", "in", "iteritems", "(", "filters", ")", "if", "not", "isinstance", "(", "value", ",", "dict", ")", "and", ...
Show all variants for a case.
[ "Show", "all", "variants", "for", "a", "case", "." ]
python
train
nerox8664/pytorch2keras
pytorch2keras/activation_layers.py
https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/activation_layers.py#L9-L32
def convert_relu(params, w_name, scope_name, inputs, layers, weights, names): """ Convert relu layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for keras layers """ print('Converting relu ...') if names == 'short': tf_name = 'RELU' + random_string(4) elif names == 'keep': tf_name = w_name else: tf_name = w_name + str(random.random()) relu = keras.layers.Activation('relu', name=tf_name) layers[scope_name] = relu(layers[inputs[0]])
[ "def", "convert_relu", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting relu ...'", ")", "if", "names", "==", "'short'", ":", "tf_name", "=", "'RELU'", "+", ...
Convert relu layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for keras layers
[ "Convert", "relu", "layer", "." ]
python
valid
jtwhite79/pyemu
pyemu/utils/helpers.py
https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/utils/helpers.py#L4002-L4087
def setup_fake_forward_run(pst,new_pst_name,org_cwd='.',bak_suffix="._bak",new_cwd='.'): """setup a fake forward run for a pst. The fake forward run simply copies existing backup versions of model output files to the outfiles pest(pp) is looking for. This is really a development option for debugging Parameters ---------- pst : pyemu.Pst new_pst_name : str org_cwd : str existing working dir new_cwd : str new working dir """ if new_cwd != org_cwd and not os.path.exists(new_cwd): os.mkdir(new_cwd) pairs = {} for output_file in pst.output_files: org_pth = os.path.join(org_cwd,output_file) new_pth = os.path.join(new_cwd,os.path.split(output_file)[-1]) assert os.path.exists(org_pth),org_pth shutil.copy2(org_pth,new_pth+bak_suffix) pairs[output_file] = os.path.split(output_file)[-1]+bak_suffix if new_cwd != org_cwd: for files in [pst.template_files,pst.instruction_files]: for f in files: raw = os.path.split(f) if len(raw[0]) == 0: raw = raw[1:] if len(raw) > 1: pth = os.path.join(*raw[:-1]) pth = os.path.join(new_cwd,pth) if not os.path.exists(pth): os.makedirs(pth) org_pth = os.path.join(org_cwd, f) new_pth = os.path.join(new_cwd, f) assert os.path.exists(org_pth), org_pth shutil.copy2(org_pth,new_pth) for f in pst.input_files: raw = os.path.split(f) if len(raw[0]) == 0: raw = raw[1:] if len(raw) > 1: pth = os.path.join(*raw[:-1]) pth = os.path.join(new_cwd, pth) if not os.path.exists(pth): os.makedirs(pth) for key,f in pst.pestpp_options.items(): if not isinstance(f,str): continue raw = os.path.split(f) if len(raw[0]) == 0: raw = raw[1:] if len(raw) > 1: pth = os.path.join(*raw[:-1]) pth = os.path.join(new_cwd, pth) if not os.path.exists(pth): os.makedirs(pth) org_pth = os.path.join(org_cwd, f) new_pth = os.path.join(new_cwd, f) if os.path.exists(org_pth): shutil.copy2(org_pth,new_pth) with open(os.path.join(new_cwd,"fake_forward_run.py"),'w') as f: f.write("import os\nimport shutil\n") for org,bak in pairs.items(): f.write("shutil.copy2('{0}','{1}')\n".format(bak,org)) pst.model_command = "python fake_forward_run.py" pst.write(os.path.join(new_cwd,new_pst_name)) return pst
[ "def", "setup_fake_forward_run", "(", "pst", ",", "new_pst_name", ",", "org_cwd", "=", "'.'", ",", "bak_suffix", "=", "\"._bak\"", ",", "new_cwd", "=", "'.'", ")", ":", "if", "new_cwd", "!=", "org_cwd", "and", "not", "os", ".", "path", ".", "exists", "("...
setup a fake forward run for a pst. The fake forward run simply copies existing backup versions of model output files to the outfiles pest(pp) is looking for. This is really a development option for debugging Parameters ---------- pst : pyemu.Pst new_pst_name : str org_cwd : str existing working dir new_cwd : str new working dir
[ "setup", "a", "fake", "forward", "run", "for", "a", "pst", ".", "The", "fake", "forward", "run", "simply", "copies", "existing", "backup", "versions", "of", "model", "output", "files", "to", "the", "outfiles", "pest", "(", "pp", ")", "is", "looking", "fo...
python
train
ashmastaflash/kal-wrapper
kalibrate/fn.py
https://github.com/ashmastaflash/kal-wrapper/blob/80ee03ab7bd3172ac26b769d6b442960f3424b0e/kalibrate/fn.py#L81-L90
def determine_device(kal_out): """Extract and return device from scan results.""" device = "" while device == "": for line in kal_out.splitlines(): if "Using device " in line: device = str(line.split(' ', 2)[-1]) if device == "": device = None return device
[ "def", "determine_device", "(", "kal_out", ")", ":", "device", "=", "\"\"", "while", "device", "==", "\"\"", ":", "for", "line", "in", "kal_out", ".", "splitlines", "(", ")", ":", "if", "\"Using device \"", "in", "line", ":", "device", "=", "str", "(", ...
Extract and return device from scan results.
[ "Extract", "and", "return", "device", "from", "scan", "results", "." ]
python
train
Yubico/python-yubico
yubico/yubikey_frame.py
https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_frame.py#L93-L134
def _debug_string(self, debug, data): """ Annotate a frames data, if debug is True. """ if not debug: return data if self.command in [ SLOT.CONFIG, SLOT.CONFIG2, SLOT.UPDATE1, SLOT.UPDATE2, SLOT.SWAP, ]: # annotate according to config_st (see ykdef.h) if yubico_util.ord_byte(data[-1]) == 0x80: return (data, "FFFFFFF") # F = Fixed data (16 bytes) if yubico_util.ord_byte(data[-1]) == 0x81: return (data, "FFFFFFF") if yubico_util.ord_byte(data[-1]) == 0x82: return (data, "FFUUUUU") # U = UID (6 bytes) if yubico_util.ord_byte(data[-1]) == 0x83: return (data, "UKKKKKK") # K = Key (16 bytes) if yubico_util.ord_byte(data[-1]) == 0x84: return (data, "KKKKKKK") if yubico_util.ord_byte(data[-1]) == 0x85: return (data, "KKKAAAA") # A = Access code to set (6 bytes) if yubico_util.ord_byte(data[-1]) == 0x86: return (data, "AAlETCr") # l = Length of fixed field (1 byte) # E = extFlags (1 byte) # T = tktFlags (1 byte) # C = cfgFlags (1 byte) # r = RFU (2 bytes) if yubico_util.ord_byte(data[-1]) == 0x87: return (data, "rCRaaaa") # CR = CRC16 checksum (2 bytes) # a = Access code to use (6 bytes) if yubico_util.ord_byte(data[-1]) == 0x88: return (data, 'aa') # after payload if yubico_util.ord_byte(data[-1]) == 0x89: return (data, " Scr") return (data, '')
[ "def", "_debug_string", "(", "self", ",", "debug", ",", "data", ")", ":", "if", "not", "debug", ":", "return", "data", "if", "self", ".", "command", "in", "[", "SLOT", ".", "CONFIG", ",", "SLOT", ".", "CONFIG2", ",", "SLOT", ".", "UPDATE1", ",", "S...
Annotate a frames data, if debug is True.
[ "Annotate", "a", "frames", "data", "if", "debug", "is", "True", "." ]
python
train
saltstack/salt
salt/modules/postgres.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L1858-L1880
def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas)
[ "def", "group_remove", "(", "groupname", ",", "user", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "maintenance_db", "=", "None", ",", "password", "=", "None", ",", "runas", "=", "None", ")", ":", "return", "_role_remove", "(",...
Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname'
[ "Removes", "a", "group", "from", "the", "Postgres", "server", "." ]
python
train
google/grr
grr/server/grr_response_server/hunts/implementation.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/hunts/implementation.py#L366-L384
def _GetSubFlowNetworkLimit(self): """Get current network limit for subflows.""" subflow_network_limit = None if self.runner_args.per_client_network_limit_bytes: subflow_network_limit = self.runner_args.per_client_network_limit_bytes if self.runner_args.network_bytes_limit: remaining_network_quota = ( self.runner_args.network_bytes_limit - self.context.network_bytes_sent) if subflow_network_limit is None: subflow_network_limit = remaining_network_quota else: subflow_network_limit = min(subflow_network_limit, remaining_network_quota) return subflow_network_limit
[ "def", "_GetSubFlowNetworkLimit", "(", "self", ")", ":", "subflow_network_limit", "=", "None", "if", "self", ".", "runner_args", ".", "per_client_network_limit_bytes", ":", "subflow_network_limit", "=", "self", ".", "runner_args", ".", "per_client_network_limit_bytes", ...
Get current network limit for subflows.
[ "Get", "current", "network", "limit", "for", "subflows", "." ]
python
train
markovmodel/PyEMMA
pyemma/msm/api.py
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/msm/api.py#L322-L625
def estimate_markov_model(dtrajs, lag, reversible=True, statdist=None, count_mode='sliding', weights='empirical', sparse=False, connectivity='largest', dt_traj='1 step', maxiter=1000000, maxerr=1e-8, score_method='VAMP2', score_k=10, mincount_connectivity='1/n'): r""" Estimates a Markov model from discrete trajectories Returns a :class:`MaximumLikelihoodMSM` that contains the estimated transition matrix and allows to compute a large number of quantities related to Markov models. Parameters ---------- dtrajs : list containing ndarrays(dtype=int) or ndarray(n, dtype=int) discrete trajectories, stored as integer ndarrays (arbitrary size) or a single ndarray for only one trajectory. lag : int lag time at which transitions are counted and the transition matrix is estimated. reversible : bool, optional If true compute reversible MSM, else non-reversible MSM statdist : (M,) ndarray, optional Stationary vector on the full state-space. Transition matrix will be estimated such that statdist is its equilibrium distribution. count_mode : str, optional, default='sliding' mode to obtain count matrices from discrete trajectories. Should be one of: * 'sliding' : A trajectory of length T will have :math:`T-\tau` counts at time indexes .. math:: (0 \rightarrow \tau), (1 \rightarrow \tau+1), ..., (T-\tau-1 \rightarrow T-1) * 'effective' : Uses an estimate of the transition counts that are statistically uncorrelated. Recommended when used with a Bayesian MSM. * 'sample' : A trajectory of length T will have :math:`T/\tau` counts at time indexes .. math:: (0 \rightarrow \tau), (\tau \rightarrow 2 \tau), ..., (((T/\tau)-1) \tau \rightarrow T) weights : str, optional can be used to re-weight non-equilibrium data to equilibrium. Must be one of the following: * 'empirical': Each trajectory frame counts as one. (default) * 'oom': Each transition is re-weighted using OOM theory, see [11]_. sparse : bool, optional If true compute count matrix, transition matrix and all derived quantities using sparse matrix algebra. In this case python sparse matrices will be returned by the corresponding functions instead of numpy arrays. This behavior is suggested for very large numbers of states (e.g. > 4000) because it is likely to be much more efficient. connectivity : str, optional Connectivity mode. Three methods are intended (currently only 'largest' is implemented) * 'largest' : The active set is the largest reversibly connected set. All estimation will be done on this subset and all quantities (transition matrix, stationary distribution, etc) are only defined on this subset and are correspondingly smaller than the full set of states * 'all' : The active set is the full set of states. Estimation will be conducted on each reversibly connected set separately. That means the transition matrix will decompose into disconnected submatrices, the stationary vector is only defined within subsets, etc. Currently not implemented. * 'none' : The active set is the full set of states. Estimation will be conducted on the full set of states without ensuring connectivity. This only permits nonreversible estimation. Currently not implemented. dt_traj : str, optional Description of the physical time corresponding to the lag. May be used by analysis algorithms such as plotting tools to pretty-print the axes. By default '1 step', i.e. there is no physical time unit. Specify by a number, whitespace and unit. Permitted units are (* is an arbitrary string): * 'fs', 'femtosecond*' * 'ps', 'picosecond*' * 'ns', 'nanosecond*' * 'us', 'microsecond*' * 'ms', 'millisecond*' * 's', 'second*' maxiter : int, optional Optional parameter with reversible = True. maximum number of iterations before the transition matrix estimation method exits maxerr : float, optional Optional parameter with reversible = True. convergence tolerance for transition matrix estimation. This specifies the maximum change of the Euclidean norm of relative stationary probabilities (:math:`x_i = \sum_k x_{ik}`). The relative stationary probability changes :math:`e_i = (x_i^{(1)} - x_i^{(2)})/(x_i^{(1)} + x_i^{(2)})` are used in order to track changes in small probabilities. The Euclidean norm of the change vector, :math:`|e_i|_2`, is compared to maxerr. score_method : str, optional, default='VAMP2' Score to be used with MSM score function. Available scores are based on the variational approach for Markov processes [13]_ [14]_: * 'VAMP1' Sum of singular values of the symmetrized transition matrix [14]_ . If the MSM is reversible, this is equal to the sum of transition matrix eigenvalues, also called Rayleigh quotient [13]_ [15]_ . * 'VAMP2' Sum of squared singular values of the symmetrized transition matrix [14]_ . If the MSM is reversible, this is equal to the kinetic variance [16]_ . score_k : int or None The maximum number of eigenvalues or singular values used in the score. If set to None, all available eigenvalues will be used. mincount_connectivity : float or '1/n' minimum number of counts to consider a connection between two states. Counts lower than that will count zero in the connectivity check and may thus separate the resulting transition matrix. The default evaluates to 1/nstates. Returns ------- msm : :class:`MaximumLikelihoodMSM <pyemma.msm.MaximumLikelihoodMSM>` Estimator object containing the MSM and estimation information. See also -------- MaximumLikelihoodMSM An MSM object that has been estimated from data .. autoclass:: pyemma.msm.estimators.maximum_likelihood_msm.MaximumLikelihoodMSM :members: :undoc-members: .. rubric:: Methods .. autoautosummary:: pyemma.msm.estimators.maximum_likelihood_msm.MaximumLikelihoodMSM :methods: .. rubric:: Attributes .. autoautosummary:: pyemma.msm.estimators.maximum_likelihood_msm.MaximumLikelihoodMSM :attributes: References ---------- The mathematical theory of Markov (state) model estimation was introduced in [1]_ . Further theoretical developments were made in [2]_ . The term Markov state model was coined in [3]_ . Continuous-time Markov models (Master equation models) were suggested in [4]_. Reversible Markov model estimation was introduced in [5]_ , and further developed in [6]_ [7]_ [9]_ . It was shown in [8]_ that the quality of Markov state models does in fact not depend on memory loss, but rather on where the discretization is suitable to approximate the eigenfunctions of the Markov operator (the 'reaction coordinates'). With a suitable choice of discretization and lag time, MSMs can thus become very accurate. [9]_ introduced a number of methodological improvements and gives a good overview of the methodological basics of Markov state modeling today. [10]_ is a more extensive review book of theory, methods and applications. .. [1] Schuette, C. , A. Fischer, W. Huisinga and P. Deuflhard: A Direct Approach to Conformational Dynamics based on Hybrid Monte Carlo. J. Comput. Phys., 151, 146-168 (1999) .. [2] Swope, W. C., J. W. Pitera and F. Suits: Describing protein folding kinetics by molecular dynamics simulations: 1. Theory J. Phys. Chem. B 108, 6571-6581 (2004) .. [3] Singhal, N., C. D. Snow, V. S. Pande: Using path sampling to build better Markovian state models: Predicting the folding rate and mechanism of a tryptophan zipper beta hairpin. J. Chem. Phys. 121, 415 (2004). .. [4] Sriraman, S., I. G. Kevrekidis and G. Hummer, G. J. Phys. Chem. B 109, 6479-6484 (2005) .. [5] Noe, F.: Probability Distributions of Molecular Observables computed from Markov Models. J. Chem. Phys. 128, 244103 (2008) .. [6] Buchete, N.-V. and Hummer, G.: Coarse master equations for peptide folding dynamics. J. Phys. Chem. B 112, 6057--6069 (2008) .. [7] Bowman, G. R., K. A. Beauchamp, G. Boxer and V. S. Pande: Progress and challenges in the automated construction of Markov state models for full protein systems. J. Chem. Phys. 131, 124101 (2009) .. [8] Sarich, M., F. Noe and C. Schuette: On the approximation quality of Markov state models. SIAM Multiscale Model. Simul. 8, 1154-1177 (2010) .. [9] Prinz, J.-H., H. Wu, M. Sarich, B. Keller, M. Senne, M. Held, J. D. Chodera, C. Schuette and F. Noe: Markov models of molecular kinetics: Generation and Validation J. Chem. Phys. 134, 174105 (2011) .. [10] Bowman, G. R., V. S. Pande and F. Noe: An Introduction to Markov State Models and Their Application to Long Timescale Molecular Simulation. Advances in Experimental Medicine and Biology 797, Springer, Heidelberg (2014) .. [11] Nueske, F., Wu, H., Prinz, J.-H., Wehmeyer, C., Clementi, C. and Noe, F.: Markov State Models from short non-Equilibrium Simulations - Analysis and Correction of Estimation Bias J. Chem. Phys. (submitted) (2017) .. [12] H. Wu and F. Noe: Variational approach for learning Markov processes from time series data (in preparation) .. [13] Noe, F. and F. Nueske: A variational approach to modeling slow processes in stochastic dynamical systems. SIAM Multiscale Model. Simul. 11, 635-655 (2013). .. [14] Wu, H and F. Noe: Variational approach for learning Markov processes from time series data (in preparation) .. [15] McGibbon, R and V. S. Pande: Variational cross-validation of slow dynamical modes in molecular kinetics, J. Chem. Phys. 142, 124105 (2015) .. [16] Noe, F. and C. Clementi: Kinetic distance and kinetic maps from molecular dynamics simulation. J. Chem. Theory Comput. 11, 5002-5011 (2015) Example ------- >>> from pyemma import msm >>> import numpy as np >>> np.set_printoptions(precision=3) >>> dtrajs = [[0,1,2,2,2,2,1,2,2,2,1,0,0,0,0,0,0,0], [0,0,0,0,1,1,2,2,2,2,2,2,2,1,0,0]] # two trajectories >>> mm = msm.estimate_markov_model(dtrajs, 2) Which is the active set of states we are working on? >>> print(mm.active_set) [0 1 2] Show the count matrix >>> print(mm.count_matrix_active) [[ 7. 2. 1.] [ 2. 0. 4.] [ 2. 3. 9.]] Show the estimated transition matrix >>> print(mm.transition_matrix) [[ 0.7 0.167 0.133] [ 0.388 0. 0.612] [ 0.119 0.238 0.643]] Is this model reversible (i.e. does it fulfill detailed balance)? >>> print(mm.is_reversible) True What is the equilibrium distribution of states? >>> print(mm.stationary_distribution) [ 0.393 0.17 0.437] Relaxation timescales? >>> print(mm.timescales()) [ 3.415 1.297] Mean first passage time from state 0 to 2: >>> print(mm.mfpt(0, 2)) # doctest: +ELLIPSIS 9.929... """ # Catch invalid inputs for weights: if isinstance(weights, str): if weights not in ['empirical', 'oom']: raise ValueError("Weights must be either \'empirical\' or \'oom\'") else: raise ValueError("Weights must be either \'empirical\' or \'oom\'") # transition matrix estimator if weights == 'empirical': mlmsm = _ML_MSM(lag=lag, reversible=reversible, statdist_constraint=statdist, count_mode=count_mode, sparse=sparse, connectivity=connectivity, dt_traj=dt_traj, maxiter=maxiter, maxerr=maxerr, score_method=score_method, score_k=score_k, mincount_connectivity=mincount_connectivity) # estimate and return return mlmsm.estimate(dtrajs) elif weights == 'oom': if (statdist is not None) or (maxiter != 1000000) or (maxerr != 1e-8): import warnings warnings.warn("Values for statdist, maxiter or maxerr are ignored if OOM-correction is used.") oom_msm = _OOM_MSM(lag=lag, reversible=reversible, count_mode=count_mode, sparse=sparse, connectivity=connectivity, dt_traj=dt_traj, score_method=score_method, score_k=score_k, mincount_connectivity=mincount_connectivity) # estimate and return return oom_msm.estimate(dtrajs)
[ "def", "estimate_markov_model", "(", "dtrajs", ",", "lag", ",", "reversible", "=", "True", ",", "statdist", "=", "None", ",", "count_mode", "=", "'sliding'", ",", "weights", "=", "'empirical'", ",", "sparse", "=", "False", ",", "connectivity", "=", "'largest...
r""" Estimates a Markov model from discrete trajectories Returns a :class:`MaximumLikelihoodMSM` that contains the estimated transition matrix and allows to compute a large number of quantities related to Markov models. Parameters ---------- dtrajs : list containing ndarrays(dtype=int) or ndarray(n, dtype=int) discrete trajectories, stored as integer ndarrays (arbitrary size) or a single ndarray for only one trajectory. lag : int lag time at which transitions are counted and the transition matrix is estimated. reversible : bool, optional If true compute reversible MSM, else non-reversible MSM statdist : (M,) ndarray, optional Stationary vector on the full state-space. Transition matrix will be estimated such that statdist is its equilibrium distribution. count_mode : str, optional, default='sliding' mode to obtain count matrices from discrete trajectories. Should be one of: * 'sliding' : A trajectory of length T will have :math:`T-\tau` counts at time indexes .. math:: (0 \rightarrow \tau), (1 \rightarrow \tau+1), ..., (T-\tau-1 \rightarrow T-1) * 'effective' : Uses an estimate of the transition counts that are statistically uncorrelated. Recommended when used with a Bayesian MSM. * 'sample' : A trajectory of length T will have :math:`T/\tau` counts at time indexes .. math:: (0 \rightarrow \tau), (\tau \rightarrow 2 \tau), ..., (((T/\tau)-1) \tau \rightarrow T) weights : str, optional can be used to re-weight non-equilibrium data to equilibrium. Must be one of the following: * 'empirical': Each trajectory frame counts as one. (default) * 'oom': Each transition is re-weighted using OOM theory, see [11]_. sparse : bool, optional If true compute count matrix, transition matrix and all derived quantities using sparse matrix algebra. In this case python sparse matrices will be returned by the corresponding functions instead of numpy arrays. This behavior is suggested for very large numbers of states (e.g. > 4000) because it is likely to be much more efficient. connectivity : str, optional Connectivity mode. Three methods are intended (currently only 'largest' is implemented) * 'largest' : The active set is the largest reversibly connected set. All estimation will be done on this subset and all quantities (transition matrix, stationary distribution, etc) are only defined on this subset and are correspondingly smaller than the full set of states * 'all' : The active set is the full set of states. Estimation will be conducted on each reversibly connected set separately. That means the transition matrix will decompose into disconnected submatrices, the stationary vector is only defined within subsets, etc. Currently not implemented. * 'none' : The active set is the full set of states. Estimation will be conducted on the full set of states without ensuring connectivity. This only permits nonreversible estimation. Currently not implemented. dt_traj : str, optional Description of the physical time corresponding to the lag. May be used by analysis algorithms such as plotting tools to pretty-print the axes. By default '1 step', i.e. there is no physical time unit. Specify by a number, whitespace and unit. Permitted units are (* is an arbitrary string): * 'fs', 'femtosecond*' * 'ps', 'picosecond*' * 'ns', 'nanosecond*' * 'us', 'microsecond*' * 'ms', 'millisecond*' * 's', 'second*' maxiter : int, optional Optional parameter with reversible = True. maximum number of iterations before the transition matrix estimation method exits maxerr : float, optional Optional parameter with reversible = True. convergence tolerance for transition matrix estimation. This specifies the maximum change of the Euclidean norm of relative stationary probabilities (:math:`x_i = \sum_k x_{ik}`). The relative stationary probability changes :math:`e_i = (x_i^{(1)} - x_i^{(2)})/(x_i^{(1)} + x_i^{(2)})` are used in order to track changes in small probabilities. The Euclidean norm of the change vector, :math:`|e_i|_2`, is compared to maxerr. score_method : str, optional, default='VAMP2' Score to be used with MSM score function. Available scores are based on the variational approach for Markov processes [13]_ [14]_: * 'VAMP1' Sum of singular values of the symmetrized transition matrix [14]_ . If the MSM is reversible, this is equal to the sum of transition matrix eigenvalues, also called Rayleigh quotient [13]_ [15]_ . * 'VAMP2' Sum of squared singular values of the symmetrized transition matrix [14]_ . If the MSM is reversible, this is equal to the kinetic variance [16]_ . score_k : int or None The maximum number of eigenvalues or singular values used in the score. If set to None, all available eigenvalues will be used. mincount_connectivity : float or '1/n' minimum number of counts to consider a connection between two states. Counts lower than that will count zero in the connectivity check and may thus separate the resulting transition matrix. The default evaluates to 1/nstates. Returns ------- msm : :class:`MaximumLikelihoodMSM <pyemma.msm.MaximumLikelihoodMSM>` Estimator object containing the MSM and estimation information. See also -------- MaximumLikelihoodMSM An MSM object that has been estimated from data .. autoclass:: pyemma.msm.estimators.maximum_likelihood_msm.MaximumLikelihoodMSM :members: :undoc-members: .. rubric:: Methods .. autoautosummary:: pyemma.msm.estimators.maximum_likelihood_msm.MaximumLikelihoodMSM :methods: .. rubric:: Attributes .. autoautosummary:: pyemma.msm.estimators.maximum_likelihood_msm.MaximumLikelihoodMSM :attributes: References ---------- The mathematical theory of Markov (state) model estimation was introduced in [1]_ . Further theoretical developments were made in [2]_ . The term Markov state model was coined in [3]_ . Continuous-time Markov models (Master equation models) were suggested in [4]_. Reversible Markov model estimation was introduced in [5]_ , and further developed in [6]_ [7]_ [9]_ . It was shown in [8]_ that the quality of Markov state models does in fact not depend on memory loss, but rather on where the discretization is suitable to approximate the eigenfunctions of the Markov operator (the 'reaction coordinates'). With a suitable choice of discretization and lag time, MSMs can thus become very accurate. [9]_ introduced a number of methodological improvements and gives a good overview of the methodological basics of Markov state modeling today. [10]_ is a more extensive review book of theory, methods and applications. .. [1] Schuette, C. , A. Fischer, W. Huisinga and P. Deuflhard: A Direct Approach to Conformational Dynamics based on Hybrid Monte Carlo. J. Comput. Phys., 151, 146-168 (1999) .. [2] Swope, W. C., J. W. Pitera and F. Suits: Describing protein folding kinetics by molecular dynamics simulations: 1. Theory J. Phys. Chem. B 108, 6571-6581 (2004) .. [3] Singhal, N., C. D. Snow, V. S. Pande: Using path sampling to build better Markovian state models: Predicting the folding rate and mechanism of a tryptophan zipper beta hairpin. J. Chem. Phys. 121, 415 (2004). .. [4] Sriraman, S., I. G. Kevrekidis and G. Hummer, G. J. Phys. Chem. B 109, 6479-6484 (2005) .. [5] Noe, F.: Probability Distributions of Molecular Observables computed from Markov Models. J. Chem. Phys. 128, 244103 (2008) .. [6] Buchete, N.-V. and Hummer, G.: Coarse master equations for peptide folding dynamics. J. Phys. Chem. B 112, 6057--6069 (2008) .. [7] Bowman, G. R., K. A. Beauchamp, G. Boxer and V. S. Pande: Progress and challenges in the automated construction of Markov state models for full protein systems. J. Chem. Phys. 131, 124101 (2009) .. [8] Sarich, M., F. Noe and C. Schuette: On the approximation quality of Markov state models. SIAM Multiscale Model. Simul. 8, 1154-1177 (2010) .. [9] Prinz, J.-H., H. Wu, M. Sarich, B. Keller, M. Senne, M. Held, J. D. Chodera, C. Schuette and F. Noe: Markov models of molecular kinetics: Generation and Validation J. Chem. Phys. 134, 174105 (2011) .. [10] Bowman, G. R., V. S. Pande and F. Noe: An Introduction to Markov State Models and Their Application to Long Timescale Molecular Simulation. Advances in Experimental Medicine and Biology 797, Springer, Heidelberg (2014) .. [11] Nueske, F., Wu, H., Prinz, J.-H., Wehmeyer, C., Clementi, C. and Noe, F.: Markov State Models from short non-Equilibrium Simulations - Analysis and Correction of Estimation Bias J. Chem. Phys. (submitted) (2017) .. [12] H. Wu and F. Noe: Variational approach for learning Markov processes from time series data (in preparation) .. [13] Noe, F. and F. Nueske: A variational approach to modeling slow processes in stochastic dynamical systems. SIAM Multiscale Model. Simul. 11, 635-655 (2013). .. [14] Wu, H and F. Noe: Variational approach for learning Markov processes from time series data (in preparation) .. [15] McGibbon, R and V. S. Pande: Variational cross-validation of slow dynamical modes in molecular kinetics, J. Chem. Phys. 142, 124105 (2015) .. [16] Noe, F. and C. Clementi: Kinetic distance and kinetic maps from molecular dynamics simulation. J. Chem. Theory Comput. 11, 5002-5011 (2015) Example ------- >>> from pyemma import msm >>> import numpy as np >>> np.set_printoptions(precision=3) >>> dtrajs = [[0,1,2,2,2,2,1,2,2,2,1,0,0,0,0,0,0,0], [0,0,0,0,1,1,2,2,2,2,2,2,2,1,0,0]] # two trajectories >>> mm = msm.estimate_markov_model(dtrajs, 2) Which is the active set of states we are working on? >>> print(mm.active_set) [0 1 2] Show the count matrix >>> print(mm.count_matrix_active) [[ 7. 2. 1.] [ 2. 0. 4.] [ 2. 3. 9.]] Show the estimated transition matrix >>> print(mm.transition_matrix) [[ 0.7 0.167 0.133] [ 0.388 0. 0.612] [ 0.119 0.238 0.643]] Is this model reversible (i.e. does it fulfill detailed balance)? >>> print(mm.is_reversible) True What is the equilibrium distribution of states? >>> print(mm.stationary_distribution) [ 0.393 0.17 0.437] Relaxation timescales? >>> print(mm.timescales()) [ 3.415 1.297] Mean first passage time from state 0 to 2: >>> print(mm.mfpt(0, 2)) # doctest: +ELLIPSIS 9.929...
[ "r", "Estimates", "a", "Markov", "model", "from", "discrete", "trajectories" ]
python
train
python-openxml/python-docx
docx/opc/package.py
https://github.com/python-openxml/python-docx/blob/6756f6cd145511d3eb6d1d188beea391b1ddfd53/docx/opc/package.py#L165-L172
def save(self, pkg_file): """ Save this package to *pkg_file*, where *file* can be either a path to a file (a string) or a file-like object. """ for part in self.parts: part.before_marshal() PackageWriter.write(pkg_file, self.rels, self.parts)
[ "def", "save", "(", "self", ",", "pkg_file", ")", ":", "for", "part", "in", "self", ".", "parts", ":", "part", ".", "before_marshal", "(", ")", "PackageWriter", ".", "write", "(", "pkg_file", ",", "self", ".", "rels", ",", "self", ".", "parts", ")" ]
Save this package to *pkg_file*, where *file* can be either a path to a file (a string) or a file-like object.
[ "Save", "this", "package", "to", "*", "pkg_file", "*", "where", "*", "file", "*", "can", "be", "either", "a", "path", "to", "a", "file", "(", "a", "string", ")", "or", "a", "file", "-", "like", "object", "." ]
python
train
timstaley/voeventdb
voeventdb/server/restapi/v1/filter_base.py
https://github.com/timstaley/voeventdb/blob/e37b176d65fced4ca4f059109a95d6974bb8a091/voeventdb/server/restapi/v1/filter_base.py#L76-L89
def apply_filters(query, args): """ Apply all QueryFilters, validating the querystring in the process. """ pre_joins = [] for querystring_key, filter_value in args.items(multi=True): if querystring_key in filter_registry: cls_inst = filter_registry[querystring_key] query = cls_inst.apply_filter(query, args, pre_joins) elif querystring_key in PaginationKeys._value_list: pass else: raise InvalidQueryString(querystring_key, filter_value) return query
[ "def", "apply_filters", "(", "query", ",", "args", ")", ":", "pre_joins", "=", "[", "]", "for", "querystring_key", ",", "filter_value", "in", "args", ".", "items", "(", "multi", "=", "True", ")", ":", "if", "querystring_key", "in", "filter_registry", ":", ...
Apply all QueryFilters, validating the querystring in the process.
[ "Apply", "all", "QueryFilters", "validating", "the", "querystring", "in", "the", "process", "." ]
python
train
simonvh/norns
norns/cfg.py
https://github.com/simonvh/norns/blob/81db0004c558f91479176daf1918b8c9473b5ee2/norns/cfg.py#L75-L80
def save(self): """ Save current state of config dictionary. """ with open(self.config_file, "w") as f: f.write(dump(self.config, default_flow_style=False))
[ "def", "save", "(", "self", ")", ":", "with", "open", "(", "self", ".", "config_file", ",", "\"w\"", ")", "as", "f", ":", "f", ".", "write", "(", "dump", "(", "self", ".", "config", ",", "default_flow_style", "=", "False", ")", ")" ]
Save current state of config dictionary.
[ "Save", "current", "state", "of", "config", "dictionary", "." ]
python
train
Clivern/PyLogging
pylogging/mailer.py
https://github.com/Clivern/PyLogging/blob/46a1442ec63796302ec7fe3d49bd06a0f7a2fe70/pylogging/mailer.py#L25-L43
def send(self, me, to, subject, msg): """ Send Message """ msg = MIMEText(msg) msg['Subject'] = subject msg['From'] = me msg['To'] = to server = smtplib.SMTP(self.host, self.port) server.starttls() # Check if user and password defined if self._usr and self._pwd: server.login(self._usr, self._pwd) try: # Send email server.sendmail(me, [x.strip() for x in to.split(",")], msg.as_string()) except: # Error sending email raise Exception("Error Sending Message.") # Quit! server.quit()
[ "def", "send", "(", "self", ",", "me", ",", "to", ",", "subject", ",", "msg", ")", ":", "msg", "=", "MIMEText", "(", "msg", ")", "msg", "[", "'Subject'", "]", "=", "subject", "msg", "[", "'From'", "]", "=", "me", "msg", "[", "'To'", "]", "=", ...
Send Message
[ "Send", "Message" ]
python
train
OpenHumans/open-humans-api
ohapi/api.py
https://github.com/OpenHumans/open-humans-api/blob/ca2a28cf5d55cfdae13dd222ba58c25565bdb86e/ohapi/api.py#L358-L385
def upload_file(target_filepath, metadata, access_token, base_url=OH_BASE_URL, remote_file_info=None, project_member_id=None, max_bytes=MAX_FILE_DEFAULT): """ Upload a file from a local filepath using the "direct upload" API. To learn more about this API endpoint see: * https://www.openhumans.org/direct-sharing/on-site-data-upload/ * https://www.openhumans.org/direct-sharing/oauth2-data-upload/ :param target_filepath: This field is the filepath of the file to be uploaded :param metadata: This field is a python dictionary with keys filename, description and tags for single user upload and filename, project member id, description and tags for multiple user upload. :param access_token: This is user specific access token/master token. :param base_url: It is this URL `https://www.openhumans.org`. :param remote_file_info: This field is for for checking if a file with matching name and file size already exists. Its default value is none. :param project_member_id: This field is the list of project member id of all members of a project. Its default value is None. :param max_bytes: This field is the maximum file size a user can upload. It's default value is 128m. """ with open(target_filepath, 'rb') as stream: filename = os.path.basename(target_filepath) return upload_stream(stream, filename, metadata, access_token, base_url, remote_file_info, project_member_id, max_bytes, file_identifier=target_filepath)
[ "def", "upload_file", "(", "target_filepath", ",", "metadata", ",", "access_token", ",", "base_url", "=", "OH_BASE_URL", ",", "remote_file_info", "=", "None", ",", "project_member_id", "=", "None", ",", "max_bytes", "=", "MAX_FILE_DEFAULT", ")", ":", "with", "op...
Upload a file from a local filepath using the "direct upload" API. To learn more about this API endpoint see: * https://www.openhumans.org/direct-sharing/on-site-data-upload/ * https://www.openhumans.org/direct-sharing/oauth2-data-upload/ :param target_filepath: This field is the filepath of the file to be uploaded :param metadata: This field is a python dictionary with keys filename, description and tags for single user upload and filename, project member id, description and tags for multiple user upload. :param access_token: This is user specific access token/master token. :param base_url: It is this URL `https://www.openhumans.org`. :param remote_file_info: This field is for for checking if a file with matching name and file size already exists. Its default value is none. :param project_member_id: This field is the list of project member id of all members of a project. Its default value is None. :param max_bytes: This field is the maximum file size a user can upload. It's default value is 128m.
[ "Upload", "a", "file", "from", "a", "local", "filepath", "using", "the", "direct", "upload", "API", ".", "To", "learn", "more", "about", "this", "API", "endpoint", "see", ":", "*", "https", ":", "//", "www", ".", "openhumans", ".", "org", "/", "direct"...
python
train
dropbox/pyannotate
pyannotate_tools/annotations/infer.py
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L194-L210
def merge_items(items): # type: (List[AbstractType]) -> List[AbstractType] """Merge union items that can be merged.""" result = [] while items: item = items.pop() merged = None for i, other in enumerate(items): merged = merged_type(item, other) if merged: break if merged: del items[i] items.append(merged) else: result.append(item) return list(reversed(result))
[ "def", "merge_items", "(", "items", ")", ":", "# type: (List[AbstractType]) -> List[AbstractType]", "result", "=", "[", "]", "while", "items", ":", "item", "=", "items", ".", "pop", "(", ")", "merged", "=", "None", "for", "i", ",", "other", "in", "enumerate"...
Merge union items that can be merged.
[ "Merge", "union", "items", "that", "can", "be", "merged", "." ]
python
train
mattiaslinnap/django-partial-index
partial_index/mixins.py
https://github.com/mattiaslinnap/django-partial-index/blob/6e60fd9484f95499587365fda34a881050bcd804/partial_index/mixins.py#L41-L89
def validate_partial_unique(self): """Check partial unique constraints on the model and raise ValidationError if any failed. We want to check if another instance already exists with the fields mentioned in idx.fields, but only if idx.where matches. But can't just check for the fields in idx.fields - idx.where may refer to other fields on the current (or other) models. Also can't check for all fields on the current model - should not include irrelevant fields which may hide duplicates. To find potential conflicts, we need to build a queryset which: 1. Filters by idx.fields with their current values on this instance, 2. Filters on idx.where 3. Filters by fields mentioned in idx.where, with their current values on this instance, 4. Excludes current object if it does not match the where condition. Note that step 2 ensures the lookup only looks for conflicts among rows covered by the PartialIndes, and steps 2+3 ensures that the QuerySet is empty if the PartialIndex does not cover the current object. """ # Find PartialIndexes with unique=True defined on model. unique_idxs = [idx for idx in self._meta.indexes if isinstance(idx, PartialIndex) and idx.unique] if unique_idxs: model_fields = set(f.name for f in self._meta.get_fields(include_parents=True, include_hidden=True)) for idx in unique_idxs: where = idx.where if not isinstance(where, Q): raise ImproperlyConfigured( 'ValidatePartialUniqueMixin is not supported for PartialIndexes with a text-based where condition. ' + 'Please upgrade to Q-object based where conditions.' ) mentioned_fields = set(idx.fields) | set(query.q_mentioned_fields(where, self.__class__)) missing_fields = mentioned_fields - model_fields if missing_fields: raise RuntimeError('Unable to use ValidatePartialUniqueMixin: expecting to find fields %s on model. ' + 'This is a bug in the PartialIndex definition or the django-partial-index library itself.') values = {field_name: getattr(self, field_name) for field_name in mentioned_fields} conflict = self.__class__.objects.filter(**values) # Step 1 and 3 conflict = conflict.filter(where) # Step 2 if self.pk: conflict = conflict.exclude(pk=self.pk) # Step 4 if conflict.exists(): raise PartialUniqueValidationError('%s with the same values for %s already exists.' % ( self.__class__.__name__, ', '.join(sorted(idx.fields)), ))
[ "def", "validate_partial_unique", "(", "self", ")", ":", "# Find PartialIndexes with unique=True defined on model.", "unique_idxs", "=", "[", "idx", "for", "idx", "in", "self", ".", "_meta", ".", "indexes", "if", "isinstance", "(", "idx", ",", "PartialIndex", ")", ...
Check partial unique constraints on the model and raise ValidationError if any failed. We want to check if another instance already exists with the fields mentioned in idx.fields, but only if idx.where matches. But can't just check for the fields in idx.fields - idx.where may refer to other fields on the current (or other) models. Also can't check for all fields on the current model - should not include irrelevant fields which may hide duplicates. To find potential conflicts, we need to build a queryset which: 1. Filters by idx.fields with their current values on this instance, 2. Filters on idx.where 3. Filters by fields mentioned in idx.where, with their current values on this instance, 4. Excludes current object if it does not match the where condition. Note that step 2 ensures the lookup only looks for conflicts among rows covered by the PartialIndes, and steps 2+3 ensures that the QuerySet is empty if the PartialIndex does not cover the current object.
[ "Check", "partial", "unique", "constraints", "on", "the", "model", "and", "raise", "ValidationError", "if", "any", "failed", "." ]
python
train
edx/edx-enterprise
enterprise/admin/views.py
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/views.py#L487-L501
def get_users_by_email(cls, emails): """ Accept a list of emails, and separate them into users that exist on OpenEdX and users who don't. Args: emails: An iterable of email addresses to split between existing and nonexisting Returns: users: Queryset of users who exist in the OpenEdX platform and who were in the list of email addresses missing_emails: List of unique emails which were in the original list, but do not yet exist as users """ users = User.objects.filter(email__in=emails) present_emails = users.values_list('email', flat=True) missing_emails = list(set(emails) - set(present_emails)) return users, missing_emails
[ "def", "get_users_by_email", "(", "cls", ",", "emails", ")", ":", "users", "=", "User", ".", "objects", ".", "filter", "(", "email__in", "=", "emails", ")", "present_emails", "=", "users", ".", "values_list", "(", "'email'", ",", "flat", "=", "True", ")"...
Accept a list of emails, and separate them into users that exist on OpenEdX and users who don't. Args: emails: An iterable of email addresses to split between existing and nonexisting Returns: users: Queryset of users who exist in the OpenEdX platform and who were in the list of email addresses missing_emails: List of unique emails which were in the original list, but do not yet exist as users
[ "Accept", "a", "list", "of", "emails", "and", "separate", "them", "into", "users", "that", "exist", "on", "OpenEdX", "and", "users", "who", "don", "t", "." ]
python
valid
googleapis/google-cloud-python
datastore/google/cloud/datastore/batch.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/batch.py#L107-L116
def _add_partial_key_entity_pb(self): """Adds a new mutation for an entity with a partial key. :rtype: :class:`.entity_pb2.Entity` :returns: The newly created entity protobuf that will be updated and sent with a commit. """ new_mutation = _datastore_pb2.Mutation() self._mutations.append(new_mutation) return new_mutation.insert
[ "def", "_add_partial_key_entity_pb", "(", "self", ")", ":", "new_mutation", "=", "_datastore_pb2", ".", "Mutation", "(", ")", "self", ".", "_mutations", ".", "append", "(", "new_mutation", ")", "return", "new_mutation", ".", "insert" ]
Adds a new mutation for an entity with a partial key. :rtype: :class:`.entity_pb2.Entity` :returns: The newly created entity protobuf that will be updated and sent with a commit.
[ "Adds", "a", "new", "mutation", "for", "an", "entity", "with", "a", "partial", "key", "." ]
python
train
behave/behave-django
behave_django/environment.py
https://github.com/behave/behave-django/blob/7b56c8f38dede3601e31c72b5921785c148434d4/behave_django/environment.py#L71-L85
def setup_fixtures(self, context): """ Sets up fixtures """ if getattr(context, 'fixtures', None): context.test.fixtures = copy(context.fixtures) if getattr(context, 'reset_sequences', None): context.test.reset_sequences = context.reset_sequences if getattr(context, 'multi_db', None): context.test.__class__.multi_db = context.multi_db if hasattr(context, 'scenario'): load_registered_fixtures(context)
[ "def", "setup_fixtures", "(", "self", ",", "context", ")", ":", "if", "getattr", "(", "context", ",", "'fixtures'", ",", "None", ")", ":", "context", ".", "test", ".", "fixtures", "=", "copy", "(", "context", ".", "fixtures", ")", "if", "getattr", "(",...
Sets up fixtures
[ "Sets", "up", "fixtures" ]
python
train
pyroscope/pyrocore
src/pyrocore/torrent/engine.py
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/engine.py#L214-L225
def lookup(cls, name): """ Try to find field C{name}. @return: Field descriptions, see C{matching.ConditionParser} for details. """ try: field = cls.FIELDS[name] except KeyError: # Is it a custom attribute? field = TorrentProxy.add_manifold_attribute(name) return {"matcher": field._matcher} if field else None
[ "def", "lookup", "(", "cls", ",", "name", ")", ":", "try", ":", "field", "=", "cls", ".", "FIELDS", "[", "name", "]", "except", "KeyError", ":", "# Is it a custom attribute?", "field", "=", "TorrentProxy", ".", "add_manifold_attribute", "(", "name", ")", "...
Try to find field C{name}. @return: Field descriptions, see C{matching.ConditionParser} for details.
[ "Try", "to", "find", "field", "C", "{", "name", "}", "." ]
python
train
ericmjl/nxviz
nxviz/plots.py
https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/plots.py#L594-L650
def compute_node_label_positions(self): """ Uses the get_cartesian function to compute the positions of each node label in the Circos plot. This method is always called after the compute_node_positions method, so that the plot_radius is pre-computed. This will also add a new attribute, `node_label_rotation` to the object which contains the rotation angles for each of the nodes. Together with the node coordinates this can be used to add additional annotations with rotated text. """ self.init_node_label_meta() for node in self.nodes: # Define radius 'radius' and circumference 'theta' theta = node_theta(self.nodes, node) # multiplication factor 1.02 moved below radius = self.plot_radius + self.nodeprops["radius"] # Coordinates of text inside nodes if self.node_label_layout == "numbers": radius_adjustment = 1.0 - (1.0 / radius) else: radius_adjustment = 1.02 x, y = get_cartesian(r=radius * radius_adjustment, theta=theta) # ----- For numbered nodes ----- # Node label x-axis coordinate tx, _ = get_cartesian(r=radius, theta=theta) # Create the quasi-circular positioning on the x axis tx *= 1 - np.log(np.cos(theta) * self.nonzero_sign(np.cos(theta))) # Move each node a little further away from the circos tx += self.nonzero_sign(x) # Node label y-axis coordinate numerator numerator = radius * ( theta % (self.nonzero_sign(y) * self.nonzero_sign(x) * np.pi) ) # Node label y-axis coordinate denominator denominator = self.nonzero_sign(x) * np.pi # Node label y-axis coordinate ty = 2 * (numerator / denominator) # ----- For rotated nodes ----- # Computes the text rotation theta_deg = to_degrees(theta) if theta_deg >= -90 and theta_deg < 90: # right side rot = theta_deg else: # left side rot = theta_deg - 180 # Store values self.store_node_label_meta(x, y, tx, ty, rot)
[ "def", "compute_node_label_positions", "(", "self", ")", ":", "self", ".", "init_node_label_meta", "(", ")", "for", "node", "in", "self", ".", "nodes", ":", "# Define radius 'radius' and circumference 'theta'", "theta", "=", "node_theta", "(", "self", ".", "nodes", ...
Uses the get_cartesian function to compute the positions of each node label in the Circos plot. This method is always called after the compute_node_positions method, so that the plot_radius is pre-computed. This will also add a new attribute, `node_label_rotation` to the object which contains the rotation angles for each of the nodes. Together with the node coordinates this can be used to add additional annotations with rotated text.
[ "Uses", "the", "get_cartesian", "function", "to", "compute", "the", "positions", "of", "each", "node", "label", "in", "the", "Circos", "plot", "." ]
python
train
aliyun/aliyun-odps-python-sdk
odps/df/expr/strings.py
https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/df/expr/strings.py#L405-L420
def _replace(expr, pat, repl, n=-1, case=True, flags=0, regex=True): """ Replace occurrence of pattern/regex in the sequence or scalar with some other string. Equivalent to str.replace() :param expr: :param pat: Character sequence or regular expression :param repl: Replacement :param n: Number of replacements to make from start :param case: if True, case sensitive :param flags: re module flag, e.g. re.IGNORECASE :return: sequence or scalar """ return _string_op(expr, Replace, _pat=pat, _repl=repl, _n=n, _case=case, _flags=flags, _regex=regex)
[ "def", "_replace", "(", "expr", ",", "pat", ",", "repl", ",", "n", "=", "-", "1", ",", "case", "=", "True", ",", "flags", "=", "0", ",", "regex", "=", "True", ")", ":", "return", "_string_op", "(", "expr", ",", "Replace", ",", "_pat", "=", "pat...
Replace occurrence of pattern/regex in the sequence or scalar with some other string. Equivalent to str.replace() :param expr: :param pat: Character sequence or regular expression :param repl: Replacement :param n: Number of replacements to make from start :param case: if True, case sensitive :param flags: re module flag, e.g. re.IGNORECASE :return: sequence or scalar
[ "Replace", "occurrence", "of", "pattern", "/", "regex", "in", "the", "sequence", "or", "scalar", "with", "some", "other", "string", ".", "Equivalent", "to", "str", ".", "replace", "()" ]
python
train
Azure/azure-cli-extensions
src/alias/azext_alias/util.py
https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/util.py#L210-L225
def filter_alias_create_namespace(namespace): """ Filter alias name and alias command inside alias create namespace to appropriate strings. Args namespace: The alias create namespace. Returns: Filtered namespace where excessive whitespaces are removed in strings. """ def filter_string(s): return ' '.join(s.strip().split()) namespace.alias_name = filter_string(namespace.alias_name) namespace.alias_command = filter_string(namespace.alias_command) return namespace
[ "def", "filter_alias_create_namespace", "(", "namespace", ")", ":", "def", "filter_string", "(", "s", ")", ":", "return", "' '", ".", "join", "(", "s", ".", "strip", "(", ")", ".", "split", "(", ")", ")", "namespace", ".", "alias_name", "=", "filter_stri...
Filter alias name and alias command inside alias create namespace to appropriate strings. Args namespace: The alias create namespace. Returns: Filtered namespace where excessive whitespaces are removed in strings.
[ "Filter", "alias", "name", "and", "alias", "command", "inside", "alias", "create", "namespace", "to", "appropriate", "strings", "." ]
python
train
INM-6/hybridLFPy
examples/Hagen_et_al_2016_cercor/figure_06.py
https://github.com/INM-6/hybridLFPy/blob/c38bdf38982c4624c2f70caeb50c40f1d5980abd/examples/Hagen_et_al_2016_cercor/figure_06.py#L284-L394
def plot_multi_scale_output_b(fig, X='L5E'): '''docstring me''' show_ax_labels = True show_insets = False show_images = False T=[800, 1000] T_inset=[900, 920] left = 0.075 bottom = 0.05 top = 0.475 right = 0.95 axwidth = 0.16 numcols = 4 insetwidth = axwidth/2 insetheight = 0.5 lefts = np.linspace(left, right-axwidth, numcols) lefts += axwidth/2 #lower row of panels #fig = plt.figure() #fig.subplots_adjust(left=0.12, right=0.9, bottom=0.36, top=0.9, wspace=0.2, hspace=0.3) ############################################################################ # E part, soma locations ############################################################################ ax4 = fig.add_axes([lefts[0], bottom, axwidth, top-bottom], frameon=False) plt.locator_params(nbins=4) ax4.xaxis.set_ticks([]) ax4.yaxis.set_ticks([]) if show_ax_labels: phlp.annotate_subplot(ax4, ncols=4, nrows=1, letter='E') plot_population(ax4, params, isometricangle=np.pi/24, rasterized=False) ############################################################################ # F part, CSD ############################################################################ ax5 = fig.add_axes([lefts[1], bottom, axwidth, top-bottom]) plt.locator_params(nbins=4) phlp.remove_axis_junk(ax5) if show_ax_labels: phlp.annotate_subplot(ax5, ncols=4, nrows=1, letter='F') plot_signal_sum(ax5, params, fname=os.path.join(params.savefolder, 'CSDsum.h5'), unit='$\mu$A mm$^{-3}$', T=T, ylim=[ax4.axis()[2], ax4.axis()[3]], rasterized=False) ax5.set_title('CSD', va='center') # Inset if show_insets: ax6 = fig.add_axes([lefts[1]+axwidth-insetwidth, top-insetheight, insetwidth, insetheight]) plt.locator_params(nbins=4) phlp.remove_axis_junk(ax6) plot_signal_sum_colorplot(ax6, params, os.path.join(params.savefolder, 'CSDsum.h5'), unit=r'$\mu$Amm$^{-3}$', T=T_inset, ylim=[ax4.axis()[2], ax4.axis()[3]], fancy=False,colorbar=False,cmap='bwr_r') ax6.set_xticks(T_inset) ax6.set_yticklabels([]) #show traces superimposed on color image if show_images: plot_signal_sum_colorplot(ax5, params, os.path.join(params.savefolder, 'CSDsum.h5'), unit=r'$\mu$Amm$^{-3}$', T=T, ylim=[ax4.axis()[2], ax4.axis()[3]], fancy=False,colorbar=False,cmap='jet_r') ############################################################################ # G part, LFP ############################################################################ ax7 = fig.add_axes([lefts[2], bottom, axwidth, top-bottom]) plt.locator_params(nbins=4) if show_ax_labels: phlp.annotate_subplot(ax7, ncols=4, nrows=1, letter='G') phlp.remove_axis_junk(ax7) plot_signal_sum(ax7, params, fname=os.path.join(params.savefolder, 'LFPsum.h5'), unit='mV', T=T, ylim=[ax4.axis()[2], ax4.axis()[3]], rasterized=False) ax7.set_title('LFP',va='center') # Inset if show_insets: ax8 = fig.add_axes([lefts[2]+axwidth-insetwidth, top-insetheight, insetwidth, insetheight]) plt.locator_params(nbins=4) phlp.remove_axis_junk(ax8) plot_signal_sum_colorplot(ax8, params, os.path.join(params.savefolder, 'LFPsum.h5'), unit='mV', T=T_inset, ylim=[ax4.axis()[2], ax4.axis()[3]], fancy=False,colorbar=False,cmap='bwr_r') ax8.set_xticks(T_inset) ax8.set_yticklabels([]) #show traces superimposed on color image if show_images: plot_signal_sum_colorplot(ax7, params, os.path.join(params.savefolder, 'LFPsum.h5'), unit='mV', T=T, ylim=[ax4.axis()[2], ax4.axis()[3]], fancy=False,colorbar=False,cmap='bwr_r')
[ "def", "plot_multi_scale_output_b", "(", "fig", ",", "X", "=", "'L5E'", ")", ":", "show_ax_labels", "=", "True", "show_insets", "=", "False", "show_images", "=", "False", "T", "=", "[", "800", ",", "1000", "]", "T_inset", "=", "[", "900", ",", "920", "...
docstring me
[ "docstring", "me" ]
python
train
CS207-Final-Project-Group-10/cs207-FinalProject
solar_system/solar_system.py
https://github.com/CS207-Final-Project-Group-10/cs207-FinalProject/blob/842e9c2d3ca1490cef18c086dfde81856d8d3a82/solar_system/solar_system.py#L71-L122
def load_constants(): """Load physical constants to simulate the earth-sun system""" # The universal gravitational constant # https://en.wikipedia.org/wiki/Gravitational_constant G: float = 6.67408E-11 # The names of the celestial bodies body_name = \ ['sun', 'moon', 'mercury', 'venus', 'earth', 'mars', 'jupiter', 'saturn', 'uranus', 'neptune'] # The mass of the celestial bodies # https://en.wikipedia.org/wiki/Earth_mass mass_earth: float = 5.9722E24 mass: Dict[str, float] = \ {'sun': mass_earth * 332946.0487, 'moon' : mass_earth * 0.012300037, 'mercury': mass_earth * 0.0553, 'venus': mass_earth * 0.815, 'earth': mass_earth * 1.0000, 'mars': mass_earth * 0.107, 'jupiter': mass_earth * 317.8, 'saturn': mass_earth * 95.2, 'uranus': mass_earth * 14.5, 'neptune': mass_earth * 17.1, } # The radii of the celestial bodiea # https://nineplanets.org/data1.html radius: Dict[str, float] = \ {'sun': 695000e3, 'moon': 1738e3, 'mercury': 2440e3, 'venus': 6052e3, 'earth': 6378e3, 'mars': 3397e3, 'jupiter': 71492e3, 'saturn': 60268e3, 'uranus': 35559e3, 'neptune': 24766e3 } return G, body_name, mass, radius
[ "def", "load_constants", "(", ")", ":", "# The universal gravitational constant", "# https://en.wikipedia.org/wiki/Gravitational_constant", "G", ":", "float", "=", "6.67408E-11", "# The names of the celestial bodies", "body_name", "=", "[", "'sun'", ",", "'moon'", ",", "'merc...
Load physical constants to simulate the earth-sun system
[ "Load", "physical", "constants", "to", "simulate", "the", "earth", "-", "sun", "system" ]
python
train
eandersson/amqpstorm
amqpstorm/basic.py
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/basic.py#L143-L160
def cancel(self, consumer_tag=''): """Cancel a queue consumer. :param str consumer_tag: Consumer tag :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: dict """ if not compatibility.is_string(consumer_tag): raise AMQPInvalidArgument('consumer_tag should be a string') cancel_frame = specification.Basic.Cancel(consumer_tag=consumer_tag) result = self._channel.rpc_request(cancel_frame) self._channel.remove_consumer_tag(consumer_tag) return result
[ "def", "cancel", "(", "self", ",", "consumer_tag", "=", "''", ")", ":", "if", "not", "compatibility", ".", "is_string", "(", "consumer_tag", ")", ":", "raise", "AMQPInvalidArgument", "(", "'consumer_tag should be a string'", ")", "cancel_frame", "=", "specificatio...
Cancel a queue consumer. :param str consumer_tag: Consumer tag :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: dict
[ "Cancel", "a", "queue", "consumer", "." ]
python
train
rochacbruno/manage
manage/cli.py
https://github.com/rochacbruno/manage/blob/e904c451862f036f4be8723df5704a9844103c74/manage/cli.py#L95-L100
def debug(version=False): """Shows the parsed manage file -V shows version""" if version: print(__version__) return print(json.dumps(MANAGE_DICT, indent=2))
[ "def", "debug", "(", "version", "=", "False", ")", ":", "if", "version", ":", "print", "(", "__version__", ")", "return", "print", "(", "json", ".", "dumps", "(", "MANAGE_DICT", ",", "indent", "=", "2", ")", ")" ]
Shows the parsed manage file -V shows version
[ "Shows", "the", "parsed", "manage", "file", "-", "V", "shows", "version" ]
python
train
KushalP/serfclient-py
serfclient/connection.py
https://github.com/KushalP/serfclient-py/blob/6892fb0a4497d1033bea6f625d57959b818b6964/serfclient/connection.py#L139-L146
def handshake(self): """ Sets up the connection with the Serf agent and does the initial handshake. """ if self._socket is None: self._socket = self._connect() return self.call('handshake', {"Version": 1}, expect_body=False)
[ "def", "handshake", "(", "self", ")", ":", "if", "self", ".", "_socket", "is", "None", ":", "self", ".", "_socket", "=", "self", ".", "_connect", "(", ")", "return", "self", ".", "call", "(", "'handshake'", ",", "{", "\"Version\"", ":", "1", "}", "...
Sets up the connection with the Serf agent and does the initial handshake.
[ "Sets", "up", "the", "connection", "with", "the", "Serf", "agent", "and", "does", "the", "initial", "handshake", "." ]
python
train
rmohr/static3
static.py
https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L212-L215
def _conditions(self, full_path, environ): """Return a tuple of etag, last_modified by mtime from stat.""" mtime = stat(full_path).st_mtime return str(mtime), rfc822.formatdate(mtime)
[ "def", "_conditions", "(", "self", ",", "full_path", ",", "environ", ")", ":", "mtime", "=", "stat", "(", "full_path", ")", ".", "st_mtime", "return", "str", "(", "mtime", ")", ",", "rfc822", ".", "formatdate", "(", "mtime", ")" ]
Return a tuple of etag, last_modified by mtime from stat.
[ "Return", "a", "tuple", "of", "etag", "last_modified", "by", "mtime", "from", "stat", "." ]
python
train
AguaClara/aguaclara
aguaclara/core/physchem.py
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L689-L698
def headloss_kozeny(Length, Diam, Vel, Porosity, Nu): """Return the Carmen Kozeny Sand Bed head loss.""" #Checking input validity ut.check_range([Length, ">0", "Length"], [Diam, ">0", "Diam"], [Vel, ">0", "Velocity"], [Nu, ">0", "Nu"], [Porosity, "0-1", "Porosity"]) return (K_KOZENY * Length * Nu / gravity.magnitude * (1-Porosity)**2 / Porosity**3 * 36 * Vel / Diam ** 2)
[ "def", "headloss_kozeny", "(", "Length", ",", "Diam", ",", "Vel", ",", "Porosity", ",", "Nu", ")", ":", "#Checking input validity", "ut", ".", "check_range", "(", "[", "Length", ",", "\">0\"", ",", "\"Length\"", "]", ",", "[", "Diam", ",", "\">0\"", ",",...
Return the Carmen Kozeny Sand Bed head loss.
[ "Return", "the", "Carmen", "Kozeny", "Sand", "Bed", "head", "loss", "." ]
python
train
fabric-bolt/fabric-bolt
fabric_bolt/web_hooks/tasks.py
https://github.com/fabric-bolt/fabric-bolt/blob/0f434783026f1b9ce16a416fa496d76921fe49ca/fabric_bolt/web_hooks/tasks.py#L23-L30
def run(self, target, payload, instance=None, hook_id=None, **kwargs): """ target: the url to receive the payload. payload: a python primitive data structure instance: a possibly null "trigger" instance hook: the defining Hook object (useful for removing) """ self.post_data(target, payload, hook_id)
[ "def", "run", "(", "self", ",", "target", ",", "payload", ",", "instance", "=", "None", ",", "hook_id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "post_data", "(", "target", ",", "payload", ",", "hook_id", ")" ]
target: the url to receive the payload. payload: a python primitive data structure instance: a possibly null "trigger" instance hook: the defining Hook object (useful for removing)
[ "target", ":", "the", "url", "to", "receive", "the", "payload", ".", "payload", ":", "a", "python", "primitive", "data", "structure", "instance", ":", "a", "possibly", "null", "trigger", "instance", "hook", ":", "the", "defining", "Hook", "object", "(", "u...
python
train
mdgoldberg/sportsref
sportsref/nba/players.py
https://github.com/mdgoldberg/sportsref/blob/09f11ac856a23c96d666d1d510bb35d6f050b5c3/sportsref/nba/players.py#L185-L187
def stats_shooting(self, kind='R', summary=False): """Returns a DataFrame of shooting stats.""" return self._get_stats_table('shooting', kind=kind, summary=summary)
[ "def", "stats_shooting", "(", "self", ",", "kind", "=", "'R'", ",", "summary", "=", "False", ")", ":", "return", "self", ".", "_get_stats_table", "(", "'shooting'", ",", "kind", "=", "kind", ",", "summary", "=", "summary", ")" ]
Returns a DataFrame of shooting stats.
[ "Returns", "a", "DataFrame", "of", "shooting", "stats", "." ]
python
test
andrey-git/pysensibo
pysensibo/__init__.py
https://github.com/andrey-git/pysensibo/blob/c471c99ee64bbcc78f3a10aabc0e3b326a1f64f8/pysensibo/__init__.py#L58-L62
def async_get_ac_state_log(self, uid, log_id, fields='*'): """Get a specific log entry.""" return ( yield from self._get('/pods/{}/acStates/{}'.format(uid, log_id), fields=fields))
[ "def", "async_get_ac_state_log", "(", "self", ",", "uid", ",", "log_id", ",", "fields", "=", "'*'", ")", ":", "return", "(", "yield", "from", "self", ".", "_get", "(", "'/pods/{}/acStates/{}'", ".", "format", "(", "uid", ",", "log_id", ")", ",", "fields"...
Get a specific log entry.
[ "Get", "a", "specific", "log", "entry", "." ]
python
train
RRZE-HPC/kerncraft
kerncraft/kernel.py
https://github.com/RRZE-HPC/kerncraft/blob/c60baf8043e4da8d8d66da7575021c2f4c6c78af/kerncraft/kernel.py#L454-L465
def global_iterator(self): """ Return global iterator sympy expression """ global_iterator = sympy.Integer(0) total_length = sympy.Integer(1) for var_name, start, end, incr in reversed(self._loop_stack): loop_var = symbol_pos_int(var_name) length = end - start # FIXME is incr handled correct here? global_iterator += (loop_var - start) * total_length total_length *= length return global_iterator
[ "def", "global_iterator", "(", "self", ")", ":", "global_iterator", "=", "sympy", ".", "Integer", "(", "0", ")", "total_length", "=", "sympy", ".", "Integer", "(", "1", ")", "for", "var_name", ",", "start", ",", "end", ",", "incr", "in", "reversed", "(...
Return global iterator sympy expression
[ "Return", "global", "iterator", "sympy", "expression" ]
python
test
SiLab-Bonn/basil
basil/utils/sim/Protocol.py
https://github.com/SiLab-Bonn/basil/blob/99052482d9334dd1f5598eb2d2fb4d5399a32291/basil/utils/sim/Protocol.py#L80-L86
def _get_next_obj(self, length): """Assumes we've already read the object length""" data = b'' while len(data) < length: data += self.sock.recv(length - len(data)) return pickle.loads(data)
[ "def", "_get_next_obj", "(", "self", ",", "length", ")", ":", "data", "=", "b''", "while", "len", "(", "data", ")", "<", "length", ":", "data", "+=", "self", ".", "sock", ".", "recv", "(", "length", "-", "len", "(", "data", ")", ")", "return", "p...
Assumes we've already read the object length
[ "Assumes", "we", "ve", "already", "read", "the", "object", "length" ]
python
train
pandas-dev/pandas
pandas/core/series.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/series.py#L1940-L2009
def idxmax(self, axis=0, skipna=True, *args, **kwargs): """ Return the row label of the maximum value. If multiple values equal the maximum, the first row label with that value is returned. Parameters ---------- skipna : bool, default True Exclude NA/null values. If the entire Series is NA, the result will be NA. axis : int, default 0 For compatibility with DataFrame.idxmax. Redundant for application on Series. *args, **kwargs Additional keywords have no effect but might be accepted for compatibility with NumPy. Returns ------- Index Label of the maximum value. Raises ------ ValueError If the Series is empty. See Also -------- numpy.argmax : Return indices of the maximum values along the given axis. DataFrame.idxmax : Return index of first occurrence of maximum over requested axis. Series.idxmin : Return index *label* of the first occurrence of minimum of values. Notes ----- This method is the Series version of ``ndarray.argmax``. This method returns the label of the maximum, while ``ndarray.argmax`` returns the position. To get the position, use ``series.values.argmax()``. Examples -------- >>> s = pd.Series(data=[1, None, 4, 3, 4], ... index=['A', 'B', 'C', 'D', 'E']) >>> s A 1.0 B NaN C 4.0 D 3.0 E 4.0 dtype: float64 >>> s.idxmax() 'C' If `skipna` is False and there is an NA value in the data, the function returns ``nan``. >>> s.idxmax(skipna=False) nan """ skipna = nv.validate_argmax_with_skipna(skipna, args, kwargs) i = nanops.nanargmax(com.values_from_object(self), skipna=skipna) if i == -1: return np.nan return self.index[i]
[ "def", "idxmax", "(", "self", ",", "axis", "=", "0", ",", "skipna", "=", "True", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "skipna", "=", "nv", ".", "validate_argmax_with_skipna", "(", "skipna", ",", "args", ",", "kwargs", ")", "i", "=",...
Return the row label of the maximum value. If multiple values equal the maximum, the first row label with that value is returned. Parameters ---------- skipna : bool, default True Exclude NA/null values. If the entire Series is NA, the result will be NA. axis : int, default 0 For compatibility with DataFrame.idxmax. Redundant for application on Series. *args, **kwargs Additional keywords have no effect but might be accepted for compatibility with NumPy. Returns ------- Index Label of the maximum value. Raises ------ ValueError If the Series is empty. See Also -------- numpy.argmax : Return indices of the maximum values along the given axis. DataFrame.idxmax : Return index of first occurrence of maximum over requested axis. Series.idxmin : Return index *label* of the first occurrence of minimum of values. Notes ----- This method is the Series version of ``ndarray.argmax``. This method returns the label of the maximum, while ``ndarray.argmax`` returns the position. To get the position, use ``series.values.argmax()``. Examples -------- >>> s = pd.Series(data=[1, None, 4, 3, 4], ... index=['A', 'B', 'C', 'D', 'E']) >>> s A 1.0 B NaN C 4.0 D 3.0 E 4.0 dtype: float64 >>> s.idxmax() 'C' If `skipna` is False and there is an NA value in the data, the function returns ``nan``. >>> s.idxmax(skipna=False) nan
[ "Return", "the", "row", "label", "of", "the", "maximum", "value", "." ]
python
train
ReFirmLabs/binwalk
src/binwalk/core/settings.py
https://github.com/ReFirmLabs/binwalk/blob/a0c5315fd2bae167e5c3d8469ce95d5defc743c2/src/binwalk/core/settings.py#L187-L201
def _system_path(self, subdir, basename=''): ''' Gets the full path to the 'subdir/basename' file in the system binwalk directory. @subdir - Subdirectory inside the system binwalk directory. @basename - File name inside the subdirectory. Returns the full path to the 'subdir/basename' file. ''' try: return self._file_path(os.path.join(self.system_dir, subdir), basename) except KeyboardInterrupt as e: raise e except Exception: return None
[ "def", "_system_path", "(", "self", ",", "subdir", ",", "basename", "=", "''", ")", ":", "try", ":", "return", "self", ".", "_file_path", "(", "os", ".", "path", ".", "join", "(", "self", ".", "system_dir", ",", "subdir", ")", ",", "basename", ")", ...
Gets the full path to the 'subdir/basename' file in the system binwalk directory. @subdir - Subdirectory inside the system binwalk directory. @basename - File name inside the subdirectory. Returns the full path to the 'subdir/basename' file.
[ "Gets", "the", "full", "path", "to", "the", "subdir", "/", "basename", "file", "in", "the", "system", "binwalk", "directory", "." ]
python
train
malramsay64/experi
src/experi/run.py
https://github.com/malramsay64/experi/blob/7159644df0420e4a395c87c0c08e11567f401443/src/experi/run.py#L289-L295
def read_file(filename: PathLike = "experiment.yml") -> Dict[str, Any]: """Read and parse yaml file.""" logger.debug("Input file: %s", filename) with open(filename, "r") as stream: structure = yaml.safe_load(stream) return structure
[ "def", "read_file", "(", "filename", ":", "PathLike", "=", "\"experiment.yml\"", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "logger", ".", "debug", "(", "\"Input file: %s\"", ",", "filename", ")", "with", "open", "(", "filename", ",", "\"r\"", ...
Read and parse yaml file.
[ "Read", "and", "parse", "yaml", "file", "." ]
python
train
tomer8007/kik-bot-api-unofficial
kik_unofficial/client.py
https://github.com/tomer8007/kik-bot-api-unofficial/blob/2ae5216bc05e7099a41895382fc8e428a7a5c3ac/kik_unofficial/client.py#L399-L407
def change_display_name(self, first_name, last_name): """ Changes the display name :param first_name: The first name :param last_name: The last name """ log.info("[+] Changing the display name to '{} {}'".format(first_name, last_name)) return self._send_xmpp_element(account.ChangeNameRequest(first_name, last_name))
[ "def", "change_display_name", "(", "self", ",", "first_name", ",", "last_name", ")", ":", "log", ".", "info", "(", "\"[+] Changing the display name to '{} {}'\"", ".", "format", "(", "first_name", ",", "last_name", ")", ")", "return", "self", ".", "_send_xmpp_elem...
Changes the display name :param first_name: The first name :param last_name: The last name
[ "Changes", "the", "display", "name" ]
python
train
saltstack/salt
salt/modules/openvswitch.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/openvswitch.py#L147-L165
def bridge_list(): ''' Lists all existing real and fake bridges. Returns: List of bridges (or empty list), False on failure. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' openvswitch.bridge_list ''' cmd = 'ovs-vsctl list-br' result = __salt__['cmd.run_all'](cmd) retcode = result['retcode'] stdout = result['stdout'] return _stdout_list_split(retcode, stdout)
[ "def", "bridge_list", "(", ")", ":", "cmd", "=", "'ovs-vsctl list-br'", "result", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "cmd", ")", "retcode", "=", "result", "[", "'retcode'", "]", "stdout", "=", "result", "[", "'stdout'", "]", "return", "_stdou...
Lists all existing real and fake bridges. Returns: List of bridges (or empty list), False on failure. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' openvswitch.bridge_list
[ "Lists", "all", "existing", "real", "and", "fake", "bridges", "." ]
python
train
jilljenn/tryalgo
tryalgo/skip_list.py
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/skip_list.py#L55-L67
def getkth(self, k): "starts from 0" if k >= len(self): raise IndexError k += 1 # self has index -1 h = len(self.next) - 1 x = self while k: while x.next[h] is None or x.count[h] > k: h -= 1 k -= x.count[h] x = x.next[h] return x.key
[ "def", "getkth", "(", "self", ",", "k", ")", ":", "if", "k", ">=", "len", "(", "self", ")", ":", "raise", "IndexError", "k", "+=", "1", "# self has index -1", "h", "=", "len", "(", "self", ".", "next", ")", "-", "1", "x", "=", "self", "while", ...
starts from 0
[ "starts", "from", "0" ]
python
train
RedFantom/ttkthemes
ttkthemes/themed_tk.py
https://github.com/RedFantom/ttkthemes/blob/e7fc354c02faf0e3eb4842d7f44131a1c43dd299/ttkthemes/themed_tk.py#L105-L113
def cget(self, k): """cget redirect to support additional options""" if k == "themebg": return self._themebg elif k == "toplevel": return self._toplevel elif k == "theme": return self.current_theme return tk.Tk.cget(self, k)
[ "def", "cget", "(", "self", ",", "k", ")", ":", "if", "k", "==", "\"themebg\"", ":", "return", "self", ".", "_themebg", "elif", "k", "==", "\"toplevel\"", ":", "return", "self", ".", "_toplevel", "elif", "k", "==", "\"theme\"", ":", "return", "self", ...
cget redirect to support additional options
[ "cget", "redirect", "to", "support", "additional", "options" ]
python
train
pywbem/pywbem
pywbem/mof_compiler.py
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/mof_compiler.py#L1261-L1268
def p_stringValueList(p): """stringValueList : stringValue | stringValueList stringValue """ if len(p) == 2: p[0] = _fixStringValue(p[1], p) else: p[0] = p[1] + _fixStringValue(p[2], p)
[ "def", "p_stringValueList", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "2", ":", "p", "[", "0", "]", "=", "_fixStringValue", "(", "p", "[", "1", "]", ",", "p", ")", "else", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "+",...
stringValueList : stringValue | stringValueList stringValue
[ "stringValueList", ":", "stringValue", "|", "stringValueList", "stringValue" ]
python
train
odlgroup/odl
odl/util/graphics.py
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/util/graphics.py#L102-L482
def show_discrete_data(values, grid, title=None, method='', force_show=False, fig=None, **kwargs): """Display a discrete 1d or 2d function. Parameters ---------- values : `numpy.ndarray` The values to visualize. grid : `RectGrid` or `RectPartition` Grid of the values. title : string, optional Set the title of the figure. method : string, optional 1d methods: 'plot' : graph plot 'scatter' : scattered 2d points (2nd axis <-> value) 2d methods: 'imshow' : image plot with coloring according to value, including a colorbar. 'scatter' : cloud of scattered 3d points (3rd axis <-> value) 'wireframe', 'plot_wireframe' : surface plot force_show : bool, optional Whether the plot should be forced to be shown now or deferred until later. Note that some backends always displays the plot, regardless of this value. fig : `matplotlib.figure.Figure`, optional The figure to show in. Expected to be of same "style", as the figure given by this function. The most common usecase is that fig is the return value from an earlier call to this function. Default: New figure interp : {'nearest', 'linear'}, optional Interpolation method to use. Default: 'nearest' axis_labels : string, optional Axis labels, default: ['x', 'y'] update_in_place : bool, optional Update the content of the figure in-place. Intended for faster real time plotting, typically ~5 times faster. This is only performed for ``method == 'imshow'`` with real data and ``fig != None``. Otherwise this parameter is treated as False. Default: False axis_fontsize : int, optional Fontsize for the axes. Default: 16 colorbar : bool, optional Argument relevant for 2d plots using ``method='imshow'``. If ``True``, include a colorbar in the plot. Default: True kwargs : {'figsize', 'saveto', ...}, optional Extra keyword arguments passed on to display method See the Matplotlib functions for documentation of extra options. Returns ------- fig : `matplotlib.figure.Figure` The resulting figure. It is also shown to the user. See Also -------- matplotlib.pyplot.plot : Show graph plot matplotlib.pyplot.imshow : Show data as image matplotlib.pyplot.scatter : Show scattered 3d points """ # Importing pyplot takes ~2 sec, only import when needed. import matplotlib.pyplot as plt args_re = [] args_im = [] dsp_kwargs = {} sub_kwargs = {} arrange_subplots = (121, 122) # horzontal arrangement # Create axis labels which remember their original meaning axis_labels = kwargs.pop('axis_labels', ['x', 'y']) values_are_complex = not is_real_dtype(values.dtype) figsize = kwargs.pop('figsize', None) saveto = kwargs.pop('saveto', None) interp = kwargs.pop('interp', 'nearest') axis_fontsize = kwargs.pop('axis_fontsize', 16) colorbar = kwargs.pop('colorbar', True) # Normalize input interp, interp_in = str(interp).lower(), interp method, method_in = str(method).lower(), method # Check if we should and can update the plot in-place update_in_place = kwargs.pop('update_in_place', False) if (update_in_place and (fig is None or values_are_complex or values.ndim != 2 or (values.ndim == 2 and method not in ('', 'imshow')))): update_in_place = False if values.ndim == 1: # TODO: maybe a plotter class would be better if not method: if interp == 'nearest': method = 'step' dsp_kwargs['where'] = 'mid' elif interp == 'linear': method = 'plot' else: raise ValueError('`interp` {!r} not supported' ''.format(interp_in)) if method == 'plot' or method == 'step' or method == 'scatter': args_re += [grid.coord_vectors[0], values.real] args_im += [grid.coord_vectors[0], values.imag] else: raise ValueError('`method` {!r} not supported' ''.format(method_in)) elif values.ndim == 2: if not method: method = 'imshow' if method == 'imshow': args_re = [np.rot90(values.real)] args_im = [np.rot90(values.imag)] if values_are_complex else [] extent = [grid.min()[0], grid.max()[0], grid.min()[1], grid.max()[1]] if interp == 'nearest': interpolation = 'nearest' elif interp == 'linear': interpolation = 'bilinear' else: raise ValueError('`interp` {!r} not supported' ''.format(interp_in)) dsp_kwargs.update({'interpolation': interpolation, 'cmap': 'bone', 'extent': extent, 'aspect': 'auto'}) elif method == 'scatter': pts = grid.points() args_re = [pts[:, 0], pts[:, 1], values.ravel().real] args_im = ([pts[:, 0], pts[:, 1], values.ravel().imag] if values_are_complex else []) sub_kwargs.update({'projection': '3d'}) elif method in ('wireframe', 'plot_wireframe'): method = 'plot_wireframe' x, y = grid.meshgrid args_re = [x, y, np.rot90(values.real)] args_im = ([x, y, np.rot90(values.imag)] if values_are_complex else []) sub_kwargs.update({'projection': '3d'}) else: raise ValueError('`method` {!r} not supported' ''.format(method_in)) else: raise NotImplementedError('no method for {}d display implemented' ''.format(values.ndim)) # Additional keyword args are passed on to the display method dsp_kwargs.update(**kwargs) if fig is not None: # Reuse figure if given as input if not isinstance(fig, plt.Figure): raise TypeError('`fig` {} not a matplotlib figure'.format(fig)) if not plt.fignum_exists(fig.number): # If figure does not exist, user either closed the figure or # is using IPython, in this case we need a new figure. fig = plt.figure(figsize=figsize) updatefig = False else: # Set current figure to given input fig = plt.figure(fig.number) updatefig = True if values.ndim > 1 and not update_in_place: # If the figure is larger than 1d, we can clear it since we # dont reuse anything. Keeping it causes performance problems. fig.clf() else: fig = plt.figure(figsize=figsize) updatefig = False if values_are_complex: # Real if len(fig.axes) == 0: # Create new axis if needed sub_re = plt.subplot(arrange_subplots[0], **sub_kwargs) sub_re.set_title('Real part') sub_re.set_xlabel(axis_labels[0], fontsize=axis_fontsize) if values.ndim == 2: sub_re.set_ylabel(axis_labels[1], fontsize=axis_fontsize) else: sub_re.set_ylabel('value') else: sub_re = fig.axes[0] display_re = getattr(sub_re, method) csub_re = display_re(*args_re, **dsp_kwargs) # Axis ticks if method == 'imshow' and not grid.is_uniform: (xpts, xlabels), (ypts, ylabels) = _axes_info(grid) plt.xticks(xpts, xlabels) plt.yticks(ypts, ylabels) if method == 'imshow' and len(fig.axes) < 2: # Create colorbar if none seems to exist # Use clim from kwargs if given if 'clim' not in kwargs: minval_re, maxval_re = _safe_minmax(values.real) else: minval_re, maxval_re = kwargs['clim'] ticks_re = _colorbar_ticks(minval_re, maxval_re) fmt_re = _colorbar_format(minval_re, maxval_re) plt.colorbar(csub_re, orientation='horizontal', ticks=ticks_re, format=fmt_re) # Imaginary if len(fig.axes) < 3: sub_im = plt.subplot(arrange_subplots[1], **sub_kwargs) sub_im.set_title('Imaginary part') sub_im.set_xlabel(axis_labels[0], fontsize=axis_fontsize) if values.ndim == 2: sub_im.set_ylabel(axis_labels[1], fontsize=axis_fontsize) else: sub_im.set_ylabel('value') else: sub_im = fig.axes[2] display_im = getattr(sub_im, method) csub_im = display_im(*args_im, **dsp_kwargs) # Axis ticks if method == 'imshow' and not grid.is_uniform: (xpts, xlabels), (ypts, ylabels) = _axes_info(grid) plt.xticks(xpts, xlabels) plt.yticks(ypts, ylabels) if method == 'imshow' and len(fig.axes) < 4: # Create colorbar if none seems to exist # Use clim from kwargs if given if 'clim' not in kwargs: minval_im, maxval_im = _safe_minmax(values.imag) else: minval_im, maxval_im = kwargs['clim'] ticks_im = _colorbar_ticks(minval_im, maxval_im) fmt_im = _colorbar_format(minval_im, maxval_im) plt.colorbar(csub_im, orientation='horizontal', ticks=ticks_im, format=fmt_im) else: if len(fig.axes) == 0: # Create new axis object if needed sub = plt.subplot(111, **sub_kwargs) sub.set_xlabel(axis_labels[0], fontsize=axis_fontsize) if values.ndim == 2: sub.set_ylabel(axis_labels[1], fontsize=axis_fontsize) else: sub.set_ylabel('value') try: # For 3d plots sub.set_zlabel('z') except AttributeError: pass else: sub = fig.axes[0] if update_in_place: import matplotlib as mpl imgs = [obj for obj in sub.get_children() if isinstance(obj, mpl.image.AxesImage)] if len(imgs) > 0 and updatefig: imgs[0].set_data(args_re[0]) csub = imgs[0] # Update min-max if 'clim' not in kwargs: minval, maxval = _safe_minmax(values) else: minval, maxval = kwargs['clim'] csub.set_clim(minval, maxval) else: display = getattr(sub, method) csub = display(*args_re, **dsp_kwargs) else: display = getattr(sub, method) csub = display(*args_re, **dsp_kwargs) # Axis ticks if method == 'imshow' and not grid.is_uniform: (xpts, xlabels), (ypts, ylabels) = _axes_info(grid) plt.xticks(xpts, xlabels) plt.yticks(ypts, ylabels) if method == 'imshow' and colorbar: # Add colorbar # Use clim from kwargs if given if 'clim' not in kwargs: minval, maxval = _safe_minmax(values) else: minval, maxval = kwargs['clim'] ticks = _colorbar_ticks(minval, maxval) fmt = _colorbar_format(minval, maxval) if len(fig.axes) < 2: # Create colorbar if none seems to exist plt.colorbar(mappable=csub, ticks=ticks, format=fmt) elif update_in_place: # If it exists and we should update it csub.colorbar.set_clim(minval, maxval) csub.colorbar.set_ticks(ticks) if '%' not in fmt: labels = [fmt] * len(ticks) else: labels = [fmt % t for t in ticks] csub.colorbar.set_ticklabels(labels) csub.colorbar.draw_all() # Set title of window if title is not None: if not values_are_complex: # Do not overwrite title for complex values plt.title(title) fig.canvas.manager.set_window_title(title) # Fixes overlapping stuff at the expense of potentially squashed subplots if not update_in_place: fig.tight_layout() if updatefig or plt.isinteractive(): # If we are running in interactive mode, we can always show the fig # This causes an artifact, where users of `CallbackShow` without # interactive mode only shows the figure after the second iteration. plt.show(block=False) if not update_in_place: plt.draw() warning_free_pause() else: try: sub.draw_artist(csub) fig.canvas.blit(fig.bbox) fig.canvas.update() fig.canvas.flush_events() except AttributeError: plt.draw() warning_free_pause() if force_show: plt.show() if saveto is not None: fig.savefig(saveto) return fig
[ "def", "show_discrete_data", "(", "values", ",", "grid", ",", "title", "=", "None", ",", "method", "=", "''", ",", "force_show", "=", "False", ",", "fig", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Importing pyplot takes ~2 sec, only import when needed...
Display a discrete 1d or 2d function. Parameters ---------- values : `numpy.ndarray` The values to visualize. grid : `RectGrid` or `RectPartition` Grid of the values. title : string, optional Set the title of the figure. method : string, optional 1d methods: 'plot' : graph plot 'scatter' : scattered 2d points (2nd axis <-> value) 2d methods: 'imshow' : image plot with coloring according to value, including a colorbar. 'scatter' : cloud of scattered 3d points (3rd axis <-> value) 'wireframe', 'plot_wireframe' : surface plot force_show : bool, optional Whether the plot should be forced to be shown now or deferred until later. Note that some backends always displays the plot, regardless of this value. fig : `matplotlib.figure.Figure`, optional The figure to show in. Expected to be of same "style", as the figure given by this function. The most common usecase is that fig is the return value from an earlier call to this function. Default: New figure interp : {'nearest', 'linear'}, optional Interpolation method to use. Default: 'nearest' axis_labels : string, optional Axis labels, default: ['x', 'y'] update_in_place : bool, optional Update the content of the figure in-place. Intended for faster real time plotting, typically ~5 times faster. This is only performed for ``method == 'imshow'`` with real data and ``fig != None``. Otherwise this parameter is treated as False. Default: False axis_fontsize : int, optional Fontsize for the axes. Default: 16 colorbar : bool, optional Argument relevant for 2d plots using ``method='imshow'``. If ``True``, include a colorbar in the plot. Default: True kwargs : {'figsize', 'saveto', ...}, optional Extra keyword arguments passed on to display method See the Matplotlib functions for documentation of extra options. Returns ------- fig : `matplotlib.figure.Figure` The resulting figure. It is also shown to the user. See Also -------- matplotlib.pyplot.plot : Show graph plot matplotlib.pyplot.imshow : Show data as image matplotlib.pyplot.scatter : Show scattered 3d points
[ "Display", "a", "discrete", "1d", "or", "2d", "function", "." ]
python
train
user-cont/conu
conu/apidefs/filesystem.py
https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/apidefs/filesystem.py#L87-L104
def copy_from(self, src, dest): """ copy a file or a directory from container or image to host system. If you are copying directories, the target directory must not exist (this function is using `shutil.copytree` to copy directories and that's a requirement of the function). In case the directory exists, OSError on python 2 or FileExistsError on python 3 are raised. :param src: str, path to a file or a directory within container or image :param dest: str, path to a file or a directory on host system :return: None """ p = self.p(src) if os.path.isfile(p): logger.info("copying file %s to %s", p, dest) shutil.copy2(p, dest) else: logger.info("copying directory %s to %s", p, dest) shutil.copytree(p, dest)
[ "def", "copy_from", "(", "self", ",", "src", ",", "dest", ")", ":", "p", "=", "self", ".", "p", "(", "src", ")", "if", "os", ".", "path", ".", "isfile", "(", "p", ")", ":", "logger", ".", "info", "(", "\"copying file %s to %s\"", ",", "p", ",", ...
copy a file or a directory from container or image to host system. If you are copying directories, the target directory must not exist (this function is using `shutil.copytree` to copy directories and that's a requirement of the function). In case the directory exists, OSError on python 2 or FileExistsError on python 3 are raised. :param src: str, path to a file or a directory within container or image :param dest: str, path to a file or a directory on host system :return: None
[ "copy", "a", "file", "or", "a", "directory", "from", "container", "or", "image", "to", "host", "system", ".", "If", "you", "are", "copying", "directories", "the", "target", "directory", "must", "not", "exist", "(", "this", "function", "is", "using", "shuti...
python
train
BoboTiG/python-mss
mss/screenshot.py
https://github.com/BoboTiG/python-mss/blob/56347f781edb38a0e7a5104080bd683f49c6f074/mss/screenshot.py#L142-L157
def pixel(self, coord_x, coord_y): # type: (int, int) -> Pixel """ Returns the pixel value at a given position. :param int coord_x: The x coordinate. :param int coord_y: The y coordinate. :return tuple: The pixel value as (R, G, B). """ try: return self.pixels[coord_y][coord_x] # type: ignore except IndexError: raise ScreenShotError( "Pixel location ({}, {}) is out of range.".format(coord_x, coord_y) )
[ "def", "pixel", "(", "self", ",", "coord_x", ",", "coord_y", ")", ":", "# type: (int, int) -> Pixel", "try", ":", "return", "self", ".", "pixels", "[", "coord_y", "]", "[", "coord_x", "]", "# type: ignore", "except", "IndexError", ":", "raise", "ScreenShotErro...
Returns the pixel value at a given position. :param int coord_x: The x coordinate. :param int coord_y: The y coordinate. :return tuple: The pixel value as (R, G, B).
[ "Returns", "the", "pixel", "value", "at", "a", "given", "position", "." ]
python
train
samjabrahams/anchorhub
anchorhub/lib/lazyregex.py
https://github.com/samjabrahams/anchorhub/blob/5ade359b08297d4003a5f477389c01de9e634b54/anchorhub/lib/lazyregex.py#L74-L80
def _create_regex_if_none(self): """ Private function. Checks to see if the local regular expression object has been created yet """ if self._regex is None: self._regex = re.compile(self._pattern, re.UNICODE)
[ "def", "_create_regex_if_none", "(", "self", ")", ":", "if", "self", ".", "_regex", "is", "None", ":", "self", ".", "_regex", "=", "re", ".", "compile", "(", "self", ".", "_pattern", ",", "re", ".", "UNICODE", ")" ]
Private function. Checks to see if the local regular expression object has been created yet
[ "Private", "function", ".", "Checks", "to", "see", "if", "the", "local", "regular", "expression", "object", "has", "been", "created", "yet" ]
python
train
isislovecruft/python-gnupg
pretty_bad_protocol/_parsers.py
https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_parsers.py#L143-L154
def _hyphenate(input, add_prefix=False): """Change underscores to hyphens so that object attributes can be easily tranlated to GPG option names. :param str input: The attribute to hyphenate. :param bool add_prefix: If True, add leading hyphens to the input. :rtype: str :return: The ``input`` with underscores changed to hyphens. """ ret = '--' if add_prefix else '' ret += input.replace('_', '-') return ret
[ "def", "_hyphenate", "(", "input", ",", "add_prefix", "=", "False", ")", ":", "ret", "=", "'--'", "if", "add_prefix", "else", "''", "ret", "+=", "input", ".", "replace", "(", "'_'", ",", "'-'", ")", "return", "ret" ]
Change underscores to hyphens so that object attributes can be easily tranlated to GPG option names. :param str input: The attribute to hyphenate. :param bool add_prefix: If True, add leading hyphens to the input. :rtype: str :return: The ``input`` with underscores changed to hyphens.
[ "Change", "underscores", "to", "hyphens", "so", "that", "object", "attributes", "can", "be", "easily", "tranlated", "to", "GPG", "option", "names", "." ]
python
train
inasafe/inasafe
safe/gui/widgets/dock.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/dock.py#L501-L545
def save_auxiliary_files(self, layer, destination): """Save auxiliary files when using the 'save as' function. If some auxiliary files (.xml, .json) exist, this function will copy them when the 'save as' function is used on the layer. :param layer: The layer which has been saved as. :type layer: QgsMapLayer :param destination: The new filename of the layer. :type destination: str """ enable_busy_cursor() auxiliary_files = ['xml', 'json'] for auxiliary_file in auxiliary_files: source_basename = os.path.splitext(layer.source())[0] source_file = "%s.%s" % (source_basename, auxiliary_file) destination_basename = os.path.splitext(destination)[0] destination_file = "%s.%s" % (destination_basename, auxiliary_file) # noinspection PyBroadException,PyBroadException try: if os.path.isfile(source_file): shutil.copy(source_file, destination_file) except (OSError, IOError): display_critical_message_bar( title=self.tr('Error while saving'), message=self.tr( 'The destination location must be writable.'), iface_object=self.iface ) except Exception: # pylint: disable=broad-except display_critical_message_bar( title=self.tr('Error while saving'), message=self.tr('Something went wrong.'), iface_object=self.iface ) disable_busy_cursor()
[ "def", "save_auxiliary_files", "(", "self", ",", "layer", ",", "destination", ")", ":", "enable_busy_cursor", "(", ")", "auxiliary_files", "=", "[", "'xml'", ",", "'json'", "]", "for", "auxiliary_file", "in", "auxiliary_files", ":", "source_basename", "=", "os",...
Save auxiliary files when using the 'save as' function. If some auxiliary files (.xml, .json) exist, this function will copy them when the 'save as' function is used on the layer. :param layer: The layer which has been saved as. :type layer: QgsMapLayer :param destination: The new filename of the layer. :type destination: str
[ "Save", "auxiliary", "files", "when", "using", "the", "save", "as", "function", "." ]
python
train
glomex/gcdt
gcdt/kumo_start_stop.py
https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/kumo_start_stop.py#L110-L136
def _stop_ecs_services(awsclient, services, template, parameters, wait=True): """Helper to change desiredCount of ECS services to zero. By default it waits for this to complete. Docs here: http://docs.aws.amazon.com/cli/latest/reference/ecs/update-service.html :param awsclient: :param services: :param template: the cloudformation template :param parameters: the parameters used for the cloudformation template :param wait: waits for services to stop :return: """ if len(services) == 0: return client_ecs = awsclient.get_client('ecs') for service in services: log.info('Resize ECS service \'%s\' to desiredCount=0', service['LogicalResourceId']) cluster, desired_count = _get_service_cluster_desired_count( template, parameters, service['LogicalResourceId']) log.debug('cluster: %s' % cluster) response = client_ecs.update_service( cluster=cluster, service=service['PhysicalResourceId'], desiredCount=0 )
[ "def", "_stop_ecs_services", "(", "awsclient", ",", "services", ",", "template", ",", "parameters", ",", "wait", "=", "True", ")", ":", "if", "len", "(", "services", ")", "==", "0", ":", "return", "client_ecs", "=", "awsclient", ".", "get_client", "(", "...
Helper to change desiredCount of ECS services to zero. By default it waits for this to complete. Docs here: http://docs.aws.amazon.com/cli/latest/reference/ecs/update-service.html :param awsclient: :param services: :param template: the cloudformation template :param parameters: the parameters used for the cloudformation template :param wait: waits for services to stop :return:
[ "Helper", "to", "change", "desiredCount", "of", "ECS", "services", "to", "zero", ".", "By", "default", "it", "waits", "for", "this", "to", "complete", ".", "Docs", "here", ":", "http", ":", "//", "docs", ".", "aws", ".", "amazon", ".", "com", "/", "c...
python
train
lincolnloop/django-dynamic-raw-id
dynamic_raw_id/widgets.py
https://github.com/lincolnloop/django-dynamic-raw-id/blob/4bf234f4a9d99daf44141205c0948222442f4957/dynamic_raw_id/widgets.py#L23-L76
def render(self, name, value, attrs=None, multi=False, renderer=None): """ Django <= 1.10 variant. """ DJANGO_111_OR_UP = (VERSION[0] == 1 and VERSION[1] >= 11) or ( VERSION[0] >= 2 ) if DJANGO_111_OR_UP: return super(DynamicRawIDWidget, self).render( name, value, attrs, renderer=renderer ) if attrs is None: attrs = {} related_url = reverse( 'admin:{0}_{1}_changelist'.format( self.rel.to._meta.app_label, self.rel.to._meta.object_name.lower(), ), current_app=self.admin_site.name, ) params = self.url_parameters() if params: url = u'?' + u'&'.join( [u'{0}={1}'.format(k, v) for k, v in params.items()] ) else: url = u'' if "class" not in attrs: attrs[ 'class' ] = ( 'vForeignKeyRawIdAdminField' ) # The JavaScript looks for this hook. app_name = self.rel.to._meta.app_label.strip() model_name = self.rel.to._meta.object_name.lower().strip() hidden_input = super(widgets.ForeignKeyRawIdWidget, self).render( name, value, attrs ) extra_context = { 'hidden_input': hidden_input, 'name': name, 'app_name': app_name, 'model_name': model_name, 'related_url': related_url, 'url': url, } return render_to_string( 'dynamic_raw_id/admin/widgets/dynamic_raw_id_field.html', extra_context, )
[ "def", "render", "(", "self", ",", "name", ",", "value", ",", "attrs", "=", "None", ",", "multi", "=", "False", ",", "renderer", "=", "None", ")", ":", "DJANGO_111_OR_UP", "=", "(", "VERSION", "[", "0", "]", "==", "1", "and", "VERSION", "[", "1", ...
Django <= 1.10 variant.
[ "Django", "<", "=", "1", ".", "10", "variant", "." ]
python
train
dask/dask-ml
dask_ml/naive_bayes.py
https://github.com/dask/dask-ml/blob/cc4837c2c2101f9302cac38354b55754263cd1f3/dask_ml/naive_bayes.py#L78-L94
def predict_log_proba(self, X): """ Return log-probability estimates for the test vector X. Parameters ---------- X : array-like, shape = [n_samples, n_features] Returns ------- C : array-like, shape = [n_samples, n_classes] Returns the log-probability of the samples for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute `classes_`. """ jll = self._joint_log_likelihood(X) # normalize by P(x) = P(f_1, ..., f_n) log_prob_x = logsumexp(jll, axis=1) return jll - log_prob_x.reshape(-1, 1)
[ "def", "predict_log_proba", "(", "self", ",", "X", ")", ":", "jll", "=", "self", ".", "_joint_log_likelihood", "(", "X", ")", "# normalize by P(x) = P(f_1, ..., f_n)", "log_prob_x", "=", "logsumexp", "(", "jll", ",", "axis", "=", "1", ")", "return", "jll", "...
Return log-probability estimates for the test vector X. Parameters ---------- X : array-like, shape = [n_samples, n_features] Returns ------- C : array-like, shape = [n_samples, n_classes] Returns the log-probability of the samples for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute `classes_`.
[ "Return", "log", "-", "probability", "estimates", "for", "the", "test", "vector", "X", ".", "Parameters", "----------", "X", ":", "array", "-", "like", "shape", "=", "[", "n_samples", "n_features", "]", "Returns", "-------", "C", ":", "array", "-", "like",...
python
train
lago-project/lago
lago/prefix.py
https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/prefix.py#L133-L141
def _save_metadata(self): """ Write this prefix metadata to disk Returns: None """ with open(self.paths.metadata(), 'w') as metadata_fd: utils.json_dump(self.metadata, metadata_fd)
[ "def", "_save_metadata", "(", "self", ")", ":", "with", "open", "(", "self", ".", "paths", ".", "metadata", "(", ")", ",", "'w'", ")", "as", "metadata_fd", ":", "utils", ".", "json_dump", "(", "self", ".", "metadata", ",", "metadata_fd", ")" ]
Write this prefix metadata to disk Returns: None
[ "Write", "this", "prefix", "metadata", "to", "disk" ]
python
train
gwastro/pycbc
pycbc/io/record.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L1840-L1843
def spin1_a(self): """Returns the dimensionless spin magnitude of mass 1.""" return coordinates.cartesian_to_spherical_rho( self.spin1x, self.spin1y, self.spin1z)
[ "def", "spin1_a", "(", "self", ")", ":", "return", "coordinates", ".", "cartesian_to_spherical_rho", "(", "self", ".", "spin1x", ",", "self", ".", "spin1y", ",", "self", ".", "spin1z", ")" ]
Returns the dimensionless spin magnitude of mass 1.
[ "Returns", "the", "dimensionless", "spin", "magnitude", "of", "mass", "1", "." ]
python
train
radujica/baloo
baloo/weld/weld_joins.py
https://github.com/radujica/baloo/blob/f6e05e35b73a75e8a300754c6bdc575e5f2d53b9/baloo/weld/weld_joins.py#L110-L156
def weld_merge_join(arrays_self, weld_types_self, arrays_other, weld_types_other, how, is_on_sorted, is_on_unique, readable_text): """Applies merge-join on the arrays returning indices from each to keep in the resulting Parameters ---------- arrays_self : list of (numpy.ndarray or WeldObject) Columns from the self DataFrame on which to join. weld_types_self : list of WeldType Corresponding Weld types. arrays_other : list of (numpy.ndarray or WeldObject) Columns from the other DataFrame on which to join. weld_types_other : list of WeldType Corresponding Weld types. how : {'inner', 'left', 'right'} Which kind of join to do. is_on_sorted : bool If we know that the on columns are already sorted, can employ faster algorithm. is_on_unique : bool If we know that the values are unique, can employ faster algorithm. readable_text : str Explanatory string to add in the Weld placeholder. Returns ------- tuple of WeldObject Two columns of indices from the input arrays, indices of the rows from self and other that should be available in the resulting joined DataFrame. """ assert is_on_unique weld_obj_vec_of_struct_self = weld_arrays_to_vec_of_struct(arrays_self, weld_types_self) weld_obj_vec_of_struct_other = weld_arrays_to_vec_of_struct(arrays_other, weld_types_other) weld_obj_join = _weld_merge_join(weld_obj_vec_of_struct_self, weld_obj_vec_of_struct_other, len(arrays_self), how, is_on_unique) intermediate_result = LazyStructOfVecResult(weld_obj_join, [WeldLong(), WeldLong()]) dependency_name = Cache.cache_intermediate_result(intermediate_result, readable_text) weld_objects = extract_placeholder_weld_objects(dependency_name, 2, readable_text) return weld_objects
[ "def", "weld_merge_join", "(", "arrays_self", ",", "weld_types_self", ",", "arrays_other", ",", "weld_types_other", ",", "how", ",", "is_on_sorted", ",", "is_on_unique", ",", "readable_text", ")", ":", "assert", "is_on_unique", "weld_obj_vec_of_struct_self", "=", "wel...
Applies merge-join on the arrays returning indices from each to keep in the resulting Parameters ---------- arrays_self : list of (numpy.ndarray or WeldObject) Columns from the self DataFrame on which to join. weld_types_self : list of WeldType Corresponding Weld types. arrays_other : list of (numpy.ndarray or WeldObject) Columns from the other DataFrame on which to join. weld_types_other : list of WeldType Corresponding Weld types. how : {'inner', 'left', 'right'} Which kind of join to do. is_on_sorted : bool If we know that the on columns are already sorted, can employ faster algorithm. is_on_unique : bool If we know that the values are unique, can employ faster algorithm. readable_text : str Explanatory string to add in the Weld placeholder. Returns ------- tuple of WeldObject Two columns of indices from the input arrays, indices of the rows from self and other that should be available in the resulting joined DataFrame.
[ "Applies", "merge", "-", "join", "on", "the", "arrays", "returning", "indices", "from", "each", "to", "keep", "in", "the", "resulting" ]
python
train
saltstack/salt
salt/states/win_dism.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_dism.py#L368-L443
def package_removed(name, image=None, restart=False): ''' Uninstall a package Args: name (str): The full path to the package. Can be either a .cab file or a folder. Should point to the original source of the package, not to where the file is installed. This can also be the name of a package as listed in ``dism.installed_packages`` image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Example: .. code-block:: yaml # Example using source remove_KB1231231: dism.package_installed: - name: C:\\Packages\\KB1231231.cab # Example using name from ``dism.installed_packages`` remove_KB1231231: dism.package_installed: - name: Package_for_KB1231231~31bf3856ad364e35~amd64~~10.0.1.3 ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} # Fail if using a non-existent package path if '~' not in name and not os.path.exists(name): if __opts__['test']: ret['result'] = None else: ret['result'] = False ret['comment'] = 'Package path {0} does not exist'.format(name) return ret old = __salt__['dism.installed_packages']() # Get package info so we can see if it's already removed package_info = __salt__['dism.package_info'](name) # If `Package Identity` isn't returned or if they passed a cab file, if # `Package Identity` isn't in the list of installed packages if 'Package Identity' not in package_info or \ package_info['Package Identity'] not in old: ret['comment'] = 'The package {0} is already removed'.format(name) return ret if __opts__['test']: ret['changes']['package'] = '{0} will be removed'.format(name) ret['result'] = None return ret # Remove the package status = __salt__['dism.remove_package'](name, image, restart) if status['retcode'] not in [0, 1641, 3010]: ret['comment'] = 'Failed to remove {0}: {1}' \ .format(name, status['stdout']) ret['result'] = False new = __salt__['dism.installed_packages']() changes = salt.utils.data.compare_lists(old, new) if changes: ret['comment'] = 'Removed {0}'.format(name) ret['changes'] = status ret['changes']['package'] = changes return ret
[ "def", "package_removed", "(", "name", ",", "image", "=", "None", ",", "restart", "=", "False", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", ",", "'changes'", ":", "{", "}", "}", "# Fa...
Uninstall a package Args: name (str): The full path to the package. Can be either a .cab file or a folder. Should point to the original source of the package, not to where the file is installed. This can also be the name of a package as listed in ``dism.installed_packages`` image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Example: .. code-block:: yaml # Example using source remove_KB1231231: dism.package_installed: - name: C:\\Packages\\KB1231231.cab # Example using name from ``dism.installed_packages`` remove_KB1231231: dism.package_installed: - name: Package_for_KB1231231~31bf3856ad364e35~amd64~~10.0.1.3
[ "Uninstall", "a", "package" ]
python
train
AkihikoITOH/capybara
capybara/virtualenv/lib/python2.7/site-packages/pip/wheel.py
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/pip/wheel.py#L193-L206
def root_is_purelib(name, wheeldir): """ Return True if the extracted wheel in wheeldir should go into purelib. """ name_folded = name.replace("-", "_") for item in os.listdir(wheeldir): match = dist_info_re.match(item) if match and match.group('name') == name_folded: with open(os.path.join(wheeldir, item, 'WHEEL')) as wheel: for line in wheel: line = line.lower().rstrip() if line == "root-is-purelib: true": return True return False
[ "def", "root_is_purelib", "(", "name", ",", "wheeldir", ")", ":", "name_folded", "=", "name", ".", "replace", "(", "\"-\"", ",", "\"_\"", ")", "for", "item", "in", "os", ".", "listdir", "(", "wheeldir", ")", ":", "match", "=", "dist_info_re", ".", "mat...
Return True if the extracted wheel in wheeldir should go into purelib.
[ "Return", "True", "if", "the", "extracted", "wheel", "in", "wheeldir", "should", "go", "into", "purelib", "." ]
python
test
bram85/topydo
topydo/lib/Todo.py
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Todo.py#L58-L64
def is_active(self): """ Returns True when the start date is today or in the past and the task has not yet been completed. """ start = self.start_date() return not self.is_completed() and (not start or start <= date.today())
[ "def", "is_active", "(", "self", ")", ":", "start", "=", "self", ".", "start_date", "(", ")", "return", "not", "self", ".", "is_completed", "(", ")", "and", "(", "not", "start", "or", "start", "<=", "date", ".", "today", "(", ")", ")" ]
Returns True when the start date is today or in the past and the task has not yet been completed.
[ "Returns", "True", "when", "the", "start", "date", "is", "today", "or", "in", "the", "past", "and", "the", "task", "has", "not", "yet", "been", "completed", "." ]
python
train
ncolony/ncolony
ncolony/directory_monitor.py
https://github.com/ncolony/ncolony/blob/6ac71bda1de6706fb34244ae4972e36db5f062d3/ncolony/directory_monitor.py#L15-L52
def checker(location, receiver): """Construct a function that checks a directory for process configuration The function checks for additions or removals of JSON process configuration files and calls the appropriate receiver methods. :param location: string, the directory to monitor :param receiver: IEventReceiver :returns: a function with no parameters """ path = filepath.FilePath(location) files = set() filesContents = {} def _check(path): currentFiles = set(fname for fname in os.listdir(location) if not fname.endswith('.new')) removed = files - currentFiles added = currentFiles - files for fname in added: contents = path.child(fname).getContent() filesContents[fname] = contents receiver.add(fname, contents) for fname in removed: receiver.remove(fname) same = currentFiles & files for fname in same: newContents = path.child(fname).getContent() oldContents = filesContents[fname] if newContents == oldContents: continue receiver.remove(fname) filesContents[fname] = newContents receiver.add(fname, newContents) files.clear() files.update(currentFiles) return functools.partial(_check, path)
[ "def", "checker", "(", "location", ",", "receiver", ")", ":", "path", "=", "filepath", ".", "FilePath", "(", "location", ")", "files", "=", "set", "(", ")", "filesContents", "=", "{", "}", "def", "_check", "(", "path", ")", ":", "currentFiles", "=", ...
Construct a function that checks a directory for process configuration The function checks for additions or removals of JSON process configuration files and calls the appropriate receiver methods. :param location: string, the directory to monitor :param receiver: IEventReceiver :returns: a function with no parameters
[ "Construct", "a", "function", "that", "checks", "a", "directory", "for", "process", "configuration" ]
python
test
ghcollin/multitables
multitables.py
https://github.com/ghcollin/multitables/blob/9654a45800289a20e66d2b0e0666149f0d370f93/multitables.py#L345-L348
def close(self): """Close the queue, signalling that no more data can be put into the queue.""" self.read_queue.put(QueueClosed) self.write_queue.put(QueueClosed)
[ "def", "close", "(", "self", ")", ":", "self", ".", "read_queue", ".", "put", "(", "QueueClosed", ")", "self", ".", "write_queue", ".", "put", "(", "QueueClosed", ")" ]
Close the queue, signalling that no more data can be put into the queue.
[ "Close", "the", "queue", "signalling", "that", "no", "more", "data", "can", "be", "put", "into", "the", "queue", "." ]
python
test
Microsoft/azure-devops-python-api
azure-devops/azure/devops/v5_1/work_item_tracking_comments/work_item_tracking_comments_client.py
https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_1/work_item_tracking_comments/work_item_tracking_comments_client.py#L28-L47
def add_comment(self, request, project, work_item_id): """AddComment. [Preview API] Add a comment on a work item. :param :class:`<WorkItemCommentCreateRequest> <azure.devops.v5_1.work_item_tracking_comments.models.WorkItemCommentCreateRequest>` request: Comment create request. :param str project: Project ID or project name :param int work_item_id: Id of a work item. :rtype: :class:`<WorkItemCommentResponse> <azure.devops.v5_1.work-item-tracking-comments.models.WorkItemCommentResponse>` """ route_values = {} if project is not None: route_values['project'] = self._serialize.url('project', project, 'str') if work_item_id is not None: route_values['workItemId'] = self._serialize.url('work_item_id', work_item_id, 'int') content = self._serialize.body(request, 'WorkItemCommentCreateRequest') response = self._send(http_method='POST', location_id='608aac0a-32e1-4493-a863-b9cf4566d257', version='5.1-preview.1', route_values=route_values, content=content) return self._deserialize('WorkItemCommentResponse', response)
[ "def", "add_comment", "(", "self", ",", "request", ",", "project", ",", "work_item_id", ")", ":", "route_values", "=", "{", "}", "if", "project", "is", "not", "None", ":", "route_values", "[", "'project'", "]", "=", "self", ".", "_serialize", ".", "url",...
AddComment. [Preview API] Add a comment on a work item. :param :class:`<WorkItemCommentCreateRequest> <azure.devops.v5_1.work_item_tracking_comments.models.WorkItemCommentCreateRequest>` request: Comment create request. :param str project: Project ID or project name :param int work_item_id: Id of a work item. :rtype: :class:`<WorkItemCommentResponse> <azure.devops.v5_1.work-item-tracking-comments.models.WorkItemCommentResponse>`
[ "AddComment", ".", "[", "Preview", "API", "]", "Add", "a", "comment", "on", "a", "work", "item", ".", ":", "param", ":", "class", ":", "<WorkItemCommentCreateRequest", ">", "<azure", ".", "devops", ".", "v5_1", ".", "work_item_tracking_comments", ".", "model...
python
train
secdev/scapy
scapy/main.py
https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/main.py#L152-L158
def load_module(name, globals_dict=None, symb_list=None): """Loads a Scapy module to make variables, objects and functions available globally. """ _load("scapy.modules." + name, globals_dict=globals_dict, symb_list=symb_list)
[ "def", "load_module", "(", "name", ",", "globals_dict", "=", "None", ",", "symb_list", "=", "None", ")", ":", "_load", "(", "\"scapy.modules.\"", "+", "name", ",", "globals_dict", "=", "globals_dict", ",", "symb_list", "=", "symb_list", ")" ]
Loads a Scapy module to make variables, objects and functions available globally.
[ "Loads", "a", "Scapy", "module", "to", "make", "variables", "objects", "and", "functions", "available", "globally", "." ]
python
train
JarryShaw/PyPCAPKit
src/const/ftp/return_code.py
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/ftp/return_code.py#L89-L97
def _missing_(cls, value): """Lookup function used when value is not found.""" if not (isinstance(value, int) and 100 <= value <= 659): raise ValueError('%r is not a valid %s' % (value, cls.__name__)) code = str(value) kind = KIND.get(code[0], 'Reserved') info = INFO.get(code[1], 'Reserved') extend_enum(cls, '%s - %s [%s]' % (kind, info, value), value) return cls(value)
[ "def", "_missing_", "(", "cls", ",", "value", ")", ":", "if", "not", "(", "isinstance", "(", "value", ",", "int", ")", "and", "100", "<=", "value", "<=", "659", ")", ":", "raise", "ValueError", "(", "'%r is not a valid %s'", "%", "(", "value", ",", "...
Lookup function used when value is not found.
[ "Lookup", "function", "used", "when", "value", "is", "not", "found", "." ]
python
train
ejeschke/ginga
ginga/rv/Control.py
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L1758-L1764
def get_menu(self, name): """Get the menu with name `name` from the global menu bar. Returns a menu widget. """ if self.menubar is None: raise ValueError("No menu bar configured") return self.menubar.get_menu(name)
[ "def", "get_menu", "(", "self", ",", "name", ")", ":", "if", "self", ".", "menubar", "is", "None", ":", "raise", "ValueError", "(", "\"No menu bar configured\"", ")", "return", "self", ".", "menubar", ".", "get_menu", "(", "name", ")" ]
Get the menu with name `name` from the global menu bar. Returns a menu widget.
[ "Get", "the", "menu", "with", "name", "name", "from", "the", "global", "menu", "bar", ".", "Returns", "a", "menu", "widget", "." ]
python
train
OSSOS/MOP
src/ossos/core/ossos/storage.py
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1159-L1183
def get_zeropoint(expnum, ccd, prefix=None, version='p'): """Get the zeropoint for this exposure using the zeropoint.used file created during source planting.. This command expects that there is a file called #######p##.zeropoint.used which contains the zeropoint. @param expnum: exposure to get zeropoint of @param ccd: which ccd (extension - 1) to get zp @param prefix: possible string prefixed to expsoure number. @param version: one of [spo] as in #######p## @return: zeropoint """ uri = get_uri(expnum, ccd, version, ext='zeropoint.used', prefix=prefix) try: return zmag[uri] except: pass try: zmag[uri] = float(open_vos_or_local(uri).read()) return zmag[uri] except: pass zmag[uri] = 0.0 return zmag[uri]
[ "def", "get_zeropoint", "(", "expnum", ",", "ccd", ",", "prefix", "=", "None", ",", "version", "=", "'p'", ")", ":", "uri", "=", "get_uri", "(", "expnum", ",", "ccd", ",", "version", ",", "ext", "=", "'zeropoint.used'", ",", "prefix", "=", "prefix", ...
Get the zeropoint for this exposure using the zeropoint.used file created during source planting.. This command expects that there is a file called #######p##.zeropoint.used which contains the zeropoint. @param expnum: exposure to get zeropoint of @param ccd: which ccd (extension - 1) to get zp @param prefix: possible string prefixed to expsoure number. @param version: one of [spo] as in #######p## @return: zeropoint
[ "Get", "the", "zeropoint", "for", "this", "exposure", "using", "the", "zeropoint", ".", "used", "file", "created", "during", "source", "planting", ".." ]
python
train
numenta/htmresearch
projects/l2_pooling/ideal_classifier_experiment.py
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/l2_pooling/ideal_classifier_experiment.py#L85-L94
def classifierPredict(testVector, storedVectors): """ Return overlap of the testVector with stored representations for each object. """ numClasses = storedVectors.shape[0] output = np.zeros((numClasses,)) for i in range(numClasses): output[i] = np.sum(np.minimum(testVector, storedVectors[i, :])) return output
[ "def", "classifierPredict", "(", "testVector", ",", "storedVectors", ")", ":", "numClasses", "=", "storedVectors", ".", "shape", "[", "0", "]", "output", "=", "np", ".", "zeros", "(", "(", "numClasses", ",", ")", ")", "for", "i", "in", "range", "(", "n...
Return overlap of the testVector with stored representations for each object.
[ "Return", "overlap", "of", "the", "testVector", "with", "stored", "representations", "for", "each", "object", "." ]
python
train
cuescience/goat
goat/matcher.py
https://github.com/cuescience/goat/blob/d76f44b9ec5dc40ad33abca50830c0d7492ef152/goat/matcher.py#L76-L91
def convert(self, pattern: str) -> str: """Convert the goat step string to CFParse String""" parameters = OrderedDict() for parameter in self.signature.parameters.values(): annotation = self.convert_type_to_parse_type(parameter) parameters[parameter.name] = "{%s:%s}" % (parameter.name, annotation) formatter = GoatFormatter() # We have to use vformat here to ensure that kwargs will be OrderedDict values = parameters.values() parameter_list = list(values) converted_pattern = formatter.vformat(pattern, parameter_list, parameters) self.context_params = formatter.unused_args return converted_pattern
[ "def", "convert", "(", "self", ",", "pattern", ":", "str", ")", "->", "str", ":", "parameters", "=", "OrderedDict", "(", ")", "for", "parameter", "in", "self", ".", "signature", ".", "parameters", ".", "values", "(", ")", ":", "annotation", "=", "self"...
Convert the goat step string to CFParse String
[ "Convert", "the", "goat", "step", "string", "to", "CFParse", "String" ]
python
train
cdgriffith/Box
box.py
https://github.com/cdgriffith/Box/blob/5f09df824022127e7e335e3d993f7ddc1ed97fce/box.py#L196-L236
def _conversion_checks(item, keys, box_config, check_only=False, pre_check=False): """ Internal use for checking if a duplicate safe attribute already exists :param item: Item to see if a dup exists :param keys: Keys to check against :param box_config: Easier to pass in than ask for specfic items :param check_only: Don't bother doing the conversion work :param pre_check: Need to add the item to the list of keys to check :return: the original unmodified key, if exists and not check_only """ if box_config['box_duplicates'] != 'ignore': if pre_check: keys = list(keys) + [item] key_list = [(k, _safe_attr(k, camel_killer=box_config['camel_killer_box'], replacement_char=box_config['box_safe_prefix'] )) for k in keys] if len(key_list) > len(set(x[1] for x in key_list)): seen = set() dups = set() for x in key_list: if x[1] in seen: dups.add("{0}({1})".format(x[0], x[1])) seen.add(x[1]) if box_config['box_duplicates'].startswith("warn"): warnings.warn('Duplicate conversion attributes exist: ' '{0}'.format(dups)) else: raise BoxError('Duplicate conversion attributes exist: ' '{0}'.format(dups)) if check_only: return # This way will be slower for warnings, as it will have double work # But faster for the default 'ignore' for k in keys: if item == _safe_attr(k, camel_killer=box_config['camel_killer_box'], replacement_char=box_config['box_safe_prefix']): return k
[ "def", "_conversion_checks", "(", "item", ",", "keys", ",", "box_config", ",", "check_only", "=", "False", ",", "pre_check", "=", "False", ")", ":", "if", "box_config", "[", "'box_duplicates'", "]", "!=", "'ignore'", ":", "if", "pre_check", ":", "keys", "=...
Internal use for checking if a duplicate safe attribute already exists :param item: Item to see if a dup exists :param keys: Keys to check against :param box_config: Easier to pass in than ask for specfic items :param check_only: Don't bother doing the conversion work :param pre_check: Need to add the item to the list of keys to check :return: the original unmodified key, if exists and not check_only
[ "Internal", "use", "for", "checking", "if", "a", "duplicate", "safe", "attribute", "already", "exists" ]
python
train
vertexproject/synapse
synapse/lib/cell.py
https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/lib/cell.py#L70-L87
def setCellUser(self, iden): ''' Switch to another user (admin only). This API allows remote admin/service accounts to impersonate a user. Used mostly by services that manage their own authentication/sessions. ''' if not self.user.admin: mesg = 'setCellUser() caller must be admin.' raise s_exc.AuthDeny(mesg=mesg) user = self.cell.auth.user(iden) if user is None: raise s_exc.NoSuchUser(iden=iden) self.user = user return True
[ "def", "setCellUser", "(", "self", ",", "iden", ")", ":", "if", "not", "self", ".", "user", ".", "admin", ":", "mesg", "=", "'setCellUser() caller must be admin.'", "raise", "s_exc", ".", "AuthDeny", "(", "mesg", "=", "mesg", ")", "user", "=", "self", "....
Switch to another user (admin only). This API allows remote admin/service accounts to impersonate a user. Used mostly by services that manage their own authentication/sessions.
[ "Switch", "to", "another", "user", "(", "admin", "only", ")", "." ]
python
train
mdgoldberg/sportsref
sportsref/nba/teams.py
https://github.com/mdgoldberg/sportsref/blob/09f11ac856a23c96d666d1d510bb35d6f050b5c3/sportsref/nba/teams.py#L67-L76
def schedule(self, year): """Gets schedule information for a team-season. :year: The year for which we want the schedule. :returns: DataFrame of schedule information. """ doc = self.get_year_doc('{}_games'.format(year)) table = doc('table#games') df = sportsref.utils.parse_table(table) return df
[ "def", "schedule", "(", "self", ",", "year", ")", ":", "doc", "=", "self", ".", "get_year_doc", "(", "'{}_games'", ".", "format", "(", "year", ")", ")", "table", "=", "doc", "(", "'table#games'", ")", "df", "=", "sportsref", ".", "utils", ".", "parse...
Gets schedule information for a team-season. :year: The year for which we want the schedule. :returns: DataFrame of schedule information.
[ "Gets", "schedule", "information", "for", "a", "team", "-", "season", "." ]
python
test
wmayner/pyphi
pyphi/models/fmt.py
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/fmt.py#L195-L199
def labels(indices, node_labels=None): """Get the labels for a tuple of mechanism indices.""" if node_labels is None: return tuple(map(str, indices)) return node_labels.indices2labels(indices)
[ "def", "labels", "(", "indices", ",", "node_labels", "=", "None", ")", ":", "if", "node_labels", "is", "None", ":", "return", "tuple", "(", "map", "(", "str", ",", "indices", ")", ")", "return", "node_labels", ".", "indices2labels", "(", "indices", ")" ]
Get the labels for a tuple of mechanism indices.
[ "Get", "the", "labels", "for", "a", "tuple", "of", "mechanism", "indices", "." ]
python
train
dddomodossola/remi
remi/gui.py
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L2041-L2050
def new_from_list(cls, items, **kwargs): """Populates the ListView with a string list. Args: items (list): list of strings to fill the widget with. """ obj = cls(**kwargs) for item in items: obj.append(ListItem(item)) return obj
[ "def", "new_from_list", "(", "cls", ",", "items", ",", "*", "*", "kwargs", ")", ":", "obj", "=", "cls", "(", "*", "*", "kwargs", ")", "for", "item", "in", "items", ":", "obj", ".", "append", "(", "ListItem", "(", "item", ")", ")", "return", "obj"...
Populates the ListView with a string list. Args: items (list): list of strings to fill the widget with.
[ "Populates", "the", "ListView", "with", "a", "string", "list", "." ]
python
train
openstack/hacking
hacking/checks/docstrings.py
https://github.com/openstack/hacking/blob/10e58f907181cac91d3b2af422c2458b04a1ec79/hacking/checks/docstrings.py#L46-L73
def hacking_docstring_multiline_end(physical_line, previous_logical, tokens): r"""Check multi line docstring end. OpenStack HACKING guide recommendation for docstring: Docstring should end on a new line Okay: '''foobar\nfoo\nbar\n''' Okay: def foo():\n '''foobar\n\nfoo\nbar\n''' Okay: class Foo(object):\n '''foobar\n\nfoo\nbar\n''' Okay: def foo():\n a = '''not\na\ndocstring''' Okay: def foo():\n a = '''not\na\ndocstring''' # blah Okay: def foo():\n pass\n'''foobar\nfoo\nbar\n d''' H403: def foo():\n '''foobar\nfoo\nbar\ndocstring''' H403: def foo():\n '''foobar\nfoo\nbar\npretend raw: r''' H403: class Foo(object):\n '''foobar\nfoo\nbar\ndocstring'''\n\n """ docstring = is_docstring(tokens, previous_logical) if docstring: if '\n' not in docstring: # not a multi line return else: last_line = docstring.split('\n')[-1] pos = max(last_line.rfind(i) for i in END_DOCSTRING_TRIPLE) if len(last_line[:pos].strip()) > 0: # Something before the end docstring triple return (pos, "H403: multi line docstrings should end on a new line")
[ "def", "hacking_docstring_multiline_end", "(", "physical_line", ",", "previous_logical", ",", "tokens", ")", ":", "docstring", "=", "is_docstring", "(", "tokens", ",", "previous_logical", ")", "if", "docstring", ":", "if", "'\\n'", "not", "in", "docstring", ":", ...
r"""Check multi line docstring end. OpenStack HACKING guide recommendation for docstring: Docstring should end on a new line Okay: '''foobar\nfoo\nbar\n''' Okay: def foo():\n '''foobar\n\nfoo\nbar\n''' Okay: class Foo(object):\n '''foobar\n\nfoo\nbar\n''' Okay: def foo():\n a = '''not\na\ndocstring''' Okay: def foo():\n a = '''not\na\ndocstring''' # blah Okay: def foo():\n pass\n'''foobar\nfoo\nbar\n d''' H403: def foo():\n '''foobar\nfoo\nbar\ndocstring''' H403: def foo():\n '''foobar\nfoo\nbar\npretend raw: r''' H403: class Foo(object):\n '''foobar\nfoo\nbar\ndocstring'''\n\n
[ "r", "Check", "multi", "line", "docstring", "end", "." ]
python
train
openstax/cnx-epub
cnxepub/adapters.py
https://github.com/openstax/cnx-epub/blob/f648a309eff551b0a68a115a98ddf7858149a2ea/cnxepub/adapters.py#L94-L99
def make_epub(binders, file): """Creates an EPUB file from a binder(s).""" if not isinstance(binders, (list, set, tuple,)): binders = [binders] epub = EPUB([_make_package(binder) for binder in binders]) epub.to_file(epub, file)
[ "def", "make_epub", "(", "binders", ",", "file", ")", ":", "if", "not", "isinstance", "(", "binders", ",", "(", "list", ",", "set", ",", "tuple", ",", ")", ")", ":", "binders", "=", "[", "binders", "]", "epub", "=", "EPUB", "(", "[", "_make_package...
Creates an EPUB file from a binder(s).
[ "Creates", "an", "EPUB", "file", "from", "a", "binder", "(", "s", ")", "." ]
python
train
hubo1016/vlcp
vlcp/utils/networkplugin.py
https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/utils/networkplugin.py#L104-L132
def deletephysicalnetwork(check_processor = default_physicalnetwork_delete_check, reorder_dict = default_iterate_dict): """ :param check_processor: check_processor(physicalnetwork, physicalnetworkmap, walk, write, \*, parameters) """ def walker(walk, write, timestamp, parameters_dict): for key, parameters in reorder_dict(parameters_dict): try: value = walk(key) except KeyError: pass else: id_ = parameters['id'] try: phy_map = walk(PhysicalNetworkMap.default_key(id_)) except KeyError: pass else: check_processor(value, phy_map, walk, write, parameters=parameters) write(phy_map.getkey(), None) try: phynetset = walk(PhysicalNetworkSet.default_key()) except KeyError: pass else: phynetset.set.dataset().discard(value.create_weakreference()) write(phynetset.getkey(), phynetset) write(key, None) return walker
[ "def", "deletephysicalnetwork", "(", "check_processor", "=", "default_physicalnetwork_delete_check", ",", "reorder_dict", "=", "default_iterate_dict", ")", ":", "def", "walker", "(", "walk", ",", "write", ",", "timestamp", ",", "parameters_dict", ")", ":", "for", "k...
:param check_processor: check_processor(physicalnetwork, physicalnetworkmap, walk, write, \*, parameters)
[ ":", "param", "check_processor", ":", "check_processor", "(", "physicalnetwork", "physicalnetworkmap", "walk", "write", "\\", "*", "parameters", ")" ]
python
train
incf-nidash/nidmresults
nidmresults/objects/modelfitting.py
https://github.com/incf-nidash/nidmresults/blob/438f7cce6abc4a4379b629bd76f4d427891e033f/nidmresults/objects/modelfitting.py#L959-L983
def export(self, nidm_version, export_dir): """ Create prov entities and activities. """ if self.masked_median is None: grand_mean_file = self.file.path grand_mean_img = nib.load(grand_mean_file) grand_mean_data = grand_mean_img.get_data() grand_mean_data = np.ndarray.flatten(grand_mean_data) mask_img = nib.load(self.mask_file) mask_data = mask_img.get_data() mask_data = np.ndarray.flatten(mask_data) grand_mean_data_in_mask = grand_mean_data[mask_data > 0] self.masked_median = np.median( np.array(grand_mean_data_in_mask, dtype=float)) self.add_attributes(( (PROV['type'], self.type), (PROV['label'], self.label), (NIDM_MASKED_MEDIAN, self.masked_median), (NIDM_IN_COORDINATE_SPACE, self.coord_space.id)) )
[ "def", "export", "(", "self", ",", "nidm_version", ",", "export_dir", ")", ":", "if", "self", ".", "masked_median", "is", "None", ":", "grand_mean_file", "=", "self", ".", "file", ".", "path", "grand_mean_img", "=", "nib", ".", "load", "(", "grand_mean_fil...
Create prov entities and activities.
[ "Create", "prov", "entities", "and", "activities", "." ]
python
train
jleinonen/pytmatrix
pytmatrix/scatter.py
https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/scatter.py#L46-L64
def ldr(scatterer, h_pol=True): """ Linear depolarizarion ratio (LDR) for the current setup. Args: scatterer: a Scatterer instance. h_pol: If True (default), return LDR_h. If False, return LDR_v. Returns: The LDR. """ Z = scatterer.get_Z() if h_pol: return (Z[0,0] - Z[0,1] + Z[1,0] - Z[1,1]) / \ (Z[0,0] - Z[0,1] - Z[1,0] + Z[1,1]) else: return (Z[0,0] + Z[0,1] - Z[1,0] - Z[1,1]) / \ (Z[0,0] + Z[0,1] + Z[1,0] + Z[1,1])
[ "def", "ldr", "(", "scatterer", ",", "h_pol", "=", "True", ")", ":", "Z", "=", "scatterer", ".", "get_Z", "(", ")", "if", "h_pol", ":", "return", "(", "Z", "[", "0", ",", "0", "]", "-", "Z", "[", "0", ",", "1", "]", "+", "Z", "[", "1", ",...
Linear depolarizarion ratio (LDR) for the current setup. Args: scatterer: a Scatterer instance. h_pol: If True (default), return LDR_h. If False, return LDR_v. Returns: The LDR.
[ "Linear", "depolarizarion", "ratio", "(", "LDR", ")", "for", "the", "current", "setup", "." ]
python
train
SylvanasSun/FishFishJump
fish_dashboard/scrapyd/scrapyd_agent.py
https://github.com/SylvanasSun/FishFishJump/blob/696212d242d8d572f3f1b43925f3d8ab8acc6a2d/fish_dashboard/scrapyd/scrapyd_agent.py#L50-L67
def init_command_set(self, scrapyd_url): """ Initialize command set by scrapyd_url,each element is a list such as ['command','supported http method type'] """ if scrapyd_url[-1:] != '/': scrapyd_url = scrapyd_url + '/' self['daemonstatus'] = [scrapyd_url + 'daemonstatus.json', http_utils.METHOD_GET] self['addversion'] = [scrapyd_url + 'addversion.json', http_utils.METHOD_POST] self['schedule'] = [scrapyd_url + 'schedule.json', http_utils.METHOD_POST] self['cancel'] = [scrapyd_url + 'cancel.json', http_utils.METHOD_POST] self['listprojects'] = [scrapyd_url + 'listprojects.json', http_utils.METHOD_GET] self['listversions'] = [scrapyd_url + 'listversions.json', http_utils.METHOD_GET] self['listspiders'] = [scrapyd_url + 'listspiders.json', http_utils.METHOD_GET] self['listjobs'] = [scrapyd_url + 'listjobs.json', http_utils.METHOD_GET] self['delversion'] = [scrapyd_url + 'delversion.json', http_utils.METHOD_POST] self['delproject'] = [scrapyd_url + 'delproject.json', http_utils.METHOD_POST] self['logs'] = [scrapyd_url + 'logs/', http_utils.METHOD_GET]
[ "def", "init_command_set", "(", "self", ",", "scrapyd_url", ")", ":", "if", "scrapyd_url", "[", "-", "1", ":", "]", "!=", "'/'", ":", "scrapyd_url", "=", "scrapyd_url", "+", "'/'", "self", "[", "'daemonstatus'", "]", "=", "[", "scrapyd_url", "+", "'daemo...
Initialize command set by scrapyd_url,each element is a list such as ['command','supported http method type']
[ "Initialize", "command", "set", "by", "scrapyd_url", "each", "element", "is", "a", "list", "such", "as", "[", "command", "supported", "http", "method", "type", "]" ]
python
train
tensorflow/tensor2tensor
tensor2tensor/models/research/glow_ops.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/glow_ops.py#L300-L331
def actnorm_scale(name, x, logscale_factor=3., reverse=False, init=False): """Per-channel scaling of x.""" x_shape = common_layers.shape_list(x) with tf.variable_scope(name, reuse=tf.AUTO_REUSE): # Variance initialization logic. assert len(x_shape) == 2 or len(x_shape) == 4 if len(x_shape) == 2: x_var = tf.reduce_mean(x**2, [0], keepdims=True) logdet_factor = 1 var_shape = (1, x_shape[1]) elif len(x_shape) == 4: x_var = tf.reduce_mean(x**2, [0, 1, 2], keepdims=True) logdet_factor = x_shape[1]*x_shape[2] var_shape = (1, 1, 1, x_shape[3]) init_value = tf.log(1.0 / (tf.sqrt(x_var) + 1e-6)) / logscale_factor logs = get_variable_ddi("logs", var_shape, initial_value=init_value, init=init) logs = logs * logscale_factor # Function and reverse function. if not reverse: x = x * tf.exp(logs) else: x = x * tf.exp(-logs) # Objective calculation, h * w * sum(log|s|) dlogdet = tf.reduce_sum(logs) * logdet_factor if reverse: dlogdet *= -1 return x, dlogdet
[ "def", "actnorm_scale", "(", "name", ",", "x", ",", "logscale_factor", "=", "3.", ",", "reverse", "=", "False", ",", "init", "=", "False", ")", ":", "x_shape", "=", "common_layers", ".", "shape_list", "(", "x", ")", "with", "tf", ".", "variable_scope", ...
Per-channel scaling of x.
[ "Per", "-", "channel", "scaling", "of", "x", "." ]
python
train
SBRG/ssbio
ssbio/pipeline/atlas2.py
https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/pipeline/atlas2.py#L560-L583
def _align_orthologous_gene_pairwise(self, g_id, gapopen=10, gapextend=0.5, engine='needle', parse=True, force_rerun=False): """Align orthologous strain sequences to representative Protein sequence, save as new pickle""" protein_seqs_aln_pickle_path = op.join(self.sequences_by_gene_dir, '{}_protein_withseqs_dis_aln.pckl'.format(g_id)) if ssbio.utils.force_rerun(flag=force_rerun, outfile=protein_seqs_aln_pickle_path): protein_seqs_pickle_path = self.gene_protein_pickles[g_id] protein_pickle = ssbio.io.load_pickle(protein_seqs_pickle_path) if not protein_pickle.representative_sequence: log.error('{}: no representative sequence to align to'.format(g_id)) return if len(protein_pickle.sequences) < 1: log.error('{}: no other sequences to align to'.format(g_id)) return alignment_dir = op.join(self.sequences_by_gene_dir, g_id) ssbio.utils.make_dir(alignment_dir) protein_pickle.pairwise_align_sequences_to_representative(gapopen=gapopen, gapextend=gapextend, engine=engine, outdir=alignment_dir, parse=parse, force_rerun=force_rerun) protein_pickle.save_pickle(outfile=protein_seqs_aln_pickle_path) return g_id, protein_seqs_aln_pickle_path
[ "def", "_align_orthologous_gene_pairwise", "(", "self", ",", "g_id", ",", "gapopen", "=", "10", ",", "gapextend", "=", "0.5", ",", "engine", "=", "'needle'", ",", "parse", "=", "True", ",", "force_rerun", "=", "False", ")", ":", "protein_seqs_aln_pickle_path",...
Align orthologous strain sequences to representative Protein sequence, save as new pickle
[ "Align", "orthologous", "strain", "sequences", "to", "representative", "Protein", "sequence", "save", "as", "new", "pickle" ]
python
train
hydpy-dev/hydpy
hydpy/models/dam/dam_model.py
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/dam/dam_model.py#L54-L58
def pic_loggedrequiredremoterelease_v1(self): """Update the receiver link sequence.""" log = self.sequences.logs.fastaccess rec = self.sequences.receivers.fastaccess log.loggedrequiredremoterelease[0] = rec.d[0]
[ "def", "pic_loggedrequiredremoterelease_v1", "(", "self", ")", ":", "log", "=", "self", ".", "sequences", ".", "logs", ".", "fastaccess", "rec", "=", "self", ".", "sequences", ".", "receivers", ".", "fastaccess", "log", ".", "loggedrequiredremoterelease", "[", ...
Update the receiver link sequence.
[ "Update", "the", "receiver", "link", "sequence", "." ]
python
train
Kozea/pygal
pygal/svg.py
https://github.com/Kozea/pygal/blob/5e25c98a59a0642eecd9fcc5dbfeeb2190fbb5e7/pygal/svg.py#L495-L525
def get_strokes(self): """Return a css snippet containing all stroke style options""" def stroke_dict_to_css(stroke, i=None): """Return a css style for the given option""" css = [ '%s.series%s {\n' % (self.id, '.serie-%d' % i if i is not None else '') ] for key in ('width', 'linejoin', 'linecap', 'dasharray', 'dashoffset'): if stroke.get(key): css.append(' stroke-%s: %s;\n' % (key, stroke[key])) css.append('}') return '\n'.join(css) css = [] if self.graph.stroke_style is not None: css.append(stroke_dict_to_css(self.graph.stroke_style)) for serie in self.graph.series: if serie.stroke_style is not None: css.append(stroke_dict_to_css(serie.stroke_style, serie.index)) for secondary_serie in self.graph.secondary_series: if secondary_serie.stroke_style is not None: css.append( stroke_dict_to_css( secondary_serie.stroke_style, secondary_serie.index ) ) return '\n'.join(css)
[ "def", "get_strokes", "(", "self", ")", ":", "def", "stroke_dict_to_css", "(", "stroke", ",", "i", "=", "None", ")", ":", "\"\"\"Return a css style for the given option\"\"\"", "css", "=", "[", "'%s.series%s {\\n'", "%", "(", "self", ".", "id", ",", "'.serie-%d'...
Return a css snippet containing all stroke style options
[ "Return", "a", "css", "snippet", "containing", "all", "stroke", "style", "options" ]
python
train
rmax/scrapydo
scrapydo/api.py
https://github.com/rmax/scrapydo/blob/b0f9e6d50a5ea9d2ba8335bffa877003109c3af5/scrapydo/api.py#L180-L216
def _run_spider_in_reactor(spider_cls, capture_items=True, return_crawler=False, settings=None, **kwargs): """Runs given spider inside the twisted reactdor. Parameters ---------- spider_cls : scrapy.Spider Spider to run. capture_items : bool (default: True) If enabled, the scraped items are captured and returned. return_crawler : bool (default: False) If enabled, the crawler instance is returned. If ``capture_items`` is enabled, the scraped items is collected in ``crawler.items``. settings : dict, optional Custom crawler settings. Returns ------- out : crochet.EventualResult If ``capture_items`` is ``True``, returns scraped items. If ``return_crawler`` is ``True``, returns the crawler instance. """ settings = settings or {} crawler_settings = get_project_settings().copy() crawler_settings.setdict(default_settings) crawler_settings.setdict(settings) log_scrapy_info(crawler_settings) crawler = Crawler(spider_cls, crawler_settings) d = crawler.crawl(**kwargs) if capture_items: crawler.items = _OutputItems() crawler.signals.connect(crawler.items.append, signal=signals.item_scraped) d.addCallback(lambda _: crawler.items) if return_crawler: d.addCallback(lambda _: crawler) return d
[ "def", "_run_spider_in_reactor", "(", "spider_cls", ",", "capture_items", "=", "True", ",", "return_crawler", "=", "False", ",", "settings", "=", "None", ",", "*", "*", "kwargs", ")", ":", "settings", "=", "settings", "or", "{", "}", "crawler_settings", "=",...
Runs given spider inside the twisted reactdor. Parameters ---------- spider_cls : scrapy.Spider Spider to run. capture_items : bool (default: True) If enabled, the scraped items are captured and returned. return_crawler : bool (default: False) If enabled, the crawler instance is returned. If ``capture_items`` is enabled, the scraped items is collected in ``crawler.items``. settings : dict, optional Custom crawler settings. Returns ------- out : crochet.EventualResult If ``capture_items`` is ``True``, returns scraped items. If ``return_crawler`` is ``True``, returns the crawler instance.
[ "Runs", "given", "spider", "inside", "the", "twisted", "reactdor", "." ]
python
train
MartinThoma/mpu
mpu/__init__.py
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/__init__.py#L40-L63
def clip(number, lowest=None, highest=None): """ Clip a number to a given lowest / highest value. Parameters ---------- number : number lowest : number, optional highest : number, optional Returns ------- clipped_number : number Examples -------- >>> clip(42, lowest=0, highest=10) 10 """ if lowest is not None: number = max(number, lowest) if highest is not None: number = min(number, highest) return number
[ "def", "clip", "(", "number", ",", "lowest", "=", "None", ",", "highest", "=", "None", ")", ":", "if", "lowest", "is", "not", "None", ":", "number", "=", "max", "(", "number", ",", "lowest", ")", "if", "highest", "is", "not", "None", ":", "number",...
Clip a number to a given lowest / highest value. Parameters ---------- number : number lowest : number, optional highest : number, optional Returns ------- clipped_number : number Examples -------- >>> clip(42, lowest=0, highest=10) 10
[ "Clip", "a", "number", "to", "a", "given", "lowest", "/", "highest", "value", "." ]
python
train
pygobject/pgi
pgi/codegen/utils.py
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/codegen/utils.py#L94-L102
def add_dependency(self, name, obj): """Add a code dependency so it gets inserted into globals""" if name in self._deps: if self._deps[name] is obj: return raise ValueError( "There exists a different dep with the same name : %r" % name) self._deps[name] = obj
[ "def", "add_dependency", "(", "self", ",", "name", ",", "obj", ")", ":", "if", "name", "in", "self", ".", "_deps", ":", "if", "self", ".", "_deps", "[", "name", "]", "is", "obj", ":", "return", "raise", "ValueError", "(", "\"There exists a different dep ...
Add a code dependency so it gets inserted into globals
[ "Add", "a", "code", "dependency", "so", "it", "gets", "inserted", "into", "globals" ]
python
train
allenai/allennlp
allennlp/training/metrics/metric.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/metrics/metric.py#L29-L33
def get_metric(self, reset: bool) -> Union[float, Tuple[float, ...], Dict[str, float], Dict[str, List[float]]]: """ Compute and return the metric. Optionally also call :func:`self.reset`. """ raise NotImplementedError
[ "def", "get_metric", "(", "self", ",", "reset", ":", "bool", ")", "->", "Union", "[", "float", ",", "Tuple", "[", "float", ",", "...", "]", ",", "Dict", "[", "str", ",", "float", "]", ",", "Dict", "[", "str", ",", "List", "[", "float", "]", "]"...
Compute and return the metric. Optionally also call :func:`self.reset`.
[ "Compute", "and", "return", "the", "metric", ".", "Optionally", "also", "call", ":", "func", ":", "self", ".", "reset", "." ]
python
train
sci-bots/mpm
mpm/api.py
https://github.com/sci-bots/mpm/blob/a69651cda4b37ee6b17df4fe0809249e7f4dc536/mpm/api.py#L646-L721
def enabled_plugins(installed_only=True): ''' .. versionadded:: 0.21 Parameters ---------- installed_only : bool, optional Only consider enabled plugins that are installed in the Conda environment. Returns ------- list List of properties corresponding to each plugin that is **enabled**. If :data:`installed_only` is True``, only consider plugins: 1. Present in the ``etc/microdrop/plugins/enabled`` directory as a link/junction to a **real** directory (i.e., not a link) in the ``share/microdrop/plugins/available`` directory. 2. Matching the name of a package in the Conda environment. If :data:`installed_only` is ``False``, consider all plugins present in the ``etc/microdrop/plugins/enabled`` directory as either a *real* directory or a link/junction. ''' enabled_path = MICRODROP_CONDA_PLUGINS.joinpath('enabled') if not enabled_path.isdir(): return [] # Construct list of property dictionaries, one per enabled plugin # directory. enabled_plugins_ = [] for plugin_path_i in enabled_path.dirs(): if not installed_only or _islinklike(plugin_path_i): # Enabled plugin path is either **a link to an installed plugin** # or call explicitly specifies that plugins that are not installed # should still be considered. # Read plugin package info from `properties.yml` file. try: with plugin_path_i.joinpath('properties.yml').open('r') as input_: properties_i = yaml.load(input_.read()) except: logger.info('[warning] Could not read package info: `%s`', plugin_path_i.joinpath('properties.yml'), exc_info=True) continue else: properties_i['path'] = plugin_path_i.realpath() enabled_plugins_.append(properties_i) if installed_only: # Only consider enabled plugins that are installed in the Conda # environment. try: # Attempt to look up installed Conda package info for each enabled # plugin. package_names = [properties_i['package_name'] for properties_i in enabled_plugins_] installed_info = ch.package_version(package_names, verbose=False) except ch.PackageNotFound, exception: # Failed to find a corresponding installed Conda package for at # least one enabled plugin. logger.warning(str(exception)) available_names = set([package_i['name'] for package_i in exception.available]) # Only return list of enabled plugins that have a corresponding # Conda package installed. return [properties_i for properties_i in enabled_plugins_ if properties_i['package_name'] in available_names] # Return list of all enabled plugins, regardless of whether or not they # have corresponding Conda packages installed. return enabled_plugins_
[ "def", "enabled_plugins", "(", "installed_only", "=", "True", ")", ":", "enabled_path", "=", "MICRODROP_CONDA_PLUGINS", ".", "joinpath", "(", "'enabled'", ")", "if", "not", "enabled_path", ".", "isdir", "(", ")", ":", "return", "[", "]", "# Construct list of pro...
.. versionadded:: 0.21 Parameters ---------- installed_only : bool, optional Only consider enabled plugins that are installed in the Conda environment. Returns ------- list List of properties corresponding to each plugin that is **enabled**. If :data:`installed_only` is True``, only consider plugins: 1. Present in the ``etc/microdrop/plugins/enabled`` directory as a link/junction to a **real** directory (i.e., not a link) in the ``share/microdrop/plugins/available`` directory. 2. Matching the name of a package in the Conda environment. If :data:`installed_only` is ``False``, consider all plugins present in the ``etc/microdrop/plugins/enabled`` directory as either a *real* directory or a link/junction.
[ "..", "versionadded", "::", "0", ".", "21" ]
python
train
pyviz/holoviews
holoviews/core/element.py
https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/element.py#L261-L272
def table(self, datatype=None): "Deprecated method to convert any Element to a Table." if config.future_deprecations: self.param.warning( "The table method is deprecated and should no " "longer be used. Instead cast the %s to a " "a Table directly." % type(self).__name__) if datatype and not isinstance(datatype, list): datatype = [datatype] from ..element import Table return Table(self, **(dict(datatype=datatype) if datatype else {}))
[ "def", "table", "(", "self", ",", "datatype", "=", "None", ")", ":", "if", "config", ".", "future_deprecations", ":", "self", ".", "param", ".", "warning", "(", "\"The table method is deprecated and should no \"", "\"longer be used. Instead cast the %s to a \"", "\"a Ta...
Deprecated method to convert any Element to a Table.
[ "Deprecated", "method", "to", "convert", "any", "Element", "to", "a", "Table", "." ]
python
train
fredRos/pypmc
pypmc/mix_adapt/hierarchical.py
https://github.com/fredRos/pypmc/blob/9138b67c976f0d58edd080353d16769a47794d09/pypmc/mix_adapt/hierarchical.py#L153-L219
def run(self, eps=1e-4, kill=True, max_steps=50, verbose=False): r"""Perform the clustering on the input components updating the initial guess. The result is available in the member ``self.g``. Return the number of iterations at convergence, or None. :param eps: If relative change of distance between current and last step falls below ``eps``, declare convergence: .. math:: 0 < \frac{d^t - d^{t-1}}{d^t} < \varepsilon :param kill: If a component is assigned zero weight (no input components), it is removed. :param max_steps: Perform a maximum number of update steps. :param verbose: Output information on progress of algorithm. """ old_distance = np.finfo(np.float64).max new_distance = np.finfo(np.float64).max if verbose: print('Starting hierarchical clustering with %d components.' % len(self.g.components)) converged = False for step in range(1, max_steps + 1): self._cleanup(kill, verbose) self._regroup() self._refit() new_distance = self._distance() assert new_distance >= 0, 'Found non-positive distance %d' % new_distance if verbose: print('Distance in step %d: %g' % (step, new_distance)) if new_distance == old_distance: converged = True if verbose: print('Exact minimum found after %d steps' % step) break rel_change = (old_distance - new_distance) / old_distance assert not (rel_change < -1e-13), 'distance increased' if rel_change < eps and not converged and step > 0: converged = True if verbose and new_distance != old_distance: print('Close enough to local minimum after %d steps' % step) break # save distance for comparison in next step old_distance = new_distance self._cleanup(kill, verbose) if verbose: print('%d components remain.' % len(self.g.components)) if converged: return step
[ "def", "run", "(", "self", ",", "eps", "=", "1e-4", ",", "kill", "=", "True", ",", "max_steps", "=", "50", ",", "verbose", "=", "False", ")", ":", "old_distance", "=", "np", ".", "finfo", "(", "np", ".", "float64", ")", ".", "max", "new_distance", ...
r"""Perform the clustering on the input components updating the initial guess. The result is available in the member ``self.g``. Return the number of iterations at convergence, or None. :param eps: If relative change of distance between current and last step falls below ``eps``, declare convergence: .. math:: 0 < \frac{d^t - d^{t-1}}{d^t} < \varepsilon :param kill: If a component is assigned zero weight (no input components), it is removed. :param max_steps: Perform a maximum number of update steps. :param verbose: Output information on progress of algorithm.
[ "r", "Perform", "the", "clustering", "on", "the", "input", "components", "updating", "the", "initial", "guess", ".", "The", "result", "is", "available", "in", "the", "member", "self", ".", "g", "." ]
python
train
vmware/pyvmomi
pyVmomi/Differ.py
https://github.com/vmware/pyvmomi/blob/3ffcb23bf77d757175c0d5216ba9a25345d824cd/pyVmomi/Differ.py#L31-L40
def IsPrimitiveType(obj): """See if the passed in type is a Primitive Type""" return (isinstance(obj, types.bool) or isinstance(obj, types.byte) or isinstance(obj, types.short) or isinstance(obj, six.integer_types) or isinstance(obj, types.double) or isinstance(obj, types.float) or isinstance(obj, six.string_types) or isinstance(obj, types.PropertyPath) or isinstance(obj, types.ManagedMethod) or isinstance(obj, types.datetime) or isinstance(obj, types.URI) or isinstance(obj, type))
[ "def", "IsPrimitiveType", "(", "obj", ")", ":", "return", "(", "isinstance", "(", "obj", ",", "types", ".", "bool", ")", "or", "isinstance", "(", "obj", ",", "types", ".", "byte", ")", "or", "isinstance", "(", "obj", ",", "types", ".", "short", ")", ...
See if the passed in type is a Primitive Type
[ "See", "if", "the", "passed", "in", "type", "is", "a", "Primitive", "Type" ]
python
train
lrq3000/pyFileFixity
pyFileFixity/structural_adaptive_ecc.py
https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/structural_adaptive_ecc.py#L97-L135
def entry_fields(file, entry_pos, field_delim="\xFF"): '''From an ecc entry position (a list with starting and ending positions), extract the metadata fields (filename, filesize, ecc for both), and the starting/ending positions of the ecc stream (containing variably encoded blocks of hash and ecc per blocks of the original file's header)''' # Read the the beginning of the ecc entry blocksize = 65535 file.seek(entry_pos[0]) entry = file.read(blocksize) entry = entry.lstrip(field_delim) # if there was some slight adjustment error (example: the last ecc block of the last file was the field_delim, then we will start with a field_delim, and thus we need to remove the trailing field_delim which is useless and will make the field detection buggy). This is not really a big problem for the previous file's ecc block: the missing ecc characters (which were mistaken for a field_delim), will just be missing (so we will lose a bit of resiliency for the last block of the previous file, but that's not a huge issue, the correction can still rely on the other characters). # TODO: do in a while loop in case the filename is really big (bigger than blocksize) - or in case we add intra-ecc for filename # Find metadata fields delimiters positions # TODO: automate this part, just give in argument the number of field_delim to find, and the func will find the x field_delims (the number needs to be specified in argument because the field_delim can maybe be found wrongly inside the ecc stream, which we don't want) first = entry.find(field_delim) second = entry.find(field_delim, first+len(field_delim)) third = entry.find(field_delim, second+len(field_delim)) fourth = entry.find(field_delim, third+len(field_delim)) # Note: we do not try to find all the field delimiters because we optimize here: we just walk the string to find the exact number of field_delim we are looking for, and after we stop, no need to walk through the whole string. # Extract the content of the fields # Metadata fields relfilepath = entry[:first] filesize = entry[first+len(field_delim):second] relfilepath_ecc = entry[second+len(field_delim):third] filesize_ecc = entry[third+len(field_delim):fourth] # Ecc stream field (aka ecc blocks) ecc_field_pos = [entry_pos[0]+fourth+len(field_delim), entry_pos[1]] # return the starting and ending position of the rest of the ecc track, which contains blocks of hash/ecc of the original file's content. # Place the cursor at the beginning of the ecc_field file.seek(ecc_field_pos[0]) # Try to convert to an int, an error may happen try: filesize = int(filesize) except Exception, e: print("Exception when trying to detect the filesize in ecc field (it may be corrupted), skipping: ") print(e) #filesize = 0 # avoid setting to 0, we keep as an int so that we can try to fix using intra-ecc # entries = [ {"message":, "ecc":, "hash":}, etc.] return {"relfilepath": relfilepath, "relfilepath_ecc": relfilepath_ecc, "filesize": filesize, "filesize_ecc": filesize_ecc, "ecc_field_pos": ecc_field_pos}
[ "def", "entry_fields", "(", "file", ",", "entry_pos", ",", "field_delim", "=", "\"\\xFF\"", ")", ":", "# Read the the beginning of the ecc entry", "blocksize", "=", "65535", "file", ".", "seek", "(", "entry_pos", "[", "0", "]", ")", "entry", "=", "file", ".", ...
From an ecc entry position (a list with starting and ending positions), extract the metadata fields (filename, filesize, ecc for both), and the starting/ending positions of the ecc stream (containing variably encoded blocks of hash and ecc per blocks of the original file's header)
[ "From", "an", "ecc", "entry", "position", "(", "a", "list", "with", "starting", "and", "ending", "positions", ")", "extract", "the", "metadata", "fields", "(", "filename", "filesize", "ecc", "for", "both", ")", "and", "the", "starting", "/", "ending", "pos...
python
train
SciTools/biggus
biggus/_init.py
https://github.com/SciTools/biggus/blob/0a76fbe7806dd6295081cd399bcb76135d834d25/biggus/_init.py#L2728-L2754
def min(a, axis=None): """ Request the minimum of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. Parameters ---------- a : Array object The object whose minimum is to be found. axis : None, or int, or iterable of ints Axis or axes along which the operation is performed. The default (axis=None) is to perform the operation over all the dimensions of the input array. The axis may be negative, in which case it counts from the last to the first axis. If axis is a tuple of ints, the operation is performed over multiple axes. Returns ------- out : Array The Array representing the requested mean. """ axes = _normalise_axis(axis, a) assert axes is not None and len(axes) == 1 return _Aggregation(a, axes[0], _MinStreamsHandler, _MinMaskedStreamsHandler, a.dtype, {})
[ "def", "min", "(", "a", ",", "axis", "=", "None", ")", ":", "axes", "=", "_normalise_axis", "(", "axis", ",", "a", ")", "assert", "axes", "is", "not", "None", "and", "len", "(", "axes", ")", "==", "1", "return", "_Aggregation", "(", "a", ",", "ax...
Request the minimum of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. Parameters ---------- a : Array object The object whose minimum is to be found. axis : None, or int, or iterable of ints Axis or axes along which the operation is performed. The default (axis=None) is to perform the operation over all the dimensions of the input array. The axis may be negative, in which case it counts from the last to the first axis. If axis is a tuple of ints, the operation is performed over multiple axes. Returns ------- out : Array The Array representing the requested mean.
[ "Request", "the", "minimum", "of", "an", "Array", "over", "any", "number", "of", "axes", "." ]
python
train
funilrys/PyFunceble
PyFunceble/helpers.py
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/helpers.py#L654-L690
def fix_path(self, splited_path=None): """ Fix the path of the given path. :param splited_path: A list to convert to the right path. :type splited_path: list :return: The fixed path. :rtype: str """ if not splited_path: # A splited path is parsed. # We initate a variable which will save the splited path. split_path = [] if self.directory: # The parsed directory is not empty or equal to None. if "/" in self.directory: # We split the separator. split_path = self.directory.split("/") elif "\\" in self.directory: # We split the separator. split_path = self.directory.split("\\") else: split_path = [self.directory] # We run the same function with the splited_path argument filled. return self.fix_path(splited_path=[x for x in split_path if x]) # We return the directory. return self.directory # We join the splited element with the directory separator as glue. return directory_separator.join(splited_path) + directory_separator
[ "def", "fix_path", "(", "self", ",", "splited_path", "=", "None", ")", ":", "if", "not", "splited_path", ":", "# A splited path is parsed.", "# We initate a variable which will save the splited path.", "split_path", "=", "[", "]", "if", "self", ".", "directory", ":", ...
Fix the path of the given path. :param splited_path: A list to convert to the right path. :type splited_path: list :return: The fixed path. :rtype: str
[ "Fix", "the", "path", "of", "the", "given", "path", "." ]
python
test
pylast/pylast
src/pylast/__init__.py
https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L496-L503
def get_track_by_mbid(self, mbid): """Looks up a track by its MusicBrainz ID""" params = {"mbid": mbid} doc = _Request(self, "track.getInfo", params).execute(True) return Track(_extract(doc, "name", 1), _extract(doc, "name"), self)
[ "def", "get_track_by_mbid", "(", "self", ",", "mbid", ")", ":", "params", "=", "{", "\"mbid\"", ":", "mbid", "}", "doc", "=", "_Request", "(", "self", ",", "\"track.getInfo\"", ",", "params", ")", ".", "execute", "(", "True", ")", "return", "Track", "(...
Looks up a track by its MusicBrainz ID
[ "Looks", "up", "a", "track", "by", "its", "MusicBrainz", "ID" ]
python
train
mamikonyana/cryptotools
cryptotools/language_score.py
https://github.com/mamikonyana/cryptotools/blob/65c8d9b9ad225817db0be31c5845a000e911f238/cryptotools/language_score.py#L5-L15
def score_meaning(text): """ Returns a score in [0,1] range if the text makes any sense in English. """ #all_characters = re.findall('[ -~]', text) # match 32-126 in ASCII table all_characters = re.findall('[a-zA-Z ]', text) # match 32-126 in ASCII table if len(all_characters) == 0: return 0 repetition_count = Counter(all_characters) score = (len(all_characters)) ** 2 / (len(repetition_count) + len(text) / 26) return score
[ "def", "score_meaning", "(", "text", ")", ":", "#all_characters = re.findall('[ -~]', text) # match 32-126 in ASCII table", "all_characters", "=", "re", ".", "findall", "(", "'[a-zA-Z ]'", ",", "text", ")", "# match 32-126 in ASCII table", "if", "len", "(", "all_characters...
Returns a score in [0,1] range if the text makes any sense in English.
[ "Returns", "a", "score", "in", "[", "0", "1", "]", "range", "if", "the", "text", "makes", "any", "sense", "in", "English", "." ]
python
train
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/schema.py
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L1116-L1128
def column_lists_equal(a: List[Column], b: List[Column]) -> bool: """ Are all columns in list ``a`` equal to their counterparts in list ``b``, as per :func:`columns_equal`? """ n = len(a) if len(b) != n: return False for i in range(n): if not columns_equal(a[i], b[i]): log.debug("Mismatch: {!r} != {!r}", a[i], b[i]) return False return True
[ "def", "column_lists_equal", "(", "a", ":", "List", "[", "Column", "]", ",", "b", ":", "List", "[", "Column", "]", ")", "->", "bool", ":", "n", "=", "len", "(", "a", ")", "if", "len", "(", "b", ")", "!=", "n", ":", "return", "False", "for", "...
Are all columns in list ``a`` equal to their counterparts in list ``b``, as per :func:`columns_equal`?
[ "Are", "all", "columns", "in", "list", "a", "equal", "to", "their", "counterparts", "in", "list", "b", "as", "per", ":", "func", ":", "columns_equal", "?" ]
python
train
saltstack/salt
salt/utils/jinja.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/jinja.py#L577-L594
def intersect(lst1, lst2): ''' Returns the intersection of two lists. .. code-block:: jinja {% my_list = [1,2,3,4] -%} {{ set my_list | intersect([2, 4, 6]) }} will be rendered as: .. code-block:: text [2, 4] ''' if isinstance(lst1, collections.Hashable) and isinstance(lst2, collections.Hashable): return set(lst1) & set(lst2) return unique([ele for ele in lst1 if ele in lst2])
[ "def", "intersect", "(", "lst1", ",", "lst2", ")", ":", "if", "isinstance", "(", "lst1", ",", "collections", ".", "Hashable", ")", "and", "isinstance", "(", "lst2", ",", "collections", ".", "Hashable", ")", ":", "return", "set", "(", "lst1", ")", "&", ...
Returns the intersection of two lists. .. code-block:: jinja {% my_list = [1,2,3,4] -%} {{ set my_list | intersect([2, 4, 6]) }} will be rendered as: .. code-block:: text [2, 4]
[ "Returns", "the", "intersection", "of", "two", "lists", "." ]
python
train
aiidateam/aiida-codtools
aiida_codtools/parsers/cif_split_primitive.py
https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/parsers/cif_split_primitive.py#L18-L47
def parse_stdout(self, filelike): """Parse the content written by the script to standard out. The standard output will contain a list of relative filepaths where the generated CIF files have been written. :param filelike: filelike object of stdout :returns: an exit code in case of an error, None otherwise """ from aiida.orm import CifData content = filelike.read().strip() if not content: return self.exit_codes.ERROR_EMPTY_OUTPUT_FILE try: cifs = {} for line in content.split('\n'): filename = line.strip() output_name = os.path.splitext(os.path.basename(filename))[0] with self.retrieved.open(filename) as handle: cifs[output_name] = CifData(file=handle) except Exception: # pylint: disable=broad-except self.logger.exception('Failed to open a generated from the stdout file\n%s', traceback.format_exc()) return self.exit_codes.ERROR_PARSING_OUTPUT_DATA self.out('cifs', cifs) return
[ "def", "parse_stdout", "(", "self", ",", "filelike", ")", ":", "from", "aiida", ".", "orm", "import", "CifData", "content", "=", "filelike", ".", "read", "(", ")", ".", "strip", "(", ")", "if", "not", "content", ":", "return", "self", ".", "exit_codes"...
Parse the content written by the script to standard out. The standard output will contain a list of relative filepaths where the generated CIF files have been written. :param filelike: filelike object of stdout :returns: an exit code in case of an error, None otherwise
[ "Parse", "the", "content", "written", "by", "the", "script", "to", "standard", "out", "." ]
python
train
twisted/mantissa
xmantissa/people.py
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L2054-L2062
def getContactItems(self, person): """ Return an iterable of L{PhoneNumber} items that are associated with C{person}. @type person: L{Person} """ return person.store.query( PhoneNumber, PhoneNumber.person == person)
[ "def", "getContactItems", "(", "self", ",", "person", ")", ":", "return", "person", ".", "store", ".", "query", "(", "PhoneNumber", ",", "PhoneNumber", ".", "person", "==", "person", ")" ]
Return an iterable of L{PhoneNumber} items that are associated with C{person}. @type person: L{Person}
[ "Return", "an", "iterable", "of", "L", "{", "PhoneNumber", "}", "items", "that", "are", "associated", "with", "C", "{", "person", "}", "." ]
python
train
fboender/ansible-cmdb
lib/mako/codegen.py
https://github.com/fboender/ansible-cmdb/blob/ebd960ac10684e8c9ec2b12751bba2c4c9504ab7/lib/mako/codegen.py#L24-L66
def compile(node, uri, filename=None, default_filters=None, buffer_filters=None, imports=None, future_imports=None, source_encoding=None, generate_magic_comment=True, disable_unicode=False, strict_undefined=False, enable_loop=True, reserved_names=frozenset()): """Generate module source code given a parsetree node, uri, and optional source filename""" # if on Py2K, push the "source_encoding" string to be # a bytestring itself, as we will be embedding it into # the generated source and we don't want to coerce the # result into a unicode object, in "disable_unicode" mode if not compat.py3k and isinstance(source_encoding, compat.text_type): source_encoding = source_encoding.encode(source_encoding) buf = util.FastEncodingBuffer() printer = PythonPrinter(buf) _GenerateRenderMethod(printer, _CompileContext(uri, filename, default_filters, buffer_filters, imports, future_imports, source_encoding, generate_magic_comment, disable_unicode, strict_undefined, enable_loop, reserved_names), node) return buf.getvalue()
[ "def", "compile", "(", "node", ",", "uri", ",", "filename", "=", "None", ",", "default_filters", "=", "None", ",", "buffer_filters", "=", "None", ",", "imports", "=", "None", ",", "future_imports", "=", "None", ",", "source_encoding", "=", "None", ",", "...
Generate module source code given a parsetree node, uri, and optional source filename
[ "Generate", "module", "source", "code", "given", "a", "parsetree", "node", "uri", "and", "optional", "source", "filename" ]
python
train
bertrandvidal/parse_this
parse_this/core.py
https://github.com/bertrandvidal/parse_this/blob/aa2e3737f19642300ef1ca65cae21c90049718a2/parse_this/core.py#L302-L311
def _get_args_name_from_parser(parser): """Retrieve the name of the function argument linked to the given parser. Args: parser: a function parser """ # Retrieve the 'action' destination of the method parser i.e. its # argument name. The HelpAction is ignored. return [action.dest for action in parser._actions if not isinstance(action, argparse._HelpAction)]
[ "def", "_get_args_name_from_parser", "(", "parser", ")", ":", "# Retrieve the 'action' destination of the method parser i.e. its", "# argument name. The HelpAction is ignored.", "return", "[", "action", ".", "dest", "for", "action", "in", "parser", ".", "_actions", "if", "not...
Retrieve the name of the function argument linked to the given parser. Args: parser: a function parser
[ "Retrieve", "the", "name", "of", "the", "function", "argument", "linked", "to", "the", "given", "parser", "." ]
python
train