code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if not voevent.xpath('Citations'):
etree.SubElement(voevent, 'Citations')
voevent.Citations.extend(_listify(event_ivorns)) | def add_citations(voevent, event_ivorns) | Add citations to other voevents.
The schema mandates that the 'Citations' section must either be entirely
absent, or non-empty - hence we require this wrapper function for its
creation prior to listing the first citation.
Args:
voevent(:class:`Voevent`): Root node of a VOEvent etree.
e... | 4.738738 | 4.125014 | 1.148781 |
if v.prefix:
# Create subelement without a prefix via etree.SubElement
etree.SubElement(v, 'original_prefix')
# Now carefully access said named subelement (without prefix cascade)
# and alter the first value in the list of children with this name...
# LXML syntax is a mi... | def _remove_root_tag_prefix(v) | Removes 'voe' namespace prefix from root tag.
When we load in a VOEvent, the root element has a tag prefixed by
the VOE namespace, e.g. {http://www.ivoa.net/xml/VOEvent/v2.0}VOEvent
Because objectify expects child elements to have the same namespace as
their parent, this breaks the python-attribute st... | 17.22584 | 13.002054 | 1.324855 |
if hasattr(v, 'original_prefix'):
original_prefix = v.original_prefix
del v.original_prefix
v.tag = ''.join(('{', v.nsmap[original_prefix], '}VOEvent'))
return | def _reinsert_root_tag_prefix(v) | Returns namespace prefix to root tag, if it had one. | 5.673976 | 5.297168 | 1.071134 |
if isinstance(x, string_types):
return [x]
elif isinstance(x, collections.Iterable):
return x
else:
return [x] | def _listify(x) | Ensure x is iterable; if not then enclose it in a list and return it. | 2.239873 | 1.995015 | 1.122735 |
params = {'per_page': per_page, 'page': page}
if label:
params['label'] = label
return self.request.get('', params) | def list(self, label=None, per_page=20, page=1) | Get a list of identities that have been created
:param per_page: The number of results per page returned
:type per_page: int
:param page: The page number of the results
:type page: int
:return: dict of REST API output with headers attached
:rtype:... | 3.169426 | 4.07361 | 0.778039 |
params = {'label': label}
if status:
params['status'] = status
if master:
params['master'] = master
return self.request.post('', params) | def create(self, label, status=None, master=None) | Create an Identity
:param label: The label to give this new identity
:param status: The status of this identity. Default: 'active'
:param master: Represents whether this identity is a master.
Default: False
:return: dict of REST API output with headers at... | 3.181505 | 3.467303 | 0.917574 |
params = {}
if label:
params['label'] = label
if status:
params['status'] = status
if master:
params['master'] = master
return self.request.put(str(id), params) | def update(self, id, label=None, status=None, master=None) | Update an Identity
:param label: The label to give this new identity
:param status: The status of this identity. Default: 'active'
:param master: Represents whether this identity is a master.
Default: False
:return: dict of REST API output with headers at... | 2.453972 | 2.909856 | 0.843331 |
return self.request.get(service + '/task/' + type + '/' + id) | def get(self, id, service='facebook', type='analysis') | Get a given Pylon task
:param id: The ID of the task
:type id: str
:param service: The PYLON service (facebook)
:type service: str
:return: dict of REST API output with headers attached
:rtype: :class:`~datasift.request.DictResponse`
:... | 7.563709 | 9.56905 | 0.790435 |
params = {}
if per_page is not None:
params['per_page'] = per_page
if page is not None:
params['page'] = page
if status:
params['status'] = status
return self.request.get(service + '/task', params) | def list(self, per_page=None, page=None, status=None, service='facebook') | Get a list of Pylon tasks
:param per_page: How many tasks to display per page
:type per_page: int
:param page: Which page of tasks to display
:type page: int
:param status: The status of the tasks to list
:type page: string
:param serv... | 2.500004 | 2.360043 | 1.059305 |
params = {
'subscription_id': subscription_id,
'name': name,
'parameters': parameters,
'type': type
}
return self.request.post(service + '/task/', params) | def create(self, subscription_id, name, parameters, type='analysis', service='facebook') | Create a PYLON task
:param subscription_id: The ID of the recording to create the task for
:type subscription_id: str
:param name: The name of the new task
:type name: str
:param parameters: The parameters for this task
:type parameters: dict
... | 3.137076 | 3.206689 | 0.978291 |
upload = super(StickyUploadWidget, self).value_from_datadict(data, files, name)
if upload is not None:
# File was posted or cleared as normal
return upload
else:
# Try the hidden input
hidden_name = self.get_hidden_name(name)
v... | def value_from_datadict(self, data, files, name) | Returns uploaded file from serialized value. | 4.66075 | 4.313551 | 1.08049 |
location = getattr(value, '_seralized_location', '')
if location and not hasattr(value, 'url'):
value.url = '#'
if hasattr(self, 'get_template_substitution_values'):
# Django 1.8-1.10
self.template_with_initial = (
'%(i... | def render(self, name, value, attrs=None, renderer=None) | Include a hidden input to store the serialized upload value. | 4.713191 | 4.235304 | 1.112834 |
if nested:
config = nested_config(config)
# Re-read settings to make sure we have everything.
# XXX It would be really nice if we didn't need to do this.
Settings.init(**config)
if datastore:
Switch.ds = datastore
# Register the builtins
__import__('switchboard.builtin... | def configure(config={}, datastore=None, nested=False) | Useful for when you need to control Switchboard's setup | 10.200836 | 9.774219 | 1.043647 |
def inner(self, *args, **kwargs):
dic = self.result_cache
cache_key = None
if dic is not None:
cache_key = (args, tuple(kwargs.items()))
try:
result = dic.get(cache_key)
except TypeError as e: # not... | def with_result_cache(func) | Decorator specifically for is_active. If self.result_cache is set to a {}
the is_active results will be cached for each set of params. | 3.46353 | 3.31568 | 1.044591 |
try:
default = kwargs.pop('default', False)
# Check all parents for a disabled state
parts = key.split(':')
if len(parts) > 1:
child_kwargs = kwargs.copy()
child_kwargs['default'] = None
result = self.is_ac... | def is_active(self, key, *instances, **kwargs) | Returns ``True`` if any of ``instances`` match an active switch.
Otherwise returns ``False``.
>>> operator.is_active('my_feature', request) #doctest: +SKIP | 3.971695 | 4.140913 | 0.959135 |
if callable(condition_set):
condition_set = condition_set()
registry[condition_set.get_id()] = condition_set
registry_by_namespace[condition_set.get_namespace()] = condition_set | def register(self, condition_set) | Registers a condition set with the manager.
>>> condition_set = MyConditionSet() #doctest: +SKIP
>>> operator.register(condition_set) #doctest: +SKIP | 3.547235 | 4.154766 | 0.853775 |
if callable(condition_set):
condition_set = condition_set()
registry.pop(condition_set.get_id(), None)
registry_by_namespace.pop(condition_set.get_namespace(), None) | def unregister(self, condition_set) | Unregisters a condition set with the manager.
>>> operator.unregister(condition_set) #doctest: +SKIP | 3.682196 | 4.339489 | 0.848532 |
path, query = _parse_url(url)
dupestats = []
extend_ds = lambda x: dupestats.extend(filter(None, (
ds_dict.get(key) for ds_dict, key in x)))
if self.urls_by_path.get(path):
extend_ds([(self.path_dupstats, path)])
# If param is in the query
... | def get_dupe_prob(self, url) | A probability of given url being a duplicate of some content
that has already been seem. | 4.135138 | 4.07671 | 1.014332 |
min_hash = get_min_hash(text, self.too_common_shingles, self.num_perm)
item_url = canonicalize_url(url)
item_path, item_query = _parse_url(item_url)
all_duplicates = [
(url, self.seen_urls[url]) for url in self.lsh.query(min_hash)]
duplicates = [(url, m.query... | def update_model(self, url, text) | Update prediction model with a page by given url and text content.
Return a list of item duplicates (for testing purposes). | 3.333982 | 3.334448 | 0.99986 |
if not all_urls:
return 0
urls = random.sample(all_urls, max_sample) \
if len(all_urls) > max_sample else all_urls
filtered = [
url for url in urls
if min_hash.jaccard(self.seen_urls[url].min_hash) <
self.jaccard_threshold]
... | def _nodup_filter(self, min_hash, all_urls, max_sample=200) | This filters results that are considered not duplicates.
But we really need to check that, because lsh.query does not always
return ALL duplicates, esp. when there are a lot of them, so
here we double-check and return only urls that are NOT duplicates.
Return estimated number of not dupl... | 3.414311 | 3.18633 | 1.07155 |
qs = super(UnrenderedAdmin, self).get_queryset(request)
if 'show_rendered' in qs.query.context:
del qs.query.context['show_rendered']
return qs | def get_queryset(self, request) | Remove ``show_rendered`` from the context, if it's there. | 4.771558 | 2.642584 | 1.805641 |
case = cls() if cls else self._CasesClass()
for attr, value in kwargs.iteritems():
setattr(case, attr, value)
return case | def get_one(self, cls=None, **kwargs) | Returns a one case. | 6.183108 | 4.278538 | 1.445145 |
defaults = {attr: kwargs[attr][0] for attr in kwargs}
for set_of_values in izip_longest(*kwargs.values()):
case = cls() if cls else self._CasesClass()
for attr, value in izip(kwargs.keys(), set_of_values):
if value is None:
value = def... | def get_each_choice(self, cls=None, **kwargs) | Returns a generator that generates positive cases by
"each choice" algorithm. | 3.932315 | 3.684935 | 1.067133 |
for set_of_values in allpairs(kwargs.values()):
case = cls() if cls else self._CasesClass()
for attr, value in izip(kwargs.keys(), set_of_values):
setattr(case, attr, value)
yield case | def get_pairwise(self, cls=None, **kwargs) | Returns a generator that generates positive cases by
"pairwise" algorithm. | 6.03871 | 5.895896 | 1.024223 |
for attr, set_of_values in kwargs.iteritems():
defaults = {key: kwargs[key][-1]["default"] for key in kwargs}
defaults.pop(attr)
for value in set_of_values[:-1]:
case = cls() if cls else self._CasesClass()
setattr(case, attr, value)
... | def get_negative(self, cls=None, **kwargs) | Returns a generator that generates negative cases by
"each negative value in separate case" algorithm. | 4.936616 | 4.249523 | 1.161687 |
def mix(length):
result = "".join(random.choice(sample) for _ in xrange(length)).strip()
if len(result) == length:
return result
return mix(length)
return mix | def get_mix_gen(self, sample) | Returns function that returns sequence of characters of a
given length from a given sample | 4.788978 | 4.02858 | 1.188751 |
db = DbManager(connection)
db.db_import(urls=urls, force_download=force_download)
db.session.close() | def update(connection=None, urls=None, force_download=False) | Updates CTD database
:param iter[str] urls: list of urls to download
:param str connection: custom database connection string
:param bool force_download: force method to download | 5.229124 | 8.043161 | 0.650133 |
set_connection('mysql+pymysql://{user}:{passwd}@{host}/{db}?charset={charset}'.format(
host=host,
user=user,
passwd=password,
db=db,
charset=charset)
) | def set_mysql_connection(host='localhost', user='pyctd_user', password='pyctd_passwd', db='pyctd', charset='utf8') | Sets the connection using MySQL Parameters | 2.041113 | 2.171875 | 0.939793 |
cfp = defaults.config_file_path
config = RawConfigParser()
if not os.path.exists(cfp):
with open(cfp, 'w') as config_file:
config['database'] = {'sqlalchemy_connection_string': connection}
config.write(config_file)
log.info('create configuration file %s', cf... | def set_connection(connection=defaults.sqlalchemy_connection_string_default) | Set the connection string for SQLAlchemy
:param str connection: SQLAlchemy connection string | 2.278 | 2.413875 | 0.943711 |
user_connection = input(
bcolors.WARNING + "\nFor any reason connection to " + bcolors.ENDC +
bcolors.FAIL + "{}".format(self.connection) + bcolors.ENDC +
bcolors.WARNING + " is not possible.\n\n" + bcolors.ENDC +
"For more information about SQLAlchemy co... | def set_connection_string_by_user_input(self) | Prompts the user to input a connection string | 2.699819 | 2.696886 | 1.001088 |
log.info('creating tables in %s', self.engine.url)
models.Base.metadata.create_all(self.engine, checkfirst=checkfirst) | def create_all(self, checkfirst=True) | Creates all tables from models in the database
:param bool checkfirst: Check if tables already exists | 3.112654 | 3.596102 | 0.865563 |
log.info('dropping tables in %s', self.engine.url)
self.session.commit()
models.Base.metadata.drop_all(self.engine)
self.session.commit() | def drop_all(self) | Drops all tables in the database | 3.632149 | 3.283321 | 1.106243 |
if not urls:
urls = [
defaults.url_base + table_conf.tables[model]['file_name']
for model in table_conf.tables
]
log.info('Update CTD database from %s', urls)
self.drop_all()
self.download_urls(urls=urls, force_download=f... | def db_import(self, urls=None, force_download=False) | Updates the CTD database
1. downloads all files from CTD
2. drops all tables in database
3. creates all tables in database
4. import all data from CTD files
:param iter[str] urls: An iterable of URL strings
:param bool force_download: force method to dow... | 5.839483 | 5.34196 | 1.093135 |
if not self.__mapper:
for model in table_conf.models_to_map:
domain = model.table_suffix
tab_conf = table_conf.tables[model]
file_path = os.path.join(self.pyctd_data_dir, tab_conf['file_name'])
col_name_in_file, col_name_in_d... | def mapper(self) | returns a dictionary with keys of pyctd.manager.table_con.domains_to_map and pandas.DataFrame as values.
DataFrames column names:
- domain_id (represents the domain identifier of e.g. chemical)
- domain__id (represents the primary key in domain table)
:return: dict of pandas ... | 4.062981 | 3.134721 | 1.296122 |
for table in self.tables:
if only_tables is not None and table.name not in only_tables:
continue
if exclude_tables is not None and table.name in exclude_tables:
continue
self.import_table(table) | def import_tables(self, only_tables=None, exclude_tables=None) | Imports all data in database tables
:param set[str] only_tables: names of tables to be imported
:param set[str] exclude_tables: names of tables to be excluded | 1.951893 | 2.259819 | 0.863739 |
columns = cls.get_column_names_from_file(file_path)
if column in columns:
return columns.index(column) | def get_index_of_column(cls, column, file_path) | Get index of a specific column name in a CTD file
:param column:
:param file_path:
:return: Optional[int] | 2.654694 | 2.856421 | 0.929378 |
use_columns_with_index = []
column_names_in_db = []
column_names_from_file = cls.get_column_names_from_file(file_path)
if not set(columns_in_file_expected).issubset(column_names_from_file):
log.exception(
'%s columns are not a subset of columns %s in... | def get_index_and_columns_order(cls, columns_in_file_expected, columns_dict, file_path) | :param columns_in_file_expected:
:param columns_dict:
:param file_path:
:rtype: tuple[list,list] | 2.07664 | 2.033457 | 1.021236 |
file_path = os.path.join(self.pyctd_data_dir, table.file_name)
log.info('importing %s data into table %s', file_path, table.name)
table_import_timer = time.time()
use_columns_with_index, column_names_in_db = self.get_index_and_columns_order(
table.columns_in_file_ex... | def import_table(self, table) | import table by Table object
:param `manager.table_conf.Table` table: Table object | 3.462949 | 3.676656 | 0.941875 |
chunks = pd.read_table(
file_path,
usecols=[column_index],
header=None,
comment='#',
index_col=False,
chunksize=1000000,
dtype=self.get_dtypes(parent_table.model)
)
for chunk in chunks:
chil... | def import_one_to_many(self, file_path, column_index, parent_table, column_in_one2many_table) | :param file_path:
:param column_index:
:param parent_table:
:param column_in_one2many_table: | 2.390141 | 2.397465 | 0.996945 |
chunks = pd.read_table(
file_path,
usecols=use_columns_with_index,
names=column_names_in_db,
header=None, comment='#',
index_col=False,
chunksize=1000000,
dtype=self.get_dtypes(table.model)
)
for chunk ... | def import_table_in_db(self, file_path, use_columns_with_index, column_names_in_db, table) | Imports data from CTD file into database
:param str file_path: path to file
:param list[int] use_columns_with_index: list of column indices in file
:param list[str] column_names_in_db: list of column names (have to fit to models except domain_id column name)
:param table: `manag... | 4.036917 | 3.949357 | 1.022171 |
if file_path.endswith('.gz'):
file_handler = io.TextIOWrapper(io.BufferedReader(gzip.open(file_path)))
else:
file_handler = open(file_path, 'r')
fields_line = False
with file_handler as file:
for line in file:
line = line.stri... | def get_column_names_from_file(file_path) | returns column names from CTD download file
:param str file_path: path to CTD download file | 2.842854 | 2.911452 | 0.976438 |
for url in urls:
file_path = cls.get_path_to_file_from_url(url)
if os.path.exists(file_path) and not force_download:
log.info('already downloaded %s to %s', url, file_path)
else:
log.info('downloading %s to %s', url, file_path)
... | def download_urls(cls, urls, force_download=False) | Downloads all CTD URLs that don't exist
:param iter[str] urls: iterable of URL of CTD
:param bool force_download: force method to download | 2.057765 | 2.29832 | 0.895335 |
def fmt(field):
return "'%s'" % field
if not fields:
return "nothing"
elif len(fields) == 1:
return fmt(fields[0])
elif len(fields) == 2:
return " and ".join([fmt(f) for f in fields])
else:
result = ", ".join([fmt(f) for f in fields[:-1]])
if ox... | def comma_join(fields, oxford=True) | Join together words. | 2.170524 | 2.144329 | 1.012216 |
if dns:
# This makes an extra DNS SRV query, which can slow down our webapps.
# It is necessary for libravatar federation, though.
import libravatar
return libravatar.libravatar_url(
openid=openid,
size=size,
default=default,
)
el... | def avatar_url_from_openid(openid, size=64, default='retro', dns=False) | Our own implementation since fas doesn't support this nicely yet. | 4.765344 | 4.719615 | 1.009689 |
if dns:
# This makes an extra DNS SRV query, which can slow down our webapps.
# It is necessary for libravatar federation, though.
import libravatar
return libravatar.libravatar_url(
email=email,
size=size,
default=default,
)
else... | def avatar_url_from_email(email, size=64, default='retro', dns=False) | Our own implementation since fas doesn't support this nicely yet. | 4.870129 | 4.804164 | 1.013731 |
run_event = threading.Event()
run_event.set()
thread = threading.Thread(target=target, args=args + (run_event, ))
self.thread_pool.append(thread)
self.run_events.append(run_event)
thread.start() | def run(self, target, args=()) | Run a function in a separate thread.
:param target: the function to run.
:param args: the parameters to pass to the function. | 2.658829 | 2.913555 | 0.912572 |
for run_event in self.run_events:
run_event.clear()
for thread in self.thread_pool:
thread.join() | def stop(self) | Stop all functions running in the thread handler. | 4.739769 | 3.976684 | 1.19189 |
atom_labels = [label[0] for label in labels]
noise = []
distribution_function = distributions[self.distribution_name]["function"]
for label in atom_labels:
params = [self.parameters["{}_{}".format(label, param)][split_idx]
for param in self.dis... | def generate(self, labels, split_idx) | Generate peak-specific noise abstract method, must be reimplemented in a subclass.
:param tuple labels: Dimension labels of a peak.
:param int split_idx: Index specifying which peak list split parameters to use.
:return: List of noise values for dimensions ordered as they appear in a peak.
... | 4.387497 | 3.868204 | 1.134247 |
if not self.args:
return False
filename = self.args.get('--cover', None) \
or self.config.get('cover', None) \
or None
if not filename:
for extension in ('png', 'jpg', 'jpeg', 'svg'):
temp_filename = 'cover.%s' % extension
... | def load_cover(self) | Load the cover out of the config, options and conventions.
Priority goes this way:
1. if a --cover option is set, use it.
2. if there's a "cover" key in the config file, use it.
3. if a cover.(png|jpg|jpeg|svg) exists in the directory, use it.
Once the choice is set, the progra... | 3.636596 | 2.990599 | 1.216009 |
prefix = 'Programming Language :: Python ::'
python_classifiers = [c.split('::')[2].strip() for c in classifiers if c.startswith(prefix)]
return ', '.join([c for c in python_classifiers if parse_version(c)]) | def parse_python(classifiers) | Parse out the versions of python supported a/c classifiers. | 3.847336 | 3.486259 | 1.103572 |
prefix = 'Framework :: Django ::'
django_classifiers = [c.split('::')[2].strip() for c in classifiers if c.startswith(prefix)]
return ', '.join([c for c in django_classifiers if parse_version(c)]) | def parse_django(classifiers) | Parse out the versions of django supported a/c classifiers. | 4.391867 | 3.872064 | 1.134244 |
if version1 is None or version2 is None:
return 'unknown'
if version1 == version2:
return 'none'
for v in ('major', 'minor', 'patch'):
if getattr(version1, v) != getattr(version2, v):
return v
return 'other' | def version_diff(version1, version2) | Return string representing the diff between package versions.
We're interested in whether this is a major, minor, patch or 'other'
update. This method will compare the two versions and return None if
they are the same, else it will return a string value indicating the
type of diff - 'major', 'minor', '... | 2.396462 | 2.404736 | 0.996559 |
key = cache_key(self.name)
data = cache.get(key)
if data is None:
logger.debug("Updating package info for %s from PyPI.", self.name)
data = requests.get(self.url).json()
cache.set(key, data, PYPI_CACHE_EXPIRY)
return data | def data(self) | Fetch latest data from PyPI, and cache for 30s. | 3.635607 | 2.722122 | 1.335578 |
with _query_lock:
global _last_query_time
since_last_query = time.time() - _last_query_time
if since_last_query < QUERY_WAIT_TIME:
time.sleep(QUERY_WAIT_TIME - since_last_query)
_last_query_time = time.time()
return fun(*args, **kwargs) | def _query_wrap(fun, *args, **kwargs) | Wait until at least QUERY_WAIT_TIME seconds have passed
since the last invocation of this function, then call the given
function with the given arguments. | 1.989979 | 1.710786 | 1.163196 |
BOUNDARY = '----form-data-boundary-ZmRkNzJkMjUtMjkyMC00'
out = []
for (key, value) in fields.items():
out.append('--' + BOUNDARY)
out.append('Content-Disposition: form-data; name="%s"' % key)
out.append('')
out.append(value)
out.append('--' + BOUNDARY + '--')
out... | def formdata_encode(fields) | Encode fields (a dict) as a multipart/form-data HTTP request
payload. Returns a (content type, request body) pair. | 2.58999 | 2.572704 | 1.006719 |
content_type, data = formdata_encode(fields)
req = urllib2.Request(url, data)
req.add_header('Content-Type', content_type)
return urllib2.urlopen(req).read() | def formdata_post(url, fields) | Send an HTTP request with a multipart/form-data body for the
given URL and return the data returned by the server. | 2.163329 | 2.315981 | 0.934088 |
metadata = metadata or {}
params = {
'artist': metadata.get('artist', ''),
'album': metadata.get('album', ''),
'track': metadata.get('title', ''),
'duration': duration,
}
url = '%s?%s' % (URL_FPID, urllib.urlencode(params))
try:
res = _query_wrap(formdata... | def fpid_query(duration, fpdata, metadata=None) | Send fingerprint data to Last.fm to get the corresponding
fingerprint ID, which can then be used to fetch metadata.
duration is the length of the track in (integral) seconds.
If metadata is provided, it is a dictionary with three optional
fields reflecting the current metadata for the file: "artist",
... | 3.334703 | 3.297011 | 1.011432 |
params = {
'method': 'track.getFingerprintMetadata',
'fingerprintid': fpid,
'api_key': apikey,
}
url = '%s?%s' % (URL_METADATA, urllib.urlencode(params))
try:
fh = _query_wrap(urllib.urlopen, url)
except urllib2.HTTPError:
raise CommunicationError('metada... | def metadata_query(fpid, apikey) | Queries the Last.fm servers for metadata about a given
fingerprint ID (an integer). Returns the XML response (a string). | 3.708428 | 3.524256 | 1.052258 |
extractor = _fplib.Extractor(samplerate, channels, duration)
# Get first block.
try:
next_block = next(pcmiter)
except StopIteration:
raise ExtractionError()
# Get and process subsequent blocks.
while True:
# Shift over blocks.
cur_block = next_block
... | def extract(pcmiter, samplerate, channels, duration = -1) | Given a PCM data stream, extract fingerprint data from the
audio. Returns a byte string of fingerprint data. Raises an
ExtractionError if fingerprinting fails. | 4.482857 | 4.134569 | 1.084238 |
fpdata = extract(pcmiter, samplerate, channels)
fpid = fpid_query(duration, fpdata, metadata)
return metadata_query(fpid, apikey) | def match(apikey, pcmiter, samplerate, duration, channels=2, metadata=None) | Given a PCM data stream, perform fingerprinting and look up the
metadata for the audio. pcmiter must be an iterable of blocks of
PCM data (buffers). duration is the total length of the track in
seconds (an integer). metadata may be a dictionary containing
existing metadata for the file (optional keys: "... | 10.865656 | 8.185008 | 1.327507 |
try:
root = etree.fromstring(xml)
except (ExpatError, etree.ParseError):
# The Last.fm API occasionally generates malformed XML when its
# includes an illegal character (UTF8-legal but prohibited by
# the XML standard).
raise CommunicationError('malformed XML respons... | def parse_metadata(xml) | Given an XML document (string) returned from metadata_query(),
parse the response into a list of track info dicts. May raise an
APIError if the lookup fails. | 3.464458 | 3.305048 | 1.048232 |
import audioread
with audioread.audio_open(path) as f:
return match(apikey, iter(f), f.samplerate, int(f.duration),
f.channels, metadata) | def match_file(apikey, path, metadata=None) | Uses the audioread library to decode an audio file and match it. | 4.839005 | 3.761487 | 1.286461 |
nmrstar_constants = {}
resonance_classes = {}
spectrum_descriptions = {}
this_directory = os.path.dirname(__file__)
nmrstar2_config_filepath = os.path.join(this_directory, "conf/constants_nmrstar2.json")
nmrstar3_config_filepath = os.path.join(this_directory, "conf/constants_nmrstar3.json... | def update_constants(nmrstar2cfg="", nmrstar3cfg="", resonance_classes_cfg="", spectrum_descriptions_cfg="") | Update constant variables.
:return: None
:rtype: :py:obj:`None` | 1.369987 | 1.3792 | 0.99332 |
if args:
for spectrum_name in args:
pprint.pprint({spectrum_name: SPECTRUM_DESCRIPTIONS.get(spectrum_name, None)}, width=120)
else:
pprint.pprint(SPECTRUM_DESCRIPTIONS, width=120) | def list_spectrum_descriptions(*args) | List all available spectrum descriptions that can be used for peak list simulation.
:param str args: Spectrum name(s), e.g. list_spectrum_descriptions("HNCO", "HNcoCACB"), leave empty to list everything.
:return: None
:rtype: :py:obj:`None` | 2.665654 | 2.504344 | 1.064412 |
input_str = filehandle.read()
nmrstar_str = StarFile._is_nmrstar(input_str)
cif_str = StarFile._is_cif(input_str)
json_str = StarFile._is_json(input_str)
if not input_str:
pass
elif nmrstar_str:
starfile = NMRStarFile(source)
... | def read(filehandle, source) | Read data into a :class:`~nmrstarlib.nmrstarlib.StarFile` instance.
:param filehandle: file-like object.
:type filehandle: :py:class:`io.TextIOWrapper`, :py:class:`gzip.GzipFile`,
:py:class:`bz2.BZ2File`, :py:class:`zipfile.ZipFile`
:param str source: String indicating... | 2.271329 | 2.160878 | 1.051114 |
try:
if file_format == "json":
json_str = self._to_json()
filehandle.write(json_str)
elif file_format == "nmrstar" and isinstance(self, NMRStarFile):
nmrstar_str = self._to_star()
filehandle.write(nmrstar_str)
... | def write(self, filehandle, file_format) | Write :class:`~nmrstarlib.nmrstarlib.StarFile` data into file.
:param filehandle: file-like object.
:type filehandle: :py:class:`io.TextIOWrapper`
:param str file_format: Format to use to write data: `nmrstar`, `cif`, or `json`.
:return: None
:rtype: :py:obj:`None` | 2.461663 | 2.138972 | 1.150863 |
star_str = io.StringIO()
self.print_file(star_str)
return star_str.getvalue() | def _to_star(self) | Save :class:`~nmrstarlib.nmrstarlib.StarFile` into NMR-STAR or CIF formatted string.
:return: NMR-STAR string.
:rtype: :py:class:`str` | 5.047678 | 5.509861 | 0.916117 |
if (string[0:5] == u"data_" and u"save_" in string) or (string[0:5] == b"data_" and b"save_" in string):
return string
return False | def _is_nmrstar(string) | Test if input string is in NMR-STAR format.
:param string: Input string.
:type string: :py:class:`str` or :py:class:`bytes`
:return: Input string if in NMR-STAR format or False otherwise.
:rtype: :py:class:`str` or :py:obj:`False` | 5.46949 | 4.607506 | 1.187082 |
if (string[0:5] == u"data_" and u"_entry.id" in string) or (string[0:5] == b"data_" and b"_entry.id" in string):
return string
return False | def _is_cif(string) | Test if input string is in CIF format.
:param string: Input string.
:type string: :py:class:`str` or :py:class:`bytes`
:return: Input string if in CIF format or False otherwise.
:rtype: :py:class:`str` or :py:obj:`False` | 4.886273 | 3.894078 | 1.254796 |
try:
if isinstance(string, bytes):
string = string.decode("utf-8")
json.loads(string)
elif isinstance(string, str):
json.loads(string)
else:
raise TypeError("Expecting <class 'str'> or <class 'bytes'>, b... | def _is_json(string) | Test if input string is in JSON format.
:param string: Input string.
:type string: :py:class:`str` or :py:class:`bytes`
:return: Input string if in JSON format or False otherwise.
:rtype: :py:class:`str` or :py:obj:`False` | 2.87677 | 2.625243 | 1.095811 |
odict = self
comment_count = 0
lexer = bmrblex(nmrstar_str)
token = next(lexer)
while token != u"":
try:
if token[0:5] == u"save_":
name = token
frame = self._build_saveframe(lexer)
... | def _build_file(self, nmrstar_str) | Build :class:`~nmrstarlib.nmrstarlib.NMRStarFile` object.
:param nmrstar_str: NMR-STAR-formatted string.
:type nmrstar_str: :py:class:`str` or :py:class:`bytes`
:return: instance of :class:`~nmrstarlib.nmrstarlib.NMRStarFile`.
:rtype: :class:`~nmrstarlib.nmrstarlib.NMRStarFile` | 3.634806 | 3.714087 | 0.978654 |
odict = OrderedDict()
loop_count = 0
token = next(lexer)
while token != u"save_":
try:
if token[0] == u"_":
# This strips off the leading underscore of tagnames for readability
odict[token[1:]] = next(lexer)
... | def _build_saveframe(self, lexer) | Build NMR-STAR file saveframe.
:param lexer: instance of the lexical analyzer.
:type lexer: :func:`~nmrstarlib.bmrblex.bmrblex`
:return: Saveframe dictionary.
:rtype: :py:class:`collections.OrderedDict` | 3.925496 | 3.863223 | 1.01612 |
fields = []
values = []
token = next(lexer)
while token[0] == u"_":
fields.append(token[1:])
token = next(lexer)
while token != u"stop_":
values.append(token)
token = next(lexer)
assert float(len(values) / len(fi... | def _build_loop(self, lexer) | Build saveframe loop.
:param lexer: instance of lexical analyzer.
:type lexer: :func:`~nmrstarlib.bmrblex.bmrblex`
:return: Fields and values of the loop.
:rtype: :py:class:`tuple` | 3.663831 | 3.333069 | 1.099237 |
token = u""
while token != u"save_":
token = next(lexer) | def _skip_saveframe(self, lexer) | Skip entire saveframe - keep emitting tokens until the end of saveframe.
:param lexer: instance of the lexical analyzer class.
:type lexer: :class:`~nmrstarlib.bmrblex.bmrblex`
:return: None
:rtype: :py:obj:`None` | 15.233604 | 15.113352 | 1.007957 |
if file_format == "nmrstar":
for saveframe in self.keys():
if saveframe == u"data":
print(u"{}_{}\n".format(saveframe, self[saveframe]), file=f)
elif saveframe.startswith(u"comment"):
print(u"{}".format(self[saveframe])... | def print_file(self, f=sys.stdout, file_format="nmrstar", tw=3) | Print :class:`~nmrstarlib.nmrstarlib.NMRStarFile` into a file or stdout.
:param io.StringIO f: writable file-like stream.
:param str file_format: Format to use: `nmrstar` or `json`.
:param int tw: Tab width.
:return: None
:rtype: :py:obj:`None` | 3.089971 | 3.32756 | 0.928599 |
if file_format == "nmrstar":
for sftag in self[sf].keys():
# handle loops
if sftag[:5] == "loop_":
print(u"\n{}loop_".format(tw * u" "), file=f)
self.print_loop(sf, sftag, f, file_format, tw * 2)
pri... | def print_saveframe(self, sf, f=sys.stdout, file_format="nmrstar", tw=3) | Print saveframe into a file or stdout.
We need to keep track of how far over everything is tabbed. The "tab width"
variable tw does this for us.
:param str sf: Saveframe name.
:param io.StringIO f: writable file-like stream.
:param str file_format: Format to use: `nmrstar` or `j... | 2.785068 | 2.859968 | 0.973811 |
if file_format == "nmrstar":
# First print the fields
for field in self[sf][sftag][0]:
print(u"{}_{}".format(tw * u" ", field), file=f)
print(u"", file=f) # new line between fields and values
# Then print the values
for valu... | def print_loop(self, sf, sftag, f=sys.stdout, file_format="nmrstar", tw=3) | Print loop into a file or stdout.
:param str sf: Saveframe name.
:param str sftag: Saveframe tag, i.e. field name.
:param io.StringIO f: writable file-like stream.
:param str file_format: Format to use: `nmrstar` or `json`.
:param int tw: Tab width.
:return: None
... | 3.350151 | 3.217301 | 1.041292 |
if (amino_acids_and_atoms and amino_acids) or (amino_acids_and_atoms and atoms):
raise ValueError('"amino_acids_and_atoms" parameter cannot be used simultaneously with '
'"amino_acids" and "atoms" parameters, one or another must be provided.')
chemshift... | def chem_shifts_by_residue(self, amino_acids=None, atoms=None, amino_acids_and_atoms=None, nmrstar_version="3") | Organize chemical shifts by amino acid residue.
:param list amino_acids: List of amino acids three-letter codes.
:param list atoms: List of BMRB atom type codes.
:param dict amino_acids_and_atoms: Amino acid and its atoms key-value pairs.
:param str nmrstar_version: Version of NMR-STAR... | 1.928369 | 1.874563 | 1.028703 |
odict = self
comment_count = 0
loop_count = 0
lexer = bmrblex(cif_str)
token = next(lexer)
while token != u"":
try:
if token[0:5] == u"data_":
self.id = token[5:]
self[u"data"] = self.id
... | def _build_file(self, cif_str) | Build :class:`~nmrstarlib.nmrstarlib.CIFFile` object.
:param cif_str: NMR-STAR-formatted string.
:type cif_str: :py:class:`str` or :py:class:`bytes`
:return: instance of :class:`~nmrstarlib.nmrstarlib.CIFFile`.
:rtype: :class:`~nmrstarlib.nmrstarlib.CIFFile` | 3.473682 | 3.443264 | 1.008834 |
if file_format == "cif":
for key in self.keys():
if key == u"data":
print(u"{}_{}".format(key, self[key]), file=f)
elif key.startswith(u"comment"):
print(u"{}".format(self[key].strip()), file=f)
elif key... | def print_file(self, f=sys.stdout, file_format="cif", tw=0) | Print :class:`~nmrstarlib.nmrstarlib.CIFFile` into a file or stdout.
:param io.StringIO f: writable file-like stream.
:param str file_format: Format to use: `cif` or `json`.
:param int tw: Tab width.
:return: None
:rtype: :py:obj:`None` | 2.982422 | 2.914824 | 1.023191 |
if func not in ['getRegisterUserInfo']:
s, message = self.checkAccount()
if s is False:
return False, message
url = nurls[func]
r = self.session.get(url, params = data)
r.encoding = 'utf-8'
if self.debug:
print r.tex... | def GET(self, func, data) | Send GET request to execute Ndrive API
:param func: The function name you want to execute in Ndrive API.
:param params: Parameter data for HTTP request.
:returns: metadata when success or False when failed | 4.275894 | 4.076836 | 1.048826 |
s, message = self.checkAccount()
if s is False:
return False, message
url = nurls[func]
r = self.session.post(url, data = data)
r.encoding = 'utf-8'
if self.debug:
print r.text.encode("utf-8")
try:
metadata = json.lo... | def POST(self, func, data) | Send POST request to execute Ndrive API
:param func: The function name you want to execute in Ndrive API.
:param params: Parameter data for HTTP request.
:returns: ``metadata`` when success or ``False`` when failed | 3.477804 | 3.392258 | 1.025218 |
data = {'userid': self.user_id,
'svctype': svctype,
'auth': auth
}
s, metadata = self.GET('getRegisterUserInfo', data)
if s is True:
self.useridx = metadata['useridx']
return True, metadata
else:
... | def getRegisterUserInfo(self, svctype = "Android NDrive App ver", auth = 0) | Retrieve information about useridx
:param svctype: Information about the platform you are using right now.
:param auth: Authentication type
:return: ``True`` when success or ``False`` when failed | 4.889301 | 4.795017 | 1.019663 |
s = self.checkStatus()
s = self.getDiskSpace()
s = self.checkUpload(file_obj, full_path, overwrite)
if s is True:
self.put(file_obj, full_path, overwrite) | def uploadFile(self, file_obj, full_path, overwrite = False) | Upload a file as Ndrive really do.
>>> nd.uploadFile('~/flower.png','/Picture/flower.png',True)
This function imitates the process when Ndrive uploads a local file to its server. The process follows 7 steps:
1. POST /CheckStatus.ndrive
2. POST /GetDiskSpace.ndrive
... | 4.575561 | 3.070147 | 1.490339 |
data = {'userid': self.user_id,
'useridx': self.useridx,
}
s, metadata = self.POST('getDiskSpace',data)
if s is True:
usedspace = byte_readable(metadata['usedspace'])
totalspace = byte_readable(metadata['totalspace'])
p... | def getDiskSpace(self) | Get disk space information.
>>> disk_info = nd.getDiskSpace()
:return: ``metadata`` if success or ``error message``
:metadata:
- expandablespace
- filemaxsize
- largefileminsize
- largefileunusedspace
- largefileusedspa... | 6.017573 | 6.809311 | 0.883727 |
try:
file_obj = file_obj.name
except:
file_obj = file_obj # do nothing
file_size = os.stat(file_obj).st_size
now = datetime.datetime.now().isoformat()
data = {'uploadsize': file_size,
'overwrite': 'T' if overwrite else 'F',
... | def checkUpload(self, file_obj, full_path = '/', overwrite = False) | Check whether it is possible to upload a file.
>>> s = nd.checkUpload('~/flower.png','/Picture/flower.png')
:param file_obj: A file-like object to check whether possible to upload. You can pass a string as a file_obj or a real file object.
:param str full_path: The full path to upload the ... | 4.707999 | 4.689207 | 1.004008 |
if to_path == '':
file_name = os.path.basename(from_path)
to_path = os.path.join(os.getcwd(), file_name)
url = nurls['download'] + from_path
data = {'attachment':2,
'userid': self.user_id,
'useridx': self.useridx,
... | def downloadFile(self, from_path, to_path = '') | Download a file.
>>> nd.downloadFile('/Picture/flower.png', '~/flower.png')
:param from_path: The full path to download the file to, *including the file name*. If the destination directory does not yet exist, it will be created.
:param to_path: The full path of a file to be saved in local ... | 4.730316 | 4.901635 | 0.965049 |
try:
file_obj = open(file_obj, 'r')
except:
file_obj = file_obj # do nothing
content = file_obj.read()
file_name = os.path.basename(full_path)
now = datetime.datetime.now().isoformat()
url = nurls['put'] + full_path
if overwrite... | def put(self, file_obj, full_path, overwrite = False) | Upload a file.
>>> nd.put('./flower.png','/Picture/flower.png')
>>> nd.put(open('./flower.png','r'),'/Picture/flower.png')
:param file_obj: A file-like object to check whether possible to upload. You can pass a string as a file_obj or a real file object.
:param full_path: The f... | 4.101926 | 4.09198 | 1.00243 |
now = datetime.datetime.now().isoformat()
url = nurls['delete'] + full_path
headers = {'userid': self.user_id,
'useridx': self.useridx,
'Content-Type': "application/x-www-form-urlencoded; charset=UTF-8",
'charset': 'UTF-8',
... | def delete(self, full_path) | Delete a file in full_path
>>> nd.delete('/Picture/flower.png')
:param full_path: The full path to delete the file to, *including the file name*.
:return: ``True`` if success to delete the file or ``False`` | 3.955343 | 4.214781 | 0.938446 |
if type not in range(1, 6):
print "Error getList: `type` should be between 1 to 5"
return False
data = {'orgresource': full_path,
'type': type,
'dept': dept,
'sort': sort,
'order': order,
'st... | def getList(self, full_path, type = 1, dept = 0, sort = 'name', order = 'asc', startnum = 0, pagingrow = 1000, dummy = 56184) | Get a list of files
>>> nd_list = nd.getList('/', type=3)
>>> print nd_list
There are 5 kinds of ``type``:
- 1 => only directories with idxfolder property
- 2 => only files
- 3 => directories and files with thumbnail info (like viewHeight, viewWidth ... | 3.707207 | 3.942228 | 0.940384 |
if overwrite:
overwrite = 'F'
else:
overwrite = 'T'
data = {'orgresource': from_path,
'dstresource': to_path,
'overwrite': overwrite,
'bShareFireCopy': bShareFireCopy,
'userid': self.user_id,
... | def doMove(self, from_path, to_path, overwrite = False, bShareFireCopy = 'false', dummy = 56147) | Move a file.
>>> nd.doMove('/Picture/flower.png', '/flower.png')
:param from_path: The path to the file or folder to be moved.
:param to_path: The destination path of the file or folder to be copied. File name should be included in the end of to_path.
:param overwrite: Whether to o... | 4.150089 | 4.940008 | 0.840098 |
if full_path[-1] is not '/':
full_path += '/'
data = {'dstresource': full_path,
'userid': self.user_id,
'useridx': self.useridx,
'dummy': dummy,
}
s, metadata = self.POST('makeDirectory', data)
return... | def makeDirectory(self, full_path, dummy = 40841) | Make a directory
>>> nd.makeDirectory('/test')
:param full_path: The full path to get the directory property. Should be end with '/'.
:return: ``True`` when success to make a directory or ``False`` | 5.976661 | 8.803935 | 0.678862 |
if full_path[-1] is not '/':
full_path += '/'
data = {'_callback': 'window.__jindo_callback._347',
'path': full_path,
'passwd': passwd,
'userid': self.user_id,
'useridx': self.useridx,
}
s, met... | def makeShareUrl(self, full_path, passwd) | Make a share url of directory
>>> nd.makeShareUrl('/Picture/flower.png', PASSWORD)
Args:
full_path:
The full path of directory to get share url.
Should be end with '/'.
ex) /folder/
passwd:
Access password for shared d... | 5.407243 | 5.598917 | 0.965766 |
prop = self.getProperty(full_path)
if not prop:
print "Error getFileLink: wrong full_path"
return False
else:
prop_url = prop['filelinkurl']
if prop_url:
print "URL: " + prop_url
return prop_url
... | def getFileLink(self, full_path) | Get a link of file
>>> file_link = nd.getFileLink('/Picture/flower.png')
:param full_path: The full path of file to get file link. Path should start and end with '/'.
:return: ``Shared url`` or ``False`` if failed to share a file or directory through url | 4.652011 | 5.321498 | 0.874192 |
data = {'_callback': 'window.__jindo_callback._8920',
'resourceno': resourceno,
'userid': self.user_id,
'useridx': self.useridx,
}
s, metadata = self.GET('createFileLink', data)
if s:
print "URL: %s" % (metada... | def createFileLink(self, resourceno) | Make a link of file
If you don't know ``resourceno``, you'd better use ``getFileLink``.
:param resourceno: Resource number of a file to create link
:return: ``Shared url`` or ``False`` when failed to share a file | 6.427269 | 6.385162 | 1.006594 |
data = {'orgresource': full_path,
'userid': self.user_id,
'useridx': self.useridx,
'dummy': dummy,
}
s, metadata = self.POST('getProperty', data)
if s is True:
return metadata
else:
return ... | def getProperty(self, full_path, dummy = 56184) | Get a file property
:param full_path: The full path to get the file or directory property.
:return: ``metadata`` if success or ``False`` if failed to get property
:metadata:
- creationdate
- exif
- filelink
- filelinkurl
- ... | 7.230428 | 8.710752 | 0.830058 |
data = {'orgresource': full_path,
'startnum': startnum,
'pagingrow': pagingrow,
'userid': self.user_id,
'useridx': self.useridx,
'dummy': dummy,
}
s, metadata = self.POST('getVersionList', data)
... | def getVersionList(self, full_path, startnum = 0, pagingrow = 50, dummy = 54213) | Get a version list of a file or dierectory.
:param full_path: The full path to get the file or directory property. Path should start with '/'
:param startnum: Start version index.
:param pagingrow: Max # of version list in one page.
:returns: ``metadata`` if succcess or ``False`` (fail... | 5.08976 | 5.795907 | 0.878165 |
data = {'orgresource': full_path,
'protect': protect,
'userid': self.user_id,
'useridx': self.useridx,
'dummy': dummy,
}
s, metadata = self.POST('setProperty', data)
if s is True:
return True
... | def setProperty(self, full_path, protect, dummy = 7046) | Set property of a file.
:param full_path: The full path to get the file or directory property.
:param protect: 'Y' or 'N', 중요 표시
:return: ``True`` when success to set property or ``False`` | 6.265035 | 7.45108 | 0.840822 |
data = {'tagtype': tagtype,
'startnum': startnum,
'pagingrow': pagingrow,
'userid': self.user_id,
'useridx': self.useridx,
'dummy': dummy,
}
s, metadata = self.POST('getMusicAlbumList', data)
... | def getMusicAlbumList(self, tagtype = 0, startnum = 0, pagingrow = 100, dummy = 51467) | Get music album list.
:param tagtype: ?
:return: ``metadata`` or ``False``
:metadata:
- u'album':u'Greatest Hits Coldplay',
- u'artist':u'Coldplay',
- u'href':u'/Coldplay - Clocks.mp3',
- u'musiccount':1,
- u'resourceno':12459548378,... | 3.673297 | 3.805403 | 0.965285 |
data = {'filename': filename,
'filetype': filetype,
'dstresource': full_path,
'sharedowner': sharedowner,
'datatype': datatype,
'sort': sort,
'order': order,
'searchtype': searchtype,
... | def doSearch(self, filename, filetype = None, type = 3, full_path = '/', sharedowner = 'A', datatype = 'all', sort = 'update', order = 'desc', searchtype = 'filesearch', startnum = 0, pagingrow = 100, includeworks = 'N', bodysearch = 'N', dummy = 36644) | Get music album list.
There are 4 kinds in ``type``:
- 1 : only directories with idxfolder property
- 2 : only files
- 3 : directories and files with thumbnail info (like viewHeight, viewWidth for Image file)
- 4 : only directories except idxfolder
- ... | 3.228239 | 3.468422 | 0.930751 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.