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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d48265ab4cefb628ec96a5ec | train | function | def mock_node_resp_func(node, func):
connection = Mock()
connection.read_response.side_effect = func
node.redis_connection.connection = connection
return node
| def mock_node_resp_func(node, func):
| connection = Mock()
connection.read_response.side_effect = func
node.redis_connection.connection = connection
return node
| cmd_parser_initialize.side_effect = cmd_init_mock
return RedisCluster(*args, **kwargs)
def mock_node_resp(node, response):
connection = Mock()
connection.read_response.return_value = response
node.redis_connection.connection = connection
return node
def mock_node_resp_func(nod... | 64 | 64 | 35 | 9 | 54 | Avital-Fine/redis-py | tests/test_cluster.py | Python | mock_node_resp_func | mock_node_resp_func | 138 | 142 | 138 | 138 | 992c14df76e90513c0858dcb5794bee00d58a7a8 | bigcode/the-stack | train |
af3f0149808d641e2f09b410 | train | class | @pytest.mark.onlycluster
class TestNodesManager:
"""
Tests for the NodesManager class
"""
def test_load_balancer(self, r):
n_manager = r.nodes_manager
lb = n_manager.read_load_balancer
slot_1 = 1257
slot_2 = 8975
node_1 = ClusterNode(default_host, 6379, PRIMARY)
... | @pytest.mark.onlycluster
class TestNodesManager:
| """
Tests for the NodesManager class
"""
def test_load_balancer(self, r):
n_manager = r.nodes_manager
lb = n_manager.read_load_balancer
slot_1 = 1257
slot_2 = 8975
node_1 = ClusterNode(default_host, 6379, PRIMARY)
node_2 = ClusterNode(default_host, 6378, ... | command", "+info"],
keys=["{cache}:*"],
nopass=True,
target_nodes="primaries",
)
r.acl_log_reset(target_nodes=node)
user_client = _get_client(
RedisCluster, request, flushdb=False, username=username
)
# Valid operation and key
... | 256 | 256 | 2,738 | 10 | 246 | Avital-Fine/redis-py | tests/test_cluster.py | Python | TestNodesManager | TestNodesManager | 1,975 | 2,272 | 1,975 | 1,976 | 0cd33d87aefc4c12a2550d3e46dab040952da809 | bigcode/the-stack | train |
35340ec2d7d7e7d7a167a9b7 | train | function | def get_mocked_redis_client(func=None, *args, **kwargs):
"""
Return a stable RedisCluster object that have deterministic
nodes and slots setup to remove the problem of different IP addresses
on different installations and machines.
"""
cluster_slots = kwargs.pop("cluster_slots", default_cluster_... | def get_mocked_redis_client(func=None, *args, **kwargs):
| """
Return a stable RedisCluster object that have deterministic
nodes and slots setup to remove the problem of different IP addresses
on different installations and machines.
"""
cluster_slots = kwargs.pop("cluster_slots", default_cluster_slots)
coverage_res = kwargs.pop("coverage_result", "... | ["slowlog-max-len"]
# Function to restore the old values
def cleanup():
r.config_set("slowlog-log-slower-than", old_slower_than_value)
r.config_set("slowlog-max-len", old_max_legnth_value)
request.addfinalizer(cleanup)
# Set the new values
r.config_set("slowlog-log-slower-than", 0... | 115 | 115 | 385 | 16 | 99 | Avital-Fine/redis-py | tests/test_cluster.py | Python | get_mocked_redis_client | get_mocked_redis_client | 82 | 128 | 82 | 82 | 11d49f3fe4c87e223ba3a6c2e6be262ed52e38de | bigcode/the-stack | train |
8dc9aa7803c482774a5b3e96 | train | class | class Stats(object):
# XXX: Edit this to compute the table cardinality
def __init__(self, table):
self.table = table
self.card = 10
# XXX: edit this to return the domain of the field
def __getitem__(self, field):
return [0, 1]
| class Stats(object):
# XXX: Edit this to compute the table cardinality
| def __init__(self, table):
self.table = table
self.card = 10
# XXX: edit this to return the domain of the field
def __getitem__(self, field):
return [0, 1]
| pandas
import numbers
import os
try:
import instabase.notebook.ipython.utils as ib
except:
pass
openfile = open
try:
openfile = ib.open
except:
pass
class Stats(object):
# XXX: Edit this to compute the table cardinality
| 64 | 64 | 71 | 18 | 45 | amitashukla/databass-public | src/engine/db.py | Python | Stats | Stats | 16 | 25 | 16 | 18 | 4d62db276fd8a7fc0faf05b6749aed5c3b893666 | bigcode/the-stack | train |
79024510869624dbfe95e620 | train | class | class InMemoryTable(Table):
"""
Table that contains its data all in memory
"""
def __init__(self, fields, rows):
super(InMemoryTable, self).__init__(fields)
self.rows = rows
def __iter__(self):
return iter(self.rows)
| class InMemoryTable(Table):
| """
Table that contains its data all in memory
"""
def __init__(self, fields, rows):
super(InMemoryTable, self).__init__(fields)
self.rows = rows
def __iter__(self):
return iter(self.rows)
| rows)
return InMemoryTable(rows[0].keys(), rows)
@property
def stats(self):
return Stats(self)
def col_values(self, field):
return [row[field] for row in self]
def __iter__(self):
yield
class InMemoryTable(Table):
| 64 | 64 | 62 | 6 | 57 | amitashukla/databass-public | src/engine/db.py | Python | InMemoryTable | InMemoryTable | 65 | 74 | 65 | 65 | 434f812dfefafac3aef97a04e894d96ec9496ad4 | bigcode/the-stack | train |
13a4f4a541cc509846d8309d | train | class | class Table(object):
def __init__(self, fields):
self.fields = fields
def type(self, field):
"""
Instead of maintaining a schema, just check the first row of the table
"""
for row in self.rows:
if isinstance(row[field], numbers.Number):
return "num"
break
return "str"
... | class Table(object):
| def __init__(self, fields):
self.fields = fields
def type(self, field):
"""
Instead of maintaining a schema, just check the first row of the table
"""
for row in self.rows:
if isinstance(row[field], numbers.Number):
return "num"
break
return "str"
@staticmethod
def ... | to compute the table cardinality
def __init__(self, table):
self.table = table
self.card = 10
# XXX: edit this to return the domain of the field
def __getitem__(self, field):
return [0, 1]
class Table(object):
| 64 | 64 | 190 | 4 | 60 | amitashukla/databass-public | src/engine/db.py | Python | Table | Table | 28 | 62 | 28 | 28 | 95159858af5095d949906c9c0373eeddb57311a1 | bigcode/the-stack | train |
f207f277cafbbb66afd22fb7 | train | class | class Database(object):
"""
Manages all tables registered in the database
"""
def __init__(self):
self.registry = {}
self.setup()
def setup(self):
"""
Walks all CSV files in the current directory and registers
them in the database
"""
for root, dirs, files in os.walk("."):
f... | class Database(object):
| """
Manages all tables registered in the database
"""
def __init__(self):
self.registry = {}
self.setup()
def setup(self):
"""
Walks all CSV files in the current directory and registers
them in the database
"""
for root, dirs, files in os.walk("."):
for fname in files:
... | in self]
def __iter__(self):
yield
class InMemoryTable(Table):
"""
Table that contains its data all in memory
"""
def __init__(self, fields, rows):
super(InMemoryTable, self).__init__(fields)
self.rows = rows
def __iter__(self):
return iter(self.rows)
class Database(object):
| 79 | 79 | 265 | 4 | 75 | amitashukla/databass-public | src/engine/db.py | Python | Database | Database | 76 | 116 | 76 | 76 | 121dd6bab9dd48ee197d39ba12f2023aacea7726 | bigcode/the-stack | train |
5fda860fc72114cd420b172a | train | class | class FittingData(Dataset):
NUM_BODY_JOINTS = 17
NUM_HAND_JOINTS = 20
def __init__(self, data_folder, img_folder='images',
keyp_folder='keypoints',
use_hands=False,
use_face=False,
dtype=torch.float32,
mode... | class FittingData(Dataset):
| NUM_BODY_JOINTS = 17
NUM_HAND_JOINTS = 20
def __init__(self, data_folder, img_folder='images',
keyp_folder='keypoints',
use_hands=False,
use_face=False,
dtype=torch.float32,
model_type='smplx',
... | .use_face_contour)
# if len(keyp_tuple.keypoints) < 1:
# return {}
# keypoints = np.stack(keyp_tuple.keypoints)
# output_dict = {'fn': img_fn,
# 'img_path': img_path,
# 'keypoints': keypoints, 'img': img}
# # if keyp... | 256 | 256 | 1,259 | 7 | 249 | chunchun2016n/boycehbzi | code/utils/data_parser.py | Python | FittingData | FittingData | 273 | 435 | 273 | 274 | 50d354b94116fc3bfb77483607d6d12d95fe8c6a | bigcode/the-stack | train |
62c5649be5ffc82eda2fe992 | train | function | def create_dataset(dataset='offline', data_folder='data', pose_format='coco17', **kwargs):
if dataset.lower() == 'offline':
return FittingData(data_folder, pose_format=pose_format, **kwargs)
else:
raise ValueError('Unknown dataset: {}'.format(dataset))
| def create_dataset(dataset='offline', data_folder='data', pose_format='coco17', **kwargs):
| if dataset.lower() == 'offline':
return FittingData(data_folder, pose_format=pose_format, **kwargs)
else:
raise ValueError('Unknown dataset: {}'.format(dataset))
| _annotation
Keypoints = namedtuple('Keypoints',
['keypoints', 'gender_gt', 'gender_pd'])
Keypoints.__new__.__defaults__ = (None,) * len(Keypoints._fields)
def create_dataset(dataset='offline', data_folder='data', pose_format='coco17', **kwargs):
| 64 | 64 | 63 | 22 | 42 | chunchun2016n/boycehbzi | code/utils/data_parser.py | Python | create_dataset | create_dataset | 35 | 39 | 35 | 35 | 16cf4e07fc61ec64a9c0a1b3af2544247d55c1e4 | bigcode/the-stack | train |
0ee8009fb17f37caedffbb57 | train | function | def read_joints(keypoint_fn, use_hands=True, use_face=True,
use_face_contour=False):
"""
load 3D annotation
"""
with open(keypoint_fn) as keypoint_file:
data = json.load(keypoint_file)
keypoints = []
gender_pd = []
gender_gt = []
for idx, person_data in enume... | def read_joints(keypoint_fn, use_hands=True, use_face=True,
use_face_contour=False):
| """
load 3D annotation
"""
with open(keypoint_fn) as keypoint_file:
data = json.load(keypoint_file)
keypoints = []
gender_pd = []
gender_gt = []
for idx, person_data in enumerate(data['people']):
try:
body_keypoints = np.array(person_data['pose_keypoints_3d'... | points_2d'],
dtype=np.float32).reshape([-1, 3])[:17, :]
body_keypoints = np.concatenate(
[body_keypoints, face_keypoints, contour_keyps], axis=0)
if 'gender_pd' in person_data:
gender_pd.append(person_data['gender_pd'])
if 'gender_gt' in pers... | 144 | 144 | 481 | 24 | 120 | chunchun2016n/boycehbzi | code/utils/data_parser.py | Python | read_joints | read_joints | 92 | 147 | 92 | 93 | b4b88c6abedbfc82e0328799992b50c1b42e45f9 | bigcode/the-stack | train |
c254e7103865b66de5032555 | train | function | def read_keypoints(keypoint_fn, use_hands=True, use_face=True,
use_face_contour=False):
with open(keypoint_fn) as keypoint_file:
data = json.load(keypoint_file)
keypoints = []
gender_pd = []
gender_gt = []
for idx, person_data in enumerate(data['people']):
body_k... | def read_keypoints(keypoint_fn, use_hands=True, use_face=True,
use_face_contour=False):
| with open(keypoint_fn) as keypoint_file:
data = json.load(keypoint_file)
keypoints = []
gender_pd = []
gender_gt = []
for idx, person_data in enumerate(data['people']):
body_keypoints = np.array(person_data['pose_keypoints_2d'],
dtype=np.float32)
... |
from utils.utils import smpl_to_annotation
Keypoints = namedtuple('Keypoints',
['keypoints', 'gender_gt', 'gender_pd'])
Keypoints.__new__.__defaults__ = (None,) * len(Keypoints._fields)
def create_dataset(dataset='offline', data_folder='data', pose_format='coco17', **kwargs):
if dataset.... | 137 | 137 | 457 | 24 | 113 | chunchun2016n/boycehbzi | code/utils/data_parser.py | Python | read_keypoints | read_keypoints | 42 | 90 | 42 | 43 | c56ce5ed70fb6c185927068f1a675b552c87d114 | bigcode/the-stack | train |
5a9a12ce1a7f3ee9d19ba8ab | train | class | class VqaAttentionBaselineTest(tf.test.TestCase):
def testVqaAttentionBaseline(self):
batch_size = 3
image_size = 448
vocab_size = 100
num_classes = 10
question_length = 5
answer_length = 10
x = 2 * np.random.rand(batch_size, image_size, image_size, 3) - 1
q = np.random.random_intege... | class VqaAttentionBaselineTest(tf.test.TestCase):
| def testVqaAttentionBaseline(self):
batch_size = 3
image_size = 448
vocab_size = 100
num_classes = 10
question_length = 5
answer_length = 10
x = 2 * np.random.rand(batch_size, image_size, image_size, 3) - 1
q = np.random.random_integers(
1, high=vocab_size - 1, size=(batch_siz... | "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Vqa_attention_baseline tests."""
from __future__ import absolute_import
from __future__ import division
from __future__ i... | 122 | 122 | 408 | 11 | 110 | jinliangwei/tensor2tensor | tensor2tensor/models/research/vqa_attention_test.py | Python | VqaAttentionBaselineTest | VqaAttentionBaselineTest | 31 | 68 | 31 | 32 | 33b0fce6bf22e5c1afdb297f7cd6f0863cd597cb | bigcode/the-stack | train |
19cd4ffa79441782c6c7248d | train | function | def tup():
sequence = [0,0,0,0,0]
for (nc_1, nc_2, c) in positions():
for conseq in range(1, MAX_ELT - 1):
sequence[(c + 0) % 5] = conseq
sequence[(c + 1) % 5] = conseq + 1
sequence[(c + 2) % 5] = conseq + 2
for non_conseq_1, non_conseq_2 in itertools.prod... | def tup():
| sequence = [0,0,0,0,0]
for (nc_1, nc_2, c) in positions():
for conseq in range(1, MAX_ELT - 1):
sequence[(c + 0) % 5] = conseq
sequence[(c + 1) % 5] = conseq + 1
sequence[(c + 2) % 5] = conseq + 2
for non_conseq_1, non_conseq_2 in itertools.product(
... | T = 70
## Yields the two nonconsecutive elts
## Then the position of the consecutive element
def positions():
yield (0, 1, 2)
yield (3, 4, 0)
yield (0, 4, 1)
def tup():
| 64 | 64 | 174 | 3 | 61 | thomastay/nim_fun | combinations/consec_tuples.py | Python | tup | tup | 12 | 23 | 12 | 12 | 796cdf43f7d5128806fa7797094453989abb5ca1 | bigcode/the-stack | train |
2d28dd9c0469eb97e797692d | train | function | def num_unique_tuples():
return len({tuple(s) for s in tup()})
| def num_unique_tuples():
| return len({tuple(s) for s in tup()})
| in itertools.product(
range(1, MAX_ELT + 1), range(1, MAX_ELT +1)):
sequence[nc_1] = non_conseq_1
sequence[nc_2] = non_conseq_2
yield sequence
def num_unique_tuples():
| 64 | 64 | 19 | 6 | 57 | thomastay/nim_fun | combinations/consec_tuples.py | Python | num_unique_tuples | num_unique_tuples | 25 | 26 | 25 | 25 | 61ed1fdcbeca0f8c2e35dbf776942538731b6271 | bigcode/the-stack | train |
2d33f71f80a6b654ce78fcf3 | train | function | def positions():
yield (0, 1, 2)
yield (3, 4, 0)
yield (0, 4, 1)
| def positions():
| yield (0, 1, 2)
yield (3, 4, 0)
yield (0, 4, 1)
| import itertools
MAX_ELT = 70
## Yields the two nonconsecutive elts
## Then the position of the consecutive element
def positions():
| 33 | 64 | 36 | 3 | 29 | thomastay/nim_fun | combinations/consec_tuples.py | Python | positions | positions | 6 | 9 | 6 | 6 | 6132202011664b1aa7ed26404cdabd6487633693 | bigcode/the-stack | train |
9b700c96bd32d10931d56b07 | train | class | @patch("requests.sessions.Session.get", side_effect=Util.mocked_requests)
class TestOp(TestCase):
@parameterized.expand(
[
[
"show_job",
"<show><jobs><id>1</id></jobs></show>",
{
"response": {
"@status": ... | @patch("requests.sessions.Session.get", side_effect=Util.mocked_requests)
class TestOp(TestCase):
@parameterized.expand(
[
[
"show_job",
"<show><jobs><id>1</id></jobs></show>",
{
"response": {
"@status": ... | def test_op(self, mock_get, name, cmd, expected):
action = Util.default_connector(Op())
actual = action.run({Input.CMD: cmd})
self.assertEqual(actual, expected)
| @patch("requests.sessions.Session.get", side_effect=Util.mocked_requests)
class TestOp(TestCase):
@parameterized.expand(
[
[
"show_job",
"<show><jobs><id>1</id></jobs></show>",
{
"response": {
"@status": ... | 225 | 80 | 268 | 225 | 0 | lukaszlaszuk/insightconnect-plugins | plugins/palo_alto_pan_os/unit_test/test_op.py | Python | TestOp | TestOp | 13 | 50 | 13 | 46 | a712f075e94cd7e5671933aa68023013e7f6e59e | bigcode/the-stack | train |
8e83f4dd75f6434a6ce24481 | train | class | class ModelWithSharedParameter(nn.Module):
def __init__(self):
super(ModelWithSharedParameter, self).__init__()
self.embedding = nn.Embedding(1000, 200)
self.FC1 = nn.Linear(200, 200)
self.FC2 = nn.Linear(200, 200)
# tie weight in FC2 to FC1
self.FC2.weight = nn.Param... | class ModelWithSharedParameter(nn.Module):
| def __init__(self):
super(ModelWithSharedParameter, self).__init__()
self.embedding = nn.Embedding(1000, 200)
self.FC1 = nn.Linear(200, 200)
self.FC2 = nn.Linear(200, 200)
# tie weight in FC2 to FC1
self.FC2.weight = nn.Parameter(self.FC1.weight)
self.FC2.bias... | of patent rights
# can be found in the PATENTS file in the same directory.
import collections
import os
import tempfile
import unittest
import shutil
import numpy as np
import torch
from torch import nn
from scripts.average_checkpoints import average_checkpoints
class ModelWithSharedParameter(nn.Module):
| 64 | 64 | 137 | 8 | 55 | Yuran-Zhao/bert-nmt | tests/test_average_checkpoints.py | Python | ModelWithSharedParameter | ModelWithSharedParameter | 21 | 34 | 21 | 21 | 760b87a259cbf50a45a2e3c13ca39373639e60e9 | bigcode/the-stack | train |
6748414268e2e033bbe65ec4 | train | class | class TestAverageCheckpoints(unittest.TestCase):
def test_average_checkpoints(self):
params_0 = collections.OrderedDict([
('a', torch.DoubleTensor([100.0])),
('b', torch.FloatTensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])),
('c', torch.IntTensor([7, 8, 9])),
])
... | class TestAverageCheckpoints(unittest.TestCase):
| def test_average_checkpoints(self):
params_0 = collections.OrderedDict([
('a', torch.DoubleTensor([100.0])),
('b', torch.FloatTensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])),
('c', torch.IntTensor([7, 8, 9])),
])
params_1 = collections.OrderedDict([
... | 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
import collections
import os
import tempfile
impo... | 245 | 245 | 817 | 9 | 236 | Yuran-Zhao/bert-nmt | tests/test_average_checkpoints.py | Python | TestAverageCheckpoints | TestAverageCheckpoints | 37 | 114 | 37 | 37 | 1c799aae97c8169ef996a4f1615e7cdf968b1383 | bigcode/the-stack | train |
10b0146293fa83807481852b | train | function | def test_secret(service_client, arn, token):
"""Test the pending secret against the database
This method tries to log into the database with the secrets staged with AWSPENDING and runs
a permissions check to ensure the user has the correct permissions.
Args:
service_client (client): The... | def test_secret(service_client, arn, token):
| """Test the pending secret against the database
This method tries to log into the database with the secrets staged with AWSPENDING and runs
a permissions check to ensure the user has the correct permissions.
Args:
service_client (client): The secrets manager service client
arn... | _dict['username'], pending_dict['username']))
else:
alter_role = "ALTER USER %s" % pending_dict['username']
cur.execute(alter_role + " WITH PASSWORD %s", (pending_dict['password'],))
conn.commit()
logger.info("setSecret: Successfully created use... | 100 | 100 | 335 | 10 | 90 | gabehollombe-aws/aws-doc-sdk-examples | lambda_functions/secretsmanager/RDSPostgreSQL-Multiuser.py | Python | test_secret | test_secret | 215 | 252 | 215 | 215 | 8d137a426611fd98fb733c00ad68a52b130847b6 | bigcode/the-stack | train |
aea50387c22b1c8d712570fd | train | function | def lambda_handler(event, context):
"""Secrets Manager RDS PostgreSQL Handler
This handler uses the master-user rotation scheme to rotate an RDS PostgreSQL user credential. During the first rotation, this
scheme logs into the database as the master user, creates a new user (appending _clone to the user... | def lambda_handler(event, context):
| """Secrets Manager RDS PostgreSQL Handler
This handler uses the master-user rotation scheme to rotate an RDS PostgreSQL user credential. During the first rotation, this
scheme logs into the database as the master user, creates a new user (appending _clone to the username), and grants the
new user a... | # snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.]
# snippet-sourcedescription:[Lambda rotation for AWS Secrets Manager - RDS PostgreSQL with separate Master secret]
# snippet-service:[secretsmanager]
# snippet-keyword:[rotation function]
# snippet-keyword:[python]
# snippet-k... | 199 | 248 | 828 | 7 | 192 | gabehollombe-aws/aws-doc-sdk-examples | lambda_functions/secretsmanager/RDSPostgreSQL-Multiuser.py | Python | lambda_handler | lambda_handler | 28 | 102 | 28 | 28 | 6d88949ca13040edbb229d2c9bd39e32408205cd | bigcode/the-stack | train |
68ff2bb99b03cbdd4d58b771 | train | function | def create_secret(service_client, arn, token):
"""Generate a new secret
This method first checks for the existence of a secret for the passed in token. If one does not exist, it will generate a
new secret and put it with the passed in token.
Args:
service_client (client): The secrets ma... | def create_secret(service_client, arn, token):
| """Generate a new secret
This method first checks for the existence of a secret for the passed in token. If one does not exist, it will generate a
new secret and put it with the passed in token.
Args:
service_client (client): The secrets manager service client
arn (string): Th... | setSecret":
set_secret(service_client, arn, token)
elif step == "testSecret":
test_secret(service_client, arn, token)
elif step == "finishSecret":
finish_secret(service_client, arn, token)
else:
logger.error("lambda_handler: Invalid step parameter %s for secret %... | 106 | 107 | 359 | 10 | 96 | gabehollombe-aws/aws-doc-sdk-examples | lambda_functions/secretsmanager/RDSPostgreSQL-Multiuser.py | Python | create_secret | create_secret | 105 | 141 | 105 | 105 | 375a8fd4676bff43866aca0f97259db4197b27f6 | bigcode/the-stack | train |
21f1b943ea98e04fa334f705 | train | function | def get_connection(secret_dict):
"""Gets a connection to PostgreSQL DB from a secret dictionary
This helper function tries to connect to the database grabbing connection info
from the secret dictionary. If successful, it returns the connection, else None
Args:
secret_dict (dict): The Se... | def get_connection(secret_dict):
| """Gets a connection to PostgreSQL DB from a secret dictionary
This helper function tries to connect to the database grabbing connection info
from the secret dictionary. If successful, it returns the connection, else None
Args:
secret_dict (dict): The Secret Dictionary
Returns:
... | .update_secret_version_stage(SecretId=arn, VersionStage="AWSCURRENT", MoveToVersionId=token, RemoveFromVersionId=current_version)
logger.info("finishSecret: Successfully set AWSCURRENT stage to version %s for secret %s." % (version, arn))
def get_connection(secret_dict):
| 65 | 66 | 220 | 6 | 59 | gabehollombe-aws/aws-doc-sdk-examples | lambda_functions/secretsmanager/RDSPostgreSQL-Multiuser.py | Python | get_connection | get_connection | 288 | 313 | 288 | 288 | c2b4cbebebcfa3cf52d30c2f58de68e4a82d7bbd | bigcode/the-stack | train |
15f44ff6b86c3ad9ebae5e55 | train | function | def get_alt_username(current_username):
"""Gets the alternate username for the current_username passed in
This helper function gets the username for the alternate user based on the passed in current username.
Args:
current_username (client): The current username
Returns:
Alte... | def get_alt_username(current_username):
| """Gets the alternate username for the current_username passed in
This helper function gets the username for the alternate user based on the passed in current username.
Args:
current_username (client): The current username
Returns:
AlternateUsername: Alternate username
... | 'postgres' in order to use this rotation lambda")
for field in required_fields:
if field not in secret_dict:
raise KeyError("%s key is missing from secret JSON" % field)
# Parse and return the secret JSON string
return secret_dict
def get_alt_username(current_username):
| 64 | 64 | 162 | 7 | 56 | gabehollombe-aws/aws-doc-sdk-examples | lambda_functions/secretsmanager/RDSPostgreSQL-Multiuser.py | Python | get_alt_username | get_alt_username | 362 | 384 | 362 | 362 | 0bdc810d206cabcab4c43f29b3c3cf712dd76c90 | bigcode/the-stack | train |
b1c47fc24a400d31b594c88d | train | function | def get_secret_dict(service_client, arn, stage, token=None):
"""Gets the secret dictionary corresponding for the secret arn, stage, and token
This helper function gets credentials for the arn and stage passed in and returns the dictionary by parsing the JSON string
Args:
service_client (clie... | def get_secret_dict(service_client, arn, stage, token=None):
| """Gets the secret dictionary corresponding for the secret arn, stage, and token
This helper function gets credentials for the arn and stage passed in and returns the dictionary by parsing the JSON string
Args:
service_client (client): The secrets manager service client
arn (string... | ' in secret_dict else 5432
dbname = secret_dict['dbname'] if 'dbname' in secret_dict else "postgres"
# Try to obtain a connection to the db
try:
conn = pgdb.connect(host=secret_dict['host'], user=secret_dict['username'], password=secret_dict['password'], database=dbname, port=port, connect_tim... | 111 | 111 | 370 | 14 | 96 | gabehollombe-aws/aws-doc-sdk-examples | lambda_functions/secretsmanager/RDSPostgreSQL-Multiuser.py | Python | get_secret_dict | get_secret_dict | 316 | 359 | 316 | 316 | 5241f5b7eab33f2c742b21e0e7f3b75b2a5a84e3 | bigcode/the-stack | train |
090cf9108d354038061b8aa7 | train | function | def set_secret(service_client, arn, token):
"""Set the pending secret in the database
This method tries to login to the database with the AWSPENDING secret and returns on success. If that fails, it
tries to login with the master credentials from the masterarn in the current secret. If this succeeds, it... | def set_secret(service_client, arn, token):
| """Set the pending secret in the database
This method tries to login to the database with the AWSPENDING secret and returns on success. If that fails, it
tries to login with the master credentials from the masterarn in the current secret. If this succeeds, it adds all
grants for AWSCURRENT user to ... | # Make sure the current secret exists
current_dict = get_secret_dict(service_client, arn, "AWSCURRENT")
# Now try to get the secret version, if that fails, put a new secret
try:
get_secret_dict(service_client, arn, "AWSPENDING", token)
logger.info("createSecret: Successfully retri... | 237 | 238 | 794 | 10 | 227 | gabehollombe-aws/aws-doc-sdk-examples | lambda_functions/secretsmanager/RDSPostgreSQL-Multiuser.py | Python | set_secret | set_secret | 144 | 212 | 144 | 144 | b5d9f90f164166d9cff56cf7d4d21f3965158bd1 | bigcode/the-stack | train |
9e2bc5478c0397da7620549f | train | function | def finish_secret(service_client, arn, token):
"""Finish the rotation by marking the pending secret as current
This method moves the secret from the AWSPENDING stage to the AWSCURRENT stage.
Args:
service_client (client): The secrets manager service client
arn (string): The secret... | def finish_secret(service_client, arn, token):
| """Finish the rotation by marking the pending secret as current
This method moves the secret from the AWSPENDING stage to the AWSCURRENT stage.
Args:
service_client (client): The secrets manager service client
arn (string): The secret ARN or other identifier
token (strin... | ()
logger.info("testSecret: Successfully signed into PostgreSQL DB with AWSPENDING secret in %s." % arn)
return
else:
logger.error("testSecret: Unable to log into database with pending secret of secret ARN %s" % arn)
raise ValueError("Unable to log into database with pending s... | 88 | 88 | 296 | 10 | 78 | gabehollombe-aws/aws-doc-sdk-examples | lambda_functions/secretsmanager/RDSPostgreSQL-Multiuser.py | Python | finish_secret | finish_secret | 255 | 285 | 255 | 255 | d18f912bf144a4e59eda503f20c11f6bd2103d42 | bigcode/the-stack | train |
9a4939d7ce4aafeb7a76b903 | train | function | @router.post("/api/content-trust/private-key")
def post_pkg_mgr_private_key(
repodata_signing_key: SigningKey,
auth: authorization.Rules = Depends(get_rules),
):
user_id = auth.assert_user()
channel_name = repodata_signing_key.channel
private_key = repodata_signing_key.private_key
with get_db_m... | @router.post("/api/content-trust/private-key")
def post_pkg_mgr_private_key(
repodata_signing_key: SigningKey,
auth: authorization.Rules = Depends(get_rules),
):
| user_id = auth.assert_user()
channel_name = repodata_signing_key.channel
private_key = repodata_signing_key.private_key
with get_db_manager() as db:
pkg_mgr_key = db_models.RepodataSigningKey(
private_key=private_key, user_id=user_id, channel_name=channel_name
)
db.a... | )
# before we can upload a file there.
pkgstore.add_file(file.file.read(), "", file.filename)
@router.post("/api/content-trust/private-key")
def post_pkg_mgr_private_key(
repodata_signing_key: SigningKey,
auth: authorization.Rules = Depends(get_rules),
):
| 64 | 64 | 124 | 40 | 24 | maresb/quetz | plugins/quetz_content_trust/quetz_content_trust/api.py | Python | post_pkg_mgr_private_key | post_pkg_mgr_private_key | 35 | 49 | 35 | 39 | 85925653051e7958a8f981a7f89aca09ad715127 | bigcode/the-stack | train |
ae446b45a6904cfd33b6c48f | train | function | def post_file(file):
if type(file.file) is SpooledTemporaryFile and not hasattr(file, "seekable"):
file.file.seekable = file.file._file.seekable
file.file.seek(0, os.SEEK_END)
file.file.seek(0)
# channel_name is passed as "" (empty string) since we want to upload the file
# in a host-wide ... | def post_file(file):
| if type(file.file) is SpooledTemporaryFile and not hasattr(file, "seekable"):
file.file.seekable = file.file._file.seekable
file.file.seek(0, os.SEEK_END)
file.file.seek(0)
# channel_name is passed as "" (empty string) since we want to upload the file
# in a host-wide manner i.e. independe... | authorization
from quetz.config import Config
from quetz.database import get_db_manager
from quetz.deps import get_rules
from . import db_models
from .rest_models import SigningKey
router = APIRouter()
config = Config()
pkgstore = config.get_package_store()
def post_file(file):
| 64 | 64 | 151 | 5 | 59 | maresb/quetz | plugins/quetz_content_trust/quetz_content_trust/api.py | Python | post_file | post_file | 20 | 32 | 20 | 20 | fe72743ba980f097b44621c030167bd853642681 | bigcode/the-stack | train |
2bd64db8c6aafa3497fc73e5 | train | function | @router.post("/api/content-trust/upload-key-mgr", status_code=201, tags=["files"])
def post_key_mgr_to_channel(
key_mgr_file: UploadFile = File(...),
auth: authorization.Rules = Depends(get_rules),
):
auth.assert_server_roles(["owner"])
post_file(key_mgr_file)
| @router.post("/api/content-trust/upload-key-mgr", status_code=201, tags=["files"])
def post_key_mgr_to_channel(
key_mgr_file: UploadFile = File(...),
auth: authorization.Rules = Depends(get_rules),
):
| auth.assert_server_roles(["owner"])
post_file(key_mgr_file)
| _server_roles(["owner"])
post_file(root_json_file)
@router.post("/api/content-trust/upload-key-mgr", status_code=201, tags=["files"])
def post_key_mgr_to_channel(
key_mgr_file: UploadFile = File(...),
auth: authorization.Rules = Depends(get_rules),
):
| 64 | 64 | 67 | 52 | 12 | maresb/quetz | plugins/quetz_content_trust/quetz_content_trust/api.py | Python | post_key_mgr_to_channel | post_key_mgr_to_channel | 61 | 67 | 61 | 65 | 72d307a83481b1a7460adf5b0eab5fda635d1328 | bigcode/the-stack | train |
653c5eda63d31fa927aeebcd | train | function | @router.post("/api/content-trust/upload-root", status_code=201, tags=["files"])
def post_root_json_to_channel(
root_json_file: UploadFile = File(...),
auth: authorization.Rules = Depends(get_rules),
):
auth.assert_server_roles(["owner"])
post_file(root_json_file)
| @router.post("/api/content-trust/upload-root", status_code=201, tags=["files"])
def post_root_json_to_channel(
root_json_file: UploadFile = File(...),
auth: authorization.Rules = Depends(get_rules),
):
| auth.assert_server_roles(["owner"])
post_file(root_json_file)
|
)
db.add(pkg_mgr_key)
db.commit()
@router.post("/api/content-trust/upload-root", status_code=201, tags=["files"])
def post_root_json_to_channel(
root_json_file: UploadFile = File(...),
auth: authorization.Rules = Depends(get_rules),
):
| 64 | 64 | 65 | 50 | 14 | maresb/quetz | plugins/quetz_content_trust/quetz_content_trust/api.py | Python | post_root_json_to_channel | post_root_json_to_channel | 52 | 58 | 52 | 56 | d206dd421b8222d32b3c3487f4096fb0883e610c | bigcode/the-stack | train |
21bbfbf1078b5b759311cd47 | train | function | def step(p: Particle) -> Particle:
vel = (p.vel[0]+p.acc[0], p.vel[1]+p.acc[1], p.vel[2]+p.acc[2])
pos = (p.pos[0]+vel[0], p.pos[1]+vel[1], p.pos[2]+vel[2])
return Particle(pos, vel, p.acc, p.id)
| def step(p: Particle) -> Particle:
| vel = (p.vel[0]+p.acc[0], p.vel[1]+p.acc[1], p.vel[2]+p.acc[2])
pos = (p.pos[0]+vel[0], p.pos[1]+vel[1], p.pos[2]+vel[2])
return Particle(pos, vel, p.acc, p.id)
| collections import Counter
from typing import NamedTuple, Tuple, List
class Particle(NamedTuple):
pos: Tuple[int, int, int]
vel: Tuple[int, int, int]
acc: Tuple[int, int, int]
id: int
def step(p: Particle) -> Particle:
| 64 | 64 | 87 | 9 | 54 | gcalmettes/AdventOfCode2017 | 2017/day20.py | Python | step | step | 15 | 18 | 15 | 15 | 45f6a1eea3414a1a66565343c27347755b23b696 | bigcode/the-stack | train |
af7f0f4c2e2f4258caa95da2 | train | function | def parse(input: str, id: int) -> Particle:
regex = "(-?[0-9]+,-?[0-9]+,-?[0-9]+)"
pos,vel,acc = re.findall(regex, input)
pos = tuple(int(i) for i in pos.split(","))
vel = tuple(int(i) for i in vel.split(","))
acc = tuple(int(i) for i in acc.split(","))
return Particle(pos, vel, acc, id)
| def parse(input: str, id: int) -> Particle:
| regex = "(-?[0-9]+,-?[0-9]+,-?[0-9]+)"
pos,vel,acc = re.findall(regex, input)
pos = tuple(int(i) for i in pos.split(","))
vel = tuple(int(i) for i in vel.split(","))
acc = tuple(int(i) for i in acc.split(","))
return Particle(pos, vel, acc, id)
| 1]+vel[1], p.pos[2]+vel[2])
return Particle(pos, vel, p.acc, p.id)
def getDist(p: Particle) -> int:
return sum([abs(i) for i in p.pos])
def parse(input: str, id: int) -> Particle:
| 64 | 64 | 102 | 13 | 51 | gcalmettes/AdventOfCode2017 | 2017/day20.py | Python | parse | parse | 23 | 29 | 23 | 23 | 7eb40b70618b0ffcbaa790adacfcb464e02780a8 | bigcode/the-stack | train |
1c3f8d4aa876f946a96f66fa | train | function | def removeCollided(pList: List[Particle]) -> List[Particle]:
allPos = Counter([p.pos for p in pList])
particles = [p for p in pList if allPos[p.pos]==1]
return particles
| def removeCollided(pList: List[Particle]) -> List[Particle]:
| allPos = Counter([p.pos for p in pList])
particles = [p for p in pList if allPos[p.pos]==1]
return particles
| (i) for i in pos.split(","))
vel = tuple(int(i) for i in vel.split(","))
acc = tuple(int(i) for i in acc.split(","))
return Particle(pos, vel, acc, id)
def removeCollided(pList: List[Particle]) -> List[Particle]:
| 64 | 64 | 52 | 16 | 48 | gcalmettes/AdventOfCode2017 | 2017/day20.py | Python | removeCollided | removeCollided | 31 | 34 | 31 | 31 | 20100d49354de5d08bcd937dc8e5a358a9459f84 | bigcode/the-stack | train |
bd98f9c6857c17b48d977ca1 | train | function | def getDist(p: Particle) -> int:
return sum([abs(i) for i in p.pos])
| def getDist(p: Particle) -> int:
| return sum([abs(i) for i in p.pos])
| p.vel[2]+p.acc[2])
pos = (p.pos[0]+vel[0], p.pos[1]+vel[1], p.pos[2]+vel[2])
return Particle(pos, vel, p.acc, p.id)
def getDist(p: Particle) -> int:
| 64 | 64 | 23 | 10 | 54 | gcalmettes/AdventOfCode2017 | 2017/day20.py | Python | getDist | getDist | 20 | 21 | 20 | 20 | c903721ee2b892450646a279996c9a082332b541 | bigcode/the-stack | train |
cc86937e8cf4453712b4b0b6 | train | class | class Particle(NamedTuple):
pos: Tuple[int, int, int]
vel: Tuple[int, int, int]
acc: Tuple[int, int, int]
id: int
| class Particle(NamedTuple):
| pos: Tuple[int, int, int]
vel: Tuple[int, int, int]
acc: Tuple[int, int, int]
id: int
| """
http://adventofcode.com/2017/day/20
"""
import re
from collections import Counter
from typing import NamedTuple, Tuple, List
class Particle(NamedTuple):
| 40 | 64 | 41 | 6 | 33 | gcalmettes/AdventOfCode2017 | 2017/day20.py | Python | Particle | Particle | 9 | 13 | 9 | 9 | b192b23c4f9b4bcb5671de4fcfc12548a9723560 | bigcode/the-stack | train |
bf5b617ff7d87e670b8e7e0f | train | class | class DecodeDetections(Layer):
'''
A Keras layer to decode the raw SSD prediction output.
Input shape:
3D tensor of shape `(batch_size, n_boxes, n_classes + 12)`.
Output shape:
3D tensor of shape `(batch_size, top_k, 6)`.
'''
def __init__(self,
confidence_thre... | class DecodeDetections(Layer):
| '''
A Keras layer to decode the raw SSD prediction output.
Input shape:
3D tensor of shape `(batch_size, n_boxes, n_classes + 12)`.
Output shape:
3D tensor of shape `(batch_size, top_k, 6)`.
'''
def __init__(self,
confidence_thresh=0.01,
iou_t... | '''
A custom Keras layer to decode the raw SSD prediction output. Corresponds to the
`DetectionOutput` layer type in the original Caffe implementation of SSD.
Copyright (C) 2018 Pierluigi Ferrari
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the Li... | 196 | 256 | 2,982 | 7 | 188 | covid19-specialist/ssd_keras | keras_layers/keras_layer_DecodeDetections.py | Python | DecodeDetections | DecodeDetections | 26 | 282 | 26 | 26 | d8111a116f28438b0e5602bdb4e2e86748ead487 | bigcode/the-stack | train |
3abae8c2d98cbbe96cc81f90 | train | class | class Migration(migrations.Migration):
dependencies = [
('files', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='user',
name='name',
field=models.CharField(max_length=55),
),
]
| class Migration(migrations.Migration):
| dependencies = [
('files', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='user',
name='name',
field=models.CharField(max_length=55),
),
]
| # Generated by Django 3.0.4 on 2020-04-06 12:08
from django.db import migrations, models
class Migration(migrations.Migration):
| 38 | 64 | 56 | 7 | 30 | Asko-Dev/File_Upload_RESTAPI | files/migrations/0002_auto_20200406_1208.py | Python | Migration | Migration | 6 | 18 | 6 | 7 | bbe7051c2b912b392d0b045d65a5fff31493cccf | bigcode/the-stack | train |
843002e70eaa40e020012c9c | train | function | def copy_files(files: T.List[str], input_dir: PathLike, output_dir: PathLike) -> None:
if not input_dir:
raise ValueError(f'Input directory value is not set')
if not output_dir:
raise ValueError(f'Output directory value is not set')
input_dir = Path(input_dir).resolve()
output_dir = Pat... | def copy_files(files: T.List[str], input_dir: PathLike, output_dir: PathLike) -> None:
| if not input_dir:
raise ValueError(f'Input directory value is not set')
if not output_dir:
raise ValueError(f'Output directory value is not set')
input_dir = Path(input_dir).resolve()
output_dir = Path(output_dir).resolve()
output_dir.mkdir(parents=True, exist_ok=True)
for f in... | permissions and
# limitations under the License.
'''
Copy files
'''
import argparse
import shutil
import typing as T
from pathlib import Path
PathLike = T.Union[Path,str]
def copy_files(files: T.List[str], input_dir: PathLike, output_dir: PathLike) -> None:
| 64 | 64 | 137 | 24 | 40 | iinuwa/meson | tools/copy_files.py | Python | copy_files | copy_files | 29 | 43 | 29 | 29 | fce6cb63595382a6dc2fbc1d0d6a2b6698e18bc2 | bigcode/the-stack | train |
d068505b2e879f57b09cd884 | train | function | def main():
Ebb = cfg.Ebb
if len(sys.argv) == 3:
provider = str(sys.argv[1])
key = str(sys.argv[2])
else:
provider = "0x4e4a0750350796164d8defc442a712b7557bf282"
key = "QmRsaBEGcqxQcJbBxCi1LN9iz5bDAGDWR6Hx7ZvWqgqmdR"
print(Ebb.getJobSize(provider, key))
| def main():
| Ebb = cfg.Ebb
if len(sys.argv) == 3:
provider = str(sys.argv[1])
key = str(sys.argv[2])
else:
provider = "0x4e4a0750350796164d8defc442a712b7557bf282"
key = "QmRsaBEGcqxQcJbBxCi1LN9iz5bDAGDWR6Hx7ZvWqgqmdR"
print(Ebb.getJobSize(provider, key))
| #!/usr/bin/env python3
import sys
from broker import cfg
def main():
| 18 | 64 | 118 | 3 | 14 | ebloc/EBlocBroker | broker/eblocbroker_scripts/get_job_size.py | Python | main | main | 8 | 17 | 8 | 8 | f2bb5f022d44deb65c7828eb6b16ffb7e91958aa | bigcode/the-stack | train |
45c35441b1c44091b08cd847 | train | function | def log_warn(*args):
_eager_log("warn", *args)
| def log_warn(*args):
| _eager_log("warn", *args)
| *args):
if tf.contrib.eager.in_eager_mode() and args in _already_logged:
return
_already_logged.add(args)
getattr(tf.logging, level)(*args)
def log_info(*args):
_eager_log("info", *args)
def log_warn(*args):
| 64 | 64 | 17 | 6 | 58 | Zhangyantsing/tensor2tensor | tensor2tensor/utils/t2t_model.py | Python | log_warn | log_warn | 1,809 | 1,810 | 1,809 | 1,809 | 4b56f2479c0397dd125db6f89409bdc92604965a | bigcode/the-stack | train |
fc4fd1e8ed4339e2f2a43973 | train | function | def _create_dummy_vars():
"""Dummy vars for restore to work when not using TPU codepath."""
var_names = set([v.name for v in tf.global_variables()])
if "losses_avg/problem_0/total_loss:0" in var_names:
return
with tf.variable_scope("losses_avg"):
with tf.variable_scope("problem_0"):
for var_name i... | def _create_dummy_vars():
| """Dummy vars for restore to work when not using TPU codepath."""
var_names = set([v.name for v in tf.global_variables()])
if "losses_avg/problem_0/total_loss:0" in var_names:
return
with tf.variable_scope("losses_avg"):
with tf.variable_scope("problem_0"):
for var_name in ["total", "extra", "trai... | ):
start_time = time.time()
res = fn(*args, **kwargs)
if not silent:
log_info("Doing %s took %.3f sec." % (msg, time.time() - start_time))
return res
return fn_with_timing
def _create_dummy_vars():
| 64 | 64 | 143 | 6 | 57 | Zhangyantsing/tensor2tensor | tensor2tensor/utils/t2t_model.py | Python | _create_dummy_vars | _create_dummy_vars | 1,505 | 1,516 | 1,505 | 1,505 | 2026a34143ad73f670b44e6257d2ce4c99998fef | bigcode/the-stack | train |
6fcfdc8c64648bf84a1a3597 | train | function | def log_info(*args):
_eager_log("info", *args)
| def log_info(*args):
| _eager_log("info", *args)
| _mean(nonpadding))
_already_logged = set()
def _eager_log(level, *args):
if tf.contrib.eager.in_eager_mode() and args in _already_logged:
return
_already_logged.add(args)
getattr(tf.logging, level)(*args)
def log_info(*args):
| 64 | 64 | 17 | 6 | 58 | Zhangyantsing/tensor2tensor | tensor2tensor/utils/t2t_model.py | Python | log_info | log_info | 1,805 | 1,806 | 1,805 | 1,805 | 9953487fec7973ff14718be6d242bda6784a9301 | bigcode/the-stack | train |
e965e350b487de07398862d6 | train | function | def _create_tpu_eval_metrics_fn(problem, hparams):
"""Create the metrics_fn that TPUEstimatorSpec expects."""
metric_fns = []
eval_metrics = problem.eval_metrics()
tm = problem.get_hparams().target_modality
if isinstance(tm, dict):
for k, v in six.iteritems(tm):
if isinstance(v, tuple):
v ... | def _create_tpu_eval_metrics_fn(problem, hparams):
| """Create the metrics_fn that TPUEstimatorSpec expects."""
metric_fns = []
eval_metrics = problem.eval_metrics()
tm = problem.get_hparams().target_modality
if isinstance(tm, dict):
for k, v in six.iteritems(tm):
if isinstance(v, tuple):
v = registry.create_modality(v, hparams)
weight... | 0" in var_names:
return
with tf.variable_scope("losses_avg"):
with tf.variable_scope("problem_0"):
for var_name in ["total", "extra", "training"]:
tf.get_variable(
"%s_loss" % var_name, initializer=100.0, trainable=False)
with tf.variable_scope("train_stats"):
tf.get_variable("... | 172 | 172 | 576 | 13 | 159 | Zhangyantsing/tensor2tensor | tensor2tensor/utils/t2t_model.py | Python | _create_tpu_eval_metrics_fn | _create_tpu_eval_metrics_fn | 1,528 | 1,596 | 1,528 | 1,528 | e566dd8d2e26d2feed29874bde715f6c407c3442 | bigcode/the-stack | train |
1f82c480c069c42da2408ae2 | train | function | def _del_dict_non_tensors(d):
for k in list(d.keys()):
if not isinstance(d[k], tf.Tensor):
del d[k]
| def _del_dict_non_tensors(d):
| for k in list(d.keys()):
if not isinstance(d[k], tf.Tensor):
del d[k]
| )), step=gs)
elif name.startswith("ImageSummary"):
name = name[len("ImageSummary"):]
tf.contrib.summary.image(name, value, step=gs)
return tf.contrib.summary.all_summary_ops()
return (host_call_fn, summary_kwargs)
def _del_dict_non_tensors(d):
| 64 | 64 | 32 | 9 | 55 | Zhangyantsing/tensor2tensor | tensor2tensor/utils/t2t_model.py | Python | _del_dict_non_tensors | _del_dict_non_tensors | 1,680 | 1,683 | 1,680 | 1,680 | f8928be87e856d6b2d0d9078b0870cc19e683a4f | bigcode/the-stack | train |
fd3e383381fbab1d352a8974 | train | function | def summarize_features(features, num_shards=1):
"""Generate summaries for features."""
if not common_layers.should_generate_summaries():
return
with tf.name_scope("input_stats"):
for (k, v) in sorted(six.iteritems(features)):
if isinstance(v, tf.Tensor) and v.get_shape().ndims > 1:
tf.summa... | def summarize_features(features, num_shards=1):
| """Generate summaries for features."""
if not common_layers.should_generate_summaries():
return
with tf.name_scope("input_stats"):
for (k, v) in sorted(six.iteritems(features)):
if isinstance(v, tf.Tensor) and v.get_shape().ndims > 1:
tf.summary.scalar("%s_batch" % k, tf.shape(v)[0] // num_... | .maximum(
tf.cast(1.0, sharded_den[0].dtype), tf.add_n(sharded_den)))
else:
mean_loss = tf.reduce_mean(all_shards)
losses[loss_name] = mean_loss
return losses
def summarize_features(features, num_shards=1):
| 64 | 64 | 176 | 11 | 52 | Zhangyantsing/tensor2tensor | tensor2tensor/utils/t2t_model.py | Python | summarize_features | summarize_features | 1,778 | 1,792 | 1,778 | 1,778 | 1f4c02fab0a69b13aac70343239577e64da3f715 | bigcode/the-stack | train |
14fefc3dd1251f29432119d2 | train | function | def average_sharded_losses(sharded_losses):
"""Average losses across datashards.
Args:
sharded_losses: list<dict<str loss_name, Tensor loss>>. The loss
can be a single Tensor or a 2-tuple (numerator and denominator).
Returns:
losses: dict<str loss_name, Tensor avg_loss>
"""
losses = {}
for l... | def average_sharded_losses(sharded_losses):
| """Average losses across datashards.
Args:
sharded_losses: list<dict<str loss_name, Tensor loss>>. The loss
can be a single Tensor or a 2-tuple (numerator and denominator).
Returns:
losses: dict<str loss_name, Tensor avg_loss>
"""
losses = {}
for loss_name in sorted(sharded_losses[0]):
a... | _sampling_warmup_steps, min_value=0.001)
sharded_logits, losses = tf.cond(
tf.less(tf.random_uniform([]), prob), sampled_results,
lambda: (sharded_logits, losses))
return sharded_logits, losses
def average_sharded_losses(sharded_losses):
| 64 | 64 | 208 | 9 | 54 | Zhangyantsing/tensor2tensor | tensor2tensor/utils/t2t_model.py | Python | average_sharded_losses | average_sharded_losses | 1,753 | 1,775 | 1,753 | 1,753 | 92c14b2d69b96efa452357f235ca2a1893e8440f | bigcode/the-stack | train |
41f1e19c4211fdb5c6614dc6 | train | class | class DummyVariableStore(object):
@contextlib.contextmanager
def as_default(self):
yield
| class DummyVariableStore(object):
@contextlib.contextmanager
| def as_default(self):
yield
| return tf.contrib.summary.all_summary_ops()
return (host_call_fn, summary_kwargs)
def _del_dict_non_tensors(d):
for k in list(d.keys()):
if not isinstance(d[k], tf.Tensor):
del d[k]
class DummyVariableStore(object):
@contextlib.contextmanager
| 64 | 64 | 22 | 13 | 51 | Zhangyantsing/tensor2tensor | tensor2tensor/utils/t2t_model.py | Python | DummyVariableStore | DummyVariableStore | 1,686 | 1,690 | 1,686 | 1,688 | 85c4296bd25827a54067e991ce104673169db350 | bigcode/the-stack | train |
8b84a5f522680ad68a233ffb | train | function | def _with_timing(fn, msg, silent=False):
def fn_with_timing(*args, **kwargs):
start_time = time.time()
res = fn(*args, **kwargs)
if not silent:
log_info("Doing %s took %.3f sec." % (msg, time.time() - start_time))
return res
return fn_with_timing
| def _with_timing(fn, msg, silent=False):
| def fn_with_timing(*args, **kwargs):
start_time = time.time()
res = fn(*args, **kwargs)
if not silent:
log_info("Doing %s took %.3f sec." % (msg, time.time() - start_time))
return res
return fn_with_timing
| log_warn(
"%s has a designated modality type %s (%s) but has been "
"overridden with a modality of type %s (%s).", feature_name, old_type,
old_name, new_type, new_name)
def _with_timing(fn, msg, silent=False):
| 64 | 64 | 81 | 12 | 52 | Zhangyantsing/tensor2tensor | tensor2tensor/utils/t2t_model.py | Python | _with_timing | _with_timing | 1,493 | 1,502 | 1,493 | 1,494 | 18f8086ffcd5720b08ab35785349a173c24bfd9b | bigcode/the-stack | train |
b5fdb2c92d44aa1cd1e2016b | train | function | def _remove_summaries():
g = tf.get_default_graph()
key = tf.GraphKeys.SUMMARIES
del g.get_collection_ref(key)[:]
assert not g.get_collection(key)
| def _remove_summaries():
| g = tf.get_default_graph()
key = tf.GraphKeys.SUMMARIES
del g.get_collection_ref(key)[:]
assert not g.get_collection(key)
| ['targets'] against labels.")
metrics_dict["%s/%s" % ("targets", name)] = fn(logits["targets"],
labels)
else:
metrics_dict[name] = fn(logits, labels)
return metrics_dict
return all_metrics_fn
def _remove_summaries():
| 64 | 64 | 44 | 7 | 56 | Zhangyantsing/tensor2tensor | tensor2tensor/utils/t2t_model.py | Python | _remove_summaries | _remove_summaries | 1,599 | 1,603 | 1,599 | 1,599 | 342fe69b0de6a806bebb4c5e90eaca3305c8e37a | bigcode/the-stack | train |
cc92a8eea7ed0c0f1bc5d37b | train | function | def scheduled_sampling(hparams, problem_hparams, dp, sharded_logits, losses,
sharded_features, transformed_features, model):
"""Scheduled sampling."""
target_modality = problem_hparams.target_modality
def sample(x):
"""Multinomial sampling from a n-dimensional tensor."""
vocab_size... | def scheduled_sampling(hparams, problem_hparams, dp, sharded_logits, losses,
sharded_features, transformed_features, model):
| """Scheduled sampling."""
target_modality = problem_hparams.target_modality
def sample(x):
"""Multinomial sampling from a n-dimensional tensor."""
vocab_size = target_modality.top_dimensionality
samples = tf.multinomial(tf.reshape(x, [-1, vocab_size]), 1)
reshaped_samples = tf.reshape(samples, co... | tf.contrib.summary.image(name, value, step=gs)
return tf.contrib.summary.all_summary_ops()
return (host_call_fn, summary_kwargs)
def _del_dict_non_tensors(d):
for k in list(d.keys()):
if not isinstance(d[k], tf.Tensor):
del d[k]
class DummyVariableStore(object):
@contextlib.co... | 150 | 150 | 501 | 28 | 122 | Zhangyantsing/tensor2tensor | tensor2tensor/utils/t2t_model.py | Python | scheduled_sampling | scheduled_sampling | 1,700 | 1,750 | 1,700 | 1,701 | fa8946c861a1a3a6a228ff36214417b2450420c5 | bigcode/the-stack | train |
c1a63eb613fa9b90056cf166 | train | function | def _eager_log(level, *args):
if tf.contrib.eager.in_eager_mode() and args in _already_logged:
return
_already_logged.add(args)
getattr(tf.logging, level)(*args)
| def _eager_log(level, *args):
| if tf.contrib.eager.in_eager_mode() and args in _already_logged:
return
_already_logged.add(args)
getattr(tf.logging, level)(*args)
| nonpadding_tokens = tf.reduce_sum(nonpadding)
tf.summary.scalar("%s_nonpadding_tokens" % k, nonpadding_tokens)
tf.summary.scalar("%s_nonpadding_fraction" % k,
tf.reduce_mean(nonpadding))
_already_logged = set()
def _eager_log(level, *args):
| 64 | 64 | 48 | 10 | 54 | Zhangyantsing/tensor2tensor | tensor2tensor/utils/t2t_model.py | Python | _eager_log | _eager_log | 1,798 | 1,802 | 1,798 | 1,798 | 154f912b394353120740313d13eee68ceb56ec9f | bigcode/the-stack | train |
e841d9dafd7daeb3931eb987 | train | function | def _create_host_call(model_dir):
"""Construct a host_call writing scalar summaries.
Args:
model_dir: String containing path to train
Returns:
(fn, args) Pair to be called by TPUEstimator as the host_call.
"""
graph = tf.get_default_graph()
summaries = graph.get_collection(tf.GraphKeys.SUMMARIES)
... | def _create_host_call(model_dir):
| """Construct a host_call writing scalar summaries.
Args:
model_dir: String containing path to train
Returns:
(fn, args) Pair to be called by TPUEstimator as the host_call.
"""
graph = tf.get_default_graph()
summaries = graph.get_collection(tf.GraphKeys.SUMMARIES)
gs_t = tf.reshape(tf.to_int32(t... | logits = kwargs
for name, fn in metric_fns:
if isinstance(logits, dict) and isinstance(labels, dict):
for k, v in six.iteritems(logits):
metrics_dict["%s/%s" % (k, name)] = fn(v, labels[k])
elif isinstance(logits, dict):
tf.logging.warning("Logits is a dict, but labels is not... | 201 | 201 | 673 | 8 | 193 | Zhangyantsing/tensor2tensor | tensor2tensor/utils/t2t_model.py | Python | _create_host_call | _create_host_call | 1,606 | 1,677 | 1,606 | 1,606 | dc04f5a66dce1c5226c30e82711053f89d71a0f8 | bigcode/the-stack | train |
b96f5581a5ac069e723dce5d | train | function | def set_custom_getter_compose(custom_getter):
"""Set a custom getter in the current variable scope.
Do not overwrite the existing custom getter - rather compose with it.
Args:
custom_getter: a custom getter.
"""
tf.get_variable_scope().set_custom_getter(
_compose_custom_getters(tf.get_variable_sco... | def set_custom_getter_compose(custom_getter):
| """Set a custom getter in the current variable scope.
Do not overwrite the existing custom getter - rather compose with it.
Args:
custom_getter: a custom getter.
"""
tf.get_variable_scope().set_custom_getter(
_compose_custom_getters(tf.get_variable_scope().custom_getter,
... | return getter_b
if not getter_b:
return getter_a
def getter_fn(getter, *args, **kwargs):
return getter_b(functools.partial(getter_a, getter), *args, **kwargs)
return getter_fn
def set_custom_getter_compose(custom_getter):
| 64 | 64 | 82 | 11 | 52 | Zhangyantsing/tensor2tensor | tensor2tensor/utils/t2t_model.py | Python | set_custom_getter_compose | set_custom_getter_compose | 1,841 | 1,851 | 1,841 | 1,841 | a6b0cbf1a478eb0d2a78d45dbd4451f381907dab | bigcode/the-stack | train |
1fb41f195d247df2a7e2959c | train | function | def create_eager_var_store():
if tf.contrib.eager.in_eager_mode():
return variable_scope.EagerVariableStore()
else:
return DummyVariableStore()
| def create_eager_var_store():
| if tf.contrib.eager.in_eager_mode():
return variable_scope.EagerVariableStore()
else:
return DummyVariableStore()
| summary_kwargs)
def _del_dict_non_tensors(d):
for k in list(d.keys()):
if not isinstance(d[k], tf.Tensor):
del d[k]
class DummyVariableStore(object):
@contextlib.contextmanager
def as_default(self):
yield
def create_eager_var_store():
| 64 | 64 | 36 | 7 | 56 | Zhangyantsing/tensor2tensor | tensor2tensor/utils/t2t_model.py | Python | create_eager_var_store | create_eager_var_store | 1,693 | 1,697 | 1,693 | 1,693 | bb8c529de3e13ab2efc44382185a40c1b5dcea31 | bigcode/the-stack | train |
8bfc3ffe1b44c89c132fb5f7 | train | function | def _compose_custom_getters(getter_a, getter_b):
"""Compose two custom getters.
Example use:
tf.get_variable_scope().set_custom_getter(
compose_custom_getters(tf.get_variable_scope().custom_getter, new_getter))
This composes getters in the same way as creating a new variable scope with
the new_getter, b... | def _compose_custom_getters(getter_a, getter_b):
| """Compose two custom getters.
Example use:
tf.get_variable_scope().set_custom_getter(
compose_custom_getters(tf.get_variable_scope().custom_getter, new_getter))
This composes getters in the same way as creating a new variable scope with
the new_getter, but it does not actually create a new variable sco... | _already_logged.add(args)
getattr(tf.logging, level)(*args)
def log_info(*args):
_eager_log("info", *args)
def log_warn(*args):
_eager_log("warn", *args)
def _compose_custom_getters(getter_a, getter_b):
| 64 | 64 | 183 | 13 | 51 | Zhangyantsing/tensor2tensor | tensor2tensor/utils/t2t_model.py | Python | _compose_custom_getters | _compose_custom_getters | 1,813 | 1,838 | 1,813 | 1,813 | b253bc5db6efbabae9b5664d645d98b17c7cd54e | bigcode/the-stack | train |
a4ca53ea90b3b42933acfb26 | train | class | class T2TModel(base.Layer):
"""Abstract base class for models.
Subclassess generally only need to override `body`.
"""
REGISTERED_NAME = None # Updated on registration.
def __init__(self,
hparams,
mode=tf.estimator.ModeKeys.TRAIN,
problem_hparams=None,
... | class T2TModel(base.Layer):
| """Abstract base class for models.
Subclassess generally only need to override `body`.
"""
REGISTERED_NAME = None # Updated on registration.
def __init__(self,
hparams,
mode=tf.estimator.ModeKeys.TRAIN,
problem_hparams=None,
data_parallelism=None,... |
import time
import six
from tensor2tensor.data_generators import multi_problem
from tensor2tensor.data_generators import text_encoder
from tensor2tensor.data_generators.problem import problem_hparams_to_features
from tensor2tensor.layers import common_layers
from tensor2tensor.layers import modalities # pylint: disa... | 256 | 256 | 13,207 | 8 | 248 | Zhangyantsing/tensor2tensor | tensor2tensor/utils/t2t_model.py | Python | T2TModel | T2TModel | 57 | 1,480 | 57 | 57 | 4197203f9072704dc693ec08aad3224179f6e5dd | bigcode/the-stack | train |
990fb1305ec615276ec49832 | train | function | def _warn_changed_modality_type(new_name, old_name, feature_name):
new_type, new_name = registry.parse_modality_name(new_name)
old_type, old_name = registry.parse_modality_name(old_name)
if new_type != old_type:
log_warn(
"%s has a designated modality type %s (%s) but has been "
"overridden wi... | def _warn_changed_modality_type(new_name, old_name, feature_name):
| new_type, new_name = registry.parse_modality_name(new_name)
old_type, old_name = registry.parse_modality_name(old_name)
if new_type != old_type:
log_warn(
"%s has a designated modality type %s (%s) but has been "
"overridden with a modality of type %s (%s).", feature_name, old_type,
ol... |
if not isinstance(losses, dict):
losses = {"extra": tf.reduce_mean(losses)}
else:
output = body_out
losses = {"extra": 0.0}
return output, losses
def _warn_changed_modality_type(new_name, old_name, feature_name):
| 64 | 64 | 106 | 16 | 47 | Zhangyantsing/tensor2tensor | tensor2tensor/utils/t2t_model.py | Python | _warn_changed_modality_type | _warn_changed_modality_type | 1,483 | 1,490 | 1,483 | 1,483 | b6e230c018a5cd73794e5782334058cc07cfb3bd | bigcode/the-stack | train |
e423d5a4b36ab18366ac2a16 | train | function | @app.route('/visualizations/', methods=['GET', 'POST'])
def visualizations():
df = pd.read_csv('../dat/graph_data.csv')
if request.method == 'POST':
selected = request.form.getlist('selected-university')
# journal
CL = int(request.form['CL'])
TACL = int(request.form['TACL'])
... | @app.route('/visualizations/', methods=['GET', 'POST'])
def visualizations():
| df = pd.read_csv('../dat/graph_data.csv')
if request.method == 'POST':
selected = request.form.getlist('selected-university')
# journal
CL = int(request.form['CL'])
TACL = int(request.form['TACL'])
# conference
ACL_C = int(request.form['ACL-C'])
NAACL_C... | ="NLP Ranking Scores Across U.S. States", tools=TOOLS,
x_axis_location=None, y_axis_location=None,
sizing_mode="scale_width",
plot_width=1100, plot_height=700,
tooltips=[
("State", "@name"), ("Score", "@rate{0,0.00}")
])
p.grid.grid_line_color = None
p.hover.p... | 252 | 252 | 840 | 17 | 235 | hickst/nlprankings | website/website.py | Python | visualizations | visualizations | 353 | 431 | 353 | 354 | 3b33498d6c3f92b39f32a154d80f231f0be27a78 | bigcode/the-stack | train |
4de496262373c962886b4497 | train | function | @app.route('/', methods=['GET', 'POST'])
def home():
s3 = boto3.resource('s3', region_name='us-east-2')
if request.method == 'POST':
# journal
CL = int(request.form['CL'])
TACL = int(request.form['TACL'])
# conference
ACL_C = int(request.form['ACL-C'])
NAACL_C =... | @app.route('/', methods=['GET', 'POST'])
def home():
| s3 = boto3.resource('s3', region_name='us-east-2')
if request.method == 'POST':
# journal
CL = int(request.form['CL'])
TACL = int(request.form['TACL'])
# conference
ACL_C = int(request.form['ACL-C'])
NAACL_C = int(request.form['NAACL-C'])
EMNLP_C = int(r... | from flask import Flask, request, render_template, redirect
import json
from collections import defaultdict
import pandas as pd
import boto3
from datetime import datetime
from bokeh.models import LogColorMapper, ColumnDataSource, FactorRange, Legend
from bokeh.plotting import figure
from bokeh.embed import components
... | 107 | 256 | 932 | 13 | 94 | hickst/nlprankings | website/website.py | Python | home | home | 16 | 103 | 16 | 17 | 6deff1b1dd0c5b0d80839beea46322ad09982a7c | bigcode/the-stack | train |
3bafe1e27d4931b4a1051d12 | train | function | def avg_author_num(df, selected):
df = df[['university','pubID','numAuthor','year']].drop_duplicates()
df = df.groupby(['university','year'])['numAuthor'].mean().reset_index()
def getColumnDataSource(df, selected):
df = df[df['university'].isin(selected)]
years = list(range(2010, 2020))
... | def avg_author_num(df, selected):
| df = df[['university','pubID','numAuthor','year']].drop_duplicates()
df = df.groupby(['university','year'])['numAuthor'].mean().reset_index()
def getColumnDataSource(df, selected):
df = df[df['university'].isin(selected)]
years = list(range(2010, 2020))
x = [years] * len(selected... | .multi_line(xs='xs', ys='ys', source=source, line_color='color')
p.xaxis[0].ticker.desired_num_ticks = 10
p.xaxis.axis_label = "Years"
p.xaxis.axis_label_text_font_style = "normal"
p.yaxis.axis_label = "Contribution Percentage"
p.yaxis.axis_label_text_font_style = "normal"
... | 123 | 123 | 410 | 8 | 115 | hickst/nlprankings | website/website.py | Python | avg_author_num | avg_author_num | 694 | 757 | 694 | 695 | 6e26a84350ac17d24e301ef49e1b9096612837d8 | bigcode/the-stack | train |
86dc2f6453e48c97dce09da7 | train | function | def ratio_of_contribution(df, selected):
df = df.groupby(['university', 'pubID', 'year', 'numAuthor']).size().reset_index(name='AuthorCount')
df['contribution'] = df.apply(lambda x: x.AuthorCount / x.numAuthor, axis=1)
df = df.groupby(['university','year']).agg({'pubID': 'size', 'contribution': 'mean'}).\
... | def ratio_of_contribution(df, selected):
| df = df.groupby(['university', 'pubID', 'year', 'numAuthor']).size().reset_index(name='AuthorCount')
df['contribution'] = df.apply(lambda x: x.AuthorCount / x.numAuthor, axis=1)
df = df.groupby(['university','year']).agg({'pubID': 'size', 'contribution': 'mean'}).\
rename(columns={'pubID': 'count', ... | "normal"
p.axis.minor_tick_line_color = None
p.outline_line_color = None
p.hover.point_policy = "follow_mouse"
legend1 = Legend(title="# of pub per authors",
items=[
("one", [v[1]]),
("two", [v[0]]),
("three or more", [v[0]]),
]... | 142 | 142 | 476 | 9 | 132 | hickst/nlprankings | website/website.py | Python | ratio_of_contribution | ratio_of_contribution | 623 | 691 | 623 | 624 | 97c3ebacd4cb8af9b005261c882a58bd94719868 | bigcode/the-stack | train |
70f4a54bda886a2807ceb0cb | train | function | @app.route('/articles/')
def articles():
return render_template("articles.html");
| @app.route('/articles/')
def articles():
| return render_template("articles.html");
| 2010, maxYear], years=years,
weights=[3,3,3,3,3,2,2,2,2,1], num=[100, 100], uni_authors=uni_authors, script=script, div=div)
@app.route('/articles/')
def articles():
| 64 | 64 | 16 | 8 | 56 | hickst/nlprankings | website/website.py | Python | articles | articles | 106 | 108 | 106 | 107 | 8f34f9224094206902aa13ed6ade354f47cffba8 | bigcode/the-stack | train |
a1fe0a839f9ca2ddbe437546 | train | function | def get_dataset(df, CL, TACL, ACL_C, NAACL_C, EMNLP_C, CoNLL_C, EACL_C, COLING, IJCNLP, WKSPDEMO):
def get_score(venue, type, numAuthor):
score = {'journal': 3, 'conference': 3, 'workshop': 1, 'demonstration': 1}
if venue == 'CL':
venue_score = CL
elif venue == 'TACL':
... | def get_dataset(df, CL, TACL, ACL_C, NAACL_C, EMNLP_C, CoNLL_C, EACL_C, COLING, IJCNLP, WKSPDEMO):
| def get_score(venue, type, numAuthor):
score = {'journal': 3, 'conference': 3, 'workshop': 1, 'demonstration': 1}
if venue == 'CL':
venue_score = CL
elif venue == 'TACL':
venue_score = TACL
elif venue == 'ACL' and type == 'conference':
venue_scor... | , div1=div1, script2=script2, div2=div2, script3=script3, div3=div3,
script4=script4, div4=div4, scriptL=scriptL, divL=divL)
def get_dataset(df, CL, TACL, ACL_C, NAACL_C, EMNLP_C, CoNLL_C, EACL_C, COLING, IJCNLP, WKSPDEMO):
| 99 | 99 | 332 | 43 | 56 | hickst/nlprankings | website/website.py | Python | get_dataset | get_dataset | 434 | 467 | 434 | 435 | 50c2e70fb13b5d2c4c493da818a82fbd34efb3b4 | bigcode/the-stack | train |
a906f7268d751782976c6305 | train | function | def find_venue(pub_id):
if 'W' in pub_id or 'D19-5' in pub_id or 'D19-6' in pub_id:
return pub_id[:-2]
else:
return pub_id[:-3]
| def find_venue(pub_id):
| if 'W' in pub_id or 'D19-5' in pub_id or 'D19-6' in pub_id:
return pub_id[:-2]
else:
return pub_id[:-3]
| line_color="black", line_width=0.5)
return p
def parse_email(domain):
if '.edu' in domain:
d = domain.split('.')
return '.'.join(d[d.index('edu')-1:])
else:
return domain
def find_venue(pub_id):
| 64 | 64 | 53 | 7 | 56 | hickst/nlprankings | website/website.py | Python | find_venue | find_venue | 346 | 350 | 346 | 346 | fd81376460f6478836b034a247fd043c71d34f2e | bigcode/the-stack | train |
9063bd8617038933c6bb10e9 | train | function | def numpub(df, selected):
df = df[df['university'].isin(selected)]
df = df.groupby(['authorID', 'university']).size().reset_index(name='pubCounts')
df['numPub'] = df.pubCounts.apply(lambda x: '1' if x==1 else '2' if x==2 else '3 or more')
df = df.groupby(['university', 'numPub']).size().reset_index(nam... | def numpub(df, selected):
| df = df[df['university'].isin(selected)]
df = df.groupby(['authorID', 'university']).size().reset_index(name='pubCounts')
df['numPub'] = df.pubCounts.apply(lambda x: '1' if x==1 else '2' if x==2 else '3 or more')
df = df.groupby(['university', 'numPub']).size().reset_index(name='count')
def getCol... | .9,
source=source,
line_color=None,
fill_alpha=[1, 0.6],
fill_color=factor_cmap('x', palette=Set2_5, factors=selected, start=1, end=2))
p.y_range.start = 0
p.x_range.range_padding = 0.1
p.xaxis.major_label_text_... | 196 | 196 | 655 | 7 | 189 | hickst/nlprankings | website/website.py | Python | numpub | numpub | 547 | 619 | 547 | 548 | 5f0e3d62f089b84cd03666a7c3f5996b9da4abf9 | bigcode/the-stack | train |
ecab964a91828be9a8324f22 | train | function | def score_timeline(df, selected):
df = df[df['university'].isin(selected)]
df = df.groupby(['authorID', 'university', 'year'])['score'].sum().reset_index()
df['90th'] = df.groupby(['university', 'year'])['score'].transform(lambda x: x.quantile(.9))
df['top10'] = df['score'] >= df['90th']
df['s_scor... | def score_timeline(df, selected):
| df = df[df['university'].isin(selected)]
df = df.groupby(['authorID', 'university', 'year'])['score'].sum().reset_index()
df['90th'] = df.groupby(['university', 'year'])['score'].transform(lambda x: x.quantile(.9))
df['top10'] = df['score'] >= df['90th']
df['s_score'] = df.groupby(['university', 'ye... | = NAACL_C
elif venue == 'EMNLP' and type == 'conference':
venue_score = EMNLP_C
elif venue == 'CoNLL' and type == 'conference':
venue_score = CoNLL_C
elif venue == 'EACL' and type == 'conference':
venue_score = EACL_C
elif venue == 'COLING':
... | 195 | 195 | 652 | 8 | 186 | hickst/nlprankings | website/website.py | Python | score_timeline | score_timeline | 470 | 544 | 470 | 471 | e742450950c44c0c112d12e021b21349f7a42478 | bigcode/the-stack | train |
09033deb7a465973274beeb3 | train | function | def get_author_dict(CL,TACL,ACL_C,NAACL_C,EMNLP_C,CoNLL_C,EACL_C,COLING,IJCNLP,WKSPDEMO):
university = pd.read_json('../dat/university_us.json', orient='records')
bibmap = json.load(open('../dat/bibmap.json'))
venue_pub = {} # only look at publications with authors from an university institution
for ... | def get_author_dict(CL,TACL,ACL_C,NAACL_C,EMNLP_C,CoNLL_C,EACL_C,COLING,IJCNLP,WKSPDEMO):
| university = pd.read_json('../dat/university_us.json', orient='records')
bibmap = json.load(open('../dat/bibmap.json'))
venue_pub = {} # only look at publications with authors from an university institution
for pub_id in [y[0] for x in university['publications'].values.tolist() if x for y in x]:
... | 2010, maxYear, 100, 100, 3, 3, 3, 3, 3, 2, 2, 2, 2, 1]
data = ','.join(map(str, info))
filename = 'log/' + str(datetime.utcnow()) + '.txt'
object = s3.Object('nlprankings', filename)
object.put(Body=data)
# us map
plot = create_us_state_map(scores)
script, div =... | 255 | 256 | 934 | 40 | 215 | hickst/nlprankings | website/website.py | Python | get_author_dict | get_author_dict | 112 | 199 | 112 | 113 | a6f09f48416d7401a9b12325866c9c9fc6a460fd | bigcode/the-stack | train |
42d9f98b42146d4bd561341b | train | function | def selected_color_legend(selected):
empty = False
if selected == []:
empty = True
selected = ['']
height = 20 + len(selected) * 40
p = figure(toolbar_location=None, plot_width=400, plot_height=height)
if empty:
p.square(x=0, y=0, size=0, color="white", legend_label='Plea... | def selected_color_legend(selected):
| empty = False
if selected == []:
empty = True
selected = ['']
height = 20 + len(selected) * 40
p = figure(toolbar_location=None, plot_width=400, plot_height=height)
if empty:
p.square(x=0, y=0, size=0, color="white", legend_label='Please choose up to 5 universities')
e... | axis.axis_label = "Avg. Number of Authors"
p.yaxis.axis_label_text_font_style = "normal"
p.xgrid.grid_line_color = None
return p
source = getColumnDataSource(df, selected)
return make_plot(source,selected)
def selected_color_legend(selected):
| 64 | 64 | 173 | 7 | 57 | hickst/nlprankings | website/website.py | Python | selected_color_legend | selected_color_legend | 759 | 782 | 759 | 760 | c1b1e66da64e9bcefaa44addcfb87e4cd0d6b50d | bigcode/the-stack | train |
88d526e49dc71a346a976f37 | train | function | def parse_email(domain):
if '.edu' in domain:
d = domain.split('.')
return '.'.join(d[d.index('edu')-1:])
else:
return domain
| def parse_email(domain):
| if '.edu' in domain:
d = domain.split('.')
return '.'.join(d[d.index('edu')-1:])
else:
return domain
| .point_policy = "follow_mouse"
p.patches('x', 'y', source=data,
fill_color={'field': 'rate', 'transform': color_mapper},
fill_alpha=0.7, line_color="black", line_width=0.5)
return p
def parse_email(domain):
| 64 | 64 | 41 | 5 | 58 | hickst/nlprankings | website/website.py | Python | parse_email | parse_email | 338 | 343 | 338 | 338 | 2187c2879045e2da2a3009b8cc70176ed924b8ec | bigcode/the-stack | train |
ea0cd9bedb99eda182d28b2f | train | function | def ranking(authors, startYear, endYear):
us_universities = pd.read_json('../dat/university_domain_us.json', orient='records')
# create dictionary with all the possible domains as key, and the domain_id (the first domain) as value
# such that for university with multiple domains, domains will be "convert... | def ranking(authors, startYear, endYear):
| us_universities = pd.read_json('../dat/university_domain_us.json', orient='records')
# create dictionary with all the possible domains as key, and the domain_id (the first domain) as value
# such that for university with multiple domains, domains will be "converted" to domain_id for matching purpose
d... | parse_email(pub['emails'][i].split('@')[1])
if uni_domain in us_domains:
author_id = pub['author_id'][i]
year = pub['year']
if int(year) > maxYear:
maxYear = int(year)
... | 256 | 256 | 946 | 11 | 244 | hickst/nlprankings | website/website.py | Python | ranking | ranking | 205 | 290 | 205 | 206 | 04242d6a167a156e6797a69fe35ff0bbf549ca5b | bigcode/the-stack | train |
37b96c7af8bd0c620f445c64 | train | function | def create_us_state_map(scores):
from bokeh.sampledata.us_states import data as states
states = {
code: states for code, states in states.items() if code not in ['AK', 'HI']
}
state_xs = [state["lons"] for state in states.values()]
state_ys = [state["lats"] for state in states.values()]
... | def create_us_state_map(scores):
| from bokeh.sampledata.us_states import data as states
states = {
code: states for code, states in states.items() if code not in ['AK', 'HI']
}
state_xs = [state["lons"] for state in states.values()]
state_ys = [state["lats"] for state in states.values()]
teal_palette = ['#ffffff', '#e... | ['domain'].map(uni_authors)
# us_map (score by states)
us_states = dict(zip(us_universities.domain_id, us_universities.state))
state_scores['State'] = rank['domain'].map(us_states)
state_scores = state_scores.groupby('State').sum()
state_scores = state_scores.round(2)
state_scores = state_scor... | 120 | 120 | 403 | 7 | 112 | hickst/nlprankings | website/website.py | Python | create_us_state_map | create_us_state_map | 295 | 336 | 295 | 295 | 422aa10a7d1855a3ae5b4cb8c30565709f2591c2 | bigcode/the-stack | train |
9855813c68a75f95ffa8d273 | train | function | def getInstDecls(s: str) -> str:
return JDeserialize.findblock(s, "instance dump")
| def getInstDecls(s: str) -> str:
| return JDeserialize.findblock(s, "instance dump")
| from anytree.exporter import DictExporter
import Download
import JDeserialize
def getInstDecls(s: str) -> str:
| 28 | 64 | 24 | 12 | 15 | arma3modorganizer/a3s_to_json | sync/__init__.py | Python | getInstDecls | getInstDecls | 7 | 8 | 7 | 7 | a96521f755db440017cc6a90f46d38331b467238 | bigcode/the-stack | train |
9a9339612e27dcfe803073a3 | train | function | def parse(url: str) -> dict:
file_path = Download.downloadFile(url)
deserialize_raw = JDeserialize.Deserialize(file_path)
autoconfig = parse_jd(deserialize_raw)
Download.cleanup(file_path)
return autoconfig
| def parse(url: str) -> dict:
| file_path = Download.downloadFile(url)
deserialize_raw = JDeserialize.Deserialize(file_path)
autoconfig = parse_jd(deserialize_raw)
Download.cleanup(file_path)
return autoconfig
| Dirs = JDeserialize.GetAllInstancesOfType(instDecl, "repository.SyncTreeDirectory")
tree = JDeserialize.BuildTree(SyncTreeDirs, SyncTreeLeafs)
# print(RenderTree(tree))
di = DictExporter().export(tree)
return di
def parse(url: str) -> dict:
| 64 | 64 | 52 | 9 | 54 | arma3modorganizer/a3s_to_json | sync/__init__.py | Python | parse | parse | 26 | 32 | 26 | 26 | 735ab9fb4bf0e86f01d7a938ff1d3cd9e9e063de | bigcode/the-stack | train |
fbd0ced9085fc331545e84d0 | train | function | def parse_jd(deserialize_raw: str) -> dict:
instDecl = getInstDecls(deserialize_raw)
SyncTreeLeafs = JDeserialize.GetAllInstancesOfType(instDecl, "repository.SyncTreeLeaf")
SyncTreeDirs = JDeserialize.GetAllInstancesOfType(instDecl, "repository.SyncTreeDirectory")
tree = JDeserialize.BuildTree(SyncTre... | def parse_jd(deserialize_raw: str) -> dict:
| instDecl = getInstDecls(deserialize_raw)
SyncTreeLeafs = JDeserialize.GetAllInstancesOfType(instDecl, "repository.SyncTreeLeaf")
SyncTreeDirs = JDeserialize.GetAllInstancesOfType(instDecl, "repository.SyncTreeDirectory")
tree = JDeserialize.BuildTree(SyncTreeDirs, SyncTreeLeafs)
# print(RenderTre... | from anytree.exporter import DictExporter
import Download
import JDeserialize
def getInstDecls(s: str) -> str:
return JDeserialize.findblock(s, "instance dump")
def parse_jd(deserialize_raw: str) -> dict:
| 53 | 64 | 105 | 13 | 40 | arma3modorganizer/a3s_to_json | sync/__init__.py | Python | parse_jd | parse_jd | 11 | 23 | 11 | 11 | bc29ed5b0c46e5b4ac5646f17046d732a8fd396c | bigcode/the-stack | train |
12b642c573a100635b0c7a4d | train | class | class TestTEDPolicyHighRankingLength(TestTEDPolicy):
def create_policy(
self, featurizer: Optional[TrackerFeaturizer], priority: int
) -> Policy:
return TEDPolicy(
featurizer=featurizer, priority=priority, **{RANKING_LENGTH: 11}
)
def test_ranking_length(self, trained_po... | class TestTEDPolicyHighRankingLength(TestTEDPolicy):
| def create_policy(
self, featurizer: Optional[TrackerFeaturizer], priority: int
) -> Policy:
return TEDPolicy(
featurizer=featurizer, priority=priority, **{RANKING_LENGTH: 11}
)
def test_ranking_length(self, trained_policy: TEDPolicy):
assert trained_policy.confi... | featurizer=featurizer, priority=priority, **{RANKING_LENGTH: 3}
)
def test_ranking_length(self, trained_policy: TEDPolicy):
assert trained_policy.config[RANKING_LENGTH] == 3
class TestTEDPolicyHighRankingLength(TestTEDPolicy):
| 64 | 64 | 97 | 11 | 52 | engahmed1190/rasa-for-botfront | tests/core/policies/test_ted_policy.py | Python | TestTEDPolicyHighRankingLength | TestTEDPolicyHighRankingLength | 464 | 473 | 464 | 464 | fb30fe18bd9271e7d75b195721aafd94b6db7253 | bigcode/the-stack | train |
5939f687f30697c53ef00ff2 | train | class | class TestTEDPolicyWithRelativeAttention(TestTEDPolicy):
def create_policy(
self, featurizer: Optional[TrackerFeaturizer], priority: int
) -> Policy:
return TEDPolicy(
featurizer=featurizer,
priority=priority,
**{
KEY_RELATIVE_ATTENTION: True,
... | class TestTEDPolicyWithRelativeAttention(TestTEDPolicy):
| def create_policy(
self, featurizer: Optional[TrackerFeaturizer], priority: int
) -> Policy:
return TEDPolicy(
featurizer=featurizer,
priority=priority,
**{
KEY_RELATIVE_ATTENTION: True,
VALUE_RELATIVE_ATTENTION: True,
... | load(str(tmp_path))
assert isinstance(loaded.featurizer, MaxHistoryTrackerFeaturizer)
assert loaded.featurizer.max_history == self.max_history
assert isinstance(loaded.featurizer.state_featurizer, SingleStateFeaturizer)
class TestTEDPolicyWithRelativeAttention(TestTEDPolicy):
| 64 | 64 | 92 | 11 | 53 | engahmed1190/rasa-for-botfront | tests/core/policies/test_ted_policy.py | Python | TestTEDPolicyWithRelativeAttention | TestTEDPolicyWithRelativeAttention | 518 | 530 | 518 | 518 | 50b4b1bf34909d43bae9a335fffc4fdff1546e3e | bigcode/the-stack | train |
0fb2c4cfc43d022ddf44c981 | train | class | class TestTEDPolicyInnerConfidence(TestTEDPolicy):
def create_policy(
self, featurizer: Optional[TrackerFeaturizer], priority: int
) -> Policy:
return TEDPolicy(
featurizer=featurizer, priority=priority, **{MODEL_CONFIDENCE: INNER}
)
def test_confidence_type(self, traine... | class TestTEDPolicyInnerConfidence(TestTEDPolicy):
| def create_policy(
self, featurizer: Optional[TrackerFeaturizer], priority: int
) -> Policy:
return TEDPolicy(
featurizer=featurizer, priority=priority, **{MODEL_CONFIDENCE: INNER}
)
def test_confidence_type(self, trained_policy: TEDPolicy):
assert trained_policy... | trained_policy: Policy, default_domain: Domain
):
tracker = DialogueStateTracker(DEFAULT_SENDER_ID, default_domain.slots)
prediction = trained_policy.predict_action_probabilities(
tracker, default_domain, RegexInterpreter()
)
assert not prediction.is_end_to_end_predictio... | 114 | 114 | 382 | 10 | 103 | engahmed1190/rasa-for-botfront | tests/core/policies/test_ted_policy.py | Python | TestTEDPolicyInnerConfidence | TestTEDPolicyInnerConfidence | 402 | 449 | 402 | 402 | 83d5d2b34dc9d55cebeae0ece647c72d65567a44 | bigcode/the-stack | train |
163b9ec38381cdc5265b92db | train | class | class TestTEDPolicyMargin(TestTEDPolicy):
def create_policy(
self, featurizer: Optional[TrackerFeaturizer], priority: int
) -> Policy:
return TEDPolicy(
featurizer=featurizer, priority=priority, **{LOSS_TYPE: "margin"}
)
def test_similarity_type(self, trained_policy: TED... | class TestTEDPolicyMargin(TestTEDPolicy):
| def create_policy(
self, featurizer: Optional[TrackerFeaturizer], priority: int
) -> Policy:
return TEDPolicy(
featurizer=featurizer, priority=priority, **{LOSS_TYPE: "margin"}
)
def test_similarity_type(self, trained_policy: TEDPolicy):
assert trained_policy.con... | assert (
batch_action_name_sentence_shape[1] == seq_len
or batch_action_name_sentence_shape[1] == 0
)
assert (
batch_entities_sentence_shape[1] == seq_len
or batch_entities_sentence_shape[1] == 0
)
assert (
batch_slots_s... | 101 | 101 | 339 | 9 | 92 | engahmed1190/rasa-for-botfront | tests/core/policies/test_ted_policy.py | Python | TestTEDPolicyMargin | TestTEDPolicyMargin | 262 | 303 | 262 | 262 | b92aff96f0d3910b6616d2190c380e7e0e7f35f6 | bigcode/the-stack | train |
cde68e61d89ec1bf7f10b634 | train | class | class TestTEDPolicyWithStandardFeaturizer(TestTEDPolicy):
def create_policy(
self, featurizer: Optional[TrackerFeaturizer], priority: int
) -> Policy:
# use standard featurizer from TEDPolicy,
# since it is using MaxHistoryTrackerFeaturizer
# if max_history is not specified
... | class TestTEDPolicyWithStandardFeaturizer(TestTEDPolicy):
| def create_policy(
self, featurizer: Optional[TrackerFeaturizer], priority: int
) -> Policy:
# use standard featurizer from TEDPolicy,
# since it is using MaxHistoryTrackerFeaturizer
# if max_history is not specified
return TEDPolicy(priority=priority)
def test_featu... | aturizer=featurizer, priority=priority, **{RANKING_LENGTH: 11}
)
def test_ranking_length(self, trained_policy: TEDPolicy):
assert trained_policy.config[RANKING_LENGTH] == 11
class TestTEDPolicyWithStandardFeaturizer(TestTEDPolicy):
| 64 | 64 | 196 | 13 | 50 | engahmed1190/rasa-for-botfront | tests/core/policies/test_ted_policy.py | Python | TestTEDPolicyWithStandardFeaturizer | TestTEDPolicyWithStandardFeaturizer | 476 | 493 | 476 | 476 | f0d2b2b2330aead3ff99bd3a2c6c81995c8e2a4f | bigcode/the-stack | train |
48310fa7caee7c39eb708655 | train | class | class TestTEDPolicyWithRelativeAttentionMaxHistoryOne(TestTEDPolicy):
max_history = 1
def create_policy(
self, featurizer: Optional[TrackerFeaturizer], priority: int
) -> Policy:
return TEDPolicy(
featurizer=featurizer,
priority=priority,
**{
... | class TestTEDPolicyWithRelativeAttentionMaxHistoryOne(TestTEDPolicy):
| max_history = 1
def create_policy(
self, featurizer: Optional[TrackerFeaturizer], priority: int
) -> Policy:
return TEDPolicy(
featurizer=featurizer,
priority=priority,
**{
KEY_RELATIVE_ATTENTION: True,
VALUE_RELATIVE_ATTEN... | Policy(
featurizer=featurizer,
priority=priority,
**{
KEY_RELATIVE_ATTENTION: True,
VALUE_RELATIVE_ATTENTION: True,
MAX_RELATIVE_POSITION: 5,
},
)
class TestTEDPolicyWithRelativeAttentionMaxHistoryOne(TestTEDPolicy):... | 64 | 64 | 102 | 14 | 50 | engahmed1190/rasa-for-botfront | tests/core/policies/test_ted_policy.py | Python | TestTEDPolicyWithRelativeAttentionMaxHistoryOne | TestTEDPolicyWithRelativeAttentionMaxHistoryOne | 533 | 548 | 533 | 534 | 0a836fa61ba5a3db7219de12986b8534be9f4f4d | bigcode/the-stack | train |
18ec6021d3067fd0339aff4b | train | function | def test_diagnostics():
domain = Domain.from_yaml(DOMAIN_YAML)
policy = TEDPolicy()
GREET_RULE = DialogueStateTracker.from_events(
"greet rule",
evts=[
UserUttered(intent={"name": GREET_INTENT_NAME}),
ActionExecuted(UTTER_GREET_ACTION),
ActionExecuted(ACTI... | def test_diagnostics():
| domain = Domain.from_yaml(DOMAIN_YAML)
policy = TEDPolicy()
GREET_RULE = DialogueStateTracker.from_events(
"greet rule",
evts=[
UserUttered(intent={"name": GREET_INTENT_NAME}),
ActionExecuted(UTTER_GREET_ACTION),
ActionExecuted(ACTION_LISTEN_NAME),
... | from rasa.shared.constants import DEFAULT_SENDER_ID
UTTER_GREET_ACTION = "utter_greet"
GREET_INTENT_NAME = "greet"
DOMAIN_YAML = f"""
intents:
- {GREET_INTENT_NAME}
actions:
- {UTTER_GREET_ACTION}
"""
def test_diagnostics():
| 64 | 64 | 173 | 5 | 59 | engahmed1190/rasa-for-botfront | tests/core/policies/test_ted_policy.py | Python | test_diagnostics | test_diagnostics | 52 | 72 | 52 | 52 | 112289cbba7830c86265cdc40e37651c7febf61a | bigcode/the-stack | train |
061c05238f20e35dc4881156 | train | class | class TestTEDPolicyWithEval(TestTEDPolicy):
def create_policy(
self, featurizer: Optional[TrackerFeaturizer], priority: int
) -> Policy:
return TEDPolicy(
featurizer=featurizer,
priority=priority,
**{SCALE_LOSS: False, EVAL_NUM_EXAMPLES: 4},
)
| class TestTEDPolicyWithEval(TestTEDPolicy):
| def create_policy(
self, featurizer: Optional[TrackerFeaturizer], priority: int
) -> Policy:
return TEDPolicy(
featurizer=featurizer,
priority=priority,
**{SCALE_LOSS: False, EVAL_NUM_EXAMPLES: 4},
)
| assert not prediction.is_end_to_end_prediction
assert len(prediction.probabilities) == default_domain.num_actions
assert max(prediction.probabilities) <= 1.0
assert min(prediction.probabilities) >= -1.0
class TestTEDPolicyWithEval(TestTEDPolicy):
| 64 | 64 | 78 | 10 | 53 | engahmed1190/rasa-for-botfront | tests/core/policies/test_ted_policy.py | Python | TestTEDPolicyWithEval | TestTEDPolicyWithEval | 306 | 314 | 306 | 306 | 67281fe0f4898c5a61dbb9094de94ff04456396c | bigcode/the-stack | train |
c33071dbde2763d00f749a12 | train | class | class TestTEDPolicyCosineConfidence(TestTEDPolicy):
def create_policy(
self, featurizer: Optional[TrackerFeaturizer], priority: int
) -> Policy:
return TEDPolicy(
featurizer=featurizer, priority=priority, **{MODEL_CONFIDENCE: COSINE}
)
def test_confidence_type(self, trai... | class TestTEDPolicyCosineConfidence(TestTEDPolicy):
| def create_policy(
self, featurizer: Optional[TrackerFeaturizer], priority: int
) -> Policy:
return TEDPolicy(
featurizer=featurizer, priority=priority, **{MODEL_CONFIDENCE: COSINE}
)
def test_confidence_type(self, trained_policy: TEDPolicy):
assert trained_polic... | predicted_probabilities = trained_policy.predict_action_probabilities(
tracker, default_domain, RegexInterpreter()
).probabilities
# there should be no normalization
assert all([confidence > 0 for confidence in predicted_probabilities])
# also check our function is not call... | 114 | 114 | 381 | 11 | 103 | engahmed1190/rasa-for-botfront | tests/core/policies/test_ted_policy.py | Python | TestTEDPolicyCosineConfidence | TestTEDPolicyCosineConfidence | 352 | 399 | 352 | 352 | 6b5345dfc0e2e1bf885a53a43d9d1ea007a58dd7 | bigcode/the-stack | train |
4b3347f37e61b6ed2392f7f5 | train | class | class TestTEDPolicyNoNormalization(TestTEDPolicy):
def create_policy(
self, featurizer: Optional[TrackerFeaturizer], priority: int
) -> Policy:
return TEDPolicy(
featurizer=featurizer, priority=priority, **{RANKING_LENGTH: 0}
)
def test_ranking_length(self, trained_polic... | class TestTEDPolicyNoNormalization(TestTEDPolicy):
| def create_policy(
self, featurizer: Optional[TrackerFeaturizer], priority: int
) -> Policy:
return TEDPolicy(
featurizer=featurizer, priority=priority, **{RANKING_LENGTH: 0}
)
def test_ranking_length(self, trained_policy: TEDPolicy):
assert trained_policy.config... | (
self, featurizer: Optional[TrackerFeaturizer], priority: int
) -> Policy:
return TEDPolicy(
featurizer=featurizer,
priority=priority,
**{SCALE_LOSS: False, EVAL_NUM_EXAMPLES: 4},
)
class TestTEDPolicyNoNormalization(TestTEDPolicy):
| 74 | 74 | 248 | 10 | 64 | engahmed1190/rasa-for-botfront | tests/core/policies/test_ted_policy.py | Python | TestTEDPolicyNoNormalization | TestTEDPolicyNoNormalization | 317 | 349 | 317 | 317 | e2597148471015019323d55492d30070fcb30b82 | bigcode/the-stack | train |
06934ea758e2c28b6d46eb24 | train | class | class TestTEDPolicy(PolicyTestCollection):
def test_train_model_checkpointing(self, tmp_path: Path):
model_name = "core-checkpointed-model"
best_model_file = tmp_path / (model_name + ".tar.gz")
assert not best_model_file.exists()
train_core(
domain="data/test_domains/def... | class TestTEDPolicy(PolicyTestCollection):
| def test_train_model_checkpointing(self, tmp_path: Path):
model_name = "core-checkpointed-model"
best_model_file = tmp_path / (model_name + ".tar.gz")
assert not best_model_file.exists()
train_core(
domain="data/test_domains/default.yml",
stories="data/test_s... | INNER,
)
from tests.core.test_policies import PolicyTestCollection
from rasa.shared.constants import DEFAULT_SENDER_ID
UTTER_GREET_ACTION = "utter_greet"
GREET_INTENT_NAME = "greet"
DOMAIN_YAML = f"""
intents:
- {GREET_INTENT_NAME}
actions:
- {UTTER_GREET_ACTION}
"""
def test_diagnostics():
domain = Domain.f... | 256 | 256 | 1,347 | 9 | 247 | engahmed1190/rasa-for-botfront | tests/core/policies/test_ted_policy.py | Python | TestTEDPolicy | TestTEDPolicy | 75 | 259 | 75 | 75 | 801812eedc12794523c0bd882b39ad5caad0f792 | bigcode/the-stack | train |
8dccdff5d05411eb7c07ffb4 | train | class | class TestTEDPolicyLowRankingLength(TestTEDPolicy):
def create_policy(
self, featurizer: Optional[TrackerFeaturizer], priority: int
) -> Policy:
return TEDPolicy(
featurizer=featurizer, priority=priority, **{RANKING_LENGTH: 3}
)
def test_ranking_length(self, trained_poli... | class TestTEDPolicyLowRankingLength(TestTEDPolicy):
| def create_policy(
self, featurizer: Optional[TrackerFeaturizer], priority: int
) -> Policy:
return TEDPolicy(
featurizer=featurizer, priority=priority, **{RANKING_LENGTH: 3}
)
def test_ranking_length(self, trained_policy: TEDPolicy):
assert trained_policy.config... | not prediction.is_end_to_end_prediction
assert len(prediction.probabilities) == default_domain.num_actions
assert max(prediction.probabilities) <= 1e9
assert min(prediction.probabilities) >= -1e9
class TestTEDPolicyLowRankingLength(TestTEDPolicy):
| 64 | 64 | 97 | 11 | 52 | engahmed1190/rasa-for-botfront | tests/core/policies/test_ted_policy.py | Python | TestTEDPolicyLowRankingLength | TestTEDPolicyLowRankingLength | 452 | 461 | 452 | 452 | 12e5e513f2bd09a176c18eae6948c017b7324122 | bigcode/the-stack | train |
7e76d3d8069a32c5c90fe47f | train | class | class TestTEDPolicyWithMaxHistory(TestTEDPolicy):
def create_policy(
self, featurizer: Optional[TrackerFeaturizer], priority: int
) -> Policy:
# use standard featurizer from TEDPolicy,
# since it is using MaxHistoryTrackerFeaturizer
# if max_history is specified
return TE... | class TestTEDPolicyWithMaxHistory(TestTEDPolicy):
| def create_policy(
self, featurizer: Optional[TrackerFeaturizer], priority: int
) -> Policy:
# use standard featurizer from TEDPolicy,
# since it is using MaxHistoryTrackerFeaturizer
# if max_history is specified
return TEDPolicy(priority=priority, max_history=self.max_hi... | trained_policy.persist(str(tmp_path))
loaded = trained_policy.__class__.load(str(tmp_path))
assert isinstance(loaded.featurizer, MaxHistoryTrackerFeaturizer)
assert isinstance(loaded.featurizer.state_featurizer, SingleStateFeaturizer)
class TestTEDPolicyWithMaxHistory(TestTEDPolicy):
| 67 | 67 | 226 | 11 | 56 | engahmed1190/rasa-for-botfront | tests/core/policies/test_ted_policy.py | Python | TestTEDPolicyWithMaxHistory | TestTEDPolicyWithMaxHistory | 496 | 515 | 496 | 496 | d0c95ef8e20c1f9a6b79ffb645807133ed1525ab | bigcode/the-stack | train |
60e6581419cacecaf35d5887 | train | class | class General(Piece):
def __init__(self, name, pos_id=0):
super().__init__(name)
if name == 'g':
self.pos_limit = BLACK_PALACE_BOUNDARY
elif name == 'G':
self.pos_limit = WHITE_PALACE_BOUNDARY
else:
raise ValueError('General only takes "g" or "G" f... | class General(Piece):
| def __init__(self, name, pos_id=0):
super().__init__(name)
if name == 'g':
self.pos_limit = BLACK_PALACE_BOUNDARY
elif name == 'G':
self.pos_limit = WHITE_PALACE_BOUNDARY
else:
raise ValueError('General only takes "g" or "G" for name.')
sel... | self.pos_limit and self.position in self.pos_limit and (self.position + 18 == next_pos or self.position - 18 == next_pos or self.position + 22 == next_pos or self.position - 22 == next_pos):
return True
else:
return False
class General(Piece):
| 64 | 64 | 186 | 5 | 58 | Ihsara/cotuong.py | verify.py | Python | General | General | 122 | 138 | 122 | 122 | 83fd1364e511b7d3153558dc46828dd2194a2c8e | bigcode/the-stack | train |
316f3fc6e47300b014a4a39f | train | class | class Pawn(Piece):
def __init__(self, name, pos_id=0):
super().__init__(name)
if name.islower():
self.fwd_only_pos_limit = [
i + 10 for i in self.position] + self.position
self.pos_limit = WHITE_TERRITORY_LOC_NUM + self.fwd_only_pos_limit
else:
... | class Pawn(Piece):
| def __init__(self, name, pos_id=0):
super().__init__(name)
if name.islower():
self.fwd_only_pos_limit = [
i + 10 for i in self.position] + self.position
self.pos_limit = WHITE_TERRITORY_LOC_NUM + self.fwd_only_pos_limit
else:
self.fwd_only_... | next_pos) and ((self.position + 8 == next_pos or self.position - 8 == next_pos) or (self.position + 12 == next_pos or self.position - 12 == next_pos) or (self.position + 19 == next_pos or self.position - 19 == next_pos) or (self.position + 21 == next_pos or self.position - 21 == next_pos)):
return True
... | 99 | 99 | 331 | 5 | 93 | Ihsara/cotuong.py | verify.py | Python | Pawn | Pawn | 155 | 177 | 155 | 155 | 5c9614772f06481370a84e9d1fc6cd85ba1d4e10 | bigcode/the-stack | train |
ca0b251edffc83655b4258d5 | train | class | class Horse(Piece):
def __init__(self, name, pos_id=0):
super().__init__(name)
self.position = self.position[pos_id]
self.id = name + str(pos_id)
self.blocking_rules = self.get_blocking_rules([1, 6])
def valid_move(self, next_pos=INVALID_POS):
if self.position != next_po... | class Horse(Piece):
| def __init__(self, name, pos_id=0):
super().__init__(name)
self.position = self.position[pos_id]
self.id = name + str(pos_id)
self.blocking_rules = self.get_blocking_rules([1, 6])
def valid_move(self, next_pos=INVALID_POS):
if self.position != next_pos and self.is_inboar... | self.pos_limit and self.position in self.pos_limit and (self.position + 1 == next_pos or self.position - 1 == next_pos or self.position + 10 == next_pos or self.position - 10 == next_pos):
return True
else:
return False
class Horse(Piece):
| 64 | 64 | 189 | 5 | 58 | Ihsara/cotuong.py | verify.py | Python | Horse | Horse | 141 | 152 | 141 | 141 | 0e2e64de7545411e8951adf7ebdcf3dc83822a47 | bigcode/the-stack | train |
c273780f6e2a77052256784b | train | class | class Advisor(Piece):
def __init__(self, name, pos_id=0):
super().__init__(name)
if name == 'a':
self.pos_limit = [14, 16, 25, 34, 36]
elif name == 'A':
self.pos_limit = [104, 106, 95, 84, 86]
else:
raise ValueError('Advisor only takes "a" or "A" f... | class Advisor(Piece):
| def __init__(self, name, pos_id=0):
super().__init__(name)
if name == 'a':
self.pos_limit = [14, 16, 25, 34, 36]
elif name == 'A':
self.pos_limit = [104, 106, 95, 84, 86]
else:
raise ValueError('Advisor only takes "a" or "A" for name.')
sel... | return next_pos if self.valid_move(next_pos) else self.position
def current_state(self):
return {self.id: self.position}
def __repr__(self):
return '{}.id {}: {}'.format(OFFICIAL_NAMES[self.name.lower()],self.id, self.position)
class Advisor(Piece):
| 64 | 64 | 202 | 5 | 59 | Ihsara/cotuong.py | verify.py | Python | Advisor | Advisor | 69 | 85 | 69 | 69 | 8902f402c65bb837a6992da0cc22c83c9c5025f5 | bigcode/the-stack | train |
41d4a4d15b87aaf3b90fe0bb | train | class | class Rock(Piece):
def __init__(self, name, pos_id=0):
super().__init__(name)
self.position = self.position[pos_id]
self.id = name + str(pos_id)
self.blocking_rules = self.get_blocking_rules([1, 2, 3])
def valid_move(self, next_pos=INVALID_POS):
if self.position != next_... | class Rock(Piece):
| def __init__(self, name, pos_id=0):
super().__init__(name)
self.position = self.position[pos_id]
self.id = name + str(pos_id)
self.blocking_rules = self.get_blocking_rules([1, 2, 3])
def valid_move(self, next_pos=INVALID_POS):
if self.position != next_pos and self.is_inb... | self.position or next_pos - 1 == self.position or next_pos + 1 == self.position)) or (self.position in self.fwd_only_pos_limit and next_pos + 10 == self.position)):
return True
else:
return False
else: return False
class Rock(Piece):
| 64 | 64 | 166 | 5 | 58 | Ihsara/cotuong.py | verify.py | Python | Rock | Rock | 180 | 191 | 180 | 180 | 7f5ce8601ca20571bc9ba9fc201ce50123ba85bf | bigcode/the-stack | train |
f07aef7146022ea868dd1dc2 | train | class | class Piece(object):
def __init__(self, name):
self.name = name
self.position = start_coords_2[name]
self.INVALID_POS = INVALID_POS
self.id = self.name + '-1'
self.blocking_rules = self.get_blocking_rules([1])
def is_inboard(self, next_pos=INVALID_POS):
if next_p... | class Piece(object):
| def __init__(self, name):
self.name = name
self.position = start_coords_2[name]
self.INVALID_POS = INVALID_POS
self.id = self.name + '-1'
self.blocking_rules = self.get_blocking_rules([1])
def is_inboard(self, next_pos=INVALID_POS):
if next_pos != INVALID_POS and... | from cotuong_const import start_coords_2, INVALID_POS, OFFICIAL_NAMES
from cotuong_const import BLACK_PALACE_BOUNDARY, WHITE_PALACE_BOUNDARY
from cotuong_const import MOVE_VERTICALLY_ONE_UNIT_FWD, BOARD_LOC_NUM
from cotuong_const import BLACK_TERRITORY_LOC_NUM, WHITE_TERRITORY_LOC_NUM
from cotuong_const import BLOCKING... | 108 | 123 | 413 | 4 | 104 | Ihsara/cotuong.py | verify.py | Python | Piece | Piece | 12 | 66 | 12 | 12 | 25584b1d4a8504a4a7d5cf501c9b11ba4803e4a1 | bigcode/the-stack | train |
fe57644b4e585455185edb38 | train | class | class Cannon(Piece):
def __init__(self, name, pos_id=0):
super().__init__(name)
self.position = self.position[pos_id]
self.id = name + str(pos_id)
self.blocking_rules = self.get_blocking_rules([1, 2, 3])
def valid_move(self, next_pos=INVALID_POS):
if self.position != nex... | class Cannon(Piece):
| def __init__(self, name, pos_id=0):
super().__init__(name)
self.position = self.position[pos_id]
self.id = name + str(pos_id)
self.blocking_rules = self.get_blocking_rules([1, 2, 3])
def valid_move(self, next_pos=INVALID_POS):
if self.position != next_pos and self.is_inb... | self.pos_limit and self.position in self.pos_limit and (self.position + 9 == next_pos or self.position - 9 == next_pos or self.position - 11 == next_pos or self.position + 11 == next_pos):
return True
else:
return False
class Cannon(Piece):
| 64 | 64 | 166 | 5 | 58 | Ihsara/cotuong.py | verify.py | Python | Cannon | Cannon | 88 | 99 | 88 | 88 | 2656e6884d60c20c344118a8a7bb2d6dde58b5f2 | bigcode/the-stack | train |
842971ead9b0d4d20b0dcfd0 | train | class | class Elephant(Piece):
def __init__(self, name, pos_id=0):
super().__init__(name)
self.position = self.position[pos_id]
self.id = name + str(pos_id)
if name == 'e':
self.pos_limit = [13, 17, 31, 35, 39, 53, 57]
elif name == 'E':
self.pos_limit = [63, 6... | class Elephant(Piece):
| def __init__(self, name, pos_id=0):
super().__init__(name)
self.position = self.position[pos_id]
self.id = name + str(pos_id)
if name == 'e':
self.pos_limit = [13, 17, 31, 35, 39, 53, 57]
elif name == 'E':
self.pos_limit = [63, 67, 81, 85, 89, 103, 107... | (next_pos - self.position) <= 8 and (next_pos//10 - self.position//10) == 0) or (abs(next_pos - self.position) >= 10 and abs(next_pos - self.position) % 10 == 0)):
return True
else:
return False
class Elephant(Piece):
| 68 | 69 | 231 | 5 | 62 | Ihsara/cotuong.py | verify.py | Python | Elephant | Elephant | 102 | 119 | 102 | 102 | ebc989f3510eae4ab97f48f7f052f4ee0a0c9a8d | bigcode/the-stack | train |
7f736426a0169fec8907570d | train | class | class ExternalProcessEnv(object):
"""Step environment in a separate process for lock free parallelism."""
# Message types for communication via the pipe.
_ACCESS = 1
_CALL = 2
_RESULT = 3
_EXCEPTION = 4
_CLOSE = 5
def __init__(self, constructor, xvfb):
"""Step environment in a separate process for... | class ExternalProcessEnv(object):
| """Step environment in a separate process for lock free parallelism."""
# Message types for communication via the pipe.
_ACCESS = 1
_CALL = 2
_RESULT = 3
_EXCEPTION = 4
_CLOSE = 5
def __init__(self, constructor, xvfb):
"""Step environment in a separate process for lock free parallelism.
The e... | behaves as gym.wrappers.Monitor,
- on the "inactive" runs it doesn't call underlying environment and only
returns last seen observation.
Videos are only generated during the active runs.
"""
def __init__(self, env):
super(EvalVideoWrapper, self).__init__(env)
self._reset_counter = 0
self._acti... | 256 | 256 | 1,368 | 6 | 250 | akshitj1/tensor2tensor | tensor2tensor/rl/envs/utils.py | Python | ExternalProcessEnv | ExternalProcessEnv | 85 | 279 | 85 | 85 | 0c0523ba02e0a75df4e1b7be25a6355e9ed26b04 | bigcode/the-stack | train |
9f7bca5d1e0a876c8ccd7397 | train | function | def define_batch_env(constructor, num_agents, xvfb=False):
"""Create environments and apply all desired wrappers."""
with tf.variable_scope("environments"):
envs = [
ExternalProcessEnv(constructor, xvfb)
for _ in range(num_agents)]
env = batch_env.BatchEnv(envs, blocking=False)
env = py_... | def define_batch_env(constructor, num_agents, xvfb=False):
| """Create environments and apply all desired wrappers."""
with tf.variable_scope("environments"):
envs = [
ExternalProcessEnv(constructor, xvfb)
for _ in range(num_agents)]
env = batch_env.BatchEnv(envs, blocking=False)
env = py_func_batch_env.PyFuncBatchEnv(env)
return env
| cur_batch_env = define_batch_env(environment_lambda, num_agents, xvfb=xvfb)
for w in wrappers:
cur_batch_env = w[0](cur_batch_env, **w[1])
return cur_batch_env
def define_batch_env(constructor, num_agents, xvfb=False):
| 64 | 64 | 87 | 14 | 49 | akshitj1/tensor2tensor | tensor2tensor/rl/envs/utils.py | Python | define_batch_env | define_batch_env | 299 | 307 | 299 | 299 | 00c6a7135ab52fcf918ce4a8ea93c9b3d250911b | bigcode/the-stack | train |
42bf82dda880ca1c9588deda | train | function | def define_simulated_batch_env(environment_lambda, num_agents, problem,
simulation_random_starts=False,
intrinsic_reward_scale=0.):
cur_batch_env = simulated_batch_env.SimulatedBatchEnv(
environment_lambda, num_agents, problem, simulation_random_star... | def define_simulated_batch_env(environment_lambda, num_agents, problem,
simulation_random_starts=False,
intrinsic_reward_scale=0.):
| cur_batch_env = simulated_batch_env.SimulatedBatchEnv(
environment_lambda, num_agents, problem, simulation_random_starts,
intrinsic_reward_scale)
return cur_batch_env
| range(num_agents)]
env = batch_env.BatchEnv(envs, blocking=False)
env = py_func_batch_env.PyFuncBatchEnv(env)
return env
def define_simulated_batch_env(environment_lambda, num_agents, problem,
simulation_random_starts=False,
intrinsic_reward_sca... | 64 | 64 | 68 | 29 | 34 | akshitj1/tensor2tensor | tensor2tensor/rl/envs/utils.py | Python | define_simulated_batch_env | define_simulated_batch_env | 310 | 316 | 310 | 312 | 370364d39c84ce6b0dcd70c9f851604447782136 | bigcode/the-stack | train |
a541d3ecfb38759a49adba55 | train | class | class EvalVideoWrapper(gym.Wrapper):
"""Wrapper for recording videos during eval phase.
This wrapper is designed to record videos via gym.wrappers.Monitor and
simplifying its usage in t2t collect phase.
It alleviate the limitation of Monitor, which doesn't allow reset on an
active environment.
EvalVideoWr... | class EvalVideoWrapper(gym.Wrapper):
| """Wrapper for recording videos during eval phase.
This wrapper is designed to record videos via gym.wrappers.Monitor and
simplifying its usage in t2t collect phase.
It alleviate the limitation of Monitor, which doesn't allow reset on an
active environment.
EvalVideoWrapper assumes that only every second ... | utility.py
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import atexit
import multiprocessing
import os
import random
import signal
import subprocess
import sys
import traceback
import gym
from tensor2tensor.rl.envs import batch_env
from tensor2tensor.rl... | 105 | 105 | 350 | 9 | 95 | akshitj1/tensor2tensor | tensor2tensor/rl/envs/utils.py | Python | EvalVideoWrapper | EvalVideoWrapper | 42 | 82 | 42 | 42 | 458e8dc0a279384d0e2b3208772fabf2cffb9415 | bigcode/the-stack | train |
3cc39cbd90e98750098c2aeb | train | function | def batch_env_factory(environment_lambda, hparams, num_agents, xvfb=False):
"""Factory of batch envs."""
wrappers = hparams.in_graph_wrappers if hasattr(
hparams, "in_graph_wrappers") else []
if hparams.simulated_environment:
cur_batch_env = define_simulated_batch_env(
environment_lambda, num_a... | def batch_env_factory(environment_lambda, hparams, num_agents, xvfb=False):
| """Factory of batch envs."""
wrappers = hparams.in_graph_wrappers if hasattr(
hparams, "in_graph_wrappers") else []
if hparams.simulated_environment:
cur_batch_env = define_simulated_batch_env(
environment_lambda, num_agents, hparams.problem,
hparams.simulation_random_starts,
hp... | (*sys.exc_info())) # pylint: disable=no-value-for-parameter
tf.logging.error("Error in environment process: {}".format(stacktrace))
conn.send((self._EXCEPTION, stacktrace))
conn.close()
def batch_env_factory(environment_lambda, hparams, num_agents, xvfb=False):
| 64 | 64 | 150 | 17 | 47 | akshitj1/tensor2tensor | tensor2tensor/rl/envs/utils.py | Python | batch_env_factory | batch_env_factory | 282 | 296 | 282 | 282 | 289cfd33319de1f1374e00e365a83e3d362975b8 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.