_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q43200 | average_over_area | train | def average_over_area(q, x, y):
"""Averages a quantity `q` over a rectangular area given a 2D array and
the x and y vectors for sample locations, using the trapezoidal rule"""
area = (np.max(x) - np.min(x))*(np.max(y) - np.min(y))
integral = np.trapz(np.trapz(q, y, axis=0), x)
return integral/a... | python | {
"resource": ""
} |
q43201 | build_plane_arrays | train | def build_plane_arrays(x, y, qlist):
"""Build a 2-D array out of data taken in the same plane, for contour
plotting.
"""
if type(qlist) is not list:
return_list = False
qlist = [qlist]
else:
return_list = True
xv = x[np.where(y==y[0])[0]]
yv = y[np.where(x==... | python | {
"resource": ""
} |
q43202 | corr_coeff | train | def corr_coeff(x1, x2, t, tau1, tau2):
"""Compute lagged correlation coefficient for two time series."""
dt = t[1] - t[0]
tau = np.arange(tau1, tau2+dt, dt)
rho = np.zeros(len(tau))
for n in range(len(tau)):
i = np.abs(int(tau[n]/dt))
if tau[n] >= 0: # Positive lag, push x2 fo... | python | {
"resource": ""
} |
q43203 | autocorr_coeff | train | def autocorr_coeff(x, t, tau1, tau2):
"""Calculate the autocorrelation coefficient."""
return corr_coeff(x, x, t, tau1, tau2) | python | {
"resource": ""
} |
q43204 | integral_scale | train | def integral_scale(u, t, tau1=0.0, tau2=1.0):
"""Calculate the integral scale of a time series by integrating up to
the first zero crossing.
"""
tau, rho = autocorr_coeff(u, t, tau1, tau2)
zero_cross_ind = np.where(np.diff(np.sign(rho)))[0][0]
int_scale = np.trapz(rho[:zero_cross_ind], tau... | python | {
"resource": ""
} |
q43205 | student_t | train | def student_t(degrees_of_freedom, confidence=0.95):
"""Return Student-t statistic for given DOF and confidence interval."""
return scipy.stats.t.interval(alpha=confidence,
df=degrees_of_freedom)[-1] | python | {
"resource": ""
} |
q43206 | calc_uncertainty | train | def calc_uncertainty(quantity, sys_unc, mean=True):
"""Calculate the combined standard uncertainty of a quantity."""
n = len(quantity)
std = np.nanstd(quantity)
if mean:
std /= np.sqrt(n)
return np.sqrt(std**2 + sys_unc**2) | python | {
"resource": ""
} |
q43207 | get_numbers | train | def get_numbers(s):
"""Extracts all integers from a string an return them in a list"""
result = map(int, re.findall(r'[0-9]+', unicode(s)))
return result + [1] * (2 - len(result)) | python | {
"resource": ""
} |
q43208 | Index.put | train | def put(self, key, value, element):
"""Puts an element in an index under a given
key-value pair
@params key: Index key string
@params value: Index value string
@params element: Vertex or Edge element to be indexed"""
self.neoindex[key][value] = element.neoelement | python | {
"resource": ""
} |
q43209 | Index.get | train | def get(self, key, value):
"""Gets an element from an index under a given
key-value pair
@params key: Index key string
@params value: Index value string
@returns A generator of Vertex or Edge objects"""
for element in self.neoindex[key][value]:
if self.indexCl... | python | {
"resource": ""
} |
q43210 | Index.remove | train | def remove(self, key, value, element):
"""Removes an element from an index under a given
key-value pair
@params key: Index key string
@params value: Index value string
@params element: Vertex or Edge element to be removed"""
self.neoindex.delete(key, value, element.neoele... | python | {
"resource": ""
} |
q43211 | Neo4jIndexableGraph.getIndices | train | def getIndices(self):
"""Returns a generator function over all the existing indexes
@returns A generator function over all rhe Index objects"""
for indexName in self.neograph.nodes.indexes.keys():
indexObject = self.neograph.nodes.indexes.get(indexName)
yield Index(index... | python | {
"resource": ""
} |
q43212 | Subversion.get_revision | train | def get_revision(self, location):
"""
Return the maximum revision for all files under a given location
"""
# Note: taken from setuptools.command.egg_info
revision = 0
for base, dirs, files in os.walk(location):
if self.dirname not in dirs:
dir... | python | {
"resource": ""
} |
q43213 | DigitWord.load | train | def load(self, value):
"""Load the value of the DigitWord from a JSON representation of a list. The representation is
validated to be a string and the encoded data a list. The list is then validated to ensure each
digit is a valid digit"""
if not isinstance(value, str):
rais... | python | {
"resource": ""
} |
q43214 | InstallCommand._build_package_finder | train | def _build_package_finder(self, options, index_urls):
"""
Create a package finder appropriate to this install command.
This method is meant to be overridden by subclasses, not
called directly.
"""
return PackageFinder(find_links=options.find_links,
... | python | {
"resource": ""
} |
q43215 | to_etree | train | def to_etree(source, root_tag=None):
""" Convert various representations of an XML structure to a etree Element
Args:
source -- The source object to be converted - ET.Element\ElementTree, dict or string.
Keyword args:
root_tag -- A optional parent tag in which to wrap the x... | python | {
"resource": ""
} |
q43216 | to_raw_xml | train | def to_raw_xml(source):
""" Convert various representations of an XML structure to a normal XML string.
Args:
source -- The source object to be converted - ET.Element, dict or string.
Returns:
A rew xml string matching the source object.
>>> to_raw_xml("<content/>")
... | python | {
"resource": ""
} |
q43217 | parse_arguments | train | def parse_arguments(filters, arguments, modern=False):
"""
Return a dict of parameters.
Take a list of filters and for each try to get the corresponding
value in arguments or a default value. Then check that value's type.
The @modern parameter indicates how the arguments should be
interpreted. T... | python | {
"resource": ""
} |
q43218 | check_type | train | def check_type(param, datatype):
"""
Make sure that param is of type datatype and return it.
If param is None, return it.
If param is an instance of datatype, return it.
If param is not an instance of datatype and is not None, cast it as
datatype and return it.
"""
if param is None:
... | python | {
"resource": ""
} |
q43219 | LocalRefResolver.resolve_local | train | def resolve_local(self, uri, base_uri, ref):
"""
Resolve a local ``uri``.
Does not check the store first.
:argument str uri: the URI to resolve
:returns: the retrieved document
"""
# read it from the filesystem
file_path = None
# make the refe... | python | {
"resource": ""
} |
q43220 | cached | train | def cached(func):
"""
A decorator function to cache values. It uses the decorated
function's arguments as the keys to determine if the function
has been called previously.
"""
cache = {}
@f.wraps(func)
def wrapper(*args, **kwargs):
key = func.__name__ + str(sorted(args)) + str(s... | python | {
"resource": ""
} |
q43221 | retry_ex | train | def retry_ex(callback, times=3, cap=120000):
"""
Retry a callback function if any exception is raised.
:param function callback: The function to call
:keyword int times: Number of times to retry on initial failure
:keyword int cap: Maximum wait time in milliseconds
:returns: The return value of... | python | {
"resource": ""
} |
q43222 | retry_bool | train | def retry_bool(callback, times=3, cap=120000):
"""
Retry a callback function if it returns False.
:param function callback: The function to call
:keyword int times: Number of times to retry on initial failure
:keyword int cap: Maximum wait time in milliseconds
:returns: The return value of the ... | python | {
"resource": ""
} |
q43223 | retryable | train | def retryable(retryer=retry_ex, times=3, cap=120000):
"""
A decorator to make a function retry. By default the retry
occurs when an exception is thrown, but this may be changed
by modifying the ``retryer`` argument.
See also :py:func:`retry_ex` and :py:func:`retry_bool`. By
default :py:func:`re... | python | {
"resource": ""
} |
q43224 | ensure_environment | train | def ensure_environment(variables):
"""
Check os.environ to ensure that a given collection of
variables has been set.
:param variables: A collection of environment variable names
:returns: os.environ
:raises IncompleteEnvironment: if any variables are not set, with
the exception's ``vari... | python | {
"resource": ""
} |
q43225 | change_column_length | train | def change_column_length(table: Table, column: Column, length: int, engine: Engine) -> None:
""" Change the column length in the supplied table
"""
if column.type.length < length:
print("Changing length of {} from {} to {}".format(column, column.type.length, length))
column.type.length = len... | python | {
"resource": ""
} |
q43226 | isdir | train | def isdir(path, message):
"""
Raise an exception if the given directory does not exist.
:param path: The path to a directory to be tested
:param message: A custom message to report in the exception
:raises: FileNotFoundError
"""
if not os.path.isdir(path):
raise FileNotFoundError(
... | python | {
"resource": ""
} |
q43227 | _HeraldInputStream.readline | train | def readline(self):
"""
Waits for a line from the Herald client
"""
content = {"session_id": self._session}
prompt_msg = self._herald.send(
self._peer, beans.Message(MSG_CLIENT_PROMPT, content))
if prompt_msg.subject == MSG_SERVER_CLOSE:
# Client c... | python | {
"resource": ""
} |
q43228 | make_frog_fresco | train | def make_frog_fresco(text, width, padding=8):
"""\
Formats your lovely text into a speech bubble spouted by this adorable
little frog.
"""
stem = r' /'
frog = r"""
{text}
{stem}
@..@
(----)
( >__< )
^^ ~~ ^^"""
offset = len(stem) - 1
formatted_indent = ' ' * offset
formatt... | python | {
"resource": ""
} |
q43229 | mgz_to_nifti | train | def mgz_to_nifti(filename,prefix=None,gzip=True):
'''Convert ``filename`` to a NIFTI file using ``mri_convert``'''
setup_freesurfer()
if prefix==None:
prefix = nl.prefix(filename) + '.nii'
if gzip and not prefix.endswith('.gz'):
prefix += '.gz'
nl.run([os.path.join(freesurfer_home,'b... | python | {
"resource": ""
} |
q43230 | guess_home | train | def guess_home():
'''If ``freesurfer_home`` is not set, try to make an intelligent guess at it'''
global freesurfer_home
if freesurfer_home != None:
return True
# if we already have it in the path, use that
fv = nl.which('freeview')
if fv:
freesurfer_home = parpar_dir(os.path.rea... | python | {
"resource": ""
} |
q43231 | setup_freesurfer | train | def setup_freesurfer():
'''Setup the freesurfer environment variables'''
guess_home()
os.environ['FREESURFER_HOME'] = freesurfer_home
os.environ['SUBJECTS_DIR'] = subjects_dir
# Run the setup script and collect the output:
o = subprocess.check_output(['bash','-c','source %s/SetUpFreeSurfer.sh &&... | python | {
"resource": ""
} |
q43232 | recon_all | train | def recon_all(subj_id,anatomies):
'''Run the ``recon_all`` script'''
if not environ_setup:
setup_freesurfer()
if isinstance(anatomies,basestring):
anatomies = [anatomies]
nl.run([os.path.join(freesurfer_home,'bin','recon-all'),'-all','-subjid',subj_id] + [['-i',anat] for anat in anatomie... | python | {
"resource": ""
} |
q43233 | parse_docstring | train | def parse_docstring(docstring):
"""
Parse a PEP-257 docstring.
SHORT -> blank line -> LONG
"""
short_desc = long_desc = ''
if docstring:
docstring = trim(docstring.lstrip('\n'))
lines = docstring.split('\n\n', 1)
short_desc = lines[0].strip().replace('\n', ' ')
... | python | {
"resource": ""
} |
q43234 | CLI.load_commands | train | def load_commands(self, obj):
"""
Load commands defined on an arbitrary object.
All functions decorated with the :func:`subparse.command` decorator
attached the specified object will be loaded. The object may
be a dictionary, an arbitrary python object, or a dotted path.
... | python | {
"resource": ""
} |
q43235 | CLI.load_commands_from_entry_point | train | def load_commands_from_entry_point(self, specifier):
"""
Load commands defined within a pkg_resources entry point.
Each entry will be a module that should be searched for functions
decorated with the :func:`subparse.command` decorator. This
operation is not recursive.
"... | python | {
"resource": ""
} |
q43236 | CLI.run | train | def run(self, argv=None):
"""
Run the command-line application.
This will dispatch to the specified function or raise a
``SystemExit`` and output the appropriate usage information
if there is an error parsing the arguments.
The default ``argv`` is equivalent to ``sys.ar... | python | {
"resource": ""
} |
q43237 | remove_small_objects | train | def remove_small_objects(image, min_size=50, connectivity=1):
"""Remove small objects from an boolean image.
:param image: boolean numpy array or :class:`jicbioimage.core.image.Image`
:returns: boolean :class:`jicbioimage.core.image.Image`
"""
return skimage.morphology.remove_small_objects(image,
... | python | {
"resource": ""
} |
q43238 | invert | train | def invert(image):
"""Return an inverted image of the same dtype.
Assumes the full range of the input dtype is in use and
that no negative values are present in the input image.
:param image: :class:`jicbioimage.core.image.Image`
:returns: inverted image of the same dtype as the input
"""
... | python | {
"resource": ""
} |
q43239 | CompletedProcess.check_returncode | train | def check_returncode(self):
"""Raise CalledProcessError if the exit code is non-zero."""
if self.returncode:
raise CalledProcessError(self.returncode, self.args, self.stdout,
self.stderr) | python | {
"resource": ""
} |
q43240 | double_lorgauss | train | def double_lorgauss(x,p):
"""Evaluates a normalized distribution that is a mixture of a double-sided Gaussian and Double-sided Lorentzian.
Parameters
----------
x : float or array-like
Value(s) at which to evaluate distribution
p : array-like
Input parameters: mu (mode of distribut... | python | {
"resource": ""
} |
q43241 | doublegauss | train | def doublegauss(x,p):
"""Evaluates normalized two-sided Gaussian distribution
Parameters
----------
x : float or array-like
Value(s) at which to evaluate distribution
p : array-like
Parameters of distribution: (mu: mode of distribution,
sig1: LH... | python | {
"resource": ""
} |
q43242 | doublegauss_cdf | train | def doublegauss_cdf(x,p):
"""Cumulative distribution function for two-sided Gaussian
Parameters
----------
x : float
Input values at which to calculate CDF.
p : array-like
Parameters of distribution: (mu: mode of distribution,
sig1: LH width,
... | python | {
"resource": ""
} |
q43243 | fit_doublegauss_samples | train | def fit_doublegauss_samples(samples,**kwargs):
"""Fits a two-sided Gaussian to a set of samples.
Calculates 0.16, 0.5, and 0.84 quantiles and passes these to
`fit_doublegauss` for fitting.
Parameters
----------
samples : array-like
Samples to which to fit the Gaussian.
kwargs
... | python | {
"resource": ""
} |
q43244 | fit_doublegauss | train | def fit_doublegauss(med,siglo,sighi,interval=0.683,p0=None,median=False,return_distribution=True):
"""Fits a two-sided Gaussian distribution to match a given confidence interval.
The center of the distribution may be either the median or the mode.
Parameters
----------
med : float
The cent... | python | {
"resource": ""
} |
q43245 | Distribution.pctile | train | def pctile(self,pct,res=1000):
"""Returns the desired percentile of the distribution.
Will only work if properly normalized. Designed to mimic
the `ppf` method of the `scipy.stats` random variate objects.
Works by gridding the CDF at a given resolution and matching the nearest
... | python | {
"resource": ""
} |
q43246 | Distribution.save_hdf | train | def save_hdf(self,filename,path='',res=1000,logspace=False):
"""Saves distribution to an HDF5 file.
Saves a pandas `dataframe` object containing tabulated pdf and cdf
values at a specfied resolution. After saving to a particular path, a
distribution may be regenerated using the `Distri... | python | {
"resource": ""
} |
q43247 | Distribution.plot | train | def plot(self,minval=None,maxval=None,fig=None,log=False,
npts=500,**kwargs):
"""
Plots distribution.
Parameters
----------
minval : float,optional
minimum value to plot. Required if minval of Distribution is
`-np.inf`.
maxval : fl... | python | {
"resource": ""
} |
q43248 | Distribution.resample | train | def resample(self,N,minval=None,maxval=None,log=False,res=1e4):
"""Returns random samples generated according to the distribution
Mirrors basic functionality of `rvs` method for `scipy.stats`
random variates. Implemented by mapping uniform numbers onto the
inverse CDF using a closest-m... | python | {
"resource": ""
} |
q43249 | Hist_Distribution.resample | train | def resample(self,N):
"""Returns a bootstrap resampling of provided samples.
Parameters
----------
N : int
Number of samples.
"""
inds = rand.randint(len(self.samples),size=N)
return self.samples[inds] | python | {
"resource": ""
} |
q43250 | Box_Distribution.resample | train | def resample(self,N):
"""Returns a random sampling.
"""
return rand.random(size=N)*(self.maxval - self.minval) + self.minval | python | {
"resource": ""
} |
q43251 | DoubleGauss_Distribution.resample | train | def resample(self,N,**kwargs):
"""Random resampling of the doublegauss distribution
"""
lovals = self.mu - np.absolute(rand.normal(size=N)*self.siglo)
hivals = self.mu + np.absolute(rand.normal(size=N)*self.sighi)
u = rand.random(size=N)
hi = (u < float(self.sighi)/(self... | python | {
"resource": ""
} |
q43252 | tzname_in_python2 | train | def tzname_in_python2(myfunc):
"""Change unicode output into bytestrings in Python 2
tzname() API changed in Python 3. It used to return bytes, but was changed
to unicode strings
"""
def inner_func(*args, **kwargs):
if PY3:
return myfunc(*args, **kwargs)
else:
... | python | {
"resource": ""
} |
q43253 | ac3 | train | def ac3(space):
"""
AC-3 algorithm. This reduces the domains of the variables by
propagating constraints to ensure arc consistency.
:param Space space: The space to reduce
"""
#determine arcs
arcs = {}
for name in space.variables:
arcs[name] = set([])
for const in space.cons... | python | {
"resource": ""
} |
q43254 | _unary | train | def _unary(space,const,name):
"""
Reduce the domain of variable name to be node-consistent with this
constraint, i.e. remove those values for the variable that are not
consistent with the constraint.
returns True if the domain of name was modified
"""
if not name in const.vnames:
re... | python | {
"resource": ""
} |
q43255 | solve | train | def solve(space,method='backtrack',ordering=None):
"""
Generator for all solutions.
:param str method: the solution method to employ
:param ordering: an optional parameter ordering
:type ordering: sequence of parameter names
Methods:
:"backtrack": simple chronological backtracking
:"... | python | {
"resource": ""
} |
q43256 | get_task_parser | train | def get_task_parser(task):
"""
Construct an ArgumentParser for the given task.
This function returns a tuple (parser, proxy_args).
If task accepts varargs only, proxy_args is True.
If task accepts only positional and explicit keyword args,
proxy args is False.
"""
args, varargs, keyword... | python | {
"resource": ""
} |
q43257 | invoke_task | train | def invoke_task(task, args):
"""
Parse args and invoke task function.
:param task: task function to invoke
:param args: arguments to the task (list of str)
:return: result of task function
:rtype: object
"""
parser, proxy_args = get_task_parser(task)
if proxy_args:
return ta... | python | {
"resource": ""
} |
q43258 | get_task_module | train | def get_task_module(feature):
"""
Return imported task module of feature.
This function first tries to import the feature and raises FeatureNotFound
if that is not possible.
Thereafter, it looks for a submodules called ``apetasks`` and ``tasks`` in that order.
If such a submodule exists, it is ... | python | {
"resource": ""
} |
q43259 | run | train | def run(args, features=None):
"""
Run an ape task.
Composes task modules out of the selected features and calls the
task with arguments.
:param args: list comprised of task name followed by arguments
:param features: list of features to compose before invoking the task
"""
features = f... | python | {
"resource": ""
} |
q43260 | main | train | def main():
"""
Entry point when used via command line.
Features are given using the environment variable ``PRODUCT_EQUATION``.
If it is not set, ``PRODUCT_EQUATION_FILENAME`` is tried: if it points
to an existing equation file that selection is used.
(if ``APE_PREPEND_FEATURES`` is given, tho... | python | {
"resource": ""
} |
q43261 | CollectNewMixin.collect | train | def collect(self):
"""
Perform the bulk of the work of collectstatic.
Split off from handle_noargs() to facilitate testing.
"""
if self.symlink:
if sys.platform == 'win32':
raise CommandError("Symlinking is not supported by this "
... | python | {
"resource": ""
} |
q43262 | CollectNewMixin.compare | train | def compare(self, path, prefixed_path, source_storage):
"""
Returns True if the file should be copied.
"""
# First try a method on the command named compare_<comparison_method>
# If that doesn't exist, create a comparitor that calls methods on the
# storage with the name ... | python | {
"resource": ""
} |
q43263 | verify_session | train | def verify_session(session, baseurl):
"""
Check that this session is still valid on this baseurl, ie, we get a list of projects
"""
request = session.post(baseurl+"/select_projet.php")
return VERIFY_SESSION_STRING in request.content.decode('iso-8859-1') | python | {
"resource": ""
} |
q43264 | get_session | train | def get_session(session, baseurl, config):
"""
Try to get a valid session for this baseurl, using login found in config.
This function invoques Firefox if necessary
"""
# Read proxy for firefox
if environ.get("HTTP_PROXY"):
myProxy = environ.get("HTTP_PROXY")
proxy = Proxy({
... | python | {
"resource": ""
} |
q43265 | LM.display | train | def display(self):
'''
Displays statistics about our LM
'''
voc_list = []
doc_ids = self.term_count_n.keys()
doc_ids.sort()
for doc_id in doc_ids:
ngrams = len(self.term_count_n[doc_id]['ngrams'])
print 'n-Grams (doc %s): %d' % (str(doc_id)... | python | {
"resource": ""
} |
q43266 | LM.get_ngram_counts | train | def get_ngram_counts(self):
''' Returns a list of n-gram counts
Array of classes counts and last item is for corpus
'''
ngram_counts = {
'classes': [],
'corpus': 0
}
doc_ids = self.term_count_n.keys()
doc_ids.sort()
for doc_id i... | python | {
"resource": ""
} |
q43267 | LM.lr_padding | train | def lr_padding(self, terms):
'''
Pad doc from the left and right before adding,
depending on what's in self.lpad and self.rpad
If any of them is '', then don't pad there.
'''
lpad = rpad = []
if self.lpad:
lpad = [self.lpad] * (self.n - 1)
if... | python | {
"resource": ""
} |
q43268 | PressEnter2ExitGUI.run | train | def run(self):
"""
pop up a dialog box and return when the user has closed it
"""
response = None
root = tkinter.Tk()
root.withdraw()
while response is not True:
response = tkinter.messagebox.askokcancel(title=self.title, message=self.pre_message)
... | python | {
"resource": ""
} |
q43269 | download | train | def download(url, file=None):
"""
Pass file as a filename, open file object, or None to return the request bytes
Args:
url (str): URL of file to download
file (Union[str, io, None]): One of the following:
- Filename of output file
- File opened in binary write mode... | python | {
"resource": ""
} |
q43270 | download_extract_tar | train | def download_extract_tar(tar_url, folder, tar_filename=''):
"""
Download and extract the tar at the url to the given folder
Args:
tar_url (str): URL of tar file to download
folder (str): Location of parent directory to extract to. Doesn't have to exist
tar_filename (str): Location t... | python | {
"resource": ""
} |
q43271 | install_package | train | def install_package(tar_url, folder, md5_url='{tar_url}.md5',
on_download=lambda: None, on_complete=lambda: None):
"""
Install or update a tar package that has an md5
Args:
tar_url (str): URL of package to download
folder (str): Location to extract tar. Will be created i... | python | {
"resource": ""
} |
q43272 | _process_cell | train | def _process_cell(i, state, finite=False):
"""Process 3 cells and return a value from 0 to 7. """
op_1 = state[i - 1]
op_2 = state[i]
if i == len(state) - 1:
if finite:
op_3 = state[0]
else:
op_3 = 0
else:
op_3 = state[i + 1]
result = 0
for i, ... | python | {
"resource": ""
} |
q43273 | _remove_lead_trail_false | train | def _remove_lead_trail_false(bool_list):
"""Remove leading and trailing false's from a list"""
# The internet can be a wonderful place...
for i in (0, -1):
while bool_list and not bool_list[i]:
bool_list.pop(i)
return bool_list | python | {
"resource": ""
} |
q43274 | _crop_list_to_size | train | def _crop_list_to_size(l, size):
"""Make a list a certain size"""
for x in range(size - len(l)):
l.append(False)
for x in range(len(l) - size):
l.pop()
return l | python | {
"resource": ""
} |
q43275 | JobManagerLocal.submit | train | def submit(self, command_line, name = None, array = None, dependencies = [], exec_dir = None, log_dir = None, dry_run = False, stop_on_failure = False, **kwargs):
"""Submits a job that will be executed on the local machine during a call to "run".
All kwargs will simply be ignored."""
# remove duplicate depe... | python | {
"resource": ""
} |
q43276 | JobManagerLocal.stop_jobs | train | def stop_jobs(self, job_ids=None):
"""Resets the status of the job to 'submitted' when they are labeled as 'executing'."""
self.lock()
jobs = self.get_jobs(job_ids)
for job in jobs:
if job.status in ('executing', 'queued', 'waiting') and job.queue_name == 'local':
logger.info("Reset job '... | python | {
"resource": ""
} |
q43277 | JobManagerLocal.stop_job | train | def stop_job(self, job_id, array_id = None):
"""Resets the status of the given to 'submitted' when they are labeled as 'executing'."""
self.lock()
job, array_job = self._job_and_array(job_id, array_id)
if job is not None:
if job.status in ('executing', 'queued', 'waiting'):
logger.info("R... | python | {
"resource": ""
} |
q43278 | JobManagerLocal._run_parallel_job | train | def _run_parallel_job(self, job_id, array_id = None, no_log = False, nice = None, verbosity = 0):
"""Executes the code for this job on the local machine."""
environ = copy.deepcopy(os.environ)
environ['JOB_ID'] = str(job_id)
if array_id:
environ['SGE_TASK_ID'] = str(array_id)
else:
envir... | python | {
"resource": ""
} |
q43279 | html_to_text | train | def html_to_text(html, base_url='', bodywidth=CONFIG_DEFAULT):
"""
Convert a HTML mesasge to plain text.
"""
def _patched_handle_charref(c):
self = h
charref = self.charref(c)
if self.code or self.pre:
charref = cgi.escape(charref)
self.o(charref, 1)
def ... | python | {
"resource": ""
} |
q43280 | render_email_template | train | def render_email_template(email_template, base_url, extra_context=None, user=None):
"""
Render the email template.
:type email_template: fluentcms_emailtemplates.models.EmailTemplate
:type base_url: str
:type extra_context: dict | None
:type user: django.contrib.auth.models.User
:return: Th... | python | {
"resource": ""
} |
q43281 | _make_links_absolute | train | def _make_links_absolute(html, base_url):
"""
Make all links absolute.
"""
url_changes = []
soup = BeautifulSoup(html)
for tag in soup.find_all('a', href=True):
old = tag['href']
fixed = urljoin(base_url, old)
if old != fixed:
url_changes.append((old, fixed))... | python | {
"resource": ""
} |
q43282 | string_to_datetime | train | def string_to_datetime(date):
"""Return a datetime.datetime instance with tzinfo.
I.e. a timezone aware datetime instance.
Acceptable formats for input are:
* 2012-01-10T12:13:14
* 2012-01-10T12:13:14.98765
* 2012-01-10T12:13:14.98765+03:00
* 2012-01-10T12:13:14.98765Z
... | python | {
"resource": ""
} |
q43283 | date_to_string | train | def date_to_string(date):
"""Transform a date or datetime object into a string and return it.
Examples:
>>> date_to_string(datetime.datetime(2012, 1, 3, 12, 23, 34, tzinfo=UTC))
'2012-01-03T12:23:34+00:00'
>>> date_to_string(datetime.datetime(2012, 1, 3, 12, 23, 34))
'2012-01-03T12:23:34'
>... | python | {
"resource": ""
} |
q43284 | uuid_to_date | train | def uuid_to_date(uuid, century='20'):
"""Return a date created from the last 6 digits of a uuid.
Arguments:
uuid The unique identifier to parse.
century The first 2 digits to assume in the year. Default is '20'.
Examples:
>>> uuid_to_date('e8820616-1462-49b6-9784-e99a32120201')
... | python | {
"resource": ""
} |
q43285 | hardware_info | train | def hardware_info():
"""
Returns basic hardware information about the computer.
Gives actual number of CPU's in the machine, even when hyperthreading is
turned on.
Returns
-------
info : dict
Dictionary containing cpu and memory information.
"""
try:
if sys.platfor... | python | {
"resource": ""
} |
q43286 | add | train | async def add(client: Client, identity_signed_raw: str) -> ClientResponse:
"""
POST identity raw document
:param client: Client to connect to the api
:param identity_signed_raw: Identity raw document
:return:
"""
return await client.post(MODULE + '/add', {'identity': identity_signed_raw}, r... | python | {
"resource": ""
} |
q43287 | certify | train | async def certify(client: Client, certification_signed_raw: str) -> ClientResponse:
"""
POST certification raw document
:param client: Client to connect to the api
:param certification_signed_raw: Certification raw document
:return:
"""
return await client.post(MODULE + '/certify', {'cert':... | python | {
"resource": ""
} |
q43288 | revoke | train | async def revoke(client: Client, revocation_signed_raw: str) -> ClientResponse:
"""
POST revocation document
:param client: Client to connect to the api
:param revocation_signed_raw: Certification raw document
:return:
"""
return await client.post(MODULE + '/revoke', {'revocation': revocati... | python | {
"resource": ""
} |
q43289 | identity_of | train | async def identity_of(client: Client, search: str) -> dict:
"""
GET Identity data written in the blockchain
:param client: Client to connect to the api
:param search: UID or public key
:return:
"""
return await client.get(MODULE + '/identity-of/%s' % search, schema=IDENTITY_OF_SCHEMA) | python | {
"resource": ""
} |
q43290 | shell_exec | train | def shell_exec(command, **kwargs): # from gitapi.py
"""Excecutes the given command silently.
"""
proc = Popen(shlex.split(command), stdout=PIPE, stderr=PIPE, **kwargs)
out, err = [x.decode("utf-8") for x in proc.communicate()]
return {'out': out, 'err': err, 'code': proc.returncode} | python | {
"resource": ""
} |
q43291 | run | train | def run(command, **kwargs):
"""Excecutes the given command while transfering control, till the execution is complete.
"""
print command
p = Popen(shlex.split(command), **kwargs)
p.wait()
return p.returncode | python | {
"resource": ""
} |
q43292 | data | train | def data(tableid,
variables=dict(),
stream=False,
descending=False,
lang=DEFAULT_LANGUAGE):
"""Pulls data from a table and generates rows.
Variables is a dictionary mapping variable codes to values.
Streaming:
Values must be chosen for all variables when streaming
... | python | {
"resource": ""
} |
q43293 | subjects | train | def subjects(subjects=None,
recursive=False,
include_tables=False,
lang=DEFAULT_LANGUAGE):
"""List subjects from the subject hierarchy.
If subjects is not given, the root subjects will be used.
Returns a generator.
"""
request = Request('subjects', *subjects,... | python | {
"resource": ""
} |
q43294 | tableinfo | train | def tableinfo(tableid, lang=DEFAULT_LANGUAGE):
"""Fetch metadata for statbank table
Metadata includes information about variables,
which can be used when extracting data.
"""
request = Request('tableinfo', tableid, lang=lang)
return Tableinfo(request.json, lang=lang) | python | {
"resource": ""
} |
q43295 | tables | train | def tables(subjects=None,
pastDays=None,
include_inactive=False,
lang=DEFAULT_LANGUAGE):
"""Find tables placed under given subjects.
"""
request = Request('tables',
subjects=subjects,
pastDays=pastDays,
includ... | python | {
"resource": ""
} |
q43296 | API.request_method | train | def request_method(self, method: str,
**method_kwargs: Union[str, int]) -> dict:
"""
Process method request and return json with results
:param method: str: specifies the method, example: "users.get"
:param method_kwargs: dict: method parameters,
example: ... | python | {
"resource": ""
} |
q43297 | API.request_get_user | train | def request_get_user(self, user_ids) -> dict:
"""
Method to get users by ID, do not need authorization
"""
method_params = {'user_ids': user_ids}
response = self.session.send_method_request('users.get', method_params)
self.check_for_errors('users.get', method_params, resp... | python | {
"resource": ""
} |
q43298 | API.request_set_status | train | def request_set_status(self, text: str) -> dict:
"""
Method to set user status
"""
method_params = {'text': text}
response = self.session.send_method_request('status.set',
method_params)
self.check_for_errors('status.set... | python | {
"resource": ""
} |
q43299 | run_spy | train | def run_spy(group, port, verbose):
"""
Runs the multicast spy
:param group: Multicast group
:param port: Multicast port
:param verbose: If True, prints more details
"""
# Create the socket
socket, group = multicast.create_multicast_socket(group, port)
print("Socket created:", group,... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.