repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
Datary/scrapbag
scrapbag/files.py
copy_remote_file
def copy_remote_file(web_file, destination): """ Check if exist the destination path, and copy the online resource file to local. Args: :web_file: reference to online file resource to take. :destination: path to store the file. """ size = 0 dir_name = os.path.dirname(destination) if not os.path.exists(dir_name): os.makedirs(dir_name) with open(destination, 'wb') as file_: chunk_size = 8 * 1024 for chunk in web_file.iter_content(chunk_size=chunk_size): if chunk: file_.write(chunk) size += len(chunk) return size
python
def copy_remote_file(web_file, destination): """ Check if exist the destination path, and copy the online resource file to local. Args: :web_file: reference to online file resource to take. :destination: path to store the file. """ size = 0 dir_name = os.path.dirname(destination) if not os.path.exists(dir_name): os.makedirs(dir_name) with open(destination, 'wb') as file_: chunk_size = 8 * 1024 for chunk in web_file.iter_content(chunk_size=chunk_size): if chunk: file_.write(chunk) size += len(chunk) return size
[ "def", "copy_remote_file", "(", "web_file", ",", "destination", ")", ":", "size", "=", "0", "dir_name", "=", "os", ".", "path", ".", "dirname", "(", "destination", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "dir_name", ")", ":", "os", "...
Check if exist the destination path, and copy the online resource file to local. Args: :web_file: reference to online file resource to take. :destination: path to store the file.
[ "Check", "if", "exist", "the", "destination", "path", "and", "copy", "the", "online", "resource", "file", "to", "local", "." ]
train
https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/files.py#L144-L164
Datary/scrapbag
scrapbag/files.py
remove_file
def remove_file(paths): """ Remove file from paths introduced. """ for path in force_list(paths): if os.path.exists(path): os.remove(path)
python
def remove_file(paths): """ Remove file from paths introduced. """ for path in force_list(paths): if os.path.exists(path): os.remove(path)
[ "def", "remove_file", "(", "paths", ")", ":", "for", "path", "in", "force_list", "(", "paths", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "os", ".", "remove", "(", "path", ")" ]
Remove file from paths introduced.
[ "Remove", "file", "from", "paths", "introduced", "." ]
train
https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/files.py#L167-L174
redhat-cip/python-dciauth
dciauth/signature.py
Signature.generate_headers
def generate_headers(self, client_type, client_id, secret): """ generate_headers is used to generate the headers automatically for your http request :param client_type (str): remoteci or feeder :param client_id (str): remoteci or feeder id :param secret (str): api secret :return: Authorization headers (dict) """ self.request.add_header(self.dci_datetime_header, self.dci_datetime_str) signature = self._sign(secret) return self.request.build_headers(client_type, client_id, signature)
python
def generate_headers(self, client_type, client_id, secret): """ generate_headers is used to generate the headers automatically for your http request :param client_type (str): remoteci or feeder :param client_id (str): remoteci or feeder id :param secret (str): api secret :return: Authorization headers (dict) """ self.request.add_header(self.dci_datetime_header, self.dci_datetime_str) signature = self._sign(secret) return self.request.build_headers(client_type, client_id, signature)
[ "def", "generate_headers", "(", "self", ",", "client_type", ",", "client_id", ",", "secret", ")", ":", "self", ".", "request", ".", "add_header", "(", "self", ".", "dci_datetime_header", ",", "self", ".", "dci_datetime_str", ")", "signature", "=", "self", "....
generate_headers is used to generate the headers automatically for your http request :param client_type (str): remoteci or feeder :param client_id (str): remoteci or feeder id :param secret (str): api secret :return: Authorization headers (dict)
[ "generate_headers", "is", "used", "to", "generate", "the", "headers", "automatically", "for", "your", "http", "request" ]
train
https://github.com/redhat-cip/python-dciauth/blob/fe39bdf387a0bcb23094dbef0bb0d8bca1823128/dciauth/signature.py#L39-L51
ttinies/sc2ladderMgmt
sc2ladderMgmt/functions.py
addLadder
def addLadder(settings): """define a new Ladder setting and save to disk file""" ladder = Ladder(settings) ladder.save() getKnownLadders()[ladder.name] = ladder return ladder
python
def addLadder(settings): """define a new Ladder setting and save to disk file""" ladder = Ladder(settings) ladder.save() getKnownLadders()[ladder.name] = ladder return ladder
[ "def", "addLadder", "(", "settings", ")", ":", "ladder", "=", "Ladder", "(", "settings", ")", "ladder", ".", "save", "(", ")", "getKnownLadders", "(", ")", "[", "ladder", ".", "name", "]", "=", "ladder", "return", "ladder" ]
define a new Ladder setting and save to disk file
[ "define", "a", "new", "Ladder", "setting", "and", "save", "to", "disk", "file" ]
train
https://github.com/ttinies/sc2ladderMgmt/blob/230292e18c54e43129c162116bbdf743b3e9dcf1/sc2ladderMgmt/functions.py#L18-L23
ttinies/sc2ladderMgmt
sc2ladderMgmt/functions.py
delLadder
def delLadder(name): """forget about a previously defined Ladder setting by deleting its disk file""" ladders = getKnownLadders() try: ladder = ladders[name] os.remove(ladder.filename) # delete from disk del ladders[name] # deallocate object return ladder except KeyError: raise ValueError("given ladder name '%s' is not a known ladder definition"%(name))
python
def delLadder(name): """forget about a previously defined Ladder setting by deleting its disk file""" ladders = getKnownLadders() try: ladder = ladders[name] os.remove(ladder.filename) # delete from disk del ladders[name] # deallocate object return ladder except KeyError: raise ValueError("given ladder name '%s' is not a known ladder definition"%(name))
[ "def", "delLadder", "(", "name", ")", ":", "ladders", "=", "getKnownLadders", "(", ")", "try", ":", "ladder", "=", "ladders", "[", "name", "]", "os", ".", "remove", "(", "ladder", ".", "filename", ")", "# delete from disk", "del", "ladders", "[", "name",...
forget about a previously defined Ladder setting by deleting its disk file
[ "forget", "about", "a", "previously", "defined", "Ladder", "setting", "by", "deleting", "its", "disk", "file" ]
train
https://github.com/ttinies/sc2ladderMgmt/blob/230292e18c54e43129c162116bbdf743b3e9dcf1/sc2ladderMgmt/functions.py#L35-L44
ttinies/sc2ladderMgmt
sc2ladderMgmt/functions.py
getKnownLadders
def getKnownLadders(reset=False): """identify all of the currently defined ladders""" if not ladderCache or reset: jsonFiles = os.path.join(c.LADDER_FOLDER, "*.json") for ladderFilepath in glob.glob(jsonFiles): filename = os.path.basename(ladderFilepath) name = re.search("^ladder_(.*?).json$", filename).groups()[0] ladder = Ladder(name) ladderCache[ladder.name] = ladder return ladderCache
python
def getKnownLadders(reset=False): """identify all of the currently defined ladders""" if not ladderCache or reset: jsonFiles = os.path.join(c.LADDER_FOLDER, "*.json") for ladderFilepath in glob.glob(jsonFiles): filename = os.path.basename(ladderFilepath) name = re.search("^ladder_(.*?).json$", filename).groups()[0] ladder = Ladder(name) ladderCache[ladder.name] = ladder return ladderCache
[ "def", "getKnownLadders", "(", "reset", "=", "False", ")", ":", "if", "not", "ladderCache", "or", "reset", ":", "jsonFiles", "=", "os", ".", "path", ".", "join", "(", "c", ".", "LADDER_FOLDER", ",", "\"*.json\"", ")", "for", "ladderFilepath", "in", "glob...
identify all of the currently defined ladders
[ "identify", "all", "of", "the", "currently", "defined", "ladders" ]
train
https://github.com/ttinies/sc2ladderMgmt/blob/230292e18c54e43129c162116bbdf743b3e9dcf1/sc2ladderMgmt/functions.py#L48-L57
thombashi/thutils
thutils/loader.py
JsonLoader.load
def load(cls, json_file_path, schema=None): """ :param str json_file_path: Path to the JSON file to be read. :param voluptuous.Schema schema: JSON schema. :return: Dictionary storing the parse results of JSON. :rtype: dictionary :raises ImportError: :raises InvalidFilePathError: :raises FileNotFoundError: :raises RuntimeError: :raises ValueError: """ gfile.check_file_existence(json_file_path) try: if not gfile.FileTypeChecker.is_text_file(json_file_path): raise ValueError("not a JSON file") except ImportError: # magicが必要とするライブラリが見つからない (e.g. Windowsでは追加DLLが必要) raise with open(json_file_path, "r") as fp: try: dict_json = json.load(fp) except ValueError: _, e, _ = sys.exc_info() # for python 2.5 compatibility raise ValueError(os.linesep.join([ str(e), "decode error: check JSON format with http://jsonlint.com/", ])) cls.__validate_json(schema, dict_json) return dict_json
python
def load(cls, json_file_path, schema=None): """ :param str json_file_path: Path to the JSON file to be read. :param voluptuous.Schema schema: JSON schema. :return: Dictionary storing the parse results of JSON. :rtype: dictionary :raises ImportError: :raises InvalidFilePathError: :raises FileNotFoundError: :raises RuntimeError: :raises ValueError: """ gfile.check_file_existence(json_file_path) try: if not gfile.FileTypeChecker.is_text_file(json_file_path): raise ValueError("not a JSON file") except ImportError: # magicが必要とするライブラリが見つからない (e.g. Windowsでは追加DLLが必要) raise with open(json_file_path, "r") as fp: try: dict_json = json.load(fp) except ValueError: _, e, _ = sys.exc_info() # for python 2.5 compatibility raise ValueError(os.linesep.join([ str(e), "decode error: check JSON format with http://jsonlint.com/", ])) cls.__validate_json(schema, dict_json) return dict_json
[ "def", "load", "(", "cls", ",", "json_file_path", ",", "schema", "=", "None", ")", ":", "gfile", ".", "check_file_existence", "(", "json_file_path", ")", "try", ":", "if", "not", "gfile", ".", "FileTypeChecker", ".", "is_text_file", "(", "json_file_path", ")...
:param str json_file_path: Path to the JSON file to be read. :param voluptuous.Schema schema: JSON schema. :return: Dictionary storing the parse results of JSON. :rtype: dictionary :raises ImportError: :raises InvalidFilePathError: :raises FileNotFoundError: :raises RuntimeError: :raises ValueError:
[ ":", "param", "str", "json_file_path", ":", "Path", "to", "the", "JSON", "file", "to", "be", "read", ".", ":", "param", "voluptuous", ".", "Schema", "schema", ":", "JSON", "schema", ".", ":", "return", ":", "Dictionary", "storing", "the", "parse", "resul...
train
https://github.com/thombashi/thutils/blob/9eba767cfc26b38cd66b83b99aee0c31b8b90dec/thutils/loader.py#L22-L57
thombashi/thutils
thutils/loader.py
JsonLoader.loads
def loads(cls, json_text, schema=None): """ :param str json_text: json text to be parse :param voluptuous.Schema schema: JSON schema. :return: Dictionary storing the parse results of JSON :rtype: dictionary :raises ImportError: :raises RuntimeError: :raises ValueError: """ try: json_text = json_text.decode("ascii") except AttributeError: pass try: dict_json = json.loads(json_text) except ValueError: _, e, _ = sys.exc_info() # for python 2.5 compatibility raise ValueError(os.linesep.join([ str(e), "decode error: check JSON format with http://jsonlint.com/", ])) cls.__validate_json(schema, dict_json) return dict_json
python
def loads(cls, json_text, schema=None): """ :param str json_text: json text to be parse :param voluptuous.Schema schema: JSON schema. :return: Dictionary storing the parse results of JSON :rtype: dictionary :raises ImportError: :raises RuntimeError: :raises ValueError: """ try: json_text = json_text.decode("ascii") except AttributeError: pass try: dict_json = json.loads(json_text) except ValueError: _, e, _ = sys.exc_info() # for python 2.5 compatibility raise ValueError(os.linesep.join([ str(e), "decode error: check JSON format with http://jsonlint.com/", ])) cls.__validate_json(schema, dict_json) return dict_json
[ "def", "loads", "(", "cls", ",", "json_text", ",", "schema", "=", "None", ")", ":", "try", ":", "json_text", "=", "json_text", ".", "decode", "(", "\"ascii\"", ")", "except", "AttributeError", ":", "pass", "try", ":", "dict_json", "=", "json", ".", "lo...
:param str json_text: json text to be parse :param voluptuous.Schema schema: JSON schema. :return: Dictionary storing the parse results of JSON :rtype: dictionary :raises ImportError: :raises RuntimeError: :raises ValueError:
[ ":", "param", "str", "json_text", ":", "json", "text", "to", "be", "parse", ":", "param", "voluptuous", ".", "Schema", "schema", ":", "JSON", "schema", ".", ":", "return", ":", "Dictionary", "storing", "the", "parse", "results", "of", "JSON", ":", "rtype...
train
https://github.com/thombashi/thutils/blob/9eba767cfc26b38cd66b83b99aee0c31b8b90dec/thutils/loader.py#L60-L87
ajyoon/blur
examples/waves/oscillator.py
Oscillator.get_samples
def get_samples(self, sample_count): """ Fetch a number of samples from self.wave_cache Args: sample_count (int): Number of samples to fetch Returns: ndarray """ if self.amplitude.value <= 0: return None # Build samples by rolling the period cache through the buffer rolled_array = numpy.roll(self.wave_cache, -1 * self.last_played_sample) # Append remaining partial period full_count, remainder = divmod(sample_count, self.cache_length) final_subarray = rolled_array[:int(remainder)] return_array = numpy.concatenate((numpy.tile(rolled_array, full_count), final_subarray)) # Keep track of where we left off to prevent popping between chunks self.last_played_sample = int(((self.last_played_sample + remainder) % self.cache_length)) # Multiply output by amplitude return return_array * (self.amplitude.value * self.amplitude_multiplier)
python
def get_samples(self, sample_count): """ Fetch a number of samples from self.wave_cache Args: sample_count (int): Number of samples to fetch Returns: ndarray """ if self.amplitude.value <= 0: return None # Build samples by rolling the period cache through the buffer rolled_array = numpy.roll(self.wave_cache, -1 * self.last_played_sample) # Append remaining partial period full_count, remainder = divmod(sample_count, self.cache_length) final_subarray = rolled_array[:int(remainder)] return_array = numpy.concatenate((numpy.tile(rolled_array, full_count), final_subarray)) # Keep track of where we left off to prevent popping between chunks self.last_played_sample = int(((self.last_played_sample + remainder) % self.cache_length)) # Multiply output by amplitude return return_array * (self.amplitude.value * self.amplitude_multiplier)
[ "def", "get_samples", "(", "self", ",", "sample_count", ")", ":", "if", "self", ".", "amplitude", ".", "value", "<=", "0", ":", "return", "None", "# Build samples by rolling the period cache through the buffer", "rolled_array", "=", "numpy", ".", "roll", "(", "sel...
Fetch a number of samples from self.wave_cache Args: sample_count (int): Number of samples to fetch Returns: ndarray
[ "Fetch", "a", "number", "of", "samples", "from", "self", ".", "wave_cache" ]
train
https://github.com/ajyoon/blur/blob/25fcf083af112bb003956a7a7e1c6ff7d8fef279/examples/waves/oscillator.py#L45-L69
cemsbr/yala
yala/base.py
LinterOutput._cmp_key
def _cmp_key(self, obj=None): """Comparison key for sorting results from all linters. The sort should group files and lines from different linters to make it easier for refactoring. """ if not obj: obj = self line_nr = int(obj.line_nr) if obj.line_nr else 0 col = int(obj.col) if obj.col else 0 return (obj.path, line_nr, col, obj.msg)
python
def _cmp_key(self, obj=None): """Comparison key for sorting results from all linters. The sort should group files and lines from different linters to make it easier for refactoring. """ if not obj: obj = self line_nr = int(obj.line_nr) if obj.line_nr else 0 col = int(obj.col) if obj.col else 0 return (obj.path, line_nr, col, obj.msg)
[ "def", "_cmp_key", "(", "self", ",", "obj", "=", "None", ")", ":", "if", "not", "obj", ":", "obj", "=", "self", "line_nr", "=", "int", "(", "obj", ".", "line_nr", ")", "if", "obj", ".", "line_nr", "else", "0", "col", "=", "int", "(", "obj", "."...
Comparison key for sorting results from all linters. The sort should group files and lines from different linters to make it easier for refactoring.
[ "Comparison", "key", "for", "sorting", "results", "from", "all", "linters", "." ]
train
https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/base.py#L41-L51
cemsbr/yala
yala/base.py
Linter.command_with_options
def command_with_options(self): """Add arguments from config to :attr:`command`.""" if 'args' in self.config: return ' '.join((self.command, self.config['args'])) return self.command
python
def command_with_options(self): """Add arguments from config to :attr:`command`.""" if 'args' in self.config: return ' '.join((self.command, self.config['args'])) return self.command
[ "def", "command_with_options", "(", "self", ")", ":", "if", "'args'", "in", "self", ".", "config", ":", "return", "' '", ".", "join", "(", "(", "self", ".", "command", ",", "self", ".", "config", "[", "'args'", "]", ")", ")", "return", "self", ".", ...
Add arguments from config to :attr:`command`.
[ "Add", "arguments", "from", "config", "to", ":", "attr", ":", "command", "." ]
train
https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/base.py#L85-L89
cemsbr/yala
yala/base.py
Linter._get_relative_path
def _get_relative_path(self, full_path): """Return the relative path from current path.""" try: rel_path = Path(full_path).relative_to(Path().absolute()) except ValueError: LOG.error("%s: Couldn't find relative path of '%s' from '%s'.", self.name, full_path, Path().absolute()) return full_path return str(rel_path)
python
def _get_relative_path(self, full_path): """Return the relative path from current path.""" try: rel_path = Path(full_path).relative_to(Path().absolute()) except ValueError: LOG.error("%s: Couldn't find relative path of '%s' from '%s'.", self.name, full_path, Path().absolute()) return full_path return str(rel_path)
[ "def", "_get_relative_path", "(", "self", ",", "full_path", ")", ":", "try", ":", "rel_path", "=", "Path", "(", "full_path", ")", ".", "relative_to", "(", "Path", "(", ")", ".", "absolute", "(", ")", ")", "except", "ValueError", ":", "LOG", ".", "error...
Return the relative path from current path.
[ "Return", "the", "relative", "path", "from", "current", "path", "." ]
train
https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/base.py#L104-L112
cemsbr/yala
yala/base.py
Linter._parse_by_pattern
def _parse_by_pattern(self, lines, pattern): """Match pattern line by line and return Results. Use ``_create_output_from_match`` to convert pattern match groups to Result instances. Args: lines (iterable): Output lines to be parsed. pattern: Compiled pattern to match against lines. result_fn (function): Receive results of one match and return a Result. Return: generator: Result instances. """ for line in lines: match = pattern.match(line) if match: params = match.groupdict() if not params: params = match.groups() yield self._create_output_from_match(params)
python
def _parse_by_pattern(self, lines, pattern): """Match pattern line by line and return Results. Use ``_create_output_from_match`` to convert pattern match groups to Result instances. Args: lines (iterable): Output lines to be parsed. pattern: Compiled pattern to match against lines. result_fn (function): Receive results of one match and return a Result. Return: generator: Result instances. """ for line in lines: match = pattern.match(line) if match: params = match.groupdict() if not params: params = match.groups() yield self._create_output_from_match(params)
[ "def", "_parse_by_pattern", "(", "self", ",", "lines", ",", "pattern", ")", ":", "for", "line", "in", "lines", ":", "match", "=", "pattern", ".", "match", "(", "line", ")", "if", "match", ":", "params", "=", "match", ".", "groupdict", "(", ")", "if",...
Match pattern line by line and return Results. Use ``_create_output_from_match`` to convert pattern match groups to Result instances. Args: lines (iterable): Output lines to be parsed. pattern: Compiled pattern to match against lines. result_fn (function): Receive results of one match and return a Result. Return: generator: Result instances.
[ "Match", "pattern", "line", "by", "line", "and", "return", "Results", "." ]
train
https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/base.py#L114-L135
cemsbr/yala
yala/base.py
Linter._create_output_from_match
def _create_output_from_match(self, match_result): """Create Result instance from pattern match results. Args: match: Pattern match. """ if isinstance(match_result, dict): return LinterOutput(self.name, **match_result) return LinterOutput(self.name, *match_result)
python
def _create_output_from_match(self, match_result): """Create Result instance from pattern match results. Args: match: Pattern match. """ if isinstance(match_result, dict): return LinterOutput(self.name, **match_result) return LinterOutput(self.name, *match_result)
[ "def", "_create_output_from_match", "(", "self", ",", "match_result", ")", ":", "if", "isinstance", "(", "match_result", ",", "dict", ")", ":", "return", "LinterOutput", "(", "self", ".", "name", ",", "*", "*", "match_result", ")", "return", "LinterOutput", ...
Create Result instance from pattern match results. Args: match: Pattern match.
[ "Create", "Result", "instance", "from", "pattern", "match", "results", "." ]
train
https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/base.py#L137-L145
robehickman/simple-http-file-sync
shttpfs/plain_storage.py
plain_storage.get_single_file_info
def get_single_file_info(self, rel_path): """ Gets last change time for a single file """ f_path = self.get_full_file_path(rel_path) return get_single_file_info(f_path, rel_path)
python
def get_single_file_info(self, rel_path): """ Gets last change time for a single file """ f_path = self.get_full_file_path(rel_path) return get_single_file_info(f_path, rel_path)
[ "def", "get_single_file_info", "(", "self", ",", "rel_path", ")", ":", "f_path", "=", "self", ".", "get_full_file_path", "(", "rel_path", ")", "return", "get_single_file_info", "(", "f_path", ",", "rel_path", ")" ]
Gets last change time for a single file
[ "Gets", "last", "change", "time", "for", "a", "single", "file" ]
train
https://github.com/robehickman/simple-http-file-sync/blob/fa29b3ee58e9504e1d3ddfc0c14047284bf9921d/shttpfs/plain_storage.py#L16-L20
robehickman/simple-http-file-sync
shttpfs/plain_storage.py
plain_storage.read_local_manifest
def read_local_manifest(self): """ Read the file manifest, or create a new one if there isn't one already """ manifest = file_or_default(self.get_full_file_path(self.manifest_file), { 'format_version' : 2, 'root' : '/', 'have_revision' : 'root', 'files' : {}}, json.loads) if 'format_version' not in manifest or manifest['format_version'] < 2: raise SystemExit('Please update the client manifest format') return manifest
python
def read_local_manifest(self): """ Read the file manifest, or create a new one if there isn't one already """ manifest = file_or_default(self.get_full_file_path(self.manifest_file), { 'format_version' : 2, 'root' : '/', 'have_revision' : 'root', 'files' : {}}, json.loads) if 'format_version' not in manifest or manifest['format_version'] < 2: raise SystemExit('Please update the client manifest format') return manifest
[ "def", "read_local_manifest", "(", "self", ")", ":", "manifest", "=", "file_or_default", "(", "self", ".", "get_full_file_path", "(", "self", ".", "manifest_file", ")", ",", "{", "'format_version'", ":", "2", ",", "'root'", ":", "'/'", ",", "'have_revision'", ...
Read the file manifest, or create a new one if there isn't one already
[ "Read", "the", "file", "manifest", "or", "create", "a", "new", "one", "if", "there", "isn", "t", "one", "already" ]
train
https://github.com/robehickman/simple-http-file-sync/blob/fa29b3ee58e9504e1d3ddfc0c14047284bf9921d/shttpfs/plain_storage.py#L23-L34
robehickman/simple-http-file-sync
shttpfs/plain_storage.py
plain_storage.fs_put
def fs_put(self, rpath, data): """ Add a file to the FS """ try: self.begin() # Add the file to the fs self.file_put_contents(rpath, data) # Add to the manifest manifest = self.read_local_manifest() manifest['files'][rpath] = self.get_single_file_info(rpath) self.write_local_manifest(manifest) self.commit() except: self.rollback(); raise
python
def fs_put(self, rpath, data): """ Add a file to the FS """ try: self.begin() # Add the file to the fs self.file_put_contents(rpath, data) # Add to the manifest manifest = self.read_local_manifest() manifest['files'][rpath] = self.get_single_file_info(rpath) self.write_local_manifest(manifest) self.commit() except: self.rollback(); raise
[ "def", "fs_put", "(", "self", ",", "rpath", ",", "data", ")", ":", "try", ":", "self", ".", "begin", "(", ")", "# Add the file to the fs", "self", ".", "file_put_contents", "(", "rpath", ",", "data", ")", "# Add to the manifest", "manifest", "=", "self", "...
Add a file to the FS
[ "Add", "a", "file", "to", "the", "FS" ]
train
https://github.com/robehickman/simple-http-file-sync/blob/fa29b3ee58e9504e1d3ddfc0c14047284bf9921d/shttpfs/plain_storage.py#L47-L62
mozilla/socorrolib
socorrolib/lib/task_manager.py
respond_to_SIGTERM
def respond_to_SIGTERM(signal_number, frame, target=None): """ these classes are instrumented to respond to a KeyboardInterrupt by cleanly shutting down. This function, when given as a handler to for a SIGTERM event, will make the program respond to a SIGTERM as neatly as it responds to ^C. This function is used in registering a signal handler from the signal module. It should be registered for any signal for which the desired behavior is to kill the application: signal.signal(signal.SIGTERM, respondToSIGTERM) signal.signal(signal.SIGHUP, respondToSIGTERM) parameters: signal_number - unused in this function but required by the api. frame - unused in this function but required by the api. target - an instance of a class that has a member called 'task_manager' that is a derivative of the TaskManager class below. """ if target: target.config.logger.info('detected SIGTERM') # by setting the quit flag to true, any calls to the 'quit_check' # method that is so liberally passed around in this framework will # result in raising the quit exception. The current quit exception # is KeyboardInterrupt target.task_manager.quit = True else: raise KeyboardInterrupt
python
def respond_to_SIGTERM(signal_number, frame, target=None): """ these classes are instrumented to respond to a KeyboardInterrupt by cleanly shutting down. This function, when given as a handler to for a SIGTERM event, will make the program respond to a SIGTERM as neatly as it responds to ^C. This function is used in registering a signal handler from the signal module. It should be registered for any signal for which the desired behavior is to kill the application: signal.signal(signal.SIGTERM, respondToSIGTERM) signal.signal(signal.SIGHUP, respondToSIGTERM) parameters: signal_number - unused in this function but required by the api. frame - unused in this function but required by the api. target - an instance of a class that has a member called 'task_manager' that is a derivative of the TaskManager class below. """ if target: target.config.logger.info('detected SIGTERM') # by setting the quit flag to true, any calls to the 'quit_check' # method that is so liberally passed around in this framework will # result in raising the quit exception. The current quit exception # is KeyboardInterrupt target.task_manager.quit = True else: raise KeyboardInterrupt
[ "def", "respond_to_SIGTERM", "(", "signal_number", ",", "frame", ",", "target", "=", "None", ")", ":", "if", "target", ":", "target", ".", "config", ".", "logger", ".", "info", "(", "'detected SIGTERM'", ")", "# by setting the quit flag to true, any calls to the 'qu...
these classes are instrumented to respond to a KeyboardInterrupt by cleanly shutting down. This function, when given as a handler to for a SIGTERM event, will make the program respond to a SIGTERM as neatly as it responds to ^C. This function is used in registering a signal handler from the signal module. It should be registered for any signal for which the desired behavior is to kill the application: signal.signal(signal.SIGTERM, respondToSIGTERM) signal.signal(signal.SIGHUP, respondToSIGTERM) parameters: signal_number - unused in this function but required by the api. frame - unused in this function but required by the api. target - an instance of a class that has a member called 'task_manager' that is a derivative of the TaskManager class below.
[ "these", "classes", "are", "instrumented", "to", "respond", "to", "a", "KeyboardInterrupt", "by", "cleanly", "shutting", "down", ".", "This", "function", "when", "given", "as", "a", "handler", "to", "for", "a", "SIGTERM", "event", "will", "make", "the", "pro...
train
https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/task_manager.py#L27-L53
mozilla/socorrolib
socorrolib/lib/task_manager.py
TaskManager._get_iterator
def _get_iterator(self): """The iterator passed in can take several forms: a class that can be instantiated and then iterated over; a function that when called returns an iterator; an actual iterator/generator or an iterable collection. This function sorts all that out and returns an iterator that can be used""" try: return self.job_param_source_iter(self.config) except TypeError: try: return self.job_param_source_iter() except TypeError: return self.job_param_source_iter
python
def _get_iterator(self): """The iterator passed in can take several forms: a class that can be instantiated and then iterated over; a function that when called returns an iterator; an actual iterator/generator or an iterable collection. This function sorts all that out and returns an iterator that can be used""" try: return self.job_param_source_iter(self.config) except TypeError: try: return self.job_param_source_iter() except TypeError: return self.job_param_source_iter
[ "def", "_get_iterator", "(", "self", ")", ":", "try", ":", "return", "self", ".", "job_param_source_iter", "(", "self", ".", "config", ")", "except", "TypeError", ":", "try", ":", "return", "self", ".", "job_param_source_iter", "(", ")", "except", "TypeError...
The iterator passed in can take several forms: a class that can be instantiated and then iterated over; a function that when called returns an iterator; an actual iterator/generator or an iterable collection. This function sorts all that out and returns an iterator that can be used
[ "The", "iterator", "passed", "in", "can", "take", "several", "forms", ":", "a", "class", "that", "can", "be", "instantiated", "and", "then", "iterated", "over", ";", "a", "function", "that", "when", "called", "returns", "an", "iterator", ";", "an", "actual...
train
https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/task_manager.py#L106-L118
mozilla/socorrolib
socorrolib/lib/task_manager.py
TaskManager._responsive_sleep
def _responsive_sleep(self, seconds, wait_log_interval=0, wait_reason=''): """When there is litte work to do, the queuing thread sleeps a lot. It can't sleep for too long without checking for the quit flag and/or logging about why it is sleeping. parameters: seconds - the number of seconds to sleep wait_log_interval - while sleeping, it is helpful if the thread periodically announces itself so that we know that it is still alive. This number is the time in seconds between log entries. wait_reason - the is for the explaination of why the thread is sleeping. This is likely to be a message like: 'there is no work to do'. This was also partially motivated by old versions' of Python inability to KeyboardInterrupt out of a long sleep().""" for x in xrange(int(seconds)): self.quit_check() if wait_log_interval and not x % wait_log_interval: self.logger.info('%s: %dsec of %dsec', wait_reason, x, seconds) self.quit_check() time.sleep(1.0)
python
def _responsive_sleep(self, seconds, wait_log_interval=0, wait_reason=''): """When there is litte work to do, the queuing thread sleeps a lot. It can't sleep for too long without checking for the quit flag and/or logging about why it is sleeping. parameters: seconds - the number of seconds to sleep wait_log_interval - while sleeping, it is helpful if the thread periodically announces itself so that we know that it is still alive. This number is the time in seconds between log entries. wait_reason - the is for the explaination of why the thread is sleeping. This is likely to be a message like: 'there is no work to do'. This was also partially motivated by old versions' of Python inability to KeyboardInterrupt out of a long sleep().""" for x in xrange(int(seconds)): self.quit_check() if wait_log_interval and not x % wait_log_interval: self.logger.info('%s: %dsec of %dsec', wait_reason, x, seconds) self.quit_check() time.sleep(1.0)
[ "def", "_responsive_sleep", "(", "self", ",", "seconds", ",", "wait_log_interval", "=", "0", ",", "wait_reason", "=", "''", ")", ":", "for", "x", "in", "xrange", "(", "int", "(", "seconds", ")", ")", ":", "self", ".", "quit_check", "(", ")", "if", "w...
When there is litte work to do, the queuing thread sleeps a lot. It can't sleep for too long without checking for the quit flag and/or logging about why it is sleeping. parameters: seconds - the number of seconds to sleep wait_log_interval - while sleeping, it is helpful if the thread periodically announces itself so that we know that it is still alive. This number is the time in seconds between log entries. wait_reason - the is for the explaination of why the thread is sleeping. This is likely to be a message like: 'there is no work to do'. This was also partially motivated by old versions' of Python inability to KeyboardInterrupt out of a long sleep().
[ "When", "there", "is", "litte", "work", "to", "do", "the", "queuing", "thread", "sleeps", "a", "lot", ".", "It", "can", "t", "sleep", "for", "too", "long", "without", "checking", "for", "the", "quit", "flag", "and", "/", "or", "logging", "about", "why"...
train
https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/task_manager.py#L121-L147
mozilla/socorrolib
socorrolib/lib/task_manager.py
TaskManager.blocking_start
def blocking_start(self, waiting_func=None): """this function starts the task manager running to do tasks. The waiting_func is normally used to do something while other threads are running, but here we don't have other threads. So the waiting func will never get called. I can see wanting this function to be called at least once after the end of the task loop.""" self.logger.debug('threadless start') try: for job_params in self._get_iterator(): # may never raise # StopIteration self.config.logger.debug('received %r', job_params) self.quit_check() if job_params is None: if self.config.quit_on_empty_queue: raise KeyboardInterrupt self.logger.info("there is nothing to do. Sleeping " "for %d seconds" % self.config.idle_delay) self._responsive_sleep(self.config.idle_delay) continue self.quit_check() try: args, kwargs = job_params except ValueError: args = job_params kwargs = {} try: self.task_func(*args, **kwargs) except Exception: self.config.logger.error("Error in processing a job", exc_info=True) except KeyboardInterrupt: self.logger.debug('queuingThread gets quit request') finally: self.quit = True self.logger.debug("ThreadlessTaskManager dies quietly")
python
def blocking_start(self, waiting_func=None): """this function starts the task manager running to do tasks. The waiting_func is normally used to do something while other threads are running, but here we don't have other threads. So the waiting func will never get called. I can see wanting this function to be called at least once after the end of the task loop.""" self.logger.debug('threadless start') try: for job_params in self._get_iterator(): # may never raise # StopIteration self.config.logger.debug('received %r', job_params) self.quit_check() if job_params is None: if self.config.quit_on_empty_queue: raise KeyboardInterrupt self.logger.info("there is nothing to do. Sleeping " "for %d seconds" % self.config.idle_delay) self._responsive_sleep(self.config.idle_delay) continue self.quit_check() try: args, kwargs = job_params except ValueError: args = job_params kwargs = {} try: self.task_func(*args, **kwargs) except Exception: self.config.logger.error("Error in processing a job", exc_info=True) except KeyboardInterrupt: self.logger.debug('queuingThread gets quit request') finally: self.quit = True self.logger.debug("ThreadlessTaskManager dies quietly")
[ "def", "blocking_start", "(", "self", ",", "waiting_func", "=", "None", ")", ":", "self", ".", "logger", ".", "debug", "(", "'threadless start'", ")", "try", ":", "for", "job_params", "in", "self", ".", "_get_iterator", "(", ")", ":", "# may never raise", ...
this function starts the task manager running to do tasks. The waiting_func is normally used to do something while other threads are running, but here we don't have other threads. So the waiting func will never get called. I can see wanting this function to be called at least once after the end of the task loop.
[ "this", "function", "starts", "the", "task", "manager", "running", "to", "do", "tasks", ".", "The", "waiting_func", "is", "normally", "used", "to", "do", "something", "while", "other", "threads", "are", "running", "but", "here", "we", "don", "t", "have", "...
train
https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/task_manager.py#L150-L185
ttm/socialLegacy
social/fsong.py
FSong.makePartitions
def makePartitions(self): """Make partitions with gmane help. """ class NetworkMeasures: pass self.nm=nm=NetworkMeasures() nm.degrees=self.network.degree() nm.nodes_= sorted(self.network.nodes(), key=lambda x : nm.degrees[x]) nm.degrees_=[nm.degrees[i] for i in nm.nodes_] nm.edges= self.network.edges(data=True) nm.E=self.network.number_of_edges() nm.N=self.network.number_of_nodes() self.np=g.NetworkPartitioning(nm,10,metric="g")
python
def makePartitions(self): """Make partitions with gmane help. """ class NetworkMeasures: pass self.nm=nm=NetworkMeasures() nm.degrees=self.network.degree() nm.nodes_= sorted(self.network.nodes(), key=lambda x : nm.degrees[x]) nm.degrees_=[nm.degrees[i] for i in nm.nodes_] nm.edges= self.network.edges(data=True) nm.E=self.network.number_of_edges() nm.N=self.network.number_of_nodes() self.np=g.NetworkPartitioning(nm,10,metric="g")
[ "def", "makePartitions", "(", "self", ")", ":", "class", "NetworkMeasures", ":", "pass", "self", ".", "nm", "=", "nm", "=", "NetworkMeasures", "(", ")", "nm", ".", "degrees", "=", "self", ".", "network", ".", "degree", "(", ")", "nm", ".", "nodes_", ...
Make partitions with gmane help.
[ "Make", "partitions", "with", "gmane", "help", "." ]
train
https://github.com/ttm/socialLegacy/blob/c0930cfe6e84392729449bf7c92569e1556fd109/social/fsong.py#L29-L41
ttm/socialLegacy
social/fsong.py
FSong.makeImages
def makeImages(self): """Make spiral images in sectors and steps. Plain, reversed, sectorialized, negative sectorialized outline, outline reversed, lonely only nodes, only edges, both """ # make layout self.makeLayout() self.setAgraph() # make function that accepts a mode, a sector # and nodes and edges True and False self.plotGraph() self.plotGraph("reversed",filename="tgraphR.png") agents=n.concatenate(self.np.sectorialized_agents__) for i, sector in enumerate(self.np.sectorialized_agents__): self.plotGraph("plain", sector,"sector{:02}.png".format(i)) self.plotGraph("reversed",sector,"sector{:02}R.png".format(i)) self.plotGraph("plain", n.setdiff1d(agents,sector),"sector{:02}N.png".format(i)) self.plotGraph("reversed",n.setdiff1d(agents,sector),"sector{:02}RN.png".format(i)) self.plotGraph("plain", [],"BLANK.png")
python
def makeImages(self): """Make spiral images in sectors and steps. Plain, reversed, sectorialized, negative sectorialized outline, outline reversed, lonely only nodes, only edges, both """ # make layout self.makeLayout() self.setAgraph() # make function that accepts a mode, a sector # and nodes and edges True and False self.plotGraph() self.plotGraph("reversed",filename="tgraphR.png") agents=n.concatenate(self.np.sectorialized_agents__) for i, sector in enumerate(self.np.sectorialized_agents__): self.plotGraph("plain", sector,"sector{:02}.png".format(i)) self.plotGraph("reversed",sector,"sector{:02}R.png".format(i)) self.plotGraph("plain", n.setdiff1d(agents,sector),"sector{:02}N.png".format(i)) self.plotGraph("reversed",n.setdiff1d(agents,sector),"sector{:02}RN.png".format(i)) self.plotGraph("plain", [],"BLANK.png")
[ "def", "makeImages", "(", "self", ")", ":", "# make layout", "self", ".", "makeLayout", "(", ")", "self", ".", "setAgraph", "(", ")", "# make function that accepts a mode, a sector", "# and nodes and edges True and False", "self", ".", "plotGraph", "(", ")", "self", ...
Make spiral images in sectors and steps. Plain, reversed, sectorialized, negative sectorialized outline, outline reversed, lonely only nodes, only edges, both
[ "Make", "spiral", "images", "in", "sectors", "and", "steps", "." ]
train
https://github.com/ttm/socialLegacy/blob/c0930cfe6e84392729449bf7c92569e1556fd109/social/fsong.py#L42-L63
ttm/socialLegacy
social/fsong.py
FSong.plotGraph
def plotGraph(self,mode="plain",nodes=None,filename="tgraph.png"): """Plot graph with nodes (iterable) into filename """ if nodes==None: nodes=self.nodes else: nodes=[i for i in self.nodes if i in nodes] for node in self.nodes: n_=self.A.get_node(node) if mode=="plain": nmode=1 else: nmode=-1 pos="{},{}".format(self.xi[::nmode][self.nm.nodes_.index(node)],self.yi[::nmode][self.nm.nodes_.index(node)]) n_.attr["pos"]=pos n_.attr["pin"]=True color='#%02x%02x%02x' % tuple([255*i for i in self.cm[int(self.clustering[n_]*255)][:-1]]) n_.attr['fillcolor']= color n_.attr['fixedsize']=True n_.attr['width']= abs(.1*(self.nm.degrees[n_]+ .5)) n_.attr['height']= abs(.1*(self.nm.degrees[n_]+.5)) n_.attr["label"]="" if node not in nodes: n_.attr["style"]="invis" else: n_.attr["style"]="filled" for e in self.edges: e.attr['penwidth']=3.4 e.attr["arrowsize"]=1.5 e.attr["arrowhead"]="lteeoldiamond" e.attr["style"]="" if sum([i in nodes for i in (e[0],e[1])])==2: e.attr["style"]="" else: e.attr["style"]="invis" tname="{}{}".format(self.basedir,filename) print(tname) self.A.draw(tname,prog="neato")
python
def plotGraph(self,mode="plain",nodes=None,filename="tgraph.png"): """Plot graph with nodes (iterable) into filename """ if nodes==None: nodes=self.nodes else: nodes=[i for i in self.nodes if i in nodes] for node in self.nodes: n_=self.A.get_node(node) if mode=="plain": nmode=1 else: nmode=-1 pos="{},{}".format(self.xi[::nmode][self.nm.nodes_.index(node)],self.yi[::nmode][self.nm.nodes_.index(node)]) n_.attr["pos"]=pos n_.attr["pin"]=True color='#%02x%02x%02x' % tuple([255*i for i in self.cm[int(self.clustering[n_]*255)][:-1]]) n_.attr['fillcolor']= color n_.attr['fixedsize']=True n_.attr['width']= abs(.1*(self.nm.degrees[n_]+ .5)) n_.attr['height']= abs(.1*(self.nm.degrees[n_]+.5)) n_.attr["label"]="" if node not in nodes: n_.attr["style"]="invis" else: n_.attr["style"]="filled" for e in self.edges: e.attr['penwidth']=3.4 e.attr["arrowsize"]=1.5 e.attr["arrowhead"]="lteeoldiamond" e.attr["style"]="" if sum([i in nodes for i in (e[0],e[1])])==2: e.attr["style"]="" else: e.attr["style"]="invis" tname="{}{}".format(self.basedir,filename) print(tname) self.A.draw(tname,prog="neato")
[ "def", "plotGraph", "(", "self", ",", "mode", "=", "\"plain\"", ",", "nodes", "=", "None", ",", "filename", "=", "\"tgraph.png\"", ")", ":", "if", "nodes", "==", "None", ":", "nodes", "=", "self", ".", "nodes", "else", ":", "nodes", "=", "[", "i", ...
Plot graph with nodes (iterable) into filename
[ "Plot", "graph", "with", "nodes", "(", "iterable", ")", "into", "filename" ]
train
https://github.com/ttm/socialLegacy/blob/c0930cfe6e84392729449bf7c92569e1556fd109/social/fsong.py#L72-L109
ttm/socialLegacy
social/fsong.py
FSong.makeSong
def makeSong(self): """Render abstract animation """ self.makeVisualSong() self.makeAudibleSong() if self.make_video: self.makeAnimation()
python
def makeSong(self): """Render abstract animation """ self.makeVisualSong() self.makeAudibleSong() if self.make_video: self.makeAnimation()
[ "def", "makeSong", "(", "self", ")", ":", "self", ".", "makeVisualSong", "(", ")", "self", ".", "makeAudibleSong", "(", ")", "if", "self", ".", "make_video", ":", "self", ".", "makeAnimation", "(", ")" ]
Render abstract animation
[ "Render", "abstract", "animation" ]
train
https://github.com/ttm/socialLegacy/blob/c0930cfe6e84392729449bf7c92569e1556fd109/social/fsong.py#L127-L133
ttm/socialLegacy
social/fsong.py
FSong.makeVisualSong
def makeVisualSong(self): """Return a sequence of images and durations. """ self.files=os.listdir(self.basedir) self.stairs=[i for i in self.files if ("stair" in i) and ("R" in i)] self.sectors=[i for i in self.files if "sector" in i] self.stairs.sort() self.sectors.sort() filenames=[self.basedir+i for i in self.sectors[:4]] self.iS0=mpy.ImageSequenceClip(filenames,durations=[1.5,2.5,.5,1.5]) self.iS1=mpy.ImageSequenceClip( [self.basedir+self.sectors[2], self.basedir+self.sectors[3], self.basedir+self.sectors[2], self.basedir+self.sectors[3], self.basedir+self.sectors[2], self.basedir+self.sectors[3], self.basedir+self.sectors[2], self.basedir+self.sectors[3]], durations=[0.25]*8) self.iS2=mpy.ImageSequenceClip( [self.basedir+self.sectors[2], self.basedir+self.sectors[3], self.basedir+self.sectors[2], self.basedir+self.sectors[3], self.basedir+self.sectors[0]], durations=[0.75,0.25,0.75,0.25,2.]) # cai para sensível self.iS3=mpy.ImageSequenceClip( [self.basedir+"BLANK.png", self.basedir+self.sectors[0], self.basedir+self.sectors[1], self.basedir+self.sectors[1], self.basedir+self.sectors[1], self.basedir+self.sectors[0], self.basedir+self.sectors[0]], durations=[1,0.5,2.,.25,.25,1.75, 0.25]) # [-1,8] self.iS4=mpy.ImageSequenceClip( [self.basedir+self.sectors[2], # 1 self.basedir+self.sectors[3], # .5 self.basedir+self.sectors[5], # .5 self.basedir+self.sectors[2], # .75 self.basedir+self.sectors[0], #.25 self.basedir+self.sectors[2], # 1 self.basedir+self.sectors[0], # 2 8 self.basedir+self.sectors[3], # 2 7 self.basedir+self.sectors[0], # 2 -1 self.basedir+"BLANK.png",# 2 ], durations=[1,0.5,0.5,.75, .25,1., 2.,2.,2.,2.]) # [0,7,11,0] self.iS=mpy.concatenate_videoclips(( self.iS0,self.iS1,self.iS2,self.iS3,self.iS4))
python
def makeVisualSong(self): """Return a sequence of images and durations. """ self.files=os.listdir(self.basedir) self.stairs=[i for i in self.files if ("stair" in i) and ("R" in i)] self.sectors=[i for i in self.files if "sector" in i] self.stairs.sort() self.sectors.sort() filenames=[self.basedir+i for i in self.sectors[:4]] self.iS0=mpy.ImageSequenceClip(filenames,durations=[1.5,2.5,.5,1.5]) self.iS1=mpy.ImageSequenceClip( [self.basedir+self.sectors[2], self.basedir+self.sectors[3], self.basedir+self.sectors[2], self.basedir+self.sectors[3], self.basedir+self.sectors[2], self.basedir+self.sectors[3], self.basedir+self.sectors[2], self.basedir+self.sectors[3]], durations=[0.25]*8) self.iS2=mpy.ImageSequenceClip( [self.basedir+self.sectors[2], self.basedir+self.sectors[3], self.basedir+self.sectors[2], self.basedir+self.sectors[3], self.basedir+self.sectors[0]], durations=[0.75,0.25,0.75,0.25,2.]) # cai para sensível self.iS3=mpy.ImageSequenceClip( [self.basedir+"BLANK.png", self.basedir+self.sectors[0], self.basedir+self.sectors[1], self.basedir+self.sectors[1], self.basedir+self.sectors[1], self.basedir+self.sectors[0], self.basedir+self.sectors[0]], durations=[1,0.5,2.,.25,.25,1.75, 0.25]) # [-1,8] self.iS4=mpy.ImageSequenceClip( [self.basedir+self.sectors[2], # 1 self.basedir+self.sectors[3], # .5 self.basedir+self.sectors[5], # .5 self.basedir+self.sectors[2], # .75 self.basedir+self.sectors[0], #.25 self.basedir+self.sectors[2], # 1 self.basedir+self.sectors[0], # 2 8 self.basedir+self.sectors[3], # 2 7 self.basedir+self.sectors[0], # 2 -1 self.basedir+"BLANK.png",# 2 ], durations=[1,0.5,0.5,.75, .25,1., 2.,2.,2.,2.]) # [0,7,11,0] self.iS=mpy.concatenate_videoclips(( self.iS0,self.iS1,self.iS2,self.iS3,self.iS4))
[ "def", "makeVisualSong", "(", "self", ")", ":", "self", ".", "files", "=", "os", ".", "listdir", "(", "self", ".", "basedir", ")", "self", ".", "stairs", "=", "[", "i", "for", "i", "in", "self", ".", "files", "if", "(", "\"stair\"", "in", "i", ")...
Return a sequence of images and durations.
[ "Return", "a", "sequence", "of", "images", "and", "durations", "." ]
train
https://github.com/ttm/socialLegacy/blob/c0930cfe6e84392729449bf7c92569e1556fd109/social/fsong.py#L134-L188
ttm/socialLegacy
social/fsong.py
FSong.makeAudibleSong
def makeAudibleSong(self): """Use mass to render wav soundtrack. """ sound0=n.hstack((sy.render(220,d=1.5), sy.render(220*(2**(7/12)),d=2.5), sy.render(220*(2**(-5/12)),d=.5), sy.render(220*(2**(0/12)),d=1.5), )) sound1=n.hstack((sy.render(220*(2**(0/12)),d=.25), sy.render(220*(2**(7/12)),d=.25), sy.render(220*(2**(0/12)),d=.25), sy.render(220*(2**(7/12)),d=.25), sy.render(220*(2**(0/12)),d=.25), sy.render(220*(2**(7/12)),d=.25), sy.render(220*(2**(0/12)),d=.25), sy.render(220*(2**(7/12)),d=.25), )) sound2=n.hstack((sy.render(220*(2**(0/12)),d=.75), sy.render(220*(2**(0/12)),d=.25), sy.render(220*(2**(7/12)),d=.75), sy.render(220*(2**(0/12)),d=.25), sy.render(220*(2**(-1/12)),d=2.0), )) sound3=n.hstack((n.zeros(44100), sy.render(220*(2**(-1/12)),d=.5), sy.render(220*(2**(8/12)),d=2.), sy.render(220*(2**(8/12)),d=.25), sy.render(220*(2**(8/12)),d=.25), sy.render(220*(2**(-1/12)),d=1.75), sy.render(220*(2**(-1/12)),d=.25), )) sound4=n.hstack(( sy.render(220*(2**(0/12)),d=1.), sy.render(220*(2**(7/12)),d=.5), sy.render(220*(2**(11/12)),d=.5), sy.render(220*(2**(12/12)),d=.75), sy.render(220*(2**(11/12)),d=.25), sy.render(220*(2**(12/12)),d=1.), sy.render(220*(2**(8/12)),d=2.), sy.render(220*(2**(7/12)),d=2.), sy.render(220*(2**(-1/12)),d=2.), n.zeros(2*44100) )) sound=n.hstack((sound0,sound1,sound2,sound3,sound4)) UT.write(sound,"sound.wav")
python
def makeAudibleSong(self): """Use mass to render wav soundtrack. """ sound0=n.hstack((sy.render(220,d=1.5), sy.render(220*(2**(7/12)),d=2.5), sy.render(220*(2**(-5/12)),d=.5), sy.render(220*(2**(0/12)),d=1.5), )) sound1=n.hstack((sy.render(220*(2**(0/12)),d=.25), sy.render(220*(2**(7/12)),d=.25), sy.render(220*(2**(0/12)),d=.25), sy.render(220*(2**(7/12)),d=.25), sy.render(220*(2**(0/12)),d=.25), sy.render(220*(2**(7/12)),d=.25), sy.render(220*(2**(0/12)),d=.25), sy.render(220*(2**(7/12)),d=.25), )) sound2=n.hstack((sy.render(220*(2**(0/12)),d=.75), sy.render(220*(2**(0/12)),d=.25), sy.render(220*(2**(7/12)),d=.75), sy.render(220*(2**(0/12)),d=.25), sy.render(220*(2**(-1/12)),d=2.0), )) sound3=n.hstack((n.zeros(44100), sy.render(220*(2**(-1/12)),d=.5), sy.render(220*(2**(8/12)),d=2.), sy.render(220*(2**(8/12)),d=.25), sy.render(220*(2**(8/12)),d=.25), sy.render(220*(2**(-1/12)),d=1.75), sy.render(220*(2**(-1/12)),d=.25), )) sound4=n.hstack(( sy.render(220*(2**(0/12)),d=1.), sy.render(220*(2**(7/12)),d=.5), sy.render(220*(2**(11/12)),d=.5), sy.render(220*(2**(12/12)),d=.75), sy.render(220*(2**(11/12)),d=.25), sy.render(220*(2**(12/12)),d=1.), sy.render(220*(2**(8/12)),d=2.), sy.render(220*(2**(7/12)),d=2.), sy.render(220*(2**(-1/12)),d=2.), n.zeros(2*44100) )) sound=n.hstack((sound0,sound1,sound2,sound3,sound4)) UT.write(sound,"sound.wav")
[ "def", "makeAudibleSong", "(", "self", ")", ":", "sound0", "=", "n", ".", "hstack", "(", "(", "sy", ".", "render", "(", "220", ",", "d", "=", "1.5", ")", ",", "sy", ".", "render", "(", "220", "*", "(", "2", "**", "(", "7", "/", "12", ")", "...
Use mass to render wav soundtrack.
[ "Use", "mass", "to", "render", "wav", "soundtrack", "." ]
train
https://github.com/ttm/socialLegacy/blob/c0930cfe6e84392729449bf7c92569e1556fd109/social/fsong.py#L194-L239
ttm/socialLegacy
social/fsong.py
FSong.makeAnimation
def makeAnimation(self): """Use pymovie to render (visual+audio)+text overlays. """ aclip=mpy.AudioFileClip("sound.wav") self.iS=self.iS.set_audio(aclip) self.iS.write_videofile("mixedVideo.webm",15,audio=True) print("wrote "+"mixedVideo.webm")
python
def makeAnimation(self): """Use pymovie to render (visual+audio)+text overlays. """ aclip=mpy.AudioFileClip("sound.wav") self.iS=self.iS.set_audio(aclip) self.iS.write_videofile("mixedVideo.webm",15,audio=True) print("wrote "+"mixedVideo.webm")
[ "def", "makeAnimation", "(", "self", ")", ":", "aclip", "=", "mpy", ".", "AudioFileClip", "(", "\"sound.wav\"", ")", "self", ".", "iS", "=", "self", ".", "iS", ".", "set_audio", "(", "aclip", ")", "self", ".", "iS", ".", "write_videofile", "(", "\"mixe...
Use pymovie to render (visual+audio)+text overlays.
[ "Use", "pymovie", "to", "render", "(", "visual", "+", "audio", ")", "+", "text", "overlays", "." ]
train
https://github.com/ttm/socialLegacy/blob/c0930cfe6e84392729449bf7c92569e1556fd109/social/fsong.py#L240-L246
Kunstmord/datalib
src/misc.py
cutoff_filename
def cutoff_filename(prefix, suffix, input_str): """ Cuts off the start and end of a string, as specified by 2 parameters Parameters ---------- prefix : string, if input_str starts with prefix, will cut off prefix suffix : string, if input_str end with suffix, will cut off suffix input_str : the string to be processed Returns ------- A string, from which the start and end have been cut """ if prefix is not '': if input_str.startswith(prefix): input_str = input_str[len(prefix):] if suffix is not '': if input_str.endswith(suffix): input_str = input_str[:-len(suffix)] return input_str
python
def cutoff_filename(prefix, suffix, input_str): """ Cuts off the start and end of a string, as specified by 2 parameters Parameters ---------- prefix : string, if input_str starts with prefix, will cut off prefix suffix : string, if input_str end with suffix, will cut off suffix input_str : the string to be processed Returns ------- A string, from which the start and end have been cut """ if prefix is not '': if input_str.startswith(prefix): input_str = input_str[len(prefix):] if suffix is not '': if input_str.endswith(suffix): input_str = input_str[:-len(suffix)] return input_str
[ "def", "cutoff_filename", "(", "prefix", ",", "suffix", ",", "input_str", ")", ":", "if", "prefix", "is", "not", "''", ":", "if", "input_str", ".", "startswith", "(", "prefix", ")", ":", "input_str", "=", "input_str", "[", "len", "(", "prefix", ")", ":...
Cuts off the start and end of a string, as specified by 2 parameters Parameters ---------- prefix : string, if input_str starts with prefix, will cut off prefix suffix : string, if input_str end with suffix, will cut off suffix input_str : the string to be processed Returns ------- A string, from which the start and end have been cut
[ "Cuts", "off", "the", "start", "and", "end", "of", "a", "string", "as", "specified", "by", "2", "parameters" ]
train
https://github.com/Kunstmord/datalib/blob/9d7db3e7c3a5feeeb5d19eb0dbee858bd2b50886/src/misc.py#L34-L54
CodyKochmann/strict_functions
strict_functions/trace3.py
get_frame_src
def get_frame_src(f:Frame) -> str: ''' inspects a frame and returns a string with the following <src-path>:<src-line> -> <function-name> <source-code> ''' path, line, src, fn = _get_frame( inspect.getframeinfo(f) ) return '{}:{} -> {}\n{}'.format( path.split(os.sep)[-1], line, fn, repr(src[0][:-1]) # shave off \n )
python
def get_frame_src(f:Frame) -> str: ''' inspects a frame and returns a string with the following <src-path>:<src-line> -> <function-name> <source-code> ''' path, line, src, fn = _get_frame( inspect.getframeinfo(f) ) return '{}:{} -> {}\n{}'.format( path.split(os.sep)[-1], line, fn, repr(src[0][:-1]) # shave off \n )
[ "def", "get_frame_src", "(", "f", ":", "Frame", ")", "->", "str", ":", "path", ",", "line", ",", "src", ",", "fn", "=", "_get_frame", "(", "inspect", ".", "getframeinfo", "(", "f", ")", ")", "return", "'{}:{} -> {}\\n{}'", ".", "format", "(", "path", ...
inspects a frame and returns a string with the following <src-path>:<src-line> -> <function-name> <source-code>
[ "inspects", "a", "frame", "and", "returns", "a", "string", "with", "the", "following" ]
train
https://github.com/CodyKochmann/strict_functions/blob/adaf78084c66929552d80c95f980e7e0c4331478/strict_functions/trace3.py#L26-L40
CodyKochmann/strict_functions
strict_functions/trace3.py
get_locals
def get_locals(f:Frame) -> str: ''' returns a formatted view of the local variables in a frame ''' return pformat({i:f.f_locals[i] for i in f.f_locals if not i.startswith('__')})
python
def get_locals(f:Frame) -> str: ''' returns a formatted view of the local variables in a frame ''' return pformat({i:f.f_locals[i] for i in f.f_locals if not i.startswith('__')})
[ "def", "get_locals", "(", "f", ":", "Frame", ")", "->", "str", ":", "return", "pformat", "(", "{", "i", ":", "f", ".", "f_locals", "[", "i", "]", "for", "i", "in", "f", ".", "f_locals", "if", "not", "i", ".", "startswith", "(", "'__'", ")", "}"...
returns a formatted view of the local variables in a frame
[ "returns", "a", "formatted", "view", "of", "the", "local", "variables", "in", "a", "frame" ]
train
https://github.com/CodyKochmann/strict_functions/blob/adaf78084c66929552d80c95f980e7e0c4331478/strict_functions/trace3.py#L42-L44
CodyKochmann/strict_functions
strict_functions/trace3.py
default_profiler
def default_profiler(f:Frame, _type:str, _value:Any): ''' inspects an input frame and pretty prints the following: <src-path>:<src-line> -> <function-name> <source-code> <local-variables> ---------------------------------------- ''' try: profile_print( '\n'.join([ get_frame_src(f), get_locals(f), '----------------------------------------' ]) ) except: pass
python
def default_profiler(f:Frame, _type:str, _value:Any): ''' inspects an input frame and pretty prints the following: <src-path>:<src-line> -> <function-name> <source-code> <local-variables> ---------------------------------------- ''' try: profile_print( '\n'.join([ get_frame_src(f), get_locals(f), '----------------------------------------' ]) ) except: pass
[ "def", "default_profiler", "(", "f", ":", "Frame", ",", "_type", ":", "str", ",", "_value", ":", "Any", ")", ":", "try", ":", "profile_print", "(", "'\\n'", ".", "join", "(", "[", "get_frame_src", "(", "f", ")", ",", "get_locals", "(", "f", ")", ",...
inspects an input frame and pretty prints the following: <src-path>:<src-line> -> <function-name> <source-code> <local-variables> ----------------------------------------
[ "inspects", "an", "input", "frame", "and", "pretty", "prints", "the", "following", ":" ]
train
https://github.com/CodyKochmann/strict_functions/blob/adaf78084c66929552d80c95f980e7e0c4331478/strict_functions/trace3.py#L46-L63
CodyKochmann/strict_functions
strict_functions/trace3.py
trace
def trace(fn=None, profiler=None) -> Callable: ''' This decorator allows you to visually trace the steps of a function as it executes to see what happens to the data as things are being processed. If you want to use a custom profiler, use the @trace(profiler=my_custom_profiler) syntax. Example Usage: def count_to(target): for i in range(1, target+1): yield i @trace def sum_of_count(target): total = 0 for i in count_to(target): total += i return total sum_of_count(10) ''' # analyze usage custom_profiler = fn is None and profiler is not None no_profiler = profiler is None and fn is not None no_args = profiler is None and fn is None # adjust for usage if custom_profiler: # for @trace(profiler=...) return partial(trace, profiler=profiler) elif no_args: # for @trace() return trace elif no_profiler: # for @trace profiler = default_profiler # validate input assert callable(fn) assert callable(profiler) # build the decorator @wraps(fn) def wrapper(*args, **kwargs): # flag for default_profiler to know to ignore this scope wafflestwaffles = None # save the previous profiler old_profiler = sys.getprofile() # set the new profiler sys.setprofile(profiler) try: # run the function return fn(*args, **kwargs) finally: # revert the profiler sys.setprofile(old_profiler) return wrapper
python
def trace(fn=None, profiler=None) -> Callable: ''' This decorator allows you to visually trace the steps of a function as it executes to see what happens to the data as things are being processed. If you want to use a custom profiler, use the @trace(profiler=my_custom_profiler) syntax. Example Usage: def count_to(target): for i in range(1, target+1): yield i @trace def sum_of_count(target): total = 0 for i in count_to(target): total += i return total sum_of_count(10) ''' # analyze usage custom_profiler = fn is None and profiler is not None no_profiler = profiler is None and fn is not None no_args = profiler is None and fn is None # adjust for usage if custom_profiler: # for @trace(profiler=...) return partial(trace, profiler=profiler) elif no_args: # for @trace() return trace elif no_profiler: # for @trace profiler = default_profiler # validate input assert callable(fn) assert callable(profiler) # build the decorator @wraps(fn) def wrapper(*args, **kwargs): # flag for default_profiler to know to ignore this scope wafflestwaffles = None # save the previous profiler old_profiler = sys.getprofile() # set the new profiler sys.setprofile(profiler) try: # run the function return fn(*args, **kwargs) finally: # revert the profiler sys.setprofile(old_profiler) return wrapper
[ "def", "trace", "(", "fn", "=", "None", ",", "profiler", "=", "None", ")", "->", "Callable", ":", "# analyze usage", "custom_profiler", "=", "fn", "is", "None", "and", "profiler", "is", "not", "None", "no_profiler", "=", "profiler", "is", "None", "and", ...
This decorator allows you to visually trace the steps of a function as it executes to see what happens to the data as things are being processed. If you want to use a custom profiler, use the @trace(profiler=my_custom_profiler) syntax. Example Usage: def count_to(target): for i in range(1, target+1): yield i @trace def sum_of_count(target): total = 0 for i in count_to(target): total += i return total sum_of_count(10)
[ "This", "decorator", "allows", "you", "to", "visually", "trace", "the", "steps", "of", "a", "function", "as", "it", "executes", "to", "see", "what", "happens", "to", "the", "data", "as", "things", "are", "being", "processed", "." ]
train
https://github.com/CodyKochmann/strict_functions/blob/adaf78084c66929552d80c95f980e7e0c4331478/strict_functions/trace3.py#L65-L118
openstack/stacktach-shoebox
shoebox/handlers.py
MoveFileCallback.on_close
def on_close(self, filename): """Move this file to destination folder.""" shutil.move(filename, self.destination_folder) path, fn = os.path.split(filename) return os.path.join(self.destination_folder, fn)
python
def on_close(self, filename): """Move this file to destination folder.""" shutil.move(filename, self.destination_folder) path, fn = os.path.split(filename) return os.path.join(self.destination_folder, fn)
[ "def", "on_close", "(", "self", ",", "filename", ")", ":", "shutil", ".", "move", "(", "filename", ",", "self", ".", "destination_folder", ")", "path", ",", "fn", "=", "os", ".", "path", ".", "split", "(", "filename", ")", "return", "os", ".", "path"...
Move this file to destination folder.
[ "Move", "this", "file", "to", "destination", "folder", "." ]
train
https://github.com/openstack/stacktach-shoebox/blob/792b0fb25dee4eb1a18f841f2b3a2b9d01472627/shoebox/handlers.py#L85-L89
i3visio/entify
entify/lib/config_entify.py
getAllRegexp
def getAllRegexp(): ''' Method that recovers ALL the list of <RegexpObject> classes to be processed.... :return: Returns a list [] of <RegexpObject> classes. ''' logger = logging.getLogger("entify") logger.debug("Recovering all the available <RegexpObject> classes.") listAll = [] # For demo only #listAll.append(Demo()) listAll.append(BitcoinAddress()) listAll.append(DNI()) listAll.append(DogecoinAddress()) listAll.append(Email()) listAll.append(IPv4()) listAll.append(LitecoinAddress()) listAll.append(MD5()) listAll.append(NamecoinAddress()) listAll.append(PeercoinAddress()) listAll.append(SHA1()) listAll.append(SHA256()) listAll.append(URL()) # Add any additional import here #listAll.append(AnyNewRegexp) # <ADD_NEW_REGEXP_TO_THE_LIST> # Please, notify the authors if you have written a new regexp. logger.debug("Returning a list of " + str(len(listAll)) + " <RegexpObject> classes.") return listAll
python
def getAllRegexp(): ''' Method that recovers ALL the list of <RegexpObject> classes to be processed.... :return: Returns a list [] of <RegexpObject> classes. ''' logger = logging.getLogger("entify") logger.debug("Recovering all the available <RegexpObject> classes.") listAll = [] # For demo only #listAll.append(Demo()) listAll.append(BitcoinAddress()) listAll.append(DNI()) listAll.append(DogecoinAddress()) listAll.append(Email()) listAll.append(IPv4()) listAll.append(LitecoinAddress()) listAll.append(MD5()) listAll.append(NamecoinAddress()) listAll.append(PeercoinAddress()) listAll.append(SHA1()) listAll.append(SHA256()) listAll.append(URL()) # Add any additional import here #listAll.append(AnyNewRegexp) # <ADD_NEW_REGEXP_TO_THE_LIST> # Please, notify the authors if you have written a new regexp. logger.debug("Returning a list of " + str(len(listAll)) + " <RegexpObject> classes.") return listAll
[ "def", "getAllRegexp", "(", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "\"entify\"", ")", "logger", ".", "debug", "(", "\"Recovering all the available <RegexpObject> classes.\"", ")", "listAll", "=", "[", "]", "# For demo only", "#listAll.append(Demo()...
Method that recovers ALL the list of <RegexpObject> classes to be processed.... :return: Returns a list [] of <RegexpObject> classes.
[ "Method", "that", "recovers", "ALL", "the", "list", "of", "<RegexpObject", ">", "classes", "to", "be", "processed", "...." ]
train
https://github.com/i3visio/entify/blob/51c5b89cebee3a39d44d0918e2798739361f337c/entify/lib/config_entify.py#L45-L75
i3visio/entify
entify/lib/config_entify.py
getAllRegexpNames
def getAllRegexpNames(regexpList = None): ''' Method that recovers the names of the <RegexpObject> in a given list. :param regexpList: list of <RegexpObject>. If None, all the available <RegexpObject> will be recovered. :return: Array of strings containing the available regexps. ''' if regexpList == None: regexpList = getAllRegexp() listNames = ['all'] # going through the regexpList for r in regexpList: listNames.append(r.name) return listNames
python
def getAllRegexpNames(regexpList = None): ''' Method that recovers the names of the <RegexpObject> in a given list. :param regexpList: list of <RegexpObject>. If None, all the available <RegexpObject> will be recovered. :return: Array of strings containing the available regexps. ''' if regexpList == None: regexpList = getAllRegexp() listNames = ['all'] # going through the regexpList for r in regexpList: listNames.append(r.name) return listNames
[ "def", "getAllRegexpNames", "(", "regexpList", "=", "None", ")", ":", "if", "regexpList", "==", "None", ":", "regexpList", "=", "getAllRegexp", "(", ")", "listNames", "=", "[", "'all'", "]", "# going through the regexpList ", "for", "r", "in", "regexpList", ":...
Method that recovers the names of the <RegexpObject> in a given list. :param regexpList: list of <RegexpObject>. If None, all the available <RegexpObject> will be recovered. :return: Array of strings containing the available regexps.
[ "Method", "that", "recovers", "the", "names", "of", "the", "<RegexpObject", ">", "in", "a", "given", "list", "." ]
train
https://github.com/i3visio/entify/blob/51c5b89cebee3a39d44d0918e2798739361f337c/entify/lib/config_entify.py#L77-L91
i3visio/entify
entify/lib/config_entify.py
getRegexpsByName
def getRegexpsByName(regexpNames = ['all']): ''' Method that recovers the names of the <RegexpObject> in a given list. :param regexpNames: list of strings containing the possible regexp. :return: Array of <RegexpObject> classes. ''' allRegexpList = getAllRegexp() if 'all' in regexpNames: return allRegexpList regexpList = [] # going through the regexpList for name in regexpNames: for r in allRegexpList: if name == r.name: regexpList.append(r) return regexpList
python
def getRegexpsByName(regexpNames = ['all']): ''' Method that recovers the names of the <RegexpObject> in a given list. :param regexpNames: list of strings containing the possible regexp. :return: Array of <RegexpObject> classes. ''' allRegexpList = getAllRegexp() if 'all' in regexpNames: return allRegexpList regexpList = [] # going through the regexpList for name in regexpNames: for r in allRegexpList: if name == r.name: regexpList.append(r) return regexpList
[ "def", "getRegexpsByName", "(", "regexpNames", "=", "[", "'all'", "]", ")", ":", "allRegexpList", "=", "getAllRegexp", "(", ")", "if", "'all'", "in", "regexpNames", ":", "return", "allRegexpList", "regexpList", "=", "[", "]", "# going through the regexpList ", "...
Method that recovers the names of the <RegexpObject> in a given list. :param regexpNames: list of strings containing the possible regexp. :return: Array of <RegexpObject> classes.
[ "Method", "that", "recovers", "the", "names", "of", "the", "<RegexpObject", ">", "in", "a", "given", "list", "." ]
train
https://github.com/i3visio/entify/blob/51c5b89cebee3a39d44d0918e2798739361f337c/entify/lib/config_entify.py#L93-L112
duniter/duniter-python-api
duniterpy/documents/crc_pubkey.py
CRCPubkey.from_str
def from_str(cls: Type[CRCPubkeyType], crc_pubkey: str) -> CRCPubkeyType: """ Return CRCPubkey instance from CRC public key string :param crc_pubkey: CRC public key :return: """ data = CRCPubkey.re_crc_pubkey.match(crc_pubkey) if data is None: raise Exception("Could not parse CRC public key {0}".format(crc_pubkey)) pubkey = data.group(1) crc = data.group(2) return cls(pubkey, crc)
python
def from_str(cls: Type[CRCPubkeyType], crc_pubkey: str) -> CRCPubkeyType: """ Return CRCPubkey instance from CRC public key string :param crc_pubkey: CRC public key :return: """ data = CRCPubkey.re_crc_pubkey.match(crc_pubkey) if data is None: raise Exception("Could not parse CRC public key {0}".format(crc_pubkey)) pubkey = data.group(1) crc = data.group(2) return cls(pubkey, crc)
[ "def", "from_str", "(", "cls", ":", "Type", "[", "CRCPubkeyType", "]", ",", "crc_pubkey", ":", "str", ")", "->", "CRCPubkeyType", ":", "data", "=", "CRCPubkey", ".", "re_crc_pubkey", ".", "match", "(", "crc_pubkey", ")", "if", "data", "is", "None", ":", ...
Return CRCPubkey instance from CRC public key string :param crc_pubkey: CRC public key :return:
[ "Return", "CRCPubkey", "instance", "from", "CRC", "public", "key", "string" ]
train
https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/documents/crc_pubkey.py#L30-L42
duniter/duniter-python-api
duniterpy/documents/crc_pubkey.py
CRCPubkey.from_pubkey
def from_pubkey(cls: Type[CRCPubkeyType], pubkey: str) -> CRCPubkeyType: """ Return CRCPubkey instance from public key string :param pubkey: Public key :return: """ hash_root = hashlib.sha256() hash_root.update(base58.b58decode(pubkey)) hash_squared = hashlib.sha256() hash_squared.update(hash_root.digest()) b58_checksum = ensure_str(base58.b58encode(hash_squared.digest())) crc = b58_checksum[:3] return cls(pubkey, crc)
python
def from_pubkey(cls: Type[CRCPubkeyType], pubkey: str) -> CRCPubkeyType: """ Return CRCPubkey instance from public key string :param pubkey: Public key :return: """ hash_root = hashlib.sha256() hash_root.update(base58.b58decode(pubkey)) hash_squared = hashlib.sha256() hash_squared.update(hash_root.digest()) b58_checksum = ensure_str(base58.b58encode(hash_squared.digest())) crc = b58_checksum[:3] return cls(pubkey, crc)
[ "def", "from_pubkey", "(", "cls", ":", "Type", "[", "CRCPubkeyType", "]", ",", "pubkey", ":", "str", ")", "->", "CRCPubkeyType", ":", "hash_root", "=", "hashlib", ".", "sha256", "(", ")", "hash_root", ".", "update", "(", "base58", ".", "b58decode", "(", ...
Return CRCPubkey instance from public key string :param pubkey: Public key :return:
[ "Return", "CRCPubkey", "instance", "from", "public", "key", "string" ]
train
https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/documents/crc_pubkey.py#L45-L59
duniter/duniter-python-api
duniterpy/documents/crc_pubkey.py
CRCPubkey.is_valid
def is_valid(self) -> bool: """ Return True if CRC is valid :return: """ return CRCPubkey.from_pubkey(self.pubkey).crc == self.crc
python
def is_valid(self) -> bool: """ Return True if CRC is valid :return: """ return CRCPubkey.from_pubkey(self.pubkey).crc == self.crc
[ "def", "is_valid", "(", "self", ")", "->", "bool", ":", "return", "CRCPubkey", ".", "from_pubkey", "(", "self", ".", "pubkey", ")", ".", "crc", "==", "self", ".", "crc" ]
Return True if CRC is valid :return:
[ "Return", "True", "if", "CRC", "is", "valid", ":", "return", ":" ]
train
https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/documents/crc_pubkey.py#L61-L66
nitmir/pyprocmail
pyprocmail/procmail.py
Statement.delete
def delete(self): """Remove the statement from a ProcmailRC structure, raise a RuntimeError if the statement is not inside a ProcmailRC structure return the parent id""" if self.parent is None: raise RuntimeError( "Current statement has no parent, so it cannot " + "be deleted form a procmailrc structure" ) elif self.id is None: raise RuntimeError("id not set but have a parent, this should not be happening") else: parent_id = self.parent.id index = int(self.id.split('.')[-1]) self.parent.pop(index) self.parent = None self.id = None return parent_id
python
def delete(self): """Remove the statement from a ProcmailRC structure, raise a RuntimeError if the statement is not inside a ProcmailRC structure return the parent id""" if self.parent is None: raise RuntimeError( "Current statement has no parent, so it cannot " + "be deleted form a procmailrc structure" ) elif self.id is None: raise RuntimeError("id not set but have a parent, this should not be happening") else: parent_id = self.parent.id index = int(self.id.split('.')[-1]) self.parent.pop(index) self.parent = None self.id = None return parent_id
[ "def", "delete", "(", "self", ")", ":", "if", "self", ".", "parent", "is", "None", ":", "raise", "RuntimeError", "(", "\"Current statement has no parent, so it cannot \"", "+", "\"be deleted form a procmailrc structure\"", ")", "elif", "self", ".", "id", "is", "None...
Remove the statement from a ProcmailRC structure, raise a RuntimeError if the statement is not inside a ProcmailRC structure return the parent id
[ "Remove", "the", "statement", "from", "a", "ProcmailRC", "structure", "raise", "a", "RuntimeError", "if", "the", "statement", "is", "not", "inside", "a", "ProcmailRC", "structure", "return", "the", "parent", "id" ]
train
https://github.com/nitmir/pyprocmail/blob/60b63a1e4ad5eb5d516cc80f93cc90e0cd6d541b/pyprocmail/procmail.py#L70-L87
uw-it-aca/uw-restclients-uwnetid
uw_uwnetid/subscription_233.py
get_office365edu_prod_subs
def get_office365edu_prod_subs(netid): """ Return a restclients.models.uwnetid.Subscription objects on the given uwnetid """ subs = get_netid_subscriptions(netid, Subscription.SUBS_CODE_OFFICE_365) if subs is not None: for subscription in subs: if (subscription.subscription_code == Subscription.SUBS_CODE_OFFICE_365): return subscription return None
python
def get_office365edu_prod_subs(netid): """ Return a restclients.models.uwnetid.Subscription objects on the given uwnetid """ subs = get_netid_subscriptions(netid, Subscription.SUBS_CODE_OFFICE_365) if subs is not None: for subscription in subs: if (subscription.subscription_code == Subscription.SUBS_CODE_OFFICE_365): return subscription return None
[ "def", "get_office365edu_prod_subs", "(", "netid", ")", ":", "subs", "=", "get_netid_subscriptions", "(", "netid", ",", "Subscription", ".", "SUBS_CODE_OFFICE_365", ")", "if", "subs", "is", "not", "None", ":", "for", "subscription", "in", "subs", ":", "if", "(...
Return a restclients.models.uwnetid.Subscription objects on the given uwnetid
[ "Return", "a", "restclients", ".", "models", ".", "uwnetid", ".", "Subscription", "objects", "on", "the", "given", "uwnetid" ]
train
https://github.com/uw-it-aca/uw-restclients-uwnetid/blob/58c78b564f9c920a8f8fd408eec959ddd5605b0b/uw_uwnetid/subscription_233.py#L13-L25
benley/butcher
butcher/targets/genrule.py
GenRuleBuilder._metahash
def _metahash(self): """Include genrule cmd in the metahash.""" if self._cached_metahash: return self._cached_metahash mhash = base.BaseBuilder._metahash(self) log.debug('[%s]: Metahash input: cmd="%s"', self.address, self.cmd) mhash.update(self.cmd) self._cached_metahash = mhash return mhash
python
def _metahash(self): """Include genrule cmd in the metahash.""" if self._cached_metahash: return self._cached_metahash mhash = base.BaseBuilder._metahash(self) log.debug('[%s]: Metahash input: cmd="%s"', self.address, self.cmd) mhash.update(self.cmd) self._cached_metahash = mhash return mhash
[ "def", "_metahash", "(", "self", ")", ":", "if", "self", ".", "_cached_metahash", ":", "return", "self", ".", "_cached_metahash", "mhash", "=", "base", ".", "BaseBuilder", ".", "_metahash", "(", "self", ")", "log", ".", "debug", "(", "'[%s]: Metahash input: ...
Include genrule cmd in the metahash.
[ "Include", "genrule", "cmd", "in", "the", "metahash", "." ]
train
https://github.com/benley/butcher/blob/8b18828ea040af56b7835beab5fd03eab23cc9ee/butcher/targets/genrule.py#L50-L58
benley/butcher
butcher/targets/genrule.py
GenRuleBuilder.expand_cmd_labels
def expand_cmd_labels(self): """Expand make-style variables in cmd parameters. Currently: $(location <foo>) Location of one dependency or output file. $(locations <foo>) Space-delimited list of foo's output files. $(SRCS) Space-delimited list of this rule's source files. $(OUTS) Space-delimited list of this rule's output files. $(@D) Full path to the output directory for this rule. $@ Path to the output (single) file for this rule. """ cmd = self.cmd def _expand_onesrc(): """Expand $@ or $(@) to one output file.""" outs = self.rule.params['outs'] or [] if len(outs) != 1: raise error.TargetBuildFailed( self.address, '$@ substitution requires exactly one output file, but ' 'this rule has %s of them: %s' % (len(outs), outs)) else: return os.path.join(self.buildroot, self.path_to_this_rule, outs[0]) # TODO: this function is dumb and way too long def _expand_makevar(re_match): """Expands one substitution symbol.""" # Expand $(location foo) and $(locations foo): label = None tagstr = re_match.groups()[0] tag_location = re.match( r'\s*location\s+([A-Za-z0-9/\-_:\.]+)\s*', tagstr) tag_locations = re.match( r'\s*locations\s+([A-Za-z0-9/\-_:\.]+)\s*', tagstr) if tag_location: label = tag_location.groups()[0] elif tag_locations: label = tag_locations.groups()[0] if label: # Is it a filename found in the outputs of this rule? if label in self.rule.params['outs']: return os.path.join(self.buildroot, self.address.repo, self.address.path, label) # Is it an address found in the deps of this rule? addr = self.rule.makeaddress(label) if addr not in self.rule.composed_deps(): raise error.TargetBuildFailed( self.address, '%s is referenced in cmd but is neither an output ' 'file from this rule nor a dependency of this rule.' % label) else: paths = [x for x in self.rulefor(addr).output_files] if len(paths) is 0: raise error.TargetBuildFailed( self.address, 'cmd refers to %s, but it has no output files.') elif len(paths) > 1 and tag_location: raise error.TargetBuildFailed( self.address, 'Bad substitution in cmd: Expected exactly one ' 'file, but %s expands to %s files.' % ( addr, len(paths))) else: return ' '.join( [os.path.join(self.buildroot, x) for x in paths]) # Expand $(OUTS): elif re.match(r'OUTS', tagstr): return ' '.join( [os.path.join(self.buildroot, x) for x in self.rule.output_files]) # Expand $(SRCS): elif re.match(r'SRCS', tagstr): return ' '.join(os.path.join(self.path_to_this_rule, x) for x in self.rule.params['srcs'] or []) # Expand $(@D): elif re.match(r'\s*@D\s*', tagstr): ruledir = os.path.join(self.buildroot, self.path_to_this_rule) return ruledir # Expand $(@), $@: elif re.match(r'\s*@\s*', tagstr): return _expand_onesrc() else: raise error.TargetBuildFailed( self.address, '[%s] Unrecognized substitution in cmd: %s' % ( self.address, re_match.group())) cmd, _ = re.subn(self.paren_tag_re, _expand_makevar, cmd) # Match tags starting with $ without parens. Will also catch parens, so # this goes after the tag_re substitutions. cmd, _ = re.subn(self.noparen_tag_re, _expand_makevar, cmd) # Now that we're done looking for $(blabla) and $bla parameters, clean # up any $$ escaping: cmd, _ = re.subn(r'\$\$', '$', cmd) # Maybe try heuristic label expansion? Actually on second thought # that's a terrible idea. Use the explicit syntax, you lazy slobs. ;-) # TODO: Maybe consider other expansions from the gnu make manual? # $^ might be useful. # http://www.gnu.org/software/make/manual/html_node/Automatic-Variables.html#Automatic-Variables self.cmd = cmd
python
def expand_cmd_labels(self): """Expand make-style variables in cmd parameters. Currently: $(location <foo>) Location of one dependency or output file. $(locations <foo>) Space-delimited list of foo's output files. $(SRCS) Space-delimited list of this rule's source files. $(OUTS) Space-delimited list of this rule's output files. $(@D) Full path to the output directory for this rule. $@ Path to the output (single) file for this rule. """ cmd = self.cmd def _expand_onesrc(): """Expand $@ or $(@) to one output file.""" outs = self.rule.params['outs'] or [] if len(outs) != 1: raise error.TargetBuildFailed( self.address, '$@ substitution requires exactly one output file, but ' 'this rule has %s of them: %s' % (len(outs), outs)) else: return os.path.join(self.buildroot, self.path_to_this_rule, outs[0]) # TODO: this function is dumb and way too long def _expand_makevar(re_match): """Expands one substitution symbol.""" # Expand $(location foo) and $(locations foo): label = None tagstr = re_match.groups()[0] tag_location = re.match( r'\s*location\s+([A-Za-z0-9/\-_:\.]+)\s*', tagstr) tag_locations = re.match( r'\s*locations\s+([A-Za-z0-9/\-_:\.]+)\s*', tagstr) if tag_location: label = tag_location.groups()[0] elif tag_locations: label = tag_locations.groups()[0] if label: # Is it a filename found in the outputs of this rule? if label in self.rule.params['outs']: return os.path.join(self.buildroot, self.address.repo, self.address.path, label) # Is it an address found in the deps of this rule? addr = self.rule.makeaddress(label) if addr not in self.rule.composed_deps(): raise error.TargetBuildFailed( self.address, '%s is referenced in cmd but is neither an output ' 'file from this rule nor a dependency of this rule.' % label) else: paths = [x for x in self.rulefor(addr).output_files] if len(paths) is 0: raise error.TargetBuildFailed( self.address, 'cmd refers to %s, but it has no output files.') elif len(paths) > 1 and tag_location: raise error.TargetBuildFailed( self.address, 'Bad substitution in cmd: Expected exactly one ' 'file, but %s expands to %s files.' % ( addr, len(paths))) else: return ' '.join( [os.path.join(self.buildroot, x) for x in paths]) # Expand $(OUTS): elif re.match(r'OUTS', tagstr): return ' '.join( [os.path.join(self.buildroot, x) for x in self.rule.output_files]) # Expand $(SRCS): elif re.match(r'SRCS', tagstr): return ' '.join(os.path.join(self.path_to_this_rule, x) for x in self.rule.params['srcs'] or []) # Expand $(@D): elif re.match(r'\s*@D\s*', tagstr): ruledir = os.path.join(self.buildroot, self.path_to_this_rule) return ruledir # Expand $(@), $@: elif re.match(r'\s*@\s*', tagstr): return _expand_onesrc() else: raise error.TargetBuildFailed( self.address, '[%s] Unrecognized substitution in cmd: %s' % ( self.address, re_match.group())) cmd, _ = re.subn(self.paren_tag_re, _expand_makevar, cmd) # Match tags starting with $ without parens. Will also catch parens, so # this goes after the tag_re substitutions. cmd, _ = re.subn(self.noparen_tag_re, _expand_makevar, cmd) # Now that we're done looking for $(blabla) and $bla parameters, clean # up any $$ escaping: cmd, _ = re.subn(r'\$\$', '$', cmd) # Maybe try heuristic label expansion? Actually on second thought # that's a terrible idea. Use the explicit syntax, you lazy slobs. ;-) # TODO: Maybe consider other expansions from the gnu make manual? # $^ might be useful. # http://www.gnu.org/software/make/manual/html_node/Automatic-Variables.html#Automatic-Variables self.cmd = cmd
[ "def", "expand_cmd_labels", "(", "self", ")", ":", "cmd", "=", "self", ".", "cmd", "def", "_expand_onesrc", "(", ")", ":", "\"\"\"Expand $@ or $(@) to one output file.\"\"\"", "outs", "=", "self", ".", "rule", ".", "params", "[", "'outs'", "]", "or", "[", "]...
Expand make-style variables in cmd parameters. Currently: $(location <foo>) Location of one dependency or output file. $(locations <foo>) Space-delimited list of foo's output files. $(SRCS) Space-delimited list of this rule's source files. $(OUTS) Space-delimited list of this rule's output files. $(@D) Full path to the output directory for this rule. $@ Path to the output (single) file for this rule.
[ "Expand", "make", "-", "style", "variables", "in", "cmd", "parameters", "." ]
train
https://github.com/benley/butcher/blob/8b18828ea040af56b7835beab5fd03eab23cc9ee/butcher/targets/genrule.py#L64-L174
benley/butcher
butcher/targets/genrule.py
GenRule.output_files
def output_files(self): """Returns list of output files from this rule, relative to buildroot. In this case it's simple (for now) - the output files are enumerated in the rule definition. """ outs = [os.path.join(self.address.repo, self.address.path, x) for x in self.params['outs']] return outs
python
def output_files(self): """Returns list of output files from this rule, relative to buildroot. In this case it's simple (for now) - the output files are enumerated in the rule definition. """ outs = [os.path.join(self.address.repo, self.address.path, x) for x in self.params['outs']] return outs
[ "def", "output_files", "(", "self", ")", ":", "outs", "=", "[", "os", ".", "path", ".", "join", "(", "self", ".", "address", ".", "repo", ",", "self", ".", "address", ".", "path", ",", "x", ")", "for", "x", "in", "self", ".", "params", "[", "'o...
Returns list of output files from this rule, relative to buildroot. In this case it's simple (for now) - the output files are enumerated in the rule definition.
[ "Returns", "list", "of", "output", "files", "from", "this", "rule", "relative", "to", "buildroot", "." ]
train
https://github.com/benley/butcher/blob/8b18828ea040af56b7835beab5fd03eab23cc9ee/butcher/targets/genrule.py#L268-L276
littlemo/moear-spider-zhihudaily
moear_spider_zhihudaily/spiders/zhihu_daily.py
ZhihuDailySpider.parse
def parse(self, response): ''' 根据对 ``start_urls`` 中提供链接的请求响应包内容,解析生成具体文章链接请求 :param Response response: 由 ``Scrapy`` 调用并传入的请求响应对象 ''' content_raw = response.body.decode() self.logger.debug('响应body原始数据:{}'.format(content_raw)) content = json.loads(content_raw, encoding='UTF-8') self.logger.debug(content) # 文章发布日期 date = datetime.datetime.strptime(content['date'], '%Y%m%d') strftime = date.strftime("%Y-%m-%d") self.logger.info('日期:{}'.format(strftime)) # 处理头条文章列表,将其 `top` 标记到相应 __story__ 中 if 'top_stories' in content: self.logger.info('处理头条文章') for item in content['top_stories']: for story in content['stories']: if item['id'] == story['id']: story['top'] = 1 break self.logger.debug(item) # 处理今日文章,并抛出具体文章请求 post_num = len(content['stories']) self.logger.info('处理今日文章,共{:>2}篇'.format(post_num)) for item in content['stories']: self.logger.info(item) post_num = 0 if post_num < 0 else post_num pub_time = date + datetime.timedelta(minutes=post_num) post_num -= 1 url = 'http://news-at.zhihu.com/api/4/news/{}'.format(item['id']) request = scrapy.Request(url, callback=self.parse_post) post_dict = { 'spider': ZhihuDailySpider.name, 'date': pub_time.strftime("%Y-%m-%d %H:%M:%S"), 'meta': { 'spider.zhihu_daily.id': str(item.get('id', '')) } } if item.get('top'): post_dict['meta']['spider.zhihu_daily.top'] = \ str(item.get('top', 0)) request.meta['post'] = post_dict self.item_list.append(post_dict) yield request
python
def parse(self, response): ''' 根据对 ``start_urls`` 中提供链接的请求响应包内容,解析生成具体文章链接请求 :param Response response: 由 ``Scrapy`` 调用并传入的请求响应对象 ''' content_raw = response.body.decode() self.logger.debug('响应body原始数据:{}'.format(content_raw)) content = json.loads(content_raw, encoding='UTF-8') self.logger.debug(content) # 文章发布日期 date = datetime.datetime.strptime(content['date'], '%Y%m%d') strftime = date.strftime("%Y-%m-%d") self.logger.info('日期:{}'.format(strftime)) # 处理头条文章列表,将其 `top` 标记到相应 __story__ 中 if 'top_stories' in content: self.logger.info('处理头条文章') for item in content['top_stories']: for story in content['stories']: if item['id'] == story['id']: story['top'] = 1 break self.logger.debug(item) # 处理今日文章,并抛出具体文章请求 post_num = len(content['stories']) self.logger.info('处理今日文章,共{:>2}篇'.format(post_num)) for item in content['stories']: self.logger.info(item) post_num = 0 if post_num < 0 else post_num pub_time = date + datetime.timedelta(minutes=post_num) post_num -= 1 url = 'http://news-at.zhihu.com/api/4/news/{}'.format(item['id']) request = scrapy.Request(url, callback=self.parse_post) post_dict = { 'spider': ZhihuDailySpider.name, 'date': pub_time.strftime("%Y-%m-%d %H:%M:%S"), 'meta': { 'spider.zhihu_daily.id': str(item.get('id', '')) } } if item.get('top'): post_dict['meta']['spider.zhihu_daily.top'] = \ str(item.get('top', 0)) request.meta['post'] = post_dict self.item_list.append(post_dict) yield request
[ "def", "parse", "(", "self", ",", "response", ")", ":", "content_raw", "=", "response", ".", "body", ".", "decode", "(", ")", "self", ".", "logger", ".", "debug", "(", "'响应body原始数据:{}'.format(conten", "t", "_raw))", "", "", "", "", "content", "=", "jso...
根据对 ``start_urls`` 中提供链接的请求响应包内容,解析生成具体文章链接请求 :param Response response: 由 ``Scrapy`` 调用并传入的请求响应对象
[ "根据对", "start_urls", "中提供链接的请求响应包内容,解析生成具体文章链接请求" ]
train
https://github.com/littlemo/moear-spider-zhihudaily/blob/1e4e60b547afe3e2fbb3bbcb7d07a75dca608149/moear_spider_zhihudaily/spiders/zhihu_daily.py#L74-L124
littlemo/moear-spider-zhihudaily
moear_spider_zhihudaily/spiders/zhihu_daily.py
ZhihuDailySpider.parse_post
def parse_post(self, response): ''' 根据 :meth:`.ZhihuDailySpider.parse` 中生成的具体文章地址,获取到文章内容, 并对其进行格式化处理,结果填充到对象属性 ``item_list`` 中 :param Response response: 由 ``Scrapy`` 调用并传入的请求响应对象 ''' content = json.loads(response.body.decode(), encoding='UTF-8') post = response.meta['post'] post['origin_url'] = content.get('share_url', '') if not all([post['origin_url']]): raise ValueError('原文地址为空') post['title'] = html.escape(content.get('title', '')) if not all([post['title']]): raise ValueError('文章标题为空 - {}'.format(post.get('origin_url'))) # 单独处理type字段为1的情况,即该文章为站外转发文章 if content.get('type') == 1: self.logger.warn('遇到站外文章,单独处理 - {}'.format(post['title'])) return post soup = BeautifulSoup(content.get('body', ''), 'lxml') author_obj = soup.select('span.author') self.logger.debug(author_obj) if author_obj: author_list = [] for author in author_obj: author_list.append( author.string.rstrip(',, ').replace(',', ',')) author_list = list(set(author_list)) post['author'] = html.escape(','.join(author_list)) post['content'] = str(soup.div) # 继续填充post数据 image_back = content.get('images', [None])[0] if image_back: post['meta']['moear.cover_image_slug'] = \ content.get('image', image_back) self.logger.debug(post)
python
def parse_post(self, response): ''' 根据 :meth:`.ZhihuDailySpider.parse` 中生成的具体文章地址,获取到文章内容, 并对其进行格式化处理,结果填充到对象属性 ``item_list`` 中 :param Response response: 由 ``Scrapy`` 调用并传入的请求响应对象 ''' content = json.loads(response.body.decode(), encoding='UTF-8') post = response.meta['post'] post['origin_url'] = content.get('share_url', '') if not all([post['origin_url']]): raise ValueError('原文地址为空') post['title'] = html.escape(content.get('title', '')) if not all([post['title']]): raise ValueError('文章标题为空 - {}'.format(post.get('origin_url'))) # 单独处理type字段为1的情况,即该文章为站外转发文章 if content.get('type') == 1: self.logger.warn('遇到站外文章,单独处理 - {}'.format(post['title'])) return post soup = BeautifulSoup(content.get('body', ''), 'lxml') author_obj = soup.select('span.author') self.logger.debug(author_obj) if author_obj: author_list = [] for author in author_obj: author_list.append( author.string.rstrip(',, ').replace(',', ',')) author_list = list(set(author_list)) post['author'] = html.escape(','.join(author_list)) post['content'] = str(soup.div) # 继续填充post数据 image_back = content.get('images', [None])[0] if image_back: post['meta']['moear.cover_image_slug'] = \ content.get('image', image_back) self.logger.debug(post)
[ "def", "parse_post", "(", "self", ",", "response", ")", ":", "content", "=", "json", ".", "loads", "(", "response", ".", "body", ".", "decode", "(", ")", ",", "encoding", "=", "'UTF-8'", ")", "post", "=", "response", ".", "meta", "[", "'post'", "]", ...
根据 :meth:`.ZhihuDailySpider.parse` 中生成的具体文章地址,获取到文章内容, 并对其进行格式化处理,结果填充到对象属性 ``item_list`` 中 :param Response response: 由 ``Scrapy`` 调用并传入的请求响应对象
[ "根据", ":", "meth", ":", ".", "ZhihuDailySpider", ".", "parse", "中生成的具体文章地址,获取到文章内容,", "并对其进行格式化处理,结果填充到对象属性", "item_list", "中" ]
train
https://github.com/littlemo/moear-spider-zhihudaily/blob/1e4e60b547afe3e2fbb3bbcb7d07a75dca608149/moear_spider_zhihudaily/spiders/zhihu_daily.py#L126-L166
littlemo/moear-spider-zhihudaily
moear_spider_zhihudaily/spiders/zhihu_daily.py
ZhihuDailySpider.closed
def closed(self, reason): ''' 异步爬取全部结束后,执行此关闭方法,对 ``item_list`` 中的数据进行 **JSON** 序列化,并输出到指定文件中,传递给 :meth:`.ZhihuDaily.crawl` :param obj reason: 爬虫关闭原因 ''' self.logger.debug('结果列表: {}'.format(self.item_list)) output_strings = json.dumps(self.item_list, ensure_ascii=False) with open(self.output_file, 'w') as fh: fh.write(output_strings)
python
def closed(self, reason): ''' 异步爬取全部结束后,执行此关闭方法,对 ``item_list`` 中的数据进行 **JSON** 序列化,并输出到指定文件中,传递给 :meth:`.ZhihuDaily.crawl` :param obj reason: 爬虫关闭原因 ''' self.logger.debug('结果列表: {}'.format(self.item_list)) output_strings = json.dumps(self.item_list, ensure_ascii=False) with open(self.output_file, 'w') as fh: fh.write(output_strings)
[ "def", "closed", "(", "self", ",", "reason", ")", ":", "self", ".", "logger", ".", "debug", "(", "'结果列表: {}'.format(", "s", "elf.it", "e", "m_li", "s", "t))", "", "", "output_strings", "=", "json", ".", "dumps", "(", "self", ".", "item_list", ",", "e...
异步爬取全部结束后,执行此关闭方法,对 ``item_list`` 中的数据进行 **JSON** 序列化,并输出到指定文件中,传递给 :meth:`.ZhihuDaily.crawl` :param obj reason: 爬虫关闭原因
[ "异步爬取全部结束后,执行此关闭方法,对", "item_list", "中的数据进行", "**", "JSON", "**", "序列化,并输出到指定文件中,传递给", ":", "meth", ":", ".", "ZhihuDaily", ".", "crawl" ]
train
https://github.com/littlemo/moear-spider-zhihudaily/blob/1e4e60b547afe3e2fbb3bbcb7d07a75dca608149/moear_spider_zhihudaily/spiders/zhihu_daily.py#L168-L179
etcher-be/epab
epab/utils/_repo.py
Repo.get_current_branch
def get_current_branch(self) -> str: """ :return: current branch :rtype: str """ current_branch: str = self.repo.active_branch.name LOGGER.debug('current branch: %s', current_branch) return current_branch
python
def get_current_branch(self) -> str: """ :return: current branch :rtype: str """ current_branch: str = self.repo.active_branch.name LOGGER.debug('current branch: %s', current_branch) return current_branch
[ "def", "get_current_branch", "(", "self", ")", "->", "str", ":", "current_branch", ":", "str", "=", "self", ".", "repo", ".", "active_branch", ".", "name", "LOGGER", ".", "debug", "(", "'current branch: %s'", ",", "current_branch", ")", "return", "current_bran...
:return: current branch :rtype: str
[ ":", "return", ":", "current", "branch", ":", "rtype", ":", "str" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L24-L31
etcher-be/epab
epab/utils/_repo.py
Repo.tag
def tag(self, tag: str, overwrite: bool = False) -> None: """ Tags the current commit :param tag: tag :type tag: str :param overwrite: overwrite existing tag :type overwrite: bool """ LOGGER.info('tagging repo: %s', tag) try: self.repo.create_tag(tag) except GitCommandError as exc: if 'already exists' in exc.stderr and overwrite: LOGGER.info('overwriting existing tag') self.remove_tag(tag) self.repo.create_tag(tag) else: LOGGER.exception('error while tagging repo') raise
python
def tag(self, tag: str, overwrite: bool = False) -> None: """ Tags the current commit :param tag: tag :type tag: str :param overwrite: overwrite existing tag :type overwrite: bool """ LOGGER.info('tagging repo: %s', tag) try: self.repo.create_tag(tag) except GitCommandError as exc: if 'already exists' in exc.stderr and overwrite: LOGGER.info('overwriting existing tag') self.remove_tag(tag) self.repo.create_tag(tag) else: LOGGER.exception('error while tagging repo') raise
[ "def", "tag", "(", "self", ",", "tag", ":", "str", ",", "overwrite", ":", "bool", "=", "False", ")", "->", "None", ":", "LOGGER", ".", "info", "(", "'tagging repo: %s'", ",", "tag", ")", "try", ":", "self", ".", "repo", ".", "create_tag", "(", "tag...
Tags the current commit :param tag: tag :type tag: str :param overwrite: overwrite existing tag :type overwrite: bool
[ "Tags", "the", "current", "commit" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L33-L52
etcher-be/epab
epab/utils/_repo.py
Repo.list_tags
def list_tags(self, pattern: str = None) -> typing.List[str]: """ Returns list of tags, optionally matching "pattern" :param pattern: optional pattern to filter results :type pattern: str :return: existing tags :rtype: list of str """ tags: typing.List[str] = [str(tag) for tag in self.repo.tags] if not pattern: LOGGER.debug('tags found in repo: %s', tags) return tags LOGGER.debug('filtering tags with pattern: %s', pattern) filtered_tags: typing.List[str] = [tag for tag in tags if pattern in tag] LOGGER.debug('filtered tags: %s', filtered_tags) return filtered_tags
python
def list_tags(self, pattern: str = None) -> typing.List[str]: """ Returns list of tags, optionally matching "pattern" :param pattern: optional pattern to filter results :type pattern: str :return: existing tags :rtype: list of str """ tags: typing.List[str] = [str(tag) for tag in self.repo.tags] if not pattern: LOGGER.debug('tags found in repo: %s', tags) return tags LOGGER.debug('filtering tags with pattern: %s', pattern) filtered_tags: typing.List[str] = [tag for tag in tags if pattern in tag] LOGGER.debug('filtered tags: %s', filtered_tags) return filtered_tags
[ "def", "list_tags", "(", "self", ",", "pattern", ":", "str", "=", "None", ")", "->", "typing", ".", "List", "[", "str", "]", ":", "tags", ":", "typing", ".", "List", "[", "str", "]", "=", "[", "str", "(", "tag", ")", "for", "tag", "in", "self",...
Returns list of tags, optionally matching "pattern" :param pattern: optional pattern to filter results :type pattern: str :return: existing tags :rtype: list of str
[ "Returns", "list", "of", "tags", "optionally", "matching", "pattern" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L54-L71
etcher-be/epab
epab/utils/_repo.py
Repo.remove_tag
def remove_tag(self, *tag: str): """ Removes tag(s) from the rpo :param tag: tags to remove :type tag: tuple """ LOGGER.info('removing tag(s) from repo: %s', tag) self.repo.delete_tag(*tag)
python
def remove_tag(self, *tag: str): """ Removes tag(s) from the rpo :param tag: tags to remove :type tag: tuple """ LOGGER.info('removing tag(s) from repo: %s', tag) self.repo.delete_tag(*tag)
[ "def", "remove_tag", "(", "self", ",", "*", "tag", ":", "str", ")", ":", "LOGGER", ".", "info", "(", "'removing tag(s) from repo: %s'", ",", "tag", ")", "self", ".", "repo", ".", "delete_tag", "(", "*", "tag", ")" ]
Removes tag(s) from the rpo :param tag: tags to remove :type tag: tuple
[ "Removes", "tag", "(", "s", ")", "from", "the", "rpo" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L73-L82
etcher-be/epab
epab/utils/_repo.py
Repo.is_on_tag
def is_on_tag(self) -> bool: """ :return: True if latest commit is tagged :rtype: bool """ if self.get_current_tag(): LOGGER.debug('latest commit is tagged') return True LOGGER.debug('latest commit is NOT tagged') return False
python
def is_on_tag(self) -> bool: """ :return: True if latest commit is tagged :rtype: bool """ if self.get_current_tag(): LOGGER.debug('latest commit is tagged') return True LOGGER.debug('latest commit is NOT tagged') return False
[ "def", "is_on_tag", "(", "self", ")", "->", "bool", ":", "if", "self", ".", "get_current_tag", "(", ")", ":", "LOGGER", ".", "debug", "(", "'latest commit is tagged'", ")", "return", "True", "LOGGER", ".", "debug", "(", "'latest commit is NOT tagged'", ")", ...
:return: True if latest commit is tagged :rtype: bool
[ ":", "return", ":", "True", "if", "latest", "commit", "is", "tagged", ":", "rtype", ":", "bool" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L108-L118
etcher-be/epab
epab/utils/_repo.py
Repo.get_current_tag
def get_current_tag(self) -> typing.Optional[str]: """ :return: tag name if current commit is on tag, else None :rtype: optional str """ tags = list(self.repo.tags) if not tags: LOGGER.debug('no tag found') return None for tag in tags: LOGGER.debug('tag found: %s; comparing with commit', tag) if tag.commit == self.latest_commit(): tag_name: str = tag.name LOGGER.debug('found tag on commit: %s', tag_name) return tag_name LOGGER.debug('no tag found on latest commit') return None
python
def get_current_tag(self) -> typing.Optional[str]: """ :return: tag name if current commit is on tag, else None :rtype: optional str """ tags = list(self.repo.tags) if not tags: LOGGER.debug('no tag found') return None for tag in tags: LOGGER.debug('tag found: %s; comparing with commit', tag) if tag.commit == self.latest_commit(): tag_name: str = tag.name LOGGER.debug('found tag on commit: %s', tag_name) return tag_name LOGGER.debug('no tag found on latest commit') return None
[ "def", "get_current_tag", "(", "self", ")", "->", "typing", ".", "Optional", "[", "str", "]", ":", "tags", "=", "list", "(", "self", ".", "repo", ".", "tags", ")", "if", "not", "tags", ":", "LOGGER", ".", "debug", "(", "'no tag found'", ")", "return"...
:return: tag name if current commit is on tag, else None :rtype: optional str
[ ":", "return", ":", "tag", "name", "if", "current", "commit", "is", "on", "tag", "else", "None", ":", "rtype", ":", "optional", "str" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L120-L137
etcher-be/epab
epab/utils/_repo.py
Repo.stash
def stash(self, stash_name: str): """ Stashes the current working tree changes :param stash_name: name of the stash :type stash_name: str """ if self.stashed: LOGGER.error('already stashed') sys.exit(-1) else: if not self.index_is_empty(): LOGGER.error('cannot stash; index is not empty') sys.exit(-1) if self.untracked_files(): LOGGER.error('cannot stash; there are untracked files') sys.exit(-1) if self.changed_files(): LOGGER.info('stashing changes') self.repo.git.stash('push', '-u', '-k', '-m', f'"{stash_name}"') self.stashed = True else: LOGGER.info('no changes to stash')
python
def stash(self, stash_name: str): """ Stashes the current working tree changes :param stash_name: name of the stash :type stash_name: str """ if self.stashed: LOGGER.error('already stashed') sys.exit(-1) else: if not self.index_is_empty(): LOGGER.error('cannot stash; index is not empty') sys.exit(-1) if self.untracked_files(): LOGGER.error('cannot stash; there are untracked files') sys.exit(-1) if self.changed_files(): LOGGER.info('stashing changes') self.repo.git.stash('push', '-u', '-k', '-m', f'"{stash_name}"') self.stashed = True else: LOGGER.info('no changes to stash')
[ "def", "stash", "(", "self", ",", "stash_name", ":", "str", ")", ":", "if", "self", ".", "stashed", ":", "LOGGER", ".", "error", "(", "'already stashed'", ")", "sys", ".", "exit", "(", "-", "1", ")", "else", ":", "if", "not", "self", ".", "index_is...
Stashes the current working tree changes :param stash_name: name of the stash :type stash_name: str
[ "Stashes", "the", "current", "working", "tree", "changes" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L139-L161
etcher-be/epab
epab/utils/_repo.py
Repo.unstash
def unstash(self): """ Pops the last stash if EPAB made a stash before """ if not self.stashed: LOGGER.error('no stash') else: LOGGER.info('popping stash') self.repo.git.stash('pop') self.stashed = False
python
def unstash(self): """ Pops the last stash if EPAB made a stash before """ if not self.stashed: LOGGER.error('no stash') else: LOGGER.info('popping stash') self.repo.git.stash('pop') self.stashed = False
[ "def", "unstash", "(", "self", ")", ":", "if", "not", "self", ".", "stashed", ":", "LOGGER", ".", "error", "(", "'no stash'", ")", "else", ":", "LOGGER", ".", "info", "(", "'popping stash'", ")", "self", ".", "repo", ".", "git", ".", "stash", "(", ...
Pops the last stash if EPAB made a stash before
[ "Pops", "the", "last", "stash", "if", "EPAB", "made", "a", "stash", "before" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L163-L172
etcher-be/epab
epab/utils/_repo.py
Repo.ensure
def ensure(): """ Makes sure the current working directory is a Git repository. """ LOGGER.debug('checking repository') if not os.path.exists('.git'): LOGGER.error('This command is meant to be ran in a Git repository.') sys.exit(-1) LOGGER.debug('repository OK')
python
def ensure(): """ Makes sure the current working directory is a Git repository. """ LOGGER.debug('checking repository') if not os.path.exists('.git'): LOGGER.error('This command is meant to be ran in a Git repository.') sys.exit(-1) LOGGER.debug('repository OK')
[ "def", "ensure", "(", ")", ":", "LOGGER", ".", "debug", "(", "'checking repository'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "'.git'", ")", ":", "LOGGER", ".", "error", "(", "'This command is meant to be ran in a Git repository.'", ")", "sys"...
Makes sure the current working directory is a Git repository.
[ "Makes", "sure", "the", "current", "working", "directory", "is", "a", "Git", "repository", "." ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L175-L183
etcher-be/epab
epab/utils/_repo.py
Repo.last_commit_msg
def last_commit_msg(self) -> str: """ :return: last commit message :rtype: str """ last_msg: str = self.latest_commit().message.rstrip() LOGGER.debug('last msg: %s', last_msg) return last_msg
python
def last_commit_msg(self) -> str: """ :return: last commit message :rtype: str """ last_msg: str = self.latest_commit().message.rstrip() LOGGER.debug('last msg: %s', last_msg) return last_msg
[ "def", "last_commit_msg", "(", "self", ")", "->", "str", ":", "last_msg", ":", "str", "=", "self", ".", "latest_commit", "(", ")", ".", "message", ".", "rstrip", "(", ")", "LOGGER", ".", "debug", "(", "'last msg: %s'", ",", "last_msg", ")", "return", "...
:return: last commit message :rtype: str
[ ":", "return", ":", "last", "commit", "message", ":", "rtype", ":", "str" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L185-L192
etcher-be/epab
epab/utils/_repo.py
Repo.untracked_files
def untracked_files(self) -> typing.List[str]: """ :return: of untracked files :rtype: list """ untracked_files = list(self.repo.untracked_files) LOGGER.debug('untracked files: %s', untracked_files) return untracked_files
python
def untracked_files(self) -> typing.List[str]: """ :return: of untracked files :rtype: list """ untracked_files = list(self.repo.untracked_files) LOGGER.debug('untracked files: %s', untracked_files) return untracked_files
[ "def", "untracked_files", "(", "self", ")", "->", "typing", ".", "List", "[", "str", "]", ":", "untracked_files", "=", "list", "(", "self", ".", "repo", ".", "untracked_files", ")", "LOGGER", ".", "debug", "(", "'untracked files: %s'", ",", "untracked_files"...
:return: of untracked files :rtype: list
[ ":", "return", ":", "of", "untracked", "files", ":", "rtype", ":", "list" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L194-L201
etcher-be/epab
epab/utils/_repo.py
Repo.status
def status(self) -> str: """ :return: Git status :rtype: str """ status: str = self.repo.git.status() LOGGER.debug('git status: %s', status) return status
python
def status(self) -> str: """ :return: Git status :rtype: str """ status: str = self.repo.git.status() LOGGER.debug('git status: %s', status) return status
[ "def", "status", "(", "self", ")", "->", "str", ":", "status", ":", "str", "=", "self", ".", "repo", ".", "git", ".", "status", "(", ")", "LOGGER", ".", "debug", "(", "'git status: %s'", ",", "status", ")", "return", "status" ]
:return: Git status :rtype: str
[ ":", "return", ":", "Git", "status", ":", "rtype", ":", "str" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L203-L210
etcher-be/epab
epab/utils/_repo.py
Repo.list_staged_files
def list_staged_files(self) -> typing.List[str]: """ :return: staged files :rtype: list of str """ staged_files: typing.List[str] = [x.a_path for x in self.repo.index.diff('HEAD')] LOGGER.debug('staged files: %s', staged_files) return staged_files
python
def list_staged_files(self) -> typing.List[str]: """ :return: staged files :rtype: list of str """ staged_files: typing.List[str] = [x.a_path for x in self.repo.index.diff('HEAD')] LOGGER.debug('staged files: %s', staged_files) return staged_files
[ "def", "list_staged_files", "(", "self", ")", "->", "typing", ".", "List", "[", "str", "]", ":", "staged_files", ":", "typing", ".", "List", "[", "str", "]", "=", "[", "x", ".", "a_path", "for", "x", "in", "self", ".", "repo", ".", "index", ".", ...
:return: staged files :rtype: list of str
[ ":", "return", ":", "staged", "files", ":", "rtype", ":", "list", "of", "str" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L212-L219
etcher-be/epab
epab/utils/_repo.py
Repo.index_is_empty
def index_is_empty(self) -> bool: """ :return: True if index is empty (no staged changes) :rtype: bool """ index_empty: bool = len(self.repo.index.diff(self.repo.head.commit)) == 0 LOGGER.debug('index is empty: %s', index_empty) return index_empty
python
def index_is_empty(self) -> bool: """ :return: True if index is empty (no staged changes) :rtype: bool """ index_empty: bool = len(self.repo.index.diff(self.repo.head.commit)) == 0 LOGGER.debug('index is empty: %s', index_empty) return index_empty
[ "def", "index_is_empty", "(", "self", ")", "->", "bool", ":", "index_empty", ":", "bool", "=", "len", "(", "self", ".", "repo", ".", "index", ".", "diff", "(", "self", ".", "repo", ".", "head", ".", "commit", ")", ")", "==", "0", "LOGGER", ".", "...
:return: True if index is empty (no staged changes) :rtype: bool
[ ":", "return", ":", "True", "if", "index", "is", "empty", "(", "no", "staged", "changes", ")", ":", "rtype", ":", "bool" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L221-L228
etcher-be/epab
epab/utils/_repo.py
Repo.changed_files
def changed_files(self) -> typing.List[str]: """ :return: changed files :rtype: list of str """ changed_files: typing.List[str] = [x.a_path for x in self.repo.index.diff(None)] LOGGER.debug('changed files: %s', changed_files) return changed_files
python
def changed_files(self) -> typing.List[str]: """ :return: changed files :rtype: list of str """ changed_files: typing.List[str] = [x.a_path for x in self.repo.index.diff(None)] LOGGER.debug('changed files: %s', changed_files) return changed_files
[ "def", "changed_files", "(", "self", ")", "->", "typing", ".", "List", "[", "str", "]", ":", "changed_files", ":", "typing", ".", "List", "[", "str", "]", "=", "[", "x", ".", "a_path", "for", "x", "in", "self", ".", "repo", ".", "index", ".", "di...
:return: changed files :rtype: list of str
[ ":", "return", ":", "changed", "files", ":", "rtype", ":", "list", "of", "str" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L230-L237
etcher-be/epab
epab/utils/_repo.py
Repo.stage_all
def stage_all(self): """ Stages all changed and untracked files """ LOGGER.info('Staging all files') self.repo.git.add(A=True)
python
def stage_all(self): """ Stages all changed and untracked files """ LOGGER.info('Staging all files') self.repo.git.add(A=True)
[ "def", "stage_all", "(", "self", ")", ":", "LOGGER", ".", "info", "(", "'Staging all files'", ")", "self", ".", "repo", ".", "git", ".", "add", "(", "A", "=", "True", ")" ]
Stages all changed and untracked files
[ "Stages", "all", "changed", "and", "untracked", "files" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L246-L251
etcher-be/epab
epab/utils/_repo.py
Repo.stage_modified
def stage_modified(self): """ Stages modified files only (no untracked) """ LOGGER.info('Staging modified files') self.repo.git.add(u=True)
python
def stage_modified(self): """ Stages modified files only (no untracked) """ LOGGER.info('Staging modified files') self.repo.git.add(u=True)
[ "def", "stage_modified", "(", "self", ")", ":", "LOGGER", ".", "info", "(", "'Staging modified files'", ")", "self", ".", "repo", ".", "git", ".", "add", "(", "u", "=", "True", ")" ]
Stages modified files only (no untracked)
[ "Stages", "modified", "files", "only", "(", "no", "untracked", ")" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L253-L258
etcher-be/epab
epab/utils/_repo.py
Repo.stage_subset
def stage_subset(self, *files_to_add: str): """ Stages a subset of files :param files_to_add: files to stage :type files_to_add: str """ LOGGER.info('staging files: %s', files_to_add) self.repo.git.add(*files_to_add, A=True)
python
def stage_subset(self, *files_to_add: str): """ Stages a subset of files :param files_to_add: files to stage :type files_to_add: str """ LOGGER.info('staging files: %s', files_to_add) self.repo.git.add(*files_to_add, A=True)
[ "def", "stage_subset", "(", "self", ",", "*", "files_to_add", ":", "str", ")", ":", "LOGGER", ".", "info", "(", "'staging files: %s'", ",", "files_to_add", ")", "self", ".", "repo", ".", "git", ".", "add", "(", "*", "files_to_add", ",", "A", "=", "True...
Stages a subset of files :param files_to_add: files to stage :type files_to_add: str
[ "Stages", "a", "subset", "of", "files" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L260-L268
etcher-be/epab
epab/utils/_repo.py
Repo.add_skip_ci_to_commit_msg
def add_skip_ci_to_commit_msg(message: str) -> str: """ Adds a "[skip ci]" tag at the end of a (possibly multi-line) commit message :param message: commit message :type message: str :return: edited commit message :rtype: str """ first_line_index = message.find('\n') if first_line_index == -1: edited_message = message + ' [skip ci]' else: edited_message = message[:first_line_index] + ' [skip ci]' + message[first_line_index:] LOGGER.debug('edited commit message: %s', edited_message) return edited_message
python
def add_skip_ci_to_commit_msg(message: str) -> str: """ Adds a "[skip ci]" tag at the end of a (possibly multi-line) commit message :param message: commit message :type message: str :return: edited commit message :rtype: str """ first_line_index = message.find('\n') if first_line_index == -1: edited_message = message + ' [skip ci]' else: edited_message = message[:first_line_index] + ' [skip ci]' + message[first_line_index:] LOGGER.debug('edited commit message: %s', edited_message) return edited_message
[ "def", "add_skip_ci_to_commit_msg", "(", "message", ":", "str", ")", "->", "str", ":", "first_line_index", "=", "message", ".", "find", "(", "'\\n'", ")", "if", "first_line_index", "==", "-", "1", ":", "edited_message", "=", "message", "+", "' [skip ci]'", "...
Adds a "[skip ci]" tag at the end of a (possibly multi-line) commit message :param message: commit message :type message: str :return: edited commit message :rtype: str
[ "Adds", "a", "[", "skip", "ci", "]", "tag", "at", "the", "end", "of", "a", "(", "possibly", "multi", "-", "line", ")", "commit", "message" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L271-L286
etcher-be/epab
epab/utils/_repo.py
Repo.commit
def commit( self, message: str, files_to_add: typing.Optional[typing.Union[typing.List[str], str]] = None, allow_empty: bool = False, ): """ Commits changes to the repo :param message: first line of the message :type message: str :param files_to_add: files to commit :type files_to_add: optional list of str :param allow_empty: allow dummy commit :type allow_empty: bool """ message = str(message) LOGGER.debug('message: %s', message) files_to_add = self._sanitize_files_to_add(files_to_add) LOGGER.debug('files to add: %s', files_to_add) if not message: LOGGER.error('empty commit message') sys.exit(-1) if os.getenv('APPVEYOR'): LOGGER.info('committing on AV, adding skip_ci tag') message = self.add_skip_ci_to_commit_msg(message) if files_to_add is None: self.stage_all() else: self.reset_index() self.stage_subset(*files_to_add) if self.index_is_empty() and not allow_empty: LOGGER.error('empty commit') sys.exit(-1) self.repo.index.commit(message=message)
python
def commit( self, message: str, files_to_add: typing.Optional[typing.Union[typing.List[str], str]] = None, allow_empty: bool = False, ): """ Commits changes to the repo :param message: first line of the message :type message: str :param files_to_add: files to commit :type files_to_add: optional list of str :param allow_empty: allow dummy commit :type allow_empty: bool """ message = str(message) LOGGER.debug('message: %s', message) files_to_add = self._sanitize_files_to_add(files_to_add) LOGGER.debug('files to add: %s', files_to_add) if not message: LOGGER.error('empty commit message') sys.exit(-1) if os.getenv('APPVEYOR'): LOGGER.info('committing on AV, adding skip_ci tag') message = self.add_skip_ci_to_commit_msg(message) if files_to_add is None: self.stage_all() else: self.reset_index() self.stage_subset(*files_to_add) if self.index_is_empty() and not allow_empty: LOGGER.error('empty commit') sys.exit(-1) self.repo.index.commit(message=message)
[ "def", "commit", "(", "self", ",", "message", ":", "str", ",", "files_to_add", ":", "typing", ".", "Optional", "[", "typing", ".", "Union", "[", "typing", ".", "List", "[", "str", "]", ",", "str", "]", "]", "=", "None", ",", "allow_empty", ":", "bo...
Commits changes to the repo :param message: first line of the message :type message: str :param files_to_add: files to commit :type files_to_add: optional list of str :param allow_empty: allow dummy commit :type allow_empty: bool
[ "Commits", "changes", "to", "the", "repo" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L301-L341
etcher-be/epab
epab/utils/_repo.py
Repo.amend_commit
def amend_commit( self, append_to_msg: typing.Optional[str] = None, new_message: typing.Optional[str] = None, files_to_add: typing.Optional[typing.Union[typing.List[str], str]] = None, ): """ Amends last commit with either an entirely new commit message, or an edited version of the previous one Note: it is an error to provide both "append_to_msg" and "new_message" :param append_to_msg: message to append to previous commit message :type append_to_msg: str :param new_message: new commit message :type new_message: str :param files_to_add: optional list of files to add to this commit :type files_to_add: str or list of str """ if new_message and append_to_msg: LOGGER.error('Cannot use "new_message" and "append_to_msg" together') sys.exit(-1) files_to_add = self._sanitize_files_to_add(files_to_add) message = self._sanitize_amend_commit_message(append_to_msg, new_message) if os.getenv('APPVEYOR'): message = f'{message} [skip ci]' LOGGER.info('amending commit with new message: %s', message) latest_tag = self.get_current_tag() if latest_tag: LOGGER.info('removing tag: %s', latest_tag) self.remove_tag(latest_tag) LOGGER.info('going back one commit') branch = self.repo.head.reference try: branch.commit = self.repo.head.commit.parents[0] except IndexError: LOGGER.error('cannot amend the first commit') sys.exit(-1) if files_to_add: self.stage_subset(*files_to_add) else: self.stage_all() self.repo.index.commit(message, skip_hooks=True) if latest_tag: LOGGER.info('resetting tag: %s', latest_tag) self.tag(latest_tag)
python
def amend_commit( self, append_to_msg: typing.Optional[str] = None, new_message: typing.Optional[str] = None, files_to_add: typing.Optional[typing.Union[typing.List[str], str]] = None, ): """ Amends last commit with either an entirely new commit message, or an edited version of the previous one Note: it is an error to provide both "append_to_msg" and "new_message" :param append_to_msg: message to append to previous commit message :type append_to_msg: str :param new_message: new commit message :type new_message: str :param files_to_add: optional list of files to add to this commit :type files_to_add: str or list of str """ if new_message and append_to_msg: LOGGER.error('Cannot use "new_message" and "append_to_msg" together') sys.exit(-1) files_to_add = self._sanitize_files_to_add(files_to_add) message = self._sanitize_amend_commit_message(append_to_msg, new_message) if os.getenv('APPVEYOR'): message = f'{message} [skip ci]' LOGGER.info('amending commit with new message: %s', message) latest_tag = self.get_current_tag() if latest_tag: LOGGER.info('removing tag: %s', latest_tag) self.remove_tag(latest_tag) LOGGER.info('going back one commit') branch = self.repo.head.reference try: branch.commit = self.repo.head.commit.parents[0] except IndexError: LOGGER.error('cannot amend the first commit') sys.exit(-1) if files_to_add: self.stage_subset(*files_to_add) else: self.stage_all() self.repo.index.commit(message, skip_hooks=True) if latest_tag: LOGGER.info('resetting tag: %s', latest_tag) self.tag(latest_tag)
[ "def", "amend_commit", "(", "self", ",", "append_to_msg", ":", "typing", ".", "Optional", "[", "str", "]", "=", "None", ",", "new_message", ":", "typing", ".", "Optional", "[", "str", "]", "=", "None", ",", "files_to_add", ":", "typing", ".", "Optional",...
Amends last commit with either an entirely new commit message, or an edited version of the previous one Note: it is an error to provide both "append_to_msg" and "new_message" :param append_to_msg: message to append to previous commit message :type append_to_msg: str :param new_message: new commit message :type new_message: str :param files_to_add: optional list of files to add to this commit :type files_to_add: str or list of str
[ "Amends", "last", "commit", "with", "either", "an", "entirely", "new", "commit", "message", "or", "an", "edited", "version", "of", "the", "previous", "one" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L366-L417
etcher-be/epab
epab/utils/_repo.py
Repo.merge
def merge(self, ref_name: str): """ Merges two refs Args: ref_name: ref to merge in the current one """ if self.is_dirty(): LOGGER.error('repository is dirty; cannot merge: %s', ref_name) sys.exit(-1) LOGGER.info('merging ref: "%s" into branch: %s', ref_name, self.get_current_branch()) self.repo.git.merge(ref_name)
python
def merge(self, ref_name: str): """ Merges two refs Args: ref_name: ref to merge in the current one """ if self.is_dirty(): LOGGER.error('repository is dirty; cannot merge: %s', ref_name) sys.exit(-1) LOGGER.info('merging ref: "%s" into branch: %s', ref_name, self.get_current_branch()) self.repo.git.merge(ref_name)
[ "def", "merge", "(", "self", ",", "ref_name", ":", "str", ")", ":", "if", "self", ".", "is_dirty", "(", ")", ":", "LOGGER", ".", "error", "(", "'repository is dirty; cannot merge: %s'", ",", "ref_name", ")", "sys", ".", "exit", "(", "-", "1", ")", "LOG...
Merges two refs Args: ref_name: ref to merge in the current one
[ "Merges", "two", "refs" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L419-L430
etcher-be/epab
epab/utils/_repo.py
Repo.push
def push(self, set_upstream: bool = True): """ Pushes all refs (branches and tags) to origin """ LOGGER.info('pushing repo to origin') try: self.repo.git.push() except GitCommandError as error: if 'has no upstream branch' in error.stderr and set_upstream: self.repo.git.push(f'--set-upstream origin {self.get_current_branch()}') else: raise self.push_tags()
python
def push(self, set_upstream: bool = True): """ Pushes all refs (branches and tags) to origin """ LOGGER.info('pushing repo to origin') try: self.repo.git.push() except GitCommandError as error: if 'has no upstream branch' in error.stderr and set_upstream: self.repo.git.push(f'--set-upstream origin {self.get_current_branch()}') else: raise self.push_tags()
[ "def", "push", "(", "self", ",", "set_upstream", ":", "bool", "=", "True", ")", ":", "LOGGER", ".", "info", "(", "'pushing repo to origin'", ")", "try", ":", "self", ".", "repo", ".", "git", ".", "push", "(", ")", "except", "GitCommandError", "as", "er...
Pushes all refs (branches and tags) to origin
[ "Pushes", "all", "refs", "(", "branches", "and", "tags", ")", "to", "origin" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L432-L445
etcher-be/epab
epab/utils/_repo.py
Repo.list_branches
def list_branches(self) -> typing.List[str]: """ :return: branches names :rtype: list of str """ branches: typing.List[str] = [head.name for head in self.repo.heads] LOGGER.debug('branches: %s', branches) return branches
python
def list_branches(self) -> typing.List[str]: """ :return: branches names :rtype: list of str """ branches: typing.List[str] = [head.name for head in self.repo.heads] LOGGER.debug('branches: %s', branches) return branches
[ "def", "list_branches", "(", "self", ")", "->", "typing", ".", "List", "[", "str", "]", ":", "branches", ":", "typing", ".", "List", "[", "str", "]", "=", "[", "head", ".", "name", "for", "head", "in", "self", ".", "repo", ".", "heads", "]", "LOG...
:return: branches names :rtype: list of str
[ ":", "return", ":", "branches", "names", ":", "rtype", ":", "list", "of", "str" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L455-L462
etcher-be/epab
epab/utils/_repo.py
Repo.get_sha
def get_sha(self) -> str: """ :return: SHA of the latest commit :rtype: str """ current_sha: str = self.repo.head.commit.hexsha LOGGER.debug('current commit SHA: %s', current_sha) return current_sha
python
def get_sha(self) -> str: """ :return: SHA of the latest commit :rtype: str """ current_sha: str = self.repo.head.commit.hexsha LOGGER.debug('current commit SHA: %s', current_sha) return current_sha
[ "def", "get_sha", "(", "self", ")", "->", "str", ":", "current_sha", ":", "str", "=", "self", ".", "repo", ".", "head", ".", "commit", ".", "hexsha", "LOGGER", ".", "debug", "(", "'current commit SHA: %s'", ",", "current_sha", ")", "return", "current_sha" ...
:return: SHA of the latest commit :rtype: str
[ ":", "return", ":", "SHA", "of", "the", "latest", "commit", ":", "rtype", ":", "str" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L464-L471
etcher-be/epab
epab/utils/_repo.py
Repo.get_short_sha
def get_short_sha(self) -> str: """ :return: short SHA of the latest commit :rtype: str """ short_sha: str = self.get_sha()[:7] LOGGER.debug('short SHA: %s', short_sha) return short_sha
python
def get_short_sha(self) -> str: """ :return: short SHA of the latest commit :rtype: str """ short_sha: str = self.get_sha()[:7] LOGGER.debug('short SHA: %s', short_sha) return short_sha
[ "def", "get_short_sha", "(", "self", ")", "->", "str", ":", "short_sha", ":", "str", "=", "self", ".", "get_sha", "(", ")", "[", ":", "7", "]", "LOGGER", ".", "debug", "(", "'short SHA: %s'", ",", "short_sha", ")", "return", "short_sha" ]
:return: short SHA of the latest commit :rtype: str
[ ":", "return", ":", "short", "SHA", "of", "the", "latest", "commit", ":", "rtype", ":", "str" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L473-L480
etcher-be/epab
epab/utils/_repo.py
Repo.checkout
def checkout(self, reference: str): """ Checks out a reference. If the index is dirty, or if the repository contains untracked files, the function will fail. :param reference: reference to check out :type reference: str """ LOGGER.info('checking out: %s', reference) if not self.index_is_empty(): LOGGER.error('index contains change; cannot checkout. Status:\n %s', self.status()) sys.exit(-1) if self.is_dirty(untracked=True): LOGGER.error('repository is dirty; cannot checkout "%s"', reference) LOGGER.error('repository is dirty; cannot checkout. Status:\n %s', self.status()) sys.exit(-1) LOGGER.debug('going through all present references') for head in self.repo.heads: if head.name == reference: LOGGER.debug('resetting repo index and working tree to: %s', reference) self.repo.head.reference = head self.repo.head.reset(index=True, working_tree=True) break else: LOGGER.error('reference not found: %s', reference) sys.exit(-1)
python
def checkout(self, reference: str): """ Checks out a reference. If the index is dirty, or if the repository contains untracked files, the function will fail. :param reference: reference to check out :type reference: str """ LOGGER.info('checking out: %s', reference) if not self.index_is_empty(): LOGGER.error('index contains change; cannot checkout. Status:\n %s', self.status()) sys.exit(-1) if self.is_dirty(untracked=True): LOGGER.error('repository is dirty; cannot checkout "%s"', reference) LOGGER.error('repository is dirty; cannot checkout. Status:\n %s', self.status()) sys.exit(-1) LOGGER.debug('going through all present references') for head in self.repo.heads: if head.name == reference: LOGGER.debug('resetting repo index and working tree to: %s', reference) self.repo.head.reference = head self.repo.head.reset(index=True, working_tree=True) break else: LOGGER.error('reference not found: %s', reference) sys.exit(-1)
[ "def", "checkout", "(", "self", ",", "reference", ":", "str", ")", ":", "LOGGER", ".", "info", "(", "'checking out: %s'", ",", "reference", ")", "if", "not", "self", ".", "index_is_empty", "(", ")", ":", "LOGGER", ".", "error", "(", "'index contains change...
Checks out a reference. If the index is dirty, or if the repository contains untracked files, the function will fail. :param reference: reference to check out :type reference: str
[ "Checks", "out", "a", "reference", "." ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L489-L516
etcher-be/epab
epab/utils/_repo.py
Repo.create_branch
def create_branch(self, branch_name: str): """ Creates a new branch Args: branch_name: name of the branch """ LOGGER.info('creating branch: %s', branch_name) self._validate_branch_name(branch_name) if branch_name in self.list_branches(): LOGGER.error('branch already exists') sys.exit(-1) new_branch = self.repo.create_head(branch_name) new_branch.commit = self.repo.head.commit
python
def create_branch(self, branch_name: str): """ Creates a new branch Args: branch_name: name of the branch """ LOGGER.info('creating branch: %s', branch_name) self._validate_branch_name(branch_name) if branch_name in self.list_branches(): LOGGER.error('branch already exists') sys.exit(-1) new_branch = self.repo.create_head(branch_name) new_branch.commit = self.repo.head.commit
[ "def", "create_branch", "(", "self", ",", "branch_name", ":", "str", ")", ":", "LOGGER", ".", "info", "(", "'creating branch: %s'", ",", "branch_name", ")", "self", ".", "_validate_branch_name", "(", "branch_name", ")", "if", "branch_name", "in", "self", ".", ...
Creates a new branch Args: branch_name: name of the branch
[ "Creates", "a", "new", "branch" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L518-L532
etcher-be/epab
epab/utils/_repo.py
Repo.create_branch_and_checkout
def create_branch_and_checkout(self, branch_name: str): """ Creates a new branch if it doesn't exist Args: branch_name: branch name """ self.create_branch(branch_name) self.checkout(branch_name)
python
def create_branch_and_checkout(self, branch_name: str): """ Creates a new branch if it doesn't exist Args: branch_name: branch name """ self.create_branch(branch_name) self.checkout(branch_name)
[ "def", "create_branch_and_checkout", "(", "self", ",", "branch_name", ":", "str", ")", ":", "self", ".", "create_branch", "(", "branch_name", ")", "self", ".", "checkout", "(", "branch_name", ")" ]
Creates a new branch if it doesn't exist Args: branch_name: branch name
[ "Creates", "a", "new", "branch", "if", "it", "doesn", "t", "exist" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L534-L542
etcher-be/epab
epab/utils/_repo.py
Repo.is_dirty
def is_dirty(self, untracked=False) -> bool: """ Checks if the current repository contains uncommitted or untracked changes Returns: true if the repository is clean """ result = False if not self.index_is_empty(): LOGGER.error('index is not empty') result = True changed_files = self.changed_files() if bool(changed_files): LOGGER.error(f'Repo has %s modified files: %s', len(changed_files), changed_files) result = True if untracked: result = result or bool(self.untracked_files()) return result
python
def is_dirty(self, untracked=False) -> bool: """ Checks if the current repository contains uncommitted or untracked changes Returns: true if the repository is clean """ result = False if not self.index_is_empty(): LOGGER.error('index is not empty') result = True changed_files = self.changed_files() if bool(changed_files): LOGGER.error(f'Repo has %s modified files: %s', len(changed_files), changed_files) result = True if untracked: result = result or bool(self.untracked_files()) return result
[ "def", "is_dirty", "(", "self", ",", "untracked", "=", "False", ")", "->", "bool", ":", "result", "=", "False", "if", "not", "self", ".", "index_is_empty", "(", ")", ":", "LOGGER", ".", "error", "(", "'index is not empty'", ")", "result", "=", "True", ...
Checks if the current repository contains uncommitted or untracked changes Returns: true if the repository is clean
[ "Checks", "if", "the", "current", "repository", "contains", "uncommitted", "or", "untracked", "changes" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L544-L561
MacHu-GWU/pymongo_mate-project
pymongo_mate/query_builder.py
Text.startswith
def startswith(text, ignore_case=True): """ Test if a string-field start with ``text``. Example:: filters = {"path": Text.startswith(r"C:\\")} """ if ignore_case: compiled = re.compile( "^%s" % text.replace("\\", "\\\\"), re.IGNORECASE) else: # pragma: no cover compiled = re.compile("^%s" % text.replace("\\", "\\\\")) return {"$regex": compiled}
python
def startswith(text, ignore_case=True): """ Test if a string-field start with ``text``. Example:: filters = {"path": Text.startswith(r"C:\\")} """ if ignore_case: compiled = re.compile( "^%s" % text.replace("\\", "\\\\"), re.IGNORECASE) else: # pragma: no cover compiled = re.compile("^%s" % text.replace("\\", "\\\\")) return {"$regex": compiled}
[ "def", "startswith", "(", "text", ",", "ignore_case", "=", "True", ")", ":", "if", "ignore_case", ":", "compiled", "=", "re", ".", "compile", "(", "\"^%s\"", "%", "text", ".", "replace", "(", "\"\\\\\"", ",", "\"\\\\\\\\\"", ")", ",", "re", ".", "IGNOR...
Test if a string-field start with ``text``. Example:: filters = {"path": Text.startswith(r"C:\\")}
[ "Test", "if", "a", "string", "-", "field", "start", "with", "text", "." ]
train
https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/query_builder.py#L123-L137
MacHu-GWU/pymongo_mate-project
pymongo_mate/query_builder.py
Text.fulltext
def fulltext(search, lang=Lang.English, ignore_case=True): """Full text search. Example:: filters = Text.fulltext("python pymongo_mate") .. note:: This field doesn't need to specify field. """ return { "$text": { "$search": search, "$language": lang, "$caseSensitive": not ignore_case, "$diacriticSensitive": False, } }
python
def fulltext(search, lang=Lang.English, ignore_case=True): """Full text search. Example:: filters = Text.fulltext("python pymongo_mate") .. note:: This field doesn't need to specify field. """ return { "$text": { "$search": search, "$language": lang, "$caseSensitive": not ignore_case, "$diacriticSensitive": False, } }
[ "def", "fulltext", "(", "search", ",", "lang", "=", "Lang", ".", "English", ",", "ignore_case", "=", "True", ")", ":", "return", "{", "\"$text\"", ":", "{", "\"$search\"", ":", "search", ",", "\"$language\"", ":", "lang", ",", "\"$caseSensitive\"", ":", ...
Full text search. Example:: filters = Text.fulltext("python pymongo_mate") .. note:: This field doesn't need to specify field.
[ "Full", "text", "search", "." ]
train
https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/query_builder.py#L174-L192
MacHu-GWU/pymongo_mate-project
pymongo_mate/query_builder.py
Geo2DSphere.near
def near(lat, lng, max_dist=None, unit_miles=False): """Find document near a point. For example:: find all document with in 25 miles radius from 32.0, -73.0. """ filters = { "$nearSphere": { "$geometry": { "type": "Point", "coordinates": [lng, lat], } } } if max_dist: if unit_miles: # pragma: no cover max_dist = max_dist / 1609.344 filters["$nearSphere"]["$maxDistance"] = max_dist return filters
python
def near(lat, lng, max_dist=None, unit_miles=False): """Find document near a point. For example:: find all document with in 25 miles radius from 32.0, -73.0. """ filters = { "$nearSphere": { "$geometry": { "type": "Point", "coordinates": [lng, lat], } } } if max_dist: if unit_miles: # pragma: no cover max_dist = max_dist / 1609.344 filters["$nearSphere"]["$maxDistance"] = max_dist return filters
[ "def", "near", "(", "lat", ",", "lng", ",", "max_dist", "=", "None", ",", "unit_miles", "=", "False", ")", ":", "filters", "=", "{", "\"$nearSphere\"", ":", "{", "\"$geometry\"", ":", "{", "\"type\"", ":", "\"Point\"", ",", "\"coordinates\"", ":", "[", ...
Find document near a point. For example:: find all document with in 25 miles radius from 32.0, -73.0.
[ "Find", "document", "near", "a", "point", "." ]
train
https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/query_builder.py#L302-L319
interstar/FSQuery
fsquery/fsquery.py
FSNode.children
def children(self) : "If the FSNode is a directory, returns a list of the children" if not self.isdir() : raise Exception("FSQuery tried to return the children of a node which is not a directory : %s" % self.abs) return [FSNode(self.abs + "/" + x,self.root,self.depth+1) for x in os.listdir(self.abs)]
python
def children(self) : "If the FSNode is a directory, returns a list of the children" if not self.isdir() : raise Exception("FSQuery tried to return the children of a node which is not a directory : %s" % self.abs) return [FSNode(self.abs + "/" + x,self.root,self.depth+1) for x in os.listdir(self.abs)]
[ "def", "children", "(", "self", ")", ":", "if", "not", "self", ".", "isdir", "(", ")", ":", "raise", "Exception", "(", "\"FSQuery tried to return the children of a node which is not a directory : %s\"", "%", "self", ".", "abs", ")", "return", "[", "FSNode", "(", ...
If the FSNode is a directory, returns a list of the children
[ "If", "the", "FSNode", "is", "a", "directory", "returns", "a", "list", "of", "the", "children" ]
train
https://github.com/interstar/FSQuery/blob/5f57dffeefde4f601af98db9f8ba4177c620dbbd/fsquery/fsquery.py#L56-L59
interstar/FSQuery
fsquery/fsquery.py
FSNode.add_file
def add_file(self,fName,content) : """If this FSNode is a directory, write a file called fName containing content inside it""" if not self.isdir() : raise Exception("FSQuery tried to add a file in a node which is not a directory : %s" % self.abs) self.write_file("%s/%s"%(self.abs,fName),content)
python
def add_file(self,fName,content) : """If this FSNode is a directory, write a file called fName containing content inside it""" if not self.isdir() : raise Exception("FSQuery tried to add a file in a node which is not a directory : %s" % self.abs) self.write_file("%s/%s"%(self.abs,fName),content)
[ "def", "add_file", "(", "self", ",", "fName", ",", "content", ")", ":", "if", "not", "self", ".", "isdir", "(", ")", ":", "raise", "Exception", "(", "\"FSQuery tried to add a file in a node which is not a directory : %s\"", "%", "self", ".", "abs", ")", "self", ...
If this FSNode is a directory, write a file called fName containing content inside it
[ "If", "this", "FSNode", "is", "a", "directory", "write", "a", "file", "called", "fName", "containing", "content", "inside", "it" ]
train
https://github.com/interstar/FSQuery/blob/5f57dffeefde4f601af98db9f8ba4177c620dbbd/fsquery/fsquery.py#L69-L72
interstar/FSQuery
fsquery/fsquery.py
FSNode.open_file
def open_file(self) : """If this FSNode is a file, open it for reading and return the file handle""" if self.isdir() : raise Exception("FSQuery tried to open a directory as a file : %s" % self.abs) return open(self.abs)
python
def open_file(self) : """If this FSNode is a file, open it for reading and return the file handle""" if self.isdir() : raise Exception("FSQuery tried to open a directory as a file : %s" % self.abs) return open(self.abs)
[ "def", "open_file", "(", "self", ")", ":", "if", "self", ".", "isdir", "(", ")", ":", "raise", "Exception", "(", "\"FSQuery tried to open a directory as a file : %s\"", "%", "self", ".", "abs", ")", "return", "open", "(", "self", ".", "abs", ")" ]
If this FSNode is a file, open it for reading and return the file handle
[ "If", "this", "FSNode", "is", "a", "file", "open", "it", "for", "reading", "and", "return", "the", "file", "handle" ]
train
https://github.com/interstar/FSQuery/blob/5f57dffeefde4f601af98db9f8ba4177c620dbbd/fsquery/fsquery.py#L75-L78
interstar/FSQuery
fsquery/fsquery.py
FSNode.mk_dir
def mk_dir(self) : """If this FSNode doesn't currently exist, then make a directory with this name.""" if not os.path.exists(self.abs) : os.makedirs(self.abs)
python
def mk_dir(self) : """If this FSNode doesn't currently exist, then make a directory with this name.""" if not os.path.exists(self.abs) : os.makedirs(self.abs)
[ "def", "mk_dir", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "abs", ")", ":", "os", ".", "makedirs", "(", "self", ".", "abs", ")" ]
If this FSNode doesn't currently exist, then make a directory with this name.
[ "If", "this", "FSNode", "doesn", "t", "currently", "exist", "then", "make", "a", "directory", "with", "this", "name", "." ]
train
https://github.com/interstar/FSQuery/blob/5f57dffeefde4f601af98db9f8ba4177c620dbbd/fsquery/fsquery.py#L80-L83
interstar/FSQuery
fsquery/fsquery.py
FSQuery.walk
def walk(self,depth=0,fsNode=None) : """Note, this is a filtered walk""" if not fsNode : fsNode = FSNode(self.init_path,self.init_path,0) if fsNode.isdir() : if self.check_dir(fsNode) : if self.check_return(fsNode) : yield fsNode for n in fsNode.children() : if n.islink() : # currently we don't follow links continue for n2 in self.walk(depth+1,n) : if self.check_return(n2) : yield n2 else : if self.check_file(fsNode) : if self.check_return(fsNode) : yield fsNode raise StopIteration
python
def walk(self,depth=0,fsNode=None) : """Note, this is a filtered walk""" if not fsNode : fsNode = FSNode(self.init_path,self.init_path,0) if fsNode.isdir() : if self.check_dir(fsNode) : if self.check_return(fsNode) : yield fsNode for n in fsNode.children() : if n.islink() : # currently we don't follow links continue for n2 in self.walk(depth+1,n) : if self.check_return(n2) : yield n2 else : if self.check_file(fsNode) : if self.check_return(fsNode) : yield fsNode raise StopIteration
[ "def", "walk", "(", "self", ",", "depth", "=", "0", ",", "fsNode", "=", "None", ")", ":", "if", "not", "fsNode", ":", "fsNode", "=", "FSNode", "(", "self", ".", "init_path", ",", "self", ".", "init_path", ",", "0", ")", "if", "fsNode", ".", "isdi...
Note, this is a filtered walk
[ "Note", "this", "is", "a", "filtered", "walk" ]
train
https://github.com/interstar/FSQuery/blob/5f57dffeefde4f601af98db9f8ba4177c620dbbd/fsquery/fsquery.py#L155-L175
interstar/FSQuery
fsquery/fsquery.py
FSQuery.shadow
def shadow(self,new_root,visitor) : """ Runs through the query, creating a clone directory structure in the new_root. Then applies process""" for n in self.walk() : sn = n.clone(new_root) if n.isdir() : visitor.process_dir(n,sn) else : visitor.process_file(n,sn)
python
def shadow(self,new_root,visitor) : """ Runs through the query, creating a clone directory structure in the new_root. Then applies process""" for n in self.walk() : sn = n.clone(new_root) if n.isdir() : visitor.process_dir(n,sn) else : visitor.process_file(n,sn)
[ "def", "shadow", "(", "self", ",", "new_root", ",", "visitor", ")", ":", "for", "n", "in", "self", ".", "walk", "(", ")", ":", "sn", "=", "n", ".", "clone", "(", "new_root", ")", "if", "n", ".", "isdir", "(", ")", ":", "visitor", ".", "process_...
Runs through the query, creating a clone directory structure in the new_root. Then applies process
[ "Runs", "through", "the", "query", "creating", "a", "clone", "directory", "structure", "in", "the", "new_root", ".", "Then", "applies", "process" ]
train
https://github.com/interstar/FSQuery/blob/5f57dffeefde4f601af98db9f8ba4177c620dbbd/fsquery/fsquery.py#L191-L198
interstar/FSQuery
fsquery/fsquery.py
FSQuery.DirContains
def DirContains(self,f) : """ Matches dirs that have a child that matches filter f""" def match(fsNode) : if not fsNode.isdir() : return False for c in fsNode.children() : if f(c) : return True return False return self.make_return(match)
python
def DirContains(self,f) : """ Matches dirs that have a child that matches filter f""" def match(fsNode) : if not fsNode.isdir() : return False for c in fsNode.children() : if f(c) : return True return False return self.make_return(match)
[ "def", "DirContains", "(", "self", ",", "f", ")", ":", "def", "match", "(", "fsNode", ")", ":", "if", "not", "fsNode", ".", "isdir", "(", ")", ":", "return", "False", "for", "c", "in", "fsNode", ".", "children", "(", ")", ":", "if", "f", "(", "...
Matches dirs that have a child that matches filter f
[ "Matches", "dirs", "that", "have", "a", "child", "that", "matches", "filter", "f" ]
train
https://github.com/interstar/FSQuery/blob/5f57dffeefde4f601af98db9f8ba4177c620dbbd/fsquery/fsquery.py#L239-L246
cohorte/cohorte-herald
python/snippets/herald_mqtt/directory.py
Directory.register
def register(self, peer): """ Registers a peer according to its description :param peer: A Peer description bean :raise KeyError: """ assert isinstance(peer, beans.Peer) with self.__lock: # Check presence peer_id = peer.peer_id if peer_id in self.peers: raise KeyError("Already known peer: {0}".format(peer)) # Store the description self.peers[peer_id] = peer # Store in the groups for name in peer.groups: self.groups.setdefault(name, set()).add(peer_id)
python
def register(self, peer): """ Registers a peer according to its description :param peer: A Peer description bean :raise KeyError: """ assert isinstance(peer, beans.Peer) with self.__lock: # Check presence peer_id = peer.peer_id if peer_id in self.peers: raise KeyError("Already known peer: {0}".format(peer)) # Store the description self.peers[peer_id] = peer # Store in the groups for name in peer.groups: self.groups.setdefault(name, set()).add(peer_id)
[ "def", "register", "(", "self", ",", "peer", ")", ":", "assert", "isinstance", "(", "peer", ",", "beans", ".", "Peer", ")", "with", "self", ".", "__lock", ":", "# Check presence", "peer_id", "=", "peer", ".", "peer_id", "if", "peer_id", "in", "self", "...
Registers a peer according to its description :param peer: A Peer description bean :raise KeyError:
[ "Registers", "a", "peer", "according", "to", "its", "description" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_mqtt/directory.py#L48-L68
cohorte/cohorte-herald
python/snippets/herald_mqtt/directory.py
Directory.unregister
def unregister(self, peer_id): """ Unregisters the given peer :param peer_id: A peer UUID :raise KeyError: Unknown peer """ with self.__lock: # Pop it from accesses (will raise a KeyError if absent) peer = self.peers.pop(peer_id) assert isinstance(peer, beans.Peer) # Remove it from groups for name in peer.groups: try: # Clean up the group group = self.groups[name] group.remove(peer_id) # Remove it if it's empty if not group: del self.groups[name] except KeyError: # Be tolerant here pass
python
def unregister(self, peer_id): """ Unregisters the given peer :param peer_id: A peer UUID :raise KeyError: Unknown peer """ with self.__lock: # Pop it from accesses (will raise a KeyError if absent) peer = self.peers.pop(peer_id) assert isinstance(peer, beans.Peer) # Remove it from groups for name in peer.groups: try: # Clean up the group group = self.groups[name] group.remove(peer_id) # Remove it if it's empty if not group: del self.groups[name] except KeyError: # Be tolerant here pass
[ "def", "unregister", "(", "self", ",", "peer_id", ")", ":", "with", "self", ".", "__lock", ":", "# Pop it from accesses (will raise a KeyError if absent)", "peer", "=", "self", ".", "peers", ".", "pop", "(", "peer_id", ")", "assert", "isinstance", "(", "peer", ...
Unregisters the given peer :param peer_id: A peer UUID :raise KeyError: Unknown peer
[ "Unregisters", "the", "given", "peer" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_mqtt/directory.py#L71-L96
rndmcnlly/ansunit
ansunit/__init__.py
reduce_contexts
def reduce_contexts(parent, local): """Combine two test contexts into one. For value types of dict and list, the new context will aggregate the parent and local contexts. For other types, the value of the local context will replace the value of the parent (if any).""" context = {} for k,v in parent.items(): if type(v) == dict: d = v.copy() d.update(local.get(k,{})) context[k] = d elif type(v) == list: context[k] = v + ensure_list(local.get(k,[])) else: context[k] = local.get(k,v) for k in set(local.keys()) - set(parent.keys()): context[k] = local[k] return context
python
def reduce_contexts(parent, local): """Combine two test contexts into one. For value types of dict and list, the new context will aggregate the parent and local contexts. For other types, the value of the local context will replace the value of the parent (if any).""" context = {} for k,v in parent.items(): if type(v) == dict: d = v.copy() d.update(local.get(k,{})) context[k] = d elif type(v) == list: context[k] = v + ensure_list(local.get(k,[])) else: context[k] = local.get(k,v) for k in set(local.keys()) - set(parent.keys()): context[k] = local[k] return context
[ "def", "reduce_contexts", "(", "parent", ",", "local", ")", ":", "context", "=", "{", "}", "for", "k", ",", "v", "in", "parent", ".", "items", "(", ")", ":", "if", "type", "(", "v", ")", "==", "dict", ":", "d", "=", "v", ".", "copy", "(", ")"...
Combine two test contexts into one. For value types of dict and list, the new context will aggregate the parent and local contexts. For other types, the value of the local context will replace the value of the parent (if any).
[ "Combine", "two", "test", "contexts", "into", "one", ".", "For", "value", "types", "of", "dict", "and", "list", "the", "new", "context", "will", "aggregate", "the", "parent", "and", "local", "contexts", ".", "For", "other", "types", "the", "value", "of", ...
train
https://github.com/rndmcnlly/ansunit/blob/3d45e22ab1ae131b6eda25d5ae2ead2c5cfee02a/ansunit/__init__.py#L33-L55
rndmcnlly/ansunit
ansunit/__init__.py
resolve_module
def resolve_module(module, definitions): """Resolve (through indirections) the program contents of a module definition. The result is a list of program chunks.""" assert module in definitions, "No definition for module '%s'" % module d = definitions[module] if type(d) == dict: if 'filename' in d: with open(d['filename']) as f: return [f.read().strip()] elif 'reference' in d: return resolve_module(d['reference'], definitions) elif 'group' in d: return sum([resolve_module(m,definitions) for m in d['group']],[]) else: assert False else: assert type(d) == str return [d]
python
def resolve_module(module, definitions): """Resolve (through indirections) the program contents of a module definition. The result is a list of program chunks.""" assert module in definitions, "No definition for module '%s'" % module d = definitions[module] if type(d) == dict: if 'filename' in d: with open(d['filename']) as f: return [f.read().strip()] elif 'reference' in d: return resolve_module(d['reference'], definitions) elif 'group' in d: return sum([resolve_module(m,definitions) for m in d['group']],[]) else: assert False else: assert type(d) == str return [d]
[ "def", "resolve_module", "(", "module", ",", "definitions", ")", ":", "assert", "module", "in", "definitions", ",", "\"No definition for module '%s'\"", "%", "module", "d", "=", "definitions", "[", "module", "]", "if", "type", "(", "d", ")", "==", "dict", ":...
Resolve (through indirections) the program contents of a module definition. The result is a list of program chunks.
[ "Resolve", "(", "through", "indirections", ")", "the", "program", "contents", "of", "a", "module", "definition", ".", "The", "result", "is", "a", "list", "of", "program", "chunks", "." ]
train
https://github.com/rndmcnlly/ansunit/blob/3d45e22ab1ae131b6eda25d5ae2ead2c5cfee02a/ansunit/__init__.py#L57-L76
rndmcnlly/ansunit
ansunit/__init__.py
canonicalize_spec
def canonicalize_spec(spec, parent_context): """Push all context declarations to the leaves of a nested test specification.""" test_specs = {k:v for (k,v) in spec.items() if k.startswith("Test")} local_context = {k:v for (k,v) in spec.items() if not k.startswith("Test")} context = reduce_contexts(parent_context, local_context) if test_specs: return {k: canonicalize_spec(v, context) for (k,v) in test_specs.items()} else: program_chunks = sum([resolve_module(m,context['Definitions']) for m in context['Modules']],[]) + [context['Program']] test_spec = { 'Arguments': context['Arguments'], 'Program': "\n".join(program_chunks), 'Expect': context['Expect'], } return test_spec
python
def canonicalize_spec(spec, parent_context): """Push all context declarations to the leaves of a nested test specification.""" test_specs = {k:v for (k,v) in spec.items() if k.startswith("Test")} local_context = {k:v for (k,v) in spec.items() if not k.startswith("Test")} context = reduce_contexts(parent_context, local_context) if test_specs: return {k: canonicalize_spec(v, context) for (k,v) in test_specs.items()} else: program_chunks = sum([resolve_module(m,context['Definitions']) for m in context['Modules']],[]) + [context['Program']] test_spec = { 'Arguments': context['Arguments'], 'Program': "\n".join(program_chunks), 'Expect': context['Expect'], } return test_spec
[ "def", "canonicalize_spec", "(", "spec", ",", "parent_context", ")", ":", "test_specs", "=", "{", "k", ":", "v", "for", "(", "k", ",", "v", ")", "in", "spec", ".", "items", "(", ")", "if", "k", ".", "startswith", "(", "\"Test\"", ")", "}", "local_c...
Push all context declarations to the leaves of a nested test specification.
[ "Push", "all", "context", "declarations", "to", "the", "leaves", "of", "a", "nested", "test", "specification", "." ]
train
https://github.com/rndmcnlly/ansunit/blob/3d45e22ab1ae131b6eda25d5ae2ead2c5cfee02a/ansunit/__init__.py#L78-L95
rndmcnlly/ansunit
ansunit/__init__.py
flatten_spec
def flatten_spec(spec, prefix,joiner=" :: "): """Flatten a canonical specification with nesting into one without nesting. When building unique names, concatenate the given prefix to the local test name without the "Test " tag.""" if any(filter(operator.methodcaller("startswith","Test"),spec.keys())): flat_spec = {} for (k,v) in spec.items(): flat_spec.update(flatten_spec(v,prefix + joiner + k[5:])) return flat_spec else: return {"Test "+prefix: spec}
python
def flatten_spec(spec, prefix,joiner=" :: "): """Flatten a canonical specification with nesting into one without nesting. When building unique names, concatenate the given prefix to the local test name without the "Test " tag.""" if any(filter(operator.methodcaller("startswith","Test"),spec.keys())): flat_spec = {} for (k,v) in spec.items(): flat_spec.update(flatten_spec(v,prefix + joiner + k[5:])) return flat_spec else: return {"Test "+prefix: spec}
[ "def", "flatten_spec", "(", "spec", ",", "prefix", ",", "joiner", "=", "\" :: \"", ")", ":", "if", "any", "(", "filter", "(", "operator", ".", "methodcaller", "(", "\"startswith\"", ",", "\"Test\"", ")", ",", "spec", ".", "keys", "(", ")", ")", ")", ...
Flatten a canonical specification with nesting into one without nesting. When building unique names, concatenate the given prefix to the local test name without the "Test " tag.
[ "Flatten", "a", "canonical", "specification", "with", "nesting", "into", "one", "without", "nesting", ".", "When", "building", "unique", "names", "concatenate", "the", "given", "prefix", "to", "the", "local", "test", "name", "without", "the", "Test", "tag", "....
train
https://github.com/rndmcnlly/ansunit/blob/3d45e22ab1ae131b6eda25d5ae2ead2c5cfee02a/ansunit/__init__.py#L97-L108
jvamvas/rhymediscovery
rhymediscovery/find_schemes.py
load_stanzas
def load_stanzas(stanzas_file): """ Load stanzas from gold standard file """ f = stanzas_file.readlines() stanzas = [] for i, line in enumerate(f): if i % 4 == 0: stanza_words = line.strip().split()[1:] stanzas.append(Stanza(stanza_words)) return stanzas
python
def load_stanzas(stanzas_file): """ Load stanzas from gold standard file """ f = stanzas_file.readlines() stanzas = [] for i, line in enumerate(f): if i % 4 == 0: stanza_words = line.strip().split()[1:] stanzas.append(Stanza(stanza_words)) return stanzas
[ "def", "load_stanzas", "(", "stanzas_file", ")", ":", "f", "=", "stanzas_file", ".", "readlines", "(", ")", "stanzas", "=", "[", "]", "for", "i", ",", "line", "in", "enumerate", "(", "f", ")", ":", "if", "i", "%", "4", "==", "0", ":", "stanza_words...
Load stanzas from gold standard file
[ "Load", "stanzas", "from", "gold", "standard", "file" ]
train
https://github.com/jvamvas/rhymediscovery/blob/b76509c98554b12efa06fe9ab557cca5fa5e4a79/rhymediscovery/find_schemes.py#L23-L33
jvamvas/rhymediscovery
rhymediscovery/find_schemes.py
get_wordlist
def get_wordlist(stanzas): """ Get an iterable of all final words in all stanzas """ return sorted(list(set().union(*[stanza.words for stanza in stanzas])))
python
def get_wordlist(stanzas): """ Get an iterable of all final words in all stanzas """ return sorted(list(set().union(*[stanza.words for stanza in stanzas])))
[ "def", "get_wordlist", "(", "stanzas", ")", ":", "return", "sorted", "(", "list", "(", "set", "(", ")", ".", "union", "(", "*", "[", "stanza", ".", "words", "for", "stanza", "in", "stanzas", "]", ")", ")", ")" ]
Get an iterable of all final words in all stanzas
[ "Get", "an", "iterable", "of", "all", "final", "words", "in", "all", "stanzas" ]
train
https://github.com/jvamvas/rhymediscovery/blob/b76509c98554b12efa06fe9ab557cca5fa5e4a79/rhymediscovery/find_schemes.py#L86-L90
jvamvas/rhymediscovery
rhymediscovery/find_schemes.py
get_rhymelists
def get_rhymelists(stanza, scheme): """ Returns ordered lists of the stanza's word indices as defined by given scheme """ rhymelists = defaultdict(list) for rhyme_group, word_index in zip(scheme, stanza.word_indices): rhymelists[rhyme_group].append(word_index) return list(rhymelists.values())
python
def get_rhymelists(stanza, scheme): """ Returns ordered lists of the stanza's word indices as defined by given scheme """ rhymelists = defaultdict(list) for rhyme_group, word_index in zip(scheme, stanza.word_indices): rhymelists[rhyme_group].append(word_index) return list(rhymelists.values())
[ "def", "get_rhymelists", "(", "stanza", ",", "scheme", ")", ":", "rhymelists", "=", "defaultdict", "(", "list", ")", "for", "rhyme_group", ",", "word_index", "in", "zip", "(", "scheme", ",", "stanza", ".", "word_indices", ")", ":", "rhymelists", "[", "rhym...
Returns ordered lists of the stanza's word indices as defined by given scheme
[ "Returns", "ordered", "lists", "of", "the", "stanza", "s", "word", "indices", "as", "defined", "by", "given", "scheme" ]
train
https://github.com/jvamvas/rhymediscovery/blob/b76509c98554b12efa06fe9ab557cca5fa5e4a79/rhymediscovery/find_schemes.py#L93-L100
jvamvas/rhymediscovery
rhymediscovery/find_schemes.py
init_distance_ttable
def init_distance_ttable(wordlist, distance_function): """ Initialize pair-wise rhyme strenghts according to the given word distance function """ n = len(wordlist) t_table = numpy.zeros((n, n + 1)) # Initialize P(c|r) accordingly for r, w in enumerate(wordlist): for c, v in enumerate(wordlist): if c < r: t_table[r, c] = t_table[c, r] # Similarity is symmetric else: t_table[r, c] = distance_function(w, v) + 0.001 # For backoff t_table[:, n] = numpy.mean(t_table[:, :-1], axis=1) # Normalize t_totals = numpy.sum(t_table, axis=0) for i, t_total in enumerate(t_totals.tolist()): t_table[:, i] /= t_total return t_table
python
def init_distance_ttable(wordlist, distance_function): """ Initialize pair-wise rhyme strenghts according to the given word distance function """ n = len(wordlist) t_table = numpy.zeros((n, n + 1)) # Initialize P(c|r) accordingly for r, w in enumerate(wordlist): for c, v in enumerate(wordlist): if c < r: t_table[r, c] = t_table[c, r] # Similarity is symmetric else: t_table[r, c] = distance_function(w, v) + 0.001 # For backoff t_table[:, n] = numpy.mean(t_table[:, :-1], axis=1) # Normalize t_totals = numpy.sum(t_table, axis=0) for i, t_total in enumerate(t_totals.tolist()): t_table[:, i] /= t_total return t_table
[ "def", "init_distance_ttable", "(", "wordlist", ",", "distance_function", ")", ":", "n", "=", "len", "(", "wordlist", ")", "t_table", "=", "numpy", ".", "zeros", "(", "(", "n", ",", "n", "+", "1", ")", ")", "# Initialize P(c|r) accordingly", "for", "r", ...
Initialize pair-wise rhyme strenghts according to the given word distance function
[ "Initialize", "pair", "-", "wise", "rhyme", "strenghts", "according", "to", "the", "given", "word", "distance", "function" ]
train
https://github.com/jvamvas/rhymediscovery/blob/b76509c98554b12efa06fe9ab557cca5fa5e4a79/rhymediscovery/find_schemes.py#L103-L123
jvamvas/rhymediscovery
rhymediscovery/find_schemes.py
init_uniform_ttable
def init_uniform_ttable(wordlist): """ Initialize (normalized) theta uniformly """ n = len(wordlist) return numpy.ones((n, n + 1)) * (1 / n)
python
def init_uniform_ttable(wordlist): """ Initialize (normalized) theta uniformly """ n = len(wordlist) return numpy.ones((n, n + 1)) * (1 / n)
[ "def", "init_uniform_ttable", "(", "wordlist", ")", ":", "n", "=", "len", "(", "wordlist", ")", "return", "numpy", ".", "ones", "(", "(", "n", ",", "n", "+", "1", ")", ")", "*", "(", "1", "/", "n", ")" ]
Initialize (normalized) theta uniformly
[ "Initialize", "(", "normalized", ")", "theta", "uniformly" ]
train
https://github.com/jvamvas/rhymediscovery/blob/b76509c98554b12efa06fe9ab557cca5fa5e4a79/rhymediscovery/find_schemes.py#L126-L131
jvamvas/rhymediscovery
rhymediscovery/find_schemes.py
basic_word_sim
def basic_word_sim(word1, word2): """ Simple measure of similarity: Number of letters in common / max length """ return sum([1 for c in word1 if c in word2]) / max(len(word1), len(word2))
python
def basic_word_sim(word1, word2): """ Simple measure of similarity: Number of letters in common / max length """ return sum([1 for c in word1 if c in word2]) / max(len(word1), len(word2))
[ "def", "basic_word_sim", "(", "word1", ",", "word2", ")", ":", "return", "sum", "(", "[", "1", "for", "c", "in", "word1", "if", "c", "in", "word2", "]", ")", "/", "max", "(", "len", "(", "word1", ")", ",", "len", "(", "word2", ")", ")" ]
Simple measure of similarity: Number of letters in common / max length
[ "Simple", "measure", "of", "similarity", ":", "Number", "of", "letters", "in", "common", "/", "max", "length" ]
train
https://github.com/jvamvas/rhymediscovery/blob/b76509c98554b12efa06fe9ab557cca5fa5e4a79/rhymediscovery/find_schemes.py#L134-L138