content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def process_singletask(
tf_path,
dnase_path,
genome_path,
data_path,
experiment,
window=200,
alphabet="ACGT",
compression="gzip",
max_len=300,
gc_match=True,
valid_frac=0.1,
test_frac=0.2,
):
"""Preprocess data for a single-class task."""
# remove extremely large... | 2,000 |
def update_topic_rule_destination(arn=None, status=None):
"""
Updates a topic rule destination. You use this to change the status, endpoint URL, or confirmation URL of the destination.
See also: AWS API Documentation
Exceptions
:example: response = client.update_topic_rule_destination(
... | 2,001 |
def test_server():
"""Testing the server executable"""
asyncio.get_event_loop().run_until_complete(server.handler()) | 2,002 |
def _get_dataset_domain(
dataset_folder: str,
is_periodic: bool,
spotlight_id: Optional[Union[str, List]] = None,
time_unit: Optional[str] = "day",
):
"""
Returns a domain for a given dataset as identified by a folder. If a
time_unit is passed as a function parameter, the function will assum... | 2,003 |
def randomize_quaternion_along_z(
mujoco_simulation: RearrangeSimulationInterface, random_state: RandomState
):
""" Rotate goal along z axis and return the rotated quat of the goal """
quat = _random_quat_along_z(mujoco_simulation.num_objects, random_state)
return rotation.quat_mul(quat, mujoco_simulati... | 2,004 |
def init(model):
"""
Initialize the server. Loads pyfunc model from the path.
"""
app = flask.Flask(__name__)
@app.route("/ping", methods=["GET"])
def ping(): # pylint: disable=unused-variable
"""
Determine if the container is working and healthy.
We declare it healthy ... | 2,005 |
def sample_tag(user, name='Comedy'):
"""Creates a sample Tag"""
return Tag.objects.create(user=user, name=name) | 2,006 |
def _middle_point(p1: np.ndarray, p2: np.ndarray) -> Tuple[int, int]:
"""Returns the middle point (x,y) between two points
Arguments:
p1 (np.ndarray): First point
p2 (np.ndarray): Second point
"""
return tuple((p1 + p2) // 2) | 2,007 |
def filter_with_prefixes(value, prefixes):
"""
Returns true if at least one of the prefixes exists in the value.
Arguments:
value -- string to validate
prefixes -- list of string prefixes to validate at the beginning of the value
"""
for prefix in prefixes:
if value.startswith(prefi... | 2,008 |
def get_idl_parser(*, allow_cache=True):
"""Get the global IdlParser object."""
# Singleton pattern
global _parser
if _parser and allow_cache:
return _parser
# Get source
with open(os.path.join(lib_dir, "resources", "webgpu.idl"), "rb") as f:
source = f.read().decode()
# C... | 2,009 |
def delete_database_entry():
"""
Wrapper function for database.delete_entry() since database hast to be set
:return:
"""
global database
if not isinstance(database, db_manager.Database):
print("Database not initialized yet! Please select a database to read from from the database menu!")
... | 2,010 |
def model_training_full_experiment():
"""
This creates the plot for figure 5B in the Montague paper. Figure 5B shows
the 'entire time course of model responses (trials 1-150).' The setup is
the same as in Figure 5A, except that training begins at trial 10.
"""
sample = pnl.TransferMechanism(
... | 2,011 |
def swarm_post_deploy(deploy_results, swarm_id, swarm_trace_id):
"""
Chord callback run after deployments. Should check for exceptions, then
launch uptests.
"""
if any(isinstance(r, Exception) for r in deploy_results):
swarm = Swarm.objects.get(id=swarm_id)
msg = "Error in deploymen... | 2,012 |
def insert_tables(cur, conn):
"""
Inserts data into tables using the queries in `insert_table_queries` list.
"""
for query in insert_table_queries:
try:
cur.execute(query)
conn.commit()
except psycopg2.Error as e:
print('Fail to execute the query: {}'... | 2,013 |
def is_seq(x, step=1):
"""Checks if the elements in a list-like object are increasing by step
Parameters
----------
x: list-like
step
Returns
-------
True if elements increase by step, else false and the index at which the condition is violated.
"""
for i in range(1, len(x)):
... | 2,014 |
def test_lambda_leaf():
""" Tests correct structure of lambda leaf.
"""
my_lambda = LambdaLeaf(leaf_title='MyLambda',
tree_name='testtree',
template=template,
dependencies=['MyDb:5432'],
lambda_config... | 2,015 |
def imatmul(a, b): # real signature unknown; restored from __doc__
""" a = imatmul(a, b) -- Same as a @= b. """
pass | 2,016 |
def create_patient(record: dict) -> tuple:
""" Returns a FHIR Patient resource entry and reference. """
gender = map_sex(record["sex_new"] or record["sex"])
patient_id = generate_patient_hash(
names = participant_names(record),
gender = gender,
birth_date = record['birth... | 2,017 |
def read_files(filenames):
"""Returns an iterator over files in a list of files"""
for filename in filenames:
with open(filename, 'r') as filehandle:
yield filehandle.read() | 2,018 |
def test_post_cve_id_wrong_header(org_admin_headers):
""" org_admin_headers cannot post for 'mitre' org """
res = requests.post(
f'{env.AWG_BASE_URL}{CVE_ID_URL}',
headers=org_admin_headers,
params={
'amount': '10',
'batch_type': 'sequential',
'cve_yea... | 2,019 |
def delete_editor(userid):
"""
:param userid: a string representing the user's UW NetID
:return: True if request is successful, False otherwise.
raise DataFailureException or a corresponding TrumbaException
if the request failed or an error code has been returned.
"""
url = _make_del_account... | 2,020 |
def sanity_check(file):
"""Runs a few checks to ensure data quality and integrity
Args:
names_df (pd.DataFrame): DataFrame containing transformed data.
"""
# Here you must add all the checks you consider important regarding the
# state of the data
# assert names_df.columns.tolist() == ["... | 2,021 |
def ecio_quality_rating(value, unit):
"""
ECIO (Ec/Io) - Energy to Interference Ratio (3G, CDMA/UMTS/EV-DO)
"""
if unit != "dBm":
raise ValueError("Unsupported unit '{:}'".format(unit))
rating = 0
if value > -2:
rating = 4
elif -2 >= value > -5:
rating = 3
elif ... | 2,022 |
def normalizeFilename(filename):
"""normalizeFilename(filename)
Replace characters that are illegal in the Window's environment"""
res = filename
rep = { "*":"_", "\"":"\'", "/":" per ", "\\":"_", ",":"_", "|":"_", ":":";" }
for frm, to in rep.iteritems():
res = res.replace(frm, to)
ret... | 2,023 |
def __virtual__():
"""
Check if macOS and PyObjC is available
"""
if not salt.utils.platform.is_darwin():
return (False, 'module: mac_wifi only available on macOS.')
if not PYOBJC:
return (False, 'PyObjC not available.')
return __virtualname__ | 2,024 |
def test_data_non_df():
"""Test the raise of error of check data."""
dataloader = DummySoccerDataLoader().set_data([4, 5])
with pytest.raises(
TypeError,
match='Data should be a pandas dataframe. Got list instead.',
):
dataloader.extract_train_data() | 2,025 |
def rearrange_kernel(kernel, data_shape=None):
"""Rearrange kernel
This method rearanges the input kernel elements for vector multiplication.
The input kernel is padded with zeroes to match the image size.
Parameters
----------
kernel : np.ndarray
Input kernel array
data_shape : tu... | 2,026 |
def exportTable(request_id, params):
"""Starts a table export task running.
This is a low-level method. The higher-level ee.batch.Export.table object
is generally preferred for initiating table exports.
Args:
request_id (string): A unique ID for the task, from newTaskId. If you are
using the cloud A... | 2,027 |
def add_parents_to_frame(qs):
"""
There seems to be bug in the django-pandas api that self-foreign keys are not returned properly
This is a workaround
:param qs:
:return:
"""
tn_parent_ids = qs.values_list("tn_parent_id", flat=True).all()
df = read_frame(qs.all(), fieldnames=get_standard... | 2,028 |
def template_check(value):
"""Check if a rendered template string equals true.
If value is not a string, return value as is.
"""
if isinstance(value, str):
return value.lower() == "true"
return value | 2,029 |
def print_top_20_disallow():
"""Makes file with top 20 disallows from files"""
print_text = ""
item_list = Counter(disallow).most_common(20)
file_name = "top_20_robot_txt_disallows.txt"
for item in item_list:
item_text = "Item: " + item[0] + " :: Count: " + str(item[1])
print_text = ... | 2,030 |
async def test_if_fires_on_change_with_for_0_advanced(hass, start_ha, calls):
"""Test for firing on change with for: 0 advanced."""
context = Context()
await hass.async_block_till_done()
hass.states.async_set("test.entity", "world", context=context)
await hass.async_block_till_done()
assert len... | 2,031 |
def return_npc(mcc, mnc):
"""
Format MCC and MNC into a NPC.
:param mcc: Country code.
:type mcc: int
:param mnc: Network code.
:type mnc: int
"""
return "{0}{1}30".format(str(mcc).zfill(3), str(mnc).zfill(3)) | 2,032 |
def class_to_bps(bw_cls):
"""
Convert a SIBRA bandwidth class to bps (Bits Per Second). Class 0 is a
special case, and is mapped to 0bps.
:param float bw_cls: SIBRA bandwidth class.
:returns: Kbps of bandwidth class
:rtype: float
"""
if bw_cls == 0:
return 0
bw_base = math.s... | 2,033 |
def _get_capacity():
"""Return constant values for dam level capacities.
Storage capacity values are measured in million cubic metres
i.e. Megalitres or Ml.
Source: https://en.wikipedia.org/wiki/Western_Cape_Water_Supply_System
@return capacity: Dict object containing maximum capacities of Wester... | 2,034 |
def create_NISMOD1_data(path_to_zip_file, path_out, path_geography):
"""
Arguments
----------
"""
print("... start running initialisation scripts", flush=True)
# Extract NISMOD population data
path_extraction = os.path.join(path_out, "MISTRAL_pop_gva")
zip_ref = zipfile.ZipFile(path_to... | 2,035 |
def login_required(f):
"""
Decorator to use if a view needs to be protected by a login.
"""
@wraps(f)
def decorated_function(*args, **kwargs):
if not 'username' in session:
return redirect(url_for('login'))
return f(*args, **kwargs)
return decorated_function | 2,036 |
def test_bare_except() -> None:
"""Bare `except` to handle any uncaught exceptions."""
def reciprocal_of(value: float) -> float:
try:
return 1 / value
except ZeroDivisionError:
raise
except:
raise
pytest.raises(TypeError, reciprocal_of, "a") | 2,037 |
def _get_image_blob(im):
"""Converts an image into a network input.
Arguments:
im (ndarray): a color image in BGR order
Returns:
blob (ndarray): a data blob holding an image pyramid
im_scale_factors (list): list of image scales (relative to im) used
in the image pyramid... | 2,038 |
def check_args():
"""Checks the arguments passed by the command line
By passing one or more parameters, you can disable a single module source.
Actual parameters allowed are:
* `-no-instagram`: disables Instagram source
* `-no-youtube`: disables YouTube source
* `-no-spotify`: disable... | 2,039 |
def toiter(x):
"""Convert to iterable. If input is iterable, returns it. Otherwise returns it in a list.
Useful when you want to iterate over something (like in a for loop),
and you don't want to have to do type checking or handle exceptions
when it isn't a sequence"""
if iterable(x):
return... | 2,040 |
def ap_date(value):
"""
Converts a date string in m/d/yyyy format into AP style.
"""
if not value:
return ''
bits = unicode(value).split('/')
month, day, year = bits
output = AP_MONTHS[int(month) - 1]
output += ' ' + unicode(int(day))
output += ', ' + year
return outp... | 2,041 |
def start_gui():
"""Initialize graphical interface in order to render board.
You must first call this function once before making calls to :py:func:`blokus.blokus_env.display_board`.
See Also
--------
blokus.blokus_env.display_board
blokus.blokus_env.terminate_gui
"""
gui.start_gui() | 2,042 |
def dump_sql(fp, query: str, encoding="utf8"):
"""
Write a given query into a file path.
"""
query = ljustify_sql(query)
for line in query:
fp.write(bytes(line, encoding=encoding))
return fp | 2,043 |
def make_design_matrix(stim, d=25):
"""Create time-lag design matrix from stimulus intensity vector.
Args:
stim (1D array): Stimulus intensity at each time point.
d (number): Number of time lags to use.
Returns
X (2D array): GLM design matrix with shape T, d
"""
padded_stim = np.concatenate([np... | 2,044 |
def delete_user_word(word_list: list, instance):
"""
Delete words in temporary dictionary, more information shows in :func:`import_dict`
:param instance: instance to execute the function
:param word_list: list of words want to delete
"""
if not hasattr(instance, "del_usr_word"):
raise N... | 2,045 |
def publisher():
"""Publishes simulated event messages to a Redis Channel"""
# Create our connection object
r = redis.StrictRedis(host=redis_host, port=redis_port, password=redis_password, decode_responses=True)
for id in range(50):
# create the event as an dict with fields type a... | 2,046 |
def _fit_subpixel_2d(image, coord, radius, voxel_size_yx, psf_yx):
"""Fit a gaussian in a 2-d image.
Parameters
----------
image : np.ndarray
Image with shape (y, x).
coord : np.ndarray, np.int64
Coordinate of the spot detected, with shape (2,). One coordinate per
dimension ... | 2,047 |
def density(sisal,temp,pres,salt=None,dliq=None,chkvals=False,
chktol=_CHKTOL,salt0=None,dliq0=None,chkbnd=False,useext=False,
mathargs=None):
"""Calculate sea-ice total density.
Calculate the total density of a sea-ice parcel.
:arg float sisal: Total sea-ice salinity in kg/kg.
:arg fl... | 2,048 |
def prod_non_zero_diag(x):
"""Compute product of nonzero elements from matrix diagonal.
input:
x -- 2-d numpy array
output:
product -- integer number
Not vectorized implementation.
"""
n = len(x)
m = len(x[0])
res = 1
for i in range(min(n, m)):
if (x[i][i] != 0):
... | 2,049 |
def LoadSparse(inputfile, verbose=False):
"""Loads a sparse matrix stored as npz file to its dense represent."""
npzfile = np.load(inputfile)
mat = sp.csr_matrix((npzfile['data'], npzfile['indices'],
npzfile['indptr']),
shape=tuple(list(npz... | 2,050 |
def _get_sw_loader_logger():
""" Setup a new logger with passed skywalking CLI env vars,
don't import from skywalking, it may not be on sys.path
if user misuses the CLI to run programs out of scope
"""
from logging import getLogger
logger = getLogger('skywalking-loader')
ch = logging.StreamH... | 2,051 |
def chain_decomposition(G, root=None):
"""Return the chain decomposition of a graph.
The *chain decomposition* of a graph with respect a depth-first
search tree is a set of cycles or paths derived from the set of
fundamental cycles of the tree in the following manner. Consider
each fundamental cycl... | 2,052 |
def test_init_params(
data,
creator,
dtype,
numpy_dtype,
ndmin: int,
copy: Optional[bool],
):
"""Check for bad combinations of init parameters leading to unexpected behavior"""
elements = (
(lambda x, y: st.floats(x, y, width=8 * np.dtype(numpy_dtype).itemsize))
if np.iss... | 2,053 |
def managed(flag=True):
"""
Puts the transaction manager into a manual state: managed transactions have
to be committed explicitly by the user. If you switch off transaction
management and there is a pending commit/rollback, the data will be
commited.
"""
thread_ident = thread.get_ident()
... | 2,054 |
def dup_lcm(f, g, K):
"""Computes polynomial LCM of `f` and `g` in `K[x]`. """
if K.has_Field or not K.is_Exact:
return dup_ff_lcm(f, g, K)
else:
return dup_rr_lcm(f, g, K) | 2,055 |
def test_dice_rolln(dice, n):
"""Test rolling many dice."""
rolls = dice.rolln(n)
assert len(rolls) == n
assert isinstance(rolls, list)
assert isinstance(rolls[0], int)
# Sum between n and s*n
assert sum(rolls) <= n * dice.sides
assert sum(rolls) >= n * 1 | 2,056 |
def alignment_guide(path, lut):
"""
Generate image alignment guide and save to disk.
"""
image = Image.new('RGBA',(lut.image_size, lut.image_size),(255,0,0,0))
draw = ImageDraw.Draw(image)
for i in range(lut.swatch_count):
image.putpixel(lut.cell_center(i),(255,0,0))
draw.rectan... | 2,057 |
def add_tag_translation(request, tag_id, lang, text):
"""Adds a translation to the given Tag."""
tag = get_object_or_404(Tag, id=tag_id)
text = urllib.unquote(text)
data = {}
langs = tag.site.get_languages(lang)
if len(langs) == 0:
data['error'] = 'No languages defined'
else:
... | 2,058 |
def etc_hosts_update(output_file=None, **kwargs):
"""Update /etc/hosts with all nodes available in configured projects
:param output_file: destination file, default is /etc/hosts
"""
update_etc_hosts_file(etc_hosts_generator(**kwargs), output_file) | 2,059 |
def simpson(x, with_replacement=False):
"""For computing simpson index directly from counts (or frequencies, if with_replacement=True)
Parameters
----------
x :
with_replacement :
(Default value = False)
Returns
-------
"""
total = np.sum(x)
if with_repla... | 2,060 |
async def setup_automation(hass, device_id, trigger_type):
"""Set up an automation trigger for testing triggering."""
return await async_setup_component(
hass,
AUTOMATION_DOMAIN,
{
AUTOMATION_DOMAIN: [
{
"trigger": {
... | 2,061 |
def generate_html_tutor_constraints(sai):
"""
Given an SAI, this finds a set of constraints for the SAI, so it don't
fire in nonsensical situations.
"""
constraints = set()
args = get_vars(sai)
# selection constraints, you can only select something that has an
# empty string value.
... | 2,062 |
def main():
"""Entry point."""
flags = _parse_args(sys.argv[1:])
logging.basicConfig(level=flags.log_level.upper())
run_experiment(flags) | 2,063 |
def run_test(request):
"""
运行用例
:param request:
:return:
"""
kwargs = {
"failfast": False,
}
runner = HttpRunner(**kwargs)
# 测试用例的路径
test_case_dir_path = os.path.join(os.getcwd(), "suite")
test_case_dir_path = os.path.join(test_case_dir_path, get_time_stamp())
... | 2,064 |
def set_up_CB(inp_d):
"""
Setting up directories and altered files
In this function we create all the needed directories and transfer
the files that were changed in order to get the program to work in KBase
into the PaperBLAST directory.
inp_d (input dict) must contain the following keys:
... | 2,065 |
def info(email):
"""Information about a specific email."""
with db_session() as db:
user = db.query(User).filter(User.email == email).first()
if user:
return [user.email, user.api_key, user.grabs]
else:
return None | 2,066 |
def TetrahedralGraph():
"""
Returns a tetrahedral graph (with 4 nodes).
A tetrahedron is a 4-sided triangular pyramid. The tetrahedral
graph corresponds to the connectivity of the vertices of the
tetrahedron. This graph is equivalent to a wheel graph with 4 nodes
and also a complete graph on fo... | 2,067 |
def build_resnet_v1(input_shape, depth, num_classes, pfac, use_frn=False,
use_internal_bias=True):
"""Builds ResNet v1.
Args:
input_shape: tf.Tensor.
depth: ResNet depth.
num_classes: Number of output classes.
pfac: priorfactory.PriorFactory class.
use_frn: if True, then use... | 2,068 |
def lr_recover_l1(invecs, intensities, nonneg=True, **kwargs):
"""Computes the low-rank matrix reconstruction using l1-minimisation
.. math::
\min_Z \sum_i \vert \langle a_i| Z | a_i \rangle - y_i \vert \\
\mathrm{s.t.} Z \ge 0
where :math:`a_i` are the input vectors and :math:`y... | 2,069 |
def fetch_function_names() -> str:
"""Returns a list of cloud function names"""
functions = fetch_functions_in_json()
logs.debug(f"Fetched {len(functions)} cloud functions")
return "Temp holder until I figure out how to get a function's name" | 2,070 |
def fieldset_experiment(objparent):
"""
:param objparent:
"""
objparent.id()
objparent.assigned_to_id()
objparent.conclusion()
objparent.created_at()
objparent.description()
# objparent.due_on() # failed this field
objparent.effort_actual()
objparent.effort_estimated()
o... | 2,071 |
def start_view_data(trans_id):
"""
This method is used to execute query using asynchronous connection.
Args:
trans_id: unique transaction id
"""
limit = -1
# Check the transaction and connection status
status, error_msg, conn, trans_obj, session_obj = \
check_transaction_st... | 2,072 |
def fft_resize(images, resize=False, new_size=None):
"""Function for applying DFT and resizing.
This function takes in an array of images, applies the 2-d fourier transform
and resizes them according to new_size, keeping the frequencies that overlap
between the two sizes.
Args:
images: a numpy a... | 2,073 |
def install_build(zipfile_name, ignore_if_exists=False):
"""
Install server build on local drive. 'zipfile_name' is the name of the
zip file in 'BSD_TEMP_FOLDER'.
The function returns the folder name of the battleserver build image.
If 'ignore_if_exists' is True, then the function returns immediatel... | 2,074 |
def vaccine_percentage(df):
"""Plot the percentage of the vaccinated population over time.
Args:
df (DataFrame): Requires data returned by get_uk_data
or get_national_data methods
Retuns:
Plot of total percentage of population vaccinated
"""
df['date'] = df['date'].... | 2,075 |
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Sequential(nn.ReplicationPad2d(1), nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=0, groups=groups, bias=False, dilation=dilation)) | 2,076 |
def get_inbound_layers_without_params(layer):
"""Return inbound layers.
Parameters
----------
layer: Keras.layers
A Keras layer.
Returns
-------
: list[Keras.layers]
List of inbound layers.
"""
return [layer for layer in get_inbound_layers(layer)
if n... | 2,077 |
def orders_matchresults(symbol, types=None, start_date=None, end_date=None, _from=None, direct=None, size=None):
"""
:param symbol:
:param types: 可选值 {buy-market:市价买, sell-market:市价卖, buy-limit:限价买, sell-limit:限价卖}
:param start_date:
:param end_date:
:param _from:
:param direct: 可选值{prev 向前... | 2,078 |
def precision(y_true, y_pred):
"""Precision metric.
Only computes a batch-wise average of precision.
Computes the precision, a metric for multi-label classification of
how many selected items are relevant.
"""
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
predicted_positiv... | 2,079 |
def check_error_in_status(retcode, statuses):
"""Check possible errors in status.
Parameters
----------
retcode : int
Return code of an MPI function
statuses : MPI_Status[]
Array of MPI_Status objects.
Raises
------
MPIStatusErrors
If there are errors in status
... | 2,080 |
def _is_grpc_unary_method(attr):
"""Check if attribute is a grpc method that returns unary."""
return isinstance(attr, (grpc.UnaryUnaryMultiCallable, grpc.StreamUnaryMultiCallable)) | 2,081 |
def addPhoto(fileName, personName):
"""
Load a supplied photo and add detected facial encoding to the database
"""
#Check if image is a jpg
if (fileName[-4:] != ".jpg"):
print("\n[!] File extenstion must be .jpg!\n")
return
#Check image exists
if (not os.path.isfile(fileNam... | 2,082 |
def gridcorner(
D,
xyz,
labels=None,
projection="max_slice",
max_n_ticks=4,
factor=2,
whspace=0.05,
showDvals=True,
lines=None,
label_offset=0.4,
**kwargs
):
"""Generate a grid corner plot
Parameters
----------
D: array_like
N-dimensional data to plot... | 2,083 |
def read_dig_hpts(fname, unit='mm'):
"""Read historical .hpts mne-c files.
Parameters
----------
fname : str
The filepath of .hpts file.
unit : 'm' | 'cm' | 'mm'
Unit of the positions. Defaults to 'mm'.
Returns
-------
montage : instance of DigMontage
The montag... | 2,084 |
def GetTaskAttr( fname, attrName, defaultVal = None ):
"""Return the specified attribute of a task, or the specified default value if the task does not have this attribute."""
for line in SlurpFile( fname ).rstrip('\n').split('\n'):
arg, val = line.split('\t')
if arg == attrName: return coerceVa... | 2,085 |
def print_board(white, black):
"""Produce GnuGO like output to verify board position.
Args:
white (np.array): array with 1's for white
black (np.array): array with 1's for black
Returns:
str: gnugo like output (without legend)
"""
s = ''
for x in xrange(19):
for... | 2,086 |
def phaseCorrelate(src1, src2, window=None):
""" phaseCorrelate(src1, src2[, window]) -> retval, response """
pass | 2,087 |
def get_repositories_containing_graph(name: str) -> List[str]:
"""Returns the repositories containing a graph with the given graph name.
Parameters
----------------------------
name: str,
The name of the graph to retrieve.
Returns
----------------------------
List of repository nam... | 2,088 |
def build_query(dct):
"""Build SQL with '?' and value tuples from clause dictionary"""
if (dct is not {}):
str_clauses = ''
tpl_values = ()
bln_start = True
#print dct
for str_field, dct_op_val in dct.iteritems():
if (str_field is not None):
if... | 2,089 |
def load_secrets(fn=".env", prefix="DJANGO_ENV_", **kwargs):
"""Load a list of configuration variables.
Return a dictionary of configuration variables, as loaded from a
configuration file or the environment. Values passed in as
``args`` or as the value in ``kwargs`` will be used as the
configurati... | 2,090 |
def dependency_chain(pkgname):
"""Return an ordered list of dependencies for a package"""
depends = recurse_depends(pkgname)
return set(list(depends.keys()) + list(itertools.chain.from_iterable(depends.values()))) | 2,091 |
def with_input(func: Callable) -> Callable:
"""
Attaches a "source" argument to the command.
"""
return click.argument(
"source", type=click.Path(exists=True), required=True
)(func) | 2,092 |
def check_loop_validity(inst_list):
""" Given a list of instructions, check whether they can form a valid loop.
This means, checking for anything that could create an infinite loop.
We are also disallowing double loops right now"""
for i, c in enumerate(inst_list):
if c in [5, 6, 16, 25]:
... | 2,093 |
def target_channel_id_name_list(
conversations_list: list=None, including_archived: bool=False):
"""extract targeted channels id list from conversations_list response.
Returns:
id_list, name_list
"""
id_list = []
name_list = []
for ch in conversations_list:
if includi... | 2,094 |
def NETWORKDAYS(*args) -> Function:
"""
Returns the number of net working days between two provided days.
Learn more: https//support.google.com/docs/answer/3092979
"""
return Function("NETWORKDAYS", args) | 2,095 |
def calc_high_outlier(values) -> float:
"""Calculates the high outlier from a pandas Series"""
q1, q3 = [values.quantile(x, 'midpoint') for x in (0.25, 0.75)]
return q3 + 1.5 * (q3 - q1) | 2,096 |
def test_api():
"""Test some aux methods."""
assert iemre.get_dailyc_mrms_ncname() is not None
assert iemre.get_dailyc_ncname() is not None | 2,097 |
def get_sql_delete_by_ids(table: str, ids_length: int):
"""
获取添加数据的字符串
:param table:
:return:
"""
# 校验数据
if not table:
raise ParamError(f"table 参数错误:table={table}")
if not ids_length or not isinstance(ids_length, int):
raise ParamError(f"ids_length 参数错误:ids_length={ids_le... | 2,098 |
def save_results_numpy(dir, filename, results):
"""Save the given dictionary of results into a numpy file.
Args:
results (dict): Dictionary of results
"""
file_path = os.path.join(dir, filename)
assert not os.path.exists(file_path), 'File ' + str(file_path) + ' already exists!'
... | 2,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.