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
lambdalisue/e4u
e4u/__init__.py
translate
def translate(source, carrier, reverse=False, encoding=None): u"""translate unicode text contain emoji character to unicode carrier text (or reverse) Attributes: source - text contain emoji character. it must be unicode instance or have to set `encoding` attribute to decode carrier - the target carrier reverse - if you want to translate CARRIER TEXT => UNICODE, turn it True encoding - encoding name for decode (Default is None) """ if not isinstance(source, unicode) and encoding: source = source.decode(encoding, 'replace') elif not isinstance(source, unicode): raise AttributeError(u"`source` must be decoded to `unicode` or set `encoding` attribute to decode `source`") regex_pattern = _loader.regex_patterns[carrier] translate_dictionary = _loader.translate_dictionaries[carrier] if not reverse: regex_pattern = regex_pattern[0] translate_dictionary = translate_dictionary[0] else: regex_pattern = regex_pattern[1] translate_dictionary = translate_dictionary[1] if not regex_pattern or not translate_dictionary: return source return regex_pattern.sub(lambda m: translate_dictionary[m.group()], source)
python
def translate(source, carrier, reverse=False, encoding=None): u"""translate unicode text contain emoji character to unicode carrier text (or reverse) Attributes: source - text contain emoji character. it must be unicode instance or have to set `encoding` attribute to decode carrier - the target carrier reverse - if you want to translate CARRIER TEXT => UNICODE, turn it True encoding - encoding name for decode (Default is None) """ if not isinstance(source, unicode) and encoding: source = source.decode(encoding, 'replace') elif not isinstance(source, unicode): raise AttributeError(u"`source` must be decoded to `unicode` or set `encoding` attribute to decode `source`") regex_pattern = _loader.regex_patterns[carrier] translate_dictionary = _loader.translate_dictionaries[carrier] if not reverse: regex_pattern = regex_pattern[0] translate_dictionary = translate_dictionary[0] else: regex_pattern = regex_pattern[1] translate_dictionary = translate_dictionary[1] if not regex_pattern or not translate_dictionary: return source return regex_pattern.sub(lambda m: translate_dictionary[m.group()], source)
[ "def", "translate", "(", "source", ",", "carrier", ",", "reverse", "=", "False", ",", "encoding", "=", "None", ")", ":", "if", "not", "isinstance", "(", "source", ",", "unicode", ")", "and", "encoding", ":", "source", "=", "source", ".", "decode", "(",...
u"""translate unicode text contain emoji character to unicode carrier text (or reverse) Attributes: source - text contain emoji character. it must be unicode instance or have to set `encoding` attribute to decode carrier - the target carrier reverse - if you want to translate CARRIER TEXT => UNICODE, turn it True encoding - encoding name for decode (Default is None)
[ "u", "translate", "unicode", "text", "contain", "emoji", "character", "to", "unicode", "carrier", "text", "(", "or", "reverse", ")", "Attributes", ":", "source", "-", "text", "contain", "emoji", "character", ".", "it", "must", "be", "unicode", "instance", "o...
train
https://github.com/lambdalisue/e4u/blob/108635c5ba37e7ae33001adbf07a95878f31fd50/e4u/__init__.py#L65-L89
bdastur/spam
pyansible/ansivault.py
AnsiVault.is_file_encrypted
def is_file_encrypted(self, filename): ''' Given a file. Check if it is already encrypted. ''' if not os.path.exists(filename): print "Invalid filename %s. Does not exist" % filename return False fhandle = open(filename, "rb") data = fhandle.read() fhandle.close() if data.startswith(AnsiVault.HEADER): return True else: return False
python
def is_file_encrypted(self, filename): ''' Given a file. Check if it is already encrypted. ''' if not os.path.exists(filename): print "Invalid filename %s. Does not exist" % filename return False fhandle = open(filename, "rb") data = fhandle.read() fhandle.close() if data.startswith(AnsiVault.HEADER): return True else: return False
[ "def", "is_file_encrypted", "(", "self", ",", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "print", "\"Invalid filename %s. Does not exist\"", "%", "filename", "return", "False", "fhandle", "=", "open", "(", ...
Given a file. Check if it is already encrypted.
[ "Given", "a", "file", ".", "Check", "if", "it", "is", "already", "encrypted", "." ]
train
https://github.com/bdastur/spam/blob/3c363302412d15bdb391f62bf90348243e456af2/pyansible/ansivault.py#L19-L34
bdastur/spam
pyansible/ansivault.py
AnsiVault.encrpyt_file
def encrpyt_file(self, filename): ''' Encrypt File Args: filename: Pass the filename to encrypt. Returns: No return. ''' if not os.path.exists(filename): print "Invalid filename %s. Does not exist" % filename return if self.vault_password is None: print "ENV Variable PYANSI_VAULT_PASSWORD not set" return if self.is_file_encrypted(filename): # No need to do anything. return cipher = 'AES256' vaulteditor = VaultEditor(cipher, self.vault_password, filename) vaulteditor.encrypt_file()
python
def encrpyt_file(self, filename): ''' Encrypt File Args: filename: Pass the filename to encrypt. Returns: No return. ''' if not os.path.exists(filename): print "Invalid filename %s. Does not exist" % filename return if self.vault_password is None: print "ENV Variable PYANSI_VAULT_PASSWORD not set" return if self.is_file_encrypted(filename): # No need to do anything. return cipher = 'AES256' vaulteditor = VaultEditor(cipher, self.vault_password, filename) vaulteditor.encrypt_file()
[ "def", "encrpyt_file", "(", "self", ",", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "print", "\"Invalid filename %s. Does not exist\"", "%", "filename", "return", "if", "self", ".", "vault_password", "is", ...
Encrypt File Args: filename: Pass the filename to encrypt. Returns: No return.
[ "Encrypt", "File", "Args", ":", "filename", ":", "Pass", "the", "filename", "to", "encrypt", ".", "Returns", ":", "No", "return", "." ]
train
https://github.com/bdastur/spam/blob/3c363302412d15bdb391f62bf90348243e456af2/pyansible/ansivault.py#L36-L58
bdastur/spam
pyansible/ansivault.py
AnsiVault.decrypt_file
def decrypt_file(self, filename): ''' Decrypt File Args: filename: Pass the filename to encrypt. Returns: No return. ''' if not os.path.exists(filename): print "Invalid filename %s. Does not exist" % filename return if self.vault_password is None: print "ENV Variable PYANSI_VAULT_PASSWORD not set" return if not self.is_file_encrypted(filename): # No need to do anything. return cipher = 'AES256' vaulteditor = VaultEditor(cipher, self.vault_password, filename) vaulteditor.decrypt_file()
python
def decrypt_file(self, filename): ''' Decrypt File Args: filename: Pass the filename to encrypt. Returns: No return. ''' if not os.path.exists(filename): print "Invalid filename %s. Does not exist" % filename return if self.vault_password is None: print "ENV Variable PYANSI_VAULT_PASSWORD not set" return if not self.is_file_encrypted(filename): # No need to do anything. return cipher = 'AES256' vaulteditor = VaultEditor(cipher, self.vault_password, filename) vaulteditor.decrypt_file()
[ "def", "decrypt_file", "(", "self", ",", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "print", "\"Invalid filename %s. Does not exist\"", "%", "filename", "return", "if", "self", ".", "vault_password", "is", ...
Decrypt File Args: filename: Pass the filename to encrypt. Returns: No return.
[ "Decrypt", "File", "Args", ":", "filename", ":", "Pass", "the", "filename", "to", "encrypt", ".", "Returns", ":", "No", "return", "." ]
train
https://github.com/bdastur/spam/blob/3c363302412d15bdb391f62bf90348243e456af2/pyansible/ansivault.py#L60-L82
mfitzp/metaviz
metaviz/metaviz.py
common_start
def common_start(*args): """ returns the longest common substring from the beginning of sa and sb """ def _iter(): for s in zip(*args): if len(set(s)) < len(args): yield s[0] else: return out = "".join(_iter()).strip() result = [s for s in args if not s.startswith(out)] result.insert(0, out) return ', '.join(result)
python
def common_start(*args): """ returns the longest common substring from the beginning of sa and sb """ def _iter(): for s in zip(*args): if len(set(s)) < len(args): yield s[0] else: return out = "".join(_iter()).strip() result = [s for s in args if not s.startswith(out)] result.insert(0, out) return ', '.join(result)
[ "def", "common_start", "(", "*", "args", ")", ":", "def", "_iter", "(", ")", ":", "for", "s", "in", "zip", "(", "*", "args", ")", ":", "if", "len", "(", "set", "(", "s", ")", ")", "<", "len", "(", "args", ")", ":", "yield", "s", "[", "0", ...
returns the longest common substring from the beginning of sa and sb
[ "returns", "the", "longest", "common", "substring", "from", "the", "beginning", "of", "sa", "and", "sb" ]
train
https://github.com/mfitzp/metaviz/blob/a31afee619a2989eacd75d0565011ba2723df514/metaviz/metaviz.py#L163-L175
fake-name/WebRequest
WebRequest/utility.py
determine_json_encoding
def determine_json_encoding(json_bytes): ''' Given the fact that the first 2 characters in json are guaranteed to be ASCII, we can use these to determine the encoding. See: http://tools.ietf.org/html/rfc4627#section-3 Copied here: Since the first two characters of a JSON text will always be ASCII characters [RFC0020], it is possible to determine whether an octet stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking at the pattern of nulls in the first four octets. 00 00 00 xx UTF-32BE 00 xx 00 xx UTF-16BE xx 00 00 00 UTF-32LE xx 00 xx 00 UTF-16LE xx xx xx xx UTF-8 ''' assert isinstance(json_bytes, bytes), "`determine_json_encoding()` can only operate on bytestring inputs" if len(json_bytes) > 4: b1, b2, b3, b4 = json_bytes[0], json_bytes[1], json_bytes[2], json_bytes[3] if b1 == 0 and b2 == 0 and b3 == 0 and b4 != 0: return "UTF-32BE" elif b1 == 0 and b2 != 0 and b3 == 0 and b4 != 0: return "UTF-16BE" elif b1 != 0 and b2 == 0 and b3 == 0 and b4 == 0: return "UTF-32LE" elif b1 != 0 and b2 == 0 and b3 != 0 and b4 == 0: return "UTF-16LE" elif b1 != 0 and b2 != 0 and b3 != 0 and b4 != 0: return "UTF-8" else: raise Exceptions.ContentTypeError("Unknown encoding!") elif len(json_bytes) > 2: b1, b2 = json_bytes[0], json_bytes[1] if b1 == 0 and b2 == 0: return "UTF-32BE" elif b1 == 0 and b2 != 0: return "UTF-16BE" elif b1 != 0 and b2 == 0: raise Exceptions.ContentTypeError("Json string too short to definitively infer encoding.") elif b1 != 0 and b2 != 0: return "UTF-8" else: raise Exceptions.ContentTypeError("Unknown encoding!") raise Exceptions.ContentTypeError("Input string too short to guess encoding!")
python
def determine_json_encoding(json_bytes): ''' Given the fact that the first 2 characters in json are guaranteed to be ASCII, we can use these to determine the encoding. See: http://tools.ietf.org/html/rfc4627#section-3 Copied here: Since the first two characters of a JSON text will always be ASCII characters [RFC0020], it is possible to determine whether an octet stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking at the pattern of nulls in the first four octets. 00 00 00 xx UTF-32BE 00 xx 00 xx UTF-16BE xx 00 00 00 UTF-32LE xx 00 xx 00 UTF-16LE xx xx xx xx UTF-8 ''' assert isinstance(json_bytes, bytes), "`determine_json_encoding()` can only operate on bytestring inputs" if len(json_bytes) > 4: b1, b2, b3, b4 = json_bytes[0], json_bytes[1], json_bytes[2], json_bytes[3] if b1 == 0 and b2 == 0 and b3 == 0 and b4 != 0: return "UTF-32BE" elif b1 == 0 and b2 != 0 and b3 == 0 and b4 != 0: return "UTF-16BE" elif b1 != 0 and b2 == 0 and b3 == 0 and b4 == 0: return "UTF-32LE" elif b1 != 0 and b2 == 0 and b3 != 0 and b4 == 0: return "UTF-16LE" elif b1 != 0 and b2 != 0 and b3 != 0 and b4 != 0: return "UTF-8" else: raise Exceptions.ContentTypeError("Unknown encoding!") elif len(json_bytes) > 2: b1, b2 = json_bytes[0], json_bytes[1] if b1 == 0 and b2 == 0: return "UTF-32BE" elif b1 == 0 and b2 != 0: return "UTF-16BE" elif b1 != 0 and b2 == 0: raise Exceptions.ContentTypeError("Json string too short to definitively infer encoding.") elif b1 != 0 and b2 != 0: return "UTF-8" else: raise Exceptions.ContentTypeError("Unknown encoding!") raise Exceptions.ContentTypeError("Input string too short to guess encoding!")
[ "def", "determine_json_encoding", "(", "json_bytes", ")", ":", "assert", "isinstance", "(", "json_bytes", ",", "bytes", ")", ",", "\"`determine_json_encoding()` can only operate on bytestring inputs\"", "if", "len", "(", "json_bytes", ")", ">", "4", ":", "b1", ",", ...
Given the fact that the first 2 characters in json are guaranteed to be ASCII, we can use these to determine the encoding. See: http://tools.ietf.org/html/rfc4627#section-3 Copied here: Since the first two characters of a JSON text will always be ASCII characters [RFC0020], it is possible to determine whether an octet stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking at the pattern of nulls in the first four octets. 00 00 00 xx UTF-32BE 00 xx 00 xx UTF-16BE xx 00 00 00 UTF-32LE xx 00 xx 00 UTF-16LE xx xx xx xx UTF-8
[ "Given", "the", "fact", "that", "the", "first", "2", "characters", "in", "json", "are", "guaranteed", "to", "be", "ASCII", "we", "can", "use", "these", "to", "determine", "the", "encoding", ".", "See", ":", "http", ":", "//", "tools", ".", "ietf", ".",...
train
https://github.com/fake-name/WebRequest/blob/b6c94631ff88b5f81f26a9f99a2d5c706810b11f/WebRequest/utility.py#L28-L77
soslan/passgen
src/passgen.py
passgen
def passgen(length=12, punctuation=False, digits=True, letters=True, case="both", **kwargs): """Generate random password. Args: length (int): The length of the password. Must be greater than zero. Defaults to 12. punctuation (bool): Whether to use punctuation or not. Defaults to False. limit_punctuation (str): Limits the allowed puncturation to defined characters. digits (bool): Whether to use digits or not. Defaults to True. One of *digits* and *letters* must be True. letters (bool): Whether to use letters or not. Defaults to True. One of *digits* and *letters* must be True. case (str): Letter case to use. Accepts 'upper' for upper case, 'lower' for lower case, and 'both' for both. Defaults to 'both'. Returns: str. The generated password. Raises: ValueError Below are some basic examples. >>> passgen() z7GlutdEEbnk >>> passgen(case='upper') Q81J9DOAMBRN >>> passgen(length=6) EzJMRX """ p_min = punctuation p_max = 0 if punctuation is False else length d_min = digits d_max = 0 if digits is False else length a_min = letters a_max = 0 if letters is False else length if d_min + p_min + a_min > length: raise ValueError("Minimum punctuation and digits number cannot be greater than length") if not digits and not letters: raise ValueError("digits and letters cannot be False at the same time") if length < 1: raise ValueError("length must be greater than zero") if letters: if case == "both": alpha = string.ascii_uppercase + string.ascii_lowercase elif case == "upper": alpha = string.ascii_uppercase elif case == "lower": alpha = string.ascii_lowercase else: raise ValueError("case can only be 'both', 'upper' or 'lower'") else: alpha = string.ascii_uppercase + string.ascii_lowercase if punctuation: limit_punctuation = kwargs.get('limit_punctuation', '') if limit_punctuation == '': punctuation_set = string.punctuation else: # In case limit_punctuation contains non-punctuation characters punctuation_set = ''.join([p for p in limit_punctuation if p in string.punctuation]) else: punctuation_set = string.punctuation srandom = random.SystemRandom() p_generator = Generator(punctuation_set, srandom, p_min, p_max) d_generator = Generator(string.digits, srandom, d_min, d_max) a_generator = Generator(alpha, srandom, a_min, a_max) main_generator = SuperGenerator(srandom, length, length) main_generator.add(p_generator) main_generator.add(a_generator) main_generator.add(d_generator) chars = [] for i in main_generator: chars.append(i) try: srandom.shuffle(chars, srandom) except: random.shuffle(chars) return "".join(chars)
python
def passgen(length=12, punctuation=False, digits=True, letters=True, case="both", **kwargs): """Generate random password. Args: length (int): The length of the password. Must be greater than zero. Defaults to 12. punctuation (bool): Whether to use punctuation or not. Defaults to False. limit_punctuation (str): Limits the allowed puncturation to defined characters. digits (bool): Whether to use digits or not. Defaults to True. One of *digits* and *letters* must be True. letters (bool): Whether to use letters or not. Defaults to True. One of *digits* and *letters* must be True. case (str): Letter case to use. Accepts 'upper' for upper case, 'lower' for lower case, and 'both' for both. Defaults to 'both'. Returns: str. The generated password. Raises: ValueError Below are some basic examples. >>> passgen() z7GlutdEEbnk >>> passgen(case='upper') Q81J9DOAMBRN >>> passgen(length=6) EzJMRX """ p_min = punctuation p_max = 0 if punctuation is False else length d_min = digits d_max = 0 if digits is False else length a_min = letters a_max = 0 if letters is False else length if d_min + p_min + a_min > length: raise ValueError("Minimum punctuation and digits number cannot be greater than length") if not digits and not letters: raise ValueError("digits and letters cannot be False at the same time") if length < 1: raise ValueError("length must be greater than zero") if letters: if case == "both": alpha = string.ascii_uppercase + string.ascii_lowercase elif case == "upper": alpha = string.ascii_uppercase elif case == "lower": alpha = string.ascii_lowercase else: raise ValueError("case can only be 'both', 'upper' or 'lower'") else: alpha = string.ascii_uppercase + string.ascii_lowercase if punctuation: limit_punctuation = kwargs.get('limit_punctuation', '') if limit_punctuation == '': punctuation_set = string.punctuation else: # In case limit_punctuation contains non-punctuation characters punctuation_set = ''.join([p for p in limit_punctuation if p in string.punctuation]) else: punctuation_set = string.punctuation srandom = random.SystemRandom() p_generator = Generator(punctuation_set, srandom, p_min, p_max) d_generator = Generator(string.digits, srandom, d_min, d_max) a_generator = Generator(alpha, srandom, a_min, a_max) main_generator = SuperGenerator(srandom, length, length) main_generator.add(p_generator) main_generator.add(a_generator) main_generator.add(d_generator) chars = [] for i in main_generator: chars.append(i) try: srandom.shuffle(chars, srandom) except: random.shuffle(chars) return "".join(chars)
[ "def", "passgen", "(", "length", "=", "12", ",", "punctuation", "=", "False", ",", "digits", "=", "True", ",", "letters", "=", "True", ",", "case", "=", "\"both\"", ",", "*", "*", "kwargs", ")", ":", "p_min", "=", "punctuation", "p_max", "=", "0", ...
Generate random password. Args: length (int): The length of the password. Must be greater than zero. Defaults to 12. punctuation (bool): Whether to use punctuation or not. Defaults to False. limit_punctuation (str): Limits the allowed puncturation to defined characters. digits (bool): Whether to use digits or not. Defaults to True. One of *digits* and *letters* must be True. letters (bool): Whether to use letters or not. Defaults to True. One of *digits* and *letters* must be True. case (str): Letter case to use. Accepts 'upper' for upper case, 'lower' for lower case, and 'both' for both. Defaults to 'both'. Returns: str. The generated password. Raises: ValueError Below are some basic examples. >>> passgen() z7GlutdEEbnk >>> passgen(case='upper') Q81J9DOAMBRN >>> passgen(length=6) EzJMRX
[ "Generate", "random", "password", "." ]
train
https://github.com/soslan/passgen/blob/7df9d7081b22df2a3dad69e6dafd3616b899cc7f/src/passgen.py#L86-L175
soslan/passgen
src/passgen.py
main
def main(): """The main entry point for command line invocation. It's output is adjusted by command line arguments. By default it outputs 10 passwords. For help on accepted arguments, run:: $ passgen -h Or:: $ python -m passgen -h """ parser = argparse.ArgumentParser( description="Generate random password." ) parser.add_argument("-l", "--length", help="the length of the generated " "password (default: 12)", type=int, default=12) parser.add_argument("-n", "--number", help="how many passwords to generate (default: 10)", type=int, default=10) parser.add_argument("-p", "--punctuation", help="use punctuation characters", action='store_true') parser.add_argument("--limit-punctuation", help="specify allowed punctuation characters", action='store', default='') alnum_group = parser.add_mutually_exclusive_group() alnum_group.add_argument("--no-digits", help="don't use digits", action='store_false', dest='digits') alnum_group.add_argument("--no-letters", help="don't use letters", action='store_false', dest='letters') case_group = parser.add_mutually_exclusive_group() case_group.add_argument("--upper", help="use only upper case letters", action='store_true') case_group.add_argument("--lower", help="use only lower case letters", action='store_true') args = parser.parse_args() if args.length < 1: _error("argument -l/--length must be greater than zero") if args.number < 1: _error("argument -n/--number must be greater than zero") if args.lower: case = "lower" elif args.upper: case = "upper" else: case = "both" for _ in range(args.number): print(passgen(args.length, punctuation=args.punctuation, limit_punctuation=args.limit_punctuation, digits=args.digits, letters=args.letters, case=case))
python
def main(): """The main entry point for command line invocation. It's output is adjusted by command line arguments. By default it outputs 10 passwords. For help on accepted arguments, run:: $ passgen -h Or:: $ python -m passgen -h """ parser = argparse.ArgumentParser( description="Generate random password." ) parser.add_argument("-l", "--length", help="the length of the generated " "password (default: 12)", type=int, default=12) parser.add_argument("-n", "--number", help="how many passwords to generate (default: 10)", type=int, default=10) parser.add_argument("-p", "--punctuation", help="use punctuation characters", action='store_true') parser.add_argument("--limit-punctuation", help="specify allowed punctuation characters", action='store', default='') alnum_group = parser.add_mutually_exclusive_group() alnum_group.add_argument("--no-digits", help="don't use digits", action='store_false', dest='digits') alnum_group.add_argument("--no-letters", help="don't use letters", action='store_false', dest='letters') case_group = parser.add_mutually_exclusive_group() case_group.add_argument("--upper", help="use only upper case letters", action='store_true') case_group.add_argument("--lower", help="use only lower case letters", action='store_true') args = parser.parse_args() if args.length < 1: _error("argument -l/--length must be greater than zero") if args.number < 1: _error("argument -n/--number must be greater than zero") if args.lower: case = "lower" elif args.upper: case = "upper" else: case = "both" for _ in range(args.number): print(passgen(args.length, punctuation=args.punctuation, limit_punctuation=args.limit_punctuation, digits=args.digits, letters=args.letters, case=case))
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Generate random password.\"", ")", "parser", ".", "add_argument", "(", "\"-l\"", ",", "\"--length\"", ",", "help", "=", "\"the length of the generated \"", ...
The main entry point for command line invocation. It's output is adjusted by command line arguments. By default it outputs 10 passwords. For help on accepted arguments, run:: $ passgen -h Or:: $ python -m passgen -h
[ "The", "main", "entry", "point", "for", "command", "line", "invocation", ".", "It", "s", "output", "is", "adjusted", "by", "command", "line", "arguments", ".", "By", "default", "it", "outputs", "10", "passwords", "." ]
train
https://github.com/soslan/passgen/blob/7df9d7081b22df2a3dad69e6dafd3616b899cc7f/src/passgen.py#L183-L244
vint21h/django-po2xls
po2xls/management/commands/po-to-xls.py
Command.convert
def convert(self, language, *args, **kwargs): """ Run converter. Args: language: (unicode) language code. """ for f in find_pos(language): PoToXls(src=f, **kwargs).convert()
python
def convert(self, language, *args, **kwargs): """ Run converter. Args: language: (unicode) language code. """ for f in find_pos(language): PoToXls(src=f, **kwargs).convert()
[ "def", "convert", "(", "self", ",", "language", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "f", "in", "find_pos", "(", "language", ")", ":", "PoToXls", "(", "src", "=", "f", ",", "*", "*", "kwargs", ")", ".", "convert", "(", ")...
Run converter. Args: language: (unicode) language code.
[ "Run", "converter", ".", "Args", ":", "language", ":", "(", "unicode", ")", "language", "code", "." ]
train
https://github.com/vint21h/django-po2xls/blob/e76d26cfae6d9e5ca95ff053d05a00f875875019/po2xls/management/commands/po-to-xls.py#L38-L46
pior/caravan
caravan/commands/base.py
BaseCommand.main
def main(cls): """Setuptools console-script entrypoint""" cmd = cls() cmd._parse_args() cmd._setup_logging() response = cmd._run() output = cmd._handle_response(response) if output is not None: print(output)
python
def main(cls): """Setuptools console-script entrypoint""" cmd = cls() cmd._parse_args() cmd._setup_logging() response = cmd._run() output = cmd._handle_response(response) if output is not None: print(output)
[ "def", "main", "(", "cls", ")", ":", "cmd", "=", "cls", "(", ")", "cmd", ".", "_parse_args", "(", ")", "cmd", ".", "_setup_logging", "(", ")", "response", "=", "cmd", ".", "_run", "(", ")", "output", "=", "cmd", ".", "_handle_response", "(", "respo...
Setuptools console-script entrypoint
[ "Setuptools", "console", "-", "script", "entrypoint" ]
train
https://github.com/pior/caravan/blob/7f298c63b5d839b23e5094f8209bc6d5d24f9f03/caravan/commands/base.py#L25-L33
rapidpro/dash
dash/orgs/middleware.py
SetOrgMiddleware.set_language
def set_language(self, request, org): """Set the current language from the org configuration.""" if org: lang = org.language or settings.DEFAULT_LANGUAGE translation.activate(lang)
python
def set_language(self, request, org): """Set the current language from the org configuration.""" if org: lang = org.language or settings.DEFAULT_LANGUAGE translation.activate(lang)
[ "def", "set_language", "(", "self", ",", "request", ",", "org", ")", ":", "if", "org", ":", "lang", "=", "org", ".", "language", "or", "settings", ".", "DEFAULT_LANGUAGE", "translation", ".", "activate", "(", "lang", ")" ]
Set the current language from the org configuration.
[ "Set", "the", "current", "language", "from", "the", "org", "configuration", "." ]
train
https://github.com/rapidpro/dash/blob/e9dc05b31b86fe3fe72e956975d1ee0a275ac016/dash/orgs/middleware.py#L89-L93
rapidpro/dash
dash/orgs/middleware.py
SetOrgMiddleware.set_timezone
def set_timezone(self, request, org): """Set the current timezone from the org configuration.""" if org and org.timezone: timezone.activate(org.timezone)
python
def set_timezone(self, request, org): """Set the current timezone from the org configuration.""" if org and org.timezone: timezone.activate(org.timezone)
[ "def", "set_timezone", "(", "self", ",", "request", ",", "org", ")", ":", "if", "org", "and", "org", ".", "timezone", ":", "timezone", ".", "activate", "(", "org", ".", "timezone", ")" ]
Set the current timezone from the org configuration.
[ "Set", "the", "current", "timezone", "from", "the", "org", "configuration", "." ]
train
https://github.com/rapidpro/dash/blob/e9dc05b31b86fe3fe72e956975d1ee0a275ac016/dash/orgs/middleware.py#L95-L98
HDI-Project/RDT
rdt/transformers/null.py
NullTransformer.transform
def transform(self, col): """Prepare the transformer to convert data and return the processed table. Args: col(pandas.DataFrame): Data to transform. Returns: pandas.DataFrame """ out = pd.DataFrame(index=col.index) out[self.col_name] = col.fillna(self.default_value) out[self.new_name] = (pd.notnull(col) * 1).astype(int) return out
python
def transform(self, col): """Prepare the transformer to convert data and return the processed table. Args: col(pandas.DataFrame): Data to transform. Returns: pandas.DataFrame """ out = pd.DataFrame(index=col.index) out[self.col_name] = col.fillna(self.default_value) out[self.new_name] = (pd.notnull(col) * 1).astype(int) return out
[ "def", "transform", "(", "self", ",", "col", ")", ":", "out", "=", "pd", ".", "DataFrame", "(", "index", "=", "col", ".", "index", ")", "out", "[", "self", ".", "col_name", "]", "=", "col", ".", "fillna", "(", "self", ".", "default_value", ")", "...
Prepare the transformer to convert data and return the processed table. Args: col(pandas.DataFrame): Data to transform. Returns: pandas.DataFrame
[ "Prepare", "the", "transformer", "to", "convert", "data", "and", "return", "the", "processed", "table", "." ]
train
https://github.com/HDI-Project/RDT/blob/b28fdd671a1d7fbd14983eefe0cfbd8d87ded92a/rdt/transformers/null.py#L33-L45
HDI-Project/RDT
rdt/transformers/null.py
NullTransformer.reverse_transform
def reverse_transform(self, col): """Converts data back into original format. Args: col(pandas.DataFrame): Data to transform. Returns: pandas.DataFrame """ output = pd.DataFrame() new_name = '?' + self.col_name col.loc[col[new_name] == 0, self.col_name] = np.nan output[self.col_name] = col[self.col_name] return output
python
def reverse_transform(self, col): """Converts data back into original format. Args: col(pandas.DataFrame): Data to transform. Returns: pandas.DataFrame """ output = pd.DataFrame() new_name = '?' + self.col_name col.loc[col[new_name] == 0, self.col_name] = np.nan output[self.col_name] = col[self.col_name] return output
[ "def", "reverse_transform", "(", "self", ",", "col", ")", ":", "output", "=", "pd", ".", "DataFrame", "(", ")", "new_name", "=", "'?'", "+", "self", ".", "col_name", "col", ".", "loc", "[", "col", "[", "new_name", "]", "==", "0", ",", "self", ".", ...
Converts data back into original format. Args: col(pandas.DataFrame): Data to transform. Returns: pandas.DataFrame
[ "Converts", "data", "back", "into", "original", "format", "." ]
train
https://github.com/HDI-Project/RDT/blob/b28fdd671a1d7fbd14983eefe0cfbd8d87ded92a/rdt/transformers/null.py#L47-L61
fake-name/WebRequest
WebRequest/Captcha/PunchPort.py
_is_private_ip
def _is_private_ip(ip): """ Taken from https://stackoverflow.com/a/39656628/268006 Check if the IP belongs to private network blocks. @param ip: IP address to verify. @return: boolean representing whether the IP belongs or not to a private network block. """ networks = [ "0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "127.0.0.0/8", "169.254.0.0/16", "172.16.0.0/12", "192.0.0.0/24", "192.0.2.0/24", "192.88.99.0/24", "192.168.0.0/16", "198.18.0.0/15", "198.51.100.0/24", "203.0.113.0/24", "240.0.0.0/4", "255.255.255.255/32", "224.0.0.0/4", ] for network in networks: try: ipaddr = struct.unpack(">I", socket.inet_aton(ip))[0] netaddr, bits = network.split("/") network_low = struct.unpack(">I", socket.inet_aton(netaddr))[0] network_high = network_low | 1 << (32 - int(bits)) - 1 if ipaddr <= network_high and ipaddr >= network_low: return True except Exception: continue return False
python
def _is_private_ip(ip): """ Taken from https://stackoverflow.com/a/39656628/268006 Check if the IP belongs to private network blocks. @param ip: IP address to verify. @return: boolean representing whether the IP belongs or not to a private network block. """ networks = [ "0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "127.0.0.0/8", "169.254.0.0/16", "172.16.0.0/12", "192.0.0.0/24", "192.0.2.0/24", "192.88.99.0/24", "192.168.0.0/16", "198.18.0.0/15", "198.51.100.0/24", "203.0.113.0/24", "240.0.0.0/4", "255.255.255.255/32", "224.0.0.0/4", ] for network in networks: try: ipaddr = struct.unpack(">I", socket.inet_aton(ip))[0] netaddr, bits = network.split("/") network_low = struct.unpack(">I", socket.inet_aton(netaddr))[0] network_high = network_low | 1 << (32 - int(bits)) - 1 if ipaddr <= network_high and ipaddr >= network_low: return True except Exception: continue return False
[ "def", "_is_private_ip", "(", "ip", ")", ":", "networks", "=", "[", "\"0.0.0.0/8\"", ",", "\"10.0.0.0/8\"", ",", "\"100.64.0.0/10\"", ",", "\"127.0.0.0/8\"", ",", "\"169.254.0.0/16\"", ",", "\"172.16.0.0/12\"", ",", "\"192.0.0.0/24\"", ",", "\"192.0.2.0/24\"", ",", ...
Taken from https://stackoverflow.com/a/39656628/268006 Check if the IP belongs to private network blocks. @param ip: IP address to verify. @return: boolean representing whether the IP belongs or not to a private network block.
[ "Taken", "from", "https", ":", "//", "stackoverflow", ".", "com", "/", "a", "/", "39656628", "/", "268006" ]
train
https://github.com/fake-name/WebRequest/blob/b6c94631ff88b5f81f26a9f99a2d5c706810b11f/WebRequest/Captcha/PunchPort.py#L9-L51
Contraz/pyrocket
rocket/tracks.py
TrackContainer.add
def add(self, obj): """ Add pre-created tracks. If the tracks are already created, we hijack the data. This way the pointer to the pre-created tracks are still valid. """ obj.controller = self.controller # Is the track already loaded or created? track = self.tracks.get(obj.name) if track: if track == obj: return # hijack the track data obj.keys = track.keys obj.controller = track.controller self.tracks[track.name] = obj self.track_index[self.track_index.index(track)] = obj else: # Add a new track obj.controller = self.controller self.tracks[obj.name] = obj self.track_index.append(obj)
python
def add(self, obj): """ Add pre-created tracks. If the tracks are already created, we hijack the data. This way the pointer to the pre-created tracks are still valid. """ obj.controller = self.controller # Is the track already loaded or created? track = self.tracks.get(obj.name) if track: if track == obj: return # hijack the track data obj.keys = track.keys obj.controller = track.controller self.tracks[track.name] = obj self.track_index[self.track_index.index(track)] = obj else: # Add a new track obj.controller = self.controller self.tracks[obj.name] = obj self.track_index.append(obj)
[ "def", "add", "(", "self", ",", "obj", ")", ":", "obj", ".", "controller", "=", "self", ".", "controller", "# Is the track already loaded or created?", "track", "=", "self", ".", "tracks", ".", "get", "(", "obj", ".", "name", ")", "if", "track", ":", "if...
Add pre-created tracks. If the tracks are already created, we hijack the data. This way the pointer to the pre-created tracks are still valid.
[ "Add", "pre", "-", "created", "tracks", ".", "If", "the", "tracks", "are", "already", "created", "we", "hijack", "the", "data", ".", "This", "way", "the", "pointer", "to", "the", "pre", "-", "created", "tracks", "are", "still", "valid", "." ]
train
https://github.com/Contraz/pyrocket/blob/97f4153c79030497b97fbaf43b1aa6dc1a6c7f7b/rocket/tracks.py#L39-L60
Contraz/pyrocket
rocket/tracks.py
Track.row_value
def row_value(self, row): """Get the tracks value at row""" irow = int(row) i = self._get_key_index(irow) if i == -1: return 0.0 # Are we dealing with the last key? if i == len(self.keys) - 1: return self.keys[-1].value return TrackKey.interpolate(self.keys[i], self.keys[i + 1], row)
python
def row_value(self, row): """Get the tracks value at row""" irow = int(row) i = self._get_key_index(irow) if i == -1: return 0.0 # Are we dealing with the last key? if i == len(self.keys) - 1: return self.keys[-1].value return TrackKey.interpolate(self.keys[i], self.keys[i + 1], row)
[ "def", "row_value", "(", "self", ",", "row", ")", ":", "irow", "=", "int", "(", "row", ")", "i", "=", "self", ".", "_get_key_index", "(", "irow", ")", "if", "i", "==", "-", "1", ":", "return", "0.0", "# Are we dealing with the last key?", "if", "i", ...
Get the tracks value at row
[ "Get", "the", "tracks", "value", "at", "row" ]
train
https://github.com/Contraz/pyrocket/blob/97f4153c79030497b97fbaf43b1aa6dc1a6c7f7b/rocket/tracks.py#L88-L99
Contraz/pyrocket
rocket/tracks.py
Track.add_or_update
def add_or_update(self, row, value, kind): """Add or update a track value""" i = bisect.bisect_left(self.keys, row) # Are we simply replacing a key? if i < len(self.keys) and self.keys[i].row == row: self.keys[i].update(value, kind) else: self.keys.insert(i, TrackKey(row, value, kind))
python
def add_or_update(self, row, value, kind): """Add or update a track value""" i = bisect.bisect_left(self.keys, row) # Are we simply replacing a key? if i < len(self.keys) and self.keys[i].row == row: self.keys[i].update(value, kind) else: self.keys.insert(i, TrackKey(row, value, kind))
[ "def", "add_or_update", "(", "self", ",", "row", ",", "value", ",", "kind", ")", ":", "i", "=", "bisect", ".", "bisect_left", "(", "self", ".", "keys", ",", "row", ")", "# Are we simply replacing a key?", "if", "i", "<", "len", "(", "self", ".", "keys"...
Add or update a track value
[ "Add", "or", "update", "a", "track", "value" ]
train
https://github.com/Contraz/pyrocket/blob/97f4153c79030497b97fbaf43b1aa6dc1a6c7f7b/rocket/tracks.py#L101-L109
Contraz/pyrocket
rocket/tracks.py
Track.delete
def delete(self, row): """Delete a track value""" i = self._get_key_index(row) del self.keys[i]
python
def delete(self, row): """Delete a track value""" i = self._get_key_index(row) del self.keys[i]
[ "def", "delete", "(", "self", ",", "row", ")", ":", "i", "=", "self", ".", "_get_key_index", "(", "row", ")", "del", "self", ".", "keys", "[", "i", "]" ]
Delete a track value
[ "Delete", "a", "track", "value" ]
train
https://github.com/Contraz/pyrocket/blob/97f4153c79030497b97fbaf43b1aa6dc1a6c7f7b/rocket/tracks.py#L111-L114
Contraz/pyrocket
rocket/tracks.py
Track._get_key_index
def _get_key_index(self, row): """Get the key that should be used as the first interpolation value""" # Don't bother with empty tracks if len(self.keys) == 0: return -1 # No track values are defined yet if row < self.keys[0].row: return -1 # Get the insertion index index = bisect.bisect_left(self.keys, row) # Index is within the array size? if index < len(self.keys): # Are we inside an interval? if row < self.keys[index].row: return index - 1 return index # Return the last index return len(self.keys) - 1
python
def _get_key_index(self, row): """Get the key that should be used as the first interpolation value""" # Don't bother with empty tracks if len(self.keys) == 0: return -1 # No track values are defined yet if row < self.keys[0].row: return -1 # Get the insertion index index = bisect.bisect_left(self.keys, row) # Index is within the array size? if index < len(self.keys): # Are we inside an interval? if row < self.keys[index].row: return index - 1 return index # Return the last index return len(self.keys) - 1
[ "def", "_get_key_index", "(", "self", ",", "row", ")", ":", "# Don't bother with empty tracks", "if", "len", "(", "self", ".", "keys", ")", "==", "0", ":", "return", "-", "1", "# No track values are defined yet", "if", "row", "<", "self", ".", "keys", "[", ...
Get the key that should be used as the first interpolation value
[ "Get", "the", "key", "that", "should", "be", "used", "as", "the", "first", "interpolation", "value" ]
train
https://github.com/Contraz/pyrocket/blob/97f4153c79030497b97fbaf43b1aa6dc1a6c7f7b/rocket/tracks.py#L116-L136
Contraz/pyrocket
rocket/tracks.py
Track.load
def load(self, filepath): """Load the track file""" with open(filepath, 'rb') as fd: num_keys = struct.unpack(">i", fd.read(4))[0] for i in range(num_keys): row, value, kind = struct.unpack('>ifb', fd.read(9)) self.keys.append(TrackKey(row, value, kind))
python
def load(self, filepath): """Load the track file""" with open(filepath, 'rb') as fd: num_keys = struct.unpack(">i", fd.read(4))[0] for i in range(num_keys): row, value, kind = struct.unpack('>ifb', fd.read(9)) self.keys.append(TrackKey(row, value, kind))
[ "def", "load", "(", "self", ",", "filepath", ")", ":", "with", "open", "(", "filepath", ",", "'rb'", ")", "as", "fd", ":", "num_keys", "=", "struct", ".", "unpack", "(", "\">i\"", ",", "fd", ".", "read", "(", "4", ")", ")", "[", "0", "]", "for"...
Load the track file
[ "Load", "the", "track", "file" ]
train
https://github.com/Contraz/pyrocket/blob/97f4153c79030497b97fbaf43b1aa6dc1a6c7f7b/rocket/tracks.py#L148-L154
Contraz/pyrocket
rocket/tracks.py
Track.save
def save(self, path): """Save the track""" name = Track.filename(self.name) with open(os.path.join(path, name), 'wb') as fd: fd.write(struct.pack('>I', len(self.keys))) for k in self.keys: fd.write(struct.pack('>ifb', k.row, k.value, k.kind))
python
def save(self, path): """Save the track""" name = Track.filename(self.name) with open(os.path.join(path, name), 'wb') as fd: fd.write(struct.pack('>I', len(self.keys))) for k in self.keys: fd.write(struct.pack('>ifb', k.row, k.value, k.kind))
[ "def", "save", "(", "self", ",", "path", ")", ":", "name", "=", "Track", ".", "filename", "(", "self", ".", "name", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "path", ",", "name", ")", ",", "'wb'", ")", "as", "fd", ":", "f...
Save the track
[ "Save", "the", "track" ]
train
https://github.com/Contraz/pyrocket/blob/97f4153c79030497b97fbaf43b1aa6dc1a6c7f7b/rocket/tracks.py#L156-L162
fake-name/WebRequest
WebRequest/iri2uri.py
iri2uri
def iri2uri(uri): """Convert an IRI to a URI. Note that IRIs must be passed in a unicode strings. That is, do not utf-8 encode the IRI before passing it into the function.""" assert uri != None, 'iri2uri must be passed a non-none string!' original = uri if isinstance(uri ,str): (scheme, authority, path, query, fragment) = urllib.parse.urlsplit(uri) authority = authority.encode('idna').decode('utf-8') # For each character in 'ucschar' or 'iprivate' # 1. encode as utf-8 # 2. then %-encode each octet of that utf-8 # path = urllib.parse.quote(path) uri = urllib.parse.urlunsplit((scheme, authority, path, query, fragment)) uri = "".join([encode(c) for c in uri]) # urllib.parse.urlunsplit(urllib.parse.urlsplit({something}) # strips any trailing "?" chars. While this may be legal according to the # spec, it breaks some services. Therefore, we patch # the "?" back in if it has been removed. if original.endswith("?") and not uri.endswith("?"): uri = uri+"?" return uri
python
def iri2uri(uri): """Convert an IRI to a URI. Note that IRIs must be passed in a unicode strings. That is, do not utf-8 encode the IRI before passing it into the function.""" assert uri != None, 'iri2uri must be passed a non-none string!' original = uri if isinstance(uri ,str): (scheme, authority, path, query, fragment) = urllib.parse.urlsplit(uri) authority = authority.encode('idna').decode('utf-8') # For each character in 'ucschar' or 'iprivate' # 1. encode as utf-8 # 2. then %-encode each octet of that utf-8 # path = urllib.parse.quote(path) uri = urllib.parse.urlunsplit((scheme, authority, path, query, fragment)) uri = "".join([encode(c) for c in uri]) # urllib.parse.urlunsplit(urllib.parse.urlsplit({something}) # strips any trailing "?" chars. While this may be legal according to the # spec, it breaks some services. Therefore, we patch # the "?" back in if it has been removed. if original.endswith("?") and not uri.endswith("?"): uri = uri+"?" return uri
[ "def", "iri2uri", "(", "uri", ")", ":", "assert", "uri", "!=", "None", ",", "'iri2uri must be passed a non-none string!'", "original", "=", "uri", "if", "isinstance", "(", "uri", ",", "str", ")", ":", "(", "scheme", ",", "authority", ",", "path", ",", "que...
Convert an IRI to a URI. Note that IRIs must be passed in a unicode strings. That is, do not utf-8 encode the IRI before passing it into the function.
[ "Convert", "an", "IRI", "to", "a", "URI", ".", "Note", "that", "IRIs", "must", "be", "passed", "in", "a", "unicode", "strings", ".", "That", "is", "do", "not", "utf", "-", "8", "encode", "the", "IRI", "before", "passing", "it", "into", "the", "functi...
train
https://github.com/fake-name/WebRequest/blob/b6c94631ff88b5f81f26a9f99a2d5c706810b11f/WebRequest/iri2uri.py#L51-L75
bdastur/spam
pyansible/ansirunner.py
AnsibleRunner.validate_host_parameters
def validate_host_parameters(self, host_list, remote_user): ''' Validate and set the host list and remote user parameters. ''' if host_list is None: host_list = self.host_list if remote_user is None: remote_user = self.remote_user if host_list is None or remote_user is None: print "Host list [%s], remote user [%s] are required" % \ (host_list, remote_user) return (None, None) return (host_list, remote_user)
python
def validate_host_parameters(self, host_list, remote_user): ''' Validate and set the host list and remote user parameters. ''' if host_list is None: host_list = self.host_list if remote_user is None: remote_user = self.remote_user if host_list is None or remote_user is None: print "Host list [%s], remote user [%s] are required" % \ (host_list, remote_user) return (None, None) return (host_list, remote_user)
[ "def", "validate_host_parameters", "(", "self", ",", "host_list", ",", "remote_user", ")", ":", "if", "host_list", "is", "None", ":", "host_list", "=", "self", ".", "host_list", "if", "remote_user", "is", "None", ":", "remote_user", "=", "self", ".", "remote...
Validate and set the host list and remote user parameters.
[ "Validate", "and", "set", "the", "host", "list", "and", "remote", "user", "parameters", "." ]
train
https://github.com/bdastur/spam/blob/3c363302412d15bdb391f62bf90348243e456af2/pyansible/ansirunner.py#L27-L42
bdastur/spam
pyansible/ansirunner.py
AnsibleRunner.validate_results
def validate_results(self, results, checks=None): ''' Valdiate results from the Anisble Run. ''' results['status'] = 'PASS' failed_hosts = [] ################################################### # First validation is to make sure connectivity to # all the hosts was ok. ################################################### if results['dark']: print "Host connectivity issues on %s", results['dark'].keys() failed_hosts.append(results['dark'].keys()) results['status'] = 'FAIL' ################################################## # Now look for status 'failed' ################################################## for node in results['contacted'].keys(): if 'failed' in results['contacted'][node]: if results['contacted'][node]['failed'] is True: results['status'] = 'FAIL' ################################################# # Check for the return code 'rc' for each host. ################################################# for node in results['contacted'].keys(): rc = results['contacted'][node].get('rc', None) if rc is not None and rc != 0: print "Operation 'return code' %s on host %s" % \ (results['contacted'][node]['rc'], node) failed_hosts.append(node) results['status'] = 'FAIL' ################################################## # Additional checks. If passed is a list of key/value # pairs that should be matched. ################################################## if checks is None: #print "No additional checks validated" return results, failed_hosts for check in checks: key = check.keys()[0] value = check.values()[0] for node in results['contacted'].keys(): if key in results['contacted'][node].keys(): if results['contacted'][node][key] != value: failed_hosts.append(node) results['status'] = 'FAIL' return (results, failed_hosts)
python
def validate_results(self, results, checks=None): ''' Valdiate results from the Anisble Run. ''' results['status'] = 'PASS' failed_hosts = [] ################################################### # First validation is to make sure connectivity to # all the hosts was ok. ################################################### if results['dark']: print "Host connectivity issues on %s", results['dark'].keys() failed_hosts.append(results['dark'].keys()) results['status'] = 'FAIL' ################################################## # Now look for status 'failed' ################################################## for node in results['contacted'].keys(): if 'failed' in results['contacted'][node]: if results['contacted'][node]['failed'] is True: results['status'] = 'FAIL' ################################################# # Check for the return code 'rc' for each host. ################################################# for node in results['contacted'].keys(): rc = results['contacted'][node].get('rc', None) if rc is not None and rc != 0: print "Operation 'return code' %s on host %s" % \ (results['contacted'][node]['rc'], node) failed_hosts.append(node) results['status'] = 'FAIL' ################################################## # Additional checks. If passed is a list of key/value # pairs that should be matched. ################################################## if checks is None: #print "No additional checks validated" return results, failed_hosts for check in checks: key = check.keys()[0] value = check.values()[0] for node in results['contacted'].keys(): if key in results['contacted'][node].keys(): if results['contacted'][node][key] != value: failed_hosts.append(node) results['status'] = 'FAIL' return (results, failed_hosts)
[ "def", "validate_results", "(", "self", ",", "results", ",", "checks", "=", "None", ")", ":", "results", "[", "'status'", "]", "=", "'PASS'", "failed_hosts", "=", "[", "]", "###################################################", "# First validation is to make sure connec...
Valdiate results from the Anisble Run.
[ "Valdiate", "results", "from", "the", "Anisble", "Run", "." ]
train
https://github.com/bdastur/spam/blob/3c363302412d15bdb391f62bf90348243e456af2/pyansible/ansirunner.py#L44-L97
bdastur/spam
pyansible/ansirunner.py
AnsibleRunner.ansible_perform_operation
def ansible_perform_operation(self, host_list=None, remote_user=None, remote_pass=None, module=None, complex_args=None, module_args='', environment=None, check=False, sudo=False, sudo_user=None, sudo_pass=None, forks=20): ''' Perform any ansible operation. ''' (host_list, remote_user) = \ self.validate_host_parameters(host_list, remote_user) if (host_list, remote_user) is (None, None): return None if module is None: print "ANSIBLE Perform operation: No module specified" return None runner = ansible.runner.Runner( module_name=module, host_list=host_list, remote_user=remote_user, remote_pass=remote_pass, module_args=module_args, complex_args=complex_args, environment=environment, check=check, become=sudo, become_user=sudo_user, become_pass=sudo_pass, forks=forks) results = runner.run() results, failed_hosts = self.validate_results(results) if results['status'] != 'PASS': print "ANSIBLE: [%s] operation failed [%s] [hosts: %s]" % \ (module, complex_args, failed_hosts) return results, failed_hosts
python
def ansible_perform_operation(self, host_list=None, remote_user=None, remote_pass=None, module=None, complex_args=None, module_args='', environment=None, check=False, sudo=False, sudo_user=None, sudo_pass=None, forks=20): ''' Perform any ansible operation. ''' (host_list, remote_user) = \ self.validate_host_parameters(host_list, remote_user) if (host_list, remote_user) is (None, None): return None if module is None: print "ANSIBLE Perform operation: No module specified" return None runner = ansible.runner.Runner( module_name=module, host_list=host_list, remote_user=remote_user, remote_pass=remote_pass, module_args=module_args, complex_args=complex_args, environment=environment, check=check, become=sudo, become_user=sudo_user, become_pass=sudo_pass, forks=forks) results = runner.run() results, failed_hosts = self.validate_results(results) if results['status'] != 'PASS': print "ANSIBLE: [%s] operation failed [%s] [hosts: %s]" % \ (module, complex_args, failed_hosts) return results, failed_hosts
[ "def", "ansible_perform_operation", "(", "self", ",", "host_list", "=", "None", ",", "remote_user", "=", "None", ",", "remote_pass", "=", "None", ",", "module", "=", "None", ",", "complex_args", "=", "None", ",", "module_args", "=", "''", ",", "environment",...
Perform any ansible operation.
[ "Perform", "any", "ansible", "operation", "." ]
train
https://github.com/bdastur/spam/blob/3c363302412d15bdb391f62bf90348243e456af2/pyansible/ansirunner.py#L99-L145
vint21h/django-po2xls
po2xls/utils.py
PoToXls.header
def header(self, sheet, name): """ Write sheet header. Args: sheet: (xlwt.Worksheet.Worksheet) instance of xlwt sheet. name: (unicode) name of sheet. """ header = sheet.row(0) for i, column in enumerate(self.headers[name]): header.write(i, self.headers[name][i])
python
def header(self, sheet, name): """ Write sheet header. Args: sheet: (xlwt.Worksheet.Worksheet) instance of xlwt sheet. name: (unicode) name of sheet. """ header = sheet.row(0) for i, column in enumerate(self.headers[name]): header.write(i, self.headers[name][i])
[ "def", "header", "(", "self", ",", "sheet", ",", "name", ")", ":", "header", "=", "sheet", ".", "row", "(", "0", ")", "for", "i", ",", "column", "in", "enumerate", "(", "self", ".", "headers", "[", "name", "]", ")", ":", "header", ".", "write", ...
Write sheet header. Args: sheet: (xlwt.Worksheet.Worksheet) instance of xlwt sheet. name: (unicode) name of sheet.
[ "Write", "sheet", "header", ".", "Args", ":", "sheet", ":", "(", "xlwt", ".", "Worksheet", ".", "Worksheet", ")", "instance", "of", "xlwt", "sheet", ".", "name", ":", "(", "unicode", ")", "name", "of", "sheet", "." ]
train
https://github.com/vint21h/django-po2xls/blob/e76d26cfae6d9e5ca95ff053d05a00f875875019/po2xls/utils.py#L54-L64
vint21h/django-po2xls
po2xls/utils.py
PoToXls.output
def output(self): """ Create full path for excel file to save parsed translations strings. Returns: unicode: full path for excel file to save parsed translations strings. """ path, src = os.path.split(self.src) src, ext = os.path.splitext(src) return os.path.join(path, "{src}.xls".format(**{"src": src, }))
python
def output(self): """ Create full path for excel file to save parsed translations strings. Returns: unicode: full path for excel file to save parsed translations strings. """ path, src = os.path.split(self.src) src, ext = os.path.splitext(src) return os.path.join(path, "{src}.xls".format(**{"src": src, }))
[ "def", "output", "(", "self", ")", ":", "path", ",", "src", "=", "os", ".", "path", ".", "split", "(", "self", ".", "src", ")", "src", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "src", ")", "return", "os", ".", "path", ".", "jo...
Create full path for excel file to save parsed translations strings. Returns: unicode: full path for excel file to save parsed translations strings.
[ "Create", "full", "path", "for", "excel", "file", "to", "save", "parsed", "translations", "strings", ".", "Returns", ":", "unicode", ":", "full", "path", "for", "excel", "file", "to", "save", "parsed", "translations", "strings", "." ]
train
https://github.com/vint21h/django-po2xls/blob/e76d26cfae6d9e5ca95ff053d05a00f875875019/po2xls/utils.py#L66-L76
vint21h/django-po2xls
po2xls/utils.py
PoToXls.strings
def strings(self): """ Write strings sheet. """ sheet = self.result.add_sheet("strings") self.header(sheet, "strings") n_row = 1 # row number for entry in self.po: row = sheet.row(n_row) row.write(0, entry.msgid) row.write(1, entry.msgstr) n_row += 1 sheet.flush_row_data()
python
def strings(self): """ Write strings sheet. """ sheet = self.result.add_sheet("strings") self.header(sheet, "strings") n_row = 1 # row number for entry in self.po: row = sheet.row(n_row) row.write(0, entry.msgid) row.write(1, entry.msgstr) n_row += 1 sheet.flush_row_data()
[ "def", "strings", "(", "self", ")", ":", "sheet", "=", "self", ".", "result", ".", "add_sheet", "(", "\"strings\"", ")", "self", ".", "header", "(", "sheet", ",", "\"strings\"", ")", "n_row", "=", "1", "# row number", "for", "entry", "in", "self", ".",...
Write strings sheet.
[ "Write", "strings", "sheet", "." ]
train
https://github.com/vint21h/django-po2xls/blob/e76d26cfae6d9e5ca95ff053d05a00f875875019/po2xls/utils.py#L78-L93
vint21h/django-po2xls
po2xls/utils.py
PoToXls.metadata
def metadata(self): """ Write metadata sheet. """ sheet = self.result.add_sheet("metadata") self.header(sheet, "metadata") n_row = 1 # row number for k in self.po.metadata: row = sheet.row(n_row) row.write(0, k) row.write(1, self.po.metadata[k]) n_row += 1 sheet.flush_row_data()
python
def metadata(self): """ Write metadata sheet. """ sheet = self.result.add_sheet("metadata") self.header(sheet, "metadata") n_row = 1 # row number for k in self.po.metadata: row = sheet.row(n_row) row.write(0, k) row.write(1, self.po.metadata[k]) n_row += 1 sheet.flush_row_data()
[ "def", "metadata", "(", "self", ")", ":", "sheet", "=", "self", ".", "result", ".", "add_sheet", "(", "\"metadata\"", ")", "self", ".", "header", "(", "sheet", ",", "\"metadata\"", ")", "n_row", "=", "1", "# row number", "for", "k", "in", "self", ".", ...
Write metadata sheet.
[ "Write", "metadata", "sheet", "." ]
train
https://github.com/vint21h/django-po2xls/blob/e76d26cfae6d9e5ca95ff053d05a00f875875019/po2xls/utils.py#L95-L110
vint21h/django-po2xls
po2xls/utils.py
PoToXls.convert
def convert(self, *args, **kwargs): """ Yes it is, thanks captain. """ self.strings() self.metadata() # save file self.result.save(self.output())
python
def convert(self, *args, **kwargs): """ Yes it is, thanks captain. """ self.strings() self.metadata() # save file self.result.save(self.output())
[ "def", "convert", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "strings", "(", ")", "self", ".", "metadata", "(", ")", "# save file", "self", ".", "result", ".", "save", "(", "self", ".", "output", "(", ")", ")" ...
Yes it is, thanks captain.
[ "Yes", "it", "is", "thanks", "captain", "." ]
train
https://github.com/vint21h/django-po2xls/blob/e76d26cfae6d9e5ca95ff053d05a00f875875019/po2xls/utils.py#L112-L121
brbsix/pip-utils
pip_utils/cli.py
_parser
def _parser(): """Parse command-line options.""" launcher = 'pip%s-utils' % sys.version_info.major parser = argparse.ArgumentParser( description='%s.' % __description__, epilog='See `%s COMMAND --help` for help ' 'on a specific subcommand.' % launcher, prog=launcher) parser.add_argument( '--version', action='version', version='%(prog)s ' + __version__) subparsers = parser.add_subparsers() # dependants parser_dependants = subparsers.add_parser( 'dependants', add_help=False, help='list dependants of package') parser_dependants.add_argument( 'package', metavar='PACKAGE', type=_distribution) parser_dependants.add_argument( '-h', '--help', action='help', help=argparse.SUPPRESS) parser_dependants.set_defaults( func=command_dependants) # dependents parser_dependents = subparsers.add_parser( 'dependents', add_help=False, help='list dependents of package') parser_dependents.add_argument( 'package', metavar='PACKAGE', type=_distribution) parser_dependents.add_argument( '-i', '--info', action='store_true', help='show version requirements') parser_dependents.add_argument( '-r', '--recursive', action='store_true', help='list dependencies recursively') parser_dependents.add_argument( '-h', '--help', action='help', help=argparse.SUPPRESS) parser_dependents.set_defaults( func=command_dependents) # locate parser_locate = subparsers.add_parser( 'locate', add_help=False, help='identify packages that file belongs to') parser_locate.add_argument( 'file', metavar='FILE', type=argparse.FileType('r')) parser_locate.add_argument( '-h', '--help', action='help', help=argparse.SUPPRESS) parser_locate.set_defaults( func=command_locate) # outdated parser_outdated = subparsers.add_parser( 'outdated', add_help=False, help='list outdated packages that may be updated') parser_outdated.add_argument( '-b', '--brief', action='store_true', help='show package name only') group = parser_outdated.add_mutually_exclusive_group() group.add_argument( '-a', '--all', action='store_true', help='list all outdated packages') group.add_argument( '-p', '--pinned', action='store_true', help='list outdated packages unable to be updated') group.add_argument( '-U', '--upgrade', action='store_true', dest='update', help='update packages that can be updated' ) parser_outdated.add_argument( '-h', '--help', action='help', help=argparse.SUPPRESS) parser_outdated.set_defaults( func=command_outdated) # parents parser_parents = subparsers.add_parser( 'parents', add_help=False, help='list packages lacking dependants') parser_parents.add_argument( '-h', '--help', action='help', help=argparse.SUPPRESS) parser_parents.set_defaults( func=command_parents) return parser
python
def _parser(): """Parse command-line options.""" launcher = 'pip%s-utils' % sys.version_info.major parser = argparse.ArgumentParser( description='%s.' % __description__, epilog='See `%s COMMAND --help` for help ' 'on a specific subcommand.' % launcher, prog=launcher) parser.add_argument( '--version', action='version', version='%(prog)s ' + __version__) subparsers = parser.add_subparsers() # dependants parser_dependants = subparsers.add_parser( 'dependants', add_help=False, help='list dependants of package') parser_dependants.add_argument( 'package', metavar='PACKAGE', type=_distribution) parser_dependants.add_argument( '-h', '--help', action='help', help=argparse.SUPPRESS) parser_dependants.set_defaults( func=command_dependants) # dependents parser_dependents = subparsers.add_parser( 'dependents', add_help=False, help='list dependents of package') parser_dependents.add_argument( 'package', metavar='PACKAGE', type=_distribution) parser_dependents.add_argument( '-i', '--info', action='store_true', help='show version requirements') parser_dependents.add_argument( '-r', '--recursive', action='store_true', help='list dependencies recursively') parser_dependents.add_argument( '-h', '--help', action='help', help=argparse.SUPPRESS) parser_dependents.set_defaults( func=command_dependents) # locate parser_locate = subparsers.add_parser( 'locate', add_help=False, help='identify packages that file belongs to') parser_locate.add_argument( 'file', metavar='FILE', type=argparse.FileType('r')) parser_locate.add_argument( '-h', '--help', action='help', help=argparse.SUPPRESS) parser_locate.set_defaults( func=command_locate) # outdated parser_outdated = subparsers.add_parser( 'outdated', add_help=False, help='list outdated packages that may be updated') parser_outdated.add_argument( '-b', '--brief', action='store_true', help='show package name only') group = parser_outdated.add_mutually_exclusive_group() group.add_argument( '-a', '--all', action='store_true', help='list all outdated packages') group.add_argument( '-p', '--pinned', action='store_true', help='list outdated packages unable to be updated') group.add_argument( '-U', '--upgrade', action='store_true', dest='update', help='update packages that can be updated' ) parser_outdated.add_argument( '-h', '--help', action='help', help=argparse.SUPPRESS) parser_outdated.set_defaults( func=command_outdated) # parents parser_parents = subparsers.add_parser( 'parents', add_help=False, help='list packages lacking dependants') parser_parents.add_argument( '-h', '--help', action='help', help=argparse.SUPPRESS) parser_parents.set_defaults( func=command_parents) return parser
[ "def", "_parser", "(", ")", ":", "launcher", "=", "'pip%s-utils'", "%", "sys", ".", "version_info", ".", "major", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'%s.'", "%", "__description__", ",", "epilog", "=", "'See `%s COMMAND ...
Parse command-line options.
[ "Parse", "command", "-", "line", "options", "." ]
train
https://github.com/brbsix/pip-utils/blob/bdd2a0a17cf36a1c88aa9e68002e9ed04a27bad8/pip_utils/cli.py#L31-L146
brbsix/pip-utils
pip_utils/cli.py
main
def main(args=None): """Start application.""" parser = _parser() # Python 2 will error 'too few arguments' if no subcommand is supplied. # No such error occurs in Python 3, which makes it feasible to check # whether a subcommand was provided (displaying a help message if not). # argparse internals vary significantly over the major versions, so it's # much easier to just override the args passed to it. In this case, print # the usage message if there are no args. if args is None and len(sys.argv) <= 1: sys.argv.append('--help') options = parser.parse_args(args) # pass options to subcommand options.func(options) return 0
python
def main(args=None): """Start application.""" parser = _parser() # Python 2 will error 'too few arguments' if no subcommand is supplied. # No such error occurs in Python 3, which makes it feasible to check # whether a subcommand was provided (displaying a help message if not). # argparse internals vary significantly over the major versions, so it's # much easier to just override the args passed to it. In this case, print # the usage message if there are no args. if args is None and len(sys.argv) <= 1: sys.argv.append('--help') options = parser.parse_args(args) # pass options to subcommand options.func(options) return 0
[ "def", "main", "(", "args", "=", "None", ")", ":", "parser", "=", "_parser", "(", ")", "# Python 2 will error 'too few arguments' if no subcommand is supplied.", "# No such error occurs in Python 3, which makes it feasible to check", "# whether a subcommand was provided (displaying a h...
Start application.
[ "Start", "application", "." ]
train
https://github.com/brbsix/pip-utils/blob/bdd2a0a17cf36a1c88aa9e68002e9ed04a27bad8/pip_utils/cli.py#L149-L167
rapidpro/dash
dash/utils/sync.py
sync_from_remote
def sync_from_remote(org, syncer, remote): """ Sync local instance against a single remote object :param * org: the org :param * syncer: the local model syncer :param * remote: the remote object :return: the outcome (created, updated or deleted) """ identity = syncer.identify_remote(remote) with syncer.lock(org, identity): existing = syncer.fetch_local(org, identity) # derive kwargs for the local model (none return here means don't keep) remote_as_kwargs = syncer.local_kwargs(org, remote) # exists locally if existing: existing.org = org # saves pre-fetching since we already have the org if remote_as_kwargs: if syncer.update_required(existing, remote, remote_as_kwargs) or not existing.is_active: for field, value in remote_as_kwargs.items(): setattr(existing, field, value) existing.is_active = True existing.save() return SyncOutcome.updated elif existing.is_active: # exists locally, but shouldn't now to due to model changes syncer.delete_local(existing) return SyncOutcome.deleted elif remote_as_kwargs: syncer.model.objects.create(**remote_as_kwargs) return SyncOutcome.created return SyncOutcome.ignored
python
def sync_from_remote(org, syncer, remote): """ Sync local instance against a single remote object :param * org: the org :param * syncer: the local model syncer :param * remote: the remote object :return: the outcome (created, updated or deleted) """ identity = syncer.identify_remote(remote) with syncer.lock(org, identity): existing = syncer.fetch_local(org, identity) # derive kwargs for the local model (none return here means don't keep) remote_as_kwargs = syncer.local_kwargs(org, remote) # exists locally if existing: existing.org = org # saves pre-fetching since we already have the org if remote_as_kwargs: if syncer.update_required(existing, remote, remote_as_kwargs) or not existing.is_active: for field, value in remote_as_kwargs.items(): setattr(existing, field, value) existing.is_active = True existing.save() return SyncOutcome.updated elif existing.is_active: # exists locally, but shouldn't now to due to model changes syncer.delete_local(existing) return SyncOutcome.deleted elif remote_as_kwargs: syncer.model.objects.create(**remote_as_kwargs) return SyncOutcome.created return SyncOutcome.ignored
[ "def", "sync_from_remote", "(", "org", ",", "syncer", ",", "remote", ")", ":", "identity", "=", "syncer", ".", "identify_remote", "(", "remote", ")", "with", "syncer", ".", "lock", "(", "org", ",", "identity", ")", ":", "existing", "=", "syncer", ".", ...
Sync local instance against a single remote object :param * org: the org :param * syncer: the local model syncer :param * remote: the remote object :return: the outcome (created, updated or deleted)
[ "Sync", "local", "instance", "against", "a", "single", "remote", "object" ]
train
https://github.com/rapidpro/dash/blob/e9dc05b31b86fe3fe72e956975d1ee0a275ac016/dash/utils/sync.py#L117-L155
rapidpro/dash
dash/utils/sync.py
sync_local_to_set
def sync_local_to_set(org, syncer, remote_set): """ Syncs an org's set of local instances of a model to match the set of remote objects. Local objects not in the remote set are deleted. :param org: the org :param * syncer: the local model syncer :param remote_set: the set of remote objects :return: tuple of number of local objects created, updated, deleted and ignored """ outcome_counts = defaultdict(int) remote_identities = set() for remote in remote_set: outcome = sync_from_remote(org, syncer, remote) outcome_counts[outcome] += 1 remote_identities.add(syncer.identify_remote(remote)) # active local objects which weren't in the remote set need to be deleted active_locals = syncer.fetch_all(org).filter(is_active=True) delete_locals = active_locals.exclude(**{syncer.local_id_attr + "__in": remote_identities}) for local in delete_locals: with syncer.lock(org, syncer.identify_local(local)): syncer.delete_local(local) outcome_counts[SyncOutcome.deleted] += 1 return ( outcome_counts[SyncOutcome.created], outcome_counts[SyncOutcome.updated], outcome_counts[SyncOutcome.deleted], outcome_counts[SyncOutcome.ignored], )
python
def sync_local_to_set(org, syncer, remote_set): """ Syncs an org's set of local instances of a model to match the set of remote objects. Local objects not in the remote set are deleted. :param org: the org :param * syncer: the local model syncer :param remote_set: the set of remote objects :return: tuple of number of local objects created, updated, deleted and ignored """ outcome_counts = defaultdict(int) remote_identities = set() for remote in remote_set: outcome = sync_from_remote(org, syncer, remote) outcome_counts[outcome] += 1 remote_identities.add(syncer.identify_remote(remote)) # active local objects which weren't in the remote set need to be deleted active_locals = syncer.fetch_all(org).filter(is_active=True) delete_locals = active_locals.exclude(**{syncer.local_id_attr + "__in": remote_identities}) for local in delete_locals: with syncer.lock(org, syncer.identify_local(local)): syncer.delete_local(local) outcome_counts[SyncOutcome.deleted] += 1 return ( outcome_counts[SyncOutcome.created], outcome_counts[SyncOutcome.updated], outcome_counts[SyncOutcome.deleted], outcome_counts[SyncOutcome.ignored], )
[ "def", "sync_local_to_set", "(", "org", ",", "syncer", ",", "remote_set", ")", ":", "outcome_counts", "=", "defaultdict", "(", "int", ")", "remote_identities", "=", "set", "(", ")", "for", "remote", "in", "remote_set", ":", "outcome", "=", "sync_from_remote", ...
Syncs an org's set of local instances of a model to match the set of remote objects. Local objects not in the remote set are deleted. :param org: the org :param * syncer: the local model syncer :param remote_set: the set of remote objects :return: tuple of number of local objects created, updated, deleted and ignored
[ "Syncs", "an", "org", "s", "set", "of", "local", "instances", "of", "a", "model", "to", "match", "the", "set", "of", "remote", "objects", ".", "Local", "objects", "not", "in", "the", "remote", "set", "are", "deleted", "." ]
train
https://github.com/rapidpro/dash/blob/e9dc05b31b86fe3fe72e956975d1ee0a275ac016/dash/utils/sync.py#L158-L192
rapidpro/dash
dash/utils/sync.py
sync_local_to_changes
def sync_local_to_changes(org, syncer, fetches, deleted_fetches, progress_callback=None): """ Sync local instances against iterators which return fetches of changed and deleted remote objects. :param * org: the org :param * syncer: the local model syncer :param * fetches: an iterator returning fetches of modified remote objects :param * deleted_fetches: an iterator returning fetches of deleted remote objects :param * progress_callback: callable for tracking progress - called for each fetch with number of contacts fetched :return: tuple containing counts of created, updated and deleted local instances """ num_synced = 0 outcome_counts = defaultdict(int) for fetch in fetches: for remote in fetch: outcome = sync_from_remote(org, syncer, remote) outcome_counts[outcome] += 1 num_synced += len(fetch) if progress_callback: progress_callback(num_synced) # any item that has been deleted remotely should also be released locally for deleted_fetch in deleted_fetches: for deleted_remote in deleted_fetch: identity = syncer.identify_remote(deleted_remote) with syncer.lock(org, identity): existing = syncer.fetch_local(org, identity) if existing: syncer.delete_local(existing) outcome_counts[SyncOutcome.deleted] += 1 num_synced += len(deleted_fetch) if progress_callback: progress_callback(num_synced) return ( outcome_counts[SyncOutcome.created], outcome_counts[SyncOutcome.updated], outcome_counts[SyncOutcome.deleted], outcome_counts[SyncOutcome.ignored], )
python
def sync_local_to_changes(org, syncer, fetches, deleted_fetches, progress_callback=None): """ Sync local instances against iterators which return fetches of changed and deleted remote objects. :param * org: the org :param * syncer: the local model syncer :param * fetches: an iterator returning fetches of modified remote objects :param * deleted_fetches: an iterator returning fetches of deleted remote objects :param * progress_callback: callable for tracking progress - called for each fetch with number of contacts fetched :return: tuple containing counts of created, updated and deleted local instances """ num_synced = 0 outcome_counts = defaultdict(int) for fetch in fetches: for remote in fetch: outcome = sync_from_remote(org, syncer, remote) outcome_counts[outcome] += 1 num_synced += len(fetch) if progress_callback: progress_callback(num_synced) # any item that has been deleted remotely should also be released locally for deleted_fetch in deleted_fetches: for deleted_remote in deleted_fetch: identity = syncer.identify_remote(deleted_remote) with syncer.lock(org, identity): existing = syncer.fetch_local(org, identity) if existing: syncer.delete_local(existing) outcome_counts[SyncOutcome.deleted] += 1 num_synced += len(deleted_fetch) if progress_callback: progress_callback(num_synced) return ( outcome_counts[SyncOutcome.created], outcome_counts[SyncOutcome.updated], outcome_counts[SyncOutcome.deleted], outcome_counts[SyncOutcome.ignored], )
[ "def", "sync_local_to_changes", "(", "org", ",", "syncer", ",", "fetches", ",", "deleted_fetches", ",", "progress_callback", "=", "None", ")", ":", "num_synced", "=", "0", "outcome_counts", "=", "defaultdict", "(", "int", ")", "for", "fetch", "in", "fetches", ...
Sync local instances against iterators which return fetches of changed and deleted remote objects. :param * org: the org :param * syncer: the local model syncer :param * fetches: an iterator returning fetches of modified remote objects :param * deleted_fetches: an iterator returning fetches of deleted remote objects :param * progress_callback: callable for tracking progress - called for each fetch with number of contacts fetched :return: tuple containing counts of created, updated and deleted local instances
[ "Sync", "local", "instances", "against", "iterators", "which", "return", "fetches", "of", "changed", "and", "deleted", "remote", "objects", "." ]
train
https://github.com/rapidpro/dash/blob/e9dc05b31b86fe3fe72e956975d1ee0a275ac016/dash/utils/sync.py#L195-L237
rapidpro/dash
dash/utils/sync.py
BaseSyncer.fetch_local
def fetch_local(self, org, identity): """ Fetches the local model instance with the given identity, returning none if it doesn't exist :param org: the org :param identity: the unique identity :return: the instance or none """ qs = self.fetch_all(org=org).filter(**{self.local_id_attr: identity}) if self.select_related: qs = qs.select_related(*self.select_related) if self.prefetch_related: qs = qs.prefetch_related(*self.prefetch_related) return qs.first()
python
def fetch_local(self, org, identity): """ Fetches the local model instance with the given identity, returning none if it doesn't exist :param org: the org :param identity: the unique identity :return: the instance or none """ qs = self.fetch_all(org=org).filter(**{self.local_id_attr: identity}) if self.select_related: qs = qs.select_related(*self.select_related) if self.prefetch_related: qs = qs.prefetch_related(*self.prefetch_related) return qs.first()
[ "def", "fetch_local", "(", "self", ",", "org", ",", "identity", ")", ":", "qs", "=", "self", ".", "fetch_all", "(", "org", "=", "org", ")", ".", "filter", "(", "*", "*", "{", "self", ".", "local_id_attr", ":", "identity", "}", ")", "if", "self", ...
Fetches the local model instance with the given identity, returning none if it doesn't exist :param org: the org :param identity: the unique identity :return: the instance or none
[ "Fetches", "the", "local", "model", "instance", "with", "the", "given", "identity", "returning", "none", "if", "it", "doesn", "t", "exist", ":", "param", "org", ":", "the", "org", ":", "param", "identity", ":", "the", "unique", "identity", ":", "return", ...
train
https://github.com/rapidpro/dash/blob/e9dc05b31b86fe3fe72e956975d1ee0a275ac016/dash/utils/sync.py#L58-L72
rapidpro/dash
dash/utils/sync.py
BaseSyncer.fetch_all
def fetch_all(self, org): """ Fetches all local objects :param org: the org :return: the queryset """ qs = self.model.objects.filter(org=org) if self.local_backend_attr is not None: qs = qs.filter(**{self.local_backend_attr: self.backend}) return qs
python
def fetch_all(self, org): """ Fetches all local objects :param org: the org :return: the queryset """ qs = self.model.objects.filter(org=org) if self.local_backend_attr is not None: qs = qs.filter(**{self.local_backend_attr: self.backend}) return qs
[ "def", "fetch_all", "(", "self", ",", "org", ")", ":", "qs", "=", "self", ".", "model", ".", "objects", ".", "filter", "(", "org", "=", "org", ")", "if", "self", ".", "local_backend_attr", "is", "not", "None", ":", "qs", "=", "qs", ".", "filter", ...
Fetches all local objects :param org: the org :return: the queryset
[ "Fetches", "all", "local", "objects", ":", "param", "org", ":", "the", "org", ":", "return", ":", "the", "queryset" ]
train
https://github.com/rapidpro/dash/blob/e9dc05b31b86fe3fe72e956975d1ee0a275ac016/dash/utils/sync.py#L74-L83
archman/pyrpn
pyrpn/rpn.py
Rpn.fsto
def fsto(self): """sto operation. """ a = float(self.tmpopslist.pop()) var = self.opslist.pop() if isinstance(var, basestring): self.variables.update({var: a}) return a else: print("Can only sto into a variable.") return 'ERROR'
python
def fsto(self): """sto operation. """ a = float(self.tmpopslist.pop()) var = self.opslist.pop() if isinstance(var, basestring): self.variables.update({var: a}) return a else: print("Can only sto into a variable.") return 'ERROR'
[ "def", "fsto", "(", "self", ")", ":", "a", "=", "float", "(", "self", ".", "tmpopslist", ".", "pop", "(", ")", ")", "var", "=", "self", ".", "opslist", ".", "pop", "(", ")", "if", "isinstance", "(", "var", ",", "basestring", ")", ":", "self", "...
sto operation.
[ "sto", "operation", "." ]
train
https://github.com/archman/pyrpn/blob/fee706fccee1aa5c527f3f4221cc6b0d69bdde2c/pyrpn/rpn.py#L111-L121
archman/pyrpn
pyrpn/rpn.py
Rpn.solve
def solve(self): """Solve rpn expression, return None if not valid.""" popflag = True self.tmpopslist = [] while True: while self.opslist and popflag: op = self.opslist.pop() if self.is_variable(op): op = self.variables.get(op) if self.is_operator(op): popflag = False break self.tmpopslist.append(op) # operations tmpr = self._get_temp_result(op) if tmpr == 'ERROR': return None if tmpr is not None: self.opslist.append('{r:.20f}'.format(r=tmpr)) if len(self.tmpopslist) > 0 or len(self.opslist) > 1: popflag = True else: break return float(self.opslist[0])
python
def solve(self): """Solve rpn expression, return None if not valid.""" popflag = True self.tmpopslist = [] while True: while self.opslist and popflag: op = self.opslist.pop() if self.is_variable(op): op = self.variables.get(op) if self.is_operator(op): popflag = False break self.tmpopslist.append(op) # operations tmpr = self._get_temp_result(op) if tmpr == 'ERROR': return None if tmpr is not None: self.opslist.append('{r:.20f}'.format(r=tmpr)) if len(self.tmpopslist) > 0 or len(self.opslist) > 1: popflag = True else: break return float(self.opslist[0])
[ "def", "solve", "(", "self", ")", ":", "popflag", "=", "True", "self", ".", "tmpopslist", "=", "[", "]", "while", "True", ":", "while", "self", ".", "opslist", "and", "popflag", ":", "op", "=", "self", ".", "opslist", ".", "pop", "(", ")", "if", ...
Solve rpn expression, return None if not valid.
[ "Solve", "rpn", "expression", "return", "None", "if", "not", "valid", "." ]
train
https://github.com/archman/pyrpn/blob/fee706fccee1aa5c527f3f4221cc6b0d69bdde2c/pyrpn/rpn.py#L144-L171
etalab/cada
cada/search.py
build_sort
def build_sort(): '''Build sort query paramter from kwargs''' sorts = request.args.getlist('sort') sorts = [sorts] if isinstance(sorts, basestring) else sorts sorts = [s.split(' ') for s in sorts] return [{SORTS[s]: d} for s, d in sorts if s in SORTS]
python
def build_sort(): '''Build sort query paramter from kwargs''' sorts = request.args.getlist('sort') sorts = [sorts] if isinstance(sorts, basestring) else sorts sorts = [s.split(' ') for s in sorts] return [{SORTS[s]: d} for s, d in sorts if s in SORTS]
[ "def", "build_sort", "(", ")", ":", "sorts", "=", "request", ".", "args", ".", "getlist", "(", "'sort'", ")", "sorts", "=", "[", "sorts", "]", "if", "isinstance", "(", "sorts", ",", "basestring", ")", "else", "sorts", "sorts", "=", "[", "s", ".", "...
Build sort query paramter from kwargs
[ "Build", "sort", "query", "paramter", "from", "kwargs" ]
train
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/search.py#L183-L188
etalab/cada
cada/search.py
index
def index(advice): '''Index/Reindex a CADA advice''' topics = [] for topic in advice.topics: topics.append(topic) parts = topic.split('/') if len(parts) > 1: topics.append(parts[0]) try: es.index(index=es.index_name, doc_type=DOCTYPE, id=advice.id, body={ 'id': advice.id, 'administration': advice.administration, 'type': advice.type, 'session': advice.session.strftime('%Y-%m-%d'), 'subject': advice.subject, 'topics': topics, 'tags': advice.tags, 'meanings': advice.meanings, 'part': advice.part, 'content': advice.content, }) except Exception: log.exception('Unable to index advice %s', advice.id)
python
def index(advice): '''Index/Reindex a CADA advice''' topics = [] for topic in advice.topics: topics.append(topic) parts = topic.split('/') if len(parts) > 1: topics.append(parts[0]) try: es.index(index=es.index_name, doc_type=DOCTYPE, id=advice.id, body={ 'id': advice.id, 'administration': advice.administration, 'type': advice.type, 'session': advice.session.strftime('%Y-%m-%d'), 'subject': advice.subject, 'topics': topics, 'tags': advice.tags, 'meanings': advice.meanings, 'part': advice.part, 'content': advice.content, }) except Exception: log.exception('Unable to index advice %s', advice.id)
[ "def", "index", "(", "advice", ")", ":", "topics", "=", "[", "]", "for", "topic", "in", "advice", ".", "topics", ":", "topics", ".", "append", "(", "topic", ")", "parts", "=", "topic", ".", "split", "(", "'/'", ")", "if", "len", "(", "parts", ")"...
Index/Reindex a CADA advice
[ "Index", "/", "Reindex", "a", "CADA", "advice" ]
train
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/search.py#L278-L301
etalab/cada
cada/search.py
ElasticSearch.initialize
def initialize(self): '''Create or update indices and mappings''' if es.indices.exists(self.index_name): es.indices.put_mapping(index=self.index_name, doc_type=DOCTYPE, body=MAPPING) else: es.indices.create(self.index_name, { 'mappings': {'advice': MAPPING}, 'settings': {'analysis': ANALSYS}, })
python
def initialize(self): '''Create or update indices and mappings''' if es.indices.exists(self.index_name): es.indices.put_mapping(index=self.index_name, doc_type=DOCTYPE, body=MAPPING) else: es.indices.create(self.index_name, { 'mappings': {'advice': MAPPING}, 'settings': {'analysis': ANALSYS}, })
[ "def", "initialize", "(", "self", ")", ":", "if", "es", ".", "indices", ".", "exists", "(", "self", ".", "index_name", ")", ":", "es", ".", "indices", ".", "put_mapping", "(", "index", "=", "self", ".", "index_name", ",", "doc_type", "=", "DOCTYPE", ...
Create or update indices and mappings
[ "Create", "or", "update", "indices", "and", "mappings" ]
train
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/search.py#L130-L138
APSL/transmanager
transmanager/templatetags/transmanager_tags.py
show_list_translations
def show_list_translations(context, item): """ Return the widget to select the translations we want to order or delete from the item it's being edited :param context: :param item: :return: """ if not item: return manager = Manager() manager.set_master(item) ct_item = ContentType.objects.get_for_model(item) item_language_codes = manager.get_languages_from_item(ct_item, item) model_language_codes = manager.get_languages_from_model(ct_item.app_label, ct_item.model) item_languages = [{'lang': lang, 'from_model': lang.code in model_language_codes} for lang in TransLanguage.objects.filter(code__in=item_language_codes).order_by('name')] more_languages = [{'lang': lang, 'from_model': lang.code in model_language_codes} for lang in TransLanguage.objects.exclude(main_language=True).order_by('name')] return render_to_string('languages/translation_language_selector.html', { 'item_languages': item_languages, 'more_languages': more_languages, 'api_url': TM_API_URL, 'app_label': manager.app_label, 'model': manager.model_label, 'object_pk': item.pk })
python
def show_list_translations(context, item): """ Return the widget to select the translations we want to order or delete from the item it's being edited :param context: :param item: :return: """ if not item: return manager = Manager() manager.set_master(item) ct_item = ContentType.objects.get_for_model(item) item_language_codes = manager.get_languages_from_item(ct_item, item) model_language_codes = manager.get_languages_from_model(ct_item.app_label, ct_item.model) item_languages = [{'lang': lang, 'from_model': lang.code in model_language_codes} for lang in TransLanguage.objects.filter(code__in=item_language_codes).order_by('name')] more_languages = [{'lang': lang, 'from_model': lang.code in model_language_codes} for lang in TransLanguage.objects.exclude(main_language=True).order_by('name')] return render_to_string('languages/translation_language_selector.html', { 'item_languages': item_languages, 'more_languages': more_languages, 'api_url': TM_API_URL, 'app_label': manager.app_label, 'model': manager.model_label, 'object_pk': item.pk })
[ "def", "show_list_translations", "(", "context", ",", "item", ")", ":", "if", "not", "item", ":", "return", "manager", "=", "Manager", "(", ")", "manager", ".", "set_master", "(", "item", ")", "ct_item", "=", "ContentType", ".", "objects", ".", "get_for_mo...
Return the widget to select the translations we want to order or delete from the item it's being edited :param context: :param item: :return:
[ "Return", "the", "widget", "to", "select", "the", "translations", "we", "want", "to", "order", "or", "delete", "from", "the", "item", "it", "s", "being", "edited" ]
train
https://github.com/APSL/transmanager/blob/79157085840008e146b264521681913090197ed1/transmanager/templatetags/transmanager_tags.py#L17-L50
josuebrunel/myql
myql/contrib/table/table.py
Table._xml_pretty_print
def _xml_pretty_print(self, data): """Pretty print xml data """ raw_string = xtree.tostring(data, 'utf-8') parsed_string = minidom.parseString(raw_string) return parsed_string.toprettyxml(indent='\t')
python
def _xml_pretty_print(self, data): """Pretty print xml data """ raw_string = xtree.tostring(data, 'utf-8') parsed_string = minidom.parseString(raw_string) return parsed_string.toprettyxml(indent='\t')
[ "def", "_xml_pretty_print", "(", "self", ",", "data", ")", ":", "raw_string", "=", "xtree", ".", "tostring", "(", "data", ",", "'utf-8'", ")", "parsed_string", "=", "minidom", ".", "parseString", "(", "raw_string", ")", "return", "parsed_string", ".", "topre...
Pretty print xml data
[ "Pretty", "print", "xml", "data" ]
train
https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/contrib/table/table.py#L33-L38
josuebrunel/myql
myql/contrib/table/table.py
Table._create_table_xml_file
def _create_table_xml_file(self, data, fname=None): """Creates a xml file of the table """ content = self._xml_pretty_print(data) if not fname: fname = self.name with open(fname+".xml", 'w') as f: f.write(content)
python
def _create_table_xml_file(self, data, fname=None): """Creates a xml file of the table """ content = self._xml_pretty_print(data) if not fname: fname = self.name with open(fname+".xml", 'w') as f: f.write(content)
[ "def", "_create_table_xml_file", "(", "self", ",", "data", ",", "fname", "=", "None", ")", ":", "content", "=", "self", ".", "_xml_pretty_print", "(", "data", ")", "if", "not", "fname", ":", "fname", "=", "self", ".", "name", "with", "open", "(", "fnam...
Creates a xml file of the table
[ "Creates", "a", "xml", "file", "of", "the", "table" ]
train
https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/contrib/table/table.py#L40-L47
josuebrunel/myql
myql/contrib/table/table.py
Table._init_table_elementTree
def _init_table_elementTree(self, xml=True, db_table=True): """Create a table """ # <table> tag object t_table = xtree.Element('table') # <table xmlns='' securityLevel='' htpps=''> if not self.table_attr : self.table_attr = self._TAB_ATTR for attr in self.table_attr.items() : t_table.set(*attr) # <meta> t_meta = xtree.SubElement(t_table, 'meta') # Loop over a sorted key,value of class attributes while ignoring table_attr and name for key, value in [(k,v) for k,v in sorted(self.__dict__.items(), key=lambda x: x[0]) if k not in ('table_attr','name') ]: if isinstance(value, list): # Works for element like sampleQuery for elt in value: t_tag = xtree.SubElement(t_meta, key) # setting attribute name as a tag name t_tag.text = elt # Setting attribute value as text else: t_tag = xtree.SubElement(t_meta,key) t_tag.text = value ## <bindings> t_bindings = xtree.SubElement(t_table, 'bindings') ## self.etree = t_table return t_table
python
def _init_table_elementTree(self, xml=True, db_table=True): """Create a table """ # <table> tag object t_table = xtree.Element('table') # <table xmlns='' securityLevel='' htpps=''> if not self.table_attr : self.table_attr = self._TAB_ATTR for attr in self.table_attr.items() : t_table.set(*attr) # <meta> t_meta = xtree.SubElement(t_table, 'meta') # Loop over a sorted key,value of class attributes while ignoring table_attr and name for key, value in [(k,v) for k,v in sorted(self.__dict__.items(), key=lambda x: x[0]) if k not in ('table_attr','name') ]: if isinstance(value, list): # Works for element like sampleQuery for elt in value: t_tag = xtree.SubElement(t_meta, key) # setting attribute name as a tag name t_tag.text = elt # Setting attribute value as text else: t_tag = xtree.SubElement(t_meta,key) t_tag.text = value ## <bindings> t_bindings = xtree.SubElement(t_table, 'bindings') ## self.etree = t_table return t_table
[ "def", "_init_table_elementTree", "(", "self", ",", "xml", "=", "True", ",", "db_table", "=", "True", ")", ":", "# <table> tag object", "t_table", "=", "xtree", ".", "Element", "(", "'table'", ")", "# <table xmlns='' securityLevel='' htpps=''>", "if", "not", "self...
Create a table
[ "Create", "a", "table" ]
train
https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/contrib/table/table.py#L49-L78
josuebrunel/myql
myql/contrib/table/table.py
Table.save
def save(self, name=None, path=None): """Save file as xml """ if path : name = os.path.join(path,name) try: self._create_table_xml_file(self.etree, name) except (Exception,) as e: print(e) return False return True
python
def save(self, name=None, path=None): """Save file as xml """ if path : name = os.path.join(path,name) try: self._create_table_xml_file(self.etree, name) except (Exception,) as e: print(e) return False return True
[ "def", "save", "(", "self", ",", "name", "=", "None", ",", "path", "=", "None", ")", ":", "if", "path", ":", "name", "=", "os", ".", "path", ".", "join", "(", "path", ",", "name", ")", "try", ":", "self", ".", "_create_table_xml_file", "(", "self...
Save file as xml
[ "Save", "file", "as", "xml" ]
train
https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/contrib/table/table.py#L80-L92
josuebrunel/myql
myql/contrib/table/table.py
Table.addBinder
def addBinder(self, binder): """Adds a binder to the file """ root = self.etree bindings = root.find('bindings') bindings.append(binder.etree) return True
python
def addBinder(self, binder): """Adds a binder to the file """ root = self.etree bindings = root.find('bindings') bindings.append(binder.etree) return True
[ "def", "addBinder", "(", "self", ",", "binder", ")", ":", "root", "=", "self", ".", "etree", "bindings", "=", "root", ".", "find", "(", "'bindings'", ")", "bindings", ".", "append", "(", "binder", ".", "etree", ")", "return", "True" ]
Adds a binder to the file
[ "Adds", "a", "binder", "to", "the", "file" ]
train
https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/contrib/table/table.py#L94-L101
josuebrunel/myql
myql/contrib/table/table.py
Table.removeBinder
def removeBinder(self, name): """Remove a binder from a table """ root = self.etree t_bindings = root.find('bindings') t_binder = t_bindings.find(name) if t_binder : t_bindings.remove(t_binder) return True return False
python
def removeBinder(self, name): """Remove a binder from a table """ root = self.etree t_bindings = root.find('bindings') t_binder = t_bindings.find(name) if t_binder : t_bindings.remove(t_binder) return True return False
[ "def", "removeBinder", "(", "self", ",", "name", ")", ":", "root", "=", "self", ".", "etree", "t_bindings", "=", "root", ".", "find", "(", "'bindings'", ")", "t_binder", "=", "t_bindings", ".", "find", "(", "name", ")", "if", "t_binder", ":", "t_bindin...
Remove a binder from a table
[ "Remove", "a", "binder", "from", "a", "table" ]
train
https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/contrib/table/table.py#L103-L116
rapidpro/dash
dash/utils/templatetags/utils.py
if_url
def if_url(context, url_name, yes, no): """ Example: %li{ class:"{% if_url 'contacts.contact_read' 'active' '' %}" } """ current = context["request"].resolver_match.url_name return yes if url_name == current else no
python
def if_url(context, url_name, yes, no): """ Example: %li{ class:"{% if_url 'contacts.contact_read' 'active' '' %}" } """ current = context["request"].resolver_match.url_name return yes if url_name == current else no
[ "def", "if_url", "(", "context", ",", "url_name", ",", "yes", ",", "no", ")", ":", "current", "=", "context", "[", "\"request\"", "]", ".", "resolver_match", ".", "url_name", "return", "yes", "if", "url_name", "==", "current", "else", "no" ]
Example: %li{ class:"{% if_url 'contacts.contact_read' 'active' '' %}" }
[ "Example", ":", "%li", "{", "class", ":", "{", "%", "if_url", "contacts", ".", "contact_read", "active", "%", "}", "}" ]
train
https://github.com/rapidpro/dash/blob/e9dc05b31b86fe3fe72e956975d1ee0a275ac016/dash/utils/templatetags/utils.py#L7-L13
raphaelgyory/django-rest-messaging-centrifugo
rest_messaging_centrifugo/views.py
CentrifugoAuthentication.post
def post(self, request, *args, **kwargs): """ Returns a token identifying the user in Centrifugo. """ current_timestamp = "%.0f" % time.time() user_id_str = u"{0}".format(request.user.id) token = generate_token(settings.CENTRIFUGE_SECRET, user_id_str, "{0}".format(current_timestamp), info="") # we get all the channels to which the user can subscribe participant = Participant.objects.get(id=request.user.id) # we use the threads as channels ids channels = [] for thread in Thread.managers.get_threads_where_participant_is_active(participant_id=participant.id): channels.append( build_channel(settings.CENTRIFUGO_MESSAGE_NAMESPACE, thread.id, thread.participants.all()) ) # we also have a channel to alert us about new threads threads_channel = build_channel(settings.CENTRIFUGO_THREAD_NAMESPACE, request.user.id, [request.user.id]) # he is the only one to have access to the channel channels.append(threads_channel) # we return the information to_return = { 'user': user_id_str, 'timestamp': current_timestamp, 'token': token, 'connection_url': "{0}connection/".format(settings.CENTRIFUGE_ADDRESS), 'channels': channels, 'debug': settings.DEBUG, } return HttpResponse(json.dumps(to_return), content_type='application/json; charset=utf-8')
python
def post(self, request, *args, **kwargs): """ Returns a token identifying the user in Centrifugo. """ current_timestamp = "%.0f" % time.time() user_id_str = u"{0}".format(request.user.id) token = generate_token(settings.CENTRIFUGE_SECRET, user_id_str, "{0}".format(current_timestamp), info="") # we get all the channels to which the user can subscribe participant = Participant.objects.get(id=request.user.id) # we use the threads as channels ids channels = [] for thread in Thread.managers.get_threads_where_participant_is_active(participant_id=participant.id): channels.append( build_channel(settings.CENTRIFUGO_MESSAGE_NAMESPACE, thread.id, thread.participants.all()) ) # we also have a channel to alert us about new threads threads_channel = build_channel(settings.CENTRIFUGO_THREAD_NAMESPACE, request.user.id, [request.user.id]) # he is the only one to have access to the channel channels.append(threads_channel) # we return the information to_return = { 'user': user_id_str, 'timestamp': current_timestamp, 'token': token, 'connection_url': "{0}connection/".format(settings.CENTRIFUGE_ADDRESS), 'channels': channels, 'debug': settings.DEBUG, } return HttpResponse(json.dumps(to_return), content_type='application/json; charset=utf-8')
[ "def", "post", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "current_timestamp", "=", "\"%.0f\"", "%", "time", ".", "time", "(", ")", "user_id_str", "=", "u\"{0}\"", ".", "format", "(", "request", ".", "user", "."...
Returns a token identifying the user in Centrifugo.
[ "Returns", "a", "token", "identifying", "the", "user", "in", "Centrifugo", "." ]
train
https://github.com/raphaelgyory/django-rest-messaging-centrifugo/blob/f44022cd9fc83e84ab573fe8a8385c85f6e77380/rest_messaging_centrifugo/views.py#L26-L59
APSL/transmanager
transmanager/search_indexes.py
TransTaskIndex.index_queryset
def index_queryset(self, using=None): """ Used when the entire index for model is updated. """ return self.get_model().objects.filter(date_creation__lte=datetime.datetime.now())
python
def index_queryset(self, using=None): """ Used when the entire index for model is updated. """ return self.get_model().objects.filter(date_creation__lte=datetime.datetime.now())
[ "def", "index_queryset", "(", "self", ",", "using", "=", "None", ")", ":", "return", "self", ".", "get_model", "(", ")", ".", "objects", ".", "filter", "(", "date_creation__lte", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ")" ]
Used when the entire index for model is updated.
[ "Used", "when", "the", "entire", "index", "for", "model", "is", "updated", "." ]
train
https://github.com/APSL/transmanager/blob/79157085840008e146b264521681913090197ed1/transmanager/search_indexes.py#L17-L21
josuebrunel/myql
myql/contrib/table/base.py
Base.addFunction
def addFunction(self, func_code, from_file=''): """Add function """ if from_file: with open(from_file) as f: func_code = f.read() root = self.etree t_execute = root.find('execute') if not t_execute : t_execute = ctree.SubElement(root, 'execute') t_execute.text = "\n\t![CDATA]{0:>5}]]\n\t".format(func_code.ljust(4)) return True
python
def addFunction(self, func_code, from_file=''): """Add function """ if from_file: with open(from_file) as f: func_code = f.read() root = self.etree t_execute = root.find('execute') if not t_execute : t_execute = ctree.SubElement(root, 'execute') t_execute.text = "\n\t![CDATA]{0:>5}]]\n\t".format(func_code.ljust(4)) return True
[ "def", "addFunction", "(", "self", ",", "func_code", ",", "from_file", "=", "''", ")", ":", "if", "from_file", ":", "with", "open", "(", "from_file", ")", "as", "f", ":", "func_code", "=", "f", ".", "read", "(", ")", "root", "=", "self", ".", "etre...
Add function
[ "Add", "function" ]
train
https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/contrib/table/base.py#L5-L20
josuebrunel/myql
myql/contrib/table/base.py
Base.removeFunction
def removeFunction(self): """Remove function tag """ root = self.etree t_execute = root.find('execute') try: root.remove(t_execute) return True except (Exception,) as e: print(e) return False
python
def removeFunction(self): """Remove function tag """ root = self.etree t_execute = root.find('execute') try: root.remove(t_execute) return True except (Exception,) as e: print(e) return False
[ "def", "removeFunction", "(", "self", ")", ":", "root", "=", "self", ".", "etree", "t_execute", "=", "root", ".", "find", "(", "'execute'", ")", "try", ":", "root", ".", "remove", "(", "t_execute", ")", "return", "True", "except", "(", "Exception", ","...
Remove function tag
[ "Remove", "function", "tag" ]
train
https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/contrib/table/base.py#L22-L33
josuebrunel/myql
myql/contrib/table/base.py
BaseBinder._buildElementTree
def _buildElementTree(self,): """Turns object into a Element Tree """ t_binder = ctree.Element(self.name) for k,v in self.__dict__.items(): if k not in ('name', 'urls', 'inputs', 'paging') and v : t_binder.set(k,v) self.etree = t_binder return t_binder
python
def _buildElementTree(self,): """Turns object into a Element Tree """ t_binder = ctree.Element(self.name) for k,v in self.__dict__.items(): if k not in ('name', 'urls', 'inputs', 'paging') and v : t_binder.set(k,v) self.etree = t_binder return t_binder
[ "def", "_buildElementTree", "(", "self", ",", ")", ":", "t_binder", "=", "ctree", ".", "Element", "(", "self", ".", "name", ")", "for", "k", ",", "v", "in", "self", ".", "__dict__", ".", "items", "(", ")", ":", "if", "k", "not", "in", "(", "'name...
Turns object into a Element Tree
[ "Turns", "object", "into", "a", "Element", "Tree" ]
train
https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/contrib/table/base.py#L56-L66
josuebrunel/myql
myql/contrib/table/base.py
BaseBinder.addUrl
def addUrl(self, url): """Add url to binder """ if url not in self.urls: self.urls.append(url) root = self.etree t_urls = root.find('urls') if not t_urls: t_urls = ctree.SubElement(root, 'urls') t_url = ctree.SubElement(t_urls, 'url') t_url.text = url return True
python
def addUrl(self, url): """Add url to binder """ if url not in self.urls: self.urls.append(url) root = self.etree t_urls = root.find('urls') if not t_urls: t_urls = ctree.SubElement(root, 'urls') t_url = ctree.SubElement(t_urls, 'url') t_url.text = url return True
[ "def", "addUrl", "(", "self", ",", "url", ")", ":", "if", "url", "not", "in", "self", ".", "urls", ":", "self", ".", "urls", ".", "append", "(", "url", ")", "root", "=", "self", ".", "etree", "t_urls", "=", "root", ".", "find", "(", "'urls'", "...
Add url to binder
[ "Add", "url", "to", "binder" ]
train
https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/contrib/table/base.py#L68-L84
josuebrunel/myql
myql/contrib/table/base.py
BaseBinder.removeUrl
def removeUrl(self, url): """Remove passed url from a binder """ root = self.etree t_urls = root.find('urls') if not t_urls: return False for t_url in t_urls.findall('url'): if t_url.text == url.strip(): t_urls.remove(t_url) if url in self.urls: self.urls.remove(url) return True return False
python
def removeUrl(self, url): """Remove passed url from a binder """ root = self.etree t_urls = root.find('urls') if not t_urls: return False for t_url in t_urls.findall('url'): if t_url.text == url.strip(): t_urls.remove(t_url) if url in self.urls: self.urls.remove(url) return True return False
[ "def", "removeUrl", "(", "self", ",", "url", ")", ":", "root", "=", "self", ".", "etree", "t_urls", "=", "root", ".", "find", "(", "'urls'", ")", "if", "not", "t_urls", ":", "return", "False", "for", "t_url", "in", "t_urls", ".", "findall", "(", "'...
Remove passed url from a binder
[ "Remove", "passed", "url", "from", "a", "binder" ]
train
https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/contrib/table/base.py#L86-L103
josuebrunel/myql
myql/contrib/table/base.py
BaseBinder.addInput
def addInput(self, key): """Add key to input : key, value or map """ if key not in self.inputs: self.inputs.append(key) root = self.etree t_inputs = root.find('inputs') if not t_inputs : t_inputs = ctree.SubElement(root, 'inputs') t_inputs.append(key.etree) return True
python
def addInput(self, key): """Add key to input : key, value or map """ if key not in self.inputs: self.inputs.append(key) root = self.etree t_inputs = root.find('inputs') if not t_inputs : t_inputs = ctree.SubElement(root, 'inputs') t_inputs.append(key.etree) return True
[ "def", "addInput", "(", "self", ",", "key", ")", ":", "if", "key", "not", "in", "self", ".", "inputs", ":", "self", ".", "inputs", ".", "append", "(", "key", ")", "root", "=", "self", ".", "etree", "t_inputs", "=", "root", ".", "find", "(", "'inp...
Add key to input : key, value or map
[ "Add", "key", "to", "input", ":", "key", "value", "or", "map" ]
train
https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/contrib/table/base.py#L105-L119
josuebrunel/myql
myql/contrib/table/base.py
BaseBinder.removeInput
def removeInput(self, key_id, input_type='key'): """Remove key (key, value, map) from Input key_id : id of the input element i.e <key id='artist' /> input_type : type of the input ; key, value or map """ root = self.etree t_inputs = root.find('inputs') if not t_inputs: return False keys = t_inputs.findall(input_type) key = [ key for key in keys if key.get('id') == key_id ] try: t_inputs.remove(key[0]) return True except (Exception,) as e: print(e) return False
python
def removeInput(self, key_id, input_type='key'): """Remove key (key, value, map) from Input key_id : id of the input element i.e <key id='artist' /> input_type : type of the input ; key, value or map """ root = self.etree t_inputs = root.find('inputs') if not t_inputs: return False keys = t_inputs.findall(input_type) key = [ key for key in keys if key.get('id') == key_id ] try: t_inputs.remove(key[0]) return True except (Exception,) as e: print(e) return False
[ "def", "removeInput", "(", "self", ",", "key_id", ",", "input_type", "=", "'key'", ")", ":", "root", "=", "self", ".", "etree", "t_inputs", "=", "root", ".", "find", "(", "'inputs'", ")", "if", "not", "t_inputs", ":", "return", "False", "keys", "=", ...
Remove key (key, value, map) from Input key_id : id of the input element i.e <key id='artist' /> input_type : type of the input ; key, value or map
[ "Remove", "key", "(", "key", "value", "map", ")", "from", "Input", "key_id", ":", "id", "of", "the", "input", "element", "i", ".", "e", "<key", "id", "=", "artist", "/", ">", "input_type", ":", "type", "of", "the", "input", ";", "key", "value", "or...
train
https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/contrib/table/base.py#L121-L142
josuebrunel/myql
myql/contrib/table/base.py
BaseBinder.addPaging
def addPaging(self,paging): """Add paging to Binder """ if not vars(self).get('paging', None): self.paging = paging root = self.etree try: root.append(paging.etree) return True except (Exception,) as e: print(e) return False
python
def addPaging(self,paging): """Add paging to Binder """ if not vars(self).get('paging', None): self.paging = paging root = self.etree try: root.append(paging.etree) return True except (Exception,) as e: print(e) return False
[ "def", "addPaging", "(", "self", ",", "paging", ")", ":", "if", "not", "vars", "(", "self", ")", ".", "get", "(", "'paging'", ",", "None", ")", ":", "self", ".", "paging", "=", "paging", "root", "=", "self", ".", "etree", "try", ":", "root", ".",...
Add paging to Binder
[ "Add", "paging", "to", "Binder" ]
train
https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/contrib/table/base.py#L144-L157
josuebrunel/myql
myql/contrib/table/base.py
BaseBinder.removePaging
def removePaging(self,): """Remove paging from Binder """ root = self.etree t_paging = root.find('paging') try: root.remove(t_paging) return True except (Exception,) as e: print(e) return False
python
def removePaging(self,): """Remove paging from Binder """ root = self.etree t_paging = root.find('paging') try: root.remove(t_paging) return True except (Exception,) as e: print(e) return False
[ "def", "removePaging", "(", "self", ",", ")", ":", "root", "=", "self", ".", "etree", "t_paging", "=", "root", ".", "find", "(", "'paging'", ")", "try", ":", "root", ".", "remove", "(", "t_paging", ")", "return", "True", "except", "(", "Exception", "...
Remove paging from Binder
[ "Remove", "paging", "from", "Binder" ]
train
https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/contrib/table/base.py#L159-L171
josuebrunel/myql
myql/contrib/table/base.py
BaseInput._buildElementTree
def _buildElementTree(self,): """Turn object into an ElementTree """ t_elt = ctree.Element(self.name) for k,v in [ (key,value) for key,value in self.__dict__.items() if key != 'name']: # Excluding name from list of items if v and v != 'false' : t_elt.set(k if k != 'like' else 'as', str(v).lower()) self._etree = t_elt return t_elt
python
def _buildElementTree(self,): """Turn object into an ElementTree """ t_elt = ctree.Element(self.name) for k,v in [ (key,value) for key,value in self.__dict__.items() if key != 'name']: # Excluding name from list of items if v and v != 'false' : t_elt.set(k if k != 'like' else 'as', str(v).lower()) self._etree = t_elt return t_elt
[ "def", "_buildElementTree", "(", "self", ",", ")", ":", "t_elt", "=", "ctree", ".", "Element", "(", "self", ".", "name", ")", "for", "k", ",", "v", "in", "[", "(", "key", ",", "value", ")", "for", "key", ",", "value", "in", "self", ".", "__dict__...
Turn object into an ElementTree
[ "Turn", "object", "into", "an", "ElementTree" ]
train
https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/contrib/table/base.py#L208-L218
josuebrunel/myql
myql/contrib/table/base.py
BasePaging._buildElementTree
def _buildElementTree(self,): """Turn object into an Element Tree """ t_paging = ctree.Element('paging') t_paging.set('model', self.model) for key in self.__dict__.keys(): if key != 'model': t_tag = ctree.SubElement(t_paging, key) for item in self.__dict__[key].items(): t_tag.set(*item) self.etree = t_paging return t_paging
python
def _buildElementTree(self,): """Turn object into an Element Tree """ t_paging = ctree.Element('paging') t_paging.set('model', self.model) for key in self.__dict__.keys(): if key != 'model': t_tag = ctree.SubElement(t_paging, key) for item in self.__dict__[key].items(): t_tag.set(*item) self.etree = t_paging return t_paging
[ "def", "_buildElementTree", "(", "self", ",", ")", ":", "t_paging", "=", "ctree", ".", "Element", "(", "'paging'", ")", "t_paging", ".", "set", "(", "'model'", ",", "self", ".", "model", ")", "for", "key", "in", "self", ".", "__dict__", ".", "keys", ...
Turn object into an Element Tree
[ "Turn", "object", "into", "an", "Element", "Tree" ]
train
https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/contrib/table/base.py#L231-L244
APSL/transmanager
transmanager/utils.py
get_application_choices
def get_application_choices(): """ Get the select options for the application selector :return: """ result = [] keys = set() for ct in ContentType.objects.order_by('app_label', 'model'): try: if issubclass(ct.model_class(), TranslatableModel) and ct.app_label not in keys: result.append(('{}'.format(ct.app_label), '{}'.format(ct.app_label.capitalize()))) keys.add(ct.app_label) except TypeError: continue return result
python
def get_application_choices(): """ Get the select options for the application selector :return: """ result = [] keys = set() for ct in ContentType.objects.order_by('app_label', 'model'): try: if issubclass(ct.model_class(), TranslatableModel) and ct.app_label not in keys: result.append(('{}'.format(ct.app_label), '{}'.format(ct.app_label.capitalize()))) keys.add(ct.app_label) except TypeError: continue return result
[ "def", "get_application_choices", "(", ")", ":", "result", "=", "[", "]", "keys", "=", "set", "(", ")", "for", "ct", "in", "ContentType", ".", "objects", ".", "order_by", "(", "'app_label'", ",", "'model'", ")", ":", "try", ":", "if", "issubclass", "("...
Get the select options for the application selector :return:
[ "Get", "the", "select", "options", "for", "the", "application", "selector" ]
train
https://github.com/APSL/transmanager/blob/79157085840008e146b264521681913090197ed1/transmanager/utils.py#L9-L24
APSL/transmanager
transmanager/utils.py
get_model_choices
def get_model_choices(): """ Get the select options for the model selector :return: """ result = [] for ct in ContentType.objects.order_by('app_label', 'model'): try: if issubclass(ct.model_class(), TranslatableModel): result.append( ('{} - {}'.format(ct.app_label, ct.model.lower()), '{} - {}'.format(ct.app_label.capitalize(), ct.model_class()._meta.verbose_name_plural)) ) except TypeError: continue return result
python
def get_model_choices(): """ Get the select options for the model selector :return: """ result = [] for ct in ContentType.objects.order_by('app_label', 'model'): try: if issubclass(ct.model_class(), TranslatableModel): result.append( ('{} - {}'.format(ct.app_label, ct.model.lower()), '{} - {}'.format(ct.app_label.capitalize(), ct.model_class()._meta.verbose_name_plural)) ) except TypeError: continue return result
[ "def", "get_model_choices", "(", ")", ":", "result", "=", "[", "]", "for", "ct", "in", "ContentType", ".", "objects", ".", "order_by", "(", "'app_label'", ",", "'model'", ")", ":", "try", ":", "if", "issubclass", "(", "ct", ".", "model_class", "(", ")"...
Get the select options for the model selector :return:
[ "Get", "the", "select", "options", "for", "the", "model", "selector" ]
train
https://github.com/APSL/transmanager/blob/79157085840008e146b264521681913090197ed1/transmanager/utils.py#L27-L43
APSL/transmanager
transmanager/utils.py
get_num_words
def get_num_words(text): """ Counts and returns the number of words found in a given text :param text: :return: """ try: word_regexp_pattern = re.compile(r"[a-zA-Záéíóúñ]+") num_words = re.findall(word_regexp_pattern, text) return len(num_words) except TypeError: return 0
python
def get_num_words(text): """ Counts and returns the number of words found in a given text :param text: :return: """ try: word_regexp_pattern = re.compile(r"[a-zA-Záéíóúñ]+") num_words = re.findall(word_regexp_pattern, text) return len(num_words) except TypeError: return 0
[ "def", "get_num_words", "(", "text", ")", ":", "try", ":", "word_regexp_pattern", "=", "re", ".", "compile", "(", "r\"[a-zA-Záéíóúñ]+\")", "", "num_words", "=", "re", ".", "findall", "(", "word_regexp_pattern", ",", "text", ")", "return", "len", "(", "num_wo...
Counts and returns the number of words found in a given text :param text: :return:
[ "Counts", "and", "returns", "the", "number", "of", "words", "found", "in", "a", "given", "text" ]
train
https://github.com/APSL/transmanager/blob/79157085840008e146b264521681913090197ed1/transmanager/utils.py#L46-L58
APSL/transmanager
transmanager/utils.py
has_field
def has_field(mc, field_name): """ detect if a model has a given field has :param field_name: :param mc: :return: """ try: mc._meta.get_field(field_name) except FieldDoesNotExist: return False return True
python
def has_field(mc, field_name): """ detect if a model has a given field has :param field_name: :param mc: :return: """ try: mc._meta.get_field(field_name) except FieldDoesNotExist: return False return True
[ "def", "has_field", "(", "mc", ",", "field_name", ")", ":", "try", ":", "mc", ".", "_meta", ".", "get_field", "(", "field_name", ")", "except", "FieldDoesNotExist", ":", "return", "False", "return", "True" ]
detect if a model has a given field has :param field_name: :param mc: :return:
[ "detect", "if", "a", "model", "has", "a", "given", "field", "has" ]
train
https://github.com/APSL/transmanager/blob/79157085840008e146b264521681913090197ed1/transmanager/utils.py#L61-L73
etalab/cada
cada/csv.py
reader
def reader(f): '''CSV Reader factory for CADA format''' return unicodecsv.reader(f, encoding='utf-8', delimiter=b',', quotechar=b'"')
python
def reader(f): '''CSV Reader factory for CADA format''' return unicodecsv.reader(f, encoding='utf-8', delimiter=b',', quotechar=b'"')
[ "def", "reader", "(", "f", ")", ":", "return", "unicodecsv", ".", "reader", "(", "f", ",", "encoding", "=", "'utf-8'", ",", "delimiter", "=", "b','", ",", "quotechar", "=", "b'\"'", ")" ]
CSV Reader factory for CADA format
[ "CSV", "Reader", "factory", "for", "CADA", "format" ]
train
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/csv.py#L30-L32
etalab/cada
cada/csv.py
writer
def writer(f): '''CSV writer factory for CADA format''' return unicodecsv.writer(f, encoding='utf-8', delimiter=b',', quotechar=b'"')
python
def writer(f): '''CSV writer factory for CADA format''' return unicodecsv.writer(f, encoding='utf-8', delimiter=b',', quotechar=b'"')
[ "def", "writer", "(", "f", ")", ":", "return", "unicodecsv", ".", "writer", "(", "f", ",", "encoding", "=", "'utf-8'", ",", "delimiter", "=", "b','", ",", "quotechar", "=", "b'\"'", ")" ]
CSV writer factory for CADA format
[ "CSV", "writer", "factory", "for", "CADA", "format" ]
train
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/csv.py#L35-L37
etalab/cada
cada/csv.py
from_row
def from_row(row): '''Create an advice from a CSV row''' subject = (row[5][0].upper() + row[5][1:]) if row[5] else row[5] return Advice.objects.create( id=row[0], administration=cleanup(row[1]), type=row[2], session=datetime.strptime(row[4], '%d/%m/%Y'), subject=cleanup(subject), topics=[t.title() for t in cleanup(row[6]).split(', ')], tags=[tag.strip() for tag in row[7].split(',') if tag.strip()], meanings=cleanup(row[8]).replace(' / ', '/').split(', '), part=_part(row[9]), content=cleanup(row[10]), )
python
def from_row(row): '''Create an advice from a CSV row''' subject = (row[5][0].upper() + row[5][1:]) if row[5] else row[5] return Advice.objects.create( id=row[0], administration=cleanup(row[1]), type=row[2], session=datetime.strptime(row[4], '%d/%m/%Y'), subject=cleanup(subject), topics=[t.title() for t in cleanup(row[6]).split(', ')], tags=[tag.strip() for tag in row[7].split(',') if tag.strip()], meanings=cleanup(row[8]).replace(' / ', '/').split(', '), part=_part(row[9]), content=cleanup(row[10]), )
[ "def", "from_row", "(", "row", ")", ":", "subject", "=", "(", "row", "[", "5", "]", "[", "0", "]", ".", "upper", "(", ")", "+", "row", "[", "5", "]", "[", "1", ":", "]", ")", "if", "row", "[", "5", "]", "else", "row", "[", "5", "]", "re...
Create an advice from a CSV row
[ "Create", "an", "advice", "from", "a", "CSV", "row" ]
train
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/csv.py#L60-L74
etalab/cada
cada/csv.py
to_row
def to_row(advice): '''Serialize an advice into a CSV row''' return [ advice.id, advice.administration, advice.type, advice.session.year, advice.session.strftime('%d/%m/%Y'), advice.subject, ', '.join(advice.topics), ', '.join(advice.tags), ', '.join(advice.meanings), ROMAN_NUMS.get(advice.part, ''), advice.content, ]
python
def to_row(advice): '''Serialize an advice into a CSV row''' return [ advice.id, advice.administration, advice.type, advice.session.year, advice.session.strftime('%d/%m/%Y'), advice.subject, ', '.join(advice.topics), ', '.join(advice.tags), ', '.join(advice.meanings), ROMAN_NUMS.get(advice.part, ''), advice.content, ]
[ "def", "to_row", "(", "advice", ")", ":", "return", "[", "advice", ".", "id", ",", "advice", ".", "administration", ",", "advice", ".", "type", ",", "advice", ".", "session", ".", "year", ",", "advice", ".", "session", ".", "strftime", "(", "'%d/%m/%Y'...
Serialize an advice into a CSV row
[ "Serialize", "an", "advice", "into", "a", "CSV", "row" ]
train
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/csv.py#L77-L91
pudo/banal
banal/dicts.py
clean_dict
def clean_dict(data): """Remove None-valued keys from a dictionary, recursively.""" if is_mapping(data): out = {} for k, v in data.items(): if v is not None: out[k] = clean_dict(v) return out elif is_sequence(data): return [clean_dict(d) for d in data if d is not None] return data
python
def clean_dict(data): """Remove None-valued keys from a dictionary, recursively.""" if is_mapping(data): out = {} for k, v in data.items(): if v is not None: out[k] = clean_dict(v) return out elif is_sequence(data): return [clean_dict(d) for d in data if d is not None] return data
[ "def", "clean_dict", "(", "data", ")", ":", "if", "is_mapping", "(", "data", ")", ":", "out", "=", "{", "}", "for", "k", ",", "v", "in", "data", ".", "items", "(", ")", ":", "if", "v", "is", "not", "None", ":", "out", "[", "k", "]", "=", "c...
Remove None-valued keys from a dictionary, recursively.
[ "Remove", "None", "-", "valued", "keys", "from", "a", "dictionary", "recursively", "." ]
train
https://github.com/pudo/banal/blob/528c339be5138458e387a058581cf7d261285447/banal/dicts.py#L19-L29
pudo/banal
banal/dicts.py
keys_values
def keys_values(data, *keys): """Get an entry as a list from a dict. Provide a fallback key.""" values = [] if is_mapping(data): for key in keys: if key in data: values.extend(ensure_list(data[key])) return values
python
def keys_values(data, *keys): """Get an entry as a list from a dict. Provide a fallback key.""" values = [] if is_mapping(data): for key in keys: if key in data: values.extend(ensure_list(data[key])) return values
[ "def", "keys_values", "(", "data", ",", "*", "keys", ")", ":", "values", "=", "[", "]", "if", "is_mapping", "(", "data", ")", ":", "for", "key", "in", "keys", ":", "if", "key", "in", "data", ":", "values", ".", "extend", "(", "ensure_list", "(", ...
Get an entry as a list from a dict. Provide a fallback key.
[ "Get", "an", "entry", "as", "a", "list", "from", "a", "dict", ".", "Provide", "a", "fallback", "key", "." ]
train
https://github.com/pudo/banal/blob/528c339be5138458e387a058581cf7d261285447/banal/dicts.py#L32-L39
fake-name/WebRequest
WebRequest/Captcha/AntiCaptchaSolver.py
AntiCaptchaSolver.solve_simple_captcha
def solve_simple_captcha(self, pathfile=None, filedata=None, filename=None): """ Upload a image (from disk or a bytearray), and then block until the captcha has been solved. Return value is the captcha result. either pathfile OR filedata should be specified. Filename is ignored (and is only kept for compatibility with the 2captcha solver interface) Failure will result in a subclass of WebRequest.CaptchaSolverFailure being thrown. """ if pathfile and os.path.exists(pathfile): fp = open(pathfile, 'rb') elif filedata: fp = io.BytesIO(filedata) else: raise ValueError("You must pass either a valid file path, or a bytes array containing the captcha image!") try: task = python_anticaptcha.ImageToTextTask(fp) job = self.client.createTask(task) job.join(maximum_time = self.waittime) return job.get_captcha_text() except python_anticaptcha.AnticaptchaException as e: raise exc.CaptchaSolverFailure("Failure solving captcha: %s, %s, %s" % ( e.error_id, e.error_code, e.error_description, ))
python
def solve_simple_captcha(self, pathfile=None, filedata=None, filename=None): """ Upload a image (from disk or a bytearray), and then block until the captcha has been solved. Return value is the captcha result. either pathfile OR filedata should be specified. Filename is ignored (and is only kept for compatibility with the 2captcha solver interface) Failure will result in a subclass of WebRequest.CaptchaSolverFailure being thrown. """ if pathfile and os.path.exists(pathfile): fp = open(pathfile, 'rb') elif filedata: fp = io.BytesIO(filedata) else: raise ValueError("You must pass either a valid file path, or a bytes array containing the captcha image!") try: task = python_anticaptcha.ImageToTextTask(fp) job = self.client.createTask(task) job.join(maximum_time = self.waittime) return job.get_captcha_text() except python_anticaptcha.AnticaptchaException as e: raise exc.CaptchaSolverFailure("Failure solving captcha: %s, %s, %s" % ( e.error_id, e.error_code, e.error_description, ))
[ "def", "solve_simple_captcha", "(", "self", ",", "pathfile", "=", "None", ",", "filedata", "=", "None", ",", "filename", "=", "None", ")", ":", "if", "pathfile", "and", "os", ".", "path", ".", "exists", "(", "pathfile", ")", ":", "fp", "=", "open", "...
Upload a image (from disk or a bytearray), and then block until the captcha has been solved. Return value is the captcha result. either pathfile OR filedata should be specified. Filename is ignored (and is only kept for compatibility with the 2captcha solver interface) Failure will result in a subclass of WebRequest.CaptchaSolverFailure being thrown.
[ "Upload", "a", "image", "(", "from", "disk", "or", "a", "bytearray", ")", "and", "then", "block", "until", "the", "captcha", "has", "been", "solved", ".", "Return", "value", "is", "the", "captcha", "result", "." ]
train
https://github.com/fake-name/WebRequest/blob/b6c94631ff88b5f81f26a9f99a2d5c706810b11f/WebRequest/Captcha/AntiCaptchaSolver.py#L45-L78
fake-name/WebRequest
WebRequest/Captcha/AntiCaptchaSolver.py
AntiCaptchaSolver.solve_recaptcha
def solve_recaptcha(self, google_key, page_url, timeout = 15 * 60): ''' Solve a recaptcha on page `page_url` with the input value `google_key`. Timeout is `timeout` seconds, defaulting to 60 seconds. Return value is either the `g-recaptcha-response` value, or an exceptionj is raised (generally `CaptchaSolverFailure`) ''' proxy = SocksProxy.ProxyLauncher(ANTICAPTCHA_IPS) try: antiprox = python_anticaptcha.Proxy( proxy_type = "socks5", proxy_address = proxy.get_wan_ip(), proxy_port = proxy.get_wan_port(), proxy_login = None, proxy_password = None, ) task = python_anticaptcha.NoCaptchaTask( website_url = page_url, website_key = google_key, proxy = antiprox, user_agent = dict(self.wg.browserHeaders).get('User-Agent') ) job = self.client.createTask(task) job.join(maximum_time = timeout) return job.get_solution_response() except python_anticaptcha.AnticaptchaException as e: raise exc.CaptchaSolverFailure("Failure solving captcha: %s, %s, %s" % ( e.error_id, e.error_code, e.error_description, )) finally: proxy.stop()
python
def solve_recaptcha(self, google_key, page_url, timeout = 15 * 60): ''' Solve a recaptcha on page `page_url` with the input value `google_key`. Timeout is `timeout` seconds, defaulting to 60 seconds. Return value is either the `g-recaptcha-response` value, or an exceptionj is raised (generally `CaptchaSolverFailure`) ''' proxy = SocksProxy.ProxyLauncher(ANTICAPTCHA_IPS) try: antiprox = python_anticaptcha.Proxy( proxy_type = "socks5", proxy_address = proxy.get_wan_ip(), proxy_port = proxy.get_wan_port(), proxy_login = None, proxy_password = None, ) task = python_anticaptcha.NoCaptchaTask( website_url = page_url, website_key = google_key, proxy = antiprox, user_agent = dict(self.wg.browserHeaders).get('User-Agent') ) job = self.client.createTask(task) job.join(maximum_time = timeout) return job.get_solution_response() except python_anticaptcha.AnticaptchaException as e: raise exc.CaptchaSolverFailure("Failure solving captcha: %s, %s, %s" % ( e.error_id, e.error_code, e.error_description, )) finally: proxy.stop()
[ "def", "solve_recaptcha", "(", "self", ",", "google_key", ",", "page_url", ",", "timeout", "=", "15", "*", "60", ")", ":", "proxy", "=", "SocksProxy", ".", "ProxyLauncher", "(", "ANTICAPTCHA_IPS", ")", "try", ":", "antiprox", "=", "python_anticaptcha", ".", ...
Solve a recaptcha on page `page_url` with the input value `google_key`. Timeout is `timeout` seconds, defaulting to 60 seconds. Return value is either the `g-recaptcha-response` value, or an exceptionj is raised (generally `CaptchaSolverFailure`)
[ "Solve", "a", "recaptcha", "on", "page", "page_url", "with", "the", "input", "value", "google_key", ".", "Timeout", "is", "timeout", "seconds", "defaulting", "to", "60", "seconds", "." ]
train
https://github.com/fake-name/WebRequest/blob/b6c94631ff88b5f81f26a9f99a2d5c706810b11f/WebRequest/Captcha/AntiCaptchaSolver.py#L81-L119
Richienb/quilt
src/quilt_lang/__init__.py
userinput
def userinput(prompttext="", times=1): """ Get the input of the user via a universally secure method. :type prompttext: string :param prompttext: The text to display while receiving the data. :type times: integer :param times: The amount of times to ask the user. If value is not 1, a list will be returned. Default is 1. :return: What the user typed in. :rtype: string """ # If times is 1 if times == 1: # Return the result return input(str(prompttext)) # Create new empty list inputlist = [] # For each time in range for _ in range(times): # Append the result of another input request inputlist.append(input(str(prompttext))) # Return the final result return inputlist
python
def userinput(prompttext="", times=1): """ Get the input of the user via a universally secure method. :type prompttext: string :param prompttext: The text to display while receiving the data. :type times: integer :param times: The amount of times to ask the user. If value is not 1, a list will be returned. Default is 1. :return: What the user typed in. :rtype: string """ # If times is 1 if times == 1: # Return the result return input(str(prompttext)) # Create new empty list inputlist = [] # For each time in range for _ in range(times): # Append the result of another input request inputlist.append(input(str(prompttext))) # Return the final result return inputlist
[ "def", "userinput", "(", "prompttext", "=", "\"\"", ",", "times", "=", "1", ")", ":", "# If times is 1", "if", "times", "==", "1", ":", "# Return the result", "return", "input", "(", "str", "(", "prompttext", ")", ")", "# Create new empty list", "inputlist", ...
Get the input of the user via a universally secure method. :type prompttext: string :param prompttext: The text to display while receiving the data. :type times: integer :param times: The amount of times to ask the user. If value is not 1, a list will be returned. Default is 1. :return: What the user typed in. :rtype: string
[ "Get", "the", "input", "of", "the", "user", "via", "a", "universally", "secure", "method", "." ]
train
https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L43-L71
Richienb/quilt
src/quilt_lang/__init__.py
shellinput
def shellinput(initialtext='>> ', splitpart=' '): """ Give the user a shell-like interface to enter commands which are returned as a multi-part list containing the command and each of the arguments. :type initialtext: string :param initialtext: Set the text to be displayed as the prompt. :type splitpart: string :param splitpart: The character to split when generating the list item. :return: A string of the user's input or a list of the user's input split by the split character. :rtype: string or list """ # Get the user's input shelluserinput = input(str(initialtext)) # Return the computed result return shelluserinput if splitpart in ( '', None) else shelluserinput.split(splitpart)
python
def shellinput(initialtext='>> ', splitpart=' '): """ Give the user a shell-like interface to enter commands which are returned as a multi-part list containing the command and each of the arguments. :type initialtext: string :param initialtext: Set the text to be displayed as the prompt. :type splitpart: string :param splitpart: The character to split when generating the list item. :return: A string of the user's input or a list of the user's input split by the split character. :rtype: string or list """ # Get the user's input shelluserinput = input(str(initialtext)) # Return the computed result return shelluserinput if splitpart in ( '', None) else shelluserinput.split(splitpart)
[ "def", "shellinput", "(", "initialtext", "=", "'>> '", ",", "splitpart", "=", "' '", ")", ":", "# Get the user's input", "shelluserinput", "=", "input", "(", "str", "(", "initialtext", ")", ")", "# Return the computed result", "return", "shelluserinput", "if", "sp...
Give the user a shell-like interface to enter commands which are returned as a multi-part list containing the command and each of the arguments. :type initialtext: string :param initialtext: Set the text to be displayed as the prompt. :type splitpart: string :param splitpart: The character to split when generating the list item. :return: A string of the user's input or a list of the user's input split by the split character. :rtype: string or list
[ "Give", "the", "user", "a", "shell", "-", "like", "interface", "to", "enter", "commands", "which", "are", "returned", "as", "a", "multi", "-", "part", "list", "containing", "the", "command", "and", "each", "of", "the", "arguments", "." ]
train
https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L74-L95
Richienb/quilt
src/quilt_lang/__init__.py
splitstring
def splitstring(string, splitcharacter=' ', part=None): """ Split a string based on a character and get the parts as a list. :type string: string :param string: The string to split. :type splitcharacter: string :param splitcharacter: The character to split for the string. :type part: integer :param part: Get a specific part of the list. :return: The split string or a specific part of it :rtype: list or string >>> splitstring('hello world !') ['hello', 'world', '!'] >>> splitstring('hello world !', ' ', None) ['hello', 'world', '!'] >>> splitstring('hello world !', ' ', None) ['hello', 'world', '!'] >>> splitstring('hello world !', ' ', 0) 'hello' """ # If the part is empty if part in [None, '']: # Return an array of the splitted text return str(string).split(splitcharacter) # Return an array of the splitted text with a specific part return str(string).split(splitcharacter)[part]
python
def splitstring(string, splitcharacter=' ', part=None): """ Split a string based on a character and get the parts as a list. :type string: string :param string: The string to split. :type splitcharacter: string :param splitcharacter: The character to split for the string. :type part: integer :param part: Get a specific part of the list. :return: The split string or a specific part of it :rtype: list or string >>> splitstring('hello world !') ['hello', 'world', '!'] >>> splitstring('hello world !', ' ', None) ['hello', 'world', '!'] >>> splitstring('hello world !', ' ', None) ['hello', 'world', '!'] >>> splitstring('hello world !', ' ', 0) 'hello' """ # If the part is empty if part in [None, '']: # Return an array of the splitted text return str(string).split(splitcharacter) # Return an array of the splitted text with a specific part return str(string).split(splitcharacter)[part]
[ "def", "splitstring", "(", "string", ",", "splitcharacter", "=", "' '", ",", "part", "=", "None", ")", ":", "# If the part is empty", "if", "part", "in", "[", "None", ",", "''", "]", ":", "# Return an array of the splitted text", "return", "str", "(", "string"...
Split a string based on a character and get the parts as a list. :type string: string :param string: The string to split. :type splitcharacter: string :param splitcharacter: The character to split for the string. :type part: integer :param part: Get a specific part of the list. :return: The split string or a specific part of it :rtype: list or string >>> splitstring('hello world !') ['hello', 'world', '!'] >>> splitstring('hello world !', ' ', None) ['hello', 'world', '!'] >>> splitstring('hello world !', ' ', None) ['hello', 'world', '!'] >>> splitstring('hello world !', ' ', 0) 'hello'
[ "Split", "a", "string", "based", "on", "a", "character", "and", "get", "the", "parts", "as", "a", "list", "." ]
train
https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L119-L155
Richienb/quilt
src/quilt_lang/__init__.py
pykeyword
def pykeyword(operation='list', keywordtotest=None): """ Check if a keyword exists in the Python keyword dictionary. :type operation: string :param operation: Whether to list or check the keywords. Possible options are 'list' and 'in'. :type keywordtotest: string :param keywordtotest: The keyword to check. :return: The list of keywords or if a keyword exists. :rtype: list or boolean >>> "True" in pykeyword("list") True >>> pykeyword("in", "True") True >>> pykeyword("in", "foo") False >>> pykeyword("foo", "foo") Traceback (most recent call last): ... ValueError: Invalid operation specified. """ # If the operation was 'list' if operation == 'list': # Return an array of keywords return str(keyword.kwlist) # If the operation was 'in' elif operation == 'in': # Return a boolean for if the string was a keyword return keyword.iskeyword(str(keywordtotest)) # Raise a warning raise ValueError("Invalid operation specified.")
python
def pykeyword(operation='list', keywordtotest=None): """ Check if a keyword exists in the Python keyword dictionary. :type operation: string :param operation: Whether to list or check the keywords. Possible options are 'list' and 'in'. :type keywordtotest: string :param keywordtotest: The keyword to check. :return: The list of keywords or if a keyword exists. :rtype: list or boolean >>> "True" in pykeyword("list") True >>> pykeyword("in", "True") True >>> pykeyword("in", "foo") False >>> pykeyword("foo", "foo") Traceback (most recent call last): ... ValueError: Invalid operation specified. """ # If the operation was 'list' if operation == 'list': # Return an array of keywords return str(keyword.kwlist) # If the operation was 'in' elif operation == 'in': # Return a boolean for if the string was a keyword return keyword.iskeyword(str(keywordtotest)) # Raise a warning raise ValueError("Invalid operation specified.")
[ "def", "pykeyword", "(", "operation", "=", "'list'", ",", "keywordtotest", "=", "None", ")", ":", "# If the operation was 'list'", "if", "operation", "==", "'list'", ":", "# Return an array of keywords", "return", "str", "(", "keyword", ".", "kwlist", ")", "# If t...
Check if a keyword exists in the Python keyword dictionary. :type operation: string :param operation: Whether to list or check the keywords. Possible options are 'list' and 'in'. :type keywordtotest: string :param keywordtotest: The keyword to check. :return: The list of keywords or if a keyword exists. :rtype: list or boolean >>> "True" in pykeyword("list") True >>> pykeyword("in", "True") True >>> pykeyword("in", "foo") False >>> pykeyword("foo", "foo") Traceback (most recent call last): ... ValueError: Invalid operation specified.
[ "Check", "if", "a", "keyword", "exists", "in", "the", "Python", "keyword", "dictionary", "." ]
train
https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L158-L197
Richienb/quilt
src/quilt_lang/__init__.py
binboolflip
def binboolflip(item): """ Convert 0 or 1 to False or True (or vice versa). The converter works as follows: - 0 > False - False > 0 - 1 > True - True > 1 :type item: integer or boolean :param item: The item to convert. >>> binboolflip(0) False >>> binboolflip(False) 0 >>> binboolflip(1) True >>> binboolflip(True) 1 >>> binboolflip("foo") Traceback (most recent call last): ... ValueError: Invalid item specified. """ if item in [0, False, 1, True]: return int(item) if isinstance(item, bool) else bool(item) # Raise a warning raise ValueError("Invalid item specified.")
python
def binboolflip(item): """ Convert 0 or 1 to False or True (or vice versa). The converter works as follows: - 0 > False - False > 0 - 1 > True - True > 1 :type item: integer or boolean :param item: The item to convert. >>> binboolflip(0) False >>> binboolflip(False) 0 >>> binboolflip(1) True >>> binboolflip(True) 1 >>> binboolflip("foo") Traceback (most recent call last): ... ValueError: Invalid item specified. """ if item in [0, False, 1, True]: return int(item) if isinstance(item, bool) else bool(item) # Raise a warning raise ValueError("Invalid item specified.")
[ "def", "binboolflip", "(", "item", ")", ":", "if", "item", "in", "[", "0", ",", "False", ",", "1", ",", "True", "]", ":", "return", "int", "(", "item", ")", "if", "isinstance", "(", "item", ",", "bool", ")", "else", "bool", "(", "item", ")", "#...
Convert 0 or 1 to False or True (or vice versa). The converter works as follows: - 0 > False - False > 0 - 1 > True - True > 1 :type item: integer or boolean :param item: The item to convert. >>> binboolflip(0) False >>> binboolflip(False) 0 >>> binboolflip(1) True >>> binboolflip(True) 1 >>> binboolflip("foo") Traceback (most recent call last): ... ValueError: Invalid item specified.
[ "Convert", "0", "or", "1", "to", "False", "or", "True", "(", "or", "vice", "versa", ")", ".", "The", "converter", "works", "as", "follows", ":" ]
train
https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L200-L235
Richienb/quilt
src/quilt_lang/__init__.py
warnconfig
def warnconfig(action='default'): """ Configure the Python warnings. :type action: string :param action: The configuration to set. Options are: 'default', 'error', 'ignore', 'always', 'module' and 'once'. """ # If action is 'default' if action.lower() == 'default': # Change warning settings warnings.filterwarnings('default') # If action is 'error' elif action.lower() == 'error': # Change warning settings warnings.filterwarnings('error') # If action is 'ignore' elif action.lower() == 'ignore': # Change warning settings warnings.filterwarnings('ignore') # If action is 'always' elif action.lower() == 'always': # Change warning settings warnings.filterwarnings('always') # If action is 'module' elif action.lower() == 'module': # Change warning settings warnings.filterwarnings('module') # If action is 'once' elif action.lower() == 'once': # Change warning settings warnings.filterwarnings('once') # Raise runtime warning raise ValueError("Invalid action specified.")
python
def warnconfig(action='default'): """ Configure the Python warnings. :type action: string :param action: The configuration to set. Options are: 'default', 'error', 'ignore', 'always', 'module' and 'once'. """ # If action is 'default' if action.lower() == 'default': # Change warning settings warnings.filterwarnings('default') # If action is 'error' elif action.lower() == 'error': # Change warning settings warnings.filterwarnings('error') # If action is 'ignore' elif action.lower() == 'ignore': # Change warning settings warnings.filterwarnings('ignore') # If action is 'always' elif action.lower() == 'always': # Change warning settings warnings.filterwarnings('always') # If action is 'module' elif action.lower() == 'module': # Change warning settings warnings.filterwarnings('module') # If action is 'once' elif action.lower() == 'once': # Change warning settings warnings.filterwarnings('once') # Raise runtime warning raise ValueError("Invalid action specified.")
[ "def", "warnconfig", "(", "action", "=", "'default'", ")", ":", "# If action is 'default'", "if", "action", ".", "lower", "(", ")", "==", "'default'", ":", "# Change warning settings", "warnings", ".", "filterwarnings", "(", "'default'", ")", "# If action is 'error'...
Configure the Python warnings. :type action: string :param action: The configuration to set. Options are: 'default', 'error', 'ignore', 'always', 'module' and 'once'.
[ "Configure", "the", "Python", "warnings", "." ]
train
https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L250-L289
Richienb/quilt
src/quilt_lang/__init__.py
happybirthday
def happybirthday(person): """ Sing Happy Birthday """ print('Happy Birthday To You') time.sleep(2) print('Happy Birthday To You') time.sleep(2) print('Happy Birthday Dear ' + str(person[0].upper()) + str(person[1:])) time.sleep(2) print('Happy Birthday To You')
python
def happybirthday(person): """ Sing Happy Birthday """ print('Happy Birthday To You') time.sleep(2) print('Happy Birthday To You') time.sleep(2) print('Happy Birthday Dear ' + str(person[0].upper()) + str(person[1:])) time.sleep(2) print('Happy Birthday To You')
[ "def", "happybirthday", "(", "person", ")", ":", "print", "(", "'Happy Birthday To You'", ")", "time", ".", "sleep", "(", "2", ")", "print", "(", "'Happy Birthday To You'", ")", "time", ".", "sleep", "(", "2", ")", "print", "(", "'Happy Birthday Dear '", "+"...
Sing Happy Birthday
[ "Sing", "Happy", "Birthday" ]
train
https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L385-L395
Richienb/quilt
src/quilt_lang/__init__.py
cowsay
def cowsay(text='', align='centre'): """ Simulate an ASCII cow saying text. :type text: string :param text: The text to print out. :type align: string :param algin: Where to align the cow. Can be 'left', 'centre' or 'right' """ # Make align lowercase align = align.lower() # Set the cowtext cowtext = str(text) # Set top part of speech bubble to the length of the text plus 2 topbar = ' ' * (len(text) + 2) # Set bottom part of speech bubble to the length of the text plus 2 bottombar = ' ' * (len(text) + 2) # If align is centre if align in ["center", "centre"]: # Set the spacing before the cow to the length of half of the length of topbar plus 1 spacing = " " * (int(len(topbar) / 2) + 1) # If align is left elif align == 'left': # Set spacing to a single space spacing = ' ' # If align is right elif align == 'right': # Set the spacing to the length of the text plus 2 spacing = " " * (len(text) + 2) else: # Raise a runtime warning raise ValueError("Invalid alignment provided.") # Print the top bar print(topbar) # Print the text print('( ' + repr(str(cowtext)) + ' )') # Print the bottom bar print(bottombar) # Print the cow with the spacing print(spacing + r'o ^__^ ') print(spacing + r' o (oO)\_______') print(spacing + r' (__)\ )\/\ ') print(spacing + r' U ||----w | ') print(spacing + r' || || ')
python
def cowsay(text='', align='centre'): """ Simulate an ASCII cow saying text. :type text: string :param text: The text to print out. :type align: string :param algin: Where to align the cow. Can be 'left', 'centre' or 'right' """ # Make align lowercase align = align.lower() # Set the cowtext cowtext = str(text) # Set top part of speech bubble to the length of the text plus 2 topbar = ' ' * (len(text) + 2) # Set bottom part of speech bubble to the length of the text plus 2 bottombar = ' ' * (len(text) + 2) # If align is centre if align in ["center", "centre"]: # Set the spacing before the cow to the length of half of the length of topbar plus 1 spacing = " " * (int(len(topbar) / 2) + 1) # If align is left elif align == 'left': # Set spacing to a single space spacing = ' ' # If align is right elif align == 'right': # Set the spacing to the length of the text plus 2 spacing = " " * (len(text) + 2) else: # Raise a runtime warning raise ValueError("Invalid alignment provided.") # Print the top bar print(topbar) # Print the text print('( ' + repr(str(cowtext)) + ' )') # Print the bottom bar print(bottombar) # Print the cow with the spacing print(spacing + r'o ^__^ ') print(spacing + r' o (oO)\_______') print(spacing + r' (__)\ )\/\ ') print(spacing + r' U ||----w | ') print(spacing + r' || || ')
[ "def", "cowsay", "(", "text", "=", "''", ",", "align", "=", "'centre'", ")", ":", "# Make align lowercase", "align", "=", "align", ".", "lower", "(", ")", "# Set the cowtext", "cowtext", "=", "str", "(", "text", ")", "# Set top part of speech bubble to the lengt...
Simulate an ASCII cow saying text. :type text: string :param text: The text to print out. :type align: string :param algin: Where to align the cow. Can be 'left', 'centre' or 'right'
[ "Simulate", "an", "ASCII", "cow", "saying", "text", "." ]
train
https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L446-L502
Richienb/quilt
src/quilt_lang/__init__.py
convertbinary
def convertbinary(value, argument): """ Convert text to binary form or backwards. :type value: string :param value: The text or the binary text :type argument: string :param argument: The action to perform on the value. Can be "to" or "from". """ if argument == 'to': return bin(value) elif argument == 'from': return format(value) raise ValueError("Invalid argument specified.")
python
def convertbinary(value, argument): """ Convert text to binary form or backwards. :type value: string :param value: The text or the binary text :type argument: string :param argument: The action to perform on the value. Can be "to" or "from". """ if argument == 'to': return bin(value) elif argument == 'from': return format(value) raise ValueError("Invalid argument specified.")
[ "def", "convertbinary", "(", "value", ",", "argument", ")", ":", "if", "argument", "==", "'to'", ":", "return", "bin", "(", "value", ")", "elif", "argument", "==", "'from'", ":", "return", "format", "(", "value", ")", "raise", "ValueError", "(", "\"Inval...
Convert text to binary form or backwards. :type value: string :param value: The text or the binary text :type argument: string :param argument: The action to perform on the value. Can be "to" or "from".
[ "Convert", "text", "to", "binary", "form", "or", "backwards", "." ]
train
https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L566-L581
Richienb/quilt
src/quilt_lang/__init__.py
reversetext
def reversetext(contenttoreverse, reconvert=True): """ Reverse any content :type contenttoreverse: string :param contenttoreverse: The content to be reversed :type reeval: boolean :param reeval: Wether or not to reconvert the object back into it's initial state. Default is "True". """ # If reconvert is specified if reconvert is True: # Return the evalated form return eval( str(type(contenttoreverse)).split("'")[1] + "('" + str(contenttoreverse)[::-1] + "')") # Return the raw version return contenttoreverse[::-1]
python
def reversetext(contenttoreverse, reconvert=True): """ Reverse any content :type contenttoreverse: string :param contenttoreverse: The content to be reversed :type reeval: boolean :param reeval: Wether or not to reconvert the object back into it's initial state. Default is "True". """ # If reconvert is specified if reconvert is True: # Return the evalated form return eval( str(type(contenttoreverse)).split("'")[1] + "('" + str(contenttoreverse)[::-1] + "')") # Return the raw version return contenttoreverse[::-1]
[ "def", "reversetext", "(", "contenttoreverse", ",", "reconvert", "=", "True", ")", ":", "# If reconvert is specified", "if", "reconvert", "is", "True", ":", "# Return the evalated form", "return", "eval", "(", "str", "(", "type", "(", "contenttoreverse", ")", ")",...
Reverse any content :type contenttoreverse: string :param contenttoreverse: The content to be reversed :type reeval: boolean :param reeval: Wether or not to reconvert the object back into it's initial state. Default is "True".
[ "Reverse", "any", "content" ]
train
https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L584-L603
Richienb/quilt
src/quilt_lang/__init__.py
convertascii
def convertascii(value, command='to'): """ Convert an ASCII value to a symbol :type value: string :param value: The text or the text in ascii form. :type argument: string :param argument: The action to perform on the value. Can be "to" or "from". """ command = command.lower() if command == 'to': return chr(value) elif command == 'from': return ord(value) else: raise ValueError('Invalid operation provided.')
python
def convertascii(value, command='to'): """ Convert an ASCII value to a symbol :type value: string :param value: The text or the text in ascii form. :type argument: string :param argument: The action to perform on the value. Can be "to" or "from". """ command = command.lower() if command == 'to': return chr(value) elif command == 'from': return ord(value) else: raise ValueError('Invalid operation provided.')
[ "def", "convertascii", "(", "value", ",", "command", "=", "'to'", ")", ":", "command", "=", "command", ".", "lower", "(", ")", "if", "command", "==", "'to'", ":", "return", "chr", "(", "value", ")", "elif", "command", "==", "'from'", ":", "return", "...
Convert an ASCII value to a symbol :type value: string :param value: The text or the text in ascii form. :type argument: string :param argument: The action to perform on the value. Can be "to" or "from".
[ "Convert", "an", "ASCII", "value", "to", "a", "symbol" ]
train
https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L648-L664
Richienb/quilt
src/quilt_lang/__init__.py
availchars
def availchars(charactertype): """ Get all the available characters for a specific type. :type charactertype: string :param charactertype: The characters to get. Can be 'letters', 'lowercase, 'uppercase', 'digits', 'hexdigits', 'punctuation', 'printable', 'whitespace' or 'all'. >>> availchars("lowercase") 'abcdefghijklmnopqrstuvwxyz' """ # If the lowercase version of the character type is 'letters' if charactertype.lower() == 'letters': # Return the result return string.ascii_letters # If the lowercase version of the character type is 'lowercase' elif charactertype.lower() == 'lowercase': # Return the result return string.ascii_lowercase # If the lowercase version of the character type is 'uppercase' elif charactertype.lower() == 'uppercase': # Return the result return string.ascii_uppercase # If the lowercase version of the character type is 'digits' elif charactertype.lower() == 'digits': # Return the result return string.digits # If the lowercase version of the character type is 'hexdigits' elif charactertype.lower() == 'hexdigits': # Return the result return string.hexdigits # If the lowercase version of the character type is 'punctuation' elif charactertype.lower() == 'punctuation': # Return the result return string.punctuation # If the lowercase version of the character type is 'printable' elif charactertype.lower() == 'printable': # Return the result return string.printable # If the lowercase version of the character type is 'whitespace' elif charactertype.lower() == 'whitespace': # Return the result return string.whitespace # If the lowercase version of the character type is 'all' elif charactertype.lower() == 'all': # Return the result return string.ascii_letters + string.ascii_lowercase + string.ascii_uppercase + string.digits + string.hexdigits + string.punctuation + string.printable + string.whitespace # Raise a warning raise ValueError("Invalid character type provided.")
python
def availchars(charactertype): """ Get all the available characters for a specific type. :type charactertype: string :param charactertype: The characters to get. Can be 'letters', 'lowercase, 'uppercase', 'digits', 'hexdigits', 'punctuation', 'printable', 'whitespace' or 'all'. >>> availchars("lowercase") 'abcdefghijklmnopqrstuvwxyz' """ # If the lowercase version of the character type is 'letters' if charactertype.lower() == 'letters': # Return the result return string.ascii_letters # If the lowercase version of the character type is 'lowercase' elif charactertype.lower() == 'lowercase': # Return the result return string.ascii_lowercase # If the lowercase version of the character type is 'uppercase' elif charactertype.lower() == 'uppercase': # Return the result return string.ascii_uppercase # If the lowercase version of the character type is 'digits' elif charactertype.lower() == 'digits': # Return the result return string.digits # If the lowercase version of the character type is 'hexdigits' elif charactertype.lower() == 'hexdigits': # Return the result return string.hexdigits # If the lowercase version of the character type is 'punctuation' elif charactertype.lower() == 'punctuation': # Return the result return string.punctuation # If the lowercase version of the character type is 'printable' elif charactertype.lower() == 'printable': # Return the result return string.printable # If the lowercase version of the character type is 'whitespace' elif charactertype.lower() == 'whitespace': # Return the result return string.whitespace # If the lowercase version of the character type is 'all' elif charactertype.lower() == 'all': # Return the result return string.ascii_letters + string.ascii_lowercase + string.ascii_uppercase + string.digits + string.hexdigits + string.punctuation + string.printable + string.whitespace # Raise a warning raise ValueError("Invalid character type provided.")
[ "def", "availchars", "(", "charactertype", ")", ":", "# If the lowercase version of the character type is 'letters'", "if", "charactertype", ".", "lower", "(", ")", "==", "'letters'", ":", "# Return the result", "return", "string", ".", "ascii_letters", "# If the lowercase ...
Get all the available characters for a specific type. :type charactertype: string :param charactertype: The characters to get. Can be 'letters', 'lowercase, 'uppercase', 'digits', 'hexdigits', 'punctuation', 'printable', 'whitespace' or 'all'. >>> availchars("lowercase") 'abcdefghijklmnopqrstuvwxyz'
[ "Get", "all", "the", "available", "characters", "for", "a", "specific", "type", "." ]
train
https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L667-L724
Richienb/quilt
src/quilt_lang/__init__.py
textbetween
def textbetween(variable, firstnum=None, secondnum=None, locationoftext='regular'): """ Get The Text Between Two Parts """ if locationoftext == 'regular': return variable[firstnum:secondnum] elif locationoftext == 'toend': return variable[firstnum:] elif locationoftext == 'tostart': return variable[:secondnum]
python
def textbetween(variable, firstnum=None, secondnum=None, locationoftext='regular'): """ Get The Text Between Two Parts """ if locationoftext == 'regular': return variable[firstnum:secondnum] elif locationoftext == 'toend': return variable[firstnum:] elif locationoftext == 'tostart': return variable[:secondnum]
[ "def", "textbetween", "(", "variable", ",", "firstnum", "=", "None", ",", "secondnum", "=", "None", ",", "locationoftext", "=", "'regular'", ")", ":", "if", "locationoftext", "==", "'regular'", ":", "return", "variable", "[", "firstnum", ":", "secondnum", "]...
Get The Text Between Two Parts
[ "Get", "The", "Text", "Between", "Two", "Parts" ]
train
https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L727-L739
Richienb/quilt
src/quilt_lang/__init__.py
letternum
def letternum(letter): """ Get The Number Corresponding To A Letter """ if not isinstance(letter, str): raise TypeError("Invalid letter provided.") if not len(letter) == 1: raise ValueError("Invalid letter length provided.") letter = letter.lower() alphaletters = string.ascii_lowercase for i in range(len(alphaletters)): if letter[0] == alphaletters[i]: return i + 1
python
def letternum(letter): """ Get The Number Corresponding To A Letter """ if not isinstance(letter, str): raise TypeError("Invalid letter provided.") if not len(letter) == 1: raise ValueError("Invalid letter length provided.") letter = letter.lower() alphaletters = string.ascii_lowercase for i in range(len(alphaletters)): if letter[0] == alphaletters[i]: return i + 1
[ "def", "letternum", "(", "letter", ")", ":", "if", "not", "isinstance", "(", "letter", ",", "str", ")", ":", "raise", "TypeError", "(", "\"Invalid letter provided.\"", ")", "if", "not", "len", "(", "letter", ")", "==", "1", ":", "raise", "ValueError", "(...
Get The Number Corresponding To A Letter
[ "Get", "The", "Number", "Corresponding", "To", "A", "Letter" ]
train
https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L742-L754
Richienb/quilt
src/quilt_lang/__init__.py
wordvalue
def wordvalue(word): """ Get the value of each letter of a string's position in the alphabet added up :type word: string :param word: The word to find the value of """ # Set total to 0 total = 0 # For each character of word for i in enumerate(word): # Add it's letter value to total total += letternum(word[i[0]]) # Return the final value return total
python
def wordvalue(word): """ Get the value of each letter of a string's position in the alphabet added up :type word: string :param word: The word to find the value of """ # Set total to 0 total = 0 # For each character of word for i in enumerate(word): # Add it's letter value to total total += letternum(word[i[0]]) # Return the final value return total
[ "def", "wordvalue", "(", "word", ")", ":", "# Set total to 0", "total", "=", "0", "# For each character of word", "for", "i", "in", "enumerate", "(", "word", ")", ":", "# Add it's letter value to total", "total", "+=", "letternum", "(", "word", "[", "i", "[", ...
Get the value of each letter of a string's position in the alphabet added up :type word: string :param word: The word to find the value of
[ "Get", "the", "value", "of", "each", "letter", "of", "a", "string", "s", "position", "in", "the", "alphabet", "added", "up" ]
train
https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L757-L774
Richienb/quilt
src/quilt_lang/__init__.py
spacelist
def spacelist(listtospace, spacechar=" "): """ Convert a list to a string with all of the list's items spaced out. :type listtospace: list :param listtospace: The list to space out. :type spacechar: string :param spacechar: The characters to insert between each list item. Default is: " ". """ output = '' space = '' output += str(listtospace[0]) space += spacechar for listnum in range(1, len(listtospace)): output += space output += str(listtospace[listnum]) return output
python
def spacelist(listtospace, spacechar=" "): """ Convert a list to a string with all of the list's items spaced out. :type listtospace: list :param listtospace: The list to space out. :type spacechar: string :param spacechar: The characters to insert between each list item. Default is: " ". """ output = '' space = '' output += str(listtospace[0]) space += spacechar for listnum in range(1, len(listtospace)): output += space output += str(listtospace[listnum]) return output
[ "def", "spacelist", "(", "listtospace", ",", "spacechar", "=", "\" \"", ")", ":", "output", "=", "''", "space", "=", "''", "output", "+=", "str", "(", "listtospace", "[", "0", "]", ")", "space", "+=", "spacechar", "for", "listnum", "in", "range", "(", ...
Convert a list to a string with all of the list's items spaced out. :type listtospace: list :param listtospace: The list to space out. :type spacechar: string :param spacechar: The characters to insert between each list item. Default is: " ".
[ "Convert", "a", "list", "to", "a", "string", "with", "all", "of", "the", "list", "s", "items", "spaced", "out", "." ]
train
https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L777-L794
Richienb/quilt
src/quilt_lang/__init__.py
numlistbetween
def numlistbetween(num1, num2, option='list', listoption='string'): """ List Or Count The Numbers Between Two Numbers """ if option == 'list': if listoption == 'string': output = '' output += str(num1) for currentnum in range(num1 + 1, num2 + 1): output += ',' output += str(currentnum) elif listoption == 'list': output = [] for currentnum in range(num1, num2 + 1): output.append(str(currentnum)) return output elif option == 'count': return num2 - num1
python
def numlistbetween(num1, num2, option='list', listoption='string'): """ List Or Count The Numbers Between Two Numbers """ if option == 'list': if listoption == 'string': output = '' output += str(num1) for currentnum in range(num1 + 1, num2 + 1): output += ',' output += str(currentnum) elif listoption == 'list': output = [] for currentnum in range(num1, num2 + 1): output.append(str(currentnum)) return output elif option == 'count': return num2 - num1
[ "def", "numlistbetween", "(", "num1", ",", "num2", ",", "option", "=", "'list'", ",", "listoption", "=", "'string'", ")", ":", "if", "option", "==", "'list'", ":", "if", "listoption", "==", "'string'", ":", "output", "=", "''", "output", "+=", "str", "...
List Or Count The Numbers Between Two Numbers
[ "List", "Or", "Count", "The", "Numbers", "Between", "Two", "Numbers" ]
train
https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L797-L814
Richienb/quilt
src/quilt_lang/__init__.py
textalign
def textalign(text, maxlength, align='left'): """ Align Text When Given Full Length """ if align == 'left': return text elif align == 'centre' or align == 'center': spaces = ' ' * (int((maxlength - len(text)) / 2)) elif align == 'right': spaces = (maxlength - len(text)) else: raise ValueError("Invalid alignment specified.") return spaces + text
python
def textalign(text, maxlength, align='left'): """ Align Text When Given Full Length """ if align == 'left': return text elif align == 'centre' or align == 'center': spaces = ' ' * (int((maxlength - len(text)) / 2)) elif align == 'right': spaces = (maxlength - len(text)) else: raise ValueError("Invalid alignment specified.") return spaces + text
[ "def", "textalign", "(", "text", ",", "maxlength", ",", "align", "=", "'left'", ")", ":", "if", "align", "==", "'left'", ":", "return", "text", "elif", "align", "==", "'centre'", "or", "align", "==", "'center'", ":", "spaces", "=", "' '", "*", "(", "...
Align Text When Given Full Length
[ "Align", "Text", "When", "Given", "Full", "Length" ]
train
https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L817-L829
Richienb/quilt
src/quilt_lang/__init__.py
shapesides
def shapesides(inputtocheck, inputtype='shape'): """ Get the sides of a shape. inputtocheck: The amount of sides or the shape to be checked, depending on the value of inputtype. inputtype: The type of input provided. Can be: 'shape', 'sides'. """ # Define the array of sides to a shape shapestosides = { 'triangle': 3, 'square': 4, 'pentagon': 5, 'hexagon': 6, 'heptagon': 7, 'octagon': 8, 'nonagon': 9, 'decagon': 10, 'hendecagon': 11, 'dodecagon': 12, 'triskaidecagon': 13, 'tetrakaidecagon': 14, 'pentadecagon': 15, 'hexakaidecagon': 16, 'heptadecagon': 17, 'octakaidecagon': 18, 'enneadecagon': 19, 'icosagon': 20, 'triacontagon': 30, 'tetracontagon': 40, 'pentacontagon': 50, 'hexacontagon': 60, 'heptacontagon': 70, 'octacontagon': 80, 'enneacontagon': 90, 'hectagon': 100, 'chiliagon': 1000, 'myriagon': 10000, 'megagon': 1000000, 'googolgon': pow(10, 100), 'ngon': 'n' } # Define an array with the flipped version of the sides to a shape sidestoshapes = dictflip(shapestosides) # If the lowercase version of the input type is 'shape' if inputtype.lower() == 'shape': # If the lowercase version of the shape is in the array if inputtocheck.lower() in shapestosides: # Return the corresponding sides return shapestosides[inputtocheck.lower()] # Return 'n' return shapestosides['n'] if inputtype.lower() == 'sides': # If the lowercase version of the shape is in the array if inputtocheck.lower() in sidestoshapes: # Return the corresponding sides return sidestoshapes[inputtocheck.lower()] # Return 'ngon' return sidestoshapes['ngon'] # Raise a warning raise ValueError("Invalid input type.")
python
def shapesides(inputtocheck, inputtype='shape'): """ Get the sides of a shape. inputtocheck: The amount of sides or the shape to be checked, depending on the value of inputtype. inputtype: The type of input provided. Can be: 'shape', 'sides'. """ # Define the array of sides to a shape shapestosides = { 'triangle': 3, 'square': 4, 'pentagon': 5, 'hexagon': 6, 'heptagon': 7, 'octagon': 8, 'nonagon': 9, 'decagon': 10, 'hendecagon': 11, 'dodecagon': 12, 'triskaidecagon': 13, 'tetrakaidecagon': 14, 'pentadecagon': 15, 'hexakaidecagon': 16, 'heptadecagon': 17, 'octakaidecagon': 18, 'enneadecagon': 19, 'icosagon': 20, 'triacontagon': 30, 'tetracontagon': 40, 'pentacontagon': 50, 'hexacontagon': 60, 'heptacontagon': 70, 'octacontagon': 80, 'enneacontagon': 90, 'hectagon': 100, 'chiliagon': 1000, 'myriagon': 10000, 'megagon': 1000000, 'googolgon': pow(10, 100), 'ngon': 'n' } # Define an array with the flipped version of the sides to a shape sidestoshapes = dictflip(shapestosides) # If the lowercase version of the input type is 'shape' if inputtype.lower() == 'shape': # If the lowercase version of the shape is in the array if inputtocheck.lower() in shapestosides: # Return the corresponding sides return shapestosides[inputtocheck.lower()] # Return 'n' return shapestosides['n'] if inputtype.lower() == 'sides': # If the lowercase version of the shape is in the array if inputtocheck.lower() in sidestoshapes: # Return the corresponding sides return sidestoshapes[inputtocheck.lower()] # Return 'ngon' return sidestoshapes['ngon'] # Raise a warning raise ValueError("Invalid input type.")
[ "def", "shapesides", "(", "inputtocheck", ",", "inputtype", "=", "'shape'", ")", ":", "# Define the array of sides to a shape", "shapestosides", "=", "{", "'triangle'", ":", "3", ",", "'square'", ":", "4", ",", "'pentagon'", ":", "5", ",", "'hexagon'", ":", "6...
Get the sides of a shape. inputtocheck: The amount of sides or the shape to be checked, depending on the value of inputtype. inputtype: The type of input provided. Can be: 'shape', 'sides'.
[ "Get", "the", "sides", "of", "a", "shape", "." ]
train
https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L846-L917
Richienb/quilt
src/quilt_lang/__init__.py
autosolve
def autosolve(equation): """ Automatically solve an easy maths problem. :type equation: string :param equation: The equation to calculate. >>> autosolve("300 + 600") 900 """ try: # Try to set a variable to an integer num1 = int(equation.split(" ")[0]) except ValueError: # Try to set a variable to a decimal num1 = float(equation.split(" ")[0]) try: # Try to set a variable to an integer num2 = int(equation.split(" ")[2]) except ValueError: # Try to set a variable to a decimal num2 = float(equation.split(" ")[2]) # If the lowercase version of the operator is '+', 'plus' or 'add' if equation.split(" ")[1].lower() in ["+", "plus", "add"]: # Return the answer return num1 + num2 # If the lowercase version of the operator is '-', 'minus' or 'subtract' elif equation.split(" ")[1].lower() in ["-", "minus", "subtract"]: # Return the answer return num1 - num2 # If the lowercase version of the operator is '*', 'times', 'multiply' elif equation.split(" ")[1].lower() in ["*", "times", "multiply"]: # Return the answer return num1 * num2 # If the lowercase version of the operator is '/', 'divide' or 'quotient' elif equation.split(" ")[1].lower() in ["/", "divide", "quotient"]: # Return the answer return num1 / num2 # If the lowercase version of the operator is '%, 'remainder' or 'rem' elif equation.split(" ")[1].lower() in ["%", "remainder", "rem"]: # Return the answer return num1 % num2 # Raise a warning raise ValueError("Invalid operation provided.")
python
def autosolve(equation): """ Automatically solve an easy maths problem. :type equation: string :param equation: The equation to calculate. >>> autosolve("300 + 600") 900 """ try: # Try to set a variable to an integer num1 = int(equation.split(" ")[0]) except ValueError: # Try to set a variable to a decimal num1 = float(equation.split(" ")[0]) try: # Try to set a variable to an integer num2 = int(equation.split(" ")[2]) except ValueError: # Try to set a variable to a decimal num2 = float(equation.split(" ")[2]) # If the lowercase version of the operator is '+', 'plus' or 'add' if equation.split(" ")[1].lower() in ["+", "plus", "add"]: # Return the answer return num1 + num2 # If the lowercase version of the operator is '-', 'minus' or 'subtract' elif equation.split(" ")[1].lower() in ["-", "minus", "subtract"]: # Return the answer return num1 - num2 # If the lowercase version of the operator is '*', 'times', 'multiply' elif equation.split(" ")[1].lower() in ["*", "times", "multiply"]: # Return the answer return num1 * num2 # If the lowercase version of the operator is '/', 'divide' or 'quotient' elif equation.split(" ")[1].lower() in ["/", "divide", "quotient"]: # Return the answer return num1 / num2 # If the lowercase version of the operator is '%, 'remainder' or 'rem' elif equation.split(" ")[1].lower() in ["%", "remainder", "rem"]: # Return the answer return num1 % num2 # Raise a warning raise ValueError("Invalid operation provided.")
[ "def", "autosolve", "(", "equation", ")", ":", "try", ":", "# Try to set a variable to an integer", "num1", "=", "int", "(", "equation", ".", "split", "(", "\" \"", ")", "[", "0", "]", ")", "except", "ValueError", ":", "# Try to set a variable to a decimal", "nu...
Automatically solve an easy maths problem. :type equation: string :param equation: The equation to calculate. >>> autosolve("300 + 600") 900
[ "Automatically", "solve", "an", "easy", "maths", "problem", "." ]
train
https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L920-L978
Richienb/quilt
src/quilt_lang/__init__.py
autohard
def autohard(equation): """ Automatically solve a hard maths problem. :type equation: string :param equation: The equation to solve. >>> autohard("log 10") 2.302585092994046 """ try: # Try to set a variable to an integer num1 = int(equation.split(" ")[1]) except ValueError: # Try to set a variable to a decimal num1 = float(equation.split(" ")[1]) # If the lowercase version of the operation equals 'log' if equation.split(" ")[0].lower() == "log": # Return the answer return math.log(num1) # If the lowercase version of the operation equals 'acos' elif equation.split(" ")[0].lower() == "acos": # Return the answer return math.acos(num1) # If the lowercase version of the operation equals 'asin' elif equation.split(" ")[0].lower() == "asin": # Return the answer return math.asin(num1) # If the lowercase version of the operation equals 'atan' elif equation.split(" ")[0].lower() == "atan": # Return the answer return math.atan(num1) # If the lowercase version of the operation equals 'cos' elif equation.split(" ")[0].lower() == "cos": # Return the answer return math.cos(num1) # If the lowercase version of the operation equals 'hypot' elif equation.split(" ")[0].lower() == "hypot": try: # Try to set a variable to an integer num2 = int(equation.split(" ")[2]) except ValueError: # Try to set a variable to an decimal num2 = float(equation.split(" ")[2]) # Return the answer return math.hypot(num1, num2) # If the lowercase version of the operation equals 'sin' elif equation.split(" ")[0].lower() == "sin": # Return the answer return math.sin(num1) # If the lowercase version of the operation equals 'tan' elif equation.split(" ")[0].lower() == "tan": # Return the answer return math.tan(num1) # Raise a warning raise ValueError("Invalid operation entered.")
python
def autohard(equation): """ Automatically solve a hard maths problem. :type equation: string :param equation: The equation to solve. >>> autohard("log 10") 2.302585092994046 """ try: # Try to set a variable to an integer num1 = int(equation.split(" ")[1]) except ValueError: # Try to set a variable to a decimal num1 = float(equation.split(" ")[1]) # If the lowercase version of the operation equals 'log' if equation.split(" ")[0].lower() == "log": # Return the answer return math.log(num1) # If the lowercase version of the operation equals 'acos' elif equation.split(" ")[0].lower() == "acos": # Return the answer return math.acos(num1) # If the lowercase version of the operation equals 'asin' elif equation.split(" ")[0].lower() == "asin": # Return the answer return math.asin(num1) # If the lowercase version of the operation equals 'atan' elif equation.split(" ")[0].lower() == "atan": # Return the answer return math.atan(num1) # If the lowercase version of the operation equals 'cos' elif equation.split(" ")[0].lower() == "cos": # Return the answer return math.cos(num1) # If the lowercase version of the operation equals 'hypot' elif equation.split(" ")[0].lower() == "hypot": try: # Try to set a variable to an integer num2 = int(equation.split(" ")[2]) except ValueError: # Try to set a variable to an decimal num2 = float(equation.split(" ")[2]) # Return the answer return math.hypot(num1, num2) # If the lowercase version of the operation equals 'sin' elif equation.split(" ")[0].lower() == "sin": # Return the answer return math.sin(num1) # If the lowercase version of the operation equals 'tan' elif equation.split(" ")[0].lower() == "tan": # Return the answer return math.tan(num1) # Raise a warning raise ValueError("Invalid operation entered.")
[ "def", "autohard", "(", "equation", ")", ":", "try", ":", "# Try to set a variable to an integer", "num1", "=", "int", "(", "equation", ".", "split", "(", "\" \"", ")", "[", "1", "]", ")", "except", "ValueError", ":", "# Try to set a variable to a decimal", "num...
Automatically solve a hard maths problem. :type equation: string :param equation: The equation to solve. >>> autohard("log 10") 2.302585092994046
[ "Automatically", "solve", "a", "hard", "maths", "problem", "." ]
train
https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L981-L1049
Richienb/quilt
src/quilt_lang/__init__.py
equation
def equation(operation, firstnum, secondnum): """ Solve a simple maths equation manually """ if operation == 'plus': return firstnum + secondnum elif operation == 'minus': return firstnum - secondnum elif operation == 'multiply': return firstnum * secondnum elif operation == 'divide': if not secondnum == 0: return firstnum / secondnum raise ZeroDivisionError("Unable to divide by 0.") raise ValueError('Invalid operation provided.')
python
def equation(operation, firstnum, secondnum): """ Solve a simple maths equation manually """ if operation == 'plus': return firstnum + secondnum elif operation == 'minus': return firstnum - secondnum elif operation == 'multiply': return firstnum * secondnum elif operation == 'divide': if not secondnum == 0: return firstnum / secondnum raise ZeroDivisionError("Unable to divide by 0.") raise ValueError('Invalid operation provided.')
[ "def", "equation", "(", "operation", ",", "firstnum", ",", "secondnum", ")", ":", "if", "operation", "==", "'plus'", ":", "return", "firstnum", "+", "secondnum", "elif", "operation", "==", "'minus'", ":", "return", "firstnum", "-", "secondnum", "elif", "oper...
Solve a simple maths equation manually
[ "Solve", "a", "simple", "maths", "equation", "manually" ]
train
https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L1052-L1066
Richienb/quilt
src/quilt_lang/__init__.py
scientific
def scientific(number, operation, number2=None, logbase=10): """ Solve scientific operations manually """ if operation == 'log': return math.log(number, logbase) elif operation == 'acos': return math.acos(number) elif operation == 'asin': return math.asin(number) elif operation == 'atan': return math.atan(number) elif operation == 'cos': return math.cos(number) elif operation == 'hypot': return math.hypot(number, number2) elif operation == 'sin': return math.sin(number) elif operation == 'tan': return math.tan(number)
python
def scientific(number, operation, number2=None, logbase=10): """ Solve scientific operations manually """ if operation == 'log': return math.log(number, logbase) elif operation == 'acos': return math.acos(number) elif operation == 'asin': return math.asin(number) elif operation == 'atan': return math.atan(number) elif operation == 'cos': return math.cos(number) elif operation == 'hypot': return math.hypot(number, number2) elif operation == 'sin': return math.sin(number) elif operation == 'tan': return math.tan(number)
[ "def", "scientific", "(", "number", ",", "operation", ",", "number2", "=", "None", ",", "logbase", "=", "10", ")", ":", "if", "operation", "==", "'log'", ":", "return", "math", ".", "log", "(", "number", ",", "logbase", ")", "elif", "operation", "==", ...
Solve scientific operations manually
[ "Solve", "scientific", "operations", "manually" ]
train
https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L1069-L1088
Richienb/quilt
src/quilt_lang/__init__.py
fracsimplify
def fracsimplify(numerator, denominator): """ Simplify a fraction. :type numerator: integer :param numerator: The numerator of the fraction to simplify :type denominator: integer :param denominator: The denominator of the fraction to simplify :return: The simplified fraction :rtype: list """ # If the numerator is the same as the denominator if numerator == denominator: # Return the most simplified fraction return '1/1' # If the numerator is larger than the denominator elif int(numerator) > int(denominator): # Set the limit to half of the numerator limit = int(numerator / 2) elif int(numerator) < int(denominator): # Set the limit to half of the denominator limit = int(denominator / 2) # For each item in range from 2 to the limit for i in range(2, limit): # Set the number to check as the limit minus i checknum = limit - i # If the number is divisible by the numerator and denominator if numerator % checknum == 0 and denominator % checknum == 0: # Set the numerator to half of the number numerator = numerator / checknum # Set the denominator to half of the number denominator = denominator / checknum # Return the integer version of the numerator and denominator return [int(numerator), int(denominator)]
python
def fracsimplify(numerator, denominator): """ Simplify a fraction. :type numerator: integer :param numerator: The numerator of the fraction to simplify :type denominator: integer :param denominator: The denominator of the fraction to simplify :return: The simplified fraction :rtype: list """ # If the numerator is the same as the denominator if numerator == denominator: # Return the most simplified fraction return '1/1' # If the numerator is larger than the denominator elif int(numerator) > int(denominator): # Set the limit to half of the numerator limit = int(numerator / 2) elif int(numerator) < int(denominator): # Set the limit to half of the denominator limit = int(denominator / 2) # For each item in range from 2 to the limit for i in range(2, limit): # Set the number to check as the limit minus i checknum = limit - i # If the number is divisible by the numerator and denominator if numerator % checknum == 0 and denominator % checknum == 0: # Set the numerator to half of the number numerator = numerator / checknum # Set the denominator to half of the number denominator = denominator / checknum # Return the integer version of the numerator and denominator return [int(numerator), int(denominator)]
[ "def", "fracsimplify", "(", "numerator", ",", "denominator", ")", ":", "# If the numerator is the same as the denominator", "if", "numerator", "==", "denominator", ":", "# Return the most simplified fraction", "return", "'1/1'", "# If the numerator is larger than the denominator", ...
Simplify a fraction. :type numerator: integer :param numerator: The numerator of the fraction to simplify :type denominator: integer :param denominator: The denominator of the fraction to simplify :return: The simplified fraction :rtype: list
[ "Simplify", "a", "fraction", "." ]
train
https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L1091-L1132