_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q50700 | BaruwaAPIClient.update_organization | train | def update_organization(self, orgid, data):
"""Update an organization"""
return self.api_call(
ENDPOINTS['organizations']['update'],
dict(orgid=orgid),
body=data) | python | {
"resource": ""
} |
q50701 | BaruwaAPIClient.create_relay | train | def create_relay(self, orgid, data):
"""Create relay settings"""
return self.api_call(
ENDPOINTS['relays']['new'],
dict(orgid=orgid), body=data) | python | {
"resource": ""
} |
q50702 | BaruwaAPIClient.update_relay | train | def update_relay(self, relayid, data):
"""Update relay settings"""
return self.api_call(
ENDPOINTS['relays']['update'],
dict(relayid=relayid),
body=data) | python | {
"resource": ""
} |
q50703 | BaruwaAPIClient.delete_relay | train | def delete_relay(self, relayid, data):
"""Delete relay settings"""
return self.api_call(
ENDPOINTS['relays']['delete'],
dict(relayid=relayid),
body=data) | python | {
"resource": ""
} |
q50704 | BaruwaAPIClient.get_fallbackservers | train | def get_fallbackservers(self, orgid, page=None):
"""Get Fallback server"""
opts = {}
if page:
opts['page'] = page
return self.api_call(
ENDPOINTS['fallbackservers']['list'],
dict(orgid=orgid), **opts) | python | {
"resource": ""
} |
q50705 | BaruwaAPIClient.create_fallbackserver | train | def create_fallbackserver(self, orgid, data):
"""Create Fallback server"""
return self.api_call(
ENDPOINTS['fallbackservers']['new'],
dict(orgid=orgid), body=data) | python | {
"resource": ""
} |
q50706 | BaruwaAPIClient.update_fallbackserver | train | def update_fallbackserver(self, serverid, data):
"""Update Fallback server"""
return self.api_call(
ENDPOINTS['fallbackservers']['update'],
dict(serverid=serverid),
body=data) | python | {
"resource": ""
} |
q50707 | BaruwaAPIClient.delete_fallbackserver | train | def delete_fallbackserver(self, serverid, data):
"""Delete Fallback server"""
return self.api_call(
ENDPOINTS['fallbackservers']['delete'],
dict(serverid=serverid),
body=data) | python | {
"resource": ""
} |
q50708 | BaruwaAPIClient.get_org_smarthost | train | def get_org_smarthost(self, orgid, serverid):
"""Get an organization smarthost"""
return self.api_call(
ENDPOINTS['orgsmarthosts']['get'],
dict(orgid=orgid, serverid=serverid)) | python | {
"resource": ""
} |
q50709 | BaruwaAPIClient.create_org_smarthost | train | def create_org_smarthost(self, orgid, data):
"""Create an organization smarthost"""
return self.api_call(
ENDPOINTS['orgsmarthosts']['new'],
dict(orgid=orgid),
body=data) | python | {
"resource": ""
} |
q50710 | BaruwaAPIClient.update_org_smarthost | train | def update_org_smarthost(self, orgid, serverid, data):
"""Update an organization smarthost"""
return self.api_call(
ENDPOINTS['orgsmarthosts']['update'],
dict(orgid=orgid, serverid=serverid),
body=data) | python | {
"resource": ""
} |
q50711 | _backup_file | train | def _backup_file(path):
"""
Backup a file but never overwrite an existing backup file
"""
backup_base = '/var/local/woven-backup'
backup_path = ''.join([backup_base,path])
if not exists(backup_path):
directory = ''.join([backup_base,os.path.split(path)[0]])
sudo('mkdir -p %s'% di... | python | {
"resource": ""
} |
q50712 | _restore_file | train | def _restore_file(path, delete_backup=True):
"""
Restore a file if it exists and remove the backup
"""
backup_base = '/var/local/woven-backup'
backup_path = ''.join([backup_base,path])
if exists(backup_path):
if delete_backup:
sudo('mv -f %s %s'% (backup_path,path))
e... | python | {
"resource": ""
} |
q50713 | _get_local_files | train | def _get_local_files(local_dir, pattern=''):
"""
Returns a dictionary with directories as keys, and filenames as values
for filenames matching the glob ``pattern`` under the ``local_dir``
``pattern can contain the Boolean OR | to evaluated multiple patterns into
a combined set.
"""
local_fi... | python | {
"resource": ""
} |
q50714 | mkdirs | train | def mkdirs(remote_dir, use_sudo=False):
"""
Wrapper around mkdir -pv
Returns a list of directories created
"""
func = use_sudo and sudo or run
result = func(' '.join(['mkdir -pv',remote_dir])).split('\n')
#extract dir list from ["mkdir: created directory `example.com/some/dir'"]
if ... | python | {
"resource": ""
} |
q50715 | upload_template | train | def upload_template(filename, destination, context={}, use_sudo=False, backup=True, modified_only=False):
"""
Render and upload a template text file to a remote host using the Django
template api.
``filename`` should be the Django template name.
``context`` is the Django template dictionar... | python | {
"resource": ""
} |
q50716 | VersionBump.pre_release | train | def pre_release(self):
""" Return true if version is a pre-release. """
label = self.version_info.get('label', None)
pre = self.version_info.get('pre', None)
return True if (label is not None and pre is not None) else False | python | {
"resource": ""
} |
q50717 | VersionBump.bump | train | def bump(self, level='patch', label=None):
""" Bump version following semantic versioning rules. """
bump = self._bump_pre if level == 'pre' else self._bump
bump(level, label) | python | {
"resource": ""
} |
q50718 | VersionBump.zeroize_after_level | train | def zeroize_after_level(self, base_level):
""" Set all levels after ``base_level`` to zero. """
index = _LEVELS.index(base_level) + 1
for level in _LEVELS[index:]:
self.version_info[level] = 0 | python | {
"resource": ""
} |
q50719 | VersionBump.get_version | train | def get_version(self):
""" Return complete version string. """
version = '{major}.{minor}.{patch}'.format(**self.version_info)
if self.pre_release:
version = '{}-{label}.{pre}'.format(version, **self.version_info)
return version | python | {
"resource": ""
} |
q50720 | Router.get | train | def get(self, request):
'''Simply list test urls
'''
data = {}
for router in self.routes:
data[router.name] = request.absolute_uri(router.path())
return Json(data).http_response(request) | python | {
"resource": ""
} |
q50721 | Router.db | train | def db(self, request):
'''Single Database Query'''
with self.mapper.begin() as session:
world = session.query(World).get(randint(1, 10000))
return Json(self.get_json(world)).http_response(request) | python | {
"resource": ""
} |
q50722 | Router.queries | train | def queries(self, request):
'''Multiple Database Queries'''
queries = self.get_queries(request)
worlds = []
with self.mapper.begin() as session:
for _ in range(queries):
world = session.query(World).get(randint(1, MAXINT))
worlds.append(self.ge... | python | {
"resource": ""
} |
q50723 | Covariance._initParams | train | def _initParams(self):
"""
initialize paramters to vector of zeros
"""
params = SP.zeros(self.getNumberParams())
self.setParams(params) | python | {
"resource": ""
} |
q50724 | make_message | train | def make_message(message, binary=False):
"""Make text message."""
if isinstance(message, str):
message = message.encode('utf-8')
if binary:
return _make_frame(message, OPCODE_BINARY)
else:
return _make_frame(message, OPCODE_TEXT) | python | {
"resource": ""
} |
q50725 | shell_command | train | def shell_command():
"""Runs an interactive Python shell in the context of a given
Flask application. The application will populate the default
namespace of this shell according to its configuration.
This is useful for executing small snippets of management code
without having to manually configur... | python | {
"resource": ""
} |
q50726 | upload | train | def upload():
"""Uploads to PyPI"""
env=os.environ.copy()
print(env)
env['PYTHONPATH']= "./pynt"
print(env)
# subprocess.call(['ssh-add', '~/.ssh/id_rsa'])
pipe=subprocess.Popen(['python', 'setup.py', 'sdist','upload'], env=env)
pipe.wait() | python | {
"resource": ""
} |
q50727 | Parguments.command | train | def command(self, func):
"""
Decorator to add a command function to the registry.
:param func: command function.
"""
command = Command(func)
self._commands[func.__name__] = command
return func | python | {
"resource": ""
} |
q50728 | Parguments.add_command | train | def add_command(self, func, name=None, doc=None):
"""
Add a command function to the registry.
:param func: command function.
:param name: default name of func.
:param doc: description of the func.default docstring of func.
"""
command = Command(func, doc)
... | python | {
"resource": ""
} |
q50729 | Parguments.run | train | def run(self, command=None, argv=None, help=True, exit=True):
"""
Parse arguments and run the funcs.
:param command: name of command to run. default argv[0]
:param argv: argument vector to be parsed.
sys.argv[1:] is used if not provided.
:param help: Set to False to ... | python | {
"resource": ""
} |
q50730 | assert_200 | train | def assert_200(response, max_len=500):
""" Check that a HTTP response returned 200. """
if response.status_code == 200:
return
raise ValueError(
"Response was {}, not 200:\n{}\n{}".format(
response.status_code,
json.dumps(dict(response.headers), indent=2),
response.content... | python | {
"resource": ""
} |
q50731 | url_as_file | train | def url_as_file(url, ext=None):
"""
Context manager that GETs a given `url` and provides it as a local file.
The file is in a closed state upon entering the context,
and removed when leaving it, if still there.
To give the file name a specific extension, use `ext`;
the exte... | python | {
"resource": ""
} |
q50732 | Cache.add_content | train | def add_content(self, **content):
"""
Adds given content to the cache.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache
{'Luke': 'Skywalker', 'John': 'Doe'}
:param \*\*content: Co... | python | {
"resource": ""
} |
q50733 | Cache.remove_content | train | def remove_content(self, *keys):
"""
Removes given content from the cache.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache.remove_content("Luke", "John")
True
>>> cache
... | python | {
"resource": ""
} |
q50734 | Cache.get_content | train | def get_content(self, key):
"""
Gets given content from the cache.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache.get_content("Luke")
'Skywalker'
:param key: Content to retrieve... | python | {
"resource": ""
} |
q50735 | Cache.flush_content | train | def flush_content(self):
"""
Flushes the cache content.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache.flush_content()
True
>>> cache
{}
:return: Method ... | python | {
"resource": ""
} |
q50736 | post | train | def post(arguments):
'''Post text to a given twitter account.'''
twitter = api.API(arguments)
params = {}
if arguments.update == '-':
params['status'] = sys.stdin.read()
else:
params['status'] = arguments.update
if arguments.media_file:
medias = [twitter.media_upload(m)... | python | {
"resource": ""
} |
q50737 | SSO.sso_api_list | train | def sso_api_list():
"""
return sso related API
"""
ssourls = []
def collect(u, prefixre, prefixname):
_prefixname = prefixname + [u._regex, ]
urldisplayname = " ".join(_prefixname)
if hasattr(u.urlconf_module, "_MODULE_MAGIC_ID_") \
... | python | {
"resource": ""
} |
q50738 | Features._simplify_feature_value | train | def _simplify_feature_value(self, name, value):
"""Return simplified and more pythonic feature values."""
if name == 'prefix':
channel_modes, channel_chars = value.split(')')
channel_modes = channel_modes[1:]
# [::-1] to reverse order and go from lowest to highest pr... | python | {
"resource": ""
} |
q50739 | Splitter._splitGenoGeneWindow | train | def _splitGenoGeneWindow(self,annotation_file=None,cis=1e4,funct='protein_coding',minSnps=1.,maxSnps=SP.inf):
"""
split into windows based on genes
"""
#1. load annotation
assert annotation_file is not None, 'Splitter:: specify annotation file'
try:
f = h5py.... | python | {
"resource": ""
} |
q50740 | check_is_created | train | def check_is_created(method):
""" Make sure the Object DOES have an id, already. """
def check(self, *args, **kwargs):
if self.id is None:
raise NotCreatedError('%s does not exists.' %
self.__class__.__name__)
return method(self, *args, **kwargs)
... | python | {
"resource": ""
} |
q50741 | check_is_not_created | train | def check_is_not_created(method):
""" Make sure the Object does NOT have an id, yet. """
def check(self, *args, **kwargs):
if self.id is not None:
raise AlreadyCreatedError('%s.id %s already exists.' %
(self.__class__.__name__, self.id))
return me... | python | {
"resource": ""
} |
q50742 | asynchronous | train | def asynchronous(method):
""" Convenience wrapper for GObject.idle_add. """
def _async(*args, **kwargs):
GObject.idle_add(method, *args, **kwargs)
return _async | python | {
"resource": ""
} |
q50743 | parent | train | def parent(version=None, include=None):
'''
Return the default args as a parent parser, optionally adding a version
Args:
version (str): version to return on <cli> --version
include (Sequence): default arguments to add to cli. Default: (config, user, dry-run, verbose, quiet)
'''
par... | python | {
"resource": ""
} |
q50744 | add_logger | train | def add_logger(name, level=None, format=None):
'''
Set up a stdout logger.
Args:
name (str): name of the logger
level: defaults to logging.INFO
format (str): format string for logging output.
defaults to ``%(filename)-11s %(lineno)-3d: %(message)s``.
Retur... | python | {
"resource": ""
} |
q50745 | Provider.create_session | train | def create_session(self, user_agent, remote_address, client_version):
"""
Create a new session.
:param str user_agent: Client user agent
:param str remote_addr: Remote address of client
:param str client_version: Remote client version
:return: The new session id
... | python | {
"resource": ""
} |
q50746 | Provider.get_next_revision | train | def get_next_revision(self, session_id, revision, delta):
"""
Determine the next revision number for a given session id, revision
and delta.
In case the client is up-to-date, this method will block until the next
revision is available.
:param int session_id: Session ide... | python | {
"resource": ""
} |
q50747 | Provider.update | train | def update(self):
"""
Update this provider. Should be invoked when the server gets updated.
This method will notify all clients that wait for
`self.next_revision_available`.
"""
with self.lock:
# Increment revision and commit it.
self.revision +=... | python | {
"resource": ""
} |
q50748 | LocalFileProvider.get_item_data | train | def get_item_data(self, session, item, byte_range=None):
"""
Return a file pointer to the item file. Assumes `item.file_name` points
to the file on disk.
"""
# Parse byte range
if byte_range is not None:
begin, end = parse_byte_range(byte_range, max_byte=item... | python | {
"resource": ""
} |
q50749 | readBIM | train | def readBIM(basefilename,usecols=None):
"""
helper method for speeding up read BED
"""
bim = basefilename+ '.bim'
bim = SP.loadtxt(bim,dtype=bytes,usecols=usecols)
return bim | python | {
"resource": ""
} |
q50750 | readFAM | train | def readFAM(basefilename,usecols=None):
"""
helper method for speeding up read FAM
"""
fam = basefilename+'.fam'
fam = SP.loadtxt(fam,dtype=bytes,usecols=usecols)
return fam | python | {
"resource": ""
} |
q50751 | ip2hex | train | def ip2hex(ip):
'''
Converts an ip to a hex value that can be used with a hex bit mask
'''
parts = ip.split(".")
if len(parts) != 4: return None
ipv = 0
for part in parts:
try:
p = int(part)
if p < 0 or p > 255: return None
ipv = (ipv << 8) + p
... | python | {
"resource": ""
} |
q50752 | ip_in_ip_mask | train | def ip_in_ip_mask(ip, mask_ip, mask):
'''
Checks whether an ip is contained in an ip subnet where the subnet is stated as an ip in the dotted format, and a hex mask
'''
ip = ip2hex(ip)
if ip is None: raise Exception("bad ip format")
if (mask_ip & mask) == (ip & mask):
return True
ret... | python | {
"resource": ""
} |
q50753 | check_ip | train | def check_ip(original_ip):
'''
Checks the format of an IP address and returns it if it is correct. Otherwise it returns None.
'''
ip = original_ip.strip()
parts = ip.split('.')
if len(parts) != 4:
return None
for p in parts:
try:
p = int(p)
if (p < 0)... | python | {
"resource": ""
} |
q50754 | slh_associate | train | def slh_associate(a_features, b_features, max_sigma=5):
"""
An implementation of the Scott and Longuet-Higgins algorithm for feature
association.
This function takes two lists of features. Each feature is a
:py:class:`MultivariateNormal` instance representing a feature
location and its associat... | python | {
"resource": ""
} |
q50755 | _proximity_to_association | train | def _proximity_to_association(proximity):
"""SLH algorithm for increasing orthogonality of a matrix."""
# pylint:disable=invalid-name
# I'm afraid that the short names here are just a function of the
# mathematical nature of the code.
# Special case: zero-size matrix
if proximity.shape[0] == 0 ... | python | {
"resource": ""
} |
q50756 | active_version | train | def active_version():
"""
Determine the current active version on the server
Just examine the which environment is symlinked
"""
link = '/'.join([deployment_root(),'env',env.project_name])
if not exists(link): return None
active = os.path.split(run('ls -al '+link).split(' -> ')[1])... | python | {
"resource": ""
} |
q50757 | activate | train | def activate():
"""
Activates the version specified in ``env.project_version`` if it is different
from the current active version.
An active version is just the version that is symlinked.
"""
env_path = '/'.join([deployment_root(),'env',env.project_fullname])
if not exists(env_path):
... | python | {
"resource": ""
} |
q50758 | sync_db | train | def sync_db():
"""
Runs the django syncdb command
"""
with cd('/'.join([deployment_root(),'env',env.project_fullname,'project',env.project_package_name,'sitesettings'])):
venv = '/'.join([deployment_root(),'env',env.project_fullname,'bin','activate'])
sites = _get_django_sites()
... | python | {
"resource": ""
} |
q50759 | migration | train | def migration():
"""
Integrate with south schema migration
"""
#activate env
with cd('/'.join([deployment_root(),'env',env.project_fullname,'project',env.project_package_name,'sitesettings'])):
#migrates all or specific env.migration
venv = '/'.join([deployment_root(),'env',... | python | {
"resource": ""
} |
q50760 | mkvirtualenv | train | def mkvirtualenv():
"""
Create the virtualenv project environment
"""
root = '/'.join([deployment_root(),'env'])
path = '/'.join([root,env.project_fullname])
dirs_created = []
if env.verbosity:
print env.host,'CREATING VIRTUALENV', path
if not exists(root): dirs_created += mkdirs... | python | {
"resource": ""
} |
q50761 | rmvirtualenv | train | def rmvirtualenv():
"""
Remove the current or ``env.project_version`` environment and all content in it
"""
path = '/'.join([deployment_root(),'env',env.project_fullname])
link = '/'.join([deployment_root(),'env',env.project_name])
if version_state('mkvirtualenv'):
sudo(' '.join(['rm -rf... | python | {
"resource": ""
} |
q50762 | main | train | def main():
"""
Run a benchmark for N items. If N is not specified, take 1,000,000 for N.
"""
# Parse arguments and configure application instance.
arguments, parser = parse_arguments()
# Start iterating
store = RevisionStore()
sys.stdout.write("Iterating over %d items.\n" % arguments.... | python | {
"resource": ""
} |
q50763 | Markov._compute_relative_probs | train | def _compute_relative_probs(self, prob_dict):
""" computes the relative probabilities for every state """
for transition_counts in prob_dict.values():
summed_occurences = sum(transition_counts.values())
if summed_occurences > 0:
for token in transition_counts.keys... | python | {
"resource": ""
} |
q50764 | Markov._text_generator | train | def _text_generator(self, next_token=None, emit=lambda x, _, __: x, max_length=None):
""" loops from the start state to the end state and records the emissions
Tokens are joint to sentences by looking ahead for the next token type
emit: by default the markovian emit (see HMM for different emiss... | python | {
"resource": ""
} |
q50765 | Markov._generate_next_token_helper | train | def _generate_next_token_helper(self, past_states, transitions):
""" generates next token based previous states """
key = tuple(past_states)
assert key in transitions, "%s" % str(key)
return utils.weighted_choice(transitions[key].items()) | python | {
"resource": ""
} |
q50766 | has_entities | train | def has_entities(status):
"""
Returns true if a Status object has entities.
Args:
status: either a tweepy.Status object or a dict returned from Twitter API
"""
try:
if sum(len(v) for v in status.entities.values()) > 0:
return True
except AttributeError:
if s... | python | {
"resource": ""
} |
q50767 | remove_entities | train | def remove_entities(status, entitylist):
'''Remove entities for a list of items.'''
try:
entities = status.entities
text = status.text
except AttributeError:
entities = status.get('entities', dict())
text = status['text']
indices = [ent['indices'] for etype, entval in li... | python | {
"resource": ""
} |
q50768 | replace_urls | train | def replace_urls(status):
'''
Replace shorturls in a status with expanded urls.
Args:
status (tweepy.status): A tweepy status object
Returns:
str
'''
text = status.text
if not has_url(status):
return text
urls = [(e['indices'], e['expanded_url']) for e in stat... | python | {
"resource": ""
} |
q50769 | chomp | train | def chomp(text, max_len=280, split=None):
'''
Shorten a string so that it fits under max_len, splitting it at 'split'.
Not guaranteed to return a string under max_len, as it may not be possible
Args:
text (str): String to shorten
max_len (int): maximum length. default 140
split ... | python | {
"resource": ""
} |
q50770 | GoogleReader.buildSubscriptionList | train | def buildSubscriptionList(self):
"""
Hits Google Reader for a users's alphabetically ordered list of feeds.
Returns true if succesful.
"""
self._clearLists()
unreadById = {}
if not self.userId:
self.getUserInfo()
unreadJson = self.httpGet(Re... | python | {
"resource": ""
} |
q50771 | GoogleReader.getFeedContent | train | def getFeedContent(self, feed, excludeRead=False, continuation=None, loadLimit=20, since=None, until=None):
"""
Return items for a particular feed
"""
return self._getFeedContent(feed.fetchUrl, excludeRead, continuation, loadLimit, since, until) | python | {
"resource": ""
} |
q50772 | GoogleReader.getCategoryContent | train | def getCategoryContent(self, category, excludeRead=False, continuation=None, loadLimit=20, since=None, until=None):
"""
Return items for a particular category
"""
return self._getFeedContent(category.fetchUrl, excludeRead, continuation, loadLimit, since, until) | python | {
"resource": ""
} |
q50773 | GoogleReader._modifyItemTag | train | def _modifyItemTag(self, item_id, action, tag):
""" wrapper around actual HTTP POST string for modify tags """
return self.httpPost(ReaderUrl.EDIT_TAG_URL,
{'i': item_id, action: tag, 'ac': 'edit-tags'}) | python | {
"resource": ""
} |
q50774 | GoogleReader.addItemTag | train | def addItemTag(self, item, tag):
"""
Add a tag to an individal item.
tag string must be in form "user/-/label/[tag]"
"""
if self.inItemTagTransaction:
# XXX: what if item's parent is not a feed?
if not tag in self.addTagBacklog:
self.addTa... | python | {
"resource": ""
} |
q50775 | GoogleReader.subscribe | train | def subscribe(self, feedUrl):
"""
Adds a feed to the top-level subscription list
Ubscribing seems idempotent, you can subscribe multiple times
without error
returns True or throws HTTPError
"""
response = self.httpPost(
ReaderUrl.SUBSCRIPTION_EDIT_UR... | python | {
"resource": ""
} |
q50776 | GoogleReader.getUserInfo | train | def getUserInfo(self):
"""
Returns a dictionary of user info that google stores.
"""
userJson = self.httpGet(ReaderUrl.USER_INFO_URL)
result = json.loads(userJson, strict=False)
self.userId = result['userId']
return result | python | {
"resource": ""
} |
q50777 | GoogleReader.getUserSignupDate | train | def getUserSignupDate(self):
"""
Returns the human readable date of when the user signed up for google reader.
"""
userinfo = self.getUserInfo()
timestamp = int(float(userinfo["signupTimeSec"]))
return time.strftime("%m/%d/%Y %H:%M", time.gmtime(timestamp)) | python | {
"resource": ""
} |
q50778 | timeout | train | def timeout(duration):
"""
A decorator to force a time limit on the execution of an external function.
:param int duration: the timeout duration
:raises: TypeError, if duration is anything other than integer
:raises: ValueError, if duration is a negative integer
:raises TimeoutError, if the ... | python | {
"resource": ""
} |
q50779 | Project.find_task | train | def find_task(self, name):
"""
Find a task by name.
If a task with the exact name cannot be found, then tasks with similar
names are searched for.
Returns
-------
Task
If the task is found.
Raises
------
NoSuchTaskError
... | python | {
"resource": ""
} |
q50780 | WovenCommand.handle | train | def handle(self, *args, **options):
"""
Initializes the fabric environment
"""
self.style = no_style()
#manage.py execution specific variables
#verbosity 0 = No output at all, 1 = woven output only, 2 = Fabric outputlevel = everything except debug
state.env.verbos... | python | {
"resource": ""
} |
q50781 | VirtualboxInstance.tear_down | train | def tear_down(self):
"""Tear down the virtual box machine
"""
if not self.browser_config.get('terminate'):
self.warning_log("Skipping terminate")
return
self.info_log("Tearing down")
if self.browser_config.get('platform').lower() == 'linux':
... | python | {
"resource": ""
} |
q50782 | VirtualboxInstance.start_video_recording | train | def start_video_recording(self, local_video_file_path, video_filename):
"""Start the video recording
"""
self.runner.info_log("Starting video recording...")
self.local_video_recording_file_path = local_video_file_path
self.remote_video_recording_file_path = video_filename
... | python | {
"resource": ""
} |
q50783 | VirtualboxInstance.stop_video_recording | train | def stop_video_recording(self):
"""Stop the video recording
"""
self.runner.info_log("Stopping video recording...")
self.execute_command("./stop_recording.sh")
# self.runner.info_log("output: %s"%output)
sleep(5)
self.scp_file_remote_to_local(
self... | python | {
"resource": ""
} |
q50784 | install_new_pipeline | train | def install_new_pipeline():
"""
Install above transformer into the existing pipeline creator.
"""
def new_create_pipeline(context, *args, **kwargs):
result = old_create_pipeline(context, *args, **kwargs)
result.insert(1, DAAPObjectTransformer(context))
return result
old_cr... | python | {
"resource": ""
} |
q50785 | ItemsContainer.loadItems | train | def loadItems(self, excludeRead=False, loadLimit=20, since=None, until=None):
"""
Load items and call itemsLoadedDone to transform data in objects
"""
self.clearItems()
self.loadtLoadOk = False
self.lastLoadLength = 0
self._itemsLoadedDone(self._getContent(excl... | python | {
"resource": ""
} |
q50786 | ItemsContainer.loadMoreItems | train | def loadMoreItems(self, excludeRead=False, continuation=None, loadLimit=20, since=None, until=None):
"""
Load more items using the continuation parameters of previously loaded items.
"""
self.lastLoadOk = False
self.lastLoadLength = 0
if not continuation and not self.... | python | {
"resource": ""
} |
q50787 | ItemsContainer._itemsLoadedDone | train | def _itemsLoadedDone(self, data):
"""
Called when all items are loaded
"""
if data is None:
return
self.continuation = data.get('continuation', None)
self.lastUpdated = data.get('updated', None)
self.lastLoadLength = len(data.get('items', []))
... | python | {
"resource": ""
} |
q50788 | IndexableRegistry.register | train | def register(self, cls):
"""Adds a new PolymorphicIndexable to the registry."""
doc_type = cls.search_objects.mapping.doc_type
self.all_models[doc_type] = cls
base_class = cls.get_base_class()
if base_class not in self.families:
self.families[base_class] = {}
... | python | {
"resource": ""
} |
q50789 | CFastVDMM.fit | train | def fit(self,Params0=None,grad_threshold=1e-2):
"""
fit a variance component model with the predefined design and the initialization and returns all the results
"""
# GPVD initialization
lik = limix.CLikNormalNULL()
# Initial Params
if Params0==None:
... | python | {
"resource": ""
} |
q50790 | set_rate | train | def set_rate(rate):
"""Defines the ideal rate at which computation is to be performed
:arg rate: the frequency in Hertz
:type rate: int or float
:raises: TypeError: if argument 'rate' is not int or float
"""
if not (isinstance(rate, int) or isinstance(rate, float)):
raise TypeError("a... | python | {
"resource": ""
} |
q50791 | _check_for_encoding | train | def _check_for_encoding(b):
"""You can use a different encoding from UTF-8 by putting a specially-formatted
comment as the first or second line of the source code."""
eol = b.find(b'\n')
if eol < 0:
return _check_line_for_encoding(b)[0]
enc, again = _check_line_for_encoding(b[:eol])
if e... | python | {
"resource": ""
} |
q50792 | _root_domain | train | def _root_domain():
"""
Deduce the root domain name - usually a 'naked' domain.
This only needs to be done prior to the first deployment
"""
if not hasattr(env,'root_domain'):
cwd = os.getcwd().split(os.sep)
domain = ''
#if the first env.host has a domain name then we'l... | python | {
"resource": ""
} |
q50793 | check_settings | train | def check_settings():
"""
Validate the users settings conf prior to deploy
"""
valid=True
if not get_version() >= '1.0':
print "FABRIC ERROR: Woven is only compatible with Fabric < 1.0"
valid = False
if not env.MEDIA_ROOT or not env.MEDIA_URL:
print "MEDIA ERROR: You must... | python | {
"resource": ""
} |
q50794 | post_exec_hook | train | def post_exec_hook(hook):
"""
Runs a hook function defined in a deploy.py file
"""
#post_setupnode hook
module_name = '.'.join([env.project_package_name,'deploy'])
funcs_run = []
try:
imported = import_module(module_name)
func = vars(imported).get(hook)
if func:
... | python | {
"resource": ""
} |
q50795 | project_version | train | def project_version(full_version):
"""
project_version context manager
"""
project_full_version=full_version
v = _parse_project_version(full_version)
name = project_name()
project_fullname = '-'.join([name,v])
return _setenv(project_full_version=project_full_version, project_version=v,... | python | {
"resource": ""
} |
q50796 | set_server_state | train | def set_server_state(name,object=None,delete=False):
"""
Sets a simple 'state' on the server by creating a file
with the desired state's name and storing ``content`` as json strings if supplied
returns the filename used to store state
"""
with fab_settings(project_fullname=''):
r... | python | {
"resource": ""
} |
q50797 | set_version_state | train | def set_version_state(name,object=None,delete=False):
"""
Sets a simple 'state' on the server by creating a file
with the desired state's name + version and storing ``content`` as json strings if supplied
returns the filename used to store state
"""
if env.project_fullname: state_name = ... | python | {
"resource": ""
} |
q50798 | Pkzip.extract | train | def extract(self, target):
"""
Extracts the archive file to given directory.
:param target: Target extraction directory.
:type target: unicode
:return: Method success.
:rtype: bool
"""
if not foundations.common.path_exists(self.__archive):
ra... | python | {
"resource": ""
} |
q50799 | get_output_stream | train | def get_output_stream(encoding=anytemplate.compat.ENCODING,
ostream=sys.stdout):
"""
Get output stream take care of characters encoding correctly.
:param ostream: Output stream (file-like object); sys.stdout by default
:param encoding: Characters set encoding, e.g. UTF-8
:retu... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.