repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
WhyNotHugo/django-renderpdf
django_renderpdf/views.py
PDFView.render
def render(self, request, template, context): """ Returns a response. By default, this will contain the rendered PDF, but if both ``allow_force_html`` is ``True`` and the querystring ``html=true`` was set it will return a plain HTML. """ if self.allow_force_html and self.request.GET.get('html', False): html = get_template(template).render(context) return HttpResponse(html) else: response = HttpResponse(content_type='application/pdf') if self.prompt_download: response['Content-Disposition'] = 'attachment; filename="{}"' \ .format(self.get_download_name()) helpers.render_pdf( template=template, file_=response, url_fetcher=self.url_fetcher, context=context, ) return response
python
def render(self, request, template, context): """ Returns a response. By default, this will contain the rendered PDF, but if both ``allow_force_html`` is ``True`` and the querystring ``html=true`` was set it will return a plain HTML. """ if self.allow_force_html and self.request.GET.get('html', False): html = get_template(template).render(context) return HttpResponse(html) else: response = HttpResponse(content_type='application/pdf') if self.prompt_download: response['Content-Disposition'] = 'attachment; filename="{}"' \ .format(self.get_download_name()) helpers.render_pdf( template=template, file_=response, url_fetcher=self.url_fetcher, context=context, ) return response
[ "def", "render", "(", "self", ",", "request", ",", "template", ",", "context", ")", ":", "if", "self", ".", "allow_force_html", "and", "self", ".", "request", ".", "GET", ".", "get", "(", "'html'", ",", "False", ")", ":", "html", "=", "get_template", ...
Returns a response. By default, this will contain the rendered PDF, but if both ``allow_force_html`` is ``True`` and the querystring ``html=true`` was set it will return a plain HTML.
[ "Returns", "a", "response", ".", "By", "default", "this", "will", "contain", "the", "rendered", "PDF", "but", "if", "both", "allow_force_html", "is", "True", "and", "the", "querystring", "html", "=", "true", "was", "set", "it", "will", "return", "a", "plai...
56de11326e61d317b5eb08c340790ef9955778e3
https://github.com/WhyNotHugo/django-renderpdf/blob/56de11326e61d317b5eb08c340790ef9955778e3/django_renderpdf/views.py#L88-L108
train
55,200
Chilipp/psy-simple
psy_simple/base.py
TextBase.replace
def replace(self, s, data, attrs=None): """ Replace the attributes of the plotter data in a string %(replace_note)s Parameters ---------- s: str String where the replacements shall be made data: InteractiveBase Data object from which to use the coordinates and insert the coordinate and attribute informations attrs: dict Meta attributes that shall be used for replacements. If None, it will be gained from `data.attrs` Returns ------- str `s` with inserted informations""" # insert labels s = s.format(**self.rc['labels']) # replace attributes attrs = attrs or data.attrs if hasattr(getattr(data, 'psy', None), 'arr_name'): attrs = attrs.copy() attrs['arr_name'] = data.psy.arr_name s = safe_modulo(s, attrs) # replace datetime.datetime like time informations if isinstance(data, InteractiveList): data = data[0] tname = self.any_decoder.get_tname( next(self.plotter.iter_base_variables), data.coords) if tname is not None and tname in data.coords: time = data.coords[tname] if not time.values.ndim: try: # assume a valid datetime.datetime instance s = pd.to_datetime(str(time.values[()])).strftime(s) except ValueError: pass if six.PY2: return s.decode('utf-8') return s
python
def replace(self, s, data, attrs=None): """ Replace the attributes of the plotter data in a string %(replace_note)s Parameters ---------- s: str String where the replacements shall be made data: InteractiveBase Data object from which to use the coordinates and insert the coordinate and attribute informations attrs: dict Meta attributes that shall be used for replacements. If None, it will be gained from `data.attrs` Returns ------- str `s` with inserted informations""" # insert labels s = s.format(**self.rc['labels']) # replace attributes attrs = attrs or data.attrs if hasattr(getattr(data, 'psy', None), 'arr_name'): attrs = attrs.copy() attrs['arr_name'] = data.psy.arr_name s = safe_modulo(s, attrs) # replace datetime.datetime like time informations if isinstance(data, InteractiveList): data = data[0] tname = self.any_decoder.get_tname( next(self.plotter.iter_base_variables), data.coords) if tname is not None and tname in data.coords: time = data.coords[tname] if not time.values.ndim: try: # assume a valid datetime.datetime instance s = pd.to_datetime(str(time.values[()])).strftime(s) except ValueError: pass if six.PY2: return s.decode('utf-8') return s
[ "def", "replace", "(", "self", ",", "s", ",", "data", ",", "attrs", "=", "None", ")", ":", "# insert labels", "s", "=", "s", ".", "format", "(", "*", "*", "self", ".", "rc", "[", "'labels'", "]", ")", "# replace attributes", "attrs", "=", "attrs", ...
Replace the attributes of the plotter data in a string %(replace_note)s Parameters ---------- s: str String where the replacements shall be made data: InteractiveBase Data object from which to use the coordinates and insert the coordinate and attribute informations attrs: dict Meta attributes that shall be used for replacements. If None, it will be gained from `data.attrs` Returns ------- str `s` with inserted informations
[ "Replace", "the", "attributes", "of", "the", "plotter", "data", "in", "a", "string" ]
7d916406a6d3c3c27c0b7102f98fef07a4da0a61
https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/base.py#L88-L131
train
55,201
Chilipp/psy-simple
psy_simple/base.py
TextBase.get_fig_data_attrs
def get_fig_data_attrs(self, delimiter=None): """Join the data attributes with other plotters in the project This method joins the attributes of the :class:`~psyplot.InteractiveBase` instances in the project that draw on the same figure as this instance does. Parameters ---------- delimiter: str Specifies the delimiter with what the attributes are joined. If None, the :attr:`delimiter` attribute of this instance or (if the latter is also None), the rcParams['texts.delimiter'] item is used. Returns ------- dict A dictionary with all the meta attributes joined by the specified `delimiter`""" if self.project is not None: delimiter = next(filter(lambda d: d is not None, [ delimiter, self.delimiter, self.rc['delimiter']])) figs = self.project.figs fig = self.ax.get_figure() if self.plotter._initialized and fig in figs: ret = figs[fig].joined_attrs(delimiter=delimiter, plot_data=True) else: ret = self.get_enhanced_attrs(self.plotter.plot_data) self.logger.debug( 'Can not get the figure attributes because plot has not ' 'yet been initialized!') return ret else: return self.get_enhanced_attrs(self.plotter.plot_data)
python
def get_fig_data_attrs(self, delimiter=None): """Join the data attributes with other plotters in the project This method joins the attributes of the :class:`~psyplot.InteractiveBase` instances in the project that draw on the same figure as this instance does. Parameters ---------- delimiter: str Specifies the delimiter with what the attributes are joined. If None, the :attr:`delimiter` attribute of this instance or (if the latter is also None), the rcParams['texts.delimiter'] item is used. Returns ------- dict A dictionary with all the meta attributes joined by the specified `delimiter`""" if self.project is not None: delimiter = next(filter(lambda d: d is not None, [ delimiter, self.delimiter, self.rc['delimiter']])) figs = self.project.figs fig = self.ax.get_figure() if self.plotter._initialized and fig in figs: ret = figs[fig].joined_attrs(delimiter=delimiter, plot_data=True) else: ret = self.get_enhanced_attrs(self.plotter.plot_data) self.logger.debug( 'Can not get the figure attributes because plot has not ' 'yet been initialized!') return ret else: return self.get_enhanced_attrs(self.plotter.plot_data)
[ "def", "get_fig_data_attrs", "(", "self", ",", "delimiter", "=", "None", ")", ":", "if", "self", ".", "project", "is", "not", "None", ":", "delimiter", "=", "next", "(", "filter", "(", "lambda", "d", ":", "d", "is", "not", "None", ",", "[", "delimite...
Join the data attributes with other plotters in the project This method joins the attributes of the :class:`~psyplot.InteractiveBase` instances in the project that draw on the same figure as this instance does. Parameters ---------- delimiter: str Specifies the delimiter with what the attributes are joined. If None, the :attr:`delimiter` attribute of this instance or (if the latter is also None), the rcParams['texts.delimiter'] item is used. Returns ------- dict A dictionary with all the meta attributes joined by the specified `delimiter`
[ "Join", "the", "data", "attributes", "with", "other", "plotters", "in", "the", "project" ]
7d916406a6d3c3c27c0b7102f98fef07a4da0a61
https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/base.py#L133-L167
train
55,202
Chilipp/psy-simple
psy_simple/base.py
TextBase.get_fmt_widget
def get_fmt_widget(self, parent, project): """Create a combobox with the attributes""" from psy_simple.widgets.texts import LabelWidget return LabelWidget(parent, self, project)
python
def get_fmt_widget(self, parent, project): """Create a combobox with the attributes""" from psy_simple.widgets.texts import LabelWidget return LabelWidget(parent, self, project)
[ "def", "get_fmt_widget", "(", "self", ",", "parent", ",", "project", ")", ":", "from", "psy_simple", ".", "widgets", ".", "texts", "import", "LabelWidget", "return", "LabelWidget", "(", "parent", ",", "self", ",", "project", ")" ]
Create a combobox with the attributes
[ "Create", "a", "combobox", "with", "the", "attributes" ]
7d916406a6d3c3c27c0b7102f98fef07a4da0a61
https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/base.py#L177-L180
train
55,203
Chilipp/psy-simple
psy_simple/base.py
Figtitle.clear_other_texts
def clear_other_texts(self, remove=False): """Make sure that no other text is a the same position as this one This method clears all text instances in the figure that are at the same position as the :attr:`_text` attribute Parameters ---------- remove: bool If True, the Text instances are permanently deleted from the figure, otherwise there text is simply set to ''""" fig = self.ax.get_figure() # don't do anything if our figtitle is the only Text instance if len(fig.texts) == 1: return for i, text in enumerate(fig.texts): if text == self._text: continue if text.get_position() == self._text.get_position(): if not remove: text.set_text('') else: del fig[i]
python
def clear_other_texts(self, remove=False): """Make sure that no other text is a the same position as this one This method clears all text instances in the figure that are at the same position as the :attr:`_text` attribute Parameters ---------- remove: bool If True, the Text instances are permanently deleted from the figure, otherwise there text is simply set to ''""" fig = self.ax.get_figure() # don't do anything if our figtitle is the only Text instance if len(fig.texts) == 1: return for i, text in enumerate(fig.texts): if text == self._text: continue if text.get_position() == self._text.get_position(): if not remove: text.set_text('') else: del fig[i]
[ "def", "clear_other_texts", "(", "self", ",", "remove", "=", "False", ")", ":", "fig", "=", "self", ".", "ax", ".", "get_figure", "(", ")", "# don't do anything if our figtitle is the only Text instance", "if", "len", "(", "fig", ".", "texts", ")", "==", "1", ...
Make sure that no other text is a the same position as this one This method clears all text instances in the figure that are at the same position as the :attr:`_text` attribute Parameters ---------- remove: bool If True, the Text instances are permanently deleted from the figure, otherwise there text is simply set to
[ "Make", "sure", "that", "no", "other", "text", "is", "a", "the", "same", "position", "as", "this", "one" ]
7d916406a6d3c3c27c0b7102f98fef07a4da0a61
https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/base.py#L521-L543
train
55,204
Chilipp/psy-simple
psy_simple/base.py
Text.transform
def transform(self): """Dictionary containing the relevant transformations""" ax = self.ax return {'axes': ax.transAxes, 'fig': ax.get_figure().transFigure, 'data': ax.transData}
python
def transform(self): """Dictionary containing the relevant transformations""" ax = self.ax return {'axes': ax.transAxes, 'fig': ax.get_figure().transFigure, 'data': ax.transData}
[ "def", "transform", "(", "self", ")", ":", "ax", "=", "self", ".", "ax", "return", "{", "'axes'", ":", "ax", ".", "transAxes", ",", "'fig'", ":", "ax", ".", "get_figure", "(", ")", ".", "transFigure", ",", "'data'", ":", "ax", ".", "transData", "}"...
Dictionary containing the relevant transformations
[ "Dictionary", "containing", "the", "relevant", "transformations" ]
7d916406a6d3c3c27c0b7102f98fef07a4da0a61
https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/base.py#L578-L583
train
55,205
Chilipp/psy-simple
psy_simple/base.py
Text._remove_texttuple
def _remove_texttuple(self, pos): """Remove a texttuple from the value in the plotter Parameters ---------- pos: tuple (x, y, cs) x and y are the x- and y-positions and cs the coordinate system""" for i, (old_x, old_y, s, old_cs, d) in enumerate(self.value): if (old_x, old_y, old_cs) == pos: self.value.pop(i) return raise ValueError("{0} not found!".format(pos))
python
def _remove_texttuple(self, pos): """Remove a texttuple from the value in the plotter Parameters ---------- pos: tuple (x, y, cs) x and y are the x- and y-positions and cs the coordinate system""" for i, (old_x, old_y, s, old_cs, d) in enumerate(self.value): if (old_x, old_y, old_cs) == pos: self.value.pop(i) return raise ValueError("{0} not found!".format(pos))
[ "def", "_remove_texttuple", "(", "self", ",", "pos", ")", ":", "for", "i", ",", "(", "old_x", ",", "old_y", ",", "s", ",", "old_cs", ",", "d", ")", "in", "enumerate", "(", "self", ".", "value", ")", ":", "if", "(", "old_x", ",", "old_y", ",", "...
Remove a texttuple from the value in the plotter Parameters ---------- pos: tuple (x, y, cs) x and y are the x- and y-positions and cs the coordinate system
[ "Remove", "a", "texttuple", "from", "the", "value", "in", "the", "plotter" ]
7d916406a6d3c3c27c0b7102f98fef07a4da0a61
https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/base.py#L592-L603
train
55,206
Chilipp/psy-simple
psy_simple/base.py
Text._update_texttuple
def _update_texttuple(self, x, y, s, cs, d): """Update the text tuple at `x` and `y` with the given `s` and `d`""" pos = (x, y, cs) for i, (old_x, old_y, old_s, old_cs, old_d) in enumerate(self.value): if (old_x, old_y, old_cs) == pos: self.value[i] = (old_x, old_y, s, old_cs, d) return raise ValueError("No text tuple found at {0}!".format(pos))
python
def _update_texttuple(self, x, y, s, cs, d): """Update the text tuple at `x` and `y` with the given `s` and `d`""" pos = (x, y, cs) for i, (old_x, old_y, old_s, old_cs, old_d) in enumerate(self.value): if (old_x, old_y, old_cs) == pos: self.value[i] = (old_x, old_y, s, old_cs, d) return raise ValueError("No text tuple found at {0}!".format(pos))
[ "def", "_update_texttuple", "(", "self", ",", "x", ",", "y", ",", "s", ",", "cs", ",", "d", ")", ":", "pos", "=", "(", "x", ",", "y", ",", "cs", ")", "for", "i", ",", "(", "old_x", ",", "old_y", ",", "old_s", ",", "old_cs", ",", "old_d", ")...
Update the text tuple at `x` and `y` with the given `s` and `d`
[ "Update", "the", "text", "tuple", "at", "x", "and", "y", "with", "the", "given", "s", "and", "d" ]
7d916406a6d3c3c27c0b7102f98fef07a4da0a61
https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/base.py#L605-L612
train
55,207
Chilipp/psy-simple
psy_simple/base.py
Text.share
def share(self, fmto, **kwargs): """Share the settings of this formatoption with other data objects Parameters ---------- fmto: Formatoption The :class:`Formatoption` instance to share the attributes with ``**kwargs`` Any other keyword argument that shall be passed to the update method of `fmto` Notes ----- The Text formatoption sets the 'texts_to_remove' keyword to the :attr:`_texts_to_remove` attribute of this instance (if not already specified in ``**kwargs``""" kwargs.setdefault('texts_to_remove', self._texts_to_remove) super(Text, self).share(fmto, **kwargs)
python
def share(self, fmto, **kwargs): """Share the settings of this formatoption with other data objects Parameters ---------- fmto: Formatoption The :class:`Formatoption` instance to share the attributes with ``**kwargs`` Any other keyword argument that shall be passed to the update method of `fmto` Notes ----- The Text formatoption sets the 'texts_to_remove' keyword to the :attr:`_texts_to_remove` attribute of this instance (if not already specified in ``**kwargs``""" kwargs.setdefault('texts_to_remove', self._texts_to_remove) super(Text, self).share(fmto, **kwargs)
[ "def", "share", "(", "self", ",", "fmto", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'texts_to_remove'", ",", "self", ".", "_texts_to_remove", ")", "super", "(", "Text", ",", "self", ")", ".", "share", "(", "fmto", ",", "*"...
Share the settings of this formatoption with other data objects Parameters ---------- fmto: Formatoption The :class:`Formatoption` instance to share the attributes with ``**kwargs`` Any other keyword argument that shall be passed to the update method of `fmto` Notes ----- The Text formatoption sets the 'texts_to_remove' keyword to the :attr:`_texts_to_remove` attribute of this instance (if not already specified in ``**kwargs``
[ "Share", "the", "settings", "of", "this", "formatoption", "with", "other", "data", "objects" ]
7d916406a6d3c3c27c0b7102f98fef07a4da0a61
https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/base.py#L670-L687
train
55,208
bryanwweber/thermohw
thermohw/pymarkdown.py
PyMarkdownPreprocessor.preprocess_cell
def preprocess_cell( self, cell: "NotebookNode", resources: dict, index: int ) -> Tuple["NotebookNode", dict]: """Preprocess cell. Parameters ---------- cell : NotebookNode cell Notebook cell being processed resources : dictionary Additional resources used in the conversion process. Allows preprocessors to pass variables into the Jinja engine. cell_index : int Index of the cell being processed (see base.py) """ if cell.cell_type == "markdown": variables = cell["metadata"].get("variables", {}) if len(variables) > 0: cell.source = self.replace_variables(cell.source, variables) if resources.get("delete_pymarkdown", False): del cell.metadata["variables"] return cell, resources
python
def preprocess_cell( self, cell: "NotebookNode", resources: dict, index: int ) -> Tuple["NotebookNode", dict]: """Preprocess cell. Parameters ---------- cell : NotebookNode cell Notebook cell being processed resources : dictionary Additional resources used in the conversion process. Allows preprocessors to pass variables into the Jinja engine. cell_index : int Index of the cell being processed (see base.py) """ if cell.cell_type == "markdown": variables = cell["metadata"].get("variables", {}) if len(variables) > 0: cell.source = self.replace_variables(cell.source, variables) if resources.get("delete_pymarkdown", False): del cell.metadata["variables"] return cell, resources
[ "def", "preprocess_cell", "(", "self", ",", "cell", ":", "\"NotebookNode\"", ",", "resources", ":", "dict", ",", "index", ":", "int", ")", "->", "Tuple", "[", "\"NotebookNode\"", ",", "dict", "]", ":", "if", "cell", ".", "cell_type", "==", "\"markdown\"", ...
Preprocess cell. Parameters ---------- cell : NotebookNode cell Notebook cell being processed resources : dictionary Additional resources used in the conversion process. Allows preprocessors to pass variables into the Jinja engine. cell_index : int Index of the cell being processed (see base.py)
[ "Preprocess", "cell", "." ]
b6be276c14f8adf6ae23f5498065de74f868ccaa
https://github.com/bryanwweber/thermohw/blob/b6be276c14f8adf6ae23f5498065de74f868ccaa/thermohw/pymarkdown.py#L74-L96
train
55,209
oxalorg/dystic
dystic/indexer.py
Indexer.index_dir
def index_dir(self, folder): """ Creates a nested dictionary that represents the folder structure of folder. Also extracts meta data from all markdown posts and adds to the dictionary. """ folder_path = folder print('Indexing folder: ' + folder_path) nested_dir = {} folder = folder_path.rstrip(os.sep) start = folder.rfind(os.sep) + 1 for root, dirs, files in os.walk(folder): folders = root[start:].split(os.sep) # subdir = dict.fromkeys(files) subdir = {} for f in files: # Create an entry for every markdown file if os.path.splitext(f)[1] == '.md': with open(os.path.abspath(os.path.join(root, f)), encoding='utf-8') as fp: try: _, meta = self.mrk.extract_meta(fp.read()) except: print("Skipping indexing " + f +"; Could not parse metadata") meta = {'title': f} pass # Value of the entry (the key) is it's metadata subdir[f] = meta parent = nested_dir for fold in folders[:-1]: parent = parent.get(fold) # Attach the config of all children nodes onto the parent parent[folders[-1]] = subdir return nested_dir
python
def index_dir(self, folder): """ Creates a nested dictionary that represents the folder structure of folder. Also extracts meta data from all markdown posts and adds to the dictionary. """ folder_path = folder print('Indexing folder: ' + folder_path) nested_dir = {} folder = folder_path.rstrip(os.sep) start = folder.rfind(os.sep) + 1 for root, dirs, files in os.walk(folder): folders = root[start:].split(os.sep) # subdir = dict.fromkeys(files) subdir = {} for f in files: # Create an entry for every markdown file if os.path.splitext(f)[1] == '.md': with open(os.path.abspath(os.path.join(root, f)), encoding='utf-8') as fp: try: _, meta = self.mrk.extract_meta(fp.read()) except: print("Skipping indexing " + f +"; Could not parse metadata") meta = {'title': f} pass # Value of the entry (the key) is it's metadata subdir[f] = meta parent = nested_dir for fold in folders[:-1]: parent = parent.get(fold) # Attach the config of all children nodes onto the parent parent[folders[-1]] = subdir return nested_dir
[ "def", "index_dir", "(", "self", ",", "folder", ")", ":", "folder_path", "=", "folder", "print", "(", "'Indexing folder: '", "+", "folder_path", ")", "nested_dir", "=", "{", "}", "folder", "=", "folder_path", ".", "rstrip", "(", "os", ".", "sep", ")", "s...
Creates a nested dictionary that represents the folder structure of folder. Also extracts meta data from all markdown posts and adds to the dictionary.
[ "Creates", "a", "nested", "dictionary", "that", "represents", "the", "folder", "structure", "of", "folder", ".", "Also", "extracts", "meta", "data", "from", "all", "markdown", "posts", "and", "adds", "to", "the", "dictionary", "." ]
6f5a449158ec12fc1c9cc25d85e2f8adc27885db
https://github.com/oxalorg/dystic/blob/6f5a449158ec12fc1c9cc25d85e2f8adc27885db/dystic/indexer.py#L17-L48
train
55,210
mdickinson/refcycle
refcycle/creators.py
cycles_created_by
def cycles_created_by(callable): """ Return graph of cyclic garbage created by the given callable. Return an :class:`~refcycle.object_graph.ObjectGraph` representing those objects generated by the given callable that can't be collected by Python's usual reference-count based garbage collection. This includes objects that will eventually be collected by the cyclic garbage collector, as well as genuinely unreachable objects that will never be collected. `callable` should be a callable that takes no arguments; its return value (if any) will be ignored. """ with restore_gc_state(): gc.disable() gc.collect() gc.set_debug(gc.DEBUG_SAVEALL) callable() new_object_count = gc.collect() if new_object_count: objects = gc.garbage[-new_object_count:] del gc.garbage[-new_object_count:] else: objects = [] return ObjectGraph(objects)
python
def cycles_created_by(callable): """ Return graph of cyclic garbage created by the given callable. Return an :class:`~refcycle.object_graph.ObjectGraph` representing those objects generated by the given callable that can't be collected by Python's usual reference-count based garbage collection. This includes objects that will eventually be collected by the cyclic garbage collector, as well as genuinely unreachable objects that will never be collected. `callable` should be a callable that takes no arguments; its return value (if any) will be ignored. """ with restore_gc_state(): gc.disable() gc.collect() gc.set_debug(gc.DEBUG_SAVEALL) callable() new_object_count = gc.collect() if new_object_count: objects = gc.garbage[-new_object_count:] del gc.garbage[-new_object_count:] else: objects = [] return ObjectGraph(objects)
[ "def", "cycles_created_by", "(", "callable", ")", ":", "with", "restore_gc_state", "(", ")", ":", "gc", ".", "disable", "(", ")", "gc", ".", "collect", "(", ")", "gc", ".", "set_debug", "(", "gc", ".", "DEBUG_SAVEALL", ")", "callable", "(", ")", "new_o...
Return graph of cyclic garbage created by the given callable. Return an :class:`~refcycle.object_graph.ObjectGraph` representing those objects generated by the given callable that can't be collected by Python's usual reference-count based garbage collection. This includes objects that will eventually be collected by the cyclic garbage collector, as well as genuinely unreachable objects that will never be collected. `callable` should be a callable that takes no arguments; its return value (if any) will be ignored.
[ "Return", "graph", "of", "cyclic", "garbage", "created", "by", "the", "given", "callable", "." ]
627fad74c74efc601209c96405f8118cd99b2241
https://github.com/mdickinson/refcycle/blob/627fad74c74efc601209c96405f8118cd99b2241/refcycle/creators.py#L26-L53
train
55,211
mdickinson/refcycle
refcycle/creators.py
snapshot
def snapshot(): """Return the graph of all currently gc-tracked objects. Excludes the returned :class:`~refcycle.object_graph.ObjectGraph` and objects owned by it. Note that a subsequent call to :func:`~refcycle.creators.snapshot` will capture all of the objects owned by this snapshot. The :meth:`~refcycle.object_graph.ObjectGraph.owned_objects` method may be helpful when excluding these objects from consideration. """ all_objects = gc.get_objects() this_frame = inspect.currentframe() selected_objects = [] for obj in all_objects: if obj is not this_frame: selected_objects.append(obj) graph = ObjectGraph(selected_objects) del this_frame, all_objects, selected_objects, obj return graph
python
def snapshot(): """Return the graph of all currently gc-tracked objects. Excludes the returned :class:`~refcycle.object_graph.ObjectGraph` and objects owned by it. Note that a subsequent call to :func:`~refcycle.creators.snapshot` will capture all of the objects owned by this snapshot. The :meth:`~refcycle.object_graph.ObjectGraph.owned_objects` method may be helpful when excluding these objects from consideration. """ all_objects = gc.get_objects() this_frame = inspect.currentframe() selected_objects = [] for obj in all_objects: if obj is not this_frame: selected_objects.append(obj) graph = ObjectGraph(selected_objects) del this_frame, all_objects, selected_objects, obj return graph
[ "def", "snapshot", "(", ")", ":", "all_objects", "=", "gc", ".", "get_objects", "(", ")", "this_frame", "=", "inspect", ".", "currentframe", "(", ")", "selected_objects", "=", "[", "]", "for", "obj", "in", "all_objects", ":", "if", "obj", "is", "not", ...
Return the graph of all currently gc-tracked objects. Excludes the returned :class:`~refcycle.object_graph.ObjectGraph` and objects owned by it. Note that a subsequent call to :func:`~refcycle.creators.snapshot` will capture all of the objects owned by this snapshot. The :meth:`~refcycle.object_graph.ObjectGraph.owned_objects` method may be helpful when excluding these objects from consideration.
[ "Return", "the", "graph", "of", "all", "currently", "gc", "-", "tracked", "objects", "." ]
627fad74c74efc601209c96405f8118cd99b2241
https://github.com/mdickinson/refcycle/blob/627fad74c74efc601209c96405f8118cd99b2241/refcycle/creators.py#L102-L122
train
55,212
moccu/django-markymark
markymark/extensions/base.py
MarkymarkExtension.extendMarkdown
def extendMarkdown(self, md, md_globals): """ Every extension requires a extendMarkdown method to tell the markdown renderer how use the extension. """ md.registerExtension(self) for processor in (self.preprocessors or []): md.preprocessors.add(processor.__name__.lower(), processor(md), '_end') for pattern in (self.inlinepatterns or []): md.inlinePatterns.add(pattern.__name__.lower(), pattern(md), '_end') for processor in (self.postprocessors or []): md.postprocessors.add(processor.__name__.lower(), processor(md), '_end')
python
def extendMarkdown(self, md, md_globals): """ Every extension requires a extendMarkdown method to tell the markdown renderer how use the extension. """ md.registerExtension(self) for processor in (self.preprocessors or []): md.preprocessors.add(processor.__name__.lower(), processor(md), '_end') for pattern in (self.inlinepatterns or []): md.inlinePatterns.add(pattern.__name__.lower(), pattern(md), '_end') for processor in (self.postprocessors or []): md.postprocessors.add(processor.__name__.lower(), processor(md), '_end')
[ "def", "extendMarkdown", "(", "self", ",", "md", ",", "md_globals", ")", ":", "md", ".", "registerExtension", "(", "self", ")", "for", "processor", "in", "(", "self", ".", "preprocessors", "or", "[", "]", ")", ":", "md", ".", "preprocessors", ".", "add...
Every extension requires a extendMarkdown method to tell the markdown renderer how use the extension.
[ "Every", "extension", "requires", "a", "extendMarkdown", "method", "to", "tell", "the", "markdown", "renderer", "how", "use", "the", "extension", "." ]
c1bf69f439981d6295e5b4d13c26dadf3dba2e9d
https://github.com/moccu/django-markymark/blob/c1bf69f439981d6295e5b4d13c26dadf3dba2e9d/markymark/extensions/base.py#L15-L29
train
55,213
Julian/L
l/cli.py
run
def run( paths, output=_I_STILL_HATE_EVERYTHING, recurse=core.flat, sort_by=None, ls=core.ls, stdout=stdout, ): """ Project-oriented directory and file information lister. """ if output is _I_STILL_HATE_EVERYTHING: output = core.columnized if stdout.isatty() else core.one_per_line if sort_by is None: if output == core.as_tree: def sort_by(thing): return ( thing.parent(), thing.basename().lstrip(string.punctuation).lower(), ) else: def sort_by(thing): return thing def _sort_by(thing): return not getattr(thing, "_always_sorts_first", False), sort_by(thing) contents = [ path_and_children for path in paths or (project.from_path(FilePath(".")),) for path_and_children in recurse(path=path, ls=ls) ] for line in output(contents, sort_by=_sort_by): stdout.write(line) stdout.write("\n")
python
def run( paths, output=_I_STILL_HATE_EVERYTHING, recurse=core.flat, sort_by=None, ls=core.ls, stdout=stdout, ): """ Project-oriented directory and file information lister. """ if output is _I_STILL_HATE_EVERYTHING: output = core.columnized if stdout.isatty() else core.one_per_line if sort_by is None: if output == core.as_tree: def sort_by(thing): return ( thing.parent(), thing.basename().lstrip(string.punctuation).lower(), ) else: def sort_by(thing): return thing def _sort_by(thing): return not getattr(thing, "_always_sorts_first", False), sort_by(thing) contents = [ path_and_children for path in paths or (project.from_path(FilePath(".")),) for path_and_children in recurse(path=path, ls=ls) ] for line in output(contents, sort_by=_sort_by): stdout.write(line) stdout.write("\n")
[ "def", "run", "(", "paths", ",", "output", "=", "_I_STILL_HATE_EVERYTHING", ",", "recurse", "=", "core", ".", "flat", ",", "sort_by", "=", "None", ",", "ls", "=", "core", ".", "ls", ",", "stdout", "=", "stdout", ",", ")", ":", "if", "output", "is", ...
Project-oriented directory and file information lister.
[ "Project", "-", "oriented", "directory", "and", "file", "information", "lister", "." ]
946b5378466ec9fa8587bd2187fc632f46d6efdf
https://github.com/Julian/L/blob/946b5378466ec9fa8587bd2187fc632f46d6efdf/l/cli.py#L24-L60
train
55,214
unixorn/logrus
logrus/utils.py
getCustomLogger
def getCustomLogger(name, logLevel, logFormat='%(asctime)s %(levelname)-9s:%(name)s:%(module)s:%(funcName)s: %(message)s'): ''' Set up logging :param str name: What log level to set :param str logLevel: What log level to use :param str logFormat: Format string for logging :rtype: logger ''' assert isinstance(logFormat, basestring), ("logFormat must be a string but is %r" % logFormat) assert isinstance(logLevel, basestring), ("logLevel must be a string but is %r" % logLevel) assert isinstance(name, basestring), ("name must be a string but is %r" % name) validLogLevels = ['CRITICAL', 'DEBUG', 'ERROR', 'INFO', 'WARNING'] if not logLevel: logLevel = 'DEBUG' # If they don't specify a valid log level, err on the side of verbosity if logLevel.upper() not in validLogLevels: logLevel = 'DEBUG' numericLevel = getattr(logging, logLevel.upper(), None) if not isinstance(numericLevel, int): raise ValueError("Invalid log level: %s" % logLevel) logging.basicConfig(level=numericLevel, format=logFormat) logger = logging.getLogger(name) return logger
python
def getCustomLogger(name, logLevel, logFormat='%(asctime)s %(levelname)-9s:%(name)s:%(module)s:%(funcName)s: %(message)s'): ''' Set up logging :param str name: What log level to set :param str logLevel: What log level to use :param str logFormat: Format string for logging :rtype: logger ''' assert isinstance(logFormat, basestring), ("logFormat must be a string but is %r" % logFormat) assert isinstance(logLevel, basestring), ("logLevel must be a string but is %r" % logLevel) assert isinstance(name, basestring), ("name must be a string but is %r" % name) validLogLevels = ['CRITICAL', 'DEBUG', 'ERROR', 'INFO', 'WARNING'] if not logLevel: logLevel = 'DEBUG' # If they don't specify a valid log level, err on the side of verbosity if logLevel.upper() not in validLogLevels: logLevel = 'DEBUG' numericLevel = getattr(logging, logLevel.upper(), None) if not isinstance(numericLevel, int): raise ValueError("Invalid log level: %s" % logLevel) logging.basicConfig(level=numericLevel, format=logFormat) logger = logging.getLogger(name) return logger
[ "def", "getCustomLogger", "(", "name", ",", "logLevel", ",", "logFormat", "=", "'%(asctime)s %(levelname)-9s:%(name)s:%(module)s:%(funcName)s: %(message)s'", ")", ":", "assert", "isinstance", "(", "logFormat", ",", "basestring", ")", ",", "(", "\"logFormat must be a string ...
Set up logging :param str name: What log level to set :param str logLevel: What log level to use :param str logFormat: Format string for logging :rtype: logger
[ "Set", "up", "logging" ]
d1af28639fd42968acc257476d526d9bbe57719f
https://github.com/unixorn/logrus/blob/d1af28639fd42968acc257476d526d9bbe57719f/logrus/utils.py#L27-L55
train
55,215
unixorn/logrus
logrus/utils.py
mkdir_p
def mkdir_p(path): ''' Mimic `mkdir -p` since os module doesn't provide one. :param str path: directory to create ''' assert isinstance(path, basestring), ("path must be a string but is %r" % path) try: os.makedirs(path) except OSError as exception: if exception.errno != errno.EEXIST: raise
python
def mkdir_p(path): ''' Mimic `mkdir -p` since os module doesn't provide one. :param str path: directory to create ''' assert isinstance(path, basestring), ("path must be a string but is %r" % path) try: os.makedirs(path) except OSError as exception: if exception.errno != errno.EEXIST: raise
[ "def", "mkdir_p", "(", "path", ")", ":", "assert", "isinstance", "(", "path", ",", "basestring", ")", ",", "(", "\"path must be a string but is %r\"", "%", "path", ")", "try", ":", "os", ".", "makedirs", "(", "path", ")", "except", "OSError", "as", "except...
Mimic `mkdir -p` since os module doesn't provide one. :param str path: directory to create
[ "Mimic", "mkdir", "-", "p", "since", "os", "module", "doesn", "t", "provide", "one", "." ]
d1af28639fd42968acc257476d526d9bbe57719f
https://github.com/unixorn/logrus/blob/d1af28639fd42968acc257476d526d9bbe57719f/logrus/utils.py#L58-L69
train
55,216
Cadasta/cadasta-workertoolbox
cadasta/workertoolbox/setup.py
setup_exchanges
def setup_exchanges(app): """ Setup result exchange to route all tasks to platform queue. """ with app.producer_or_acquire() as P: # Ensure all queues are noticed and configured with their # appropriate exchange. for q in app.amqp.queues.values(): P.maybe_declare(q)
python
def setup_exchanges(app): """ Setup result exchange to route all tasks to platform queue. """ with app.producer_or_acquire() as P: # Ensure all queues are noticed and configured with their # appropriate exchange. for q in app.amqp.queues.values(): P.maybe_declare(q)
[ "def", "setup_exchanges", "(", "app", ")", ":", "with", "app", ".", "producer_or_acquire", "(", ")", "as", "P", ":", "# Ensure all queues are noticed and configured with their", "# appropriate exchange.", "for", "q", "in", "app", ".", "amqp", ".", "queues", ".", "...
Setup result exchange to route all tasks to platform queue.
[ "Setup", "result", "exchange", "to", "route", "all", "tasks", "to", "platform", "queue", "." ]
e17cf376538cee0b32c7a21afd5319e3549b954f
https://github.com/Cadasta/cadasta-workertoolbox/blob/e17cf376538cee0b32c7a21afd5319e3549b954f/cadasta/workertoolbox/setup.py#L16-L24
train
55,217
Cadasta/cadasta-workertoolbox
cadasta/workertoolbox/setup.py
setup_app
def setup_app(app, throw=True): """ Ensure application is set up to expected configuration. This function is typically triggered by the worker_init signal, however it must be called manually by codebases that are run only as task producers or from within a Python shell. """ success = True try: for func in SETUP_FUNCS: try: func(app) except Exception: success = False if throw: raise else: msg = "Failed to run setup function %r(app)" logger.exception(msg, func.__name__) finally: setattr(app, 'is_set_up', success)
python
def setup_app(app, throw=True): """ Ensure application is set up to expected configuration. This function is typically triggered by the worker_init signal, however it must be called manually by codebases that are run only as task producers or from within a Python shell. """ success = True try: for func in SETUP_FUNCS: try: func(app) except Exception: success = False if throw: raise else: msg = "Failed to run setup function %r(app)" logger.exception(msg, func.__name__) finally: setattr(app, 'is_set_up', success)
[ "def", "setup_app", "(", "app", ",", "throw", "=", "True", ")", ":", "success", "=", "True", "try", ":", "for", "func", "in", "SETUP_FUNCS", ":", "try", ":", "func", "(", "app", ")", "except", "Exception", ":", "success", "=", "False", "if", "throw",...
Ensure application is set up to expected configuration. This function is typically triggered by the worker_init signal, however it must be called manually by codebases that are run only as task producers or from within a Python shell.
[ "Ensure", "application", "is", "set", "up", "to", "expected", "configuration", ".", "This", "function", "is", "typically", "triggered", "by", "the", "worker_init", "signal", "however", "it", "must", "be", "called", "manually", "by", "codebases", "that", "are", ...
e17cf376538cee0b32c7a21afd5319e3549b954f
https://github.com/Cadasta/cadasta-workertoolbox/blob/e17cf376538cee0b32c7a21afd5319e3549b954f/cadasta/workertoolbox/setup.py#L33-L53
train
55,218
ofek/depq
depq/depq.py
DEPQ._poplast
def _poplast(self): """For avoiding lock during inserting to keep maxlen""" try: tup = self.data.pop() except IndexError as ex: ex.args = ('DEPQ is already empty',) raise self_items = self.items try: self_items[tup[0]] -= 1 if self_items[tup[0]] == 0: del self_items[tup[0]] except TypeError: r = repr(tup[0]) self_items[r] -= 1 if self_items[r] == 0: del self_items[r] return tup
python
def _poplast(self): """For avoiding lock during inserting to keep maxlen""" try: tup = self.data.pop() except IndexError as ex: ex.args = ('DEPQ is already empty',) raise self_items = self.items try: self_items[tup[0]] -= 1 if self_items[tup[0]] == 0: del self_items[tup[0]] except TypeError: r = repr(tup[0]) self_items[r] -= 1 if self_items[r] == 0: del self_items[r] return tup
[ "def", "_poplast", "(", "self", ")", ":", "try", ":", "tup", "=", "self", ".", "data", ".", "pop", "(", ")", "except", "IndexError", "as", "ex", ":", "ex", ".", "args", "=", "(", "'DEPQ is already empty'", ",", ")", "raise", "self_items", "=", "self"...
For avoiding lock during inserting to keep maxlen
[ "For", "avoiding", "lock", "during", "inserting", "to", "keep", "maxlen" ]
370e3ad503d3e9cedc3c49dc64add393ba945764
https://github.com/ofek/depq/blob/370e3ad503d3e9cedc3c49dc64add393ba945764/depq/depq.py#L188-L209
train
55,219
memphis-iis/GLUDB
gludb/data.py
DatabaseEnabled
def DatabaseEnabled(cls): """Given persistence methods to classes with this annotation. All this really does is add some functions that forward to the mapped database class. """ if not issubclass(cls, Storable): raise ValueError( "%s is not a subclass of gludb.datab.Storage" % repr(cls) ) cls.ensure_table = classmethod(_ensure_table) cls.find_one = classmethod(_find_one) cls.find_all = classmethod(_find_all) cls.find_by_index = classmethod(_find_by_index) cls.save = _save cls.delete = _delete return cls
python
def DatabaseEnabled(cls): """Given persistence methods to classes with this annotation. All this really does is add some functions that forward to the mapped database class. """ if not issubclass(cls, Storable): raise ValueError( "%s is not a subclass of gludb.datab.Storage" % repr(cls) ) cls.ensure_table = classmethod(_ensure_table) cls.find_one = classmethod(_find_one) cls.find_all = classmethod(_find_all) cls.find_by_index = classmethod(_find_by_index) cls.save = _save cls.delete = _delete return cls
[ "def", "DatabaseEnabled", "(", "cls", ")", ":", "if", "not", "issubclass", "(", "cls", ",", "Storable", ")", ":", "raise", "ValueError", "(", "\"%s is not a subclass of gludb.datab.Storage\"", "%", "repr", "(", "cls", ")", ")", "cls", ".", "ensure_table", "=",...
Given persistence methods to classes with this annotation. All this really does is add some functions that forward to the mapped database class.
[ "Given", "persistence", "methods", "to", "classes", "with", "this", "annotation", "." ]
25692528ff6fe8184a3570f61f31f1a90088a388
https://github.com/memphis-iis/GLUDB/blob/25692528ff6fe8184a3570f61f31f1a90088a388/gludb/data.py#L145-L163
train
55,220
studionow/pybrightcove
pybrightcove/playlist.py
Playlist._find_playlist
def _find_playlist(self): """ Internal method to populate the object given the ``id`` or ``reference_id`` that has been set in the constructor. """ data = None if self.id: data = self.connection.get_item( 'find_playlist_by_id', playlist_id=self.id) elif self.reference_id: data = self.connection.get_item( 'find_playlist_by_reference_id', reference_id=self.reference_id) if data: self._load(data)
python
def _find_playlist(self): """ Internal method to populate the object given the ``id`` or ``reference_id`` that has been set in the constructor. """ data = None if self.id: data = self.connection.get_item( 'find_playlist_by_id', playlist_id=self.id) elif self.reference_id: data = self.connection.get_item( 'find_playlist_by_reference_id', reference_id=self.reference_id) if data: self._load(data)
[ "def", "_find_playlist", "(", "self", ")", ":", "data", "=", "None", "if", "self", ".", "id", ":", "data", "=", "self", ".", "connection", ".", "get_item", "(", "'find_playlist_by_id'", ",", "playlist_id", "=", "self", ".", "id", ")", "elif", "self", "...
Internal method to populate the object given the ``id`` or ``reference_id`` that has been set in the constructor.
[ "Internal", "method", "to", "populate", "the", "object", "given", "the", "id", "or", "reference_id", "that", "has", "been", "set", "in", "the", "constructor", "." ]
19c946b689a80156e070fe9bc35589c4b768e614
https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/playlist.py#L93-L108
train
55,221
studionow/pybrightcove
pybrightcove/playlist.py
Playlist._to_dict
def _to_dict(self): """ Internal method that serializes object into a dictionary. """ data = { 'name': self.name, 'referenceId': self.reference_id, 'shortDescription': self.short_description, 'playlistType': self.type, 'id': self.id} if self.videos: for video in self.videos: if video.id not in self.video_ids: self.video_ids.append(video.id) if self.video_ids: data['videoIds'] = self.video_ids [data.pop(key) for key in data.keys() if data[key] == None] return data
python
def _to_dict(self): """ Internal method that serializes object into a dictionary. """ data = { 'name': self.name, 'referenceId': self.reference_id, 'shortDescription': self.short_description, 'playlistType': self.type, 'id': self.id} if self.videos: for video in self.videos: if video.id not in self.video_ids: self.video_ids.append(video.id) if self.video_ids: data['videoIds'] = self.video_ids [data.pop(key) for key in data.keys() if data[key] == None] return data
[ "def", "_to_dict", "(", "self", ")", ":", "data", "=", "{", "'name'", ":", "self", ".", "name", ",", "'referenceId'", ":", "self", ".", "reference_id", ",", "'shortDescription'", ":", "self", ".", "short_description", ",", "'playlistType'", ":", "self", "....
Internal method that serializes object into a dictionary.
[ "Internal", "method", "that", "serializes", "object", "into", "a", "dictionary", "." ]
19c946b689a80156e070fe9bc35589c4b768e614
https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/playlist.py#L110-L127
train
55,222
studionow/pybrightcove
pybrightcove/playlist.py
Playlist._load
def _load(self, data): """ Internal method that deserializes a ``pybrightcove.playlist.Playlist`` object. """ self.raw_data = data self.id = data['id'] self.reference_id = data['referenceId'] self.name = data['name'] self.short_description = data['shortDescription'] self.thumbnail_url = data['thumbnailURL'] self.videos = [] self.video_ids = data['videoIds'] self.type = data['playlistType'] for video in data.get('videos', []): self.videos.append(pybrightcove.video.Video( data=video, connection=self.connection))
python
def _load(self, data): """ Internal method that deserializes a ``pybrightcove.playlist.Playlist`` object. """ self.raw_data = data self.id = data['id'] self.reference_id = data['referenceId'] self.name = data['name'] self.short_description = data['shortDescription'] self.thumbnail_url = data['thumbnailURL'] self.videos = [] self.video_ids = data['videoIds'] self.type = data['playlistType'] for video in data.get('videos', []): self.videos.append(pybrightcove.video.Video( data=video, connection=self.connection))
[ "def", "_load", "(", "self", ",", "data", ")", ":", "self", ".", "raw_data", "=", "data", "self", ".", "id", "=", "data", "[", "'id'", "]", "self", ".", "reference_id", "=", "data", "[", "'referenceId'", "]", "self", ".", "name", "=", "data", "[", ...
Internal method that deserializes a ``pybrightcove.playlist.Playlist`` object.
[ "Internal", "method", "that", "deserializes", "a", "pybrightcove", ".", "playlist", ".", "Playlist", "object", "." ]
19c946b689a80156e070fe9bc35589c4b768e614
https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/playlist.py#L129-L146
train
55,223
studionow/pybrightcove
pybrightcove/playlist.py
Playlist.save
def save(self): """ Create or update a playlist. """ d = self._to_dict() if len(d.get('videoIds', [])) > 0: if not self.id: self.id = self.connection.post('create_playlist', playlist=d) else: data = self.connection.post('update_playlist', playlist=d) if data: self._load(data)
python
def save(self): """ Create or update a playlist. """ d = self._to_dict() if len(d.get('videoIds', [])) > 0: if not self.id: self.id = self.connection.post('create_playlist', playlist=d) else: data = self.connection.post('update_playlist', playlist=d) if data: self._load(data)
[ "def", "save", "(", "self", ")", ":", "d", "=", "self", ".", "_to_dict", "(", ")", "if", "len", "(", "d", ".", "get", "(", "'videoIds'", ",", "[", "]", ")", ")", ">", "0", ":", "if", "not", "self", ".", "id", ":", "self", ".", "id", "=", ...
Create or update a playlist.
[ "Create", "or", "update", "a", "playlist", "." ]
19c946b689a80156e070fe9bc35589c4b768e614
https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/playlist.py#L148-L159
train
55,224
studionow/pybrightcove
pybrightcove/playlist.py
Playlist.delete
def delete(self, cascade=False): """ Deletes this playlist. """ if self.id: self.connection.post('delete_playlist', playlist_id=self.id, cascade=cascade) self.id = None
python
def delete(self, cascade=False): """ Deletes this playlist. """ if self.id: self.connection.post('delete_playlist', playlist_id=self.id, cascade=cascade) self.id = None
[ "def", "delete", "(", "self", ",", "cascade", "=", "False", ")", ":", "if", "self", ".", "id", ":", "self", ".", "connection", ".", "post", "(", "'delete_playlist'", ",", "playlist_id", "=", "self", ".", "id", ",", "cascade", "=", "cascade", ")", "se...
Deletes this playlist.
[ "Deletes", "this", "playlist", "." ]
19c946b689a80156e070fe9bc35589c4b768e614
https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/playlist.py#L161-L168
train
55,225
studionow/pybrightcove
pybrightcove/playlist.py
Playlist.find_all
def find_all(connection=None, page_size=100, page_number=0, sort_by=DEFAULT_SORT_BY, sort_order=DEFAULT_SORT_ORDER): """ List all playlists. """ return pybrightcove.connection.ItemResultSet("find_all_playlists", Playlist, connection, page_size, page_number, sort_by, sort_order)
python
def find_all(connection=None, page_size=100, page_number=0, sort_by=DEFAULT_SORT_BY, sort_order=DEFAULT_SORT_ORDER): """ List all playlists. """ return pybrightcove.connection.ItemResultSet("find_all_playlists", Playlist, connection, page_size, page_number, sort_by, sort_order)
[ "def", "find_all", "(", "connection", "=", "None", ",", "page_size", "=", "100", ",", "page_number", "=", "0", ",", "sort_by", "=", "DEFAULT_SORT_BY", ",", "sort_order", "=", "DEFAULT_SORT_ORDER", ")", ":", "return", "pybrightcove", ".", "connection", ".", "...
List all playlists.
[ "List", "all", "playlists", "." ]
19c946b689a80156e070fe9bc35589c4b768e614
https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/playlist.py#L171-L177
train
55,226
studionow/pybrightcove
pybrightcove/playlist.py
Playlist.find_by_ids
def find_by_ids(ids, connection=None, page_size=100, page_number=0, sort_by=DEFAULT_SORT_BY, sort_order=DEFAULT_SORT_ORDER): """ List playlists by specific IDs. """ ids = ','.join([str(i) for i in ids]) return pybrightcove.connection.ItemResultSet('find_playlists_by_ids', Playlist, connection, page_size, page_number, sort_by, sort_order, playlist_ids=ids)
python
def find_by_ids(ids, connection=None, page_size=100, page_number=0, sort_by=DEFAULT_SORT_BY, sort_order=DEFAULT_SORT_ORDER): """ List playlists by specific IDs. """ ids = ','.join([str(i) for i in ids]) return pybrightcove.connection.ItemResultSet('find_playlists_by_ids', Playlist, connection, page_size, page_number, sort_by, sort_order, playlist_ids=ids)
[ "def", "find_by_ids", "(", "ids", ",", "connection", "=", "None", ",", "page_size", "=", "100", ",", "page_number", "=", "0", ",", "sort_by", "=", "DEFAULT_SORT_BY", ",", "sort_order", "=", "DEFAULT_SORT_ORDER", ")", ":", "ids", "=", "','", ".", "join", ...
List playlists by specific IDs.
[ "List", "playlists", "by", "specific", "IDs", "." ]
19c946b689a80156e070fe9bc35589c4b768e614
https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/playlist.py#L180-L188
train
55,227
studionow/pybrightcove
pybrightcove/playlist.py
Playlist.find_by_reference_ids
def find_by_reference_ids(reference_ids, connection=None, page_size=100, page_number=0, sort_by=DEFAULT_SORT_BY, sort_order=DEFAULT_SORT_ORDER): """ List playlists by specific reference_ids. """ reference_ids = ','.join([str(i) for i in reference_ids]) return pybrightcove.connection.ItemResultSet( "find_playlists_by_reference_ids", Playlist, connection, page_size, page_number, sort_by, sort_order, reference_ids=reference_ids)
python
def find_by_reference_ids(reference_ids, connection=None, page_size=100, page_number=0, sort_by=DEFAULT_SORT_BY, sort_order=DEFAULT_SORT_ORDER): """ List playlists by specific reference_ids. """ reference_ids = ','.join([str(i) for i in reference_ids]) return pybrightcove.connection.ItemResultSet( "find_playlists_by_reference_ids", Playlist, connection, page_size, page_number, sort_by, sort_order, reference_ids=reference_ids)
[ "def", "find_by_reference_ids", "(", "reference_ids", ",", "connection", "=", "None", ",", "page_size", "=", "100", ",", "page_number", "=", "0", ",", "sort_by", "=", "DEFAULT_SORT_BY", ",", "sort_order", "=", "DEFAULT_SORT_ORDER", ")", ":", "reference_ids", "="...
List playlists by specific reference_ids.
[ "List", "playlists", "by", "specific", "reference_ids", "." ]
19c946b689a80156e070fe9bc35589c4b768e614
https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/playlist.py#L191-L199
train
55,228
studionow/pybrightcove
pybrightcove/playlist.py
Playlist.find_for_player_id
def find_for_player_id(player_id, connection=None, page_size=100, page_number=0, sort_by=DEFAULT_SORT_BY, sort_order=DEFAULT_SORT_ORDER): """ List playlists for a for given player id. """ return pybrightcove.connection.ItemResultSet( "find_playlists_for_player_id", Playlist, connection, page_size, page_number, sort_by, sort_order, player_id=player_id)
python
def find_for_player_id(player_id, connection=None, page_size=100, page_number=0, sort_by=DEFAULT_SORT_BY, sort_order=DEFAULT_SORT_ORDER): """ List playlists for a for given player id. """ return pybrightcove.connection.ItemResultSet( "find_playlists_for_player_id", Playlist, connection, page_size, page_number, sort_by, sort_order, player_id=player_id)
[ "def", "find_for_player_id", "(", "player_id", ",", "connection", "=", "None", ",", "page_size", "=", "100", ",", "page_number", "=", "0", ",", "sort_by", "=", "DEFAULT_SORT_BY", ",", "sort_order", "=", "DEFAULT_SORT_ORDER", ")", ":", "return", "pybrightcove", ...
List playlists for a for given player id.
[ "List", "playlists", "for", "a", "for", "given", "player", "id", "." ]
19c946b689a80156e070fe9bc35589c4b768e614
https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/playlist.py#L202-L209
train
55,229
smarie/python-parsyfiles
parsyfiles/converting_core.py
get_options_for_id
def get_options_for_id(options: Dict[str, Dict[str, Any]], identifier: str): """ Helper method, from the full options dict of dicts, to return either the options related to this parser or an empty dictionary. It also performs all the var type checks :param options: :param identifier: :return: """ check_var(options, var_types=dict, var_name='options') res = options[identifier] if identifier in options.keys() else dict() check_var(res, var_types=dict, var_name='options[' + identifier + ']') return res
python
def get_options_for_id(options: Dict[str, Dict[str, Any]], identifier: str): """ Helper method, from the full options dict of dicts, to return either the options related to this parser or an empty dictionary. It also performs all the var type checks :param options: :param identifier: :return: """ check_var(options, var_types=dict, var_name='options') res = options[identifier] if identifier in options.keys() else dict() check_var(res, var_types=dict, var_name='options[' + identifier + ']') return res
[ "def", "get_options_for_id", "(", "options", ":", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "Any", "]", "]", ",", "identifier", ":", "str", ")", ":", "check_var", "(", "options", ",", "var_types", "=", "dict", ",", "var_name", "=", "'options'",...
Helper method, from the full options dict of dicts, to return either the options related to this parser or an empty dictionary. It also performs all the var type checks :param options: :param identifier: :return:
[ "Helper", "method", "from", "the", "full", "options", "dict", "of", "dicts", "to", "return", "either", "the", "options", "related", "to", "this", "parser", "or", "an", "empty", "dictionary", ".", "It", "also", "performs", "all", "the", "var", "type", "chec...
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/converting_core.py#L373-L385
train
55,230
smarie/python-parsyfiles
parsyfiles/converting_core.py
Converter._convert
def _convert(self, desired_type: Type[T], source_obj: S, logger: Logger, options: Dict[str, Dict[str, Any]]) -> T: """ Implementing classes should implement this method to perform the conversion itself :param desired_type: the destination type of the conversion :param source_obj: the source object that should be converter :param logger: a logger to use if any is available, or None :param options: additional options map. Implementing classes may use 'self.get_applicable_options()' to get the options that are of interest for this converter. :return: """ pass
python
def _convert(self, desired_type: Type[T], source_obj: S, logger: Logger, options: Dict[str, Dict[str, Any]]) -> T: """ Implementing classes should implement this method to perform the conversion itself :param desired_type: the destination type of the conversion :param source_obj: the source object that should be converter :param logger: a logger to use if any is available, or None :param options: additional options map. Implementing classes may use 'self.get_applicable_options()' to get the options that are of interest for this converter. :return: """ pass
[ "def", "_convert", "(", "self", ",", "desired_type", ":", "Type", "[", "T", "]", ",", "source_obj", ":", "S", ",", "logger", ":", "Logger", ",", "options", ":", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "Any", "]", "]", ")", "->", "T", ...
Implementing classes should implement this method to perform the conversion itself :param desired_type: the destination type of the conversion :param source_obj: the source object that should be converter :param logger: a logger to use if any is available, or None :param options: additional options map. Implementing classes may use 'self.get_applicable_options()' to get the options that are of interest for this converter. :return:
[ "Implementing", "classes", "should", "implement", "this", "method", "to", "perform", "the", "conversion", "itself" ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/converting_core.py#L324-L335
train
55,231
smarie/python-parsyfiles
parsyfiles/converting_core.py
ConverterFunction._convert
def _convert(self, desired_type: Type[T], source_obj: S, logger: Logger, options: Dict[str, Dict[str, Any]]) -> T: """ Delegates to the user-provided method. Passes the appropriate part of the options according to the function name. :param desired_type: :param source_obj: :param logger: :param options: :return: """ try: if self.unpack_options: opts = self.get_applicable_options(options) if self.function_args is not None: return self.conversion_method(desired_type, source_obj, logger, **self.function_args, **opts) else: return self.conversion_method(desired_type, source_obj, logger, **opts) else: if self.function_args is not None: return self.conversion_method(desired_type, source_obj, logger, options, **self.function_args) else: return self.conversion_method(desired_type, source_obj, logger, options) except TypeError as e: raise CaughtTypeError.create(self.conversion_method, e)
python
def _convert(self, desired_type: Type[T], source_obj: S, logger: Logger, options: Dict[str, Dict[str, Any]]) -> T: """ Delegates to the user-provided method. Passes the appropriate part of the options according to the function name. :param desired_type: :param source_obj: :param logger: :param options: :return: """ try: if self.unpack_options: opts = self.get_applicable_options(options) if self.function_args is not None: return self.conversion_method(desired_type, source_obj, logger, **self.function_args, **opts) else: return self.conversion_method(desired_type, source_obj, logger, **opts) else: if self.function_args is not None: return self.conversion_method(desired_type, source_obj, logger, options, **self.function_args) else: return self.conversion_method(desired_type, source_obj, logger, options) except TypeError as e: raise CaughtTypeError.create(self.conversion_method, e)
[ "def", "_convert", "(", "self", ",", "desired_type", ":", "Type", "[", "T", "]", ",", "source_obj", ":", "S", ",", "logger", ":", "Logger", ",", "options", ":", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "Any", "]", "]", ")", "->", "T", ...
Delegates to the user-provided method. Passes the appropriate part of the options according to the function name. :param desired_type: :param source_obj: :param logger: :param options: :return:
[ "Delegates", "to", "the", "user", "-", "provided", "method", ".", "Passes", "the", "appropriate", "part", "of", "the", "options", "according", "to", "the", "function", "name", "." ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/converting_core.py#L507-L532
train
55,232
smarie/python-parsyfiles
parsyfiles/converting_core.py
ConversionChain.remove_first
def remove_first(self, inplace: bool = False): """ Utility method to remove the first converter of this chain. If inplace is True, this object is modified and None is returned. Otherwise, a copy is returned :param inplace: boolean indicating whether to modify this object (True) or return a copy (False) :return: None or a copy with the first converter removed """ if len(self._converters_list) > 1: if inplace: self._converters_list = self._converters_list[1:] # update the current source type self.from_type = self._converters_list[0].from_type return else: new = copy(self) new._converters_list = new._converters_list[1:] # update the current source type new.from_type = new._converters_list[0].from_type return new else: raise ValueError('cant remove first: would make it empty!')
python
def remove_first(self, inplace: bool = False): """ Utility method to remove the first converter of this chain. If inplace is True, this object is modified and None is returned. Otherwise, a copy is returned :param inplace: boolean indicating whether to modify this object (True) or return a copy (False) :return: None or a copy with the first converter removed """ if len(self._converters_list) > 1: if inplace: self._converters_list = self._converters_list[1:] # update the current source type self.from_type = self._converters_list[0].from_type return else: new = copy(self) new._converters_list = new._converters_list[1:] # update the current source type new.from_type = new._converters_list[0].from_type return new else: raise ValueError('cant remove first: would make it empty!')
[ "def", "remove_first", "(", "self", ",", "inplace", ":", "bool", "=", "False", ")", ":", "if", "len", "(", "self", ".", "_converters_list", ")", ">", "1", ":", "if", "inplace", ":", "self", ".", "_converters_list", "=", "self", ".", "_converters_list", ...
Utility method to remove the first converter of this chain. If inplace is True, this object is modified and None is returned. Otherwise, a copy is returned :param inplace: boolean indicating whether to modify this object (True) or return a copy (False) :return: None or a copy with the first converter removed
[ "Utility", "method", "to", "remove", "the", "first", "converter", "of", "this", "chain", ".", "If", "inplace", "is", "True", "this", "object", "is", "modified", "and", "None", "is", "returned", ".", "Otherwise", "a", "copy", "is", "returned" ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/converting_core.py#L621-L642
train
55,233
smarie/python-parsyfiles
parsyfiles/converting_core.py
ConversionChain.add_conversion_steps
def add_conversion_steps(self, converters: List[Converter], inplace: bool = False): """ Utility method to add converters to this chain. If inplace is True, this object is modified and None is returned. Otherwise, a copy is returned :param converters: the list of converters to add :param inplace: boolean indicating whether to modify this object (True) or return a copy (False) :return: None or a copy with the converters added """ check_var(converters, var_types=list, min_len=1) if inplace: for converter in converters: self.add_conversion_step(converter, inplace=True) else: new = copy(self) new.add_conversion_steps(converters, inplace=True) return new
python
def add_conversion_steps(self, converters: List[Converter], inplace: bool = False): """ Utility method to add converters to this chain. If inplace is True, this object is modified and None is returned. Otherwise, a copy is returned :param converters: the list of converters to add :param inplace: boolean indicating whether to modify this object (True) or return a copy (False) :return: None or a copy with the converters added """ check_var(converters, var_types=list, min_len=1) if inplace: for converter in converters: self.add_conversion_step(converter, inplace=True) else: new = copy(self) new.add_conversion_steps(converters, inplace=True) return new
[ "def", "add_conversion_steps", "(", "self", ",", "converters", ":", "List", "[", "Converter", "]", ",", "inplace", ":", "bool", "=", "False", ")", ":", "check_var", "(", "converters", ",", "var_types", "=", "list", ",", "min_len", "=", "1", ")", "if", ...
Utility method to add converters to this chain. If inplace is True, this object is modified and None is returned. Otherwise, a copy is returned :param converters: the list of converters to add :param inplace: boolean indicating whether to modify this object (True) or return a copy (False) :return: None or a copy with the converters added
[ "Utility", "method", "to", "add", "converters", "to", "this", "chain", ".", "If", "inplace", "is", "True", "this", "object", "is", "modified", "and", "None", "is", "returned", ".", "Otherwise", "a", "copy", "is", "returned" ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/converting_core.py#L644-L660
train
55,234
smarie/python-parsyfiles
parsyfiles/converting_core.py
ConversionChain.add_conversion_step
def add_conversion_step(self, converter: Converter[S, T], inplace: bool = False): """ Utility method to add a converter to this chain. If inplace is True, this object is modified and None is returned. Otherwise, a copy is returned :param converter: the converter to add :param inplace: boolean indicating whether to modify this object (True) or return a copy (False) :return: None or a copy with the converter added """ # it the current chain is generic, raise an error if self.is_generic() and converter.is_generic(): raise ValueError('Cannot chain this generic converter chain to the provided converter : it is generic too!') # if the current chain is able to transform its input into a valid input for the new converter elif converter.can_be_appended_to(self, self.strict): if inplace: self._converters_list.append(converter) # update the current destination type self.to_type = converter.to_type return else: new = copy(self) new._converters_list.append(converter) # update the current destination type new.to_type = converter.to_type return new else: raise TypeError('Cannnot register a converter on this conversion chain : source type \'' + get_pretty_type_str(converter.from_type) + '\' is not compliant with current destination type of the chain : \'' + get_pretty_type_str(self.to_type) + ' (this chain performs ' + ('' if self.strict else 'non-') + 'strict mode matching)')
python
def add_conversion_step(self, converter: Converter[S, T], inplace: bool = False): """ Utility method to add a converter to this chain. If inplace is True, this object is modified and None is returned. Otherwise, a copy is returned :param converter: the converter to add :param inplace: boolean indicating whether to modify this object (True) or return a copy (False) :return: None or a copy with the converter added """ # it the current chain is generic, raise an error if self.is_generic() and converter.is_generic(): raise ValueError('Cannot chain this generic converter chain to the provided converter : it is generic too!') # if the current chain is able to transform its input into a valid input for the new converter elif converter.can_be_appended_to(self, self.strict): if inplace: self._converters_list.append(converter) # update the current destination type self.to_type = converter.to_type return else: new = copy(self) new._converters_list.append(converter) # update the current destination type new.to_type = converter.to_type return new else: raise TypeError('Cannnot register a converter on this conversion chain : source type \'' + get_pretty_type_str(converter.from_type) + '\' is not compliant with current destination type of the chain : \'' + get_pretty_type_str(self.to_type) + ' (this chain performs ' + ('' if self.strict else 'non-') + 'strict mode matching)')
[ "def", "add_conversion_step", "(", "self", ",", "converter", ":", "Converter", "[", "S", ",", "T", "]", ",", "inplace", ":", "bool", "=", "False", ")", ":", "# it the current chain is generic, raise an error", "if", "self", ".", "is_generic", "(", ")", "and", ...
Utility method to add a converter to this chain. If inplace is True, this object is modified and None is returned. Otherwise, a copy is returned :param converter: the converter to add :param inplace: boolean indicating whether to modify this object (True) or return a copy (False) :return: None or a copy with the converter added
[ "Utility", "method", "to", "add", "a", "converter", "to", "this", "chain", ".", "If", "inplace", "is", "True", "this", "object", "is", "modified", "and", "None", "is", "returned", ".", "Otherwise", "a", "copy", "is", "returned" ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/converting_core.py#L662-L693
train
55,235
smarie/python-parsyfiles
parsyfiles/converting_core.py
ConversionChain.insert_conversion_steps_at_beginning
def insert_conversion_steps_at_beginning(self, converters: List[Converter], inplace: bool = False): """ Utility method to insert converters at the beginning ofthis chain. If inplace is True, this object is modified and None is returned. Otherwise, a copy is returned :param converters: the list of converters to insert :param inplace: boolean indicating whether to modify this object (True) or return a copy (False) :return: None or a copy with the converters added """ if inplace: for converter in reversed(converters): self.insert_conversion_step_at_beginning(converter, inplace=True) return else: new = copy(self) for converter in reversed(converters): # do inplace since it is a copy new.insert_conversion_step_at_beginning(converter, inplace=True) return new
python
def insert_conversion_steps_at_beginning(self, converters: List[Converter], inplace: bool = False): """ Utility method to insert converters at the beginning ofthis chain. If inplace is True, this object is modified and None is returned. Otherwise, a copy is returned :param converters: the list of converters to insert :param inplace: boolean indicating whether to modify this object (True) or return a copy (False) :return: None or a copy with the converters added """ if inplace: for converter in reversed(converters): self.insert_conversion_step_at_beginning(converter, inplace=True) return else: new = copy(self) for converter in reversed(converters): # do inplace since it is a copy new.insert_conversion_step_at_beginning(converter, inplace=True) return new
[ "def", "insert_conversion_steps_at_beginning", "(", "self", ",", "converters", ":", "List", "[", "Converter", "]", ",", "inplace", ":", "bool", "=", "False", ")", ":", "if", "inplace", ":", "for", "converter", "in", "reversed", "(", "converters", ")", ":", ...
Utility method to insert converters at the beginning ofthis chain. If inplace is True, this object is modified and None is returned. Otherwise, a copy is returned :param converters: the list of converters to insert :param inplace: boolean indicating whether to modify this object (True) or return a copy (False) :return: None or a copy with the converters added
[ "Utility", "method", "to", "insert", "converters", "at", "the", "beginning", "ofthis", "chain", ".", "If", "inplace", "is", "True", "this", "object", "is", "modified", "and", "None", "is", "returned", ".", "Otherwise", "a", "copy", "is", "returned" ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/converting_core.py#L695-L713
train
55,236
smarie/python-parsyfiles
parsyfiles/converting_core.py
ConversionChain._convert
def _convert(self, desired_type: Type[T], obj: S, logger: Logger, options: Dict[str, Dict[str, Any]]) -> T: """ Apply the converters of the chain in order to produce the desired result. Only the last converter will see the 'desired type', the others will be asked to produce their declared to_type. :param desired_type: :param obj: :param logger: :param options: :return: """ for converter in self._converters_list[:-1]: # convert into each converters destination type obj = converter.convert(converter.to_type, obj, logger, options) # the last converter in the chain should convert to desired type return self._converters_list[-1].convert(desired_type, obj, logger, options)
python
def _convert(self, desired_type: Type[T], obj: S, logger: Logger, options: Dict[str, Dict[str, Any]]) -> T: """ Apply the converters of the chain in order to produce the desired result. Only the last converter will see the 'desired type', the others will be asked to produce their declared to_type. :param desired_type: :param obj: :param logger: :param options: :return: """ for converter in self._converters_list[:-1]: # convert into each converters destination type obj = converter.convert(converter.to_type, obj, logger, options) # the last converter in the chain should convert to desired type return self._converters_list[-1].convert(desired_type, obj, logger, options)
[ "def", "_convert", "(", "self", ",", "desired_type", ":", "Type", "[", "T", "]", ",", "obj", ":", "S", ",", "logger", ":", "Logger", ",", "options", ":", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "Any", "]", "]", ")", "->", "T", ":", ...
Apply the converters of the chain in order to produce the desired result. Only the last converter will see the 'desired type', the others will be asked to produce their declared to_type. :param desired_type: :param obj: :param logger: :param options: :return:
[ "Apply", "the", "converters", "of", "the", "chain", "in", "order", "to", "produce", "the", "desired", "result", ".", "Only", "the", "last", "converter", "will", "see", "the", "desired", "type", "the", "others", "will", "be", "asked", "to", "produce", "thei...
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/converting_core.py#L754-L770
train
55,237
frascoweb/frasco
frasco/signals.py
listens_to
def listens_to(name, sender=None, weak=True): """Listens to a named signal """ def decorator(f): if sender: return signal(name).connect(f, sender=sender, weak=weak) return signal(name).connect(f, weak=weak) return decorator
python
def listens_to(name, sender=None, weak=True): """Listens to a named signal """ def decorator(f): if sender: return signal(name).connect(f, sender=sender, weak=weak) return signal(name).connect(f, weak=weak) return decorator
[ "def", "listens_to", "(", "name", ",", "sender", "=", "None", ",", "weak", "=", "True", ")", ":", "def", "decorator", "(", "f", ")", ":", "if", "sender", ":", "return", "signal", "(", "name", ")", ".", "connect", "(", "f", ",", "sender", "=", "se...
Listens to a named signal
[ "Listens", "to", "a", "named", "signal" ]
ea519d69dd5ca6deaf3650175692ee4a1a02518f
https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/signals.py#L9-L16
train
55,238
korfuri/pip-prometheus
pip_prometheus/__init__.py
LoadInstallations
def LoadInstallations(counter): """Load installed packages and export the version map. This function may be called multiple times, but the counters will be increased each time. Since Prometheus counters are never decreased, the aggregated results will not make sense. """ process = subprocess.Popen(["pip", "list", "--format=json"], stdout=subprocess.PIPE) output, _ = process.communicate() installations = json.loads(output) for i in installations: counter.labels(i["name"], i["version"]).inc()
python
def LoadInstallations(counter): """Load installed packages and export the version map. This function may be called multiple times, but the counters will be increased each time. Since Prometheus counters are never decreased, the aggregated results will not make sense. """ process = subprocess.Popen(["pip", "list", "--format=json"], stdout=subprocess.PIPE) output, _ = process.communicate() installations = json.loads(output) for i in installations: counter.labels(i["name"], i["version"]).inc()
[ "def", "LoadInstallations", "(", "counter", ")", ":", "process", "=", "subprocess", ".", "Popen", "(", "[", "\"pip\"", ",", "\"list\"", ",", "\"--format=json\"", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "output", ",", "_", "=", "process", ...
Load installed packages and export the version map. This function may be called multiple times, but the counters will be increased each time. Since Prometheus counters are never decreased, the aggregated results will not make sense.
[ "Load", "installed", "packages", "and", "export", "the", "version", "map", "." ]
0be5d55739312828365833b87399183dc838e0b7
https://github.com/korfuri/pip-prometheus/blob/0be5d55739312828365833b87399183dc838e0b7/pip_prometheus/__init__.py#L7-L19
train
55,239
EnricoGiampieri/keggrest
keggrest/keggrest.py
RESTrequest
def RESTrequest(*args, **kwargs): """return and save the blob of data that is returned from kegg without caring to the format""" verbose = kwargs.get('verbose', False) force_download = kwargs.get('force', False) save = kwargs.get('force', True) # so you can copy paste from kegg args = list(chain.from_iterable(a.split('/') for a in args)) args = [a for a in args if a] request = 'http://rest.kegg.jp/' + "/".join(args) print_verbose(verbose, "richiedo la pagina: " + request) filename = "KEGG_" + "_".join(args) try: if force_download: raise IOError() print_verbose(verbose, "loading the cached file " + filename) with open(filename, 'r') as f: data = pickle.load(f) except IOError: print_verbose(verbose, "downloading the library,it may take some time") import urllib2 try: req = urllib2.urlopen(request) data = req.read() if save: with open(filename, 'w') as f: print_verbose(verbose, "saving the file to " + filename) pickle.dump(data, f) # clean the error stacktrace except urllib2.HTTPError as e: raise e return data
python
def RESTrequest(*args, **kwargs): """return and save the blob of data that is returned from kegg without caring to the format""" verbose = kwargs.get('verbose', False) force_download = kwargs.get('force', False) save = kwargs.get('force', True) # so you can copy paste from kegg args = list(chain.from_iterable(a.split('/') for a in args)) args = [a for a in args if a] request = 'http://rest.kegg.jp/' + "/".join(args) print_verbose(verbose, "richiedo la pagina: " + request) filename = "KEGG_" + "_".join(args) try: if force_download: raise IOError() print_verbose(verbose, "loading the cached file " + filename) with open(filename, 'r') as f: data = pickle.load(f) except IOError: print_verbose(verbose, "downloading the library,it may take some time") import urllib2 try: req = urllib2.urlopen(request) data = req.read() if save: with open(filename, 'w') as f: print_verbose(verbose, "saving the file to " + filename) pickle.dump(data, f) # clean the error stacktrace except urllib2.HTTPError as e: raise e return data
[ "def", "RESTrequest", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "verbose", "=", "kwargs", ".", "get", "(", "'verbose'", ",", "False", ")", "force_download", "=", "kwargs", ".", "get", "(", "'force'", ",", "False", ")", "save", "=", "kwargs...
return and save the blob of data that is returned from kegg without caring to the format
[ "return", "and", "save", "the", "blob", "of", "data", "that", "is", "returned", "from", "kegg", "without", "caring", "to", "the", "format" ]
012c15d6ac591bebec875946d8f9493b000fb1ee
https://github.com/EnricoGiampieri/keggrest/blob/012c15d6ac591bebec875946d8f9493b000fb1ee/keggrest/keggrest.py#L12-L44
train
55,240
nikcub/floyd
floyd/core/multiopt.py
MultioptHelpFormatter.command_help_long
def command_help_long(self): """ Return command help for use in global parser usage string @TODO update to support self.current_indent from formatter """ indent = " " * 2 # replace with current_indent help = "Command must be one of:\n" for action_name in self.parser.valid_commands: help += "%s%-10s %-70s\n" % (indent, action_name, self.parser.commands[action_name].desc_short.capitalize()) help += '\nSee \'%s help COMMAND\' for help and information on a command' % self.parser.prog return help
python
def command_help_long(self): """ Return command help for use in global parser usage string @TODO update to support self.current_indent from formatter """ indent = " " * 2 # replace with current_indent help = "Command must be one of:\n" for action_name in self.parser.valid_commands: help += "%s%-10s %-70s\n" % (indent, action_name, self.parser.commands[action_name].desc_short.capitalize()) help += '\nSee \'%s help COMMAND\' for help and information on a command' % self.parser.prog return help
[ "def", "command_help_long", "(", "self", ")", ":", "indent", "=", "\" \"", "*", "2", "# replace with current_indent", "help", "=", "\"Command must be one of:\\n\"", "for", "action_name", "in", "self", ".", "parser", ".", "valid_commands", ":", "help", "+=", "\"%s%...
Return command help for use in global parser usage string @TODO update to support self.current_indent from formatter
[ "Return", "command", "help", "for", "use", "in", "global", "parser", "usage", "string" ]
5772d0047efb11c9ce5f7d234a9da4576ce24edc
https://github.com/nikcub/floyd/blob/5772d0047efb11c9ce5f7d234a9da4576ce24edc/floyd/core/multiopt.py#L66-L77
train
55,241
nikcub/floyd
floyd/core/multiopt.py
MultioptParser.run
def run(self): """ Run the multiopt parser """ self.parser = MultioptOptionParser( usage="%prog <command> [options] [args]", prog=self.clsname, version=self.version, option_list=self.global_options, description=self.desc_short, commands=self.command_set, epilog=self.footer ) try: self.options, self.args = self.parser.parse_args(self.argv) except Exception, e: print str(e) pass if len(self.args) < 1: self.parser.print_lax_help() return 2 self.command = self.args.pop(0) showHelp = False if self.command == 'help': if len(self.args) < 1: self.parser.print_lax_help() return 2 else: self.command = self.args.pop() showHelp = True if self.command not in self.valid_commands: self.parser.print_cmd_error(self.command) return 2 self.command_set[self.command].set_cmdname(self.command) subcmd_parser = self.command_set[self.command].get_parser(self.clsname, self.version, self.global_options) subcmd_options, subcmd_args = subcmd_parser.parse_args(self.args) if showHelp: subcmd_parser.print_help_long() return 1 try: self.command_set[self.command].func(subcmd_options, *subcmd_args) except (CommandError, TypeError), e: # self.parser.print_exec_error(self.command, str(e)) subcmd_parser.print_exec_error(self.command, str(e)) print # @TODO show command help # self.parser.print_lax_help() return 2 return 1
python
def run(self): """ Run the multiopt parser """ self.parser = MultioptOptionParser( usage="%prog <command> [options] [args]", prog=self.clsname, version=self.version, option_list=self.global_options, description=self.desc_short, commands=self.command_set, epilog=self.footer ) try: self.options, self.args = self.parser.parse_args(self.argv) except Exception, e: print str(e) pass if len(self.args) < 1: self.parser.print_lax_help() return 2 self.command = self.args.pop(0) showHelp = False if self.command == 'help': if len(self.args) < 1: self.parser.print_lax_help() return 2 else: self.command = self.args.pop() showHelp = True if self.command not in self.valid_commands: self.parser.print_cmd_error(self.command) return 2 self.command_set[self.command].set_cmdname(self.command) subcmd_parser = self.command_set[self.command].get_parser(self.clsname, self.version, self.global_options) subcmd_options, subcmd_args = subcmd_parser.parse_args(self.args) if showHelp: subcmd_parser.print_help_long() return 1 try: self.command_set[self.command].func(subcmd_options, *subcmd_args) except (CommandError, TypeError), e: # self.parser.print_exec_error(self.command, str(e)) subcmd_parser.print_exec_error(self.command, str(e)) print # @TODO show command help # self.parser.print_lax_help() return 2 return 1
[ "def", "run", "(", "self", ")", ":", "self", ".", "parser", "=", "MultioptOptionParser", "(", "usage", "=", "\"%prog <command> [options] [args]\"", ",", "prog", "=", "self", ".", "clsname", ",", "version", "=", "self", ".", "version", ",", "option_list", "="...
Run the multiopt parser
[ "Run", "the", "multiopt", "parser" ]
5772d0047efb11c9ce5f7d234a9da4576ce24edc
https://github.com/nikcub/floyd/blob/5772d0047efb11c9ce5f7d234a9da4576ce24edc/floyd/core/multiopt.py#L383-L441
train
55,242
KvasirSecurity/kvasirapi-python
KvasirAPI/jsonrpc/snmp.py
SNMP.add
def add(self, host=None, f_community=None, f_access=None, f_version=None): """ Add an SNMP community string to a host :param host: t_hosts.id or t_hosts.f_ipaddr :param f_community: Community string to add :param f_access: READ or WRITE :param f_version: v1, v2c or v3 :return: (True/False, t_snmp.id/Error string) """ return self.send.snmp_add(host, f_community, f_access, f_version)
python
def add(self, host=None, f_community=None, f_access=None, f_version=None): """ Add an SNMP community string to a host :param host: t_hosts.id or t_hosts.f_ipaddr :param f_community: Community string to add :param f_access: READ or WRITE :param f_version: v1, v2c or v3 :return: (True/False, t_snmp.id/Error string) """ return self.send.snmp_add(host, f_community, f_access, f_version)
[ "def", "add", "(", "self", ",", "host", "=", "None", ",", "f_community", "=", "None", ",", "f_access", "=", "None", ",", "f_version", "=", "None", ")", ":", "return", "self", ".", "send", ".", "snmp_add", "(", "host", ",", "f_community", ",", "f_acce...
Add an SNMP community string to a host :param host: t_hosts.id or t_hosts.f_ipaddr :param f_community: Community string to add :param f_access: READ or WRITE :param f_version: v1, v2c or v3 :return: (True/False, t_snmp.id/Error string)
[ "Add", "an", "SNMP", "community", "string", "to", "a", "host" ]
ec8c5818bd5913f3afd150f25eaec6e7cc732f4c
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/jsonrpc/snmp.py#L39-L49
train
55,243
memphis-iis/GLUDB
gludb/backends/mongodb.py
delete_collection
def delete_collection(db_name, collection_name, host='localhost', port=27017): """Almost exclusively for testing.""" client = MongoClient("mongodb://%s:%d" % (host, port)) client[db_name].drop_collection(collection_name)
python
def delete_collection(db_name, collection_name, host='localhost', port=27017): """Almost exclusively for testing.""" client = MongoClient("mongodb://%s:%d" % (host, port)) client[db_name].drop_collection(collection_name)
[ "def", "delete_collection", "(", "db_name", ",", "collection_name", ",", "host", "=", "'localhost'", ",", "port", "=", "27017", ")", ":", "client", "=", "MongoClient", "(", "\"mongodb://%s:%d\"", "%", "(", "host", ",", "port", ")", ")", "client", "[", "db_...
Almost exclusively for testing.
[ "Almost", "exclusively", "for", "testing", "." ]
25692528ff6fe8184a3570f61f31f1a90088a388
https://github.com/memphis-iis/GLUDB/blob/25692528ff6fe8184a3570f61f31f1a90088a388/gludb/backends/mongodb.py#L11-L14
train
55,244
inveniosoftware/kwalitee
kwalitee/kwalitee.py
_check_1st_line
def _check_1st_line(line, **kwargs): """First line check. Check that the first line has a known component name followed by a colon and then a short description of the commit. :param line: first line :type line: str :param components: list of known component names :type line: list :param max_first_line: maximum length of the first line :type max_first_line: int :return: errors as in (code, line number, *args) :rtype: list """ components = kwargs.get("components", ()) max_first_line = kwargs.get("max_first_line", 50) errors = [] lineno = 1 if len(line) > max_first_line: errors.append(("M190", lineno, max_first_line, len(line))) if line.endswith("."): errors.append(("M191", lineno)) if ':' not in line: errors.append(("M110", lineno)) else: component, msg = line.split(':', 1) if component not in components: errors.append(("M111", lineno, component)) return errors
python
def _check_1st_line(line, **kwargs): """First line check. Check that the first line has a known component name followed by a colon and then a short description of the commit. :param line: first line :type line: str :param components: list of known component names :type line: list :param max_first_line: maximum length of the first line :type max_first_line: int :return: errors as in (code, line number, *args) :rtype: list """ components = kwargs.get("components", ()) max_first_line = kwargs.get("max_first_line", 50) errors = [] lineno = 1 if len(line) > max_first_line: errors.append(("M190", lineno, max_first_line, len(line))) if line.endswith("."): errors.append(("M191", lineno)) if ':' not in line: errors.append(("M110", lineno)) else: component, msg = line.split(':', 1) if component not in components: errors.append(("M111", lineno, component)) return errors
[ "def", "_check_1st_line", "(", "line", ",", "*", "*", "kwargs", ")", ":", "components", "=", "kwargs", ".", "get", "(", "\"components\"", ",", "(", ")", ")", "max_first_line", "=", "kwargs", ".", "get", "(", "\"max_first_line\"", ",", "50", ")", "errors"...
First line check. Check that the first line has a known component name followed by a colon and then a short description of the commit. :param line: first line :type line: str :param components: list of known component names :type line: list :param max_first_line: maximum length of the first line :type max_first_line: int :return: errors as in (code, line number, *args) :rtype: list
[ "First", "line", "check", "." ]
9124f8f55b15547fef08c6c43cabced314e70674
https://github.com/inveniosoftware/kwalitee/blob/9124f8f55b15547fef08c6c43cabced314e70674/kwalitee/kwalitee.py#L92-L126
train
55,245
inveniosoftware/kwalitee
kwalitee/kwalitee.py
_check_bullets
def _check_bullets(lines, **kwargs): """Check that the bullet point list is well formatted. Each bullet point shall have one space before and after it. The bullet character is the "*" and there is no space before it but one after it meaning the next line are starting with two blanks spaces to respect the indentation. :param lines: all the lines of the message :type lines: list :param max_lengths: maximum length of any line. (Default 72) :return: errors as in (code, line number, *args) :rtype: list """ max_length = kwargs.get("max_length", 72) labels = {l for l, _ in kwargs.get("commit_msg_labels", tuple())} def _strip_ticket_directives(line): return re.sub(r'( \([^)]*\)){1,}$', '', line) errors = [] missed_lines = [] skipped = [] for (i, line) in enumerate(lines[1:]): if line.startswith('*'): dot_found = False if len(missed_lines) > 0: errors.append(("M130", i + 2)) if lines[i].strip() != '': errors.append(("M120", i + 2)) if _strip_ticket_directives(line).endswith('.'): dot_found = True label = _re_bullet_label.search(line) if label and label.group('label') not in labels: errors.append(("M122", i + 2, label.group('label'))) for (j, indented) in enumerate(lines[i + 2:]): if indented.strip() == '': break if not re.search(r"^ {2}\S", indented): errors.append(("M121", i + j + 3)) else: skipped.append(i + j + 1) stripped_line = _strip_ticket_directives(indented) if stripped_line.endswith('.'): dot_found = True elif stripped_line.strip(): dot_found = False if not dot_found: errors.append(("M123", i + 2)) elif i not in skipped and line.strip(): missed_lines.append((i + 2, line)) if len(line) > max_length: errors.append(("M190", i + 2, max_length, len(line))) return errors, missed_lines
python
def _check_bullets(lines, **kwargs): """Check that the bullet point list is well formatted. Each bullet point shall have one space before and after it. The bullet character is the "*" and there is no space before it but one after it meaning the next line are starting with two blanks spaces to respect the indentation. :param lines: all the lines of the message :type lines: list :param max_lengths: maximum length of any line. (Default 72) :return: errors as in (code, line number, *args) :rtype: list """ max_length = kwargs.get("max_length", 72) labels = {l for l, _ in kwargs.get("commit_msg_labels", tuple())} def _strip_ticket_directives(line): return re.sub(r'( \([^)]*\)){1,}$', '', line) errors = [] missed_lines = [] skipped = [] for (i, line) in enumerate(lines[1:]): if line.startswith('*'): dot_found = False if len(missed_lines) > 0: errors.append(("M130", i + 2)) if lines[i].strip() != '': errors.append(("M120", i + 2)) if _strip_ticket_directives(line).endswith('.'): dot_found = True label = _re_bullet_label.search(line) if label and label.group('label') not in labels: errors.append(("M122", i + 2, label.group('label'))) for (j, indented) in enumerate(lines[i + 2:]): if indented.strip() == '': break if not re.search(r"^ {2}\S", indented): errors.append(("M121", i + j + 3)) else: skipped.append(i + j + 1) stripped_line = _strip_ticket_directives(indented) if stripped_line.endswith('.'): dot_found = True elif stripped_line.strip(): dot_found = False if not dot_found: errors.append(("M123", i + 2)) elif i not in skipped and line.strip(): missed_lines.append((i + 2, line)) if len(line) > max_length: errors.append(("M190", i + 2, max_length, len(line))) return errors, missed_lines
[ "def", "_check_bullets", "(", "lines", ",", "*", "*", "kwargs", ")", ":", "max_length", "=", "kwargs", ".", "get", "(", "\"max_length\"", ",", "72", ")", "labels", "=", "{", "l", "for", "l", ",", "_", "in", "kwargs", ".", "get", "(", "\"commit_msg_la...
Check that the bullet point list is well formatted. Each bullet point shall have one space before and after it. The bullet character is the "*" and there is no space before it but one after it meaning the next line are starting with two blanks spaces to respect the indentation. :param lines: all the lines of the message :type lines: list :param max_lengths: maximum length of any line. (Default 72) :return: errors as in (code, line number, *args) :rtype: list
[ "Check", "that", "the", "bullet", "point", "list", "is", "well", "formatted", "." ]
9124f8f55b15547fef08c6c43cabced314e70674
https://github.com/inveniosoftware/kwalitee/blob/9124f8f55b15547fef08c6c43cabced314e70674/kwalitee/kwalitee.py#L129-L190
train
55,246
inveniosoftware/kwalitee
kwalitee/kwalitee.py
_check_signatures
def _check_signatures(lines, **kwargs): """Check that the signatures are valid. There should be at least three signatures. If not, one of them should be a trusted developer/reviewer. Formatting supported being: [signature] full name <email@address> :param lines: lines (lineno, content) to verify. :type lines: list :param signatures: list of supported signature :type signatures: list :param alt_signatures: list of alternative signatures, not counted :type alt_signatures: list :param trusted: list of trusted reviewers, the e-mail address. :type trusted: list :param min_reviewers: minimal number of reviewers needed. (Default 3) :type min_reviewers: int :return: errors as in (code, line number, *args) :rtype: list """ trusted = kwargs.get("trusted", ()) signatures = tuple(kwargs.get("signatures", ())) alt_signatures = tuple(kwargs.get("alt_signatures", ())) min_reviewers = kwargs.get("min_reviewers", 3) matching = [] errors = [] signatures += alt_signatures test_signatures = re.compile("^({0})".format("|".join(signatures))) test_alt_signatures = re.compile("^({0})".format("|".join(alt_signatures))) for i, line in lines: if signatures and test_signatures.search(line): if line.endswith("."): errors.append(("M191", i)) if not alt_signatures or not test_alt_signatures.search(line): matching.append(line) else: errors.append(("M102", i)) if not matching: errors.append(("M101", 1)) errors.append(("M100", 1)) elif len(matching) < min_reviewers: pattern = re.compile('|'.join(map(lambda x: '<' + re.escape(x) + '>', trusted))) trusted_matching = list(filter(None, map(pattern.search, matching))) if len(trusted_matching) == 0: errors.append(("M100", 1)) return errors
python
def _check_signatures(lines, **kwargs): """Check that the signatures are valid. There should be at least three signatures. If not, one of them should be a trusted developer/reviewer. Formatting supported being: [signature] full name <email@address> :param lines: lines (lineno, content) to verify. :type lines: list :param signatures: list of supported signature :type signatures: list :param alt_signatures: list of alternative signatures, not counted :type alt_signatures: list :param trusted: list of trusted reviewers, the e-mail address. :type trusted: list :param min_reviewers: minimal number of reviewers needed. (Default 3) :type min_reviewers: int :return: errors as in (code, line number, *args) :rtype: list """ trusted = kwargs.get("trusted", ()) signatures = tuple(kwargs.get("signatures", ())) alt_signatures = tuple(kwargs.get("alt_signatures", ())) min_reviewers = kwargs.get("min_reviewers", 3) matching = [] errors = [] signatures += alt_signatures test_signatures = re.compile("^({0})".format("|".join(signatures))) test_alt_signatures = re.compile("^({0})".format("|".join(alt_signatures))) for i, line in lines: if signatures and test_signatures.search(line): if line.endswith("."): errors.append(("M191", i)) if not alt_signatures or not test_alt_signatures.search(line): matching.append(line) else: errors.append(("M102", i)) if not matching: errors.append(("M101", 1)) errors.append(("M100", 1)) elif len(matching) < min_reviewers: pattern = re.compile('|'.join(map(lambda x: '<' + re.escape(x) + '>', trusted))) trusted_matching = list(filter(None, map(pattern.search, matching))) if len(trusted_matching) == 0: errors.append(("M100", 1)) return errors
[ "def", "_check_signatures", "(", "lines", ",", "*", "*", "kwargs", ")", ":", "trusted", "=", "kwargs", ".", "get", "(", "\"trusted\"", ",", "(", ")", ")", "signatures", "=", "tuple", "(", "kwargs", ".", "get", "(", "\"signatures\"", ",", "(", ")", ")...
Check that the signatures are valid. There should be at least three signatures. If not, one of them should be a trusted developer/reviewer. Formatting supported being: [signature] full name <email@address> :param lines: lines (lineno, content) to verify. :type lines: list :param signatures: list of supported signature :type signatures: list :param alt_signatures: list of alternative signatures, not counted :type alt_signatures: list :param trusted: list of trusted reviewers, the e-mail address. :type trusted: list :param min_reviewers: minimal number of reviewers needed. (Default 3) :type min_reviewers: int :return: errors as in (code, line number, *args) :rtype: list
[ "Check", "that", "the", "signatures", "are", "valid", "." ]
9124f8f55b15547fef08c6c43cabced314e70674
https://github.com/inveniosoftware/kwalitee/blob/9124f8f55b15547fef08c6c43cabced314e70674/kwalitee/kwalitee.py#L193-L245
train
55,247
inveniosoftware/kwalitee
kwalitee/kwalitee.py
check_message
def check_message(message, **kwargs): """Check the message format. Rules: - the first line must start by a component name - and a short description (52 chars), - then bullet points are expected - and finally signatures. :param components: compontents, e.g. ``('auth', 'utils', 'misc')`` :type components: `list` :param signatures: signatures, e.g. ``('Signed-off-by', 'Reviewed-by')`` :type signatures: `list` :param alt_signatures: alternative signatures, e.g. ``('Tested-by',)`` :type alt_signatures: `list` :param trusted: optional list of reviewers, e.g. ``('john.doe@foo.org',)`` :type trusted: `list` :param max_length: optional maximum line length (by default: 72) :type max_length: int :param max_first_line: optional maximum first line length (by default: 50) :type max_first_line: int :param allow_empty: optional way to allow empty message (by default: False) :type allow_empty: bool :return: errors sorted by line number :rtype: `list` """ if kwargs.pop("allow_empty", False): if not message or message.isspace(): return [] lines = re.split(r"\r\n|\r|\n", message) errors = _check_1st_line(lines[0], **kwargs) err, signature_lines = _check_bullets(lines, **kwargs) errors += err errors += _check_signatures(signature_lines, **kwargs) def _format(code, lineno, args): return "{0}: {1} {2}".format(lineno, code, _messages_codes[code].format(*args)) return list(map(lambda x: _format(x[0], x[1], x[2:]), sorted(errors, key=lambda x: x[0])))
python
def check_message(message, **kwargs): """Check the message format. Rules: - the first line must start by a component name - and a short description (52 chars), - then bullet points are expected - and finally signatures. :param components: compontents, e.g. ``('auth', 'utils', 'misc')`` :type components: `list` :param signatures: signatures, e.g. ``('Signed-off-by', 'Reviewed-by')`` :type signatures: `list` :param alt_signatures: alternative signatures, e.g. ``('Tested-by',)`` :type alt_signatures: `list` :param trusted: optional list of reviewers, e.g. ``('john.doe@foo.org',)`` :type trusted: `list` :param max_length: optional maximum line length (by default: 72) :type max_length: int :param max_first_line: optional maximum first line length (by default: 50) :type max_first_line: int :param allow_empty: optional way to allow empty message (by default: False) :type allow_empty: bool :return: errors sorted by line number :rtype: `list` """ if kwargs.pop("allow_empty", False): if not message or message.isspace(): return [] lines = re.split(r"\r\n|\r|\n", message) errors = _check_1st_line(lines[0], **kwargs) err, signature_lines = _check_bullets(lines, **kwargs) errors += err errors += _check_signatures(signature_lines, **kwargs) def _format(code, lineno, args): return "{0}: {1} {2}".format(lineno, code, _messages_codes[code].format(*args)) return list(map(lambda x: _format(x[0], x[1], x[2:]), sorted(errors, key=lambda x: x[0])))
[ "def", "check_message", "(", "message", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ".", "pop", "(", "\"allow_empty\"", ",", "False", ")", ":", "if", "not", "message", "or", "message", ".", "isspace", "(", ")", ":", "return", "[", "]", "lines"...
Check the message format. Rules: - the first line must start by a component name - and a short description (52 chars), - then bullet points are expected - and finally signatures. :param components: compontents, e.g. ``('auth', 'utils', 'misc')`` :type components: `list` :param signatures: signatures, e.g. ``('Signed-off-by', 'Reviewed-by')`` :type signatures: `list` :param alt_signatures: alternative signatures, e.g. ``('Tested-by',)`` :type alt_signatures: `list` :param trusted: optional list of reviewers, e.g. ``('john.doe@foo.org',)`` :type trusted: `list` :param max_length: optional maximum line length (by default: 72) :type max_length: int :param max_first_line: optional maximum first line length (by default: 50) :type max_first_line: int :param allow_empty: optional way to allow empty message (by default: False) :type allow_empty: bool :return: errors sorted by line number :rtype: `list`
[ "Check", "the", "message", "format", "." ]
9124f8f55b15547fef08c6c43cabced314e70674
https://github.com/inveniosoftware/kwalitee/blob/9124f8f55b15547fef08c6c43cabced314e70674/kwalitee/kwalitee.py#L248-L291
train
55,248
inveniosoftware/kwalitee
kwalitee/kwalitee.py
_register_pyflakes_check
def _register_pyflakes_check(): """Register the pyFlakes checker into PEP8 set of checks.""" from flake8_isort import Flake8Isort from flake8_blind_except import check_blind_except # Resolving conflicts between pep8 and pyflakes. codes = { "UnusedImport": "F401", "ImportShadowedByLoopVar": "F402", "ImportStarUsed": "F403", "LateFutureImport": "F404", "Redefined": "F801", "RedefinedInListComp": "F812", "UndefinedName": "F821", "UndefinedExport": "F822", "UndefinedLocal": "F823", "DuplicateArgument": "F831", "UnusedVariable": "F841", } for name, obj in vars(pyflakes.messages).items(): if name[0].isupper() and obj.message: obj.tpl = "{0} {1}".format(codes.get(name, "F999"), obj.message) pep8.register_check(_PyFlakesChecker, codes=['F']) # FIXME parser hack parser = pep8.get_parser('', '') Flake8Isort.add_options(parser) options, args = parser.parse_args([]) # end of hack pep8.register_check(Flake8Isort, codes=['I']) pep8.register_check(check_blind_except, codes=['B90'])
python
def _register_pyflakes_check(): """Register the pyFlakes checker into PEP8 set of checks.""" from flake8_isort import Flake8Isort from flake8_blind_except import check_blind_except # Resolving conflicts between pep8 and pyflakes. codes = { "UnusedImport": "F401", "ImportShadowedByLoopVar": "F402", "ImportStarUsed": "F403", "LateFutureImport": "F404", "Redefined": "F801", "RedefinedInListComp": "F812", "UndefinedName": "F821", "UndefinedExport": "F822", "UndefinedLocal": "F823", "DuplicateArgument": "F831", "UnusedVariable": "F841", } for name, obj in vars(pyflakes.messages).items(): if name[0].isupper() and obj.message: obj.tpl = "{0} {1}".format(codes.get(name, "F999"), obj.message) pep8.register_check(_PyFlakesChecker, codes=['F']) # FIXME parser hack parser = pep8.get_parser('', '') Flake8Isort.add_options(parser) options, args = parser.parse_args([]) # end of hack pep8.register_check(Flake8Isort, codes=['I']) pep8.register_check(check_blind_except, codes=['B90'])
[ "def", "_register_pyflakes_check", "(", ")", ":", "from", "flake8_isort", "import", "Flake8Isort", "from", "flake8_blind_except", "import", "check_blind_except", "# Resolving conflicts between pep8 and pyflakes.", "codes", "=", "{", "\"UnusedImport\"", ":", "\"F401\"", ",", ...
Register the pyFlakes checker into PEP8 set of checks.
[ "Register", "the", "pyFlakes", "checker", "into", "PEP8", "set", "of", "checks", "." ]
9124f8f55b15547fef08c6c43cabced314e70674
https://github.com/inveniosoftware/kwalitee/blob/9124f8f55b15547fef08c6c43cabced314e70674/kwalitee/kwalitee.py#L307-L338
train
55,249
inveniosoftware/kwalitee
kwalitee/kwalitee.py
check_pydocstyle
def check_pydocstyle(filename, **kwargs): """Perform static analysis on the given file docstrings. :param filename: path of file to check. :type filename: str :param ignore: codes to ignore, e.g. ('D400',) :type ignore: `list` :param match: regex the filename has to match to be checked :type match: str :param match_dir: regex everydir in path should match to be checked :type match_dir: str :return: errors :rtype: `list` .. seealso:: `PyCQA/pydocstyle <https://github.com/GreenSteam/pydocstyle/>`_ """ ignore = kwargs.get("ignore") match = kwargs.get("match", None) match_dir = kwargs.get("match_dir", None) errors = [] if match and not re.match(match, os.path.basename(filename)): return errors if match_dir: # FIXME here the full path is checked, be sure, if match_dir doesn't # match the path (usually temporary) before the actual application path # it may not run the checks when it should have. path = os.path.split(os.path.abspath(filename))[0] while path != "/": path, dirname = os.path.split(path) if not re.match(match_dir, dirname): return errors checker = pydocstyle.PEP257Checker() with open(filename) as fp: try: for error in checker.check_source(fp.read(), filename): if ignore is None or error.code not in ignore: # Removing the colon ':' after the error code message = re.sub("(D[0-9]{3}): ?(.*)", r"\1 \2", error.message) errors.append("{0}: {1}".format(error.line, message)) except tokenize.TokenError as e: errors.append("{1}:{2} {0}".format(e.args[0], *e.args[1])) except pydocstyle.AllError as e: errors.append(str(e)) return errors
python
def check_pydocstyle(filename, **kwargs): """Perform static analysis on the given file docstrings. :param filename: path of file to check. :type filename: str :param ignore: codes to ignore, e.g. ('D400',) :type ignore: `list` :param match: regex the filename has to match to be checked :type match: str :param match_dir: regex everydir in path should match to be checked :type match_dir: str :return: errors :rtype: `list` .. seealso:: `PyCQA/pydocstyle <https://github.com/GreenSteam/pydocstyle/>`_ """ ignore = kwargs.get("ignore") match = kwargs.get("match", None) match_dir = kwargs.get("match_dir", None) errors = [] if match and not re.match(match, os.path.basename(filename)): return errors if match_dir: # FIXME here the full path is checked, be sure, if match_dir doesn't # match the path (usually temporary) before the actual application path # it may not run the checks when it should have. path = os.path.split(os.path.abspath(filename))[0] while path != "/": path, dirname = os.path.split(path) if not re.match(match_dir, dirname): return errors checker = pydocstyle.PEP257Checker() with open(filename) as fp: try: for error in checker.check_source(fp.read(), filename): if ignore is None or error.code not in ignore: # Removing the colon ':' after the error code message = re.sub("(D[0-9]{3}): ?(.*)", r"\1 \2", error.message) errors.append("{0}: {1}".format(error.line, message)) except tokenize.TokenError as e: errors.append("{1}:{2} {0}".format(e.args[0], *e.args[1])) except pydocstyle.AllError as e: errors.append(str(e)) return errors
[ "def", "check_pydocstyle", "(", "filename", ",", "*", "*", "kwargs", ")", ":", "ignore", "=", "kwargs", ".", "get", "(", "\"ignore\"", ")", "match", "=", "kwargs", ".", "get", "(", "\"match\"", ",", "None", ")", "match_dir", "=", "kwargs", ".", "get", ...
Perform static analysis on the given file docstrings. :param filename: path of file to check. :type filename: str :param ignore: codes to ignore, e.g. ('D400',) :type ignore: `list` :param match: regex the filename has to match to be checked :type match: str :param match_dir: regex everydir in path should match to be checked :type match_dir: str :return: errors :rtype: `list` .. seealso:: `PyCQA/pydocstyle <https://github.com/GreenSteam/pydocstyle/>`_
[ "Perform", "static", "analysis", "on", "the", "given", "file", "docstrings", "." ]
9124f8f55b15547fef08c6c43cabced314e70674
https://github.com/inveniosoftware/kwalitee/blob/9124f8f55b15547fef08c6c43cabced314e70674/kwalitee/kwalitee.py#L405-L457
train
55,250
inveniosoftware/kwalitee
kwalitee/kwalitee.py
check_license
def check_license(filename, **kwargs): """Perform a license check on the given file. The license format should be commented using # and live at the top of the file. Also, the year should be the current one. :param filename: path of file to check. :type filename: str :param year: default current year :type year: int :param ignore: codes to ignore, e.g. ``('L100', 'L101')`` :type ignore: `list` :param python_style: False for JavaScript or CSS files :type python_style: bool :return: errors :rtype: `list` """ year = kwargs.pop("year", datetime.now().year) python_style = kwargs.pop("python_style", True) ignores = kwargs.get("ignore") template = "{0}: {1} {2}" if python_style: re_comment = re.compile(r"^#.*|\{#.*|[\r\n]+$") starter = "# " else: re_comment = re.compile(r"^/\*.*| \*.*|[\r\n]+$") starter = " *" errors = [] lines = [] file_is_empty = False license = "" lineno = 0 try: with codecs.open(filename, "r", "utf-8") as fp: line = fp.readline() blocks = [] while re_comment.match(line): if line.startswith(starter): line = line[len(starter):].lstrip() blocks.append(line) lines.append((lineno, line.strip())) lineno, line = lineno + 1, fp.readline() file_is_empty = line == "" license = "".join(blocks) except UnicodeDecodeError: errors.append((lineno + 1, "L190", "utf-8")) license = "" if file_is_empty and not license.strip(): return errors match_year = _re_copyright_year.search(license) if match_year is None: errors.append((lineno + 1, "L101")) elif int(match_year.group("year")) != year: theline = match_year.group(0) lno = lineno for no, l in lines: if theline.strip() == l: lno = no break errors.append((lno + 1, "L102", year, match_year.group("year"))) else: program_match = _re_program.search(license) program_2_match = _re_program_2.search(license) program_3_match = _re_program_3.search(license) if program_match is None: errors.append((lineno, "L100")) elif (program_2_match is None or program_3_match is None or (program_match.group("program").upper() != program_2_match.group("program").upper() != program_3_match.group("program").upper())): errors.append((lineno, "L103")) def _format_error(lineno, code, *args): return template.format(lineno, code, _licenses_codes[code].format(*args)) def _filter_codes(error): if not ignores or error[1] not in ignores: return error return list(map(lambda x: _format_error(*x), filter(_filter_codes, errors)))
python
def check_license(filename, **kwargs): """Perform a license check on the given file. The license format should be commented using # and live at the top of the file. Also, the year should be the current one. :param filename: path of file to check. :type filename: str :param year: default current year :type year: int :param ignore: codes to ignore, e.g. ``('L100', 'L101')`` :type ignore: `list` :param python_style: False for JavaScript or CSS files :type python_style: bool :return: errors :rtype: `list` """ year = kwargs.pop("year", datetime.now().year) python_style = kwargs.pop("python_style", True) ignores = kwargs.get("ignore") template = "{0}: {1} {2}" if python_style: re_comment = re.compile(r"^#.*|\{#.*|[\r\n]+$") starter = "# " else: re_comment = re.compile(r"^/\*.*| \*.*|[\r\n]+$") starter = " *" errors = [] lines = [] file_is_empty = False license = "" lineno = 0 try: with codecs.open(filename, "r", "utf-8") as fp: line = fp.readline() blocks = [] while re_comment.match(line): if line.startswith(starter): line = line[len(starter):].lstrip() blocks.append(line) lines.append((lineno, line.strip())) lineno, line = lineno + 1, fp.readline() file_is_empty = line == "" license = "".join(blocks) except UnicodeDecodeError: errors.append((lineno + 1, "L190", "utf-8")) license = "" if file_is_empty and not license.strip(): return errors match_year = _re_copyright_year.search(license) if match_year is None: errors.append((lineno + 1, "L101")) elif int(match_year.group("year")) != year: theline = match_year.group(0) lno = lineno for no, l in lines: if theline.strip() == l: lno = no break errors.append((lno + 1, "L102", year, match_year.group("year"))) else: program_match = _re_program.search(license) program_2_match = _re_program_2.search(license) program_3_match = _re_program_3.search(license) if program_match is None: errors.append((lineno, "L100")) elif (program_2_match is None or program_3_match is None or (program_match.group("program").upper() != program_2_match.group("program").upper() != program_3_match.group("program").upper())): errors.append((lineno, "L103")) def _format_error(lineno, code, *args): return template.format(lineno, code, _licenses_codes[code].format(*args)) def _filter_codes(error): if not ignores or error[1] not in ignores: return error return list(map(lambda x: _format_error(*x), filter(_filter_codes, errors)))
[ "def", "check_license", "(", "filename", ",", "*", "*", "kwargs", ")", ":", "year", "=", "kwargs", ".", "pop", "(", "\"year\"", ",", "datetime", ".", "now", "(", ")", ".", "year", ")", "python_style", "=", "kwargs", ".", "pop", "(", "\"python_style\"",...
Perform a license check on the given file. The license format should be commented using # and live at the top of the file. Also, the year should be the current one. :param filename: path of file to check. :type filename: str :param year: default current year :type year: int :param ignore: codes to ignore, e.g. ``('L100', 'L101')`` :type ignore: `list` :param python_style: False for JavaScript or CSS files :type python_style: bool :return: errors :rtype: `list`
[ "Perform", "a", "license", "check", "on", "the", "given", "file", "." ]
9124f8f55b15547fef08c6c43cabced314e70674
https://github.com/inveniosoftware/kwalitee/blob/9124f8f55b15547fef08c6c43cabced314e70674/kwalitee/kwalitee.py#L460-L547
train
55,251
inveniosoftware/kwalitee
kwalitee/kwalitee.py
get_options
def get_options(config=None): """Build the options from the config object.""" if config is None: from . import config config.get = lambda key, default=None: getattr(config, key, default) base = { "components": config.get("COMPONENTS"), "signatures": config.get("SIGNATURES"), "commit_msg_template": config.get("COMMIT_MSG_TEMPLATE"), "commit_msg_labels": config.get("COMMIT_MSG_LABELS"), "alt_signatures": config.get("ALT_SIGNATURES"), "trusted": config.get("TRUSTED_DEVELOPERS"), "pep8": config.get("CHECK_PEP8", True), "pydocstyle": config.get("CHECK_PYDOCSTYLE", True), "license": config.get("CHECK_LICENSE", True), "pyflakes": config.get("CHECK_PYFLAKES", True), "ignore": config.get("IGNORE"), "select": config.get("SELECT"), "match": config.get("PYDOCSTYLE_MATCH"), "match_dir": config.get("PYDOCSTYLE_MATCH_DIR"), "min_reviewers": config.get("MIN_REVIEWERS"), "colors": config.get("COLORS", True), "excludes": config.get("EXCLUDES", []), "authors": config.get("AUTHORS"), "exclude_author_names": config.get("EXCLUDE_AUTHOR_NAMES"), } options = {} for k, v in base.items(): if v is not None: options[k] = v return options
python
def get_options(config=None): """Build the options from the config object.""" if config is None: from . import config config.get = lambda key, default=None: getattr(config, key, default) base = { "components": config.get("COMPONENTS"), "signatures": config.get("SIGNATURES"), "commit_msg_template": config.get("COMMIT_MSG_TEMPLATE"), "commit_msg_labels": config.get("COMMIT_MSG_LABELS"), "alt_signatures": config.get("ALT_SIGNATURES"), "trusted": config.get("TRUSTED_DEVELOPERS"), "pep8": config.get("CHECK_PEP8", True), "pydocstyle": config.get("CHECK_PYDOCSTYLE", True), "license": config.get("CHECK_LICENSE", True), "pyflakes": config.get("CHECK_PYFLAKES", True), "ignore": config.get("IGNORE"), "select": config.get("SELECT"), "match": config.get("PYDOCSTYLE_MATCH"), "match_dir": config.get("PYDOCSTYLE_MATCH_DIR"), "min_reviewers": config.get("MIN_REVIEWERS"), "colors": config.get("COLORS", True), "excludes": config.get("EXCLUDES", []), "authors": config.get("AUTHORS"), "exclude_author_names": config.get("EXCLUDE_AUTHOR_NAMES"), } options = {} for k, v in base.items(): if v is not None: options[k] = v return options
[ "def", "get_options", "(", "config", "=", "None", ")", ":", "if", "config", "is", "None", ":", "from", ".", "import", "config", "config", ".", "get", "=", "lambda", "key", ",", "default", "=", "None", ":", "getattr", "(", "config", ",", "key", ",", ...
Build the options from the config object.
[ "Build", "the", "options", "from", "the", "config", "object", "." ]
9124f8f55b15547fef08c6c43cabced314e70674
https://github.com/inveniosoftware/kwalitee/blob/9124f8f55b15547fef08c6c43cabced314e70674/kwalitee/kwalitee.py#L640-L671
train
55,252
inveniosoftware/kwalitee
kwalitee/kwalitee.py
_PyFlakesChecker.run
def run(self): """Yield the error messages.""" for msg in self.messages: col = getattr(msg, 'col', 0) yield msg.lineno, col, (msg.tpl % msg.message_args), msg.__class__
python
def run(self): """Yield the error messages.""" for msg in self.messages: col = getattr(msg, 'col', 0) yield msg.lineno, col, (msg.tpl % msg.message_args), msg.__class__
[ "def", "run", "(", "self", ")", ":", "for", "msg", "in", "self", ".", "messages", ":", "col", "=", "getattr", "(", "msg", ",", "'col'", ",", "0", ")", "yield", "msg", ".", "lineno", ",", "col", ",", "(", "msg", ".", "tpl", "%", "msg", ".", "m...
Yield the error messages.
[ "Yield", "the", "error", "messages", "." ]
9124f8f55b15547fef08c6c43cabced314e70674
https://github.com/inveniosoftware/kwalitee/blob/9124f8f55b15547fef08c6c43cabced314e70674/kwalitee/kwalitee.py#L300-L304
train
55,253
inveniosoftware/kwalitee
kwalitee/kwalitee.py
_Report.error
def error(self, line_number, offset, text, check): """Run the checks and collect the errors.""" code = super(_Report, self).error(line_number, offset, text, check) if code: self.errors.append((line_number, offset + 1, code, text, check))
python
def error(self, line_number, offset, text, check): """Run the checks and collect the errors.""" code = super(_Report, self).error(line_number, offset, text, check) if code: self.errors.append((line_number, offset + 1, code, text, check))
[ "def", "error", "(", "self", ",", "line_number", ",", "offset", ",", "text", ",", "check", ")", ":", "code", "=", "super", "(", "_Report", ",", "self", ")", ".", "error", "(", "line_number", ",", "offset", ",", "text", ",", "check", ")", "if", "cod...
Run the checks and collect the errors.
[ "Run", "the", "checks", "and", "collect", "the", "errors", "." ]
9124f8f55b15547fef08c6c43cabced314e70674
https://github.com/inveniosoftware/kwalitee/blob/9124f8f55b15547fef08c6c43cabced314e70674/kwalitee/kwalitee.py#L353-L357
train
55,254
toumorokoshi/sprinter
sprinter/lib/__init__.py
prompt
def prompt(prompt_string, default=None, secret=False, boolean=False, bool_type=None): """ Prompt user for a string, with a default value * secret converts to password prompt * boolean converts return value to boolean, checking for starting with a Y """ if boolean or bool_type in BOOLEAN_DEFAULTS: if bool_type is None: bool_type = 'y_n' default_msg = BOOLEAN_DEFAULTS[bool_type][is_affirmative(default)] else: default_msg = " (default {val}): " prompt_string += (default_msg.format(val=default) if default else ": ") if secret: val = getpass(prompt_string) else: val = input(prompt_string) val = (val if val else default) if boolean: val = val.lower().startswith('y') return val
python
def prompt(prompt_string, default=None, secret=False, boolean=False, bool_type=None): """ Prompt user for a string, with a default value * secret converts to password prompt * boolean converts return value to boolean, checking for starting with a Y """ if boolean or bool_type in BOOLEAN_DEFAULTS: if bool_type is None: bool_type = 'y_n' default_msg = BOOLEAN_DEFAULTS[bool_type][is_affirmative(default)] else: default_msg = " (default {val}): " prompt_string += (default_msg.format(val=default) if default else ": ") if secret: val = getpass(prompt_string) else: val = input(prompt_string) val = (val if val else default) if boolean: val = val.lower().startswith('y') return val
[ "def", "prompt", "(", "prompt_string", ",", "default", "=", "None", ",", "secret", "=", "False", ",", "boolean", "=", "False", ",", "bool_type", "=", "None", ")", ":", "if", "boolean", "or", "bool_type", "in", "BOOLEAN_DEFAULTS", ":", "if", "bool_type", ...
Prompt user for a string, with a default value * secret converts to password prompt * boolean converts return value to boolean, checking for starting with a Y
[ "Prompt", "user", "for", "a", "string", "with", "a", "default", "value" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/lib/__init__.py#L32-L53
train
55,255
BreakingBytes/UncertaintyWrapper
uncertainty_wrapper/core.py
jflatten
def jflatten(j): """ Flatten 3_D Jacobian into 2-D. """ nobs, nf, nargs = j.shape nrows, ncols = nf * nobs, nargs * nobs jflat = np.zeros((nrows, ncols)) for n in xrange(nobs): r, c = n * nf, n * nargs jflat[r:(r + nf), c:(c + nargs)] = j[n] return jflat
python
def jflatten(j): """ Flatten 3_D Jacobian into 2-D. """ nobs, nf, nargs = j.shape nrows, ncols = nf * nobs, nargs * nobs jflat = np.zeros((nrows, ncols)) for n in xrange(nobs): r, c = n * nf, n * nargs jflat[r:(r + nf), c:(c + nargs)] = j[n] return jflat
[ "def", "jflatten", "(", "j", ")", ":", "nobs", ",", "nf", ",", "nargs", "=", "j", ".", "shape", "nrows", ",", "ncols", "=", "nf", "*", "nobs", ",", "nargs", "*", "nobs", "jflat", "=", "np", ".", "zeros", "(", "(", "nrows", ",", "ncols", ")", ...
Flatten 3_D Jacobian into 2-D.
[ "Flatten", "3_D", "Jacobian", "into", "2", "-", "D", "." ]
b2431588fb6c1cf6f2a54e2afc9bfa8e10067bd0
https://github.com/BreakingBytes/UncertaintyWrapper/blob/b2431588fb6c1cf6f2a54e2afc9bfa8e10067bd0/uncertainty_wrapper/core.py#L104-L114
train
55,256
BreakingBytes/UncertaintyWrapper
uncertainty_wrapper/core.py
jtosparse
def jtosparse(j): """ Generate sparse matrix coordinates from 3-D Jacobian. """ data = j.flatten().tolist() nobs, nf, nargs = j.shape indices = zip(*[(r, c) for n in xrange(nobs) for r in xrange(n * nf, (n + 1) * nf) for c in xrange(n * nargs, (n + 1) * nargs)]) return csr_matrix((data, indices), shape=(nobs * nf, nobs * nargs))
python
def jtosparse(j): """ Generate sparse matrix coordinates from 3-D Jacobian. """ data = j.flatten().tolist() nobs, nf, nargs = j.shape indices = zip(*[(r, c) for n in xrange(nobs) for r in xrange(n * nf, (n + 1) * nf) for c in xrange(n * nargs, (n + 1) * nargs)]) return csr_matrix((data, indices), shape=(nobs * nf, nobs * nargs))
[ "def", "jtosparse", "(", "j", ")", ":", "data", "=", "j", ".", "flatten", "(", ")", ".", "tolist", "(", ")", "nobs", ",", "nf", ",", "nargs", "=", "j", ".", "shape", "indices", "=", "zip", "(", "*", "[", "(", "r", ",", "c", ")", "for", "n",...
Generate sparse matrix coordinates from 3-D Jacobian.
[ "Generate", "sparse", "matrix", "coordinates", "from", "3", "-", "D", "Jacobian", "." ]
b2431588fb6c1cf6f2a54e2afc9bfa8e10067bd0
https://github.com/BreakingBytes/UncertaintyWrapper/blob/b2431588fb6c1cf6f2a54e2afc9bfa8e10067bd0/uncertainty_wrapper/core.py#L117-L126
train
55,257
KvasirSecurity/kvasirapi-python
KvasirAPI/jsonrpc/accounts.py
Accounts.upload_file
def upload_file(self, service_rec=None, host_service=None, filename=None, pw_data=None, f_type=None, add_to_evidence=True): """ Upload a password file :param service_rec: db.t_services.id :param host_service: db.t_hosts.id :param filename: Filename :param pw_data: Content of file :param f_type: Type of file :param add_to_evidence: True/False to add to t_evidence :return: (True/False, Response Message) """ return self.send.accounts_upload_file(service_rec, host_service, filename, pw_data, f_type, add_to_evidence)
python
def upload_file(self, service_rec=None, host_service=None, filename=None, pw_data=None, f_type=None, add_to_evidence=True): """ Upload a password file :param service_rec: db.t_services.id :param host_service: db.t_hosts.id :param filename: Filename :param pw_data: Content of file :param f_type: Type of file :param add_to_evidence: True/False to add to t_evidence :return: (True/False, Response Message) """ return self.send.accounts_upload_file(service_rec, host_service, filename, pw_data, f_type, add_to_evidence)
[ "def", "upload_file", "(", "self", ",", "service_rec", "=", "None", ",", "host_service", "=", "None", ",", "filename", "=", "None", ",", "pw_data", "=", "None", ",", "f_type", "=", "None", ",", "add_to_evidence", "=", "True", ")", ":", "return", "self", ...
Upload a password file :param service_rec: db.t_services.id :param host_service: db.t_hosts.id :param filename: Filename :param pw_data: Content of file :param f_type: Type of file :param add_to_evidence: True/False to add to t_evidence :return: (True/False, Response Message)
[ "Upload", "a", "password", "file" ]
ec8c5818bd5913f3afd150f25eaec6e7cc732f4c
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/jsonrpc/accounts.py#L86-L99
train
55,258
gtaylor/EVE-Market-Data-Structures
emds/formats/unified/unified_utils.py
parse_datetime
def parse_datetime(time_str): """ Wraps dateutil's parser function to set an explicit UTC timezone, and to make sure microseconds are 0. Unified Uploader format and EMK format bother don't use microseconds at all. :param str time_str: The date/time str to parse. :rtype: datetime.datetime :returns: A parsed, UTC datetime. """ try: return dateutil.parser.parse( time_str ).replace(microsecond=0).astimezone(UTC_TZINFO) except ValueError: # This was some kind of unrecognizable time string. raise ParseError("Invalid time string: %s" % time_str)
python
def parse_datetime(time_str): """ Wraps dateutil's parser function to set an explicit UTC timezone, and to make sure microseconds are 0. Unified Uploader format and EMK format bother don't use microseconds at all. :param str time_str: The date/time str to parse. :rtype: datetime.datetime :returns: A parsed, UTC datetime. """ try: return dateutil.parser.parse( time_str ).replace(microsecond=0).astimezone(UTC_TZINFO) except ValueError: # This was some kind of unrecognizable time string. raise ParseError("Invalid time string: %s" % time_str)
[ "def", "parse_datetime", "(", "time_str", ")", ":", "try", ":", "return", "dateutil", ".", "parser", ".", "parse", "(", "time_str", ")", ".", "replace", "(", "microsecond", "=", "0", ")", ".", "astimezone", "(", "UTC_TZINFO", ")", "except", "ValueError", ...
Wraps dateutil's parser function to set an explicit UTC timezone, and to make sure microseconds are 0. Unified Uploader format and EMK format bother don't use microseconds at all. :param str time_str: The date/time str to parse. :rtype: datetime.datetime :returns: A parsed, UTC datetime.
[ "Wraps", "dateutil", "s", "parser", "function", "to", "set", "an", "explicit", "UTC", "timezone", "and", "to", "make", "sure", "microseconds", "are", "0", ".", "Unified", "Uploader", "format", "and", "EMK", "format", "bother", "don", "t", "use", "microsecond...
77d69b24f2aada3aeff8fba3d75891bfba8fdcf3
https://github.com/gtaylor/EVE-Market-Data-Structures/blob/77d69b24f2aada3aeff8fba3d75891bfba8fdcf3/emds/formats/unified/unified_utils.py#L46-L62
train
55,259
klahnakoski/mo-files
mo_files/__init__.py
File.backup_name
def backup_name(self, timestamp=None): """ RETURN A FILENAME THAT CAN SERVE AS A BACKUP FOR THIS FILE """ suffix = datetime2string(coalesce(timestamp, datetime.now()), "%Y%m%d_%H%M%S") return File.add_suffix(self._filename, suffix)
python
def backup_name(self, timestamp=None): """ RETURN A FILENAME THAT CAN SERVE AS A BACKUP FOR THIS FILE """ suffix = datetime2string(coalesce(timestamp, datetime.now()), "%Y%m%d_%H%M%S") return File.add_suffix(self._filename, suffix)
[ "def", "backup_name", "(", "self", ",", "timestamp", "=", "None", ")", ":", "suffix", "=", "datetime2string", "(", "coalesce", "(", "timestamp", ",", "datetime", ".", "now", "(", ")", ")", ",", "\"%Y%m%d_%H%M%S\"", ")", "return", "File", ".", "add_suffix",...
RETURN A FILENAME THAT CAN SERVE AS A BACKUP FOR THIS FILE
[ "RETURN", "A", "FILENAME", "THAT", "CAN", "SERVE", "AS", "A", "BACKUP", "FOR", "THIS", "FILE" ]
f6974a997cdc9fdabccb60c19edee13356a5787a
https://github.com/klahnakoski/mo-files/blob/f6974a997cdc9fdabccb60c19edee13356a5787a/mo_files/__init__.py#L204-L209
train
55,260
klahnakoski/mo-files
mo_files/__init__.py
File.append
def append(self, content, encoding='utf8'): """ add a line to file """ if not self.parent.exists: self.parent.create() with open(self._filename, "ab") as output_file: if not is_text(content): Log.error(u"expecting to write unicode only") output_file.write(content.encode(encoding)) output_file.write(b"\n")
python
def append(self, content, encoding='utf8'): """ add a line to file """ if not self.parent.exists: self.parent.create() with open(self._filename, "ab") as output_file: if not is_text(content): Log.error(u"expecting to write unicode only") output_file.write(content.encode(encoding)) output_file.write(b"\n")
[ "def", "append", "(", "self", ",", "content", ",", "encoding", "=", "'utf8'", ")", ":", "if", "not", "self", ".", "parent", ".", "exists", ":", "self", ".", "parent", ".", "create", "(", ")", "with", "open", "(", "self", ".", "_filename", ",", "\"a...
add a line to file
[ "add", "a", "line", "to", "file" ]
f6974a997cdc9fdabccb60c19edee13356a5787a
https://github.com/klahnakoski/mo-files/blob/f6974a997cdc9fdabccb60c19edee13356a5787a/mo_files/__init__.py#L314-L324
train
55,261
klahnakoski/mo-files
mo_files/url.py
url_param2value
def url_param2value(param): """ CONVERT URL QUERY PARAMETERS INTO DICT """ if param == None: return Null if param == None: return Null def _decode(v): output = [] i = 0 while i < len(v): c = v[i] if c == "%": d = hex2chr(v[i + 1:i + 3]) output.append(d) i += 3 else: output.append(c) i += 1 output = text_type("".join(output)) try: return json2value(output) except Exception: pass return output query = Data() for p in param.split('&'): if not p: continue if p.find("=") == -1: k = p v = True else: k, v = p.split("=") v = _decode(v) u = query.get(k) if u is None: query[k] = v elif is_list(u): u += [v] else: query[k] = [u, v] return query
python
def url_param2value(param): """ CONVERT URL QUERY PARAMETERS INTO DICT """ if param == None: return Null if param == None: return Null def _decode(v): output = [] i = 0 while i < len(v): c = v[i] if c == "%": d = hex2chr(v[i + 1:i + 3]) output.append(d) i += 3 else: output.append(c) i += 1 output = text_type("".join(output)) try: return json2value(output) except Exception: pass return output query = Data() for p in param.split('&'): if not p: continue if p.find("=") == -1: k = p v = True else: k, v = p.split("=") v = _decode(v) u = query.get(k) if u is None: query[k] = v elif is_list(u): u += [v] else: query[k] = [u, v] return query
[ "def", "url_param2value", "(", "param", ")", ":", "if", "param", "==", "None", ":", "return", "Null", "if", "param", "==", "None", ":", "return", "Null", "def", "_decode", "(", "v", ")", ":", "output", "=", "[", "]", "i", "=", "0", "while", "i", ...
CONVERT URL QUERY PARAMETERS INTO DICT
[ "CONVERT", "URL", "QUERY", "PARAMETERS", "INTO", "DICT" ]
f6974a997cdc9fdabccb60c19edee13356a5787a
https://github.com/klahnakoski/mo-files/blob/f6974a997cdc9fdabccb60c19edee13356a5787a/mo_files/url.py#L144-L192
train
55,262
kevinconway/confpy
confpy/parser.py
configfile_from_path
def configfile_from_path(path, strict=True): """Get a ConfigFile object based on a file path. This method will inspect the file extension and return the appropriate ConfigFile subclass initialized with the given path. Args: path (str): The file path which represents the configuration file. strict (bool): Whether or not to parse the file in strict mode. Returns: confpy.loaders.base.ConfigurationFile: The subclass which is specialized for the given file path. Raises: UnrecognizedFileExtension: If there is no loader for the path. """ extension = path.split('.')[-1] conf_type = FILE_TYPES.get(extension) if not conf_type: raise exc.UnrecognizedFileExtension( "Cannot parse file of type {0}. Choices are {1}.".format( extension, FILE_TYPES.keys(), ) ) return conf_type(path=path, strict=strict)
python
def configfile_from_path(path, strict=True): """Get a ConfigFile object based on a file path. This method will inspect the file extension and return the appropriate ConfigFile subclass initialized with the given path. Args: path (str): The file path which represents the configuration file. strict (bool): Whether or not to parse the file in strict mode. Returns: confpy.loaders.base.ConfigurationFile: The subclass which is specialized for the given file path. Raises: UnrecognizedFileExtension: If there is no loader for the path. """ extension = path.split('.')[-1] conf_type = FILE_TYPES.get(extension) if not conf_type: raise exc.UnrecognizedFileExtension( "Cannot parse file of type {0}. Choices are {1}.".format( extension, FILE_TYPES.keys(), ) ) return conf_type(path=path, strict=strict)
[ "def", "configfile_from_path", "(", "path", ",", "strict", "=", "True", ")", ":", "extension", "=", "path", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "conf_type", "=", "FILE_TYPES", ".", "get", "(", "extension", ")", "if", "not", "conf_type", ...
Get a ConfigFile object based on a file path. This method will inspect the file extension and return the appropriate ConfigFile subclass initialized with the given path. Args: path (str): The file path which represents the configuration file. strict (bool): Whether or not to parse the file in strict mode. Returns: confpy.loaders.base.ConfigurationFile: The subclass which is specialized for the given file path. Raises: UnrecognizedFileExtension: If there is no loader for the path.
[ "Get", "a", "ConfigFile", "object", "based", "on", "a", "file", "path", "." ]
1ee8afcab46ac6915a5ff4184180434ac7b84a60
https://github.com/kevinconway/confpy/blob/1ee8afcab46ac6915a5ff4184180434ac7b84a60/confpy/parser.py#L25-L53
train
55,263
kevinconway/confpy
confpy/parser.py
configuration_from_paths
def configuration_from_paths(paths, strict=True): """Get a Configuration object based on multiple file paths. Args: paths (iter of str): An iterable of file paths which identify config files on the system. strict (bool): Whether or not to parse the files in strict mode. Returns: confpy.core.config.Configuration: The loaded configuration object. Raises: NamespaceNotRegistered: If a file contains a namespace which is not defined. OptionNotRegistered: If a file contains an option which is not defined but resides under a valid namespace. UnrecognizedFileExtension: If there is no loader for a path. """ for path in paths: cfg = configfile_from_path(path, strict=strict).config return cfg
python
def configuration_from_paths(paths, strict=True): """Get a Configuration object based on multiple file paths. Args: paths (iter of str): An iterable of file paths which identify config files on the system. strict (bool): Whether or not to parse the files in strict mode. Returns: confpy.core.config.Configuration: The loaded configuration object. Raises: NamespaceNotRegistered: If a file contains a namespace which is not defined. OptionNotRegistered: If a file contains an option which is not defined but resides under a valid namespace. UnrecognizedFileExtension: If there is no loader for a path. """ for path in paths: cfg = configfile_from_path(path, strict=strict).config return cfg
[ "def", "configuration_from_paths", "(", "paths", ",", "strict", "=", "True", ")", ":", "for", "path", "in", "paths", ":", "cfg", "=", "configfile_from_path", "(", "path", ",", "strict", "=", "strict", ")", ".", "config", "return", "cfg" ]
Get a Configuration object based on multiple file paths. Args: paths (iter of str): An iterable of file paths which identify config files on the system. strict (bool): Whether or not to parse the files in strict mode. Returns: confpy.core.config.Configuration: The loaded configuration object. Raises: NamespaceNotRegistered: If a file contains a namespace which is not defined. OptionNotRegistered: If a file contains an option which is not defined but resides under a valid namespace. UnrecognizedFileExtension: If there is no loader for a path.
[ "Get", "a", "Configuration", "object", "based", "on", "multiple", "file", "paths", "." ]
1ee8afcab46ac6915a5ff4184180434ac7b84a60
https://github.com/kevinconway/confpy/blob/1ee8afcab46ac6915a5ff4184180434ac7b84a60/confpy/parser.py#L56-L78
train
55,264
kevinconway/confpy
confpy/parser.py
set_environment_var_options
def set_environment_var_options(config, env=None, prefix='CONFPY'): """Set any configuration options which have an environment var set. Args: config (confpy.core.config.Configuration): A configuration object which has been initialized with options. env (dict): Optional dictionary which contains environment variables. The default is os.environ if no value is given. prefix (str): The string prefix prepended to all environment variables. This value will be set to upper case. The default is CONFPY. Returns: confpy.core.config.Configuration: A configuration object with environment variables set. The pattern to follow when setting environment variables is: <PREFIX>_<SECTION>_<OPTION> Each value should be upper case and separated by underscores. """ env = env or os.environ for section_name, section in config: for option_name, _ in section: var_name = '{0}_{1}_{2}'.format( prefix.upper(), section_name.upper(), option_name.upper(), ) env_var = env.get(var_name) if env_var: setattr(section, option_name, env_var) return config
python
def set_environment_var_options(config, env=None, prefix='CONFPY'): """Set any configuration options which have an environment var set. Args: config (confpy.core.config.Configuration): A configuration object which has been initialized with options. env (dict): Optional dictionary which contains environment variables. The default is os.environ if no value is given. prefix (str): The string prefix prepended to all environment variables. This value will be set to upper case. The default is CONFPY. Returns: confpy.core.config.Configuration: A configuration object with environment variables set. The pattern to follow when setting environment variables is: <PREFIX>_<SECTION>_<OPTION> Each value should be upper case and separated by underscores. """ env = env or os.environ for section_name, section in config: for option_name, _ in section: var_name = '{0}_{1}_{2}'.format( prefix.upper(), section_name.upper(), option_name.upper(), ) env_var = env.get(var_name) if env_var: setattr(section, option_name, env_var) return config
[ "def", "set_environment_var_options", "(", "config", ",", "env", "=", "None", ",", "prefix", "=", "'CONFPY'", ")", ":", "env", "=", "env", "or", "os", ".", "environ", "for", "section_name", ",", "section", "in", "config", ":", "for", "option_name", ",", ...
Set any configuration options which have an environment var set. Args: config (confpy.core.config.Configuration): A configuration object which has been initialized with options. env (dict): Optional dictionary which contains environment variables. The default is os.environ if no value is given. prefix (str): The string prefix prepended to all environment variables. This value will be set to upper case. The default is CONFPY. Returns: confpy.core.config.Configuration: A configuration object with environment variables set. The pattern to follow when setting environment variables is: <PREFIX>_<SECTION>_<OPTION> Each value should be upper case and separated by underscores.
[ "Set", "any", "configuration", "options", "which", "have", "an", "environment", "var", "set", "." ]
1ee8afcab46ac6915a5ff4184180434ac7b84a60
https://github.com/kevinconway/confpy/blob/1ee8afcab46ac6915a5ff4184180434ac7b84a60/confpy/parser.py#L81-L117
train
55,265
kevinconway/confpy
confpy/parser.py
set_cli_options
def set_cli_options(config, arguments=None): """Set any configuration options which have a CLI value set. Args: config (confpy.core.config.Configuration): A configuration object which has been initialized with options. arguments (iter of str): An iterable of strings which contains the CLI arguments passed. If nothing is give then sys.argv is used. Returns: confpy.core.config.Configuration: A configuration object with CLI values set. The pattern to follow when setting CLI values is: <section>_<option> Each value should be lower case and separated by underscores. """ arguments = arguments or sys.argv[1:] parser = argparse.ArgumentParser() for section_name, section in config: for option_name, _ in section: var_name = '{0}_{1}'.format( section_name.lower(), option_name.lower(), ) parser.add_argument('--{0}'.format(var_name)) args, _ = parser.parse_known_args(arguments) args = vars(args) for section_name, section in config: for option_name, _ in section: var_name = '{0}_{1}'.format( section_name.lower(), option_name.lower(), ) value = args.get(var_name) if value: setattr(section, option_name, value) return config
python
def set_cli_options(config, arguments=None): """Set any configuration options which have a CLI value set. Args: config (confpy.core.config.Configuration): A configuration object which has been initialized with options. arguments (iter of str): An iterable of strings which contains the CLI arguments passed. If nothing is give then sys.argv is used. Returns: confpy.core.config.Configuration: A configuration object with CLI values set. The pattern to follow when setting CLI values is: <section>_<option> Each value should be lower case and separated by underscores. """ arguments = arguments or sys.argv[1:] parser = argparse.ArgumentParser() for section_name, section in config: for option_name, _ in section: var_name = '{0}_{1}'.format( section_name.lower(), option_name.lower(), ) parser.add_argument('--{0}'.format(var_name)) args, _ = parser.parse_known_args(arguments) args = vars(args) for section_name, section in config: for option_name, _ in section: var_name = '{0}_{1}'.format( section_name.lower(), option_name.lower(), ) value = args.get(var_name) if value: setattr(section, option_name, value) return config
[ "def", "set_cli_options", "(", "config", ",", "arguments", "=", "None", ")", ":", "arguments", "=", "arguments", "or", "sys", ".", "argv", "[", "1", ":", "]", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "for", "section_name", ",", "sectio...
Set any configuration options which have a CLI value set. Args: config (confpy.core.config.Configuration): A configuration object which has been initialized with options. arguments (iter of str): An iterable of strings which contains the CLI arguments passed. If nothing is give then sys.argv is used. Returns: confpy.core.config.Configuration: A configuration object with CLI values set. The pattern to follow when setting CLI values is: <section>_<option> Each value should be lower case and separated by underscores.
[ "Set", "any", "configuration", "options", "which", "have", "a", "CLI", "value", "set", "." ]
1ee8afcab46ac6915a5ff4184180434ac7b84a60
https://github.com/kevinconway/confpy/blob/1ee8afcab46ac6915a5ff4184180434ac7b84a60/confpy/parser.py#L120-L166
train
55,266
kevinconway/confpy
confpy/parser.py
check_for_missing_options
def check_for_missing_options(config): """Iter over a config and raise if a required option is still not set. Args: config (confpy.core.config.Configuration): The configuration object to validate. Raises: MissingRequiredOption: If any required options are not set in the configuration object. Required options with default values are considered set and will not cause this function to raise. """ for section_name, section in config: for option_name, option in section: if option.required and option.value is None: raise exc.MissingRequiredOption( "Option {0} in namespace {1} is required.".format( option_name, section_name, ) ) return config
python
def check_for_missing_options(config): """Iter over a config and raise if a required option is still not set. Args: config (confpy.core.config.Configuration): The configuration object to validate. Raises: MissingRequiredOption: If any required options are not set in the configuration object. Required options with default values are considered set and will not cause this function to raise. """ for section_name, section in config: for option_name, option in section: if option.required and option.value is None: raise exc.MissingRequiredOption( "Option {0} in namespace {1} is required.".format( option_name, section_name, ) ) return config
[ "def", "check_for_missing_options", "(", "config", ")", ":", "for", "section_name", ",", "section", "in", "config", ":", "for", "option_name", ",", "option", "in", "section", ":", "if", "option", ".", "required", "and", "option", ".", "value", "is", "None", ...
Iter over a config and raise if a required option is still not set. Args: config (confpy.core.config.Configuration): The configuration object to validate. Raises: MissingRequiredOption: If any required options are not set in the configuration object. Required options with default values are considered set and will not cause this function to raise.
[ "Iter", "over", "a", "config", "and", "raise", "if", "a", "required", "option", "is", "still", "not", "set", "." ]
1ee8afcab46ac6915a5ff4184180434ac7b84a60
https://github.com/kevinconway/confpy/blob/1ee8afcab46ac6915a5ff4184180434ac7b84a60/confpy/parser.py#L169-L196
train
55,267
kevinconway/confpy
confpy/parser.py
parse_options
def parse_options(files, env_prefix='CONFPY', strict=True): """Parse configuration options and return a configuration object. Args: files (iter of str): File paths which identify configuration files. These files are processed in order with values in later files overwriting values in earlier files. env_prefix (str): The static prefix prepended to all options when set as environment variables. The default is CONFPY. strict (bool): Whether or not to parse the files in strict mode. Returns: confpy.core.config.Configuration: The loaded configuration object. Raises: MissingRequiredOption: If a required option is not defined in any file. NamespaceNotRegistered: If a file contains a namespace which is not defined. OptionNotRegistered: If a file contains an option which is not defined but resides under a valid namespace. UnrecognizedFileExtension: If there is no loader for a path. """ return check_for_missing_options( config=set_cli_options( config=set_environment_var_options( config=configuration_from_paths( paths=files, strict=strict, ), prefix=env_prefix, ), ) )
python
def parse_options(files, env_prefix='CONFPY', strict=True): """Parse configuration options and return a configuration object. Args: files (iter of str): File paths which identify configuration files. These files are processed in order with values in later files overwriting values in earlier files. env_prefix (str): The static prefix prepended to all options when set as environment variables. The default is CONFPY. strict (bool): Whether or not to parse the files in strict mode. Returns: confpy.core.config.Configuration: The loaded configuration object. Raises: MissingRequiredOption: If a required option is not defined in any file. NamespaceNotRegistered: If a file contains a namespace which is not defined. OptionNotRegistered: If a file contains an option which is not defined but resides under a valid namespace. UnrecognizedFileExtension: If there is no loader for a path. """ return check_for_missing_options( config=set_cli_options( config=set_environment_var_options( config=configuration_from_paths( paths=files, strict=strict, ), prefix=env_prefix, ), ) )
[ "def", "parse_options", "(", "files", ",", "env_prefix", "=", "'CONFPY'", ",", "strict", "=", "True", ")", ":", "return", "check_for_missing_options", "(", "config", "=", "set_cli_options", "(", "config", "=", "set_environment_var_options", "(", "config", "=", "...
Parse configuration options and return a configuration object. Args: files (iter of str): File paths which identify configuration files. These files are processed in order with values in later files overwriting values in earlier files. env_prefix (str): The static prefix prepended to all options when set as environment variables. The default is CONFPY. strict (bool): Whether or not to parse the files in strict mode. Returns: confpy.core.config.Configuration: The loaded configuration object. Raises: MissingRequiredOption: If a required option is not defined in any file. NamespaceNotRegistered: If a file contains a namespace which is not defined. OptionNotRegistered: If a file contains an option which is not defined but resides under a valid namespace. UnrecognizedFileExtension: If there is no loader for a path.
[ "Parse", "configuration", "options", "and", "return", "a", "configuration", "object", "." ]
1ee8afcab46ac6915a5ff4184180434ac7b84a60
https://github.com/kevinconway/confpy/blob/1ee8afcab46ac6915a5ff4184180434ac7b84a60/confpy/parser.py#L199-L231
train
55,268
pauleveritt/kaybee
kaybee/plugins/widgets/base_widget.py
BaseWidget.render
def render(self, sphinx_app: Sphinx, context): """ Given a Sphinx builder and context with sphinx_app in it, generate HTML """ # Called from kaybee.plugins.widgets.handlers.render_widgets builder: StandaloneHTMLBuilder = sphinx_app.builder resource = sphinx_app.env.resources[self.docname] context['sphinx_app'] = sphinx_app context['widget'] = self context['resource'] = resource # make_context is optionally implemented on the concrete class # for each widget self.make_context(context, sphinx_app) # NOTE: Can use builder.templates.render_string template = self.template + '.html' html = builder.templates.render(template, context) return html
python
def render(self, sphinx_app: Sphinx, context): """ Given a Sphinx builder and context with sphinx_app in it, generate HTML """ # Called from kaybee.plugins.widgets.handlers.render_widgets builder: StandaloneHTMLBuilder = sphinx_app.builder resource = sphinx_app.env.resources[self.docname] context['sphinx_app'] = sphinx_app context['widget'] = self context['resource'] = resource # make_context is optionally implemented on the concrete class # for each widget self.make_context(context, sphinx_app) # NOTE: Can use builder.templates.render_string template = self.template + '.html' html = builder.templates.render(template, context) return html
[ "def", "render", "(", "self", ",", "sphinx_app", ":", "Sphinx", ",", "context", ")", ":", "# Called from kaybee.plugins.widgets.handlers.render_widgets", "builder", ":", "StandaloneHTMLBuilder", "=", "sphinx_app", ".", "builder", "resource", "=", "sphinx_app", ".", "e...
Given a Sphinx builder and context with sphinx_app in it, generate HTML
[ "Given", "a", "Sphinx", "builder", "and", "context", "with", "sphinx_app", "in", "it", "generate", "HTML" ]
a00a718aaaa23b2d12db30dfacb6b2b6ec84459c
https://github.com/pauleveritt/kaybee/blob/a00a718aaaa23b2d12db30dfacb6b2b6ec84459c/kaybee/plugins/widgets/base_widget.py#L70-L89
train
55,269
botstory/botstory
botstory/di/desciption.py
desc
def desc(t=None, reg=True): """ Describe Class Dependency :param reg: should we register this class as well :param t: custom type as well :return: """ def decorated_fn(cls): if not inspect.isclass(cls): return NotImplemented('For now we can only describe classes') name = t or camel_case_to_underscore(cls.__name__)[0] if reg: di.injector.register(name, cls) else: di.injector.describe(name, cls) return cls return decorated_fn
python
def desc(t=None, reg=True): """ Describe Class Dependency :param reg: should we register this class as well :param t: custom type as well :return: """ def decorated_fn(cls): if not inspect.isclass(cls): return NotImplemented('For now we can only describe classes') name = t or camel_case_to_underscore(cls.__name__)[0] if reg: di.injector.register(name, cls) else: di.injector.describe(name, cls) return cls return decorated_fn
[ "def", "desc", "(", "t", "=", "None", ",", "reg", "=", "True", ")", ":", "def", "decorated_fn", "(", "cls", ")", ":", "if", "not", "inspect", ".", "isclass", "(", "cls", ")", ":", "return", "NotImplemented", "(", "'For now we can only describe classes'", ...
Describe Class Dependency :param reg: should we register this class as well :param t: custom type as well :return:
[ "Describe", "Class", "Dependency" ]
9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3
https://github.com/botstory/botstory/blob/9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3/botstory/di/desciption.py#L6-L25
train
55,270
bitesofcode/projex
projex/enum.py
enum.label
def label(self, value): """ Returns a pretty text version of the key for the inputted value. :param value | <variant> :return <str> """ return self._labels.get(value) or text.pretty(self(value))
python
def label(self, value): """ Returns a pretty text version of the key for the inputted value. :param value | <variant> :return <str> """ return self._labels.get(value) or text.pretty(self(value))
[ "def", "label", "(", "self", ",", "value", ")", ":", "return", "self", ".", "_labels", ".", "get", "(", "value", ")", "or", "text", ".", "pretty", "(", "self", "(", "value", ")", ")" ]
Returns a pretty text version of the key for the inputted value. :param value | <variant> :return <str>
[ "Returns", "a", "pretty", "text", "version", "of", "the", "key", "for", "the", "inputted", "value", "." ]
d31743ec456a41428709968ab11a2cf6c6c76247
https://github.com/bitesofcode/projex/blob/d31743ec456a41428709968ab11a2cf6c6c76247/projex/enum.py#L202-L210
train
55,271
bitesofcode/projex
projex/enum.py
enum.setLabel
def setLabel(self, value, label): """ Sets the label text for the inputted value. This will override the default pretty text label that is used for the key. :param value | <variant> label | <str> """ if label: self._labels[value] = label else: self._labels.pop(value, None)
python
def setLabel(self, value, label): """ Sets the label text for the inputted value. This will override the default pretty text label that is used for the key. :param value | <variant> label | <str> """ if label: self._labels[value] = label else: self._labels.pop(value, None)
[ "def", "setLabel", "(", "self", ",", "value", ",", "label", ")", ":", "if", "label", ":", "self", ".", "_labels", "[", "value", "]", "=", "label", "else", ":", "self", ".", "_labels", ".", "pop", "(", "value", ",", "None", ")" ]
Sets the label text for the inputted value. This will override the default pretty text label that is used for the key. :param value | <variant> label | <str>
[ "Sets", "the", "label", "text", "for", "the", "inputted", "value", ".", "This", "will", "override", "the", "default", "pretty", "text", "label", "that", "is", "used", "for", "the", "key", "." ]
d31743ec456a41428709968ab11a2cf6c6c76247
https://github.com/bitesofcode/projex/blob/d31743ec456a41428709968ab11a2cf6c6c76247/projex/enum.py#L221-L232
train
55,272
bitesofcode/projex
projex/enum.py
enum.valueByLabel
def valueByLabel(self, label): """ Determine a given value based on the inputted label. :param label <str> :return <int> """ keys = self.keys() labels = [text.pretty(key) for key in keys] if label in labels: return self[keys[labels.index(label)]] return 0
python
def valueByLabel(self, label): """ Determine a given value based on the inputted label. :param label <str> :return <int> """ keys = self.keys() labels = [text.pretty(key) for key in keys] if label in labels: return self[keys[labels.index(label)]] return 0
[ "def", "valueByLabel", "(", "self", ",", "label", ")", ":", "keys", "=", "self", ".", "keys", "(", ")", "labels", "=", "[", "text", ".", "pretty", "(", "key", ")", "for", "key", "in", "keys", "]", "if", "label", "in", "labels", ":", "return", "se...
Determine a given value based on the inputted label. :param label <str> :return <int>
[ "Determine", "a", "given", "value", "based", "on", "the", "inputted", "label", "." ]
d31743ec456a41428709968ab11a2cf6c6c76247
https://github.com/bitesofcode/projex/blob/d31743ec456a41428709968ab11a2cf6c6c76247/projex/enum.py#L255-L267
train
55,273
invinst/ResponseBot
responsebot/utils/config_utils.py
ResponseBotConfig.load_config_file
def load_config_file(self): """Parse configuration file and get config values.""" config_parser = SafeConfigParser() config_parser.read(self.CONFIG_FILE) if config_parser.has_section('handlers'): self._config['handlers_package'] = config_parser.get('handlers', 'package') if config_parser.has_section('auth'): self._config['consumer_key'] = config_parser.get('auth', 'consumer_key') self._config['consumer_secret'] = config_parser.get('auth', 'consumer_secret') self._config['token_key'] = config_parser.get('auth', 'token_key') self._config['token_secret'] = config_parser.get('auth', 'token_secret') if config_parser.has_section('stream'): self._config['user_stream'] = config_parser.get('stream', 'user_stream').lower() == 'true' else: self._config['user_stream'] = False if config_parser.has_option('general', 'min_seconds_between_errors'): self._config['min_seconds_between_errors'] = config_parser.get('general', 'min_seconds_between_errors') if config_parser.has_option('general', 'sleep_seconds_on_consecutive_errors'): self._config['sleep_seconds_on_consecutive_errors'] = config_parser.get( 'general', 'sleep_seconds_on_consecutive_errors')
python
def load_config_file(self): """Parse configuration file and get config values.""" config_parser = SafeConfigParser() config_parser.read(self.CONFIG_FILE) if config_parser.has_section('handlers'): self._config['handlers_package'] = config_parser.get('handlers', 'package') if config_parser.has_section('auth'): self._config['consumer_key'] = config_parser.get('auth', 'consumer_key') self._config['consumer_secret'] = config_parser.get('auth', 'consumer_secret') self._config['token_key'] = config_parser.get('auth', 'token_key') self._config['token_secret'] = config_parser.get('auth', 'token_secret') if config_parser.has_section('stream'): self._config['user_stream'] = config_parser.get('stream', 'user_stream').lower() == 'true' else: self._config['user_stream'] = False if config_parser.has_option('general', 'min_seconds_between_errors'): self._config['min_seconds_between_errors'] = config_parser.get('general', 'min_seconds_between_errors') if config_parser.has_option('general', 'sleep_seconds_on_consecutive_errors'): self._config['sleep_seconds_on_consecutive_errors'] = config_parser.get( 'general', 'sleep_seconds_on_consecutive_errors')
[ "def", "load_config_file", "(", "self", ")", ":", "config_parser", "=", "SafeConfigParser", "(", ")", "config_parser", ".", "read", "(", "self", ".", "CONFIG_FILE", ")", "if", "config_parser", ".", "has_section", "(", "'handlers'", ")", ":", "self", ".", "_c...
Parse configuration file and get config values.
[ "Parse", "configuration", "file", "and", "get", "config", "values", "." ]
a6b1a431a343007f7ae55a193e432a61af22253f
https://github.com/invinst/ResponseBot/blob/a6b1a431a343007f7ae55a193e432a61af22253f/responsebot/utils/config_utils.py#L29-L53
train
55,274
invinst/ResponseBot
responsebot/utils/config_utils.py
ResponseBotConfig.load_config_from_cli_arguments
def load_config_from_cli_arguments(self, *args, **kwargs): """ Get config values of passed in CLI options. :param dict kwargs: CLI options """ self._load_config_from_cli_argument(key='handlers_package', **kwargs) self._load_config_from_cli_argument(key='auth', **kwargs) self._load_config_from_cli_argument(key='user_stream', **kwargs) self._load_config_from_cli_argument(key='min_seconds_between_errors', **kwargs) self._load_config_from_cli_argument(key='sleep_seconds_on_consecutive_errors', **kwargs)
python
def load_config_from_cli_arguments(self, *args, **kwargs): """ Get config values of passed in CLI options. :param dict kwargs: CLI options """ self._load_config_from_cli_argument(key='handlers_package', **kwargs) self._load_config_from_cli_argument(key='auth', **kwargs) self._load_config_from_cli_argument(key='user_stream', **kwargs) self._load_config_from_cli_argument(key='min_seconds_between_errors', **kwargs) self._load_config_from_cli_argument(key='sleep_seconds_on_consecutive_errors', **kwargs)
[ "def", "load_config_from_cli_arguments", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_load_config_from_cli_argument", "(", "key", "=", "'handlers_package'", ",", "*", "*", "kwargs", ")", "self", ".", "_load_config_from_cli_arg...
Get config values of passed in CLI options. :param dict kwargs: CLI options
[ "Get", "config", "values", "of", "passed", "in", "CLI", "options", "." ]
a6b1a431a343007f7ae55a193e432a61af22253f
https://github.com/invinst/ResponseBot/blob/a6b1a431a343007f7ae55a193e432a61af22253f/responsebot/utils/config_utils.py#L55-L65
train
55,275
rogerhil/thegamesdb
thegamesdb/base.py
Resource.get
def get(self, id): """ Gets the dict data and builds the item object. """ data = self.db.get_data(self.get_path, id=id) return self._build_item(**data['Data'][self.name])
python
def get(self, id): """ Gets the dict data and builds the item object. """ data = self.db.get_data(self.get_path, id=id) return self._build_item(**data['Data'][self.name])
[ "def", "get", "(", "self", ",", "id", ")", ":", "data", "=", "self", ".", "db", ".", "get_data", "(", "self", ".", "get_path", ",", "id", "=", "id", ")", "return", "self", ".", "_build_item", "(", "*", "*", "data", "[", "'Data'", "]", "[", "sel...
Gets the dict data and builds the item object.
[ "Gets", "the", "dict", "data", "and", "builds", "the", "item", "object", "." ]
795314215f9ee73697c7520dea4ddecfb23ca8e6
https://github.com/rogerhil/thegamesdb/blob/795314215f9ee73697c7520dea4ddecfb23ca8e6/thegamesdb/base.py#L66-L70
train
55,276
leodesouza/pyenty
pyenty/entitymanager.py
EntityManager.save
def save(self, entity): """Maps entity to dict and returns future""" assert isinstance(entity, Entity), " entity must have an instance of Entity" return self.__collection.save(entity.as_dict())
python
def save(self, entity): """Maps entity to dict and returns future""" assert isinstance(entity, Entity), " entity must have an instance of Entity" return self.__collection.save(entity.as_dict())
[ "def", "save", "(", "self", ",", "entity", ")", ":", "assert", "isinstance", "(", "entity", ",", "Entity", ")", ",", "\" entity must have an instance of Entity\"", "return", "self", ".", "__collection", ".", "save", "(", "entity", ".", "as_dict", "(", ")", "...
Maps entity to dict and returns future
[ "Maps", "entity", "to", "dict", "and", "returns", "future" ]
20d2834eada4b971208e816b387479c4fb6ffe61
https://github.com/leodesouza/pyenty/blob/20d2834eada4b971208e816b387479c4fb6ffe61/pyenty/entitymanager.py#L65-L68
train
55,277
leodesouza/pyenty
pyenty/entitymanager.py
EntityManager.find_one
def find_one(self, **kwargs): """Returns future. Executes collection's find_one method based on keyword args maps result ( dict to instance ) and return future Example:: manager = EntityManager(Product) product_saved = yield manager.find_one(_id=object_id) """ future = TracebackFuture() def handle_response(result, error): if error: future.set_exception(error) else: instance = self.__entity() instance.map_dict(result) future.set_result(instance) self.__collection.find_one(kwargs, callback=handle_response) return future
python
def find_one(self, **kwargs): """Returns future. Executes collection's find_one method based on keyword args maps result ( dict to instance ) and return future Example:: manager = EntityManager(Product) product_saved = yield manager.find_one(_id=object_id) """ future = TracebackFuture() def handle_response(result, error): if error: future.set_exception(error) else: instance = self.__entity() instance.map_dict(result) future.set_result(instance) self.__collection.find_one(kwargs, callback=handle_response) return future
[ "def", "find_one", "(", "self", ",", "*", "*", "kwargs", ")", ":", "future", "=", "TracebackFuture", "(", ")", "def", "handle_response", "(", "result", ",", "error", ")", ":", "if", "error", ":", "future", ".", "set_exception", "(", "error", ")", "else...
Returns future. Executes collection's find_one method based on keyword args maps result ( dict to instance ) and return future Example:: manager = EntityManager(Product) product_saved = yield manager.find_one(_id=object_id)
[ "Returns", "future", "." ]
20d2834eada4b971208e816b387479c4fb6ffe61
https://github.com/leodesouza/pyenty/blob/20d2834eada4b971208e816b387479c4fb6ffe61/pyenty/entitymanager.py#L83-L107
train
55,278
leodesouza/pyenty
pyenty/entitymanager.py
EntityManager.update
def update(self, entity): """ Executes collection's update method based on keyword args. Example:: manager = EntityManager(Product) p = Product() p.name = 'new name' p.description = 'new description' p.price = 300.0 yield manager.update(p) """ assert isinstance(entity, Entity), "Error: entity must have an instance of Entity" return self.__collection.update({'_id': entity._id}, {'$set': entity.as_dict()})
python
def update(self, entity): """ Executes collection's update method based on keyword args. Example:: manager = EntityManager(Product) p = Product() p.name = 'new name' p.description = 'new description' p.price = 300.0 yield manager.update(p) """ assert isinstance(entity, Entity), "Error: entity must have an instance of Entity" return self.__collection.update({'_id': entity._id}, {'$set': entity.as_dict()})
[ "def", "update", "(", "self", ",", "entity", ")", ":", "assert", "isinstance", "(", "entity", ",", "Entity", ")", ",", "\"Error: entity must have an instance of Entity\"", "return", "self", ".", "__collection", ".", "update", "(", "{", "'_id'", ":", "entity", ...
Executes collection's update method based on keyword args. Example:: manager = EntityManager(Product) p = Product() p.name = 'new name' p.description = 'new description' p.price = 300.0 yield manager.update(p)
[ "Executes", "collection", "s", "update", "method", "based", "on", "keyword", "args", "." ]
20d2834eada4b971208e816b387479c4fb6ffe61
https://github.com/leodesouza/pyenty/blob/20d2834eada4b971208e816b387479c4fb6ffe61/pyenty/entitymanager.py#L135-L150
train
55,279
EricDalrymple91/strawpy
strawpy/asyncstrawpy.py
StrawPoll.open
def open(self, results=False): """ Open the strawpoll in a browser. Can specify to open the main or results page. :param results: True/False """ webbrowser.open(self.results_url if results else self.url)
python
def open(self, results=False): """ Open the strawpoll in a browser. Can specify to open the main or results page. :param results: True/False """ webbrowser.open(self.results_url if results else self.url)
[ "def", "open", "(", "self", ",", "results", "=", "False", ")", ":", "webbrowser", ".", "open", "(", "self", ".", "results_url", "if", "results", "else", "self", ".", "url", ")" ]
Open the strawpoll in a browser. Can specify to open the main or results page. :param results: True/False
[ "Open", "the", "strawpoll", "in", "a", "browser", ".", "Can", "specify", "to", "open", "the", "main", "or", "results", "page", "." ]
0c4294fc2dca250a5c13a97e825ae21587278a91
https://github.com/EricDalrymple91/strawpy/blob/0c4294fc2dca250a5c13a97e825ae21587278a91/strawpy/asyncstrawpy.py#L156-L162
train
55,280
GeorgeArgyros/symautomata
symautomata/brzozowski.py
main
def main(): """ Testing function for DFA brzozowski algebraic method Operation """ argv = sys.argv if len(argv) < 2: targetfile = 'target.y' else: targetfile = argv[1] print 'Parsing ruleset: ' + targetfile, flex_a = Flexparser() mma = flex_a.yyparse(targetfile) print 'OK' print 'Perform minimization on initial automaton:', mma.minimize() print 'OK' print 'Perform Brzozowski on minimal automaton:', brzozowski_a = Brzozowski(mma) mma_regex = brzozowski_a.get_regex() print mma_regex
python
def main(): """ Testing function for DFA brzozowski algebraic method Operation """ argv = sys.argv if len(argv) < 2: targetfile = 'target.y' else: targetfile = argv[1] print 'Parsing ruleset: ' + targetfile, flex_a = Flexparser() mma = flex_a.yyparse(targetfile) print 'OK' print 'Perform minimization on initial automaton:', mma.minimize() print 'OK' print 'Perform Brzozowski on minimal automaton:', brzozowski_a = Brzozowski(mma) mma_regex = brzozowski_a.get_regex() print mma_regex
[ "def", "main", "(", ")", ":", "argv", "=", "sys", ".", "argv", "if", "len", "(", "argv", ")", "<", "2", ":", "targetfile", "=", "'target.y'", "else", ":", "targetfile", "=", "argv", "[", "1", "]", "print", "'Parsing ruleset: '", "+", "targetfile", ",...
Testing function for DFA brzozowski algebraic method Operation
[ "Testing", "function", "for", "DFA", "brzozowski", "algebraic", "method", "Operation" ]
f5d66533573b27e155bec3f36b8c00b8e3937cb3
https://github.com/GeorgeArgyros/symautomata/blob/f5d66533573b27e155bec3f36b8c00b8e3937cb3/symautomata/brzozowski.py#L199-L218
train
55,281
jasedit/pymmd
pymmd/mmd.py
load_mmd
def load_mmd(): """Loads libMultiMarkdown for usage""" global _MMD_LIB global _LIB_LOCATION try: lib_file = 'libMultiMarkdown' + SHLIB_EXT[platform.system()] _LIB_LOCATION = os.path.abspath(os.path.join(DEFAULT_LIBRARY_DIR, lib_file)) if not os.path.isfile(_LIB_LOCATION): _LIB_LOCATION = ctypes.util.find_library('MultiMarkdown') _MMD_LIB = ctypes.cdll.LoadLibrary(_LIB_LOCATION) except: _MMD_LIB = None
python
def load_mmd(): """Loads libMultiMarkdown for usage""" global _MMD_LIB global _LIB_LOCATION try: lib_file = 'libMultiMarkdown' + SHLIB_EXT[platform.system()] _LIB_LOCATION = os.path.abspath(os.path.join(DEFAULT_LIBRARY_DIR, lib_file)) if not os.path.isfile(_LIB_LOCATION): _LIB_LOCATION = ctypes.util.find_library('MultiMarkdown') _MMD_LIB = ctypes.cdll.LoadLibrary(_LIB_LOCATION) except: _MMD_LIB = None
[ "def", "load_mmd", "(", ")", ":", "global", "_MMD_LIB", "global", "_LIB_LOCATION", "try", ":", "lib_file", "=", "'libMultiMarkdown'", "+", "SHLIB_EXT", "[", "platform", ".", "system", "(", ")", "]", "_LIB_LOCATION", "=", "os", ".", "path", ".", "abspath", ...
Loads libMultiMarkdown for usage
[ "Loads", "libMultiMarkdown", "for", "usage" ]
37b5a717241b837ca15b8a4d4cc3c06b4456bfbd
https://github.com/jasedit/pymmd/blob/37b5a717241b837ca15b8a4d4cc3c06b4456bfbd/pymmd/mmd.py#L15-L28
train
55,282
jasedit/pymmd
pymmd/mmd.py
_expand_source
def _expand_source(source, dname, fmt): """Expands source text to include headers, footers, and expands Multimarkdown transclusion directives. Keyword arguments: source -- string containing the Multimarkdown text to expand dname -- directory name to use as the base directory for transclusion references fmt -- format flag indicating which format to use to convert transclusion statements """ _MMD_LIB.g_string_new.restype = ctypes.POINTER(GString) _MMD_LIB.g_string_new.argtypes = [ctypes.c_char_p] src = source.encode('utf-8') gstr = _MMD_LIB.g_string_new(src) _MMD_LIB.prepend_mmd_header(gstr) _MMD_LIB.append_mmd_footer(gstr) manif = _MMD_LIB.g_string_new(b"") _MMD_LIB.transclude_source.argtypes = [ctypes.POINTER(GString), ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int, ctypes.POINTER(GString)] _MMD_LIB.transclude_source(gstr, dname.encode('utf-8'), None, fmt, manif) manifest_txt = manif.contents.str full_txt = gstr.contents.str _MMD_LIB.g_string_free(manif, True) _MMD_LIB.g_string_free(gstr, True) manifest_txt = [ii for ii in manifest_txt.decode('utf-8').split('\n') if ii] return full_txt.decode('utf-8'), manifest_txt
python
def _expand_source(source, dname, fmt): """Expands source text to include headers, footers, and expands Multimarkdown transclusion directives. Keyword arguments: source -- string containing the Multimarkdown text to expand dname -- directory name to use as the base directory for transclusion references fmt -- format flag indicating which format to use to convert transclusion statements """ _MMD_LIB.g_string_new.restype = ctypes.POINTER(GString) _MMD_LIB.g_string_new.argtypes = [ctypes.c_char_p] src = source.encode('utf-8') gstr = _MMD_LIB.g_string_new(src) _MMD_LIB.prepend_mmd_header(gstr) _MMD_LIB.append_mmd_footer(gstr) manif = _MMD_LIB.g_string_new(b"") _MMD_LIB.transclude_source.argtypes = [ctypes.POINTER(GString), ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int, ctypes.POINTER(GString)] _MMD_LIB.transclude_source(gstr, dname.encode('utf-8'), None, fmt, manif) manifest_txt = manif.contents.str full_txt = gstr.contents.str _MMD_LIB.g_string_free(manif, True) _MMD_LIB.g_string_free(gstr, True) manifest_txt = [ii for ii in manifest_txt.decode('utf-8').split('\n') if ii] return full_txt.decode('utf-8'), manifest_txt
[ "def", "_expand_source", "(", "source", ",", "dname", ",", "fmt", ")", ":", "_MMD_LIB", ".", "g_string_new", ".", "restype", "=", "ctypes", ".", "POINTER", "(", "GString", ")", "_MMD_LIB", ".", "g_string_new", ".", "argtypes", "=", "[", "ctypes", ".", "c...
Expands source text to include headers, footers, and expands Multimarkdown transclusion directives. Keyword arguments: source -- string containing the Multimarkdown text to expand dname -- directory name to use as the base directory for transclusion references fmt -- format flag indicating which format to use to convert transclusion statements
[ "Expands", "source", "text", "to", "include", "headers", "footers", "and", "expands", "Multimarkdown", "transclusion", "directives", "." ]
37b5a717241b837ca15b8a4d4cc3c06b4456bfbd
https://github.com/jasedit/pymmd/blob/37b5a717241b837ca15b8a4d4cc3c06b4456bfbd/pymmd/mmd.py#L74-L101
train
55,283
jasedit/pymmd
pymmd/mmd.py
has_metadata
def has_metadata(source, ext): """Returns a flag indicating if a given block of MultiMarkdown text contains metadata.""" _MMD_LIB.has_metadata.argtypes = [ctypes.c_char_p, ctypes.c_int] _MMD_LIB.has_metadata.restype = ctypes.c_bool return _MMD_LIB.has_metadata(source.encode('utf-8'), ext)
python
def has_metadata(source, ext): """Returns a flag indicating if a given block of MultiMarkdown text contains metadata.""" _MMD_LIB.has_metadata.argtypes = [ctypes.c_char_p, ctypes.c_int] _MMD_LIB.has_metadata.restype = ctypes.c_bool return _MMD_LIB.has_metadata(source.encode('utf-8'), ext)
[ "def", "has_metadata", "(", "source", ",", "ext", ")", ":", "_MMD_LIB", ".", "has_metadata", ".", "argtypes", "=", "[", "ctypes", ".", "c_char_p", ",", "ctypes", ".", "c_int", "]", "_MMD_LIB", ".", "has_metadata", ".", "restype", "=", "ctypes", ".", "c_b...
Returns a flag indicating if a given block of MultiMarkdown text contains metadata.
[ "Returns", "a", "flag", "indicating", "if", "a", "given", "block", "of", "MultiMarkdown", "text", "contains", "metadata", "." ]
37b5a717241b837ca15b8a4d4cc3c06b4456bfbd
https://github.com/jasedit/pymmd/blob/37b5a717241b837ca15b8a4d4cc3c06b4456bfbd/pymmd/mmd.py#L103-L107
train
55,284
jasedit/pymmd
pymmd/mmd.py
convert
def convert(source, ext=COMPLETE, fmt=HTML, dname=None): """Converts a string of MultiMarkdown text to the requested format. Transclusion is performed if the COMPATIBILITY extension is not set, and dname is set to a valid directory Keyword arguments: source -- string containing MultiMarkdown text ext -- extension bitfield to pass to conversion process fmt -- flag indicating output format to use dname -- Path to use for transclusion - if None, transclusion functionality is bypassed """ if dname and not ext & COMPATIBILITY: if os.path.isfile(dname): dname = os.path.abspath(os.path.dirname(dname)) source, _ = _expand_source(source, dname, fmt) _MMD_LIB.markdown_to_string.argtypes = [ctypes.c_char_p, ctypes.c_ulong, ctypes.c_int] _MMD_LIB.markdown_to_string.restype = ctypes.c_char_p src = source.encode('utf-8') return _MMD_LIB.markdown_to_string(src, ext, fmt).decode('utf-8')
python
def convert(source, ext=COMPLETE, fmt=HTML, dname=None): """Converts a string of MultiMarkdown text to the requested format. Transclusion is performed if the COMPATIBILITY extension is not set, and dname is set to a valid directory Keyword arguments: source -- string containing MultiMarkdown text ext -- extension bitfield to pass to conversion process fmt -- flag indicating output format to use dname -- Path to use for transclusion - if None, transclusion functionality is bypassed """ if dname and not ext & COMPATIBILITY: if os.path.isfile(dname): dname = os.path.abspath(os.path.dirname(dname)) source, _ = _expand_source(source, dname, fmt) _MMD_LIB.markdown_to_string.argtypes = [ctypes.c_char_p, ctypes.c_ulong, ctypes.c_int] _MMD_LIB.markdown_to_string.restype = ctypes.c_char_p src = source.encode('utf-8') return _MMD_LIB.markdown_to_string(src, ext, fmt).decode('utf-8')
[ "def", "convert", "(", "source", ",", "ext", "=", "COMPLETE", ",", "fmt", "=", "HTML", ",", "dname", "=", "None", ")", ":", "if", "dname", "and", "not", "ext", "&", "COMPATIBILITY", ":", "if", "os", ".", "path", ".", "isfile", "(", "dname", ")", ...
Converts a string of MultiMarkdown text to the requested format. Transclusion is performed if the COMPATIBILITY extension is not set, and dname is set to a valid directory Keyword arguments: source -- string containing MultiMarkdown text ext -- extension bitfield to pass to conversion process fmt -- flag indicating output format to use dname -- Path to use for transclusion - if None, transclusion functionality is bypassed
[ "Converts", "a", "string", "of", "MultiMarkdown", "text", "to", "the", "requested", "format", ".", "Transclusion", "is", "performed", "if", "the", "COMPATIBILITY", "extension", "is", "not", "set", "and", "dname", "is", "set", "to", "a", "valid", "directory" ]
37b5a717241b837ca15b8a4d4cc3c06b4456bfbd
https://github.com/jasedit/pymmd/blob/37b5a717241b837ca15b8a4d4cc3c06b4456bfbd/pymmd/mmd.py#L109-L127
train
55,285
jasedit/pymmd
pymmd/mmd.py
convert_from
def convert_from(fname, ext=COMPLETE, fmt=HTML): """ Reads in a file and performs MultiMarkdown conversion, with transclusion ocurring based on the file directory. Returns the converted string. Keyword arguments: fname -- Filename of document to convert ext -- extension bitfield to pass to conversion process fmt -- flag indicating output format to use """ dname = os.path.abspath(os.path.dirname(fname)) with open(fname, 'r') as fp: src = fp.read() return convert(src, ext, fmt, dname)
python
def convert_from(fname, ext=COMPLETE, fmt=HTML): """ Reads in a file and performs MultiMarkdown conversion, with transclusion ocurring based on the file directory. Returns the converted string. Keyword arguments: fname -- Filename of document to convert ext -- extension bitfield to pass to conversion process fmt -- flag indicating output format to use """ dname = os.path.abspath(os.path.dirname(fname)) with open(fname, 'r') as fp: src = fp.read() return convert(src, ext, fmt, dname)
[ "def", "convert_from", "(", "fname", ",", "ext", "=", "COMPLETE", ",", "fmt", "=", "HTML", ")", ":", "dname", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "fname", ")", ")", "with", "open", "(", "fname", ",...
Reads in a file and performs MultiMarkdown conversion, with transclusion ocurring based on the file directory. Returns the converted string. Keyword arguments: fname -- Filename of document to convert ext -- extension bitfield to pass to conversion process fmt -- flag indicating output format to use
[ "Reads", "in", "a", "file", "and", "performs", "MultiMarkdown", "conversion", "with", "transclusion", "ocurring", "based", "on", "the", "file", "directory", ".", "Returns", "the", "converted", "string", "." ]
37b5a717241b837ca15b8a4d4cc3c06b4456bfbd
https://github.com/jasedit/pymmd/blob/37b5a717241b837ca15b8a4d4cc3c06b4456bfbd/pymmd/mmd.py#L129-L144
train
55,286
jasedit/pymmd
pymmd/mmd.py
manifest
def manifest(txt, dname): """Extracts file manifest for a body of text with the given directory.""" _, files = _expand_source(txt, dname, HTML) return files
python
def manifest(txt, dname): """Extracts file manifest for a body of text with the given directory.""" _, files = _expand_source(txt, dname, HTML) return files
[ "def", "manifest", "(", "txt", ",", "dname", ")", ":", "_", ",", "files", "=", "_expand_source", "(", "txt", ",", "dname", ",", "HTML", ")", "return", "files" ]
Extracts file manifest for a body of text with the given directory.
[ "Extracts", "file", "manifest", "for", "a", "body", "of", "text", "with", "the", "given", "directory", "." ]
37b5a717241b837ca15b8a4d4cc3c06b4456bfbd
https://github.com/jasedit/pymmd/blob/37b5a717241b837ca15b8a4d4cc3c06b4456bfbd/pymmd/mmd.py#L146-L149
train
55,287
jasedit/pymmd
pymmd/mmd.py
keys
def keys(source, ext=COMPLETE): """Extracts metadata keys from the provided MultiMarkdown text. Keyword arguments: source -- string containing MultiMarkdown text ext -- extension bitfield for extracting MultiMarkdown """ _MMD_LIB.extract_metadata_keys.restype = ctypes.c_char_p _MMD_LIB.extract_metadata_keys.argtypes = [ctypes.c_char_p, ctypes.c_ulong] src = source.encode('utf-8') all_keys = _MMD_LIB.extract_metadata_keys(src, ext) all_keys = all_keys.decode('utf-8') if all_keys else '' key_list = [ii for ii in all_keys.split('\n') if ii] return key_list
python
def keys(source, ext=COMPLETE): """Extracts metadata keys from the provided MultiMarkdown text. Keyword arguments: source -- string containing MultiMarkdown text ext -- extension bitfield for extracting MultiMarkdown """ _MMD_LIB.extract_metadata_keys.restype = ctypes.c_char_p _MMD_LIB.extract_metadata_keys.argtypes = [ctypes.c_char_p, ctypes.c_ulong] src = source.encode('utf-8') all_keys = _MMD_LIB.extract_metadata_keys(src, ext) all_keys = all_keys.decode('utf-8') if all_keys else '' key_list = [ii for ii in all_keys.split('\n') if ii] return key_list
[ "def", "keys", "(", "source", ",", "ext", "=", "COMPLETE", ")", ":", "_MMD_LIB", ".", "extract_metadata_keys", ".", "restype", "=", "ctypes", ".", "c_char_p", "_MMD_LIB", ".", "extract_metadata_keys", ".", "argtypes", "=", "[", "ctypes", ".", "c_char_p", ","...
Extracts metadata keys from the provided MultiMarkdown text. Keyword arguments: source -- string containing MultiMarkdown text ext -- extension bitfield for extracting MultiMarkdown
[ "Extracts", "metadata", "keys", "from", "the", "provided", "MultiMarkdown", "text", "." ]
37b5a717241b837ca15b8a4d4cc3c06b4456bfbd
https://github.com/jasedit/pymmd/blob/37b5a717241b837ca15b8a4d4cc3c06b4456bfbd/pymmd/mmd.py#L151-L164
train
55,288
jasedit/pymmd
pymmd/mmd.py
value
def value(source, key, ext=COMPLETE): """Extracts value for the specified metadata key from the given extension set. Keyword arguments: source -- string containing MultiMarkdown text ext -- extension bitfield for processing text key -- key to extract """ _MMD_LIB.extract_metadata_value.restype = ctypes.c_char_p _MMD_LIB.extract_metadata_value.argtypes = [ctypes.c_char_p, ctypes.c_ulong, ctypes.c_char_p] src = source.encode('utf-8') dkey = key.encode('utf-8') value = _MMD_LIB.extract_metadata_value(src, ext, dkey) return value.decode('utf-8') if value else ''
python
def value(source, key, ext=COMPLETE): """Extracts value for the specified metadata key from the given extension set. Keyword arguments: source -- string containing MultiMarkdown text ext -- extension bitfield for processing text key -- key to extract """ _MMD_LIB.extract_metadata_value.restype = ctypes.c_char_p _MMD_LIB.extract_metadata_value.argtypes = [ctypes.c_char_p, ctypes.c_ulong, ctypes.c_char_p] src = source.encode('utf-8') dkey = key.encode('utf-8') value = _MMD_LIB.extract_metadata_value(src, ext, dkey) return value.decode('utf-8') if value else ''
[ "def", "value", "(", "source", ",", "key", ",", "ext", "=", "COMPLETE", ")", ":", "_MMD_LIB", ".", "extract_metadata_value", ".", "restype", "=", "ctypes", ".", "c_char_p", "_MMD_LIB", ".", "extract_metadata_value", ".", "argtypes", "=", "[", "ctypes", ".", ...
Extracts value for the specified metadata key from the given extension set. Keyword arguments: source -- string containing MultiMarkdown text ext -- extension bitfield for processing text key -- key to extract
[ "Extracts", "value", "for", "the", "specified", "metadata", "key", "from", "the", "given", "extension", "set", "." ]
37b5a717241b837ca15b8a4d4cc3c06b4456bfbd
https://github.com/jasedit/pymmd/blob/37b5a717241b837ca15b8a4d4cc3c06b4456bfbd/pymmd/mmd.py#L166-L181
train
55,289
invinst/ResponseBot
responsebot/responsebot_client.py
ResponseBotClient.tweet
def tweet(self, text, in_reply_to=None, filename=None, file=None): """ Post a new tweet. :param text: the text to post :param in_reply_to: The ID of the tweet to reply to :param filename: If `file` param is not provided, read file from this path :param file: A file object, which will be used instead of opening `filename`. `filename` is still required, for MIME type detection and to use as a form field in the POST data :return: Tweet object """ if filename is None: return Tweet(self._client.update_status(status=text, in_reply_to_status_id=in_reply_to)._json) else: return Tweet(self._client.update_with_media(filename=filename, file=file, status=text, in_reply_to_status_id=in_reply_to)._json)
python
def tweet(self, text, in_reply_to=None, filename=None, file=None): """ Post a new tweet. :param text: the text to post :param in_reply_to: The ID of the tweet to reply to :param filename: If `file` param is not provided, read file from this path :param file: A file object, which will be used instead of opening `filename`. `filename` is still required, for MIME type detection and to use as a form field in the POST data :return: Tweet object """ if filename is None: return Tweet(self._client.update_status(status=text, in_reply_to_status_id=in_reply_to)._json) else: return Tweet(self._client.update_with_media(filename=filename, file=file, status=text, in_reply_to_status_id=in_reply_to)._json)
[ "def", "tweet", "(", "self", ",", "text", ",", "in_reply_to", "=", "None", ",", "filename", "=", "None", ",", "file", "=", "None", ")", ":", "if", "filename", "is", "None", ":", "return", "Tweet", "(", "self", ".", "_client", ".", "update_status", "(...
Post a new tweet. :param text: the text to post :param in_reply_to: The ID of the tweet to reply to :param filename: If `file` param is not provided, read file from this path :param file: A file object, which will be used instead of opening `filename`. `filename` is still required, for MIME type detection and to use as a form field in the POST data :return: Tweet object
[ "Post", "a", "new", "tweet", "." ]
a6b1a431a343007f7ae55a193e432a61af22253f
https://github.com/invinst/ResponseBot/blob/a6b1a431a343007f7ae55a193e432a61af22253f/responsebot/responsebot_client.py#L64-L80
train
55,290
invinst/ResponseBot
responsebot/responsebot_client.py
ResponseBotClient.retweet
def retweet(self, id): """ Retweet a tweet. :param id: ID of the tweet in question :return: True if success, False otherwise """ try: self._client.retweet(id=id) return True except TweepError as e: if e.api_code == TWITTER_PAGE_DOES_NOT_EXISTS_ERROR: return False raise
python
def retweet(self, id): """ Retweet a tweet. :param id: ID of the tweet in question :return: True if success, False otherwise """ try: self._client.retweet(id=id) return True except TweepError as e: if e.api_code == TWITTER_PAGE_DOES_NOT_EXISTS_ERROR: return False raise
[ "def", "retweet", "(", "self", ",", "id", ")", ":", "try", ":", "self", ".", "_client", ".", "retweet", "(", "id", "=", "id", ")", "return", "True", "except", "TweepError", "as", "e", ":", "if", "e", ".", "api_code", "==", "TWITTER_PAGE_DOES_NOT_EXISTS...
Retweet a tweet. :param id: ID of the tweet in question :return: True if success, False otherwise
[ "Retweet", "a", "tweet", "." ]
a6b1a431a343007f7ae55a193e432a61af22253f
https://github.com/invinst/ResponseBot/blob/a6b1a431a343007f7ae55a193e432a61af22253f/responsebot/responsebot_client.py#L82-L95
train
55,291
invinst/ResponseBot
responsebot/responsebot_client.py
ResponseBotClient.get_tweet
def get_tweet(self, id): """ Get an existing tweet. :param id: ID of the tweet in question :return: Tweet object. None if not found """ try: return Tweet(self._client.get_status(id=id)._json) except TweepError as e: if e.api_code == TWITTER_TWEET_NOT_FOUND_ERROR: return None raise
python
def get_tweet(self, id): """ Get an existing tweet. :param id: ID of the tweet in question :return: Tweet object. None if not found """ try: return Tweet(self._client.get_status(id=id)._json) except TweepError as e: if e.api_code == TWITTER_TWEET_NOT_FOUND_ERROR: return None raise
[ "def", "get_tweet", "(", "self", ",", "id", ")", ":", "try", ":", "return", "Tweet", "(", "self", ".", "_client", ".", "get_status", "(", "id", "=", "id", ")", ".", "_json", ")", "except", "TweepError", "as", "e", ":", "if", "e", ".", "api_code", ...
Get an existing tweet. :param id: ID of the tweet in question :return: Tweet object. None if not found
[ "Get", "an", "existing", "tweet", "." ]
a6b1a431a343007f7ae55a193e432a61af22253f
https://github.com/invinst/ResponseBot/blob/a6b1a431a343007f7ae55a193e432a61af22253f/responsebot/responsebot_client.py#L97-L109
train
55,292
invinst/ResponseBot
responsebot/responsebot_client.py
ResponseBotClient.get_user
def get_user(self, id): """ Get a user's info. :param id: ID of the user in question :return: User object. None if not found """ try: return User(self._client.get_user(user_id=id)._json) except TweepError as e: if e.api_code == TWITTER_USER_NOT_FOUND_ERROR: return None raise
python
def get_user(self, id): """ Get a user's info. :param id: ID of the user in question :return: User object. None if not found """ try: return User(self._client.get_user(user_id=id)._json) except TweepError as e: if e.api_code == TWITTER_USER_NOT_FOUND_ERROR: return None raise
[ "def", "get_user", "(", "self", ",", "id", ")", ":", "try", ":", "return", "User", "(", "self", ".", "_client", ".", "get_user", "(", "user_id", "=", "id", ")", ".", "_json", ")", "except", "TweepError", "as", "e", ":", "if", "e", ".", "api_code", ...
Get a user's info. :param id: ID of the user in question :return: User object. None if not found
[ "Get", "a", "user", "s", "info", "." ]
a6b1a431a343007f7ae55a193e432a61af22253f
https://github.com/invinst/ResponseBot/blob/a6b1a431a343007f7ae55a193e432a61af22253f/responsebot/responsebot_client.py#L111-L123
train
55,293
invinst/ResponseBot
responsebot/responsebot_client.py
ResponseBotClient.remove_tweet
def remove_tweet(self, id): """ Delete a tweet. :param id: ID of the tweet in question :return: True if success, False otherwise """ try: self._client.destroy_status(id=id) return True except TweepError as e: if e.api_code in [TWITTER_PAGE_DOES_NOT_EXISTS_ERROR, TWITTER_DELETE_OTHER_USER_TWEET]: return False raise
python
def remove_tweet(self, id): """ Delete a tweet. :param id: ID of the tweet in question :return: True if success, False otherwise """ try: self._client.destroy_status(id=id) return True except TweepError as e: if e.api_code in [TWITTER_PAGE_DOES_NOT_EXISTS_ERROR, TWITTER_DELETE_OTHER_USER_TWEET]: return False raise
[ "def", "remove_tweet", "(", "self", ",", "id", ")", ":", "try", ":", "self", ".", "_client", ".", "destroy_status", "(", "id", "=", "id", ")", "return", "True", "except", "TweepError", "as", "e", ":", "if", "e", ".", "api_code", "in", "[", "TWITTER_P...
Delete a tweet. :param id: ID of the tweet in question :return: True if success, False otherwise
[ "Delete", "a", "tweet", "." ]
a6b1a431a343007f7ae55a193e432a61af22253f
https://github.com/invinst/ResponseBot/blob/a6b1a431a343007f7ae55a193e432a61af22253f/responsebot/responsebot_client.py#L125-L138
train
55,294
invinst/ResponseBot
responsebot/responsebot_client.py
ResponseBotClient.create_list
def create_list(self, name, mode='public', description=None): """ Create a list :param name: Name of the new list :param mode: :code:`'public'` (default) or :code:`'private'` :param description: Description of the new list :return: The new list object :rtype: :class:`~responsebot.models.List` """ return List(tweepy_list_to_json(self._client.create_list(name=name, mode=mode, description=description)))
python
def create_list(self, name, mode='public', description=None): """ Create a list :param name: Name of the new list :param mode: :code:`'public'` (default) or :code:`'private'` :param description: Description of the new list :return: The new list object :rtype: :class:`~responsebot.models.List` """ return List(tweepy_list_to_json(self._client.create_list(name=name, mode=mode, description=description)))
[ "def", "create_list", "(", "self", ",", "name", ",", "mode", "=", "'public'", ",", "description", "=", "None", ")", ":", "return", "List", "(", "tweepy_list_to_json", "(", "self", ".", "_client", ".", "create_list", "(", "name", "=", "name", ",", "mode",...
Create a list :param name: Name of the new list :param mode: :code:`'public'` (default) or :code:`'private'` :param description: Description of the new list :return: The new list object :rtype: :class:`~responsebot.models.List`
[ "Create", "a", "list" ]
a6b1a431a343007f7ae55a193e432a61af22253f
https://github.com/invinst/ResponseBot/blob/a6b1a431a343007f7ae55a193e432a61af22253f/responsebot/responsebot_client.py#L168-L178
train
55,295
invinst/ResponseBot
responsebot/responsebot_client.py
ResponseBotClient.destroy_list
def destroy_list(self, list_id): """ Destroy a list :param list_id: list ID number :return: The destroyed list object :rtype: :class:`~responsebot.models.List` """ return List(tweepy_list_to_json(self._client.destroy_list(list_id=list_id)))
python
def destroy_list(self, list_id): """ Destroy a list :param list_id: list ID number :return: The destroyed list object :rtype: :class:`~responsebot.models.List` """ return List(tweepy_list_to_json(self._client.destroy_list(list_id=list_id)))
[ "def", "destroy_list", "(", "self", ",", "list_id", ")", ":", "return", "List", "(", "tweepy_list_to_json", "(", "self", ".", "_client", ".", "destroy_list", "(", "list_id", "=", "list_id", ")", ")", ")" ]
Destroy a list :param list_id: list ID number :return: The destroyed list object :rtype: :class:`~responsebot.models.List`
[ "Destroy", "a", "list" ]
a6b1a431a343007f7ae55a193e432a61af22253f
https://github.com/invinst/ResponseBot/blob/a6b1a431a343007f7ae55a193e432a61af22253f/responsebot/responsebot_client.py#L181-L189
train
55,296
invinst/ResponseBot
responsebot/responsebot_client.py
ResponseBotClient.update_list
def update_list(self, list_id, name=None, mode=None, description=None): """ Update a list :param list_id: list ID number :param name: New name for the list :param mode: :code:`'public'` (default) or :code:`'private'` :param description: New description of the list :return: The updated list object :rtype: :class:`~responsebot.models.List` """ return List(tweepy_list_to_json( self._client.update_list(list_id=list_id, name=name, mode=mode, description=description)) )
python
def update_list(self, list_id, name=None, mode=None, description=None): """ Update a list :param list_id: list ID number :param name: New name for the list :param mode: :code:`'public'` (default) or :code:`'private'` :param description: New description of the list :return: The updated list object :rtype: :class:`~responsebot.models.List` """ return List(tweepy_list_to_json( self._client.update_list(list_id=list_id, name=name, mode=mode, description=description)) )
[ "def", "update_list", "(", "self", ",", "list_id", ",", "name", "=", "None", ",", "mode", "=", "None", ",", "description", "=", "None", ")", ":", "return", "List", "(", "tweepy_list_to_json", "(", "self", ".", "_client", ".", "update_list", "(", "list_id...
Update a list :param list_id: list ID number :param name: New name for the list :param mode: :code:`'public'` (default) or :code:`'private'` :param description: New description of the list :return: The updated list object :rtype: :class:`~responsebot.models.List`
[ "Update", "a", "list" ]
a6b1a431a343007f7ae55a193e432a61af22253f
https://github.com/invinst/ResponseBot/blob/a6b1a431a343007f7ae55a193e432a61af22253f/responsebot/responsebot_client.py#L192-L205
train
55,297
invinst/ResponseBot
responsebot/responsebot_client.py
ResponseBotClient.list_timeline
def list_timeline(self, list_id, since_id=None, max_id=None, count=20): """ List the tweets of specified list. :param list_id: list ID number :param since_id: results will have ID greater than specified ID (more recent than) :param max_id: results will have ID less than specified ID (older than) :param count: number of results per page :return: list of :class:`~responsebot.models.Tweet` objects """ statuses = self._client.list_timeline(list_id=list_id, since_id=since_id, max_id=max_id, count=count) return [Tweet(tweet._json) for tweet in statuses]
python
def list_timeline(self, list_id, since_id=None, max_id=None, count=20): """ List the tweets of specified list. :param list_id: list ID number :param since_id: results will have ID greater than specified ID (more recent than) :param max_id: results will have ID less than specified ID (older than) :param count: number of results per page :return: list of :class:`~responsebot.models.Tweet` objects """ statuses = self._client.list_timeline(list_id=list_id, since_id=since_id, max_id=max_id, count=count) return [Tweet(tweet._json) for tweet in statuses]
[ "def", "list_timeline", "(", "self", ",", "list_id", ",", "since_id", "=", "None", ",", "max_id", "=", "None", ",", "count", "=", "20", ")", ":", "statuses", "=", "self", ".", "_client", ".", "list_timeline", "(", "list_id", "=", "list_id", ",", "since...
List the tweets of specified list. :param list_id: list ID number :param since_id: results will have ID greater than specified ID (more recent than) :param max_id: results will have ID less than specified ID (older than) :param count: number of results per page :return: list of :class:`~responsebot.models.Tweet` objects
[ "List", "the", "tweets", "of", "specified", "list", "." ]
a6b1a431a343007f7ae55a193e432a61af22253f
https://github.com/invinst/ResponseBot/blob/a6b1a431a343007f7ae55a193e432a61af22253f/responsebot/responsebot_client.py#L235-L246
train
55,298
invinst/ResponseBot
responsebot/responsebot_client.py
ResponseBotClient.get_list
def get_list(self, list_id): """ Get info of specified list :param list_id: list ID number :return: :class:`~responsebot.models.List` object """ return List(tweepy_list_to_json(self._client.get_list(list_id=list_id)))
python
def get_list(self, list_id): """ Get info of specified list :param list_id: list ID number :return: :class:`~responsebot.models.List` object """ return List(tweepy_list_to_json(self._client.get_list(list_id=list_id)))
[ "def", "get_list", "(", "self", ",", "list_id", ")", ":", "return", "List", "(", "tweepy_list_to_json", "(", "self", ".", "_client", ".", "get_list", "(", "list_id", "=", "list_id", ")", ")", ")" ]
Get info of specified list :param list_id: list ID number :return: :class:`~responsebot.models.List` object
[ "Get", "info", "of", "specified", "list" ]
a6b1a431a343007f7ae55a193e432a61af22253f
https://github.com/invinst/ResponseBot/blob/a6b1a431a343007f7ae55a193e432a61af22253f/responsebot/responsebot_client.py#L249-L256
train
55,299