_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q50800 | uniq | train | def uniq(items):
"""Remove duplicates in given list with its order kept.
>>> uniq([])
[]
>>> uniq([1, 4, 5, 1, 2, 3, 5, 10])
[1, 4, 5, 2, 3, 10]
"""
acc = items[:1]
for item in items[1:]:
if item not in acc:
acc += [item]
return acc | python | {
"resource": ""
} |
q50801 | normpath | train | def normpath(path):
"""Normalize given path in various different forms.
>>> normpath("/tmp/../etc/hosts")
'/etc/hosts'
>>> normpath("~root/t")
'/root/t'
"""
funcs = [os.path.normpath, os.path.abspath]
if "~" in path:
funcs = [os.path.expanduser] + funcs
return chaincalls(fu... | python | {
"resource": ""
} |
q50802 | mk_template_paths | train | def mk_template_paths(filepath, paths=None):
"""
Make template paths from given filepath and paths list.
:param filepath: (Base) filepath of template file or None
:param paths: A list of template search paths or None
>>> mk_template_paths("/tmp/t.j2", [])
['/tmp']
>>> mk_template_paths("/t... | python | {
"resource": ""
} |
q50803 | find_template_from_path | train | def find_template_from_path(filepath, paths=None):
"""
Return resolved path of given template file
:param filepath: (Base) filepath of template file
:param paths: A list of template search paths
"""
if paths is None or not paths:
paths = [os.path.dirname(filepath), os.curdir]
for p... | python | {
"resource": ""
} |
q50804 | _render | train | def _render(template=None, filepath=None, context=None, at_paths=None,
at_encoding=anytemplate.compat.ENCODING, at_engine=None,
at_ask_missing=False, at_cls_args=None, _at_usr_tmpl=None,
**kwargs):
"""
Compile and render given template string and return the result string.
... | python | {
"resource": ""
} |
q50805 | render | train | def render(filepath, context=None, **options):
"""
Compile and render given template file and return the result string.
:param filepath: Template file path or '-'
:param context: A dict or dict-like object to instantiate given
template file
:param options: Optional keyword arguments such as... | python | {
"resource": ""
} |
q50806 | render_to | train | def render_to(filepath, context=None, output=None,
at_encoding=anytemplate.compat.ENCODING, **options):
"""
Render given template file and write the result string to given `output`.
The result string will be printed to sys.stdout if output is None or '-'.
:param filepath: Template file pa... | python | {
"resource": ""
} |
q50807 | _fetch_url | train | def _fetch_url(url):
"""\
Returns the content of the provided URL.
"""
try:
resp = urllib2.urlopen(_Request(url))
except urllib2.URLError:
if 'wikileaks.org' in url:
resp = urllib2.urlopen(_Request(url.replace('wikileaks.org', 'wikileaks.ch')))
else:
r... | python | {
"resource": ""
} |
q50808 | rows_from_csv | train | def rows_from_csv(filename, predicate=None, encoding='utf-8'):
"""\
Returns an iterator over all rows in the provided CSV `filename`.
`filename`
Absolute path to a file to read the cables from.
The file must be a CSV file with the following columns:
<identifier>, <creation-date>, <r... | python | {
"resource": ""
} |
q50809 | tag_kind | train | def tag_kind(tag, default=consts.TAG_KIND_UNKNOWN):
"""\
Returns the TAG kind.
`tag`
A string.
`default`
A value to return if the TAG kind is unknown
(set to ``constants.TAG_KIND_UNKNOWN`` by default)
"""
if len(tag) == 2:
return consts.TAG_KIND_GEO
if u',' i... | python | {
"resource": ""
} |
q50810 | clean_content | train | def clean_content(content):
"""\
Removes paragraph numbers, section delimiters, xxxx etc. from the content.
This function can be used to clean-up the cable's content before it
is processed by NLP tools or to create a search engine index.
`content`
The content of the cable.
"""
... | python | {
"resource": ""
} |
q50811 | titlefy | train | def titlefy(subject):
"""\
Titlecases the provided subject but respects common abbreviations.
This function returns ``None`` if the provided `subject` is ``None``. It
returns an empty string if the provided subject is empty.
`subject
A cable's subject.
"""
def clean_word(word... | python | {
"resource": ""
} |
q50812 | oauth_scope | train | def oauth_scope(*scope_names):
""" Return a decorator that restricts requests to those authorized with
a certain scope or scopes.
For example, to restrict access to a given endpoint like this:
.. code-block:: python
@require_login
def secret_attribute_endpoint(request, *args, **kwargs):
... | python | {
"resource": ""
} |
q50813 | Tokenizer.tokenize | train | def tokenize(self, tw):
""" Given a Tweet object, return a dict mapping field name to tokens. """
toks = defaultdict(lambda: [])
for field in self.fields:
if '.' in field:
parts = field.split('.')
value = tw.js
for p in parts:
... | python | {
"resource": ""
} |
q50814 | server | train | def server(service, log=None):
"""
Creates a threaded http service based on the passed HttpService instance.
The returned object can be watched via taskforce.poll(), select.select(), etc.
When activity is detected, the handle_request() method should be invoked.
This starts a thread to handle the re... | python | {
"resource": ""
} |
q50815 | get_query | train | def get_query(path, force_unicode=True):
"""
Convert the query path of the URL to a dict.
See _unicode regarding force_unicode.
"""
u = urlparse(path)
if not u.query:
return {}
p = parse_qs(u.query)
if force_unicode:
p = _unicode(p)
return p | python | {
"resource": ""
} |
q50816 | merge_query | train | def merge_query(path, postmap, force_unicode=True):
"""
Merges params parsed from the URI into the mapping from the POST body and
returns a new dict with the values.
This is a convenience function that gives use a dict a bit like PHP's $_REQUEST
array. The original 'postmap' is preserved so the ca... | python | {
"resource": ""
} |
q50817 | HttpService.cmp | train | def cmp(self, other_service):
"""
Compare with an instance of this object. Returns None if the object
is not comparable, False is relevant attributes don't match and True
if they do.
"""
if not isinstance(other_service, HttpService):
return None
for att i... | python | {
"resource": ""
} |
q50818 | BaseServer.register_get | train | def register_get(self, regex, callback):
"""
Register a regex for processing HTTP GET
requests. If the callback is None, any
existing registration is removed.
"""
if callback is None: # pragma: no cover
... | python | {
"resource": ""
} |
q50819 | BaseServer.register_post | train | def register_post(self, regex, callback):
"""
Register a regex for processing HTTP POST
requests. If the callback is None, any
existing registration is removed.
The callback will be called as:
callback(path, postmap)
"""
if callback is None: ... | python | {
"resource": ""
} |
q50820 | BaseServer.serve_get | train | def serve_get(self, path, **params):
"""
Find a GET callback for the given HTTP path, call it and return the
results. The callback is called with two arguments, the path used to
match it, and params which include the BaseHTTPRequestHandler instance.
The callback must return a t... | python | {
"resource": ""
} |
q50821 | BaseServer.serve_post | train | def serve_post(self, path, postmap, **params):
"""
Find a POST callback for the given HTTP path, call it and return
the results. The callback is called with the path used to match
it, a dict of vars from the POST body and params which include the
BaseHTTPRequestHandler instance.... | python | {
"resource": ""
} |
q50822 | get | train | def get(**kwargs):
"""
Safe sensor wrapper
"""
sensor = None
tick = 0
driver = DHTReader(**kwargs)
while not sensor and tick < TIME_LIMIT:
try:
sensor = driver.receive_data()
except DHTException:
tick += 1
return sensor | python | {
"resource": ""
} |
q50823 | parse_url | train | def parse_url(url, extra_schemes={}):
"""
parse a munge url
type:URL
URL.type
examples:
file.yaml
yaml:file.txt
http://example.com/file.yaml
yaml:http://example.com/file.txt
mysql://user:password@localhost/database/table
django:///home/user/project/... | python | {
"resource": ""
} |
q50824 | Config.get_nested | train | def get_nested(self, *args):
"""
get a nested value, returns None if path does not exist
"""
data = self.data
for key in args:
if key not in data:
return None
data = data[key]
return data | python | {
"resource": ""
} |
q50825 | Config.read | train | def read(self, config_dir=None, config_name=None, clear=False):
"""
read config from config_dir
if config_dir is None, clear to default config
clear will clear to default before reading new file
"""
# TODO should probably allow config_dir to be a list as well
# get name ... | python | {
"resource": ""
} |
q50826 | Config.write | train | def write(self, config_dir=None, config_name=None, codec=None):
"""
writes config to config_dir using config_name
"""
# get name of config directory
if not config_dir:
config_dir = self._meta_config_dir
if not config_dir:
raise IOError("con... | python | {
"resource": ""
} |
q50827 | Command.get_handler | train | def get_handler(self, *args, **options):
"""
Returns the default WSGI handler for the runner.
"""
handler = get_internal_wsgi_application()
from django.contrib.staticfiles.handlers import StaticFilesHandler
return StaticFilesHandler(handler) | python | {
"resource": ""
} |
q50828 | Context.validate_certificate | train | def validate_certificate(self, cert):
"""
Validate a certificate using this SSL Context
"""
store_ctx = X509.X509_Store_Context(_m2ext.x509_store_ctx_new(), _pyfree=1)
_m2ext.x509_store_ctx_init(store_ctx.ctx,
self.get_cert_store().store,
... | python | {
"resource": ""
} |
q50829 | is_pdf | train | def is_pdf(document):
"""Check if a document is a PDF file and return True if is is."""
if not executable_exists('pdftotext'):
current_app.logger.warning(
"GNU file was not found on the system. "
"Switching to a weak file extension test."
)
if document.lower().end... | python | {
"resource": ""
} |
q50830 | text_lines_from_local_file | train | def text_lines_from_local_file(document, remote=False):
"""Return the fulltext of the local file.
@param document: fullpath to the file that should be read
@param remote: boolean, if True does not count lines
@return: list of lines if st was read or an empty list
"""
try:
if is_pdf(doc... | python | {
"resource": ""
} |
q50831 | executable_exists | train | def executable_exists(executable):
"""Test if an executable is available on the system."""
for directory in os.getenv("PATH").split(":"):
if os.path.exists(os.path.join(directory, executable)):
return True
return False | python | {
"resource": ""
} |
q50832 | get_plaintext_document_body | train | def get_plaintext_document_body(fpath, keep_layout=False):
"""Given a file-path to a full-text, return a list of unicode strings.
Each string is a line of the fulltext.
In the case of a plain-text document, this simply means reading the
contents in from the file. In the case of a PDF/PostScript however... | python | {
"resource": ""
} |
q50833 | convert_PDF_to_plaintext | train | def convert_PDF_to_plaintext(fpath, keep_layout=False):
"""Convert PDF to txt using pdftotext.
Take the path to a PDF file and run pdftotext for this file, capturing
the output.
:param fpath: (string) path to the PDF file
:return: (list) of unicode strings (contents of the PDF file translated
... | python | {
"resource": ""
} |
q50834 | pdftotext_conversion_is_bad | train | def pdftotext_conversion_is_bad(txtlines):
"""Check if conversion after pdftotext is bad.
Sometimes pdftotext performs a bad conversion which consists of many
spaces and garbage characters.
This method takes a list of strings obtained from a pdftotext conversion
and examines them to see if they ar... | python | {
"resource": ""
} |
q50835 | readBimFile | train | def readBimFile(basefilename):
"""
Helper fuinction that reads bim files
"""
# read bim file
bim_fn = basefilename+'.bim'
rv = SP.loadtxt(bim_fn,delimiter='\t',usecols = (0,3),dtype=int)
return rv | python | {
"resource": ""
} |
q50836 | readCovarianceMatrixFile | train | def readCovarianceMatrixFile(cfile,readCov=True,readEig=True):
""""
reading in similarity matrix
cfile File containing the covariance matrix. The corresponding ID file must be specified in cfile.id)
"""
covFile = cfile+'.cov'
evalFile = cfile+'.cov.eval'
evecFile = cfile+'.cov.evec'
... | python | {
"resource": ""
} |
q50837 | readCovariatesFile | train | def readCovariatesFile(fFile):
""""
reading in covariate file
cfile file containing the fixed effects as NxP matrix
(N=number of samples, P=number of covariates)
"""
assert os.path.exists(fFile), '%s is missing.'%fFile
F = SP.loadtxt(fFile)
if F.ndim==1: F=F[:,SP.newaxis]
... | python | {
"resource": ""
} |
q50838 | readPhenoFile | train | def readPhenoFile(pfile,idx=None):
""""
reading in phenotype file
pfile root of the file containing the phenotypes as NxP matrix
(N=number of samples, P=number of traits)
"""
usecols = None
if idx!=None:
""" different traits are comma-seperated """
usecols = [int(... | python | {
"resource": ""
} |
q50839 | readNullModelFile | train | def readNullModelFile(nfile):
""""
reading file with null model info
nfile File containing null model info
"""
params0_file = nfile+'.p0'
nll0_file = nfile+'.nll0'
assert os.path.exists(params0_file), '%s is missing.'%params0_file
assert os.path.exists(nll0_file), '%s is missing.'%nl... | python | {
"resource": ""
} |
q50840 | readWindowsFile | train | def readWindowsFile(wfile):
""""
reading file with windows
wfile File containing window info
"""
window_file = wfile+'.wnd'
assert os.path.exists(window_file), '%s is missing.'%window_file
rv = SP.loadtxt(window_file)
return rv | python | {
"resource": ""
} |
q50841 | extract_irc_colours | train | def extract_irc_colours(msg):
"""Extract the IRC colours from the start of the string.
Extracts the colours from the start, and returns the colour code in our
format, and then the rest of the message.
"""
# first colour
fore, msg = _extract_irc_colour_code(msg)
if not fore:
return ... | python | {
"resource": ""
} |
q50842 | extract_girc_colours | train | def extract_girc_colours(msg, fill_last):
"""Extract the girc-formatted colours from the start of the string.
Extracts the colours from the start, and returns the colour code in IRC
format, and then the rest of the message.
If `fill_last`, last number must be zero-padded.
"""
if not len(msg):
... | python | {
"resource": ""
} |
q50843 | escape | train | def escape(msg):
"""Takes a raw IRC message and returns a girc-escaped message."""
msg = msg.replace(escape_character, 'girc-escaped-character')
for escape_key, irc_char in format_dict.items():
msg = msg.replace(irc_char, escape_character + escape_key)
# convert colour codes
new_msg = ''
... | python | {
"resource": ""
} |
q50844 | _get_from_format_dict | train | def _get_from_format_dict(format_dict, key):
"""Return a value from our format dict."""
if isinstance(format_dict[key], str):
return format_dict[key]
elif isinstance(format_dict[key], (list, tuple)):
fn_list = list(format_dict[key])
function = fn_list.pop(0)
if len(fn_list):... | python | {
"resource": ""
} |
q50845 | unescape | train | def unescape(msg, extra_format_dict={}):
"""Takes a girc-escaped message and returns a raw IRC message"""
new_msg = ''
extra_format_dict.update(format_dict)
while len(msg):
char = msg[0]
msg = msg[1:]
if char == escape_character:
escape_key = msg[0]
msg ... | python | {
"resource": ""
} |
q50846 | remove_formatting_codes | train | def remove_formatting_codes(line, irc=False):
"""Remove girc control codes from the given line."""
if irc:
line = escape(line)
new_line = ''
while len(line) > 0:
try:
if line[0] == '$':
line = line[1:]
if line[0] == '$':
ne... | python | {
"resource": ""
} |
q50847 | CSimulator.genRegionTerm | train | def genRegionTerm(self,X,vTot=0.1,pCausal=0.10,nCausal=None,pCommon=1.,nCommon=None,plot=False,distribution='biNormal'):
"""
Generate population structure term
Population structure is simulated by background SNPs
beta_pdf: pdf used to generate the regression weights
... | python | {
"resource": ""
} |
q50848 | CSimulator._genBgTerm_fromXX | train | def _genBgTerm_fromXX(self,vTot,vCommon,XX,a=None,c=None):
"""
generate background term from SNPs
Args:
vTot: variance of Yc+Yi
vCommon: variance of Yc
XX: kinship matrix
a: common scales, it can be set for debugging purposes
c: indipe... | python | {
"resource": ""
} |
q50849 | realtime_comment_classifier | train | def realtime_comment_classifier(sender, instance, created, **kwargs):
"""
Classifies a comment after it has been created.
This behaviour is configurable by the REALTIME_CLASSIFICATION MODERATOR,
default behaviour is to classify(True).
"""
# Only classify if newly created.
if created:
... | python | {
"resource": ""
} |
q50850 | run_benchmark | train | def run_benchmark(monitor):
'''Run the benchmarks
'''
url = urlparse(monitor.cfg.test_url)
name = slugify(url.path) or 'home'
name = '%s_%d.csv' % (name, monitor.cfg.workers)
monitor.logger.info('WRITING RESULTS ON "%s"', name)
total = REQUESTS//monitor.cfg.workers
with open(name, 'w') ... | python | {
"resource": ""
} |
q50851 | files_walker | train | def files_walker(directory, filters_in=None, filters_out=None, flags=0):
"""
Defines a generator used to walk files using given filters.
Usage::
>>> for file in files_walker("./foundations/tests/tests_foundations/resources/standard/level_0"):
... print(file)
...
./found... | python | {
"resource": ""
} |
q50852 | depth_walker | train | def depth_walker(directory, maximum_depth=1):
"""
Defines a generator used to walk into directories using given maximum depth.
Usage::
>>> for item in depth_walker("./foundations/tests/tests_foundations/resources/standard/level_0"):
... print(item)
...
(u'./foundations/... | python | {
"resource": ""
} |
q50853 | dictionaries_walker | train | def dictionaries_walker(dictionary, path=()):
"""
Defines a generator used to walk into nested dictionaries.
Usage::
>>> nested_dictionary = {"Level 1A":{"Level 2A": { "Level 3A" : "Higher Level"}}, "Level 1B" : "Lower level"}
>>> dictionaries_walker(nested_dictionary)
<generator o... | python | {
"resource": ""
} |
q50854 | nodes_walker | train | def nodes_walker(node, ascendants=False):
"""
Defines a generator used to walk into Nodes hierarchy.
Usage::
>>> node_a = AbstractCompositeNode("MyNodeA")
>>> node_b = AbstractCompositeNode("MyNodeB", node_a)
>>> node_c = AbstractCompositeNode("MyNodeC", node_a)
>>> node_d ... | python | {
"resource": ""
} |
q50855 | GP.LML | train | def LML(self,params=None):
"""
evalutes the log marginal likelihood for the given hyperparameters
hyperparams
"""
if params is not None:
self.setParams(params)
KV = self._update_cache()
alpha = KV['alpha']
L = KV['L']
lml_quad = 0.5 ... | python | {
"resource": ""
} |
q50856 | GP.LMLgrad | train | def LMLgrad(self,params=None):
"""
evaluates the gradient of the log marginal likelihood for the given hyperparameters
"""
if params is not None:
self.setParams(params)
KV = self._update_cache()
W = KV['W']
LMLgrad = SP.zeros(self.covar.n_params)
... | python | {
"resource": ""
} |
q50857 | GP.predict | train | def predict(self,Xstar):
"""
predict on Xstar
"""
KV = self._update_cache()
self.covar.setXstar(Xstar)
Kstar = self.covar.Kcross()
Ystar = SP.dot(Kstar,KV['alpha'])
return Ystar | python | {
"resource": ""
} |
q50858 | GP.checkGradient | train | def checkGradient(self,h=1e-6,verbose=True):
""" utility function to check the gradient of the gp """
grad_an = self.LMLgrad()
grad_num = {}
params0 = self.params.copy()
for key in list(self.params.keys()):
paramsL = params0.copy()
paramsR = params0.copy()... | python | {
"resource": ""
} |
q50859 | configure | train | def configure(screen_name=None, config_file=None, app=None, **kwargs):
"""
Set up a config dictionary using a bots.yaml config file and optional keyword args.
Args:
screen_name (str): screen_name of user to search for in config file
config_file (str): Path to read for the config file
... | python | {
"resource": ""
} |
q50860 | parse | train | def parse(file_path):
'''Parse a YAML or JSON file.'''
_, ext = path.splitext(file_path)
if ext in ('.yaml', '.yml'):
func = yaml.load
elif ext == '.json':
func = json.load
else:
raise ValueError("Unrecognized config file type %s" % ext)
with open(file_path, 'r') as ... | python | {
"resource": ""
} |
q50861 | find_file | train | def find_file(config_file=None, default_directories=None, default_bases=None):
'''Search for a config file in a list of files.'''
if config_file:
if path.exists(path.expanduser(config_file)):
return config_file
else:
raise FileNotFoundError('Config file not found: {}'.fo... | python | {
"resource": ""
} |
q50862 | setup_auth | train | def setup_auth(**keys):
'''Set up Tweepy authentication using passed args or config file settings.'''
auth = tweepy.OAuthHandler(consumer_key=keys['consumer_key'], consumer_secret=keys['consumer_secret'])
auth.set_access_token(
key=keys.get('token', keys.get('key', keys.get('oauth_token'))),
... | python | {
"resource": ""
} |
q50863 | list_engines_by_priority | train | def list_engines_by_priority(engines=None):
"""
Return a list of engines supported sorted by each priority.
"""
if engines is None:
engines = ENGINES
return sorted(engines, key=operator.methodcaller("priority")) | python | {
"resource": ""
} |
q50864 | find_by_filename | train | def find_by_filename(filename=None, engines=None):
"""
Find a list of template engine classes to render template `filename`.
:param filename: Template file name (may be a absolute/relative path)
:param engines: Template engines
:return: A list of engines support given template file
"""
if ... | python | {
"resource": ""
} |
q50865 | find_by_name | train | def find_by_name(name, engines=None):
"""
Find a template engine class specified by its name `name`.
:param name: Template name
:param engines: Template engines
:return: A template engine or None if no any template engine of given name
were found.
"""
if engines is None:
en... | python | {
"resource": ""
} |
q50866 | API.update_status | train | def update_status(self, *pargs, **kwargs):
"""
Wrapper for tweepy.api.update_status with a 10s wait when twitter is over capacity
"""
try:
return super(API, self).update_status(*pargs, **kwargs)
except tweepy.TweepError as e:
if getattr(e, 'api_code', Non... | python | {
"resource": ""
} |
q50867 | CodecBase.open | train | def open(self, url, mode='r', stdio=True):
"""
opens a URL, no scheme is assumed to be a file
no path will use stdin or stdout depending on mode, unless stdio is False
"""
# doesn't need to use config, because the object is already created
res = urlsplit(url)
if ... | python | {
"resource": ""
} |
q50868 | find_end_of_reference_section | train | def find_end_of_reference_section(docbody,
ref_start_line,
ref_line_marker,
ref_line_marker_ptn):
"""Find end of reference section.
Given that the start of a document's reference section has already been
r... | python | {
"resource": ""
} |
q50869 | get_reference_section_beginning | train | def get_reference_section_beginning(fulltext):
"""Get start of reference section."""
sect_start = {
'start_line': None,
'end_line': None,
'title_string': None,
'marker_pattern': None,
'marker': None,
'how_found_start': None,
}
# Find start of refs section... | python | {
"resource": ""
} |
q50870 | Library.bind_function | train | def bind_function(self, function):
"""
Binds given function to a class object attribute.
Usage::
>>> import ctypes
>>> path = "FreeImage.dll"
>>> function = LibraryHook(name="FreeImage_GetVersion", arguments_types=None, return_value=ctypes.c_char_p)
... | python | {
"resource": ""
} |
q50871 | estCumPos | train | def estCumPos(pos,chrom,offset = 20000000):
'''
compute the cumulative position of each variant given the position and the chromosome
Also return the starting cumulativeposition of each chromosome
Args:
pos: scipy.array of basepair positions (on the chromosome)
chrom: scipy.... | python | {
"resource": ""
} |
q50872 | _imputeMissing | train | def _imputeMissing(X, center=True, unit=True, betaNotUnitVariance=False, betaA=1.0, betaB=1.0):
'''
fill in missing values in the SNP matrix by the mean value
optionally center the data and unit-variance it
Args:
X: scipy.array of SNP values. If dtype=='int8' the missin... | python | {
"resource": ""
} |
q50873 | QTLData.getCovariance | train | def getCovariance(self,normalize=True,i0=None,i1=None,pos0=None,pos1=None,chrom=None,center=True,unit=True,pos_cum0=None,pos_cum1=None,blocksize=None,X=None,**kw_args):
"""calculate the empirical genotype covariance in a region"""
if X is not None:
K=X.dot(X.T)
Nsnp=X.shape[1]
... | python | {
"resource": ""
} |
q50874 | QTLData.getIcis_geno | train | def getIcis_geno(self,geneID,cis_window=50E3):
""" if eqtl==True it returns a bool vec for cis """
assert self.eqtl == True, 'Only for eqtl data'
index = self.geneID==geneID
[_chrom,_gene_start,_gene_end] = self.gene_pos[index][0,:]
Icis = (self.genoChrom==_chrom)*(self.genoPos>=... | python | {
"resource": ""
} |
q50875 | load_credentials_from_file | train | def load_credentials_from_file(username):
'''Loads password for `username` from a file.
The file must be called ``.tm_pass`` and stored in
the home directory. It must provide a YAML mapping where
keys are usernames and values the corresponding passwords.
Parameters
----------
username: str... | python | {
"resource": ""
} |
q50876 | prompt_for_credentials | train | def prompt_for_credentials(username):
'''Prompt `username` for password.
Parameters
----------
username: str
name of the TissueMAPS user
Returns
-------
str
password for the given user
'''
message = 'Enter password for user "{0}": '.format(username)
password = ... | python | {
"resource": ""
} |
q50877 | generate_brome_config | train | def generate_brome_config():
"""Generate a brome config with default value
Returns:
config (dict)
"""
config = {}
for key in iter(default_config):
for inner_key, value in iter(default_config[key].items()):
if key not in config:
config[key] = {}
... | python | {
"resource": ""
} |
q50878 | parse_brome_config_from_browser_config | train | def parse_brome_config_from_browser_config(browser_config):
"""Parse the browser config and look for brome specific config
Args:
browser_config (dict)
"""
config = {}
brome_keys = [key for key in browser_config if key.find(':') != -1]
for brome_key in brome_keys:
section, opt... | python | {
"resource": ""
} |
q50879 | grab_xml | train | def grab_xml(host, token=None):
"""Grab XML data from Gateway, returned as a dict."""
urllib3.disable_warnings()
if token:
scheme = "https"
if not token:
scheme = "http"
token = "1234567890"
url = (
scheme + '://' + host + '/gwr/gop.php?cmd=GWRBatch&data=<gwrcmds>... | python | {
"resource": ""
} |
q50880 | set_brightness | train | def set_brightness(host, did, value, token=None):
"""Set brightness of a bulb or fixture."""
urllib3.disable_warnings()
if token:
scheme = "https"
if not token:
scheme = "http"
token = "1234567890"
url = (
scheme + '://' + host + '/gwr/gop.php?cmd=DeviceSendComman... | python | {
"resource": ""
} |
q50881 | turn_on | train | def turn_on(host, did, token=None):
"""Turn on bulb or fixture"""
urllib3.disable_warnings()
if token:
scheme = "https"
if not token:
scheme = "http"
token = "1234567890"
url = (
scheme + '://' + host + '/gwr/gop.php?cmd=DeviceSendCommand&data=<gip><version>1</ver... | python | {
"resource": ""
} |
q50882 | grab_token | train | def grab_token(host, email, password):
"""Grab token from gateway. Press sync button before running."""
urllib3.disable_warnings()
url = ('https://' + host + '/gwr/gop.php?cmd=GWRLogin&data=<gip><version>1</version><email>' + str(email) + '</email><password>' + str(password) + '</password></gip>&fmt=xml')
... | python | {
"resource": ""
} |
q50883 | grab_bulbs | train | def grab_bulbs(host, token=None):
"""Grab XML, then add all bulbs to a dict. Removes room functionality"""
xml = grab_xml(host, token)
bulbs = {}
for room in xml:
for device in room['device']:
bulbs[int(device['did'])] = device
return bulbs | python | {
"resource": ""
} |
q50884 | IndexableManager.client | train | def client(self):
"""Get an elasticsearch client
"""
if not hasattr(self, "_client"):
self._client = connections.get_connection("default")
return self._client | python | {
"resource": ""
} |
q50885 | IndexableManager.mapping | train | def mapping(self):
"""Get a mapping class for this model
This method will return a Mapping class for your model, generating it using settings from a
`Mapping` class on your model (if one exists). The generated class is cached on the manager.
"""
if not hasattr(self, "_mapping"):... | python | {
"resource": ""
} |
q50886 | IndexableManager.from_es | train | def from_es(self, hit):
"""Returns a Django model instance, using a document from Elasticsearch"""
doc = hit.copy()
klass = shallow_class_factory(self.model)
# We can pass in the entire source, except when we have a non-indexable many-to-many
for field in self.model._meta.get_fi... | python | {
"resource": ""
} |
q50887 | IndexableManager.get | train | def get(self, **kwargs):
"""Get a object from Elasticsearch by id
"""
# get the doc id
id = None
if "id" in kwargs:
id = kwargs["id"]
del kwargs["id"]
elif "pk" in kwargs:
id = kwargs["pk"]
del kwargs["pk"]
else:
... | python | {
"resource": ""
} |
q50888 | IndexableManager.refresh | train | def refresh(self):
"""Force a refresh of the Elasticsearch index
"""
self.client.indices.refresh(index=self.model.search_objects.mapping.index) | python | {
"resource": ""
} |
q50889 | Indexable.to_dict | train | def to_dict(self):
"""Get a dictionary representation of this item, formatted for Elasticsearch"""
out = {}
fields = self.__class__.search_objects.mapping.properties.properties
for key in fields:
# TODO: What if we've mapped the property to a different name? Will we allow t... | python | {
"resource": ""
} |
q50890 | Indexable.delete_index | train | def delete_index(self, refresh=False, ignore=None):
"""Removes the object from the index if `indexed=False`"""
es = connections.get_connection("default")
index = self.__class__.search_objects.mapping.index
doc_type = self.__class__.search_objects.mapping.doc_type
es.delete(index,... | python | {
"resource": ""
} |
q50891 | Indexable.get_doc_types | train | def get_doc_types(cls, exclude_base=False):
"""Returns the doc_type of this class and all of its descendants."""
names = []
if not exclude_base and hasattr(cls, 'search_objects'):
if not getattr(cls.search_objects.mapping, "elastic_abstract", False):
names.append(cls.... | python | {
"resource": ""
} |
q50892 | TellCoreClient.start | train | def start(self):
"""Start client."""
self.proc = []
for telldus, port in (
(TELLDUS_CLIENT, self.port_client),
(TELLDUS_EVENTS, self.port_events)):
args = shlex.split(SOCAT_CLIENT.format(
type=telldus, host=self.host, port=port))
... | python | {
"resource": ""
} |
q50893 | TellCoreClient.stop | train | def stop(self):
"""Stop client."""
if self.proc:
for proc in self.proc:
proc.kill()
self.proc = None | python | {
"resource": ""
} |
q50894 | estimateKronCovariances | train | def estimateKronCovariances(phenos,K1r=None,K1c=None,K2r=None,K2c=None,covs=None,Acovs=None,covar_type='lowrank_diag',rank=1):
"""
estimates the background covariance model before testing
Args:
phenos: [N x P] SP.array of P phenotypes for N individuals
K1r: [N x N] SP.array of LMM-covari... | python | {
"resource": ""
} |
q50895 | updateKronCovs | train | def updateKronCovs(covs,Acovs,N,P):
"""
make sure that covs and Acovs are lists
"""
if (covs is None) and (Acovs is None):
covs = [SP.ones([N,1])]
Acovs = [SP.eye(P)]
if Acovs is None or covs is None:
raise Exception("Either Acovs or covs is None, while the other isn't")
... | python | {
"resource": ""
} |
q50896 | kronecker_lmm | train | def kronecker_lmm(snps,phenos,covs=None,Acovs=None,Asnps=None,K1r=None,K1c=None,K2r=None,K2c=None,covar_type='lowrank_diag',rank=1,NumIntervalsDelta0=100,NumIntervalsDeltaAlt=0,searchDelta=False):
"""
simple wrapper for kroneckerLMM code
Args:
snps: [N x S] SP.array of S SNPs for N individuals (t... | python | {
"resource": ""
} |
q50897 | simple_lmm | train | def simple_lmm(snps,pheno,K=None,covs=None, test='lrt',NumIntervalsDelta0=100,NumIntervalsDeltaAlt=0,searchDelta=False):
"""
Univariate fixed effects linear mixed model test for all SNPs
Args:
snps: [N x S] SP.array of S SNPs for N individuals
pheno: [N x 1] SP.array of 1 phenotype for N... | python | {
"resource": ""
} |
q50898 | interact_GxG | train | def interact_GxG(pheno,snps1,snps2=None,K=None,covs=None):
"""
Epistasis test between two sets of SNPs
Args:
pheno: [N x 1] SP.array of 1 phenotype for N individuals
snps1: [N x S1] SP.array of S1 SNPs for N individuals
snps2: [N x S2] SP.array of S2 SNPs for N individuals
... | python | {
"resource": ""
} |
q50899 | interact_GxE_1dof | train | def interact_GxE_1dof(snps,pheno,env,K=None,covs=None, test='lrt'):
"""
Univariate GxE fixed effects interaction linear mixed model test for all
pairs of SNPs and environmental variables.
Args:
snps: [N x S] SP.array of S SNPs for N individuals
pheno: [N x 1] SP.array of 1 phenotype ... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.