code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
name = method.__name__
special_names = '__getattr__', '__getitem__'
if name not in special_names:
return
wrapper_name = '__cached' + name
def proxy(self, *args, **kwargs):
if wrapper_name not in vars(self):
bound = types.MethodType(method, self)
cache = cache_wrapper(bound)
setattr(self, wrapper_n... | def _special_method_cache(method, cache_wrapper) | Because Python treats special methods differently, it's not
possible to use instance attributes to implement the cached
methods.
Instead, install the wrapper method under a different name
and return a simple proxy to that wrapper.
https://github.com/jaraco/jaraco.functools/issues/5 | 2.685186 | 2.570136 | 1.044764 |
r
def wrap(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
action(result)
return result
return wrapper
return wrap | def result_invoke(action) | r"""
Decorate a function with an action function that is
invoked on the results returned from the decorated
function (for its side-effect), then return the original
result.
>>> @result_invoke(print)
... def add_two(a, b):
... return a + b
>>> x = add_two(2, 3)
5 | 2.493748 | 2.523057 | 0.988384 |
def wrapper(*args, **kwargs):
func1()
return func2(*args, **kwargs)
return wrapper | def first_invoke(func1, func2) | Return a function that when invoked will invoke func1 without
any parameters (for its side-effect) and then invoke func2
with whatever parameters were passed, returning its result. | 2.854218 | 2.943883 | 0.969542 |
attempts = count() if retries == float('inf') else range(retries)
for attempt in attempts:
try:
return func()
except trap:
cleanup()
return func() | def retry_call(func, cleanup=lambda: None, retries=0, trap=()) | Given a callable func, trap the indicated exceptions
for up to 'retries' times, invoking cleanup on the
exception. On the final attempt, allow any exceptions
to propagate. | 3.987192 | 3.68541 | 1.081885 |
def decorate(func):
@functools.wraps(func)
def wrapper(*f_args, **f_kwargs):
bound = functools.partial(func, *f_args, **f_kwargs)
return retry_call(bound, *r_args, **r_kwargs)
return wrapper
return decorate | def retry(*r_args, **r_kwargs) | Decorator wrapper for retry_call. Accepts arguments to retry_call
except func and then returns a decorator for the decorated function.
Ex:
>>> @retry(retries=3)
... def my_func(a, b):
... "this is my funk"
... print(a, b)
>>> my_func.__doc__
'this is my funk' | 1.85952 | 1.944472 | 0.956311 |
print_all = functools.partial(map, print)
print_results = compose(more_itertools.recipes.consume, print_all, func)
return functools.wraps(func)(print_results) | def print_yielded(func) | Convert a generator into a function that prints all yielded elements
>>> @print_yielded
... def x():
... yield 3; yield None
>>> x()
3
None | 6.914151 | 8.629358 | 0.801236 |
@functools.wraps(func)
def wrapper(param, *args, **kwargs):
if param is not None:
return func(param, *args, **kwargs)
return wrapper | def pass_none(func) | Wrap func so it's not called if its first param is None
>>> print_text = pass_none(print)
>>> print_text('text')
text
>>> print_text(None) | 2.165087 | 2.500528 | 0.865852 |
try:
sig = inspect.signature(func)
params = sig.parameters.keys()
except AttributeError:
spec = inspect.getargspec(func)
params = spec.args
call_ns = {
k: namespace[k]
for k in params
if k in namespace
}
return functools.partial(func, **call_ns) | def assign_params(func, namespace) | Assign parameters from namespace where func solicits.
>>> def func(x, y=3):
... print(x, y)
>>> assigned = assign_params(func, dict(x=2, z=4))
>>> assigned()
2 3
The usual errors are raised if a function doesn't receive
its required parameters:
>>> assigned = assign_params(func, dict(y=3, z=4))
>>> assi... | 2.324813 | 3.020369 | 0.769712 |
args_and_kwargs = collections.namedtuple('args_and_kwargs', 'args kwargs')
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
attr_name = '_saved_' + method.__name__
attr = args_and_kwargs(args, kwargs)
setattr(self, attr_name, attr)
return method(self, *args, **kwargs)
return wrapper | def save_method_args(method) | Wrap a method such that when it is called, the args and kwargs are
saved on the method.
>>> class MyClass:
... @save_method_args
... def method(self, a, b):
... print(a, b)
>>> my_ob = MyClass()
>>> my_ob.method(1, 2)
1 2
>>> my_ob._saved_method.args
(1, 2)
>>> my_ob._saved_method.kwargs
{}... | 2.32505 | 2.618593 | 0.887901 |
"ensure at least 1/max_rate seconds from last call"
elapsed = time.time() - self.last_called
must_wait = 1 / self.max_rate - elapsed
time.sleep(max(0, must_wait))
self.last_called = time.time() | def _wait(self) | ensure at least 1/max_rate seconds from last call | 3.874706 | 2.330198 | 1.662823 |
row_col = nodes.entry()
para_col = nodes.paragraph()
if need_key in need_info and need_info[need_key] is not None:
if not isinstance(need_info[need_key], (list, set)):
data = [need_info[need_key]]
else:
data = need_info[need_key]
for index, datum in enu... | def row_col_maker(app, fromdocname, all_needs, need_info, need_key, make_ref=False, ref_lookup=False, prefix='') | Creates and returns a column.
:param app: current sphinx app
:param fromdocname: current document
:param all_needs: Dictionary of all need objects
:param need_info: need_info object, which stores all related need data
:param need_key: The key to access the needed data from need_info
:param make... | 2.299465 | 2.199603 | 1.0454 |
conn = connect(hosts)
container = conn.get_blob_container(table)
with open(filename, 'rb') as f:
digest = container.put(f)
return '{server}/_blobs/{table}/{digest}'.format(
server=conn.client.active_servers[0],
table=table,
digest=digest
) | def insert_blob(filename, hosts=None, table=None) | Upload a file into a blob table | 4.276969 | 4.347741 | 0.983722 |
_dois_arr = []
_dois_raw = []
# open the CSV file
with open(csv_source, "r") as f:
reader = csv.reader(f)
for row in reader:
# sort the DOIs as an array of DOI strings
_dois_arr.append(row[0])
# run the DOI resolver once for each DOI string.
for _d... | def update_dois(csv_source, write_file=True) | Get DOI publication info for a batch of DOIs. This is LiPD-independent and only requires a CSV file with all DOIs
listed in a single column. The output is LiPD-formatted publication data for each entry.
:param str csv_source: Local path to CSV file
:param bool write_file: Write output data to JSON file (Tr... | 3.03708 | 3.120926 | 0.973134 |
# Use demjson to maintain unicode characters in output
json_bin = demjson.encode(json_data, encoding='utf-8', compactly=False)
# Write json to file
try:
open("{}.json".format(filename), "wb").write(json_bin)
except FileNotFoundError as e:
print("Error: Writing json to file: {}".... | def write_json_to_file(json_data, filename="metadata") | Write all JSON in python dictionary to a new json file.
:param any json_data: JSON data
:param str filename: Target filename (defaults to 'metadata.jsonld')
:return None: | 5.082295 | 5.882013 | 0.86404 |
author_list = []
for person in authors:
author_list.append({'name': person['family'] + ", " + person['given']})
return author_list | def compile_authors(authors) | Compiles authors "Last, First" into a single list
:param list authors: Raw author data retrieved from doi.org
:return list: Author objects | 3.562461 | 3.451421 | 1.032172 |
fetch_dict = OrderedDict()
order = {'author': 'author', 'type': 'type', 'identifier': '', 'title': 'title', 'journal': 'container-title',
'pubYear': '', 'volume': 'volume', 'publisher': 'publisher', 'page':'page', 'issue': 'issue'}
for k, v in order.items():
try:
if k =... | def compile_fetch(raw, doi_id) | Loop over Raw and add selected items to Fetch with proper formatting
:param dict raw: JSON data from doi.org
:param str doi_id:
:return dict: | 2.889161 | 2.893556 | 0.998481 |
fetch_dict = {}
try:
# Send request to grab metadata at URL
print("Requesting : {}".format(doi_id))
url = "http://dx.doi.org/" + doi_id
headers = {"accept": "application/rdf+xml;q=0.5, application/citeproc+json;q=1.0"}
r = requests.get(url, headers=headers)
... | def get_data(doi_id) | Resolve DOI and compile all attributes into one dictionary
:param str doi_id:
:param int idx: Publication index
:return dict: Updated publication dictionary | 4.343598 | 4.189798 | 1.036708 |
regex = re.compile(r'\b(10[.][0-9]{3,}(?:[.][0-9]+)*/(?:(?!["&\'<>,])\S)+)\b')
try:
# Returns a list of matching strings
m = re.findall(regex, doi_string)
except TypeError as e:
# If doi_string is None type, return empty list
print("TypeError cleaning DOI: {}, {}".format... | def clean_doi(doi_string) | Use regex to extract all DOI ids from string (i.e. 10.1029/2005pa001215)
:param str doi_string: Raw DOI string value from input file. Often not properly formatted.
:return list: DOI ids. May contain 0, 1, or multiple ids. | 3.307108 | 3.539834 | 0.934255 |
elapsed = round(end - start, 2)
line = ("Benchmark - Function: {} , Time: {} seconds".format(fn, elapsed))
return line | def log_benchmark(fn, start, end) | Log a given function and how long the function takes in seconds
:param str fn: Function name
:param float start: Function start time
:param float end: Function end time
:return none: | 6.022953 | 8.540538 | 0.705219 |
# description = input("Please enter a short description for this update:\n ")
description = 'Placeholder for description here.'
# open changelog file for appending. if doesn't exist, creates file.
with open('changelog.txt', 'a+') as f:
# write update line
f.write(str(datetime.datet... | def update_changelog() | Create or update the changelog txt file. Prompt for update description.
:return None: | 5.38991 | 4.772738 | 1.129312 |
handler = logging.FileHandler(log_file)
rtf_handler = RotatingFileHandler(log_file, maxBytes=30000, backupCount=0)
formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(name)s: %(message)s')
handler.setFormatter(formatter)
logger = logging.getLogger(name)
logger.setLevel(level)
l... | def create_benchmark(name, log_file, level=logging.INFO) | Creates a logger for function benchmark times
:param str name: Name of the logger
:param str log_file: Filename
:return obj: Logger | 1.837409 | 1.966712 | 0.934254 |
logging.config.dictConfig({
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'simple': {
'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'
},
'detailed': {
'format': '%(asctime)s %(module)-17... | def create_logger(name) | Creates a logger with the below attributes.
:param str name: Name of the logger
:return obj: Logger | 1.714832 | 1.738661 | 0.986294 |
num_lines = 0
log = Logger(output_fmt)
with Runner(hosts, concurrency, sample_mode) as runner:
version_info = aio.run(runner.client.get_server_version)
for line in as_statements(lines_from_stdin(stmt)):
runner.warmup(line, warmup)
timed_stats = runner.run(line, i... | def timeit(hosts=None,
stmt=None,
warmup=30,
repeat=None,
duration=None,
concurrency=1,
output_fmt=None,
fail_if=None,
sample_mode='reservoir') | Run the given statement a number of times and return the runtime stats
Args:
fail-if: An expression that causes cr8 to exit with a failure if it
evaluates to true.
The expression can contain formatting expressions for:
- runtime_stats
- statement
... | 5.005434 | 5.494739 | 0.91095 |
if os.name == 'nt':
import winreg
sub_key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders'
downloads_guid = '{374DE290-123F-4565-9164-39C4925E467B}'
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, sub_key) as key:
location = winreg.QueryValueEx(key... | def get_download_path() | Determine the OS and the associated download folder.
:return str Download path: | 1.388897 | 1.432673 | 0.969445 |
if "MD982181" not in src_url:
try:
print("downloading file from url...")
urllib.request.urlretrieve(src_url, dst_path)
except Exception as e:
print("Error: unable to download from url: {}".format(e))
return | def download_file(src_url, dst_path) | Use the given URL and destination to download and save a file
:param str src_url: Direct URL to lipd file download
:param str dst_path: Local path to download file to, including filename and ext. ex. /path/to/filename.lpd
:return none: | 4.623982 | 5.141945 | 0.899267 |
not_expired = Timeout(timeout)
while not_expired():
r = predicate()
if r:
break | def wait_until(predicate, timeout=30) | Wait until predicate returns a truthy value or the timeout is reached.
>>> wait_until(lambda: True, timeout=10) | 7.15307 | 19.238514 | 0.37181 |
pattern = fnmatch.translate(version_pattern.replace('x', '*'))
return next((v for v in versions if re.match(pattern, v)), None) | def _find_matching_version(versions, version_pattern) | Return the first matching version
>>> _find_matching_version(['1.1.4', '1.0.12', '1.0.5'], '1.0.x')
'1.0.12'
>>> _find_matching_version(['1.1.4', '1.0.6', '1.0.5'], '2.x.x') | 3.563116 | 6.615306 | 0.538617 |
run = partial(subprocess.run, cwd=src_repo, check=True)
run(['git', 'clean', '-xdff'])
src_repo = Path(src_repo)
if os.path.exists(src_repo / 'es' / 'upstream'):
run(['git', 'submodule', 'update', '--init', '--', 'es/upstream'])
run(['./gradlew', '--no-daemon', 'clean', 'distTar'])
... | def _build_tarball(src_repo) -> str | Build a tarball from src and return the path to it | 4.529915 | 4.200721 | 1.078366 |
return os.environ.get(
'XDG_CACHE_HOME',
os.path.join(os.path.expanduser('~'), '.cache', 'cr8', 'crates')) | def _crates_cache() -> str | Return the path to the crates cache folder | 3.580112 | 2.883057 | 1.241776 |
if not crate_root:
crate_root = _crates_cache()
_remove_old_crates(crate_root)
if _is_project_repo(version):
return _extract_tarball(_build_tarball(version))
m = BRANCH_VERSION_RE.match(version)
if m:
return _build_from_release_branch(m.group(0), crate_root)
uri ... | def get_crate(version, crate_root=None) | Retrieve a Crate tarball, extract it and return the path.
Args:
version: The Crate version to get.
Can be specified in different ways:
- A concrete version like '0.55.0'
- A version including a `x` as wildcards. Like: '1.1.x' or '1.x.x'.
This will use the ... | 4.280035 | 4.483882 | 0.954538 |
try:
return dict(i.split('=', maxsplit=1) for i in options)
except ValueError:
raise ArgumentError(
f'Option must be in format <key>=<value>, got: {options}') | def _parse_options(options: List[str]) -> Dict[str, str] | Parse repeatable CLI options
>>> opts = _parse_options(['cluster.name=foo', 'CRATE_JAVA_OPTS="-Dxy=foo"'])
>>> print(json.dumps(opts, sort_keys=True))
{"CRATE_JAVA_OPTS": "\\"-Dxy=foo\\"", "cluster.name": "foo"} | 3.524782 | 4.367198 | 0.807104 |
with create_node(
version,
env,
setting,
crate_root,
keep_data,
java_magic=not disable_java_magic,
) as n:
try:
n.start()
n.process.wait()
except KeyboardInterrupt:
print('Stopping Cr... | def run_crate(
version,
env=None,
setting=None,
crate_root=None,
keep_data=False,
disable_java_magic=False,
) | Launch a crate instance.
Supported version specifications:
- Concrete version like "0.55.0" or with wildcard: "1.1.x"
- An alias (one of [latest-nightly, latest-stable, latest-testing])
- A URI pointing to a CrateDB tarball (in .tar.gz format)
- A URI pointing to a checked out Crate... | 3.729438 | 5.687493 | 0.655726 |
log.info('Starting Crate process')
self.process = proc = self.enter_context(subprocess.Popen(
self.cmd,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
env=self.env,
universal_newlines=True
... | def start(self) | Start the process.
This will block until the Crate cluster is ready to process requests. | 3.852649 | 3.669334 | 1.049959 |
m = AddrConsumer.ADDRESS_RE.match(line)
if not m:
return None, None
protocol = m.group('protocol')
protocol = AddrConsumer.PROTOCOL_MAP.get(protocol, protocol)
return protocol, m.group('addr') | def _parse(line) | Parse protocol and bound address from log message
>>> AddrConsumer._parse('NONE')
(None, None)
>>> AddrConsumer._parse('[INFO ][i.c.p.h.CrateNettyHttpServerTransport] [Widderstein] publish_address {127.0.0.1:4200}, bound_addresses {[fe80::1]:4200}, {[::1]:4200}, {127.0.0.1:4200}')
('ht... | 4.664785 | 3.343737 | 1.395081 |
I = image.copy()
I_f = I.astype(np.float32) / 255. # Used for mean and std.
result = np.zeros(
(image.shape[0] / blocksize, image.shape[1] / blocksize),
dtype=np.float32)
for i in xrange(0, image.shape[0] - blocksize, blocksize):
for j in xrange(0, image.shape[1] - blocks... | def _calc_block_mean_variance(image, mask, blocksize) | Adaptively determines image background.
Args:
image: image converted 1-channel image.
mask: 1-channel mask, same size as image.
blocksize: adaptive algorithm parameter.
Returns:
image of same size as input with foreground inpainted with background. | 2.212341 | 2.193086 | 1.00878 |
if mask is None:
mask = np.zeros(image.shape[:2], dtype=np.uint8)
mask[:] = 255
if len(image.shape) > 2 and image.shape[2] == 4:
image = cv2.cvtColor(image, cv2.COLOR_BGRA2GRAY)
res = _calc_block_mean_variance(image, mask, block_size)
res = image.astype(np.float32) - res.as... | def threshold(image, block_size=DEFAULT_BLOCKSIZE, mask=None) | Applies adaptive thresholding to the given image.
Args:
image: BGRA image.
block_size: optional int block_size to use for adaptive thresholding.
mask: optional mask.
Returns:
Thresholded image. | 2.252715 | 2.402893 | 0.937501 |
dist.metadata.version = find_version(**value).version | def setup(dist, attr, value) | A hook for simplifying ``vcversioner`` use from distutils.
This hook, when installed properly, allows vcversioner to automatically run
when specifying a ``vcversioner`` argument to ``setup``. For example::
from setuptools import setup
setup(
setup_requires=['vcversioner'],
vcv... | 37.698238 | 14.536466 | 2.593357 |
columns = []
args = []
for key, val in d.items():
columns.append('"{}"'.format(key))
args.append(val)
stmt = 'insert into {table} ({columns}) values ({params})'.format(
table=table,
columns=', '.join(columns),
params=', '.join(['?'] * len(columns)))
retu... | def to_insert(table, d) | Generate an insert statement using the given table and dictionary.
Args:
table (str): table name
d (dict): dictionary with column names as keys and values as values.
Returns:
tuple of statement and arguments
>>> to_insert('doc.foobar', {'name': 'Marvin'})
('insert into doc.foob... | 2.288055 | 2.069126 | 1.105807 |
if not hosts:
return print_only(table)
queries = (to_insert(table, d) for d in dicts_from_stdin())
bulk_queries = as_bulk_queries(queries, bulk_size)
print('Executing inserts: bulk_size={} concurrency={}'.format(
bulk_size, concurrency), file=sys.stderr)
stats = Stats()
wi... | def insert_json(table=None,
bulk_size=1000,
concurrency=25,
hosts=None,
output_fmt=None) | Insert JSON lines fed into stdin into a Crate cluster.
If no hosts are specified the statements will be printed.
Args:
table: Target table name.
bulk_size: Bulk size of the insert statements.
concurrency: Number of operations to run concurrently.
hosts: hostname:port pairs of t... | 5.615393 | 6.202873 | 0.905289 |
if domination_type == MEDIAN:
return _get_median_angle(lines)
elif domination_type == MEAN:
return _get_mean_angle(lines)
else:
raise ValueError('Unknown domination type provided: %s' % (
domination_type)) | def _get_dominant_angle(lines, domination_type=MEDIAN) | Picks dominant angle of a set of lines.
Args:
lines: iterable of (x1, y1, x2, y2) tuples that define lines.
domination_type: either MEDIAN or MEAN.
Returns:
Dominant angle value in radians.
Raises:
ValueError: on unknown domination_type. | 2.111651 | 2.46469 | 0.856761 |
while angle <= range[0]:
angle += step
while angle >= range[1]:
angle -= step
return angle | def _normalize_angle(angle, range, step) | Finds an angle that matches the given one modulo step.
Increments and decrements the given value with a given step.
Args:
range: a 2-tuple of min and max target values.
step: tuning step.
Returns:
Normalized value within a given range. | 2.3188 | 4.444103 | 0.52177 |
options = {
'limit': limit,
'offset': offset,
}
request = requests.get(self.url, params=options, auth=self.auth)
try:
results = request.json()['collectors']
except KeyError:
results = request.json()
except json.dec... | def get_collectors(self, limit=1000, offset=0) | Returns a dict of collectors.
Args:
limit (int): number of collectors to return
offset (int): the offset of where the list of collectors should begin from | 2.567752 | 3.030265 | 0.847369 |
collectors = self.get_collectors()
for collector in collectors:
if name.lower() == collector['name'].lower():
self.collector_id = collector['id']
return collector
return {'status': 'No results found.'} | def find(self, name) | Returns a dict of collector's details if found.
Args:
name (str): name of collector searching for | 4.138676 | 3.419831 | 1.210199 |
cid = self.collector_id
if collector_id:
cid = collector_id
# param to delete id
url = '{0}/{1}'.format(self.url, cid)
request = requests.delete(url, auth=self.auth)
try:
# unable to delete collector
response = request.json()... | def delete(self, collector_id=None) | Delete a collector from inventory.
Args:
collector_id (int): id of collector (optional) | 4.685764 | 5.078566 | 0.922655 |
cid = self.collector_id
if collector_id:
cid = collector_id
url = '{0}/{1}'.format(self.url, cid)
request = requests.get(url, auth=self.auth)
return request.json() | def info(self, collector_id) | Return a dict of collector.
Args:
collector_id (int): id of collector (optional) | 3.243148 | 3.288549 | 0.986194 |
if key == 'chronData':
# Not interested in expanding chronData in dot notation. Keep it as a chunk.
dots[key] = d
elif isinstance(d, dict):
for k in d:
_dotnotation_for_nested_dictionary(d[k], key + '.' + k if key else k, dots)
elif isinstance(d, list) and \
... | def _dotnotation_for_nested_dictionary(d, key, dots) | Flattens nested data structures using dot notation.
:param dict d: Original or nested dictionary
:param str key:
:param dict dots: Dotted dictionary so far
:return dict: Dotted dictionary so far | 3.403516 | 3.451847 | 0.985999 |
logger_dataframes.info("enter ens_to_df")
# "Flatten" the nested lists. Bring all nested lists up to top-level. Output looks like [ [1,2], [1,2], ... ]
ll = unwrap_arrays(ensemble)
# Check that list lengths are all equal
valid = match_arr_lengths(ll)
if valid:
# Lists are equal leng... | def create_dataframe(ensemble) | Create a data frame from given nested lists of ensemble data
:param list ensemble: Ensemble data
:return obj: Dataframe | 8.521993 | 8.057463 | 1.057652 |
dfs = {}
logger_dataframes.info("enter lipd_to_df")
# Flatten the dictionary, but ignore the chron data items
dict_in_dotted = {}
logger_dataframes.info("enter dot_notation")
_dotnotation_for_nested_dictionary(metadata, '', dict_in_dotted)
dict_in_dotted = collections.OrderedDict(sorte... | def lipd_to_df(metadata, csvs) | Create an organized collection of data frames from LiPD data
:param dict metadata: LiPD data
:param dict csvs: Csv data
:return dict: One data frame per table, organized in a dictionary by name | 6.879814 | 6.57079 | 1.04703 |
logger_dataframes.info("enter ts_to_df")
dfs = {}
# Plot the variable + values vs year, age, depth (whichever are available)
dfs["paleoData"] = pd.DataFrame(_plot_ts_cols(metadata))
# Plot the chronology variables + values in a data frame
dfs["chronData"] = _get_key_data(metadata, "chronD... | def ts_to_df(metadata) | Create a data frame from one TimeSeries object
:param dict metadata: Time Series dictionary
:return dict: One data frame per table, organized in a dictionary by name | 7.719975 | 7.785051 | 0.991641 |
logger_dataframes.info("enter get_ts_cols()")
d = {}
# Not entirely necessary, but this will make the column headers look nicer for the data frame
# The column header will be in format "variableName (units)"
try:
units = " (" + ts["paleoData_units"] + ")"
except KeyError as e:
... | def _plot_ts_cols(ts) | Get variable + values vs year, age, depth (whichever are available)
:param dict ts: TimeSeries dictionary
:return dict: Key: variableName, Value: Panda Series object | 4.19733 | 3.732964 | 1.124396 |
logger_dataframes.info("enter get_lipd_cols")
# placeholders for the incoming data frames
dfs = {"chronData": {}, "paleoData": {}}
try:
for filename, cols in csvs.items():
tmp = {}
for var, data in cols.items():
tmp[var] = pd.Series(data["values"])
... | def _get_dfs(csvs) | LiPD Version 1.2
Create a data frame for each table for the given key
:param dict csvs: LiPD metadata dictionary
:return dict: paleo data data frames | 4.551505 | 4.033615 | 1.128393 |
d2 = ""
try:
d2 = d[key]
except KeyError:
logger_dataframes.info("get_key_data: KeyError: {}".format(key))
return d2 | def _get_key_data(d, key) | Generic function to grab dictionary data by key with error handling
:return: | 5.810725 | 5.7648 | 1.007966 |
logger_dataframes.info("enter get_filtered_dfs")
dfs = {}
tt = None
# Process all lipds files or one lipds file?
specific_files = _check_expr_filename(expr)
# Determine the table type wanted
if "chron" in expr:
tt = "chron"
elif "paleo" in expr:
tt = "paleo"
... | def get_filtered_dfs(lib, expr) | Main: Get all data frames that match the given expression
:return dict: Filenames and data frames (filtered) | 4.346067 | 4.197312 | 1.035441 |
logger_dataframes.info("enter match_dfs_expr")
filenames = []
s = "{}Data".format(tt)
# Top table level. Going through all tables of certain type (i.e. chron or paleo)
for k, v in lo_meta["{}Data".format(tt)].items():
# Inner table level. Get data from one specific table
if "m... | def _match_dfs_expr(lo_meta, expr, tt) | Use the given expression to get all data frames that match the criteria (i.e. "paleo measurement tables")
:param dict lo_meta: Lipd object metadata
:param str expr: Search expression
:param str tt: Table type (chron or paleo)
:return list: All filenames that match the expression | 2.407185 | 2.168198 | 1.110224 |
logger_dataframes.info("enter match_filenames_w_dfs")
dfs = {}
for filename in filenames:
try:
if filename in lo_dfs["chronData"]:
dfs[filename] = lo_dfs["chronData"][filename]
elif filename in lo_dfs["paleoData"]:
dfs[filename] = lo_dfs[... | def _match_filenames_w_dfs(filenames, lo_dfs) | Match a list of filenames to their data frame counterparts. Return data frames
:param list filenames: Filenames of data frames to retrieve
:param dict lo_dfs: All data frames
:return dict: Filenames and data frames (filtered) | 3.66357 | 3.410424 | 1.074227 |
expr_lst = expr.split()
f = [x for x in expr_lst if x not in DATA_FRAMES and x.endswith(".lpd")]
return f | def _check_expr_filename(expr) | Split the expression and look to see if there's a specific filename that the user wants to process.
:param str expr: Search expression
:return str: Filename or None | 9.828763 | 10.465558 | 0.939153 |
_j = {}
dir_original = os.getcwd()
# Import metadata into object
try:
print("reading: {}".format(print_filename(path)))
# bigger than 2mb file? This could take a while
if os.stat(path).st_size > 1000000:
_size = os.stat(path).st_size
print("{} :That'... | def lipd_read(path) | Loads a LiPD file from local path. Unzip, read, and process data
Steps: create tmp, unzip lipd, read files into memory, manipulate data, move to original dir, delete tmp.
:param str path: Source path
:return none: | 5.239718 | 5.258504 | 0.996428 |
# Json is pass by reference. Make a copy so we don't mess up the original data.
_json_tmp = copy.deepcopy(_json)
dir_original = os.getcwd()
try:
dir_tmp = create_tmp_dir()
dir_bag = os.path.join(dir_tmp, "bag")
os.mkdir(dir_bag)
os.chdir(dir_bag)
_dsn = get_d... | def lipd_write(_json, path) | Saves current state of LiPD object data. Outputs to a LiPD file.
Steps: create tmp, create bag dir, get dsn, splice csv from json, write csv, clean json, write json, create bagit,
zip up bag folder, place lipd in target dst, move to original dir, delete tmp
:param dict _json: Metadata
:param str pa... | 3.904277 | 3.528935 | 1.106361 |
while active and num_records > 0:
req_size = min(num_records, bulk_size)
num_records -= req_size
yield req_size | def _bulk_size_generator(num_records, bulk_size, active) | Generate bulk_size until num_records is reached or active becomes false
>>> gen = _bulk_size_generator(155, 50, [True])
>>> list(gen)
[50, 50, 50, 5] | 2.707074 | 3.454096 | 0.783729 |
with clients.client(hosts, concurrency=1) as client:
schema, table_name = parse_table(table)
columns = retrieve_columns(client, schema, table_name)
if not columns:
sys.exit('Could not find columns for table "{}"'.format(table))
print('Found schema: ')
print(json.dumps(column... | def insert_fake_data(hosts=None,
table=None,
num_records=1e5,
bulk_size=1000,
concurrency=25,
mapping_file=None) | Generate random data and insert it into a table.
This will read the table schema and then find suitable random data providers.
Which provider is choosen depends on the column name and data type.
Example:
A column named `name` will map to the `name` provider.
A column named `x` of type int... | 3.329686 | 3.403747 | 0.978241 |
logger_doi_resolver.info("enter doi_resolver")
for idx, pub in enumerate(self.root_dict['pub']):
# Retrieve DOI id key-value from the root_dict
doi_string, doi_found = self.find_doi(pub)
if doi_found:
logger_doi_resolver.info("doi found: {}".... | def main(self) | Main function that gets file(s), creates outputs, and runs all operations.
:return dict: Updated or original data for jsonld file | 5.419938 | 5.634861 | 0.961858 |
blank = [" ", "", None]
for k, v in fetch_dict.items():
try:
if fetch_dict[k] != blank:
pub_dict[k] = fetch_dict[k]
except KeyError:
pass
return pub_dict | def compare_replace(pub_dict, fetch_dict) | Take in our Original Pub, and Fetched Pub. For each Fetched entry that has data, overwrite the Original entry
:param pub_dict: (dict) Original pub dictionary
:param fetch_dict: (dict) Fetched pub dictionary from doi.org
:return: (dict) Updated pub dictionary, with fetched data taking precedence | 3.067109 | 2.909338 | 1.054229 |
# Append location 1
if 'link' in self.root_dict['pub'][0]:
self.root_dict['pub'][0]['link'].append({"url": doi_string})
else:
self.root_dict['pub'][0]['link'] = [{"url": doi_string}]
# Append location 2
self.root_dict['dataURL'] = doi_string
... | def noaa_citation(self, doi_string) | Special instructions for moving noaa data to the correct fields
:param doi_string: (str) NOAA url
:return: None | 3.898571 | 4.008587 | 0.972555 |
logger_doi_resolver.info("enter illegal_doi")
# Ignores empty or irrelevant strings (blank, spaces, na, nan, ', others)
if len(doi_string) > 5:
# NOAA string
if 'noaa' in doi_string.lower():
self.noaa_citation(doi_string)
# Paragraph... | def illegal_doi(self, doi_string) | DOI string did not match the regex. Determine what the data is.
:param doi_string: (str) Malformed DOI string
:return: None | 8.755022 | 8.627779 | 1.014748 |
fetch_dict = OrderedDict()
order = {'author': 'author', 'type': 'type', 'identifier': '', 'title': 'title', 'journal': 'container-title',
'pubYear': '', 'volume': 'volume', 'publisher': 'publisher', 'page':'page', 'issue': 'issue'}
for k, v in order.items():
... | def compile_fetch(self, raw, doi_id) | Loop over Raw and add selected items to Fetch with proper formatting
:param dict raw: JSON data from doi.org
:param str doi_id:
:return dict: | 3.200249 | 3.205624 | 0.998324 |
tmp_dict = self.root_dict['pub'][0].copy()
try:
# Send request to grab metadata at URL
url = "http://dx.doi.org/" + doi_id
headers = {"accept": "application/rdf+xml;q=0.5, application/citeproc+json;q=1.0"}
r = requests.get(url, headers=headers)
... | def get_data(self, doi_id, idx) | Resolve DOI and compile all attributes into one dictionary
:param str doi_id:
:param int idx: Publication index
:return dict: Updated publication dictionary | 4.791401 | 4.581171 | 1.04589 |
try:
if 'id' in curr_dict:
return curr_dict['id'], True
elif isinstance(curr_dict, list):
for i in curr_dict:
return self.find_doi(i)
elif isinstance(curr_dict, dict):
for k, v in curr_dict.items():
... | def find_doi(self, curr_dict) | Recursively search the file for the DOI id. More taxing, but more flexible when dictionary structuring isn't absolute
:param dict curr_dict: Current dictionary being searched
:return dict bool: Recursive - Current dictionary, False flag that DOI was not found
:return str bool: Final - DOI id, Tr... | 2.559999 | 2.280152 | 1.122732 |
try:
d[idx].append(float(x))
except ValueError:
d[idx].append(x)
# logger_misc.warn("cast_values_csv: ValueError")
# logger_misc.warn("ValueError: col: {}, {}".format(x, e))
except KeyError as e:
logger_misc.warn("cast_values_csv: KeyError: col: {}, {}".format(x,... | def cast_values_csvs(d, idx, x) | Attempt to cast string to float. If error, keep as a string.
:param dict d: Data
:param int idx: Index number
:param str x: Data
:return any: | 3.880072 | 3.98873 | 0.972759 |
try:
x = float(x)
except ValueError:
try:
x = x.strip()
except AttributeError as e:
logger_misc.warn("parse_str: AttributeError: String not number or word, {}, {}".format(x, e))
return x | def cast_float(x) | Attempt to cleanup string or convert to number value.
:param any x:
:return float: | 7.519624 | 7.691204 | 0.977691 |
try:
x = int(x)
except ValueError:
try:
x = x.strip()
except AttributeError as e:
logger_misc.warn("parse_str: AttributeError: String not number or word, {}, {}".format(x, e))
return x | def cast_int(x) | Cast unknown type into integer
:param any x:
:return int: | 7.321408 | 8.485661 | 0.862798 |
regex = re.compile(r'\b(10[.][0-9]{3,}(?:[.][0-9]+)*/(?:(?!["&\'<>,])\S)+)\b')
try:
# Returns a list of matching strings
m = re.findall(regex, doi_string)
except TypeError as e:
# If doi_string is None type, return empty list
logger_misc.warn("TypeError cleaning DOI: {},... | def clean_doi(doi_string) | Use regex to extract all DOI ids from string (i.e. 10.1029/2005pa001215)
:param str doi_string: Raw DOI string value from input file. Often not properly formatted.
:return list: DOI ids. May contain 0, 1, or multiple ids. | 3.729033 | 4.009366 | 0.93008 |
# _row = []
try:
# Convert tuple to list for processing
row = list(row)
for idx, x in enumerate(row):
x = str(x)
# Is this a scientific notated float? Tear it apart with regex, round, and piece together again
m = re.match(re_sci_notation, x)
... | def decimal_precision(row) | Change the "precision" of values before writing to CSV. Each value is rounded to 3 numbers.
ex: 300 -> 300
ex: 300.123456 -> 300.123
ex: 3.123456e-25 - > 3.123e-25
:param tuple row: Row of numbers to process
:return list row: Processed row | 5.199104 | 4.809555 | 1.080995 |
try:
for idx, n in enumerate(d["geo"]["geometry"]["coordinates"]):
d["geo"]["geometry"]["coordinates"][idx] = round(n, 5)
except Exception as e:
logger_misc.error("fix_coordinate_decimal: {}".format(e))
return d | def fix_coordinate_decimal(d) | Coordinate decimal degrees calculated by an excel formula are often too long as a repeating decimal.
Round them down to 5 decimals
:param dict d: Metadata
:return dict d: Metadata | 3.719883 | 3.815891 | 0.97484 |
if fmt:
time = dt.datetime.now().strftime(fmt)
else:
time = dt.date.today()
return str(time) | def generate_timestamp(fmt=None) | Generate a timestamp to mark when this file was last modified.
:param str fmt: Special format instructions
:return str: YYYY-MM-DD format, or specified format | 3.395967 | 5.269868 | 0.644412 |
chars = string.ascii_uppercase + string.digits
_gen = "".join(random.choice(chars) for _ in range(size))
return "PYT" + str(_gen) | def generate_tsid(size=8) | Generate a TSid string. Use the "PYT" prefix for traceability, and 8 trailing generated characters
ex: PYT9AG234GS
:return str: TSid | 4.107694 | 3.232828 | 1.27062 |
loop = 0
while name in columns:
loop += 1
if loop > 10:
logger_misc.warn("get_appended_name: Too many loops: Tried to get appended name but something looks wrong")
break
tmp = name + "-" + str(loop)
if tmp not in columns:
return tmp
re... | def get_appended_name(name, columns) | Append numbers to a name until it no longer conflicts with the other names in a column.
Necessary to avoid overwriting columns and losing data. Loop a preset amount of times to avoid an infinite loop.
There shouldn't ever be more than two or three identical variable names in a table.
:param str name: Varia... | 5.242879 | 5.585156 | 0.938717 |
_authors = ""
# if it's a string already, we're done
if isinstance(x, str):
return x
# elif it's a list, keep going
elif isinstance(x, list):
# item in list is a str
if isinstance(x[0], str):
# loop and concat until the last item
for name in x[:-... | def get_authors_as_str(x) | Take author or investigator data, and convert it to a concatenated string of names.
Author data structure has a few variations, so account for all.
:param any x: Author data
:return str: Author string | 3.686685 | 3.446949 | 1.06955 |
try:
return d["dataSetName"]
except Exception as e:
logger_misc.warn("get_dsn: Exception: No datasetname found, unable to continue: {}".format(e))
exit(1) | def get_dsn(d) | Get the dataset name from a record
:param dict d: Metadata
:return str: Dataset name | 10.379432 | 8.025423 | 1.293319 |
_rows_cols = {"rows": 0, "cols": 0}
try:
if len(d) == 1:
for var, data in d.items():
# increment columns by one
_rows_cols["cols"] += len(data["values"])
# get row count by getting len of column (since it's only one list
_... | def get_ensemble_counts(d) | Determine if this is a 1 or 2 column ensemble. Then determine how many columns and rows it has.
:param dict d: Metadata (table)
:return dict _rows_cols: Row and column counts | 3.568896 | 3.222048 | 1.107649 |
_mv = "nan"
# Attempt to find a table-level missing value key
try:
# check for missing value key at the table root
_mv = d["missingValue"]
except KeyError as e:
logger_misc.info("get_missing_value: No missing value key found: {}".format(e))
except AttributeError as e:
... | def get_missing_value_key(d) | Get the Missing Value entry from a table of data. If none is found, try the columns.
If still none found, prompt user.
:param dict d: Table of data
:return str _mv: Missing Value | 4.929384 | 4.674479 | 1.054531 |
var = ""
try:
var = d["variableName"]
except KeyError:
try:
var = d["name"]
except KeyError:
num = "unknown"
if "number" in d:
num = d["number"]
print("Error: column number <{}> is missing a variableName. Please fix... | def get_variable_name_col(d) | Get the variable name from a table or column
:param dict d: Metadata (column)
:return str var: Variable name | 5.052383 | 5.098603 | 0.990935 |
try:
var = d[key]
return var
except KeyError:
logger_misc.info("get_variable_name_table: KeyError: missing {}, use name: {}".format(key, fallback))
return fallback | def get_table_key(key, d, fallback="") | Try to get a table name from a data table
:param str key: Key to try first
:param dict d: Data table
:param str fallback: (optional) If we don't find a table name, use this as a generic name fallback.
:return str var: Data table name | 8.197331 | 7.594743 | 1.079343 |
for var, data in d.items():
try:
if isinstance(data["number"], list):
return True
except Exception as e:
logger_misc.debug("misc: is_ensemble: {}".format(e))
return False | def is_ensemble(d) | Check if a table of data is an ensemble table. Is the first values index a list? ensemble. Int/float? not ensemble.
:param dict d: Table data
:return bool: Ensemble or not ensemble | 6.192088 | 6.744201 | 0.918135 |
correct_ext = False
curr_ext = os.path.splitext(file_path)[1]
exts = [curr_ext, file_type]
try:
# special case: if file type is excel, both extensions are valid.
if ".xlsx" in exts and ".xls" in exts:
correct_ext = True
elif curr_ext == file_type:
cor... | def load_fn_matches_ext(file_path, file_type) | Check that the file extension matches the target extension given.
:param str file_path: Path to be checked
:param str file_type: Target extension
:return bool correct_ext: Extension match or does not match | 3.93124 | 4.111372 | 0.956187 |
logger_misc.info("enter match_operators")
ops = {'>': operator.gt,
'<': operator.lt,
'>=': operator.ge,
'<=': operator.le,
'=': operator.eq
}
try:
truth = ops[relate](inp, cut)
except KeyError as e:
truth = False
logger_... | def match_operators(inp, relate, cut) | Compare two items. Match a string operator to an operator function
:param str inp: Comparison item
:param str relate: Comparison operator
:param any cut: Comparison item
:return bool truth: Comparison truth | 3.276624 | 2.958368 | 1.107578 |
try:
# length of first list. use as basis to check other list lengths against.
inner_len = len(l[0])
# check each nested list
for i in l:
# if the length doesn't match the first list, then don't proceed.
if len(i) != inner_len:
return Fals... | def match_arr_lengths(l) | Check that all the array lengths match so that a DataFrame can be created successfully.
:param list l: Nested arrays
:return bool: Valid or invalid | 7.350742 | 6.904568 | 1.06462 |
# list the files in the src directory
files = os.listdir(src)
# loop for each file found
for file in files:
# move the file from the src to the dst
shutil.move(os.path.join(src, file), os.path.join(dst, file))
return | def mv_files(src, dst) | Move all files from one directory to another
:param str src: Source directory
:param str dst: Destination directory
:return none: | 2.497659 | 2.756253 | 0.906179 |
# Normalize the string into a byte string form
s = unicodedata.normalize('NFKD', s).encode('ascii', 'ignore')
# Remove the byte string and quotes from the string
s = str(s)[2:-1]
return s | def normalize_name(s) | Remove foreign accents and characters to normalize the string. Prevents encoding errors.
:param str s: String
:return str s: String | 4.956861 | 5.387603 | 0.92005 |
if os.path.isfile(path) and target == "file":
return True
elif os.path.isdir(path) and target == "directory":
return True
else:
print("Error: Path given is not a {}: {}".format(target, path))
return False | def path_type(path, target) | Determine if given path is file, directory, or other. Compare with target to see if it's the type we wanted.
:param str path: Path
:param str target: Target type wanted
:return bool: Path is what it claims to be (True) or mismatch (False) | 2.829126 | 2.764125 | 1.023516 |
if os.path.basename(path):
return os.path.basename(path)
return path | def print_filename(path) | Print out lipd filename that is being read or written
:param str path: all file metadata
:return str: filename | 4.587453 | 4.766176 | 0.962502 |
stop = 3
ans = ""
while True and stop > 0:
ans = input("Save as (d)ictionary or (o)bject?\n"
"* Note:\n"
"Dictionaries are more basic, and are compatible with Python v2.7+.\n"
"Objects are more complex, and are only compatible with v3.... | def prompt_protocol() | Prompt user if they would like to save pickle file as a dictionary or an object.
:return str: Answer | 7.375393 | 6.259546 | 1.178263 |
try:
if isinstance(x, dict):
try:
for k, v in x.items():
# Is this the columns key?
if k == "columns":
try:
# loop over each column of data. Sorted by variableName key
... | def put_tsids(x) | (Recursive) Add in TSids into any columns that do not have them.
Look for "columns" keys, and then start looping and adding generated TSids to each column
:param any x: Unknown
:return any x: Unknown | 3.136338 | 2.896313 | 1.082873 |
# No logger here because the function is recursive.
# Int types don't matter. Return as-is.
if not isinstance(x, int) and not isinstance(x, float):
if isinstance(x, str) or x is None:
try:
# Remove new line characters and carriage returns
x = x.rstrip... | def rm_empty_fields(x) | (Recursive) Go through N number of nested data types and remove all empty entries.
:param any x: Unknown
:return any x: Unknown | 5.110615 | 4.928432 | 1.036966 |
logger_misc.info("enter remove_empty_doi")
try:
# Check each publication dictionary
for pub in d['pub']:
# If no identifier, then we can quit here. If identifier, then keep going.
if 'identifier' in pub:
if 'id' in pub['identifier'][0]:
... | def rm_empty_doi(d) | If an "identifier" dictionary has no doi ID, then it has no use. Delete it.
:param dict d: Metadata
:return dict d: Metadata | 4.997453 | 4.754004 | 1.051209 |
files = list_files(extension, path)
for file in files:
if file.endswith(extension):
os.remove(os.path.join(path, file))
return | def rm_files(path, extension) | Remove all files in the given directory with the given extension
:param str path: Directory
:param str extension: File type to remove
:return none: | 2.579295 | 3.454805 | 0.746582 |
if isinstance(x, dict):
if "values" in x:
del x["values"]
else:
for k, v in x.items():
if isinstance(v, dict):
rm_values_fields(v)
elif isinstance(v, list):
rm_values_fields(v)
elif isinstance(x,... | def rm_values_fields(x) | (Recursive) Remove all "values" fields from the metadata
:param any x: Any data type
:return dict x: Metadata (values removed) | 1.66639 | 1.677603 | 0.993316 |
try:
for k, v in d["columns"].items():
d["columns"][k] = rm_keys_from_dict(v, ["missingValue"])
except Exception:
# If we get a KeyError or some other error, it's not a big deal. Keep going.
pass
return d | def rm_missing_values_table(d) | Loop for each table column and remove the missingValue key & data
:param dict d: Metadata (table)
:return dict d: Metadata (table) | 5.522294 | 5.04899 | 1.093742 |
# Loop for each key given
for key in keys:
# Is the key in the dictionary?
if key in d:
try:
d.pop(key, None)
except KeyError:
# Not concerned with an error. Keep going.
pass
return d | def rm_keys_from_dict(d, keys) | Given a dictionary and a key list, remove any data in the dictionary with the given keys.
:param dict d: Metadata
:param list keys: Keys to be removed
:return dict d: Metadata | 5.417377 | 6.240128 | 0.868152 |
for idx, column in enumerate(values):
values[idx] = _replace_missing_values_column(column, mv)
return values | def _replace_missing_values_table(values, mv) | Receive all table column values as a list of lists. Loop for each column of values
:param list values: Metadata (columns)
:param any mv: Missing value currently in use
:return list: Metadata (columns) | 3.01792 | 3.092333 | 0.975936 |
for idx, v in enumerate(values):
try:
if v in EMPTY or v == mv:
values[idx] = "nan"
elif math.isnan(float(v)):
values[idx] = "nan"
else:
values[idx] = v
except (TypeError, ValueError):
values[idx] = ... | def _replace_missing_values_column(values, mv) | Replace missing values in the values list where applicable
:param list values: Metadata (column values)
:return list values: Metadata (column values) | 2.819566 | 3.093566 | 0.911429 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.