content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_match_history(start_at_match_id=None, player_name=None, hero_id=None,
skill=0, date_min=None, date_max=None, account_id=None,
league_id=None, matches_requested=None, game_mode=None,
min_players=None, tournament_games_only=None,
... | 5,317,600 |
def get_add_drop_period(semester):
"""
Returns the AddDropPeriod object corresponding to the given semester. Throws the same
errors and behaves the same way as AddDropPeriod.objects.get(semester=semester) but runs faster.
This function uses caching to speed up add/drop period object retrieval. Cached ob... | 5,317,601 |
def run_nwp(forecast, model, run_time, issue_time):
"""
Calculate benchmark irradiance and power forecasts for a Forecast or
ProbabilisticForecast.
Forecasts may be run operationally or retrospectively. For
operational forecasts, *run_time* is typically set to now. For
retrospective forecasts, ... | 5,317,602 |
def test_metrics_page(client):
"""
GIVEN a Flask application
WHEN the '/' page is requested (GET)
THEN check the response is valid
"""
response = client.get('/metrics')
assert response.status_code == 200 | 5,317,603 |
def get_path_filename(handle):
""" cleans path, combines it"""
path = config['path'].strip('/').strip()
return path + '/' + handle + config['extension'] | 5,317,604 |
def get_user_subscription_steps(signature=None):
"""ユーザー申込みのステップ数
:return:
"""
url_pattern = 'format:user_subscription_step%s'
url_kwargs = {'signature': signature}
step_list = create_steps(
[
('①', '申込み基本情報'),
('②', '申込者分類選択'),
('③', '申込者情報入力'),
... | 5,317,605 |
def approx(g, nodes):
"""
Computes the approximation of g over the nodes for Simpson's method
"""
factor = g(nodes[2] - nodes[0]) / _real(6)
_sum = g(nodes[0]) + _real(4) * g(nodes[1]) + g(nodes[2])
return factor * _sum | 5,317,606 |
def _get_db_path():
"""
Return the path to the database file. If the environment variable NATURE_RECORDER_DB is set, this will be used
as the path to the SQLite database file. If not, then the default "development" database file, in the
applications data folder, is used.
:return: The path to the d... | 5,317,607 |
def sdf_read(auth, file_types, filter_type, filter_ids, version='3.1'):
""" Read sdf file from DV360 api
https://developers.google.com/bid-manager/v1/sdf/download
Args:
* auth: (string) Either user or service.
* file_types: (list[string]) List of the requested file types
* filter_type: (string) Val... | 5,317,608 |
def get_fmtfldsdict(prtfmt):
"""Return the fieldnames in the formatter text."""
# Example prtfmt: "{NS} {study_cnt:2} {fdr_bh:5.3e} L{level:02} D{depth:02} {GO} {name}\n"
return {v:v for v in get_fmtflds(prtfmt)} | 5,317,609 |
async def on_ready():
"""
A function that will be called upon when the bot is ready, prints out bot information and owner information.
Returns:
None
"""
bot.defaultPre = default_prefix
bot.appinfo = await bot.application_info()
bot.loaded = loaded_cogs
bot.unloaded = unloaded_c... | 5,317,610 |
def save_progress(config, net, mapping_assignment_dataloader,
mapping_test_dataloader, index, sobel, render_count):
"""
Draws all predictions using convex combination.
"""
# Using this for MNIST
if sobel:
raise NotImplementedError
prog_out_dir = os.path.join(config.out_dir, "progress... | 5,317,611 |
def get_checksum(file_name: str) -> str:
"""Returns checksum of the file"""
sha_hash = hashlib.sha224()
a_file = open(file_name, "rb")
content = a_file.read()
sha_hash.update(content)
digest = sha_hash.hexdigest()
a_file.close()
return digest | 5,317,612 |
def find_tool(name, additional_paths = [], path_last = False):
""" Attempts to find tool (binary) named 'name' in PATH and in
'additional-paths'. If found in path, returns 'name'. If
found in additional paths, returns full name. If the tool
is found in several directories, returns the... | 5,317,613 |
async def test_set_hvac_bad_attr_and_state(hass):
"""Test setting hvac mode without required attribute.
Also check the state.
"""
state = hass.states.get(ENTITY_CLIMATE)
assert state.attributes.get(ATTR_HVAC_ACTION) == CURRENT_HVAC_COOL
assert state.state == HVAC_MODE_COOL
with pytest.rais... | 5,317,614 |
def sync_grains(name, **kwargs):
"""
Performs the same task as saltutil.sync_grains module
See :mod:`saltutil module for full list of options <salt.modules.saltutil>`
.. code-block:: yaml
sync_everything:
saltutil.sync_grains:
- refresh: True
"""
return _sync_sing... | 5,317,615 |
def masked_topk(
input_: torch.FloatTensor,
mask: torch.BoolTensor,
k: Union[int, torch.LongTensor],
dim: int = -1,
) -> Tuple[torch.LongTensor, torch.LongTensor, torch.FloatTensor]:
"""
Extracts the top-k items along a certain dimension. This is similar to `torch.topk` except:
(1) we allow ... | 5,317,616 |
def bessel_kve(v, z, name=None):
"""Computes exponentially scaled modified Bessel function of the 2nd kind.
This function computes `Kve` which is an exponentially scaled version
of the modified Bessel function of the first kind.
`Kve(v, z) = Kv(v, z) * exp(abs(z))`
Warning: Gradients with respect to the fi... | 5,317,617 |
def cvReleaseConDensation(*args):
"""cvReleaseConDensation(PyObject obj)"""
return _cv.cvReleaseConDensation(*args) | 5,317,618 |
def solution(num_buns, num_required):
"""
Each choice of num_required-1 of the num_buns determines a missing key.
Therefore, we use binom[num_buns,num_required-1] different keys.
Each key is used in each num_buns-num_required+1 bunny.
Therefore, each key is repeated num_buns-num_required+1 times.
... | 5,317,619 |
def check_SSL_certificate(url, verbose):
""" Check SSL certificate expiration date of a server hostname """
hostname = urllib.parse.urlparse(url).hostname
port = urllib.parse.urlparse(url).port
if verbose == 1:
print("- Checking SSL certificate in progres...")
now = datetime.now()
cont... | 5,317,620 |
def save_class_activation_images(org_img, activation_map, file_name):
"""
Saves cam activation map and activation map on the original image
Args:
org_img (PIL img): Original image
activation_map (numpy arr): Activation map (grayscale) 0-255
file_name (str): File name of the expor... | 5,317,621 |
def isToday(date_str):
"""
Check whether the last_checkt_time is today.
:param date:
:return:
"""
today = datetime.datetime.today()
date = datetime.datetime.strptime(date_str, '%Y-%m-%d %H:%M')
return today.year == date.year and today.month == date.month and today.day == date.day | 5,317,622 |
def mpl_3d_remove_margins():
"""
Remove thin margins in matplotlib 3d plots.
The Solution is from `Stackoverflow`_.
.. _Stackoverflow:
http://stackoverflow.com/questions/16488182/
"""
from mpl_toolkits.mplot3d.axis3d import Axis
if not hasattr(Axis, "_get_coord_info_old"):
... | 5,317,623 |
def copy_flatpages():
"""Copy existing flatpages into Pages"""
from django.contrib.flatpages.models import FlatPage
for fp in FlatPage.objects.all():
p = Page(url=fp.url, title=fp.title, content=fp.content, publish=False, index=0)
p.save() | 5,317,624 |
def try_compute_data(s3, webhook, old_data):
"""
Try to run the scraper and return course data. If something goes
wrong, raise `ScrapeError`. Otherwise, invoke the provided
`Webhook`. `old_data` is the previous course data or `util.Unset`.
"""
scraper_timeout = util.get_env("scraper_timeout")
... | 5,317,625 |
def get_chinese_relation_name(request, user1, user2):
"""
Gets what user1 called user2 in Chinese
Response:
{'status': Http status,
'title': string
}
"""
try:
title = get_chinese_relation(user1, user2)
return Response({
'title': title
})
... | 5,317,626 |
def test_wrong_key(mocker: MockerFixture) -> None:
"""Test if the configuration file contains non-recognized keys.
The file keys are the expected ones but written in capital, the keys are case sensitive.
An exception is expected.
"""
l_file = "tests/config/toml_files/wrong_key.toml"
config.sav... | 5,317,627 |
def projplot(theta, phi, fmt=None, **kwargs):
"""projplot is a wrapper around :func:`matplotlib.Axes.plot` to take into account the
spherical projection.
You can call this function as::
projplot(theta, phi) # plot a line going through points at coord (theta, phi)
projplot(theta, p... | 5,317,628 |
def compress_vertex_list(individual_vertex: list) -> list:
"""
Given a list of vertices that should not be fillet'd,
search for a range and make them one compressed list.
If the vertex is a point and not a line segment, the returned tuple's
start and end are the same index.
Args:
indivi... | 5,317,629 |
def step_db_connect_dbserver(context):
"""
Send connect to database.
"""
context.cli.sendline('\\connect postgres')
context.currentdb = 'postgres' | 5,317,630 |
def update_context_with_user_data(update: Update, context: CallbackContext) -> tuple:
"""Update context.user_data with UserProfile data."""
# Update needed only when context.user_data is empty
if context.user_data:
return update, context
if hasattr(update.callback_query, 'message'):
chat... | 5,317,631 |
async def fetchScans(startscan, endscan, destination='downloads/'):
"""Wrapper function to download a bunch of scans based on a
first and last scan name taken from the SAA index browser.
Args:
startscan (str): First scan of the inventory
endscan (str): Last scan of the inventory
... | 5,317,632 |
def multiply_images( images, normalize_result = False, color_mode = MODE ):
"""Multiplica N imagens
Args:
images: lista de imagens
normalize_result: indica truncamento(False) ou normalização(True), default=False
color_mode = 'color color_mode' da imagem resultante, defaul='RGB'
... | 5,317,633 |
def setup_harn(**kwargs):
"""
CommandLine:
python ~/code/netharn/netharn/examples/ggr_matching.py setup_harn
Args:
dbname (str): Name of IBEIS database to use
nice (str): Custom tag for this run
workdir (PathLike): path to dump all the intermedate results
dim (int): ... | 5,317,634 |
def simulate(sim, dt=1.0, get_frames=True, data=None):
"""Simulate dt seconds at 60Hz to the nearest fixed timestep"""
observations = []
physics_step_times = []
graphics_render_times = []
collisions = []
start_time = sim.get_world_time()
while sim.get_world_time() < start_time + dt:
... | 5,317,635 |
def test_BGP_GR_chaos_34_1_p1(request):
"""
Test Objective : Restarting node doesn't preserve forwarding
state, helper router should not keep the stale entries.
"""
tgen = get_topogen()
tc_name = request.node.name
write_test_header(tc_name)
# Check router status
check_router_status... | 5,317,636 |
def sanitize_comment(comment):
"""Sanitize malicious tags from posted comments.
Takes an HTML comment string, returns that comment with malicious tags removed.
Defaults to bleach's default set of allowed tags:
['a', 'abbr', 'acronym', 'b', 'blockquote', 'code', 'em', 'i', 'li', 'ol', 'strong', 'ul']
... | 5,317,637 |
def process_classes(classes, num_workers, failed_save_file, no_sound_save_file):
"""
Extract sounds for a category.
:param classes: List of classes.
:param num_workers: Number of worker processes.
:param failed_save_file: Path to a log of failed extractions.
:param no_sound_save... | 5,317,638 |
def get_api_result(mode, extra_arguments={}):
""" Build JSON request to SABnzbd """
arguments = {'apikey': 'apikey', 'output': 'json', 'mode': mode}
arguments.update(extra_arguments)
r = requests.get('http://%s:%s/api' % (SAB_HOST, SAB_PORT), params=arguments)
return r.json() | 5,317,639 |
async def get_exchange_info(exchange):
""" Fetches and returns relevant information about an exchange for historical data fetch.
Args:
exchange (str): The name of the exchange.
Returns:
str: JSON data with market exchange information.
"""
# Loads the market.
ex = getattr(ccxt_... | 5,317,640 |
def create_top_key_words_all(data_res, query, filter, filter_values):
"""Returns keywords graph as dcc.Graph component
Only displays it when all data is retrieved"""
dff_res = pd.DataFrame(data_res['data'])
dff_res['result'] = 'direct'
dff_res = data_preprocess.filter_data_by_time(dff_res, filter... | 5,317,641 |
def proccess_grains(grains_data, model_code, host_name, ip=None):
""" new_data 增加 model_code + "_HOSTNAME"""
all_data = grains_data.get("data")
data = all_data.get(host_name)
selinux = data.get("selinux", None)
dns = data.get("dns", None)
if dns:
dns = dns.get("nameservers")
else:
... | 5,317,642 |
def rehash_handler(data: ConfigRoot):
"""
Apply context-related configuration values from event
Args:
data(typing.Dict): configuration object
"""
Context.PREFIX = data.commands.prefix
Context.DRILL_MODE = data.commands.drill_mode
logger.debug(f"in rehash handler, using new prefix {C... | 5,317,643 |
def build_keywords_array(value):
"""Take a comma-separated string of items and turn it into an array.
"""
pass | 5,317,644 |
def V2(params, fs, hs, ops, opsH, vector, shots=2**13, backend=Aer.get_backend('aer_simulator') ):
"""
Calculate the matrix A
"""
N = params.shape[0]
v = np.zeros(N)
for k in range(N):
v[k] = V_k(params, fs, hs, ops, opsH, vector, k, shots, backend )
return v | 5,317,645 |
def cachedeterministic(parser, token):
"""
This will cache the contents of a template fragment for a given amount of
time, just like {% cache .. %} except that the key is deterministic and not
mangled or run through MD5.
Usage::
{% cachedeterministic [expire_time] [key] %}
.. s... | 5,317,646 |
async def generate_acl6(participant: Participant) -> List[str]:
"""Generate a Participant-Specific IPv6 ACL."""
peer_acl = sorted(DEFAULT6.copy())
init_lines = (
f"no ipv6 access-list ipv6-{participant.asn}-in",
f"ipv6 access-list ipv6-{participant.asn}-in",
)
for i, l in enumerate(i... | 5,317,647 |
def make_veth_signed_order(
asset_infos, # pylint: disable=redefined-outer-name
pydex_client, # pylint: disable=redefined-outer-name
exchange_address, # pylint: disable=redefined-outer-name
):
"""Convenience function for creating a new instance of a signed order"""
def _make_veth_signed_order( #... | 5,317,648 |
def normalize(vec):
"""Return unit vector for parameter vec.
>>> normalize(np.array([3, 4]))
array([ 0.6, 0.8])
"""
if np.any(vec):
norm = np.linalg.norm(vec)
return vec / norm
else:
return vec | 5,317,649 |
def get_x_coordinate(width, year_index):
"""
Given the width of the canvas and the index of the current year
in the YEARS list, returns the x coordinate of the vertical
line associated with that year.
Input:
width (int): The width of the canvas
year_index (int): The index of the cur... | 5,317,650 |
def add_rnaseq_args():
"""
Arguments for RNAseq pipeline
"""
parser = argparse.ArgumentParser(
description='RNA-seq pipeline')
parser.add_argument('-b', '--build-design', dest='build_design',
action='store_true',
help='Create design for fastq files')
parser.add_argument('... | 5,317,651 |
def get_downloader(start_date,
end_date,
granularity='daily',):
"""returns a downloader closure for oanda
:param start_date: the first day on which dat are downloaded
:param end_date: the last day on which data are downloaded
:param granularity: the frequency of price data,... | 5,317,652 |
def run_GUI(computer=False):
"""Start the GUI.
computer -- True if playing against computer
"""
root = Tk()
root.title('The Game of Hog')
root.minsize(520, 600)
root.geometry("520x600")
# Tkinter only works with GIFs
HogGUI.IMAGES = {
1: PhotoImage(file='images/die1.gif'),
... | 5,317,653 |
def stick_together(seg, factor, connectivity=1):
"""
For every segment which are immediate neighbors, determine the number
of neighboring pixels and the volume of the smaller of the two
segments. If n_neighbors / volume**(2/3) > factor, stick the two
segments together. This is based on the heuristic... | 5,317,654 |
def init_db_for_functionality_tests(doc, constants, session, add_doc_classes_and_properties_to_db):
"""
Initalze the database for testing app in
tests/functional/test_app.py.
"""
for class_ in doc.parsed_classes:
class_title = doc.parsed_classes[class_]['class'].title
dummy_obj = gen... | 5,317,655 |
def spkacs(targ, et, arg3, arg4, obs):
"""spkacs(SpiceInt targ, SpiceDouble et, ConstSpiceChar * arg3, ConstSpiceChar * arg4, SpiceInt obs)"""
return _cspyce0.spkacs(targ, et, arg3, arg4, obs) | 5,317,656 |
def replicated_all_reduce_(t: Tensor,
op: CollectiveOperator = CollectiveOperator.Add,
group: Optional[CommGroup] = None) -> Tensor:
"""Reduces tensor `t` across replicas inplace on `t`.
Args:
t (Tensor): Tensor to be reduced
op (CollectiveO... | 5,317,657 |
def destroy(token):
"""
take down the droplets by tag name.
this is useful when testing deploying to keep taking down all the droplets
of the tag "marian".
"""
params = {
'tag_name': 'marian',
}
url = 'https://api.digitalocean.com/v2/droplets'
request = requests.delete(url... | 5,317,658 |
def main():
"""Main function."""
runner = IcePartialRunner()
return runner.start() | 5,317,659 |
def get_kip_main_page_body(kip_main_info: Dict[str, Any]) -> str:
"""Gets the RAW HTML body of the KIP main page"""
kip_body_request: requests.Response = requests.get(
CONTENT_URL + "/" + kip_main_info["id"], params={"expand": "body.view"}
)
kip_body_request.raise_for_status()
return kip_... | 5,317,660 |
def load_model_tf(checkpoint_path):
"""
Restores custom model class which imitates keras' Model behaviour
"""
model = Model()
model.load(checkpoint_path)
return model | 5,317,661 |
def _get_project_folder(name: str) -> str:
"""
Returns the full folder path of the named project.
Args:
name (str): The name of the project.
Returns:
(str): The path of the project folder.
"""
reg_data = _get_registry_data()
return reg_data[name]["location"] | 5,317,662 |
def dcos_service_url(service):
"""Return the URL of a service running on DC/OS, based on the value of
shakedown.dcos.dcos_url() and the service name.
:param service: the name of a registered DC/OS service, as a string
:return: the full DC/OS service URL, as a string
"""
return _gen_url("/service... | 5,317,663 |
def train_new_error(h1, h2, number_of_epochs,
training_set, test_set, batch_size_train, batch_size_test,
OptimizerClass, optimizer_kwargs,
NewErrorLossClass,
lambda_c, new_error_loss_kwargs=None, device="cpu"):
"""
Args:
h1:... | 5,317,664 |
def to_timedelta(arg: pandas.core.series.Series, errors: Literal["coerce"]):
"""
usage.dask: 1
"""
... | 5,317,665 |
def get_configuration(resource_type, resource_id, configuration_capture_time):
"""Get configurationItem using getResourceConfigHistory API
in case of OversizedConfigurationItemChangeNotification
"""
result = AWS_CONFIG_CLIENT.get_resource_config_history(
resourceType=resource_type,
resou... | 5,317,666 |
def scenario_development_one_hot_encoded(sources, scenarios, territory="Europe"):
"""
Creates a dataframe with the operation of a production facility encoded to its activity in the given
years
:param sources: List or string of carbon sources
:param scenarios: List of Desired scenarios
:param ter... | 5,317,667 |
def urlparse(d, keys=None):
"""Return a copy of the given dictionary with url values parsed."""
d = d.copy()
if keys is None:
keys = d.keys()
for key in keys:
d[key] = _urlparse(d[key])
return d | 5,317,668 |
def run():
"""KIPper Main Method"""
parser: ArgumentParser = create_parser()
args: Namespace = parser.parse_args()
if args.subcommand == "init":
print("Initializing all data caches")
print("Downloading KIP Wiki Information")
args.overwrite = True
setup_wiki_download(arg... | 5,317,669 |
def URFeaturizer(input_shape, hparams, **kwargs):
"""Auto-select an appropriate featurizer for the given input shape."""
if input_shape[1:3] == (224, 224):
return URResNet(input_shape, hparams, **kwargs)
else:
raise NotImplementedError(f"Input shape {input_shape} is not supported") | 5,317,670 |
def week_of_year(datetime_col):
"""Returns the week from a datetime column."""
return datetime_col.dt.week | 5,317,671 |
def _NamespaceKeyToString(key):
"""Extract namespace name from __namespace__ key.
Raises an ApplicationError if the key is not of the form '__namespace__'/name
or '__namespace__'/_EMPTY_NAMESPACE_ID.
Args:
key: a key for a __namespace__ instance.
Returns:
namespace specified by key.
"""
key_path... | 5,317,672 |
def load_rss(rss_file_path) -> List[str]: # pragma: no cover
"""
Given a file, yield all RSS links
TODO: check edge cases and exclude links that don't validate accepted RSS link format
"""
with open(rss_file_path, 'r') as f:
for line in f.readlines():
yield line.strip() | 5,317,673 |
def novo_usuario(usuario,senha,root):
"""Cria e insere um usuário no banco"""
if("True" in root):
estado=1
else:
estado=""
dados={"login":usuario,"senha":crypt.crypt(senha),"root":bool(estado)}
try:
colecao.insert_one(dados)
#sucesso ao criar um usuário.
retur... | 5,317,674 |
def fill_dict(_dict, **kwargs):
"""A helper to fill the dict passed with the items passed as keyword
arguments if they are not yet in the dict. If the dict passed was
`None` a new dict is created and returned.
This can be used to prepopulate initial dicts in overriden constructors:
class MyFo... | 5,317,675 |
def list_live_assessment_results(request_ctx, course_id, assessment_id, user_id=None, **request_kwargs):
"""
Returns a list of live assessment results
:param request_ctx: The request context
:type request_ctx: :class:RequestContext
:param course_id: (required) ID
:type course_id... | 5,317,676 |
def extract_format_data(matrix):
"""Extract format information from the upper-left corner.
Parameters:
matrix (ndarray): 2D array containing the QR matrix.
Returns:
Tuple (error_correction_level, mask_pattern).
Raises:
QRDecodeError: If the format information can not be decode... | 5,317,677 |
def on_core_type_change(_step, _prop):
"""
When core type value is changed
:param _step: unused
:param _prop: unused
:return:
"""
transformer.prefill_core_models() | 5,317,678 |
def updateiface(data, elements):
"""
Run only updates of data on the interface
data : input data
elements : output of createiface(data)
"""
(xx, yy, dx, dy, angle, xr, yr, adeg, xxx, xxy, yyx, yyy, xwidth, ywidth, xc, yc, xcut, ycut, xcutg, ycutg) = analyze(data)
(fig, img, centre, ell... | 5,317,679 |
def decrypt_and_print_message(args):
"""Try to decrypt and print a message."""
for key in args.keys:
for nounce in range(args.nounce_lower, args.nounce_upper):
if _decrypt_chacha20poly1305(args.message, nounce, key):
return 0
return 1 | 5,317,680 |
def readCylWFSRaw(fn):
"""
Load in data from WFS measurement of cylindrical mirror.
Assumes that data was processed using processHAS, and loaded into
a .fits file.
Scale to microns, remove misalignments,
strip NaNs.
If rotate is set to an array of angles, the rotation angle
which minimiz... | 5,317,681 |
def normalize(df, df_ref=None):
"""
Normalize all numerical values in dataframe
:param df: dataframe
:param df_ref: reference dataframe
"""
if df_ref is None:
df_ref = df
df_norm = (df - df_ref.mean()) / df_ref.std()
return df_norm | 5,317,682 |
def get_shapes(ndim):
"""
produce a bunch of tensor shapes of order `ndim`.
Args:
ndim: The tensor order.
Returns:
list[tuple[int]]: A list of shapes.
"""
if ndim == 3:
shapes = unique_permutations((8, 64, 128))
some_combs = sum((list(zip(shapes, unique_permutations(pshape)))
... | 5,317,683 |
def generate_package(
package_type: str, nickname: str, title: str, description: str
) -> None:
"""Generate a new package folder"""
generator = create_package_generator(package_type, nickname, title, description)
generator.generate()
generator.create_build_file()
click.echo()
click.secho("Yo... | 5,317,684 |
def gen_stimuli(M, N):
"""
This function generates the stimuli (taken from actual data)
"""
a = (np.random.randn(1, M) * 100).astype(np.float32)
B = (np.random.randn(M, N) * 100).astype(np.float32)
y = custom_vecmatmul(a, B)
return a, B, y | 5,317,685 |
def set_ipconfig(var1):
"""Configuration du fichier interfaces de l'OS Debian"""
try:
fichier = open("/etc/network/interfaces", "a")
fichier.write(var1["int"]+"\n")
fichier.write(var1["type"]+"\n")
fichier.write(var1["ip"]+"\n")
fichier.write(var1["mask"]+"\n")
fichier.write(... | 5,317,686 |
def agentXML(request, identifier):
"""
Return a representation of a given agent
"""
if 'premis' in request.path:
identifier = identifier.replace('.premis', '')
try:
agentObject = Agent.objects.get(agent_identifier=identifier)
except Agent.DoesNotExist:
re... | 5,317,687 |
def dmlc_opts(opts):
"""convert from mxnet's opts to dmlc's opts
"""
args = ['--num-workers', str(opts.num_workers),
'--num-servers', str(opts.num_servers),
'--cluster', opts.launcher,
'--host-file', opts.hostfile,
'--sync-dst-dir', opts.sync_dst_dir]
args... | 5,317,688 |
def pretty_print_my_submissions_data(submissions, start_date, end_date):
"""
Funcion to print the submissions for a particular Challenge.
"""
table = BeautifulTable(max_width=100)
attributes = ["id", "participant_team_name", "execution_time", "status"]
columns_attributes = [
"ID",
... | 5,317,689 |
def get_virtual_border_routers(filters: Optional[Sequence[pulumi.InputType['GetVirtualBorderRoutersFilterArgs']]] = None,
ids: Optional[Sequence[str]] = None,
name_regex: Optional[str] = None,
output_file: Optional[str] = None,... | 5,317,690 |
def cal_angle(center, point):
"""
利用向量点乘 ,计算center为顶点,center->point 与 x 轴 的夹角
:param center: 顶点 tuple
:param point: x轴外边上一点 tuple
:return:angle 角度
"""
center = center[:2]
point = point[:2]
vec1 = (point[0] - center[0], point[1] - center[1])
dis_of_vec1 = math.sqrt(vec1[0] ** 2 +... | 5,317,691 |
def PermutationGroup(gens=None, gap_group=None, domain=None, canonicalize=True, category=None):
"""
Return the permutation group associated to `x` (typically a
list of generators).
INPUT:
- ``gens`` - list of generators (default: ``None``)
- ``gap_group`` - a gap permutation group (default... | 5,317,692 |
def lunar_diameter(tee):
"""Return the geocentric apparent lunar diameter of the moon (in
degrees) at moment, tee. Adapted from 'Astronomical
Algorithms' by Jean Meeus, Willmann_Bell, Inc., 2nd ed."""
return deg(1792367000/9) / lunar_distance(tee) | 5,317,693 |
def findCongressPerson(name, nicknames_json):
"""
Checks the nicknames endpoint of the NYT Congress API
to determine if the inputted name is that of a member of Congress
"""
congress_json = [x['nickname'] for x in nicknames_json if x['nickname'] == name]
if len(congress_json) > 0:
return... | 5,317,694 |
def main(repo, doc, imp, args=None):
"""Console script for gojot"""
click.echo("Replace this message by putting your code into "
"gojot.cli.main")
click.echo("See click documentation at http://click.pocoo.org/")
if imp != None:
run_import(repo, imp)
else:
run(repo, doc... | 5,317,695 |
def make_canonical_transform_np(
n_xyz: np.ndarray,
ca_xyz: np.ndarray,
c_xyz: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
"""Returns translation and rotation matrices to canonicalize residue atoms.
Note that this method does not take care of symmetries. If you provide the
atom positions in t... | 5,317,696 |
def get_data_for_result_table(all_answers):
"""
Generate simple data for result table (question, answer status true/false).
@param all_answers: dict with pairs question_id and list of answers for question.
@return: dict with all data for result table.
"""
result_data = {}
for question_id, a... | 5,317,697 |
def _validate_positive_int(value):
"""Validate value is a natural number."""
try:
value = int(value)
except ValueError as err:
raise ValueError("Could not convert to int") from err
if value > 0:
return value
else:
raise ValueError("Only positive values are valid") | 5,317,698 |
def transpose(table):
"""
Returns a copy of table with rows and columns swapped
Example:
1 2 1 3 5
3 4 => 2 4 6
5 6
Parameter table: the table to transpose
Precondition: table is a rectangular 2d List of numbers
"""
result = []... | 5,317,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.