_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q240200
Traces.Y_dist
train
def Y_dist(self, new_y_distance): """Use preset values for the distance between lines.""" self.parent.value('y_distance', new_y_distance) self.parent.traces.display()
python
{ "resource": "" }
q240201
Traces.mousePressEvent
train
def mousePressEvent(self, event): """Create a marker or start selection Parameters ---------- event : instance of QtCore.QEvent it contains the position that was clicked. """ if not self.scene: return if self.event_sel or self...
python
{ "resource": "" }
q240202
Traces.mouseReleaseEvent
train
def mouseReleaseEvent(self, event): """Create a new event or marker, or show the previous power spectrum """ if not self.scene: return if self.event_sel: return if self.deselect: self.deselect = False return if not self.r...
python
{ "resource": "" }
q240203
Traces.next_event
train
def next_event(self, delete=False): """Go to next event.""" if delete: msg = "Delete this event? This cannot be undone." msgbox = QMessageBox(QMessageBox.Question, 'Delete event', msg) msgbox.setStandardButtons(QMessageBox.Yes | QMessageBox.No) msgbox.setD...
python
{ "resource": "" }
q240204
Traces.resizeEvent
train
def resizeEvent(self, event): """Resize scene so that it fits the whole widget. Parameters ---------- event : instance of QtCore.QEvent not important Notes ----- This function overwrites Qt function, therefore the non-standard name. Argument ...
python
{ "resource": "" }
q240205
Edf.return_dat
train
def return_dat(self, chan, begsam, endsam): """Read data from an EDF file. Reads channel by channel, and adjusts the values by calibration. Parameters ---------- chan : list of int index (indices) of the channels to read begsam : int index of the...
python
{ "resource": "" }
q240206
Edf._read_record
train
def _read_record(self, f, blk, chans): """Read raw data from a single EDF channel. Parameters ---------- i_chan : int index of the channel to read begsam : int index of the first sample endsam : int index of the last sample Re...
python
{ "resource": "" }
q240207
write_brainvision
train
def write_brainvision(data, filename, markers=None): """Export data in BrainVision format Parameters ---------- data : instance of ChanTime data with only one trial filename : path to file file to export to (use '.vhdr' as extension) """ filename = Path(filename).resolve().w...
python
{ "resource": "" }
q240208
calc_xyz2surf
train
def calc_xyz2surf(surf, xyz, threshold=20, exponent=None, std=None): """Calculate transformation matrix from xyz values to vertices. Parameters ---------- surf : instance of wonambi.attr.Surf the surface of only one hemisphere. xyz : numpy.ndarray nChan x 3 matrix, with the location...
python
{ "resource": "" }
q240209
calc_one_vert_inverse
train
def calc_one_vert_inverse(one_vert, xyz=None, exponent=None): """Calculate how many electrodes influence one vertex, using the inverse function. Parameters ---------- one_vert : ndarray vector of xyz position of a vertex xyz : ndarray nChan X 3 with the position of all the chann...
python
{ "resource": "" }
q240210
calc_one_vert_gauss
train
def calc_one_vert_gauss(one_vert, xyz=None, std=None): """Calculate how many electrodes influence one vertex, using a Gaussian function. Parameters ---------- one_vert : ndarray vector of xyz position of a vertex xyz : ndarray nChan X 3 with the position of all the channels ...
python
{ "resource": "" }
q240211
_read_history
train
def _read_history(f, zone): """This matches the Matlab reader from Matlab Exchange but doesn't seem correct. """ pos, length = zone f.seek(pos, SEEK_SET) histories = [] while f.tell() < (pos + length): history = { 'nSample': unpack(MAX_SAMPLE * 'I', f.read(MAX_SAMPLE * 4...
python
{ "resource": "" }
q240212
Video.create_video
train
def create_video(self): """Create video widget.""" self.instance = vlc.Instance() video_widget = QFrame() self.mediaplayer = self.instance.media_player_new() if system() == 'Linux': self.mediaplayer.set_xwindow(video_widget.winId()) elif system() == 'Windows...
python
{ "resource": "" }
q240213
Video.stop_video
train
def stop_video(self, tick): """Stop video if tick is more than the end, only for last file. Parameters ---------- tick : int time in ms from the beginning of the file useless? """ if self.cnt_video == self.n_video: if tick >= self.end_dif...
python
{ "resource": "" }
q240214
Video.next_video
train
def next_video(self, _): """Also runs when file is loaded, so index starts at 2.""" self.cnt_video += 1 lg.info('Update video to ' + str(self.cnt_video))
python
{ "resource": "" }
q240215
Video.start_stop_video
train
def start_stop_video(self): """Start and stop the video, and change the button. """ if self.parent.info.dataset is None: self.parent.statusBar().showMessage('No Dataset Loaded') return # & is added automatically by PyQt, it seems if 'Start' in self.idx_bu...
python
{ "resource": "" }
q240216
Video.update_video
train
def update_video(self): """Read list of files, convert to video time, and add video to queue. """ window_start = self.parent.value('window_start') window_length = self.parent.value('window_length') d = self.parent.info.dataset videos, begsec, endsec = d.read_videos(windo...
python
{ "resource": "" }
q240217
montage
train
def montage(data, ref_chan=None, ref_to_avg=False, bipolar=None, method='average'): """Apply linear transformation to the channels. Parameters ---------- data : instance of DataRaw the data to filter ref_chan : list of str list of channels used as reference ref_to_av...
python
{ "resource": "" }
q240218
_assert_equal_channels
train
def _assert_equal_channels(axis): """check that all the trials have the same channels, in the same order. Parameters ---------- axis : ndarray of ndarray one of the data axis Raises ------ """ for i0 in axis: for i1 in axis: if not all(i0 == i1): ...
python
{ "resource": "" }
q240219
compute_average_regress
train
def compute_average_regress(x, idx_chan): """Take the mean across channels and regress out the mean from each channel Parameters ---------- x : ndarray 2d array with channels on one dimension idx_chan: which axis contains channels Returns ------- ndarray same as...
python
{ "resource": "" }
q240220
keep_recent_datasets
train
def keep_recent_datasets(max_dataset_history, info=None): """Keep track of the most recent recordings. Parameters ---------- max_dataset_history : int maximum number of datasets to remember info : str, optional TODO path to file Returns ------- list of str paths...
python
{ "resource": "" }
q240221
choose_file_or_dir
train
def choose_file_or_dir(): """Create a simple message box to see if the user wants to open dir or file Returns ------- str 'dir' or 'file' or 'abort' """ question = QMessageBox(QMessageBox.Information, 'Open Dataset', 'Do you want to open a file or a directory...
python
{ "resource": "" }
q240222
convert_name_to_color
train
def convert_name_to_color(s): """Convert any string to an RGB color. Parameters ---------- s : str string to convert selection : bool, optional if an event is being selected, it's lighter Returns ------- instance of QColor one of the possible color Notes ...
python
{ "resource": "" }
q240223
freq_from_str
train
def freq_from_str(freq_str): """Obtain frequency ranges from input string, either as list or dynamic notation. Parameters ---------- freq_str : str String with frequency ranges, either as a list: e.g. [[1-3], [3-5], [5-8]]; or with a dynamic definition: (start, stop, width, ...
python
{ "resource": "" }
q240224
export_graphics_to_svg
train
def export_graphics_to_svg(widget, filename): """Export graphics to svg Parameters ---------- widget : instance of QGraphicsView traces or overview filename : str path to save svg """ generator = QSvgGenerator() generator.setFileName(filename) generator.setSize(widge...
python
{ "resource": "" }
q240225
FormList.get_value
train
def get_value(self, default=None): """Get int from widget. Parameters ---------- default : list list with widgets Returns ------- list list that might contain int or str or float etc """ if default is None: de...
python
{ "resource": "" }
q240226
FormDir.connect
train
def connect(self, funct): """Call funct when the text was changed. Parameters ---------- funct : function function that broadcasts a change. Notes ----- There is something wrong here. When you run this function, it calls for opening a directo...
python
{ "resource": "" }
q240227
FormMenu.get_value
train
def get_value(self, default=None): """Get selection from widget. Parameters ---------- default : str str for use by widget Returns ------- str selected item from the combobox """ if default is None: default = ...
python
{ "resource": "" }
q240228
_write_ieeg_json
train
def _write_ieeg_json(output_file): """Use only required fields """ dataset_info = { "TaskName": "unknown", "Manufacturer": "n/a", "PowerLineFrequency": 50, "iEEGReference": "n/a", } with output_file.open('w') as f: dump(dataset_info, f, indent=' ')
python
{ "resource": "" }
q240229
MainWindow.value
train
def value(self, parameter, new_value=None): """This function is a shortcut for any parameter. Instead of calling the widget, its config and its values, you can call directly the parameter. Parameters ---------- parameter : str name of the parameter of interes...
python
{ "resource": "" }
q240230
MainWindow.update
train
def update(self): """Once you open a dataset, it activates all the widgets. """ self.info.display_dataset() self.overview.update() self.labels.update(labels=self.info.dataset.header['chan_name']) self.channels.update() try: self.info.markers = self.in...
python
{ "resource": "" }
q240231
MainWindow.reset
train
def reset(self): """Remove all the information from previous dataset before loading a new dataset. """ # store current dataset max_dataset_history = self.value('max_dataset_history') keep_recent_datasets(max_dataset_history, self.info) # reset all the widgets ...
python
{ "resource": "" }
q240232
MainWindow.show_settings
train
def show_settings(self): """Open the Setting windows, after updating the values in GUI. """ self.notes.config.put_values() self.overview.config.put_values() self.settings.config.put_values() self.spectrum.config.put_values() self.traces.config.put_values() self.vi...
python
{ "resource": "" }
q240233
MainWindow.show_spindle_dialog
train
def show_spindle_dialog(self): """Create the spindle detection dialog.""" self.spindle_dialog.update_groups() self.spindle_dialog.update_cycles() self.spindle_dialog.show()
python
{ "resource": "" }
q240234
MainWindow.show_slow_wave_dialog
train
def show_slow_wave_dialog(self): """Create the SW detection dialog.""" self.slow_wave_dialog.update_groups() self.slow_wave_dialog.update_cycles() self.slow_wave_dialog.show()
python
{ "resource": "" }
q240235
MainWindow.show_event_analysis_dialog
train
def show_event_analysis_dialog(self): """Create the event analysis dialog.""" self.event_analysis_dialog.update_types() self.event_analysis_dialog.update_groups() self.event_analysis_dialog.update_cycles() self.event_analysis_dialog.show()
python
{ "resource": "" }
q240236
MainWindow.show_analysis_dialog
train
def show_analysis_dialog(self): """Create the analysis dialog.""" self.analysis_dialog.update_evt_types() self.analysis_dialog.update_groups() self.analysis_dialog.update_cycles() self.analysis_dialog.show()
python
{ "resource": "" }
q240237
MainWindow.closeEvent
train
def closeEvent(self, event): """save the name of the last open dataset.""" max_dataset_history = self.value('max_dataset_history') keep_recent_datasets(max_dataset_history, self.info) settings.setValue('window/geometry', self.saveGeometry()) settings.setValue('window/state', sel...
python
{ "resource": "" }
q240238
_read_header
train
def _read_header(filename): """It's a pain to parse the header. It might be better to use the cpp code but I would need to include it here. """ header = _read_header_text(filename) first_row = header[0] EXTRA_ROWS = 3 # drop DefaultValue1 LowRange1 HighRange1 hdr = {} for group in find...
python
{ "resource": "" }
q240239
remove_artf_evts
train
def remove_artf_evts(times, annot, chan=None, min_dur=0.1): """Correct times to remove events marked 'Artefact'. Parameters ---------- times : list of tuple of float the start and end times of each segment annot : instance of Annotations the annotation file containing events and epo...
python
{ "resource": "" }
q240240
WDBaseDataType.statement_ref_mode
train
def statement_ref_mode(self, value): """Set the reference mode for a statement, always overrides the global reference state.""" valid_values = ['STRICT_KEEP', 'STRICT_KEEP_APPEND', 'STRICT_OVERWRITE', 'KEEP_GOOD', 'CUSTOM'] if value not in valid_values: raise ValueError('Not an allow...
python
{ "resource": "" }
q240241
WDBaseDataType.equals
train
def equals(self, that, include_ref=False, fref=None): """ Tests for equality of two statements. If comparing references, the order of the arguments matters!!! self is the current statement, the next argument is the new statement. Allows passing in a function to use to compare the...
python
{ "resource": "" }
q240242
WDBaseDataType.refs_equal
train
def refs_equal(olditem, newitem): """ tests for exactly identical references """ oldrefs = olditem.references newrefs = newitem.references ref_equal = lambda oldref, newref: True if (len(oldref) == len(newref)) and all( x in oldref for x in newref) else False...
python
{ "resource": "" }
q240243
try_write
train
def try_write(wd_item, record_id, record_prop, login, edit_summary='', write=True): """ Write a PBB_core item. Log if item was created, updated, or skipped. Catch and log all errors. :param wd_item: A wikidata item that will be written :type wd_item: PBB_Core.WDItemEngine :param record_id: An e...
python
{ "resource": "" }
q240244
_build_app_dict
train
def _build_app_dict(site, request, label=None): """ Builds the app dictionary. Takes an optional label parameters to filter models of a specific app. """ app_dict = {} if label: models = { m: m_a for m, m_a in site._registry.items() if m._meta.app_label == label ...
python
{ "resource": "" }
q240245
get_app_list
train
def get_app_list(site, request): """ Returns a sorted list of all the installed apps that have been registered in this site. """ app_dict = _build_app_dict(site, request) # Sort the apps alphabetically. app_list = sorted(app_dict.values(), key=lambda x: x['name'].lower()) # Sort the mo...
python
{ "resource": "" }
q240246
FastRunContainer.format_query_results
train
def format_query_results(self, r, prop_nr): """ `r` is the results of the sparql query in _query_data and is modified in place `prop_nr` is needed to get the property datatype to determine how to format the value `r` is a list of dicts. The keys are: item: the subject. the i...
python
{ "resource": "" }
q240247
FastRunContainer.clear
train
def clear(self): """ convinience function to empty this fastrun container """ self.prop_dt_map = dict() self.prop_data = dict() self.rev_lookup = defaultdict(set)
python
{ "resource": "" }
q240248
times
train
def times(p, mint, maxt=None): '''Repeat a parser between `mint` and `maxt` times. DO AS MUCH MATCH AS IT CAN. Return a list of values.''' maxt = maxt if maxt else mint @Parser def times_parser(text, index): cnt, values, res = 0, Value.success(index, []), None while cnt < maxt: ...
python
{ "resource": "" }
q240249
optional
train
def optional(p, default_value=None): '''`Make a parser as optional. If success, return the result, otherwise return default_value silently, without raising any exception. If default_value is not provided None is returned instead. ''' @Parser def optional_parser(text, index): res = p(text...
python
{ "resource": "" }
q240250
separated
train
def separated(p, sep, mint, maxt=None, end=None): '''Repeat a parser `p` separated by `s` between `mint` and `maxt` times. When `end` is None, a trailing separator is optional. When `end` is True, a trailing separator is required. When `end` is False, a trailing separator is not allowed. MATCHES AS ...
python
{ "resource": "" }
q240251
one_of
train
def one_of(s): '''Parser a char from specified string.''' @Parser def one_of_parser(text, index=0): if index < len(text) and text[index] in s: return Value.success(index + 1, text[index]) else: return Value.failure(index, 'one of {}'.format(s)) return one_of_parse...
python
{ "resource": "" }
q240252
none_of
train
def none_of(s): '''Parser a char NOT from specified string.''' @Parser def none_of_parser(text, index=0): if index < len(text) and text[index] not in s: return Value.success(index + 1, text[index]) else: return Value.failure(index, 'none of {}'.format(s)) return n...
python
{ "resource": "" }
q240253
space
train
def space(): '''Parser a whitespace character.''' @Parser def space_parser(text, index=0): if index < len(text) and text[index].isspace(): return Value.success(index + 1, text[index]) else: return Value.failure(index, 'one space') return space_parser
python
{ "resource": "" }
q240254
letter
train
def letter(): '''Parse a letter in alphabet.''' @Parser def letter_parser(text, index=0): if index < len(text) and text[index].isalpha(): return Value.success(index + 1, text[index]) else: return Value.failure(index, 'a letter') return letter_parser
python
{ "resource": "" }
q240255
digit
train
def digit(): '''Parse a digit character.''' @Parser def digit_parser(text, index=0): if index < len(text) and text[index].isdigit(): return Value.success(index + 1, text[index]) else: return Value.failure(index, 'a digit') return digit_parser
python
{ "resource": "" }
q240256
eof
train
def eof(): '''Parser EOF flag of a string.''' @Parser def eof_parser(text, index=0): if index >= len(text): return Value.success(index, None) else: return Value.failure(index, 'EOF') return eof_parser
python
{ "resource": "" }
q240257
string
train
def string(s): '''Parser a string.''' @Parser def string_parser(text, index=0): slen, tlen = len(s), len(text) if text[index:index + slen] == s: return Value.success(index + slen, s) else: matched = 0 while matched < slen and index + matched < tlen...
python
{ "resource": "" }
q240258
ParseError.loc_info
train
def loc_info(text, index): '''Location of `index` in source code `text`.''' if index > len(text): raise ValueError('Invalid index.') line, last_ln = text.count('\n', 0, index), text.rfind('\n', 0, index) col = index - (last_ln + 1) return (line, col)
python
{ "resource": "" }
q240259
ParseError.loc
train
def loc(self): '''Locate the error position in the source code text.''' try: return '{}:{}'.format(*ParseError.loc_info(self.text, self.index)) except ValueError: return '<out of bounds index {!r}>'.format(self.index)
python
{ "resource": "" }
q240260
Value.aggregate
train
def aggregate(self, other=None): '''collect the furthest failure from self and other.''' if not self.status: return self if not other: return self if not other.status: return other return Value(True, other.index, self.value + other.value, None)
python
{ "resource": "" }
q240261
Value.combinate
train
def combinate(values): '''aggregate multiple values into tuple''' prev_v = None for v in values: if prev_v: if not v: return prev_v if not v.status: return v out_values = tuple([v.value for v in values]) ...
python
{ "resource": "" }
q240262
Parser.parse_partial
train
def parse_partial(self, text): '''Parse the longest possible prefix of a given string. Return a tuple of the result value and the rest of the string. If failed, raise a ParseError. ''' if not isinstance(text, str): raise TypeError( 'Can only parsing string but...
python
{ "resource": "" }
q240263
Parser.bind
train
def bind(self, fn): '''This is the monadic binding operation. Returns a parser which, if parser is successful, passes the result to fn, and continues with the parser returned from fn. ''' @Parser def bind_parser(text, index): res = self(text, index) ...
python
{ "resource": "" }
q240264
Parser.parsecmap
train
def parsecmap(self, fn): '''Returns a parser that transforms the produced value of parser with `fn`.''' return self.bind(lambda res: Parser(lambda _, index: Value.success(index, fn(res))))
python
{ "resource": "" }
q240265
Parser.parsecapp
train
def parsecapp(self, other): '''Returns a parser that applies the produced value of this parser to the produced value of `other`.''' # pylint: disable=unnecessary-lambda return self.bind(lambda res: other.parsecmap(lambda x: res(x)))
python
{ "resource": "" }
q240266
Parser.result
train
def result(self, res): '''Return a value according to the parameter `res` when parse successfully.''' return self >> Parser(lambda _, index: Value.success(index, res))
python
{ "resource": "" }
q240267
Parser.mark
train
def mark(self): '''Mark the line and column information of the result of this parser.''' def pos(text, index): return ParseError.loc_info(text, index) @Parser def mark_parser(text, index): res = self(text, index) if res.status: return ...
python
{ "resource": "" }
q240268
Parser.desc
train
def desc(self, description): '''Describe a parser, when it failed, print out the description text.''' return self | Parser(lambda _, index: Value.failure(index, description))
python
{ "resource": "" }
q240269
route
train
def route(*args): """ This function is used to define an explicit route for a path segment. You generally only want to use this in situations where your desired path segment is not a valid Python variable/function name. For example, if you wanted to be able to route to: /path/with-dashes/ ...
python
{ "resource": "" }
q240270
lookup_controller
train
def lookup_controller(obj, remainder, request=None): ''' Traverses the requested url path and returns the appropriate controller object, including default routes. Handles common errors gracefully. ''' if request is None: warnings.warn( ( "The function signatu...
python
{ "resource": "" }
q240271
find_object
train
def find_object(obj, remainder, notfound_handlers, request): ''' 'Walks' the url path in search of an action for which a controller is implemented and returns that controller object along with what's left of the remainder. ''' prev_obj = None while True: if obj is None: r...
python
{ "resource": "" }
q240272
unlocked
train
def unlocked(func_or_obj): """ This method unlocks method or class attribute on a SecureController. Can be used to decorate or wrap an attribute """ if ismethod(func_or_obj) or isfunction(func_or_obj): return _unlocked_method(func_or_obj) else: return _UnlockedAttribute(func_or_...
python
{ "resource": "" }
q240273
secure
train
def secure(func_or_obj, check_permissions_for_obj=None): """ This method secures a method or class depending on invocation. To decorate a method use one argument: @secure(<check_permissions_method>) To secure a class, invoke with two arguments: secure(<obj instance>, <check_permissions...
python
{ "resource": "" }
q240274
_make_wrapper
train
def _make_wrapper(f): """return a wrapped function with a copy of the _pecan context""" @wraps(f) def wrapper(*args, **kwargs): return f(*args, **kwargs) wrapper._pecan = f._pecan.copy() return wrapper
python
{ "resource": "" }
q240275
handle_security
train
def handle_security(controller, im_self=None): """ Checks the security of a controller. """ if controller._pecan.get('secured', False): check_permissions = controller._pecan['check_permissions'] if isinstance(check_permissions, six.string_types): check_permissions = getattr( ...
python
{ "resource": "" }
q240276
cross_boundary
train
def cross_boundary(prev_obj, obj): """ Check permissions as we move between object instances. """ if prev_obj is None: return if isinstance(obj, _SecuredAttribute): # a secure attribute can live in unsecure class so we have to set # while we walk the route obj.parent = prev_...
python
{ "resource": "" }
q240277
makedirs
train
def makedirs(directory): """ Resursively create a named directory. """ parent = os.path.dirname(os.path.abspath(directory)) if not os.path.exists(parent): makedirs(parent) os.mkdir(directory)
python
{ "resource": "" }
q240278
substitute_filename
train
def substitute_filename(fn, variables): """ Substitute +variables+ in file directory names. """ for var, value in variables.items(): fn = fn.replace('+%s+' % var, str(value)) return fn
python
{ "resource": "" }
q240279
make_app
train
def make_app(root, **kw): ''' Utility for creating the Pecan application object. This function should generally be called from the ``setup_app`` function in your project's ``app.py`` file. :param root: A string representing a root controller object (e.g., "myapp.controller.root.Ro...
python
{ "resource": "" }
q240280
conf_from_file
train
def conf_from_file(filepath): ''' Creates a configuration dictionary from a file. :param filepath: The path to the file. ''' abspath = os.path.abspath(os.path.expanduser(filepath)) conf_dict = {} if not os.path.isfile(abspath): raise RuntimeError('`%s` is not a file.' % abspath) ...
python
{ "resource": "" }
q240281
get_conf_path_from_env
train
def get_conf_path_from_env(): ''' If the ``PECAN_CONFIG`` environment variable exists and it points to a valid path it will return that, otherwise it will raise a ``RuntimeError``. ''' config_path = os.environ.get('PECAN_CONFIG') if not config_path: error = "PECAN_CONFIG is not set a...
python
{ "resource": "" }
q240282
conf_from_dict
train
def conf_from_dict(conf_dict): ''' Creates a configuration dictionary from a dictionary. :param conf_dict: The configuration dictionary. ''' conf = Config(filename=conf_dict.get('__file__', '')) for k, v in six.iteritems(conf_dict): if k.startswith('__'): continue e...
python
{ "resource": "" }
q240283
set_config
train
def set_config(config, overwrite=False): ''' Updates the global configuration. :param config: Can be a dictionary containing configuration, or a string which represents a (relative) configuration filename. ''' if config is None: config = get_conf_path_from_env() # m...
python
{ "resource": "" }
q240284
Config.update
train
def update(self, conf_dict): ''' Updates this configuration with a dictionary. :param conf_dict: A python dictionary to update this configuration with. ''' if isinstance(conf_dict, dict): iterator = six.iteritems(conf_dict) else: ...
python
{ "resource": "" }
q240285
Config.to_dict
train
def to_dict(self, prefix=None): ''' Converts recursively the Config object into a valid dictionary. :param prefix: A string to optionally prefix all key elements in the returned dictonary. ''' conf_obj = dict(self) return self.__dictify__(conf_obj...
python
{ "resource": "" }
q240286
override_template
train
def override_template(template, content_type=None): ''' Call within a controller to override the template that is used in your response. :param template: a valid path to a template file, just as you would specify in an ``@expose``. :param content_type: a valid MIME type to use ...
python
{ "resource": "" }
q240287
abort
train
def abort(status_code, detail='', headers=None, comment=None, **kw): ''' Raise an HTTP status code, as specified. Useful for returning status codes like 401 Unauthorized or 403 Forbidden. :param status_code: The HTTP status code as an integer. :param detail: The message to send along, as a string. ...
python
{ "resource": "" }
q240288
redirect
train
def redirect(location=None, internal=False, code=None, headers={}, add_slash=False, request=None): ''' Perform a redirect, either internal or external. An internal redirect performs the redirect server-side, while the external redirect utilizes an HTTP 302 status code. :param location:...
python
{ "resource": "" }
q240289
load_app
train
def load_app(config, **kwargs): ''' Used to load a ``Pecan`` application and its environment based on passed configuration. :param config: Can be a dictionary containing configuration, a string which represents a (relative) configuration filename returns a pecan.Pecan object ...
python
{ "resource": "" }
q240290
PecanBase.route
train
def route(self, req, node, path): ''' Looks up a controller from a node based upon the specified path. :param node: The node, such as a root controller object. :param path: The path to look up on this node. ''' path = path.split('/')[1:] try: node, re...
python
{ "resource": "" }
q240291
PecanBase.determine_hooks
train
def determine_hooks(self, controller=None): ''' Determines the hooks to be run, in which order. :param controller: If specified, includes hooks for a specific controller. ''' controller_hooks = [] if controller: controller_hooks = ...
python
{ "resource": "" }
q240292
PecanBase.handle_hooks
train
def handle_hooks(self, hooks, hook_type, *args): ''' Processes hooks of the specified type. :param hook_type: The type of hook, including ``before``, ``after``, ``on_error``, and ``on_route``. :param \*args: Arguments to pass to the hooks. ''' i...
python
{ "resource": "" }
q240293
PecanBase.get_args
train
def get_args(self, state, all_params, remainder, argspec, im_self): ''' Determines the arguments for a controller based upon parameters passed the argument specification for the controller. ''' args = [] varargs = [] kwargs = dict() valid_args = argspec.ar...
python
{ "resource": "" }
q240294
ShellCommand.run
train
def run(self, args): """ Load the pecan app, prepare the locals, sets the banner, and invokes the python shell. """ super(ShellCommand, self).run(args) # load the application app = self.load_app() # prepare the locals locs = dict(__name__='pecan-...
python
{ "resource": "" }
q240295
ShellCommand.load_model
train
def load_model(self, config): """ Load the model extension module """ for package_name in getattr(config.app, 'modules', []): module = __import__(package_name, fromlist=['model']) if hasattr(module, 'model'): return module.model return None
python
{ "resource": "" }
q240296
RestController._handle_bad_rest_arguments
train
def _handle_bad_rest_arguments(self, controller, remainder, request): """ Ensure that the argspec for a discovered controller actually matched the positional arguments in the request path. If not, raise a webob.exc.HTTPBadRequest. """ argspec = self._get_args_for_control...
python
{ "resource": "" }
q240297
RestController._route
train
def _route(self, args, request=None): ''' Routes a request to the appropriate controller and returns its result. Performs a bit of validation - refuses to route delete and put actions via a GET request). ''' if request is None: from pecan import request ...
python
{ "resource": "" }
q240298
RestController._find_controller
train
def _find_controller(self, *args): ''' Returns the appropriate controller for routing a custom action. ''' for name in args: obj = self._lookup_child(name) if obj and iscontroller(obj): return obj return None
python
{ "resource": "" }
q240299
RestController._find_sub_controllers
train
def _find_sub_controllers(self, remainder, request): ''' Identifies the correct controller to route to by analyzing the request URI. ''' # need either a get_one or get to parse args method = None for name in ('get_one', 'get'): if hasattr(self, name): ...
python
{ "resource": "" }