repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
peterwittek/ncpol2sdpa
ncpol2sdpa/steering_hierarchy.py
SteeringHierarchy.set_objective
def set_objective(self, objective, extraobjexpr=None): """Set or change the objective function of the polynomial optimization problem. :param objective: Describes the objective function. :type objective: :class:`sympy.core.expr.Expr` :param extraobjexpr: Optional parameter of a string expression of a linear combination of moment matrix elements to be included in the objective function :type extraobjexpr: str. """ if objective is not None and self.matrix_var_dim is not None: facvar = self.__get_trace_facvar(objective) self.obj_facvar = facvar[1:] self.constant_term = facvar[0] if self.verbose > 0 and facvar[0] != 0: print("Warning: The objective function has a non-zero %s " "constant term. It is not included in the SDP objective." % facvar[0]) else: super(SteeringHierarchy, self).\ set_objective(objective, extraobjexpr=extraobjexpr)
python
def set_objective(self, objective, extraobjexpr=None): """Set or change the objective function of the polynomial optimization problem. :param objective: Describes the objective function. :type objective: :class:`sympy.core.expr.Expr` :param extraobjexpr: Optional parameter of a string expression of a linear combination of moment matrix elements to be included in the objective function :type extraobjexpr: str. """ if objective is not None and self.matrix_var_dim is not None: facvar = self.__get_trace_facvar(objective) self.obj_facvar = facvar[1:] self.constant_term = facvar[0] if self.verbose > 0 and facvar[0] != 0: print("Warning: The objective function has a non-zero %s " "constant term. It is not included in the SDP objective." % facvar[0]) else: super(SteeringHierarchy, self).\ set_objective(objective, extraobjexpr=extraobjexpr)
[ "def", "set_objective", "(", "self", ",", "objective", ",", "extraobjexpr", "=", "None", ")", ":", "if", "objective", "is", "not", "None", "and", "self", ".", "matrix_var_dim", "is", "not", "None", ":", "facvar", "=", "self", ".", "__get_trace_facvar", "("...
Set or change the objective function of the polynomial optimization problem. :param objective: Describes the objective function. :type objective: :class:`sympy.core.expr.Expr` :param extraobjexpr: Optional parameter of a string expression of a linear combination of moment matrix elements to be included in the objective function :type extraobjexpr: str.
[ "Set", "or", "change", "the", "objective", "function", "of", "the", "polynomial", "optimization", "problem", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/steering_hierarchy.py#L221-L242
train
peterwittek/ncpol2sdpa
ncpol2sdpa/steering_hierarchy.py
SteeringHierarchy._calculate_block_structure
def _calculate_block_structure(self, inequalities, equalities, momentinequalities, momentequalities, extramomentmatrix, removeequalities, block_struct=None): """Calculates the block_struct array for the output file. """ super(SteeringHierarchy, self).\ _calculate_block_structure(inequalities, equalities, momentinequalities, momentequalities, extramomentmatrix, removeequalities) if self.matrix_var_dim is not None: self.block_struct = [self.matrix_var_dim*bs for bs in self.block_struct]
python
def _calculate_block_structure(self, inequalities, equalities, momentinequalities, momentequalities, extramomentmatrix, removeequalities, block_struct=None): """Calculates the block_struct array for the output file. """ super(SteeringHierarchy, self).\ _calculate_block_structure(inequalities, equalities, momentinequalities, momentequalities, extramomentmatrix, removeequalities) if self.matrix_var_dim is not None: self.block_struct = [self.matrix_var_dim*bs for bs in self.block_struct]
[ "def", "_calculate_block_structure", "(", "self", ",", "inequalities", ",", "equalities", ",", "momentinequalities", ",", "momentequalities", ",", "extramomentmatrix", ",", "removeequalities", ",", "block_struct", "=", "None", ")", ":", "super", "(", "SteeringHierarch...
Calculates the block_struct array for the output file.
[ "Calculates", "the", "block_struct", "array", "for", "the", "output", "file", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/steering_hierarchy.py#L244-L256
train
peterwittek/ncpol2sdpa
ncpol2sdpa/steering_hierarchy.py
SteeringHierarchy.write_to_file
def write_to_file(self, filename, filetype=None): """Write the relaxation to a file. :param filename: The name of the file to write to. The type can be autodetected from the extension: .dat-s for SDPA, .task for mosek, .csv for human readable format, or .txt for a symbolic export :type filename: str. :param filetype: Optional parameter to define the filetype. It can be "sdpa" for SDPA , "mosek" for Mosek, "csv" for human readable format, or "txt" for a symbolic export. :type filetype: str. """ if filetype == "txt" and not filename.endswith(".txt"): raise Exception("TXT files must have .txt extension!") elif filetype is None and filename.endswith(".txt"): filetype = "txt" else: return super(SteeringHierarchy, self).write_to_file(filename, filetype=filetype) tempfile_ = tempfile.NamedTemporaryFile() tmp_filename = tempfile_.name tempfile_.close() tmp_dats_filename = tmp_filename + ".dat-s" write_to_sdpa(self, tmp_dats_filename) f = open(tmp_dats_filename, 'r') f.readline();f.readline();f.readline() blocks = ((f.readline().strip().split(" = ")[0])[1:-1]).split(", ") block_offset, matrix_size = [0], 0 for block in blocks: matrix_size += abs(int(block)) block_offset.append(matrix_size) f.readline() matrix = [[0 for _ in range(matrix_size)] for _ in range(matrix_size)] for line in f: entry = line.strip().split("\t") var, block = int(entry[0]), int(entry[1])-1 row, column = int(entry[2]) - 1, int(entry[3]) - 1 value = float(entry[4]) offset = block_offset[block] matrix[offset+row][offset+column] = int(value*var) matrix[offset+column][offset+row] = int(value*var) f.close() f = open(filename, 'w') for matrix_line in matrix: f.write(str(matrix_line).replace('[', '').replace(']', '') + '\n') f.close() os.remove(tmp_dats_filename)
python
def write_to_file(self, filename, filetype=None): """Write the relaxation to a file. :param filename: The name of the file to write to. The type can be autodetected from the extension: .dat-s for SDPA, .task for mosek, .csv for human readable format, or .txt for a symbolic export :type filename: str. :param filetype: Optional parameter to define the filetype. It can be "sdpa" for SDPA , "mosek" for Mosek, "csv" for human readable format, or "txt" for a symbolic export. :type filetype: str. """ if filetype == "txt" and not filename.endswith(".txt"): raise Exception("TXT files must have .txt extension!") elif filetype is None and filename.endswith(".txt"): filetype = "txt" else: return super(SteeringHierarchy, self).write_to_file(filename, filetype=filetype) tempfile_ = tempfile.NamedTemporaryFile() tmp_filename = tempfile_.name tempfile_.close() tmp_dats_filename = tmp_filename + ".dat-s" write_to_sdpa(self, tmp_dats_filename) f = open(tmp_dats_filename, 'r') f.readline();f.readline();f.readline() blocks = ((f.readline().strip().split(" = ")[0])[1:-1]).split(", ") block_offset, matrix_size = [0], 0 for block in blocks: matrix_size += abs(int(block)) block_offset.append(matrix_size) f.readline() matrix = [[0 for _ in range(matrix_size)] for _ in range(matrix_size)] for line in f: entry = line.strip().split("\t") var, block = int(entry[0]), int(entry[1])-1 row, column = int(entry[2]) - 1, int(entry[3]) - 1 value = float(entry[4]) offset = block_offset[block] matrix[offset+row][offset+column] = int(value*var) matrix[offset+column][offset+row] = int(value*var) f.close() f = open(filename, 'w') for matrix_line in matrix: f.write(str(matrix_line).replace('[', '').replace(']', '') + '\n') f.close() os.remove(tmp_dats_filename)
[ "def", "write_to_file", "(", "self", ",", "filename", ",", "filetype", "=", "None", ")", ":", "if", "filetype", "==", "\"txt\"", "and", "not", "filename", ".", "endswith", "(", "\".txt\"", ")", ":", "raise", "Exception", "(", "\"TXT files must have .txt extens...
Write the relaxation to a file. :param filename: The name of the file to write to. The type can be autodetected from the extension: .dat-s for SDPA, .task for mosek, .csv for human readable format, or .txt for a symbolic export :type filename: str. :param filetype: Optional parameter to define the filetype. It can be "sdpa" for SDPA , "mosek" for Mosek, "csv" for human readable format, or "txt" for a symbolic export. :type filetype: str.
[ "Write", "the", "relaxation", "to", "a", "file", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/steering_hierarchy.py#L268-L315
train
laike9m/ezcf
ezcf/_base.py
BaseFinder.get_outerframe_skip_importlib_frame
def get_outerframe_skip_importlib_frame(level): """ There's a bug in Python3.4+, see http://bugs.python.org/issue23773, remove this and use sys._getframe(3) when bug is fixed """ if sys.version_info < (3, 4): return sys._getframe(level) else: currentframe = inspect.currentframe() levelup = 0 while levelup < level: currentframe = currentframe.f_back if currentframe.f_globals['__name__'] == 'importlib._bootstrap': continue else: levelup += 1 return currentframe
python
def get_outerframe_skip_importlib_frame(level): """ There's a bug in Python3.4+, see http://bugs.python.org/issue23773, remove this and use sys._getframe(3) when bug is fixed """ if sys.version_info < (3, 4): return sys._getframe(level) else: currentframe = inspect.currentframe() levelup = 0 while levelup < level: currentframe = currentframe.f_back if currentframe.f_globals['__name__'] == 'importlib._bootstrap': continue else: levelup += 1 return currentframe
[ "def", "get_outerframe_skip_importlib_frame", "(", "level", ")", ":", "if", "sys", ".", "version_info", "<", "(", "3", ",", "4", ")", ":", "return", "sys", ".", "_getframe", "(", "level", ")", "else", ":", "currentframe", "=", "inspect", ".", "currentframe...
There's a bug in Python3.4+, see http://bugs.python.org/issue23773, remove this and use sys._getframe(3) when bug is fixed
[ "There", "s", "a", "bug", "in", "Python3", ".", "4", "+", "see", "http", ":", "//", "bugs", ".", "python", ".", "org", "/", "issue23773", "remove", "this", "and", "use", "sys", ".", "_getframe", "(", "3", ")", "when", "bug", "is", "fixed" ]
30b0f7ecfd4062e9b9a2f8f13ae1f2fd9f21fa12
https://github.com/laike9m/ezcf/blob/30b0f7ecfd4062e9b9a2f8f13ae1f2fd9f21fa12/ezcf/_base.py#L46-L62
train
kmn/coincheck
coincheck/market.py
Market.public_api
def public_api(self,url): ''' template function of public api''' try : url in api_urls return ast.literal_eval(requests.get(base_url + api_urls.get(url)).text) except Exception as e: print(e)
python
def public_api(self,url): ''' template function of public api''' try : url in api_urls return ast.literal_eval(requests.get(base_url + api_urls.get(url)).text) except Exception as e: print(e)
[ "def", "public_api", "(", "self", ",", "url", ")", ":", "try", ":", "url", "in", "api_urls", "return", "ast", ".", "literal_eval", "(", "requests", ".", "get", "(", "base_url", "+", "api_urls", ".", "get", "(", "url", ")", ")", ".", "text", ")", "e...
template function of public api
[ "template", "function", "of", "public", "api" ]
4e1062f1e564cddceec2f6fb4d70fe3a3ab645bc
https://github.com/kmn/coincheck/blob/4e1062f1e564cddceec2f6fb4d70fe3a3ab645bc/coincheck/market.py#L19-L25
train
bpython/curtsies
curtsies/escseqparse.py
parse
def parse(s): r""" Returns a list of strings or format dictionaries to describe the strings. May raise a ValueError if it can't be parsed. >>> parse(">>> []") ['>>> []'] >>> #parse("\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m") """ stuff = [] rest = s while True: front, token, rest = peel_off_esc_code(rest) if front: stuff.append(front) if token: try: tok = token_type(token) if tok: stuff.extend(tok) except ValueError: raise ValueError("Can't parse escape sequence: %r %r %r %r" % (s, repr(front), token, repr(rest))) if not rest: break return stuff
python
def parse(s): r""" Returns a list of strings or format dictionaries to describe the strings. May raise a ValueError if it can't be parsed. >>> parse(">>> []") ['>>> []'] >>> #parse("\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m") """ stuff = [] rest = s while True: front, token, rest = peel_off_esc_code(rest) if front: stuff.append(front) if token: try: tok = token_type(token) if tok: stuff.extend(tok) except ValueError: raise ValueError("Can't parse escape sequence: %r %r %r %r" % (s, repr(front), token, repr(rest))) if not rest: break return stuff
[ "def", "parse", "(", "s", ")", ":", "stuff", "=", "[", "]", "rest", "=", "s", "while", "True", ":", "front", ",", "token", ",", "rest", "=", "peel_off_esc_code", "(", "rest", ")", "if", "front", ":", "stuff", ".", "append", "(", "front", ")", "if...
r""" Returns a list of strings or format dictionaries to describe the strings. May raise a ValueError if it can't be parsed. >>> parse(">>> []") ['>>> []'] >>> #parse("\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m")
[ "r", "Returns", "a", "list", "of", "strings", "or", "format", "dictionaries", "to", "describe", "the", "strings", "." ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/escseqparse.py#L23-L48
train
bpython/curtsies
curtsies/escseqparse.py
peel_off_esc_code
def peel_off_esc_code(s): r"""Returns processed text, the next token, and unprocessed text >>> front, d, rest = peel_off_esc_code('somestuff') >>> front, rest ('some', 'stuff') >>> d == {'numbers': [2], 'command': 'A', 'intermed': '', 'private': '', 'csi': '\x1b[', 'seq': '\x1b[2A'} True """ p = r"""(?P<front>.*?) (?P<seq> (?P<csi> (?:[]\[) | ["""+'\x9b' + r"""]) (?P<private>) (?P<numbers> (?:\d+;)* (?:\d+)?) (?P<intermed>""" + '[\x20-\x2f]*)' + r""" (?P<command>""" + '[\x40-\x7e]))' + r""" (?P<rest>.*)""" m1 = re.match(p, s, re.VERBOSE) # multibyte esc seq m2 = re.match('(?P<front>.*?)(?P<seq>(?P<csi>)(?P<command>[\x40-\x5f]))(?P<rest>.*)', s) # 2 byte escape sequence if m1 and m2: m = m1 if len(m1.groupdict()['front']) <= len(m2.groupdict()['front']) else m2 # choose the match which has less processed text in order to get the # first escape sequence elif m1: m = m1 elif m2: m = m2 else: m = None if m: d = m.groupdict() del d['front'] del d['rest'] if 'numbers' in d and all(d['numbers'].split(';')): d['numbers'] = [int(x) for x in d['numbers'].split(';')] return m.groupdict()['front'], d, m.groupdict()['rest'] else: return s, None, ''
python
def peel_off_esc_code(s): r"""Returns processed text, the next token, and unprocessed text >>> front, d, rest = peel_off_esc_code('somestuff') >>> front, rest ('some', 'stuff') >>> d == {'numbers': [2], 'command': 'A', 'intermed': '', 'private': '', 'csi': '\x1b[', 'seq': '\x1b[2A'} True """ p = r"""(?P<front>.*?) (?P<seq> (?P<csi> (?:[]\[) | ["""+'\x9b' + r"""]) (?P<private>) (?P<numbers> (?:\d+;)* (?:\d+)?) (?P<intermed>""" + '[\x20-\x2f]*)' + r""" (?P<command>""" + '[\x40-\x7e]))' + r""" (?P<rest>.*)""" m1 = re.match(p, s, re.VERBOSE) # multibyte esc seq m2 = re.match('(?P<front>.*?)(?P<seq>(?P<csi>)(?P<command>[\x40-\x5f]))(?P<rest>.*)', s) # 2 byte escape sequence if m1 and m2: m = m1 if len(m1.groupdict()['front']) <= len(m2.groupdict()['front']) else m2 # choose the match which has less processed text in order to get the # first escape sequence elif m1: m = m1 elif m2: m = m2 else: m = None if m: d = m.groupdict() del d['front'] del d['rest'] if 'numbers' in d and all(d['numbers'].split(';')): d['numbers'] = [int(x) for x in d['numbers'].split(';')] return m.groupdict()['front'], d, m.groupdict()['rest'] else: return s, None, ''
[ "def", "peel_off_esc_code", "(", "s", ")", ":", "p", "=", "r\"\"\"(?P<front>.*?)\n (?P<seq>\n (?P<csi>\n (?:[\u001b]\\[)\n |\n [\"\"\"", "+", "'\\x9b'", "+", "r\"\"\"])\n (?P<private>)\n ...
r"""Returns processed text, the next token, and unprocessed text >>> front, d, rest = peel_off_esc_code('somestuff') >>> front, rest ('some', 'stuff') >>> d == {'numbers': [2], 'command': 'A', 'intermed': '', 'private': '', 'csi': '\x1b[', 'seq': '\x1b[2A'} True
[ "r", "Returns", "processed", "text", "the", "next", "token", "and", "unprocessed", "text" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/escseqparse.py#L51-L92
train
bpython/curtsies
curtsies/events.py
get_key
def get_key(bytes_, encoding, keynames='curtsies', full=False): """Return key pressed from bytes_ or None Return a key name or None meaning it's an incomplete sequence of bytes (more bytes needed to determine the key pressed) encoding is how the bytes should be translated to unicode - it should match the terminal encoding. keynames is a string describing how keys should be named: * curtsies uses unicode strings like <F8> * curses uses unicode strings similar to those returned by the Python ncurses window.getkey function, like KEY_F(8), plus a nonstandard representation of meta keys (bytes 128-255) because returning the corresponding unicode code point would be indistinguishable from the multibyte sequence that encodes that character in the current encoding * bytes returns the original bytes from stdin (NOT unicode) if full, match a key even if it could be a prefix to another key (useful for detecting a plain escape key for instance, since escape is also a prefix to a bunch of char sequences for other keys) Events are subclasses of Event, or unicode strings Precondition: get_key(prefix, keynames) is None for all proper prefixes of bytes. This means get_key should be called on progressively larger inputs (for 'asdf', first on 'a', then on 'as', then on 'asd' - until a non-None value is returned) """ if not all(isinstance(c, type(b'')) for c in bytes_): raise ValueError("get key expects bytes, got %r" % bytes_) # expects raw bytes if keynames not in ['curtsies', 'curses', 'bytes']: raise ValueError("keynames must be one of 'curtsies', 'curses' or 'bytes'") seq = b''.join(bytes_) if len(seq) > MAX_KEYPRESS_SIZE: raise ValueError('unable to decode bytes %r' % seq) def key_name(): if keynames == 'curses': if seq in CURSES_NAMES: # may not be here (and still not decodable) curses names incomplete return CURSES_NAMES[seq] # Otherwise, there's no special curses name for this try: return seq.decode(encoding) # for normal decodable text or a special curtsies sequence with bytes that can be decoded except UnicodeDecodeError: # this sequence can't be decoded with this encoding, so we need to represent the bytes if len(seq) == 1: return u'x%02X' % ord(seq) #TODO figure out a better thing to return here else: raise NotImplementedError("are multibyte unnameable sequences possible?") return u'bytes: ' + u'-'.join(u'x%02X' % ord(seq[i:i+1]) for i in range(len(seq))) #TODO if this isn't possible, return multiple meta keys as a paste event if paste events enabled elif keynames == 'curtsies': if seq in CURTSIES_NAMES: return CURTSIES_NAMES[seq] return seq.decode(encoding) #assumes that curtsies names are a subset of curses ones else: assert keynames == 'bytes' return seq key_known = seq in CURTSIES_NAMES or seq in CURSES_NAMES or decodable(seq, encoding) if full and key_known: return key_name() elif seq in KEYMAP_PREFIXES or could_be_unfinished_char(seq, encoding): return None # need more input to make up a full keypress elif key_known: return key_name() else: seq.decode(encoding) # this will raise a unicode error (they're annoying to raise ourselves) assert False, 'should have raised an unicode decode error'
python
def get_key(bytes_, encoding, keynames='curtsies', full=False): """Return key pressed from bytes_ or None Return a key name or None meaning it's an incomplete sequence of bytes (more bytes needed to determine the key pressed) encoding is how the bytes should be translated to unicode - it should match the terminal encoding. keynames is a string describing how keys should be named: * curtsies uses unicode strings like <F8> * curses uses unicode strings similar to those returned by the Python ncurses window.getkey function, like KEY_F(8), plus a nonstandard representation of meta keys (bytes 128-255) because returning the corresponding unicode code point would be indistinguishable from the multibyte sequence that encodes that character in the current encoding * bytes returns the original bytes from stdin (NOT unicode) if full, match a key even if it could be a prefix to another key (useful for detecting a plain escape key for instance, since escape is also a prefix to a bunch of char sequences for other keys) Events are subclasses of Event, or unicode strings Precondition: get_key(prefix, keynames) is None for all proper prefixes of bytes. This means get_key should be called on progressively larger inputs (for 'asdf', first on 'a', then on 'as', then on 'asd' - until a non-None value is returned) """ if not all(isinstance(c, type(b'')) for c in bytes_): raise ValueError("get key expects bytes, got %r" % bytes_) # expects raw bytes if keynames not in ['curtsies', 'curses', 'bytes']: raise ValueError("keynames must be one of 'curtsies', 'curses' or 'bytes'") seq = b''.join(bytes_) if len(seq) > MAX_KEYPRESS_SIZE: raise ValueError('unable to decode bytes %r' % seq) def key_name(): if keynames == 'curses': if seq in CURSES_NAMES: # may not be here (and still not decodable) curses names incomplete return CURSES_NAMES[seq] # Otherwise, there's no special curses name for this try: return seq.decode(encoding) # for normal decodable text or a special curtsies sequence with bytes that can be decoded except UnicodeDecodeError: # this sequence can't be decoded with this encoding, so we need to represent the bytes if len(seq) == 1: return u'x%02X' % ord(seq) #TODO figure out a better thing to return here else: raise NotImplementedError("are multibyte unnameable sequences possible?") return u'bytes: ' + u'-'.join(u'x%02X' % ord(seq[i:i+1]) for i in range(len(seq))) #TODO if this isn't possible, return multiple meta keys as a paste event if paste events enabled elif keynames == 'curtsies': if seq in CURTSIES_NAMES: return CURTSIES_NAMES[seq] return seq.decode(encoding) #assumes that curtsies names are a subset of curses ones else: assert keynames == 'bytes' return seq key_known = seq in CURTSIES_NAMES or seq in CURSES_NAMES or decodable(seq, encoding) if full and key_known: return key_name() elif seq in KEYMAP_PREFIXES or could_be_unfinished_char(seq, encoding): return None # need more input to make up a full keypress elif key_known: return key_name() else: seq.decode(encoding) # this will raise a unicode error (they're annoying to raise ourselves) assert False, 'should have raised an unicode decode error'
[ "def", "get_key", "(", "bytes_", ",", "encoding", ",", "keynames", "=", "'curtsies'", ",", "full", "=", "False", ")", ":", "if", "not", "all", "(", "isinstance", "(", "c", ",", "type", "(", "b''", ")", ")", "for", "c", "in", "bytes_", ")", ":", "...
Return key pressed from bytes_ or None Return a key name or None meaning it's an incomplete sequence of bytes (more bytes needed to determine the key pressed) encoding is how the bytes should be translated to unicode - it should match the terminal encoding. keynames is a string describing how keys should be named: * curtsies uses unicode strings like <F8> * curses uses unicode strings similar to those returned by the Python ncurses window.getkey function, like KEY_F(8), plus a nonstandard representation of meta keys (bytes 128-255) because returning the corresponding unicode code point would be indistinguishable from the multibyte sequence that encodes that character in the current encoding * bytes returns the original bytes from stdin (NOT unicode) if full, match a key even if it could be a prefix to another key (useful for detecting a plain escape key for instance, since escape is also a prefix to a bunch of char sequences for other keys) Events are subclasses of Event, or unicode strings Precondition: get_key(prefix, keynames) is None for all proper prefixes of bytes. This means get_key should be called on progressively larger inputs (for 'asdf', first on 'a', then on 'as', then on 'asd' - until a non-None value is returned)
[ "Return", "key", "pressed", "from", "bytes_", "or", "None" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/events.py#L142-L218
train
bpython/curtsies
curtsies/events.py
could_be_unfinished_char
def could_be_unfinished_char(seq, encoding): """Whether seq bytes might create a char in encoding if more bytes were added""" if decodable(seq, encoding): return False # any sensible encoding surely doesn't require lookahead (right?) # (if seq bytes encoding a character, adding another byte shouldn't also encode something) if encodings.codecs.getdecoder('utf8') is encodings.codecs.getdecoder(encoding): return could_be_unfinished_utf8(seq) elif encodings.codecs.getdecoder('ascii') is encodings.codecs.getdecoder(encoding): return False else: return True
python
def could_be_unfinished_char(seq, encoding): """Whether seq bytes might create a char in encoding if more bytes were added""" if decodable(seq, encoding): return False # any sensible encoding surely doesn't require lookahead (right?) # (if seq bytes encoding a character, adding another byte shouldn't also encode something) if encodings.codecs.getdecoder('utf8') is encodings.codecs.getdecoder(encoding): return could_be_unfinished_utf8(seq) elif encodings.codecs.getdecoder('ascii') is encodings.codecs.getdecoder(encoding): return False else: return True
[ "def", "could_be_unfinished_char", "(", "seq", ",", "encoding", ")", ":", "if", "decodable", "(", "seq", ",", "encoding", ")", ":", "return", "False", "# any sensible encoding surely doesn't require lookahead (right?)", "# (if seq bytes encoding a character, adding another byte...
Whether seq bytes might create a char in encoding if more bytes were added
[ "Whether", "seq", "bytes", "might", "create", "a", "char", "in", "encoding", "if", "more", "bytes", "were", "added" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/events.py#L220-L231
train
bpython/curtsies
curtsies/events.py
pp_event
def pp_event(seq): """Returns pretty representation of an Event or keypress""" if isinstance(seq, Event): return str(seq) # Get the original sequence back if seq is a pretty name already rev_curses = dict((v, k) for k, v in CURSES_NAMES.items()) rev_curtsies = dict((v, k) for k, v in CURTSIES_NAMES.items()) if seq in rev_curses: seq = rev_curses[seq] elif seq in rev_curtsies: seq = rev_curtsies[seq] pretty = curtsies_name(seq) if pretty != seq: return pretty return repr(seq).lstrip('u')[1:-1]
python
def pp_event(seq): """Returns pretty representation of an Event or keypress""" if isinstance(seq, Event): return str(seq) # Get the original sequence back if seq is a pretty name already rev_curses = dict((v, k) for k, v in CURSES_NAMES.items()) rev_curtsies = dict((v, k) for k, v in CURTSIES_NAMES.items()) if seq in rev_curses: seq = rev_curses[seq] elif seq in rev_curtsies: seq = rev_curtsies[seq] pretty = curtsies_name(seq) if pretty != seq: return pretty return repr(seq).lstrip('u')[1:-1]
[ "def", "pp_event", "(", "seq", ")", ":", "if", "isinstance", "(", "seq", ",", "Event", ")", ":", "return", "str", "(", "seq", ")", "# Get the original sequence back if seq is a pretty name already", "rev_curses", "=", "dict", "(", "(", "v", ",", "k", ")", "f...
Returns pretty representation of an Event or keypress
[ "Returns", "pretty", "representation", "of", "an", "Event", "or", "keypress" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/events.py#L243-L260
train
chris1610/barnum-proj
barnum/gen_data.py
create_nouns
def create_nouns(max=2): """ Return a string of random nouns up to max number """ nouns = [] for noun in range(0, max): nouns.append(random.choice(noun_list)) return " ".join(nouns)
python
def create_nouns(max=2): """ Return a string of random nouns up to max number """ nouns = [] for noun in range(0, max): nouns.append(random.choice(noun_list)) return " ".join(nouns)
[ "def", "create_nouns", "(", "max", "=", "2", ")", ":", "nouns", "=", "[", "]", "for", "noun", "in", "range", "(", "0", ",", "max", ")", ":", "nouns", ".", "append", "(", "random", ".", "choice", "(", "noun_list", ")", ")", "return", "\" \"", ".",...
Return a string of random nouns up to max number
[ "Return", "a", "string", "of", "random", "nouns", "up", "to", "max", "number" ]
0a38f24bde66373553d02fbf67b733c1d55ada33
https://github.com/chris1610/barnum-proj/blob/0a38f24bde66373553d02fbf67b733c1d55ada33/barnum/gen_data.py#L112-L119
train
chris1610/barnum-proj
barnum/gen_data.py
create_date
def create_date(past=False, max_years_future=10, max_years_past=10): """ Create a random valid date If past, then dates can be in the past If into the future, then no more than max_years into the future If it's not, then it can't be any older than max_years_past """ if past: start = datetime.datetime.today() - datetime.timedelta(days=max_years_past * 365) #Anywhere between 1980 and today plus max_ears num_days = (max_years_future * 365) + start.day else: start = datetime.datetime.today() num_days = max_years_future * 365 random_days = random.randint(1, num_days) random_date = start + datetime.timedelta(days=random_days) return(random_date)
python
def create_date(past=False, max_years_future=10, max_years_past=10): """ Create a random valid date If past, then dates can be in the past If into the future, then no more than max_years into the future If it's not, then it can't be any older than max_years_past """ if past: start = datetime.datetime.today() - datetime.timedelta(days=max_years_past * 365) #Anywhere between 1980 and today plus max_ears num_days = (max_years_future * 365) + start.day else: start = datetime.datetime.today() num_days = max_years_future * 365 random_days = random.randint(1, num_days) random_date = start + datetime.timedelta(days=random_days) return(random_date)
[ "def", "create_date", "(", "past", "=", "False", ",", "max_years_future", "=", "10", ",", "max_years_past", "=", "10", ")", ":", "if", "past", ":", "start", "=", "datetime", ".", "datetime", ".", "today", "(", ")", "-", "datetime", ".", "timedelta", "(...
Create a random valid date If past, then dates can be in the past If into the future, then no more than max_years into the future If it's not, then it can't be any older than max_years_past
[ "Create", "a", "random", "valid", "date", "If", "past", "then", "dates", "can", "be", "in", "the", "past", "If", "into", "the", "future", "then", "no", "more", "than", "max_years", "into", "the", "future", "If", "it", "s", "not", "then", "it", "can", ...
0a38f24bde66373553d02fbf67b733c1d55ada33
https://github.com/chris1610/barnum-proj/blob/0a38f24bde66373553d02fbf67b733c1d55ada33/barnum/gen_data.py#L122-L139
train
chris1610/barnum-proj
barnum/gen_data.py
create_birthday
def create_birthday(min_age=18, max_age=80): """ Create a random birthday fomr someone between the ages of min_age and max_age """ age = random.randint(min_age, max_age) start = datetime.date.today() - datetime.timedelta(days=random.randint(0, 365)) return start - datetime.timedelta(days=age * 365)
python
def create_birthday(min_age=18, max_age=80): """ Create a random birthday fomr someone between the ages of min_age and max_age """ age = random.randint(min_age, max_age) start = datetime.date.today() - datetime.timedelta(days=random.randint(0, 365)) return start - datetime.timedelta(days=age * 365)
[ "def", "create_birthday", "(", "min_age", "=", "18", ",", "max_age", "=", "80", ")", ":", "age", "=", "random", ".", "randint", "(", "min_age", ",", "max_age", ")", "start", "=", "datetime", ".", "date", ".", "today", "(", ")", "-", "datetime", ".", ...
Create a random birthday fomr someone between the ages of min_age and max_age
[ "Create", "a", "random", "birthday", "fomr", "someone", "between", "the", "ages", "of", "min_age", "and", "max_age" ]
0a38f24bde66373553d02fbf67b733c1d55ada33
https://github.com/chris1610/barnum-proj/blob/0a38f24bde66373553d02fbf67b733c1d55ada33/barnum/gen_data.py#L142-L148
train
chris1610/barnum-proj
barnum/gen_data.py
create_pw
def create_pw(length=8, digits=2, upper=2, lower=2): """Create a random password From Stackoverflow: http://stackoverflow.com/questions/7479442/high-quality-simple-random-password-generator Create a random password with the specified length and no. of digit, upper and lower case letters. :param length: Maximum no. of characters in the password :type length: int :param digits: Minimum no. of digits in the password :type digits: int :param upper: Minimum no. of upper case letters in the password :type upper: int :param lower: Minimum no. of lower case letters in the password :type lower: int :returns: A random password with the above constaints :rtype: str """ seed(time()) lowercase = string.ascii_lowercase uppercase = string.ascii_uppercase letters = string.ascii_letters password = list( chain( (choice(uppercase) for _ in range(upper)), (choice(lowercase) for _ in range(lower)), (choice(string.digits) for _ in range(digits)), (choice(letters) for _ in range((length - digits - upper - lower))) ) ) return "".join(sample(password, len(password)))
python
def create_pw(length=8, digits=2, upper=2, lower=2): """Create a random password From Stackoverflow: http://stackoverflow.com/questions/7479442/high-quality-simple-random-password-generator Create a random password with the specified length and no. of digit, upper and lower case letters. :param length: Maximum no. of characters in the password :type length: int :param digits: Minimum no. of digits in the password :type digits: int :param upper: Minimum no. of upper case letters in the password :type upper: int :param lower: Minimum no. of lower case letters in the password :type lower: int :returns: A random password with the above constaints :rtype: str """ seed(time()) lowercase = string.ascii_lowercase uppercase = string.ascii_uppercase letters = string.ascii_letters password = list( chain( (choice(uppercase) for _ in range(upper)), (choice(lowercase) for _ in range(lower)), (choice(string.digits) for _ in range(digits)), (choice(letters) for _ in range((length - digits - upper - lower))) ) ) return "".join(sample(password, len(password)))
[ "def", "create_pw", "(", "length", "=", "8", ",", "digits", "=", "2", ",", "upper", "=", "2", ",", "lower", "=", "2", ")", ":", "seed", "(", "time", "(", ")", ")", "lowercase", "=", "string", ".", "ascii_lowercase", "uppercase", "=", "string", ".",...
Create a random password From Stackoverflow: http://stackoverflow.com/questions/7479442/high-quality-simple-random-password-generator Create a random password with the specified length and no. of digit, upper and lower case letters. :param length: Maximum no. of characters in the password :type length: int :param digits: Minimum no. of digits in the password :type digits: int :param upper: Minimum no. of upper case letters in the password :type upper: int :param lower: Minimum no. of lower case letters in the password :type lower: int :returns: A random password with the above constaints :rtype: str
[ "Create", "a", "random", "password", "From", "Stackoverflow", ":", "http", ":", "//", "stackoverflow", ".", "com", "/", "questions", "/", "7479442", "/", "high", "-", "quality", "-", "simple", "-", "random", "-", "password", "-", "generator" ]
0a38f24bde66373553d02fbf67b733c1d55ada33
https://github.com/chris1610/barnum-proj/blob/0a38f24bde66373553d02fbf67b733c1d55ada33/barnum/gen_data.py#L189-L227
train
chris1610/barnum-proj
barnum/gen_data.py
show_examples
def show_examples(): """ Run through some simple examples """ first, last = create_name() add = create_street() zip, city, state = create_city_state_zip() phone = create_phone(zip) print(first, last) print(add) print("{0:s} {1:s} {2:s}".format(city, state, zip)) print(phone) print(create_sentence()) print(create_paragraphs(num=3)) print(create_cc_number()) expiry = create_date(max_years_future=3) print("{0:%m/%y}".format(expiry)) print(create_email(name=(first, last))) print("Password: {0:s}".format(create_pw())) print(create_company_name()) print(create_job_title()) print("Born on {0:%m/%d/%Y}".format(create_birthday()))
python
def show_examples(): """ Run through some simple examples """ first, last = create_name() add = create_street() zip, city, state = create_city_state_zip() phone = create_phone(zip) print(first, last) print(add) print("{0:s} {1:s} {2:s}".format(city, state, zip)) print(phone) print(create_sentence()) print(create_paragraphs(num=3)) print(create_cc_number()) expiry = create_date(max_years_future=3) print("{0:%m/%y}".format(expiry)) print(create_email(name=(first, last))) print("Password: {0:s}".format(create_pw())) print(create_company_name()) print(create_job_title()) print("Born on {0:%m/%d/%Y}".format(create_birthday()))
[ "def", "show_examples", "(", ")", ":", "first", ",", "last", "=", "create_name", "(", ")", "add", "=", "create_street", "(", ")", "zip", ",", "city", ",", "state", "=", "create_city_state_zip", "(", ")", "phone", "=", "create_phone", "(", "zip", ")", "...
Run through some simple examples
[ "Run", "through", "some", "simple", "examples" ]
0a38f24bde66373553d02fbf67b733c1d55ada33
https://github.com/chris1610/barnum-proj/blob/0a38f24bde66373553d02fbf67b733c1d55ada33/barnum/gen_data.py#L229-L249
train
peterwittek/ncpol2sdpa
ncpol2sdpa/mosek_utils.py
convert_to_mosek_index
def convert_to_mosek_index(block_struct, row_offsets, block_offsets, row): """MOSEK requires a specific sparse format to define the lower-triangular part of a symmetric matrix. This function does the conversion from the sparse upper triangular matrix format of Ncpol2SDPA. """ block_index, i, j = convert_row_to_sdpa_index(block_struct, row_offsets, row) offset = block_offsets[block_index] ci = offset + i cj = offset + j return cj, ci
python
def convert_to_mosek_index(block_struct, row_offsets, block_offsets, row): """MOSEK requires a specific sparse format to define the lower-triangular part of a symmetric matrix. This function does the conversion from the sparse upper triangular matrix format of Ncpol2SDPA. """ block_index, i, j = convert_row_to_sdpa_index(block_struct, row_offsets, row) offset = block_offsets[block_index] ci = offset + i cj = offset + j return cj, ci
[ "def", "convert_to_mosek_index", "(", "block_struct", ",", "row_offsets", ",", "block_offsets", ",", "row", ")", ":", "block_index", ",", "i", ",", "j", "=", "convert_row_to_sdpa_index", "(", "block_struct", ",", "row_offsets", ",", "row", ")", "offset", "=", ...
MOSEK requires a specific sparse format to define the lower-triangular part of a symmetric matrix. This function does the conversion from the sparse upper triangular matrix format of Ncpol2SDPA.
[ "MOSEK", "requires", "a", "specific", "sparse", "format", "to", "define", "the", "lower", "-", "triangular", "part", "of", "a", "symmetric", "matrix", ".", "This", "function", "does", "the", "conversion", "from", "the", "sparse", "upper", "triangular", "matrix...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/mosek_utils.py#L102-L113
train
peterwittek/ncpol2sdpa
ncpol2sdpa/mosek_utils.py
convert_to_mosek_matrix
def convert_to_mosek_matrix(sdp): """Converts the entire sparse representation of the Fi constraint matrices to sparse MOSEK matrices. """ barci = [] barcj = [] barcval = [] barai = [] baraj = [] baraval = [] for k in range(sdp.n_vars): barai.append([]) baraj.append([]) baraval.append([]) row_offsets = [0] block_offsets = [0] cumulative_sum = 0 cumulative_square_sum = 0 for block_size in sdp.block_struct: cumulative_sum += block_size cumulative_square_sum += block_size ** 2 row_offsets.append(cumulative_square_sum) block_offsets.append(cumulative_sum) for row in range(len(sdp.F.rows)): if len(sdp.F.rows[row]) > 0: col_index = 0 for k in sdp.F.rows[row]: value = sdp.F.data[row][col_index] i, j = convert_to_mosek_index(sdp.block_struct, row_offsets, block_offsets, row) if k > 0: barai[k - 1].append(i) baraj[k - 1].append(j) baraval[k - 1].append(-value) else: barci.append(i) barcj.append(j) barcval.append(value) col_index += 1 return barci, barcj, barcval, barai, baraj, baraval
python
def convert_to_mosek_matrix(sdp): """Converts the entire sparse representation of the Fi constraint matrices to sparse MOSEK matrices. """ barci = [] barcj = [] barcval = [] barai = [] baraj = [] baraval = [] for k in range(sdp.n_vars): barai.append([]) baraj.append([]) baraval.append([]) row_offsets = [0] block_offsets = [0] cumulative_sum = 0 cumulative_square_sum = 0 for block_size in sdp.block_struct: cumulative_sum += block_size cumulative_square_sum += block_size ** 2 row_offsets.append(cumulative_square_sum) block_offsets.append(cumulative_sum) for row in range(len(sdp.F.rows)): if len(sdp.F.rows[row]) > 0: col_index = 0 for k in sdp.F.rows[row]: value = sdp.F.data[row][col_index] i, j = convert_to_mosek_index(sdp.block_struct, row_offsets, block_offsets, row) if k > 0: barai[k - 1].append(i) baraj[k - 1].append(j) baraval[k - 1].append(-value) else: barci.append(i) barcj.append(j) barcval.append(value) col_index += 1 return barci, barcj, barcval, barai, baraj, baraval
[ "def", "convert_to_mosek_matrix", "(", "sdp", ")", ":", "barci", "=", "[", "]", "barcj", "=", "[", "]", "barcval", "=", "[", "]", "barai", "=", "[", "]", "baraj", "=", "[", "]", "baraval", "=", "[", "]", "for", "k", "in", "range", "(", "sdp", "...
Converts the entire sparse representation of the Fi constraint matrices to sparse MOSEK matrices.
[ "Converts", "the", "entire", "sparse", "representation", "of", "the", "Fi", "constraint", "matrices", "to", "sparse", "MOSEK", "matrices", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/mosek_utils.py#L116-L155
train
peterwittek/ncpol2sdpa
ncpol2sdpa/mosek_utils.py
convert_to_mosek
def convert_to_mosek(sdp): """Convert an SDP relaxation to a MOSEK task. :param sdp: The SDP relaxation to convert. :type sdp: :class:`ncpol2sdpa.sdp`. :returns: :class:`mosek.Task`. """ import mosek # Cheat when variables are complex and convert with PICOS if sdp.complex_matrix: from .picos_utils import convert_to_picos Problem = convert_to_picos(sdp).to_real() Problem._make_mosek_instance() task = Problem.msk_task if sdp.verbose > 0: task.set_Stream(mosek.streamtype.log, streamprinter) return task barci, barcj, barcval, barai, baraj, baraval = \ convert_to_mosek_matrix(sdp) bkc = [mosek.boundkey.fx] * sdp.n_vars blc = [-v for v in sdp.obj_facvar] buc = [-v for v in sdp.obj_facvar] env = mosek.Env() task = env.Task(0, 0) if sdp.verbose > 0: task.set_Stream(mosek.streamtype.log, streamprinter) numvar = 0 numcon = len(bkc) BARVARDIM = [sum(sdp.block_struct)] task.appendvars(numvar) task.appendcons(numcon) task.appendbarvars(BARVARDIM) for i in range(numcon): task.putconbound(i, bkc[i], blc[i], buc[i]) symc = task.appendsparsesymmat(BARVARDIM[0], barci, barcj, barcval) task.putbarcj(0, [symc], [1.0]) for i in range(len(barai)): syma = task.appendsparsesymmat(BARVARDIM[0], barai[i], baraj[i], baraval[i]) task.putbaraij(i, 0, [syma], [1.0]) # Input the objective sense (minimize/maximize) task.putobjsense(mosek.objsense.minimize) return task
python
def convert_to_mosek(sdp): """Convert an SDP relaxation to a MOSEK task. :param sdp: The SDP relaxation to convert. :type sdp: :class:`ncpol2sdpa.sdp`. :returns: :class:`mosek.Task`. """ import mosek # Cheat when variables are complex and convert with PICOS if sdp.complex_matrix: from .picos_utils import convert_to_picos Problem = convert_to_picos(sdp).to_real() Problem._make_mosek_instance() task = Problem.msk_task if sdp.verbose > 0: task.set_Stream(mosek.streamtype.log, streamprinter) return task barci, barcj, barcval, barai, baraj, baraval = \ convert_to_mosek_matrix(sdp) bkc = [mosek.boundkey.fx] * sdp.n_vars blc = [-v for v in sdp.obj_facvar] buc = [-v for v in sdp.obj_facvar] env = mosek.Env() task = env.Task(0, 0) if sdp.verbose > 0: task.set_Stream(mosek.streamtype.log, streamprinter) numvar = 0 numcon = len(bkc) BARVARDIM = [sum(sdp.block_struct)] task.appendvars(numvar) task.appendcons(numcon) task.appendbarvars(BARVARDIM) for i in range(numcon): task.putconbound(i, bkc[i], blc[i], buc[i]) symc = task.appendsparsesymmat(BARVARDIM[0], barci, barcj, barcval) task.putbarcj(0, [symc], [1.0]) for i in range(len(barai)): syma = task.appendsparsesymmat(BARVARDIM[0], barai[i], baraj[i], baraval[i]) task.putbaraij(i, 0, [syma], [1.0]) # Input the objective sense (minimize/maximize) task.putobjsense(mosek.objsense.minimize) return task
[ "def", "convert_to_mosek", "(", "sdp", ")", ":", "import", "mosek", "# Cheat when variables are complex and convert with PICOS", "if", "sdp", ".", "complex_matrix", ":", "from", ".", "picos_utils", "import", "convert_to_picos", "Problem", "=", "convert_to_picos", "(", "...
Convert an SDP relaxation to a MOSEK task. :param sdp: The SDP relaxation to convert. :type sdp: :class:`ncpol2sdpa.sdp`. :returns: :class:`mosek.Task`.
[ "Convert", "an", "SDP", "relaxation", "to", "a", "MOSEK", "task", "." ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/mosek_utils.py#L158-L208
train
bpython/curtsies
docs/ansi.py
ANSIColorParser._add_text
def _add_text(self, text): """ If ``text`` is not empty, append a new Text node to the most recent pending node, if there is any, or to the new nodes, if there are no pending nodes. """ if text: if self.pending_nodes: self.pending_nodes[-1].append(nodes.Text(text)) else: self.new_nodes.append(nodes.Text(text))
python
def _add_text(self, text): """ If ``text`` is not empty, append a new Text node to the most recent pending node, if there is any, or to the new nodes, if there are no pending nodes. """ if text: if self.pending_nodes: self.pending_nodes[-1].append(nodes.Text(text)) else: self.new_nodes.append(nodes.Text(text))
[ "def", "_add_text", "(", "self", ",", "text", ")", ":", "if", "text", ":", "if", "self", ".", "pending_nodes", ":", "self", ".", "pending_nodes", "[", "-", "1", "]", ".", "append", "(", "nodes", ".", "Text", "(", "text", ")", ")", "else", ":", "s...
If ``text`` is not empty, append a new Text node to the most recent pending node, if there is any, or to the new nodes, if there are no pending nodes.
[ "If", "text", "is", "not", "empty", "append", "a", "new", "Text", "node", "to", "the", "most", "recent", "pending", "node", "if", "there", "is", "any", "or", "to", "the", "new", "nodes", "if", "there", "are", "no", "pending", "nodes", "." ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/docs/ansi.py#L96-L106
train
bpython/curtsies
setup.py
version
def version(): """Return version string.""" with open(os.path.join('curtsies', '__init__.py')) as input_file: for line in input_file: if line.startswith('__version__'): return ast.parse(line).body[0].value.s
python
def version(): """Return version string.""" with open(os.path.join('curtsies', '__init__.py')) as input_file: for line in input_file: if line.startswith('__version__'): return ast.parse(line).body[0].value.s
[ "def", "version", "(", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "'curtsies'", ",", "'__init__.py'", ")", ")", "as", "input_file", ":", "for", "line", "in", "input_file", ":", "if", "line", ".", "startswith", "(", "'__version_...
Return version string.
[ "Return", "version", "string", "." ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/setup.py#L6-L11
train
bpython/curtsies
curtsies/formatstringarray.py
fsarray
def fsarray(strings, *args, **kwargs): """fsarray(list_of_FmtStrs_or_strings, width=None) -> FSArray Returns a new FSArray of width of the maximum size of the provided strings, or width provided, and height of the number of strings provided. If a width is provided, raises a ValueError if any of the strings are of length greater than this width""" strings = list(strings) if 'width' in kwargs: width = kwargs['width'] del kwargs['width'] if strings and max(len(s) for s in strings) > width: raise ValueError("Those strings won't fit for width %d" % width) else: width = max(len(s) for s in strings) if strings else 0 fstrings = [s if isinstance(s, FmtStr) else fmtstr(s, *args, **kwargs) for s in strings] arr = FSArray(len(fstrings), width, *args, **kwargs) rows = [fs.setslice_with_length(0, len(s), s, width) for fs, s in zip(arr.rows, fstrings)] arr.rows = rows return arr
python
def fsarray(strings, *args, **kwargs): """fsarray(list_of_FmtStrs_or_strings, width=None) -> FSArray Returns a new FSArray of width of the maximum size of the provided strings, or width provided, and height of the number of strings provided. If a width is provided, raises a ValueError if any of the strings are of length greater than this width""" strings = list(strings) if 'width' in kwargs: width = kwargs['width'] del kwargs['width'] if strings and max(len(s) for s in strings) > width: raise ValueError("Those strings won't fit for width %d" % width) else: width = max(len(s) for s in strings) if strings else 0 fstrings = [s if isinstance(s, FmtStr) else fmtstr(s, *args, **kwargs) for s in strings] arr = FSArray(len(fstrings), width, *args, **kwargs) rows = [fs.setslice_with_length(0, len(s), s, width) for fs, s in zip(arr.rows, fstrings)] arr.rows = rows return arr
[ "def", "fsarray", "(", "strings", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "strings", "=", "list", "(", "strings", ")", "if", "'width'", "in", "kwargs", ":", "width", "=", "kwargs", "[", "'width'", "]", "del", "kwargs", "[", "'width'", ...
fsarray(list_of_FmtStrs_or_strings, width=None) -> FSArray Returns a new FSArray of width of the maximum size of the provided strings, or width provided, and height of the number of strings provided. If a width is provided, raises a ValueError if any of the strings are of length greater than this width
[ "fsarray", "(", "list_of_FmtStrs_or_strings", "width", "=", "None", ")", "-", ">", "FSArray" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstringarray.py#L40-L60
train
bpython/curtsies
curtsies/formatstringarray.py
FSArray.diff
def diff(cls, a, b, ignore_formatting=False): """Returns two FSArrays with differences underlined""" def underline(x): return u'\x1b[4m%s\x1b[0m' % (x,) def blink(x): return u'\x1b[5m%s\x1b[0m' % (x,) a_rows = [] b_rows = [] max_width = max([len(row) for row in a] + [len(row) for row in b]) a_lengths = [] b_lengths = [] for a_row, b_row in zip(a, b): a_lengths.append(len(a_row)) b_lengths.append(len(b_row)) extra_a = u'`' * (max_width - len(a_row)) extra_b = u'`' * (max_width - len(b_row)) a_line = u'' b_line = u'' for a_char, b_char in zip(a_row + extra_a, b_row + extra_b): if ignore_formatting: a_char_for_eval = a_char.s if isinstance(a_char, FmtStr) else a_char b_char_for_eval = b_char.s if isinstance(b_char, FmtStr) else b_char else: a_char_for_eval = a_char b_char_for_eval = b_char if a_char_for_eval == b_char_for_eval: a_line += actualize(a_char) b_line += actualize(b_char) else: a_line += underline(blink(actualize(a_char))) b_line += underline(blink(actualize(b_char))) a_rows.append(a_line) b_rows.append(b_line) hdiff = '\n'.join(a_line + u' %3d | %3d ' % (a_len, b_len) + b_line for a_line, b_line, a_len, b_len in zip(a_rows, b_rows, a_lengths, b_lengths)) return hdiff
python
def diff(cls, a, b, ignore_formatting=False): """Returns two FSArrays with differences underlined""" def underline(x): return u'\x1b[4m%s\x1b[0m' % (x,) def blink(x): return u'\x1b[5m%s\x1b[0m' % (x,) a_rows = [] b_rows = [] max_width = max([len(row) for row in a] + [len(row) for row in b]) a_lengths = [] b_lengths = [] for a_row, b_row in zip(a, b): a_lengths.append(len(a_row)) b_lengths.append(len(b_row)) extra_a = u'`' * (max_width - len(a_row)) extra_b = u'`' * (max_width - len(b_row)) a_line = u'' b_line = u'' for a_char, b_char in zip(a_row + extra_a, b_row + extra_b): if ignore_formatting: a_char_for_eval = a_char.s if isinstance(a_char, FmtStr) else a_char b_char_for_eval = b_char.s if isinstance(b_char, FmtStr) else b_char else: a_char_for_eval = a_char b_char_for_eval = b_char if a_char_for_eval == b_char_for_eval: a_line += actualize(a_char) b_line += actualize(b_char) else: a_line += underline(blink(actualize(a_char))) b_line += underline(blink(actualize(b_char))) a_rows.append(a_line) b_rows.append(b_line) hdiff = '\n'.join(a_line + u' %3d | %3d ' % (a_len, b_len) + b_line for a_line, b_line, a_len, b_len in zip(a_rows, b_rows, a_lengths, b_lengths)) return hdiff
[ "def", "diff", "(", "cls", ",", "a", ",", "b", ",", "ignore_formatting", "=", "False", ")", ":", "def", "underline", "(", "x", ")", ":", "return", "u'\\x1b[4m%s\\x1b[0m'", "%", "(", "x", ",", ")", "def", "blink", "(", "x", ")", ":", "return", "u'\\...
Returns two FSArrays with differences underlined
[ "Returns", "two", "FSArrays", "with", "differences", "underlined" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstringarray.py#L139-L171
train
kmn/coincheck
coincheck/order.py
Order.create
def create(self,rate, amount, order_type, pair): ''' create new order function :param rate: float :param amount: float :param order_type: str; set 'buy' or 'sell' :param pair: str; set 'btc_jpy' ''' nonce = nounce() payload = { 'rate': rate, 'amount': amount, 'order_type': order_type, 'pair': pair } url= 'https://coincheck.com/api/exchange/orders' body = 'rate={rate}&amount={amount}&order_type={order_type}&pair={pair}'.format(**payload) message = nonce + url + body signature = hmac.new(self.secret_key.encode('utf-8'), message.encode('utf-8'), hashlib.sha256).hexdigest() headers = { 'ACCESS-KEY' : self.access_key, 'ACCESS-NONCE' : nonce, 'ACCESS-SIGNATURE': signature } r = requests.post(url,headers=headers,data=body) return json.loads(r.text)
python
def create(self,rate, amount, order_type, pair): ''' create new order function :param rate: float :param amount: float :param order_type: str; set 'buy' or 'sell' :param pair: str; set 'btc_jpy' ''' nonce = nounce() payload = { 'rate': rate, 'amount': amount, 'order_type': order_type, 'pair': pair } url= 'https://coincheck.com/api/exchange/orders' body = 'rate={rate}&amount={amount}&order_type={order_type}&pair={pair}'.format(**payload) message = nonce + url + body signature = hmac.new(self.secret_key.encode('utf-8'), message.encode('utf-8'), hashlib.sha256).hexdigest() headers = { 'ACCESS-KEY' : self.access_key, 'ACCESS-NONCE' : nonce, 'ACCESS-SIGNATURE': signature } r = requests.post(url,headers=headers,data=body) return json.loads(r.text)
[ "def", "create", "(", "self", ",", "rate", ",", "amount", ",", "order_type", ",", "pair", ")", ":", "nonce", "=", "nounce", "(", ")", "payload", "=", "{", "'rate'", ":", "rate", ",", "'amount'", ":", "amount", ",", "'order_type'", ":", "order_type", ...
create new order function :param rate: float :param amount: float :param order_type: str; set 'buy' or 'sell' :param pair: str; set 'btc_jpy'
[ "create", "new", "order", "function", ":", "param", "rate", ":", "float", ":", "param", "amount", ":", "float", ":", "param", "order_type", ":", "str", ";", "set", "buy", "or", "sell", ":", "param", "pair", ":", "str", ";", "set", "btc_jpy" ]
4e1062f1e564cddceec2f6fb4d70fe3a3ab645bc
https://github.com/kmn/coincheck/blob/4e1062f1e564cddceec2f6fb4d70fe3a3ab645bc/coincheck/order.py#L20-L43
train
kmn/coincheck
coincheck/order.py
Order.cancel
def cancel(self,order_id): ''' cancel the specified order :param order_id: order_id to be canceled ''' url= 'https://coincheck.com/api/exchange/orders/' + order_id headers = make_header(url,access_key=self.access_key,secret_key=self.secret_key) r = requests.delete(url,headers=headers) return json.loads(r.text)
python
def cancel(self,order_id): ''' cancel the specified order :param order_id: order_id to be canceled ''' url= 'https://coincheck.com/api/exchange/orders/' + order_id headers = make_header(url,access_key=self.access_key,secret_key=self.secret_key) r = requests.delete(url,headers=headers) return json.loads(r.text)
[ "def", "cancel", "(", "self", ",", "order_id", ")", ":", "url", "=", "'https://coincheck.com/api/exchange/orders/'", "+", "order_id", "headers", "=", "make_header", "(", "url", ",", "access_key", "=", "self", ".", "access_key", ",", "secret_key", "=", "self", ...
cancel the specified order :param order_id: order_id to be canceled
[ "cancel", "the", "specified", "order", ":", "param", "order_id", ":", "order_id", "to", "be", "canceled" ]
4e1062f1e564cddceec2f6fb4d70fe3a3ab645bc
https://github.com/kmn/coincheck/blob/4e1062f1e564cddceec2f6fb4d70fe3a3ab645bc/coincheck/order.py#L59-L66
train
kmn/coincheck
coincheck/order.py
Order.history
def history(self): ''' show payment history ''' url= 'https://coincheck.com/api/exchange/orders/transactions' headers = make_header(url,access_key=self.access_key,secret_key=self.secret_key) r = requests.get(url,headers=headers) return json.loads(r.text)
python
def history(self): ''' show payment history ''' url= 'https://coincheck.com/api/exchange/orders/transactions' headers = make_header(url,access_key=self.access_key,secret_key=self.secret_key) r = requests.get(url,headers=headers) return json.loads(r.text)
[ "def", "history", "(", "self", ")", ":", "url", "=", "'https://coincheck.com/api/exchange/orders/transactions'", "headers", "=", "make_header", "(", "url", ",", "access_key", "=", "self", ".", "access_key", ",", "secret_key", "=", "self", ".", "secret_key", ")", ...
show payment history
[ "show", "payment", "history" ]
4e1062f1e564cddceec2f6fb4d70fe3a3ab645bc
https://github.com/kmn/coincheck/blob/4e1062f1e564cddceec2f6fb4d70fe3a3ab645bc/coincheck/order.py#L68-L74
train
mottosso/be
be/vendor/click/_termui_impl.py
_length_hint
def _length_hint(obj): """Returns the length hint of an object.""" try: return len(obj) except TypeError: try: get_hint = type(obj).__length_hint__ except AttributeError: return None try: hint = get_hint(obj) except TypeError: return None if hint is NotImplemented or \ not isinstance(hint, (int, long)) or \ hint < 0: return None return hint
python
def _length_hint(obj): """Returns the length hint of an object.""" try: return len(obj) except TypeError: try: get_hint = type(obj).__length_hint__ except AttributeError: return None try: hint = get_hint(obj) except TypeError: return None if hint is NotImplemented or \ not isinstance(hint, (int, long)) or \ hint < 0: return None return hint
[ "def", "_length_hint", "(", "obj", ")", ":", "try", ":", "return", "len", "(", "obj", ")", "except", "TypeError", ":", "try", ":", "get_hint", "=", "type", "(", "obj", ")", ".", "__length_hint__", "except", "AttributeError", ":", "return", "None", "try",...
Returns the length hint of an object.
[ "Returns", "the", "length", "hint", "of", "an", "object", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/_termui_impl.py#L30-L47
train
mottosso/be
be/vendor/click/_termui_impl.py
pager
def pager(text, color=None): """Decide what method to use for paging through text.""" stdout = _default_text_stdout() if not isatty(sys.stdin) or not isatty(stdout): return _nullpager(stdout, text, color) if 'PAGER' in os.environ: if WIN: return _tempfilepager(text, os.environ['PAGER'], color) return _pipepager(text, os.environ['PAGER'], color) if os.environ.get('TERM') in ('dumb', 'emacs'): return _nullpager(stdout, text, color) if WIN or sys.platform.startswith('os2'): return _tempfilepager(text, 'more <', color) if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0: return _pipepager(text, 'less', color) import tempfile fd, filename = tempfile.mkstemp() os.close(fd) try: if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0: return _pipepager(text, 'more', color) return _nullpager(stdout, text, color) finally: os.unlink(filename)
python
def pager(text, color=None): """Decide what method to use for paging through text.""" stdout = _default_text_stdout() if not isatty(sys.stdin) or not isatty(stdout): return _nullpager(stdout, text, color) if 'PAGER' in os.environ: if WIN: return _tempfilepager(text, os.environ['PAGER'], color) return _pipepager(text, os.environ['PAGER'], color) if os.environ.get('TERM') in ('dumb', 'emacs'): return _nullpager(stdout, text, color) if WIN or sys.platform.startswith('os2'): return _tempfilepager(text, 'more <', color) if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0: return _pipepager(text, 'less', color) import tempfile fd, filename = tempfile.mkstemp() os.close(fd) try: if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0: return _pipepager(text, 'more', color) return _nullpager(stdout, text, color) finally: os.unlink(filename)
[ "def", "pager", "(", "text", ",", "color", "=", "None", ")", ":", "stdout", "=", "_default_text_stdout", "(", ")", "if", "not", "isatty", "(", "sys", ".", "stdin", ")", "or", "not", "isatty", "(", "stdout", ")", ":", "return", "_nullpager", "(", "std...
Decide what method to use for paging through text.
[ "Decide", "what", "method", "to", "use", "for", "paging", "through", "text", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/_termui_impl.py#L255-L279
train
mottosso/be
be/vendor/requests/packages/urllib3/util/retry.py
Retry.from_int
def from_int(cls, retries, redirect=True, default=None): """ Backwards-compatibility for the old retries format.""" if retries is None: retries = default if default is not None else cls.DEFAULT if isinstance(retries, Retry): return retries redirect = bool(redirect) and None new_retries = cls(retries, redirect=redirect) log.debug("Converted retries value: %r -> %r" % (retries, new_retries)) return new_retries
python
def from_int(cls, retries, redirect=True, default=None): """ Backwards-compatibility for the old retries format.""" if retries is None: retries = default if default is not None else cls.DEFAULT if isinstance(retries, Retry): return retries redirect = bool(redirect) and None new_retries = cls(retries, redirect=redirect) log.debug("Converted retries value: %r -> %r" % (retries, new_retries)) return new_retries
[ "def", "from_int", "(", "cls", ",", "retries", ",", "redirect", "=", "True", ",", "default", "=", "None", ")", ":", "if", "retries", "is", "None", ":", "retries", "=", "default", "if", "default", "is", "not", "None", "else", "cls", ".", "DEFAULT", "i...
Backwards-compatibility for the old retries format.
[ "Backwards", "-", "compatibility", "for", "the", "old", "retries", "format", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/util/retry.py#L145-L156
train
mottosso/be
be/vendor/requests/packages/urllib3/util/retry.py
Retry.get_backoff_time
def get_backoff_time(self): """ Formula for computing the current backoff :rtype: float """ if self._observed_errors <= 1: return 0 backoff_value = self.backoff_factor * (2 ** (self._observed_errors - 1)) return min(self.BACKOFF_MAX, backoff_value)
python
def get_backoff_time(self): """ Formula for computing the current backoff :rtype: float """ if self._observed_errors <= 1: return 0 backoff_value = self.backoff_factor * (2 ** (self._observed_errors - 1)) return min(self.BACKOFF_MAX, backoff_value)
[ "def", "get_backoff_time", "(", "self", ")", ":", "if", "self", ".", "_observed_errors", "<=", "1", ":", "return", "0", "backoff_value", "=", "self", ".", "backoff_factor", "*", "(", "2", "**", "(", "self", ".", "_observed_errors", "-", "1", ")", ")", ...
Formula for computing the current backoff :rtype: float
[ "Formula", "for", "computing", "the", "current", "backoff" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/util/retry.py#L158-L167
train
mottosso/be
be/vendor/requests/packages/urllib3/util/retry.py
Retry.is_forced_retry
def is_forced_retry(self, method, status_code): """ Is this method/status code retryable? (Based on method/codes whitelists) """ if self.method_whitelist and method.upper() not in self.method_whitelist: return False return self.status_forcelist and status_code in self.status_forcelist
python
def is_forced_retry(self, method, status_code): """ Is this method/status code retryable? (Based on method/codes whitelists) """ if self.method_whitelist and method.upper() not in self.method_whitelist: return False return self.status_forcelist and status_code in self.status_forcelist
[ "def", "is_forced_retry", "(", "self", ",", "method", ",", "status_code", ")", ":", "if", "self", ".", "method_whitelist", "and", "method", ".", "upper", "(", ")", "not", "in", "self", ".", "method_whitelist", ":", "return", "False", "return", "self", ".",...
Is this method/status code retryable? (Based on method/codes whitelists)
[ "Is", "this", "method", "/", "status", "code", "retryable?", "(", "Based", "on", "method", "/", "codes", "whitelists", ")" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/util/retry.py#L192-L198
train
mottosso/be
be/vendor/click/types.py
convert_type
def convert_type(ty, default=None): """Converts a callable or python ty into the most appropriate param ty. """ if isinstance(ty, tuple): return Tuple(ty) if isinstance(ty, ParamType): return ty guessed_type = False if ty is None and default is not None: ty = type(default) guessed_type = True if ty is text_type or ty is str or ty is None: return STRING if ty is int: return INT # Booleans are only okay if not guessed. This is done because for # flags the default value is actually a bit of a lie in that it # indicates which of the flags is the one we want. See get_default() # for more information. if ty is bool and not guessed_type: return BOOL if ty is float: return FLOAT if guessed_type: return STRING # Catch a common mistake if __debug__: try: if issubclass(ty, ParamType): raise AssertionError('Attempted to use an uninstantiated ' 'parameter type (%s).' % ty) except TypeError: pass return FuncParamType(ty)
python
def convert_type(ty, default=None): """Converts a callable or python ty into the most appropriate param ty. """ if isinstance(ty, tuple): return Tuple(ty) if isinstance(ty, ParamType): return ty guessed_type = False if ty is None and default is not None: ty = type(default) guessed_type = True if ty is text_type or ty is str or ty is None: return STRING if ty is int: return INT # Booleans are only okay if not guessed. This is done because for # flags the default value is actually a bit of a lie in that it # indicates which of the flags is the one we want. See get_default() # for more information. if ty is bool and not guessed_type: return BOOL if ty is float: return FLOAT if guessed_type: return STRING # Catch a common mistake if __debug__: try: if issubclass(ty, ParamType): raise AssertionError('Attempted to use an uninstantiated ' 'parameter type (%s).' % ty) except TypeError: pass return FuncParamType(ty)
[ "def", "convert_type", "(", "ty", ",", "default", "=", "None", ")", ":", "if", "isinstance", "(", "ty", ",", "tuple", ")", ":", "return", "Tuple", "(", "ty", ")", "if", "isinstance", "(", "ty", ",", "ParamType", ")", ":", "return", "ty", "guessed_typ...
Converts a callable or python ty into the most appropriate param ty.
[ "Converts", "a", "callable", "or", "python", "ty", "into", "the", "most", "appropriate", "param", "ty", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/types.py#L445-L480
train
mottosso/be
be/vendor/click/formatting.py
wrap_text
def wrap_text(text, width=78, initial_indent='', subsequent_indent='', preserve_paragraphs=False): """A helper function that intelligently wraps text. By default, it assumes that it operates on a single paragraph of text but if the `preserve_paragraphs` parameter is provided it will intelligently handle paragraphs (defined by two empty lines). If paragraphs are handled, a paragraph can be prefixed with an empty line containing the ``\\b`` character (``\\x08``) to indicate that no rewrapping should happen in that block. :param text: the text that should be rewrapped. :param width: the maximum width for the text. :param initial_indent: the initial indent that should be placed on the first line as a string. :param subsequent_indent: the indent string that should be placed on each consecutive line. :param preserve_paragraphs: if this flag is set then the wrapping will intelligently handle paragraphs. """ from ._textwrap import TextWrapper text = text.expandtabs() post_wrap_indent = subsequent_indent[:-1] subsequent_indent = subsequent_indent[-1:] wrapper = TextWrapper(width, initial_indent=initial_indent, subsequent_indent=subsequent_indent, replace_whitespace=False) if not preserve_paragraphs: return add_subsequent_indent(wrapper.fill(text), post_wrap_indent) p = [] buf = [] indent = None def _flush_par(): if not buf: return if buf[0].strip() == '\b': p.append((indent or 0, True, '\n'.join(buf[1:]))) else: p.append((indent or 0, False, ' '.join(buf))) del buf[:] for line in text.splitlines(): if not line: _flush_par() indent = None else: if indent is None: orig_len = term_len(line) line = line.lstrip() indent = orig_len - term_len(line) buf.append(line) _flush_par() rv = [] for indent, raw, text in p: with wrapper.extra_indent(' ' * indent): if raw: rv.append(add_subsequent_indent(wrapper.indent_only(text), post_wrap_indent)) else: rv.append(add_subsequent_indent(wrapper.fill(text), post_wrap_indent)) return '\n\n'.join(rv)
python
def wrap_text(text, width=78, initial_indent='', subsequent_indent='', preserve_paragraphs=False): """A helper function that intelligently wraps text. By default, it assumes that it operates on a single paragraph of text but if the `preserve_paragraphs` parameter is provided it will intelligently handle paragraphs (defined by two empty lines). If paragraphs are handled, a paragraph can be prefixed with an empty line containing the ``\\b`` character (``\\x08``) to indicate that no rewrapping should happen in that block. :param text: the text that should be rewrapped. :param width: the maximum width for the text. :param initial_indent: the initial indent that should be placed on the first line as a string. :param subsequent_indent: the indent string that should be placed on each consecutive line. :param preserve_paragraphs: if this flag is set then the wrapping will intelligently handle paragraphs. """ from ._textwrap import TextWrapper text = text.expandtabs() post_wrap_indent = subsequent_indent[:-1] subsequent_indent = subsequent_indent[-1:] wrapper = TextWrapper(width, initial_indent=initial_indent, subsequent_indent=subsequent_indent, replace_whitespace=False) if not preserve_paragraphs: return add_subsequent_indent(wrapper.fill(text), post_wrap_indent) p = [] buf = [] indent = None def _flush_par(): if not buf: return if buf[0].strip() == '\b': p.append((indent or 0, True, '\n'.join(buf[1:]))) else: p.append((indent or 0, False, ' '.join(buf))) del buf[:] for line in text.splitlines(): if not line: _flush_par() indent = None else: if indent is None: orig_len = term_len(line) line = line.lstrip() indent = orig_len - term_len(line) buf.append(line) _flush_par() rv = [] for indent, raw, text in p: with wrapper.extra_indent(' ' * indent): if raw: rv.append(add_subsequent_indent(wrapper.indent_only(text), post_wrap_indent)) else: rv.append(add_subsequent_indent(wrapper.fill(text), post_wrap_indent)) return '\n\n'.join(rv)
[ "def", "wrap_text", "(", "text", ",", "width", "=", "78", ",", "initial_indent", "=", "''", ",", "subsequent_indent", "=", "''", ",", "preserve_paragraphs", "=", "False", ")", ":", "from", ".", "_textwrap", "import", "TextWrapper", "text", "=", "text", "."...
A helper function that intelligently wraps text. By default, it assumes that it operates on a single paragraph of text but if the `preserve_paragraphs` parameter is provided it will intelligently handle paragraphs (defined by two empty lines). If paragraphs are handled, a paragraph can be prefixed with an empty line containing the ``\\b`` character (``\\x08``) to indicate that no rewrapping should happen in that block. :param text: the text that should be rewrapped. :param width: the maximum width for the text. :param initial_indent: the initial indent that should be placed on the first line as a string. :param subsequent_indent: the indent string that should be placed on each consecutive line. :param preserve_paragraphs: if this flag is set then the wrapping will intelligently handle paragraphs.
[ "A", "helper", "function", "that", "intelligently", "wraps", "text", ".", "By", "default", "it", "assumes", "that", "it", "operates", "on", "a", "single", "paragraph", "of", "text", "but", "if", "the", "preserve_paragraphs", "parameter", "is", "provided", "it"...
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/formatting.py#L27-L92
train
mottosso/be
be/vendor/click/formatting.py
HelpFormatter.write_usage
def write_usage(self, prog, args='', prefix='Usage: '): """Writes a usage line into the buffer. :param prog: the program name. :param args: whitespace separated list of arguments. :param prefix: the prefix for the first line. """ prefix = '%*s%s' % (self.current_indent, prefix, prog) self.write(prefix) text_width = max(self.width - self.current_indent - term_len(prefix), 10) indent = ' ' * (term_len(prefix) + 1) self.write(wrap_text(args, text_width, initial_indent=' ', subsequent_indent=indent)) self.write('\n')
python
def write_usage(self, prog, args='', prefix='Usage: '): """Writes a usage line into the buffer. :param prog: the program name. :param args: whitespace separated list of arguments. :param prefix: the prefix for the first line. """ prefix = '%*s%s' % (self.current_indent, prefix, prog) self.write(prefix) text_width = max(self.width - self.current_indent - term_len(prefix), 10) indent = ' ' * (term_len(prefix) + 1) self.write(wrap_text(args, text_width, initial_indent=' ', subsequent_indent=indent)) self.write('\n')
[ "def", "write_usage", "(", "self", ",", "prog", ",", "args", "=", "''", ",", "prefix", "=", "'Usage: '", ")", ":", "prefix", "=", "'%*s%s'", "%", "(", "self", ".", "current_indent", ",", "prefix", ",", "prog", ")", "self", ".", "write", "(", "prefix"...
Writes a usage line into the buffer. :param prog: the program name. :param args: whitespace separated list of arguments. :param prefix: the prefix for the first line.
[ "Writes", "a", "usage", "line", "into", "the", "buffer", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/formatting.py#L129-L145
train
mottosso/be
be/cli.py
in_
def in_(ctx, topics, yes, as_, enter): """Set the current topics to `topics` Environment: BE_PROJECT: First topic BE_CWD: Current `be` working directory BE_TOPICS: Arguments to `in` BE_DEVELOPMENTDIR: Absolute path to current development directory BE_PROJECTROOT: Absolute path to current project BE_PROJECTSROOT: Absolute path to where projects are located BE_ACTIVE: 0 or 1, indicates an active be environment BE_USER: Current user, overridden with `--as` BE_SCRIPT: User-supplied shell script BE_PYTHON: User-supplied python script BE_ENTER: 0 or 1 depending on whether the topic was entered BE_GITHUB_API_TOKEN: Optional GitHub API token BE_ENVIRONMENT: Space-separated list of user-added environment variables BE_TEMPDIR: Directory in which temporary files are stored BE_PRESETSDIR: Directory in which presets are searched BE_ALIASDIR: Directory in which aliases are written BE_BINDING: Binding between template and item in inventory \b Usage: $ be in project topics """ topics = map(str, topics) # They enter as unicode if self.isactive(): lib.echo("ERROR: Exit current project first") sys.exit(lib.USER_ERROR) # Determine topic syntax if len(topics[0].split("/")) == 3: topic_syntax = lib.FIXED project = topics[0].split("/")[0] else: topic_syntax = lib.POSITIONAL project = topics[0] project_dir = lib.project_dir(_extern.cwd(), project) if not os.path.exists(project_dir): lib.echo("Project \"%s\" not found. " % project) lib.echo("\nAvailable:") ctx.invoke(ls) sys.exit(lib.USER_ERROR) # Boot up context = lib.context(root=_extern.cwd(), project=project) be = _extern.load_be(project) templates = _extern.load_templates(project) inventory = _extern.load_inventory(project) context.update({ "BE_PROJECT": project, "BE_USER": str(as_), "BE_ENTER": "1" if enter else "", "BE_TOPICS": " ".join(topics) }) # Remap topic syntax, for backwards compatibility # In cases where the topic is entered in a way that # differs from the template, remap topic to template. if any(re.findall("{\d+}", pattern) for pattern in templates.values()): template_syntax = lib.POSITIONAL else: template_syntax = lib.FIXED if topic_syntax & lib.POSITIONAL and not template_syntax & lib.POSITIONAL: topics = ["/".join(topics)] if topic_syntax & lib.FIXED and not template_syntax & lib.FIXED: topics[:] = topics[0].split("/") try: key = be.get("templates", {}).get("key") or "{1}" item = lib.item_from_topics(key, topics) binding = lib.binding_from_item(inventory, item) context["BE_BINDING"] = binding except IndexError as exc: lib.echo("At least %s topics are required" % str(exc)) sys.exit(lib.USER_ERROR) except KeyError as exc: lib.echo("\"%s\" not found" % item) if exc.bindings: lib.echo("\nAvailable:") for item_ in sorted(exc.bindings, key=lambda a: (exc.bindings[a], a)): lib.echo("- %s (%s)" % (item_, exc.bindings[item_])) sys.exit(lib.USER_ERROR) # Finally, determine a development directory # based on the template-, not topic-syntax. if template_syntax & lib.POSITIONAL: try: development_dir = lib.pos_development_directory( templates=templates, inventory=inventory, context=context, topics=topics, user=as_, item=item) except KeyError as exc: lib.echo("\"%s\" not found" % item) if exc.bindings: lib.echo("\nAvailable:") for item_ in sorted(exc.bindings, key=lambda a: (exc.bindings[a], a)): lib.echo("- %s (%s)" % (item_, exc.bindings[item_])) sys.exit(lib.USER_ERROR) else: # FIXED topic_syntax development_dir = lib.fixed_development_directory( templates, inventory, topics, as_) context["BE_DEVELOPMENTDIR"] = development_dir tempdir = (tempfile.mkdtemp() if not os.environ.get("BE_TEMPDIR") else os.environ["BE_TEMPDIR"]) context["BE_TEMPDIR"] = tempdir # Should it be entered? if enter and not os.path.exists(development_dir): create = False if yes: create = True else: sys.stdout.write("No development directory found. Create? [Y/n]: ") sys.stdout.flush() if raw_input().lower() in ("", "y", "yes"): create = True if create: ctx.invoke(mkdir, dir=development_dir) else: sys.stdout.write("Cancelled") sys.exit(lib.NORMAL) # Parse be.yaml if "script" in be: context["BE_SCRIPT"] = _extern.write_script( be["script"], tempdir).replace("\\", "/") if "python" in be: script = "\n".join(be["python"]) context["BE_PYTHON"] = script try: exec script in {"__name__": __name__} except Exception as e: lib.echo("ERROR: %s" % e) invalids = [v for v in context.values() if not isinstance(v, str)] assert all(isinstance(v, str) for v in context.values()), invalids # Create aliases aliases_dir = _extern.write_aliases( be.get("alias", {}), tempdir) context["PATH"] = (aliases_dir + os.pathsep + context.get("PATH", "")) context["BE_ALIASDIR"] = aliases_dir # Parse redirects lib.parse_redirect( be.get("redirect", {}), topics, context) # Override inherited context # with that coming from be.yaml. if "environment" in be: parsed = lib.parse_environment( fields=be["environment"], context=context, topics=topics) context["BE_ENVIRONMENT"] = " ".join(parsed.keys()) context.update(parsed) if "BE_TESTING" in context: os.chdir(development_dir) os.environ.update(context) else: parent = lib.parent() cmd = lib.cmd(parent) # Store reference to calling shell context["BE_SHELL"] = parent try: sys.exit(subprocess.call(cmd, env=context)) finally: import shutil shutil.rmtree(tempdir)
python
def in_(ctx, topics, yes, as_, enter): """Set the current topics to `topics` Environment: BE_PROJECT: First topic BE_CWD: Current `be` working directory BE_TOPICS: Arguments to `in` BE_DEVELOPMENTDIR: Absolute path to current development directory BE_PROJECTROOT: Absolute path to current project BE_PROJECTSROOT: Absolute path to where projects are located BE_ACTIVE: 0 or 1, indicates an active be environment BE_USER: Current user, overridden with `--as` BE_SCRIPT: User-supplied shell script BE_PYTHON: User-supplied python script BE_ENTER: 0 or 1 depending on whether the topic was entered BE_GITHUB_API_TOKEN: Optional GitHub API token BE_ENVIRONMENT: Space-separated list of user-added environment variables BE_TEMPDIR: Directory in which temporary files are stored BE_PRESETSDIR: Directory in which presets are searched BE_ALIASDIR: Directory in which aliases are written BE_BINDING: Binding between template and item in inventory \b Usage: $ be in project topics """ topics = map(str, topics) # They enter as unicode if self.isactive(): lib.echo("ERROR: Exit current project first") sys.exit(lib.USER_ERROR) # Determine topic syntax if len(topics[0].split("/")) == 3: topic_syntax = lib.FIXED project = topics[0].split("/")[0] else: topic_syntax = lib.POSITIONAL project = topics[0] project_dir = lib.project_dir(_extern.cwd(), project) if not os.path.exists(project_dir): lib.echo("Project \"%s\" not found. " % project) lib.echo("\nAvailable:") ctx.invoke(ls) sys.exit(lib.USER_ERROR) # Boot up context = lib.context(root=_extern.cwd(), project=project) be = _extern.load_be(project) templates = _extern.load_templates(project) inventory = _extern.load_inventory(project) context.update({ "BE_PROJECT": project, "BE_USER": str(as_), "BE_ENTER": "1" if enter else "", "BE_TOPICS": " ".join(topics) }) # Remap topic syntax, for backwards compatibility # In cases where the topic is entered in a way that # differs from the template, remap topic to template. if any(re.findall("{\d+}", pattern) for pattern in templates.values()): template_syntax = lib.POSITIONAL else: template_syntax = lib.FIXED if topic_syntax & lib.POSITIONAL and not template_syntax & lib.POSITIONAL: topics = ["/".join(topics)] if topic_syntax & lib.FIXED and not template_syntax & lib.FIXED: topics[:] = topics[0].split("/") try: key = be.get("templates", {}).get("key") or "{1}" item = lib.item_from_topics(key, topics) binding = lib.binding_from_item(inventory, item) context["BE_BINDING"] = binding except IndexError as exc: lib.echo("At least %s topics are required" % str(exc)) sys.exit(lib.USER_ERROR) except KeyError as exc: lib.echo("\"%s\" not found" % item) if exc.bindings: lib.echo("\nAvailable:") for item_ in sorted(exc.bindings, key=lambda a: (exc.bindings[a], a)): lib.echo("- %s (%s)" % (item_, exc.bindings[item_])) sys.exit(lib.USER_ERROR) # Finally, determine a development directory # based on the template-, not topic-syntax. if template_syntax & lib.POSITIONAL: try: development_dir = lib.pos_development_directory( templates=templates, inventory=inventory, context=context, topics=topics, user=as_, item=item) except KeyError as exc: lib.echo("\"%s\" not found" % item) if exc.bindings: lib.echo("\nAvailable:") for item_ in sorted(exc.bindings, key=lambda a: (exc.bindings[a], a)): lib.echo("- %s (%s)" % (item_, exc.bindings[item_])) sys.exit(lib.USER_ERROR) else: # FIXED topic_syntax development_dir = lib.fixed_development_directory( templates, inventory, topics, as_) context["BE_DEVELOPMENTDIR"] = development_dir tempdir = (tempfile.mkdtemp() if not os.environ.get("BE_TEMPDIR") else os.environ["BE_TEMPDIR"]) context["BE_TEMPDIR"] = tempdir # Should it be entered? if enter and not os.path.exists(development_dir): create = False if yes: create = True else: sys.stdout.write("No development directory found. Create? [Y/n]: ") sys.stdout.flush() if raw_input().lower() in ("", "y", "yes"): create = True if create: ctx.invoke(mkdir, dir=development_dir) else: sys.stdout.write("Cancelled") sys.exit(lib.NORMAL) # Parse be.yaml if "script" in be: context["BE_SCRIPT"] = _extern.write_script( be["script"], tempdir).replace("\\", "/") if "python" in be: script = "\n".join(be["python"]) context["BE_PYTHON"] = script try: exec script in {"__name__": __name__} except Exception as e: lib.echo("ERROR: %s" % e) invalids = [v for v in context.values() if not isinstance(v, str)] assert all(isinstance(v, str) for v in context.values()), invalids # Create aliases aliases_dir = _extern.write_aliases( be.get("alias", {}), tempdir) context["PATH"] = (aliases_dir + os.pathsep + context.get("PATH", "")) context["BE_ALIASDIR"] = aliases_dir # Parse redirects lib.parse_redirect( be.get("redirect", {}), topics, context) # Override inherited context # with that coming from be.yaml. if "environment" in be: parsed = lib.parse_environment( fields=be["environment"], context=context, topics=topics) context["BE_ENVIRONMENT"] = " ".join(parsed.keys()) context.update(parsed) if "BE_TESTING" in context: os.chdir(development_dir) os.environ.update(context) else: parent = lib.parent() cmd = lib.cmd(parent) # Store reference to calling shell context["BE_SHELL"] = parent try: sys.exit(subprocess.call(cmd, env=context)) finally: import shutil shutil.rmtree(tempdir)
[ "def", "in_", "(", "ctx", ",", "topics", ",", "yes", ",", "as_", ",", "enter", ")", ":", "topics", "=", "map", "(", "str", ",", "topics", ")", "# They enter as unicode", "if", "self", ".", "isactive", "(", ")", ":", "lib", ".", "echo", "(", "\"ERRO...
Set the current topics to `topics` Environment: BE_PROJECT: First topic BE_CWD: Current `be` working directory BE_TOPICS: Arguments to `in` BE_DEVELOPMENTDIR: Absolute path to current development directory BE_PROJECTROOT: Absolute path to current project BE_PROJECTSROOT: Absolute path to where projects are located BE_ACTIVE: 0 or 1, indicates an active be environment BE_USER: Current user, overridden with `--as` BE_SCRIPT: User-supplied shell script BE_PYTHON: User-supplied python script BE_ENTER: 0 or 1 depending on whether the topic was entered BE_GITHUB_API_TOKEN: Optional GitHub API token BE_ENVIRONMENT: Space-separated list of user-added environment variables BE_TEMPDIR: Directory in which temporary files are stored BE_PRESETSDIR: Directory in which presets are searched BE_ALIASDIR: Directory in which aliases are written BE_BINDING: Binding between template and item in inventory \b Usage: $ be in project topics
[ "Set", "the", "current", "topics", "to", "topics" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/cli.py#L77-L274
train
mottosso/be
be/cli.py
new
def new(preset, name, silent, update): """Create new default preset \b Usage: $ be new ad "blue_unicorn" created $ be new film --name spiderman "spiderman" created """ if self.isactive(): lib.echo("Please exit current preset before starting a new") sys.exit(lib.USER_ERROR) if not name: count = 0 name = lib.random_name() while name in _extern.projects(): if count > 10: lib.echo("ERROR: Couldn't come up with a unique name :(") sys.exit(lib.USER_ERROR) name = lib.random_name() count += 1 project_dir = lib.project_dir(_extern.cwd(), name) if os.path.exists(project_dir): lib.echo("\"%s\" already exists" % name) sys.exit(lib.USER_ERROR) username, preset = ([None] + preset.split("/", 1))[-2:] presets_dir = _extern.presets_dir() preset_dir = os.path.join(presets_dir, preset) # Is the preset given referring to a repository directly? relative = False if username else True try: if not update and preset in _extern.local_presets(): _extern.copy_preset(preset_dir, project_dir) else: lib.echo("Finding preset for \"%s\".. " % preset, silent) time.sleep(1 if silent else 0) if relative: # Preset is relative, look it up from the Hub presets = _extern.github_presets() if preset not in presets: sys.stdout.write("\"%s\" not found" % preset) sys.exit(lib.USER_ERROR) time.sleep(1 if silent else 0) repository = presets[preset] else: # Absolute paths are pulled directly repository = username + "/" + preset lib.echo("Pulling %s.. " % repository, silent) repository = _extern.fetch_release(repository) # Remove existing preset if preset in _extern.local_presets(): _extern.remove_preset(preset) try: _extern.pull_preset(repository, preset_dir) except IOError as e: lib.echo("ERROR: Sorry, something went wrong.\n" "Use be --verbose for more") lib.echo(e) sys.exit(lib.USER_ERROR) try: _extern.copy_preset(preset_dir, project_dir) finally: # Absolute paths are not stored locally if not relative: _extern.remove_preset(preset) except IOError as exc: if self.verbose: lib.echo("ERROR: %s" % exc) else: lib.echo("ERROR: Could not write, do you have permission?") sys.exit(lib.PROGRAM_ERROR) lib.echo("\"%s\" created" % name, silent)
python
def new(preset, name, silent, update): """Create new default preset \b Usage: $ be new ad "blue_unicorn" created $ be new film --name spiderman "spiderman" created """ if self.isactive(): lib.echo("Please exit current preset before starting a new") sys.exit(lib.USER_ERROR) if not name: count = 0 name = lib.random_name() while name in _extern.projects(): if count > 10: lib.echo("ERROR: Couldn't come up with a unique name :(") sys.exit(lib.USER_ERROR) name = lib.random_name() count += 1 project_dir = lib.project_dir(_extern.cwd(), name) if os.path.exists(project_dir): lib.echo("\"%s\" already exists" % name) sys.exit(lib.USER_ERROR) username, preset = ([None] + preset.split("/", 1))[-2:] presets_dir = _extern.presets_dir() preset_dir = os.path.join(presets_dir, preset) # Is the preset given referring to a repository directly? relative = False if username else True try: if not update and preset in _extern.local_presets(): _extern.copy_preset(preset_dir, project_dir) else: lib.echo("Finding preset for \"%s\".. " % preset, silent) time.sleep(1 if silent else 0) if relative: # Preset is relative, look it up from the Hub presets = _extern.github_presets() if preset not in presets: sys.stdout.write("\"%s\" not found" % preset) sys.exit(lib.USER_ERROR) time.sleep(1 if silent else 0) repository = presets[preset] else: # Absolute paths are pulled directly repository = username + "/" + preset lib.echo("Pulling %s.. " % repository, silent) repository = _extern.fetch_release(repository) # Remove existing preset if preset in _extern.local_presets(): _extern.remove_preset(preset) try: _extern.pull_preset(repository, preset_dir) except IOError as e: lib.echo("ERROR: Sorry, something went wrong.\n" "Use be --verbose for more") lib.echo(e) sys.exit(lib.USER_ERROR) try: _extern.copy_preset(preset_dir, project_dir) finally: # Absolute paths are not stored locally if not relative: _extern.remove_preset(preset) except IOError as exc: if self.verbose: lib.echo("ERROR: %s" % exc) else: lib.echo("ERROR: Could not write, do you have permission?") sys.exit(lib.PROGRAM_ERROR) lib.echo("\"%s\" created" % name, silent)
[ "def", "new", "(", "preset", ",", "name", ",", "silent", ",", "update", ")", ":", "if", "self", ".", "isactive", "(", ")", ":", "lib", ".", "echo", "(", "\"Please exit current preset before starting a new\"", ")", "sys", ".", "exit", "(", "lib", ".", "US...
Create new default preset \b Usage: $ be new ad "blue_unicorn" created $ be new film --name spiderman "spiderman" created
[ "Create", "new", "default", "preset" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/cli.py#L284-L374
train
mottosso/be
be/cli.py
update
def update(preset, clean): """Update a local preset This command will cause `be` to pull a preset already available locally. \b Usage: $ be update ad Updating "ad".. """ if self.isactive(): lib.echo("ERROR: Exit current project first") sys.exit(lib.USER_ERROR) presets = _extern.github_presets() if preset not in presets: sys.stdout.write("\"%s\" not found" % preset) sys.exit(lib.USER_ERROR) lib.echo("Are you sure you want to update \"%s\", " "any changes will be lost?: [y/N]: ", newline=False) if raw_input().lower() in ("y", "yes"): presets_dir = _extern.presets_dir() preset_dir = os.path.join(presets_dir, preset) repository = presets[preset] if clean: try: _extern.remove_preset(preset) except: lib.echo("ERROR: Could not clean existing preset") sys.exit(lib.USER_ERROR) lib.echo("Updating %s.. " % repository) try: _extern.pull_preset(repository, preset_dir) except IOError as e: lib.echo(e) sys.exit(lib.USER_ERROR) else: lib.echo("Cancelled")
python
def update(preset, clean): """Update a local preset This command will cause `be` to pull a preset already available locally. \b Usage: $ be update ad Updating "ad".. """ if self.isactive(): lib.echo("ERROR: Exit current project first") sys.exit(lib.USER_ERROR) presets = _extern.github_presets() if preset not in presets: sys.stdout.write("\"%s\" not found" % preset) sys.exit(lib.USER_ERROR) lib.echo("Are you sure you want to update \"%s\", " "any changes will be lost?: [y/N]: ", newline=False) if raw_input().lower() in ("y", "yes"): presets_dir = _extern.presets_dir() preset_dir = os.path.join(presets_dir, preset) repository = presets[preset] if clean: try: _extern.remove_preset(preset) except: lib.echo("ERROR: Could not clean existing preset") sys.exit(lib.USER_ERROR) lib.echo("Updating %s.. " % repository) try: _extern.pull_preset(repository, preset_dir) except IOError as e: lib.echo(e) sys.exit(lib.USER_ERROR) else: lib.echo("Cancelled")
[ "def", "update", "(", "preset", ",", "clean", ")", ":", "if", "self", ".", "isactive", "(", ")", ":", "lib", ".", "echo", "(", "\"ERROR: Exit current project first\"", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "presets", "=", "_extern"...
Update a local preset This command will cause `be` to pull a preset already available locally. \b Usage: $ be update ad Updating "ad"..
[ "Update", "a", "local", "preset" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/cli.py#L380-L427
train
mottosso/be
be/cli.py
tab
def tab(topics, complete): """Utility sub-command for tabcompletion This command is meant to be called by a tab completion function and is given a the currently entered topics, along with a boolean indicating whether or not the last entered argument is complete. """ # Discard `be tab` topics = list(topics)[2:] # When given an incomplete argument, # the argument is *sometimes* returned twice (?) # .. note:: Seen in Git Bash on Windows # $ be in giant [TAB] # -> ['giant'] # $ be in gi[TAB] # -> ['gi', 'gi'] if len(topics) > 1 and topics[-1] == topics[-2]: topics.pop() # Suggest projects if len(topics) == 0: projects = lib.list_projects(root=_extern.cwd()) sys.stdout.write(" ".join(projects)) elif len(topics) == 1: project = topics[0] projects = lib.list_projects(root=_extern.cwd()) # Complete project if not complete: projects = [i for i in projects if i.startswith(project)] sys.stdout.write(" ".join(projects)) else: # Suggest items from inventory inventory = _extern.load_inventory(project) inventory = lib.list_inventory(inventory) items = [i for i, b in inventory] sys.stdout.write(" ".join(items)) else: project, item = topics[:2] # Complete inventory item if len(topics) == 2 and not complete: inventory = _extern.load_inventory(project) inventory = lib.list_inventory(inventory) items = [i for i, b in inventory] items = [i for i in items if i.startswith(item)] sys.stdout.write(" ".join(items)) # Suggest items from template else: try: be = _extern.load_be(project) templates = _extern.load_templates(project) inventory = _extern.load_inventory(project) item = topics[-1] items = lib.list_template(root=_extern.cwd(), topics=topics, templates=templates, inventory=inventory, be=be) if not complete: items = lib.list_template(root=_extern.cwd(), topics=topics[:-1], templates=templates, inventory=inventory, be=be) items = [i for i in items if i.startswith(item)] sys.stdout.write(" ".join(items) + " ") else: sys.stdout.write(" ".join(items) + " ") except IndexError: sys.exit(lib.NORMAL)
python
def tab(topics, complete): """Utility sub-command for tabcompletion This command is meant to be called by a tab completion function and is given a the currently entered topics, along with a boolean indicating whether or not the last entered argument is complete. """ # Discard `be tab` topics = list(topics)[2:] # When given an incomplete argument, # the argument is *sometimes* returned twice (?) # .. note:: Seen in Git Bash on Windows # $ be in giant [TAB] # -> ['giant'] # $ be in gi[TAB] # -> ['gi', 'gi'] if len(topics) > 1 and topics[-1] == topics[-2]: topics.pop() # Suggest projects if len(topics) == 0: projects = lib.list_projects(root=_extern.cwd()) sys.stdout.write(" ".join(projects)) elif len(topics) == 1: project = topics[0] projects = lib.list_projects(root=_extern.cwd()) # Complete project if not complete: projects = [i for i in projects if i.startswith(project)] sys.stdout.write(" ".join(projects)) else: # Suggest items from inventory inventory = _extern.load_inventory(project) inventory = lib.list_inventory(inventory) items = [i for i, b in inventory] sys.stdout.write(" ".join(items)) else: project, item = topics[:2] # Complete inventory item if len(topics) == 2 and not complete: inventory = _extern.load_inventory(project) inventory = lib.list_inventory(inventory) items = [i for i, b in inventory] items = [i for i in items if i.startswith(item)] sys.stdout.write(" ".join(items)) # Suggest items from template else: try: be = _extern.load_be(project) templates = _extern.load_templates(project) inventory = _extern.load_inventory(project) item = topics[-1] items = lib.list_template(root=_extern.cwd(), topics=topics, templates=templates, inventory=inventory, be=be) if not complete: items = lib.list_template(root=_extern.cwd(), topics=topics[:-1], templates=templates, inventory=inventory, be=be) items = [i for i in items if i.startswith(item)] sys.stdout.write(" ".join(items) + " ") else: sys.stdout.write(" ".join(items) + " ") except IndexError: sys.exit(lib.NORMAL)
[ "def", "tab", "(", "topics", ",", "complete", ")", ":", "# Discard `be tab`", "topics", "=", "list", "(", "topics", ")", "[", "2", ":", "]", "# When given an incomplete argument,", "# the argument is *sometimes* returned twice (?)", "# .. note:: Seen in Git Bash on Windows"...
Utility sub-command for tabcompletion This command is meant to be called by a tab completion function and is given a the currently entered topics, along with a boolean indicating whether or not the last entered argument is complete.
[ "Utility", "sub", "-", "command", "for", "tabcompletion" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/cli.py#L433-L512
train
mottosso/be
be/cli.py
activate
def activate(): """Enter into an environment with support for tab-completion This command drops you into a subshell, similar to the one generated via `be in ...`, except no topic is present and instead it enables tab-completion for supported shells. See documentation for further information. https://github.com/mottosso/be/wiki/cli """ parent = lib.parent() try: cmd = lib.cmd(parent) except SystemError as exc: lib.echo(exc) sys.exit(lib.PROGRAM_ERROR) # Store reference to calling shell context = lib.context(root=_extern.cwd()) context["BE_SHELL"] = parent if lib.platform() == "unix": context["BE_TABCOMPLETION"] = os.path.join( os.path.dirname(__file__), "_autocomplete.sh").replace("\\", "/") context.pop("BE_ACTIVE", None) sys.exit(subprocess.call(cmd, env=context))
python
def activate(): """Enter into an environment with support for tab-completion This command drops you into a subshell, similar to the one generated via `be in ...`, except no topic is present and instead it enables tab-completion for supported shells. See documentation for further information. https://github.com/mottosso/be/wiki/cli """ parent = lib.parent() try: cmd = lib.cmd(parent) except SystemError as exc: lib.echo(exc) sys.exit(lib.PROGRAM_ERROR) # Store reference to calling shell context = lib.context(root=_extern.cwd()) context["BE_SHELL"] = parent if lib.platform() == "unix": context["BE_TABCOMPLETION"] = os.path.join( os.path.dirname(__file__), "_autocomplete.sh").replace("\\", "/") context.pop("BE_ACTIVE", None) sys.exit(subprocess.call(cmd, env=context))
[ "def", "activate", "(", ")", ":", "parent", "=", "lib", ".", "parent", "(", ")", "try", ":", "cmd", "=", "lib", ".", "cmd", "(", "parent", ")", "except", "SystemError", "as", "exc", ":", "lib", ".", "echo", "(", "exc", ")", "sys", ".", "exit", ...
Enter into an environment with support for tab-completion This command drops you into a subshell, similar to the one generated via `be in ...`, except no topic is present and instead it enables tab-completion for supported shells. See documentation for further information. https://github.com/mottosso/be/wiki/cli
[ "Enter", "into", "an", "environment", "with", "support", "for", "tab", "-", "completion" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/cli.py#L516-L546
train
mottosso/be
be/cli.py
ls
def ls(topics): """List contents of current context \b Usage: $ be ls - spiderman - hulk $ be ls spiderman - peter - mjay $ be ls spiderman seq01 - 1000 - 2000 - 2500 Return codes: 0 Normal 2 When insufficient arguments are supplied, or a template is unsupported. """ if self.isactive(): lib.echo("ERROR: Exit current project first") sys.exit(lib.USER_ERROR) # List projects if len(topics) == 0: for project in lib.list_projects(root=_extern.cwd()): lib.echo("- %s (project)" % project) sys.exit(lib.NORMAL) # List inventory of project elif len(topics) == 1: inventory = _extern.load_inventory(topics[0]) for item, binding in lib.list_inventory(inventory): lib.echo("- %s (%s)" % (item, binding)) sys.exit(lib.NORMAL) # List specific portion of template else: try: project = topics[0] be = _extern.load_be(project) templates = _extern.load_templates(project) inventory = _extern.load_inventory(project) for item in lib.list_template(root=_extern.cwd(), topics=topics, templates=templates, inventory=inventory, be=be): lib.echo("- %s" % item) except IndexError as exc: lib.echo(exc) sys.exit(lib.USER_ERROR) sys.exit(lib.NORMAL)
python
def ls(topics): """List contents of current context \b Usage: $ be ls - spiderman - hulk $ be ls spiderman - peter - mjay $ be ls spiderman seq01 - 1000 - 2000 - 2500 Return codes: 0 Normal 2 When insufficient arguments are supplied, or a template is unsupported. """ if self.isactive(): lib.echo("ERROR: Exit current project first") sys.exit(lib.USER_ERROR) # List projects if len(topics) == 0: for project in lib.list_projects(root=_extern.cwd()): lib.echo("- %s (project)" % project) sys.exit(lib.NORMAL) # List inventory of project elif len(topics) == 1: inventory = _extern.load_inventory(topics[0]) for item, binding in lib.list_inventory(inventory): lib.echo("- %s (%s)" % (item, binding)) sys.exit(lib.NORMAL) # List specific portion of template else: try: project = topics[0] be = _extern.load_be(project) templates = _extern.load_templates(project) inventory = _extern.load_inventory(project) for item in lib.list_template(root=_extern.cwd(), topics=topics, templates=templates, inventory=inventory, be=be): lib.echo("- %s" % item) except IndexError as exc: lib.echo(exc) sys.exit(lib.USER_ERROR) sys.exit(lib.NORMAL)
[ "def", "ls", "(", "topics", ")", ":", "if", "self", ".", "isactive", "(", ")", ":", "lib", ".", "echo", "(", "\"ERROR: Exit current project first\"", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "# List projects", "if", "len", "(", "topic...
List contents of current context \b Usage: $ be ls - spiderman - hulk $ be ls spiderman - peter - mjay $ be ls spiderman seq01 - 1000 - 2000 - 2500 Return codes: 0 Normal 2 When insufficient arguments are supplied, or a template is unsupported.
[ "List", "contents", "of", "current", "context" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/cli.py#L551-L608
train
mottosso/be
be/cli.py
mkdir
def mkdir(dir, enter): """Create directory with template for topic of the current environment """ if not os.path.exists(dir): os.makedirs(dir)
python
def mkdir(dir, enter): """Create directory with template for topic of the current environment """ if not os.path.exists(dir): os.makedirs(dir)
[ "def", "mkdir", "(", "dir", ",", "enter", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "dir", ")", ":", "os", ".", "makedirs", "(", "dir", ")" ]
Create directory with template for topic of the current environment
[ "Create", "directory", "with", "template", "for", "topic", "of", "the", "current", "environment" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/cli.py#L614-L620
train
mottosso/be
be/cli.py
preset_ls
def preset_ls(remote): """List presets \b Usage: $ be preset ls - ad - game - film """ if self.isactive(): lib.echo("ERROR: Exit current project first") sys.exit(lib.USER_ERROR) if remote: presets = _extern.github_presets() else: presets = _extern.local_presets() if not presets: lib.echo("No presets found") sys.exit(lib.NORMAL) for preset in sorted(presets): lib.echo("- %s" % preset) sys.exit(lib.NORMAL)
python
def preset_ls(remote): """List presets \b Usage: $ be preset ls - ad - game - film """ if self.isactive(): lib.echo("ERROR: Exit current project first") sys.exit(lib.USER_ERROR) if remote: presets = _extern.github_presets() else: presets = _extern.local_presets() if not presets: lib.echo("No presets found") sys.exit(lib.NORMAL) for preset in sorted(presets): lib.echo("- %s" % preset) sys.exit(lib.NORMAL)
[ "def", "preset_ls", "(", "remote", ")", ":", "if", "self", ".", "isactive", "(", ")", ":", "lib", ".", "echo", "(", "\"ERROR: Exit current project first\"", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "if", "remote", ":", "presets", "=",...
List presets \b Usage: $ be preset ls - ad - game - film
[ "List", "presets" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/cli.py#L630-L656
train
mottosso/be
be/cli.py
preset_find
def preset_find(query): """Find preset from hub \b $ be find ad https://github.com/mottosso/be-ad.git """ if self.isactive(): lib.echo("ERROR: Exit current project first") sys.exit(lib.USER_ERROR) found = _extern.github_presets().get(query) if found: lib.echo(found) else: lib.echo("Unable to locate preset \"%s\"" % query)
python
def preset_find(query): """Find preset from hub \b $ be find ad https://github.com/mottosso/be-ad.git """ if self.isactive(): lib.echo("ERROR: Exit current project first") sys.exit(lib.USER_ERROR) found = _extern.github_presets().get(query) if found: lib.echo(found) else: lib.echo("Unable to locate preset \"%s\"" % query)
[ "def", "preset_find", "(", "query", ")", ":", "if", "self", ".", "isactive", "(", ")", ":", "lib", ".", "echo", "(", "\"ERROR: Exit current project first\"", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "found", "=", "_extern", ".", "gith...
Find preset from hub \b $ be find ad https://github.com/mottosso/be-ad.git
[ "Find", "preset", "from", "hub" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/cli.py#L661-L678
train
mottosso/be
be/cli.py
dump
def dump(): """Print current environment Environment is outputted in a YAML-friendly format \b Usage: $ be dump Prefixed: - BE_TOPICS=hulk bruce animation - ... """ if not self.isactive(): lib.echo("ERROR: Enter a project first") sys.exit(lib.USER_ERROR) # Print custom environment variables first custom = sorted(os.environ.get("BE_ENVIRONMENT", "").split()) if custom: lib.echo("Custom:") for key in custom: lib.echo("- %s=%s" % (key, os.environ.get(key))) # Then print redirected variables project = os.environ["BE_PROJECT"] root = os.environ["BE_PROJECTSROOT"] be = _extern.load(project, "be", optional=True, root=root) redirect = be.get("redirect", {}).items() if redirect: lib.echo("\nRedirect:") for map_source, map_dest in sorted(redirect): lib.echo("- %s=%s" % (map_dest, os.environ.get(map_dest))) # And then everything else prefixed = dict((k, v) for k, v in os.environ.iteritems() if k.startswith("BE_")) if prefixed: lib.echo("\nPrefixed:") for key in sorted(prefixed): if not key.startswith("BE_"): continue lib.echo("- %s=%s" % (key, os.environ.get(key))) sys.exit(lib.NORMAL)
python
def dump(): """Print current environment Environment is outputted in a YAML-friendly format \b Usage: $ be dump Prefixed: - BE_TOPICS=hulk bruce animation - ... """ if not self.isactive(): lib.echo("ERROR: Enter a project first") sys.exit(lib.USER_ERROR) # Print custom environment variables first custom = sorted(os.environ.get("BE_ENVIRONMENT", "").split()) if custom: lib.echo("Custom:") for key in custom: lib.echo("- %s=%s" % (key, os.environ.get(key))) # Then print redirected variables project = os.environ["BE_PROJECT"] root = os.environ["BE_PROJECTSROOT"] be = _extern.load(project, "be", optional=True, root=root) redirect = be.get("redirect", {}).items() if redirect: lib.echo("\nRedirect:") for map_source, map_dest in sorted(redirect): lib.echo("- %s=%s" % (map_dest, os.environ.get(map_dest))) # And then everything else prefixed = dict((k, v) for k, v in os.environ.iteritems() if k.startswith("BE_")) if prefixed: lib.echo("\nPrefixed:") for key in sorted(prefixed): if not key.startswith("BE_"): continue lib.echo("- %s=%s" % (key, os.environ.get(key))) sys.exit(lib.NORMAL)
[ "def", "dump", "(", ")", ":", "if", "not", "self", ".", "isactive", "(", ")", ":", "lib", ".", "echo", "(", "\"ERROR: Enter a project first\"", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "# Print custom environment variables first", "custom",...
Print current environment Environment is outputted in a YAML-friendly format \b Usage: $ be dump Prefixed: - BE_TOPICS=hulk bruce animation - ...
[ "Print", "current", "environment" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/cli.py#L682-L727
train
mottosso/be
be/cli.py
what
def what(): """Print current topics""" if not self.isactive(): lib.echo("No topic") sys.exit(lib.USER_ERROR) lib.echo(os.environ.get("BE_TOPICS", "This is a bug"))
python
def what(): """Print current topics""" if not self.isactive(): lib.echo("No topic") sys.exit(lib.USER_ERROR) lib.echo(os.environ.get("BE_TOPICS", "This is a bug"))
[ "def", "what", "(", ")", ":", "if", "not", "self", ".", "isactive", "(", ")", ":", "lib", ".", "echo", "(", "\"No topic\"", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "lib", ".", "echo", "(", "os", ".", "environ", ".", "get", ...
Print current topics
[ "Print", "current", "topics" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/cli.py#L731-L738
train
mottosso/be
be/vendor/requests/utils.py
get_netrc_auth
def get_netrc_auth(url): """Returns the Requests tuple auth for a given url from netrc.""" try: from netrc import netrc, NetrcParseError netrc_path = None for f in NETRC_FILES: try: loc = os.path.expanduser('~/{0}'.format(f)) except KeyError: # os.path.expanduser can fail when $HOME is undefined and # getpwuid fails. See http://bugs.python.org/issue20164 & # https://github.com/kennethreitz/requests/issues/1846 return if os.path.exists(loc): netrc_path = loc break # Abort early if there isn't one. if netrc_path is None: return ri = urlparse(url) # Strip port numbers from netloc host = ri.netloc.split(':')[0] try: _netrc = netrc(netrc_path).authenticators(host) if _netrc: # Return with login / password login_i = (0 if _netrc[0] else 1) return (_netrc[login_i], _netrc[2]) except (NetrcParseError, IOError): # If there was a parsing error or a permissions issue reading the file, # we'll just skip netrc auth pass # AppEngine hackiness. except (ImportError, AttributeError): pass
python
def get_netrc_auth(url): """Returns the Requests tuple auth for a given url from netrc.""" try: from netrc import netrc, NetrcParseError netrc_path = None for f in NETRC_FILES: try: loc = os.path.expanduser('~/{0}'.format(f)) except KeyError: # os.path.expanduser can fail when $HOME is undefined and # getpwuid fails. See http://bugs.python.org/issue20164 & # https://github.com/kennethreitz/requests/issues/1846 return if os.path.exists(loc): netrc_path = loc break # Abort early if there isn't one. if netrc_path is None: return ri = urlparse(url) # Strip port numbers from netloc host = ri.netloc.split(':')[0] try: _netrc = netrc(netrc_path).authenticators(host) if _netrc: # Return with login / password login_i = (0 if _netrc[0] else 1) return (_netrc[login_i], _netrc[2]) except (NetrcParseError, IOError): # If there was a parsing error or a permissions issue reading the file, # we'll just skip netrc auth pass # AppEngine hackiness. except (ImportError, AttributeError): pass
[ "def", "get_netrc_auth", "(", "url", ")", ":", "try", ":", "from", "netrc", "import", "netrc", ",", "NetrcParseError", "netrc_path", "=", "None", "for", "f", "in", "NETRC_FILES", ":", "try", ":", "loc", "=", "os", ".", "path", ".", "expanduser", "(", "...
Returns the Requests tuple auth for a given url from netrc.
[ "Returns", "the", "Requests", "tuple", "auth", "for", "a", "given", "url", "from", "netrc", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/utils.py#L70-L113
train
mottosso/be
be/vendor/requests/utils.py
add_dict_to_cookiejar
def add_dict_to_cookiejar(cj, cookie_dict): """Returns a CookieJar from a key/value dictionary. :param cj: CookieJar to insert cookies into. :param cookie_dict: Dict of key/values to insert into CookieJar. """ cj2 = cookiejar_from_dict(cookie_dict) cj.update(cj2) return cj
python
def add_dict_to_cookiejar(cj, cookie_dict): """Returns a CookieJar from a key/value dictionary. :param cj: CookieJar to insert cookies into. :param cookie_dict: Dict of key/values to insert into CookieJar. """ cj2 = cookiejar_from_dict(cookie_dict) cj.update(cj2) return cj
[ "def", "add_dict_to_cookiejar", "(", "cj", ",", "cookie_dict", ")", ":", "cj2", "=", "cookiejar_from_dict", "(", "cookie_dict", ")", "cj", ".", "update", "(", "cj2", ")", "return", "cj" ]
Returns a CookieJar from a key/value dictionary. :param cj: CookieJar to insert cookies into. :param cookie_dict: Dict of key/values to insert into CookieJar.
[ "Returns", "a", "CookieJar", "from", "a", "key", "/", "value", "dictionary", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/utils.py#L276-L285
train
mottosso/be
be/vendor/requests/utils.py
should_bypass_proxies
def should_bypass_proxies(url): """ Returns whether we should bypass proxies or not. """ get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper()) # First check whether no_proxy is defined. If it is, check that the URL # we're getting isn't in the no_proxy list. no_proxy = get_proxy('no_proxy') netloc = urlparse(url).netloc if no_proxy: # We need to check whether we match here. We need to see if we match # the end of the netloc, both with and without the port. no_proxy = no_proxy.replace(' ', '').split(',') ip = netloc.split(':')[0] if is_ipv4_address(ip): for proxy_ip in no_proxy: if is_valid_cidr(proxy_ip): if address_in_network(ip, proxy_ip): return True else: for host in no_proxy: if netloc.endswith(host) or netloc.split(':')[0].endswith(host): # The URL does match something in no_proxy, so we don't want # to apply the proxies on this URL. return True # If the system proxy settings indicate that this URL should be bypassed, # don't proxy. # The proxy_bypass function is incredibly buggy on OS X in early versions # of Python 2.6, so allow this call to fail. Only catch the specific # exceptions we've seen, though: this call failing in other ways can reveal # legitimate problems. try: bypass = proxy_bypass(netloc) except (TypeError, socket.gaierror): bypass = False if bypass: return True return False
python
def should_bypass_proxies(url): """ Returns whether we should bypass proxies or not. """ get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper()) # First check whether no_proxy is defined. If it is, check that the URL # we're getting isn't in the no_proxy list. no_proxy = get_proxy('no_proxy') netloc = urlparse(url).netloc if no_proxy: # We need to check whether we match here. We need to see if we match # the end of the netloc, both with and without the port. no_proxy = no_proxy.replace(' ', '').split(',') ip = netloc.split(':')[0] if is_ipv4_address(ip): for proxy_ip in no_proxy: if is_valid_cidr(proxy_ip): if address_in_network(ip, proxy_ip): return True else: for host in no_proxy: if netloc.endswith(host) or netloc.split(':')[0].endswith(host): # The URL does match something in no_proxy, so we don't want # to apply the proxies on this URL. return True # If the system proxy settings indicate that this URL should be bypassed, # don't proxy. # The proxy_bypass function is incredibly buggy on OS X in early versions # of Python 2.6, so allow this call to fail. Only catch the specific # exceptions we've seen, though: this call failing in other ways can reveal # legitimate problems. try: bypass = proxy_bypass(netloc) except (TypeError, socket.gaierror): bypass = False if bypass: return True return False
[ "def", "should_bypass_proxies", "(", "url", ")", ":", "get_proxy", "=", "lambda", "k", ":", "os", ".", "environ", ".", "get", "(", "k", ")", "or", "os", ".", "environ", ".", "get", "(", "k", ".", "upper", "(", ")", ")", "# First check whether no_proxy ...
Returns whether we should bypass proxies or not.
[ "Returns", "whether", "we", "should", "bypass", "proxies", "or", "not", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/utils.py#L487-L530
train
mottosso/be
be/vendor/requests/utils.py
default_user_agent
def default_user_agent(name="python-requests"): """Return a string representing the default user agent.""" _implementation = platform.python_implementation() if _implementation == 'CPython': _implementation_version = platform.python_version() elif _implementation == 'PyPy': _implementation_version = '%s.%s.%s' % (sys.pypy_version_info.major, sys.pypy_version_info.minor, sys.pypy_version_info.micro) if sys.pypy_version_info.releaselevel != 'final': _implementation_version = ''.join([_implementation_version, sys.pypy_version_info.releaselevel]) elif _implementation == 'Jython': _implementation_version = platform.python_version() # Complete Guess elif _implementation == 'IronPython': _implementation_version = platform.python_version() # Complete Guess else: _implementation_version = 'Unknown' try: p_system = platform.system() p_release = platform.release() except IOError: p_system = 'Unknown' p_release = 'Unknown' return " ".join(['%s/%s' % (name, __version__), '%s/%s' % (_implementation, _implementation_version), '%s/%s' % (p_system, p_release)])
python
def default_user_agent(name="python-requests"): """Return a string representing the default user agent.""" _implementation = platform.python_implementation() if _implementation == 'CPython': _implementation_version = platform.python_version() elif _implementation == 'PyPy': _implementation_version = '%s.%s.%s' % (sys.pypy_version_info.major, sys.pypy_version_info.minor, sys.pypy_version_info.micro) if sys.pypy_version_info.releaselevel != 'final': _implementation_version = ''.join([_implementation_version, sys.pypy_version_info.releaselevel]) elif _implementation == 'Jython': _implementation_version = platform.python_version() # Complete Guess elif _implementation == 'IronPython': _implementation_version = platform.python_version() # Complete Guess else: _implementation_version = 'Unknown' try: p_system = platform.system() p_release = platform.release() except IOError: p_system = 'Unknown' p_release = 'Unknown' return " ".join(['%s/%s' % (name, __version__), '%s/%s' % (_implementation, _implementation_version), '%s/%s' % (p_system, p_release)])
[ "def", "default_user_agent", "(", "name", "=", "\"python-requests\"", ")", ":", "_implementation", "=", "platform", ".", "python_implementation", "(", ")", "if", "_implementation", "==", "'CPython'", ":", "_implementation_version", "=", "platform", ".", "python_versio...
Return a string representing the default user agent.
[ "Return", "a", "string", "representing", "the", "default", "user", "agent", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/utils.py#L540-L568
train
mottosso/be
be/vendor/requests/utils.py
to_native_string
def to_native_string(string, encoding='ascii'): """ Given a string object, regardless of type, returns a representation of that string in the native string type, encoding and decoding where necessary. This assumes ASCII unless told otherwise. """ out = None if isinstance(string, builtin_str): out = string else: if is_py2: out = string.encode(encoding) else: out = string.decode(encoding) return out
python
def to_native_string(string, encoding='ascii'): """ Given a string object, regardless of type, returns a representation of that string in the native string type, encoding and decoding where necessary. This assumes ASCII unless told otherwise. """ out = None if isinstance(string, builtin_str): out = string else: if is_py2: out = string.encode(encoding) else: out = string.decode(encoding) return out
[ "def", "to_native_string", "(", "string", ",", "encoding", "=", "'ascii'", ")", ":", "out", "=", "None", "if", "isinstance", "(", "string", ",", "builtin_str", ")", ":", "out", "=", "string", "else", ":", "if", "is_py2", ":", "out", "=", "string", ".",...
Given a string object, regardless of type, returns a representation of that string in the native string type, encoding and decoding where necessary. This assumes ASCII unless told otherwise.
[ "Given", "a", "string", "object", "regardless", "of", "type", "returns", "a", "representation", "of", "that", "string", "in", "the", "native", "string", "type", "encoding", "and", "decoding", "where", "necessary", ".", "This", "assumes", "ASCII", "unless", "to...
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/utils.py#L676-L692
train
mottosso/be
be/vendor/click/core.py
_bashcomplete
def _bashcomplete(cmd, prog_name, complete_var=None): """Internal handler for the bash completion support.""" if complete_var is None: complete_var = '_%s_COMPLETE' % (prog_name.replace('-', '_')).upper() complete_instr = os.environ.get(complete_var) if not complete_instr: return from ._bashcomplete import bashcomplete if bashcomplete(cmd, prog_name, complete_var, complete_instr): sys.exit(1)
python
def _bashcomplete(cmd, prog_name, complete_var=None): """Internal handler for the bash completion support.""" if complete_var is None: complete_var = '_%s_COMPLETE' % (prog_name.replace('-', '_')).upper() complete_instr = os.environ.get(complete_var) if not complete_instr: return from ._bashcomplete import bashcomplete if bashcomplete(cmd, prog_name, complete_var, complete_instr): sys.exit(1)
[ "def", "_bashcomplete", "(", "cmd", ",", "prog_name", ",", "complete_var", "=", "None", ")", ":", "if", "complete_var", "is", "None", ":", "complete_var", "=", "'_%s_COMPLETE'", "%", "(", "prog_name", ".", "replace", "(", "'-'", ",", "'_'", ")", ")", "."...
Internal handler for the bash completion support.
[ "Internal", "handler", "for", "the", "bash", "completion", "support", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/core.py#L25-L35
train
mottosso/be
be/vendor/click/core.py
Context.invoke
def invoke(*args, **kwargs): """Invokes a command callback in exactly the way it expects. There are two ways to invoke this method: 1. the first argument can be a callback and all other arguments and keyword arguments are forwarded directly to the function. 2. the first argument is a click command object. In that case all arguments are forwarded as well but proper click parameters (options and click arguments) must be keyword arguments and Click will fill in defaults. Note that before Click 3.2 keyword arguments were not properly filled in against the intention of this code and no context was created. For more information about this change and why it was done in a bugfix release see :ref:`upgrade-to-3.2`. """ self, callback = args[:2] ctx = self # This is just to improve the error message in cases where old # code incorrectly invoked this method. This will eventually be # removed. injected_arguments = False # It's also possible to invoke another command which might or # might not have a callback. In that case we also fill # in defaults and make a new context for this command. if isinstance(callback, Command): other_cmd = callback callback = other_cmd.callback ctx = Context(other_cmd, info_name=other_cmd.name, parent=self) if callback is None: raise TypeError('The given command does not have a ' 'callback that can be invoked.') for param in other_cmd.params: if param.name not in kwargs and param.expose_value: kwargs[param.name] = param.get_default(ctx) injected_arguments = True args = args[2:] if getattr(callback, '__click_pass_context__', False): args = (ctx,) + args with augment_usage_errors(self): try: with ctx: return callback(*args, **kwargs) except TypeError as e: if not injected_arguments: raise if 'got multiple values for' in str(e): raise RuntimeError( 'You called .invoke() on the context with a command ' 'but provided parameters as positional arguments. ' 'This is not supported but sometimes worked by chance ' 'in older versions of Click. To fix this see ' 'http://click.pocoo.org/upgrading/#upgrading-to-3.2') raise
python
def invoke(*args, **kwargs): """Invokes a command callback in exactly the way it expects. There are two ways to invoke this method: 1. the first argument can be a callback and all other arguments and keyword arguments are forwarded directly to the function. 2. the first argument is a click command object. In that case all arguments are forwarded as well but proper click parameters (options and click arguments) must be keyword arguments and Click will fill in defaults. Note that before Click 3.2 keyword arguments were not properly filled in against the intention of this code and no context was created. For more information about this change and why it was done in a bugfix release see :ref:`upgrade-to-3.2`. """ self, callback = args[:2] ctx = self # This is just to improve the error message in cases where old # code incorrectly invoked this method. This will eventually be # removed. injected_arguments = False # It's also possible to invoke another command which might or # might not have a callback. In that case we also fill # in defaults and make a new context for this command. if isinstance(callback, Command): other_cmd = callback callback = other_cmd.callback ctx = Context(other_cmd, info_name=other_cmd.name, parent=self) if callback is None: raise TypeError('The given command does not have a ' 'callback that can be invoked.') for param in other_cmd.params: if param.name not in kwargs and param.expose_value: kwargs[param.name] = param.get_default(ctx) injected_arguments = True args = args[2:] if getattr(callback, '__click_pass_context__', False): args = (ctx,) + args with augment_usage_errors(self): try: with ctx: return callback(*args, **kwargs) except TypeError as e: if not injected_arguments: raise if 'got multiple values for' in str(e): raise RuntimeError( 'You called .invoke() on the context with a command ' 'but provided parameters as positional arguments. ' 'This is not supported but sometimes worked by chance ' 'in older versions of Click. To fix this see ' 'http://click.pocoo.org/upgrading/#upgrading-to-3.2') raise
[ "def", "invoke", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ",", "callback", "=", "args", "[", ":", "2", "]", "ctx", "=", "self", "# This is just to improve the error message in cases where old", "# code incorrectly invoked this method. This will ev...
Invokes a command callback in exactly the way it expects. There are two ways to invoke this method: 1. the first argument can be a callback and all other arguments and keyword arguments are forwarded directly to the function. 2. the first argument is a click command object. In that case all arguments are forwarded as well but proper click parameters (options and click arguments) must be keyword arguments and Click will fill in defaults. Note that before Click 3.2 keyword arguments were not properly filled in against the intention of this code and no context was created. For more information about this change and why it was done in a bugfix release see :ref:`upgrade-to-3.2`.
[ "Invokes", "a", "command", "callback", "in", "exactly", "the", "way", "it", "expects", ".", "There", "are", "two", "ways", "to", "invoke", "this", "method", ":" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/core.py#L418-L475
train
mottosso/be
be/vendor/click/core.py
BaseCommand.make_context
def make_context(self, info_name, args, parent=None, **extra): """This function when given an info name and arguments will kick off the parsing and create a new :class:`Context`. It does not invoke the actual command callback though. :param info_name: the info name for this invokation. Generally this is the most descriptive name for the script or command. For the toplevel script it's usually the name of the script, for commands below it it's the name of the script. :param args: the arguments to parse as list of strings. :param parent: the parent context if available. :param extra: extra keyword arguments forwarded to the context constructor. """ for key, value in iteritems(self.context_settings): if key not in extra: extra[key] = value ctx = Context(self, info_name=info_name, parent=parent, **extra) self.parse_args(ctx, args) return ctx
python
def make_context(self, info_name, args, parent=None, **extra): """This function when given an info name and arguments will kick off the parsing and create a new :class:`Context`. It does not invoke the actual command callback though. :param info_name: the info name for this invokation. Generally this is the most descriptive name for the script or command. For the toplevel script it's usually the name of the script, for commands below it it's the name of the script. :param args: the arguments to parse as list of strings. :param parent: the parent context if available. :param extra: extra keyword arguments forwarded to the context constructor. """ for key, value in iteritems(self.context_settings): if key not in extra: extra[key] = value ctx = Context(self, info_name=info_name, parent=parent, **extra) self.parse_args(ctx, args) return ctx
[ "def", "make_context", "(", "self", ",", "info_name", ",", "args", ",", "parent", "=", "None", ",", "*", "*", "extra", ")", ":", "for", "key", ",", "value", "in", "iteritems", "(", "self", ".", "context_settings", ")", ":", "if", "key", "not", "in", ...
This function when given an info name and arguments will kick off the parsing and create a new :class:`Context`. It does not invoke the actual command callback though. :param info_name: the info name for this invokation. Generally this is the most descriptive name for the script or command. For the toplevel script it's usually the name of the script, for commands below it it's the name of the script. :param args: the arguments to parse as list of strings. :param parent: the parent context if available. :param extra: extra keyword arguments forwarded to the context constructor.
[ "This", "function", "when", "given", "an", "info", "name", "and", "arguments", "will", "kick", "off", "the", "parsing", "and", "create", "a", "new", ":", "class", ":", "Context", ".", "It", "does", "not", "invoke", "the", "actual", "command", "callback", ...
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/core.py#L541-L561
train
mottosso/be
be/vendor/click/core.py
BaseCommand.main
def main(self, args=None, prog_name=None, complete_var=None, standalone_mode=True, **extra): """This is the way to invoke a script with all the bells and whistles as a command line application. This will always terminate the application after a call. If this is not wanted, ``SystemExit`` needs to be caught. This method is also available by directly calling the instance of a :class:`Command`. .. versionadded:: 3.0 Added the `standalone_mode` flag to control the standalone mode. :param args: the arguments that should be used for parsing. If not provided, ``sys.argv[1:]`` is used. :param prog_name: the program name that should be used. By default the program name is constructed by taking the file name from ``sys.argv[0]``. :param complete_var: the environment variable that controls the bash completion support. The default is ``"_<prog_name>_COMPLETE"`` with prog name in uppercase. :param standalone_mode: the default behavior is to invoke the script in standalone mode. Click will then handle exceptions and convert them into error messages and the function will never return but shut down the interpreter. If this is set to `False` they will be propagated to the caller and the return value of this function is the return value of :meth:`invoke`. :param extra: extra keyword arguments are forwarded to the context constructor. See :class:`Context` for more information. """ # If we are in Python 3, we will verify that the environment is # sane at this point of reject further execution to avoid a # broken script. if not PY2: try: import locale fs_enc = codecs.lookup(locale.getpreferredencoding()).name except Exception: fs_enc = 'ascii' if fs_enc == 'ascii': raise RuntimeError('Click will abort further execution ' 'because Python 3 was configured to use ' 'ASCII as encoding for the environment. ' 'Either switch to Python 2 or consult ' 'http://click.pocoo.org/python3/ ' 'for mitigation steps.') if args is None: args = sys.argv[1:] else: args = list(args) if prog_name is None: prog_name = make_str(os.path.basename( sys.argv and sys.argv[0] or __file__)) # Hook for the Bash completion. This only activates if the Bash # completion is actually enabled, otherwise this is quite a fast # noop. _bashcomplete(self, prog_name, complete_var) try: try: with self.make_context(prog_name, args, **extra) as ctx: rv = self.invoke(ctx) if not standalone_mode: return rv ctx.exit() except (EOFError, KeyboardInterrupt): echo(file=sys.stderr) raise Abort() except ClickException as e: if not standalone_mode: raise e.show() sys.exit(e.exit_code) except Abort: if not standalone_mode: raise echo('Aborted!', file=sys.stderr) sys.exit(1)
python
def main(self, args=None, prog_name=None, complete_var=None, standalone_mode=True, **extra): """This is the way to invoke a script with all the bells and whistles as a command line application. This will always terminate the application after a call. If this is not wanted, ``SystemExit`` needs to be caught. This method is also available by directly calling the instance of a :class:`Command`. .. versionadded:: 3.0 Added the `standalone_mode` flag to control the standalone mode. :param args: the arguments that should be used for parsing. If not provided, ``sys.argv[1:]`` is used. :param prog_name: the program name that should be used. By default the program name is constructed by taking the file name from ``sys.argv[0]``. :param complete_var: the environment variable that controls the bash completion support. The default is ``"_<prog_name>_COMPLETE"`` with prog name in uppercase. :param standalone_mode: the default behavior is to invoke the script in standalone mode. Click will then handle exceptions and convert them into error messages and the function will never return but shut down the interpreter. If this is set to `False` they will be propagated to the caller and the return value of this function is the return value of :meth:`invoke`. :param extra: extra keyword arguments are forwarded to the context constructor. See :class:`Context` for more information. """ # If we are in Python 3, we will verify that the environment is # sane at this point of reject further execution to avoid a # broken script. if not PY2: try: import locale fs_enc = codecs.lookup(locale.getpreferredencoding()).name except Exception: fs_enc = 'ascii' if fs_enc == 'ascii': raise RuntimeError('Click will abort further execution ' 'because Python 3 was configured to use ' 'ASCII as encoding for the environment. ' 'Either switch to Python 2 or consult ' 'http://click.pocoo.org/python3/ ' 'for mitigation steps.') if args is None: args = sys.argv[1:] else: args = list(args) if prog_name is None: prog_name = make_str(os.path.basename( sys.argv and sys.argv[0] or __file__)) # Hook for the Bash completion. This only activates if the Bash # completion is actually enabled, otherwise this is quite a fast # noop. _bashcomplete(self, prog_name, complete_var) try: try: with self.make_context(prog_name, args, **extra) as ctx: rv = self.invoke(ctx) if not standalone_mode: return rv ctx.exit() except (EOFError, KeyboardInterrupt): echo(file=sys.stderr) raise Abort() except ClickException as e: if not standalone_mode: raise e.show() sys.exit(e.exit_code) except Abort: if not standalone_mode: raise echo('Aborted!', file=sys.stderr) sys.exit(1)
[ "def", "main", "(", "self", ",", "args", "=", "None", ",", "prog_name", "=", "None", ",", "complete_var", "=", "None", ",", "standalone_mode", "=", "True", ",", "*", "*", "extra", ")", ":", "# If we are in Python 3, we will verify that the environment is", "# sa...
This is the way to invoke a script with all the bells and whistles as a command line application. This will always terminate the application after a call. If this is not wanted, ``SystemExit`` needs to be caught. This method is also available by directly calling the instance of a :class:`Command`. .. versionadded:: 3.0 Added the `standalone_mode` flag to control the standalone mode. :param args: the arguments that should be used for parsing. If not provided, ``sys.argv[1:]`` is used. :param prog_name: the program name that should be used. By default the program name is constructed by taking the file name from ``sys.argv[0]``. :param complete_var: the environment variable that controls the bash completion support. The default is ``"_<prog_name>_COMPLETE"`` with prog name in uppercase. :param standalone_mode: the default behavior is to invoke the script in standalone mode. Click will then handle exceptions and convert them into error messages and the function will never return but shut down the interpreter. If this is set to `False` they will be propagated to the caller and the return value of this function is the return value of :meth:`invoke`. :param extra: extra keyword arguments are forwarded to the context constructor. See :class:`Context` for more information.
[ "This", "is", "the", "way", "to", "invoke", "a", "script", "with", "all", "the", "bells", "and", "whistles", "as", "a", "command", "line", "application", ".", "This", "will", "always", "terminate", "the", "application", "after", "a", "call", ".", "If", "...
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/core.py#L577-L660
train
mottosso/be
be/vendor/click/core.py
Command.make_parser
def make_parser(self, ctx): """Creates the underlying option parser for this command.""" parser = OptionParser(ctx) parser.allow_interspersed_args = ctx.allow_interspersed_args parser.ignore_unknown_options = ctx.ignore_unknown_options for param in self.get_params(ctx): param.add_to_parser(parser, ctx) return parser
python
def make_parser(self, ctx): """Creates the underlying option parser for this command.""" parser = OptionParser(ctx) parser.allow_interspersed_args = ctx.allow_interspersed_args parser.ignore_unknown_options = ctx.ignore_unknown_options for param in self.get_params(ctx): param.add_to_parser(parser, ctx) return parser
[ "def", "make_parser", "(", "self", ",", "ctx", ")", ":", "parser", "=", "OptionParser", "(", "ctx", ")", "parser", ".", "allow_interspersed_args", "=", "ctx", ".", "allow_interspersed_args", "parser", ".", "ignore_unknown_options", "=", "ctx", ".", "ignore_unkno...
Creates the underlying option parser for this command.
[ "Creates", "the", "underlying", "option", "parser", "for", "this", "command", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/core.py#L758-L765
train
mottosso/be
be/vendor/click/core.py
Command.format_help_text
def format_help_text(self, ctx, formatter): """Writes the help text to the formatter if it exists.""" if self.help: formatter.write_paragraph() with formatter.indentation(): formatter.write_text(self.help)
python
def format_help_text(self, ctx, formatter): """Writes the help text to the formatter if it exists.""" if self.help: formatter.write_paragraph() with formatter.indentation(): formatter.write_text(self.help)
[ "def", "format_help_text", "(", "self", ",", "ctx", ",", "formatter", ")", ":", "if", "self", ".", "help", ":", "formatter", ".", "write_paragraph", "(", ")", "with", "formatter", ".", "indentation", "(", ")", ":", "formatter", ".", "write_text", "(", "s...
Writes the help text to the formatter if it exists.
[ "Writes", "the", "help", "text", "to", "the", "formatter", "if", "it", "exists", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/core.py#L790-L795
train
mottosso/be
be/vendor/click/core.py
Group.add_command
def add_command(self, cmd, name=None): """Registers another :class:`Command` with this group. If the name is not provided, the name of the command is used. """ name = name or cmd.name if name is None: raise TypeError('Command has no name.') self.commands[name] = cmd
python
def add_command(self, cmd, name=None): """Registers another :class:`Command` with this group. If the name is not provided, the name of the command is used. """ name = name or cmd.name if name is None: raise TypeError('Command has no name.') self.commands[name] = cmd
[ "def", "add_command", "(", "self", ",", "cmd", ",", "name", "=", "None", ")", ":", "name", "=", "name", "or", "cmd", ".", "name", "if", "name", "is", "None", ":", "raise", "TypeError", "(", "'Command has no name.'", ")", "self", ".", "commands", "[", ...
Registers another :class:`Command` with this group. If the name is not provided, the name of the command is used.
[ "Registers", "another", ":", "class", ":", "Command", "with", "this", "group", ".", "If", "the", "name", "is", "not", "provided", "the", "name", "of", "the", "command", "is", "used", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/core.py#L1071-L1078
train
mottosso/be
be/vendor/click/decorators.py
pass_obj
def pass_obj(f): """Similar to :func:`pass_context`, but only pass the object on the context onwards (:attr:`Context.obj`). This is useful if that object represents the state of a nested system. """ @pass_context def new_func(*args, **kwargs): ctx = args[0] return ctx.invoke(f, ctx.obj, *args[1:], **kwargs) return update_wrapper(new_func, f)
python
def pass_obj(f): """Similar to :func:`pass_context`, but only pass the object on the context onwards (:attr:`Context.obj`). This is useful if that object represents the state of a nested system. """ @pass_context def new_func(*args, **kwargs): ctx = args[0] return ctx.invoke(f, ctx.obj, *args[1:], **kwargs) return update_wrapper(new_func, f)
[ "def", "pass_obj", "(", "f", ")", ":", "@", "pass_context", "def", "new_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ctx", "=", "args", "[", "0", "]", "return", "ctx", ".", "invoke", "(", "f", ",", "ctx", ".", "obj", ",", "*", ...
Similar to :func:`pass_context`, but only pass the object on the context onwards (:attr:`Context.obj`). This is useful if that object represents the state of a nested system.
[ "Similar", "to", ":", "func", ":", "pass_context", "but", "only", "pass", "the", "object", "on", "the", "context", "onwards", "(", ":", "attr", ":", "Context", ".", "obj", ")", ".", "This", "is", "useful", "if", "that", "object", "represents", "the", "...
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/decorators.py#L18-L27
train
mottosso/be
be/vendor/click/decorators.py
option
def option(*param_decls, **attrs): """Attaches an option to the command. All positional arguments are passed as parameter declarations to :class:`Option`; all keyword arguments are forwarded unchanged (except ``cls``). This is equivalent to creating an :class:`Option` instance manually and attaching it to the :attr:`Command.params` list. :param cls: the option class to instantiate. This defaults to :class:`Option`. """ def decorator(f): if 'help' in attrs: attrs['help'] = inspect.cleandoc(attrs['help']) OptionClass = attrs.pop('cls', Option) _param_memo(f, OptionClass(param_decls, **attrs)) return f return decorator
python
def option(*param_decls, **attrs): """Attaches an option to the command. All positional arguments are passed as parameter declarations to :class:`Option`; all keyword arguments are forwarded unchanged (except ``cls``). This is equivalent to creating an :class:`Option` instance manually and attaching it to the :attr:`Command.params` list. :param cls: the option class to instantiate. This defaults to :class:`Option`. """ def decorator(f): if 'help' in attrs: attrs['help'] = inspect.cleandoc(attrs['help']) OptionClass = attrs.pop('cls', Option) _param_memo(f, OptionClass(param_decls, **attrs)) return f return decorator
[ "def", "option", "(", "*", "param_decls", ",", "*", "*", "attrs", ")", ":", "def", "decorator", "(", "f", ")", ":", "if", "'help'", "in", "attrs", ":", "attrs", "[", "'help'", "]", "=", "inspect", ".", "cleandoc", "(", "attrs", "[", "'help'", "]", ...
Attaches an option to the command. All positional arguments are passed as parameter declarations to :class:`Option`; all keyword arguments are forwarded unchanged (except ``cls``). This is equivalent to creating an :class:`Option` instance manually and attaching it to the :attr:`Command.params` list. :param cls: the option class to instantiate. This defaults to :class:`Option`.
[ "Attaches", "an", "option", "to", "the", "command", ".", "All", "positional", "arguments", "are", "passed", "as", "parameter", "declarations", "to", ":", "class", ":", "Option", ";", "all", "keyword", "arguments", "are", "forwarded", "unchanged", "(", "except"...
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/decorators.py#L153-L169
train
mottosso/be
be/vendor/click/decorators.py
version_option
def version_option(version=None, *param_decls, **attrs): """Adds a ``--version`` option which immediately ends the program printing out the version number. This is implemented as an eager option that prints the version and exits the program in the callback. :param version: the version number to show. If not provided Click attempts an auto discovery via setuptools. :param prog_name: the name of the program (defaults to autodetection) :param message: custom message to show instead of the default (``'%(prog)s, version %(version)s'``) :param others: everything else is forwarded to :func:`option`. """ if version is None: module = sys._getframe(1).f_globals.get('__name__') def decorator(f): prog_name = attrs.pop('prog_name', None) message = attrs.pop('message', '%(prog)s, version %(version)s') def callback(ctx, param, value): if not value or ctx.resilient_parsing: return prog = prog_name if prog is None: prog = ctx.find_root().info_name ver = version if ver is None: try: import pkg_resources except ImportError: pass else: for dist in pkg_resources.working_set: scripts = dist.get_entry_map().get('console_scripts') or {} for script_name, entry_point in iteritems(scripts): if entry_point.module_name == module: ver = dist.version break if ver is None: raise RuntimeError('Could not determine version') echo(message % { 'prog': prog, 'version': ver, }, color=ctx.color) ctx.exit() attrs.setdefault('is_flag', True) attrs.setdefault('expose_value', False) attrs.setdefault('is_eager', True) attrs.setdefault('help', 'Show the version and exit.') attrs['callback'] = callback return option(*(param_decls or ('--version',)), **attrs)(f) return decorator
python
def version_option(version=None, *param_decls, **attrs): """Adds a ``--version`` option which immediately ends the program printing out the version number. This is implemented as an eager option that prints the version and exits the program in the callback. :param version: the version number to show. If not provided Click attempts an auto discovery via setuptools. :param prog_name: the name of the program (defaults to autodetection) :param message: custom message to show instead of the default (``'%(prog)s, version %(version)s'``) :param others: everything else is forwarded to :func:`option`. """ if version is None: module = sys._getframe(1).f_globals.get('__name__') def decorator(f): prog_name = attrs.pop('prog_name', None) message = attrs.pop('message', '%(prog)s, version %(version)s') def callback(ctx, param, value): if not value or ctx.resilient_parsing: return prog = prog_name if prog is None: prog = ctx.find_root().info_name ver = version if ver is None: try: import pkg_resources except ImportError: pass else: for dist in pkg_resources.working_set: scripts = dist.get_entry_map().get('console_scripts') or {} for script_name, entry_point in iteritems(scripts): if entry_point.module_name == module: ver = dist.version break if ver is None: raise RuntimeError('Could not determine version') echo(message % { 'prog': prog, 'version': ver, }, color=ctx.color) ctx.exit() attrs.setdefault('is_flag', True) attrs.setdefault('expose_value', False) attrs.setdefault('is_eager', True) attrs.setdefault('help', 'Show the version and exit.') attrs['callback'] = callback return option(*(param_decls or ('--version',)), **attrs)(f) return decorator
[ "def", "version_option", "(", "version", "=", "None", ",", "*", "param_decls", ",", "*", "*", "attrs", ")", ":", "if", "version", "is", "None", ":", "module", "=", "sys", ".", "_getframe", "(", "1", ")", ".", "f_globals", ".", "get", "(", "'__name__'...
Adds a ``--version`` option which immediately ends the program printing out the version number. This is implemented as an eager option that prints the version and exits the program in the callback. :param version: the version number to show. If not provided Click attempts an auto discovery via setuptools. :param prog_name: the name of the program (defaults to autodetection) :param message: custom message to show instead of the default (``'%(prog)s, version %(version)s'``) :param others: everything else is forwarded to :func:`option`.
[ "Adds", "a", "--", "version", "option", "which", "immediately", "ends", "the", "program", "printing", "out", "the", "version", "number", ".", "This", "is", "implemented", "as", "an", "eager", "option", "that", "prints", "the", "version", "and", "exits", "the...
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/decorators.py#L222-L273
train
mottosso/be
be/vendor/requests/auth.py
_basic_auth_str
def _basic_auth_str(username, password): """Returns a Basic Auth string.""" authstr = 'Basic ' + to_native_string( b64encode(('%s:%s' % (username, password)).encode('latin1')).strip() ) return authstr
python
def _basic_auth_str(username, password): """Returns a Basic Auth string.""" authstr = 'Basic ' + to_native_string( b64encode(('%s:%s' % (username, password)).encode('latin1')).strip() ) return authstr
[ "def", "_basic_auth_str", "(", "username", ",", "password", ")", ":", "authstr", "=", "'Basic '", "+", "to_native_string", "(", "b64encode", "(", "(", "'%s:%s'", "%", "(", "username", ",", "password", ")", ")", ".", "encode", "(", "'latin1'", ")", ")", "...
Returns a Basic Auth string.
[ "Returns", "a", "Basic", "Auth", "string", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/auth.py#L26-L33
train
mottosso/be
be/util.py
ls
def ls(*topic, **kwargs): """List topic from external datastore Arguments: topic (str): One or more topics, e.g. ("project", "item", "task") root (str, optional): Absolute path to where projects reside, defaults to os.getcwd() backend (callable, optional): Function to call with absolute path as argument to retrieve children. Defaults to os.listdir absolute (bool, optional): Whether to return relative or absolute paths Example: >> ls() /projects/thedeal /projects/hulk >> ls("thedeal") /projects/thedeal/assets/ben /projects/thedeal/assets/table >> ls("thedeal", "ben") /projects/thedeal/assets/ben/rigging /projects/thedeal/assets/ben/modeling """ context = dump() root = kwargs.get("root") or context.get("cwd") or os.getcwd() backend = kwargs.get("backend", os.listdir) absolute = kwargs.get("absolute", True) content = { 0: "projects", 1: "inventory", 2: "template" }[min(2, len(topic))] # List projects if content == "projects": projects = lib.list_projects(root=root, backend=backend) if absolute: return map(lambda p: os.path.join(root, p), projects) else: return projects # List items if content == "inventory": project = topic[0] be = _extern.load(project, "be", root=root) inventory = _extern.load(project, "inventory", root=root) inventory = lib.invert_inventory(inventory) templates = _extern.load(project, "templates", root=root) if absolute: paths = list() for item, binding in inventory.iteritems(): template = templates.get(binding) index = len(topic) sliced = lib.slice(index, template) paths.append(sliced.format(*(topic + (item,)), **context)) return paths else: return inventory.keys() # List template if content == "template": project = topic[0] be = _extern.load(project, "be", root=root) templates = _extern.load(project, "templates", root=root) inventory = _extern.load(project, "inventory", root=root) return lib.list_template(root=root, topics=topic, templates=templates, inventory=inventory, be=be, absolute=absolute)
python
def ls(*topic, **kwargs): """List topic from external datastore Arguments: topic (str): One or more topics, e.g. ("project", "item", "task") root (str, optional): Absolute path to where projects reside, defaults to os.getcwd() backend (callable, optional): Function to call with absolute path as argument to retrieve children. Defaults to os.listdir absolute (bool, optional): Whether to return relative or absolute paths Example: >> ls() /projects/thedeal /projects/hulk >> ls("thedeal") /projects/thedeal/assets/ben /projects/thedeal/assets/table >> ls("thedeal", "ben") /projects/thedeal/assets/ben/rigging /projects/thedeal/assets/ben/modeling """ context = dump() root = kwargs.get("root") or context.get("cwd") or os.getcwd() backend = kwargs.get("backend", os.listdir) absolute = kwargs.get("absolute", True) content = { 0: "projects", 1: "inventory", 2: "template" }[min(2, len(topic))] # List projects if content == "projects": projects = lib.list_projects(root=root, backend=backend) if absolute: return map(lambda p: os.path.join(root, p), projects) else: return projects # List items if content == "inventory": project = topic[0] be = _extern.load(project, "be", root=root) inventory = _extern.load(project, "inventory", root=root) inventory = lib.invert_inventory(inventory) templates = _extern.load(project, "templates", root=root) if absolute: paths = list() for item, binding in inventory.iteritems(): template = templates.get(binding) index = len(topic) sliced = lib.slice(index, template) paths.append(sliced.format(*(topic + (item,)), **context)) return paths else: return inventory.keys() # List template if content == "template": project = topic[0] be = _extern.load(project, "be", root=root) templates = _extern.load(project, "templates", root=root) inventory = _extern.load(project, "inventory", root=root) return lib.list_template(root=root, topics=topic, templates=templates, inventory=inventory, be=be, absolute=absolute)
[ "def", "ls", "(", "*", "topic", ",", "*", "*", "kwargs", ")", ":", "context", "=", "dump", "(", ")", "root", "=", "kwargs", ".", "get", "(", "\"root\"", ")", "or", "context", ".", "get", "(", "\"cwd\"", ")", "or", "os", ".", "getcwd", "(", ")",...
List topic from external datastore Arguments: topic (str): One or more topics, e.g. ("project", "item", "task") root (str, optional): Absolute path to where projects reside, defaults to os.getcwd() backend (callable, optional): Function to call with absolute path as argument to retrieve children. Defaults to os.listdir absolute (bool, optional): Whether to return relative or absolute paths Example: >> ls() /projects/thedeal /projects/hulk >> ls("thedeal") /projects/thedeal/assets/ben /projects/thedeal/assets/table >> ls("thedeal", "ben") /projects/thedeal/assets/ben/rigging /projects/thedeal/assets/ben/modeling
[ "List", "topic", "from", "external", "datastore" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/util.py#L7-L82
train
mottosso/be
be/util.py
dump
def dump(context=os.environ): """Dump current environment as a dictionary Arguments: context (dict, optional): Current context, defaults to the current environment. """ output = {} for key, value in context.iteritems(): if not key.startswith("BE_"): continue output[key[3:].lower()] = value return output
python
def dump(context=os.environ): """Dump current environment as a dictionary Arguments: context (dict, optional): Current context, defaults to the current environment. """ output = {} for key, value in context.iteritems(): if not key.startswith("BE_"): continue output[key[3:].lower()] = value return output
[ "def", "dump", "(", "context", "=", "os", ".", "environ", ")", ":", "output", "=", "{", "}", "for", "key", ",", "value", "in", "context", ".", "iteritems", "(", ")", ":", "if", "not", "key", ".", "startswith", "(", "\"BE_\"", ")", ":", "continue", ...
Dump current environment as a dictionary Arguments: context (dict, optional): Current context, defaults to the current environment.
[ "Dump", "current", "environment", "as", "a", "dictionary" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/util.py#L100-L115
train
mottosso/be
be/_extern.py
cwd
def cwd(): """Return the be current working directory""" cwd = os.environ.get("BE_CWD") if cwd and not os.path.isdir(cwd): sys.stderr.write("ERROR: %s is not a directory" % cwd) sys.exit(lib.USER_ERROR) return cwd or os.getcwd().replace("\\", "/")
python
def cwd(): """Return the be current working directory""" cwd = os.environ.get("BE_CWD") if cwd and not os.path.isdir(cwd): sys.stderr.write("ERROR: %s is not a directory" % cwd) sys.exit(lib.USER_ERROR) return cwd or os.getcwd().replace("\\", "/")
[ "def", "cwd", "(", ")", ":", "cwd", "=", "os", ".", "environ", ".", "get", "(", "\"BE_CWD\"", ")", "if", "cwd", "and", "not", "os", ".", "path", ".", "isdir", "(", "cwd", ")", ":", "sys", ".", "stderr", ".", "write", "(", "\"ERROR: %s is not a dire...
Return the be current working directory
[ "Return", "the", "be", "current", "working", "directory" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/_extern.py#L52-L58
train
mottosso/be
be/_extern.py
write_script
def write_script(script, tempdir): """Write script to a temporary directory Arguments: script (list): Commands which to put into a file Returns: Absolute path to script """ name = "script" + self.suffix path = os.path.join(tempdir, name) with open(path, "w") as f: f.write("\n".join(script)) return path
python
def write_script(script, tempdir): """Write script to a temporary directory Arguments: script (list): Commands which to put into a file Returns: Absolute path to script """ name = "script" + self.suffix path = os.path.join(tempdir, name) with open(path, "w") as f: f.write("\n".join(script)) return path
[ "def", "write_script", "(", "script", ",", "tempdir", ")", ":", "name", "=", "\"script\"", "+", "self", ".", "suffix", "path", "=", "os", ".", "path", ".", "join", "(", "tempdir", ",", "name", ")", "with", "open", "(", "path", ",", "\"w\"", ")", "a...
Write script to a temporary directory Arguments: script (list): Commands which to put into a file Returns: Absolute path to script
[ "Write", "script", "to", "a", "temporary", "directory" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/_extern.py#L105-L122
train
mottosso/be
be/_extern.py
write_aliases
def write_aliases(aliases, tempdir): """Write aliases to temporary directory Arguments: aliases (dict): {name: value} dict of aliases tempdir (str): Absolute path to where aliases will be stored """ platform = lib.platform() if platform == "unix": home_alias = "cd $BE_DEVELOPMENTDIR" else: home_alias = "cd %BE_DEVELOPMENTDIR%" aliases["home"] = home_alias tempdir = os.path.join(tempdir, "aliases") os.makedirs(tempdir) for alias, cmd in aliases.iteritems(): path = os.path.join(tempdir, alias) if platform == "windows": path += ".bat" with open(path, "w") as f: f.write(cmd) if platform == "unix": # Make executable st = os.stat(path) os.chmod(path, st.st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) return tempdir
python
def write_aliases(aliases, tempdir): """Write aliases to temporary directory Arguments: aliases (dict): {name: value} dict of aliases tempdir (str): Absolute path to where aliases will be stored """ platform = lib.platform() if platform == "unix": home_alias = "cd $BE_DEVELOPMENTDIR" else: home_alias = "cd %BE_DEVELOPMENTDIR%" aliases["home"] = home_alias tempdir = os.path.join(tempdir, "aliases") os.makedirs(tempdir) for alias, cmd in aliases.iteritems(): path = os.path.join(tempdir, alias) if platform == "windows": path += ".bat" with open(path, "w") as f: f.write(cmd) if platform == "unix": # Make executable st = os.stat(path) os.chmod(path, st.st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) return tempdir
[ "def", "write_aliases", "(", "aliases", ",", "tempdir", ")", ":", "platform", "=", "lib", ".", "platform", "(", ")", "if", "platform", "==", "\"unix\"", ":", "home_alias", "=", "\"cd $BE_DEVELOPMENTDIR\"", "else", ":", "home_alias", "=", "\"cd %BE_DEVELOPMENTDIR...
Write aliases to temporary directory Arguments: aliases (dict): {name: value} dict of aliases tempdir (str): Absolute path to where aliases will be stored
[ "Write", "aliases", "to", "temporary", "directory" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/_extern.py#L125-L160
train
mottosso/be
be/_extern.py
presets_dir
def presets_dir(): """Return presets directory""" default_presets_dir = os.path.join( os.path.expanduser("~"), ".be", "presets") presets_dir = os.environ.get(BE_PRESETSDIR) or default_presets_dir if not os.path.exists(presets_dir): os.makedirs(presets_dir) return presets_dir
python
def presets_dir(): """Return presets directory""" default_presets_dir = os.path.join( os.path.expanduser("~"), ".be", "presets") presets_dir = os.environ.get(BE_PRESETSDIR) or default_presets_dir if not os.path.exists(presets_dir): os.makedirs(presets_dir) return presets_dir
[ "def", "presets_dir", "(", ")", ":", "default_presets_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "expanduser", "(", "\"~\"", ")", ",", "\".be\"", ",", "\"presets\"", ")", "presets_dir", "=", "os", ".", "environ", ".", "get"...
Return presets directory
[ "Return", "presets", "directory" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/_extern.py#L168-L175
train
mottosso/be
be/_extern.py
remove_preset
def remove_preset(preset): """Physically delete local preset Arguments: preset (str): Name of preset """ preset_dir = os.path.join(presets_dir(), preset) try: shutil.rmtree(preset_dir) except IOError: lib.echo("\"%s\" did not exist" % preset)
python
def remove_preset(preset): """Physically delete local preset Arguments: preset (str): Name of preset """ preset_dir = os.path.join(presets_dir(), preset) try: shutil.rmtree(preset_dir) except IOError: lib.echo("\"%s\" did not exist" % preset)
[ "def", "remove_preset", "(", "preset", ")", ":", "preset_dir", "=", "os", ".", "path", ".", "join", "(", "presets_dir", "(", ")", ",", "preset", ")", "try", ":", "shutil", ".", "rmtree", "(", "preset_dir", ")", "except", "IOError", ":", "lib", ".", "...
Physically delete local preset Arguments: preset (str): Name of preset
[ "Physically", "delete", "local", "preset" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/_extern.py#L178-L191
train
mottosso/be
be/_extern.py
get
def get(path, **kwargs): """requests.get wrapper""" token = os.environ.get(BE_GITHUB_API_TOKEN) if token: kwargs["headers"] = { "Authorization": "token %s" % token } try: response = requests.get(path, verify=False, **kwargs) if response.status_code == 403: lib.echo("Patience: You can't pull more than 60 " "presets per hour without an API token.\n" "See https://github.com/mottosso/be/wiki" "/advanced#extended-preset-access") sys.exit(lib.USER_ERROR) return response except Exception as e: if self.verbose: lib.echo("ERROR: %s" % e) else: lib.echo("ERROR: Something went wrong. " "See --verbose for more information")
python
def get(path, **kwargs): """requests.get wrapper""" token = os.environ.get(BE_GITHUB_API_TOKEN) if token: kwargs["headers"] = { "Authorization": "token %s" % token } try: response = requests.get(path, verify=False, **kwargs) if response.status_code == 403: lib.echo("Patience: You can't pull more than 60 " "presets per hour without an API token.\n" "See https://github.com/mottosso/be/wiki" "/advanced#extended-preset-access") sys.exit(lib.USER_ERROR) return response except Exception as e: if self.verbose: lib.echo("ERROR: %s" % e) else: lib.echo("ERROR: Something went wrong. " "See --verbose for more information")
[ "def", "get", "(", "path", ",", "*", "*", "kwargs", ")", ":", "token", "=", "os", ".", "environ", ".", "get", "(", "BE_GITHUB_API_TOKEN", ")", "if", "token", ":", "kwargs", "[", "\"headers\"", "]", "=", "{", "\"Authorization\"", ":", "\"token %s\"", "%...
requests.get wrapper
[ "requests", ".", "get", "wrapper" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/_extern.py#L194-L216
train
mottosso/be
be/_extern.py
_gist_is_preset
def _gist_is_preset(repo): """Evaluate whether gist is a be package Arguments: gist (str): username/id pair e.g. mottosso/2bb4651a05af85711cde """ _, gistid = repo.split("/") gist_template = "https://api.github.com/gists/{}" gist_path = gist_template.format(gistid) response = get(gist_path) if response.status_code == 404: return False try: data = response.json() except: return False files = data.get("files", {}) package = files.get("package.json", {}) try: content = json.loads(package.get("content", "")) except: return False if content.get("type") != "bepreset": return False return True
python
def _gist_is_preset(repo): """Evaluate whether gist is a be package Arguments: gist (str): username/id pair e.g. mottosso/2bb4651a05af85711cde """ _, gistid = repo.split("/") gist_template = "https://api.github.com/gists/{}" gist_path = gist_template.format(gistid) response = get(gist_path) if response.status_code == 404: return False try: data = response.json() except: return False files = data.get("files", {}) package = files.get("package.json", {}) try: content = json.loads(package.get("content", "")) except: return False if content.get("type") != "bepreset": return False return True
[ "def", "_gist_is_preset", "(", "repo", ")", ":", "_", ",", "gistid", "=", "repo", ".", "split", "(", "\"/\"", ")", "gist_template", "=", "\"https://api.github.com/gists/{}\"", "gist_path", "=", "gist_template", ".", "format", "(", "gistid", ")", "response", "=...
Evaluate whether gist is a be package Arguments: gist (str): username/id pair e.g. mottosso/2bb4651a05af85711cde
[ "Evaluate", "whether", "gist", "is", "a", "be", "package" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/_extern.py#L239-L272
train
mottosso/be
be/_extern.py
_repo_is_preset
def _repo_is_preset(repo): """Evaluate whether GitHub repository is a be package Arguments: gist (str): username/id pair e.g. mottosso/be-ad """ package_template = "https://raw.githubusercontent.com" package_template += "/{repo}/master/package.json" package_path = package_template.format(repo=repo) response = get(package_path) if response.status_code == 404: return False try: data = response.json() except: return False if not data.get("type") == "bepreset": return False return True
python
def _repo_is_preset(repo): """Evaluate whether GitHub repository is a be package Arguments: gist (str): username/id pair e.g. mottosso/be-ad """ package_template = "https://raw.githubusercontent.com" package_template += "/{repo}/master/package.json" package_path = package_template.format(repo=repo) response = get(package_path) if response.status_code == 404: return False try: data = response.json() except: return False if not data.get("type") == "bepreset": return False return True
[ "def", "_repo_is_preset", "(", "repo", ")", ":", "package_template", "=", "\"https://raw.githubusercontent.com\"", "package_template", "+=", "\"/{repo}/master/package.json\"", "package_path", "=", "package_template", ".", "format", "(", "repo", "=", "repo", ")", "response...
Evaluate whether GitHub repository is a be package Arguments: gist (str): username/id pair e.g. mottosso/be-ad
[ "Evaluate", "whether", "GitHub", "repository", "is", "a", "be", "package" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/_extern.py#L275-L299
train
mottosso/be
be/_extern.py
github_presets
def github_presets(): """Return remote presets hosted on GitHub""" addr = ("https://raw.githubusercontent.com" "/mottosso/be-presets/master/presets.json") response = get(addr) if response.status_code == 404: lib.echo("Could not connect with preset database") sys.exit(lib.PROGRAM_ERROR) return dict((package["name"], package["repository"]) for package in response.json().get("presets"))
python
def github_presets(): """Return remote presets hosted on GitHub""" addr = ("https://raw.githubusercontent.com" "/mottosso/be-presets/master/presets.json") response = get(addr) if response.status_code == 404: lib.echo("Could not connect with preset database") sys.exit(lib.PROGRAM_ERROR) return dict((package["name"], package["repository"]) for package in response.json().get("presets"))
[ "def", "github_presets", "(", ")", ":", "addr", "=", "(", "\"https://raw.githubusercontent.com\"", "\"/mottosso/be-presets/master/presets.json\"", ")", "response", "=", "get", "(", "addr", ")", "if", "response", ".", "status_code", "==", "404", ":", "lib", ".", "e...
Return remote presets hosted on GitHub
[ "Return", "remote", "presets", "hosted", "on", "GitHub" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/_extern.py#L383-L394
train
mottosso/be
be/_extern.py
copy_preset
def copy_preset(preset_dir, project_dir): """Copy contents of preset into new project If package.json contains the key "contents", limit the files copied to those present in this list. Arguments: preset_dir (str): Absolute path to preset project_dir (str): Absolute path to new project """ os.makedirs(project_dir) package_file = os.path.join(preset_dir, "package.json") with open(package_file) as f: package = json.load(f) for fname in os.listdir(preset_dir): src = os.path.join(preset_dir, fname) contents = package.get("contents") or [] if fname not in self.files + contents: continue if os.path.isfile(src): shutil.copy2(src, project_dir) else: dest = os.path.join(project_dir, fname) shutil.copytree(src, dest)
python
def copy_preset(preset_dir, project_dir): """Copy contents of preset into new project If package.json contains the key "contents", limit the files copied to those present in this list. Arguments: preset_dir (str): Absolute path to preset project_dir (str): Absolute path to new project """ os.makedirs(project_dir) package_file = os.path.join(preset_dir, "package.json") with open(package_file) as f: package = json.load(f) for fname in os.listdir(preset_dir): src = os.path.join(preset_dir, fname) contents = package.get("contents") or [] if fname not in self.files + contents: continue if os.path.isfile(src): shutil.copy2(src, project_dir) else: dest = os.path.join(project_dir, fname) shutil.copytree(src, dest)
[ "def", "copy_preset", "(", "preset_dir", ",", "project_dir", ")", ":", "os", ".", "makedirs", "(", "project_dir", ")", "package_file", "=", "os", ".", "path", ".", "join", "(", "preset_dir", ",", "\"package.json\"", ")", "with", "open", "(", "package_file", ...
Copy contents of preset into new project If package.json contains the key "contents", limit the files copied to those present in this list. Arguments: preset_dir (str): Absolute path to preset project_dir (str): Absolute path to new project
[ "Copy", "contents", "of", "preset", "into", "new", "project" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/_extern.py#L397-L427
train
mottosso/be
be/_extern.py
_resolve_references
def _resolve_references(templates): """Resolve {@} occurences by expansion Given a dictionary {"a": "{@b}/x", "b": "{key}/y"} Return {"a", "{key}/y/x", "b": "{key}/y"} { key: {@reference}/{variable} # pattern } In plain english, it looks within `pattern` for references and replaces them with the value of the matching key. { root: {cwd}/{project} item: {@root}/{item} } In the above case, `item` is referencing `root` which is resolved into this. { item: {cwd}/{project}/{item} } Example: >>> templates = {"a": "{@b}/x", "b": "{key}/y"} >>> resolved = _resolve_references(templates) >>> assert resolved["a"] == "{key}/y/x" """ def repl(match): lib.echo("Deprecation warning: The {@ref} syntax is being removed") key = pattern[match.start():match.end()].strip("@{}") if key not in templates: sys.stderr.write("Unresolvable reference: \"%s\"" % key) sys.exit(lib.USER_ERROR) return templates[key] for key, pattern in templates.copy().iteritems(): templates[key] = re.sub("{@\w+}", repl, pattern) return templates
python
def _resolve_references(templates): """Resolve {@} occurences by expansion Given a dictionary {"a": "{@b}/x", "b": "{key}/y"} Return {"a", "{key}/y/x", "b": "{key}/y"} { key: {@reference}/{variable} # pattern } In plain english, it looks within `pattern` for references and replaces them with the value of the matching key. { root: {cwd}/{project} item: {@root}/{item} } In the above case, `item` is referencing `root` which is resolved into this. { item: {cwd}/{project}/{item} } Example: >>> templates = {"a": "{@b}/x", "b": "{key}/y"} >>> resolved = _resolve_references(templates) >>> assert resolved["a"] == "{key}/y/x" """ def repl(match): lib.echo("Deprecation warning: The {@ref} syntax is being removed") key = pattern[match.start():match.end()].strip("@{}") if key not in templates: sys.stderr.write("Unresolvable reference: \"%s\"" % key) sys.exit(lib.USER_ERROR) return templates[key] for key, pattern in templates.copy().iteritems(): templates[key] = re.sub("{@\w+}", repl, pattern) return templates
[ "def", "_resolve_references", "(", "templates", ")", ":", "def", "repl", "(", "match", ")", ":", "lib", ".", "echo", "(", "\"Deprecation warning: The {@ref} syntax is being removed\"", ")", "key", "=", "pattern", "[", "match", ".", "start", "(", ")", ":", "mat...
Resolve {@} occurences by expansion Given a dictionary {"a": "{@b}/x", "b": "{key}/y"} Return {"a", "{key}/y/x", "b": "{key}/y"} { key: {@reference}/{variable} # pattern } In plain english, it looks within `pattern` for references and replaces them with the value of the matching key. { root: {cwd}/{project} item: {@root}/{item} } In the above case, `item` is referencing `root` which is resolved into this. { item: {cwd}/{project}/{item} } Example: >>> templates = {"a": "{@b}/x", "b": "{key}/y"} >>> resolved = _resolve_references(templates) >>> assert resolved["a"] == "{key}/y/x"
[ "Resolve", "{", "@", "}", "occurences", "by", "expansion" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/_extern.py#L430-L474
train
mottosso/be
be/vendor/requests/packages/urllib3/_collections.py
HTTPHeaderDict.add
def add(self, key, val): """Adds a (name, value) pair, doesn't overwrite the value if it already exists. >>> headers = HTTPHeaderDict(foo='bar') >>> headers.add('Foo', 'baz') >>> headers['foo'] 'bar, baz' """ key_lower = key.lower() new_vals = key, val # Keep the common case aka no item present as fast as possible vals = _dict_setdefault(self, key_lower, new_vals) if new_vals is not vals: # new_vals was not inserted, as there was a previous one if isinstance(vals, list): # If already several items got inserted, we have a list vals.append(val) else: # vals should be a tuple then, i.e. only one item so far # Need to convert the tuple to list for further extension _dict_setitem(self, key_lower, [vals[0], vals[1], val])
python
def add(self, key, val): """Adds a (name, value) pair, doesn't overwrite the value if it already exists. >>> headers = HTTPHeaderDict(foo='bar') >>> headers.add('Foo', 'baz') >>> headers['foo'] 'bar, baz' """ key_lower = key.lower() new_vals = key, val # Keep the common case aka no item present as fast as possible vals = _dict_setdefault(self, key_lower, new_vals) if new_vals is not vals: # new_vals was not inserted, as there was a previous one if isinstance(vals, list): # If already several items got inserted, we have a list vals.append(val) else: # vals should be a tuple then, i.e. only one item so far # Need to convert the tuple to list for further extension _dict_setitem(self, key_lower, [vals[0], vals[1], val])
[ "def", "add", "(", "self", ",", "key", ",", "val", ")", ":", "key_lower", "=", "key", ".", "lower", "(", ")", "new_vals", "=", "key", ",", "val", "# Keep the common case aka no item present as fast as possible", "vals", "=", "_dict_setdefault", "(", "self", ",...
Adds a (name, value) pair, doesn't overwrite the value if it already exists. >>> headers = HTTPHeaderDict(foo='bar') >>> headers.add('Foo', 'baz') >>> headers['foo'] 'bar, baz'
[ "Adds", "a", "(", "name", "value", ")", "pair", "doesn", "t", "overwrite", "the", "value", "if", "it", "already", "exists", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/_collections.py#L207-L228
train
mottosso/be
be/vendor/requests/packages/urllib3/_collections.py
HTTPHeaderDict.getlist
def getlist(self, key): """Returns a list of all the values for the named field. Returns an empty list if the key doesn't exist.""" try: vals = _dict_getitem(self, key.lower()) except KeyError: return [] else: if isinstance(vals, tuple): return [vals[1]] else: return vals[1:]
python
def getlist(self, key): """Returns a list of all the values for the named field. Returns an empty list if the key doesn't exist.""" try: vals = _dict_getitem(self, key.lower()) except KeyError: return [] else: if isinstance(vals, tuple): return [vals[1]] else: return vals[1:]
[ "def", "getlist", "(", "self", ",", "key", ")", ":", "try", ":", "vals", "=", "_dict_getitem", "(", "self", ",", "key", ".", "lower", "(", ")", ")", "except", "KeyError", ":", "return", "[", "]", "else", ":", "if", "isinstance", "(", "vals", ",", ...
Returns a list of all the values for the named field. Returns an empty list if the key doesn't exist.
[ "Returns", "a", "list", "of", "all", "the", "values", "for", "the", "named", "field", ".", "Returns", "an", "empty", "list", "if", "the", "key", "doesn", "t", "exist", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/_collections.py#L256-L267
train
mottosso/be
be/vendor/requests/packages/urllib3/_collections.py
HTTPHeaderDict.iteritems
def iteritems(self): """Iterate over all header lines, including duplicate ones.""" for key in self: vals = _dict_getitem(self, key) for val in vals[1:]: yield vals[0], val
python
def iteritems(self): """Iterate over all header lines, including duplicate ones.""" for key in self: vals = _dict_getitem(self, key) for val in vals[1:]: yield vals[0], val
[ "def", "iteritems", "(", "self", ")", ":", "for", "key", "in", "self", ":", "vals", "=", "_dict_getitem", "(", "self", ",", "key", ")", "for", "val", "in", "vals", "[", "1", ":", "]", ":", "yield", "vals", "[", "0", "]", ",", "val" ]
Iterate over all header lines, including duplicate ones.
[ "Iterate", "over", "all", "header", "lines", "including", "duplicate", "ones", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/_collections.py#L290-L295
train
mottosso/be
be/vendor/requests/packages/urllib3/_collections.py
HTTPHeaderDict.itermerged
def itermerged(self): """Iterate over all headers, merging duplicate ones together.""" for key in self: val = _dict_getitem(self, key) yield val[0], ', '.join(val[1:])
python
def itermerged(self): """Iterate over all headers, merging duplicate ones together.""" for key in self: val = _dict_getitem(self, key) yield val[0], ', '.join(val[1:])
[ "def", "itermerged", "(", "self", ")", ":", "for", "key", "in", "self", ":", "val", "=", "_dict_getitem", "(", "self", ",", "key", ")", "yield", "val", "[", "0", "]", ",", "', '", ".", "join", "(", "val", "[", "1", ":", "]", ")" ]
Iterate over all headers, merging duplicate ones together.
[ "Iterate", "over", "all", "headers", "merging", "duplicate", "ones", "together", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/_collections.py#L297-L301
train
mottosso/be
be/vendor/requests/packages/urllib3/_collections.py
HTTPHeaderDict.from_httplib
def from_httplib(cls, message, duplicates=('set-cookie',)): # Python 2 """Read headers from a Python 2 httplib message object.""" ret = cls(message.items()) # ret now contains only the last header line for each duplicate. # Importing with all duplicates would be nice, but this would # mean to repeat most of the raw parsing already done, when the # message object was created. Extracting only the headers of interest # separately, the cookies, should be faster and requires less # extra code. for key in duplicates: ret.discard(key) for val in message.getheaders(key): ret.add(key, val) return ret
python
def from_httplib(cls, message, duplicates=('set-cookie',)): # Python 2 """Read headers from a Python 2 httplib message object.""" ret = cls(message.items()) # ret now contains only the last header line for each duplicate. # Importing with all duplicates would be nice, but this would # mean to repeat most of the raw parsing already done, when the # message object was created. Extracting only the headers of interest # separately, the cookies, should be faster and requires less # extra code. for key in duplicates: ret.discard(key) for val in message.getheaders(key): ret.add(key, val) return ret
[ "def", "from_httplib", "(", "cls", ",", "message", ",", "duplicates", "=", "(", "'set-cookie'", ",", ")", ")", ":", "# Python 2", "ret", "=", "cls", "(", "message", ".", "items", "(", ")", ")", "# ret now contains only the last header line for each duplicate.", ...
Read headers from a Python 2 httplib message object.
[ "Read", "headers", "from", "a", "Python", "2", "httplib", "message", "object", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/_collections.py#L307-L320
train
mottosso/be
be/vendor/requests/packages/urllib3/request.py
RequestMethods.request_encode_url
def request_encode_url(self, method, url, fields=None, **urlopen_kw): """ Make a request using :meth:`urlopen` with the ``fields`` encoded in the url. This is useful for request methods like GET, HEAD, DELETE, etc. """ if fields: url += '?' + urlencode(fields) return self.urlopen(method, url, **urlopen_kw)
python
def request_encode_url(self, method, url, fields=None, **urlopen_kw): """ Make a request using :meth:`urlopen` with the ``fields`` encoded in the url. This is useful for request methods like GET, HEAD, DELETE, etc. """ if fields: url += '?' + urlencode(fields) return self.urlopen(method, url, **urlopen_kw)
[ "def", "request_encode_url", "(", "self", ",", "method", ",", "url", ",", "fields", "=", "None", ",", "*", "*", "urlopen_kw", ")", ":", "if", "fields", ":", "url", "+=", "'?'", "+", "urlencode", "(", "fields", ")", "return", "self", ".", "urlopen", "...
Make a request using :meth:`urlopen` with the ``fields`` encoded in the url. This is useful for request methods like GET, HEAD, DELETE, etc.
[ "Make", "a", "request", "using", ":", "meth", ":", "urlopen", "with", "the", "fields", "encoded", "in", "the", "url", ".", "This", "is", "useful", "for", "request", "methods", "like", "GET", "HEAD", "DELETE", "etc", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/request.py#L74-L81
train
mottosso/be
be/vendor/click/utils.py
make_str
def make_str(value): """Converts a value into a valid string.""" if isinstance(value, bytes): try: return value.decode(sys.getfilesystemencoding()) except UnicodeError: return value.decode('utf-8', 'replace') return text_type(value)
python
def make_str(value): """Converts a value into a valid string.""" if isinstance(value, bytes): try: return value.decode(sys.getfilesystemencoding()) except UnicodeError: return value.decode('utf-8', 'replace') return text_type(value)
[ "def", "make_str", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "bytes", ")", ":", "try", ":", "return", "value", ".", "decode", "(", "sys", ".", "getfilesystemencoding", "(", ")", ")", "except", "UnicodeError", ":", "return", "value", ...
Converts a value into a valid string.
[ "Converts", "a", "value", "into", "a", "valid", "string", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/utils.py#L89-L96
train
mottosso/be
be/vendor/click/utils.py
echo
def echo(message=None, file=None, nl=True, err=False, color=None): """Prints a message plus a newline to the given file or stdout. On first sight, this looks like the print function, but it has improved support for handling Unicode and binary data that does not fail no matter how badly configured the system is. Primarily it means that you can print binary data as well as Unicode data on both 2.x and 3.x to the given file in the most appropriate way possible. This is a very carefree function as in that it will try its best to not fail. In addition to that, if `colorama`_ is installed, the echo function will also support clever handling of ANSI codes. Essentially it will then do the following: - add transparent handling of ANSI color codes on Windows. - hide ANSI codes automatically if the destination file is not a terminal. .. _colorama: http://pypi.python.org/pypi/colorama .. versionchanged:: 2.0 Starting with version 2.0 of Click, the echo function will work with colorama if it's installed. .. versionadded:: 3.0 The `err` parameter was added. .. versionchanged:: 4.0 Added the `color` flag. :param message: the message to print :param file: the file to write to (defaults to ``stdout``) :param err: if set to true the file defaults to ``stderr`` instead of ``stdout``. This is faster and easier than calling :func:`get_text_stderr` yourself. :param nl: if set to `True` (the default) a newline is printed afterwards. :param color: controls if the terminal supports ANSI colors or not. The default is autodetection. """ if file is None: if err: file = _default_text_stderr() else: file = _default_text_stdout() # Convert non bytes/text into the native string type. if message is not None and not isinstance(message, echo_native_types): message = text_type(message) # If there is a message, and we're in Python 3, and the value looks # like bytes, we manually need to find the binary stream and write the # message in there. This is done separately so that most stream # types will work as you would expect. Eg: you can write to StringIO # for other cases. if message and not PY2 and is_bytes(message): binary_file = _find_binary_writer(file) if binary_file is not None: file.flush() binary_file.write(message) if nl: binary_file.write(b'\n') binary_file.flush() return # ANSI-style support. If there is no message or we are dealing with # bytes nothing is happening. If we are connected to a file we want # to strip colors. If we are on windows we either wrap the stream # to strip the color or we use the colorama support to translate the # ansi codes to API calls. if message and not is_bytes(message): if should_strip_ansi(file, color): message = strip_ansi(message) elif WIN: if auto_wrap_for_ansi is not None: file = auto_wrap_for_ansi(file) elif not color: message = strip_ansi(message) if message: file.write(message) if nl: file.write('\n') file.flush()
python
def echo(message=None, file=None, nl=True, err=False, color=None): """Prints a message plus a newline to the given file or stdout. On first sight, this looks like the print function, but it has improved support for handling Unicode and binary data that does not fail no matter how badly configured the system is. Primarily it means that you can print binary data as well as Unicode data on both 2.x and 3.x to the given file in the most appropriate way possible. This is a very carefree function as in that it will try its best to not fail. In addition to that, if `colorama`_ is installed, the echo function will also support clever handling of ANSI codes. Essentially it will then do the following: - add transparent handling of ANSI color codes on Windows. - hide ANSI codes automatically if the destination file is not a terminal. .. _colorama: http://pypi.python.org/pypi/colorama .. versionchanged:: 2.0 Starting with version 2.0 of Click, the echo function will work with colorama if it's installed. .. versionadded:: 3.0 The `err` parameter was added. .. versionchanged:: 4.0 Added the `color` flag. :param message: the message to print :param file: the file to write to (defaults to ``stdout``) :param err: if set to true the file defaults to ``stderr`` instead of ``stdout``. This is faster and easier than calling :func:`get_text_stderr` yourself. :param nl: if set to `True` (the default) a newline is printed afterwards. :param color: controls if the terminal supports ANSI colors or not. The default is autodetection. """ if file is None: if err: file = _default_text_stderr() else: file = _default_text_stdout() # Convert non bytes/text into the native string type. if message is not None and not isinstance(message, echo_native_types): message = text_type(message) # If there is a message, and we're in Python 3, and the value looks # like bytes, we manually need to find the binary stream and write the # message in there. This is done separately so that most stream # types will work as you would expect. Eg: you can write to StringIO # for other cases. if message and not PY2 and is_bytes(message): binary_file = _find_binary_writer(file) if binary_file is not None: file.flush() binary_file.write(message) if nl: binary_file.write(b'\n') binary_file.flush() return # ANSI-style support. If there is no message or we are dealing with # bytes nothing is happening. If we are connected to a file we want # to strip colors. If we are on windows we either wrap the stream # to strip the color or we use the colorama support to translate the # ansi codes to API calls. if message and not is_bytes(message): if should_strip_ansi(file, color): message = strip_ansi(message) elif WIN: if auto_wrap_for_ansi is not None: file = auto_wrap_for_ansi(file) elif not color: message = strip_ansi(message) if message: file.write(message) if nl: file.write('\n') file.flush()
[ "def", "echo", "(", "message", "=", "None", ",", "file", "=", "None", ",", "nl", "=", "True", ",", "err", "=", "False", ",", "color", "=", "None", ")", ":", "if", "file", "is", "None", ":", "if", "err", ":", "file", "=", "_default_text_stderr", "...
Prints a message plus a newline to the given file or stdout. On first sight, this looks like the print function, but it has improved support for handling Unicode and binary data that does not fail no matter how badly configured the system is. Primarily it means that you can print binary data as well as Unicode data on both 2.x and 3.x to the given file in the most appropriate way possible. This is a very carefree function as in that it will try its best to not fail. In addition to that, if `colorama`_ is installed, the echo function will also support clever handling of ANSI codes. Essentially it will then do the following: - add transparent handling of ANSI color codes on Windows. - hide ANSI codes automatically if the destination file is not a terminal. .. _colorama: http://pypi.python.org/pypi/colorama .. versionchanged:: 2.0 Starting with version 2.0 of Click, the echo function will work with colorama if it's installed. .. versionadded:: 3.0 The `err` parameter was added. .. versionchanged:: 4.0 Added the `color` flag. :param message: the message to print :param file: the file to write to (defaults to ``stdout``) :param err: if set to true the file defaults to ``stderr`` instead of ``stdout``. This is faster and easier than calling :func:`get_text_stderr` yourself. :param nl: if set to `True` (the default) a newline is printed afterwards. :param color: controls if the terminal supports ANSI colors or not. The default is autodetection.
[ "Prints", "a", "message", "plus", "a", "newline", "to", "the", "given", "file", "or", "stdout", ".", "On", "first", "sight", "this", "looks", "like", "the", "print", "function", "but", "it", "has", "improved", "support", "for", "handling", "Unicode", "and"...
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/utils.py#L213-L296
train
mottosso/be
be/lib.py
parent
def parent(): """Determine subshell matching the currently running shell The shell is determined by either a pre-defined BE_SHELL environment variable, or, if none is found, via psutil which looks at the parent process directly through system-level calls. For example, is `be` is run from cmd.exe, then the full path to cmd.exe is returned, and the same goes for bash.exe and bash (without suffix) for Unix environments. The point is to return an appropriate subshell for the running shell, as opposed to the currently running OS. """ if self._parent: return self._parent if "BE_SHELL" in os.environ: self._parent = os.environ["BE_SHELL"] else: # If a shell is not provided, rely on `psutil` # to look at the calling process name. try: import psutil except ImportError: raise ImportError( "No shell provided, see documentation for " "BE_SHELL for more information.\n" "https://github.com/mottosso/be/wiki" "/environment#read-environment-variables") parent = psutil.Process(os.getpid()).parent() # `pip install` creates an additional executable # that tricks the above mechanism to think of it # as the parent shell. See #34 for more. if parent.name() in ("be", "be.exe"): parent = parent.parent() self._parent = str(parent.exe()) return self._parent
python
def parent(): """Determine subshell matching the currently running shell The shell is determined by either a pre-defined BE_SHELL environment variable, or, if none is found, via psutil which looks at the parent process directly through system-level calls. For example, is `be` is run from cmd.exe, then the full path to cmd.exe is returned, and the same goes for bash.exe and bash (without suffix) for Unix environments. The point is to return an appropriate subshell for the running shell, as opposed to the currently running OS. """ if self._parent: return self._parent if "BE_SHELL" in os.environ: self._parent = os.environ["BE_SHELL"] else: # If a shell is not provided, rely on `psutil` # to look at the calling process name. try: import psutil except ImportError: raise ImportError( "No shell provided, see documentation for " "BE_SHELL for more information.\n" "https://github.com/mottosso/be/wiki" "/environment#read-environment-variables") parent = psutil.Process(os.getpid()).parent() # `pip install` creates an additional executable # that tricks the above mechanism to think of it # as the parent shell. See #34 for more. if parent.name() in ("be", "be.exe"): parent = parent.parent() self._parent = str(parent.exe()) return self._parent
[ "def", "parent", "(", ")", ":", "if", "self", ".", "_parent", ":", "return", "self", ".", "_parent", "if", "\"BE_SHELL\"", "in", "os", ".", "environ", ":", "self", ".", "_parent", "=", "os", ".", "environ", "[", "\"BE_SHELL\"", "]", "else", ":", "# I...
Determine subshell matching the currently running shell The shell is determined by either a pre-defined BE_SHELL environment variable, or, if none is found, via psutil which looks at the parent process directly through system-level calls. For example, is `be` is run from cmd.exe, then the full path to cmd.exe is returned, and the same goes for bash.exe and bash (without suffix) for Unix environments. The point is to return an appropriate subshell for the running shell, as opposed to the currently running OS.
[ "Determine", "subshell", "matching", "the", "currently", "running", "shell" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/lib.py#L23-L67
train
mottosso/be
be/lib.py
platform
def platform(): """Return platform for the current shell, e.g. windows or unix""" executable = parent() basename = os.path.basename(executable) basename, _ = os.path.splitext(basename) if basename in ("bash", "sh"): return "unix" if basename in ("cmd", "powershell"): return "windows" raise SystemError("Unsupported shell: %s" % basename)
python
def platform(): """Return platform for the current shell, e.g. windows or unix""" executable = parent() basename = os.path.basename(executable) basename, _ = os.path.splitext(basename) if basename in ("bash", "sh"): return "unix" if basename in ("cmd", "powershell"): return "windows" raise SystemError("Unsupported shell: %s" % basename)
[ "def", "platform", "(", ")", ":", "executable", "=", "parent", "(", ")", "basename", "=", "os", ".", "path", ".", "basename", "(", "executable", ")", "basename", ",", "_", "=", "os", ".", "path", ".", "splitext", "(", "basename", ")", "if", "basename...
Return platform for the current shell, e.g. windows or unix
[ "Return", "platform", "for", "the", "current", "shell", "e", ".", "g", ".", "windows", "or", "unix" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/lib.py#L70-L81
train
mottosso/be
be/lib.py
cmd
def cmd(parent): """Determine subshell command for subprocess.call Arguments: parent (str): Absolute path to parent shell executable """ shell_name = os.path.basename(parent).rsplit(".", 1)[0] dirname = os.path.dirname(__file__) # Support for Bash if shell_name in ("bash", "sh"): shell = os.path.join(dirname, "_shell.sh").replace("\\", "/") cmd = [parent.replace("\\", "/"), shell] # Support for Cmd elif shell_name in ("cmd",): shell = os.path.join(dirname, "_shell.bat").replace("\\", "/") cmd = [parent, "/K", shell] # Support for Powershell elif shell_name in ("powershell",): raise SystemError("Powershell not yet supported") # Unsupported else: raise SystemError("Unsupported shell: %s" % shell_name) return cmd
python
def cmd(parent): """Determine subshell command for subprocess.call Arguments: parent (str): Absolute path to parent shell executable """ shell_name = os.path.basename(parent).rsplit(".", 1)[0] dirname = os.path.dirname(__file__) # Support for Bash if shell_name in ("bash", "sh"): shell = os.path.join(dirname, "_shell.sh").replace("\\", "/") cmd = [parent.replace("\\", "/"), shell] # Support for Cmd elif shell_name in ("cmd",): shell = os.path.join(dirname, "_shell.bat").replace("\\", "/") cmd = [parent, "/K", shell] # Support for Powershell elif shell_name in ("powershell",): raise SystemError("Powershell not yet supported") # Unsupported else: raise SystemError("Unsupported shell: %s" % shell_name) return cmd
[ "def", "cmd", "(", "parent", ")", ":", "shell_name", "=", "os", ".", "path", ".", "basename", "(", "parent", ")", ".", "rsplit", "(", "\".\"", ",", "1", ")", "[", "0", "]", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ...
Determine subshell command for subprocess.call Arguments: parent (str): Absolute path to parent shell executable
[ "Determine", "subshell", "command", "for", "subprocess", ".", "call" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/lib.py#L84-L114
train
mottosso/be
be/lib.py
context
def context(root, project=""): """Produce the be environment The environment is an exact replica of the active environment of the current process, with a few additional variables, all of which are listed below. """ environment = os.environ.copy() environment.update({ "BE_PROJECT": project, "BE_PROJECTROOT": ( os.path.join(root, project).replace("\\", "/") if project else ""), "BE_PROJECTSROOT": root, "BE_ALIASDIR": "", "BE_CWD": root, "BE_CD": "", "BE_ROOT": "", "BE_TOPICS": "", "BE_DEVELOPMENTDIR": "", "BE_ACTIVE": "1", "BE_USER": "", "BE_SCRIPT": "", "BE_PYTHON": "", "BE_ENTER": "", "BE_TEMPDIR": "", "BE_PRESETSDIR": "", "BE_GITHUB_API_TOKEN": "", "BE_ENVIRONMENT": "", "BE_BINDING": "", "BE_TABCOMPLETION": "" }) return environment
python
def context(root, project=""): """Produce the be environment The environment is an exact replica of the active environment of the current process, with a few additional variables, all of which are listed below. """ environment = os.environ.copy() environment.update({ "BE_PROJECT": project, "BE_PROJECTROOT": ( os.path.join(root, project).replace("\\", "/") if project else ""), "BE_PROJECTSROOT": root, "BE_ALIASDIR": "", "BE_CWD": root, "BE_CD": "", "BE_ROOT": "", "BE_TOPICS": "", "BE_DEVELOPMENTDIR": "", "BE_ACTIVE": "1", "BE_USER": "", "BE_SCRIPT": "", "BE_PYTHON": "", "BE_ENTER": "", "BE_TEMPDIR": "", "BE_PRESETSDIR": "", "BE_GITHUB_API_TOKEN": "", "BE_ENVIRONMENT": "", "BE_BINDING": "", "BE_TABCOMPLETION": "" }) return environment
[ "def", "context", "(", "root", ",", "project", "=", "\"\"", ")", ":", "environment", "=", "os", ".", "environ", ".", "copy", "(", ")", "environment", ".", "update", "(", "{", "\"BE_PROJECT\"", ":", "project", ",", "\"BE_PROJECTROOT\"", ":", "(", "os", ...
Produce the be environment The environment is an exact replica of the active environment of the current process, with a few additional variables, all of which are listed below.
[ "Produce", "the", "be", "environment" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/lib.py#L117-L152
train
mottosso/be
be/lib.py
random_name
def random_name(): """Return a random name Example: >> random_name() dizzy_badge >> random_name() evasive_cactus """ adj = _data.adjectives[random.randint(0, len(_data.adjectives) - 1)] noun = _data.nouns[random.randint(0, len(_data.nouns) - 1)] return "%s_%s" % (adj, noun)
python
def random_name(): """Return a random name Example: >> random_name() dizzy_badge >> random_name() evasive_cactus """ adj = _data.adjectives[random.randint(0, len(_data.adjectives) - 1)] noun = _data.nouns[random.randint(0, len(_data.nouns) - 1)] return "%s_%s" % (adj, noun)
[ "def", "random_name", "(", ")", ":", "adj", "=", "_data", ".", "adjectives", "[", "random", ".", "randint", "(", "0", ",", "len", "(", "_data", ".", "adjectives", ")", "-", "1", ")", "]", "noun", "=", "_data", ".", "nouns", "[", "random", ".", "r...
Return a random name Example: >> random_name() dizzy_badge >> random_name() evasive_cactus
[ "Return", "a", "random", "name" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/lib.py#L155-L168
train
mottosso/be
be/lib.py
isproject
def isproject(path): """Return whether or not `path` is a project Arguments: path (str): Absolute path """ try: if os.path.basename(path)[0] in (".", "_"): return False if not os.path.isdir(path): return False if not any(fname in os.listdir(path) for fname in ("templates.yaml", "inventory.yaml")): return False except: return False return True
python
def isproject(path): """Return whether or not `path` is a project Arguments: path (str): Absolute path """ try: if os.path.basename(path)[0] in (".", "_"): return False if not os.path.isdir(path): return False if not any(fname in os.listdir(path) for fname in ("templates.yaml", "inventory.yaml")): return False except: return False return True
[ "def", "isproject", "(", "path", ")", ":", "try", ":", "if", "os", ".", "path", ".", "basename", "(", "path", ")", "[", "0", "]", "in", "(", "\".\"", ",", "\"_\"", ")", ":", "return", "False", "if", "not", "os", ".", "path", ".", "isdir", "(", ...
Return whether or not `path` is a project Arguments: path (str): Absolute path
[ "Return", "whether", "or", "not", "path", "is", "a", "project" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/lib.py#L171-L191
train
mottosso/be
be/lib.py
echo
def echo(text, silent=False, newline=True): """Print to the console Arguments: text (str): Text to print to the console silen (bool, optional): Whether or not to produce any output newline (bool, optional): Whether or not to append a newline. """ if silent: return print(text) if newline else sys.stdout.write(text)
python
def echo(text, silent=False, newline=True): """Print to the console Arguments: text (str): Text to print to the console silen (bool, optional): Whether or not to produce any output newline (bool, optional): Whether or not to append a newline. """ if silent: return print(text) if newline else sys.stdout.write(text)
[ "def", "echo", "(", "text", ",", "silent", "=", "False", ",", "newline", "=", "True", ")", ":", "if", "silent", ":", "return", "print", "(", "text", ")", "if", "newline", "else", "sys", ".", "stdout", ".", "write", "(", "text", ")" ]
Print to the console Arguments: text (str): Text to print to the console silen (bool, optional): Whether or not to produce any output newline (bool, optional): Whether or not to append a newline.
[ "Print", "to", "the", "console" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/lib.py#L194-L206
train
mottosso/be
be/lib.py
list_projects
def list_projects(root, backend=os.listdir): """List projects at `root` Arguments: root (str): Absolute path to the `be` root directory, typically the current working directory. """ projects = list() for project in sorted(backend(root)): abspath = os.path.join(root, project) if not isproject(abspath): continue projects.append(project) return projects
python
def list_projects(root, backend=os.listdir): """List projects at `root` Arguments: root (str): Absolute path to the `be` root directory, typically the current working directory. """ projects = list() for project in sorted(backend(root)): abspath = os.path.join(root, project) if not isproject(abspath): continue projects.append(project) return projects
[ "def", "list_projects", "(", "root", ",", "backend", "=", "os", ".", "listdir", ")", ":", "projects", "=", "list", "(", ")", "for", "project", "in", "sorted", "(", "backend", "(", "root", ")", ")", ":", "abspath", "=", "os", ".", "path", ".", "join...
List projects at `root` Arguments: root (str): Absolute path to the `be` root directory, typically the current working directory.
[ "List", "projects", "at", "root" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/lib.py#L209-L223
train
mottosso/be
be/lib.py
list_inventory
def list_inventory(inventory): """List a projects inventory Given a project, simply list the contents of `inventory.yaml` Arguments: root (str): Absolute path to the `be` root directory, typically the current working directory. inventory (dict): inventory.yaml """ inverted = invert_inventory(inventory) items = list() for item in sorted(inverted, key=lambda a: (inverted[a], a)): items.append((item, inverted[item])) return items
python
def list_inventory(inventory): """List a projects inventory Given a project, simply list the contents of `inventory.yaml` Arguments: root (str): Absolute path to the `be` root directory, typically the current working directory. inventory (dict): inventory.yaml """ inverted = invert_inventory(inventory) items = list() for item in sorted(inverted, key=lambda a: (inverted[a], a)): items.append((item, inverted[item])) return items
[ "def", "list_inventory", "(", "inventory", ")", ":", "inverted", "=", "invert_inventory", "(", "inventory", ")", "items", "=", "list", "(", ")", "for", "item", "in", "sorted", "(", "inverted", ",", "key", "=", "lambda", "a", ":", "(", "inverted", "[", ...
List a projects inventory Given a project, simply list the contents of `inventory.yaml` Arguments: root (str): Absolute path to the `be` root directory, typically the current working directory. inventory (dict): inventory.yaml
[ "List", "a", "projects", "inventory" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/lib.py#L226-L242
train
mottosso/be
be/lib.py
list_template
def list_template(root, topics, templates, inventory, be, absolute=False): """List contents for resolved template Resolve a template as far as possible via the given `topics`. For example, if a template supports 5 arguments, but only 3 are given, resolve the template until its 4th argument and list the contents thereafter. In some cases, an additional path is present following an argument, e.g. {3}/assets. The `/assets` portion is referred to as the "tail" and is appended also. Arguments: topics (tuple): Current topics templates (dict): templates.yaml inventory (dict): inventory.yaml be (dict): be.yaml """ project = topics[0] # Get item try: key = be.get("templates", {}).get("key") or "{1}" item = item_from_topics(key, topics) binding = binding_from_item(inventory, item) except KeyError: return [] except IndexError as exc: raise IndexError("At least %s topics are required" % str(exc)) fields = replacement_fields_from_context( context(root, project)) binding = binding_from_item(inventory, item) pattern = pattern_from_template(templates, binding) # 2 arguments, {1}/{2}/{3} -> {1}/{2} # 2 arguments, {1}/{2}/assets/{3} -> {1}/{2}/assets index_end = pattern.index(str(len(topics)-1)) + 2 trimmed_pattern = pattern[:index_end] # If there aren't any more positional arguments, we're done print trimmed_pattern if not re.findall("{[\d]+}", pattern[index_end:]): return [] # Append trail # e.g. {1}/{2}/assets # ^^^^^^^ try: index_trail = pattern[index_end:].index("{") trail = pattern[index_end:index_end + index_trail - 1] trimmed_pattern += trail except ValueError: pass try: path = trimmed_pattern.format(*topics, **fields) except IndexError: raise IndexError("Template for \"%s\" has unordered " "positional arguments: \"%s\"" % (item, pattern)) if not os.path.isdir(path): return [] items = list() for dirname in os.listdir(path): abspath = os.path.join(path, dirname).replace("\\", "/") if not os.path.isdir(abspath): continue if absolute: items.append(abspath) else: items.append(dirname) return items
python
def list_template(root, topics, templates, inventory, be, absolute=False): """List contents for resolved template Resolve a template as far as possible via the given `topics`. For example, if a template supports 5 arguments, but only 3 are given, resolve the template until its 4th argument and list the contents thereafter. In some cases, an additional path is present following an argument, e.g. {3}/assets. The `/assets` portion is referred to as the "tail" and is appended also. Arguments: topics (tuple): Current topics templates (dict): templates.yaml inventory (dict): inventory.yaml be (dict): be.yaml """ project = topics[0] # Get item try: key = be.get("templates", {}).get("key") or "{1}" item = item_from_topics(key, topics) binding = binding_from_item(inventory, item) except KeyError: return [] except IndexError as exc: raise IndexError("At least %s topics are required" % str(exc)) fields = replacement_fields_from_context( context(root, project)) binding = binding_from_item(inventory, item) pattern = pattern_from_template(templates, binding) # 2 arguments, {1}/{2}/{3} -> {1}/{2} # 2 arguments, {1}/{2}/assets/{3} -> {1}/{2}/assets index_end = pattern.index(str(len(topics)-1)) + 2 trimmed_pattern = pattern[:index_end] # If there aren't any more positional arguments, we're done print trimmed_pattern if not re.findall("{[\d]+}", pattern[index_end:]): return [] # Append trail # e.g. {1}/{2}/assets # ^^^^^^^ try: index_trail = pattern[index_end:].index("{") trail = pattern[index_end:index_end + index_trail - 1] trimmed_pattern += trail except ValueError: pass try: path = trimmed_pattern.format(*topics, **fields) except IndexError: raise IndexError("Template for \"%s\" has unordered " "positional arguments: \"%s\"" % (item, pattern)) if not os.path.isdir(path): return [] items = list() for dirname in os.listdir(path): abspath = os.path.join(path, dirname).replace("\\", "/") if not os.path.isdir(abspath): continue if absolute: items.append(abspath) else: items.append(dirname) return items
[ "def", "list_template", "(", "root", ",", "topics", ",", "templates", ",", "inventory", ",", "be", ",", "absolute", "=", "False", ")", ":", "project", "=", "topics", "[", "0", "]", "# Get item", "try", ":", "key", "=", "be", ".", "get", "(", "\"templ...
List contents for resolved template Resolve a template as far as possible via the given `topics`. For example, if a template supports 5 arguments, but only 3 are given, resolve the template until its 4th argument and list the contents thereafter. In some cases, an additional path is present following an argument, e.g. {3}/assets. The `/assets` portion is referred to as the "tail" and is appended also. Arguments: topics (tuple): Current topics templates (dict): templates.yaml inventory (dict): inventory.yaml be (dict): be.yaml
[ "List", "contents", "for", "resolved", "template" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/lib.py#L245-L324
train
mottosso/be
be/lib.py
invert_inventory
def invert_inventory(inventory): """Return {item: binding} from {binding: item} Protect against items with additional metadata and items whose type is a number Returns: Dictionary of inverted inventory """ inverted = dict() for binding, items in inventory.iteritems(): for item in items: if isinstance(item, dict): item = item.keys()[0] item = str(item) # Key may be number if item in inverted: echo("Warning: Duplicate item found, " "for \"%s: %s\"" % (binding, item)) continue inverted[item] = binding return inverted
python
def invert_inventory(inventory): """Return {item: binding} from {binding: item} Protect against items with additional metadata and items whose type is a number Returns: Dictionary of inverted inventory """ inverted = dict() for binding, items in inventory.iteritems(): for item in items: if isinstance(item, dict): item = item.keys()[0] item = str(item) # Key may be number if item in inverted: echo("Warning: Duplicate item found, " "for \"%s: %s\"" % (binding, item)) continue inverted[item] = binding return inverted
[ "def", "invert_inventory", "(", "inventory", ")", ":", "inverted", "=", "dict", "(", ")", "for", "binding", ",", "items", "in", "inventory", ".", "iteritems", "(", ")", ":", "for", "item", "in", "items", ":", "if", "isinstance", "(", "item", ",", "dict...
Return {item: binding} from {binding: item} Protect against items with additional metadata and items whose type is a number Returns: Dictionary of inverted inventory
[ "Return", "{", "item", ":", "binding", "}", "from", "{", "binding", ":", "item", "}" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/lib.py#L327-L351
train
mottosso/be
be/lib.py
pos_development_directory
def pos_development_directory(templates, inventory, context, topics, user, item): """Return absolute path to development directory Arguments: templates (dict): templates.yaml inventory (dict): inventory.yaml context (dict): The be context, from context() topics (list): Arguments to `in` user (str): Current `be` user item (str): Item from template-binding address """ replacement_fields = replacement_fields_from_context(context) binding = binding_from_item(inventory, item) pattern = pattern_from_template(templates, binding) positional_arguments = find_positional_arguments(pattern) highest_argument = find_highest_position(positional_arguments) highest_available = len(topics) - 1 if highest_available < highest_argument: echo("Template for \"%s\" requires at least %i arguments" % ( item, highest_argument + 1)) sys.exit(USER_ERROR) try: return pattern.format(*topics, **replacement_fields).replace("\\", "/") except KeyError as exc: echo("TEMPLATE ERROR: %s is not an available key\n" % exc) echo("Available tokens:") for key in replacement_fields: echo("\n- %s" % key) sys.exit(TEMPLATE_ERROR)
python
def pos_development_directory(templates, inventory, context, topics, user, item): """Return absolute path to development directory Arguments: templates (dict): templates.yaml inventory (dict): inventory.yaml context (dict): The be context, from context() topics (list): Arguments to `in` user (str): Current `be` user item (str): Item from template-binding address """ replacement_fields = replacement_fields_from_context(context) binding = binding_from_item(inventory, item) pattern = pattern_from_template(templates, binding) positional_arguments = find_positional_arguments(pattern) highest_argument = find_highest_position(positional_arguments) highest_available = len(topics) - 1 if highest_available < highest_argument: echo("Template for \"%s\" requires at least %i arguments" % ( item, highest_argument + 1)) sys.exit(USER_ERROR) try: return pattern.format(*topics, **replacement_fields).replace("\\", "/") except KeyError as exc: echo("TEMPLATE ERROR: %s is not an available key\n" % exc) echo("Available tokens:") for key in replacement_fields: echo("\n- %s" % key) sys.exit(TEMPLATE_ERROR)
[ "def", "pos_development_directory", "(", "templates", ",", "inventory", ",", "context", ",", "topics", ",", "user", ",", "item", ")", ":", "replacement_fields", "=", "replacement_fields_from_context", "(", "context", ")", "binding", "=", "binding_from_item", "(", ...
Return absolute path to development directory Arguments: templates (dict): templates.yaml inventory (dict): inventory.yaml context (dict): The be context, from context() topics (list): Arguments to `in` user (str): Current `be` user item (str): Item from template-binding address
[ "Return", "absolute", "path", "to", "development", "directory" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/lib.py#L358-L395
train
mottosso/be
be/lib.py
fixed_development_directory
def fixed_development_directory(templates, inventory, topics, user): """Return absolute path to development directory Arguments: templates (dict): templates.yaml inventory (dict): inventory.yaml context (dict): The be context, from context() topics (list): Arguments to `in` user (str): Current `be` user """ echo("Fixed syntax has been deprecated, see positional syntax") project, item, task = topics[0].split("/") template = binding_from_item(inventory, item) pattern = pattern_from_template(templates, template) if find_positional_arguments(pattern): echo("\"%s\" uses a positional syntax" % project) echo("Try this:") echo(" be in %s" % " ".join([project, item, task])) sys.exit(USER_ERROR) keys = { "cwd": os.getcwd(), "project": project, "item": item.replace("\\", "/"), "user": user, "task": task, "type": task, # deprecated } try: return pattern.format(**keys).replace("\\", "/") except KeyError as exc: echo("TEMPLATE ERROR: %s is not an available key\n" % exc) echo("Available keys") for key in keys: echo("\n- %s" % key) sys.exit(1)
python
def fixed_development_directory(templates, inventory, topics, user): """Return absolute path to development directory Arguments: templates (dict): templates.yaml inventory (dict): inventory.yaml context (dict): The be context, from context() topics (list): Arguments to `in` user (str): Current `be` user """ echo("Fixed syntax has been deprecated, see positional syntax") project, item, task = topics[0].split("/") template = binding_from_item(inventory, item) pattern = pattern_from_template(templates, template) if find_positional_arguments(pattern): echo("\"%s\" uses a positional syntax" % project) echo("Try this:") echo(" be in %s" % " ".join([project, item, task])) sys.exit(USER_ERROR) keys = { "cwd": os.getcwd(), "project": project, "item": item.replace("\\", "/"), "user": user, "task": task, "type": task, # deprecated } try: return pattern.format(**keys).replace("\\", "/") except KeyError as exc: echo("TEMPLATE ERROR: %s is not an available key\n" % exc) echo("Available keys") for key in keys: echo("\n- %s" % key) sys.exit(1)
[ "def", "fixed_development_directory", "(", "templates", ",", "inventory", ",", "topics", ",", "user", ")", ":", "echo", "(", "\"Fixed syntax has been deprecated, see positional syntax\"", ")", "project", ",", "item", ",", "task", "=", "topics", "[", "0", "]", ".",...
Return absolute path to development directory Arguments: templates (dict): templates.yaml inventory (dict): inventory.yaml context (dict): The be context, from context() topics (list): Arguments to `in` user (str): Current `be` user
[ "Return", "absolute", "path", "to", "development", "directory" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/lib.py#L398-L439
train
mottosso/be
be/lib.py
replacement_fields_from_context
def replacement_fields_from_context(context): """Convert context replacement fields Example: BE_KEY=value -> {"key": "value} Arguments: context (dict): The current context """ return dict((k[3:].lower(), context[k]) for k in context if k.startswith("BE_"))
python
def replacement_fields_from_context(context): """Convert context replacement fields Example: BE_KEY=value -> {"key": "value} Arguments: context (dict): The current context """ return dict((k[3:].lower(), context[k]) for k in context if k.startswith("BE_"))
[ "def", "replacement_fields_from_context", "(", "context", ")", ":", "return", "dict", "(", "(", "k", "[", "3", ":", "]", ".", "lower", "(", ")", ",", "context", "[", "k", "]", ")", "for", "k", "in", "context", "if", "k", ".", "startswith", "(", "\"...
Convert context replacement fields Example: BE_KEY=value -> {"key": "value} Arguments: context (dict): The current context
[ "Convert", "context", "replacement", "fields" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/lib.py#L442-L454
train
mottosso/be
be/lib.py
item_from_topics
def item_from_topics(key, topics): """Get binding from `topics` via `key` Example: {0} == hello --> be in hello world {1} == world --> be in hello world Returns: Single topic matching the key Raises: IndexError (int): With number of required arguments for the key """ if re.match("{\d+}", key): pos = int(key.strip("{}")) try: binding = topics[pos] except IndexError: raise IndexError(pos + 1) else: echo("be.yaml template key not recognised") sys.exit(PROJECT_ERROR) return binding
python
def item_from_topics(key, topics): """Get binding from `topics` via `key` Example: {0} == hello --> be in hello world {1} == world --> be in hello world Returns: Single topic matching the key Raises: IndexError (int): With number of required arguments for the key """ if re.match("{\d+}", key): pos = int(key.strip("{}")) try: binding = topics[pos] except IndexError: raise IndexError(pos + 1) else: echo("be.yaml template key not recognised") sys.exit(PROJECT_ERROR) return binding
[ "def", "item_from_topics", "(", "key", ",", "topics", ")", ":", "if", "re", ".", "match", "(", "\"{\\d+}\"", ",", "key", ")", ":", "pos", "=", "int", "(", "key", ".", "strip", "(", "\"{}\"", ")", ")", "try", ":", "binding", "=", "topics", "[", "p...
Get binding from `topics` via `key` Example: {0} == hello --> be in hello world {1} == world --> be in hello world Returns: Single topic matching the key Raises: IndexError (int): With number of required arguments for the key
[ "Get", "binding", "from", "topics", "via", "key" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/lib.py#L457-L484
train
mottosso/be
be/lib.py
pattern_from_template
def pattern_from_template(templates, name): """Return pattern for name Arguments: templates (dict): Current templates name (str): Name of name """ if name not in templates: echo("No template named \"%s\"" % name) sys.exit(1) return templates[name]
python
def pattern_from_template(templates, name): """Return pattern for name Arguments: templates (dict): Current templates name (str): Name of name """ if name not in templates: echo("No template named \"%s\"" % name) sys.exit(1) return templates[name]
[ "def", "pattern_from_template", "(", "templates", ",", "name", ")", ":", "if", "name", "not", "in", "templates", ":", "echo", "(", "\"No template named \\\"%s\\\"\"", "%", "name", ")", "sys", ".", "exit", "(", "1", ")", "return", "templates", "[", "name", ...
Return pattern for name Arguments: templates (dict): Current templates name (str): Name of name
[ "Return", "pattern", "for", "name" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/lib.py#L510-L523
train
mottosso/be
be/lib.py
binding_from_item
def binding_from_item(inventory, item): """Return binding for `item` Example: asset: - myasset The binding is "asset" Arguments: project: Name of project item (str): Name of item """ if item in self.bindings: return self.bindings[item] bindings = invert_inventory(inventory) try: self.bindings[item] = bindings[item] return bindings[item] except KeyError as exc: exc.bindings = bindings raise exc
python
def binding_from_item(inventory, item): """Return binding for `item` Example: asset: - myasset The binding is "asset" Arguments: project: Name of project item (str): Name of item """ if item in self.bindings: return self.bindings[item] bindings = invert_inventory(inventory) try: self.bindings[item] = bindings[item] return bindings[item] except KeyError as exc: exc.bindings = bindings raise exc
[ "def", "binding_from_item", "(", "inventory", ",", "item", ")", ":", "if", "item", "in", "self", ".", "bindings", ":", "return", "self", ".", "bindings", "[", "item", "]", "bindings", "=", "invert_inventory", "(", "inventory", ")", "try", ":", "self", "....
Return binding for `item` Example: asset: - myasset The binding is "asset" Arguments: project: Name of project item (str): Name of item
[ "Return", "binding", "for", "item" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/lib.py#L526-L552
train
mottosso/be
be/lib.py
parse_environment
def parse_environment(fields, context, topics): """Resolve the be.yaml environment key Features: - Lists, e.g. ["/path1", "/path2"] - Environment variable references, via $ - Replacement field references, e.g. {key} - Topic references, e.g. {1} """ def _resolve_environment_lists(context): """Concatenate environment lists""" for key, value in context.copy().iteritems(): if isinstance(value, list): context[key] = os.pathsep.join(value) return context def _resolve_environment_references(fields, context): """Resolve $ occurences by expansion Given a dictionary {"PATH": "$PATH;somevalue;{0}"} Return {"PATH": "value_of_PATH;somevalue;myproject"}, given that the first topic - {0} - is "myproject" Arguments: fields (dict): Environment from be.yaml context (dict): Source context """ def repl(match): key = pattern[match.start():match.end()].strip("$") return context.get(key) pat = re.compile("\$\w+", re.IGNORECASE) for key, pattern in fields.copy().iteritems(): fields[key] = pat.sub(repl, pattern) \ .strip(os.pathsep) # Remove superflous separators return fields def _resolve_environment_fields(fields, context, topics): """Resolve {} occurences Supports both positional and BE_-prefixed variables. Example: BE_MYKEY -> "{mykey}" from `BE_MYKEY` {1} -> "{mytask}" from `be in myproject mytask` Returns: Dictionary of resolved fields """ source_dict = replacement_fields_from_context(context) source_dict.update(dict((str(topics.index(topic)), topic) for topic in topics)) def repl(match): key = pattern[match.start():match.end()].strip("{}") try: return source_dict[key] except KeyError: echo("PROJECT ERROR: Unavailable reference \"%s\" " "in be.yaml" % key) sys.exit(PROJECT_ERROR) for key, pattern in fields.copy().iteritems(): fields[key] = re.sub("{[\d\w]+}", repl, pattern) return fields fields = _resolve_environment_lists(fields) fields = _resolve_environment_references(fields, context) fields = _resolve_environment_fields(fields, context, topics) return fields
python
def parse_environment(fields, context, topics): """Resolve the be.yaml environment key Features: - Lists, e.g. ["/path1", "/path2"] - Environment variable references, via $ - Replacement field references, e.g. {key} - Topic references, e.g. {1} """ def _resolve_environment_lists(context): """Concatenate environment lists""" for key, value in context.copy().iteritems(): if isinstance(value, list): context[key] = os.pathsep.join(value) return context def _resolve_environment_references(fields, context): """Resolve $ occurences by expansion Given a dictionary {"PATH": "$PATH;somevalue;{0}"} Return {"PATH": "value_of_PATH;somevalue;myproject"}, given that the first topic - {0} - is "myproject" Arguments: fields (dict): Environment from be.yaml context (dict): Source context """ def repl(match): key = pattern[match.start():match.end()].strip("$") return context.get(key) pat = re.compile("\$\w+", re.IGNORECASE) for key, pattern in fields.copy().iteritems(): fields[key] = pat.sub(repl, pattern) \ .strip(os.pathsep) # Remove superflous separators return fields def _resolve_environment_fields(fields, context, topics): """Resolve {} occurences Supports both positional and BE_-prefixed variables. Example: BE_MYKEY -> "{mykey}" from `BE_MYKEY` {1} -> "{mytask}" from `be in myproject mytask` Returns: Dictionary of resolved fields """ source_dict = replacement_fields_from_context(context) source_dict.update(dict((str(topics.index(topic)), topic) for topic in topics)) def repl(match): key = pattern[match.start():match.end()].strip("{}") try: return source_dict[key] except KeyError: echo("PROJECT ERROR: Unavailable reference \"%s\" " "in be.yaml" % key) sys.exit(PROJECT_ERROR) for key, pattern in fields.copy().iteritems(): fields[key] = re.sub("{[\d\w]+}", repl, pattern) return fields fields = _resolve_environment_lists(fields) fields = _resolve_environment_references(fields, context) fields = _resolve_environment_fields(fields, context, topics) return fields
[ "def", "parse_environment", "(", "fields", ",", "context", ",", "topics", ")", ":", "def", "_resolve_environment_lists", "(", "context", ")", ":", "\"\"\"Concatenate environment lists\"\"\"", "for", "key", ",", "value", "in", "context", ".", "copy", "(", ")", "....
Resolve the be.yaml environment key Features: - Lists, e.g. ["/path1", "/path2"] - Environment variable references, via $ - Replacement field references, e.g. {key} - Topic references, e.g. {1}
[ "Resolve", "the", "be", ".", "yaml", "environment", "key" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/lib.py#L555-L633
train
mottosso/be
be/lib.py
parse_redirect
def parse_redirect(redirect, topics, context): """Resolve the be.yaml redirect key Arguments: redirect (dict): Source/destination pairs, e.g. {BE_ACTIVE: ACTIVE} topics (tuple): Topics from which to sample, e.g. (project, item, task) context (dict): Context from which to sample """ for map_source, map_dest in redirect.items(): if re.match("{\d+}", map_source): topics_index = int(map_source.strip("{}")) topics_value = topics[topics_index] context[map_dest] = topics_value continue context[map_dest] = context[map_source]
python
def parse_redirect(redirect, topics, context): """Resolve the be.yaml redirect key Arguments: redirect (dict): Source/destination pairs, e.g. {BE_ACTIVE: ACTIVE} topics (tuple): Topics from which to sample, e.g. (project, item, task) context (dict): Context from which to sample """ for map_source, map_dest in redirect.items(): if re.match("{\d+}", map_source): topics_index = int(map_source.strip("{}")) topics_value = topics[topics_index] context[map_dest] = topics_value continue context[map_dest] = context[map_source]
[ "def", "parse_redirect", "(", "redirect", ",", "topics", ",", "context", ")", ":", "for", "map_source", ",", "map_dest", "in", "redirect", ".", "items", "(", ")", ":", "if", "re", ".", "match", "(", "\"{\\d+}\"", ",", "map_source", ")", ":", "topics_inde...
Resolve the be.yaml redirect key Arguments: redirect (dict): Source/destination pairs, e.g. {BE_ACTIVE: ACTIVE} topics (tuple): Topics from which to sample, e.g. (project, item, task) context (dict): Context from which to sample
[ "Resolve", "the", "be", ".", "yaml", "redirect", "key" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/lib.py#L636-L653
train