repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
jvamvas/rhymediscovery
rhymediscovery/find_schemes.py
post_prob_scheme
def post_prob_scheme(t_table, stanza, scheme): """ Compute posterior probability of a scheme for a stanza, with probability of every word in rhymelist rhyming with all the ones before it """ myprob = 1 rhymelists = get_rhymelists(stanza, scheme) for rhymelist in rhymelists: for i, word_index in enumerate(rhymelist): if i == 0: # first word, use P(w|x) myprob *= t_table[word_index, -1] else: for word_index2 in rhymelist[:i]: # history myprob *= t_table[word_index, word_index2] if myprob == 0 and len(stanza) > 30: # probably underflow myprob = 1e-300 return myprob
python
def post_prob_scheme(t_table, stanza, scheme): """ Compute posterior probability of a scheme for a stanza, with probability of every word in rhymelist rhyming with all the ones before it """ myprob = 1 rhymelists = get_rhymelists(stanza, scheme) for rhymelist in rhymelists: for i, word_index in enumerate(rhymelist): if i == 0: # first word, use P(w|x) myprob *= t_table[word_index, -1] else: for word_index2 in rhymelist[:i]: # history myprob *= t_table[word_index, word_index2] if myprob == 0 and len(stanza) > 30: # probably underflow myprob = 1e-300 return myprob
[ "def", "post_prob_scheme", "(", "t_table", ",", "stanza", ",", "scheme", ")", ":", "myprob", "=", "1", "rhymelists", "=", "get_rhymelists", "(", "stanza", ",", "scheme", ")", "for", "rhymelist", "in", "rhymelists", ":", "for", "i", ",", "word_index", "in",...
Compute posterior probability of a scheme for a stanza, with probability of every word in rhymelist rhyming with all the ones before it
[ "Compute", "posterior", "probability", "of", "a", "scheme", "for", "a", "stanza", "with", "probability", "of", "every", "word", "in", "rhymelist", "rhyming", "with", "all", "the", "ones", "before", "it" ]
train
https://github.com/jvamvas/rhymediscovery/blob/b76509c98554b12efa06fe9ab557cca5fa5e4a79/rhymediscovery/find_schemes.py#L157-L173
jvamvas/rhymediscovery
rhymediscovery/find_schemes.py
expectation_step
def expectation_step(t_table, stanzas, schemes, rprobs): """ Compute posterior probability of schemes for each stanza """ probs = numpy.zeros((len(stanzas), schemes.num_schemes)) for i, stanza in enumerate(stanzas): scheme_indices = schemes.get_schemes_for_len(len(stanza)) for scheme_index in scheme_indices: scheme = schemes.scheme_list[scheme_index] probs[i, scheme_index] = post_prob_scheme(t_table, stanza, scheme) probs = numpy.dot(probs, numpy.diag(rprobs)) # Normalize scheme_sums = numpy.sum(probs, axis=1) for i, scheme_sum in enumerate(scheme_sums.tolist()): if scheme_sum > 0: probs[i, :] /= scheme_sum return probs
python
def expectation_step(t_table, stanzas, schemes, rprobs): """ Compute posterior probability of schemes for each stanza """ probs = numpy.zeros((len(stanzas), schemes.num_schemes)) for i, stanza in enumerate(stanzas): scheme_indices = schemes.get_schemes_for_len(len(stanza)) for scheme_index in scheme_indices: scheme = schemes.scheme_list[scheme_index] probs[i, scheme_index] = post_prob_scheme(t_table, stanza, scheme) probs = numpy.dot(probs, numpy.diag(rprobs)) # Normalize scheme_sums = numpy.sum(probs, axis=1) for i, scheme_sum in enumerate(scheme_sums.tolist()): if scheme_sum > 0: probs[i, :] /= scheme_sum return probs
[ "def", "expectation_step", "(", "t_table", ",", "stanzas", ",", "schemes", ",", "rprobs", ")", ":", "probs", "=", "numpy", ".", "zeros", "(", "(", "len", "(", "stanzas", ")", ",", "schemes", ".", "num_schemes", ")", ")", "for", "i", ",", "stanza", "i...
Compute posterior probability of schemes for each stanza
[ "Compute", "posterior", "probability", "of", "schemes", "for", "each", "stanza" ]
train
https://github.com/jvamvas/rhymediscovery/blob/b76509c98554b12efa06fe9ab557cca5fa5e4a79/rhymediscovery/find_schemes.py#L176-L193
jvamvas/rhymediscovery
rhymediscovery/find_schemes.py
maximization_step
def maximization_step(num_words, stanzas, schemes, probs): """ Update latent variables t_table, rprobs """ t_table = numpy.zeros((num_words, num_words + 1)) rprobs = numpy.ones(schemes.num_schemes) for i, stanza in enumerate(stanzas): scheme_indices = schemes.get_schemes_for_len(len(stanza)) for scheme_index in scheme_indices: myprob = probs[i, scheme_index] rprobs[scheme_index] += myprob scheme = schemes.scheme_list[scheme_index] rhymelists = get_rhymelists(stanza, scheme) for rhymelist in rhymelists: for j, word_index in enumerate(rhymelist): t_table[word_index, -1] += myprob for word_index2 in rhymelist[:j] + rhymelist[j + 1:]: t_table[word_index, word_index2] += myprob # Normalize t_table t_table_sums = numpy.sum(t_table, axis=0) for i, t_table_sum in enumerate(t_table_sums.tolist()): if t_table_sum != 0: t_table[:, i] /= t_table_sum # Normalize rprobs totrprob = numpy.sum(rprobs) rprobs /= totrprob return t_table, rprobs
python
def maximization_step(num_words, stanzas, schemes, probs): """ Update latent variables t_table, rprobs """ t_table = numpy.zeros((num_words, num_words + 1)) rprobs = numpy.ones(schemes.num_schemes) for i, stanza in enumerate(stanzas): scheme_indices = schemes.get_schemes_for_len(len(stanza)) for scheme_index in scheme_indices: myprob = probs[i, scheme_index] rprobs[scheme_index] += myprob scheme = schemes.scheme_list[scheme_index] rhymelists = get_rhymelists(stanza, scheme) for rhymelist in rhymelists: for j, word_index in enumerate(rhymelist): t_table[word_index, -1] += myprob for word_index2 in rhymelist[:j] + rhymelist[j + 1:]: t_table[word_index, word_index2] += myprob # Normalize t_table t_table_sums = numpy.sum(t_table, axis=0) for i, t_table_sum in enumerate(t_table_sums.tolist()): if t_table_sum != 0: t_table[:, i] /= t_table_sum # Normalize rprobs totrprob = numpy.sum(rprobs) rprobs /= totrprob return t_table, rprobs
[ "def", "maximization_step", "(", "num_words", ",", "stanzas", ",", "schemes", ",", "probs", ")", ":", "t_table", "=", "numpy", ".", "zeros", "(", "(", "num_words", ",", "num_words", "+", "1", ")", ")", "rprobs", "=", "numpy", ".", "ones", "(", "schemes...
Update latent variables t_table, rprobs
[ "Update", "latent", "variables", "t_table", "rprobs" ]
train
https://github.com/jvamvas/rhymediscovery/blob/b76509c98554b12efa06fe9ab557cca5fa5e4a79/rhymediscovery/find_schemes.py#L196-L225
jvamvas/rhymediscovery
rhymediscovery/find_schemes.py
iterate
def iterate(t_table, wordlist, stanzas, schemes, rprobs, maxsteps): """ Iterate EM and return final probabilities """ data_probs = numpy.zeros(len(stanzas)) old_data_probs = None probs = None num_words = len(wordlist) ctr = 0 for ctr in range(maxsteps): logging.info("Iteration {}".format(ctr)) old_data_probs = data_probs logging.info("Expectation step") probs = expectation_step(t_table, stanzas, schemes, rprobs) logging.info("Maximization step") t_table, rprobs = maximization_step(num_words, stanzas, schemes, probs) # Warn if it did not converge data_probs = numpy.logaddexp.reduce(probs, axis=1) if ctr == maxsteps - 1 and not numpy.allclose(data_probs, old_data_probs): logging.warning("Warning: EM did not converge") logging.info("Stopped after {} interations".format(ctr)) return probs
python
def iterate(t_table, wordlist, stanzas, schemes, rprobs, maxsteps): """ Iterate EM and return final probabilities """ data_probs = numpy.zeros(len(stanzas)) old_data_probs = None probs = None num_words = len(wordlist) ctr = 0 for ctr in range(maxsteps): logging.info("Iteration {}".format(ctr)) old_data_probs = data_probs logging.info("Expectation step") probs = expectation_step(t_table, stanzas, schemes, rprobs) logging.info("Maximization step") t_table, rprobs = maximization_step(num_words, stanzas, schemes, probs) # Warn if it did not converge data_probs = numpy.logaddexp.reduce(probs, axis=1) if ctr == maxsteps - 1 and not numpy.allclose(data_probs, old_data_probs): logging.warning("Warning: EM did not converge") logging.info("Stopped after {} interations".format(ctr)) return probs
[ "def", "iterate", "(", "t_table", ",", "wordlist", ",", "stanzas", ",", "schemes", ",", "rprobs", ",", "maxsteps", ")", ":", "data_probs", "=", "numpy", ".", "zeros", "(", "len", "(", "stanzas", ")", ")", "old_data_probs", "=", "None", "probs", "=", "N...
Iterate EM and return final probabilities
[ "Iterate", "EM", "and", "return", "final", "probabilities" ]
train
https://github.com/jvamvas/rhymediscovery/blob/b76509c98554b12efa06fe9ab557cca5fa5e4a79/rhymediscovery/find_schemes.py#L228-L254
jvamvas/rhymediscovery
rhymediscovery/find_schemes.py
get_results
def get_results(probs, stanzas, schemes): """ Returns a list of tuples ( stanza [as list of final words], best scheme [as list of integers] ) """ results = [] for i, stanza in enumerate(stanzas): best_scheme = schemes.scheme_list[numpy.argmax(probs[i, :])] results.append((stanza.words, best_scheme)) return results
python
def get_results(probs, stanzas, schemes): """ Returns a list of tuples ( stanza [as list of final words], best scheme [as list of integers] ) """ results = [] for i, stanza in enumerate(stanzas): best_scheme = schemes.scheme_list[numpy.argmax(probs[i, :])] results.append((stanza.words, best_scheme)) return results
[ "def", "get_results", "(", "probs", ",", "stanzas", ",", "schemes", ")", ":", "results", "=", "[", "]", "for", "i", ",", "stanza", "in", "enumerate", "(", "stanzas", ")", ":", "best_scheme", "=", "schemes", ".", "scheme_list", "[", "numpy", ".", "argma...
Returns a list of tuples ( stanza [as list of final words], best scheme [as list of integers] )
[ "Returns", "a", "list", "of", "tuples", "(", "stanza", "[", "as", "list", "of", "final", "words", "]", "best", "scheme", "[", "as", "list", "of", "integers", "]", ")" ]
train
https://github.com/jvamvas/rhymediscovery/blob/b76509c98554b12efa06fe9ab557cca5fa5e4a79/rhymediscovery/find_schemes.py#L264-L275
jvamvas/rhymediscovery
rhymediscovery/find_schemes.py
print_results
def print_results(results, outfile): """ Write results to outfile """ for stanza_words, scheme in results: outfile.write(str(' ').join(stanza_words) + str('\n')) outfile.write(str(' ').join(map(str, scheme)) + str('\n\n')) outfile.close() logging.info("Wrote result")
python
def print_results(results, outfile): """ Write results to outfile """ for stanza_words, scheme in results: outfile.write(str(' ').join(stanza_words) + str('\n')) outfile.write(str(' ').join(map(str, scheme)) + str('\n\n')) outfile.close() logging.info("Wrote result")
[ "def", "print_results", "(", "results", ",", "outfile", ")", ":", "for", "stanza_words", ",", "scheme", "in", "results", ":", "outfile", ".", "write", "(", "str", "(", "' '", ")", ".", "join", "(", "stanza_words", ")", "+", "str", "(", "'\\n'", ")", ...
Write results to outfile
[ "Write", "results", "to", "outfile" ]
train
https://github.com/jvamvas/rhymediscovery/blob/b76509c98554b12efa06fe9ab557cca5fa5e4a79/rhymediscovery/find_schemes.py#L278-L286
jvamvas/rhymediscovery
rhymediscovery/find_schemes.py
main
def main(args_list=None): """ Wrapper for find_schemes if called from command line """ args_list = args_list or sys.argv[1:] parser = argparse.ArgumentParser(description='Discover schemes of given stanza file') parser.add_argument( 'infile', type=argparse.FileType('r'), ) parser.add_argument( 'outfile', help='Where the result is written to. Default: stdout', nargs='?', type=argparse.FileType('w'), default=sys.stdout, ) parser.add_argument( '-t --init-type', help='Whether to initialize theta uniformly (u), with the orthographic similarity ' 'measure (o), or using CELEX pronunciations and definition of rhyme (p). ' 'The last one requires you to have CELEX on your machine.', dest='init_type', choices=('u', 'o', 'p', 'd'), default='o', ) parser.add_argument( '-i, --iterations', help='Number of iterations (default: 10)', dest='num_iterations', type=int, default=10, ) parser.add_argument( '-v', '--verbose', help="Verbose output", action="store_const", dest="loglevel", const=logging.INFO, ) args = parser.parse_args(args_list) logging.basicConfig(level=args.loglevel) stanzas = load_stanzas(args.infile) init_function = None if args.init_type == 'u': init_function = init_uniform_ttable elif args.init_type == 'o': init_function = init_basicortho_ttable elif args.init_type == 'p': init_function = celex.init_perfect_ttable elif args.init_type == 'd': init_function = init_difflib_ttable results = find_schemes(stanzas, init_function, args.num_iterations) print_results(results, args.outfile)
python
def main(args_list=None): """ Wrapper for find_schemes if called from command line """ args_list = args_list or sys.argv[1:] parser = argparse.ArgumentParser(description='Discover schemes of given stanza file') parser.add_argument( 'infile', type=argparse.FileType('r'), ) parser.add_argument( 'outfile', help='Where the result is written to. Default: stdout', nargs='?', type=argparse.FileType('w'), default=sys.stdout, ) parser.add_argument( '-t --init-type', help='Whether to initialize theta uniformly (u), with the orthographic similarity ' 'measure (o), or using CELEX pronunciations and definition of rhyme (p). ' 'The last one requires you to have CELEX on your machine.', dest='init_type', choices=('u', 'o', 'p', 'd'), default='o', ) parser.add_argument( '-i, --iterations', help='Number of iterations (default: 10)', dest='num_iterations', type=int, default=10, ) parser.add_argument( '-v', '--verbose', help="Verbose output", action="store_const", dest="loglevel", const=logging.INFO, ) args = parser.parse_args(args_list) logging.basicConfig(level=args.loglevel) stanzas = load_stanzas(args.infile) init_function = None if args.init_type == 'u': init_function = init_uniform_ttable elif args.init_type == 'o': init_function = init_basicortho_ttable elif args.init_type == 'p': init_function = celex.init_perfect_ttable elif args.init_type == 'd': init_function = init_difflib_ttable results = find_schemes(stanzas, init_function, args.num_iterations) print_results(results, args.outfile)
[ "def", "main", "(", "args_list", "=", "None", ")", ":", "args_list", "=", "args_list", "or", "sys", ".", "argv", "[", "1", ":", "]", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Discover schemes of given stanza file'", ")", "p...
Wrapper for find_schemes if called from command line
[ "Wrapper", "for", "find_schemes", "if", "called", "from", "command", "line" ]
train
https://github.com/jvamvas/rhymediscovery/blob/b76509c98554b12efa06fe9ab557cca5fa5e4a79/rhymediscovery/find_schemes.py#L315-L372
jvamvas/rhymediscovery
rhymediscovery/find_schemes.py
Stanza.set_word_indices
def set_word_indices(self, wordlist): """ Populate the list of word_indices, mapping self.words to the given wordlist """ self.word_indices = [wordlist.index(word) for word in self.words]
python
def set_word_indices(self, wordlist): """ Populate the list of word_indices, mapping self.words to the given wordlist """ self.word_indices = [wordlist.index(word) for word in self.words]
[ "def", "set_word_indices", "(", "self", ",", "wordlist", ")", ":", "self", ".", "word_indices", "=", "[", "wordlist", ".", "index", "(", "word", ")", "for", "word", "in", "self", ".", "words", "]" ]
Populate the list of word_indices, mapping self.words to the given wordlist
[ "Populate", "the", "list", "of", "word_indices", "mapping", "self", ".", "words", "to", "the", "given", "wordlist" ]
train
https://github.com/jvamvas/rhymediscovery/blob/b76509c98554b12efa06fe9ab557cca5fa5e4a79/rhymediscovery/find_schemes.py#L42-L46
jvamvas/rhymediscovery
rhymediscovery/find_schemes.py
Schemes._parse_scheme_file
def _parse_scheme_file(self): """ Initialize redundant data structures for lookup optimization """ schemes = json.loads(self.scheme_file.read(), object_pairs_hook=OrderedDict) scheme_list = [] scheme_dict = defaultdict(list) for scheme_len, scheme_group in schemes.items(): for scheme_str, _count in scheme_group: scheme_code = tuple(int(c) for c in scheme_str.split(' ')) scheme_list.append(scheme_code) scheme_dict[int(scheme_len)].append(len(scheme_list) - 1) return scheme_list, scheme_dict
python
def _parse_scheme_file(self): """ Initialize redundant data structures for lookup optimization """ schemes = json.loads(self.scheme_file.read(), object_pairs_hook=OrderedDict) scheme_list = [] scheme_dict = defaultdict(list) for scheme_len, scheme_group in schemes.items(): for scheme_str, _count in scheme_group: scheme_code = tuple(int(c) for c in scheme_str.split(' ')) scheme_list.append(scheme_code) scheme_dict[int(scheme_len)].append(len(scheme_list) - 1) return scheme_list, scheme_dict
[ "def", "_parse_scheme_file", "(", "self", ")", ":", "schemes", "=", "json", ".", "loads", "(", "self", ".", "scheme_file", ".", "read", "(", ")", ",", "object_pairs_hook", "=", "OrderedDict", ")", "scheme_list", "=", "[", "]", "scheme_dict", "=", "defaultd...
Initialize redundant data structures for lookup optimization
[ "Initialize", "redundant", "data", "structures", "for", "lookup", "optimization" ]
train
https://github.com/jvamvas/rhymediscovery/blob/b76509c98554b12efa06fe9ab557cca5fa5e4a79/rhymediscovery/find_schemes.py#L65-L77
cemsbr/yala
yala/linters.py
Isort._create_output_from_match
def _create_output_from_match(self, match_result): """As isort outputs full path, we change it to relative path.""" full_path = match_result['full_path'] path = self._get_relative_path(full_path) return LinterOutput(self.name, path, match_result['msg'])
python
def _create_output_from_match(self, match_result): """As isort outputs full path, we change it to relative path.""" full_path = match_result['full_path'] path = self._get_relative_path(full_path) return LinterOutput(self.name, path, match_result['msg'])
[ "def", "_create_output_from_match", "(", "self", ",", "match_result", ")", ":", "full_path", "=", "match_result", "[", "'full_path'", "]", "path", "=", "self", ".", "_get_relative_path", "(", "full_path", ")", "return", "LinterOutput", "(", "self", ".", "name", ...
As isort outputs full path, we change it to relative path.
[ "As", "isort", "outputs", "full", "path", "we", "change", "it", "to", "relative", "path", "." ]
train
https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/linters.py#L23-L27
cemsbr/yala
yala/linters.py
Pydocstyle.parse
def parse(self, lines): """Get :class:`base.Result` parameters using regex. There are 2 lines for each pydocstyle result: 1. Filename and line number; 2. Message for the problem found. """ patterns = [re.compile(r'^(.+?):(\d+)'), re.compile(r'^\s+(.+)$')] for i, line in enumerate(lines): if i % 2 == 0: path, line_nr = patterns[0].match(line).groups() else: msg = patterns[1].match(line).group(1) yield LinterOutput(self.name, path, msg, line_nr)
python
def parse(self, lines): """Get :class:`base.Result` parameters using regex. There are 2 lines for each pydocstyle result: 1. Filename and line number; 2. Message for the problem found. """ patterns = [re.compile(r'^(.+?):(\d+)'), re.compile(r'^\s+(.+)$')] for i, line in enumerate(lines): if i % 2 == 0: path, line_nr = patterns[0].match(line).groups() else: msg = patterns[1].match(line).group(1) yield LinterOutput(self.name, path, msg, line_nr)
[ "def", "parse", "(", "self", ",", "lines", ")", ":", "patterns", "=", "[", "re", ".", "compile", "(", "r'^(.+?):(\\d+)'", ")", ",", "re", ".", "compile", "(", "r'^\\s+(.+)$'", ")", "]", "for", "i", ",", "line", "in", "enumerate", "(", "lines", ")", ...
Get :class:`base.Result` parameters using regex. There are 2 lines for each pydocstyle result: 1. Filename and line number; 2. Message for the problem found.
[ "Get", ":", "class", ":", "base", ".", "Result", "parameters", "using", "regex", "." ]
train
https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/linters.py#L64-L78
cemsbr/yala
yala/linters.py
Pylint.parse
def parse(self, lines): """Get :class:`base.Result` parameters using regex.""" pattern = re.compile(r"""^(?P<path>.+?) :(?P<msg>.+) :(?P<line_nr>\d+?) :(?P<col>\d+?)$""", re.VERBOSE) return self._parse_by_pattern(lines, pattern)
python
def parse(self, lines): """Get :class:`base.Result` parameters using regex.""" pattern = re.compile(r"""^(?P<path>.+?) :(?P<msg>.+) :(?P<line_nr>\d+?) :(?P<col>\d+?)$""", re.VERBOSE) return self._parse_by_pattern(lines, pattern)
[ "def", "parse", "(", "self", ",", "lines", ")", ":", "pattern", "=", "re", ".", "compile", "(", "r\"\"\"^(?P<path>.+?)\n :(?P<msg>.+)\n :(?P<line_nr>\\d+?)\n :(?P<col>\\d+?)$\"\"\"", ",", ...
Get :class:`base.Result` parameters using regex.
[ "Get", ":", "class", ":", "base", ".", "Result", "parameters", "using", "regex", "." ]
train
https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/linters.py#L86-L92
thespacedoctor/rockfinder
rockfinder/orbfit_ephemeris.py
_generate_one_ephemeris
def _generate_one_ephemeris( cmd): """generate one orbfit ephemeris **Key Arguments:** - ``cmd`` -- the command to execute [cmd, object] **Return:** - ``results`` -- the single ephemeris results """ global cmdList cmd = cmdList[cmd] results = [] for c in cmd: p = Popen(c[0], stdout=PIPE, stderr=PIPE, shell=True) stdout, stderr = p.communicate() if len(stderr) and len(stderr.split()) != 15: print stderr, len(stderr.split()) return None elif "!!WARNING! WARNING! WARNING! WARNING!!" in stdout: print "%(stdout)s was not found in astorb.dat" % locals() return None # SPLIT RESULTS INTO LIST OF DICTIONARIES r = stdout.strip().split("\n") keys = r[0].strip().split(',') lines = r[1:] for l in lines: # CREATE DICTIONARY FROM KEYS AND VALUES values = l.strip().split(',') for k, v in zip(keys, values): v = v.strip().replace("/", "") try: v = float(v) except: pass result = dict(zip(keys, values)) result["object_name"] = c[1] results.append(result) return results
python
def _generate_one_ephemeris( cmd): """generate one orbfit ephemeris **Key Arguments:** - ``cmd`` -- the command to execute [cmd, object] **Return:** - ``results`` -- the single ephemeris results """ global cmdList cmd = cmdList[cmd] results = [] for c in cmd: p = Popen(c[0], stdout=PIPE, stderr=PIPE, shell=True) stdout, stderr = p.communicate() if len(stderr) and len(stderr.split()) != 15: print stderr, len(stderr.split()) return None elif "!!WARNING! WARNING! WARNING! WARNING!!" in stdout: print "%(stdout)s was not found in astorb.dat" % locals() return None # SPLIT RESULTS INTO LIST OF DICTIONARIES r = stdout.strip().split("\n") keys = r[0].strip().split(',') lines = r[1:] for l in lines: # CREATE DICTIONARY FROM KEYS AND VALUES values = l.strip().split(',') for k, v in zip(keys, values): v = v.strip().replace("/", "") try: v = float(v) except: pass result = dict(zip(keys, values)) result["object_name"] = c[1] results.append(result) return results
[ "def", "_generate_one_ephemeris", "(", "cmd", ")", ":", "global", "cmdList", "cmd", "=", "cmdList", "[", "cmd", "]", "results", "=", "[", "]", "for", "c", "in", "cmd", ":", "p", "=", "Popen", "(", "c", "[", "0", "]", ",", "stdout", "=", "PIPE", "...
generate one orbfit ephemeris **Key Arguments:** - ``cmd`` -- the command to execute [cmd, object] **Return:** - ``results`` -- the single ephemeris results
[ "generate", "one", "orbfit", "ephemeris" ]
train
https://github.com/thespacedoctor/rockfinder/blob/631371032d4d4166ee40484e93d35a0efc400600/rockfinder/orbfit_ephemeris.py#L26-L68
thespacedoctor/rockfinder
rockfinder/orbfit_ephemeris.py
orbfit_ephemeris
def orbfit_ephemeris( log, objectId, mjd, settings, obscode=500, verbose=False, astorbPath=False): """Given a known solar-system object ID (human-readable name or MPC number but *NOT* an MPC packed format) or list of names and one or more specific epochs, return the calculated ephemerides **Key Arguments:** - ``log`` -- logger - ``objectId`` -- human-readable name, MPC number or solar-system object name, or list of names - ``mjd`` -- a single MJD, or a list MJDs to generate an ephemeris for - ``settings`` -- the settings dictionary for rockfinder - ``obscode`` -- the observatory code for the ephemeris generation. Default **500** (geocentric) - ``verbose`` -- return extra information with each ephemeris - ``astorbPath`` -- override the default path to astorb.dat orbital elements file **Return:** - ``resultList`` -- a list of ordered dictionaries containing the returned ephemerides **Usage:** To generate a an ephemeris for a single epoch run,using ATLAS Haleakala as your observatory: .. code-block:: python from rockfinder import orbfit_ephemeris eph = orbfit_ephemeris( log=log, objectId=1, obscode="T05" mjd=57916., ) or to generate an ephemeris for multiple epochs: .. code-block:: python from rockfinder import orbfit_ephemeris eph = orbfit_ephemeris( log=log, objectId="ceres", mjd=[57916.1,57917.234,57956.34523] verbose=True ) Note by passing `verbose=True` the essential ephemeris data is supplimented with some extra data It's also possible to pass in an array of object IDs: .. code-block:: python from rockfinder import orbfit_ephemeris eph = orbfit_ephemeris( log=log, objectId=[1,5,03547,"Shikoku"], mjd=[57916.1,57917.234,57956.34523] ) And finally you override the default path to astorb.dat orbital elements file by passing in a custom path (useful for passing in a trimmed orbital elements database): .. code-block:: python from rockfinder import orbfit_ephemeris eph = orbfit_ephemeris( log=log, objectId=[1,5,03547,"Shikoku"], mjd=[57916.1,57917.234,57956.34523], astorbPath="/path/to/astorb.dat" ) """ log.debug('starting the ``orbfit_ephemeris`` function') global cmdList # MAKE SURE MJDs ARE IN A LIST if not isinstance(mjd, list): mjdList = [str(mjd)] else: mjdList = mjd if not isinstance(objectId, list): objectList = [objectId] else: objectList = objectId ephem = settings["path to ephem binary"] home = expanduser("~") results = [] tmpCmdList = [] for o in objectList: for m in mjdList: if not isinstance(o, int) and "'" in o: cmd = """%(ephem)s %(obscode)s %(m)s "%(o)s" """ % locals() else: cmd = """%(ephem)s %(obscode)s %(m)s '%(o)s'""" % locals() if astorbPath: cmd += " '%(astorbPath)s'" % locals() tmpCmdList.append((cmd, o)) def chunks(l, n): """Yield successive n-sized chunks from l.""" for i in range(0, len(l), n): yield l[i:i + n] # BATCH INTO 10s cmdList = [c for c in chunks(tmpCmdList, 10)] # DEFINE AN INPUT ARRAY results = fmultiprocess(log=log, function=_generate_one_ephemeris, inputArray=range(len(cmdList))) if verbose == True: order = ["object_name", "mjd", "ra_deg", "dec_deg", "apparent_mag", "observer_distance", "heliocentric_distance", "phase_angle", "obscode", "sun_obs_target_angle", "galactic_latitude", "ra_arcsec_per_hour", "dec_arcsec_per_hour"] else: order = ["object_name", "mjd", "ra_deg", "dec_deg", "apparent_mag", "observer_distance", "heliocentric_distance", "phase_angle"] # ORDER THE RESULTS resultList = [] for r2 in results: if not r2: continue for r in r2: if not r: continue orderDict = collections.OrderedDict({}) for i in order: orderDict[i] = r[i] resultList.append(orderDict) log.debug('completed the ``orbfit_ephemeris`` function') return resultList
python
def orbfit_ephemeris( log, objectId, mjd, settings, obscode=500, verbose=False, astorbPath=False): """Given a known solar-system object ID (human-readable name or MPC number but *NOT* an MPC packed format) or list of names and one or more specific epochs, return the calculated ephemerides **Key Arguments:** - ``log`` -- logger - ``objectId`` -- human-readable name, MPC number or solar-system object name, or list of names - ``mjd`` -- a single MJD, or a list MJDs to generate an ephemeris for - ``settings`` -- the settings dictionary for rockfinder - ``obscode`` -- the observatory code for the ephemeris generation. Default **500** (geocentric) - ``verbose`` -- return extra information with each ephemeris - ``astorbPath`` -- override the default path to astorb.dat orbital elements file **Return:** - ``resultList`` -- a list of ordered dictionaries containing the returned ephemerides **Usage:** To generate a an ephemeris for a single epoch run,using ATLAS Haleakala as your observatory: .. code-block:: python from rockfinder import orbfit_ephemeris eph = orbfit_ephemeris( log=log, objectId=1, obscode="T05" mjd=57916., ) or to generate an ephemeris for multiple epochs: .. code-block:: python from rockfinder import orbfit_ephemeris eph = orbfit_ephemeris( log=log, objectId="ceres", mjd=[57916.1,57917.234,57956.34523] verbose=True ) Note by passing `verbose=True` the essential ephemeris data is supplimented with some extra data It's also possible to pass in an array of object IDs: .. code-block:: python from rockfinder import orbfit_ephemeris eph = orbfit_ephemeris( log=log, objectId=[1,5,03547,"Shikoku"], mjd=[57916.1,57917.234,57956.34523] ) And finally you override the default path to astorb.dat orbital elements file by passing in a custom path (useful for passing in a trimmed orbital elements database): .. code-block:: python from rockfinder import orbfit_ephemeris eph = orbfit_ephemeris( log=log, objectId=[1,5,03547,"Shikoku"], mjd=[57916.1,57917.234,57956.34523], astorbPath="/path/to/astorb.dat" ) """ log.debug('starting the ``orbfit_ephemeris`` function') global cmdList # MAKE SURE MJDs ARE IN A LIST if not isinstance(mjd, list): mjdList = [str(mjd)] else: mjdList = mjd if not isinstance(objectId, list): objectList = [objectId] else: objectList = objectId ephem = settings["path to ephem binary"] home = expanduser("~") results = [] tmpCmdList = [] for o in objectList: for m in mjdList: if not isinstance(o, int) and "'" in o: cmd = """%(ephem)s %(obscode)s %(m)s "%(o)s" """ % locals() else: cmd = """%(ephem)s %(obscode)s %(m)s '%(o)s'""" % locals() if astorbPath: cmd += " '%(astorbPath)s'" % locals() tmpCmdList.append((cmd, o)) def chunks(l, n): """Yield successive n-sized chunks from l.""" for i in range(0, len(l), n): yield l[i:i + n] # BATCH INTO 10s cmdList = [c for c in chunks(tmpCmdList, 10)] # DEFINE AN INPUT ARRAY results = fmultiprocess(log=log, function=_generate_one_ephemeris, inputArray=range(len(cmdList))) if verbose == True: order = ["object_name", "mjd", "ra_deg", "dec_deg", "apparent_mag", "observer_distance", "heliocentric_distance", "phase_angle", "obscode", "sun_obs_target_angle", "galactic_latitude", "ra_arcsec_per_hour", "dec_arcsec_per_hour"] else: order = ["object_name", "mjd", "ra_deg", "dec_deg", "apparent_mag", "observer_distance", "heliocentric_distance", "phase_angle"] # ORDER THE RESULTS resultList = [] for r2 in results: if not r2: continue for r in r2: if not r: continue orderDict = collections.OrderedDict({}) for i in order: orderDict[i] = r[i] resultList.append(orderDict) log.debug('completed the ``orbfit_ephemeris`` function') return resultList
[ "def", "orbfit_ephemeris", "(", "log", ",", "objectId", ",", "mjd", ",", "settings", ",", "obscode", "=", "500", ",", "verbose", "=", "False", ",", "astorbPath", "=", "False", ")", ":", "log", ".", "debug", "(", "'starting the ``orbfit_ephemeris`` function'", ...
Given a known solar-system object ID (human-readable name or MPC number but *NOT* an MPC packed format) or list of names and one or more specific epochs, return the calculated ephemerides **Key Arguments:** - ``log`` -- logger - ``objectId`` -- human-readable name, MPC number or solar-system object name, or list of names - ``mjd`` -- a single MJD, or a list MJDs to generate an ephemeris for - ``settings`` -- the settings dictionary for rockfinder - ``obscode`` -- the observatory code for the ephemeris generation. Default **500** (geocentric) - ``verbose`` -- return extra information with each ephemeris - ``astorbPath`` -- override the default path to astorb.dat orbital elements file **Return:** - ``resultList`` -- a list of ordered dictionaries containing the returned ephemerides **Usage:** To generate a an ephemeris for a single epoch run,using ATLAS Haleakala as your observatory: .. code-block:: python from rockfinder import orbfit_ephemeris eph = orbfit_ephemeris( log=log, objectId=1, obscode="T05" mjd=57916., ) or to generate an ephemeris for multiple epochs: .. code-block:: python from rockfinder import orbfit_ephemeris eph = orbfit_ephemeris( log=log, objectId="ceres", mjd=[57916.1,57917.234,57956.34523] verbose=True ) Note by passing `verbose=True` the essential ephemeris data is supplimented with some extra data It's also possible to pass in an array of object IDs: .. code-block:: python from rockfinder import orbfit_ephemeris eph = orbfit_ephemeris( log=log, objectId=[1,5,03547,"Shikoku"], mjd=[57916.1,57917.234,57956.34523] ) And finally you override the default path to astorb.dat orbital elements file by passing in a custom path (useful for passing in a trimmed orbital elements database): .. code-block:: python from rockfinder import orbfit_ephemeris eph = orbfit_ephemeris( log=log, objectId=[1,5,03547,"Shikoku"], mjd=[57916.1,57917.234,57956.34523], astorbPath="/path/to/astorb.dat" )
[ "Given", "a", "known", "solar", "-", "system", "object", "ID", "(", "human", "-", "readable", "name", "or", "MPC", "number", "but", "*", "NOT", "*", "an", "MPC", "packed", "format", ")", "or", "list", "of", "names", "and", "one", "or", "more", "speci...
train
https://github.com/thespacedoctor/rockfinder/blob/631371032d4d4166ee40484e93d35a0efc400600/rockfinder/orbfit_ephemeris.py#L71-L213
timothycrosley/short
short/compile.py
text
def text(short): """Compiles short markup text into an HTML strings""" return indent(short, branch_method=html_block_tag, leaf_method=convert_line, pass_syntax=PASS_SYNTAX, flush_left_syntax=FLUSH_LEFT_SYNTAX, flush_left_empty_line=FLUSH_LEFT_EMPTY_LINE, indentation_method=find_indentation)
python
def text(short): """Compiles short markup text into an HTML strings""" return indent(short, branch_method=html_block_tag, leaf_method=convert_line, pass_syntax=PASS_SYNTAX, flush_left_syntax=FLUSH_LEFT_SYNTAX, flush_left_empty_line=FLUSH_LEFT_EMPTY_LINE, indentation_method=find_indentation)
[ "def", "text", "(", "short", ")", ":", "return", "indent", "(", "short", ",", "branch_method", "=", "html_block_tag", ",", "leaf_method", "=", "convert_line", ",", "pass_syntax", "=", "PASS_SYNTAX", ",", "flush_left_syntax", "=", "FLUSH_LEFT_SYNTAX", ",", "flush...
Compiles short markup text into an HTML strings
[ "Compiles", "short", "markup", "text", "into", "an", "HTML", "strings" ]
train
https://github.com/timothycrosley/short/blob/dcf25ec01b5406d9e0a35ac7dd8112239c0912a5/short/compile.py#L112-L116
timothycrosley/short
short/compile.py
get_indented_block
def get_indented_block(prefix_lines): """Returns an integer. The return value is the number of lines that belong to block begun on the first line. Parameters ---------- prefix_lines : list of basestring pairs Each pair corresponds to a line of SHPAML source code. The first element of each pair is indentation. The second is the remaining part of the line, except for trailing newline. """ prefix, line = prefix_lines[0] len_prefix = len(prefix) # Find the first nonempty line with len(prefix) <= len(prefix) i = 1 while i < len(prefix_lines): new_prefix, line = prefix_lines[i] if line and len(new_prefix) <= len_prefix: break i += 1 # Rewind to exclude empty lines while i - 1 > 0 and prefix_lines[i - 1][1] == '': i -= 1 return i
python
def get_indented_block(prefix_lines): """Returns an integer. The return value is the number of lines that belong to block begun on the first line. Parameters ---------- prefix_lines : list of basestring pairs Each pair corresponds to a line of SHPAML source code. The first element of each pair is indentation. The second is the remaining part of the line, except for trailing newline. """ prefix, line = prefix_lines[0] len_prefix = len(prefix) # Find the first nonempty line with len(prefix) <= len(prefix) i = 1 while i < len(prefix_lines): new_prefix, line = prefix_lines[i] if line and len(new_prefix) <= len_prefix: break i += 1 # Rewind to exclude empty lines while i - 1 > 0 and prefix_lines[i - 1][1] == '': i -= 1 return i
[ "def", "get_indented_block", "(", "prefix_lines", ")", ":", "prefix", ",", "line", "=", "prefix_lines", "[", "0", "]", "len_prefix", "=", "len", "(", "prefix", ")", "# Find the first nonempty line with len(prefix) <= len(prefix)", "i", "=", "1", "while", "i", "<",...
Returns an integer. The return value is the number of lines that belong to block begun on the first line. Parameters ---------- prefix_lines : list of basestring pairs Each pair corresponds to a line of SHPAML source code. The first element of each pair is indentation. The second is the remaining part of the line, except for trailing newline.
[ "Returns", "an", "integer", "." ]
train
https://github.com/timothycrosley/short/blob/dcf25ec01b5406d9e0a35ac7dd8112239c0912a5/short/compile.py#L214-L243
timothycrosley/short
short/compile.py
indent
def indent(text, branch_method, leaf_method, pass_syntax, flush_left_syntax, flush_left_empty_line, indentation_method, get_block=get_indented_block): """Returns HTML as a basestring. Parameters ---------- text : basestring Source code, typically SHPAML, but could be a different (but related) language. The remaining parameters specify details about the language used in the source code. To parse SHPAML, pass the same values as convert_shpaml_tree. branch_method : function convert_shpaml_tree passes html_block_tag here. leaf_method : function convert_shpaml_tree passes convert_line here. pass_syntax : basestring convert_shpaml_tree passes PASS_SYNTAX here. flush_left_syntax : basestring convert_shpaml_tree passes FLUSH_LEFT_SYNTAX here. flush_left_empty_line : basestring convert_shpaml_tree passes FLUSH_LEFT_EMPTY_LINE here. indentation_method : function convert_shpaml_tree passes _indent here. get_block : function Defaults to get_indented_block. """ text = text.rstrip() lines = text.split('\n') if lines and lines[0].startswith('!! '): lines[0] = lines[0].replace('!! ', '<!DOCTYPE ') + '>' output = [] indent_lines(lines, output, branch_method, leaf_method, pass_syntax, flush_left_syntax, flush_left_empty_line, indentation_method, get_block=get_indented_block) return '\n'.join(output) + '\n'
python
def indent(text, branch_method, leaf_method, pass_syntax, flush_left_syntax, flush_left_empty_line, indentation_method, get_block=get_indented_block): """Returns HTML as a basestring. Parameters ---------- text : basestring Source code, typically SHPAML, but could be a different (but related) language. The remaining parameters specify details about the language used in the source code. To parse SHPAML, pass the same values as convert_shpaml_tree. branch_method : function convert_shpaml_tree passes html_block_tag here. leaf_method : function convert_shpaml_tree passes convert_line here. pass_syntax : basestring convert_shpaml_tree passes PASS_SYNTAX here. flush_left_syntax : basestring convert_shpaml_tree passes FLUSH_LEFT_SYNTAX here. flush_left_empty_line : basestring convert_shpaml_tree passes FLUSH_LEFT_EMPTY_LINE here. indentation_method : function convert_shpaml_tree passes _indent here. get_block : function Defaults to get_indented_block. """ text = text.rstrip() lines = text.split('\n') if lines and lines[0].startswith('!! '): lines[0] = lines[0].replace('!! ', '<!DOCTYPE ') + '>' output = [] indent_lines(lines, output, branch_method, leaf_method, pass_syntax, flush_left_syntax, flush_left_empty_line, indentation_method, get_block=get_indented_block) return '\n'.join(output) + '\n'
[ "def", "indent", "(", "text", ",", "branch_method", ",", "leaf_method", ",", "pass_syntax", ",", "flush_left_syntax", ",", "flush_left_empty_line", ",", "indentation_method", ",", "get_block", "=", "get_indented_block", ")", ":", "text", "=", "text", ".", "rstrip"...
Returns HTML as a basestring. Parameters ---------- text : basestring Source code, typically SHPAML, but could be a different (but related) language. The remaining parameters specify details about the language used in the source code. To parse SHPAML, pass the same values as convert_shpaml_tree. branch_method : function convert_shpaml_tree passes html_block_tag here. leaf_method : function convert_shpaml_tree passes convert_line here. pass_syntax : basestring convert_shpaml_tree passes PASS_SYNTAX here. flush_left_syntax : basestring convert_shpaml_tree passes FLUSH_LEFT_SYNTAX here. flush_left_empty_line : basestring convert_shpaml_tree passes FLUSH_LEFT_EMPTY_LINE here. indentation_method : function convert_shpaml_tree passes _indent here. get_block : function Defaults to get_indented_block.
[ "Returns", "HTML", "as", "a", "basestring", "." ]
train
https://github.com/timothycrosley/short/blob/dcf25ec01b5406d9e0a35ac7dd8112239c0912a5/short/compile.py#L246-L284
timothycrosley/short
short/compile.py
indent_lines
def indent_lines(lines, output, branch_method, leaf_method, pass_syntax, flush_left_syntax, flush_left_empty_line, indentation_method, get_block): """Returns None. The way this function produces output is by adding strings to the list that's passed in as the second parameter. Parameters ---------- lines : list of basestring's Each string is a line of a SHPAML source code (trailing newlines not included). output : empty list Explained earlier... The remaining parameters are exactly the same as in the indent function: * branch_method * leaf_method * pass_syntax * flush_left_syntax * flush_left_empty_line * indentation_method * get_block """ append = output.append def recurse(prefix_lines): while prefix_lines: prefix, line = prefix_lines[0] if line == '': prefix_lines.pop(0) append('') continue block_size = get_block(prefix_lines) if block_size == 1: prefix_lines.pop(0) if line == pass_syntax: pass elif line.startswith(flush_left_syntax): append(line[len(flush_left_syntax):]) elif line.startswith(flush_left_empty_line): append('') else: append(prefix + leaf_method(line)) else: block = prefix_lines[:block_size] prefix_lines = prefix_lines[block_size:] branch_method(output, block, recurse) return prefix_lines = list(map(indentation_method, lines)) recurse(prefix_lines)
python
def indent_lines(lines, output, branch_method, leaf_method, pass_syntax, flush_left_syntax, flush_left_empty_line, indentation_method, get_block): """Returns None. The way this function produces output is by adding strings to the list that's passed in as the second parameter. Parameters ---------- lines : list of basestring's Each string is a line of a SHPAML source code (trailing newlines not included). output : empty list Explained earlier... The remaining parameters are exactly the same as in the indent function: * branch_method * leaf_method * pass_syntax * flush_left_syntax * flush_left_empty_line * indentation_method * get_block """ append = output.append def recurse(prefix_lines): while prefix_lines: prefix, line = prefix_lines[0] if line == '': prefix_lines.pop(0) append('') continue block_size = get_block(prefix_lines) if block_size == 1: prefix_lines.pop(0) if line == pass_syntax: pass elif line.startswith(flush_left_syntax): append(line[len(flush_left_syntax):]) elif line.startswith(flush_left_empty_line): append('') else: append(prefix + leaf_method(line)) else: block = prefix_lines[:block_size] prefix_lines = prefix_lines[block_size:] branch_method(output, block, recurse) return prefix_lines = list(map(indentation_method, lines)) recurse(prefix_lines)
[ "def", "indent_lines", "(", "lines", ",", "output", ",", "branch_method", ",", "leaf_method", ",", "pass_syntax", ",", "flush_left_syntax", ",", "flush_left_empty_line", ",", "indentation_method", ",", "get_block", ")", ":", "append", "=", "output", ".", "append",...
Returns None. The way this function produces output is by adding strings to the list that's passed in as the second parameter. Parameters ---------- lines : list of basestring's Each string is a line of a SHPAML source code (trailing newlines not included). output : empty list Explained earlier... The remaining parameters are exactly the same as in the indent function: * branch_method * leaf_method * pass_syntax * flush_left_syntax * flush_left_empty_line * indentation_method * get_block
[ "Returns", "None", "." ]
train
https://github.com/timothycrosley/short/blob/dcf25ec01b5406d9e0a35ac7dd8112239c0912a5/short/compile.py#L287-L341
etcher-be/epab
epab/cmd/_reqs.py
_write_reqs
def _write_reqs(amend: bool = False, stage: bool = False): """ Writes the requirement files Args: amend: amend last commit with changes stage: stage changes """ LOGGER.info('writing requirements') base_cmd = 'pipenv lock -r' _write_reqs_file(f'{base_cmd}', 'requirements.txt') _write_reqs_file(f'{base_cmd} -d', 'requirements-dev.txt') files_to_add = ['Pipfile', 'requirements.txt', 'requirements-dev.txt'] if amend: CTX.repo.amend_commit(append_to_msg='update requirements [auto]', files_to_add=files_to_add) elif stage: CTX.repo.stage_subset(*files_to_add)
python
def _write_reqs(amend: bool = False, stage: bool = False): """ Writes the requirement files Args: amend: amend last commit with changes stage: stage changes """ LOGGER.info('writing requirements') base_cmd = 'pipenv lock -r' _write_reqs_file(f'{base_cmd}', 'requirements.txt') _write_reqs_file(f'{base_cmd} -d', 'requirements-dev.txt') files_to_add = ['Pipfile', 'requirements.txt', 'requirements-dev.txt'] if amend: CTX.repo.amend_commit(append_to_msg='update requirements [auto]', files_to_add=files_to_add) elif stage: CTX.repo.stage_subset(*files_to_add)
[ "def", "_write_reqs", "(", "amend", ":", "bool", "=", "False", ",", "stage", ":", "bool", "=", "False", ")", ":", "LOGGER", ".", "info", "(", "'writing requirements'", ")", "base_cmd", "=", "'pipenv lock -r'", "_write_reqs_file", "(", "f'{base_cmd}'", ",", "...
Writes the requirement files Args: amend: amend last commit with changes stage: stage changes
[ "Writes", "the", "requirement", "files" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/cmd/_reqs.py#L35-L53
etcher-be/epab
epab/cmd/_reqs.py
reqs
def reqs(amend: bool = False, stage: bool = False): """ Write requirements files Args: amend: amend last commit with changes stage: stage changes """ changed_files = CTX.repo.changed_files() if 'requirements.txt' in changed_files or 'requirements-dev.txt' in changed_files: LOGGER.error('Requirements have changed; cannot update them') sys.exit(-1) _write_reqs(amend, stage)
python
def reqs(amend: bool = False, stage: bool = False): """ Write requirements files Args: amend: amend last commit with changes stage: stage changes """ changed_files = CTX.repo.changed_files() if 'requirements.txt' in changed_files or 'requirements-dev.txt' in changed_files: LOGGER.error('Requirements have changed; cannot update them') sys.exit(-1) _write_reqs(amend, stage)
[ "def", "reqs", "(", "amend", ":", "bool", "=", "False", ",", "stage", ":", "bool", "=", "False", ")", ":", "changed_files", "=", "CTX", ".", "repo", ".", "changed_files", "(", ")", "if", "'requirements.txt'", "in", "changed_files", "or", "'requirements-dev...
Write requirements files Args: amend: amend last commit with changes stage: stage changes
[ "Write", "requirements", "files" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/cmd/_reqs.py#L59-L71
cohorte/cohorte-herald
python/snippets/herald_irc/client.py
chunks
def chunks(data, size): """ Generator that splits the given data into chunks """ for i in range(0, len(data), size): yield data[i:i + size]
python
def chunks(data, size): """ Generator that splits the given data into chunks """ for i in range(0, len(data), size): yield data[i:i + size]
[ "def", "chunks", "(", "data", ",", "size", ")", ":", "for", "i", "in", "range", "(", "0", ",", "len", "(", "data", ")", ",", "size", ")", ":", "yield", "data", "[", "i", ":", "i", "+", "size", "]" ]
Generator that splits the given data into chunks
[ "Generator", "that", "splits", "the", "given", "data", "into", "chunks" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_irc/client.py#L21-L26
cohorte/cohorte-herald
python/snippets/herald_irc/client.py
main
def main(): """ Entry point """ client_1 = MessageBot("verne", "Jules Verne") client_1.start() client_1.connect("127.0.0.1") client_2 = MessageBot("adams", "Douglas Adams") client_2.start() client_2.connect("127.0.0.1") herald_1 = Herald(client_1) herald_1.start() herald_2 = Herald(client_2) herald_2.start() handler = LogHandler() herald_1.register('/toto/*', handler) herald_2.register('/toto/*', handler) cmd = HeraldBot("bot", "Robotnik", herald_1) cmd.connect("127.0.0.1") cmd.wait_stop() for closable in (client_1, client_2, herald_1, herald_2): closable.close() logging.info("Bye !")
python
def main(): """ Entry point """ client_1 = MessageBot("verne", "Jules Verne") client_1.start() client_1.connect("127.0.0.1") client_2 = MessageBot("adams", "Douglas Adams") client_2.start() client_2.connect("127.0.0.1") herald_1 = Herald(client_1) herald_1.start() herald_2 = Herald(client_2) herald_2.start() handler = LogHandler() herald_1.register('/toto/*', handler) herald_2.register('/toto/*', handler) cmd = HeraldBot("bot", "Robotnik", herald_1) cmd.connect("127.0.0.1") cmd.wait_stop() for closable in (client_1, client_2, herald_1, herald_2): closable.close() logging.info("Bye !")
[ "def", "main", "(", ")", ":", "client_1", "=", "MessageBot", "(", "\"verne\"", ",", "\"Jules Verne\"", ")", "client_1", ".", "start", "(", ")", "client_1", ".", "connect", "(", "\"127.0.0.1\"", ")", "client_2", "=", "MessageBot", "(", "\"adams\"", ",", "\"...
Entry point
[ "Entry", "point" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_irc/client.py#L685-L715
cohorte/cohorte-herald
python/snippets/herald_irc/client.py
Bot.connect
def connect(self, host, port=6667, password=None): """ Connects to a server """ # Prepare the callbacks self._irc.add_global_handler('all_events', self.__handler) # Prepare the connection self._connection = self._irc.server().connect( host, port, self._nickname, password, self._username, self._realname) # Start connection thread self.__stopped.clear() self.__thread = threading.Thread(target=self.__loop, name="IRC-Bot-Loop") self.__thread.daemon = True self.__thread.start()
python
def connect(self, host, port=6667, password=None): """ Connects to a server """ # Prepare the callbacks self._irc.add_global_handler('all_events', self.__handler) # Prepare the connection self._connection = self._irc.server().connect( host, port, self._nickname, password, self._username, self._realname) # Start connection thread self.__stopped.clear() self.__thread = threading.Thread(target=self.__loop, name="IRC-Bot-Loop") self.__thread.daemon = True self.__thread.start()
[ "def", "connect", "(", "self", ",", "host", ",", "port", "=", "6667", ",", "password", "=", "None", ")", ":", "# Prepare the callbacks", "self", ".", "_irc", ".", "add_global_handler", "(", "'all_events'", ",", "self", ".", "__handler", ")", "# Prepare the c...
Connects to a server
[ "Connects", "to", "a", "server" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_irc/client.py#L52-L69
cohorte/cohorte-herald
python/snippets/herald_irc/client.py
Bot.__handler
def __handler(self, connection, event): """ Handles an IRC event """ try: # Find local handler method = getattr(self, "on_{0}".format(event.type)) except AttributeError: pass else: try: # Call it return method(connection, event) except Exception as ex: logging.exception("Error calling handler: %s", ex)
python
def __handler(self, connection, event): """ Handles an IRC event """ try: # Find local handler method = getattr(self, "on_{0}".format(event.type)) except AttributeError: pass else: try: # Call it return method(connection, event) except Exception as ex: logging.exception("Error calling handler: %s", ex)
[ "def", "__handler", "(", "self", ",", "connection", ",", "event", ")", ":", "try", ":", "# Find local handler", "method", "=", "getattr", "(", "self", ",", "\"on_{0}\"", ".", "format", "(", "event", ".", "type", ")", ")", "except", "AttributeError", ":", ...
Handles an IRC event
[ "Handles", "an", "IRC", "event" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_irc/client.py#L79-L93
cohorte/cohorte-herald
python/snippets/herald_irc/client.py
Bot.close
def close(self): """ Disconnects from the server """ # Disconnect with a fancy message, then close connection if self._connection is not None: self._connection.disconnect("Bot is quitting") self._connection.close() self._connection = None # Stop the client loop self.__stopped.set() if self.__thread is not None: try: self.__thread.join(5) except RuntimeError: pass self.__thread = None
python
def close(self): """ Disconnects from the server """ # Disconnect with a fancy message, then close connection if self._connection is not None: self._connection.disconnect("Bot is quitting") self._connection.close() self._connection = None # Stop the client loop self.__stopped.set() if self.__thread is not None: try: self.__thread.join(5) except RuntimeError: pass self.__thread = None
[ "def", "close", "(", "self", ")", ":", "# Disconnect with a fancy message, then close connection", "if", "self", ".", "_connection", "is", "not", "None", ":", "self", ".", "_connection", ".", "disconnect", "(", "\"Bot is quitting\"", ")", "self", ".", "_connection",...
Disconnects from the server
[ "Disconnects", "from", "the", "server" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_irc/client.py#L96-L114
cohorte/cohorte-herald
python/snippets/herald_irc/client.py
Bot.wait
def wait(self, timeout=None): """ Waits for the client to stop its loop """ self.__stopped.wait(timeout) return self.__stopped.is_set()
python
def wait(self, timeout=None): """ Waits for the client to stop its loop """ self.__stopped.wait(timeout) return self.__stopped.is_set()
[ "def", "wait", "(", "self", ",", "timeout", "=", "None", ")", ":", "self", ".", "__stopped", ".", "wait", "(", "timeout", ")", "return", "self", ".", "__stopped", ".", "is_set", "(", ")" ]
Waits for the client to stop its loop
[ "Waits", "for", "the", "client", "to", "stop", "its", "loop" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_irc/client.py#L117-L122
cohorte/cohorte-herald
python/snippets/herald_irc/client.py
CommandBot.on_welcome
def on_welcome(self, connection, event): """ Server welcome: we're connected """ # Start the pool self.__pool.start() logging.info("! Connected to server '%s': %s", event.source, event.arguments[0]) connection.join("#cohorte")
python
def on_welcome(self, connection, event): """ Server welcome: we're connected """ # Start the pool self.__pool.start() logging.info("! Connected to server '%s': %s", event.source, event.arguments[0]) connection.join("#cohorte")
[ "def", "on_welcome", "(", "self", ",", "connection", ",", "event", ")", ":", "# Start the pool", "self", ".", "__pool", ".", "start", "(", ")", "logging", ".", "info", "(", "\"! Connected to server '%s': %s\"", ",", "event", ".", "source", ",", "event", ".",...
Server welcome: we're connected
[ "Server", "welcome", ":", "we", "re", "connected" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_irc/client.py#L147-L156
cohorte/cohorte-herald
python/snippets/herald_irc/client.py
CommandBot.on_pubmsg
def on_pubmsg(self, connection, event): """ Got a message from a channel """ sender = self.get_nick(event.source) channel = event.target message = event.arguments[0] self.handle_message(connection, sender, channel, message)
python
def on_pubmsg(self, connection, event): """ Got a message from a channel """ sender = self.get_nick(event.source) channel = event.target message = event.arguments[0] self.handle_message(connection, sender, channel, message)
[ "def", "on_pubmsg", "(", "self", ",", "connection", ",", "event", ")", ":", "sender", "=", "self", ".", "get_nick", "(", "event", ".", "source", ")", "channel", "=", "event", ".", "target", "message", "=", "event", ".", "arguments", "[", "0", "]", "s...
Got a message from a channel
[ "Got", "a", "message", "from", "a", "channel" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_irc/client.py#L166-L174
cohorte/cohorte-herald
python/snippets/herald_irc/client.py
CommandBot.on_privmsg
def on_privmsg(self, connection, event): """ Got a message from a user """ sender = self.get_nick(event.source) message = event.arguments[0] if sender == 'NickServ': logging.info("Got message from NickServ: %s", message) if "password" in message.lower(): connection.privmsg("NickServ", "pass") else: connection.join('#cohorte') return self.handle_message(connection, sender, sender, message)
python
def on_privmsg(self, connection, event): """ Got a message from a user """ sender = self.get_nick(event.source) message = event.arguments[0] if sender == 'NickServ': logging.info("Got message from NickServ: %s", message) if "password" in message.lower(): connection.privmsg("NickServ", "pass") else: connection.join('#cohorte') return self.handle_message(connection, sender, sender, message)
[ "def", "on_privmsg", "(", "self", ",", "connection", ",", "event", ")", ":", "sender", "=", "self", ".", "get_nick", "(", "event", ".", "source", ")", "message", "=", "event", ".", "arguments", "[", "0", "]", "if", "sender", "==", "'NickServ'", ":", ...
Got a message from a user
[ "Got", "a", "message", "from", "a", "user" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_irc/client.py#L177-L193
cohorte/cohorte-herald
python/snippets/herald_irc/client.py
CommandBot.handle_message
def handle_message(self, connection, sender, target, message): """ Handles a received message """ parts = message.strip().split(' ', 2) if parts and parts[0].lower() == '!bot': try: command = parts[1].lower() except IndexError: self.safe_send(connection, target, "No command given") return try: payload = parts[2] except IndexError: payload = "" self.__pool.enqueue(self._handle_command, connection, sender, target, command, payload)
python
def handle_message(self, connection, sender, target, message): """ Handles a received message """ parts = message.strip().split(' ', 2) if parts and parts[0].lower() == '!bot': try: command = parts[1].lower() except IndexError: self.safe_send(connection, target, "No command given") return try: payload = parts[2] except IndexError: payload = "" self.__pool.enqueue(self._handle_command, connection, sender, target, command, payload)
[ "def", "handle_message", "(", "self", ",", "connection", ",", "sender", ",", "target", ",", "message", ")", ":", "parts", "=", "message", ".", "strip", "(", ")", ".", "split", "(", "' '", ",", "2", ")", "if", "parts", "and", "parts", "[", "0", "]",...
Handles a received message
[ "Handles", "a", "received", "message" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_irc/client.py#L196-L214
cohorte/cohorte-herald
python/snippets/herald_irc/client.py
CommandBot.on_invite
def on_invite(self, connection, event): """ Got an invitation to a channel """ sender = self.get_nick(event.source) invited = self.get_nick(event.target) channel = event.arguments[0] if invited == self._nickname: logging.info("! I am invited to %s by %s", channel, sender) connection.join(channel) else: logging.info(">> %s invited %s to %s", sender, invited, channel)
python
def on_invite(self, connection, event): """ Got an invitation to a channel """ sender = self.get_nick(event.source) invited = self.get_nick(event.target) channel = event.arguments[0] if invited == self._nickname: logging.info("! I am invited to %s by %s", channel, sender) connection.join(channel) else: logging.info(">> %s invited %s to %s", sender, invited, channel)
[ "def", "on_invite", "(", "self", ",", "connection", ",", "event", ")", ":", "sender", "=", "self", ".", "get_nick", "(", "event", ".", "source", ")", "invited", "=", "self", ".", "get_nick", "(", "event", ".", "target", ")", "channel", "=", "event", ...
Got an invitation to a channel
[ "Got", "an", "invitation", "to", "a", "channel" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_irc/client.py#L217-L230
cohorte/cohorte-herald
python/snippets/herald_irc/client.py
CommandBot._handle_command
def _handle_command(self, connection, sender, target, command, payload): """ Handles a command, if any """ try: # Find the handler handler = getattr(self, "cmd_{0}".format(command)) except AttributeError: self.safe_send(connection, target, "Unknown command: %s", command) else: try: logging.info("! Handling command: %s", command) handler(connection, sender, target, payload) except Exception as ex: logging.exception("Error calling command handler: %s", ex)
python
def _handle_command(self, connection, sender, target, command, payload): """ Handles a command, if any """ try: # Find the handler handler = getattr(self, "cmd_{0}".format(command)) except AttributeError: self.safe_send(connection, target, "Unknown command: %s", command) else: try: logging.info("! Handling command: %s", command) handler(connection, sender, target, payload) except Exception as ex: logging.exception("Error calling command handler: %s", ex)
[ "def", "_handle_command", "(", "self", ",", "connection", ",", "sender", ",", "target", ",", "command", ",", "payload", ")", ":", "try", ":", "# Find the handler", "handler", "=", "getattr", "(", "self", ",", "\"cmd_{0}\"", ".", "format", "(", "command", "...
Handles a command, if any
[ "Handles", "a", "command", "if", "any" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_irc/client.py#L233-L248
cohorte/cohorte-herald
python/snippets/herald_irc/client.py
CommandBot.safe_send
def safe_send(self, connection, target, message, *args, **kwargs): """ Safely sends a message to the given target """ # Compute maximum length of payload prefix = "PRIVMSG {0} :".format(target) max_len = 510 - len(prefix) for chunk in chunks(message.format(*args, **kwargs), max_len): connection.send_raw("{0}{1}".format(prefix, chunk))
python
def safe_send(self, connection, target, message, *args, **kwargs): """ Safely sends a message to the given target """ # Compute maximum length of payload prefix = "PRIVMSG {0} :".format(target) max_len = 510 - len(prefix) for chunk in chunks(message.format(*args, **kwargs), max_len): connection.send_raw("{0}{1}".format(prefix, chunk))
[ "def", "safe_send", "(", "self", ",", "connection", ",", "target", ",", "message", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Compute maximum length of payload", "prefix", "=", "\"PRIVMSG {0} :\"", ".", "format", "(", "target", ")", "max_len", "...
Safely sends a message to the given target
[ "Safely", "sends", "a", "message", "to", "the", "given", "target" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_irc/client.py#L251-L260
cohorte/cohorte-herald
python/snippets/herald_irc/client.py
HeraldBot.cmd_send
def cmd_send(self, connection, sender, target, payload): """ Sends a message """ msg_target, topic, content = self.parse_payload(payload) results = self.__herald.send(msg_target, topic, content) self.safe_send(connection, target, "GOT RESULT: {0}".format(results))
python
def cmd_send(self, connection, sender, target, payload): """ Sends a message """ msg_target, topic, content = self.parse_payload(payload) results = self.__herald.send(msg_target, topic, content) self.safe_send(connection, target, "GOT RESULT: {0}".format(results))
[ "def", "cmd_send", "(", "self", ",", "connection", ",", "sender", ",", "target", ",", "payload", ")", ":", "msg_target", ",", "topic", ",", "content", "=", "self", ".", "parse_payload", "(", "payload", ")", "results", "=", "self", ".", "__herald", ".", ...
Sends a message
[ "Sends", "a", "message" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_irc/client.py#L288-L294
cohorte/cohorte-herald
python/snippets/herald_irc/client.py
HeraldBot.cmd_fire
def cmd_fire(self, connection, sender, target, payload): """ Sends a message """ msg_target, topic, content = self.parse_payload(payload) def callback(sender, payload): logging.info("FIRE ACK from %s", sender) self.__herald.fire(msg_target, topic, content, callback)
python
def cmd_fire(self, connection, sender, target, payload): """ Sends a message """ msg_target, topic, content = self.parse_payload(payload) def callback(sender, payload): logging.info("FIRE ACK from %s", sender) self.__herald.fire(msg_target, topic, content, callback)
[ "def", "cmd_fire", "(", "self", ",", "connection", ",", "sender", ",", "target", ",", "payload", ")", ":", "msg_target", ",", "topic", ",", "content", "=", "self", ".", "parse_payload", "(", "payload", ")", "def", "callback", "(", "sender", ",", "payload...
Sends a message
[ "Sends", "a", "message" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_irc/client.py#L297-L306
cohorte/cohorte-herald
python/snippets/herald_irc/client.py
HeraldBot.cmd_notice
def cmd_notice(self, connection, sender, target, payload): """ Sends a message """ msg_target, topic, content = self.parse_payload(payload) def callback(sender, payload): logging.info("NOTICE ACK from %s: %s", sender, payload) self.__herald.notice(msg_target, topic, content, callback)
python
def cmd_notice(self, connection, sender, target, payload): """ Sends a message """ msg_target, topic, content = self.parse_payload(payload) def callback(sender, payload): logging.info("NOTICE ACK from %s: %s", sender, payload) self.__herald.notice(msg_target, topic, content, callback)
[ "def", "cmd_notice", "(", "self", ",", "connection", ",", "sender", ",", "target", ",", "payload", ")", ":", "msg_target", ",", "topic", ",", "content", "=", "self", ".", "parse_payload", "(", "payload", ")", "def", "callback", "(", "sender", ",", "paylo...
Sends a message
[ "Sends", "a", "message" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_irc/client.py#L309-L318
cohorte/cohorte-herald
python/snippets/herald_irc/client.py
HeraldBot.cmd_post
def cmd_post(self, connection, sender, target, payload): """ Sends a message """ msg_target, topic, content = self.parse_payload(payload) def callback(sender, payload): logging.info("POST RES from %s: %s", sender, payload) self.__herald.post(msg_target, topic, content, callback)
python
def cmd_post(self, connection, sender, target, payload): """ Sends a message """ msg_target, topic, content = self.parse_payload(payload) def callback(sender, payload): logging.info("POST RES from %s: %s", sender, payload) self.__herald.post(msg_target, topic, content, callback)
[ "def", "cmd_post", "(", "self", ",", "connection", ",", "sender", ",", "target", ",", "payload", ")", ":", "msg_target", ",", "topic", ",", "content", "=", "self", ".", "parse_payload", "(", "payload", ")", "def", "callback", "(", "sender", ",", "payload...
Sends a message
[ "Sends", "a", "message" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_irc/client.py#L321-L330
cohorte/cohorte-herald
python/snippets/herald_irc/client.py
MessageBot.on_privmsg
def on_privmsg(self, connection, event): """ Got a message from a channel """ sender = self.get_nick(event.source) message = event.arguments[0] if sender == 'NickServ': logging.info("Got message from NickServ: %s", message) if "password" in message.lower(): connection.privmsg("NickServ", "pass") else: connection.join('#cohorte') return self._pool.enqueue(self.__on_message, connection, sender, message)
python
def on_privmsg(self, connection, event): """ Got a message from a channel """ sender = self.get_nick(event.source) message = event.arguments[0] if sender == 'NickServ': logging.info("Got message from NickServ: %s", message) if "password" in message.lower(): connection.privmsg("NickServ", "pass") else: connection.join('#cohorte') return self._pool.enqueue(self.__on_message, connection, sender, message)
[ "def", "on_privmsg", "(", "self", ",", "connection", ",", "event", ")", ":", "sender", "=", "self", ".", "get_nick", "(", "event", ".", "source", ")", "message", "=", "event", ".", "arguments", "[", "0", "]", "if", "sender", "==", "'NickServ'", ":", ...
Got a message from a channel
[ "Got", "a", "message", "from", "a", "channel" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_irc/client.py#L405-L421
cohorte/cohorte-herald
python/snippets/herald_irc/client.py
MessageBot.__on_message
def __on_message(self, connection, sender, message): """ Got a message from a channel """ if message.strip() == '!bot send': cycle = itertools.cycle(string.digits) content = ''.join(next(cycle) for _ in range(100)) self.send_message(sender, content) else: parts = message.split(':', 2) if not parts or parts[0] != 'HRLD': return if parts[1] == 'BEGIN': # Beginning of multi-line message self._queue[parts[2]] = [] elif parts[1] == 'END': # End of multi-line message content = ''.join(self._queue.pop(parts[2])) self.__notify(sender, content) elif parts[1] == 'MSG': # Single-line message content = parts[2] self.__notify(sender, content) else: # Multi-line message continuation uid = parts[1] self._queue[uid].append(parts[2])
python
def __on_message(self, connection, sender, message): """ Got a message from a channel """ if message.strip() == '!bot send': cycle = itertools.cycle(string.digits) content = ''.join(next(cycle) for _ in range(100)) self.send_message(sender, content) else: parts = message.split(':', 2) if not parts or parts[0] != 'HRLD': return if parts[1] == 'BEGIN': # Beginning of multi-line message self._queue[parts[2]] = [] elif parts[1] == 'END': # End of multi-line message content = ''.join(self._queue.pop(parts[2])) self.__notify(sender, content) elif parts[1] == 'MSG': # Single-line message content = parts[2] self.__notify(sender, content) else: # Multi-line message continuation uid = parts[1] self._queue[uid].append(parts[2])
[ "def", "__on_message", "(", "self", ",", "connection", ",", "sender", ",", "message", ")", ":", "if", "message", ".", "strip", "(", ")", "==", "'!bot send'", ":", "cycle", "=", "itertools", ".", "cycle", "(", "string", ".", "digits", ")", "content", "=...
Got a message from a channel
[ "Got", "a", "message", "from", "a", "channel" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_irc/client.py#L427-L458
cohorte/cohorte-herald
python/snippets/herald_irc/client.py
MessageBot.__notify
def __notify(self, sender, content): """ Calls back listener when a message is received """ if self.handle_message is not None: try: self.handle_message(sender, content) except Exception as ex: logging.exception("Error calling message listener: %s", ex)
python
def __notify(self, sender, content): """ Calls back listener when a message is received """ if self.handle_message is not None: try: self.handle_message(sender, content) except Exception as ex: logging.exception("Error calling message listener: %s", ex)
[ "def", "__notify", "(", "self", ",", "sender", ",", "content", ")", ":", "if", "self", ".", "handle_message", "is", "not", "None", ":", "try", ":", "self", ".", "handle_message", "(", "sender", ",", "content", ")", "except", "Exception", "as", "ex", ":...
Calls back listener when a message is received
[ "Calls", "back", "listener", "when", "a", "message", "is", "received" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_irc/client.py#L461-L469
cohorte/cohorte-herald
python/snippets/herald_irc/client.py
MessageBot._make_line
def _make_line(self, uid, command=None): """ Prepares an IRC line in Herald's format """ if command: return ":".join(("HRLD", command, uid)) else: return ":".join(("HRLD", uid))
python
def _make_line(self, uid, command=None): """ Prepares an IRC line in Herald's format """ if command: return ":".join(("HRLD", command, uid)) else: return ":".join(("HRLD", uid))
[ "def", "_make_line", "(", "self", ",", "uid", ",", "command", "=", "None", ")", ":", "if", "command", ":", "return", "\":\"", ".", "join", "(", "(", "\"HRLD\"", ",", "command", ",", "uid", ")", ")", "else", ":", "return", "\":\"", ".", "join", "(",...
Prepares an IRC line in Herald's format
[ "Prepares", "an", "IRC", "line", "in", "Herald", "s", "format" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_irc/client.py#L472-L479
cohorte/cohorte-herald
python/snippets/herald_irc/client.py
MessageBot.send_message
def send_message(self, target, content, uid=None): """ Sends a message through IRC """ # Compute maximum length of payload prefix = "PRIVMSG {0} :".format(target) single_prefix = self._make_line("MSG:") single_prefix_len = len(single_prefix) max_len = 510 - len(prefix) content_len = len(content) if (content_len + single_prefix_len) < max_len: # One pass message self._connection.send_raw("{0}{1}{2}" \ .format(prefix, single_prefix, content)) else: # Multiple-passes message uid = uid or str(uuid.uuid4()).replace('-', '').upper() prefix = "{0}{1}:".format(prefix, self._make_line(uid)) max_len = 510 - len(prefix) self._connection.privmsg(target, self._make_line(uid, "BEGIN")) for chunk in chunks(content, max_len): self._connection.send_raw(''.join((prefix, chunk))) self._connection.privmsg(target, self._make_line(uid, "END"))
python
def send_message(self, target, content, uid=None): """ Sends a message through IRC """ # Compute maximum length of payload prefix = "PRIVMSG {0} :".format(target) single_prefix = self._make_line("MSG:") single_prefix_len = len(single_prefix) max_len = 510 - len(prefix) content_len = len(content) if (content_len + single_prefix_len) < max_len: # One pass message self._connection.send_raw("{0}{1}{2}" \ .format(prefix, single_prefix, content)) else: # Multiple-passes message uid = uid or str(uuid.uuid4()).replace('-', '').upper() prefix = "{0}{1}:".format(prefix, self._make_line(uid)) max_len = 510 - len(prefix) self._connection.privmsg(target, self._make_line(uid, "BEGIN")) for chunk in chunks(content, max_len): self._connection.send_raw(''.join((prefix, chunk))) self._connection.privmsg(target, self._make_line(uid, "END"))
[ "def", "send_message", "(", "self", ",", "target", ",", "content", ",", "uid", "=", "None", ")", ":", "# Compute maximum length of payload", "prefix", "=", "\"PRIVMSG {0} :\"", ".", "format", "(", "target", ")", "single_prefix", "=", "self", ".", "_make_line", ...
Sends a message through IRC
[ "Sends", "a", "message", "through", "IRC" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_irc/client.py#L482-L509
cohorte/cohorte-herald
python/snippets/herald_irc/client.py
Herald.__make_message
def __make_message(self, topic, content): """ Prepares the message content """ return {"uid": str(uuid.uuid4()).replace('-', '').upper(), "topic": topic, "content": content}
python
def __make_message(self, topic, content): """ Prepares the message content """ return {"uid": str(uuid.uuid4()).replace('-', '').upper(), "topic": topic, "content": content}
[ "def", "__make_message", "(", "self", ",", "topic", ",", "content", ")", ":", "return", "{", "\"uid\"", ":", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", ".", "replace", "(", "'-'", ",", "''", ")", ".", "upper", "(", ")", ",", "\"topic\"", ":...
Prepares the message content
[ "Prepares", "the", "message", "content" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_irc/client.py#L538-L544
cohorte/cohorte-herald
python/snippets/herald_irc/client.py
Herald.fire
def fire(self, target, topic, content, callback=None): """ Fires a message """ message = self.__make_message(topic, content) if callback is not None: self.__callbacks[message['uid']] = ('fire', callback) self.__client.send_message(target, json.dumps(message), message['uid'])
python
def fire(self, target, topic, content, callback=None): """ Fires a message """ message = self.__make_message(topic, content) if callback is not None: self.__callbacks[message['uid']] = ('fire', callback) self.__client.send_message(target, json.dumps(message), message['uid'])
[ "def", "fire", "(", "self", ",", "target", ",", "topic", ",", "content", ",", "callback", "=", "None", ")", ":", "message", "=", "self", ".", "__make_message", "(", "topic", ",", "content", ")", "if", "callback", "is", "not", "None", ":", "self", "."...
Fires a message
[ "Fires", "a", "message" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_irc/client.py#L547-L555
cohorte/cohorte-herald
python/snippets/herald_irc/client.py
Herald.send
def send(self, target, topic, content): """ Fires a message """ event = threading.Event() results = [] def got_message(sender, content): results.append(content) event.set() self.post(target, topic, content, got_message) event.wait() return results
python
def send(self, target, topic, content): """ Fires a message """ event = threading.Event() results = [] def got_message(sender, content): results.append(content) event.set() self.post(target, topic, content, got_message) event.wait() return results
[ "def", "send", "(", "self", ",", "target", ",", "topic", ",", "content", ")", ":", "event", "=", "threading", ".", "Event", "(", ")", "results", "=", "[", "]", "def", "got_message", "(", "sender", ",", "content", ")", ":", "results", ".", "append", ...
Fires a message
[ "Fires", "a", "message" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_irc/client.py#L569-L583
cohorte/cohorte-herald
python/snippets/herald_irc/client.py
Herald._notify_listeners
def _notify_listeners(self, sender, message): """ Notifies listeners of a new message """ uid = message['uid'] msg_topic = message['topic'] self._ack(sender, uid, 'fire') all_listeners = set() for lst_topic, listeners in self.__listeners.items(): if fnmatch.fnmatch(msg_topic, lst_topic): all_listeners.update(listeners) self._ack(sender, uid, 'notice', 'ok' if all_listeners else 'none') try: results = [] for listener in all_listeners: result = listener.handle_message(sender, message['topic'], message['content']) if result: results.append(result) self._ack(sender, uid, 'send', json.dumps(results)) except: self._ack(sender, uid, 'send', "Error")
python
def _notify_listeners(self, sender, message): """ Notifies listeners of a new message """ uid = message['uid'] msg_topic = message['topic'] self._ack(sender, uid, 'fire') all_listeners = set() for lst_topic, listeners in self.__listeners.items(): if fnmatch.fnmatch(msg_topic, lst_topic): all_listeners.update(listeners) self._ack(sender, uid, 'notice', 'ok' if all_listeners else 'none') try: results = [] for listener in all_listeners: result = listener.handle_message(sender, message['topic'], message['content']) if result: results.append(result) self._ack(sender, uid, 'send', json.dumps(results)) except: self._ack(sender, uid, 'send', "Error")
[ "def", "_notify_listeners", "(", "self", ",", "sender", ",", "message", ")", ":", "uid", "=", "message", "[", "'uid'", "]", "msg_topic", "=", "message", "[", "'topic'", "]", "self", ".", "_ack", "(", "sender", ",", "uid", ",", "'fire'", ")", "all_liste...
Notifies listeners of a new message
[ "Notifies", "listeners", "of", "a", "new", "message" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_irc/client.py#L597-L625
cohorte/cohorte-herald
python/snippets/herald_irc/client.py
Herald._ack
def _ack(self, sender, uid, level, payload=None): """ Replies to a message """ content = {'reply-to': uid, 'reply-level': level, 'payload': payload} self.__client.send_message(sender, json.dumps(content))
python
def _ack(self, sender, uid, level, payload=None): """ Replies to a message """ content = {'reply-to': uid, 'reply-level': level, 'payload': payload} self.__client.send_message(sender, json.dumps(content))
[ "def", "_ack", "(", "self", ",", "sender", ",", "uid", ",", "level", ",", "payload", "=", "None", ")", ":", "content", "=", "{", "'reply-to'", ":", "uid", ",", "'reply-level'", ":", "level", ",", "'payload'", ":", "payload", "}", "self", ".", "__clie...
Replies to a message
[ "Replies", "to", "a", "message" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_irc/client.py#L628-L635
cohorte/cohorte-herald
python/snippets/herald_irc/client.py
Herald.on_message
def on_message(self, sender, content): """ Got a message from the client """ try: message = json.loads(content) except (ValueError, TypeError) as ex: logging.error("Not a valid JSON string: %s", ex) return try: # Check the replied message reply_uid = message['reply-to'] reply_level = message['reply-level'] except KeyError: # Got a new message logging.info("Got message %s from %s", message['content'], sender) # Notify listeners self.__pool.enqueue(self._notify_listeners, sender, message) else: # Got a reply try: level, callback = self.__callbacks[reply_uid] except KeyError: # Nobody to callback... pass else: if level == reply_level: # Match try: callback(sender, message['payload']) except Exception as ex: logging.exception("Error notifying sender: %s", ex)
python
def on_message(self, sender, content): """ Got a message from the client """ try: message = json.loads(content) except (ValueError, TypeError) as ex: logging.error("Not a valid JSON string: %s", ex) return try: # Check the replied message reply_uid = message['reply-to'] reply_level = message['reply-level'] except KeyError: # Got a new message logging.info("Got message %s from %s", message['content'], sender) # Notify listeners self.__pool.enqueue(self._notify_listeners, sender, message) else: # Got a reply try: level, callback = self.__callbacks[reply_uid] except KeyError: # Nobody to callback... pass else: if level == reply_level: # Match try: callback(sender, message['payload']) except Exception as ex: logging.exception("Error notifying sender: %s", ex)
[ "def", "on_message", "(", "self", ",", "sender", ",", "content", ")", ":", "try", ":", "message", "=", "json", ".", "loads", "(", "content", ")", "except", "(", "ValueError", ",", "TypeError", ")", "as", "ex", ":", "logging", ".", "error", "(", "\"No...
Got a message from the client
[ "Got", "a", "message", "from", "the", "client" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_irc/client.py#L638-L676
tk0miya/tk.phpautodoc
src/phply/phplex.py
t_php_OBJECT_OPERATOR
def t_php_OBJECT_OPERATOR(t): r'->' if re.match(r'[A-Za-z_]', peek(t.lexer)): t.lexer.push_state('property') return t
python
def t_php_OBJECT_OPERATOR(t): r'->' if re.match(r'[A-Za-z_]', peek(t.lexer)): t.lexer.push_state('property') return t
[ "def", "t_php_OBJECT_OPERATOR", "(", "t", ")", ":", "if", "re", ".", "match", "(", "r'[A-Za-z_]'", ",", "peek", "(", "t", ".", "lexer", ")", ")", ":", "t", ".", "lexer", ".", "push_state", "(", "'property'", ")", "return", "t" ]
r'->
[ "r", "-", ">" ]
train
https://github.com/tk0miya/tk.phpautodoc/blob/cf789f64abaf76351485cee231a075227e665fb6/src/phply/phplex.py#L182-L186
tk0miya/tk.phpautodoc
src/phply/phplex.py
t_OPEN_TAG
def t_OPEN_TAG(t): r'<[?%]((php[ \t\r\n]?)|=)?' if '=' in t.value: t.type = 'OPEN_TAG_WITH_ECHO' t.lexer.lineno += t.value.count("\n") t.lexer.begin('php') return t
python
def t_OPEN_TAG(t): r'<[?%]((php[ \t\r\n]?)|=)?' if '=' in t.value: t.type = 'OPEN_TAG_WITH_ECHO' t.lexer.lineno += t.value.count("\n") t.lexer.begin('php') return t
[ "def", "t_OPEN_TAG", "(", "t", ")", ":", "if", "'='", "in", "t", ".", "value", ":", "t", ".", "type", "=", "'OPEN_TAG_WITH_ECHO'", "t", ".", "lexer", ".", "lineno", "+=", "t", ".", "value", ".", "count", "(", "\"\\n\"", ")", "t", ".", "lexer", "....
r'<[?%]((php[ \t\r\n]?)|=)?
[ "r", "<", "[", "?%", "]", "((", "php", "[", "\\", "t", "\\", "r", "\\", "n", "]", "?", ")", "|", "=", ")", "?" ]
train
https://github.com/tk0miya/tk.phpautodoc/blob/cf789f64abaf76351485cee231a075227e665fb6/src/phply/phplex.py#L243-L248
tk0miya/tk.phpautodoc
src/phply/phplex.py
t_php_CLOSE_TAG
def t_php_CLOSE_TAG(t): r'[?%]>\r?\n?' t.lexer.lineno += t.value.count("\n") t.lexer.begin('INITIAL') return t
python
def t_php_CLOSE_TAG(t): r'[?%]>\r?\n?' t.lexer.lineno += t.value.count("\n") t.lexer.begin('INITIAL') return t
[ "def", "t_php_CLOSE_TAG", "(", "t", ")", ":", "t", ".", "lexer", ".", "lineno", "+=", "t", ".", "value", ".", "count", "(", "\"\\n\"", ")", "t", ".", "lexer", ".", "begin", "(", "'INITIAL'", ")", "return", "t" ]
r'[?%]>\r?\n?
[ "r", "[", "?%", "]", ">", "\\", "r?", "\\", "n?" ]
train
https://github.com/tk0miya/tk.phpautodoc/blob/cf789f64abaf76351485cee231a075227e665fb6/src/phply/phplex.py#L250-L254
tk0miya/tk.phpautodoc
src/phply/phplex.py
t_php_STRING
def t_php_STRING(t): r'[A-Za-z_][\w_]*' t.type = reserved_map.get(t.value.upper(), 'STRING') return t
python
def t_php_STRING(t): r'[A-Za-z_][\w_]*' t.type = reserved_map.get(t.value.upper(), 'STRING') return t
[ "def", "t_php_STRING", "(", "t", ")", ":", "t", ".", "type", "=", "reserved_map", ".", "get", "(", "t", ".", "value", ".", "upper", "(", ")", ",", "'STRING'", ")", "return", "t" ]
r'[A-Za-z_][\w_]*
[ "r", "[", "A", "-", "Za", "-", "z_", "]", "[", "\\", "w_", "]", "*" ]
train
https://github.com/tk0miya/tk.phpautodoc/blob/cf789f64abaf76351485cee231a075227e665fb6/src/phply/phplex.py#L284-L287
tk0miya/tk.phpautodoc
src/phply/phplex.py
t_quoted_DOLLAR_OPEN_CURLY_BRACES
def t_quoted_DOLLAR_OPEN_CURLY_BRACES(t): r'\$\{' if re.match(r'[A-Za-z_]', peek(t.lexer)): t.lexer.push_state('varname') else: t.lexer.push_state('php') return t
python
def t_quoted_DOLLAR_OPEN_CURLY_BRACES(t): r'\$\{' if re.match(r'[A-Za-z_]', peek(t.lexer)): t.lexer.push_state('varname') else: t.lexer.push_state('php') return t
[ "def", "t_quoted_DOLLAR_OPEN_CURLY_BRACES", "(", "t", ")", ":", "if", "re", ".", "match", "(", "r'[A-Za-z_]'", ",", "peek", "(", "t", ".", "lexer", ")", ")", ":", "t", ".", "lexer", ".", "push_state", "(", "'varname'", ")", "else", ":", "t", ".", "le...
r'\$\{
[ "r", "\\", "$", "\\", "{" ]
train
https://github.com/tk0miya/tk.phpautodoc/blob/cf789f64abaf76351485cee231a075227e665fb6/src/phply/phplex.py#L335-L341
tk0miya/tk.phpautodoc
src/phply/phplex.py
t_quotedvar_ENCAPSED_AND_WHITESPACE
def t_quotedvar_ENCAPSED_AND_WHITESPACE(t): r'( [^"\\${] | \\(.|\n) | \$(?![A-Za-z_{]) | \{(?!\$) )+' t.lexer.lineno += t.value.count("\n") t.lexer.pop_state() return t
python
def t_quotedvar_ENCAPSED_AND_WHITESPACE(t): r'( [^"\\${] | \\(.|\n) | \$(?![A-Za-z_{]) | \{(?!\$) )+' t.lexer.lineno += t.value.count("\n") t.lexer.pop_state() return t
[ "def", "t_quotedvar_ENCAPSED_AND_WHITESPACE", "(", "t", ")", ":", "t", ".", "lexer", ".", "lineno", "+=", "t", ".", "value", ".", "count", "(", "\"\\n\"", ")", "t", ".", "lexer", ".", "pop_state", "(", ")", "return", "t" ]
r'( [^"\\${] | \\(.|\n) | \$(?![A-Za-z_{]) | \{(?!\$) )+
[ "r", "(", "[", "^", "\\\\", "$", "{", "]", "|", "\\\\", "(", ".", "|", "\\", "n", ")", "|", "\\", "$", "(", "?!", "[", "A", "-", "Za", "-", "z_", "{", "]", ")", "|", "\\", "{", "(", "?!", "\\", "$", ")", ")", "+" ]
train
https://github.com/tk0miya/tk.phpautodoc/blob/cf789f64abaf76351485cee231a075227e665fb6/src/phply/phplex.py#L359-L363
tk0miya/tk.phpautodoc
src/phply/phplex.py
t_quotedvar_DOLLAR_OPEN_CURLY_BRACES
def t_quotedvar_DOLLAR_OPEN_CURLY_BRACES(t): r'\$\{' if re.match(r'[A-Za-z_]', peek(t.lexer)): t.lexer.begin('varname') else: t.lexer.begin('php') return t
python
def t_quotedvar_DOLLAR_OPEN_CURLY_BRACES(t): r'\$\{' if re.match(r'[A-Za-z_]', peek(t.lexer)): t.lexer.begin('varname') else: t.lexer.begin('php') return t
[ "def", "t_quotedvar_DOLLAR_OPEN_CURLY_BRACES", "(", "t", ")", ":", "if", "re", ".", "match", "(", "r'[A-Za-z_]'", ",", "peek", "(", "t", ".", "lexer", ")", ")", ":", "t", ".", "lexer", ".", "begin", "(", "'varname'", ")", "else", ":", "t", ".", "lexe...
r'\$\{
[ "r", "\\", "$", "\\", "{" ]
train
https://github.com/tk0miya/tk.phpautodoc/blob/cf789f64abaf76351485cee231a075227e665fb6/src/phply/phplex.py#L372-L378
tk0miya/tk.phpautodoc
src/phply/phplex.py
t_php_START_HEREDOC
def t_php_START_HEREDOC(t): r'<<<[ \t]*(?P<label>[A-Za-z_][\w_]*)\n' t.lexer.lineno += t.value.count("\n") t.lexer.push_state('heredoc') t.lexer.heredoc_label = t.lexer.lexmatch.group('label') return t
python
def t_php_START_HEREDOC(t): r'<<<[ \t]*(?P<label>[A-Za-z_][\w_]*)\n' t.lexer.lineno += t.value.count("\n") t.lexer.push_state('heredoc') t.lexer.heredoc_label = t.lexer.lexmatch.group('label') return t
[ "def", "t_php_START_HEREDOC", "(", "t", ")", ":", "t", ".", "lexer", ".", "lineno", "+=", "t", ".", "value", ".", "count", "(", "\"\\n\"", ")", "t", ".", "lexer", ".", "push_state", "(", "'heredoc'", ")", "t", ".", "lexer", ".", "heredoc_label", "=",...
r'<<<[ \t]*(?P<label>[A-Za-z_][\w_]*)\n
[ "r", "<<<", "[", "\\", "t", "]", "*", "(", "?P<label", ">", "[", "A", "-", "Za", "-", "z_", "]", "[", "\\", "w_", "]", "*", ")", "\\", "n" ]
train
https://github.com/tk0miya/tk.phpautodoc/blob/cf789f64abaf76351485cee231a075227e665fb6/src/phply/phplex.py#L405-L410
tk0miya/tk.phpautodoc
src/phply/phplex.py
t_heredoc_END_HEREDOC
def t_heredoc_END_HEREDOC(t): r'(?<=\n)[A-Za-z_][\w_]*' if t.value == t.lexer.heredoc_label: del t.lexer.heredoc_label t.lexer.pop_state() else: t.type = 'ENCAPSED_AND_WHITESPACE' return t
python
def t_heredoc_END_HEREDOC(t): r'(?<=\n)[A-Za-z_][\w_]*' if t.value == t.lexer.heredoc_label: del t.lexer.heredoc_label t.lexer.pop_state() else: t.type = 'ENCAPSED_AND_WHITESPACE' return t
[ "def", "t_heredoc_END_HEREDOC", "(", "t", ")", ":", "if", "t", ".", "value", "==", "t", ".", "lexer", ".", "heredoc_label", ":", "del", "t", ".", "lexer", ".", "heredoc_label", "t", ".", "lexer", ".", "pop_state", "(", ")", "else", ":", "t", ".", "...
r'(?<=\n)[A-Za-z_][\w_]*
[ "r", "(", "?<", "=", "\\", "n", ")", "[", "A", "-", "Za", "-", "z_", "]", "[", "\\", "w_", "]", "*" ]
train
https://github.com/tk0miya/tk.phpautodoc/blob/cf789f64abaf76351485cee231a075227e665fb6/src/phply/phplex.py#L412-L419
tk0miya/tk.phpautodoc
src/phply/phplex.py
t_heredocvar_ENCAPSED_AND_WHITESPACE
def t_heredocvar_ENCAPSED_AND_WHITESPACE(t): r'( [^\n\\${] | \\. | \$(?![A-Za-z_{]) | \{(?!\$) )+\n? | \\?\n' t.lexer.lineno += t.value.count("\n") t.lexer.pop_state() return t
python
def t_heredocvar_ENCAPSED_AND_WHITESPACE(t): r'( [^\n\\${] | \\. | \$(?![A-Za-z_{]) | \{(?!\$) )+\n? | \\?\n' t.lexer.lineno += t.value.count("\n") t.lexer.pop_state() return t
[ "def", "t_heredocvar_ENCAPSED_AND_WHITESPACE", "(", "t", ")", ":", "t", ".", "lexer", ".", "lineno", "+=", "t", ".", "value", ".", "count", "(", "\"\\n\"", ")", "t", ".", "lexer", ".", "pop_state", "(", ")", "return", "t" ]
r'( [^\n\\${] | \\. | \$(?![A-Za-z_{]) | \{(?!\$) )+\n? | \\?\n
[ "r", "(", "[", "^", "\\", "n", "\\\\", "$", "{", "]", "|", "\\\\", ".", "|", "\\", "$", "(", "?!", "[", "A", "-", "Za", "-", "z_", "{", "]", ")", "|", "\\", "{", "(", "?!", "\\", "$", ")", ")", "+", "\\", "n?", "|", "\\\\", "?", "\\...
train
https://github.com/tk0miya/tk.phpautodoc/blob/cf789f64abaf76351485cee231a075227e665fb6/src/phply/phplex.py#L434-L438
COLORFULBOARD/revision
revision/orchestrator.py
Orchestrator.use
def use(self, client_key): """ :param client_key: The client key. :type client_key: str :return: The Orchestrator instance (method chaining) :rtype: :class:`revision.orchestrator.Orchestrator` """ if not self.clients.has_client(client_key): raise ClientNotExist() self.current_client = self.clients.get_client(client_key) return self
python
def use(self, client_key): """ :param client_key: The client key. :type client_key: str :return: The Orchestrator instance (method chaining) :rtype: :class:`revision.orchestrator.Orchestrator` """ if not self.clients.has_client(client_key): raise ClientNotExist() self.current_client = self.clients.get_client(client_key) return self
[ "def", "use", "(", "self", ",", "client_key", ")", ":", "if", "not", "self", ".", "clients", ".", "has_client", "(", "client_key", ")", ":", "raise", "ClientNotExist", "(", ")", "self", ".", "current_client", "=", "self", ".", "clients", ".", "get_client...
:param client_key: The client key. :type client_key: str :return: The Orchestrator instance (method chaining) :rtype: :class:`revision.orchestrator.Orchestrator`
[ ":", "param", "client_key", ":", "The", "client", "key", ".", ":", "type", "client_key", ":", "str", ":", "return", ":", "The", "Orchestrator", "instance", "(", "method", "chaining", ")", ":", "rtype", ":", ":", "class", ":", "revision", ".", "orchestrat...
train
https://github.com/COLORFULBOARD/revision/blob/2f22e72cce5b60032a80c002ac45c2ecef0ed987/revision/orchestrator.py#L55-L67
COLORFULBOARD/revision
revision/orchestrator.py
Orchestrator.commit
def commit(self, revision, is_amend=False): """ :param revision: :type revision: :class:`revision.data.Revision` :param is_amend: :type is_amend: boolean :return: The Orchestrator instance (for method chaining) :rtype: :class:`revision.orchestrator.Orchestrator` """ if not isinstance(revision, Revision): raise InvalidArgType() if not self.current_client: raise ClientNotSpecified() if is_amend: self.current_client.save(revision) else: self.current_client.write() self.current_client.save(revision) return self
python
def commit(self, revision, is_amend=False): """ :param revision: :type revision: :class:`revision.data.Revision` :param is_amend: :type is_amend: boolean :return: The Orchestrator instance (for method chaining) :rtype: :class:`revision.orchestrator.Orchestrator` """ if not isinstance(revision, Revision): raise InvalidArgType() if not self.current_client: raise ClientNotSpecified() if is_amend: self.current_client.save(revision) else: self.current_client.write() self.current_client.save(revision) return self
[ "def", "commit", "(", "self", ",", "revision", ",", "is_amend", "=", "False", ")", ":", "if", "not", "isinstance", "(", "revision", ",", "Revision", ")", ":", "raise", "InvalidArgType", "(", ")", "if", "not", "self", ".", "current_client", ":", "raise", ...
:param revision: :type revision: :class:`revision.data.Revision` :param is_amend: :type is_amend: boolean :return: The Orchestrator instance (for method chaining) :rtype: :class:`revision.orchestrator.Orchestrator`
[ ":", "param", "revision", ":", ":", "type", "revision", ":", ":", "class", ":", "revision", ".", "data", ".", "Revision", ":", "param", "is_amend", ":", ":", "type", "is_amend", ":", "boolean", ":", "return", ":", "The", "Orchestrator", "instance", "(", ...
train
https://github.com/COLORFULBOARD/revision/blob/2f22e72cce5b60032a80c002ac45c2ecef0ed987/revision/orchestrator.py#L69-L90
COLORFULBOARD/revision
revision/orchestrator.py
Orchestrator.has_commit
def has_commit(self, client_key=None): """ Return True if client has new commit. :param client_key: The client key :type client_key: str :return: :rtype: boolean """ if client_key is None and self.current_client is None: raise ClientNotExist() if client_key: if not self.clients.has_client(client_key): raise ClientNotExist() client = self.clients.get_client(client_key) return client.has_commit() if self.current_client: client = self.current_client return client.has_commit() return False
python
def has_commit(self, client_key=None): """ Return True if client has new commit. :param client_key: The client key :type client_key: str :return: :rtype: boolean """ if client_key is None and self.current_client is None: raise ClientNotExist() if client_key: if not self.clients.has_client(client_key): raise ClientNotExist() client = self.clients.get_client(client_key) return client.has_commit() if self.current_client: client = self.current_client return client.has_commit() return False
[ "def", "has_commit", "(", "self", ",", "client_key", "=", "None", ")", ":", "if", "client_key", "is", "None", "and", "self", ".", "current_client", "is", "None", ":", "raise", "ClientNotExist", "(", ")", "if", "client_key", ":", "if", "not", "self", ".",...
Return True if client has new commit. :param client_key: The client key :type client_key: str :return: :rtype: boolean
[ "Return", "True", "if", "client", "has", "new", "commit", "." ]
train
https://github.com/COLORFULBOARD/revision/blob/2f22e72cce5b60032a80c002ac45c2ecef0ed987/revision/orchestrator.py#L111-L136
six8/corona-cipr
src/cipr/commands/core.py
init
def init(ciprcfg, env, console): """ Initialize a Corona project directory. """ ciprcfg.create() templ_dir = path.join(env.skel_dir, 'default') console.quiet('Copying files from %s' % templ_dir) for src, dst in util.sync_dir_to(templ_dir, env.project_directory, ignore_existing=True): console.quiet(' %s -> %s' % (src, dst)) src = path.join(env.code_dir, 'cipr.dev.lua') dst = path.join(env.project_directory, 'cipr.lua') console.quiet(' %s -> %s' % (src, dst)) shutil.copy(src, dst)
python
def init(ciprcfg, env, console): """ Initialize a Corona project directory. """ ciprcfg.create() templ_dir = path.join(env.skel_dir, 'default') console.quiet('Copying files from %s' % templ_dir) for src, dst in util.sync_dir_to(templ_dir, env.project_directory, ignore_existing=True): console.quiet(' %s -> %s' % (src, dst)) src = path.join(env.code_dir, 'cipr.dev.lua') dst = path.join(env.project_directory, 'cipr.lua') console.quiet(' %s -> %s' % (src, dst)) shutil.copy(src, dst)
[ "def", "init", "(", "ciprcfg", ",", "env", ",", "console", ")", ":", "ciprcfg", ".", "create", "(", ")", "templ_dir", "=", "path", ".", "join", "(", "env", ".", "skel_dir", ",", "'default'", ")", "console", ".", "quiet", "(", "'Copying files from %s'", ...
Initialize a Corona project directory.
[ "Initialize", "a", "Corona", "project", "directory", "." ]
train
https://github.com/six8/corona-cipr/blob/a2f45761080c874afa39bf95fd5c4467c8eae272/src/cipr/commands/core.py#L20-L36
six8/corona-cipr
src/cipr/commands/core.py
update
def update(env): """ Update an existing cipr project to the latest intalled version. """ files = [path.join(env.project_directory, 'cipr.lua')] for filename in files: if path.exists(filename): os.remove(filename) app.command.run(['init', env.project_directory])
python
def update(env): """ Update an existing cipr project to the latest intalled version. """ files = [path.join(env.project_directory, 'cipr.lua')] for filename in files: if path.exists(filename): os.remove(filename) app.command.run(['init', env.project_directory])
[ "def", "update", "(", "env", ")", ":", "files", "=", "[", "path", ".", "join", "(", "env", ".", "project_directory", ",", "'cipr.lua'", ")", "]", "for", "filename", "in", "files", ":", "if", "path", ".", "exists", "(", "filename", ")", ":", "os", "...
Update an existing cipr project to the latest intalled version.
[ "Update", "an", "existing", "cipr", "project", "to", "the", "latest", "intalled", "version", "." ]
train
https://github.com/six8/corona-cipr/blob/a2f45761080c874afa39bf95fd5c4467c8eae272/src/cipr/commands/core.py#L39-L47
six8/corona-cipr
src/cipr/commands/core.py
uninstall
def uninstall(args, env, console, ciprcfg): """ Remove a package """ for name in args: package_dir = path.join(env.package_dir, name) if path.exists(package_dir): console.quiet('Removing %s...' % name) if path.islink(package_dir): os.remove(package_dir) else: shutil.rmtree(package_dir) ciprcfg.remove_package(name)
python
def uninstall(args, env, console, ciprcfg): """ Remove a package """ for name in args: package_dir = path.join(env.package_dir, name) if path.exists(package_dir): console.quiet('Removing %s...' % name) if path.islink(package_dir): os.remove(package_dir) else: shutil.rmtree(package_dir) ciprcfg.remove_package(name)
[ "def", "uninstall", "(", "args", ",", "env", ",", "console", ",", "ciprcfg", ")", ":", "for", "name", "in", "args", ":", "package_dir", "=", "path", ".", "join", "(", "env", ".", "package_dir", ",", "name", ")", "if", "path", ".", "exists", "(", "p...
Remove a package
[ "Remove", "a", "package" ]
train
https://github.com/six8/corona-cipr/blob/a2f45761080c874afa39bf95fd5c4467c8eae272/src/cipr/commands/core.py#L50-L63
six8/corona-cipr
src/cipr/commands/core.py
install
def install(args, console, env, ciprcfg, opts): """ Install a package from github and make it available for use. """ if len(args) == 0: # Is this a cipr project? if ciprcfg.exists: # Install all the packages for this project console.quiet('Installing current project packages...') for name, source in ciprcfg.packages.items(): if opts.upgrade: app.command.run(['install', '--upgrade', source]) else: app.command.run(['install', source]) else: console.error('No cipr project or package found.') return else: for source in args: package, name, version, type = _package_info(source) if not path.exists(env.package_dir): os.makedirs(env.package_dir) package_dir = path.join(env.package_dir, name) if path.exists(package_dir): if opts.upgrade: app.command.run(['uninstall', name]) else: console.quiet('Package %s already exists. Use --upgrade to force a re-install.' % name) return console.quiet('Installing %s...' % name) if type == 'git': tmpdir = tempfile.mkdtemp(prefix='cipr') clom.git.clone(package, tmpdir).shell.execute() if version: cmd = AND(clom.cd(tmpdir), clom.git.checkout(version)) cmd.shell.execute() package_json = path.join(tmpdir, 'package.json') if path.exists(package_json): # Looks like a cipr package, copy directly shutil.move(tmpdir, package_dir) else: # Not a cipr package, sandbox in sub-directory shutil.move(tmpdir, path.join(package_dir, name)) console.quiet('`%s` installed from git repo to `%s`' % (name, package_dir)) elif path.exists(package): # Local os.symlink(package, package_dir) else: console.error('Package `%s` type not recognized' % package) return pkg = Package(package_dir, source) ciprcfg.add_package(pkg) if pkg.dependencies: console.quiet('Installing dependancies...') for name, require in pkg.dependencies.items(): if opts.upgrade: app.command.run(['install', '--upgrade', require]) else: app.command.run(['install', require])
python
def install(args, console, env, ciprcfg, opts): """ Install a package from github and make it available for use. """ if len(args) == 0: # Is this a cipr project? if ciprcfg.exists: # Install all the packages for this project console.quiet('Installing current project packages...') for name, source in ciprcfg.packages.items(): if opts.upgrade: app.command.run(['install', '--upgrade', source]) else: app.command.run(['install', source]) else: console.error('No cipr project or package found.') return else: for source in args: package, name, version, type = _package_info(source) if not path.exists(env.package_dir): os.makedirs(env.package_dir) package_dir = path.join(env.package_dir, name) if path.exists(package_dir): if opts.upgrade: app.command.run(['uninstall', name]) else: console.quiet('Package %s already exists. Use --upgrade to force a re-install.' % name) return console.quiet('Installing %s...' % name) if type == 'git': tmpdir = tempfile.mkdtemp(prefix='cipr') clom.git.clone(package, tmpdir).shell.execute() if version: cmd = AND(clom.cd(tmpdir), clom.git.checkout(version)) cmd.shell.execute() package_json = path.join(tmpdir, 'package.json') if path.exists(package_json): # Looks like a cipr package, copy directly shutil.move(tmpdir, package_dir) else: # Not a cipr package, sandbox in sub-directory shutil.move(tmpdir, path.join(package_dir, name)) console.quiet('`%s` installed from git repo to `%s`' % (name, package_dir)) elif path.exists(package): # Local os.symlink(package, package_dir) else: console.error('Package `%s` type not recognized' % package) return pkg = Package(package_dir, source) ciprcfg.add_package(pkg) if pkg.dependencies: console.quiet('Installing dependancies...') for name, require in pkg.dependencies.items(): if opts.upgrade: app.command.run(['install', '--upgrade', require]) else: app.command.run(['install', require])
[ "def", "install", "(", "args", ",", "console", ",", "env", ",", "ciprcfg", ",", "opts", ")", ":", "if", "len", "(", "args", ")", "==", "0", ":", "# Is this a cipr project?", "if", "ciprcfg", ".", "exists", ":", "# Install all the packages for this project", ...
Install a package from github and make it available for use.
[ "Install", "a", "package", "from", "github", "and", "make", "it", "available", "for", "use", "." ]
train
https://github.com/six8/corona-cipr/blob/a2f45761080c874afa39bf95fd5c4467c8eae272/src/cipr/commands/core.py#L88-L158
six8/corona-cipr
src/cipr/commands/core.py
packages
def packages(ciprcfg, env, opts, console): """ List installed packages for this project """ for name, source in ciprcfg.packages.items(): console.normal('- %s' % name) if opts.long_details: console.normal(' - directory: %s' % path.join(env.package_dir, name)) console.normal(' - source: %s' % source)
python
def packages(ciprcfg, env, opts, console): """ List installed packages for this project """ for name, source in ciprcfg.packages.items(): console.normal('- %s' % name) if opts.long_details: console.normal(' - directory: %s' % path.join(env.package_dir, name)) console.normal(' - source: %s' % source)
[ "def", "packages", "(", "ciprcfg", ",", "env", ",", "opts", ",", "console", ")", ":", "for", "name", ",", "source", "in", "ciprcfg", ".", "packages", ".", "items", "(", ")", ":", "console", ".", "normal", "(", "'- %s'", "%", "name", ")", "if", "opt...
List installed packages for this project
[ "List", "installed", "packages", "for", "this", "project" ]
train
https://github.com/six8/corona-cipr/blob/a2f45761080c874afa39bf95fd5c4467c8eae272/src/cipr/commands/core.py#L161-L170
six8/corona-cipr
src/cipr/commands/core.py
run
def run(env): """ Run current project in the Corona Simulator """ os.putenv('CIPR_PACKAGES', env.package_dir) os.putenv('CIPR_PROJECT', env.project_directory) # `Corona Terminal` doesn't support spaces in filenames so we cd in and use '.'. cmd = AND( clom.cd(path.dirname(env.project_directory)), clom[CORONA_SIMULATOR_PATH](path.basename(env.project_directory)) ) try: cmd.shell.execute() except KeyboardInterrupt: pass
python
def run(env): """ Run current project in the Corona Simulator """ os.putenv('CIPR_PACKAGES', env.package_dir) os.putenv('CIPR_PROJECT', env.project_directory) # `Corona Terminal` doesn't support spaces in filenames so we cd in and use '.'. cmd = AND( clom.cd(path.dirname(env.project_directory)), clom[CORONA_SIMULATOR_PATH](path.basename(env.project_directory)) ) try: cmd.shell.execute() except KeyboardInterrupt: pass
[ "def", "run", "(", "env", ")", ":", "os", ".", "putenv", "(", "'CIPR_PACKAGES'", ",", "env", ".", "package_dir", ")", "os", ".", "putenv", "(", "'CIPR_PROJECT'", ",", "env", ".", "project_directory", ")", "# `Corona Terminal` doesn't support spaces in filenames so...
Run current project in the Corona Simulator
[ "Run", "current", "project", "in", "the", "Corona", "Simulator" ]
train
https://github.com/six8/corona-cipr/blob/a2f45761080c874afa39bf95fd5c4467c8eae272/src/cipr/commands/core.py#L174-L191
six8/corona-cipr
src/cipr/commands/core.py
build
def build(env, ciprcfg, console): """ Build the current project for distribution """ os.putenv('CIPR_PACKAGES', env.package_dir) os.putenv('CIPR_PROJECT', env.project_directory) build_settings = path.join(env.project_directory, 'build.settings') with open(build_settings, 'r') as f: data = f.read() m = _build_re.search(data) if m: ver = int(m.group(2)) data = data.replace(m.group(0), 'CFBundleVersion = "%d"' % (ver + 1)) with open(build_settings, 'w') as f: f.write(data) if path.exists(env.build_dir): shutil.rmtree(env.build_dir) os.makedirs(env.build_dir) if path.exists(env.dist_dir): shutil.rmtree(env.dist_dir) os.makedirs(env.dist_dir) console.normal('Building in %s' % env.build_dir) console.normal('Copy project files...') for src, dst in util.sync_dir_to(env.project_directory, env.build_dir, exclude=['.cipr', '.git', 'build', 'dist', '.*']): console.quiet(' %s -> %s' % (src, dst)) if src.endswith('.lua'): _fix_lua_module_name(src, dst) console.normal('Copy cipr packages...') for package in ciprcfg.packages.keys(): for src, dst in util.sync_lua_dir_to(path.join(env.package_dir, package), env.build_dir, exclude=['.git'], include=['*.lua']): console.quiet(' %s -> %s' % (src, dst)) if src.endswith('.lua'): _fix_lua_module_name(src, dst) src = path.join(env.code_dir, 'cipr.lua') dst = path.join(env.build_dir, 'cipr.lua') shutil.copy(src, dst) cmd = AND(clom.cd(env.build_dir), clom[CORONA_SIMULATOR_PATH](env.build_dir)) console.normal('Be sure to output your app to %s' % env.dist_dir) try: cmd.shell.execute() except KeyboardInterrupt: pass
python
def build(env, ciprcfg, console): """ Build the current project for distribution """ os.putenv('CIPR_PACKAGES', env.package_dir) os.putenv('CIPR_PROJECT', env.project_directory) build_settings = path.join(env.project_directory, 'build.settings') with open(build_settings, 'r') as f: data = f.read() m = _build_re.search(data) if m: ver = int(m.group(2)) data = data.replace(m.group(0), 'CFBundleVersion = "%d"' % (ver + 1)) with open(build_settings, 'w') as f: f.write(data) if path.exists(env.build_dir): shutil.rmtree(env.build_dir) os.makedirs(env.build_dir) if path.exists(env.dist_dir): shutil.rmtree(env.dist_dir) os.makedirs(env.dist_dir) console.normal('Building in %s' % env.build_dir) console.normal('Copy project files...') for src, dst in util.sync_dir_to(env.project_directory, env.build_dir, exclude=['.cipr', '.git', 'build', 'dist', '.*']): console.quiet(' %s -> %s' % (src, dst)) if src.endswith('.lua'): _fix_lua_module_name(src, dst) console.normal('Copy cipr packages...') for package in ciprcfg.packages.keys(): for src, dst in util.sync_lua_dir_to(path.join(env.package_dir, package), env.build_dir, exclude=['.git'], include=['*.lua']): console.quiet(' %s -> %s' % (src, dst)) if src.endswith('.lua'): _fix_lua_module_name(src, dst) src = path.join(env.code_dir, 'cipr.lua') dst = path.join(env.build_dir, 'cipr.lua') shutil.copy(src, dst) cmd = AND(clom.cd(env.build_dir), clom[CORONA_SIMULATOR_PATH](env.build_dir)) console.normal('Be sure to output your app to %s' % env.dist_dir) try: cmd.shell.execute() except KeyboardInterrupt: pass
[ "def", "build", "(", "env", ",", "ciprcfg", ",", "console", ")", ":", "os", ".", "putenv", "(", "'CIPR_PACKAGES'", ",", "env", ".", "package_dir", ")", "os", ".", "putenv", "(", "'CIPR_PROJECT'", ",", "env", ".", "project_directory", ")", "build_settings",...
Build the current project for distribution
[ "Build", "the", "current", "project", "for", "distribution" ]
train
https://github.com/six8/corona-cipr/blob/a2f45761080c874afa39bf95fd5c4467c8eae272/src/cipr/commands/core.py#L206-L264
six8/corona-cipr
src/cipr/commands/core.py
packageipa
def packageipa(env, console): """ Package the built app as an ipa for distribution in iOS App Store """ ipa_path, app_path = _get_ipa(env) output_dir = path.dirname(ipa_path) if path.exists(ipa_path): console.quiet('Removing %s' % ipa_path) os.remove(ipa_path) zf = zipfile.ZipFile(ipa_path, mode='w') payload_dir = 'Payload' for (dirpath, dirnames, filenames) in os.walk(app_path): for filename in filenames: filepath = path.join(dirpath, filename) prefix = path.commonprefix([filepath, path.dirname(app_path)]) write_path = path.join(payload_dir, filepath[len(prefix) + 1:]) console.quiet('Write %s' % write_path) zf.write(filepath, write_path) zf.close() console.quiet('Packaged %s' % ipa_path)
python
def packageipa(env, console): """ Package the built app as an ipa for distribution in iOS App Store """ ipa_path, app_path = _get_ipa(env) output_dir = path.dirname(ipa_path) if path.exists(ipa_path): console.quiet('Removing %s' % ipa_path) os.remove(ipa_path) zf = zipfile.ZipFile(ipa_path, mode='w') payload_dir = 'Payload' for (dirpath, dirnames, filenames) in os.walk(app_path): for filename in filenames: filepath = path.join(dirpath, filename) prefix = path.commonprefix([filepath, path.dirname(app_path)]) write_path = path.join(payload_dir, filepath[len(prefix) + 1:]) console.quiet('Write %s' % write_path) zf.write(filepath, write_path) zf.close() console.quiet('Packaged %s' % ipa_path)
[ "def", "packageipa", "(", "env", ",", "console", ")", ":", "ipa_path", ",", "app_path", "=", "_get_ipa", "(", "env", ")", "output_dir", "=", "path", ".", "dirname", "(", "ipa_path", ")", "if", "path", ".", "exists", "(", "ipa_path", ")", ":", "console"...
Package the built app as an ipa for distribution in iOS App Store
[ "Package", "the", "built", "app", "as", "an", "ipa", "for", "distribution", "in", "iOS", "App", "Store" ]
train
https://github.com/six8/corona-cipr/blob/a2f45761080c874afa39bf95fd5c4467c8eae272/src/cipr/commands/core.py#L275-L301
six8/corona-cipr
src/cipr/commands/core.py
expanddotpaths
def expanddotpaths(env, console): """ Move files with dots in them to sub-directories """ for filepath in os.listdir(path.join(env.dir)): filename, ext = path.splitext(filepath) if ext == '.lua' and '.' in filename: paths, newfilename = filename.rsplit('.', 1) newpath = paths.replace('.', '/') newfilename = path.join(newpath, newfilename) + ext console.quiet('Move %s to %s' % (filepath, newfilename)) fullpath = path.join(env.project_directory, newpath) if not path.exists(fullpath): os.makedirs(fullpath) clom.git.mv(filepath, newfilename).shell.execute()
python
def expanddotpaths(env, console): """ Move files with dots in them to sub-directories """ for filepath in os.listdir(path.join(env.dir)): filename, ext = path.splitext(filepath) if ext == '.lua' and '.' in filename: paths, newfilename = filename.rsplit('.', 1) newpath = paths.replace('.', '/') newfilename = path.join(newpath, newfilename) + ext console.quiet('Move %s to %s' % (filepath, newfilename)) fullpath = path.join(env.project_directory, newpath) if not path.exists(fullpath): os.makedirs(fullpath) clom.git.mv(filepath, newfilename).shell.execute()
[ "def", "expanddotpaths", "(", "env", ",", "console", ")", ":", "for", "filepath", "in", "os", ".", "listdir", "(", "path", ".", "join", "(", "env", ".", "dir", ")", ")", ":", "filename", ",", "ext", "=", "path", ".", "splitext", "(", "filepath", ")...
Move files with dots in them to sub-directories
[ "Move", "files", "with", "dots", "in", "them", "to", "sub", "-", "directories" ]
train
https://github.com/six8/corona-cipr/blob/a2f45761080c874afa39bf95fd5c4467c8eae272/src/cipr/commands/core.py#L304-L321
thombashi/thutils
thutils/gfile.py
check_file_existence
def check_file_existence(path): """ :return: FileType :rtype: int :raises InvalidFilePathError: :raises FileNotFoundError: :raises RuntimeError: """ pathvalidate.validate_file_path(path) if not os.path.lexists(path): raise FileNotFoundError(path) if os.path.isfile(path): logger.debug("file found: " + path) return FileType.FILE if os.path.isdir(path): logger.debug("directory found: " + path) return FileType.DIRECTORY if os.path.islink(path): logger.debug("link found: " + path) return FileType.LINK raise RuntimeError()
python
def check_file_existence(path): """ :return: FileType :rtype: int :raises InvalidFilePathError: :raises FileNotFoundError: :raises RuntimeError: """ pathvalidate.validate_file_path(path) if not os.path.lexists(path): raise FileNotFoundError(path) if os.path.isfile(path): logger.debug("file found: " + path) return FileType.FILE if os.path.isdir(path): logger.debug("directory found: " + path) return FileType.DIRECTORY if os.path.islink(path): logger.debug("link found: " + path) return FileType.LINK raise RuntimeError()
[ "def", "check_file_existence", "(", "path", ")", ":", "pathvalidate", ".", "validate_file_path", "(", "path", ")", "if", "not", "os", ".", "path", ".", "lexists", "(", "path", ")", ":", "raise", "FileNotFoundError", "(", "path", ")", "if", "os", ".", "pa...
:return: FileType :rtype: int :raises InvalidFilePathError: :raises FileNotFoundError: :raises RuntimeError:
[ ":", "return", ":", "FileType", ":", "rtype", ":", "int", ":", "raises", "InvalidFilePathError", ":", ":", "raises", "FileNotFoundError", ":", ":", "raises", "RuntimeError", ":" ]
train
https://github.com/thombashi/thutils/blob/9eba767cfc26b38cd66b83b99aee0c31b8b90dec/thutils/gfile.py#L315-L341
thombashi/thutils
thutils/gfile.py
parsePermission3Char
def parsePermission3Char(permission): """ 'rwx' 形式のアクセス権限文字列 permission を8進数形式に変換する :return: :rtype: int """ if len(permission) != 3: raise ValueError(permission) permission_int = 0 if permission[0] == "r": permission_int += 4 if permission[1] == "w": permission_int += 2 if permission[2] == "x": permission_int += 1 return permission_int
python
def parsePermission3Char(permission): """ 'rwx' 形式のアクセス権限文字列 permission を8進数形式に変換する :return: :rtype: int """ if len(permission) != 3: raise ValueError(permission) permission_int = 0 if permission[0] == "r": permission_int += 4 if permission[1] == "w": permission_int += 2 if permission[2] == "x": permission_int += 1 return permission_int
[ "def", "parsePermission3Char", "(", "permission", ")", ":", "if", "len", "(", "permission", ")", "!=", "3", ":", "raise", "ValueError", "(", "permission", ")", "permission_int", "=", "0", "if", "permission", "[", "0", "]", "==", "\"r\"", ":", "permission_i...
'rwx' 形式のアクセス権限文字列 permission を8進数形式に変換する :return: :rtype: int
[ "rwx", "形式のアクセス権限文字列", "permission", "を8進数形式に変換する" ]
train
https://github.com/thombashi/thutils/blob/9eba767cfc26b38cd66b83b99aee0c31b8b90dec/thutils/gfile.py#L390-L409
thombashi/thutils
thutils/gfile.py
parseLsPermissionText
def parseLsPermissionText(permission_text): """ parse "ls -l" style permission text: e.g. -rw-r--r-- """ from six.moves import range match = re.search("[-drwx]+", permission_text) if match is None: raise ValueError( "invalid permission character: " + permission_text) if len(permission_text) != 10: raise ValueError( "invalid permission text length: " + permission_text) permission_text = permission_text[1:] return int( "0" + "".join([ str(parsePermission3Char(permission_text[i:i + 3])) for i in range(0, 9, 3) ]), base=8)
python
def parseLsPermissionText(permission_text): """ parse "ls -l" style permission text: e.g. -rw-r--r-- """ from six.moves import range match = re.search("[-drwx]+", permission_text) if match is None: raise ValueError( "invalid permission character: " + permission_text) if len(permission_text) != 10: raise ValueError( "invalid permission text length: " + permission_text) permission_text = permission_text[1:] return int( "0" + "".join([ str(parsePermission3Char(permission_text[i:i + 3])) for i in range(0, 9, 3) ]), base=8)
[ "def", "parseLsPermissionText", "(", "permission_text", ")", ":", "from", "six", ".", "moves", "import", "range", "match", "=", "re", ".", "search", "(", "\"[-drwx]+\"", ",", "permission_text", ")", "if", "match", "is", "None", ":", "raise", "ValueError", "(...
parse "ls -l" style permission text: e.g. -rw-r--r--
[ "parse", "ls", "-", "l", "style", "permission", "text", ":", "e", ".", "g", ".", "-", "rw", "-", "r", "--", "r", "--" ]
train
https://github.com/thombashi/thutils/blob/9eba767cfc26b38cd66b83b99aee0c31b8b90dec/thutils/gfile.py#L412-L435
thombashi/thutils
thutils/gfile.py
FileManager.chmod
def chmod(cls, path, permission_text): """ :param str permission_text: "ls -l" style permission string. e.g. -rw-r--r-- """ try: check_file_existence(path) except FileNotFoundError: _, e, _ = sys.exc_info() # for python 2.5 compatibility logger.debug(e) return False logger.debug("chmod %s %s" % (path, permission_text)) os.chmod(path, parseLsPermissionText(permission_text))
python
def chmod(cls, path, permission_text): """ :param str permission_text: "ls -l" style permission string. e.g. -rw-r--r-- """ try: check_file_existence(path) except FileNotFoundError: _, e, _ = sys.exc_info() # for python 2.5 compatibility logger.debug(e) return False logger.debug("chmod %s %s" % (path, permission_text)) os.chmod(path, parseLsPermissionText(permission_text))
[ "def", "chmod", "(", "cls", ",", "path", ",", "permission_text", ")", ":", "try", ":", "check_file_existence", "(", "path", ")", "except", "FileNotFoundError", ":", "_", ",", "e", ",", "_", "=", "sys", ".", "exc_info", "(", ")", "# for python 2.5 compatibi...
:param str permission_text: "ls -l" style permission string. e.g. -rw-r--r--
[ ":", "param", "str", "permission_text", ":", "ls", "-", "l", "style", "permission", "string", ".", "e", ".", "g", ".", "-", "rw", "-", "r", "--", "r", "--" ]
train
https://github.com/thombashi/thutils/blob/9eba767cfc26b38cd66b83b99aee0c31b8b90dec/thutils/gfile.py#L149-L163
thespacedoctor/rockfinder
rockfinder/jpl_horizons_ephemeris.py
jpl_horizons_ephemeris
def jpl_horizons_ephemeris( log, objectId, mjd, obscode=500, verbose=False): """Given a known solar-system object ID (human-readable name, MPC number or MPC packed format) and one or more specific epochs, return the calculated ephemerides **Key Arguments:** - ``log`` -- logger - ``objectId`` -- human-readable name, MPC number or MPC packed format id of the solar-system object or list of names - ``mjd`` -- a single MJD, or a list of up to 10,000 MJDs to generate an ephemeris for - ``obscode`` -- the observatory code for the ephemeris generation. Default **500** (geocentric) - ``verbose`` -- return extra information with each ephemeris **Return:** - ``resultList`` -- a list of ordered dictionaries containing the returned ephemerides **Usage:** To generate a an ephemeris for a single epoch run, using ATLAS Haleakala as your observatory: .. code-block:: python from rockfinder import jpl_horizons_ephemeris eph = jpl_horizons_ephemeris( log=log, objectId=1, mjd=57916., obscode='T05' ) or to generate an ephemeris for multiple epochs: .. code-block:: python from rockfinder import jpl_horizons_ephemeris eph = jpl_horizons_ephemeris( log=log, objectId="ceres", mjd=[57916.1,57917.234,57956.34523] verbose=True ) Note by passing `verbose=True` the essential ephemeris data is supplimented with some extra data It's also possible to pass in an array of object IDs: .. code-block:: python from rockfinder import jpl_horizons_ephemeris eph = jpl_horizons_ephemeris( log=log, objectId=[1,5,03547,"Shikoku","K10B11A"], mjd=[57916.1,57917.234,57956.34523] ) """ log.debug('starting the ``jpl_horizons_ephemeris`` function') # MAKE SURE MJDs ARE IN A LIST if not isinstance(mjd, list): mjd = [str(mjd)] mjd = (" ").join(map(str, mjd)) if not isinstance(objectId, list): objectList = [objectId] else: objectList = objectId keys = ["jd", "solar_presence", "lunar_presence", "ra_deg", "dec_deg", "ra_arcsec_per_hour", "dec_arcsec_per_hour", "apparent_mag", "surface_brightness", "heliocentric_distance", "heliocentric_motion", "observer_distance", "observer_motion", "sun_obs_target_angle", "apparent_motion_relative_to_sun", "sun_target_obs_angle", "ra_3sig_error", "dec_3sig_error", "true_anomaly_angle", "phase_angle", "phase_angle_bisector_long", "phase_angle_bisector_lat"] if verbose == True: order = ["requestId", "objectId", "mjd", "ra_deg", "dec_deg", "ra_3sig_error", "dec_3sig_error", "ra_arcsec_per_hour", "dec_arcsec_per_hour", "apparent_mag", "heliocentric_distance", "heliocentric_motion", "observer_distance", "observer_motion", "phase_angle", "true_anomaly_angle", "surface_brightness", "sun_obs_target_angle", "sun_target_obs_angle", "apparent_motion_relative_to_sun", "phase_angle_bisector_long", "phase_angle_bisector_lat"] else: order = ["requestId", "objectId", "mjd", "ra_deg", "dec_deg", "ra_3sig_error", "dec_3sig_error", "ra_arcsec_per_hour", "dec_arcsec_per_hour", "apparent_mag", "heliocentric_distance", "observer_distance", "phase_angle"] params = { "COMMAND": "", "OBJ_DATA": "'NO'", "MAKE_EPHEM": "'YES'", "TABLE_TYPE": "'OBS'", "CENTER": "'%(obscode)s'" % locals(), "TLIST": mjd, "QUANTITIES": "'1,3,9,19,20,23,24,36,41,43'", "REF_SYSTEM": "'J2000'", "CAL_FORMAT": "'JD'", "ANG_FORMAT": "'DEG'", "APPARENT": "'REFRACTED'", "TIME_DIGITS": "'FRACSEC'", "TIME_ZONE": "'+00:00'", "RANGE_UNITS": "'AU'", "SUPPRESS_RANGE_RATE": "'NO'", "SKIP_DAYLT": "'YES'", "EXTRA_PREC": "'YES'", "CSV_FORMAT": "'YES'", "batch": "1", } resultList = [] paramList = [] for objectId in objectList: requestId = objectId # FIX THE COMMAND FOR NUMBERED OBJECTS try: thisId = int(objectId) objectId = "%(thisId)s" % locals() except Exception as e: pass theseparams = copy.deepcopy(params) theseparams["COMMAND"] = '"' + objectId + '"' paramList.append(theseparams) # TEST THE URL # try: # import requests # response = requests.get( # url="https://ssd.jpl.nasa.gov/horizons_batch.cgi", # params=theseparams, # ) # content = response.content # status_code = response.status_code # print response.url # except requests.exceptions.RequestException: # print('HTTP Request failed') # sys.exit(0) rs = [grequests.get("https://ssd.jpl.nasa.gov/horizons_batch.cgi", params=p) for p in paramList] def exception_handler(request, exception): print "Request failed" print exception returns = grequests.map(rs, size=1, exception_handler=exception_handler) for result, requestId in zip(returns, objectList): r = result.content match = re.search( r'Target body name:\s(.*?)\{', r, flags=re.S # re.S ) if not match: log.warning( "Horizons could not find a match for `%(requestId)s`" % locals()) try: import requests response = requests.get( url="https://ssd.jpl.nasa.gov/horizons_batch.cgi", params=theseparams, ) content = response.content status_code = response.status_code print response.url except requests.exceptions.RequestException: print('HTTP Request failed') sys.exit(0) objectDict = {} for k in keys: v = None objectDict[k] = v objectDict["objectId"] = requestId + " - NOT FOUND" objectDict["requestId"] = requestId objectDict["mjd"] = None orderDict = collections.OrderedDict({}) for i in order: orderDict[i] = objectDict[i] resultList.append(orderDict) continue horizonsId = match.group(1).replace("(", "").replace(")", "").strip() match = re.search( r'\$\$SOE\n(.*?)\n\$\$EOE', r, flags=re.S # re.S ) keys2 = copy.deepcopy(keys) order2 = copy.deepcopy(order) if "S-brt," not in r: keys2.remove("surface_brightness") try: order2.remove("surface_brightness") except: pass lines = match.group(1).split("\n") for line in lines: vals = line.split(",") objectDict = {} for k, v in zip(keys2, vals): v = v.strip().replace("/", "") try: v = float(v) except: pass objectDict[k] = v objectDict["mjd"] = objectDict["jd"] - 2400000.5 objectDict["objectId"] = horizonsId objectDict["requestId"] = requestId orderDict = collections.OrderedDict({}) for i in order2: orderDict[i] = objectDict[i] resultList.append(orderDict) log.debug('completed the ``jpl_horizons_ephemeris`` function') return resultList
python
def jpl_horizons_ephemeris( log, objectId, mjd, obscode=500, verbose=False): """Given a known solar-system object ID (human-readable name, MPC number or MPC packed format) and one or more specific epochs, return the calculated ephemerides **Key Arguments:** - ``log`` -- logger - ``objectId`` -- human-readable name, MPC number or MPC packed format id of the solar-system object or list of names - ``mjd`` -- a single MJD, or a list of up to 10,000 MJDs to generate an ephemeris for - ``obscode`` -- the observatory code for the ephemeris generation. Default **500** (geocentric) - ``verbose`` -- return extra information with each ephemeris **Return:** - ``resultList`` -- a list of ordered dictionaries containing the returned ephemerides **Usage:** To generate a an ephemeris for a single epoch run, using ATLAS Haleakala as your observatory: .. code-block:: python from rockfinder import jpl_horizons_ephemeris eph = jpl_horizons_ephemeris( log=log, objectId=1, mjd=57916., obscode='T05' ) or to generate an ephemeris for multiple epochs: .. code-block:: python from rockfinder import jpl_horizons_ephemeris eph = jpl_horizons_ephemeris( log=log, objectId="ceres", mjd=[57916.1,57917.234,57956.34523] verbose=True ) Note by passing `verbose=True` the essential ephemeris data is supplimented with some extra data It's also possible to pass in an array of object IDs: .. code-block:: python from rockfinder import jpl_horizons_ephemeris eph = jpl_horizons_ephemeris( log=log, objectId=[1,5,03547,"Shikoku","K10B11A"], mjd=[57916.1,57917.234,57956.34523] ) """ log.debug('starting the ``jpl_horizons_ephemeris`` function') # MAKE SURE MJDs ARE IN A LIST if not isinstance(mjd, list): mjd = [str(mjd)] mjd = (" ").join(map(str, mjd)) if not isinstance(objectId, list): objectList = [objectId] else: objectList = objectId keys = ["jd", "solar_presence", "lunar_presence", "ra_deg", "dec_deg", "ra_arcsec_per_hour", "dec_arcsec_per_hour", "apparent_mag", "surface_brightness", "heliocentric_distance", "heliocentric_motion", "observer_distance", "observer_motion", "sun_obs_target_angle", "apparent_motion_relative_to_sun", "sun_target_obs_angle", "ra_3sig_error", "dec_3sig_error", "true_anomaly_angle", "phase_angle", "phase_angle_bisector_long", "phase_angle_bisector_lat"] if verbose == True: order = ["requestId", "objectId", "mjd", "ra_deg", "dec_deg", "ra_3sig_error", "dec_3sig_error", "ra_arcsec_per_hour", "dec_arcsec_per_hour", "apparent_mag", "heliocentric_distance", "heliocentric_motion", "observer_distance", "observer_motion", "phase_angle", "true_anomaly_angle", "surface_brightness", "sun_obs_target_angle", "sun_target_obs_angle", "apparent_motion_relative_to_sun", "phase_angle_bisector_long", "phase_angle_bisector_lat"] else: order = ["requestId", "objectId", "mjd", "ra_deg", "dec_deg", "ra_3sig_error", "dec_3sig_error", "ra_arcsec_per_hour", "dec_arcsec_per_hour", "apparent_mag", "heliocentric_distance", "observer_distance", "phase_angle"] params = { "COMMAND": "", "OBJ_DATA": "'NO'", "MAKE_EPHEM": "'YES'", "TABLE_TYPE": "'OBS'", "CENTER": "'%(obscode)s'" % locals(), "TLIST": mjd, "QUANTITIES": "'1,3,9,19,20,23,24,36,41,43'", "REF_SYSTEM": "'J2000'", "CAL_FORMAT": "'JD'", "ANG_FORMAT": "'DEG'", "APPARENT": "'REFRACTED'", "TIME_DIGITS": "'FRACSEC'", "TIME_ZONE": "'+00:00'", "RANGE_UNITS": "'AU'", "SUPPRESS_RANGE_RATE": "'NO'", "SKIP_DAYLT": "'YES'", "EXTRA_PREC": "'YES'", "CSV_FORMAT": "'YES'", "batch": "1", } resultList = [] paramList = [] for objectId in objectList: requestId = objectId # FIX THE COMMAND FOR NUMBERED OBJECTS try: thisId = int(objectId) objectId = "%(thisId)s" % locals() except Exception as e: pass theseparams = copy.deepcopy(params) theseparams["COMMAND"] = '"' + objectId + '"' paramList.append(theseparams) # TEST THE URL # try: # import requests # response = requests.get( # url="https://ssd.jpl.nasa.gov/horizons_batch.cgi", # params=theseparams, # ) # content = response.content # status_code = response.status_code # print response.url # except requests.exceptions.RequestException: # print('HTTP Request failed') # sys.exit(0) rs = [grequests.get("https://ssd.jpl.nasa.gov/horizons_batch.cgi", params=p) for p in paramList] def exception_handler(request, exception): print "Request failed" print exception returns = grequests.map(rs, size=1, exception_handler=exception_handler) for result, requestId in zip(returns, objectList): r = result.content match = re.search( r'Target body name:\s(.*?)\{', r, flags=re.S # re.S ) if not match: log.warning( "Horizons could not find a match for `%(requestId)s`" % locals()) try: import requests response = requests.get( url="https://ssd.jpl.nasa.gov/horizons_batch.cgi", params=theseparams, ) content = response.content status_code = response.status_code print response.url except requests.exceptions.RequestException: print('HTTP Request failed') sys.exit(0) objectDict = {} for k in keys: v = None objectDict[k] = v objectDict["objectId"] = requestId + " - NOT FOUND" objectDict["requestId"] = requestId objectDict["mjd"] = None orderDict = collections.OrderedDict({}) for i in order: orderDict[i] = objectDict[i] resultList.append(orderDict) continue horizonsId = match.group(1).replace("(", "").replace(")", "").strip() match = re.search( r'\$\$SOE\n(.*?)\n\$\$EOE', r, flags=re.S # re.S ) keys2 = copy.deepcopy(keys) order2 = copy.deepcopy(order) if "S-brt," not in r: keys2.remove("surface_brightness") try: order2.remove("surface_brightness") except: pass lines = match.group(1).split("\n") for line in lines: vals = line.split(",") objectDict = {} for k, v in zip(keys2, vals): v = v.strip().replace("/", "") try: v = float(v) except: pass objectDict[k] = v objectDict["mjd"] = objectDict["jd"] - 2400000.5 objectDict["objectId"] = horizonsId objectDict["requestId"] = requestId orderDict = collections.OrderedDict({}) for i in order2: orderDict[i] = objectDict[i] resultList.append(orderDict) log.debug('completed the ``jpl_horizons_ephemeris`` function') return resultList
[ "def", "jpl_horizons_ephemeris", "(", "log", ",", "objectId", ",", "mjd", ",", "obscode", "=", "500", ",", "verbose", "=", "False", ")", ":", "log", ".", "debug", "(", "'starting the ``jpl_horizons_ephemeris`` function'", ")", "# MAKE SURE MJDs ARE IN A LIST", "if",...
Given a known solar-system object ID (human-readable name, MPC number or MPC packed format) and one or more specific epochs, return the calculated ephemerides **Key Arguments:** - ``log`` -- logger - ``objectId`` -- human-readable name, MPC number or MPC packed format id of the solar-system object or list of names - ``mjd`` -- a single MJD, or a list of up to 10,000 MJDs to generate an ephemeris for - ``obscode`` -- the observatory code for the ephemeris generation. Default **500** (geocentric) - ``verbose`` -- return extra information with each ephemeris **Return:** - ``resultList`` -- a list of ordered dictionaries containing the returned ephemerides **Usage:** To generate a an ephemeris for a single epoch run, using ATLAS Haleakala as your observatory: .. code-block:: python from rockfinder import jpl_horizons_ephemeris eph = jpl_horizons_ephemeris( log=log, objectId=1, mjd=57916., obscode='T05' ) or to generate an ephemeris for multiple epochs: .. code-block:: python from rockfinder import jpl_horizons_ephemeris eph = jpl_horizons_ephemeris( log=log, objectId="ceres", mjd=[57916.1,57917.234,57956.34523] verbose=True ) Note by passing `verbose=True` the essential ephemeris data is supplimented with some extra data It's also possible to pass in an array of object IDs: .. code-block:: python from rockfinder import jpl_horizons_ephemeris eph = jpl_horizons_ephemeris( log=log, objectId=[1,5,03547,"Shikoku","K10B11A"], mjd=[57916.1,57917.234,57956.34523] )
[ "Given", "a", "known", "solar", "-", "system", "object", "ID", "(", "human", "-", "readable", "name", "MPC", "number", "or", "MPC", "packed", "format", ")", "and", "one", "or", "more", "specific", "epochs", "return", "the", "calculated", "ephemerides" ]
train
https://github.com/thespacedoctor/rockfinder/blob/631371032d4d4166ee40484e93d35a0efc400600/rockfinder/jpl_horizons_ephemeris.py#L24-L246
reflexsc/reflex
dev/build.py
Obj.status
def status(self, key, value): """Update the status of a build""" value = value.lower() if value not in valid_statuses: raise ValueError("Build Status must have a value from:\n{}".format(", ".join(valid_statuses))) self.obj['status'][key] = value self.changes.append("Updating build:{}.status.{}={}" .format(self.obj['name'], key, value)) return self
python
def status(self, key, value): """Update the status of a build""" value = value.lower() if value not in valid_statuses: raise ValueError("Build Status must have a value from:\n{}".format(", ".join(valid_statuses))) self.obj['status'][key] = value self.changes.append("Updating build:{}.status.{}={}" .format(self.obj['name'], key, value)) return self
[ "def", "status", "(", "self", ",", "key", ",", "value", ")", ":", "value", "=", "value", ".", "lower", "(", ")", "if", "value", "not", "in", "valid_statuses", ":", "raise", "ValueError", "(", "\"Build Status must have a value from:\\n{}\"", ".", "format", "(...
Update the status of a build
[ "Update", "the", "status", "of", "a", "build" ]
train
https://github.com/reflexsc/reflex/blob/cee6b0ccfef395ca5e157d644a2e3252cea9fe62/dev/build.py#L70-L79
reflexsc/reflex
dev/build.py
Obj.state
def state(self, state): """Update the status of a build""" state = state.lower() if state not in valid_states: raise ValueError("Build state must have a value from:\n{}".format(", ".join(valid_state))) self.obj['state'] = state self.changes.append("Updating build:{}.state={}" .format(self.obj['name'], state)) return self
python
def state(self, state): """Update the status of a build""" state = state.lower() if state not in valid_states: raise ValueError("Build state must have a value from:\n{}".format(", ".join(valid_state))) self.obj['state'] = state self.changes.append("Updating build:{}.state={}" .format(self.obj['name'], state)) return self
[ "def", "state", "(", "self", ",", "state", ")", ":", "state", "=", "state", ".", "lower", "(", ")", "if", "state", "not", "in", "valid_states", ":", "raise", "ValueError", "(", "\"Build state must have a value from:\\n{}\"", ".", "format", "(", "\", \"", "."...
Update the status of a build
[ "Update", "the", "status", "of", "a", "build" ]
train
https://github.com/reflexsc/reflex/blob/cee6b0ccfef395ca5e157d644a2e3252cea9fe62/dev/build.py#L82-L91
reflexsc/reflex
dev/build.py
Obj.change
def change(self, key, value): """Update any other attribute on the build object""" self.obj[key] = value self.changes.append("Updating build:{}.{}={}" .format(self.obj['name'], key, value)) return self
python
def change(self, key, value): """Update any other attribute on the build object""" self.obj[key] = value self.changes.append("Updating build:{}.{}={}" .format(self.obj['name'], key, value)) return self
[ "def", "change", "(", "self", ",", "key", ",", "value", ")", ":", "self", ".", "obj", "[", "key", "]", "=", "value", "self", ".", "changes", ".", "append", "(", "\"Updating build:{}.{}={}\"", ".", "format", "(", "self", ".", "obj", "[", "'name'", "]"...
Update any other attribute on the build object
[ "Update", "any", "other", "attribute", "on", "the", "build", "object" ]
train
https://github.com/reflexsc/reflex/blob/cee6b0ccfef395ca5e157d644a2e3252cea9fe62/dev/build.py#L94-L99
reflexsc/reflex
dev/build.py
Obj.release
def release(self, lane, status, target=None, meta=None, svcs=None): """Set release information on a build""" if target not in (None, 'current', 'future'): raise ValueError("\nError: Target must be None, 'current', or 'future'\n") svcs, meta, lane = self._prep_for_release(lane, svcs=svcs, meta=meta) when = time.time() # loathe non-functional dictionaries in python rel_data = meta.copy() rel_data.update({ "_time": when, "status": status, "services": list(svcs.keys()), }) rel_lane = self.obj.get('lanes', {}).get(lane, dict(log=[],status=status)) rel_lane['status'] = status rel_lane['log'] = [rel_data] + rel_lane.get('log', []) self.rcs.patch('build', self.name, { "lanes": { lane: rel_lane, } }) if target: for svc in svcs: rel_data = {target: self.name} # if target is specified, then also update svc.release # {current/previous/future} if target == "current": mysvc = svcs[svc] curver = mysvc.get('release', {}).get('current', '') prev = [] if curver: prev = mysvc.get('release', {}).get('previous', []) if not prev or prev[0] != curver: prev = [curver] + prev while len(prev) > 5: # magic values FTW prev.pop() # only keep history of 5 previous rel_data['previous'] = prev self.rcs.patch('service', svc, { "release": rel_data, "statuses": {status: when}, "status": status })
python
def release(self, lane, status, target=None, meta=None, svcs=None): """Set release information on a build""" if target not in (None, 'current', 'future'): raise ValueError("\nError: Target must be None, 'current', or 'future'\n") svcs, meta, lane = self._prep_for_release(lane, svcs=svcs, meta=meta) when = time.time() # loathe non-functional dictionaries in python rel_data = meta.copy() rel_data.update({ "_time": when, "status": status, "services": list(svcs.keys()), }) rel_lane = self.obj.get('lanes', {}).get(lane, dict(log=[],status=status)) rel_lane['status'] = status rel_lane['log'] = [rel_data] + rel_lane.get('log', []) self.rcs.patch('build', self.name, { "lanes": { lane: rel_lane, } }) if target: for svc in svcs: rel_data = {target: self.name} # if target is specified, then also update svc.release # {current/previous/future} if target == "current": mysvc = svcs[svc] curver = mysvc.get('release', {}).get('current', '') prev = [] if curver: prev = mysvc.get('release', {}).get('previous', []) if not prev or prev[0] != curver: prev = [curver] + prev while len(prev) > 5: # magic values FTW prev.pop() # only keep history of 5 previous rel_data['previous'] = prev self.rcs.patch('service', svc, { "release": rel_data, "statuses": {status: when}, "status": status })
[ "def", "release", "(", "self", ",", "lane", ",", "status", ",", "target", "=", "None", ",", "meta", "=", "None", ",", "svcs", "=", "None", ")", ":", "if", "target", "not", "in", "(", "None", ",", "'current'", ",", "'future'", ")", ":", "raise", "...
Set release information on a build
[ "Set", "release", "information", "on", "a", "build" ]
train
https://github.com/reflexsc/reflex/blob/cee6b0ccfef395ca5e157d644a2e3252cea9fe62/dev/build.py#L146-L194
reflexsc/reflex
dev/build.py
Obj.promote
def promote(self, lane, svcs=None, meta=None): """promote a build so it is ready for an upper lane""" svcs, meta, lane = self._prep_for_release(lane, svcs=svcs, meta=meta) # iterate and mark as future release for svc in svcs: self.changes.append("Promoting: {}.release.future={}".format(svc, self.name)) self.rcs.patch('service', svc, { "release": {"future": self.name}, # new way "statuses": {"future": time.time()}, }) return self
python
def promote(self, lane, svcs=None, meta=None): """promote a build so it is ready for an upper lane""" svcs, meta, lane = self._prep_for_release(lane, svcs=svcs, meta=meta) # iterate and mark as future release for svc in svcs: self.changes.append("Promoting: {}.release.future={}".format(svc, self.name)) self.rcs.patch('service', svc, { "release": {"future": self.name}, # new way "statuses": {"future": time.time()}, }) return self
[ "def", "promote", "(", "self", ",", "lane", ",", "svcs", "=", "None", ",", "meta", "=", "None", ")", ":", "svcs", ",", "meta", ",", "lane", "=", "self", ".", "_prep_for_release", "(", "lane", ",", "svcs", "=", "svcs", ",", "meta", "=", "meta", ")...
promote a build so it is ready for an upper lane
[ "promote", "a", "build", "so", "it", "is", "ready", "for", "an", "upper", "lane" ]
train
https://github.com/reflexsc/reflex/blob/cee6b0ccfef395ca5e157d644a2e3252cea9fe62/dev/build.py#L197-L210
reflexsc/reflex
dev/build.py
Obj.add_info
def add_info(self, data): """add info to a build""" for key in data: # verboten if key in ('status','state','name','id','application','services','release'): raise ValueError("Sorry, cannot set build info with key of {}".format(key)) self.obj[key] = data[key] self.changes.append("Adding build info") return self
python
def add_info(self, data): """add info to a build""" for key in data: # verboten if key in ('status','state','name','id','application','services','release'): raise ValueError("Sorry, cannot set build info with key of {}".format(key)) self.obj[key] = data[key] self.changes.append("Adding build info") return self
[ "def", "add_info", "(", "self", ",", "data", ")", ":", "for", "key", "in", "data", ":", "# verboten", "if", "key", "in", "(", "'status'", ",", "'state'", ",", "'name'", ",", "'id'", ",", "'application'", ",", "'services'", ",", "'release'", ")", ":", ...
add info to a build
[ "add", "info", "to", "a", "build" ]
train
https://github.com/reflexsc/reflex/blob/cee6b0ccfef395ca5e157d644a2e3252cea9fe62/dev/build.py#L213-L221
renzon/gaeforms
gaeforms/base.py
BaseField.validate_field
def validate_field(self, value): ''' Method that must validate the value It must return None if the value is valid and a error msg otherelse. Ex: If expected input must be int, validate should a return a msg like "The filed must be a integer value" ''' if self.choices: value = self.normalize_field(value) if value in self.choices: return None return _('Must be one of: %(choices)s') % {'choices': '; '.join(self.choices)} if self.default is not None: if value is None or value == '': value = self.default if self.required and (value is None or value == ''): return _('Required field')
python
def validate_field(self, value): ''' Method that must validate the value It must return None if the value is valid and a error msg otherelse. Ex: If expected input must be int, validate should a return a msg like "The filed must be a integer value" ''' if self.choices: value = self.normalize_field(value) if value in self.choices: return None return _('Must be one of: %(choices)s') % {'choices': '; '.join(self.choices)} if self.default is not None: if value is None or value == '': value = self.default if self.required and (value is None or value == ''): return _('Required field')
[ "def", "validate_field", "(", "self", ",", "value", ")", ":", "if", "self", ".", "choices", ":", "value", "=", "self", ".", "normalize_field", "(", "value", ")", "if", "value", "in", "self", ".", "choices", ":", "return", "None", "return", "_", "(", ...
Method that must validate the value It must return None if the value is valid and a error msg otherelse. Ex: If expected input must be int, validate should a return a msg like "The filed must be a integer value"
[ "Method", "that", "must", "validate", "the", "value", "It", "must", "return", "None", "if", "the", "value", "is", "valid", "and", "a", "error", "msg", "otherelse", ".", "Ex", ":", "If", "expected", "input", "must", "be", "int", "validate", "should", "a",...
train
https://github.com/renzon/gaeforms/blob/7d3f4d964f087c992fe92bc8d41222010b7f6430/gaeforms/base.py#L38-L54
renzon/gaeforms
gaeforms/base.py
BaseField.normalize_field
def normalize_field(self, value): """ Method that must transform the value from string Ex: if the expected type is int, it should return int(self._attr) """ if self.default is not None: if value is None or value == '': value = self.default return value
python
def normalize_field(self, value): """ Method that must transform the value from string Ex: if the expected type is int, it should return int(self._attr) """ if self.default is not None: if value is None or value == '': value = self.default return value
[ "def", "normalize_field", "(", "self", ",", "value", ")", ":", "if", "self", ".", "default", "is", "not", "None", ":", "if", "value", "is", "None", "or", "value", "==", "''", ":", "value", "=", "self", ".", "default", "return", "value" ]
Method that must transform the value from string Ex: if the expected type is int, it should return int(self._attr)
[ "Method", "that", "must", "transform", "the", "value", "from", "string", "Ex", ":", "if", "the", "expected", "type", "is", "int", "it", "should", "return", "int", "(", "self", ".", "_attr", ")" ]
train
https://github.com/renzon/gaeforms/blob/7d3f4d964f087c992fe92bc8d41222010b7f6430/gaeforms/base.py#L86-L95
renzon/gaeforms
gaeforms/base.py
BaseField.localize_field
def localize_field(self, value): """ Method that must transform the value from object to localized string """ if self.default is not None: if value is None or value == '': value = self.default return value or ''
python
def localize_field(self, value): """ Method that must transform the value from object to localized string """ if self.default is not None: if value is None or value == '': value = self.default return value or ''
[ "def", "localize_field", "(", "self", ",", "value", ")", ":", "if", "self", ".", "default", "is", "not", "None", ":", "if", "value", "is", "None", "or", "value", "==", "''", ":", "value", "=", "self", ".", "default", "return", "value", "or", "''" ]
Method that must transform the value from object to localized string
[ "Method", "that", "must", "transform", "the", "value", "from", "object", "to", "localized", "string" ]
train
https://github.com/renzon/gaeforms/blob/7d3f4d964f087c992fe92bc8d41222010b7f6430/gaeforms/base.py#L106-L114
scieloorg/publicationstatsapi
publicationstats/queries.py
journal_composition
def journal_composition(collection, issn, raw=False): """ This method retrieve the total of documents, articles (citable documents), issues and bibliografic references of a journal arguments collection: SciELO 3 letters Acronym issn: Journal ISSN return for journal context { "citable": 12140, "non_citable": 20, "docs": 12160, "issues": 120, "references": 286619 } """ tc = ThriftClient() body = {"query": {"filtered": {}}} fltr = {} query = { "query": { "bool": { "must": [ { "match": { "collection": collection } }, { "match": { "issn": issn } }, ] } } } body['query']['filtered'].update(fltr) body['query']['filtered'].update(query) query_parameters = [ ('size', '0'), ('search_type', 'count') ] body['aggs'] = { "issues": { "cardinality": { "field": "issue" } }, "citations": { "sum": { "field": "citations" } }, "citable": { "filter": { "terms": { "document_type": [i for i in utils.CITABLE_DOCUMENT_TYPES] } } } } query_result = tc.search('article', json.dumps(body), query_parameters) computed = _compute_journal_composition(query_result) return query_result if raw else computed
python
def journal_composition(collection, issn, raw=False): """ This method retrieve the total of documents, articles (citable documents), issues and bibliografic references of a journal arguments collection: SciELO 3 letters Acronym issn: Journal ISSN return for journal context { "citable": 12140, "non_citable": 20, "docs": 12160, "issues": 120, "references": 286619 } """ tc = ThriftClient() body = {"query": {"filtered": {}}} fltr = {} query = { "query": { "bool": { "must": [ { "match": { "collection": collection } }, { "match": { "issn": issn } }, ] } } } body['query']['filtered'].update(fltr) body['query']['filtered'].update(query) query_parameters = [ ('size', '0'), ('search_type', 'count') ] body['aggs'] = { "issues": { "cardinality": { "field": "issue" } }, "citations": { "sum": { "field": "citations" } }, "citable": { "filter": { "terms": { "document_type": [i for i in utils.CITABLE_DOCUMENT_TYPES] } } } } query_result = tc.search('article', json.dumps(body), query_parameters) computed = _compute_journal_composition(query_result) return query_result if raw else computed
[ "def", "journal_composition", "(", "collection", ",", "issn", ",", "raw", "=", "False", ")", ":", "tc", "=", "ThriftClient", "(", ")", "body", "=", "{", "\"query\"", ":", "{", "\"filtered\"", ":", "{", "}", "}", "}", "fltr", "=", "{", "}", "query", ...
This method retrieve the total of documents, articles (citable documents), issues and bibliografic references of a journal arguments collection: SciELO 3 letters Acronym issn: Journal ISSN return for journal context { "citable": 12140, "non_citable": 20, "docs": 12160, "issues": 120, "references": 286619 }
[ "This", "method", "retrieve", "the", "total", "of", "documents", "articles", "(", "citable", "documents", ")", "issues", "and", "bibliografic", "references", "of", "a", "journal" ]
train
https://github.com/scieloorg/publicationstatsapi/blob/118995d75ef9478f64d5707107f4ce1640a0aa8e/publicationstats/queries.py#L39-L115
scieloorg/publicationstatsapi
publicationstats/queries.py
collection_composition
def collection_composition(collection, raw=False): """ This method retrieve the total of documents, articles (citable documents), issues and bibliografic references of a journal arguments collection: SciELO 3 letters Acronym issn: Journal ISSN return for journal context { "citable": 12140, "non_citable": 20, "docs": 12160, "issues": 120, "references": 286619 } """ tc = ThriftClient() body = {"query": {"filtered": {}}} fltr = {} query = { "query": { "bool": { "must": [ { "match": { "collection": collection } } ] } } } body['query']['filtered'].update(fltr) body['query']['filtered'].update(query) query_parameters = [ ('size', '0'), ('search_type', 'count') ] body['aggs'] = { "journals": { "cardinality": { "field": "issn" } }, "issues": { "cardinality": { "field": "issue" } }, "citations": { "sum": { "field": "citations" } }, "citable": { "filter": { "terms": { "document_type": [i for i in utils.CITABLE_DOCUMENT_TYPES] } } } } query_result = tc.search('article', json.dumps(body), query_parameters) computed = _compute_collection_composition(query_result) return query_result if raw else computed
python
def collection_composition(collection, raw=False): """ This method retrieve the total of documents, articles (citable documents), issues and bibliografic references of a journal arguments collection: SciELO 3 letters Acronym issn: Journal ISSN return for journal context { "citable": 12140, "non_citable": 20, "docs": 12160, "issues": 120, "references": 286619 } """ tc = ThriftClient() body = {"query": {"filtered": {}}} fltr = {} query = { "query": { "bool": { "must": [ { "match": { "collection": collection } } ] } } } body['query']['filtered'].update(fltr) body['query']['filtered'].update(query) query_parameters = [ ('size', '0'), ('search_type', 'count') ] body['aggs'] = { "journals": { "cardinality": { "field": "issn" } }, "issues": { "cardinality": { "field": "issue" } }, "citations": { "sum": { "field": "citations" } }, "citable": { "filter": { "terms": { "document_type": [i for i in utils.CITABLE_DOCUMENT_TYPES] } } } } query_result = tc.search('article', json.dumps(body), query_parameters) computed = _compute_collection_composition(query_result) return query_result if raw else computed
[ "def", "collection_composition", "(", "collection", ",", "raw", "=", "False", ")", ":", "tc", "=", "ThriftClient", "(", ")", "body", "=", "{", "\"query\"", ":", "{", "\"filtered\"", ":", "{", "}", "}", "}", "fltr", "=", "{", "}", "query", "=", "{", ...
This method retrieve the total of documents, articles (citable documents), issues and bibliografic references of a journal arguments collection: SciELO 3 letters Acronym issn: Journal ISSN return for journal context { "citable": 12140, "non_citable": 20, "docs": 12160, "issues": 120, "references": 286619 }
[ "This", "method", "retrieve", "the", "total", "of", "documents", "articles", "(", "citable", "documents", ")", "issues", "and", "bibliografic", "references", "of", "a", "journal" ]
train
https://github.com/scieloorg/publicationstatsapi/blob/118995d75ef9478f64d5707107f4ce1640a0aa8e/publicationstats/queries.py#L131-L207
scieloorg/publicationstatsapi
publicationstats/queries.py
journals_status
def journals_status(collection, raw=False): """ This method retrieve the total of documents, articles (citable documents), issues and bibliografic references of a journal arguments collection: SciELO 3 letters Acronym issn: Journal ISSN return for journal context { "citable": 12140, "non_citable": 20, "docs": 12160, "issues": 120, "references": 286619 } """ tc = ThriftClient() body = {"query": {"filtered": {}}} fltr = {} query = { "query": { "bool": { "must": [ { "match": { "collection": collection } } ] } } } body['query']['filtered'].update(fltr) body['query']['filtered'].update(query) query_parameters = [ ('size', '0'), ('search_type', 'count') ] body['aggs'] = { "status": { "terms": { "field": "status" } } } query_result = tc.search('journal', json.dumps(body), query_parameters) computed = _compute_journals_status(query_result) return query_result if raw else computed
python
def journals_status(collection, raw=False): """ This method retrieve the total of documents, articles (citable documents), issues and bibliografic references of a journal arguments collection: SciELO 3 letters Acronym issn: Journal ISSN return for journal context { "citable": 12140, "non_citable": 20, "docs": 12160, "issues": 120, "references": 286619 } """ tc = ThriftClient() body = {"query": {"filtered": {}}} fltr = {} query = { "query": { "bool": { "must": [ { "match": { "collection": collection } } ] } } } body['query']['filtered'].update(fltr) body['query']['filtered'].update(query) query_parameters = [ ('size', '0'), ('search_type', 'count') ] body['aggs'] = { "status": { "terms": { "field": "status" } } } query_result = tc.search('journal', json.dumps(body), query_parameters) computed = _compute_journals_status(query_result) return query_result if raw else computed
[ "def", "journals_status", "(", "collection", ",", "raw", "=", "False", ")", ":", "tc", "=", "ThriftClient", "(", ")", "body", "=", "{", "\"query\"", ":", "{", "\"filtered\"", ":", "{", "}", "}", "}", "fltr", "=", "{", "}", "query", "=", "{", "\"que...
This method retrieve the total of documents, articles (citable documents), issues and bibliografic references of a journal arguments collection: SciELO 3 letters Acronym issn: Journal ISSN return for journal context { "citable": 12140, "non_citable": 20, "docs": 12160, "issues": 120, "references": 286619 }
[ "This", "method", "retrieve", "the", "total", "of", "documents", "articles", "(", "citable", "documents", ")", "issues", "and", "bibliografic", "references", "of", "a", "journal" ]
train
https://github.com/scieloorg/publicationstatsapi/blob/118995d75ef9478f64d5707107f4ce1640a0aa8e/publicationstats/queries.py#L227-L286
scivision/gridaurora
gridaurora/eFluxGen.py
maxwellian
def maxwellian(E: np.ndarray, E0: np.ndarray, Q0: np.ndarray) -> Tuple[np.ndarray, float]: """ input: ------ E: 1-D vector of energy bins [eV] E0: characteristic energy (scalar or vector) [eV] Q0: flux coefficient (scalar or vector) (to yield overall flux Q) output: ------- Phi: differential number flux Q: total flux Tanaka 2006 Eqn. 1 http://odin.gi.alaska.edu/lumm/Papers/Tanaka_2006JA011744.pdf """ E0 = np.atleast_1d(E0) Q0 = np.atleast_1d(Q0) assert E0.ndim == Q0.ndim == 1 assert (Q0.size == 1 or Q0.size == E0.size) Phi = Q0/(2*pi*E0**3) * E[:, None] * np.exp(-E[:, None]/E0) Q = np.trapz(Phi, E, axis=0) logging.info('total maxwellian flux Q: ' + (' '.join('{:.1e}'.format(q) for q in Q))) return Phi, Q
python
def maxwellian(E: np.ndarray, E0: np.ndarray, Q0: np.ndarray) -> Tuple[np.ndarray, float]: """ input: ------ E: 1-D vector of energy bins [eV] E0: characteristic energy (scalar or vector) [eV] Q0: flux coefficient (scalar or vector) (to yield overall flux Q) output: ------- Phi: differential number flux Q: total flux Tanaka 2006 Eqn. 1 http://odin.gi.alaska.edu/lumm/Papers/Tanaka_2006JA011744.pdf """ E0 = np.atleast_1d(E0) Q0 = np.atleast_1d(Q0) assert E0.ndim == Q0.ndim == 1 assert (Q0.size == 1 or Q0.size == E0.size) Phi = Q0/(2*pi*E0**3) * E[:, None] * np.exp(-E[:, None]/E0) Q = np.trapz(Phi, E, axis=0) logging.info('total maxwellian flux Q: ' + (' '.join('{:.1e}'.format(q) for q in Q))) return Phi, Q
[ "def", "maxwellian", "(", "E", ":", "np", ".", "ndarray", ",", "E0", ":", "np", ".", "ndarray", ",", "Q0", ":", "np", ".", "ndarray", ")", "->", "Tuple", "[", "np", ".", "ndarray", ",", "float", "]", ":", "E0", "=", "np", ".", "atleast_1d", "("...
input: ------ E: 1-D vector of energy bins [eV] E0: characteristic energy (scalar or vector) [eV] Q0: flux coefficient (scalar or vector) (to yield overall flux Q) output: ------- Phi: differential number flux Q: total flux Tanaka 2006 Eqn. 1 http://odin.gi.alaska.edu/lumm/Papers/Tanaka_2006JA011744.pdf
[ "input", ":", "------", "E", ":", "1", "-", "D", "vector", "of", "energy", "bins", "[", "eV", "]", "E0", ":", "characteristic", "energy", "(", "scalar", "or", "vector", ")", "[", "eV", "]", "Q0", ":", "flux", "coefficient", "(", "scalar", "or", "ve...
train
https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/eFluxGen.py#L14-L39
scivision/gridaurora
gridaurora/eFluxGen.py
hitail
def hitail(E: np.ndarray, diffnumflux: np.ndarray, isimE0: np.ndarray, E0: np.ndarray, Bhf: np.ndarray, bh: float, verbose: int = 0): """ strickland 1993 said 0.2, but 0.145 gives better match to peak flux at 2500 = E0 """ Bh = np.empty_like(E0) for iE0 in np.arange(E0.size): Bh[iE0] = Bhf[iE0]*diffnumflux[isimE0[iE0], iE0] # 4100. # bh = 4 #2.9 het = Bh*(E[:, None] / E0)**-bh het[E[:, None] < E0] = 0. if verbose > 0: print('Bh: ' + (' '.join('{:0.1f}'.format(b) for b in Bh))) return het
python
def hitail(E: np.ndarray, diffnumflux: np.ndarray, isimE0: np.ndarray, E0: np.ndarray, Bhf: np.ndarray, bh: float, verbose: int = 0): """ strickland 1993 said 0.2, but 0.145 gives better match to peak flux at 2500 = E0 """ Bh = np.empty_like(E0) for iE0 in np.arange(E0.size): Bh[iE0] = Bhf[iE0]*diffnumflux[isimE0[iE0], iE0] # 4100. # bh = 4 #2.9 het = Bh*(E[:, None] / E0)**-bh het[E[:, None] < E0] = 0. if verbose > 0: print('Bh: ' + (' '.join('{:0.1f}'.format(b) for b in Bh))) return het
[ "def", "hitail", "(", "E", ":", "np", ".", "ndarray", ",", "diffnumflux", ":", "np", ".", "ndarray", ",", "isimE0", ":", "np", ".", "ndarray", ",", "E0", ":", "np", ".", "ndarray", ",", "Bhf", ":", "np", ".", "ndarray", ",", "bh", ":", "float", ...
strickland 1993 said 0.2, but 0.145 gives better match to peak flux at 2500 = E0
[ "strickland", "1993", "said", "0", ".", "2", "but", "0", ".", "145", "gives", "better", "match", "to", "peak", "flux", "at", "2500", "=", "E0" ]
train
https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/eFluxGen.py#L90-L103
aerogear/digger-build-cli
digger/actions.py
BuildAction.handler
def handler(self, path='/app', mode='debug'): """ Handler that executes the application build based on its platform (using the ``project`` package). param: path(str): the project source code path, default is '/app'. param: target(str): the platform target, android-23 is the default for android platform if no value is provided. Returns: Doesn't return a value but prints the output in the STDOUT/STDERR. """ options = { 'path': path } project = builds.from_path(path) project.prepare() project.validate() project.build(mode=mode)
python
def handler(self, path='/app', mode='debug'): """ Handler that executes the application build based on its platform (using the ``project`` package). param: path(str): the project source code path, default is '/app'. param: target(str): the platform target, android-23 is the default for android platform if no value is provided. Returns: Doesn't return a value but prints the output in the STDOUT/STDERR. """ options = { 'path': path } project = builds.from_path(path) project.prepare() project.validate() project.build(mode=mode)
[ "def", "handler", "(", "self", ",", "path", "=", "'/app'", ",", "mode", "=", "'debug'", ")", ":", "options", "=", "{", "'path'", ":", "path", "}", "project", "=", "builds", ".", "from_path", "(", "path", ")", "project", ".", "prepare", "(", ")", "p...
Handler that executes the application build based on its platform (using the ``project`` package). param: path(str): the project source code path, default is '/app'. param: target(str): the platform target, android-23 is the default for android platform if no value is provided. Returns: Doesn't return a value but prints the output in the STDOUT/STDERR.
[ "Handler", "that", "executes", "the", "application", "build", "based", "on", "its", "platform", "(", "using", "the", "project", "package", ")", "." ]
train
https://github.com/aerogear/digger-build-cli/blob/8b88a31063526ec7222dbea6a87309686ad21320/digger/actions.py#L18-L34
aerogear/digger-build-cli
digger/actions.py
ExportAction.handler
def handler(self, path='/app'): """ Handler that prints the apk file(s) path that can be exported from the container (using the ``project`` package). :param path(str): the project source code path, default is '/app'. Returns: Doesn't return a value but prints the output in the STDOUT/STDERR (separated by a comma). """ options = { 'path': path } project = builds.from_path(path) print(project.get_export_path())
python
def handler(self, path='/app'): """ Handler that prints the apk file(s) path that can be exported from the container (using the ``project`` package). :param path(str): the project source code path, default is '/app'. Returns: Doesn't return a value but prints the output in the STDOUT/STDERR (separated by a comma). """ options = { 'path': path } project = builds.from_path(path) print(project.get_export_path())
[ "def", "handler", "(", "self", ",", "path", "=", "'/app'", ")", ":", "options", "=", "{", "'path'", ":", "path", "}", "project", "=", "builds", ".", "from_path", "(", "path", ")", "print", "(", "project", ".", "get_export_path", "(", ")", ")" ]
Handler that prints the apk file(s) path that can be exported from the container (using the ``project`` package). :param path(str): the project source code path, default is '/app'. Returns: Doesn't return a value but prints the output in the STDOUT/STDERR (separated by a comma).
[ "Handler", "that", "prints", "the", "apk", "file", "(", "s", ")", "path", "that", "can", "be", "exported", "from", "the", "container", "(", "using", "the", "project", "package", ")", "." ]
train
https://github.com/aerogear/digger-build-cli/blob/8b88a31063526ec7222dbea6a87309686ad21320/digger/actions.py#L46-L59
aerogear/digger-build-cli
digger/actions.py
LogAction.handler
def handler(self, path='/app', ctx='all'): """ Handler that prints the project build log into the STDOUT (using the ``project`` package). :param path(str): the project source code path, default is '/app'. :param ctx(str): build log context file to be used, available options: validate, prepare, build or all. Returns: Doesn't return a value but prints the output in the STDOUT/STDERR (separated by a comma). """ options = { 'path': path } project = builds.from_path(path) project.log(ctx=ctx)
python
def handler(self, path='/app', ctx='all'): """ Handler that prints the project build log into the STDOUT (using the ``project`` package). :param path(str): the project source code path, default is '/app'. :param ctx(str): build log context file to be used, available options: validate, prepare, build or all. Returns: Doesn't return a value but prints the output in the STDOUT/STDERR (separated by a comma). """ options = { 'path': path } project = builds.from_path(path) project.log(ctx=ctx)
[ "def", "handler", "(", "self", ",", "path", "=", "'/app'", ",", "ctx", "=", "'all'", ")", ":", "options", "=", "{", "'path'", ":", "path", "}", "project", "=", "builds", ".", "from_path", "(", "path", ")", "project", ".", "log", "(", "ctx", "=", ...
Handler that prints the project build log into the STDOUT (using the ``project`` package). :param path(str): the project source code path, default is '/app'. :param ctx(str): build log context file to be used, available options: validate, prepare, build or all. Returns: Doesn't return a value but prints the output in the STDOUT/STDERR (separated by a comma).
[ "Handler", "that", "prints", "the", "project", "build", "log", "into", "the", "STDOUT", "(", "using", "the", "project", "package", ")", "." ]
train
https://github.com/aerogear/digger-build-cli/blob/8b88a31063526ec7222dbea6a87309686ad21320/digger/actions.py#L97-L111
fredericklussier/ObservablePy
observablePy/Diffusible.py
Diffusible.diffuse
def diffuse(self, *args): """ this is a dispatcher of diffuse implementation. Depending of the arguments used. """ mode = diffusingModeEnum.unknown if (isinstance(args[0], str) and (len(args) == 3)): # reveived diffuse(str, any, any) mode = diffusingModeEnum.element elif (hasattr(args[0], "__len__") and (len(args) == 2)): # reveived diffuse(dict({str: any}), dict({str: any})) mode = diffusingModeEnum.elements else: raise TypeError( "Called diffuse method using bad argments, receive this" + " '{0}', but expected 'str, any, any' or" + " 'dict(str: any), dict(str: any)'." .format(args)) self._diffuse(mode, *args)
python
def diffuse(self, *args): """ this is a dispatcher of diffuse implementation. Depending of the arguments used. """ mode = diffusingModeEnum.unknown if (isinstance(args[0], str) and (len(args) == 3)): # reveived diffuse(str, any, any) mode = diffusingModeEnum.element elif (hasattr(args[0], "__len__") and (len(args) == 2)): # reveived diffuse(dict({str: any}), dict({str: any})) mode = diffusingModeEnum.elements else: raise TypeError( "Called diffuse method using bad argments, receive this" + " '{0}', but expected 'str, any, any' or" + " 'dict(str: any), dict(str: any)'." .format(args)) self._diffuse(mode, *args)
[ "def", "diffuse", "(", "self", ",", "*", "args", ")", ":", "mode", "=", "diffusingModeEnum", ".", "unknown", "if", "(", "isinstance", "(", "args", "[", "0", "]", ",", "str", ")", "and", "(", "len", "(", "args", ")", "==", "3", ")", ")", ":", "#...
this is a dispatcher of diffuse implementation. Depending of the arguments used.
[ "this", "is", "a", "dispatcher", "of", "diffuse", "implementation", ".", "Depending", "of", "the", "arguments", "used", "." ]
train
https://github.com/fredericklussier/ObservablePy/blob/fd7926a0568621f80b1d567d18f199976f1fa4e8/observablePy/Diffusible.py#L35-L57
hangyan/shaw
shaw/web/web.py
json_response
def json_response(data, status=200): """Return a JsonResponse. Make sure you have django installed first.""" from django.http import JsonResponse return JsonResponse(data=data, status=status, safe=isinstance(data, dict))
python
def json_response(data, status=200): """Return a JsonResponse. Make sure you have django installed first.""" from django.http import JsonResponse return JsonResponse(data=data, status=status, safe=isinstance(data, dict))
[ "def", "json_response", "(", "data", ",", "status", "=", "200", ")", ":", "from", "django", ".", "http", "import", "JsonResponse", "return", "JsonResponse", "(", "data", "=", "data", ",", "status", "=", "status", ",", "safe", "=", "isinstance", "(", "dat...
Return a JsonResponse. Make sure you have django installed first.
[ "Return", "a", "JsonResponse", ".", "Make", "sure", "you", "have", "django", "installed", "first", "." ]
train
https://github.com/hangyan/shaw/blob/63d01d35e225ba4edb9c61edaf351e1bc0e8fd15/shaw/web/web.py#L11-L14
hangyan/shaw
shaw/web/web.py
error_response
def error_response(message, status=400, code=None): """"Return error message(in dict).""" from django.http import JsonResponse data = {'message': message} if code: data['code'] = code LOG.error("Error response, status code is : {} | {}".format(status, data)) return JsonResponse(data=data, status=status)
python
def error_response(message, status=400, code=None): """"Return error message(in dict).""" from django.http import JsonResponse data = {'message': message} if code: data['code'] = code LOG.error("Error response, status code is : {} | {}".format(status, data)) return JsonResponse(data=data, status=status)
[ "def", "error_response", "(", "message", ",", "status", "=", "400", ",", "code", "=", "None", ")", ":", "from", "django", ".", "http", "import", "JsonResponse", "data", "=", "{", "'message'", ":", "message", "}", "if", "code", ":", "data", "[", "'code'...
Return error message(in dict).
[ "Return", "error", "message", "(", "in", "dict", ")", "." ]
train
https://github.com/hangyan/shaw/blob/63d01d35e225ba4edb9c61edaf351e1bc0e8fd15/shaw/web/web.py#L23-L30
django-fluent/fluentcms-emailtemplates
fluentcms_emailtemplates/shortcuts.py
send_email_template
def send_email_template(slug, base_url=None, context=None, user=None, to=None, cc=None, bcc=None, attachments=None, headers=None, connection=None, fail_silently=False): """ Shortcut to send an email template. """ email_template = EmailTemplate.objects.get_for_slug(slug) email = email_template.get_email_message( base_url, context, user, to=to, cc=cc, bcc=bcc, attachments=attachments, headers=headers, connection=connection ) return email.send(fail_silently=fail_silently)
python
def send_email_template(slug, base_url=None, context=None, user=None, to=None, cc=None, bcc=None, attachments=None, headers=None, connection=None, fail_silently=False): """ Shortcut to send an email template. """ email_template = EmailTemplate.objects.get_for_slug(slug) email = email_template.get_email_message( base_url, context, user, to=to, cc=cc, bcc=bcc, attachments=attachments, headers=headers, connection=connection ) return email.send(fail_silently=fail_silently)
[ "def", "send_email_template", "(", "slug", ",", "base_url", "=", "None", ",", "context", "=", "None", ",", "user", "=", "None", ",", "to", "=", "None", ",", "cc", "=", "None", ",", "bcc", "=", "None", ",", "attachments", "=", "None", ",", "headers", ...
Shortcut to send an email template.
[ "Shortcut", "to", "send", "an", "email", "template", "." ]
train
https://github.com/django-fluent/fluentcms-emailtemplates/blob/29f032dab9f60d05db852d2a1adcbd16e18017d1/fluentcms_emailtemplates/shortcuts.py#L7-L20
wadoon/smvceviz
smvceviz/__init__.py
parse_assign
def parse_assign(string): """Parse an assignment line: >>> parse_assign(" scenario8.Actuator_MagazinVacuumOn = TRUE") ("scenario8.Actuator_MagazinVacuumOn", "TRUE") """ try: a, b = string.split(" = ") return a.strip(), b.strip() except: print("Error with assignment: %s" % string, file=sys.stderr) return None, None
python
def parse_assign(string): """Parse an assignment line: >>> parse_assign(" scenario8.Actuator_MagazinVacuumOn = TRUE") ("scenario8.Actuator_MagazinVacuumOn", "TRUE") """ try: a, b = string.split(" = ") return a.strip(), b.strip() except: print("Error with assignment: %s" % string, file=sys.stderr) return None, None
[ "def", "parse_assign", "(", "string", ")", ":", "try", ":", "a", ",", "b", "=", "string", ".", "split", "(", "\" = \"", ")", "return", "a", ".", "strip", "(", ")", ",", "b", ".", "strip", "(", ")", "except", ":", "print", "(", "\"Error with assignm...
Parse an assignment line: >>> parse_assign(" scenario8.Actuator_MagazinVacuumOn = TRUE") ("scenario8.Actuator_MagazinVacuumOn", "TRUE")
[ "Parse", "an", "assignment", "line", ":" ]
train
https://github.com/wadoon/smvceviz/blob/d8f2b35246d92c8fe1530df9b9ecb10253804d2d/smvceviz/__init__.py#L134-L145
wadoon/smvceviz
smvceviz/__init__.py
Trace.from_file
def from_file(filename): """Read in filename and creates a trace object. :param filename: path to nu(x|s)mv output file :type filename: str :return: """ trace = Trace() reached = False with open(filename) as fp: for line in fp.readlines(): if not reached and line.strip() == "Trace Type: Counterexample": reached = True continue elif reached: trace.parse_line(line) return trace
python
def from_file(filename): """Read in filename and creates a trace object. :param filename: path to nu(x|s)mv output file :type filename: str :return: """ trace = Trace() reached = False with open(filename) as fp: for line in fp.readlines(): if not reached and line.strip() == "Trace Type: Counterexample": reached = True continue elif reached: trace.parse_line(line) return trace
[ "def", "from_file", "(", "filename", ")", ":", "trace", "=", "Trace", "(", ")", "reached", "=", "False", "with", "open", "(", "filename", ")", "as", "fp", ":", "for", "line", "in", "fp", ".", "readlines", "(", ")", ":", "if", "not", "reached", "and...
Read in filename and creates a trace object. :param filename: path to nu(x|s)mv output file :type filename: str :return:
[ "Read", "in", "filename", "and", "creates", "a", "trace", "object", "." ]
train
https://github.com/wadoon/smvceviz/blob/d8f2b35246d92c8fe1530df9b9ecb10253804d2d/smvceviz/__init__.py#L115-L131
jamesabel/pressenter2exit
pressenter2exit/pressenter2exit.py
PressEnter2Exit.run
def run(self): """ run method """ if self.pre_message is None: try: input() # pre message of None causes the input to be silent except EOFError: pass else: try: input(self.pre_message) except EOFError: pass if self.post_message: print(self.post_message) self.exit_time = time.time()
python
def run(self): """ run method """ if self.pre_message is None: try: input() # pre message of None causes the input to be silent except EOFError: pass else: try: input(self.pre_message) except EOFError: pass if self.post_message: print(self.post_message) self.exit_time = time.time()
[ "def", "run", "(", "self", ")", ":", "if", "self", ".", "pre_message", "is", "None", ":", "try", ":", "input", "(", ")", "# pre message of None causes the input to be silent", "except", "EOFError", ":", "pass", "else", ":", "try", ":", "input", "(", "self", ...
run method
[ "run", "method" ]
train
https://github.com/jamesabel/pressenter2exit/blob/bea51dd0dfb2cb61fe9a0e61f0ccb799d9e16dd9/pressenter2exit/pressenter2exit.py#L27-L43
simodalla/pygmount
thirdparty/PyZenity-0.1.7/PyZenity.py
kwargs_helper
def kwargs_helper(kwargs): """This function preprocesses the kwargs dictionary to sanitize it.""" args = [] for param, value in kwargs.items(): param = kw_subst.get(param, param) args.append((param, value)) return args
python
def kwargs_helper(kwargs): """This function preprocesses the kwargs dictionary to sanitize it.""" args = [] for param, value in kwargs.items(): param = kw_subst.get(param, param) args.append((param, value)) return args
[ "def", "kwargs_helper", "(", "kwargs", ")", ":", "args", "=", "[", "]", "for", "param", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "param", "=", "kw_subst", ".", "get", "(", "param", ",", "param", ")", "args", ".", "append", "(", ...
This function preprocesses the kwargs dictionary to sanitize it.
[ "This", "function", "preprocesses", "the", "kwargs", "dictionary", "to", "sanitize", "it", "." ]
train
https://github.com/simodalla/pygmount/blob/8027cfa2ed5fa8e9207d72b6013ecec7fcf2e5f5/thirdparty/PyZenity-0.1.7/PyZenity.py#L74-L81