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
36494b979e8d1858eba76502
train
function
def main(): container = [] funcs = [get_1, get_1111, get_112, get_211, get_13, get_31, get_22] for index in range(3, 5): for name in ['C', 'D', 'E', 'F', 'G', 'A', 'B']: key = '{}_{}'.format(name, index) container.append(getattr(midi, key)) for i in range(1000): f...
def main():
container = [] funcs = [get_1, get_1111, get_112, get_211, get_13, get_31, get_22] for index in range(3, 5): for name in ['C', 'D', 'E', 'F', 'G', 'A', 'B']: key = '{}_{}'.format(name, index) container.append(getattr(midi, key)) for i in range(1000): func = random...
.NoteOffEvent(tick=100, pitch=pitch2) track.extend([on, off]) on = midi.NoteOnEvent(tick=0, velocity=83, pitch=patch3) off = midi.NoteOffEvent(tick=100, pitch=patch3) track.extend([on, off]) def main():
70
70
235
3
67
shiyeli/jupyter_notebook
library_learn/midi_gen.py
Python
main
main
84
101
84
84
7ae5735f0db95a04431844b3c783a73a5e9503f7
bigcode/the-stack
train
c5545aafa5761ac6cdb77e09
train
function
def get_1(pitch): on = midi.NoteOnEvent(tick=0, velocity=100, pitch=pitch) off = midi.NoteOffEvent(tick=400, pitch=pitch) track.extend([on, off])
def get_1(pitch):
on = midi.NoteOnEvent(tick=0, velocity=100, pitch=pitch) off = midi.NoteOffEvent(tick=400, pitch=pitch) track.extend([on, off])
# -*- coding: utf-8 -*- # midi_gen.py in jupyter_notebook # Created by yetongxue at 2020-12-17 import midi import random patten = midi.Pattern() track = midi.Track() patten.append(track) def get_1(pitch):
64
64
51
7
57
shiyeli/jupyter_notebook
library_learn/midi_gen.py
Python
get_1
get_1
14
17
14
14
492f257793a196f5150134044f41beb558435eb0
bigcode/the-stack
train
bd56351fc7f8948da8b0a22c
train
function
def get_1111(pitch, pitch1, pitch2, patch3): on = midi.NoteOnEvent(tick=0, velocity=90, pitch=pitch) off = midi.NoteOffEvent(tick=100, pitch=pitch) track.extend([on, off]) on = midi.NoteOnEvent(tick=0, velocity=85, pitch=pitch1) off = midi.NoteOffEvent(tick=100, pitch=pitch1) track.extend([on, o...
def get_1111(pitch, pitch1, pitch2, patch3):
on = midi.NoteOnEvent(tick=0, velocity=90, pitch=pitch) off = midi.NoteOffEvent(tick=100, pitch=pitch) track.extend([on, off]) on = midi.NoteOnEvent(tick=0, velocity=85, pitch=pitch1) off = midi.NoteOffEvent(tick=100, pitch=pitch1) track.extend([on, off]) on = midi.NoteOnEvent(tick=0, veloci...
off]) on = midi.NoteOnEvent(tick=0, velocity=90, pitch=pitch1) off = midi.NoteOffEvent(tick=300, pitch=pitch) track.extend([on, off]) def get_1111(pitch, pitch1, pitch2, patch3):
64
64
199
17
47
shiyeli/jupyter_notebook
library_learn/midi_gen.py
Python
get_1111
get_1111
69
81
69
69
32e690a85d7050916ec686e605190cc0c8d60175
bigcode/the-stack
train
d747bcfec3fc1543dd458c4c
train
function
def get_211(pitch, pitch1, pitch2): on = midi.NoteOnEvent(tick=0, velocity=90, pitch=pitch) off = midi.NoteOffEvent(tick=200, pitch=pitch) track.extend([on, off]) on = midi.NoteOnEvent(tick=0, velocity=85, pitch=pitch1) off = midi.NoteOffEvent(tick=100, pitch=pitch1) track.extend([on, off]) ...
def get_211(pitch, pitch1, pitch2):
on = midi.NoteOnEvent(tick=0, velocity=90, pitch=pitch) off = midi.NoteOffEvent(tick=200, pitch=pitch) track.extend([on, off]) on = midi.NoteOnEvent(tick=0, velocity=85, pitch=pitch1) off = midi.NoteOffEvent(tick=100, pitch=pitch1) track.extend([on, off]) on = midi.NoteOnEvent(tick=0, veloci...
([on, off]) on = midi.NoteOnEvent(tick=0, velocity=80, pitch=pitch1) off = midi.NoteOffEvent(tick=200, pitch=pitch1) track.extend([on, off]) def get_211(pitch, pitch1, pitch2):
64
64
149
13
51
shiyeli/jupyter_notebook
library_learn/midi_gen.py
Python
get_211
get_211
29
38
29
29
a8ba9d390de190aab7e28f72db0d32d15383e542
bigcode/the-stack
train
add9536362a925e4790fc5ff
train
function
def get_112(pitch, pitch1, pitch2): on = midi.NoteOnEvent(tick=0, velocity=90, pitch=pitch) off = midi.NoteOffEvent(tick=100, pitch=pitch) track.extend([on, off]) on = midi.NoteOnEvent(tick=0, velocity=85, pitch=pitch1) off = midi.NoteOffEvent(tick=100, pitch=pitch1) track.extend([on, off]) ...
def get_112(pitch, pitch1, pitch2):
on = midi.NoteOnEvent(tick=0, velocity=90, pitch=pitch) off = midi.NoteOffEvent(tick=100, pitch=pitch) track.extend([on, off]) on = midi.NoteOnEvent(tick=0, velocity=85, pitch=pitch1) off = midi.NoteOffEvent(tick=100, pitch=pitch1) track.extend([on, off]) on = midi.NoteOnEvent(tick=0, veloci...
([on, off]) on = midi.NoteOnEvent(tick=0, velocity=80, pitch=pitch2) off = midi.NoteOffEvent(tick=100, pitch=pitch2) track.extend([on, off]) def get_112(pitch, pitch1, pitch2):
64
64
149
13
51
shiyeli/jupyter_notebook
library_learn/midi_gen.py
Python
get_112
get_112
41
50
41
41
e30674cc57aed14c68bf4615cc9b923d253ba17b
bigcode/the-stack
train
efcda9570aa8243859729356
train
function
def launch_executable(executable, args, cwd, env=None): """ Launches an executable with optional arguments :param executable: A unicode string of an executable :param args: A list of unicode strings to pass as arguments to the executable :param cwd: A unicode string of the...
def launch_executable(executable, args, cwd, env=None):
""" Launches an executable with optional arguments :param executable: A unicode string of an executable :param args: A list of unicode strings to pass as arguments to the executable :param cwd: A unicode string of the working directory to open the executable to :param...
# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import sys import os import subprocess from ._types import verify_unicode, verify_unicode_list, verify_unicode_dict def launch_executable(executable, args, cwd, env=None):
62
110
367
14
47
angelofdeauth/dotfiles
sublime-text-3/.config/sublime-text-3/Packages/newterm/all/newterm/_posix.py
Python
launch_executable
launch_executable
11
65
11
11
5d04c4c906152c9395c251ae3cf88008f9c2c034
bigcode/the-stack
train
8a607876277e63ab5044fa06
train
class
class Team(models.Model): created = models.DateTimeField(auto_now_add=True) changed = models.DateTimeField(auto_now=True) token = models.CharField(max_length=255) name = models.CharField(max_length=255) slack_id = models.CharField(max_length=255, unique=True) domain = models.CharField(max_lengt...
class Team(models.Model):
created = models.DateTimeField(auto_now_add=True) changed = models.DateTimeField(auto_now=True) token = models.CharField(max_length=255) name = models.CharField(max_length=255) slack_id = models.CharField(max_length=255, unique=True) domain = models.CharField(max_length=255) def __str__(sel...
from django.db import models class Team(models.Model):
11
64
96
5
5
phildini/tintg
slack/models.py
Python
Team
Team
4
14
4
5
ae483b7601a292c62bca2312768394cce7330c4d
bigcode/the-stack
train
f6071308441e30a5983aaa97
train
function
def elapsed(start_time, end_time): delta = end_time - start_time return delta.days * SECONDS_IN_A_DAY + delta.seconds + delta.microseconds / 1E6
def elapsed(start_time, end_time):
delta = end_time - start_time return delta.days * SECONDS_IN_A_DAY + delta.seconds + delta.microseconds / 1E6
from sys import stdout from datetime import datetime from time import sleep import pandas as pd from math import floor _map = map SECONDS_IN_A_DAY = 60.0 * 60.0 * 24.0 def elapsed(start_time, end_time):
57
64
39
8
48
idin/chronometry
chronometry/progress/ProgressBar.py
Python
elapsed
elapsed
11
13
11
11
618f48372ad350d1b687391ac257c2bba3df637f
bigcode/the-stack
train
69e1d5d406add3f9e0aee182
train
class
class ProgressBar: def __init__( self, total, bar_length=20, animation='clock', full_colour='blue', empty_colour='grey', text_colour='grey', next_line=True, echo=1, parent=None, disappear=False, display_wait=0.5, bar_characters=None ): """ :type total: int or float or NoneType :type bar_length: int ...
class ProgressBar:
def __init__( self, total, bar_length=20, animation='clock', full_colour='blue', empty_colour='grey', text_colour='grey', next_line=True, echo=1, parent=None, disappear=False, display_wait=0.5, bar_characters=None ): """ :type total: int or float or NoneType :type bar_length: int :type bar_full: s...
from sys import stdout from datetime import datetime from time import sleep import pandas as pd from math import floor _map = map SECONDS_IN_A_DAY = 60.0 * 60.0 * 24.0 def elapsed(start_time, end_time): delta = end_time - start_time return delta.days * SECONDS_IN_A_DAY + delta.seconds + delta.microseconds / 1E6 ...
115
256
3,939
4
110
idin/chronometry
chronometry/progress/ProgressBar.py
Python
ProgressBar
ProgressBar
22
525
22
22
66e385b51d139558d283efeae2b0fb7732c3223f
bigcode/the-stack
train
35a0b69e6d0c11ce81c7d29f
train
function
def _GetLargeMatrixSolveLsOpTests(dtype, use_placeholder, fast, l2_regularizer): def LargeBatchSquare(self): np.random.seed(1) num_rhs = 1 matrix_shape = (127, 127) matrix = np.random.uniform( low=-1.0, high=1.0, size=np.prod(matrix_shape)).reshape(matrix_shape).astype(np.float32) ...
def _GetLargeMatrixSolveLsOpTests(dtype, use_placeholder, fast, l2_regularizer):
def LargeBatchSquare(self): np.random.seed(1) num_rhs = 1 matrix_shape = (127, 127) matrix = np.random.uniform( low=-1.0, high=1.0, size=np.prod(matrix_shape)).reshape(matrix_shape).astype(np.float32) rhs = np.ones([matrix_shape[0], num_rhs]).astype(np.float32) self._verifySolv...
1., 2., 3], [4., 5., 6.]]) rhs = np.array([[1., 0., 1.], [0., 1., 1.]]) for batch_shape in (), (2, 3): self._verifySolve( matrix, rhs, dtype, use_placeholder, fast, l2_regularizer, batch_shape=batch_shape) return (Square, Overdetermi...
123
123
413
21
102
tianyapiaozi/tensorflow
tensorflow/python/kernel_tests/matrix_solve_ls_op_test.py
Python
_GetLargeMatrixSolveLsOpTests
_GetLargeMatrixSolveLsOpTests
215
268
215
216
eca31ce54149d09500ca0621b3a09923305198a8
bigcode/the-stack
train
7e115e25e5ec20b686865cf1
train
function
def _AddTest(test, op_name, testcase_name, fn): test_name = "_".join(["test", op_name, testcase_name]) if hasattr(test, test_name): raise RuntimeError("Test %s defined more than once" % test_name) setattr(test, test_name, fn)
def _AddTest(test, op_name, testcase_name, fn):
test_name = "_".join(["test", op_name, testcase_name]) if hasattr(test, test_name): raise RuntimeError("Test %s defined more than once" % test_name) setattr(test, test_name, fn)
tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import linalg_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import variables from tensorflow.python.platform import test as test_lib def _AddTest(test, op_name, testcase_name...
64
64
64
14
49
tianyapiaozi/tensorflow
tensorflow/python/kernel_tests/matrix_solve_ls_op_test.py
Python
_AddTest
_AddTest
35
39
35
35
5e1f285015554cee77e128d2742c828723635c39
bigcode/the-stack
train
25b2173326c99c4288f85e59
train
function
def _SolveWithNumpy(matrix, rhs, l2_regularizer=0): if l2_regularizer == 0: np_ans, _, _, _ = np.linalg.lstsq(matrix, rhs) return np_ans else: rows = matrix.shape[-2] cols = matrix.shape[-1] if rows >= cols: preconditioner = l2_regularizer * np.identity(cols) gramian = np.dot(np.conj...
def _SolveWithNumpy(matrix, rhs, l2_regularizer=0):
if l2_regularizer == 0: np_ans, _, _, _ = np.linalg.lstsq(matrix, rhs) return np_ans else: rows = matrix.shape[-2] cols = matrix.shape[-1] if rows >= cols: preconditioner = l2_regularizer * np.identity(cols) gramian = np.dot(np.conj(matrix.T), matrix) + preconditioner rhs = np....
( np.tile(matrix, batch_shape + (1, 1)), trainable=False) rhs = variables.Variable(np.tile(rhs, batch_shape + (1, 1)), trainable=False) return matrix, rhs def _SolveWithNumpy(matrix, rhs, l2_regularizer=0):
64
64
191
17
46
tianyapiaozi/tensorflow
tensorflow/python/kernel_tests/matrix_solve_ls_op_test.py
Python
_SolveWithNumpy
_SolveWithNumpy
57
73
57
57
4714e5516d863657ad8d3fb6560132f56e1dc69c
bigcode/the-stack
train
2446aca4ad2b34002dadda33
train
function
def _GenerateTestData(matrix_shape, num_rhs): batch_shape = matrix_shape[:-2] matrix_shape = matrix_shape[-2:] m = matrix_shape[-2] np.random.seed(1) matrix = np.random.uniform( low=-1.0, high=1.0, size=np.prod(matrix_shape)).reshape(matrix_shape).astype(np.float32) rhs = np.ones([m, num_rhs]).a...
def _GenerateTestData(matrix_shape, num_rhs):
batch_shape = matrix_shape[:-2] matrix_shape = matrix_shape[-2:] m = matrix_shape[-2] np.random.seed(1) matrix = np.random.uniform( low=-1.0, high=1.0, size=np.prod(matrix_shape)).reshape(matrix_shape).astype(np.float32) rhs = np.ones([m, num_rhs]).astype(np.float32) matrix = variables.Variabl...
, fn): test_name = "_".join(["test", op_name, testcase_name]) if hasattr(test, test_name): raise RuntimeError("Test %s defined more than once" % test_name) setattr(test, test_name, fn) def _GenerateTestData(matrix_shape, num_rhs):
64
64
148
11
53
tianyapiaozi/tensorflow
tensorflow/python/kernel_tests/matrix_solve_ls_op_test.py
Python
_GenerateTestData
_GenerateTestData
42
54
42
42
5b46ee73958ba0dbc2fb491316b9bbf30590d34e
bigcode/the-stack
train
c0b6a287c070d09831b29ec4
train
function
def _GetSmallMatrixSolveLsOpTests(dtype, use_placeholder, fast, l2_regularizer): def Square(self): # 2x2 matrices, 2x3 right-hand sides. matrix = np.array([[1., 2.], [3., 4.]]) rhs = np.array([[1., 0., 1.], [0., 1., 1.]]) for batch_shape in (), (2, 3): self._verifySolve( matrix, ...
def _GetSmallMatrixSolveLsOpTests(dtype, use_placeholder, fast, l2_regularizer):
def Square(self): # 2x2 matrices, 2x3 right-hand sides. matrix = np.array([[1., 2.], [3., 4.]]) rhs = np.array([[1., 0., 1.], [0., 1., 1.]]) for batch_shape in (), (2, 3): self._verifySolve( matrix, rhs, dtype, use_placeholder, fast, l2...
3, 3) rhs = np.array([1., 2., 3.] * 3).reshape(3, 3, 1) answer = linalg_ops.matrix_solve(matrix, rhs) ls_answer = linalg_ops.matrix_solve_ls(matrix, rhs) self.assertEqual(ls_answer.get_shape(), [3, 3, 1]) self.assertEqual(answer.get_shape(), [3, 3, 1]) def _GetSmallMatrixSolveLsOpTests(dtype, use_pl...
117
117
393
21
96
tianyapiaozi/tensorflow
tensorflow/python/kernel_tests/matrix_solve_ls_op_test.py
Python
_GetSmallMatrixSolveLsOpTests
_GetSmallMatrixSolveLsOpTests
168
212
168
169
2ca15e35f8406e3fc901500dd620743074abc6f9
bigcode/the-stack
train
d36d20f9b17f1f6aa7da4bd3
train
class
class MatrixSolveLsOpTest(test_lib.TestCase): def _verifySolve(self, x, y, dtype, use_placeholder, fast, l2_regularizer, batch_shape=()): if not fast and l2_regularizer != 0: ...
class MatrixSolveLsOpTest(test_lib.TestCase):
def _verifySolve(self, x, y, dtype, use_placeholder, fast, l2_regularizer, batch_shape=()): if not fast and l2_regularizer != 0: # The slow path does not support regularizatio...
32) matrix = variables.Variable( np.tile(matrix, batch_shape + (1, 1)), trainable=False) rhs = variables.Variable(np.tile(rhs, batch_shape + (1, 1)), trainable=False) return matrix, rhs def _SolveWithNumpy(matrix, rhs, l2_regularizer=0): if l2_regularizer == 0: np_ans, _, _, _ = np.linalg.lstsq(matr...
256
256
1,136
11
245
tianyapiaozi/tensorflow
tensorflow/python/kernel_tests/matrix_solve_ls_op_test.py
Python
MatrixSolveLsOpTest
MatrixSolveLsOpTest
76
165
76
77
6bf1e12b03b7667585938a739406e8469e2817d9
bigcode/the-stack
train
ba81a7588ff858e56eddbea2
train
class
class MatrixSolveLsBenchmark(test_lib.Benchmark): matrix_shapes = [ (4, 4), (8, 4), (4, 8), (10, 10), (10, 8), (8, 10), (16, 16), (16, 10), (10, 16), (101, 101), (101, 31), (31, 101), (256, 256), (256, 200), (200, 256), (...
class MatrixSolveLsBenchmark(test_lib.Benchmark):
matrix_shapes = [ (4, 4), (8, 4), (4, 8), (10, 10), (10, 8), (8, 10), (16, 16), (16, 10), (10, 16), (101, 101), (101, 31), (31, 101), (256, 256), (256, 200), (200, 256), (1001, 1001), (1001, 501), (501, 1001), ...
Solve( matrix, rhs, dtype, use_placeholder, fast, l2_regularizer, batch_shape=(16, 8)) def LargeBatchUnderdetermined(self): np.random.seed(1) num_rhs = 1 matrix_shape = (64, 127) matrix = np.random.uniform( low=-1.0, high=1.0, si...
187
187
624
10
177
tianyapiaozi/tensorflow
tensorflow/python/kernel_tests/matrix_solve_ls_op_test.py
Python
MatrixSolveLsBenchmark
MatrixSolveLsBenchmark
271
343
271
272
c5061e2037c555eff6c272bcbd229c952b859bd8
bigcode/the-stack
train
9bbebeddaf90adb81727fe4c
train
function
def test_intro_tutorial_repository(): repo = define_repository() assert repo assert repo.get_all_pipelines()
def test_intro_tutorial_repository():
repo = define_repository() assert repo assert repo.get_all_pipelines()
from dagster_examples.intro_tutorial.tutorial_repository import define_repository def test_intro_tutorial_repository():
22
64
25
7
14
bambielli-flex/dagster
python_modules/dagster/dagster_tests/tutorial_tests/intro_tutorial/test_tutorial_repository.py
Python
test_intro_tutorial_repository
test_intro_tutorial_repository
4
7
4
4
1deb8ba7dedc29526190c33702bda13d8a81bf1b
bigcode/the-stack
train
df7d336a2b3ddb1b7ec811ad
train
class
class NetworkInterfaceIPConfigurationsOperations: """NetworkInterfaceIPConfigurationsOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model clas...
class NetworkInterfaceIPConfigurationsOperations:
"""NetworkInterfaceIPConfigurationsOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
212
256
1,587
7
205
rsdoherty/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_05_01/aio/operations/_network_interface_ip_configurations_operations.py
Python
NetworkInterfaceIPConfigurationsOperations
NetworkInterfaceIPConfigurationsOperations
22
178
22
22
0b02f198bfb511c6597230ce35acc53f08653cea
bigcode/the-stack
train
d7dafad399f98e772d233c33
train
class
class logger(): def __init__(self): self._st = "[ STARTED ] " self._ed = "[ COMPLETED ] " self._if = "[ INFO ] " self._wr = "[ WARNING ] " self._er = "[ ERROR ] " self._cr = "[ CRITICAL ] "
class logger():
def __init__(self): self._st = "[ STARTED ] " self._ed = "[ COMPLETED ] " self._if = "[ INFO ] " self._wr = "[ WARNING ] " self._er = "[ ERROR ] " self._cr = "[ CRITICAL ] "
class logger():
3
64
79
3
0
vikilabs/Image_Recognition_CNN_CIFAR10
packages/VikiLabs_Logger.py
Python
logger
logger
1
8
1
1
aca81159051d5a28e84d674cf0aa1940c5115701
bigcode/the-stack
train
d52f688f4741a65bad6e5ef6
train
class
class CouchDbPersister(Persister): """ A basic couchDB persister. Note that the couchDB persister is designed not to overwrite the value of a key if the key already exists. You can subclass it and use update_one instead of insert_one if you want to be able to overwrite data. >>> s = CouchDbPersiste...
class CouchDbPersister(Persister):
""" A basic couchDB persister. Note that the couchDB persister is designed not to overwrite the value of a key if the key already exists. You can subclass it and use update_one instead of insert_one if you want to be able to overwrite data. >>> s = CouchDbPersister() >>> for _id in s: # deleti...
from py2store.base import Persister from py2store.util import ModuleNotFoundErrorNiceMessage with ModuleNotFoundErrorNiceMessage(): from couchdb import Server class CouchDbPersister(Persister):
46
256
1,467
9
36
Perfect111/py2store
py2store/persisters/couchdb_w_couchdb.py
Python
CouchDbPersister
CouchDbPersister
8
166
8
8
7e8da36409fd9a187dbecaf813b503318c56b0fb
bigcode/the-stack
train
dd02fcb8e8c0bf6cf52bc80c
train
function
def int_diff(arr, n): ans = [] arr = sorted(arr) for i in range(len(arr)): for j in range(i+1, len(arr)): if arr[j] - arr[i] == n: ans.append((arr[i], arr[j])) return len(ans)
def int_diff(arr, n):
ans = [] arr = sorted(arr) for i in range(len(arr)): for j in range(i+1, len(arr)): if arr[j] - arr[i] == n: ans.append((arr[i], arr[j])) return len(ans)
import sys def int_diff(arr, n):
10
64
64
7
2
hwakabh/codewars
Python/7/IntegerDiffernce/integer_difference.py
Python
int_diff
int_diff
4
11
4
4
2a3ab7d03213342830d4d3dbf5f3dc57d7db386e
bigcode/the-stack
train
2861e1f1fd5c5dc6910ea27f
train
function
def getNextSendPort(): global SEND_PORT SEND_PORT += 10 return SEND_PORT
def getNextSendPort():
global SEND_PORT SEND_PORT += 10 return SEND_PORT
RECEIVE_PORT = DEFAULT_RECEIVE_PORT SEND_PORT = DEFAULT_SEND_PORT LOG_PORT = DEFAULT_LOG_PORT GOSSIP_WAIT_SECONDS = DEFAULT_GOSSIP_WAIT_SECONDS QUEUE_CREDENTIALS = {"LOGIN": QUEUE_USERNAME, "PASSWORD": QUEUE_PASSWORD} def getNextSendPort():
64
64
20
6
58
chetmancini/Timber
config.py
Python
getNextSendPort
getNextSendPort
110
113
110
110
d8b7af7ae80595f1e6f8332ee043a116a575c01e
bigcode/the-stack
train
e3765148f097a1dc474578d9
train
function
def add_color(grey_img, c1_img, c2_img, c3_img, color): # Blue c1_img[grey_img == 0] = color[2] # Green c2_img[grey_img == 0] = color[1] # Red c3_img[grey_img == 0] = color[0] return c1_img, c2_img, c3_img
def add_color(grey_img, c1_img, c2_img, c3_img, color): # Blue
c1_img[grey_img == 0] = color[2] # Green c2_img[grey_img == 0] = color[1] # Red c3_img[grey_img == 0] = color[0] return c1_img, c2_img, c3_img
khaki, lawngreen, saddlebrown, crimson, darkcyan, green, lightsteelblue, purple2, darkseagreen, ] def add_color(grey_img, c1_img, c2_img, c3_img, color): # Blue
64
64
95
25
39
VinAIResearch/mDSDI
utils/generate_color_mnist.py
Python
add_color
add_color
106
113
106
107
1a5790ea12cbd08eceb0e32515d6936dfa9865e0
bigcode/the-stack
train
209b9a444493358324462ad7
train
function
def __virtual__(): """ Only load if boto libraries exist and if boto libraries are greater than a given version. """ has_boto_reqs = salt.utils.versions.check_boto_reqs(boto_ver="2.8.0", boto3_ver="1.2.6") if has_boto_reqs is True: if HAS_BOTO: __utils__["boto.assign_funcs"]...
def __virtual__():
""" Only load if boto libraries exist and if boto libraries are greater than a given version. """ has_boto_reqs = salt.utils.versions.check_boto_reqs(boto_ver="2.8.0", boto3_ver="1.2.6") if has_boto_reqs is True: if HAS_BOTO: __utils__["boto.assign_funcs"](__name__, "cloudwa...
: # pylint: disable=unused-import import boto3 # pylint: enable=unused-import logging.getLogger("boto3").setLevel(logging.CRITICAL) HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def __virtual__():
64
64
166
5
58
snetsystems/salt
salt/modules/boto_cloudwatch.py
Python
__virtual__
__virtual__
86
104
86
86
45adb1503f02678209791703ba76a88871ba9e90
bigcode/the-stack
train
188b9d5235771b4fd40cd897
train
function
def create_or_update_alarm( connection=None, name=None, metric=None, namespace=None, statistic=None, comparison=None, threshold=None, period=None, evaluation_periods=None, unit=None, description="", dimensions=None, alarm_actions=None, insufficient_data_actions=No...
def create_or_update_alarm( connection=None, name=None, metric=None, namespace=None, statistic=None, comparison=None, threshold=None, period=None, evaluation_periods=None, unit=None, description="", dimensions=None, alarm_actions=None, insufficient_data_actions=No...
""" Create or update a cloudwatch alarm. Params are the same as: https://boto.readthedocs.io/en/latest/ref/cloudwatch.html#boto.ec2.cloudwatch.alarm.MetricAlarm. Dimensions must be a dict. If the value of Dimensions is a string, it will be json decoded to produce a dict. alarm_actions, ins...
example:: salt myminion boto_cloudwatch.get_all_alarms region=us-east-1 --out=txt """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) alarms = conn.describe_alarms() results = odict.OrderedDict() for alarm in alarms: alarm = _metric_alarm_to_dict(alarm) ...
256
256
855
90
166
snetsystems/salt
salt/modules/boto_cloudwatch.py
Python
create_or_update_alarm
create_or_update_alarm
203
311
203
223
f1ef8322a57c4bdcbd03d32006eb4587278f333b
bigcode/the-stack
train
b461e2abe05317aeb4056cde
train
function
def _metric_alarm_to_dict(alarm): """ Convert a boto.ec2.cloudwatch.alarm.MetricAlarm into a dict. Convenience for pretty printing. """ d = odict.OrderedDict() fields = [ "name", "metric", "namespace", "statistic", "comparison", "threshold", ...
def _metric_alarm_to_dict(alarm):
""" Convert a boto.ec2.cloudwatch.alarm.MetricAlarm into a dict. Convenience for pretty printing. """ d = odict.OrderedDict() fields = [ "name", "metric", "namespace", "statistic", "comparison", "threshold", "period", "evaluation_pe...
us-east-1 """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.delete_alarms([name]) log.info("Deleted alarm %s", name) return True def _metric_alarm_to_dict(alarm):
64
64
145
9
54
snetsystems/salt
salt/modules/boto_cloudwatch.py
Python
_metric_alarm_to_dict
_metric_alarm_to_dict
354
379
354
354
2cc1d37e65431c83aba395c030d5523c46cf37b8
bigcode/the-stack
train
8c610be5e74ab92978569edd
train
function
def _safe_dump(data): """ this presenter magic makes yaml.safe_dump work with the objects returned from boto.describe_alarms() """ custom_dumper = __utils__["yaml.get_dumper"]("SafeOrderedDumper") def boto_listelement_presenter(dumper, data): return dumper.represent_list(list(data))...
def _safe_dump(data):
""" this presenter magic makes yaml.safe_dump work with the objects returned from boto.describe_alarms() """ custom_dumper = __utils__["yaml.get_dumper"]("SafeOrderedDumper") def boto_listelement_presenter(dumper, data): return dumper.represent_list(list(data)) yaml.add_represe...
= conn.describe_alarms(alarm_names=[name]) if not alarms: return None if len(alarms) > 1: log.error("multiple alarms matched name '%s'", name) return _metric_alarm_to_dict(alarms[0]) def _safe_dump(data):
64
64
181
6
58
snetsystems/salt
salt/modules/boto_cloudwatch.py
Python
_safe_dump
_safe_dump
125
151
125
125
301bbc1444efd21e1ef14fb071d32aacc51380ac
bigcode/the-stack
train
af2bee0d1353141df931938a
train
function
def get_alarm(name, region=None, key=None, keyid=None, profile=None): """ Get alarm details. Also can be used to check to see if an alarm exists. CLI example:: salt myminion boto_cloudwatch.get_alarm myalarm region=us-east-1 """ conn = _get_conn(region=region, key=key, keyid=keyid, profile...
def get_alarm(name, region=None, key=None, keyid=None, profile=None):
""" Get alarm details. Also can be used to check to see if an alarm exists. CLI example:: salt myminion boto_cloudwatch.get_alarm myalarm region=us-east-1 """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) alarms = conn.describe_alarms(alarm_names=[name]) i...
boto3.assign_funcs"]( __name__, "cloudwatch", get_conn_funcname="_get_conn3", cache_id_funcname="_cache_id3" ) return has_boto_reqs def get_alarm(name, region=None, key=None, keyid=None, profile=None):
64
64
147
18
45
snetsystems/salt
salt/modules/boto_cloudwatch.py
Python
get_alarm
get_alarm
107
122
107
107
d7d27080db9f249f30b55c23f01e3e47bfde4142
bigcode/the-stack
train
18416f6b84fea1d510c38ea3
train
function
def convert_to_arn(arns, region=None, key=None, keyid=None, profile=None): """ Convert a list of strings into actual arns. Converts convenience names such as 'scaling_policy:...' CLI Example:: salt '*' convert_to_arn 'scaling_policy:' """ results = [] for arn in arns: if ar...
def convert_to_arn(arns, region=None, key=None, keyid=None, profile=None):
""" Convert a list of strings into actual arns. Converts convenience names such as 'scaling_policy:...' CLI Example:: salt '*' convert_to_arn 'scaling_policy:' """ results = [] for arn in arns: if arn.startswith("scaling_policy:"): _, as_group, scaling_policy_na...
insufficient_data_actions=insufficient_data_actions, ok_actions=ok_actions, ) conn.create_alarm(alarm) log.info("Created/updated alarm %s", name) return True def convert_to_arn(arns, region=None, key=None, keyid=None, profile=None):
64
64
182
21
42
snetsystems/salt
salt/modules/boto_cloudwatch.py
Python
convert_to_arn
convert_to_arn
314
336
314
314
14def4c476f1002da0055e1595c60aae0b219685
bigcode/the-stack
train
38effa8ce2176cfbe8380f18
train
function
def delete_alarm(name, region=None, key=None, keyid=None, profile=None): """ Delete a cloudwatch alarm CLI example to delete a queue:: salt myminion boto_cloudwatch.delete_alarm myalarm region=us-east-1 """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.de...
def delete_alarm(name, region=None, key=None, keyid=None, profile=None):
""" Delete a cloudwatch alarm CLI example to delete a queue:: salt myminion boto_cloudwatch.delete_alarm myalarm region=us-east-1 """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.delete_alarms([name]) log.info("Deleted alarm %s", name) return Tru...
profile ) if policy_arn: results.append(policy_arn) else: log.error("Could not convert: %s", arn) else: results.append(arn) return results def delete_alarm(name, region=None, key=None, keyid=None, profile=None):
64
64
104
18
45
snetsystems/salt
salt/modules/boto_cloudwatch.py
Python
delete_alarm
delete_alarm
339
351
339
339
adf8d2733d18fa3f99c07df9c7ad042fcdb023af
bigcode/the-stack
train
56cb96065b15baa132520aa0
train
function
def list_metrics( namespace=None, dimensions=[], next_token=None, region=None, key=None, keyid=None, profile=None, ): """ List the specified metrics. You can use the returned metrics with `GetMetricData <https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_GetMetricD...
def list_metrics( namespace=None, dimensions=[], next_token=None, region=None, key=None, keyid=None, profile=None, ):
""" List the specified metrics. You can use the returned metrics with `GetMetricData <https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_GetMetricData.html>`_ or `GetMetricStatistics <https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_GetMetricStatistics.html>`_ to obtain sta...
alarms([name]) log.info("Deleted alarm %s", name) return True def _metric_alarm_to_dict(alarm): """ Convert a boto.ec2.cloudwatch.alarm.MetricAlarm into a dict. Convenience for pretty printing. """ d = odict.OrderedDict() fields = [ "name", "metric", "namespace"...
200
200
669
35
164
snetsystems/salt
salt/modules/boto_cloudwatch.py
Python
list_metrics
list_metrics
382
463
382
391
feec77d9806bf85665c3395d2e493d5f5937bac9
bigcode/the-stack
train
2cb2ce7c5c25d208f67ab5ba
train
function
def get_all_alarms(region=None, prefix=None, key=None, keyid=None, profile=None): """ Get all alarm details. Produces results that can be used to create an sls file. If prefix parameter is given, alarm names in the output will be prepended with the prefix; alarms that have the prefix will be skipp...
def get_all_alarms(region=None, prefix=None, key=None, keyid=None, profile=None):
""" Get all alarm details. Produces results that can be used to create an sls file. If prefix parameter is given, alarm names in the output will be prepended with the prefix; alarms that have the prefix will be skipped. This can be used to convert existing alarms to be managed by salt, as fol...
SafeOrderedDumper") def boto_listelement_presenter(dumper, data): return dumper.represent_list(list(data)) yaml.add_representer( boto.ec2.cloudwatch.listelement.ListElement, boto_listelement_presenter, Dumper=custom_dumper, ) def dimension_presenter(dumper, data): ...
155
155
518
22
133
snetsystems/salt
salt/modules/boto_cloudwatch.py
Python
get_all_alarms
get_all_alarms
154
200
154
154
d1df3bc03c1e7640472e921364f1f5bc0e339879
bigcode/the-stack
train
57408395db3b2ec51f24bff6
train
class
class ExpressRouteConnectionsOperations: """ExpressRouteConnectionsOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this o...
class ExpressRouteConnectionsOperations:
"""ExpressRouteConnectionsOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure....
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
233
256
4,314
6
227
praveenkuttappan/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_12_01/aio/operations/_express_route_connections_operations.py
Python
ExpressRouteConnectionsOperations
ExpressRouteConnectionsOperations
23
414
23
23
cf50ebc330a7410cac335f156c748b2f65810ae2
bigcode/the-stack
train
0ee1d60b1e2851ff7acab482
train
class
class OptunaKNeighborRegressorOutOfFold(GenericOutOfFoldOptunaFeature): model_class = KNeighborsRegressor def generate_model_class_try_params(self, trial: Trial): params = { 'weights': trial.suggest_categorical('weights', ['distance', 'uniform']), 'p': trial.suggest_uniform('p',...
class OptunaKNeighborRegressorOutOfFold(GenericOutOfFoldOptunaFeature):
model_class = KNeighborsRegressor def generate_model_class_try_params(self, trial: Trial): params = { 'weights': trial.suggest_categorical('weights', ['distance', 'uniform']), 'p': trial.suggest_uniform('p', 1, 4), 'n_neighbors': int(trial.suggest_int('n_neighbors', ...
n_neighbors': 5 } class KNeighborRegressorOutOfFold(GenericOutOfFoldFeature): model_class = KNeighborsRegressor initial_params = { 'n_neighbors': 5 } class OptunaKNeighborRegressorOutOfFold(GenericOutOfFoldOptunaFeature):
64
64
162
18
46
upura/vivid
vivid/out_of_fold/kneighbor.py
Python
OptunaKNeighborRegressorOutOfFold
OptunaKNeighborRegressorOutOfFold
25
39
25
25
986316afe91d92f3f8b441236923fa8a59ffd75a
bigcode/the-stack
train
64db3f52e77bf1e0c9777944
train
class
class KNeighborRegressorOutOfFold(GenericOutOfFoldFeature): model_class = KNeighborsRegressor initial_params = { 'n_neighbors': 5 }
class KNeighborRegressorOutOfFold(GenericOutOfFoldFeature):
model_class = KNeighborsRegressor initial_params = { 'n_neighbors': 5 }
import GenericOutOfFoldFeature, GenericOutOfFoldOptunaFeature class KNeighborClassifierOOF(GenericOutOfFoldFeature): model_class = KNeighborsClassifier initial_params = { 'n_neighbors': 5 } class KNeighborRegressorOutOfFold(GenericOutOfFoldFeature):
64
64
38
14
50
upura/vivid
vivid/out_of_fold/kneighbor.py
Python
KNeighborRegressorOutOfFold
KNeighborRegressorOutOfFold
18
22
18
18
3dafaa2d606d79c4b18a03f7fcdc874dce56cb45
bigcode/the-stack
train
ce69a10b451b3b8fbf51ec02
train
class
class KNeighborClassifierOOF(GenericOutOfFoldFeature): model_class = KNeighborsClassifier initial_params = { 'n_neighbors': 5 }
class KNeighborClassifierOOF(GenericOutOfFoldFeature):
model_class = KNeighborsClassifier initial_params = { 'n_neighbors': 5 }
# coding: utf-8 """ """ from optuna.trial import Trial from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor from .base import GenericOutOfFoldFeature, GenericOutOfFoldOptunaFeature class KNeighborClassifierOOF(GenericOutOfFoldFeature):
61
64
35
12
48
upura/vivid
vivid/out_of_fold/kneighbor.py
Python
KNeighborClassifierOOF
KNeighborClassifierOOF
11
15
11
11
b7112c4209c0b1b4cc5d67f9590895815af83026
bigcode/the-stack
train
08b55a177749ec27dedf9d62
train
class
class ModelBuffer(CPOBuffer): def __init__(self, batch_size, env, max_path_length, ensemble_size, rollout_mode=False, cares_about_cost = False, max_uncertainty_r = 5.5, max_uncertainty_c = 5.5, *args, **kwargs, ...
class ModelBuffer(CPOBuffer):
def __init__(self, batch_size, env, max_path_length, ensemble_size, rollout_mode=False, cares_about_cost = False, max_uncertainty_r = 5.5, max_uncertainty_c = 5.5, *args, **kwargs, ): ...
import numpy as np from softlearning.policies.safe_utils.mpi_tools import mpi_statistics_scalar from softlearning.policies.safe_utils.utils import * from softlearning.replay_pools.cpobuffer import CPOBuffer import scipy.signal class ModelBuffer(CPOBuffer):
56
256
5,468
7
48
anyboby/ConstrainedMBPO
softlearning/replay_pools/modelbuffer.py
Python
ModelBuffer
ModelBuffer
8
405
8
9
d4bae3c8be033e3b90061a3f586fb480071656ca
bigcode/the-stack
train
4eceece6808f380d4f5ea6e1
train
function
def update_build_systems(): ''' Update build system and Qt resource descriptors. ''' filename_lang = [re.match(r'((remita_(.*)).ts)$', filename).groups() for (filename, filepath) in all_ts_files(include_source=True)] filename_lang.sort(key=lambda x: x[0]) # update qrc locales with open('src...
def update_build_systems():
''' Update build system and Qt resource descriptors. ''' filename_lang = [re.match(r'((remita_(.*)).ts)$', filename).groups() for (filename, filepath) in all_ts_files(include_source=True)] filename_lang.sort(key=lambda x: x[0]) # update qrc locales with open('src/qt/remita_locale.qrc', 'w')...
def update_git(): ''' Add new files to git repository. (Removing files isn't necessary here, as `git commit -a` will take care of removing files that are gone) ''' file_paths = [filepath for (filename, filepath) in all_ts_files()] subprocess.check_call([GIT, 'add'] + file_paths) def update_build...
79
79
265
6
73
Remitacoin/rem
contrib/devtools/update-translations.py
Python
update_build_systems
update_build_systems
233
253
233
233
cf64ac8025c5775dd80d7ae911c03caa98d757ab
bigcode/the-stack
train
607ebb625a320ed398b25646
train
function
def sanitize_string(s): '''Sanitize string for printing''' return s.replace('\n',' ')
def sanitize_string(s):
'''Sanitize string for printing''' return s.replace('\n',' ')
this, this function # would wrongly detect '%)' as a printf format specifier. if numeric: other = [] # numeric (Qt) can be present in any order, others (strprintf) must be in specified order return set(numeric),other def sanitize_string(s):
64
64
21
5
58
Remitacoin/rem
contrib/devtools/update-translations.py
Python
sanitize_string
sanitize_string
99
101
99
99
3bf41e4a161e3999fd7cc587b8f72f523ec406e8
bigcode/the-stack
train
05e4eb33782f028a7dfb72fe
train
function
def split_format_specifiers(specifiers): '''Split format specifiers between numeric (Qt) and others (strprintf)''' numeric = [] other = [] for s in specifiers: if s in {'1','2','3','4','5','6','7','8','9'}: numeric.append(s) else: other.append(s) # If both nu...
def split_format_specifiers(specifiers):
'''Split format specifiers between numeric (Qt) and others (strprintf)''' numeric = [] other = [] for s in specifiers: if s in {'1','2','3','4','5','6','7','8','9'}: numeric.append(s) else: other.append(s) # If both numeric format specifiers and "others" are ...
while True: percent = s.find('%', pos) if percent < 0: break try: specifiers.append(s[percent+1]) except: print('Failed to get specifier') pos = percent+2 return specifiers def split_format_specifiers(specifiers):
68
68
228
8
59
Remitacoin/rem
contrib/devtools/update-translations.py
Python
split_format_specifiers
split_format_specifiers
78
97
78
78
2236932f922a87224fea1284803651bb4b50670c
bigcode/the-stack
train
267f452bb0caa31d084ea209
train
function
def all_ts_files(suffix='', include_source=False): for filename in os.listdir(LOCALE_DIR): # process only language files, and do not process source language if not filename.endswith('.ts'+suffix) or (not include_source and filename == SOURCE_LANG+suffix): continue if suffix: # re...
def all_ts_files(suffix='', include_source=False):
for filename in os.listdir(LOCALE_DIR): # process only language files, and do not process source language if not filename.endswith('.ts'+suffix) or (not include_source and filename == SOURCE_LANG+suffix): continue if suffix: # remove provided suffix filename = filenam...
translations to omit %n specifier (usually when it only has one possible value) return True errors.append("Mismatch between '%s' and '%s'" % (sanitize_string(source), sanitize_string(translation))) return False return True def all_ts_files(suffix='', include_source=False):
64
64
101
11
52
Remitacoin/rem
contrib/devtools/update-translations.py
Python
all_ts_files
all_ts_files
122
130
122
122
06e5b4e457c11c95b19ec8f707d92e5ad1db75a5
bigcode/the-stack
train
95c2c112f4af3c0b88b575fa
train
function
def remove_current_translations(): ''' Remove current translations, as well as temporary files that might be left behind We only want the active translations that are currently on transifex. This leaves remita_en.ts untouched. ''' for (_,name) in all_ts_files(): os.remove(name) for (...
def remove_current_translations():
''' Remove current translations, as well as temporary files that might be left behind We only want the active translations that are currently on transifex. This leaves remita_en.ts untouched. ''' for (_,name) in all_ts_files(): os.remove(name) for (_,name) in all_ts_files('.orig'): ...
IT = os.getenv("GIT", "git") def check_at_repository_root(): if not os.path.exists('.git'): print('No .git directory found') print('Execute this script at the root of the repository', file=sys.stderr) sys.exit(1) def remove_current_translations():
64
64
85
6
58
Remitacoin/rem
contrib/devtools/update-translations.py
Python
remove_current_translations
remove_current_translations
44
53
44
44
e9c7569472996867bea406458bdb7e5789aea6df
bigcode/the-stack
train
75d94542ffecc5fe65cf54a8
train
function
def fetch_all_translations(fAll = False): call_list = [TX, 'pull', '-f', '-a'] if not fAll: call_list.append('--minimum-perc=%s' % MINIMUM_PERC) if subprocess.call(call_list): print('Error while fetching translations', file=sys.stderr) sys.exit(1)
def fetch_all_translations(fAll = False):
call_list = [TX, 'pull', '-f', '-a'] if not fAll: call_list.append('--minimum-perc=%s' % MINIMUM_PERC) if subprocess.call(call_list): print('Error while fetching translations', file=sys.stderr) sys.exit(1)
that are currently on transifex. This leaves remita_en.ts untouched. ''' for (_,name) in all_ts_files(): os.remove(name) for (_,name) in all_ts_files('.orig'): os.remove(name + '.orig') def fetch_all_translations(fAll = False):
64
64
74
10
54
Remitacoin/rem
contrib/devtools/update-translations.py
Python
fetch_all_translations
fetch_all_translations
55
61
55
55
3c6b185a3467bb0b021459ca44c8a59e264d8fa7
bigcode/the-stack
train
9f15aa8c53522230fb1525a9
train
function
def update_git(): ''' Add new files to git repository. (Removing files isn't necessary here, as `git commit -a` will take care of removing files that are gone) ''' file_paths = [filepath for (filename, filepath) in all_ts_files()] subprocess.check_call([GIT, 'add'] + file_paths)
def update_git():
''' Add new files to git repository. (Removing files isn't necessary here, as `git commit -a` will take care of removing files that are gone) ''' file_paths = [filepath for (filename, filepath) in all_ts_files()] subprocess.check_call([GIT, 'add'] + file_paths)
='utf-8') out = out.getvalue() out = out.replace(b' />', b'/>') with open(filepath, 'wb') as f: f.write(out) else: tree.write(filepath, encoding='utf-8') return have_errors def update_git():
64
64
73
4
59
Remitacoin/rem
contrib/devtools/update-translations.py
Python
update_git
update_git
224
230
224
224
9164b44cd5c11064b17048d7a84a44984e4a134b
bigcode/the-stack
train
2632fa389f0c6cee0063fa44
train
function
def escape_cdata(text): text = _orig_escape_cdata(text) text = text.replace("'", '&apos;') text = text.replace('"', '&quot;') return text
def escape_cdata(text):
text = _orig_escape_cdata(text) text = text.replace("'", '&apos;') text = text.replace('"', '&quot;') return text
acters(s): '''Remove invalid characters from translation string''' return FIX_RE.sub(b'', s) # Override cdata escape function to make our output match Qt's (optional, just for cleaner diffs for # comparison, disable by default) _orig_escape_cdata = None def escape_cdata(text):
64
64
42
6
57
Remitacoin/rem
contrib/devtools/update-translations.py
Python
escape_cdata
escape_cdata
140
144
140
140
a0ad083ad5161501d817976805d7156747d0fc02
bigcode/the-stack
train
d7825ee2fc3762de42ebe615
train
function
def check_at_repository_root(): if not os.path.exists('.git'): print('No .git directory found') print('Execute this script at the root of the repository', file=sys.stderr) sys.exit(1)
def check_at_repository_root():
if not os.path.exists('.git'): print('No .git directory found') print('Execute this script at the root of the repository', file=sys.stderr) sys.exit(1)
' # Minimum number of messages for translation to be considered at all MIN_NUM_MESSAGES = 10 # Minimum completion percentage required to download from transifex MINIMUM_PERC = 80 # Path to git GIT = os.getenv("GIT", "git") def check_at_repository_root():
64
64
47
6
58
Remitacoin/rem
contrib/devtools/update-translations.py
Python
check_at_repository_root
check_at_repository_root
38
42
38
38
3f13d26680e10bef2a3f45d6dea32e2eb1b6f9fe
bigcode/the-stack
train
96ac12381a1e86c652438aab
train
function
def find_format_specifiers(s): '''Find all format specifiers in a string.''' pos = 0 specifiers = [] while True: percent = s.find('%', pos) if percent < 0: break try: specifiers.append(s[percent+1]) except: print('Failed to get specifie...
def find_format_specifiers(s):
'''Find all format specifiers in a string.''' pos = 0 specifiers = [] while True: percent = s.find('%', pos) if percent < 0: break try: specifiers.append(s[percent+1]) except: print('Failed to get specifier') pos = percent+2 ...
'pull', '-f', '-a'] if not fAll: call_list.append('--minimum-perc=%s' % MINIMUM_PERC) if subprocess.call(call_list): print('Error while fetching translations', file=sys.stderr) sys.exit(1) def find_format_specifiers(s):
64
64
90
7
57
Remitacoin/rem
contrib/devtools/update-translations.py
Python
find_format_specifiers
find_format_specifiers
63
76
63
63
948e241f4d1445b95b1ad11701db51eb2146e7c1
bigcode/the-stack
train
43e937f1382b1c1c16dc54cf
train
function
def check_format_specifiers(source, translation, errors, numerus): source_f = split_format_specifiers(find_format_specifiers(source)) # assert that no source messages contain both Qt and strprintf format specifiers # if this fails, go change the source as this is hacky and confusing! assert(not(source_f...
def check_format_specifiers(source, translation, errors, numerus):
source_f = split_format_specifiers(find_format_specifiers(source)) # assert that no source messages contain both Qt and strprintf format specifiers # if this fails, go change the source as this is hacky and confusing! assert(not(source_f[0] and source_f[1])) try: translation_f = split_format...
[] # numeric (Qt) can be present in any order, others (strprintf) must be in specified order return set(numeric),other def sanitize_string(s): '''Sanitize string for printing''' return s.replace('\n',' ') def check_format_specifiers(source, translation, errors, numerus):
68
69
230
14
54
Remitacoin/rem
contrib/devtools/update-translations.py
Python
check_format_specifiers
check_format_specifiers
103
120
103
103
0279122a5f1f1c3ac141693e4d6ef894869e697f
bigcode/the-stack
train
46f261ef504dfd96cb5144d2
train
function
def postprocess_translations(reduce_diff_hacks=False): print('Checking and postprocessing...') if reduce_diff_hacks: global _orig_escape_cdata _orig_escape_cdata = ET._escape_cdata ET._escape_cdata = escape_cdata for (filename,filepath) in all_ts_files(): os.rename(filepath...
def postprocess_translations(reduce_diff_hacks=False):
print('Checking and postprocessing...') if reduce_diff_hacks: global _orig_escape_cdata _orig_escape_cdata = ET._escape_cdata ET._escape_cdata = escape_cdata for (filename,filepath) in all_ts_files(): os.rename(filepath, filepath+'.orig') have_errors = False for (f...
_source and filename == SOURCE_LANG+suffix): continue if suffix: # remove provided suffix filename = filename[0:-len(suffix)] filepath = os.path.join(LOCALE_DIR, filename) yield(filename, filepath) FIX_RE = re.compile(b'[\x00-\x09\x0b\x0c\x0e-\x1f]') def remove_invalid_c...
194
194
647
12
181
Remitacoin/rem
contrib/devtools/update-translations.py
Python
postprocess_translations
postprocess_translations
146
222
146
146
15bee6a32bf7dbeb48912f0b8d5ec9553a40f7bb
bigcode/the-stack
train
e0af2fa8ef59208d91d5e55e
train
function
def remove_invalid_characters(s): '''Remove invalid characters from translation string''' return FIX_RE.sub(b'', s)
def remove_invalid_characters(s):
'''Remove invalid characters from translation string''' return FIX_RE.sub(b'', s)
filename = filename[0:-len(suffix)] filepath = os.path.join(LOCALE_DIR, filename) yield(filename, filepath) FIX_RE = re.compile(b'[\x00-\x09\x0b\x0c\x0e-\x1f]') def remove_invalid_characters(s):
64
64
25
7
58
Remitacoin/rem
contrib/devtools/update-translations.py
Python
remove_invalid_characters
remove_invalid_characters
133
135
133
133
f01df57c7e739d19b8f8316a2a6f3ece5e1fe7c1
bigcode/the-stack
train
c24ac93b5727e98302545b31
train
class
class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_images') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self....
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_images') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) if img.h...
from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model):
24
64
110
5
18
Rxavio/teamwork-django
mywork/users/models.py
Python
Profile
Profile
6
21
6
6
a46b9cd884b63da520dd1caab61335dbbb89ac45
bigcode/the-stack
train
fc6acf6ef1c8ec430afab13f
train
class
class CountryRepository: def __init__(self): self.country_data_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), "countrydata", "data", "countries") country_codes_file = os.path.join(os.path.abspath(os.path.dirname(__file__)), "country_codes....
class CountryRepository:
def __init__(self): self.country_data_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), "countrydata", "data", "countries") country_codes_file = os.path.join(os.path.abspath(os.path.dirname(__file__)), "country_codes.json") with open(...
import json import os class CountryRepository:
10
64
203
4
5
BlueBrain/covid-19-find
api/covid19find/simulation/countryrepository.py
Python
CountryRepository
CountryRepository
5
30
5
5
d396a19286016c60ccada38670c6ce0aef38532f
bigcode/the-stack
train
9acde9cfe42463a1263a9896
train
function
def watch_continuous(): parser = argparse.ArgumentParser(description="Watch a continuous agent.") parser.add_argument("env", help="ID of the Environment") parser.add_argument("dir", help="Directory where the agent's model was saved.") parser.add_argument( "--device", default="cpu", ...
def watch_continuous():
parser = argparse.ArgumentParser(description="Watch a continuous agent.") parser.add_argument("env", help="ID of the Environment") parser.add_argument("dir", help="Directory where the agent's model was saved.") parser.add_argument( "--device", default="cpu", help="The name of the...
# pylint: disable=unused-import import argparse import pybullet import pybullet_envs from all.bodies import TimeFeature from all.environments import GymEnvironment from all.experiments import GreedyAgent, watch from continuous import ENVS def watch_continuous():
61
64
187
6
54
gordon-frost-hwu/autonomous-learning-library
scripts/watch_continuous.py
Python
watch_continuous
watch_continuous
11
34
11
11
e86660a74b13f122067c5f1df531072fb7380228
bigcode/the-stack
train
a03adaffe4604f82b4c48773
train
class
class FormsApi(object): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client ...
class FormsApi(object):
"""NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client self.list_form_en...
""" PandaDoc Public API PandaDoc Public API documentation # noqa: E501 Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 from pandadoc_client.api_client import ApiClient, Endpoint as _Endpoint from pandadoc_client.model_utils import ( # noqa: F401 c...
132
256
1,178
5
126
dyakutkin/pandadoc-api-python-client
pandadoc_client/api/forms_api.py
Python
FormsApi
FormsApi
26
205
26
26
bc9fc647b773f1af54f3bee1b5207956a8ab9156
bigcode/the-stack
train
dc46c8532d0de324fbb44c55
train
class
class WeaponTestCase(unittest.TestCase): def test_accuracy1(self): w = weapon.Weapon(range_tm=1) self.assertEqual(w.get_accuracy(0), 100) def test_accuracy2(self): w = weapon.Weapon(range_tm=1) self.assertEqual(w.get_accuracy(1), 0) def test_accuracy3(self): w = wea...
class WeaponTestCase(unittest.TestCase):
def test_accuracy1(self): w = weapon.Weapon(range_tm=1) self.assertEqual(w.get_accuracy(0), 100) def test_accuracy2(self): w = weapon.Weapon(range_tm=1) self.assertEqual(w.get_accuracy(1), 0) def test_accuracy3(self): w = weapon.Weapon(range_tm=1, is_beam=False) ...
import unittest from unittest.mock import patch from .. import * class WeaponTestCase(unittest.TestCase):
21
256
1,020
8
13
therussellhome/inherit_the_stars
stars/test/test_weapon.py
Python
WeaponTestCase
WeaponTestCase
6
89
6
6
6c56cac60958f23e5846729d8a678bb954375127
bigcode/the-stack
train
bc588a3be4eeb88fae115b1a
train
class
class YahooAnswersTopics(datalabs.GeneratorBasedBuilder): "Yahoo! Answers Topic Classification Dataset" VERSION = datalabs.Version("1.0.0") BUILDER_CONFIGS = [ datalabs.BuilderConfig( name="yahoo_answers_topics", version=datalabs.Version("1.0.0", ""), ), ] d...
class YahooAnswersTopics(datalabs.GeneratorBasedBuilder):
"Yahoo! Answers Topic Classification Dataset" VERSION = datalabs.Version("1.0.0") BUILDER_CONFIGS = [ datalabs.BuilderConfig( name="yahoo_answers_topics", version=datalabs.Version("1.0.0", ""), ), ] def _info(self): return datalabs.DatasetInfo( ...
and other meta-information, this dataset only used the best answer content and the main category information. """ _URL = "https://drive.google.com/uc?export=download&id=0Bz8a_Dbh9Qhbd2JNdDBsQUdocVU&confirm=yes" _TOPICS = [ "Society & Culture", "Science & Mathematics", "Health", "Education & Reference...
134
134
449
12
122
ExpressAI/DataLab
datasets/yahoo_answers_topics/yahoo_answers_topics.py
Python
YahooAnswersTopics
YahooAnswersTopics
46
101
46
46
d6888fc79a0af917cc799c6fb843969a55b029d4
bigcode/the-stack
train
5029f6eab2971dec610e0581
train
class
class PNASNetTest(tf.test.TestCase): def testBuildLogitsLargeModel(self): batch_size = 5 height, width = 331, 331 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) tf.train.create_global_step() with slim.arg_scope(pnasnet.pnasnet_large_arg_scope()): logits, e...
class PNASNetTest(tf.test.TestCase):
def testBuildLogitsLargeModel(self): batch_size = 5 height, width = 331, 331 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) tf.train.create_global_step() with slim.arg_scope(pnasnet.pnasnet_large_arg_scope()): logits, end_points = pnasnet.build_pnasnet_larg...
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
178
256
2,701
10
167
jiahuei/tf-sparse-captioning
common/nets/nasnet/pnasnet_test.py
Python
PNASNetTest
PNASNetTest
24
250
24
25
bb6f5feeeb12efaf16abc31f18850fd44df7b14f
bigcode/the-stack
train
8cc09d5838a7bac024c104c4
train
function
def _check_measurements(measurements: List[Measurement], limit: int): assert len(measurements) == limit i = limit for measurement in measurements: assert measurement.value == (i - 1) * 1.0 i -= 1
def _check_measurements(measurements: List[Measurement], limit: int):
assert len(measurements) == limit i = limit for measurement in measurements: assert measurement.value == (i - 1) * 1.0 i -= 1
_c=i * 1.0, wh_used=i * 1.0, wh_generated=i * 1.0, timestamp=time)) time = time - datetime.timedelta(minutes=1) yield readings def _check_measurements(measurements: List[Measurement], limit: int):
64
64
61
17
46
4heck/ru102py
tests/api/test_metrics_api.py
Python
_check_measurements
_check_measurements
38
44
38
38
8ed5901ffac1b5e63f1d608dd704d1f5c0db075d
bigcode/the-stack
train
567f5256b63ac3836cdc2c37
train
function
@pytest.mark.skip("Remove for challenge #2") def test_small(metric_dao, readings, client): _test_insert_and_retrieve(client, readings, metric_dao, 1)
@pytest.mark.skip("Remove for challenge #2") def test_small(metric_dao, readings, client):
_test_insert_and_retrieve(client, readings, metric_dao, 1)
rdt = reading.timestamp assert mdt.hour == rdt.hour and mdt.minute == rdt.minute \ and mdt.day == mdt.day and mdt.year == rdt.year @pytest.mark.skip("Remove for challenge #2") def test_small(metric_dao, readings, client):
64
64
39
21
42
4heck/ru102py
tests/api/test_metrics_api.py
Python
test_small
test_small
81
83
81
82
7b88d4446b2e33f428fdd472bbbbf0852e378448
bigcode/the-stack
train
8cf905269b3221819dde54fe
train
function
@pytest.mark.skip("Remove for challenge #2") def _test_insert_and_retrieve(client, readings: List[MeterReading], metric_dao: MetricDaoRedis, limit: int): for reading in readings: metric_dao.insert(reading) resp = client.get(f'/metrics/{TESTING_SITE_ID}?count={limit}').json...
@pytest.mark.skip("Remove for challenge #2") def _test_insert_and_retrieve(client, readings: List[MeterReading], metric_dao: MetricDaoRedis, limit: int):
for reading in readings: metric_dao.insert(reading) resp = client.get(f'/metrics/{TESTING_SITE_ID}?count={limit}').json plots = resp['plots'] for plot in plots: measurements = MeasurementSchema(many=True).load(plot['measurements']) _check_measurements(measurements, limit)
== (i - 1) * 1.0 i -= 1 # Callenge #2 @pytest.mark.skip("Remove for challenge #2") def _test_insert_and_retrieve(client, readings: List[MeterReading], metric_dao: MetricDaoRedis, limit: int):
64
64
113
39
24
4heck/ru102py
tests/api/test_metrics_api.py
Python
_test_insert_and_retrieve
_test_insert_and_retrieve
49
60
49
51
b05dbcef785a578ce5226b80a6032d5a9fef723c
bigcode/the-stack
train
8451412ce8b82041c9663cdb
train
function
@pytest.fixture def readings(metric_dao) -> Generator[Deque[MeterReading], None, None]: readings: deque = deque() time = NOW for i in range(72 * 60): readings.appendleft( MeterReading(site_id=1, temp_c=i * 1.0, wh_used=i * 1.0, ...
@pytest.fixture def readings(metric_dao) -> Generator[Deque[MeterReading], None, None]:
readings: deque = deque() time = NOW for i in range(72 * 60): readings.appendleft( MeterReading(site_id=1, temp_c=i * 1.0, wh_used=i * 1.0, wh_generated=i * 1.0, timestamp=time)) t...
redisolar.schema import MeasurementSchema TESTING_SITE_ID = 1 NOW = datetime.datetime.utcnow() @pytest.fixture def metric_dao(redis, key_schema): yield MetricDaoRedis(redis, key_schema) @pytest.fixture def readings(metric_dao) -> Generator[Deque[MeterReading], None, None]:
64
64
106
21
43
4heck/ru102py
tests/api/test_metrics_api.py
Python
readings
readings
23
35
23
24
c8097609bae9c7657af20bc599fccc00ad7b930d
bigcode/the-stack
train
dbce59a4578018dcd30d2d29
train
function
@pytest.mark.skip("Remove for challenge #2") def test_large(metric_dao, readings, client): _test_insert_and_retrieve(client, readings, metric_dao, 100)
@pytest.mark.skip("Remove for challenge #2") def test_large(metric_dao, readings, client):
_test_insert_and_retrieve(client, readings, metric_dao, 100)
rdt.year @pytest.mark.skip("Remove for challenge #2") def test_small(metric_dao, readings, client): _test_insert_and_retrieve(client, readings, metric_dao, 1) @pytest.mark.skip("Remove for challenge #2") def test_large(metric_dao, readings, client):
64
64
39
21
43
4heck/ru102py
tests/api/test_metrics_api.py
Python
test_large
test_large
86
88
86
87
997bc0fa6133523199ccf85149e9b6b3adf61395
bigcode/the-stack
train
96b42dac90adfc37bfc1d7fa
train
function
@pytest.fixture def metric_dao(redis, key_schema): yield MetricDaoRedis(redis, key_schema)
@pytest.fixture def metric_dao(redis, key_schema):
yield MetricDaoRedis(redis, key_schema)
List import pytest from redisolar.dao.redis import MetricDaoRedis from redisolar.models import Measurement from redisolar.models import MeterReading from redisolar.schema import MeasurementSchema TESTING_SITE_ID = 1 NOW = datetime.datetime.utcnow() @pytest.fixture def metric_dao(redis, key_schema):
64
64
22
12
52
4heck/ru102py
tests/api/test_metrics_api.py
Python
metric_dao
metric_dao
18
20
18
19
a1ef6a4d78fdf4bc14b0556466531966ebc795f5
bigcode/the-stack
train
93c66d99ad1bc74cc381efcd
train
function
@pytest.mark.skip("Remove for challenge #2") def test_datetime_is_unix_timestamp(metric_dao, client): reading = MeterReading(site_id=1, temp_c=1.0, wh_used=1.0, wh_generated=1.0, timestamp=NOW) metric_dao...
@pytest.mark.skip("Remove for challenge #2") def test_datetime_is_unix_timestamp(metric_dao, client):
reading = MeterReading(site_id=1, temp_c=1.0, wh_used=1.0, wh_generated=1.0, timestamp=NOW) metric_dao.insert(reading) resp = client.get(f'/metrics/{TESTING_SITE_ID}?count=1').json plots = resp['...
json plots = resp['plots'] for plot in plots: measurements = MeasurementSchema(many=True).load(plot['measurements']) _check_measurements(measurements, limit) @pytest.mark.skip("Remove for challenge #2") def test_datetime_is_unix_timestamp(metric_dao, client):
64
64
166
23
41
4heck/ru102py
tests/api/test_metrics_api.py
Python
test_datetime_is_unix_timestamp
test_datetime_is_unix_timestamp
63
78
63
64
2ea9073535cafc8cc335c731f6e088700a09ad8b
bigcode/the-stack
train
51412b27a64ed1b27234eb38
train
class
class PaymentResponseTest(unittest.TestCase): def test_response_cast(self): response = PaymentResponse({ "id": "21b23365-000f-500b-9000-070fa3554403", "amount": { "value": "1000.00", "currency": "RUB" }, "confirmation": { ...
class PaymentResponseTest(unittest.TestCase):
def test_response_cast(self): response = PaymentResponse({ "id": "21b23365-000f-500b-9000-070fa3554403", "amount": { "value": "1000.00", "currency": "RUB" }, "confirmation": { "type": "redirect", ...
import unittest from yandex_checkout.domain.models.amount import Amount from yandex_checkout.domain.models.authorization_details import AuthorizationDetails from yandex_checkout.domain.models.cancellation_details import CancellationDetails from yandex_checkout.domain.models.confirmation.confirmation import Confirmatio...
101
195
651
8
92
krkmetal/yandex-checkout-sdk-python
test/unit/payment_response_test.py
Python
PaymentResponseTest
PaymentResponseTest
12
79
12
12
62325a3179b729fd1af0ffd4f57d1761f2d793ee
bigcode/the-stack
train
e482aeb143a5564c9afe72fe
train
class
class HTTPConnectionPool(urllib3.connectionpool.HTTPConnectionPool): ''' Socket HTTP Connection Pool ''' def __init__(self, url, timeout): self.timeout = urllib3.connectionpool.Timeout(connect=timeout[0], read=timeout[1]) super(HTTPConnectionPool, self).__init__('localhost', timeout=self.timeout...
class HTTPConnectionPool(urllib3.connectionpool.HTTPConnectionPool):
''' Socket HTTP Connection Pool ''' def __init__(self, url, timeout): self.timeout = urllib3.connectionpool.Timeout(connect=timeout[0], read=timeout[1]) super(HTTPConnectionPool, self).__init__('localhost', timeout=self.timeout) self.url = url def _new_conn(self): return HTT...
(url).netloc) self.timeout = timeout def connect(self): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.settimeout(self.timeout) sock.connect(self.path_socket) self.sock = sock class HTTPConnectionPool(urllib3.connectionpool.HTTPConnectionPool):
64
64
94
13
50
kenanpelit/archdocker
scripts/utils/unixconn.py
Python
HTTPConnectionPool
HTTPConnectionPool
26
34
26
26
3c921036e18773fc07a169ae4f7b58847b648001
bigcode/the-stack
train
3a451fc500c30491fc33f894
train
function
def url_format(path_socket, path, prefix='http+unix://'): ''' Format URL ''' return '{0:s}{1:s}{2:s}'.format(prefix, requests.compat.quote_plus(path_socket), path)
def url_format(path_socket, path, prefix='http+unix://'):
''' Format URL ''' return '{0:s}{1:s}{2:s}'.format(prefix, requests.compat.quote_plus(path_socket), path)
.timeout) def session(prefix='http+unix://', timeout_connect=31, timeout_read=181): ''' Requests session ''' sess = requests.Session() sess.mount(prefix, Adapter((timeout_connect, timeout_read))) return sess def url_format(path_socket, path, prefix='http+unix://'):
64
64
44
15
48
kenanpelit/archdocker
scripts/utils/unixconn.py
Python
url_format
url_format
54
56
54
54
dd955efd92b28a60edb073d9bef56fed9968f913
bigcode/the-stack
train
53610c57062370f815ff67e0
train
function
def session(prefix='http+unix://', timeout_connect=31, timeout_read=181): ''' Requests session ''' sess = requests.Session() sess.mount(prefix, Adapter((timeout_connect, timeout_read))) return sess
def session(prefix='http+unix://', timeout_connect=31, timeout_read=181):
''' Requests session ''' sess = requests.Session() sess.mount(prefix, Adapter((timeout_connect, timeout_read))) return sess
''' def __init__(self, timeout): self.timeout = timeout super(Adapter, self).__init__() def get_connection(self, url, proxies=None): return HTTPConnectionPool(url, self.timeout) def session(prefix='http+unix://', timeout_connect=31, timeout_read=181):
64
64
47
19
45
kenanpelit/archdocker
scripts/utils/unixconn.py
Python
session
session
47
51
47
47
2edfefc982e917cd0c318bf0d5336abf47abcbec
bigcode/the-stack
train
014f11e6e4a4530cc48fa55a
train
class
class Adapter(requests.adapters.HTTPAdapter): ''' Socket Adapter''' def __init__(self, timeout): self.timeout = timeout super(Adapter, self).__init__() def get_connection(self, url, proxies=None): return HTTPConnectionPool(url, self.timeout)
class Adapter(requests.adapters.HTTPAdapter):
''' Socket Adapter''' def __init__(self, timeout): self.timeout = timeout super(Adapter, self).__init__() def get_connection(self, url, proxies=None): return HTTPConnectionPool(url, self.timeout)
pool.Timeout(connect=timeout[0], read=timeout[1]) super(HTTPConnectionPool, self).__init__('localhost', timeout=self.timeout) self.url = url def _new_conn(self): return HTTPConnection(self.url, self.timeout.read_timeout) class Adapter(requests.adapters.HTTPAdapter):
64
64
57
8
56
kenanpelit/archdocker
scripts/utils/unixconn.py
Python
Adapter
Adapter
37
44
37
37
f733779e9a308d9b92acc7d2250e7a049f0a287b
bigcode/the-stack
train
fa2152c96438056eaa8df5e5
train
function
def error(response): ''' Return error ''' return { 'url': response.url, 'headers': dict(response.headers), 'encoding': response.encoding, 'status_code': response.status_code, 'ok': response.ok, 'reason': response.reason, 'elapsed': response.elapsed.total_seconds(), 'text': response.text,...
def error(response):
''' Return error ''' return { 'url': response.url, 'headers': dict(response.headers), 'encoding': response.encoding, 'status_code': response.status_code, 'ok': response.ok, 'reason': response.reason, 'elapsed': response.elapsed.total_seconds(), 'text': response.text, }
sess.mount(prefix, Adapter((timeout_connect, timeout_read))) return sess def url_format(path_socket, path, prefix='http+unix://'): ''' Format URL ''' return '{0:s}{1:s}{2:s}'.format(prefix, requests.compat.quote_plus(path_socket), path) def error(response):
64
64
70
4
60
kenanpelit/archdocker
scripts/utils/unixconn.py
Python
error
error
59
65
59
59
98c7ad8a4040f458c8a0d533822f4e87d9a7718b
bigcode/the-stack
train
33cb384c8806857632ec1a4e
train
class
class HTTPConnection(urllib3.connection.HTTPConnection): ''' Socket HTTP Connection ''' def __init__(self, url, timeout): super(HTTPConnection, self).__init__('localhost', timeout=timeout) self.path_socket = requests.compat.unquote(requests.compat.urlparse(url).netloc) self.timeout = tim...
class HTTPConnection(urllib3.connection.HTTPConnection):
''' Socket HTTP Connection ''' def __init__(self, url, timeout): super(HTTPConnection, self).__init__('localhost', timeout=timeout) self.path_socket = requests.compat.unquote(requests.compat.urlparse(url).netloc) self.timeout = timeout def connect(self): sock = socket.socket...
''' requests Unix socket connection ''' import socket import requests.adapters import urllib3 __all__ = ['session', 'url_format', 'error'] class HTTPConnection(urllib3.connection.HTTPConnection):
41
64
108
10
31
kenanpelit/archdocker
scripts/utils/unixconn.py
Python
HTTPConnection
HTTPConnection
12
23
12
12
c016c594639fbcbfa02af13379c4374bab806807
bigcode/the-stack
train
cce2b22f7ed9f4f1ad34bffd
train
function
def convert_examples_to_features(examples, label_list, max_seq_length, tokenizer): """Loads a data file into a list of `InputBatch`s.""" label_map = {label : i for i, label in enumerate(label_list)} features = [] for (ex_index, example) in enumerate(examples): tokens_a = tokenizer.tokenize(exa...
def convert_examples_to_features(examples, label_list, max_seq_length, tokenizer):
"""Loads a data file into a list of `InputBatch`s.""" label_map = {label : i for i, label in enumerate(label_list)} features = [] for (ex_index, example) in enumerate(examples): tokens_a = tokenizer.tokenize(example.text_a) tokens_b = None if example.text_b: tokens...
clsentiment' else [0, 1, 2, 3] class ColaProcessor(DataProcessor): """Processor for the CoLA data set (GLUE version).""" def get_train_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") d...
256
256
900
17
238
jfilter/masters-thesis
code/ynacc/10 bert/run_classifier.py
Python
convert_examples_to_features
convert_examples_to_features
227
306
227
227
9fef59f6aff72762dba4f377958b5338239a0ed2
bigcode/the-stack
train
687feea0be92329f3884755d
train
class
class DataProcessor(object): """Base class for data converters for sequence classification data sets.""" def get_train_examples(self, data_dir): """Gets a collection of `InputExample`s for the train set.""" raise NotImplementedError() def get_dev_examples(self, data_dir): """Gets a...
class DataProcessor(object):
"""Base class for data converters for sequence classification data sets.""" def get_train_examples(self, data_dir): """Gets a collection of `InputExample`s for the train set.""" raise NotImplementedError() def get_dev_examples(self, data_dir): """Gets a collection of `InputExample`...
A single set of features of data.""" def __init__(self, input_ids, input_mask, segment_ids, label_id): self.input_ids = input_ids self.input_mask = input_mask self.segment_ids = segment_ids self.label_id = label_id class DataProcessor(object):
64
64
186
5
58
jfilter/masters-thesis
code/ynacc/10 bert/run_classifier.py
Python
DataProcessor
DataProcessor
79
102
79
79
f53cb403ea9cfc32a9281b7d02b5b4afd628dd15
bigcode/the-stack
train
50b87246d9e3b3173ec1df8c
train
class
class InputExample(object): """A single training/test example for simple sequence classification.""" def __init__(self, guid, text_a, text_b=None, label=None): """Constructs a InputExample. Args: guid: Unique id for the example. text_a: string. The untokenized text of t...
class InputExample(object):
"""A single training/test example for simple sequence classification.""" def __init__(self, guid, text_a, text_b=None, label=None): """Constructs a InputExample. Args: guid: Unique id for the example. text_a: string. The untokenized text of the first sequence. For singl...
ERT_CACHE logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt = '%m/%d/%Y %H:%M:%S', level = logging.INFO) logger = logging.getLogger(__name__) class InputExample(object):
64
64
177
5
59
jfilter/masters-thesis
code/ynacc/10 bert/run_classifier.py
Python
InputExample
InputExample
48
66
48
48
304a9d92cd586131afbb38051f1a84f21c867054
bigcode/the-stack
train
c0cd28c624e1dac3e28dc13e
train
function
def _truncate_seq_pair(tokens_a, tokens_b, max_length): """Truncates a sequence pair in place to the maximum length.""" # This is a simple heuristic which will always truncate the longer sequence # one token at a time. This makes more sense than truncating an equal percent # of tokens from each, since ...
def _truncate_seq_pair(tokens_a, tokens_b, max_length):
"""Truncates a sequence pair in place to the maximum length.""" # This is a simple heuristic which will always truncate the longer sequence # one token at a time. This makes more sense than truncating an equal percent # of tokens from each, since if one sequence is very short then each token # that...
(id = %d)" % (example.label, label_id)) features.append( InputFeatures(input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids, label_id=label_id)) return features def _truncate_seq_pair(t...
64
64
146
14
49
jfilter/masters-thesis
code/ynacc/10 bert/run_classifier.py
Python
_truncate_seq_pair
_truncate_seq_pair
309
323
309
309
9995435b6f0f9e8b55affc060dc9d3a9604f03f3
bigcode/the-stack
train
16425f650a70d1cd87f0b475
train
class
class MnliProcessor(DataProcessor): """Processor for the MultiNLI data set (GLUE version).""" def get_train_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") def get_dev_examples(self, dat...
class MnliProcessor(DataProcessor):
"""Processor for the MultiNLI data set (GLUE version).""" def get_train_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") def get_dev_examples(self, data_dir): """See base class.""...
continue guid = "%s-%s" % (set_type, i) text_a = line[3] text_b = line[4] label = line[0] examples.append( InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) return examples class MnliProcessor(DataProcessor):
77
77
257
7
69
jfilter/masters-thesis
code/ynacc/10 bert/run_classifier.py
Python
MnliProcessor
MnliProcessor
138
168
138
138
b9a2f3ed3bde937b495dd614ce231c9a3c30ff6a
bigcode/the-stack
train
d63765e89931a80831ad1887
train
class
class InputFeatures(object): """A single set of features of data.""" def __init__(self, input_ids, input_mask, segment_ids, label_id): self.input_ids = input_ids self.input_mask = input_mask self.segment_ids = segment_ids self.label_id = label_id
class InputFeatures(object):
"""A single set of features of data.""" def __init__(self, input_ids, input_mask, segment_ids, label_id): self.input_ids = input_ids self.input_mask = input_mask self.segment_ids = segment_ids self.label_id = label_id
(Optional) string. The label of the example. This should be specified for train and dev examples, but not for test examples. """ self.guid = guid self.text_a = text_a self.text_b = text_b self.label = label class InputFeatures(object):
64
64
66
5
58
jfilter/masters-thesis
code/ynacc/10 bert/run_classifier.py
Python
InputFeatures
InputFeatures
69
76
69
69
48b09f13b0660472b231cbb42247d2189808a155
bigcode/the-stack
train
877fa6eb311def9e3a9ba729
train
function
def main(): parser = argparse.ArgumentParser() ## Required parameters parser.add_argument("--data_dir", default=None, type=str, required=True, help="The input data dir. Should contain the .tsv files (or other da...
def main():
parser = argparse.ArgumentParser() ## Required parameters parser.add_argument("--data_dir", default=None, type=str, required=True, help="The input data dir. Should contain the .tsv files (or other data files) fo...
% (example.label, label_id)) features.append( InputFeatures(input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids, label_id=label_id)) return features def _truncate_seq_pair(tokens_a, ...
256
256
3,193
3
252
jfilter/masters-thesis
code/ynacc/10 bert/run_classifier.py
Python
main
main
334
667
334
334
f477bd86bc30f718a2616c36e51b9f15b3bae594
bigcode/the-stack
train
3ed98546a9c8d2b986a46f0e
train
function
def accuracy(out, labels): outputs = np.argmax(out, axis=1) return np.sum(outputs == labels), outputs
def accuracy(out, labels):
outputs = np.argmax(out, axis=1) return np.sum(outputs == labels), outputs
information than a longer sequence. while True: total_length = len(tokens_a) + len(tokens_b) if total_length <= max_length: break if len(tokens_a) > len(tokens_b): tokens_a.pop() else: tokens_b.pop() def accuracy(out, labels):
64
64
27
6
58
jfilter/masters-thesis
code/ynacc/10 bert/run_classifier.py
Python
accuracy
accuracy
325
327
325
325
8f2247b27f200d083ba837565acf062fae0feb87
bigcode/the-stack
train
2135a8ab524be0f8fe59538d
train
class
class YnaccProcessor(DataProcessor): def __init__(self, cls_idx): all_classes = ['claudience', 'clpersuasive', 'clagreement', 'cldisagreement', 'clinformative', 'clmean', 'clcontroversial', 'cltopic', 'clsentiment'] self.ynlabel = all_classes[cls_idx] def _create_examples(self, df): ex...
class YnaccProcessor(DataProcessor):
def __init__(self, cls_idx): all_classes = ['claudience', 'clpersuasive', 'clagreement', 'cldisagreement', 'clinformative', 'clmean', 'clcontroversial', 'cltopic', 'clsentiment'] self.ynlabel = all_classes[cls_idx] def _create_examples(self, df): examples = [] for i, row in df.i...
for (i, line) in enumerate(lines): if i == 0: continue guid = "%s-%s" % (set_type, line[0]) text_a = line[8] text_b = line[9] label = line[-1] examples.append( InputExample(guid=guid, text_a=text_a, text_b=te...
98
98
329
7
90
jfilter/masters-thesis
code/ynacc/10 bert/run_classifier.py
Python
YnaccProcessor
YnaccProcessor
170
195
170
171
da0a582aa4958da7226276aa6711a7200e13829e
bigcode/the-stack
train
bb5908d7f111669ce69ce441
train
class
class MrpcProcessor(DataProcessor): """Processor for the MRPC data set (GLUE version).""" def get_train_examples(self, data_dir): """See base class.""" logger.info("LOOKING AT {}".format(os.path.join(data_dir, "train.tsv"))) return self._create_examples( self._read_tsv(os.pa...
class MrpcProcessor(DataProcessor):
"""Processor for the MRPC data set (GLUE version).""" def get_train_examples(self, data_dir): """See base class.""" logger.info("LOOKING AT {}".format(os.path.join(data_dir, "train.tsv"))) return self._create_examples( self._read_tsv(os.path.join(data_dir, "train.tsv")), "tr...
, input_file, quotechar=None): """Reads a tab separated value file.""" with open(input_file, "r", encoding='utf-8') as f: reader = csv.reader(f, delimiter="\t", quotechar=quotechar) lines = [] for line in reader: lines.append(line) return l...
78
78
261
7
70
jfilter/masters-thesis
code/ynacc/10 bert/run_classifier.py
Python
MrpcProcessor
MrpcProcessor
105
135
105
105
045af037699f350370e99adf6329c6465e0b9839
bigcode/the-stack
train
209d2b32218b55b3f30c1203
train
function
def warmup_linear(x, warmup=0.002): if x < warmup: return x/warmup return 1.0 - x
def warmup_linear(x, warmup=0.002):
if x < warmup: return x/warmup return 1.0 - x
if len(tokens_a) > len(tokens_b): tokens_a.pop() else: tokens_b.pop() def accuracy(out, labels): outputs = np.argmax(out, axis=1) return np.sum(outputs == labels), outputs def warmup_linear(x, warmup=0.002):
64
64
36
13
50
jfilter/masters-thesis
code/ynacc/10 bert/run_classifier.py
Python
warmup_linear
warmup_linear
329
332
329
329
b27181f005baf28a16503be8c93bed33082a70ff
bigcode/the-stack
train
ded56b23336af462beca138d
train
class
class ColaProcessor(DataProcessor): """Processor for the CoLA data set (GLUE version).""" def get_train_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") def get_dev_examples(self, data_di...
class ColaProcessor(DataProcessor):
"""Processor for the CoLA data set (GLUE version).""" def get_train_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") def get_dev_examples(self, data_dir): """See base class.""" ...
df = df.dropna(subset=[self.ynlabel]) return self._create_examples(df) def get_labels(self): return [0, 1] if self.ynlabel != 'clsentiment' else [0, 1, 2, 3] class ColaProcessor(DataProcessor):
66
66
222
6
60
jfilter/masters-thesis
code/ynacc/10 bert/run_classifier.py
Python
ColaProcessor
ColaProcessor
198
224
198
198
f91a6384309ef2f365101b5c91cb56780e41701f
bigcode/the-stack
train
d0e58f00656d3876f8d88fae
train
class
class PhobertTokenizationTest(TokenizerTesterMixin, unittest.TestCase): tokenizer_class = PhobertTokenizer test_rust_tokenizer = False def setUp(self): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt vocab = ["T@@", "i", "I", "R@@",...
class PhobertTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
tokenizer_class = PhobertTokenizer test_rust_tokenizer = False def setUp(self): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt vocab = ["T@@", "i", "I", "R@@", "r", "e@@"] vocab_tokens = dict(zip(vocab, range(len(vocab)))) ...
the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is dis...
172
172
576
16
155
bugface/transformers
tests/models/phobert/test_tokenization_phobert.py
Python
PhobertTokenizationTest
PhobertTokenizationTest
24
67
24
25
68b57ea3cc88c88e0b7045aa37e546443a42c546
bigcode/the-stack
train
4a6452c66756a1c245668cca
train
class
class ReferencesWithWebApplicationIDLink(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. ...
class ReferencesWithWebApplicationIDLink(object):
"""NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name ...
format/#document-links\">\"Link Object\"</a> and <a target=\"_blank\" href=\"http://json-schema.org/latest/json-schema-hypermedia.html\">JSON Hyper-Schema</a> <a target=\"_blank\" href=\"http://json-schema.org/latest/json-schema-hypermedia.html#rfc.section.5.2\">\"Link Description Object\"</a> formats. For example: ...
250
250
834
9
240
pdeardorff-r7/vm-console-client-python
rapid7vmconsole/models/references_with_web_application_id_link.py
Python
ReferencesWithWebApplicationIDLink
ReferencesWithWebApplicationIDLink
22
144
22
22
26ab80236394824071c7b698d32976f73174c9c6
bigcode/the-stack
train
d1c2195ef4272a2ea5d1e916
train
class
class TestAnimalDummy(unittest.TestCase): def setUp(self): self.animal_data = { 'name': 'Doggy', 'id': 'uniqueid', 'since': '2017.03.18', 'category': ['dog'], 'photos': ['photo1', 'photo2'], 'description': ['line1', 'line2'], ...
class TestAnimalDummy(unittest.TestCase):
def setUp(self): self.animal_data = { 'name': 'Doggy', 'id': 'uniqueid', 'since': '2017.03.18', 'category': ['dog'], 'photos': ['photo1', 'photo2'], 'description': ['line1', 'line2'], 'url': 'http://example.org', ...
import pickle import unittest from unittest import mock from lapka.models import AnimalDummy class TestAnimalDummy(unittest.TestCase):
27
76
254
8
18
glujan/lapka
tests/unit/test_models.py
Python
TestAnimalDummy
TestAnimalDummy
9
43
9
9
52e28ebef841723d2e94ccca744f52ab475439ee
bigcode/the-stack
train
b8a32189ad41d66c9397f33e
train
class
class TestAnimalDummyLoad(unittest.TestCase): def setUp(self): self.data = ['sample', 'data'] def test__load(self): pickled = pickle.dumps(self.data) with mock.patch('builtins.open', mock.mock_open(read_data=pickled)) as m_open: data = AnimalDummy._load() self.as...
class TestAnimalDummyLoad(unittest.TestCase):
def setUp(self): self.data = ['sample', 'data'] def test__load(self): pickled = pickle.dumps(self.data) with mock.patch('builtins.open', mock.mock_open(read_data=pickled)) as m_open: data = AnimalDummy._load() self.assertListEqual(data, self.data) m_o...
) self.animal.remove() result = AnimalDummy.find(self.animal.a_id) self.assertEqual(result, None) def test_to_dict(self): data = self.animal.to_dict() self.assertDictEqual(data, self.animal_data) class TestAnimalDummyLoad(unittest.TestCase):
64
64
142
9
55
glujan/lapka
tests/unit/test_models.py
Python
TestAnimalDummyLoad
TestAnimalDummyLoad
46
61
46
46
60da8e12a830985a844cde287fc663abf0a3c5e4
bigcode/the-stack
train
f5da09e1c23492f7aa4b9c35
train
class
class LegendgroupValidator(_plotly_utils.basevalidators.StringValidator): def __init__( self, plotly_name='legendgroup', parent_name='candlestick', **kwargs ): super(LegendgroupValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_...
class LegendgroupValidator(_plotly_utils.basevalidators.StringValidator):
def __init__( self, plotly_name='legendgroup', parent_name='candlestick', **kwargs ): super(LegendgroupValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop('edit_type', 'style'), role=kwargs.pop('role', ...
import _plotly_utils.basevalidators class LegendgroupValidator(_plotly_utils.basevalidators.StringValidator):
21
64
97
13
7
gnestor/plotly.py
plotly/validators/candlestick/_legendgroup.py
Python
LegendgroupValidator
LegendgroupValidator
4
15
4
5
7a7b9af90f0abff422d9f2f31f52720394a3fda3
bigcode/the-stack
train
1d8e58f8d8f20c5a6476334d
train
function
def test_tourism(dirpath): # Eurostat # Employed doctorate holders in non managerial and non professional # occupations by fields of science (%) dsd = _read_sdmx_dsd(os.path.join(dirpath, "sdmx", "DSD_cdh_e_fos.xml")) df = read_sdmx(os.path.join(dirpath, "sdmx", "cdh_e_fos.xml"), dsd=dsd) asser...
def test_tourism(dirpath): # Eurostat # Employed doctorate holders in non managerial and non professional # occupations by fields of science (%)
dsd = _read_sdmx_dsd(os.path.join(dirpath, "sdmx", "DSD_cdh_e_fos.xml")) df = read_sdmx(os.path.join(dirpath, "sdmx", "cdh_e_fos.xml"), dsd=dsd) assert isinstance(df, pd.DataFrame) assert df.shape == (2, 336) df = df["Percentage"]["Total"]["Natural sciences"] df = df[["Norway", "Poland", "Port...
_datareader.io.sdmx import _read_sdmx_dsd, read_sdmx pytestmark = pytest.mark.stable @pytest.fixture def dirpath(datapath): return datapath("io", "data") def test_tourism(dirpath): # Eurostat # Employed doctorate holders in non managerial and non professional # occupations by fields of science (%)
83
83
278
35
48
iVibudh/stock-prediction
email-updates-stonks-AI-ML/venv/Lib/site-packages/pandas_datareader/tests/io/test_sdmx.py
Python
test_tourism
test_tourism
20
40
20
23
50c9994d42eb41f8f316dd06a144f24b20a26cec
bigcode/the-stack
train
43c38be71cc264f0c7cd2a66
train
function
@pytest.fixture def dirpath(datapath): return datapath("io", "data")
@pytest.fixture def dirpath(datapath):
return datapath("io", "data")
import os import numpy as np import pandas as pd import pandas.util.testing as tm import pytest from pandas_datareader.io.sdmx import _read_sdmx_dsd, read_sdmx pytestmark = pytest.mark.stable @pytest.fixture def dirpath(datapath):
64
64
20
10
53
iVibudh/stock-prediction
email-updates-stonks-AI-ML/venv/Lib/site-packages/pandas_datareader/tests/io/test_sdmx.py
Python
dirpath
dirpath
15
17
15
16
80a18545c0072720852983a6de03bb8795d2245e
bigcode/the-stack
train
04cb768d224c60552fd4627d
train
class
class Reduced_MVP12(RawDatasetLoader): def __init__(self, file_name, is_train=True): super(Reduced_MVP12, self).__init__(file_name) self.is_train = is_train complete_indices = self.get_indices(is_complete=True) indices = self.get_indices(is_complete=False) self.incomplete_p...
class Reduced_MVP12(RawDatasetLoader):
def __init__(self, file_name, is_train=True): super(Reduced_MVP12, self).__init__(file_name) self.is_train = is_train complete_indices = self.get_indices(is_complete=True) indices = self.get_indices(is_complete=False) self.incomplete_pcds = np.array(self.incomplete_pcds) ...
import h5py import numpy as np from pathlib import Path from src.dataset.partition import RawDatasetLoader PROJECT_ROOT = Path("/home/goda/Undergraduate/capstone_design_base") # REDUCED CATEGORIES 0 / 12 / 14 / 15 class Reduced_MVP12(RawDatasetLoader):
69
256
967
10
58
GoDa-Choe/capstone_design
src/dataset/reduce_category.py
Python
Reduced_MVP12
Reduced_MVP12
13
94
13
13
57605d2193c39c818813ce74232fffeb2cb7798a
bigcode/the-stack
train
d2234cd3e8a8f62a0656fd91
train
class
@ddt class QueryTest(bq_test_case.BQTestCase): @classmethod def setUpClass(cls): """Set up class.""" super(QueryTest, cls).setUpClass(use_mocks=False) cls.sql_to_test = open( os.path.join(os.path.dirname(os.path.realpath(__file__)), SQL_TEMPLATE), "r").read() @classmetho...
@ddt class QueryTest(bq_test_case.BQTestCase): @classmethod
def setUpClass(cls): """Set up class.""" super(QueryTest, cls).setUpClass(use_mocks=False) cls.sql_to_test = open( os.path.join(os.path.dirname(os.path.realpath(__file__)), SQL_TEMPLATE), "r").read() @classmethod def create_mock_tables(cls): """Create mock tables.""" ...
"""Tests for query most_recent_measurement_of_interest.sql. See https://github.com/verilylifesciences/analysis-py-utils for more details about the testing framework. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from datetime import date from datetim...
133
256
1,101
20
113
kouamea/workbench-snippets
snippets/most_recent_measurement_of_interest_test.py
Python
QueryTest
QueryTest
22
109
22
25
f0865f3b1d25da3391c3895fa1e258a87cae07e0
bigcode/the-stack
train
11d35140c6fc4052a7cf5880
train
function
def psycopg2_type_as_string(type_id): type_ = string_types.get(type_id) return type_.name if type_ else 'unknown'
def psycopg2_type_as_string(type_id):
type_ = string_types.get(type_id) return type_.name if type_ else 'unknown'
from psycopg2.extensions import string_types def psycopg2_type_as_string(type_id):
21
64
33
11
9
Rovaro/Longitude
longitude/core/data_sources/postgres/common.py
Python
psycopg2_type_as_string
psycopg2_type_as_string
4
6
4
4
e843204e7f332efa9aad5d4fdf047296793ebfd3
bigcode/the-stack
train
33eb6aba39d27c0abd3c44bc
train
class
class PolicySet(PolicyBase): """XACML Policy Set @cvar DEFAULT_XACML_VERSION: default is 2.0 @type DEFAULT_XACML_VERSION: string @cvar ELEMENT_LOCAL_NAME: XML local name for this element @type ELEMENT_LOCAL_NAME: string @cvar POLICY_SET_ID_ATTRIB_NAME: policy set id XML attribute name @...
class PolicySet(PolicyBase):
"""XACML Policy Set @cvar DEFAULT_XACML_VERSION: default is 2.0 @type DEFAULT_XACML_VERSION: string @cvar ELEMENT_LOCAL_NAME: XML local name for this element @type ELEMENT_LOCAL_NAME: string @cvar POLICY_SET_ID_ATTRIB_NAME: policy set id XML attribute name @type POLICY_SET_ID_ATTRIB_NAM...
"""NDG Security Policy Set type definition NERC DataGrid """ __author__ = "R B Wilkinson" __date__ = "01/11/11" __copyright__ = "(C) 2011 Science and Technology Facilities Council" __contact__ = "Philip.Kershaw@stfc.ac.uk" __license__ = "BSD - see LICENSE file in top-level directory" __contact__ = "Philip.Kershaw@stfc...
245
256
3,135
7
238
philipkershaw/ndg_xacml
ndg/xacml/core/policyset.py
Python
PolicySet
PolicySet
28
390
28
28
c071e578b5c9ee80c60a2df58446bf1cf00ab9e9
bigcode/the-stack
train
683a99e8138c4f80a4512243
train
function
def train(args, model, device, train_loader, optimizer, epoch, digit): model.train() criterion = nn.CrossEntropyLoss() for batch_idx, (data, target) in enumerate(train_loader): data, target = data.reshape(-1, resize * resize).to(device), target.to( device ) # for fc input layer ...
def train(args, model, device, train_loader, optimizer, epoch, digit):
model.train() criterion = nn.CrossEntropyLoss() for batch_idx, (data, target) in enumerate(train_loader): data, target = data.reshape(-1, resize * resize).to(device), target.to( device ) # for fc input layer # data, target = data.to(device), target.to(device) # for conv ...
.relu(x_prop) x_prop = self.fc2_prop(x_prop) x_prop = F.relu(x_prop) # x_prop = self.fc3_prop(x_prop) # x_prop = F.relu(x_prop) x_prop = self.fc_output_prop(x_prop) output_prop = x_prop return output, output_prop def train(args, model, device, train_loader, optim...
88
88
295
17
70
LebronX/Neuro-Symbolic-Verification
src/mnist/mnist_digit_training.py
Python
train
train
64
96
64
64
fe9af38ac098dafba062f27c000306373bc58f8e
bigcode/the-stack
train
45b76727ad682fc5b6c29ad4
train
function
def main(): # Training settings parser = argparse.ArgumentParser(description="PyTorch MNIST Example") parser.add_argument( "--batch-size", type=int, default=100, metavar="N", help="input batch size for training (default: 100)", ) parser.add_argument( "...
def main(): # Training settings
parser = argparse.ArgumentParser(description="PyTorch MNIST Example") parser.add_argument( "--batch-size", type=int, default=100, metavar="N", help="input batch size for training (default: 100)", ) parser.add_argument( "--test-batch-size", type=int...
property property_list = [1 if item == digit else 0 for item in target] target_eight_tensor = torch.Tensor(property_list).long() test_loss_prop += criterion( output_prop, target_eight_tensor ).item() # sum up property nn loss pred_prop = out...
256
256
866
8
248
LebronX/Neuro-Symbolic-Verification
src/mnist/mnist_digit_training.py
Python
main
main
154
278
154
155
fce6b1c5e4470c69154c824d5c08bbbe5927e1b5
bigcode/the-stack
train
8dbd545a5f7a9c37d88dac52
train
class
class DigitNet(nn.Module): def __init__(self): super(DigitNet, self).__init__() self.fc_input = nn.Linear(resize * resize, 10) self.fc1 = nn.Linear(10, 10) # 3*10/15: 4 sec, 3*20: > 5 hr, 4*10: > 1 hr self.fc2 = nn.Linear(10, 10) # self.fc3 = nn.Linear(10, 10) # self...
class DigitNet(nn.Module):
def __init__(self): super(DigitNet, self).__init__() self.fc_input = nn.Linear(resize * resize, 10) self.fc1 = nn.Linear(10, 10) # 3*10/15: 4 sec, 3*20: > 5 hr, 4*10: > 1 hr self.fc2 = nn.Linear(10, 10) # self.fc3 = nn.Linear(10, 10) # self.fc4 = nn.Linear(10, 10) ...
from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from torch.optim.lr_scheduler import StepLR import matplotlib.pyplot as plt device = torch.device("cuda" if torch.cuda.is_ava...
89
134
447
6
82
LebronX/Neuro-Symbolic-Verification
src/mnist/mnist_digit_training.py
Python
DigitNet
DigitNet
16
61
16
16
05be0935b7868e41c725c14dbb28d69879048ae1
bigcode/the-stack
train
51062a891ba0c6d89b9271ab
train
function
def test(model, device, test_loader, digit): model.eval() test_loss = 0 correct = 0 test_loss_prop = 0 correct_prop = 0 criterion = nn.CrossEntropyLoss(reduction="sum").to(device) with torch.no_grad(): for data, target in test_loader: data, target = data.reshape(-1, resiz...
def test(model, device, test_loader, digit):
model.eval() test_loss = 0 correct = 0 test_loss_prop = 0 correct_prop = 0 criterion = nn.CrossEntropyLoss(reduction="sum").to(device) with torch.no_grad(): for data, target in test_loader: data, target = data.reshape(-1, resize * resize).to(device), target.to( ...
_prop = criterion(output_prop, target_eight_tensor) loss = loss_prop + loss_nnv # total sum of loss loss.backward() optimizer.step() if batch_idx % args.log_interval == 0: print( "Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}".format( e...
133
133
446
11
121
LebronX/Neuro-Symbolic-Verification
src/mnist/mnist_digit_training.py
Python
test
test
99
151
99
99
49aae5275eafe11fc3b63f6038390caa249a8250
bigcode/the-stack
train
249980405be12ce6476dba97
train
class
class PrivateTagsApiTests(TestCase): """Test the authorized user tags API""" def setUp(self): self.user = get_user_model().objects.create_user( 'test@morrissp.com', 'password123' ) self.client = APIClient() self.client.force_authenticate(self.user) d...
class PrivateTagsApiTests(TestCase):
"""Test the authorized user tags API""" def setUp(self): self.user = get_user_model().objects.create_user( 'test@morrissp.com', 'password123' ) self.client = APIClient() self.client.force_authenticate(self.user) def test_retrieve_tags(self): ...
from django.contrib.auth import get_user_model from django.urls import reverse from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient from core.models import Tag, Recipe from recipe.serializers import TagSerializer TAGS_URL = reverse('recipe:tag-list') class P...
144
216
723
8
136
morrissp2/recipe-app-api
app/recipe/tests/test_tags_api.py
Python
PrivateTagsApiTests
PrivateTagsApiTests
28
126
28
28
401ed572c7e70037b380e46ab2f29412d936ccd3
bigcode/the-stack
train
c69b4961d036382a74ed8b42
train
class
class PublicTagsApiTests(TestCase): """Test the publicly available tags API""" def setUp(self): self.client = APIClient() def test_login_required(self): """Test that login is required for retrieving tags""" res = self.client.get(TAGS_URL) self.assertEqual(res.status_code, ...
class PublicTagsApiTests(TestCase):
"""Test the publicly available tags API""" def setUp(self): self.client = APIClient() def test_login_required(self): """Test that login is required for retrieving tags""" res = self.client.get(TAGS_URL) self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
_model from django.urls import reverse from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient from core.models import Tag, Recipe from recipe.serializers import TagSerializer TAGS_URL = reverse('recipe:tag-list') class PublicTagsApiTests(TestCase):
64
64
73
8
56
morrissp2/recipe-app-api
app/recipe/tests/test_tags_api.py
Python
PublicTagsApiTests
PublicTagsApiTests
15
25
15
15
c25510fc2b879297a66af0e93078e9758ca22a41
bigcode/the-stack
train