content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def hessian (f, X, eps=1e-6):
"""
Check Hessian of function.
checkgrad.hessian (f, X, eps=1e-6)
Inputs:
f Function, returns Y(X), d^2Y / dX^2.
X [D1, ..., Dn]
Y [E1, ..., Em]
d^2Y/dX^2 [E1, ..., Em, D1,... | 74,100 |
def is_available():
"""
Test whether YouCompleteMe plugin is available (was loaded).
"""
return 'g:loaded_youcompleteme' in vimp.var | 74,101 |
def nl_print(msg):
"""
print with a new line :)
:param msg:
:return:
"""
print(str(msg) + "\n") | 74,102 |
def rs1_score(sequence):
"""
Generates a binary matrix for DNA/RNA sequence, where each column is a possible base
and each row is a position along the sequence. Matrix column order is A, T/U, C, G
"""
import math
import numpy as np
seq = str(sequence).upper()
seq = list(seq)
matrix1 ... | 74,103 |
def get_build_summary(results):
"""Prints to screen the complication results of example programs.
Args:
results - results of the compilation stage. which is the output of compile_repos()
Returns: Numbers of failed results
"""
pass_table = PrettyTable()
pass_table.field_names = ["EXAMPL... | 74,104 |
def s2n(s):
"""
String to number.
"""
if not len(s):
return 0
return int(binascii.hexlify(s), 16) | 74,105 |
def test_show_queue():
"""
Test for show contents of the mail queue
"""
with patch.dict(postfix.__salt__, {"cmd.run": MagicMock(return_value="A\nB")}):
assert postfix.show_queue() == []
# Test if get an extra newline in the output
with patch.dict(postfix.__salt__, {"cmd.run": MagicMock(... | 74,106 |
def show_version_queue(a_device, output_q):
"""
Use Netmiko to execute show version. Use a queue to pass the data back to
the main process.
"""
output_dict = {}
remote_conn = ConnectHandler(**a_device)
hostname = remote_conn.base_prompt
output = ("#" * 80) + "\n"
output += remote_con... | 74,107 |
def test_serialize_missing_path(server_rule_factory):
"""Check that RuleSerializeError is raised if rule class does not have path attribute.
1. Create preparator for a rule factory.
2. Prepare path rule.
3. Try to serialize rule without path attribute.
4. Check that RuleSerializeError is raised.
... | 74,108 |
def diff_lists(old, new):
"""Returns sorted lists of added and removed items."""
old = set(old or [])
new = set(new or [])
return sorted(new - old), sorted(old - new) | 74,109 |
def get_astyle_strings(astyle_strings, astyle_path):
"""Read the astyle_main.cpp file and save the settext strings."""
astyle_total = 0 # total strings extracted
lines = 0 # current input line number
file_in = open(astyle_path, 'r')
# get astyle settext strings
for... | 74,110 |
def save_csv_given_urls(urls, csv_filename='AAAI_tmp.csv'):
"""
write IJCAI papers' urls in one csv file
:param urls: str, the urls of paper website, such as 'https://www.aaai.org/Library/AAAI/aaai20contents-issue01.php'
:param csv_filename: str, csv file's name, default to 'AAAI_tmp.csv'
:retu... | 74,111 |
def indicator_remove(_id, username=None):
"""
Remove an Indicator from CRITs.
:param _id: The ObjectId of the indicator to remove.
:type _id: str
:param username: The user removing the indicator.
:type username: str
:returns: dict with keys "success" (boolean) and "message" (list) if failed... | 74,112 |
def get(github_repository, **args):
"""Send data and perform Core()"""
return Core(github_repository, **args).get() | 74,113 |
def get_profile(login):
"""Get the GitHub profile from login"""
print("get profile for %s" % (login,))
try:
profile = get("https://api.github.com/users/%s" % login).json()
except requests.exceptions.HTTPError:
return dict(name=login, avatar_url=LOGO_URL, html_url="")
if profile["nam... | 74,114 |
def test_makeSEQXFile(awg2, random_wfm_m1_m2_package):
"""
Test that this function works (for some input)
"""
seqlen = 25
chans = 3
wfmpkg = random_wfm_m1_m2_package
trig_waits = [0]*seqlen
nreps = [1]*seqlen
event_jumps = [0]*seqlen
event_jump_to = [0]*seqlen
go_to = [0]*... | 74,115 |
def create_U_layer(mol, auxinfo):
"""
Creates a string with the positions of the atoms that bear unpaired electrons. The string
can be used to complement the InChI with an additional layer that allows for the differentiation
between structures with multiple unpaired electrons.
The string is compose... | 74,116 |
def result(product_id):
""" Speak query result"""
response = PhoneInterface()
result = Product.query.get(product_id)
response.speak(to_result(result))
response.speak('Is there anything else we can help you with?')
response.listen('listenbot.done', 'yes, no')
return str(response) | 74,117 |
def key2board(key):
""" Turn a key into a "Game of Life" board.
We might add an arbitrary size parameter.
"""
Z = np.zeros((512 + 2, ((512 * 4) + 2)), int)
Z[1:-1, 1:-1] = (np.frombuffer(hex2bin(key), 'u1') - ord('0')).reshape((512, 512 * 4))
return(Z) | 74,118 |
def PV(FV,i,n,m=1):
"""
future value
interest
years
optional payments per year
"""
PV = FV / ((1 + i/m)**(m*n))
return PV | 74,119 |
def getCeleryApp():
"""
Lazy loader for the celery app. Reloads anytime the settings are updated.
"""
global _celeryapp
if _celeryapp is None:
backend = Setting().get(PluginSettings.BACKEND) or 'amqp://guest:guest@localhost/'
broker = Setting().get(PluginSettings.BROKER) or 'amqp://... | 74,120 |
def get_gw_bytes_encoding():
"""
get gateway encoding method
:return: string
"""
return "utf-8" | 74,121 |
def build_py_ide_info(target, ctx):
"""Build PyIdeInfo."""
if not hasattr(target, "py"):
return (None, set())
sources = sources_from_target(ctx)
transitive_sources = target.py.transitive_sources
py_ide_info = struct_omit_none(
sources = sources,
)
return (py_ide_info, transitive_sources) | 74,122 |
def down(url,i):
"""
下载文件的函数
"""
r = requests.get(url)
with open(i+".gif", "wb") as code:
code.write(r.content) | 74,123 |
def factor_new_space(M):
"""
Given a new space `M` of modular symbols, return the
decomposition into simple of `M` under the Hecke
operators.
INPUT:
- ``M`` - modular symbols space
OUTPUT: list of factors
EXAMPLES::
sage: M = ModularSymbols(37).cuspidal_subspace()
... | 74,124 |
def tag(c):
"""Tag the current version of NumS and push the tag upstream."""
result = c.run("git tag", hide=True)
versions = result.stdout.splitlines()
current_version = "v" + __version__
if current_version in versions:
if not accepts(f"{current_version} is already tagged. Force update?"):
... | 74,125 |
def build_core_template(images, N=5, thresh=40, vb=True):
"""
Overlay images of core trays from e.g. a drillhole to calculate a template that is used for extracting
individual core segments and is robust to data quirks (e.g. empty trays). All images must be identical
dimensions and properly co-aligned.
... | 74,126 |
def cohort_tests(config: Dict, n_days: int) -> Dict[str, int]:
"""Determines the number of tests required per person for all cohorts.
The number of tests required for a person in a cohort is approximately the
number of testing days divided by the cohort's target testing interval.
We assume that each pe... | 74,127 |
def check_oversamplers_classifiers(oversamplers, classifiers):
"""Extract estimators and parameters grids."""
# Create estimators and parameter grids
estimators, param_grids = [], []
for oversampler, classifier in product(oversamplers, classifiers):
# Unpack oversamplers and classifiers
... | 74,128 |
def run_driver():
""" Run webdriver Chrome """
try:
current_path = os.getcwd()
options = Options()
options.add_experimental_option("prefs", {
"download.default_directory": current_path,
"download.prompt_for_download": False,
"download.directory_upgrade... | 74,129 |
def axiom_generator_have_arrow_ssa(t):
"""
Assert the conditions at time t under which the Agent
has the arrow at time t+1
t := time
"""
"*** YOUR CODE HERE ***"
axiom_str = state_have_arrow_str(t+1) + ' <=> (' + state_have_arrow_str(t) + ' & ~' + action_shoot_str(t) + ')'
# Comment or... | 74,130 |
def vacuum_inactive_subscribers(self):
"""Deletes subscribers with no outbound activity.
Each network can turn on this feature to automatically deactivate
subscribers. This runs this as a periodic task managed by celerybeat.
"""
for network in Network.objects.iterator():
# Do nothing if su... | 74,131 |
def map_(key, value, *tail) -> Expression:
"""
Creates a map of expressions.
Example:
::
>>> tab.select(
>>> map_(
>>> "key1", 1,
>>> "key2", 2,
>>> "key3", 3
>>> ))
.. note::
keys and values should have the ... | 74,132 |
def test_neptune_mock(neptune):
"""Simple to check if same experiment is created."""
logger = NeptuneLogger(api_token="test", project_dir="namespace/project")
logger.on_experiment_start()
created_experiment = neptune.init(name="namespace/project", api_token="test")
assert logger.experiment is not No... | 74,133 |
def exoNPremiersNombresPremiers () -> None :
""" imprime les n nombres premiers
:return: None
"""
nb = [10, 100, 1000]
for i in nb :
l, n = nombreNPremiers (i)
print("Il y a ", n, " nombres premiers de 0 à ", i , "\nListe = ",l,"\n"+120*'_')
print(l) | 74,134 |
def CSPDarkNet53(input_shape=None,
input_tensor=None,
include_top=True,
weights='imagenet',
pooling=None,
classes=1000,
**kwargs):
"""Generate cspdarknet53 model for Imagenet classification."""
if not (weights in {'imagenet', None} or os.p... | 74,135 |
def convert_coords(container: pygame.Rect, x: float, y: float) -> (int, int):
"""Converts the given coordinates for a simulation display purposes.
:param container: the simulation surface
:param x: the x position coordinate
:param y: the x position coordinate
:return: converted coordinates
"""
... | 74,136 |
def vec2display(vec):
""" Stores an image in vec format in a temporary location and displays it
on screen using a web browser. """
image2display(vec2image(vec)) | 74,137 |
def _debug_warning(prod, txn, warning_table, vtec, segment, ets):
"""Get a more useful warning message for this failure"""
cnt = txn.rowcount
txn.execute(
"SELECT ugc, issue at time zone 'UTC' as utc_issue, "
"expire at time zone 'UTC' as utc_expire, "
"updated at time zone 'UTC' as ... | 74,138 |
def ensure_root():
"""Prints error and exit if not root"""
if os.geteuid() != 0:
logger.error("This functionality is accessible to root only")
sys.exit(1) | 74,139 |
def _parse_unit(unit_element, namespace):
"""returns a list of dicts that represent the values for a given unit or
units element
"""
unit_dict = _element_dict(unit_element)
tag_name = unit_element.tag.split('}')[-1]
return_dict = {}
if '1.0' in namespace:
return_dict['name'] = unit_... | 74,140 |
def kw(sa: 'Atmosphere', frequency: float) -> Tensor1D_or_3D:
"""
:param frequency: частота излучения в ГГц
:param sa: объект Atmosphere
:return: весовая функция k_w (вода в жидкокапельной фазе).
"""
return wf.kw(frequency, sa.temperature) | 74,141 |
def plot_lines(df: pd.DataFrame, cols: list = None, cols_like: list = None, x: str = None, h: int = 300, w: int = 1200,
t_str: str = 'box_zoom,pan,hover,reset,save', x_type: str = 'datetime', show_p: bool = True,
t_loc: str = 'right', out_path: str = None, return_p: bool = False, palette: ... | 74,142 |
def main():
"""
Generates a few new mazes
:return: None
"""
for i in range(5):
breadth_first_generation(name=f'image{i}.jpg') | 74,143 |
def add_postgraduate_info():
"""
添加一条信息
:return:{'result': result}
"""
user_id = request.values.get('openid') # 用户微信openid
subject = request.values.get('subject') # 考研方向
msg = request.values.get('msg') # 附加消息
phone = request.values.get('phone') # 联系电话
grade = request.values.get('... | 74,144 |
def depth_first_traversal_for_node(node, callback, direction, obj=None):
"""
Executes a depth-first traversal from this node in a given direction. Raising
a StopIteration will terminate the traversal.
:type node: treestruct.Node
:type callback: (treestruct.Node, treestruct.Node, object) -> ()
:... | 74,145 |
def build_model(tparams, options):
"""
Construct computation graph for the whole model
"""
# inputs (image, sentence, contrast images, constrast sentences)
im = tensor.matrix('im', dtype='float32')
s = tensor.matrix('s', dtype='float32')
cim = tensor.matrix('cim', dtype='float32')
... | 74,146 |
def test_time_delta_high_minimum_unit() -> None:
"""It raises ValueError."""
with pytest.raises(ValueError):
times.time_delta(1, minimum_unit="years") | 74,147 |
def _show_info(app):
"""
显示系统信息
"""
print ("Server start on port {0} (processes: {1}) ...".format(app.port, app.processes))
print ("Start time: {0}".format(datetime.now().isoformat(" ")))
print
print ("Parameters:")
for k in sorted(dir(__conf__)):
if k.startswith... | 74,148 |
def default_slugifier(value, allow_unicode=False):
"""
Oscar's default slugifier function. When unicode is allowed
it uses Django's slugify function, otherwise it uses cautious_slugify.
"""
if allow_unicode:
return django_slugify(value, allow_unicode=True)
else:
return cautious_s... | 74,149 |
def extract_pos_tags(input_xls: str) -> dict:
"""
Read all post-tas from JUIZ column and returns a dictionary
indexed by the sentence id with a list of all pos-tags.
Parameters
----------
input_xls: str
Input xls file.
Returns
-------
dict:
Dict of sentence ids and ... | 74,150 |
def secure_atbd_version_lock(
atbd_id: str,
version: str,
db: DbSession = Depends(get_db_session),
override: bool = False,
user: CognitoUser = Depends(require_user),
principals=Depends(get_active_user_principals),
):
"""
Sets locked_by field of ATBD Version to current user.
Succeeds ... | 74,151 |
def ClusterToPDF(cluster, fileName, size=(300, 300), ptColors=[], lineWidth=None, showIndices=0,
stopAtCentroids=0, logScale=0):
""" handles the work of drawing a cluster tree to an PDF file
**Arguments**
- cluster: the cluster tree to be drawn
- fileName: the name of the file to b... | 74,152 |
def configure_app(app, testing, config):
"""Set configuration for application
Configuration will be loaded in the following order:
* test_config if testing is True
* else if config parameter is not None we load it
* else if env variable for config is set we use it
"""
app.config.from_objec... | 74,153 |
def ants_move(space, pos, inv_distance, pheromones, alpha, beta, del_tau):
"""Moves the ants from starting position to cover all the nodes.
Arguments:
space {numpy.ndarray} -- The sample space
pos {numpy.ndarray} -- The starting position of the ants
inv_distance {numpy.ndarray} -- T... | 74,154 |
def list_to_tree(S: list) -> TreeNode:
"""
:param L:
:return:
"""
L = [TreeNode(val) if val is not None else None for val in S]
# print(L)
tmp_list = [L[0]]
cursor = 1
N = len(L)
while tmp_list:
n = len(tmp_list)
next_cursor = cursor + n * 2
for i, node in... | 74,155 |
def three_points_to_circle(p1, p2, p3):
"""
Function that calculates circle parameters defined by three points.
Input:
- p1 [float,float] : pair (x,y) of coordinates of the 1st point
- p2 [float,float] : pair (x,y) of coordinates of the 2nd point
- p3 [float,float] : pair (x,y) of coordinates of... | 74,156 |
def dnlsim(system, u, t=None, x0=None):
"""Simulate output of a discrete-time nonlinear system.
Calculate the output and the states of a nonlinear state-space model.
x(t+1) = A x(t) + B u(t) + E zeta(x(t),u(t))
y(t) = C x(t) + D u(t) + F eta(x(t),u(t))
where zeta and eta are polynomials w... | 74,157 |
def get_cloudinit_instance():
"""Return the current CloudInit instance ID."""
try:
target = os.readlink('/var/lib/cloud/instance')
except OSError as e:
if e.errno != errno.ENOENT:
raise
return
path, instance = os.path.split(target)
return instance | 74,158 |
def open_file(filename: str):
"""
>>> open_file("hello.txt")
No such file or directory: hello.txt
>>> import os
>>> if os.path.exists("../LICENSE"):
... f = open_file("../LICENSE")
... _ = f is not None
... _ = f.readline().strip() == "Apache License"
... _ = f.readl... | 74,159 |
def sanitize(report: str) -> Tuple[str, str, List[str]]:
"""Returns a sanitized report, remarks, and elements ready for parsing"""
clean = sanitization.sanitize_report_string(report)
data, remark_str = get_remarks(clean)
data = core.dedupe(data)
data = sanitization.sanitize_report_list(data)
cle... | 74,160 |
def matfromrcell(astar, bstar=None, cstar=None, alphastar=None, betastar=None,
gammastar=None):
"""Make standard-orientation reciprocal cell matrix from reciprocal cell.
"""
if isinstance(astar, CellParam):
cell = astar
else:
cell = fillCellParam(astar, bstar, cstar, alp... | 74,161 |
def updateSingleDicomImage(objWeasel, spinBoxIntensity, spinBoxContrast,
imagePath='', seriesID='', studyID='', colourmap=None, lut=None):
"""This method is used in the Displays module. It saves the image in the viewer to DICOM,
with the intensity and contrast values and colourmap set in t... | 74,162 |
def list_octicons() -> List[str]:
"""List available octicon names."""
return list(get_octicon_data().keys()) | 74,163 |
def sampler_params(scope="function"):
"""Common parameters for sampler test"""
params = {
"tag_type": "ner",
"query_number": 4,
"label_names": ["O", "PER", "LOC"],
"token_based": False,
"tagger": MagicMock(),
"embeddings": MagicMock(),
"kmeans_params": {"n... | 74,164 |
def test_pragmas_06():
"""
Test the case where we specify a 'disable-next-line' pragma with a valid name to disable.
"""
# Arrange
scanner = MarkdownScanner()
supplied_arguments = [
"scan",
"test/resources/pragmas/atx_heading_with_multiple_spaces_disable_line_by_name.md",
]
... | 74,165 |
def ocfn(filename, openMode='r+', binary=False):
"""Atomically open or create file from filename.
If file already exists, Then open file using openMode
Else create file using write update mode If not binary Else
write update binary mode
Returns file object
If binary Then If ... | 74,166 |
def strip_xml(element):
"""
Recursively strip clean indentation from xml. Especially useful
if you're using a template.
For example, this is a bit of a mess:
>>> xml_mess = '''
... <help> How did
...
... <person>I
... </person>
... get to be so <cleanliness
... | 74,167 |
def section3():
"""
If you want to iterate through all items within your filter, you can also do so without going through them page by page:
""" | 74,168 |
def add_gaussian(p, g_std):
"""add gaussian noise
:param p: input tensor
:param g_std: standard deviation of Gaussian
:returns: tensor with added noise
:rtype: tensor
"""
if g_std > 0:
size = p.size()
p += torch.normal(0, g_std, size=size)
return p | 74,169 |
def extension_supported(extension_name, request):
"""
this method will determine if nova supports a given extension name.
example values for the extension_name include AdminActions, ConsoleOutput,
etc.
"""
extensions = list_extensions(request)
for extension in extensions:
if extensio... | 74,170 |
async def get_text(
# https://fastapi.tiangolo.com/tutorial/query-params/
msg: Optional[str] = Query(
...,
max_length=1500,
min_length=2, # disallow one character message
title="user's message",
description="max. 5000 chars.",
),
prev_resp: Optional[str] = Query(... | 74,171 |
def parse_interactions(input_file):
""" Parse through the interactions input file.
@param[in] input_file The name of the input file.
"""
# Three dictionaries of return variables.
Systems = OrderedDict()
Interactions = OrderedDict()
Globals = {}
InterNum = 0
InterName = "I0"
... | 74,172 |
def quit():
"""Make :func:`~run` return.
Quitting when the main loop is not running does nothing.
"""
if _running:
bananagui._get_wrapper('mainloop:quit')() | 74,173 |
def get_rates_above_threshold(y_vals, rec_bins):
""" Gives the total number of interactions above every given threshold
The input is expected to be integrated rates over time. Thus, the
total rate returned is counts/kg/t_full
Parameters
----------
y_vals : `array`
... | 74,174 |
def test_count_and_set_headers_flex():
"""Verify that we are setting the correct flex headers"""
reader = csvReader.CsvReader()
csv_schema = [Mock(name_short='some_col'), Mock(name_short='other')]
header_row = ['ignored', 'flex_my_col', 'flex test', 'space col', 'some_col', 'flex_other', 'some_col']
... | 74,175 |
def stormpath_login(request):
"""
Verify user login. It uses django_stormpath to check if user credentials
are valid.
"""
if settings.USE_ID_SITE:
return redirect('sample:stormpath_id_site_login')
if request.user.is_authenticated():
return redirect('sample:home')
form = Au... | 74,176 |
def generate_csv(data_dir, id_prefix, out, overwrite, worker_pool=None):
"""Transforms a vs-dataset into a CSV file.
Args:
data_dir: Directory name. Should contain two subdirectories named
"shards" and "targets". The "shards" directory should contain
gzipped sdf files. The "targets"... | 74,177 |
def chain(_input, funcs):
"""Execute recursive function chain on input and return it.
Side Effects: Mutates input, funcs.
Args:
_input: Input of any data type to be passed into functions.
funcs: Ordered list of funcs to be applied to input.
Returns:
Recusive call if any functi... | 74,178 |
def connect_mysql(options):
""" Make connection to Mysql."""
try:
con = mdb.connect(
host = options.mysqlhost,
user = options.mysqluser,
passwd = options.mysqlpass,
db = 'gold_cup_web',
port = int(options.mysqlport),
)
cur = con... | 74,179 |
def sample_circle(c, N=32):
""" Sample points on a circle c
Returns a 2D PointSet with N points
"""
assert len(c) == 3
# Get x, y and radius
x, y, r = c
# Sample N points, but add one to close the loop
a = np.linspace(0,2*np.pi, N+1)
# Prepare array
pp = ... | 74,180 |
def turn_animation_into_updater2(animation, cycle=False, delay=0.0, **kwargs):
"""
Add an updater to the animation's mobject which applies
the interpolation and update functions of the animation
If cycle is True, this repeats over and over. Otherwise,
the updater will be popped upon completion
... | 74,181 |
def analyze(obj):
"""
Given a Job, visits all the execution steps making sure that:
- no undefined blobs will be found during excution
- no blob with same name is defined in concurrent steps
"""
Analyzer()(obj) | 74,182 |
def handle_right(left_entry_box, right_entry_box, mqtt_sender):
"""
Tells the robot to move using the speeds in the given entry boxes,
but using the negative of the speed in the right entry box.
:type left_entry_box: ttk.Entry
:type right_entry_box: ttk.Entry
:type mqtt_sender: ... | 74,183 |
def all_levels(df, bucket_var, include_levels=None, ret_map=False):
"""
Assign each row of `df` to a bucket according to the unique
values of `bucket_var`.
bucket_var: Column name of the values to split on.
Missing values will not be assigned to an interval.
include_levels: Level value... | 74,184 |
def test_get_settings_path():
"""
gets the application settings path.
"""
root_path = application_services.get_application_main_package_path()
settings_path = os.path.abspath(os.path.join(root_path, 'settings'))
assert application_services.get_settings_path() == settings_path | 74,185 |
def loss_function(real, pred, loss_object):
"""
measure loss object in a logically consistent way
:param real:
:param pred:
:param loss_object:
:return:
"""
logging.info("loss_function")
mask = tf.math.logical_not(tf.math.equal(real, 0))
loss_ = loss_object(real, pred)
mask ... | 74,186 |
def do_CreateVolume(client, args):
""" Create Volume """
val = client.CreateVolume(args.name,
disksize=args.disksize,
zone=args.zone)
utils.print_dict(val) | 74,187 |
def Z(theta=0, pulse_pars=None):
"""
Software Z-gate of arbitrary rotation.
:param theta: rotation angle
:param pulse_pars: pulse parameters (dict)
:return: Pulse dict of the Z-gate
"""
if pulse_pars is None:
raise ValueError('Pulse_pars is None.')
else:
... | 74,188 |
def spend_separator_tx(tx_sep_tx, keys_for_sep_tx):
"""spends Transaction with scriptPubKey in form of:
<pk1> OP_CHECKSIGVERIFY OP_CODESEPARATOR <pk2> OP_CHECKSIGVERIFY OP_CODESEPARATOR ... <pk N_signings> OP_CHECKSIG
"""
tx = CTransaction()
tx.vin.append(CTxIn(COutPoint(tx_sep_tx.sha256, 0), b"",... | 74,189 |
def get_nested_grid_bounds(land_cover_pth):
"""
Get the lat/lon bounds of the nested grid window (NA, EU, AS) for the inversion.
The land cover file path specifies the window.
"""
if "NA" in land_cover_pth:
if "GEOSFP" in land_cover_pth:
minLat_allowed = 9.75
maxLat_... | 74,190 |
def get_resolution_HRF():
"""Returns RIM_ONE_v2 resolution after post-processing."""
return (3504, 3504) | 74,191 |
def crop_brain(image, n_top_areas = 5, max_scale_diff = 3, plot = False, dimensions = None, area = None):
""" Crop image in order to only include square image of the "best" image of the brain """
import cv2
from matplotlib import pyplot as plt
image = normalize_img(image, use_min_max = True)
if di... | 74,192 |
def generate_password(size=4, chars=string.ascii_uppercase + string.digits):
"""Randomly generate a password with length `size`.
Args:
size (int): Length of the password.
chars (str): The char appeared in this string will be considered as
one of the choice.
Returns:
A passw... | 74,193 |
def overlaps_bool(pred_roi, bbox):
"""
:param rois: regions of interest in format (y1, x1, y2, x2)
:return: Boolean
Example:
[[ 99,325,135,363], [ 54,229,88,264], [ 53,230,94,266], [ 93,321,132,361]]
-> [1, 2, 2, 1]
"""
l_1_y1 = pred_roi[0]
l_1_x1 = pred_roi[1]
r_1_y2 = pre... | 74,194 |
def angle_distance(innodes, name='angle_distance'):
"""
Returns the angle distance between two nodes. Angle distance is <x,y>/(||x||||y||)
@param innodes: array of 2 tensorflow tensors with equal dimensions
@param name: name of the subgraph. everything in this subgraph would be _[name], and the output... | 74,195 |
def report(config, output, use, output_dir, accounts,
field, no_default_fields, tags, region, debug, verbose,
policy, policy_tags, format, resource, cache_path):
"""report on a cross account policy execution."""
accounts_config, custodian_config, executor = init(
config, use, debug... | 74,196 |
def spec_exists(notification: Notification) -> bool:
"""
Check whether the spec exists.
Args:
notification: The SNS notification.
Returns:
Whether the spec file in the SNS notification exists.
"""
response = S3_CLIENT.list_objects_v2(
Bucket=notification.bucket_name, P... | 74,197 |
def person(request, pk):
"""
Retrieve, update or delete a code snippet.
"""
try:
person = Personnel.objects.get(pk=pk)
except Personnel.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = PersonnelSerializer(person)
return JsonResponse(serializer.data)
elif request.me... | 74,198 |
def is_ipython_frame(frame: FrameType) -> bool:
"""
Determine whether a frame is being executed by IPython.
Args:
frame (``types.FrameType``): the frame to examine
Returns:
``bool``: whether the frame is an IPython frame
"""
filename = frame.f_code.co_filename
parent_dir = ... | 74,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.