content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def normalize_vector(v):
"""
Takes in a vector in list form, concatenates it to form a single vector,
normalizes it to unit length, then returns it in list form together with its norm.
"""
norm_val = np.linalg.norm(np.concatenate(v))
norm_v = [a / norm_val for a in v]
return norm_v, n... | 61,800 |
def clean_data(df):
"""Clean categories and merge to messages
Args:
df => DataFrame of merged categories and messages csv files
Returns:
df => Dataframe of cleaned categories and dropped duplicates
"""
categories = pd.Series(df.categories).str.split(';', expand=True)
row = catego... | 61,801 |
def test_get_committed_sc_mixed_object_class_1100():
"""Test getting the committed sync count with mixed object classes."""
# Insert Committed and Following Committed Session Rows #
cursor, cnx, errno = open_db()
assert None == errno
statement = """INSERT INTO SyncCount (objectClass, isCommitted)
... | 61,802 |
def main(_):
"""config.py の CLASSES、もしくは引数で検索を実施."""
os.makedirs(DOWNLOAD_PATH, exist_ok=True)
if _.query:
query_list = [_.query]
else:
query_list = CLASSES
for query in query_list:
download(query) | 61,803 |
def vote():
"""
/vote
description: Seconds the proposal
vote: Vote on a Referendum either "yes" or "no"
ref_index: the value returned from /get_ref or use PropIndex
Request payload
{
'spider_id' : 'xxxx',
'phrase' : '...',
'ref_index' : '4',
'vote': 'ye... | 61,804 |
def getAllModules():
"""
Returns a list of all modules that should be checked.
@rtype: list of L{pcmodules.PyCheckerModule}
"""
modules = []
for module in pcmodules.getPCModules():
if module.check:
modules.append(module)
return modules | 61,805 |
def ExampleOne_PartFive_MaskBasinsMF(DataDirectory, fname_prefix):
"""
This function makes a shaded relief plot of the DEM with the basins coloured
by the basin ID.
Args:
DataDirectory (str): the data directory with the m/n csv files
fname_prefix (str): The prefix for the m/n csv files
... | 61,806 |
def load_matrix_flexible(matrix_file: str) -> ndarray:
"""Load a matrix data from .tiff, .npy or .txt file."""
path = Path(matrix_file)
if path.suffix in (".tiff", ".tif"):
return load_img(matrix_file)
elif path.suffix == ".npy":
return np.load(matrix_file)
elif path.suffix == ".txt"... | 61,807 |
def sp2torch(sparse_mx):
"""Convert a scipy sparse matrix to a torch sparse tensor."""
sparse_mx = sparse_mx.tocoo().astype(np.float32)
indices = torch.from_numpy(np.vstack((sparse_mx.row, sparse_mx.col)).astype(np.int64))
values = torch.from_numpy(sparse_mx.data)
shape = torch.Size(sparse_mx.sha... | 61,808 |
def Distribution_of_masses(**kwds):
"""
输出双黑洞质量的分布。(ratio_step 不能小于 0.01,可以通过增大 doa=100 提高精度)
Input:
共有三种输入方式,如下面的例子:
Eg1: mass1_scope = (5,75), mass2_scope = (5,75), mass_step = 2
Eg2: mass1_scope = (5,75), mass_step = 2, ratio_scope = (0.1,1), ratio_step = 0.1
Eg3: Mass_scope = (5, 30... | 61,809 |
def run_command(command, cwd=None):
# type: (List[str], str) -> List[str]
""" Run a given command and report the execution.
:param command: array of tokens
:param cwd: the working directory where the command will be executed
:return: output of the command
"""
def decode_when_needed(result):... | 61,810 |
def DecodePublic(curve, bb):
"""
Decode a public key from bytes. Invalid points are rejected. The
neutral element is NOT accepted as a public key.
"""
pk = curve.Decode(bb)
if pk.is_neutral():
raise Exception('Invalid public key (neutral point)')
return pk | 61,811 |
def parse_result_page(html):
"""
"""
dfs = []
for df in pd.read_html(html, thousands=' '):
grouper = df.columns[0]
value_cols = df.columns[1:].tolist()
df.columns = ["group"] + value_cols
df_long = pd.melt(df, id_vars="group", value_vars=df.columns[1:],
... | 61,812 |
def _read_schema(proto_path):
"""Reads a TF Metadata schema from the given text proto file."""
result = schema_pb2.Schema()
with open(proto_path) as fp:
text_format.Parse(fp.read(), result)
return result | 61,813 |
def test_round_pick_draft(pick_number=1, round_number=7):
"""
Test function to check that draft_pick function returns
correct information with specified parameters.
Keyword Arguments:
pick_number {int} -- default pick_number to query (default: {'1'})
round_number {int} -- round_number t... | 61,814 |
def compact(it):
"""Filter false (in the truth sense) elements in iterator."""
return filter(bool, it) | 61,815 |
def export(export_file_type, filename, exporter_name=None):
""" Convert a file to another type and download that file.
:param export_file_type: the type to export a file as
:param filename: file to be exported
:param exporter_name: optional name of the specific exporter module
"""
try:
... | 61,816 |
def session_capabilities(session_capabilities):
"""Log browser (console log) and performance (request / response headers)
data.
They will appear in `Links` section of pytest-html's html report.
"""
session_capabilities["loggingPrefs"] = {
"browser": "ALL",
"performance": "ALL"
}
return session... | 61,817 |
def test_only_setup_missing(
capsys, tmp_path, shared_datadir, source_pipfile_dirname, update_count
): # type: (Any, Path, Path, str, int) -> None
"""
test setup.py generation (when it is missing)
"""
pipfile_dir = shared_datadir / source_pipfile_dirname
expected_setup_text = (pipfile_dir /... | 61,818 |
def find_nearest(arr, val):
"""Find index(es) of "nearest" value(s).
Parameters
----------
arr : array_like (ND)
The array to search in (nd). No need to be sorted.
val : scalar or array_like
Value(s) to find.
Returns
-------
out : tuple
The index (or tuple if nd... | 61,819 |
def calculate_overlap_rate(inventor_class_nbr_group_count_dict):
"""
计算交叠率
:param inventor_class_nbr_group_patent_count:
:return:
"""
#发明家的总数
inventor_cnt = len(inventor_class_nbr_group_count_dict.keys())
#无法分组的发明家数量
cant_group_inventor = 0
for inventor, class_nbr_group... | 61,820 |
def _parse_mock_imports(mod_ast, expanded_imports):
"""Parses a module AST node for import statements and resolves them against
expanded_imports (such as you might get from _expand_mock_imports).
If an import is not recognized, it is omitted from the returned dictionary.
Returns a dictionary suitable for eval... | 61,821 |
def init_distributed_mode(args: Any) -> None:
"""Initialise regarding the distribution mode."""
if "RANK" in os.environ and "WORLD_SIZE" in os.environ:
args.rank = int(os.environ["RANK"])
args.world_size = int(os.environ["WORLD_SIZE"])
args.gpu = int(os.environ["LOCAL_RANK"])
elif "S... | 61,822 |
def to_numpy(array: Union[pa.Array, pa.ChunkedArray]):
"""For non-chunked arrays, need to pass zero_copy_only=False."""
if isinstance(array, pa.ChunkedArray):
return array.to_numpy()
return array.to_numpy(zero_copy_only=False) | 61,823 |
def merge_coord_and_label_files(ROI_coords_dir):
"""
utils for merging different label and coord file before computing label masks if necessary
should be rewritten to more more general with glob("Coord*.txt) and glob("Labels*.txt)...
"""
import os
import numpy as np
list_coords = []
... | 61,824 |
def get_model(inputs, max_length, dim=25):
"""
input - vocabulary size, a number of unique words in
our data set
max_length - the maximum length of each sequence of words
(a document)
dim - word embedding dimension, the lenght of word vector
that will be produced... | 61,825 |
def calc_field_size(field_type, length):
"""
Рассчитывает размер данных поля
:param field_type: Тип поля
:type field_type: string
:param length: Длина поля
:type length: int
:return: Длина поля в байтах
:rtype: int
"""
if field_type == 'B':
return length
elif field_t... | 61,826 |
def local_channel(obj):
"""
Return the parallel region local channel number `obj` is executing in.
The channel number is in the range of zero to ``local_max_channel(obj)``.
Args:
obj: Instance of a class executing within Streams.
Returns:
int: Parallel region local channel num... | 61,827 |
def import_results(file_name):
"""Import scientific instrument data. The routine is as follows:
1. Read in all the excel sheets at one time.
2. Get the sample name.
3. Get and tidy the compound data from the compound sheet.
4. Add the analyte names and measurements to a list of resul... | 61,828 |
async def raw_reaction_add(payload: discord.RawReactionActionEvent):
"""
Helper to handle a raw reaction added on discord
"""
# Try to fetch channel without API call first
channel = common.bot.get_channel(payload.channel_id)
if channel is None:
try:
channel = await common.bo... | 61,829 |
def SortByName(list_response):
"""Return the list_response sorted by name."""
return sorted(list_response, key=lambda x: x.name) | 61,830 |
def calculateTetTwt(C):
"""Calculate tetanus/twitch ratio.
Calculate the tetanus/twitch ratio for every sigmoid with
parameter c in vector C.
Parameters
----------
C : 1-D array, float
Sequence of values to be used as parameter of a sigmoid function.
Returns
------... | 61,831 |
def save_results(trainer, base_fname='figure_data_', store_x=True):
"""
Save the function trace for different optimizers for a
given model to a .npz file.
"""
if not store_x:
# delete the saved final x value so we don't run out of memory
trainer.history['x'] = defaultdict(list)
... | 61,832 |
def jwt_encode(
payload: dict[str, any],
secret: Optional[str] = None,
algo: Optional[str] = None,
) -> str:
"""Encode payload into a JWT"""
return jwt.encode(
payload,
secret or current_app.config["SECRET_KEY"],
algorithm=algo or current_app.config["JWT_ALGORITHM"],
) | 61,833 |
def test_construct_sign_and_submit_transfer_transaction():
"""Test the construction, signing and submitting of a transfer transaction."""
account = FetchAICrypto()
balance = get_wealth(account.address)
assert balance > 0, "Failed to fund account."
fc2 = FetchAICrypto()
fetchai_api = FetchAIApi(*... | 61,834 |
def specs_free_photoz_info(my_photoz_info):
"""specs_free_photoz_info(user_pz_info my_photoz_info)"""
return _ccllib.specs_free_photoz_info(my_photoz_info) | 61,835 |
def index(filename, format=None, key_function=None, **kwargs):
"""Indexes a search output file and returns a dictionary-like object.
- filename - string giving name of file to be indexed
- format - Lower case string denoting one of the supported formats.
- key_function - Optional callback ... | 61,836 |
def parse_png_to_mpeg2ts_stream(file_path: str) -> None:
"""
Strip the mpeg2-ts data from a file.
Parameters
----------
file_path: str
The file_path to be converted to mpeg2-ts, note this function assumes that the file will
be detected as png due to starting bytes, and re parse it a... | 61,837 |
def test_channel_declaration4():
"""Test declaring channel aliases.
"""
class DeclareChannel(DummyParent):
ch = channel((1, 2))
class OverrideChannel(DeclareChannel):
ch = channel(aliases={1: 'Test', 2: ('a', 'b')})
class OverrideChannel2(OverrideChannel):
ch = channel... | 61,838 |
def _save_story(committer_id, story, commit_message, change_list):
"""Validates a story and commits it to persistent storage. If
successful, increments the version number of the incoming story domain
object by 1.
Args:
committer_id: str. ID of the given committer.
story: Story. The stor... | 61,839 |
def sync(local_to_remote):
"""Syncs git tags. Remote to local."""
if local_to_remote:
sync_local_to_remote()
else:
sync_remote_to_local() | 61,840 |
def write_line(file_name, line):
"""
将行数据写入文件
:param file_name: 文件名
:param line: 行数据
:return: None
"""
if file_name == "":
return
with io.open(file_name, "a+") as fs:
if type(line) is (tuple or list):
fs.write("%s\n" % ", ".join(line))
else:
... | 61,841 |
def equal_two_arrays(array1, array2, eps, tolerance, throwError=True):
"""
This function will compare the values of two python tuples. First, if the values are below
eps which denotes the significance level that we care, no comparison is performed. Next,
False is returned if the different between any ... | 61,842 |
def additive_attention(query, memory, mem_mask, hidden_size,
ln=False, proj_memory=None, num_heads=1,
dropout=None, scope=None):
"""
additive attention model
:param query: [batch_size, dim]
:param memory: [batch_size, seq_len, mem_dim]
:param mem_mask: [... | 61,843 |
def radec_to_xyz(ra_deg, dec_deg):
""" Convert RA and Dec to xyz positions on a unit sphere.
Parameters
----------
ra_deg, dec_deg : float or arrays of floats, shape (N,)
RA and Dec in degrees.
Returns an array of floats with shape (N, 3).
"""
ra = np.asarray(ra_deg) * RAD_PER_DE... | 61,844 |
def sample_hybrid_zprior_xmetro(network, niter, nprior, nmetro, prior_std=1.0, noise=0.02, z0=None, x0=None,
mapper=None, verbose=0):
""" Samples iteratively using Prior MCMC in z-space and Metropolis MCMC in z-space
Parameters
----------
network : network
Latent... | 61,845 |
def multiplex_modularity(B, mu, membership):
"""Calculates a multiplex modularity score.
Calculates the modularity from a given modularity matrix and membership
vector.
Args:
B (scipy.sparse.csr_matrix): An n by n sparse modularity matrix where
n is the number of vertices across al... | 61,846 |
def unindent(string):
"""Remove the initial part of whitespace from string.
>>> unindent("1 + 2 + 3\\n")
'1 + 2 + 3'
>>> unindent(" def fun():\\n return 42\\n")
'def fun():\\n return 42'
>>> unindent("\\n def fun():\\n return 42\\n")
'def fun():\\n return 42'
>>> unindent(" d... | 61,847 |
def unpackdict(table, field, keys=None, includeoriginal=False,
samplesize=1000, missing=None):
"""
Unpack dictionary values into separate fields. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar'],
... [1, {'baz': 'a', 'quux': 'b'}],
... ... | 61,848 |
def is_collection(path):
"""Check if the collection exists"""
return Collection.find(path) is not None | 61,849 |
def dump(obj, name, opener=open):
"""Dump an object to the named file using cloudpickle."""
with opener(name, "wb") as f:
cloudpickle.dump(obj, f) | 61,850 |
def download_file(url, download_dir: str):
"""
https://stackoverflow.com/a/53153505/12988588
"""
response = calls.ping_url(url)
filename = url.split("/")[-1]
if len(download_dir) > 0:
os_makedirs(download_dir, exist_ok=True)
out_filepath = os_path.join(download_dir, filename)
wi... | 61,851 |
def conv2d_padding_size(
h_w_in: Union[int, Tuple[int, int]],
h_w_out: Union[int, Tuple[int, int]],
kernel_size: int = 1,
stride: int = 1,
dilation: int = 1,
) -> Tuple[Tuple[int, int], Tuple[int, int]]:
"""
:param h_w_in:
:type h_w_in:
:param h_w_out:
:type h_w_out:
:param ... | 61,852 |
def classifyContourListsNodePathBayes(dataViewer,
probabilityFunction,
contourListsNodePath):
"""Deprecated. Naive Bayes classification strategy."""
contourListsNode =\
dataViewer.mainDoc.dataTree.getSubtree(contourListsNodePat... | 61,853 |
def register_user(email, name, password, password2):
"""
Register the user to the database
:param email: the email of the user
:param name: the name of the user
:param password: the password of user
:param password2: another password input to make sure the input is correct
:return: an error ... | 61,854 |
def ShowZTracesAbove(cmd_args=None):
""" Prints all traces with size greater than X
Usage: showztracesabove <size>
"""
if not cmd_args:
print ShowZTracesAbove.__doc__
return
print '{0: <5s} {1: <6s}'.format('INDEX','SIZE')
current_index = 0
ztrace_count = 0
max_ztrace... | 61,855 |
def GetIntervalVarFromMatlab(doc:NexDoc, MatrixName):
"""Imports the specified matrix containing intervals from Matlab."""
return NexRun("GetIntervalVarFromMatlab", locals()) | 61,856 |
def get_display_backend_size():
"""Function to get the display backend size resolution
:return : display resolution size as x,y
:rtype : integer
"""
xc, yc = default_display_backend_size.split('x')
x = int(xc)
y = int(yc)
return x, y | 61,857 |
def _skip_block(
lines: Sequence[bytes],
sline: int,
scol: int,
sstr: bytes,
estr: bytes,
skips: Optional[Mapping[bytes, SkipFun]] = None,
) -> Optional[Tuple[int, int]]:
"""A generic function to skip the next block contained in sstr estr."""
assert lines[sline].startswith(sstr, scol)
... | 61,858 |
def get_database_connection(file_path, timeout=0.0):
"""
Gets a Connection to an Sqlite Database
:param timeout: how long in seconds the driver will attempt to execute a statement before aborting.
:param file_path: path to the sqlite database
:return: a connection to the database
"""
db_co... | 61,859 |
def cartesian_product(p_dict):
"""
Compute Cartesian product on parameter dict:
In:
{"number": [1,2,3], "color": ["orange","blue"] }
Out:
[ {"number": 1, "color": "orange"},
{"number": 1, "color": "blue"},
{"number": 2, "color": "orange"},
{"number": 2, "col... | 61,860 |
def normalize(vector, pre_computed=None):
"""Return the normalized version of a vector.
Parameters
----------
vector : np.array
pre_computed : float, optional
The pre-computed norm for optimization. If not given, the norm
will be computed.
"""
n = pre_computed if pre_compute... | 61,861 |
def has_valid_padding(cipher_bytes):
"""
Decrypt cipher_bytes using AES CBC mode, then ...
- return True if it has valid padding (PKCS7)
- otherwise (catch an Exception for padding) return False
"""
# NOTE: This function is the padding oracle. It only return True or False on padding... | 61,862 |
def test_sample_numbers_trajectory():
"""Test `pyabc.visualization.plot_sample_numbers_trajectory`"""
pyabc.visualization.plot_sample_numbers_trajectory(
histories, labels, yscale='log', rotation=90
)
_, ax = plt.subplots()
pyabc.visualization.plot_sample_numbers_trajectory(
historie... | 61,863 |
def account_unlock(account, token):
"""
Unlock account
Note that if you call account_lock, you must always unlock account,
otherwise it will be locked until process restart
"""
if config.keep_integrity:
with lock_account_token:
l = account_lockers.get(account.upper())
... | 61,864 |
def activate_detection(timeout: int = 10000) -> str:
"""Active sound detection
Parameter:
timeout: duration of detection default 10 sec
(value in milisec)
"""
msg = 'Sound detected in the room !'
no_sound_msg = "No sound detected in the room."
# waiting for edge cases for sete... | 61,865 |
async def get_ohlcv(ticker: str = "KRW-BTC",
interval: str = "day",
count: int = 200,
to: str = None,
contain_req: bool = False) -> tuple or DataFrame:
"""Candle data request
Args:
ticker (str, optional): Coin's ticker. De... | 61,866 |
def reset_window_environment() -> BoxLayout:
"""Remove PythonHere app widgets and styles."""
# import Window inside function to avoid early loading of the app config
from kivy.core.window import Window # pylint: disable=import-outside-toplevel
for widget in Window.children:
widget.clear_widget... | 61,867 |
def select_frame(img, img_width_margin, img_height_margin):
"""
This function handles the drag and drop frame selection event.
This is the first part of a three stage labeling process. After selecting
the frame's coordinates it gives those to a function which creates a Frame
object that functio... | 61,868 |
def partition_sequentially(
items: Iterable[_T],
*,
key: Callable[[_T], str],
size_target: int,
size_max: int | None = None,
) -> Iterator[list[_T]]:
"""Stably partitions the given items into batches of around `size_target` items.
The "stability" property refers to avoiding adjusting all ba... | 61,869 |
def quad_kappa_loss(input, targets, y_pow=1, eps=1e-15):
"""
https://github.com/JeffreyDF/kaggle_diabetic_retinopathy/blob/master/losses.py#L22
:param input:
:param targets:
:param y_pow:
:param eps:
:return:
"""
batch_size = input.size(0)
num_ratings = 5
assert input.size(1... | 61,870 |
def parse_response(xml):
"""
Converts the response into an XML element
"""
# Uncomment for debugging
# print("Parsing xml: {}".format(xml))
return ET.fromstring(xml) | 61,871 |
def test_3d_numpy_input(Estimator):
"""Test classifiers handle 3D numpy input correctly."""
estimator = Estimator.create_test_instance()
fit_args = _make_args(estimator, "fit", return_numpy=True)
estimator.fit(*fit_args)
for method in NON_STATE_CHANGING_METHODS:
if _has_capability(estimator... | 61,872 |
def help():
"""
@summary: Print help in console
"""
print """
Usage: rdpy-rdphoneypot.py
[-L logfile]
[-l listen_port default 3389]
[-k private_key_file_path (mandatory for SSL)]
[-c certificate_file_path (mandatory for SSL)]
rss_filep... | 61,873 |
def clamp_remaining(max_timeout: float) -> float:
"""Return the remaining timeout clamped to a max value."""
timeout = remaining()
if timeout is None:
return max_timeout
return min(timeout, max_timeout) | 61,874 |
def is_tag_exists(
lf_client,
account_id: str,
key: str,
) -> bool:
"""
Check if an Lake Formation tag exists or not
Ref: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/lakeformation.html#LakeFormation.Client.get_lf_tag
"""
try:
lf_client.get_lf_tag(C... | 61,875 |
def browse_repository(script, project, repository):
"""
Gets the list of repositories for the specified project
:param script: A TestScript instance
:type script: TestScript
:param project: The project for the repository
:type project: str
:param repository: The repository to browse
:typ... | 61,876 |
def baseline(saver, model, y, data, T, lr, lmd=None, name='baseline'):
# TODO other optimizers?
"""
BASELINE EXECUTION (valid also for oracle and final training,
with optimized values of lambda)
:param saver: `Saver` object (can be None)
:param name: optional name for the saver
:param data:... | 61,877 |
def build_node_statistics(nodes, images):
"""Build a dictionary of cache statistics about a group of nodes."""
# Generic statistics applicable to all groups of nodes.
node_statistics = {
'provisioned': len(list(filter(lambda n: n.provisioned, nodes))),
'not provisioned': len(list(filter(lamb... | 61,878 |
def track_local_coordinate_systems(
markers: TimeSeries,
/,
segments: Union[str, Sequence[str]],
*,
method: int = 1) -> TimeSeries:
"""
Create local coordinate system definitions based on static markers.
Parameters
----------
markers
TimeSeries that c... | 61,879 |
def select_white(image):
"""
Threshold to select a white color objects
:param image: Undistorted image
:return: Thresholded image
Ref: Udacity reviewer suggestion
"""
lower = np.array([210, 210, 210])
upper = np.array([255, 255, 255])
mask = cv2.inRange(image, lower, upper)
retur... | 61,880 |
def is_libpsp():
"""Was libbinding successfully loaded in this module?"""
return __is_libpsp__ | 61,881 |
def test_FN125_str():
"""
Verify that the string representation of a FN125 object is the
project code followed by sample number, effort, species code,
group code and fish number each separated by a dash.
e.g. - LHA_IA00_123-001-051-091-00-1
"""
project_code = "LHA_IA00_123"
sam = "001... | 61,882 |
def make_dirs(directory):
"""
Checks if a directory exists and creates it if it doesn't.
Parameters
----------
:param directory: string
complete path to the directory to be created.
"""
if not os.path.exists(directory):
os.makedirs(directory, 0o755) | 61,883 |
def cluster_report(ref, pred, classes):
"""
Print Cluster Report
"""
pred = reassign_cluster_with_ref(pred, ref)
cm = confusion_matrix(ref, pred)
print('\n## Confusion matrix ##\n')
print(cm)
print('\n## Cluster Report ##\n')
print(classification_report(ref, pred, target_names=classe... | 61,884 |
def run_batch(args: dict) -> int:
"""Runs a batch operation for the given arguments."""
batcher.run_project(
project_directory=args.get('project_directory'),
log_path=args.get('logging_path'),
output_directory=args.get('output_directory'),
shared_data=load_shared_data(args.get('s... | 61,885 |
def prepare(statement, variables, extra_data={}):
"""
Set variable in statement and return the prepared statement
"""
template = Template(statement)
data = extra_data.copy()
for variable in variables:
if variable == S.LOGIN_VARIABLE:
data[variable] = Settings().get_github_log... | 61,886 |
def privatekey_to_publickey(private_key_bin: bytes) -> bytes:
""" Returns public key in bitcoins 'bin' encoding. """
if not ishash(private_key_bin):
raise ValueError('private_key_bin format mismatch. maybe hex encoded?')
return keys.PrivateKey(private_key_bin).public_key.to_bytes() | 61,887 |
def single_value_rnn_regressor(num_units,
sequence_feature_columns,
context_feature_columns=None,
cell_type='basic_rnn',
num_rnn_layers=1,
optimizer_type='SGD',
... | 61,888 |
def log_event(event):
"""
Log a structured job event into log file
Parameters
----------
event: :obj:`StructuredLogEvent`
An instance of :obj:`StructuredLogEvent`
"""
logger = logging.getLogger(_EVENT_LOGGER_NAME)
logger.info(event) | 61,889 |
def k_fold(
n_splits,
epochs,
batch_size,
transforms,
criterion,
model,
dataset,
device):
"""
Perform K-fold cross validation.
Parameters
----------
n_splits: int
Number of splits to make of the data.
epochs: int
Nu... | 61,890 |
def render_instruction(name, content):
""" Render an arbitrary in-line instruction with the given name and
content """
return ':{}: {}'.format(name, content) | 61,891 |
def test_all_options_are_added(parser, opt):
""" If requested, all of the standard logging options are added. """
assert opt not in _get_optnames(parser)
add_logging_options(parser)
assert opt in _get_optnames(parser) | 61,892 |
def check_nan_columns(df: pd.DataFrame) -> pd.Series:
"""Check whether the columns of the DataFrame object contain missing
values.
Arguement:
df: the DataFrame object to be checked whether its columns contain the
missing values
Return:
_: the Series object whose values are True ... | 61,893 |
def test_resolve_non_fully_qualified_url(db_mock, app):
"""Tests that it resolves a track url when not fully qualified"""
with app.test_request_context():
with db_mock.scoped_session() as session:
url = '/urbanbankai/mb-shola-vivienne-%22westwood%22-87325'
resolved_url = resolve_... | 61,894 |
def site_time() -> Timestamp:
"""Wrapper for site server time."""
return _site.server_time() | 61,895 |
def contract_id(owner_id, nonce):
"""
Compute the contract id of a contract
:param owner_id: the account creating the conctract
:param nonce: the nonce of the contract creation transaction
"""
return hash_encode("ct", decode(owner_id) + _int(nonce)) | 61,896 |
def json_patch_link(url, title, description):
"""Generate a json patch Link object."""
return serializers.Link(
url=url,
title=title,
description=description + " (Using an RFC6902 JSON Patch)",
action="patch",
) | 61,897 |
def smoothing(outmap, inmap, sigma, sigmacut = 3, verbose = False,
renormalize_kernel = False):
"""
Kernel smoothing of harpix maps in real space.
Works best for small patches of the sky. For the convolution of full sky maps
use standard healpy routines, based on spherical harmonics.
NOTE... | 61,898 |
def sign_up_post(request: HttpRequest, *args, **kwargs):
"""用户邮箱验证注册。"""
body = json.loads(request.body)
if keys_missed(body, ['email', 'password', 'code']):
response = HttpResponse(MSG_BAD_REQUEST, status=400)
else:
exists = User.objects.filter(email=body['email'])
if len(exis... | 61,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.