_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q53700 | transform_to_mods_multimono | train | def transform_to_mods_multimono(marc_xml, uuid, url):
"""
Convert `marc_xml` to multimonograph MODS data format.
Args:
marc_xml (str): Filename or XML string. Don't use ``\\n`` in case of
filename.
uuid (str): UUID string giving the package ID.
url (str): URL... | python | {
"resource": ""
} |
q53701 | transform_to_mods_periodical | train | def transform_to_mods_periodical(marc_xml, uuid, url):
"""
Convert `marc_xml` to periodical MODS data format.
Args:
marc_xml (str): Filename or XML string. Don't use ``\\n`` in case of
filename.
uuid (str): UUID string giving the package ID.
url (str): URL of... | python | {
"resource": ""
} |
q53702 | type_decisioner | train | def type_decisioner(marc_xml, mono_callback, multimono_callback,
periodical_callback):
"""
Detect type of the `marc_xml`. Call proper callback.
Args:
marc_xml (str): Filename or XML string. Don't use ``\\n`` in case of
filename.
mono_callback (fn ... | python | {
"resource": ""
} |
q53703 | _vax_to_ieee_single_float | train | def _vax_to_ieee_single_float(data):
"""Converts a float in Vax format to IEEE format.
data should be a single string of chars that have been read in from
a binary file. These will be processed 4 at a time into float values.
Thus the total number of byte/chars in the string should be divisible
by 4... | python | {
"resource": ""
} |
q53704 | DB.read_contents | train | def read_contents(self):
'''Read all schemas in database'''
cur = self.conn.cursor()
cur.execute('''select nspname,
description
from pg_catalog.pg_namespace s
left join pg_catalog.pg_description d
... | python | {
"resource": ""
} |
q53705 | scrub | train | def scrub(data):
"""Verify and clean data. Raise error if input fails."""
# blanks, Nones, and empty strings can stay as is
if not data:
return data
if isinstance(data, (int, float)):
return data
if isinstance(data, list):
return [scrub(entry) for entry in data]
if isinst... | python | {
"resource": ""
} |
q53706 | database | train | def database(connection_string, db_class=SimplDB):
"""Return database singleton instance.
This function will always return the same database instance for the same
connection_string. It stores instances in a dict saved as an attribute of
this function.
"""
if not hasattr(database, "singletons"):... | python | {
"resource": ""
} |
q53707 | params_to_mongo | train | def params_to_mongo(query_params):
"""Convert HTTP query params to mongodb query syntax.
Converts the parse query params into a mongodb spec.
:param dict query_params: return of func:`rest.process_params`
"""
if not query_params:
return {}
for key, value in query_params.items():
... | python | {
"resource": ""
} |
q53708 | SimplDB._set_client | train | def _set_client(self):
"""Set client property if not set."""
if self._client is None:
if mongo_proxy:
self._client = mongo_proxy.MongoProxy(
pymongo.MongoClient(self.connection_string),
logger=LOG)
else:
LOG.... | python | {
"resource": ""
} |
q53709 | SimplDB.client | train | def client(self):
"""Return a lazy-instantiated pymongo client.
When running with eventlet, connection causes IO and can result in more
than one MongoDB client getting instantiatied, so we wrap the code in
a semaphore to make sure only one mongodb client is instantiated per
Simp... | python | {
"resource": ""
} |
q53710 | SimplDB.connection | train | def connection(self):
"""Connect to and return mongodb database object."""
if self._connection is None:
self._connection = self.client[self.database_name]
if self.disable_id_injector:
incoming = self._connection._Database__incoming_manipulators
f... | python | {
"resource": ""
} |
q53711 | SimplDB.create_index | train | def create_index(self, collection, index_name, **kwargs):
"""Safely attempt to create index."""
try:
self.connection[collection].create_index(index_name, **kwargs)
except Exception as exc:
LOG.warn("Error tuning mongodb database: %s", exc) | python | {
"resource": ""
} |
q53712 | Collection.update | train | def update(self, key, data):
"""Update document by key with partial data.
Updates the document matching _id=<key> with 'data'
Where 1st argument 'key' is <key>
'data' may contain dot notation fields in
order to specify nested values in the documents, e.g.
colle... | python | {
"resource": ""
} |
q53713 | Collection.list | train | def list(self, offset=0, limit=0, fields=None, sort=None, **kwargs):
"""Return filtered list of documents in a collection.
For text-based search, we support searching on a name/string field by
regex and text index. So strings passed in to a r=text search are
used to filter collections b... | python | {
"resource": ""
} |
q53714 | Collection._cursor | train | def _cursor(self, offset=0, limit=0, fields=None, sort=None, **kwargs):
"""Return a cursor on a filtered list of documents in a collection.
:param offset: for pagination, which record to start attribute
:param limit: for pagination, how many records to return
:param fields: list of fiel... | python | {
"resource": ""
} |
q53715 | Collection.delete | train | def delete(self, key):
"""Delete a document by id."""
assert key, "A key must be supplied for delete operations"
self._collection.remove(spec_or_id={'_id': key})
LOG.debug("DB REMOVE: %s.%s", self.collection_name, key) | python | {
"resource": ""
} |
q53716 | Collection.get | train | def get(self, key):
"""Get a document by id."""
doc = self._collection.find_one({'_id': key})
if doc:
doc.pop('_id')
return doc | python | {
"resource": ""
} |
q53717 | KeyTransform.transform_outgoing | train | def transform_outgoing(self, son, collection):
"""Recursively restore all transformed keys."""
if isinstance(son, dict):
for (key, value) in son.items():
if self.replacement in key:
k = self.revert_key(key)
son[k] = self.transform_outgo... | python | {
"resource": ""
} |
q53718 | PrintFeed | train | def PrintFeed(feed):
"""Example function from Google to print a feed"""
import gdata
for i, entry in enumerate(feed.entry):
if isinstance(feed, gdata.spreadsheet.SpreadsheetsCellsFeed):
print '%s %s\n' % (entry.title.text, entry.content.text)
elif isinstance(feed, gdata.spreadsheet.SpreadsheetsListF... | python | {
"resource": ""
} |
q53719 | Application.parse_application_name | train | def parse_application_name(setup_filename):
"""Parse a setup.py file for the name.
Returns:
name, or None
"""
with open(setup_filename, 'rt') as setup_file:
fst = RedBaron(setup_file.read())
for node in fst:
if (
no... | python | {
"resource": ""
} |
q53720 | Application.build | train | def build(self):
"""Builds the app in the app's environment.
Only builds if the build is out-of-date and is non-empty.
Builds in 3 stages: requirements, dev requirements, and app.
pip is used to install requirements, and setup.py is used to
install the app itself.
Raise... | python | {
"resource": ""
} |
q53721 | Application.generate | train | def generate(self, blueprint, context, interactive=True):
"""Generate a blueprint within this application."""
if not isinstance(blueprint, Blueprint):
bp = self.blueprints.get(blueprint)
if not bp:
raise ValueError('%s is not a valid blueprint' % blueprint)
... | python | {
"resource": ""
} |
q53722 | Application.add | train | def add(self, addon, dev=False, interactive=True):
"""Add a new dependency and install it."""
dependencies = self.get_dependency_manager(dev=dev)
other_dependencies = self.get_dependency_manager(dev=not dev)
existing = dependencies.get(addon)
self.stdout.write(style.format_comman... | python | {
"resource": ""
} |
q53723 | Application.remove | train | def remove(self, addon, dev=False):
"""Remove a dependency and uninstall it."""
dependencies = self.get_dependency_manager(dev=dev)
other_dependencies = self.get_dependency_manager(dev=not dev)
self.stdout.write(style.format_command('Removing', addon))
removed = dependencies.remo... | python | {
"resource": ""
} |
q53724 | make | train | def make(target="all", dir=".", **kwargs):
"""
Run make.
Arguments:
target (str, optional): Name of the target to build. Defaults
to "all".
dir (str, optional): Path to directory containing Makefile.
**kwargs (optional): Any additional arguments to be passed to
... | python | {
"resource": ""
} |
q53725 | VVVVClient.send_msg | train | def send_msg(self, address, args=[]):
""" Send multiple args into a single message to a given address.
Args:
address (str): OSC Address.
args (list): Arguments to be parsed in VVVV.
"""
if not address.startswith('/'):
address = '/{}'.format(address)
... | python | {
"resource": ""
} |
q53726 | lint | train | def lint(args):
"""Run lint checks using flake8."""
application = get_current_application()
if not args:
args = [application.name, 'tests']
args = ['flake8'] + list(args)
run.main(args, standalone_mode=False) | python | {
"resource": ""
} |
q53727 | load_module | train | def load_module(filename):
"""Loads a module from anywhere in the system.
Does not depend on or modify sys.path.
"""
path, name = os.path.split(filename)
name, ext = os.path.splitext(name)
(file, filename, desc) = imp.find_module(name, [path])
try:
return imp.load_module(name, file... | python | {
"resource": ""
} |
q53728 | PythonMTA._start_new_worker_process | train | def _start_new_worker_process(self, server_socket):
"""Start a new child worker process which will listen on the given
socket and return a reference to the new process."""
from multiprocessing import Process
p = Process(target=forked_child, args=self._get_child_args(server_socket))
... | python | {
"resource": ""
} |
q53729 | get_template | train | def get_template(template_name, using=None):
"""
Loads and returns a template for the given name.
Raises TemplateDoesNotExist if no such template exists.
"""
engines = _engine_list(using)
for engine in engines:
try:
return engine.get_template(template_name)
except Tem... | python | {
"resource": ""
} |
q53730 | select_template | train | def select_template(template_name_list, using=None):
"""
Loads and returns a template for one of the given names.
Tries names in order and returns the first template found.
Raises TemplateDoesNotExist if no such template exists.
"""
if isinstance(template_name_list, six.string_types):
ra... | python | {
"resource": ""
} |
q53731 | render_to_string | train | def render_to_string(template_name, context=None, request=None, using=None):
"""
Loads a template and renders it with a context. Returns a string.
template_name may be a string or a list of strings.
"""
if isinstance(template_name, (list, tuple)):
template = select_template(template_name, us... | python | {
"resource": ""
} |
q53732 | spectral_registration | train | def spectral_registration(data, target, initial_guess=(0.0, 0.0), frequency_range=None):
"""
Performs the spectral registration method to calculate the frequency and
phase shifts between the input data and the reference spectrum target. The
frequency range over which the two spectra are compared can be ... | python | {
"resource": ""
} |
q53733 | get_adapter_path | train | def get_adapter_path(obj, to_cls):
"""
Returns the adapter path that would be used to adapt `obj` to `to_cls`.
"""
from_cls = type(obj)
key = (from_cls, to_cls)
if key not in __mro__:
__mro__[key] = list(itertools.product(inspect.getmro(from_cls), inspect.getmro(to_cls)))
return __m... | python | {
"resource": ""
} |
q53734 | adapt | train | def adapt(obj, to_cls):
"""
Will adapt `obj` to an instance of `to_cls`.
First sees if `obj` has an `__adapt__` method and uses it to adapt. If that fails
it checks if `to_cls` has an `__adapt__` classmethod and uses it to adapt. IF that
fails, MRO is used. If that
fails, a `TypeError` is raise... | python | {
"resource": ""
} |
q53735 | register_adapter | train | def register_adapter(from_classes, to_classes, func):
"""
Register a function that can handle adapting from `from_classes` to `to_classes`.
"""
assert from_classes, 'Must supply classes to adapt from'
assert to_classes, 'Must supply classes to adapt to'
assert func, 'Must supply adapter function... | python | {
"resource": ""
} |
q53736 | AdaptErrors.errors_string | train | def errors_string(self):
"""
Returns all errors as a string
"""
output = []
for e in self.errors:
output.append('%s: %s in %s:' % (e[1], e[2], e[0]))
output.append(''.join(traceback.format_tb(e[3])))
return '\n'.join(output) | python | {
"resource": ""
} |
q53737 | ScriptEditor.on_close | train | def on_close(self):
"""
Defines the slot triggered on Framework close.
"""
LOGGER.debug("> Calling '{0}' Component Framework 'on_close' method.".format(self.__class__.__name__))
map(self.unregister_file, self.list_files())
if self.store_session() and self.close_all_fil... | python | {
"resource": ""
} |
q53738 | ScriptEditor.__initialize_languages_model | train | def __initialize_languages_model(self):
"""
Initializes the languages Model.
"""
languages = [PYTHON_LANGUAGE, LOGGING_LANGUAGE, TEXT_LANGUAGE]
existingGrammarFiles = [os.path.normpath(language.file) for language in languages]
for directory in RuntimeGlobals.resources_d... | python | {
"resource": ""
} |
q53739 | ScriptEditor.__handle_dropped_content | train | def __handle_dropped_content(self, event):
"""
Handles dopped content event.
:param event: Content dropped event.
:type event: QEvent
"""
if not event.mimeData().hasUrls():
return
urls = event.mimeData().urls()
self.__engine.start_processin... | python | {
"resource": ""
} |
q53740 | ScriptEditor.__get_supported_file_types_string | train | def __get_supported_file_types_string(self):
"""
Returns the supported file types dialog string.
"""
languages = ["All Files (*)"]
for language in self.__languages_model.languages:
languages.append("{0} Files ({1})".format(language.name,
... | python | {
"resource": ""
} |
q53741 | ScriptEditor.__set_recent_files_actions | train | def __set_recent_files_actions(self):
"""
Sets the recent files actions.
"""
recentFiles = [foundations.strings.to_string(file)
for file in self.__settings.get_key(self.__settings_section, "recentFiles").toStringList()
if foundations.common.... | python | {
"resource": ""
} |
q53742 | ScriptEditor.__store_recent_file | train | def __store_recent_file(self, file):
"""
Stores given recent file into the settings.
:param file: File to store.
:type file: unicode
"""
LOGGER.debug("> Storing '{0}' file in recent files.".format(file))
recentFiles = [foundations.strings.to_string(recentFile)
... | python | {
"resource": ""
} |
q53743 | ScriptEditor.__set_window_title | train | def __set_window_title(self):
"""
Sets the Component window title.
"""
if self.has_editor_tab():
windowTitle = "{0} - {1}".format(self.__default_window_title, self.get_current_editor().file)
else:
windowTitle = "{0}".format(self.__default_window_title)
... | python | {
"resource": ""
} |
q53744 | ScriptEditor.__get_untitled_file_name | train | def __get_untitled_file_name(self):
"""
Returns an untitled file name.
:return: Untitled file name.
:rtype: unicode
"""
untitledNameId = Editor._Editor__untitled_name_id
for file in self.list_files():
if not os.path.dirname(file) == self.__default_se... | python | {
"resource": ""
} |
q53745 | ScriptEditor.get_focus_widget | train | def get_focus_widget(self):
"""
Returns the Widget with focus.
:return: Widget with focus.
:rtype: QWidget
"""
current_widget = QApplication.focusWidget()
if current_widget is None:
return False
if current_widget.objectName() == "Script_Edit... | python | {
"resource": ""
} |
q53746 | ScriptEditor.load_path | train | def load_path(self, path):
"""
Loads given path.
:param path: Path to load.
:type path: unicode
:return: Method success.
:rtype: bool
"""
if not foundations.common.path_exists(path):
return False
if os.path.isfile(path):
... | python | {
"resource": ""
} |
q53747 | ScriptEditor.add_project | train | def add_project(self, path):
"""
Adds a project.
:param path: Project path.
:type path: unicode
:return: Method success.
:rtype: bool
"""
if not foundations.common.path_exists(path):
return False
path = os.path.normpath(path)
... | python | {
"resource": ""
} |
q53748 | ScriptEditor.remove_project | train | def remove_project(self, path):
"""
Removes a project.
:param path: Project path.
:type path: unicode
:return: Method success.
:rtype: bool
"""
project_node = foundations.common.get_first_item(self.__model.get_project_nodes(path))
if not project_... | python | {
"resource": ""
} |
q53749 | ScriptEditor.get_editor | train | def get_editor(self, file):
"""
Returns the Model editor associated with given file.
:param file: File to search editors for.
:type file: unicode
:return: Editor.
:rtype: Editor
"""
for editor in self.__model.list_editors():
if editor.file ==... | python | {
"resource": ""
} |
q53750 | ScriptEditor.set_language | train | def set_language(self, editor, language):
"""
Sets given language to given Model editor.
:param editor: Editor to set language to.
:type editor: Editor
:param language: Language to set.
:type language: Language
:return: Method success.
:rtype: bool
... | python | {
"resource": ""
} |
q53751 | ScriptEditor.evaluate_code | train | def evaluate_code(self, code):
"""
Evaluates given code into the interactive console.
:param code: Code to evaluate.
:type code: unicode
:return: Method success.
:rtype: bool
"""
if not code:
return False
LOGGER.debug("> Evaluating g... | python | {
"resource": ""
} |
q53752 | ScriptEditor.store_session | train | def store_session(self):
"""
Stores the current session.
:return: Method success.
:rtype: bool
"""
session = []
for editor in self.list_editors():
file = editor.file
ignore_file = True
if editor.is_untitled and not editor.is_e... | python | {
"resource": ""
} |
q53753 | ScriptEditor.restore_session | train | def restore_session(self):
"""
Restores the stored session.
:return: Method success.
:rtype: bool
"""
session = [foundations.strings.to_string(path)
for path in self.__settings.get_key(self.__settings_section, "session").toStringList()
... | python | {
"resource": ""
} |
q53754 | ScriptEditor.loop_through_editors | train | def loop_through_editors(self, backward=False):
"""
Loops through the editor tabs.
:param backward: Looping backward.
:type backward: bool
:return: Method success.
:rtype: bool
"""
step = not backward and 1 or -1
idx = self.Script_Editor_tabWidge... | python | {
"resource": ""
} |
q53755 | ScriptEditor.restore_development_layout | train | def restore_development_layout(self):
"""
Restores the development layout.
:return: Definition success.
:rtype: bool
"""
if self.__engine.layouts_manager.current_layout != self.__development_layout and not self.isVisible():
self.__engine.layouts_manager.rest... | python | {
"resource": ""
} |
q53756 | estimate | train | def estimate(phenotype, G=None, K=None, covariates=None, overdispersion=True):
"""Estimate the so-called narrow-sense heritability.
It supports Bernoulli and Binomial phenotypes (see `outcome_type`).
The user must specifiy only one of the parameters G, K, and QS for
defining the genetic background.
... | python | {
"resource": ""
} |
q53757 | TransactionsInterface.retrieve_mtm_results | train | def retrieve_mtm_results(self, book_id, asset_manager_id, paramaters):
"""
parameters is a dictionary of all the mtm result filter parameters
"""
self.logger.info('Retrieving mtm Positions - Asset Manager: %s', asset_manager_id)
url = '%s/mtm/%s' % (self.endpoint, asset_manager_i... | python | {
"resource": ""
} |
q53758 | TransactionsInterface.pnl_search | train | def pnl_search(self, asset_manager_id, pnl_type, business_date,
**kwargs):
"""
Search pnl records.
Args:
asset_manager_id (int): id of asset manager owning the pnl records
pnl_type (str): either "Position" or "Transaction
business_date (dat... | python | {
"resource": ""
} |
q53759 | TransactionsInterface.pnl_cancel | train | def pnl_cancel(self, asset_manager_id, pnl_type,
business_date, book_id,
next_hash_key=None, next_range_key=None,
page_size=None):
"""
Cancel the PNL records matching the request
Args:
asset_manager_id (int): id of asset manag... | python | {
"resource": ""
} |
q53760 | TransactionsInterface.clear | train | def clear(self, asset_manager_id, book_ids=None):
""" This method deletes all the data for an asset_manager_id
and option book_ids.
It should be used with extreme caution. In production it
is almost always better to Inactivate rather than delete. """
self.logger.info... | python | {
"resource": ""
} |
q53761 | Dict.join | train | def join(self, dic):
""" Add dic pairs to self.data """
for k,v in dic.iteritems():
if k in self.data:
self[k] += dic[k]
else:
self[k] = deepcopy(v)
return self | python | {
"resource": ""
} |
q53762 | Dict.map | train | def map(self, callable):
""" Apply 'callable' function over all values. """
for k,v in self.iteritems():
self[k] = callable(v) | python | {
"resource": ""
} |
q53763 | Dict.fromrepetitions | train | def fromrepetitions(cls, iterable):
""" Create a dict whose keys are the members of the iterable and values
are the number of times the key appears in the iterable.
"""
d = cls()
for key in iterable:
d[key] = d[key] + 1 if key in d else 1
return d | python | {
"resource": ""
} |
q53764 | Dict.relookup | train | def relookup(self, pattern):
""" Dictionary lookup with a regular expression. Return pairs whose key
matches pattern.
"""
key = re.compile(pattern)
return filter(lambda x : key.match(x[0]), self.data.items()) | python | {
"resource": ""
} |
q53765 | _get_corenlp_version | train | def _get_corenlp_version():
"Return the corenlp version pointed at by CORENLP_HOME, or None"
corenlp_home = os.environ.get("CORENLP_HOME")
if corenlp_home:
for fn in os.listdir(corenlp_home):
m = re.match("stanford-corenlp-([\d.]+)-models.jar", fn)
if m:
retur... | python | {
"resource": ""
} |
q53766 | StanfordCoreNLP.read_output_lines | train | def read_output_lines(self):
"intended to be run as background thread to collect parser output"
while True:
chars = self.corenlp_process.stdout.readline()
if chars == '': # EOF
break
self.out.write(chars) | python | {
"resource": ""
} |
q53767 | StanfordCoreNLP.parse | train | def parse(self, text):
"""Call the server and return the raw results."""
if isinstance(text, bytes):
text = text.decode("ascii")
text = re.sub("\s+", " ", unidecode(text))
return self.communicate(text + "\n") | python | {
"resource": ""
} |
q53768 | KarmaAdv.message | train | def message(self, bot, comm):
"""
Check for strings ending with 2 or more '-' or '+'
"""
super(KarmaAdv, self).message(bot, comm)
# No directed karma giving or taking
if not comm['directed'] and not comm['pm']:
msg = comm['message'].strip().lower()
... | python | {
"resource": ""
} |
q53769 | KarmaAdv.modify_karma | train | def modify_karma(self, words):
"""
Given a regex object, look through the groups and modify karma
as necessary
"""
# 'user': karma
k = defaultdict(int)
if words:
# For loop through all of the group members
for word_tuple in words:
... | python | {
"resource": ""
} |
q53770 | KarmaAdv.update_db | train | def update_db(self, giver, receiverkarma):
"""
Record a the giver of karma, the receiver of karma, and the karma
amount. Typically the count will be 1, but it can be any positive or
negative integer.
"""
for receiver in receiverkarma:
if receiver != giver:
... | python | {
"resource": ""
} |
q53771 | info | train | def info():
"""Display app info.
Examples:
$ dj info
No application, try running dj init.
$ dj info
Application:
foo @ 2.7.9
Requirements:
Django == 1.10
"""
application = get_current_application()
info = application.info()
stdout.write(info)
return info | python | {
"resource": ""
} |
q53772 | Application_QToolBar.set_toolbar_children_widgets | train | def set_toolbar_children_widgets(self):
"""
Sets the toolBar children widgets.
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> Adding 'Application_Logo_label' widget!")
self.addWidget(self.get_application_logo_label())
LOGGER.debug("> Adding '... | python | {
"resource": ""
} |
q53773 | sup_of_layouts | train | def sup_of_layouts(layout1, layout2):
""" Return the least layout compatible with layout1 and layout2 """
if len(layout1) > len(layout2):
layout1, layout2 = layout2, layout1
if len(layout1) < len(layout2):
layout1 += [0] * (len(layout2) - len(layout1))
ret... | python | {
"resource": ""
} |
q53774 | Table.layout | train | def layout(self):
""" Calculate the widths of the columns to set the table """
ret = []
for row in self.rows:
if len(row) > len(ret):
ret += [0] * (len(row) - len(ret))
for n, field in enumera... | python | {
"resource": ""
} |
q53775 | plotLattice | train | def plotLattice(beamlinepatchlist,
fignum=1, fig_size=20, fig_ratio=0.5,
xranges=(-10, 10), yranges=(-10, 10),
zoomfac=1.5):
"""
function plot beamline defined by ``beamlinepatchlist``, which is a set of patches for all elements
:param beamlinepatchlist: gene... | python | {
"resource": ""
} |
q53776 | Book.utc_book_close_time | train | def utc_book_close_time(self):
"""
The book close time in utc.
"""
tz = pytz.timezone(self.timezone)
close_time = datetime.datetime.strptime(self.close_time, '%H:%M:%S').time()
close_time = tz.localize(datetime.datetime.combine(datetime.datetime.now(tz), close_time))
... | python | {
"resource": ""
} |
q53777 | uibei | train | def uibei(order, energy_lo, temp, chem_potential):
"""
Upper incomplete Bose-Einstein integral.
The upper incomplete Bose-Einstein integral is given by (cf. Levy and Honsberg :cite:`10.1016/j.sse.2006.06.017`):
.. math::
F_{m}(E_{A},T,\mu) = \\frac{2 \pi}{h^{3}c^{2}} \int_{E_{A}}^{\infty} E^{... | python | {
"resource": ""
} |
q53778 | main | train | def main(argv=None):
"""Entry point for the `simpl` command."""
#
# `simpl server`
#
logging.basicConfig(level=logging.INFO)
server_func = functools.partial(server.main, argv=argv)
server_parser = server.attach_parser(default_subparser())
server_parser.set_defaults(_func=server_func)
... | python | {
"resource": ""
} |
q53779 | _find_project_config_file | train | def _find_project_config_file(user_config_file):
"""Find path to project-wide config file
Search from current working directory, and traverse path up to
directory with .versionner.rc file or root directory
:param user_config_file: instance with user-wide config path
:type: pathlib.Path
:rtype: ... | python | {
"resource": ""
} |
q53780 | execute | train | def execute(prog, argv):
"""Execute whole program
:param prog: program name
:param argv: list: script arguments
:return:
"""
if pathlib.Path(prog).parts[-1] in ('versionner', 'versionner.py'):
print("versionner name is deprecated, use \"ver\" now!", file=sys.stderr)
cfg_files = [
... | python | {
"resource": ""
} |
q53781 | run_deploy_website | train | def run_deploy_website(restart_apache=False, restart_uwsgi=False,
restart_nginx=False):
"""
Executes all tasks necessary to deploy the website on the given server.
Usage::
fab <server> run_deploy_website
"""
run_git_pull()
run_pip_install()
run_rsync_project... | python | {
"resource": ""
} |
q53782 | run_download_media | train | def run_download_media(filename=None):
"""
Downloads the media dump from the server into your local machine.
In order to import the downloaded media dump, run ``fab import_media``
Usage::
fab prod run_download_media
fab prod run_download_media:filename=foobar.tar.gz
"""
if no... | python | {
"resource": ""
} |
q53783 | run_export_db | train | def run_export_db(filename=None):
"""
Exports the database on the server.
Usage::
fab prod run_export_db
fab prod run_export_db:filename=foobar.dump
"""
if not filename:
filename = settings.DB_DUMP_FILENAME
with cd(settings.FAB_SETTING('SERVER_PROJECT_ROOT')):
... | python | {
"resource": ""
} |
q53784 | run_export_media | train | def run_export_media(filename=None):
"""
Exports the media folder on the server.
Usage::
fab prod run_export_media
fab prod run_export_media:filename=foobar.tar.gz
"""
if not filename:
filename = settings.MEDIA_DUMP_FILENAME
with cd(settings.FAB_SETTING('SERVER_MEDIA_... | python | {
"resource": ""
} |
q53785 | run_pip_install | train | def run_pip_install(upgrade=0):
"""
Installs the requirement.txt file on the given server.
Usage::
fab <server> run_pip_install
fab <server> run_pip_install:upgrade=1
:param upgrade: If set to 1, the command will be executed with the
``--upgrade`` flag.
"""
command = 'p... | python | {
"resource": ""
} |
q53786 | run_rsync_project | train | def run_rsync_project():
"""
Copies the project from the git repository to it's destination folder.
This has the nice side effect of rsync deleting all ``.pyc`` files and
removing other files that might have been left behind by sys admins messing
around on the server.
Usage::
fab <ser... | python | {
"resource": ""
} |
q53787 | run_upload_db | train | def run_upload_db(filename=None):
"""
Uploads your local database to the server.
You can create a local dump with ``fab export_db`` first.
In order to import the database on the server you still need to SSH into
the server.
Usage::
fab prod run_upload_db
fab prod run_upload_d... | python | {
"resource": ""
} |
q53788 | get_version | train | def get_version(version=None):
"""Derives a PEP386-compliant version number from VERSION."""
if version is None:
version = VERSION
assert len(version) == 5
assert version[3] in ('alpha', 'beta', 'rc', 'final')
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub =... | python | {
"resource": ""
} |
q53789 | register_service | train | def register_service(email, password, organisation_id, name=None,
service_type=None, accounts_url=None,
location=None, config=None):
"""Register a service with the accounts service
\b
EMAIL: a user's email
PASSWORD: a user's password
ORGANISATION_ID: ID of ... | python | {
"resource": ""
} |
q53790 | _options | train | def _options():
"""Collect all command line options"""
opts = sys.argv[1:]
return [click.Option((v.split('=')[0],)) for v in opts
if v[0] == '-' and v != '--help'] | python | {
"resource": ""
} |
q53791 | run | train | def run(func):
"""Execute the provided function if there are no subcommands"""
@defaults.command(help='Run the service')
@click.pass_context
def runserver(ctx, *args, **kwargs):
if (ctx.parent.invoked_subcommand and
ctx.command.name != ctx.parent.invoked_subcommand):
... | python | {
"resource": ""
} |
q53792 | cli | train | def cli(main, conf_dir=None, commands_dir=None):
"""Convenience function for initialising a Command CLI
For parameter definitions see :class:`.Command`
"""
return Command(main, conf_dir=conf_dir, commands_dir=commands_dir)() | python | {
"resource": ""
} |
q53793 | Command.list_commands | train | def list_commands(self, ctx):
"""List commands from the commands dir and default group"""
rv = defaults.list_commands(ctx)
if self._commands_dir:
for filename in os.listdir(self._commands_dir):
if _is_command_file(filename) and filename[:-3] not in rv:
... | python | {
"resource": ""
} |
q53794 | Command.get_command | train | def get_command(self, ctx, name):
"""Get the command from either the commands dir or default group"""
if not self._commands_dir:
return defaults.get_command(ctx, name)
ns = {}
fn = os.path.join(self._commands_dir, name + '.py')
try:
with open(fn) as f:
... | python | {
"resource": ""
} |
q53795 | Response._check_for_inception | train | def _check_for_inception(self, root_dict):
'''
Used to check if there is a dict in a dict
'''
for key, value in root_dict.items():
if isinstance(value, dict):
root_dict[key] = Response(value)
return root_dict | python | {
"resource": ""
} |
q53796 | FTPMonitorDaemon.body | train | def body(self):
"""
This method handles AMQP connection details and reacts to FTP events by
sending messages to output queue.
"""
self.connection = pika.BlockingConnection(self.connection_param)
self.channel = self.connection.channel()
print "Monitoring file '%s'... | python | {
"resource": ""
} |
q53797 | default_roles | train | def default_roles(*role_list):
"""Decorate task with these roles by default, but override with -R, -H"""
def selectively_attach(func):
"""Only decorate if nothing specified on command line"""
# pylint: disable=W0142
if not env.roles and not env.hosts:
return roles(*role_list)... | python | {
"resource": ""
} |
q53798 | chown | train | def chown(dirs, user=None, group=None):
"""User sudo to set user and group ownership"""
if isinstance(dirs, basestring):
dirs = [dirs]
args = ' '.join(dirs)
if user and group:
return sudo('chown {}:{} {}'.format(user, group, args))
elif user:
return sudo('chown {} {}'.format(... | python | {
"resource": ""
} |
q53799 | chput | train | def chput(local_path=None, remote_path=None, user=None, group=None,
mode=None, use_sudo=True, mirror_local_mode=False, check=True):
"""Put file and set user and group ownership. Default to use sudo."""
# pylint: disable=R0913
result = None
if env.get('full') or not check or diff(local_path, r... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.