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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
36404692eb1ae6181b5962e5 | train | function | def libgd():
http_archive(
name = "libgd",
build_file = "//bazel/deps/libgd:build.BUILD",
sha256 = "ef0bb94002d1fbc5e593c517ea353d3c039b92d20024fdf4bacb1cdc26c0dd9f",
strip_prefix = "libgd-e0cb1b76c305db68b251fe782faa12da5d357593",
urls = [
"https://github.com/Uni... | def libgd():
| http_archive(
name = "libgd",
build_file = "//bazel/deps/libgd:build.BUILD",
sha256 = "ef0bb94002d1fbc5e593c517ea353d3c039b92d20024fdf4bacb1cdc26c0dd9f",
strip_prefix = "libgd-e0cb1b76c305db68b251fe782faa12da5d357593",
urls = [
"https://github.com/Unilang/libgd/ar... | this file directly.
# It was auto-generated by: code/programs/reflexivity/reflexive_refresh
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file")
def libgd():
| 64 | 64 | 148 | 4 | 60 | luxe/CodeLang-compiler | source/bazel/deps/libgd/get.bzl | Python | libgd | libgd | 7 | 16 | 7 | 7 | d56a173f4edd5f283af7f810e8e1766269297cfc | bigcode/the-stack | train |
f3c5a2d1f0631a4ca5d4b698 | train | class | class AbstractModel:
def __init__(self, save_directory):
self.save_directory = save_directory
def save(self):
self.model.save('{}/final_model.hdf5'.format(self.save_directory))
def load(self, which = 'final_model'):
self.model = load_model('{}/{}.hdf5'.format(self.save_directory, which))
| class AbstractModel:
| def __init__(self, save_directory):
self.save_directory = save_directory
def save(self):
self.model.save('{}/final_model.hdf5'.format(self.save_directory))
def load(self, which = 'final_model'):
self.model = load_model('{}/{}.hdf5'.format(self.save_directory, which))
| from keras.models import load_model
class AbstractModel:
| 11 | 64 | 72 | 4 | 6 | thonic92/chal_TM | src/models/AbstractModel.py | Python | AbstractModel | AbstractModel | 3 | 12 | 3 | 3 | 99fef0c1c1acfc5b5eef280c891eb8aaa751e090 | bigcode/the-stack | train |
99158ffd9d1065f78b74f1e3 | train | class | class TestAvroEncoderAsync(AzureRecordedTestCase):
def create_client(self, **kwargs):
fully_qualified_namespace = kwargs.pop("fully_qualified_namespace")
credential = self.get_credential(SchemaRegistryClient, is_async=True)
return self.create_client_from_credential(SchemaRegistryClient, cre... | class TestAvroEncoderAsync(AzureRecordedTestCase):
| def create_client(self, **kwargs):
fully_qualified_namespace = kwargs.pop("fully_qualified_namespace")
credential = self.get_credential(SchemaRegistryClient, is_async=True)
return self.create_client_from_credential(SchemaRegistryClient, credential, fully_qualified_namespace=fully_qualified_n... | INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTIO... | 256 | 256 | 5,844 | 12 | 244 | NateLehman/azure-sdk-for-python | sdk/schemaregistry/azure-schemaregistry-avroencoder/tests/test_avro_encoder_async.py | Python | TestAvroEncoderAsync | TestAvroEncoderAsync | 47 | 542 | 47 | 48 | fbf02e86ba5f196913c9889f84050067fb16e828 | bigcode/the-stack | train |
380ff25964f714c064135c55 | train | function | def initialize_logging(name: str = __name__) -> Logger:
"""Initialize logger for logging system.
Args:
name (str, optional): Name of logging file.
- Defaults to __name__.
Returns:
Logger: Logger to handle.
"""
logger = getLogger(name)
logger.propagate = False
lo... | def initialize_logging(name: str = __name__) -> Logger:
| """Initialize logger for logging system.
Args:
name (str, optional): Name of logging file.
- Defaults to __name__.
Returns:
Logger: Logger to handle.
"""
logger = getLogger(name)
logger.propagate = False
logger.setLevel(DEBUG)
handler = StreamHandler()
... | # -*- coding: utf-8 -*-
from logging import DEBUG, Formatter, Logger, StreamHandler, getLogger
def initialize_logging(name: str = __name__) -> Logger:
| 36 | 64 | 140 | 13 | 22 | Yoshi-0921/toio_API | toio_API/utils/logging.py | Python | initialize_logging | initialize_logging | 6 | 29 | 6 | 6 | 5fbfd62ef64e41f1070f1ceb719b3d35c331c387 | bigcode/the-stack | train |
a1f64694b3ff9b7361495eb8 | train | class | class DroneEnvHumanFollowV1(DroneEnv):
def __init__(self, env_args):
super().__init__()
self.reward_version = env_args['reward_version']
self.policy_model = env_args['policy_model']
self.use_temporal = env_args['use_temporal']
if self.use_temporal:
self.observat... | class DroneEnvHumanFollowV1(DroneEnv):
| def __init__(self, env_args):
super().__init__()
self.reward_version = env_args['reward_version']
self.policy_model = env_args['policy_model']
self.use_temporal = env_args['use_temporal']
if self.use_temporal:
self.observation_space = Box(low=-100, high=100, sha... | import numpy as np
from envs.drone_env import *
np.set_printoptions(precision=3, suppress=True)
class DroneEnvHumanFollowV1(DroneEnv):
| 36 | 256 | 1,228 | 11 | 25 | PeihongYu/PPO-PyTorch | envs/drone_env_human_follow_v1.py | Python | DroneEnvHumanFollowV1 | DroneEnvHumanFollowV1 | 7 | 151 | 7 | 7 | a600c589fb5d64eded3e807c192829dd381e5e8d | bigcode/the-stack | train |
51b27a4ad3ba3cce4754ca90 | train | function | def main():
"""
Takes in a character matrix, an algorithm, and an output file and
returns a tree in newick format.
"""
parser = argparse.ArgumentParser()
parser.add_argument("netfp", type=str, help="character_matrix")
parser.add_argument("-nj", "--neighbor-joining", action="store_true", def... | def main():
| """
Takes in a character matrix, an algorithm, and an output file and
returns a tree in newick format.
"""
parser = argparse.ArgumentParser()
parser.add_argument("netfp", type=str, help="character_matrix")
parser.add_argument("-nj", "--neighbor-joining", action="store_true", default=False)
... | aln = AlignIO.read(phy, "phylip")
df = pc.from_bioalignment(aln)
abund = df.apply(lambda x: len(x[x == "1"]) / len(x), axis=1)
labund = np.array(
list(map(lambda x: float(-1 * np.log2(x)) if x > 1 else x, abund))
)
labund[labund == 0] = labund.min()
# scale linearly to range for phy... | 256 | 256 | 3,200 | 3 | 252 | pjb7687/Cassiopeia | cassiopeia/TreeSolver/reconstruct_sim_tree.py | Python | main | main | 203 | 622 | 203 | 203 | 6229fdc261a73b3aee614fa9493cea5945884b6a | bigcode/the-stack | train |
0b46ca90e6150de44b5bd125 | train | function | def unique_alignments(aln):
new_aln = []
obs = []
for a in aln:
if a.seq in obs:
continue
new_aln.append(a)
obs.append(a.seq)
return MultipleSeqAlignment(new_aln)
| def unique_alignments(aln):
| new_aln = []
obs = []
for a in aln:
if a.seq in obs:
continue
new_aln.append(a)
obs.append(a.seq)
return MultipleSeqAlignment(new_aln)
| ")
for n in target_nodes:
charstring, sname = n.char_string, n.name
f.write(sname)
chars = charstring.split("|")
for c in chars:
f.write("\t" + c)
f.write("\n")
def unique_alignments(aln):
| 64 | 64 | 55 | 7 | 57 | pjb7687/Cassiopeia | cassiopeia/TreeSolver/reconstruct_sim_tree.py | Python | unique_alignments | unique_alignments | 127 | 139 | 127 | 128 | 5b1a70830c45e9f0d950b5311090826a01926dea | bigcode/the-stack | train |
e656239b6112187ef879a625 | train | function | def nx_to_charmat(target_nodes):
number_of_characters = len(target_nodes[0].split("|"))
cm = pd.DataFrame(np.zeros((len(target_nodes), number_of_characters)))
ind = []
for i in range(len(target_nodes)):
nr = []
n = target_nodes[i]
charstring, sname = n.split("_")
ind.ap... | def nx_to_charmat(target_nodes):
| number_of_characters = len(target_nodes[0].split("|"))
cm = pd.DataFrame(np.zeros((len(target_nodes), number_of_characters)))
ind = []
for i in range(len(target_nodes)):
nr = []
n = target_nodes[i]
charstring, sname = n.split("_")
ind.append("s" + sname)
chars = ... | ")
def unique_alignments(aln):
new_aln = []
obs = []
for a in aln:
if a.seq in obs:
continue
new_aln.append(a)
obs.append(a.seq)
return MultipleSeqAlignment(new_aln)
def nx_to_charmat(target_nodes):
| 64 | 64 | 147 | 8 | 56 | pjb7687/Cassiopeia | cassiopeia/TreeSolver/reconstruct_sim_tree.py | Python | nx_to_charmat | nx_to_charmat | 142 | 162 | 142 | 143 | fbd0d2d46240cb1cb239758d0751efae041c3a70 | bigcode/the-stack | train |
025683ee549f99a531597561 | train | function | def construct_weights(phy, weights_fn, write=True):
"""
Given some binary phylip infile file path, compute the character-wise log frequencies
and translate to the phylip scaling (0-Z) for the weights file.
"""
aln = AlignIO.read(phy, "phylip")
df = pc.from_bioalignment(aln)
abund = df.app... | def construct_weights(phy, weights_fn, write=True):
| """
Given some binary phylip infile file path, compute the character-wise log frequencies
and translate to the phylip scaling (0-Z) for the weights file.
"""
aln = AlignIO.read(phy, "phylip")
df = pc.from_bioalignment(aln)
abund = df.apply(lambda x: len(x[x == "1"]) / len(x), axis=1)
... | , sname = n.split("_")
ind.append("s" + sname)
chars = charstring.split("|")
for c in chars:
nr.append(c)
cm.iloc[i] = np.array(nr)
cm.columns = [("r" + str(i)) for i in range(number_of_characters)]
cm.index = ind
return cm
def construct_weights(phy, weights_fn... | 91 | 91 | 306 | 12 | 78 | pjb7687/Cassiopeia | cassiopeia/TreeSolver/reconstruct_sim_tree.py | Python | construct_weights | construct_weights | 165 | 200 | 165 | 165 | 7c6229fb027a194d1b43b0b810e62644654aad10 | bigcode/the-stack | train |
f17732124d796641a9599436 | train | function | @jit(parallel=True)
def compute_distance_mat(cm, C, priors=None):
dm = np.zeros(C * (C - 1) // 2, dtype=float)
k = 0
for i in range(C - 1):
for j in range(i + 1, C):
s1 = cm[i]
s2 = cm[j]
dm[k] = pairwise_dist(s1, s2, priors)
k += 1
return dm
| @jit(parallel=True)
def compute_distance_mat(cm, C, priors=None):
| dm = np.zeros(C * (C - 1) // 2, dtype=float)
k = 0
for i in range(C - 1):
for j in range(i + 1, C):
s1 = cm[i]
s2 = cm[j]
dm[k] = pairwise_dist(s1, s2, priors)
k += 1
return dm
| from cassiopeia.TreeSolver import Cassiopeia_Tree, Node
from numba import jit
import cassiopeia as sclt
SCLT_PATH = Path(sclt.__path__[0])
@jit(parallel=True)
def compute_distance_mat(cm, C, priors=None):
| 64 | 64 | 107 | 18 | 46 | pjb7687/Cassiopeia | cassiopeia/TreeSolver/reconstruct_sim_tree.py | Python | compute_distance_mat | compute_distance_mat | 51 | 65 | 51 | 53 | 4e6adec0571f40534f5b9c1ee94e5dff5a58659a | bigcode/the-stack | train |
b70d739dd78c82f901b29f99 | train | function | def pairwise_dist(s1, s2, priors=None):
d = 0
num_present = 0
for i in range(len(s1)):
if s1[i] == "-" or s2[i] == "-":
continue
num_present += 1
if priors:
if s1[i] == s2[i]:
d += np.log(priors[i][str(s1[i])])
if s1[i] != s2[i]:
... | def pairwise_dist(s1, s2, priors=None):
| d = 0
num_present = 0
for i in range(len(s1)):
if s1[i] == "-" or s2[i] == "-":
continue
num_present += 1
if priors:
if s1[i] == s2[i]:
d += np.log(priors[i][str(s1[i])])
if s1[i] != s2[i]:
if s1[i] == "0" or s2[i] == "0... | range(C - 1):
for j in range(i + 1, C):
s1 = cm[i]
s2 = cm[j]
dm[k] = pairwise_dist(s1, s2, priors)
k += 1
return dm
def pairwise_dist(s1, s2, priors=None):
| 73 | 73 | 246 | 14 | 58 | pjb7687/Cassiopeia | cassiopeia/TreeSolver/reconstruct_sim_tree.py | Python | pairwise_dist | pairwise_dist | 68 | 100 | 68 | 69 | 086edf25c49d5c20a56927074c521e95e98d65e2 | bigcode/the-stack | train |
e440931557ada64d1829cc5f | train | function | def write_leaves_to_charmat(target_nodes, fn):
"""
Helper function to write TARGET_NODES to a character matrix to conver to multistate;
needed to run camin-sokal.
"""
number_of_characters = len(target_nodes[0].char_string.split("|"))
with open(fn, "w") as f:
f.write("cellBC")
f... | def write_leaves_to_charmat(target_nodes, fn):
| """
Helper function to write TARGET_NODES to a character matrix to conver to multistate;
needed to run camin-sokal.
"""
number_of_characters = len(target_nodes[0].char_string.split("|"))
with open(fn, "w") as f:
f.write("cellBC")
for i in range(number_of_characters):
... | (priors[i][str(s1[i])]) + np.log(priors[i][str(s2[i])])
else:
d += 2
if num_present == 0:
return 0
return d / num_present
def write_leaves_to_charmat(target_nodes, fn):
| 64 | 64 | 160 | 12 | 51 | pjb7687/Cassiopeia | cassiopeia/TreeSolver/reconstruct_sim_tree.py | Python | write_leaves_to_charmat | write_leaves_to_charmat | 103 | 124 | 103 | 103 | 4f998b3a16d907ffc198c2881bf2b169e1031673 | bigcode/the-stack | train |
3d1c5b4cc53efa458f0ca6a7 | train | class | class Solution:
def canBeEqual(self, target: List[int], arr: List[int]) -> bool:
return set(target) == set(arr)
| class Solution:
| def canBeEqual(self, target: List[int], arr: List[int]) -> bool:
return set(target) == set(arr)
| from typing import List
class Solution:
| 8 | 64 | 32 | 3 | 4 | KenWoo/Algorithm | Algorithms/Easy/1460. Make Two Arrays Equal by Reversing Sub-arrays/answer.py | Python | Solution | Solution | 4 | 6 | 4 | 4 | aff19fbd8ce0eb84a367e2b5dde3f0e37b9bc73a | bigcode/the-stack | train |
c5b81e94bf8da98f5037a293 | train | function | def make_map():
"""Create, configure and return the routes Mapper"""
# import controllers here rather than at root level because
# pylons config is initialised by this point.
# Helpers to reduce code clutter
GET = dict(method=['GET'])
PUT = dict(method=['PUT'])
POST = dict(method=['POST'])
... | def make_map():
| """Create, configure and return the routes Mapper"""
# import controllers here rather than at root level because
# pylons config is initialised by this point.
# Helpers to reduce code clutter
GET = dict(method=['GET'])
PUT = dict(method=['PUT'])
POST = dict(method=['POST'])
DELETE = dic... | '
:type highlight_actions: string
'''
ckan_icon = kw.pop('ckan_icon', None)
highlight_actions = kw.pop('highlight_actions', kw.get('action', ''))
ckan_core = kw.pop('ckan_core', None)
out = _Mapper.connect(self, *args, **kw)
route = self.matchlist[-1]
if... | 256 | 256 | 1,102 | 4 | 251 | thehyve/ckan | ckan/config/routing.py | Python | make_map | make_map | 72 | 197 | 72 | 72 | 204cbfddaae69e0df2bbce0c1572993a076994d3 | bigcode/the-stack | train |
042ee1c987461c538fdd06ca | train | class | class Mapper(_Mapper):
''' This Mapper allows us to intercept the connect calls used by routes
so that we can collect named routes and later use them to create links
via some helper functions like build_nav(). '''
def connect(self, *args, **kw):
'''Connect a new route, storing any named routes ... | class Mapper(_Mapper):
| ''' This Mapper allows us to intercept the connect calls used by routes
so that we can collect named routes and later use them to create links
via some helper functions like build_nav(). '''
def connect(self, *args, **kw):
'''Connect a new route, storing any named routes for later.
Thi... | # encoding: utf-8
"""Routes configuration
The more specific and detailed routes should be defined first so they
may take precedent over the more generic routes. For more information
refer to the routes manual at http://routes.groovie.org/docs/
"""
import re
from routes.mapper import SubMapper, Mapper as _Mapper
imp... | 94 | 145 | 485 | 5 | 89 | thehyve/ckan | ckan/config/routing.py | Python | Mapper | Mapper | 19 | 69 | 19 | 19 | 8dfa79db9b38cf3630153f44fea22eee6510fbb1 | bigcode/the-stack | train |
d9e0b164e95b47c7f00dd8e0 | train | function | def install(package):
subprocess.call([sys.executable, "-m", "pip", "install", package])
| def install(package):
| subprocess.call([sys.executable, "-m", "pip", "install", package])
| manipulating HDF5 files:
import h5py
# Plotting and visualization:
import matplotlib.pyplot as plt
# for downloading files:
import wget
import os
# multivariate analysis:
from sklearn.cluster import KMeans
from sklearn.decomposition import NMF
import subprocess
import sys
def install(package):
| 64 | 64 | 23 | 4 | 59 | po2c7b665tikqm7rct7qgdzqqefmyc5uzwiytup/pycroscopy | examples/plot_spectral_unmixing.py | Python | install | install | 52 | 53 | 52 | 52 | 533044201bd16a120d979fc0213d8edea5089779 | bigcode/the-stack | train |
2d2cf9f49580746307d6c57c | train | class | class VisualBasic6Lexer(Lexer):
atn = ATNDeserializer().deserialize(serializedATN())
decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
ACCESS = 1
ADDRESSOF = 2
ALIAS = 3
AND = 4
ATTRIBUTE = 5
APPACTIVATE = 6
APPEND = 7
AS = 8
BEEP = 9
BEGIN = ... | class VisualBasic6Lexer(Lexer):
| atn = ATNDeserializer().deserialize(serializedATN())
decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
ACCESS = 1
ADDRESSOF = 2
ALIAS = 3
AND = 4
ATTRIBUTE = 5
APPACTIVATE = 6
APPEND = 7
AS = 8
BEEP = 9
BEGIN = 10
BEGINPROPERTY = 11
BIN... | \u082b\t\"\2\2\u082b\u01f0\3\2\2\2\u082c\u082d")
buf.write("\t#\2\2\u082d\u01f2\3\2\2\2\u082e\u082f\t$\2\2\u082f\u01f4")
buf.write("\3\2\2\2)\2\u072e\u0730\u0739\u0744\u0747\u074b\u0750")
buf.write("\u0756\u075d\u0761\u0766\u076d\u0772\u0777\u077b\u0782")
buf.write("\u0788\u078c\u0794\u0... | 256 | 256 | 3,743 | 9 | 247 | deeso/antlr_vb | antlr_vb/vb6/VisualBasic6Lexer.py | Python | VisualBasic6Lexer | VisualBasic6Lexer | 1,175 | 1,501 | 1,175 | 1,176 | f378c2bb80d10de40907c208001d0449bc49efb1 | bigcode/the-stack | train |
8f77d0e92d2526db2b890460 | train | function | def serializedATN():
with StringIO() as buf:
buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\u00df")
buf.write("\u0830\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7")
buf.write("\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r")
buf.write("\4\16\t\16\4\17\t\17... | def serializedATN():
| with StringIO() as buf:
buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\u00df")
buf.write("\u0830\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7")
buf.write("\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r")
buf.write("\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\... | # Generated from VisualBasic6.g4 by ANTLR 4.7.1
from antlr4 import *
from io import StringIO
from typing.io import TextIO
import sys
def serializedATN():
| 46 | 256 | 49,111 | 5 | 40 | deeso/antlr_vb | antlr_vb/vb6/VisualBasic6Lexer.py | Python | serializedATN | serializedATN | 8 | 1,172 | 8 | 8 | 0246339f7b71224f6fc2d1bb8675b9d89749f3b6 | bigcode/the-stack | train |
c4b75801d0df1620e8c2b470 | train | function | def indexed_color(idx, total):
if idx < COLOR_WHEEL_SIZE:
# use colors from the color wheel if possible
base_col = (idx % 4) + 1
tone = ((idx / 4) % 6) + 1
if idx % 8 < 4:
shade = "a"
else:
shade = "b"
return "%d%d/%s" % (base_col, tone, shade)... | def indexed_color(idx, total):
| if idx < COLOR_WHEEL_SIZE:
# use colors from the color wheel if possible
base_col = (idx % 4) + 1
tone = ((idx / 4) % 6) + 1
if idx % 8 < 4:
shade = "a"
else:
shade = "b"
return "%d%d/%s" % (base_col, tone, shade)
else:
# generate d... | color. This function tries to return
# high contrast colors for "close" indices, so the colors of idx 1 and idx 2 may
# have stronger contrast than the colors at idx 3 and idx 10.
# retrieve an indexed color.
# param idx: the color index
# param total: the total number of colors needed in one graph.
COLOR_WHEEL_SIZE ... | 90 | 90 | 302 | 7 | 82 | NCAR/spol-nagios | omd/versions/1.2.8p15.cre/share/check_mk/web/plugins/metrics/check_mk.py | Python | indexed_color | indexed_color | 271 | 293 | 271 | 271 | e7b78509e0ed8a2adc52ed243b50f0eb67ee8463 | bigcode/the-stack | train |
9432af1ed0b1ae6cba75f0ce | train | class | class IOSXRSingleRpStateMachine(StateMachine):
# Make it easy for subclasses to pick these up.
default_commands = default_commands
def __init__(self, hostname=None):
super().__init__(hostname)
def create(self):
enable = State('enable', patterns.enable_prompt)
config = State('c... | class IOSXRSingleRpStateMachine(StateMachine):
# Make it easy for subclasses to pick these up.
| default_commands = default_commands
def __init__(self, hostname=None):
super().__init__(hostname)
def create(self):
enable = State('enable', patterns.enable_prompt)
config = State('config', patterns.config_prompt)
run = State('run', patterns.run_prompt)
admin = Sta... | __author__ = "Syed Raza <syedraza@cisco.com>"
from unicon.statemachine import StateMachine
from unicon.plugins.iosxr.patterns import IOSXRPatterns
from unicon.plugins.iosxr.statements import IOSXRStatements
from unicon.statemachine import State, Path
from unicon.eal.dialogs import Statement, Dialog
patterns = IOSXRP... | 125 | 154 | 516 | 22 | 103 | tahigash/unicon.plugins | src/unicon/plugins/iosxr/statemachine.py | Python | IOSXRSingleRpStateMachine | IOSXRSingleRpStateMachine | 16 | 75 | 16 | 18 | 0240a86c364cb454422525e01a10307dbf4ca848 | bigcode/the-stack | train |
c7f407191faf93b372f097e0 | train | class | class IOSXRDualRpStateMachine(IOSXRSingleRpStateMachine):
def __init__(self, hostname=None):
super().__init__(hostname)
def create(self):
super().create()
standby_locked = State('standby_locked', patterns.standby_prompt)
self.add_state(standby_locked)
| class IOSXRDualRpStateMachine(IOSXRSingleRpStateMachine):
| def __init__(self, hostname=None):
super().__init__(hostname)
def create(self):
super().create()
standby_locked = State('standby_locked', patterns.standby_prompt)
self.add_state(standby_locked)
| _to_admin)
self.add_default_statements(default_commands)
@staticmethod
def handle_failed_config(spawn):
spawn.sendline('show configuration failed')
spawn.expect([patterns.config_prompt])
spawn.sendline('abort')
class IOSXRDualRpStateMachine(IOSXRSingleRpStateMachine):
| 64 | 64 | 68 | 16 | 48 | tahigash/unicon.plugins | src/unicon/plugins/iosxr/statemachine.py | Python | IOSXRDualRpStateMachine | IOSXRDualRpStateMachine | 78 | 87 | 78 | 79 | bdc9c1c672716a6588707a50836de76fa3c333d2 | bigcode/the-stack | train |
69511056c38eb2f354605c12 | train | class | class LocaleNegotiationMixin(object):
"""A mixin for CBV to select a locale based on Accept-Language headers."""
def get_locale(self):
accept_language = self.request.META.get('HTTP_ACCEPT_LANGUAGE', '')
lang = get_best_language(accept_language)
return lang or settings.WIKI_DEFAULT_LANGU... | class LocaleNegotiationMixin(object):
| """A mixin for CBV to select a locale based on Accept-Language headers."""
def get_locale(self):
accept_language = self.request.META.get('HTTP_ACCEPT_LANGUAGE', '')
lang = get_best_language(accept_language)
return lang or settings.WIKI_DEFAULT_LANGUAGE
def get_serializer_context(se... | instances
instead of lots of subclasses.
"""
def __init__(self, status_code, detail, **kwargs):
self.status_code = status_code
self.detail = detail
for key, val in kwargs.items():
setattr(self, key, val)
class LocaleNegotiationMixin(object):
| 64 | 64 | 103 | 7 | 57 | navgurukul-shivani18/kitsune | kitsune/sumo/api_utils.py | Python | LocaleNegotiationMixin | LocaleNegotiationMixin | 38 | 49 | 38 | 38 | 9006425f96a0e67162b90a9d96f43e904a34c98e | bigcode/the-stack | train |
301019e4d1deac9627ea52c8 | train | class | class JSONRenderer(DRFJSONRenderer):
def render(self, data, accepted_media_type=None, renderer_context=None):
json = super(JSONRenderer, self).render(data, accepted_media_type, renderer_context)
# In HTML (such as in <script> tags), "</" is an illegal sequence in a
# <script> tag. In JSON,... | class JSONRenderer(DRFJSONRenderer):
| def render(self, data, accepted_media_type=None, renderer_context=None):
json = super(JSONRenderer, self).render(data, accepted_media_type, renderer_context)
# In HTML (such as in <script> tags), "</" is an illegal sequence in a
# <script> tag. In JSON, "\/" is a legal representation of the... | a file name.
Additionally, if there is no file associated with this image, this
returns ``None`` instead of erroring.
"""
def to_native(self, value):
try:
return value.url
except ValueError:
return None
class JSONRenderer(DRFJSONRenderer):
| 64 | 64 | 154 | 8 | 55 | navgurukul-shivani18/kitsune | kitsune/sumo/api_utils.py | Python | JSONRenderer | JSONRenderer | 340 | 353 | 340 | 341 | efcacfcacd581b60c6a544e816ad18b992598a5e | bigcode/the-stack | train |
2a265d7801f4da7a3e4ea74d | train | class | class GenericRelatedField(fields.ReadOnlyField):
"""
Serializes GenericForeignKey relations using specified type of serializer.
"""
def __init__(self, serializer_type='fk', **kwargs):
self.serializer_type = serializer_type
super(GenericRelatedField, self).__init__(**kwargs)
def to_... | class GenericRelatedField(fields.ReadOnlyField):
| """
Serializes GenericForeignKey relations using specified type of serializer.
"""
def __init__(self, serializer_type='fk', **kwargs):
self.serializer_type = serializer_type
super(GenericRelatedField, self).__init__(**kwargs)
def to_representation(self, value):
content_type... | )
value = value.astimezone(pytz.utc)
return super(DateTimeUTCField, self).to_representation(value)
class _IDSerializer(serializers.Serializer):
id = fields.Field(source='pk')
class Meta:
fields = ('id', )
class GenericRelatedField(fields.ReadOnlyField):
| 64 | 64 | 155 | 9 | 55 | navgurukul-shivani18/kitsune | kitsune/sumo/api_utils.py | Python | GenericRelatedField | GenericRelatedField | 165 | 187 | 165 | 165 | 4cc2ddaf8e245a7ba41faa631f7962f5418715ef | bigcode/the-stack | train |
66608e442bc0790ba4c6e8dc | train | class | class OnlyCreatorEdits(permissions.BasePermission):
"""
Only allow objects to be edited and deleted by their creators.
TODO: This should be tied to user and object permissions better, but
for now this is a bandaid.
"""
def has_object_permission(self, request, view, obj):
# SAFE_METHODS... | class OnlyCreatorEdits(permissions.BasePermission):
| """
Only allow objects to be edited and deleted by their creators.
TODO: This should be tied to user and object permissions better, but
for now this is a bandaid.
"""
def has_object_permission(self, request, view, obj):
# SAFE_METHODS is a list containing all the read-only methods.
... | raise NotImplemented
def has_permission(self, request, view):
u = request.user
not_inactive = u.is_anonymous() or u.is_active
return not_inactive and all(u.has_perm(p) for p in self.permissions)
class OnlyCreatorEdits(permissions.BasePermission):
| 64 | 64 | 145 | 10 | 54 | navgurukul-shivani18/kitsune | kitsune/sumo/api_utils.py | Python | OnlyCreatorEdits | OnlyCreatorEdits | 238 | 254 | 238 | 238 | 55854a7b15f1f8aa4d702106182fc2b685c22934 | bigcode/the-stack | train |
095fcdacfb54e43ef4bc6019 | train | class | class _IDSerializer(serializers.Serializer):
id = fields.Field(source='pk')
class Meta:
fields = ('id', )
| class _IDSerializer(serializers.Serializer):
| id = fields.Field(source='pk')
class Meta:
fields = ('id', )
| zinfo is None:
default_tzinfo = pytz.timezone(settings.TIME_ZONE)
value = default_tzinfo.localize(value)
value = value.astimezone(pytz.utc)
return super(DateTimeUTCField, self).to_representation(value)
class _IDSerializer(serializers.Serializer):
| 64 | 64 | 27 | 7 | 57 | navgurukul-shivani18/kitsune | kitsune/sumo/api_utils.py | Python | _IDSerializer | _IDSerializer | 158 | 162 | 158 | 158 | 4800c8061ea5cc95fa8b18b2ff851192e532a85e | bigcode/the-stack | train |
050f7fee7cb708d49aca5bc6 | train | class | class DateTimeUTCField(fields.DateTimeField):
"""
This is like DateTimeField, except it always outputs in UTC.
"""
def to_representation(self, value):
if value.tzinfo is None:
default_tzinfo = pytz.timezone(settings.TIME_ZONE)
value = default_tzinfo.localize(value)
... | class DateTimeUTCField(fields.DateTimeField):
| """
This is like DateTimeField, except it always outputs in UTC.
"""
def to_representation(self, value):
if value.tzinfo is None:
default_tzinfo = pytz.timezone(settings.TIME_ZONE)
value = default_tzinfo.localize(value)
value = value.astimezone(pytz.utc)
... | robust than the DRF original, but it
# should be fine for our purposes.
return getattr(instance, self.read_source)
def to_representation(self, obj):
return obj
def to_internal_value(self, data):
return data
class DateTimeUTCField(fields.DateTimeField):
| 64 | 64 | 99 | 10 | 53 | navgurukul-shivani18/kitsune | kitsune/sumo/api_utils.py | Python | DateTimeUTCField | DateTimeUTCField | 145 | 155 | 145 | 145 | c088c5595924addb15ba42c9eb0f228080c12124 | bigcode/the-stack | train |
951d37f9e3166ab8d978370c | train | class | class GenericDjangoPermission(permissions.BasePermission):
@property
def permissions(self):
raise NotImplemented
def has_permission(self, request, view):
u = request.user
not_inactive = u.is_anonymous() or u.is_active
return not_inactive and all(u.has_perm(p) for p in self.... | class GenericDjangoPermission(permissions.BasePermission):
@property
| def permissions(self):
raise NotImplemented
def has_permission(self, request, view):
u = request.user
not_inactive = u.is_anonymous() or u.is_active
return not_inactive and all(u.has_perm(p) for p in self.permissions)
| ):
arg = {key + '__gte': value}
return queryset.filter(**arg)
def op_lte(self, queryset, key, value):
arg = {key + '__lte': value}
return queryset.filter(**arg)
class GenericDjangoPermission(permissions.BasePermission):
@property
| 64 | 64 | 73 | 14 | 50 | navgurukul-shivani18/kitsune | kitsune/sumo/api_utils.py | Python | GenericDjangoPermission | GenericDjangoPermission | 226 | 235 | 226 | 228 | 3861c6347e1cebd1286fa26f2c579095c5783518 | bigcode/the-stack | train |
b38a911fe249b7e802f2f16d | train | function | def PermissionMod(field, permissions):
"""
Takes a class and modifies it to conditionally hide based on permissions.
"""
class Modded(field):
@classmethod
def many_init(cls, *args, **kwargs):
kwargs['child'] = field()
return PermissionMod(serializers.ListSerializ... | def PermissionMod(field, permissions):
| """
Takes a class and modifies it to conditionally hide based on permissions.
"""
class Modded(field):
@classmethod
def many_init(cls, *args, **kwargs):
kwargs['child'] = field()
return PermissionMod(serializers.ListSerializer, permissions)(*args, **kwargs)
... |
# If flow gets here, the method will modify something.
user = getattr(request, 'user', None)
creator = getattr(obj, 'creator', None)
# Only the creator can modify things.
return user == creator
PermissionListSerializer = None
def PermissionMod(field, permissions):
| 64 | 64 | 176 | 7 | 56 | navgurukul-shivani18/kitsune | kitsune/sumo/api_utils.py | Python | PermissionMod | PermissionMod | 260 | 287 | 260 | 260 | 7779f65fc0d80c9f4356fb2276becae77346de93 | bigcode/the-stack | train |
cf67066ff0418b1d362ddcfa | train | class | class GenericAPIException(APIException):
"""Generic Exception, since DRF doesn't provide one.
DRF allows views to throw subclasses of APIException to cause non-200
status codes to be sent back to API consumers. These subclasses are
expected to have a ``status_code`` and ``detail`` property.
DRF do... | class GenericAPIException(APIException):
| """Generic Exception, since DRF doesn't provide one.
DRF allows views to throw subclasses of APIException to cause non-200
status codes to be sent back to API consumers. These subclasses are
expected to have a ``status_code`` and ``detail`` property.
DRF doesn't give a generic way to make an objec... | Failed
from rest_framework.filters import BaseFilterBackend
from rest_framework.renderers import JSONRenderer as DRFJSONRenderer
from kitsune.sumo.utils import uselocale
from kitsune.sumo.urlresolvers import get_best_language
from kitsune.users.models import Profile
class GenericAPIException(APIException):
| 64 | 64 | 165 | 7 | 56 | navgurukul-shivani18/kitsune | kitsune/sumo/api_utils.py | Python | GenericAPIException | GenericAPIException | 19 | 35 | 19 | 19 | 6745ba7ce7c41ca7d6ffa9038f7e2e926f5a2d46 | bigcode/the-stack | train |
b9ffad8418312e195e85fd79 | train | class | class InactiveSessionAuthentication(SessionAuthentication):
"""
Use Django's session framework for authentication.
Allows inactive users.
"""
def authenticate(self, request):
"""
Returns a `User` if the request session currently has a logged in user.
Otherwise returns `None... | class InactiveSessionAuthentication(SessionAuthentication):
| """
Use Django's session framework for authentication.
Allows inactive users.
"""
def authenticate(self, request):
"""
Returns a `User` if the request session currently has a logged in user.
Otherwise returns `None`.
"""
# Get the underlying HttpRequest obj... | .context.get('request')
for Perm in permissions:
perm = Perm()
if not perm.has_permission(request, self):
return False
if not perm.has_object_permission(request, self, obj):
return False
return True
retu... | 64 | 64 | 206 | 8 | 55 | navgurukul-shivani18/kitsune | kitsune/sumo/api_utils.py | Python | InactiveSessionAuthentication | InactiveSessionAuthentication | 290 | 323 | 290 | 290 | 5bb827985a815fbc3f909f23e6742fdf86e95216 | bigcode/the-stack | train |
06ce23e5753fee77ae240cce | train | class | class SplitSourceField(fields.Field):
"""
This allows reading from one field and writing to another under the same
name in the serialized/deserialized data.
A serializer can use this field like this:
class FooSerializer(serializers.ModelSerializer):
content = SplitSourceField(read_... | class SplitSourceField(fields.Field):
| """
This allows reading from one field and writing to another under the same
name in the serialized/deserialized data.
A serializer can use this field like this:
class FooSerializer(serializers.ModelSerializer):
content = SplitSourceField(read_source='content_parsed', write_source=... | .CharField
read_only = True
def __init__(self, l10n_context=None, **kwargs):
self.l10n_context = l10n_context
super(LocalizedCharField, self).__init__(**kwargs)
def to_native(self, value):
value = super(LocalizedCharField, self).from_native(value)
locale = self.context.get(... | 119 | 119 | 399 | 7 | 112 | navgurukul-shivani18/kitsune | kitsune/sumo/api_utils.py | Python | SplitSourceField | SplitSourceField | 91 | 142 | 91 | 91 | 67b67e04f67bf00cb7e5908b9d226ab9bd5aa844 | bigcode/the-stack | train |
dff42dde7ad46b27a79508d5 | train | class | class LocalizedCharField(fields.CharField):
"""
This is a field for DRF that localizes itself based on the current locale.
There should be a locale field on the serialization context. If the view
that uses this serializer subclasses LocaleNegotiationMixin, the context
will get a locale field automa... | class LocalizedCharField(fields.CharField):
| """
This is a field for DRF that localizes itself based on the current locale.
There should be a locale field on the serialization context. If the view
that uses this serializer subclasses LocaleNegotiationMixin, the context
will get a locale field automatically.
A serializer can use this fiel... | def get_locale(self):
accept_language = self.request.META.get('HTTP_ACCEPT_LANGUAGE', '')
lang = get_best_language(accept_language)
return lang or settings.WIKI_DEFAULT_LANGUAGE
def get_serializer_context(self):
context = super(LocaleNegotiationMixin, self).get_serializer_contex... | 86 | 86 | 287 | 9 | 76 | navgurukul-shivani18/kitsune | kitsune/sumo/api_utils.py | Python | LocalizedCharField | LocalizedCharField | 52 | 88 | 52 | 52 | 997e1e9d9ad4cdde7f16ed2cf66a9394edb7a837 | bigcode/the-stack | train |
6074511e7c7c8ccd87d0fdce | train | class | class InequalityFilterBackend(BaseFilterBackend):
"""A filter backend that allows for field__gt style filtering."""
def filter_queryset(self, request, queryset, view):
filter_fields = getattr(view, 'filter_fields', [])
for key, value in request.query_params.items():
splits = key.sp... | class InequalityFilterBackend(BaseFilterBackend):
| """A filter backend that allows for field__gt style filtering."""
def filter_queryset(self, request, queryset, view):
filter_fields = getattr(view, 'filter_fields', [])
for key, value in request.query_params.items():
splits = key.split('__')
if len(splits) != 2:
... | content_type.model}
if isinstance(value, User):
value = Profile.objects.get(user=value)
if hasattr(value, 'get_serializer'):
SerializerClass = value.get_serializer(self.serializer_type)
else:
SerializerClass = _IDSerializer
data.update(SerializerCla... | 75 | 75 | 251 | 9 | 65 | navgurukul-shivani18/kitsune | kitsune/sumo/api_utils.py | Python | InequalityFilterBackend | InequalityFilterBackend | 190 | 223 | 190 | 190 | c0af5c92cb32c65913bfcf969491ac397da020ed | bigcode/the-stack | train |
8f62e7b880ad4c53a2f11a2e | train | class | class ImageUrlField(fields.ImageField):
"""An image field that serializes to a url instead of a file name.
Additionally, if there is no file associated with this image, this
returns ``None`` instead of erroring.
"""
def to_native(self, value):
try:
return value.url
exce... | class ImageUrlField(fields.ImageField):
| """An image field that serializes to a url instead of a file name.
Additionally, if there is no file associated with this image, this
returns ``None`` instead of erroring.
"""
def to_native(self, value):
try:
return value.url
except ValueError:
return None
| CSRF validation for session based authentication.
"""
reason = CSRFCheck().process_view(request, None, (), {})
if reason:
# CSRF failed, bail with explicit error message
raise AuthenticationFailed('CSRF Failed: %s' % reason)
class ImageUrlField(fields.ImageField):
| 64 | 64 | 77 | 8 | 56 | navgurukul-shivani18/kitsune | kitsune/sumo/api_utils.py | Python | ImageUrlField | ImageUrlField | 326 | 337 | 326 | 326 | 498e6c20389bb5c0325e5001cec3af6a661a864b | bigcode/the-stack | train |
8a39abd8f653cdb0d3b8ce62 | train | class | class TestInit:
base.set_log_level()
def test_good_parameter_strings(self):
good_tests = {
"param:value": [{"param": "value"}],
"param_test-value.with.dots/and/slash:value-test_value.with.dots/and/slash": [{"param_test-value.with.dots/and/slash": "value-test_value.with.dots/and/... | class TestInit:
| base.set_log_level()
def test_good_parameter_strings(self):
good_tests = {
"param:value": [{"param": "value"}],
"param_test-value.with.dots/and/slash:value-test_value.with.dots/and/slash": [{"param_test-value.with.dots/and/slash": "value-test_value.with.dots/and/slash"}],
... | from typing import List, Dict
from mason.definitions import from_root
from mason.operators.operator import Operator
from mason.parameters.operator_parameters import OperatorParameters
from mason.parameters.validated_parameters import ValidatedParameters
from mason.parameters.workflow_parameters import WorkflowParamete... | 66 | 165 | 553 | 4 | 61 | kyprifog/mason | mason/test/parameters_test.py | Python | TestInit | TestInit | 10 | 59 | 10 | 10 | 895b8f06d9d9d917580dfa3e8dd606f458741e5d | bigcode/the-stack | train |
ff8cf47e01716ce16aa58d78 | train | class | class TestValidation:
def test_parameter_validation(self):
tests: Dict[str, List[List[str]]] = {
"param:value": [["param"], [], ["value"], [], ["value"]],
"param:value,other_param:stuff": [["other_param"], ["param"], ["stuff"], ["value"], ["value", "stuff"]]
}
for pa... | class TestValidation:
| def test_parameter_validation(self):
tests: Dict[str, List[List[str]]] = {
"param:value": [["param"], [], ["value"], [], ["value"]],
"param:value,other_param:stuff": [["other_param"], ["param"], ["stuff"], ["value"], ["value", "stuff"]]
}
for param_string, results in... | def test_bad_workflow_parameters(self):
params = WorkflowParameters(parameter_path=from_root("/test/support/parameters/bad_workflow_params.yaml"))
assert(f"Invalid parameters: Schema error {from_root('/parameters/workflow_schema.json')}: " in params.invalid[0].reason)
class TestValidation:
| 64 | 64 | 195 | 4 | 60 | kyprifog/mason | mason/test/parameters_test.py | Python | TestValidation | TestValidation | 61 | 75 | 61 | 61 | 47ad4d08c6ead4855611cd94f13acce1f3401dcd | bigcode/the-stack | train |
88f0797c0147634c22c8163a | train | function | def main():
# Parse Arguments
parser = argparse.ArgumentParser(
description='Uses MDAnalysis and PointNet to identify largest cluster of solid-like atoms')
parser.add_argument('--weights', help='folder containing network weights to use', type=str, required=True)
parser.add_argument('--nclass', h... | def main():
# Parse Arguments
| parser = argparse.ArgumentParser(
description='Uses MDAnalysis and PointNet to identify largest cluster of solid-like atoms')
parser.add_argument('--weights', help='folder containing network weights to use', type=str, required=True)
parser.add_argument('--nclass', help='number of classes', type=int,... | # Ryan DeFever
# Sarupria Research Group
# Clemson University
# 2019 Jun 10
import argparse
import os
import sys
import MDAnalysis as mda
import networkx as nx
import numpy as np
# For PointNet modules
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(BASE_D... | 117 | 256 | 1,098 | 8 | 108 | jkelowitt/GenStrIde | scripts/mda_cluster.py | Python | main | main | 23 | 129 | 23 | 24 | 396be6586a1b0c91993bc025e1764fa131e93fe2 | bigcode/the-stack | train |
01560a41d724872cc30212be | train | class | class HttpProxy:
"""Forwards HTTP requests to an application instance."""
def __init__(self, host, port, instance_died_unexpectedly,
instance_logs_getter, error_handler_file, prior_error=None):
"""Initializer for HttpProxy.
Args:
host: A hostname or an IP address of where application i... | class HttpProxy:
| """Forwards HTTP requests to an application instance."""
def __init__(self, host, port, instance_died_unexpectedly,
instance_logs_getter, error_handler_file, prior_error=None):
"""Initializer for HttpProxy.
Args:
host: A hostname or an IP address of where application instance is
... | Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | 256 | 256 | 1,682 | 4 | 251 | yc550370460/google_app_engine | google/appengine/tools/devappserver2/http_proxy.py | Python | HttpProxy | HttpProxy | 36 | 230 | 36 | 36 | a9ab23bbf071a2102dea838ecc91fdf606e34c40 | bigcode/the-stack | train |
648340f8cdb75f0bf305b638 | train | function | def inflatedart(l, n):
if n == 0:
px, py = pos()
h, x, y = int(heading()), round(px,3), round(py,3)
tiledict[(h,x,y)] = False
return
fl = f * l
inflatekite(fl, n-1)
lt(36)
fd(l)
rt(180)
inflatedart(fl, n-1)
lt(54)
fd(l*d)
rt(126)
inflatedart(fl... | def inflatedart(l, n):
| if n == 0:
px, py = pos()
h, x, y = int(heading()), round(px,3), round(py,3)
tiledict[(h,x,y)] = False
return
fl = f * l
inflatekite(fl, n-1)
lt(36)
fd(l)
rt(180)
inflatedart(fl, n-1)
lt(54)
fd(l*d)
rt(126)
inflatedart(fl, n-1)
fd(l)
rt... | n-1)
lt(18)
fd(l*d)
rt(162)
inflatekite(fl, n-1)
lt(36)
fd(l)
rt(180)
inflatedart(fl, n-1)
lt(36)
def inflatedart(l, n):
| 64 | 64 | 129 | 7 | 57 | kappaIO-Dev/kappaIO-sdk-armhf-crosscompile | rootfs/usr/lib/python3.2/turtledemo/penrose.py | Python | inflatedart | inflatedart | 71 | 88 | 71 | 71 | 0322c06cea3142313a4d482df3cd82693db4347b | bigcode/the-stack | train |
bda84a2528b36060e03a16ff | train | function | def makeshapes():
tracer(0)
begin_poly()
kite(100)
end_poly()
register_shape("kite", get_poly())
begin_poly()
dart(100)
end_poly()
register_shape("dart", get_poly())
tracer(1)
| def makeshapes():
| tracer(0)
begin_poly()
kite(100)
end_poly()
register_shape("kite", get_poly())
begin_poly()
dart(100)
end_poly()
register_shape("dart", get_poly())
tracer(1)
| , 0))
stamp()
def sun(l, n):
for i in range(5):
inflatekite(l, n)
lt(72)
def star(l,n):
for i in range(5):
inflatedart(l, n)
lt(72)
def makeshapes():
| 64 | 64 | 59 | 5 | 59 | kappaIO-Dev/kappaIO-sdk-armhf-crosscompile | rootfs/usr/lib/python3.2/turtledemo/penrose.py | Python | makeshapes | makeshapes | 116 | 126 | 116 | 116 | da66d9812b1da0320dca03ed7b2aa0ad20a674f0 | bigcode/the-stack | train |
685b8fdda2fce2a39cd185f2 | train | function | def kite(l):
fl = f * l
lt(36)
fd(l)
rt(108)
fd(fl)
rt(36)
fd(fl)
rt(108)
fd(l)
rt(144)
| def kite(l):
| fl = f * l
lt(36)
fd(l)
rt(108)
fd(fl)
rt(36)
fd(fl)
rt(108)
fd(l)
rt(144)
| -----------
"""
from turtle import *
from math import cos, pi
from time import clock, sleep
f = (5**0.5-1)/2.0 # (sqrt(5)-1)/2 -- golden ratio
d = 2 * cos(3*pi/10)
def kite(l):
| 64 | 64 | 52 | 4 | 60 | kappaIO-Dev/kappaIO-sdk-armhf-crosscompile | rootfs/usr/lib/python3.2/turtledemo/penrose.py | Python | kite | kite | 25 | 35 | 25 | 25 | 3dbca333a1a4bb69ef15b73e10d60f1e7c8021a8 | bigcode/the-stack | train |
bec1529ca4e6f66494d9b28b | train | function | def dart(l):
fl = f * l
lt(36)
fd(l)
rt(144)
fd(fl)
lt(36)
fd(fl)
rt(144)
fd(l)
rt(144)
| def dart(l):
| fl = f * l
lt(36)
fd(l)
rt(144)
fd(fl)
lt(36)
fd(fl)
rt(144)
fd(l)
rt(144)
| * cos(3*pi/10)
def kite(l):
fl = f * l
lt(36)
fd(l)
rt(108)
fd(fl)
rt(36)
fd(fl)
rt(108)
fd(l)
rt(144)
def dart(l):
| 64 | 64 | 52 | 4 | 60 | kappaIO-Dev/kappaIO-sdk-armhf-crosscompile | rootfs/usr/lib/python3.2/turtledemo/penrose.py | Python | dart | dart | 37 | 47 | 37 | 37 | 659e4c3495497d326d175f473ba332fbfc5a800b | bigcode/the-stack | train |
1998594f6c6861db7f162f70 | train | function | def star(l,n):
for i in range(5):
inflatedart(l, n)
lt(72)
| def star(l,n):
| for i in range(5):
inflatedart(l, n)
lt(72)
| 75, 0))
else:
shape("dart")
color("black", (0.75, 0, 0))
stamp()
def sun(l, n):
for i in range(5):
inflatekite(l, n)
lt(72)
def star(l,n):
| 64 | 64 | 25 | 5 | 59 | kappaIO-Dev/kappaIO-sdk-armhf-crosscompile | rootfs/usr/lib/python3.2/turtledemo/penrose.py | Python | star | star | 111 | 114 | 111 | 111 | a16bc7ed065fec6b7c7085554331127825f7f797 | bigcode/the-stack | train |
aea1790e434dd6918304818a | train | function | def start():
reset()
ht()
pu()
makeshapes()
resizemode("user")
| def start():
| reset()
ht()
pu()
makeshapes()
resizemode("user")
| 72)
def makeshapes():
tracer(0)
begin_poly()
kite(100)
end_poly()
register_shape("kite", get_poly())
begin_poly()
dart(100)
end_poly()
register_shape("dart", get_poly())
tracer(1)
def start():
| 64 | 64 | 24 | 3 | 61 | kappaIO-Dev/kappaIO-sdk-armhf-crosscompile | rootfs/usr/lib/python3.2/turtledemo/penrose.py | Python | start | start | 128 | 133 | 128 | 128 | 6adac27ba23d5defd49448632db9ca2d51ed5b96 | bigcode/the-stack | train |
15bf6539faab2ae3edfa8dd3 | train | function | def main():
#title("Penrose-tiling with kites and darts.")
mode("logo")
bgcolor(0.3, 0.3, 0)
demo(sun)
sleep(2)
demo(star)
pencolor("black")
goto(0,-200)
pencolor(0.7,0.7,1)
write("Please wait...",
align="center", font=('Arial Black', 36, 'bold'))
test(600, 8, start... | def main():
#title("Penrose-tiling with kites and darts.")
| mode("logo")
bgcolor(0.3, 0.3, 0)
demo(sun)
sleep(2)
demo(star)
pencolor("black")
goto(0,-200)
pencolor(0.7,0.7,1)
write("Please wait...",
align="center", font=('Arial Black', 36, 'bold'))
test(600, 8, startpos=(70, 117))
return "Done"
| i in range(8):
a = clock()
test(300, i, fun)
b = clock()
t = b - a
if t < 2:
sleep(2 - t)
def main():
#title("Penrose-tiling with kites and darts.")
| 64 | 64 | 123 | 18 | 46 | kappaIO-Dev/kappaIO-sdk-armhf-crosscompile | rootfs/usr/lib/python3.2/turtledemo/penrose.py | Python | main | main | 164 | 177 | 164 | 165 | 082381a123197f9c2470587034695c1ec605bee1 | bigcode/the-stack | train |
7c2297761f6ff7c169fdbd7f | train | function | def sun(l, n):
for i in range(5):
inflatekite(l, n)
lt(72)
| def sun(l, n):
| for i in range(5):
inflatekite(l, n)
lt(72)
| setheading(h)
if tiledict[k]:
shape("kite")
color("black", (0, 0.75, 0))
else:
shape("dart")
color("black", (0.75, 0, 0))
stamp()
def sun(l, n):
| 64 | 64 | 27 | 6 | 58 | kappaIO-Dev/kappaIO-sdk-armhf-crosscompile | rootfs/usr/lib/python3.2/turtledemo/penrose.py | Python | sun | sun | 106 | 109 | 106 | 106 | b042f28a006aada45a9addda34cafafb42de45f6 | bigcode/the-stack | train |
6b9994a6a4c03e1c5cd21602 | train | function | def inflatekite(l, n):
if n == 0:
px, py = pos()
h, x, y = int(heading()), round(px,3), round(py,3)
tiledict[(h,x,y)] = True
return
fl = f * l
lt(36)
inflatedart(fl, n-1)
fd(l)
rt(144)
inflatekite(fl, n-1)
lt(18)
fd(l*d)
rt(162)
inflatekite(fl,... | def inflatekite(l, n):
| if n == 0:
px, py = pos()
h, x, y = int(heading()), round(px,3), round(py,3)
tiledict[(h,x,y)] = True
return
fl = f * l
lt(36)
inflatedart(fl, n-1)
fd(l)
rt(144)
inflatekite(fl, n-1)
lt(18)
fd(l*d)
rt(162)
inflatekite(fl, n-1)
lt(36)
fd... | rt(144)
def dart(l):
fl = f * l
lt(36)
fd(l)
rt(144)
fd(fl)
lt(36)
fd(fl)
rt(144)
fd(l)
rt(144)
def inflatekite(l, n):
| 64 | 64 | 150 | 8 | 56 | kappaIO-Dev/kappaIO-sdk-armhf-crosscompile | rootfs/usr/lib/python3.2/turtledemo/penrose.py | Python | inflatekite | inflatekite | 49 | 69 | 49 | 49 | 2dda64264802d75068ff2b18abadf35ae5b9ea87 | bigcode/the-stack | train |
596ebe49182b2d6a641133b7 | train | function | def demo(fun=sun):
start()
for i in range(8):
a = clock()
test(300, i, fun)
b = clock()
t = b - a
if t < 2:
sleep(2 - t)
| def demo(fun=sun):
| start()
for i in range(8):
a = clock()
test(300, i, fun)
b = clock()
t = b - a
if t < 2:
sleep(2 - t)
| nk = len([x for x in tiledict if tiledict[x]])
nd = len([x for x in tiledict if not tiledict[x]])
print("%d kites and %d darts = %d pieces." % (nk, nd, nk+nd))
def demo(fun=sun):
| 64 | 64 | 57 | 6 | 58 | kappaIO-Dev/kappaIO-sdk-armhf-crosscompile | rootfs/usr/lib/python3.2/turtledemo/penrose.py | Python | demo | demo | 154 | 162 | 154 | 154 | 1b90940a967dda60c4ffa29475fc2be0bfe0d5b9 | bigcode/the-stack | train |
c172e63898be5ceca6efbaa3 | train | function | def draw(l, n, th=2):
clear()
l = l * f**n
shapesize(l/100.0, l/100.0, th)
for k in tiledict:
h, x, y = k
setpos(x, y)
setheading(h)
if tiledict[k]:
shape("kite")
color("black", (0, 0.75, 0))
else:
shape("dart")
colo... | def draw(l, n, th=2):
| clear()
l = l * f**n
shapesize(l/100.0, l/100.0, th)
for k in tiledict:
h, x, y = k
setpos(x, y)
setheading(h)
if tiledict[k]:
shape("kite")
color("black", (0, 0.75, 0))
else:
shape("dart")
color("black", (0.75, 0, 0... | (36)
fd(l)
rt(180)
inflatedart(fl, n-1)
lt(54)
fd(l*d)
rt(126)
inflatedart(fl, n-1)
fd(l)
rt(144)
def draw(l, n, th=2):
| 64 | 64 | 121 | 10 | 54 | kappaIO-Dev/kappaIO-sdk-armhf-crosscompile | rootfs/usr/lib/python3.2/turtledemo/penrose.py | Python | draw | draw | 90 | 104 | 90 | 90 | 49a6d9d564dda503e2cd37db2f43f9dd499ea69c | bigcode/the-stack | train |
e1ea31cf44792f2c183b40dc | train | function | def test(l=200, n=4, fun=sun, startpos=(0,0), th=2):
global tiledict
goto(startpos)
setheading(0)
tiledict = {}
a = clock()
tracer(0)
fun(l, n)
b = clock()
draw(l, n, th)
tracer(1)
c = clock()
print("Calculation: %7.4f s" % (b - a))
print("Drawing: %7.4f s" % (c - ... | def test(l=200, n=4, fun=sun, startpos=(0,0), th=2):
| global tiledict
goto(startpos)
setheading(0)
tiledict = {}
a = clock()
tracer(0)
fun(l, n)
b = clock()
draw(l, n, th)
tracer(1)
c = clock()
print("Calculation: %7.4f s" % (b - a))
print("Drawing: %7.4f s" % (c - b))
print("Together: %7.4f s" % (c - a))
nk =... | ()
register_shape("dart", get_poly())
tracer(1)
def start():
reset()
ht()
pu()
makeshapes()
resizemode("user")
def test(l=200, n=4, fun=sun, startpos=(0,0), th=2):
| 64 | 64 | 199 | 25 | 39 | kappaIO-Dev/kappaIO-sdk-armhf-crosscompile | rootfs/usr/lib/python3.2/turtledemo/penrose.py | Python | test | test | 135 | 152 | 135 | 135 | 6bfeb8566fa85181745347b7a758e4ae31201953 | bigcode/the-stack | train |
1eb62a6f00a050a1184b8320 | train | class | class UnitTest(unittest.TestCase):
# ----------------------------------------------------------------------
@classmethod
def setUp(cls):
cls._ti = CustomTypeInfo( lambda item: isinstance(item, str),
lambda item: None if item == "test" else "invalid",
... | class UnitTest(unittest.TestCase):
# ----------------------------------------------------------------------
@classmethod
| def setUp(cls):
cls._ti = CustomTypeInfo( lambda item: isinstance(item, str),
lambda item: None if item == "test" else "invalid",
"Constraints Desc",
)
# -------------------------------------------... | script_fullpath)
# ----------------------------------------------------------------------
with Package.NameInfo(__package__) as ni:
__package__ = ni.created
from ..CustomTypeInfo import *
__package__ = ni.original
# ----------------------------------------------------------------------
cla... | 63 | 64 | 191 | 17 | 46 | davidbrownell/Common_Environment | Libraries/Python/CommonEnvironment/v1.0/CommonEnvironment/TypeInfo/UnitTests/CustomTypeInfo_UnitTest.py | Python | UnitTest | UnitTest | 34 | 57 | 34 | 37 | bb63a4427fdaf5f2336eced25e30706c0eab1fe1 | bigcode/the-stack | train |
e1c745346bf2ee6f7e931ed9 | train | function | def generate_annotations(folds_df,
data_dir,
save_annotations_dir,
percent_no_opacity,
percent_normal,
fold=None):
# Generate annotations for keras-retinanet for each fold
if fold is... | def generate_annotations(folds_df,
data_dir,
save_annotations_dir,
percent_no_opacity,
percent_normal,
fold=None):
# Generate annotations for keras-retinanet for each fold
| if fold is not None:
folds = fold
if type(folds) != list: folds = [folds]
else:
folds = np.unique(folds_df.fold)
for each_fold in folds:
tmp_train_df = folds_df[folds_df.fold != each_fold]
tmp_valid_df = folds_df[folds_df.fold == each_fold]
tmp_train_df["f... | ###########
# IMPORTS #
###########
import pandas as pd
import numpy as np
import os, json
WDIR = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(WDIR, "../../SETTINGS.json")) as f:
SETTINGS_JSON = json.load(f)
#############
# FUNCTIONS #
#############
def generate_annotations(folds_df,
... | 117 | 190 | 636 | 48 | 69 | SurajK7/kaggle-rsna18 | src/etl/9_GeneratePositiveRetinaAnnotations.py | Python | generate_annotations | generate_annotations | 17 | 59 | 17 | 23 | 31c3c56dec95cb0bd8a6842eb0ffa57e15b2862f | bigcode/the-stack | train |
53b9ce6e3ee48083790dce55 | train | function | def _to_json_string(stm, buf):
stm.write('"')
for c in buf:
nc = REV_ESC_MAP.get(c, None)
if nc:
stm.write('\\' + nc)
elif (ord(c) <= 127):
stm.write(str(c))
else:
stm.write('\\u%04x' % ord(c))
stm.write('"')
| def _to_json_string(stm, buf):
| stm.write('"')
for c in buf:
nc = REV_ESC_MAP.get(c, None)
if nc:
stm.write('\\' + nc)
elif (ord(c) <= 127):
stm.write(str(c))
else:
stm.write('\\u%04x' % ord(c))
stm.write('"')
| _list(stm, lst):
seen = 0
stm.write('[')
for elem in lst:
if seen:
stm.write(',')
seen = 1
_to_json_object(stm, elem)
stm.write(']')
def _to_json_string(stm, buf):
| 63 | 64 | 81 | 10 | 54 | Anirban166/tstl | examples/microjson/mutants/AOR_BinOp_mutant_1486201040.py | Python | _to_json_string | _to_json_string | 238 | 248 | 238 | 238 | 26e6d62f8aaba30375337d2f9c0db35d8acd200e | bigcode/the-stack | train |
19bd7fc443859e85e5541eeb | train | function | def _to_json_dict(stm, dct):
seen = 0
stm.write('{')
for key in dct.keys():
if seen:
stm.write(',')
seen = 1
val = dct[key]
if (not (type(key) in (types.StringType, types.UnicodeType))):
key = str(key)
_to_json_string(stm, key)
stm.writ... | def _to_json_dict(stm, dct):
| seen = 0
stm.write('{')
for key in dct.keys():
if seen:
stm.write(',')
seen = 1
val = dct[key]
if (not (type(key) in (types.StringType, types.UnicodeType))):
key = str(key)
_to_json_string(stm, key)
stm.write(':')
_to_json_objec... | (c, None)
if nc:
stm.write('\\' + nc)
elif (ord(c) <= 127):
stm.write(str(c))
else:
stm.write('\\u%04x' % ord(c))
stm.write('"')
def _to_json_dict(stm, dct):
| 64 | 64 | 107 | 11 | 53 | Anirban166/tstl | examples/microjson/mutants/AOR_BinOp_mutant_1486201040.py | Python | _to_json_dict | _to_json_dict | 250 | 263 | 250 | 250 | 1ece3e4900d38f00a666e78e3459d39b99e33bb9 | bigcode/the-stack | train |
c9302abfe04ef8af0a589a75 | train | function | def decode_escape(c, stm):
v = ESC_MAP.get(c, None)
if (v is not None):
return v
elif (c != 'u'):
return c
sv = 12
r = 0
for _ in range(0, 4):
r |= int(stm.next(), 16) << sv
sv -= 4
return unichr(r)
| def decode_escape(c, stm):
| v = ESC_MAP.get(c, None)
if (v is not None):
return v
elif (c != 'u'):
return c
sv = 12
r = 0
for _ in range(0, 4):
r |= int(stm.next(), 16) << sv
sv -= 4
return unichr(r)
| 63
elif (c0 & 248 == 240):
r = c0 & 7 << 18 + nc() & 63 << 12 + nc() & 63 << 6 + nc() & 63
return unichr(r)
def decode_escape(c, stm):
| 64 | 64 | 91 | 7 | 57 | Anirban166/tstl | examples/microjson/mutants/AOR_BinOp_mutant_1486201040.py | Python | decode_escape | decode_escape | 88 | 99 | 88 | 88 | 42c61a9467011723b0387202daba6c3c90ba4b02 | bigcode/the-stack | train |
2ab660bd0af006ff36553c3a | train | function | def _from_json_string(stm):
stm.next()
r = []
while True:
c = stm.next()
if (c == ''):
raiseJSONError(E_TRUNC, stm, stm.pos - 1)
elif (c == '\\'):
c = stm.next()
r.append(decode_escape(c, stm))
elif (c == '"'):
return ''.join(r)... | def _from_json_string(stm):
| stm.next()
r = []
while True:
c = stm.next()
if (c == ''):
raiseJSONError(E_TRUNC, stm, stm.pos - 1)
elif (c == '\\'):
c = stm.next()
r.append(decode_escape(c, stm))
elif (c == '"'):
return ''.join(r)
elif (c > '\x7f'):
... | u'):
return c
sv = 12
r = 0
for _ in range(0, 4):
r |= int(stm.next(), 16) << sv
sv -= 4
return unichr(r)
def _from_json_string(stm):
| 64 | 64 | 114 | 8 | 56 | Anirban166/tstl | examples/microjson/mutants/AOR_BinOp_mutant_1486201040.py | Python | _from_json_string | _from_json_string | 101 | 116 | 101 | 101 | eee05cf56d1b6aa98248744c8f2bfbfc226ba291 | bigcode/the-stack | train |
35622f61cc00f74b18d4e20f | train | class | class JSONError(Exception):
def __init__(self, msg, stm=None, pos=0):
if stm:
msg += ' at position %d, "%s"' % (pos, repr(stm.substr(pos, 32)))
Exception.__init__(self, msg)
| class JSONError(Exception):
| def __init__(self, msg, stm=None, pos=0):
if stm:
msg += ' at position %d, "%s"' % (pos, repr(stm.substr(pos, 32)))
Exception.__init__(self, msg)
| valid JSON data'
E_BADESC = 'bad escape character found'
E_UNSUPP = 'unsupported type "%s" cannot be JSON-encoded'
E_BADFLOAT = 'cannot emit floating point value "%s"'
NEG_INF = float('-inf')
POS_INF = float('inf')
class JSONError(Exception):
| 64 | 64 | 59 | 5 | 59 | Anirban166/tstl | examples/microjson/mutants/AOR_BinOp_mutant_1486201040.py | Python | JSONError | JSONError | 27 | 32 | 27 | 28 | c82d28f4fe265c92e27e4c6cd7b0502df73a9e47 | bigcode/the-stack | train |
413647ede2ceeff2f555b6b1 | train | function | def _from_json_list(stm):
stm.next()
result = []
pos = stm.pos
while True:
stm.skipspaces()
c = stm.peek()
if (c == ''):
raiseJSONError(E_TRUNC, stm, pos)
elif (c == ']'):
stm.next()
return result
elif (c == ','):
st... | def _from_json_list(stm):
| stm.next()
result = []
pos = stm.pos
while True:
stm.skipspaces()
c = stm.peek()
if (c == ''):
raiseJSONError(E_TRUNC, stm, pos)
elif (c == ']'):
stm.next()
return result
elif (c == ','):
stm.next()
resul... | is_float = 1
if (c in ('e', 'E')):
saw_exp = 1
stm.next()
s = stm.substr(pos, stm.pos - pos)
if is_float:
return float(s)
return long(s)
def _from_json_list(stm):
| 64 | 64 | 131 | 8 | 56 | Anirban166/tstl | examples/microjson/mutants/AOR_BinOp_mutant_1486201040.py | Python | _from_json_list | _from_json_list | 146 | 166 | 146 | 146 | 72baf8701a2d81c33e7fc93b7c7215d3e4369759 | bigcode/the-stack | train |
9208eff39bece9f1d7e6f0b8 | train | function | def _from_json_dict(stm):
stm.next()
result = {}
expect_key = 0
pos = stm.pos
while True:
stm.skipspaces()
c = stm.peek()
if (c == ''):
raiseJSONError(E_TRUNC, stm, pos)
if (c in ('}', ',')):
stm.next()
if expect_key:
... | def _from_json_dict(stm):
| stm.next()
result = {}
expect_key = 0
pos = stm.pos
while True:
stm.skipspaces()
c = stm.peek()
if (c == ''):
raiseJSONError(E_TRUNC, stm, pos)
if (c in ('}', ',')):
stm.next()
if expect_key:
raiseJSONError(E_DKEY, s... | == ','):
stm.next()
result.append(_from_json_raw(stm))
continue
elif (not result):
result.append(_from_json_raw(stm))
continue
else:
raiseJSONError(E_MALF, stm, stm.pos)
def _from_json_dict(stm):
| 64 | 64 | 209 | 8 | 56 | Anirban166/tstl | examples/microjson/mutants/AOR_BinOp_mutant_1486201040.py | Python | _from_json_dict | _from_json_dict | 168 | 197 | 168 | 168 | 124763c98b9901739cf00a2c6eacce3ae538f11c | bigcode/the-stack | train |
0e337bb3be6ee829ec27b16b | train | function | def from_json(data):
"\n Converts 'data' which is UTF-8 (or the 7-bit pure ASCII subset) into\n a Python representation. You must pass bytes to this in a str type,\n not unicode.\n "
if (not isinstance(data, str)):
raiseJSONError(E_BYTES)
if (not data):
return None
stm = JSO... | def from_json(data):
| "\n Converts 'data' which is UTF-8 (or the 7-bit pure ASCII subset) into\n a Python representation. You must pass bytes to this in a str type,\n not unicode.\n "
if (not isinstance(data, str)):
raiseJSONError(E_BYTES)
if (not data):
return None
stm = JSONStream(data)
ret... | E_BOOL)
elif (c == 'n'):
return _from_json_fixed(stm, 'null', None, E_NULL)
elif (c in NUMSTART):
return _from_json_number(stm)
raiseJSONError(E_MALF, stm, stm.pos)
def from_json(data):
| 64 | 64 | 97 | 5 | 59 | Anirban166/tstl | examples/microjson/mutants/AOR_BinOp_mutant_1486201040.py | Python | from_json | from_json | 219 | 226 | 219 | 219 | 2aa1a413fdee85cd57f8ec43a3701c0f846b36fd | bigcode/the-stack | train |
60a9cbea7d2b50e724f071ea | train | class | class JSONStream(object):
def __init__(self, data):
self._stm = StringIO.StringIO(data)
@property
def pos(self):
return self._stm.pos
@property
def len(self):
return self._stm.len
def getvalue(self):
return self._stm.getvalue()
def skipspaces(self):
... | class JSONStream(object):
| def __init__(self, data):
self._stm = StringIO.StringIO(data)
@property
def pos(self):
return self._stm.pos
@property
def len(self):
return self._stm.len
def getvalue(self):
return self._stm.getvalue()
def skipspaces(self):
'post-cond: read pointer... | inf')
class JSONError(Exception):
def __init__(self, msg, stm=None, pos=0):
if stm:
msg += ' at position %d, "%s"' % (pos, repr(stm.substr(pos, 32)))
Exception.__init__(self, msg)
class JSONStream(object):
| 66 | 66 | 221 | 5 | 61 | Anirban166/tstl | examples/microjson/mutants/AOR_BinOp_mutant_1486201040.py | Python | JSONStream | JSONStream | 35 | 74 | 35 | 36 | accad0f22e09334d4c9bf422c545175ec27047c4 | bigcode/the-stack | train |
60588158e8778e2447e458d4 | train | function | def _to_json_object(stm, obj):
if isinstance(obj, (types.ListType, types.TupleType)):
_to_json_list(stm, obj)
elif isinstance(obj, types.BooleanType):
if obj:
stm.write('true')
else:
stm.write('false')
elif isinstance(obj, types.FloatType):
if (not (NE... | def _to_json_object(stm, obj):
| if isinstance(obj, (types.ListType, types.TupleType)):
_to_json_list(stm, obj)
elif isinstance(obj, types.BooleanType):
if obj:
stm.write('true')
else:
stm.write('false')
elif isinstance(obj, types.FloatType):
if (not (NEG_INF < obj < POS_INF)):
... | 1
val = dct[key]
if (not (type(key) in (types.StringType, types.UnicodeType))):
key = str(key)
_to_json_string(stm, key)
stm.write(':')
_to_json_object(stm, val)
stm.write('}')
def _to_json_object(stm, obj):
| 75 | 75 | 253 | 10 | 65 | Anirban166/tstl | examples/microjson/mutants/AOR_BinOp_mutant_1486201040.py | Python | _to_json_object | _to_json_object | 265 | 290 | 265 | 265 | e254c73be1496c59fee61d7e2fd757e4ad464db7 | bigcode/the-stack | train |
11d94bcb479b4c8ff462b954 | train | function | def _from_json_raw(stm):
while True:
stm.skipspaces()
c = stm.peek()
if (c == '"'):
return _from_json_string(stm)
elif (c == '{'):
return _from_json_dict(stm)
elif (c == '['):
return _from_json_list(stm)
elif (c == 't'):
... | def _from_json_raw(stm):
| while True:
stm.skipspaces()
c = stm.peek()
if (c == '"'):
return _from_json_string(stm)
elif (c == '{'):
return _from_json_dict(stm)
elif (c == '['):
return _from_json_list(stm)
elif (c == 't'):
return _from_json_fixed(... | Error(E_COLON, stm, stm.pos)
stm.skipspaces()
val = _from_json_raw(stm)
result[key] = val
expect_key = 0
continue
raiseJSONError(E_MALF, stm, stm.pos)
def _from_json_raw(stm):
| 64 | 64 | 177 | 8 | 56 | Anirban166/tstl | examples/microjson/mutants/AOR_BinOp_mutant_1486201040.py | Python | _from_json_raw | _from_json_raw | 199 | 217 | 199 | 199 | 46db57c05930293ff29b4f3ac96be5993fecb78f | bigcode/the-stack | train |
d1d20eaab1f5826afa4b75bf | train | function | def _decode_utf8(c0, stm):
c0 = ord(c0)
r = 65533
nc = stm.next_ord
if (c0 & 224 == 192):
r = c0 & 31 << 6 - nc() & 63
elif (c0 & 240 == 224):
r = c0 & 15 << 12 + nc() & 63 << 6 + nc() & 63
elif (c0 & 248 == 240):
r = c0 & 7 << 18 + nc() & 63 << 12 + nc() & 63 << 6 + nc()... | def _decode_utf8(c0, stm):
| c0 = ord(c0)
r = 65533
nc = stm.next_ord
if (c0 & 224 == 192):
r = c0 & 31 << 6 - nc() & 63
elif (c0 & 240 == 224):
r = c0 & 15 << 12 + nc() & 63 << 6 + nc() & 63
elif (c0 & 248 == 240):
r = c0 & 7 << 18 + nc() & 63 << 12 + nc() & 63 << 6 + nc() & 63
return unichr(r)
| ):
return ord(self.next())
def peek(self):
if (self.pos == self.len):
return ''
return self.getvalue()[self.pos]
def substr(self, pos, length):
return self.getvalue()[pos:pos + length]
def _decode_utf8(c0, stm):
| 64 | 64 | 156 | 10 | 54 | Anirban166/tstl | examples/microjson/mutants/AOR_BinOp_mutant_1486201040.py | Python | _decode_utf8 | _decode_utf8 | 76 | 86 | 76 | 76 | eec28546c752eb5c8d6a3f9e801e7bc5146327e5 | bigcode/the-stack | train |
26943961e124e26b1013c55e | train | function | def to_json(obj):
"\n Converts 'obj' to an ASCII JSON string representation.\n "
stm = StringIO.StringIO('')
_to_json_object(stm, obj)
return stm.getvalue()
| def to_json(obj):
| "\n Converts 'obj' to an ASCII JSON string representation.\n "
stm = StringIO.StringIO('')
_to_json_object(stm, obj)
return stm.getvalue()
| elif hasattr(obj, '__unicode__'):
_to_json_string(stm, obj.__unicode__())
elif hasattr(obj, '__str__'):
_to_json_string(stm, obj.__str__())
else:
raiseJSONError(E_UNSUPP % type(obj))
def to_json(obj):
| 64 | 64 | 47 | 5 | 59 | Anirban166/tstl | examples/microjson/mutants/AOR_BinOp_mutant_1486201040.py | Python | to_json | to_json | 292 | 296 | 292 | 292 | 4315fd2c67c8a42aa1d4f14353131ba23a90e7f2 | bigcode/the-stack | train |
93736262e50e017054345f28 | train | function | def _to_json_list(stm, lst):
seen = 0
stm.write('[')
for elem in lst:
if seen:
stm.write(',')
seen = 1
_to_json_object(stm, elem)
stm.write(']')
| def _to_json_list(stm, lst):
| seen = 0
stm.write('[')
for elem in lst:
if seen:
stm.write(',')
seen = 1
_to_json_object(stm, elem)
stm.write(']')
| a str type,\n not unicode.\n "
if (not isinstance(data, str)):
raiseJSONError(E_BYTES)
if (not data):
return None
stm = JSONStream(data)
return _from_json_raw(stm)
def _to_json_list(stm, lst):
| 64 | 64 | 57 | 10 | 54 | Anirban166/tstl | examples/microjson/mutants/AOR_BinOp_mutant_1486201040.py | Python | _to_json_list | _to_json_list | 228 | 236 | 228 | 228 | 70263c9dc4e7fd085e4bf355b98917e0b1fcab9c | bigcode/the-stack | train |
d7d69f98e6561b85efeaa9f8 | train | function | def _from_json_number(stm):
is_float = 0
saw_exp = 0
pos = stm.pos
while True:
c = stm.peek()
if (c not in NUMCHARS):
break
elif ((c == '-') and (not saw_exp)):
pass
elif (c in ('.', 'e', 'E')):
is_float = 1
if (c in ('e', '... | def _from_json_number(stm):
| is_float = 0
saw_exp = 0
pos = stm.pos
while True:
c = stm.peek()
if (c not in NUMCHARS):
break
elif ((c == '-') and (not saw_exp)):
pass
elif (c in ('.', 'e', 'E')):
is_float = 1
if (c in ('e', 'E')):
saw_ex... | from_json_fixed(stm, expected, value, errmsg):
off = len(expected)
pos = stm.pos
if (stm.substr(pos, off) == expected):
stm.next(off)
return value
raiseJSONError(errmsg, stm, pos)
def _from_json_number(stm):
| 64 | 64 | 136 | 8 | 56 | Anirban166/tstl | examples/microjson/mutants/AOR_BinOp_mutant_1486201040.py | Python | _from_json_number | _from_json_number | 126 | 144 | 126 | 126 | 4b3cc05b1f0f3b896442a443af3ed0d277a29691 | bigcode/the-stack | train |
dc00402877c52fe667d09ca1 | train | function | def _from_json_fixed(stm, expected, value, errmsg):
off = len(expected)
pos = stm.pos
if (stm.substr(pos, off) == expected):
stm.next(off)
return value
raiseJSONError(errmsg, stm, pos)
| def _from_json_fixed(stm, expected, value, errmsg):
| off = len(expected)
pos = stm.pos
if (stm.substr(pos, off) == expected):
stm.next(off)
return value
raiseJSONError(errmsg, stm, pos)
| .append(decode_escape(c, stm))
elif (c == '"'):
return ''.join(r)
elif (c > '\x7f'):
r.append(_decode_utf8(c, stm))
else:
r.append(c)
def _from_json_fixed(stm, expected, value, errmsg):
| 64 | 64 | 58 | 14 | 50 | Anirban166/tstl | examples/microjson/mutants/AOR_BinOp_mutant_1486201040.py | Python | _from_json_fixed | _from_json_fixed | 118 | 124 | 118 | 118 | f0944499869cdadf859637db1b9d3f47dae267cd | bigcode/the-stack | train |
8d607274bf771a4def0a0b5c | train | function | def kbdInput(cmdQ):
'''
read keyboard input, run as backround-thread to aviod blocking
'''
# 1st, remove pyhton 2 vs. python 3 incompatibility for keyboard input
if sys.version_info[:2] <=(2,7):
get_input = raw_input
else:
get_input = input
while ACTIVE:
kbdtxt = get_input(20*' ' + 'type -... | def kbdInput(cmdQ):
| '''
read keyboard input, run as backround-thread to aviod blocking
'''
# 1st, remove pyhton 2 vs. python 3 incompatibility for keyboard input
if sys.version_info[:2] <=(2,7):
get_input = raw_input
else:
get_input = input
while ACTIVE:
kbdtxt = get_input(20*' ' + 'type -> P(ause), R(esume),... | __future__ import absolute_import
import sys, time, yaml, numpy as np, threading, multiprocessing as mp
# import relevant pieces from picodaqa
import picodaqa.picoConfig
from picodaqa.mpDataGraphs import mpDataGraphs
# helper functions
def kbdInput(cmdQ):
| 64 | 64 | 134 | 7 | 56 | GuenterQuast/picoDAQ | examples/runDataGraphs.py | Python | kbdInput | kbdInput | 22 | 35 | 22 | 22 | 9392b4f814156628b5dccb22414bfca6aaf04b0d | bigcode/the-stack | train |
8bcad757924bd2a5f5f67d9f | train | function | def stop_processes(proclst):
'''
Close all running processes at end of run
'''
for p in proclst: # stop all sub-processes
if p.is_alive():
print(' terminating '+p.name)
if p.is_alive(): p.terminate()
time.sleep(1.)
| def stop_processes(proclst):
| '''
Close all running processes at end of run
'''
for p in proclst: # stop all sub-processes
if p.is_alive():
print(' terminating '+p.name)
if p.is_alive(): p.terminate()
time.sleep(1.)
|
while ACTIVE:
kbdtxt = get_input(20*' ' + 'type -> P(ause), R(esume), E(nd) or s(ave) + <ret> ')
cmdQ.put(kbdtxt)
kbdtxt = ''
def stop_processes(proclst):
| 64 | 64 | 67 | 8 | 56 | GuenterQuast/picoDAQ | examples/runDataGraphs.py | Python | stop_processes | stop_processes | 37 | 45 | 37 | 37 | 256be3f5a1e9359a61f81286c68754b79beb102f | bigcode/the-stack | train |
04dbb06c83ab1250873faea5 | train | class | class Solution:
def XXX(self, n: int) -> int:
# 递归树, 去重复子问题, 变向斐波那契
# f[1] = 1
# f[2] = 2
# f[3] = f[1] + f[2]
if n<=2:
return n
pre_pre = 1
pre = 2
res = 0
for i in range(3,n+1):
res = pre_pre + pre
pre_pre... | class Solution:
| def XXX(self, n: int) -> int:
# 递归树, 去重复子问题, 变向斐波那契
# f[1] = 1
# f[2] = 2
# f[3] = f[1] + f[2]
if n<=2:
return n
pre_pre = 1
pre = 2
res = 0
for i in range(3,n+1):
res = pre_pre + pre
pre_pre = pre
... | class Solution:
| 3 | 64 | 135 | 3 | 0 | kkcookies99/UAST | Dataset/Leetcode/train/70/569.py | Python | Solution | Solution | 1 | 18 | 1 | 1 | 632e4319807ab61fb3b99bb305ad0f3a83134553 | bigcode/the-stack | train |
1dab573608d1932287533a1d | train | class | class VncAmqpHandle(object):
def __init__(self, sandesh, logger, db_cls, reaction_map, q_name_prefix,
rabbitmq_cfg, host_ip, trace_file=None, timer_obj=None,
register_handler=True):
self.sandesh = sandesh
self.logger = logger
self.db_cls = db_cls
se... | class VncAmqpHandle(object):
| def __init__(self, sandesh, logger, db_cls, reaction_map, q_name_prefix,
rabbitmq_cfg, host_ip, trace_file=None, timer_obj=None,
register_handler=True):
self.sandesh = sandesh
self.logger = logger
self.db_cls = db_cls
self.reaction_map = reaction_map... | from __future__ import unicode_literals
from future import standard_library
standard_library.install_aliases()
from builtins import object
import socket
import gevent
from six import StringIO
from pprint import pformat
from requests.exceptions import ConnectionError
from cfgm_common.utils import cgitb_hook
from cfgm_c... | 131 | 256 | 1,937 | 8 | 122 | hamzazafar/contrail-controller | src/config/common/cfgm_common/vnc_amqp.py | Python | VncAmqpHandle | VncAmqpHandle | 19 | 256 | 19 | 20 | fd351018f317e3aac192eed522734ae9ffa1258d | bigcode/the-stack | train |
af8db249402283852c963e86 | train | function | def parse_css_data():
"""
Returns a dictionary containing values associated to their property names
"""
props = {}
for names, values in PROPERTY_DICT.items():
# Determine which values are available for the current property name
allowed_values = []
for value in values:
... | def parse_css_data():
| """
Returns a dictionary containing values associated to their property names
"""
props = {}
for names, values in PROPERTY_DICT.items():
# Determine which values are available for the current property name
allowed_values = []
for value in values:
if value[0] == '<... | ', 'vertical-rl', 'vertical-lr', 'sideways-rl', 'sideways-lr'],
'z-index': ['auto', '<integer>'],
}
def completion_sort_key(v):
if isinstance(v, str):
return v
return v[0]
def parse_css_data():
| 64 | 64 | 166 | 5 | 59 | rvantonder/Packages | CSS/css_completions.py | Python | parse_css_data | parse_css_data | 482 | 504 | 482 | 482 | 55a6ca5bb4a4bc29c47aa63878e22b07d16fef9e | bigcode/the-stack | train |
4b5e67bd0dfea699391250a7 | train | function | def completion_sort_key(v):
if isinstance(v, str):
return v
return v[0]
| def completion_sort_key(v):
| if isinstance(v, str):
return v
return v[0]
| '],
'word-wrap': ['normal', 'break-word'],
'writing-mode': ['horizontal-tb', 'vertical-rl', 'vertical-lr', 'sideways-rl', 'sideways-lr'],
'z-index': ['auto', '<integer>'],
}
def completion_sort_key(v):
| 64 | 64 | 23 | 6 | 58 | rvantonder/Packages | CSS/css_completions.py | Python | completion_sort_key | completion_sort_key | 476 | 479 | 476 | 476 | 3244af4d8e981a9f3a8e1cd748eded262d136d5c | bigcode/the-stack | train |
86d6327324b83b1a32d6ff52 | train | class | class CSSCompletions(sublime_plugin.EventListener):
props = None
regex = None
def on_query_completions(self, view, prefix, locations):
# match inside a CSS document and
# match inside the style attribute of HTML tags, incl. just before the quote that closes the attribute value
css_s... | class CSSCompletions(sublime_plugin.EventListener):
| props = None
regex = None
def on_query_completions(self, view, prefix, locations):
# match inside a CSS document and
# match inside the style attribute of HTML tags, incl. just before the quote that closes the attribute value
css_selector_scope = "source.css - meta.selector.css"
... | ': ['horizontal-tb', 'vertical-rl', 'vertical-lr', 'sideways-rl', 'sideways-lr'],
'z-index': ['auto', '<integer>'],
}
def completion_sort_key(v):
if isinstance(v, str):
return v
return v[0]
def parse_css_data():
"""
Returns a dictionary containing values associated to their property name... | 242 | 242 | 809 | 12 | 229 | rvantonder/Packages | CSS/css_completions.py | Python | CSSCompletions | CSSCompletions | 506 | 594 | 506 | 506 | 8bc296cb9d12da2a42e0ca18ebd0ade59552f6e8 | bigcode/the-stack | train |
f0cf1688ae1db6ae013d8072 | train | class | class Entity(object):
def __init__(self):
# name
self.name = ''
# properties:
self.size = 0.050
# entity can move / be pushed
self.movable = False
# entity collides with others
self.collide = True
# material density (affects mass)
self... | class Entity(object):
| def __init__(self):
# name
self.name = ''
# properties:
self.size = 0.050
# entity can move / be pushed
self.movable = False
# entity collides with others
self.collide = True
# material density (affects mass)
self.density = 25.0
... | # communication utterance
self.c = None
# action of the agent
class Action(object):
def __init__(self):
# physical action
self.u = None
# communication action
self.c = None
# properties and state of physical world entity
class Entity(object):
| 64 | 64 | 154 | 4 | 59 | pedramrabiee/multiagent-particle-envs | multiagent/core.py | Python | Entity | Entity | 27 | 51 | 27 | 27 | 161100bbded4a75edf09c758c8dafe7d3ee39d61 | bigcode/the-stack | train |
3893c7be26191120dafc223c | train | class | class AgentState(EntityState):
def __init__(self):
super(AgentState, self).__init__()
# communication utterance
self.c = None
| class AgentState(EntityState):
| def __init__(self):
super(AgentState, self).__init__()
# communication utterance
self.c = None
| /external base state of all entites
class EntityState(object):
def __init__(self):
# physical position
self.p_pos = None
# physical velocity
self.p_vel = None
# state of agents (including communication and internal/mental state)
class AgentState(EntityState):
| 64 | 64 | 35 | 6 | 58 | pedramrabiee/multiagent-particle-envs | multiagent/core.py | Python | AgentState | AgentState | 12 | 16 | 12 | 12 | df2ddc64a07d22ba2876872a4f1dd544238882e4 | bigcode/the-stack | train |
3c5fb3f1a0c437fddafc1ad1 | train | class | class Action(object):
def __init__(self):
# physical action
self.u = None
# communication action
self.c = None
| class Action(object):
| def __init__(self):
# physical action
self.u = None
# communication action
self.c = None
| self.p_vel = None
# state of agents (including communication and internal/mental state)
class AgentState(EntityState):
def __init__(self):
super(AgentState, self).__init__()
# communication utterance
self.c = None
# action of the agent
class Action(object):
| 64 | 64 | 33 | 4 | 59 | pedramrabiee/multiagent-particle-envs | multiagent/core.py | Python | Action | Action | 19 | 24 | 19 | 19 | 1e627f8309439c05ddce9353ec902d3c9b18cc5c | bigcode/the-stack | train |
0bde6f58e0da1aa8992f4199 | train | class | class EntityState(object):
def __init__(self):
# physical position
self.p_pos = None
# physical velocity
self.p_vel = None
| class EntityState(object):
| def __init__(self):
# physical position
self.p_pos = None
# physical velocity
self.p_vel = None
| import numpy as np
# physical/external base state of all entites
class EntityState(object):
| 21 | 64 | 36 | 5 | 15 | pedramrabiee/multiagent-particle-envs | multiagent/core.py | Python | EntityState | EntityState | 4 | 9 | 4 | 4 | f8892073934f4a22155d45a2424f44c2fd00e1dd | bigcode/the-stack | train |
9dc6e78712f579e3a8122fb0 | train | class | class World(object):
def __init__(self):
# list of agents and entities (can change at execution-time!)
self.agents = []
self.landmarks = []
# communication channel dimensionality
self.dim_c = 0
# position dimensionality
self.dim_p = 2
# color dimension... | class World(object):
| def __init__(self):
# list of agents and entities (can change at execution-time!)
self.agents = []
self.landmarks = []
# communication channel dimensionality
self.dim_c = 0
# position dimensionality
self.dim_p = 2
# color dimensionality
self.di... | self.color = None
# max speed and accel
self.max_speed = None
self.accel = None
# state
self.state = EntityState()
# mass
self.initial_mass = 1.0
@property
def mass(self):
return self.initial_mass
# properties of landmark entities
class L... | 256 | 256 | 1,086 | 4 | 251 | pedramrabiee/multiagent-particle-envs | multiagent/core.py | Python | World | World | 82 | 196 | 82 | 82 | 2861511386beacf831ca3114410a4e13e0dac1da | bigcode/the-stack | train |
885bac2ce46829e9b9e6131d | train | class | class Agent(Entity):
def __init__(self):
super(Agent, self).__init__()
# agents are movable by default
self.movable = True
# cannot send communication signals
self.silent = False
# cannot observe the world
self.blind = False
# physical motor noise amou... | class Agent(Entity):
| def __init__(self):
super(Agent, self).__init__()
# agents are movable by default
self.movable = True
# cannot send communication signals
self.silent = False
# cannot observe the world
self.blind = False
# physical motor noise amount
self.u_noi... | mass
self.initial_mass = 1.0
@property
def mass(self):
return self.initial_mass
# properties of landmark entities
class Landmark(Entity):
def __init__(self):
super(Landmark, self).__init__()
# properties of agent entities
class Agent(Entity):
| 64 | 64 | 147 | 4 | 59 | pedramrabiee/multiagent-particle-envs | multiagent/core.py | Python | Agent | Agent | 59 | 79 | 59 | 59 | c434a744dc71a068d20f847850847c9a14c9b35a | bigcode/the-stack | train |
8c98592cb239c5048e0a675a | train | class | class Landmark(Entity):
def __init__(self):
super(Landmark, self).__init__()
| class Landmark(Entity):
| def __init__(self):
super(Landmark, self).__init__()
| self.max_speed = None
self.accel = None
# state
self.state = EntityState()
# mass
self.initial_mass = 1.0
@property
def mass(self):
return self.initial_mass
# properties of landmark entities
class Landmark(Entity):
| 64 | 64 | 21 | 4 | 59 | pedramrabiee/multiagent-particle-envs | multiagent/core.py | Python | Landmark | Landmark | 54 | 56 | 54 | 54 | 60c0ce941d530c343692129d3b9a827c1543c47d | bigcode/the-stack | train |
0393612058adc8e09a9c6c1c | train | class | @init_model_state_from_kwargs
class ClientOptions(object):
"""
NFS export options applied to a specified set of
clients. Only governs access through the associated
export. Access to the same file system through a different
export (on the same or different mount target) will be governed
by that e... | @init_model_state_from_kwargs
class ClientOptions(object):
| """
NFS export options applied to a specified set of
clients. Only governs access through the associated
export. Access to the same file system through a different
export (on the same or different mount target) will be governed
by that export's export options.
"""
#: A constant which ca... | # coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | 145 | 256 | 2,248 | 12 | 132 | Manny27nyc/oci-python-sdk | src/oci/file_storage/models/client_options.py | Python | ClientOptions | ClientOptions | 10 | 299 | 10 | 11 | aa2bef43c471b77d04fe11fcf4171da8b0f08d6f | bigcode/the-stack | train |
57d359e11d68967758cab042 | train | class | class QuestionLevelViewset(ModelViewSet):
queryset = Model.objects.all().order_by('-id')
serializer_class = Serializer | class QuestionLevelViewset(ModelViewSet):
| queryset = Model.objects.all().order_by('-id')
serializer_class = Serializer | from rest_framework.viewsets import ModelViewSet
from question.models import TblQuestionLevel as Model
from question.serializers import QuestionLevelSerializer as Serializer
class QuestionLevelViewset(ModelViewSet):
| 40 | 64 | 26 | 9 | 30 | xingxingzaixian/django-vue3.2-online-exam | backend/apps/question/views/level.py | Python | QuestionLevelViewset | QuestionLevelViewset | 7 | 9 | 7 | 7 | 5f18a0acc0ecad7df6131ebbf81ca29d26c0b2e4 | bigcode/the-stack | train |
4de6b0d288e7708775c8d350 | train | class | class ObjectIdentifier(object):
def __init__(self, dotted_string):
self._dotted_string = dotted_string
nodes = self._dotted_string.split(".")
intnodes = []
# There must be at least 2 nodes, the first node must be 0..2, and
# if less than 2, the second node cannot have a val... | class ObjectIdentifier(object):
| def __init__(self, dotted_string):
self._dotted_string = dotted_string
nodes = self._dotted_string.split(".")
intnodes = []
# There must be at least 2 nodes, the first node must be 0..2, and
# if less than 2, the second node cannot have a value outside the
# range 0... | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
from cryptography import utils
class ObjectIdentifier(object):
| 67 | 146 | 487 | 5 | 61 | dvaerum/cryptography | src/cryptography/hazmat/_oid.py | Python | ObjectIdentifier | ObjectIdentifier | 10 | 77 | 10 | 10 | 5356c696559318e35b88b45f5c1ec87c474b0174 | bigcode/the-stack | train |
360163c6143f16249ffbede9 | train | function | def main():
## define the main program
args = get_args()
if args.excited == True:
print(args.greeting + ', ' + args.name + '!')
else:
print(args.greeting + ', ' + args.name + '.')
| def main():
## define the main program
| args = get_args()
if args.excited == True:
print(args.greeting + ', ' + args.name + '!')
else:
print(args.greeting + ', ' + args.name + '.')
| ',
default='Stranger',
help='Name to greet')
parser.add_argument('-e', '--excited',
action='store_true',
help='punctuation to include')
return parser.parse_args()
#----------------------... | 63 | 64 | 56 | 10 | 53 | arjibsamlee/be434-fall-2021 | assignments/01_salutations/salutations.py | Python | main | main | 37 | 45 | 37 | 39 | a1eecd3474c420c1f7ed8fe497b1099ea4b2d8be | bigcode/the-stack | train |
0b796a2f8f9b4153379d56b0 | train | function | def get_args():
# pull the command line arguments
parser = argparse.ArgumentParser(
description='Greetings and salutations')
parser.add_argument('-g', '--greeting',
metavar='greeting',
default='Howdy',
help='the greeting use... | def get_args():
# pull the command line arguments
| parser = argparse.ArgumentParser(
description='Greetings and salutations')
parser.add_argument('-g', '--greeting',
metavar='greeting',
default='Howdy',
help='the greeting used')
parser.add_argument('-n', '--name',
... | #!/usr/bin/env python3
"""
Author: Megan Kane
Class: BE 534
Purpose: print greetings
Type: Assignment 1
"""
import argparse
#-------------------------------
def get_args():
# pull the command line arguments
| 53 | 64 | 123 | 12 | 41 | arjibsamlee/be434-fall-2021 | assignments/01_salutations/salutations.py | Python | get_args | get_args | 14 | 34 | 14 | 16 | efee39058b51382c4c6324ef1b1242f820870709 | bigcode/the-stack | train |
4e2246194c303dd853d8dd93 | train | function | def main():
argument_specs = dict(
state=dict(default='present',
choices=['absent', 'present']),
avi_api_update_method=dict(default='put',
choices=['put', 'patch']),
avi_api_patch_op=dict(choices=['add', 'replace', 'delete']),
des... | def main():
| argument_specs = dict(
state=dict(default='present',
choices=['absent', 'present']),
avi_api_update_method=dict(default='put',
choices=['put', 'patch']),
avi_api_patch_op=dict(choices=['add', 'replace', 'delete']),
description=dic... | HTTPS
name: MyWebsite-HTTPS
"""
RETURN = '''
obj:
description: HealthMonitor (api/healthmonitor) object
returned: success, changed
type: dict
'''
from ansible.module_utils.basic import AnsibleModule
try:
from ansible_collections.community.general.plugins.module_utils.network.avi.avi import (
... | 102 | 102 | 342 | 3 | 98 | tr3ck3r/linklight | exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/plugins/modules/network/avi/avi_healthmonitor.py | Python | main | main | 165 | 201 | 165 | 165 | f77f875fc12b1d13dc00603ab76c7dad9f6929f4 | bigcode/the-stack | train |
72a41c9d9f0e48bc3b365be9 | train | function | def test_city_search_no_matches(client, monkeypatch, award_data_fixture, elasticsearch_transaction_index):
monkeypatch.setattr(
"usaspending_api.common.elasticsearch.search_wrappers.TransactionSearch._index_name",
settings.ES_TRANSACTIONS_QUERY_ALIAS_PREFIX,
)
elasticsearch_transaction_index... | def test_city_search_no_matches(client, monkeypatch, award_data_fixture, elasticsearch_transaction_index):
| monkeypatch.setattr(
"usaspending_api.common.elasticsearch.search_wrappers.TransactionSearch._index_name",
settings.ES_TRANSACTIONS_QUERY_ALIAS_PREFIX,
)
elasticsearch_transaction_index.update_index()
body = {"filter": {"country_code": "USA", "scope": "recipient_location"}, "search_text"... | ("/api/v2/autocomplete/city", content_type="application/json", data=json.dumps(body))
assert response.data["count"] == 1
for entry in response.data["results"]:
assert entry["city_name"].lower().find("arl") > -1
def test_city_search_no_matches(client, monkeypatch, award_data_fixture, elasticsearch_transa... | 77 | 77 | 257 | 20 | 56 | jbuendiallc/usaspending-api | usaspending_api/references/tests/integration/test_city.py | Python | test_city_search_no_matches | test_city_search_no_matches | 73 | 93 | 73 | 73 | 36c220c605cd4c19d14ee954777cff7258044cd3 | bigcode/the-stack | train |
1b07a0355d8a8524f84578c9 | train | function | def test_city_search_foreign(client, monkeypatch, award_data_fixture, elasticsearch_transaction_index):
monkeypatch.setattr(
"usaspending_api.common.elasticsearch.search_wrappers.TransactionSearch._index_name",
settings.ES_TRANSACTIONS_QUERY_ALIAS_PREFIX,
)
elasticsearch_transaction_index.up... | def test_city_search_foreign(client, monkeypatch, award_data_fixture, elasticsearch_transaction_index):
| monkeypatch.setattr(
"usaspending_api.common.elasticsearch.search_wrappers.TransactionSearch._index_name",
settings.ES_TRANSACTIONS_QUERY_ALIAS_PREFIX,
)
elasticsearch_transaction_index.update_index()
body = {"filter": {"country_code": "FOREIGN", "scope": "recipient_location"}, "search_t... | ", data=json.dumps(body))
assert response.data["count"] == 1
for entry in response.data["results"]:
assert entry["city_name"].lower().find("bri") > -1
def test_city_search_foreign(client, monkeypatch, award_data_fixture, elasticsearch_transaction_index):
| 64 | 64 | 162 | 20 | 43 | jbuendiallc/usaspending-api | usaspending_api/references/tests/integration/test_city.py | Python | test_city_search_foreign | test_city_search_foreign | 132 | 142 | 132 | 132 | b12b7ba27e2ab3d148f4162d1c2108ce81563f1b | bigcode/the-stack | train |
d5ff6d249e331671d96333fb | train | function | def test_city_search_special_characters(client, monkeypatch, award_data_fixture, elasticsearch_transaction_index):
monkeypatch.setattr(
"usaspending_api.common.elasticsearch.search_wrappers.TransactionSearch._index_name",
settings.ES_TRANSACTIONS_QUERY_ALIAS_PREFIX,
)
elasticsearch_transacti... | def test_city_search_special_characters(client, monkeypatch, award_data_fixture, elasticsearch_transaction_index):
| monkeypatch.setattr(
"usaspending_api.common.elasticsearch.search_wrappers.TransactionSearch._index_name",
settings.ES_TRANSACTIONS_QUERY_ALIAS_PREFIX,
)
elasticsearch_transaction_index.update_index()
body = {
"filter": {"country_code": "USA", "scope": "recipient_location"},
... | ", content_type="application/json", data=json.dumps(body))
assert response.data["count"] == 0
for entry in response.data["results"]:
assert False # this should never be reached
def test_city_search_special_characters(client, monkeypatch, award_data_fixture, elasticsearch_transaction_index):
| 64 | 64 | 193 | 21 | 42 | jbuendiallc/usaspending-api | usaspending_api/references/tests/integration/test_city.py | Python | test_city_search_special_characters | test_city_search_special_characters | 96 | 110 | 96 | 96 | f9a0cb6f048e2a8f4b8b1ba9aabb2ae80376d323 | bigcode/the-stack | train |
cdb29dc4177ee76ec809ea43 | train | function | @pytest.fixture
def award_data_fixture(db):
mommy.make("awards.TransactionNormalized", id=1, award_id=1, action_date="2010-10-01", is_fpds=True, type="A")
mommy.make(
"awards.TransactionFPDS",
transaction_id=1,
legal_entity_zip5="abcde",
legal_entity_city_name="ARLINGTON",
... | @pytest.fixture
def award_data_fixture(db):
| mommy.make("awards.TransactionNormalized", id=1, award_id=1, action_date="2010-10-01", is_fpds=True, type="A")
mommy.make(
"awards.TransactionFPDS",
transaction_id=1,
legal_entity_zip5="abcde",
legal_entity_city_name="ARLINGTON",
legal_entity_state_code="VA",
lega... | import json
import pytest
from django.conf import settings
from model_mommy import mommy
@pytest.fixture
def award_data_fixture(db):
| 29 | 176 | 587 | 9 | 19 | jbuendiallc/usaspending-api | usaspending_api/references/tests/integration/test_city.py | Python | award_data_fixture | award_data_fixture | 8 | 57 | 8 | 9 | a04bba987c8264f9558ac1e263d975e8037e574d | bigcode/the-stack | train |
a41cf3e8d62375a5d228b018 | train | function | def test_city_search_matches_found(client, monkeypatch, award_data_fixture, elasticsearch_transaction_index):
monkeypatch.setattr(
"usaspending_api.common.elasticsearch.search_wrappers.TransactionSearch._index_name",
settings.ES_TRANSACTIONS_QUERY_ALIAS_PREFIX,
)
elasticsearch_transaction_in... | def test_city_search_matches_found(client, monkeypatch, award_data_fixture, elasticsearch_transaction_index):
| monkeypatch.setattr(
"usaspending_api.common.elasticsearch.search_wrappers.TransactionSearch._index_name",
settings.ES_TRANSACTIONS_QUERY_ALIAS_PREFIX,
)
elasticsearch_transaction_index.update_index()
body = {"filter": {"country_code": "USA", "scope": "recipient_location"}, "search_text"... | mommy.make("references.RefCountryCode", country_code="USA", country_name="UNITED STATES")
mommy.make("references.RefCountryCode", country_code="GBR", country_name="UNITED KINGDOM")
def test_city_search_matches_found(client, monkeypatch, award_data_fixture, elasticsearch_transaction_index):
| 64 | 64 | 160 | 20 | 44 | jbuendiallc/usaspending-api | usaspending_api/references/tests/integration/test_city.py | Python | test_city_search_matches_found | test_city_search_matches_found | 60 | 70 | 60 | 60 | c7b264ebc7a7fe73c153137b64333ff1c6a6bb84 | bigcode/the-stack | train |
cde69bc1a77fcd6e7b024e38 | train | function | def test_city_search_non_usa(client, monkeypatch, award_data_fixture, elasticsearch_transaction_index):
monkeypatch.setattr(
"usaspending_api.common.elasticsearch.search_wrappers.TransactionSearch._index_name",
settings.ES_TRANSACTIONS_QUERY_ALIAS_PREFIX,
)
elasticsearch_transaction_index.up... | def test_city_search_non_usa(client, monkeypatch, award_data_fixture, elasticsearch_transaction_index):
| monkeypatch.setattr(
"usaspending_api.common.elasticsearch.search_wrappers.TransactionSearch._index_name",
settings.ES_TRANSACTIONS_QUERY_ALIAS_PREFIX,
)
elasticsearch_transaction_index.update_index()
body = {"filter": {"country_code": "GBR", "scope": "recipient_location"}, "search_text"... | ("/api/v2/autocomplete/city", content_type="application/json", data=json.dumps(body))
assert response.data["count"] == 1
for entry in response.data["results"]:
assert entry["city_name"].lower().find("arl") > -1
def test_city_search_non_usa(client, monkeypatch, award_data_fixture, elasticsearch_transacti... | 78 | 78 | 260 | 21 | 56 | jbuendiallc/usaspending-api | usaspending_api/references/tests/integration/test_city.py | Python | test_city_search_non_usa | test_city_search_non_usa | 113 | 129 | 113 | 113 | c0a19aa9398d1ba348da2c10e7aec29b098c48b4 | bigcode/the-stack | train |
35428021b075a87e1ebea8b3 | train | function | def test_city_search_nulls_are_usa(client, monkeypatch, award_data_fixture, elasticsearch_transaction_index):
monkeypatch.setattr(
"usaspending_api.common.elasticsearch.search_wrappers.TransactionSearch._index_name",
settings.ES_TRANSACTIONS_QUERY_ALIAS_PREFIX,
)
elasticsearch_transaction_in... | def test_city_search_nulls_are_usa(client, monkeypatch, award_data_fixture, elasticsearch_transaction_index):
| monkeypatch.setattr(
"usaspending_api.common.elasticsearch.search_wrappers.TransactionSearch._index_name",
settings.ES_TRANSACTIONS_QUERY_ALIAS_PREFIX,
)
elasticsearch_transaction_index.update_index()
body = {"filter": {"country_code": "USA", "scope": "recipient_location"}, "search_text"... | /city", content_type="application/json", data=json.dumps(body))
assert response.data["count"] == 1
for entry in response.data["results"]:
assert entry["city_name"].lower().find("bri") > -1
def test_city_search_nulls_are_usa(client, monkeypatch, award_data_fixture, elasticsearch_transaction_index):
| 75 | 75 | 252 | 23 | 51 | jbuendiallc/usaspending-api | usaspending_api/references/tests/integration/test_city.py | Python | test_city_search_nulls_are_usa | test_city_search_nulls_are_usa | 145 | 161 | 145 | 145 | 1021c4e29b98546d721138628e20b0b3faa519b5 | bigcode/the-stack | train |
3d48aaaf533b9b1fffb8da3a | train | class | class TestErrorHandling(FabricTest):
@with_patched_object(utils, 'warn', Fake('warn', callable=True,
expect_call=True))
def test_error_warns_if_warn_only_True_and_func_None(self):
"""
warn_only=True, error(func=None) => calls warn()
"""
with settings(warn_only=True):
... | class TestErrorHandling(FabricTest):
@with_patched_object(utils, 'warn', Fake('warn', callable=True,
expect_call=True))
| def test_error_warns_if_warn_only_True_and_func_None(self):
"""
warn_only=True, error(func=None) => calls warn()
"""
with settings(warn_only=True):
error('foo')
@with_patched_object(utils, 'abort', Fake('abort', callable=True,
expect_call=True))
def test_... | .stdout.getvalue(), "%s" % (s + "\n"))
@with_fakes
def test_fastprint_calls_puts():
"""
fastprint() is just an alias to puts()
"""
text = "Some output"
fake_puts = Fake('puts', expect_call=True).with_args(
text=text, show_prefix=False, end="", flush=True
)
with patched_context(utils... | 129 | 129 | 433 | 31 | 98 | objectified/fabric | tests/test_utils.py | Python | TestErrorHandling | TestErrorHandling | 131 | 180 | 131 | 133 | e221e8a44dfcd1b7013be9417ff312884ebcba0c | bigcode/the-stack | train |
6e73ecdbeb66ca518c6b2d1a | train | function | @mock_streams('stdout')
def test_puts_without_prefix():
"""
puts() shouldn't prefix output with env.host_string if show_prefix is False
"""
s = "my output"
h = "localhost"
puts(s, show_prefix=False)
eq_(sys.stdout.getvalue(), "%s" % (s + "\n"))
| @mock_streams('stdout')
def test_puts_without_prefix():
| """
puts() shouldn't prefix output with env.host_string if show_prefix is False
"""
s = "my output"
h = "localhost"
puts(s, show_prefix=False)
eq_(sys.stdout.getvalue(), "%s" % (s + "\n"))
| """
s = "my output"
h = "localhost"
with settings(host_string=h):
puts(s)
eq_(sys.stdout.getvalue(), "[%s] %s" % (h, s + "\n"))
@mock_streams('stdout')
def test_puts_without_prefix():
| 63 | 64 | 73 | 14 | 49 | objectified/fabric | tests/test_utils.py | Python | test_puts_without_prefix | test_puts_without_prefix | 108 | 116 | 108 | 109 | 9244de472948c2a4c5a2510998f9f0e7e1b7a0b5 | bigcode/the-stack | train |
2631ac231e8abee315db5563 | train | function | @aborts
def test_abort():
"""
abort() should raise SystemExit
"""
abort("Test")
| @aborts
def test_abort():
| """
abort() should raise SystemExit
"""
abort("Test")
| of strings",
indent([" Test", " Test"], strip=True),
' Test\n Test'),
):
eq_.description = "indent(strip=True): %s" % description
yield eq_, input, output
del eq_.description
@aborts
def test_abort():
| 64 | 64 | 25 | 8 | 55 | objectified/fabric | tests/test_utils.py | Python | test_abort | test_abort | 53 | 58 | 53 | 54 | 0e3497b658010917e67f9a4e3e76a3e4b0cb3be4 | bigcode/the-stack | train |
400f29b7447fe72af74c4bbe | train | function | @mock_streams('stderr')
@with_patched_object(output, 'warnings', True)
def test_warn():
"""
warn() should print 'Warning' plus given text
"""
warn("Test")
assert "\nWarning: Test\n\n" == sys.stderr.getvalue()
| @mock_streams('stderr')
@with_patched_object(output, 'warnings', True)
def test_warn():
| """
warn() should print 'Warning' plus given text
"""
warn("Test")
assert "\nWarning: Test\n\n" == sys.stderr.getvalue()
| fastprint, error
from fabric import utils # For patching
from fabric.context_managers import settings, hide
from utils import mock_streams, aborts, FabricTest, assert_contains
@mock_streams('stderr')
@with_patched_object(output, 'warnings', True)
def test_warn():
| 64 | 64 | 60 | 23 | 40 | objectified/fabric | tests/test_utils.py | Python | test_warn | test_warn | 16 | 23 | 16 | 18 | e751020b641229c9b6baf99df3295d7701755d90 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.