content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def post_authorizables(authorizable_id, intermediate_path, create_user=None, create_group=None, reppassword=None, profilegiven_name=None): # noqa: E501
"""post_authorizables
# noqa: E501
:param authorizable_id:
:type authorizable_id: str
:param intermediate_path:
:type intermediate_path: s... | 42c7fcffebf623030c791790973455228646696a | 665,779 |
def add_segment_final_space(segments):
"""
>>> segments = ['Hi there!', 'Here... ', 'My name is Peter. ']
>>> add_segment_final_space(segments)
['Hi there! ', 'Here... ', 'My name is Peter.']
"""
r = []
for segment in segments[:-1]:
r.append(segment.rstrip()+' ')
r.append(segment... | 6593cbd325cac7a102ec21a7bfc16e22e74dc31f | 665,780 |
def construct_publish_comands(additional_steps=None):
"""Get the shell commands we'll use to actually build and publish a package to PyPI.
Returns:
List[str]: List of shell commands needed to publish a module.
"""
return (additional_steps or []) + [
"python setup.py sdist bdist_wheel",... | ec1a1512e47a9839ea9d23ba7c23a44485a2c503 | 665,781 |
def max_ones(n):
""" Given a base-10 integer,n , convert it to binary (base-2).
Then find and print the base-10 integer denoting the maximum number of consecutive 1's in n's binary representation.
When working with different bases, it is common to show the base as a subscript."""
print(bin(n))
resul... | 85286dba31898c0c418623cf2ac1e4cc4a0dbdbc | 665,782 |
import math
def get_shanno_entropy(values):
"""
根据给定列表中的值计算其Shanno Entropy
"""
uniq_vals = set(values)
val_nums = {key: values.count(key) for key in uniq_vals}
probs = [v / len(values) for k, v in val_nums.items()]
entropy = sum([-prob * math.log2(prob) for prob in probs])
return entro... | 09f404c8a8fbb2696b933dc4c1e55a9b07dc304b | 665,784 |
def n_lexemes_for_lemma(conn, language_code, lemma) -> int:
"""Get the number of dictionary entries with ``lemma`` as headword.
:param conn: The database connection for the dictionary.
:param str language_code: ISO 639-3 language code of the language of interest.
:param lemma: A dictionary that con... | 9b66d78931921127afa5d0739d86f00d649f9b21 | 665,785 |
def _get_binary_op_bcast_shape(lhs_shape, rhs_shape):
"""Get the shape after binary broadcasting.
We will strictly follow the broadcasting rule in numpy.
Parameters
----------
lhs_shape : tuple
rhs_shape : tuple
Returns
-------
ret_shape : tuple
"""
ret_shape = []
if l... | 2461caa4a720bf178f0aef85d74ca783db6e6cce | 665,786 |
def Influence(Weight):
"""Takes a normalized Vector (one that sums to 1), and computes relative strength of the indicators."""
N = len(Weight)
Expected = [[1/N]]*N
Out = []
for i in range(1, N):
Out.append(Weight[i]/Expected[i])
return(Out) | ec549a98f715e9abb4368af7adcf804277caee11 | 665,787 |
def _get_value_from_line(line):
"""Parses the values from incoming line"""
comment=None
if '=' not in line:
value = True
return value, comment
else:
# if ends with comments, take them out
# if sameline comments are NOT seperated by a whitespace
# they are conside... | 5a23d82cbf4707380f8e8ab16f1908ae913d80e6 | 665,788 |
def _sort_key_max_confidence_sd(sample, labels):
"""Samples sort key by the maximum confidence_sd."""
max_confidence_sd = float("-inf")
for inference in sample["inferences"]:
if labels and inference["label"] not in labels:
continue
confidence_sd = inference.get("confidence_sd", f... | f0be3921c40edbe7648c580874424b065b0c1dde | 665,789 |
import sys
def import_module(name):
"""Lazy impor _module"""
__import__(name)
return sys.modules[name] | e1da9b64601e6e0da05b8f4695986d02bc786bba | 665,791 |
def reassemble_addresses(seq):
"""Takes a sequence of strings and combines any sub-sequence that looks
like an IPv4 address into a single string.
Example:
['listener', '0', '0', '0', '0_80', downstream_cx_total'] ->
['listener', '0.0.0.0:80', 'downstream_cx_total']
"""
reassembled =... | 93395113428c5d905917593f59c6bf2b3361b506 | 665,792 |
import operator
def best_assembly(assembly_list):
"""Based on assembly summaries find the one with the highest scaffold N50"""
if assembly_list:
return sorted(assembly_list, key=operator.itemgetter('scaffoldn50'))[-1] | 44aab301c2eba9c8caa24134a4f75606d2eb0d54 | 665,794 |
import math
def compute_distance(x1, y1, x2, y2):
"""Compute the distance between 2 points.
Parameters
----------
x1 : float
x coordinate of the first point.
y1 : float
y coordinate of the first point.
x2 : float
x coordinate of the second point.
y2 : float
... | 38cbf3ee7c94daf7b241b8907328b971fc3eea49 | 665,795 |
def get_version_integer(version):
"""Get an integer of the OGC version value x.y.z"""
if version is not None: # split and make integer
xyz = version.split('.')
if len(xyz) != 3:
return -1
try:
return int(xyz[0]) * 10000 + int(xyz[1]) * 100 + int(xyz[2])
e... | a371a43bff4977fbdf068a0b1801c61b3b6c8b22 | 665,796 |
import os
import shutil
def copyFile(file_path, dest_dir):
""" Copy a file to a new directory, preserving its filename.
Parameters
----------
file_path : str
Path to the file that will be copied.
dest_dir : str
Path to the directory where the copy will be placed.
Returns
... | 5d0185ea936dcf21ec32a42ebaae8af222c562da | 665,797 |
import requests
def download(url: str) -> bytes:
"""
Download a file from the internet using a GET request. If it fails for any
reason, an exception is raised. For more complicated behavior, use an
HttpAgent object.
Returns the bytes of the downloaded object.
"""
resp = requests.get(url, stream=True)
if not... | b36925edb5ad79ffcc412ab09dd096662e15761c | 665,798 |
import os
def generate_initialisation_vector():
"""
Generates a 128 bits initialisation vector.
Uses ``/dev/urandom`` on UNIX platforms, and ``CryptGenRandom`` on Windows.
:return: the 128 bits initialisation vector
:rtype: bytes
"""
return os.urandom(16) | db8954b107134327466278b4e1c7ff73fc101481 | 665,799 |
def _get_headers(data):
"""
get headers from data
:param data: parsed message
:return: headers
"""
headers = {}
data = str(data, encoding="utf-8")
header_str, body = data.split("\r\n\r\n", 1)
header_list = header_str.split("\r\n")
headers['method'], headers['protocol'] = header_l... | 58aaca44ef84d73c0ab0bdbedfbe9697a27f2576 | 665,800 |
def cidr_to_netmask(cidr):
"""
:param cidr:
:return:
"""
cidr = int(cidr)
mask_addr = (0xffffffff >> (32 - cidr)) << (32 - cidr)
return (str((0xff000000 & mask_addr) >> 24) + '.' +
str((0x00ff0000 & mask_addr) >> 16) + '.' +
str((0x0000ff00 & mask_addr) >> 8) + '.' +... | e6ce2cc3d18c662c0acebd47379c60097a51b0d0 | 665,801 |
import re
def fix_bad_html(html):
"""
Fixes for various DOM errors that MAL commits.
Yes, I know this is a cardinal sin, but there's really no elegant way to fix this.
"""
# on anime list pages, sometimes tds won't be properly opened.
html = re.sub(r'[\s]td class=', "<td class=", html)
# on anime li... | 0c974c4c3d5e873a8a072e7f0255da89b9b750eb | 665,802 |
def convertFromRavenComment(msg):
"""
Converts fake comment nodes back into real comments
@ In, msg, converted file contents as a string (with line seperators)
@ Out, string, string contents of a file
"""
msg=msg.replace('<ravenTEMPcomment>','<!--')
msg=msg.replace('</ravenTEMPcomment>','-->')
ret... | ac7f8495471ce491889799961163b584518c0fed | 665,803 |
import argparse
def validate_xml(value):
"""
Validates if teh file is in YAML or YML and it's a string
:param value: string location of the file
:return: value
"""
if isinstance(value, bool):
return value
if not isinstance(value, str):
raise argparse.ArgumentTypeError('Val... | 8dd29352ff72f17a630d6b87a0a030915e1a4194 | 665,804 |
import bisect
def romanNumeral(n):
"""
>>> romanNumeral(13)
'XIII'
>>> romanNumeral(2944)
'MMCMXLIV'
"""
if 0 > n > 4000: raise ValueError('``n`` must lie between 1 and 3999: %d' % n)
roman = 'I IV V IX X XL L XC C CD D CM M'.split()
arabic = [1, 4, 5, 9, 10... | b6ea736f25b10fdca0d7539d570825eb5a894674 | 665,805 |
def text_objects(text, font, color, pos):
"""Return text surface and rect"""
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect(center=pos)
return text_surface, text_rect | f51a15805383b9d013e98b5913122517bc090d7c | 665,806 |
def hms2deg(h, m, s):
"""Convert from hour, minutes, seconds to degrees
Args:
h (int)
m (int)
s (float)
Return:
float
"""
return h * 360 / 24 + m / 60.0 + s / 3600.0 | e231896ad56d8c7be6ebaea5f5379b00d32464c3 | 665,807 |
def highest(x, a, b=0):
"""Calculate the highest sum of X."""
a, b = a + x, b + x
return a if a > b else b | 18d4aa4fd62ed8a720efed203ce7aaaeeaf98542 | 665,808 |
def lanes_id():
""" return a list of all lane identificator """
lanes = []
for id_lane in ["_0"]: # right turn protected for now else use ["_0", "_1", "_2"]
for edg in ["2to1", "3to1", "4to1", "5to1"]:
lanes.append(edg+id_lane)
return lanes | 95cd7df0c831950314ddabd9502dd0082693fc5a | 665,809 |
def missing_char(str_: str, n: int) -> str:
"""Remove character at index n."""
return f'{str_[:n]}{str_[n+1:]}' | d3705835e07d83429a9103d6c7fce49ee19451fb | 665,810 |
import numpy
def integrate_over_blocks_in_units(blocks, series, unit, function=numpy.sum):
"""
Integrates the block-level values in :series: to produce vtd-level
aggregate values.
:fips: state fips code
:series: pandas Series, assumed to be indexed by Census block GEOID
:function: (defaults t... | 29d7a161b3109e607072af5e1dafe22483324341 | 665,811 |
def get_id_type(
id: int, # noqa
) -> int:
"""
Parameters
----------
id: int
Returns
-------
int
"""
return (id & 65535) >> 11 | da4fea72004b28f49cdcd76ad02315c16af0f1dd | 665,812 |
def mutator_show_trackid(n_digits_in_trackid=5):
"""Mutate the image to show track ID with a fixed number of digits appended to the shortlabel as (####)"""
return lambda im, k=None: (im.objectmap(lambda o: o.shortlabel('%s (%s)' % (o.shortlabel(), o.attributes['trackid'][0:n_digits_in_trackid]))
... | 4e80eb978b042166fde1c505b947f49139a3d4b0 | 665,814 |
def table_name_to_query(table_name):
"""
Maps the given table to a complete query to get all the columns in this table. (PRAGMA)
:param table_name:
:type table_name: str
:return: The query for the PRAGMA for the given table.
:rtype: str
"""
if table_name == "crime_codes":
return... | ba30d9e5abe3ec12ef631b444a60c865cfaa63e9 | 665,815 |
import math
def f_slow(X):
"""
slow function
"""
a = X[0]
b = X[1]
c = X[2]
s = 0
for i in range(10000):
s += math.sin(a * i) + math.sin(b * i) + math.cos(c * i)
return s | b271c782e05bc3430ce17d4ca6323356dfe914b4 | 665,816 |
def chunkstring(string, length):
""" slice a string into chunks of letters of a certain length, defined by the length argument
passed to the function (--> note the third value in the 'range' function, that specifies the
incrementation or the step taken after each iteration); return the result """
retur... | b6ab5cf669127184779ef00b3bddd6990fa5c2c5 | 665,817 |
def write_reg_input(model_type, order, maxl_list):
"""Write input file for mlptools/mlpgen/regression.py
Args:
model_type (str): Type of polynomial model
order (str): Order of invariants
maxl_list (list of str): List of maxl for each invariants order
"""
content = """\
n_type 1
... | db852c3ea3cd50939c1c9e5c377904baeaa3e951 | 665,818 |
import json
def get_pg_params(json_file):
"""
Takes the path to the json file specifying database connection information and returns formatted information.
Parameters
----------
json_file : 'str'
The path to the json file specifying database connection information.
Returns... | b0097b2201962b4bc2d516a919459459a5afdbdc | 665,819 |
from typing import OrderedDict
def update_src_dict(key, item_dict, src_dict=None):
"""
updates existing or non existing src dict with key values of item dict
@param key: search key in item dict
@type key: str
@param item_dict: the dictionary to search for key
@type item_dict: dict
@param ... | b22683fa2c7f2f3958a200be3c3d4bd1bdd4ce88 | 665,820 |
def str_format(text, data, enc_char):
"""This takes a text template, and formats the encapsulated occurences with data keys
Example: if text = 'My name is $$name$$', provided data = 'Bob' and enc_char = '$$'.
the returned text will be 'My name is Bob'.
"""
for key in data:
val = data[key]
text = tex... | 207024659439a6f1fb920312d7256fc107ebd97a | 665,821 |
from typing import Callable
from typing import Any
import functools
def compose(*functions: Callable) -> Callable:
"""Compose multiple functions into a single one."""
def noop(x: Any) -> Any:
return x
return functools.reduce(lambda f, g: lambda x: f(g(x)), functions, noop) | 5ab28c12463cb84876b25f28551fa33e78e1b12c | 665,822 |
def factorial(n: int) -> int:
"""Return n! (0! is 1)."""
if n <= 1:
return 1
result = 2
for x in range(3, n + 1):
result *= x
return result | 8e4139bb5a227ddfbd46164e6fb0f092fdd8dfcd | 665,823 |
def _get_bbox_from_points(polygon):
"""
根据polygon顶点获取bbox
:param polygon:
:return:
"""
x_list = [p[0] for p in polygon]
y_list = [p[1] for p in polygon]
xmin = min(x_list)
ymin = min(y_list)
xmax = max(x_list)
ymax = max(y_list)
return xmin, ymin, xmax, ymax | ab18f1becd468d33725d46ff9125907bed867e62 | 665,824 |
def col_collection(records):
"""Takes the collection of records and returns the list of freeform tags."""
z = len(records[0]) - 1
a = records[0][z]
# rewrite!
for x in range(1, len(records)):
print(x)
z1 = len(records[x]) - 1
a = a + records[x][z1]
return list(set(a)) | 0e60ac40a7bb198d0727e32aaf9fab1f63feb263 | 665,825 |
def inherited_branches(bases):
"""Returns a dictionary of combined branches for all the given bases.
Bases are evaluated in reverse order (right to left), mimicking Python's
method resolution order. This means that branches defined on multiple
bases will take the value from the leftmost base.
"""
... | 28b20ca471736361e03b38d9e1e2f8d5246be0f3 | 665,826 |
def _parse_initialize(initialize):
"""
parse the initialization of Reveal.js
:param initialize: the params given in the HTML-Doc
:return: the parsed initialization
"""
lines = []
# parse the input
for line in initialize.strip().rstrip(");").splitlines():
line = line.strip()
... | 117c7fa813b172b777c9ab1de587a29ff9509126 | 665,827 |
def massage_link(linkstring):
"""Don't allow html in the link string. Prepend http:// if there isn't
already a protocol."""
for c in "<>'\"":
linkstring = linkstring.replace(c, '')
if linkstring and linkstring.find(':') == -1:
linkstring = 'http://' + linkstring
return linkstring | e624ba8ce489f3a9c82430e1d3ef1af820ba113a | 665,828 |
def construct_instance_market_options(instancemarket, spotinterruptionbehavior, spotmaxprice):
""" construct the dictionary necessary to configure instance market selection
(on-demand vs spot)
See:
https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.ServiceResource.create_instances
... | 03daf402bfbd5e0f2d39c56f39e15441fd03a2b1 | 665,829 |
def tau_column(tau, k, j):
"""
Determine the column index for the non-zero elements of the matrix for a
particular row `k` and the value of `j` from the Dicke space.
Parameters
----------
tau: str
The tau function to check for this `k` and `j`.
k: int
The row of the matrix ... | 26e390f4d8c3d13d57e4cb470b3169e493eb3915 | 665,830 |
from pathlib import Path
def configure_output_dir(output_dir: str):
"""
Create a directory (recursively) and ignore errors if they already exist.
:param output_dir: path to the output directory
:return: output_path
"""
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_o... | e5bc9b176cade54a99bc6bdc9e3da4f240e37307 | 665,831 |
def simple_transfer(type, file_path, out_path=None):
"""
simple_transfer [summary]
Args:
type (str): File's encoding type
file_path (str): Path to the file
out_path (str, optional): Path to the output file. Defaults to None.
Returns:
[bool]: whether transfer the encoding type successfully.
"""
with ope... | d6ddb1beed83e8082415379bf9ff9f0811461897 | 665,832 |
import re
def extract_fifos_from_module_call(module_call):
"""
Returns a list containing all the fifos in the module call.
"""
fifos = []
for line in module_call:
if line.find('/* fifo */') != -1:
m = re.search(r'\*/ (.+),', line)
if m:
fifo = m.gro... | a8f5572172d5faa2576ee50c867369eb8eeb5188 | 665,833 |
import plistlib
import xml
def read_manifest_plist(path):
"""Given a path to a ProfileCreator manifest plist, return the contents of
the plist."""
with open(path, "rb") as openfile:
try:
return plistlib.load(openfile)
except xml.parsers.expat.ExpatError:
print("Erro... | d9710b9bdf38af10a285f06e714692938ea5306d | 665,834 |
import uuid
import socket
def srv_uuid():
"""
Service UUID
:return: This function returns the service UUID calculated
using the server' hostname
"""
# UUID from hostname/IP
return uuid.uuid3(uuid.NAMESPACE_DNS, socket.gethostname()) | 76a8be322868cf8bf166633b40e49186e3bbf3b2 | 665,835 |
def sign(val: int, size: int) -> int:
"""Convert unsigned val of size nibbles into a signed int."""
mask = 1 << (4 * size - 1)
return -(val & mask) + (val & ~mask) | b29f2483a3a963c90a1fe7610de086e3691bfc94 | 665,837 |
def tr(data):
"""
Calculate True Range
indicator = data.tr()
"""
data["previous_close"] = data["close"].shift(1)
data["high-low"] = abs(data["high"] - data["low"])
data["high-pc"] = abs(data["high"] - data["previous_close"])
data["low-pc"] = abs(data["low"] - data["previous_close"])
... | 95662e7e03cc1f19bcbf0c20033b38c29cdc3355 | 665,838 |
import six
def get_dict_from_output(output):
"""Parse list of dictionaries, return a dictionary.
:param output: list of dictionaries
"""
obj = {}
for item in output:
obj[item['Property']] = six.text_type(item['Value'])
return obj | a71fe78f131887e35ccea1406da93b0d15bf73d2 | 665,839 |
from io import StringIO
import pandas as pd
def MakeModelCSV(data):
"""Creates an in-memory csv.
Assumes 'data' is a list of dictionaries
with native python types
"""
mem_csv = StringIO()
pd.DataFrame(data).to_csv(mem_csv, index=False)
mem_csv.seek(0)
return mem_csv | b3fe821d83b500629a6c5ed155854e11a431155a | 665,840 |
def get_feature_set():
"""
Return a list of features' names.
Features' name that are used to train a model and predict a class.
Sorted by the names.
Returns
-------
feature_names : list
A list of features' names.
"""
features = ['amplitude', 'hl_amp_ratio', 'kurtosis', 'pe... | d886bef471ef3a6ba8a5367fadb1e801f872b888 | 665,841 |
import torch
def pack_tensors(tensors, use_cuda=False):
"""
Packs a list of tensors into one 1-dimensional tensor.
Args:
tensors (list[torch.Tensor]): The tensors to pack
use_cuda (bool): Whether the resulting tensor should be on cuda
Returns:
(torch.Tensor, list[int], list[(... | c5656c701a4eeeb0920471bc9831b1b284034441 | 665,842 |
def hms6(a_datetime):
"""'145359'"""
return a_datetime.strftime("%H%M%S") | a6a6a692b4bcfbcb293dcb4508eaf44725543496 | 665,843 |
def _get_comm_phase(comms, vecs, indices):
"""Get the commutator and phase from a commutator entry.
This function assumes that the given vectors has an entry.
"""
entry = comms[vecs]
if len(entry) == 2:
return entry
elif len(entry) == 3:
dumms, comm, phase = entry
if len... | f745a2f3aa0d06dffe05e12279462ce6f9d405c3 | 665,844 |
def fake_event_issue(a, b, c, d):
"""
Mock out the _event_issue function because it is being called when instance
objects are created. It ends up trying to communicate with another thread
(that doesn't exist) and this eventually leads to nosetests hanging if
enough events are issued.
"""
ret... | 1ad7133a51f44bf9b41cb496f16e70aaa85007b3 | 665,845 |
def cstr(s):
"""convenience function to encode a str as bytes"""
return None if s is None else s.encode('utf-8') | 205cb71b1e5f2ff0852ba164a3f8fb33b6dfd8db | 665,846 |
import sys
def decode(s):
"""
Decode a string using the system encoding if needed (ie byte strings)
"""
if isinstance(s, bytes):
return s.decode(sys.getdefaultencoding())
else:
return s | 5f909d3929931d602b350d14b5f784737d761cfb | 665,847 |
def SFR(z):
""" returns the cosmic star formation rate in M_\odot/yr/Mpc^3 following Strolger+15"""
A = 0.015 #M_\odot/yr/Mpc^3
B = 1.5
C = 5.0
D = 6.1
return A*(1+z)**C/( ((1+z)/B)**D + 1 ) | 5736e3034fb4d1da8b69e40f1926209f184df52a | 665,848 |
def primitive_roots(p, g, l):
"""Finds another primitive root of p using g (assumed to be a generator).
p is also assumed to equal 2q+1 where q is another prime. l is the number
of primitive roots desired. This will just be used on the server."""
q = (p-1)//2
roots = tuple(pow(g, (k*2)+1, p) for k ... | 6a0bbc3e57b9d0bfdb8efbdd0d1f7e2290b20f0b | 665,849 |
import os
import math
def ConvertToLatex(df):
""" Convert a Pandas DataFrame to a pretty LaTeX table
The pandas data frame should have an entry "Additional Information".
Args:
df (pandas.DataFrame): A pandas data frame
Returns:
str: LaTeX text for table
"""
#df['Addit... | 0872947942dcbd441df7da657aeb907e06c05ca7 | 665,850 |
def ESAclouds(toa):
"""
European Space Agency (ESA) clouds from 'QA60', i.e. Quality Assessment band at 60m
parsed by Nick Clinton
"""
qa = toa.select('QA60')
# bits 10 and 11 are clouds and cirrus
cloudBitMask = int(2**10)
cirrusBitMask = int(2**11)
# both flags set to zero indi... | 9a9a8705a5db24c65c82bfe064c538d016142615 | 665,851 |
def private_repo_count(self):
"""count of private repositories of `org`"""
return len(self.get_repos('private')) | e6d1a66d17cf862574e1a223ebb119b4614c5abb | 665,852 |
def dobra(x):
"""
Dobra o valor da entrada
Parâmetros
----------
x : número
O valor a ser dobrado
Retorno
-------
número
O dobro da entrada
"""
return 2*x | 00431c5fb8a1ab056252b5d8389868f71c872c62 | 665,853 |
def get_called_variants(var_list, cn_prob_processed, starting_index=0):
"""
Return called variants based on called copy number and list of variant names
"""
total_callset = []
if starting_index != 0:
assert len(var_list) == len(cn_prob_processed) + starting_index
for i, cn_called in enum... | 46e6dbce20d9e004872999bee220558d4446ac8d | 665,854 |
def add_deviations_from_sample_mean(data):
"""
Adds columns in which [profitability, inv_rate] are demeaned at the firm-level and then the full-sample mean is added again.
Args
----
data (pandas.DataFrame): dataframe with 4 columns: firm, year, profitability, inv_rate
Returns
---... | 0eda4c5526e238b80fc9eabb4a071f410f1af103 | 665,855 |
def get_normal_vector(hkl, Astar):
"""
Get normal vector to real-space Miller plane, hkl.
Note
----
The normal vector to a real-space Miller plane is collinear with
the reciprocal dHKL vector. As such, we can use this simpler
formula in the reciprocal lattice basis to get the c... | 34cf8f02acfb6c88f92022831f5e310221977b46 | 665,856 |
import numpy
def get_average_pixel_offset(lines, average_line_distance):
"""Get the average x and y pixel offset."""
offset_sum_x = 0
offset_sum_y = 0
for line in lines:
if line[1] < numpy.pi:
offset_sum_y += line[0] % average_line_distance
else:
offset_sum_x +=... | 8f44740ebcff626149b418de8f080fc114a4480c | 665,858 |
from datetime import datetime
def get_alert_values(root):
"""Finds important alert info, returned in this order:
1. Alert header
2. Alert type
3. Alert status
4. Alert confidence
5. Alert latitude (of radiative center)
6. Alert longitude (of radiative center)
7. Alert date and time (da... | c6b54a42f8ad4ec79d990e7b8139b7f3ea8bdef6 | 665,859 |
import re
def clean_text(text_):
"""
Cleans the text, so it can be used to find similar words.
:param text_: The text we would like to clean.
:return: Cleaned text.
"""
text_ = text_.lower()
text_ = text_.replace('.', ' ')
text_ = text_.replace(',', ' ')
text_ = text_.replace(... | 5c86532e938ff5ef65a7b90e4c887ac80df52819 | 665,860 |
def endpoint(line, x=0, y=0):
"""
>>> endpoint('nwwswee')
(0, 0)
"""
if line == "":
return x, y
if line.startswith("nw"):
return endpoint(line[2:], x, y - 1)
if line.startswith("ne"):
return endpoint(line[2:], x + 1, y - 1)
if line.startswith("sw"):
return... | f8679370030de3248ad8ac72f2ba6cab0a61dc90 | 665,861 |
from typing import Dict
from typing import Any
def main(*args, **kwargs) -> Dict[str, Any]:
"""
This file and folder will be replaced when container is built.
"""
return {'result': 'Hello World!'} | b7206ce486636b2ed6a301b98fc63a3eeb870cb8 | 665,862 |
from datetime import datetime
def _string2datetime(value):
"""Convert String to datetime."""
value = value.replace('T', ' ')
value = value.replace('-', ' ')
value = value.replace(':', ' ')
value = value.replace(',', ' ')
value = value.replace('_', ' ')
parts = value.split(' ')
strfmt... | d9e289c9c770e72d7c2226252568dd94b81749dd | 665,863 |
import sympy
import six
def _factor_non_decimal(value):
"""Extras x dividing value such that x is coprime to 2 and 5."""
result = 1
factors = sympy.factorint(value)
for factor, power in six.iteritems(factors):
if factor not in [2, 5]:
result *= factor ** power
return result | 144638e19c595e60344a3f9d66bfc8de2e2d4294 | 665,864 |
def gini_criteria_proxy(l_weight, l_length, r_weight, r_length, not_repeated):
"""
Maximizing the Gini gain is equivalent to minimizing this proxy function.
"""
return -(l_weight / l_length + r_weight / r_length) * not_repeated | fcf22646842037b3f30258a97ae435ff5980996a | 665,865 |
def convert_types(type_dict):
"""
Check dictionary on nested dictionaries, convert it into one dictionary without nested dictionaries
:param type_dict: dictionary that can contain nested dictionaries
:type: dict
:return: dictionary contained data from type_dict without nested dictionary in it
... | 6291244ed1eb1062fe8e3fc5662f0a8676c434ff | 665,866 |
import re
def uncomment(text):
"""Remove all INNO Setup comments from the specified text"""
def replacer(match):
s = match.group(0)
if s.startswith(';'):
return ''
else:
return s
pattern = ';.*?$|"[^"]*"|\'[^"]*\''
return re.sub(re.compile(pattern, re... | b0ad9c9d86d91fec14face8aae8f232b1cf45813 | 665,868 |
def host_data(fqdn):
"""
Splits input FQDN to usable elements:
domain_attr = {
"fqdn": "name.example.com",
"domain": "example.com",
"host": "name",
}
Takes into account multiple subdomains
(i.e., name1.name2.example.com).
"""
hosts = fqdn.split(".")
domain_at... | ca6c4ac77a42070ba6740c0eefaf703e1dbdca30 | 665,869 |
def getOutShape(input_dim,layersList):
"""
params:
input_dim : input dimension of the data to the sequential network. A tupple (in_channels,H_in,W_in)
layersList : A list of dictionaries for each layer. Refer the example to know more.
"""
in_ch, H_in, W_in = input_dim
out_ch_prev = in_ch
... | 8d2498d071592a64af76e973227c417085184a70 | 665,870 |
def manhattan_distance(pos1, pos2):
"""Returns manhattan distance between two points in (x, y) format"""
return abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1]) | c239e75605088c6a061c5c25b1b47676ccd619ae | 665,871 |
def left_join(hash1, hash2):
"""Left join 2 hash tables."""
result = []
for each in hash1.buckets:
if each:
for node in each.display():
result.append(list(node.keys())[0])
result[-1] = [result[-1], hash1.get(result[-1]), hash2.get(result[-1])]
return r... | 465c5f2b0f3d69e43e2ccd7fa83b4a91219ec2ae | 665,872 |
import subprocess
import os
def test_release():
""" Uploads the package to test.pypi.org
"""
result = subprocess.run(['twine', 'upload', '--repository-url',
'https://test.pypi.org/legacy/', 'dist/*'],
cwd=os.getcwd())
return result.returncode | 2214030ba84991b82ffb3f7b5489709e0fa4d5ba | 665,873 |
def is_linear_perpetual(trading_pair: str) -> bool:
"""
Returns True if trading_pair is in USDT(Linear) Perpetual
"""
_, quote_asset = trading_pair.split("-")
return quote_asset == "USDT" | 945029d75191056172cceeb8304a3461e4e704c4 | 665,874 |
def _f2r(v, depth):
"""\
_f2r(floatval,depth) -> (numerator, denominator)
Generates a rational fraction representation of a *positive* floating point
value using the continuous fractions technique to the specified depth.
Used rational() in preference, to get the most optional match. This function
... | e3986b608a949d1b60a834fc56b53ec21b32af6e | 665,875 |
import sys
def get_gpu():
"""Returns the installed video card(s) name.
Not cached as the GPU driver may change underneat.
Returns:
All the video cards detected.
tuple(list(dimensions), list(state)).
"""
if sys.platform == 'darwin':
dimensions, state = platforms.osx.get_gpu()
elif sys.platfor... | ad42fddbb0ef683e7d2a12b48e347ff50f066db4 | 665,876 |
def tableName(line):
""" Generate the name of the table. """
words = line.split()
tableNum = words[1].replace(":", "")
tname = "Table" + tableNum
for w in words[2:]:
tname += "-" + w
tname += ".csv"
return tname | 5626704fe2fd1e8ba28c7c22292a9a4a1c0618a2 | 665,878 |
def validate_parameters(params):
"""Validate event counter parameters and return an error, if any."""
# Sanitize input to correct numeric types
for key in ('start_year', 'end_year'):
if params.get(key):
try:
params[key] = int(params[key])
except ValueError:
return "%s must be an in... | 693d0974d95abc6a8067700fc709aaddde19b7d9 | 665,879 |
from datetime import datetime
def to_datetime(datetime_str: str, sep: str = ":") -> datetime:
"""Convert datetime formatted string to datetime object.
Arguments:
---
datetime_str: datetime value in string
sep: separator for time in datetime string
returns:
---
return datetime objec... | b31ef7a8d4d679e193a2786ae8c0c2861746acdc | 665,880 |
def listProduct(an_iterable):
"""assumes an_iterable is an iteraqble of numerics
returns a numeric, the product of the elements of a_list"""
# innitialize product variable
product = 1
# multiply by elements of iterables
for num in an_iterable:
product *= num
return product | 4ee7c5a132ec89d9ac6fcf79efa615163753cb4c | 665,881 |
def w_binary_to_hex(word):
"""Converts binary word to hex (word is a list)
>>> w_binary_to_hex("111")
'0x7'
>>> w_binary_to_hex([1,1,1,1])
'0xf'
>>> w_binary_to_hex([0,0,0,0,1,1,1,1])
'0xf'
>>> w_binary_to_hex([0,1,1,1,1,1,0,0])
'0x7c'
"""
if isinstance(word, str):
... | 1fd5c6f84e8a19ee16dc191f333d46202f2049a2 | 665,882 |
import logging
import json
def connect_and_get_output(device):
"""
Helper function which get LLDP data from specified device
Positional argument:
- device -- NAPALM driver object
Returns:
- json_output -- LLDP device data serialized to JSON
"""
try:
device.open()
outp... | 41403b46728f63ac34d7c8f42f8e3bd076d20ddf | 665,883 |
def canonicalize_emails(changelog, mapping):
"""Takes in a string and an email alias mapping and replaces all
instances of the aliases in the string with their real email.
"""
for alias, email_address in mapping.iteritems():
changelog = changelog.replace(alias, email_address)
return chang... | bd40ce178d64a32af114b168de6aef481a089ace | 665,884 |
def denormalize(features, mean, std):
"""
Normalizes features with the specificed mean and std
"""
return features * std + mean | e17006012ab61f056e2094cb973b1f98bb31d359 | 665,885 |
def num_sections(course: tuple[str, str, set]) -> int:
"""Return the number of sections for the given course.
Preconditions:
- The input matches the format for a course described by the assignment handout.
"""
return len(course[2]) | bc0120a451ea2c771b20e65224e3dacce47bba2d | 665,886 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.