_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q44500
FetchTransformSaveWithSeparateNewCrashSourceApp._setup_source_and_destination
train
def _setup_source_and_destination(self): """use the base class to setup the source and destinations but add to that setup the instantiation of the "new_crash_source" """ super(FetchTransformSaveWithSeparateNewCrashSourceApp, self) \ ._setup_source_and_destination() if self.co...
python
{ "resource": "" }
q44501
load_config
train
def load_config(options): ''' Load options, platform, colors, and icons. ''' global opts, pform opts = options pform = options.pform global_ns = globals() # get colors if pform.hicolor: global_ns['dim_templ'] = ansi.dim8t global_ns['swap_clr_templ'] = ansi.csi8_blk % ansi.bl...
python
{ "resource": "" }
q44502
fmtstr
train
def fmtstr(text='', colorstr=None, align='>', trunc=True, width=0, end=' '): ''' Formats, justifies, and returns a given string according to specifications. ''' colwidth = width or opts.colwidth if trunc: if len(text) > colwidth: text = truncstr(text, colwidth, align=trunc) ...
python
{ "resource": "" }
q44503
fmtval
train
def fmtval(value, colorstr=None, precision=None, spacing=True, trunc=True, end=' '): ''' Formats and returns a given number according to specifications. ''' colwidth = opts.colwidth # get precision if precision is None: precision = opts.precision fmt = '%%.%sf' % precision # ...
python
{ "resource": "" }
q44504
get_units
train
def get_units(unit, binary=False): ''' Sets the output unit and precision for future calculations and returns an integer and the string representation of it. ''' result = None if unit == 'b': result = 1, 'Byte' elif binary: # 2^X if unit == 'k': result = 10...
python
{ "resource": "" }
q44505
truncstr
train
def truncstr(text, width, align='right'): ''' Truncate a string, with trailing ellipsis. ''' before = after = '' if align == 'left': truncated = text[-width+1:] before = _ellpico elif align: truncated = text[:width-1] after = _ellpico return f'{before}{truncated}{aft...
python
{ "resource": "" }
q44506
Archiver.archive
train
def archive(self, target_path=None, zip_path=None): """ Writes the Zip-encoded file to a directory. :param target_path: The directory path to add. :type target_path: str :param zip_path: The file path of the ZIP archive. :type zip_path: str """ if target_...
python
{ "resource": "" }
q44507
Archiver.unarchive
train
def unarchive(self, target_path=None, zip_path=None): """ Extract the given files to the specified destination. :param src_path: The destination path where to extract the files. :type src_path: str :param zip_path: The file path of the ZIP archive. :type zip_path: str ...
python
{ "resource": "" }
q44508
set_sns
train
def set_sns(style="white", context="paper", font_scale=1.5, color_codes=True, rc={}): """Set default plot style using seaborn. Font size is set to match the size of the tick labels, rather than the axes labels. """ rcd = {"lines.markersize": 8, "lines.markeredgewidth": 1.25, ...
python
{ "resource": "" }
q44509
label_subplot
train
def label_subplot(ax=None, x=0.5, y=-0.25, text="(a)", **kwargs): """Create a subplot label.""" if ax is None: ax = plt.gca() ax.text(x=x, y=y, s=text, transform=ax.transAxes, horizontalalignment="center", verticalalignment="top", **kwargs)
python
{ "resource": "" }
q44510
GenDebBuilder.genchanges
train
def genchanges(self): """Generate a .changes file for this package.""" chparams = self.params.copy() debpath = os.path.join(self.buildroot, self.rule.output_files[0]) chparams.update({ 'fullversion': '{epoch}:{version}-{release}'.format(**chparams), 'metahash': se...
python
{ "resource": "" }
q44511
GenDeb.validate_args
train
def validate_args(self): """Input validators for this rule type.""" base.BaseTarget.validate_args(self) params = self.params if params['extra_control_fields'] is not None: assert isinstance(params['extra_control_fields'], list), ( 'extra_control_fields must be...
python
{ "resource": "" }
q44512
LineDiscountItem.value
train
def value(self): """Returns the positive value to subtract from the total.""" originalPrice = self.lineItem.totalPrice if self.flatRate == 0: return originalPrice * self.percent return self.flatRate
python
{ "resource": "" }
q44513
voxel_count
train
def voxel_count(dset,p=None,positive_only=False,mask=None,ROI=None): ''' returns the number of non-zero voxels :p: threshold the dataset at the given *p*-value, then count :positive_only: only count positive values :mask: count within the given mask :ROI: only use the...
python
{ "resource": "" }
q44514
mask_average
train
def mask_average(dset,mask): '''Returns average of voxels in ``dset`` within non-zero voxels of ``mask``''' o = nl.run(['3dmaskave','-q','-mask',mask,dset]) if o: return float(o.output.split()[-1])
python
{ "resource": "" }
q44515
FreeIPAUser.is_member_of
train
def is_member_of(self, group_name): """Return True if member of LDAP group, otherwise return False""" group_dn = 'cn=%s,cn=groups,cn=accounts,%s' % (group_name, self._base_dn) if str(group_dn).lower() in [str(i).lower() for i in self.member_of]: return True else: ...
python
{ "resource": "" }
q44516
_commonPrefetchDeclarativeIds
train
def _commonPrefetchDeclarativeIds(engine, mutex, Declarative, count) -> Optional[Iterable[int]]: """ Common Prefetch Declarative IDs This function is used by the worker and server """ if not count: logger.debug("Count was zero, no range returned") retur...
python
{ "resource": "" }
q44517
DbConnection.ormSessionCreator
train
def ormSessionCreator(self) -> DbSessionCreator: """ Get Orm Session :return: A SQLAlchemy session scoped for the callers thread.. """ assert self._dbConnectString if self._ScopedSession: return self._ScopedSession self._dbEngine = create_engine( ...
python
{ "resource": "" }
q44518
DbConnection.checkForeignKeys
train
def checkForeignKeys(self, engine: Engine) -> None: """ Check Foreign Keys Log any foreign keys that don't have indexes assigned to them. This is a performance issue. """ missing = (sqlalchemy_utils.functions .non_indexed_foreign_keys(self._metadata, engine=e...
python
{ "resource": "" }
q44519
temporary_tag
train
def temporary_tag(tag): """ Temporarily tags the repo """ if tag: CTX.repo.tag(tag) try: yield finally: if tag: CTX.repo.remove_tag(tag)
python
{ "resource": "" }
q44520
savejson
train
def savejson(filename, datadict): """Save data from a dictionary in JSON format. Note that this only works to the second level of the dictionary with Numpy arrays. """ for key, value in datadict.items(): if type(value) == np.ndarray: datadict[key] = value.tolist() if type(val...
python
{ "resource": "" }
q44521
loadjson
train
def loadjson(filename, asnparrays=False): """Load data from text file in JSON format. Numpy arrays are converted if specified with the `asnparrays` keyword argument. Note that this only works to the second level of the dictionary. Returns a single dict. """ with open(filename) as f: dat...
python
{ "resource": "" }
q44522
savecsv
train
def savecsv(filename, datadict, mode="w"): """Save a dictionary of data to CSV.""" if mode == "a" : header = False else: header = True with open(filename, mode) as f: _pd.DataFrame(datadict).to_csv(f, index=False, header=header)
python
{ "resource": "" }
q44523
loadcsv
train
def loadcsv(filename): """Load data from CSV file. Returns a single dict with column names as keys. """ dataframe = _pd.read_csv(filename) data = {} for key, value in dataframe.items(): data[key] = value.values return data
python
{ "resource": "" }
q44524
save_hdf_metadata
train
def save_hdf_metadata(filename, metadata, groupname="data", mode="a"): """"Save a dictionary of metadata to a group's attrs.""" with _h5py.File(filename, mode) as f: for key, val in metadata.items(): f[groupname].attrs[key] = val
python
{ "resource": "" }
q44525
load_hdf_metadata
train
def load_hdf_metadata(filename, groupname="data"): """"Load attrs of the desired group into a dictionary.""" with _h5py.File(filename, "r") as f: data = dict(f[groupname].attrs) return data
python
{ "resource": "" }
q44526
FuncArgParser.get_param_doc
train
def get_param_doc(doc, param): """Get the documentation and datatype for a parameter This function returns the documentation and the argument for a napoleon like structured docstring `doc` Parameters ---------- doc: str The base docstring to use para...
python
{ "resource": "" }
q44527
FuncArgParser.setup_args
train
def setup_args(self, func=None, setup_as=None, insert_at=None, interprete=True, epilog_sections=None, overwrite=False, append_epilog=True): """ Add the parameters from the given `func` to the parameter settings Parameters ---------- func: fu...
python
{ "resource": "" }
q44528
FuncArgParser.add_subparsers
train
def add_subparsers(self, *args, **kwargs): """ Add subparsers to this parser Parameters ---------- ``*args, **kwargs`` As specified by the original :meth:`argparse.ArgumentParser.add_subparsers` method chain: bool Default: False. If Tr...
python
{ "resource": "" }
q44529
FuncArgParser.setup_subparser
train
def setup_subparser( self, func=None, setup_as=None, insert_at=None, interprete=True, epilog_sections=None, overwrite=False, append_epilog=True, return_parser=False, name=None, **kwargs): """ Create a subparser with the name of the given function Parameters a...
python
{ "resource": "" }
q44530
FuncArgParser.update_arg
train
def update_arg(self, arg, if_existent=None, **kwargs): """ Update the `add_argument` data for the given parameter Parameters ---------- arg: str The name of the function argument if_existent: bool or None If True, the argument is updated. If None ...
python
{ "resource": "" }
q44531
FuncArgParser._get_corresponding_parsers
train
def _get_corresponding_parsers(self, func): """Get the parser that has been set up by the given `function`""" if func in self._used_functions: yield self if self._subparsers_action is not None: for parser in self._subparsers_action.choices.values(): for sp...
python
{ "resource": "" }
q44532
FuncArgParser.pop_key
train
def pop_key(self, arg, key, *args, **kwargs): """Delete a previously defined key for the `add_argument` """ return self.unfinished_arguments[arg].pop(key, *args, **kwargs)
python
{ "resource": "" }
q44533
FuncArgParser.create_arguments
train
def create_arguments(self, subparsers=False): """Create and add the arguments Parameters ---------- subparsers: bool If True, the arguments of the subparsers are also created""" ret = [] if not self._finalized: for arg, d in self.unfinished_argume...
python
{ "resource": "" }
q44534
FuncArgParser.format_epilog_section
train
def format_epilog_section(self, section, text): """Format a section for the epilog by inserting a format""" try: func = self._epilog_formatters[self.epilog_formatter] except KeyError: if not callable(self.epilog_formatter): raise func = self.ep...
python
{ "resource": "" }
q44535
FuncArgParser.extract_as_epilog
train
def extract_as_epilog(self, text, sections=None, overwrite=False, append=True): """Extract epilog sections from the a docstring Parameters ---------- text The docstring to use sections: list of str The headers of the sections to ...
python
{ "resource": "" }
q44536
FuncArgParser.grouparg
train
def grouparg(self, arg, my_arg=None, parent_cmds=[]): """ Grouper function for chaining subcommands Parameters ---------- arg: str The current command line argument that is parsed my_arg: str The name of this subparser. If None, this parser is the...
python
{ "resource": "" }
q44537
FuncArgParser.__parse_main
train
def __parse_main(self, args): """Parse the main arguments only. This is a work around for python 2.7 because argparse does not allow to parse arguments without subparsers """ if six.PY2: self._subparsers_action.add_parser("__dummy") return super(FuncArgParser, sel...
python
{ "resource": "" }
q44538
FuncArgParser._parse2subparser_funcs
train
def _parse2subparser_funcs(self, kws): """ Recursive function to parse arguments to chained parsers """ choices = getattr(self._subparsers_action, 'choices', {}) replaced = {key.replace('-', '_'): key for key in choices} sp_commands = set(replaced).intersection(kws) ...
python
{ "resource": "" }
q44539
FuncArgParser.get_subparser
train
def get_subparser(self, name): """ Convenience method to get a certain subparser Parameters ---------- name: str The name of the subparser Returns ------- FuncArgParser The subparsers corresponding to `name` """ if...
python
{ "resource": "" }
q44540
parse_file
train
def parse_file(src): """ find file in config and output to dest dir """ #clear the stack between parses if config.dest_dir == None: dest = src.dir else: dest = config.dest_dir output = get_output(src) output_file = dest + '/' + src.basename + '.min.js' f = open(output...
python
{ "resource": "" }
q44541
get_output
train
def get_output(src): """ parse lines looking for commands """ output = '' lines = open(src.path, 'rU').readlines() for line in lines: m = re.match(config.import_regex,line) if m: include_path = os.path.abspath(src.dir + '/' + m.group('script')); if include...
python
{ "resource": "" }
q44542
get_signed_raw_revocation_document
train
def get_signed_raw_revocation_document(identity: Identity, salt: str, password: str) -> str: """ Generate account revocation document for given identity :param identity: Self Certification of the identity :param salt: Salt :param password: Password :rtype: str """ revocation = Revocati...
python
{ "resource": "" }
q44543
motion_from_params
train
def motion_from_params(param_file,motion_file,individual=True,rms=True): '''calculate a motion regressor from the params file given by 3dAllineate Basically just calculates the rms change in the translation and rotation components. Returns the 6 motion vector (if ``individual`` is ``True``) and the RMS differe...
python
{ "resource": "" }
q44544
volreg
train
def volreg(dset,suffix='_volreg',base=3,tshift=3,dfile_suffix='_volreg.1D'): '''simple interface to 3dvolreg :suffix: suffix to add to ``dset`` for volreg'ed file :base: either a number or ``dset[#]`` of the base image to register to :tshift: if a number, then tshift ...
python
{ "resource": "" }
q44545
affine_align
train
def affine_align(dset_from,dset_to,skull_strip=True,mask=None,suffix='_aff',prefix=None,cost=None,epi=False,resample='wsinc5',grid_size=None,opts=[]): ''' interface to 3dAllineate to align anatomies and EPIs ''' dset_ss = lambda dset: os.path.split(nl.suffix(dset,'_ns'))[1] def dset_source(dset): i...
python
{ "resource": "" }
q44546
affine_apply
train
def affine_apply(dset_from,affine_1D,master,affine_suffix='_aff',interp='NN',inverse=False,prefix=None): '''apply the 1D file from a previously aligned dataset Applies the matrix in ``affine_1D`` to ``dset_from`` and makes the final grid look like the dataset ``master`` using the interpolation method ``inte...
python
{ "resource": "" }
q44547
qwarp_align
train
def qwarp_align(dset_from,dset_to,skull_strip=True,mask=None,affine_suffix='_aff',suffix='_qwarp',prefix=None): '''aligns ``dset_from`` to ``dset_to`` using 3dQwarp Will run ``3dSkullStrip`` (unless ``skull_strip`` is ``False``), ``3dUnifize``, ``3dAllineate``, and then ``3dQwarp``. This method will add su...
python
{ "resource": "" }
q44548
qwarp_apply
train
def qwarp_apply(dset_from,dset_warp,affine=None,warp_suffix='_warp',master='WARP',interp=None,prefix=None): '''applies the transform from a previous qwarp Uses the warp parameters from the dataset listed in ``dset_warp`` (usually the dataset name ends in ``_WARP``) to the dataset ``dset_from``. If a ``...
python
{ "resource": "" }
q44549
qwarp_epi
train
def qwarp_epi(dset,align_subbrick=5,suffix='_qwal',prefix=None): '''aligns an EPI time-series using 3dQwarp Very expensive and not efficient at all, but it can produce pretty impressive alignment for EPI time-series with significant distortions due to motion''' info = nl.dset_info(dset) if info==No...
python
{ "resource": "" }
q44550
align_epi_anat
train
def align_epi_anat(anatomy,epi_dsets,skull_strip_anat=True): ''' aligns epis to anatomy using ``align_epi_anat.py`` script :epi_dsets: can be either a string or list of strings of the epi child datasets :skull_strip_anat: if ``True``, ``anatomy`` will be skull-stripped using the default method ...
python
{ "resource": "" }
q44551
skullstrip_template
train
def skullstrip_template(dset,template,prefix=None,suffix=None,dilate=0): '''Takes the raw anatomy ``dset``, aligns it to a template brain, and applies a templated skullstrip. Should produce fairly reliable skullstrips as long as there is a decent amount of normal brain and the overall shape of the brain is norm...
python
{ "resource": "" }
q44552
printmp
train
def printmp(msg): """Print temporarily, until next print overrides it. """ filler = (80 - len(msg)) * ' ' print(msg + filler, end='\r') sys.stdout.flush()
python
{ "resource": "" }
q44553
contacts
train
def contacts(github, logins): """Extract public contact info from users. """ printmp('Fetching contacts') users = [github.user(login).as_dict() for login in logins] mails = set() blogs = set() for user in users: contact = user.get('name', 'login') if user['email']: ...
python
{ "resource": "" }
q44554
extract_mail
train
def extract_mail(issues): """Extract mails that sometimes leak from issue comments. """ contacts = set() for idx, issue in enumerate(issues): printmp('Fetching issue #%s' % idx) for comment in issue.comments(): comm = comment.as_dict() emails = list(email[0] for e...
python
{ "resource": "" }
q44555
fetch_logins
train
def fetch_logins(roles, repo): """Fetch logins for users with given roles. """ users = set() if 'stargazer' in roles: printmp('Fetching stargazers') users |= set(repo.stargazers()) if 'collaborator' in roles: printmp('Fetching collaborators') users |= set(repo.collabo...
python
{ "resource": "" }
q44556
high_cli
train
def high_cli(repo_name, login, with_blog, as_list, role): """Extract mails from stargazers, collaborators and people involved with issues of given repository. """ passw = getpass.getpass() github = gh_login(login, passw) repo = github.repository(login, repo_name) role = [ROLES[k] for k in ro...
python
{ "resource": "" }
q44557
HeraldBot.__callback
train
def __callback(self, data): """ Safely calls back a method :param data: Associated stanza """ method = self.__cb_message if method is not None: try: method(data) except Exception as ex: _logger.exception("Error call...
python
{ "resource": "" }
q44558
HeraldBot.__on_message
train
def __on_message(self, msg): """ XMPP message received """ msgtype = msg['type'] msgfrom = msg['from'] if msgtype == 'groupchat': # MUC Room chat if self._nick == msgfrom.resource: # Loopback message return e...
python
{ "resource": "" }
q44559
freeze
train
def freeze(ctx, version: str, clean: bool): """ Freeze current package into a single file """ if clean: _clean_spec() ctx.invoke(epab.cmd.compile_qt_resources) _freeze(version)
python
{ "resource": "" }
q44560
_ztanh
train
def _ztanh(Np: int, gridmin: float, gridmax: float) -> np.ndarray: """ typically call via setupz instead """ x0 = np.linspace(0, 3.14, Np) # arbitrarily picking 3.14 as where tanh gets to 99% of asymptote return np.tanh(x0)*gridmax+gridmin
python
{ "resource": "" }
q44561
SiteNotifications.get
train
def get(self, name): """Returns a Notification by name. """ if not self.loaded: raise RegistryNotLoaded(self) if not self._registry.get(name): raise NotificationNotRegistered( f"Notification not registered. Got '{name}'." ) retu...
python
{ "resource": "" }
q44562
SiteNotifications.register
train
def register(self, notification_cls=None): """Registers a Notification class unique by name. """ self.loaded = True display_names = [n.display_name for n in self.registry.values()] if ( notification_cls.name not in self.registry and notification_cls.displa...
python
{ "resource": "" }
q44563
SiteNotifications.notify
train
def notify(self, instance=None, **kwargs): """A wrapper to call notification.notify for each notification class associated with the given model instance. Returns a dictionary of {notification.name: model, ...} including only notifications sent. """ notified = {} ...
python
{ "resource": "" }
q44564
SiteNotifications.update_notification_list
train
def update_notification_list(self, apps=None, schema_editor=None, verbose=False): """Updates the notification model to ensure all registered notifications classes are listed. Typically called from a post_migrate signal. Also, in tests you can register a notification and the Notificatio...
python
{ "resource": "" }
q44565
SiteNotifications.delete_unregistered_notifications
train
def delete_unregistered_notifications(self, apps=None): """Delete orphaned notification model instances. """ Notification = (apps or django_apps).get_model("edc_notification.notification") return Notification.objects.exclude( name__in=[n.name for n in site_notifications.regis...
python
{ "resource": "" }
q44566
SiteNotifications.create_mailing_lists
train
def create_mailing_lists(self, verbose=True): """Creates the mailing list for each registered notification. """ responses = {} if ( settings.EMAIL_ENABLED and self.loaded and settings.EMAIL_BACKEND != "django.core.mail.backends.locmem.Email...
python
{ "resource": "" }
q44567
SiteNotifications.autodiscover
train
def autodiscover(self, module_name=None, verbose=False): """Autodiscovers classes in the notifications.py file of any INSTALLED_APP. """ module_name = module_name or "notifications" verbose = True if verbose is None else verbose sys.stdout.write(f" * checking for {module_...
python
{ "resource": "" }
q44568
CiprCfg.add_package
train
def add_package(self, package): """ Add a package to this project """ self._data.setdefault('packages', {}) self._data['packages'][package.name] = package.source for package in package.deploy_packages: self.add_package(package) self._save()
python
{ "resource": "" }
q44569
touch
train
def touch(): """ Create a .vacationrc file if none exists. """ if not os.path.isfile(get_rc_path()): open(get_rc_path(), 'a').close() print('Created file: {}'.format(get_rc_path()))
python
{ "resource": "" }
q44570
write
train
def write(entries): """ Write an entire rc file. """ try: with open(get_rc_path(), 'w') as rc: rc.writelines(entries) except IOError: print('Error writing your ~/.vacationrc file!')
python
{ "resource": "" }
q44571
append
train
def append(entry): """ Append either a list of strings or a string to our file. """ if not entry: return try: with open(get_rc_path(), 'a') as f: if isinstance(entry, list): f.writelines(entry) else: f.write(entry + '\n') except IOE...
python
{ "resource": "" }
q44572
delete
train
def delete(bad_entry): """ Removes an entry from rc file. """ entries = read() kept_entries = [x for x in entries if x.rstrip() != bad_entry] write(kept_entries)
python
{ "resource": "" }
q44573
sort_func
train
def sort_func(variant=VARIANT1, case_sensitive=False): """A function generator that can be used for sorting. All keywords are passed to `normalize()` and generate keywords that can be passed to `sorted()`:: >>> key = sort_func() >>> print(sorted(["fur", "far"], key=key)) [u'far', u'fur']...
python
{ "resource": "" }
q44574
fetcher
train
def fetcher(date=datetime.today(), url_pattern=URL_PATTERN): """ Fetch json data from n.pl Args: date (date) - default today url_patter (string) - default URL_PATTERN Returns: dict - data from api """ api_url = url_pattern % date.strftime('%Y-%m-%d') headers = {'Re...
python
{ "resource": "" }
q44575
result_to_dict
train
def result_to_dict(raw_result): """ Parse raw result from fetcher into readable dictionary Args: raw_result (dict) - raw data from `fetcher` Returns: dict - readable dictionary """ result = {} for channel_index, channel in enumerate(raw_result): channel_id, channe...
python
{ "resource": "" }
q44576
TaskManager.waitForCompletion
train
def waitForCompletion (self): """Wait for all threads to complete their work The worker threads are told to quit when they receive a task that is a tuple of (None, None). This routine puts as many of those tuples in the task queue as there are threads. As soon as a thread receives one of these tu...
python
{ "resource": "" }
q44577
SIG.token
train
def token(cls: Type[SIGType], pubkey: str) -> SIGType: """ Return SIG instance from pubkey :param pubkey: Public key of the signature issuer :return: """ sig = cls() sig.pubkey = pubkey return sig
python
{ "resource": "" }
q44578
CSV.token
train
def token(cls: Type[CSVType], time: int) -> CSVType: """ Return CSV instance from time :param time: Timestamp :return: """ csv = cls() csv.time = str(time) return csv
python
{ "resource": "" }
q44579
CLTV.token
train
def token(cls: Type[CLTVType], timestamp: int) -> CLTVType: """ Return CLTV instance from timestamp :param timestamp: Timestamp :return: """ cltv = cls() cltv.timestamp = str(timestamp) return cltv
python
{ "resource": "" }
q44580
XHX.token
train
def token(cls: Type[XHXType], sha_hash: str) -> XHXType: """ Return XHX instance from sha_hash :param sha_hash: SHA256 hash :return: """ xhx = cls() xhx.sha_hash = sha_hash return xhx
python
{ "resource": "" }
q44581
Operator.token
train
def token(cls: Type[OperatorType], keyword: str) -> OperatorType: """ Return Operator instance from keyword :param keyword: Operator keyword in expression :return: """ op = cls(keyword) return op
python
{ "resource": "" }
q44582
Condition.token
train
def token(cls: Type[ConditionType], left: Any, op: Optional[Any] = None, right: Optional[Any] = None) -> ConditionType: """ Return Condition instance from arguments and Operator :param left: Left argument :param op: Operator :param right: Right argument :re...
python
{ "resource": "" }
q44583
Condition.compose
train
def compose(self, parser: Any, grammar: Any = None, attr_of: str = None) -> str: """ Return the Condition as string format :param parser: Parser instance :param grammar: Grammar :param attr_of: Attribute of... """ if type(self.left) is Condition: left...
python
{ "resource": "" }
q44584
Parser.load_library
train
def load_library(self, path): ''' Load a template library into the state. ''' module = import_module(path) self.tags.update(module.register.tags) self.helpers.update(module.register.helpers)
python
{ "resource": "" }
q44585
Connection.get_default_logger
train
def get_default_logger(): """Returns default driver logger. :return: logger instance :rtype: logging.Logger """ handler = logging.StreamHandler() handler.setLevel(logging.DEBUG) handler.setFormatter(logging.Formatter( "[%(levelname)1.1s %(asctime)s %(...
python
{ "resource": "" }
q44586
Connection.ensure_connected
train
def ensure_connected(self): """Ensures database connection is still open.""" if not self.is_connected(): if not self._auto_connect: raise DBALConnectionError.connection_closed() self.connect()
python
{ "resource": "" }
q44587
Connection.query
train
def query(self, sql, *args, **kwargs): """Executes an SQL SELECT query, returning a result set as a Statement object. :param sql: query to execute :param args: parameters iterable :param kwargs: parameters iterable :return: result set as a Statement object :rtype: pydbal...
python
{ "resource": "" }
q44588
Connection.begin_transaction
train
def begin_transaction(self): """Starts a transaction by suspending auto-commit mode.""" self.ensure_connected() self._transaction_nesting_level += 1 if self._transaction_nesting_level == 1: self._driver.begin_transaction() elif self._nest_transactions_with_savepoints:...
python
{ "resource": "" }
q44589
Connection.commit
train
def commit(self): """Commits the current transaction.""" if self._transaction_nesting_level == 0: raise DBALConnectionError.no_active_transaction() if self._is_rollback_only: raise DBALConnectionError.commit_failed_rollback_only() self.ensure_connected() ...
python
{ "resource": "" }
q44590
Connection.commit_all
train
def commit_all(self): """Commits all current nesting transactions.""" while self._transaction_nesting_level != 0: if not self._auto_commit and self._transaction_nesting_level == 1: return self.commit() self.commit()
python
{ "resource": "" }
q44591
Connection.rollback
train
def rollback(self): """Cancels any database changes done during the current transaction.""" if self._transaction_nesting_level == 0: raise DBALConnectionError.no_active_transaction() self.ensure_connected() if self._transaction_nesting_level == 1: self._transacti...
python
{ "resource": "" }
q44592
Connection.transaction
train
def transaction(self, callback): """Executes a function in a transaction. The function gets passed this Connection instance as an (optional) parameter. If an exception occurs during execution of the function or transaction commit, the transaction is rolled back and the exception re-thr...
python
{ "resource": "" }
q44593
Connection.set_auto_commit
train
def set_auto_commit(self, auto_commit): """Sets auto-commit mode for this connection. If a connection is in auto-commit mode, then all its SQL statements will be executed and committed as individual transactions. Otherwise, its SQL statements are grouped into transactions that are terminated by...
python
{ "resource": "" }
q44594
Connection.set_transaction_isolation
train
def set_transaction_isolation(self, level): """Sets the transaction isolation level. :param level: the level to set """ self.ensure_connected() self._transaction_isolation_level = level self._platform.set_transaction_isolation(level)
python
{ "resource": "" }
q44595
Connection.get_transaction_isolation
train
def get_transaction_isolation(self): """Returns the currently active transaction isolation level. :return: the current transaction isolation level :rtype: int """ if self._transaction_isolation_level is None: self._transaction_isolation_level = self._platform.get_def...
python
{ "resource": "" }
q44596
Connection.set_nest_transactions_with_savepoints
train
def set_nest_transactions_with_savepoints(self, nest_transactions_with_savepoints): """Sets if nested transactions should use savepoints. :param nest_transactions_with_savepoints: `True` or `False` """ if self._transaction_nesting_level > 0: raise DBALConnectionError.may_not...
python
{ "resource": "" }
q44597
Connection.create_savepoint
train
def create_savepoint(self, savepoint): """Creates a new savepoint. :param savepoint: the name of the savepoint to create :raise: pydbal.exception.DBALConnectionError """ if not self._platform.is_savepoints_supported(): raise DBALConnectionError.savepoints_not_support...
python
{ "resource": "" }
q44598
Connection.release_savepoint
train
def release_savepoint(self, savepoint): """Releases the given savepoint. :param savepoint: the name of the savepoint to release :raise: pydbal.exception.DBALConnectionError """ if not self._platform.is_savepoints_supported(): raise DBALConnectionError.savepoints_not_...
python
{ "resource": "" }
q44599
Connection.rollback_savepoint
train
def rollback_savepoint(self, savepoint): """Rolls back to the given savepoint. :param savepoint: the name of the savepoint to rollback to :raise: pydbal.exception.DBALConnectionError """ if not self._platform.is_savepoints_supported(): raise DBALConnectionError.savep...
python
{ "resource": "" }