uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8bc2c2cca14e3f595950a4c3 | train | function | def unknown_target_igsp(
setting_list: List[Dict],
nodes: set,
ci_tester: CI_Tester,
invariance_tester: InvarianceTester,
depth: Optional[int] = 4,
nruns: int = 5,
initial_undirected: Optional[Union[str, UndirectedGraph]] = 'threshold',
initial_permutation... | def unknown_target_igsp(
setting_list: List[Dict],
nodes: set,
ci_tester: CI_Tester,
invariance_tester: InvarianceTester,
depth: Optional[int] = 4,
nruns: int = 5,
initial_undirected: Optional[Union[str, UndirectedGraph]] = 'threshold',
initial_permutation... | """
Use the Unknown Target Interventional Greedy Sparsest Permutation algorithm to estimate a DAG in the I-MEC of the
data-generating DAG.
Parameters
----------
setting_list:
A list of dictionaries that provide meta-information about each non-observational setting.
nodes:
No... | \in I, the distribution of j given its parents varies between the observational and
interventional data.
setting_list:
A list of dictionaries that provide meta-information about each setting.
The first setting must be observational.
i:
Source of the edge being tested.
j:
... | 256 | 256 | 2,228 | 124 | 131 | uhlerlab/graphical_model_learning | graphical_model_learning/algorithms/dag/gsp.py | Python | unknown_target_igsp | unknown_target_igsp | 770 | 967 | 770 | 783 | 48c0fc8badd49f5449989e38bad358da73c993c9 | bigcode/the-stack | train |
b889aaa06ad4594a2a969299 | train | function | def sparsest_permutation(nodes, ci_tester, progress=False):
"""
Estimate the Markov equivalence class of a DAG using the Sparsest Permutations (SP) algorithm.
Parameters
----------
nodes:
list of nodes.
ci_tester:
object for testing conditional independence.
progress:
... | def sparsest_permutation(nodes, ci_tester, progress=False):
| """
Estimate the Markov equivalence class of a DAG using the Sparsest Permutations (SP) algorithm.
Parameters
----------
nodes:
list of nodes.
ci_tester:
object for testing conditional independence.
progress:
if True, show a progress bar over the enumeration of permu... | frozenset({pi_i, pi_j}) in fixed_gaps:
continue
# === TEST MARKOV BLANKET
mb = d.markov_blanket_of(pi_i)
is_ci = ci_tester.is_ci(pi_i, pi_j, mb)
if not is_ci:
d.add_arc(pi_i, pi_j, check_acyclic=True)
if verbose: print(f"{pi_i} is independent of {pi_j} ... | 122 | 122 | 407 | 14 | 107 | uhlerlab/graphical_model_learning | graphical_model_learning/algorithms/dag/gsp.py | Python | sparsest_permutation | sparsest_permutation | 109 | 149 | 109 | 109 | 04f1744ada2df5a822bb51b2fae4eef9a07d53ae | bigcode/the-stack | train |
8055911effbeef41774b2b67 | train | function | def perm2dag2(perm, ci_tester, node2nbrs=None):
arcs = set()
for (i, pi_i), (j, pi_j) in itr.combinations(enumerate(perm), 2):
c = set(perm[:j]) - {pi_i}
c = c if node2nbrs is None else c & (node2nbrs[pi_i] | node2nbrs[pi_j])
print(pi_i, pi_j, c)
if not ci_tester.is_ci(pi_i, pi_j... | def perm2dag2(perm, ci_tester, node2nbrs=None):
| arcs = set()
for (i, pi_i), (j, pi_j) in itr.combinations(enumerate(perm), 2):
c = set(perm[:j]) - {pi_i}
c = c if node2nbrs is None else c & (node2nbrs[pi_i] | node2nbrs[pi_j])
print(pi_i, pi_j, c)
if not ci_tester.is_ci(pi_i, pi_j, c):
arcs.add((pi_i, pi_j))
ret... | , nodes - {i} - candidate_parent_set, candidate_parent_set):
arcs.update({(parent, i) for parent in candidate_parent_set})
break
return DAG(nodes=nodes, arcs=arcs)
def perm2dag2(perm, ci_tester, node2nbrs=None):
| 64 | 64 | 145 | 18 | 46 | uhlerlab/graphical_model_learning | graphical_model_learning/algorithms/dag/gsp.py | Python | perm2dag2 | perm2dag2 | 168 | 176 | 168 | 168 | aca2fdd3768a571a73eb5761d1a52e1114942189 | bigcode/the-stack | train |
049dd9ed86b72a55c6119cf0 | train | function | def permutation2dag(
perm: list,
ci_tester: CI_Tester,
verbose=False,
fixed_adjacencies: Set[UndirectedEdge]=set(),
fixed_gaps: Set[UndirectedEdge]=set(),
progress=False
):
"""
Estimate the minimal IMAP of a DAG which is consistent with the given permutation.
... | def permutation2dag(
perm: list,
ci_tester: CI_Tester,
verbose=False,
fixed_adjacencies: Set[UndirectedEdge]=set(),
fixed_gaps: Set[UndirectedEdge]=set(),
progress=False
):
| """
Estimate the minimal IMAP of a DAG which is consistent with the given permutation.
Parameters
----------
perm:
list of nodes representing the permutation.
ci_tester:
object for testing conditional independence.
verbose:
if True, log each CI test.
fixed_adjace... | = np.nonzero(current_precision_thresholded[-1])[0]
else:
parents = np.nonzero(~iszero(current_precision[-1]))[0]
label = perm[node]
new_arcs = set(itr.product(perm[parents], [label])) - {(label, label)}
arcs.update(new_arcs)
# marginalize out the last node
c... | 189 | 189 | 631 | 55 | 134 | uhlerlab/graphical_model_learning | graphical_model_learning/algorithms/dag/gsp.py | Python | permutation2dag | permutation2dag | 41 | 106 | 41 | 48 | 5b9ac98c947f4d1a96a6945a6e049eb6340061da | bigcode/the-stack | train |
120210cfd8e72b06a653be42 | train | function | def perm2dag_precision(perm, precision, alpha=.01, num_samples=None):
perm = np.array(perm)
current_precision = precision.copy()
current_precision[:, :] = current_precision[perm, :]
current_precision[:, :] = current_precision[:, perm]
nnodes = precision.shape[0]
arcs = set()
# iterate throu... | def perm2dag_precision(perm, precision, alpha=.01, num_samples=None):
| perm = np.array(perm)
current_precision = precision.copy()
current_precision[:, :] = current_precision[perm, :]
current_precision[:, :] = current_precision[:, perm]
nnodes = precision.shape[0]
arcs = set()
# iterate through the permutation in reverse order
for node in range(nnodes-1, -1... | _model_learning.utils.core_utils import powerset, iszero
import random
from graphical_model_learning.algorithms.undirected import threshold_ug, partial_correlation_threshold
from graphical_models import UndirectedGraph
import numpy as np
from tqdm import trange, tqdm
from math import factorial
def perm2dag_precision(pe... | 78 | 78 | 261 | 18 | 59 | uhlerlab/graphical_model_learning | graphical_model_learning/algorithms/dag/gsp.py | Python | perm2dag_precision | perm2dag_precision | 16 | 38 | 16 | 16 | 833e470ae00c1a44b9de0ac5b323d0a281a76076 | bigcode/the-stack | train |
7ce0e2b1d302886f70b10623 | train | function | def update_minimal_imap(dag, i, j, ci_tester, fixed_adjacencies=set(), fixed_gaps=set()):
"""
TODO
Parameters
----------
TODO
Examples
--------
TODO
"""
removed_arcs = set()
parents = dag.parents_of(i)
for parent in parents:
rest = parents - {parent}
if ... | def update_minimal_imap(dag, i, j, ci_tester, fixed_adjacencies=set(), fixed_gaps=set()):
| """
TODO
Parameters
----------
TODO
Examples
--------
TODO
"""
removed_arcs = set()
parents = dag.parents_of(i)
for parent in parents:
rest = parents - {parent}
if (i, parent) not in fixed_adjacencies | fixed_gaps and (parent, i) not in fixed_adjacencies... | ci_tester.is_ci(pi_i, pi_j, c):
arcs.add((pi_i, pi_j))
return DAG(nodes=set(perm), arcs=arcs)
def update_minimal_imap(dag, i, j, ci_tester, fixed_adjacencies=set(), fixed_gaps=set()):
| 64 | 64 | 205 | 28 | 36 | uhlerlab/graphical_model_learning | graphical_model_learning/algorithms/dag/gsp.py | Python | update_minimal_imap | update_minimal_imap | 179 | 201 | 179 | 179 | a94c68038301f46de41814a0bb8bb541f211c46b | bigcode/the-stack | train |
5c8effd1fae9842b6f1e28f2 | train | function | def jci_gsp(
setting_list: List[Dict],
nodes: set,
combined_ci_tester: CI_Tester,
depth: int = 4,
nruns: int = 5,
verbose: bool = False,
initial_undirected: Optional[Union[str, UndirectedGraph]] = 'threshold',
):
"""
TODO
Parameters
----------
... | def jci_gsp(
setting_list: List[Dict],
nodes: set,
combined_ci_tester: CI_Tester,
depth: int = 4,
nruns: int = 5,
verbose: bool = False,
initial_undirected: Optional[Union[str, UndirectedGraph]] = 'threshold',
):
| """
TODO
Parameters
----------
TODO
Examples
--------
TODO
"""
# CREATE NEW NODES AND OTHER INPUT TO ALGORITHM
context_nodes = ['c%d' % i for i in range(len(setting_list))]
context_adjacencies = set(itr.permutations(context_nodes, r=2))
known_iv_adjacencies = set.un... | curr_undirected_graph.add_edges_from(nodes2added[removed_node])
# if delete:
# curr_undirected_graph.delete_edges_from(nodes2removed[removed_node])
#
# permutation.append(removed_node)
#
# return list(reversed(permutation))
# def min_degree_alg2(undirected_graph):
# amat =... | 168 | 169 | 565 | 73 | 95 | uhlerlab/graphical_model_learning | graphical_model_learning/algorithms/dag/gsp.py | Python | jci_gsp | jci_gsp | 296 | 357 | 296 | 304 | 3fe39a76004e3fe7f7a4d32300c48da96cec6368 | bigcode/the-stack | train |
371efd695b898a882742ca7c | train | class | class Direction(IntFlag):
Stay = 0
North = 1
East = 2
South = 4
West = 8
All = 15
# get the enum name without the class
def __str__(self): return self.name
def get_value( direction_list: List[int] ) -> int:
''' convert a list of directions into a single bitfield va... | class Direction(IntFlag):
| Stay = 0
North = 1
East = 2
South = 4
West = 8
All = 15
# get the enum name without the class
def __str__(self): return self.name
def get_value( direction_list: List[int] ) -> int:
''' convert a list of directions into a single bitfield value '''
dir_value = ... | from enum import IntFlag
from typing import List,Union
''' simple helper class to enumerate directions in the grid levels '''
class Direction(IntFlag):
| 30 | 169 | 564 | 5 | 25 | WhatIThinkAbout/BabyRobotGym | babyrobot/envs/lib/direction.py | Python | Direction | Direction | 5 | 65 | 5 | 5 | bc38e1fd7ddb89e17c9bf3d897e7dd52c1d6ac36 | bigcode/the-stack | train |
c9e307cd429c0bd6ea7de5dd | train | class | class tm700_rgbd_gym(tm700_possensor_gym):
"""Class for tm700 environment with diverse objects.
"""
def __init__(self,
urdfRoot=pybullet_data.getDataPath(),
objRoot='',
actionRepeat=80,
isEnableSelfCollision=True,
renders=False,
... | class tm700_rgbd_gym(tm700_possensor_gym):
| """Class for tm700 environment with diverse objects.
"""
def __init__(self,
urdfRoot=pybullet_data.getDataPath(),
objRoot='',
actionRepeat=80,
isEnableSelfCollision=True,
renders=False,
isDiscrete=True,
maxSte... | import random
import os
from gym import spaces
import time
import json
import pybullet as p
import numpy as np
import pybullet_data
import pdb
import distutils.dir_util
import glob
from pathlib import Path
from pkg_resources import parse_version
import gym
from bullet.tm700 import tm700
from bullet.tm700_possensor_Gym ... | 115 | 256 | 3,637 | 14 | 101 | Tung-I/RoboticArmSimulator | bullet/shapenet_gym.py | Python | tm700_rgbd_gym | tm700_rgbd_gym | 20 | 391 | 20 | 20 | c0bc60980b4b2c2dabecd21f134176a49aef3272 | bigcode/the-stack | train |
c68a5dad68c29b21e7dc36bc | train | function | def main():
print(runbook_json(DslExistingEndpoint))
| def main():
| print(runbook_json(DslExistingEndpoint))
| be given as 'Endpoint.use_existing(<ep-name>)'
Existing endpoints are not allowed in endpoints argument in runbook creation
"""
Task.Exec.ssh(
name="Task1",
script='echo "hello"',
target=ref(Endpoint.use_existing("DslEndpoint")),
)
def main():
| 64 | 64 | 13 | 3 | 61 | tuxtof/calm-dsl | tests/sample_runbooks/existing_endpoint.py | Python | main | main | 25 | 26 | 25 | 25 | 81c6d026e0ed9757ee3591d4e32296507155f8e6 | bigcode/the-stack | train |
d4cdd9c2d652e68754e69f7d | train | function | @runbook
def DslExistingEndpoint():
"""
Runbook example for using existing endpoint
Existing endpoint as target can be given as 'Endpoint.use_existing(<ep-name>)'
Existing endpoints are not allowed in endpoints argument in runbook creation
"""
Task.Exec.ssh(
name="Task1",
script... | @runbook
def DslExistingEndpoint():
| """
Runbook example for using existing endpoint
Existing endpoint as target can be given as 'Endpoint.use_existing(<ep-name>)'
Existing endpoints are not allowed in endpoints argument in runbook creation
"""
Task.Exec.ssh(
name="Task1",
script='echo "hello"',
target=ref(... | """
Calm Runbook Sample for running task on already existing endpoint
"""
from calm.dsl.runbooks import runbook, runbook_json
from calm.dsl.runbooks import RunbookTask as Task
from calm.dsl.runbooks import CalmEndpoint as Endpoint, ref
@runbook
def DslExistingEndpoint():
| 63 | 64 | 88 | 10 | 52 | tuxtof/calm-dsl | tests/sample_runbooks/existing_endpoint.py | Python | DslExistingEndpoint | DslExistingEndpoint | 10 | 22 | 10 | 11 | 60d35c45eafb94ad89f924f0e829a54c37d3b5b8 | bigcode/the-stack | train |
0289c4ac542e2c5d1e3d3332 | train | function | def slice4(s):
c = s[0:2]
return c
| def slice4(s):
| c = s[0:2]
return c
| # @desc A slice is inclusive of the starting index and exclusive of the ending index.
def slice4(s):
| 23 | 64 | 18 | 5 | 18 | readingbat/readingbat-python-content | python/string_ops/slice4.py | Python | slice4 | slice4 | 3 | 5 | 3 | 3 | 044adf9ff2ef1794079b3815f7beb081b1f58ea2 | bigcode/the-stack | train |
267878d8a5f83b36793e39d3 | train | function | def main():
print(slice4('Car'))
print(slice4('Truck'))
print(slice4('556843'))
print(slice4('Elephant'))
print(slice4('Roses'))
| def main():
| print(slice4('Car'))
print(slice4('Truck'))
print(slice4('556843'))
print(slice4('Elephant'))
print(slice4('Roses'))
| # @desc A slice is inclusive of the starting index and exclusive of the ending index.
def slice4(s):
c = s[0:2]
return c
def main():
| 39 | 64 | 41 | 3 | 35 | readingbat/readingbat-python-content | python/string_ops/slice4.py | Python | main | main | 8 | 13 | 8 | 8 | 3035835b80740bc857390e7a19b5e7b320501603 | bigcode/the-stack | train |
90c8e4f517a4b87f7fdc8a03 | train | class | class Test(BaseTest):
def test_base(self):
"""
Basic test with exiting Fastcombeat normally
"""
self.render_config_template(
path=os.path.abspath(self.working_dir) + "/log/*"
)
fastcombeat_proc = self.start_beat()
self.wait_until(lambda: self.log... | class Test(BaseTest):
| def test_base(self):
"""
Basic test with exiting Fastcombeat normally
"""
self.render_config_template(
path=os.path.abspath(self.working_dir) + "/log/*"
)
fastcombeat_proc = self.start_beat()
self.wait_until(lambda: self.log_contains("fastcombeat ... | from fastcombeat import BaseTest
import os
class Test(BaseTest):
| 16 | 64 | 95 | 5 | 10 | ctindel/fastcombeat | tests/system/test_base.py | Python | Test | Test | 6 | 19 | 6 | 7 | b68f49ef8537cb6cde562397f0562827efe23c39 | bigcode/the-stack | train |
325b0d632170888b7899ba94 | train | function | def sync(tenant_sessions, logger):
tenant_ds_enabled = []
#Get DS enabled status for all tenants
for session in tenant_sessions:
logger.debug('API - Getting Data Security Enabled Status')
res = session.request('GET', '/api/v1/provision/dlp/status')
info = res.json().get('status')
... | def sync(tenant_sessions, logger):
| tenant_ds_enabled = []
#Get DS enabled status for all tenants
for session in tenant_sessions:
logger.debug('API - Getting Data Security Enabled Status')
res = session.request('GET', '/api/v1/provision/dlp/status')
info = res.json().get('status')
if info:
if info ... | def sync(tenant_sessions, logger):
| 8 | 64 | 188 | 8 | 0 | PaloAltoNetworks/pcs-migration-management | data_security/data_sync.py | Python | sync | sync | 1 | 21 | 1 | 1 | 0077554e2b72ea31e8daeb148f1f5422438ffe86 | bigcode/the-stack | train |
1cccca08d984aab7b05235ba | train | class | class Consulta():
def __init__(self):
def consultar():
pass
area = Tk()
listbox = Listbox(area)
listbox.pack()
listbox.insert(END, "a list entry")
for item in ["one", "two", "three", "four"]:
listbox.insert(END, item)
mainloop()
| class Consulta():
| def __init__(self):
def consultar():
pass
area = Tk()
listbox = Listbox(area)
listbox.pack()
listbox.insert(END, "a list entry")
for item in ["one", "two", "three", "four"]:
listbox.insert(END, item)
mainloop()
| # -*- coding: utf-8 -*-
import tkinter
from tkinter import *
from tkinter import messagebox
from tkinter import filedialog
import os
from os import popen
import subprocess
import time
#Criando classe para executar na celula principal
class Consulta():
| 56 | 64 | 76 | 3 | 52 | gu22/Files_Organizer | Projeto Big Bang/ConsultaBigBang.py | Python | Consulta | Consulta | 16 | 30 | 16 | 16 | 68a28cb5e446946738b74be8c22f67b3e5634a14 | bigcode/the-stack | train |
0765e18729145fc519a98718 | train | function | def im_list_to_blob(ims):
"""Convert a list of images into a network input.
Assumes images are already prepared (means subtracted, BGR order, ...).
"""
max_shape = np.array([im.shape for im in ims]).max(axis=0)
num_images = len(ims)
blob = np.zeros((num_images, max_shape[0], max_shape[1], 3),
... | def im_list_to_blob(ims):
| """Convert a list of images into a network input.
Assumes images are already prepared (means subtracted, BGR order, ...).
"""
max_shape = np.array([im.shape for im in ims]).max(axis=0)
num_images = len(ims)
blob = np.zeros((num_images, max_shape[0], max_shape[1], 3),
dtype=n... | functions."""
import numpy as np
# from scipy.misc import imread, imresize
import cv2
from model.utils.config import cfg
import torch
try:
xrange # Python 2
except NameError:
xrange = range # Python 3
def im_list_to_blob(ims):
| 64 | 64 | 137 | 8 | 55 | xjtAlgo/Visual-Manipulation-Relationship-Network-Pytorch | model/utils/blob.py | Python | im_list_to_blob | im_list_to_blob | 23 | 36 | 23 | 23 | b87d9da5a67527595fc44611df0e8b61e2689d4e | bigcode/the-stack | train |
3d57846519be145813f423f3 | train | function | def prep_im_for_blob(im, target_size, max_size, fix_size = False):
"""Mean subtract and scale an image for use in a blob."""
im = im.astype(np.float32, copy=False)
# im = im[:, :, ::-1]
im_shape = im.shape
im_scale = {}
if not fix_size:
im_size_min = np.min(im_shape[0:2])
im_sca... | def prep_im_for_blob(im, target_size, max_size, fix_size = False):
| """Mean subtract and scale an image for use in a blob."""
im = im.astype(np.float32, copy=False)
# im = im[:, :, ::-1]
im_shape = im.shape
im_scale = {}
if not fix_size:
im_size_min = np.min(im_shape[0:2])
im_scale['x'] = float(target_size) / float(im_size_min)
im_scale[... | , max_shape[0], max_shape[1], 3),
dtype=np.float32)
for i in xrange(num_images):
im = ims[i]
blob[i, 0:im.shape[0], 0:im.shape[1], :] = im
return blob
def prep_im_for_blob(im, target_size, max_size, fix_size = False):
| 80 | 80 | 268 | 18 | 61 | xjtAlgo/Visual-Manipulation-Relationship-Network-Pytorch | model/utils/blob.py | Python | prep_im_for_blob | prep_im_for_blob | 38 | 59 | 38 | 38 | ce0e412d4c26dbe90875616ab26efeb44ff8a8ce | bigcode/the-stack | train |
fe651f67a96dec199cb01416 | train | function | def prepare_data_batch_from_cvimage(cv_img, is_cuda = True):
# BGR to RGB
image = cv_img[:, :, ::-1]
image, im_scale = prep_im_for_blob(image, cfg.SCALES[0], cfg.TRAIN.COMMON.MAX_SIZE)
image = image_normalize(image, mean=cfg.PIXEL_MEANS, std=cfg.PIXEL_STDS)
im_info = np.array(
[image.shape[... | def prepare_data_batch_from_cvimage(cv_img, is_cuda = True):
# BGR to RGB
| image = cv_img[:, :, ::-1]
image, im_scale = prep_im_for_blob(image, cfg.SCALES[0], cfg.TRAIN.COMMON.MAX_SIZE)
image = image_normalize(image, mean=cfg.PIXEL_MEANS, std=cfg.PIXEL_STDS)
im_info = np.array(
[image.shape[0], image.shape[1], im_scale['y'], im_scale['x'], -1],
dtype=np.float3... | 485, 0.456, 0.406), std=(0.229, 0.224, 0.225)):
im = im * (std + 1e-8) + mean
im *= 255.
return im.astype(np.float32)
def prepare_data_batch_from_cvimage(cv_img, is_cuda = True):
# BGR to RGB
| 81 | 81 | 270 | 22 | 59 | xjtAlgo/Visual-Manipulation-Relationship-Network-Pytorch | model/utils/blob.py | Python | prepare_data_batch_from_cvimage | prepare_data_batch_from_cvimage | 71 | 96 | 71 | 72 | 4b1e72b800d827cc9fcf2187bcd7427560f58422 | bigcode/the-stack | train |
07305e4f4f0e10b6ba444bf4 | train | function | def image_unnormalize(im, mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)):
im = im * (std + 1e-8) + mean
im *= 255.
return im.astype(np.float32)
| def image_unnormalize(im, mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)):
| im = im * (std + 1e-8) + mean
im *= 255.
return im.astype(np.float32)
| = (im - mean) / (std + 1e-8)
return im.astype(np.float32)
def image_unnormalize(im, mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)):
| 64 | 64 | 71 | 40 | 24 | xjtAlgo/Visual-Manipulation-Relationship-Network-Pytorch | model/utils/blob.py | Python | image_unnormalize | image_unnormalize | 66 | 69 | 66 | 66 | 18a43e8e5bbd93c468415c2fcf2b592fe9b82a54 | bigcode/the-stack | train |
1ec32fe418721146b7967520 | train | function | def image_normalize(im, mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)):
im /= 255.
im = (im - mean) / (std + 1e-8)
return im.astype(np.float32)
| def image_normalize(im, mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)):
| im /= 255.
im = (im - mean) / (std + 1e-8)
return im.astype(np.float32)
| im_scale['x'], fy=im_scale['y'],
interpolation=cv2.INTER_LINEAR)
return im, im_scale
def image_normalize(im, mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)):
| 64 | 64 | 71 | 38 | 25 | xjtAlgo/Visual-Manipulation-Relationship-Network-Pytorch | model/utils/blob.py | Python | image_normalize | image_normalize | 61 | 64 | 61 | 61 | 58e5c22eb6cd509674d20ae58591a6bea72443d4 | bigcode/the-stack | train |
b0c07830fbf46936d8258209 | train | function | def _apply_log(data, log_changed, log_new):
"""Helper used to set log10/10^ to data in AMRKDTree"""
if not log_changed:
return
if log_new:
np.log10(data, data)
else:
np.power(10.0, data, data)
| def _apply_log(data, log_changed, log_new):
| """Helper used to set log10/10^ to data in AMRKDTree"""
if not log_changed:
return
if log_new:
np.log10(data, data)
else:
np.power(10.0, data, data)
| [1, 0, 0],
[1, 0, 1],
[1, 1, -1],
[1, 1, 0],
[1, 1, 1],
]
)
def _apply_log(data, log_changed, log_new):
| 64 | 64 | 68 | 12 | 52 | evaneschneider/yt | yt/utilities/amr_kdtree/amr_kdtree.py | Python | _apply_log | _apply_log | 53 | 60 | 53 | 53 | 6c8cd0dae3e3d46ecf8b841667bba8d4b7f3ab93 | bigcode/the-stack | train |
1b6b51de9288af0261a181c6 | train | class | class AMRKDTree(ParallelAnalysisInterface):
r"""A KDTree for AMR data.
Not applicable to particle or octree-based datasets.
"""
fields = None
log_fields = None
no_ghost = True
def __init__(self, ds, min_level=None, max_level=None, data_source=None):
if not issubclass(ds.index.__... | class AMRKDTree(ParallelAnalysisInterface):
| r"""A KDTree for AMR data.
Not applicable to particle or octree-based datasets.
"""
fields = None
log_fields = None
no_ghost = True
def __init__(self, ds, min_level=None, max_level=None, data_source=None):
if not issubclass(ds.index.__class__, GridIndex):
raise Runti... | .all(dims > 0)
# print(grid, dims, li, ri)
# Calculate the Volume
vol = self.trunk.kd_sum_volume()
mylog.debug("AMRKDTree volume = %e", vol)
self.trunk.kd_node_check()
def sum_cells(self, all_cells=False):
cells = 0
for node in self.trunk.depth_traverse(... | 256 | 256 | 4,011 | 10 | 245 | evaneschneider/yt | yt/utilities/amr_kdtree/amr_kdtree.py | Python | AMRKDTree | AMRKDTree | 162 | 644 | 162 | 162 | d6ed90cdc32b7f8f64b2be9760032586e31f683d | bigcode/the-stack | train |
fbcd94b00a73e872f1fb9d5a | train | class | class Tree:
def __init__(
self,
ds,
comm_rank=0,
comm_size=1,
left=None,
right=None,
min_level=None,
max_level=None,
data_source=None,
):
self.ds = ds
try:
self._id_offset = ds.index.grids[0]._id_offset
... | class Tree:
| def __init__(
self,
ds,
comm_rank=0,
comm_size=1,
left=None,
right=None,
min_level=None,
max_level=None,
data_source=None,
):
self.ds = ds
try:
self._id_offset = ds.index.grids[0]._id_offset
except Attri... | , -1],
[0, -1, 0],
[0, -1, 1],
[0, 0, -1],
# [ 0, 0, 0],
[0, 0, 1],
[0, 1, -1],
[0, 1, 0],
[0, 1, 1],
[1, -1, -1],
[1, -1, 0],
[1, -1, 1],
[1, 0, -1],
[1, 0, 0],
[1, 0, 1],
[1, 1, -1],
[1, 1... | 252 | 252 | 843 | 3 | 249 | evaneschneider/yt | yt/utilities/amr_kdtree/amr_kdtree.py | Python | Tree | Tree | 63 | 159 | 63 | 63 | a11fd3afa3a1e21b92140b943336ddc919b84e84 | bigcode/the-stack | train |
00299b06243445ef78382c79 | train | class | class MLP(nn.Module):
def __init__(self, in_size=in_size, layer_size=layer_size, layer_num=layer_num, out_size=out_size):
super(MLP, self).__init__()
self.hidden_1 = nn.Linear(in_size, layer_size)
for i in range(layer_num - 1):
self.add_module("hidden_{0}".format(i + 2), nn.Linea... | class MLP(nn.Module):
| def __init__(self, in_size=in_size, layer_size=layer_size, layer_num=layer_num, out_size=out_size):
super(MLP, self).__init__()
self.hidden_1 = nn.Linear(in_size, layer_size)
for i in range(layer_num - 1):
self.add_module("hidden_{0}".format(i + 2), nn.Linear(layer_size, layer_si... | # @Site :
# @File : MLP.py
# @Software: PyCharm
import torch.nn as nn
import torch
in_size = 28 * 28
layer_size = 256
layer_num = 3
out_size = 10
class MLP(nn.Module):
| 64 | 64 | 191 | 6 | 57 | wildkid1024/DNN-optim-tool | nets/MLP.py | Python | MLP | MLP | 18 | 35 | 18 | 18 | 25fd725153fb8391058b7abc946413a533b7ddb8 | bigcode/the-stack | train |
ae8519b4601d7f9c519e493d | train | class | class TimeStampPlugin(service_base.ServicePluginBase,
ts_db.TimeStamp_db_mixin):
"""Implements Neutron Timestamp Service plugin."""
supported_extension_aliases = ['timestamp_core', 'timestamp_ext']
def __init__(self):
super(TimeStampPlugin, self).__init__()
self.regis... | class TimeStampPlugin(service_base.ServicePluginBase,
ts_db.TimeStamp_db_mixin):
| """Implements Neutron Timestamp Service plugin."""
supported_extension_aliases = ['timestamp_core', 'timestamp_ext']
def __init__(self):
super(TimeStampPlugin, self).__init__()
self.register_db_events()
rs_model_maps = {
attributes.NETWORKS: models_v2.Network,
... | .db import db_base_plugin_v2
from neutron.db import l3_db
from neutron.db.models import securitygroup as sg_db
from neutron.db import models_v2
from neutron.extensions import l3
from neutron.extensions import securitygroup as sg
from neutron.objects import base as base_obj
from neutron.services import service_base
from... | 97 | 97 | 326 | 19 | 77 | igor-toga/local-snat | neutron/services/timestamp/timestamp_plugin.py | Python | TimeStampPlugin | TimeStampPlugin | 27 | 62 | 27 | 28 | a50cde80be0245c6b9ed1f2c0b3fae5b6ae345cf | bigcode/the-stack | train |
264dd30bfd50c88d11f03b01 | train | function | def main():
from itertools import accumulate
n, k = map(int, input().split())
p = [int(i) + 1 for i in input().split()]
e = list(accumulate([0] + p))
ans = 0
for j in range(n - k + 1):
ans = max(ans, e[j + k] - e[j])
print(ans / 2)
| def main():
| from itertools import accumulate
n, k = map(int, input().split())
p = [int(i) + 1 for i in input().split()]
e = list(accumulate([0] + p))
ans = 0
for j in range(n - k + 1):
ans = max(ans, e[j + k] - e[j])
print(ans / 2)
| # -*- coding: utf-8 -*-
def main():
| 11 | 64 | 91 | 3 | 8 | KATO-Hiro/AtCoder | ABC/abc151-abc200/abc154/d.py | Python | main | main | 4 | 15 | 4 | 4 | 87c50cb2aaac0eefd10295634fae113acf28ca75 | bigcode/the-stack | train |
da18ae810c84b8807aa3b55f | train | class | class LDAPBackendTest(unittest2.TestCase):
def test_instantaite_no_group_dns_provided(self):
# User is member of two of the groups, but none of them are required
required_group_dns = []
expected_msg = 'One or more user groups must be specified'
self.assertRaisesRegexp(ValueError, ex... | class LDAPBackendTest(unittest2.TestCase):
| def test_instantaite_no_group_dns_provided(self):
# User is member of two of the groups, but none of them are required
required_group_dns = []
expected_msg = 'One or more user groups must be specified'
self.assertRaisesRegexp(ValueError, expected_msg, ldap_backend.LDAPAuthenticationB... | '],
'objectGUID': ['\x1cR\xca\x12\x8a\xda\x8eL\xabe\xcfp\xda\x17H\xf7'],
'primaryGroupID': ['513'],
'pwdLastSet': ['131144314220000000'],
'sAMAccountName': ['tomaz'],
'sAMAccountType': ['805306368'],
'sn': ['Muraus'],
'uSNChanged': ['9835'],
'uSNCreated': ['3550'],
'userAccountContro... | 256 | 256 | 8,329 | 9 | 247 | sagar-orchestral/st2-auth-ldap | tests/unit/test_backend.py | Python | LDAPBackendTest | LDAPBackendTest | 81 | 1,045 | 81 | 82 | 808d6e748d274a8cfe7bdecb8858213466fc4628 | bigcode/the-stack | train |
41c3f81614039481123eec23 | train | class | class WalletNode:
key_config: Dict
config: Dict
constants: ConsensusConstants
server: Optional[WheatServer]
log: logging.Logger
wallet_peers: WalletPeers
# Maintains the state of the wallet (blockchain and transactions), handles DB connections
wallet_state_manager: Optional[WalletStateMa... | class WalletNode:
| key_config: Dict
config: Dict
constants: ConsensusConstants
server: Optional[WheatServer]
log: logging.Logger
wallet_peers: WalletPeers
# Maintains the state of the wallet (blockchain and transactions), handles DB connections
wallet_state_manager: Optional[WalletStateManager]
# How ... | from wheat.types.blockchain_format.sized_bytes import bytes32
from wheat.types.coin_solution import CoinSolution
from wheat.types.header_block import HeaderBlock
from wheat.types.mempool_inclusion_status import MempoolInclusionStatus
from wheat.types.peer_info import PeerInfo
from wheat.util.byte_types import hexstr_to... | 256 | 256 | 8,216 | 4 | 251 | Jsewill/wheat-blockchain | wheat/wallet/wallet_node.py | Python | WalletNode | WalletNode | 58 | 998 | 58 | 58 | 274f1af31c8000cea76535425e6103e72174cf67 | bigcode/the-stack | train |
59508193f638978fae345872 | train | function | def test_mult():
assert mult(2,2)==4 | def test_mult():
| assert mult(2,2)==4 | import pytest
from principal import soma
from principal import mult
def test_soma():
assert soma(2,4)==6
def test_mult():
| 32 | 64 | 13 | 4 | 27 | gabrielMoralles/Travisteste | teste.py | Python | test_mult | test_mult | 10 | 12 | 10 | 11 | c5df4764fc5cd864cced38ce3cad6bad278c8880 | bigcode/the-stack | train |
8e2c6c8454badeda5987e04e | train | function | def test_soma():
assert soma(2,4)==6
| def test_soma():
| assert soma(2,4)==6
| import pytest
from principal import soma
from principal import mult
def test_soma():
| 18 | 64 | 15 | 5 | 12 | gabrielMoralles/Travisteste | teste.py | Python | test_soma | test_soma | 7 | 8 | 7 | 7 | ea7401a19dede1d67a842a36a17ead53d021fae1 | bigcode/the-stack | train |
b3a25a491a077c9515e9d680 | train | class | class TestProperties(KratosUnittest.TestCase):
def test_copy_properties(self):
current_model = KM.Model()
model_part= current_model.CreateModelPart("Main")
model_part.CreateNewProperties(1)
properties = model_part.GetProperties()[1]
properties.SetValue(KM.YOUNG_MODULUS, 1... | class TestProperties(KratosUnittest.TestCase):
| def test_copy_properties(self):
current_model = KM.Model()
model_part= current_model.CreateModelPart("Main")
model_part.CreateNewProperties(1)
properties = model_part.GetProperties()[1]
properties.SetValue(KM.YOUNG_MODULUS, 1.0)
self.assertEqual(properties.GetValue... | import KratosMultiphysics.KratosUnittest as KratosUnittest
import KratosMultiphysics as KM
class TestProperties(KratosUnittest.TestCase):
| 37 | 127 | 424 | 11 | 25 | ma6yu/Kratos | kratos/tests/test_properties.py | Python | TestProperties | TestProperties | 4 | 43 | 4 | 5 | b8353b816d04aa0beb9b8e8796bf18041af3653c | bigcode/the-stack | train |
8365119f15025055e89fe99b | train | function | def evaluate(args, loader, generator, num_samples):
trajs = []
times = []
ade_outer, fde_outer = [], []
total_traj = 0
with torch.no_grad():
for batch in loader:
batch = [tensor.cuda() for tensor in batch]
(obs_traj, pred_traj_gt, obs_traj_rel, pred_traj_gt_rel,
... | def evaluate(args, loader, generator, num_samples):
| trajs = []
times = []
ade_outer, fde_outer = [], []
total_traj = 0
with torch.no_grad():
for batch in loader:
batch = [tensor.cuda() for tensor in batch]
(obs_traj, pred_traj_gt, obs_traj_rel, pred_traj_gt_rel,
non_linear_ped, loss_mask, seq_start_end) = ... | generator.train()
return generator
def evaluate_helper(error, seq_start_end):
sum_ = 0
error = torch.stack(error, dim=1)
for (start, end) in seq_start_end:
start = start.item()
end = end.item()
_error = error[start:end]
_error = torch.sum(_error, dim=0)
_er... | 111 | 112 | 375 | 11 | 100 | LucasPagano/trajectory_cnn | scripts/evaluate_model.py | Python | evaluate | evaluate | 67 | 107 | 67 | 67 | d3efc0a592ec96ef38f70f425fbf22bd5d49fdc8 | bigcode/the-stack | train |
ca3b28e72f7b7013498e0497 | train | function | def get_generator(checkpoint):
args = AttrDict(checkpoint['args'])
generator = TrajectoryGenerator(
obs_len=args.obs_len,
pred_len=args.pred_len,
embedding_dim=args.embedding_dim,
encoder_h_dim=args.encoder_h_dim_g,
decoder_h_dim=args.decoder_h_dim_g,
mlp_dim=args... | def get_generator(checkpoint):
| args = AttrDict(checkpoint['args'])
generator = TrajectoryGenerator(
obs_len=args.obs_len,
pred_len=args.pred_len,
embedding_dim=args.embedding_dim,
encoder_h_dim=args.encoder_h_dim_g,
decoder_h_dim=args.decoder_h_dim_g,
mlp_dim=args.mlp_dim,
num_layers=ar... | get_dset_path
import numpy as np
import time
parser = argparse.ArgumentParser()
parser.add_argument('--model_path', type=str)
parser.add_argument('--num_samples', default=20, type=int)
parser.add_argument('--dset_type', default='test', type=str)
def get_generator(checkpoint):
| 64 | 64 | 185 | 6 | 58 | LucasPagano/trajectory_cnn | scripts/evaluate_model.py | Python | get_generator | get_generator | 27 | 50 | 27 | 27 | 019e06e80baa32cb0001c2f5ccf749b1f26b654a | bigcode/the-stack | train |
9df2f0cdd92076b13dc15297 | train | function | def evaluate_helper(error, seq_start_end):
sum_ = 0
error = torch.stack(error, dim=1)
for (start, end) in seq_start_end:
start = start.item()
end = end.item()
_error = error[start:end]
_error = torch.sum(_error, dim=0)
_error = torch.min(_error)
sum_ += _erro... | def evaluate_helper(error, seq_start_end):
| sum_ = 0
error = torch.stack(error, dim=1)
for (start, end) in seq_start_end:
start = start.item()
end = end.item()
_error = error[start:end]
_error = torch.sum(_error, dim=0)
_error = torch.min(_error)
sum_ += _error
return sum_
| bottleneck_dim=args.bottleneck_dim,
neighborhood_size=args.neighborhood_size,
grid_size=args.grid_size,
batch_norm=args.batch_norm)
generator.load_state_dict(checkpoint['g_state'])
generator.cuda()
generator.train()
return generator
def evaluate_helper(error, seq_start_en... | 64 | 64 | 92 | 9 | 54 | LucasPagano/trajectory_cnn | scripts/evaluate_model.py | Python | evaluate_helper | evaluate_helper | 53 | 64 | 53 | 53 | 8471b339102b872a38e031b2c1cea77a84769d46 | bigcode/the-stack | train |
cdaa32c117db1900ff297150 | train | function | def main(args):
if os.path.isdir(args.model_path):
filenames = os.listdir(args.model_path)
filenames.sort()
paths = [
os.path.join(args.model_path, file_) for file_ in filenames
]
else:
paths = [args.model_path]
for path in paths:
checkpoint = tor... | def main(args):
| if os.path.isdir(args.model_path):
filenames = os.listdir(args.model_path)
filenames.sort()
paths = [
os.path.join(args.model_path, file_) for file_ in filenames
]
else:
paths = [args.model_path]
for path in paths:
checkpoint = torch.load(path)
... | de_sum = evaluate_helper(fde, seq_start_end)
ade_outer.append(ade_sum)
fde_outer.append(fde_sum)
ade = sum(ade_outer) / (total_traj * args.pred_len)
fde = sum(fde_outer) / (total_traj)
return ade, fde, trajs, times
def main(args):
| 78 | 78 | 261 | 4 | 73 | LucasPagano/trajectory_cnn | scripts/evaluate_model.py | Python | main | main | 111 | 136 | 111 | 111 | 4382231fc1eaf648424380a8abb454e6a5dede9f | bigcode/the-stack | train |
7c9de761664bcb1dc050f657 | train | class | class Solution(object):
def canPartition(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
s = sum(nums)
if s%2!=0:
return False
t = s//2
if max(nums)>t:
return False
old = set([0])
for n in nums:
... | class Solution(object):
| def canPartition(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
s = sum(nums)
if s%2!=0:
return False
t = s//2
if max(nums)>t:
return False
old = set([0])
for n in nums:
new = set()
... | class Solution(object):
| 4 | 64 | 135 | 4 | 0 | szhu3210/LeetCode_Solutions | LC/416.py | Python | Solution | Solution | 1 | 26 | 1 | 1 | 778ac4544810cd52ed0bcdd084c65a7f856cda3b | bigcode/the-stack | train |
d8728390aefe785e44ec0981 | train | function | def export():
return thread_delete_middleware
| def export():
| return thread_delete_middleware
|
-------
Tuple[:class:`str`, List[:class:`~pincer.objects.guild.channel.Channel`]]
``on_thread_delete`` and an ``Channel``
"""
return "on_thread_delete", [
Channel.from_dict(construct_client_dict(self, payload.data))
]
def export():
| 63 | 64 | 10 | 3 | 60 | MithicSpirit/Pincer | pincer/middleware/thread_delete.py | Python | export | export | 32 | 33 | 32 | 32 | 7b65b391ede9ac2fa67e2fef8d0cadd96d0d4be1 | bigcode/the-stack | train |
98ccdb104f909879d77c5b38 | train | function | async def thread_delete_middleware(self, payload: GatewayDispatch):
"""|coro|
Middleware for ``on_thread_delete`` event.
Parameters
----------
payload : :class:`GatewayDispatch`
The data received from the thread delete event.
Returns
-------
Tuple[:class:`str`, List[:class:`~p... | async def thread_delete_middleware(self, payload: GatewayDispatch):
| """|coro|
Middleware for ``on_thread_delete`` event.
Parameters
----------
payload : :class:`GatewayDispatch`
The data received from the thread delete event.
Returns
-------
Tuple[:class:`str`, List[:class:`~pincer.objects.guild.channel.Channel`]]
``on_thread_delete`` ... | -Present
# Full MIT License can be found in `LICENSE` at the project root.
"""sent when a thread is deleted"""
from ..core.dispatch import GatewayDispatch
from ..objects import Channel
from ..utils.conversion import construct_client_dict
async def thread_delete_middleware(self, payload: GatewayDispatch):
| 64 | 64 | 115 | 13 | 50 | MithicSpirit/Pincer | pincer/middleware/thread_delete.py | Python | thread_delete_middleware | thread_delete_middleware | 11 | 29 | 11 | 11 | db01f330bcdb8be9824c9e4aa79df43e41ec191b | bigcode/the-stack | train |
83449c3f0ca4ce166d448ec2 | train | class | class Console():
'''the console interface for the subnet calculator'''
EXIT = 'close'
HELP = 'help'
PROMPT = '>>> '
IN_PROMPT = '?> '
ERR_PROMPT = '!> '
OUT_PROMPT = '#> '
def help():
'''print a help message'''
print(Console.PROMPT+'Input an IPv4 network addre... | class Console():
| '''the console interface for the subnet calculator'''
EXIT = 'close'
HELP = 'help'
PROMPT = '>>> '
IN_PROMPT = '?> '
ERR_PROMPT = '!> '
OUT_PROMPT = '#> '
def help():
'''print a help message'''
print(Console.PROMPT+'Input an IPv4 network address with a slash no... | from subnetter import SubnetterV4
from subnet import SubnetV4
class Console():
| 21 | 209 | 697 | 3 | 17 | dGameBoy101b/subnet-calculator | console.py | Python | Console | Console | 4 | 80 | 4 | 4 | da49250474f0385144bb32a4825c9109fd796bbd | bigcode/the-stack | train |
d1912a4e99b7c86319d30931 | train | function | def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'device_notification_subsystem.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are y... | def main():
| """Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'device_notification_subsystem.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's... | ; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""
import os
import sys
def main():
| 64 | 64 | 101 | 3 | 60 | CACF/Notification-Subsystem | manage.py | Python | main | main | 36 | 47 | 36 | 36 | 0943e22dd0a52d3863910278b6e82a6e3e802b33 | bigcode/the-stack | train |
ca5178f67d9e69ea5168d546 | train | function | def TwoPeriodSunnyTimes(constant,delta,slope,slopedir,lat):
# First derive A1 and A2 from the normal procedure
A1,A2 = SunHours(delta,slope,slopedir,lat)
# Then calculate the other two functions.
# Initialize function
a,b,c = Constants(delta,slope,slopedir,lat)
riseSlope, setSl... | def TwoPeriodSunnyTimes(constant,delta,slope,slopedir,lat):
# First derive A1 and A2 from the normal procedure
| A1,A2 = SunHours(delta,slope,slopedir,lat)
# Then calculate the other two functions.
# Initialize function
a,b,c = Constants(delta,slope,slopedir,lat)
riseSlope, setSlope = BoundsSlope(a,b,c)
B1 = np.maximum(riseSlope,setSlope)
B2 = np.minimum(riseSlope,setSlope)
... | ,lat):
# Initialize function
sunrise,sunset = SunHours(delta,slope,slopedir,lat)
# Finally calculate resulting values
Vals = IntegrateSlope(constant,sunrise,sunset,delta,slope,slopedir,lat)
return(Vals)
def TwoPeriodSunnyTimes(constant,delta,slope,slopedir,lat):
# First derive A1... | 96 | 96 | 320 | 32 | 64 | ElgaSalvadore/watools | Products/ETref/SlopeInfluence_ETref.py | Python | TwoPeriodSunnyTimes | TwoPeriodSunnyTimes | 256 | 280 | 256 | 257 | d13c62f35fd885c8801e1009c2b0af95dd654ccf | bigcode/the-stack | train |
cdbc04e7f280384943ad895b | train | function | def Table1b(w1,w2,w1b,w2b):
f1 = np.sin(w2b) - np.sin(w1) + np.sin(w2) - np.sin(w1b)
f2 = np.cos(w2b) - np.cos(w1) + np.cos(w2) - np.cos(w1b)
f3 = w2b - w1 + w2 - w1b
f4 = np.sin(2*w2b) - np.sin(2*w1) + np.sin(2*w2) - np.sin(2*w1b)
f5 = np.sin(w2b)**2 - np.sin(w1)**2 + np.sin(w2)**2 - np.sin(w1b)**2... | def Table1b(w1,w2,w1b,w2b):
| f1 = np.sin(w2b) - np.sin(w1) + np.sin(w2) - np.sin(w1b)
f2 = np.cos(w2b) - np.cos(w1) + np.cos(w2) - np.cos(w1b)
f3 = w2b - w1 + w2 - w1b
f4 = np.sin(2*w2b) - np.sin(2*w1) + np.sin(2*w2) - np.sin(2*w1b)
f5 = np.sin(w2b)**2 - np.sin(w1)**2 + np.sin(w2)**2 - np.sin(w1b)**2
return f1, f2, f3, f4, ... | *sunset) - np.sin(2*sunrise)
f5 = np.sin(sunset)**2 - np.sin(sunrise)**2
return f1, f2, f3, f4, f5
def Table1b(w1,w2,w1b,w2b):
| 64 | 64 | 179 | 15 | 48 | ElgaSalvadore/watools | Products/ETref/SlopeInfluence_ETref.py | Python | Table1b | Table1b | 162 | 168 | 162 | 162 | 37d3c233b36a314a6f3ba28a1a60a33cf9ebf092 | bigcode/the-stack | train |
9334baef62ef7903b6bade1e | train | function | def Table2(delta,lat,slope,slopedir):
a = np.sin(delta)*np.cos(lat)*np.sin(slope)*np.cos(slopedir) - np.sin(delta)*np.sin(lat)*np.cos(slope)
b = np.cos(delta)*np.cos(lat)*np.cos(slope) + np.cos(delta)*np.sin(lat)*np.sin(slope)*np.cos(slopedir)
c = np.cos(delta)*np.sin(slopedir)*np.sin(slope)
g = np.sin(... | def Table2(delta,lat,slope,slopedir):
| a = np.sin(delta)*np.cos(lat)*np.sin(slope)*np.cos(slopedir) - np.sin(delta)*np.sin(lat)*np.cos(slope)
b = np.cos(delta)*np.cos(lat)*np.cos(slope) + np.cos(delta)*np.sin(lat)*np.sin(slope)*np.cos(slopedir)
c = np.cos(delta)*np.sin(slopedir)*np.sin(slope)
g = np.sin(delta)*np.sin(lat)
h = np.cos(delt... | f5 = np.sin(w2b)**2 - np.sin(w1)**2 + np.sin(w2)**2 - np.sin(w1b)**2
return f1, f2, f3, f4, f5
def Table2(delta,lat,slope,slopedir):
| 64 | 64 | 134 | 13 | 50 | ElgaSalvadore/watools | Products/ETref/SlopeInfluence_ETref.py | Python | Table2 | Table2 | 170 | 177 | 170 | 170 | 337e3f24ceb4823d5639b3e5ba4a1be4c5012cb8 | bigcode/the-stack | train |
01f414fcedebd288745f1acd | train | function | def IntegrateNormal(constant,sunrise,sunset):
integral = constant * (sunset - sunrise)
return(integral)
| def IntegrateNormal(constant,sunrise,sunset):
| integral = constant * (sunset - sunrise)
return(integral)
| (ws))
# integral = constant * (np.sin(delta)*np.sin(lat)*(sunset-sunrise)
# + np.cos(delta)*np.cos(lat)*(np.sin(sunset)-np.sin(sunrise)))
return(integral)
def IntegrateNormal(constant,sunrise,sunset):
| 64 | 64 | 29 | 12 | 52 | ElgaSalvadore/watools | Products/ETref/SlopeInfluence_ETref.py | Python | IntegrateNormal | IntegrateNormal | 368 | 370 | 368 | 368 | 44b6ed93b6146c46f43284731dedfb3eb24294d2 | bigcode/the-stack | train |
98e2ee40c3e7acfd44a29465 | train | function | def TwoPeriods(delta,slope,lat):
# Equation 7
TwoPeriod = (np.sin(slope) > np.ones(slope.shape)*np.sin(lat)*np.cos(delta)+np.cos(lat)*np.sin(delta))
return(TwoPeriod)
| def TwoPeriods(delta,slope,lat):
# Equation 7
| TwoPeriod = (np.sin(slope) > np.ones(slope.shape)*np.sin(lat)*np.cos(delta)+np.cos(lat)*np.sin(delta))
return(TwoPeriod)
| ] = -1; sinA[sinA > 1] = 1
sunrise = np.arcsin(sinA)
sunset = np.arcsin(sinB)
return(sunrise,sunset)
def TwoPeriods(delta,slope,lat):
# Equation 7
| 63 | 64 | 54 | 15 | 48 | ElgaSalvadore/watools | Products/ETref/SlopeInfluence_ETref.py | Python | TwoPeriods | TwoPeriods | 345 | 348 | 345 | 346 | 465a21f3c59d2959b8932a38f62479a167fc5498 | bigcode/the-stack | train |
ce80870d46762aea475dd484 | train | function | def Table1a(sunrise,sunset):
f1 = np.sin(sunset) - np.sin(sunrise)
f2 = np.cos(sunset) - np.cos(sunrise)
f3 = sunset - sunrise
f4 = np.sin(2*sunset) - np.sin(2*sunrise)
f5 = np.sin(sunset)**2 - np.sin(sunrise)**2
return f1, f2, f3, f4, f5
| def Table1a(sunrise,sunset):
| f1 = np.sin(sunset) - np.sin(sunrise)
f2 = np.cos(sunset) - np.cos(sunrise)
f3 = sunset - sunrise
f4 = np.sin(2*sunset) - np.sin(2*sunrise)
f5 = np.sin(sunset)**2 - np.sin(sunrise)**2
return f1, f2, f3, f4, f5
| .75 + 0.25*np.cos(slope) - (0.5*slope/np.pi)
return(Horizontal,Sloping, sinb, sinb_hor, fi, slope, np.where(np.ravel(TwoPeriod == True)))
def Table1a(sunrise,sunset):
| 64 | 64 | 107 | 10 | 54 | ElgaSalvadore/watools | Products/ETref/SlopeInfluence_ETref.py | Python | Table1a | Table1a | 154 | 160 | 154 | 154 | 168fb04403a86a89e02e62af0276c2a29852c831 | bigcode/the-stack | train |
d04735a921c2b42310d1ceb6 | train | function | def BoundsHorizontal(delta,lat):
# This function calculates sunrise hours based on earth inclination and latitude
# If there is no sunset or sunrise hours the values are either set to 0 (polar night)
# or pi (polar day)
bound = np.arccos(-np.tan(delta)*np.tan(lat))
bound[abs(delta+lat) > (np.pi/... | def BoundsHorizontal(delta,lat):
# This function calculates sunrise hours based on earth inclination and latitude
# If there is no sunset or sunrise hours the values are either set to 0 (polar night)
# or pi (polar day)
| bound = np.arccos(-np.tan(delta)*np.tan(lat))
bound[abs(delta+lat) > (np.pi/2)] = np.pi
bound[abs(delta-lat) > (np.pi/2)] = 0
return(bound)
| )*np.sin(delta))
return(TwoPeriod)
def BoundsHorizontal(delta,lat):
# This function calculates sunrise hours based on earth inclination and latitude
# If there is no sunset or sunrise hours the values are either set to 0 (polar night)
# or pi (polar day)
| 63 | 64 | 112 | 52 | 11 | ElgaSalvadore/watools | Products/ETref/SlopeInfluence_ETref.py | Python | BoundsHorizontal | BoundsHorizontal | 350 | 358 | 350 | 353 | a70fb5c7e4feb288fcbe86497e4942849e405648 | bigcode/the-stack | train |
cdb659fe12abfe22373a3f0d | train | function | def SunHours(delta,slope,slopedir,lat):
# Define sun hours in case of one sunlight period
a,b,c = Constants(delta,slope,slopedir,lat)
riseSlope, setSlope = BoundsSlope(a,b,c)
bound = BoundsHorizontal(delta,lat)
Calculated = np.zeros(slope.shape, dtype = bool)
RiseFinal = np.zeros(s... | def SunHours(delta,slope,slopedir,lat):
# Define sun hours in case of one sunlight period
| a,b,c = Constants(delta,slope,slopedir,lat)
riseSlope, setSlope = BoundsSlope(a,b,c)
bound = BoundsHorizontal(delta,lat)
Calculated = np.zeros(slope.shape, dtype = bool)
RiseFinal = np.zeros(slope.shape)
SetFinal = np.zeros(slope.shape)
# First check sunrise is not nan
... | 1 + w2 - w1b
f4 = np.sin(2*w2b) - np.sin(2*w1) + np.sin(2*w2) - np.sin(2*w1b)
f5 = np.sin(w2b)**2 - np.sin(w1)**2 + np.sin(w2)**2 - np.sin(w1b)**2
return f1, f2, f3, f4, f5
def Table2(delta,lat,slope,slopedir):
a = np.sin(delta)*np.cos(lat)*np.sin(slope)*np.cos(slopedir) - np.sin(delta)*np.sin(lat)*np.... | 256 | 256 | 878 | 25 | 230 | ElgaSalvadore/watools | Products/ETref/SlopeInfluence_ETref.py | Python | SunHours | SunHours | 179 | 245 | 179 | 181 | 702ac1997508c337777e8bf577bb77d8aa2f0009 | bigcode/the-stack | train |
e1504f33bd69b9773e2897a5 | train | function | def BoundsSlope(a,b,c):
#Equation 13
Div = (b**2+c**2)
Div[Div <= 0] = 0.00001
sinB = (a*c + b*np.sqrt(b**2+c**2-a**2))/ Div
sinA = (a*c - b*np.sqrt(b**2+c**2-a**2))/ Div
sinB[sinB < -1] = -1; sinB[sinB > 1] = 1
sinA[sinA < -1] = -1; sinA[sinA > 1] = 1
sunrise = np.arcsin(si... | def BoundsSlope(a,b,c):
#Equation 13
| Div = (b**2+c**2)
Div[Div <= 0] = 0.00001
sinB = (a*c + b*np.sqrt(b**2+c**2-a**2))/ Div
sinA = (a*c - b*np.sqrt(b**2+c**2-a**2))/ Div
sinB[sinB < -1] = -1; sinB[sinB > 1] = 1
sinA[sinA < -1] = -1; sinA[sinA > 1] = 1
sunrise = np.arcsin(sinA)
sunset = np.arcsin(sinB)
retu... | b*np.cos(time) + c*np.sin(time)
return(angle)
def AngleHorizontal(delta,lat,time):
angle = np.sin(delta)*np.sin(lat)+np.cos(delta)*np.cos(lat)*np.cos(time)
return(angle)
def BoundsSlope(a,b,c):
#Equation 13
| 64 | 64 | 170 | 13 | 51 | ElgaSalvadore/watools | Products/ETref/SlopeInfluence_ETref.py | Python | BoundsSlope | BoundsSlope | 331 | 343 | 331 | 332 | 950023fe34f247d5965437f1aecb703310e7a019 | bigcode/the-stack | train |
3d1f214347ba3190cb950b14 | train | function | def AngleSlope(a,b,c,time):
angle = -a + b*np.cos(time) + c*np.sin(time)
return(angle)
| def AngleSlope(a,b,c,time):
| angle = -a + b*np.cos(time) + c*np.sin(time)
return(angle)
| .cos(delta)*np.cos(lat)*np.cos(slope) + np.cos(delta)*np.sin(lat)*np.sin(slope)*np.cos(slopedir)
c = np.cos(delta)*np.sin(slope)*np.sin(slopedir)
return(a,b,c)
def AngleSlope(a,b,c,time):
| 64 | 64 | 29 | 8 | 56 | ElgaSalvadore/watools | Products/ETref/SlopeInfluence_ETref.py | Python | AngleSlope | AngleSlope | 323 | 325 | 323 | 323 | 2320fab4410a953772476fa59d791994b5a58f0d | bigcode/the-stack | train |
b447326a99f363414cac9c6b | train | function | def IntegrateHorizontal(constant,sunrise,sunset,delta,lat):
# Equation 4 & 6
ws = np.arccos(-np.tan(delta)*np.tan(lat))
integral = constant * (np.sin(delta)*np.sin(lat)*ws + np.cos(delta)*np.cos(lat)*np.sin(ws))
# integral = constant * (np.sin(delta)*np.sin(lat)*(sunset-sunrise)
# + np.co... | def IntegrateHorizontal(constant,sunrise,sunset,delta,lat):
# Equation 4 & 6
| ws = np.arccos(-np.tan(delta)*np.tan(lat))
integral = constant * (np.sin(delta)*np.sin(lat)*ws + np.cos(delta)*np.cos(lat)*np.sin(ws))
# integral = constant * (np.sin(delta)*np.sin(lat)*(sunset-sunrise)
# + np.cos(delta)*np.cos(lat)*(np.sin(sunset)-np.sin(sunrise)))
return(integral)
| abs(delta+lat) > (np.pi/2)] = np.pi
bound[abs(delta-lat) > (np.pi/2)] = 0
return(bound)
def IntegrateHorizontal(constant,sunrise,sunset,delta,lat):
# Equation 4 & 6
| 64 | 64 | 121 | 25 | 39 | ElgaSalvadore/watools | Products/ETref/SlopeInfluence_ETref.py | Python | IntegrateHorizontal | IntegrateHorizontal | 360 | 366 | 360 | 361 | 54e01f8072dae2e2502bd9884f2e2fb24779cc40 | bigcode/the-stack | train |
58ad67c1370d9ae8635442a9 | train | function | def IntegrateSlope(constant,sunrise,sunset,delta,slope,slopedir,lat):
# Equation 5 & 6
integral = constant * (np.sin(delta)*np.sin(lat)*np.cos(slope)*(sunset-sunrise)
- np.sin(delta)*np.cos(lat)*np.sin(slope)*np.cos(slopedir)*(sunset-sunrise)
+ np.cos(delta)*np.cos(lat)*np.cos(s... | def IntegrateSlope(constant,sunrise,sunset,delta,slope,slopedir,lat):
# Equation 5 & 6
| integral = constant * (np.sin(delta)*np.sin(lat)*np.cos(slope)*(sunset-sunrise)
- np.sin(delta)*np.cos(lat)*np.sin(slope)*np.cos(slopedir)*(sunset-sunrise)
+ np.cos(delta)*np.cos(lat)*np.cos(slope)*(np.sin(sunset)-np.sin(sunrise))
+ np.cos(delta)*np.sin(lat)*np.sin(s... | (integral)
def IntegrateNormal(constant,sunrise,sunset):
integral = constant * (sunset - sunrise)
return(integral)
def IntegrateSlope(constant,sunrise,sunset,delta,slope,slopedir,lat):
# Equation 5 & 6
| 64 | 64 | 176 | 31 | 33 | ElgaSalvadore/watools | Products/ETref/SlopeInfluence_ETref.py | Python | IntegrateSlope | IntegrateSlope | 372 | 379 | 372 | 373 | 9badbf5189f2a3aa3edc7daf7fdc3ccd34b83829 | bigcode/the-stack | train |
c5bb0e4b003ade00258ff432 | train | function | def TwoPeriodSun(constant,delta,slope,slopedir,lat):
# First derive A1 and A2 from the normal procedure
A1,A2 = SunHours(delta,slope,slopedir,lat)
# Then calculate the other two functions.
# Initialize function
a,b,c = Constants(delta,slope,slopedir,lat)
riseSlope, setSlope = B... | def TwoPeriodSun(constant,delta,slope,slopedir,lat):
# First derive A1 and A2 from the normal procedure
| A1,A2 = SunHours(delta,slope,slopedir,lat)
# Then calculate the other two functions.
# Initialize function
a,b,c = Constants(delta,slope,slopedir,lat)
riseSlope, setSlope = BoundsSlope(a,b,c)
B1 = np.maximum(riseSlope,setSlope)
B2 = np.minimum(riseSlope,setSlope)
... | (Angle_B2) > 0.001]
# Check if two periods really exist
ID = np.ravel_multi_index(np.where(np.logical_and(B2 >= A1, B1 <= A2) == True),a.shape)
Val = IntegrateSlope(constant,B2.flat[ID],B1.flat[ID],delta,slope.flat[ID],slopedir.flat[ID],lat.flat[ID])
ID = ID[Val < 0]
return A1,A2,B1,B2... | 144 | 144 | 480 | 31 | 112 | ElgaSalvadore/watools | Products/ETref/SlopeInfluence_ETref.py | Python | TwoPeriodSun | TwoPeriodSun | 282 | 314 | 282 | 283 | a83d0e0d878bb6aca18d25b8184507c673c64554 | bigcode/the-stack | train |
d444ab6f892deab478743f44 | train | function | def Constants(delta,slope,slopedir,lat):
# Equation 11
a = np.sin(delta)*np.cos(lat)*np.sin(slope)*np.cos(slopedir) - np.sin(delta)*np.sin(lat)*np.cos(slope)
b = np.cos(delta)*np.cos(lat)*np.cos(slope) + np.cos(delta)*np.sin(lat)*np.sin(slope)*np.cos(slopedir)
c = np.cos(delta)*np.sin(slope)*np.sin(slop... | def Constants(delta,slope,slopedir,lat):
# Equation 11
| a = np.sin(delta)*np.cos(lat)*np.sin(slope)*np.cos(slopedir) - np.sin(delta)*np.sin(lat)*np.cos(slope)
b = np.cos(delta)*np.cos(lat)*np.cos(slope) + np.cos(delta)*np.sin(lat)*np.sin(slope)*np.cos(slopedir)
c = np.cos(delta)*np.sin(slope)*np.sin(slopedir)
return(a,b,c)
| [ID] = IntegrateSlope(constant,A1.flat[ID],A2.flat[ID],delta,slope.flat[ID],slopedir.flat[ID],lat.flat[ID])
return(Vals)
def Constants(delta,slope,slopedir,lat):
# Equation 11
| 64 | 64 | 114 | 18 | 46 | ElgaSalvadore/watools | Products/ETref/SlopeInfluence_ETref.py | Python | Constants | Constants | 316 | 321 | 316 | 317 | d8dcc099f3d54f1f5e2e8cd583cb03e1a5f45bc6 | bigcode/the-stack | train |
c4af0da1ed73c5f855f5467e | train | function | def OnePeriodSun(constant,delta,slope,slopedir,lat):
# Initialize function
sunrise,sunset = SunHours(delta,slope,slopedir,lat)
# Finally calculate resulting values
Vals = IntegrateSlope(constant,sunrise,sunset,delta,slope,slopedir,lat)
return(Vals)
| def OnePeriodSun(constant,delta,slope,slopedir,lat):
# Initialize function
| sunrise,sunset = SunHours(delta,slope,slopedir,lat)
# Finally calculate resulting values
Vals = IntegrateSlope(constant,sunrise,sunset,delta,slope,slopedir,lat)
return(Vals)
| sunlight during the day
SetFinal[SetFinal <= RiseFinal] = 0
RiseFinal[SetFinal <= RiseFinal] = 0
return(RiseFinal,SetFinal)
def OnePeriodSun(constant,delta,slope,slopedir,lat):
# Initialize function
| 64 | 64 | 78 | 22 | 42 | ElgaSalvadore/watools | Products/ETref/SlopeInfluence_ETref.py | Python | OnePeriodSun | OnePeriodSun | 247 | 254 | 247 | 248 | 33e2f686b162871fd5da866709b3bb545637e9de | bigcode/the-stack | train |
983ea153cf4a86098b386428 | train | function | def SlopeInfluence(DEMmap,latitude,longitude,day):
'''
This function corrects the solar radiation for the sloping terrain.
All the formulas are based on Allen (2006)
DEMmap -- path to the DEM map
latitude -- numpy array with the latitude
longitude -- numpy array with the longitude
day --... | def SlopeInfluence(DEMmap,latitude,longitude,day):
| '''
This function corrects the solar radiation for the sloping terrain.
All the formulas are based on Allen (2006)
DEMmap -- path to the DEM map
latitude -- numpy array with the latitude
longitude -- numpy array with the longitude
day -- Day of the year
'''
# This model calculate... | # -*- coding: utf-8 -*-
'''
Authors: Bert Coerver, Gert Mulder, Tim Hessels
UNESCO-IHE 2016
Contact: b.coerver@unesco-ihe.org
t.hessels@unesco-ihe.org
Repository: https://github.com/wateraccounting/wa
Module: Products/ETref
'''
from __future__ import division
# import general python modules
import num... | 111 | 256 | 1,932 | 16 | 94 | ElgaSalvadore/watools | Products/ETref/SlopeInfluence_ETref.py | Python | SlopeInfluence | SlopeInfluence | 14 | 152 | 14 | 15 | 52166626f990110d996c3a506376264890046fe4 | bigcode/the-stack | train |
f0730f8c72c896d93d6fa8f4 | train | function | def AngleHorizontal(delta,lat,time):
angle = np.sin(delta)*np.sin(lat)+np.cos(delta)*np.cos(lat)*np.cos(time)
return(angle)
| def AngleHorizontal(delta,lat,time):
| angle = np.sin(delta)*np.sin(lat)+np.cos(delta)*np.cos(lat)*np.cos(time)
return(angle)
| ir)
c = np.cos(delta)*np.sin(slope)*np.sin(slopedir)
return(a,b,c)
def AngleSlope(a,b,c,time):
angle = -a + b*np.cos(time) + c*np.sin(time)
return(angle)
def AngleHorizontal(delta,lat,time):
| 63 | 64 | 35 | 8 | 55 | ElgaSalvadore/watools | Products/ETref/SlopeInfluence_ETref.py | Python | AngleHorizontal | AngleHorizontal | 327 | 329 | 327 | 327 | 0b5f5eb4ca7ba0687a0937c7bd612b665efcaadf | bigcode/the-stack | train |
0323454637311a223020651b | train | function | def spanify(f):
"""A decorator which attaches span information
to the value returned by calling `f`.
Intended for use with the below AST visiting
methods. The idea is that after we do the work
of constructing the AST we attach Span information.
"""
def _wrapper(*args, **kwargs)... | def spanify(f):
| """A decorator which attaches span information
to the value returned by calling `f`.
Intended for use with the below AST visiting
methods. The idea is that after we do the work
of constructing the AST we attach Span information.
"""
def _wrapper(*args, **kwargs):
# Assu... | opes, name):
# type: (Scopes[T], str) -> Optional[T]
"""Look up `name` in `scopes`."""
for scope in scopes:
for key, val in scope:
if key == name:
return val
return None
def spanify(f):
| 64 | 64 | 164 | 5 | 58 | mostafaelhoushi/tvm | python/tvm/relay/_parser.py | Python | spanify | spanify | 83 | 102 | 83 | 83 | 17bcf65e47d9ddeaee47e0a90d83efc2dadf244b | bigcode/the-stack | train |
e66b670725a701354b56b11f | train | function | def fromtext(data, source_name=None):
# type: (str, str) -> Union[expr.Expr, module.Module]
"""Parse a Relay program."""
if data == "":
raise ParseError("Cannot parse the empty string.")
global __source_name_counter__
if source_name is None:
source_name = "source_file{0}".format(__... | def fromtext(data, source_name=None):
# type: (str, str) -> Union[expr.Expr, module.Module]
| """Parse a Relay program."""
if data == "":
raise ParseError("Cannot parse the empty string.")
global __source_name_counter__
if source_name is None:
source_name = "source_file{0}".format(__source_name_counter__)
if isinstance(source_name, str):
source_name = SourceName(so... | Stream(data)
lexer = RelayLexer(input_stream)
token_stream = CommonTokenStream(lexer)
return RelayParser(token_stream)
__source_name_counter__ = 0
def fromtext(data, source_name=None):
# type: (str, str) -> Union[expr.Expr, module.Module]
| 64 | 64 | 119 | 27 | 36 | mostafaelhoushi/tvm | python/tvm/relay/_parser.py | Python | fromtext | fromtext | 512 | 527 | 512 | 513 | c989ff17ec429dd10e718284b050508a012852d4 | bigcode/the-stack | train |
d9ec493c0cc7031389d649a9 | train | function | def make_parser(data):
# type: (str) -> RelayParser
"""Construct a RelayParser a given data stream."""
input_stream = InputStream(data)
lexer = RelayLexer(input_stream)
token_stream = CommonTokenStream(lexer)
return RelayParser(token_stream)
| def make_parser(data):
# type: (str) -> RelayParser
| """Construct a RelayParser a given data stream."""
input_stream = InputStream(data)
lexer = RelayLexer(input_stream)
token_stream = CommonTokenStream(lexer)
return RelayParser(token_stream)
| TypeContext) -> ty.FuncType
types = self.visit_list(ctx.type_())
arg_types = types[:-1]
ret_type = types[-1]
return ty.FuncType(arg_types, ret_type, [], None)
def make_parser(data):
# type: (str) -> RelayParser
| 64 | 64 | 60 | 16 | 48 | mostafaelhoushi/tvm | python/tvm/relay/_parser.py | Python | make_parser | make_parser | 502 | 508 | 502 | 503 | c5408d94b9ac8ce2aac33268364c319e45ba976b | bigcode/the-stack | train |
453146d2361de11c7d5eb530 | train | class | class ParseError(Exception):
"""Exception type for parse errors."""
def __init__(self, message):
# type: (str) -> None
super(ParseError, self).__init__()
self.message = message
| class ParseError(Exception):
| """Exception type for parse errors."""
def __init__(self, message):
# type: (str) -> None
super(ParseError, self).__init__()
self.message = message
| from typing import TypeVar, Deque, Tuple, Optional, Union, NamedTuple, List, Callable, Any, Dict
import tvm
from . import module
from .base import Span, SourceName
from . import expr
from . import ty
from . import op
class ParseError(Exception):
| 64 | 64 | 47 | 5 | 58 | mostafaelhoushi/tvm | python/tvm/relay/_parser.py | Python | ParseError | ParseError | 20 | 26 | 20 | 20 | ce1c7f6d4c0b61be5c068311975d438542ca263d | bigcode/the-stack | train |
0c7c680d17553b7defb2c9a4 | train | class | class ParseTreeToRelayIR(RelayVisitor):
"""Parse Relay text format into Relay IR."""
def __init__(self, source_name):
# type: (str) -> None
self.source_name = source_name
self.module = module.Module({}) # type: module.Module
# Adding an empty scope allows naked lets without p... | class ParseTreeToRelayIR(RelayVisitor):
| """Parse Relay text format into Relay IR."""
def __init__(self, source_name):
# type: (str) -> None
self.source_name = source_name
self.module = module.Module({}) # type: module.Module
# Adding an empty scope allows naked lets without pain.
self.var_scopes = deque([de... | str) -> Optional[T]
"""Look up `name` in `scopes`."""
for scope in scopes:
for key, val in scope:
if key == name:
return val
return None
def spanify(f):
"""A decorator which attaches span information
to the value returned by calling `f`.
Intended for... | 256 | 256 | 3,131 | 10 | 245 | mostafaelhoushi/tvm | python/tvm/relay/_parser.py | Python | ParseTreeToRelayIR | ParseTreeToRelayIR | 106 | 500 | 106 | 106 | 64c10b1cca6dc7847c3376f105934e46332d33a2 | bigcode/the-stack | train |
0bc3ddfa16accee56aac0459 | train | function | def lookup(scopes, name):
# type: (Scopes[T], str) -> Optional[T]
"""Look up `name` in `scopes`."""
for scope in scopes:
for key, val in scope:
if key == name:
return val
return None
| def lookup(scopes, name):
# type: (Scopes[T], str) -> Optional[T]
| """Look up `name` in `scopes`."""
for scope in scopes:
for key, val in scope:
if key == name:
return val
return None
| [
"int",
"uint",
"float",
"bool",
]
T = TypeVar("T")
Scope = Deque[Tuple[str, T]]
Scopes = Deque[Scope[T]]
def lookup(scopes, name):
# type: (Scopes[T], str) -> Optional[T]
| 64 | 64 | 62 | 21 | 43 | mostafaelhoushi/tvm | python/tvm/relay/_parser.py | Python | lookup | lookup | 73 | 81 | 73 | 74 | 21bfe28fc8028d48a0f50438f45b22764e12e19e | bigcode/the-stack | train |
754c7e18ad8e0dd429b37ebc | train | function | def ogr_ods_4():
drv = ogr.GetDriverByName('ODS')
if drv is None:
return 'skip'
import test_cli_utilities
if test_cli_utilities.get_test_ogrsf_path() is None:
return 'skip'
ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro data/test.ods')
if ret.find... | def ogr_ods_4():
| drv = ogr.GetDriverByName('ODS')
if drv is None:
return 'skip'
import test_cli_utilities
if test_cli_utilities.get_test_ogrsf_path() is None:
return 'skip'
ret = gdaltest.runexternal(test_cli_utilities.get_test_ogrsf_path() + ' -ro data/test.ods')
if ret.find('INFO') == -1 or ... | n(1).GetType() != ogr.OFTString:
gdaltest.post_reason('fail')
return 'fail'
gdal.SetConfigOption('OGR_ODS_FIELD_TYPES', None)
return 'success'
###############################################################################
# Run test_ogrsf
def ogr_ods_4():
| 64 | 64 | 121 | 7 | 56 | chambbj/gdal | autotest/ogr/ogr_ods.py | Python | ogr_ods_4 | ogr_ods_4 | 292 | 308 | 292 | 293 | 0df86cbaf5bc7b11e8b3b355c2aea09c86bb28b8 | bigcode/the-stack | train |
ba83b8ee464383962ba370e8 | train | function | def ogr_ods_kspread_1():
drv = ogr.GetDriverByName('ODS')
if drv is None:
return 'skip'
if drv.TestCapability("foo") != 0:
gdaltest.post_reason('fail')
return 'fail'
ds = ogr.Open('data/test_kspread.ods')
if ds is None:
gdaltest.post_reason('cannot open dataset')
... | def ogr_ods_kspread_1():
| drv = ogr.GetDriverByName('ODS')
if drv is None:
return 'skip'
if drv.TestCapability("foo") != 0:
gdaltest.post_reason('fail')
return 'fail'
ds = ogr.Open('data/test_kspread.ods')
if ds is None:
gdaltest.post_reason('cannot open dataset')
return 'fail'
... | '2012/01/22' or \
feat.GetFieldAsString(5) != '2012/01/22 18:49:00':
gdaltest.post_reason('fail')
feat.DumpReadable()
return 'fail'
feat = lyr.GetNextFeature()
if feat.IsFieldSet(2):
gdaltest.post_reason('fail')
feat.DumpReadable()
return 'fail'
retu... | 213 | 213 | 711 | 9 | 203 | chambbj/gdal | autotest/ogr/ogr_ods.py | Python | ogr_ods_kspread_1 | ogr_ods_kspread_1 | 150 | 242 | 150 | 151 | 5770afd49296923ae2cc2d6bb4b8757d6c78b8dc | bigcode/the-stack | train |
e267c30bb7288f2f24b70770 | train | function | def ogr_ods_3():
drv = ogr.GetDriverByName('ODS')
if drv is None:
return 'skip'
gdal.SetConfigOption('OGR_ODS_FIELD_TYPES', 'STRING')
ds = ogr.Open('data/test.ods')
lyr = ds.GetLayerByName('Feuille7')
if lyr.GetLayerDefn().GetFieldDefn(1).GetType() != ogr.OFTString:
gdaltest.... | def ogr_ods_3():
| drv = ogr.GetDriverByName('ODS')
if drv is None:
return 'skip'
gdal.SetConfigOption('OGR_ODS_FIELD_TYPES', 'STRING')
ds = ogr.Open('data/test.ods')
lyr = ds.GetLayerByName('Feuille7')
if lyr.GetLayerDefn().GetFieldDefn(1).GetType() != ogr.OFTString:
gdaltest.post_reason('fail'... | 3:
gdaltest.post_reason('fail')
print(lyr.GetFeatureCount())
return 'fail'
gdal.SetConfigOption('OGR_ODS_HEADERS', None)
return 'success'
###############################################################################
# Test OGR_ODS_FIELD_TYPES = STRING
def ogr_ods_3():
| 64 | 64 | 127 | 7 | 56 | chambbj/gdal | autotest/ogr/ogr_ods.py | Python | ogr_ods_3 | ogr_ods_3 | 270 | 287 | 270 | 271 | 51f79bee032676b24b1660de16d499f10ee9de0e | bigcode/the-stack | train |
da87e818e0769059f4d49997 | train | function | def ogr_ods_check(ds, variant = False):
if ds.TestCapability("foo") != 0:
gdaltest.post_reason('fail')
return 'fail'
if ds.GetLayerCount() != 8:
gdaltest.post_reason('bad layer count')
return 'fail'
lyr = ds.GetLayer(0)
if lyr.GetName() != 'Feuille1':
gdaltest.... | def ogr_ods_check(ds, variant = False):
| if ds.TestCapability("foo") != 0:
gdaltest.post_reason('fail')
return 'fail'
if ds.GetLayerCount() != 8:
gdaltest.post_reason('bad layer count')
return 'fail'
lyr = ds.GetLayer(0)
if lyr.GetName() != 'Feuille1':
gdaltest.post_reason('bad layer name')
ret... | # The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE... | 188 | 188 | 627 | 11 | 176 | chambbj/gdal | autotest/ogr/ogr_ods.py | Python | ogr_ods_check | ogr_ods_check | 46 | 125 | 46 | 47 | 0fbf7c71e4400f972a43b64b318c43cfb0e2cf6f | bigcode/the-stack | train |
7d0c448109cc5616afbd5664 | train | function | def ogr_ods_6():
drv = ogr.GetDriverByName('ODS')
if drv is None:
return 'skip'
src_ds = ogr.Open('ODS:data/content_formulas.xml')
out_ds = ogr.GetDriverByName('CSV').CopyDataSource(src_ds, '/vsimem/content_formulas.csv')
out_ds = None
src_ds = None
fp = gdal.VSIFOpenL('/vsimem/co... | def ogr_ods_6():
| drv = ogr.GetDriverByName('ODS')
if drv is None:
return 'skip'
src_ds = ogr.Open('ODS:data/content_formulas.xml')
out_ds = ogr.GetDriverByName('CSV').CopyDataSource(src_ds, '/vsimem/content_formulas.csv')
out_ds = None
src_ds = None
fp = gdal.VSIFOpenL('/vsimem/content_formulas.csv... | ret.find('INFO') == -1 or ret.find('ERROR') != -1:
print(ret)
return 'fail'
return 'success'
###############################################################################
# Test write support
def ogr_ods_5():
drv = ogr.GetDriverByName('ODS')
if drv is None:
return 'skip'
... | 184 | 184 | 616 | 7 | 176 | chambbj/gdal | autotest/ogr/ogr_ods.py | Python | ogr_ods_6 | ogr_ods_6 | 336 | 373 | 336 | 337 | 81560da90a13d08819239c75f2454ca1c0b20914 | bigcode/the-stack | train |
1ca31819a67da30607c8d9c1 | train | function | def ogr_ods_1():
drv = ogr.GetDriverByName('ODS')
if drv is None:
return 'skip'
if drv.TestCapability("foo") != 0:
gdaltest.post_reason('fail')
return 'fail'
ds = ogr.Open('data/test.ods')
if ds is None:
gdaltest.post_reason('cannot open dataset')
return 'f... | def ogr_ods_1():
| drv = ogr.GetDriverByName('ODS')
if drv is None:
return 'skip'
if drv.TestCapability("foo") != 0:
gdaltest.post_reason('fail')
return 'fail'
ds = ogr.Open('data/test.ods')
if ds is None:
gdaltest.post_reason('cannot open dataset')
return 'fail'
return o... | .DumpReadable()
return 'fail'
feat = lyr.GetNextFeature()
if feat.IsFieldSet(2):
gdaltest.post_reason('fail')
feat.DumpReadable()
return 'fail'
return 'success'
###############################################################################
# Basic tests
def ogr_ods_1():
| 64 | 64 | 96 | 7 | 56 | chambbj/gdal | autotest/ogr/ogr_ods.py | Python | ogr_ods_1 | ogr_ods_1 | 130 | 145 | 130 | 131 | 4b9b5f2111a1203ebc417ab7bc33fb1eeaef475e | bigcode/the-stack | train |
90dbba1ee5310cc48f85fb26 | train | function | def ogr_ods_2():
drv = ogr.GetDriverByName('ODS')
if drv is None:
return 'skip'
gdal.SetConfigOption('OGR_ODS_HEADERS', 'DISABLE')
ds = ogr.Open('data/test.ods')
lyr = ds.GetLayerByName('Feuille7')
if lyr.GetFeatureCount() != 3:
gdaltest.post_reason('fail')
print(lyr.... | def ogr_ods_2():
| drv = ogr.GetDriverByName('ODS')
if drv is None:
return 'skip'
gdal.SetConfigOption('OGR_ODS_HEADERS', 'DISABLE')
ds = ogr.Open('data/test.ods')
lyr = ds.GetLayerByName('Feuille7')
if lyr.GetFeatureCount() != 3:
gdaltest.post_reason('fail')
print(lyr.GetFeatureCount())... | fail'
feat = lyr.GetNextFeature()
if feat.IsFieldSet(2):
gdaltest.post_reason('fail')
feat.DumpReadable()
return 'fail'
return 'success'
###############################################################################
# Test OGR_ODS_HEADERS = DISABLE
def ogr_ods_2():
| 64 | 64 | 122 | 7 | 56 | chambbj/gdal | autotest/ogr/ogr_ods.py | Python | ogr_ods_2 | ogr_ods_2 | 247 | 265 | 247 | 248 | 2309f6ac82153e1d47d2dad04bc0e6f9bb72e665 | bigcode/the-stack | train |
cc254d15f834b7a304ceb155 | train | function | def ogr_ods_5():
drv = ogr.GetDriverByName('ODS')
if drv is None:
return 'skip'
import test_cli_utilities
if test_cli_utilities.get_ogr2ogr_path() is None:
return 'skip'
gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -f ODS tmp/test.ods data/test.ods')
ds = og... | def ogr_ods_5():
| drv = ogr.GetDriverByName('ODS')
if drv is None:
return 'skip'
import test_cli_utilities
if test_cli_utilities.get_ogr2ogr_path() is None:
return 'skip'
gdaltest.runexternal(test_cli_utilities.get_ogr2ogr_path() + ' -f ODS tmp/test.ods data/test.ods')
ds = ogr.Open('tmp/test.o... | _test_ogrsf_path() + ' -ro data/test.ods')
if ret.find('INFO') == -1 or ret.find('ERROR') != -1:
print(ret)
return 'fail'
return 'success'
###############################################################################
# Test write support
def ogr_ods_5():
| 64 | 64 | 131 | 7 | 56 | chambbj/gdal | autotest/ogr/ogr_ods.py | Python | ogr_ods_5 | ogr_ods_5 | 313 | 331 | 313 | 314 | 46ae3e423034243eddda7bddee6c36d68d58f6a3 | bigcode/the-stack | train |
963c54317021ec877e571da3 | train | function | def ogr_ods_7():
drv = ogr.GetDriverByName('ODS')
if drv is None:
return 'skip'
try:
os.unlink('tmp/ogr_ods_7.ods')
except:
pass
shutil.copy('data/test.ods', 'tmp/ogr_ods_7.ods')
ds = ogr.Open('tmp/ogr_ods_7.ods', update = 1)
lyr = ds.GetLayerByName('Feuille7')
... | def ogr_ods_7():
| drv = ogr.GetDriverByName('ODS')
if drv is None:
return 'skip'
try:
os.unlink('tmp/ogr_ods_7.ods')
except:
pass
shutil.copy('data/test.ods', 'tmp/ogr_ods_7.ods')
ds = ogr.Open('tmp/ogr_ods_7.ods', update = 1)
lyr = ds.GetLayerByName('Feuille7')
feat = lyr.GetNex... | ,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
""".split()
if res != expected_res:
gdaltest.post_reason('did not get expected result')
print(res)
return 'fail'
return 'success'
###############################################################################
# Test update support
def ogr_od... | 95 | 95 | 318 | 7 | 87 | chambbj/gdal | autotest/ogr/ogr_ods.py | Python | ogr_ods_7 | ogr_ods_7 | 378 | 418 | 378 | 379 | 66f782e50cec867365d34277e3b8724bb6325271 | bigcode/the-stack | train |
a493133dd6db8347d5c7480d | train | function | def prepare_arguments(sources, destination, force, rename, onyo_root):
problem_str = ""
list_of_commands = []
list_of_destinations = []
assets = get_list_of_assets(onyo_root)
for source in sources:
# set all paths
source_filename = os.path.join(onyo_root, source)
destination_... | def prepare_arguments(sources, destination, force, rename, onyo_root):
| problem_str = ""
list_of_commands = []
list_of_destinations = []
assets = get_list_of_assets(onyo_root)
for source in sources:
# set all paths
source_filename = os.path.join(onyo_root, source)
destination_filename = os.path.join(onyo_root, destination)
if not os.path.... | _root + " mv -f \"" + source + "\" \"" + destination + "\""
else:
return (os.path.join(onyo_root, destination) + " already exists.")
return "git -C " + onyo_root + " mv \"" + source + "\" \"" + destination + "\""
def build_commit_cmd(list_of_commands, onyo_root):
return ["git -C " + onyo_r... | 125 | 126 | 422 | 16 | 109 | TobiasKadelka/onyo | onyo/commands/mv.py | Python | prepare_arguments | prepare_arguments | 33 | 67 | 33 | 33 | 1e1667c029cab60838d75d916c70a5dab1bb4282 | bigcode/the-stack | train |
8d1fce1b23b08f753e5dc7cb | train | function | def build_mv_cmd(onyo_root, source, destination, force, rename):
if (os.path.basename(destination) != os.path.basename(source) and not
(rename or os.path.isdir(source))):
return (os.path.basename(source) + " -> " + os.path.basename(destination) + " Assets can't be renamed without --rename.")
... | def build_mv_cmd(onyo_root, source, destination, force, rename):
| if (os.path.basename(destination) != os.path.basename(source) and not
(rename or os.path.isdir(source))):
return (os.path.basename(source) + " -> " + os.path.basename(destination) + " Assets can't be renamed without --rename.")
if os.path.isfile(os.path.join(onyo_root, destination)):
... |
import os
import sys
from onyo.utils import (
get_list_of_assets,
run_cmd
)
from onyo.commands.fsck import fsck
logging.basicConfig()
logger = logging.getLogger('onyo')
def build_mv_cmd(onyo_root, source, destination, force, rename):
| 64 | 64 | 164 | 17 | 47 | TobiasKadelka/onyo | onyo/commands/mv.py | Python | build_mv_cmd | build_mv_cmd | 17 | 26 | 17 | 17 | 8a78d7a4d9de3871fbb63a1fa696441bc88d3392 | bigcode/the-stack | train |
afba3562757e402af0892931 | train | function | def mv(args, onyo_root):
# run onyo fsck
fsck(args, onyo_root, quiet=True)
# check and set paths
list_of_commands = prepare_arguments(args.source, args.destination, args.force, args.rename, onyo_root)
# run list of commands, afterwards commit
for command in list_of_commands:
run_cmd(comm... | def mv(args, onyo_root):
# run onyo fsck
| fsck(args, onyo_root, quiet=True)
# check and set paths
list_of_commands = prepare_arguments(args.source, args.destination, args.force, args.rename, onyo_root)
# run list of commands, afterwards commit
for command in list_of_commands:
run_cmd(command)
[commit_cmd, commit_msg] = build_com... | else:
problem_str = problem_str + "\n" + current_cmd
if problem_str != "":
logger.error(problem_str + "\nNo folders or assets moved.")
sys.exit(1)
return list_of_commands
def mv(args, onyo_root):
# run onyo fsck
| 64 | 64 | 110 | 16 | 47 | TobiasKadelka/onyo | onyo/commands/mv.py | Python | mv | mv | 70 | 79 | 70 | 71 | b981aec2fb78fa38ec6cdc31de0abceab687eec3 | bigcode/the-stack | train |
5d35c5afc3bdafd662663a4a | train | function | def build_commit_cmd(list_of_commands, onyo_root):
return ["git -C " + onyo_root + " commit -m", "move asset(s).\n\n" + "\n".join(list_of_commands)]
| def build_commit_cmd(list_of_commands, onyo_root):
| return ["git -C " + onyo_root + " commit -m", "move asset(s).\n\n" + "\n".join(list_of_commands)]
| \"" + destination + "\""
else:
return (os.path.join(onyo_root, destination) + " already exists.")
return "git -C " + onyo_root + " mv \"" + source + "\" \"" + destination + "\""
def build_commit_cmd(list_of_commands, onyo_root):
| 64 | 64 | 46 | 12 | 51 | TobiasKadelka/onyo | onyo/commands/mv.py | Python | build_commit_cmd | build_commit_cmd | 29 | 30 | 29 | 29 | 3f9b3b8b1182c4213e0fff2de5f19b45c94f0220 | bigcode/the-stack | train |
ac2444f0837cc1c5f80774f9 | train | class | class V2AlphaRestTestCase(unittest.TestCase):
# Consumer must define
# USER_ID = <some string>
# TO_REGISTER = [<list of REST servlets to register>]
@defer.inlineCallbacks
def setUp(self):
self.mock_resource = MockHttpResource(prefix=PATH_PREFIX)
hs = yield setup_test_homeserve... | class V2AlphaRestTestCase(unittest.TestCase):
# Consumer must define
# USER_ID = <some string>
# TO_REGISTER = [<list of REST servlets to register>]
@defer.inlineCallbacks
| def setUp(self):
self.mock_resource = MockHttpResource(prefix=PATH_PREFIX)
hs = yield setup_test_homeserver(
datastore=self.make_datastore_mock(),
http_client=None,
resource_for_client=self.mock_resource,
resource_for_federation=self.mock_resource,
... | UserID
from twisted.internet import defer
PATH_PREFIX = "/_matrix/client/v2_alpha"
class V2AlphaRestTestCase(unittest.TestCase):
# Consumer must define
# USER_ID = <some string>
# TO_REGISTER = [<list of REST servlets to register>]
@defer.inlineCallbacks
| 71 | 71 | 238 | 51 | 20 | rzr/synapse | tests/rest/client/v2_alpha/__init__.py | Python | V2AlphaRestTestCase | V2AlphaRestTestCase | 30 | 63 | 30 | 35 | 7aab1288054c8e5cfdac2f4ca94eefaeeb6b2ad1 | bigcode/the-stack | train |
3ea048f562ff9707141b523a | train | function | @app.get("/health", response_model=HealthCheckOutput)
def health_check():
return {"health": "True"}
| @app.get("/health", response_model=HealthCheckOutput)
def health_check():
| return {"health": "True"}
| fastapi.responses import JSONResponse
from app.bidding_strategy import ClickPerCost
from app.get_ads import GetAdsFromPostgres
import psycopg2
log = get_logger(logger_name="main")
app = FastAPI()
@app.get("/health", response_model=HealthCheckOutput)
def health_check():
| 64 | 64 | 24 | 16 | 48 | raywu60kg/mini-demand-side-platform | src/bidding-server/app/main.py | Python | health_check | health_check | 15 | 17 | 15 | 16 | 7b81b883a162143becf038409e84485ddfc245f0 | bigcode/the-stack | train |
cd7c078f1513c7e47e58ae46 | train | function | @app.post("/bw_dsp")
# @app.post("/bw_dsp", response_model=RequestOutput)
def handle_bid_request(bid_request: RequestInput):
# get ads
try:
if get_ads_method == "postgres":
postgres_client = psycopg2.connect(
dbname=postgres_server_info["dbname"],
user=postgr... | @app.post("/bw_dsp")
# @app.post("/bw_dsp", response_model=RequestOutput)
def handle_bid_request(bid_request: RequestInput):
# get ads
| try:
if get_ads_method == "postgres":
postgres_client = psycopg2.connect(
dbname=postgres_server_info["dbname"],
user=postgres_server_info["user"],
password=postgres_server_info["password"],
host=postgres_server_info["host"],
... | ClickPerCost
from app.get_ads import GetAdsFromPostgres
import psycopg2
log = get_logger(logger_name="main")
app = FastAPI()
@app.get("/health", response_model=HealthCheckOutput)
def health_check():
return {"health": "True"}
@app.post("/bw_dsp")
# @app.post("/bw_dsp", response_model=RequestOutput)
def handle_b... | 96 | 97 | 325 | 37 | 59 | raywu60kg/mini-demand-side-platform | src/bidding-server/app/main.py | Python | handle_bid_request | handle_bid_request | 20 | 57 | 20 | 24 | cfb03fbf0e0014b971c98eee291535bddbb82b3c | bigcode/the-stack | train |
dedeab959adcf5670aeab8f4 | train | class | class intf_isis(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module brocade-common-def - based on the path /routing-system/interface/ve/intf-isis. Each member element of
the container is represented as a class variable - with a specific
YANG type.
"""
__slot... | class intf_isis(PybindBase):
| """
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module brocade-common-def - based on the path /routing-system/interface/ve/intf-isis. Each member element of
the container is represented as a class variable - with a specific
YANG type.
"""
__slots__ = ('_pybind_generated_by'... |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from d... | 105 | 256 | 1,503 | 9 | 95 | extremenetworks/pybind | pybind/slxos/v17s_1_02/routing_system/interface/ve/intf_isis/__init__.py | Python | intf_isis | intf_isis | 11 | 121 | 11 | 11 | c8c388ef604912d8839506c0573e66006ea6d445 | bigcode/the-stack | train |
a7925ea195fe20f084b6eadc | train | class | class LinkedInBackend(BaseSocialBackend):
"""
Backend to handle login with LinkedIn.
"""
model = LinkedInOAuthProfile
| class LinkedInBackend(BaseSocialBackend):
| """
Backend to handle login with LinkedIn.
"""
model = LinkedInOAuthProfile
| from .models import LinkedInOAuthProfile
from ..core.backends import BaseSocialBackend
class LinkedInBackend(BaseSocialBackend):
| 26 | 64 | 29 | 8 | 17 | gGonz/django-socialnetworks | socialnetworks/linkedin/backends.py | Python | LinkedInBackend | LinkedInBackend | 5 | 9 | 5 | 5 | 55e3a48e106203636e706dc0e96a2fc3e0c6ca3a | bigcode/the-stack | train |
ec9967903f226de103fd92a4 | train | function | def handle_pagination(url: str, data: list, response_headers: dict, http_fields: dict, request_headers=None) -> tuple:
"""Handles retrieving the remaining data for a request that is paginated
:param url: the url to query
:type url: str
:param data: the data from the first request
:type data: list
... | def handle_pagination(url: str, data: list, response_headers: dict, http_fields: dict, request_headers=None) -> tuple:
| """Handles retrieving the remaining data for a request that is paginated
:param url: the url to query
:type url: str
:param data: the data from the first request
:type data: list
:param response_headers: the HTTP response headers containing the pagination links
:type response_headers: dict
... | )
except json.decoder.JSONDecodeError:
data_dict = {'message': decoded_data}
if response.status < 200 or response.status >= 300:
print('Request for ' + url + " failed. Response data:")
print(decoded_data)
return False, data_dict, response.headers
return True, data_dict, res... | 102 | 102 | 341 | 29 | 72 | awslabs/aws-repository-status-monitor | RepositoryStatusMonitor/lambda_dir/http_handler.py | Python | handle_pagination | handle_pagination | 40 | 76 | 40 | 40 | a7998bba5b3282043f2ff9bbdb15eccad124d8cd | bigcode/the-stack | train |
46aa457f9a83dd67463a6fc6 | train | function | def request_handler(url: str, method='GET', headers=None, http_fields=None, post_body=None) -> tuple:
"""Performs an HTTP request to the specified URL and gracefully handles a failed request
:param url: the url to query
:type url: str
:param method: the HTTP method to perform (default is "GET")
:ty... | def request_handler(url: str, method='GET', headers=None, http_fields=None, post_body=None) -> tuple:
| """Performs an HTTP request to the specified URL and gracefully handles a failed request
:param url: the url to query
:type url: str
:param method: the HTTP method to perform (default is "GET")
:type method: Optional[str]
:param headers: the HTTP headers to send with the request
:type heade... | import json
import re
import urllib3
http = urllib3.PoolManager()
def request_handler(url: str, method='GET', headers=None, http_fields=None, post_body=None) -> tuple:
| 43 | 91 | 306 | 25 | 18 | awslabs/aws-repository-status-monitor | RepositoryStatusMonitor/lambda_dir/http_handler.py | Python | request_handler | request_handler | 9 | 37 | 9 | 9 | c66ef952a9fea18fbaa88874beacb0b306e58dc0 | bigcode/the-stack | train |
f9bbbddffab0dec93d50e9fc | train | function | def test_reading_config(temp_dir):
(temp_dir / "setup.cfg").write_text(CONFIG1)
config = Config.read()
assert config.fragment_directory == "changelog.d"
assert config.output_file == "README.md"
assert config.categories == ["New", "Different", "Gone", "Bad"]
| def test_reading_config(temp_dir):
| (temp_dir / "setup.cfg").write_text(CONFIG1)
config = Config.read()
assert config.fragment_directory == "changelog.d"
assert config.output_file == "README.md"
assert config.categories == ["New", "Different", "Gone", "Bad"]
| == "=-"
assert config.md_header_level == "1"
assert "{{ date.strftime('%Y-%m-%d') }}" in config.entry_title_template
assert config.main_branches == ["master", "main", "develop"]
assert config.version == ""
def test_reading_config(temp_dir):
| 63 | 64 | 66 | 8 | 55 | kurtmckee/scriv | tests/test_config.py | Python | test_reading_config | test_reading_config | 97 | 102 | 97 | 97 | ab27881af75d546b4c2514663e9a593826a1f23f | bigcode/the-stack | train |
46c8ffa0b696faa4263b5a36 | train | function | def test_defaults(temp_dir):
# No configuration files anywhere, just get all the defaults.
config = Config.read()
assert config.fragment_directory == "changelog.d"
assert config.format == "rst"
assert config.new_fragment_template.startswith(
".. A new scriv changelog fragment"
)
asse... | def test_defaults(temp_dir):
# No configuration files anywhere, just get all the defaults.
| config = Config.read()
assert config.fragment_directory == "changelog.d"
assert config.format == "rst"
assert config.new_fragment_template.startswith(
".. A new scriv changelog fragment"
)
assert config.categories == [
"Removed",
"Added",
"Changed",
"Depre... | + """
[tool.scriv]
output_file = "README.md"
categories = [
"New",
"Different",
"Gone",
"Bad",
]
["more stuff"]
value = 17
"""
)
def test_defaults(temp_dir):
# No configuration files anywhere, just get all the defaults.
| 64 | 64 | 184 | 19 | 45 | kurtmckee/scriv | tests/test_config.py | Python | test_defaults | test_defaults | 72 | 94 | 72 | 73 | 40993fbdcb17ac913d8f517c5b2ad3db3ac7b296 | bigcode/the-stack | train |
6aee064e384b60c61fbaabb0 | train | function | def test_no_such_template():
# If you specify a template name, and it doesn't exist, an error will
# be raised.
with pytest.raises(Exception, match="No such file: changelog.d/foo.j2"):
Config(new_fragment_template="file: foo.j2")
| def test_no_such_template():
# If you specify a template name, and it doesn't exist, an error will
# be raised.
| with pytest.raises(Exception, match="No such file: changelog.d/foo.j2"):
Config(new_fragment_template="file: foo.j2")
| Error, match=r"'format' must be in \['rst', 'md'\] \(got 'xyzzy'\)"
):
Config(format="xyzzy")
def test_no_such_template():
# If you specify a template name, and it doesn't exist, an error will
# be raised.
| 64 | 64 | 61 | 30 | 34 | kurtmckee/scriv | tests/test_config.py | Python | test_no_such_template | test_no_such_template | 147 | 151 | 147 | 149 | eb2d0857cac8ed0019e42f2c6d0a9e5b6e54630b | bigcode/the-stack | train |
d4189ed9125e1b9e578626e7 | train | function | def test_reading_config_from_directory(changelog_d):
# The settings file can be changelog.d/scriv.ini .
(changelog_d / "scriv.ini").write_text(CONFIG1)
config = Config.read()
assert config.categories == ["New", "Different", "Gone", "Bad"]
| def test_reading_config_from_directory(changelog_d):
# The settings file can be changelog.d/scriv.ini .
| (changelog_d / "scriv.ini").write_text(CONFIG1)
config = Config.read()
assert config.categories == ["New", "Different", "Gone", "Bad"]
| ):
(temp_dir / "tox.ini").write_text(CONFIG2)
config = Config.read()
assert config.categories == ["New", "Different", "Gone", "Bad"]
def test_reading_config_from_directory(changelog_d):
# The settings file can be changelog.d/scriv.ini .
| 63 | 64 | 64 | 25 | 38 | kurtmckee/scriv | tests/test_config.py | Python | test_reading_config_from_directory | test_reading_config_from_directory | 111 | 115 | 111 | 112 | 3f4a16a89c38f11b98887386043d9b0d2cb0108f | bigcode/the-stack | train |
64b05514304f1a01070f3e58 | train | function | def test_override_default_name(changelog_d):
# You can define a file named new_fragment.rst.j2, and it will be read
# as the template.
(changelog_d / "new_fragment.rst.j2").write_text("Hello there!")
fmt = Config().new_fragment_template
assert fmt == "Hello there!"
| def test_override_default_name(changelog_d):
# You can define a file named new_fragment.rst.j2, and it will be read
# as the template.
| (changelog_d / "new_fragment.rst.j2").write_text("Hello there!")
fmt = Config().new_fragment_template
assert fmt == "Hello there!"
| .raises(Exception, match="No such file: changelog.d/foo.j2"):
Config(new_fragment_template="file: foo.j2")
def test_override_default_name(changelog_d):
# You can define a file named new_fragment.rst.j2, and it will be read
# as the template.
| 64 | 64 | 73 | 36 | 28 | kurtmckee/scriv | tests/test_config.py | Python | test_override_default_name | test_override_default_name | 154 | 159 | 154 | 156 | 2de4a3e499ff576c37760c544cb238d70e944e0c | bigcode/the-stack | train |
bc9f55764415b70c93fe3d02 | train | function | def test_reading_config_list(temp_dir):
(temp_dir / "tox.ini").write_text(CONFIG2)
config = Config.read()
assert config.categories == ["New", "Different", "Gone", "Bad"]
| def test_reading_config_list(temp_dir):
| (temp_dir / "tox.ini").write_text(CONFIG2)
config = Config.read()
assert config.categories == ["New", "Different", "Gone", "Bad"]
| / "setup.cfg").write_text(CONFIG1)
config = Config.read()
assert config.fragment_directory == "changelog.d"
assert config.output_file == "README.md"
assert config.categories == ["New", "Different", "Gone", "Bad"]
def test_reading_config_list(temp_dir):
| 63 | 64 | 46 | 9 | 54 | kurtmckee/scriv | tests/test_config.py | Python | test_reading_config_list | test_reading_config_list | 105 | 108 | 105 | 105 | 5f5d415e4ac4b45afccd0ed8c5c7959e7f4cce6d | bigcode/the-stack | train |
eb84d7c21ed1baf433677976 | train | function | def test_reading_config_from_other_directory(temp_dir):
# setup.cfg can set the fragment directory, and then scriv.ini will
# be found there.
(temp_dir / "scriv.d").mkdir()
(temp_dir / "scriv.d" / "scriv.ini").write_text(CONFIG1)
(temp_dir / "setup.cfg").write_text(
"[tool.scriv]\nfragment_d... | def test_reading_config_from_other_directory(temp_dir):
# setup.cfg can set the fragment directory, and then scriv.ini will
# be found there.
| (temp_dir / "scriv.d").mkdir()
(temp_dir / "scriv.d" / "scriv.ini").write_text(CONFIG1)
(temp_dir / "setup.cfg").write_text(
"[tool.scriv]\nfragment_directory = scriv.d\n"
)
config = Config.read()
assert config.fragment_directory == "scriv.d"
assert config.categories == ["New", "Diff... | ").write_text(CONFIG1)
config = Config.read()
assert config.categories == ["New", "Different", "Gone", "Bad"]
def test_reading_config_from_other_directory(temp_dir):
# setup.cfg can set the fragment directory, and then scriv.ini will
# be found there.
| 63 | 64 | 130 | 34 | 29 | kurtmckee/scriv | tests/test_config.py | Python | test_reading_config_from_other_directory | test_reading_config_from_other_directory | 118 | 128 | 118 | 120 | 52c0c3a414ca1f25b1a77ac65aa4c6e23337c108 | bigcode/the-stack | train |
8de94eb199e94ebad9d68be8 | train | function | def test_custom_template(changelog_d):
# You can define your own template with your own name.
(changelog_d / "start_here.j2").write_text("Custom template.")
fmt = Config(
new_fragment_template="file: start_here.j2"
).new_fragment_template
assert fmt == "Custom template."
| def test_custom_template(changelog_d):
# You can define your own template with your own name.
| (changelog_d / "start_here.j2").write_text("Custom template.")
fmt = Config(
new_fragment_template="file: start_here.j2"
).new_fragment_template
assert fmt == "Custom template."
| = scriv.d\n"
)
config = Config.read()
assert config.fragment_directory == "scriv.d"
assert config.categories == ["New", "Different", "Gone", "Bad"]
def test_custom_template(changelog_d):
# You can define your own template with your own name.
| 63 | 64 | 70 | 21 | 42 | kurtmckee/scriv | tests/test_config.py | Python | test_custom_template | test_custom_template | 131 | 137 | 131 | 132 | 7708f73d3e15b093a3077a52ec0ffdc735586b68 | bigcode/the-stack | train |
a987f7ca59c219be5191c1af | train | function | def test_literal_no_file(temp_dir):
# What happens if the file for a literal doesn't exist?
with pytest.raises(
FileNotFoundError, match=r"No such file or directory: 'sub/foob.py'"
):
Config(version="literal:sub/foob.py: __version__")
| def test_literal_no_file(temp_dir):
# What happens if the file for a literal doesn't exist?
| with pytest.raises(
FileNotFoundError, match=r"No such file or directory: 'sub/foob.py'"
):
Config(version="literal:sub/foob.py: __version__")
| = "12.34.56"\n"""
)
text = Config(version="literal:sub/foob.py: __version__").version
assert text == "12.34.56"
def test_literal_no_file(temp_dir):
# What happens if the file for a literal doesn't exist?
| 64 | 64 | 65 | 21 | 43 | kurtmckee/scriv | tests/test_config.py | Python | test_literal_no_file | test_literal_no_file | 179 | 184 | 179 | 180 | 0b6b69236832e5b5483d4e9bfffd8f0b91aa4820 | bigcode/the-stack | train |
e6cdc45c0322c3f556fd6745 | train | function | def test_literal_reading(temp_dir):
# Any setting can be read from a literal in a file.
(temp_dir / "sub").mkdir()
(temp_dir / "sub" / "foob.py").write_text(
"""# comment\n__version__ = "12.34.56"\n"""
)
text = Config(version="literal:sub/foob.py: __version__").version
assert text == "12... | def test_literal_reading(temp_dir):
# Any setting can be read from a literal in a file.
| (temp_dir / "sub").mkdir()
(temp_dir / "sub" / "foob.py").write_text(
"""# comment\n__version__ = "12.34.56"\n"""
)
text = Config(version="literal:sub/foob.py: __version__").version
assert text == "12.34.56"
| .
(changelog_d / "hello.txt").write_text("Xyzzy")
text = Config(output_file="file:hello.txt").output_file
assert text == "Xyzzy"
def test_literal_reading(temp_dir):
# Any setting can be read from a literal in a file.
| 64 | 64 | 100 | 22 | 42 | kurtmckee/scriv | tests/test_config.py | Python | test_literal_reading | test_literal_reading | 169 | 176 | 169 | 170 | 1f460cb799b41febc9930b2e50790bbeba151277 | bigcode/the-stack | train |
a7e07a4c6613e572b9c2fb53 | train | function | @pytest.mark.parametrize("chars", ["", "#", "#=-", "# ", " "])
def test_rst_chars_is_two_chars(chars):
# rst_header_chars must be exactly two non-space characters.
with pytest.raises(ValueError):
Config(rst_header_chars=chars)
| @pytest.mark.parametrize("chars", ["", "#", "#=-", "# ", " "])
def test_rst_chars_is_two_chars(chars):
# rst_header_chars must be exactly two non-space characters.
| with pytest.raises(ValueError):
Config(rst_header_chars=chars)
| /foob.py: version'",
):
Config(version="literal:sub/foob.py: version")
@pytest.mark.parametrize("chars", ["", "#", "#=-", "# ", " "])
def test_rst_chars_is_two_chars(chars):
# rst_header_chars must be exactly two non-space characters.
| 64 | 64 | 57 | 41 | 23 | kurtmckee/scriv | tests/test_config.py | Python | test_rst_chars_is_two_chars | test_rst_chars_is_two_chars | 200 | 204 | 200 | 202 | 083412fb6b8df7c4e55a381650416c363550f1f2 | bigcode/the-stack | train |
605ea798cdfc811109063994 | train | function | def test_file_reading(changelog_d):
# Any setting can be read from a file, even where it doesn't make sense.
(changelog_d / "hello.txt").write_text("Xyzzy")
text = Config(output_file="file:hello.txt").output_file
assert text == "Xyzzy"
| def test_file_reading(changelog_d):
# Any setting can be read from a file, even where it doesn't make sense.
| (changelog_d / "hello.txt").write_text("Xyzzy")
text = Config(output_file="file:hello.txt").output_file
assert text == "Xyzzy"
| (changelog_d / "new_fragment.rst.j2").write_text("Hello there!")
fmt = Config().new_fragment_template
assert fmt == "Hello there!"
def test_file_reading(changelog_d):
# Any setting can be read from a file, even where it doesn't make sense.
| 63 | 64 | 68 | 27 | 36 | kurtmckee/scriv | tests/test_config.py | Python | test_file_reading | test_file_reading | 162 | 166 | 162 | 163 | 97a72dad4792834da389befdeb37e95a40469aaa | bigcode/the-stack | train |
3cd91252c19cb53dfb320c00 | train | class | class TestTomlConfig:
"""
Tests of the TOML configuration support.
"""
def test_reading_toml_file(self, temp_dir):
(temp_dir / "pyproject.toml").write_text(TOML_CONFIG)
config = Config.read()
assert config.categories == ["New", "Different", "Gone", "Bad"]
def test_toml_with... | class TestTomlConfig:
| """
Tests of the TOML configuration support.
"""
def test_reading_toml_file(self, temp_dir):
(temp_dir / "pyproject.toml").write_text(TOML_CONFIG)
config = Config.read()
assert config.categories == ["New", "Different", "Gone", "Bad"]
def test_toml_without_us(self, temp_dir)... | Exception,
match=r"Couldn't find literal: 'literal:sub/foob.py: version'",
):
Config(version="literal:sub/foob.py: version")
@pytest.mark.parametrize("chars", ["", "#", "#=-", "# ", " "])
def test_rst_chars_is_two_chars(chars):
# rst_header_chars must be exactly two non-space characters.
... | 100 | 100 | 335 | 6 | 94 | kurtmckee/scriv | tests/test_config.py | Python | TestTomlConfig | TestTomlConfig | 207 | 244 | 207 | 207 | cf15045560ef43c8ba312ea081e2bcf3685d410a | bigcode/the-stack | train |
4933357cf678d54452bdd075 | train | function | def test_unknown_format():
with pytest.raises(
ValueError, match=r"'format' must be in \['rst', 'md'\] \(got 'xyzzy'\)"
):
Config(format="xyzzy")
| def test_unknown_format():
| with pytest.raises(
ValueError, match=r"'format' must be in \['rst', 'md'\] \(got 'xyzzy'\)"
):
Config(format="xyzzy")
| can define your own template with your own name.
(changelog_d / "start_here.j2").write_text("Custom template.")
fmt = Config(
new_fragment_template="file: start_here.j2"
).new_fragment_template
assert fmt == "Custom template."
def test_unknown_format():
| 64 | 64 | 46 | 5 | 59 | kurtmckee/scriv | tests/test_config.py | Python | test_unknown_format | test_unknown_format | 140 | 144 | 140 | 140 | 846cee3079e24ef6c2eb568f033b5c8a15dfc224 | bigcode/the-stack | train |
82597f8bfe35c2594285925d | train | function | def test_literal_no_literal(temp_dir):
# What happens if the literal we're looking for isn't there?
(temp_dir / "sub").mkdir()
(temp_dir / "sub" / "foob.py").write_text(
"""# comment\n__version__ = "12.34.56"\n"""
)
with pytest.raises(
Exception,
match=r"Couldn't find literal... | def test_literal_no_literal(temp_dir):
# What happens if the literal we're looking for isn't there?
| (temp_dir / "sub").mkdir()
(temp_dir / "sub" / "foob.py").write_text(
"""# comment\n__version__ = "12.34.56"\n"""
)
with pytest.raises(
Exception,
match=r"Couldn't find literal: 'literal:sub/foob.py: version'",
):
Config(version="literal:sub/foob.py: version")
| with pytest.raises(
FileNotFoundError, match=r"No such file or directory: 'sub/foob.py'"
):
Config(version="literal:sub/foob.py: __version__")
def test_literal_no_literal(temp_dir):
# What happens if the literal we're looking for isn't there?
| 64 | 64 | 111 | 21 | 43 | kurtmckee/scriv | tests/test_config.py | Python | test_literal_no_literal | test_literal_no_literal | 187 | 197 | 187 | 188 | 0fea1e3871136b6749880a19b180a49d0a54238c | bigcode/the-stack | train |
fb18203305081041a14e22c9 | train | class | class GetFile(Processor):
def __init__(self, input_dir="/tmp/input", schedule={'scheduling period': '2 sec'}):
super(GetFile, self).__init__(
'GetFile',
properties={
'Input Directory': input_dir,
},
schedule=schedule,
auto_terminate... | class GetFile(Processor):
| def __init__(self, input_dir="/tmp/input", schedule={'scheduling period': '2 sec'}):
super(GetFile, self).__init__(
'GetFile',
properties={
'Input Directory': input_dir,
},
schedule=schedule,
auto_terminate=['success'])
| from ..core.Processor import Processor
class GetFile(Processor):
| 14 | 64 | 69 | 6 | 7 | dtrodrigues/nifi-minifi-cpp | docker/test/integration/minifi/processors/GetFile.py | Python | GetFile | GetFile | 4 | 12 | 4 | 4 | a75a7221f79aa0227f0fd1c26d408c7d005911a4 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.