content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def load_panel_from_excel(excelfile):
"""Load a pandas Panel object by reading it from an Excel spreadsheet.
:param excelfile:
Path to Excel file.
:returns:
pandas Panel object.
"""
paneldict = {}
xl = pd.ExcelFile(excelfile)
for sheet in xl.sheet_names:
frame = pd.read_... | 5,309,000 |
def load_config(config_file):
"""
load config
"""
config = configparser.RawConfigParser()
config.optionxform = str
config_file = real_path(config_file)
if not os.path.exists(config_file):
print("config file %s not exist!" % config_file)
sys.exit(0)
config.read(... | 5,309,001 |
def tweets_request(tweets_ids):
"""
Make a request to Tweeter API
"""
df_lst = []
for batch in tqdm(tweets_ids):
url = "https://api.twitter.com/2/tweets?ids={}&&tweet.fields=created_at,entities,geo,id,public_metrics,text&user.fields=description,entities,id,location,name,public_metrics,u... | 5,309,002 |
def test_configure_live_does_not_leak_passwords(tmpdir, capsys, cursor, db_config):
"""
We add a new user (NEW_USER) through pgbedrock and make sure that 1) this change isn't
committed if we pass --check and 2) this change _is_ committed if we pass --live
"""
# Assert that we start without the role ... | 5,309,003 |
def prefix_to_netmask(in_prefix):
"""
Converts a prefix into a netmask
:param in_prefix: Cidr prefix n <= 32
:return: Netmask value
"""
prefix = int(in_prefix)
if prefix > 32 or prefix <= 0:
return None
return IPAddress(inet_ntoa(pack(">I", (0xffffffff << (32 - prefix)) & 0xffff... | 5,309,004 |
def compute_class_correspondence(predicted_domain, true_domain, verbose=True):
"""Compute the best match of two lists of labels among all permutations."""
def mismatches(domain1, domain2):
return (domain1 != domain2).sum()
def associate(domain, current_ids, new_ids):
new_domain = deepcopy(d... | 5,309,005 |
def test_config():
"""Test Config."""
config = Config()
config.update(dict(invert=True, overflow=('-D', 'key=value'), root_ref='master', verbose=1))
# Verify values.
assert config.banner_main_ref == 'master'
assert config.greatest_tag is False
assert config.invert is True
assert config.... | 5,309,006 |
def adjust_model_for_inference(config: ModelConfigBase, lightning_model: InnerEyeLightning) -> None:
"""
Makes all necessary adjustments to use a given model for inference, possibly on multiple GPUs via
model parallelization. The method also computes parameters like output patch size for segmentation model,... | 5,309,007 |
def l2norm(
mdata: Union[MuData, AnnData],
mod: Optional[Union[Iterable[str], str]] = None,
rep: Optional[Union[Iterable[str], str]] = None,
n_pcs: Optional[Union[Iterable[int], int]] = 0,
copy: bool = False,
) -> Optional[Union[MuData, AnnData]]:
"""
Normalize observations to unit L2 norm.
... | 5,309,008 |
def topsis(df, weights, impacts):
"""
Validates dataframe, impacts, weights and calculates performance score.
Outputs a dataframe with "Performance Score" and "Rank" column appended.
"""
validate_data(df, weights, impacts)
ops_df = df.iloc[:,1:]
## normalized matrix
ops_df1 = ops_df ** 2
demoninat... | 5,309,009 |
def mergeGC_genecategories(GC_content_df, gene_categories):
"""merged GC content df with gene categories"""
# read in gene categories
gene_cats = pd.read_csv(gene_categories, sep="\t", header=None)
gene_cats.columns = ["AGI", "gene_type"]
# merge to limit to genes of interest
GC_content_categori... | 5,309,010 |
def noise_lut_range(atracks, xtracks, noiseLuts):
"""
Parameters
----------
atracks: np.ndarray
1D array of atracks. lut is defined at each atrack
xtracks: list of np.ndarray
arrays of xtracks. list length is same as xtracks. each array define xtracks where lut is defined
noiseL... | 5,309,011 |
def pp(var):
"""Pretty print.
Wrapper around beeprint
Args:
var: some variable
"""
beeprint.pp(var) | 5,309,012 |
def set_spacing(image, spacing):
"""
Set spacing of ANTsImage
ANTsR function: `antsSetSpacing`
"""
image.set_spacing(spacing) | 5,309,013 |
def compute_scores(results_file, # complete path to results.csv which contains the output of a model run
key, # the key from the results to consider
dest_file, # the filename to save the resulting figure to
zero_division=1.0): # sets the value to return when ... | 5,309,014 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up this integration using UI."""
if hass.data.get(DOMAIN) is None:
hass.data.setdefault(DOMAIN, {})
_LOGGER.info(STARTUP_MESSAGE)
username = entry.data.get(CONF_USERNAME)
password = entry.data.get(CONF_PASSWORD... | 5,309,015 |
def view_shape(shape, view):
"""Return the shape of a view of an array
:param shape: Tuple describing shape of the array
:param view: View object -- a valid index into a numpy array, or None
Returns equivalent of np.zeros(shape)[view].shape
"""
if view is None:
return shape
shp = t... | 5,309,016 |
def get_requester_ip(request):
""" Get the IP address from a request """
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip_addr = x_forwarded_for.split(',')[0]
else:
ip_addr = request.META.get('REMOTE_ADDR')
return ip_addr | 5,309,017 |
def get_image_text(image, whitelist=None):
"""
Uses Tesseract to extract text from a grayscale image
Args:
image: a grayscale image
whitelist: string with the characters that should be detected.
If nothing is passed, every character is whitelisted
Re... | 5,309,018 |
def _get_info_source(context) -> Dict:
"""Returns the current information source"""
return context.transaction_data[TransactionLoops.INFORMATION_SOURCE][-1] | 5,309,019 |
def timestamping_validate(data, schema):
"""
Custom validation function which inserts a timestamp for when the
validation occurred
"""
jsonschema.validate(data, schema)
data['timestamp'] = str(time.time()) | 5,309,020 |
def history_snapshot(
order_book_id: str,
bar_count: int,
dt: datetime.datetime,
fields: List[str]=None,
skip_suspended: bool=True,
include_now: bool=False,
adjust_type: str="none",
adjust_orig:datetime = None,
) -> pd.DataFrame:
"""获取指定合约的历史快照数据
:param order_book_id: 合约代码
... | 5,309,021 |
def determine_header_length(trf_contents: bytes) -> int:
"""Returns the header length of a TRF file
Determined through brute force reverse engineering only. Not based
upon official documentation.
Parameters
----------
trf_contents : bytes
Returns
-------
header_length : int
... | 5,309,022 |
def dThetaXZ(x, z, thetab, case=None):
"""Analytical espression of the angular deviation from Bragg
reflection over a diffractor in conventional point-to-point
focusing geometries
Parameters
==========
x, z : masked array of floats
2D meshgrid where to evaluate dThetaXZ
thetab :... | 5,309,023 |
def _parse_define(define: xml.etree.ElementTree.Element) -> str:
"""Parse <define> manifest stanza.
Schema:
<define name="EXAMPLE" value="1"/>
<define name="OTHER"/>
Args:
define: XML Element for <define>.
Returns:
str with a value NAME=VALUE or NAME.
"""
name ... | 5,309,024 |
def _join_lines(source):
"""Remove Fortran line continuations"""
return re.sub(r'[\t ]*&[\t ]*[\r\n]+[\t ]*&[\t ]*', ' ', source) | 5,309,025 |
def fromjson(datatype, value):
"""A generic converter from json base types to python datatype.
"""
if value is None:
return None
if isinstance(datatype, atypes.ArrayType):
return fromjson_array(datatype, value)
if isinstance(datatype, atypes.DictType):
return fromjson_dict... | 5,309,026 |
def get_logger(
name: str = "",
log_level_console: int = logging.DEBUG,
log_level_file: int = logging.DEBUG,
log_file: str = "application.log",
) -> logging.Logger:
"""
Creates and returns a logger instance as per hoofbite style guides.
Turn off console or file logging by setting the corres... | 5,309,027 |
def format(t):
"""
function to format the stopwatch time to A:BC.D
Returns: the formatted six character string
"""
A = t/600
t = t - A * 600
# this round function isn't needed when t is an integer
CD = round(t/10.0, 1)
B = ""
if CD < 10.0:
B = "0"
r... | 5,309,028 |
def var(array, axis=None, controller=None):
"""Returns the variance of all values along a particular axis (dimension).
Given an array of m tuples and n components:
* Default is to return the variance of all values in an array.
* axis=0: Return the variance values of all components and return a one
... | 5,309,029 |
def test_is_2d_array():
"""
Tests :func:`fatf.utils.array.validation.is_2d_array` function.
"""
# pylint: disable=too-many-branches,too-many-locals,too-many-nested-blocks
# pylint: disable=too-many-statements
type_error = 'The input should be a numpy array-like.'
warning_message = ('2-dimens... | 5,309,030 |
def test_list_view_returns_html(dummy_request):
"""Function to test if list_view returns proper list of dictionaries."""
from learning_journal.views.default import list_view
response = list_view(dummy_request)
assert isinstance(response, dict) | 5,309,031 |
def get_kalliope_bijlage(path, session):
"""
Perform the API-call to get a poststuk-uit bijlage.
:param path: url of the api endpoint that we want to fetch
:param session: a Kalliope session, as returned by open_kalliope_api_session()
:returns: buffer with bijlage
"""
r = session.get(path)
... | 5,309,032 |
def validate_dice_seed(dice, min_length):
"""
Validates dice data (i.e. ensures all digits are between 1 and 6).
returns => <boolean>
dice: <string> representing list of dice rolls (e.g. "5261435236...")
"""
if len(dice) < min_length:
print("Error: You must provide at least {0} dice rol... | 5,309,033 |
def train(net, train_iter, test_iter, num_epochs, lr, device):
"""用GPU训练模型(在第六章定义)。
Defined in :numref:`sec_lenet`"""
def init_weights(m):
if type(m) == nn.Linear or type(m) == nn.Conv2d:
nn.init.xavier_uniform_(m.weight)
net.apply(init_weights)
print('training on', device... | 5,309,034 |
def test_colon_number_command(vim_bot):
"""Go to line."""
main, editor_stack, editor, vim, qtbot = vim_bot
editor.stdkey_backspace()
editor.go_to_line(3)
cmd_line = vim.get_focus_widget()
qtbot.keyClicks(cmd_line, ':1')
qtbot.keyPress(cmd_line, Qt.Key_Return)
line, _ = editor.get_cursor_... | 5,309,035 |
async def new_review(event, gh, *args, **kwargs):
"""Update the stage based on the latest review."""
pull_request = event.data["pull_request"]
review = event.data["review"]
reviewer = util.user_login(review)
state = review["state"].lower()
if state == "commented":
# Don't care about comm... | 5,309,036 |
def make_vocab_from_docs(docs):
"""
Make a dictionary that contains all words from the docs. The order of words is arbitrary.
docs: iterable of documents
"""
vocab_words=set()
for doc in docs:
doc=doc.lower()
doc=re.sub(r'-',' ',doc)
doc=re.sub(r' +',' ',doc) # turn multi... | 5,309,037 |
def filter_by_book_style(bibtexs, book_style):
"""Returns bibtex objects of the selected book type.
Args:
bibtexs (list of core.models.Bibtex): queryset of Bibtex.
book_style (str): book style key (e.g. JOUNRAL)
Returns:
list of Bibtex objectsxs
"""
return [bib for bib in ... | 5,309,038 |
def Main():
"""The main program function.
Returns:
bool: True if successful or False if not.
"""
output_formats = frozenset(['2008', '2010', '2012', '2013', '2015'])
argument_parser = argparse.ArgumentParser(description=(
'Converts source directory (autoconf and automake files) into '
'Visua... | 5,309,039 |
def plot_classifier(X_train, y_train, classifier, scaler, order=1, grid=100, xlabel=r"$x_1$", ylabel=r"$x_2$"):
"""
Affichage des résultats de classification
REMARQUE IMPORTANTE: le code ci-dessous a été écrit à l'arrache et n'est absolument pas un modèle de beau code...
"""
# Create polyn... | 5,309,040 |
def _rmse(a, b, weights, axis):
"""
Root Mean Squared Error.
Parameters
----------
a : ndarray
Input array.
b : ndarray
Input array.
axis : int
The axis to apply the rmse along.
weights : ndarray
Input array.
Returns
-------
res : ndarray
... | 5,309,041 |
def ListParamProcessorCreate(type: object = str):
"""Create a ListParamProcessor
Args:
type (object) : type of each element in list.
Returns:
ListParamProcessor (argparse.Action) : Processor which receives list arguments.
Examples:
>>> import argparse
>>> from veditor.... | 5,309,042 |
def cdf_function_5(cd: ChemicalDiagram):
"""exclusion: all M hydroxide"""
env_dict = cd.get_env_dict()
def neighboring_hydrogen_count(node):
return max(
Counter(env_dict[node]["nb_elements"])["H"],
Counter(env_dict[node]["nb_elements"])["D"],
)
def is_m_hydroxid... | 5,309,043 |
def _add_role_and_annotate(var, role, annotations=()):
"""Add a role and zero or more annotations to a variable."""
add_role(var, role)
for annotation in annotations:
add_annotation(var, annotation) | 5,309,044 |
def load_npy_to_any(path='', name='file.npy'):
"""Load .npy file.
Examples
---------
- see save_any_to_npy()
"""
file_path = os.path.join(path, name)
try:
npy = np.load(file_path).item()
except:
npy = np.load(file_path)
finally:
try:
return npy
... | 5,309,045 |
def _ns_tag(ns_id, tag):
"""Return a namespace/tag item. The ns_id is translated to a full name
space via the NS module variable.
:param ns_id: The name space ID. Translated to a namespace via the module
variable NS
:type ns_id: str
:param tag: The tag
:type str: str
"""
return... | 5,309,046 |
def half_size(A, amount=50, interp='bicubic', mode=None):
""" nearest, bilinear, bicubic, cubic """
return misc.imresize(A, amount, interp, mode) | 5,309,047 |
def load_labels(lamost_ids, filename='lamost_labels_all_dates.csv'):
""" Extracts training labels from file.
Assumes that first row is # then label names, first col is # then
filenames, remaining values are floats and user wants all the labels.
"""
print("Loading reference labels from file %s" %fi... | 5,309,048 |
def _create_alb(
stack, name: str, vpc: ec2.Vpc, target_group: elbv2.ApplicationTargetGroup
) -> elbv2.ApplicationListener:
"""Create Application Load Balancer for integration to the service's API"""
sg = ec2.SecurityGroup(stack, f'{name}-http-public-sg', vpc=vpc)
sg.add_ingress_rule(ec2.Peer.any_ipv4()... | 5,309,049 |
def fix_env(**kwargs):
"""
This method "fixes" os.environ relatively to the given ENV_MAIN_PCK package.
This method ignores current working directory or __main__ module's __file__ atrribute.
For each key in ENV_KEYS, this method prepends full_prefix to os.environ[key].
full_prefix is calculated as a... | 5,309,050 |
def test_malformed(client):
"""Test malformed site creation failure."""
url = reverse('site-list')
response = client.post(url, data='Non-JSON')
assert_error(response, status.HTTP_400_BAD_REQUEST) | 5,309,051 |
def load_mock_response(file_name: str) -> dict:
"""
Load one of the mock responses to be used for assertion.
Args:
file_name (str): Name of the mock response JSON file to return.
"""
with open(f'{file_name}', mode='r', encoding='utf-8') as json_file:
return json.loads(json_file.read(... | 5,309,052 |
def summarize_stats(stats):
"""Summarize a dictionary of variables.
Args:
stats: a dictionary of {name: tensor} to compute stats over.
"""
for name, stat in stats.items():
mean = tf.reduce_mean(stat)
tf.summary.scalar('mean_%s' % name, mean)
tf.summary.scalar('max_%s' % name, tf.reduce_max(stat... | 5,309,053 |
def fixedvals_from_searchspaces(params):
"""Converts any search space hyperparams in params dict into fixed default values."""
if any(isinstance(params[hyperparam], Space) for hyperparam in params):
logger.warning("Attempting to fit model without HPO, but search space is provided. fit() will only consid... | 5,309,054 |
def extract_patch_information(
basename,
input_dir="./",
annotations=[],
threshold=0.5,
patch_size=224,
generate_finetune_segmentation=False,
target_class=0,
intensity_threshold=100.0,
target_threshold=0.0,
adj_mask="",
basic_preprocess=False,
tries=0,
entire_image=Fa... | 5,309,055 |
def attributions(scores: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
"""Error analysis for antecedent scoring
## Inputs
- `scores`: `(batch_size, max_antecedent_number)`-shaped float tensor.
The first dimension might be padded with `-float("-inf")` or
approximations (such as `1e-3... | 5,309,056 |
def test_devices_user_id_missing(flask_app, app, db): # pylint: disable=unused-argument
""" To verify that de_registration device fails
with missing user ids"""
headers = {'Content-Type': 'multipart/form-data'}
request_data = copy.deepcopy(DE_REG_REQ_DATA)
request_data['file'] = 'de-reg-test-f... | 5,309,057 |
def lifecycle_c(sim,sol,single_sol,par,single_par):
""" simulate couple model """
# unpack
d_w = sim.d[:,:,0]
d_h = sim.d[:,:,1]
RA_w = sim.RA[:,0]
RA_h = sim.RA[:,1]
alive_w = sim.alive[:,:,0]
alive_h = sim.alive[:,:,1]
probs_w = sim.probs[:,:,0]
probs_h = sim.probs[:,:,1]
... | 5,309,058 |
def get_recommendation_and_prediction_from_text(input_text, num_feats=10):
"""
플래스크 앱에 출력할 점수와 추천을 구합니다.
:param input_text: 입력 문자열
:param num_feats: 추천으로 제시한 특성 개수
:return: 추천과 현재 점수
"""
global MODEL
feats = get_features_from_input_text(input_text)
pos_score = MODEL.predict_proba([f... | 5,309,059 |
def Ct_a(a, F=None, method='Glauert', ac=None):
"""
High thrust corrections of the form: Ct = Ct(a)
see a_Ct
"""
if F is None:
F=np.ones(a.shape)
if method=='Glauert':
Ct = 4*a*F*(1-a)
if ac is None:
ac = 1/3
Ic = a>ac
Ct[Ic] =4*a[... | 5,309,060 |
def authors_to_string(*authors):
"""
>>> author1 = {'first': 'S.', 'last': 'Miyamoto'}
>>> author2 = {'first': 'K.', 'last': 'Kondo'}
>>> author3 = {'first': 'H.', 'last': 'Tanaka'}
>>> authors_to_string(author1)
'S. Miyamoto'
>>> authors_to_string(author1, author2)
'S. Miyamoto and K. K... | 5,309,061 |
def migration(path):
"""Canadian Interprovincial Migration Data
The `Migration` data frame has 90 rows and 8 columns.
This data frame contains the following columns:
source
Province of origin (source). A factor with levels: `ALTA`,
Alberta; `BC`, British Columbia; `MAN`, Manitoba; `NB`, New
... | 5,309,062 |
def square_quad_f(x, a, matrix):
"""
Compute the square of the quadratic function.
Parameters
----------
x : 1-D array
Point in which the square of the quadratic is to be evaluated.
minimizer : 1-D array
Minimizer of the square of the quadratic function.
ma... | 5,309,063 |
def calc_dist_matrix(chain_one, chain_two) :
"""Returns a matrix of C-alpha distances between two chains"""
''' an example
chain_one = chain
chain_two = chain'''
answer = np.zeros((len(chain_one), len(chain_two)), np.float)
for row, residue_one in enumerate(chain_one) :
for col, residue... | 5,309,064 |
def Upload(results, flakiness_dashboard_server, test_type):
"""Reports test results to the flakiness dashboard for Chrome for Android.
Args:
results: test results.
flakiness_dashboard_server: the server to upload the results to.
test_type: the type of the tests (as displayed by the flakiness dashboard)... | 5,309,065 |
def compare_sequence(old, new):
"""Compare two Seq or DBSeq objects."""
assert len(old) == len(new), "%i vs %i" % (len(old), len(new))
assert str(old) == str(new), "%s vs %s" % (old, new)
if isinstance(old, UnknownSeq):
assert isinstance(new, UnknownSeq)
else:
assert not isinstance(... | 5,309,066 |
def split_numbers(number):
"""
Split high precision number(s) into doubles.
TODO: Consider the option of using a third number to specify shift.
Parameters
----------
number: long double
The input high precision number which is to be split
Returns
-------
number_I: double
... | 5,309,067 |
def _get_slope(x, y):
"""
Retrun the slope of x and y data, using scipy.signal.linregress
"""
slope = linregress(x, y)
return slope | 5,309,068 |
def get_spans(tokens, tags):
"""Convert tags to textspans."""
spans = tags_to_spans(tags)
text_spans = [
x[0] + ": " + " ".join([tokens[i]
for i in range(x[1][0], x[1][1] + 1)])
for x in spans
]
if not text_spans:
text_spans = ["None"]
return text_spans | 5,309,069 |
def applyPCA(data_points,pcaComponents):
"""Apply PCA to a list of values
Parameters
----------
data_points : numpy.ndarray
Array of type numpy.ndarray.
pcaComponents : int
Number of components to be used in PCA analysis.
Returns
Array of t... | 5,309,070 |
def delete_account(Id, token: str):
"""Deletes the account resource."""
headers = Header(token)
URL = "https://api.mail.tm/accounts/"+Id
response = requests.delete(url=URL, headers=headers.header)
if response.status_code == 204:
return response.status_code
elif response.status_c... | 5,309,071 |
def modify_existing_stack(client, config, codebuild):
"""Modify and exist Codebuild project's CloudFormation stack"""
stack_name = config.get("Global", "stack_name")
# ChangeSetNames are required to start with an Alphabetic character, and to be unique.
# Prefixing the hashed timed with an 'A' gets it d... | 5,309,072 |
def load_quran_obj_from_json(input_json_path):
"""
Loads the Json object containing Qur'anic data from the specific path.
"""
try:
with open(input_json_path, 'rb') as quran_json_file:
# Import json file and return Qur'an object.
return json.load(quran_json_file)[QURAN_KE... | 5,309,073 |
def get_company_info(secret1, secret2, symbol):
"""
scrapes data (currently from alphavantage) and returns the response in json format
Arguments:
secret1: one of the API keys to scrape data
secret2: a second API key to scrape data
symbol: synonymous to ticker
Returns:
... | 5,309,074 |
def cyclic_digraph(n: int = 3, metadata: bool = False) -> Union[sparse.csr_matrix, Bunch]:
"""Cyclic graph (directed).
Parameters
----------
n : int
Number of nodes.
metadata : bool
If ``True``, return a `Bunch` object with metadata.
Returns
-------
adjacency or graph :... | 5,309,075 |
def is_wildcard_query(query):
"""
Checks if provided query selects using a * wildcard
:type query str
:rtype bool
"""
if not is_select_query(query):
return False
query = preprocess_query(query)
tokens = get_query_tokens(query)
last_token = None
for token in tokens:
... | 5,309,076 |
def random_val(index, tune_params):
"""return a random value for a parameter"""
key = list(tune_params.keys())[index]
return random.choice(tune_params[key]) | 5,309,077 |
def adaptor():
"""
A running VimAdaptor instance that uses a loopback broker connection
"""
adaptor = VimAdaptor(use_loopback_connection=True, fake_registration=True)
yield adaptor
adaptor.conn.close() | 5,309,078 |
def scan(container, output_queue, audit=False, audit_queue=None):
"""Docker user-info scan plugin.
:param container: container instance.
:type container: docker.models.containers.Container
:param output_queue: Output holder for this plugin.
:type output_queue: multiprocessing.managers.AutoProxy[Qu... | 5,309,079 |
def read_envvar_file(name, extension):
"""
Read values from a file provided as a environment variable
``NAME_CONFIG_FILE``.
:param name: environment variable prefix to look for (without the
``_CONFIG_FILE``)
:param extension: *(unused)*
:return: a `.Configuration`, possibly `.NotConfigu... | 5,309,080 |
def take_while(array, callback=None):
"""Creates a slice of `array` with elements taken from the beginning.
Elements are taken until the `callback` returns falsey. The
`callback` is invoked with three arguments: ``(value, index, array)``.
Args:
array (list): List to process.
callback (m... | 5,309,081 |
def build_model():
"""
Using grid search, builds the model to classify the messages
Returns:
model (): The trained model over the data
"""
# text pipeline
text_pipeline = Pipeline([
('vect', CountVectorizer(tokenizer=tokenize)),
... | 5,309,082 |
def extract_cutted_data_and_timesteps_from_given_indexes(dataframe_indexes, dict_instances, result_data_shape, result_timesteps_shape):
"""This function extracts data and labels in window format via corresponding indexes located in dataframe_indexes
Cut format is needed for train recurrent models. The techni... | 5,309,083 |
def test_remove_root_option(httpcs_svc_instance, pub, source):
"""Test: Remove option from rootInstance in Httpcs Service Instance object
Steps:
1. Remove option from rootInstance in HttpCsSvcInstance object
2. Compare expected result with actual
Result:
OK: httpcssvcinst object is updated as ... | 5,309,084 |
def main(
target_ip: str = typer.Option(..., callback=validate_ipaddr),
target_port: int = typer.Option(68),
source_ip: str = typer.Option(
DEFAULT_SOURCE_IP,
callback=validate_ipaddr,
help="IP for target to respond to and attempt to bind locally",
),
source_port: int = typer... | 5,309,085 |
def run(magic, command, args, options):
"""
Launch Rider. Open it in the code folder.
"""
platform = detect_platform()
if platform in ['osx', 'linux']:
cmd = "rider"
elif platform == 'win':
cmd = "rider.exe"
code = magic.get_uri('code')
if code is None:
return ... | 5,309,086 |
def rerun():
"""
Rerun (part of) a map from scratch.
The selected components must be completed or errored.
See the subcommands of this command group for different ways to specify
which components to rerun.
Any existing output of rerun components is removed; they are re-submitted
to the HTC... | 5,309,087 |
def git_version_specifier(refspec, branch, commit, tag):
"""
Return the minimal set of specifiers that the user
input reduces to, in a dict of variables for Ansible.
:param refspec: provided refspec like 'pull/1/head'
:param branch: provided branch like 'master'
:param commit: provided commit S... | 5,309,088 |
def receive_bytes(socket: socket.socket, buffer_size: int) -> str:
"""
Receives the specified number of bytes
from the specified socket
@param socket - the socket from which to receive
@param buffer_size - the number of bytes to receive
@return - string
"""
receiver_buffer: bytes = b''
... | 5,309,089 |
def roulette_selection(population, pop_fitness, select_n, config):
"""
Metoda selekcji ruletki
Minimalizujemy wartośc funkcji dopasowania, co jest podejściem odwrotnym do standardowego. By moc poprawnie
zastosowac algorytm selekcji ruletki wykorzystujemy odwrocone wartosci funkcji.
W celu rozproszen... | 5,309,090 |
def create_additional_front_points(pt6x, pt7x, pt14x, pt9z, pt15x, pt8z, pt14z, pt9x, pt8x, pt15z):
"""Create pot surface points to create faces--Nameing them 21(L)-22(R) to not collide with current fuel vert numbers"""
# Left point
pt20x = pt6x
pt20z = pt14z
pt20y = 0
# Right point
p... | 5,309,091 |
def console():
""" Defines the behavior of the console web2py execution """
import optparse
import textwrap
usage = "python web2py.py"
description = """\
web2py Web Framework startup script.
ATTENTION: unless a password is specified (-a 'passwd') web2py will
attempt to run a GUI. In th... | 5,309,092 |
def concatenate_digits(a, b):
"""
Concatenate the digits of a and b
e.g. a=42, b=666 returns 42666
"""
return a * (10 ** num_digits(b)) + b | 5,309,093 |
def base64_decode_openflow(data):
"""Decode openflow message from base64 string to msg object"""
(msg, packet_length) = OFConnection.parse_of_packet(base64_decode(data))
return msg | 5,309,094 |
def cfmakeecho(mode, echo=True):
"""Set/unset ECHO."""
if echo:
mode[LFLAG] |= ECHO
else:
mode[LFLAG] &= ~ECHO | 5,309,095 |
def coupledHarmonicOscillator( N=10000,
T=1,
ICs={ 'y1_0': 0,
'x1_0': 0.9,
'y2_0': 0,
'x2_0': -1},
args={ 'k': 1,
'kappa': 1,
'm': 1e-4},
plot=False):
"""
Solve a coupled harmonic oscillator problem. See reference for details.
Exampl... | 5,309,096 |
def test_get_template_text_open_file_returns_string():
"""Test that return value returned is a string."""
filename = 'template.txt'
assert type(get_template_text(filename)) == str | 5,309,097 |
def impvol_table(data):
"""Implied volatility for structured data.
Parameters
----------
data : pandas DataFrame, record array, or dictionary of arrays
Mandatory labels: moneyness, maturity, premium, call
Returns
-------
array
Implied volatilities
Notes
... | 5,309,098 |
def deserialize(payload: str) -> Model:
"""
:raises: ParsingError
"""
try:
raw_data = json.loads(payload)
except json.decoder.JSONDecodeError:
raise ParsingError
return Model.from_dict(raw_data) | 5,309,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.