code stringlengths 281 23.7M |
|---|
def string_token_to_bytes(token: Token) -> Union[(Token, bytes)]:
if (isinstance(token, Token) and (token.type == 'STRING')):
bstring = token.value[1:(- 1)]
buffer = []
it = StringIterator(bstring)
for c in it:
if ((c == '\\') and it.has_next()):
next2 = n... |
.parametrize('django_elasticapm_client', [{'capture_body': 'errors'}, {'capture_body': 'transactions'}, {'capture_body': 'all'}, {'capture_body': 'off'}], indirect=True)
def test_capture_empty_body(client, django_elasticapm_client):
with pytest.raises(MyException):
client.post(reverse('elasticapm-raise-exc'... |
class AbstractIndexManager(ABCHasStrictTraits):
def create_index(self, parent, row):
raise NotImplementedError()
def get_parent_and_row(self, index):
raise NotImplementedError()
def from_sequence(self, indices):
index = Root
for row in indices:
index = self.create... |
def first(predicate=None, defaultValue=None):
if (defaultValue is None):
if (predicate is not None):
return JsUtils.jsWrap(('%sfirst(%s)' % (LIB_REF, predicate)))
return JsUtils.jsWrap(('%sfirst()' % LIB_REF))
defaultValue = JsUtils.jsConvertData(defaultValue, None)
return JsUtil... |
class OptionPlotoptionsVenn(Options):
def accessibility(self) -> 'OptionPlotoptionsVennAccessibility':
return self._config_sub_data('accessibility', OptionPlotoptionsVennAccessibility)
def allowPointSelect(self):
return self._config_get(False)
def allowPointSelect(self, flag: bool):
... |
class RequestDispatcher(Dispatcher):
__slots__ = ['response_builder']
def __init__(self, route, rule, response_builder):
super().__init__(route)
self.response_builder = response_builder
async def dispatch(self, reqargs, response):
return self.response_builder((await self.f(**reqargs)... |
class OptionSeriesPieSonificationTracksMappingTremolo(Options):
def depth(self) -> 'OptionSeriesPieSonificationTracksMappingTremoloDepth':
return self._config_sub_data('depth', OptionSeriesPieSonificationTracksMappingTremoloDepth)
def speed(self) -> 'OptionSeriesPieSonificationTracksMappingTremoloSpeed'... |
def test_DataclassTransformer_to_python_value():
class MyDataClassMashumaro(DataClassJsonMixin):
x: int
_json
class MyDataClass():
x: int
de = DataclassTransformer()
json_str = '{ "x" : 5 }'
mock_literal = Literal(scalar=Scalar(generic=_json_format.Parse(json_str, _struct.Struct(... |
class OptionSeriesVariablepieSonificationTracksMappingVolume(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
sel... |
class ChartJsOptTicks(DataAttrs):
def beginAtZero(self, flag: Union[(bool, primitives.JsDataModel)]):
self._attrs['beginAtZero'] = JsUtils.jsConvertData(flag, None)
return self
def display(self, flag: Union[(bool, primitives.JsDataModel)]):
self._attrs['display'] = JsUtils.jsConvertData(... |
class Solution():
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
def construct(preorder, idx, inorder, start, end):
if (start > end):
return None
node = TreeNode(preorder[idx])
i = (inorder[start:(end + 1)].index(preorder[idx]) +... |
class UIWrapper():
def __init__(self, target, *, registries, delay=0, auto_process_events=True):
self._target = target
self._registries = registries
self._auto_process_events = auto_process_events
self.delay = delay
def help(self):
interaction_to_doc = dict()
loca... |
class TestBackend(ErrBot):
def change_presence(self, status: str=ONLINE, message: str='') -> None:
pass
def __init__(self, config):
config.BOT_LOG_LEVEL = logging.DEBUG
config.CHATROOM_PRESENCE = ('testroom',)
config.BOT_IDENTITY = {'username': 'err'}
self.bot_identifier ... |
def clear_all_regions():
for window in sublime.windows():
for view in window.views():
for region_key in view.settings().get('bracket_highlighter.regions', []):
view.erase_regions(region_key)
view.settings().set('bracket_highlighter.locations', {'open': {}, 'close': {}... |
def get_test_cls(cls):
cls_instances = list(classes[cls])
ids = [('%s.%s::%s' % (mod, cls, i['tag'])) for (_, i, cls, mod) in cls_instances]
.parametrize(('instance', 'i_data', 'cls', 'mod'), cls_instances, ids=ids)
class TestWrap(BaseInstanceTest):
pass
name = ('Test%s' % cls)
return ty... |
def prod_tile(p, i_tile=32, j_tile=32):
p = inline(p, 'producer(_)')
p = inline(p, 'consumer(_)')
p = tile(p, 'g', 'i', 'j', ['io', 'ii'], ['jo', 'ji'], i_tile, j_tile, perfect=True)
p = simplify(p)
loop = p.find_loop('io')
p = fuse_at(p, 'f', 'g', loop)
loop = p.find_loop('jo')
p = fuse... |
class HashEngine(object):
def __init__(self, inputQueue, outputQueue, threads=2, pHash=True, integrity=True):
self.log = logging.getLogger('Main.HashEngine')
self.tlog = logging.getLogger('Main.HashEngineThread')
self.hashWorkers = threads
self.inQ = inputQueue
self.outQ = ou... |
def test_unit(rel_path='.'):
try:
import pytest
except ImportError:
sys.exit('Cannot do unit tests, pytest not installed')
py2 = (sys.version_info[0] == 2)
rel_path = (('flexx_legacy/' + rel_path) if py2 else ('flexx/' + rel_path))
test_path = os.path.join(ROOT_DIR, rel_path)
if ... |
class TestUnit(unittest.TestCase):
def test_record_soh(self):
get_new_test_db()
car = vehicule_list[0]
soh_list = [99.0, 96.0, 90.2]
for x in range(len(soh_list)):
Database.record_battery_soh(car.vin, get_date(x), soh_list[x])
compare_dict(vars(BatterySoh(car.vin,... |
class CompositeRaceStore():
def __init__(self, es_store, file_store):
self.es_store = es_store
self.file_store = file_store
def find_by_race_id(self, race_id):
return self.es_store.find_by_race_id(race_id)
def store_race(self, race):
self.file_store.store_race(race)
s... |
def get_deleted_fpds_data_from_s3(date):
ids_to_delete = []
regex_str = '.*_delete_records_(IDV|award).*'
if (not date):
return []
if settings.IS_LOCAL:
for file in os.listdir(settings.CSV_LOCAL_PATH):
if (re.search(regex_str, file) and (datetime.strptime(file[:file.find('_')... |
class TraitSheetApp(wx.App):
def __init__(self, object):
self.object = object
wx.InitAllImageHandlers()
wx.App.__init__(self, 1, 'debug.log')
self.MainLoop()
def OnInit(self):
ui = self.object.edit_traits(kind='live')
ui = self.object.edit_traits(kind='modal')
... |
class test(testing.TestCase):
def test_torque(self):
args = main(rotation=1.0, increment=1.0, elemsize=1.0, poisson=0.25)
self.assertAlmostEqual64(args['u'], '\n eNoN0stLE3AcAHAC58Ieq9SDh8Z87ffcQrCQJBcVJFMKKUzaQSExeihKFzvEwsBU6GJlJCYpLCQKLXQY\n VjazmHWI7ff4/rYx3Tx4CSotw2lQff6Gz... |
def openflags_to_symbols(openflags):
open_symbols = []
flags = OrderedDict([('O_WRONLY', 1), ('O_RDWR', 2), ('O_CREAT', 64), ('O_EXCL', 128), ('O_NOCTTY', 256), ('O_TRUNC', 512), ('O_APPEND', 1024), ('O_NONBLOCK', 2048), ('O_DSYNC', 4096), ('O_ASYNC', 8192), ('O_DIRECT', 16384), ('O_DIRECTORY', 65536), ('O_NOFO... |
def gen_function_src(sorted_graph: List[Tensor], workdir: str, model_name: str='') -> List[Tuple[(str, str)]]:
target = Target.current()
file_pairs = []
exist_func = set()
prefix = os.path.join(workdir, model_name)
for node in sorted_graph:
for func in node.src_ops():
fname = fun... |
class PDFNum(PDFObject):
def __init__(self, s):
PDFObject.__init__(self)
self.s = s
def __str__(self):
sign = ''
if (random.randint(0, 100) > 50):
if (self.s > 0):
sign = '+'
elif (self.s < 0):
sign = '-'
elif (r... |
class CouncilAgenda(Base):
__tablename__ = 'council_agenda'
agenda_id = Column(Integer, primary_key=True)
country_id = Column(ForeignKey(Country.country_id), nullable=False, index=True)
start_date = Column(Integer)
launch_date = Column(Integer)
cooldown_date = Column(Integer)
is_resolved = C... |
class Solution():
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
def subtree_with_deepest(node):
if (node is None):
return (node, 0)
(lt, ll) = subtree_with_deepest(node.left)
(rt, rl) = subtree_with_deepest(node.right)
if (ll == ... |
def upgrade():
op.execute("ALTER TABLE image_sizes ALTER full_aspect TYPE boolean USING CASE full_aspect WHEN 'on' THEN TRUE ELSE FALSE END", execution_options=None)
op.execute("ALTER TABLE image_sizes ALTER icon_aspect TYPE boolean USING CASE icon_aspect WHEN 'on' THEN TRUE ELSE F... |
def get_result_formatters(method_name: Union[(RPCEndpoint, Callable[(..., RPCEndpoint)])], module: 'Module') -> Dict[(str, Callable[(..., Any)])]:
formatters = combine_formatters((PYTHONIC_RESULT_FORMATTERS,), method_name)
formatters_requiring_module = combine_formatters((FILTER_RESULT_FORMATTERS,), method_name... |
.usefixtures('use_tmpdir')
def test_move_file(shell):
with open('file', 'w', encoding='utf-8') as f:
f.write('Hei')
shell.move_file('file', 'file2')
assert os.path.isfile('file2')
assert (not os.path.isfile('file'))
assert (b'No such file or directory' in shell.move_file('file2', 'path/file2... |
def set_fast_pyparsing_reprs():
for obj in vars(_pyparsing).values():
try:
if issubclass(obj, ParserElement):
_old_pyparsing_reprs.append((obj, (obj.__repr__, obj.__str__)))
obj.__repr__ = fast_repr
obj.__str__ = fast_repr
except TypeError:... |
class _Worker(Thread):
def __init__(self, task_queue):
Thread.__init__(self)
self.tasks_queue = task_queue
self.setDaemon(True)
def run(self):
while True:
func = self.tasks_queue.get()
try:
try:
func()
ex... |
class getCounters_args():
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
def isUnion():
return False
def read(self, iprot):
if ((isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocol) a... |
def extractJackofalltastesconnoisseurofnoneWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('A Tale of Two Phoenixes', 'A Tale of Two Phoenixes', 'translated'), ('PR... |
class TestReentrancy():
def setup_class(cls):
protocol_path = os.path.join(ROOT_DIR, 'packages', 'fetchai', 'protocols', 'oef_search')
connection_path = os.path.join(ROOT_DIR, 'packages', 'fetchai', 'connections', 'soef')
builder = AEABuilder()
builder.set_name('aea1')
builde... |
class FitterOptions(BaseModel):
num_poles: Optional[int] = 1
num_tries: Optional[int] = 50
tolerance_rms: Optional[float] = 0.01
min_wvl: Optional[float] = None
max_wvl: Optional[float] = None
bound_amp: Optional[float] = None
bound_eps_inf: Optional[float] = 1.0
bound_f: Optional[float]... |
class OptionSeriesOrganizationLevelsDatalabelsFilter(Options):
def operator(self):
return self._config_get(None)
def operator(self, value: Any):
self._config(value, js_type=False)
def property(self):
return self._config_get(None)
def property(self, text: str):
self._confi... |
def prepare_ndarray(data, schema):
if hasattr(data, '__array_interface__'):
array_interface = data.__array_interface__.copy()
array_interface['data'] = data.tobytes()
array_interface['shape'] = list(array_interface['shape'])
return array_interface
else:
return data |
class StorageManager():
def __init__(self, hass, config_manager: ConfigManager):
self._hass = hass
self._config_manager = config_manager
def config_data(self) -> ConfigData:
config_data = None
if (self._config_manager is not None):
config_data = self._config_manager.d... |
class OptionSeriesVariwideDataDatalabelsFilter(Options):
def operator(self):
return self._config_get(None)
def operator(self, value: Any):
self._config(value, js_type=False)
def property(self):
return self._config_get(None)
def property(self, text: str):
self._config(text... |
def main(args):
parser = argparse.ArgumentParser(description='Generate ESPHome Home Assistant config.json')
parser.add_argument('channels', nargs='+', type=Channel, choices=list(Channel))
args = parser.parse_args(args)
root = Path(__file__).parent.parent
templ = (root / 'template')
with open((te... |
class OptionPlotoptionsBulletDragdrop(Options):
def draggableTarget(self):
return self._config_get(True)
def draggableTarget(self, flag: bool):
self._config(flag, js_type=False)
def draggableX(self):
return self._config_get(None)
def draggableX(self, flag: bool):
self._co... |
_settings(ROOT_URLCONF='tests.browsable_api.no_auth_urls')
class NoDropdownWithoutAuthTests(TestCase):
def setUp(self):
self.client = APIClient(enforce_csrf_checks=True)
self.username = 'john'
self.email = ''
self.password = 'password'
self.user = User.objects.create_user(sel... |
class OptionPlotoptionsColumnSonificationContexttracksMappingRate(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
class TestAchromaticRoundTrip(TestRoundTrip):
class Color(Base):
Color.deregister('space:hpluv')
Color.deregister('space:ryb')
Color.deregister('space:ryb-biased')
SPACES = {k: 6 for k in Color.CS_MAP.keys()}
COLORS = [Color('darkgrey'), Color('lightgrey'), Color('gray'), Color('black'), Color('... |
def cfg_with_single_aliased_variable_4(x, z_aliased):
cfg = ControlFlowGraph()
(mem0, mem1, mem2, mem3) = generate_mem_phi_variables(4)
n0 = BasicBlock(0, [Assignment(ListOperation([]), Call(function_symbol('func'), [UnaryOperation(OperationType.dereference, [z_aliased[1]])]))])
n1 = BasicBlock(1, [MemP... |
class InputSticker(Dictionaryable, JsonSerializable):
def __init__(self, sticker: Union[(str, InputFile)], emoji_list: List[str], mask_position: Optional[MaskPosition]=None, keywords: Optional[List[str]]=None) -> None:
self.sticker: Union[(str, InputFile)] = sticker
self.emoji_list: List[str] = emoj... |
def _prepare_input_tensors(m, nk_groups, dtype, start=0, has_bias=True, only_params=False):
inputs = []
for (i, (n, k)) in enumerate(nk_groups):
X = Tensor(shape=[m, k], dtype=dtype, name='x_{}'.format((i + start)), is_input=True)
W = Tensor(shape=[n, k], dtype=dtype, name='w_{}'.format((i + sta... |
def test_math_operations():
c = 2.0
x = (0.25 - (1j * 14.5))
y = ((- 1.0) + (1j * 0.5))
x_fxp = Fxp(x, dtype='Q14.3')
y_fxp = Fxp(y, dtype='Q14.3')
z = (x + y)
z_fxp = (x_fxp + y_fxp)
assert (z_fxp() == z)
z = (x + c)
z_fxp = (x_fxp + c)
assert (z_fxp() == z)
z = (x - y)
... |
def convert_traditional_views_to_materialized_views(transactional_db):
with connection.cursor() as cursor:
cursor.execute('; '.join((f'drop view if exists {v} cascade' for v in ALL_MATVIEWS)))
generate_matviews(materialized_views_as_traditional_views=False)
(yield)
with connection.cursor() as cu... |
class BadLen(BgpExc):
CODE = BGP_ERROR_MESSAGE_HEADER_ERROR
SUB_CODE = BGP_ERROR_SUB_BAD_MESSAGE_LENGTH
def __init__(self, msg_type_code, message_length):
super(BadLen, self).__init__()
self.msg_type_code = msg_type_code
self.length = message_length
self.data = struct.pack('!... |
class TestCoinChange(unittest.TestCase):
def test_coin_change(self):
coin_changer = CoinChanger()
self.assertRaises(TypeError, coin_changer.make_change, None, None)
self.assertEqual(coin_changer.make_change([], 0), 0)
self.assertEqual(coin_changer.make_change([1, 2, 3], 5), 2)
... |
def _cli_reverse_dns_lookup(ip_list, max_workers=600):
socket.setdefaulttimeout(8)
count_df = pd.Series(ip_list).value_counts().reset_index()
count_df.columns = ['ip_address', 'count']
count_df['cum_count'] = count_df['count'].cumsum()
count_df['perc'] = count_df['count'].div(count_df['count'].sum()... |
_counter
_table
_wkt
_with_session
def get_statistics(session, interval='day', wkt=None, distance=None, begin=None, end=None, limit=None, offset=None, tbl=None, **kwargs):
query = emissionsapi.db.get_statistics(session, tbl, interval_length=interval)
query = emissionsapi.db.filter_query(query, tbl, wkt=wkt, dis... |
class RowLimitedContractDownloadViewSet(BaseDownloadViewSet):
endpoint_doc = 'usaspending_api/api_contracts/contracts/v2/download/contract.md'
def post(self, request):
request.data['constraint_type'] = 'row_count'
return BaseDownloadViewSet.post(self, request, validator_type=ContractDownloadVali... |
class OptionPlotoptionsPieStates(Options):
def hover(self) -> 'OptionPlotoptionsPieStatesHover':
return self._config_sub_data('hover', OptionPlotoptionsPieStatesHover)
def inactive(self) -> 'OptionPlotoptionsPieStatesInactive':
return self._config_sub_data('inactive', OptionPlotoptionsPieStatesI... |
(LOOK_DEV_TYPES)
def check_only_supported_materials_are_used(progress_controller=None):
if (progress_controller is None):
progress_controller = ProgressControllerBase()
non_arnold_materials = []
all_valid_materials = []
for renderer in VALID_MATERIALS.keys():
all_valid_materials.extend(V... |
class PageTest(FaunaTestCase):
def test_page(self):
self.assertEqual(Page.from_raw({'data': 1, 'before': 2, 'after': 3}), Page(1, 2, 3))
self.assertEqual(Page([1, 2, 3], 2, 3).map_data((lambda x: (x + 1))), Page([2, 3, 4], 2, 3))
def test_set_iterator(self):
collection_ref = self.client.... |
def test_tas_b_defaults_success(client, download_test_data):
download_generation.retrieve_db_string = Mock(return_value=get_database_dsn_string())
resp = client.post('/api/v2/download/accounts/', content_type='application/json', data=json.dumps({'account_level': 'treasury_account', 'filters': {'submission_types... |
def test_get_limited_markdown_msg():
slack_message_builder = SlackMessageBuilder()
short_message = 'short message'
long_message = (short_message * 3000)
markdown_short_message = slack_message_builder.get_limited_markdown_msg(short_message)
markdown_long_message = slack_message_builder.get_limited_ma... |
def test_should_guess_only_specific_actions_and_fix_upper_lowercase():
input_policy = PolicyDocument(Version='2012-10-17', Statement=[Statement(Effect='Allow', Action=[Action('ec2', 'DetachVolume')], Resource=['*'])])
expected_output = PolicyDocument(Version='2012-10-17', Statement=[Statement(Effect='Allow', Ac... |
class OptionSeriesBarSonificationDefaultspeechoptionsMappingPlaydelay(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
class get_config_reply(message):
version = 1
type = 8
def __init__(self, xid=None, flags=None, miss_send_len=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (flags != None):
self.flags = flags
else:
self.flags =... |
def get_chain_backend_class(backend_import_path=None):
warnings.simplefilter('default')
if (backend_import_path is None):
if ('ETHEREUM_TESTER_CHAIN_BACKEND' in os.environ):
backend_import_path = os.environ['ETHEREUM_TESTER_CHAIN_BACKEND']
elif is_supported_pyevm_version_available():... |
class Solution():
def maximalSquare(self, matrix: List[List[str]]) -> int:
dp = [([0] * len(matrix[0])) for _ in range(len(matrix))]
ans = 0
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if ((i == 0) or (j == 0)):
dp[i][j] = int(... |
def eql_search(path, query_text, config=None):
config = (config or {})
config.setdefault('flatten', True)
engine = get_engine(query_text, config)
event_stream = stream_file_events(path)
rows = [result.data for result in engine(event_stream)]
frame = DataFrame(rows)
return frame.replace(numpy... |
class OptionPlotoptionsSolidgaugeSonificationDefaultinstrumentoptionsMappingTremoloDepth(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(s... |
class MarkdownEmbedding(SourceEmbedding):
def __init__(self, file_path, vector_store_config, source_reader: Optional=None, text_splitter: Optional[TextSplitter]=None):
super().__init__(file_path, vector_store_config, source_reader=None, text_splitter=None)
self.file_path = file_path
self.vec... |
def apply_crd():
crd_spec = {'apiVersion': 'apiextensions.k8s.io/v1', 'kind': 'CustomResourceDefinition', 'metadata': {'name': f'{PLURAL}.{GROUP}'}, 'spec': {'group': GROUP, 'names': {'kind': 'MagicHappens', 'listKind': 'MagicHappensList', 'plural': PLURAL, 'singular': 'magichappens'}, 'scope': 'Namespaced', 'versi... |
def extractNovelhereWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type)... |
def test_check_inds():
assert (check_inds(1) == np.array([1]))
assert array_equal(check_inds([0, 2]), np.array([0, 2]))
assert array_equal(check_inds(range(0, 2)), np.array([0, 1]))
assert array_equal(check_inds(np.array([1, 2, 3])), np.array([1, 2, 3]))
assert array_equal(check_inds(np.array([True,... |
('frontend.management.commands.generate_presentation_replacements.cleanup_empty_classes')
('frontend.management.commands.generate_presentation_replacements.create_bigquery_table')
class CommandsTestCase(TestCase):
def setUp(self):
Section.objects.create(bnf_id='0000', name='Subsection 0.0', bnf_chapter=0, b... |
def identify_plant(file_names):
params = {'images': [encode_file(img) for img in file_names], 'latitude': 49.1951239, 'longitude': 16.6077111, 'datetime': , 'modifiers': ['crops_fast', 'similar_images']}
headers = {'Content-Type': 'application/json', 'Api-Key': API_KEY}
response = requests.post(' json=param... |
class ReduceStreamOperator(BaseOperator, Generic[(IN, OUT)]):
def __init__(self, reduce_function=None, **kwargs):
super().__init__(**kwargs)
if (reduce_function and (not callable(reduce_function))):
raise ValueError('reduce_function must be callable')
self.reduce_function = reduc... |
def test_mine_multiple_timedelta(devnetwork, chain):
chain.mine(5, timedelta=123)
timestamps = [i.timestamp for i in list(chain)[(- 5):]]
assert ((chain.time() - timestamps[(- 1)]) < 3)
for i in range(1, 5):
assert (timestamps[i] > timestamps[(i - 1)])
assert ((timestamps[0] + 123) == timest... |
def main(page: Page):
N = 45
(x, y) = np.random.rand(2, N)
c = np.random.randint(1, 5, size=N)
s = np.random.randint(10, 220, size=N)
(fig, ax) = plt.subplots()
scatter = ax.scatter(x, y, c=c, s=s)
legend1 = ax.legend(*scatter.legend_elements(), loc='lower left', title='Classes')
ax.add_... |
def extractMusubinovelBlogspotCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type... |
def get_os_name(metadata=None):
if metadata:
platform = metadata['platform'].lower()
if ('linux' in platform):
return 'linux'
elif (('darwin' in platform) or ('macos' in platform) or ('osx' in platform)):
return 'mac'
elif ('win' in platform):
retu... |
class SignInViaUsernameForm(SignIn):
username = forms.CharField(label=_('Username'))
def field_order(self):
if settings.USE_REMEMBER_ME:
return ['username', 'password', 'remember_me']
return ['username', 'password']
def clean_username(self):
username = self.cleaned_data['... |
class Descritor():
def __init__(self, obj):
self.obj = obj
def __set__(self, obj, val):
print('Estou setando algo')
self.obj = val
def __get__(self, obj, tipo=None):
print('Estou pegango algo')
return self.obj
def __delete__(self, obj):
print('Estou deleta... |
class NoiselessDetector(Detector):
def __init__(self, detector_grid, subsamping=1):
Detector.__init__(self, detector_grid, subsamping)
self.accumulated_charge = 0
def integrate(self, wavefront, dt, weight=1):
if hasattr(wavefront, 'power'):
power = wavefront.power
els... |
.parametrize('defines, expected', [pytest.param('\nNUM_REALIZATIONS 1\nDEFINE <A> <B><C>\nDEFINE <B> my\nDEFINE <C> name\nJOBNAME <A>%d', 'myname0', id='Testing of use before declaration works for defines'), pytest.param('\nNUM_REALIZATIONS 1\nDATA_KW <A> <B><C>\nDATA_KW <B> my\nDATA_KW <C> name\nJOBNAME <A>%d', 'mynam... |
class InputMediaDocument(InputMedia):
def __init__(self, media, thumbnail=None, caption=None, parse_mode=None, caption_entities=None, disable_content_type_detection=None):
super(InputMediaDocument, self).__init__(type='document', media=media, caption=caption, parse_mode=parse_mode, caption_entities=caption_... |
.external
.parametrize('config_name', ('fewshot.cfg', 'zeroshot.cfg'))
def test_textcat_openai(config_name: str):
path = (_USAGE_EXAMPLE_PATH / 'textcat_openai')
textcat_openai.run_pipeline(text='text', config_path=(path / config_name), examples_path=(None if (config_name == 'zeroshot.cfg') else (path / 'exampl... |
class BulkCommandResponder(cmdrsp.BulkCommandResponder):
def handleMgmtOperation(self, snmp_engine, state_reference, context_name, pdu, ac_info):
try:
cmdrsp.BulkCommandResponder.handleMgmtOperation(self, snmp_engine, state_reference, probe_hash_context(self, snmp_engine), pdu, (None, snmp_engin... |
class TakeWhile(Op):
__slots__ = ('_predicate',)
def __init__(self, predicate=bool, source=None):
Op.__init__(self, source)
self._predicate = predicate
def on_source(self, *args):
if self._predicate(*args):
self.emit(*args)
else:
self.set_done()
... |
class Cards():
def __init__(self, cards: List[Card], lowest_rank=2):
self._sorted = sorted(cards, key=int, reverse=True)
self._lowest_rank: int = lowest_rank
def _group_by_ranks(self) -> Dict[(int, List[Card])]:
ranks = collections.defaultdict(list)
for card in self._sorted:
... |
def get_example_tree():
t = Tree()
t.populate(10)
rs1 = faces.TextFace('branch-right\nmargins&borders', fsize=12, fgcolor='#009000')
rs1.margin_top = 10
rs1.margin_bottom = 50
rs1.margin_left = 40
rs1.margin_right = 40
rs1.border.width = 1
rs1.background.color = 'lightgreen'
rs1.... |
def test_new_variable_names_correct_assignment():
tr = DatetimeSubtraction(variables='var1', reference='var2')
assert (tr.new_variables_names is None)
tr = DatetimeSubtraction(variables='var1', reference='var2', new_variables_names=['var1'])
assert (tr.new_variables_names == ['var1'])
tr = DatetimeS... |
def test_record_names_must_match():
'
writer_schema = {'type': 'record', 'name': 'test', 'fields': [{'name': 'test1', 'type': {'type': 'record', 'name': 'my_record', 'fields': [{'name': 'field1', 'type': 'string'}]}}, {'name': 'test2', 'type': 'my_record'}]}
reader_schema = {'type': 'record', 'name': 'test'... |
def extractFinebymetranslationsWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Death Progress Bar', 'Death Progress Bar', 'translated'), ('PRC', 'PRC', 'translated... |
def validate_eth1_withdrawal_address(cts: click.Context, param: Any, address: str) -> HexAddress:
if (address is None):
return None
if (not is_hex_address(address)):
raise ValidationError(load_text(['err_invalid_ECDSA_hex_addr']))
if (not is_checksum_address(address)):
raise Validati... |
class PhoneHolder(Boxes):
ui_group = 'Misc'
description = '\n This phone stand holds your phone between two tabs, with access to its\n bottom, in order to connect a charger, headphones, and also not to obstruct\n the mic.\n\n Default values are currently based on Galaxy S7.\n'
def __init__(self)... |
def exp(computation: ComputationAPI, gas_per_byte: int) -> None:
(base, exponent) = computation.stack_pop_ints(2)
bit_size = exponent.bit_length()
byte_size = (ceil8(bit_size) // 8)
if (exponent == 0):
result = 1
elif (base == 0):
result = 0
else:
result = pow(base, expon... |
class HTMLParser(markupbase.ParserBase):
CDATA_CONTENT_ELEMENTS = ('script', 'style')
def __init__(self):
self.reset()
def reset(self):
self.rawdata = ''
self.lasttag = '???'
self.interesting = interesting_normal
self.cdata_elem = None
markupbase.ParserBase.re... |
def _plotDistribution(axes: 'Axes', plot_config: 'PlotConfig', data: pd.DataFrame, label: str, index, previous_data):
data = (pd.Series(dtype='float64') if data.empty else data[0])
axes.set_xlabel(plot_config.xLabel())
axes.set_ylabel(plot_config.yLabel())
style = plot_config.distributionStyle()
if ... |
class MapError(RuntimeError):
def __init__(self, error='', node_or_link=None):
prefix = ''
if node_or_link:
prefix = f"{node_or_link.__class__.__name__} '{node_or_link.symbol}' at XYZ=({node_or_link.X:g},{node_or_link.Y:g},{node_or_link.Z}) "
self.node_or_link = node_or_link
... |
class OptionPlotoptionsFunnel3dSonificationDefaultspeechoptionsMappingTime(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str... |
class OptionSeriesWordcloudSonificationDefaultspeechoptionsMappingTime(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.