content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def wrench2msg(wrench):
"""
Converts a 6x1 wrench vector into a geometry_msgs/Twist message
:type twist: numpy.array
:param twist: 6x1 wrench matrix
:rtype: geometry_msgs.msg.Wrench
:return The ROS Wrench message
"""
wrench2=np.reshape(wrench, (6,))
return Wrench(Vector3(wrench2... | 53,500 |
def get_fuzz_target_weights():
"""Get a list of fuzz target weights based on the current fuzzer."""
# No work to do if this isn't fuzz task. Weights are only required if a
# fuzzer has not yet been selected.
task_name = environment.get_value('TASK_NAME')
if task_name != 'fuzz':
return None
job_type = e... | 53,501 |
def measure_network_density(streets_for_networkd_prj, gross_city_blocks_prj):
"""
Adds network density (m/ha.) onto a gdf of gross urban blocks
Requires a gdf of streets to overlay with the gross city blocks. Streets
that are within a gross urban blocks (i.e. do not coincide with its perimeter)
hav... | 53,502 |
def param_size(model, *args, **kwargs):
"""Return size of model parameters."""
val = 4 * param_count(model, format=False)
return format_value(val, *args, binary=True, **kwargs) if format else val | 53,503 |
def resolve_source(ctx_file):
"""Resolve best URL from acquisition."""
# get settings
# read in context
with open(ctx_file) as f:
ctx = json.load(f)
'''
settings_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'settings.json')
with open(settings_file) as f:
... | 53,504 |
def now(update: Update , context : CallbackContext, lang) -> int:
"""
Thhis functions implements the quick search, after checking if the campus is in
the preferences of the user call the end_state function, otherwise return to the initial_state
"""
user = update.message.from_user
logging.info("%... | 53,505 |
def __analyze_function(input_str: str) -> str:
"""
transfer the syntax from python to the math -- adding auto "*" sign between signed variables
:param input_str: ~
:return: the modified input str
"""
var_element = [] # the variables and element which used in the input_str. it contains all... | 53,506 |
def jsonNodeToAvroType(x):
"""Convert a Python-encoded Avro type into a titus.datatype.AvroType.
:type x: dicts, lists, strings, numbers, ``True``, ``False``, ``None``
:param x: Avro type in Python form
:rtype: titus.datatype.AvroType
:return: AvroType object
"""
return schemaToAvroType(av... | 53,507 |
def wordfreq_viz(
word_cnts: pd.Series,
nrows: int,
plot_width: int,
plot_height: int,
wordfreq: WordFrequency,
) -> Figure:
"""
Visualize the word frequency bar chart
"""
col = word_cnts.name
df = word_cnts.to_frame()
df["pct"] = df[col] / nrows * 100
tooltips = [
... | 53,508 |
def scatter():
"""Fake endpoint."""
if 'override' in request.args:
with open('{}/examples/overrides.json'.format(cwd), 'r') as jsonfile:
return jsonfile.read()
return json.dumps({
"bar1": [1, 2, 30, 12, 100],
"bar2": rr_list(max_range=40),
"bar3": rr_list(max_rang... | 53,509 |
async def test_state_changed_event_exclude_domain_include_entity(hass, mqtt_mock):
"""Test filtering with excluded domain and included entity."""
base_topic = "pub"
incl = {"entities": ["fake.entity"]}
excl = {"domains": ["fake"]}
# Add the statestream component for publishing state updates
# ... | 53,510 |
def default_crop() -> Crop:
"""
Set Tea as the default crop.
"""
try:
# Check whether Tea Object exists in Crop Model
crop = Crop.objects.get(name="Tea")
except Crop.DoesNotExist:
crop_data = {}
crop_data["name"] = "Tea"
crop_data["initial_moisture"] = "69"
... | 53,511 |
def get_item(id: str):
"""
get any specific item
"""
item = item_service.get_item(id)
if not item:
raise HTTPException(status_code=404, detail="Item not found.")
return item | 53,512 |
def test_unknown_event(caplog, ws_message_event):
"""Test that an unknown event type is handled correctly."""
ws_message_event["data"]["eventCid"] = 9999
event = websocket_event_from_payload(ws_message_event)
assert event.event_type is None
assert any(
"Encountered unknown websocket event ty... | 53,513 |
def get_nested_value(the_map, dot_separated_key):
"""Give a nested dictionary map, get the value specified by a dot-separated key where dots
denote an additional depth. Taken from stack overflow (http://stackoverflow.com/a/12414913).
"""
keys = dot_separated_key.split(".")
return reduce(operator.get... | 53,514 |
def _transform_points(reg_dir: Path, points_file: Path, out_dir: Path) -> Path:
"""
Given a Lama output regisrtation directory and a points file, apply the concatenated transforms to the points
and return the output points file.
Parameters
----------
reg_dir
Lama output directory
po... | 53,515 |
def repairMask(graph,start,end):
"""
:param graph:
:param start:
:param end:
:return:
@type graph: ImageGraph
@type start: str
@type end: str
"""
edge = graph.get_edge(start,end)
startimage, name = graph.get_image(start)
finalimage, fname = graph.get_image... | 53,516 |
def cxSet(ind1, ind2):
"""Apply a crossover operation on input sets. The first child is the
intersection of the two sets, the second child is the difference of the
two sets.
"""
temp = set(ind1) # Used in order to keep type
ind1 &= ind2 # Intersection (inplace)
ind2 ^= temp # Symmetric Di... | 53,517 |
def preprocess(self, im, allobj = None):
"""
Takes an image, return it as a numpy tensor that is readily
to be fed into tfnet. If there is an accompanied annotation (allobj),
meaning this preprocessing is serving the train process, then this
image will be transformed with random noise to augment training data,
us... | 53,518 |
def get_module(obs_space: Space, action_space: Space, config: dict) -> nn.Module:
"""Retrieve and construct module of given name.
Args:
obs_space: Observation space
action_space: Action space
config: Configurations for module construction and initialization
"""
type_ = config.po... | 53,519 |
def safe_bcolz_open(fname, idx=None, debug=False):
"""Threadsafe way to read bcolz arrays.
bcolz might have issues with multithreading and underlying blosc
compression code. Lots of discussion out there, here are some
starting points:
http://www.pytables.org/latest/cookbook/threading.html
... | 53,520 |
def edit(client: ModelTrainingClient, train_id: str, file: str, wait: bool,
timeout: int):
"""
\b
Rerun a training.
You should specify a path to file with a training. The file must contain only one training.
For now, CLI supports YAML and JSON file formats.
If you want to update multipl... | 53,521 |
def _replace_event_values_arr(
timearr: NDArray[float], old_value: int, new_value: int
) -> NDArray[int]:
"""Replace the values 'old_value' with 'new_value' for the array."""
timearr[np.where(timearr == old_value)] = new_value
return timearr | 53,522 |
def validate_api_host_url(url):
"""
Validate SolveBio API host url.
Valid urls must not be empty and
must contain either HTTP or HTTPS scheme.
"""
if not url:
raise SolveError('No SolveBio API host is set')
# Default to https if no scheme is set
if '://' not in url:
url... | 53,523 |
def add_implicit_arguments(unknown_args, parser):
"""
Given the list of "unknown" args, dynamically adds proper arguments to
the subparser, allowing us to support any token parameter as a flag
"""
num_unknown_args = len(unknown_args)
for i in range(num_unknown_args):
arg = unknown_args[i... | 53,524 |
def search_permission_filter():
"""Filter list of results."""
# Send empty query for admins
if Permission(superuser_access).allows(g.identity):
return Q()
provides = get_user_provides()
# Filter for public records
public = Q('missing', field='_access.read')
# Filter for restricted ... | 53,525 |
def check_depth_submission(path):
"""Checks if all files required for the submission exist and are in the right format."""
ready_for_submission = True
ready_for_submission = ready_for_submission and _check_frames(_get_test_frame_paths('depth', path, '.pfm'))
return ready_for_submission | 53,526 |
def test_main_run_pipe_in():
"""Have CT run the tty test code with a pipe on stdin."""
master, slave = os.openpty()
subprocess.run(CLI + ' ' + get_python_command(CODE_ISATTY),
check=True,
shell=True,
stdin=subprocess.PIPE,
stdout=sl... | 53,527 |
def post_query(sql_statement, values, db='test_soda'):
"""
insert_query(sql_statement)
This function is a database accessor function that will
insert a query into the database.
It has no return value.
"""
conn = MySQLdb.connect(host="10.24.12.21",
us... | 53,528 |
def qual2fastq(quals):
"""
Convert a list of quality scores to a single fastq line
:param quals: A list of quality scores
:type quals: list
:return: A fastq quality string
:rtype: str
"""
quality = [chr(q + 33) for q in quals]
return "".join(quality) | 53,529 |
def generate_honeycomb_coordinates(n_x, n_y, scaling=1.0):
"""
Generate coordinates from a honeycomb mesh which can be used to set up a
cell population.
Parameters
----------
n_x: int
number of columns
n_y: int
number of rows
scaling: float
distance between the c... | 53,530 |
def exists(path: str) -> bool:
"""Checks if path exists
e.g
j.sals.fs.exists("/home/rafy/testing_make_dir/test1") -> True
j.sals.fs.exists("/home/rafy/testing_make_dir/fasdljd") -> False
Args:
path (str): path to check for existence
Returns:
bool: True if exists
"... | 53,531 |
def load_token(token):
"""
decrypt token and load User
"""
max_age = app.config['REMEMBER_COOKIE_DURATION'].total_seconds()
data = login_serializer.loads(token, max_age=max_age)
u = model.Users.query.filter_by(email=data[0]).first()
if u and data[1] == u.password:
return u
retu... | 53,532 |
def main():
"""Updates the packages' 'LLVM_NEXT_HASH' and submits tryjobs.
Raises:
AssertionError: The script was run inside the chroot.
"""
VerifyOutsideChroot()
args_output = GetCommandLineArgs()
last_svn_version = GetLastTestedSVNVersion(args_output.last_tested)
update_packages = [
'sys-... | 53,533 |
def heSHjuBBFVLp():
"""Let notation."""
return Injector.let(bar=(this << 2).foo) | 53,534 |
def shell(ctx):
"""
Execute command in docker container
"""
docker_exec(ctx, '/bin/bash') | 53,535 |
def largest_of_three(a,b,c):
"""
Tells you which was the largest of the three numbers it is provided with
"""
print("The largest of a, b and c is " + str(max(a,b,c))) | 53,536 |
def _create_cql_update_query(key_space: str, table_name: str,
set_columns_value_dict: dict,
primary_key_values: dict) -> str:
""" This function will create an update CQL query"""
cql_update = "UPDATE " + key_space + "." + table_name + " SET "
fo... | 53,537 |
def apply_psd(signal_t, psd, sampling_rate=4096, apply_butter=True):
"""
Take a signal in the time domain, and a precalculated Power Spectral
Density, and color the signal according to the given PSD.
Args:
signal_t: A signal in time domain (i.e. a 1D numpy array)
psd: A Power Spectral D... | 53,538 |
def test_get_non_existing_file_obj(psql_fixture): # noqa: F811
"""Test getting not existing file info and expect corresponding error."""
non_existing_file_info = psql_fixture.non_existing_file_infos[0]
with pytest.raises(FileInfoNotFoundError):
psql_fixture.database.get_file_info(non_existing_file... | 53,539 |
def do_zoom_image_job(port_input_name: str,
zoom_factor: float,
do_interpolation: bool = True, port_output_name: str = None,
level: PYRAMID_LEVEL = PYRAMID_LEVEL.LEVEL_0, wave_offset: int = 0, is_rgb: bool = False) -> str:
"""
Function for zoomin... | 53,540 |
def delete_rare_nodes(parent: FqNameNode, min_count: int):
"""
Recursively leave only children with count greater then `min_count`.
:param parent: node to remove extra rare children
:param min_count: min value of children count that is allowed to leave
"""
parent.children = list(filter(lambda n... | 53,541 |
def update_raid_group_resync_speed(session, raid_id, minimum, maximum,
return_type=None, **kwargs):
"""
Updates the speed at which a RAID group will rebuild using the minimum and
maximum arguments.
:type session: zadarapy.session.Session
:param session: A valid za... | 53,542 |
def write_lib_kde(kde, outname, libID):
"""Write a dict of KDE objects for one library.
Parameters
----------
kde : {taxon:kde}
outname : str
output file name
libID : int|str
library ID
Returns
-------
str : file name of output.
"""
prefix = os.path.splite... | 53,543 |
def loadToken():
"""
get cookie and crumb from APPL page or disk.
force = overwrite disk data
"""
refreshDays = 30 # refreh cookie every x days
# set destinatioin file
dataDir = os.path.expanduser('~')+'/twpData'
dataFile = dataFile = os.path.join(dataDir,'yahoo_cookie.ym... | 53,544 |
def extract_file_number(file_name):
""" Extract the file number from a file name """
file_name = str(file_name)
dot_contents = file_name.split('.')
hyp_contents = dot_contents[0].split('-')
base_name = hyp_contents[len(hyp_contents) - 1]
return int(base_name[:-1]) | 53,545 |
def solve_rational_inequalities(eqs):
"""
Solve a system of rational inequalities with rational coefficients.
Examples
========
>>> solve_rational_inequalities([[((Poly(-x + 1), Poly(1, x)), '>='),
... ((Poly(-x + 1), Poly(1, x)), '<=')]])
{1}
>>> solve_r... | 53,546 |
def BHV_diffeo( ind_current_topo, dictionnary_topology_comparison,
mask_topo_comparison, mask_topo, mask_segments,
singular_template, singular_connections, n_leaves,
template, template_connections,
target, target_connections,
folder2save,... | 53,547 |
def add_address(x, y):
"""Returns a string representation of the sum of the two parameters.
x is a hex string address that can be converted to an int.
y is an int.
"""
return "{0:08X}".format(int(x, 16) + y) | 53,548 |
def inv_linear_DisPrinc_sparse(
Tn=None,
TTn=None,
Tyn=None,
R=None,
yn=None,
sol0=None,
nchan=None,
mu0=None,
precond=None,
verb=None,
verb2head=None,
# specific
chi2n_tol=None,
chi2n_obj=None,
maxiter=None,
tol=None,
**kwdargs,
):
"""
Discrep... | 53,549 |
def get_dist_name():
"""Get the product name by reading distribution pom.
"""
global dist_name
global dist_zip_name
global product_version
dist_pom_path = Path(workspace + "/" + product_id + "/" + DIST_POM_PATH[product_id])
if sys.platform.startswith('win'):
dist_pom_path = cp.winapi... | 53,550 |
def polygon(t , n , length , polyg = 0):
"""Draws n line segments with the given length and angle (in degrees)
between them. t is a turtle. """
if(polyg == 0):
polyg = n
for i in range(polyg):
fd(t , length)
lt(t , 360.0/n) | 53,551 |
def shutdown() -> None:
"""Turns off speech recognition."""
SHUTDOWN = True | 53,552 |
def map_to_template(id, template_id, result_key, created_by):
"""
Map the result specified by ID to the template specified by TEMPLATE_ID for RESULT_KEY in
in the output generated by that template
"""
# If created_by is not set and there is an email config variable, fill with that
if created_by ... | 53,553 |
def replaceRoadWithRd(a_string):
"""assumes a_string is a string
returns a string, with "Rd." where a_string has "Road" """
pattern = "[Rr]oad"
replacement = "Rd."
result = re.sub(pattern, replacement, a_string)
return result | 53,554 |
def get(columns=None):
"""Get or create MetaData singleton."""
if columns is None:
columns = _DEFAULT_COLUMNS
global _METADATA
if not _METADATA:
_METADATA = MetaData(columns)
return _METADATA | 53,555 |
def read_data(report_name: str):
"""Читает исходные данные по стоимости портфеля из файла"""
data = pd.read_excel(REPORTS_DATA_PATH / f'{report_name}.xlsx',
sheet_name=SHEET_NAME,
header=0,
index_col=0,
converter... | 53,556 |
def extract_fcp_data(raw_data, status):
"""
extract data from smcli System_WWPN_Query output.
Input:
raw data returned from smcli
Output:
data extracted would be like:
'status:Free \n
fcp_dev_no:1D2F\n
physical_wwpn:C05076E9928051D1\n
channel_path_id:8B\n
npiv_wwp... | 53,557 |
def prepare_design_symmetry(D: np.ndarray) -> np.ndarray:
"""Add to the design matrix strip simmetric to the one in the input
Args
----
D: np.ndarray
The design matrix as it comes from build_Design_Matrix
Returns
-------
New design matrix with appended the simmetric angles
... | 53,558 |
def generate_output_html(htmlfile):
"""Load HTML template and add current date, return result"""
try:
with open(htmlfile) as f:
html = f.read().format(date_string)
return html
except Exception as ex:
logger.error('Exception occured while loading template {}. Details: ... | 53,559 |
def check_existence_and_date_s3(query_hash: Union[int, str]) -> Dict[str, str]:
"""Check if a query hash has corresponding result and query json on S3
Parameters
----------
query_hash :
The query hash to check
Returns
-------
:
Dict with S3 key for query and corresponding r... | 53,560 |
def verifying_key_from_hex(key: bytes):
"""Load the VerifyingKey from a compressed or uncompressed hex public key.
"""
id_byte = key[0]
if not isinstance(id_byte, int):
id_byte = ord(id_byte)
if id_byte == 4:
# Uncompressed public point
# 1B ID + 32B x coord + 32B y coord = 6... | 53,561 |
def get_graph():
"""Creates dictionary {node: {child1, child2, ..},..} for current
TensorFlow graph. Result is compatible with networkx/toposort"""
ops = tf.get_default_graph().get_operations()
return {op: children(op) for op in ops} | 53,562 |
def find_coord(find_coords, search_coords, tol=1.e-6):
""" {TEST}
Find the index for the coordinate in search_coords that matches
the coordinate find_coords.
:param find_coords: Coordinates for the point to find
:type find_coords: tuple[ float ]
:param search_coords: Coordinate lists ... | 53,563 |
def debug():
""" Debug function - runs if heimdall called directly. """
png('https://www.distilled.net/', device="iPhone") | 53,564 |
def nonOverlappingMinima(minDists, m, fromSeq=None):
"""
Returns the indices i such that (minDist[i] <= minDists[j] or
fromSeq[i] != fromSeq[j]) for all j in [i, i + m - 1]. If fromSeq
is not provided, the latter test always fails (i.e., both dists are
assumed to be from the same sequence, and thus able to overlap... | 53,565 |
def draw_contour_(contour_img,
contour,
color,
gradient_colors=("red", "blue"),
min_size=10,
filled=True,
compute_mask=False):
""" Draw a contour as optionally fill it with color.
Differs from draw_contour() i... | 53,566 |
def find_table_config_pairs(tag, paths):
"""
Args:
str tag: part of filename to filter files to be used
dict paths: hard-coded paths to output folders
Out:
dict path_pairs: keys "config" and "meet_table"
"""
aa = os.listdir(paths[ "configs"])
bb = os.listdir(paths["me... | 53,567 |
def test_float_field() -> None:
"""Float field should load correct values."""
_check_field("17.2", 17.2) | 53,568 |
def list_to_include_array(data_list):
"""Convert python list to ble_gattc_include_array."""
data_array = _populate_array(data_list, driver.ble_gattc_include_array)
return data_array | 53,569 |
def test_sql_creds_for_windows_auth_non_default_port():
"""
Tests that the SqlCreds object can be created without Username and Password (Windows Auth)
"""
creds = SqlCreds(server="test_server", database="test_database", driver_version=99, port=9999,)
assert creds.port == 9999
assert creds.with_k... | 53,570 |
def test_delete_security_group():
"""
This methos tests the deletion of Security Groups
:return:
"""
ec2_client = boto3.client('ec2', region_name=region_name)
vpc_response = ec2_client.create_vpc(CidrBlock='10.0.0.0/16')
vpc_id = vpc_response['Vpc']['VpcId']
subnet1 = ec2_client.create_s... | 53,571 |
def check_for_valid_numerical_encoding_of_labels(labels):
"""
Checks whether the labels are numerical labels satisfying the following
requirements:
1. each label is an integer greater or equal to zero
2. the smallest label is zero
The labels encoded by applying "sklearn.preprocessing.La... | 53,572 |
def video_pack_sequences(in_batch):
"""
Pad the variable-length input sequences to fixed length
:param in_batch: the original input batch of sequences generated by pytorch DataLoader
:return:
out_batch (list): the padded batch of sequences
"""
# Get the number of return values from __get... | 53,573 |
def generate_nologin_hash(public_string):
"""Generate hash for users who are not logged in"""
hex_hash = sha256(settings.EMAIL_SECRET_KEY + public_string).hexdigest()
# Decode the hex hash into base64, reducing the length of the code
b64_hash = hex_hash.decode('hex').encode("base64")
# Remove all ... | 53,574 |
async def test_battery_service(hass, hk_driver, caplog):
"""Test battery service."""
entity_id = "homekit.accessory"
hass.states.async_set(entity_id, None, {ATTR_BATTERY_LEVEL: 50})
await hass.async_block_till_done()
acc = HomeAccessory(hass, hk_driver, "Battery Service", entity_id, 2, None)
as... | 53,575 |
def compute_v_dot_upper_bound(dV, mean, variance=None, beta=2.):
"""
Compute the safe set
Parameters
----------
dV: np.array
The derivatives of the Lyapunov function at grid points
mean: np.array
mean of the dynamics (including prior dynamics as mean)
variance: np.array
... | 53,576 |
def success(pred_data, true_data):
"""TODO: Docstring for success.
:input_data: TODO
:input_data: List with a dict containing belief state, action, and
response.
:db: TODO
:goals: TODO
:booked_domains: TODO
:returns: TODO
"""
jaccard = {"belief":[], "action":[]}
for pred, t... | 53,577 |
async def protocol_factory(cot_url: urllib.parse.ParseResult):
"""
Given a COT Destination URL, create a Connection Class Instance for the
given protocol.
`url` is urllib-parsed URL to remote host. eg. 'udp://example.com:1234'
"""
reader = None
writer = None
scheme = cot_url.scheme.low... | 53,578 |
def _login(nick, password, users_storage, library) -> int:
"""
Function for login user in system
:param nick: user nick
:param password: user password
:param users_storage: place where store all users
:param library: library interface, join all library functions in one
interface
:return:... | 53,579 |
def decode_resource_id_options(request):
""" Extract resource ID options from a HTTP request, making sure the keys have the same names as the
ResourceIdentifier object's fields. """
return {
# Resource ID
'resource_id': request['id'],
'target_platforms': json.dumps(request['target_pl... | 53,580 |
def test_references_uniqueness(record_data, duplicate_record_indexes):
"""Verify the uniqueness of reference numbers within a file."""
dta_file = DTAFile(sender_id='ABC12', client_clearing='8888')
for record_datum in record_data:
dta_file.add_836_record(**record_datum)
dta_file._sort_records() ... | 53,581 |
def vimming_process(path_to_file):
"""Search for vim editting that file with the ps command"""
filename = escape_quotes(os.path.basename(path_to_file))
if not filename:
return []
command = find_vimming_process_command(path_to_file)
output = getoutput(command)
if not output:
retur... | 53,582 |
def test_not_found(service_client):
""" Test that an unkown task returns 404 """
db = boto3.client('dynamodb')
resp = db.describe_table(TableName='test')
assert resp['Table']['ItemCount'] == 0
resp = service_client.post(
"/tasks",
json={
"action": "start",
"r... | 53,583 |
def load_data(data):
""" Wrapper to load json data, to be compatible with Python3.
Returns: JSON data
Keyword arguments:
data: might be bytes or str
"""
if type(data) == bytes:
return json.loads(data.decode("utf-8"))
else:
return json.loads(data) | 53,584 |
def Pauli_strings(num_qubits):
"""Returns the matrix representation of Pauli strings of size=num_qubits. e.g., for num_qubits=2, it returns
the matrix representations of ['II','IX','IY','IZ,'XI','YI',...]"""
pauli_labels = ['I', 'X', 'Y', 'Z']
Pauli_strings_matrices = [Pauli(''.join(p)).to_matrix() for ... | 53,585 |
def persistent_watermark():
"""Show persistent WM for queues"""
pass | 53,586 |
def factor_rank_autocorrelation(factor_data, period=1):
"""
Computes autocorrelation of mean factor ranks in specified time spans.
We must compare period to period factor ranks rather than factor values
to account for systematic shifts in the factor values of all names or names
within a group. This ... | 53,587 |
def imwrite(path, obj):
"""Save Image.
Args:
path: path to save the image. Suffix support: png or jpg or gif
image: array or list of array(list of image --> save as gif). Shape support: WxHx3 or WxHx1 or 3xWxH or 1xWxH
"""
if not isinstance(obj, (collections.Sequence, collections.Us... | 53,588 |
def indices_for(df, nprocs):
"""
group rows in dataframe and assign each group to each process
Args:
df: Pandas dataframe object
nprocs: number of processes used
Returns:
indeces grouped to each process
"""
N = df.shape[0]
L = int(N / nprocs)
indices... | 53,589 |
def test_new_encryption_keys():
"""
arg=None
"""
_info = setup_conv()
conv = _info['conv']
rsa = RSA.generate(2048)
kb0 = KeyBundle([{"kty": "rsa", "key": rsa, "use": "enc"}])
conv.keybundle = [kb0]
rsa = RSA.generate(2048)
kb1 = KeyBundle([{"kty": "rsa", "key": rsa, "use": "enc"... | 53,590 |
def run(args):
"""
Parse allsongsconsidered form results and remove duplicate entries
within a time window passed as a parameter
"""
rows = []
reader = csv.DictReader(sys.stdin)
writer = csv.DictWriter(sys.stdout, fieldnames=reader.fieldnames)
writer.writeheader()
rows = list(reader)... | 53,591 |
def _dynamic_range(fig, range_padding=0.05, range_padding_units='percent'):
"""Automatically rescales figure axes range when source data changes."""
fig.x_range.range_padding = range_padding
fig.x_range.range_padding_units = range_padding_units
fig.y_range.range_padding = range_padding
fig.y_range.r... | 53,592 |
def test__time_decompose_query():
"""Test function which decomposes queries into 5 year chunks.
The AEMET OpenData API refuses queries spanning more than 5 years, so we
provide a function for breaking up queries longer than this into separate
subqueries which will be subsequently recombined.
"""
... | 53,593 |
def norm(x):
"""
This function takes an array and makes it strictly superior to zero.
This is NOT a normalizing function, as it doesn't scale each value relatively to the others.
:param x: Array to make superior to zero.
:return: Resulting array.
"""
return np.log(np.exp(x + 1)) | 53,594 |
def _match_expr(parent, expr):
"""Match expressions to rewrite `A.select(A < 5)` into select expression
The argument must match the parent, so this _won't_ be rewritten: `A.select(B < 5)`
"""
args = expr.args
op = expr.op
if (
expr.method_name == "apply"
and len(args) == 2
... | 53,595 |
def generate_new_api_key(user_id):
"""
Generate a new API key for the user.
:param user_id: User ID for which to generate a new API key
:return: User object for that user ID with a modified API key
:raises UserDoesNotExistException: If no user exists with the given user_id
"""
user = get_us... | 53,596 |
def account_reset():
"""Handler for account reset."""
return account_handler("account_reset") | 53,597 |
def _get_validated_config_mapping(name, config_schema, config_fn):
"""Config mapping must set composite config_schema and config_fn or neither."""
if config_fn is None and config_schema is None:
return None
elif config_fn is not None and config_schema is not None:
return ConfigMapping(confi... | 53,598 |
def find_ops(optype):
"""Find ops of a given type in graphdef or a graph.
Args:
optype: operation type (e.g. Conv2D)
Returns:
List of operations.
"""
gd = tf.get_default_graph()
return [var for var in gd.get_operations() if var.type == optype] | 53,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.