id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
251,200
tomnor/channelpack
channelpack/pulltxt.py
loadtxt
def loadtxt(fn, **kwargs): """Study the text data file fn. Call numpys loadtxt with keyword arguments based on the study. Return data returned from numpy `loadtxt <http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html#numpy-loadtxt>`. kwargs: keyword arguments accepted by numpys loadtxt. Any keyword arguments provided will take precedence over the ones resulting from the study. Set the module attribute PP to the instance of PatternPull used. """ global PP PP = PatternPull(fn) txtargs = PP.loadtxtargs() txtargs.update(kwargs) # Let kwargs dominate. return np.loadtxt(fn, **txtargs)
python
def loadtxt(fn, **kwargs): """Study the text data file fn. Call numpys loadtxt with keyword arguments based on the study. Return data returned from numpy `loadtxt <http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html#numpy-loadtxt>`. kwargs: keyword arguments accepted by numpys loadtxt. Any keyword arguments provided will take precedence over the ones resulting from the study. Set the module attribute PP to the instance of PatternPull used. """ global PP PP = PatternPull(fn) txtargs = PP.loadtxtargs() txtargs.update(kwargs) # Let kwargs dominate. return np.loadtxt(fn, **txtargs)
[ "def", "loadtxt", "(", "fn", ",", "*", "*", "kwargs", ")", ":", "global", "PP", "PP", "=", "PatternPull", "(", "fn", ")", "txtargs", "=", "PP", ".", "loadtxtargs", "(", ")", "txtargs", ".", "update", "(", "kwargs", ")", "# Let kwargs dominate.", "return", "np", ".", "loadtxt", "(", "fn", ",", "*", "*", "txtargs", ")" ]
Study the text data file fn. Call numpys loadtxt with keyword arguments based on the study. Return data returned from numpy `loadtxt <http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html#numpy-loadtxt>`. kwargs: keyword arguments accepted by numpys loadtxt. Any keyword arguments provided will take precedence over the ones resulting from the study. Set the module attribute PP to the instance of PatternPull used.
[ "Study", "the", "text", "data", "file", "fn", ".", "Call", "numpys", "loadtxt", "with", "keyword", "arguments", "based", "on", "the", "study", "." ]
9ad3cd11c698aed4c0fc178385b2ba38a7d0efae
https://github.com/tomnor/channelpack/blob/9ad3cd11c698aed4c0fc178385b2ba38a7d0efae/channelpack/pulltxt.py#L325-L342
251,201
tomnor/channelpack
channelpack/pulltxt.py
loadtxt_asdict
def loadtxt_asdict(fn, **kwargs): """Return what is returned from loadtxt as a dict. The 'unpack' keyword is enforced to True. The keys in the dict is the column numbers loaded. It is the integers 0...N-1 for N loaded columns, or the numbers in usecols.""" kwargs.update(unpack=True) d = loadtxt(fn, **kwargs) if len(np.shape(d)) == 2: keys = kwargs.get('usecols', None) or range(len(d)) D = dict([(k, v) for k, v in zip(keys, d)]) elif len(np.shape(d)) == 1: keys = kwargs.get('usecols', None) or [0] D = dict([(keys[0], d)]) else: raise Exception('Unknown dimension of loaded data.') return D
python
def loadtxt_asdict(fn, **kwargs): """Return what is returned from loadtxt as a dict. The 'unpack' keyword is enforced to True. The keys in the dict is the column numbers loaded. It is the integers 0...N-1 for N loaded columns, or the numbers in usecols.""" kwargs.update(unpack=True) d = loadtxt(fn, **kwargs) if len(np.shape(d)) == 2: keys = kwargs.get('usecols', None) or range(len(d)) D = dict([(k, v) for k, v in zip(keys, d)]) elif len(np.shape(d)) == 1: keys = kwargs.get('usecols', None) or [0] D = dict([(keys[0], d)]) else: raise Exception('Unknown dimension of loaded data.') return D
[ "def", "loadtxt_asdict", "(", "fn", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "unpack", "=", "True", ")", "d", "=", "loadtxt", "(", "fn", ",", "*", "*", "kwargs", ")", "if", "len", "(", "np", ".", "shape", "(", "d", ")", ")", "==", "2", ":", "keys", "=", "kwargs", ".", "get", "(", "'usecols'", ",", "None", ")", "or", "range", "(", "len", "(", "d", ")", ")", "D", "=", "dict", "(", "[", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "zip", "(", "keys", ",", "d", ")", "]", ")", "elif", "len", "(", "np", ".", "shape", "(", "d", ")", ")", "==", "1", ":", "keys", "=", "kwargs", ".", "get", "(", "'usecols'", ",", "None", ")", "or", "[", "0", "]", "D", "=", "dict", "(", "[", "(", "keys", "[", "0", "]", ",", "d", ")", "]", ")", "else", ":", "raise", "Exception", "(", "'Unknown dimension of loaded data.'", ")", "return", "D" ]
Return what is returned from loadtxt as a dict. The 'unpack' keyword is enforced to True. The keys in the dict is the column numbers loaded. It is the integers 0...N-1 for N loaded columns, or the numbers in usecols.
[ "Return", "what", "is", "returned", "from", "loadtxt", "as", "a", "dict", "." ]
9ad3cd11c698aed4c0fc178385b2ba38a7d0efae
https://github.com/tomnor/channelpack/blob/9ad3cd11c698aed4c0fc178385b2ba38a7d0efae/channelpack/pulltxt.py#L345-L363
251,202
tomnor/channelpack
channelpack/pulltxt.py
PatternPull.file_rows
def file_rows(self, fo): """Return the lines in the file as a list. fo is the open file object.""" rows = [] for i in range(NUMROWS): line = fo.readline() if not line: break rows += [line] return rows
python
def file_rows(self, fo): """Return the lines in the file as a list. fo is the open file object.""" rows = [] for i in range(NUMROWS): line = fo.readline() if not line: break rows += [line] return rows
[ "def", "file_rows", "(", "self", ",", "fo", ")", ":", "rows", "=", "[", "]", "for", "i", "in", "range", "(", "NUMROWS", ")", ":", "line", "=", "fo", ".", "readline", "(", ")", "if", "not", "line", ":", "break", "rows", "+=", "[", "line", "]", "return", "rows" ]
Return the lines in the file as a list. fo is the open file object.
[ "Return", "the", "lines", "in", "the", "file", "as", "a", "list", "." ]
9ad3cd11c698aed4c0fc178385b2ba38a7d0efae
https://github.com/tomnor/channelpack/blob/9ad3cd11c698aed4c0fc178385b2ba38a7d0efae/channelpack/pulltxt.py#L101-L113
251,203
tomnor/channelpack
channelpack/pulltxt.py
PatternPull.count_matches
def count_matches(self): """Set the matches_p, matches_c and rows attributes.""" try: self.fn = self.fo.name rows = self.file_rows(self.fo) self.fo.seek(0) except AttributeError: with open(self.fn) as fo: rows = self.file_rows(fo) matches_p = [] matches_c = [] for line in rows: cnt = len(re.findall(DATPRX, line)) matches_p.append(cnt) cnt = len(re.findall(DATCRX, line)) matches_c.append(cnt) self.rows = rows # Is newlines in the end a problem? self.matches_p = matches_p self.matches_c = matches_c
python
def count_matches(self): """Set the matches_p, matches_c and rows attributes.""" try: self.fn = self.fo.name rows = self.file_rows(self.fo) self.fo.seek(0) except AttributeError: with open(self.fn) as fo: rows = self.file_rows(fo) matches_p = [] matches_c = [] for line in rows: cnt = len(re.findall(DATPRX, line)) matches_p.append(cnt) cnt = len(re.findall(DATCRX, line)) matches_c.append(cnt) self.rows = rows # Is newlines in the end a problem? self.matches_p = matches_p self.matches_c = matches_c
[ "def", "count_matches", "(", "self", ")", ":", "try", ":", "self", ".", "fn", "=", "self", ".", "fo", ".", "name", "rows", "=", "self", ".", "file_rows", "(", "self", ".", "fo", ")", "self", ".", "fo", ".", "seek", "(", "0", ")", "except", "AttributeError", ":", "with", "open", "(", "self", ".", "fn", ")", "as", "fo", ":", "rows", "=", "self", ".", "file_rows", "(", "fo", ")", "matches_p", "=", "[", "]", "matches_c", "=", "[", "]", "for", "line", "in", "rows", ":", "cnt", "=", "len", "(", "re", ".", "findall", "(", "DATPRX", ",", "line", ")", ")", "matches_p", ".", "append", "(", "cnt", ")", "cnt", "=", "len", "(", "re", ".", "findall", "(", "DATCRX", ",", "line", ")", ")", "matches_c", ".", "append", "(", "cnt", ")", "self", ".", "rows", "=", "rows", "# Is newlines in the end a problem?", "self", ".", "matches_p", "=", "matches_p", "self", ".", "matches_c", "=", "matches_c" ]
Set the matches_p, matches_c and rows attributes.
[ "Set", "the", "matches_p", "matches_c", "and", "rows", "attributes", "." ]
9ad3cd11c698aed4c0fc178385b2ba38a7d0efae
https://github.com/tomnor/channelpack/blob/9ad3cd11c698aed4c0fc178385b2ba38a7d0efae/channelpack/pulltxt.py#L115-L137
251,204
tomnor/channelpack
channelpack/pulltxt.py
PatternPull.rows2skip
def rows2skip(self, decdel): """ Return the number of rows to skip based on the decimal delimiter decdel. When each record start to have the same number of matches, this is where the data starts. This is the idea. And the number of consecutive records to have the same number of matches is to be EQUAL_CNT_REQ. """ if decdel == '.': ms = self.matches_p elif decdel == ',': ms = self.matches_c # else make error... cnt = row = 0 for val1, val2 in zip(ms, ms[1:]): # val2 is one element ahead. row += 1 if val2 == val1 != 0: # 0 is no matches, so it doesn't count. cnt += 1 else: cnt = 0 if cnt == EQUAL_CNT_REQ: break else: # print 'No break-out for', decdel, 'cnt:', cnt pass self.cnt = cnt return row - EQUAL_CNT_REQ
python
def rows2skip(self, decdel): """ Return the number of rows to skip based on the decimal delimiter decdel. When each record start to have the same number of matches, this is where the data starts. This is the idea. And the number of consecutive records to have the same number of matches is to be EQUAL_CNT_REQ. """ if decdel == '.': ms = self.matches_p elif decdel == ',': ms = self.matches_c # else make error... cnt = row = 0 for val1, val2 in zip(ms, ms[1:]): # val2 is one element ahead. row += 1 if val2 == val1 != 0: # 0 is no matches, so it doesn't count. cnt += 1 else: cnt = 0 if cnt == EQUAL_CNT_REQ: break else: # print 'No break-out for', decdel, 'cnt:', cnt pass self.cnt = cnt return row - EQUAL_CNT_REQ
[ "def", "rows2skip", "(", "self", ",", "decdel", ")", ":", "if", "decdel", "==", "'.'", ":", "ms", "=", "self", ".", "matches_p", "elif", "decdel", "==", "','", ":", "ms", "=", "self", ".", "matches_c", "# else make error...", "cnt", "=", "row", "=", "0", "for", "val1", ",", "val2", "in", "zip", "(", "ms", ",", "ms", "[", "1", ":", "]", ")", ":", "# val2 is one element ahead.", "row", "+=", "1", "if", "val2", "==", "val1", "!=", "0", ":", "# 0 is no matches, so it doesn't count.", "cnt", "+=", "1", "else", ":", "cnt", "=", "0", "if", "cnt", "==", "EQUAL_CNT_REQ", ":", "break", "else", ":", "# print 'No break-out for', decdel, 'cnt:', cnt", "pass", "self", ".", "cnt", "=", "cnt", "return", "row", "-", "EQUAL_CNT_REQ" ]
Return the number of rows to skip based on the decimal delimiter decdel. When each record start to have the same number of matches, this is where the data starts. This is the idea. And the number of consecutive records to have the same number of matches is to be EQUAL_CNT_REQ.
[ "Return", "the", "number", "of", "rows", "to", "skip", "based", "on", "the", "decimal", "delimiter", "decdel", "." ]
9ad3cd11c698aed4c0fc178385b2ba38a7d0efae
https://github.com/tomnor/channelpack/blob/9ad3cd11c698aed4c0fc178385b2ba38a7d0efae/channelpack/pulltxt.py#L139-L173
251,205
tomnor/channelpack
channelpack/pulltxt.py
PatternPull.set_decdel_rts
def set_decdel_rts(self): """Figure out the decimal seperator and rows to skip and set corresponding attributes. """ lnr = max(self.rows2skip(','), self.rows2skip('.')) + 1 # If EQUAL_CNT_REQ was not met, raise error. Implement! if self.cnt > EQUAL_CNT_REQ: raise PatternError('Did not find ' + str(EQUAL_CNT_REQ) + ' data rows with equal data pattern in file: ' + self.fn) elif self.cnt < EQUAL_CNT_REQ: # Too few rows raise PatternError('Less than', str(EQUAL_CNT_REQ) + 'data rows in', self.fn + '?', '\nTry lower the EQUAL_CNT_REQ') if self.matches_p[lnr] <= self.matches_c[lnr]: self.decdel = '.' # If equal, assume decimal point is used. self.datrx = DATPRX else: self.decdel = ',' # Assume the lesser count is correct. self.datrx = DATCRX self.rts = self.rows2skip(self.decdel)
python
def set_decdel_rts(self): """Figure out the decimal seperator and rows to skip and set corresponding attributes. """ lnr = max(self.rows2skip(','), self.rows2skip('.')) + 1 # If EQUAL_CNT_REQ was not met, raise error. Implement! if self.cnt > EQUAL_CNT_REQ: raise PatternError('Did not find ' + str(EQUAL_CNT_REQ) + ' data rows with equal data pattern in file: ' + self.fn) elif self.cnt < EQUAL_CNT_REQ: # Too few rows raise PatternError('Less than', str(EQUAL_CNT_REQ) + 'data rows in', self.fn + '?', '\nTry lower the EQUAL_CNT_REQ') if self.matches_p[lnr] <= self.matches_c[lnr]: self.decdel = '.' # If equal, assume decimal point is used. self.datrx = DATPRX else: self.decdel = ',' # Assume the lesser count is correct. self.datrx = DATCRX self.rts = self.rows2skip(self.decdel)
[ "def", "set_decdel_rts", "(", "self", ")", ":", "lnr", "=", "max", "(", "self", ".", "rows2skip", "(", "','", ")", ",", "self", ".", "rows2skip", "(", "'.'", ")", ")", "+", "1", "# If EQUAL_CNT_REQ was not met, raise error. Implement!", "if", "self", ".", "cnt", ">", "EQUAL_CNT_REQ", ":", "raise", "PatternError", "(", "'Did not find '", "+", "str", "(", "EQUAL_CNT_REQ", ")", "+", "' data rows with equal data pattern in file: '", "+", "self", ".", "fn", ")", "elif", "self", ".", "cnt", "<", "EQUAL_CNT_REQ", ":", "# Too few rows", "raise", "PatternError", "(", "'Less than'", ",", "str", "(", "EQUAL_CNT_REQ", ")", "+", "'data rows in'", ",", "self", ".", "fn", "+", "'?'", ",", "'\\nTry lower the EQUAL_CNT_REQ'", ")", "if", "self", ".", "matches_p", "[", "lnr", "]", "<=", "self", ".", "matches_c", "[", "lnr", "]", ":", "self", ".", "decdel", "=", "'.'", "# If equal, assume decimal point is used.", "self", ".", "datrx", "=", "DATPRX", "else", ":", "self", ".", "decdel", "=", "','", "# Assume the lesser count is correct.", "self", ".", "datrx", "=", "DATCRX", "self", ".", "rts", "=", "self", ".", "rows2skip", "(", "self", ".", "decdel", ")" ]
Figure out the decimal seperator and rows to skip and set corresponding attributes.
[ "Figure", "out", "the", "decimal", "seperator", "and", "rows", "to", "skip", "and", "set", "corresponding", "attributes", "." ]
9ad3cd11c698aed4c0fc178385b2ba38a7d0efae
https://github.com/tomnor/channelpack/blob/9ad3cd11c698aed4c0fc178385b2ba38a7d0efae/channelpack/pulltxt.py#L175-L197
251,206
tomnor/channelpack
channelpack/pulltxt.py
PatternPull.study_datdel
def study_datdel(self): """Figure out the data delimiter.""" nodigs = r'(\D+)' line = self.rows[self.rts + 1] # Study second line of data only. digs = re.findall(self.datrx, line) # if any of the numbers contain a '+' in it, it need to be escaped # before used in the pattern: digs = [dig.replace('+', r'\+') for dig in digs] pat = nodigs.join(digs) m = re.search(pat, line) groups = m.groups() # If the count of data on the row is 1, the groups tuple (the # data delimiters) is empty. if not groups: self.datdelgroups = groups return # self.datdel remain None. rpt_cnt = groups.count(groups[0]) if rpt_cnt != len(groups): self.warnings.append('Warning, data seperator not consistent.') if groups[0].strip(): # If a delimiter apart from white space is included, let that be # the delimiter for numpys loadtxt. self.datdel = groups[0].strip() elif groups[0] == '\t': # If specifically a tab as delimiter, use that. self.datdel = groups[0] # For other white space delimiters, let datdel remain None. # work-around for the event that numbers clutters the channel names and # rts is one number low: res = [dat.strip() for dat in self.rows[self.rts].split(self.datdel) if dat.strip()] if not all([re.match(self.datrx, dat) for dat in res]): self.rts += 1 # print 'DEBUG: rts was adjusted with 1' # Keep the groups for debug: self.datdelgroups = groups
python
def study_datdel(self): """Figure out the data delimiter.""" nodigs = r'(\D+)' line = self.rows[self.rts + 1] # Study second line of data only. digs = re.findall(self.datrx, line) # if any of the numbers contain a '+' in it, it need to be escaped # before used in the pattern: digs = [dig.replace('+', r'\+') for dig in digs] pat = nodigs.join(digs) m = re.search(pat, line) groups = m.groups() # If the count of data on the row is 1, the groups tuple (the # data delimiters) is empty. if not groups: self.datdelgroups = groups return # self.datdel remain None. rpt_cnt = groups.count(groups[0]) if rpt_cnt != len(groups): self.warnings.append('Warning, data seperator not consistent.') if groups[0].strip(): # If a delimiter apart from white space is included, let that be # the delimiter for numpys loadtxt. self.datdel = groups[0].strip() elif groups[0] == '\t': # If specifically a tab as delimiter, use that. self.datdel = groups[0] # For other white space delimiters, let datdel remain None. # work-around for the event that numbers clutters the channel names and # rts is one number low: res = [dat.strip() for dat in self.rows[self.rts].split(self.datdel) if dat.strip()] if not all([re.match(self.datrx, dat) for dat in res]): self.rts += 1 # print 'DEBUG: rts was adjusted with 1' # Keep the groups for debug: self.datdelgroups = groups
[ "def", "study_datdel", "(", "self", ")", ":", "nodigs", "=", "r'(\\D+)'", "line", "=", "self", ".", "rows", "[", "self", ".", "rts", "+", "1", "]", "# Study second line of data only.", "digs", "=", "re", ".", "findall", "(", "self", ".", "datrx", ",", "line", ")", "# if any of the numbers contain a '+' in it, it need to be escaped", "# before used in the pattern:", "digs", "=", "[", "dig", ".", "replace", "(", "'+'", ",", "r'\\+'", ")", "for", "dig", "in", "digs", "]", "pat", "=", "nodigs", ".", "join", "(", "digs", ")", "m", "=", "re", ".", "search", "(", "pat", ",", "line", ")", "groups", "=", "m", ".", "groups", "(", ")", "# If the count of data on the row is 1, the groups tuple (the", "# data delimiters) is empty.", "if", "not", "groups", ":", "self", ".", "datdelgroups", "=", "groups", "return", "# self.datdel remain None.", "rpt_cnt", "=", "groups", ".", "count", "(", "groups", "[", "0", "]", ")", "if", "rpt_cnt", "!=", "len", "(", "groups", ")", ":", "self", ".", "warnings", ".", "append", "(", "'Warning, data seperator not consistent.'", ")", "if", "groups", "[", "0", "]", ".", "strip", "(", ")", ":", "# If a delimiter apart from white space is included, let that be", "# the delimiter for numpys loadtxt.", "self", ".", "datdel", "=", "groups", "[", "0", "]", ".", "strip", "(", ")", "elif", "groups", "[", "0", "]", "==", "'\\t'", ":", "# If specifically a tab as delimiter, use that.", "self", ".", "datdel", "=", "groups", "[", "0", "]", "# For other white space delimiters, let datdel remain None.", "# work-around for the event that numbers clutters the channel names and", "# rts is one number low:", "res", "=", "[", "dat", ".", "strip", "(", ")", "for", "dat", "in", "self", ".", "rows", "[", "self", ".", "rts", "]", ".", "split", "(", "self", ".", "datdel", ")", "if", "dat", ".", "strip", "(", ")", "]", "if", "not", "all", "(", "[", "re", ".", "match", "(", "self", ".", "datrx", ",", "dat", ")", "for", "dat", "in", "res", "]", ")", ":", "self", ".", "rts", "+=", "1", "# print 'DEBUG: rts was adjusted with 1'", "# Keep the groups for debug:", "self", ".", "datdelgroups", "=", "groups" ]
Figure out the data delimiter.
[ "Figure", "out", "the", "data", "delimiter", "." ]
9ad3cd11c698aed4c0fc178385b2ba38a7d0efae
https://github.com/tomnor/channelpack/blob/9ad3cd11c698aed4c0fc178385b2ba38a7d0efae/channelpack/pulltxt.py#L199-L244
251,207
tomnor/channelpack
channelpack/pulltxt.py
PatternPull.channel_names
def channel_names(self, usecols=None): """Attempt to extract the channel names from the data file. Return a list with names. Return None on failed attempt. usecols: A list with columns to use. If present, the returned list will include only names for columns requested. It will align with the columns returned by numpys loadtxt by using the same keyword (usecols). """ # Search from [rts - 1] and up (last row before data). Split respective # row on datdel. Accept consecutive elements starting with alphas # character after strip. If the count of elements equals the data count # on row rts + 1, accept it as the channel names. if self.decdel == '.': datcnt = self.matches_p[self.rts] elif self.decdel == ',': datcnt = self.matches_c[self.rts] if usecols and max(usecols) >= datcnt: mess = ' Max column index is ' raise IndexError(str(usecols) + mess + str(datcnt - 1)) names = None if not self.rts: # Only data. return None # From last row before data and up. for row in self.rows[self.rts - 1::-1]: # datdel might be None, (whitespace) splitlist = row.split(self.datdel) for i, word in enumerate(splitlist): if not word.strip().startswith(ALPHAS): break elif i + 1 == datcnt: # Accept names = [ch.strip() for ch in splitlist[:datcnt]] break if names: break if usecols: names = [names[i] for i in sorted(usecols)] return names
python
def channel_names(self, usecols=None): """Attempt to extract the channel names from the data file. Return a list with names. Return None on failed attempt. usecols: A list with columns to use. If present, the returned list will include only names for columns requested. It will align with the columns returned by numpys loadtxt by using the same keyword (usecols). """ # Search from [rts - 1] and up (last row before data). Split respective # row on datdel. Accept consecutive elements starting with alphas # character after strip. If the count of elements equals the data count # on row rts + 1, accept it as the channel names. if self.decdel == '.': datcnt = self.matches_p[self.rts] elif self.decdel == ',': datcnt = self.matches_c[self.rts] if usecols and max(usecols) >= datcnt: mess = ' Max column index is ' raise IndexError(str(usecols) + mess + str(datcnt - 1)) names = None if not self.rts: # Only data. return None # From last row before data and up. for row in self.rows[self.rts - 1::-1]: # datdel might be None, (whitespace) splitlist = row.split(self.datdel) for i, word in enumerate(splitlist): if not word.strip().startswith(ALPHAS): break elif i + 1 == datcnt: # Accept names = [ch.strip() for ch in splitlist[:datcnt]] break if names: break if usecols: names = [names[i] for i in sorted(usecols)] return names
[ "def", "channel_names", "(", "self", ",", "usecols", "=", "None", ")", ":", "# Search from [rts - 1] and up (last row before data). Split respective", "# row on datdel. Accept consecutive elements starting with alphas", "# character after strip. If the count of elements equals the data count", "# on row rts + 1, accept it as the channel names.", "if", "self", ".", "decdel", "==", "'.'", ":", "datcnt", "=", "self", ".", "matches_p", "[", "self", ".", "rts", "]", "elif", "self", ".", "decdel", "==", "','", ":", "datcnt", "=", "self", ".", "matches_c", "[", "self", ".", "rts", "]", "if", "usecols", "and", "max", "(", "usecols", ")", ">=", "datcnt", ":", "mess", "=", "' Max column index is '", "raise", "IndexError", "(", "str", "(", "usecols", ")", "+", "mess", "+", "str", "(", "datcnt", "-", "1", ")", ")", "names", "=", "None", "if", "not", "self", ".", "rts", ":", "# Only data.", "return", "None", "# From last row before data and up.", "for", "row", "in", "self", ".", "rows", "[", "self", ".", "rts", "-", "1", ":", ":", "-", "1", "]", ":", "# datdel might be None, (whitespace)", "splitlist", "=", "row", ".", "split", "(", "self", ".", "datdel", ")", "for", "i", ",", "word", "in", "enumerate", "(", "splitlist", ")", ":", "if", "not", "word", ".", "strip", "(", ")", ".", "startswith", "(", "ALPHAS", ")", ":", "break", "elif", "i", "+", "1", "==", "datcnt", ":", "# Accept", "names", "=", "[", "ch", ".", "strip", "(", ")", "for", "ch", "in", "splitlist", "[", ":", "datcnt", "]", "]", "break", "if", "names", ":", "break", "if", "usecols", ":", "names", "=", "[", "names", "[", "i", "]", "for", "i", "in", "sorted", "(", "usecols", ")", "]", "return", "names" ]
Attempt to extract the channel names from the data file. Return a list with names. Return None on failed attempt. usecols: A list with columns to use. If present, the returned list will include only names for columns requested. It will align with the columns returned by numpys loadtxt by using the same keyword (usecols).
[ "Attempt", "to", "extract", "the", "channel", "names", "from", "the", "data", "file", ".", "Return", "a", "list", "with", "names", ".", "Return", "None", "on", "failed", "attempt", "." ]
9ad3cd11c698aed4c0fc178385b2ba38a7d0efae
https://github.com/tomnor/channelpack/blob/9ad3cd11c698aed4c0fc178385b2ba38a7d0efae/channelpack/pulltxt.py#L273-L317
251,208
exekias/droplet
droplet/catalog.py
LocalCatalog.register
def register(self, cls, instance): """ Register the given instance as implementation for a class interface """ if not issubclass(cls, DropletInterface): raise TypeError('Given class is not a NAZInterface subclass: %s' % cls) if not isinstance(instance, cls): raise TypeError('Given instance does not implement the class: %s' % instance) if instance.name in self.INSTANCES_BY_NAME: if self.INSTANCES_BY_NAME[instance.name] != instance: raise ValueError('Given name is registered ' 'by other instance: %s' % instance.name) self.INSTANCES_BY_INTERFACE[cls].add(instance) self.INSTANCES_BY_NAME[instance.name] = instance
python
def register(self, cls, instance): """ Register the given instance as implementation for a class interface """ if not issubclass(cls, DropletInterface): raise TypeError('Given class is not a NAZInterface subclass: %s' % cls) if not isinstance(instance, cls): raise TypeError('Given instance does not implement the class: %s' % instance) if instance.name in self.INSTANCES_BY_NAME: if self.INSTANCES_BY_NAME[instance.name] != instance: raise ValueError('Given name is registered ' 'by other instance: %s' % instance.name) self.INSTANCES_BY_INTERFACE[cls].add(instance) self.INSTANCES_BY_NAME[instance.name] = instance
[ "def", "register", "(", "self", ",", "cls", ",", "instance", ")", ":", "if", "not", "issubclass", "(", "cls", ",", "DropletInterface", ")", ":", "raise", "TypeError", "(", "'Given class is not a NAZInterface subclass: %s'", "%", "cls", ")", "if", "not", "isinstance", "(", "instance", ",", "cls", ")", ":", "raise", "TypeError", "(", "'Given instance does not implement the class: %s'", "%", "instance", ")", "if", "instance", ".", "name", "in", "self", ".", "INSTANCES_BY_NAME", ":", "if", "self", ".", "INSTANCES_BY_NAME", "[", "instance", ".", "name", "]", "!=", "instance", ":", "raise", "ValueError", "(", "'Given name is registered '", "'by other instance: %s'", "%", "instance", ".", "name", ")", "self", ".", "INSTANCES_BY_INTERFACE", "[", "cls", "]", ".", "add", "(", "instance", ")", "self", ".", "INSTANCES_BY_NAME", "[", "instance", ".", "name", "]", "=", "instance" ]
Register the given instance as implementation for a class interface
[ "Register", "the", "given", "instance", "as", "implementation", "for", "a", "class", "interface" ]
aeac573a2c1c4b774e99d5414a1c79b1bb734941
https://github.com/exekias/droplet/blob/aeac573a2c1c4b774e99d5414a1c79b1bb734941/droplet/catalog.py#L34-L52
251,209
johnwlockwood/stream_tap
stream_tap/__init__.py
stream_tap
def stream_tap(callables, stream): """ Calls each callable with each item in the stream. Use with Buckets. Make a Bucket with a callable and then pass a tuple of those buckets in as the callables. After iterating over this generator, get contents from each Spigot. :param callables: collection of callable. :param stream: Iterator if values. """ for item in stream: for caller in callables: caller(item) yield item
python
def stream_tap(callables, stream): """ Calls each callable with each item in the stream. Use with Buckets. Make a Bucket with a callable and then pass a tuple of those buckets in as the callables. After iterating over this generator, get contents from each Spigot. :param callables: collection of callable. :param stream: Iterator if values. """ for item in stream: for caller in callables: caller(item) yield item
[ "def", "stream_tap", "(", "callables", ",", "stream", ")", ":", "for", "item", "in", "stream", ":", "for", "caller", "in", "callables", ":", "caller", "(", "item", ")", "yield", "item" ]
Calls each callable with each item in the stream. Use with Buckets. Make a Bucket with a callable and then pass a tuple of those buckets in as the callables. After iterating over this generator, get contents from each Spigot. :param callables: collection of callable. :param stream: Iterator if values.
[ "Calls", "each", "callable", "with", "each", "item", "in", "the", "stream", ".", "Use", "with", "Buckets", ".", "Make", "a", "Bucket", "with", "a", "callable", "and", "then", "pass", "a", "tuple", "of", "those", "buckets", "in", "as", "the", "callables", ".", "After", "iterating", "over", "this", "generator", "get", "contents", "from", "each", "Spigot", "." ]
068f6427c39202991a1db2be842b0fa43c6c5b91
https://github.com/johnwlockwood/stream_tap/blob/068f6427c39202991a1db2be842b0fa43c6c5b91/stream_tap/__init__.py#L40-L54
251,210
tbreitenfeldt/invisible_ui
invisible_ui/elements/element.py
Element.selected
def selected(self, interrupt=False): """This object has been selected.""" self.ao2.output(self.get_title(), interrupt=interrupt)
python
def selected(self, interrupt=False): """This object has been selected.""" self.ao2.output(self.get_title(), interrupt=interrupt)
[ "def", "selected", "(", "self", ",", "interrupt", "=", "False", ")", ":", "self", ".", "ao2", ".", "output", "(", "self", ".", "get_title", "(", ")", ",", "interrupt", "=", "interrupt", ")" ]
This object has been selected.
[ "This", "object", "has", "been", "selected", "." ]
1a6907bfa61bded13fa9fb83ec7778c0df84487f
https://github.com/tbreitenfeldt/invisible_ui/blob/1a6907bfa61bded13fa9fb83ec7778c0df84487f/invisible_ui/elements/element.py#L42-L44
251,211
tomokinakamaru/mapletree
mapletree/response.py
Response.header
def header(self, k, v, replace=True): """ Sets header value. Replaces existing value if `replace` is True. Otherwise create a list of existing values and `v` :param k: Header key :param v: Header value :param replace: flag for setting mode. :type k: str :type v: str :type replace: bool """ if replace: self._headers[k] = [v] else: self._headers.setdefault(k, []).append(v) return self
python
def header(self, k, v, replace=True): """ Sets header value. Replaces existing value if `replace` is True. Otherwise create a list of existing values and `v` :param k: Header key :param v: Header value :param replace: flag for setting mode. :type k: str :type v: str :type replace: bool """ if replace: self._headers[k] = [v] else: self._headers.setdefault(k, []).append(v) return self
[ "def", "header", "(", "self", ",", "k", ",", "v", ",", "replace", "=", "True", ")", ":", "if", "replace", ":", "self", ".", "_headers", "[", "k", "]", "=", "[", "v", "]", "else", ":", "self", ".", "_headers", ".", "setdefault", "(", "k", ",", "[", "]", ")", ".", "append", "(", "v", ")", "return", "self" ]
Sets header value. Replaces existing value if `replace` is True. Otherwise create a list of existing values and `v` :param k: Header key :param v: Header value :param replace: flag for setting mode. :type k: str :type v: str :type replace: bool
[ "Sets", "header", "value", ".", "Replaces", "existing", "value", "if", "replace", "is", "True", ".", "Otherwise", "create", "a", "list", "of", "existing", "values", "and", "v" ]
19ec68769ef2c1cd2e4164ed8623e0c4280279bb
https://github.com/tomokinakamaru/mapletree/blob/19ec68769ef2c1cd2e4164ed8623e0c4280279bb/mapletree/response.py#L41-L58
251,212
tomokinakamaru/mapletree
mapletree/response.py
Response.cookie
def cookie(self, k, v, expires=None, domain=None, path='/', secure=False): """ Sets cookie value. :param k: Name for cookie value :param v: Cookie value :param expires: Cookie expiration date :param domain: Cookie domain :param path: Cookie path :param secure: Flag for `https only` :type k: str :type v: str :type expires: datetime.datetime :type domain: str :type path: str :type secure: bool """ ls = ['{}={}'.format(k, v)] if expires is not None: dt = format_date_time(mktime(expires.timetuple())) ls.append('expires={}'.format(dt)) if domain is not None: ls.append('domain={}'.format(domain)) if path is not None: ls.append('path={}'.format(path)) if secure: ls.append('secure') return self.header('Set-Cookie', '; '.join(ls), False)
python
def cookie(self, k, v, expires=None, domain=None, path='/', secure=False): """ Sets cookie value. :param k: Name for cookie value :param v: Cookie value :param expires: Cookie expiration date :param domain: Cookie domain :param path: Cookie path :param secure: Flag for `https only` :type k: str :type v: str :type expires: datetime.datetime :type domain: str :type path: str :type secure: bool """ ls = ['{}={}'.format(k, v)] if expires is not None: dt = format_date_time(mktime(expires.timetuple())) ls.append('expires={}'.format(dt)) if domain is not None: ls.append('domain={}'.format(domain)) if path is not None: ls.append('path={}'.format(path)) if secure: ls.append('secure') return self.header('Set-Cookie', '; '.join(ls), False)
[ "def", "cookie", "(", "self", ",", "k", ",", "v", ",", "expires", "=", "None", ",", "domain", "=", "None", ",", "path", "=", "'/'", ",", "secure", "=", "False", ")", ":", "ls", "=", "[", "'{}={}'", ".", "format", "(", "k", ",", "v", ")", "]", "if", "expires", "is", "not", "None", ":", "dt", "=", "format_date_time", "(", "mktime", "(", "expires", ".", "timetuple", "(", ")", ")", ")", "ls", ".", "append", "(", "'expires={}'", ".", "format", "(", "dt", ")", ")", "if", "domain", "is", "not", "None", ":", "ls", ".", "append", "(", "'domain={}'", ".", "format", "(", "domain", ")", ")", "if", "path", "is", "not", "None", ":", "ls", ".", "append", "(", "'path={}'", ".", "format", "(", "path", ")", ")", "if", "secure", ":", "ls", ".", "append", "(", "'secure'", ")", "return", "self", ".", "header", "(", "'Set-Cookie'", ",", "'; '", ".", "join", "(", "ls", ")", ",", "False", ")" ]
Sets cookie value. :param k: Name for cookie value :param v: Cookie value :param expires: Cookie expiration date :param domain: Cookie domain :param path: Cookie path :param secure: Flag for `https only` :type k: str :type v: str :type expires: datetime.datetime :type domain: str :type path: str :type secure: bool
[ "Sets", "cookie", "value", "." ]
19ec68769ef2c1cd2e4164ed8623e0c4280279bb
https://github.com/tomokinakamaru/mapletree/blob/19ec68769ef2c1cd2e4164ed8623e0c4280279bb/mapletree/response.py#L85-L116
251,213
pjuren/pyokit
src/pyokit/util/meta.py
decorate_all_methods
def decorate_all_methods(decorator): """ Build and return a decorator that will decorate all class members. This will apply the passed decorator to all of the methods in the decorated class, except the __init__ method, when a class is decorated with it. """ def decorate_class(cls): for name, m in inspect.getmembers(cls, inspect.ismethod): if name != "__init__": setattr(cls, name, decorator(m)) return cls return decorate_class
python
def decorate_all_methods(decorator): """ Build and return a decorator that will decorate all class members. This will apply the passed decorator to all of the methods in the decorated class, except the __init__ method, when a class is decorated with it. """ def decorate_class(cls): for name, m in inspect.getmembers(cls, inspect.ismethod): if name != "__init__": setattr(cls, name, decorator(m)) return cls return decorate_class
[ "def", "decorate_all_methods", "(", "decorator", ")", ":", "def", "decorate_class", "(", "cls", ")", ":", "for", "name", ",", "m", "in", "inspect", ".", "getmembers", "(", "cls", ",", "inspect", ".", "ismethod", ")", ":", "if", "name", "!=", "\"__init__\"", ":", "setattr", "(", "cls", ",", "name", ",", "decorator", "(", "m", ")", ")", "return", "cls", "return", "decorate_class" ]
Build and return a decorator that will decorate all class members. This will apply the passed decorator to all of the methods in the decorated class, except the __init__ method, when a class is decorated with it.
[ "Build", "and", "return", "a", "decorator", "that", "will", "decorate", "all", "class", "members", "." ]
fddae123b5d817daa39496183f19c000d9c3791f
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/util/meta.py#L49-L61
251,214
pjuren/pyokit
src/pyokit/util/meta.py
just_in_time_method
def just_in_time_method(func): """ This is a dcorator for methods. It redirect calls to the decorated method to the equivalent method in a class member called 'item'. 'item' is expected to be None when the class is instantiated. The point is to easily allow on-demand construction or loading of large, expensive objects just-in-time. To apply this decorator to a method in a class, the class must have the following instance variables: +--------------------------------------------------------------------------+ | Name | Description | +=========+================================================================+ | item | The wrapped object. Calls to this method will be redirected | | | to the method with the same name in item. This should be set | | | to None when the object is created; it will be loaded | | | on-demand the first time this method is called. | +---------+----------------------------------------------------------------+ | factory | An object from which 'item' can be loaded. Can be a factory, | | | or similar, but must provide the subscript operator, as this | | | is used to pass a key that uniquely identifies 'item' | +---------+----------------------------------------------------------------+ | key | any object that uniquely identifies 'item'; must be what is | | | expected by 'index' as argument for the subscript operator. | +--------------------------------------------------------------------------+ A common pattern is to create a new class B which inherits from A, implement the above requirements in B and then apply this decorator to all the methods inherited from A. If 'item' is an object of type A, then this pattern makes B behave exactly like A, but with just-in-time construction. """ if not inspect.ismethod: raise MetaError("oops") def wrapper(self, *args, **kwargs): if self.item is None: self.item = self.factory[self.key] return getattr(self.item, func.__name__)(*args, **kwargs) return wrapper
python
def just_in_time_method(func): """ This is a dcorator for methods. It redirect calls to the decorated method to the equivalent method in a class member called 'item'. 'item' is expected to be None when the class is instantiated. The point is to easily allow on-demand construction or loading of large, expensive objects just-in-time. To apply this decorator to a method in a class, the class must have the following instance variables: +--------------------------------------------------------------------------+ | Name | Description | +=========+================================================================+ | item | The wrapped object. Calls to this method will be redirected | | | to the method with the same name in item. This should be set | | | to None when the object is created; it will be loaded | | | on-demand the first time this method is called. | +---------+----------------------------------------------------------------+ | factory | An object from which 'item' can be loaded. Can be a factory, | | | or similar, but must provide the subscript operator, as this | | | is used to pass a key that uniquely identifies 'item' | +---------+----------------------------------------------------------------+ | key | any object that uniquely identifies 'item'; must be what is | | | expected by 'index' as argument for the subscript operator. | +--------------------------------------------------------------------------+ A common pattern is to create a new class B which inherits from A, implement the above requirements in B and then apply this decorator to all the methods inherited from A. If 'item' is an object of type A, then this pattern makes B behave exactly like A, but with just-in-time construction. """ if not inspect.ismethod: raise MetaError("oops") def wrapper(self, *args, **kwargs): if self.item is None: self.item = self.factory[self.key] return getattr(self.item, func.__name__)(*args, **kwargs) return wrapper
[ "def", "just_in_time_method", "(", "func", ")", ":", "if", "not", "inspect", ".", "ismethod", ":", "raise", "MetaError", "(", "\"oops\"", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "item", "is", "None", ":", "self", ".", "item", "=", "self", ".", "factory", "[", "self", ".", "key", "]", "return", "getattr", "(", "self", ".", "item", ",", "func", ".", "__name__", ")", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper" ]
This is a dcorator for methods. It redirect calls to the decorated method to the equivalent method in a class member called 'item'. 'item' is expected to be None when the class is instantiated. The point is to easily allow on-demand construction or loading of large, expensive objects just-in-time. To apply this decorator to a method in a class, the class must have the following instance variables: +--------------------------------------------------------------------------+ | Name | Description | +=========+================================================================+ | item | The wrapped object. Calls to this method will be redirected | | | to the method with the same name in item. This should be set | | | to None when the object is created; it will be loaded | | | on-demand the first time this method is called. | +---------+----------------------------------------------------------------+ | factory | An object from which 'item' can be loaded. Can be a factory, | | | or similar, but must provide the subscript operator, as this | | | is used to pass a key that uniquely identifies 'item' | +---------+----------------------------------------------------------------+ | key | any object that uniquely identifies 'item'; must be what is | | | expected by 'index' as argument for the subscript operator. | +--------------------------------------------------------------------------+ A common pattern is to create a new class B which inherits from A, implement the above requirements in B and then apply this decorator to all the methods inherited from A. If 'item' is an object of type A, then this pattern makes B behave exactly like A, but with just-in-time construction.
[ "This", "is", "a", "dcorator", "for", "methods", ".", "It", "redirect", "calls", "to", "the", "decorated", "method", "to", "the", "equivalent", "method", "in", "a", "class", "member", "called", "item", ".", "item", "is", "expected", "to", "be", "None", "when", "the", "class", "is", "instantiated", ".", "The", "point", "is", "to", "easily", "allow", "on", "-", "demand", "construction", "or", "loading", "of", "large", "expensive", "objects", "just", "-", "in", "-", "time", "." ]
fddae123b5d817daa39496183f19c000d9c3791f
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/util/meta.py#L79-L118
251,215
chrisnorman7/MyGui
MyGui/frame.py
AddAccelerator
def AddAccelerator(self, modifiers, key, action): """ Add an accelerator. Modifiers and key follow the same pattern as the list used to create wx.AcceleratorTable objects. """ newId = wx.NewId() self.Bind(wx.EVT_MENU, action, id = newId) self.RawAcceleratorTable.append((modifiers, key, newId)) self.SetAcceleratorTable(wx.AcceleratorTable(self.RawAcceleratorTable)) return newId
python
def AddAccelerator(self, modifiers, key, action): """ Add an accelerator. Modifiers and key follow the same pattern as the list used to create wx.AcceleratorTable objects. """ newId = wx.NewId() self.Bind(wx.EVT_MENU, action, id = newId) self.RawAcceleratorTable.append((modifiers, key, newId)) self.SetAcceleratorTable(wx.AcceleratorTable(self.RawAcceleratorTable)) return newId
[ "def", "AddAccelerator", "(", "self", ",", "modifiers", ",", "key", ",", "action", ")", ":", "newId", "=", "wx", ".", "NewId", "(", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_MENU", ",", "action", ",", "id", "=", "newId", ")", "self", ".", "RawAcceleratorTable", ".", "append", "(", "(", "modifiers", ",", "key", ",", "newId", ")", ")", "self", ".", "SetAcceleratorTable", "(", "wx", ".", "AcceleratorTable", "(", "self", ".", "RawAcceleratorTable", ")", ")", "return", "newId" ]
Add an accelerator. Modifiers and key follow the same pattern as the list used to create wx.AcceleratorTable objects.
[ "Add", "an", "accelerator", ".", "Modifiers", "and", "key", "follow", "the", "same", "pattern", "as", "the", "list", "used", "to", "create", "wx", ".", "AcceleratorTable", "objects", "." ]
83aecb9c24107b41085cd0047a3e5b3fa18fac35
https://github.com/chrisnorman7/MyGui/blob/83aecb9c24107b41085cd0047a3e5b3fa18fac35/MyGui/frame.py#L11-L21
251,216
dhain/potpy
potpy/configparser.py
parse_config
def parse_config(lines, module=None): """Parse a config file. Names referenced within the config file are found within the calling scope. For example:: >>> from potpy.configparser import parse_config >>> class foo: ... @staticmethod ... def bar(): ... pass ... >>> config = ''' ... /foo: ... foo.bar ... ''' >>> router = parse_config(config.splitlines()) would find the ``bar`` method of the ``foo`` class, because ``foo`` is in the same scope as the call to parse_config. :param lines: An iterable of configuration lines (an open file object will do). :param module: Optional. If provided and not None, look for referenced names within this object instead of the calling module. """ if module is None: module = _calling_scope(2) lines = IndentChecker(lines) path_router = PathRouter() for depth, line in lines: if depth > 0: raise SyntaxError('unexpected indent') name, path, types = parse_path_spec(line) if types: template_arg = (path, dict( (k, find_object(module, v)) for k, v in types.iteritems() )) else: template_arg = path handler = read_handler_block(lines, module) path_router.add(name, template_arg, handler) return path_router
python
def parse_config(lines, module=None): """Parse a config file. Names referenced within the config file are found within the calling scope. For example:: >>> from potpy.configparser import parse_config >>> class foo: ... @staticmethod ... def bar(): ... pass ... >>> config = ''' ... /foo: ... foo.bar ... ''' >>> router = parse_config(config.splitlines()) would find the ``bar`` method of the ``foo`` class, because ``foo`` is in the same scope as the call to parse_config. :param lines: An iterable of configuration lines (an open file object will do). :param module: Optional. If provided and not None, look for referenced names within this object instead of the calling module. """ if module is None: module = _calling_scope(2) lines = IndentChecker(lines) path_router = PathRouter() for depth, line in lines: if depth > 0: raise SyntaxError('unexpected indent') name, path, types = parse_path_spec(line) if types: template_arg = (path, dict( (k, find_object(module, v)) for k, v in types.iteritems() )) else: template_arg = path handler = read_handler_block(lines, module) path_router.add(name, template_arg, handler) return path_router
[ "def", "parse_config", "(", "lines", ",", "module", "=", "None", ")", ":", "if", "module", "is", "None", ":", "module", "=", "_calling_scope", "(", "2", ")", "lines", "=", "IndentChecker", "(", "lines", ")", "path_router", "=", "PathRouter", "(", ")", "for", "depth", ",", "line", "in", "lines", ":", "if", "depth", ">", "0", ":", "raise", "SyntaxError", "(", "'unexpected indent'", ")", "name", ",", "path", ",", "types", "=", "parse_path_spec", "(", "line", ")", "if", "types", ":", "template_arg", "=", "(", "path", ",", "dict", "(", "(", "k", ",", "find_object", "(", "module", ",", "v", ")", ")", "for", "k", ",", "v", "in", "types", ".", "iteritems", "(", ")", ")", ")", "else", ":", "template_arg", "=", "path", "handler", "=", "read_handler_block", "(", "lines", ",", "module", ")", "path_router", ".", "add", "(", "name", ",", "template_arg", ",", "handler", ")", "return", "path_router" ]
Parse a config file. Names referenced within the config file are found within the calling scope. For example:: >>> from potpy.configparser import parse_config >>> class foo: ... @staticmethod ... def bar(): ... pass ... >>> config = ''' ... /foo: ... foo.bar ... ''' >>> router = parse_config(config.splitlines()) would find the ``bar`` method of the ``foo`` class, because ``foo`` is in the same scope as the call to parse_config. :param lines: An iterable of configuration lines (an open file object will do). :param module: Optional. If provided and not None, look for referenced names within this object instead of the calling module.
[ "Parse", "a", "config", "file", "." ]
e39a5a84f763fbf144b07a620afb02a5ff3741c9
https://github.com/dhain/potpy/blob/e39a5a84f763fbf144b07a620afb02a5ff3741c9/potpy/configparser.py#L244-L287
251,217
dhain/potpy
potpy/configparser.py
load_config
def load_config(name='urls.conf'): """Load a config from a resource file. The resource is found using `pkg_resources.resource_stream()`_, relative to the calling module. See :func:`parse_config` for config file details. :param name: The name of the resource, relative to the calling module. .. _pkg_resources.resource_stream(): http://packages.python.org/distribute/pkg_resources.html#basic-resource-access """ module = _calling_scope(2) config = resource_stream(module.__name__, name) return parse_config(config, module)
python
def load_config(name='urls.conf'): """Load a config from a resource file. The resource is found using `pkg_resources.resource_stream()`_, relative to the calling module. See :func:`parse_config` for config file details. :param name: The name of the resource, relative to the calling module. .. _pkg_resources.resource_stream(): http://packages.python.org/distribute/pkg_resources.html#basic-resource-access """ module = _calling_scope(2) config = resource_stream(module.__name__, name) return parse_config(config, module)
[ "def", "load_config", "(", "name", "=", "'urls.conf'", ")", ":", "module", "=", "_calling_scope", "(", "2", ")", "config", "=", "resource_stream", "(", "module", ".", "__name__", ",", "name", ")", "return", "parse_config", "(", "config", ",", "module", ")" ]
Load a config from a resource file. The resource is found using `pkg_resources.resource_stream()`_, relative to the calling module. See :func:`parse_config` for config file details. :param name: The name of the resource, relative to the calling module. .. _pkg_resources.resource_stream(): http://packages.python.org/distribute/pkg_resources.html#basic-resource-access
[ "Load", "a", "config", "from", "a", "resource", "file", "." ]
e39a5a84f763fbf144b07a620afb02a5ff3741c9
https://github.com/dhain/potpy/blob/e39a5a84f763fbf144b07a620afb02a5ff3741c9/potpy/configparser.py#L290-L304
251,218
treycucco/bidon
bidon/db/core/sql_writer.py
SqlWriter.to_placeholder
def to_placeholder(self, name=None, db_type=None): """Returns a placeholder for the specified name, by applying the instance's format strings. :name: if None an unamed placeholder is returned, otherwise a named placeholder is returned. :db_type: if not None the placeholder is typecast. """ if name is None: placeholder = self.unnamed_placeholder else: placeholder = self.named_placeholder.format(name) if db_type: return self.typecast(placeholder, db_type) else: return placeholder
python
def to_placeholder(self, name=None, db_type=None): """Returns a placeholder for the specified name, by applying the instance's format strings. :name: if None an unamed placeholder is returned, otherwise a named placeholder is returned. :db_type: if not None the placeholder is typecast. """ if name is None: placeholder = self.unnamed_placeholder else: placeholder = self.named_placeholder.format(name) if db_type: return self.typecast(placeholder, db_type) else: return placeholder
[ "def", "to_placeholder", "(", "self", ",", "name", "=", "None", ",", "db_type", "=", "None", ")", ":", "if", "name", "is", "None", ":", "placeholder", "=", "self", ".", "unnamed_placeholder", "else", ":", "placeholder", "=", "self", ".", "named_placeholder", ".", "format", "(", "name", ")", "if", "db_type", ":", "return", "self", ".", "typecast", "(", "placeholder", ",", "db_type", ")", "else", ":", "return", "placeholder" ]
Returns a placeholder for the specified name, by applying the instance's format strings. :name: if None an unamed placeholder is returned, otherwise a named placeholder is returned. :db_type: if not None the placeholder is typecast.
[ "Returns", "a", "placeholder", "for", "the", "specified", "name", "by", "applying", "the", "instance", "s", "format", "strings", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/core/sql_writer.py#L29-L43
251,219
treycucco/bidon
bidon/db/core/sql_writer.py
SqlWriter.to_tuple
def to_tuple(self, iterable, surround="()", joiner=", "): """Returns the iterable as a SQL tuple.""" return "{0}{1}{2}".format(surround[0], joiner.join(iterable), surround[1])
python
def to_tuple(self, iterable, surround="()", joiner=", "): """Returns the iterable as a SQL tuple.""" return "{0}{1}{2}".format(surround[0], joiner.join(iterable), surround[1])
[ "def", "to_tuple", "(", "self", ",", "iterable", ",", "surround", "=", "\"()\"", ",", "joiner", "=", "\", \"", ")", ":", "return", "\"{0}{1}{2}\"", ".", "format", "(", "surround", "[", "0", "]", ",", "joiner", ".", "join", "(", "iterable", ")", ",", "surround", "[", "1", "]", ")" ]
Returns the iterable as a SQL tuple.
[ "Returns", "the", "iterable", "as", "a", "SQL", "tuple", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/core/sql_writer.py#L45-L47
251,220
treycucco/bidon
bidon/db/core/sql_writer.py
SqlWriter.to_expression
def to_expression(self, lhs, rhs, op): """Builds a binary sql expression. At its most basic, returns 'lhs op rhs' such as '5 + 3'. However, it also specially handles the 'in' and 'between' operators. For each of these operators it is expected that rhs will be iterable. If the comparison operator is of the form 'not(op)' where op is the operator, it will result in not (lhs op rhs). This allows for doing the full range of null checks on composite types. For composite types, 'is null' only returns true when all fields are null, and 'is not null' returns true only when all fields are not null. So, for a composite type with some null fields, 'is null' and 'is not null' will both return false, making it difficult to get all rows that have composite columns with some value in them. The solution to this is to use not (composite is null) which is true when all composite fields, or only some composite fields are not null. """ if op == "raw": # TODO: This is not documented return lhs elif op == "between": return "{0} between {1} and {2}".format(lhs, *rhs) elif op == "in": return "{0} in {1}".format(lhs, self.to_tuple(rhs)) elif op.startswith("not(") and op.endswith(")"): return "not ({0} {1} {2})".format(lhs, op[4:-1].strip(), rhs) else: return "{0} {1} {2}".format(lhs, op.strip(), rhs)
python
def to_expression(self, lhs, rhs, op): """Builds a binary sql expression. At its most basic, returns 'lhs op rhs' such as '5 + 3'. However, it also specially handles the 'in' and 'between' operators. For each of these operators it is expected that rhs will be iterable. If the comparison operator is of the form 'not(op)' where op is the operator, it will result in not (lhs op rhs). This allows for doing the full range of null checks on composite types. For composite types, 'is null' only returns true when all fields are null, and 'is not null' returns true only when all fields are not null. So, for a composite type with some null fields, 'is null' and 'is not null' will both return false, making it difficult to get all rows that have composite columns with some value in them. The solution to this is to use not (composite is null) which is true when all composite fields, or only some composite fields are not null. """ if op == "raw": # TODO: This is not documented return lhs elif op == "between": return "{0} between {1} and {2}".format(lhs, *rhs) elif op == "in": return "{0} in {1}".format(lhs, self.to_tuple(rhs)) elif op.startswith("not(") and op.endswith(")"): return "not ({0} {1} {2})".format(lhs, op[4:-1].strip(), rhs) else: return "{0} {1} {2}".format(lhs, op.strip(), rhs)
[ "def", "to_expression", "(", "self", ",", "lhs", ",", "rhs", ",", "op", ")", ":", "if", "op", "==", "\"raw\"", ":", "# TODO: This is not documented", "return", "lhs", "elif", "op", "==", "\"between\"", ":", "return", "\"{0} between {1} and {2}\"", ".", "format", "(", "lhs", ",", "*", "rhs", ")", "elif", "op", "==", "\"in\"", ":", "return", "\"{0} in {1}\"", ".", "format", "(", "lhs", ",", "self", ".", "to_tuple", "(", "rhs", ")", ")", "elif", "op", ".", "startswith", "(", "\"not(\"", ")", "and", "op", ".", "endswith", "(", "\")\"", ")", ":", "return", "\"not ({0} {1} {2})\"", ".", "format", "(", "lhs", ",", "op", "[", "4", ":", "-", "1", "]", ".", "strip", "(", ")", ",", "rhs", ")", "else", ":", "return", "\"{0} {1} {2}\"", ".", "format", "(", "lhs", ",", "op", ".", "strip", "(", ")", ",", "rhs", ")" ]
Builds a binary sql expression. At its most basic, returns 'lhs op rhs' such as '5 + 3'. However, it also specially handles the 'in' and 'between' operators. For each of these operators it is expected that rhs will be iterable. If the comparison operator is of the form 'not(op)' where op is the operator, it will result in not (lhs op rhs). This allows for doing the full range of null checks on composite types. For composite types, 'is null' only returns true when all fields are null, and 'is not null' returns true only when all fields are not null. So, for a composite type with some null fields, 'is null' and 'is not null' will both return false, making it difficult to get all rows that have composite columns with some value in them. The solution to this is to use not (composite is null) which is true when all composite fields, or only some composite fields are not null.
[ "Builds", "a", "binary", "sql", "expression", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/core/sql_writer.py#L49-L76
251,221
treycucco/bidon
bidon/db/core/sql_writer.py
SqlWriter.value_comparisons
def value_comparisons(self, values, comp="=", is_assignment=False): """Builds out a series of value comparisions. :values: can either be a dictionary, in which case the return will compare a name to a named placeholder, using the comp argument. I.E. values = {"first_name": "John", "last_name": "Smith"} will return ["first_name = %(first_name)s", "last_name = %(last_name)s"]. Otherwise values will be assumed to be an iterable of 2- or 3-tuples in the form (column, value[, operator]). When operator is not specified, it will fallback to comp. So for instance values = [("first_name", "John"), ("id", (10, 100), "between")] will return ["first_name = %s", "id between %s and %s "]. :is_assigment: if False, transform_op will be called on each operator. """ if isinstance(values, dict): if self.sort_columns: keys = sorted(values.keys()) else: keys = list(values.keys()) params = zip(keys, [self.to_placeholder(k) for k in keys]) return [ self.to_expression( i[0], i[1], comp if is_assignment else self.transform_op(comp, values[i[0]])) for i in params] else: if self.sort_columns: values = sorted(values, key=operator.itemgetter(0)) comps = [] for val in values: lhs = val[0] op = val[2] if len(val) == 3 else comp if op == "raw": rhs = None elif op == "between": rhs = (self.to_placeholder(), self.to_placeholder()) elif op == "in": rhs = [self.to_placeholder() for i in val[1]] else: rhs = self.to_placeholder() if not is_assignment: op = self.transform_op(op, val[1]) comps.append(self.to_expression(lhs, rhs, op)) return comps
python
def value_comparisons(self, values, comp="=", is_assignment=False): """Builds out a series of value comparisions. :values: can either be a dictionary, in which case the return will compare a name to a named placeholder, using the comp argument. I.E. values = {"first_name": "John", "last_name": "Smith"} will return ["first_name = %(first_name)s", "last_name = %(last_name)s"]. Otherwise values will be assumed to be an iterable of 2- or 3-tuples in the form (column, value[, operator]). When operator is not specified, it will fallback to comp. So for instance values = [("first_name", "John"), ("id", (10, 100), "between")] will return ["first_name = %s", "id between %s and %s "]. :is_assigment: if False, transform_op will be called on each operator. """ if isinstance(values, dict): if self.sort_columns: keys = sorted(values.keys()) else: keys = list(values.keys()) params = zip(keys, [self.to_placeholder(k) for k in keys]) return [ self.to_expression( i[0], i[1], comp if is_assignment else self.transform_op(comp, values[i[0]])) for i in params] else: if self.sort_columns: values = sorted(values, key=operator.itemgetter(0)) comps = [] for val in values: lhs = val[0] op = val[2] if len(val) == 3 else comp if op == "raw": rhs = None elif op == "between": rhs = (self.to_placeholder(), self.to_placeholder()) elif op == "in": rhs = [self.to_placeholder() for i in val[1]] else: rhs = self.to_placeholder() if not is_assignment: op = self.transform_op(op, val[1]) comps.append(self.to_expression(lhs, rhs, op)) return comps
[ "def", "value_comparisons", "(", "self", ",", "values", ",", "comp", "=", "\"=\"", ",", "is_assignment", "=", "False", ")", ":", "if", "isinstance", "(", "values", ",", "dict", ")", ":", "if", "self", ".", "sort_columns", ":", "keys", "=", "sorted", "(", "values", ".", "keys", "(", ")", ")", "else", ":", "keys", "=", "list", "(", "values", ".", "keys", "(", ")", ")", "params", "=", "zip", "(", "keys", ",", "[", "self", ".", "to_placeholder", "(", "k", ")", "for", "k", "in", "keys", "]", ")", "return", "[", "self", ".", "to_expression", "(", "i", "[", "0", "]", ",", "i", "[", "1", "]", ",", "comp", "if", "is_assignment", "else", "self", ".", "transform_op", "(", "comp", ",", "values", "[", "i", "[", "0", "]", "]", ")", ")", "for", "i", "in", "params", "]", "else", ":", "if", "self", ".", "sort_columns", ":", "values", "=", "sorted", "(", "values", ",", "key", "=", "operator", ".", "itemgetter", "(", "0", ")", ")", "comps", "=", "[", "]", "for", "val", "in", "values", ":", "lhs", "=", "val", "[", "0", "]", "op", "=", "val", "[", "2", "]", "if", "len", "(", "val", ")", "==", "3", "else", "comp", "if", "op", "==", "\"raw\"", ":", "rhs", "=", "None", "elif", "op", "==", "\"between\"", ":", "rhs", "=", "(", "self", ".", "to_placeholder", "(", ")", ",", "self", ".", "to_placeholder", "(", ")", ")", "elif", "op", "==", "\"in\"", ":", "rhs", "=", "[", "self", ".", "to_placeholder", "(", ")", "for", "i", "in", "val", "[", "1", "]", "]", "else", ":", "rhs", "=", "self", ".", "to_placeholder", "(", ")", "if", "not", "is_assignment", ":", "op", "=", "self", ".", "transform_op", "(", "op", ",", "val", "[", "1", "]", ")", "comps", ".", "append", "(", "self", ".", "to_expression", "(", "lhs", ",", "rhs", ",", "op", ")", ")", "return", "comps" ]
Builds out a series of value comparisions. :values: can either be a dictionary, in which case the return will compare a name to a named placeholder, using the comp argument. I.E. values = {"first_name": "John", "last_name": "Smith"} will return ["first_name = %(first_name)s", "last_name = %(last_name)s"]. Otherwise values will be assumed to be an iterable of 2- or 3-tuples in the form (column, value[, operator]). When operator is not specified, it will fallback to comp. So for instance values = [("first_name", "John"), ("id", (10, 100), "between")] will return ["first_name = %s", "id between %s and %s "]. :is_assigment: if False, transform_op will be called on each operator.
[ "Builds", "out", "a", "series", "of", "value", "comparisions", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/core/sql_writer.py#L91-L137
251,222
treycucco/bidon
bidon/db/core/sql_writer.py
SqlWriter.join_comparisons
def join_comparisons(self, values, joiner, *, is_assignment=False, comp="="): """Generates comparisons with the value_comparisions method, and joins them with joiner. :is_assignment: if false, transform_op will be called on each comparison operator. """ if isinstance(values, str): return values else: return joiner.join(self.value_comparisons(values, comp, is_assignment))
python
def join_comparisons(self, values, joiner, *, is_assignment=False, comp="="): """Generates comparisons with the value_comparisions method, and joins them with joiner. :is_assignment: if false, transform_op will be called on each comparison operator. """ if isinstance(values, str): return values else: return joiner.join(self.value_comparisons(values, comp, is_assignment))
[ "def", "join_comparisons", "(", "self", ",", "values", ",", "joiner", ",", "*", ",", "is_assignment", "=", "False", ",", "comp", "=", "\"=\"", ")", ":", "if", "isinstance", "(", "values", ",", "str", ")", ":", "return", "values", "else", ":", "return", "joiner", ".", "join", "(", "self", ".", "value_comparisons", "(", "values", ",", "comp", ",", "is_assignment", ")", ")" ]
Generates comparisons with the value_comparisions method, and joins them with joiner. :is_assignment: if false, transform_op will be called on each comparison operator.
[ "Generates", "comparisons", "with", "the", "value_comparisions", "method", "and", "joins", "them", "with", "joiner", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/core/sql_writer.py#L139-L147
251,223
treycucco/bidon
bidon/db/core/sql_writer.py
SqlWriter.get_params
def get_params(self, values): """Gets params to be passed to execute from values. :values: can either be a dict, in which case it will be returned as is, or can be an enumerable of 2- or 3-tuples. This will return an enumerable of the 2nd values, and in the case of some operators such as 'in' and 'between' the values will be specially handled. """ if values is None: return None elif isinstance(values, dict): return values elif isinstance(values, (list, tuple)): params = [] for val in values: if len(val) == 2: params.append(val[1]) else: if val[2] in ("in", "between"): params.extend(val[1]) else: params.append(val[1]) return params elif isinstance(values, str): return None else: raise TypeError( "values must be None, a dict, list or tuple, is {0}".format(type(values).__name__))
python
def get_params(self, values): """Gets params to be passed to execute from values. :values: can either be a dict, in which case it will be returned as is, or can be an enumerable of 2- or 3-tuples. This will return an enumerable of the 2nd values, and in the case of some operators such as 'in' and 'between' the values will be specially handled. """ if values is None: return None elif isinstance(values, dict): return values elif isinstance(values, (list, tuple)): params = [] for val in values: if len(val) == 2: params.append(val[1]) else: if val[2] in ("in", "between"): params.extend(val[1]) else: params.append(val[1]) return params elif isinstance(values, str): return None else: raise TypeError( "values must be None, a dict, list or tuple, is {0}".format(type(values).__name__))
[ "def", "get_params", "(", "self", ",", "values", ")", ":", "if", "values", "is", "None", ":", "return", "None", "elif", "isinstance", "(", "values", ",", "dict", ")", ":", "return", "values", "elif", "isinstance", "(", "values", ",", "(", "list", ",", "tuple", ")", ")", ":", "params", "=", "[", "]", "for", "val", "in", "values", ":", "if", "len", "(", "val", ")", "==", "2", ":", "params", ".", "append", "(", "val", "[", "1", "]", ")", "else", ":", "if", "val", "[", "2", "]", "in", "(", "\"in\"", ",", "\"between\"", ")", ":", "params", ".", "extend", "(", "val", "[", "1", "]", ")", "else", ":", "params", ".", "append", "(", "val", "[", "1", "]", ")", "return", "params", "elif", "isinstance", "(", "values", ",", "str", ")", ":", "return", "None", "else", ":", "raise", "TypeError", "(", "\"values must be None, a dict, list or tuple, is {0}\"", ".", "format", "(", "type", "(", "values", ")", ".", "__name__", ")", ")" ]
Gets params to be passed to execute from values. :values: can either be a dict, in which case it will be returned as is, or can be an enumerable of 2- or 3-tuples. This will return an enumerable of the 2nd values, and in the case of some operators such as 'in' and 'between' the values will be specially handled.
[ "Gets", "params", "to", "be", "passed", "to", "execute", "from", "values", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/core/sql_writer.py#L177-L203
251,224
treycucco/bidon
bidon/db/core/sql_writer.py
SqlWriter.get_find_all_query
def get_find_all_query(self, table_name, constraints=None, *, columns=None, order_by=None, limiting=(None, None)): """Builds a find query. :limiting: if present must be a 2-tuple of (limit, offset) either of which can be None. """ where, params = self.parse_constraints(constraints) if columns: if isinstance(columns, str): pass else: columns = ", ".join(columns) else: columns = "*" if order_by: order = " order by {0}".format(order_by) else: order = "" paging = "" if limiting is not None: limit, offset = limiting if limit is not None: paging += " limit {0}".format(limit) if offset is not None: paging += " offset {0}".format(offset) return ("select {0} from {1} where {2}{3}{4}".format( columns, table_name, where or "1 = 1", order, paging ), params)
python
def get_find_all_query(self, table_name, constraints=None, *, columns=None, order_by=None, limiting=(None, None)): """Builds a find query. :limiting: if present must be a 2-tuple of (limit, offset) either of which can be None. """ where, params = self.parse_constraints(constraints) if columns: if isinstance(columns, str): pass else: columns = ", ".join(columns) else: columns = "*" if order_by: order = " order by {0}".format(order_by) else: order = "" paging = "" if limiting is not None: limit, offset = limiting if limit is not None: paging += " limit {0}".format(limit) if offset is not None: paging += " offset {0}".format(offset) return ("select {0} from {1} where {2}{3}{4}".format( columns, table_name, where or "1 = 1", order, paging ), params)
[ "def", "get_find_all_query", "(", "self", ",", "table_name", ",", "constraints", "=", "None", ",", "*", ",", "columns", "=", "None", ",", "order_by", "=", "None", ",", "limiting", "=", "(", "None", ",", "None", ")", ")", ":", "where", ",", "params", "=", "self", ".", "parse_constraints", "(", "constraints", ")", "if", "columns", ":", "if", "isinstance", "(", "columns", ",", "str", ")", ":", "pass", "else", ":", "columns", "=", "\", \"", ".", "join", "(", "columns", ")", "else", ":", "columns", "=", "\"*\"", "if", "order_by", ":", "order", "=", "\" order by {0}\"", ".", "format", "(", "order_by", ")", "else", ":", "order", "=", "\"\"", "paging", "=", "\"\"", "if", "limiting", "is", "not", "None", ":", "limit", ",", "offset", "=", "limiting", "if", "limit", "is", "not", "None", ":", "paging", "+=", "\" limit {0}\"", ".", "format", "(", "limit", ")", "if", "offset", "is", "not", "None", ":", "paging", "+=", "\" offset {0}\"", ".", "format", "(", "offset", ")", "return", "(", "\"select {0} from {1} where {2}{3}{4}\"", ".", "format", "(", "columns", ",", "table_name", ",", "where", "or", "\"1 = 1\"", ",", "order", ",", "paging", ")", ",", "params", ")" ]
Builds a find query. :limiting: if present must be a 2-tuple of (limit, offset) either of which can be None.
[ "Builds", "a", "find", "query", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/core/sql_writer.py#L205-L240
251,225
mkouhei/tonicdnscli
src/tonicdnscli/utils.py
pretty_print
def pretty_print(rows, keyword, domain): """ rows is list when get domains dict when get specific domain """ if isinstance(rows, dict): pretty_print_domain(rows, keyword, domain) elif isinstance(rows, list): pretty_print_zones(rows)
python
def pretty_print(rows, keyword, domain): """ rows is list when get domains dict when get specific domain """ if isinstance(rows, dict): pretty_print_domain(rows, keyword, domain) elif isinstance(rows, list): pretty_print_zones(rows)
[ "def", "pretty_print", "(", "rows", ",", "keyword", ",", "domain", ")", ":", "if", "isinstance", "(", "rows", ",", "dict", ")", ":", "pretty_print_domain", "(", "rows", ",", "keyword", ",", "domain", ")", "elif", "isinstance", "(", "rows", ",", "list", ")", ":", "pretty_print_zones", "(", "rows", ")" ]
rows is list when get domains dict when get specific domain
[ "rows", "is", "list", "when", "get", "domains", "dict", "when", "get", "specific", "domain" ]
df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c
https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/utils.py#L118-L127
251,226
KnowledgeLinks/rdfframework
rdfframework/connections/blazegraph.py
Blazegraph.load_data
def load_data(self, data, datatype="ttl", namespace=None, graph=None, is_file=False, **kwargs): """ Loads data via file stream from python to triplestore Args: ----- data: The data or filepath to load datatype(['ttl', 'xml', 'rdf']): the type of data to load namespace: the namespace to use graph: the graph to load the data to. is_file(False): If true python will read the data argument as a filepath, determine the datatype from the file extension, read the file and send it to blazegraph as a datastream """ log.setLevel(kwargs.get("log_level", self.log_level)) time_start = datetime.datetime.now() datatype_map = { 'ttl': 'text/turtle', 'xml': 'application/rdf+xml', 'rdf': 'application/rdf+xml', 'nt': 'text/plain' } if is_file: datatype = data.split(os.path.extsep)[-1] file_name = data log.debug('starting data load of %s', file_name) data = open(data, 'rb').read() else: try: data = data.encode('utf-8') except AttributeError: # data already encoded pass try: content_type = datatype_map[datatype] except KeyError: raise NotImplementedError("'%s' is not an implemented data format", datatype) context_uri = pick(graph, self.graph) result = requests.post(url=self._make_url(namespace), headers={"Content-Type": content_type}, params={"context-uri": context_uri}, data=data) if result.status_code == 200: if is_file: log.info (" loaded %s into blazegraph - %s", file_name, self.format_response(result.text)) else: log.info(" loaded data - %s", self.format_response(result.text)) log.setLevel(self.log_level) return result else: raise SyntaxError(result.text)
python
def load_data(self, data, datatype="ttl", namespace=None, graph=None, is_file=False, **kwargs): """ Loads data via file stream from python to triplestore Args: ----- data: The data or filepath to load datatype(['ttl', 'xml', 'rdf']): the type of data to load namespace: the namespace to use graph: the graph to load the data to. is_file(False): If true python will read the data argument as a filepath, determine the datatype from the file extension, read the file and send it to blazegraph as a datastream """ log.setLevel(kwargs.get("log_level", self.log_level)) time_start = datetime.datetime.now() datatype_map = { 'ttl': 'text/turtle', 'xml': 'application/rdf+xml', 'rdf': 'application/rdf+xml', 'nt': 'text/plain' } if is_file: datatype = data.split(os.path.extsep)[-1] file_name = data log.debug('starting data load of %s', file_name) data = open(data, 'rb').read() else: try: data = data.encode('utf-8') except AttributeError: # data already encoded pass try: content_type = datatype_map[datatype] except KeyError: raise NotImplementedError("'%s' is not an implemented data format", datatype) context_uri = pick(graph, self.graph) result = requests.post(url=self._make_url(namespace), headers={"Content-Type": content_type}, params={"context-uri": context_uri}, data=data) if result.status_code == 200: if is_file: log.info (" loaded %s into blazegraph - %s", file_name, self.format_response(result.text)) else: log.info(" loaded data - %s", self.format_response(result.text)) log.setLevel(self.log_level) return result else: raise SyntaxError(result.text)
[ "def", "load_data", "(", "self", ",", "data", ",", "datatype", "=", "\"ttl\"", ",", "namespace", "=", "None", ",", "graph", "=", "None", ",", "is_file", "=", "False", ",", "*", "*", "kwargs", ")", ":", "log", ".", "setLevel", "(", "kwargs", ".", "get", "(", "\"log_level\"", ",", "self", ".", "log_level", ")", ")", "time_start", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "datatype_map", "=", "{", "'ttl'", ":", "'text/turtle'", ",", "'xml'", ":", "'application/rdf+xml'", ",", "'rdf'", ":", "'application/rdf+xml'", ",", "'nt'", ":", "'text/plain'", "}", "if", "is_file", ":", "datatype", "=", "data", ".", "split", "(", "os", ".", "path", ".", "extsep", ")", "[", "-", "1", "]", "file_name", "=", "data", "log", ".", "debug", "(", "'starting data load of %s'", ",", "file_name", ")", "data", "=", "open", "(", "data", ",", "'rb'", ")", ".", "read", "(", ")", "else", ":", "try", ":", "data", "=", "data", ".", "encode", "(", "'utf-8'", ")", "except", "AttributeError", ":", "# data already encoded", "pass", "try", ":", "content_type", "=", "datatype_map", "[", "datatype", "]", "except", "KeyError", ":", "raise", "NotImplementedError", "(", "\"'%s' is not an implemented data format\"", ",", "datatype", ")", "context_uri", "=", "pick", "(", "graph", ",", "self", ".", "graph", ")", "result", "=", "requests", ".", "post", "(", "url", "=", "self", ".", "_make_url", "(", "namespace", ")", ",", "headers", "=", "{", "\"Content-Type\"", ":", "content_type", "}", ",", "params", "=", "{", "\"context-uri\"", ":", "context_uri", "}", ",", "data", "=", "data", ")", "if", "result", ".", "status_code", "==", "200", ":", "if", "is_file", ":", "log", ".", "info", "(", "\" loaded %s into blazegraph - %s\"", ",", "file_name", ",", "self", ".", "format_response", "(", "result", ".", "text", ")", ")", "else", ":", "log", ".", "info", "(", "\" loaded data - %s\"", ",", "self", ".", "format_response", "(", "result", ".", "text", ")", ")", "log", ".", "setLevel", "(", "self", ".", "log_level", ")", "return", "result", "else", ":", "raise", "SyntaxError", "(", "result", ".", "text", ")" ]
Loads data via file stream from python to triplestore Args: ----- data: The data or filepath to load datatype(['ttl', 'xml', 'rdf']): the type of data to load namespace: the namespace to use graph: the graph to load the data to. is_file(False): If true python will read the data argument as a filepath, determine the datatype from the file extension, read the file and send it to blazegraph as a datastream
[ "Loads", "data", "via", "file", "stream", "from", "python", "to", "triplestore" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/connections/blazegraph.py#L273-L332
251,227
KnowledgeLinks/rdfframework
rdfframework/connections/blazegraph.py
Blazegraph.load_local_file
def load_local_file(self, file_path, namespace=None, graph=None, **kwargs): """ Uploads data to the Blazegraph Triplestore that is stored in files in directory that is available locally to blazegraph args: file_path: full path to the file namespace: the Blazegraph namespace to load the data graph: uri of the graph to load the data. Default is None kwargs: container_dir: the directory as seen by blazegraph - defaults to instance attribute if not passed """ time_start = datetime.datetime.now() url = self._make_url(namespace) params = {} if graph: params['context-uri'] = graph new_path = [] container_dir = pick(kwargs.get('container_dir'), self.container_dir) if container_dir: new_path.append(self.container_dir) new_path.append(file_path) params['uri'] = "file:///%s" % os.path.join(*new_path) log.debug(" loading %s into blazegraph", file_path) result = requests.post(url=url, params=params) if result.status_code > 300: raise SyntaxError(result.text) log.info("loaded '%s' in time: %s blazegraph response: %s", file_path, datetime.datetime.now() - time_start, self.format_response(result.text)) return result
python
def load_local_file(self, file_path, namespace=None, graph=None, **kwargs): """ Uploads data to the Blazegraph Triplestore that is stored in files in directory that is available locally to blazegraph args: file_path: full path to the file namespace: the Blazegraph namespace to load the data graph: uri of the graph to load the data. Default is None kwargs: container_dir: the directory as seen by blazegraph - defaults to instance attribute if not passed """ time_start = datetime.datetime.now() url = self._make_url(namespace) params = {} if graph: params['context-uri'] = graph new_path = [] container_dir = pick(kwargs.get('container_dir'), self.container_dir) if container_dir: new_path.append(self.container_dir) new_path.append(file_path) params['uri'] = "file:///%s" % os.path.join(*new_path) log.debug(" loading %s into blazegraph", file_path) result = requests.post(url=url, params=params) if result.status_code > 300: raise SyntaxError(result.text) log.info("loaded '%s' in time: %s blazegraph response: %s", file_path, datetime.datetime.now() - time_start, self.format_response(result.text)) return result
[ "def", "load_local_file", "(", "self", ",", "file_path", ",", "namespace", "=", "None", ",", "graph", "=", "None", ",", "*", "*", "kwargs", ")", ":", "time_start", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "url", "=", "self", ".", "_make_url", "(", "namespace", ")", "params", "=", "{", "}", "if", "graph", ":", "params", "[", "'context-uri'", "]", "=", "graph", "new_path", "=", "[", "]", "container_dir", "=", "pick", "(", "kwargs", ".", "get", "(", "'container_dir'", ")", ",", "self", ".", "container_dir", ")", "if", "container_dir", ":", "new_path", ".", "append", "(", "self", ".", "container_dir", ")", "new_path", ".", "append", "(", "file_path", ")", "params", "[", "'uri'", "]", "=", "\"file:///%s\"", "%", "os", ".", "path", ".", "join", "(", "*", "new_path", ")", "log", ".", "debug", "(", "\" loading %s into blazegraph\"", ",", "file_path", ")", "result", "=", "requests", ".", "post", "(", "url", "=", "url", ",", "params", "=", "params", ")", "if", "result", ".", "status_code", ">", "300", ":", "raise", "SyntaxError", "(", "result", ".", "text", ")", "log", ".", "info", "(", "\"loaded '%s' in time: %s blazegraph response: %s\"", ",", "file_path", ",", "datetime", ".", "datetime", ".", "now", "(", ")", "-", "time_start", ",", "self", ".", "format_response", "(", "result", ".", "text", ")", ")", "return", "result" ]
Uploads data to the Blazegraph Triplestore that is stored in files in directory that is available locally to blazegraph args: file_path: full path to the file namespace: the Blazegraph namespace to load the data graph: uri of the graph to load the data. Default is None kwargs: container_dir: the directory as seen by blazegraph - defaults to instance attribute if not passed
[ "Uploads", "data", "to", "the", "Blazegraph", "Triplestore", "that", "is", "stored", "in", "files", "in", "directory", "that", "is", "available", "locally", "to", "blazegraph" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/connections/blazegraph.py#L439-L471
251,228
KnowledgeLinks/rdfframework
rdfframework/connections/blazegraph.py
Blazegraph.has_namespace
def has_namespace(self, namespace): """ tests to see if the namespace exists args: namespace: the name of the namespace """ result = requests.get(self._make_url(namespace)) if result.status_code == 200: return True elif result.status_code == 404: return False
python
def has_namespace(self, namespace): """ tests to see if the namespace exists args: namespace: the name of the namespace """ result = requests.get(self._make_url(namespace)) if result.status_code == 200: return True elif result.status_code == 404: return False
[ "def", "has_namespace", "(", "self", ",", "namespace", ")", ":", "result", "=", "requests", ".", "get", "(", "self", ".", "_make_url", "(", "namespace", ")", ")", "if", "result", ".", "status_code", "==", "200", ":", "return", "True", "elif", "result", ".", "status_code", "==", "404", ":", "return", "False" ]
tests to see if the namespace exists args: namespace: the name of the namespace
[ "tests", "to", "see", "if", "the", "namespace", "exists" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/connections/blazegraph.py#L473-L483
251,229
KnowledgeLinks/rdfframework
rdfframework/connections/blazegraph.py
Blazegraph.create_namespace
def create_namespace(self, namespace=None, params=None): """ Creates a namespace in the triplestore args: namespace: the name of the namspace to create params: Dictionary of Blazegraph paramaters. defaults are: {'axioms': 'com.bigdata.rdf.axioms.NoAxioms', 'geoSpatial': False, 'isolatableIndices': False, 'justify': False, 'quads': False, 'rdr': False, 'textIndex': False, 'truthMaintenance': False} """ namespace = pick(namespace, self.namespace) params = pick(params, self.namespace_params) if not namespace: raise ReferenceError("No 'namespace' specified") _params = {'axioms': 'com.bigdata.rdf.axioms.NoAxioms', 'geoSpatial': False, 'isolatableIndices': False, 'justify': False, 'namespace': namespace, 'quads': True, 'rdr': False, 'textIndex': False, 'truthMaintenance': False} if params: _params.update(params) content_type = "text/plain" url = self._make_url("prepareProperties").replace("/sparql", "") params = ["%s=%s" % (map_val, json.dumps(_params[map_key]).replace("\"", "")) \ for map_key, map_val in self.ns_property_map.items()] params = "\n".join(params) result = requests.post(url=url, headers={"Content-Type": content_type}, data=params) data = result.text content_type = "application/xml" url = self._make_url("x").replace("/x/sparql", "") result = requests.post(url=url, headers={"Content-Type": content_type}, data=data) if result.status_code == 201: log.warning(result.text) return result.text else: raise RuntimeError(result.text)
python
def create_namespace(self, namespace=None, params=None): """ Creates a namespace in the triplestore args: namespace: the name of the namspace to create params: Dictionary of Blazegraph paramaters. defaults are: {'axioms': 'com.bigdata.rdf.axioms.NoAxioms', 'geoSpatial': False, 'isolatableIndices': False, 'justify': False, 'quads': False, 'rdr': False, 'textIndex': False, 'truthMaintenance': False} """ namespace = pick(namespace, self.namespace) params = pick(params, self.namespace_params) if not namespace: raise ReferenceError("No 'namespace' specified") _params = {'axioms': 'com.bigdata.rdf.axioms.NoAxioms', 'geoSpatial': False, 'isolatableIndices': False, 'justify': False, 'namespace': namespace, 'quads': True, 'rdr': False, 'textIndex': False, 'truthMaintenance': False} if params: _params.update(params) content_type = "text/plain" url = self._make_url("prepareProperties").replace("/sparql", "") params = ["%s=%s" % (map_val, json.dumps(_params[map_key]).replace("\"", "")) \ for map_key, map_val in self.ns_property_map.items()] params = "\n".join(params) result = requests.post(url=url, headers={"Content-Type": content_type}, data=params) data = result.text content_type = "application/xml" url = self._make_url("x").replace("/x/sparql", "") result = requests.post(url=url, headers={"Content-Type": content_type}, data=data) if result.status_code == 201: log.warning(result.text) return result.text else: raise RuntimeError(result.text)
[ "def", "create_namespace", "(", "self", ",", "namespace", "=", "None", ",", "params", "=", "None", ")", ":", "namespace", "=", "pick", "(", "namespace", ",", "self", ".", "namespace", ")", "params", "=", "pick", "(", "params", ",", "self", ".", "namespace_params", ")", "if", "not", "namespace", ":", "raise", "ReferenceError", "(", "\"No 'namespace' specified\"", ")", "_params", "=", "{", "'axioms'", ":", "'com.bigdata.rdf.axioms.NoAxioms'", ",", "'geoSpatial'", ":", "False", ",", "'isolatableIndices'", ":", "False", ",", "'justify'", ":", "False", ",", "'namespace'", ":", "namespace", ",", "'quads'", ":", "True", ",", "'rdr'", ":", "False", ",", "'textIndex'", ":", "False", ",", "'truthMaintenance'", ":", "False", "}", "if", "params", ":", "_params", ".", "update", "(", "params", ")", "content_type", "=", "\"text/plain\"", "url", "=", "self", ".", "_make_url", "(", "\"prepareProperties\"", ")", ".", "replace", "(", "\"/sparql\"", ",", "\"\"", ")", "params", "=", "[", "\"%s=%s\"", "%", "(", "map_val", ",", "json", ".", "dumps", "(", "_params", "[", "map_key", "]", ")", ".", "replace", "(", "\"\\\"\"", ",", "\"\"", ")", ")", "for", "map_key", ",", "map_val", "in", "self", ".", "ns_property_map", ".", "items", "(", ")", "]", "params", "=", "\"\\n\"", ".", "join", "(", "params", ")", "result", "=", "requests", ".", "post", "(", "url", "=", "url", ",", "headers", "=", "{", "\"Content-Type\"", ":", "content_type", "}", ",", "data", "=", "params", ")", "data", "=", "result", ".", "text", "content_type", "=", "\"application/xml\"", "url", "=", "self", ".", "_make_url", "(", "\"x\"", ")", ".", "replace", "(", "\"/x/sparql\"", ",", "\"\"", ")", "result", "=", "requests", ".", "post", "(", "url", "=", "url", ",", "headers", "=", "{", "\"Content-Type\"", ":", "content_type", "}", ",", "data", "=", "data", ")", "if", "result", ".", "status_code", "==", "201", ":", "log", ".", "warning", "(", "result", ".", "text", ")", "return", "result", ".", "text", "else", ":", "raise", "RuntimeError", "(", "result", ".", "text", ")" ]
Creates a namespace in the triplestore args: namespace: the name of the namspace to create params: Dictionary of Blazegraph paramaters. defaults are: {'axioms': 'com.bigdata.rdf.axioms.NoAxioms', 'geoSpatial': False, 'isolatableIndices': False, 'justify': False, 'quads': False, 'rdr': False, 'textIndex': False, 'truthMaintenance': False}
[ "Creates", "a", "namespace", "in", "the", "triplestore" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/connections/blazegraph.py#L485-L535
251,230
KnowledgeLinks/rdfframework
rdfframework/connections/blazegraph.py
Blazegraph.delete_namespace
def delete_namespace(self, namespace): """ Deletes a namespace fromt the triplestore args: namespace: the name of the namespace """ # if not self.has_namespace(namespace): # return "Namespace does not exists" # log = logging.getLogger("%s.%s" % (self.log_name, # inspect.stack()[0][3])) # log.setLevel(self.log_level) url = self._make_url(namespace).replace("/sparql", "") result = requests.delete(url=url) if result.status_code == 200: log.critical(result.text) return result.text raise RuntimeError(result.text)
python
def delete_namespace(self, namespace): """ Deletes a namespace fromt the triplestore args: namespace: the name of the namespace """ # if not self.has_namespace(namespace): # return "Namespace does not exists" # log = logging.getLogger("%s.%s" % (self.log_name, # inspect.stack()[0][3])) # log.setLevel(self.log_level) url = self._make_url(namespace).replace("/sparql", "") result = requests.delete(url=url) if result.status_code == 200: log.critical(result.text) return result.text raise RuntimeError(result.text)
[ "def", "delete_namespace", "(", "self", ",", "namespace", ")", ":", "# if not self.has_namespace(namespace):", "# return \"Namespace does not exists\"", "# log = logging.getLogger(\"%s.%s\" % (self.log_name,", "# inspect.stack()[0][3]))", "# log.setLevel(self.log_level)", "url", "=", "self", ".", "_make_url", "(", "namespace", ")", ".", "replace", "(", "\"/sparql\"", ",", "\"\"", ")", "result", "=", "requests", ".", "delete", "(", "url", "=", "url", ")", "if", "result", ".", "status_code", "==", "200", ":", "log", ".", "critical", "(", "result", ".", "text", ")", "return", "result", ".", "text", "raise", "RuntimeError", "(", "result", ".", "text", ")" ]
Deletes a namespace fromt the triplestore args: namespace: the name of the namespace
[ "Deletes", "a", "namespace", "fromt", "the", "triplestore" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/connections/blazegraph.py#L537-L556
251,231
KnowledgeLinks/rdfframework
rdfframework/connections/blazegraph.py
Blazegraph._make_url
def _make_url(self, namespace=None, url=None, **kwargs): """ Creates the REST Url based on the supplied namespace args: namespace: string of the namespace kwargs: check_status_call: True/False, whether the function is called from check_status. Used to avoid recurrsion error """ if not kwargs.get("check_status_call"): if not self.url: self.check_status rtn_url = self.url if url: rtn_url = url if rtn_url is None: rtn_url = self.ext_url namespace = pick(namespace, self.namespace) if namespace: rtn_url = os.path.join(rtn_url.replace("sparql", ""), "namespace", namespace, "sparql").replace("\\", "/") elif not rtn_url.endswith("sparql"): rtn_url = os.path.join(rtn_url, "sparql").replace("\\", "/") return rtn_url
python
def _make_url(self, namespace=None, url=None, **kwargs): """ Creates the REST Url based on the supplied namespace args: namespace: string of the namespace kwargs: check_status_call: True/False, whether the function is called from check_status. Used to avoid recurrsion error """ if not kwargs.get("check_status_call"): if not self.url: self.check_status rtn_url = self.url if url: rtn_url = url if rtn_url is None: rtn_url = self.ext_url namespace = pick(namespace, self.namespace) if namespace: rtn_url = os.path.join(rtn_url.replace("sparql", ""), "namespace", namespace, "sparql").replace("\\", "/") elif not rtn_url.endswith("sparql"): rtn_url = os.path.join(rtn_url, "sparql").replace("\\", "/") return rtn_url
[ "def", "_make_url", "(", "self", ",", "namespace", "=", "None", ",", "url", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "kwargs", ".", "get", "(", "\"check_status_call\"", ")", ":", "if", "not", "self", ".", "url", ":", "self", ".", "check_status", "rtn_url", "=", "self", ".", "url", "if", "url", ":", "rtn_url", "=", "url", "if", "rtn_url", "is", "None", ":", "rtn_url", "=", "self", ".", "ext_url", "namespace", "=", "pick", "(", "namespace", ",", "self", ".", "namespace", ")", "if", "namespace", ":", "rtn_url", "=", "os", ".", "path", ".", "join", "(", "rtn_url", ".", "replace", "(", "\"sparql\"", ",", "\"\"", ")", ",", "\"namespace\"", ",", "namespace", ",", "\"sparql\"", ")", ".", "replace", "(", "\"\\\\\"", ",", "\"/\"", ")", "elif", "not", "rtn_url", ".", "endswith", "(", "\"sparql\"", ")", ":", "rtn_url", "=", "os", ".", "path", ".", "join", "(", "rtn_url", ",", "\"sparql\"", ")", ".", "replace", "(", "\"\\\\\"", ",", "\"/\"", ")", "return", "rtn_url" ]
Creates the REST Url based on the supplied namespace args: namespace: string of the namespace kwargs: check_status_call: True/False, whether the function is called from check_status. Used to avoid recurrsion error
[ "Creates", "the", "REST", "Url", "based", "on", "the", "supplied", "namespace" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/connections/blazegraph.py#L558-L583
251,232
KnowledgeLinks/rdfframework
rdfframework/connections/blazegraph.py
Blazegraph.reset_namespace
def reset_namespace(self, namespace=None, params=None): """ Will delete and recreate specified namespace args: namespace(str): Namespace to reset params(dict): params used to reset the namespace """ log = logging.getLogger("%s.%s" % (self.log_name, inspect.stack()[0][3])) log.setLevel(self.log_level) namespace = pick(namespace, self.namespace) params = pick(params, self.namespace_params) log.warning(" Reseting namespace '%s' at host: %s", namespace, self.url) try: self.delete_namespace(namespace) except RuntimeError: pass self.create_namespace(namespace, params)
python
def reset_namespace(self, namespace=None, params=None): """ Will delete and recreate specified namespace args: namespace(str): Namespace to reset params(dict): params used to reset the namespace """ log = logging.getLogger("%s.%s" % (self.log_name, inspect.stack()[0][3])) log.setLevel(self.log_level) namespace = pick(namespace, self.namespace) params = pick(params, self.namespace_params) log.warning(" Reseting namespace '%s' at host: %s", namespace, self.url) try: self.delete_namespace(namespace) except RuntimeError: pass self.create_namespace(namespace, params)
[ "def", "reset_namespace", "(", "self", ",", "namespace", "=", "None", ",", "params", "=", "None", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "\"%s.%s\"", "%", "(", "self", ".", "log_name", ",", "inspect", ".", "stack", "(", ")", "[", "0", "]", "[", "3", "]", ")", ")", "log", ".", "setLevel", "(", "self", ".", "log_level", ")", "namespace", "=", "pick", "(", "namespace", ",", "self", ".", "namespace", ")", "params", "=", "pick", "(", "params", ",", "self", ".", "namespace_params", ")", "log", ".", "warning", "(", "\" Reseting namespace '%s' at host: %s\"", ",", "namespace", ",", "self", ".", "url", ")", "try", ":", "self", ".", "delete_namespace", "(", "namespace", ")", "except", "RuntimeError", ":", "pass", "self", ".", "create_namespace", "(", "namespace", ",", "params", ")" ]
Will delete and recreate specified namespace args: namespace(str): Namespace to reset params(dict): params used to reset the namespace
[ "Will", "delete", "and", "recreate", "specified", "namespace" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/connections/blazegraph.py#L585-L604
251,233
20tab/twentytab-tree
tree/views.py
tree_render
def tree_render(request, upy_context, vars_dictionary): """ It renders template defined in upy_context's page passed in arguments """ page = upy_context['PAGE'] return render_to_response(page.template.file_name, vars_dictionary, context_instance=RequestContext(request))
python
def tree_render(request, upy_context, vars_dictionary): """ It renders template defined in upy_context's page passed in arguments """ page = upy_context['PAGE'] return render_to_response(page.template.file_name, vars_dictionary, context_instance=RequestContext(request))
[ "def", "tree_render", "(", "request", ",", "upy_context", ",", "vars_dictionary", ")", ":", "page", "=", "upy_context", "[", "'PAGE'", "]", "return", "render_to_response", "(", "page", ".", "template", ".", "file_name", ",", "vars_dictionary", ",", "context_instance", "=", "RequestContext", "(", "request", ")", ")" ]
It renders template defined in upy_context's page passed in arguments
[ "It", "renders", "template", "defined", "in", "upy_context", "s", "page", "passed", "in", "arguments" ]
f2c1ced33e6c211bb52a25a7d48155e39fbdc088
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/views.py#L8-L13
251,234
20tab/twentytab-tree
tree/views.py
view_404
def view_404(request, url=None): """ It returns a 404 http response """ res = render_to_response("404.html", {"PAGE_URL": request.get_full_path()}, context_instance=RequestContext(request)) res.status_code = 404 return res
python
def view_404(request, url=None): """ It returns a 404 http response """ res = render_to_response("404.html", {"PAGE_URL": request.get_full_path()}, context_instance=RequestContext(request)) res.status_code = 404 return res
[ "def", "view_404", "(", "request", ",", "url", "=", "None", ")", ":", "res", "=", "render_to_response", "(", "\"404.html\"", ",", "{", "\"PAGE_URL\"", ":", "request", ".", "get_full_path", "(", ")", "}", ",", "context_instance", "=", "RequestContext", "(", "request", ")", ")", "res", ".", "status_code", "=", "404", "return", "res" ]
It returns a 404 http response
[ "It", "returns", "a", "404", "http", "response" ]
f2c1ced33e6c211bb52a25a7d48155e39fbdc088
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/views.py#L16-L23
251,235
20tab/twentytab-tree
tree/views.py
view_500
def view_500(request, url=None): """ it returns a 500 http response """ res = render_to_response("500.html", context_instance=RequestContext(request)) res.status_code = 500 return res
python
def view_500(request, url=None): """ it returns a 500 http response """ res = render_to_response("500.html", context_instance=RequestContext(request)) res.status_code = 500 return res
[ "def", "view_500", "(", "request", ",", "url", "=", "None", ")", ":", "res", "=", "render_to_response", "(", "\"500.html\"", ",", "context_instance", "=", "RequestContext", "(", "request", ")", ")", "res", ".", "status_code", "=", "500", "return", "res" ]
it returns a 500 http response
[ "it", "returns", "a", "500", "http", "response" ]
f2c1ced33e6c211bb52a25a7d48155e39fbdc088
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/views.py#L26-L32
251,236
20tab/twentytab-tree
tree/views.py
favicon
def favicon(request): """ It returns favicon's location """ favicon = u"{}tree/images/favicon.ico".format(settings.STATIC_URL) try: from seo.models import MetaSite site = MetaSite.objects.get(default=True) return HttpResponseRedirect(site.favicon.url) except: return HttpResponseRedirect(favicon)
python
def favicon(request): """ It returns favicon's location """ favicon = u"{}tree/images/favicon.ico".format(settings.STATIC_URL) try: from seo.models import MetaSite site = MetaSite.objects.get(default=True) return HttpResponseRedirect(site.favicon.url) except: return HttpResponseRedirect(favicon)
[ "def", "favicon", "(", "request", ")", ":", "favicon", "=", "u\"{}tree/images/favicon.ico\"", ".", "format", "(", "settings", ".", "STATIC_URL", ")", "try", ":", "from", "seo", ".", "models", "import", "MetaSite", "site", "=", "MetaSite", ".", "objects", ".", "get", "(", "default", "=", "True", ")", "return", "HttpResponseRedirect", "(", "site", ".", "favicon", ".", "url", ")", "except", ":", "return", "HttpResponseRedirect", "(", "favicon", ")" ]
It returns favicon's location
[ "It", "returns", "favicon", "s", "location" ]
f2c1ced33e6c211bb52a25a7d48155e39fbdc088
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/views.py#L51-L61
251,237
minhhoit/yacms
yacms/accounts/forms.py
ProfileForm.clean_username
def clean_username(self): """ Ensure the username doesn't exist or contain invalid chars. We limit it to slugifiable chars since it's used as the slug for the user's profile view. """ username = self.cleaned_data.get("username") if username.lower() != slugify(username).lower(): raise forms.ValidationError( ugettext("Username can only contain letters, numbers, dashes " "or underscores.")) lookup = {"username__iexact": username} try: User.objects.exclude(id=self.instance.id).get(**lookup) except User.DoesNotExist: return username raise forms.ValidationError( ugettext("This username is already registered"))
python
def clean_username(self): """ Ensure the username doesn't exist or contain invalid chars. We limit it to slugifiable chars since it's used as the slug for the user's profile view. """ username = self.cleaned_data.get("username") if username.lower() != slugify(username).lower(): raise forms.ValidationError( ugettext("Username can only contain letters, numbers, dashes " "or underscores.")) lookup = {"username__iexact": username} try: User.objects.exclude(id=self.instance.id).get(**lookup) except User.DoesNotExist: return username raise forms.ValidationError( ugettext("This username is already registered"))
[ "def", "clean_username", "(", "self", ")", ":", "username", "=", "self", ".", "cleaned_data", ".", "get", "(", "\"username\"", ")", "if", "username", ".", "lower", "(", ")", "!=", "slugify", "(", "username", ")", ".", "lower", "(", ")", ":", "raise", "forms", ".", "ValidationError", "(", "ugettext", "(", "\"Username can only contain letters, numbers, dashes \"", "\"or underscores.\"", ")", ")", "lookup", "=", "{", "\"username__iexact\"", ":", "username", "}", "try", ":", "User", ".", "objects", ".", "exclude", "(", "id", "=", "self", ".", "instance", ".", "id", ")", ".", "get", "(", "*", "*", "lookup", ")", "except", "User", ".", "DoesNotExist", ":", "return", "username", "raise", "forms", ".", "ValidationError", "(", "ugettext", "(", "\"This username is already registered\"", ")", ")" ]
Ensure the username doesn't exist or contain invalid chars. We limit it to slugifiable chars since it's used as the slug for the user's profile view.
[ "Ensure", "the", "username", "doesn", "t", "exist", "or", "contain", "invalid", "chars", ".", "We", "limit", "it", "to", "slugifiable", "chars", "since", "it", "s", "used", "as", "the", "slug", "for", "the", "user", "s", "profile", "view", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/accounts/forms.py#L130-L147
251,238
minhhoit/yacms
yacms/accounts/forms.py
ProfileForm.clean_password2
def clean_password2(self): """ Ensure the password fields are equal, and match the minimum length defined by ``ACCOUNTS_MIN_PASSWORD_LENGTH``. """ password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1: errors = [] if password1 != password2: errors.append(ugettext("Passwords do not match")) if len(password1) < settings.ACCOUNTS_MIN_PASSWORD_LENGTH: errors.append( ugettext("Password must be at least %s characters") % settings.ACCOUNTS_MIN_PASSWORD_LENGTH) if errors: self._errors["password1"] = self.error_class(errors) return password2
python
def clean_password2(self): """ Ensure the password fields are equal, and match the minimum length defined by ``ACCOUNTS_MIN_PASSWORD_LENGTH``. """ password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1: errors = [] if password1 != password2: errors.append(ugettext("Passwords do not match")) if len(password1) < settings.ACCOUNTS_MIN_PASSWORD_LENGTH: errors.append( ugettext("Password must be at least %s characters") % settings.ACCOUNTS_MIN_PASSWORD_LENGTH) if errors: self._errors["password1"] = self.error_class(errors) return password2
[ "def", "clean_password2", "(", "self", ")", ":", "password1", "=", "self", ".", "cleaned_data", ".", "get", "(", "\"password1\"", ")", "password2", "=", "self", ".", "cleaned_data", ".", "get", "(", "\"password2\"", ")", "if", "password1", ":", "errors", "=", "[", "]", "if", "password1", "!=", "password2", ":", "errors", ".", "append", "(", "ugettext", "(", "\"Passwords do not match\"", ")", ")", "if", "len", "(", "password1", ")", "<", "settings", ".", "ACCOUNTS_MIN_PASSWORD_LENGTH", ":", "errors", ".", "append", "(", "ugettext", "(", "\"Password must be at least %s characters\"", ")", "%", "settings", ".", "ACCOUNTS_MIN_PASSWORD_LENGTH", ")", "if", "errors", ":", "self", ".", "_errors", "[", "\"password1\"", "]", "=", "self", ".", "error_class", "(", "errors", ")", "return", "password2" ]
Ensure the password fields are equal, and match the minimum length defined by ``ACCOUNTS_MIN_PASSWORD_LENGTH``.
[ "Ensure", "the", "password", "fields", "are", "equal", "and", "match", "the", "minimum", "length", "defined", "by", "ACCOUNTS_MIN_PASSWORD_LENGTH", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/accounts/forms.py#L149-L167
251,239
minhhoit/yacms
yacms/accounts/forms.py
ProfileForm.clean_email
def clean_email(self): """ Ensure the email address is not already registered. """ email = self.cleaned_data.get("email") qs = User.objects.exclude(id=self.instance.id).filter(email=email) if len(qs) == 0: return email raise forms.ValidationError( ugettext("This email is already registered"))
python
def clean_email(self): """ Ensure the email address is not already registered. """ email = self.cleaned_data.get("email") qs = User.objects.exclude(id=self.instance.id).filter(email=email) if len(qs) == 0: return email raise forms.ValidationError( ugettext("This email is already registered"))
[ "def", "clean_email", "(", "self", ")", ":", "email", "=", "self", ".", "cleaned_data", ".", "get", "(", "\"email\"", ")", "qs", "=", "User", ".", "objects", ".", "exclude", "(", "id", "=", "self", ".", "instance", ".", "id", ")", ".", "filter", "(", "email", "=", "email", ")", "if", "len", "(", "qs", ")", "==", "0", ":", "return", "email", "raise", "forms", ".", "ValidationError", "(", "ugettext", "(", "\"This email is already registered\"", ")", ")" ]
Ensure the email address is not already registered.
[ "Ensure", "the", "email", "address", "is", "not", "already", "registered", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/accounts/forms.py#L169-L178
251,240
voidabhi/TheZineAPI
tz/tz.py
TZ.get_articles
def get_articles(self, issue=''): """ Yields a list of articles from the given issue. """ soup = get_soup() # get soup of all articles issues = soup.find_all('ul') # validating and assigning default value for issue if not type(issue) is int or issue < 0 : issue = 1 if issue > len(issues): issue = len(issues) # considering latest article is last element articles = issues[len(issues)-issue].find_all('a') mArticles = [] for article in articles: mArticle = {} mArticle['link'] = article.get('href')[1:] mArticle['title'] = article.find('li').contents[0].strip() mArticle['author'] = article.find('span').contents[0].encode('utf8') mArticles.append(mArticle) return mArticles
python
def get_articles(self, issue=''): """ Yields a list of articles from the given issue. """ soup = get_soup() # get soup of all articles issues = soup.find_all('ul') # validating and assigning default value for issue if not type(issue) is int or issue < 0 : issue = 1 if issue > len(issues): issue = len(issues) # considering latest article is last element articles = issues[len(issues)-issue].find_all('a') mArticles = [] for article in articles: mArticle = {} mArticle['link'] = article.get('href')[1:] mArticle['title'] = article.find('li').contents[0].strip() mArticle['author'] = article.find('span').contents[0].encode('utf8') mArticles.append(mArticle) return mArticles
[ "def", "get_articles", "(", "self", ",", "issue", "=", "''", ")", ":", "soup", "=", "get_soup", "(", ")", "# get soup of all articles ", "issues", "=", "soup", ".", "find_all", "(", "'ul'", ")", "# validating and assigning default value for issue", "if", "not", "type", "(", "issue", ")", "is", "int", "or", "issue", "<", "0", ":", "issue", "=", "1", "if", "issue", ">", "len", "(", "issues", ")", ":", "issue", "=", "len", "(", "issues", ")", "# considering latest article is last element \t\t", "articles", "=", "issues", "[", "len", "(", "issues", ")", "-", "issue", "]", ".", "find_all", "(", "'a'", ")", "mArticles", "=", "[", "]", "for", "article", "in", "articles", ":", "mArticle", "=", "{", "}", "mArticle", "[", "'link'", "]", "=", "article", ".", "get", "(", "'href'", ")", "[", "1", ":", "]", "mArticle", "[", "'title'", "]", "=", "article", ".", "find", "(", "'li'", ")", ".", "contents", "[", "0", "]", ".", "strip", "(", ")", "mArticle", "[", "'author'", "]", "=", "article", ".", "find", "(", "'span'", ")", ".", "contents", "[", "0", "]", ".", "encode", "(", "'utf8'", ")", "mArticles", ".", "append", "(", "mArticle", ")", "return", "mArticles" ]
Yields a list of articles from the given issue.
[ "Yields", "a", "list", "of", "articles", "from", "the", "given", "issue", "." ]
c13da4c464fe3e0d31cea0f7d4e6a50a360947ad
https://github.com/voidabhi/TheZineAPI/blob/c13da4c464fe3e0d31cea0f7d4e6a50a360947ad/tz/tz.py#L30-L54
251,241
voidabhi/TheZineAPI
tz/tz.py
Article.fromLink
def fromLink(self, link): """ Factory Method. Fetches article data from given link and builds the object """ soup = get_article_soup(link) head = soup.find_all('article',class_='')[0] parts = link.split('/') id = '%s-%s'%(parts[0],parts[-1]) issue = parts[0].split('-')[-1] #fetching head title = head.find("h1").contents[0] if head.find("h1") else '' tagline = head.find("h2").contents[0] if head.find("h2") else '' body = '' #fetching body if len(soup.find_all('article',class_='main-body')) > 0: body = soup.find_all('article',class_='main-body')[0].find(class_='inner') author = '' #fetching author if len(soup.find_all('aside')) > 0: aside = soup.find_all('aside')[0] if soup.find_all('aside')[0] else '' author = Author.from_soup(aside) return Article(id=id,title=title,tagline=tagline,body=body,issue=issue,link='http://thezine.biz/%s'%link,author=author)
python
def fromLink(self, link): """ Factory Method. Fetches article data from given link and builds the object """ soup = get_article_soup(link) head = soup.find_all('article',class_='')[0] parts = link.split('/') id = '%s-%s'%(parts[0],parts[-1]) issue = parts[0].split('-')[-1] #fetching head title = head.find("h1").contents[0] if head.find("h1") else '' tagline = head.find("h2").contents[0] if head.find("h2") else '' body = '' #fetching body if len(soup.find_all('article',class_='main-body')) > 0: body = soup.find_all('article',class_='main-body')[0].find(class_='inner') author = '' #fetching author if len(soup.find_all('aside')) > 0: aside = soup.find_all('aside')[0] if soup.find_all('aside')[0] else '' author = Author.from_soup(aside) return Article(id=id,title=title,tagline=tagline,body=body,issue=issue,link='http://thezine.biz/%s'%link,author=author)
[ "def", "fromLink", "(", "self", ",", "link", ")", ":", "soup", "=", "get_article_soup", "(", "link", ")", "head", "=", "soup", ".", "find_all", "(", "'article'", ",", "class_", "=", "''", ")", "[", "0", "]", "parts", "=", "link", ".", "split", "(", "'/'", ")", "id", "=", "'%s-%s'", "%", "(", "parts", "[", "0", "]", ",", "parts", "[", "-", "1", "]", ")", "issue", "=", "parts", "[", "0", "]", ".", "split", "(", "'-'", ")", "[", "-", "1", "]", "#fetching head", "title", "=", "head", ".", "find", "(", "\"h1\"", ")", ".", "contents", "[", "0", "]", "if", "head", ".", "find", "(", "\"h1\"", ")", "else", "''", "tagline", "=", "head", ".", "find", "(", "\"h2\"", ")", ".", "contents", "[", "0", "]", "if", "head", ".", "find", "(", "\"h2\"", ")", "else", "''", "body", "=", "''", "#fetching body", "if", "len", "(", "soup", ".", "find_all", "(", "'article'", ",", "class_", "=", "'main-body'", ")", ")", ">", "0", ":", "body", "=", "soup", ".", "find_all", "(", "'article'", ",", "class_", "=", "'main-body'", ")", "[", "0", "]", ".", "find", "(", "class_", "=", "'inner'", ")", "author", "=", "''", "#fetching author", "if", "len", "(", "soup", ".", "find_all", "(", "'aside'", ")", ")", ">", "0", ":", "aside", "=", "soup", ".", "find_all", "(", "'aside'", ")", "[", "0", "]", "if", "soup", ".", "find_all", "(", "'aside'", ")", "[", "0", "]", "else", "''", "author", "=", "Author", ".", "from_soup", "(", "aside", ")", "return", "Article", "(", "id", "=", "id", ",", "title", "=", "title", ",", "tagline", "=", "tagline", ",", "body", "=", "body", ",", "issue", "=", "issue", ",", "link", "=", "'http://thezine.biz/%s'", "%", "link", ",", "author", "=", "author", ")" ]
Factory Method. Fetches article data from given link and builds the object
[ "Factory", "Method", ".", "Fetches", "article", "data", "from", "given", "link", "and", "builds", "the", "object" ]
c13da4c464fe3e0d31cea0f7d4e6a50a360947ad
https://github.com/voidabhi/TheZineAPI/blob/c13da4c464fe3e0d31cea0f7d4e6a50a360947ad/tz/tz.py#L73-L95
251,242
voidabhi/TheZineAPI
tz/tz.py
Author.from_soup
def from_soup(self,soup): """ Factory Pattern. Fetches author data from given soup and builds the object """ if soup is None or soup is '': return None else: author_name = soup.find('em').contents[0].strip() if soup.find('em') else '' author_image = soup.find('img').get('src') if soup.find('img') else '' author_contact = Contact.from_soup(self,soup) return Author(author_name,author_image,author_contact)
python
def from_soup(self,soup): """ Factory Pattern. Fetches author data from given soup and builds the object """ if soup is None or soup is '': return None else: author_name = soup.find('em').contents[0].strip() if soup.find('em') else '' author_image = soup.find('img').get('src') if soup.find('img') else '' author_contact = Contact.from_soup(self,soup) return Author(author_name,author_image,author_contact)
[ "def", "from_soup", "(", "self", ",", "soup", ")", ":", "if", "soup", "is", "None", "or", "soup", "is", "''", ":", "return", "None", "else", ":", "author_name", "=", "soup", ".", "find", "(", "'em'", ")", ".", "contents", "[", "0", "]", ".", "strip", "(", ")", "if", "soup", ".", "find", "(", "'em'", ")", "else", "''", "author_image", "=", "soup", ".", "find", "(", "'img'", ")", ".", "get", "(", "'src'", ")", "if", "soup", ".", "find", "(", "'img'", ")", "else", "''", "author_contact", "=", "Contact", ".", "from_soup", "(", "self", ",", "soup", ")", "return", "Author", "(", "author_name", ",", "author_image", ",", "author_contact", ")" ]
Factory Pattern. Fetches author data from given soup and builds the object
[ "Factory", "Pattern", ".", "Fetches", "author", "data", "from", "given", "soup", "and", "builds", "the", "object" ]
c13da4c464fe3e0d31cea0f7d4e6a50a360947ad
https://github.com/voidabhi/TheZineAPI/blob/c13da4c464fe3e0d31cea0f7d4e6a50a360947ad/tz/tz.py#L122-L132
251,243
voidabhi/TheZineAPI
tz/tz.py
Contact.from_soup
def from_soup(self,author,soup): """ Factory Pattern. Fetches contact data from given soup and builds the object """ email = soup.find('span',class_='icon icon-mail').findParent('a').get('href').split(':')[-1] if soup.find('span',class_='icon icon-mail') else '' facebook = soup.find('span',class_='icon icon-facebook').findParent('a').get('href') if soup.find('span',class_='icon icon-facebook') else '' twitter = soup.find('span',class_='icon icon-twitter-3').findParent('a').get('href') if soup.find('span',class_='icon icon-twitter-3') else '' link = soup.find('span',class_='icon icon-link').findParent('a').get('href') if soup.find('span',class_='icon icon-link') else '' return Contact(email,facebook,twitter,link)
python
def from_soup(self,author,soup): """ Factory Pattern. Fetches contact data from given soup and builds the object """ email = soup.find('span',class_='icon icon-mail').findParent('a').get('href').split(':')[-1] if soup.find('span',class_='icon icon-mail') else '' facebook = soup.find('span',class_='icon icon-facebook').findParent('a').get('href') if soup.find('span',class_='icon icon-facebook') else '' twitter = soup.find('span',class_='icon icon-twitter-3').findParent('a').get('href') if soup.find('span',class_='icon icon-twitter-3') else '' link = soup.find('span',class_='icon icon-link').findParent('a').get('href') if soup.find('span',class_='icon icon-link') else '' return Contact(email,facebook,twitter,link)
[ "def", "from_soup", "(", "self", ",", "author", ",", "soup", ")", ":", "email", "=", "soup", ".", "find", "(", "'span'", ",", "class_", "=", "'icon icon-mail'", ")", ".", "findParent", "(", "'a'", ")", ".", "get", "(", "'href'", ")", ".", "split", "(", "':'", ")", "[", "-", "1", "]", "if", "soup", ".", "find", "(", "'span'", ",", "class_", "=", "'icon icon-mail'", ")", "else", "''", "facebook", "=", "soup", ".", "find", "(", "'span'", ",", "class_", "=", "'icon icon-facebook'", ")", ".", "findParent", "(", "'a'", ")", ".", "get", "(", "'href'", ")", "if", "soup", ".", "find", "(", "'span'", ",", "class_", "=", "'icon icon-facebook'", ")", "else", "''", "twitter", "=", "soup", ".", "find", "(", "'span'", ",", "class_", "=", "'icon icon-twitter-3'", ")", ".", "findParent", "(", "'a'", ")", ".", "get", "(", "'href'", ")", "if", "soup", ".", "find", "(", "'span'", ",", "class_", "=", "'icon icon-twitter-3'", ")", "else", "''", "link", "=", "soup", ".", "find", "(", "'span'", ",", "class_", "=", "'icon icon-link'", ")", ".", "findParent", "(", "'a'", ")", ".", "get", "(", "'href'", ")", "if", "soup", ".", "find", "(", "'span'", ",", "class_", "=", "'icon icon-link'", ")", "else", "''", "return", "Contact", "(", "email", ",", "facebook", ",", "twitter", ",", "link", ")" ]
Factory Pattern. Fetches contact data from given soup and builds the object
[ "Factory", "Pattern", ".", "Fetches", "contact", "data", "from", "given", "soup", "and", "builds", "the", "object" ]
c13da4c464fe3e0d31cea0f7d4e6a50a360947ad
https://github.com/voidabhi/TheZineAPI/blob/c13da4c464fe3e0d31cea0f7d4e6a50a360947ad/tz/tz.py#L148-L156
251,244
marteinn/genres
genres/finder.py
Finder.find
def find(self, text): """ Return a list of genres found in text. """ genres = [] text = text.lower() category_counter = Counter() counter = Counter() for genre in self.db.genres: found = self.contains_entity(genre, text) if found: counter[genre] += found category = self.db.reference[genre] points = self.db.points[genre] points *= found # Add bonus points if additional terms points to category if category_counter[category] > 0: points += 1 category_counter[category] += points for tag in self.db.tags: found = self.contains_entity(tag, text) if found: category = self.db.reference[tag] if not counter[category]: counter[category] += found points = self.db.points[tag] points *= found category_counter[category] += points if not category_counter: return genres main_category = category_counter.most_common(1)[0][0] # Convert counter to a flat list of genres, sorted by count sorted_genres = [ite for ite, it in counter.most_common()] for genre in sorted_genres: insert = True if self.unique_category: if not self.db.reference[genre] == main_category: insert = False if insert: genres.append(genre) return genres
python
def find(self, text): """ Return a list of genres found in text. """ genres = [] text = text.lower() category_counter = Counter() counter = Counter() for genre in self.db.genres: found = self.contains_entity(genre, text) if found: counter[genre] += found category = self.db.reference[genre] points = self.db.points[genre] points *= found # Add bonus points if additional terms points to category if category_counter[category] > 0: points += 1 category_counter[category] += points for tag in self.db.tags: found = self.contains_entity(tag, text) if found: category = self.db.reference[tag] if not counter[category]: counter[category] += found points = self.db.points[tag] points *= found category_counter[category] += points if not category_counter: return genres main_category = category_counter.most_common(1)[0][0] # Convert counter to a flat list of genres, sorted by count sorted_genres = [ite for ite, it in counter.most_common()] for genre in sorted_genres: insert = True if self.unique_category: if not self.db.reference[genre] == main_category: insert = False if insert: genres.append(genre) return genres
[ "def", "find", "(", "self", ",", "text", ")", ":", "genres", "=", "[", "]", "text", "=", "text", ".", "lower", "(", ")", "category_counter", "=", "Counter", "(", ")", "counter", "=", "Counter", "(", ")", "for", "genre", "in", "self", ".", "db", ".", "genres", ":", "found", "=", "self", ".", "contains_entity", "(", "genre", ",", "text", ")", "if", "found", ":", "counter", "[", "genre", "]", "+=", "found", "category", "=", "self", ".", "db", ".", "reference", "[", "genre", "]", "points", "=", "self", ".", "db", ".", "points", "[", "genre", "]", "points", "*=", "found", "# Add bonus points if additional terms points to category", "if", "category_counter", "[", "category", "]", ">", "0", ":", "points", "+=", "1", "category_counter", "[", "category", "]", "+=", "points", "for", "tag", "in", "self", ".", "db", ".", "tags", ":", "found", "=", "self", ".", "contains_entity", "(", "tag", ",", "text", ")", "if", "found", ":", "category", "=", "self", ".", "db", ".", "reference", "[", "tag", "]", "if", "not", "counter", "[", "category", "]", ":", "counter", "[", "category", "]", "+=", "found", "points", "=", "self", ".", "db", ".", "points", "[", "tag", "]", "points", "*=", "found", "category_counter", "[", "category", "]", "+=", "points", "if", "not", "category_counter", ":", "return", "genres", "main_category", "=", "category_counter", ".", "most_common", "(", "1", ")", "[", "0", "]", "[", "0", "]", "# Convert counter to a flat list of genres, sorted by count", "sorted_genres", "=", "[", "ite", "for", "ite", ",", "it", "in", "counter", ".", "most_common", "(", ")", "]", "for", "genre", "in", "sorted_genres", ":", "insert", "=", "True", "if", "self", ".", "unique_category", ":", "if", "not", "self", ".", "db", ".", "reference", "[", "genre", "]", "==", "main_category", ":", "insert", "=", "False", "if", "insert", ":", "genres", ".", "append", "(", "genre", ")", "return", "genres" ]
Return a list of genres found in text.
[ "Return", "a", "list", "of", "genres", "found", "in", "text", "." ]
4bbc90f7c2c527631380c08b4d99a4e40abed955
https://github.com/marteinn/genres/blob/4bbc90f7c2c527631380c08b4d99a4e40abed955/genres/finder.py#L22-L78
251,245
marteinn/genres
genres/finder.py
Finder.contains_entity
def contains_entity(entity, text): """ Attempt to try entity, return false if not found. Otherwise the amount of time entitu is occuring. """ try: entity = re.escape(entity) entity = entity.replace("\ ", "([^\w])?") pattern = "(\ |-|\\\|/|\.|,|^)%s(\ |\-|\\\|/|\.|,|$)" % entity found = len(re.findall(pattern, text, re.I | re.M)) except Exception as e: found = False return found
python
def contains_entity(entity, text): """ Attempt to try entity, return false if not found. Otherwise the amount of time entitu is occuring. """ try: entity = re.escape(entity) entity = entity.replace("\ ", "([^\w])?") pattern = "(\ |-|\\\|/|\.|,|^)%s(\ |\-|\\\|/|\.|,|$)" % entity found = len(re.findall(pattern, text, re.I | re.M)) except Exception as e: found = False return found
[ "def", "contains_entity", "(", "entity", ",", "text", ")", ":", "try", ":", "entity", "=", "re", ".", "escape", "(", "entity", ")", "entity", "=", "entity", ".", "replace", "(", "\"\\ \"", ",", "\"([^\\w])?\"", ")", "pattern", "=", "\"(\\ |-|\\\\\\|/|\\.|,|^)%s(\\ |\\-|\\\\\\|/|\\.|,|$)\"", "%", "entity", "found", "=", "len", "(", "re", ".", "findall", "(", "pattern", ",", "text", ",", "re", ".", "I", "|", "re", ".", "M", ")", ")", "except", "Exception", "as", "e", ":", "found", "=", "False", "return", "found" ]
Attempt to try entity, return false if not found. Otherwise the amount of time entitu is occuring.
[ "Attempt", "to", "try", "entity", "return", "false", "if", "not", "found", ".", "Otherwise", "the", "amount", "of", "time", "entitu", "is", "occuring", "." ]
4bbc90f7c2c527631380c08b4d99a4e40abed955
https://github.com/marteinn/genres/blob/4bbc90f7c2c527631380c08b4d99a4e40abed955/genres/finder.py#L81-L95
251,246
cirruscluster/cirruscluster
cirruscluster/ext/ansible/utils/__init__.py
is_executable
def is_executable(path): '''is the given path executable?''' return (stat.S_IXUSR & os.stat(path)[stat.ST_MODE] or stat.S_IXGRP & os.stat(path)[stat.ST_MODE] or stat.S_IXOTH & os.stat(path)[stat.ST_MODE])
python
def is_executable(path): '''is the given path executable?''' return (stat.S_IXUSR & os.stat(path)[stat.ST_MODE] or stat.S_IXGRP & os.stat(path)[stat.ST_MODE] or stat.S_IXOTH & os.stat(path)[stat.ST_MODE])
[ "def", "is_executable", "(", "path", ")", ":", "return", "(", "stat", ".", "S_IXUSR", "&", "os", ".", "stat", "(", "path", ")", "[", "stat", ".", "ST_MODE", "]", "or", "stat", ".", "S_IXGRP", "&", "os", ".", "stat", "(", "path", ")", "[", "stat", ".", "ST_MODE", "]", "or", "stat", ".", "S_IXOTH", "&", "os", ".", "stat", "(", "path", ")", "[", "stat", ".", "ST_MODE", "]", ")" ]
is the given path executable?
[ "is", "the", "given", "path", "executable?" ]
977409929dd81322d886425cdced10608117d5d7
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/utils/__init__.py#L159-L163
251,247
cirruscluster/cirruscluster
cirruscluster/ext/ansible/utils/__init__.py
prepare_writeable_dir
def prepare_writeable_dir(tree): ''' make sure a directory exists and is writeable ''' if tree != '/': tree = os.path.realpath(os.path.expanduser(tree)) if not os.path.exists(tree): try: os.makedirs(tree) except (IOError, OSError), e: exit("Could not make dir %s: %s" % (tree, e)) if not os.access(tree, os.W_OK): exit("Cannot write to path %s" % tree)
python
def prepare_writeable_dir(tree): ''' make sure a directory exists and is writeable ''' if tree != '/': tree = os.path.realpath(os.path.expanduser(tree)) if not os.path.exists(tree): try: os.makedirs(tree) except (IOError, OSError), e: exit("Could not make dir %s: %s" % (tree, e)) if not os.access(tree, os.W_OK): exit("Cannot write to path %s" % tree)
[ "def", "prepare_writeable_dir", "(", "tree", ")", ":", "if", "tree", "!=", "'/'", ":", "tree", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "expanduser", "(", "tree", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "tree", ")", ":", "try", ":", "os", ".", "makedirs", "(", "tree", ")", "except", "(", "IOError", ",", "OSError", ")", ",", "e", ":", "exit", "(", "\"Could not make dir %s: %s\"", "%", "(", "tree", ",", "e", ")", ")", "if", "not", "os", ".", "access", "(", "tree", ",", "os", ".", "W_OK", ")", ":", "exit", "(", "\"Cannot write to path %s\"", "%", "tree", ")" ]
make sure a directory exists and is writeable
[ "make", "sure", "a", "directory", "exists", "and", "is", "writeable" ]
977409929dd81322d886425cdced10608117d5d7
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/utils/__init__.py#L165-L176
251,248
cirruscluster/cirruscluster
cirruscluster/ext/ansible/utils/__init__.py
path_dwim
def path_dwim(basedir, given): ''' make relative paths work like folks expect. ''' if given.startswith("/"): return given elif given.startswith("~/"): return os.path.expanduser(given) else: return os.path.join(basedir, given)
python
def path_dwim(basedir, given): ''' make relative paths work like folks expect. ''' if given.startswith("/"): return given elif given.startswith("~/"): return os.path.expanduser(given) else: return os.path.join(basedir, given)
[ "def", "path_dwim", "(", "basedir", ",", "given", ")", ":", "if", "given", ".", "startswith", "(", "\"/\"", ")", ":", "return", "given", "elif", "given", ".", "startswith", "(", "\"~/\"", ")", ":", "return", "os", ".", "path", ".", "expanduser", "(", "given", ")", "else", ":", "return", "os", ".", "path", ".", "join", "(", "basedir", ",", "given", ")" ]
make relative paths work like folks expect.
[ "make", "relative", "paths", "work", "like", "folks", "expect", "." ]
977409929dd81322d886425cdced10608117d5d7
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/utils/__init__.py#L178-L188
251,249
cirruscluster/cirruscluster
cirruscluster/ext/ansible/utils/__init__.py
parse_json
def parse_json(raw_data): ''' this version for module return data only ''' orig_data = raw_data # ignore stuff like tcgetattr spewage or other warnings data = filter_leading_non_json_lines(raw_data) try: return json.loads(data) except: # not JSON, but try "Baby JSON" which allows many of our modules to not # require JSON and makes writing modules in bash much simpler results = {} try: tokens = shlex.split(data) except: print "failed to parse json: "+ data raise for t in tokens: if t.find("=") == -1: raise errors.AnsibleError("failed to parse: %s" % orig_data) (key,value) = t.split("=", 1) if key == 'changed' or 'failed': if value.lower() in [ 'true', '1' ]: value = True elif value.lower() in [ 'false', '0' ]: value = False if key == 'rc': value = int(value) results[key] = value if len(results.keys()) == 0: return { "failed" : True, "parsed" : False, "msg" : orig_data } return results
python
def parse_json(raw_data): ''' this version for module return data only ''' orig_data = raw_data # ignore stuff like tcgetattr spewage or other warnings data = filter_leading_non_json_lines(raw_data) try: return json.loads(data) except: # not JSON, but try "Baby JSON" which allows many of our modules to not # require JSON and makes writing modules in bash much simpler results = {} try: tokens = shlex.split(data) except: print "failed to parse json: "+ data raise for t in tokens: if t.find("=") == -1: raise errors.AnsibleError("failed to parse: %s" % orig_data) (key,value) = t.split("=", 1) if key == 'changed' or 'failed': if value.lower() in [ 'true', '1' ]: value = True elif value.lower() in [ 'false', '0' ]: value = False if key == 'rc': value = int(value) results[key] = value if len(results.keys()) == 0: return { "failed" : True, "parsed" : False, "msg" : orig_data } return results
[ "def", "parse_json", "(", "raw_data", ")", ":", "orig_data", "=", "raw_data", "# ignore stuff like tcgetattr spewage or other warnings", "data", "=", "filter_leading_non_json_lines", "(", "raw_data", ")", "try", ":", "return", "json", ".", "loads", "(", "data", ")", "except", ":", "# not JSON, but try \"Baby JSON\" which allows many of our modules to not", "# require JSON and makes writing modules in bash much simpler", "results", "=", "{", "}", "try", ":", "tokens", "=", "shlex", ".", "split", "(", "data", ")", "except", ":", "print", "\"failed to parse json: \"", "+", "data", "raise", "for", "t", "in", "tokens", ":", "if", "t", ".", "find", "(", "\"=\"", ")", "==", "-", "1", ":", "raise", "errors", ".", "AnsibleError", "(", "\"failed to parse: %s\"", "%", "orig_data", ")", "(", "key", ",", "value", ")", "=", "t", ".", "split", "(", "\"=\"", ",", "1", ")", "if", "key", "==", "'changed'", "or", "'failed'", ":", "if", "value", ".", "lower", "(", ")", "in", "[", "'true'", ",", "'1'", "]", ":", "value", "=", "True", "elif", "value", ".", "lower", "(", ")", "in", "[", "'false'", ",", "'0'", "]", ":", "value", "=", "False", "if", "key", "==", "'rc'", ":", "value", "=", "int", "(", "value", ")", "results", "[", "key", "]", "=", "value", "if", "len", "(", "results", ".", "keys", "(", ")", ")", "==", "0", ":", "return", "{", "\"failed\"", ":", "True", ",", "\"parsed\"", ":", "False", ",", "\"msg\"", ":", "orig_data", "}", "return", "results" ]
this version for module return data only
[ "this", "version", "for", "module", "return", "data", "only" ]
977409929dd81322d886425cdced10608117d5d7
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/utils/__init__.py#L195-L229
251,250
cirruscluster/cirruscluster
cirruscluster/ext/ansible/utils/__init__.py
md5
def md5(filename): ''' Return MD5 hex digest of local file, or None if file is not present. ''' if not os.path.exists(filename): return None digest = _md5() blocksize = 64 * 1024 infile = open(filename, 'rb') block = infile.read(blocksize) while block: digest.update(block) block = infile.read(blocksize) infile.close() return digest.hexdigest()
python
def md5(filename): ''' Return MD5 hex digest of local file, or None if file is not present. ''' if not os.path.exists(filename): return None digest = _md5() blocksize = 64 * 1024 infile = open(filename, 'rb') block = infile.read(blocksize) while block: digest.update(block) block = infile.read(blocksize) infile.close() return digest.hexdigest()
[ "def", "md5", "(", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "return", "None", "digest", "=", "_md5", "(", ")", "blocksize", "=", "64", "*", "1024", "infile", "=", "open", "(", "filename", ",", "'rb'", ")", "block", "=", "infile", ".", "read", "(", "blocksize", ")", "while", "block", ":", "digest", ".", "update", "(", "block", ")", "block", "=", "infile", ".", "read", "(", "blocksize", ")", "infile", ".", "close", "(", ")", "return", "digest", ".", "hexdigest", "(", ")" ]
Return MD5 hex digest of local file, or None if file is not present.
[ "Return", "MD5", "hex", "digest", "of", "local", "file", "or", "None", "if", "file", "is", "not", "present", "." ]
977409929dd81322d886425cdced10608117d5d7
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/utils/__init__.py#L304-L317
251,251
cirruscluster/cirruscluster
cirruscluster/ext/ansible/utils/__init__.py
_gitinfo
def _gitinfo(): ''' returns a string containing git branch, commit id and commit date ''' result = None repo_path = os.path.join(os.path.dirname(__file__), '..', '..', '..', '.git') if os.path.exists(repo_path): # Check if the .git is a file. If it is a file, it means that we are in a submodule structure. if os.path.isfile(repo_path): try: gitdir = yaml.load(open(repo_path)).get('gitdir') # There is a posibility the .git file to have an absolute path. if os.path.isabs(gitdir): repo_path = gitdir else: repo_path = os.path.join(repo_path.split('.git')[0], gitdir) except (IOError, AttributeError): return '' f = open(os.path.join(repo_path, "HEAD")) branch = f.readline().split('/')[-1].rstrip("\n") f.close() branch_path = os.path.join(repo_path, "refs", "heads", branch) if os.path.exists(branch_path): f = open(branch_path) commit = f.readline()[:10] f.close() date = time.localtime(os.stat(branch_path).st_mtime) if time.daylight == 0: offset = time.timezone else: offset = time.altzone result = "({0} {1}) last updated {2} (GMT {3:+04d})".format(branch, commit, time.strftime("%Y/%m/%d %H:%M:%S", date), offset / -36) else: result = '' return result
python
def _gitinfo(): ''' returns a string containing git branch, commit id and commit date ''' result = None repo_path = os.path.join(os.path.dirname(__file__), '..', '..', '..', '.git') if os.path.exists(repo_path): # Check if the .git is a file. If it is a file, it means that we are in a submodule structure. if os.path.isfile(repo_path): try: gitdir = yaml.load(open(repo_path)).get('gitdir') # There is a posibility the .git file to have an absolute path. if os.path.isabs(gitdir): repo_path = gitdir else: repo_path = os.path.join(repo_path.split('.git')[0], gitdir) except (IOError, AttributeError): return '' f = open(os.path.join(repo_path, "HEAD")) branch = f.readline().split('/')[-1].rstrip("\n") f.close() branch_path = os.path.join(repo_path, "refs", "heads", branch) if os.path.exists(branch_path): f = open(branch_path) commit = f.readline()[:10] f.close() date = time.localtime(os.stat(branch_path).st_mtime) if time.daylight == 0: offset = time.timezone else: offset = time.altzone result = "({0} {1}) last updated {2} (GMT {3:+04d})".format(branch, commit, time.strftime("%Y/%m/%d %H:%M:%S", date), offset / -36) else: result = '' return result
[ "def", "_gitinfo", "(", ")", ":", "result", "=", "None", "repo_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'..'", ",", "'..'", ",", "'..'", ",", "'.git'", ")", "if", "os", ".", "path", ".", "exists", "(", "repo_path", ")", ":", "# Check if the .git is a file. If it is a file, it means that we are in a submodule structure.", "if", "os", ".", "path", ".", "isfile", "(", "repo_path", ")", ":", "try", ":", "gitdir", "=", "yaml", ".", "load", "(", "open", "(", "repo_path", ")", ")", ".", "get", "(", "'gitdir'", ")", "# There is a posibility the .git file to have an absolute path.", "if", "os", ".", "path", ".", "isabs", "(", "gitdir", ")", ":", "repo_path", "=", "gitdir", "else", ":", "repo_path", "=", "os", ".", "path", ".", "join", "(", "repo_path", ".", "split", "(", "'.git'", ")", "[", "0", "]", ",", "gitdir", ")", "except", "(", "IOError", ",", "AttributeError", ")", ":", "return", "''", "f", "=", "open", "(", "os", ".", "path", ".", "join", "(", "repo_path", ",", "\"HEAD\"", ")", ")", "branch", "=", "f", ".", "readline", "(", ")", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", ".", "rstrip", "(", "\"\\n\"", ")", "f", ".", "close", "(", ")", "branch_path", "=", "os", ".", "path", ".", "join", "(", "repo_path", ",", "\"refs\"", ",", "\"heads\"", ",", "branch", ")", "if", "os", ".", "path", ".", "exists", "(", "branch_path", ")", ":", "f", "=", "open", "(", "branch_path", ")", "commit", "=", "f", ".", "readline", "(", ")", "[", ":", "10", "]", "f", ".", "close", "(", ")", "date", "=", "time", ".", "localtime", "(", "os", ".", "stat", "(", "branch_path", ")", ".", "st_mtime", ")", "if", "time", ".", "daylight", "==", "0", ":", "offset", "=", "time", ".", "timezone", "else", ":", "offset", "=", "time", ".", "altzone", "result", "=", "\"({0} {1}) last updated {2} (GMT {3:+04d})\"", ".", "format", "(", "branch", ",", "commit", ",", "time", ".", "strftime", "(", "\"%Y/%m/%d %H:%M:%S\"", ",", "date", ")", ",", "offset", "/", "-", "36", ")", "else", ":", "result", "=", "''", "return", "result" ]
returns a string containing git branch, commit id and commit date
[ "returns", "a", "string", "containing", "git", "branch", "commit", "id", "and", "commit", "date" ]
977409929dd81322d886425cdced10608117d5d7
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/utils/__init__.py#L325-L359
251,252
cirruscluster/cirruscluster
cirruscluster/ext/ansible/utils/__init__.py
compile_when_to_only_if
def compile_when_to_only_if(expression): ''' when is a shorthand for writing only_if conditionals. It requires less quoting magic. only_if is retained for backwards compatibility. ''' # when: set $variable # when: unset $variable # when: failed $json_result # when: changed $json_result # when: int $x >= $z and $y < 3 # when: int $x in $alist # when: float $x > 2 and $y <= $z # when: str $x != $y if type(expression) not in [ str, unicode ]: raise errors.AnsibleError("invalid usage of when_ operator: %s" % expression) tokens = expression.split() if len(tokens) < 2: raise errors.AnsibleError("invalid usage of when_ operator: %s" % expression) # when_set / when_unset if tokens[0] in [ 'set', 'unset' ]: tcopy = tokens[1:] for (i,t) in enumerate(tokens[1:]): if t.find("$") != -1: tcopy[i] = "is_%s('''%s''')" % (tokens[0], t) else: tcopy[i] = t return " ".join(tcopy) # when_failed / when_changed elif tokens[0] in [ 'failed', 'changed' ]: tcopy = tokens[1:] for (i,t) in enumerate(tokens[1:]): if t.find("$") != -1: tcopy[i] = "is_%s(%s)" % (tokens[0], t) else: tcopy[i] = t return " ".join(tcopy) # when_integer / when_float / when_string elif tokens[0] in [ 'integer', 'float', 'string' ]: cast = None if tokens[0] == 'integer': cast = 'int' elif tokens[0] == 'string': cast = 'str' elif tokens[0] == 'float': cast = 'float' tcopy = tokens[1:] for (i,t) in enumerate(tokens[1:]): if t.find("$") != -1: # final variable substitution will happen in Runner code tcopy[i] = "%s('''%s''')" % (cast, t) else: tcopy[i] = t return " ".join(tcopy) # when_boolean elif tokens[0] in [ 'bool', 'boolean' ]: tcopy = tokens[1:] for (i, t) in enumerate(tcopy): if t.find("$") != -1: tcopy[i] = "(is_set('''%s''') and '''%s'''.lower() not in ('false', 'no', 'n', 'none', '0', ''))" % (t, t) return " ".join(tcopy) else: raise errors.AnsibleError("invalid usage of when_ operator: %s" % expression)
python
def compile_when_to_only_if(expression): ''' when is a shorthand for writing only_if conditionals. It requires less quoting magic. only_if is retained for backwards compatibility. ''' # when: set $variable # when: unset $variable # when: failed $json_result # when: changed $json_result # when: int $x >= $z and $y < 3 # when: int $x in $alist # when: float $x > 2 and $y <= $z # when: str $x != $y if type(expression) not in [ str, unicode ]: raise errors.AnsibleError("invalid usage of when_ operator: %s" % expression) tokens = expression.split() if len(tokens) < 2: raise errors.AnsibleError("invalid usage of when_ operator: %s" % expression) # when_set / when_unset if tokens[0] in [ 'set', 'unset' ]: tcopy = tokens[1:] for (i,t) in enumerate(tokens[1:]): if t.find("$") != -1: tcopy[i] = "is_%s('''%s''')" % (tokens[0], t) else: tcopy[i] = t return " ".join(tcopy) # when_failed / when_changed elif tokens[0] in [ 'failed', 'changed' ]: tcopy = tokens[1:] for (i,t) in enumerate(tokens[1:]): if t.find("$") != -1: tcopy[i] = "is_%s(%s)" % (tokens[0], t) else: tcopy[i] = t return " ".join(tcopy) # when_integer / when_float / when_string elif tokens[0] in [ 'integer', 'float', 'string' ]: cast = None if tokens[0] == 'integer': cast = 'int' elif tokens[0] == 'string': cast = 'str' elif tokens[0] == 'float': cast = 'float' tcopy = tokens[1:] for (i,t) in enumerate(tokens[1:]): if t.find("$") != -1: # final variable substitution will happen in Runner code tcopy[i] = "%s('''%s''')" % (cast, t) else: tcopy[i] = t return " ".join(tcopy) # when_boolean elif tokens[0] in [ 'bool', 'boolean' ]: tcopy = tokens[1:] for (i, t) in enumerate(tcopy): if t.find("$") != -1: tcopy[i] = "(is_set('''%s''') and '''%s'''.lower() not in ('false', 'no', 'n', 'none', '0', ''))" % (t, t) return " ".join(tcopy) else: raise errors.AnsibleError("invalid usage of when_ operator: %s" % expression)
[ "def", "compile_when_to_only_if", "(", "expression", ")", ":", "# when: set $variable", "# when: unset $variable", "# when: failed $json_result", "# when: changed $json_result", "# when: int $x >= $z and $y < 3", "# when: int $x in $alist", "# when: float $x > 2 and $y <= $z", "# when: str $x != $y", "if", "type", "(", "expression", ")", "not", "in", "[", "str", ",", "unicode", "]", ":", "raise", "errors", ".", "AnsibleError", "(", "\"invalid usage of when_ operator: %s\"", "%", "expression", ")", "tokens", "=", "expression", ".", "split", "(", ")", "if", "len", "(", "tokens", ")", "<", "2", ":", "raise", "errors", ".", "AnsibleError", "(", "\"invalid usage of when_ operator: %s\"", "%", "expression", ")", "# when_set / when_unset", "if", "tokens", "[", "0", "]", "in", "[", "'set'", ",", "'unset'", "]", ":", "tcopy", "=", "tokens", "[", "1", ":", "]", "for", "(", "i", ",", "t", ")", "in", "enumerate", "(", "tokens", "[", "1", ":", "]", ")", ":", "if", "t", ".", "find", "(", "\"$\"", ")", "!=", "-", "1", ":", "tcopy", "[", "i", "]", "=", "\"is_%s('''%s''')\"", "%", "(", "tokens", "[", "0", "]", ",", "t", ")", "else", ":", "tcopy", "[", "i", "]", "=", "t", "return", "\" \"", ".", "join", "(", "tcopy", ")", "# when_failed / when_changed", "elif", "tokens", "[", "0", "]", "in", "[", "'failed'", ",", "'changed'", "]", ":", "tcopy", "=", "tokens", "[", "1", ":", "]", "for", "(", "i", ",", "t", ")", "in", "enumerate", "(", "tokens", "[", "1", ":", "]", ")", ":", "if", "t", ".", "find", "(", "\"$\"", ")", "!=", "-", "1", ":", "tcopy", "[", "i", "]", "=", "\"is_%s(%s)\"", "%", "(", "tokens", "[", "0", "]", ",", "t", ")", "else", ":", "tcopy", "[", "i", "]", "=", "t", "return", "\" \"", ".", "join", "(", "tcopy", ")", "# when_integer / when_float / when_string", "elif", "tokens", "[", "0", "]", "in", "[", "'integer'", ",", "'float'", ",", "'string'", "]", ":", "cast", "=", "None", "if", "tokens", "[", "0", "]", "==", "'integer'", ":", "cast", "=", "'int'", "elif", "tokens", "[", "0", "]", "==", "'string'", ":", "cast", "=", "'str'", "elif", "tokens", "[", "0", "]", "==", "'float'", ":", "cast", "=", "'float'", "tcopy", "=", "tokens", "[", "1", ":", "]", "for", "(", "i", ",", "t", ")", "in", "enumerate", "(", "tokens", "[", "1", ":", "]", ")", ":", "if", "t", ".", "find", "(", "\"$\"", ")", "!=", "-", "1", ":", "# final variable substitution will happen in Runner code", "tcopy", "[", "i", "]", "=", "\"%s('''%s''')\"", "%", "(", "cast", ",", "t", ")", "else", ":", "tcopy", "[", "i", "]", "=", "t", "return", "\" \"", ".", "join", "(", "tcopy", ")", "# when_boolean", "elif", "tokens", "[", "0", "]", "in", "[", "'bool'", ",", "'boolean'", "]", ":", "tcopy", "=", "tokens", "[", "1", ":", "]", "for", "(", "i", ",", "t", ")", "in", "enumerate", "(", "tcopy", ")", ":", "if", "t", ".", "find", "(", "\"$\"", ")", "!=", "-", "1", ":", "tcopy", "[", "i", "]", "=", "\"(is_set('''%s''') and '''%s'''.lower() not in ('false', 'no', 'n', 'none', '0', ''))\"", "%", "(", "t", ",", "t", ")", "return", "\" \"", ".", "join", "(", "tcopy", ")", "else", ":", "raise", "errors", ".", "AnsibleError", "(", "\"invalid usage of when_ operator: %s\"", "%", "expression", ")" ]
when is a shorthand for writing only_if conditionals. It requires less quoting magic. only_if is retained for backwards compatibility.
[ "when", "is", "a", "shorthand", "for", "writing", "only_if", "conditionals", ".", "It", "requires", "less", "quoting", "magic", ".", "only_if", "is", "retained", "for", "backwards", "compatibility", "." ]
977409929dd81322d886425cdced10608117d5d7
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/utils/__init__.py#L506-L578
251,253
cirruscluster/cirruscluster
cirruscluster/ext/ansible/utils/__init__.py
make_sudo_cmd
def make_sudo_cmd(sudo_user, executable, cmd): """ helper function for connection plugins to create sudo commands """ # Rather than detect if sudo wants a password this time, -k makes # sudo always ask for a password if one is required. # Passing a quoted compound command to sudo (or sudo -s) # directly doesn't work, so we shellquote it with pipes.quote() # and pass the quoted string to the user's shell. We loop reading # output until we see the randomly-generated sudo prompt set with # the -p option. randbits = ''.join(chr(random.randint(ord('a'), ord('z'))) for x in xrange(32)) prompt = '[sudo via ansible, key=%s] password: ' % randbits sudocmd = '%s -k && %s %s -S -p "%s" -u %s %s -c %s' % ( C.DEFAULT_SUDO_EXE, C.DEFAULT_SUDO_EXE, C.DEFAULT_SUDO_FLAGS, prompt, sudo_user, executable or '$SHELL', pipes.quote(cmd)) return ('/bin/sh -c ' + pipes.quote(sudocmd), prompt)
python
def make_sudo_cmd(sudo_user, executable, cmd): """ helper function for connection plugins to create sudo commands """ # Rather than detect if sudo wants a password this time, -k makes # sudo always ask for a password if one is required. # Passing a quoted compound command to sudo (or sudo -s) # directly doesn't work, so we shellquote it with pipes.quote() # and pass the quoted string to the user's shell. We loop reading # output until we see the randomly-generated sudo prompt set with # the -p option. randbits = ''.join(chr(random.randint(ord('a'), ord('z'))) for x in xrange(32)) prompt = '[sudo via ansible, key=%s] password: ' % randbits sudocmd = '%s -k && %s %s -S -p "%s" -u %s %s -c %s' % ( C.DEFAULT_SUDO_EXE, C.DEFAULT_SUDO_EXE, C.DEFAULT_SUDO_FLAGS, prompt, sudo_user, executable or '$SHELL', pipes.quote(cmd)) return ('/bin/sh -c ' + pipes.quote(sudocmd), prompt)
[ "def", "make_sudo_cmd", "(", "sudo_user", ",", "executable", ",", "cmd", ")", ":", "# Rather than detect if sudo wants a password this time, -k makes", "# sudo always ask for a password if one is required.", "# Passing a quoted compound command to sudo (or sudo -s)", "# directly doesn't work, so we shellquote it with pipes.quote()", "# and pass the quoted string to the user's shell. We loop reading", "# output until we see the randomly-generated sudo prompt set with", "# the -p option.", "randbits", "=", "''", ".", "join", "(", "chr", "(", "random", ".", "randint", "(", "ord", "(", "'a'", ")", ",", "ord", "(", "'z'", ")", ")", ")", "for", "x", "in", "xrange", "(", "32", ")", ")", "prompt", "=", "'[sudo via ansible, key=%s] password: '", "%", "randbits", "sudocmd", "=", "'%s -k && %s %s -S -p \"%s\" -u %s %s -c %s'", "%", "(", "C", ".", "DEFAULT_SUDO_EXE", ",", "C", ".", "DEFAULT_SUDO_EXE", ",", "C", ".", "DEFAULT_SUDO_FLAGS", ",", "prompt", ",", "sudo_user", ",", "executable", "or", "'$SHELL'", ",", "pipes", ".", "quote", "(", "cmd", ")", ")", "return", "(", "'/bin/sh -c '", "+", "pipes", ".", "quote", "(", "sudocmd", ")", ",", "prompt", ")" ]
helper function for connection plugins to create sudo commands
[ "helper", "function", "for", "connection", "plugins", "to", "create", "sudo", "commands" ]
977409929dd81322d886425cdced10608117d5d7
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/utils/__init__.py#L580-L596
251,254
jmgilman/Neolib
neolib/user/User.py
User.login
def login(self): """ Logs the user in, returns the result Returns bool - Whether or not the user logged in successfully """ # Request index to obtain initial cookies and look more human pg = self.getPage("http://www.neopets.com") form = pg.form(action="/login.phtml") form.update({'username': self.username, 'password': self.password}) pg = form.submit() logging.getLogger("neolib.user").info("Login check", {'pg': pg}) return self.username in pg.content
python
def login(self): """ Logs the user in, returns the result Returns bool - Whether or not the user logged in successfully """ # Request index to obtain initial cookies and look more human pg = self.getPage("http://www.neopets.com") form = pg.form(action="/login.phtml") form.update({'username': self.username, 'password': self.password}) pg = form.submit() logging.getLogger("neolib.user").info("Login check", {'pg': pg}) return self.username in pg.content
[ "def", "login", "(", "self", ")", ":", "# Request index to obtain initial cookies and look more human", "pg", "=", "self", ".", "getPage", "(", "\"http://www.neopets.com\"", ")", "form", "=", "pg", ".", "form", "(", "action", "=", "\"/login.phtml\"", ")", "form", ".", "update", "(", "{", "'username'", ":", "self", ".", "username", ",", "'password'", ":", "self", ".", "password", "}", ")", "pg", "=", "form", ".", "submit", "(", ")", "logging", ".", "getLogger", "(", "\"neolib.user\"", ")", ".", "info", "(", "\"Login check\"", ",", "{", "'pg'", ":", "pg", "}", ")", "return", "self", ".", "username", "in", "pg", ".", "content" ]
Logs the user in, returns the result Returns bool - Whether or not the user logged in successfully
[ "Logs", "the", "user", "in", "returns", "the", "result", "Returns", "bool", "-", "Whether", "or", "not", "the", "user", "logged", "in", "successfully" ]
228fafeaed0f3195676137732384a14820ae285c
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/user/User.py#L158-L173
251,255
jmgilman/Neolib
neolib/user/User.py
User.sync
def sync(self, browser): """ Enables cookie synchronization with specified browser, returns result Returns bool - True if successful, false otherwise """ BrowserCookies.loadBrowsers() if not browser in BrowserCookies.browsers: return False self.browserSync = True self.browser = browser return True
python
def sync(self, browser): """ Enables cookie synchronization with specified browser, returns result Returns bool - True if successful, false otherwise """ BrowserCookies.loadBrowsers() if not browser in BrowserCookies.browsers: return False self.browserSync = True self.browser = browser return True
[ "def", "sync", "(", "self", ",", "browser", ")", ":", "BrowserCookies", ".", "loadBrowsers", "(", ")", "if", "not", "browser", "in", "BrowserCookies", ".", "browsers", ":", "return", "False", "self", ".", "browserSync", "=", "True", "self", ".", "browser", "=", "browser", "return", "True" ]
Enables cookie synchronization with specified browser, returns result Returns bool - True if successful, false otherwise
[ "Enables", "cookie", "synchronization", "with", "specified", "browser", "returns", "result", "Returns", "bool", "-", "True", "if", "successful", "false", "otherwise" ]
228fafeaed0f3195676137732384a14820ae285c
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/user/User.py#L185-L197
251,256
jmgilman/Neolib
neolib/user/User.py
User.save
def save(self): """ Exports all user attributes to the user's configuration and writes configuration Saves the values for each attribute stored in User.configVars into the user's configuration. The password is automatically encoded and salted to prevent saving it as plaintext. The session is pickled, encoded, and compressed to take up less space in the configuration file. All other attributes are saved in plain text. Writes the changes to the configuration file. """ # Code to load all attributes for prop in dir(self): if getattr(self, prop) == None: continue if not prop in self.configVars: continue # Special handling for some attributes if prop == "session": pic = pickle.dumps(getattr(self, prop).cookies) comp = zlib.compress(pic) enc = base64.b64encode(comp) self.config[prop] = enc.decode() continue if prop == "password" and not self.savePassword: continue if prop == "password": s = hashlib.md5(self.username.encode()).hexdigest() p = base64.b64encode(getattr(self, prop).encode()) + s.encode() self.config[prop] = p.decode() continue self.config[prop] = str(getattr(self, prop)) if 'password' in self.config and not self.savePassword: del self.config.password self.config.write() self.__loadConfig()
python
def save(self): """ Exports all user attributes to the user's configuration and writes configuration Saves the values for each attribute stored in User.configVars into the user's configuration. The password is automatically encoded and salted to prevent saving it as plaintext. The session is pickled, encoded, and compressed to take up less space in the configuration file. All other attributes are saved in plain text. Writes the changes to the configuration file. """ # Code to load all attributes for prop in dir(self): if getattr(self, prop) == None: continue if not prop in self.configVars: continue # Special handling for some attributes if prop == "session": pic = pickle.dumps(getattr(self, prop).cookies) comp = zlib.compress(pic) enc = base64.b64encode(comp) self.config[prop] = enc.decode() continue if prop == "password" and not self.savePassword: continue if prop == "password": s = hashlib.md5(self.username.encode()).hexdigest() p = base64.b64encode(getattr(self, prop).encode()) + s.encode() self.config[prop] = p.decode() continue self.config[prop] = str(getattr(self, prop)) if 'password' in self.config and not self.savePassword: del self.config.password self.config.write() self.__loadConfig()
[ "def", "save", "(", "self", ")", ":", "# Code to load all attributes", "for", "prop", "in", "dir", "(", "self", ")", ":", "if", "getattr", "(", "self", ",", "prop", ")", "==", "None", ":", "continue", "if", "not", "prop", "in", "self", ".", "configVars", ":", "continue", "# Special handling for some attributes", "if", "prop", "==", "\"session\"", ":", "pic", "=", "pickle", ".", "dumps", "(", "getattr", "(", "self", ",", "prop", ")", ".", "cookies", ")", "comp", "=", "zlib", ".", "compress", "(", "pic", ")", "enc", "=", "base64", ".", "b64encode", "(", "comp", ")", "self", ".", "config", "[", "prop", "]", "=", "enc", ".", "decode", "(", ")", "continue", "if", "prop", "==", "\"password\"", "and", "not", "self", ".", "savePassword", ":", "continue", "if", "prop", "==", "\"password\"", ":", "s", "=", "hashlib", ".", "md5", "(", "self", ".", "username", ".", "encode", "(", ")", ")", ".", "hexdigest", "(", ")", "p", "=", "base64", ".", "b64encode", "(", "getattr", "(", "self", ",", "prop", ")", ".", "encode", "(", ")", ")", "+", "s", ".", "encode", "(", ")", "self", ".", "config", "[", "prop", "]", "=", "p", ".", "decode", "(", ")", "continue", "self", ".", "config", "[", "prop", "]", "=", "str", "(", "getattr", "(", "self", ",", "prop", ")", ")", "if", "'password'", "in", "self", ".", "config", "and", "not", "self", ".", "savePassword", ":", "del", "self", ".", "config", ".", "password", "self", ".", "config", ".", "write", "(", ")", "self", ".", "__loadConfig", "(", ")" ]
Exports all user attributes to the user's configuration and writes configuration Saves the values for each attribute stored in User.configVars into the user's configuration. The password is automatically encoded and salted to prevent saving it as plaintext. The session is pickled, encoded, and compressed to take up less space in the configuration file. All other attributes are saved in plain text. Writes the changes to the configuration file.
[ "Exports", "all", "user", "attributes", "to", "the", "user", "s", "configuration", "and", "writes", "configuration", "Saves", "the", "values", "for", "each", "attribute", "stored", "in", "User", ".", "configVars", "into", "the", "user", "s", "configuration", ".", "The", "password", "is", "automatically", "encoded", "and", "salted", "to", "prevent", "saving", "it", "as", "plaintext", ".", "The", "session", "is", "pickled", "encoded", "and", "compressed", "to", "take", "up", "less", "space", "in", "the", "configuration", "file", ".", "All", "other", "attributes", "are", "saved", "in", "plain", "text", ".", "Writes", "the", "changes", "to", "the", "configuration", "file", "." ]
228fafeaed0f3195676137732384a14820ae285c
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/user/User.py#L204-L238
251,257
KnowledgeLinks/rdfframework
rdfframework/utilities/gitutilities.py
mod_git_ignore
def mod_git_ignore(directory, ignore_item, action): """ checks if an item is in the specified gitignore file and adds it if it is not in the file """ if not os.path.isdir(directory): return ignore_filepath = os.path.join(directory,".gitignore") if not os.path.exists(ignore_filepath): items = [] else: with open(ignore_filepath) as ig_file: items = ig_file.readlines() # strip and clean the lines clean_items = [line.strip("\n").strip() for line in items] clean_items = make_list(clean_items) if action == "add": if ignore_item not in clean_items: with open(ignore_filepath, "w") as ig_file: clean_items.append(ignore_item) ig_file.write("\n".join(clean_items) + "\n") elif action == "remove": with open(ignore_filepath, "w") as ig_file: for i, value in enumerate(clean_items): if value != ignore_item.lower(): ig_file.write(items[i])
python
def mod_git_ignore(directory, ignore_item, action): """ checks if an item is in the specified gitignore file and adds it if it is not in the file """ if not os.path.isdir(directory): return ignore_filepath = os.path.join(directory,".gitignore") if not os.path.exists(ignore_filepath): items = [] else: with open(ignore_filepath) as ig_file: items = ig_file.readlines() # strip and clean the lines clean_items = [line.strip("\n").strip() for line in items] clean_items = make_list(clean_items) if action == "add": if ignore_item not in clean_items: with open(ignore_filepath, "w") as ig_file: clean_items.append(ignore_item) ig_file.write("\n".join(clean_items) + "\n") elif action == "remove": with open(ignore_filepath, "w") as ig_file: for i, value in enumerate(clean_items): if value != ignore_item.lower(): ig_file.write(items[i])
[ "def", "mod_git_ignore", "(", "directory", ",", "ignore_item", ",", "action", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "directory", ")", ":", "return", "ignore_filepath", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "\".gitignore\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "ignore_filepath", ")", ":", "items", "=", "[", "]", "else", ":", "with", "open", "(", "ignore_filepath", ")", "as", "ig_file", ":", "items", "=", "ig_file", ".", "readlines", "(", ")", "# strip and clean the lines", "clean_items", "=", "[", "line", ".", "strip", "(", "\"\\n\"", ")", ".", "strip", "(", ")", "for", "line", "in", "items", "]", "clean_items", "=", "make_list", "(", "clean_items", ")", "if", "action", "==", "\"add\"", ":", "if", "ignore_item", "not", "in", "clean_items", ":", "with", "open", "(", "ignore_filepath", ",", "\"w\"", ")", "as", "ig_file", ":", "clean_items", ".", "append", "(", "ignore_item", ")", "ig_file", ".", "write", "(", "\"\\n\"", ".", "join", "(", "clean_items", ")", "+", "\"\\n\"", ")", "elif", "action", "==", "\"remove\"", ":", "with", "open", "(", "ignore_filepath", ",", "\"w\"", ")", "as", "ig_file", ":", "for", "i", ",", "value", "in", "enumerate", "(", "clean_items", ")", ":", "if", "value", "!=", "ignore_item", ".", "lower", "(", ")", ":", "ig_file", ".", "write", "(", "items", "[", "i", "]", ")" ]
checks if an item is in the specified gitignore file and adds it if it is not in the file
[ "checks", "if", "an", "item", "is", "in", "the", "specified", "gitignore", "file", "and", "adds", "it", "if", "it", "is", "not", "in", "the", "file" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/gitutilities.py#L3-L27
251,258
etcher-be/elib_run
elib_run/_run/_monitor_running_process.py
monitor_running_process
def monitor_running_process(context: RunContext): """ Runs an infinite loop that waits for the process to either exit on its or time out Captures all output from the running process :param context: run context :type context: RunContext """ while True: capture_output_from_running_process(context) if context.process_finished(): context.return_code = context.command.returncode break if context.process_timed_out(): context.return_code = -1 raise ProcessTimeoutError( exe_name=context.exe_short_name, timeout=context.timeout, )
python
def monitor_running_process(context: RunContext): """ Runs an infinite loop that waits for the process to either exit on its or time out Captures all output from the running process :param context: run context :type context: RunContext """ while True: capture_output_from_running_process(context) if context.process_finished(): context.return_code = context.command.returncode break if context.process_timed_out(): context.return_code = -1 raise ProcessTimeoutError( exe_name=context.exe_short_name, timeout=context.timeout, )
[ "def", "monitor_running_process", "(", "context", ":", "RunContext", ")", ":", "while", "True", ":", "capture_output_from_running_process", "(", "context", ")", "if", "context", ".", "process_finished", "(", ")", ":", "context", ".", "return_code", "=", "context", ".", "command", ".", "returncode", "break", "if", "context", ".", "process_timed_out", "(", ")", ":", "context", ".", "return_code", "=", "-", "1", "raise", "ProcessTimeoutError", "(", "exe_name", "=", "context", ".", "exe_short_name", ",", "timeout", "=", "context", ".", "timeout", ",", ")" ]
Runs an infinite loop that waits for the process to either exit on its or time out Captures all output from the running process :param context: run context :type context: RunContext
[ "Runs", "an", "infinite", "loop", "that", "waits", "for", "the", "process", "to", "either", "exit", "on", "its", "or", "time", "out" ]
c9d8ba9f067ab90c5baa27375a92b23f1b97cdde
https://github.com/etcher-be/elib_run/blob/c9d8ba9f067ab90c5baa27375a92b23f1b97cdde/elib_run/_run/_monitor_running_process.py#L12-L33
251,259
b3j0f/utils
b3j0f/utils/reflect.py
base_elts
def base_elts(elt, cls=None, depth=None): """Get bases elements of the input elt. - If elt is an instance, get class and all base classes. - If elt is a method, get all base methods. - If elt is a class, get all base classes. - In other case, get an empty list. :param elt: supposed inherited elt. :param cls: cls from where find attributes equal to elt. If None, it is found as much as possible. Required in python3 for function classes. :type cls: type or list :param int depth: search depth. If None (default), depth is maximal. :return: elt bases elements. if elt has not base elements, result is empty. :rtype: list """ result = [] elt_name = getattr(elt, '__name__', None) if elt_name is not None: cls = [] if cls is None else ensureiterable(cls) elt_is_class = False # if cls is None and elt is routine, it is possible to find the cls if not cls and isroutine(elt): if hasattr(elt, '__self__'): # from the instance instance = get_method_self(elt) # get instance if instance is None and PY2: # get base im_class if PY2 cls = list(elt.im_class.__bases__) else: # use instance class cls = [instance.__class__] # cls is elt if elt is a class elif isclass(elt): elt_is_class = True cls = list(elt.__bases__) if cls: # if cls is not empty, find all base classes index_of_found_classes = 0 # get last visited class index visited_classes = set(cls) # cache for visited classes len_classes = len(cls) if depth is None: # if depth is None, get maximal value depth = -1 # set negative value while depth != 0 and index_of_found_classes != len_classes: len_classes = len(cls) for index in range(index_of_found_classes, len_classes): _cls = cls[index] for base_cls in _cls.__bases__: if base_cls in visited_classes: continue else: visited_classes.add(base_cls) cls.append(base_cls) index_of_found_classes = len_classes depth -= 1 if elt_is_class: # if cls is elt, result is classes minus first class result = cls elif isroutine(elt): # get an elt to compare with found element if ismethod(elt): elt_to_compare = get_method_function(elt) else: elt_to_compare = elt for _cls in cls: # for all classes # get possible base elt b_elt = getattr(_cls, elt_name, None) if b_elt is not None: # compare funcs if ismethod(b_elt): bec = get_method_function(b_elt) else: bec = b_elt # if matching, add to result if bec is elt_to_compare: result.append(b_elt) return result
python
def base_elts(elt, cls=None, depth=None): """Get bases elements of the input elt. - If elt is an instance, get class and all base classes. - If elt is a method, get all base methods. - If elt is a class, get all base classes. - In other case, get an empty list. :param elt: supposed inherited elt. :param cls: cls from where find attributes equal to elt. If None, it is found as much as possible. Required in python3 for function classes. :type cls: type or list :param int depth: search depth. If None (default), depth is maximal. :return: elt bases elements. if elt has not base elements, result is empty. :rtype: list """ result = [] elt_name = getattr(elt, '__name__', None) if elt_name is not None: cls = [] if cls is None else ensureiterable(cls) elt_is_class = False # if cls is None and elt is routine, it is possible to find the cls if not cls and isroutine(elt): if hasattr(elt, '__self__'): # from the instance instance = get_method_self(elt) # get instance if instance is None and PY2: # get base im_class if PY2 cls = list(elt.im_class.__bases__) else: # use instance class cls = [instance.__class__] # cls is elt if elt is a class elif isclass(elt): elt_is_class = True cls = list(elt.__bases__) if cls: # if cls is not empty, find all base classes index_of_found_classes = 0 # get last visited class index visited_classes = set(cls) # cache for visited classes len_classes = len(cls) if depth is None: # if depth is None, get maximal value depth = -1 # set negative value while depth != 0 and index_of_found_classes != len_classes: len_classes = len(cls) for index in range(index_of_found_classes, len_classes): _cls = cls[index] for base_cls in _cls.__bases__: if base_cls in visited_classes: continue else: visited_classes.add(base_cls) cls.append(base_cls) index_of_found_classes = len_classes depth -= 1 if elt_is_class: # if cls is elt, result is classes minus first class result = cls elif isroutine(elt): # get an elt to compare with found element if ismethod(elt): elt_to_compare = get_method_function(elt) else: elt_to_compare = elt for _cls in cls: # for all classes # get possible base elt b_elt = getattr(_cls, elt_name, None) if b_elt is not None: # compare funcs if ismethod(b_elt): bec = get_method_function(b_elt) else: bec = b_elt # if matching, add to result if bec is elt_to_compare: result.append(b_elt) return result
[ "def", "base_elts", "(", "elt", ",", "cls", "=", "None", ",", "depth", "=", "None", ")", ":", "result", "=", "[", "]", "elt_name", "=", "getattr", "(", "elt", ",", "'__name__'", ",", "None", ")", "if", "elt_name", "is", "not", "None", ":", "cls", "=", "[", "]", "if", "cls", "is", "None", "else", "ensureiterable", "(", "cls", ")", "elt_is_class", "=", "False", "# if cls is None and elt is routine, it is possible to find the cls", "if", "not", "cls", "and", "isroutine", "(", "elt", ")", ":", "if", "hasattr", "(", "elt", ",", "'__self__'", ")", ":", "# from the instance", "instance", "=", "get_method_self", "(", "elt", ")", "# get instance", "if", "instance", "is", "None", "and", "PY2", ":", "# get base im_class if PY2", "cls", "=", "list", "(", "elt", ".", "im_class", ".", "__bases__", ")", "else", ":", "# use instance class", "cls", "=", "[", "instance", ".", "__class__", "]", "# cls is elt if elt is a class", "elif", "isclass", "(", "elt", ")", ":", "elt_is_class", "=", "True", "cls", "=", "list", "(", "elt", ".", "__bases__", ")", "if", "cls", ":", "# if cls is not empty, find all base classes", "index_of_found_classes", "=", "0", "# get last visited class index", "visited_classes", "=", "set", "(", "cls", ")", "# cache for visited classes", "len_classes", "=", "len", "(", "cls", ")", "if", "depth", "is", "None", ":", "# if depth is None, get maximal value", "depth", "=", "-", "1", "# set negative value", "while", "depth", "!=", "0", "and", "index_of_found_classes", "!=", "len_classes", ":", "len_classes", "=", "len", "(", "cls", ")", "for", "index", "in", "range", "(", "index_of_found_classes", ",", "len_classes", ")", ":", "_cls", "=", "cls", "[", "index", "]", "for", "base_cls", "in", "_cls", ".", "__bases__", ":", "if", "base_cls", "in", "visited_classes", ":", "continue", "else", ":", "visited_classes", ".", "add", "(", "base_cls", ")", "cls", ".", "append", "(", "base_cls", ")", "index_of_found_classes", "=", "len_classes", "depth", "-=", "1", "if", "elt_is_class", ":", "# if cls is elt, result is classes minus first class", "result", "=", "cls", "elif", "isroutine", "(", "elt", ")", ":", "# get an elt to compare with found element", "if", "ismethod", "(", "elt", ")", ":", "elt_to_compare", "=", "get_method_function", "(", "elt", ")", "else", ":", "elt_to_compare", "=", "elt", "for", "_cls", "in", "cls", ":", "# for all classes", "# get possible base elt", "b_elt", "=", "getattr", "(", "_cls", ",", "elt_name", ",", "None", ")", "if", "b_elt", "is", "not", "None", ":", "# compare funcs", "if", "ismethod", "(", "b_elt", ")", ":", "bec", "=", "get_method_function", "(", "b_elt", ")", "else", ":", "bec", "=", "b_elt", "# if matching, add to result", "if", "bec", "is", "elt_to_compare", ":", "result", ".", "append", "(", "b_elt", ")", "return", "result" ]
Get bases elements of the input elt. - If elt is an instance, get class and all base classes. - If elt is a method, get all base methods. - If elt is a class, get all base classes. - In other case, get an empty list. :param elt: supposed inherited elt. :param cls: cls from where find attributes equal to elt. If None, it is found as much as possible. Required in python3 for function classes. :type cls: type or list :param int depth: search depth. If None (default), depth is maximal. :return: elt bases elements. if elt has not base elements, result is empty. :rtype: list
[ "Get", "bases", "elements", "of", "the", "input", "elt", "." ]
793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff
https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/reflect.py#L48-L145
251,260
b3j0f/utils
b3j0f/utils/reflect.py
find_embedding
def find_embedding(elt, embedding=None): """Try to get elt embedding elements. :param embedding: embedding element. Must have a module. :return: a list of [module [,class]*] embedding elements which define elt. :rtype: list """ result = [] # result is empty in the worst case # start to get module module = getmodule(elt) if module is not None: # if module exists visited = set() # cache to avoid to visit twice same element if embedding is None: embedding = module # list of compounds elements which construct the path to elt compounds = [embedding] while compounds: # while compounds elements exist # get last compound last_embedding = compounds[-1] # stop to iterate on compounds when last embedding is elt if last_embedding == elt: result = compounds # result is compounds break else: # search among embedded elements for name in dir(last_embedding): # get embedded element embedded = getattr(last_embedding, name) try: # check if embedded has already been visited if embedded not in visited: visited.add(embedded) # set it as visited else: continue except TypeError: pass else: # get embedded module embedded_module = getmodule(embedded) # and compare it with elt module if embedded_module is module: # add embedded to compounds compounds.append(embedded) # end the second loop break else: # remove last element if no coumpound element is found compounds.pop(-1) return result
python
def find_embedding(elt, embedding=None): """Try to get elt embedding elements. :param embedding: embedding element. Must have a module. :return: a list of [module [,class]*] embedding elements which define elt. :rtype: list """ result = [] # result is empty in the worst case # start to get module module = getmodule(elt) if module is not None: # if module exists visited = set() # cache to avoid to visit twice same element if embedding is None: embedding = module # list of compounds elements which construct the path to elt compounds = [embedding] while compounds: # while compounds elements exist # get last compound last_embedding = compounds[-1] # stop to iterate on compounds when last embedding is elt if last_embedding == elt: result = compounds # result is compounds break else: # search among embedded elements for name in dir(last_embedding): # get embedded element embedded = getattr(last_embedding, name) try: # check if embedded has already been visited if embedded not in visited: visited.add(embedded) # set it as visited else: continue except TypeError: pass else: # get embedded module embedded_module = getmodule(embedded) # and compare it with elt module if embedded_module is module: # add embedded to compounds compounds.append(embedded) # end the second loop break else: # remove last element if no coumpound element is found compounds.pop(-1) return result
[ "def", "find_embedding", "(", "elt", ",", "embedding", "=", "None", ")", ":", "result", "=", "[", "]", "# result is empty in the worst case", "# start to get module", "module", "=", "getmodule", "(", "elt", ")", "if", "module", "is", "not", "None", ":", "# if module exists", "visited", "=", "set", "(", ")", "# cache to avoid to visit twice same element", "if", "embedding", "is", "None", ":", "embedding", "=", "module", "# list of compounds elements which construct the path to elt", "compounds", "=", "[", "embedding", "]", "while", "compounds", ":", "# while compounds elements exist", "# get last compound", "last_embedding", "=", "compounds", "[", "-", "1", "]", "# stop to iterate on compounds when last embedding is elt", "if", "last_embedding", "==", "elt", ":", "result", "=", "compounds", "# result is compounds", "break", "else", ":", "# search among embedded elements", "for", "name", "in", "dir", "(", "last_embedding", ")", ":", "# get embedded element", "embedded", "=", "getattr", "(", "last_embedding", ",", "name", ")", "try", ":", "# check if embedded has already been visited", "if", "embedded", "not", "in", "visited", ":", "visited", ".", "add", "(", "embedded", ")", "# set it as visited", "else", ":", "continue", "except", "TypeError", ":", "pass", "else", ":", "# get embedded module", "embedded_module", "=", "getmodule", "(", "embedded", ")", "# and compare it with elt module", "if", "embedded_module", "is", "module", ":", "# add embedded to compounds", "compounds", ".", "append", "(", "embedded", ")", "# end the second loop", "break", "else", ":", "# remove last element if no coumpound element is found", "compounds", ".", "pop", "(", "-", "1", ")", "return", "result" ]
Try to get elt embedding elements. :param embedding: embedding element. Must have a module. :return: a list of [module [,class]*] embedding elements which define elt. :rtype: list
[ "Try", "to", "get", "elt", "embedding", "elements", "." ]
793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff
https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/reflect.py#L160-L223
251,261
wohlgejm/accountable
accountable/cli.py
projects
def projects(accountable): """ List all projects. """ projects = accountable.metadata()['projects'] headers = sorted(['id', 'key', 'self']) rows = [[v for k, v in sorted(p.items()) if k in headers] for p in projects] rows.insert(0, headers) print_table(SingleTable(rows))
python
def projects(accountable): """ List all projects. """ projects = accountable.metadata()['projects'] headers = sorted(['id', 'key', 'self']) rows = [[v for k, v in sorted(p.items()) if k in headers] for p in projects] rows.insert(0, headers) print_table(SingleTable(rows))
[ "def", "projects", "(", "accountable", ")", ":", "projects", "=", "accountable", ".", "metadata", "(", ")", "[", "'projects'", "]", "headers", "=", "sorted", "(", "[", "'id'", ",", "'key'", ",", "'self'", "]", ")", "rows", "=", "[", "[", "v", "for", "k", ",", "v", "in", "sorted", "(", "p", ".", "items", "(", ")", ")", "if", "k", "in", "headers", "]", "for", "p", "in", "projects", "]", "rows", ".", "insert", "(", "0", ",", "headers", ")", "print_table", "(", "SingleTable", "(", "rows", ")", ")" ]
List all projects.
[ "List", "all", "projects", "." ]
20586365ccd319061e5548ce14fb0b8f449580fa
https://github.com/wohlgejm/accountable/blob/20586365ccd319061e5548ce14fb0b8f449580fa/accountable/cli.py#L71-L79
251,262
wohlgejm/accountable
accountable/cli.py
issuetypes
def issuetypes(accountable, project_key): """ List all issue types. Optional parameter to list issue types by a given project. """ projects = accountable.issue_types(project_key) headers = sorted(['id', 'name', 'description']) rows = [] for key, issue_types in sorted(projects.items()): for issue_type in issue_types: rows.append( [key] + [v for k, v in sorted(issue_type.items()) if k in headers] ) rows.insert(0, ['project_key'] + headers) print_table(SingleTable(rows))
python
def issuetypes(accountable, project_key): """ List all issue types. Optional parameter to list issue types by a given project. """ projects = accountable.issue_types(project_key) headers = sorted(['id', 'name', 'description']) rows = [] for key, issue_types in sorted(projects.items()): for issue_type in issue_types: rows.append( [key] + [v for k, v in sorted(issue_type.items()) if k in headers] ) rows.insert(0, ['project_key'] + headers) print_table(SingleTable(rows))
[ "def", "issuetypes", "(", "accountable", ",", "project_key", ")", ":", "projects", "=", "accountable", ".", "issue_types", "(", "project_key", ")", "headers", "=", "sorted", "(", "[", "'id'", ",", "'name'", ",", "'description'", "]", ")", "rows", "=", "[", "]", "for", "key", ",", "issue_types", "in", "sorted", "(", "projects", ".", "items", "(", ")", ")", ":", "for", "issue_type", "in", "issue_types", ":", "rows", ".", "append", "(", "[", "key", "]", "+", "[", "v", "for", "k", ",", "v", "in", "sorted", "(", "issue_type", ".", "items", "(", ")", ")", "if", "k", "in", "headers", "]", ")", "rows", ".", "insert", "(", "0", ",", "[", "'project_key'", "]", "+", "headers", ")", "print_table", "(", "SingleTable", "(", "rows", ")", ")" ]
List all issue types. Optional parameter to list issue types by a given project.
[ "List", "all", "issue", "types", ".", "Optional", "parameter", "to", "list", "issue", "types", "by", "a", "given", "project", "." ]
20586365ccd319061e5548ce14fb0b8f449580fa
https://github.com/wohlgejm/accountable/blob/20586365ccd319061e5548ce14fb0b8f449580fa/accountable/cli.py#L85-L100
251,263
wohlgejm/accountable
accountable/cli.py
components
def components(accountable, project_key): """ Returns a list of all a project's components. """ components = accountable.project_components(project_key) headers = sorted(['id', 'name', 'self']) rows = [[v for k, v in sorted(component.items()) if k in headers] for component in components] rows.insert(0, headers) print_table(SingleTable(rows))
python
def components(accountable, project_key): """ Returns a list of all a project's components. """ components = accountable.project_components(project_key) headers = sorted(['id', 'name', 'self']) rows = [[v for k, v in sorted(component.items()) if k in headers] for component in components] rows.insert(0, headers) print_table(SingleTable(rows))
[ "def", "components", "(", "accountable", ",", "project_key", ")", ":", "components", "=", "accountable", ".", "project_components", "(", "project_key", ")", "headers", "=", "sorted", "(", "[", "'id'", ",", "'name'", ",", "'self'", "]", ")", "rows", "=", "[", "[", "v", "for", "k", ",", "v", "in", "sorted", "(", "component", ".", "items", "(", ")", ")", "if", "k", "in", "headers", "]", "for", "component", "in", "components", "]", "rows", ".", "insert", "(", "0", ",", "headers", ")", "print_table", "(", "SingleTable", "(", "rows", ")", ")" ]
Returns a list of all a project's components.
[ "Returns", "a", "list", "of", "all", "a", "project", "s", "components", "." ]
20586365ccd319061e5548ce14fb0b8f449580fa
https://github.com/wohlgejm/accountable/blob/20586365ccd319061e5548ce14fb0b8f449580fa/accountable/cli.py#L106-L115
251,264
wohlgejm/accountable
accountable/cli.py
checkoutbranch
def checkoutbranch(accountable, options): """ Create a new issue and checkout a branch named after it. """ issue = accountable.checkout_branch(options) headers = sorted(['id', 'key', 'self']) rows = [headers, [itemgetter(header)(issue) for header in headers]] print_table(SingleTable(rows))
python
def checkoutbranch(accountable, options): """ Create a new issue and checkout a branch named after it. """ issue = accountable.checkout_branch(options) headers = sorted(['id', 'key', 'self']) rows = [headers, [itemgetter(header)(issue) for header in headers]] print_table(SingleTable(rows))
[ "def", "checkoutbranch", "(", "accountable", ",", "options", ")", ":", "issue", "=", "accountable", ".", "checkout_branch", "(", "options", ")", "headers", "=", "sorted", "(", "[", "'id'", ",", "'key'", ",", "'self'", "]", ")", "rows", "=", "[", "headers", ",", "[", "itemgetter", "(", "header", ")", "(", "issue", ")", "for", "header", "in", "headers", "]", "]", "print_table", "(", "SingleTable", "(", "rows", ")", ")" ]
Create a new issue and checkout a branch named after it.
[ "Create", "a", "new", "issue", "and", "checkout", "a", "branch", "named", "after", "it", "." ]
20586365ccd319061e5548ce14fb0b8f449580fa
https://github.com/wohlgejm/accountable/blob/20586365ccd319061e5548ce14fb0b8f449580fa/accountable/cli.py#L168-L175
251,265
wohlgejm/accountable
accountable/cli.py
checkout
def checkout(accountable, issue_key): """ Checkout a new branch or checkout to a branch for a given issue. """ issue = accountable.checkout(issue_key) headers = issue.keys() rows = [headers, [v for k, v in issue.items()]] print_table(SingleTable(rows))
python
def checkout(accountable, issue_key): """ Checkout a new branch or checkout to a branch for a given issue. """ issue = accountable.checkout(issue_key) headers = issue.keys() rows = [headers, [v for k, v in issue.items()]] print_table(SingleTable(rows))
[ "def", "checkout", "(", "accountable", ",", "issue_key", ")", ":", "issue", "=", "accountable", ".", "checkout", "(", "issue_key", ")", "headers", "=", "issue", ".", "keys", "(", ")", "rows", "=", "[", "headers", ",", "[", "v", "for", "k", ",", "v", "in", "issue", ".", "items", "(", ")", "]", "]", "print_table", "(", "SingleTable", "(", "rows", ")", ")" ]
Checkout a new branch or checkout to a branch for a given issue.
[ "Checkout", "a", "new", "branch", "or", "checkout", "to", "a", "branch", "for", "a", "given", "issue", "." ]
20586365ccd319061e5548ce14fb0b8f449580fa
https://github.com/wohlgejm/accountable/blob/20586365ccd319061e5548ce14fb0b8f449580fa/accountable/cli.py#L181-L188
251,266
wohlgejm/accountable
accountable/cli.py
issue
def issue(ctx, accountable, issue_key): """ List metadata for a given issue key. """ accountable.issue_key = issue_key if not ctx.invoked_subcommand: issue = accountable.issue_meta() headers = issue.keys() rows = [headers, [v for k, v in issue.items()]] print_table(SingleTable(rows))
python
def issue(ctx, accountable, issue_key): """ List metadata for a given issue key. """ accountable.issue_key = issue_key if not ctx.invoked_subcommand: issue = accountable.issue_meta() headers = issue.keys() rows = [headers, [v for k, v in issue.items()]] print_table(SingleTable(rows))
[ "def", "issue", "(", "ctx", ",", "accountable", ",", "issue_key", ")", ":", "accountable", ".", "issue_key", "=", "issue_key", "if", "not", "ctx", ".", "invoked_subcommand", ":", "issue", "=", "accountable", ".", "issue_meta", "(", ")", "headers", "=", "issue", ".", "keys", "(", ")", "rows", "=", "[", "headers", ",", "[", "v", "for", "k", ",", "v", "in", "issue", ".", "items", "(", ")", "]", "]", "print_table", "(", "SingleTable", "(", "rows", ")", ")" ]
List metadata for a given issue key.
[ "List", "metadata", "for", "a", "given", "issue", "key", "." ]
20586365ccd319061e5548ce14fb0b8f449580fa
https://github.com/wohlgejm/accountable/blob/20586365ccd319061e5548ce14fb0b8f449580fa/accountable/cli.py#L195-L204
251,267
wohlgejm/accountable
accountable/cli.py
update
def update(accountable, options): """ Update an existing issue. """ issue = accountable.issue_update(options) headers = issue.keys() rows = [headers, [v for k, v in issue.items()]] print_table(SingleTable(rows))
python
def update(accountable, options): """ Update an existing issue. """ issue = accountable.issue_update(options) headers = issue.keys() rows = [headers, [v for k, v in issue.items()]] print_table(SingleTable(rows))
[ "def", "update", "(", "accountable", ",", "options", ")", ":", "issue", "=", "accountable", ".", "issue_update", "(", "options", ")", "headers", "=", "issue", ".", "keys", "(", ")", "rows", "=", "[", "headers", ",", "[", "v", "for", "k", ",", "v", "in", "issue", ".", "items", "(", ")", "]", "]", "print_table", "(", "SingleTable", "(", "rows", ")", ")" ]
Update an existing issue.
[ "Update", "an", "existing", "issue", "." ]
20586365ccd319061e5548ce14fb0b8f449580fa
https://github.com/wohlgejm/accountable/blob/20586365ccd319061e5548ce14fb0b8f449580fa/accountable/cli.py#L209-L216
251,268
wohlgejm/accountable
accountable/cli.py
comments
def comments(accountable): """ Lists all comments for a given issue key. """ comments = accountable.issue_comments() headers = sorted(['author_name', 'body', 'updated']) if comments: rows = [[v for k, v in sorted(c.items()) if k in headers] for c in comments] rows.insert(0, headers) print_table(SingleTable(rows)) else: click.secho('No comments found for {}'.format( accountable.issue_key ), fg='red')
python
def comments(accountable): """ Lists all comments for a given issue key. """ comments = accountable.issue_comments() headers = sorted(['author_name', 'body', 'updated']) if comments: rows = [[v for k, v in sorted(c.items()) if k in headers] for c in comments] rows.insert(0, headers) print_table(SingleTable(rows)) else: click.secho('No comments found for {}'.format( accountable.issue_key ), fg='red')
[ "def", "comments", "(", "accountable", ")", ":", "comments", "=", "accountable", ".", "issue_comments", "(", ")", "headers", "=", "sorted", "(", "[", "'author_name'", ",", "'body'", ",", "'updated'", "]", ")", "if", "comments", ":", "rows", "=", "[", "[", "v", "for", "k", ",", "v", "in", "sorted", "(", "c", ".", "items", "(", ")", ")", "if", "k", "in", "headers", "]", "for", "c", "in", "comments", "]", "rows", ".", "insert", "(", "0", ",", "headers", ")", "print_table", "(", "SingleTable", "(", "rows", ")", ")", "else", ":", "click", ".", "secho", "(", "'No comments found for {}'", ".", "format", "(", "accountable", ".", "issue_key", ")", ",", "fg", "=", "'red'", ")" ]
Lists all comments for a given issue key.
[ "Lists", "all", "comments", "for", "a", "given", "issue", "key", "." ]
20586365ccd319061e5548ce14fb0b8f449580fa
https://github.com/wohlgejm/accountable/blob/20586365ccd319061e5548ce14fb0b8f449580fa/accountable/cli.py#L221-L236
251,269
wohlgejm/accountable
accountable/cli.py
addcomment
def addcomment(accountable, body): """ Add a comment to the given issue key. Accepts a body argument to be used as the comment's body. """ r = accountable.issue_add_comment(body) headers = sorted(['author_name', 'body', 'updated']) rows = [[v for k, v in sorted(r.items()) if k in headers]] rows.insert(0, headers) print_table(SingleTable(rows))
python
def addcomment(accountable, body): """ Add a comment to the given issue key. Accepts a body argument to be used as the comment's body. """ r = accountable.issue_add_comment(body) headers = sorted(['author_name', 'body', 'updated']) rows = [[v for k, v in sorted(r.items()) if k in headers]] rows.insert(0, headers) print_table(SingleTable(rows))
[ "def", "addcomment", "(", "accountable", ",", "body", ")", ":", "r", "=", "accountable", ".", "issue_add_comment", "(", "body", ")", "headers", "=", "sorted", "(", "[", "'author_name'", ",", "'body'", ",", "'updated'", "]", ")", "rows", "=", "[", "[", "v", "for", "k", ",", "v", "in", "sorted", "(", "r", ".", "items", "(", ")", ")", "if", "k", "in", "headers", "]", "]", "rows", ".", "insert", "(", "0", ",", "headers", ")", "print_table", "(", "SingleTable", "(", "rows", ")", ")" ]
Add a comment to the given issue key. Accepts a body argument to be used as the comment's body.
[ "Add", "a", "comment", "to", "the", "given", "issue", "key", ".", "Accepts", "a", "body", "argument", "to", "be", "used", "as", "the", "comment", "s", "body", "." ]
20586365ccd319061e5548ce14fb0b8f449580fa
https://github.com/wohlgejm/accountable/blob/20586365ccd319061e5548ce14fb0b8f449580fa/accountable/cli.py#L242-L252
251,270
wohlgejm/accountable
accountable/cli.py
worklog
def worklog(accountable): """ List all worklogs for a given issue key. """ worklog = accountable.issue_worklog() headers = ['author_name', 'comment', 'time_spent'] if worklog: rows = [[v for k, v in sorted(w.items()) if k in headers] for w in worklog] rows.insert(0, headers) print_table(SingleTable(rows)) else: click.secho( 'No worklogs found for {}'.format(accountable.issue_key), fg='red' )
python
def worklog(accountable): """ List all worklogs for a given issue key. """ worklog = accountable.issue_worklog() headers = ['author_name', 'comment', 'time_spent'] if worklog: rows = [[v for k, v in sorted(w.items()) if k in headers] for w in worklog] rows.insert(0, headers) print_table(SingleTable(rows)) else: click.secho( 'No worklogs found for {}'.format(accountable.issue_key), fg='red' )
[ "def", "worklog", "(", "accountable", ")", ":", "worklog", "=", "accountable", ".", "issue_worklog", "(", ")", "headers", "=", "[", "'author_name'", ",", "'comment'", ",", "'time_spent'", "]", "if", "worklog", ":", "rows", "=", "[", "[", "v", "for", "k", ",", "v", "in", "sorted", "(", "w", ".", "items", "(", ")", ")", "if", "k", "in", "headers", "]", "for", "w", "in", "worklog", "]", "rows", ".", "insert", "(", "0", ",", "headers", ")", "print_table", "(", "SingleTable", "(", "rows", ")", ")", "else", ":", "click", ".", "secho", "(", "'No worklogs found for {}'", ".", "format", "(", "accountable", ".", "issue_key", ")", ",", "fg", "=", "'red'", ")" ]
List all worklogs for a given issue key.
[ "List", "all", "worklogs", "for", "a", "given", "issue", "key", "." ]
20586365ccd319061e5548ce14fb0b8f449580fa
https://github.com/wohlgejm/accountable/blob/20586365ccd319061e5548ce14fb0b8f449580fa/accountable/cli.py#L257-L272
251,271
wohlgejm/accountable
accountable/cli.py
transitions
def transitions(accountable): """ List all possible transitions for a given issue. """ transitions = accountable.issue_transitions().get('transitions') headers = ['id', 'name'] if transitions: rows = [[v for k, v in sorted(t.items()) if k in headers] for t in transitions] rows.insert(0, headers) print_table(SingleTable(rows)) else: click.secho( 'No transitions found for {}'.format(accountable.issue_key), fg='red' )
python
def transitions(accountable): """ List all possible transitions for a given issue. """ transitions = accountable.issue_transitions().get('transitions') headers = ['id', 'name'] if transitions: rows = [[v for k, v in sorted(t.items()) if k in headers] for t in transitions] rows.insert(0, headers) print_table(SingleTable(rows)) else: click.secho( 'No transitions found for {}'.format(accountable.issue_key), fg='red' )
[ "def", "transitions", "(", "accountable", ")", ":", "transitions", "=", "accountable", ".", "issue_transitions", "(", ")", ".", "get", "(", "'transitions'", ")", "headers", "=", "[", "'id'", ",", "'name'", "]", "if", "transitions", ":", "rows", "=", "[", "[", "v", "for", "k", ",", "v", "in", "sorted", "(", "t", ".", "items", "(", ")", ")", "if", "k", "in", "headers", "]", "for", "t", "in", "transitions", "]", "rows", ".", "insert", "(", "0", ",", "headers", ")", "print_table", "(", "SingleTable", "(", "rows", ")", ")", "else", ":", "click", ".", "secho", "(", "'No transitions found for {}'", ".", "format", "(", "accountable", ".", "issue_key", ")", ",", "fg", "=", "'red'", ")" ]
List all possible transitions for a given issue.
[ "List", "all", "possible", "transitions", "for", "a", "given", "issue", "." ]
20586365ccd319061e5548ce14fb0b8f449580fa
https://github.com/wohlgejm/accountable/blob/20586365ccd319061e5548ce14fb0b8f449580fa/accountable/cli.py#L277-L292
251,272
wohlgejm/accountable
accountable/cli.py
dotransition
def dotransition(accountable, transition_id): """ Transition the given issue to the provided ID. The API does not return a JSON response for this call. """ t = accountable.issue_do_transition(transition_id) if t.status_code == 204: click.secho( 'Successfully transitioned {}'.format(accountable.issue_key), fg='green' )
python
def dotransition(accountable, transition_id): """ Transition the given issue to the provided ID. The API does not return a JSON response for this call. """ t = accountable.issue_do_transition(transition_id) if t.status_code == 204: click.secho( 'Successfully transitioned {}'.format(accountable.issue_key), fg='green' )
[ "def", "dotransition", "(", "accountable", ",", "transition_id", ")", ":", "t", "=", "accountable", ".", "issue_do_transition", "(", "transition_id", ")", "if", "t", ".", "status_code", "==", "204", ":", "click", ".", "secho", "(", "'Successfully transitioned {}'", ".", "format", "(", "accountable", ".", "issue_key", ")", ",", "fg", "=", "'green'", ")" ]
Transition the given issue to the provided ID. The API does not return a JSON response for this call.
[ "Transition", "the", "given", "issue", "to", "the", "provided", "ID", ".", "The", "API", "does", "not", "return", "a", "JSON", "response", "for", "this", "call", "." ]
20586365ccd319061e5548ce14fb0b8f449580fa
https://github.com/wohlgejm/accountable/blob/20586365ccd319061e5548ce14fb0b8f449580fa/accountable/cli.py#L298-L308
251,273
wohlgejm/accountable
accountable/cli.py
users
def users(accountable, query): """ Executes a user search for the given query. """ users = accountable.users(query) headers = ['display_name', 'key'] if users: rows = [[v for k, v in sorted(u.items()) if k in headers] for u in users] rows.insert(0, headers) print_table(SingleTable(rows)) else: click.secho('No users found for query {}'.format( query ), fg='red')
python
def users(accountable, query): """ Executes a user search for the given query. """ users = accountable.users(query) headers = ['display_name', 'key'] if users: rows = [[v for k, v in sorted(u.items()) if k in headers] for u in users] rows.insert(0, headers) print_table(SingleTable(rows)) else: click.secho('No users found for query {}'.format( query ), fg='red')
[ "def", "users", "(", "accountable", ",", "query", ")", ":", "users", "=", "accountable", ".", "users", "(", "query", ")", "headers", "=", "[", "'display_name'", ",", "'key'", "]", "if", "users", ":", "rows", "=", "[", "[", "v", "for", "k", ",", "v", "in", "sorted", "(", "u", ".", "items", "(", ")", ")", "if", "k", "in", "headers", "]", "for", "u", "in", "users", "]", "rows", ".", "insert", "(", "0", ",", "headers", ")", "print_table", "(", "SingleTable", "(", "rows", ")", ")", "else", ":", "click", ".", "secho", "(", "'No users found for query {}'", ".", "format", "(", "query", ")", ",", "fg", "=", "'red'", ")" ]
Executes a user search for the given query.
[ "Executes", "a", "user", "search", "for", "the", "given", "query", "." ]
20586365ccd319061e5548ce14fb0b8f449580fa
https://github.com/wohlgejm/accountable/blob/20586365ccd319061e5548ce14fb0b8f449580fa/accountable/cli.py#L314-L328
251,274
abalkin/tz
tz/system_tzdata.py
guess_saves
def guess_saves(zone, data): """Return types with guessed DST saves""" saves = {} details = {} for (time0, type0), (time1, type1) in pairs(data.times): is_dst0 = bool(data.types[type0][1]) is_dst1 = bool(data.types[type1][1]) if (is_dst0, is_dst1) == (False, True): shift = data.types[type1][0] - data.types[type0][0] if shift: saves.setdefault(type1, set()).add(shift) details[type1, shift] = (time0, time1) elif (is_dst0, is_dst1) == (True, False): shift = data.types[type0][0] - data.types[type1][0] if shift: saves.setdefault(type0, set()).add(shift) details[type0, shift] = (time0, time1) types = data.types[:] for i, (offset, save, abbr) in enumerate(data.types): if save: guesses = saves.get(i, set()) if not guesses: print("No save value guesses for type %d (%r) in zone %s." % (i, types[i][-1], zone)) guess = timedelta(hours=1) elif len(guesses) == 1: guess = guesses.pop() else: print("Multiple save value guesses for type %d in zone %s." % (i, zone)) for g in guesses: d = details[i, g] print(" ", g, *d) guess = min(g for g in guesses if g) types[i] = (offset, guess, abbr) return types
python
def guess_saves(zone, data): """Return types with guessed DST saves""" saves = {} details = {} for (time0, type0), (time1, type1) in pairs(data.times): is_dst0 = bool(data.types[type0][1]) is_dst1 = bool(data.types[type1][1]) if (is_dst0, is_dst1) == (False, True): shift = data.types[type1][0] - data.types[type0][0] if shift: saves.setdefault(type1, set()).add(shift) details[type1, shift] = (time0, time1) elif (is_dst0, is_dst1) == (True, False): shift = data.types[type0][0] - data.types[type1][0] if shift: saves.setdefault(type0, set()).add(shift) details[type0, shift] = (time0, time1) types = data.types[:] for i, (offset, save, abbr) in enumerate(data.types): if save: guesses = saves.get(i, set()) if not guesses: print("No save value guesses for type %d (%r) in zone %s." % (i, types[i][-1], zone)) guess = timedelta(hours=1) elif len(guesses) == 1: guess = guesses.pop() else: print("Multiple save value guesses for type %d in zone %s." % (i, zone)) for g in guesses: d = details[i, g] print(" ", g, *d) guess = min(g for g in guesses if g) types[i] = (offset, guess, abbr) return types
[ "def", "guess_saves", "(", "zone", ",", "data", ")", ":", "saves", "=", "{", "}", "details", "=", "{", "}", "for", "(", "time0", ",", "type0", ")", ",", "(", "time1", ",", "type1", ")", "in", "pairs", "(", "data", ".", "times", ")", ":", "is_dst0", "=", "bool", "(", "data", ".", "types", "[", "type0", "]", "[", "1", "]", ")", "is_dst1", "=", "bool", "(", "data", ".", "types", "[", "type1", "]", "[", "1", "]", ")", "if", "(", "is_dst0", ",", "is_dst1", ")", "==", "(", "False", ",", "True", ")", ":", "shift", "=", "data", ".", "types", "[", "type1", "]", "[", "0", "]", "-", "data", ".", "types", "[", "type0", "]", "[", "0", "]", "if", "shift", ":", "saves", ".", "setdefault", "(", "type1", ",", "set", "(", ")", ")", ".", "add", "(", "shift", ")", "details", "[", "type1", ",", "shift", "]", "=", "(", "time0", ",", "time1", ")", "elif", "(", "is_dst0", ",", "is_dst1", ")", "==", "(", "True", ",", "False", ")", ":", "shift", "=", "data", ".", "types", "[", "type0", "]", "[", "0", "]", "-", "data", ".", "types", "[", "type1", "]", "[", "0", "]", "if", "shift", ":", "saves", ".", "setdefault", "(", "type0", ",", "set", "(", ")", ")", ".", "add", "(", "shift", ")", "details", "[", "type0", ",", "shift", "]", "=", "(", "time0", ",", "time1", ")", "types", "=", "data", ".", "types", "[", ":", "]", "for", "i", ",", "(", "offset", ",", "save", ",", "abbr", ")", "in", "enumerate", "(", "data", ".", "types", ")", ":", "if", "save", ":", "guesses", "=", "saves", ".", "get", "(", "i", ",", "set", "(", ")", ")", "if", "not", "guesses", ":", "print", "(", "\"No save value guesses for type %d (%r) in zone %s.\"", "%", "(", "i", ",", "types", "[", "i", "]", "[", "-", "1", "]", ",", "zone", ")", ")", "guess", "=", "timedelta", "(", "hours", "=", "1", ")", "elif", "len", "(", "guesses", ")", "==", "1", ":", "guess", "=", "guesses", ".", "pop", "(", ")", "else", ":", "print", "(", "\"Multiple save value guesses for type %d in zone %s.\"", "%", "(", "i", ",", "zone", ")", ")", "for", "g", "in", "guesses", ":", "d", "=", "details", "[", "i", ",", "g", "]", "print", "(", "\" \"", ",", "g", ",", "*", "d", ")", "guess", "=", "min", "(", "g", "for", "g", "in", "guesses", "if", "g", ")", "types", "[", "i", "]", "=", "(", "offset", ",", "guess", ",", "abbr", ")", "return", "types" ]
Return types with guessed DST saves
[ "Return", "types", "with", "guessed", "DST", "saves" ]
f25fca6afbf1abd46fd7aeb978282823c7dab5ab
https://github.com/abalkin/tz/blob/f25fca6afbf1abd46fd7aeb978282823c7dab5ab/tz/system_tzdata.py#L69-L105
251,275
jtpaasch/simplygithub
simplygithub/files.py
get_commit_tree
def get_commit_tree(profile, sha): """Get the SHA of a commit's tree. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. sha The SHA of a commit. Returns: The SHA of the commit's tree. """ data = commits.get_commit(profile, sha) tree = data.get("tree") sha = tree.get("sha") return sha
python
def get_commit_tree(profile, sha): """Get the SHA of a commit's tree. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. sha The SHA of a commit. Returns: The SHA of the commit's tree. """ data = commits.get_commit(profile, sha) tree = data.get("tree") sha = tree.get("sha") return sha
[ "def", "get_commit_tree", "(", "profile", ",", "sha", ")", ":", "data", "=", "commits", ".", "get_commit", "(", "profile", ",", "sha", ")", "tree", "=", "data", ".", "get", "(", "\"tree\"", ")", "sha", "=", "tree", ".", "get", "(", "\"sha\"", ")", "return", "sha" ]
Get the SHA of a commit's tree. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. sha The SHA of a commit. Returns: The SHA of the commit's tree.
[ "Get", "the", "SHA", "of", "a", "commit", "s", "tree", "." ]
b77506275ec276ce90879bf1ea9299a79448b903
https://github.com/jtpaasch/simplygithub/blob/b77506275ec276ce90879bf1ea9299a79448b903/simplygithub/files.py#L43-L63
251,276
jtpaasch/simplygithub
simplygithub/files.py
remove_file_from_tree
def remove_file_from_tree(tree, file_path): """Remove a file from a tree. Args: tree A list of dicts containing info about each blob in a tree. file_path The path of a file to remove from a tree. Returns: The provided tree, but with the item matching the specified file_path removed. """ match = None for item in tree: if item.get("path") == file_path: match = item break if match: tree.remove(match) return tree
python
def remove_file_from_tree(tree, file_path): """Remove a file from a tree. Args: tree A list of dicts containing info about each blob in a tree. file_path The path of a file to remove from a tree. Returns: The provided tree, but with the item matching the specified file_path removed. """ match = None for item in tree: if item.get("path") == file_path: match = item break if match: tree.remove(match) return tree
[ "def", "remove_file_from_tree", "(", "tree", ",", "file_path", ")", ":", "match", "=", "None", "for", "item", "in", "tree", ":", "if", "item", ".", "get", "(", "\"path\"", ")", "==", "file_path", ":", "match", "=", "item", "break", "if", "match", ":", "tree", ".", "remove", "(", "match", ")", "return", "tree" ]
Remove a file from a tree. Args: tree A list of dicts containing info about each blob in a tree. file_path The path of a file to remove from a tree. Returns: The provided tree, but with the item matching the specified file_path removed.
[ "Remove", "a", "file", "from", "a", "tree", "." ]
b77506275ec276ce90879bf1ea9299a79448b903
https://github.com/jtpaasch/simplygithub/blob/b77506275ec276ce90879bf1ea9299a79448b903/simplygithub/files.py#L89-L112
251,277
jtpaasch/simplygithub
simplygithub/files.py
add_file_to_tree
def add_file_to_tree(tree, file_path, file_contents, is_executable=False): """Add a file to a tree. Args: tree A list of dicts containing info about each blob in a tree. file_path The path of the new file in the tree. file_contents The (UTF-8 encoded) contents of the new file. is_executable If ``True``, the new file will get executable permissions (0755). Otherwise, it will get 0644 permissions. Returns: The provided tree, but with the new file added. """ record = { "path": file_path, "mode": "100755" if is_executable else "100644", "type": "blob", "content": file_contents, } tree.append(record) return tree
python
def add_file_to_tree(tree, file_path, file_contents, is_executable=False): """Add a file to a tree. Args: tree A list of dicts containing info about each blob in a tree. file_path The path of the new file in the tree. file_contents The (UTF-8 encoded) contents of the new file. is_executable If ``True``, the new file will get executable permissions (0755). Otherwise, it will get 0644 permissions. Returns: The provided tree, but with the new file added. """ record = { "path": file_path, "mode": "100755" if is_executable else "100644", "type": "blob", "content": file_contents, } tree.append(record) return tree
[ "def", "add_file_to_tree", "(", "tree", ",", "file_path", ",", "file_contents", ",", "is_executable", "=", "False", ")", ":", "record", "=", "{", "\"path\"", ":", "file_path", ",", "\"mode\"", ":", "\"100755\"", "if", "is_executable", "else", "\"100644\"", ",", "\"type\"", ":", "\"blob\"", ",", "\"content\"", ":", "file_contents", ",", "}", "tree", ".", "append", "(", "record", ")", "return", "tree" ]
Add a file to a tree. Args: tree A list of dicts containing info about each blob in a tree. file_path The path of the new file in the tree. file_contents The (UTF-8 encoded) contents of the new file. is_executable If ``True``, the new file will get executable permissions (0755). Otherwise, it will get 0644 permissions. Returns: The provided tree, but with the new file added.
[ "Add", "a", "file", "to", "a", "tree", "." ]
b77506275ec276ce90879bf1ea9299a79448b903
https://github.com/jtpaasch/simplygithub/blob/b77506275ec276ce90879bf1ea9299a79448b903/simplygithub/files.py#L115-L144
251,278
jtpaasch/simplygithub
simplygithub/files.py
get_files_in_branch
def get_files_in_branch(profile, branch_sha): """Get all files in a branch's tree. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. branch_sha The SHA a branch's HEAD points to. Returns: A list of dicts containing info about each blob in the tree. """ tree_sha = get_commit_tree(profile, branch_sha) files = get_files_in_tree(profile, tree_sha) tree = [prepare(x) for x in files] return tree
python
def get_files_in_branch(profile, branch_sha): """Get all files in a branch's tree. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. branch_sha The SHA a branch's HEAD points to. Returns: A list of dicts containing info about each blob in the tree. """ tree_sha = get_commit_tree(profile, branch_sha) files = get_files_in_tree(profile, tree_sha) tree = [prepare(x) for x in files] return tree
[ "def", "get_files_in_branch", "(", "profile", ",", "branch_sha", ")", ":", "tree_sha", "=", "get_commit_tree", "(", "profile", ",", "branch_sha", ")", "files", "=", "get_files_in_tree", "(", "profile", ",", "tree_sha", ")", "tree", "=", "[", "prepare", "(", "x", ")", "for", "x", "in", "files", "]", "return", "tree" ]
Get all files in a branch's tree. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. branch_sha The SHA a branch's HEAD points to. Returns: A list of dicts containing info about each blob in the tree.
[ "Get", "all", "files", "in", "a", "branch", "s", "tree", "." ]
b77506275ec276ce90879bf1ea9299a79448b903
https://github.com/jtpaasch/simplygithub/blob/b77506275ec276ce90879bf1ea9299a79448b903/simplygithub/files.py#L147-L167
251,279
jtpaasch/simplygithub
simplygithub/files.py
add_file
def add_file( profile, branch, file_path, file_contents, is_executable=False, commit_message=None): """Add a file to a branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. branch The name of a branch. file_path The path of the new file in the tree. file_contents The (UTF-8 encoded) contents of the new file. is_executable If ``True``, the new file will get executable permissions (0755). Otherwise, it will get 0644 permissions. commit_message A commit message to give to the commit. Returns: A dict with data about the branch's new ref (it includes the new SHA the branch's HEAD points to, after committing the new file). """ branch_sha = get_branch_sha(profile, branch) tree = get_files_in_branch(profile, branch_sha) new_tree = add_file_to_tree(tree, file_path, file_contents, is_executable) data = trees.create_tree(profile, new_tree) sha = data.get("sha") if not commit_message: commit_message = "Added " + file_path + "." parents = [branch_sha] commit_data = commits.create_commit(profile, commit_message, sha, parents) commit_sha = commit_data.get("sha") ref_data = refs.update_ref(profile, "heads/" + branch, commit_sha) return ref_data
python
def add_file( profile, branch, file_path, file_contents, is_executable=False, commit_message=None): """Add a file to a branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. branch The name of a branch. file_path The path of the new file in the tree. file_contents The (UTF-8 encoded) contents of the new file. is_executable If ``True``, the new file will get executable permissions (0755). Otherwise, it will get 0644 permissions. commit_message A commit message to give to the commit. Returns: A dict with data about the branch's new ref (it includes the new SHA the branch's HEAD points to, after committing the new file). """ branch_sha = get_branch_sha(profile, branch) tree = get_files_in_branch(profile, branch_sha) new_tree = add_file_to_tree(tree, file_path, file_contents, is_executable) data = trees.create_tree(profile, new_tree) sha = data.get("sha") if not commit_message: commit_message = "Added " + file_path + "." parents = [branch_sha] commit_data = commits.create_commit(profile, commit_message, sha, parents) commit_sha = commit_data.get("sha") ref_data = refs.update_ref(profile, "heads/" + branch, commit_sha) return ref_data
[ "def", "add_file", "(", "profile", ",", "branch", ",", "file_path", ",", "file_contents", ",", "is_executable", "=", "False", ",", "commit_message", "=", "None", ")", ":", "branch_sha", "=", "get_branch_sha", "(", "profile", ",", "branch", ")", "tree", "=", "get_files_in_branch", "(", "profile", ",", "branch_sha", ")", "new_tree", "=", "add_file_to_tree", "(", "tree", ",", "file_path", ",", "file_contents", ",", "is_executable", ")", "data", "=", "trees", ".", "create_tree", "(", "profile", ",", "new_tree", ")", "sha", "=", "data", ".", "get", "(", "\"sha\"", ")", "if", "not", "commit_message", ":", "commit_message", "=", "\"Added \"", "+", "file_path", "+", "\".\"", "parents", "=", "[", "branch_sha", "]", "commit_data", "=", "commits", ".", "create_commit", "(", "profile", ",", "commit_message", ",", "sha", ",", "parents", ")", "commit_sha", "=", "commit_data", ".", "get", "(", "\"sha\"", ")", "ref_data", "=", "refs", ".", "update_ref", "(", "profile", ",", "\"heads/\"", "+", "branch", ",", "commit_sha", ")", "return", "ref_data" ]
Add a file to a branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. branch The name of a branch. file_path The path of the new file in the tree. file_contents The (UTF-8 encoded) contents of the new file. is_executable If ``True``, the new file will get executable permissions (0755). Otherwise, it will get 0644 permissions. commit_message A commit message to give to the commit. Returns: A dict with data about the branch's new ref (it includes the new SHA the branch's HEAD points to, after committing the new file).
[ "Add", "a", "file", "to", "a", "branch", "." ]
b77506275ec276ce90879bf1ea9299a79448b903
https://github.com/jtpaasch/simplygithub/blob/b77506275ec276ce90879bf1ea9299a79448b903/simplygithub/files.py#L191-L239
251,280
jtpaasch/simplygithub
simplygithub/files.py
remove_file
def remove_file(profile, branch, file_path, commit_message=None): """Remove a file from a branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. branch The name of a branch. file_path The path of the file to delete. commit_message A commit message to give to the commit. Returns: A dict with data about the branch's new ref (it includes the new SHA the branch's HEAD points to, after committing the new file). """ branch_sha = get_branch_sha(profile, branch) tree = get_files_in_branch(profile, branch_sha) new_tree = remove_file_from_tree(tree, file_path) data = trees.create_tree(profile, new_tree) sha = data.get("sha") if not commit_message: commit_message = "Deleted " + file_path + "." parents = [branch_sha] commit_data = commits.create_commit(profile, commit_message, sha, parents) commit_sha = commit_data.get("sha") ref_data = refs.update_ref(profile, "heads/" + branch, commit_sha) return ref_data
python
def remove_file(profile, branch, file_path, commit_message=None): """Remove a file from a branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. branch The name of a branch. file_path The path of the file to delete. commit_message A commit message to give to the commit. Returns: A dict with data about the branch's new ref (it includes the new SHA the branch's HEAD points to, after committing the new file). """ branch_sha = get_branch_sha(profile, branch) tree = get_files_in_branch(profile, branch_sha) new_tree = remove_file_from_tree(tree, file_path) data = trees.create_tree(profile, new_tree) sha = data.get("sha") if not commit_message: commit_message = "Deleted " + file_path + "." parents = [branch_sha] commit_data = commits.create_commit(profile, commit_message, sha, parents) commit_sha = commit_data.get("sha") ref_data = refs.update_ref(profile, "heads/" + branch, commit_sha) return ref_data
[ "def", "remove_file", "(", "profile", ",", "branch", ",", "file_path", ",", "commit_message", "=", "None", ")", ":", "branch_sha", "=", "get_branch_sha", "(", "profile", ",", "branch", ")", "tree", "=", "get_files_in_branch", "(", "profile", ",", "branch_sha", ")", "new_tree", "=", "remove_file_from_tree", "(", "tree", ",", "file_path", ")", "data", "=", "trees", ".", "create_tree", "(", "profile", ",", "new_tree", ")", "sha", "=", "data", ".", "get", "(", "\"sha\"", ")", "if", "not", "commit_message", ":", "commit_message", "=", "\"Deleted \"", "+", "file_path", "+", "\".\"", "parents", "=", "[", "branch_sha", "]", "commit_data", "=", "commits", ".", "create_commit", "(", "profile", ",", "commit_message", ",", "sha", ",", "parents", ")", "commit_sha", "=", "commit_data", ".", "get", "(", "\"sha\"", ")", "ref_data", "=", "refs", ".", "update_ref", "(", "profile", ",", "\"heads/\"", "+", "branch", ",", "commit_sha", ")", "return", "ref_data" ]
Remove a file from a branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. branch The name of a branch. file_path The path of the file to delete. commit_message A commit message to give to the commit. Returns: A dict with data about the branch's new ref (it includes the new SHA the branch's HEAD points to, after committing the new file).
[ "Remove", "a", "file", "from", "a", "branch", "." ]
b77506275ec276ce90879bf1ea9299a79448b903
https://github.com/jtpaasch/simplygithub/blob/b77506275ec276ce90879bf1ea9299a79448b903/simplygithub/files.py#L242-L277
251,281
jtpaasch/simplygithub
simplygithub/files.py
get_file
def get_file(profile, branch, file_path): """Get a file from a branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. branch The name of a branch. file_path The path of the file to fetch. Returns: The (UTF-8 encoded) content of the file, as a string. """ branch_sha = get_branch_sha(profile, branch) tree = get_files_in_branch(profile, branch_sha) match = None for item in tree: if item.get("path") == file_path: match = item break file_sha = match.get("sha") blob = blobs.get_blob(profile, file_sha) content = blob.get("content") decoded_content = b64decode(content) return decoded_content.decode("utf-8")
python
def get_file(profile, branch, file_path): """Get a file from a branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. branch The name of a branch. file_path The path of the file to fetch. Returns: The (UTF-8 encoded) content of the file, as a string. """ branch_sha = get_branch_sha(profile, branch) tree = get_files_in_branch(profile, branch_sha) match = None for item in tree: if item.get("path") == file_path: match = item break file_sha = match.get("sha") blob = blobs.get_blob(profile, file_sha) content = blob.get("content") decoded_content = b64decode(content) return decoded_content.decode("utf-8")
[ "def", "get_file", "(", "profile", ",", "branch", ",", "file_path", ")", ":", "branch_sha", "=", "get_branch_sha", "(", "profile", ",", "branch", ")", "tree", "=", "get_files_in_branch", "(", "profile", ",", "branch_sha", ")", "match", "=", "None", "for", "item", "in", "tree", ":", "if", "item", ".", "get", "(", "\"path\"", ")", "==", "file_path", ":", "match", "=", "item", "break", "file_sha", "=", "match", ".", "get", "(", "\"sha\"", ")", "blob", "=", "blobs", ".", "get_blob", "(", "profile", ",", "file_sha", ")", "content", "=", "blob", ".", "get", "(", "\"content\"", ")", "decoded_content", "=", "b64decode", "(", "content", ")", "return", "decoded_content", ".", "decode", "(", "\"utf-8\"", ")" ]
Get a file from a branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. branch The name of a branch. file_path The path of the file to fetch. Returns: The (UTF-8 encoded) content of the file, as a string.
[ "Get", "a", "file", "from", "a", "branch", "." ]
b77506275ec276ce90879bf1ea9299a79448b903
https://github.com/jtpaasch/simplygithub/blob/b77506275ec276ce90879bf1ea9299a79448b903/simplygithub/files.py#L280-L311
251,282
djtaylor/python-lsbinit
lsbinit/lock.py
_LSBLockHandler.make
def make(self): """ Make the lock file. """ try: # Create the lock file self.mkfile(self.lock_file) except Exception as e: self.die('Failed to generate lock file: {}'.format(str(e)))
python
def make(self): """ Make the lock file. """ try: # Create the lock file self.mkfile(self.lock_file) except Exception as e: self.die('Failed to generate lock file: {}'.format(str(e)))
[ "def", "make", "(", "self", ")", ":", "try", ":", "# Create the lock file", "self", ".", "mkfile", "(", "self", ".", "lock_file", ")", "except", "Exception", "as", "e", ":", "self", ".", "die", "(", "'Failed to generate lock file: {}'", ".", "format", "(", "str", "(", "e", ")", ")", ")" ]
Make the lock file.
[ "Make", "the", "lock", "file", "." ]
a41fc551226f61ac2bf1b8b0f3f5395db85e75a2
https://github.com/djtaylor/python-lsbinit/blob/a41fc551226f61ac2bf1b8b0f3f5395db85e75a2/lsbinit/lock.py#L36-L45
251,283
jkenlooper/chill
src/chill/api.py
_short_circuit
def _short_circuit(value=None): """ Add the `value` to the `collection` by modifying the collection to be either a dict or list depending on what is already in the collection and value. Returns the collection with the value added to it. Clean up by removing single item array and single key dict. ['abc'] -> 'abc' [['abc']] -> 'abc' [{'abc':123},{'def':456}] -> {'abc':123,'def':456} [{'abc':123},{'abc':456}] -> [{'abc':123,'abc':456}] # skip for same set keys [[{'abc':123},{'abc':456}]] -> [{'abc':123,'abc':456}] """ if not isinstance(value, list): return value if len(value) == 0: return value if len(value) == 1: if not isinstance(value[0], list): return value[0] else: if len(value[0]) == 1: return value[0][0] else: return value[0] else: value = filter(None, value) # Only checking first item and assumin all others are same type if isinstance(value[0], dict): if set(value[0].keys()) == set(value[1].keys()): return value elif max([len(x.keys()) for x in value]) == 1: newvalue = {} for v in value: key = v.keys()[0] newvalue[key] = v[key] return newvalue else: return value else: return value
python
def _short_circuit(value=None): """ Add the `value` to the `collection` by modifying the collection to be either a dict or list depending on what is already in the collection and value. Returns the collection with the value added to it. Clean up by removing single item array and single key dict. ['abc'] -> 'abc' [['abc']] -> 'abc' [{'abc':123},{'def':456}] -> {'abc':123,'def':456} [{'abc':123},{'abc':456}] -> [{'abc':123,'abc':456}] # skip for same set keys [[{'abc':123},{'abc':456}]] -> [{'abc':123,'abc':456}] """ if not isinstance(value, list): return value if len(value) == 0: return value if len(value) == 1: if not isinstance(value[0], list): return value[0] else: if len(value[0]) == 1: return value[0][0] else: return value[0] else: value = filter(None, value) # Only checking first item and assumin all others are same type if isinstance(value[0], dict): if set(value[0].keys()) == set(value[1].keys()): return value elif max([len(x.keys()) for x in value]) == 1: newvalue = {} for v in value: key = v.keys()[0] newvalue[key] = v[key] return newvalue else: return value else: return value
[ "def", "_short_circuit", "(", "value", "=", "None", ")", ":", "if", "not", "isinstance", "(", "value", ",", "list", ")", ":", "return", "value", "if", "len", "(", "value", ")", "==", "0", ":", "return", "value", "if", "len", "(", "value", ")", "==", "1", ":", "if", "not", "isinstance", "(", "value", "[", "0", "]", ",", "list", ")", ":", "return", "value", "[", "0", "]", "else", ":", "if", "len", "(", "value", "[", "0", "]", ")", "==", "1", ":", "return", "value", "[", "0", "]", "[", "0", "]", "else", ":", "return", "value", "[", "0", "]", "else", ":", "value", "=", "filter", "(", "None", ",", "value", ")", "# Only checking first item and assumin all others are same type", "if", "isinstance", "(", "value", "[", "0", "]", ",", "dict", ")", ":", "if", "set", "(", "value", "[", "0", "]", ".", "keys", "(", ")", ")", "==", "set", "(", "value", "[", "1", "]", ".", "keys", "(", ")", ")", ":", "return", "value", "elif", "max", "(", "[", "len", "(", "x", ".", "keys", "(", ")", ")", "for", "x", "in", "value", "]", ")", "==", "1", ":", "newvalue", "=", "{", "}", "for", "v", "in", "value", ":", "key", "=", "v", ".", "keys", "(", ")", "[", "0", "]", "newvalue", "[", "key", "]", "=", "v", "[", "key", "]", "return", "newvalue", "else", ":", "return", "value", "else", ":", "return", "value" ]
Add the `value` to the `collection` by modifying the collection to be either a dict or list depending on what is already in the collection and value. Returns the collection with the value added to it. Clean up by removing single item array and single key dict. ['abc'] -> 'abc' [['abc']] -> 'abc' [{'abc':123},{'def':456}] -> {'abc':123,'def':456} [{'abc':123},{'abc':456}] -> [{'abc':123,'abc':456}] # skip for same set keys [[{'abc':123},{'abc':456}]] -> [{'abc':123,'abc':456}]
[ "Add", "the", "value", "to", "the", "collection", "by", "modifying", "the", "collection", "to", "be", "either", "a", "dict", "or", "list", "depending", "on", "what", "is", "already", "in", "the", "collection", "and", "value", ".", "Returns", "the", "collection", "with", "the", "value", "added", "to", "it", "." ]
35360c17c2a3b769ecb5406c6dabcf4cc70bd76f
https://github.com/jkenlooper/chill/blob/35360c17c2a3b769ecb5406c6dabcf4cc70bd76f/src/chill/api.py#L8-L49
251,284
jkenlooper/chill
src/chill/api.py
_query
def _query(_node_id, value=None, **kw): "Look up value by using Query table" query_result = [] try: query_result = db.execute(text(fetch_query_string('select_query_from_node.sql')), **kw).fetchall() except DatabaseError as err: current_app.logger.error("DatabaseError: %s, %s", err, kw) return value #current_app.logger.debug("queries kw: %s", kw) #current_app.logger.debug("queries value: %s", value) current_app.logger.debug("queries: %s", query_result) if query_result: values = [] for query_name in [x['name'] for x in query_result]: if query_name: result = [] try: current_app.logger.debug("query_name: %s", query_name) #current_app.logger.debug("kw: %s", kw) # Query string can be insert or select here #statement = text(fetch_query_string(query_name)) #params = [x.key for x in statement.params().get_children()] #skw = {key: kw[key] for key in params} #result = db.execute(statement, **skw) result = db.execute(text(fetch_query_string(query_name)), **kw) current_app.logger.debug("result query: %s", result.keys()) except (DatabaseError, StatementError) as err: current_app.logger.error("DatabaseError (%s) %s: %s", query_name, kw, err) if result and result.returns_rows: result = result.fetchall() #values.append(([[dict(zip(result.keys(), x)) for x in result]], result.keys())) #values.append((result.fetchall(), result.keys())) #current_app.logger.debug("fetchall: %s", values) if len(result) == 0: values.append(([], [])) else: current_app.logger.debug("result: %s", result) # There may be more results, but only interested in the # first one. Use the older rowify method for now. # TODO: use case for rowify? values.append(rowify(result, [(x, None) for x in result[0].keys()])) #current_app.logger.debug("fetchone: %s", values) value = values #current_app.logger.debug("value: %s", value) return value
python
def _query(_node_id, value=None, **kw): "Look up value by using Query table" query_result = [] try: query_result = db.execute(text(fetch_query_string('select_query_from_node.sql')), **kw).fetchall() except DatabaseError as err: current_app.logger.error("DatabaseError: %s, %s", err, kw) return value #current_app.logger.debug("queries kw: %s", kw) #current_app.logger.debug("queries value: %s", value) current_app.logger.debug("queries: %s", query_result) if query_result: values = [] for query_name in [x['name'] for x in query_result]: if query_name: result = [] try: current_app.logger.debug("query_name: %s", query_name) #current_app.logger.debug("kw: %s", kw) # Query string can be insert or select here #statement = text(fetch_query_string(query_name)) #params = [x.key for x in statement.params().get_children()] #skw = {key: kw[key] for key in params} #result = db.execute(statement, **skw) result = db.execute(text(fetch_query_string(query_name)), **kw) current_app.logger.debug("result query: %s", result.keys()) except (DatabaseError, StatementError) as err: current_app.logger.error("DatabaseError (%s) %s: %s", query_name, kw, err) if result and result.returns_rows: result = result.fetchall() #values.append(([[dict(zip(result.keys(), x)) for x in result]], result.keys())) #values.append((result.fetchall(), result.keys())) #current_app.logger.debug("fetchall: %s", values) if len(result) == 0: values.append(([], [])) else: current_app.logger.debug("result: %s", result) # There may be more results, but only interested in the # first one. Use the older rowify method for now. # TODO: use case for rowify? values.append(rowify(result, [(x, None) for x in result[0].keys()])) #current_app.logger.debug("fetchone: %s", values) value = values #current_app.logger.debug("value: %s", value) return value
[ "def", "_query", "(", "_node_id", ",", "value", "=", "None", ",", "*", "*", "kw", ")", ":", "query_result", "=", "[", "]", "try", ":", "query_result", "=", "db", ".", "execute", "(", "text", "(", "fetch_query_string", "(", "'select_query_from_node.sql'", ")", ")", ",", "*", "*", "kw", ")", ".", "fetchall", "(", ")", "except", "DatabaseError", "as", "err", ":", "current_app", ".", "logger", ".", "error", "(", "\"DatabaseError: %s, %s\"", ",", "err", ",", "kw", ")", "return", "value", "#current_app.logger.debug(\"queries kw: %s\", kw)", "#current_app.logger.debug(\"queries value: %s\", value)", "current_app", ".", "logger", ".", "debug", "(", "\"queries: %s\"", ",", "query_result", ")", "if", "query_result", ":", "values", "=", "[", "]", "for", "query_name", "in", "[", "x", "[", "'name'", "]", "for", "x", "in", "query_result", "]", ":", "if", "query_name", ":", "result", "=", "[", "]", "try", ":", "current_app", ".", "logger", ".", "debug", "(", "\"query_name: %s\"", ",", "query_name", ")", "#current_app.logger.debug(\"kw: %s\", kw)", "# Query string can be insert or select here", "#statement = text(fetch_query_string(query_name))", "#params = [x.key for x in statement.params().get_children()]", "#skw = {key: kw[key] for key in params}", "#result = db.execute(statement, **skw)", "result", "=", "db", ".", "execute", "(", "text", "(", "fetch_query_string", "(", "query_name", ")", ")", ",", "*", "*", "kw", ")", "current_app", ".", "logger", ".", "debug", "(", "\"result query: %s\"", ",", "result", ".", "keys", "(", ")", ")", "except", "(", "DatabaseError", ",", "StatementError", ")", "as", "err", ":", "current_app", ".", "logger", ".", "error", "(", "\"DatabaseError (%s) %s: %s\"", ",", "query_name", ",", "kw", ",", "err", ")", "if", "result", "and", "result", ".", "returns_rows", ":", "result", "=", "result", ".", "fetchall", "(", ")", "#values.append(([[dict(zip(result.keys(), x)) for x in result]], result.keys()))", "#values.append((result.fetchall(), result.keys()))", "#current_app.logger.debug(\"fetchall: %s\", values)", "if", "len", "(", "result", ")", "==", "0", ":", "values", ".", "append", "(", "(", "[", "]", ",", "[", "]", ")", ")", "else", ":", "current_app", ".", "logger", ".", "debug", "(", "\"result: %s\"", ",", "result", ")", "# There may be more results, but only interested in the", "# first one. Use the older rowify method for now.", "# TODO: use case for rowify?", "values", ".", "append", "(", "rowify", "(", "result", ",", "[", "(", "x", ",", "None", ")", "for", "x", "in", "result", "[", "0", "]", ".", "keys", "(", ")", "]", ")", ")", "#current_app.logger.debug(\"fetchone: %s\", values)", "value", "=", "values", "#current_app.logger.debug(\"value: %s\", value)", "return", "value" ]
Look up value by using Query table
[ "Look", "up", "value", "by", "using", "Query", "table" ]
35360c17c2a3b769ecb5406c6dabcf4cc70bd76f
https://github.com/jkenlooper/chill/blob/35360c17c2a3b769ecb5406c6dabcf4cc70bd76f/src/chill/api.py#L53-L97
251,285
jkenlooper/chill
src/chill/api.py
_template
def _template(node_id, value=None): "Check if a template is assigned to it and render that with the value" result = [] select_template_from_node = fetch_query_string('select_template_from_node.sql') try: result = db.execute(text(select_template_from_node), node_id=node_id) template_result = result.fetchone() result.close() if template_result and template_result['name']: template = template_result['name'] if isinstance(value, dict): return render_template(template, **value) else: return render_template(template, value=value) except DatabaseError as err: current_app.logger.error("DatabaseError: %s", err) # No template assigned to this node so just return the value return value
python
def _template(node_id, value=None): "Check if a template is assigned to it and render that with the value" result = [] select_template_from_node = fetch_query_string('select_template_from_node.sql') try: result = db.execute(text(select_template_from_node), node_id=node_id) template_result = result.fetchone() result.close() if template_result and template_result['name']: template = template_result['name'] if isinstance(value, dict): return render_template(template, **value) else: return render_template(template, value=value) except DatabaseError as err: current_app.logger.error("DatabaseError: %s", err) # No template assigned to this node so just return the value return value
[ "def", "_template", "(", "node_id", ",", "value", "=", "None", ")", ":", "result", "=", "[", "]", "select_template_from_node", "=", "fetch_query_string", "(", "'select_template_from_node.sql'", ")", "try", ":", "result", "=", "db", ".", "execute", "(", "text", "(", "select_template_from_node", ")", ",", "node_id", "=", "node_id", ")", "template_result", "=", "result", ".", "fetchone", "(", ")", "result", ".", "close", "(", ")", "if", "template_result", "and", "template_result", "[", "'name'", "]", ":", "template", "=", "template_result", "[", "'name'", "]", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "return", "render_template", "(", "template", ",", "*", "*", "value", ")", "else", ":", "return", "render_template", "(", "template", ",", "value", "=", "value", ")", "except", "DatabaseError", "as", "err", ":", "current_app", ".", "logger", ".", "error", "(", "\"DatabaseError: %s\"", ",", "err", ")", "# No template assigned to this node so just return the value", "return", "value" ]
Check if a template is assigned to it and render that with the value
[ "Check", "if", "a", "template", "is", "assigned", "to", "it", "and", "render", "that", "with", "the", "value" ]
35360c17c2a3b769ecb5406c6dabcf4cc70bd76f
https://github.com/jkenlooper/chill/blob/35360c17c2a3b769ecb5406c6dabcf4cc70bd76f/src/chill/api.py#L99-L118
251,286
jkenlooper/chill
src/chill/api.py
render_node
def render_node(_node_id, value=None, noderequest={}, **kw): "Recursively render a node's value" if value == None: kw.update( noderequest ) results = _query(_node_id, **kw) current_app.logger.debug("results: %s", results) if results: values = [] for (result, cols) in results: if set(cols) == set(['node_id', 'name', 'value']): for subresult in result: #if subresult.get('name') == kw.get('name'): # This is a link node current_app.logger.debug("sub: %s", subresult) name = subresult['name'] if noderequest.get('_no_template'): # For debugging or just simply viewing with the # operate script we append the node_id to the name # of each. This doesn't work with templates. name = "{0} ({1})".format(name, subresult['node_id']) values.append( {name: render_node( subresult['node_id'], noderequest=noderequest, **subresult )} ) #elif 'node_id' and 'name' in cols: # for subresult in result: # current_app.logger.debug("sub2: %s", subresult) # values.append( {subresult.get('name'): render_node( subresult.get('node_id'), **subresult )} ) else: values.append( result ) value = values value = _short_circuit(value) if not noderequest.get('_no_template'): value = _template(_node_id, value) return value
python
def render_node(_node_id, value=None, noderequest={}, **kw): "Recursively render a node's value" if value == None: kw.update( noderequest ) results = _query(_node_id, **kw) current_app.logger.debug("results: %s", results) if results: values = [] for (result, cols) in results: if set(cols) == set(['node_id', 'name', 'value']): for subresult in result: #if subresult.get('name') == kw.get('name'): # This is a link node current_app.logger.debug("sub: %s", subresult) name = subresult['name'] if noderequest.get('_no_template'): # For debugging or just simply viewing with the # operate script we append the node_id to the name # of each. This doesn't work with templates. name = "{0} ({1})".format(name, subresult['node_id']) values.append( {name: render_node( subresult['node_id'], noderequest=noderequest, **subresult )} ) #elif 'node_id' and 'name' in cols: # for subresult in result: # current_app.logger.debug("sub2: %s", subresult) # values.append( {subresult.get('name'): render_node( subresult.get('node_id'), **subresult )} ) else: values.append( result ) value = values value = _short_circuit(value) if not noderequest.get('_no_template'): value = _template(_node_id, value) return value
[ "def", "render_node", "(", "_node_id", ",", "value", "=", "None", ",", "noderequest", "=", "{", "}", ",", "*", "*", "kw", ")", ":", "if", "value", "==", "None", ":", "kw", ".", "update", "(", "noderequest", ")", "results", "=", "_query", "(", "_node_id", ",", "*", "*", "kw", ")", "current_app", ".", "logger", ".", "debug", "(", "\"results: %s\"", ",", "results", ")", "if", "results", ":", "values", "=", "[", "]", "for", "(", "result", ",", "cols", ")", "in", "results", ":", "if", "set", "(", "cols", ")", "==", "set", "(", "[", "'node_id'", ",", "'name'", ",", "'value'", "]", ")", ":", "for", "subresult", "in", "result", ":", "#if subresult.get('name') == kw.get('name'):", "# This is a link node", "current_app", ".", "logger", ".", "debug", "(", "\"sub: %s\"", ",", "subresult", ")", "name", "=", "subresult", "[", "'name'", "]", "if", "noderequest", ".", "get", "(", "'_no_template'", ")", ":", "# For debugging or just simply viewing with the", "# operate script we append the node_id to the name", "# of each. This doesn't work with templates.", "name", "=", "\"{0} ({1})\"", ".", "format", "(", "name", ",", "subresult", "[", "'node_id'", "]", ")", "values", ".", "append", "(", "{", "name", ":", "render_node", "(", "subresult", "[", "'node_id'", "]", ",", "noderequest", "=", "noderequest", ",", "*", "*", "subresult", ")", "}", ")", "#elif 'node_id' and 'name' in cols:", "# for subresult in result:", "# current_app.logger.debug(\"sub2: %s\", subresult)", "# values.append( {subresult.get('name'): render_node( subresult.get('node_id'), **subresult )} )", "else", ":", "values", ".", "append", "(", "result", ")", "value", "=", "values", "value", "=", "_short_circuit", "(", "value", ")", "if", "not", "noderequest", ".", "get", "(", "'_no_template'", ")", ":", "value", "=", "_template", "(", "_node_id", ",", "value", ")", "return", "value" ]
Recursively render a node's value
[ "Recursively", "render", "a", "node", "s", "value" ]
35360c17c2a3b769ecb5406c6dabcf4cc70bd76f
https://github.com/jkenlooper/chill/blob/35360c17c2a3b769ecb5406c6dabcf4cc70bd76f/src/chill/api.py#L120-L154
251,287
heikomuller/sco-client
scocli/experiment.py
ExperimentHandle.create
def create(url, name, subject_id, image_group_id, properties): """Create a new experiment using the given SCO-API create experiment Url. Parameters ---------- url : string Url to POST experiment create request name : string User-defined name for experiment subject_id : string Unique identifier for subject at given SCO-API image_group_id : string Unique identifier for image group at given SCO-API properties : Dictionary Set of additional properties for created experiment. Argument may be None. Given name will override name property in this set (if present). Returns ------- string Url of created experiment resource """ # Create list of key,value-pairs representing experiment properties for # request. The given name overrides the name in properties (if present). obj_props = [{'key':'name','value':name}] if not properties is None: # Catch TypeErrors if properties is not a list. try: for key in properties: if key != 'name': obj_props.append({'key':key, 'value':properties[key]}) except TypeError as ex: raise ValueError('invalid property set') # Create request body and send POST request to given Url body = { 'subject' : subject_id, 'images' : image_group_id, 'properties' : obj_props } try: req = urllib2.Request(url) req.add_header('Content-Type', 'application/json') response = urllib2.urlopen(req, json.dumps(body)) except urllib2.URLError as ex: raise ValueError(str(ex)) # Get experiment self reference from successful response return references_to_dict(json.load(response)['links'])[REF_SELF]
python
def create(url, name, subject_id, image_group_id, properties): """Create a new experiment using the given SCO-API create experiment Url. Parameters ---------- url : string Url to POST experiment create request name : string User-defined name for experiment subject_id : string Unique identifier for subject at given SCO-API image_group_id : string Unique identifier for image group at given SCO-API properties : Dictionary Set of additional properties for created experiment. Argument may be None. Given name will override name property in this set (if present). Returns ------- string Url of created experiment resource """ # Create list of key,value-pairs representing experiment properties for # request. The given name overrides the name in properties (if present). obj_props = [{'key':'name','value':name}] if not properties is None: # Catch TypeErrors if properties is not a list. try: for key in properties: if key != 'name': obj_props.append({'key':key, 'value':properties[key]}) except TypeError as ex: raise ValueError('invalid property set') # Create request body and send POST request to given Url body = { 'subject' : subject_id, 'images' : image_group_id, 'properties' : obj_props } try: req = urllib2.Request(url) req.add_header('Content-Type', 'application/json') response = urllib2.urlopen(req, json.dumps(body)) except urllib2.URLError as ex: raise ValueError(str(ex)) # Get experiment self reference from successful response return references_to_dict(json.load(response)['links'])[REF_SELF]
[ "def", "create", "(", "url", ",", "name", ",", "subject_id", ",", "image_group_id", ",", "properties", ")", ":", "# Create list of key,value-pairs representing experiment properties for", "# request. The given name overrides the name in properties (if present).", "obj_props", "=", "[", "{", "'key'", ":", "'name'", ",", "'value'", ":", "name", "}", "]", "if", "not", "properties", "is", "None", ":", "# Catch TypeErrors if properties is not a list.", "try", ":", "for", "key", "in", "properties", ":", "if", "key", "!=", "'name'", ":", "obj_props", ".", "append", "(", "{", "'key'", ":", "key", ",", "'value'", ":", "properties", "[", "key", "]", "}", ")", "except", "TypeError", "as", "ex", ":", "raise", "ValueError", "(", "'invalid property set'", ")", "# Create request body and send POST request to given Url", "body", "=", "{", "'subject'", ":", "subject_id", ",", "'images'", ":", "image_group_id", ",", "'properties'", ":", "obj_props", "}", "try", ":", "req", "=", "urllib2", ".", "Request", "(", "url", ")", "req", ".", "add_header", "(", "'Content-Type'", ",", "'application/json'", ")", "response", "=", "urllib2", ".", "urlopen", "(", "req", ",", "json", ".", "dumps", "(", "body", ")", ")", "except", "urllib2", ".", "URLError", "as", "ex", ":", "raise", "ValueError", "(", "str", "(", "ex", ")", ")", "# Get experiment self reference from successful response", "return", "references_to_dict", "(", "json", ".", "load", "(", "response", ")", "[", "'links'", "]", ")", "[", "REF_SELF", "]" ]
Create a new experiment using the given SCO-API create experiment Url. Parameters ---------- url : string Url to POST experiment create request name : string User-defined name for experiment subject_id : string Unique identifier for subject at given SCO-API image_group_id : string Unique identifier for image group at given SCO-API properties : Dictionary Set of additional properties for created experiment. Argument may be None. Given name will override name property in this set (if present). Returns ------- string Url of created experiment resource
[ "Create", "a", "new", "experiment", "using", "the", "given", "SCO", "-", "API", "create", "experiment", "Url", "." ]
c4afab71297f73003379bba4c1679be9dcf7cef8
https://github.com/heikomuller/sco-client/blob/c4afab71297f73003379bba4c1679be9dcf7cef8/scocli/experiment.py#L62-L108
251,288
heikomuller/sco-client
scocli/experiment.py
ExperimentHandle.runs
def runs(self, offset=0, limit=-1, properties=None): """Get a list of run descriptors associated with this expriment. Parameters ---------- offset : int, optional Starting offset for returned list items limit : int, optional Limit the number of items in the result properties : List(string) List of additional object properties to be included for items in the result Returns ------- List(scoserv.ModelRunDescriptor) List of model run descriptors """ return get_run_listing( self.runs_url, offset=offset, limit=limit, properties=properties )
python
def runs(self, offset=0, limit=-1, properties=None): """Get a list of run descriptors associated with this expriment. Parameters ---------- offset : int, optional Starting offset for returned list items limit : int, optional Limit the number of items in the result properties : List(string) List of additional object properties to be included for items in the result Returns ------- List(scoserv.ModelRunDescriptor) List of model run descriptors """ return get_run_listing( self.runs_url, offset=offset, limit=limit, properties=properties )
[ "def", "runs", "(", "self", ",", "offset", "=", "0", ",", "limit", "=", "-", "1", ",", "properties", "=", "None", ")", ":", "return", "get_run_listing", "(", "self", ".", "runs_url", ",", "offset", "=", "offset", ",", "limit", "=", "limit", ",", "properties", "=", "properties", ")" ]
Get a list of run descriptors associated with this expriment. Parameters ---------- offset : int, optional Starting offset for returned list items limit : int, optional Limit the number of items in the result properties : List(string) List of additional object properties to be included for items in the result Returns ------- List(scoserv.ModelRunDescriptor) List of model run descriptors
[ "Get", "a", "list", "of", "run", "descriptors", "associated", "with", "this", "expriment", "." ]
c4afab71297f73003379bba4c1679be9dcf7cef8
https://github.com/heikomuller/sco-client/blob/c4afab71297f73003379bba4c1679be9dcf7cef8/scocli/experiment.py#L163-L186
251,289
hweickert/itermate
itermate/__init__.py
imapchain
def imapchain(*a, **kwa): """ Like map but also chains the results. """ imap_results = map( *a, **kwa ) return itertools.chain( *imap_results )
python
def imapchain(*a, **kwa): """ Like map but also chains the results. """ imap_results = map( *a, **kwa ) return itertools.chain( *imap_results )
[ "def", "imapchain", "(", "*", "a", ",", "*", "*", "kwa", ")", ":", "imap_results", "=", "map", "(", "*", "a", ",", "*", "*", "kwa", ")", "return", "itertools", ".", "chain", "(", "*", "imap_results", ")" ]
Like map but also chains the results.
[ "Like", "map", "but", "also", "chains", "the", "results", "." ]
501cb4c31c6435b2f99703eb516aca2886d513b6
https://github.com/hweickert/itermate/blob/501cb4c31c6435b2f99703eb516aca2886d513b6/itermate/__init__.py#L13-L17
251,290
hweickert/itermate
itermate/__init__.py
iskip
def iskip( value, iterable ): """ Skips all values in 'iterable' matching the given 'value'. """ for e in iterable: if value is None: if e is None: continue elif e == value: continue yield e
python
def iskip( value, iterable ): """ Skips all values in 'iterable' matching the given 'value'. """ for e in iterable: if value is None: if e is None: continue elif e == value: continue yield e
[ "def", "iskip", "(", "value", ",", "iterable", ")", ":", "for", "e", "in", "iterable", ":", "if", "value", "is", "None", ":", "if", "e", "is", "None", ":", "continue", "elif", "e", "==", "value", ":", "continue", "yield", "e" ]
Skips all values in 'iterable' matching the given 'value'.
[ "Skips", "all", "values", "in", "iterable", "matching", "the", "given", "value", "." ]
501cb4c31c6435b2f99703eb516aca2886d513b6
https://github.com/hweickert/itermate/blob/501cb4c31c6435b2f99703eb516aca2886d513b6/itermate/__init__.py#L33-L42
251,291
rorr73/LifeSOSpy
lifesospy/command.py
Command.format
def format(self, password: str = '') -> str: """Format command along with any arguments, ready to be sent.""" return MARKER_START + \ self.name + \ self.action + \ self.args + \ password + \ MARKER_END
python
def format(self, password: str = '') -> str: """Format command along with any arguments, ready to be sent.""" return MARKER_START + \ self.name + \ self.action + \ self.args + \ password + \ MARKER_END
[ "def", "format", "(", "self", ",", "password", ":", "str", "=", "''", ")", "->", "str", ":", "return", "MARKER_START", "+", "self", ".", "name", "+", "self", ".", "action", "+", "self", ".", "args", "+", "password", "+", "MARKER_END" ]
Format command along with any arguments, ready to be sent.
[ "Format", "command", "along", "with", "any", "arguments", "ready", "to", "be", "sent", "." ]
62360fbab2e90bf04d52b547093bdab2d4e389b4
https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/command.py#L38-L45
251,292
rackerlabs/silverberg
scripts/python-lint.py
lint
def lint(to_lint): """ Run all linters against a list of files. :param to_lint: a list of files to lint. """ exit_code = 0 for linter, options in (('pyflakes', []), ('pep8', [])): try: output = local[linter](*(options + to_lint)) except commands.ProcessExecutionError as e: output = e.stdout if output: exit_code = 1 print "{0} Errors:".format(linter) print output output = hacked_pep257(to_lint) if output: exit_code = 1 print "Docstring Errors:".format(linter.upper()) print output sys.exit(exit_code)
python
def lint(to_lint): """ Run all linters against a list of files. :param to_lint: a list of files to lint. """ exit_code = 0 for linter, options in (('pyflakes', []), ('pep8', [])): try: output = local[linter](*(options + to_lint)) except commands.ProcessExecutionError as e: output = e.stdout if output: exit_code = 1 print "{0} Errors:".format(linter) print output output = hacked_pep257(to_lint) if output: exit_code = 1 print "Docstring Errors:".format(linter.upper()) print output sys.exit(exit_code)
[ "def", "lint", "(", "to_lint", ")", ":", "exit_code", "=", "0", "for", "linter", ",", "options", "in", "(", "(", "'pyflakes'", ",", "[", "]", ")", ",", "(", "'pep8'", ",", "[", "]", ")", ")", ":", "try", ":", "output", "=", "local", "[", "linter", "]", "(", "*", "(", "options", "+", "to_lint", ")", ")", "except", "commands", ".", "ProcessExecutionError", "as", "e", ":", "output", "=", "e", ".", "stdout", "if", "output", ":", "exit_code", "=", "1", "print", "\"{0} Errors:\"", ".", "format", "(", "linter", ")", "print", "output", "output", "=", "hacked_pep257", "(", "to_lint", ")", "if", "output", ":", "exit_code", "=", "1", "print", "\"Docstring Errors:\"", ".", "format", "(", "linter", ".", "upper", "(", ")", ")", "print", "output", "sys", ".", "exit", "(", "exit_code", ")" ]
Run all linters against a list of files. :param to_lint: a list of files to lint.
[ "Run", "all", "linters", "against", "a", "list", "of", "files", "." ]
c6fae78923a019f1615e9516ab30fa105c72a542
https://github.com/rackerlabs/silverberg/blob/c6fae78923a019f1615e9516ab30fa105c72a542/scripts/python-lint.py#L24-L49
251,293
rackerlabs/silverberg
scripts/python-lint.py
hacked_pep257
def hacked_pep257(to_lint): """ Check for the presence of docstrings, but ignore some of the options """ def ignore(*args, **kwargs): pass pep257.check_blank_before_after_class = ignore pep257.check_blank_after_last_paragraph = ignore pep257.check_blank_after_summary = ignore pep257.check_ends_with_period = ignore pep257.check_one_liners = ignore pep257.check_imperative_mood = ignore original_check_return_type = pep257.check_return_type def better_check_return_type(def_docstring, context, is_script): """ Ignore private methods """ def_name = context.split()[1] if def_name.startswith('_') and not def_name.endswith('__'): original_check_return_type(def_docstring, context, is_script) pep257.check_return_type = better_check_return_type errors = [] for filename in to_lint: with open(filename) as f: source = f.read() if source: errors.extend(pep257.check_source(source, filename)) return '\n'.join([str(error) for error in sorted(errors)])
python
def hacked_pep257(to_lint): """ Check for the presence of docstrings, but ignore some of the options """ def ignore(*args, **kwargs): pass pep257.check_blank_before_after_class = ignore pep257.check_blank_after_last_paragraph = ignore pep257.check_blank_after_summary = ignore pep257.check_ends_with_period = ignore pep257.check_one_liners = ignore pep257.check_imperative_mood = ignore original_check_return_type = pep257.check_return_type def better_check_return_type(def_docstring, context, is_script): """ Ignore private methods """ def_name = context.split()[1] if def_name.startswith('_') and not def_name.endswith('__'): original_check_return_type(def_docstring, context, is_script) pep257.check_return_type = better_check_return_type errors = [] for filename in to_lint: with open(filename) as f: source = f.read() if source: errors.extend(pep257.check_source(source, filename)) return '\n'.join([str(error) for error in sorted(errors)])
[ "def", "hacked_pep257", "(", "to_lint", ")", ":", "def", "ignore", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "pass", "pep257", ".", "check_blank_before_after_class", "=", "ignore", "pep257", ".", "check_blank_after_last_paragraph", "=", "ignore", "pep257", ".", "check_blank_after_summary", "=", "ignore", "pep257", ".", "check_ends_with_period", "=", "ignore", "pep257", ".", "check_one_liners", "=", "ignore", "pep257", ".", "check_imperative_mood", "=", "ignore", "original_check_return_type", "=", "pep257", ".", "check_return_type", "def", "better_check_return_type", "(", "def_docstring", ",", "context", ",", "is_script", ")", ":", "\"\"\"\n Ignore private methods\n \"\"\"", "def_name", "=", "context", ".", "split", "(", ")", "[", "1", "]", "if", "def_name", ".", "startswith", "(", "'_'", ")", "and", "not", "def_name", ".", "endswith", "(", "'__'", ")", ":", "original_check_return_type", "(", "def_docstring", ",", "context", ",", "is_script", ")", "pep257", ".", "check_return_type", "=", "better_check_return_type", "errors", "=", "[", "]", "for", "filename", "in", "to_lint", ":", "with", "open", "(", "filename", ")", "as", "f", ":", "source", "=", "f", ".", "read", "(", ")", "if", "source", ":", "errors", ".", "extend", "(", "pep257", ".", "check_source", "(", "source", ",", "filename", ")", ")", "return", "'\\n'", ".", "join", "(", "[", "str", "(", "error", ")", "for", "error", "in", "sorted", "(", "errors", ")", "]", ")" ]
Check for the presence of docstrings, but ignore some of the options
[ "Check", "for", "the", "presence", "of", "docstrings", "but", "ignore", "some", "of", "the", "options" ]
c6fae78923a019f1615e9516ab30fa105c72a542
https://github.com/rackerlabs/silverberg/blob/c6fae78923a019f1615e9516ab30fa105c72a542/scripts/python-lint.py#L52-L84
251,294
rackerlabs/silverberg
scripts/python-lint.py
Lint.main
def main(self, *directories): """ The actual logic that runs the linters """ if not self.git and len(directories) == 0: print ("ERROR: At least one directory must be provided (or the " "--git-precommit flag must be passed.\n") self.help() return if len(directories) > 0: find = local['find'] files = [] for directory in directories: real = os.path.expanduser(directory) if not os.path.exists(real): raise ValueError("{0} does not exist".format(directory)) files.extend(find(real, '-name', '*.py').strip().split('\n')) if len(files) > 0: print "Linting {0} python files.\n".format(len(files)) lint(files) else: print "No python files found to lint.\n" else: status = local['git']('status', '--porcelain', '-uno') root = local['git']('rev-parse', '--show-toplevel').strip() # get all modified or added python files modified = re.findall(r"^[AM]\s+\S+\.py$", status, re.MULTILINE) # now just get the path part, which all should be relative to the # root files = [os.path.join(root, line.split(' ', 1)[-1].strip()) for line in modified] if len(files) > 0: lint(files)
python
def main(self, *directories): """ The actual logic that runs the linters """ if not self.git and len(directories) == 0: print ("ERROR: At least one directory must be provided (or the " "--git-precommit flag must be passed.\n") self.help() return if len(directories) > 0: find = local['find'] files = [] for directory in directories: real = os.path.expanduser(directory) if not os.path.exists(real): raise ValueError("{0} does not exist".format(directory)) files.extend(find(real, '-name', '*.py').strip().split('\n')) if len(files) > 0: print "Linting {0} python files.\n".format(len(files)) lint(files) else: print "No python files found to lint.\n" else: status = local['git']('status', '--porcelain', '-uno') root = local['git']('rev-parse', '--show-toplevel').strip() # get all modified or added python files modified = re.findall(r"^[AM]\s+\S+\.py$", status, re.MULTILINE) # now just get the path part, which all should be relative to the # root files = [os.path.join(root, line.split(' ', 1)[-1].strip()) for line in modified] if len(files) > 0: lint(files)
[ "def", "main", "(", "self", ",", "*", "directories", ")", ":", "if", "not", "self", ".", "git", "and", "len", "(", "directories", ")", "==", "0", ":", "print", "(", "\"ERROR: At least one directory must be provided (or the \"", "\"--git-precommit flag must be passed.\\n\"", ")", "self", ".", "help", "(", ")", "return", "if", "len", "(", "directories", ")", ">", "0", ":", "find", "=", "local", "[", "'find'", "]", "files", "=", "[", "]", "for", "directory", "in", "directories", ":", "real", "=", "os", ".", "path", ".", "expanduser", "(", "directory", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "real", ")", ":", "raise", "ValueError", "(", "\"{0} does not exist\"", ".", "format", "(", "directory", ")", ")", "files", ".", "extend", "(", "find", "(", "real", ",", "'-name'", ",", "'*.py'", ")", ".", "strip", "(", ")", ".", "split", "(", "'\\n'", ")", ")", "if", "len", "(", "files", ")", ">", "0", ":", "print", "\"Linting {0} python files.\\n\"", ".", "format", "(", "len", "(", "files", ")", ")", "lint", "(", "files", ")", "else", ":", "print", "\"No python files found to lint.\\n\"", "else", ":", "status", "=", "local", "[", "'git'", "]", "(", "'status'", ",", "'--porcelain'", ",", "'-uno'", ")", "root", "=", "local", "[", "'git'", "]", "(", "'rev-parse'", ",", "'--show-toplevel'", ")", ".", "strip", "(", ")", "# get all modified or added python files", "modified", "=", "re", ".", "findall", "(", "r\"^[AM]\\s+\\S+\\.py$\"", ",", "status", ",", "re", ".", "MULTILINE", ")", "# now just get the path part, which all should be relative to the", "# root", "files", "=", "[", "os", ".", "path", ".", "join", "(", "root", ",", "line", ".", "split", "(", "' '", ",", "1", ")", "[", "-", "1", "]", ".", "strip", "(", ")", ")", "for", "line", "in", "modified", "]", "if", "len", "(", "files", ")", ">", "0", ":", "lint", "(", "files", ")" ]
The actual logic that runs the linters
[ "The", "actual", "logic", "that", "runs", "the", "linters" ]
c6fae78923a019f1615e9516ab30fa105c72a542
https://github.com/rackerlabs/silverberg/blob/c6fae78923a019f1615e9516ab30fa105c72a542/scripts/python-lint.py#L97-L133
251,295
20tab/twentytab-tree
tree/template_context/context_processors.py
set_meta
def set_meta(request): """ This context processor returns meta informations contained in cached files. If there aren't cache it calculates dictionary to return """ context_extras = {} if not request.is_ajax() and hasattr(request, 'upy_context') and request.upy_context['PAGE']: context_extras['PAGE'] = request.upy_context['PAGE'] context_extras['NODE'] = request.upy_context['NODE'] return context_extras
python
def set_meta(request): """ This context processor returns meta informations contained in cached files. If there aren't cache it calculates dictionary to return """ context_extras = {} if not request.is_ajax() and hasattr(request, 'upy_context') and request.upy_context['PAGE']: context_extras['PAGE'] = request.upy_context['PAGE'] context_extras['NODE'] = request.upy_context['NODE'] return context_extras
[ "def", "set_meta", "(", "request", ")", ":", "context_extras", "=", "{", "}", "if", "not", "request", ".", "is_ajax", "(", ")", "and", "hasattr", "(", "request", ",", "'upy_context'", ")", "and", "request", ".", "upy_context", "[", "'PAGE'", "]", ":", "context_extras", "[", "'PAGE'", "]", "=", "request", ".", "upy_context", "[", "'PAGE'", "]", "context_extras", "[", "'NODE'", "]", "=", "request", ".", "upy_context", "[", "'NODE'", "]", "return", "context_extras" ]
This context processor returns meta informations contained in cached files. If there aren't cache it calculates dictionary to return
[ "This", "context", "processor", "returns", "meta", "informations", "contained", "in", "cached", "files", ".", "If", "there", "aren", "t", "cache", "it", "calculates", "dictionary", "to", "return" ]
f2c1ced33e6c211bb52a25a7d48155e39fbdc088
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/template_context/context_processors.py#L1-L10
251,296
necrolyte2/bootstrap_vi
bootstrap_vi.py
download_virtualenv
def download_virtualenv(version, dldir=None): ''' Download virtualenv package from pypi and return response that can be read and written to file :param str version: version to download or latest version if None :param str dldir: directory to download into or None for cwd ''' dl_url = PYPI_DL_URL.format(VER=version) filename = basename(dl_url) if dldir: dl_path = join(dldir, filename) else: dl_path = filename data = urlopen(PYPI_DL_URL.format(VER=version)) with open(dl_path, 'wb') as fh: fh.write(data.read()) return dl_path
python
def download_virtualenv(version, dldir=None): ''' Download virtualenv package from pypi and return response that can be read and written to file :param str version: version to download or latest version if None :param str dldir: directory to download into or None for cwd ''' dl_url = PYPI_DL_URL.format(VER=version) filename = basename(dl_url) if dldir: dl_path = join(dldir, filename) else: dl_path = filename data = urlopen(PYPI_DL_URL.format(VER=version)) with open(dl_path, 'wb') as fh: fh.write(data.read()) return dl_path
[ "def", "download_virtualenv", "(", "version", ",", "dldir", "=", "None", ")", ":", "dl_url", "=", "PYPI_DL_URL", ".", "format", "(", "VER", "=", "version", ")", "filename", "=", "basename", "(", "dl_url", ")", "if", "dldir", ":", "dl_path", "=", "join", "(", "dldir", ",", "filename", ")", "else", ":", "dl_path", "=", "filename", "data", "=", "urlopen", "(", "PYPI_DL_URL", ".", "format", "(", "VER", "=", "version", ")", ")", "with", "open", "(", "dl_path", ",", "'wb'", ")", "as", "fh", ":", "fh", ".", "write", "(", "data", ".", "read", "(", ")", ")", "return", "dl_path" ]
Download virtualenv package from pypi and return response that can be read and written to file :param str version: version to download or latest version if None :param str dldir: directory to download into or None for cwd
[ "Download", "virtualenv", "package", "from", "pypi", "and", "return", "response", "that", "can", "be", "read", "and", "written", "to", "file" ]
cde96df76ecea1850cd26c2234ac13b3420d64dd
https://github.com/necrolyte2/bootstrap_vi/blob/cde96df76ecea1850cd26c2234ac13b3420d64dd/bootstrap_vi.py#L74-L91
251,297
necrolyte2/bootstrap_vi
bootstrap_vi.py
create_virtualenv
def create_virtualenv(venvpath, venvargs=None): ''' Run virtualenv from downloaded venvpath using venvargs If venvargs is None, then 'venv' will be used as the virtualenv directory :param str venvpath: Path to root downloaded virtualenv package(must contain virtualenv.py) :param list venvargs: Virtualenv arguments to pass to virtualenv.py ''' cmd = [join(venvpath, 'virtualenv.py')] venv_path = None if venvargs: cmd += venvargs venv_path = abspath(venvargs[-1]) else: cmd += ['venv'] p = subprocess.Popen(cmd) p.communicate()
python
def create_virtualenv(venvpath, venvargs=None): ''' Run virtualenv from downloaded venvpath using venvargs If venvargs is None, then 'venv' will be used as the virtualenv directory :param str venvpath: Path to root downloaded virtualenv package(must contain virtualenv.py) :param list venvargs: Virtualenv arguments to pass to virtualenv.py ''' cmd = [join(venvpath, 'virtualenv.py')] venv_path = None if venvargs: cmd += venvargs venv_path = abspath(venvargs[-1]) else: cmd += ['venv'] p = subprocess.Popen(cmd) p.communicate()
[ "def", "create_virtualenv", "(", "venvpath", ",", "venvargs", "=", "None", ")", ":", "cmd", "=", "[", "join", "(", "venvpath", ",", "'virtualenv.py'", ")", "]", "venv_path", "=", "None", "if", "venvargs", ":", "cmd", "+=", "venvargs", "venv_path", "=", "abspath", "(", "venvargs", "[", "-", "1", "]", ")", "else", ":", "cmd", "+=", "[", "'venv'", "]", "p", "=", "subprocess", ".", "Popen", "(", "cmd", ")", "p", ".", "communicate", "(", ")" ]
Run virtualenv from downloaded venvpath using venvargs If venvargs is None, then 'venv' will be used as the virtualenv directory :param str venvpath: Path to root downloaded virtualenv package(must contain virtualenv.py) :param list venvargs: Virtualenv arguments to pass to virtualenv.py
[ "Run", "virtualenv", "from", "downloaded", "venvpath", "using", "venvargs", "If", "venvargs", "is", "None", "then", "venv", "will", "be", "used", "as", "the", "virtualenv", "directory" ]
cde96df76ecea1850cd26c2234ac13b3420d64dd
https://github.com/necrolyte2/bootstrap_vi/blob/cde96df76ecea1850cd26c2234ac13b3420d64dd/bootstrap_vi.py#L93-L110
251,298
necrolyte2/bootstrap_vi
bootstrap_vi.py
bootstrap_vi
def bootstrap_vi(version=None, venvargs=None): ''' Bootstrap virtualenv into current directory :param str version: Virtualenv version like 13.1.0 or None for latest version :param list venvargs: argv list for virtualenv.py or None for default ''' if not version: version = get_latest_virtualenv_version() tarball = download_virtualenv(version) p = subprocess.Popen('tar xzvf {0}'.format(tarball), shell=True) p.wait() p = 'virtualenv-{0}'.format(version) create_virtualenv(p, venvargs)
python
def bootstrap_vi(version=None, venvargs=None): ''' Bootstrap virtualenv into current directory :param str version: Virtualenv version like 13.1.0 or None for latest version :param list venvargs: argv list for virtualenv.py or None for default ''' if not version: version = get_latest_virtualenv_version() tarball = download_virtualenv(version) p = subprocess.Popen('tar xzvf {0}'.format(tarball), shell=True) p.wait() p = 'virtualenv-{0}'.format(version) create_virtualenv(p, venvargs)
[ "def", "bootstrap_vi", "(", "version", "=", "None", ",", "venvargs", "=", "None", ")", ":", "if", "not", "version", ":", "version", "=", "get_latest_virtualenv_version", "(", ")", "tarball", "=", "download_virtualenv", "(", "version", ")", "p", "=", "subprocess", ".", "Popen", "(", "'tar xzvf {0}'", ".", "format", "(", "tarball", ")", ",", "shell", "=", "True", ")", "p", ".", "wait", "(", ")", "p", "=", "'virtualenv-{0}'", ".", "format", "(", "version", ")", "create_virtualenv", "(", "p", ",", "venvargs", ")" ]
Bootstrap virtualenv into current directory :param str version: Virtualenv version like 13.1.0 or None for latest version :param list venvargs: argv list for virtualenv.py or None for default
[ "Bootstrap", "virtualenv", "into", "current", "directory" ]
cde96df76ecea1850cd26c2234ac13b3420d64dd
https://github.com/necrolyte2/bootstrap_vi/blob/cde96df76ecea1850cd26c2234ac13b3420d64dd/bootstrap_vi.py#L112-L125
251,299
edeposit/edeposit.amqp.storage
src/edeposit/amqp/storage/web_tools.py
compose_path
def compose_path(pub, uuid_url=False): """ Compose absolute path for given `pub`. Args: pub (obj): :class:`.DBPublication` instance. uuid_url (bool, default False): Compose URL using UUID. Returns: str: Absolute url-path of the publication, without server's address \ and protocol. Raises: PrivatePublicationError: When the `pub` is private publication. """ if uuid_url: return join( "/", UUID_DOWNLOAD_KEY, str(pub.uuid) ) return join( "/", DOWNLOAD_KEY, basename(pub.file_pointer), basename(pub.filename) )
python
def compose_path(pub, uuid_url=False): """ Compose absolute path for given `pub`. Args: pub (obj): :class:`.DBPublication` instance. uuid_url (bool, default False): Compose URL using UUID. Returns: str: Absolute url-path of the publication, without server's address \ and protocol. Raises: PrivatePublicationError: When the `pub` is private publication. """ if uuid_url: return join( "/", UUID_DOWNLOAD_KEY, str(pub.uuid) ) return join( "/", DOWNLOAD_KEY, basename(pub.file_pointer), basename(pub.filename) )
[ "def", "compose_path", "(", "pub", ",", "uuid_url", "=", "False", ")", ":", "if", "uuid_url", ":", "return", "join", "(", "\"/\"", ",", "UUID_DOWNLOAD_KEY", ",", "str", "(", "pub", ".", "uuid", ")", ")", "return", "join", "(", "\"/\"", ",", "DOWNLOAD_KEY", ",", "basename", "(", "pub", ".", "file_pointer", ")", ",", "basename", "(", "pub", ".", "filename", ")", ")" ]
Compose absolute path for given `pub`. Args: pub (obj): :class:`.DBPublication` instance. uuid_url (bool, default False): Compose URL using UUID. Returns: str: Absolute url-path of the publication, without server's address \ and protocol. Raises: PrivatePublicationError: When the `pub` is private publication.
[ "Compose", "absolute", "path", "for", "given", "pub", "." ]
fb6bd326249847de04b17b64e856c878665cea92
https://github.com/edeposit/edeposit.amqp.storage/blob/fb6bd326249847de04b17b64e856c878665cea92/src/edeposit/amqp/storage/web_tools.py#L31-L58