_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q43100 | Client.frog_tip | train | def frog_tip(self):
"""\
Return a single FROG tip.
"""
cache = self._cache
client = self._client
if self.should_refresh:
tips = client.croak()
for number, tip in tips.items():
cache[str(number)] = tip
choice = random.choic... | python | {
"resource": ""
} |
q43101 | cli | train | def cli(dirty, stash):
"""
This is a tool that handles all the tasks to build a Python application
This tool is installed as a setuptools entry point, which means it should be accessible from your terminal once
this application is installed in develop mode.
"""
_setup_logging()
LOGGER.info... | python | {
"resource": ""
} |
q43102 | _handle_response | train | def _handle_response(response, command, id_xpath='./id', **kwargs):
""" Initialize the corect Response object from the response string based on the API command type. """
_response_switch = {
'insert': ModifyResponse,
'replace': ModifyResponse,
'partial-replace': ModifyResponse,
'... | python | {
"resource": ""
} |
q43103 | Response._parse_for_errors | train | def _parse_for_errors(self):
""" Look for an error tag and raise APIError for fatal errors or APIWarning for nonfatal ones. """
error = self._response.find('{www.clusterpoint.com}error')
if error is not None:
if error.find('level').text.lower() in ('rejected', 'failed', 'error', 'fat... | python | {
"resource": ""
} |
q43104 | Response.get_content_string | train | def get_content_string(self):
""" Ge thet Clusterpoint response's content as a string. """
return ''.join([ET.tostring(element, encoding="utf-8", method="xml")
for element in list(self._content)]) | python | {
"resource": ""
} |
q43105 | Response.get_content_field | train | def get_content_field(self, name):
""" Get the contents of a specific subtag from Clusterpoint Storage's response's content tag.
Args:
name -- A name string of the content's subtag to be returned.
Returns:
A dict representing the contents of the specifie... | python | {
"resource": ""
} |
q43106 | ListResponse.get_documents | train | def get_documents(self, doc_format='dict'):
""" Get the documents returned from Storege in this response.
Keyword args:
doc_format -- Specifies the doc_format for the returned documents.
Can be 'dict', 'etree' or 'string'. Default is 'dict'.
Returns:... | python | {
"resource": ""
} |
q43107 | SearchResponse.get_aggregate | train | def get_aggregate(self):
""" Get aggregate data.
Returns:
A dict in with queries as keys and results as values.
"""
return dict([(aggregate.find('query').text, [(ET.tostring(data).lstrip('<data xmlns:cps="www.clusterpoint.com" xmlns:cpse="www.clusterpoint.com">').str... | python | {
"resource": ""
} |
q43108 | WordsResponse.get_words | train | def get_words(self):
""" Get words matching the request search terms.
Returns:
A dict in form:
{<search term>: {<matching word>: <number of times this word is found in the Storage>
} // Repeated for every matching word.
... | python | {
"resource": ""
} |
q43109 | AlternativesResponse.get_alternatives | train | def get_alternatives(self):
""" Get the spelling alternatives for search terms.
Returns:
A dict in form:
{<search term>: {'count': <number of times the searh term occurs in the Storage>,
'words': {<an alternative>: {'count': <number o... | python | {
"resource": ""
} |
q43110 | ListFacetsResponse.get_facets | train | def get_facets(self):
""" Get facets from the response.
Returns:
A dict where requested facet paths are keys and a list of coresponding terms are values.
"""
return dict([(facet.attrib['path'], [term.text
for term in facet... | python | {
"resource": ""
} |
q43111 | HttpClient._process_response | train | def _process_response(self):
"""Return a JSON result after an HTTP Request.
Process the response of an HTTP Request and make it a JSON error if
it failed. Otherwise return the response's content.
"""
response = self.conn.getresponse()
if response.status == 200 or respon... | python | {
"resource": ""
} |
q43112 | HttpClient.post | train | def post(self, url, data):
"""Send a HTTP POST request to a URL and return the result.
"""
headers = {
"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/json"
}
self.conn.request("POST", url, data, headers)
return self._process_r... | python | {
"resource": ""
} |
q43113 | HttpClient.put | train | def put(self, url, data=None):
"""Send a HTTP PUT request to a URL and return the result.
"""
self.conn.request("PUT", url, data)
return self._process_response() | python | {
"resource": ""
} |
q43114 | ServerAbstract.nginx_web_ssl_config | train | def nginx_web_ssl_config(self):
"""
Nginx web ssl config
"""
dt = [self.nginx_web_dir, self.nginx_ssl_dir]
return nginx_conf_string.simple_ssl_web_conf.format(dt=dt) | python | {
"resource": ""
} |
q43115 | extract_feature_base | train | def extract_feature_base(dbpath, folder_path, set_object, extractor, force_extraction=False, verbose=0,
add_args=None, custom_name=None):
"""
Generic function which extracts a feature and stores it in the database
Parameters
----------
dbpath : string, path to SQLite databa... | python | {
"resource": ""
} |
q43116 | return_features_base | train | def return_features_base(dbpath, set_object, names):
"""
Generic function which returns a list of extracted features from the database
Parameters
----------
dbpath : string, path to SQLite database file
set_object : object (either TestSet or TrainSet) which is stored in the database
names :... | python | {
"resource": ""
} |
q43117 | return_features_numpy_base | train | def return_features_numpy_base(dbpath, set_object, points_amt, names):
"""
Generic function which returns a 2d numpy array of extracted features
Parameters
----------
dbpath : string, path to SQLite database file
set_object : object (either TestSet or TrainSet) which is stored in the database
... | python | {
"resource": ""
} |
q43118 | return_real_id_base | train | def return_real_id_base(dbpath, set_object):
"""
Generic function which returns a list of real_id's
Parameters
----------
dbpath : string, path to SQLite database file
set_object : object (either TestSet or TrainSet) which is stored in the database
Returns
-------
return_list : lis... | python | {
"resource": ""
} |
q43119 | return_feature_list_base | train | def return_feature_list_base(dbpath, set_object):
"""
Generic function which returns a list of the names of all available features
Parameters
----------
dbpath : string, path to SQLite database file
set_object : object (either TestSet or TrainSet) which is stored in the database
Returns
... | python | {
"resource": ""
} |
q43120 | return_single_real_id_base | train | def return_single_real_id_base(dbpath, set_object, object_id):
"""
Generic function which returns a real_id string of an object specified by the object_id
Parameters
----------
dbpath : string, path to SQLite database file
set_object : object (either TestSet or TrainSet) which is stored in the ... | python | {
"resource": ""
} |
q43121 | return_single_features_base | train | def return_single_features_base(dbpath, set_object, object_id):
"""
Generic function which returns the features of an object specified by the object_id
Parameters
----------
dbpath : string, path to SQLite database file
set_object : object (either TestSet or TrainSet) which is stored in the dat... | python | {
"resource": ""
} |
q43122 | return_single_convert_numpy_base | train | def return_single_convert_numpy_base(dbpath, folder_path, set_object, object_id, converter, add_args=None):
"""
Generic function which converts an object specified by the object_id into a numpy array and returns the array,
the conversion is done by the 'converter' function
Parameters
----------
... | python | {
"resource": ""
} |
q43123 | delete_feature_base | train | def delete_feature_base(dbpath, set_object, name):
"""
Generic function which deletes a feature from a database
Parameters
----------
dbpath : string, path to SQLite database file
set_object : object (either TestSet or TrainSet) which is stored in the database
name : string, name of the fea... | python | {
"resource": ""
} |
q43124 | DataSetBase.extract_feature | train | def extract_feature(self, extractor, force_extraction=False, verbose=0, add_args=None, custom_name=None):
"""
Extracts a feature and stores it in the database
Parameters
----------
extractor : function, which takes the path of a data point and *args as parameters and returns a f... | python | {
"resource": ""
} |
q43125 | DataSetBase.extract_feature_dependent_feature | train | def extract_feature_dependent_feature(self, extractor, force_extraction=False, verbose=0, add_args=None,
custom_name=None):
"""
Extracts a feature which may be dependent on other features and stores it in the database
Parameters
----------
... | python | {
"resource": ""
} |
q43126 | DataSetBase.return_features | train | def return_features(self, names='all'):
"""
Returns a list of extracted features from the database
Parameters
----------
names : list of strings, a list of feature names which are to be retrieved from the database, if equal
to 'all', the all features will be returned, de... | python | {
"resource": ""
} |
q43127 | DataSetBase.return_features_numpy | train | def return_features_numpy(self, names='all'):
"""
Returns a 2d numpy array of extracted features
Parameters
----------
names : list of strings, a list of feature names which are to be retrieved from the database, if equal to 'all',
all features will be returned, default ... | python | {
"resource": ""
} |
q43128 | DataSetBase.return_real_id | train | def return_real_id(self):
"""
Returns a list of real_id's
Parameters
----------
Returns
-------
A list of real_id values for the dataset (a real_id is the filename minus the suffix and prefix)
"""
if self._prepopulated is False:
raise... | python | {
"resource": ""
} |
q43129 | DataSetBase.return_single_convert_numpy | train | def return_single_convert_numpy(self, object_id, converter, add_args=None):
"""
Converts an object specified by the object_id into a numpy array and returns the array,
the conversion is done by the 'converter' function
Parameters
----------
object_id : int, id of object ... | python | {
"resource": ""
} |
q43130 | LabeledDataSet.return_labels | train | def return_labels(self, original=False):
"""
Returns the labels of the dataset
Parameters
----------
original : if True, will return original labels, if False, will return transformed labels (as defined by
label_dict), default value: False
Returns
------... | python | {
"resource": ""
} |
q43131 | LabeledDataSet.return_labels_numpy | train | def return_labels_numpy(self, original=False):
"""
Returns a 2d numpy array of labels
Parameters
----------
original : if True, will return original labels, if False, will return transformed labels (as defined by
label_dict), default value: False
Returns
... | python | {
"resource": ""
} |
q43132 | LabeledDataSet.return_single_labels | train | def return_single_labels(self, object_id):
"""
Returns all labels for an object specified by the object_id
Parameters
----------
object_id : int, id of object in database
Returns
-------
result : list of labels
"""
engine = create_engine(... | python | {
"resource": ""
} |
q43133 | CacheManager.path_in_cache | train | def path_in_cache(self, filename, metahash):
"""Generates the path to a file in the mh cache.
The generated path does not imply the file's existence!
Args:
filename: Filename relative to buildroot
rule: A targets.SomeBuildRule object
metahash: hash object
... | python | {
"resource": ""
} |
q43134 | CacheManager._genpath | train | def _genpath(self, filename, mhash):
"""Generate the path to a file in the cache.
Does not check to see if the file exists. Just constructs the path
where it should be.
"""
mhash = mhash.hexdigest()
return os.path.join(self.mh_cachedir, mhash[0:2], mhash[2:4],
... | python | {
"resource": ""
} |
q43135 | CacheManager.putfile | train | def putfile(self, filepath, buildroot, metahash):
"""Put a file in the cache.
Args:
filepath: Path to file on disk.
buildroot: Path to buildroot
buildrule: The rule that generated this file.
metahash: hash object
"""
def gen_obj_path(filename):
... | python | {
"resource": ""
} |
q43136 | CacheManager.in_cache | train | def in_cache(self, objpath, metahash):
"""Returns true if object is cached.
Args:
objpath: Filename relative to buildroot.
metahash: hash object
"""
try:
self.path_in_cache(objpath, metahash)
return True
except CacheMiss:
r... | python | {
"resource": ""
} |
q43137 | CacheManager.get_obj | train | def get_obj(self, objpath, metahash, dst_path):
"""Get object from cache, write it to dst_path.
Args:
objpath: filename relative to buildroot
(example: mini-boot/blahblah/somefile.bin)
metahash: metahash. See targets/base.py
dst_path: Absolute path where... | python | {
"resource": ""
} |
q43138 | Herald._get_link | train | def _get_link(self, peer):
"""
Returns a link to the given peer
:return: A Link object
:raise ValueError: Unknown peer
"""
assert isinstance(peer, beans.Peer)
# Look for a link to the peer, using routers
for router in self._routers:
link = ro... | python | {
"resource": ""
} |
q43139 | Herald.send | train | def send(self, peer_id, message):
"""
Synchronously sends a message
:param peer_id: UUID of a peer
:param message: Message to send to the peer
:raise KeyError: Unknown peer
:raise ValueError: No link to the peer
"""
assert isinstance(message, beans.RawMes... | python | {
"resource": ""
} |
q43140 | change_default | train | def change_default(
kls,
key,
new_default,
new_converter=None,
new_reference_value=None,
):
"""return a new configman Option object that is a copy of an existing one,
giving the new one a different default value"""
an_option = kls.get_required_config()[key].copy()
an_option.default =... | python | {
"resource": ""
} |
q43141 | AntBuild.get_target | train | def get_target(self):
"""
Reads the android target based on project.properties file.
Returns
A string containing the project target (android-23 being the default if none is found)
"""
with open('%s/project.properties' % self.path) as f:
for line in f.readlines():
matches = re.fi... | python | {
"resource": ""
} |
q43142 | Server.lookup | train | def lookup(self, name, host_override=None):
"""
Looks up a name from the DNSChain server. Throws exception if the
data is not valid JSON or if the namecoin entry does not exist in the
blockchain.
@param name: The name to lookup, e.g. 'id/dionyziz', note this $NAMESPACE/$NAME
... | python | {
"resource": ""
} |
q43143 | cache_function | train | def cache_function(length):
"""
Caches a function, using the function itself as the key, and the return
value as the value saved. It passes all arguments on to the function, as
it should.
The decorator itself takes a length argument, which is the number of
seconds the cache will keep the result... | python | {
"resource": ""
} |
q43144 | PluginClientEntryHookABC.angularFrontendAppDir | train | def angularFrontendAppDir(self) -> str:
""" Angular Frontend Dir
This directory will be linked into the angular app when it is compiled.
:return: The absolute path of the Angular2 app directory.
"""
relDir = self._packageCfg.config.plugin.title(require_string)
dir = os.... | python | {
"resource": ""
} |
q43145 | HTTPURI.put_content | train | def put_content(self, content):
"""
Makes a ``PUT`` request with the content in the body.
:raise: An :exc:`requests.RequestException` if it is not 2xx.
"""
r = requests.request(self.method if self.method else 'PUT', self.url, data=content, **self.storage_args)
if self.r... | python | {
"resource": ""
} |
q43146 | HTTPURI.dir_exists | train | def dir_exists(self):
"""
Makes a ``HEAD`` requests to the URI.
:returns: ``True`` if status code is 2xx.
"""
r = requests.request(self.method if self.method else 'HEAD', self.url, **self.storage_args)
try: r.raise_for_status()
except Exception: return False
... | python | {
"resource": ""
} |
q43147 | SNSURI.put_content | train | def put_content(self, content):
"""
Publishes a message straight to SNS.
:param bytes content: raw bytes content to publish, will decode to ``UTF-8`` if string is detected
"""
if not isinstance(content, str):
content = content.decode('utf-8')
self.topic.publ... | python | {
"resource": ""
} |
q43148 | registerExitCall | train | def registerExitCall():
r"""Registers an exit call to start the core.
The core would be started after the main module is loaded. Ec would be exited from the core.
"""
if state.isExitHooked:
return
state.isExitHooked = True
from atexit import register
register(core.start) | python | {
"resource": ""
} |
q43149 | generate_veq | train | def generate_veq(R=1.3, dR=0.1, Prot=6, dProt=0.1,nsamples=1e4,plot=False,
R_samples=None,Prot_samples=None):
""" Returns the mean and std equatorial velocity given R,dR,Prot,dProt
Assumes all distributions are normal. This will be used mainly for
testing purposes; I can use MC-generated ... | python | {
"resource": ""
} |
q43150 | VirtualEnv.get_paths | train | def get_paths(self):
'''
get list of module paths
'''
# guess site package dir of virtualenv (system dependent)
venv_site_packages = '%s/lib/site-packages' % self.venv_dir
if not os.path.isdir(venv_site_packages):
venv_site_packages_glob = glob.glob('%s/lib/... | python | {
"resource": ""
} |
q43151 | VirtualEnv.create_virtualenv | train | def create_virtualenv(venv_dir, use_venv_module=True):
"""
creates a new virtualenv in venv_dir
By default, the built-in venv module is used.
On older versions of python, you may set use_venv_module to False to use virtualenv
"""
if not use_venv_module:
try:... | python | {
"resource": ""
} |
q43152 | data_dirpath | train | def data_dirpath(task=None, **kwargs):
"""Get the path of the corresponding data directory.
Parameters
----------
task : str, optional
The task for which datasets in the desired directory are used for. If
not given, a path for the corresponding task-agnostic directory is
returne... | python | {
"resource": ""
} |
q43153 | Resource.save | train | def save(self, *args, **kwargs):
"""
saves creates or updates current resource
returns new resource
"""
self._pre_save(*args, **kwargs)
response = self._save(*args, **kwargs)
response = self._post_save(response, *args, **kwargs)
return response | python | {
"resource": ""
} |
q43154 | Resource.load | train | def load(self, id, *args, **kwargs):
"""
loads a remote resource by id
"""
self._pre_load(id, *args, **kwargs)
response = self._load(id, *args, **kwargs)
response = self._post_load(response, *args, **kwargs)
return response | python | {
"resource": ""
} |
q43155 | Resource.delete | train | def delete(self, *args, **kwargs):
"""
deletes current resource
returns response from api
"""
self._pre_delete(*args, **kwargs)
response = self._delete(*args, **kwargs)
response = self._post_delete(response, *args, **kwargs)
return response | python | {
"resource": ""
} |
q43156 | BaseResource.to_json | train | def to_json(self):
"""
put the object to json and remove the internal stuff
salesking schema stores the type in the title
"""
data = json.dumps(self)
out = u'{"%s":%s}' % (self.schema['title'], data)
return out | python | {
"resource": ""
} |
q43157 | RemoteResource._do_api_call | train | def _do_api_call(self, call_type=u'', id = None):
"""
returns a response if it is a valid call
otherwise the corresponding error
"""
endpoint = None
url = None
# print "call_type %s" % (call_type)
if call_type == u'load':
endpoint = se... | python | {
"resource": ""
} |
q43158 | open_logfile | train | def open_logfile(filename, mode='a'):
"""Open the named log file in append mode.
If the file already exists, a separator will also be printed to
the file to separate past activity from current activity.
"""
filename = os.path.expanduser(filename)
filename = os.path.abspath(filename)
dirname... | python | {
"resource": ""
} |
q43159 | ServiceBase.create | train | def create(self, resource, data):
'''
A base function that performs a default create POST request for a given object
'''
service_def, resource_def, path = self._get_service_information(
resource)
self._validate(resource, data)
return self.call(path=path, dat... | python | {
"resource": ""
} |
q43160 | ServiceBase.update | train | def update(self, resource, resource_id, data):
'''
A base function that performs a default create PATCH request for a given object
'''
service_def, resource_def, path = self._get_service_information(
resource)
update_path = "{0}{1}/" . format(path, resource_id)
... | python | {
"resource": ""
} |
q43161 | ServiceBase.delete | train | def delete(self, resource, resource_id):
'''
A base function that performs a default delete DELETE request for a given object
'''
service_def, resource_def, path = self._get_service_information(
resource)
delete_path = "{0}{1}/" . format(path, resource_id)
re... | python | {
"resource": ""
} |
q43162 | ServiceBase._make_api | train | def _make_api(self, service_name):
'''
not yet in use ..
'''
resources = [resource for resource, resource_details in
service_definitions.get(service_name, {}).get("resources", {}).items()]
for resource in resources:
setattr(self, 'list_{0}' . fo... | python | {
"resource": ""
} |
q43163 | NetInfo.getSystemIps | train | def getSystemIps():
""" will not return the localhost one """
IPs = []
for interface in NetInfo.getSystemIfs():
if not interface.startswith('lo'):
ip = netinfo.get_ip(interface)
IPs.append(ip)
return IPs | python | {
"resource": ""
} |
q43164 | NetInfo.getIPString | train | def getIPString():
""" return comma delimited string of all the system IPs"""
if not(NetInfo.systemip):
NetInfo.systemip = ",".join(NetInfo.getSystemIps())
return NetInfo.systemip | python | {
"resource": ""
} |
q43165 | check_update | train | def check_update():
"""
Return True if an update is available on pypi
"""
r = requests.get("https://pypi.python.org/pypi/prof/json")
data = r.json()
if versiontuple(data['info']['version']) > versiontuple(__version__):
return True
return False | python | {
"resource": ""
} |
q43166 | to_ut1unix | train | def to_ut1unix(time: Union[str, datetime, float, np.ndarray]) -> np.ndarray:
"""
converts time inputs to UT1 seconds since Unix epoch
"""
# keep this order
time = totime(time)
if isinstance(time, (float, int)):
return time
if isinstance(time, (tuple, list, np.ndarray)):
ass... | python | {
"resource": ""
} |
q43167 | execute | train | def execute(tokens):
""" Perform the actions described by the input tokens. """
if not validate_rc():
print('Your .vacationrc file has errors!')
echo_vacation_rc()
return
for action, value in tokens:
if action == 'show':
show()
elif action == 'log':
... | python | {
"resource": ""
} |
q43168 | unique | train | def unique(transactions):
""" Remove any duplicate entries. """
seen = set()
# TODO: Handle comments
return [x for x in transactions if not (x in seen or seen.add(x))] | python | {
"resource": ""
} |
q43169 | sort | train | def sort(transactions):
""" Return a list of sorted transactions by date. """
return transactions.sort(key=lambda x: datetime.datetime.strptime(x.split(':')[0], '%Y-%m-%d'))[:] | python | {
"resource": ""
} |
q43170 | validate_rc | train | def validate_rc():
""" Before we execute any actions, let's validate our .vacationrc. """
transactions = rc.read()
if not transactions:
print('Your .vacationrc file is empty! Set days and rate.')
return False
transactions = sort(unique(transactions))
return validate_setup(transaction... | python | {
"resource": ""
} |
q43171 | validate_setup | train | def validate_setup(transactions):
""" First two transactions must set rate & days. """
if not transactions:
return True
try:
first, second = transactions[:2]
except ValueError:
print('Error: vacationrc file must have both initial days and rates entries')
return False
... | python | {
"resource": ""
} |
q43172 | stat_holidays | train | def stat_holidays(province='BC', year=2015):
""" Returns a list of holiday dates for a province and year. """
return holidays.Canada(state=province, years=year).keys() | python | {
"resource": ""
} |
q43173 | sum_transactions | train | def sum_transactions(transactions):
""" Sums transactions into a total of remaining vacation days. """
workdays_per_year = 250
previous_date = None
rate = 0
day_sum = 0
for transaction in transactions:
date, action, value = _parse_transaction_entry(transaction)
if previous_date i... | python | {
"resource": ""
} |
q43174 | get_days_off | train | def get_days_off(transactions):
""" Return the dates for any 'take day off' transactions. """
days_off = []
for trans in transactions:
date, action, _ = _parse_transaction_entry(trans)
if action == 'off':
days_off.append(date)
return days_off | python | {
"resource": ""
} |
q43175 | log_vacation_days | train | def log_vacation_days():
""" Sum and report taken days off. """
days_off = get_days_off(rc.read())
pretty_days = map(lambda day: day.strftime('%a %b %d %Y'), days_off)
for day in pretty_days:
print(day) | python | {
"resource": ""
} |
q43176 | echo_vacation_rc | train | def echo_vacation_rc():
""" Display all our .vacationrc file. """
contents = rc.read()
print('.vacationrc\n===========')
for line in contents:
print(line.rstrip()) | python | {
"resource": ""
} |
q43177 | to_email | train | def to_email(email_class, email, language=None, **data):
"""
Send email to specified email address
"""
if language:
email_class().send([email], language=language, **data)
else:
email_class().send([email], translation.get_language(), **data) | python | {
"resource": ""
} |
q43178 | to_staff | train | def to_staff(email_class, **data):
"""
Email staff users
"""
for user in get_user_model().objects.filter(is_staff=True):
try:
email_class().send([user.email], user.language, **data)
except AttributeError:
email_class().send([user.email], translation.get_language()... | python | {
"resource": ""
} |
q43179 | listify | train | def listify(args):
"""Return args as a list.
If already a list - return as is.
>>> listify([1, 2, 3])
[1, 2, 3]
If a set - return as a list.
>>> listify(set([1, 2, 3]))
[1, 2, 3]
If a tuple - return as a list.
>>> listify(tuple([1, 2, 3]))
[1, 2, 3]
If a generator (als... | python | {
"resource": ""
} |
q43180 | create_censor_file | train | def create_censor_file(input_dset,out_prefix=None,fraction=0.1,clip_to=0.1,max_exclude=0.3,motion_file=None,motion_exclude=1.0):
'''create a binary censor file using 3dToutcount
:input_dset: the input dataset
:prefix: output 1D file (default: ``prefix(input_dset)`` + ``.1D``)
:fractio... | python | {
"resource": ""
} |
q43181 | calc | train | def calc(dsets,expr,prefix=None,datum=None):
''' returns a string of an inline ``3dcalc``-style expression
``dsets`` can be a single string, or list of strings. Each string in ``dsets`` will
be labeled 'a','b','c', sequentially. The expression ``expr`` is used directly
If ``prefix`` is not given, will... | python | {
"resource": ""
} |
q43182 | cluster | train | def cluster(dset,min_distance,min_cluster_size,prefix=None):
'''clusters given ``dset`` connecting voxels ``min_distance``mm away with minimum cluster size of ``min_cluster_size``
default prefix is ``dset`` suffixed with ``_clust%d``'''
if prefix==None:
prefix = nl.suffix(dset,'_clust%d' % min_clust... | python | {
"resource": ""
} |
q43183 | blur | train | def blur(dset,fwhm,prefix=None):
'''blurs ``dset`` with given ``fwhm`` runs 3dmerge to blur dataset to given ``fwhm``
default ``prefix`` is to suffix ``dset`` with ``_blur%.1fmm``'''
if prefix==None:
prefix = nl.suffix(dset,'_blur%.1fmm'%fwhm)
return available_method('blur')(dset,fwhm,prefix) | python | {
"resource": ""
} |
q43184 | skull_strip | train | def skull_strip(dset,suffix='_ns',prefix=None,unifize=True):
'''attempts to cleanly remove skull from ``dset``'''
return available_method('skull_strip')(dset,suffix,prefix,unifize) | python | {
"resource": ""
} |
q43185 | collect_manifest_dependencies | train | def collect_manifest_dependencies(manifest_data, lockfile_data):
"""Convert the manifest format to the dependencies schema"""
output = {}
for dependencyName, dependencyConstraint in manifest_data.items():
output[dependencyName] = {
# identifies where this dependency is installed from
... | python | {
"resource": ""
} |
q43186 | collect_lockfile_dependencies | train | def collect_lockfile_dependencies(lockfile_data):
"""Convert the lockfile format to the dependencies schema"""
output = {}
for dependencyName, installedVersion in lockfile_data.items():
output[dependencyName] = {
'source': 'example-package-manager',
'installed': {'name': ins... | python | {
"resource": ""
} |
q43187 | match_similar | train | def match_similar(base, items):
"""Get the most similar matching item from a list of items.
@param base: base item to locate best match
@param items: list of items for comparison
@return: most similar matching item or None
"""
finds = list(find_similar(base, items))
if finds:
retur... | python | {
"resource": ""
} |
q43188 | duplicates | train | def duplicates(base, items):
"""Get an iterator of items similar but not equal to the base.
@param base: base item to perform comparison against
@param items: list of items to compare to the base
@return: generator of items sorted by similarity to the base
"""
for item in items:
if ite... | python | {
"resource": ""
} |
q43189 | sort | train | def sort(base, items):
"""Get a sorted list of items ranked in descending similarity.
@param base: base item to perform comparison against
@param items: list of items to compare to the base
@return: list of items sorted by similarity to the base
"""
return sorted(items, key=base.similarity, re... | python | {
"resource": ""
} |
q43190 | terms_from_dict | train | def terms_from_dict(source):
""" Convert a dict representing a query to a string.
Args:
source -- A dict with query xpaths as keys and text or nested query dicts as values.
Returns:
A string composed from the nested query terms given.
>>> terms_from_dict({'document': {... | python | {
"resource": ""
} |
q43191 | json_schema_validation_format | train | def json_schema_validation_format(value, schema_validation_type):
"""
adds iso8601 to the datetimevalidator
raises SchemaError if validation fails
"""
DEFAULT_FORMAT_VALIDATORS['date-time'] = validate_format_iso8601
DEFAULT_FORMAT_VALIDATORS['text'] = validate_format_text
validictory.validat... | python | {
"resource": ""
} |
q43192 | Tasks.register | train | def register(self, func):
"""
Register a task. Typically used as a decorator to the task function.
If a task by that name already exists,
a TaskAlreadyRegistered exception is raised.
:param func: func to register as an ape task
:return: invalid accessor
"""
... | python | {
"resource": ""
} |
q43193 | purge_old_logs | train | def purge_old_logs(delete_before_days=7):
"""
Purges old logs from the database table
"""
delete_before_date = timezone.now() - timedelta(days=delete_before_days)
logs_deleted = Log.objects.filter(
created_on__lte=delete_before_date).delete()
return logs_deleted | python | {
"resource": ""
} |
q43194 | purge_old_event_logs | train | def purge_old_event_logs(delete_before_days=7):
"""
Purges old event logs from the database table
"""
delete_before_date = timezone.now() - timedelta(days=delete_before_days)
logs_deleted = EventLog.objects.filter(
created_on__lte=delete_before_date).delete()
return logs_deleted | python | {
"resource": ""
} |
q43195 | purge_old_request_logs | train | def purge_old_request_logs(delete_before_days=7):
"""
Purges old request logs from the database table
"""
delete_before_date = timezone.now() - timedelta(days=delete_before_days)
logs_deleted = RequestLog.objects.filter(
created_on__lte=delete_before_date).delete()
return logs_deleted | python | {
"resource": ""
} |
q43196 | sigmafilter | train | def sigmafilter(data, sigmas, passes):
"""Remove datapoints outside of a specified standard deviation range."""
for n in range(passes):
meandata = np.mean(data[~np.isnan(data)])
sigma = np.std(data[~np.isnan(data)])
data[data > meandata+sigmas*sigma] = np.nan
data[data < me... | python | {
"resource": ""
} |
q43197 | runningstd | train | def runningstd(t, data, width):
"""Compute the running standard deviation of a time series.
Returns `t_new`, `std_r`.
"""
ne = len(t) - width
t_new = np.zeros(ne)
std_r = np.zeros(ne)
for i in range(ne):
t_new[i] = np.mean(t[i:i+width+1])
std_r[i] = scipy.stats.nan... | python | {
"resource": ""
} |
q43198 | smooth | train | def smooth(data, fw):
"""Smooth data with a moving average."""
if fw == 0:
fdata = data
else:
fdata = lfilter(np.ones(fw)/fw, 1, data)
return fdata | python | {
"resource": ""
} |
q43199 | calcstats | train | def calcstats(data, t1, t2, sr):
"""Calculate the mean and standard deviation of some array between
t1 and t2 provided the sample rate sr.
"""
dataseg = data[sr*t1:sr*t2]
meandata = np.mean(dataseg[~np.isnan(dataseg)])
stddata = np.std(dataseg[~np.isnan(dataseg)])
return meandata, std... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.