content
stringlengths 39
14.9k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
import torch
def map2central(cell, coordinates, pbc):
"""Map atoms outside the unit cell into the cell using PBC.
Arguments:
cell (:class:`torch.Tensor`): tensor of shape (3, 3) of the three
vectors defining unit cell:
.. code-block:: python
tensor([[x1, y1, z1],
[x2, y2, z2],
[x3, y3, z3]])
coordinates (:class:`torch.Tensor`): Tensor of shape
``(molecules, atoms, 3)``.
pbc (:class:`torch.Tensor`): boolean vector of size 3 storing
if pbc is enabled for that direction.
Returns:
:class:`torch.Tensor`: coordinates of atoms mapped back to unit cell.
"""
# Step 1: convert coordinates from standard cartesian coordinate to unit
# cell coordinates
inv_cell = torch.inverse(cell)
coordinates_cell = torch.matmul(coordinates, inv_cell)
# Step 2: wrap cell coordinates into [0, 1)
coordinates_cell -= coordinates_cell.floor() * pbc
# Step 3: convert from cell coordinates back to standard cartesian
# coordinate
return torch.matmul(coordinates_cell, cell)
|
5ab75804efa182516ec4e99ec6707e65f205b842
| 698,553 |
def get_left_strip(chonk):
"""
Compute the left vertical strip of a 2D list.
"""
return [chonk[_i][0] for _i in range(len(chonk))]
|
dfc57a0776e5ab97a808a75170634fa6a072d9d3
| 698,554 |
def _shift_num_right_by(num: int, digits: int) -> int:
"""Shift a number to the right by discarding some digits
We actually use string conversion here since division can provide
wrong results due to precision errors for very big numbers. e.g.:
6150000000000000000000000000000000000000000000000 // 1e27
6.149999999999999e+21 <--- wrong
"""
return int(str(num)[:-digits])
|
ba459cb419ef19ac2884d8299d4f1a9213832fa3
| 698,556 |
def handle_extends(tail, line_index):
"""Handles an extends line in a snippet."""
if tail:
return 'extends', ([p.strip() for p in tail.split(',')],)
else:
return 'error', ("'extends' without file types", line_index)
|
3b20cc5719d123e36db954c5ffc4537df64f268a
| 698,560 |
import torch
def repackage_hidden(h):
"""Wraps hidden states in new Tensors,
to detach them from their history."""
if isinstance(h, torch.Tensor):
return h.detach()
else:
return tuple(repackage_hidden(v) for v in h)
|
b435d7537e4418d3877db55077285d35a24e46b3
| 698,563 |
def minus(evaluator, ast, state):
"""Evaluates "-expr"."""
return -evaluator.eval_ast(ast["expr"], state)
|
bf945c368e84d3badd7a90bfce74cb3c89b6890a
| 698,564 |
def angle_M(M_r: float, n: float, t_r: float, t: float) -> float:
"""
M = Mr + n * (t - tr)
:param M_r: mean anomaly at tr
:type M_r: float
:param n: mean movement
:type n: float
:param t_r: reference time
:type t_r: float
:param t: time
:type t: float
:return: mean anomaly at t
:rtype: float
"""
return M_r + n * (t - t_r)
|
c99e5dacffea44fa7fadfaebaf6ce734eea81e16
| 698,565 |
import re
def is_transaction_expired_exception(e):
"""
Checks if exception occurred for an expired transaction
:type e: :py:class:`botocore.exceptions.ClientError`
:param e: The ClientError caught.
:rtype: bool
:return: True if the exception denote that a transaction has expired. False otherwise.
"""
is_invalid_session = e.response['Error']['Code'] == 'InvalidSessionException'
if "Message" in e.response["Error"]:
return is_invalid_session and re.search("Transaction .* has expired", e.response["Error"]["Message"])
return False
|
c836521a7137b61ad8443157824ca5da59de65e3
| 698,567 |
def parse_int(sin):
"""A version of int but fail-safe"""
return int(sin) if sin.isdigit() else -99
|
204cbcb01b6df1bbdd09af318fdfe90feb5fe68f
| 698,570 |
def check_read(read):
"""
a callback function for pysam.count function, returns true if the read should be included in the count
:param read: the read to check
:return: True of False whether the read should be included in the count
"""
return read.is_proper_pair
|
1bc80c9156bdeb0bc34b2724da8d0147a435b3dd
| 698,571 |
def createAggregatedTestCase(doc, parent_node, testclass_name):
"""
Create a node which represents a single aggregated testcase.
Aggregated testcase sums the result of all test cases that
belong to the speified classname. If one of these test cases
fails, the aggregated test case's status is set to failed.
"""
testcase = doc.createElement('testcase')
# This holds the complete test id.
testcase.setAttribute('classname', testclass_name)
# classname holds the whole test id already, so the 'name'
# attribute holds just a persistent label, common to all
# test cases. Let's call it aggregated, to indicate that
# the result represents multiple steps in lettuce scenario.
testcase.setAttribute('name', 'aggregated')
testcase.setAttribute('time', "0")
return testcase
|
a6cfaa405464a09e76d3e4840f99a3d5ff9a87b1
| 698,572 |
def enable_cdc(client):
"""Utility method to enable Change Data Capture for Contact change events in an org.
Args:
client (:py:class:`simple_salesforce.Salesforce`): Salesforce client
Returns:
(:obj:`str`) Event channel Id
"""
payload = {
"FullName": "ChangeEvents_ContactChangeEvent",
"Metadata": {
"eventChannel": "ChangeEvents",
"selectedEntity": "ContactChangeEvent"
}
}
result = client.restful('tooling/sobjects/PlatformEventChannelMember', method='POST', json=payload)
assert True == result['success']
return result['id']
|
2c7bc57f33e83029caea542db9daeaa81f6661cc
| 698,579 |
import yaml
def load_config_from_yaml(filename='fsm.yaml'):
"""
Returns the current fsm configuration dictionary, loaded from file.
:return: a dict.
"""
yaml_file = open(filename, 'r')
yaml_dict = yaml.safe_load(yaml_file.read())
return yaml_dict
|
e1ff03a8fcc2a77288d8971cd76fd17e7a30f65a
| 698,584 |
import torch
def atanh(x, eps=1e-2):
"""
The inverse hyperbolic tangent function, missing in pytorch.
:param x: a tensor or a Variable
:param eps: used to enhance numeric stability
:return: :math:`\\tanh^{-1}{x}`, of the same type as ``x``
"""
x = x * (1 - eps)
return 0.5 * torch.log((1.0 + x) / (1.0 - x))
|
27b0e8de0eeceb44d739f686ca22d616bc8f75de
| 698,585 |
def index_names_from_symbol(symbol):
"""
Return the domain names of a GAMS symbol,
except ['*'] cases are replaced by the name of the symbol
and ['*',..,'*'] cases are replaced with ['index_0',..'index_n']
"""
index_names = list(symbol.domains_as_strings)
if index_names == ["*"]:
return [symbol.name]
if index_names.count("*") > 1:
for i, name in enumerate(index_names):
if name == "*":
index_names[i] = f"index_{i}"
return index_names
|
dc4acc473eaf13d18f553abd722384bf4fe3115a
| 698,586 |
from pathlib import Path
import json
def read_description(filename):
"""Read the description from .zenodo.json file."""
with Path(filename).open() as file:
info = json.load(file)
return info['description']
|
0568aa956f3b0c3f5be4ba75ea8e6b98e08c469e
| 698,588 |
import importlib
def get_func(func_name):
"""Helper to return a function object by name. func_name must identify a
function in this module or the path to a function relative to the base
'modeling' module.
"""
if func_name == '':
return None
try:
parts = func_name.split('.')
# Refers to a function in this module
if len(parts) == 1:
return globals()[parts[0]]
# Otherwise, assume we're referencing a module under modeling
module_name = 'models.' + '.'.join(parts[:-1])
module = importlib.import_module(module_name)
return getattr(module, parts[-1])
except Exception:
print('Failed to find function: %s', func_name)
raise
|
da95b0933ce60cd55049c13ef198eba4d9d0b0ee
| 698,600 |
def MTFfreq(MTFpos, MTF, modulation=0.2):
""" Return the frequency for the requested modulation height. """
mtf_freq = 0
for f in range(len(MTFpos)):
if MTF[f] < modulation:
if f > 0:
# Linear interpolation:
x0 = MTFpos[f-1]
x1 = MTFpos[f]
y0 = MTF[f-1]
y1 = MTF[f]
m = (y1-y0)/(x1-x0)
n = y0 - m*x0
mtf_freq = (modulation-n)/m
else:
mtf_freq = MTFpos[f]
break
return mtf_freq
|
fadec075afaffa405ef4135f714be6e2bceb71c7
| 698,603 |
def allStudentsMajoringIn(thisMajor,listOfStudents):
"""
return a list of the students with the major, thisMajor
>>> majorToLNames("MATH",[Student("MARY","KAY","MATH"), Student("FRED","CRUZ","HISTORY"), Student("CHRIS","GAUCHO","UNDEC")])
[Student(fName='MARY',lName='KAY',major="MATH")]
>>>
"""
answerList = []
for student in listOfStudents:
# step through every item in listOfStudents
# when you find a match, return that students's major
if student.major == thisMajor:
answerList.append(student)
# if you got all the way through the loop and didn't find
# the name, return False
return answerList
|
ad32dfd68b2daa4aa3e46ff8563e4575bd940336
| 698,606 |
def bounding_box(ptlist):
"""
Returns the bounding box for the list of points, in the form
(x1, y1, x2, y2), where (x1, y1) is the top left of the box and
(x2, y2) is the bottom right of the box.
"""
xs = [pt[0] for pt in ptlist]
ys = [pt[1] for pt in ptlist]
return (min(xs), max(ys), max(xs), min(ys))
|
cd27b3e5783ee7dd8c5960389079b32768516e4d
| 698,611 |
def is_good(filename: str, force: bool = False) -> bool:
"""
Verify whether a file is good or not, i.e., it does not need
any shape or illumination modification. By default a file is
good if it is a pdf.
Parameters
----------
filename
The file name.
force
Wether to force the goodness of a file.
Returns
-------
good
True whether the file is a pdf or its goodnes is forced,
False otherwise.
"""
return filename.endswith('.pdf') or force
|
acaee589288db3eb48bd7bc89dc21c0a7d75822c
| 698,613 |
import re
def all_whitespace(string):
""" all_whitespace(string : str) -> bool
>>> all_whitespace(' ')
True
Returns True if a string has only whitespace.
"""
return re.search('^[ \t]*(\r|\n|$)', string)
|
766b92da0b6e91fbcd05eed408cb5651cdf42b4e
| 698,622 |
import copy
import uuid
import collections
def deep_copy(item_original):
"""Return a recursive deep-copy of item where each copy has a new ID."""
item = copy.copy(item_original)
item._id = uuid.uuid4().hex
if hasattr(item, '_children') and len(item._children) > 0:
children_new = collections.OrderedDict()
for subitem_original in item._children.values():
subitem = deep_copy(subitem_original)
subitem._parent = item
children_new[subitem.get_name()] = subitem
item._children = children_new
return item
|
83c8ee5dd620e30a518391752905ba1966d27aa4
| 698,623 |
def string_empty(string):
"""Return True if the input string is None or whitespace."""
return (string is None) or not (string and string.strip())
|
fddb1e639a57b29674ce6d0a101e875272731d77
| 698,628 |
import imghdr
def detect_image_type(filename):
"""
获取图像文件类型
:param filename:
:return: jpge|png|gif|tiff等。失败返回None
"""
return imghdr.what(filename)
|
a4701aa60927e730899ed8036d6f2d875aa0524a
| 698,631 |
from typing import Dict
def _results_data_row(row: Dict[str, str]):
"""
Transform the keys of each CSV row. If the CSV headers change,
this will make a single place to fix it.
"""
return {
"k": row["Key"],
"v": row["Content"],
}
|
97dc7f9842d7e6a564cbe66fd93e3dbaeca08517
| 698,635 |
from typing import List
def _split_inputs(inputs: str, named_groups: dict) -> List[str]:
"""
Identify and split inputs for torch operations.
This assumes that no quotes, apostrophes, or braces show up in the operation string.
Currently, items in lists that are not within functions will be broken up into separate inputs.
:param inputs: String of inputs to a torch operation.
:param named_groups: Dictionary of names of grouped inputs. If the name of a group shows up in the inputs list,
Map it to the group in this dictionary and treat each member of the group as a separate input.
:return: List of strings representing each input to the operation.
"""
replaced_str = inputs
parentheses_depth = 0
bracket_depth = 0
# Step through each character in the line and see if it is a comma which separates inputs.
# Keep counters for parentheses, brackets, and braces to only identify commas outside of any such structures.
for idx, inp in enumerate(inputs):
curr_char = inp
# Currently, individual elements in lists are each treated as a separate parameter. See if we need to keep the
# lists intact as well (check bracket depth as well)
if curr_char == ',' and parentheses_depth == 0:
# Replace comma with '$' for easy splitting later. Assumes '$' does not normally show up in the code.
replaced_str = replaced_str[:idx] + '$' + replaced_str[idx+1:]
elif curr_char == '(':
parentheses_depth += 1
elif curr_char == '[':
bracket_depth += 1
elif curr_char == ')':
parentheses_depth -= 1
elif curr_char == ']':
bracket_depth -= 1
# We should never have seen more right parentheses, brackets, or braces than left ones.
assert parentheses_depth >= 0 and bracket_depth >= 0
# Split the string using the '$' characters replaced earlier.
# Also remove leading and trailing list brackets
split = replaced_str.split('$')
split = [s.strip('[] ') for s in split]
# Items in split may be a named group. If so, replace the item with each item in the group.
# Call split inputs recursively on the group in case it contains named groups within as well.
split_inputs = []
for inp in split:
if inp in named_groups.keys():
group_items = _split_inputs(named_groups[inp], named_groups)
for item in group_items:
split_inputs.append(item)
else:
split_inputs.append(inp)
return split_inputs
|
5edc3c53fb9b7a19557504335eb04eb15dd3c932
| 698,639 |
def jsdate(d):
"""formats a python date into a js Date() constructor.
"""
try:
return "new Date({0},{1},{2})".format(d.year, d.month - 1, d.day)
except AttributeError:
return 'undefined'
|
0c8331f928cf26e4cac7663dd6619c62cfff0fae
| 698,644 |
import random
def mutate(chromosome):
"""
Pick a random bit to mutate by XOR and shifting the selected bit. This
ensures diversity in the population.
"""
altered_bit_position = random.randint(0, 31)
mutation = chromosome ^ (1 << altered_bit_position)
return mutation
|
ff93fb19d7d83c558172d005fbd140284e2b16c2
| 698,646 |
def mileage_format(value):
""" Custom formatting for mileage. """
return "{:,} miles".format(value)
|
056f5fbf5d291ac892bd8f2c16cda16937f758da
| 698,648 |
def _list(key: str, vals: dict) -> list:
"""Get a key from a dictionary of values and ensure it is a list."""
result = vals.get(key, [])
if not isinstance(result, list):
result = [result]
return result
|
cf8a5da580dc4d95f83f18a92f82f646be5c4cb3
| 698,649 |
def contrast_color(hex_color):
"""
Util function to know if it's best to use a white or a black color on the foreground given in parameter
:param str hex_color: the foreground color to analyse
:return: A black or a white color
"""
r1 = int(hex_color[1:3], 16)
g1 = int(hex_color[3:5], 16)
b1 = int(hex_color[5:7], 16)
# Black RGB
black_color = "#000000"
r2_black_color = int(black_color[1:3], 16)
g2_black_color = int(black_color[3:5], 16)
b2_black_color = int(black_color[5:7], 16)
# Calc contrast ratio
l1 = 0.2126 * pow(r1 / 255, 2.2) + 0.7152 * pow(g1 / 255, 2.2) + 0.0722 * pow(b1 / 255, 2.2)
l2 = 0.2126 * pow(r2_black_color / 255, 2.2) + 0.7152 * pow(g2_black_color / 255, 2.2) + 0.0722 * pow(
b2_black_color / 255, 2.2)
if l1 > l2:
contrast_ratio = int((l1 + 0.05) / (l2 + 0.05))
else:
contrast_ratio = int((l2 + 0.05) / (l1 + 0.05))
# If contrast is more than 5, return black color
if contrast_ratio > 5:
return '#000000'
# if not, return white color
return '#FFFFFF'
|
470f713af48673d7b9fb8aa3bb30f7e1498da9b5
| 698,651 |
import itertools
def get_common_base(files):
"""Find the common parent base path for a list of files.
For example, ``["/usr/src/app", "/usr/src/tests", "/usr/src/app2"]``
would return ``"/usr/src"``.
:param files: files to scan.
:type files: ``iterable``
:return: Common parent path.
:rtype: str
"""
def allnamesequal(name):
"""Return if all names in an iterable are equal."""
return all(n == name[0] for n in name[1:])
level_slices = zip(*[f.split("/") for f in files])
tw = itertools.takewhile(allnamesequal, level_slices)
return "/".join(x[0] for x in tw)
|
bb6c7fde6a9e2f9c620febf52047b547cf24e602
| 698,655 |
def comment(src_line: str) -> list:
"""Returns an empty list."""
return []
|
c7e584811b899ae4a17ba4c9fd0debbc97e0a5cc
| 698,657 |
def hidden_loc(obj, name):
"""
Generate the location of a hidden attribute.
Importantly deals with attributes beginning with an underscore.
"""
return ("_" + obj.__class__.__name__ + "__" + name).replace("___", "__")
|
5a8c3d066cb96cf282c1b8814ac1302bd68111c0
| 698,660 |
def find_neighbors_hexagonal_grid(map_coordinates: list, current_position: tuple) -> list:
"""Finds the set of adjacent positions of coordinates 'current_position' in a hexagonal grid.
Args:
map_coordinates (list): List of map coordinates.
current_position (tuple): Current position of the hexagonal grid whose neighbors we want to find.
Returns:
neighbors (list): List of neighbors from the current position in the hexagonal grid map.
"""
x = current_position[0]
y = current_position[1]
candidates = [(x - 2, y), (x - 1, y + 1), (x + 1, y + 1), (x + 2, y), (x + 1, y - 1), (x - 1, y - 1)]
neighbors = [
neighbor
for neighbor in candidates
if neighbor[0] >= 0 and neighbor[1] >= 0 and (neighbor[0], neighbor[1]) in map_coordinates
]
return neighbors
|
2a6071d59a69b828eb252504508fa3f706969e1b
| 698,662 |
from pathlib import Path
def openW2wFile(path, mode):
"""
Helper function to read/write all files with same encoding and line endings
:param str|Path path: full path to file
:param str mode: open mode: 'r' - read, 'w' - write, 'a' - append
:return TextIO:
"""
if isinstance(path, Path):
path = str(path)
# Windows line endings so that less advanced people can edit files, created on Unix in Windows Notepad
return open(path, mode, encoding='utf-8', newline='\r\n')
|
6e42a26d2262ed10d15e19292e7b32fffd14aeb8
| 698,663 |
def ugly_numbers(n: int) -> int:
"""
Returns the nth ugly number.
>>> ugly_numbers(100)
1536
>>> ugly_numbers(0)
1
>>> ugly_numbers(20)
36
>>> ugly_numbers(-5)
1
>>> ugly_numbers(-5.5)
Traceback (most recent call last):
...
TypeError: 'float' object cannot be interpreted as an integer
"""
ugly_nums = [1]
i2, i3, i5 = 0, 0, 0
next_2 = ugly_nums[i2] * 2
next_3 = ugly_nums[i3] * 3
next_5 = ugly_nums[i5] * 5
for _ in range(1, n):
next_num = min(next_2, next_3, next_5)
ugly_nums.append(next_num)
if next_num == next_2:
i2 += 1
next_2 = ugly_nums[i2] * 2
if next_num == next_3:
i3 += 1
next_3 = ugly_nums[i3] * 3
if next_num == next_5:
i5 += 1
next_5 = ugly_nums[i5] * 5
return ugly_nums[-1]
|
69c92c8eea98b6d8d869f0725c49d6b164d24480
| 698,664 |
from typing import Iterable
def make_conda_description(summary: str, conda_channels: Iterable[str] = ()) -> str:
"""
Create a description for the Conda package from its summary and a list of channels required to install it.
The description will look like::
This is my fancy Conda package. Hope you like it 😉.
Before installing please ensure you have added the following channels: conda-forge, bioconda
.. versionadded:: 0.8.0
:param summary:
:param conda_channels:
"""
conda_description = summary
conda_channels = tuple(conda_channels)
if conda_channels:
conda_description += "\n\n\n"
conda_description += "Before installing please ensure you have added the following channels: "
conda_description += ", ".join(conda_channels)
conda_description += '\n'
return conda_description
|
b275e3bfcb67da33a4c7a34d7801a0cb4144527a
| 698,665 |
import hashlib
def sha1(text):
"""
Calculate the SHA1 fingerprint of text.
:param text: The text to fingerprint (a string).
:returns: The fingerprint of the text (a string).
"""
context = hashlib.sha1()
context.update(text.encode('utf-8'))
return context.hexdigest()
|
43473e9cc22b6cbe072170244b56b831f0cc88ee
| 698,666 |
def ifirst_is_not(l, v):
"""
Return index of first item in list which is not the specified value.
If the list is empty or if all items are the specified value, raise
a ValueError exception.
Parameters
----------
l : sequence
The list of elements to be inspected.
v : object
The value not to be matched.
Example:
--------
>>> ifirst_is_not(['a', 'b', 'c'], 'a')
1
"""
try:
return next((i for i, _ in enumerate(l) if _ is not v))
except StopIteration:
raise ValueError('There is no matching item in the list.')
|
fef5ae1a512772cf4df75a294057330280047f88
| 698,668 |
def format_date_ihme(date_in):
"""
Formats "m/d/yyy" to "yyyymmdd"
"""
try:
month, day, year = date_in.split('/')
return '%s%02i%02i' % (year, int(month), int(day))
except:
return date_in.replace('-', '')
|
166739b2245833c6dddf35fcde87433648697277
| 698,670 |
def reverse_map(dict_of_sets):
"""Reverse a map of one-to-many.
So the map::
{
'A': {'B', 'C'},
'B': {'C'},
}
becomes
{
'B': {'A'},
'C': {'A', 'B'},
}
Args:
dict_of_sets (dict[set]): A dictionary of sets, mapping
one value to many.
Returns:
dict[set]: The reversed map.
"""
result = {}
for key, values in dict_of_sets.items():
for value in values:
result.setdefault(value, set()).add(key)
return result
|
87b0679a0ebd00c3dbdcafc89fd2644b21ecbc85
| 698,671 |
import functools
def expand_args(function):
"""Expand arguments passed inside the CallContext object.
Converts internal method signature 'method(ctx)' to whatever
is appropriate to the client code.
Args:
function: Async function expecting CallContext as a last argument.
Returns:
Async function with altered signature.
"""
@functools.wraps(function)
async def expand_args_wrapper(*args):
# Valid method signatures are foo(ctx) and foo(self, ctx).
context = args[-1]
return await function(*args, *context.args, **context.kwargs)
return expand_args_wrapper
|
72e7de46684b2c02d958fad7f9ded71e653bb811
| 698,674 |
def derivative_of_binary_cross_entropy_loss_function(y_predicted, y_true):
"""
Use the derivative of the binary cross entropy (BCE) loss function.
Parameters
----------
y_predicted : ndarray
The predicted output of the model.
y_true : ndarray
The actual output value.
Returns
-------
float
The derivative of the BCE loss function.
"""
numerator = (y_predicted - y_true)
denominator = (y_predicted * (1 - y_predicted))
y = numerator / denominator
return y
|
7803c852f794ab9eae165c639bfb7a04cd0c1028
| 698,675 |
def api_failed(response, endpoint, exit_on_error=True):
"""
Check if api request failed
Can raise exception
"""
if 200 <= response.status_code < 300:
return False
if exit_on_error:
raise Exception("Status code {0} calling {1}".format(
response.status_code, endpoint))
return True
|
6a9d803444c4be09806eb6c5b588e1e04062c431
| 698,680 |
def select_field(X, cols=None, single_dimension=False):
"""
Select columns from a pandas DataFrame
Args:
X (pandas DataFrame): input data
cols (array-like): list of columns to select
single_dimension (bool): reduce data to
one dimension if only one column
is requested
Returns:
X (numpy array)
"""
if cols is None:
return X.values
if len(cols) > 1:
return X[cols].values
if len(cols) == 1:
if single_dimension:
return X[cols[0]].values
else:
return X[cols].values
|
4f80af3621af5e0c622f2c880e88d95a6e93034e
| 698,681 |
def get_pathless_file_size(data_file):
"""
Takes an open file-like object, gets its end location (in bytes),
and returns it as a measure of the file size.
Traditionally, one would use a systems-call to get the size
of a file (using the `os` module). But `TemporaryFileWrapper`s
do not feature a location in the filesystem, and so cannot be
tested with `os` methods, as they require access to a filepath,
or a file-like object that supports a path, in order to work.
This function seeks the end of a file-like object, records
the location, and then seeks back to the beginning so that
the file behaves as if it was opened for the first time.
This way you can get a file's size before reading it.
(Note how we aren't using a `with` block, which would close
the file after use. So this function leaves the file open,
as an implicit non-effect. Closing is problematic for
TemporaryFileWrappers which wouldn't be operable again)
:param data_file:
:return size:
"""
if not data_file.closed:
data_file.seek(0, 2)
size = data_file.tell()
print(size)
data_file.seek(0, 0)
return size
else:
return 0
|
df1edfa6cb7b97c6abbdb2252b7dd8d505931768
| 698,682 |
from functools import reduce
import operator
def factorial(n):
"""Calculate n factorial"""
return reduce(operator.mul, range(2, n+1), 1)
|
a58e0aad4e3a8baf06bbd1a6929a3aab2ab4e66e
| 698,685 |
from typing import Optional
from typing import Tuple
from typing import Match
import re
def is_conversion_err(error: Exception) -> Optional[Tuple[str, int]]:
"""Check if error is caused by generic conversion error.
Return a tuple of the converter type and parameter name if True,
otherwise return None.
"""
pattern: str = r'Converting to "(.+?)" failed for parameter "(.+?)"\.'
match: Optional[Match] = re.search(pattern, str(error))
if match:
return (match.group(1), match.group(2))
return None
|
2e53420bb8a5715c75ee30a549453f40202d4ff7
| 698,687 |
def txt_file_to_list(genomes_txt):
"""
Read ids from a one column file to a list
Args:
genomes_txt:str: Path to file with the ids.
"""
with open(genomes_txt, 'r') as fin:
genomes_list = [line.strip() for line in fin]
return genomes_list
|
f79874dfbcb6a2a71be87b180e80513d480fcc8e
| 698,688 |
def dense_rank(x, na_option = "keep"):
"""Return the dense rank.
This method of ranking returns values ranging from 1 to the number of unique entries.
Ties are all given the same ranking.
Example:
>>> dense_rank(pd.Series([1,3,3,5]))
0 1.0
1 2.0
2 2.0
3 3.0
dtype: float64
"""
return x.rank(method = "dense", na_option = na_option)
|
53bd64e112741f20c0e62f44ba7f5bcf8cdb2f83
| 698,692 |
from unittest.mock import Mock
def mock_channel_file(
offered_by, channel_id, playlist_id, create_user_list=False, user_list_title=None
):
"""Mock video channel github file"""
content = f"""---
offered_by: {offered_by}
channel_id: {channel_id}
playlists:
- id: {playlist_id}
{"create_user_list: true" if create_user_list else "" }
{ "user_list_title: " + user_list_title if user_list_title else "" }
"""
return Mock(decoded_content=content)
|
3042a7fc6f0fb622db8bf035a408672ddd6408ab
| 698,695 |
from functools import wraps
def run_only_once(resolve_func):
"""
Make sure middleware is run only once,
this is done by setting a flag in the `context` of `ResolverInfo`
Example:
class AuthenticationMiddleware:
@run_only_once
def resolve(self, next, root, info, *args, **kwargs):
pass
"""
@wraps(resolve_func)
def wrapper(self, nextFn, root, info, *args, **kwargs):
has_context = info.context is not None
decorator_name = "__{0}_run__".format(self.__class__.__name__)
if has_context:
if isinstance(info.context, dict) and not info.context.get(
decorator_name, False
):
info.context[decorator_name] = True
return resolve_func(self, nextFn, root, info, *args, **kwargs)
elif not isinstance(info.context, dict) and not getattr(
info.context, decorator_name, False
):
# Graphene: it could be a Context or WSGIRequest object
setattr(info.context, decorator_name, True)
return resolve_func(self, nextFn, root, info, *args, **kwargs)
# No context, run_only_once will not work
return nextFn(root, info, *args, **kwargs)
return wrapper
|
9742318ca44ec92d7826d561968c87cea62db1bf
| 698,696 |
import re
def get_input_size(filename):
"""Gets input size and # of channels."""
with open(filename) as input_file:
for line in input_file:
match = re.match(r'^input.*\(None, (\d*), (\d*), (\d*)\)', line)
if match is not None:
x = int(match.group(1))
c = int(match.group(3))
return x,c
|
3e753e5ac74babcbe4f48830cfde7a3002f7cc37
| 698,698 |
def indexOfSmallestInt(listOfInts):
"""
return index of smallest element of non-empty list of ints, or False otherwise
That is, return False if parameter is an empty list, or not a list
parameter is not a list consisting only of ints
By "smallest", we mean a value that is no larger than any other
value in the l There may be more than one instance of that value.
Example: in [7,3,3,7],3 is smallest
By "index", we mean the subscript that will select that item of the list when placed in []
Since there can be more than one smallest, we'll return the index of the first such value in those cases,
i.e. the one with the lowest index.
>>> indexOfSmallestInt([])
False
>>> indexOfSmallestInt('foo')
False
>>> indexOfSmallestInt([3,5,4.5,6])
False
>>> indexOfSmallestInt([40])
0
>>> indexOfSmallestInt([-90,40,70,80,20])
0
>>> indexOfSmallestInt([10,30,-50,20,-50])
2
>>>
"""
if type(listOfInts)!=list or listOfInts==[]: # Return False if not a list or is empty
return False
currentMinIndex = 0
for i in range(0,len(listOfInts)):
if type(listOfInts[i])!=int:
return False # Return False if not all elements are ints
if listOfInts[i] < listOfInts[currentMinIndex]:
currentMinIndex = i
return currentMinIndex
|
63afb453b13ad4da75c83e9a7f6b409f58739d7e
| 698,700 |
def field_with_classes(field, *classes):
"""
Adds the specified classes to the HTML element produced for the field.
"""
return field.as_widget(attrs = { 'class': ' '.join(classes) })
|
2b9929b2629fafaafbe1d2537afc0a9a601eed53
| 698,701 |
import tkinter as Tkinter
import tkinter.filedialog as tkFileDialog
def directory_from_gui(
initialdir='.',
title='Choose directory'): # pragma: no cover
"""
Opens dialog to one select directory
Parameters
----------
initialdir : str, optional
Initial directory, in which opens GUI (default: '.')
title : str, optional
Title of GUI (default: 'Choose directory')
Returns
-------
str
Selected directory
Examples
--------
.. code-block:: python
if not idir:
idir = directory_from_gui()
if not idir:
raise ValueError('Error: no directory given.')
"""
root = Tkinter.Tk()
root.withdraw() # hide root window, i.e. white square
# always on top
# focus on (hidden) window so that child is on top
root.tk.call('wm', 'attributes', '.', '-topmost', 1)
direcs = tkFileDialog.askdirectory(
parent=root, title=title, initialdir=initialdir)
root.destroy()
return direcs
|
e0b43a044c0e05815023de2275cc0ff1ffb01d8e
| 698,702 |
def create_model_name(src):
"""Generate a name for a source object given its spatial/spectral
properties.
Parameters
----------
src : `~fermipy.roi_model.Source`
A source object.
Returns
-------
name : str
A source name.
"""
o = ''
spatial_type = src['SpatialModel'].lower()
o += spatial_type
if spatial_type == 'gaussian':
o += '_s%04.2f' % src['SpatialWidth']
if src['SpectrumType'] == 'PowerLaw':
o += '_powerlaw_%04.2f' % float(src.spectral_pars['Index']['value'])
else:
o += '_%s' % (src['SpectrumType'].lower())
return o
|
d305dd26bc6017f3fce5db2a5267fa6e74df3bc6
| 698,705 |
def csv_to_list(value):
"""
Converts the given value to a list of strings, spliting by ',' and removing empty strings.
:param str value: the value to split to strings.
:return: a list of strings.
:rtype: List[str]
"""
return list(filter(None, [x.strip() for x in value.split(',')]))
|
dbfb90dccf8d48a46f528ca02e958306e8dcc266
| 698,707 |
def swapaxes(dat, ax1, ax2):
"""Swap axes of a Data object.
This method swaps two axes of a Data object by swapping the
appropriate ``.data``, ``.names``, ``.units``, and ``.axes``.
Parameters
----------
dat : Data
ax1, ax2 : int
the indices of the axes to swap
Returns
-------
dat : Data
a copy of ``dat`` with the appropriate axes swapped.
Examples
--------
>>> dat.names
['time', 'channels']
>>> dat = swapaxes(dat, 0, 1)
>>> dat.names
['channels', 'time']
See Also
--------
numpy.swapaxes
"""
data = dat.data.swapaxes(ax1, ax2)
axes = dat.axes[:]
axes[ax1], axes[ax2] = axes[ax2], axes[ax1]
units = dat.units[:]
units[ax1], units[ax2] = units[ax2], units[ax1]
names = dat.names[:]
names[ax1], names[ax2] = names[ax2], names[ax1]
return dat.copy(data=data, axes=axes, units=units, names=names)
|
576ec10826c3ab92465052edcadf38cf04952c02
| 698,714 |
import re
def is_url(value):
"""Return whether or not given value is a valid URL."""
regex = re.compile(
r"^"
# startchar <
r"<?"
# protocol identifier
r"(?:(?:https?|ftp)://)"
r"(?:"
r"(localhost)"
r"|"
# host name
r"(?:(?:[a-z\u00a1-\uffff0-9]-?)*[a-z\u00a1-\uffff0-9]+)"
# domain name
r"(?:\.(?:[a-z\u00a1-\uffff0-9]-?)*[a-z\u00a1-\uffff0-9]+)*"
# TLD identifier
r"(?:\.(?:[a-z\u00a1-\uffff]{2,}))"
r")"
# port number
r"(?::\d{2,5})?"
# resource path
r"(?:/\S*)?"
# query string
r"(?:\?\S*)?"
# endchar >
r">?"
r"$",
re.UNICODE | re.IGNORECASE
)
return regex.match(value)
|
3a50e541a9e62156a89693d15d248080abb3718f
| 698,716 |
def remote_call(method):
"""Decorator to set a method as callable remotely (remote call)."""
method.remote_call = True
return method
|
ab276cbdb190185c7e46c5205df25f022a56a097
| 698,719 |
from pathlib import Path
def node(ph5, path, class_name):
"""
Get the node handle of a given path and class name
:param ph5: an open ph5 object
:type ph5: ph5 object
:param path: path to node
:type path: string
:param class_name: name of class to get
:type class_name: string
"""
handle = None
path = Path(path)
handle = ph5.get_node(str(path.parent),
name=path.name,
classname=class_name)
return handle
|
2a8090952fdec3dda7490844990f41c8e154c3af
| 698,721 |
def txfDate(date):
"""Returns a date string in the TXF format, which is MM/DD/YYYY."""
return date.strftime('%m/%d/%Y')
|
fd1f19b4080447379ec3ec57be0f2af047099673
| 698,726 |
from typing import Union
def get_json_url(year: Union[str, int], kind: str = "photos") -> str:
"""Returns url for the json data from news-navigator for given `year` and `kind`"""
return f"https://news-navigator.labs.loc.gov/prepackaged/{year}_{kind}.json"
|
0c7650f667cb1fceebbd73e7a6eaf00145061d38
| 698,729 |
def vdecomp(v, m=None, minlen=None, maxlen=None):
"""
Decompose a vector into components. an nD stack of m-element vectors will return a tuple with up to m elements,
each of which will be an nD stack of scalars
:param v: nD stack of m-element vectors, a numpy (n+1)D array with shape
(n_stack0,n_stack1,...,n_stackn-2,m,n_stackn-1)
:param minlen: If passed, this will pad out the returned vector components with zero scalars
such that the returned tuple has minlen components. We do zero scalars rather than zero arrays
of the same size as the other components to save memory, since a scalar is compatible by
broadcasting with an array of any size.
:param maxlen: If passed, this will restrict the returned vector components to the given
size, even if the input vector has more components.
:param m: If passed, treat the input as if it were an nD stack of m-element vectors. If the actual
stack has more components, don't return them. If it has less, return scalar zeros for the
missing components
:return: A tuple. Each element is a vector component. Vector components pulled from the vector will be
an nD stack of scalars, a numpy nD array with shape (n_stack0,n_stack1,...,n_stackn-2,n_stackn-1).
Vector components which are made up will be scalar zeros.
Note: If you pass maxlen<minlen, the result is still well-defined, since the maxlen is used first,
then the minlen. If you pass a vector with m=4, a minlen of 7, and a maxlen of 2, you will get
a result with the first two components of the vector, followed by 5 zeros. I'm not sure if this
is useful, but there it is.
Example:
v=np.zeros((24,3,50)) #Suitable for holding multiple trajectories
#OR
v0=np.zeros((3,50)) #Initial conditions for 50 trajectories
t=np.arange(24) #Time steps
v=rk4(x0=v0,t=t) #Numerically integrate multiple trajectories. Result shape will be (t.size,)+v0.shape,
#IE (24,3,50)
x,y,z=vcomp(v) #after this, x, y, and z are each numpy arrays of shape (24,50)
"""
if maxlen is None and m is not None:
maxlen = m
if minlen is None and m is not None:
minlen = m
ndStack = len(v.shape) > 2
efflen = v.shape[-2 if ndStack else 0]
if maxlen is not None and maxlen < efflen:
efflen = maxlen
result = tuple([v[..., i, :] if ndStack else v[i, ...] for i in range(efflen)])
if minlen is not None and minlen > efflen:
result = result + (0,) * (minlen - efflen)
return result
|
cbc846be6a07082711e5c9faa191181c8cdc75f8
| 698,736 |
def get_max_table_size(final_tables):
"""
Compute the maximum number of elements that appear in one of the table generated inside the main process.
Parameters
----------
final_tables : list
list of the tables generated inside the loop for each bucket.
Returns:
--------
max_table_size : int
the number of elements inside the largest table (i.e., number of row multiplied by the number of columns).
"""
# Variable initialization
max_table_size = 0
for table in final_tables:
max_table_size = max(max_table_size,len(table[0])*len(table))
return max_table_size
|
a562d6f944a03785034028e8b2e83bdb19a8d9aa
| 698,740 |
import itertools
def next_bigger(n: int) -> int:
"""
A function that takes a positive integer number
and returns the next bigger number formed by the same digits.
If no bigger number can be composed using those digits, return -1
"""
numbers = sorted(set(sorted(int(''.join(i)) for i in itertools.permutations(str(n)))))
if n == numbers[-1]:
return -1
else:
return numbers[numbers.index(n) + 1]
|
8800040f3e88054bcacdb432131f8a9e0a872277
| 698,741 |
def get_mac_addr_from_datapath(datapath):
"""
Return the MAC address from the datapath ID.
According to OpenFlow switch specification, the lower 48 bits of the datapath
ID contains the MAC address.
"""
mac_addr_int = datapath.id & 0x0000ffffffffffff
mac_addr = format(mac_addr_int, '02x')
return ':'.join(mac_addr[i:i+2] for i in range(0, 12, 2))
|
539c0b0a92f3eead947aed65ed62a1e630dcb30f
| 698,745 |
def create_empty(val=0x00):
"""Create an empty Userdata object.
val: value to fill the empty user data fields with (default is 0x00)
"""
user_data_dict = {}
for index in range(1, 15):
key = "d{}".format(index)
user_data_dict.update({key: val})
return user_data_dict
|
55e614059940b7eda5a0684dd105a60dbc7f1549
| 698,746 |
import re
def remove_tags(text):
"""
remove html style tags from some text
"""
cleaned = re.sub('<[^>]+>', '', text)
return re.sub('\s+',' ', cleaned).strip()
|
5bbce34ca179f871eca6306f7fbe50b5cc1ee893
| 698,747 |
def get_note_type(syllables, song_db) -> list:
"""
Function to determine the category of the syllable
Parameters
----------
syllables : str
song_db : db
Returns
-------
type_str : list
"""
type_str = []
for syllable in syllables:
if syllable in song_db.motif:
type_str.append('M') # motif
elif syllable in song_db.calls:
type_str.append('C') # call
elif syllable in song_db.introNotes:
type_str.append('I') # intro notes
else:
type_str.append(None) # intro notes
return type_str
|
621448603581a56af22ec9c559f9854c62073318
| 698,749 |
def get_plain_text(values, strip=True):
"""Get the first value in a list of values that we expect to be plain-text.
If it is a dict, then return the value of "value".
:param list values: a list of values
:param boolean strip: true if we should strip the plaintext value
:return: a string or None
"""
if values:
v = values[0]
if isinstance(v, dict):
v = v.get('value', '')
if strip:
v = v.strip()
return v
|
3c0937d1faefda4ba8649005e29c9961afbadc0a
| 698,751 |
def validate_request(request):
"""
Make sure the request is from Twilio and is valid.
Ref: https://www.twilio.com/docs/security#validating-requests
"""
# Forgot where this token if from. Different from above.
# From: https://www.twilio.com/user/account/developer-tools/test-credentials
# Should probably use TWILIO_AUTH_TOKEN once testing complete.
auth_token = '9ea8a4f0ac5fd659fef71719e480c3c0'
if 'HTTP_X_TWILIO_SIGNATURE' not in request.META:
return 'X_TWILIO_SIGNATURE header is missing ' \
'from request, not a valid Twilio request.'
validator = RequestValidator(auth_token)
if not validator.validate(
request.build_absolute_uri(),
request.POST,
request.META['HTTP_X_TWILIO_SIGNATURE']):
return 'Twilio request is not valid.'
|
a83f3065fcebcb8231be4ed5558743fa6d837754
| 698,754 |
def mathprod(seq): # math.prod function is available at python 3.8
"""
returns product of sequence elements
"""
v = seq[0]
for s in seq[1:]:
v *= s
return v
|
b75ff229e4cfaabe42e542367dd27e257f1d33ec
| 698,755 |
from typing import List
from typing import Any
def _split_list_into_chunks(x: List[Any], chunk_size: int = 50) -> List[List[Any]]:
"""Helper function that splits a list into chunks."""
chunks = [x[i:i + chunk_size] for i in range(0, len(x), chunk_size)]
return chunks
|
b9972b57a18a97fceec78ec1d55156c83d255f9f
| 698,756 |
import math
def fix(x):
"""
From http://www.mathworks.com/help/matlab/ref/fix.html
fix
Round toward zero
Syntax:
B = fix(A)
Description:
B = fix(A) rounds the elements of A toward zero,
resulting in an array of integers.
For complex A, the imaginary and real parts are
rounded independently.
Examples:
a = [-1.9, -0.2, 3.4, 5.6, 7.0, 2.4+3.6i]
a =
Columns 1 through 4
-1.9000 -0.2000 3.4000 5.6000
Columns 5 through 6
7.0000 2.4000 + 3.6000i
fix(a)
ans =
Columns 1 through 4
-1.0000 0 3.0000 5.0000
Columns 5 through 6
7.0000 2.0000 + 3.0000i
"""
if x < 0:
return math.ceil(x);
else:
return math.floor(x);
|
d57d4dd7088b2191e63fff16d0000508275f8a09
| 698,758 |
def create_demand_callback(data):
"""Creates callback to get demands at each location."""
def demand_callback(from_node, to_node):
return data["demands"][from_node]
return demand_callback
|
ceff0d3caaa1e1269fee18e8aa4684afaa7a5e81
| 698,763 |
def _get_unique_index_values(idf, index_col, assert_all_same=True):
"""
Get unique values in index column from a dataframe
Parameters
----------
idf : :obj:`pd.DataFrame`
Dataframe to get index values from
index_col : str
Column in index to get the values for
assert_all_same : bool
Should we assert that all the values are the same before
returning? If True, only a single value is returned. If
False, a list is returned.
Returns
-------
str, list
Values found, either a string or a list depending on
``assert_all_same``.
Raises
------
AssertionError
``assert_all_same`` is True and there's more than one
unique value.
"""
out = idf.index.get_level_values(index_col).unique().tolist()
if assert_all_same:
if len(out) > 1:
raise AssertionError(out)
return out[0]
return out
|
306a919a547a6d0056a4547daa50e6149d840910
| 698,766 |
def str_to_bytes(s):
"""convert string to byte unit. Case insensitive.
>>> str_to_bytes('2GB')
2147483648
>>> str_to_bytes('1kb')
1024
"""
s = s.replace(' ', '')
if s[-1].isalpha() and s[-2].isalpha():
_unit = s[-2:].upper()
_num = s[:-2]
elif s[-1].isalpha():
_unit = s[-1].upper()
_num = s[:-1]
else:
return float(s)
if not _unit in ('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'):
raise ValueError('invalid unit', _unit)
carry = {
'B': 1,
'KB': 1024,
'MB': 1024 ** 2,
'GB': 1024 ** 3,
'TB': 1024 ** 4,
'PB': 1024 ** 5,
'EB': 1024 ** 6,
'ZB': 1024 ** 7,
'YB': 1024 ** 8
}
return float(_num) * carry[_unit]
|
71bef1d7a81fad44a00deb268fba83dac1ed633e
| 698,779 |
def select_first_node(g):
"""
:param g: the graph
:return: the first node of the node sequence based on which the graph will be partitioned. We select the first node
as the node which has the lowest degree
"""
all_degrees = []
node_list = list(range(0, len(g)))
for node in node_list:
all_degrees.append(g.degree[node])
return all_degrees.index(min(all_degrees))
|
769a36437e38b19984f88f510b544c22df984106
| 698,780 |
def _flatten(coll):
""" Flatten list and convert elements to int
"""
if isinstance(coll, list):
return [int(a) for i in coll for a in _flatten(i)]
else:
return [coll]
|
a6f1dee42a5c881e4cf4496283f248a230f38465
| 698,784 |
def to_float_hours(hours, minutes, seconds):
""" (int, int, int) -> float
Return the total number of hours in the specified number
of hours, minutes, and seconds.
Precondition: 0 <= minutes < 60 and 0 <= seconds < 60
>>> to_float_hours(0, 15, 0)
0.25
>>> to_float_hours(2, 45, 9)
2.7525
>>> to_float_hours(1, 0, 36)
1.01
"""
return hours + (minutes / 60) + (seconds / 3600)
|
f94f37585929fc45f4b417ab63ca9b7b501a2e57
| 698,786 |
import difflib
def _get_suggestion(provided_string, allowed_strings):
"""
Given a string and a list of allowed_strings, it returns a string to print
on screen, with sensible text depending on whether no suggestion is found,
or one or more than one suggestions are found.
:param provided_string: the string to compare
:param allowed_strings: a list of valid strings
:return: A string to print on output, to suggest to the user
a possible valid value.
"""
similar_kws = difflib.get_close_matches(provided_string, allowed_strings)
if len(similar_kws) == 1:
return "(Maybe you wanted to specify {0}?)".format(similar_kws[0])
elif len(similar_kws) > 1:
return "(Maybe you wanted to specify one of these: {0}?)".format(
", ".join(similar_kws))
else:
return "(No similar keywords found...)"
|
ebd1b963116bddebbc340312f2d7a16be36b11c6
| 698,789 |
def iso_8601(datetime):
"""Convert a datetime into an iso 8601 string."""
if datetime is None:
return datetime
value = datetime.isoformat()
if value.endswith('+00:00'):
value = value[:-6] + 'Z'
return value
|
968b9d9edfe13340e4c2f74fb78c11cb38d6c013
| 698,790 |
def get_request_url(url, *args, **kwargs):
"""Returns url parameter that request will use"""
return url
|
fde43b531d53e0f3cf80655b0da9895b7a001e13
| 698,794 |
def square_table_while(n):
"""
Returns: list of squares less than (or equal to) N
This function creates a list of integer squares 1*1, 2*2, ...
It only adds those squares that are less than or equal to N.
Parameter n: the bound on the squares
Precondition: n >= 0 is a number
"""
seq = []
k = 0
while k*k < n:
seq.append(k*k)
k = k+1
return seq
|
8eb94d9690f4138fb6759cf73d5a602659571b34
| 698,796 |
def populate_words(words, oxford_api, words_api=None, allow_messages=True):
"""
Iterates the words dictionary, populating the data of each object using the OxfordAPI and with the optional
WordsAPI to be used in the case the word is not found in the Oxford dictionary.
:param words: The dictionary containing the words to be populated.
:param oxford_api: The OxfordAPI object.
:param words_api: The WordsAPI object.
:param allow_messages: Boolean value to indicate if messages should be displayed in the console.
:return: A list of those words that have not been found.
"""
incomplete_words = []
i = 0
for word in words.values():
if allow_messages:
print(i, ': ', word.text)
i = i + 1
success = oxford_api.get_word(word)
if not success and words_api:
definitions = words_api.definitions(word.text)
if definitions and definitions.get('definitions', False):
for definition in definitions.get('definitions', list()):
word.definitions.append(definition.get('definition', None))
for item in words.items():
key = item[0]
word = item[1]
if len(word.definitions) == 0:
incomplete_words.append(key)
return incomplete_words
|
6f435b2e8d9947a9e7c6ba558aa43e13fe0dcfd6
| 698,798 |
def poly(a, x, y, order=4):
"""Polynomial evaluation.
pol = a[i,j] * x**(i-j) * y**j summed over i and j, where i runs from 0 to order.
Then for each value of i, j runs from 0 to i.
For many of the polynomial operations the coefficients A[i,j] are contained in an
array of dimension (order+1, order+1) but with all elements where j > i set equal to zero.
This is called the triangular layout.
The flattened layout is a one-dimensional array containing copies of only the elements
where j <= i.
The JWST layout is a[0,0] a[1,0] a[1,1] a[2,0] a[2,1] a[2,2] ...
The number of coefficients will be (n+1)(n+2)/2
Parameters
----------
a : array
float array of polynomial coefficients in flattened arrangement
x : array
x pixel position. Can be integer or float or an array of integers or floats
y : array
y pixel position in same layout as x positions.
order : int
integer polynomial order
Returns
-------
pol : float
result as described above
"""
pol = 0.0
k = 0 # index for coefficients
for i in range(order+1):
for j in range(i+1):
pol = pol + a[k] * x**(i-j) * y**j
k += 1
return pol
|
e5575d4df2ae4cc5f7f1eea467d9b04ebbb97942
| 698,804 |
import struct
def short_to_bytes(short_data):
"""
For a 16 bit signed short in little endian
:param short_data:
:return: bytes(); len == 2
"""
result = struct.pack('<h', short_data)
return result
|
26eeb2de936fa6b434c724ef80c008d93aec0446
| 698,806 |
def find_components(value):
""" Extract the three values which have been combined to
form the given output.
"""
r1 = value >> 20 # 11 most significant bits
r2 = (2**10 - 1) & (value >> 10) # 10 middle bits
r3 = (2**10 - 1) & value # 10 least significant bits
return r1, r2, r3
|
80a235cafe8ceb37cafb6453f3338e03653bffe1
| 698,811 |
def GetInvalidTypeErrors(type_names, metrics):
"""Check that all of the metrics have valid types.
Args:
type_names: The set of valid type names.
metrics: A list of rappor metric description objects.
Returns:
A list of errors about metrics with invalid_types.
"""
invalid_types = [m for m in metrics if m['type'] not in type_names]
return ['Rappor metric "%s" has invalid type "%s"' % (
metric['name'], metric['type'])
for metric in invalid_types]
|
27af3804cb4a857d044ad365cdfee090a0d1ab56
| 698,813 |
import textwrap
def indent(multiline_str: str, indented=4):
"""
Converts a multiline string to an indented string
Args:
multiline_str: string to be converted
indented: number of space used for indentation
Returns: Indented string
"""
return textwrap.indent(multiline_str, " " * indented)
|
9fd5f2310ade00071a57731040435428cff88557
| 698,815 |
def list_pattern_features(client, patter_name, type_=None, file_=None):
"""List features in a Creo Pattern.
Args:
client (obj):
creopyson Client.
patter_name (str):
Pattern name.
`type_` (str, optional):
Feature type patter (wildcards allowed: True).
Defaults: All feature types.
`file_` (str, optional):
File name. Defaults is the currently active model.
Returns:
(list:dict): List of feature information
"""
data = {
"patter_name": patter_name,
}
if file_ is not None:
data["file"] = file_
else:
active_file = client.file_get_active()
if active_file:
data["file"] = active_file["file"]
if type_:
data["type"] = type_
return client._creoson_post("feature", "list_group_features", data, "featlist")
|
d1923ccdb178a211ecd896c325170a5e247557aa
| 698,816 |
def get_answer(offer, user):
"""Returns an user answer for the given offer"""
if not user.is_authenticated:
return None
return offer.answers.filter(user=user).first()
|
e89da7d11e6e8a01deb8177d3af9c693267fe09a
| 698,820 |
def process_dsn(dsn):
"""
Take a standard DSN-dict and return the args and
kwargs that will be passed to the psycopg2 Connection
constructor.
"""
args = ['host=%s dbname=%s user=%s password=%s' % (dsn['host'], dsn['db'], dsn['user'], dsn['passwd'])]
del dsn['host']
del dsn['db']
del dsn['user']
del dsn['passwd']
return args, dsn
|
c73b641cd4e28c5824db6d37d3aec2786c7461ff
| 698,826 |
def moftype(cimtype, refclass):
"""Converts a CIM type name to MOF syntax."""
if cimtype == 'reference':
_moftype = refclass + " REF"
else:
_moftype = cimtype
return _moftype
|
c09697b9a1fabea1f1529de8ab7ee7eeed4da846
| 698,834 |
def handle_status_update(loan_id, new_status):
"""Handles a status update for an order."""
# lookup order in your system using loan_id
# set order status to new_status
return ''
|
d75f6c145346d7fe9c6fd124dc0590fd66b64da6
| 698,836 |
import json
def translate_header(df, dictionary, dictionary_type='inline'):
"""change the headers of a dataframe base on a mapping dictionary.
Parameters
----------
df : `DataFrame`
The dataframe to be translated
dictionary_type : `str`, default to `inline`
The type of dictionary, choose from `inline` or `file`
dictionary : `dict` or `str`
The mapping dictionary or path of mapping file
"""
if dictionary_type == 'inline':
return df.rename(columns=dictionary)
elif dictionary_type == 'file':
with open(dictionary, 'r') as f:
dictionary = json.load(f)
return df.rename(columns=dictionary)
else:
raise ValueError('dictionary not supported: '+dictionary_type)
|
371443bc112fa2b0892bbcf945e3089aab995122
| 698,839 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.