content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_existing_path_FileLinks_repr_alt_formatter():
"""FileLinks: Calling repr() functions as expected w/ alt formatter
"""
td = mkdtemp()
tf1 = NamedTemporaryFile(dir=td)
tf2 = NamedTemporaryFile(dir=td)
def fake_formatter(dirname,fnames,included_suffixes):
return ["hello","world"]
... | 76,600 |
def test_paragraph_extra_e3b():
"""
Test case extra e3b: Inline image inside of inline link
"""
# Arrange
source_markdown = """a](/uri)a"""
expected_tokens = [
"[para(1,1):]",
"[text(1,1):a:]",
"[image(1,2):inline:/uri::foo bar::::foo :Fals... | 76,601 |
def model_cv_mse(Model, X, y, alphas, k = 5):
"""
This function calculates the MSE resulting from k-fold CV using lasso regression performed on a training subset of
X and y for different values of alpha.
Inputs:
Model (sklearn model): the type of sklearn model with which to fit the data - Ridg... | 76,602 |
def latent_samples_FGPVAE(train_images, train_aux_data, vae, GP, N_t, clipping_qs=False):
"""
Get latent samples for training data. For t-SNE plots :)
:param train_images:
:param train_aux_data:
:param vae:
:param GP:
:param clipping_qs:
:return:
"""
train_aux_data ... | 76,603 |
def rotate_matrix_cw(matrix, angle = 90):
"""Rotate the matrix clockwise by certain angle (multiples of 90 deg)."""
def rotate_matrix_90(matrix):
rows, columns = matrix.shape
matrix_new = np.zeros((columns, rows))
for i in range(rows):
for j in range(columns):
... | 76,604 |
def test_compute_perfect_model_different_dims_quite_close(
perfectModelEnsemble_initialized_control,
):
"""Tests nearly equal dim=['init','member'] and dim='member'."""
stack_dims_true = perfectModelEnsemble_initialized_control.verify(
comparison="m2c", metric="rmse", dim=["init", "member"],
)["... | 76,605 |
def SplitRM(instruction):
"""Split instruction into two versions (using register or memory).
Args:
instruction: instruction.
Returns:
List of one or two instructions. If original instruction contains operand
that can be either register or memory (such as 'E'), two specific versions
are produced.... | 76,606 |
def reduce_mem_usage(df, verbose=False):
""" iterate through all the columns of a dataframe and modify the data type
to reduce memory usage.
"""
df = pd.DataFrame(df)
UINT8 = np.iinfo(np.uint8)
UINT16 = np.iinfo(np.uint16)
UINT32 = np.iinfo(np.uint32)
UINT64 = np.iinfo(np.uint64)
... | 76,607 |
def deserialize_ndarray_npy(d):
"""
Deserializes a JSONified :obj:`numpy.ndarray` that was created using numpy's
:obj:`save` function.
Args:
d (:obj:`dict`): A dictionary representation of an :obj:`ndarray` object, created
using :obj:`numpy.save`.
Returns:
An :obj:`ndar... | 76,608 |
def lic_flow(vectors,len_pix=10):
""" MANU: was side to side with lic_internal????? """
vectors = np.asarray(vectors)
m,n,two = vectors.shape
if two!=2:
raise ValueError
result = np.zeros((2*len_pix+1,m,n,2),dtype=np.int32) # FIXME: int16?
center = len_pix
result[center,:,:,0] = np.a... | 76,609 |
def compute_hessian(image):
""" Compute Hessian components of 2D image using finite difference.
Parameters
----------
image: array_like
Input image.
Returns
-------
hxx, hxy, hyy: ndarray, ndim=2
Gradients in x, y directions respectively.
"""
image = np.asarray(ima... | 76,610 |
def run_port_465_command(target_list, tnum):
"""
Use ZGrab to test for SMTPS on port 465
"""
if global_sleep_time > 0:
time.sleep(global_sleep_time)
targets = ""
for ip in target_list:
targets = targets + ip + "\\n"
targets = targets[:-2]
p1 = subprocess.Popen(["echo", "... | 76,611 |
def test_click_table_printer(capsys):
"""Test click_table_printer."""
headers = ['header_one']
sample_data = [['very_very_long_row_one'],
['very_very_long_row_two']]
click_table_printer(headers, [], sample_data)
out, err = capsys.readouterr()
assert out == 'HEADER_ONE ... | 76,612 |
def projectToImage(pts_3D, P):
"""
PROJECTTOIMAGE projects 3D points in given coordinate system in the image
plane using the given projection matrix P.
Usage: pts_2D = projectToImage(pts_3D, P)
input: pts_3D: 3xn matrix
P: 3x4 projection matrix
output: pts_2D: 2xn matrix
las... | 76,613 |
def docs():
"""
Displays the API documentation at '/'
"""
return render_template('index.html',
last_updated=dir_last_updated('app/static')) | 76,614 |
def courant(dx, dt, v_max, **kwargs):
"""
Calculate the Courant's number describing
stability of the numerical scheme.
Parameters
----------
dx : float
Size of the spatial grid cell [m].
dt : float
Time step [s].
v_max : float
Max. velocity of the model.
Returns
-------
C : flo... | 76,615 |
def weighted_count(instances_obj, m_weights):
"""Weight nt count by nt weights at each position"""
weighted_counts = {}
for letter in instances_obj.alphabet:
weighted_counts[letter] = [0] * instances_obj.length
for idx, instance in enumerate(instances_obj):
for position, letter in enumer... | 76,616 |
def plot_interaction_network(
kg_data: pd.DataFrame
) -> nx.DiGraph:
"""Plot a knowledge graph based on the interaction data."""
interaction_graph = nx.DiGraph()
# Append the source to target mapping to the main data edgelist
for idx in tqdm(kg_data.index, desc='Plotting interaction network: ')... | 76,617 |
def space_linear_tree(actions, sent=None, SHIFT=0, REDUCE=1):
""" Use `( ` instead of `(`. Similarly for ` )`.
"""
stack = []
pointer = 0
if sent is None:
sent = list(map(str, range((len(actions)+1) // 2)))
for action in actions:
if action == SHIFT:
word = ... | 76,618 |
def check_labels_file_header(filename):
"""Validate that filename corresponds to labels for the MNIST dataset."""
with tf.gfile.Open(filename, "rb") as fptr:
magic = read32(fptr)
read32(fptr) # num_items, unused
if magic != 2049:
raise ValueError(
"Invalid ma... | 76,619 |
def n_thermal_qbits(pops: list) -> DensityMatrix:
"""
Args:
pops: a list of population numbers between 0 and .5
Returns:
A density matrix for n thermal qbits with the specified populations
"""
num_states = 2 ** len(pops)
data = []
for i in range(num_states):
state = ... | 76,620 |
def entropysea(salt=None,temp=None,pres=None,dliq=None,chkvals=False,
chktol=_CHKTOL,salt0=None,temp0=None,pres0=None,dliq0=None,
chkbnd=False,useext=False,mathargs=None):
"""Calculate sea-ice seawater entropy.
Calculate the specific entropy of seawater in sea-ice.
:arg salt: Salinity in k... | 76,621 |
def alpha_beta_pruning(board, color, depth):
"""
Returns the best move calculated using the C++ compiled binary
"""
st = time.time()
player = 16
proc = subprocess.Popen(
["ai/minimax", str(player), str(depth)],
stdout=subprocess.PIPE,
stdin=subprocess.PIPE
)
data = transform_board_to_strin... | 76,622 |
def down_sample(period, source, target):
"""
Downsamples all the csv files located in source folder, and saves the new csv in target folder
:param period: period [ms] at which you want to sample the time series
:param source: subfolder with original data
:param target: subfolder to save the downsamp... | 76,623 |
def rm(args):
"""
Remove files from tracking and delete the file.
Args:
args (obj): Arguments from command line.
"""
args.delete = True
return remove(args) | 76,624 |
def compute_cost_rmsle(Y, Y_hat):
"""
Computes the RMSLE cost.
Arguments:
Y : true labels vector placeholder, same shape as Y_hat
Y_hat : output of forward propagation of shape (1, number of examples)
Returns:
cost : Tensor of the cost function.
"""
return tf.sq... | 76,625 |
def standard_deviation(series):
"""
implements the sample standard deviation of a series from scratch
you may need a for loop and your average function
also the function math.sqrt
you should get the same result as calling .std() on your data
https://pandas.pydata.org/pandas-docs/stable/reference... | 76,626 |
async def test_temperature_setting_climate_range(hass):
"""Test TemperatureSetting trait support for climate domain - range."""
assert helpers.get_google_type(climate.DOMAIN, None) is not None
assert trait.TemperatureSettingTrait.supported(climate.DOMAIN, 0, None)
hass.config.units.temperature_unit = T... | 76,627 |
def ldns_rdf2buffer_str_time(*args):
"""LDNS buffer."""
return _ldns.ldns_rdf2buffer_str_time(*args) | 76,628 |
def read_file(netcdf_file_name):
"""Reads SHIPS data from NetCDF file.
:param netcdf_file_name: Path to input file.
:return: ships_table_xarray: xarray table. Documentation in the xarray
table should make values self-explanatory.
"""
return xarray.open_dataset(netcdf_file_name) | 76,629 |
def get_settings(values):
"""
Retrieve settings from command line, and set them up
"""
settings = Settings()
settings.input.XC.GGA = values['functional']
if values['dispersion'] is not None:
settings.input.XC.DISPERSION = values['dispersion']
settings.input.BASIS.type = values['b... | 76,630 |
async def test_swagger_ui_config_json(aiohttp_api_spec_dir, aiohttp_client):
""" Verify the swagger-ui-config.json file is returned for swagger_ui_config option passed to app. """
swagger_ui_config = {"displayOperationId": True}
options = {"swagger_ui_config": swagger_ui_config}
app = AioHttpApp(__name_... | 76,631 |
def help_info(self, commands):
"""
systeminfo : Shows system information
=======================================================
Usage:
show system info -i {serverid}
-i -- serverid, the target server number. Typically 1-48
[-h] -help; displa... | 76,632 |
def o2satv2b(salinity: np.ndarray, temp: np.ndarray) -> np.ndarray:
"""
Calculate oxygen concentration at saturation
:param salinity:
:param temp:
:return:
"""
# Define constants, etc. for saturation calculation
# The constants used are for units of umol O2/kg
a0 = 5.80818
a1 = ... | 76,633 |
def comma_flow_batch_gen(data, batch_size):
"""
Generate training images given image paths and associated steering angles
:param data : (numpy.array) the loaded data (converted to list from pandas format)
:param batch_size : (int) batch size for training
:rtype: Iterator[images, angles... | 76,634 |
def get_factories(
config,
device,
debug = False,
):
"""Feed config to factories and return objects."""
pretrain_loaders = get_pretraining_dataloaders(config, debug)
downstream_loaders = get_downstream_dataloaders(config, debug)
model = factory.model_from_config(config)
optimizer = factory.optim_f... | 76,635 |
def trace_block(msg=None):
""" Traces the execution of a code block.
Example:
with trace_block("Creating universe"):
universe = Universe(god=None)
universe.bang()
:param msg: Message to log
:return: A decorator function
"""
context = gcm.get_context()
if tra... | 76,636 |
def _get_crm_resource_v2(credentials):
"""
Instantiates a Google Compute Resource Manager v2 resource object to call the Resource Manager API.
We need a v2 resource object to query for GCP folders.
:param credentials: The GoogleCredentials object
:return: A CRM v2 resource object
"""
return ... | 76,637 |
def make_parser(inheritable=False):
"""Expose parser for ``main``.
Parameters
----------
inheritable: bool
whether the parser can be inherited from (default False).
if True, sets ``add_help=False`` and ``conflict_hander='resolve'``
Returns
-------
parser: ArgumentParser
... | 76,638 |
def _obtain_rapt(http_request, access_token, requested_scopes, rounds_num=5):
"""Given an http request method and reauth access token, get rapt token.
Args:
http_request: callable to run http requests. Accepts uri, method, body
and headers. Returns a tuple: (response, content)
acces... | 76,639 |
def format_attribute(
el,
visibility=False,
is_derived=False,
type=False,
multiplicity=False,
default=False,
tags=False,
):
"""
Create a OCL representation of the attribute,
Returns the attribute as a string.
If one or more of the parameters (visibility, is_derived, type,
... | 76,640 |
def function(op):
"""
Convert a function into a delayed evaluator.
The value of the function is computed from the values of the parameters
at the time that the function value is requested rather than when the
function is created.
"""
# Note: @functools.wraps(op) does not work with numpy ufu... | 76,641 |
def convolve(x, W, input_multi_channel=False, output_multi_channel=False, mode='full'):
"""Convolution that supports multi-dimensional and multi-channel inputs.
Args:
x (array): input array with shape batch_shape + input_shape
if input_multi_channel=False.
Otherwise with shape ... | 76,642 |
def unify_projection(dic):
"""Unifies names of projections.
Some projections are referred using different names like
'Universal Transverse Mercator' and 'Universe Transverse Mercator'.
This function replaces synonyms by a unified name.
Example of common typo in UTM replaced by correct spelling::
... | 76,643 |
def diagonal_zigzag_square(x):
"""
Fill square matrix in diagonal order.
x = [0, ..., 8]
y = diagonal_zigzag_square(x)
y = [[0 2 5]
[1 4 7]
[3 6 8]]
:param x: vector of length n**2.
:return: y
"""
x = np.array(x)
# length of the square side
n = np.sqrt(le... | 76,644 |
def make_access_var(name, agent, target_variable=False, target_value=False,
radius=1000, agg_function='sum', decay='flat', log=True,
filters=False):
"""
Generator function for accessibility variables. Registers with orca.
"""
@orca.column('nodes', name, cache=Tru... | 76,645 |
def make_path(index):
"""
Given a size of a node to add get the binary path to reach it.
"""
order = "{0:b}".format(index + 1)
order = torch.tensor(list(map(int, order)))
print(order)
out = [1]
for i in range(1, len(order)):
out.append(order[i] + 2 * out[-1])
return torch.ten... | 76,646 |
def getName(full_name):
"""
the getName function splits the name of the application returning the executable name and
ignoring the path details.
:param full_name: the path and executable name
:return: the executable name
"""
# Determine if '\\' and ':' are within the full_name
if ':' in ... | 76,647 |
def batchnorm_backward_alt(dout, cache):
"""
Alternative backward pass for batch normalization.
For this implementation you should work out the derivatives for the batch
normalizaton backward pass on paper and simplify as much as possible. You
should be able to derive a simple expression for the backward p... | 76,648 |
def test_odskey(platform_id, base_url):
"""Basic tests for the CLI """
other_args = []
if platform_id is not None:
assert base_url is None
other_args += ['-p', platform_id]
url_used = "https://%s.opendatasoft.com" % platform_id
elif base_url is not None:
other_args += ['... | 76,649 |
def survey_id(client: citric.Client) -> Generator[int, None, None]:
"""Import a survey from a file and return its ID."""
with open("./examples/survey.lss", "rb") as f:
survey_id = client.import_survey(f, survey_id=98765)
yield survey_id
client.delete_survey(survey_id) | 76,650 |
def test_seir_forecast():
"""
Use the SEIR forecasting example to compare peak size and time predictions
at two forecasting dates.
Note that the observation probability is set to 0.5 (much too high) and so
we should only obtain sensible forecasts if the observation model is able
to use the look... | 76,651 |
def _package_rootdir(name):
"""Get the root directory of the installed package with the given name."""
initfile = importlib.util.find_spec(name).origin
return os.path.split(os.path.split(initfile)[0])[0] | 76,652 |
def start():
"""
Builds default mininet topology with 4 clients and 3 servers. Tests the scenario where we are overloading the load
balancing server
"""
size = 7
servs = 3
topo = SingleSwitchTopo(n=size)
parser = ArgumentParser(description='Builds default mininet topology with ... | 76,653 |
def _check_stcs(stc1, stc2):
"""Helper to check correctness"""
assert_allclose(stc1.times, stc2.times)
assert_allclose(stc1.data, stc2.data)
assert_allclose(stc1.vertices[0], stc2.vertices[0])
assert_allclose(stc1.vertices[1], stc2.vertices[1])
assert_allclose(stc1.tmin, stc2.tmin)
assert_al... | 76,654 |
def selfcal_pcal(imc, combine='spw,scan', trial='1'):
"""
Self Calibration. Generate a per observation solution first.
"""
if trial == '1':
solint = 'inf' # Sum entire scheduling block
elif trial == '2':
solint = '1800s' # Half block
else:
raise ValueError('Invalid pcal... | 76,655 |
def phovea(registry):
"""
register extension points
:param registry:
"""
# generator-phovea:begin
<% - sextensions.map((d) => ` registry.append('${d.type}', '${d.id}', '${name.toLowerCase()}.${d.module}', ${stringifyPython(d.extras, ' ')})`).join('\n\n')%>
# generator-phovea:end
pas... | 76,656 |
def _cor_coeff(X, y):
"""
pearson correlation coefficient
"""
corr, _ = pearsonr(X, y)
return corr | 76,657 |
def test_set_tokens(doc):
"""
Test setting values on tokens
"""
ner_contents = ["O", "ARTIFACT", "ARTIFACT", "O", "CAT"]
doc.set(fields=NER,
contents=ner_contents,
to_token=True)
result = doc.get(NER, from_token=True)
assert result == ner_contents | 76,658 |
def __battery_charge_decoder__(port: serial.Serial, *args, **kwargs):
"""Returns the raw battery value as a byte."""
return port.read(1)[0] | 76,659 |
def transform_viewpoint(v):
"""Transforms the viewpoint vector into a consistentrepresentation"""
return np.concatenate([v[:, :3],
np.cos(v[:, 3:4]),
np.sin(v[:, 3:4]),
np.cos(v[:, 4:5]),
np.sin(v[:, 4:5... | 76,660 |
def alpino(doc, output="raw"):
"""Wrapper around the Alpino (dependency) parser for Dutch.
Expects an environment variable ALPINO_HOME to point at
the Alpino installation dir.
The script uses the 'dependencies' end_hook to generate lemmata and
the dependency structure.
Parameters
--------... | 76,661 |
def inverseKinematics(target, rootJoint, numJoints):
"""
Solve the inverse Kinematics problem using the BFGS optimisation algorithm as described in:
Inverse Kinematics The state of the art (http://image.diku.dk/projects/media/morten.engell_noerregaard.07.pdf)
target - The target coordinates
rootJoint - The robot ... | 76,662 |
def contar_consonantes(cadena):
"""
Cuenta las vocales en una cadena
>>> contar_consonantes('hola')
2
>>> contar_consonantes('Duque')
2
>>> contar_consonantes('qwqwqwq')
7
:param cadena:
:return:
"""
return len(cadena) - contar_vocales(cadena) | 76,663 |
def list_all_csv_files(dir):
"""List all sgf-files in a dir
Recursively explores a path and returns the filepaths
for all files ending in .sgf
"""
root_dir = os.path.abspath(dir)
sgf_files = []
for root, sub_dirs, files in os.walk(root_dir):
for file in files:
path = os.... | 76,664 |
def SpecificSub(subject): #Aditi edit
"""
Function to separate correct and wrong answers on a subject basis from sub_correct and sub_wrong
sub_resp is a dictionary with correct and wrong answers for each subject
"""
sub_resp = {}
str1 = subject + '_correct'
str2 = subject + '_wrong'
... | 76,665 |
def get_color(rgb):
"""Get the name of a color for a RGB value.
Resolve the human readable names for a RBG value. This method is a great
speed increase over the `get_most_likely_colors` method, however it assumes
that the hue is the exact color name and is limited to 16 colors (for now).
Args:
... | 76,666 |
def other_sentence(type, request, sentence):
"""
process the other from of a sentence
Input=type and requesting of sentence and the sentence
Output=class Sentence
"""
#init... | 76,667 |
def get_host_file(_path=None):
"""
If ``_path`` is passed in, return that (makes it easier for the caller if
it can pass a ``None``) otherwise look into the most common locations for
a host file and if found, return that.
"""
if _path:
return _path
# if no path is passed onto us try ... | 76,668 |
def expand_families(stmts_in, **kwargs):
"""Expand FamPlex Agents to individual genes.
Parameters
----------
stmts_in : list[indra.statements.Statement]
A list of statements to expand.
save : Optional[str]
The name of a pickle file to save the results (stmts_out) into.
Returns
... | 76,669 |
def _run_suite(test_class, config=default_config, debug=ENABLE_DEBUG,
**kwargs):
"""Run a test of the given class, passing extra parameters as arguments.
Args:
test_class (type): class inheriting from AbstractTest.
config (dict): run configuration dict.
debug (bool): whet... | 76,670 |
def prep_img_motors(n_mot, img_motors, prev_out=True, tail_in=True,
timeout=None):
"""
Plan to prepare image motors for taking data. Moves the correct imagers in
and waits for them to be ready.
Parameters
----------
n_mot: int
Index of the motor in img_motors that we... | 76,671 |
def get_all_classes_of_module(
module: str,
base_class: Optional[Type[Any]] = None,
ignore: Sequence[Type[Any]] = tuple(),
):
"""Get a set of classes defined in the specified module to include into __all__."""
classes = set()
resolved_module = sys.modules[module]
for name, member in getmembe... | 76,672 |
def test_bake_custom_project(cookies, custom_template):
"""Test for 'cookiecutter-template'."""
result = cookies.bake(template=str(custom_template))
assert result.exit_code == 0
assert result.exception is None
assert result.project_path.name == "my-project-repo"
assert result.project_path.is_d... | 76,673 |
def approx_eq_above(a, b):
"""
a < b
:param a:
:param b:
:return:
"""
if approx_eq(a, b):
return True
else:
return a <= b | 76,674 |
def description(value):
"""A string providing a description of the application
(default: none)
:param str value: Description value
"""
global _parser
_parser.description = value | 76,675 |
def help():
"""Display a small help guide"""
help_str = """
TOTP-cli. Generates TOTP from given secret
usage: totp [COMMAND]
and then follow instructions
commands:
- add (add secret to the keyring)
- show (show all the accounts)
- get (generate TOTP of a account)
- help (this)
... | 76,676 |
def precision_score(targets, preds, cm=None, w=None, average='binary'):
"""
:purpose:
Calculates the precision score between a discrete target and pred array
:params:
targets, preds : discrete input arrays, both of shape (n,)
cm : if you have previously calculated a confusion matrix... | 76,677 |
def test_swap_time_to_year_errors(test_df):
"""Assert that swapping time column for year (int) raises the expected errors"""
# swapping time to year raises when the IamDataFrame has time domain `year`
if test_df.time_col == "year":
match = "Time domain must be datetime to use this method"
w... | 76,678 |
def complete_feature(ctx, args, incomplete):
"""Completion function that returns feature/<id> for open issues."""
return sorted([('feature/{}'.format(id), description) for id, description in complete_issue(ctx, args, incomplete)]) | 76,679 |
def min_weight_simple_path_anneal(
graph: nx.Graph,
n: int,
start_path=None,
anneal_schedule: Optional[np.array] = None,
weight_fun: Callable[[nx.Graph, List], float] = path_weight):
"""A simulated-annealing algorithm for finding a simple path consisting of
n nodes in the... | 76,680 |
def creer_entete(nomFichier) :
"""!Crée l'en-tête du fichier
Prend le nom de base du fichier et sa taille, et l'écrit dans l'en-tête.
@param nomFichier Nom du fichier à concaténer
@return L'en-tête à écrire dans le fichier d'archive
"""
# Pour l'en-tête, on fait un truc simple avec le nom du ... | 76,681 |
def upload_to_sharepoint(settings_file, distribution):
"""
Check that latest build is not yet on Sharepoint. Download from Artifactory and upload to Sharepoint.
Add new build date to list of product on SP
Args:
settings_file: path to file with download settings
distribution: linux or win... | 76,682 |
def dX_dt_Duffing(X,t=0):
""" Return the Duffing oscillator derivative """
return array([X[1],
-epsi*X[1] -X[0]*(beta*X[0]**2+alpha)]) | 76,683 |
def tl(
ctx: click.Context,
next: bool,
first: bool,
goto_date: str,
today: bool,
yesterday: bool,
date_prefix: str,
count: str,
pub: bool,
pri: bool,
fav: bool,
limit: int,
zen: bool,
):
"""Timeline: Read my messages. (阅读自己发布的消息)
Examples:
ago tl ... | 76,684 |
def stake(amount, token, account):
"""stake a token"""
stm = shared_blockchain_instance()
if stm.rpc is not None:
stm.rpc.rpcconnect()
if not stm.is_steem:
print("Please set a Steem node")
return
if not account:
account = stm.config["default_account"]... | 76,685 |
def mock_api_request():
"""Patch simplepush api request."""
with patch("homeassistant.components.simplepush.config_flow.send"), patch(
"homeassistant.components.simplepush.config_flow.send_encrypted"
):
yield | 76,686 |
def mySettings():
""" Define your trading system settings here """
settings = {}
print('your call')
# Futures Contracts
settings['markets'] = ['CASH', 'KSU', 'VLO', 'ZTS', 'GOOG', 'AMZN', 'AAPL', 'BA', 'FB', 'NFLX', 'THC', 'F_US',
'F_TU', 'F_ES']
# settings['markets... | 76,687 |
def iou(segments1, segments2):
"""Computes pairwise intersection-over-union between segment collections.
Args:
segments1 (numpy array): shape [N, 2] holding N segments
segments2 (numpy array): shape [M, 4] holding N boxes.
Returns:
a numpy array with shape [N, M] representing pairwi... | 76,688 |
def to_feed(df):
"""Generate and return a feed item for the given data frame"""
fg = FeedGenerator()
fg.id(feed["id"])
fg.title(feed["title"])
fg.link(href=feed["link"], rel="self")
fg.language(feed["language"])
fg.description(feed["description"])
fg.generator("SNSZ")
fg.rights(feed[... | 76,689 |
def find_index(filename):
"""Search the file index of the filename, if any, or return None."""
r = re.search(r"([^\n]+)\.([^\.]+)\.([0-9]+)$", filename)
if r:
return int(r.group(3))
# If the filename has no index in it, and if the file does not actually
# exist, return the index of an existi... | 76,690 |
def validate_auth_keys(path, extension):
"""
validates and maintains ZMQ Auth Keys/Certificates
"""
#check for valid path
if not(os.path.exists(path)): return False
#check if directory empty
if not(os.listdir(path)): return False
keys_buffer = [] #stores auth-keys
# loop over auth-keys
for ... | 76,691 |
def filter_links(links, **kwargs):
"""
"""
filtered_links = {}
for url, v in links.items():
parsed = urlparse(url)
if parsed.netloc in ['scholar.google.com', 'scholar.google.ca']:
# At this point for google scholar, we are only
# interested in the links
... | 76,692 |
def use_versioneer():
"""
Setup versioneer, auto versioning system.
Args:
None
Returns:
None
"""
run_shell_command(['versioneer', 'install']) | 76,693 |
def runtimeerror_error(e):
"""Flask error handler for RuntimeError exceptions"""
log.exception("RuntimeError exception raised")
return json_error(500, "Internal Server Error", str(e)) | 76,694 |
def arg_types_from_json(arg_types_json: str) -> Dict[str, type]:
"""Reify the encoded argument types from the format produced by arg_types_to_json."""
arg_types = json.loads(arg_types_json)
return {name: type_from_dict(type_dict) for name, type_dict in arg_types.items()} | 76,695 |
def service_signal(service, ident=None):
"""Encode service and identifier into signal."""
signal = "{}_{}".format(DOMAIN, service)
if ident:
signal += "_{}".format(ident.replace(".", "_"))
return signal | 76,696 |
def test_three_chars_with_zero_repeat():
"""Test that prefix regex matches three combinations that contain 0."""
groups = RE_VIM_PREFIX.match("20D").groups()
assert groups == ("20", "D", "") | 76,697 |
def create_dir(path):
""" will try and make sure that path exists at all costs. raises an
exception if it fails at this task. """
if not os.path.exists(path):
try : os.makedirs(path)
except Exception as e : raise FailedToCreateDir(path, e)
else: # if no error occurs... | 76,698 |
def is_version_bump_enabled(bump_config: Mapping, ctx: Optional[click.Context] = None, *, is_publish_from_branch_allowed: Optional[bool] = None) -> bool:
"""
Check if current branch with version configuration is allowed to bump version
To avoid multiple is_publish_branch calls this can optionally be passed ... | 76,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.