content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_set_item():
"""Tests element written to lin objects. This includes tests for negative
indexing and expected exceptions.
"""
m = lin.Matrix2x3()
def set_and_check(x, *args):
if len(args) == 1:
args = args[0]
assert m[args] != x
m[args] = x
assert ... | 9,700 |
def populate_api_servers():
""" Find running API servers. """
def api_server_info(entry):
prefix, port = entry.rsplit('-', 1)
project_id = prefix[len(API_SERVER_PREFIX):]
return project_id, int(port)
global api_servers
monit_entries = yield monit_operator.get_entries()
server_entries = [api_serve... | 9,701 |
def draw_result(points, colors=None):
""" Draw point clouds
Args:
points ([ndarray]): N x 3 array
colors ([ndarray]): N x 3 array
"""
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(points)
if colors is not None:
pcd.colors = o3d.utility.Vector3dV... | 9,702 |
def gen_classification_func(model, *, state_file=None, transform=None, pred_func=None,
device=None):
""" 工厂函数,生成一个分类器函数
用这个函数做过渡的一个重要目的,也是避免重复加载模型
:param model: 模型结构
:param state_file: 存储参数的文件
:param transform: 每一个输入样本的预处理函数
:param pred_func: model 结果的参数的后处理
:re... | 9,703 |
def create_recipe_json(image_paths: list) -> dict:
"""
Orchestrate the various services to respond to a create recipe request.
"""
logger.info('Creating recipe json from image paths: {}'.format(image_paths))
full_text = load_images_return_text(image_paths)
recipe_json = assign_text_to_recip... | 9,704 |
def rstrip_extra(fname):
"""Strip extraneous, non-discriminative filename info from the end of a file.
"""
to_strip = ("_R", "_", "fastq", ".", "-")
while fname.endswith(to_strip):
for x in to_strip:
if fname.endswith(x):
fname = fname[:len(fname) - len(x)]
... | 9,705 |
def test_xor2():
"""
Two inputs, two outputs.
"""
net = Network("XOR2")
net.add(Layer("input1", shape=1))
net.add(Layer("input2", shape=1))
net.add(Layer("hidden1", shape=2, activation="sigmoid"))
net.add(Layer("hidden2", shape=2, activation="sigmoid"))
net.add(Layer("shared-hidden",... | 9,706 |
def test_remove_same_word_function(session, query, expected):
"""
Test when input is word with space, the result will not show the same word
"""
response = get_complete(session, {'q': query, 'contextual': False})
compare_two_lists(get_typeahead_values(response), expected) | 9,707 |
def run(preprocessors, data, preprocessing=defaultdict(lambda: None), fit=True):
"""Applies preprocessing to data. It currently suppoerts StandardScaler and
OneHotEncoding
Parameters
----------
preprocessors : list
preprocessors to be applied
data : pd.DataFrame
data to be prepr... | 9,708 |
async def test_setting_attribute_with_template(hass, mqtt_mock):
"""Test the setting of attribute via MQTT with JSON payload."""
await help_test_setting_attribute_with_template(
hass, mqtt_mock, fan.DOMAIN, DEFAULT_CONFIG
) | 9,709 |
def vouchers_tab(request, voucher_group, deleted=False, template_name="manage/voucher/vouchers.html"):
"""Displays the vouchers tab
"""
vouchers = voucher_group.vouchers.all()
paginator = Paginator(vouchers, 20)
page = paginator.page((request.POST if request.method == 'POST' else request.GET).get("p... | 9,710 |
def all_ground_operators_given_partial(
operator: STRIPSOperator, objects: Collection[Object],
sub: VarToObjSub) -> Iterator[_GroundSTRIPSOperator]:
"""Get all possible groundings of the given operator with the given objects
such that the parameters are consistent with the given substitution."""... | 9,711 |
def normalise_intensity(x,
mode="minmax",
min_in=0.0,
max_in=255.0,
min_out=0.0,
max_out=1.0,
clip=False,
clip_range_percentile=(0.05, 99.95),
... | 9,712 |
def spots_rmsd(spots):
""" Calculate the rmsd for a series of small_cell_spot objects
@param list of small_cell_spot objects
@param RMSD (pixels) of each spot
"""
rmsd = 0
count = 0
print 'Spots with no preds', [spot.pred is None for spot in spots].count(True), 'of', len(spots)
for spot in spots:
if... | 9,713 |
def test_point_at_center_bottom(points, point_at_line):
"""
Test aligned at the line text position calculation, horizontal mode
"""
x, y = text_point_at_line(points, (10, 5), TextAlign.CENTER)
assert x == pytest.approx(point_at_line[0])
assert y == pytest.approx(point_at_line[1]) | 9,714 |
def sanitize_df(data_df, schema, setup_index=True, missing_column_procedure='fill_zero'):
""" Sanitize dataframe according to provided schema
Returns
-------
data_df : pandas DataFrame
Will have fields provided by schema
Will have field types (categorical, datetime, etc) provided by sch... | 9,715 |
def log(message):
"""
Write log message to stdout and to predefined file
"""
time = "[" + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + "] "
outmsg = time + message
print(outmsg)
with open(LOCAL_STORAGE_DIR + "/" + LOG_FILE_NAME, "a") as myfile:
myfile.write(outmsg... | 9,716 |
def get_id_argument(id_card):
"""
获取身份证号码信息
:param id_card:
:return:
"""
id_card = id_card.upper()
id_length = len(id_card)
if id_length == 18:
code = {
'body': id_card[0:17],
'address_code': id_card[0:6],
'birthday_code': id_card[6:14],
... | 9,717 |
def rhypergeometric(n, m, N, size=None):
"""
Returns hypergeometric random variates.
"""
if n == 0:
return np.zeros(size, dtype=int)
elif n == N:
out = np.empty(size, dtype=int)
out.fill(m)
return out
return np.random.hypergeometric(n, N - n, m, size) | 9,718 |
def ctd_upload(Id, filenames, production):
""" Edit entry at Caltech Data for data set to upload data given by filenames.
Id is an integer that defines the Caltech Data entry.
"""
caltechdata.edit_ctd(Id, filenames=filenames, production=production) | 9,719 |
def _validate_query(
hgnc_manager: HgncManager,
query_result,
original_identifier: str,
original_namespace: str,
) -> Tuple[str, str, str]:
"""Process and validate HGNC query.
:param hgnc_manager: hgnc manager
:param query_result:
:param original_identifier:
:param original_namespac... | 9,720 |
def AdjustforPeriod(numsnaps,numhalos,boxsize,hval,atime,halodata,icomove=0):
"""
Map halo positions from 0 to box size
"""
for i in range(numsnaps):
if (icomove):
boxval=boxsize/hval
else:
boxval=boxsize*atime[i]/hval
wdata=np.where(halodata[i]["Xc"]<0)
halodata[i]["Xc"][wdata]+=boxval
wdata=np.whe... | 9,721 |
def my_model_builder(my_model: MyModel) -> KerasModel:
"""Build the siamese network model """
input_1 = layers.Input(my_model.input_shape)
input_2 = layers.Input(my_model.input_shape)
# As mentioned above, Siamese Network share weights between
# tower networks (sister networks). To allow this, we w... | 9,722 |
def test_upper_bounds_ensured():
"""
Long enough simulation should saturate a bounded variable
"""
example_step = SimulationStep(
x0=0,
inputs=(15000,1),
duration=100
)
_, samples = bounded_angular_velocity(example_step)
assert not any(s > bounded_angular_velocity.max... | 9,723 |
def test_copy_contents():
"""test copy contents if dst is already existed."""
# create addon src
addon_path = path.join(root_path, 'tests', 'src', 'addon')
addon_main = path.join(root_path, 'tests', 'src', 'addon', 'addon_main')
addon_sub = path.join(root_path, 'tests', 'src', 'addon', 'addon_sub')
... | 9,724 |
def save_csv(log, additions, field_cfg, date_format):
"""Add any unique entries from new to current"""
qtys = collections.Counter()
pool = {}
log_rows = []
log_hashes = set()
for row in csv.DictReader(log):
log_rows.append(row)
hash_ = hash_row(row)
assert hash_ not in lo... | 9,725 |
def create_embed(
title,
description,
fields = None,
colour = None,
timestamp = datetime.utcnow(),
author = None,
author_icon = None,
thumbnail = None,
image = None,
footer = None
):
"""Create an Embed
Args:
title (str): Set title
description (str): Set d... | 9,726 |
def autoCalibration(I):
"""Returns horizontal and vertical factors by which every distance in
pixels should be multiplied in order to obtain the equivalent distance in
millimeters. This program assumes that the scale presents clear axis ticks and
that the distance between two biggest ticks is equal to 1... | 9,727 |
def reverse_handler(handler_input):
"""Check if a verb is provided in slot values. If provided, then
looks for the paradigm in the irregular_verbs file.
If not, then it asks user to provide the verb again.
"""
# iterate over the dictionaries in irregular_verbs.py and looks for
# the verb in the... | 9,728 |
def generate_dummy_makefile(target_dir):
"""Create a dummy makefile to demonstrate how it works.
Use dummy values unrelated to any gyp files. Its output should remain the
same unless/until makefile_writer.write_android_mk changes.
Args:
target_dir: directory in which to write the resulting Android.mk
... | 9,729 |
def commit_user_deletions():
"""Delete (marked) users."""
AccountTerminationQueue.objects.commit_terminations() | 9,730 |
def load_wrf_data(filename):
"""Load required data form the WRF output file : filename"""
base_data=load_vars(filename,wrfvars)
skin_t=load_tskin(filename,tsvar,landmask)
base_data.append(skin_t)
atts=mygis.read_atts(filename,global_atts=True)
return Bunch(data=base_data,global_atts=at... | 9,731 |
def DensityRatio_QP(X_den, X_num, kernel, g, v_matrix, ridge=1e-3):
"""
The function computes a model of the density ratio.
The function is in the form $A^T K$
The function returns the coefficients $\alpha_i$ and the bias term b
"""
l_den, d = X_den.shape
l_num, d_num = X_num.shape
# TO... | 9,732 |
def sanitize_date(date_dict: dict):
"""
Function to take the date values entered by the user and check their validity. If valid it returns True,
otherwise it sets the values to None and returns False
:param date_dict:
:return:
"""
month = date_dict["month"]
day = date_dict["day"]
ye... | 9,733 |
def create_scale(tonic, pattern, octave=1):
"""
Create an octave-repeating scale from a tonic note
and a pattern of intervals
Args:
tonic: root note (midi note number)
pattern: pattern of intervals (list of numbers representing
intervals in semito... | 9,734 |
def _qfloat_append(qf, values, axis=None):
"""Implement np.append for qfloats."""
# First, convert to the same unit.
qf1, qf2 = same_unit(qf, values, func=np.append)
nominal = np.append(qf1.nominal, qf2.nominal, axis)
std = np.append(qf1.uncertainty, qf2.uncertainty, axis)
return QFloat(nominal,... | 9,735 |
def power_off_progressive(part, restart=False, ibmi_immed=False,
timeout=CONF.pypowervm_job_request_timeout):
"""Attempt soft power-off, retrying with increasing aggression on failure.
IBMi partitions always start with OS shutdown. If ibmi_immed == False,
os-normal shutdown is tr... | 9,736 |
async def test_strip(hass: HomeAssistant) -> None:
"""Test a smart strip."""
already_migrated_config_entry = MockConfigEntry(
domain=DOMAIN, data={}, unique_id=MAC_ADDRESS
)
already_migrated_config_entry.add_to_hass(hass)
plug = _mocked_strip()
with _patch_discovery(device=plug), _patch_... | 9,737 |
def pre_spawn_hook_environ(monkeypatch, jupyterhub_api_environ):
"""
Set the environment variables used in the setup_course_hook function
"""
monkeypatch.setenv('NB_GID', '100')
monkeypatch.setenv('NB_NON_GRADER_UID', '1000') | 9,738 |
def filter_by_mean_color(img:np.ndarray, circles:List[Circle], threshold=170) -> List[Circle]:
"""Filter circles to keep only those who covers an area which high pixel mean than threshold"""
filtered = []
for circle in circles:
box = Box(circle=circle)
area = box.get_region(img)
if n... | 9,739 |
def test_deletion_no_child(basic_tree):
"""Test the deletion of a red black tree."""
tree = red_black_tree.RBTree()
test_tree = [(23, "23"), (4, "4"), (30, "30"), (11, "11")]
for key, data in test_tree:
tree.insert(key=key, data=data)
tree.delete(4)
assert [item for item in tree.inord... | 9,740 |
def ParseSortByArg(sort_by=None):
"""Parses and creates the sort by object from parsed arguments.
Args:
sort_by: list of strings, passed in from the --sort-by flag.
Returns:
A parsed sort by string ending in asc or desc.
"""
if not sort_by:
return None
fields = []
for field in sort_by:
... | 9,741 |
def dense_to_text(decoded, originals):
"""
Convert a dense, integer encoded `tf.Tensor` into a readable string.
Create a summary comparing the decoded plaintext with a given original string.
Args:
decoded (np.ndarray):
Integer array, containing the decoded sequences.
... | 9,742 |
def admin_view_all_working_curriculums(request):
""" views all the working curriculums offered by the institute """
user_details = ExtraInfo.objects.get(user = request.user)
des = HoldsDesignation.objects.all().filter(user = request.user).first()
if str(des.designation) == "student" or str(des.designat... | 9,743 |
async def test_learn(hass):
"""Test learn service."""
mock_device = MagicMock()
mock_device.enter_learning.return_value = None
mock_device.check_data.return_value = b64decode(DUMMY_IR_PACKET)
with patch.object(
hass.components.persistent_notification, "async_create"
) as mock_create:
... | 9,744 |
def getEmuAtVa(vw, va, maxhit=None):
"""
Build and run an emulator to the given virtual address
from the function entry point.
(most useful for state analysis. kinda heavy though...)
"""
fva = vw.getFunction(va)
if fva == None:
return None
cbva,cbsize,cbfva = vw.getCodeBlock(v... | 9,745 |
def _create_test_validity_conditional(metric):
"""Creates BigQuery SQL clauses to specify validity rules for an NDT test.
Args:
metric: (string) The metric for which to add the conditional.
Returns:
(string) A set of SQL clauses that specify conditions an NDT test must
meet to be c... | 9,746 |
def tfds_train_test_split(
tfds: tf.data.Dataset,
test_frac: float,
dataset_size: Union[int, str],
buffer_size: int = 256,
seed: int = 123,
) -> Sequence[Union[tf.data.Dataset, tf.data.Dataset, int, int]]:
"""
!!! does not properly work, seems to be dependant on hardware, open isssue on
... | 9,747 |
def seconds_to_hms(seconds):
"""
Convert seconds to H:M:S format.
Works for periods over 24H also.
"""
return datetime.timedelta(seconds=seconds) | 9,748 |
def parse_args(args):
"""
Takes in the command-line arguments list (args), and returns a nice argparse
result with fields for all the options.
Borrows heavily from the argparse documentation examples:
<http://docs.python.org/library/argparse.html>
"""
# The command line arguments start ... | 9,749 |
def train(config):
"""Trains the model based on configuration settings
Args:
config: configurations for training the model
"""
tf.reset_default_graph()
data = DataReader(config.directory, config.image_dims, config.batch_size,
config.num_epochs, config.use_weights)
train_data = da... | 9,750 |
def test_sentry_middleware(db, clients, mocker, settings):
"""
Check that users are added to the Sentry context when the middleware
is active.
"""
settings.MIDDLEWARE.append("creator.middleware.SentryMiddleware")
client = clients.get("Administrators")
mock = mocker.patch("sentry_sdk.set_us... | 9,751 |
def _add_spot_2d(image, ground_truth, voxel_size_yx, precomputed_gaussian):
"""Add a 2-d gaussian spot in an image.
Parameters
----------
image : np.ndarray, np.uint
A 2-d image with shape (y, x).
ground_truth : np.ndarray
Ground truth array with shape (nb_spots, 4).
- coord... | 9,752 |
def bing(text, bot):
"""<query> - returns the first bing search result for <query>"""
api_key = bot.config.get("api_keys", {}).get("bing_azure")
# handle NSFW
show_nsfw = text.endswith(" nsfw")
# remove "nsfw" from the input string after checking for it
if show_nsfw:
text = text[:-5].st... | 9,753 |
def single_length_RB(
RB_number: int, RB_length: int, target: int = 0
) -> List[List[str]]:
"""Given a length and number of repetitions it compiles Randomized Benchmarking
sequences.
Parameters
----------
RB_number : int
The number of sequences to construct.
RB_length : int
... | 9,754 |
def decode(text_file_abs_path, threshold=10):
"""
Decodes a text into a ciphertext.
Parameters
---------
text_file_abs_path: str
Returns
-------
ciphertext: str
"""
try:
with open(text_file_abs_path, "rb") as f:
text = f.read()
except Exc... | 9,755 |
def pixelizenxncircregion(bmp: array,
x: int, y: int, r: int, n: int):
"""Pixelize a circular region in a
bitmap file by n
Args:
bmp : unsigned byte array
with bmp format
x, y, r: center (x, y)
and radius r
n : integer ... | 9,756 |
def templatetag(parser, token):
"""
Outputs one of the bits used to compose template tags.
Since the template system has no concept of "escaping", to display one of
the bits used in template tags, you must use the ``{% templatetag %}`` tag.
The argument tells which template bit to output:
... | 9,757 |
def create_test_folder(df_test, target_path):
"""Create test set in the target folder
Parameters:
df_test -- dataframe that contains all the test set details
('patient_id', 'filename', 'class', 'data_source')
target_path -- path to the new dataset folder
"""
fo... | 9,758 |
def reflected_phase_curve(phases, omega, g, a_rp):
"""
Reflected light phase curve for a homogeneous sphere by
Heng, Morris & Kitzmann (2021).
Parameters
----------
phases : `~np.ndarray`
Orbital phases of each observation defined on (0, 1)
omega : tensor-like
Single-scatter... | 9,759 |
def train_single_span(config: TrainConfig) -> None:
"""Train a single span edge probing model.
Trains the model until either a maximum number of evaluations or a maximum number
of evaluations without improvement is reached. Furthermore the learning rate can be halved
if the model does not improve for a... | 9,760 |
def costspec(
currencies: list[str] = ["USD"],
) -> s.SearchStrategy[pos.CostSpec]:
"""Generates a random CostSpec.
Args:
currencies: An optional list of currencies to select from.
Returns:
A new search strategy.
"""
return s.builds(pos.CostSpec, currency=common.currency(curren... | 9,761 |
def send_approved_mail(request, user):
"""
Sends an email to a user once their ``is_active`` status goes from
``False`` to ``True`` when the ``ACCOUNTS_APPROVAL_REQUIRED``
setting is ``True``.
"""
context = {"request": request, "user": user}
subject = subject_template("email/account_approved... | 9,762 |
def test_init_3(rate_sim_3):
"""Test initialization with true rank arguments."""
desired_n_sequence = 4
desired_max_timestep = 2
desired_stimulus_set = np.array(
[
[
[3, 1],
[3, 1]
],
[
[9, 12],
[... | 9,763 |
def get_gene_names_conversion():
"""Get the compressed file containing two-way mappings of gene_id to gene_symbol"""
with gzip.open(
os.path.join(
current_app.config["FIVEX_DATA_DIR"], "gene.id.symbol.map.json.gz",
),
"rt",
) as f:
return json.loads(f.read()) | 9,764 |
def _process_input(data, context):
""" Pre-process request input before it is sent to TensorFlow Serving REST API
Args:
data (obj): the request data stream
context (Context): an object containing request and configuration details
Returns:
(dict): a JSON-serializable dict that conta... | 9,765 |
def similarity_matrix_2d(X, Y, metric='cos'):
"""
Calculate similarity matrix
Parameters:
X: ndarray
input matrix 1
Y: ndarray
input matrix 2
distFunc: function
distance function
Returns:
result: ndarray
similarity matrix
"""
n_X ... | 9,766 |
def issue_list_with_tag(request, tag=None, sortorder=None):
"""
For a tag. display list of issues
"""
if tag:
stag = "\"%s\"" % tag
issues = Issue.tagged.with_any(stag)
tag_cloud = []
if issues:
tag_cloud = get_tagcloud_issues(issues)
issues = iss... | 9,767 |
def update_deal(id, deal_dict):
"""
Runs local validation on the given dict and gives passing ones to the API to update
"""
if utils.validate_deal_dict(utils.UPDATE, deal_dict, skip_id=True):
resp = utils.request(utils.UPDATE, 'deals', {'id': id}, data=deal_dict)
return utils.parse(resp)... | 9,768 |
def plot_tilt_hist(series, ntile: str, group_name: str, extra_space: bool = True):
"""
Plots the histogram group tilts for a single ntile
:param series: frame containing the avg tilts, columns: group, index: pd.Period
:param ntile: the Ntile we are plotting for
:param group_name: the name of the gro... | 9,769 |
def test_oef_serialization_description():
"""Testing the serialization of the OEF."""
foo_datamodel = DataModel("foo", [Attribute("bar", int, True, "A bar attribute.")])
desc = Description({"bar": 1}, data_model=foo_datamodel)
msg = OefSearchMessage(
performative=OefSearchMessage.Performative.RE... | 9,770 |
def get_constraints_for_x(cell, board):
"""
Get the constraints for a given cell cell
@param cell Class instance of Variable; a cell of the Sudoku board
@param board
@return Number of constraints
"""
nconstraints = 0
# Row
for cellj in board[cell.row][:cell.col]:
if cellj.... | 9,771 |
def average(values):
"""Computes the arithmetic mean of a list of numbers.
>>> print average([20, 30, 70])
40.0
"""
try:
return stats.mean(values)
except ZeroDivisionError:
return None | 9,772 |
def get_subgraph_pos(G, pos):
""" Returns the filtered positions for subgraph G. If subgraph = original graph then pos will be returned.
Parameters
----------
G : nx.Graph
A graph object.
Pos : dict
A dictionary with nodes as keys and positions as values.
Example
-------... | 9,773 |
def _calculateWindowPosition(screenGeometry, iconGeometry, windowWidth, windowHeight):
"""
Calculate window position near-by the system tray using geometry of a system tray
and window geometry
@param screenGeometry: geometry of the screen where system tray is located
@type screenGeometry: QRect
... | 9,774 |
def build_from_config(config: dict, name: str) -> HomingMotor:
"""Build the named HomingMotor from data found in config"""
def check_for_key(key, cfg):
if key not in cfg:
raise RuntimeError('Key "{}" for HomingMotor "{}" not found.'.format(key, name))
else:
return cfg[ke... | 9,775 |
def arg_return_greetings(name):
"""
This is greeting function with arguments and return greeting message
:param name:
:return:
"""
message = F"hello {name}"
return message | 9,776 |
def basic_usage(card_id: str, parent: Any = None):
"""Basic usage of the application, minus the card recognition bits"""
data = pull_card_data(card_id)
qt_window = Card(parent, data)
qt_window.setWindowTitle("YGO Scanner")
qt_window.show()
return qt_window | 9,777 |
async def test_bad_requests(request_path, request_params, aiohttp_client):
"""Test request paths that should be filtered."""
app = web.Application()
app.router.add_get("/{all:.*}", mock_handler)
setup_security_filter(app)
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client... | 9,778 |
def get_abi(
contract_sources: Dict[str, str],
allow_paths: Optional[str] = None,
remappings: Optional[list] = None,
silent: bool = True,
) -> Dict:
"""
Generate ABIs from contract interfaces.
Arguments
---------
contract_sources : dict
a dictionary in the form of {'path': "... | 9,779 |
def init_layer_linear_quant_params(quantizer, original_model, layer_name, init_mode=ClipMode.NONE,
init_method='Powell', eval_fn=None, search_clipping=False):
"""
Initializes a layer's linear quant parameters.
This is done to set the scipy.optimize.minimize initial guess.
... | 9,780 |
def predict(w , b , X ):
"""
使用学习逻辑回归参数logistic (w,b)预测标签是0还是1,
参数:
w - 权重,大小不等的数组(num_px * num_px * 3,1)
b - 偏差,一个标量
X - 维度为(num_px * num_px * 3,训练数据的数量)的数据
返回:
Y_prediction - 包含X中所有图片的所有预测【0 | 1】的一个numpy数组(向量)
"""
m = X.shape[1] #图片的数量
Y_prediction ... | 9,781 |
def delta_C(parcels_old, parcels_new, normed=False):
"""
Compute the number of vertices that change connected component from
old parcellation to new parcellation.
Parameters:
- - - - -
parcels_old : dictionary
old connected component sample assignments
parcels_new : dictionary
... | 9,782 |
def increment(number):
"""Increases a given number by 1"""
return number + 1 | 9,783 |
def get_recent_added_companies(parser, token):
"""
Gets any number of the recent added comapnies.
Syntax::
{% get_recent_added_companies [limit] as [var_name] %}
"""
return base_tag(parser, token, RecentCreatedCompanies) | 9,784 |
def search_data(templates, pols, matched_pols=False, reverse_nesting=False, flatten=False):
"""
Glob-parse data templates to search for data files.
Parameters
----------
templates : str or list
A glob-parsable search string, or list of such strings, with a {pol}
spot for string form... | 9,785 |
def normalize_word(word):
"""
:type word: str
:rtype: str
"""
acronym_pattern = r'^(?:[A-Z]\.)+$'
if re.match(pattern=acronym_pattern, string=word):
word = word.replace('.', '')
if word.lower() in _REPLACE_WORDS:
replacement = _REPLACE_WORDS[word.lower()]
if word.islower():
return replacement.lower()
... | 9,786 |
def _ggm_qsize_prob_gt_0_whitt_5_2(arr_rate, svc_rate, c, ca2, cs2):
"""
Return the approximate P(Q>0) in G/G/m queue using Whitt's simple
approximation involving rho and P(W>0).
This approximation is exact for M/M/m and has strong theoretical
support for GI/M/m. It's described by Whitt as "crude" ... | 9,787 |
def pds3_label_gen_date(file):
"""Returns the creation date of a given PDS3 label.
:param path: File path
:type path: str
:return: Creation date
:rtype: str
"""
generation_date = "N/A"
with open(file, "r") as f:
for line in f:
if "PRODUCT_CREATION_TIME" in line:
... | 9,788 |
def harmony(*args):
"""
Takes an arbitrary number of floats and prints their harmonic
medium value. Calculation is done with formula:
number_of_args \ (1 \ item1 + 1 \ item2 + ...)
Args:
*args (tuple): number of arguments with a type: float, integer
Returns:
float: harmonic... | 9,789 |
def node_gdf_from_graph(G, crs = 'epsg:4326', attr_list = None, geometry_tag = 'geometry', xCol='x', yCol='y'):
"""
Function for generating GeoDataFrame from Graph
:param G: a graph object G
:param crs: projection of format {'init' :'epsg:4326'}. Defaults to WGS84. note: here we are defining the crs of... | 9,790 |
def views():
""" Used for the creation of Orientation objects with
`Orientations.from_view_up`
"""
return [[1, 0, 0], [2, 0, 0], [-1, 0, 0]] | 9,791 |
def savePlot(widget, default_file_type, old_file_path=None):
"""Saves a plot in the specified file format.
:param widget: graphics widget.
:param default_file_type: default save file type.
:param old_file_path: file path from a previous save operation.
:return: returns file path,
retur... | 9,792 |
def check_closed(f):
"""Decorator that checks if connection/cursor is closed."""
def g(self, *args, **kwargs):
if self.closed:
raise exceptions.Error(f'{self.__class__.__name__} already closed')
return f(self, *args, **kwargs)
return g | 9,793 |
def generate_glove_vecs(revs):
"""
This function generates GloVe vectors based on the training data. This function
can be more optimized in future.
:return: A dictionary containing words as keys and their GloVe vectors as the corresponding values.
:rtype: dict
"""
os.chdir("GloVe")
... | 9,794 |
def test_valid_nym_with_fees(fees,
helpers,
nodeSetWithIntegratedTokenPlugin,
sdk_wallet_steward,
address_main,
sdk_pool_handle,
sdk_wallet_truste... | 9,795 |
def poll_input_files():
"""
Polls the specified input folder for any new files. This is done by tracking the difference
in results. This could be faster by leveraging the WIN32 FileChangeAPI, but this code aims to
be more cross-platform and easier to digest.
"""
global POLL_DELAY
global I... | 9,796 |
def get_diff_comparison_score(git_commit, review_url, git_checkout_path,
cc): # pragma: no cover
"""Reads the diff for a specified commit
Args:
git_commit(str): a commit hash
review_url(str): a rietveld review url
git_checkout_path(str): path to a local git checkout
c... | 9,797 |
def pack(pieces=()):
"""
Join a sequence of strings together.
:param list pieces: list of strings
:rtype: bytes
"""
return b''.join(pieces) | 9,798 |
def list_programs(plugin, item_id, **kwargs):
"""
Build programs listing
- Les feux de l'amour
- ...
"""
resp = urlquick.get(URL_ROOT)
root = resp.parse()
for program_datas in root.iterfind(".//a"):
if program_datas.get('href'):
if 'emission/' in program_datas.get('h... | 9,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.