_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q50900 | phenSpecificEffects | train | def phenSpecificEffects(snps,pheno1,pheno2,K=None,covs=None,test='lrt'):
"""
Univariate fixed effects interaction test for phenotype specific SNP effects
Args:
snps: [N x S] SP.array of S SNPs for N individuals (test SNPs)
pheno1: [N x 1] SP.array of 1 phenotype for N individuals
... | python | {
"resource": ""
} |
q50901 | forward_lmm | train | def forward_lmm(snps,pheno,K=None,covs=None,qvalues=False,threshold = 5e-8, maxiter = 2,test='lrt',**kw_args):
"""
univariate fixed effects test with forward selection
Args:
snps: [N x S] SP.array of S SNPs for N individuals (test SNPs)
pheno: [N x 1] SP.array of 1 phenotype for N indivi... | python | {
"resource": ""
} |
q50902 | Parser.prepare | train | def prepare(self, start=-1):
"""Setup the parser for parsing.
Takes the starting symbol as an argument.
"""
if start == -1:
start = self.grammar.start
self.root = None
current_node = Node(start, None, [], 0, 0)
self.stack = []
self.stack.appen... | python | {
"resource": ""
} |
q50903 | Parser.classify | train | def classify(self, token_type, value, lineno, column, line):
"""Find the label for a token."""
if token_type == self.grammar.KEYWORD_TOKEN:
label_index = self.grammar.keyword_ids.get(value, -1)
if label_index != -1:
return label_index
label_index = self.gr... | python | {
"resource": ""
} |
q50904 | Parser.shift | train | def shift(self, next_state, token_type, value, lineno, column):
"""Shift a non-terminal and prepare for the next state."""
dfa, state, node = self.stack[-1]
new_node = Node(token_type, value, None, lineno, column)
node.children.append(new_node)
self.stack[-1] = (dfa, next_state, ... | python | {
"resource": ""
} |
q50905 | Parser.push | train | def push(self, next_dfa, next_state, node_type, lineno, column):
"""Push a terminal and adjust the current state."""
dfa, state, node = self.stack[-1]
new_node = Node(node_type, None, [], lineno, column)
self.stack[-1] = (dfa, next_state, node)
self.stack.append((next_dfa, 0, new... | python | {
"resource": ""
} |
q50906 | Parser.pop | train | def pop(self):
"""Pop an entry off the stack and make its node a child of the last."""
dfa, state, node = self.stack.pop()
if self.stack:
self.stack[-1][2].children.append(node)
else:
self.root = node | python | {
"resource": ""
} |
q50907 | Object._get | train | def _get(self, url, params=None):
""" Wrapper method for GET calls. """
self._call(self.GET, url, params, None) | python | {
"resource": ""
} |
q50908 | Object._post | train | def _post(self, url, params, uploads=None):
""" Wrapper method for POST calls. """
self._call(self.POST, url, params, uploads) | python | {
"resource": ""
} |
q50909 | Object._call | train | def _call(self, method, url, params, uploads):
""" Initiate resquest to server and handle outcomes. """
try:
data = self._request(method, url, params, uploads)
except Exception, e:
self._failed_cb(e)
else:
self._completed_cb(data) | python | {
"resource": ""
} |
q50910 | Object._request | train | def _request(self, method, url, params=None, uploads=None):
""" Request to server and handle transfer status. """
c = pycurl.Curl()
if method == self.POST:
c.setopt(c.POST, 1)
if uploads is not None:
if isinstance(uploads, dict):
# han... | python | {
"resource": ""
} |
q50911 | Object._completed_cb | train | def _completed_cb(self, data):
""" Extract info from data and emit completed. """
try:
info = json.loads(data)
except ValueError:
info = self._hook_data(data)
except Exception, e:
info = None
logging.error('%s: _completed_cb crashed with %s... | python | {
"resource": ""
} |
q50912 | Object._updated_cb | train | def _updated_cb(self, downtotal, downdone, uptotal, updone):
""" Emit update signal, including transfer status metadata. """
self.emit('updated', downtotal, downdone, uptotal, updone) | python | {
"resource": ""
} |
q50913 | Object._hook_id | train | def _hook_id(self, info):
""" Extract id from info. Override for custom behaviour. """
if isinstance(info, dict) and 'id' in info.keys():
self.id = info['id'] | python | {
"resource": ""
} |
q50914 | Command.handle | train | def handle(self, *args, **options):
"""
Collect all comments that hasn't already been
classified or are classified as unsure.
Order randomly so we don't rehash previously unsure classifieds
when count limiting.
"""
comments = Comment.objects.filter(
Q(... | python | {
"resource": ""
} |
q50915 | Segment.update_text | train | def update_text(self, token, match):
"""Update text from results of regex match"""
if isinstance(self.text, MatchGroup):
self.text = self.text.get_group_value(token, match) | python | {
"resource": ""
} |
q50916 | Segment.update_params | train | def update_params(self, token, match):
"""Update dict of params from results of regex match"""
for k, v in self.params.items():
if isinstance(v, MatchGroup):
self.params[k] = v.get_group_value(token, match) | python | {
"resource": ""
} |
q50917 | Token.modify_pattern | train | def modify_pattern(self, pattern, group):
"""Rename groups in regex pattern and enclose it in named group"""
pattern = group_regex.sub(r'?P<{}_\1>'.format(self.name), pattern)
return r'(?P<{}>{})'.format(group, pattern) | python | {
"resource": ""
} |
q50918 | MatchGroup.get_group_value | train | def get_group_value(self, token, match):
"""Return value of regex match for the specified group"""
try:
value = match.group('{}_{}'.format(token.name, self.group))
except IndexError:
value = ''
return self.func(value) if callable(self.func) else value | python | {
"resource": ""
} |
q50919 | Parser.build_regex | train | def build_regex(self, tokens):
"""Build compound regex from list of tokens"""
patterns = []
for token in tokens:
patterns.append(token.pattern_start)
if token.pattern_end:
patterns.append(token.pattern_end)
return re.compile('|'.join(patterns), re.... | python | {
"resource": ""
} |
q50920 | Parser.build_groups | train | def build_groups(self, tokens):
"""Build dict of groups from list of tokens"""
groups = {}
for token in tokens:
match_type = MatchType.start if token.group_end else MatchType.single
groups[token.group_start] = (token, match_type)
if token.group_end:
... | python | {
"resource": ""
} |
q50921 | Parser.get_matched_token | train | def get_matched_token(self, match):
"""Find which token has been matched by compound regex"""
match_groupdict = match.groupdict()
for group in self.groups:
if match_groupdict[group] is not None:
token, match_type = self.groups[group]
return (token, mat... | python | {
"resource": ""
} |
q50922 | Parser.get_params | train | def get_params(self, token_stack):
"""Get params from stack of tokens"""
params = {}
for token in token_stack:
params.update(token.params)
return params | python | {
"resource": ""
} |
q50923 | Parser.remove_token | train | def remove_token(self, token_stack, token):
"""Remove last occurance of token from stack"""
token_stack.reverse()
try:
token_stack.remove(token)
retval = True
except ValueError:
retval = False
token_stack.reverse()
return retval | python | {
"resource": ""
} |
q50924 | Parser.parse | train | def parse(self, text):
"""Parse text to obtain list of Segments"""
text = self.preprocess(text)
token_stack = []
last_pos = 0
# Iterate through all matched tokens
for match in self.regex.finditer(text):
# Find which token has been matched by regex
... | python | {
"resource": ""
} |
q50925 | Engine.__render | train | def __render(self, context, **kwargs):
"""
Render template.
:param context: A dict or dict-like object to instantiate given
template file
:param kwargs: Keyword arguments passed to the template engine to
render templates with specific features enabled.
:... | python | {
"resource": ""
} |
q50926 | compute_arxiv_re | train | def compute_arxiv_re(report_pattern, report_number):
"""Compute arXiv report-number."""
if report_number is None:
report_number = r"\g<name>"
report_re = re.compile(r"(?<!<cds\.REPORTNUMBER>)(?<!\w)" +
"(?P<name>" + report_pattern + ")" +
old_arx... | python | {
"resource": ""
} |
q50927 | get_reference_section_title_patterns | train | def get_reference_section_title_patterns():
"""Return a list of compiled regex patterns used to search for the title.
:return: (list) of compiled regex patterns.
"""
patterns = []
titles = [u'references',
u'references.',
u'r\u00C9f\u00E9rences',
u'r\u00C9f\... | python | {
"resource": ""
} |
q50928 | get_reference_line_numeration_marker_patterns | train | def get_reference_line_numeration_marker_patterns(prefix=u''):
"""Return a list of compiled regex patterns used to search for the marker.
Marker of a reference line in a full-text document.
:param prefix: (string) the possible prefix to a reference line
:return: (list) of compiled regex patterns.
... | python | {
"resource": ""
} |
q50929 | get_post_reference_section_title_patterns | train | def get_post_reference_section_title_patterns():
"""Return a list of compiled regex patterns for post title section.
Search for the title of the section after the reference section in a
full-text document.
:return: (list) of compiled regex patterns.
"""
compiled_patterns = []
thead = r'^\s... | python | {
"resource": ""
} |
q50930 | get_post_reference_section_keyword_patterns | train | def get_post_reference_section_keyword_patterns():
"""Return a list of compiled regex patterns for keywords.
Keywords that can often be found after, and therefore suggest the end of
a reference section in a full-text document.
:return: (list) of compiled regex patterns.
"""
compiled_patterns =... | python | {
"resource": ""
} |
q50931 | BundleManager.refresh | train | def refresh(self):
"""
Reload list of bundles from the store
:return: self
"""
self._bundles = {}
bundles = self._api.get_bundles(self._document.id)
for bundle in bundles:
self._bundles[bundle['identifier']] = Bundle(self._api, self._document, bundle... | python | {
"resource": ""
} |
q50932 | BaseMIOCableHandler._occ | train | def _occ(self, value, typ, datatype=None):
"""\
Issues events to create an occurrence.
`value`
The string value
`typ`
The occurrence type
`datatype`
The datatype (default: xsd:string)
"""
self._handler.occurrence(typ, value, da... | python | {
"resource": ""
} |
q50933 | calc_digest | train | def calc_digest(origin, algorithm="sha1", block_size=None):
"""Calculate digest of a readable object
Args:
origin -- a readable object for which calculate digest
algorithn -- the algorithm to use. See ``hashlib.algorithms_available`` for supported algorithms.
block_size -- the size of ... | python | {
"resource": ""
} |
q50934 | calc_AF | train | def calc_AF(M,major=0,minor=2):
"""calculate minor allelel frequency, by default assuming that minor==2"""
if minor==2:
Nhet = (M==0).sum(axis=0)
Nmajor = 2*(M==0).sum(axis=0)
Nminor = 2*(M==2).sum(axis=0)
af = Nminor/sp.double(2*M.shape[0])
else:
Nmajor = (M==0).s... | python | {
"resource": ""
} |
q50935 | evaluate_callables | train | def evaluate_callables(data):
"""
Call any callable values in the input dictionary;
return a new dictionary containing the evaluated results.
Useful for lazily evaluating default values in ``build`` methods.
>>> data = {"spam": "ham", "eggs": (lambda: 123)}
>>> result = evaluate_callables(data)... | python | {
"resource": ""
} |
q50936 | prompt_bool | train | def prompt_bool(name, default=False, yes_choices=None, no_choices=None):
"""
Grabs user input from command line and converts to boolean
value.
:param name: prompt text
:param default: default value if no input provided.
:param yes_choices: default 'y', 'yes', '1', 'on', 'true', 't'
:param n... | python | {
"resource": ""
} |
q50937 | base_warfare | train | def base_warfare(name, bases, attributes):
"""
Adds any number of attributes to an existing class.
:param name: Name.
:type name: unicode
:param bases: Bases.
:type bases: list
:param attributes: Attributes.
:type attributes: dict
:return: Base.
:rtype: object
"""
asser... | python | {
"resource": ""
} |
q50938 | Resource._update | train | def _update(self, data):
"""Update the object with new data."""
for k, v in six.iteritems(data):
new_value = v
if isinstance(v, dict):
new_value = type(self)(v)
elif isinstance(v, list):
new_value = [(type(self)(e) if isinstance(e, dict... | python | {
"resource": ""
} |
q50939 | MultivariateNormal.rvs | train | def rvs(self, size=1):
"""Convenience method to sample from this distribution.
Args:
size (int or tuple): Shape of return value. Each element is drawn
independently from this distribution.
"""
return np.random.multivariate_normal(self.mean, self.cov, size) | python | {
"resource": ""
} |
q50940 | Producer._send_message_to_topic | train | def _send_message_to_topic(self, topic, message):
"""
Send a message to a Kafka topic.
Parameters
----------
topic : str
The kafka topic where the message should be sent to.
message : FranzEvent
The message to be sent.
Raises
----... | python | {
"resource": ""
} |
q50941 | Producer.check_for_message_exception | train | def check_for_message_exception(cls, message_result):
"""
Makes sure there isn't an error when sending the message.
Kafka will silently catch exceptions and not bubble them up.
Parameters
----------
message_result : FutureRecordMetadata
"""
exception = me... | python | {
"resource": ""
} |
q50942 | generate_csv | train | def generate_csv(in_dir, out):
"""\
Walks through the `in_dir` and generates the CSV file `out`
"""
writer = UnicodeWriter(open(out, 'wb'), delimiter=';')
writer.writerow(('Reference ID', 'Created', 'Origin', 'Subject'))
for cable in cables_from_source(in_dir):
writer.writerow((cable.ref... | python | {
"resource": ""
} |
q50943 | RotatingBackup.backup | train | def backup(self):
"""
Does the rotating backup.
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> Storing '{0}' file backup.".format(self.__source))
foundations.common.path_exists(self.__destination) or foundations.io.set_directory(self.__destination)
... | python | {
"resource": ""
} |
q50944 | ordered_uniqify | train | def ordered_uniqify(sequence):
"""
Uniqifies the given hashable sequence while preserving its order.
:param sequence: Sequence.
:type sequence: object
:return: Uniqified sequence.
:rtype: list
"""
items = set()
return [key for key in sequence if key not in items and not items.add(k... | python | {
"resource": ""
} |
q50945 | unpack_default | train | def unpack_default(iterable, length=3, default=None):
"""
Unpacks given iterable maintaining given length and filling missing entries with given default.
:param iterable: iterable.
:type iterable: object
:param length: Iterable length.
:type length: int
:param default: Filling default objec... | python | {
"resource": ""
} |
q50946 | dependency_resolver | train | def dependency_resolver(dependencies):
"""
Resolves given dependencies.
:param dependencies: Dependencies to resolve.
:type dependencies: dict
:return: Resolved dependencies.
:rtype: list
"""
items = dict((key, set(dependencies[key])) for key in dependencies)
resolved_dependencies ... | python | {
"resource": ""
} |
q50947 | is_internet_available | train | def is_internet_available(ips=CONNECTION_IPS, timeout=1.0):
"""
Returns if an internet connection is available.
:param ips: Address ips to check against.
:type ips: list
:param timeout: Timeout in seconds.
:type timeout: int
:return: Is internet available.
:rtype: bool
"""
whil... | python | {
"resource": ""
} |
q50948 | get_host_address | train | def get_host_address(host=None, default_address=DEFAULT_HOST_IP):
"""
Returns the given host address.
:param host: Host to retrieve the address.
:type host: unicode
:param default_address: Default address if the host is unreachable.
:type default_address: unicode
:return: Host address.
... | python | {
"resource": ""
} |
q50949 | Form.validate | train | def validate(cls, **kwargs):
''' Validates the data received as keyword arguments whose name match
this class attributes. '''
# errors can store multiple errors
# obj is an instance in case validation succeeds
# redis is needed for database validation
errors = ValidationE... | python | {
"resource": ""
} |
q50950 | Form.set_engine | train | def set_engine(cls, neweng):
''' Sets the given coralillo engine so the model uses it to communicate
with the redis database '''
assert isinstance(neweng, Engine), 'Provided object must be of class Engine'
if hasattr(cls, 'Meta'):
cls.Meta.engine = neweng
else:
... | python | {
"resource": ""
} |
q50951 | Model.save | train | def save(self):
''' Persists this object to the database. Each field knows how to store
itself so we don't have to worry about it '''
redis = type(self).get_redis()
pipe = to_pipeline(redis)
pipe.hset(self.key(), 'id', self.id)
for fieldname, field in self.proxy:
... | python | {
"resource": ""
} |
q50952 | Model.update | train | def update(self, **kwargs):
''' validates the given data against this object's rules and then
updates '''
redis = type(self).get_redis()
errors = ValidationErrors()
for fieldname, field in self.proxy:
if not field.fillable:
continue
given... | python | {
"resource": ""
} |
q50953 | Model.get | train | def get(cls, id):
''' Retrieves an object by id. Returns None in case of failure '''
if not id:
return None
redis = cls.get_redis()
key = '{}:{}:obj'.format(cls.cls_key(), id)
if not redis.exists(key):
return None
obj = cls(id=id)
obj._... | python | {
"resource": ""
} |
q50954 | Model.q | train | def q(cls, **kwargs):
''' Creates an iterator over the members of this class that applies the
given filters and returns only the elements matching them '''
redis = cls.get_redis()
return QuerySet(cls, redis.sscan_iter(cls.members_key())) | python | {
"resource": ""
} |
q50955 | Model.reload | train | def reload(self):
''' reloads this object so if it was updated in the database it now
contains the new values'''
key = self.key()
redis = type(self).get_redis()
if not redis.exists(key):
raise ModelNotFoundError('This object has been deleted')
data = debyte_... | python | {
"resource": ""
} |
q50956 | Model.get_or_exception | train | def get_or_exception(cls, id):
''' Tries to retrieve an instance of this model from the database or
raises an exception in case of failure '''
obj = cls.get(id)
if obj is None:
raise ModelNotFoundError('This object does not exist in database')
return obj | python | {
"resource": ""
} |
q50957 | Model.get_by | train | def get_by(cls, field, value):
''' Tries to retrieve an isinstance of this model from the database
given a value for a defined index. Return None in case of failure '''
redis = cls.get_redis()
key = cls.cls_key()+':index_'+field
id = redis.hget(key, value)
if id:
... | python | {
"resource": ""
} |
q50958 | Model.get_all | train | def get_all(cls):
''' Gets all available instances of this model from the database '''
redis = cls.get_redis()
return list(map(
lambda id: cls.get(id),
map(
debyte_string,
redis.smembers(cls.members_key())
)
)) | python | {
"resource": ""
} |
q50959 | Model.key | train | def key(self):
''' Returns the redis key to access this object's values '''
prefix = type(self).cls_key()
return '{}:{}:obj'.format(prefix, self.id) | python | {
"resource": ""
} |
q50960 | Model.fqn | train | def fqn(self):
''' Returns a fully qualified name for this object '''
prefix = type(self).cls_key()
return '{}:{}'.format(prefix, self.id) | python | {
"resource": ""
} |
q50961 | Model.to_json | train | def to_json(self, *, include=None):
''' Serializes this model to a JSON representation so it can be sent
via an HTTP REST API '''
json = dict()
if include is None or 'id' in include or '*' in include:
json['id'] = self.id
if include is None or '_type' in include or ... | python | {
"resource": ""
} |
q50962 | Model.delete | train | def delete(self):
''' Deletes this model from the database, calling delete in each field
to properly delete special cases '''
redis = type(self).get_redis()
for fieldname, field in self.proxy:
field.delete(redis)
redis.delete(self.key())
redis.srem(type(self... | python | {
"resource": ""
} |
q50963 | Context.init | train | def init(self):
"""
call after updating options
"""
# remove root logger, so we can reinit
# TODO only remove our own
# TODO move to _init, let overrides use init()
logging.getLogger().handlers = []
if self.debug:
logging.basicConfig(level=log... | python | {
"resource": ""
} |
q50964 | cable_from_file | train | def cable_from_file(filename):
"""\
Returns a cable from the provided file.
`filename`
An absolute path to the cable file.
"""
html = codecs.open(filename, 'rb', 'utf-8').read()
return cable_from_html(html, reader.reference_id_from_filename(filename)) | python | {
"resource": ""
} |
q50965 | cable_from_html | train | def cable_from_html(html, reference_id=None):
"""\
Returns a cable from the provided HTML page.
`html`
The HTML page of the cable
`reference_id`
The reference identifier of the cable. If the reference_id is ``None``
this function tries to detect it.
"""
if not html:
... | python | {
"resource": ""
} |
q50966 | generate_access_token_from_authorization_code | train | def generate_access_token_from_authorization_code(request, client):
""" Generates a new AccessToken from a request with an authorization code.
Read the specification: http://tools.ietf.org/html/rfc6749#section-4.1.3
"""
authorization_code_value = request.POST.get('code')
if not authorization_code_value:
... | python | {
"resource": ""
} |
q50967 | generate_access_token_from_refresh_token | train | def generate_access_token_from_refresh_token(request, client):
""" Generates a new AccessToken from a request containing a refresh token.
Read the specification: http://tools.ietf.org/html/rfc6749#section-6.
"""
refresh_token_value = request.POST.get('refresh_token')
if not refresh_token_value:
raise Inv... | python | {
"resource": ""
} |
q50968 | help | train | def help(project, task, step, variables):
"""Run a help step."""
task_name = step.args or variables['task']
try:
task = project.find_task(task_name)
except NoSuchTaskError as e:
yield events.task_not_found(task_name, e.similarities)
raise StopTask
text = f'# {task.name}\n'... | python | {
"resource": ""
} |
q50969 | get_loglevel | train | def get_loglevel(level):
"""
Set log level.
>>> assert get_loglevel(2) == logging.WARN
>>> assert get_loglevel(10) == logging.INFO
"""
try:
return [logging.DEBUG, logging.INFO, logging.WARN][level]
except IndexError:
return logging.INFO | python | {
"resource": ""
} |
q50970 | RedisClient.get_cache_token | train | def get_cache_token(self, token):
""" Get token and data from Redis """
if self.conn is None:
raise CacheException('Redis is not connected')
token_data = self.conn.get(token)
token_data = json.loads(token_data) if token_data else None
return token_data | python | {
"resource": ""
} |
q50971 | RedisClient.set_cache_token | train | def set_cache_token(self, token_data):
""" Set Token with data in Redis """
if self.conn is None:
raise CacheException('Redis is not connected')
token = token_data['auth_token']
token_expires = token_data['expires_at']
roles = token_data['roles']
try:
... | python | {
"resource": ""
} |
q50972 | check_config | train | def check_config(conf):
'''Type and boundary check'''
if 'fmode' in conf and not isinstance(conf['fmode'], string_types):
raise TypeError(TAG + ": `fmode` must be a string")
if 'dmode' in conf and not isinstance(conf['dmode'], string_types):
raise TypeError(TAG + ": `dmode` must be a string... | python | {
"resource": ""
} |
q50973 | from_json_format | train | def from_json_format(conf):
'''Convert fields of parsed json dictionary to python format'''
if 'fmode' in conf:
conf['fmode'] = int(conf['fmode'], 8)
if 'dmode' in conf:
conf['dmode'] = int(conf['dmode'], 8) | python | {
"resource": ""
} |
q50974 | to_json_format | train | def to_json_format(conf):
'''Convert fields of a python dictionary to be dumped in json format'''
if 'fmode' in conf:
conf['fmode'] = oct(conf['fmode'])[-3:]
if 'dmode' in conf:
conf['dmode'] = oct(conf['dmode'])[-3:] | python | {
"resource": ""
} |
q50975 | normalize_conf | train | def normalize_conf(conf):
'''Check, convert and adjust user passed config
Given a user configuration it returns a verified configuration with
all parameters converted to the types that are needed at runtime.
'''
conf = conf.copy()
# check for type error
check_config(conf)
# conver... | python | {
"resource": ""
} |
q50976 | _site_users | train | def _site_users():
"""
Get a list of site_n users
"""
userlist = sudo("cat /etc/passwd | awk '/site/'").split('\n')
siteuserlist = [user.split(':')[0] for user in userlist if 'site_' in user]
return siteuserlist | python | {
"resource": ""
} |
q50977 | domain_sites | train | def domain_sites():
"""
Get a list of domains
Each domain is an attribute dict with name, site_id and settings
"""
if not hasattr(env,'domains'):
sites = _get_django_sites()
site_ids = sites.keys()
site_ids.sort()
domains = []
for id in site_ids... | python | {
"resource": ""
} |
q50978 | deploy_webconf | train | def deploy_webconf():
""" Deploy nginx and other wsgi server site configurations to the host """
deployed = []
log_dir = '/'.join([deployment_root(),'log'])
#TODO - incorrect - check for actual package to confirm installation
if webserver_list():
if env.verbosity:
print env.host,... | python | {
"resource": ""
} |
q50979 | webserver_list | train | def webserver_list():
"""
list of webserver packages
"""
p = set(get_packages())
w = set(['apache2','gunicorn','uwsgi','nginx'])
installed = p & w
return list(installed) | python | {
"resource": ""
} |
q50980 | reload_webservers | train | def reload_webservers():
"""
Reload apache2 and nginx
"""
if env.verbosity:
print env.host, "RELOADING apache2"
with settings(warn_only=True):
a = sudo("/etc/init.d/apache2 reload")
if env.verbosity:
print '',a
if env.verbosity:
#Reload used t... | python | {
"resource": ""
} |
q50981 | Auth.is_url_ok | train | def is_url_ok(self):
""" Verify Keystone Auth URL """
response = requests.head(settings.KEYSTONE_AUTH_URL)
if response.status_code == 200:
return True
return False | python | {
"resource": ""
} |
q50982 | Auth._set_token_data | train | def _set_token_data(self):
""" Set token_data by Keystone """
if not self.token:
return
self._set_config_keystone(
settings.KEYSTONE_USERNAME, settings.KEYSTONE_PASSWORD)
token_data = self._keystone_auth.validate_token(self.token)
if not token_data:
... | python | {
"resource": ""
} |
q50983 | Auth._set_config_keystone | train | def _set_config_keystone(self, username, password):
""" Set config to Keystone """
self._keystone_auth = KeystoneAuth(
settings.KEYSTONE_AUTH_URL, settings.KEYSTONE_PROJECT_NAME, username, password,
settings.KEYSTONE_USER_DOMAIN_NAME, settings.KEYSTONE_PROJECT_DOMAIN_NAME,
... | python | {
"resource": ""
} |
q50984 | Auth.get_token_data | train | def get_token_data(self):
""" Get token and data from keystone """
token_data = self._keystone_auth.conn.auth_ref
token = token_data['auth_token']
self.set_token(token)
if self.cache.is_redis_ok():
try:
self.cache.set_cache_token(token_data)
... | python | {
"resource": ""
} |
q50985 | get_cache | train | def get_cache(taxonomy_id):
"""Return cache for the given taxonomy id.
:param taxonomy_id: identifier of the taxonomy
:type taxonomy_id: str
:return: dictionary object (empty if no taxonomy_id
is found), you must not change anything inside it.
Create a new dictionary and use set_cache ... | python | {
"resource": ""
} |
q50986 | _get_remote_ontology | train | def _get_remote_ontology(onto_url, time_difference=None):
"""Check if the online ontology is more recent than the local ontology.
If yes, try to download and store it in Invenio's cache directory.
Return a boolean describing the success of the operation.
:return: path to the downloaded ontology.
... | python | {
"resource": ""
} |
q50987 | _discover_ontology | train | def _discover_ontology(ontology_path):
"""Look for the file in known places.
:param ontology: path name or url
:type ontology: str
:return: absolute path of a file if found, or None
"""
last_part = os.path.split(os.path.abspath(ontology_path))[1]
possible_patterns = [last_part, last_part.l... | python | {
"resource": ""
} |
q50988 | _capitalize_first_letter | train | def _capitalize_first_letter(word):
"""Return a regex pattern with the first letter.
Accepts both lowercase and uppercase.
"""
if word[0].isalpha():
# These two cases are necessary in order to get a regex pattern
# starting with '[xX]' and not '[Xx]'. This allows to check for
# ... | python | {
"resource": ""
} |
q50989 | _convert_punctuation | train | def _convert_punctuation(punctuation, conversion_table):
"""Return a regular expression for a punctuation string."""
if punctuation in conversion_table:
return conversion_table[punctuation]
return re.escape(punctuation) | python | {
"resource": ""
} |
q50990 | _convert_word | train | def _convert_word(word):
"""Return the plural form of the word if it exists.
Otherwise return the word itself.
"""
out = None
# Acronyms.
if word.isupper():
out = word + "s?"
# Proper nouns or word with digits.
elif word.istitle():
out = word + "('?s)?"
elif _contai... | python | {
"resource": ""
} |
q50991 | _get_cache | train | def _get_cache(cache_file, source_file=None):
"""Get cached taxonomy using the cPickle module.
No check is done at that stage.
:param cache_file: full path to the file holding pickled data
:param source_file: if we discover the cache is obsolete, we
will build a new cache, therefore we need th... | python | {
"resource": ""
} |
q50992 | _get_last_modification_date | train | def _get_last_modification_date(url):
"""Get the last modification date of the ontology."""
request = requests.head(url)
date_string = request.headers["last-modified"]
parsed = time.strptime(date_string, "%a, %d %b %Y %H:%M:%S %Z")
return datetime(*(parsed)[0:6]) | python | {
"resource": ""
} |
q50993 | _download_ontology | train | def _download_ontology(url, local_file):
"""Download the ontology and stores it in CLASSIFIER_WORKDIR."""
current_app.logger.debug(
"Copying remote ontology '%s' to file '%s'." % (url, local_file)
)
try:
request = requests.get(url, stream=True)
if request.status_code == 200:
... | python | {
"resource": ""
} |
q50994 | _get_searchable_regex | train | def _get_searchable_regex(basic=None, hidden=None):
"""Return the searchable regular expressions for the single keyword."""
# Hidden labels are used to store regular expressions.
basic = basic or []
hidden = hidden or []
hidden_regex_dict = {}
for hidden_label in hidden:
if _is_regex(hi... | python | {
"resource": ""
} |
q50995 | _get_regex_pattern | train | def _get_regex_pattern(label):
"""Return a regular expression of the label.
This takes care of plural and different kinds of separators.
"""
parts = _split_by_punctuation.split(label)
for index, part in enumerate(parts):
if index % 2 == 0:
# Word
if not parts[index]... | python | {
"resource": ""
} |
q50996 | KeywordToken.refreshCompositeOf | train | def refreshCompositeOf(self, single_keywords, composite_keywords,
store=None, namespace=None):
"""Re-check sub-parts of this keyword.
This should be called after the whole RDF was processed, because
it is using a cache of single keywords and if that
one is inc... | python | {
"resource": ""
} |
q50997 | create_user | train | def create_user(username, key, session):
"""
Create a User and UserKey record in the session provided.
Will rollback both records if any issues are encountered.
After rollback, Exception is re-raised.
:param username: The username for the User
:param key: The public key to associate with this U... | python | {
"resource": ""
} |
q50998 | build_definitions | train | def build_definitions(dpath="sqlalchemy_models/_definitions.json"):
"""
Nasty hacky method of ensuring LedgerAmounts are rendered as floats in json schemas, instead of integers.
:param str dpath: The path of the definitions file to create as part of the build process.
"""
command.run(AlsoChildrenWa... | python | {
"resource": ""
} |
q50999 | multiply_tickers | train | def multiply_tickers(t1, t2):
"""
Multiply two tickers. Quote currency of t1 must match base currency of t2.
:param Ticker t1: Ticker # 1
:param Ticker t2: Ticker # 2
"""
t1pair = t1.market.split("_")
t2pair = t2.market.split("_")
assert t1pair[1] == t2pair[0]
market = t1pair[0] + "... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.