content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import re
def urlify(s):
"""
Replacing spaces, and other URL-hostile characters
like question marks, apostrophes, exclamation points, etc.
Example:
>>> s = 'iso met'
iso_met
>>> s = 'isomet?'
'isomet'
"""
# Remove all non-word characters (everything except numbers and letters)... | 412091865dee3162a7175050618c614fd6d4190d | 616,912 |
def _prompt_username(prompt="Username: "):
"""Prompt the user for username."""
try:
while True:
username = input(prompt).strip()
if not username:
print("Username cannot be empty, please try again.")
elif "@" in username:
print("Please e... | df960c72e3ef97d2ce19bc046cd3a1e686862d04 | 616,916 |
def _course_runs_from_container(container):
"""
Pluck nested course runs out of a ``container`` dictionary,
which is either the ``curriculum`` field of a program, or
a program itself (since either may contain a ``courses`` list).
"""
return [
course_run.get('key')
for course in c... | 8f794fbaa17d07b5a4e90f4a7398b4ca020df41e | 616,917 |
def species_as_str(class_name, id, label, smiles, inchi, inchi_key):
"""
A helper function for generating a user-friendly string representation of a Species or NonPhysicalSpecies object.
"""
str_ = f"<{class_name}("
str_ += f"id={id}"
if label is not None and label:
str_ += f", label={la... | 0a32e5f65f41f6b00bf3672ff2f756527f4d74b1 | 616,921 |
def make_zipf(length):
"""Returns a list of counts that follows a Zipf distribution.
Args:
length: the number of counts to be generated
Returns:
A list of the provided length of floating point numbers corresponding
exactly the zipf distribution. For example, for length=5:
... | ce49000c2a23b6821bddd717169fd028bd92318c | 616,922 |
def distance(puissance: int, reserve: str) -> str:
"""Calculation of the shooting distance
Args:
puissance (int): Power of the shot
reserve (str): Reserve of flakes
Returns:
str: Distance reached
"""
return str(puissance * len(reserve)//2 - 1) + 'm' | 85bc6db7502861170cac69cef479ae64d1a0b3f4 | 616,925 |
def string_equal(name1, name2, case_sensitive=True, as_prefix=False):
"""
Determine if `name1` and `name2` are equal with taking special rules (`case_sensitive` and `as_prefix`) into account.
If ``as_prefix==True``, strings match even if `name1` is just a prefix of `name2`.
"""
if not case_sens... | 39051972f96c8f85a30c8bad98a8cd5bcf2bece0 | 616,930 |
def cli(ctx, library_id, dataset_id, purged=False):
"""Delete a library dataset in a data library.
Output:
A dictionary containing the dataset id and whether the dataset
has been deleted.
For example::
{'deleted': True,
'id': '60e680a037f41974'}
"""
return... | a6b12a6ac87af34dc675a9680e750ff60a13a497 | 616,934 |
def extract_prefix(keys):
"""
Takes a list of strings and extracts a common prefix delimited by a dot,
for example::
extract_prefix(["entity.bang", "entity.bar", "entity.bat"])
entity.
"""
prefixes = set()
for key in keys:
parts = key.split(".")
if len(parts) > 1:
... | 060ef3214b970bffa0c3b50bdb3fe98b81f2eeeb | 616,936 |
def identity(u):
""" returns the field itself """
return u | 48cec79a2e2fe4686471f32e7c9cd892fe4f97d6 | 616,937 |
def camel_to_snake_case(s: str) -> str:
"""Convert a camel cased string into snake case.
Args:
s (str): A camel cased string.
Returns:
The snake case converted string.
"""
words = []
s_index = 0
for i in range(len(s)):
if s[i].isupper():
words.append(s[s_ind... | a0516f02978dc6dfbb965dcf7f854db0deea913a | 616,938 |
def augment_class(string):
"""
Given a [string] representing the contents of a <main-classification> tag
(see USPTO XML Documentation 4.2 or later), realize the semantic meaning
of the string and return a string of form recognized by USPTO:
<main-class>/<sub-class>.<more-sub-class>
"""
mainc... | 06e8b3016538907f09e07d074f27908a496ab223 | 616,942 |
def update_gms_group(
self,
group_pk: str,
group_name: str,
background_image_file: str = "",
) -> bool:
"""Update appliance group in Orchestrator
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - group
- POST
... | c8e379ac41de7296a628ef45bc2dc4817b838de7 | 616,951 |
import re
def extract_ints(raw: str):
"""
Extract integers from a string.
"""
return map(int, re.findall(r'(\d+)', raw)) | c540b1314f102765813891c137fe75d631b291df | 616,952 |
def wheeled_network_2_robot_action_decoder(action, wheel_max, wheel_min, diff=0.25):
"""
Decode wheeled action from network to linear and angular speed for the robot
:param action: action for wheel spd
:param wheel_max: max wheel spd
:param wheel_min: min wheel spd
:param diff: diff of wheel for... | 0d99312e315b4242963cf1132f2ec553fd5713d2 | 616,956 |
def normalize_weights_dictionary(weights_dict):
"""
Normalizes weights provided as values in passed weight_dict so that
the sum of the weights equals 1.
Arguments
----------
weights_dict: a dictionary containing the columns to be included in the weighted sum
as keys, and the associate... | 4aaae26e220977701942cd8f98eb65c20fac6e62 | 616,959 |
from typing import Iterable
def natural_prefix_len(values: Iterable[int]) -> int:
"""Counts the consecutive integers from 1 to n from the start of values."""
index = 0
for index, value in enumerate(values):
if value - 1 != index:
break
return index | d6ebbf85b23dd6b3e11292153baff2fc0d6bfff8 | 616,960 |
import logging
def set_log_level(config):
"""
Sets the default log level in the config dict. (logging.INFO)
"""
config['logger_level'] = logging.INFO
return config | a108b74f660fbc8ee8633ffcfd1a075072658f0e | 616,965 |
def find_idx_in_co(idx,co):
"""
Find the index such that co[index,0]==idx.
"""
for i in range(len(co)):
if co[i,0] == idx:
return i
return None | a73c01a7b4f1f0a8bcc841a7fc36d88189894a86 | 616,971 |
def attr(obj, *path, **kwargs):
"""Safely get a nested attribute from an dictionary"""
default = kwargs.get('default')
if obj is None:
return default
res = obj
for p in path:
if p not in res:
return default
res = res[p]
return res | d198d1f9f670ff58cb362841b972b01babab8d37 | 616,973 |
def boolean_integer(string_or_bool):
"""
Converter to convert a boolean or "0"/"1" string to a boolean.
"""
if isinstance(string_or_bool, bool):
return string_or_bool
if string_or_bool.strip() == "1":
return True
return False | 981b909bd1bac7a85ae223153e657a92e2b6da11 | 616,980 |
def distance_between_nodes(graph, node_1_id, node_2_id):
"""Calculate the distance between two nodes in a given graph.
Args:
graph: A Map object representing the graph containing the nodes to find
the distance between
node_1_id: An int representing the id of the first node in the pa... | ba164d8e4fa06a2b7a827059fc74a4c71dd6806b | 616,981 |
import re
def load(stream):
"""Load the parameter keys, values and descriptions from a SOG
infile into a Python data structure.
Comments (lines starting with !) and empty lines are ignored.
:arg stream: An iterable (tyically a file object) containing SOG
infile formatted lines separ... | 1e2542689439da894e9be4c97d3ccb8fc0cf1eb7 | 616,983 |
def io(func):
"""
@io decorator for blocking io operations.
In pycsp.parallel it has no effect, other than compatibility
>>> @io
... def sleep(n):
... import time
... time.sleep(n)
>>> sleep(0.01)
"""
return func | 8dc21702ac884d953e79df7d951dfef76ef71b93 | 616,986 |
def read_string_file(file):
""" Read a file as a string.
Args:
file: File name
Returns:
File content as a string
"""
with open(file, "r") as f:
str = f.read()
return str | 1e98c64a188e4596887690e9ec475e429084fc56 | 616,987 |
def fwhm_dict(fwhm):
"""Convert a list of FWHM into a dictionary"""
fwhm = [float(f) for f in fwhm]
return {'fwhm_x': fwhm[0], 'fwhm_y': fwhm[1],
'fwhm_z': fwhm[2], 'fwhm_avg': fwhm[3]} | 4422bb0a22da5772a90c4931b5982af50afa1ac7 | 616,988 |
def create_query(languages, min_stars):
"""
Create the query string for the GitHub search API,
based on the minimum amount of stars for a project, and
the provided programming languages.
"""
# Notice we are calling .strip() on each language, to clear it of leading
# and trailing whitespace... | f5dffd3f193fc3ab1242b63cf556274e3eb61ca7 | 616,990 |
def uppercase_first_letter(string):
"""Converts the first letter of a string to uppercase.
>>> uppercase_first_letter('createHandler')
'CreateHandler'
>>> uppercase_first_letter('CreateHandler')
'CreateHandler'
>>> uppercase_first_letter('')
''
"""
return string[0].upper() + string[... | 654b3cbe56717ac233945d7d67e648ffa5562b98 | 616,993 |
import re
def make_container_name(image: str, suffix: str = "") -> str:
"""
Make default container name for the given Docker image.
Args:
image: Docker image tag.
suffix: Suffix to append to the container name.
Returns:
Docker container name.
"""
name = re.sub(r"[^a-z... | 570e3f89a5c76b9b4383e19d462ec1ee04b5118c | 616,995 |
def midi_to_pitch(midi: int) -> float:
"""Returns the absolute pitch in Hz for the given MIDI note value."""
return 440 * (2 ** ((midi - 69) / 12)) | 41f6f64071f7f990077167d0faaf3e6fb5b9a3f9 | 616,998 |
import copy
def to_list(value):
"""
Takes a value and wraps it into a list if it is not already one. The result is returned.
If None is passed, None is returned.
Parameters
----------
value : object
value to convert
Returns
-------
list or None
A list that wraps t... | 56eccfc8debadf22d1ad6ece8a6d4396e60cbc9e | 617,000 |
def remove_troublesome_chars(string: str):
"""Remove chars that cause trouble when pushed into postgres."""
if type(string) is not str:
return string
troublesome_chars = {'"': "", "'": "", "\n": " "}
for k, v in troublesome_chars.items():
string = string.replace(k, v)
return string | 1ad3858ab8beed047452e1d725c6f25da619d9ae | 617,003 |
def _check_hospital_unhappy(resident, hospital):
"""Determine whether a hospital is unhappy because they are
under-subscribed, or they prefer the resident to at least one of their
current matches."""
return len(hospital.matching) < hospital.capacity or any(
[hospital.prefers(resident, match) fo... | 2144e6f553f2b43b01a4f6f61f94e2c4c91cccfb | 617,004 |
def escape_special_characters(input_string):
""" Escape special characters to avoid unwanted behavior.
Note that they are not stored in the index so you cannot search for them.
Args:
input_string (str): String to escape special characters of
Returns:
str: Input string that has its spe... | e7aeae6fa0af903173caecd1f267da6b6c6d7259 | 617,005 |
import typing
def _normalize_sample_plan(sample, plan) -> typing.Tuple[list, list]:
"""Normalize samples and plans to list of samples and plans
Parameters
----------
sample :
Sample metadata. If a beamtime object is linked, an integer will be interpreted as the index appears in
the `... | b7dc8ad86156d1354d3bbcab6f1e166a478794fb | 617,007 |
def clean_up_spacing(sentence: str) -> str:
"""Clean up leading and trailing space characters from the string.
:param sentence: str - a sentence to clean of leading and trailing space characters.
:return: str - a sentence that has been cleaned of leading and trailing space characters.
"""
return s... | 49ed9c8cc9a20edb6e2e210f04bbac102c63ada5 | 617,008 |
def find_features(extent, df):
"""
given an extent and a dataframe, return a new dataframe
containing only features that fall within the extent
Parameters
----------
extent: list -- geographic extent in lon (deg E)/lat (deg N)
df: the geopandas dataframe to slice
"""
xleft, xrigh... | 90d7e0811dbb6340d89387dc5331c4039cc9f6bf | 617,010 |
def create_geometry_string(geometry):
"""This function converts MolecularData geometry to Dirac geometry.
This function is taken from Openfermion-Psi4 interface.
Args:
geometry: A list of tuples giving the coordinates of each atom.
example is [('H', (0, 0, 0)), ('H', (0, 0, 0.7414))]... | 09dbfcd2eb1b6105e6649056225cb1ed19abe4d7 | 617,014 |
def update_firm(bac, firm):
"""Update the Firmicutes slider."""
return 100 - bac | 626b46eb5c219737c053371329833f2c43ed1ca3 | 617,016 |
def float_if_not_none(value):
"""
Returns an float(value) if the value is not None.
:param value: None or a value that can be converted to an float.
:return: None or float(value)
"""
return None if value is None else float(value) | bd87c020fde2fe82bf9922f2b1023acc995a3449 | 617,017 |
def influxdb_config(influxdb):
"""
Returns the InfluxDB relation data as dict to use in config.
:param influxdb: InfluxDB relation data object
:type influxdb: InfluxdbClient
:returns: dict with InfluxDB configuration options
"""
return {
"host": influxdb.hostname(),
"port": ... | 37998190c20d894db925db4026a086e525fbcee4 | 617,018 |
def get_clipped_freq(records_l, records_r, records_s, minclip=4):
"""
Get the number of reads that are clipped over the breakpoints in a meaningful way. For the left and right
breakpoints, look for clipping in the SV. For the single breakpoint, look for clipping on either side of the read.
:param recor... | e3fe7374db78d4db2303aec2807e9e7d218cbd77 | 617,019 |
from typing import List
from typing import Dict
from typing import Any
def convert_list_to_comma_separated_string(values: List[Dict[str, Any]], key: str) -> str:
"""
Retrieve values of an attribute in comma separated manner from response to populate human readable output
:param: values: list of attribute... | 833254f3d95849016ee049fe4e76ee47db64e04a | 617,021 |
def decrement_items(inventory, items):
"""Decrement items in inventory using elements from the `items` list.
:param inventory: dict - inventory dictionary.
:param items: list - list of items to decrement from the inventory.
:return: dict - updated inventory with items decremented.
"""
for item... | b4e253ee07fcb37d7420e5ab4a84ce90d8fcb28f | 617,022 |
def verse(bottle):
""" Sing a verse """
current_bottle = '1 bottle' if bottle == 1 else f'{bottle} bottles'
next_bottle = 'No more bottles' if bottle == 1 else f'{bottle - 1} bottle' if bottle == 2 else f'{bottle - 1} bottles'
return '\n'.join([
f'{current_bottle} of beer on the wall,',
... | f1862b3f958c3e223d29bb52496fa301e687f28b | 617,023 |
import calendar
def utc_to_ts(y, m, d, hrs_utc):
"""Converts from a UTC tuple-time to unix epoch time.
y,m,d: The year, month, day for which the conversion is desired.
hrs_tc: Floating point number with the number of hours since midnight in UTC.
Returns: The unix epoch time.
>>... | d5e6efafe289040488aa36ad89da6a88641d43c9 | 617,025 |
def argmin(iterable):
"""Return index of minimum value."""
lowest_val = iterable[0]
lowest_i = 0
for i, val in enumerate(iterable):
if val < lowest_val:
lowest_val = val
lowest_i = i
return lowest_i | 18b25a02b7530e20927a153cb79f610a15abc350 | 617,026 |
def normalize_state(state):
"""Convert state into standardized (slurm style) state."""
state = state.lower()
if state == 'queued':
state = 'pending'
return state | 0ce871d4f7ba33dd2518036320aecce83ba24525 | 617,027 |
def set_file_content(file, content):
"""
write content to file
:param file: the file to rewrite its content
:param content: content to write to the given file
"""
nchar_written = 0
with open(file, 'w') as f:
nchar_written = f.write(content)
return nchar_written | 1d5e697a92d1239abf316c29def52504289d1392 | 617,029 |
def ensure_list(var):
"""Makes sure that `var` is a list.
Parameters
----------
var
List like object
Returns
-------
list
`var` as list
"""
return var if type(var) is list else [var] | 22be5103d49b13f426c3f5455b0dea7ebad26c57 | 617,031 |
def get_entry_by_filename(entries, fn, key=None):
"""Search for an entry in entries where key(entry['file']) matches
key(fn) and returns it. If key is None than file names are compared
directly. Returns None if none is found."""
if key is None:
key = lambda x: x
for e in entries:
i... | 2171acc8f63afa652c07c4a2965db5c7971683f3 | 617,032 |
import uuid
def CreateBudget(client):
"""Adds a new budget.
Args:
client: an AdWordsClient instance.
Returns:
A budget ID.
"""
budget_service = client.GetService('BudgetService', version='v201809')
budget = {
'name': 'Interplanetary budget #%s' % uuid.uuid4(),
'amount': {
'... | 68afa676b8784882efc2142e62c8d123397480e2 | 617,041 |
def _job_id_from_worker_name(name):
""" utility to parse the job ID from the worker name
template: 'prefix--jobid--suffix'
"""
_, job_id, _ = name.split("--")
return job_id | 033b4d20bfe57632b89bfe1c4de04de1e4476f34 | 617,044 |
def transpose_board(board):
"""Transpose the board --> change row to column"""
return [list(col) for col in zip(*board)] | a154fb452bb03ee45422fe83986ba4839144d13e | 617,047 |
from typing import Union
def sqrt(num: Union[int, float]) -> float:
"""
Get square root of num or negative square root of positive num if num is negative.
:param num: int, float
:return: float
>>> sqrt(0)
0.0
>>> sqrt(1)
1.0
>>> sqrt(81)
9.0
With negative number.
>>>... | 6abf7e732c001d24553550537e760b4143709821 | 617,048 |
def count_data(data, code = None):
"""Helper function that counts the number of data points in an arbitrary list of lists"""
if isinstance(data,list):
sum = 0
for d in data:
sum += count_data(d, code=code)
return sum
if data != '' and data != 'NA':
if code == None or data == code:
return 1
return 0 | 6fa25d54802e1cf37d77d317c55006357e110170 | 617,049 |
from typing import List
from typing import Set
def unique_answers(group: List[str]) -> Set[str]:
"""Finds the unique answers in a given group, that anyone gave."""
answers = set()
for member in group:
answers.update(answer for answer in member)
return answers | 5b363c46bcc6a3541290c0bdb72bc6a6c2f1d9f4 | 617,051 |
import re
def natural_keys(text):
"""Sort list of string with number in human order.
Examples
----------
>>> l = ['im1.jpg', 'im31.jpg', 'im11.jpg', 'im21.jpg', 'im03.jpg', 'im05.jpg']
>>> l.sort(key=tl.files.natural_keys)
... ['im1.jpg', 'im03.jpg', 'im05', 'im11.jpg', 'im21.jpg', 'im31.jpg'... | 92b63b281099c90fa08edcca29c01e83fc13b766 | 617,056 |
def get_cam_location_by_id(cam_id):
"""Get the location of the camera by its ID"""
lat = None # latitude
lng = None # longitude
if cam_id == 0: # clairton1
lat = 40.305062
lng = -79.876692
elif cam_id == 1: # braddock1
lat = 40.392967
lng = -79.855709
elif cam_id ... | 52b88b1835f85a77a830a4bab65213e18fdae510 | 617,058 |
def _simplify_features(df):
""" Remove 'standard error' columns from
the breast cancer dataset for simplicity
and replace spaces with underscores.
"""
simple = [col for col in df.columns if 'error' not in col]
simple_df = df[simple]
simple_df.columns = [col.replace(' ', '_') for col in simpl... | 83545b6f3c900887ea730dfeafa97a332c1acb89 | 617,061 |
import requests
import string
def count_capital_words_in_website(url: str) -> int:
"""
Given a URL, count the number of words which start with a capital letter
"""
text = requests.get(url).text
count = 0
for text_word in text.split():
if text_word[0] in string.ascii_uppercase:
... | 510706245783b9b1953804f41cf4a52f4d10b88f | 617,062 |
import struct
def unpack_linkmsg(data):
"""For *LINK RTNETLINK messages, unpack the body
Discards a number of uninteresting parts.
Returns if type, flags and remainder of message
"""
if_family, _, if_type, index, flags, change = struct.unpack("=BBHiII",
... | 7d84da34b3cb0fac1c03e757254436650455d74b | 617,064 |
from typing import Counter
def uniq_tokens_css(thresh, *collection_vals):
"""
Extract unique tokens in comma separated strings, contained in a collection,
return list of unique tokens that occur more than a threshold value.
Apply sorted to output for reproducible output.
"""
temp_lists = [... | 66ec0cd8f01b9d1121d942641d314b6e14721708 | 617,066 |
def valid_gain(gain):
"""
Use this parse an argument as if it were a float and get back a valid gain as a float.
Raises ValueError if passed an un-parse-able value.
"""
try:
my_gain = round(float(gain), 1)
except TypeError:
raise ValueError("Could not parse value as into a valid ... | 2dd48252812a408e8cc55cd0cbfc768096ca6d81 | 617,067 |
import re
def sanitize_query(query):
"""Remove special characters from a given query.
Args:
query:
str: String to sanitize
Returns:
A sanitized string without special characters.
"""
return re.sub(r"[^a-zA-Z0-9_]+", " ", query) | 5b29f835afcf4ca056b55b3e83b09b2a2f9b928d | 617,070 |
import re
def containsURL(line: str):
"""
Checks if the line contains any URLs
Parameters
----------
line : str\n
The string that needs to be checked if it countains URLs
Returns
-------
bool\n
True if it contains URL and False if no URL in 'line'
"""
... | 9886f7966dc61ed595d5ac2aab640fe26a717d35 | 617,071 |
def get_tbl_struct_info(content_tbl):
"""
get the structural information of a table, including:
- the number of columns
- the difference between the number of actual cells and the estimated cells
"""
tbl_struct = content_tbl[0].split(',')
tbl_struct = [int(val) for val in tbl_struct[1:]]
tbl_struct... | 49ff17aadfdd9b46c0667aa51a54504af571bc90 | 617,073 |
def time_std(xr_da, time_name="time"):
"""
Calculate standard deviation along the time axis of an `xarray.DataArray`.
Parameters
----------
xr_da: xarray.DataArray
Data array with a time coordinate.
time_name: str, optional
Name of t-coordinate
Returns
-------
xarra... | e33b473b0e44ea0d4961dfde3edd887fbbe5f2d7 | 617,078 |
def QLineEdit_parseVectors(lineedit):
"""
Return one or more component real vector as list from comma separated text in QLineEdit widget
or None if invalid.
"""
try:
text = lineedit.text()
values = [ float(value) for value in text.split(",") ]
return values
except:
... | 8137100564e20d1c36de4bb7c159db479b670bda | 617,079 |
def find_below(target, valid_data):
""" Finds the nearest valid cell below the target.
Parameters
----------
target: tuple
Indices of target cell
valid_data: np.array(logical)
Returns
-------
below_idx: tuple
Indices of valid cell immediately below target
"""
#... | c9489b8bb57094d730c3127b4b02d13296e25beb | 617,086 |
def _join_dictable_with_defaults(tbl_def1, tbl_def2):
"""
performs a join while allowing for a default
:Example:
--------------
>>> from pyg import *
>>> tbl_def1 = dictable(a = [1,2,3], b = [4,5,6]), dict(b=0)
>>> tbl_def2 = dictable(a = [2,3,4], c = [5,6,7]), dict(c=1)
>>> res = _... | 3b2e32479dd990563ec6e46bc622102e7946dab7 | 617,087 |
from typing import List
import copy
def get_flow_keys(results: dict) -> List[str]:
"""Get keys of optical flow in results.
Args:
results (dict): The data that includes data and meta information and
used in data augmentation pipeline.
Returns:
List: keys of optical flow in res... | ab700a78e5719232cc962a904d8b40ea181fab53 | 617,089 |
def has_units(qty, units):
"""
Test quantity (`qty`) for compatibility with given `units`.
.. note::
The following two expressions are equivalent:
1. ``chemtk.units.has_units(qty, units)``
2. ``qty.has_units(units)``
Parameters
----------
qty : :class:`Quantity... | 4496c02466ce9c99722955b4322a71cba55b80ed | 617,091 |
import torch
def _multiclass_accuracy(prediction, ground_truth):
"""
Computes metrics for multiclass classification
Arguments:
prediction, np array of int (num_samples) - model predictions
ground_truth, np array of int (num_samples) - true labels
Returns:
accuracy - ratio of accurate pre... | d8efb8b1adba5e8379313fbb8b1150d97ff23892 | 617,093 |
def is_tls_record_magic(d):
"""
Returns:
True, if the passed bytes start with the TLS record magic bytes.
False, otherwise.
"""
d = d[:3]
# TLS ClientHello magic, works for SSLv3, TLSv1.0, TLSv1.1, TLSv1.2
# http://www.moserware.com/2009/06/first-few-milliseconds-of-https.html#c... | 697171e44dfe981db219c5398342813babccb086 | 617,100 |
def fix_kwds(kwds_dict, **kwargs):
"""
Given a dictionary of plot parameters (kwds_dict) and a dict of kwds,
merge the parameters into a single consolidated dictionary to avoid
argument duplication errors.
If kwds_dict an kwargs have the same key, only the value in kwds_dict is kept.
Parameter... | 72b2bfabc9d4c0b804203de799bf576e07c7ed20 | 617,105 |
def percentage_of_num(percent, whole):
"""returns percent of a number. e.g. what is 5% of 20
"""
return (percent * whole) / 100.0 | 4e0fa707db651027c4dae5d6e008a21b0de754b1 | 617,106 |
def addExposures(exposureList):
"""Add a set of exposures together.
Parameters
----------
exposureList : `list` of `lsst.afw.image.Exposure`
Sequence of exposures to add.
Returns
-------
addedExposure : `lsst.afw.image.Exposure`
An exposure of the same size as each exposure... | f12733e78cda08232a34760adcadbf841858337d | 617,107 |
def spyOn(layers, names, verbose=False):
"""Add hooks to the specified layers to capture their outputs.
The outputs are stored in a dict(), with the names given as keys.
Args:
-layers : Array containing the model layers to spy on.
-names : Array containing the names of the layer, to be used as k... | 37c0f0581f1face7df87ba7b0cb2ee872788ee9c | 617,109 |
def filter_entry(node):
"""Filters on nodes of type entry"""
return node.type == "Entry" | dfc28e3e89b972e120a254dabf7b80f93460cdd9 | 617,110 |
import json
def get_course_urls(dept):
"""
Returns a list of all the course urls in the given department
"""
with open(f"data\{dept}_dict.json", 'r') as fp:
dept_dict = json.load(fp)
dept_urls = [k['url'] for k in list(dept_dict.values())]
return dept_urls | 1ede7de11e02534b10764affec00d9f3f4ca2a48 | 617,111 |
def get_emailids_query(conn_, query_='', qtype_='from', qexplicit_=False, **kwargs):
"""
Get all email ids from the emails after a simple query. Accepts explicit queries or one structures through query_ and qtype_
(Dev note: should be created more robust for future use!)
"""
assert qtype_.upper() ... | 25610a9c2fa1d8eeadac09c6cf34612df06ab1f9 | 617,113 |
def age_check(df):
"""
Checks age is within permitted bounds
If age is missing or outside bounds,
replaces age with median age
Parameters
----------
df : main dataset
Returns
-------
df : main dataset
adds age_admit column
"""
df.loc[df['age_admit'] > 110, 'age... | f432e5d7a4614e649693649ab04e3f26a5ff95d8 | 617,114 |
def keys_from_hash(hexdigest):
"""
Return a cache keys triple for a hash hexdigest string.
NOTE: since we use the first character and next two characters as directories, we
create at most 16 dir at the first level and 16 dir at the second level for each
first level directory for a maximum total of ... | ffa4a1685e92a1b9768ccf1efa206c4b7f8b0e85 | 617,115 |
def _convert_img_to_str(img):
"""
Convert an image in numpy array format, shape (1, height, width, depth), to a string. Depth is 1 for grayscale, 3 for RGB.
Returns:
img_string
height
width
depth
"""
# height, width, and depth are all going to be features in the seri... | ee5fd9be20de6325b5c1f1ee59272b30a8614ede | 617,118 |
def read_algin(filepath: str) -> str:
"""read word or phone alignment file.
<start-sample> <end-sample> <token><newline>
Args:
filepath (str): [description]
Returns:
str: token sepearte by <space>
"""
aligns = [] # (start, end, token)
with open(filepath, 'r') as f:
... | d91c66adbe260bce5020e60ba9d1513c68e5f8fb | 617,120 |
def list_instances(compute, resource_group):
"""Returns list of Azure instance resources for specified resource_group
:param compute: Azure object using ComputeManagementClient
:param resource_group: string, name of Azure resource group
:return: list of Azure VMs in resource_group
:rtype: list
... | 19372b17373d8885c30c7c1d28706218489077d7 | 617,121 |
import json
def read_dict(path):
""" Reads a dictionary from a file using JSON. This file should have been
written by write_dict.
:param path: complete path including file name for output file
:return: output dictionary from file
"""
with open(path) as file:
out_dict = json.load(f... | 0ded0580fb92412489d39ff97f98ba2c6c6321c3 | 617,123 |
import re
def remove_yaml_header(content: str) -> str:
"""删除 site 用的 md 文档中的 yaml 头
这些头信息,在简书或博客园中是多余信息,没有意义,所以需要去除
Args:
content (str): 带 yaml 的文章内容
Returns:
str: 删除 yaml 头的文章内容
"""
return re.sub(r"---\n.+?\n---\n{1,2}", "", content, flags=re.MULTILINE | re.DOTALL) | 790c2ce8fcb5fefe1f648fcb345331232e6522ec | 617,127 |
def get_chars_hashed_by_yoffset(csv_reader, precision, pages=None):
""" Hash the characters by the y-offset height rounded to [precision] decimals. """
line_hash = {}
for i, row in enumerate(csv_reader):
if pages:
if int(row['pageid']) not in pages:
continue
... | b9cbf0a31688565ccc63d0aa97fc64ff5c2ddd97 | 617,133 |
from datetime import datetime
def to_isoformat(date_str: str) -> str:
"""
Last-modified to isoformat
Sat, 27 Jun 2020 02:00:18 GMT => 2020-06-27T02:00:18
"""
return datetime.strptime(date_str, "%a, %d %b %Y %H:%M:%S %Z").isoformat() | e04e57a023d2332c0d92b8d898b8277884f63080 | 617,134 |
def calc_combined_lens(f1, f2, d):
"""Calculate focal length and principal planes of a compound lens.
Args:
f1: focal length of first lens
f2: focal length of second lens
d: distance
Returns:
f: effective focal length of combined lens
pp1: distance from first lens t... | 07581c78567be6ad4adfe56bac3abfad2802366d | 617,136 |
def bit_not(a: int) -> int:
"""
~ 取反
:param a:
:return:
"""
return ~a | fbf889e8a132792ecc818dba08e6642bd0401c9a | 617,139 |
import typing
def check_key_type(key: typing.Union[str, bytes]):
"""
Enforce the type of the key to bytes.
Parameters
----------
key: str | bytes
The key to check
Returns
-------
str
The key as bytes
"""
if isinstance(key, bytes):
return key
return... | 07da98b6d296b97d0e454668dc6da9f4840e2788 | 617,142 |
def obj_index(obj, key):
"""Get a key from an object"""
return (getattr(obj, "__getitem__", None) or getattr(obj, "__getattribute__"))(key) | 77bde9c35a44e8bb0ce3f664b186a9155f373862 | 617,143 |
import math
def r2d(r):
"""Convert radians into degrees."""
return math.degrees(r) | d90681a9d92332d10763da1b693695283dee1396 | 617,145 |
def utilSameType(agent, otherAgent, cutoff=1):
"""
matchUtilFct overload
utility = 1 if same type, 0 otherwise
"""
return cutoff * (agent.type == otherAgent.type) | 36714bf768113b2eddd240bb20ba922d875352a3 | 617,146 |
import types
def writer_checkout_only(wrapped, instance, args, kwargs) -> types.MethodType:
"""Only allow a method to be called in a write-enable checkout.
Parameters
----------
wrapped
bound method which is being called
instance
class object being operated on ie. ``instance is se... | 0d0ca3429218dadaf1087c6784092235f7678bbf | 617,149 |
def expected(A, B):
"""
Calculate expected score of A in a match against B
:param A: Elo rating for player A
:param B: Elo rating for player B
"""
return 1 / (1 + 10 ** ((B - A) / 400)) | dba74e15081c3792026e3b5abf0cee4e849b714a | 617,150 |
def _TestPath(test_name, chart_name, trace_name):
"""Get the slash-separated test path to send.
Args:
test: Test name. Typically, this will be a top-level 'test suite' name.
chart_name: Name of a chart where multiple trace lines are grouped. If the
chart name is the same as the trace name, that sig... | 93efa64931d9631dde62bb8e803f342e66588c43 | 617,151 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.