repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
Clinical-Genomics/trailblazer
trailblazer/mip/miplog.py
job_ids
def job_ids(log_stream): """Grep out all lines with scancel example.""" id_rows = [line for line in log_stream if 'scancel' in line] jobs = [id_row.strip()[-7:-1] for id_row in id_rows] return jobs
python
def job_ids(log_stream): """Grep out all lines with scancel example.""" id_rows = [line for line in log_stream if 'scancel' in line] jobs = [id_row.strip()[-7:-1] for id_row in id_rows] return jobs
[ "def", "job_ids", "(", "log_stream", ")", ":", "id_rows", "=", "[", "line", "for", "line", "in", "log_stream", "if", "'scancel'", "in", "line", "]", "jobs", "=", "[", "id_row", ".", "strip", "(", ")", "[", "-", "7", ":", "-", "1", "]", "for", "id...
Grep out all lines with scancel example.
[ "Grep", "out", "all", "lines", "with", "scancel", "example", "." ]
27f3cd21043a1077bd7029e85783459a50a7b798
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/miplog.py#L3-L7
train
49,800
ARMmbed/autoversion
src/auto_version/config.py
get_or_create_config
def get_or_create_config(path, config): """Using TOML format, load config from given path, or write out example based on defaults""" if os.path.isfile(path): with open(path) as fh: _LOG.debug("loading config from %s", os.path.abspath(path)) config._inflate(toml.load(fh)) else: try: os.makedirs(os.path.dirname(path)) except OSError: pass with open(path, "w") as fh: toml.dump(config._deflate(), fh)
python
def get_or_create_config(path, config): """Using TOML format, load config from given path, or write out example based on defaults""" if os.path.isfile(path): with open(path) as fh: _LOG.debug("loading config from %s", os.path.abspath(path)) config._inflate(toml.load(fh)) else: try: os.makedirs(os.path.dirname(path)) except OSError: pass with open(path, "w") as fh: toml.dump(config._deflate(), fh)
[ "def", "get_or_create_config", "(", "path", ",", "config", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "with", "open", "(", "path", ")", "as", "fh", ":", "_LOG", ".", "debug", "(", "\"loading config from %s\"", ",", "os", ...
Using TOML format, load config from given path, or write out example based on defaults
[ "Using", "TOML", "format", "load", "config", "from", "given", "path", "or", "write", "out", "example", "based", "on", "defaults" ]
c5b127d2059c8219f5637fe45bf9e1be3a0af2aa
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/config.py#L81-L93
train
49,801
ARMmbed/autoversion
src/auto_version/config.py
AutoVersionConfig._deflate
def _deflate(cls): """Prepare for serialisation - returns a dictionary""" data = {k: v for k, v in vars(cls).items() if not k.startswith("_")} return {Constants.CONFIG_KEY: data}
python
def _deflate(cls): """Prepare for serialisation - returns a dictionary""" data = {k: v for k, v in vars(cls).items() if not k.startswith("_")} return {Constants.CONFIG_KEY: data}
[ "def", "_deflate", "(", "cls", ")", ":", "data", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "vars", "(", "cls", ")", ".", "items", "(", ")", "if", "not", "k", ".", "startswith", "(", "\"_\"", ")", "}", "return", "{", "Constants", "....
Prepare for serialisation - returns a dictionary
[ "Prepare", "for", "serialisation", "-", "returns", "a", "dictionary" ]
c5b127d2059c8219f5637fe45bf9e1be3a0af2aa
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/config.py#L68-L71
train
49,802
ARMmbed/autoversion
src/auto_version/config.py
AutoVersionConfig._inflate
def _inflate(cls, data): """Update config by deserialising input dictionary""" for k, v in data[Constants.CONFIG_KEY].items(): setattr(cls, k, v) return cls._deflate()
python
def _inflate(cls, data): """Update config by deserialising input dictionary""" for k, v in data[Constants.CONFIG_KEY].items(): setattr(cls, k, v) return cls._deflate()
[ "def", "_inflate", "(", "cls", ",", "data", ")", ":", "for", "k", ",", "v", "in", "data", "[", "Constants", ".", "CONFIG_KEY", "]", ".", "items", "(", ")", ":", "setattr", "(", "cls", ",", "k", ",", "v", ")", "return", "cls", ".", "_deflate", "...
Update config by deserialising input dictionary
[ "Update", "config", "by", "deserialising", "input", "dictionary" ]
c5b127d2059c8219f5637fe45bf9e1be3a0af2aa
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/config.py#L74-L78
train
49,803
fudge-py/fudge
fudge/patcher.py
with_patched_object
def with_patched_object(obj, attr_name, patched_value): """Decorator that patches an object before the decorated method is called and restores it afterwards. This is a wrapper around :func:`fudge.patcher.patch_object` Example:: >>> from fudge import with_patched_object >>> class Session: ... state = 'clean' ... >>> @with_patched_object(Session, "state", "dirty") ... def test(): ... print Session.state ... >>> test() dirty >>> print Session.state clean """ def patcher(method): @wraps(method) def method_call(*m_args, **m_kw): patched_obj = patch_object(obj, attr_name, patched_value) try: return method(*m_args, **m_kw) finally: patched_obj.restore() return method_call return patcher
python
def with_patched_object(obj, attr_name, patched_value): """Decorator that patches an object before the decorated method is called and restores it afterwards. This is a wrapper around :func:`fudge.patcher.patch_object` Example:: >>> from fudge import with_patched_object >>> class Session: ... state = 'clean' ... >>> @with_patched_object(Session, "state", "dirty") ... def test(): ... print Session.state ... >>> test() dirty >>> print Session.state clean """ def patcher(method): @wraps(method) def method_call(*m_args, **m_kw): patched_obj = patch_object(obj, attr_name, patched_value) try: return method(*m_args, **m_kw) finally: patched_obj.restore() return method_call return patcher
[ "def", "with_patched_object", "(", "obj", ",", "attr_name", ",", "patched_value", ")", ":", "def", "patcher", "(", "method", ")", ":", "@", "wraps", "(", "method", ")", "def", "method_call", "(", "*", "m_args", ",", "*", "*", "m_kw", ")", ":", "patched...
Decorator that patches an object before the decorated method is called and restores it afterwards. This is a wrapper around :func:`fudge.patcher.patch_object` Example:: >>> from fudge import with_patched_object >>> class Session: ... state = 'clean' ... >>> @with_patched_object(Session, "state", "dirty") ... def test(): ... print Session.state ... >>> test() dirty >>> print Session.state clean
[ "Decorator", "that", "patches", "an", "object", "before", "the", "decorated", "method", "is", "called", "and", "restores", "it", "afterwards", "." ]
b283fbc1a41900f3f5845b10b8c2ef9136a67ebc
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/patcher.py#L136-L167
train
49,804
fudge-py/fudge
fudge/patcher.py
PatchHandler.patch
def patch(self, patched_value): """Set a new value for the attribute of the object.""" try: if self.getter: setattr(self.getter_class, self.attr_name, patched_value) else: setattr(self.orig_object, self.attr_name, patched_value) except TypeError: # Workaround for patching builtin objects: proxy_name = 'fudge_proxy_%s_%s_%s' % ( self.orig_object.__module__, self.orig_object.__name__, patched_value.__class__.__name__ ) self.proxy_object = type(proxy_name, (self.orig_object,), {self.attr_name: patched_value}) mod = sys.modules[self.orig_object.__module__] setattr(mod, self.orig_object.__name__, self.proxy_object)
python
def patch(self, patched_value): """Set a new value for the attribute of the object.""" try: if self.getter: setattr(self.getter_class, self.attr_name, patched_value) else: setattr(self.orig_object, self.attr_name, patched_value) except TypeError: # Workaround for patching builtin objects: proxy_name = 'fudge_proxy_%s_%s_%s' % ( self.orig_object.__module__, self.orig_object.__name__, patched_value.__class__.__name__ ) self.proxy_object = type(proxy_name, (self.orig_object,), {self.attr_name: patched_value}) mod = sys.modules[self.orig_object.__module__] setattr(mod, self.orig_object.__name__, self.proxy_object)
[ "def", "patch", "(", "self", ",", "patched_value", ")", ":", "try", ":", "if", "self", ".", "getter", ":", "setattr", "(", "self", ".", "getter_class", ",", "self", ".", "attr_name", ",", "patched_value", ")", "else", ":", "setattr", "(", "self", ".", ...
Set a new value for the attribute of the object.
[ "Set", "a", "new", "value", "for", "the", "attribute", "of", "the", "object", "." ]
b283fbc1a41900f3f5845b10b8c2ef9136a67ebc
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/patcher.py#L309-L326
train
49,805
fudge-py/fudge
fudge/patcher.py
PatchHandler.restore
def restore(self): """Restore the saved value for the attribute of the object.""" if self.proxy_object is None: if self.getter: setattr(self.getter_class, self.attr_name, self.getter) elif self.is_local: setattr(self.orig_object, self.attr_name, self.orig_value) else: # Was not a local, safe to delete: delattr(self.orig_object, self.attr_name) else: setattr(sys.modules[self.orig_object.__module__], self.orig_object.__name__, self.orig_object)
python
def restore(self): """Restore the saved value for the attribute of the object.""" if self.proxy_object is None: if self.getter: setattr(self.getter_class, self.attr_name, self.getter) elif self.is_local: setattr(self.orig_object, self.attr_name, self.orig_value) else: # Was not a local, safe to delete: delattr(self.orig_object, self.attr_name) else: setattr(sys.modules[self.orig_object.__module__], self.orig_object.__name__, self.orig_object)
[ "def", "restore", "(", "self", ")", ":", "if", "self", ".", "proxy_object", "is", "None", ":", "if", "self", ".", "getter", ":", "setattr", "(", "self", ".", "getter_class", ",", "self", ".", "attr_name", ",", "self", ".", "getter", ")", "elif", "sel...
Restore the saved value for the attribute of the object.
[ "Restore", "the", "saved", "value", "for", "the", "attribute", "of", "the", "object", "." ]
b283fbc1a41900f3f5845b10b8c2ef9136a67ebc
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/patcher.py#L328-L341
train
49,806
Clinical-Genomics/trailblazer
trailblazer/mip/files.py
parse_config
def parse_config(data: dict) -> dict: """Parse MIP config file. Args: data (dict): raw YAML input from MIP analysis config file Returns: dict: parsed data """ return { 'email': data.get('email'), 'family': data['family_id'], 'samples': [{ 'id': sample_id, 'type': analysis_type, } for sample_id, analysis_type in data['analysis_type'].items()], 'config_path': data['config_file_analysis'], 'is_dryrun': True if 'dry_run_all' in data else False, 'log_path': data['log_file'], 'out_dir': data['outdata_dir'], 'priority': data['slurm_quality_of_service'], 'sampleinfo_path': data['sample_info_file'], }
python
def parse_config(data: dict) -> dict: """Parse MIP config file. Args: data (dict): raw YAML input from MIP analysis config file Returns: dict: parsed data """ return { 'email': data.get('email'), 'family': data['family_id'], 'samples': [{ 'id': sample_id, 'type': analysis_type, } for sample_id, analysis_type in data['analysis_type'].items()], 'config_path': data['config_file_analysis'], 'is_dryrun': True if 'dry_run_all' in data else False, 'log_path': data['log_file'], 'out_dir': data['outdata_dir'], 'priority': data['slurm_quality_of_service'], 'sampleinfo_path': data['sample_info_file'], }
[ "def", "parse_config", "(", "data", ":", "dict", ")", "->", "dict", ":", "return", "{", "'email'", ":", "data", ".", "get", "(", "'email'", ")", ",", "'family'", ":", "data", "[", "'family_id'", "]", ",", "'samples'", ":", "[", "{", "'id'", ":", "s...
Parse MIP config file. Args: data (dict): raw YAML input from MIP analysis config file Returns: dict: parsed data
[ "Parse", "MIP", "config", "file", "." ]
27f3cd21043a1077bd7029e85783459a50a7b798
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/files.py#L9-L31
train
49,807
Clinical-Genomics/trailblazer
trailblazer/mip/files.py
parse_sampleinfo
def parse_sampleinfo(data: dict) -> dict: """Parse MIP sample info file. Args: data (dict): raw YAML input from MIP qc sample info file Returns: dict: parsed data """ genome_build = data['human_genome_build'] genome_build_str = f"{genome_build['source']}{genome_build['version']}" if 'svdb' in data['program']: svdb_outpath = (f"{data['program']['svdb']['path']}") else: svdb_outpath = '' outdata = { 'date': data['analysis_date'], 'family': data['family'], 'genome_build': genome_build_str, 'rank_model_version': data['program']['genmod']['rank_model']['version'], 'is_finished': True if data['analysisrunstatus'] == 'finished' else False, 'pedigree_path': data['pedigree_minimal'], 'peddy': { 'ped': (data['program']['peddy']['peddy']['path'] if 'peddy' in data['program'] else None), 'ped_check': (data['program']['peddy']['ped_check']['path'] if 'peddy' in data['program'] else None), 'sex_check': (data['program']['peddy']['sex_check']['path'] if 'peddy' in data['program'] else None), }, 'qcmetrics_path': data['program']['qccollect']['path'], 'samples': [], 'snv': { 'bcf': data['most_complete_bcf']['path'], 'clinical_vcf': data['vcf_binary_file']['clinical']['path'], 'gbcf': data['gbcf_file']['path'], 'research_vcf': data['vcf_binary_file']['research']['path'], }, 'svdb_outpath': svdb_outpath, 'sv': { 'bcf': data.get('sv_bcf_file', {}).get('path'), 'clinical_vcf': (data['sv_vcf_binary_file']['clinical']['path'] if 'sv_vcf_binary_file' in data else None), 'merged': svdb_outpath, 'research_vcf': (data['sv_vcf_binary_file']['research']['path'] if 'sv_vcf_binary_file' in data else None), }, 'version': data['mip_version'], } for sample_id, sample_data in data['sample'].items(): sample = { 'id': sample_id, 'bam': sample_data['most_complete_bam']['path'], 'sambamba': list(sample_data['program']['sambamba_depth'].values())[0]['path'], 'sex': sample_data['sex'], # subsample mt is only for wgs data 'subsample_mt': (list(sample_data['program']['samtools_subsample_mt'].values())[0]['path'] if 'samtools_subsample_mt' in sample_data['program'] else None), 'vcf2cytosure': list(sample_data['program']['vcf2cytosure'].values())[0]['path'], } chanjo_sexcheck = list(sample_data['program']['chanjo_sexcheck'].values())[0] sample['chanjo_sexcheck'] = chanjo_sexcheck['path'] outdata['samples'].append(sample) return outdata
python
def parse_sampleinfo(data: dict) -> dict: """Parse MIP sample info file. Args: data (dict): raw YAML input from MIP qc sample info file Returns: dict: parsed data """ genome_build = data['human_genome_build'] genome_build_str = f"{genome_build['source']}{genome_build['version']}" if 'svdb' in data['program']: svdb_outpath = (f"{data['program']['svdb']['path']}") else: svdb_outpath = '' outdata = { 'date': data['analysis_date'], 'family': data['family'], 'genome_build': genome_build_str, 'rank_model_version': data['program']['genmod']['rank_model']['version'], 'is_finished': True if data['analysisrunstatus'] == 'finished' else False, 'pedigree_path': data['pedigree_minimal'], 'peddy': { 'ped': (data['program']['peddy']['peddy']['path'] if 'peddy' in data['program'] else None), 'ped_check': (data['program']['peddy']['ped_check']['path'] if 'peddy' in data['program'] else None), 'sex_check': (data['program']['peddy']['sex_check']['path'] if 'peddy' in data['program'] else None), }, 'qcmetrics_path': data['program']['qccollect']['path'], 'samples': [], 'snv': { 'bcf': data['most_complete_bcf']['path'], 'clinical_vcf': data['vcf_binary_file']['clinical']['path'], 'gbcf': data['gbcf_file']['path'], 'research_vcf': data['vcf_binary_file']['research']['path'], }, 'svdb_outpath': svdb_outpath, 'sv': { 'bcf': data.get('sv_bcf_file', {}).get('path'), 'clinical_vcf': (data['sv_vcf_binary_file']['clinical']['path'] if 'sv_vcf_binary_file' in data else None), 'merged': svdb_outpath, 'research_vcf': (data['sv_vcf_binary_file']['research']['path'] if 'sv_vcf_binary_file' in data else None), }, 'version': data['mip_version'], } for sample_id, sample_data in data['sample'].items(): sample = { 'id': sample_id, 'bam': sample_data['most_complete_bam']['path'], 'sambamba': list(sample_data['program']['sambamba_depth'].values())[0]['path'], 'sex': sample_data['sex'], # subsample mt is only for wgs data 'subsample_mt': (list(sample_data['program']['samtools_subsample_mt'].values())[0]['path'] if 'samtools_subsample_mt' in sample_data['program'] else None), 'vcf2cytosure': list(sample_data['program']['vcf2cytosure'].values())[0]['path'], } chanjo_sexcheck = list(sample_data['program']['chanjo_sexcheck'].values())[0] sample['chanjo_sexcheck'] = chanjo_sexcheck['path'] outdata['samples'].append(sample) return outdata
[ "def", "parse_sampleinfo", "(", "data", ":", "dict", ")", "->", "dict", ":", "genome_build", "=", "data", "[", "'human_genome_build'", "]", "genome_build_str", "=", "f\"{genome_build['source']}{genome_build['version']}\"", "if", "'svdb'", "in", "data", "[", "'program'...
Parse MIP sample info file. Args: data (dict): raw YAML input from MIP qc sample info file Returns: dict: parsed data
[ "Parse", "MIP", "sample", "info", "file", "." ]
27f3cd21043a1077bd7029e85783459a50a7b798
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/files.py#L34-L100
train
49,808
Clinical-Genomics/trailblazer
trailblazer/mip/files.py
parse_peddy_sexcheck
def parse_peddy_sexcheck(handle: TextIO): """Parse Peddy sexcheck output.""" data = {} samples = csv.DictReader(handle) for sample in samples: data[sample['sample_id']] = { 'predicted_sex': sample['predicted_sex'], 'het_ratio': float(sample['het_ratio']), 'error': True if sample['error'] == 'True' else False, } return data
python
def parse_peddy_sexcheck(handle: TextIO): """Parse Peddy sexcheck output.""" data = {} samples = csv.DictReader(handle) for sample in samples: data[sample['sample_id']] = { 'predicted_sex': sample['predicted_sex'], 'het_ratio': float(sample['het_ratio']), 'error': True if sample['error'] == 'True' else False, } return data
[ "def", "parse_peddy_sexcheck", "(", "handle", ":", "TextIO", ")", ":", "data", "=", "{", "}", "samples", "=", "csv", ".", "DictReader", "(", "handle", ")", "for", "sample", "in", "samples", ":", "data", "[", "sample", "[", "'sample_id'", "]", "]", "=",...
Parse Peddy sexcheck output.
[ "Parse", "Peddy", "sexcheck", "output", "." ]
27f3cd21043a1077bd7029e85783459a50a7b798
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/files.py#L171-L181
train
49,809
Clinical-Genomics/trailblazer
trailblazer/mip/files.py
parse_chanjo_sexcheck
def parse_chanjo_sexcheck(handle: TextIO): """Parse Chanjo sex-check output.""" samples = csv.DictReader(handle, delimiter='\t') for sample in samples: return { 'predicted_sex': sample['sex'], 'x_coverage': float(sample['#X_coverage']), 'y_coverage': float(sample['Y_coverage']), }
python
def parse_chanjo_sexcheck(handle: TextIO): """Parse Chanjo sex-check output.""" samples = csv.DictReader(handle, delimiter='\t') for sample in samples: return { 'predicted_sex': sample['sex'], 'x_coverage': float(sample['#X_coverage']), 'y_coverage': float(sample['Y_coverage']), }
[ "def", "parse_chanjo_sexcheck", "(", "handle", ":", "TextIO", ")", ":", "samples", "=", "csv", ".", "DictReader", "(", "handle", ",", "delimiter", "=", "'\\t'", ")", "for", "sample", "in", "samples", ":", "return", "{", "'predicted_sex'", ":", "sample", "[...
Parse Chanjo sex-check output.
[ "Parse", "Chanjo", "sex", "-", "check", "output", "." ]
27f3cd21043a1077bd7029e85783459a50a7b798
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/files.py#L184-L192
train
49,810
ARMmbed/autoversion
src/auto_version/cli.py
get_cli
def get_cli(): """Load cli options""" parser = argparse.ArgumentParser( prog="auto_version", description="auto version v%s: a tool to control version numbers" % __version__, ) parser.add_argument( "--target", action="append", default=[], help="Files containing version info. " "Assumes unique variable names between files. (default: %s)." % (config.targets,), ) parser.add_argument( "--bump", choices=SemVerSigFig, help="Bumps the specified part of SemVer string. " "Use this locally to correctly modify the version file.", ) parser.add_argument( "--news", "--file-triggers", action="store_true", dest="file_triggers", help="Detects need to bump based on presence of files (as specified in config).", ) parser.add_argument( "--set", help="Set the SemVer string. Use this locally to set the project version explicitly.", ) parser.add_argument( "--set-patch-count", action="store_true", help="Sets the patch number to the commit count.", ) parser.add_argument( "--lock", action="store_true", help="Locks the SemVer string. " "Lock will remain for another call to autoversion before being cleared.", ) parser.add_argument( "--release", action="store_true", default=False, help="Marks as a release build, which flags the build as released.", ) parser.add_argument( "--version", action="store_true", default=False, help="Prints the version of auto_version itself (self-version).", ) parser.add_argument("--config", help="Configuration file path.") parser.add_argument( "-v", "--verbosity", action="count", default=0, help="increase output verbosity. " "can be specified multiple times", ) return parser.parse_known_args()
python
def get_cli(): """Load cli options""" parser = argparse.ArgumentParser( prog="auto_version", description="auto version v%s: a tool to control version numbers" % __version__, ) parser.add_argument( "--target", action="append", default=[], help="Files containing version info. " "Assumes unique variable names between files. (default: %s)." % (config.targets,), ) parser.add_argument( "--bump", choices=SemVerSigFig, help="Bumps the specified part of SemVer string. " "Use this locally to correctly modify the version file.", ) parser.add_argument( "--news", "--file-triggers", action="store_true", dest="file_triggers", help="Detects need to bump based on presence of files (as specified in config).", ) parser.add_argument( "--set", help="Set the SemVer string. Use this locally to set the project version explicitly.", ) parser.add_argument( "--set-patch-count", action="store_true", help="Sets the patch number to the commit count.", ) parser.add_argument( "--lock", action="store_true", help="Locks the SemVer string. " "Lock will remain for another call to autoversion before being cleared.", ) parser.add_argument( "--release", action="store_true", default=False, help="Marks as a release build, which flags the build as released.", ) parser.add_argument( "--version", action="store_true", default=False, help="Prints the version of auto_version itself (self-version).", ) parser.add_argument("--config", help="Configuration file path.") parser.add_argument( "-v", "--verbosity", action="count", default=0, help="increase output verbosity. " "can be specified multiple times", ) return parser.parse_known_args()
[ "def", "get_cli", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "\"auto_version\"", ",", "description", "=", "\"auto version v%s: a tool to control version numbers\"", "%", "__version__", ",", ")", "parser", ".", "add_argument", ...
Load cli options
[ "Load", "cli", "options" ]
c5b127d2059c8219f5637fe45bf9e1be3a0af2aa
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/cli.py#L9-L71
train
49,811
bskinn/stdio-mgr
src/stdio_mgr/stdio_mgr.py
stdio_mgr
def stdio_mgr(in_str=""): r"""Subsitute temporary text buffers for `stdio` in a managed context. Context manager. Substitutes empty :cls:`~io.StringIO`\ s for :cls:`sys.stdout` and :cls:`sys.stderr`, and a :cls:`TeeStdin` for :cls:`sys.stdin` within the managed context. Upon exiting the context, the original stream objects are restored within :mod:`sys`, and the temporary streams are closed. Parameters ---------- in_str |str| *(optional)* -- Initialization text for the :cls:`TeeStdin` substitution for `stdin`. Default is an empty string. Yields ------ in_ :cls:`TeeStdin` -- Temporary stream for `stdin`. out_ :cls:`~io.StringIO` -- Temporary stream for `stdout`, initially empty. err_ :cls:`~io.StringIO` -- Temporary stream for `stderr`, initially empty. """ old_stdin = sys.stdin old_stdout = sys.stdout old_stderr = sys.stderr new_stdout = StringIO() new_stderr = StringIO() new_stdin = TeeStdin(new_stdout, in_str) sys.stdin = new_stdin sys.stdout = new_stdout sys.stderr = new_stderr yield new_stdin, new_stdout, new_stderr sys.stdin = old_stdin sys.stdout = old_stdout sys.stderr = old_stderr new_stdin.close() new_stdout.close() new_stderr.close()
python
def stdio_mgr(in_str=""): r"""Subsitute temporary text buffers for `stdio` in a managed context. Context manager. Substitutes empty :cls:`~io.StringIO`\ s for :cls:`sys.stdout` and :cls:`sys.stderr`, and a :cls:`TeeStdin` for :cls:`sys.stdin` within the managed context. Upon exiting the context, the original stream objects are restored within :mod:`sys`, and the temporary streams are closed. Parameters ---------- in_str |str| *(optional)* -- Initialization text for the :cls:`TeeStdin` substitution for `stdin`. Default is an empty string. Yields ------ in_ :cls:`TeeStdin` -- Temporary stream for `stdin`. out_ :cls:`~io.StringIO` -- Temporary stream for `stdout`, initially empty. err_ :cls:`~io.StringIO` -- Temporary stream for `stderr`, initially empty. """ old_stdin = sys.stdin old_stdout = sys.stdout old_stderr = sys.stderr new_stdout = StringIO() new_stderr = StringIO() new_stdin = TeeStdin(new_stdout, in_str) sys.stdin = new_stdin sys.stdout = new_stdout sys.stderr = new_stderr yield new_stdin, new_stdout, new_stderr sys.stdin = old_stdin sys.stdout = old_stdout sys.stderr = old_stderr new_stdin.close() new_stdout.close() new_stderr.close()
[ "def", "stdio_mgr", "(", "in_str", "=", "\"\"", ")", ":", "old_stdin", "=", "sys", ".", "stdin", "old_stdout", "=", "sys", ".", "stdout", "old_stderr", "=", "sys", ".", "stderr", "new_stdout", "=", "StringIO", "(", ")", "new_stderr", "=", "StringIO", "("...
r"""Subsitute temporary text buffers for `stdio` in a managed context. Context manager. Substitutes empty :cls:`~io.StringIO`\ s for :cls:`sys.stdout` and :cls:`sys.stderr`, and a :cls:`TeeStdin` for :cls:`sys.stdin` within the managed context. Upon exiting the context, the original stream objects are restored within :mod:`sys`, and the temporary streams are closed. Parameters ---------- in_str |str| *(optional)* -- Initialization text for the :cls:`TeeStdin` substitution for `stdin`. Default is an empty string. Yields ------ in_ :cls:`TeeStdin` -- Temporary stream for `stdin`. out_ :cls:`~io.StringIO` -- Temporary stream for `stdout`, initially empty. err_ :cls:`~io.StringIO` -- Temporary stream for `stderr`, initially empty.
[ "r", "Subsitute", "temporary", "text", "buffers", "for", "stdio", "in", "a", "managed", "context", "." ]
dff9f326528aac67d7ca0dc0a86ce3dffa3e0d39
https://github.com/bskinn/stdio-mgr/blob/dff9f326528aac67d7ca0dc0a86ce3dffa3e0d39/src/stdio_mgr/stdio_mgr.py#L139-L196
train
49,812
andrewda/frc-livescore
livescore/simpleocr_utils/opencv_utils.py
draw_segments
def draw_segments(image, segments, color=(255, 0, 0), line_width=1): """draws segments on image""" for segment in segments: x, y, w, h = segment cv2.rectangle(image, (x, y), (x + w, y + h), color, line_width)
python
def draw_segments(image, segments, color=(255, 0, 0), line_width=1): """draws segments on image""" for segment in segments: x, y, w, h = segment cv2.rectangle(image, (x, y), (x + w, y + h), color, line_width)
[ "def", "draw_segments", "(", "image", ",", "segments", ",", "color", "=", "(", "255", ",", "0", ",", "0", ")", ",", "line_width", "=", "1", ")", ":", "for", "segment", "in", "segments", ":", "x", ",", "y", ",", "w", ",", "h", "=", "segment", "c...
draws segments on image
[ "draws", "segments", "on", "image" ]
71594cd6d2c8b6c5feb3889bb05552d09b8128b1
https://github.com/andrewda/frc-livescore/blob/71594cd6d2c8b6c5feb3889bb05552d09b8128b1/livescore/simpleocr_utils/opencv_utils.py#L105-L109
train
49,813
andrewda/frc-livescore
livescore/simpleocr_utils/opencv_utils.py
draw_lines
def draw_lines(image, ys, color=(255, 0, 0), line_width=1): """draws horizontal lines""" for y in ys: cv2.line(image, (0, y), (image.shape[1], y), color, line_width)
python
def draw_lines(image, ys, color=(255, 0, 0), line_width=1): """draws horizontal lines""" for y in ys: cv2.line(image, (0, y), (image.shape[1], y), color, line_width)
[ "def", "draw_lines", "(", "image", ",", "ys", ",", "color", "=", "(", "255", ",", "0", ",", "0", ")", ",", "line_width", "=", "1", ")", ":", "for", "y", "in", "ys", ":", "cv2", ".", "line", "(", "image", ",", "(", "0", ",", "y", ")", ",", ...
draws horizontal lines
[ "draws", "horizontal", "lines" ]
71594cd6d2c8b6c5feb3889bb05552d09b8128b1
https://github.com/andrewda/frc-livescore/blob/71594cd6d2c8b6c5feb3889bb05552d09b8128b1/livescore/simpleocr_utils/opencv_utils.py#L112-L115
train
49,814
Clinical-Genomics/trailblazer
trailblazer/mip/sacct.py
time_to_sec
def time_to_sec(time_str: str) -> int: """Convert time in string format to seconds. Skipping seconds since sometimes the last column is truncated for entries where >10 days. """ total_sec = 0 if '-' in time_str: # parse out days days, time_str = time_str.split('-') total_sec += (int(days) * 24 * 60 * 60) # parse out the hours and mins (skip seconds) hours_min_raw = time_str.split(':')[:-1] time_parts = [int(round(float(val))) for val in hours_min_raw] total_sec += time_parts[-1] * 60 # minutes if len(time_parts) > 1: total_sec += time_parts[-2] * 60 * 60 # hours return total_sec
python
def time_to_sec(time_str: str) -> int: """Convert time in string format to seconds. Skipping seconds since sometimes the last column is truncated for entries where >10 days. """ total_sec = 0 if '-' in time_str: # parse out days days, time_str = time_str.split('-') total_sec += (int(days) * 24 * 60 * 60) # parse out the hours and mins (skip seconds) hours_min_raw = time_str.split(':')[:-1] time_parts = [int(round(float(val))) for val in hours_min_raw] total_sec += time_parts[-1] * 60 # minutes if len(time_parts) > 1: total_sec += time_parts[-2] * 60 * 60 # hours return total_sec
[ "def", "time_to_sec", "(", "time_str", ":", "str", ")", "->", "int", ":", "total_sec", "=", "0", "if", "'-'", "in", "time_str", ":", "# parse out days", "days", ",", "time_str", "=", "time_str", ".", "split", "(", "'-'", ")", "total_sec", "+=", "(", "i...
Convert time in string format to seconds. Skipping seconds since sometimes the last column is truncated for entries where >10 days.
[ "Convert", "time", "in", "string", "format", "to", "seconds", "." ]
27f3cd21043a1077bd7029e85783459a50a7b798
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/sacct.py#L9-L27
train
49,815
Clinical-Genomics/trailblazer
trailblazer/mip/sacct.py
convert_job
def convert_job(row: list) -> dict: """Convert sacct row to dict.""" state = row[-2] start_time_raw = row[-4] end_time_raw = row[-3] if state not in ('PENDING', 'CANCELLED'): start_time = datetime.strptime(start_time_raw, '%Y-%m-%dT%H:%M:%S') if state != 'RUNNING': end_time = datetime.strptime(end_time_raw, '%Y-%m-%dT%H:%M:%S') else: end_time = None else: start_time = end_time = None # parse name of job job_name = row[1] step_name, step_context = job_name.rstrip('_BOTH').rstrip('_SV').rsplit('_', 1) return { 'id': int(row[0]), 'name': job_name, 'step': step_name, 'context': step_context, 'state': state, 'start': start_time, 'end': end_time, 'elapsed': time_to_sec(row[-5]), 'cpu': time_to_sec(row[-6]), 'is_completed': state == 'COMPLETED', }
python
def convert_job(row: list) -> dict: """Convert sacct row to dict.""" state = row[-2] start_time_raw = row[-4] end_time_raw = row[-3] if state not in ('PENDING', 'CANCELLED'): start_time = datetime.strptime(start_time_raw, '%Y-%m-%dT%H:%M:%S') if state != 'RUNNING': end_time = datetime.strptime(end_time_raw, '%Y-%m-%dT%H:%M:%S') else: end_time = None else: start_time = end_time = None # parse name of job job_name = row[1] step_name, step_context = job_name.rstrip('_BOTH').rstrip('_SV').rsplit('_', 1) return { 'id': int(row[0]), 'name': job_name, 'step': step_name, 'context': step_context, 'state': state, 'start': start_time, 'end': end_time, 'elapsed': time_to_sec(row[-5]), 'cpu': time_to_sec(row[-6]), 'is_completed': state == 'COMPLETED', }
[ "def", "convert_job", "(", "row", ":", "list", ")", "->", "dict", ":", "state", "=", "row", "[", "-", "2", "]", "start_time_raw", "=", "row", "[", "-", "4", "]", "end_time_raw", "=", "row", "[", "-", "3", "]", "if", "state", "not", "in", "(", "...
Convert sacct row to dict.
[ "Convert", "sacct", "row", "to", "dict", "." ]
27f3cd21043a1077bd7029e85783459a50a7b798
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/sacct.py#L30-L59
train
49,816
Clinical-Genomics/trailblazer
trailblazer/mip/sacct.py
parse_sacct
def parse_sacct(sacct_stream): """Parse out information from sacct status output.""" rows = (line.split() for line in sacct_stream) # filter rows that begin with a SLURM job id relevant_rows = (row for row in rows if row[0].isdigit()) jobs = [convert_job(row) for row in relevant_rows] return jobs
python
def parse_sacct(sacct_stream): """Parse out information from sacct status output.""" rows = (line.split() for line in sacct_stream) # filter rows that begin with a SLURM job id relevant_rows = (row for row in rows if row[0].isdigit()) jobs = [convert_job(row) for row in relevant_rows] return jobs
[ "def", "parse_sacct", "(", "sacct_stream", ")", ":", "rows", "=", "(", "line", ".", "split", "(", ")", "for", "line", "in", "sacct_stream", ")", "# filter rows that begin with a SLURM job id", "relevant_rows", "=", "(", "row", "for", "row", "in", "rows", "if",...
Parse out information from sacct status output.
[ "Parse", "out", "information", "from", "sacct", "status", "output", "." ]
27f3cd21043a1077bd7029e85783459a50a7b798
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/sacct.py#L62-L68
train
49,817
Clinical-Genomics/trailblazer
trailblazer/mip/sacct.py
filter_jobs
def filter_jobs(sacct_jobs, failed=True): """Filter jobs that have a FAILED etc. status.""" categories = FAILED_CATEGORIES if failed else NORMAL_CATEGORIES filtered_jobs = [job for job in sacct_jobs if job['state'] in categories] return filtered_jobs
python
def filter_jobs(sacct_jobs, failed=True): """Filter jobs that have a FAILED etc. status.""" categories = FAILED_CATEGORIES if failed else NORMAL_CATEGORIES filtered_jobs = [job for job in sacct_jobs if job['state'] in categories] return filtered_jobs
[ "def", "filter_jobs", "(", "sacct_jobs", ",", "failed", "=", "True", ")", ":", "categories", "=", "FAILED_CATEGORIES", "if", "failed", "else", "NORMAL_CATEGORIES", "filtered_jobs", "=", "[", "job", "for", "job", "in", "sacct_jobs", "if", "job", "[", "'state'",...
Filter jobs that have a FAILED etc. status.
[ "Filter", "jobs", "that", "have", "a", "FAILED", "etc", ".", "status", "." ]
27f3cd21043a1077bd7029e85783459a50a7b798
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/sacct.py#L71-L75
train
49,818
andrewda/frc-livescore
livescore/simpleocr_utils/segmentation_aux.py
guess_segments_lines
def guess_segments_lines(segments, lines, nearline_tolerance=5.0): """ given segments, outputs a array of line numbers, or -1 if it doesn't belong to any """ ys = segments[:, 1] closeness = numpy.abs(numpy.subtract.outer(ys, lines)) # each row a y, each collumn a distance to each line line_of_y = numpy.argmin(closeness, axis=1) distance = numpy.min(closeness, axis=1) bad = distance > numpy.mean(distance) + nearline_tolerance * numpy.std(distance) line_of_y[bad] = -1 return line_of_y
python
def guess_segments_lines(segments, lines, nearline_tolerance=5.0): """ given segments, outputs a array of line numbers, or -1 if it doesn't belong to any """ ys = segments[:, 1] closeness = numpy.abs(numpy.subtract.outer(ys, lines)) # each row a y, each collumn a distance to each line line_of_y = numpy.argmin(closeness, axis=1) distance = numpy.min(closeness, axis=1) bad = distance > numpy.mean(distance) + nearline_tolerance * numpy.std(distance) line_of_y[bad] = -1 return line_of_y
[ "def", "guess_segments_lines", "(", "segments", ",", "lines", ",", "nearline_tolerance", "=", "5.0", ")", ":", "ys", "=", "segments", "[", ":", ",", "1", "]", "closeness", "=", "numpy", ".", "abs", "(", "numpy", ".", "subtract", ".", "outer", "(", "ys"...
given segments, outputs a array of line numbers, or -1 if it doesn't belong to any
[ "given", "segments", "outputs", "a", "array", "of", "line", "numbers", "or", "-", "1", "if", "it", "doesn", "t", "belong", "to", "any" ]
71594cd6d2c8b6c5feb3889bb05552d09b8128b1
https://github.com/andrewda/frc-livescore/blob/71594cd6d2c8b6c5feb3889bb05552d09b8128b1/livescore/simpleocr_utils/segmentation_aux.py#L88-L99
train
49,819
andrewda/frc-livescore
livescore/simpleocr_utils/segmentation_aux.py
SegmentOrderer._process
def _process(self, segments): """sort segments in read order - left to right, up to down""" # sort_f= lambda r: max_line_width*(r[1]/max_line_height)+r[0] # segments= sorted(segments, key=sort_f) # segments= segments_to_numpy( segments ) # return segments mlh, mlw = self.max_line_height, self.max_line_width s = segments.astype(numpy.uint32) # prevent overflows order = mlw * (s[:, 1] // mlh) + s[:, 0] sort_order = numpy.argsort(order) return segments[sort_order]
python
def _process(self, segments): """sort segments in read order - left to right, up to down""" # sort_f= lambda r: max_line_width*(r[1]/max_line_height)+r[0] # segments= sorted(segments, key=sort_f) # segments= segments_to_numpy( segments ) # return segments mlh, mlw = self.max_line_height, self.max_line_width s = segments.astype(numpy.uint32) # prevent overflows order = mlw * (s[:, 1] // mlh) + s[:, 0] sort_order = numpy.argsort(order) return segments[sort_order]
[ "def", "_process", "(", "self", ",", "segments", ")", ":", "# sort_f= lambda r: max_line_width*(r[1]/max_line_height)+r[0]", "# segments= sorted(segments, key=sort_f)", "# segments= segments_to_numpy( segments )", "# return segments", "mlh", ",", "mlw", "=", "self", ".", "max_lin...
sort segments in read order - left to right, up to down
[ "sort", "segments", "in", "read", "order", "-", "left", "to", "right", "up", "to", "down" ]
71594cd6d2c8b6c5feb3889bb05552d09b8128b1
https://github.com/andrewda/frc-livescore/blob/71594cd6d2c8b6c5feb3889bb05552d09b8128b1/livescore/simpleocr_utils/segmentation_aux.py#L11-L21
train
49,820
andrewda/frc-livescore
livescore/simpleocr_utils/segmentation_aux.py
LineFinder._guess_lines
def _guess_lines(ys, max_lines=50, confidence_minimum=0.0): """guesses and returns text inter-line distance, number of lines, y_position of first line""" ys = ys.astype(numpy.float32) compactness_list, means_list, diffs, deviations = [], [], [], [] start_n = 1 for k in range(start_n, min(len(ys), max_lines)): compactness, classified_points, means = cv2.kmeans(data=ys, K=k, bestLabels=None, criteria=( cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_MAX_ITER, 1, 10), attempts=2, flags=cv2.KMEANS_PP_CENTERS) means = numpy.sort(means, axis=0) means_list.append(means) compactness_list.append(compactness) if k < 3: tmp1 = [1, 2, 500, 550] # forge data for bad clusters else: # calculate the center of each cluster. Assuming lines are equally spaced... tmp1 = numpy.diff(means, axis=0) # diff will be equal or very similar tmp2 = numpy.std(tmp1) / numpy.mean(means) # so variance is minimal tmp3 = numpy.sum((tmp1 - numpy.mean(tmp1)) ** 2) # root mean square deviation, more sensitive than std diffs.append(tmp1) deviations.append(tmp3) compactness_list = numpy.diff( numpy.log(numpy.array(compactness_list) + 0.01)) # sum small amount to avoid log(0) deviations = numpy.array(deviations[1:]) deviations[0] = numpy.mean(deviations[1:]) compactness_list = (compactness_list - numpy.mean(compactness_list)) / numpy.std(compactness_list) deviations = (deviations - numpy.mean(deviations)) / numpy.std(deviations) aglomerated_metric = 0.1 * compactness_list + 0.9 * deviations i = numpy.argmin(aglomerated_metric) + 1 lines = means_list[i] # calculate confidence betterness = numpy.sort(aglomerated_metric, axis=0) confidence = (betterness[1] - betterness[0]) / (betterness[2] - betterness[1]) if confidence < confidence_minimum: raise Exception("low confidence") return lines
python
def _guess_lines(ys, max_lines=50, confidence_minimum=0.0): """guesses and returns text inter-line distance, number of lines, y_position of first line""" ys = ys.astype(numpy.float32) compactness_list, means_list, diffs, deviations = [], [], [], [] start_n = 1 for k in range(start_n, min(len(ys), max_lines)): compactness, classified_points, means = cv2.kmeans(data=ys, K=k, bestLabels=None, criteria=( cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_MAX_ITER, 1, 10), attempts=2, flags=cv2.KMEANS_PP_CENTERS) means = numpy.sort(means, axis=0) means_list.append(means) compactness_list.append(compactness) if k < 3: tmp1 = [1, 2, 500, 550] # forge data for bad clusters else: # calculate the center of each cluster. Assuming lines are equally spaced... tmp1 = numpy.diff(means, axis=0) # diff will be equal or very similar tmp2 = numpy.std(tmp1) / numpy.mean(means) # so variance is minimal tmp3 = numpy.sum((tmp1 - numpy.mean(tmp1)) ** 2) # root mean square deviation, more sensitive than std diffs.append(tmp1) deviations.append(tmp3) compactness_list = numpy.diff( numpy.log(numpy.array(compactness_list) + 0.01)) # sum small amount to avoid log(0) deviations = numpy.array(deviations[1:]) deviations[0] = numpy.mean(deviations[1:]) compactness_list = (compactness_list - numpy.mean(compactness_list)) / numpy.std(compactness_list) deviations = (deviations - numpy.mean(deviations)) / numpy.std(deviations) aglomerated_metric = 0.1 * compactness_list + 0.9 * deviations i = numpy.argmin(aglomerated_metric) + 1 lines = means_list[i] # calculate confidence betterness = numpy.sort(aglomerated_metric, axis=0) confidence = (betterness[1] - betterness[0]) / (betterness[2] - betterness[1]) if confidence < confidence_minimum: raise Exception("low confidence") return lines
[ "def", "_guess_lines", "(", "ys", ",", "max_lines", "=", "50", ",", "confidence_minimum", "=", "0.0", ")", ":", "ys", "=", "ys", ".", "astype", "(", "numpy", ".", "float32", ")", "compactness_list", ",", "means_list", ",", "diffs", ",", "deviations", "="...
guesses and returns text inter-line distance, number of lines, y_position of first line
[ "guesses", "and", "returns", "text", "inter", "-", "line", "distance", "number", "of", "lines", "y_position", "of", "first", "line" ]
71594cd6d2c8b6c5feb3889bb05552d09b8128b1
https://github.com/andrewda/frc-livescore/blob/71594cd6d2c8b6c5feb3889bb05552d09b8128b1/livescore/simpleocr_utils/segmentation_aux.py#L26-L63
train
49,821
pytroll/posttroll
posttroll/message_broadcaster.py
MessageBroadcaster._run
def _run(self): """Broadcasts forever. """ self._is_running = True network_fail = False try: while self._do_run: try: if network_fail is True: LOGGER.info("Network connection re-established!") network_fail = False self._sender(self._message) except IOError as err: if err.errno == errno.ENETUNREACH: LOGGER.error("Network unreachable. " "Trying again in %d s.", self._interval) network_fail = True else: raise time.sleep(self._interval) finally: self._is_running = False self._sender.close()
python
def _run(self): """Broadcasts forever. """ self._is_running = True network_fail = False try: while self._do_run: try: if network_fail is True: LOGGER.info("Network connection re-established!") network_fail = False self._sender(self._message) except IOError as err: if err.errno == errno.ENETUNREACH: LOGGER.error("Network unreachable. " "Trying again in %d s.", self._interval) network_fail = True else: raise time.sleep(self._interval) finally: self._is_running = False self._sender.close()
[ "def", "_run", "(", "self", ")", ":", "self", ".", "_is_running", "=", "True", "network_fail", "=", "False", "try", ":", "while", "self", ".", "_do_run", ":", "try", ":", "if", "network_fail", "is", "True", ":", "LOGGER", ".", "info", "(", "\"Network c...
Broadcasts forever.
[ "Broadcasts", "forever", "." ]
8e811a0544b5182c4a72aed074b2ff8c4324e94d
https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/message_broadcaster.py#L127-L150
train
49,822
contentful-labs/contentful.py
contentful/cda/serialization.py
ResourceFactory.from_json
def from_json(self, json): """Create resource out of JSON data. :param json: JSON dict. :return: Resource with a type defined by the given JSON data. """ res_type = json['sys']['type'] if ResourceType.Array.value == res_type: return self.create_array(json) elif ResourceType.Entry.value == res_type: return self.create_entry(json) elif ResourceType.Asset.value == res_type: return ResourceFactory.create_asset(json) elif ResourceType.ContentType.value == res_type: return ResourceFactory.create_content_type(json) elif ResourceType.Space.value == res_type: return ResourceFactory.create_space(json)
python
def from_json(self, json): """Create resource out of JSON data. :param json: JSON dict. :return: Resource with a type defined by the given JSON data. """ res_type = json['sys']['type'] if ResourceType.Array.value == res_type: return self.create_array(json) elif ResourceType.Entry.value == res_type: return self.create_entry(json) elif ResourceType.Asset.value == res_type: return ResourceFactory.create_asset(json) elif ResourceType.ContentType.value == res_type: return ResourceFactory.create_content_type(json) elif ResourceType.Space.value == res_type: return ResourceFactory.create_space(json)
[ "def", "from_json", "(", "self", ",", "json", ")", ":", "res_type", "=", "json", "[", "'sys'", "]", "[", "'type'", "]", "if", "ResourceType", ".", "Array", ".", "value", "==", "res_type", ":", "return", "self", ".", "create_array", "(", "json", ")", ...
Create resource out of JSON data. :param json: JSON dict. :return: Resource with a type defined by the given JSON data.
[ "Create", "resource", "out", "of", "JSON", "data", "." ]
d9eb4a68abcad33e4766e2be8c7b35e605210b5a
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/serialization.py#L34-L51
train
49,823
contentful-labs/contentful.py
contentful/cda/serialization.py
ResourceFactory.process_array_items
def process_array_items(self, array, json): """Iterate through all `items` and create a resource for each. In addition map the resources under the `items_mapped` by the resource id and type. :param array: Array resource. :param json: Raw JSON dictionary. """ for item in json['items']: key = None processed = self.from_json(item) if isinstance(processed, Asset): key = 'Asset' elif isinstance(processed, Entry): key = 'Entry' if key is not None: array.items_mapped[key][processed.sys['id']] = processed array.items.append(processed)
python
def process_array_items(self, array, json): """Iterate through all `items` and create a resource for each. In addition map the resources under the `items_mapped` by the resource id and type. :param array: Array resource. :param json: Raw JSON dictionary. """ for item in json['items']: key = None processed = self.from_json(item) if isinstance(processed, Asset): key = 'Asset' elif isinstance(processed, Entry): key = 'Entry' if key is not None: array.items_mapped[key][processed.sys['id']] = processed array.items.append(processed)
[ "def", "process_array_items", "(", "self", ",", "array", ",", "json", ")", ":", "for", "item", "in", "json", "[", "'items'", "]", ":", "key", "=", "None", "processed", "=", "self", ".", "from_json", "(", "item", ")", "if", "isinstance", "(", "processed...
Iterate through all `items` and create a resource for each. In addition map the resources under the `items_mapped` by the resource id and type. :param array: Array resource. :param json: Raw JSON dictionary.
[ "Iterate", "through", "all", "items", "and", "create", "a", "resource", "for", "each", "." ]
d9eb4a68abcad33e4766e2be8c7b35e605210b5a
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/serialization.py#L189-L209
train
49,824
contentful-labs/contentful.py
contentful/cda/serialization.py
ResourceFactory.process_array_includes
def process_array_includes(self, array, json): """Iterate through all `includes` and create a resource for every item. In addition map the resources under the `items_mapped` by the resource id and type. :param array: Array resource. :param json: Raw JSON dictionary. """ includes = json.get('includes') or {} for key in array.items_mapped.keys(): if key in includes: for resource in includes[key]: processed = self.from_json(resource) array.items_mapped[key][processed.sys['id']] = processed
python
def process_array_includes(self, array, json): """Iterate through all `includes` and create a resource for every item. In addition map the resources under the `items_mapped` by the resource id and type. :param array: Array resource. :param json: Raw JSON dictionary. """ includes = json.get('includes') or {} for key in array.items_mapped.keys(): if key in includes: for resource in includes[key]: processed = self.from_json(resource) array.items_mapped[key][processed.sys['id']] = processed
[ "def", "process_array_includes", "(", "self", ",", "array", ",", "json", ")", ":", "includes", "=", "json", ".", "get", "(", "'includes'", ")", "or", "{", "}", "for", "key", "in", "array", ".", "items_mapped", ".", "keys", "(", ")", ":", "if", "key",...
Iterate through all `includes` and create a resource for every item. In addition map the resources under the `items_mapped` by the resource id and type. :param array: Array resource. :param json: Raw JSON dictionary.
[ "Iterate", "through", "all", "includes", "and", "create", "a", "resource", "for", "every", "item", "." ]
d9eb4a68abcad33e4766e2be8c7b35e605210b5a
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/serialization.py#L211-L224
train
49,825
fudge-py/fudge
fudge/__init__.py
Registry.clear_calls
def clear_calls(self): """Clears out any calls that were made on previously registered fake objects and resets all call stacks. You do not need to use this directly. Use fudge.clear_calls() """ self.clear_actual_calls() for stack in self.call_stacks: stack.reset() for fake, call_order in self.get_expected_call_order().items(): call_order.reset_calls()
python
def clear_calls(self): """Clears out any calls that were made on previously registered fake objects and resets all call stacks. You do not need to use this directly. Use fudge.clear_calls() """ self.clear_actual_calls() for stack in self.call_stacks: stack.reset() for fake, call_order in self.get_expected_call_order().items(): call_order.reset_calls()
[ "def", "clear_calls", "(", "self", ")", ":", "self", ".", "clear_actual_calls", "(", ")", "for", "stack", "in", "self", ".", "call_stacks", ":", "stack", ".", "reset", "(", ")", "for", "fake", ",", "call_order", "in", "self", ".", "get_expected_call_order"...
Clears out any calls that were made on previously registered fake objects and resets all call stacks. You do not need to use this directly. Use fudge.clear_calls()
[ "Clears", "out", "any", "calls", "that", "were", "made", "on", "previously", "registered", "fake", "objects", "and", "resets", "all", "call", "stacks", "." ]
b283fbc1a41900f3f5845b10b8c2ef9136a67ebc
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L43-L53
train
49,826
fudge-py/fudge
fudge/__init__.py
Registry.verify
def verify(self): """Ensure all expected calls were called, raise AssertionError otherwise. You do not need to use this directly. Use fudge.verify() """ try: for exp in self.get_expected_calls(): exp.assert_called() exp.assert_times_called() for fake, call_order in self.get_expected_call_order().items(): call_order.assert_order_met(finalize=True) finally: self.clear_calls()
python
def verify(self): """Ensure all expected calls were called, raise AssertionError otherwise. You do not need to use this directly. Use fudge.verify() """ try: for exp in self.get_expected_calls(): exp.assert_called() exp.assert_times_called() for fake, call_order in self.get_expected_call_order().items(): call_order.assert_order_met(finalize=True) finally: self.clear_calls()
[ "def", "verify", "(", "self", ")", ":", "try", ":", "for", "exp", "in", "self", ".", "get_expected_calls", "(", ")", ":", "exp", ".", "assert_called", "(", ")", "exp", ".", "assert_times_called", "(", ")", "for", "fake", ",", "call_order", "in", "self"...
Ensure all expected calls were called, raise AssertionError otherwise. You do not need to use this directly. Use fudge.verify()
[ "Ensure", "all", "expected", "calls", "were", "called", "raise", "AssertionError", "otherwise", "." ]
b283fbc1a41900f3f5845b10b8c2ef9136a67ebc
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L87-L100
train
49,827
fudge-py/fudge
fudge/__init__.py
ExpectedCallOrder.assert_order_met
def assert_order_met(self, finalize=False): """assert that calls have been made in the right order.""" error = None actual_call_len = len(self._actual_calls) expected_call_len = len(self._call_order) if actual_call_len == 0: error = "Not enough calls were made" else: for i,call in enumerate(self._call_order): if actual_call_len < i+1: if not finalize: # we're not done asserting calls so # forget about not having enough calls continue calls_made = len(self._actual_calls) if calls_made == 1: error = "Only 1 call was made" else: error = "Only %s calls were made" % calls_made break ac_call = self._actual_calls[i] if ac_call is not call: error = "Call #%s was %r" % (i+1, ac_call) break if not error: if actual_call_len > expected_call_len: # only show the first extra call since this # will be triggered before all calls are finished: error = "#%s %s was unexpected" % ( expected_call_len+1, self._actual_calls[expected_call_len] ) if error: msg = "%s; Expected: %s" % ( error, self._repr_call_list(self._call_order)) raise AssertionError(msg)
python
def assert_order_met(self, finalize=False): """assert that calls have been made in the right order.""" error = None actual_call_len = len(self._actual_calls) expected_call_len = len(self._call_order) if actual_call_len == 0: error = "Not enough calls were made" else: for i,call in enumerate(self._call_order): if actual_call_len < i+1: if not finalize: # we're not done asserting calls so # forget about not having enough calls continue calls_made = len(self._actual_calls) if calls_made == 1: error = "Only 1 call was made" else: error = "Only %s calls were made" % calls_made break ac_call = self._actual_calls[i] if ac_call is not call: error = "Call #%s was %r" % (i+1, ac_call) break if not error: if actual_call_len > expected_call_len: # only show the first extra call since this # will be triggered before all calls are finished: error = "#%s %s was unexpected" % ( expected_call_len+1, self._actual_calls[expected_call_len] ) if error: msg = "%s; Expected: %s" % ( error, self._repr_call_list(self._call_order)) raise AssertionError(msg)
[ "def", "assert_order_met", "(", "self", ",", "finalize", "=", "False", ")", ":", "error", "=", "None", "actual_call_len", "=", "len", "(", "self", ".", "_actual_calls", ")", "expected_call_len", "=", "len", "(", "self", ".", "_call_order", ")", "if", "actu...
assert that calls have been made in the right order.
[ "assert", "that", "calls", "have", "been", "made", "in", "the", "right", "order", "." ]
b283fbc1a41900f3f5845b10b8c2ef9136a67ebc
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L482-L522
train
49,828
fudge-py/fudge
fudge/__init__.py
Fake.expects_call
def expects_call(self): """The fake must be called. .. doctest:: :hide: >>> import fudge >>> fudge.clear_expectations() >>> fudge.clear_calls() This is useful for when you stub out a function as opposed to a class. For example:: >>> import fudge >>> remove = fudge.Fake('os.remove').expects_call() >>> fudge.verify() Traceback (most recent call last): ... AssertionError: fake:os.remove() was not called .. doctest:: :hide: >>> fudge.clear_expectations() """ self._callable = ExpectedCall(self, call_name=self._name, callable=True) return self
python
def expects_call(self): """The fake must be called. .. doctest:: :hide: >>> import fudge >>> fudge.clear_expectations() >>> fudge.clear_calls() This is useful for when you stub out a function as opposed to a class. For example:: >>> import fudge >>> remove = fudge.Fake('os.remove').expects_call() >>> fudge.verify() Traceback (most recent call last): ... AssertionError: fake:os.remove() was not called .. doctest:: :hide: >>> fudge.clear_expectations() """ self._callable = ExpectedCall(self, call_name=self._name, callable=True) return self
[ "def", "expects_call", "(", "self", ")", ":", "self", ".", "_callable", "=", "ExpectedCall", "(", "self", ",", "call_name", "=", "self", ".", "_name", ",", "callable", "=", "True", ")", "return", "self" ]
The fake must be called. .. doctest:: :hide: >>> import fudge >>> fudge.clear_expectations() >>> fudge.clear_calls() This is useful for when you stub out a function as opposed to a class. For example:: >>> import fudge >>> remove = fudge.Fake('os.remove').expects_call() >>> fudge.verify() Traceback (most recent call last): ... AssertionError: fake:os.remove() was not called .. doctest:: :hide: >>> fudge.clear_expectations()
[ "The", "fake", "must", "be", "called", "." ]
b283fbc1a41900f3f5845b10b8c2ef9136a67ebc
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L777-L805
train
49,829
fudge-py/fudge
fudge/__init__.py
Fake.is_callable
def is_callable(self): """The fake can be called. This is useful for when you stub out a function as opposed to a class. For example:: >>> import fudge >>> remove = Fake('os.remove').is_callable() >>> remove('some/path') """ self._callable = Call(self, call_name=self._name, callable=True) return self
python
def is_callable(self): """The fake can be called. This is useful for when you stub out a function as opposed to a class. For example:: >>> import fudge >>> remove = Fake('os.remove').is_callable() >>> remove('some/path') """ self._callable = Call(self, call_name=self._name, callable=True) return self
[ "def", "is_callable", "(", "self", ")", ":", "self", ".", "_callable", "=", "Call", "(", "self", ",", "call_name", "=", "self", ".", "_name", ",", "callable", "=", "True", ")", "return", "self" ]
The fake can be called. This is useful for when you stub out a function as opposed to a class. For example:: >>> import fudge >>> remove = Fake('os.remove').is_callable() >>> remove('some/path')
[ "The", "fake", "can", "be", "called", "." ]
b283fbc1a41900f3f5845b10b8c2ef9136a67ebc
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L807-L819
train
49,830
fudge-py/fudge
fudge/__init__.py
Fake.calls
def calls(self, call): """Redefine a call. The fake method will execute your function. I.E.:: >>> f = Fake().provides('hello').calls(lambda: 'Why, hello there') >>> f.hello() 'Why, hello there' """ exp = self._get_current_call() exp.call_replacement = call return self
python
def calls(self, call): """Redefine a call. The fake method will execute your function. I.E.:: >>> f = Fake().provides('hello').calls(lambda: 'Why, hello there') >>> f.hello() 'Why, hello there' """ exp = self._get_current_call() exp.call_replacement = call return self
[ "def", "calls", "(", "self", ",", "call", ")", ":", "exp", "=", "self", ".", "_get_current_call", "(", ")", "exp", ".", "call_replacement", "=", "call", "return", "self" ]
Redefine a call. The fake method will execute your function. I.E.:: >>> f = Fake().provides('hello').calls(lambda: 'Why, hello there') >>> f.hello() 'Why, hello there'
[ "Redefine", "a", "call", "." ]
b283fbc1a41900f3f5845b10b8c2ef9136a67ebc
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L832-L844
train
49,831
fudge-py/fudge
fudge/__init__.py
Fake.expects
def expects(self, call_name): """Expect a call. .. doctest:: :hide: >>> import fudge >>> fudge.clear_expectations() >>> fudge.clear_calls() If the method *call_name* is never called, then raise an error. I.E.:: >>> session = Fake('session').expects('open').expects('close') >>> session.open() >>> fudge.verify() Traceback (most recent call last): ... AssertionError: fake:session.close() was not called .. note:: If you want to also verify the order these calls are made in, use :func:`fudge.Fake.remember_order`. When using :func:`fudge.Fake.next_call` after ``expects(...)``, each new call will be part of the expected order Declaring ``expects()`` multiple times is the same as declaring :func:`fudge.Fake.next_call` """ if call_name in self._declared_calls: return self.next_call(for_method=call_name) self._last_declared_call_name = call_name c = ExpectedCall(self, call_name, call_order=self._expected_call_order) self._declare_call(call_name, c) return self
python
def expects(self, call_name): """Expect a call. .. doctest:: :hide: >>> import fudge >>> fudge.clear_expectations() >>> fudge.clear_calls() If the method *call_name* is never called, then raise an error. I.E.:: >>> session = Fake('session').expects('open').expects('close') >>> session.open() >>> fudge.verify() Traceback (most recent call last): ... AssertionError: fake:session.close() was not called .. note:: If you want to also verify the order these calls are made in, use :func:`fudge.Fake.remember_order`. When using :func:`fudge.Fake.next_call` after ``expects(...)``, each new call will be part of the expected order Declaring ``expects()`` multiple times is the same as declaring :func:`fudge.Fake.next_call` """ if call_name in self._declared_calls: return self.next_call(for_method=call_name) self._last_declared_call_name = call_name c = ExpectedCall(self, call_name, call_order=self._expected_call_order) self._declare_call(call_name, c) return self
[ "def", "expects", "(", "self", ",", "call_name", ")", ":", "if", "call_name", "in", "self", ".", "_declared_calls", ":", "return", "self", ".", "next_call", "(", "for_method", "=", "call_name", ")", "self", ".", "_last_declared_call_name", "=", "call_name", ...
Expect a call. .. doctest:: :hide: >>> import fudge >>> fudge.clear_expectations() >>> fudge.clear_calls() If the method *call_name* is never called, then raise an error. I.E.:: >>> session = Fake('session').expects('open').expects('close') >>> session.open() >>> fudge.verify() Traceback (most recent call last): ... AssertionError: fake:session.close() was not called .. note:: If you want to also verify the order these calls are made in, use :func:`fudge.Fake.remember_order`. When using :func:`fudge.Fake.next_call` after ``expects(...)``, each new call will be part of the expected order Declaring ``expects()`` multiple times is the same as declaring :func:`fudge.Fake.next_call`
[ "Expect", "a", "call", "." ]
b283fbc1a41900f3f5845b10b8c2ef9136a67ebc
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L846-L879
train
49,832
fudge-py/fudge
fudge/__init__.py
Fake.next_call
def next_call(self, for_method=None): """Start expecting or providing multiple calls. .. note:: next_call() cannot be used in combination with :func:`fudge.Fake.times_called` Up until calling this method, calls are infinite. For example, before next_call() ... :: >>> from fudge import Fake >>> f = Fake().provides('status').returns('Awake!') >>> f.status() 'Awake!' >>> f.status() 'Awake!' After next_call() ... :: >>> from fudge import Fake >>> f = Fake().provides('status').returns('Awake!') >>> f = f.next_call().returns('Asleep') >>> f = f.next_call().returns('Dreaming') >>> f.status() 'Awake!' >>> f.status() 'Asleep' >>> f.status() 'Dreaming' >>> f.status() Traceback (most recent call last): ... AssertionError: This attribute of fake:unnamed can only be called 3 time(s). Call reset() if necessary or fudge.clear_calls(). If you need to affect the next call of something other than the last declared call, use ``next_call(for_method="other_call")``. Here is an example using getters and setters on a session object :: >>> from fudge import Fake >>> sess = Fake('session').provides('get_count').returns(1) >>> sess = sess.provides('set_count').with_args(5) Now go back and adjust return values for get_count() :: >>> sess = sess.next_call(for_method='get_count').returns(5) This allows these calls to be made :: >>> sess.get_count() 1 >>> sess.set_count(5) >>> sess.get_count() 5 When using :func:`fudge.Fake.remember_order` in combination with :func:`fudge.Fake.expects` and :func:`fudge.Fake.next_call` each new call will be part of the expected order. """ last_call_name = self._last_declared_call_name if for_method: if for_method not in self._declared_calls: raise FakeDeclarationError( "next_call(for_method=%r) is not possible; " "declare expects(%r) or provides(%r) first" % ( for_method, for_method, for_method)) else: # set this for the local function: last_call_name = for_method # reset this for subsequent methods: self._last_declared_call_name = last_call_name if last_call_name: exp = self._declared_calls[last_call_name] elif self._callable: exp = self._callable else: raise FakeDeclarationError('next_call() must follow provides(), ' 'expects() or is_callable()') if getattr(exp, 'expected_times_called', None) is not None: raise FakeDeclarationError("Cannot use next_call() in combination with times_called()") if not isinstance(exp, CallStack): # lazily create a stack with the last defined # expected call as the first on the stack: stack = CallStack(self, initial_calls=[exp], expected=isinstance(exp, ExpectedCall), call_name=exp.call_name) # replace the old call obj using the same name: if last_call_name: self._declare_call(last_call_name, stack) elif self._callable: self._callable = stack else: stack = exp # hmm, we need a copy here so that the last call # falls off the stack. if stack.expected: next_call = ExpectedCall(self, call_name=exp.call_name, call_order=self._expected_call_order) else: next_call = Call(self, call_name=exp.call_name) stack.add_call(next_call) return self
python
def next_call(self, for_method=None): """Start expecting or providing multiple calls. .. note:: next_call() cannot be used in combination with :func:`fudge.Fake.times_called` Up until calling this method, calls are infinite. For example, before next_call() ... :: >>> from fudge import Fake >>> f = Fake().provides('status').returns('Awake!') >>> f.status() 'Awake!' >>> f.status() 'Awake!' After next_call() ... :: >>> from fudge import Fake >>> f = Fake().provides('status').returns('Awake!') >>> f = f.next_call().returns('Asleep') >>> f = f.next_call().returns('Dreaming') >>> f.status() 'Awake!' >>> f.status() 'Asleep' >>> f.status() 'Dreaming' >>> f.status() Traceback (most recent call last): ... AssertionError: This attribute of fake:unnamed can only be called 3 time(s). Call reset() if necessary or fudge.clear_calls(). If you need to affect the next call of something other than the last declared call, use ``next_call(for_method="other_call")``. Here is an example using getters and setters on a session object :: >>> from fudge import Fake >>> sess = Fake('session').provides('get_count').returns(1) >>> sess = sess.provides('set_count').with_args(5) Now go back and adjust return values for get_count() :: >>> sess = sess.next_call(for_method='get_count').returns(5) This allows these calls to be made :: >>> sess.get_count() 1 >>> sess.set_count(5) >>> sess.get_count() 5 When using :func:`fudge.Fake.remember_order` in combination with :func:`fudge.Fake.expects` and :func:`fudge.Fake.next_call` each new call will be part of the expected order. """ last_call_name = self._last_declared_call_name if for_method: if for_method not in self._declared_calls: raise FakeDeclarationError( "next_call(for_method=%r) is not possible; " "declare expects(%r) or provides(%r) first" % ( for_method, for_method, for_method)) else: # set this for the local function: last_call_name = for_method # reset this for subsequent methods: self._last_declared_call_name = last_call_name if last_call_name: exp = self._declared_calls[last_call_name] elif self._callable: exp = self._callable else: raise FakeDeclarationError('next_call() must follow provides(), ' 'expects() or is_callable()') if getattr(exp, 'expected_times_called', None) is not None: raise FakeDeclarationError("Cannot use next_call() in combination with times_called()") if not isinstance(exp, CallStack): # lazily create a stack with the last defined # expected call as the first on the stack: stack = CallStack(self, initial_calls=[exp], expected=isinstance(exp, ExpectedCall), call_name=exp.call_name) # replace the old call obj using the same name: if last_call_name: self._declare_call(last_call_name, stack) elif self._callable: self._callable = stack else: stack = exp # hmm, we need a copy here so that the last call # falls off the stack. if stack.expected: next_call = ExpectedCall(self, call_name=exp.call_name, call_order=self._expected_call_order) else: next_call = Call(self, call_name=exp.call_name) stack.add_call(next_call) return self
[ "def", "next_call", "(", "self", ",", "for_method", "=", "None", ")", ":", "last_call_name", "=", "self", ".", "_last_declared_call_name", "if", "for_method", ":", "if", "for_method", "not", "in", "self", ".", "_declared_calls", ":", "raise", "FakeDeclarationErr...
Start expecting or providing multiple calls. .. note:: next_call() cannot be used in combination with :func:`fudge.Fake.times_called` Up until calling this method, calls are infinite. For example, before next_call() ... :: >>> from fudge import Fake >>> f = Fake().provides('status').returns('Awake!') >>> f.status() 'Awake!' >>> f.status() 'Awake!' After next_call() ... :: >>> from fudge import Fake >>> f = Fake().provides('status').returns('Awake!') >>> f = f.next_call().returns('Asleep') >>> f = f.next_call().returns('Dreaming') >>> f.status() 'Awake!' >>> f.status() 'Asleep' >>> f.status() 'Dreaming' >>> f.status() Traceback (most recent call last): ... AssertionError: This attribute of fake:unnamed can only be called 3 time(s). Call reset() if necessary or fudge.clear_calls(). If you need to affect the next call of something other than the last declared call, use ``next_call(for_method="other_call")``. Here is an example using getters and setters on a session object :: >>> from fudge import Fake >>> sess = Fake('session').provides('get_count').returns(1) >>> sess = sess.provides('set_count').with_args(5) Now go back and adjust return values for get_count() :: >>> sess = sess.next_call(for_method='get_count').returns(5) This allows these calls to be made :: >>> sess.get_count() 1 >>> sess.set_count(5) >>> sess.get_count() 5 When using :func:`fudge.Fake.remember_order` in combination with :func:`fudge.Fake.expects` and :func:`fudge.Fake.next_call` each new call will be part of the expected order.
[ "Start", "expecting", "or", "providing", "multiple", "calls", "." ]
b283fbc1a41900f3f5845b10b8c2ef9136a67ebc
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L914-L1016
train
49,833
fudge-py/fudge
fudge/__init__.py
Fake.provides
def provides(self, call_name): """Provide a call. The call acts as a stub -- no error is raised if it is not called.:: >>> session = Fake('session').provides('open').provides('close') >>> import fudge >>> fudge.clear_expectations() # from any previously declared fakes >>> fudge.clear_calls() >>> session.open() >>> fudge.verify() # close() not called but no error Declaring ``provides()`` multiple times is the same as declaring :func:`fudge.Fake.next_call` """ if call_name in self._declared_calls: return self.next_call(for_method=call_name) self._last_declared_call_name = call_name c = Call(self, call_name) self._declare_call(call_name, c) return self
python
def provides(self, call_name): """Provide a call. The call acts as a stub -- no error is raised if it is not called.:: >>> session = Fake('session').provides('open').provides('close') >>> import fudge >>> fudge.clear_expectations() # from any previously declared fakes >>> fudge.clear_calls() >>> session.open() >>> fudge.verify() # close() not called but no error Declaring ``provides()`` multiple times is the same as declaring :func:`fudge.Fake.next_call` """ if call_name in self._declared_calls: return self.next_call(for_method=call_name) self._last_declared_call_name = call_name c = Call(self, call_name) self._declare_call(call_name, c) return self
[ "def", "provides", "(", "self", ",", "call_name", ")", ":", "if", "call_name", "in", "self", ".", "_declared_calls", ":", "return", "self", ".", "next_call", "(", "for_method", "=", "call_name", ")", "self", ".", "_last_declared_call_name", "=", "call_name", ...
Provide a call. The call acts as a stub -- no error is raised if it is not called.:: >>> session = Fake('session').provides('open').provides('close') >>> import fudge >>> fudge.clear_expectations() # from any previously declared fakes >>> fudge.clear_calls() >>> session.open() >>> fudge.verify() # close() not called but no error Declaring ``provides()`` multiple times is the same as declaring :func:`fudge.Fake.next_call`
[ "Provide", "a", "call", "." ]
b283fbc1a41900f3f5845b10b8c2ef9136a67ebc
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L1018-L1040
train
49,834
fudge-py/fudge
fudge/__init__.py
Fake.raises
def raises(self, exc): """Set last call to raise an exception class or instance. For example:: >>> import fudge >>> db = fudge.Fake('db').provides('insert').raises(ValueError("not enough parameters for insert")) >>> db.insert() Traceback (most recent call last): ... ValueError: not enough parameters for insert """ exp = self._get_current_call() exp.exception_to_raise = exc return self
python
def raises(self, exc): """Set last call to raise an exception class or instance. For example:: >>> import fudge >>> db = fudge.Fake('db').provides('insert').raises(ValueError("not enough parameters for insert")) >>> db.insert() Traceback (most recent call last): ... ValueError: not enough parameters for insert """ exp = self._get_current_call() exp.exception_to_raise = exc return self
[ "def", "raises", "(", "self", ",", "exc", ")", ":", "exp", "=", "self", ".", "_get_current_call", "(", ")", "exp", ".", "exception_to_raise", "=", "exc", "return", "self" ]
Set last call to raise an exception class or instance. For example:: >>> import fudge >>> db = fudge.Fake('db').provides('insert').raises(ValueError("not enough parameters for insert")) >>> db.insert() Traceback (most recent call last): ... ValueError: not enough parameters for insert
[ "Set", "last", "call", "to", "raise", "an", "exception", "class", "or", "instance", "." ]
b283fbc1a41900f3f5845b10b8c2ef9136a67ebc
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L1042-L1057
train
49,835
fudge-py/fudge
fudge/__init__.py
Fake.returns
def returns(self, val): """Set the last call to return a value. Set a static value to return when a method is called. I.E.:: >>> f = Fake().provides('get_number').returns(64) >>> f.get_number() 64 """ exp = self._get_current_call() exp.return_val = val return self
python
def returns(self, val): """Set the last call to return a value. Set a static value to return when a method is called. I.E.:: >>> f = Fake().provides('get_number').returns(64) >>> f.get_number() 64 """ exp = self._get_current_call() exp.return_val = val return self
[ "def", "returns", "(", "self", ",", "val", ")", ":", "exp", "=", "self", ".", "_get_current_call", "(", ")", "exp", ".", "return_val", "=", "val", "return", "self" ]
Set the last call to return a value. Set a static value to return when a method is called. I.E.:: >>> f = Fake().provides('get_number').returns(64) >>> f.get_number() 64
[ "Set", "the", "last", "call", "to", "return", "a", "value", "." ]
b283fbc1a41900f3f5845b10b8c2ef9136a67ebc
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L1098-L1110
train
49,836
fudge-py/fudge
fudge/__init__.py
Fake.times_called
def times_called(self, n): """Set the number of times an object can be called. When working with provided calls, you'll only see an error if the expected call count is exceeded :: >>> auth = Fake('auth').provides('login').times_called(1) >>> auth.login() >>> auth.login() Traceback (most recent call last): ... AssertionError: fake:auth.login() was called 2 time(s). Expected 1. When working with expected calls, you'll see an error if the call count is never met :: >>> import fudge >>> auth = fudge.Fake('auth').expects('login').times_called(2) >>> auth.login() >>> fudge.verify() Traceback (most recent call last): ... AssertionError: fake:auth.login() was called 1 time(s). Expected 2. .. note:: This cannot be used in combination with :func:`fudge.Fake.next_call` """ if self._last_declared_call_name: actual_last_call = self._declared_calls[self._last_declared_call_name] if isinstance(actual_last_call, CallStack): raise FakeDeclarationError("Cannot use times_called() in combination with next_call()") # else: # self._callable is in effect exp = self._get_current_call() exp.expected_times_called = n return self
python
def times_called(self, n): """Set the number of times an object can be called. When working with provided calls, you'll only see an error if the expected call count is exceeded :: >>> auth = Fake('auth').provides('login').times_called(1) >>> auth.login() >>> auth.login() Traceback (most recent call last): ... AssertionError: fake:auth.login() was called 2 time(s). Expected 1. When working with expected calls, you'll see an error if the call count is never met :: >>> import fudge >>> auth = fudge.Fake('auth').expects('login').times_called(2) >>> auth.login() >>> fudge.verify() Traceback (most recent call last): ... AssertionError: fake:auth.login() was called 1 time(s). Expected 2. .. note:: This cannot be used in combination with :func:`fudge.Fake.next_call` """ if self._last_declared_call_name: actual_last_call = self._declared_calls[self._last_declared_call_name] if isinstance(actual_last_call, CallStack): raise FakeDeclarationError("Cannot use times_called() in combination with next_call()") # else: # self._callable is in effect exp = self._get_current_call() exp.expected_times_called = n return self
[ "def", "times_called", "(", "self", ",", "n", ")", ":", "if", "self", ".", "_last_declared_call_name", ":", "actual_last_call", "=", "self", ".", "_declared_calls", "[", "self", ".", "_last_declared_call_name", "]", "if", "isinstance", "(", "actual_last_call", "...
Set the number of times an object can be called. When working with provided calls, you'll only see an error if the expected call count is exceeded :: >>> auth = Fake('auth').provides('login').times_called(1) >>> auth.login() >>> auth.login() Traceback (most recent call last): ... AssertionError: fake:auth.login() was called 2 time(s). Expected 1. When working with expected calls, you'll see an error if the call count is never met :: >>> import fudge >>> auth = fudge.Fake('auth').expects('login').times_called(2) >>> auth.login() >>> fudge.verify() Traceback (most recent call last): ... AssertionError: fake:auth.login() was called 1 time(s). Expected 2. .. note:: This cannot be used in combination with :func:`fudge.Fake.next_call`
[ "Set", "the", "number", "of", "times", "an", "object", "can", "be", "called", "." ]
b283fbc1a41900f3f5845b10b8c2ef9136a67ebc
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L1141-L1176
train
49,837
fudge-py/fudge
fudge/__init__.py
Fake.with_args
def with_args(self, *args, **kwargs): """Set the last call to expect specific argument values. The app under test must send all declared arguments and keyword arguments otherwise your test will raise an AssertionError. For example: .. doctest:: >>> import fudge >>> counter = fudge.Fake('counter').expects('increment').with_args(25, table='hits') >>> counter.increment(24, table='clicks') Traceback (most recent call last): ... AssertionError: fake:counter.increment(25, table='hits') was called unexpectedly with args (24, table='clicks') If you need to work with dynamic argument values consider using :func:`fudge.Fake.with_matching_args` to make looser declarations. You can also use :mod:`fudge.inspector` functions. Here is an example of providing a more flexible ``with_args()`` declaration using inspectors: .. doctest:: :hide: >>> fudge.clear_expectations() .. doctest:: >>> import fudge >>> from fudge.inspector import arg >>> counter = fudge.Fake('counter') >>> counter = counter.expects('increment').with_args( ... arg.any(), ... table=arg.endswith("hits")) ... The above declaration would allow you to call counter like this: .. doctest:: >>> counter.increment(999, table="image_hits") >>> fudge.verify() .. doctest:: :hide: >>> fudge.clear_calls() Or like this: .. doctest:: >>> counter.increment(22, table="user_profile_hits") >>> fudge.verify() .. doctest:: :hide: >>> fudge.clear_expectations() """ exp = self._get_current_call() if args: exp.expected_args = args if kwargs: exp.expected_kwargs = kwargs return self
python
def with_args(self, *args, **kwargs): """Set the last call to expect specific argument values. The app under test must send all declared arguments and keyword arguments otherwise your test will raise an AssertionError. For example: .. doctest:: >>> import fudge >>> counter = fudge.Fake('counter').expects('increment').with_args(25, table='hits') >>> counter.increment(24, table='clicks') Traceback (most recent call last): ... AssertionError: fake:counter.increment(25, table='hits') was called unexpectedly with args (24, table='clicks') If you need to work with dynamic argument values consider using :func:`fudge.Fake.with_matching_args` to make looser declarations. You can also use :mod:`fudge.inspector` functions. Here is an example of providing a more flexible ``with_args()`` declaration using inspectors: .. doctest:: :hide: >>> fudge.clear_expectations() .. doctest:: >>> import fudge >>> from fudge.inspector import arg >>> counter = fudge.Fake('counter') >>> counter = counter.expects('increment').with_args( ... arg.any(), ... table=arg.endswith("hits")) ... The above declaration would allow you to call counter like this: .. doctest:: >>> counter.increment(999, table="image_hits") >>> fudge.verify() .. doctest:: :hide: >>> fudge.clear_calls() Or like this: .. doctest:: >>> counter.increment(22, table="user_profile_hits") >>> fudge.verify() .. doctest:: :hide: >>> fudge.clear_expectations() """ exp = self._get_current_call() if args: exp.expected_args = args if kwargs: exp.expected_kwargs = kwargs return self
[ "def", "with_args", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "exp", "=", "self", ".", "_get_current_call", "(", ")", "if", "args", ":", "exp", ".", "expected_args", "=", "args", "if", "kwargs", ":", "exp", ".", "expected_kwar...
Set the last call to expect specific argument values. The app under test must send all declared arguments and keyword arguments otherwise your test will raise an AssertionError. For example: .. doctest:: >>> import fudge >>> counter = fudge.Fake('counter').expects('increment').with_args(25, table='hits') >>> counter.increment(24, table='clicks') Traceback (most recent call last): ... AssertionError: fake:counter.increment(25, table='hits') was called unexpectedly with args (24, table='clicks') If you need to work with dynamic argument values consider using :func:`fudge.Fake.with_matching_args` to make looser declarations. You can also use :mod:`fudge.inspector` functions. Here is an example of providing a more flexible ``with_args()`` declaration using inspectors: .. doctest:: :hide: >>> fudge.clear_expectations() .. doctest:: >>> import fudge >>> from fudge.inspector import arg >>> counter = fudge.Fake('counter') >>> counter = counter.expects('increment').with_args( ... arg.any(), ... table=arg.endswith("hits")) ... The above declaration would allow you to call counter like this: .. doctest:: >>> counter.increment(999, table="image_hits") >>> fudge.verify() .. doctest:: :hide: >>> fudge.clear_calls() Or like this: .. doctest:: >>> counter.increment(22, table="user_profile_hits") >>> fudge.verify() .. doctest:: :hide: >>> fudge.clear_expectations()
[ "Set", "the", "last", "call", "to", "expect", "specific", "argument", "values", "." ]
b283fbc1a41900f3f5845b10b8c2ef9136a67ebc
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L1178-L1243
train
49,838
fudge-py/fudge
fudge/__init__.py
Fake.with_matching_args
def with_matching_args(self, *args, **kwargs): """Set the last call to expect specific argument values if those arguments exist. Unlike :func:`fudge.Fake.with_args` use this if you want to only declare expectations about matching arguments. Any unknown keyword arguments used by the app under test will be allowed. For example, you can declare positional arguments but ignore keyword arguments: .. doctest:: >>> import fudge >>> db = fudge.Fake('db').expects('transaction').with_matching_args('insert') With this declaration, any keyword argument is allowed: .. doctest:: >>> db.transaction('insert', isolation_level='lock') >>> db.transaction('insert', isolation_level='shared') >>> db.transaction('insert', retry_on_error=True) .. doctest:: :hide: >>> fudge.clear_expectations() .. note:: you may get more mileage out of :mod:`fudge.inspector` functions as described in :func:`fudge.Fake.with_args` """ exp = self._get_current_call() if args: exp.expected_matching_args = args if kwargs: exp.expected_matching_kwargs = kwargs return self
python
def with_matching_args(self, *args, **kwargs): """Set the last call to expect specific argument values if those arguments exist. Unlike :func:`fudge.Fake.with_args` use this if you want to only declare expectations about matching arguments. Any unknown keyword arguments used by the app under test will be allowed. For example, you can declare positional arguments but ignore keyword arguments: .. doctest:: >>> import fudge >>> db = fudge.Fake('db').expects('transaction').with_matching_args('insert') With this declaration, any keyword argument is allowed: .. doctest:: >>> db.transaction('insert', isolation_level='lock') >>> db.transaction('insert', isolation_level='shared') >>> db.transaction('insert', retry_on_error=True) .. doctest:: :hide: >>> fudge.clear_expectations() .. note:: you may get more mileage out of :mod:`fudge.inspector` functions as described in :func:`fudge.Fake.with_args` """ exp = self._get_current_call() if args: exp.expected_matching_args = args if kwargs: exp.expected_matching_kwargs = kwargs return self
[ "def", "with_matching_args", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "exp", "=", "self", ".", "_get_current_call", "(", ")", "if", "args", ":", "exp", ".", "expected_matching_args", "=", "args", "if", "kwargs", ":", "exp", "."...
Set the last call to expect specific argument values if those arguments exist. Unlike :func:`fudge.Fake.with_args` use this if you want to only declare expectations about matching arguments. Any unknown keyword arguments used by the app under test will be allowed. For example, you can declare positional arguments but ignore keyword arguments: .. doctest:: >>> import fudge >>> db = fudge.Fake('db').expects('transaction').with_matching_args('insert') With this declaration, any keyword argument is allowed: .. doctest:: >>> db.transaction('insert', isolation_level='lock') >>> db.transaction('insert', isolation_level='shared') >>> db.transaction('insert', retry_on_error=True) .. doctest:: :hide: >>> fudge.clear_expectations() .. note:: you may get more mileage out of :mod:`fudge.inspector` functions as described in :func:`fudge.Fake.with_args`
[ "Set", "the", "last", "call", "to", "expect", "specific", "argument", "values", "if", "those", "arguments", "exist", "." ]
b283fbc1a41900f3f5845b10b8c2ef9136a67ebc
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L1245-L1283
train
49,839
fudge-py/fudge
fudge/__init__.py
Fake.without_args
def without_args(self, *args, **kwargs): """Set the last call to expect that certain arguments will not exist. This is the opposite of :func:`fudge.Fake.with_matching_args`. It will fail if any of the arguments are passed. .. doctest:: >>> import fudge >>> query = fudge.Fake('query').expects_call().without_args( ... 'http://example.com', name="Steve" ... ) >>> query('http://python.org', name="Joe") >>> query('http://example.com') Traceback (most recent call last): ... AssertionError: fake:query() was called unexpectedly with arg http://example.com >>> query("Joe", "Frank", "Bartholomew", "Steve") >>> query(name='Steve') Traceback (most recent call last): ... AssertionError: fake:query() was called unexpectedly with kwarg name=Steve >>> query('http://python.org', name='Steve') Traceback (most recent call last): ... AssertionError: fake:query() was called unexpectedly with kwarg name=Steve >>> query(city='Chicago', name='Steve') Traceback (most recent call last): ... AssertionError: fake:query() was called unexpectedly with kwarg name=Steve >>> query.expects_call().without_args('http://example2.com') fake:query >>> query('foobar') >>> query('foobar', 'http://example2.com') Traceback (most recent call last): ... AssertionError: fake:query() was called unexpectedly with arg http://example2.com >>> query.expects_call().without_args(name="Hieronymus") fake:query >>> query("Gottfried", "Hieronymus") >>> query(name="Wexter", other_name="Hieronymus") >>> query('asdf', name="Hieronymus") Traceback (most recent call last): ... AssertionError: fake:query() was called unexpectedly with kwarg name=Hieronymus >>> query(name="Hieronymus") Traceback (most recent call last): ... AssertionError: fake:query() was called unexpectedly with kwarg name=Hieronymus >>> query = fudge.Fake('query').expects_call().without_args( ... 'http://example.com', name="Steve" ... ).with_args('dog') >>> query('dog') >>> query('dog', 'http://example.com') Traceback (most recent call last): ... AssertionError: fake:query('dog') was called unexpectedly with args ('dog', 'http://example.com') >>> query() Traceback (most recent call last): ... AssertionError: fake:query('dog') was called unexpectedly with args () """ exp = self._get_current_call() if args: exp.unexpected_args = args if kwargs: exp.unexpected_kwargs = kwargs return self
python
def without_args(self, *args, **kwargs): """Set the last call to expect that certain arguments will not exist. This is the opposite of :func:`fudge.Fake.with_matching_args`. It will fail if any of the arguments are passed. .. doctest:: >>> import fudge >>> query = fudge.Fake('query').expects_call().without_args( ... 'http://example.com', name="Steve" ... ) >>> query('http://python.org', name="Joe") >>> query('http://example.com') Traceback (most recent call last): ... AssertionError: fake:query() was called unexpectedly with arg http://example.com >>> query("Joe", "Frank", "Bartholomew", "Steve") >>> query(name='Steve') Traceback (most recent call last): ... AssertionError: fake:query() was called unexpectedly with kwarg name=Steve >>> query('http://python.org', name='Steve') Traceback (most recent call last): ... AssertionError: fake:query() was called unexpectedly with kwarg name=Steve >>> query(city='Chicago', name='Steve') Traceback (most recent call last): ... AssertionError: fake:query() was called unexpectedly with kwarg name=Steve >>> query.expects_call().without_args('http://example2.com') fake:query >>> query('foobar') >>> query('foobar', 'http://example2.com') Traceback (most recent call last): ... AssertionError: fake:query() was called unexpectedly with arg http://example2.com >>> query.expects_call().without_args(name="Hieronymus") fake:query >>> query("Gottfried", "Hieronymus") >>> query(name="Wexter", other_name="Hieronymus") >>> query('asdf', name="Hieronymus") Traceback (most recent call last): ... AssertionError: fake:query() was called unexpectedly with kwarg name=Hieronymus >>> query(name="Hieronymus") Traceback (most recent call last): ... AssertionError: fake:query() was called unexpectedly with kwarg name=Hieronymus >>> query = fudge.Fake('query').expects_call().without_args( ... 'http://example.com', name="Steve" ... ).with_args('dog') >>> query('dog') >>> query('dog', 'http://example.com') Traceback (most recent call last): ... AssertionError: fake:query('dog') was called unexpectedly with args ('dog', 'http://example.com') >>> query() Traceback (most recent call last): ... AssertionError: fake:query('dog') was called unexpectedly with args () """ exp = self._get_current_call() if args: exp.unexpected_args = args if kwargs: exp.unexpected_kwargs = kwargs return self
[ "def", "without_args", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "exp", "=", "self", ".", "_get_current_call", "(", ")", "if", "args", ":", "exp", ".", "unexpected_args", "=", "args", "if", "kwargs", ":", "exp", ".", "unexpect...
Set the last call to expect that certain arguments will not exist. This is the opposite of :func:`fudge.Fake.with_matching_args`. It will fail if any of the arguments are passed. .. doctest:: >>> import fudge >>> query = fudge.Fake('query').expects_call().without_args( ... 'http://example.com', name="Steve" ... ) >>> query('http://python.org', name="Joe") >>> query('http://example.com') Traceback (most recent call last): ... AssertionError: fake:query() was called unexpectedly with arg http://example.com >>> query("Joe", "Frank", "Bartholomew", "Steve") >>> query(name='Steve') Traceback (most recent call last): ... AssertionError: fake:query() was called unexpectedly with kwarg name=Steve >>> query('http://python.org', name='Steve') Traceback (most recent call last): ... AssertionError: fake:query() was called unexpectedly with kwarg name=Steve >>> query(city='Chicago', name='Steve') Traceback (most recent call last): ... AssertionError: fake:query() was called unexpectedly with kwarg name=Steve >>> query.expects_call().without_args('http://example2.com') fake:query >>> query('foobar') >>> query('foobar', 'http://example2.com') Traceback (most recent call last): ... AssertionError: fake:query() was called unexpectedly with arg http://example2.com >>> query.expects_call().without_args(name="Hieronymus") fake:query >>> query("Gottfried", "Hieronymus") >>> query(name="Wexter", other_name="Hieronymus") >>> query('asdf', name="Hieronymus") Traceback (most recent call last): ... AssertionError: fake:query() was called unexpectedly with kwarg name=Hieronymus >>> query(name="Hieronymus") Traceback (most recent call last): ... AssertionError: fake:query() was called unexpectedly with kwarg name=Hieronymus >>> query = fudge.Fake('query').expects_call().without_args( ... 'http://example.com', name="Steve" ... ).with_args('dog') >>> query('dog') >>> query('dog', 'http://example.com') Traceback (most recent call last): ... AssertionError: fake:query('dog') was called unexpectedly with args ('dog', 'http://example.com') >>> query() Traceback (most recent call last): ... AssertionError: fake:query('dog') was called unexpectedly with args ()
[ "Set", "the", "last", "call", "to", "expect", "that", "certain", "arguments", "will", "not", "exist", "." ]
b283fbc1a41900f3f5845b10b8c2ef9136a67ebc
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L1285-L1357
train
49,840
fudge-py/fudge
fudge/__init__.py
Fake.with_arg_count
def with_arg_count(self, count): """Set the last call to expect an exact argument count. I.E.:: >>> auth = Fake('auth').provides('login').with_arg_count(2) >>> auth.login('joe_user') # forgot password Traceback (most recent call last): ... AssertionError: fake:auth.login() was called with 1 arg(s) but expected 2 """ exp = self._get_current_call() exp.expected_arg_count = count return self
python
def with_arg_count(self, count): """Set the last call to expect an exact argument count. I.E.:: >>> auth = Fake('auth').provides('login').with_arg_count(2) >>> auth.login('joe_user') # forgot password Traceback (most recent call last): ... AssertionError: fake:auth.login() was called with 1 arg(s) but expected 2 """ exp = self._get_current_call() exp.expected_arg_count = count return self
[ "def", "with_arg_count", "(", "self", ",", "count", ")", ":", "exp", "=", "self", ".", "_get_current_call", "(", ")", "exp", ".", "expected_arg_count", "=", "count", "return", "self" ]
Set the last call to expect an exact argument count. I.E.:: >>> auth = Fake('auth').provides('login').with_arg_count(2) >>> auth.login('joe_user') # forgot password Traceback (most recent call last): ... AssertionError: fake:auth.login() was called with 1 arg(s) but expected 2
[ "Set", "the", "last", "call", "to", "expect", "an", "exact", "argument", "count", "." ]
b283fbc1a41900f3f5845b10b8c2ef9136a67ebc
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L1359-L1373
train
49,841
fudge-py/fudge
fudge/__init__.py
Fake.with_kwarg_count
def with_kwarg_count(self, count): """Set the last call to expect an exact count of keyword arguments. I.E.:: >>> auth = Fake('auth').provides('login').with_kwarg_count(2) >>> auth.login(username='joe') # forgot password= Traceback (most recent call last): ... AssertionError: fake:auth.login() was called with 1 keyword arg(s) but expected 2 """ exp = self._get_current_call() exp.expected_kwarg_count = count return self
python
def with_kwarg_count(self, count): """Set the last call to expect an exact count of keyword arguments. I.E.:: >>> auth = Fake('auth').provides('login').with_kwarg_count(2) >>> auth.login(username='joe') # forgot password= Traceback (most recent call last): ... AssertionError: fake:auth.login() was called with 1 keyword arg(s) but expected 2 """ exp = self._get_current_call() exp.expected_kwarg_count = count return self
[ "def", "with_kwarg_count", "(", "self", ",", "count", ")", ":", "exp", "=", "self", ".", "_get_current_call", "(", ")", "exp", ".", "expected_kwarg_count", "=", "count", "return", "self" ]
Set the last call to expect an exact count of keyword arguments. I.E.:: >>> auth = Fake('auth').provides('login').with_kwarg_count(2) >>> auth.login(username='joe') # forgot password= Traceback (most recent call last): ... AssertionError: fake:auth.login() was called with 1 keyword arg(s) but expected 2
[ "Set", "the", "last", "call", "to", "expect", "an", "exact", "count", "of", "keyword", "arguments", "." ]
b283fbc1a41900f3f5845b10b8c2ef9136a67ebc
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L1375-L1389
train
49,842
thespacedoctor/sherlock
sherlock/database.py
database.connect
def connect(self): """connect to the various databases, the credientals and settings of which are found in the sherlock settings file **Return:** - ``transientsDbConn`` -- the database hosting the transient source data - ``cataloguesDbConn`` -- connection to the database hosting the contextual catalogues the transients are to be crossmatched against - ``pmDbConn`` -- connection to the PESSTO Marshall database See the class docstring for usage .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip any useful text to docs mindmap - regenerate the docs and check redendering of this docstring """ self.log.debug('starting the ``get`` method') transientSettings = self.settings[ "database settings"]["transients"] catalogueSettings = self.settings[ "database settings"]["static catalogues"] if "pessto marshall" in self.settings[ "database settings"]: marshallSettings = self.settings[ "database settings"]["pessto marshall"] else: marshallSettings = False dbConns = [] for dbSettings in [transientSettings, catalogueSettings, marshallSettings]: port = False if dbSettings and dbSettings["tunnel"]: port = self._setup_tunnel( tunnelParameters=dbSettings["tunnel"] ) if dbSettings: # SETUP A DATABASE CONNECTION FOR THE STATIC CATALOGUES host = dbSettings["host"] user = dbSettings["user"] passwd = dbSettings["password"] dbName = dbSettings["db"] thisConn = ms.connect( host=host, user=user, passwd=passwd, db=dbName, port=port, use_unicode=True, charset='utf8', client_flag=ms.constants.CLIENT.MULTI_STATEMENTS, connect_timeout=3600 ) thisConn.autocommit(True) dbConns.append(thisConn) else: dbConns.append(None) # CREATE A DICTIONARY OF DATABASES dbConns = { "transients": dbConns[0], "catalogues": dbConns[1], "marshall": dbConns[2] } dbVersions = {} for k, v in dbConns.iteritems(): if v: sqlQuery = u""" SELECT VERSION() as v; """ % locals() rows = readquery( log=self.log, sqlQuery=sqlQuery, dbConn=v, quiet=False ) version = rows[0]['v'] dbVersions[k] = version else: dbVersions[k] = None self.log.debug('completed the ``get`` method') return dbConns, dbVersions
python
def connect(self): """connect to the various databases, the credientals and settings of which are found in the sherlock settings file **Return:** - ``transientsDbConn`` -- the database hosting the transient source data - ``cataloguesDbConn`` -- connection to the database hosting the contextual catalogues the transients are to be crossmatched against - ``pmDbConn`` -- connection to the PESSTO Marshall database See the class docstring for usage .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip any useful text to docs mindmap - regenerate the docs and check redendering of this docstring """ self.log.debug('starting the ``get`` method') transientSettings = self.settings[ "database settings"]["transients"] catalogueSettings = self.settings[ "database settings"]["static catalogues"] if "pessto marshall" in self.settings[ "database settings"]: marshallSettings = self.settings[ "database settings"]["pessto marshall"] else: marshallSettings = False dbConns = [] for dbSettings in [transientSettings, catalogueSettings, marshallSettings]: port = False if dbSettings and dbSettings["tunnel"]: port = self._setup_tunnel( tunnelParameters=dbSettings["tunnel"] ) if dbSettings: # SETUP A DATABASE CONNECTION FOR THE STATIC CATALOGUES host = dbSettings["host"] user = dbSettings["user"] passwd = dbSettings["password"] dbName = dbSettings["db"] thisConn = ms.connect( host=host, user=user, passwd=passwd, db=dbName, port=port, use_unicode=True, charset='utf8', client_flag=ms.constants.CLIENT.MULTI_STATEMENTS, connect_timeout=3600 ) thisConn.autocommit(True) dbConns.append(thisConn) else: dbConns.append(None) # CREATE A DICTIONARY OF DATABASES dbConns = { "transients": dbConns[0], "catalogues": dbConns[1], "marshall": dbConns[2] } dbVersions = {} for k, v in dbConns.iteritems(): if v: sqlQuery = u""" SELECT VERSION() as v; """ % locals() rows = readquery( log=self.log, sqlQuery=sqlQuery, dbConn=v, quiet=False ) version = rows[0]['v'] dbVersions[k] = version else: dbVersions[k] = None self.log.debug('completed the ``get`` method') return dbConns, dbVersions
[ "def", "connect", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "'starting the ``get`` method'", ")", "transientSettings", "=", "self", ".", "settings", "[", "\"database settings\"", "]", "[", "\"transients\"", "]", "catalogueSettings", "=", "sel...
connect to the various databases, the credientals and settings of which are found in the sherlock settings file **Return:** - ``transientsDbConn`` -- the database hosting the transient source data - ``cataloguesDbConn`` -- connection to the database hosting the contextual catalogues the transients are to be crossmatched against - ``pmDbConn`` -- connection to the PESSTO Marshall database See the class docstring for usage .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip any useful text to docs mindmap - regenerate the docs and check redendering of this docstring
[ "connect", "to", "the", "various", "databases", "the", "credientals", "and", "settings", "of", "which", "are", "found", "in", "the", "sherlock", "settings", "file" ]
2c80fb6fa31b04e7820e6928e3d437a21e692dd3
https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/database.py#L83-L171
train
49,843
ozgurgunes/django-manifest
manifest/accounts/forms.py
RegistrationForm.clean_username
def clean_username(self): """ Validate that the username is unique and not listed in ``defaults.ACCOUNTS_FORBIDDEN_USERNAMES`` list. """ try: user = get_user_model().objects.get(username=self.cleaned_data["username"]) except get_user_model().DoesNotExist: pass else: raise forms.ValidationError( self.error_messages['duplicate_username']) if self.cleaned_data['username'].lower() \ in defaults.ACCOUNTS_FORBIDDEN_USERNAMES: raise forms.ValidationError(_(u'This username is not allowed.')) return self.cleaned_data['username']
python
def clean_username(self): """ Validate that the username is unique and not listed in ``defaults.ACCOUNTS_FORBIDDEN_USERNAMES`` list. """ try: user = get_user_model().objects.get(username=self.cleaned_data["username"]) except get_user_model().DoesNotExist: pass else: raise forms.ValidationError( self.error_messages['duplicate_username']) if self.cleaned_data['username'].lower() \ in defaults.ACCOUNTS_FORBIDDEN_USERNAMES: raise forms.ValidationError(_(u'This username is not allowed.')) return self.cleaned_data['username']
[ "def", "clean_username", "(", "self", ")", ":", "try", ":", "user", "=", "get_user_model", "(", ")", ".", "objects", ".", "get", "(", "username", "=", "self", ".", "cleaned_data", "[", "\"username\"", "]", ")", "except", "get_user_model", "(", ")", ".", ...
Validate that the username is unique and not listed in ``defaults.ACCOUNTS_FORBIDDEN_USERNAMES`` list.
[ "Validate", "that", "the", "username", "is", "unique", "and", "not", "listed", "in", "defaults", ".", "ACCOUNTS_FORBIDDEN_USERNAMES", "list", "." ]
9873bbf2a475b76284ad7e36b2b26c92131e72dd
https://github.com/ozgurgunes/django-manifest/blob/9873bbf2a475b76284ad7e36b2b26c92131e72dd/manifest/accounts/forms.py#L48-L65
train
49,844
ozgurgunes/django-manifest
manifest/accounts/forms.py
RegistrationForm.clean_email
def clean_email(self): """ Validate that the email address is unique. """ if get_user_model().objects.filter( Q(email__iexact=self.cleaned_data['email']) | Q(email_unconfirmed__iexact=self.cleaned_data['email'])): raise forms.ValidationError(_(u'This email address is already ' 'in use. Please supply a different email.')) return self.cleaned_data['email']
python
def clean_email(self): """ Validate that the email address is unique. """ if get_user_model().objects.filter( Q(email__iexact=self.cleaned_data['email']) | Q(email_unconfirmed__iexact=self.cleaned_data['email'])): raise forms.ValidationError(_(u'This email address is already ' 'in use. Please supply a different email.')) return self.cleaned_data['email']
[ "def", "clean_email", "(", "self", ")", ":", "if", "get_user_model", "(", ")", ".", "objects", ".", "filter", "(", "Q", "(", "email__iexact", "=", "self", ".", "cleaned_data", "[", "'email'", "]", ")", "|", "Q", "(", "email_unconfirmed__iexact", "=", "se...
Validate that the email address is unique.
[ "Validate", "that", "the", "email", "address", "is", "unique", "." ]
9873bbf2a475b76284ad7e36b2b26c92131e72dd
https://github.com/ozgurgunes/django-manifest/blob/9873bbf2a475b76284ad7e36b2b26c92131e72dd/manifest/accounts/forms.py#L67-L77
train
49,845
ozgurgunes/django-manifest
manifest/accounts/forms.py
EmailForm.clean_email
def clean_email(self): """ Validate that the email is not already registered with another user. """ if self.cleaned_data['email'].lower() == self.user.email: raise forms.ValidationError(_(u"You're already known under " "this email address.")) if get_user_model().objects.filter( email__iexact=self.cleaned_data['email']).exclude( email__iexact=self.user.email): raise forms.ValidationError(_(u'This email address is already ' 'in use. Please supply a different email address.')) return self.cleaned_data['email']
python
def clean_email(self): """ Validate that the email is not already registered with another user. """ if self.cleaned_data['email'].lower() == self.user.email: raise forms.ValidationError(_(u"You're already known under " "this email address.")) if get_user_model().objects.filter( email__iexact=self.cleaned_data['email']).exclude( email__iexact=self.user.email): raise forms.ValidationError(_(u'This email address is already ' 'in use. Please supply a different email address.')) return self.cleaned_data['email']
[ "def", "clean_email", "(", "self", ")", ":", "if", "self", ".", "cleaned_data", "[", "'email'", "]", ".", "lower", "(", ")", "==", "self", ".", "user", ".", "email", ":", "raise", "forms", ".", "ValidationError", "(", "_", "(", "u\"You're already known u...
Validate that the email is not already registered with another user.
[ "Validate", "that", "the", "email", "is", "not", "already", "registered", "with", "another", "user", "." ]
9873bbf2a475b76284ad7e36b2b26c92131e72dd
https://github.com/ozgurgunes/django-manifest/blob/9873bbf2a475b76284ad7e36b2b26c92131e72dd/manifest/accounts/forms.py#L221-L234
train
49,846
ozgurgunes/django-manifest
manifest/accounts/forms.py
ProfileForm.clean_picture
def clean_picture(self): """ Validates format and file size of uploaded profile picture. """ if self.cleaned_data.get('picture'): picture_data = self.cleaned_data['picture'] if 'error' in picture_data: raise forms.ValidationError(_(u'Upload a valid image. ' 'The file you uploaded was either not an image ' 'or a corrupted image.')) content_type = picture_data.content_type if content_type: main, sub = content_type.split('/') if not (main == 'image' and sub in defaults.ACCOUNTS_PICTURE_FORMATS): raise forms.ValidationError(_(u'%s only.' % defaults.ACCOUNTS_PICTURE_FORMATS)) if picture_data.size > int(defaults.ACCOUNTS_PICTURE_MAX_FILE): raise forms.ValidationError(_(u'Image size is too big.')) return self.cleaned_data['picture']
python
def clean_picture(self): """ Validates format and file size of uploaded profile picture. """ if self.cleaned_data.get('picture'): picture_data = self.cleaned_data['picture'] if 'error' in picture_data: raise forms.ValidationError(_(u'Upload a valid image. ' 'The file you uploaded was either not an image ' 'or a corrupted image.')) content_type = picture_data.content_type if content_type: main, sub = content_type.split('/') if not (main == 'image' and sub in defaults.ACCOUNTS_PICTURE_FORMATS): raise forms.ValidationError(_(u'%s only.' % defaults.ACCOUNTS_PICTURE_FORMATS)) if picture_data.size > int(defaults.ACCOUNTS_PICTURE_MAX_FILE): raise forms.ValidationError(_(u'Image size is too big.')) return self.cleaned_data['picture']
[ "def", "clean_picture", "(", "self", ")", ":", "if", "self", ".", "cleaned_data", ".", "get", "(", "'picture'", ")", ":", "picture_data", "=", "self", ".", "cleaned_data", "[", "'picture'", "]", "if", "'error'", "in", "picture_data", ":", "raise", "forms",...
Validates format and file size of uploaded profile picture.
[ "Validates", "format", "and", "file", "size", "of", "uploaded", "profile", "picture", "." ]
9873bbf2a475b76284ad7e36b2b26c92131e72dd
https://github.com/ozgurgunes/django-manifest/blob/9873bbf2a475b76284ad7e36b2b26c92131e72dd/manifest/accounts/forms.py#L280-L302
train
49,847
pytroll/posttroll
posttroll/logger.py
Logger.log
def log(self): """Log stuff. """ with Subscribe(services=[""], addr_listener=True) as sub: for msg in sub.recv(1): if msg: if msg.type in ["log.debug", "log.info", "log.warning", "log.error", "log.critical"]: getattr(LOGGER, msg.type[4:])(msg.subject + " " + msg.sender + " " + str(msg.data) + " " + str(msg.time)) elif msg.binary: LOGGER.debug("%s %s %s [binary] %s", msg.subject, msg.sender, msg.type, str(msg.time)) else: LOGGER.debug("%s %s %s %s %s", msg.subject, msg.sender, msg.type, str(msg.data), str(msg.time)) if not self.loop: LOGGER.info("Stop logging") break
python
def log(self): """Log stuff. """ with Subscribe(services=[""], addr_listener=True) as sub: for msg in sub.recv(1): if msg: if msg.type in ["log.debug", "log.info", "log.warning", "log.error", "log.critical"]: getattr(LOGGER, msg.type[4:])(msg.subject + " " + msg.sender + " " + str(msg.data) + " " + str(msg.time)) elif msg.binary: LOGGER.debug("%s %s %s [binary] %s", msg.subject, msg.sender, msg.type, str(msg.time)) else: LOGGER.debug("%s %s %s %s %s", msg.subject, msg.sender, msg.type, str(msg.data), str(msg.time)) if not self.loop: LOGGER.info("Stop logging") break
[ "def", "log", "(", "self", ")", ":", "with", "Subscribe", "(", "services", "=", "[", "\"\"", "]", ",", "addr_listener", "=", "True", ")", "as", "sub", ":", "for", "msg", "in", "sub", ".", "recv", "(", "1", ")", ":", "if", "msg", ":", "if", "msg...
Log stuff.
[ "Log", "stuff", "." ]
8e811a0544b5182c4a72aed074b2ff8c4324e94d
https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/logger.py#L129-L156
train
49,848
emichael/PyREM
pyrem/task.py
cleanup
def cleanup(): """Stop all started tasks on system exit. Note: This only handles signals caught by the atexit module by default. SIGKILL, for instance, will not be caught, so cleanup is not guaranteed in all cases. """ to_stop = STARTED_TASKS.copy() if to_stop: print "Cleaning up..." for task in to_stop: try: task.stop() except: # pylint: disable=W0702 etype, value, trace = sys.exc_info() # Disregard no such process exceptions, print out the rest if not (isinstance(value, OSError) and value.errno == 3): print ''.join(format_exception(etype, value, trace, None)) continue
python
def cleanup(): """Stop all started tasks on system exit. Note: This only handles signals caught by the atexit module by default. SIGKILL, for instance, will not be caught, so cleanup is not guaranteed in all cases. """ to_stop = STARTED_TASKS.copy() if to_stop: print "Cleaning up..." for task in to_stop: try: task.stop() except: # pylint: disable=W0702 etype, value, trace = sys.exc_info() # Disregard no such process exceptions, print out the rest if not (isinstance(value, OSError) and value.errno == 3): print ''.join(format_exception(etype, value, trace, None)) continue
[ "def", "cleanup", "(", ")", ":", "to_stop", "=", "STARTED_TASKS", ".", "copy", "(", ")", "if", "to_stop", ":", "print", "\"Cleaning up...\"", "for", "task", "in", "to_stop", ":", "try", ":", "task", ".", "stop", "(", ")", "except", ":", "# pylint: disabl...
Stop all started tasks on system exit. Note: This only handles signals caught by the atexit module by default. SIGKILL, for instance, will not be caught, so cleanup is not guaranteed in all cases.
[ "Stop", "all", "started", "tasks", "on", "system", "exit", "." ]
2609249ead197cd9496d164f4998ca9985503579
https://github.com/emichael/PyREM/blob/2609249ead197cd9496d164f4998ca9985503579/pyrem/task.py#L30-L48
train
49,849
emichael/PyREM
pyrem/task.py
Task.wait
def wait(self): """Wait on a task to finish and stop it when it has finished. Raises: RuntimeError: If the task hasn't been started or has already been stopped. Returns: The ``return_values`` of the task. """ if self._status is not TaskStatus.STARTED: raise RuntimeError("Cannot wait on %s in state %s" % (self, self._status)) self._wait() self.stop() return self.return_values
python
def wait(self): """Wait on a task to finish and stop it when it has finished. Raises: RuntimeError: If the task hasn't been started or has already been stopped. Returns: The ``return_values`` of the task. """ if self._status is not TaskStatus.STARTED: raise RuntimeError("Cannot wait on %s in state %s" % (self, self._status)) self._wait() self.stop() return self.return_values
[ "def", "wait", "(", "self", ")", ":", "if", "self", ".", "_status", "is", "not", "TaskStatus", ".", "STARTED", ":", "raise", "RuntimeError", "(", "\"Cannot wait on %s in state %s\"", "%", "(", "self", ",", "self", ".", "_status", ")", ")", "self", ".", "...
Wait on a task to finish and stop it when it has finished. Raises: RuntimeError: If the task hasn't been started or has already been stopped. Returns: The ``return_values`` of the task.
[ "Wait", "on", "a", "task", "to", "finish", "and", "stop", "it", "when", "it", "has", "finished", "." ]
2609249ead197cd9496d164f4998ca9985503579
https://github.com/emichael/PyREM/blob/2609249ead197cd9496d164f4998ca9985503579/pyrem/task.py#L112-L127
train
49,850
emichael/PyREM
pyrem/task.py
Task.stop
def stop(self): """Stop a task immediately. Raises: RuntimeError: If the task hasn't been started or has already been stopped. """ if self._status is TaskStatus.STOPPED: return if self._status is not TaskStatus.STARTED: raise RuntimeError("Cannot stop %s in state %s" % (self, self._status)) self._stop() STARTED_TASKS.remove(self) self._status = TaskStatus.STOPPED
python
def stop(self): """Stop a task immediately. Raises: RuntimeError: If the task hasn't been started or has already been stopped. """ if self._status is TaskStatus.STOPPED: return if self._status is not TaskStatus.STARTED: raise RuntimeError("Cannot stop %s in state %s" % (self, self._status)) self._stop() STARTED_TASKS.remove(self) self._status = TaskStatus.STOPPED
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "_status", "is", "TaskStatus", ".", "STOPPED", ":", "return", "if", "self", ".", "_status", "is", "not", "TaskStatus", ".", "STARTED", ":", "raise", "RuntimeError", "(", "\"Cannot stop %s in state %s\"...
Stop a task immediately. Raises: RuntimeError: If the task hasn't been started or has already been stopped.
[ "Stop", "a", "task", "immediately", "." ]
2609249ead197cd9496d164f4998ca9985503579
https://github.com/emichael/PyREM/blob/2609249ead197cd9496d164f4998ca9985503579/pyrem/task.py#L133-L149
train
49,851
emichael/PyREM
pyrem/task.py
Task.reset
def reset(self): """Reset a task. Allows a task to be started again, clears the ``return_values``. Raises: RuntimeError: If the task has not been stopped. """ if self._status is not TaskStatus.STOPPED: raise RuntimeError("Cannot reset %s in state %s" % (self, self._status)) self._reset() self.return_values = {} self._status = TaskStatus.IDLE
python
def reset(self): """Reset a task. Allows a task to be started again, clears the ``return_values``. Raises: RuntimeError: If the task has not been stopped. """ if self._status is not TaskStatus.STOPPED: raise RuntimeError("Cannot reset %s in state %s" % (self, self._status)) self._reset() self.return_values = {} self._status = TaskStatus.IDLE
[ "def", "reset", "(", "self", ")", ":", "if", "self", ".", "_status", "is", "not", "TaskStatus", ".", "STOPPED", ":", "raise", "RuntimeError", "(", "\"Cannot reset %s in state %s\"", "%", "(", "self", ",", "self", ".", "_status", ")", ")", "self", ".", "_...
Reset a task. Allows a task to be started again, clears the ``return_values``. Raises: RuntimeError: If the task has not been stopped.
[ "Reset", "a", "task", "." ]
2609249ead197cd9496d164f4998ca9985503579
https://github.com/emichael/PyREM/blob/2609249ead197cd9496d164f4998ca9985503579/pyrem/task.py#L155-L168
train
49,852
emichael/PyREM
pyrem/task.py
Parallel._aggregate
def _aggregate(self): """Helper method to aggregate RemoteTasks into single ssh session.""" # pylint: disable=W0212 nonremote = [t for t in self._tasks if not isinstance(t, RemoteTask)] remote = [t for t in self._tasks if isinstance(t, RemoteTask)] host_dict = defaultdict(list) for task in remote: host_dict[task.host].append(task) aggregated = [] for task_group in host_dict.values(): # Build up combined command combined_cmd = [] for task in task_group: if combined_cmd: combined_cmd.append('&') combined_cmd.append(' '.join(task._remote_command)) # Now, generated aggregate task t0 = task_group[0] # pylint: disable=C0103 task = RemoteTask( t0.host, combined_cmd, t0._quiet, t0._return_output, t0._kill_remote, t0._identity_file) aggregated.append(task) self._tasks = nonremote + aggregated
python
def _aggregate(self): """Helper method to aggregate RemoteTasks into single ssh session.""" # pylint: disable=W0212 nonremote = [t for t in self._tasks if not isinstance(t, RemoteTask)] remote = [t for t in self._tasks if isinstance(t, RemoteTask)] host_dict = defaultdict(list) for task in remote: host_dict[task.host].append(task) aggregated = [] for task_group in host_dict.values(): # Build up combined command combined_cmd = [] for task in task_group: if combined_cmd: combined_cmd.append('&') combined_cmd.append(' '.join(task._remote_command)) # Now, generated aggregate task t0 = task_group[0] # pylint: disable=C0103 task = RemoteTask( t0.host, combined_cmd, t0._quiet, t0._return_output, t0._kill_remote, t0._identity_file) aggregated.append(task) self._tasks = nonremote + aggregated
[ "def", "_aggregate", "(", "self", ")", ":", "# pylint: disable=W0212", "nonremote", "=", "[", "t", "for", "t", "in", "self", ".", "_tasks", "if", "not", "isinstance", "(", "t", ",", "RemoteTask", ")", "]", "remote", "=", "[", "t", "for", "t", "in", "...
Helper method to aggregate RemoteTasks into single ssh session.
[ "Helper", "method", "to", "aggregate", "RemoteTasks", "into", "single", "ssh", "session", "." ]
2609249ead197cd9496d164f4998ca9985503579
https://github.com/emichael/PyREM/blob/2609249ead197cd9496d164f4998ca9985503579/pyrem/task.py#L385-L412
train
49,853
ozgurgunes/django-manifest
manifest/accounts/models.py
upload_to_picture
def upload_to_picture(instance, filename): """ Uploads a picture for a user to the ``ACCOUNTS_PICTURE_PATH`` and saving it under unique hash for the image. This is for privacy reasons so others can't just browse through the picture directory. """ extension = filename.split('.')[-1].lower() salt, hash = generate_sha1(instance.id) return '%(path)s/%(hash)s.%(extension)s' % { 'path': getattr(defaults, 'ACCOUNTS_PICTURE_PATH','%s/%s' % ( str(instance._meta.app_label), str(instance._meta.model_name))), 'hash': hash[:10], 'extension': extension}
python
def upload_to_picture(instance, filename): """ Uploads a picture for a user to the ``ACCOUNTS_PICTURE_PATH`` and saving it under unique hash for the image. This is for privacy reasons so others can't just browse through the picture directory. """ extension = filename.split('.')[-1].lower() salt, hash = generate_sha1(instance.id) return '%(path)s/%(hash)s.%(extension)s' % { 'path': getattr(defaults, 'ACCOUNTS_PICTURE_PATH','%s/%s' % ( str(instance._meta.app_label), str(instance._meta.model_name))), 'hash': hash[:10], 'extension': extension}
[ "def", "upload_to_picture", "(", "instance", ",", "filename", ")", ":", "extension", "=", "filename", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", ".", "lower", "(", ")", "salt", ",", "hash", "=", "generate_sha1", "(", "instance", ".", "id", ")...
Uploads a picture for a user to the ``ACCOUNTS_PICTURE_PATH`` and saving it under unique hash for the image. This is for privacy reasons so others can't just browse through the picture directory.
[ "Uploads", "a", "picture", "for", "a", "user", "to", "the", "ACCOUNTS_PICTURE_PATH", "and", "saving", "it", "under", "unique", "hash", "for", "the", "image", ".", "This", "is", "for", "privacy", "reasons", "so", "others", "can", "t", "just", "browse", "thr...
9873bbf2a475b76284ad7e36b2b26c92131e72dd
https://github.com/ozgurgunes/django-manifest/blob/9873bbf2a475b76284ad7e36b2b26c92131e72dd/manifest/accounts/models.py#L173-L188
train
49,854
ozgurgunes/django-manifest
manifest/accounts/models.py
AccountActivationMixin.activation_key_expired
def activation_key_expired(self): """ Checks if activation key is expired. Returns ``True`` when the ``activation_key`` of the user is expired and ``False`` if the key is still valid. The key is expired when it's set to the value defined in ``ACCOUNTS_ACTIVATED`` or ``activation_key_created`` is beyond the amount of days defined in ``ACCOUNTS_ACTIVATION_DAYS``. """ expiration_days = datetime.timedelta( days=defaults.ACCOUNTS_ACTIVATION_DAYS) expiration_date = self.date_joined + expiration_days if self.activation_key == defaults.ACCOUNTS_ACTIVATED: return True if get_datetime_now() >= expiration_date: return True return False
python
def activation_key_expired(self): """ Checks if activation key is expired. Returns ``True`` when the ``activation_key`` of the user is expired and ``False`` if the key is still valid. The key is expired when it's set to the value defined in ``ACCOUNTS_ACTIVATED`` or ``activation_key_created`` is beyond the amount of days defined in ``ACCOUNTS_ACTIVATION_DAYS``. """ expiration_days = datetime.timedelta( days=defaults.ACCOUNTS_ACTIVATION_DAYS) expiration_date = self.date_joined + expiration_days if self.activation_key == defaults.ACCOUNTS_ACTIVATED: return True if get_datetime_now() >= expiration_date: return True return False
[ "def", "activation_key_expired", "(", "self", ")", ":", "expiration_days", "=", "datetime", ".", "timedelta", "(", "days", "=", "defaults", ".", "ACCOUNTS_ACTIVATION_DAYS", ")", "expiration_date", "=", "self", ".", "date_joined", "+", "expiration_days", "if", "sel...
Checks if activation key is expired. Returns ``True`` when the ``activation_key`` of the user is expired and ``False`` if the key is still valid. The key is expired when it's set to the value defined in ``ACCOUNTS_ACTIVATED`` or ``activation_key_created`` is beyond the amount of days defined in ``ACCOUNTS_ACTIVATION_DAYS``.
[ "Checks", "if", "activation", "key", "is", "expired", "." ]
9873bbf2a475b76284ad7e36b2b26c92131e72dd
https://github.com/ozgurgunes/django-manifest/blob/9873bbf2a475b76284ad7e36b2b26c92131e72dd/manifest/accounts/models.py#L31-L50
train
49,855
ozgurgunes/django-manifest
manifest/accounts/models.py
AccountActivationMixin.send_activation_email
def send_activation_email(self): """ Sends a activation email to the user. This email is send when the user wants to activate their newly created user. """ context= {'user': self, 'protocol': get_protocol(), 'activation_days': defaults.ACCOUNTS_ACTIVATION_DAYS, 'activation_key': self.activation_key, 'site': Site.objects.get_current()} subject = ''.join(render_to_string( 'accounts/emails/activation_email_subject.txt', context).splitlines()) message = render_to_string( 'accounts/emails/activation_email_message.txt', context) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [self.email,])
python
def send_activation_email(self): """ Sends a activation email to the user. This email is send when the user wants to activate their newly created user. """ context= {'user': self, 'protocol': get_protocol(), 'activation_days': defaults.ACCOUNTS_ACTIVATION_DAYS, 'activation_key': self.activation_key, 'site': Site.objects.get_current()} subject = ''.join(render_to_string( 'accounts/emails/activation_email_subject.txt', context).splitlines()) message = render_to_string( 'accounts/emails/activation_email_message.txt', context) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [self.email,])
[ "def", "send_activation_email", "(", "self", ")", ":", "context", "=", "{", "'user'", ":", "self", ",", "'protocol'", ":", "get_protocol", "(", ")", ",", "'activation_days'", ":", "defaults", ".", "ACCOUNTS_ACTIVATION_DAYS", ",", "'activation_key'", ":", "self",...
Sends a activation email to the user. This email is send when the user wants to activate their newly created user.
[ "Sends", "a", "activation", "email", "to", "the", "user", "." ]
9873bbf2a475b76284ad7e36b2b26c92131e72dd
https://github.com/ozgurgunes/django-manifest/blob/9873bbf2a475b76284ad7e36b2b26c92131e72dd/manifest/accounts/models.py#L52-L76
train
49,856
ozgurgunes/django-manifest
manifest/accounts/models.py
EmailConfirmationMixin.change_email
def change_email(self, email): """ Changes the email address for a user. A user needs to verify this new email address before it becomes active. By storing the new email address in a temporary field -- ``temporary_email`` -- we are able to set this email address after the user has verified it by clicking on the verification URI in the email. This email gets send out by ``send_verification_email``. :param email: The new email address that the user wants to use. """ self.email_unconfirmed = email salt, hash = generate_sha1(self.username) self.email_confirmation_key = hash self.email_confirmation_key_created = get_datetime_now() self.save() # Send email for activation self.send_confirmation_email() return self
python
def change_email(self, email): """ Changes the email address for a user. A user needs to verify this new email address before it becomes active. By storing the new email address in a temporary field -- ``temporary_email`` -- we are able to set this email address after the user has verified it by clicking on the verification URI in the email. This email gets send out by ``send_verification_email``. :param email: The new email address that the user wants to use. """ self.email_unconfirmed = email salt, hash = generate_sha1(self.username) self.email_confirmation_key = hash self.email_confirmation_key_created = get_datetime_now() self.save() # Send email for activation self.send_confirmation_email() return self
[ "def", "change_email", "(", "self", ",", "email", ")", ":", "self", ".", "email_unconfirmed", "=", "email", "salt", ",", "hash", "=", "generate_sha1", "(", "self", ".", "username", ")", "self", ".", "email_confirmation_key", "=", "hash", "self", ".", "emai...
Changes the email address for a user. A user needs to verify this new email address before it becomes active. By storing the new email address in a temporary field -- ``temporary_email`` -- we are able to set this email address after the user has verified it by clicking on the verification URI in the email. This email gets send out by ``send_verification_email``. :param email: The new email address that the user wants to use.
[ "Changes", "the", "email", "address", "for", "a", "user", "." ]
9873bbf2a475b76284ad7e36b2b26c92131e72dd
https://github.com/ozgurgunes/django-manifest/blob/9873bbf2a475b76284ad7e36b2b26c92131e72dd/manifest/accounts/models.py#L99-L123
train
49,857
ozgurgunes/django-manifest
manifest/accounts/models.py
EmailConfirmationMixin.send_confirmation_email
def send_confirmation_email(self): """ Sends an email to confirm the new email address. This method sends out two emails. One to the new email address that contains the ``email_confirmation_key`` which is used to verify this this email address with :func:`User.objects.confirm_email`. The other email is to the old email address to let the user know that a request is made to change this email address. """ context= {'user': self, 'new_email': self.email_unconfirmed, 'protocol': get_protocol(), 'confirmation_key': self.email_confirmation_key, 'site': Site.objects.get_current()} # Email to the old address subject_old = ''.join(render_to_string( 'accounts/emails/confirmation_email_subject_old.txt', context).splitlines()) message_old = render_to_string( 'accounts/emails/confirmation_email_message_old.txt', context) send_mail(subject_old, message_old, settings.DEFAULT_FROM_EMAIL, [self.email]) # Email to the new address subject_new = ''.join(render_to_string( 'accounts/emails/confirmation_email_subject_new.txt', context).splitlines()) message_new = render_to_string( 'accounts/emails/confirmation_email_message_new.txt', context) send_mail(subject_new, message_new, settings.DEFAULT_FROM_EMAIL, [self.email_unconfirmed,])
python
def send_confirmation_email(self): """ Sends an email to confirm the new email address. This method sends out two emails. One to the new email address that contains the ``email_confirmation_key`` which is used to verify this this email address with :func:`User.objects.confirm_email`. The other email is to the old email address to let the user know that a request is made to change this email address. """ context= {'user': self, 'new_email': self.email_unconfirmed, 'protocol': get_protocol(), 'confirmation_key': self.email_confirmation_key, 'site': Site.objects.get_current()} # Email to the old address subject_old = ''.join(render_to_string( 'accounts/emails/confirmation_email_subject_old.txt', context).splitlines()) message_old = render_to_string( 'accounts/emails/confirmation_email_message_old.txt', context) send_mail(subject_old, message_old, settings.DEFAULT_FROM_EMAIL, [self.email]) # Email to the new address subject_new = ''.join(render_to_string( 'accounts/emails/confirmation_email_subject_new.txt', context).splitlines()) message_new = render_to_string( 'accounts/emails/confirmation_email_message_new.txt', context) send_mail(subject_new, message_new, settings.DEFAULT_FROM_EMAIL, [self.email_unconfirmed,])
[ "def", "send_confirmation_email", "(", "self", ")", ":", "context", "=", "{", "'user'", ":", "self", ",", "'new_email'", ":", "self", ".", "email_unconfirmed", ",", "'protocol'", ":", "get_protocol", "(", ")", ",", "'confirmation_key'", ":", "self", ".", "em...
Sends an email to confirm the new email address. This method sends out two emails. One to the new email address that contains the ``email_confirmation_key`` which is used to verify this this email address with :func:`User.objects.confirm_email`. The other email is to the old email address to let the user know that a request is made to change this email address.
[ "Sends", "an", "email", "to", "confirm", "the", "new", "email", "address", "." ]
9873bbf2a475b76284ad7e36b2b26c92131e72dd
https://github.com/ozgurgunes/django-manifest/blob/9873bbf2a475b76284ad7e36b2b26c92131e72dd/manifest/accounts/models.py#L125-L170
train
49,858
ozgurgunes/django-manifest
manifest/accounts/models.py
UserProfileMixin.get_picture_url
def get_picture_url(self): """ Returns the image containing the picture for the user. The picture can be a uploaded image or a Gravatar. Gravatar functionality will only be used when ``ACCOUNTS_GRAVATAR_PICTURE`` is set to ``True``. :return: ``None`` when Gravatar is not used and no default image is supplied by ``ACCOUNTS_GRAVATAR_DEFAULT``. """ # First check for a picture and if any return that. if self.picture: return self.picture.url # Use Gravatar if the user wants to. if defaults.ACCOUNTS_GRAVATAR_PICTURE: return get_gravatar(self.email, defaults.ACCOUNTS_GRAVATAR_SIZE, defaults.ACCOUNTS_GRAVATAR_DEFAULT) # Gravatar not used, check for a default image. else: if defaults.ACCOUNTS_GRAVATAR_DEFAULT not in ['404', 'mm', 'identicon', 'monsterid', 'wavatar']: return defaults.ACCOUNTS_GRAVATAR_DEFAULT else: return None
python
def get_picture_url(self): """ Returns the image containing the picture for the user. The picture can be a uploaded image or a Gravatar. Gravatar functionality will only be used when ``ACCOUNTS_GRAVATAR_PICTURE`` is set to ``True``. :return: ``None`` when Gravatar is not used and no default image is supplied by ``ACCOUNTS_GRAVATAR_DEFAULT``. """ # First check for a picture and if any return that. if self.picture: return self.picture.url # Use Gravatar if the user wants to. if defaults.ACCOUNTS_GRAVATAR_PICTURE: return get_gravatar(self.email, defaults.ACCOUNTS_GRAVATAR_SIZE, defaults.ACCOUNTS_GRAVATAR_DEFAULT) # Gravatar not used, check for a default image. else: if defaults.ACCOUNTS_GRAVATAR_DEFAULT not in ['404', 'mm', 'identicon', 'monsterid', 'wavatar']: return defaults.ACCOUNTS_GRAVATAR_DEFAULT else: return None
[ "def", "get_picture_url", "(", "self", ")", ":", "# First check for a picture and if any return that.", "if", "self", ".", "picture", ":", "return", "self", ".", "picture", ".", "url", "# Use Gravatar if the user wants to.", "if", "defaults", ".", "ACCOUNTS_GRAVATAR_PICTU...
Returns the image containing the picture for the user. The picture can be a uploaded image or a Gravatar. Gravatar functionality will only be used when ``ACCOUNTS_GRAVATAR_PICTURE`` is set to ``True``. :return: ``None`` when Gravatar is not used and no default image is supplied by ``ACCOUNTS_GRAVATAR_DEFAULT``.
[ "Returns", "the", "image", "containing", "the", "picture", "for", "the", "user", "." ]
9873bbf2a475b76284ad7e36b2b26c92131e72dd
https://github.com/ozgurgunes/django-manifest/blob/9873bbf2a475b76284ad7e36b2b26c92131e72dd/manifest/accounts/models.py#L240-L271
train
49,859
ozgurgunes/django-manifest
manifest/accounts/models.py
UserProfileMixin.get_full_name_or_username
def get_full_name_or_username(self): """ Returns the full name of the user, or if none is supplied will return the username. Also looks at ``ACCOUNTS_WITHOUT_USERNAMES`` settings to define if it should return the username or email address when the full name is not supplied. :return: ``String`` containing the full name of the user. If no name is supplied it will return the username or email address depending on the ``ACCOUNTS_WITHOUT_USERNAMES`` setting. """ if self.first_name or self.last_name: # We will return this as translated string. Maybe there are some # countries that first display the last name. name = _(u"%(first_name)s %(last_name)s") % \ {'first_name': self.first_name, 'last_name': self.last_name} else: # Fallback to the username if usernames are used if not defaults.ACCOUNTS_WITHOUT_USERNAMES: name = "%(username)s" % {'username': self.username} else: name = "%(email)s" % {'email': self.email} return name.strip()
python
def get_full_name_or_username(self): """ Returns the full name of the user, or if none is supplied will return the username. Also looks at ``ACCOUNTS_WITHOUT_USERNAMES`` settings to define if it should return the username or email address when the full name is not supplied. :return: ``String`` containing the full name of the user. If no name is supplied it will return the username or email address depending on the ``ACCOUNTS_WITHOUT_USERNAMES`` setting. """ if self.first_name or self.last_name: # We will return this as translated string. Maybe there are some # countries that first display the last name. name = _(u"%(first_name)s %(last_name)s") % \ {'first_name': self.first_name, 'last_name': self.last_name} else: # Fallback to the username if usernames are used if not defaults.ACCOUNTS_WITHOUT_USERNAMES: name = "%(username)s" % {'username': self.username} else: name = "%(email)s" % {'email': self.email} return name.strip()
[ "def", "get_full_name_or_username", "(", "self", ")", ":", "if", "self", ".", "first_name", "or", "self", ".", "last_name", ":", "# We will return this as translated string. Maybe there are some", "# countries that first display the last name.", "name", "=", "_", "(", "u\"%...
Returns the full name of the user, or if none is supplied will return the username. Also looks at ``ACCOUNTS_WITHOUT_USERNAMES`` settings to define if it should return the username or email address when the full name is not supplied. :return: ``String`` containing the full name of the user. If no name is supplied it will return the username or email address depending on the ``ACCOUNTS_WITHOUT_USERNAMES`` setting.
[ "Returns", "the", "full", "name", "of", "the", "user", "or", "if", "none", "is", "supplied", "will", "return", "the", "username", "." ]
9873bbf2a475b76284ad7e36b2b26c92131e72dd
https://github.com/ozgurgunes/django-manifest/blob/9873bbf2a475b76284ad7e36b2b26c92131e72dd/manifest/accounts/models.py#L273-L300
train
49,860
contentful-labs/contentful.py
contentful/cda/client.py
Client.resolve
def resolve(self, link_resource_type, resource_id, array=None): """Resolve a link to a CDA resource. Provided an `array` argument, attempt to retrieve the resource from the `mapped_items` section of that array (containing both included and regular resources), in case the resource cannot be found in the array (or if no `array` was provided) - attempt to fetch the resource from the API by issuing a network request. :param link_resource_type: (str) Resource type as str. :param resource_id: (str) Remote ID of the linked resource. :param array: (:class:`.Array`) Optional array resource. :return: :class:`.Resource` subclass, `None` if it cannot be retrieved. """ result = None if array is not None: container = array.items_mapped.get(link_resource_type) result = container.get(resource_id) if result is None: clz = utils.class_for_type(link_resource_type) result = self.fetch(clz).where({'sys.id': resource_id}).first() return result
python
def resolve(self, link_resource_type, resource_id, array=None): """Resolve a link to a CDA resource. Provided an `array` argument, attempt to retrieve the resource from the `mapped_items` section of that array (containing both included and regular resources), in case the resource cannot be found in the array (or if no `array` was provided) - attempt to fetch the resource from the API by issuing a network request. :param link_resource_type: (str) Resource type as str. :param resource_id: (str) Remote ID of the linked resource. :param array: (:class:`.Array`) Optional array resource. :return: :class:`.Resource` subclass, `None` if it cannot be retrieved. """ result = None if array is not None: container = array.items_mapped.get(link_resource_type) result = container.get(resource_id) if result is None: clz = utils.class_for_type(link_resource_type) result = self.fetch(clz).where({'sys.id': resource_id}).first() return result
[ "def", "resolve", "(", "self", ",", "link_resource_type", ",", "resource_id", ",", "array", "=", "None", ")", ":", "result", "=", "None", "if", "array", "is", "not", "None", ":", "container", "=", "array", ".", "items_mapped", ".", "get", "(", "link_reso...
Resolve a link to a CDA resource. Provided an `array` argument, attempt to retrieve the resource from the `mapped_items` section of that array (containing both included and regular resources), in case the resource cannot be found in the array (or if no `array` was provided) - attempt to fetch the resource from the API by issuing a network request. :param link_resource_type: (str) Resource type as str. :param resource_id: (str) Remote ID of the linked resource. :param array: (:class:`.Array`) Optional array resource. :return: :class:`.Resource` subclass, `None` if it cannot be retrieved.
[ "Resolve", "a", "link", "to", "a", "CDA", "resource", "." ]
d9eb4a68abcad33e4766e2be8c7b35e605210b5a
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/client.py#L109-L132
train
49,861
contentful-labs/contentful.py
contentful/cda/client.py
Client.resolve_dict_link
def resolve_dict_link(self, dct, array=None): """Convenience method for resolving links given a dict object. Extract link values and pass to the :func:`.resolve` method of this class. :param dct: (dict) Dictionary with the link data. :param array: (:class:`.Array`) Optional array resource. :return: :class:`.Resource` subclass, `None` if it cannot be retrieved. """ sys = dct.get('sys') return self.resolve(sys['linkType'], sys['id'], array) if sys is not None else None
python
def resolve_dict_link(self, dct, array=None): """Convenience method for resolving links given a dict object. Extract link values and pass to the :func:`.resolve` method of this class. :param dct: (dict) Dictionary with the link data. :param array: (:class:`.Array`) Optional array resource. :return: :class:`.Resource` subclass, `None` if it cannot be retrieved. """ sys = dct.get('sys') return self.resolve(sys['linkType'], sys['id'], array) if sys is not None else None
[ "def", "resolve_dict_link", "(", "self", ",", "dct", ",", "array", "=", "None", ")", ":", "sys", "=", "dct", ".", "get", "(", "'sys'", ")", "return", "self", ".", "resolve", "(", "sys", "[", "'linkType'", "]", ",", "sys", "[", "'id'", "]", ",", "...
Convenience method for resolving links given a dict object. Extract link values and pass to the :func:`.resolve` method of this class. :param dct: (dict) Dictionary with the link data. :param array: (:class:`.Array`) Optional array resource. :return: :class:`.Resource` subclass, `None` if it cannot be retrieved.
[ "Convenience", "method", "for", "resolving", "links", "given", "a", "dict", "object", "." ]
d9eb4a68abcad33e4766e2be8c7b35e605210b5a
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/client.py#L145-L155
train
49,862
contentful-labs/contentful.py
contentful/cda/client.py
RequestArray.all
def all(self): """Attempt to retrieve all available resources matching this request. :return: Result instance as returned by the :class:`.Dispatcher`. """ result = self.invoke() if self.resolve_links: result.resolve_links() return result
python
def all(self): """Attempt to retrieve all available resources matching this request. :return: Result instance as returned by the :class:`.Dispatcher`. """ result = self.invoke() if self.resolve_links: result.resolve_links() return result
[ "def", "all", "(", "self", ")", ":", "result", "=", "self", ".", "invoke", "(", ")", "if", "self", ".", "resolve_links", ":", "result", ".", "resolve_links", "(", ")", "return", "result" ]
Attempt to retrieve all available resources matching this request. :return: Result instance as returned by the :class:`.Dispatcher`.
[ "Attempt", "to", "retrieve", "all", "available", "resources", "matching", "this", "request", "." ]
d9eb4a68abcad33e4766e2be8c7b35e605210b5a
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/client.py#L263-L272
train
49,863
contentful-labs/contentful.py
contentful/cda/client.py
RequestArray.first
def first(self): """Attempt to retrieve only the first resource matching this request. :return: Result instance, or `None` if there are no matching resources. """ self.params['limit'] = 1 result = self.all() return result.items[0] if result.total > 0 else None
python
def first(self): """Attempt to retrieve only the first resource matching this request. :return: Result instance, or `None` if there are no matching resources. """ self.params['limit'] = 1 result = self.all() return result.items[0] if result.total > 0 else None
[ "def", "first", "(", "self", ")", ":", "self", ".", "params", "[", "'limit'", "]", "=", "1", "result", "=", "self", ".", "all", "(", ")", "return", "result", ".", "items", "[", "0", "]", "if", "result", ".", "total", ">", "0", "else", "None" ]
Attempt to retrieve only the first resource matching this request. :return: Result instance, or `None` if there are no matching resources.
[ "Attempt", "to", "retrieve", "only", "the", "first", "resource", "matching", "this", "request", "." ]
d9eb4a68abcad33e4766e2be8c7b35e605210b5a
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/client.py#L274-L281
train
49,864
contentful-labs/contentful.py
contentful/cda/client.py
RequestArray.where
def where(self, params): """Set a dict of parameters to be passed to the API when invoking this request. :param params: (dict) query parameters. :return: this :class:`.RequestArray` instance for convenience. """ self.params = dict(self.params, **params) # params overrides self.params return self
python
def where(self, params): """Set a dict of parameters to be passed to the API when invoking this request. :param params: (dict) query parameters. :return: this :class:`.RequestArray` instance for convenience. """ self.params = dict(self.params, **params) # params overrides self.params return self
[ "def", "where", "(", "self", ",", "params", ")", ":", "self", ".", "params", "=", "dict", "(", "self", ".", "params", ",", "*", "*", "params", ")", "# params overrides self.params", "return", "self" ]
Set a dict of parameters to be passed to the API when invoking this request. :param params: (dict) query parameters. :return: this :class:`.RequestArray` instance for convenience.
[ "Set", "a", "dict", "of", "parameters", "to", "be", "passed", "to", "the", "API", "when", "invoking", "this", "request", "." ]
d9eb4a68abcad33e4766e2be8c7b35e605210b5a
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/client.py#L283-L290
train
49,865
dusktreader/py-buzz
examples/require_condition.py
complex_require_condition
def complex_require_condition(): """ This function demonstrates a more complex usage of the require_condition function. It shows argument interpolation and handling a more complex boolean expression """ print("Demonstrating complex require_condition example") val = 64 Buzz.require_condition(is_even(val), 'This condition should pass') val = 81 Buzz.require_condition(is_even(val), 'Value {val} is not even', val=val)
python
def complex_require_condition(): """ This function demonstrates a more complex usage of the require_condition function. It shows argument interpolation and handling a more complex boolean expression """ print("Demonstrating complex require_condition example") val = 64 Buzz.require_condition(is_even(val), 'This condition should pass') val = 81 Buzz.require_condition(is_even(val), 'Value {val} is not even', val=val)
[ "def", "complex_require_condition", "(", ")", ":", "print", "(", "\"Demonstrating complex require_condition example\"", ")", "val", "=", "64", "Buzz", ".", "require_condition", "(", "is_even", "(", "val", ")", ",", "'This condition should pass'", ")", "val", "=", "8...
This function demonstrates a more complex usage of the require_condition function. It shows argument interpolation and handling a more complex boolean expression
[ "This", "function", "demonstrates", "a", "more", "complex", "usage", "of", "the", "require_condition", "function", ".", "It", "shows", "argument", "interpolation", "and", "handling", "a", "more", "complex", "boolean", "expression" ]
f2fd97abe158a1688188647992a5be6531058ec3
https://github.com/dusktreader/py-buzz/blob/f2fd97abe158a1688188647992a5be6531058ec3/examples/require_condition.py#L27-L38
train
49,866
zeroSteiner/smoke-zephyr
smoke_zephyr/configuration.py
MemoryConfiguration.get
def get(self, item_name): """ Retrieve the value of an option. :param str item_name: The name of the option to retrieve. :return: The value of *item_name* in the configuration. """ if self.prefix: item_name = self.prefix + self.seperator + item_name item_names = item_name.split(self.seperator) node = self._storage for item_name in item_names: node = node[item_name] return node
python
def get(self, item_name): """ Retrieve the value of an option. :param str item_name: The name of the option to retrieve. :return: The value of *item_name* in the configuration. """ if self.prefix: item_name = self.prefix + self.seperator + item_name item_names = item_name.split(self.seperator) node = self._storage for item_name in item_names: node = node[item_name] return node
[ "def", "get", "(", "self", ",", "item_name", ")", ":", "if", "self", ".", "prefix", ":", "item_name", "=", "self", ".", "prefix", "+", "self", ".", "seperator", "+", "item_name", "item_names", "=", "item_name", ".", "split", "(", "self", ".", "seperato...
Retrieve the value of an option. :param str item_name: The name of the option to retrieve. :return: The value of *item_name* in the configuration.
[ "Retrieve", "the", "value", "of", "an", "option", "." ]
a6d2498aeacc72ee52e7806f783a4d83d537ffb2
https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/configuration.py#L80-L93
train
49,867
zeroSteiner/smoke-zephyr
smoke_zephyr/configuration.py
MemoryConfiguration.has_option
def has_option(self, option_name): """ Check that an option exists. :param str option_name: The name of the option to check. :return: True of the option exists in the configuration. :rtype: bool """ if self.prefix: option_name = self.prefix + self.seperator + option_name item_names = option_name.split(self.seperator) node = self._storage for item_name in item_names: if node is None: return False if not item_name in node: return False node = node[item_name] return True
python
def has_option(self, option_name): """ Check that an option exists. :param str option_name: The name of the option to check. :return: True of the option exists in the configuration. :rtype: bool """ if self.prefix: option_name = self.prefix + self.seperator + option_name item_names = option_name.split(self.seperator) node = self._storage for item_name in item_names: if node is None: return False if not item_name in node: return False node = node[item_name] return True
[ "def", "has_option", "(", "self", ",", "option_name", ")", ":", "if", "self", ".", "prefix", ":", "option_name", "=", "self", ".", "prefix", "+", "self", ".", "seperator", "+", "option_name", "item_names", "=", "option_name", ".", "split", "(", "self", "...
Check that an option exists. :param str option_name: The name of the option to check. :return: True of the option exists in the configuration. :rtype: bool
[ "Check", "that", "an", "option", "exists", "." ]
a6d2498aeacc72ee52e7806f783a4d83d537ffb2
https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/configuration.py#L118-L136
train
49,868
zeroSteiner/smoke-zephyr
smoke_zephyr/configuration.py
MemoryConfiguration.has_section
def has_section(self, section_name): """ Checks that an option exists and that it contains sub options. :param str section_name: The name of the section to check. :return: True if the section exists. :rtype: dict """ if not self.has_option(section_name): return False return isinstance(self.get(section_name), dict)
python
def has_section(self, section_name): """ Checks that an option exists and that it contains sub options. :param str section_name: The name of the section to check. :return: True if the section exists. :rtype: dict """ if not self.has_option(section_name): return False return isinstance(self.get(section_name), dict)
[ "def", "has_section", "(", "self", ",", "section_name", ")", ":", "if", "not", "self", ".", "has_option", "(", "section_name", ")", ":", "return", "False", "return", "isinstance", "(", "self", ".", "get", "(", "section_name", ")", ",", "dict", ")" ]
Checks that an option exists and that it contains sub options. :param str section_name: The name of the section to check. :return: True if the section exists. :rtype: dict
[ "Checks", "that", "an", "option", "exists", "and", "that", "it", "contains", "sub", "options", "." ]
a6d2498aeacc72ee52e7806f783a4d83d537ffb2
https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/configuration.py#L138-L148
train
49,869
zeroSteiner/smoke-zephyr
smoke_zephyr/configuration.py
MemoryConfiguration.set
def set(self, item_name, item_value): """ Sets the value of an option in the configuration. :param str item_name: The name of the option to set. :param item_value: The value of the option to set. """ if self.prefix: item_name = self.prefix + self.seperator + item_name item_names = item_name.split(self.seperator) item_last = item_names.pop() node = self._storage for item_name in item_names: if not item_name in node: node[item_name] = {} node = node[item_name] node[item_last] = item_value return
python
def set(self, item_name, item_value): """ Sets the value of an option in the configuration. :param str item_name: The name of the option to set. :param item_value: The value of the option to set. """ if self.prefix: item_name = self.prefix + self.seperator + item_name item_names = item_name.split(self.seperator) item_last = item_names.pop() node = self._storage for item_name in item_names: if not item_name in node: node[item_name] = {} node = node[item_name] node[item_last] = item_value return
[ "def", "set", "(", "self", ",", "item_name", ",", "item_value", ")", ":", "if", "self", ".", "prefix", ":", "item_name", "=", "self", ".", "prefix", "+", "self", ".", "seperator", "+", "item_name", "item_names", "=", "item_name", ".", "split", "(", "se...
Sets the value of an option in the configuration. :param str item_name: The name of the option to set. :param item_value: The value of the option to set.
[ "Sets", "the", "value", "of", "an", "option", "in", "the", "configuration", "." ]
a6d2498aeacc72ee52e7806f783a4d83d537ffb2
https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/configuration.py#L150-L167
train
49,870
zeroSteiner/smoke-zephyr
smoke_zephyr/configuration.py
Configuration.get_missing
def get_missing(self, verify_file): """ Use a verification configuration which has a list of required options and their respective types. This information is used to identify missing and incompatible options in the loaded configuration. :param str verify_file: The file to load for verification data. :return: A dictionary of missing and incompatible settings. :rtype: dict """ vconf = Configuration(verify_file) missing = {} for setting, setting_type in vconf.get('settings').items(): if not self.has_option(setting): missing['missing'] = missing.get('settings', []) missing['missing'].append(setting) elif not type(self.get(setting)).__name__ == setting_type: missing['incompatible'] = missing.get('incompatible', []) missing['incompatible'].append((setting, setting_type)) return missing
python
def get_missing(self, verify_file): """ Use a verification configuration which has a list of required options and their respective types. This information is used to identify missing and incompatible options in the loaded configuration. :param str verify_file: The file to load for verification data. :return: A dictionary of missing and incompatible settings. :rtype: dict """ vconf = Configuration(verify_file) missing = {} for setting, setting_type in vconf.get('settings').items(): if not self.has_option(setting): missing['missing'] = missing.get('settings', []) missing['missing'].append(setting) elif not type(self.get(setting)).__name__ == setting_type: missing['incompatible'] = missing.get('incompatible', []) missing['incompatible'].append((setting, setting_type)) return missing
[ "def", "get_missing", "(", "self", ",", "verify_file", ")", ":", "vconf", "=", "Configuration", "(", "verify_file", ")", "missing", "=", "{", "}", "for", "setting", ",", "setting_type", "in", "vconf", ".", "get", "(", "'settings'", ")", ".", "items", "("...
Use a verification configuration which has a list of required options and their respective types. This information is used to identify missing and incompatible options in the loaded configuration. :param str verify_file: The file to load for verification data. :return: A dictionary of missing and incompatible settings. :rtype: dict
[ "Use", "a", "verification", "configuration", "which", "has", "a", "list", "of", "required", "options", "and", "their", "respective", "types", ".", "This", "information", "is", "used", "to", "identify", "missing", "and", "incompatible", "options", "in", "the", ...
a6d2498aeacc72ee52e7806f783a4d83d537ffb2
https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/configuration.py#L197-L216
train
49,871
zeroSteiner/smoke-zephyr
smoke_zephyr/configuration.py
Configuration.save
def save(self): """ Save the current configuration to disk. """ with open(self.configuration_file, 'w') as file_h: file_h.write(self._serializer('dumps', self._storage))
python
def save(self): """ Save the current configuration to disk. """ with open(self.configuration_file, 'w') as file_h: file_h.write(self._serializer('dumps', self._storage))
[ "def", "save", "(", "self", ")", ":", "with", "open", "(", "self", ".", "configuration_file", ",", "'w'", ")", "as", "file_h", ":", "file_h", ".", "write", "(", "self", ".", "_serializer", "(", "'dumps'", ",", "self", ".", "_storage", ")", ")" ]
Save the current configuration to disk.
[ "Save", "the", "current", "configuration", "to", "disk", "." ]
a6d2498aeacc72ee52e7806f783a4d83d537ffb2
https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/configuration.py#L218-L223
train
49,872
ARMmbed/autoversion
src/auto_version/auto_version_tool.py
replace_lines
def replace_lines(regexer, handler, lines): """Uses replacement handler to perform replacements on lines of text First we strip off all whitespace We run the replacement on a clean 'content' string Finally we replace the original content with the replaced version This ensures that we retain the correct whitespace from the original line """ result = [] for line in lines: content = line.strip() replaced = regexer.sub(handler, content) result.append(line.replace(content, replaced, 1)) return result
python
def replace_lines(regexer, handler, lines): """Uses replacement handler to perform replacements on lines of text First we strip off all whitespace We run the replacement on a clean 'content' string Finally we replace the original content with the replaced version This ensures that we retain the correct whitespace from the original line """ result = [] for line in lines: content = line.strip() replaced = regexer.sub(handler, content) result.append(line.replace(content, replaced, 1)) return result
[ "def", "replace_lines", "(", "regexer", ",", "handler", ",", "lines", ")", ":", "result", "=", "[", "]", "for", "line", "in", "lines", ":", "content", "=", "line", ".", "strip", "(", ")", "replaced", "=", "regexer", ".", "sub", "(", "handler", ",", ...
Uses replacement handler to perform replacements on lines of text First we strip off all whitespace We run the replacement on a clean 'content' string Finally we replace the original content with the replaced version This ensures that we retain the correct whitespace from the original line
[ "Uses", "replacement", "handler", "to", "perform", "replacements", "on", "lines", "of", "text" ]
c5b127d2059c8219f5637fe45bf9e1be3a0af2aa
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/auto_version_tool.py#L37-L50
train
49,873
ARMmbed/autoversion
src/auto_version/auto_version_tool.py
write_targets
def write_targets(targets, **params): """Writes version info into version file""" handler = ReplacementHandler(**params) for target, regexer in regexer_for_targets(targets): with open(target) as fh: lines = fh.readlines() lines = replace_lines(regexer, handler, lines) with open(target, "w") as fh: fh.writelines(lines) if handler.missing: raise Exception( "Failed to complete all expected replacements: %r" % handler.missing )
python
def write_targets(targets, **params): """Writes version info into version file""" handler = ReplacementHandler(**params) for target, regexer in regexer_for_targets(targets): with open(target) as fh: lines = fh.readlines() lines = replace_lines(regexer, handler, lines) with open(target, "w") as fh: fh.writelines(lines) if handler.missing: raise Exception( "Failed to complete all expected replacements: %r" % handler.missing )
[ "def", "write_targets", "(", "targets", ",", "*", "*", "params", ")", ":", "handler", "=", "ReplacementHandler", "(", "*", "*", "params", ")", "for", "target", ",", "regexer", "in", "regexer_for_targets", "(", "targets", ")", ":", "with", "open", "(", "t...
Writes version info into version file
[ "Writes", "version", "info", "into", "version", "file" ]
c5b127d2059c8219f5637fe45bf9e1be3a0af2aa
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/auto_version_tool.py#L53-L65
train
49,874
ARMmbed/autoversion
src/auto_version/auto_version_tool.py
regexer_for_targets
def regexer_for_targets(targets): """Pairs up target files with their correct regex""" for target in targets: path, file_ext = os.path.splitext(target) regexer = config.regexers[file_ext] yield target, regexer
python
def regexer_for_targets(targets): """Pairs up target files with their correct regex""" for target in targets: path, file_ext = os.path.splitext(target) regexer = config.regexers[file_ext] yield target, regexer
[ "def", "regexer_for_targets", "(", "targets", ")", ":", "for", "target", "in", "targets", ":", "path", ",", "file_ext", "=", "os", ".", "path", ".", "splitext", "(", "target", ")", "regexer", "=", "config", ".", "regexers", "[", "file_ext", "]", "yield",...
Pairs up target files with their correct regex
[ "Pairs", "up", "target", "files", "with", "their", "correct", "regex" ]
c5b127d2059c8219f5637fe45bf9e1be3a0af2aa
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/auto_version_tool.py#L68-L73
train
49,875
ARMmbed/autoversion
src/auto_version/auto_version_tool.py
extract_keypairs
def extract_keypairs(lines, regexer): """Given some lines of text, extract key-value pairs from them""" updates = {} for line in lines: # for consistency we must match the replacer and strip whitespace / newlines match = regexer.match(line.strip()) if not match: continue k_v = match.groupdict() updates[k_v[Constants.KEY_GROUP]] = k_v[Constants.VALUE_GROUP] return updates
python
def extract_keypairs(lines, regexer): """Given some lines of text, extract key-value pairs from them""" updates = {} for line in lines: # for consistency we must match the replacer and strip whitespace / newlines match = regexer.match(line.strip()) if not match: continue k_v = match.groupdict() updates[k_v[Constants.KEY_GROUP]] = k_v[Constants.VALUE_GROUP] return updates
[ "def", "extract_keypairs", "(", "lines", ",", "regexer", ")", ":", "updates", "=", "{", "}", "for", "line", "in", "lines", ":", "# for consistency we must match the replacer and strip whitespace / newlines", "match", "=", "regexer", ".", "match", "(", "line", ".", ...
Given some lines of text, extract key-value pairs from them
[ "Given", "some", "lines", "of", "text", "extract", "key", "-", "value", "pairs", "from", "them" ]
c5b127d2059c8219f5637fe45bf9e1be3a0af2aa
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/auto_version_tool.py#L76-L86
train
49,876
ARMmbed/autoversion
src/auto_version/auto_version_tool.py
read_targets
def read_targets(targets): """Reads generic key-value pairs from input files""" results = {} for target, regexer in regexer_for_targets(targets): with open(target) as fh: results.update(extract_keypairs(fh.readlines(), regexer)) return results
python
def read_targets(targets): """Reads generic key-value pairs from input files""" results = {} for target, regexer in regexer_for_targets(targets): with open(target) as fh: results.update(extract_keypairs(fh.readlines(), regexer)) return results
[ "def", "read_targets", "(", "targets", ")", ":", "results", "=", "{", "}", "for", "target", ",", "regexer", "in", "regexer_for_targets", "(", "targets", ")", ":", "with", "open", "(", "target", ")", "as", "fh", ":", "results", ".", "update", "(", "extr...
Reads generic key-value pairs from input files
[ "Reads", "generic", "key", "-", "value", "pairs", "from", "input", "files" ]
c5b127d2059c8219f5637fe45bf9e1be3a0af2aa
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/auto_version_tool.py#L89-L95
train
49,877
ARMmbed/autoversion
src/auto_version/auto_version_tool.py
detect_file_triggers
def detect_file_triggers(trigger_patterns): """The existence of files matching configured globs will trigger a version bump""" triggers = set() for trigger, pattern in trigger_patterns.items(): matches = glob.glob(pattern) if matches: _LOG.debug("trigger: %s bump from %r\n\t%s", trigger, pattern, matches) triggers.add(trigger) else: _LOG.debug("trigger: no match on %r", pattern) return triggers
python
def detect_file_triggers(trigger_patterns): """The existence of files matching configured globs will trigger a version bump""" triggers = set() for trigger, pattern in trigger_patterns.items(): matches = glob.glob(pattern) if matches: _LOG.debug("trigger: %s bump from %r\n\t%s", trigger, pattern, matches) triggers.add(trigger) else: _LOG.debug("trigger: no match on %r", pattern) return triggers
[ "def", "detect_file_triggers", "(", "trigger_patterns", ")", ":", "triggers", "=", "set", "(", ")", "for", "trigger", ",", "pattern", "in", "trigger_patterns", ".", "items", "(", ")", ":", "matches", "=", "glob", ".", "glob", "(", "pattern", ")", "if", "...
The existence of files matching configured globs will trigger a version bump
[ "The", "existence", "of", "files", "matching", "configured", "globs", "will", "trigger", "a", "version", "bump" ]
c5b127d2059c8219f5637fe45bf9e1be3a0af2aa
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/auto_version_tool.py#L98-L108
train
49,878
ARMmbed/autoversion
src/auto_version/auto_version_tool.py
get_all_triggers
def get_all_triggers(bump, file_triggers): """Aggregated set of significant figures to bump""" triggers = set() if file_triggers: triggers = triggers.union(detect_file_triggers(config.trigger_patterns)) if bump: _LOG.debug("trigger: %s bump requested", bump) triggers.add(bump) return triggers
python
def get_all_triggers(bump, file_triggers): """Aggregated set of significant figures to bump""" triggers = set() if file_triggers: triggers = triggers.union(detect_file_triggers(config.trigger_patterns)) if bump: _LOG.debug("trigger: %s bump requested", bump) triggers.add(bump) return triggers
[ "def", "get_all_triggers", "(", "bump", ",", "file_triggers", ")", ":", "triggers", "=", "set", "(", ")", "if", "file_triggers", ":", "triggers", "=", "triggers", ".", "union", "(", "detect_file_triggers", "(", "config", ".", "trigger_patterns", ")", ")", "i...
Aggregated set of significant figures to bump
[ "Aggregated", "set", "of", "significant", "figures", "to", "bump" ]
c5b127d2059c8219f5637fe45bf9e1be3a0af2aa
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/auto_version_tool.py#L111-L119
train
49,879
ARMmbed/autoversion
src/auto_version/auto_version_tool.py
get_lock_behaviour
def get_lock_behaviour(triggers, all_data, lock): """Binary state lock protects from version increments if set""" updates = {} lock_key = config._forward_aliases.get(Constants.VERSION_LOCK_FIELD) # if we are explicitly setting or locking the version, then set the lock field True anyway if lock: updates[Constants.VERSION_LOCK_FIELD] = config.VERSION_LOCK_VALUE elif ( triggers and lock_key and str(all_data.get(lock_key)) == str(config.VERSION_LOCK_VALUE) ): triggers.clear() updates[Constants.VERSION_LOCK_FIELD] = config.VERSION_UNLOCK_VALUE return updates
python
def get_lock_behaviour(triggers, all_data, lock): """Binary state lock protects from version increments if set""" updates = {} lock_key = config._forward_aliases.get(Constants.VERSION_LOCK_FIELD) # if we are explicitly setting or locking the version, then set the lock field True anyway if lock: updates[Constants.VERSION_LOCK_FIELD] = config.VERSION_LOCK_VALUE elif ( triggers and lock_key and str(all_data.get(lock_key)) == str(config.VERSION_LOCK_VALUE) ): triggers.clear() updates[Constants.VERSION_LOCK_FIELD] = config.VERSION_UNLOCK_VALUE return updates
[ "def", "get_lock_behaviour", "(", "triggers", ",", "all_data", ",", "lock", ")", ":", "updates", "=", "{", "}", "lock_key", "=", "config", ".", "_forward_aliases", ".", "get", "(", "Constants", ".", "VERSION_LOCK_FIELD", ")", "# if we are explicitly setting or loc...
Binary state lock protects from version increments if set
[ "Binary", "state", "lock", "protects", "from", "version", "increments", "if", "set" ]
c5b127d2059c8219f5637fe45bf9e1be3a0af2aa
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/auto_version_tool.py#L122-L136
train
49,880
ARMmbed/autoversion
src/auto_version/auto_version_tool.py
get_final_version_string
def get_final_version_string(release_mode, semver, commit_count=0): """Generates update dictionary entries for the version string""" version_string = ".".join(semver) maybe_dev_version_string = version_string updates = {} if release_mode: # in production, we have something like `1.2.3`, as well as a flag e.g. PRODUCTION=True updates[Constants.RELEASE_FIELD] = config.RELEASED_VALUE else: # in dev mode, we have a dev marker e.g. `1.2.3.dev678` maybe_dev_version_string = config.DEVMODE_TEMPLATE.format( version=version_string, count=commit_count ) # make available all components of the semantic version including the full string updates[Constants.VERSION_FIELD] = maybe_dev_version_string updates[Constants.VERSION_STRICT_FIELD] = version_string return updates
python
def get_final_version_string(release_mode, semver, commit_count=0): """Generates update dictionary entries for the version string""" version_string = ".".join(semver) maybe_dev_version_string = version_string updates = {} if release_mode: # in production, we have something like `1.2.3`, as well as a flag e.g. PRODUCTION=True updates[Constants.RELEASE_FIELD] = config.RELEASED_VALUE else: # in dev mode, we have a dev marker e.g. `1.2.3.dev678` maybe_dev_version_string = config.DEVMODE_TEMPLATE.format( version=version_string, count=commit_count ) # make available all components of the semantic version including the full string updates[Constants.VERSION_FIELD] = maybe_dev_version_string updates[Constants.VERSION_STRICT_FIELD] = version_string return updates
[ "def", "get_final_version_string", "(", "release_mode", ",", "semver", ",", "commit_count", "=", "0", ")", ":", "version_string", "=", "\".\"", ".", "join", "(", "semver", ")", "maybe_dev_version_string", "=", "version_string", "updates", "=", "{", "}", "if", ...
Generates update dictionary entries for the version string
[ "Generates", "update", "dictionary", "entries", "for", "the", "version", "string" ]
c5b127d2059c8219f5637fe45bf9e1be3a0af2aa
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/auto_version_tool.py#L139-L156
train
49,881
ARMmbed/autoversion
src/auto_version/auto_version_tool.py
get_dvcs_info
def get_dvcs_info(): """Gets current repository info from git""" cmd = "git rev-list --count HEAD" commit_count = str( int(subprocess.check_output(shlex.split(cmd)).decode("utf8").strip()) ) cmd = "git rev-parse HEAD" commit = str(subprocess.check_output(shlex.split(cmd)).decode("utf8").strip()) return {Constants.COMMIT_FIELD: commit, Constants.COMMIT_COUNT_FIELD: commit_count}
python
def get_dvcs_info(): """Gets current repository info from git""" cmd = "git rev-list --count HEAD" commit_count = str( int(subprocess.check_output(shlex.split(cmd)).decode("utf8").strip()) ) cmd = "git rev-parse HEAD" commit = str(subprocess.check_output(shlex.split(cmd)).decode("utf8").strip()) return {Constants.COMMIT_FIELD: commit, Constants.COMMIT_COUNT_FIELD: commit_count}
[ "def", "get_dvcs_info", "(", ")", ":", "cmd", "=", "\"git rev-list --count HEAD\"", "commit_count", "=", "str", "(", "int", "(", "subprocess", ".", "check_output", "(", "shlex", ".", "split", "(", "cmd", ")", ")", ".", "decode", "(", "\"utf8\"", ")", ".", ...
Gets current repository info from git
[ "Gets", "current", "repository", "info", "from", "git" ]
c5b127d2059c8219f5637fe45bf9e1be3a0af2aa
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/auto_version_tool.py#L159-L167
train
49,882
Clinical-Genomics/trailblazer
trailblazer/cli/core.py
log_cmd
def log_cmd(context, sampleinfo, sacct, quiet, config): """Log an analysis. CONFIG: MIP config file for an analysis """ log_analysis = LogAnalysis(context.obj['store']) try: new_run = log_analysis(config, sampleinfo=sampleinfo, sacct=sacct) except MissingFileError as error: click.echo(click.style(f"Skipping, missing Sacct file: {error.message}", fg='yellow')) return except KeyError as error: print(click.style(f"unexpected output, missing key: {error.args[0]}", fg='yellow')) return if new_run is None: if not quiet: click.echo(click.style('Analysis already logged', fg='yellow')) else: message = f"New log added: {new_run.family} ({new_run.id}) - {new_run.status}" click.echo(click.style(message, fg='green'))
python
def log_cmd(context, sampleinfo, sacct, quiet, config): """Log an analysis. CONFIG: MIP config file for an analysis """ log_analysis = LogAnalysis(context.obj['store']) try: new_run = log_analysis(config, sampleinfo=sampleinfo, sacct=sacct) except MissingFileError as error: click.echo(click.style(f"Skipping, missing Sacct file: {error.message}", fg='yellow')) return except KeyError as error: print(click.style(f"unexpected output, missing key: {error.args[0]}", fg='yellow')) return if new_run is None: if not quiet: click.echo(click.style('Analysis already logged', fg='yellow')) else: message = f"New log added: {new_run.family} ({new_run.id}) - {new_run.status}" click.echo(click.style(message, fg='green'))
[ "def", "log_cmd", "(", "context", ",", "sampleinfo", ",", "sacct", ",", "quiet", ",", "config", ")", ":", "log_analysis", "=", "LogAnalysis", "(", "context", ".", "obj", "[", "'store'", "]", ")", "try", ":", "new_run", "=", "log_analysis", "(", "config",...
Log an analysis. CONFIG: MIP config file for an analysis
[ "Log", "an", "analysis", "." ]
27f3cd21043a1077bd7029e85783459a50a7b798
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/cli/core.py#L49-L68
train
49,883
Clinical-Genomics/trailblazer
trailblazer/cli/core.py
start
def start(context, mip_config, email, priority, dryrun, command, start_with, family): """Start a new analysis.""" mip_cli = MipCli(context.obj['script']) mip_config = mip_config or context.obj['mip_config'] email = email or environ_email() kwargs = dict(config=mip_config, family=family, priority=priority, email=email, dryrun=dryrun, start_with=start_with) if command: mip_command = mip_cli.build_command(**kwargs) click.echo(' '.join(mip_command)) else: try: mip_cli(**kwargs) if not dryrun: context.obj['store'].add_pending(family, email=email) except MipStartError as error: click.echo(click.style(error.message, fg='red'))
python
def start(context, mip_config, email, priority, dryrun, command, start_with, family): """Start a new analysis.""" mip_cli = MipCli(context.obj['script']) mip_config = mip_config or context.obj['mip_config'] email = email or environ_email() kwargs = dict(config=mip_config, family=family, priority=priority, email=email, dryrun=dryrun, start_with=start_with) if command: mip_command = mip_cli.build_command(**kwargs) click.echo(' '.join(mip_command)) else: try: mip_cli(**kwargs) if not dryrun: context.obj['store'].add_pending(family, email=email) except MipStartError as error: click.echo(click.style(error.message, fg='red'))
[ "def", "start", "(", "context", ",", "mip_config", ",", "email", ",", "priority", ",", "dryrun", ",", "command", ",", "start_with", ",", "family", ")", ":", "mip_cli", "=", "MipCli", "(", "context", ".", "obj", "[", "'script'", "]", ")", "mip_config", ...
Start a new analysis.
[ "Start", "a", "new", "analysis", "." ]
27f3cd21043a1077bd7029e85783459a50a7b798
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/cli/core.py#L80-L95
train
49,884
Clinical-Genomics/trailblazer
trailblazer/cli/core.py
scan
def scan(context, root_dir): """Scan a directory for analyses.""" root_dir = root_dir or context.obj['root'] config_files = Path(root_dir).glob('*/analysis/*_config.yaml') for config_file in config_files: LOG.debug("found analysis config: %s", config_file) with config_file.open() as stream: context.invoke(log_cmd, config=stream, quiet=True) context.obj['store'].track_update()
python
def scan(context, root_dir): """Scan a directory for analyses.""" root_dir = root_dir or context.obj['root'] config_files = Path(root_dir).glob('*/analysis/*_config.yaml') for config_file in config_files: LOG.debug("found analysis config: %s", config_file) with config_file.open() as stream: context.invoke(log_cmd, config=stream, quiet=True) context.obj['store'].track_update()
[ "def", "scan", "(", "context", ",", "root_dir", ")", ":", "root_dir", "=", "root_dir", "or", "context", ".", "obj", "[", "'root'", "]", "config_files", "=", "Path", "(", "root_dir", ")", ".", "glob", "(", "'*/analysis/*_config.yaml'", ")", "for", "config_f...
Scan a directory for analyses.
[ "Scan", "a", "directory", "for", "analyses", "." ]
27f3cd21043a1077bd7029e85783459a50a7b798
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/cli/core.py#L122-L131
train
49,885
Clinical-Genomics/trailblazer
trailblazer/cli/core.py
user
def user(context, name, email): """Add a new or display information about an existing user.""" existing_user = context.obj['store'].user(email) if existing_user: click.echo(existing_user.to_dict()) elif name: new_user = context.obj['store'].add_user(name, email) click.echo(click.style(f"New user added: {email} ({new_user.id})", fg='green')) else: click.echo(click.style('User not found', fg='yellow'))
python
def user(context, name, email): """Add a new or display information about an existing user.""" existing_user = context.obj['store'].user(email) if existing_user: click.echo(existing_user.to_dict()) elif name: new_user = context.obj['store'].add_user(name, email) click.echo(click.style(f"New user added: {email} ({new_user.id})", fg='green')) else: click.echo(click.style('User not found', fg='yellow'))
[ "def", "user", "(", "context", ",", "name", ",", "email", ")", ":", "existing_user", "=", "context", ".", "obj", "[", "'store'", "]", ".", "user", "(", "email", ")", "if", "existing_user", ":", "click", ".", "echo", "(", "existing_user", ".", "to_dict"...
Add a new or display information about an existing user.
[ "Add", "a", "new", "or", "display", "information", "about", "an", "existing", "user", "." ]
27f3cd21043a1077bd7029e85783459a50a7b798
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/cli/core.py#L138-L147
train
49,886
Clinical-Genomics/trailblazer
trailblazer/cli/core.py
cancel
def cancel(context, jobs, analysis_id): """Cancel all jobs in a run.""" analysis_obj = context.obj['store'].analysis(analysis_id) if analysis_obj is None: click.echo('analysis not found') context.abort() elif analysis_obj.status != 'running': click.echo(f"analysis not running: {analysis_obj.status}") context.abort() config_path = Path(analysis_obj.config_path) with config_path.open() as config_stream: config_raw = ruamel.yaml.safe_load(config_stream) config_data = parse_config(config_raw) log_path = Path(f"{config_data['log_path']}") if not log_path.exists(): click.echo(f"missing MIP log file: {log_path}") context.abort() with log_path.open() as log_stream: all_jobs = job_ids(log_stream) if jobs: for job_id in all_jobs: click.echo(job_id) else: for job_id in all_jobs: LOG.debug(f"cancelling job: {job_id}") process = subprocess.Popen(['scancel', job_id]) process.wait() analysis_obj.status = 'canceled' context.obj['store'].commit() click.echo('cancelled analysis successfully!')
python
def cancel(context, jobs, analysis_id): """Cancel all jobs in a run.""" analysis_obj = context.obj['store'].analysis(analysis_id) if analysis_obj is None: click.echo('analysis not found') context.abort() elif analysis_obj.status != 'running': click.echo(f"analysis not running: {analysis_obj.status}") context.abort() config_path = Path(analysis_obj.config_path) with config_path.open() as config_stream: config_raw = ruamel.yaml.safe_load(config_stream) config_data = parse_config(config_raw) log_path = Path(f"{config_data['log_path']}") if not log_path.exists(): click.echo(f"missing MIP log file: {log_path}") context.abort() with log_path.open() as log_stream: all_jobs = job_ids(log_stream) if jobs: for job_id in all_jobs: click.echo(job_id) else: for job_id in all_jobs: LOG.debug(f"cancelling job: {job_id}") process = subprocess.Popen(['scancel', job_id]) process.wait() analysis_obj.status = 'canceled' context.obj['store'].commit() click.echo('cancelled analysis successfully!')
[ "def", "cancel", "(", "context", ",", "jobs", ",", "analysis_id", ")", ":", "analysis_obj", "=", "context", ".", "obj", "[", "'store'", "]", ".", "analysis", "(", "analysis_id", ")", "if", "analysis_obj", "is", "None", ":", "click", ".", "echo", "(", "...
Cancel all jobs in a run.
[ "Cancel", "all", "jobs", "in", "a", "run", "." ]
27f3cd21043a1077bd7029e85783459a50a7b798
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/cli/core.py#L154-L188
train
49,887
pytroll/posttroll
posttroll/ns.py
NameServer.run
def run(self, *args): """Run the listener and answer to requests. """ del args arec = AddressReceiver(max_age=self._max_age, multicast_enabled=self._multicast_enabled) arec.start() port = PORT try: with nslock: self.listener = get_context().socket(REP) self.listener.bind("tcp://*:" + str(port)) logger.debug('Listening on port %s', str(port)) poller = Poller() poller.register(self.listener, POLLIN) while self.loop: with nslock: socks = dict(poller.poll(1000)) if socks: if socks.get(self.listener) == POLLIN: msg = self.listener.recv_string() else: continue logger.debug("Replying to request: " + str(msg)) msg = Message.decode(msg) self.listener.send_unicode(six.text_type(get_active_address( msg.data["service"], arec))) except KeyboardInterrupt: # Needed to stop the nameserver. pass finally: arec.stop() self.stop()
python
def run(self, *args): """Run the listener and answer to requests. """ del args arec = AddressReceiver(max_age=self._max_age, multicast_enabled=self._multicast_enabled) arec.start() port = PORT try: with nslock: self.listener = get_context().socket(REP) self.listener.bind("tcp://*:" + str(port)) logger.debug('Listening on port %s', str(port)) poller = Poller() poller.register(self.listener, POLLIN) while self.loop: with nslock: socks = dict(poller.poll(1000)) if socks: if socks.get(self.listener) == POLLIN: msg = self.listener.recv_string() else: continue logger.debug("Replying to request: " + str(msg)) msg = Message.decode(msg) self.listener.send_unicode(six.text_type(get_active_address( msg.data["service"], arec))) except KeyboardInterrupt: # Needed to stop the nameserver. pass finally: arec.stop() self.stop()
[ "def", "run", "(", "self", ",", "*", "args", ")", ":", "del", "args", "arec", "=", "AddressReceiver", "(", "max_age", "=", "self", ".", "_max_age", ",", "multicast_enabled", "=", "self", ".", "_multicast_enabled", ")", "arec", ".", "start", "(", ")", "...
Run the listener and answer to requests.
[ "Run", "the", "listener", "and", "answer", "to", "requests", "." ]
8e811a0544b5182c4a72aed074b2ff8c4324e94d
https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/ns.py#L130-L164
train
49,888
pytroll/posttroll
posttroll/ns.py
NameServer.stop
def stop(self): """Stop the name server. """ self.listener.setsockopt(LINGER, 1) self.loop = False with nslock: self.listener.close()
python
def stop(self): """Stop the name server. """ self.listener.setsockopt(LINGER, 1) self.loop = False with nslock: self.listener.close()
[ "def", "stop", "(", "self", ")", ":", "self", ".", "listener", ".", "setsockopt", "(", "LINGER", ",", "1", ")", "self", ".", "loop", "=", "False", "with", "nslock", ":", "self", ".", "listener", ".", "close", "(", ")" ]
Stop the name server.
[ "Stop", "the", "name", "server", "." ]
8e811a0544b5182c4a72aed074b2ff8c4324e94d
https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/ns.py#L166-L172
train
49,889
andrewda/frc-livescore
livescore/simpleocr_utils/segmentation.py
segments_to_numpy
def segments_to_numpy(segments): """given a list of 4-element tuples, transforms it into a numpy array""" segments = numpy.array(segments, dtype=SEGMENT_DATATYPE, ndmin=2) # each segment in a row segments = segments if SEGMENTS_DIRECTION == 0 else numpy.transpose(segments) return segments
python
def segments_to_numpy(segments): """given a list of 4-element tuples, transforms it into a numpy array""" segments = numpy.array(segments, dtype=SEGMENT_DATATYPE, ndmin=2) # each segment in a row segments = segments if SEGMENTS_DIRECTION == 0 else numpy.transpose(segments) return segments
[ "def", "segments_to_numpy", "(", "segments", ")", ":", "segments", "=", "numpy", ".", "array", "(", "segments", ",", "dtype", "=", "SEGMENT_DATATYPE", ",", "ndmin", "=", "2", ")", "# each segment in a row", "segments", "=", "segments", "if", "SEGMENTS_DIRECTION"...
given a list of 4-element tuples, transforms it into a numpy array
[ "given", "a", "list", "of", "4", "-", "element", "tuples", "transforms", "it", "into", "a", "numpy", "array" ]
71594cd6d2c8b6c5feb3889bb05552d09b8128b1
https://github.com/andrewda/frc-livescore/blob/71594cd6d2c8b6c5feb3889bb05552d09b8128b1/livescore/simpleocr_utils/segmentation.py#L20-L24
train
49,890
thespacedoctor/sherlock
sherlock/imports/marshall.py
marshall._create_dictionary_of_marshall
def _create_dictionary_of_marshall( self, marshallQuery, marshallTable): """create a list of dictionaries containing all the rows in the marshall stream **Key Arguments:** - ``marshallQuery`` -- the query used to lift the required data from the marshall database. - ``marshallTable`` -- the name of the marshall table we are lifting the data from. **Return:** - ``dictList`` - a list of dictionaries containing all the rows in the marshall stream """ self.log.debug( 'starting the ``_create_dictionary_of_marshall`` method') dictList = [] tableName = self.dbTableName rows = readquery( log=self.log, sqlQuery=marshallQuery, dbConn=self.pmDbConn, quiet=False ) totalCount = len(rows) count = 0 for row in rows: if "dateCreated" in row: del row["dateCreated"] count += 1 if count > 1: # Cursor up one line and clear line sys.stdout.write("\x1b[1A\x1b[2K") print "%(count)s / %(totalCount)s `%(tableName)s` data added to memory" % locals() dictList.append(dict(row)) self.log.debug( 'completed the ``_create_dictionary_of_marshall`` method') return dictList
python
def _create_dictionary_of_marshall( self, marshallQuery, marshallTable): """create a list of dictionaries containing all the rows in the marshall stream **Key Arguments:** - ``marshallQuery`` -- the query used to lift the required data from the marshall database. - ``marshallTable`` -- the name of the marshall table we are lifting the data from. **Return:** - ``dictList`` - a list of dictionaries containing all the rows in the marshall stream """ self.log.debug( 'starting the ``_create_dictionary_of_marshall`` method') dictList = [] tableName = self.dbTableName rows = readquery( log=self.log, sqlQuery=marshallQuery, dbConn=self.pmDbConn, quiet=False ) totalCount = len(rows) count = 0 for row in rows: if "dateCreated" in row: del row["dateCreated"] count += 1 if count > 1: # Cursor up one line and clear line sys.stdout.write("\x1b[1A\x1b[2K") print "%(count)s / %(totalCount)s `%(tableName)s` data added to memory" % locals() dictList.append(dict(row)) self.log.debug( 'completed the ``_create_dictionary_of_marshall`` method') return dictList
[ "def", "_create_dictionary_of_marshall", "(", "self", ",", "marshallQuery", ",", "marshallTable", ")", ":", "self", ".", "log", ".", "debug", "(", "'starting the ``_create_dictionary_of_marshall`` method'", ")", "dictList", "=", "[", "]", "tableName", "=", "self", "...
create a list of dictionaries containing all the rows in the marshall stream **Key Arguments:** - ``marshallQuery`` -- the query used to lift the required data from the marshall database. - ``marshallTable`` -- the name of the marshall table we are lifting the data from. **Return:** - ``dictList`` - a list of dictionaries containing all the rows in the marshall stream
[ "create", "a", "list", "of", "dictionaries", "containing", "all", "the", "rows", "in", "the", "marshall", "stream" ]
2c80fb6fa31b04e7820e6928e3d437a21e692dd3
https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/imports/marshall.py#L110-L151
train
49,891
thespacedoctor/sherlock
sherlock/imports/ned_d.py
ned_d.ingest
def ingest(self): """Import the ned_d catalogue into the catalogues database The method first generates a list of python dictionaries from the ned_d datafile, imports this list of dictionaries into a database table and then generates the HTMIDs for that table. **Usage:** See class docstring for usage .. todo :: - update docstring text - check sublime snippet exists - clip any useful text to docs mindmap - regenerate the docs and check redendering of this docstring """ self.log.debug('starting the ``get`` method') dictList = self._create_dictionary_of_ned_d() self.primaryIdColumnName = "primaryId" self.raColName = "raDeg" self.declColName = "decDeg" tableName = self.dbTableName createStatement = u""" CREATE TABLE `%(tableName)s` ( `primaryId` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'An internal counter', `Method` varchar(150) DEFAULT NULL, `dateCreated` datetime DEFAULT CURRENT_TIMESTAMP, `dateLastModified` datetime DEFAULT CURRENT_TIMESTAMP, `updated` varchar(45) DEFAULT '0', `dist_derived_from_sn` varchar(150) DEFAULT NULL, `dist_in_ned_flag` varchar(10) DEFAULT NULL, `dist_index_id` mediumint(9) DEFAULT NULL, `dist_mod` double DEFAULT NULL, `dist_mod_err` double DEFAULT NULL, `dist_mpc` double DEFAULT NULL, `galaxy_index_id` mediumint(9) DEFAULT NULL, `hubble_const` double DEFAULT NULL, `lmc_mod` double DEFAULT NULL, `notes` varchar(500) DEFAULT NULL, `primary_ned_id` varchar(150) DEFAULT NULL, `redshift` double DEFAULT NULL, `ref` varchar(150) DEFAULT NULL, `ref_date` int(11) DEFAULT NULL, `master_row` tinyint(4) DEFAULT '0', `major_diameter_arcmin` double DEFAULT NULL, `ned_notes` varchar(700) DEFAULT NULL, `object_type` varchar(100) DEFAULT NULL, `redshift_err` double DEFAULT NULL, `redshift_quality` varchar(100) DEFAULT NULL, `magnitude_filter` varchar(10) DEFAULT NULL, `minor_diameter_arcmin` double DEFAULT NULL, `morphology` varchar(50) DEFAULT NULL, `hierarchy` varchar(50) DEFAULT NULL, `galaxy_morphology` varchar(50) DEFAULT NULL, `radio_morphology` varchar(50) DEFAULT NULL, `activity_type` varchar(50) DEFAULT NULL, `in_ned` tinyint(4) DEFAULT NULL, `raDeg` double DEFAULT NULL, `decDeg` double DEFAULT NULL, `eb_v` double DEFAULT NULL, `sdss_coverage` TINYINT DEFAULT NULL, PRIMARY KEY (`primaryId`), UNIQUE KEY `galaxy_index_id_dist_index_id` (`galaxy_index_id`,`dist_index_id`) ) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=latin1; DROP VIEW IF EXISTS `view_%(tableName)s_master_recorders`; CREATE VIEW `view_%(tableName)s_master_recorders` AS (SELECT `%(tableName)s`.`primary_ned_id` AS `primary_ned_id`, `%(tableName)s`.`object_type` AS `object_type`, `%(tableName)s`.`raDeg` AS `raDeg`, `%(tableName)s`.`decDeg` AS `decDeg`, `%(tableName)s`.`dist_mpc` AS `dist_mpc`, `%(tableName)s`.`dist_mod` AS `dist_mod`, `%(tableName)s`.`dist_mod_err` AS `dist_mod_err`, `%(tableName)s`.`Method` AS `dist_measurement_method`, `%(tableName)s`.`redshift` AS `redshift`, `%(tableName)s`.`redshift_err` AS `redshift_err`, `%(tableName)s`.`redshift_quality` AS `redshift_quality`, `%(tableName)s`.`major_diameter_arcmin` AS `major_diameter_arcmin`, `%(tableName)s`.`minor_diameter_arcmin` AS `minor_diameter_arcmin`, `%(tableName)s`.`magnitude_filter` AS `magnitude_filter`, `%(tableName)s`.`eb_v` AS `gal_eb_v`, `%(tableName)s`.`hierarchy` AS `hierarchy`, `%(tableName)s`.`morphology` AS `morphology`, `%(tableName)s`.`radio_morphology` AS `radio_morphology`, `%(tableName)s`.`activity_type` AS `activity_type`, `%(tableName)s`.`ned_notes` AS `ned_notes`, `%(tableName)s`.`in_ned` AS `in_ned`, `%(tableName)s`.`primaryId` AS `primaryId` FROM `%(tableName)s` WHERE (`%(tableName)s`.`master_row` = 1)); """ % locals() self.add_data_to_database_table( dictList=dictList, createStatement=createStatement ) self._clean_up_columns() self._get_metadata_for_galaxies() self._update_sdss_coverage() self.log.debug('completed the ``get`` method') return None
python
def ingest(self): """Import the ned_d catalogue into the catalogues database The method first generates a list of python dictionaries from the ned_d datafile, imports this list of dictionaries into a database table and then generates the HTMIDs for that table. **Usage:** See class docstring for usage .. todo :: - update docstring text - check sublime snippet exists - clip any useful text to docs mindmap - regenerate the docs and check redendering of this docstring """ self.log.debug('starting the ``get`` method') dictList = self._create_dictionary_of_ned_d() self.primaryIdColumnName = "primaryId" self.raColName = "raDeg" self.declColName = "decDeg" tableName = self.dbTableName createStatement = u""" CREATE TABLE `%(tableName)s` ( `primaryId` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'An internal counter', `Method` varchar(150) DEFAULT NULL, `dateCreated` datetime DEFAULT CURRENT_TIMESTAMP, `dateLastModified` datetime DEFAULT CURRENT_TIMESTAMP, `updated` varchar(45) DEFAULT '0', `dist_derived_from_sn` varchar(150) DEFAULT NULL, `dist_in_ned_flag` varchar(10) DEFAULT NULL, `dist_index_id` mediumint(9) DEFAULT NULL, `dist_mod` double DEFAULT NULL, `dist_mod_err` double DEFAULT NULL, `dist_mpc` double DEFAULT NULL, `galaxy_index_id` mediumint(9) DEFAULT NULL, `hubble_const` double DEFAULT NULL, `lmc_mod` double DEFAULT NULL, `notes` varchar(500) DEFAULT NULL, `primary_ned_id` varchar(150) DEFAULT NULL, `redshift` double DEFAULT NULL, `ref` varchar(150) DEFAULT NULL, `ref_date` int(11) DEFAULT NULL, `master_row` tinyint(4) DEFAULT '0', `major_diameter_arcmin` double DEFAULT NULL, `ned_notes` varchar(700) DEFAULT NULL, `object_type` varchar(100) DEFAULT NULL, `redshift_err` double DEFAULT NULL, `redshift_quality` varchar(100) DEFAULT NULL, `magnitude_filter` varchar(10) DEFAULT NULL, `minor_diameter_arcmin` double DEFAULT NULL, `morphology` varchar(50) DEFAULT NULL, `hierarchy` varchar(50) DEFAULT NULL, `galaxy_morphology` varchar(50) DEFAULT NULL, `radio_morphology` varchar(50) DEFAULT NULL, `activity_type` varchar(50) DEFAULT NULL, `in_ned` tinyint(4) DEFAULT NULL, `raDeg` double DEFAULT NULL, `decDeg` double DEFAULT NULL, `eb_v` double DEFAULT NULL, `sdss_coverage` TINYINT DEFAULT NULL, PRIMARY KEY (`primaryId`), UNIQUE KEY `galaxy_index_id_dist_index_id` (`galaxy_index_id`,`dist_index_id`) ) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=latin1; DROP VIEW IF EXISTS `view_%(tableName)s_master_recorders`; CREATE VIEW `view_%(tableName)s_master_recorders` AS (SELECT `%(tableName)s`.`primary_ned_id` AS `primary_ned_id`, `%(tableName)s`.`object_type` AS `object_type`, `%(tableName)s`.`raDeg` AS `raDeg`, `%(tableName)s`.`decDeg` AS `decDeg`, `%(tableName)s`.`dist_mpc` AS `dist_mpc`, `%(tableName)s`.`dist_mod` AS `dist_mod`, `%(tableName)s`.`dist_mod_err` AS `dist_mod_err`, `%(tableName)s`.`Method` AS `dist_measurement_method`, `%(tableName)s`.`redshift` AS `redshift`, `%(tableName)s`.`redshift_err` AS `redshift_err`, `%(tableName)s`.`redshift_quality` AS `redshift_quality`, `%(tableName)s`.`major_diameter_arcmin` AS `major_diameter_arcmin`, `%(tableName)s`.`minor_diameter_arcmin` AS `minor_diameter_arcmin`, `%(tableName)s`.`magnitude_filter` AS `magnitude_filter`, `%(tableName)s`.`eb_v` AS `gal_eb_v`, `%(tableName)s`.`hierarchy` AS `hierarchy`, `%(tableName)s`.`morphology` AS `morphology`, `%(tableName)s`.`radio_morphology` AS `radio_morphology`, `%(tableName)s`.`activity_type` AS `activity_type`, `%(tableName)s`.`ned_notes` AS `ned_notes`, `%(tableName)s`.`in_ned` AS `in_ned`, `%(tableName)s`.`primaryId` AS `primaryId` FROM `%(tableName)s` WHERE (`%(tableName)s`.`master_row` = 1)); """ % locals() self.add_data_to_database_table( dictList=dictList, createStatement=createStatement ) self._clean_up_columns() self._get_metadata_for_galaxies() self._update_sdss_coverage() self.log.debug('completed the ``get`` method') return None
[ "def", "ingest", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "'starting the ``get`` method'", ")", "dictList", "=", "self", ".", "_create_dictionary_of_ned_d", "(", ")", "self", ".", "primaryIdColumnName", "=", "\"primaryId\"", "self", ".", "...
Import the ned_d catalogue into the catalogues database The method first generates a list of python dictionaries from the ned_d datafile, imports this list of dictionaries into a database table and then generates the HTMIDs for that table. **Usage:** See class docstring for usage .. todo :: - update docstring text - check sublime snippet exists - clip any useful text to docs mindmap - regenerate the docs and check redendering of this docstring
[ "Import", "the", "ned_d", "catalogue", "into", "the", "catalogues", "database" ]
2c80fb6fa31b04e7820e6928e3d437a21e692dd3
https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/imports/ned_d.py#L66-L175
train
49,892
thespacedoctor/sherlock
sherlock/imports/ned_d.py
ned_d._create_dictionary_of_ned_d
def _create_dictionary_of_ned_d( self): """create a list of dictionaries containing all the rows in the ned_d catalogue **Return:** - ``dictList`` - a list of dictionaries containing all the rows in the ned_d catalogue .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip any useful text to docs mindmap - regenerate the docs and check redendering of this docstring """ self.log.debug( 'starting the ``_create_dictionary_of_ned_d`` method') count = 0 with open(self.pathToDataFile, 'rb') as csvFile: csvReader = csv.reader( csvFile, dialect='excel', delimiter=',', quotechar='"') totalRows = sum(1 for row in csvReader) csvFile.close() totalCount = totalRows with open(self.pathToDataFile, 'rb') as csvFile: csvReader = csv.reader( csvFile, dialect='excel', delimiter=',', quotechar='"') theseKeys = [] dictList = [] for row in csvReader: if len(theseKeys) == 0: totalRows -= 1 if "Exclusion Code" in row and "Hubble const." in row: for i in row: if i == "redshift (z)": theseKeys.append("redshift") elif i == "Hubble const.": theseKeys.append("hubble_const") elif i == "G": theseKeys.append("galaxy_index_id") elif i == "err": theseKeys.append("dist_mod_err") elif i == "D (Mpc)": theseKeys.append("dist_mpc") elif i == "Date (Yr. - 1980)": theseKeys.append("ref_date") elif i == "REFCODE": theseKeys.append("ref") elif i == "Exclusion Code": theseKeys.append("dist_in_ned_flag") elif i == "Adopted LMC modulus": theseKeys.append("lmc_mod") elif i == "m-M": theseKeys.append("dist_mod") elif i == "Notes": theseKeys.append("notes") elif i == "SN ID": theseKeys.append("dist_derived_from_sn") elif i == "method": theseKeys.append("dist_method") elif i == "Galaxy ID": theseKeys.append("primary_ned_id") elif i == "D": theseKeys.append("dist_index_id") else: theseKeys.append(i) continue if len(theseKeys): count += 1 if count > 1: # Cursor up one line and clear line sys.stdout.write("\x1b[1A\x1b[2K") if count > totalCount: count = totalCount percent = (float(count) / float(totalCount)) * 100. print "%(count)s / %(totalCount)s (%(percent)1.1f%%) rows added to memory" % locals() rowDict = {} for t, r in zip(theseKeys, row): rowDict[t] = r if t == "ref_date": try: rowDict[t] = int(r) + 1980 except: rowDict[t] = None if rowDict["dist_index_id"] != "999999": dictList.append(rowDict) csvFile.close() self.log.debug( 'completed the ``_create_dictionary_of_ned_d`` method') return dictList
python
def _create_dictionary_of_ned_d( self): """create a list of dictionaries containing all the rows in the ned_d catalogue **Return:** - ``dictList`` - a list of dictionaries containing all the rows in the ned_d catalogue .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip any useful text to docs mindmap - regenerate the docs and check redendering of this docstring """ self.log.debug( 'starting the ``_create_dictionary_of_ned_d`` method') count = 0 with open(self.pathToDataFile, 'rb') as csvFile: csvReader = csv.reader( csvFile, dialect='excel', delimiter=',', quotechar='"') totalRows = sum(1 for row in csvReader) csvFile.close() totalCount = totalRows with open(self.pathToDataFile, 'rb') as csvFile: csvReader = csv.reader( csvFile, dialect='excel', delimiter=',', quotechar='"') theseKeys = [] dictList = [] for row in csvReader: if len(theseKeys) == 0: totalRows -= 1 if "Exclusion Code" in row and "Hubble const." in row: for i in row: if i == "redshift (z)": theseKeys.append("redshift") elif i == "Hubble const.": theseKeys.append("hubble_const") elif i == "G": theseKeys.append("galaxy_index_id") elif i == "err": theseKeys.append("dist_mod_err") elif i == "D (Mpc)": theseKeys.append("dist_mpc") elif i == "Date (Yr. - 1980)": theseKeys.append("ref_date") elif i == "REFCODE": theseKeys.append("ref") elif i == "Exclusion Code": theseKeys.append("dist_in_ned_flag") elif i == "Adopted LMC modulus": theseKeys.append("lmc_mod") elif i == "m-M": theseKeys.append("dist_mod") elif i == "Notes": theseKeys.append("notes") elif i == "SN ID": theseKeys.append("dist_derived_from_sn") elif i == "method": theseKeys.append("dist_method") elif i == "Galaxy ID": theseKeys.append("primary_ned_id") elif i == "D": theseKeys.append("dist_index_id") else: theseKeys.append(i) continue if len(theseKeys): count += 1 if count > 1: # Cursor up one line and clear line sys.stdout.write("\x1b[1A\x1b[2K") if count > totalCount: count = totalCount percent = (float(count) / float(totalCount)) * 100. print "%(count)s / %(totalCount)s (%(percent)1.1f%%) rows added to memory" % locals() rowDict = {} for t, r in zip(theseKeys, row): rowDict[t] = r if t == "ref_date": try: rowDict[t] = int(r) + 1980 except: rowDict[t] = None if rowDict["dist_index_id"] != "999999": dictList.append(rowDict) csvFile.close() self.log.debug( 'completed the ``_create_dictionary_of_ned_d`` method') return dictList
[ "def", "_create_dictionary_of_ned_d", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "'starting the ``_create_dictionary_of_ned_d`` method'", ")", "count", "=", "0", "with", "open", "(", "self", ".", "pathToDataFile", ",", "'rb'", ")", "as", "csvF...
create a list of dictionaries containing all the rows in the ned_d catalogue **Return:** - ``dictList`` - a list of dictionaries containing all the rows in the ned_d catalogue .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip any useful text to docs mindmap - regenerate the docs and check redendering of this docstring
[ "create", "a", "list", "of", "dictionaries", "containing", "all", "the", "rows", "in", "the", "ned_d", "catalogue" ]
2c80fb6fa31b04e7820e6928e3d437a21e692dd3
https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/imports/ned_d.py#L177-L274
train
49,893
thespacedoctor/sherlock
sherlock/imports/ned_d.py
ned_d._clean_up_columns
def _clean_up_columns( self): """clean up columns of the NED table .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip any useful text to docs mindmap - regenerate the docs and check redendering of this docstring """ self.log.debug('starting the ``_clean_up_columns`` method') tableName = self.dbTableName print "cleaning up %(tableName)s columns" % locals() sqlQuery = u""" set sql_mode="STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"; """ % locals() writequery( log=self.log, sqlQuery=sqlQuery, dbConn=self.cataloguesDbConn, ) sqlQuery = u""" update %(tableName)s set dist_mod_err = null where dist_mod_err = 0; update %(tableName)s set dist_in_ned_flag = null where dist_in_ned_flag = ""; update %(tableName)s set notes = null where notes = ""; update %(tableName)s set redshift = null where redshift = 0; update %(tableName)s set dist_derived_from_sn = null where dist_derived_from_sn = ""; update %(tableName)s set hubble_const = null where hubble_const = 0; update %(tableName)s set lmc_mod = null where lmc_mod = 0; update %(tableName)s set master_row = 0; update %(tableName)s set master_row = 1 where primaryId in (select * from (select distinct primaryId from %(tableName)s group by galaxy_index_id) as alias); """ % locals() writequery( log=self.log, sqlQuery=sqlQuery, dbConn=self.cataloguesDbConn, ) self.log.debug('completed the ``_clean_up_columns`` method') return None
python
def _clean_up_columns( self): """clean up columns of the NED table .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip any useful text to docs mindmap - regenerate the docs and check redendering of this docstring """ self.log.debug('starting the ``_clean_up_columns`` method') tableName = self.dbTableName print "cleaning up %(tableName)s columns" % locals() sqlQuery = u""" set sql_mode="STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"; """ % locals() writequery( log=self.log, sqlQuery=sqlQuery, dbConn=self.cataloguesDbConn, ) sqlQuery = u""" update %(tableName)s set dist_mod_err = null where dist_mod_err = 0; update %(tableName)s set dist_in_ned_flag = null where dist_in_ned_flag = ""; update %(tableName)s set notes = null where notes = ""; update %(tableName)s set redshift = null where redshift = 0; update %(tableName)s set dist_derived_from_sn = null where dist_derived_from_sn = ""; update %(tableName)s set hubble_const = null where hubble_const = 0; update %(tableName)s set lmc_mod = null where lmc_mod = 0; update %(tableName)s set master_row = 0; update %(tableName)s set master_row = 1 where primaryId in (select * from (select distinct primaryId from %(tableName)s group by galaxy_index_id) as alias); """ % locals() writequery( log=self.log, sqlQuery=sqlQuery, dbConn=self.cataloguesDbConn, ) self.log.debug('completed the ``_clean_up_columns`` method') return None
[ "def", "_clean_up_columns", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "'starting the ``_clean_up_columns`` method'", ")", "tableName", "=", "self", ".", "dbTableName", "print", "\"cleaning up %(tableName)s columns\"", "%", "locals", "(", ")", "sq...
clean up columns of the NED table .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip any useful text to docs mindmap - regenerate the docs and check redendering of this docstring
[ "clean", "up", "columns", "of", "the", "NED", "table" ]
2c80fb6fa31b04e7820e6928e3d437a21e692dd3
https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/imports/ned_d.py#L276-L323
train
49,894
thespacedoctor/sherlock
sherlock/imports/ned_d.py
ned_d._get_metadata_for_galaxies
def _get_metadata_for_galaxies( self): """get metadata for galaxies .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip any useful text to docs mindmap - regenerate the docs and check redendering of this docstring """ self.log.debug('starting the ``_get_metadata_for_galaxies`` method') total, batches = self._count_galaxies_requiring_metadata() print "%(total)s galaxies require metadata. Need to send %(batches)s batch requests to NED." % locals() totalBatches = self.batches thisCount = 0 # FOR EACH BATCH, GET THE GALAXY IDs, QUERY NED AND UPDATE THE DATABASE while self.total: thisCount += 1 self._get_3000_galaxies_needing_metadata() dictList = self._query_ned_and_add_results_to_database(thisCount) self.add_data_to_database_table( dictList=dictList, createStatement=False ) self._count_galaxies_requiring_metadata() self.log.debug('completed the ``_get_metadata_for_galaxies`` method') return None
python
def _get_metadata_for_galaxies( self): """get metadata for galaxies .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip any useful text to docs mindmap - regenerate the docs and check redendering of this docstring """ self.log.debug('starting the ``_get_metadata_for_galaxies`` method') total, batches = self._count_galaxies_requiring_metadata() print "%(total)s galaxies require metadata. Need to send %(batches)s batch requests to NED." % locals() totalBatches = self.batches thisCount = 0 # FOR EACH BATCH, GET THE GALAXY IDs, QUERY NED AND UPDATE THE DATABASE while self.total: thisCount += 1 self._get_3000_galaxies_needing_metadata() dictList = self._query_ned_and_add_results_to_database(thisCount) self.add_data_to_database_table( dictList=dictList, createStatement=False ) self._count_galaxies_requiring_metadata() self.log.debug('completed the ``_get_metadata_for_galaxies`` method') return None
[ "def", "_get_metadata_for_galaxies", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "'starting the ``_get_metadata_for_galaxies`` method'", ")", "total", ",", "batches", "=", "self", ".", "_count_galaxies_requiring_metadata", "(", ")", "print", "\"%(tot...
get metadata for galaxies .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip any useful text to docs mindmap - regenerate the docs and check redendering of this docstring
[ "get", "metadata", "for", "galaxies" ]
2c80fb6fa31b04e7820e6928e3d437a21e692dd3
https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/imports/ned_d.py#L325-L361
train
49,895
thespacedoctor/sherlock
sherlock/imports/ned_d.py
ned_d._get_3000_galaxies_needing_metadata
def _get_3000_galaxies_needing_metadata( self): """ get 3000 galaxies needing metadata **Return:** - ``len(self.theseIds)`` -- the number of NED IDs returned .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip any useful text to docs mindmap - regenerate the docs and check redendering of this docstring """ self.log.debug( 'starting the ``_get_3000_galaxies_needing_metadata`` method') tableName = self.dbTableName # SELECT THE DATA FROM NED TABLE self.theseIds = {} sqlQuery = u""" select primaryId, primary_ned_id from %(tableName)s where master_row = 1 and in_ned is null limit 3000; """ % locals() rows = readquery( log=self.log, sqlQuery=sqlQuery, dbConn=self.cataloguesDbConn, quiet=False ) for row in rows: self.theseIds[row["primary_ned_id"]] = row["primaryId"] self.log.debug( 'completed the ``_get_3000_galaxies_needing_metadata`` method') return len(self.theseIds)
python
def _get_3000_galaxies_needing_metadata( self): """ get 3000 galaxies needing metadata **Return:** - ``len(self.theseIds)`` -- the number of NED IDs returned .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip any useful text to docs mindmap - regenerate the docs and check redendering of this docstring """ self.log.debug( 'starting the ``_get_3000_galaxies_needing_metadata`` method') tableName = self.dbTableName # SELECT THE DATA FROM NED TABLE self.theseIds = {} sqlQuery = u""" select primaryId, primary_ned_id from %(tableName)s where master_row = 1 and in_ned is null limit 3000; """ % locals() rows = readquery( log=self.log, sqlQuery=sqlQuery, dbConn=self.cataloguesDbConn, quiet=False ) for row in rows: self.theseIds[row["primary_ned_id"]] = row["primaryId"] self.log.debug( 'completed the ``_get_3000_galaxies_needing_metadata`` method') return len(self.theseIds)
[ "def", "_get_3000_galaxies_needing_metadata", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "'starting the ``_get_3000_galaxies_needing_metadata`` method'", ")", "tableName", "=", "self", ".", "dbTableName", "# SELECT THE DATA FROM NED TABLE", "self", ".", ...
get 3000 galaxies needing metadata **Return:** - ``len(self.theseIds)`` -- the number of NED IDs returned .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip any useful text to docs mindmap - regenerate the docs and check redendering of this docstring
[ "get", "3000", "galaxies", "needing", "metadata" ]
2c80fb6fa31b04e7820e6928e3d437a21e692dd3
https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/imports/ned_d.py#L404-L443
train
49,896
thespacedoctor/sherlock
sherlock/imports/ned_d.py
ned_d._update_sdss_coverage
def _update_sdss_coverage( self): """ update sdss coverage .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip any useful text to docs mindmap - regenerate the docs and check redendering of this docstring """ self.log.debug('starting the ``_update_sdss_coverage`` method') tableName = self.dbTableName # SELECT THE LOCATIONS NEEDING TO BE CHECKED sqlQuery = u""" select primary_ned_id, primaryID, raDeg, decDeg, sdss_coverage from %(tableName)s where sdss_coverage is null and master_row = 1 and in_ned = 1 order by dist_mpc; """ % locals() rows = readquery( log=self.log, sqlQuery=sqlQuery, dbConn=self.cataloguesDbConn, quiet=False ) totalCount = len(rows) count = 0 for row in rows: count += 1 if count > 1: # Cursor up three lines and clear sys.stdout.write("\x1b[1A\x1b[2K") sys.stdout.write("\x1b[1A\x1b[2K") sys.stdout.write("\x1b[1A\x1b[2K") if count > totalCount: count = totalCount percent = (float(count) / float(totalCount)) * 100. primaryID = row["primaryID"] raDeg = float(row["raDeg"]) decDeg = float(row["decDeg"]) primary_ned_id = row["primary_ned_id"] # SDSS CAN ONLY ACCEPT 60 QUERIES/MIN time.sleep(1.1) print "%(count)s / %(totalCount)s (%(percent)1.1f%%) NED galaxies checked for SDSS coverage" % locals() print "NED NAME: ", primary_ned_id # covered = True | False | 999 (i.e. not sure) sdss_coverage = check_coverage( log=self.log, ra=raDeg, dec=decDeg ).get() if sdss_coverage == 999: sdss_coverage_flag = "null" elif sdss_coverage == True: sdss_coverage_flag = 1 elif sdss_coverage == False: sdss_coverage_flag = 0 else: self.log.error('cound not get sdss coverage' % locals()) sys.exit(0) # UPDATE THE DATABASE FLAG sqlQuery = u""" update %(tableName)s set sdss_coverage = %(sdss_coverage_flag)s where primaryID = %(primaryID)s """ % locals() writequery( log=self.log, sqlQuery=sqlQuery, dbConn=self.cataloguesDbConn, ) self.log.debug('completed the ``_update_sdss_coverage`` method') return None
python
def _update_sdss_coverage( self): """ update sdss coverage .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip any useful text to docs mindmap - regenerate the docs and check redendering of this docstring """ self.log.debug('starting the ``_update_sdss_coverage`` method') tableName = self.dbTableName # SELECT THE LOCATIONS NEEDING TO BE CHECKED sqlQuery = u""" select primary_ned_id, primaryID, raDeg, decDeg, sdss_coverage from %(tableName)s where sdss_coverage is null and master_row = 1 and in_ned = 1 order by dist_mpc; """ % locals() rows = readquery( log=self.log, sqlQuery=sqlQuery, dbConn=self.cataloguesDbConn, quiet=False ) totalCount = len(rows) count = 0 for row in rows: count += 1 if count > 1: # Cursor up three lines and clear sys.stdout.write("\x1b[1A\x1b[2K") sys.stdout.write("\x1b[1A\x1b[2K") sys.stdout.write("\x1b[1A\x1b[2K") if count > totalCount: count = totalCount percent = (float(count) / float(totalCount)) * 100. primaryID = row["primaryID"] raDeg = float(row["raDeg"]) decDeg = float(row["decDeg"]) primary_ned_id = row["primary_ned_id"] # SDSS CAN ONLY ACCEPT 60 QUERIES/MIN time.sleep(1.1) print "%(count)s / %(totalCount)s (%(percent)1.1f%%) NED galaxies checked for SDSS coverage" % locals() print "NED NAME: ", primary_ned_id # covered = True | False | 999 (i.e. not sure) sdss_coverage = check_coverage( log=self.log, ra=raDeg, dec=decDeg ).get() if sdss_coverage == 999: sdss_coverage_flag = "null" elif sdss_coverage == True: sdss_coverage_flag = 1 elif sdss_coverage == False: sdss_coverage_flag = 0 else: self.log.error('cound not get sdss coverage' % locals()) sys.exit(0) # UPDATE THE DATABASE FLAG sqlQuery = u""" update %(tableName)s set sdss_coverage = %(sdss_coverage_flag)s where primaryID = %(primaryID)s """ % locals() writequery( log=self.log, sqlQuery=sqlQuery, dbConn=self.cataloguesDbConn, ) self.log.debug('completed the ``_update_sdss_coverage`` method') return None
[ "def", "_update_sdss_coverage", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "'starting the ``_update_sdss_coverage`` method'", ")", "tableName", "=", "self", ".", "dbTableName", "# SELECT THE LOCATIONS NEEDING TO BE CHECKED", "sqlQuery", "=", "u\"\"\"\n ...
update sdss coverage .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip any useful text to docs mindmap - regenerate the docs and check redendering of this docstring
[ "update", "sdss", "coverage" ]
2c80fb6fa31b04e7820e6928e3d437a21e692dd3
https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/imports/ned_d.py#L555-L636
train
49,897
emichael/PyREM
pyrem/host.py
RemoteHost._rsync_cmd
def _rsync_cmd(self): """Helper method to generate base rsync command.""" cmd = ['rsync'] if self._identity_file: cmd += ['-e', 'ssh -i ' + os.path.expanduser(self._identity_file)] return cmd
python
def _rsync_cmd(self): """Helper method to generate base rsync command.""" cmd = ['rsync'] if self._identity_file: cmd += ['-e', 'ssh -i ' + os.path.expanduser(self._identity_file)] return cmd
[ "def", "_rsync_cmd", "(", "self", ")", ":", "cmd", "=", "[", "'rsync'", "]", "if", "self", ".", "_identity_file", ":", "cmd", "+=", "[", "'-e'", ",", "'ssh -i '", "+", "os", ".", "path", ".", "expanduser", "(", "self", ".", "_identity_file", ")", "]"...
Helper method to generate base rsync command.
[ "Helper", "method", "to", "generate", "base", "rsync", "command", "." ]
2609249ead197cd9496d164f4998ca9985503579
https://github.com/emichael/PyREM/blob/2609249ead197cd9496d164f4998ca9985503579/pyrem/host.py#L61-L66
train
49,898
emichael/PyREM
pyrem/host.py
RemoteHost.send_file
def send_file(self, file_name, remote_destination=None, **kwargs): """Send a file to a remote host with rsync. Args: file_name (str): The relative location of the file on the local host. remote_destination (str): The destination for the file on the remote host. If `None`, will be assumed to be the same as **file_name**. Default `None`. **kwargs: Passed to ``SubprocessTask``'s init method. Return: ``pyrem.task.SubprocessTask``: The resulting task. """ if not remote_destination: remote_destination = file_name return SubprocessTask( self._rsync_cmd() + ['-ut', file_name, '%s:%s' % (self.hostname, remote_destination)], **kwargs)
python
def send_file(self, file_name, remote_destination=None, **kwargs): """Send a file to a remote host with rsync. Args: file_name (str): The relative location of the file on the local host. remote_destination (str): The destination for the file on the remote host. If `None`, will be assumed to be the same as **file_name**. Default `None`. **kwargs: Passed to ``SubprocessTask``'s init method. Return: ``pyrem.task.SubprocessTask``: The resulting task. """ if not remote_destination: remote_destination = file_name return SubprocessTask( self._rsync_cmd() + ['-ut', file_name, '%s:%s' % (self.hostname, remote_destination)], **kwargs)
[ "def", "send_file", "(", "self", ",", "file_name", ",", "remote_destination", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "remote_destination", ":", "remote_destination", "=", "file_name", "return", "SubprocessTask", "(", "self", ".", "_rsync_...
Send a file to a remote host with rsync. Args: file_name (str): The relative location of the file on the local host. remote_destination (str): The destination for the file on the remote host. If `None`, will be assumed to be the same as **file_name**. Default `None`. **kwargs: Passed to ``SubprocessTask``'s init method. Return: ``pyrem.task.SubprocessTask``: The resulting task.
[ "Send", "a", "file", "to", "a", "remote", "host", "with", "rsync", "." ]
2609249ead197cd9496d164f4998ca9985503579
https://github.com/emichael/PyREM/blob/2609249ead197cd9496d164f4998ca9985503579/pyrem/host.py#L68-L90
train
49,899