content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import math
def decode_fsw(fsw_array):
"""
Parse the array into specific faultgroups
"""
faultGroup = [0] * NUM_OF_FAULTGROUPS;
faultGroup[FAULTGROUP_TRANSIENT] = 0
faultGroup[FAULTGROUP_CRITICAL] = (fsw_array[FSW_CRITICAL_FAULTS_INDEX] & FSW_CRITICAL_FAULTS_MASK) >> FSW_CRITIC... | 421dfea23813e73d12918f361063614d3cbf33a8 | 3,627,922 |
def lower_allbutfirst_letter(mystring):
"""Lowercase all letters except the first one
"""
return mystring[0].upper() + mystring[1:].lower() | 860d1449865790e15ccc840ee85ea366b2de5a64 | 3,627,923 |
def get_world_size():
"""Replace linklink.get_world_size"""
try:
world_size = get_world_size_from_env()
if world_size is not None:
return world_size
else:
# return link.get_world_size()
return dist.get_world_size()
except Exception as e: # noqa
... | 2e308370e42d9bc847488efb8c17e46344060839 | 3,627,924 |
def orginal(S,R,RT,nNodes=20550):
"""
This function is used to calculate the reconstructed data from reduced variables using POD.
This function is used to deal with flow past cylinder data.
Parameters
----------
S : array
The array contains total data that combine two features as a col... | 1fa4bd17afdc83d8209cd1b97082594d89382d98 | 3,627,925 |
import random
def strtest(aString):
"""this function takes the string and returns the string in a random order"""
newstring = random.sample(aString, len(aString))
newstring = "".join(newstring)
return(newstring) | 28bb6ed6b9f3a10ea19fbebb8ef60091123b0fd5 | 3,627,926 |
import urllib
def build_url(base_url=DEFAULT_BASE_URL, command=None):
"""Append a command (if it exists) to a base URL.
Args:
base_url (str): Ignore unless you need to specify a custom domain,
port or version to connect to the CyREST API. Default is http://127.0.0.1:1234
and t... | 5dc322f459bdf8d4f58ab7c8da78dbcf40e2696f | 3,627,927 |
from typing import Optional
def get_first_bonding_box(boxes: BoundingBoxes) -> Optional[BoundingBox]:
"""
Get the first bounding box that belongs to the trash class.
:param boxes: the list of detected bounding boxes
:return: the first box that belongs to the trash class. If no valid box can be found... | 3c9244983af82287f6044579d813ea792c53f7cb | 3,627,928 |
def svn_diff_contains_diffs(*args):
"""svn_diff_contains_diffs(svn_diff_t diff) -> svn_boolean_t"""
return _diff.svn_diff_contains_diffs(*args) | 76a47b063dcf14088bb05d46fb1d8cf3346c5401 | 3,627,929 |
def init_shared_manager(items):
"""Initialize and start shared manager."""
for cls in items:
proxy = create_proxy(cls)
SyncManager.register(cls.__name__, cls, proxy)
manager = SyncManager()
manager.start()
return manager | 62a4ce5b2bf5eb1b178104ced772ec08ad9778c9 | 3,627,930 |
def cnn2d(image: np.ndarray,
filters: np.ndarray):
"""
Vanilla convolutions.
Args:
image: (hi, wi, cin).
filters: (hf, wf, cin, cout).
Returns:
(hi, wi, cout)
"""
filter_len, image_padded = pad_image(filters, image)
out = np.zeros([image.shape[0], image.s... | 5b3710736912fe0d7ee6b815fd8fa2e7cac013a4 | 3,627,931 |
def mongo_uses_error_check(store):
"""
Does mongo use the error check as a separate message?
"""
if hasattr(store, 'modulestores'):
return any(mongo_uses_error_check(substore) for substore in store.modulestores)
return False | 52d4a5135531ff18b0e19ac7aa91a453a2e736f1 | 3,627,932 |
def bootstrap_consensus(msa, times, tree_constructor, consensus):
"""Consensus tree of a series of bootstrap trees for a multiple sequence alignment.
:Parameters:
msa : MultipleSeqAlignment
Multiple sequence alignment to generate replicates.
times : int
Number of bootstr... | ee5aa0f4a2457a55ad9b975606c39a88f721d0cc | 3,627,933 |
def get_snapshot_seconds():
"""Returns the amount of time in seconds between snapshots of a
fuzzer's corpus during an experiment."""
return environment.get('SNAPSHOT_PERIOD', DEFAULT_SNAPSHOT_SECONDS) | fc6d1d940b64c69e202ba2e8ac32d45681c24c19 | 3,627,934 |
import random
import re
import collections
def realize_question(dialog, template, filter_objs):
"""Samples attributes for template using filtered objects.
In addition, creates scene graph for the new information added.
Args:
scene: Current scene graph
template: Text template to use to generate questio... | 512c92025ee6ac0b93ac49be9a3957df9b8f241e | 3,627,935 |
def coroutine(func):
"""
_coroutine_
Decorator method used to prime coroutines
"""
def start(*args,**kwargs):
cr = func(*args,**kwargs)
next(cr)
return cr
return start | f096958d45cb391e0f12e5bfd162e5250085bb52 | 3,627,936 |
from typing import Union
from typing import Optional
from typing import Tuple
def image_to_tensor(
image: Union[PILImage, np.ndarray, str],
roi: Optional[Rect] = None,
output_size: Optional[Tuple[int, int]] = None,
keep_aspect_ratio: bool = False,
output_range: Tuple[float, float] = (0., 1.),
... | cadbe61514321c2bac9ba3d96d2f3243fdfcc9b0 | 3,627,938 |
def _setup_request(bucket_acl=None, object_acl=None):
"""
add a foo key, and specified key and bucket acls to
a (new or existing) bucket.
"""
bucket = _create_keys(keys=['foo'])
key = bucket.get_key('foo')
if bucket_acl is not None:
bucket.set_acl(bucket_acl)
if object_acl is no... | be9d09c6ddadaa6a55d84e3e8385bf46aa06efc9 | 3,627,940 |
def _some_lt(t1: 'Tensor', t2: 'Tensor', only_value: bool) -> bool:
"""
:param t1:
:param t2:
:param only_value:
:return:
"""
res = np.sum(t1.data < t2.data)
if only_value:
if res > 0:
return True
else:
return False
else:
raise NotIm... | 8b816eeb57a41611275c7dc2f4d018134e387a01 | 3,627,941 |
from typing import Optional
def get_folders(parent_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetFoldersResult:
"""
Retrieve information about a set of folders based on a parent ID. See the
[REST API](https://cloud.google.com/resource-manager/referen... | e507c2d36b20997859db55bce9a7f555d6ac122f | 3,627,942 |
def bedLine(chrom, chromStart, chromEnd, name, score=None, strand=None,
thickStart=None, thickEnd=None, itemRgb=None, blockCount=None,
blockSizes=None, blockStarts=None):
""" Give the fields, create a bed line string
"""
s = ('%s %d %d %s'
% (chrom, chromStart, chromEnd, name))
i... | dd294d5d31ea3a2f7beb8a11a7ec705eb10cf1a4 | 3,627,943 |
import pickle
def tuning(sortedfile):
"""
Fit r = a0 + a1*f1.
"""
# Load sorted trials
with open(sortedfile) as f:
t, sorted_trials = pickle.load(f)
# Get f1s
f1s = sorted(sorted_trials.keys())
# Active units
units = get_active_units(sorted_trials)
units = range(next... | 1c5c71c8ef2ce04088f164befb619ccb03eb2079 | 3,627,944 |
def balance_conversion_constraint_rule(backend_model, loc_tech, timestep):
"""
Balance energy carrier consumption and production
.. container:: scrolling-wrapper
.. math::
-1 * \\boldsymbol{carrier_{con}}(loc::tech::carrier, timestep)
\\times \\eta_{energy}(loc::tech, time... | b10fa6203eb8ae0dc5054a98bce2d4ed4412a586 | 3,627,945 |
def follow(id):
"""Follow a user"""
user = token_auth.current_user()
followed_user = db.session.get(User, id) or abort(404)
if user.is_following(followed_user):
abort(409)
user.follow(followed_user)
db.session.commit()
return {} | e88f1968f41f819bae4baecab006889f2d42eb0d | 3,627,946 |
def get_rules():
"""
Get the virtual server rules
CLI Example:
.. code-block:: bash
salt '*' lvs.get_rules
"""
cmd = "{} -S -n".format(__detect_os())
ret = __salt__["cmd.run"](cmd, python_shell=False)
return ret | 76d7e4fcb1e2fc30769011fa110cc8c98532a5ba | 3,627,947 |
def all_user_tickets(uid, conference):
"""
Cache-friendly version of user_tickets: returns a list of
(ticket_id, fare_type, fare_code, complete)
for each ticket associated to the user.
"""
qs = _user_ticket(User.objects.get(id=uid), conference)
output = []
for t in qs:
output... | 9fedff351ce896dfe6a431813c60ba7b68b4dff5 | 3,627,948 |
from typing import List
def get_titles(url: str = URL) -> List[str]:
"""List titles in feed."""
articles = _feed(url).entries
return [a.title for a in articles] | 325d431fdb350188077156e6a9541c21ce73986a | 3,627,949 |
def fatorial(num):
"""
Calcula a fatorial
:param num:
:return:
"""
fat = 1
if num == 0:
return fat
for i in range(1,num+1,1):
fat *= i # fat = fat * i
return fat | 181ea2bde3acef3f6ff4311054fb209edfad6160 | 3,627,950 |
def indent_code(*code, indent: int = 1) -> str:
"""Indent multiple lines (`*code`) by the given amount, then join on newlines."""
return "\n".join(indent_str(line, indent, end="") for line in code) + "\n" | d78fac12e726638321799142cbd68b326ebc02f0 | 3,627,951 |
import torch
def evaluate_accuracy_gpu(net, data_iter, device=None):
"""使用GPU计算模型在数据集上的精度。
Defined in :numref:`sec_lenet`"""
if isinstance(net, nn.Module):
net.eval() # 设置为评估模式
if not device:
device = next(iter(net.parameters())).device
# 正确预测的数量,总预测的数量
metric = d2l.A... | 84d78795e541b5d60c8338356952c47786a35722 | 3,627,952 |
def get_rdns_from_ip(ip):
"""Basic get RDNS via gethostbyaddr.
:param ip: IP address to lookup
:type ip: str
:return: Returns `hostname` if found, or empty string '' otherwise
:rtype: str
"""
try:
coro = resolver.gethostbyaddr(ip)
result = loop.run_until_complete(coro)
... | bf7927d97767d7ca6091a2318a8dc879ec2cda01 | 3,627,953 |
def GePacketOut(egress_port, mcast, padding):
""" Generate packet_out packet with bytearray format """
out1 = "{0:09b}".format(egress_port)
out2 = "{0:016b}".format(mcast)
out3 = "{0:07b}".format(padding)
out = out1+out2+out3
a = bytearray([int(out[0:8],2),int(out[8:16],2),int(out[16:24],2),int... | c56abb84ec067cf8abb8e69d82c1342c4f20e0e9 | 3,627,954 |
def damage_per_max_ammo(weapon_dic: dict, damage_range_arr: np.ndarray) -> np.ndarray:
"""
Calculate the damage per max ammo at varying distances.
This assumes you were to fire all ammo in the gun and in reserve at a set distance.
Parameters
----------
weapon_dic : dict
Dict of specifi... | 8724a1bbe408a58399e6547a63b3e80c5ecf7eda | 3,627,955 |
import requests
from bs4 import BeautifulSoup
import warnings
def get_PDB_summary(PDB_id, verbose=False):
"""
Similar info to get_meta, but for a PDB entry - returns info about when it was regitered etc.
Parameters
----------
PDB_id :
verbose : Bool, optional, default: False
Flag t... | 0fb0c1a2623656c0dc18067b3f52f7ee67d303a0 | 3,627,956 |
import requests
import json
def distance_from_user(beer):
"""
This method is used to calculate distace from user to each store that carry
specific beer that user seached for and return list of store, beer and distance from user to
those stores sorted by distance
"""
# user_lat = 40.8200471
... | 67b0de0751a2dfd2f440bcb0595c31be3c644026 | 3,627,958 |
from mesh.Triangulation import TrivialSystem, ComposedSystem, State
def meshes2system(meshes):
"""
recursively generate system.
"""
firstKey = list(meshes.keys())[0]
mm = meshes[firstKey]
state = State(translation=mm['translate'],
rotation=mm['rotate'],
velo... | 7a6dc5a7f41735a37e54f6444148141085d9fece | 3,627,959 |
def cmp_public_numbers(pn1, pn2):
"""
Compare 2 sets of public numbers. These is a way to compare
2 public RSA keys. If the sets are the same then the keys are the same.
:param pn1: The set of values belonging to the 1st key
:param pn2: The set of values belonging to the 2nd key
:return: True i... | a91a7204412d07808dbd6d5040f6df8baa576417 | 3,627,960 |
def phred(vals):
""" apply the phred scale to the vals provided """
return -10*np.log10(1-vals)
return -10*np.ma.log10(1-vals).filled(-3) | c09b38a5f736ddef994ea1eff8f0cc614362f3d3 | 3,627,962 |
def __get_useconds_of(stage_idx, block_idx, event_acc, wanted, block_prefix=''):
"""
gets useconds of chan/kernel of specific stage_idx & block_idx, from tensorboard event_acc
:param wanted: 'chan' or 'kernel'
"""
useconds = []
summary_prefix = block_prefix + 'use_%s_' % wanted
idx = 0
... | 1fed126224649e368694d63013643cf2fb5f4aaa | 3,627,963 |
def create_menu(*args):
"""
create_menu(name, label, menupath=None) -> bool
Create a menu with the given name, label and optional position, either
in the menubar, or as a submenu. If 'menupath' is non-NULL, it
provides information about where the menu should be positioned. First,
IDA will try and resolve ... | 0c3cb60c1193b422b11ca1ac92f7124f05086a69 | 3,627,964 |
def parse_proxy_url(purl):
"""Adapted from UStreamTV plugin (ustreamtv.py)"""
proxy_options = {}
if purl:
p = urlparse(purl)
proxy_options['proxy_type'] = p.scheme
proxy_options['http_proxy_host'] = p.hostname
if p.port:
proxy_options['http_proxy_port'] = p.port
... | 94b903cc3199b34c61f0b86c16a75bd503f13325 | 3,627,965 |
def cma(data):
"""
Cumulative Moving Average
:type data: np.ndarray
:rtype: np.ndarray
"""
size = len(data)
out = np.array([np.nan] * size)
last_sum = np.array([np.nan] * size)
last_sum[1] = sum(data[:2])
for i in range(2, size):
last_sum[i] = last_sum[i - 1] + data[i]
... | caeb4d7b30d8cc5a079532aac817bbc49ef85746 | 3,627,966 |
from pycalphad import __version__ as pycalphad_version
from typing import OrderedDict
def starting_point(conditions, state_variables, phase_records, grid):
"""
Find a starting point for the solution using a sample of the system energy surface.
Parameters
----------
conditions : OrderedDict
... | 59537ea36fa7b73e250ccbcc660f1363213109bc | 3,627,967 |
def intersects(a0, a1, b0, b1):
"""
Checks whether two line segments, each defined by two end points, will intersect.
"""
# First line is vertical
if a0[0] == a1[0]:
# Both lines are vertical
if b0[0] == b1[0]:
return (a0[0] == b0[0]) and (in_range(b0[1], a0[1], a1[1]) or... | 626a682e24358243faa43c18fefec2c7c874f10d | 3,627,968 |
def getAccident(id=None):
""" return the Accident object or None if not exist
return a list of all Accident if no id passed.
return one object if filtered by 'id'"""
if id:
return Accident.query.get(id)
return Accident.query.all() | 798b4cb51d7d15400b376ca13b77c17bb0da9568 | 3,627,969 |
def ranges(int_list):
"""
Given a sorted list of integers function will return
an array of strings that represent the ranges
"""
begin = 0
end = 0
ranges = []
for i in int_list:
# At the start of iteration set the value of
# `begin` and `end` to equal the first element
... | cc6aab9442a6f6986acccb1fa46cd61ff1e4ba07 | 3,627,970 |
def format_data(x_data=None,y_data=None):
"""
=============================================================================
Function converts a list of separate x and y coordinates to a format suitable
for plotting in ReportLab
Arguments:
x_data - a list of x coordinates (or any object that can be indexe... | 34ac418f38194644f9372f20d47535424c7bfb52 | 3,627,971 |
from typing import List
from typing import Counter
def explicit_endorsements(user: domain.User) -> List[domain.Category]:
"""
Load endorsed categories for a user.
These are endorsements (including auto-endorsements) that have been
explicitly commemorated.
Parameters
----------
user : :cl... | 1e70415443a6f9a0bd27a8e2bbac3998dab090b5 | 3,627,974 |
def detec_apache_root(binPath):
"""
根据apachectl -V 获得apache的安装路径
"""
result = commands.getoutput(binPath + """ -V | grep -i "HTTPD_ROOT"
| awk -F '[="]' '{print $3}'""")
return result | dfa07a0311dbc3cc9ee74425c103ed94d768da83 | 3,627,975 |
def hindu_zodiac(tee):
"""Return the zodiacal sign of the sun, as integer in range 1..12,
at moment tee."""
return quotient(float(hindu_solar_longitude(tee)), deg(30)) + 1 | 87c293c20ee0880ac844e27000e2f8f774b2bbb1 | 3,627,976 |
def SearchRelativeLongitude(body, targetRelLon, startTime):
"""Searches for when the Earth and another planet are separated by a certain ecliptic longitude.
Searches for the time when the Earth and another planet are separated by a specified angle
in ecliptic longitude, as seen from the Sun.
A relativ... | effce7c99297e183182b8142e0dc037bb9c924da | 3,627,977 |
import time
def _fitFunc2(x, *pfit, verbose=True, follow=[], errs=None):
"""
for curve_fit
"""
global pfitKeys, pfix, _func, Ncalls, verboseTime
Ncalls +=1
params = {}
# -- build dic from parameters to fit and their values:
for i,k in enumerate(pfitKeys):
params[k]=pfit[i]
... | 1f61a3746761d47ffa43dcfdb370b756df9733b8 | 3,627,978 |
import io
import numpy
def sendForward(cwt,solver):
"""Use this function to communicate data between nodes"""
if solver.nodeMasterBool:
cwt = io.sweptWrite(cwt,solver)
buff = numpy.copy(solver.sharedArray[:,:,-solver.splitx:,:])
buffer = solver.clusterComm.Sendrecv(sendobj=buff,dest=so... | b47c1a2db202a2bfead6f76e2e2c8b9eb03dc50a | 3,627,979 |
import re
def get_parameters(img_path_complete):
"""
Get the parameters of an hyper-spectral image from file.
:param img_path_complete: complete path of the bil file to get the parameters. Ex. <path>/img.bil
:return: array of totals of [lines, samples, bands]
"""
file_info = img_path_complete ... | 26fb411d737b259801681fb7152d7570583df969 | 3,627,980 |
def phone_move_handler(pid):
"""
@api {post} /v1/asset/phone/move/{int:id} 流转 资产设备
@apiName MovePhone
@apiGroup 项目
@apiDescription 流转 资产设备
@apiParam {int} id
@apiParam {int} borrow_id 流转人 ID
@apiParamExample {json} Request-Example:
{
"borrow_id": 2
}
@apiSuccessExampl... | fd6e36849f9461544144bea5f60fcc8a174c54c0 | 3,627,981 |
def extractLargestRegion(actor):
"""Keep only the largest connected part of a mesh and discard all the smaller pieces.
.. hint:: |largestregion.py|_
"""
conn = vtk.vtkConnectivityFilter()
conn.SetExtractionModeToLargestRegion()
conn.ScalarConnectivityOff()
poly = actor.GetMapper().GetInput(... | d481cdd5975eb9c8d7e835d24c49deb9a0a5961a | 3,627,982 |
import zlib
def query_stock_concept(code="", date=""):
"""获取概念分类
@param code:股票代码,默认为空。
@param date:查询日期,默认为空。不为空时,格式 XXXX-XX-XX。
"""
data = rs.ResultData()
if code is None or code == "":
code = ""
if code != "" and code is not None:
if len(code) != cons.STOCK_CODE_LENGTH:... | 4ca53f065564fd78855e94a89d43f4590c51e89a | 3,627,983 |
def checkForVideoRetainment(op, graph, frm, to):
"""
Confirm video channel is retained in the resulting media file.
:param op:
:param graph:
:param frm:
:param to:
:return:
@type op: Operation
@type graph: ImageGraph
@type frm: str
... | d04296adc58611798007066e26cf1a784949520c | 3,627,984 |
def get_console_scripts(entry_points):
"""pygradle's 'entrypoints' are misnamed: they really mean 'consolescripts'"""
if not entry_points:
return None
if isinstance(entry_points, dict):
return entry_points.get("console_scripts")
if isinstance(entry_points, list):
result = []
... | 4ca1f6bb50959570c1c6d28312aabb939fe9daf8 | 3,627,985 |
def create_deepcopied_groupby_dict(orig_df, obs_id_col):
"""
Will create a dictionary where each key corresponds to a unique value in
`orig_df[obs_id_col]` and each value corresponds to all of the rows of
`orig_df` where `orig_df[obs_id_col] == key`.
Parameters
----------
orig_df : pandas D... | 5af41d6410adf643ccd7f5f2072a7e6539609ccb | 3,627,986 |
from typing import Optional
def _create_configuration(
user_agent: Optional[str] = None,
user_agent_config_yaml: Optional[str] = None,
user_agent_lookup: Optional[str] = None,
hdx_url: Optional[str] = None,
hdx_site: Optional[str] = None,
hdx_read_only: bool = False,
hdx_key: Optional[str]... | 4ef7a985b8507e3e710a0465101d5db01c1329ed | 3,627,987 |
def batch_autocorr(data, lag, starts, ends, threshold, backoffset=0):
"""
Calculate autocorrelation for batch (many time series at once)
:param data: Time series, shape [n_pages, n_days]
:param lag: Autocorrelation lag
:param starts: Start index for each series
:param ends: End index for each se... | 8c6b9cdb3a62a4e8d1bd613414bda54f3fa75c9a | 3,627,989 |
import yaml
def merge_yaml(y1, y2):
""" Merge two yaml HOT into one
The parameters, resources and outputs sections are merged.
:param y1: the first yaml
:param y2: the second yaml
:return y: merged yaml
"""
d1 = yaml.load(y1)
d2 = yaml.load(y2)
for key in ('parameters', 'resource... | 08351fcbd6ba5d5350b166224a33d558df6c8010 | 3,627,990 |
def infix(token_list):
"""
Parses Infix notation and returns the equivilant RPN form (Pseudocode used from: https://en.wikipedia.org/wiki/Shunting-yard_algorithm)
Parameters
==========
token_list : list
The list of infix tokens
Returns
--------
output : list
This is t... | 97fc5c75b173aeed42c9383625037374caddf261 | 3,627,991 |
from typing import Union
from typing import Tuple
from typing import Dict
def pre_process_steps(
draw, return_kwargs: bool = False
) -> Union[
st.SearchStrategy[pre_process_step_pb2.PreProcessStep],
st.SearchStrategy[Tuple[pre_process_step_pb2.PreProcessStep, Dict]],
]:
"""Returns a SearchStrategy for... | d13cf4343abd670ffd0be4ec83db36483fd761ee | 3,627,993 |
def _decode(hdf5_handle):
"""
Construct the object stored at the given HDF5 location.
"""
if 'symmetries' in hdf5_handle:
return _decode_symgroup(hdf5_handle)
elif 'rotation_matrix' in hdf5_handle:
return _decode_symop(hdf5_handle)
elif 'matrix' in hdf5_handle:
return _de... | ea9420799b8abe435ce7d5d98dd156356d790e1f | 3,627,994 |
def r_network():
"""Loads network from the R library tmlenet for comparison"""
df = pd.read_csv("tests/tmlenet_r_data.csv")
df['IDs'] = df['IDs'].str[1:].astype(int)
df['NETID_split'] = df['Net_str'].str.split()
G = nx.DiGraph()
G.add_nodes_from(df['IDs'])
for i, c in zip(df['IDs'], df['NE... | 5dc728cef2118c981b78da29e73308fbc8ce8cab | 3,627,995 |
def _legend_with_triplot_fix(ax: plt.Axes, **kwargs):
"""Add legend for triplot with fix that avoids duplicate labels.
Parameters
----------
ax : matplotlib.axes.Axes
Matplotlib axes to apply legend to.
**kwargs
These parameters are passed to :func:`matplotlib.pyplot.legend`.
R... | 565fb3937aa0d1deb8f07d0f632354135282389c | 3,627,996 |
from typing import Dict
from typing import Any
def gjson_from_tasks(tasks: Dict[TileIdx_txy, Any],
grid_info: Dict[TileIdx_xy, Any]) -> Dict[str, Dict[str, Any]]:
"""
Group tasks by time period and compute geosjon describing every tile covered by each time period.
Returns time_period... | bb82ec50d79e7425db83ce6b55b7a089b0456cec | 3,627,997 |
def arcz_to_arcs(arcz):
"""Convert a compact textual representation of arcs to a list of pairs.
The text has space-separated pairs of letters. Period is -1, 1-9 are
1-9, A-Z are 10 through 36. The resulting list is sorted regardless of
the order of the input pairs.
".1 12 2." --> [(-1,1), (1,2),... | 80f37daaa57f7b7ae1a89385a22df8e17c3bf46a | 3,627,999 |
def bbox_to_radec_grid(wcs, bbox, tol=1e-7):
"""
Create an ra/dec grid aligned with pixels from a bounding box.
Parameters
----------
wcs : `lsst.afw.geom.SkyWcs`
WCS object
bbox : `lsst.geom.Box2I`
Bounding box
tol : `float`
Tolerance for WCS grid approximation
... | 5f11541dd1c1bbdaffa4fff8048785f511f41757 | 3,628,000 |
def step2(x):
"""Convolution of three step functions."""
y = np.zeros_like(x)
y[x > 0] = 1/2 * x[x > 0]**2
return y | dadfd366ecd1900ed7993b49084b79c0ca10f275 | 3,628,001 |
from typing import Union
from datetime import datetime
from typing import List
from pathlib import Path
def evtx2json(input_path: str, shift: Union[str, datetime], multiprocess: bool = False, chunk_size: int = 500) -> List[dict]:
"""Convert Windows Eventlog to List[dict].
Args:
input_path (str): Inpu... | 677f8927567bbaaa49e47073a08526781e64d6da | 3,628,002 |
import math
def multid_dilution_wrapper(inducers,constructs,fname,avoidedges=[],maxinducer=500,\
wellvol=50,shuffle=False,wellorder="across",mypath=".",start=None):
"""this function contains some helpful pre-sets for doing multiple
inducer sweeps in a 384 well plate.
inducers:
this is ... | d18063c3396d093d0792dbb70b6d968234f2fcca | 3,628,003 |
def matyas(x: np.ndarray):
"""
The Matyas function has no local minima except the global one.
The function is usually evaluated on the square xi ∈ [-10, 10], for all i = 1, 2.
Global minimum at (0, 0)
:param x: 2-dimensional
:return: float
"""
assert x.shape[-1] == 2
x1 = x.T[0]
... | 1e33694a26d0829e49c81691dd45d662d71961f2 | 3,628,004 |
def flatten(array: list):
"""Converts a list of lists into a single list of x elements"""
return [x for row in array for x in row] | 178f8ddb6e4b4887e8c1eb79f32fe51c0cf5fd89 | 3,628,005 |
def slice_sample(x_start, logpdf_target, D, num_samples=1, burn=1, lag=1,
w=1.0, rng=None):
"""Slice samples from the univariate disitrbution logpdf_target.
Parameters
----------
x_start : float
Initial point.
logpdf_target : function(x)
Evaluates the log pdf of target distr... | 8937ddc6bd3e6368c75bb9eb9f65766a2376baf1 | 3,628,006 |
def ShortName(url):
"""Returns a shortened version of a URL."""
parsed = urlparse.urlparse(url)
path = parsed.path
hostname = parsed.hostname if parsed.hostname else '?.?.?'
if path != '' and path != '/':
last_path = parsed.path.split('/')[-1]
if len(last_path) < 10:
if len(path) < 10:
r... | 80669ecbe46bdb0adf3f9c9a9ceb35a9a628fc27 | 3,628,008 |
def select_attachment(pattern, cursor):
"""Prompt the user for the attachment that matches the pattern.
Args:
This function takes the same arguments as the find_attachments
function.
Returns:
A (parentItemID, path) pair, None if no matches were found.
"""
attachments = find... | 84ec1b4cb869321eb2d21147cc7576e9d31ce5b3 | 3,628,009 |
def keyevent2tuple(event):
"""Convert QKeyEvent instance into a tuple"""
return (event.type(), event.key(), event.modifiers(), event.text(),
event.isAutoRepeat(), event.count()) | a456ce7790232ecf8ea4f6f68109a2023f4f257b | 3,628,010 |
from typing import Union
import pathlib
def log_git(repo_path: Union[pathlib.Path, str], repo_name: str = None):
"""
Use python logging module to log git information
Args:
repo_path (Union[pathlib.Path, str]): path to repo or file inside repository (repository is recursively searched)
"""
... | ca11f8247ca875ff45c477baa3a7ae89dcfdc92c | 3,628,011 |
def datetime_to_absolute_validity(d, tzname='Unknown'):
"""Convert ``d`` to its integer representation"""
n = d.strftime("%y %m %d %H %M %S %z").split(" ")
# compute offset
offset = FixedOffset.from_timezone(n[-1], tzname).offset
# one unit is 15 minutes
s = "%02d" % int(floor(offset.seconds / (... | 2dcf6001bfb84bc87c16f4e6cfda390a56466eb3 | 3,628,012 |
def backward_committor(basis, weights, in_domain, guess, lag, test_basis=None):
"""Estimate the backward committor using DGA.
Parameters
----------
basis : list of (n_frames[i], n_basis) ndarray of float
Basis for estimating the committor. Must be zero outside of the
domain.
weights... | ffec1798c41903e26c84ecb85c15c9a7b075db25 | 3,628,013 |
def get_language_from_request(request, current_page=None):
"""
Return the most obvious language according the request
"""
language = get_language_in_settings(request.REQUEST.get('language', None))
if language is None:
language = getattr(request, 'LANGUAGE_CODE', None)
if language is None... | ae224ba3c4900821b664ba12cd2c5d95b87031b7 | 3,628,014 |
from typing import Tuple
import struct
def process_refund_contract_transaction(contract_transaction_bytes: bytes, delivery_time: int,
funding_value: int, funding_output_script: P2MultiSig_Output, server_keys: ServerKeys,
account_metadata: AccountMetadata, channel_row: ChannelRow) -> Tuple[bytes, bytes... | 95554ca7ba14a0e945e1d4deb45548b5508b5dc5 | 3,628,015 |
def _get_link_url(start_component_revision_dict, end_component_revision_dict):
"""Return link text given a start and end revision. This is used in cases
when revision url is not available."""
url = start_component_revision_dict['url']
if not url:
return None
vcs_viewer = source_mapper.get_vcs_viewer_for_... | 8b7c18c2aa3d58f5b77d56ace86fed2a521f326c | 3,628,016 |
import math
def get_inv_unit(block_index,diff):
"""
given a block index and a 0-indexed layer in that block, returns a unit index.
"""
bottleneck_block_mapping = {1:0,
2:3,
3:7,
4:13}
return bottleneck... | ed6936a81dd8f32f76a27efcf89b8e76d384b008 | 3,628,018 |
def dummy_token(db, dummy_app_link):
"""Return a token for the dummy app/user."""
token_string = TOKEN_PREFIX_OAUTH + generate_token()
token = OAuthToken(access_token=token_string, app_user_link=dummy_app_link, scopes=['read:legacy_api', 'read:user'])
token._plaintext_token = token_string
db.session... | 4ef1c7ab09db2a33cf6cfff9c0281603c7e8cb19 | 3,628,020 |
def powspec_highom(fs, mu, s, kp, km, vr, vt, tr):
"""Return the high-frequency behavior of the power spectrum"""
o = 2*pi*fs
Td = np.log((mu + s - vr) / (mu + s - vt)) + tr
Ppp = (kp*exp(-(kp+km)*tr)+km)/(kp+km)
return r0(locals()) * (1.-Ppp*Ppp*np.exp(-2*kp*(Td-tr)))/(1+Ppp*Ppp*np.exp(-2*kp*(Td-tr... | 6e02a6a930ca326286a8214e132c2ab203ca35f5 | 3,628,024 |
def bigger_price(limit: int, data: list) -> list:
"""
TOP most expensive goods
"""
result_list = []
for i in range(limit):
id_max_price, max_price = find_max_price(data)
result_list.append(data.pop(id_max_price))
return result_list | e380183071686778244656fbfaeac80630527fd5 | 3,628,025 |
def makeBlock(data):
"""Applies the block tags to text
"""
global appliedstyle
return "%s%s%s" % (appliedstyle['block'][0], data, appliedstyle['block'][1]) | 018f0ec12742241ab3e62b3125e47fc33c2bcadc | 3,628,026 |
def by_key(dct, keys, fill_val=None):
""" dictionary on a set of keys, filling missing entries
"""
return dict(zip(keys, values_by_key(dct, keys, fill_val=fill_val))) | cd069ab90a5a8db26f6191a81f52d352a231efbd | 3,628,027 |
import random
def get_vivo_uri():
"""
Find an unused VIVO URI with the specified VIVO_URI_PREFIX
"""
test_uri = VIVO_URI_PREFIX + 'n' + str(random.randint(1, 9999999999))
query = """
SELECT COUNT(?z) WHERE {
<""" + test_uri + """> ?y ?z
}"""
response = vivo_sparql_query(query)
while int... | d68f3676de24907fb9399e5ac995c0c3963483dd | 3,628,028 |
def imbothat(img, el):
"""
Function to mimic MATLAB's imbothat function
Returns bottom-hat of image
Bottom-hat defined to be the difference between input and
the closing of the image
"""
closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, el)
return closing - img | 8c0b51b443169a6feec10b92fecac99d271cdb9a | 3,628,029 |
import numpy
def _downsampling_base(
primary_id_strings, storm_times_unix_sec, target_values, target_name,
class_fraction_dict, test_mode=False):
"""Base for `downsample_for_training` and `downsample_for_non_training`.
The procedure is described below.
[1] Find all storm objects in the h... | 0e5b834e0ca011ad83c3929ad05757c777cfc77a | 3,628,030 |
def liste_erreur(estimation, sol):
"""
Renvoie une liste d'erreurs pour une estimation et un pas donnés.
Paramètres
----------
estimation : estimation calculée pour la résolution de l'équation différentielle
sol : solution exacte
"""
(x,y) = estimation ... | 61a800f1316a153d50e39ce80239ddd4b841f74e | 3,628,031 |
def get_pods_amount(v1: CoreV1Api, namespace) -> int:
"""
Get an amount of pods.
:param v1: CoreV1Api
:param namespace: namespace
:return: int
"""
pods = v1.list_namespaced_pod(namespace)
return 0 if not pods.items else len(pods.items) | f676bc9ec4c2fc48c4ff3c332e4201b6ca591f87 | 3,628,032 |
def create_pod(kube_host, kube_port, namespace, pod_name, image_name,
container_port_list, cmd_list, arg_list):
"""Creates a Kubernetes Pod.
Note that it is generally NOT considered a good practice to directly create
Pods. Typically, the recommendation is to create 'Controllers' to create and
ma... | 1c578c4eec5df0ec37ba687f053d932c37be7186 | 3,628,033 |
import json
def convert_jupyter_to_databricks(
input_filename: str = "nofile", output_filename: str = "nofile"
):
"""Main function to convert jupyter files to databricks python files.
Args:
input_filename (str, optional): input filename .ipynb. Defaults to "nofile".
output_filename (str, ... | 6a5fc3010a84a4fdbeb817bd57824e99867cb6dc | 3,628,035 |
import warnings
def insul_diamond(pixels, bins,
window=10, ignore_diags=2, balanced=True, norm_by_median=True):
"""
Calculates the insulation score of a Hi-C interaction matrix.
Parameters
----------
pixels : pandas.DataFrame
A table of Hi-C interactions. Must follow the Cooler co... | a2ce240a669789b1beacc443c122b805ac34cb57 | 3,628,036 |
import random
import numpy
def add_frame(dataset):
""" process a dataset consisting of a list of imgs"""
if args.place != 'random':
offset = eval(args.place)
assert type(offset) == tuple and len(offset) == 2
Xs = dataset[0]
newX = []
for (idx, k) in enumerate(Xs):
if args.... | 948e0e09a12f3835b10ba1d5dd4a5720b7477f0f | 3,628,037 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.