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
jmbhughes/suvi-trainer
suvitrainer/gui.py
App.on_exit
def on_exit(self): """ When you click to exit, this function is called, prompts whether to save""" answer = messagebox.askyesnocancel("Exit", "Do you want to save as you quit the application?") if answer: self.save() self.quit() self.destroy() elif answer is None: pass # the cancel action else: self.quit() self.destroy()
python
def on_exit(self): """ When you click to exit, this function is called, prompts whether to save""" answer = messagebox.askyesnocancel("Exit", "Do you want to save as you quit the application?") if answer: self.save() self.quit() self.destroy() elif answer is None: pass # the cancel action else: self.quit() self.destroy()
[ "def", "on_exit", "(", "self", ")", ":", "answer", "=", "messagebox", ".", "askyesnocancel", "(", "\"Exit\"", ",", "\"Do you want to save as you quit the application?\"", ")", "if", "answer", ":", "self", ".", "save", "(", ")", "self", ".", "quit", "(", ")", ...
When you click to exit, this function is called, prompts whether to save
[ "When", "you", "click", "to", "exit", "this", "function", "is", "called", "prompts", "whether", "to", "save" ]
3d89894a4a037286221974c7eb5634d229b4f5d4
https://github.com/jmbhughes/suvi-trainer/blob/3d89894a4a037286221974c7eb5634d229b4f5d4/suvitrainer/gui.py#L204-L215
train
54,400
jmbhughes/suvi-trainer
suvitrainer/gui.py
App.make_gui
def make_gui(self): """ Setups the general structure of the gui, the first function called """ self.option_window = Toplevel() self.option_window.protocol("WM_DELETE_WINDOW", self.on_exit) self.canvas_frame = tk.Frame(self, height=500) self.option_frame = tk.Frame(self.option_window, height=300) self.canvas_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) self.option_frame.pack(side=tk.RIGHT, fill=None, expand=False) self.make_options_frame() self.make_canvas_frame() self.disable_singlecolor()
python
def make_gui(self): """ Setups the general structure of the gui, the first function called """ self.option_window = Toplevel() self.option_window.protocol("WM_DELETE_WINDOW", self.on_exit) self.canvas_frame = tk.Frame(self, height=500) self.option_frame = tk.Frame(self.option_window, height=300) self.canvas_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) self.option_frame.pack(side=tk.RIGHT, fill=None, expand=False) self.make_options_frame() self.make_canvas_frame() self.disable_singlecolor()
[ "def", "make_gui", "(", "self", ")", ":", "self", ".", "option_window", "=", "Toplevel", "(", ")", "self", ".", "option_window", ".", "protocol", "(", "\"WM_DELETE_WINDOW\"", ",", "self", ".", "on_exit", ")", "self", ".", "canvas_frame", "=", "tk", ".", ...
Setups the general structure of the gui, the first function called
[ "Setups", "the", "general", "structure", "of", "the", "gui", "the", "first", "function", "called" ]
3d89894a4a037286221974c7eb5634d229b4f5d4
https://github.com/jmbhughes/suvi-trainer/blob/3d89894a4a037286221974c7eb5634d229b4f5d4/suvitrainer/gui.py#L222-L232
train
54,401
jmbhughes/suvi-trainer
suvitrainer/gui.py
App.make_options_frame
def make_options_frame(self): """ make the frame that allows for configuration and classification""" self.tab_frame = ttk.Notebook(self.option_frame, width=800) self.tab_configure = tk.Frame(self.tab_frame) self.tab_classify = tk.Frame(self.tab_frame) self.make_configure_tab() self.make_classify_tab() self.tab_frame.add(self.tab_configure, text="Configure") self.tab_frame.add(self.tab_classify, text="Classify") self.tab_frame.pack(fill=tk.BOTH, expand=True)
python
def make_options_frame(self): """ make the frame that allows for configuration and classification""" self.tab_frame = ttk.Notebook(self.option_frame, width=800) self.tab_configure = tk.Frame(self.tab_frame) self.tab_classify = tk.Frame(self.tab_frame) self.make_configure_tab() self.make_classify_tab() self.tab_frame.add(self.tab_configure, text="Configure") self.tab_frame.add(self.tab_classify, text="Classify") self.tab_frame.pack(fill=tk.BOTH, expand=True)
[ "def", "make_options_frame", "(", "self", ")", ":", "self", ".", "tab_frame", "=", "ttk", ".", "Notebook", "(", "self", ".", "option_frame", ",", "width", "=", "800", ")", "self", ".", "tab_configure", "=", "tk", ".", "Frame", "(", "self", ".", "tab_fr...
make the frame that allows for configuration and classification
[ "make", "the", "frame", "that", "allows", "for", "configuration", "and", "classification" ]
3d89894a4a037286221974c7eb5634d229b4f5d4
https://github.com/jmbhughes/suvi-trainer/blob/3d89894a4a037286221974c7eb5634d229b4f5d4/suvitrainer/gui.py#L447-L457
train
54,402
jmbhughes/suvi-trainer
suvitrainer/gui.py
App.disable_multicolor
def disable_multicolor(self): """ swap from the multicolor image to the single color image """ # disable the multicolor image for color in ['red', 'green', 'blue']: self.multicolorscales[color].config(state=tk.DISABLED, bg='grey') self.multicolorframes[color].config(bg='grey') self.multicolorlabels[color].config(bg='grey') self.multicolordropdowns[color].config(bg='grey', state=tk.DISABLED) self.multicolorminscale[color].config(bg='grey', state=tk.DISABLED) self.multicolormaxscale[color].config(bg='grey', state=tk.DISABLED) # enable the single color self.singlecolorscale.config(state=tk.NORMAL, bg=self.single_color_theme) self.singlecolorframe.config(bg=self.single_color_theme) self.singlecolorlabel.config(bg=self.single_color_theme) self.singlecolordropdown.config(bg=self.single_color_theme, state=tk.NORMAL) self.singlecolorminscale.config(bg=self.single_color_theme, state=tk.NORMAL) self.singlecolormaxscale.config(bg=self.single_color_theme, state=tk.NORMAL)
python
def disable_multicolor(self): """ swap from the multicolor image to the single color image """ # disable the multicolor image for color in ['red', 'green', 'blue']: self.multicolorscales[color].config(state=tk.DISABLED, bg='grey') self.multicolorframes[color].config(bg='grey') self.multicolorlabels[color].config(bg='grey') self.multicolordropdowns[color].config(bg='grey', state=tk.DISABLED) self.multicolorminscale[color].config(bg='grey', state=tk.DISABLED) self.multicolormaxscale[color].config(bg='grey', state=tk.DISABLED) # enable the single color self.singlecolorscale.config(state=tk.NORMAL, bg=self.single_color_theme) self.singlecolorframe.config(bg=self.single_color_theme) self.singlecolorlabel.config(bg=self.single_color_theme) self.singlecolordropdown.config(bg=self.single_color_theme, state=tk.NORMAL) self.singlecolorminscale.config(bg=self.single_color_theme, state=tk.NORMAL) self.singlecolormaxscale.config(bg=self.single_color_theme, state=tk.NORMAL)
[ "def", "disable_multicolor", "(", "self", ")", ":", "# disable the multicolor image", "for", "color", "in", "[", "'red'", ",", "'green'", ",", "'blue'", "]", ":", "self", ".", "multicolorscales", "[", "color", "]", ".", "config", "(", "state", "=", "tk", "...
swap from the multicolor image to the single color image
[ "swap", "from", "the", "multicolor", "image", "to", "the", "single", "color", "image" ]
3d89894a4a037286221974c7eb5634d229b4f5d4
https://github.com/jmbhughes/suvi-trainer/blob/3d89894a4a037286221974c7eb5634d229b4f5d4/suvitrainer/gui.py#L459-L476
train
54,403
jmbhughes/suvi-trainer
suvitrainer/gui.py
App.update_button_action
def update_button_action(self): """ when update button is clicked, refresh the data preview""" if self.mode.get() == 3: # threecolor self.configure_threecolor_image() elif self.mode.get() == 1: # singlecolor self.configure_singlecolor_image() else: raise ValueError("mode can only be singlecolor or threecolor") self.imageplot.set_data(self.image) if self.mode.get() == 1: # singlecolor self.imageplot.set_cmap('gist_gray') self.fig.canvas.draw_idle()
python
def update_button_action(self): """ when update button is clicked, refresh the data preview""" if self.mode.get() == 3: # threecolor self.configure_threecolor_image() elif self.mode.get() == 1: # singlecolor self.configure_singlecolor_image() else: raise ValueError("mode can only be singlecolor or threecolor") self.imageplot.set_data(self.image) if self.mode.get() == 1: # singlecolor self.imageplot.set_cmap('gist_gray') self.fig.canvas.draw_idle()
[ "def", "update_button_action", "(", "self", ")", ":", "if", "self", ".", "mode", ".", "get", "(", ")", "==", "3", ":", "# threecolor", "self", ".", "configure_threecolor_image", "(", ")", "elif", "self", ".", "mode", ".", "get", "(", ")", "==", "1", ...
when update button is clicked, refresh the data preview
[ "when", "update", "button", "is", "clicked", "refresh", "the", "data", "preview" ]
3d89894a4a037286221974c7eb5634d229b4f5d4
https://github.com/jmbhughes/suvi-trainer/blob/3d89894a4a037286221974c7eb5634d229b4f5d4/suvitrainer/gui.py#L497-L509
train
54,404
jmbhughes/suvi-trainer
suvitrainer/gui.py
App.make_configure_tab
def make_configure_tab(self): """ initial set up of configure tab""" # Setup the choice between single and multicolor modeframe = tk.Frame(self.tab_configure) self.mode = tk.IntVar() singlecolor = tk.Radiobutton(modeframe, text="Single color", variable=self.mode, value=1, command=lambda: self.disable_multicolor()) multicolor = tk.Radiobutton(modeframe, text="Three color", variable=self.mode, value=3, command=lambda: self.disable_singlecolor()) self.mode.set(3) singlecolor.pack(side=tk.LEFT) multicolor.pack(side=tk.LEFT) updatebutton = tk.Button(master=modeframe, text="Update", command=self.update_button_action) updatebutton.pack(side=tk.RIGHT) modeframe.grid(row=0, column=0) self.setup_multicolor() self.setup_singlecolor()
python
def make_configure_tab(self): """ initial set up of configure tab""" # Setup the choice between single and multicolor modeframe = tk.Frame(self.tab_configure) self.mode = tk.IntVar() singlecolor = tk.Radiobutton(modeframe, text="Single color", variable=self.mode, value=1, command=lambda: self.disable_multicolor()) multicolor = tk.Radiobutton(modeframe, text="Three color", variable=self.mode, value=3, command=lambda: self.disable_singlecolor()) self.mode.set(3) singlecolor.pack(side=tk.LEFT) multicolor.pack(side=tk.LEFT) updatebutton = tk.Button(master=modeframe, text="Update", command=self.update_button_action) updatebutton.pack(side=tk.RIGHT) modeframe.grid(row=0, column=0) self.setup_multicolor() self.setup_singlecolor()
[ "def", "make_configure_tab", "(", "self", ")", ":", "# Setup the choice between single and multicolor", "modeframe", "=", "tk", ".", "Frame", "(", "self", ".", "tab_configure", ")", "self", ".", "mode", "=", "tk", ".", "IntVar", "(", ")", "singlecolor", "=", "...
initial set up of configure tab
[ "initial", "set", "up", "of", "configure", "tab" ]
3d89894a4a037286221974c7eb5634d229b4f5d4
https://github.com/jmbhughes/suvi-trainer/blob/3d89894a4a037286221974c7eb5634d229b4f5d4/suvitrainer/gui.py#L511-L529
train
54,405
jmbhughes/suvi-trainer
suvitrainer/gui.py
App.make_classify_tab
def make_classify_tab(self): """ initial set up of classification tab""" self.pick_frame = tk.Frame(self.tab_classify) self.pick_frame2 = tk.Frame(self.tab_classify) self.solar_class_var = tk.IntVar() self.solar_class_var.set(0) # initialize to unlabeled buttonnum = 0 frame = [self.pick_frame, self.pick_frame2] for text, value in self.config.solar_classes: b = tk.Radiobutton(frame[buttonnum % 2], text=text, variable=self.solar_class_var, value=value, background=self.config.solar_colors[text], indicatoron=0, width=50, height=2, command=self.change_class) b.pack(fill=tk.BOTH, expand=1) buttonnum += 1 self.pick_frame.grid(row=0, column=0, rowspan=5, sticky=tk.W + tk.E + tk.N + tk.S) self.pick_frame2.grid(row=0, column=1, rowspan=5, sticky=tk.W + tk.E + tk.N + tk.S) undobutton = tk.Button(master=self.tab_classify, text="Undo", command=self.undobutton_action) undobutton.grid(row=6, column=0, columnspan=2, sticky=tk.W + tk.E)
python
def make_classify_tab(self): """ initial set up of classification tab""" self.pick_frame = tk.Frame(self.tab_classify) self.pick_frame2 = tk.Frame(self.tab_classify) self.solar_class_var = tk.IntVar() self.solar_class_var.set(0) # initialize to unlabeled buttonnum = 0 frame = [self.pick_frame, self.pick_frame2] for text, value in self.config.solar_classes: b = tk.Radiobutton(frame[buttonnum % 2], text=text, variable=self.solar_class_var, value=value, background=self.config.solar_colors[text], indicatoron=0, width=50, height=2, command=self.change_class) b.pack(fill=tk.BOTH, expand=1) buttonnum += 1 self.pick_frame.grid(row=0, column=0, rowspan=5, sticky=tk.W + tk.E + tk.N + tk.S) self.pick_frame2.grid(row=0, column=1, rowspan=5, sticky=tk.W + tk.E + tk.N + tk.S) undobutton = tk.Button(master=self.tab_classify, text="Undo", command=self.undobutton_action) undobutton.grid(row=6, column=0, columnspan=2, sticky=tk.W + tk.E)
[ "def", "make_classify_tab", "(", "self", ")", ":", "self", ".", "pick_frame", "=", "tk", ".", "Frame", "(", "self", ".", "tab_classify", ")", "self", ".", "pick_frame2", "=", "tk", ".", "Frame", "(", "self", ".", "tab_classify", ")", "self", ".", "sola...
initial set up of classification tab
[ "initial", "set", "up", "of", "classification", "tab" ]
3d89894a4a037286221974c7eb5634d229b4f5d4
https://github.com/jmbhughes/suvi-trainer/blob/3d89894a4a037286221974c7eb5634d229b4f5d4/suvitrainer/gui.py#L531-L554
train
54,406
jmbhughes/suvi-trainer
suvitrainer/gui.py
App.setup_singlecolor
def setup_singlecolor(self): """ initial setup of single color options and variables""" self.singlecolorframe = tk.Frame(self.tab_configure, bg=self.single_color_theme) channel_choices = sorted(list(self.data.keys())) self.singlecolorlabel = tk.Label(self.singlecolorframe, text="single", bg=self.single_color_theme, width=10) self.singlecolorvar = tk.StringVar() self.singlecolorpower = tk.DoubleVar() self.singlecolormin = tk.DoubleVar() self.singlecolormax = tk.DoubleVar() self.singlecolordropdown = tk.OptionMenu(self.singlecolorframe, self.singlecolorvar, *channel_choices) self.singlecolorscale = tk.Scale(self.singlecolorframe, variable=self.singlecolorpower, orient=tk.HORIZONTAL, from_=self.config.ranges['single_color_power_min'], bg=self.single_color_theme, to_=self.config.ranges['single_color_power_max'], resolution=self.config.ranges['single_color_power_resolution'], length=200) self.singlecolorminscale = tk.Scale(self.singlecolorframe, variable=self.singlecolormin, orient=tk.HORIZONTAL, from_=0, bg=self.single_color_theme, to_=self.config.ranges['single_color_vmin'], resolution=self.config.ranges['single_color_vresolution'], length=200) self.singlecolormaxscale = tk.Scale(self.singlecolorframe, variable=self.singlecolormax, orient=tk.HORIZONTAL, from_=self.config.ranges['single_color_vmax'], bg=self.single_color_theme, to_=100, resolution=self.config.ranges['single_color_vresolution'], length=200) self.singlecolorvar.set(self.config.products_map[self.config.default['single']]) self.singlecolorpower.set(self.config.default['single_power']) self.singlecolormin.set(0) self.singlecolormax.set(100) self.singlecolordropdown.config(bg=self.single_color_theme, width=10) self.singlecolorlabel.pack(side=tk.LEFT) self.singlecolorscale.pack(side=tk.RIGHT) self.singlecolormaxscale.pack(side=tk.RIGHT) self.singlecolorminscale.pack(side=tk.RIGHT) self.singlecolordropdown.pack() self.singlecolorframe.grid(row=4, columnspan=5, rowspan=1)
python
def setup_singlecolor(self): """ initial setup of single color options and variables""" self.singlecolorframe = tk.Frame(self.tab_configure, bg=self.single_color_theme) channel_choices = sorted(list(self.data.keys())) self.singlecolorlabel = tk.Label(self.singlecolorframe, text="single", bg=self.single_color_theme, width=10) self.singlecolorvar = tk.StringVar() self.singlecolorpower = tk.DoubleVar() self.singlecolormin = tk.DoubleVar() self.singlecolormax = tk.DoubleVar() self.singlecolordropdown = tk.OptionMenu(self.singlecolorframe, self.singlecolorvar, *channel_choices) self.singlecolorscale = tk.Scale(self.singlecolorframe, variable=self.singlecolorpower, orient=tk.HORIZONTAL, from_=self.config.ranges['single_color_power_min'], bg=self.single_color_theme, to_=self.config.ranges['single_color_power_max'], resolution=self.config.ranges['single_color_power_resolution'], length=200) self.singlecolorminscale = tk.Scale(self.singlecolorframe, variable=self.singlecolormin, orient=tk.HORIZONTAL, from_=0, bg=self.single_color_theme, to_=self.config.ranges['single_color_vmin'], resolution=self.config.ranges['single_color_vresolution'], length=200) self.singlecolormaxscale = tk.Scale(self.singlecolorframe, variable=self.singlecolormax, orient=tk.HORIZONTAL, from_=self.config.ranges['single_color_vmax'], bg=self.single_color_theme, to_=100, resolution=self.config.ranges['single_color_vresolution'], length=200) self.singlecolorvar.set(self.config.products_map[self.config.default['single']]) self.singlecolorpower.set(self.config.default['single_power']) self.singlecolormin.set(0) self.singlecolormax.set(100) self.singlecolordropdown.config(bg=self.single_color_theme, width=10) self.singlecolorlabel.pack(side=tk.LEFT) self.singlecolorscale.pack(side=tk.RIGHT) self.singlecolormaxscale.pack(side=tk.RIGHT) self.singlecolorminscale.pack(side=tk.RIGHT) self.singlecolordropdown.pack() self.singlecolorframe.grid(row=4, columnspan=5, rowspan=1)
[ "def", "setup_singlecolor", "(", "self", ")", ":", "self", ".", "singlecolorframe", "=", "tk", ".", "Frame", "(", "self", ".", "tab_configure", ",", "bg", "=", "self", ".", "single_color_theme", ")", "channel_choices", "=", "sorted", "(", "list", "(", "sel...
initial setup of single color options and variables
[ "initial", "setup", "of", "single", "color", "options", "and", "variables" ]
3d89894a4a037286221974c7eb5634d229b4f5d4
https://github.com/jmbhughes/suvi-trainer/blob/3d89894a4a037286221974c7eb5634d229b4f5d4/suvitrainer/gui.py#L556-L594
train
54,407
jmbhughes/suvi-trainer
suvitrainer/gui.py
App.undobutton_action
def undobutton_action(self): """ when undo is clicked, revert the thematic map to the previous state""" if len(self.history) > 1: old = self.history.pop(-1) self.selection_array = old self.mask.set_data(old) self.fig.canvas.draw_idle()
python
def undobutton_action(self): """ when undo is clicked, revert the thematic map to the previous state""" if len(self.history) > 1: old = self.history.pop(-1) self.selection_array = old self.mask.set_data(old) self.fig.canvas.draw_idle()
[ "def", "undobutton_action", "(", "self", ")", ":", "if", "len", "(", "self", ".", "history", ")", ">", "1", ":", "old", "=", "self", ".", "history", ".", "pop", "(", "-", "1", ")", "self", ".", "selection_array", "=", "old", "self", ".", "mask", ...
when undo is clicked, revert the thematic map to the previous state
[ "when", "undo", "is", "clicked", "revert", "the", "thematic", "map", "to", "the", "previous", "state" ]
3d89894a4a037286221974c7eb5634d229b4f5d4
https://github.com/jmbhughes/suvi-trainer/blob/3d89894a4a037286221974c7eb5634d229b4f5d4/suvitrainer/gui.py#L650-L656
train
54,408
jmbhughes/suvi-trainer
suvitrainer/gui.py
App.change_class
def change_class(self): """ "on changing the classification label, update the "draw" text """ self.toolbarcenterframe.config(text="Draw: {}".format(self.config.solar_class_name[self.solar_class_var.get()]))
python
def change_class(self): """ "on changing the classification label, update the "draw" text """ self.toolbarcenterframe.config(text="Draw: {}".format(self.config.solar_class_name[self.solar_class_var.get()]))
[ "def", "change_class", "(", "self", ")", ":", "self", ".", "toolbarcenterframe", ".", "config", "(", "text", "=", "\"Draw: {}\"", ".", "format", "(", "self", ".", "config", ".", "solar_class_name", "[", "self", ".", "solar_class_var", ".", "get", "(", ")",...
"on changing the classification label, update the "draw" text
[ "on", "changing", "the", "classification", "label", "update", "the", "draw", "text" ]
3d89894a4a037286221974c7eb5634d229b4f5d4
https://github.com/jmbhughes/suvi-trainer/blob/3d89894a4a037286221974c7eb5634d229b4f5d4/suvitrainer/gui.py#L658-L660
train
54,409
portfors-lab/sparkle
sparkle/gui/dialogs/specgram_dlg.py
SpecDialog.values
def values(self): """Gets the parameter values :returns: dict of inputs: | *'nfft'*: int -- length, in samples, of FFT chunks | *'window'*: str -- name of window to apply to FFT chunks | *'overlap'*: float -- percent overlap of windows """ self.vals['nfft'] = self.ui.nfftSpnbx.value() self.vals['window'] = str(self.ui.windowCmbx.currentText()).lower() self.vals['overlap'] = self.ui.overlapSpnbx.value() return self.vals
python
def values(self): """Gets the parameter values :returns: dict of inputs: | *'nfft'*: int -- length, in samples, of FFT chunks | *'window'*: str -- name of window to apply to FFT chunks | *'overlap'*: float -- percent overlap of windows """ self.vals['nfft'] = self.ui.nfftSpnbx.value() self.vals['window'] = str(self.ui.windowCmbx.currentText()).lower() self.vals['overlap'] = self.ui.overlapSpnbx.value() return self.vals
[ "def", "values", "(", "self", ")", ":", "self", ".", "vals", "[", "'nfft'", "]", "=", "self", ".", "ui", ".", "nfftSpnbx", ".", "value", "(", ")", "self", ".", "vals", "[", "'window'", "]", "=", "str", "(", "self", ".", "ui", ".", "windowCmbx", ...
Gets the parameter values :returns: dict of inputs: | *'nfft'*: int -- length, in samples, of FFT chunks | *'window'*: str -- name of window to apply to FFT chunks | *'overlap'*: float -- percent overlap of windows
[ "Gets", "the", "parameter", "values" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/dialogs/specgram_dlg.py#L23-L34
train
54,410
TorkamaniLab/metapipe
metapipe/app.py
main
def main(): """ Parses the command-line args, and calls run. """ parser = argparse.ArgumentParser( description='A pipeline that generates analysis pipelines.') parser.add_argument('input', nargs='?', help='A valid metapipe configuration file.') parser.add_argument('-o', '--output', help='An output destination. If none is provided, the ' 'results will be printed to stdout.', default=sys.stdout) parser.add_argument('-t', '--temp', help='A desired metapipe binary file. This is used to store ' 'temp data between generation and execution. ' '(Default: "%(default)s")', default='.metapipe') parser.add_argument('-s', '--shell', help='The path to the shell to be used when executing the ' 'pipeline. (Default: "%(default)s)"', default='/bin/bash') parser.add_argument('-r', '--run', help='Run the pipeline as soon as it\'s ready.', action='store_true') parser.add_argument('-n', '--name', help='A name for the pipeline.', default='') parser.add_argument('-j', '--job-type', help='The destination for calculations (i.e. local, a PBS ' 'queue on a cluster, etc).\nOptions: {}. ' '(Default: "%(default)s)"'.format(JOB_TYPES.keys()), default='local') parser.add_argument('-p', '--max-jobs', help='The maximum number of concurrent jobs allowed. ' 'Defaults to maximum available cores.', default=None) parser.add_argument('--report-type', help='The output report type. By default metapipe will ' 'print updates to the console. \nOptions: {}. ' '(Default: "%(default)s)"'.format(QUEUE_TYPES.keys()), default='text') parser.add_argument('-v','--version', help='Displays the current version of the application.', action='store_true') args = parser.parse_args() if args.version: print('Version: {}'.format(__version__)) sys.exit(0) try: with open(args.input) as f: config = f.read() except IOError: print('No valid config file found.') return -1 run(config, args.max_jobs, args.output, args.job_type, args.report_type, args.shell, args.temp, args.run)
python
def main(): """ Parses the command-line args, and calls run. """ parser = argparse.ArgumentParser( description='A pipeline that generates analysis pipelines.') parser.add_argument('input', nargs='?', help='A valid metapipe configuration file.') parser.add_argument('-o', '--output', help='An output destination. If none is provided, the ' 'results will be printed to stdout.', default=sys.stdout) parser.add_argument('-t', '--temp', help='A desired metapipe binary file. This is used to store ' 'temp data between generation and execution. ' '(Default: "%(default)s")', default='.metapipe') parser.add_argument('-s', '--shell', help='The path to the shell to be used when executing the ' 'pipeline. (Default: "%(default)s)"', default='/bin/bash') parser.add_argument('-r', '--run', help='Run the pipeline as soon as it\'s ready.', action='store_true') parser.add_argument('-n', '--name', help='A name for the pipeline.', default='') parser.add_argument('-j', '--job-type', help='The destination for calculations (i.e. local, a PBS ' 'queue on a cluster, etc).\nOptions: {}. ' '(Default: "%(default)s)"'.format(JOB_TYPES.keys()), default='local') parser.add_argument('-p', '--max-jobs', help='The maximum number of concurrent jobs allowed. ' 'Defaults to maximum available cores.', default=None) parser.add_argument('--report-type', help='The output report type. By default metapipe will ' 'print updates to the console. \nOptions: {}. ' '(Default: "%(default)s)"'.format(QUEUE_TYPES.keys()), default='text') parser.add_argument('-v','--version', help='Displays the current version of the application.', action='store_true') args = parser.parse_args() if args.version: print('Version: {}'.format(__version__)) sys.exit(0) try: with open(args.input) as f: config = f.read() except IOError: print('No valid config file found.') return -1 run(config, args.max_jobs, args.output, args.job_type, args.report_type, args.shell, args.temp, args.run)
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'A pipeline that generates analysis pipelines.'", ")", "parser", ".", "add_argument", "(", "'input'", ",", "nargs", "=", "'?'", ",", "help", "=", "'A valid ...
Parses the command-line args, and calls run.
[ "Parses", "the", "command", "-", "line", "args", "and", "calls", "run", "." ]
15592e5b0c217afb00ac03503f8d0d7453d4baf4
https://github.com/TorkamaniLab/metapipe/blob/15592e5b0c217afb00ac03503f8d0d7453d4baf4/metapipe/app.py#L39-L94
train
54,411
TorkamaniLab/metapipe
metapipe/app.py
run
def run(config, max_jobs, output=sys.stdout, job_type='local', report_type='text', shell='/bin/bash', temp='.metapipe', run_now=False): """ Create the metapipe based on the provided input. """ if max_jobs == None: max_jobs = cpu_count() parser = Parser(config) try: command_templates = parser.consume() except ValueError as e: raise SyntaxError('Invalid config file. \n%s' % e) options = '\n'.join(parser.global_options) queue_type = QUEUE_TYPES[report_type] pipeline = Runtime(command_templates,queue_type,JOB_TYPES,job_type,max_jobs) template = env.get_template('output_script.tmpl.sh') with open(temp, 'wb') as f: pickle.dump(pipeline, f, 2) script = template.render(shell=shell, temp=os.path.abspath(temp), options=options) if run_now: output = output if output != sys.stdout else PIPELINE_ALIAS submit_job = make_submit_job(shell, output, job_type) submit_job.submit() try: f = open(output, 'w') output = f except TypeError: pass output.write(script) f.close()
python
def run(config, max_jobs, output=sys.stdout, job_type='local', report_type='text', shell='/bin/bash', temp='.metapipe', run_now=False): """ Create the metapipe based on the provided input. """ if max_jobs == None: max_jobs = cpu_count() parser = Parser(config) try: command_templates = parser.consume() except ValueError as e: raise SyntaxError('Invalid config file. \n%s' % e) options = '\n'.join(parser.global_options) queue_type = QUEUE_TYPES[report_type] pipeline = Runtime(command_templates,queue_type,JOB_TYPES,job_type,max_jobs) template = env.get_template('output_script.tmpl.sh') with open(temp, 'wb') as f: pickle.dump(pipeline, f, 2) script = template.render(shell=shell, temp=os.path.abspath(temp), options=options) if run_now: output = output if output != sys.stdout else PIPELINE_ALIAS submit_job = make_submit_job(shell, output, job_type) submit_job.submit() try: f = open(output, 'w') output = f except TypeError: pass output.write(script) f.close()
[ "def", "run", "(", "config", ",", "max_jobs", ",", "output", "=", "sys", ".", "stdout", ",", "job_type", "=", "'local'", ",", "report_type", "=", "'text'", ",", "shell", "=", "'/bin/bash'", ",", "temp", "=", "'.metapipe'", ",", "run_now", "=", "False", ...
Create the metapipe based on the provided input.
[ "Create", "the", "metapipe", "based", "on", "the", "provided", "input", "." ]
15592e5b0c217afb00ac03503f8d0d7453d4baf4
https://github.com/TorkamaniLab/metapipe/blob/15592e5b0c217afb00ac03503f8d0d7453d4baf4/metapipe/app.py#L97-L131
train
54,412
TorkamaniLab/metapipe
metapipe/app.py
make_submit_job
def make_submit_job(shell, output, job_type): """ Preps the metapipe main job to be submitted. """ run_cmd = [shell, output] submit_command = Command(alias=PIPELINE_ALIAS, cmds=run_cmd) submit_job = get_job(submit_command, job_type) submit_job.make() return submit_job
python
def make_submit_job(shell, output, job_type): """ Preps the metapipe main job to be submitted. """ run_cmd = [shell, output] submit_command = Command(alias=PIPELINE_ALIAS, cmds=run_cmd) submit_job = get_job(submit_command, job_type) submit_job.make() return submit_job
[ "def", "make_submit_job", "(", "shell", ",", "output", ",", "job_type", ")", ":", "run_cmd", "=", "[", "shell", ",", "output", "]", "submit_command", "=", "Command", "(", "alias", "=", "PIPELINE_ALIAS", ",", "cmds", "=", "run_cmd", ")", "submit_job", "=", ...
Preps the metapipe main job to be submitted.
[ "Preps", "the", "metapipe", "main", "job", "to", "be", "submitted", "." ]
15592e5b0c217afb00ac03503f8d0d7453d4baf4
https://github.com/TorkamaniLab/metapipe/blob/15592e5b0c217afb00ac03503f8d0d7453d4baf4/metapipe/app.py#L134-L140
train
54,413
raymondEhlers/pachyderm
pachyderm/yaml.py
yaml
def yaml(modules_to_register: Iterable[Any] = None, classes_to_register: Iterable[Any] = None) -> ruamel.yaml.YAML: """ Create a YAML object for loading a YAML configuration. Args: modules_to_register: Modules containing classes to be registered with the YAML object. Default: None. classes_to_register: Classes to be registered with the YAML object. Default: None. Returns: A newly creating YAML object, configured as apporpirate. """ # Defein a round-trip yaml object for us to work with. This object should be imported by other modules # NOTE: "typ" is a not a typo. It stands for "type" yaml = ruamel.yaml.YAML(typ = "rt") # Register representers and constructors # Numpy yaml.representer.add_representer(np.ndarray, numpy_to_yaml) yaml.constructor.add_constructor("!numpy_array", numpy_from_yaml) # Register external classes yaml = register_module_classes(yaml = yaml, modules = modules_to_register) yaml = register_classes(yaml = yaml, classes = classes_to_register) return yaml
python
def yaml(modules_to_register: Iterable[Any] = None, classes_to_register: Iterable[Any] = None) -> ruamel.yaml.YAML: """ Create a YAML object for loading a YAML configuration. Args: modules_to_register: Modules containing classes to be registered with the YAML object. Default: None. classes_to_register: Classes to be registered with the YAML object. Default: None. Returns: A newly creating YAML object, configured as apporpirate. """ # Defein a round-trip yaml object for us to work with. This object should be imported by other modules # NOTE: "typ" is a not a typo. It stands for "type" yaml = ruamel.yaml.YAML(typ = "rt") # Register representers and constructors # Numpy yaml.representer.add_representer(np.ndarray, numpy_to_yaml) yaml.constructor.add_constructor("!numpy_array", numpy_from_yaml) # Register external classes yaml = register_module_classes(yaml = yaml, modules = modules_to_register) yaml = register_classes(yaml = yaml, classes = classes_to_register) return yaml
[ "def", "yaml", "(", "modules_to_register", ":", "Iterable", "[", "Any", "]", "=", "None", ",", "classes_to_register", ":", "Iterable", "[", "Any", "]", "=", "None", ")", "->", "ruamel", ".", "yaml", ".", "YAML", ":", "# Defein a round-trip yaml object for us t...
Create a YAML object for loading a YAML configuration. Args: modules_to_register: Modules containing classes to be registered with the YAML object. Default: None. classes_to_register: Classes to be registered with the YAML object. Default: None. Returns: A newly creating YAML object, configured as apporpirate.
[ "Create", "a", "YAML", "object", "for", "loading", "a", "YAML", "configuration", "." ]
aaa1d8374fd871246290ce76f1796f2f7582b01d
https://github.com/raymondEhlers/pachyderm/blob/aaa1d8374fd871246290ce76f1796f2f7582b01d/pachyderm/yaml.py#L53-L74
train
54,414
raymondEhlers/pachyderm
pachyderm/yaml.py
register_classes
def register_classes(yaml: ruamel.yaml.YAML, classes: Optional[Iterable[Any]] = None) -> ruamel.yaml.YAML: """ Register externally defined classes. """ # Validation if classes is None: classes = [] # Register the classes for cls in classes: logger.debug(f"Registering class {cls} with YAML") yaml.register_class(cls) return yaml
python
def register_classes(yaml: ruamel.yaml.YAML, classes: Optional[Iterable[Any]] = None) -> ruamel.yaml.YAML: """ Register externally defined classes. """ # Validation if classes is None: classes = [] # Register the classes for cls in classes: logger.debug(f"Registering class {cls} with YAML") yaml.register_class(cls) return yaml
[ "def", "register_classes", "(", "yaml", ":", "ruamel", ".", "yaml", ".", "YAML", ",", "classes", ":", "Optional", "[", "Iterable", "[", "Any", "]", "]", "=", "None", ")", "->", "ruamel", ".", "yaml", ".", "YAML", ":", "# Validation", "if", "classes", ...
Register externally defined classes.
[ "Register", "externally", "defined", "classes", "." ]
aaa1d8374fd871246290ce76f1796f2f7582b01d
https://github.com/raymondEhlers/pachyderm/blob/aaa1d8374fd871246290ce76f1796f2f7582b01d/pachyderm/yaml.py#L76-L87
train
54,415
raymondEhlers/pachyderm
pachyderm/yaml.py
register_module_classes
def register_module_classes(yaml: ruamel.yaml.YAML, modules: Optional[Iterable[Any]] = None) -> ruamel.yaml.YAML: """ Register all classes in the given modules with the YAML object. This is a simple helper function. """ # Validation if modules is None: modules = [] # Extract the classes from the modules classes_to_register = set() for module in modules: module_classes = [member[1] for member in inspect.getmembers(module, inspect.isclass)] classes_to_register.update(module_classes) # Register the extracted classes return register_classes(yaml = yaml, classes = classes_to_register)
python
def register_module_classes(yaml: ruamel.yaml.YAML, modules: Optional[Iterable[Any]] = None) -> ruamel.yaml.YAML: """ Register all classes in the given modules with the YAML object. This is a simple helper function. """ # Validation if modules is None: modules = [] # Extract the classes from the modules classes_to_register = set() for module in modules: module_classes = [member[1] for member in inspect.getmembers(module, inspect.isclass)] classes_to_register.update(module_classes) # Register the extracted classes return register_classes(yaml = yaml, classes = classes_to_register)
[ "def", "register_module_classes", "(", "yaml", ":", "ruamel", ".", "yaml", ".", "YAML", ",", "modules", ":", "Optional", "[", "Iterable", "[", "Any", "]", "]", "=", "None", ")", "->", "ruamel", ".", "yaml", ".", "YAML", ":", "# Validation", "if", "modu...
Register all classes in the given modules with the YAML object. This is a simple helper function.
[ "Register", "all", "classes", "in", "the", "given", "modules", "with", "the", "YAML", "object", "." ]
aaa1d8374fd871246290ce76f1796f2f7582b01d
https://github.com/raymondEhlers/pachyderm/blob/aaa1d8374fd871246290ce76f1796f2f7582b01d/pachyderm/yaml.py#L89-L105
train
54,416
raymondEhlers/pachyderm
pachyderm/yaml.py
numpy_to_yaml
def numpy_to_yaml(representer: Representer, data: np.ndarray) -> Sequence[Any]: """ Write a numpy array to YAML. It registers the array under the tag ``!numpy_array``. Use with: .. code-block:: python >>> yaml = ruamel.yaml.YAML() >>> yaml.representer.add_representer(np.ndarray, yaml.numpy_to_yaml) Note: We cannot use ``yaml.register_class`` because it won't register the proper type. (It would register the type of the class, rather than of `numpy.ndarray`). Instead, we use the above approach to register this method explicitly with the representer. """ return representer.represent_sequence( "!numpy_array", data.tolist() )
python
def numpy_to_yaml(representer: Representer, data: np.ndarray) -> Sequence[Any]: """ Write a numpy array to YAML. It registers the array under the tag ``!numpy_array``. Use with: .. code-block:: python >>> yaml = ruamel.yaml.YAML() >>> yaml.representer.add_representer(np.ndarray, yaml.numpy_to_yaml) Note: We cannot use ``yaml.register_class`` because it won't register the proper type. (It would register the type of the class, rather than of `numpy.ndarray`). Instead, we use the above approach to register this method explicitly with the representer. """ return representer.represent_sequence( "!numpy_array", data.tolist() )
[ "def", "numpy_to_yaml", "(", "representer", ":", "Representer", ",", "data", ":", "np", ".", "ndarray", ")", "->", "Sequence", "[", "Any", "]", ":", "return", "representer", ".", "represent_sequence", "(", "\"!numpy_array\"", ",", "data", ".", "tolist", "(",...
Write a numpy array to YAML. It registers the array under the tag ``!numpy_array``. Use with: .. code-block:: python >>> yaml = ruamel.yaml.YAML() >>> yaml.representer.add_representer(np.ndarray, yaml.numpy_to_yaml) Note: We cannot use ``yaml.register_class`` because it won't register the proper type. (It would register the type of the class, rather than of `numpy.ndarray`). Instead, we use the above approach to register this method explicitly with the representer.
[ "Write", "a", "numpy", "array", "to", "YAML", "." ]
aaa1d8374fd871246290ce76f1796f2f7582b01d
https://github.com/raymondEhlers/pachyderm/blob/aaa1d8374fd871246290ce76f1796f2f7582b01d/pachyderm/yaml.py#L111-L131
train
54,417
raymondEhlers/pachyderm
pachyderm/yaml.py
numpy_from_yaml
def numpy_from_yaml(constructor: Constructor, data: ruamel.yaml.nodes.SequenceNode) -> np.ndarray: """ Read an array from YAML to numpy. It reads arrays registered under the tag ``!numpy_array``. Use with: .. code-block:: python >>> yaml = ruamel.yaml.YAML() >>> yaml.constructor.add_constructor("!numpy_array", yaml.numpy_from_yaml) Note: We cannot use ``yaml.register_class`` because it won't register the proper type. (It would register the type of the class, rather than of `numpy.ndarray`). Instead, we use the above approach to register this method explicitly with the representer. """ # Construct the contained values so that we properly construct int, float, etc. # We just leave this to YAML because it already stores this information. values = [constructor.construct_object(n) for n in data.value] logger.debug(f"{data}, {values}") return np.array(values)
python
def numpy_from_yaml(constructor: Constructor, data: ruamel.yaml.nodes.SequenceNode) -> np.ndarray: """ Read an array from YAML to numpy. It reads arrays registered under the tag ``!numpy_array``. Use with: .. code-block:: python >>> yaml = ruamel.yaml.YAML() >>> yaml.constructor.add_constructor("!numpy_array", yaml.numpy_from_yaml) Note: We cannot use ``yaml.register_class`` because it won't register the proper type. (It would register the type of the class, rather than of `numpy.ndarray`). Instead, we use the above approach to register this method explicitly with the representer. """ # Construct the contained values so that we properly construct int, float, etc. # We just leave this to YAML because it already stores this information. values = [constructor.construct_object(n) for n in data.value] logger.debug(f"{data}, {values}") return np.array(values)
[ "def", "numpy_from_yaml", "(", "constructor", ":", "Constructor", ",", "data", ":", "ruamel", ".", "yaml", ".", "nodes", ".", "SequenceNode", ")", "->", "np", ".", "ndarray", ":", "# Construct the contained values so that we properly construct int, float, etc.", "# We j...
Read an array from YAML to numpy. It reads arrays registered under the tag ``!numpy_array``. Use with: .. code-block:: python >>> yaml = ruamel.yaml.YAML() >>> yaml.constructor.add_constructor("!numpy_array", yaml.numpy_from_yaml) Note: We cannot use ``yaml.register_class`` because it won't register the proper type. (It would register the type of the class, rather than of `numpy.ndarray`). Instead, we use the above approach to register this method explicitly with the representer.
[ "Read", "an", "array", "from", "YAML", "to", "numpy", "." ]
aaa1d8374fd871246290ce76f1796f2f7582b01d
https://github.com/raymondEhlers/pachyderm/blob/aaa1d8374fd871246290ce76f1796f2f7582b01d/pachyderm/yaml.py#L133-L154
train
54,418
raymondEhlers/pachyderm
pachyderm/yaml.py
enum_to_yaml
def enum_to_yaml(cls: Type[T_EnumToYAML], representer: Representer, data: T_EnumToYAML) -> ruamel.yaml.nodes.ScalarNode: """ Encodes YAML representation. This is a mixin method for writing enum values to YAML. It needs to be added to the enum as a classmethod. See the module docstring for further information on this approach and how to implement it. This method writes whatever is used in the string representation of the YAML value. Usually, this will be the unique name of the enumeration value. If the name is used, the corresponding ``EnumFromYAML`` mixin can be used to recreate the value. If the name isn't used, more care may be necessary, so a ``from_yaml`` method for that particular enumeration may be necessary. Note: This method assumes that the name of the enumeration value should be stored as a scalar node. Args: representer: Representation from YAML. data: Enumeration value to be encoded. Returns: Scalar representation of the name of the enumeration value. """ return representer.represent_scalar( f"!{cls.__name__}", f"{str(data)}" )
python
def enum_to_yaml(cls: Type[T_EnumToYAML], representer: Representer, data: T_EnumToYAML) -> ruamel.yaml.nodes.ScalarNode: """ Encodes YAML representation. This is a mixin method for writing enum values to YAML. It needs to be added to the enum as a classmethod. See the module docstring for further information on this approach and how to implement it. This method writes whatever is used in the string representation of the YAML value. Usually, this will be the unique name of the enumeration value. If the name is used, the corresponding ``EnumFromYAML`` mixin can be used to recreate the value. If the name isn't used, more care may be necessary, so a ``from_yaml`` method for that particular enumeration may be necessary. Note: This method assumes that the name of the enumeration value should be stored as a scalar node. Args: representer: Representation from YAML. data: Enumeration value to be encoded. Returns: Scalar representation of the name of the enumeration value. """ return representer.represent_scalar( f"!{cls.__name__}", f"{str(data)}" )
[ "def", "enum_to_yaml", "(", "cls", ":", "Type", "[", "T_EnumToYAML", "]", ",", "representer", ":", "Representer", ",", "data", ":", "T_EnumToYAML", ")", "->", "ruamel", ".", "yaml", ".", "nodes", ".", "ScalarNode", ":", "return", "representer", ".", "repre...
Encodes YAML representation. This is a mixin method for writing enum values to YAML. It needs to be added to the enum as a classmethod. See the module docstring for further information on this approach and how to implement it. This method writes whatever is used in the string representation of the YAML value. Usually, this will be the unique name of the enumeration value. If the name is used, the corresponding ``EnumFromYAML`` mixin can be used to recreate the value. If the name isn't used, more care may be necessary, so a ``from_yaml`` method for that particular enumeration may be necessary. Note: This method assumes that the name of the enumeration value should be stored as a scalar node. Args: representer: Representation from YAML. data: Enumeration value to be encoded. Returns: Scalar representation of the name of the enumeration value.
[ "Encodes", "YAML", "representation", "." ]
aaa1d8374fd871246290ce76f1796f2f7582b01d
https://github.com/raymondEhlers/pachyderm/blob/aaa1d8374fd871246290ce76f1796f2f7582b01d/pachyderm/yaml.py#L156-L181
train
54,419
raymondEhlers/pachyderm
pachyderm/yaml.py
enum_from_yaml
def enum_from_yaml(cls: Type[T_EnumFromYAML], constructor: Constructor, node: ruamel.yaml.nodes.ScalarNode) -> T_EnumFromYAML: """ Decode YAML representation. This is a mixin method for reading enum values from YAML. It needs to be added to the enum as a classmethod. See the module docstring for further information on this approach and how to implement it. Note: This method assumes that the name of the enumeration value was stored as a scalar node. Args: constructor: Constructor from the YAML object. node: Scalar node extracted from the YAML being read. Returns: The constructed YAML value from the name of the enumerated value. """ # mypy doesn't like indexing to construct the enumeration. return cls[node.value]
python
def enum_from_yaml(cls: Type[T_EnumFromYAML], constructor: Constructor, node: ruamel.yaml.nodes.ScalarNode) -> T_EnumFromYAML: """ Decode YAML representation. This is a mixin method for reading enum values from YAML. It needs to be added to the enum as a classmethod. See the module docstring for further information on this approach and how to implement it. Note: This method assumes that the name of the enumeration value was stored as a scalar node. Args: constructor: Constructor from the YAML object. node: Scalar node extracted from the YAML being read. Returns: The constructed YAML value from the name of the enumerated value. """ # mypy doesn't like indexing to construct the enumeration. return cls[node.value]
[ "def", "enum_from_yaml", "(", "cls", ":", "Type", "[", "T_EnumFromYAML", "]", ",", "constructor", ":", "Constructor", ",", "node", ":", "ruamel", ".", "yaml", ".", "nodes", ".", "ScalarNode", ")", "->", "T_EnumFromYAML", ":", "# mypy doesn't like indexing to con...
Decode YAML representation. This is a mixin method for reading enum values from YAML. It needs to be added to the enum as a classmethod. See the module docstring for further information on this approach and how to implement it. Note: This method assumes that the name of the enumeration value was stored as a scalar node. Args: constructor: Constructor from the YAML object. node: Scalar node extracted from the YAML being read. Returns: The constructed YAML value from the name of the enumerated value.
[ "Decode", "YAML", "representation", "." ]
aaa1d8374fd871246290ce76f1796f2f7582b01d
https://github.com/raymondEhlers/pachyderm/blob/aaa1d8374fd871246290ce76f1796f2f7582b01d/pachyderm/yaml.py#L183-L200
train
54,420
computational-metabolomics/msp2db
msp2db/parse.py
LibraryData._get_current_ids
def _get_current_ids(self, source=True, meta=True, spectra=True, spectra_annotation=True): """Get the current id for each table in the database Args: source (boolean): get the id for the table "library_spectra_source" will update self.current_id_origin meta (boolean): get the id for the table "library_spectra_meta" will update self.current_id_meta spectra (boolean): get the id for the table "library_spectra" will update self.current_id_spectra spectra_annotation (boolean): get the id for the table "library_spectra_annotation" will update self.current_id_spectra_annotation """ # get the cursor for the database connection c = self.c # Get the last uid for the spectra_info table if source: c.execute('SELECT max(id) FROM library_spectra_source') last_id_origin = c.fetchone()[0] if last_id_origin: self.current_id_origin = last_id_origin + 1 else: self.current_id_origin = 1 if meta: c.execute('SELECT max(id) FROM library_spectra_meta') last_id_meta = c.fetchone()[0] if last_id_meta: self.current_id_meta = last_id_meta + 1 else: self.current_id_meta = 1 if spectra: c.execute('SELECT max(id) FROM library_spectra') last_id_spectra = c.fetchone()[0] if last_id_spectra: self.current_id_spectra = last_id_spectra + 1 else: self.current_id_spectra = 1 if spectra_annotation: c.execute('SELECT max(id) FROM library_spectra_annotation') last_id_spectra_annotation = c.fetchone()[0] if last_id_spectra_annotation: self.current_id_spectra_annotation = last_id_spectra_annotation + 1 else: self.current_id_spectra_annotation = 1
python
def _get_current_ids(self, source=True, meta=True, spectra=True, spectra_annotation=True): """Get the current id for each table in the database Args: source (boolean): get the id for the table "library_spectra_source" will update self.current_id_origin meta (boolean): get the id for the table "library_spectra_meta" will update self.current_id_meta spectra (boolean): get the id for the table "library_spectra" will update self.current_id_spectra spectra_annotation (boolean): get the id for the table "library_spectra_annotation" will update self.current_id_spectra_annotation """ # get the cursor for the database connection c = self.c # Get the last uid for the spectra_info table if source: c.execute('SELECT max(id) FROM library_spectra_source') last_id_origin = c.fetchone()[0] if last_id_origin: self.current_id_origin = last_id_origin + 1 else: self.current_id_origin = 1 if meta: c.execute('SELECT max(id) FROM library_spectra_meta') last_id_meta = c.fetchone()[0] if last_id_meta: self.current_id_meta = last_id_meta + 1 else: self.current_id_meta = 1 if spectra: c.execute('SELECT max(id) FROM library_spectra') last_id_spectra = c.fetchone()[0] if last_id_spectra: self.current_id_spectra = last_id_spectra + 1 else: self.current_id_spectra = 1 if spectra_annotation: c.execute('SELECT max(id) FROM library_spectra_annotation') last_id_spectra_annotation = c.fetchone()[0] if last_id_spectra_annotation: self.current_id_spectra_annotation = last_id_spectra_annotation + 1 else: self.current_id_spectra_annotation = 1
[ "def", "_get_current_ids", "(", "self", ",", "source", "=", "True", ",", "meta", "=", "True", ",", "spectra", "=", "True", ",", "spectra_annotation", "=", "True", ")", ":", "# get the cursor for the database connection", "c", "=", "self", ".", "c", "# Get the ...
Get the current id for each table in the database Args: source (boolean): get the id for the table "library_spectra_source" will update self.current_id_origin meta (boolean): get the id for the table "library_spectra_meta" will update self.current_id_meta spectra (boolean): get the id for the table "library_spectra" will update self.current_id_spectra spectra_annotation (boolean): get the id for the table "library_spectra_annotation" will update self.current_id_spectra_annotation
[ "Get", "the", "current", "id", "for", "each", "table", "in", "the", "database" ]
f86f01efca26fd2745547c9993f97337c6bef123
https://github.com/computational-metabolomics/msp2db/blob/f86f01efca26fd2745547c9993f97337c6bef123/msp2db/parse.py#L116-L163
train
54,421
computational-metabolomics/msp2db
msp2db/parse.py
LibraryData._update_libdata
def _update_libdata(self, line): """Update the library meta data from the current line being parsed Args: line (str): The current line of the of the file being parsed """ #################################################### # parse MONA Comments line #################################################### # The mona msp files contain a "comments" line that contains lots of other information normally separated # into by "" if re.match('^Comment.*$', line, re.IGNORECASE): comments = re.findall('"([^"]*)"', line) for c in comments: self._parse_meta_info(c) self._parse_compound_info(c) #################################################### # parse meta and compound info lines #################################################### # check the current line for both general meta data # and compound information self._parse_meta_info(line) self._parse_compound_info(line) #################################################### # End of meta data #################################################### # Most MSP files have the a standard line of text before the spectra information begins. Here we check # for this line and store the relevant details for the compound and meta information to be ready for insertion # into the database if self.collect_meta and (re.match('^Num Peaks(.*)$', line, re.IGNORECASE) or re.match('^PK\$PEAK:(.*)', line, re.IGNORECASE) or re.match('^PK\$ANNOTATION(.*)', line, re.IGNORECASE)): self._store_compound_info() self._store_meta_info() # Reset the temp meta and compound information self.meta_info = get_blank_dict(self.meta_regex) self.compound_info = get_blank_dict(self.compound_regex) self.other_names = [] self.collect_meta = False # ignore additional information in the 3rd column if using the MassBank spectra schema if re.match('^PK\$PEAK: m/z int\. rel\.int\.$', line, re.IGNORECASE): self.ignore_additional_spectra_info = True # Check if annnotation or spectra is to be in the next lines to be parsed if re.match('^Num Peaks(.*)$', line, re.IGNORECASE) or re.match('^PK\$PEAK:(.*)', line, re.IGNORECASE): self.start_spectra = True return elif re.match('^PK\$ANNOTATION(.*)', line, re.IGNORECASE): self.start_spectra_annotation = True match = re.match('^PK\$ANNOTATION:(.*)', line, re.IGNORECASE) columns = match.group(1) cl = columns.split() self.spectra_annotation_indexes = {i: cl.index(i) for i in cl} return #################################################### # Process annotation details #################################################### # e.g. molecular formula for each peak in the spectra if self.start_spectra_annotation: self._parse_spectra_annotation(line) #################################################### # Process spectra #################################################### if self.start_spectra: self._parse_spectra(line)
python
def _update_libdata(self, line): """Update the library meta data from the current line being parsed Args: line (str): The current line of the of the file being parsed """ #################################################### # parse MONA Comments line #################################################### # The mona msp files contain a "comments" line that contains lots of other information normally separated # into by "" if re.match('^Comment.*$', line, re.IGNORECASE): comments = re.findall('"([^"]*)"', line) for c in comments: self._parse_meta_info(c) self._parse_compound_info(c) #################################################### # parse meta and compound info lines #################################################### # check the current line for both general meta data # and compound information self._parse_meta_info(line) self._parse_compound_info(line) #################################################### # End of meta data #################################################### # Most MSP files have the a standard line of text before the spectra information begins. Here we check # for this line and store the relevant details for the compound and meta information to be ready for insertion # into the database if self.collect_meta and (re.match('^Num Peaks(.*)$', line, re.IGNORECASE) or re.match('^PK\$PEAK:(.*)', line, re.IGNORECASE) or re.match('^PK\$ANNOTATION(.*)', line, re.IGNORECASE)): self._store_compound_info() self._store_meta_info() # Reset the temp meta and compound information self.meta_info = get_blank_dict(self.meta_regex) self.compound_info = get_blank_dict(self.compound_regex) self.other_names = [] self.collect_meta = False # ignore additional information in the 3rd column if using the MassBank spectra schema if re.match('^PK\$PEAK: m/z int\. rel\.int\.$', line, re.IGNORECASE): self.ignore_additional_spectra_info = True # Check if annnotation or spectra is to be in the next lines to be parsed if re.match('^Num Peaks(.*)$', line, re.IGNORECASE) or re.match('^PK\$PEAK:(.*)', line, re.IGNORECASE): self.start_spectra = True return elif re.match('^PK\$ANNOTATION(.*)', line, re.IGNORECASE): self.start_spectra_annotation = True match = re.match('^PK\$ANNOTATION:(.*)', line, re.IGNORECASE) columns = match.group(1) cl = columns.split() self.spectra_annotation_indexes = {i: cl.index(i) for i in cl} return #################################################### # Process annotation details #################################################### # e.g. molecular formula for each peak in the spectra if self.start_spectra_annotation: self._parse_spectra_annotation(line) #################################################### # Process spectra #################################################### if self.start_spectra: self._parse_spectra(line)
[ "def", "_update_libdata", "(", "self", ",", "line", ")", ":", "####################################################", "# parse MONA Comments line", "####################################################", "# The mona msp files contain a \"comments\" line that contains lots of other information ...
Update the library meta data from the current line being parsed Args: line (str): The current line of the of the file being parsed
[ "Update", "the", "library", "meta", "data", "from", "the", "current", "line", "being", "parsed" ]
f86f01efca26fd2745547c9993f97337c6bef123
https://github.com/computational-metabolomics/msp2db/blob/f86f01efca26fd2745547c9993f97337c6bef123/msp2db/parse.py#L236-L309
train
54,422
computational-metabolomics/msp2db
msp2db/parse.py
LibraryData._store_compound_info
def _store_compound_info(self): """Update the compound_info dictionary with the current chunk of compound details Note that we use the inchikey as unique identifier. If we can't find an appropiate inchikey we just use a random string (uuid4) suffixed with UNKNOWN """ other_name_l = [name for name in self.other_names if name != self.compound_info['name']] self.compound_info['other_names'] = ' <#> '.join(other_name_l) if not self.compound_info['inchikey_id']: self._set_inchi_pcc(self.compound_info['pubchem_id'], 'cid', 0) if not self.compound_info['inchikey_id']: self._set_inchi_pcc(self.compound_info['smiles'], 'smiles', 0) if not self.compound_info['inchikey_id']: self._set_inchi_pcc(self.compound_info['name'], 'name', 0) if not self.compound_info['inchikey_id']: print('WARNING, cant get inchi key for ', self.compound_info) print(self.meta_info) print('#########################') self.compound_info['inchikey_id'] = 'UNKNOWN_' + str(uuid.uuid4()) if not self.compound_info['pubchem_id'] and self.compound_info['inchikey_id']: self._set_inchi_pcc(self.compound_info['inchikey_id'], 'inchikey', 0) if not self.compound_info['name']: self.compound_info['name'] = 'unknown name' if not self.compound_info['inchikey_id'] in self.compound_ids: self.compound_info_all.append(tuple(self.compound_info.values()) + ( str(datetime.datetime.now()), str(datetime.datetime.now()), )) self.compound_ids.append(self.compound_info['inchikey_id'])
python
def _store_compound_info(self): """Update the compound_info dictionary with the current chunk of compound details Note that we use the inchikey as unique identifier. If we can't find an appropiate inchikey we just use a random string (uuid4) suffixed with UNKNOWN """ other_name_l = [name for name in self.other_names if name != self.compound_info['name']] self.compound_info['other_names'] = ' <#> '.join(other_name_l) if not self.compound_info['inchikey_id']: self._set_inchi_pcc(self.compound_info['pubchem_id'], 'cid', 0) if not self.compound_info['inchikey_id']: self._set_inchi_pcc(self.compound_info['smiles'], 'smiles', 0) if not self.compound_info['inchikey_id']: self._set_inchi_pcc(self.compound_info['name'], 'name', 0) if not self.compound_info['inchikey_id']: print('WARNING, cant get inchi key for ', self.compound_info) print(self.meta_info) print('#########################') self.compound_info['inchikey_id'] = 'UNKNOWN_' + str(uuid.uuid4()) if not self.compound_info['pubchem_id'] and self.compound_info['inchikey_id']: self._set_inchi_pcc(self.compound_info['inchikey_id'], 'inchikey', 0) if not self.compound_info['name']: self.compound_info['name'] = 'unknown name' if not self.compound_info['inchikey_id'] in self.compound_ids: self.compound_info_all.append(tuple(self.compound_info.values()) + ( str(datetime.datetime.now()), str(datetime.datetime.now()), )) self.compound_ids.append(self.compound_info['inchikey_id'])
[ "def", "_store_compound_info", "(", "self", ")", ":", "other_name_l", "=", "[", "name", "for", "name", "in", "self", ".", "other_names", "if", "name", "!=", "self", ".", "compound_info", "[", "'name'", "]", "]", "self", ".", "compound_info", "[", "'other_n...
Update the compound_info dictionary with the current chunk of compound details Note that we use the inchikey as unique identifier. If we can't find an appropiate inchikey we just use a random string (uuid4) suffixed with UNKNOWN
[ "Update", "the", "compound_info", "dictionary", "with", "the", "current", "chunk", "of", "compound", "details" ]
f86f01efca26fd2745547c9993f97337c6bef123
https://github.com/computational-metabolomics/msp2db/blob/f86f01efca26fd2745547c9993f97337c6bef123/msp2db/parse.py#L321-L356
train
54,423
computational-metabolomics/msp2db
msp2db/parse.py
LibraryData._store_meta_info
def _store_meta_info(self): """Update the meta dictionary with the current chunk of meta data details """ # In the mass bank msp files, sometimes the precursor_mz is missing but we have the neutral mass and # the precursor_type (e.g. adduct) so we can calculate the precursor_mz if not self.meta_info['precursor_mz'] and self.meta_info['precursor_type'] and \ self.compound_info['exact_mass']: self.meta_info['precursor_mz'] = get_precursor_mz(float(self.compound_info['exact_mass']), self.meta_info['precursor_type']) if not self.meta_info['polarity']: # have to do special check for polarity (as sometimes gets missed) m = re.search('^\[.*\](\-|\+)', self.meta_info['precursor_type'], re.IGNORECASE) if m: polarity = m.group(1).strip() if polarity == '+': self.meta_info['polarity'] = 'positive' elif polarity == '-': self.meta_info['polarity'] = 'negative' if not self.meta_info['accession']: self.meta_info['accession'] = 'unknown accession' self.meta_info_all.append( (str(self.current_id_meta),) + tuple(self.meta_info.values()) + (str(self.current_id_origin), self.compound_info['inchikey_id'],) )
python
def _store_meta_info(self): """Update the meta dictionary with the current chunk of meta data details """ # In the mass bank msp files, sometimes the precursor_mz is missing but we have the neutral mass and # the precursor_type (e.g. adduct) so we can calculate the precursor_mz if not self.meta_info['precursor_mz'] and self.meta_info['precursor_type'] and \ self.compound_info['exact_mass']: self.meta_info['precursor_mz'] = get_precursor_mz(float(self.compound_info['exact_mass']), self.meta_info['precursor_type']) if not self.meta_info['polarity']: # have to do special check for polarity (as sometimes gets missed) m = re.search('^\[.*\](\-|\+)', self.meta_info['precursor_type'], re.IGNORECASE) if m: polarity = m.group(1).strip() if polarity == '+': self.meta_info['polarity'] = 'positive' elif polarity == '-': self.meta_info['polarity'] = 'negative' if not self.meta_info['accession']: self.meta_info['accession'] = 'unknown accession' self.meta_info_all.append( (str(self.current_id_meta),) + tuple(self.meta_info.values()) + (str(self.current_id_origin), self.compound_info['inchikey_id'],) )
[ "def", "_store_meta_info", "(", "self", ")", ":", "# In the mass bank msp files, sometimes the precursor_mz is missing but we have the neutral mass and", "# the precursor_type (e.g. adduct) so we can calculate the precursor_mz", "if", "not", "self", ".", "meta_info", "[", "'precursor_mz'...
Update the meta dictionary with the current chunk of meta data details
[ "Update", "the", "meta", "dictionary", "with", "the", "current", "chunk", "of", "meta", "data", "details" ]
f86f01efca26fd2745547c9993f97337c6bef123
https://github.com/computational-metabolomics/msp2db/blob/f86f01efca26fd2745547c9993f97337c6bef123/msp2db/parse.py#L358-L385
train
54,424
computational-metabolomics/msp2db
msp2db/parse.py
LibraryData._parse_spectra_annotation
def _parse_spectra_annotation(self, line): """Parse and store the spectral annotation details """ if re.match('^PK\$NUM_PEAK(.*)', line, re.IGNORECASE): self.start_spectra_annotation = False return saplist = line.split() sarow = ( self.current_id_spectra_annotation, float(saplist[self.spectra_annotation_indexes['m/z']]) if 'm/z' in self.spectra_annotation_indexes else None, saplist[self.spectra_annotation_indexes[ 'tentative_formula']] if 'tentative_formula' in self.spectra_annotation_indexes else None, float(saplist[self.spectra_annotation_indexes[ 'mass_error(ppm)']]) if 'mass_error(ppm)' in self.spectra_annotation_indexes else None, self.current_id_meta) self.spectra_annotation_all.append(sarow) self.current_id_spectra_annotation += 1
python
def _parse_spectra_annotation(self, line): """Parse and store the spectral annotation details """ if re.match('^PK\$NUM_PEAK(.*)', line, re.IGNORECASE): self.start_spectra_annotation = False return saplist = line.split() sarow = ( self.current_id_spectra_annotation, float(saplist[self.spectra_annotation_indexes['m/z']]) if 'm/z' in self.spectra_annotation_indexes else None, saplist[self.spectra_annotation_indexes[ 'tentative_formula']] if 'tentative_formula' in self.spectra_annotation_indexes else None, float(saplist[self.spectra_annotation_indexes[ 'mass_error(ppm)']]) if 'mass_error(ppm)' in self.spectra_annotation_indexes else None, self.current_id_meta) self.spectra_annotation_all.append(sarow) self.current_id_spectra_annotation += 1
[ "def", "_parse_spectra_annotation", "(", "self", ",", "line", ")", ":", "if", "re", ".", "match", "(", "'^PK\\$NUM_PEAK(.*)'", ",", "line", ",", "re", ".", "IGNORECASE", ")", ":", "self", ".", "start_spectra_annotation", "=", "False", "return", "saplist", "=...
Parse and store the spectral annotation details
[ "Parse", "and", "store", "the", "spectral", "annotation", "details" ]
f86f01efca26fd2745547c9993f97337c6bef123
https://github.com/computational-metabolomics/msp2db/blob/f86f01efca26fd2745547c9993f97337c6bef123/msp2db/parse.py#L387-L407
train
54,425
computational-metabolomics/msp2db
msp2db/parse.py
LibraryData._parse_spectra
def _parse_spectra(self, line): """Parse and store the spectral details """ if line in ['\n', '\r\n', '//\n', '//\r\n', '', '//']: self.start_spectra = False self.current_id_meta += 1 self.collect_meta = True return splist = line.split() if len(splist) > 2 and not self.ignore_additional_spectra_info: additional_info = ''.join(map(str, splist[2:len(splist)])) else: additional_info = '' srow = ( self.current_id_spectra, float(splist[0]), float(splist[1]), additional_info, self.current_id_meta) self.spectra_all.append(srow) self.current_id_spectra += 1
python
def _parse_spectra(self, line): """Parse and store the spectral details """ if line in ['\n', '\r\n', '//\n', '//\r\n', '', '//']: self.start_spectra = False self.current_id_meta += 1 self.collect_meta = True return splist = line.split() if len(splist) > 2 and not self.ignore_additional_spectra_info: additional_info = ''.join(map(str, splist[2:len(splist)])) else: additional_info = '' srow = ( self.current_id_spectra, float(splist[0]), float(splist[1]), additional_info, self.current_id_meta) self.spectra_all.append(srow) self.current_id_spectra += 1
[ "def", "_parse_spectra", "(", "self", ",", "line", ")", ":", "if", "line", "in", "[", "'\\n'", ",", "'\\r\\n'", ",", "'//\\n'", ",", "'//\\r\\n'", ",", "''", ",", "'//'", "]", ":", "self", ".", "start_spectra", "=", "False", "self", ".", "current_id_me...
Parse and store the spectral details
[ "Parse", "and", "store", "the", "spectral", "details" ]
f86f01efca26fd2745547c9993f97337c6bef123
https://github.com/computational-metabolomics/msp2db/blob/f86f01efca26fd2745547c9993f97337c6bef123/msp2db/parse.py#L409-L431
train
54,426
computational-metabolomics/msp2db
msp2db/parse.py
LibraryData._set_inchi_pcc
def _set_inchi_pcc(self, in_str, pcp_type, elem): """Check pubchem compounds via API for both an inchikey and any available compound details """ if not in_str: return 0 try: pccs = pcp.get_compounds(in_str, pcp_type) except pcp.BadRequestError as e: print(e) return 0 except pcp.TimeoutError as e: print(e) return 0 except pcp.ServerError as e: print(e) return 0 except URLError as e: print(e) return 0 except BadStatusLine as e: print(e) return 0 if pccs: pcc = pccs[elem] self.compound_info['inchikey_id'] = pcc.inchikey self.compound_info['pubchem_id'] = pcc.cid self.compound_info['molecular_formula'] = pcc.molecular_formula self.compound_info['molecular_weight'] = pcc.molecular_weight self.compound_info['exact_mass'] = pcc.exact_mass self.compound_info['smiles'] = pcc.canonical_smiles if len(pccs) > 1: print('WARNING, multiple compounds for ', self.compound_info)
python
def _set_inchi_pcc(self, in_str, pcp_type, elem): """Check pubchem compounds via API for both an inchikey and any available compound details """ if not in_str: return 0 try: pccs = pcp.get_compounds(in_str, pcp_type) except pcp.BadRequestError as e: print(e) return 0 except pcp.TimeoutError as e: print(e) return 0 except pcp.ServerError as e: print(e) return 0 except URLError as e: print(e) return 0 except BadStatusLine as e: print(e) return 0 if pccs: pcc = pccs[elem] self.compound_info['inchikey_id'] = pcc.inchikey self.compound_info['pubchem_id'] = pcc.cid self.compound_info['molecular_formula'] = pcc.molecular_formula self.compound_info['molecular_weight'] = pcc.molecular_weight self.compound_info['exact_mass'] = pcc.exact_mass self.compound_info['smiles'] = pcc.canonical_smiles if len(pccs) > 1: print('WARNING, multiple compounds for ', self.compound_info)
[ "def", "_set_inchi_pcc", "(", "self", ",", "in_str", ",", "pcp_type", ",", "elem", ")", ":", "if", "not", "in_str", ":", "return", "0", "try", ":", "pccs", "=", "pcp", ".", "get_compounds", "(", "in_str", ",", "pcp_type", ")", "except", "pcp", ".", "...
Check pubchem compounds via API for both an inchikey and any available compound details
[ "Check", "pubchem", "compounds", "via", "API", "for", "both", "an", "inchikey", "and", "any", "available", "compound", "details" ]
f86f01efca26fd2745547c9993f97337c6bef123
https://github.com/computational-metabolomics/msp2db/blob/f86f01efca26fd2745547c9993f97337c6bef123/msp2db/parse.py#L433-L467
train
54,427
computational-metabolomics/msp2db
msp2db/parse.py
LibraryData._get_other_names
def _get_other_names(self, line): """Parse and extract any other names that might be recorded for the compound Args: line (str): line of the msp file """ m = re.search(self.compound_regex['other_names'][0], line, re.IGNORECASE) if m: self.other_names.append(m.group(1).strip())
python
def _get_other_names(self, line): """Parse and extract any other names that might be recorded for the compound Args: line (str): line of the msp file """ m = re.search(self.compound_regex['other_names'][0], line, re.IGNORECASE) if m: self.other_names.append(m.group(1).strip())
[ "def", "_get_other_names", "(", "self", ",", "line", ")", ":", "m", "=", "re", ".", "search", "(", "self", ".", "compound_regex", "[", "'other_names'", "]", "[", "0", "]", ",", "line", ",", "re", ".", "IGNORECASE", ")", "if", "m", ":", "self", ".",...
Parse and extract any other names that might be recorded for the compound Args: line (str): line of the msp file
[ "Parse", "and", "extract", "any", "other", "names", "that", "might", "be", "recorded", "for", "the", "compound" ]
f86f01efca26fd2745547c9993f97337c6bef123
https://github.com/computational-metabolomics/msp2db/blob/f86f01efca26fd2745547c9993f97337c6bef123/msp2db/parse.py#L469-L477
train
54,428
computational-metabolomics/msp2db
msp2db/parse.py
LibraryData._parse_meta_info
def _parse_meta_info(self, line): """Parse and extract all meta data by looping through the dictionary of meta_info regexs updates self.meta_info Args: line (str): line of the msp file """ if self.mslevel: self.meta_info['ms_level'] = self.mslevel if self.polarity: self.meta_info['polarity'] = self.polarity for k, regexes in six.iteritems(self.meta_regex): for reg in regexes: m = re.search(reg, line, re.IGNORECASE) if m: self.meta_info[k] = m.group(1).strip()
python
def _parse_meta_info(self, line): """Parse and extract all meta data by looping through the dictionary of meta_info regexs updates self.meta_info Args: line (str): line of the msp file """ if self.mslevel: self.meta_info['ms_level'] = self.mslevel if self.polarity: self.meta_info['polarity'] = self.polarity for k, regexes in six.iteritems(self.meta_regex): for reg in regexes: m = re.search(reg, line, re.IGNORECASE) if m: self.meta_info[k] = m.group(1).strip()
[ "def", "_parse_meta_info", "(", "self", ",", "line", ")", ":", "if", "self", ".", "mslevel", ":", "self", ".", "meta_info", "[", "'ms_level'", "]", "=", "self", ".", "mslevel", "if", "self", ".", "polarity", ":", "self", ".", "meta_info", "[", "'polari...
Parse and extract all meta data by looping through the dictionary of meta_info regexs updates self.meta_info Args: line (str): line of the msp file
[ "Parse", "and", "extract", "all", "meta", "data", "by", "looping", "through", "the", "dictionary", "of", "meta_info", "regexs" ]
f86f01efca26fd2745547c9993f97337c6bef123
https://github.com/computational-metabolomics/msp2db/blob/f86f01efca26fd2745547c9993f97337c6bef123/msp2db/parse.py#L479-L499
train
54,429
computational-metabolomics/msp2db
msp2db/parse.py
LibraryData._parse_compound_info
def _parse_compound_info(self, line): """Parse and extract all compound data by looping through the dictionary of compound_info regexs updates self.compound_info Args: line (str): line of the msp file """ for k, regexes in six.iteritems(self.compound_regex): for reg in regexes: if self.compound_info[k]: continue m = re.search(reg, line, re.IGNORECASE) if m: self.compound_info[k] = m.group(1).strip() self._get_other_names(line)
python
def _parse_compound_info(self, line): """Parse and extract all compound data by looping through the dictionary of compound_info regexs updates self.compound_info Args: line (str): line of the msp file """ for k, regexes in six.iteritems(self.compound_regex): for reg in regexes: if self.compound_info[k]: continue m = re.search(reg, line, re.IGNORECASE) if m: self.compound_info[k] = m.group(1).strip() self._get_other_names(line)
[ "def", "_parse_compound_info", "(", "self", ",", "line", ")", ":", "for", "k", ",", "regexes", "in", "six", ".", "iteritems", "(", "self", ".", "compound_regex", ")", ":", "for", "reg", "in", "regexes", ":", "if", "self", ".", "compound_info", "[", "k"...
Parse and extract all compound data by looping through the dictionary of compound_info regexs updates self.compound_info Args: line (str): line of the msp file
[ "Parse", "and", "extract", "all", "compound", "data", "by", "looping", "through", "the", "dictionary", "of", "compound_info", "regexs" ]
f86f01efca26fd2745547c9993f97337c6bef123
https://github.com/computational-metabolomics/msp2db/blob/f86f01efca26fd2745547c9993f97337c6bef123/msp2db/parse.py#L501-L518
train
54,430
computational-metabolomics/msp2db
msp2db/parse.py
LibraryData.insert_data
def insert_data(self, remove_data=False, db_type='sqlite'): """Insert data stored in the current chunk of parsing into the selected database Args: remove_data (boolean): Remove the data stored within the LibraryData object for the current chunk of processing db_type (str): The type of database to submit to either 'sqlite', 'mysql' or 'django_mysql' [default sqlite] """ if self.update_source: # print "insert ref id" import msp2db self.c.execute( "INSERT INTO library_spectra_source (id, name, parsing_software) VALUES" " ({a}, '{b}', 'msp2db-v{c}')".format(a=self.current_id_origin, b=self.source, c=msp2db.__version__)) self.conn.commit() if self.compound_info_all: self.compound_info_all = _make_sql_compatible(self.compound_info_all) cn = ', '.join(self.compound_info.keys()) + ',created_at,updated_at' insert_query_m(self.compound_info_all, columns=cn, conn=self.conn, table='metab_compound', db_type=db_type) self.meta_info_all = _make_sql_compatible(self.meta_info_all) cn = 'id,' + ', '.join(self.meta_info.keys()) + ',library_spectra_source_id, inchikey_id' insert_query_m(self.meta_info_all, columns=cn, conn=self.conn, table='library_spectra_meta', db_type=db_type) cn = "id, mz, i, other, library_spectra_meta_id" insert_query_m(self.spectra_all, columns=cn, conn=self.conn, table='library_spectra', db_type=db_type) if self.spectra_annotation_all: cn = "id, mz, tentative_formula, mass_error, library_spectra_meta_id" insert_query_m(self.spectra_annotation_all, columns=cn, conn=self.conn, table='library_spectra_annotation', db_type=db_type) # self.conn.close() if remove_data: self.meta_info_all = [] self.spectra_all = [] self.spectra_annotation_all = [] self.compound_info_all = [] self._get_current_ids(source=False)
python
def insert_data(self, remove_data=False, db_type='sqlite'): """Insert data stored in the current chunk of parsing into the selected database Args: remove_data (boolean): Remove the data stored within the LibraryData object for the current chunk of processing db_type (str): The type of database to submit to either 'sqlite', 'mysql' or 'django_mysql' [default sqlite] """ if self.update_source: # print "insert ref id" import msp2db self.c.execute( "INSERT INTO library_spectra_source (id, name, parsing_software) VALUES" " ({a}, '{b}', 'msp2db-v{c}')".format(a=self.current_id_origin, b=self.source, c=msp2db.__version__)) self.conn.commit() if self.compound_info_all: self.compound_info_all = _make_sql_compatible(self.compound_info_all) cn = ', '.join(self.compound_info.keys()) + ',created_at,updated_at' insert_query_m(self.compound_info_all, columns=cn, conn=self.conn, table='metab_compound', db_type=db_type) self.meta_info_all = _make_sql_compatible(self.meta_info_all) cn = 'id,' + ', '.join(self.meta_info.keys()) + ',library_spectra_source_id, inchikey_id' insert_query_m(self.meta_info_all, columns=cn, conn=self.conn, table='library_spectra_meta', db_type=db_type) cn = "id, mz, i, other, library_spectra_meta_id" insert_query_m(self.spectra_all, columns=cn, conn=self.conn, table='library_spectra', db_type=db_type) if self.spectra_annotation_all: cn = "id, mz, tentative_formula, mass_error, library_spectra_meta_id" insert_query_m(self.spectra_annotation_all, columns=cn, conn=self.conn, table='library_spectra_annotation', db_type=db_type) # self.conn.close() if remove_data: self.meta_info_all = [] self.spectra_all = [] self.spectra_annotation_all = [] self.compound_info_all = [] self._get_current_ids(source=False)
[ "def", "insert_data", "(", "self", ",", "remove_data", "=", "False", ",", "db_type", "=", "'sqlite'", ")", ":", "if", "self", ".", "update_source", ":", "# print \"insert ref id\"", "import", "msp2db", "self", ".", "c", ".", "execute", "(", "\"INSERT INTO libr...
Insert data stored in the current chunk of parsing into the selected database Args: remove_data (boolean): Remove the data stored within the LibraryData object for the current chunk of processing db_type (str): The type of database to submit to either 'sqlite', 'mysql' or 'django_mysql' [default sqlite]
[ "Insert", "data", "stored", "in", "the", "current", "chunk", "of", "parsing", "into", "the", "selected", "database" ]
f86f01efca26fd2745547c9993f97337c6bef123
https://github.com/computational-metabolomics/msp2db/blob/f86f01efca26fd2745547c9993f97337c6bef123/msp2db/parse.py#L520-L568
train
54,431
0k/kids.cmd
src/kids/cmd/menu.py
line
def line(line_def, **kwargs): """Highlights a character in the line""" def replace(s): return "(%s)" % ansi.aformat(s.group()[1:], attrs=["bold", ]) return ansi.aformat( re.sub('@.?', replace, line_def), **kwargs)
python
def line(line_def, **kwargs): """Highlights a character in the line""" def replace(s): return "(%s)" % ansi.aformat(s.group()[1:], attrs=["bold", ]) return ansi.aformat( re.sub('@.?', replace, line_def), **kwargs)
[ "def", "line", "(", "line_def", ",", "*", "*", "kwargs", ")", ":", "def", "replace", "(", "s", ")", ":", "return", "\"(%s)\"", "%", "ansi", ".", "aformat", "(", "s", ".", "group", "(", ")", "[", "1", ":", "]", ",", "attrs", "=", "[", "\"bold\""...
Highlights a character in the line
[ "Highlights", "a", "character", "in", "the", "line" ]
bbe958556bc72e6579d4007a28064e2f62109bcf
https://github.com/0k/kids.cmd/blob/bbe958556bc72e6579d4007a28064e2f62109bcf/src/kids/cmd/menu.py#L8-L14
train
54,432
Chilipp/psy-simple
psy_simple/plugin.py
try_and_error
def try_and_error(*funcs): """Apply multiple validation functions Parameters ---------- ``*funcs`` Validation functions to test Returns ------- function""" def validate(value): exc = None for func in funcs: try: return func(value) except (ValueError, TypeError) as e: exc = e raise exc return validate
python
def try_and_error(*funcs): """Apply multiple validation functions Parameters ---------- ``*funcs`` Validation functions to test Returns ------- function""" def validate(value): exc = None for func in funcs: try: return func(value) except (ValueError, TypeError) as e: exc = e raise exc return validate
[ "def", "try_and_error", "(", "*", "funcs", ")", ":", "def", "validate", "(", "value", ")", ":", "exc", "=", "None", "for", "func", "in", "funcs", ":", "try", ":", "return", "func", "(", "value", ")", "except", "(", "ValueError", ",", "TypeError", ")"...
Apply multiple validation functions Parameters ---------- ``*funcs`` Validation functions to test Returns ------- function
[ "Apply", "multiple", "validation", "functions" ]
7d916406a6d3c3c27c0b7102f98fef07a4da0a61
https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/plugin.py#L55-L74
train
54,433
Chilipp/psy-simple
psy_simple/plugin.py
validate_text
def validate_text(value): """Validate a text formatoption Parameters ---------- value: see :attr:`psyplot.plotter.labelplotter.text` Raises ------ ValueError""" possible_transform = ['axes', 'fig', 'data'] validate_transform = ValidateInStrings('transform', possible_transform, True) tests = [validate_float, validate_float, validate_str, validate_transform, dict] if isinstance(value, six.string_types): xpos, ypos = rcParams['texts.default_position'] return [(xpos, ypos, value, 'axes', {'ha': 'right'})] elif isinstance(value, tuple): value = [value] try: value = list(value)[:] except TypeError: raise ValueError("Value must be string or list of tuples!") for i, val in enumerate(value): try: val = tuple(val) except TypeError: raise ValueError( "Text must be an iterable of the form " "(x, y, s[, trans, params])!") if len(val) < 3: raise ValueError( "Text tuple must at least be like [x, y, s], with floats x, " "y and string s!") elif len(val) == 3 or isinstance(val[3], dict): val = list(val) val.insert(3, 'data') if len(val) == 4: val += [{}] val = tuple(val) if len(val) > 5: raise ValueError( "Text tuple must not be longer then length 5. It can be " "like (x, y, s[, trans, params])!") value[i] = (validate(x) for validate, x in zip(tests, val)) return value
python
def validate_text(value): """Validate a text formatoption Parameters ---------- value: see :attr:`psyplot.plotter.labelplotter.text` Raises ------ ValueError""" possible_transform = ['axes', 'fig', 'data'] validate_transform = ValidateInStrings('transform', possible_transform, True) tests = [validate_float, validate_float, validate_str, validate_transform, dict] if isinstance(value, six.string_types): xpos, ypos = rcParams['texts.default_position'] return [(xpos, ypos, value, 'axes', {'ha': 'right'})] elif isinstance(value, tuple): value = [value] try: value = list(value)[:] except TypeError: raise ValueError("Value must be string or list of tuples!") for i, val in enumerate(value): try: val = tuple(val) except TypeError: raise ValueError( "Text must be an iterable of the form " "(x, y, s[, trans, params])!") if len(val) < 3: raise ValueError( "Text tuple must at least be like [x, y, s], with floats x, " "y and string s!") elif len(val) == 3 or isinstance(val[3], dict): val = list(val) val.insert(3, 'data') if len(val) == 4: val += [{}] val = tuple(val) if len(val) > 5: raise ValueError( "Text tuple must not be longer then length 5. It can be " "like (x, y, s[, trans, params])!") value[i] = (validate(x) for validate, x in zip(tests, val)) return value
[ "def", "validate_text", "(", "value", ")", ":", "possible_transform", "=", "[", "'axes'", ",", "'fig'", ",", "'data'", "]", "validate_transform", "=", "ValidateInStrings", "(", "'transform'", ",", "possible_transform", ",", "True", ")", "tests", "=", "[", "val...
Validate a text formatoption Parameters ---------- value: see :attr:`psyplot.plotter.labelplotter.text` Raises ------ ValueError
[ "Validate", "a", "text", "formatoption" ]
7d916406a6d3c3c27c0b7102f98fef07a4da0a61
https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/plugin.py#L117-L163
train
54,434
Chilipp/psy-simple
psy_simple/plugin.py
validate_none
def validate_none(b): """Validate that None is given Parameters ---------- b: {None, 'none'} None or string (the case is ignored) Returns ------- None Raises ------ ValueError""" if isinstance(b, six.string_types): b = b.lower() if b is None or b == 'none': return None else: raise ValueError('Could not convert "%s" to None' % b)
python
def validate_none(b): """Validate that None is given Parameters ---------- b: {None, 'none'} None or string (the case is ignored) Returns ------- None Raises ------ ValueError""" if isinstance(b, six.string_types): b = b.lower() if b is None or b == 'none': return None else: raise ValueError('Could not convert "%s" to None' % b)
[ "def", "validate_none", "(", "b", ")", ":", "if", "isinstance", "(", "b", ",", "six", ".", "string_types", ")", ":", "b", "=", "b", ".", "lower", "(", ")", "if", "b", "is", "None", "or", "b", "==", "'none'", ":", "return", "None", "else", ":", ...
Validate that None is given Parameters ---------- b: {None, 'none'} None or string (the case is ignored) Returns ------- None Raises ------ ValueError
[ "Validate", "that", "None", "is", "given" ]
7d916406a6d3c3c27c0b7102f98fef07a4da0a61
https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/plugin.py#L184-L204
train
54,435
Chilipp/psy-simple
psy_simple/plugin.py
validate_axiscolor
def validate_axiscolor(value): """Validate a dictionary containing axiscolor definitions Parameters ---------- value: dict see :attr:`psyplot.plotter.baseplotter.axiscolor` Returns ------- dict Raises ------ ValueError""" validate = try_and_error(validate_none, validate_color) possible_keys = {'right', 'left', 'top', 'bottom'} try: value = dict(value) false_keys = set(value) - possible_keys if false_keys: raise ValueError("Wrong keys (%s)!" % (', '.join(false_keys))) for key, val in value.items(): value[key] = validate(val) except: value = dict(zip(possible_keys, repeat(validate(value)))) return value
python
def validate_axiscolor(value): """Validate a dictionary containing axiscolor definitions Parameters ---------- value: dict see :attr:`psyplot.plotter.baseplotter.axiscolor` Returns ------- dict Raises ------ ValueError""" validate = try_and_error(validate_none, validate_color) possible_keys = {'right', 'left', 'top', 'bottom'} try: value = dict(value) false_keys = set(value) - possible_keys if false_keys: raise ValueError("Wrong keys (%s)!" % (', '.join(false_keys))) for key, val in value.items(): value[key] = validate(val) except: value = dict(zip(possible_keys, repeat(validate(value)))) return value
[ "def", "validate_axiscolor", "(", "value", ")", ":", "validate", "=", "try_and_error", "(", "validate_none", ",", "validate_color", ")", "possible_keys", "=", "{", "'right'", ",", "'left'", ",", "'top'", ",", "'bottom'", "}", "try", ":", "value", "=", "dict"...
Validate a dictionary containing axiscolor definitions Parameters ---------- value: dict see :attr:`psyplot.plotter.baseplotter.axiscolor` Returns ------- dict Raises ------ ValueError
[ "Validate", "a", "dictionary", "containing", "axiscolor", "definitions" ]
7d916406a6d3c3c27c0b7102f98fef07a4da0a61
https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/plugin.py#L207-L233
train
54,436
Chilipp/psy-simple
psy_simple/plugin.py
validate_cbarpos
def validate_cbarpos(value): """Validate a colorbar position Parameters ---------- value: bool or str A string can be a combination of 'sh|sv|fl|fr|ft|fb|b|r' Returns ------- list list of strings with possible colorbar positions Raises ------ ValueError""" patt = 'sh|sv|fl|fr|ft|fb|b|r' if value is True: value = {'b'} elif not value: value = set() elif isinstance(value, six.string_types): for s in re.finditer('[^%s]+' % patt, value): warn("Unknown colorbar position %s!" % s.group(), RuntimeWarning) value = set(re.findall(patt, value)) else: value = validate_stringset(value) for s in (s for s in value if not re.match(patt, s)): warn("Unknown colorbar position %s!" % s) value.remove(s) return value
python
def validate_cbarpos(value): """Validate a colorbar position Parameters ---------- value: bool or str A string can be a combination of 'sh|sv|fl|fr|ft|fb|b|r' Returns ------- list list of strings with possible colorbar positions Raises ------ ValueError""" patt = 'sh|sv|fl|fr|ft|fb|b|r' if value is True: value = {'b'} elif not value: value = set() elif isinstance(value, six.string_types): for s in re.finditer('[^%s]+' % patt, value): warn("Unknown colorbar position %s!" % s.group(), RuntimeWarning) value = set(re.findall(patt, value)) else: value = validate_stringset(value) for s in (s for s in value if not re.match(patt, s)): warn("Unknown colorbar position %s!" % s) value.remove(s) return value
[ "def", "validate_cbarpos", "(", "value", ")", ":", "patt", "=", "'sh|sv|fl|fr|ft|fb|b|r'", "if", "value", "is", "True", ":", "value", "=", "{", "'b'", "}", "elif", "not", "value", ":", "value", "=", "set", "(", ")", "elif", "isinstance", "(", "value", ...
Validate a colorbar position Parameters ---------- value: bool or str A string can be a combination of 'sh|sv|fl|fr|ft|fb|b|r' Returns ------- list list of strings with possible colorbar positions Raises ------ ValueError
[ "Validate", "a", "colorbar", "position" ]
7d916406a6d3c3c27c0b7102f98fef07a4da0a61
https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/plugin.py#L269-L300
train
54,437
Chilipp/psy-simple
psy_simple/plugin.py
validate_cmap
def validate_cmap(val): """Validate a colormap Parameters ---------- val: str or :class:`mpl.colors.Colormap` Returns ------- str or :class:`mpl.colors.Colormap` Raises ------ ValueError""" from matplotlib.colors import Colormap try: return validate_str(val) except ValueError: if not isinstance(val, Colormap): raise ValueError( "Could not find a valid colormap!") return val
python
def validate_cmap(val): """Validate a colormap Parameters ---------- val: str or :class:`mpl.colors.Colormap` Returns ------- str or :class:`mpl.colors.Colormap` Raises ------ ValueError""" from matplotlib.colors import Colormap try: return validate_str(val) except ValueError: if not isinstance(val, Colormap): raise ValueError( "Could not find a valid colormap!") return val
[ "def", "validate_cmap", "(", "val", ")", ":", "from", "matplotlib", ".", "colors", "import", "Colormap", "try", ":", "return", "validate_str", "(", "val", ")", "except", "ValueError", ":", "if", "not", "isinstance", "(", "val", ",", "Colormap", ")", ":", ...
Validate a colormap Parameters ---------- val: str or :class:`mpl.colors.Colormap` Returns ------- str or :class:`mpl.colors.Colormap` Raises ------ ValueError
[ "Validate", "a", "colormap" ]
7d916406a6d3c3c27c0b7102f98fef07a4da0a61
https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/plugin.py#L303-L324
train
54,438
Chilipp/psy-simple
psy_simple/plugin.py
validate_cmaps
def validate_cmaps(cmaps): """Validate a dictionary of color lists Parameters ---------- cmaps: dict a mapping from a colormap name to a list of colors Raises ------ ValueError If one of the values in `cmaps` is not a color list Notes ----- For all items (listname, list) in `cmaps`, the reversed list is automatically inserted with the ``listname + '_r'`` key.""" cmaps = {validate_str(key): validate_colorlist(val) for key, val in cmaps} for key, val in six.iteritems(cmaps): cmaps.setdefault(key + '_r', val[::-1]) return cmaps
python
def validate_cmaps(cmaps): """Validate a dictionary of color lists Parameters ---------- cmaps: dict a mapping from a colormap name to a list of colors Raises ------ ValueError If one of the values in `cmaps` is not a color list Notes ----- For all items (listname, list) in `cmaps`, the reversed list is automatically inserted with the ``listname + '_r'`` key.""" cmaps = {validate_str(key): validate_colorlist(val) for key, val in cmaps} for key, val in six.iteritems(cmaps): cmaps.setdefault(key + '_r', val[::-1]) return cmaps
[ "def", "validate_cmaps", "(", "cmaps", ")", ":", "cmaps", "=", "{", "validate_str", "(", "key", ")", ":", "validate_colorlist", "(", "val", ")", "for", "key", ",", "val", "in", "cmaps", "}", "for", "key", ",", "val", "in", "six", ".", "iteritems", "(...
Validate a dictionary of color lists Parameters ---------- cmaps: dict a mapping from a colormap name to a list of colors Raises ------ ValueError If one of the values in `cmaps` is not a color list Notes ----- For all items (listname, list) in `cmaps`, the reversed list is automatically inserted with the ``listname + '_r'`` key.
[ "Validate", "a", "dictionary", "of", "color", "lists" ]
7d916406a6d3c3c27c0b7102f98fef07a4da0a61
https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/plugin.py#L327-L347
train
54,439
Chilipp/psy-simple
psy_simple/plugin.py
validate_lineplot
def validate_lineplot(value): """Validate the value for the LinePlotter.plot formatoption Parameters ---------- value: None, str or list with mixture of both The value to validate""" if value is None: return value elif isinstance(value, six.string_types): return six.text_type(value) else: value = list(value) for i, v in enumerate(value): if v is None: pass elif isinstance(v, six.string_types): value[i] = six.text_type(v) else: raise ValueError('Expected None or string, found %s' % (v, )) return value
python
def validate_lineplot(value): """Validate the value for the LinePlotter.plot formatoption Parameters ---------- value: None, str or list with mixture of both The value to validate""" if value is None: return value elif isinstance(value, six.string_types): return six.text_type(value) else: value = list(value) for i, v in enumerate(value): if v is None: pass elif isinstance(v, six.string_types): value[i] = six.text_type(v) else: raise ValueError('Expected None or string, found %s' % (v, )) return value
[ "def", "validate_lineplot", "(", "value", ")", ":", "if", "value", "is", "None", ":", "return", "value", "elif", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "return", "six", ".", "text_type", "(", "value", ")", "else", ":", "...
Validate the value for the LinePlotter.plot formatoption Parameters ---------- value: None, str or list with mixture of both The value to validate
[ "Validate", "the", "value", "for", "the", "LinePlotter", ".", "plot", "formatoption" ]
7d916406a6d3c3c27c0b7102f98fef07a4da0a61
https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/plugin.py#L377-L397
train
54,440
rob-smallshire/trailer
trailer/writers/json/renderer.py
GpxJsonEncoder.visit_GpxModel
def visit_GpxModel(self, gpx_model, *args, **kwargs): """Render a GPXModel as a single JSON structure.""" result = OrderedDict() put_scalar = lambda name, json_name=None: self.optional_attribute_scalar(result, gpx_model, name, json_name) put_list = lambda name, json_name=None: self.optional_attribute_list(result, gpx_model, name, json_name) put_scalar('creator') put_scalar('metadata') put_list('waypoints') put_list('routes') put_list('tracks') put_list('extensions') return result
python
def visit_GpxModel(self, gpx_model, *args, **kwargs): """Render a GPXModel as a single JSON structure.""" result = OrderedDict() put_scalar = lambda name, json_name=None: self.optional_attribute_scalar(result, gpx_model, name, json_name) put_list = lambda name, json_name=None: self.optional_attribute_list(result, gpx_model, name, json_name) put_scalar('creator') put_scalar('metadata') put_list('waypoints') put_list('routes') put_list('tracks') put_list('extensions') return result
[ "def", "visit_GpxModel", "(", "self", ",", "gpx_model", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "result", "=", "OrderedDict", "(", ")", "put_scalar", "=", "lambda", "name", ",", "json_name", "=", "None", ":", "self", ".", "optional_attribute...
Render a GPXModel as a single JSON structure.
[ "Render", "a", "GPXModel", "as", "a", "single", "JSON", "structure", "." ]
e4b8a240561bfb6df91cc71247b7ef0c61e7d363
https://github.com/rob-smallshire/trailer/blob/e4b8a240561bfb6df91cc71247b7ef0c61e7d363/trailer/writers/json/renderer.py#L62-L76
train
54,441
rob-smallshire/trailer
trailer/writers/json/renderer.py
GpxJsonEncoder.visit_Metadata
def visit_Metadata(self, metadata, *args, **kwargs): """Render GPX Metadata as a single JSON structure.""" result = OrderedDict() put_scalar = lambda name, json_name=None: self.optional_attribute_scalar(result, metadata, name, json_name) put_list = lambda name, json_name=None: self.optional_attribute_list(result, metadata, name, json_name) put_scalar('name') put_scalar('description') put_scalar('author') put_scalar('copyright') put_list('links') put_scalar('time') put_scalar('keywords') put_scalar('bounds') put_list('extensions') return result
python
def visit_Metadata(self, metadata, *args, **kwargs): """Render GPX Metadata as a single JSON structure.""" result = OrderedDict() put_scalar = lambda name, json_name=None: self.optional_attribute_scalar(result, metadata, name, json_name) put_list = lambda name, json_name=None: self.optional_attribute_list(result, metadata, name, json_name) put_scalar('name') put_scalar('description') put_scalar('author') put_scalar('copyright') put_list('links') put_scalar('time') put_scalar('keywords') put_scalar('bounds') put_list('extensions') return result
[ "def", "visit_Metadata", "(", "self", ",", "metadata", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "result", "=", "OrderedDict", "(", ")", "put_scalar", "=", "lambda", "name", ",", "json_name", "=", "None", ":", "self", ".", "optional_attribute_...
Render GPX Metadata as a single JSON structure.
[ "Render", "GPX", "Metadata", "as", "a", "single", "JSON", "structure", "." ]
e4b8a240561bfb6df91cc71247b7ef0c61e7d363
https://github.com/rob-smallshire/trailer/blob/e4b8a240561bfb6df91cc71247b7ef0c61e7d363/trailer/writers/json/renderer.py#L79-L95
train
54,442
wheeler-microfluidics/dmf-control-board-firmware
dmf_control_board_firmware/calibrate/feedback.py
swap_default
def swap_default(mode, equation, symbol_names, default, **kwargs): ''' Given a `sympy` equation or equality, along with a list of symbol names, substitute the specified default value for each symbol for which a value is not provided through a keyword argument. For example, consider the following equality: >>> sp.pprint(H) V₂ Z₂ ── = ── V₁ Z₁ Let us substitute a default value of 1 for terms Z1 and Z2: >>> sp.pprint(subs_default(H, ['Z1', 'Z2'], 1)) V₂ ── = 1 V₁ Now, let us specify a default value of 1 for terms Z1 and Z2, but provide an overriding value for Z1: >>> sp.pprint(subs_default(H, ['Z1', 'Z2'], 1, Z1=4)) V₂ ── = 1/4 V₁ Note that keyword arguments for terms not specified in the list of symbol names are ignored: >>> sp.pprint(subs_default(H, ['Z1', 'Z2'], 1, Z1=4, Q=7)) V₂ ── = 1/4 V₁ ''' if mode == 'subs': swap_f = _subs default_swap_f = _subs elif mode == 'limit': swap_f = _limit default_swap_f = _subs elif mode == 'limit_default': swap_f = _subs default_swap_f = _limit else: raise ValueError('''Unsupported mode. `mode` must be one of: ''' '''('subs', 'limit').''') result = equation for s in symbol_names: if s in kwargs: if isinstance(kwargs[s], Iterable): continue else: result = swap_f(result, s, kwargs[s]) else: result = default_swap_f(result, s, default) return result
python
def swap_default(mode, equation, symbol_names, default, **kwargs): ''' Given a `sympy` equation or equality, along with a list of symbol names, substitute the specified default value for each symbol for which a value is not provided through a keyword argument. For example, consider the following equality: >>> sp.pprint(H) V₂ Z₂ ── = ── V₁ Z₁ Let us substitute a default value of 1 for terms Z1 and Z2: >>> sp.pprint(subs_default(H, ['Z1', 'Z2'], 1)) V₂ ── = 1 V₁ Now, let us specify a default value of 1 for terms Z1 and Z2, but provide an overriding value for Z1: >>> sp.pprint(subs_default(H, ['Z1', 'Z2'], 1, Z1=4)) V₂ ── = 1/4 V₁ Note that keyword arguments for terms not specified in the list of symbol names are ignored: >>> sp.pprint(subs_default(H, ['Z1', 'Z2'], 1, Z1=4, Q=7)) V₂ ── = 1/4 V₁ ''' if mode == 'subs': swap_f = _subs default_swap_f = _subs elif mode == 'limit': swap_f = _limit default_swap_f = _subs elif mode == 'limit_default': swap_f = _subs default_swap_f = _limit else: raise ValueError('''Unsupported mode. `mode` must be one of: ''' '''('subs', 'limit').''') result = equation for s in symbol_names: if s in kwargs: if isinstance(kwargs[s], Iterable): continue else: result = swap_f(result, s, kwargs[s]) else: result = default_swap_f(result, s, default) return result
[ "def", "swap_default", "(", "mode", ",", "equation", ",", "symbol_names", ",", "default", ",", "*", "*", "kwargs", ")", ":", "if", "mode", "==", "'subs'", ":", "swap_f", "=", "_subs", "default_swap_f", "=", "_subs", "elif", "mode", "==", "'limit'", ":", ...
Given a `sympy` equation or equality, along with a list of symbol names, substitute the specified default value for each symbol for which a value is not provided through a keyword argument. For example, consider the following equality: >>> sp.pprint(H) V₂ Z₂ ── = ── V₁ Z₁ Let us substitute a default value of 1 for terms Z1 and Z2: >>> sp.pprint(subs_default(H, ['Z1', 'Z2'], 1)) V₂ ── = 1 V₁ Now, let us specify a default value of 1 for terms Z1 and Z2, but provide an overriding value for Z1: >>> sp.pprint(subs_default(H, ['Z1', 'Z2'], 1, Z1=4)) V₂ ── = 1/4 V₁ Note that keyword arguments for terms not specified in the list of symbol names are ignored: >>> sp.pprint(subs_default(H, ['Z1', 'Z2'], 1, Z1=4, Q=7)) V₂ ── = 1/4 V₁
[ "Given", "a", "sympy", "equation", "or", "equality", "along", "with", "a", "list", "of", "symbol", "names", "substitute", "the", "specified", "default", "value", "for", "each", "symbol", "for", "which", "a", "value", "is", "not", "provided", "through", "a", ...
1cd8cc9a148d530f9a11f634f2dbfe73f08aa27c
https://github.com/wheeler-microfluidics/dmf-control-board-firmware/blob/1cd8cc9a148d530f9a11f634f2dbfe73f08aa27c/dmf_control_board_firmware/calibrate/feedback.py#L43-L101
train
54,443
wheeler-microfluidics/dmf-control-board-firmware
dmf_control_board_firmware/calibrate/feedback.py
z_transfer_functions
def z_transfer_functions(): r''' Return a symbolic equality representation of the transfer function of RMS voltage measured by either control board analog feedback circuits. According to the figure below, the transfer function describes the following relationship:: # Hardware V1 # # Hardware V2 # V₂ V₁ V₂ Z₁ ── = ─────── ── = ── Z₂ Z₁ + Z₂ V₁ Z₂ where $V_{1}$ denotes the high-voltage actuation signal from the amplifier output and $V_{2}$ denotes the signal sufficiently attenuated to fall within the measurable input range of the analog-to-digital converter *(approx. 5V)*. The feedback circuits for control board **hardware version 1** and **hardware version 2** are shown below. .. code-block:: none # Hardware V1 # # Hardware V2 # V_1 @ frequency V_1 @ frequency ┯ ┯ ┌─┴─┐ ┌─┴─┐ ┌───┐ │Z_1│ │Z_1│ ┌─┤Z_2├─┐ └─┬─┘ └─┬─┘ │ └───┘ │ ├───⊸ V_2 │ │ │╲ ├───⊸ V_2 ┌─┴─┐ └────┴──│-╲__│ │Z_2│ ┌──│+╱ └─┬─┘ │ │╱ ═╧═ │ ¯ ═╧═ ¯ Notes ----- - The symbolic equality can be solved for any symbol, _e.g.,_ $V_{1}$ or $V_{2}$. - A symbolically solved representation can be converted to a Python function using `sympy.utilities.lambdify.lambdify`_, to compute results for specific values of the remaining parameters. .. _`sympy.utilities.lambdify.lambdify`: http://docs.sympy.org/dev/modules/utilities/lambdify.html ''' # Define transfer function as a symbolic equality using SymPy. V1, V2, Z1, Z2 = sp.symbols('V1 V2 Z1 Z2') xfer_funcs = pd.Series([sp.Eq(V2 / Z2, V1 / (Z1 + Z2)), sp.Eq(V2 / V1, Z2 / Z1)], # Index by hardware version. index=[1, 2]) xfer_funcs.index.name = 'Hardware version' return xfer_funcs
python
def z_transfer_functions(): r''' Return a symbolic equality representation of the transfer function of RMS voltage measured by either control board analog feedback circuits. According to the figure below, the transfer function describes the following relationship:: # Hardware V1 # # Hardware V2 # V₂ V₁ V₂ Z₁ ── = ─────── ── = ── Z₂ Z₁ + Z₂ V₁ Z₂ where $V_{1}$ denotes the high-voltage actuation signal from the amplifier output and $V_{2}$ denotes the signal sufficiently attenuated to fall within the measurable input range of the analog-to-digital converter *(approx. 5V)*. The feedback circuits for control board **hardware version 1** and **hardware version 2** are shown below. .. code-block:: none # Hardware V1 # # Hardware V2 # V_1 @ frequency V_1 @ frequency ┯ ┯ ┌─┴─┐ ┌─┴─┐ ┌───┐ │Z_1│ │Z_1│ ┌─┤Z_2├─┐ └─┬─┘ └─┬─┘ │ └───┘ │ ├───⊸ V_2 │ │ │╲ ├───⊸ V_2 ┌─┴─┐ └────┴──│-╲__│ │Z_2│ ┌──│+╱ └─┬─┘ │ │╱ ═╧═ │ ¯ ═╧═ ¯ Notes ----- - The symbolic equality can be solved for any symbol, _e.g.,_ $V_{1}$ or $V_{2}$. - A symbolically solved representation can be converted to a Python function using `sympy.utilities.lambdify.lambdify`_, to compute results for specific values of the remaining parameters. .. _`sympy.utilities.lambdify.lambdify`: http://docs.sympy.org/dev/modules/utilities/lambdify.html ''' # Define transfer function as a symbolic equality using SymPy. V1, V2, Z1, Z2 = sp.symbols('V1 V2 Z1 Z2') xfer_funcs = pd.Series([sp.Eq(V2 / Z2, V1 / (Z1 + Z2)), sp.Eq(V2 / V1, Z2 / Z1)], # Index by hardware version. index=[1, 2]) xfer_funcs.index.name = 'Hardware version' return xfer_funcs
[ "def", "z_transfer_functions", "(", ")", ":", "# Define transfer function as a symbolic equality using SymPy.", "V1", ",", "V2", ",", "Z1", ",", "Z2", "=", "sp", ".", "symbols", "(", "'V1 V2 Z1 Z2'", ")", "xfer_funcs", "=", "pd", ".", "Series", "(", "[", "sp", ...
r''' Return a symbolic equality representation of the transfer function of RMS voltage measured by either control board analog feedback circuits. According to the figure below, the transfer function describes the following relationship:: # Hardware V1 # # Hardware V2 # V₂ V₁ V₂ Z₁ ── = ─────── ── = ── Z₂ Z₁ + Z₂ V₁ Z₂ where $V_{1}$ denotes the high-voltage actuation signal from the amplifier output and $V_{2}$ denotes the signal sufficiently attenuated to fall within the measurable input range of the analog-to-digital converter *(approx. 5V)*. The feedback circuits for control board **hardware version 1** and **hardware version 2** are shown below. .. code-block:: none # Hardware V1 # # Hardware V2 # V_1 @ frequency V_1 @ frequency ┯ ┯ ┌─┴─┐ ┌─┴─┐ ┌───┐ │Z_1│ │Z_1│ ┌─┤Z_2├─┐ └─┬─┘ └─┬─┘ │ └───┘ │ ├───⊸ V_2 │ │ │╲ ├───⊸ V_2 ┌─┴─┐ └────┴──│-╲__│ │Z_2│ ┌──│+╱ └─┬─┘ │ │╱ ═╧═ │ ¯ ═╧═ ¯ Notes ----- - The symbolic equality can be solved for any symbol, _e.g.,_ $V_{1}$ or $V_{2}$. - A symbolically solved representation can be converted to a Python function using `sympy.utilities.lambdify.lambdify`_, to compute results for specific values of the remaining parameters. .. _`sympy.utilities.lambdify.lambdify`: http://docs.sympy.org/dev/modules/utilities/lambdify.html
[ "r", "Return", "a", "symbolic", "equality", "representation", "of", "the", "transfer", "function", "of", "RMS", "voltage", "measured", "by", "either", "control", "board", "analog", "feedback", "circuits", "." ]
1cd8cc9a148d530f9a11f634f2dbfe73f08aa27c
https://github.com/wheeler-microfluidics/dmf-control-board-firmware/blob/1cd8cc9a148d530f9a11f634f2dbfe73f08aa27c/dmf_control_board_firmware/calibrate/feedback.py#L104-L159
train
54,444
studionow/pybrightcove
pybrightcove/config.py
has_option
def has_option(section, name): """ Wrapper around ConfigParser's ``has_option`` method. """ cfg = ConfigParser.SafeConfigParser({"working_dir": "/tmp", "debug": "0"}) cfg.read(CONFIG_LOCATIONS) return cfg.has_option(section, name)
python
def has_option(section, name): """ Wrapper around ConfigParser's ``has_option`` method. """ cfg = ConfigParser.SafeConfigParser({"working_dir": "/tmp", "debug": "0"}) cfg.read(CONFIG_LOCATIONS) return cfg.has_option(section, name)
[ "def", "has_option", "(", "section", ",", "name", ")", ":", "cfg", "=", "ConfigParser", ".", "SafeConfigParser", "(", "{", "\"working_dir\"", ":", "\"/tmp\"", ",", "\"debug\"", ":", "\"0\"", "}", ")", "cfg", ".", "read", "(", "CONFIG_LOCATIONS", ")", "retu...
Wrapper around ConfigParser's ``has_option`` method.
[ "Wrapper", "around", "ConfigParser", "s", "has_option", "method", "." ]
19c946b689a80156e070fe9bc35589c4b768e614
https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/config.py#L40-L46
train
54,445
studionow/pybrightcove
pybrightcove/config.py
get
def get(section, name): """ Wrapper around ConfigParser's ``get`` method. """ cfg = ConfigParser.SafeConfigParser({"working_dir": "/tmp", "debug": "0"}) cfg.read(CONFIG_LOCATIONS) val = cfg.get(section, name) return val.strip("'").strip('"')
python
def get(section, name): """ Wrapper around ConfigParser's ``get`` method. """ cfg = ConfigParser.SafeConfigParser({"working_dir": "/tmp", "debug": "0"}) cfg.read(CONFIG_LOCATIONS) val = cfg.get(section, name) return val.strip("'").strip('"')
[ "def", "get", "(", "section", ",", "name", ")", ":", "cfg", "=", "ConfigParser", ".", "SafeConfigParser", "(", "{", "\"working_dir\"", ":", "\"/tmp\"", ",", "\"debug\"", ":", "\"0\"", "}", ")", "cfg", ".", "read", "(", "CONFIG_LOCATIONS", ")", "val", "="...
Wrapper around ConfigParser's ``get`` method.
[ "Wrapper", "around", "ConfigParser", "s", "get", "method", "." ]
19c946b689a80156e070fe9bc35589c4b768e614
https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/config.py#L49-L56
train
54,446
memphis-iis/GLUDB
gludb/backends/gcd.py
make_key
def make_key(table_name, objid): """Create an object key for storage.""" key = datastore.Key() path = key.path_element.add() path.kind = table_name path.name = str(objid) return key
python
def make_key(table_name, objid): """Create an object key for storage.""" key = datastore.Key() path = key.path_element.add() path.kind = table_name path.name = str(objid) return key
[ "def", "make_key", "(", "table_name", ",", "objid", ")", ":", "key", "=", "datastore", ".", "Key", "(", ")", "path", "=", "key", ".", "path_element", ".", "add", "(", ")", "path", ".", "kind", "=", "table_name", "path", ".", "name", "=", "str", "("...
Create an object key for storage.
[ "Create", "an", "object", "key", "for", "storage", "." ]
25692528ff6fe8184a3570f61f31f1a90088a388
https://github.com/memphis-iis/GLUDB/blob/25692528ff6fe8184a3570f61f31f1a90088a388/gludb/backends/gcd.py#L53-L59
train
54,447
memphis-iis/GLUDB
gludb/backends/gcd.py
extract_entity
def extract_entity(found): """Copy found entity to a dict.""" obj = dict() for prop in found.entity.property: obj[prop.name] = prop.value.string_value return obj
python
def extract_entity(found): """Copy found entity to a dict.""" obj = dict() for prop in found.entity.property: obj[prop.name] = prop.value.string_value return obj
[ "def", "extract_entity", "(", "found", ")", ":", "obj", "=", "dict", "(", ")", "for", "prop", "in", "found", ".", "entity", ".", "property", ":", "obj", "[", "prop", ".", "name", "]", "=", "prop", ".", "value", ".", "string_value", "return", "obj" ]
Copy found entity to a dict.
[ "Copy", "found", "entity", "to", "a", "dict", "." ]
25692528ff6fe8184a3570f61f31f1a90088a388
https://github.com/memphis-iis/GLUDB/blob/25692528ff6fe8184a3570f61f31f1a90088a388/gludb/backends/gcd.py#L83-L88
train
54,448
memphis-iis/GLUDB
gludb/backends/gcd.py
read_rec
def read_rec(table_name, objid): """Generator that yields keyed recs from store.""" req = datastore.LookupRequest() req.key.extend([make_key(table_name, objid)]) for found in datastore.lookup(req).found: yield extract_entity(found)
python
def read_rec(table_name, objid): """Generator that yields keyed recs from store.""" req = datastore.LookupRequest() req.key.extend([make_key(table_name, objid)]) for found in datastore.lookup(req).found: yield extract_entity(found)
[ "def", "read_rec", "(", "table_name", ",", "objid", ")", ":", "req", "=", "datastore", ".", "LookupRequest", "(", ")", "req", ".", "key", ".", "extend", "(", "[", "make_key", "(", "table_name", ",", "objid", ")", "]", ")", "for", "found", "in", "data...
Generator that yields keyed recs from store.
[ "Generator", "that", "yields", "keyed", "recs", "from", "store", "." ]
25692528ff6fe8184a3570f61f31f1a90088a388
https://github.com/memphis-iis/GLUDB/blob/25692528ff6fe8184a3570f61f31f1a90088a388/gludb/backends/gcd.py#L91-L97
train
54,449
memphis-iis/GLUDB
gludb/backends/gcd.py
read_by_indexes
def read_by_indexes(table_name, index_name_values=None): """Index reader.""" req = datastore.RunQueryRequest() query = req.query query.kind.add().name = table_name if not index_name_values: index_name_values = [] for name, val in index_name_values: queryFilter = query.filter.property_filter queryFilter.property.name = name queryFilter.operator = datastore.PropertyFilter.EQUAL queryFilter.value.string_value = str(val) loop_its = 0 have_more = True while have_more: resp = datastore.run_query(req) found_something = False for found in resp.batch.entity_result: yield extract_entity(found) found_something = True if not found_something: # This is a guard against bugs or excessive looping - as long we # can keep yielding records we'll continue to execute loop_its += 1 if loop_its > 5: raise ValueError("Exceeded the excessive query threshold") if resp.batch.more_results != datastore.QueryResultBatch.NOT_FINISHED: have_more = False else: have_more = True end_cursor = resp.batch.end_cursor query.start_cursor.CopyFrom(end_cursor)
python
def read_by_indexes(table_name, index_name_values=None): """Index reader.""" req = datastore.RunQueryRequest() query = req.query query.kind.add().name = table_name if not index_name_values: index_name_values = [] for name, val in index_name_values: queryFilter = query.filter.property_filter queryFilter.property.name = name queryFilter.operator = datastore.PropertyFilter.EQUAL queryFilter.value.string_value = str(val) loop_its = 0 have_more = True while have_more: resp = datastore.run_query(req) found_something = False for found in resp.batch.entity_result: yield extract_entity(found) found_something = True if not found_something: # This is a guard against bugs or excessive looping - as long we # can keep yielding records we'll continue to execute loop_its += 1 if loop_its > 5: raise ValueError("Exceeded the excessive query threshold") if resp.batch.more_results != datastore.QueryResultBatch.NOT_FINISHED: have_more = False else: have_more = True end_cursor = resp.batch.end_cursor query.start_cursor.CopyFrom(end_cursor)
[ "def", "read_by_indexes", "(", "table_name", ",", "index_name_values", "=", "None", ")", ":", "req", "=", "datastore", ".", "RunQueryRequest", "(", ")", "query", "=", "req", ".", "query", "query", ".", "kind", ".", "add", "(", ")", ".", "name", "=", "t...
Index reader.
[ "Index", "reader", "." ]
25692528ff6fe8184a3570f61f31f1a90088a388
https://github.com/memphis-iis/GLUDB/blob/25692528ff6fe8184a3570f61f31f1a90088a388/gludb/backends/gcd.py#L100-L138
train
54,450
memphis-iis/GLUDB
gludb/backends/gcd.py
delete_table
def delete_table(table_name): """Mainly for testing.""" to_delete = [ make_key(table_name, rec['id']) for rec in read_by_indexes(table_name, []) ] with DatastoreTransaction() as tx: tx.get_commit_req().mutation.delete.extend(to_delete)
python
def delete_table(table_name): """Mainly for testing.""" to_delete = [ make_key(table_name, rec['id']) for rec in read_by_indexes(table_name, []) ] with DatastoreTransaction() as tx: tx.get_commit_req().mutation.delete.extend(to_delete)
[ "def", "delete_table", "(", "table_name", ")", ":", "to_delete", "=", "[", "make_key", "(", "table_name", ",", "rec", "[", "'id'", "]", ")", "for", "rec", "in", "read_by_indexes", "(", "table_name", ",", "[", "]", ")", "]", "with", "DatastoreTransaction", ...
Mainly for testing.
[ "Mainly", "for", "testing", "." ]
25692528ff6fe8184a3570f61f31f1a90088a388
https://github.com/memphis-iis/GLUDB/blob/25692528ff6fe8184a3570f61f31f1a90088a388/gludb/backends/gcd.py#L141-L149
train
54,451
memphis-iis/GLUDB
gludb/backends/gcd.py
DatastoreTransaction.get_commit_req
def get_commit_req(self): """Lazy commit request getter.""" if not self.commit_req: self.commit_req = datastore.CommitRequest() self.commit_req.transaction = self.tx return self.commit_req
python
def get_commit_req(self): """Lazy commit request getter.""" if not self.commit_req: self.commit_req = datastore.CommitRequest() self.commit_req.transaction = self.tx return self.commit_req
[ "def", "get_commit_req", "(", "self", ")", ":", "if", "not", "self", ".", "commit_req", ":", "self", ".", "commit_req", "=", "datastore", ".", "CommitRequest", "(", ")", "self", ".", "commit_req", ".", "transaction", "=", "self", ".", "tx", "return", "se...
Lazy commit request getter.
[ "Lazy", "commit", "request", "getter", "." ]
25692528ff6fe8184a3570f61f31f1a90088a388
https://github.com/memphis-iis/GLUDB/blob/25692528ff6fe8184a3570f61f31f1a90088a388/gludb/backends/gcd.py#L31-L36
train
54,452
toumorokoshi/sprinter
sprinter/lib/command.py
call
def call(command, stdin=None, stdout=subprocess.PIPE, env=os.environ, cwd=None, shell=False, output_log_level=logging.INFO, sensitive_info=False): """ Better, smarter call logic """ if not sensitive_info: logger.debug("calling command: %s" % command) else: logger.debug("calling command with sensitive information") try: args = command if shell else whitespace_smart_split(command) kw = {} if not shell and not which(args[0], cwd=cwd): raise CommandMissingException(args[0]) if shell: kw['shell'] = True process = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=stdout, stderr=subprocess.STDOUT, env=env, cwd=cwd, **kw) output = process.communicate(input=stdin)[0] if output is not None: try: logger.log(output_log_level, output.decode('utf-8')) except UnicodeDecodeError: pass return (process.returncode, output) except OSError: e = sys.exc_info()[1] if not sensitive_info: logger.exception("Error running command: %s" % command) logger.error("Root directory: %s" % cwd) if stdin: logger.error("stdin: %s" % stdin) raise e
python
def call(command, stdin=None, stdout=subprocess.PIPE, env=os.environ, cwd=None, shell=False, output_log_level=logging.INFO, sensitive_info=False): """ Better, smarter call logic """ if not sensitive_info: logger.debug("calling command: %s" % command) else: logger.debug("calling command with sensitive information") try: args = command if shell else whitespace_smart_split(command) kw = {} if not shell and not which(args[0], cwd=cwd): raise CommandMissingException(args[0]) if shell: kw['shell'] = True process = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=stdout, stderr=subprocess.STDOUT, env=env, cwd=cwd, **kw) output = process.communicate(input=stdin)[0] if output is not None: try: logger.log(output_log_level, output.decode('utf-8')) except UnicodeDecodeError: pass return (process.returncode, output) except OSError: e = sys.exc_info()[1] if not sensitive_info: logger.exception("Error running command: %s" % command) logger.error("Root directory: %s" % cwd) if stdin: logger.error("stdin: %s" % stdin) raise e
[ "def", "call", "(", "command", ",", "stdin", "=", "None", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "env", "=", "os", ".", "environ", ",", "cwd", "=", "None", ",", "shell", "=", "False", ",", "output_log_level", "=", "logging", ".", "INFO",...
Better, smarter call logic
[ "Better", "smarter", "call", "logic" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/lib/command.py#L22-L53
train
54,453
toumorokoshi/sprinter
sprinter/lib/command.py
whitespace_smart_split
def whitespace_smart_split(command): """ Split a command by whitespace, taking care to not split on whitespace within quotes. >>> whitespace_smart_split("test this \\\"in here\\\" again") ['test', 'this', '"in here"', 'again'] """ return_array = [] s = "" in_double_quotes = False escape = False for c in command: if c == '"': if in_double_quotes: if escape: s += c escape = False else: s += c in_double_quotes = False else: in_double_quotes = True s += c else: if in_double_quotes: if c == '\\': escape = True s += c else: escape = False s += c else: if c == ' ': return_array.append(s) s = "" else: s += c if s != "": return_array.append(s) return return_array
python
def whitespace_smart_split(command): """ Split a command by whitespace, taking care to not split on whitespace within quotes. >>> whitespace_smart_split("test this \\\"in here\\\" again") ['test', 'this', '"in here"', 'again'] """ return_array = [] s = "" in_double_quotes = False escape = False for c in command: if c == '"': if in_double_quotes: if escape: s += c escape = False else: s += c in_double_quotes = False else: in_double_quotes = True s += c else: if in_double_quotes: if c == '\\': escape = True s += c else: escape = False s += c else: if c == ' ': return_array.append(s) s = "" else: s += c if s != "": return_array.append(s) return return_array
[ "def", "whitespace_smart_split", "(", "command", ")", ":", "return_array", "=", "[", "]", "s", "=", "\"\"", "in_double_quotes", "=", "False", "escape", "=", "False", "for", "c", "in", "command", ":", "if", "c", "==", "'\"'", ":", "if", "in_double_quotes", ...
Split a command by whitespace, taking care to not split on whitespace within quotes. >>> whitespace_smart_split("test this \\\"in here\\\" again") ['test', 'this', '"in here"', 'again']
[ "Split", "a", "command", "by", "whitespace", "taking", "care", "to", "not", "split", "on", "whitespace", "within", "quotes", "." ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/lib/command.py#L56-L97
train
54,454
toumorokoshi/sprinter
sprinter/feature/__init__.py
Feature.sync
def sync(self): """ execute the steps required to have the feature end with the desired state. """ phase = _get_phase(self._formula_instance) self.logger.info("%s %s..." % (phase.verb.capitalize(), self.feature_name)) message = "...finished %s %s." % (phase.verb, self.feature_name) result = getattr(self, phase.name)() if result or phase in (PHASE.INSTALL, PHASE.REMOVE): self.logger.info(message) else: self.logger.debug(message) return result
python
def sync(self): """ execute the steps required to have the feature end with the desired state. """ phase = _get_phase(self._formula_instance) self.logger.info("%s %s..." % (phase.verb.capitalize(), self.feature_name)) message = "...finished %s %s." % (phase.verb, self.feature_name) result = getattr(self, phase.name)() if result or phase in (PHASE.INSTALL, PHASE.REMOVE): self.logger.info(message) else: self.logger.debug(message) return result
[ "def", "sync", "(", "self", ")", ":", "phase", "=", "_get_phase", "(", "self", ".", "_formula_instance", ")", "self", ".", "logger", ".", "info", "(", "\"%s %s...\"", "%", "(", "phase", ".", "verb", ".", "capitalize", "(", ")", ",", "self", ".", "fea...
execute the steps required to have the feature end with the desired state.
[ "execute", "the", "steps", "required", "to", "have", "the", "feature", "end", "with", "the", "desired", "state", "." ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/feature/__init__.py#L33-L46
train
54,455
satori-ng/hooker
hooker/hook_list.py
HookList.isloaded
def isloaded(self, name): """Checks if given hook module has been loaded Args: name (str): The name of the module to check Returns: bool. The return code:: True -- Loaded False -- Not Loaded """ if name is None: return True if isinstance(name, str): return (name in [x.__module__ for x in self]) if isinstance(name, Iterable): return set(name).issubset([x.__module__ for x in self]) return False
python
def isloaded(self, name): """Checks if given hook module has been loaded Args: name (str): The name of the module to check Returns: bool. The return code:: True -- Loaded False -- Not Loaded """ if name is None: return True if isinstance(name, str): return (name in [x.__module__ for x in self]) if isinstance(name, Iterable): return set(name).issubset([x.__module__ for x in self]) return False
[ "def", "isloaded", "(", "self", ",", "name", ")", ":", "if", "name", "is", "None", ":", "return", "True", "if", "isinstance", "(", "name", ",", "str", ")", ":", "return", "(", "name", "in", "[", "x", ".", "__module__", "for", "x", "in", "self", "...
Checks if given hook module has been loaded Args: name (str): The name of the module to check Returns: bool. The return code:: True -- Loaded False -- Not Loaded
[ "Checks", "if", "given", "hook", "module", "has", "been", "loaded" ]
8ef1fffe1537f06313799d1e5e6f7acc4ab405b4
https://github.com/satori-ng/hooker/blob/8ef1fffe1537f06313799d1e5e6f7acc4ab405b4/hooker/hook_list.py#L103-L124
train
54,456
satori-ng/hooker
hooker/hook_list.py
HookList.hook
def hook(self, function, dependencies=None): """Tries to load a hook Args: function (func): Function that will be called when the event is called Kwargs: dependencies (str): String or Iterable with modules whose hooks should be called before this one Raises: :class:TypeError Note that the dependencies are module-wide, that means that if `parent.foo` and `parent.bar` are both subscribed to `example` event and `child` enumerates `parent` as dependcy, **both** `foo` and `bar` must be called in order for the dependcy to get resolved. """ if not isinstance(dependencies, (Iterable, type(None), str)): raise TypeError("Invalid list of dependencies provided!") # Tag the function with its dependencies if not hasattr(function, "__deps__"): function.__deps__ = dependencies # If a module is loaded before all its dependencies are loaded, put # it in _later list and don't load yet if self.isloaded(function.__deps__): self.append(function) else: self._later.append(function) # After each module load, retry to resolve dependencies for ext in self._later: if self.isloaded(ext.__deps__): self._later.remove(ext) self.hook(ext)
python
def hook(self, function, dependencies=None): """Tries to load a hook Args: function (func): Function that will be called when the event is called Kwargs: dependencies (str): String or Iterable with modules whose hooks should be called before this one Raises: :class:TypeError Note that the dependencies are module-wide, that means that if `parent.foo` and `parent.bar` are both subscribed to `example` event and `child` enumerates `parent` as dependcy, **both** `foo` and `bar` must be called in order for the dependcy to get resolved. """ if not isinstance(dependencies, (Iterable, type(None), str)): raise TypeError("Invalid list of dependencies provided!") # Tag the function with its dependencies if not hasattr(function, "__deps__"): function.__deps__ = dependencies # If a module is loaded before all its dependencies are loaded, put # it in _later list and don't load yet if self.isloaded(function.__deps__): self.append(function) else: self._later.append(function) # After each module load, retry to resolve dependencies for ext in self._later: if self.isloaded(ext.__deps__): self._later.remove(ext) self.hook(ext)
[ "def", "hook", "(", "self", ",", "function", ",", "dependencies", "=", "None", ")", ":", "if", "not", "isinstance", "(", "dependencies", ",", "(", "Iterable", ",", "type", "(", "None", ")", ",", "str", ")", ")", ":", "raise", "TypeError", "(", "\"Inv...
Tries to load a hook Args: function (func): Function that will be called when the event is called Kwargs: dependencies (str): String or Iterable with modules whose hooks should be called before this one Raises: :class:TypeError Note that the dependencies are module-wide, that means that if `parent.foo` and `parent.bar` are both subscribed to `example` event and `child` enumerates `parent` as dependcy, **both** `foo` and `bar` must be called in order for the dependcy to get resolved.
[ "Tries", "to", "load", "a", "hook" ]
8ef1fffe1537f06313799d1e5e6f7acc4ab405b4
https://github.com/satori-ng/hooker/blob/8ef1fffe1537f06313799d1e5e6f7acc4ab405b4/hooker/hook_list.py#L126-L161
train
54,457
gtaylor/EVE-Market-Data-Structures
emds/formats/unified/__init__.py
parse_from_json
def parse_from_json(json_str): """ Given a Unified Uploader message, parse the contents and return a MarketOrderList or MarketHistoryList instance. :param str json_str: A Unified Uploader message as a JSON string. :rtype: MarketOrderList or MarketHistoryList :raises: MalformedUploadError when invalid JSON is passed in. """ try: message_dict = json.loads(json_str) except ValueError: raise ParseError("Mal-formed JSON input.") upload_keys = message_dict.get('uploadKeys', False) if upload_keys is False: raise ParseError( "uploadKeys does not exist. At minimum, an empty array is required." ) elif not isinstance(upload_keys, list): raise ParseError( "uploadKeys must be an array object." ) upload_type = message_dict['resultType'] try: if upload_type == 'orders': return orders.parse_from_dict(message_dict) elif upload_type == 'history': return history.parse_from_dict(message_dict) else: raise ParseError( 'Unified message has unknown upload_type: %s' % upload_type) except TypeError as exc: # MarketOrder and HistoryEntry both raise TypeError exceptions if # invalid input is encountered. raise ParseError(exc.message)
python
def parse_from_json(json_str): """ Given a Unified Uploader message, parse the contents and return a MarketOrderList or MarketHistoryList instance. :param str json_str: A Unified Uploader message as a JSON string. :rtype: MarketOrderList or MarketHistoryList :raises: MalformedUploadError when invalid JSON is passed in. """ try: message_dict = json.loads(json_str) except ValueError: raise ParseError("Mal-formed JSON input.") upload_keys = message_dict.get('uploadKeys', False) if upload_keys is False: raise ParseError( "uploadKeys does not exist. At minimum, an empty array is required." ) elif not isinstance(upload_keys, list): raise ParseError( "uploadKeys must be an array object." ) upload_type = message_dict['resultType'] try: if upload_type == 'orders': return orders.parse_from_dict(message_dict) elif upload_type == 'history': return history.parse_from_dict(message_dict) else: raise ParseError( 'Unified message has unknown upload_type: %s' % upload_type) except TypeError as exc: # MarketOrder and HistoryEntry both raise TypeError exceptions if # invalid input is encountered. raise ParseError(exc.message)
[ "def", "parse_from_json", "(", "json_str", ")", ":", "try", ":", "message_dict", "=", "json", ".", "loads", "(", "json_str", ")", "except", "ValueError", ":", "raise", "ParseError", "(", "\"Mal-formed JSON input.\"", ")", "upload_keys", "=", "message_dict", ".",...
Given a Unified Uploader message, parse the contents and return a MarketOrderList or MarketHistoryList instance. :param str json_str: A Unified Uploader message as a JSON string. :rtype: MarketOrderList or MarketHistoryList :raises: MalformedUploadError when invalid JSON is passed in.
[ "Given", "a", "Unified", "Uploader", "message", "parse", "the", "contents", "and", "return", "a", "MarketOrderList", "or", "MarketHistoryList", "instance", "." ]
77d69b24f2aada3aeff8fba3d75891bfba8fdcf3
https://github.com/gtaylor/EVE-Market-Data-Structures/blob/77d69b24f2aada3aeff8fba3d75891bfba8fdcf3/emds/formats/unified/__init__.py#L6-L43
train
54,458
gtaylor/EVE-Market-Data-Structures
emds/formats/unified/__init__.py
encode_to_json
def encode_to_json(order_or_history): """ Given an order or history entry, encode it to JSON and return. :type order_or_history: MarketOrderList or MarketHistoryList :param order_or_history: A MarketOrderList or MarketHistoryList instance to encode to JSON. :rtype: str :return: The encoded JSON string. """ if isinstance(order_or_history, MarketOrderList): return orders.encode_to_json(order_or_history) elif isinstance(order_or_history, MarketHistoryList): return history.encode_to_json(order_or_history) else: raise Exception("Must be one of MarketOrderList or MarketHistoryList.")
python
def encode_to_json(order_or_history): """ Given an order or history entry, encode it to JSON and return. :type order_or_history: MarketOrderList or MarketHistoryList :param order_or_history: A MarketOrderList or MarketHistoryList instance to encode to JSON. :rtype: str :return: The encoded JSON string. """ if isinstance(order_or_history, MarketOrderList): return orders.encode_to_json(order_or_history) elif isinstance(order_or_history, MarketHistoryList): return history.encode_to_json(order_or_history) else: raise Exception("Must be one of MarketOrderList or MarketHistoryList.")
[ "def", "encode_to_json", "(", "order_or_history", ")", ":", "if", "isinstance", "(", "order_or_history", ",", "MarketOrderList", ")", ":", "return", "orders", ".", "encode_to_json", "(", "order_or_history", ")", "elif", "isinstance", "(", "order_or_history", ",", ...
Given an order or history entry, encode it to JSON and return. :type order_or_history: MarketOrderList or MarketHistoryList :param order_or_history: A MarketOrderList or MarketHistoryList instance to encode to JSON. :rtype: str :return: The encoded JSON string.
[ "Given", "an", "order", "or", "history", "entry", "encode", "it", "to", "JSON", "and", "return", "." ]
77d69b24f2aada3aeff8fba3d75891bfba8fdcf3
https://github.com/gtaylor/EVE-Market-Data-Structures/blob/77d69b24f2aada3aeff8fba3d75891bfba8fdcf3/emds/formats/unified/__init__.py#L45-L60
train
54,459
bioidiap/bob.ip.facedetect
bob/ip/facedetect/detector/cascade.py
Cascade.add
def add(self, classifier, threshold, begin=None, end=None): """Adds a new strong classifier with the given threshold to the cascade. **Parameters:** classifier : :py:class:`bob.learn.boosting.BoostedMachine` A strong classifier to add ``threshold`` : float The classification threshold for this cascade step ``begin``, ``end`` : int or ``None`` If specified, only the weak machines with the indices ``range(begin,end)`` will be added. """ boosted_machine = bob.learn.boosting.BoostedMachine() if begin is None: begin = 0 if end is None: end = len(classifier.weak_machines) for i in range(begin, end): boosted_machine.add_weak_machine(classifier.weak_machines[i], classifier.weights[i]) self.cascade.append(boosted_machine) self.thresholds.append(threshold) self._indices()
python
def add(self, classifier, threshold, begin=None, end=None): """Adds a new strong classifier with the given threshold to the cascade. **Parameters:** classifier : :py:class:`bob.learn.boosting.BoostedMachine` A strong classifier to add ``threshold`` : float The classification threshold for this cascade step ``begin``, ``end`` : int or ``None`` If specified, only the weak machines with the indices ``range(begin,end)`` will be added. """ boosted_machine = bob.learn.boosting.BoostedMachine() if begin is None: begin = 0 if end is None: end = len(classifier.weak_machines) for i in range(begin, end): boosted_machine.add_weak_machine(classifier.weak_machines[i], classifier.weights[i]) self.cascade.append(boosted_machine) self.thresholds.append(threshold) self._indices()
[ "def", "add", "(", "self", ",", "classifier", ",", "threshold", ",", "begin", "=", "None", ",", "end", "=", "None", ")", ":", "boosted_machine", "=", "bob", ".", "learn", ".", "boosting", ".", "BoostedMachine", "(", ")", "if", "begin", "is", "None", ...
Adds a new strong classifier with the given threshold to the cascade. **Parameters:** classifier : :py:class:`bob.learn.boosting.BoostedMachine` A strong classifier to add ``threshold`` : float The classification threshold for this cascade step ``begin``, ``end`` : int or ``None`` If specified, only the weak machines with the indices ``range(begin,end)`` will be added.
[ "Adds", "a", "new", "strong", "classifier", "with", "the", "given", "threshold", "to", "the", "cascade", "." ]
601da5141ca7302ad36424d1421b33190ba46779
https://github.com/bioidiap/bob.ip.facedetect/blob/601da5141ca7302ad36424d1421b33190ba46779/bob/ip/facedetect/detector/cascade.py#L44-L65
train
54,460
bioidiap/bob.ip.facedetect
bob/ip/facedetect/detector/cascade.py
Cascade.create_from_boosted_machine
def create_from_boosted_machine(self, boosted_machine, classifiers_per_round, classification_thresholds=-5.): """Creates this cascade from the given boosted machine, by simply splitting off strong classifiers that have classifiers_per_round weak classifiers. **Parameters:** ``boosted_machine`` : :py:class:`bob.learn.boosting.BoostedMachine` The strong classifier to split into a regular cascade. ``classifiers_per_round`` : int The number of classifiers that each cascade step should contain. ``classification_threshold`` : float A single threshold that will be applied in all rounds of the cascade. """ indices = list(range(0, len(boosted_machine.weak_machines), classifiers_per_round)) if indices[-1] != len(boosted_machine.weak_machines): indices.append(len(boosted_machine.weak_machines)) self.cascade = [] self.indices = [] for i in range(len(indices)-1): machine = bob.learn.boosting.BoostedMachine() for index in range(indices[i], indices[i+1]): machine.add_weak_machine(boosted_machine.weak_machines[index], boosted_machine.weights[index, 0]) self.cascade.append(machine) if isinstance(classification_thresholds, (int, float)): self.thresholds = [classification_thresholds] * len(self.cascade) else: self.thresholds = classification_thresholds
python
def create_from_boosted_machine(self, boosted_machine, classifiers_per_round, classification_thresholds=-5.): """Creates this cascade from the given boosted machine, by simply splitting off strong classifiers that have classifiers_per_round weak classifiers. **Parameters:** ``boosted_machine`` : :py:class:`bob.learn.boosting.BoostedMachine` The strong classifier to split into a regular cascade. ``classifiers_per_round`` : int The number of classifiers that each cascade step should contain. ``classification_threshold`` : float A single threshold that will be applied in all rounds of the cascade. """ indices = list(range(0, len(boosted_machine.weak_machines), classifiers_per_round)) if indices[-1] != len(boosted_machine.weak_machines): indices.append(len(boosted_machine.weak_machines)) self.cascade = [] self.indices = [] for i in range(len(indices)-1): machine = bob.learn.boosting.BoostedMachine() for index in range(indices[i], indices[i+1]): machine.add_weak_machine(boosted_machine.weak_machines[index], boosted_machine.weights[index, 0]) self.cascade.append(machine) if isinstance(classification_thresholds, (int, float)): self.thresholds = [classification_thresholds] * len(self.cascade) else: self.thresholds = classification_thresholds
[ "def", "create_from_boosted_machine", "(", "self", ",", "boosted_machine", ",", "classifiers_per_round", ",", "classification_thresholds", "=", "-", "5.", ")", ":", "indices", "=", "list", "(", "range", "(", "0", ",", "len", "(", "boosted_machine", ".", "weak_ma...
Creates this cascade from the given boosted machine, by simply splitting off strong classifiers that have classifiers_per_round weak classifiers. **Parameters:** ``boosted_machine`` : :py:class:`bob.learn.boosting.BoostedMachine` The strong classifier to split into a regular cascade. ``classifiers_per_round`` : int The number of classifiers that each cascade step should contain. ``classification_threshold`` : float A single threshold that will be applied in all rounds of the cascade.
[ "Creates", "this", "cascade", "from", "the", "given", "boosted", "machine", "by", "simply", "splitting", "off", "strong", "classifiers", "that", "have", "classifiers_per_round", "weak", "classifiers", "." ]
601da5141ca7302ad36424d1421b33190ba46779
https://github.com/bioidiap/bob.ip.facedetect/blob/601da5141ca7302ad36424d1421b33190ba46779/bob/ip/facedetect/detector/cascade.py#L68-L94
train
54,461
bioidiap/bob.ip.facedetect
bob/ip/facedetect/detector/cascade.py
Cascade.save
def save(self, hdf5): """Saves this cascade into the given HDF5 file. **Parameters:** ``hdf5`` : :py:class:`bob.io.base.HDF5File` An HDF5 file open for writing """ # write the cascade to file hdf5.set("Thresholds", self.thresholds) for i in range(len(self.cascade)): hdf5.create_group("Classifier_%d" % (i+1)) hdf5.cd("Classifier_%d" % (i+1)) self.cascade[i].save(hdf5) hdf5.cd("..") hdf5.create_group("FeatureExtractor") hdf5.cd("FeatureExtractor") self.extractor.save(hdf5) hdf5.cd("..")
python
def save(self, hdf5): """Saves this cascade into the given HDF5 file. **Parameters:** ``hdf5`` : :py:class:`bob.io.base.HDF5File` An HDF5 file open for writing """ # write the cascade to file hdf5.set("Thresholds", self.thresholds) for i in range(len(self.cascade)): hdf5.create_group("Classifier_%d" % (i+1)) hdf5.cd("Classifier_%d" % (i+1)) self.cascade[i].save(hdf5) hdf5.cd("..") hdf5.create_group("FeatureExtractor") hdf5.cd("FeatureExtractor") self.extractor.save(hdf5) hdf5.cd("..")
[ "def", "save", "(", "self", ",", "hdf5", ")", ":", "# write the cascade to file", "hdf5", ".", "set", "(", "\"Thresholds\"", ",", "self", ".", "thresholds", ")", "for", "i", "in", "range", "(", "len", "(", "self", ".", "cascade", ")", ")", ":", "hdf5",...
Saves this cascade into the given HDF5 file. **Parameters:** ``hdf5`` : :py:class:`bob.io.base.HDF5File` An HDF5 file open for writing
[ "Saves", "this", "cascade", "into", "the", "given", "HDF5", "file", "." ]
601da5141ca7302ad36424d1421b33190ba46779
https://github.com/bioidiap/bob.ip.facedetect/blob/601da5141ca7302ad36424d1421b33190ba46779/bob/ip/facedetect/detector/cascade.py#L174-L192
train
54,462
bioidiap/bob.ip.facedetect
bob/ip/facedetect/detector/cascade.py
Cascade.load
def load(self, hdf5): """Loads this cascade from the given HDF5 file. **Parameters:** ``hdf5`` : :py:class:`bob.io.base.HDF5File` An HDF5 file open for reading """ # write the cascade to file self.thresholds = hdf5.read("Thresholds") self.cascade = [] for i in range(len(self.thresholds)): hdf5.cd("Classifier_%d" % (i+1)) self.cascade.append(bob.learn.boosting.BoostedMachine(hdf5)) hdf5.cd("..") hdf5.cd("FeatureExtractor") self.extractor = FeatureExtractor(hdf5) hdf5.cd("..") self._indices()
python
def load(self, hdf5): """Loads this cascade from the given HDF5 file. **Parameters:** ``hdf5`` : :py:class:`bob.io.base.HDF5File` An HDF5 file open for reading """ # write the cascade to file self.thresholds = hdf5.read("Thresholds") self.cascade = [] for i in range(len(self.thresholds)): hdf5.cd("Classifier_%d" % (i+1)) self.cascade.append(bob.learn.boosting.BoostedMachine(hdf5)) hdf5.cd("..") hdf5.cd("FeatureExtractor") self.extractor = FeatureExtractor(hdf5) hdf5.cd("..") self._indices()
[ "def", "load", "(", "self", ",", "hdf5", ")", ":", "# write the cascade to file", "self", ".", "thresholds", "=", "hdf5", ".", "read", "(", "\"Thresholds\"", ")", "self", ".", "cascade", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "self"...
Loads this cascade from the given HDF5 file. **Parameters:** ``hdf5`` : :py:class:`bob.io.base.HDF5File` An HDF5 file open for reading
[ "Loads", "this", "cascade", "from", "the", "given", "HDF5", "file", "." ]
601da5141ca7302ad36424d1421b33190ba46779
https://github.com/bioidiap/bob.ip.facedetect/blob/601da5141ca7302ad36424d1421b33190ba46779/bob/ip/facedetect/detector/cascade.py#L195-L213
train
54,463
inveniosoftware/kwalitee
kwalitee/cli/check.py
check
def check(ctx, repository, config): """Check commits.""" ctx.obj = Repo(repository=repository, config=config)
python
def check(ctx, repository, config): """Check commits.""" ctx.obj = Repo(repository=repository, config=config)
[ "def", "check", "(", "ctx", ",", "repository", ",", "config", ")", ":", "ctx", ".", "obj", "=", "Repo", "(", "repository", "=", "repository", ",", "config", "=", "config", ")" ]
Check commits.
[ "Check", "commits", "." ]
9124f8f55b15547fef08c6c43cabced314e70674
https://github.com/inveniosoftware/kwalitee/blob/9124f8f55b15547fef08c6c43cabced314e70674/kwalitee/cli/check.py#L64-L66
train
54,464
inveniosoftware/kwalitee
kwalitee/cli/check.py
message
def message(obj, commit='HEAD', skip_merge_commits=False): """Check the messages of the commits.""" from ..kwalitee import check_message options = obj.options repository = obj.repository if options.get('colors') is not False: colorama.init(autoreset=True) reset = colorama.Style.RESET_ALL yellow = colorama.Fore.YELLOW green = colorama.Fore.GREEN red = colorama.Fore.RED else: reset = yellow = green = red = '' try: sha = 'oid' commits = _pygit2_commits(commit, repository) except ImportError: try: sha = 'hexsha' commits = _git_commits(commit, repository) except ImportError: click.echo('To use this feature, please install pygit2. ' 'GitPython will also work but is not recommended ' '(python <= 2.7 only).', file=sys.stderr) return 2 template = '{0}commit {{commit.{1}}}{2}\n\n'.format(yellow, sha, reset) template += '{message}{errors}' count = 0 ident = ' ' re_line = re.compile('^', re.MULTILINE) for commit in commits: if skip_merge_commits and _is_merge_commit(commit): continue message = commit.message errors = check_message(message, **options) message = re.sub(re_line, ident, message) if errors: count += 1 errors.insert(0, red) else: errors = [green, 'Everything is OK.'] errors.append(reset) click.echo(template.format(commit=commit, message=message.encode('utf-8'), errors='\n'.join(errors))) if min(count, 1): raise click.Abort
python
def message(obj, commit='HEAD', skip_merge_commits=False): """Check the messages of the commits.""" from ..kwalitee import check_message options = obj.options repository = obj.repository if options.get('colors') is not False: colorama.init(autoreset=True) reset = colorama.Style.RESET_ALL yellow = colorama.Fore.YELLOW green = colorama.Fore.GREEN red = colorama.Fore.RED else: reset = yellow = green = red = '' try: sha = 'oid' commits = _pygit2_commits(commit, repository) except ImportError: try: sha = 'hexsha' commits = _git_commits(commit, repository) except ImportError: click.echo('To use this feature, please install pygit2. ' 'GitPython will also work but is not recommended ' '(python <= 2.7 only).', file=sys.stderr) return 2 template = '{0}commit {{commit.{1}}}{2}\n\n'.format(yellow, sha, reset) template += '{message}{errors}' count = 0 ident = ' ' re_line = re.compile('^', re.MULTILINE) for commit in commits: if skip_merge_commits and _is_merge_commit(commit): continue message = commit.message errors = check_message(message, **options) message = re.sub(re_line, ident, message) if errors: count += 1 errors.insert(0, red) else: errors = [green, 'Everything is OK.'] errors.append(reset) click.echo(template.format(commit=commit, message=message.encode('utf-8'), errors='\n'.join(errors))) if min(count, 1): raise click.Abort
[ "def", "message", "(", "obj", ",", "commit", "=", "'HEAD'", ",", "skip_merge_commits", "=", "False", ")", ":", "from", ".", ".", "kwalitee", "import", "check_message", "options", "=", "obj", ".", "options", "repository", "=", "obj", ".", "repository", "if"...
Check the messages of the commits.
[ "Check", "the", "messages", "of", "the", "commits", "." ]
9124f8f55b15547fef08c6c43cabced314e70674
https://github.com/inveniosoftware/kwalitee/blob/9124f8f55b15547fef08c6c43cabced314e70674/kwalitee/cli/check.py#L117-L170
train
54,465
0k/kids.cmd
src/kids/cmd/cmd.py
get_obj_subcmds
def get_obj_subcmds(obj): """Fetch action in callable attributes which and commands Callable must have their attribute 'command' set to True to be recognised by this lookup. Please consider using the decorator ``@cmd`` to declare your subcommands in classes for instance. """ subcmds = [] for label in dir(obj.__class__): if label.startswith("_"): continue if isinstance(getattr(obj.__class__, label, False), property): continue rvalue = getattr(obj, label) if not callable(rvalue) or not is_cmd(rvalue): continue if isinstance(obj, types.MethodType) and \ label in ("im_func", "im_self", "im_class"): continue ## potential command command_name = getattr(rvalue, "command_name", label[:-1] if label.endswith("_") else label) subcmds.append((command_name, rvalue)) return OrderedDict(subcmds)
python
def get_obj_subcmds(obj): """Fetch action in callable attributes which and commands Callable must have their attribute 'command' set to True to be recognised by this lookup. Please consider using the decorator ``@cmd`` to declare your subcommands in classes for instance. """ subcmds = [] for label in dir(obj.__class__): if label.startswith("_"): continue if isinstance(getattr(obj.__class__, label, False), property): continue rvalue = getattr(obj, label) if not callable(rvalue) or not is_cmd(rvalue): continue if isinstance(obj, types.MethodType) and \ label in ("im_func", "im_self", "im_class"): continue ## potential command command_name = getattr(rvalue, "command_name", label[:-1] if label.endswith("_") else label) subcmds.append((command_name, rvalue)) return OrderedDict(subcmds)
[ "def", "get_obj_subcmds", "(", "obj", ")", ":", "subcmds", "=", "[", "]", "for", "label", "in", "dir", "(", "obj", ".", "__class__", ")", ":", "if", "label", ".", "startswith", "(", "\"_\"", ")", ":", "continue", "if", "isinstance", "(", "getattr", "...
Fetch action in callable attributes which and commands Callable must have their attribute 'command' set to True to be recognised by this lookup. Please consider using the decorator ``@cmd`` to declare your subcommands in classes for instance.
[ "Fetch", "action", "in", "callable", "attributes", "which", "and", "commands" ]
bbe958556bc72e6579d4007a28064e2f62109bcf
https://github.com/0k/kids.cmd/blob/bbe958556bc72e6579d4007a28064e2f62109bcf/src/kids/cmd/cmd.py#L68-L95
train
54,466
0k/kids.cmd
src/kids/cmd/cmd.py
get_module_resources
def get_module_resources(mod): """Return probed sub module names from given module""" path = os.path.dirname(os.path.realpath(mod.__file__)) prefix = kf.basename(mod.__file__, (".py", ".pyc")) if not os.path.exists(mod.__file__): import pkg_resources for resource_name in pkg_resources.resource_listdir(mod.__name__, ''): if resource_name.startswith("%s_" % prefix) and resource_name.endswith(".py"): module_name, _ext = os.path.splitext(kf.basename(resource_name)) yield module_name for f in glob.glob(os.path.join(path, '%s_*.py' % prefix)): module_name, _ext = os.path.splitext(kf.basename(f)) yield module_name
python
def get_module_resources(mod): """Return probed sub module names from given module""" path = os.path.dirname(os.path.realpath(mod.__file__)) prefix = kf.basename(mod.__file__, (".py", ".pyc")) if not os.path.exists(mod.__file__): import pkg_resources for resource_name in pkg_resources.resource_listdir(mod.__name__, ''): if resource_name.startswith("%s_" % prefix) and resource_name.endswith(".py"): module_name, _ext = os.path.splitext(kf.basename(resource_name)) yield module_name for f in glob.glob(os.path.join(path, '%s_*.py' % prefix)): module_name, _ext = os.path.splitext(kf.basename(f)) yield module_name
[ "def", "get_module_resources", "(", "mod", ")", ":", "path", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "mod", ".", "__file__", ")", ")", "prefix", "=", "kf", ".", "basename", "(", "mod", ".", "__file__", ...
Return probed sub module names from given module
[ "Return", "probed", "sub", "module", "names", "from", "given", "module" ]
bbe958556bc72e6579d4007a28064e2f62109bcf
https://github.com/0k/kids.cmd/blob/bbe958556bc72e6579d4007a28064e2f62109bcf/src/kids/cmd/cmd.py#L98-L113
train
54,467
0k/kids.cmd
src/kids/cmd/cmd.py
get_mod_subcmds
def get_mod_subcmds(mod): """Fetch action in same directory in python module python module loaded are of this form: '%s_*.py' % prefix """ ## Look in modules attributes subcmds = get_obj_subcmds(mod) path = os.path.dirname(os.path.realpath(mod.__file__)) if mod.__package__ is None: sys.path.insert(0, os.path.dirname(path)) mod.__package__ = kf.basename(path) for module_name in get_module_resources(mod): try: mod = importlib.import_module(".%s" % module_name, mod.__package__) except ImportError as e: msg.warn("%r could not be loaded: %s" % (module_name, e.message)) continue except IOError as e: print("%s" % module_name) raise if hasattr(mod, "Command") and is_cmd(mod.Command): obj = mod.Command if obj.__doc__ is None: msg.warn("Missing doc string for command from " "module %s" % module_name) continue if isinstance(obj, type): obj = obj() ## instanciate it. name = module_name.split("_", 1)[1] if name in subcmds: raise ValueError( "Module command %r conflicts with already defined object " "command." % name) subcmds[name] = obj return subcmds
python
def get_mod_subcmds(mod): """Fetch action in same directory in python module python module loaded are of this form: '%s_*.py' % prefix """ ## Look in modules attributes subcmds = get_obj_subcmds(mod) path = os.path.dirname(os.path.realpath(mod.__file__)) if mod.__package__ is None: sys.path.insert(0, os.path.dirname(path)) mod.__package__ = kf.basename(path) for module_name in get_module_resources(mod): try: mod = importlib.import_module(".%s" % module_name, mod.__package__) except ImportError as e: msg.warn("%r could not be loaded: %s" % (module_name, e.message)) continue except IOError as e: print("%s" % module_name) raise if hasattr(mod, "Command") and is_cmd(mod.Command): obj = mod.Command if obj.__doc__ is None: msg.warn("Missing doc string for command from " "module %s" % module_name) continue if isinstance(obj, type): obj = obj() ## instanciate it. name = module_name.split("_", 1)[1] if name in subcmds: raise ValueError( "Module command %r conflicts with already defined object " "command." % name) subcmds[name] = obj return subcmds
[ "def", "get_mod_subcmds", "(", "mod", ")", ":", "## Look in modules attributes", "subcmds", "=", "get_obj_subcmds", "(", "mod", ")", "path", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "mod", ".", "__file__", ")", ...
Fetch action in same directory in python module python module loaded are of this form: '%s_*.py' % prefix
[ "Fetch", "action", "in", "same", "directory", "in", "python", "module" ]
bbe958556bc72e6579d4007a28064e2f62109bcf
https://github.com/0k/kids.cmd/blob/bbe958556bc72e6579d4007a28064e2f62109bcf/src/kids/cmd/cmd.py#L116-L158
train
54,468
0k/kids.cmd
src/kids/cmd/cmd.py
get_help
def get_help(obj, env, subcmds): """Interpolate complete help doc of given object Assumption that given object as a specific interface: obj.__doc__ is the basic help object. obj.get_actions_titles() returns the subcommand if any. """ doc = txt.dedent(obj.__doc__ or "") env = env.copy() ## get a local copy doc = doc.strip() if not re.search(r"^usage:\s*$", doc, flags=re.IGNORECASE | re.MULTILINE): doc += txt.dedent(""" Usage: %(std_usage)s Options: %(std_options)s""") help_line = (" %%-%ds %%s" % (max([5] + [len(a) for a in subcmds]), )) env["actions"] = "\n".join( help_line % ( name, get_help(subcmd, subcmd_env(env, name), {}).split("\n")[0]) for name, subcmd in subcmds.items()) env["actions_help"] = "" if not env["actions"] else ( "ACTION could be one of:\n\n" "%(actions)s\n\n" "See '%(surcmd)s help ACTION' for more information " "on a specific command." % env) if "%(std_usage)s" in doc: env["std_usage"] = txt.indent( ("%(surcmd)s --help\n" "%(surcmd)s --version" + (("\n%(surcmd)s help [COMMAND]" "\n%(surcmd)s ACTION [ARGS...]") if subcmds else "")) % env, _find_prefix(doc, "%(std_usage)s"), first="") if "%(std_options)s" in doc: env["std_options"] = txt.indent( "--help Show this screen.\n" "--version Show version.", _find_prefix(doc, "%(std_options)s"), first="") if subcmds and "%(actions_help)s" not in doc: doc += "\n\n%(actions_help)s" try: output = doc % env except KeyError as e: msg.err("Doc interpolation of %s needed missing key %r" % (aformat(env["surcmd"], attrs=["bold", ]), e.args[0])) exit(1) except Exception as e: msg.err( "Documentation of %s is not valid. Please check it:\n%s" % (aformat(env["surcmd"], attrs=["bold", ]), doc)) exit(1) return output
python
def get_help(obj, env, subcmds): """Interpolate complete help doc of given object Assumption that given object as a specific interface: obj.__doc__ is the basic help object. obj.get_actions_titles() returns the subcommand if any. """ doc = txt.dedent(obj.__doc__ or "") env = env.copy() ## get a local copy doc = doc.strip() if not re.search(r"^usage:\s*$", doc, flags=re.IGNORECASE | re.MULTILINE): doc += txt.dedent(""" Usage: %(std_usage)s Options: %(std_options)s""") help_line = (" %%-%ds %%s" % (max([5] + [len(a) for a in subcmds]), )) env["actions"] = "\n".join( help_line % ( name, get_help(subcmd, subcmd_env(env, name), {}).split("\n")[0]) for name, subcmd in subcmds.items()) env["actions_help"] = "" if not env["actions"] else ( "ACTION could be one of:\n\n" "%(actions)s\n\n" "See '%(surcmd)s help ACTION' for more information " "on a specific command." % env) if "%(std_usage)s" in doc: env["std_usage"] = txt.indent( ("%(surcmd)s --help\n" "%(surcmd)s --version" + (("\n%(surcmd)s help [COMMAND]" "\n%(surcmd)s ACTION [ARGS...]") if subcmds else "")) % env, _find_prefix(doc, "%(std_usage)s"), first="") if "%(std_options)s" in doc: env["std_options"] = txt.indent( "--help Show this screen.\n" "--version Show version.", _find_prefix(doc, "%(std_options)s"), first="") if subcmds and "%(actions_help)s" not in doc: doc += "\n\n%(actions_help)s" try: output = doc % env except KeyError as e: msg.err("Doc interpolation of %s needed missing key %r" % (aformat(env["surcmd"], attrs=["bold", ]), e.args[0])) exit(1) except Exception as e: msg.err( "Documentation of %s is not valid. Please check it:\n%s" % (aformat(env["surcmd"], attrs=["bold", ]), doc)) exit(1) return output
[ "def", "get_help", "(", "obj", ",", "env", ",", "subcmds", ")", ":", "doc", "=", "txt", ".", "dedent", "(", "obj", ".", "__doc__", "or", "\"\"", ")", "env", "=", "env", ".", "copy", "(", ")", "## get a local copy", "doc", "=", "doc", ".", "strip", ...
Interpolate complete help doc of given object Assumption that given object as a specific interface: obj.__doc__ is the basic help object. obj.get_actions_titles() returns the subcommand if any.
[ "Interpolate", "complete", "help", "doc", "of", "given", "object" ]
bbe958556bc72e6579d4007a28064e2f62109bcf
https://github.com/0k/kids.cmd/blob/bbe958556bc72e6579d4007a28064e2f62109bcf/src/kids/cmd/cmd.py#L195-L262
train
54,469
0k/kids.cmd
src/kids/cmd/cmd.py
get_calling_prototype
def get_calling_prototype(acallable): """Returns actual working calling prototype This means that the prototype given can be used directly in the same way by bound method, method, function, lambda:: >>> def f1(a, b, c=1): pass >>> get_calling_prototype(f1) (['a', 'b', 'c'], (1,)) >>> get_calling_prototype(lambda a, b: None) (['a', 'b'], ()) >>> get_calling_prototype(lambda a=None: None) (['a'], (None,)) >>> get_calling_prototype(lambda : None) ([], ()) >>> class A(object): ... def m1(self, a, b, c=None): pass ... @classmethod ... def cm(cls, a, b, c=None): pass ... @staticmethod ... def st(a, b, c=None): pass ... def __call__(self, a, b, c=None): pass >>> get_calling_prototype(A.m1) (['self', 'a', 'b', 'c'], (None,)) >>> A.m1(A(), 1, 2, 3) >>> get_calling_prototype(A().m1) (['a', 'b', 'c'], (None,)) >>> get_calling_prototype(A.cm) (['a', 'b', 'c'], (None,)) >>> get_calling_prototype(A().cm) (['a', 'b', 'c'], (None,)) >>> get_calling_prototype(A.st) (['a', 'b', 'c'], (None,)) >>> get_calling_prototype(A().st) (['a', 'b', 'c'], (None,)) >>> get_calling_prototype(A()) (['a', 'b', 'c'], (None,)) """ assert callable(acallable) if inspect.ismethod(acallable) or inspect.isfunction(acallable): args, vargs, vkwargs, defaults = inspect.getargspec(acallable) elif not inspect.isfunction(acallable) and hasattr(acallable, "__call__"): ## a class instance ? which is callable... args, vargs, vkwargs, defaults = inspect.getargspec(acallable.__call__) ## remove the 'self' argument args = args[1:] else: raise ValueError("Hum, %r is a callable, but not a function/method, " "nor a instance with __call__ arg..." % acallable) if vargs or vkwargs: raise SyntaxError("variable *arg or **kwarg are not supported.") if is_bound(acallable): args = args[1:] if defaults is None: defaults = () ## be coherent return args, defaults
python
def get_calling_prototype(acallable): """Returns actual working calling prototype This means that the prototype given can be used directly in the same way by bound method, method, function, lambda:: >>> def f1(a, b, c=1): pass >>> get_calling_prototype(f1) (['a', 'b', 'c'], (1,)) >>> get_calling_prototype(lambda a, b: None) (['a', 'b'], ()) >>> get_calling_prototype(lambda a=None: None) (['a'], (None,)) >>> get_calling_prototype(lambda : None) ([], ()) >>> class A(object): ... def m1(self, a, b, c=None): pass ... @classmethod ... def cm(cls, a, b, c=None): pass ... @staticmethod ... def st(a, b, c=None): pass ... def __call__(self, a, b, c=None): pass >>> get_calling_prototype(A.m1) (['self', 'a', 'b', 'c'], (None,)) >>> A.m1(A(), 1, 2, 3) >>> get_calling_prototype(A().m1) (['a', 'b', 'c'], (None,)) >>> get_calling_prototype(A.cm) (['a', 'b', 'c'], (None,)) >>> get_calling_prototype(A().cm) (['a', 'b', 'c'], (None,)) >>> get_calling_prototype(A.st) (['a', 'b', 'c'], (None,)) >>> get_calling_prototype(A().st) (['a', 'b', 'c'], (None,)) >>> get_calling_prototype(A()) (['a', 'b', 'c'], (None,)) """ assert callable(acallable) if inspect.ismethod(acallable) or inspect.isfunction(acallable): args, vargs, vkwargs, defaults = inspect.getargspec(acallable) elif not inspect.isfunction(acallable) and hasattr(acallable, "__call__"): ## a class instance ? which is callable... args, vargs, vkwargs, defaults = inspect.getargspec(acallable.__call__) ## remove the 'self' argument args = args[1:] else: raise ValueError("Hum, %r is a callable, but not a function/method, " "nor a instance with __call__ arg..." % acallable) if vargs or vkwargs: raise SyntaxError("variable *arg or **kwarg are not supported.") if is_bound(acallable): args = args[1:] if defaults is None: defaults = () ## be coherent return args, defaults
[ "def", "get_calling_prototype", "(", "acallable", ")", ":", "assert", "callable", "(", "acallable", ")", "if", "inspect", ".", "ismethod", "(", "acallable", ")", "or", "inspect", ".", "isfunction", "(", "acallable", ")", ":", "args", ",", "vargs", ",", "vk...
Returns actual working calling prototype This means that the prototype given can be used directly in the same way by bound method, method, function, lambda:: >>> def f1(a, b, c=1): pass >>> get_calling_prototype(f1) (['a', 'b', 'c'], (1,)) >>> get_calling_prototype(lambda a, b: None) (['a', 'b'], ()) >>> get_calling_prototype(lambda a=None: None) (['a'], (None,)) >>> get_calling_prototype(lambda : None) ([], ()) >>> class A(object): ... def m1(self, a, b, c=None): pass ... @classmethod ... def cm(cls, a, b, c=None): pass ... @staticmethod ... def st(a, b, c=None): pass ... def __call__(self, a, b, c=None): pass >>> get_calling_prototype(A.m1) (['self', 'a', 'b', 'c'], (None,)) >>> A.m1(A(), 1, 2, 3) >>> get_calling_prototype(A().m1) (['a', 'b', 'c'], (None,)) >>> get_calling_prototype(A.cm) (['a', 'b', 'c'], (None,)) >>> get_calling_prototype(A().cm) (['a', 'b', 'c'], (None,)) >>> get_calling_prototype(A.st) (['a', 'b', 'c'], (None,)) >>> get_calling_prototype(A().st) (['a', 'b', 'c'], (None,)) >>> get_calling_prototype(A()) (['a', 'b', 'c'], (None,))
[ "Returns", "actual", "working", "calling", "prototype" ]
bbe958556bc72e6579d4007a28064e2f62109bcf
https://github.com/0k/kids.cmd/blob/bbe958556bc72e6579d4007a28064e2f62109bcf/src/kids/cmd/cmd.py#L305-L369
train
54,470
toumorokoshi/sprinter
sprinter/core/directory.py
Directory.initialize
def initialize(self): """ Generate the root directory root if it doesn't already exist """ if not os.path.exists(self.root_dir): os.makedirs(self.root_dir) assert os.path.isdir(self.root_dir), "%s is not a directory! Please move or remove it." % self.root_dir for d in ["bin", "lib", "include"]: target_path = os.path.join(self.root_dir, d) if not os.path.exists(target_path): os.makedirs(target_path) if not os.path.exists(self.manifest_path): open(self.manifest_path, "w+").close() self.new = False
python
def initialize(self): """ Generate the root directory root if it doesn't already exist """ if not os.path.exists(self.root_dir): os.makedirs(self.root_dir) assert os.path.isdir(self.root_dir), "%s is not a directory! Please move or remove it." % self.root_dir for d in ["bin", "lib", "include"]: target_path = os.path.join(self.root_dir, d) if not os.path.exists(target_path): os.makedirs(target_path) if not os.path.exists(self.manifest_path): open(self.manifest_path, "w+").close() self.new = False
[ "def", "initialize", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "root_dir", ")", ":", "os", ".", "makedirs", "(", "self", ".", "root_dir", ")", "assert", "os", ".", "path", ".", "isdir", "(", "self", "...
Generate the root directory root if it doesn't already exist
[ "Generate", "the", "root", "directory", "root", "if", "it", "doesn", "t", "already", "exist" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/directory.py#L50-L61
train
54,471
toumorokoshi/sprinter
sprinter/core/directory.py
Directory.finalize
def finalize(self): """ finalize any open file handles """ if self.rc_file: self.rc_file.close() if self.env_file: self.env_file.close()
python
def finalize(self): """ finalize any open file handles """ if self.rc_file: self.rc_file.close() if self.env_file: self.env_file.close()
[ "def", "finalize", "(", "self", ")", ":", "if", "self", ".", "rc_file", ":", "self", ".", "rc_file", ".", "close", "(", ")", "if", "self", ".", "env_file", ":", "self", ".", "env_file", ".", "close", "(", ")" ]
finalize any open file handles
[ "finalize", "any", "open", "file", "handles" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/directory.py#L63-L68
train
54,472
toumorokoshi/sprinter
sprinter/core/directory.py
Directory.remove
def remove(self): """ Removes the sprinter directory, if it exists """ if self.rc_file: self.rc_file.close() if self.env_file: self.env_file.close() shutil.rmtree(self.root_dir)
python
def remove(self): """ Removes the sprinter directory, if it exists """ if self.rc_file: self.rc_file.close() if self.env_file: self.env_file.close() shutil.rmtree(self.root_dir)
[ "def", "remove", "(", "self", ")", ":", "if", "self", ".", "rc_file", ":", "self", ".", "rc_file", ".", "close", "(", ")", "if", "self", ".", "env_file", ":", "self", ".", "env_file", ".", "close", "(", ")", "shutil", ".", "rmtree", "(", "self", ...
Removes the sprinter directory, if it exists
[ "Removes", "the", "sprinter", "directory", "if", "it", "exists" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/directory.py#L70-L76
train
54,473
toumorokoshi/sprinter
sprinter/core/directory.py
Directory.symlink_to_bin
def symlink_to_bin(self, name, path): """ Symlink an object at path to name in the bin folder. """ self.__symlink_dir("bin", name, path) os.chmod(os.path.join(self.root_dir, "bin", name), os.stat(path).st_mode | stat.S_IXUSR | stat.S_IRUSR)
python
def symlink_to_bin(self, name, path): """ Symlink an object at path to name in the bin folder. """ self.__symlink_dir("bin", name, path) os.chmod(os.path.join(self.root_dir, "bin", name), os.stat(path).st_mode | stat.S_IXUSR | stat.S_IRUSR)
[ "def", "symlink_to_bin", "(", "self", ",", "name", ",", "path", ")", ":", "self", ".", "__symlink_dir", "(", "\"bin\"", ",", "name", ",", "path", ")", "os", ".", "chmod", "(", "os", ".", "path", ".", "join", "(", "self", ".", "root_dir", ",", "\"bi...
Symlink an object at path to name in the bin folder.
[ "Symlink", "an", "object", "at", "path", "to", "name", "in", "the", "bin", "folder", "." ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/directory.py#L78-L81
train
54,474
toumorokoshi/sprinter
sprinter/core/directory.py
Directory.remove_feature
def remove_feature(self, feature_name): """ Remove an feature from the environment root folder. """ self.clear_feature_symlinks(feature_name) if os.path.exists(self.install_directory(feature_name)): self.__remove_path(self.install_directory(feature_name))
python
def remove_feature(self, feature_name): """ Remove an feature from the environment root folder. """ self.clear_feature_symlinks(feature_name) if os.path.exists(self.install_directory(feature_name)): self.__remove_path(self.install_directory(feature_name))
[ "def", "remove_feature", "(", "self", ",", "feature_name", ")", ":", "self", ".", "clear_feature_symlinks", "(", "feature_name", ")", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "install_directory", "(", "feature_name", ")", ")", ":", "self", ...
Remove an feature from the environment root folder.
[ "Remove", "an", "feature", "from", "the", "environment", "root", "folder", "." ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/directory.py#L91-L95
train
54,475
toumorokoshi/sprinter
sprinter/core/directory.py
Directory.clear_feature_symlinks
def clear_feature_symlinks(self, feature_name): """ Clear the symlinks for a feature in the symlinked path """ logger.debug("Clearing feature symlinks for %s" % feature_name) feature_path = self.install_directory(feature_name) for d in ('bin', 'lib'): if os.path.exists(os.path.join(self.root_dir, d)): for link in os.listdir(os.path.join(self.root_dir, d)): path = os.path.join(self.root_dir, d, link) if feature_path in os.path.realpath(path): getattr(self, 'remove_from_%s' % d)(link)
python
def clear_feature_symlinks(self, feature_name): """ Clear the symlinks for a feature in the symlinked path """ logger.debug("Clearing feature symlinks for %s" % feature_name) feature_path = self.install_directory(feature_name) for d in ('bin', 'lib'): if os.path.exists(os.path.join(self.root_dir, d)): for link in os.listdir(os.path.join(self.root_dir, d)): path = os.path.join(self.root_dir, d, link) if feature_path in os.path.realpath(path): getattr(self, 'remove_from_%s' % d)(link)
[ "def", "clear_feature_symlinks", "(", "self", ",", "feature_name", ")", ":", "logger", ".", "debug", "(", "\"Clearing feature symlinks for %s\"", "%", "feature_name", ")", "feature_path", "=", "self", ".", "install_directory", "(", "feature_name", ")", "for", "d", ...
Clear the symlinks for a feature in the symlinked path
[ "Clear", "the", "symlinks", "for", "a", "feature", "in", "the", "symlinked", "path" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/directory.py#L117-L126
train
54,476
toumorokoshi/sprinter
sprinter/core/directory.py
Directory.add_to_env
def add_to_env(self, content): """ add content to the env script. """ if not self.rewrite_config: raise DirectoryException("Error! Directory was not intialized w/ rewrite_config.") if not self.env_file: self.env_path, self.env_file = self.__get_env_handle(self.root_dir) self.env_file.write(content + '\n')
python
def add_to_env(self, content): """ add content to the env script. """ if not self.rewrite_config: raise DirectoryException("Error! Directory was not intialized w/ rewrite_config.") if not self.env_file: self.env_path, self.env_file = self.__get_env_handle(self.root_dir) self.env_file.write(content + '\n')
[ "def", "add_to_env", "(", "self", ",", "content", ")", ":", "if", "not", "self", ".", "rewrite_config", ":", "raise", "DirectoryException", "(", "\"Error! Directory was not intialized w/ rewrite_config.\"", ")", "if", "not", "self", ".", "env_file", ":", "self", "...
add content to the env script.
[ "add", "content", "to", "the", "env", "script", "." ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/directory.py#L134-L142
train
54,477
toumorokoshi/sprinter
sprinter/core/directory.py
Directory.add_to_rc
def add_to_rc(self, content): """ add content to the rc script. """ if not self.rewrite_config: raise DirectoryException("Error! Directory was not intialized w/ rewrite_config.") if not self.rc_file: self.rc_path, self.rc_file = self.__get_rc_handle(self.root_dir) self.rc_file.write(content + '\n')
python
def add_to_rc(self, content): """ add content to the rc script. """ if not self.rewrite_config: raise DirectoryException("Error! Directory was not intialized w/ rewrite_config.") if not self.rc_file: self.rc_path, self.rc_file = self.__get_rc_handle(self.root_dir) self.rc_file.write(content + '\n')
[ "def", "add_to_rc", "(", "self", ",", "content", ")", ":", "if", "not", "self", ".", "rewrite_config", ":", "raise", "DirectoryException", "(", "\"Error! Directory was not intialized w/ rewrite_config.\"", ")", "if", "not", "self", ".", "rc_file", ":", "self", "."...
add content to the rc script.
[ "add", "content", "to", "the", "rc", "script", "." ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/directory.py#L144-L152
train
54,478
toumorokoshi/sprinter
sprinter/core/directory.py
Directory.add_to_gui
def add_to_gui(self, content): """ add content to the gui script. """ if not self.rewrite_config: raise DirectoryException("Error! Directory was not intialized w/ rewrite_config.") if not self.gui_file: self.gui_path, self.gui_file = self.__get_gui_handle(self.root_dir) self.gui_file.write(content + '\n')
python
def add_to_gui(self, content): """ add content to the gui script. """ if not self.rewrite_config: raise DirectoryException("Error! Directory was not intialized w/ rewrite_config.") if not self.gui_file: self.gui_path, self.gui_file = self.__get_gui_handle(self.root_dir) self.gui_file.write(content + '\n')
[ "def", "add_to_gui", "(", "self", ",", "content", ")", ":", "if", "not", "self", ".", "rewrite_config", ":", "raise", "DirectoryException", "(", "\"Error! Directory was not intialized w/ rewrite_config.\"", ")", "if", "not", "self", ".", "gui_file", ":", "self", "...
add content to the gui script.
[ "add", "content", "to", "the", "gui", "script", "." ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/directory.py#L154-L162
train
54,479
toumorokoshi/sprinter
sprinter/core/directory.py
Directory.__remove_path
def __remove_path(self, path): """ Remove an object """ curpath = os.path.abspath(os.curdir) if not os.path.exists(path): logger.warn("Attempted to remove a non-existent path %s" % path) return try: if os.path.islink(path): os.unlink(path) elif os.path.isdir(path): shutil.rmtree(path) else: os.unlink(path) # in the case we just deleted ourselves out of a valid directory, # we move to a valid directory. if curpath == path: os.chdir(tempfile.gettempdir()) except OSError: logger.error("Unable to remove object at path %s" % path) raise DirectoryException("Unable to remove object at path %s" % path)
python
def __remove_path(self, path): """ Remove an object """ curpath = os.path.abspath(os.curdir) if not os.path.exists(path): logger.warn("Attempted to remove a non-existent path %s" % path) return try: if os.path.islink(path): os.unlink(path) elif os.path.isdir(path): shutil.rmtree(path) else: os.unlink(path) # in the case we just deleted ourselves out of a valid directory, # we move to a valid directory. if curpath == path: os.chdir(tempfile.gettempdir()) except OSError: logger.error("Unable to remove object at path %s" % path) raise DirectoryException("Unable to remove object at path %s" % path)
[ "def", "__remove_path", "(", "self", ",", "path", ")", ":", "curpath", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "curdir", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "logger", ".", "warn", "(", "\"Att...
Remove an object
[ "Remove", "an", "object" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/directory.py#L164-L185
train
54,480
toumorokoshi/sprinter
sprinter/core/directory.py
Directory.__get_rc_handle
def __get_rc_handle(self, root_dir): """ get the filepath and filehandle to the rc file for the environment """ rc_path = os.path.join(root_dir, '.rc') env_path = os.path.join(root_dir, '.env') fh = open(rc_path, "w+") # .rc will always source .env fh.write(source_template % (env_path, env_path)) return (rc_path, fh)
python
def __get_rc_handle(self, root_dir): """ get the filepath and filehandle to the rc file for the environment """ rc_path = os.path.join(root_dir, '.rc') env_path = os.path.join(root_dir, '.env') fh = open(rc_path, "w+") # .rc will always source .env fh.write(source_template % (env_path, env_path)) return (rc_path, fh)
[ "def", "__get_rc_handle", "(", "self", ",", "root_dir", ")", ":", "rc_path", "=", "os", ".", "path", ".", "join", "(", "root_dir", ",", "'.rc'", ")", "env_path", "=", "os", ".", "path", ".", "join", "(", "root_dir", ",", "'.env'", ")", "fh", "=", "...
get the filepath and filehandle to the rc file for the environment
[ "get", "the", "filepath", "and", "filehandle", "to", "the", "rc", "file", "for", "the", "environment" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/directory.py#L198-L205
train
54,481
toumorokoshi/sprinter
sprinter/core/directory.py
Directory.__symlink_dir
def __symlink_dir(self, dir_name, name, path): """ Symlink an object at path to name in the dir_name folder. remove it if it already exists. """ target_dir = os.path.join(self.root_dir, dir_name) if not os.path.exists(target_dir): os.makedirs(target_dir) target_path = os.path.join(self.root_dir, dir_name, name) logger.debug("Attempting to symlink %s to %s..." % (path, target_path)) if os.path.exists(target_path): if os.path.islink(target_path): os.remove(target_path) else: logger.warn("%s is not a symlink! please remove it manually." % target_path) return os.symlink(path, target_path)
python
def __symlink_dir(self, dir_name, name, path): """ Symlink an object at path to name in the dir_name folder. remove it if it already exists. """ target_dir = os.path.join(self.root_dir, dir_name) if not os.path.exists(target_dir): os.makedirs(target_dir) target_path = os.path.join(self.root_dir, dir_name, name) logger.debug("Attempting to symlink %s to %s..." % (path, target_path)) if os.path.exists(target_path): if os.path.islink(target_path): os.remove(target_path) else: logger.warn("%s is not a symlink! please remove it manually." % target_path) return os.symlink(path, target_path)
[ "def", "__symlink_dir", "(", "self", ",", "dir_name", ",", "name", ",", "path", ")", ":", "target_dir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "root_dir", ",", "dir_name", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "ta...
Symlink an object at path to name in the dir_name folder. remove it if it already exists.
[ "Symlink", "an", "object", "at", "path", "to", "name", "in", "the", "dir_name", "folder", ".", "remove", "it", "if", "it", "already", "exists", "." ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/directory.py#L213-L228
train
54,482
jkeyes/python-docraptor
docraptor/__init__.py
DocRaptor.list_docs
def list_docs(self, options=None): """Return list of previously created documents.""" if options is None: raise ValueError("Please pass in an options dict") default_options = { "page": 1, "per_page": 100, "raise_exception_on_failure": False, "user_credentials": self.api_key, } options = dict(list(default_options.items()) + list(options.items())) raise_exception_on_failure = options.pop("raise_exception_on_failure") resp = requests.get( "%sdocs" % (self._url), params=options, timeout=self._timeout ) if raise_exception_on_failure and resp.status_code != 200: raise DocumentListingFailure(resp.content, resp.status_code) return resp
python
def list_docs(self, options=None): """Return list of previously created documents.""" if options is None: raise ValueError("Please pass in an options dict") default_options = { "page": 1, "per_page": 100, "raise_exception_on_failure": False, "user_credentials": self.api_key, } options = dict(list(default_options.items()) + list(options.items())) raise_exception_on_failure = options.pop("raise_exception_on_failure") resp = requests.get( "%sdocs" % (self._url), params=options, timeout=self._timeout ) if raise_exception_on_failure and resp.status_code != 200: raise DocumentListingFailure(resp.content, resp.status_code) return resp
[ "def", "list_docs", "(", "self", ",", "options", "=", "None", ")", ":", "if", "options", "is", "None", ":", "raise", "ValueError", "(", "\"Please pass in an options dict\"", ")", "default_options", "=", "{", "\"page\"", ":", "1", ",", "\"per_page\"", ":", "1...
Return list of previously created documents.
[ "Return", "list", "of", "previously", "created", "documents", "." ]
4be5b641f92820539b2c42165fec9251a6603dea
https://github.com/jkeyes/python-docraptor/blob/4be5b641f92820539b2c42165fec9251a6603dea/docraptor/__init__.py#L102-L122
train
54,483
jkeyes/python-docraptor
docraptor/__init__.py
DocRaptor.status
def status(self, status_id, raise_exception_on_failure=False): """Return the status of the generation job.""" query = {"output": "json", "user_credentials": self.api_key} resp = requests.get( "%sstatus/%s" % (self._url, status_id), params=query, timeout=self._timeout ) if raise_exception_on_failure and resp.status_code != 200: raise DocumentStatusFailure(resp.content, resp.status_code) if resp.status_code == 200: as_json = json.loads(resp.content) if as_json["status"] == "completed": as_json["download_key"] = _get_download_key(as_json["download_url"]) return as_json return resp
python
def status(self, status_id, raise_exception_on_failure=False): """Return the status of the generation job.""" query = {"output": "json", "user_credentials": self.api_key} resp = requests.get( "%sstatus/%s" % (self._url, status_id), params=query, timeout=self._timeout ) if raise_exception_on_failure and resp.status_code != 200: raise DocumentStatusFailure(resp.content, resp.status_code) if resp.status_code == 200: as_json = json.loads(resp.content) if as_json["status"] == "completed": as_json["download_key"] = _get_download_key(as_json["download_url"]) return as_json return resp
[ "def", "status", "(", "self", ",", "status_id", ",", "raise_exception_on_failure", "=", "False", ")", ":", "query", "=", "{", "\"output\"", ":", "\"json\"", ",", "\"user_credentials\"", ":", "self", ".", "api_key", "}", "resp", "=", "requests", ".", "get", ...
Return the status of the generation job.
[ "Return", "the", "status", "of", "the", "generation", "job", "." ]
4be5b641f92820539b2c42165fec9251a6603dea
https://github.com/jkeyes/python-docraptor/blob/4be5b641f92820539b2c42165fec9251a6603dea/docraptor/__init__.py#L124-L140
train
54,484
jkeyes/python-docraptor
docraptor/__init__.py
DocRaptor.download
def download(self, download_key, raise_exception_on_failure=False): """Download the file represented by the download_key.""" query = {"output": "json", "user_credentials": self.api_key} resp = requests.get( "%sdownload/%s" % (self._url, download_key), params=query, timeout=self._timeout, ) if raise_exception_on_failure and resp.status_code != 200: raise DocumentDownloadFailure(resp.content, resp.status_code) return resp
python
def download(self, download_key, raise_exception_on_failure=False): """Download the file represented by the download_key.""" query = {"output": "json", "user_credentials": self.api_key} resp = requests.get( "%sdownload/%s" % (self._url, download_key), params=query, timeout=self._timeout, ) if raise_exception_on_failure and resp.status_code != 200: raise DocumentDownloadFailure(resp.content, resp.status_code) return resp
[ "def", "download", "(", "self", ",", "download_key", ",", "raise_exception_on_failure", "=", "False", ")", ":", "query", "=", "{", "\"output\"", ":", "\"json\"", ",", "\"user_credentials\"", ":", "self", ".", "api_key", "}", "resp", "=", "requests", ".", "ge...
Download the file represented by the download_key.
[ "Download", "the", "file", "represented", "by", "the", "download_key", "." ]
4be5b641f92820539b2c42165fec9251a6603dea
https://github.com/jkeyes/python-docraptor/blob/4be5b641f92820539b2c42165fec9251a6603dea/docraptor/__init__.py#L142-L153
train
54,485
smarie/python-parsyfiles
parsyfiles/plugins_base/support_for_collections.py
MultifileCollectionParser._get_parsing_plan_for_multifile_children
def _get_parsing_plan_for_multifile_children(self, obj_on_fs: PersistedObject, desired_type: Type[Any], logger: Logger) -> Dict[str, Any]: """ Simply inspects the required type to find the base type expected for items of the collection, and relies on the ParserFinder to find the parsing plan :param obj_on_fs: :param desired_type: :param logger: :return: """ # nb of file children n_children = len(obj_on_fs.get_multifile_children()) # first extract base collection type subtypes, key_type = _extract_collection_base_type(desired_type) if isinstance(subtypes, tuple): # -- check the tuple length if n_children != len(subtypes): raise FolderAndFilesStructureError.create_for_multifile_tuple(obj_on_fs, len(subtypes), len(obj_on_fs.get_multifile_children())) else: # -- repeat the subtype n times subtypes = [subtypes] * n_children # -- for each child create a plan with the appropriate parser children_plan = OrderedDict() # use sorting for reproducible results in case of multiple errors for (child_name, child_fileobject), child_typ in zip(sorted(obj_on_fs.get_multifile_children().items()), subtypes): # -- use the parserfinder to find the plan t, child_parser = self.parser_finder.build_parser_for_fileobject_and_desiredtype(child_fileobject, child_typ, logger) children_plan[child_name] = child_parser.create_parsing_plan(t, child_fileobject, logger, _main_call=False) return children_plan
python
def _get_parsing_plan_for_multifile_children(self, obj_on_fs: PersistedObject, desired_type: Type[Any], logger: Logger) -> Dict[str, Any]: """ Simply inspects the required type to find the base type expected for items of the collection, and relies on the ParserFinder to find the parsing plan :param obj_on_fs: :param desired_type: :param logger: :return: """ # nb of file children n_children = len(obj_on_fs.get_multifile_children()) # first extract base collection type subtypes, key_type = _extract_collection_base_type(desired_type) if isinstance(subtypes, tuple): # -- check the tuple length if n_children != len(subtypes): raise FolderAndFilesStructureError.create_for_multifile_tuple(obj_on_fs, len(subtypes), len(obj_on_fs.get_multifile_children())) else: # -- repeat the subtype n times subtypes = [subtypes] * n_children # -- for each child create a plan with the appropriate parser children_plan = OrderedDict() # use sorting for reproducible results in case of multiple errors for (child_name, child_fileobject), child_typ in zip(sorted(obj_on_fs.get_multifile_children().items()), subtypes): # -- use the parserfinder to find the plan t, child_parser = self.parser_finder.build_parser_for_fileobject_and_desiredtype(child_fileobject, child_typ, logger) children_plan[child_name] = child_parser.create_parsing_plan(t, child_fileobject, logger, _main_call=False) return children_plan
[ "def", "_get_parsing_plan_for_multifile_children", "(", "self", ",", "obj_on_fs", ":", "PersistedObject", ",", "desired_type", ":", "Type", "[", "Any", "]", ",", "logger", ":", "Logger", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "# nb of file childr...
Simply inspects the required type to find the base type expected for items of the collection, and relies on the ParserFinder to find the parsing plan :param obj_on_fs: :param desired_type: :param logger: :return:
[ "Simply", "inspects", "the", "required", "type", "to", "find", "the", "base", "type", "expected", "for", "items", "of", "the", "collection", "and", "relies", "on", "the", "ParserFinder", "to", "find", "the", "parsing", "plan" ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/plugins_base/support_for_collections.py#L269-L306
train
54,486
wheeler-microfluidics/dmf-control-board-firmware
dmf_control_board_firmware/calibrate/impedance_benchmarks.py
plot_stat_summary
def plot_stat_summary(df, fig=None): ''' Plot stats grouped by test capacitor load _and_ frequency. In other words, we calculate the mean of all samples in the data frame for each test capacitance and frequency pairing, plotting the following stats: - Root mean squared error - Coefficient of variation - Bias ## [Coefficient of variation][1] ## > In probability theory and statistics, the coefficient of > variation (CV) is a normalized measure of dispersion of a > probability distribution or frequency distribution. It is defined > as the ratio of the standard deviation to the mean. [1]: http://en.wikipedia.org/wiki/Coefficient_of_variation ''' if fig is None: fig = plt.figure(figsize=(8, 8)) # Define a subplot layout, 3 rows, 2 columns grid = GridSpec(3, 2) stats = calculate_stats(df, groupby=['test_capacitor', 'frequency']).dropna() for i, stat in enumerate(['RMSE %', 'cv %', 'bias %']): axis = fig.add_subplot(grid[i, 0]) axis.set_title(stat) # Plot a colormap to show how the statistical value changes # according to frequency/capacitance pairs. plot_colormap(stats, stat, axis=axis, fig=fig) axis = fig.add_subplot(grid[i, 1]) axis.set_title(stat) # Plot a histogram to show the distribution of statistical # values across all frequency/capacitance pairs. try: axis.hist(stats[stat].values, bins=50) except AttributeError: print stats[stat].describe() fig.tight_layout()
python
def plot_stat_summary(df, fig=None): ''' Plot stats grouped by test capacitor load _and_ frequency. In other words, we calculate the mean of all samples in the data frame for each test capacitance and frequency pairing, plotting the following stats: - Root mean squared error - Coefficient of variation - Bias ## [Coefficient of variation][1] ## > In probability theory and statistics, the coefficient of > variation (CV) is a normalized measure of dispersion of a > probability distribution or frequency distribution. It is defined > as the ratio of the standard deviation to the mean. [1]: http://en.wikipedia.org/wiki/Coefficient_of_variation ''' if fig is None: fig = plt.figure(figsize=(8, 8)) # Define a subplot layout, 3 rows, 2 columns grid = GridSpec(3, 2) stats = calculate_stats(df, groupby=['test_capacitor', 'frequency']).dropna() for i, stat in enumerate(['RMSE %', 'cv %', 'bias %']): axis = fig.add_subplot(grid[i, 0]) axis.set_title(stat) # Plot a colormap to show how the statistical value changes # according to frequency/capacitance pairs. plot_colormap(stats, stat, axis=axis, fig=fig) axis = fig.add_subplot(grid[i, 1]) axis.set_title(stat) # Plot a histogram to show the distribution of statistical # values across all frequency/capacitance pairs. try: axis.hist(stats[stat].values, bins=50) except AttributeError: print stats[stat].describe() fig.tight_layout()
[ "def", "plot_stat_summary", "(", "df", ",", "fig", "=", "None", ")", ":", "if", "fig", "is", "None", ":", "fig", "=", "plt", ".", "figure", "(", "figsize", "=", "(", "8", ",", "8", ")", ")", "# Define a subplot layout, 3 rows, 2 columns", "grid", "=", ...
Plot stats grouped by test capacitor load _and_ frequency. In other words, we calculate the mean of all samples in the data frame for each test capacitance and frequency pairing, plotting the following stats: - Root mean squared error - Coefficient of variation - Bias ## [Coefficient of variation][1] ## > In probability theory and statistics, the coefficient of > variation (CV) is a normalized measure of dispersion of a > probability distribution or frequency distribution. It is defined > as the ratio of the standard deviation to the mean. [1]: http://en.wikipedia.org/wiki/Coefficient_of_variation
[ "Plot", "stats", "grouped", "by", "test", "capacitor", "load", "_and_", "frequency", "." ]
1cd8cc9a148d530f9a11f634f2dbfe73f08aa27c
https://github.com/wheeler-microfluidics/dmf-control-board-firmware/blob/1cd8cc9a148d530f9a11f634f2dbfe73f08aa27c/dmf_control_board_firmware/calibrate/impedance_benchmarks.py#L207-L250
train
54,487
toumorokoshi/sprinter
sprinter/core/manifest.py
load_manifest
def load_manifest(raw_manifest, namespace=None, **kwargs): """ wrapper method which generates the manifest from various sources """ if isinstance(raw_manifest, configparser.RawConfigParser): return Manifest(raw_manifest) manifest = create_configparser() if not manifest.has_section('config'): manifest.add_section('config') _load_manifest_interpret_source(manifest, raw_manifest, **kwargs) return Manifest(manifest, namespace=namespace)
python
def load_manifest(raw_manifest, namespace=None, **kwargs): """ wrapper method which generates the manifest from various sources """ if isinstance(raw_manifest, configparser.RawConfigParser): return Manifest(raw_manifest) manifest = create_configparser() if not manifest.has_section('config'): manifest.add_section('config') _load_manifest_interpret_source(manifest, raw_manifest, **kwargs) return Manifest(manifest, namespace=namespace)
[ "def", "load_manifest", "(", "raw_manifest", ",", "namespace", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "raw_manifest", ",", "configparser", ".", "RawConfigParser", ")", ":", "return", "Manifest", "(", "raw_manifest", ")", "ma...
wrapper method which generates the manifest from various sources
[ "wrapper", "method", "which", "generates", "the", "manifest", "from", "various", "sources" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/manifest.py#L36-L49
train
54,488
toumorokoshi/sprinter
sprinter/core/manifest.py
_load_manifest_from_url
def _load_manifest_from_url(manifest, url, verify_certificate=True, username=None, password=None): """ load a url body into a manifest """ try: if username and password: manifest_file_handler = StringIO(lib.authenticated_get(username, password, url, verify=verify_certificate).decode("utf-8")) else: manifest_file_handler = StringIO(lib.cleaned_request( 'get', url, verify=verify_certificate ).text) manifest.readfp(manifest_file_handler) except requests.exceptions.RequestException: logger.debug("", exc_info=True) error_message = sys.exc_info()[1] raise ManifestException("There was an error retrieving {0}!\n {1}".format(url, str(error_message)))
python
def _load_manifest_from_url(manifest, url, verify_certificate=True, username=None, password=None): """ load a url body into a manifest """ try: if username and password: manifest_file_handler = StringIO(lib.authenticated_get(username, password, url, verify=verify_certificate).decode("utf-8")) else: manifest_file_handler = StringIO(lib.cleaned_request( 'get', url, verify=verify_certificate ).text) manifest.readfp(manifest_file_handler) except requests.exceptions.RequestException: logger.debug("", exc_info=True) error_message = sys.exc_info()[1] raise ManifestException("There was an error retrieving {0}!\n {1}".format(url, str(error_message)))
[ "def", "_load_manifest_from_url", "(", "manifest", ",", "url", ",", "verify_certificate", "=", "True", ",", "username", "=", "None", ",", "password", "=", "None", ")", ":", "try", ":", "if", "username", "and", "password", ":", "manifest_file_handler", "=", "...
load a url body into a manifest
[ "load", "a", "url", "body", "into", "a", "manifest" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/manifest.py#L86-L100
train
54,489
toumorokoshi/sprinter
sprinter/core/manifest.py
_load_manifest_from_file
def _load_manifest_from_file(manifest, path): """ load manifest from file """ path = os.path.abspath(os.path.expanduser(path)) if not os.path.exists(path): raise ManifestException("Manifest does not exist at {0}!".format(path)) manifest.read(path) if not manifest.has_option('config', 'source'): manifest.set('config', 'source', str(path))
python
def _load_manifest_from_file(manifest, path): """ load manifest from file """ path = os.path.abspath(os.path.expanduser(path)) if not os.path.exists(path): raise ManifestException("Manifest does not exist at {0}!".format(path)) manifest.read(path) if not manifest.has_option('config', 'source'): manifest.set('config', 'source', str(path))
[ "def", "_load_manifest_from_file", "(", "manifest", ",", "path", ")", ":", "path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "path", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ...
load manifest from file
[ "load", "manifest", "from", "file" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/manifest.py#L103-L110
train
54,490
toumorokoshi/sprinter
sprinter/core/manifest.py
Manifest.formula_sections
def formula_sections(self): """ Return all sections related to a formula, re-ordered according to the "depends" section. """ if self.dtree is not None: return self.dtree.order else: return [s for s in self.manifest.sections() if s != "config"]
python
def formula_sections(self): """ Return all sections related to a formula, re-ordered according to the "depends" section. """ if self.dtree is not None: return self.dtree.order else: return [s for s in self.manifest.sections() if s != "config"]
[ "def", "formula_sections", "(", "self", ")", ":", "if", "self", ".", "dtree", "is", "not", "None", ":", "return", "self", ".", "dtree", ".", "order", "else", ":", "return", "[", "s", "for", "s", "in", "self", ".", "manifest", ".", "sections", "(", ...
Return all sections related to a formula, re-ordered according to the "depends" section.
[ "Return", "all", "sections", "related", "to", "a", "formula", "re", "-", "ordered", "according", "to", "the", "depends", "section", "." ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/manifest.py#L149-L156
train
54,491
toumorokoshi/sprinter
sprinter/core/manifest.py
Manifest.is_affirmative
def is_affirmative(self, section, option): """ Return true if the section option combo exists and it is set to a truthy value. """ return self.has_option(section, option) and \ lib.is_affirmative(self.get(section, option))
python
def is_affirmative(self, section, option): """ Return true if the section option combo exists and it is set to a truthy value. """ return self.has_option(section, option) and \ lib.is_affirmative(self.get(section, option))
[ "def", "is_affirmative", "(", "self", ",", "section", ",", "option", ")", ":", "return", "self", ".", "has_option", "(", "section", ",", "option", ")", "and", "lib", ".", "is_affirmative", "(", "self", ".", "get", "(", "section", ",", "option", ")", ")...
Return true if the section option combo exists and it is set to a truthy value.
[ "Return", "true", "if", "the", "section", "option", "combo", "exists", "and", "it", "is", "set", "to", "a", "truthy", "value", "." ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/manifest.py#L169-L175
train
54,492
toumorokoshi/sprinter
sprinter/core/manifest.py
Manifest.write
def write(self, file_handle): """ write the current state to a file manifest """ for k, v in self.inputs.write_values().items(): self.set('config', k, v) self.set('config', 'namespace', self.namespace) self.manifest.write(file_handle)
python
def write(self, file_handle): """ write the current state to a file manifest """ for k, v in self.inputs.write_values().items(): self.set('config', k, v) self.set('config', 'namespace', self.namespace) self.manifest.write(file_handle)
[ "def", "write", "(", "self", ",", "file_handle", ")", ":", "for", "k", ",", "v", "in", "self", ".", "inputs", ".", "write_values", "(", ")", ".", "items", "(", ")", ":", "self", ".", "set", "(", "'config'", ",", "k", ",", "v", ")", "self", ".",...
write the current state to a file manifest
[ "write", "the", "current", "state", "to", "a", "file", "manifest" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/manifest.py#L182-L187
train
54,493
toumorokoshi/sprinter
sprinter/core/manifest.py
Manifest.get_context_dict
def get_context_dict(self): """ return a context dict of the desired state """ context_dict = {} for s in self.sections(): for k, v in self.manifest.items(s): context_dict["%s:%s" % (s, k)] = v for k, v in self.inputs.values().items(): context_dict["config:{0}".format(k)] = v context_dict.update(self.additional_context_variables.items()) context_dict.update(dict([("%s|escaped" % k, re.escape(str(v) or "")) for k, v in context_dict.items()])) return context_dict
python
def get_context_dict(self): """ return a context dict of the desired state """ context_dict = {} for s in self.sections(): for k, v in self.manifest.items(s): context_dict["%s:%s" % (s, k)] = v for k, v in self.inputs.values().items(): context_dict["config:{0}".format(k)] = v context_dict.update(self.additional_context_variables.items()) context_dict.update(dict([("%s|escaped" % k, re.escape(str(v) or "")) for k, v in context_dict.items()])) return context_dict
[ "def", "get_context_dict", "(", "self", ")", ":", "context_dict", "=", "{", "}", "for", "s", "in", "self", ".", "sections", "(", ")", ":", "for", "k", ",", "v", "in", "self", ".", "manifest", ".", "items", "(", "s", ")", ":", "context_dict", "[", ...
return a context dict of the desired state
[ "return", "a", "context", "dict", "of", "the", "desired", "state" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/manifest.py#L196-L206
train
54,494
toumorokoshi/sprinter
sprinter/core/manifest.py
Manifest.get
def get(self, section, key, default=MANIFEST_NULL_KEY): """ Returns the value if it exist, or default if default is set """ if not self.manifest.has_option(section, key) and default is not MANIFEST_NULL_KEY: return default return self.manifest.get(section, key)
python
def get(self, section, key, default=MANIFEST_NULL_KEY): """ Returns the value if it exist, or default if default is set """ if not self.manifest.has_option(section, key) and default is not MANIFEST_NULL_KEY: return default return self.manifest.get(section, key)
[ "def", "get", "(", "self", ",", "section", ",", "key", ",", "default", "=", "MANIFEST_NULL_KEY", ")", ":", "if", "not", "self", ".", "manifest", ".", "has_option", "(", "section", ",", "key", ")", "and", "default", "is", "not", "MANIFEST_NULL_KEY", ":", ...
Returns the value if it exist, or default if default is set
[ "Returns", "the", "value", "if", "it", "exist", "or", "default", "if", "default", "is", "set" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/manifest.py#L212-L216
train
54,495
toumorokoshi/sprinter
sprinter/core/manifest.py
Manifest.__parse_namespace
def __parse_namespace(self): """ Parse the namespace from various sources """ if self.manifest.has_option('config', 'namespace'): return self.manifest.get('config', 'namespace') elif self.manifest.has_option('config', 'source'): return NAMESPACE_REGEX.search(self.manifest.get('config', 'source')).groups()[0] else: logger.warn('Could not parse namespace implicitely') return None
python
def __parse_namespace(self): """ Parse the namespace from various sources """ if self.manifest.has_option('config', 'namespace'): return self.manifest.get('config', 'namespace') elif self.manifest.has_option('config', 'source'): return NAMESPACE_REGEX.search(self.manifest.get('config', 'source')).groups()[0] else: logger.warn('Could not parse namespace implicitely') return None
[ "def", "__parse_namespace", "(", "self", ")", ":", "if", "self", ".", "manifest", ".", "has_option", "(", "'config'", ",", "'namespace'", ")", ":", "return", "self", ".", "manifest", ".", "get", "(", "'config'", ",", "'namespace'", ")", "elif", "self", "...
Parse the namespace from various sources
[ "Parse", "the", "namespace", "from", "various", "sources" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/manifest.py#L218-L228
train
54,496
toumorokoshi/sprinter
sprinter/core/manifest.py
Manifest.__generate_dependency_tree
def __generate_dependency_tree(self): """ Generate the dependency tree object """ dependency_dict = {} for s in self.manifest.sections(): if s != "config": if self.manifest.has_option(s, 'depends'): dependency_list = [d.strip() for d in re.split('\n|,', self.manifest.get(s, 'depends'))] dependency_dict[s] = dependency_list else: dependency_dict[s] = [] try: return DependencyTree(dependency_dict) except DependencyTreeException: dte = sys.exc_info()[1] raise ManifestException("Dependency tree for manifest is invalid! %s" % str(dte))
python
def __generate_dependency_tree(self): """ Generate the dependency tree object """ dependency_dict = {} for s in self.manifest.sections(): if s != "config": if self.manifest.has_option(s, 'depends'): dependency_list = [d.strip() for d in re.split('\n|,', self.manifest.get(s, 'depends'))] dependency_dict[s] = dependency_list else: dependency_dict[s] = [] try: return DependencyTree(dependency_dict) except DependencyTreeException: dte = sys.exc_info()[1] raise ManifestException("Dependency tree for manifest is invalid! %s" % str(dte))
[ "def", "__generate_dependency_tree", "(", "self", ")", ":", "dependency_dict", "=", "{", "}", "for", "s", "in", "self", ".", "manifest", ".", "sections", "(", ")", ":", "if", "s", "!=", "\"config\"", ":", "if", "self", ".", "manifest", ".", "has_option",...
Generate the dependency tree object
[ "Generate", "the", "dependency", "tree", "object" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/manifest.py#L230-L246
train
54,497
toumorokoshi/sprinter
sprinter/core/manifest.py
Manifest.__substitute_objects
def __substitute_objects(self, value, context_dict): """ recursively substitute value with the context_dict """ if type(value) == dict: return dict([(k, self.__substitute_objects(v, context_dict)) for k, v in value.items()]) elif type(value) == str: try: return value % context_dict except KeyError: e = sys.exc_info()[1] logger.warn("Could not specialize %s! Error: %s" % (value, e)) return value else: return value
python
def __substitute_objects(self, value, context_dict): """ recursively substitute value with the context_dict """ if type(value) == dict: return dict([(k, self.__substitute_objects(v, context_dict)) for k, v in value.items()]) elif type(value) == str: try: return value % context_dict except KeyError: e = sys.exc_info()[1] logger.warn("Could not specialize %s! Error: %s" % (value, e)) return value else: return value
[ "def", "__substitute_objects", "(", "self", ",", "value", ",", "context_dict", ")", ":", "if", "type", "(", "value", ")", "==", "dict", ":", "return", "dict", "(", "[", "(", "k", ",", "self", ".", "__substitute_objects", "(", "v", ",", "context_dict", ...
recursively substitute value with the context_dict
[ "recursively", "substitute", "value", "with", "the", "context_dict" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/manifest.py#L248-L262
train
54,498
toumorokoshi/sprinter
sprinter/core/manifest.py
Manifest.__setup_inputs
def __setup_inputs(self): """ Setup the inputs object """ input_object = Inputs() # populate input schemas for s in self.manifest.sections(): if self.has_option(s, 'inputs'): input_object.add_inputs_from_inputstring(self.get(s, 'inputs')) # add in values for k, v in self.items('config'): if input_object.is_input(s): input_object.set_input(k, v) return input_object
python
def __setup_inputs(self): """ Setup the inputs object """ input_object = Inputs() # populate input schemas for s in self.manifest.sections(): if self.has_option(s, 'inputs'): input_object.add_inputs_from_inputstring(self.get(s, 'inputs')) # add in values for k, v in self.items('config'): if input_object.is_input(s): input_object.set_input(k, v) return input_object
[ "def", "__setup_inputs", "(", "self", ")", ":", "input_object", "=", "Inputs", "(", ")", "# populate input schemas", "for", "s", "in", "self", ".", "manifest", ".", "sections", "(", ")", ":", "if", "self", ".", "has_option", "(", "s", ",", "'inputs'", ")...
Setup the inputs object
[ "Setup", "the", "inputs", "object" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/manifest.py#L264-L275
train
54,499