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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0b3966d94365a91e003e8f20 | train | class | class CatalogManagerTests(unittest.TestCase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def test_catalog_manager_singleton_pattern(self):
x = CatalogManager()
y = CatalogManager()
self.assertEqual(x, y)
@mock.patch('eva.catalog.catalog_manager.... | class CatalogManagerTests(unittest.TestCase):
| def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def test_catalog_manager_singleton_pattern(self):
x = CatalogManager()
y = CatalogManager()
self.assertEqual(x, y)
@mock.patch('eva.catalog.catalog_manager.init_db')
def test_catalog_bootstrap(self, ... | # coding=utf-8
# Copyright 2018-2020 EVA
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | 189 | 256 | 1,740 | 8 | 180 | LordDarkula/eva | test/catalog/test_catalog_manager.py | Python | CatalogManagerTests | CatalogManagerTests | 24 | 229 | 24 | 25 | dddb32ce570b198fa11ba8b7266c625117b9a71e | bigcode/the-stack | train |
b89eb75bf5a200f3669c3391 | train | function | async def _call_blocking(loop: asyncio.AbstractEventLoop, executor: concurrent.futures.Executor, func, *args):
futures = [
loop.run_in_executor(executor, func, *args)]
while futures:
done, futures = await asyncio.wait(
futures,
loop=loop, return_when=asyncio.ALL_COMPLETED... | async def _call_blocking(loop: asyncio.AbstractEventLoop, executor: concurrent.futures.Executor, func, *args):
| futures = [
loop.run_in_executor(executor, func, *args)]
while futures:
done, futures = await asyncio.wait(
futures,
loop=loop, return_when=asyncio.ALL_COMPLETED
)
for f in done:
await f
return f.result()
| timeout=None):
return self._values.get(block=block, timeout=timeout)
def join(self):
self._thread.join()
def stop(self):
self._stop.set()
async def _call_blocking(loop: asyncio.AbstractEventLoop, executor: concurrent.futures.Executor, func, *args):
| 64 | 64 | 89 | 25 | 39 | shoriwe/bftool | bftool/bftool_pool.py | Python | _call_blocking | _call_blocking | 48 | 58 | 48 | 48 | aea5b600c7904d934201adc106498a38e2700351 | bigcode/the-stack | train |
26d398565e0f33d8bd00e259 | train | class | class Queue(object):
def __init__(self, values):
self.__reference = values
self._values = multiprocessing.Queue()
self._stop = multiprocessing.Event()
self._complete = multiprocessing.Event()
self._thread = threading.Thread(target=self.__fill, )
self._thread.start()
... | class Queue(object):
| def __init__(self, values):
self.__reference = values
self._values = multiprocessing.Queue()
self._stop = multiprocessing.Event()
self._complete = multiprocessing.Event()
self._thread = threading.Thread(target=self.__fill, )
self._thread.start()
def __fill(self):... | import asyncio
import collections
import concurrent.futures
import multiprocessing
import multiprocessing.pool
import queue
import sys
import threading
import time
import types
from .arguments import Arguments
__all__ = ["Pool"]
class Queue(object):
| 50 | 64 | 172 | 4 | 46 | shoriwe/bftool | bftool/bftool_pool.py | Python | Queue | Queue | 17 | 45 | 17 | 17 | bc3a52fa5a9d4c51bff599f41922049174c6da47 | bigcode/the-stack | train |
04c9801da8f218b6ee1c3e47 | train | class | class Pool(object):
def __init__(
self,
function_: collections.abc.Callable or types.FunctionType or types.MethodType,
function_arguments: Arguments or collections.abc.Iterable[Arguments or collections.abc.Iterable],
check_function: collections.abc.Callable = lambda _... | class Pool(object):
| def __init__(
self,
function_: collections.abc.Callable or types.FunctionType or types.MethodType,
function_arguments: Arguments or collections.abc.Iterable[Arguments or collections.abc.Iterable],
check_function: collections.abc.Callable = lambda _: True,
... | self, values):
self.__reference = values
self._values = multiprocessing.Queue()
self._stop = multiprocessing.Event()
self._complete = multiprocessing.Event()
self._thread = threading.Thread(target=self.__fill, )
self._thread.start()
def __fill(self):
for elem... | 256 | 256 | 1,305 | 4 | 252 | shoriwe/bftool | bftool/bftool_pool.py | Python | Pool | Pool | 61 | 214 | 61 | 61 | 9feb989e0ace78092694afce8e9f06a1acdbca35 | bigcode/the-stack | train |
7f1af1b208cea718bf0b8abd | train | class | class saveAnalysisGFS(generic.saveAnalysis):
def setup(self, config, an):
# Get generic defaults
generic.saveAnalysis.setup(self, config, an)
# Use GFS specific script
self.command = os.path.join(config['model_path'], "tasks/runSaveAnalysis.py")
| class saveAnalysisGFS(generic.saveAnalysis):
| def setup(self, config, an):
# Get generic defaults
generic.saveAnalysis.setup(self, config, an)
# Use GFS specific script
self.command = os.path.join(config['model_path'], "tasks/runSaveAnalysis.py")
|
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
import os
import yamltools
import ewok.tasks.saveAnalysis as generic
class saveAnalysisGFS(generic.saveAnalysis):
| 64 | 64 | 63 | 10 | 53 | NOAA-EMC/fv3-jedi | ewok/tasks/saveAnalysisGFS.py | Python | saveAnalysisGFS | saveAnalysisGFS | 11 | 19 | 11 | 12 | 8862e648ffffb789030202d9a92d354809f0ceb9 | bigcode/the-stack | train |
8894b6d2fffedef2b8c0b634 | train | function | def get_signed_url_client(service, op, url):
'''
get_signed_url_client
'''
from rucio.client.credentialclient import CredentialClient
return CredentialClient().get_signed_url(service, op, url)
| def get_signed_url_client(service, op, url):
| '''
get_signed_url_client
'''
from rucio.client.credentialclient import CredentialClient
return CredentialClient().get_signed_url(service, op, url)
| se, vo='def', **kwarg):
'''
get_rse_client
'''
from rucio.client.rseclient import RSEClient
client = RSEClient(vo=vo)
return client.get_rse(rse)
def get_signed_url_client(service, op, url):
| 64 | 64 | 48 | 11 | 53 | ijjorama/rucio | lib/rucio/rse/__init__.py | Python | get_signed_url_client | get_signed_url_client | 50 | 55 | 50 | 50 | 583982aa6b4d454893971faf475e2eb7331fc6f9 | bigcode/the-stack | train |
3ce54eb7db3f38e0f7327c98 | train | function | def get_rse_client(rse, vo='def', **kwarg):
'''
get_rse_client
'''
from rucio.client.rseclient import RSEClient
client = RSEClient(vo=vo)
return client.get_rse(rse)
| def get_rse_client(rse, vo='def', **kwarg):
| '''
get_rse_client
'''
from rucio.client.rseclient import RSEClient
client = RSEClient(vo=vo)
return client.get_rse(rse)
| (rsemanager, 'CLIENT_MODE', True)
setattr(rsemanager, 'SERVER_MODE', False)
else:
setattr(rsemanager, 'CLIENT_MODE', False)
setattr(rsemanager, 'SERVER_MODE', True)
def get_rse_client(rse, vo='def', **kwarg):
| 64 | 64 | 59 | 16 | 48 | ijjorama/rucio | lib/rucio/rse/__init__.py | Python | get_rse_client | get_rse_client | 41 | 47 | 41 | 41 | e76c3d8e0832a871d8b7998927d131ece9b970f7 | bigcode/the-stack | train |
9a12c8832cae96de7485752f | train | function | def rse_key_generator(namespace, fn, **kwargs):
'''
Key generator for RSE
'''
def generate_key(rse, vo='def', session=None):
'''
generate_key
'''
return '{}:{}'.format(rse, vo)
return generate_key
| def rse_key_generator(namespace, fn, **kwargs):
| '''
Key generator for RSE
'''
def generate_key(rse, vo='def', session=None):
'''
generate_key
'''
return '{}:{}'.format(rse, vo)
return generate_key
| se(rse)
def get_signed_url_client(service, op, url):
'''
get_signed_url_client
'''
from rucio.client.credentialclient import CredentialClient
return CredentialClient().get_signed_url(service, op, url)
def rse_key_generator(namespace, fn, **kwargs):
| 64 | 64 | 61 | 12 | 52 | ijjorama/rucio | lib/rucio/rse/__init__.py | Python | rse_key_generator | rse_key_generator | 58 | 67 | 58 | 58 | abd56958fcece89afda42d8f86c78a944ebedee6 | bigcode/the-stack | train |
0787dbc9ee2b9c48e6045563 | train | function | def locate_linear_layer(mod: nn.Module) -> Optional[str]:
"""Attempts to find a fully connecter layer to use for CAM extraction
Args:
mod: the module to inspect
Returns:
str: the candidate layer
"""
print("locate_linear_layer")
candidate_layer = None
for layer_name, m in mo... | def locate_linear_layer(mod: nn.Module) -> Optional[str]:
| """Attempts to find a fully connecter layer to use for CAM extraction
Args:
mod: the module to inspect
Returns:
str: the candidate layer
"""
print("locate_linear_layer")
candidate_layer = None
for layer_name, m in mod.named_modules():
print(layer_name,m,"_+_+_+_+__+... | pooling
if len(output_shape) != (len(input_shape) + 1) or all(v == 1 for v in output_shape[2:]):
break
else:
candidate_layer = layer_name
return candidate_layer
def locate_linear_layer(mod: nn.Module) -> Optional[str]:
| 64 | 64 | 130 | 13 | 50 | 13263081188/torch-cam | latent_cam/cams/utils.py | Python | locate_linear_layer | locate_linear_layer | 61 | 78 | 61 | 61 | 538629774f4ae5e2be1c0488cf3a882973f28498 | bigcode/the-stack | train |
3430a9b9441ef3b2ccbe3c71 | train | function | def locate_candidate_layer(mod: nn.Module, input_shape: Tuple[int, ...] = (3, 224, 224)) -> Optional[str]:
"""Attempts to find a candidate layer to use for CAM extraction
Args:
mod: the module to inspect
input_shape: the expected shape of input tensor excluding the batch dimension
Returns:... | def locate_candidate_layer(mod: nn.Module, input_shape: Tuple[int, ...] = (3, 224, 224)) -> Optional[str]:
| """Attempts to find a candidate layer to use for CAM extraction
Args:
mod: the module to inspect
input_shape: the expected shape of input tensor excluding the batch dimension
Returns:
str: the candidate layer for CAM
"""
# Set module in eval mode
module_mode = mod.trai... | This program is licensed under the Apache License version 2.
# See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.
import torch
from torch import Tensor
from torch import nn
from typing import List, Optional, Tuple
from functools import partial
__all__ = ['locate_candidat... | 111 | 111 | 371 | 31 | 80 | 13263081188/torch-cam | latent_cam/cams/utils.py | Python | locate_candidate_layer | locate_candidate_layer | 14 | 58 | 14 | 14 | 2d4865751bc4336b8ec2cd5128144afc6d810667 | bigcode/the-stack | train |
6dc3a255fc66ddaaf9468efa | train | function | @pytest.mark.trio
async def test_event_trigger_with_multiple_subscriptions():
event = Event("test")
async with event.subscribe() as subscription_a:
await event.trigger(1234)
async with event.subscribe() as subscription_b:
await event.trigger(4321)
result_a_1 = subscrip... | @pytest.mark.trio
async def test_event_trigger_with_multiple_subscriptions():
| event = Event("test")
async with event.subscribe() as subscription_a:
await event.trigger(1234)
async with event.subscribe() as subscription_b:
await event.trigger(4321)
result_a_1 = subscription_a.receive_nowait()
result_a_2 = subscription_a.receive_nowait... | )
result = await subscription.receive()
assert result == 1234
with pytest.raises(trio.ClosedResourceError):
subscription.receive_nowait()
with pytest.raises(trio.ClosedResourceError):
await subscription.receive()
@pytest.mark.trio
async def test_event_trigger_with_multiple_subs... | 64 | 64 | 161 | 15 | 49 | vaporydev/ddht | tests/core/test_event.py | Python | test_event_trigger_with_multiple_subscriptions | test_event_trigger_with_multiple_subscriptions | 59 | 80 | 59 | 60 | 8e0970651663667cdd5af21fa819ecdc097a7f4e | bigcode/the-stack | train |
b0379ff133c5033e3b82cbe0 | train | function | @pytest.mark.trio
async def test_event_trigger_nowait_with_multiple_subscriptions():
event = Event("test")
async with event.subscribe() as subscription_a:
event.trigger_nowait(1234)
async with event.subscribe() as subscription_b:
event.trigger_nowait(4321)
result_a_1 =... | @pytest.mark.trio
async def test_event_trigger_nowait_with_multiple_subscriptions():
| event = Event("test")
async with event.subscribe() as subscription_a:
event.trigger_nowait(1234)
async with event.subscribe() as subscription_b:
event.trigger_nowait(4321)
result_a_1 = subscription_a.receive_nowait()
result_a_2 = subscription_a.receive_nowa... | 1
assert result_b_1 == 4321
with pytest.raises(trio.WouldBlock):
subscription_a.receive_nowait()
with pytest.raises(trio.WouldBlock):
subscription_b.receive_nowait()
@pytest.mark.trio
async def test_event_trigger_nowait_with_multiple_subscriptions():
| 64 | 64 | 165 | 17 | 47 | vaporydev/ddht | tests/core/test_event.py | Python | test_event_trigger_nowait_with_multiple_subscriptions | test_event_trigger_nowait_with_multiple_subscriptions | 83 | 104 | 83 | 84 | 10ebe5fdb471ab6a63a997809d433cdd082001d6 | bigcode/the-stack | train |
442d82bb68b0035e19b8ae8b | train | function | @pytest.mark.trio
async def test_event_trigger_nowait_with_single_subscription():
event = Event("test")
async with event.subscribe() as subscription:
with pytest.raises(trio.WouldBlock):
subscription.receive_nowait()
event.trigger_nowait(1234)
result = await subscription.r... | @pytest.mark.trio
async def test_event_trigger_nowait_with_single_subscription():
| event = Event("test")
async with event.subscribe() as subscription:
with pytest.raises(trio.WouldBlock):
subscription.receive_nowait()
event.trigger_nowait(1234)
result = await subscription.receive()
assert result == 1234
with pytest.raises(trio.ClosedResource... | result = await subscription.receive()
assert result == 1234
with pytest.raises(trio.ClosedResourceError):
subscription.receive_nowait()
with pytest.raises(trio.ClosedResourceError):
await subscription.receive()
@pytest.mark.trio
async def test_event_trigger_nowait_with_single_su... | 64 | 64 | 105 | 16 | 48 | vaporydev/ddht | tests/core/test_event.py | Python | test_event_trigger_nowait_with_single_subscription | test_event_trigger_nowait_with_single_subscription | 40 | 56 | 40 | 41 | aa85819ee4ba37d7a546de5bce64d0c22df1bb39 | bigcode/the-stack | train |
9d87cb1a90aef87dcb02eabf | train | function | @pytest.mark.trio
async def test_event_trigger_with_single_subscription():
event = Event("test")
async with event.subscribe() as subscription:
with pytest.raises(trio.WouldBlock):
subscription.receive_nowait()
await event.trigger(1234)
result = await subscription.receive()... | @pytest.mark.trio
async def test_event_trigger_with_single_subscription():
| event = Event("test")
async with event.subscribe() as subscription:
with pytest.raises(trio.WouldBlock):
subscription.receive_nowait()
await event.trigger(1234)
result = await subscription.receive()
assert result == 1234
with pytest.raises(trio.ClosedResourceE... | _event_trigger_with_no_subscriptions():
event = Event("test")
await event.trigger(None)
@pytest.mark.trio
async def test_event_trigger_nowait_with_no_subscriptions():
event = Event("test")
await event.trigger(None)
@pytest.mark.trio
async def test_event_trigger_with_single_subscription():
| 64 | 64 | 102 | 14 | 50 | vaporydev/ddht | tests/core/test_event.py | Python | test_event_trigger_with_single_subscription | test_event_trigger_with_single_subscription | 21 | 37 | 21 | 22 | 4a46f25d6570c9ea42eaae83c9a7f690cc0be4f9 | bigcode/the-stack | train |
5ca4c8e5301bb84aff2f4caf | train | function | @pytest.mark.trio
async def test_event_wait_without_explicit_subscription():
event = Event("test")
async with trio.open_nursery() as nursery:
got_it = trio.Event()
async def wait_for_it():
result = await event.wait()
assert result == 1234
got_it.set()
... | @pytest.mark.trio
async def test_event_wait_without_explicit_subscription():
| event = Event("test")
async with trio.open_nursery() as nursery:
got_it = trio.Event()
async def wait_for_it():
result = await event.wait()
assert result == 1234
got_it.set()
nursery.start_soon(wait_for_it)
# give the wait_for_it task a mome... | 4321
assert result_b_1 == 4321
with pytest.raises(trio.WouldBlock):
subscription_a.receive_nowait()
with pytest.raises(trio.WouldBlock):
subscription_b.receive_nowait()
@pytest.mark.trio
async def test_event_wait_without_explicit_subscription():
| 64 | 64 | 177 | 15 | 49 | vaporydev/ddht | tests/core/test_event.py | Python | test_event_wait_without_explicit_subscription | test_event_wait_without_explicit_subscription | 107 | 131 | 107 | 108 | 6210658fd489bb12426852dffd664f7f32962ff3 | bigcode/the-stack | train |
f3c9b22d6f678cdb40af3287 | train | function | @pytest.mark.trio
async def test_event_trigger_with_no_subscriptions():
event = Event("test")
await event.trigger(None)
| @pytest.mark.trio
async def test_event_trigger_with_no_subscriptions():
| event = Event("test")
await event.trigger(None)
| import pytest
import trio
from ddht.event import Event
@pytest.mark.trio
async def test_event_trigger_with_no_subscriptions():
| 28 | 64 | 28 | 15 | 12 | vaporydev/ddht | tests/core/test_event.py | Python | test_event_trigger_with_no_subscriptions | test_event_trigger_with_no_subscriptions | 7 | 11 | 7 | 8 | 38008d1af3bcc212a5677209b8d325b4134a1c7c | bigcode/the-stack | train |
c2740bfa4b06ebcf4163ddda | train | function | @pytest.mark.trio
async def test_event_trigger_nowait_with_no_subscriptions():
event = Event("test")
await event.trigger(None)
| @pytest.mark.trio
async def test_event_trigger_nowait_with_no_subscriptions():
| event = Event("test")
await event.trigger(None)
| import pytest
import trio
from ddht.event import Event
@pytest.mark.trio
async def test_event_trigger_with_no_subscriptions():
event = Event("test")
await event.trigger(None)
@pytest.mark.trio
async def test_event_trigger_nowait_with_no_subscriptions():
| 58 | 64 | 30 | 17 | 41 | vaporydev/ddht | tests/core/test_event.py | Python | test_event_trigger_nowait_with_no_subscriptions | test_event_trigger_nowait_with_no_subscriptions | 14 | 18 | 14 | 15 | 1a8389fb295dda2732f0af64ddba16b42894a969 | bigcode/the-stack | train |
3bd723810f6bf81cb93b186a | train | function | @pytest.mark.trio
async def test_event_subscribe_and_wait():
event = Event("test")
with trio.fail_after(1):
async with trio.open_nursery() as nursery:
async with event.subscribe_and_wait():
nursery.start_soon(event.trigger, 1234)
| @pytest.mark.trio
async def test_event_subscribe_and_wait():
| event = Event("test")
with trio.fail_after(1):
async with trio.open_nursery() as nursery:
async with event.subscribe_and_wait():
nursery.start_soon(event.trigger, 1234)
| isn't setup yet....
await event.trigger(1234)
await event.trigger(1234)
await event.trigger(1234)
await event.trigger(1234)
with trio.fail_after(1):
await got_it.wait()
@pytest.mark.trio
async def test_event_subscribe_and_wait():
| 64 | 64 | 61 | 14 | 50 | vaporydev/ddht | tests/core/test_event.py | Python | test_event_subscribe_and_wait | test_event_subscribe_and_wait | 134 | 141 | 134 | 135 | 42dd321ba1e4f7d2d40d62a37076ca275ce6d2b8 | bigcode/the-stack | train |
bce0cf93eb8f964f39b469dc | train | class | class ReverseProxied(object):
"""
Because we are reverse proxied from an http/s server
use environ/config to signal https
since flask ignores preferred_url_scheme in url_for calls
"""
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
# if ... | class ReverseProxied(object):
| """
Because we are reverse proxied from an http/s server
use environ/config to signal https
since flask ignores preferred_url_scheme in url_for calls
"""
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
# if one of x_forwarded or preferre... | import os
import decimal
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_mail_sendgrid import MailSendGrid
from flask_socketio import SocketIO
from addresswatcher import AddressWatcher
from timer import Timer
class ReverseProxied(object):
| 57 | 64 | 156 | 7 | 49 | zap-me/zap_bill_payment | app_core.py | Python | ReverseProxied | ReverseProxied | 12 | 28 | 12 | 12 | b175cc331f6962f1ed73b29aed8ac78ade4eda43 | bigcode/the-stack | train |
9f16ebd4ad9eaeef2faa2cad | train | class | class LogsTaskTest(BaseHarborTestClass):
def test_will_print_logs_for_container(self):
"""Run command inside container, do not test output as it is passed-through directly to the console"""
service = ServiceDeclaration('alpine_3', {})
drv = self._get_prepared_compose_driver()
drv.up... | class LogsTaskTest(BaseHarborTestClass):
| def test_will_print_logs_for_container(self):
"""Run command inside container, do not test output as it is passed-through directly to the console"""
service = ServiceDeclaration('alpine_3', {})
drv = self._get_prepared_compose_driver()
drv.up(service, capture=True)
out = se... | from rkd_harbor.test import BaseHarborTestClass
from rkd_harbor.tasks.service import LogsTask
from rkd_harbor.service import ServiceDeclaration
class LogsTaskTest(BaseHarborTestClass):
| 47 | 64 | 134 | 10 | 36 | attawayinc/riotkit-harbor | test/test_servicelogstask.py | Python | LogsTaskTest | LogsTaskTest | 6 | 21 | 6 | 6 | a9e4b73e782129e96cae673e0a533d7e15f539df | bigcode/the-stack | train |
5b3823c8d0020814d1d37a03 | train | function | def send_clock():
# We find the proper input port for the software synth
# (which is the output port for Magenta)
output_ports = [name for name in mido.get_output_names()
if args.midi_port in name]
if not output_ports:
raise Exception(f"Cannot find proper output ports in: "
... | def send_clock():
# We find the proper input port for the software synth
# (which is the output port for Magenta)
| output_ports = [name for name in mido.get_output_names()
if args.midi_port in name]
if not output_ports:
raise Exception(f"Cannot find proper output ports in: "
f"{mido.get_output_names()}")
print(f"Sending clock to output port names: {output_ports}")
# Start a new MID... | _clock)
# Sends a stop message when finished
self._outport.send(self._message_stop)
def stop(self):
self._stop_signal = True
def send_clock():
# We find the proper input port for the software synth
# (which is the output port for Magenta)
| 64 | 64 | 216 | 29 | 34 | pesader/hands-on-music-generation-with-magenta | Chapter09/chapter_09_example_04.py | Python | send_clock | send_clock | 61 | 85 | 61 | 63 | 2ede71048d5d52736c9ce2aa1f69d11e08974920 | bigcode/the-stack | train |
02d82372905ccbf31cb474e8 | train | class | class Metronome(Thread):
def __init__(self, outport, qpm):
super(Metronome, self).__init__()
self._message_clock = mido.Message(type='clock')
self._message_start = mido.Message(type='start')
self._message_stop = mido.Message(type='stop')
self._message_reset = mido.Message(type='reset')
self._... | class Metronome(Thread):
| def __init__(self, outport, qpm):
super(Metronome, self).__init__()
self._message_clock = mido.Message(type='clock')
self._message_start = mido.Message(type='start')
self._message_stop = mido.Message(type='stop')
self._message_reset = mido.Message(type='reset')
self._outport = outport
# Pe... | transport messages.
VERSION: Magenta 1.1.7
"""
import argparse
import time
from decimal import Decimal
from threading import Thread
import mido
from magenta.common.concurrency import Sleeper
from magenta.interfaces.midi.midi_hub import MidiHub
parser = argparse.ArgumentParser()
parser.add_argument("--midi_port", t... | 94 | 94 | 316 | 6 | 88 | pesader/hands-on-music-generation-with-magenta | Chapter09/chapter_09_example_04.py | Python | Metronome | Metronome | 22 | 58 | 22 | 23 | f6eb103fa374c8ba3ccc70482ec46c725ed6236f | bigcode/the-stack | train |
2a1a71f41bae1b3ac0558592 | train | class | class FrameRate(DirectObject):
"""Toggles displaying the framerate with F12."""
def __init__(self):
self.state = False
self.accept('f12', self.Toggle)
def Toggle(self):
self.state = not self.state
getBase().setFrameRateMeter(self.state) | class FrameRate(DirectObject):
| """Toggles displaying the framerate with F12."""
def __init__(self):
self.state = False
self.accept('f12', self.Toggle)
def Toggle(self):
self.state = not self.state
getBase().setFrameRateMeter(self.state) | from direct.showbase.DirectObject import DirectObject
class FrameRate(DirectObject):
| 18 | 64 | 69 | 8 | 9 | Derfies/panda3d-editor | src/p3d/frameRate.py | Python | FrameRate | FrameRate | 4 | 14 | 4 | 5 | 5d780f7dc299edaa78636df3a2bbc513b420934d | bigcode/the-stack | train |
8274eb9ce6d01c9bb69d6254 | train | class | class PlayQueue(object):
def __init__(self, current_file_folder, current_file_list, current_offset):
self.song_list = [current_file_folder.joinpath(
Path(x)) for x in current_file_list]
self.song_list = self.song_list[current_offset:len(self.song_list)]
def pop_song(self):
... | class PlayQueue(object):
| def __init__(self, current_file_folder, current_file_list, current_offset):
self.song_list = [current_file_folder.joinpath(
Path(x)) for x in current_file_list]
self.song_list = self.song_list[current_offset:len(self.song_list)]
def pop_song(self):
if len(self.song_list) > 0... | from pathlib import Path
class PlayQueue(object):
| 10 | 64 | 101 | 5 | 4 | antismap/micpyplayer | src/play_queue.py | Python | PlayQueue | PlayQueue | 4 | 16 | 4 | 5 | b378d4848f5a30c44e23ff30830f2808463c99de | bigcode/the-stack | train |
53025d3aec7eef199a1e3e35 | train | class | class TestV2alpha1PodsMetricStatus(unittest.TestCase):
""" V2alpha1PodsMetricStatus unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testV2alpha1PodsMetricStatus(self):
"""
Test V2alpha1PodsMetricStatus
"""
model = kubernetes.clien... | class TestV2alpha1PodsMetricStatus(unittest.TestCase):
| """ V2alpha1PodsMetricStatus unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testV2alpha1PodsMetricStatus(self):
"""
Test V2alpha1PodsMetricStatus
"""
model = kubernetes.client.models.v2alpha1_pods_metric_status.V2alpha1PodsMetric... | absolute_import
import os
import sys
import unittest
import kubernetes.client
from kubernetes.client.rest import ApiException
from kubernetes.client.models.v2alpha1_pods_metric_status import V2alpha1PodsMetricStatus
class TestV2alpha1PodsMetricStatus(unittest.TestCase):
| 64 | 64 | 95 | 13 | 50 | jraby/kubernetes-client-python | kubernetes/test/test_v2alpha1_pods_metric_status.py | Python | TestV2alpha1PodsMetricStatus | TestV2alpha1PodsMetricStatus | 25 | 38 | 25 | 25 | 8df3f84819b1019900eab5a82a5988b0bfdeb579 | bigcode/the-stack | train |
fcffa868a2afa029c9680422 | train | function | @pytest.fixture
def KeywordAttribute(Serialisable):
from ..base import Bool
class SomeElement(Serialisable):
tagname = "dummy"
_from = Bool()
def __init__(self, _from):
self._from = _from
return SomeElement
| @pytest.fixture
def KeywordAttribute(Serialisable):
| from ..base import Bool
class SomeElement(Serialisable):
tagname = "dummy"
_from = Bool()
def __init__(self, _from):
self._from = _from
return SomeElement
| :r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" r:rId="rId1"/>
"""
node = fromstring(src)
obj = Relation.from_tree(node)
assert obj.rId == "rId1"
@pytest.fixture
def KeywordAttribute(Serialisable):
| 64 | 64 | 61 | 10 | 54 | hfutxqd/openpyxl | openpyxl/descriptors/tests/test_serialisable.py | Python | KeywordAttribute | KeywordAttribute | 121 | 133 | 121 | 122 | a335b7b852dc39beeb9fb596bbd11a8d00481939 | bigcode/the-stack | train |
6d93335dcf7645209f30b3e0 | train | function | @pytest.fixture
def HyphenatedAttribute(Serialisable):
from ..base import Bool
class SomeElement(Serialisable):
tagname = "dummy"
z_order = Bool(hyphenated=True)
a_order = Bool()
def __init__(self, z_order, a_order):
self.z_order = z_order
self.a_order ... | @pytest.fixture
def HyphenatedAttribute(Serialisable):
| from ..base import Bool
class SomeElement(Serialisable):
tagname = "dummy"
z_order = Bool(hyphenated=True)
a_order = Bool()
def __init__(self, z_order, a_order):
self.z_order = z_order
self.a_order = a_order
return SomeElement
|
def test_from_tree(self, KeywordNode):
src = """<dummy><from val="1" /></dummy>"""
el = fromstring(src)
dummy = KeywordNode.from_tree(el)
assert dummy._from.val is True
@pytest.fixture
def HyphenatedAttribute(Serialisable):
| 64 | 64 | 85 | 12 | 51 | hfutxqd/openpyxl | openpyxl/descriptors/tests/test_serialisable.py | Python | HyphenatedAttribute | HyphenatedAttribute | 214 | 228 | 214 | 215 | 4d0c9e1c2cabbbc77a8f51b5a9f6ec5eeda4fb97 | bigcode/the-stack | train |
51e5ca6bfc5c727d9a2c06bc | train | class | class TestKeywordNode:
def test_to_tree(self, KeywordNode, Node):
n = Node(val=True)
dummy = KeywordNode(_from=n)
xml = tostring(dummy.to_tree())
expected = """<dummy><from val="1" /></dummy>"""
diff = compare_xml(xml, expected)
assert diff is None, diff
d... | class TestKeywordNode:
| def test_to_tree(self, KeywordNode, Node):
n = Node(val=True)
dummy = KeywordNode(_from=n)
xml = tostring(dummy.to_tree())
expected = """<dummy><from val="1" /></dummy>"""
diff = compare_xml(xml, expected)
assert diff is None, diff
def test_from_tree(self, K... | isable, Node):
from ..base import Typed
class SomeElement(Serialisable):
tagname = "dummy"
_from = Typed(expected_type=Node)
def __init__(self, _from):
self._from = _from
return SomeElement
class TestKeywordNode:
| 64 | 64 | 125 | 5 | 58 | hfutxqd/openpyxl | openpyxl/descriptors/tests/test_serialisable.py | Python | TestKeywordNode | TestKeywordNode | 190 | 211 | 190 | 192 | f9e50cd1874a5fb8160f8f0840c32be32976a7a2 | bigcode/the-stack | train |
3b90873e609a9bbb841511f7 | train | function | @pytest.fixture
def Relation(Serialisable):
from ..excel import Relation
class Dummy(Serialisable):
tagname = "dummy"
rId = Relation()
def __init__(self, rId=None):
self.rId = rId
return Dummy
| @pytest.fixture
def Relation(Serialisable):
| from ..excel import Relation
class Dummy(Serialisable):
tagname = "dummy"
rId = Relation()
def __init__(self, rId=None):
self.rId = rId
return Dummy
| d2 = Immutable(2)
assert d1 != d2
def test_copy(self, Immutable):
d1 = Immutable({})
from copy import copy
d2 = copy(d1)
assert d1.value is not d2.value
@pytest.fixture
def Relation(Serialisable):
| 64 | 64 | 59 | 9 | 54 | hfutxqd/openpyxl | openpyxl/descriptors/tests/test_serialisable.py | Python | Relation | Relation | 74 | 87 | 74 | 75 | 81aea94e70794bd8fe4fe402261bd3fea1ad79d9 | bigcode/the-stack | train |
c39fac1590dbfc2f4a0fa8f3 | train | function | @pytest.fixture
def Node(Serialisable):
from ..base import Bool
class SomeNode(Serialisable):
tagname = "from"
val = Bool()
def __init__(self, val):
self.val = val
return SomeNode
| @pytest.fixture
def Node(Serialisable):
| from ..base import Bool
class SomeNode(Serialisable):
tagname = "from"
val = Bool()
def __init__(self, val):
self.val = val
return SomeNode
| )
assert diff is None, diff
def test_from_tree(self, KeywordAttribute):
src = """<dummy from="1" />"""
el = fromstring(src)
dummy = KeywordAttribute.from_tree(el)
assert dummy._from is True
@pytest.fixture
def Node(Serialisable):
| 64 | 64 | 56 | 9 | 54 | hfutxqd/openpyxl | openpyxl/descriptors/tests/test_serialisable.py | Python | Node | Node | 158 | 171 | 158 | 160 | 7969d5e54b76ba335c7d2a3bcf49b40774447f70 | bigcode/the-stack | train |
1989fbdc2bb7fa4fe420b4e6 | train | function | @pytest.fixture
def KeywordNode(Serialisable, Node):
from ..base import Typed
class SomeElement(Serialisable):
tagname = "dummy"
_from = Typed(expected_type=Node)
def __init__(self, _from):
self._from = _from
return SomeElement
| @pytest.fixture
def KeywordNode(Serialisable, Node):
| from ..base import Typed
class SomeElement(Serialisable):
tagname = "dummy"
_from = Typed(expected_type=Node)
def __init__(self, _from):
self._from = _from
return SomeElement
| Node(Serialisable):
from ..base import Bool
class SomeNode(Serialisable):
tagname = "from"
val = Bool()
def __init__(self, val):
self.val = val
return SomeNode
@pytest.fixture
def KeywordNode(Serialisable, Node):
| 64 | 64 | 67 | 12 | 51 | hfutxqd/openpyxl | openpyxl/descriptors/tests/test_serialisable.py | Python | KeywordNode | KeywordNode | 174 | 187 | 174 | 176 | 9a94fd5253e589068979317ea346739d40006803 | bigcode/the-stack | train |
142d5b97ae24f1ec7cadd11a | train | class | class TestRelation:
def test_binding(self, Relation):
assert Relation.__namespaced__ == (
("rId", "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}rId"),
)
def test_to_tree(self, Relation):
dummy = Relation("rId1")
xml = tostring(dummy... | class TestRelation:
| def test_binding(self, Relation):
assert Relation.__namespaced__ == (
("rId", "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}rId"),
)
def test_to_tree(self, Relation):
dummy = Relation("rId1")
xml = tostring(dummy.to_tree())
ex... |
@pytest.fixture
def Relation(Serialisable):
from ..excel import Relation
class Dummy(Serialisable):
tagname = "dummy"
rId = Relation()
def __init__(self, rId=None):
self.rId = rId
return Dummy
class TestRelation:
| 64 | 64 | 199 | 4 | 59 | hfutxqd/openpyxl | openpyxl/descriptors/tests/test_serialisable.py | Python | TestRelation | TestRelation | 90 | 118 | 90 | 92 | 9c378aaa31702d27e83a65cb1ca90f364e13fd43 | bigcode/the-stack | train |
1a2b6bea2c628da9d25eff4c | train | function | @pytest.fixture
def Serialisable():
from ..serialisable import Serialisable
return Serialisable
| @pytest.fixture
def Serialisable():
| from ..serialisable import Serialisable
return Serialisable
| # Copyright (c) 2010-2019 openpyxl
import pytest
from openpyxl.xml.functions import fromstring, tostring
from openpyxl.tests.helper import compare_xml
@pytest.fixture
def Serialisable():
| 47 | 64 | 21 | 7 | 39 | hfutxqd/openpyxl | openpyxl/descriptors/tests/test_serialisable.py | Python | Serialisable | Serialisable | 9 | 12 | 9 | 10 | 10440f70e387e10b1dab5dc928693691788c2505 | bigcode/the-stack | train |
426b71e12757e26156a53adc | train | class | class TestHyphenatedAttribute:
def test_to_tree(self, HyphenatedAttribute):
dummy = HyphenatedAttribute(z_order=True, a_order=True)
xml = tostring(dummy.to_tree())
expected = """<dummy z-order="1" a_order="1" />"""
diff = compare_xml(xml, expected)
assert diff is None, di... | class TestHyphenatedAttribute:
| def test_to_tree(self, HyphenatedAttribute):
dummy = HyphenatedAttribute(z_order=True, a_order=True)
xml = tostring(dummy.to_tree())
expected = """<dummy z-order="1" a_order="1" />"""
diff = compare_xml(xml, expected)
assert diff is None, diff
def test_from_tree(self... | tagname = "dummy"
z_order = Bool(hyphenated=True)
a_order = Bool()
def __init__(self, z_order, a_order):
self.z_order = z_order
self.a_order = a_order
return SomeElement
class TestHyphenatedAttribute:
| 64 | 64 | 141 | 7 | 56 | hfutxqd/openpyxl | openpyxl/descriptors/tests/test_serialisable.py | Python | TestHyphenatedAttribute | TestHyphenatedAttribute | 231 | 250 | 231 | 232 | b118525d76d21b06fb6cd53eab963a97d90633f7 | bigcode/the-stack | train |
793aeca6b4c35c875b833aca | train | class | class TestKeywordAttribute:
def test_to_tree(self, KeywordAttribute):
dummy = KeywordAttribute(_from=True)
xml = tostring(dummy.to_tree())
expected = """<dummy from="1" />"""
diff = compare_xml(xml, expected)
assert diff is None, diff
def test_from_tree(self, Keywo... | class TestKeywordAttribute:
| def test_to_tree(self, KeywordAttribute):
dummy = KeywordAttribute(_from=True)
xml = tostring(dummy.to_tree())
expected = """<dummy from="1" />"""
diff = compare_xml(xml, expected)
assert diff is None, diff
def test_from_tree(self, KeywordAttribute):
src = ""... |
def KeywordAttribute(Serialisable):
from ..base import Bool
class SomeElement(Serialisable):
tagname = "dummy"
_from = Bool()
def __init__(self, _from):
self._from = _from
return SomeElement
class TestKeywordAttribute:
| 64 | 64 | 107 | 5 | 58 | hfutxqd/openpyxl | openpyxl/descriptors/tests/test_serialisable.py | Python | TestKeywordAttribute | TestKeywordAttribute | 136 | 155 | 136 | 138 | 7cd0f4c7a62c403952627cba0690bded23ea374f | bigcode/the-stack | train |
9548b79fb1aa69db264c9de0 | train | function | @pytest.fixture
def Immutable(Serialisable):
class Immutable(Serialisable):
__attrs__ = ('value',)
def __init__(self, value=None):
self.value = value
return Immutable
| @pytest.fixture
def Immutable(Serialisable):
| class Immutable(Serialisable):
__attrs__ = ('value',)
def __init__(self, value=None):
self.value = value
return Immutable
| 2010-2019 openpyxl
import pytest
from openpyxl.xml.functions import fromstring, tostring
from openpyxl.tests.helper import compare_xml
@pytest.fixture
def Serialisable():
from ..serialisable import Serialisable
return Serialisable
@pytest.fixture
def Immutable(Serialisable):
| 64 | 64 | 45 | 9 | 54 | hfutxqd/openpyxl | openpyxl/descriptors/tests/test_serialisable.py | Python | Immutable | Immutable | 15 | 25 | 15 | 17 | 9e96bef3f08e22ba0fc36596a10a7aa311e248fe | bigcode/the-stack | train |
5ab9efda9d2eb516b9d6dd12 | train | class | class TestSerialisable:
def test_hash(self, Immutable):
d1 = Immutable()
d2 = Immutable()
assert hash(d1) == hash(d2)
def test_add_attrs(self, Immutable):
d1 = Immutable()
d2 = Immutable(value=2)
assert d1 + d2 == d2
def test_str(self, Immutable):
... | class TestSerialisable:
| def test_hash(self, Immutable):
d1 = Immutable()
d2 = Immutable()
assert hash(d1) == hash(d2)
def test_add_attrs(self, Immutable):
d1 = Immutable()
d2 = Immutable(value=2)
assert d1 + d2 == d2
def test_str(self, Immutable):
d = Immutable()
... | .tests.helper import compare_xml
@pytest.fixture
def Serialisable():
from ..serialisable import Serialisable
return Serialisable
@pytest.fixture
def Immutable(Serialisable):
class Immutable(Serialisable):
__attrs__ = ('value',)
def __init__(self, value=None):
self.value = ... | 77 | 77 | 257 | 5 | 71 | hfutxqd/openpyxl | openpyxl/descriptors/tests/test_serialisable.py | Python | TestSerialisable | TestSerialisable | 28 | 71 | 28 | 29 | d5eef445756bd12485bfa23d9e4a39a3f2d9734c | bigcode/the-stack | train |
08002736f9feea9d27c6192d | train | class | class IntegrationEventHandler(ABC, Generic[ET]):
@abstractmethod
async def handle(self, event: ET) -> None:
pass
| class IntegrationEventHandler(ABC, Generic[ET]):
@abstractmethod
| async def handle(self, event: ET) -> None:
pass
| from abc import ABC, abstractmethod
from app.event.event import IntegrationEvent
from typing import Generic, TypeVar
ET = TypeVar("ET", bound=IntegrationEvent)
class IntegrationEventHandler(ABC, Generic[ET]):
@abstractmethod
| 52 | 64 | 32 | 16 | 36 | NovemberOscar/my-be-architecture | app/event/handler.py | Python | IntegrationEventHandler | IntegrationEventHandler | 8 | 11 | 8 | 9 | d8d2f6dc362010fd87f7e6f6e75bb7001f59143a | bigcode/the-stack | train |
98953f8d9b318c3fd391de32 | train | class | class SSISLogLocation(Model):
"""SSIS package execution log location.
Variables are only populated by the server, and will be ignored when
sending a request.
All required parameters must be populated in order to send to Azure.
:param log_path: Required. The SSIS package execution log path. Type:
... | class SSISLogLocation(Model):
| """SSIS package execution log location.
Variables are only populated by the server, and will be ignored when
sending a request.
All required parameters must be populated in order to send to Azure.
:param log_path: Required. The SSIS package execution log path. Type:
string (or Expression wit... | # 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 ... | 90 | 130 | 434 | 7 | 82 | tzhanl/azure-sdk-for-python | sdk/datafactory/azure-mgmt-datafactory/azure/mgmt/datafactory/models/ssis_log_location_py3.py | Python | SSISLogLocation | SSISLogLocation | 15 | 57 | 15 | 15 | 84be93930dee1cebbaa83fba4a239b0bde0fad56 | bigcode/the-stack | train |
7bd120966efe72bdd8caef94 | train | function | def demosaicing_CFA_Bayer_bilinear(CFA, pattern='RGGB'):
"""
Returns the demosaiced *RGB* colourspace array from given *Bayer* CFA using
bilinear interpolation.
Parameters
----------
CFA : array_like
*Bayer* CFA.
pattern : unicode, optional
**{'RGGB', 'BGGR', 'GRBG', 'GBRG'}... | def demosaicing_CFA_Bayer_bilinear(CFA, pattern='RGGB'):
| """
Returns the demosaiced *RGB* colourspace array from given *Bayer* CFA using
bilinear interpolation.
Parameters
----------
CFA : array_like
*Bayer* CFA.
pattern : unicode, optional
**{'RGGB', 'BGGR', 'GRBG', 'GBRG'}**,
Arrangement of the colour filters on the pixe... | Colour Filter Array) bilinear demosaicing.
References
----------
- :cite:`Losson2010c` : Losson, O., Macaire, L., & Yang, Y. (2010).
Comparison of Color Demosaicing Methods. In Advances in Imaging and
Electron Physics (Vol. 162, pp. 173-265). doi:10.1016/S1076-5670(10)62005-8
"""
from __future__ import divi... | 256 | 256 | 1,049 | 19 | 237 | lwcyjq/colour-demosaicing | colour_demosaicing/bayer/demosaicing/bilinear.py | Python | demosaicing_CFA_Bayer_bilinear | demosaicing_CFA_Bayer_bilinear | 33 | 114 | 33 | 33 | 413e050efeab4ff8318375f6d0462a57a795aefc | bigcode/the-stack | train |
0693dc9b9d81d18cd68bdce0 | train | class | class RPCError(Exception):
def __init__(self, code: int, message: str) -> None:
self.code = code
self.message = message
| class RPCError(Exception):
| def __init__(self, code: int, message: str) -> None:
self.code = code
self.message = message
| ps,
NetworkInfo,
RawTransaction,
)
# Neat trick found in asyncio library for task enumeration
# https://github.com/python/cpython/blob/3.8/Lib/asyncio/tasks.py#L31
_next_rpc_id = itertools.count(1).__next__
class RPCError(Exception):
| 63 | 64 | 35 | 5 | 58 | frstrtr/bitcoin_tools | bitcoin_tools/bitcoinrpc/bitcoin_rpc.py | Python | RPCError | RPCError | 32 | 35 | 32 | 32 | 8b15f50f6765f10f85ed2fa20d69e1a03c964d57 | bigcode/the-stack | train |
8b1cd3a9890646991ec6e4dd | train | class | class BitcoinRPC:
__slots__ = ("_url", "_client")
"""
For list of all available commands, visit:
https://developer.bitcoin.org/reference/rpc/index.html
"""
def __init__(self, host: str, port: int, rpc_user: str, rpc_password: str) -> None:
self._url = self._set_url(host, port)
s... | class BitcoinRPC:
| __slots__ = ("_url", "_client")
"""
For list of all available commands, visit:
https://developer.bitcoin.org/reference/rpc/index.html
"""
def __init__(self, host: str, port: int, rpc_user: str, rpc_password: str) -> None:
self._url = self._set_url(host, port)
self._client = self... | import itertools
from typing import Any, List, Optional, Union
import httpx
import orjson
from typing_extensions import Literal
from ._types import (
BestBlockHash,
BitcoinRPCResponse,
Block,
BlockchainInfo,
BlockCount,
BlockHash,
BlockHeader,
BlockStats,
ChainTips,
ConnectionC... | 189 | 256 | 1,459 | 4 | 184 | frstrtr/bitcoin_tools | bitcoin_tools/bitcoinrpc/bitcoin_rpc.py | Python | BitcoinRPC | BitcoinRPC | 38 | 213 | 38 | 38 | 9eb7787f12fbb6575362d3beafc46a5b3485736f | bigcode/the-stack | train |
f0ed032187f387867e2a2952 | train | class | class Solution:
def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
minimumDiff = 2**31-1; pairs = []
arr.sort()
for i in range(len(arr)-1):
if arr[i+1]-arr[i] < minimumDiff:
minimumDiff = arr[i+1]-arr[i]
for i in range(len(arr)-1):
... | class Solution:
| def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
minimumDiff = 2**31-1; pairs = []
arr.sort()
for i in range(len(arr)-1):
if arr[i+1]-arr[i] < minimumDiff:
minimumDiff = arr[i+1]-arr[i]
for i in range(len(arr)-1):
if arr[i+1]-... | class Solution:
| 3 | 64 | 113 | 3 | 0 | BrynjarGeir/LeetCode | Easy/minimum_absolute_difference.py | Python | Solution | Solution | 1 | 11 | 1 | 1 | 770d4e3a936260dee008dafaf1770b2511fd3d53 | bigcode/the-stack | train |
8df1fa514cbed1518bf65f44 | train | class | class GraphQLApp:
def __init__(
self,
schema: "graphene.Schema",
executor: typing.Any = None,
executor_class: type = None,
graphiql: bool = True,
middleware: typing.Optional[list] = None,
) -> None:
self.schema = schema
self.graphiql = graphiql
... | class GraphQLApp:
| def __init__(
self,
schema: "graphene.Schema",
executor: typing.Any = None,
executor_class: type = None,
graphiql: bool = True,
middleware: typing.Optional[list] = None,
) -> None:
self.schema = schema
self.graphiql = graphiql
self.middlewa... | import json
import typing
from starlette import status
from starlette.background import BackgroundTasks
from starlette.concurrency import run_in_threadpool
from starlette.requests import Request
from starlette.responses import HTMLResponse, JSONResponse, PlainTextResponse, Response
from starlette.types import Receive,... | 160 | 256 | 897 | 5 | 154 | meseta/starlette | starlette/graphql.py | Python | GraphQLApp | GraphQLApp | 22 | 147 | 22 | 22 | 0c4ffcd6b8af8b0bfb56571a1b4954d68a489284 | bigcode/the-stack | train |
769d1268de157205a635d7ed | train | function | def hints(env: PysmtEnv) -> FrozenSet[Hint]:
assert isinstance(env, PysmtEnv)
mgr = env.formula_manager
pc = mgr.Symbol("pc", types.INT)
x = mgr.Symbol("x", types.INT)
y = mgr.Symbol("y", types.INT)
symbs = frozenset([pc, x, y])
m_100 = mgr.Int(-100)
m_1 = mgr.Int(-1)
i_0 = mgr.Int... | def hints(env: PysmtEnv) -> FrozenSet[Hint]:
| assert isinstance(env, PysmtEnv)
mgr = env.formula_manager
pc = mgr.Symbol("pc", types.INT)
x = mgr.Symbol("x", types.INT)
y = mgr.Symbol("y", types.INT)
symbs = frozenset([pc, x, y])
m_100 = mgr.Int(-100)
m_1 = mgr.Int(-1)
i_0 = mgr.Int(0)
i_1 = mgr.Int(1)
i_2 = mgr.Int(2)... | = mgr.And(same_x, same_y)
# pc = 0 -> same
trans.append(mgr.Implies(pcs[0], same))
# pc = 1 -> x' = x + y & same_y
trans.append(mgr.Implies(pcs[1],
mgr.And(mgr.Equals(x_x, mgr.Plus(x, y)),
same_y)))
# pc = 2 -> same_x & y' = y + 1
... | 209 | 209 | 699 | 15 | 193 | EnricoMagnago/F3 | benchmarks/f3_wrong_hints/scaling_software_termination/4-2Nested_false-termination_22.py | Python | hints | hints | 84 | 142 | 84 | 84 | 304ecced2b725c666a836da1c231cde0d247a157 | bigcode/the-stack | train |
9a368f16ac2d9d19cfbd3538 | train | function | def transition_system(env: PysmtEnv) -> Tuple[FrozenSet[FNode], FNode, FNode,
FNode]:
assert isinstance(env, PysmtEnv)
mgr = env.formula_manager
pc = mgr.Symbol("pc", types.INT)
x = mgr.Symbol("x", types.INT)
y = mgr.Symbol("y", types.INT)
x_pc = sym... | def transition_system(env: PysmtEnv) -> Tuple[FrozenSet[FNode], FNode, FNode,
FNode]:
| assert isinstance(env, PysmtEnv)
mgr = env.formula_manager
pc = mgr.Symbol("pc", types.INT)
x = mgr.Symbol("x", types.INT)
y = mgr.Symbol("y", types.INT)
x_pc = symb_to_next(mgr, pc)
x_x = symb_to_next(mgr, x)
x_y = symb_to_next(mgr, y)
symbols = frozenset([pc, x, y])
m_1 = mgr... | from typing import Tuple, FrozenSet
from pysmt.environment import Environment as PysmtEnv
from pysmt.fnode import FNode
import pysmt.typing as types
from utils import symb_to_next
from hint import Hint, Location
def transition_system(env: PysmtEnv) -> Tuple[FrozenSet[FNode], FNode, FNode,
... | 80 | 207 | 690 | 28 | 51 | EnricoMagnago/F3 | benchmarks/f3_wrong_hints/scaling_software_termination/4-2Nested_false-termination_22.py | Python | transition_system | transition_system | 11 | 81 | 11 | 12 | ee7d9122ed3dd418f18e1c09634da5f16f30d0d1 | bigcode/the-stack | train |
ebbf2ed58c382f0ace591ee6 | train | function | def lambda_handler(event, context):
"""Sample pure Lambda function
Parameters
----------
event: dict, required
API Gateway Lambda Proxy Input Format
Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-fo... | def lambda_handler(event, context):
| """Sample pure Lambda function
Parameters
----------
event: dict, required
API Gateway Lambda Proxy Input Format
Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format
context: ... | np
import requests
import warnings
from astropy.utils.data import CacheMissingWarning
from astropy.config import ConfigurationMissingWarning
from astropy.config import InvalidConfigurationItemWarning
warnings.simplefilter('ignore', CacheMissingWarning)
warnings.simplefilter('ignore', ConfigurationMissingWarning)
warni... | 120 | 120 | 402 | 7 | 113 | mustaric/lambda-tess-search | sandbox/app_ffiheader.py | Python | lambda_handler | lambda_handler | 18 | 78 | 18 | 18 | 228b94b80f362cf598d74ed70ebe07ddbc9c035f | bigcode/the-stack | train |
7a0730599476744543db8bfa | train | function | @window.event
def on_mouse_release(x, y, button, modifiers):
print('on_mouse_release(%r, %r, %r, %r' % (x, y, button, modifiers))
| @window.event
def on_mouse_release(x, y, button, modifiers):
| print('on_mouse_release(%r, %r, %r, %r' % (x, y, button, modifiers))
| y, pressure))
@window.event
def on_mouse_press(x, y, button, modifiers):
print('on_mouse_press(%r, %r, %r, %r' % (x, y, button, modifiers))
@window.event
def on_mouse_release(x, y, button, modifiers):
| 64 | 64 | 44 | 16 | 48 | bitcraft/pyglet | examples/tablet.py | Python | on_mouse_release | on_mouse_release | 56 | 58 | 56 | 57 | 8e70babf4765629ecf2f9f03f9130050663a6836 | bigcode/the-stack | train |
9bb9bf7d77609e484982efeb | train | function | @window.event
def on_text(text):
try:
index = int(text) - 1
except ValueError:
return
if not (0 <= index < len(tablets)):
return
name = tablets[i].name
try:
canvas = tablets[i].open(window)
except pyglet.input.DeviceException:
print('Failed to open tabl... | @window.event
def on_text(text):
| try:
index = int(text) - 1
except ValueError:
return
if not (0 <= index < len(tablets)):
return
name = tablets[i].name
try:
canvas = tablets[i].open(window)
except pyglet.input.DeviceException:
print('Failed to open tablet %d on window' % index)
pr... | Tablets:')
for i, tablet in enumerate(tablets):
print(' (%d) %s' % (i + 1, tablet.name))
print('Press number key to open corresponding tablet device.')
else:
print('No tablets found.')
@window.event
def on_text(text):
| 63 | 64 | 200 | 9 | 54 | bitcraft/pyglet | examples/tablet.py | Python | on_text | on_text | 19 | 48 | 19 | 20 | 2ef0cc39636387b30e1d31d9a58a971eae6dfedd | bigcode/the-stack | train |
49322692b311ad5b6863a63e | train | function | @window.event
def on_mouse_press(x, y, button, modifiers):
print('on_mouse_press(%r, %r, %r, %r' % (x, y, button, modifiers))
| @window.event
def on_mouse_press(x, y, button, modifiers):
| print('on_mouse_press(%r, %r, %r, %r' % (x, y, button, modifiers))
| @canvas.event
def on_motion(cursor, x, y, pressure):
print('%s: on_motion(%r, %r, %r, %r)' % (name, cursor, x, y, pressure))
@window.event
def on_mouse_press(x, y, button, modifiers):
| 64 | 64 | 44 | 16 | 48 | bitcraft/pyglet | examples/tablet.py | Python | on_mouse_press | on_mouse_press | 51 | 53 | 51 | 52 | 82d2d44f99e2de96d9cac84f91674ffd74e6f8da | bigcode/the-stack | train |
f8d4249f7ba1fd7589fe8156 | train | function | def init_adv(num_samples, use_new_model='False', use_new_name='', batch_size=1, gpu_id=0,adv_lr_rate=0.01):
if use_new_model and os.path.exists(root_path_completion('predict_module/models/adv_model{}.index'.format(use_new_name))):
model_path = root_path_completion('predict_module/models/adv_model{}'.format(... | def init_adv(num_samples, use_new_model='False', use_new_name='', batch_size=1, gpu_id=0,adv_lr_rate=0.01):
| if use_new_model and os.path.exists(root_path_completion('predict_module/models/adv_model{}.index'.format(use_new_name))):
model_path = root_path_completion('predict_module/models/adv_model{}'.format(use_new_name))
else:
model_path = root_path_completion('predict_module/models/Shake_model')
... | gpu_id, num_samples)
G.BATCH_SIZE = batch_size
G.test_init(lr_rate)
return G
# debug
def init_adv(num_samples, use_new_model='False', use_new_name='', batch_size=1, gpu_id=0,adv_lr_rate=0.01):
| 64 | 64 | 144 | 34 | 29 | shfkdroal/Robot-Learning-in-Mixed-Adversarial-and-Collaborative-Settings | Lib/site-packages/grasp-1.0-py3.5.egg/grasp/predict_module/predict_API.py | Python | init_adv | init_adv | 82 | 92 | 82 | 82 | c62386f1a0b501cab4239c4bd355473e20d6be55 | bigcode/the-stack | train |
6195fd45e7d983716ff5c385 | train | function | def adv_predict_from_img(I, G_adv):
A = Adv_Predictors(I, G_adv)
print('Adv Predicting on samples')
st_time = time.time()
probs, adv_action = A.shakeNet_shake(num_actions= 6, num_samples = 1)
print('Time take: {}s'.format(time.time()-st_time))
del A
return probs,adv_action
| def adv_predict_from_img(I, G_adv):
| A = Adv_Predictors(I, G_adv)
print('Adv Predicting on samples')
st_time = time.time()
probs, adv_action = A.shakeNet_shake(num_actions= 6, num_samples = 1)
print('Time take: {}s'.format(time.time()-st_time))
del A
return probs,adv_action
| 1]
del P
# one patch, one prediction [1, 18], one groundtruth [1,18]
return (center_pt, R, angle, patch_Is_resized, pred)
# debug, adv_precition using shakeNet
def adv_predict_from_img(I, G_adv):
| 64 | 64 | 89 | 10 | 53 | shfkdroal/Robot-Learning-in-Mixed-Adversarial-and-Collaborative-Settings | Lib/site-packages/grasp-1.0-py3.5.egg/grasp/predict_module/predict_API.py | Python | adv_predict_from_img | adv_predict_from_img | 150 | 158 | 150 | 150 | 032c779ef484cba3f2d45e5bab1d71b329effc9e | bigcode/the-stack | train |
38dc503304ccd17adb1b3692 | train | function | def init_detector(num_samples,use_pro_new='False', use_pro_name='', batch_size=1, gpu_id=0, lr_rate=0.01, test_user= False):
# init
if test_user:
if use_pro_new and os.path.exists(root_path_completion2('predict_module/models/pro_model{}.index'.format(use_pro_name))):
model_path = root_path_c... | def init_detector(num_samples,use_pro_new='False', use_pro_name='', batch_size=1, gpu_id=0, lr_rate=0.01, test_user= False):
# init
| if test_user:
if use_pro_new and os.path.exists(root_path_completion2('predict_module/models/pro_model{}.index'.format(use_pro_name))):
model_path = root_path_completion2('predict_module/models/pro_model{}'.format(use_pro_name))
else:
model_path = root_path_completion2('predi... | , center_pt, R, grasp_angle)
# if train: root_path_completion
# if inference: root_path_completion2
def init_detector(num_samples,use_pro_new='False', use_pro_name='', batch_size=1, gpu_id=0, lr_rate=0.01, test_user= False):
# init
| 67 | 67 | 224 | 41 | 25 | shfkdroal/Robot-Learning-in-Mixed-Adversarial-and-Collaborative-Settings | Lib/site-packages/grasp-1.0-py3.5.egg/grasp/predict_module/predict_API.py | Python | init_detector | init_detector | 58 | 76 | 58 | 59 | c3a68e520e8b694225416f40d19984268c1a96e2 | bigcode/the-stack | train |
ba1e0bdd88aa16e2d40bcc7d | train | function | def predict_from_img(image, obj_name, G, timestep, log_dir, is_train=True):
gscale = 0.234
I = cv2.imread(image)
imsize = 896
gsize = int(gscale * imsize)
# detector needs to have been initialized
P = Predictors(I, G)
print('Predicting on samples')
st_time = time.time()
print(colo... | def predict_from_img(image, obj_name, G, timestep, log_dir, is_train=True):
| gscale = 0.234
I = cv2.imread(image)
imsize = 896
gsize = int(gscale * imsize)
# detector needs to have been initialized
P = Predictors(I, G)
print('Predicting on samples')
st_time = time.time()
print(colored('is_train in predict_from_img: {}'.format(is_train),'red'))
P.graspN... | adv_lr_rate=0.01):
if use_new_model and os.path.exists(root_path_completion('predict_module/models/adv_model{}.index'.format(use_new_name))):
model_path = root_path_completion('predict_module/models/adv_model{}'.format(use_new_name))
else:
model_path = root_path_completion('predict_module/models... | 145 | 145 | 484 | 20 | 124 | shfkdroal/Robot-Learning-in-Mixed-Adversarial-and-Collaborative-Settings | Lib/site-packages/grasp-1.0-py3.5.egg/grasp/predict_module/predict_API.py | Python | predict_from_img | predict_from_img | 97 | 144 | 97 | 97 | 2586d36585a6c5ec57a8d25b3e12fa7cfd2514fb | bigcode/the-stack | train |
d168bb6d78cb5413a68e0f4e | train | function | def drawRectangle(I, h, w, t, gsize=300):
I_temp = I
grasp_l = gsize/2.5
grasp_w = gsize/5.0
grasp_angle = t*(np.pi/18)-np.pi/2
points = np.array([[-grasp_l, -grasp_w],
[grasp_l, -grasp_w],
[grasp_l, grasp_w],
[-grasp_l, grasp_w]]... | def drawRectangle(I, h, w, t, gsize=300):
| I_temp = I
grasp_l = gsize/2.5
grasp_w = gsize/5.0
grasp_angle = t*(np.pi/18)-np.pi/2
points = np.array([[-grasp_l, -grasp_w],
[grasp_l, -grasp_w],
[grasp_l, grasp_w],
[-grasp_l, grasp_w]])
R = np.array([[np.cos(grasp_angle), ... | import grasp_obj
from .grasp_predictor import Predictors
from .shake_learner import shake_obj
from .shake_predictor import Predictors as Adv_Predictors
import time
import os
import ipdb
from grasp.utils.mjcf_utils import xml_path_completion
from grasp.utils.mjcf_utils import image_path_completion
from grasp.utils.mjc... | 160 | 160 | 534 | 16 | 143 | shfkdroal/Robot-Learning-in-Mixed-Adversarial-and-Collaborative-Settings | Lib/site-packages/grasp-1.0-py3.5.egg/grasp/predict_module/predict_API.py | Python | drawRectangle | drawRectangle | 23 | 51 | 23 | 23 | ce00410e39faee3b4e0ea3c96990df2b3ea64f53 | bigcode/the-stack | train |
4a8865985393910be6cb2f60 | train | class | class OCRPredictor(nn.Module, _OCRPredictor):
"""Implements an object able to localize and identify text elements in a set of documents
Args:
det_predictor: detection module
reco_predictor: recognition module
"""
def __init__(
self,
det_predictor: DetectionPredictor,
... | class OCRPredictor(nn.Module, _OCRPredictor):
| """Implements an object able to localize and identify text elements in a set of documents
Args:
det_predictor: detection module
reco_predictor: recognition module
"""
def __init__(
self,
det_predictor: DetectionPredictor,
reco_predictor: RecognitionPredictor,
... | # Copyright (C) 2021, Mindee.
# This program is licensed under the Apache License version 2.
# See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.
from typing import Any, List, Union
import numpy as np
import torch
from torch import nn
from doctr.io.elements import Docum... | 141 | 145 | 485 | 12 | 129 | thentgesMindee/doctr | doctr/models/predictor/pytorch.py | Python | OCRPredictor | OCRPredictor | 22 | 78 | 22 | 22 | c1270071485e29e523c5922152452d189334b264 | bigcode/the-stack | train |
b0cc6bcab8fe3ecd3dcef735 | train | class | class BiomeAffinity:
def __init__(self, affinity_scores, specificity_scores, site, decimals):
self._affinity_scores = affinity_scores
self._specificity_scores = specificity_scores
self._site = site
self._decimals = decimals
# Deduct the specificity scores to give biomes with... | class BiomeAffinity:
| def __init__(self, affinity_scores, specificity_scores, site, decimals):
self._affinity_scores = affinity_scores
self._specificity_scores = specificity_scores
self._site = site
self._decimals = decimals
# Deduct the specificity scores to give biomes with more mapped taxas a ... | number of decimals
# used in the samples.
decimals = stabilized_samples.decimals + self._specificity_decimals
specificity_scores = pd.Series([self._taxas_per_biome[biome] * 10 ** -decimals
for biome in self._taxa_biome_matrix],
... | 105 | 105 | 353 | 5 | 100 | petli/brioche | src/brioche/biomization.py | Python | BiomeAffinity | BiomeAffinity | 65 | 101 | 65 | 65 | a240fddb40573905a2483aef1ece8188eda05984 | bigcode/the-stack | train |
ed9ac9f9698feae3f75d68de | train | class | class Biomization:
def __init__(self, pft_taxas, pft_biomes):
# Join the mappings on PFTs to get relationships between taxas and biomes
self._taxa_biome_mapping = pft_biomes.mapping.merge(
pft_taxas.mapping, on='pft', how='outer', sort=False)
# Turn the relationships back into a... | class Biomization:
| def __init__(self, pft_taxas, pft_biomes):
# Join the mappings on PFTs to get relationships between taxas and biomes
self._taxa_biome_mapping = pft_biomes.mapping.merge(
pft_taxas.mapping, on='pft', how='outer', sort=False)
# Turn the relationships back into a matrix indexed by ... | # Copyright 2020 Peter Liljenberg <peter.liljenberg@gmail.com>
# Open source under the MIT license (see LICENSE)
# pylint: disable=import-error
import math
import pandas as pd
class Biomization:
| 50 | 189 | 632 | 4 | 45 | petli/brioche | src/brioche/biomization.py | Python | Biomization | Biomization | 9 | 63 | 9 | 9 | 4951e3910ebac81ab4e61efef56b6b515ccea26f | bigcode/the-stack | train |
4545e1fc4727d6e8bf8bf231 | train | function | def get_timezone():
"""
Grab the system timezone, should generally only be used when we don't have any further
information on what timezone we should be using
:return:
:rtype: pytz.tzinfo.DstTzInfo
"""
# noinspection PyUnresolvedReferences
return tzlocal.get_localzone()
| def get_timezone():
| """
Grab the system timezone, should generally only be used when we don't have any further
information on what timezone we should be using
:return:
:rtype: pytz.tzinfo.DstTzInfo
"""
# noinspection PyUnresolvedReferences
return tzlocal.get_localzone()
| import re
import tzlocal
from datetime import datetime, timedelta
def get_timezone():
| 18 | 64 | 72 | 4 | 13 | elihschiff/Submitty | python_submitty_utils/submitty_utils/dateutils.py | Python | get_timezone | get_timezone | 6 | 15 | 6 | 6 | 287d9a1a76b366190e6aa28e08479290e3476b3f | bigcode/the-stack | train |
b1e0b5a9a84484b20e922186 | train | function | def parse_datetime(date_string):
"""
Given a string that should either represent an absolute date or an arbitrary date, parse this
into a datetime object that is then used. Absolute dates should be in the format of
YYYY-MM-DD HH:MM:SS while arbitrary dates are of the format "+/-# day(s) [at HH:MM:SS]" w... | def parse_datetime(date_string):
| """
Given a string that should either represent an absolute date or an arbitrary date, parse this
into a datetime object that is then used. Absolute dates should be in the format of
YYYY-MM-DD HH:MM:SS while arbitrary dates are of the format "+/-# day(s) [at HH:MM:SS]" where
the last part is optiona... | timezone
without_timezone = datetime.strptime(thedatetime, '%Y-%m-%d %H:%M:%S')
my_timezone = get_timezone()
with_timezone = my_timezone.localize(without_timezone)
except ValueError:
try:
# hoping to find timezone -04
thedatetime =... | 157 | 157 | 525 | 6 | 150 | elihschiff/Submitty | python_submitty_utils/submitty_utils/dateutils.py | Python | parse_datetime | parse_datetime | 85 | 135 | 85 | 85 | 7b842ac49d044795be6d199ae589278a2b88a6ac | bigcode/the-stack | train |
4fbb3097692dc520f71ffca0 | train | function | def get_current_time():
"""
Get the current time, in the timezone set on the server
:return:
"""
return datetime.now(get_timezone())
| def get_current_time():
| """
Get the current time, in the timezone set on the server
:return:
"""
return datetime.now(get_timezone())
| generally only be used when we don't have any further
information on what timezone we should be using
:return:
:rtype: pytz.tzinfo.DstTzInfo
"""
# noinspection PyUnresolvedReferences
return tzlocal.get_localzone()
def get_current_time():
| 64 | 64 | 34 | 5 | 59 | elihschiff/Submitty | python_submitty_utils/submitty_utils/dateutils.py | Python | get_current_time | get_current_time | 18 | 23 | 18 | 18 | e4532ab6a193eb4c6eb2e72ecb9efbd6771c274d | bigcode/the-stack | train |
de504657034b111e1635840c | train | function | def read_submitty_date(s):
"""
Convert a string (with a timezone) to a date time object with a timezone
:param s:
:return:
FIXME: We should not be raising a SystemExit within a utility function
"""
words = s.split()
if len(words) < 2 or len(words) > 3:
raise SystemExit("ERROR: u... | def read_submitty_date(s):
| """
Convert a string (with a timezone) to a date time object with a timezone
:param s:
:return:
FIXME: We should not be raising a SystemExit within a utility function
"""
words = s.split()
if len(words) < 2 or len(words) > 3:
raise SystemExit("ERROR: unexpected date format %s" %... | ()
d = my_timezone.localize(d)
answer = d.strftime("%Y-%m-%d %H:%M:%S%z")
if microseconds:
mlsec = d.strftime("%f")
mlsec = mlsec[0:3]
answer = d.strftime("%Y-%m-%d %H:%M:%S.{} %z".format(mlsec))
return answer
def read_submitty_date(s):
| 93 | 93 | 312 | 7 | 85 | elihschiff/Submitty | python_submitty_utils/submitty_utils/dateutils.py | Python | read_submitty_date | read_submitty_date | 52 | 82 | 52 | 52 | 53dc3bab0f0ffae08f9e323b6a3c0e59f00fc09d | bigcode/the-stack | train |
e65fa5fce8d2d782938a3b8d | train | function | def write_submitty_date(d=get_current_time(),microseconds=False):
"""
Converts a datetime object to a string with a timezone. If the datetime object
does not have a timezone, it'll use the server's timezone.
:param d: datetime object you want to convert to string
:return:
FIXME: We should not ... | def write_submitty_date(d=get_current_time(),microseconds=False):
| """
Converts a datetime object to a string with a timezone. If the datetime object
does not have a timezone, it'll use the server's timezone.
:param d: datetime object you want to convert to string
:return:
FIXME: We should not be printing anything out here
"""
if not isinstance(d, dat... | TzInfo
"""
# noinspection PyUnresolvedReferences
return tzlocal.get_localzone()
def get_current_time():
"""
Get the current time, in the timezone set on the server
:return:
"""
return datetime.now(get_timezone())
def write_submitty_date(d=get_current_time(),microseconds=False):
| 71 | 71 | 239 | 14 | 57 | elihschiff/Submitty | python_submitty_utils/submitty_utils/dateutils.py | Python | write_submitty_date | write_submitty_date | 26 | 49 | 26 | 26 | d563d271ca7adc7bbd5058fd4c05e23c60259ed0 | bigcode/the-stack | train |
ed91a1de06247e286375d3a7 | train | function | def update_q_factor(q, state, action, diff, visits, step, ps):
"""
:param q: Q-table to learn and update
:param state: current sate
:param action: current action
:param diff: difference calculated to update Q factor
:param visits: visit-time table
:param step: current learning step
:par... | def update_q_factor(q, state, action, diff, visits, step, ps):
| """
:param q: Q-table to learn and update
:param state: current sate
:param action: current action
:param diff: difference calculated to update Q factor
:param visits: visit-time table
:param step: current learning step
:param ps: flag for PS employment
:return: updated Q-table
... | q[i, 0] = np.inf
for i in range(0, s.NUM_STATES - 1):
q[i, -1] = np.inf
return q # initialized Q-table
def update_q_factor(q, state, action, diff, visits, step, ps):
| 64 | 64 | 194 | 18 | 45 | LawrenceChengJiaxiang/DT-ACS | qlearning.py | Python | update_q_factor | update_q_factor | 26 | 42 | 26 | 26 | 9a7687a3228bc93fa4c2e709e422841b5f60bd39 | bigcode/the-stack | train |
acddb8d370cb5b21b26dd064 | train | function | def init_q_factor(action_number):
"""
:param action_number: number of actions
:return: initialized Q-table
"""
q = np.zeros([s.NUM_STATES, action_number])
for i in range(1, action_number):
q[0, i] = np.inf
for i in range(0, action_number - 1):
q[-1, i] = np.inf
for i in... | def init_q_factor(action_number):
| """
:param action_number: number of actions
:return: initialized Q-table
"""
q = np.zeros([s.NUM_STATES, action_number])
for i in range(1, action_number):
q[0, i] = np.inf
for i in range(0, action_number - 1):
q[-1, i] = np.inf
for i in range(1, s.NUM_STATES):
q... | """Q-Learning functions"""
import numpy as np
import settings as s
def init_q_factor(action_number):
| 23 | 64 | 150 | 7 | 15 | LawrenceChengJiaxiang/DT-ACS | qlearning.py | Python | init_q_factor | init_q_factor | 7 | 23 | 7 | 7 | 15238e82161e584b6216de0f09f7e6de1d6b097c | bigcode/the-stack | train |
efc5b95c467f5f6372546378 | train | class | class SampleConan(ConanFile):
name = "local-recipe-multi-folders"
settings = "os"
no_copy_source = True
| class SampleConan(ConanFile):
| name = "local-recipe-multi-folders"
settings = "os"
no_copy_source = True
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from conans import ConanFile
class SampleConan(ConanFile):
| 30 | 64 | 34 | 9 | 20 | ccdc-opensource/conan-ccdc-index-tools | test/recipe_loading/local-recipe-multi-folders/all/conanfile.py | Python | SampleConan | SampleConan | 6 | 9 | 6 | 6 | 359aaee1727b8f169e946c594b7e3f81641e60ef | bigcode/the-stack | train |
a3155b19b47ef2a2183d7a28 | train | function | def test_q3_tree_inorder_traversal(capsys, monkeypatch):
inputs = ["6", "1 2 5 3 6 4"]
monkeypatch.setattr('builtins.input', lambda: inputs.pop(0))
q3_tree_inorder_traversal.main()
captured = capsys.readouterr()
output = "1 2 3 4 5 6 "
assert captured.out == output
inputs = ["15", "1 14 3 ... | def test_q3_tree_inorder_traversal(capsys, monkeypatch):
| inputs = ["6", "1 2 5 3 6 4"]
monkeypatch.setattr('builtins.input', lambda: inputs.pop(0))
q3_tree_inorder_traversal.main()
captured = capsys.readouterr()
output = "1 2 3 4 5 6 "
assert captured.out == output
inputs = ["15", "1 14 3 7 4 5 15 6 13 10 11 2 12 8 9"]
monkeypatch.setattr('b... | capsys.readouterr()
output = "2 6 5 4 9 8 12 11 10 13 7 3 15 14 1 "
assert captured.out == output
def test_q3_tree_inorder_traversal(capsys, monkeypatch):
| 64 | 64 | 211 | 17 | 46 | mxdzi/hackerrank | tests/test_problem_solving_data_structures_trees.py | Python | test_q3_tree_inorder_traversal | test_q3_tree_inorder_traversal | 32 | 47 | 32 | 32 | 5ebee537874eb42c4b2e70376ec661608e5dfa79 | bigcode/the-stack | train |
39dec0f511636a6eca8d9ca6 | train | function | def test_q2_tree_postorder_traversal(capsys, monkeypatch):
inputs = ["6", "1 2 5 3 6 4"]
monkeypatch.setattr('builtins.input', lambda: inputs.pop(0))
q2_tree_postorder_traversal.main()
captured = capsys.readouterr()
output = "4 3 6 5 2 1 "
assert captured.out == output
inputs = ["15", "1 1... | def test_q2_tree_postorder_traversal(capsys, monkeypatch):
| inputs = ["6", "1 2 5 3 6 4"]
monkeypatch.setattr('builtins.input', lambda: inputs.pop(0))
q2_tree_postorder_traversal.main()
captured = capsys.readouterr()
output = "4 3 6 5 2 1 "
assert captured.out == output
inputs = ["15", "1 14 3 7 4 5 15 6 13 10 11 2 12 8 9"]
monkeypatch.setattr(... | .pop(0))
q1_tree_preorder_traversal.main()
captured = capsys.readouterr()
output = "1 2 5 3 4 6 "
assert captured.out == output
def test_q2_tree_postorder_traversal(capsys, monkeypatch):
| 64 | 64 | 211 | 17 | 46 | mxdzi/hackerrank | tests/test_problem_solving_data_structures_trees.py | Python | test_q2_tree_postorder_traversal | test_q2_tree_postorder_traversal | 14 | 29 | 14 | 14 | 9649fa3fd1ae90325f12fa2328ae53256fbb0a11 | bigcode/the-stack | train |
280976116656b57188d75f98 | train | function | def test_q4_tree_height_of_a_binary_tree(capsys, monkeypatch):
inputs = ["7", "3 5 2 1 4 6 7"]
monkeypatch.setattr('builtins.input', lambda: inputs.pop(0))
q4_tree_height_of_a_binary_tree.main()
captured = capsys.readouterr()
output = "3\n"
assert captured.out == output
inputs = ["1", "15"... | def test_q4_tree_height_of_a_binary_tree(capsys, monkeypatch):
| inputs = ["7", "3 5 2 1 4 6 7"]
monkeypatch.setattr('builtins.input', lambda: inputs.pop(0))
q4_tree_height_of_a_binary_tree.main()
captured = capsys.readouterr()
output = "3\n"
assert captured.out == output
inputs = ["1", "15"]
monkeypatch.setattr('builtins.input', lambda: inputs.pop(... | = capsys.readouterr()
output = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 "
assert captured.out == output
def test_q4_tree_height_of_a_binary_tree(capsys, monkeypatch):
| 65 | 65 | 217 | 17 | 47 | mxdzi/hackerrank | tests/test_problem_solving_data_structures_trees.py | Python | test_q4_tree_height_of_a_binary_tree | test_q4_tree_height_of_a_binary_tree | 50 | 73 | 50 | 50 | 15a4ae1cfb5549bb7d14c1bf09d8132b932d427d | bigcode/the-stack | train |
234ca7540721a90440f2170c | train | function | def test_q1_tree_preorder_traversal(capsys, monkeypatch):
inputs = ["6", "1 2 5 3 6 4"]
monkeypatch.setattr('builtins.input', lambda: inputs.pop(0))
q1_tree_preorder_traversal.main()
captured = capsys.readouterr()
output = "1 2 5 3 4 6 "
assert captured.out == output
| def test_q1_tree_preorder_traversal(capsys, monkeypatch):
| inputs = ["6", "1 2 5 3 6 4"]
monkeypatch.setattr('builtins.input', lambda: inputs.pop(0))
q1_tree_preorder_traversal.main()
captured = capsys.readouterr()
output = "1 2 5 3 4 6 "
assert captured.out == output
| from problem_solving.data_structures.trees import *
def test_q1_tree_preorder_traversal(capsys, monkeypatch):
| 28 | 64 | 96 | 17 | 11 | mxdzi/hackerrank | tests/test_problem_solving_data_structures_trees.py | Python | test_q1_tree_preorder_traversal | test_q1_tree_preorder_traversal | 4 | 11 | 4 | 4 | 99c715e49c52c1b0de118b575d9ef0cb176c09fb | bigcode/the-stack | train |
85f312bcbf0c0b0424878289 | train | function | def test_q6_tree_level_order_traversal(capsys, monkeypatch):
inputs = ["6", "1 2 5 3 6 4"]
monkeypatch.setattr('builtins.input', lambda: inputs.pop(0))
q6_tree_level_order_traversal.main()
captured = capsys.readouterr()
output = "1 2 5 3 6 4 "
assert captured.out == output
| def test_q6_tree_level_order_traversal(capsys, monkeypatch):
| inputs = ["6", "1 2 5 3 6 4"]
monkeypatch.setattr('builtins.input', lambda: inputs.pop(0))
q6_tree_level_order_traversal.main()
captured = capsys.readouterr()
output = "1 2 5 3 6 4 "
assert captured.out == output
| attr('builtins.input', lambda: inputs.pop(0))
q4_tree_height_of_a_binary_tree.main()
captured = capsys.readouterr()
output = "3\n"
assert captured.out == output
def test_q6_tree_level_order_traversal(capsys, monkeypatch):
| 64 | 64 | 96 | 17 | 46 | mxdzi/hackerrank | tests/test_problem_solving_data_structures_trees.py | Python | test_q6_tree_level_order_traversal | test_q6_tree_level_order_traversal | 76 | 83 | 76 | 76 | 802a598914c33d1afa99bd92615e4eced995e7cb | bigcode/the-stack | train |
467091a547718fdf6d6ca413 | train | class | class MultipleNegativesRankingLoss(nn.Module):
"""
This loss expects as input a batch consisting of sentence pairs (a_1, b_1), (a_2, b_2)..., (a_n, b_n)
where we assume that (a_i, b_i) are a positive pair and (a_i, b_j) for i!=j a negative pair.
For each a_i, it uses all other b_j as negati... | class MultipleNegativesRankingLoss(nn.Module):
| """
This loss expects as input a batch consisting of sentence pairs (a_1, b_1), (a_2, b_2)..., (a_n, b_n)
where we assume that (a_i, b_i) are a positive pair and (a_i, b_j) for i!=j a negative pair.
For each a_i, it uses all other b_j as negative samples, i.e., for a_i, we have 1 positive e... | import torch
from torch import nn, Tensor
from typing import Iterable, Dict
from ..SentenceTransformer import SentenceTransformer
class MultipleNegativesRankingLoss(nn.Module):
| 34 | 156 | 523 | 9 | 24 | azdaly/sentence-transformers | sentence_transformers/losses/MultipleNegativesRankingLoss.py | Python | MultipleNegativesRankingLoss | MultipleNegativesRankingLoss | 6 | 52 | 6 | 6 | dc604b77f899edff48701d5fa671f74b6997a568 | bigcode/the-stack | train |
602c1628f68af50697e464ab | train | class | class SshKey(pulumi.CustomResource):
encoding: pulumi.Output[str]
"""
Specifies the public key encoding format to use in the response. To retrieve the public key in ssh-rsa format, use `SSH`. To retrieve the public key in PEM format, use `PEM`.
"""
fingerprint: pulumi.Output[str]
"""
The MD5... | class SshKey(pulumi.CustomResource):
| encoding: pulumi.Output[str]
"""
Specifies the public key encoding format to use in the response. To retrieve the public key in ssh-rsa format, use `SSH`. To retrieve the public key in PEM format, use `PEM`.
"""
fingerprint: pulumi.Output[str]
"""
The MD5 message digest of the SSH public key... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from .. import utilities, tables
class SshKey(pulumi.CustomResource):
| 78 | 248 | 829 | 10 | 67 | Charliekenney23/pulumi-aws | sdk/python/pulumi_aws/iam/ssh_key.py | Python | SshKey | SshKey | 11 | 90 | 11 | 11 | ecc71b1f887903b6c4326b6487b48b56bcbac42e | bigcode/the-stack | train |
cd4e69c7d3156cfe68a61547 | train | class | class BST(object):
def __init__(self):
self.root = None
def get_root(self):
return self.root
"""
Get the number of elements
Using recursion. Complexity O(logN)
"""
def size(self):
return self.recur_size(self.root)
def recur_size(self, root):
if ... | class BST(object):
| def __init__(self):
self.root = None
def get_root(self):
return self.root
"""
Get the number of elements
Using recursion. Complexity O(logN)
"""
def size(self):
return self.recur_size(self.root)
def recur_size(self, root):
if root is None:
... | """
Implement Binary Search Tree. It has method:
1. Insert
2. Search
3. Size
4. Traversal (Preorder, Inorder, Postorder)
"""
import unittest
class Node(object):
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BST(object):
| 83 | 160 | 535 | 4 | 78 | zhengli0817/algorithms | algorithms/tree/bst/bst.py | Python | BST | BST | 17 | 100 | 17 | 17 | a3c76e910754e9fc7172cdbaeadfda4f56d7f8ec | bigcode/the-stack | train |
0f1beec62e59e8f3a52067fa | train | class | class TestSuite(unittest.TestCase):
def setUp(self):
self.tree = BST()
self.tree.insert(10)
self.tree.insert(15)
self.tree.insert(6)
self.tree.insert(4)
self.tree.insert(9)
self.tree.insert(12)
self.tree.insert(24)
self.tree.insert(7)
s... | class TestSuite(unittest.TestCase):
| def setUp(self):
self.tree = BST()
self.tree.insert(10)
self.tree.insert(15)
self.tree.insert(6)
self.tree.insert(4)
self.tree.insert(9)
self.tree.insert(12)
self.tree.insert(24)
self.tree.insert(7)
self.tree.insert(20)
self.tre... | 10
/ \
6 15
/ \ / \
4 9 12 24
/ / \
7 20 30
/
18
"""
class TestSuite(unittest.TestCase):
| 64 | 64 | 139 | 7 | 57 | zhengli0817/algorithms | algorithms/tree/bst/bst.py | Python | TestSuite | TestSuite | 116 | 136 | 116 | 116 | 494daf0dca18aff201946e0f7774ae128aed6556 | bigcode/the-stack | train |
1b432ac6b41e15337e928906 | train | class | class Node(object):
def __init__(self, data):
self.data = data
self.left = None
self.right = None
| class Node(object):
| def __init__(self, data):
self.data = data
self.left = None
self.right = None
| """
Implement Binary Search Tree. It has method:
1. Insert
2. Search
3. Size
4. Traversal (Preorder, Inorder, Postorder)
"""
import unittest
class Node(object):
| 52 | 64 | 31 | 4 | 47 | zhengli0817/algorithms | algorithms/tree/bst/bst.py | Python | Node | Node | 11 | 15 | 11 | 11 | c77a0b297595aa5e46b81b051973d5ff423987c2 | bigcode/the-stack | train |
b75e88c923884783c378e374 | train | class | class Migration(migrations.Migration):
dependencies = [
('learn_word', '0014_auto_20200509_1006'),
]
operations = [
migrations.AddField(
model_name='wordlearnsetting',
name='show_mean',
field=models.BooleanField(default=True),
),
migratio... | class Migration(migrations.Migration):
| dependencies = [
('learn_word', '0014_auto_20200509_1006'),
]
operations = [
migrations.AddField(
model_name='wordlearnsetting',
name='show_mean',
field=models.BooleanField(default=True),
),
migrations.AddField(
model_name='wor... | # Generated by Django 3.0.5 on 2020-05-09 02:19
from django.db import migrations, models
class Migration(migrations.Migration):
| 38 | 64 | 127 | 7 | 30 | kamei002/LET | src/learn_word/migrations/0015_auto_20200509_1119.py | Python | Migration | Migration | 6 | 28 | 6 | 7 | dc2bca95db67e47dfba18c95fd011aa5272598b8 | bigcode/the-stack | train |
9d928fa1916705d463a5b026 | train | function | def exp10(x):
"""Calculate 10**x
Parameters
----------
x : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.exp10", x)
| def exp10(x):
| """Calculate 10**x
Parameters
----------
x : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.exp10", x)
| exp2(x):
"""Calculate 2**x
Parameters
----------
x : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.exp2", x)
def exp10(x):
| 64 | 64 | 60 | 5 | 59 | XiaoSong9905/tvm | python/tvm/tir/op.py | Python | exp10 | exp10 | 402 | 415 | 402 | 402 | 3272559f9e47ca7fd40b7e747aa043d290158d35 | bigcode/the-stack | train |
37b65abb8b86456fdf828ba0 | train | function | def call_pure_extern(dtype, func_name, *args, span=None):
"""Build expression by calling a pure extern function.
Parameters
----------
dtype : str
The data type of the result.
func_name: str
The extern function name.
args : list
Positional arguments.
span : Option... | def call_pure_extern(dtype, func_name, *args, span=None):
| """Build expression by calling a pure extern function.
Parameters
----------
dtype : str
The data type of the result.
func_name: str
The extern function name.
args : list
Positional arguments.
span : Optional[Span]
The location of this operator in the sour... | : Optional[Span]
The location of this operator in the source code.
Returns
-------
call : PrimExpr
The call expression.
"""
return Call(dtype, func_name, convert(args), span)
def call_pure_extern(dtype, func_name, *args, span=None):
| 64 | 64 | 136 | 17 | 47 | XiaoSong9905/tvm | python/tvm/tir/op.py | Python | call_pure_extern | call_pure_extern | 104 | 128 | 104 | 104 | cb5c27abc0cb26d292718116f4ba2981b2d30e3b | bigcode/the-stack | train |
1d62df0159f0c59bf3c6a1d5 | train | function | def copysign(x1, x2):
"""Change the sign of x1 to that of x2, element-wise.
Parameters
----------
x1 : PrimExpr
Input argument.
x2 : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x1.dtype, "tir.copysign", x1, x... | def copysign(x1, x2):
| """Change the sign of x1 to that of x2, element-wise.
Parameters
----------
x1 : PrimExpr
Input argument.
x2 : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x1.dtype, "tir.copysign", x1, x2) # type: ignore
| x2 : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x1.dtype, "tir.hypot", x1, x2) # type: ignore
def copysign(x1, x2):
| 64 | 64 | 99 | 10 | 53 | XiaoSong9905/tvm | python/tvm/tir/op.py | Python | copysign | copysign | 936 | 952 | 936 | 936 | ae7ff0511fe7c21a0406a7742b2b7750e5d34897 | bigcode/the-stack | train |
788854953dbe53354e70e95c | train | function | def truncmod(a, b, span=None):
"""Compute the truncmod of two expressions.
Parameters
----------
a : PrimExpr
The left hand operand
b : PrimExpr
The right hand operand
span : Optional[Span]
The location of this operator in the source.
Returns
-------
res :... | def truncmod(a, b, span=None):
| """Compute the truncmod of two expressions.
Parameters
----------
a : PrimExpr
The left hand operand
b : PrimExpr
The right hand operand
span : Optional[Span]
The location of this operator in the source.
Returns
-------
res : PrimExpr
The result ex... | -------
res : PrimExpr
The result expression.
Note
----
This is the default integer division behavior in C.
"""
return _ffi_api._OpTruncDiv(a, b, span) # type: ignore
def truncmod(a, b, span=None):
| 64 | 64 | 123 | 10 | 53 | XiaoSong9905/tvm | python/tvm/tir/op.py | Python | truncmod | truncmod | 1,256 | 1,279 | 1,256 | 1,256 | f19f3b50e13274c66b86ab9a6ae5ac99ba5e5601 | bigcode/the-stack | train |
7022d36101a27a14c5d69d24 | train | function | def q_multiply_shift(x, y, q, s):
"""Execute a multiplication between two Q-numbers x and y
followed by a right shift s. The mathematical expression is:
out = round(x*y*2^-s)
More about Q-numbers here: https://en.wikipedia.org/wiki/Q_(number_format)
The rounding rule is to the nearest value, ro... | def q_multiply_shift(x, y, q, s):
| """Execute a multiplication between two Q-numbers x and y
followed by a right shift s. The mathematical expression is:
out = round(x*y*2^-s)
More about Q-numbers here: https://en.wikipedia.org/wiki/Q_(number_format)
The rounding rule is to the nearest value, rounding half up
(i.e., round(x.... | in input x.
Parameters
----------
x : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.popcount", x)
def q_multiply_shift(x, y, q, s):
| 64 | 64 | 209 | 13 | 51 | XiaoSong9905/tvm | python/tvm/tir/op.py | Python | q_multiply_shift | q_multiply_shift | 1,069 | 1,095 | 1,069 | 1,069 | ae8812a4bfa478b56c9a749b66f18453a039b16b | bigcode/the-stack | train |
7c42354b39dff4e3047a54b7 | train | function | def sigmoid(x):
"""Quick function to get sigmoid
Parameters
----------
x : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.sigmoid", x)
| def sigmoid(x):
| """Quick function to get sigmoid
Parameters
----------
x : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.sigmoid", x)
| ):
"""Take hyperbolic tanh of input x.
Parameters
----------
x : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.tanh", x)
def sigmoid(x):
| 64 | 64 | 59 | 4 | 60 | XiaoSong9905/tvm | python/tvm/tir/op.py | Python | sigmoid | sigmoid | 450 | 463 | 450 | 450 | faa2e42545a21a0a28eba9c319faa63d8ca81b88 | bigcode/the-stack | train |
30d7f4edcd7dd4b286fe6cfd | train | function | def floordiv(a, b, span=None):
"""Compute the floordiv of two expressions.
Parameters
----------
a : PrimExpr
The left hand operand
b : PrimExpr
The right hand operand
span : Optional[Span]
The location of this operator in the source.
Returns
-------
res :... | def floordiv(a, b, span=None):
| """Compute the floordiv of two expressions.
Parameters
----------
a : PrimExpr
The left hand operand
b : PrimExpr
The right hand operand
span : Optional[Span]
The location of this operator in the source.
Returns
-------
res : PrimExpr
The result ex... | -------
res : PrimExpr
The result expression.
Note
----
This is the default integer division behavior in C.
"""
return _ffi_api._OpTruncMod(a, b, span) # type: ignore
def floordiv(a, b, span=None):
| 64 | 64 | 107 | 11 | 52 | XiaoSong9905/tvm | python/tvm/tir/op.py | Python | floordiv | floordiv | 1,282 | 1,301 | 1,282 | 1,282 | 720ff8ea672fafca70ea7e338b544dca94f81ca8 | bigcode/the-stack | train |
e9e1bb8b26a8c7c7c85f259c | train | function | def call_llvm_pure_intrin(dtype, name, *args, span=None):
"""Build expression by calling a pure llvm intrinsic function
Parameters
----------
dtype : str
The data type of the result.
name : str
The name of the llvm intrinsic function.
args : list
Poistional arguments.
... | def call_llvm_pure_intrin(dtype, name, *args, span=None):
| """Build expression by calling a pure llvm intrinsic function
Parameters
----------
dtype : str
The data type of the result.
name : str
The name of the llvm intrinsic function.
args : list
Poistional arguments.
span : Optional[Span]
The location of this opera... | intrinsic" % name
return call_intrin(
dtype, Op.get("tir.call_llvm_intrin"), tvm.tir.const(llvm_id, "uint32"), *args, span=span
)
def call_llvm_pure_intrin(dtype, name, *args, span=None):
| 64 | 64 | 210 | 18 | 46 | XiaoSong9905/tvm | python/tvm/tir/op.py | Python | call_llvm_pure_intrin | call_llvm_pure_intrin | 190 | 223 | 190 | 190 | 7da9d581629be030ea4fb3884162e427f6c0532a | bigcode/the-stack | train |
e977d1fe49e57569ac5883ac | train | function | def if_then_else(cond, t, f, span=None):
"""Conditional selection expression.
Parameters
----------
cond : PrimExpr
The condition
t : PrimExpr
The result expression if cond is true.
f : PrimExpr
The result expression if cond is false.
span : Optional[Span]
... | def if_then_else(cond, t, f, span=None):
| """Conditional selection expression.
Parameters
----------
cond : PrimExpr
The condition
t : PrimExpr
The result expression if cond is true.
f : PrimExpr
The result expression if cond is false.
span : Optional[Span]
The location of this operator in the sou... | PrimExpr
Input argument.
y : PrimExpr
Input argument.
Returns
-------
z : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.fmod", x, y)
def if_then_else(cond, t, f, span=None):
| 64 | 64 | 190 | 13 | 51 | XiaoSong9905/tvm | python/tvm/tir/op.py | Python | if_then_else | if_then_else | 1,116 | 1,146 | 1,116 | 1,116 | dcb5f9bad50c04055885fc8628023ca98fa0ba5e | bigcode/the-stack | train |
55a6e3decfef9235d772d03c | train | function | def sqrt(x):
"""Take square root of input x.
Parameters
----------
x : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.sqrt", x)
| def sqrt(x):
| """Take square root of input x.
Parameters
----------
x : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.sqrt", x)
| ----------
x1 : PrimExpr
Input argument.
x2 : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x1.dtype, "tir.atan2", x1, x2)
def sqrt(x):
| 64 | 64 | 59 | 4 | 60 | XiaoSong9905/tvm | python/tvm/tir/op.py | Python | sqrt | sqrt | 725 | 738 | 725 | 725 | d9d1dad8a750d60031fd00fbc77af3f631dcb920 | bigcode/the-stack | train |
67a5487fdf01f60c24c349f9 | train | function | def nextafter(x1, x2):
"""Return the next floating-point value after x1 towards x2.
Parameters
----------
x1 : PrimExpr
Input argument.
x2 : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x1.dtype, "tir.nextafte... | def nextafter(x1, x2):
| """Return the next floating-point value after x1 towards x2.
Parameters
----------
x1 : PrimExpr
Input argument.
x2 : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x1.dtype, "tir.nextafter", x1, x2) # type: ig... | .
span : Optional[Span]
The location of this operator in the source code.
Returns
-------
y : PrimExpr
The result.
"""
return _ffi_api.nearbyint(x, span) # type: ignore
def nextafter(x1, x2):
| 64 | 64 | 94 | 9 | 54 | XiaoSong9905/tvm | python/tvm/tir/op.py | Python | nextafter | nextafter | 898 | 914 | 898 | 898 | 90c0b155094f74e76aaba4eb184681b51b22b72d | bigcode/the-stack | train |
0f859794b807666bf7a122ff | train | function | def sinh(x):
"""Take sinh of input x.
Parameters
----------
x : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.sinh", x)
| def sinh(x):
| """Take sinh of input x.
Parameters
----------
x : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.sinh", x)
| x)
def sin(x):
"""Take sin of input x.
Parameters
----------
x : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.sin", x)
def sinh(x):
| 64 | 64 | 59 | 4 | 60 | XiaoSong9905/tvm | python/tvm/tir/op.py | Python | sinh | sinh | 626 | 639 | 626 | 626 | f63f26168e9e291185ce667281cd5d7a8db188bf | bigcode/the-stack | train |
318d2c7bee3276a7275531eb | train | function | def atanh(x):
"""Take atanh of input x.
Parameters
----------
x : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.atanh", x)
| def atanh(x):
| """Take atanh of input x.
Parameters
----------
x : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.atanh", x)
| )
def atan(x):
"""Take atan of input x.
Parameters
----------
x : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.atan", x)
def atanh(x):
| 64 | 64 | 61 | 5 | 59 | XiaoSong9905/tvm | python/tvm/tir/op.py | Python | atanh | atanh | 690 | 703 | 690 | 690 | bef4cfa2a25c6991309177144bdcc0bd24c455bc | bigcode/the-stack | train |
dce01c151f1ac441000aa7ad | train | function | def isnan(x, span=None):
"""Check if input value is Nan.
Parameters
----------
x : PrimExpr
Input argument.
span : Optional[Span]
The location of this operator in the source code.
Returns
-------
y : PrimExpr
The result.
"""
return _ffi_api.isnan(x, spa... | def isnan(x, span=None):
| """Check if input value is Nan.
Parameters
----------
x : PrimExpr
Input argument.
span : Optional[Span]
The location of this operator in the source code.
Returns
-------
y : PrimExpr
The result.
"""
return _ffi_api.isnan(x, span) # type: ignore
| argument.
x2 : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x1.dtype, "tir.ldexp", x1, x2) # type: ignore
def isnan(x, span=None):
| 64 | 64 | 83 | 8 | 55 | XiaoSong9905/tvm | python/tvm/tir/op.py | Python | isnan | isnan | 974 | 990 | 974 | 974 | 4b83eaf0f07643a4753df712b52df697f7bea8f3 | bigcode/the-stack | train |
abd4706cef822541368a432d | train | function | def exp(x):
"""Take exponential of input x.
Parameters
----------
x : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.exp", x)
| def exp(x):
| """Take exponential of input x.
Parameters
----------
x : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.exp", x)
| The data type.
span : Optional[Span]
The location of this operator in the source code.
Returns
-------
value : tvm.Expr
The maximum value of dtype.
"""
return _ffi_api.max_value(dtype, span) # type: ignore
def exp(x):
| 64 | 64 | 58 | 4 | 59 | XiaoSong9905/tvm | python/tvm/tir/op.py | Python | exp | exp | 370 | 383 | 370 | 370 | d11874abf76aca29fcb81e808d4d43dca3fe08e5 | bigcode/the-stack | train |
2b03668456a866a6014172ba | train | function | def ldexp(x1, x2):
"""Returns x1 * (2 ** x2).
Parameters
----------
x1 : PrimExpr
Input argument.
x2 : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x1.dtype, "tir.ldexp", x1, x2) # type: ignore
| def ldexp(x1, x2):
| """Returns x1 * (2 ** x2).
Parameters
----------
x1 : PrimExpr
Input argument.
x2 : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x1.dtype, "tir.ldexp", x1, x2) # type: ignore
| x2 : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x1.dtype, "tir.copysign", x1, x2) # type: ignore
def ldexp(x1, x2):
| 64 | 64 | 91 | 9 | 54 | XiaoSong9905/tvm | python/tvm/tir/op.py | Python | ldexp | ldexp | 955 | 971 | 955 | 955 | 00e3a55bcf98fa0f5ceeea7367269ffcb80016fb | bigcode/the-stack | train |
3f741f8594bf3238075fb2bb | train | function | def log(x):
"""Take log of input x.
Parameters
----------
x : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.log", x)
| def log(x):
| """Take log of input x.
Parameters
----------
x : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.log", x)
| )
def sigmoid(x):
"""Quick function to get sigmoid
Parameters
----------
x : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.sigmoid", x)
def log(x):
| 64 | 64 | 58 | 4 | 60 | XiaoSong9905/tvm | python/tvm/tir/op.py | Python | log | log | 466 | 479 | 466 | 466 | f2f22422afc77fca24e15c216687c81d6a157ed8 | bigcode/the-stack | train |
6fd1f169d00e4f899d9ec7d6 | train | function | def isinf(x, span=None):
"""Check if input value is infinite.
Parameters
----------
x : PrimExpr
Input argument.
span : Optional[Span]
The location of this operator in the source code.
Returns
-------
y : PrimExpr
The result.
"""
return _ffi_api.isinf(x... | def isinf(x, span=None):
| """Check if input value is infinite.
Parameters
----------
x : PrimExpr
Input argument.
span : Optional[Span]
The location of this operator in the source code.
Returns
-------
y : PrimExpr
The result.
"""
return _ffi_api.isinf(x, span) # type: ignore
| Input argument.
span : Optional[Span]
The location of this operator in the source code.
Returns
-------
y : PrimExpr
The result.
"""
return _ffi_api.isfinite(x, span) # type: ignore
def isinf(x, span=None):
| 64 | 64 | 84 | 8 | 55 | XiaoSong9905/tvm | python/tvm/tir/op.py | Python | isinf | isinf | 1,012 | 1,028 | 1,012 | 1,012 | 0a8b43450728f23027944b15b4032f4692f02ffa | bigcode/the-stack | train |
07900c0a77764db8d00f25a6 | train | function | def ret(val):
"""Create a tir return expression
Parameters
----------
val : Expr
The returned tir expression, whose data type is int, float or void pointer.
Returns
-------
ret : PrimExpr
The return expression
"""
return call_intrin(val.dtype, "tir.ret", val)
| def ret(val):
| """Create a tir return expression
Parameters
----------
val : Expr
The returned tir expression, whose data type is int, float or void pointer.
Returns
-------
ret : PrimExpr
The return expression
"""
return call_intrin(val.dtype, "tir.ret", val)
| 0, "%s is not an LLVM intrinsic" % name
return call_intrin(
dtype,
Op.get("tir.call_llvm_pure_intrin"),
tvm.tir.const(llvm_id, "uint32"),
*args,
span=span,
)
def ret(val):
| 64 | 64 | 71 | 4 | 60 | XiaoSong9905/tvm | python/tvm/tir/op.py | Python | ret | ret | 226 | 239 | 226 | 226 | 880808aae3496b61e5b8a29d2f69fe15cbb541d6 | bigcode/the-stack | train |
fecc341e611cece20fc93ad2 | train | function | def erf(x):
"""Take gauss error function of the input x.
Parameters
----------
x : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.erf", x)
| def erf(x):
| """Take gauss error function of the input x.
Parameters
----------
x : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.erf", x)
| def exp10(x):
"""Calculate 10**x
Parameters
----------
x : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.exp10", x)
def erf(x):
| 64 | 64 | 63 | 4 | 60 | XiaoSong9905/tvm | python/tvm/tir/op.py | Python | erf | erf | 418 | 431 | 418 | 418 | 3e2441e6da2a30e07dd59d938d814cb45f42dcd8 | bigcode/the-stack | train |
00babc02909433b78143d1da | train | function | def max_value(dtype: str, span: Optional[Span] = None) -> Any:
"""maximum value of dtype
Parameters
----------
dtype : str
The data type.
span : Optional[Span]
The location of this operator in the source code.
Returns
-------
value : tvm.Expr
The maximum value ... | def max_value(dtype: str, span: Optional[Span] = None) -> Any:
| """maximum value of dtype
Parameters
----------
dtype : str
The data type.
span : Optional[Span]
The location of this operator in the source code.
Returns
-------
value : tvm.Expr
The maximum value of dtype.
"""
return _ffi_api.max_value(dtype, span) #... | this operator in the source code.
Returns
-------
value : tvm.Expr
The minimum value of dtype.
"""
return _ffi_api.min_value(dtype, span) # type: ignore
def max_value(dtype: str, span: Optional[Span] = None) -> Any:
| 64 | 64 | 97 | 19 | 44 | XiaoSong9905/tvm | python/tvm/tir/op.py | Python | max_value | max_value | 351 | 367 | 351 | 351 | 2e9fa0afda95ba9583d509205dca13e078e9467c | bigcode/the-stack | train |
75badbe1b6ba6bf96ed21d88 | train | function | def clz(x):
"""Count leading zero bits of an integer x.
Parameters
----------
x : PrimExpr
Input 32 or 64 bit integer.
The result is undefined if the input is 0.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin("int32", "tir.clz", x)
| def clz(x):
| """Count leading zero bits of an integer x.
Parameters
----------
x : PrimExpr
Input 32 or 64 bit integer.
The result is undefined if the input is 0.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin("int32", "tir.clz", x)
| ):
"""Take reciprocal of square root of input x.
Parameters
----------
x : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.rsqrt", x)
def clz(x):
| 64 | 64 | 82 | 5 | 59 | XiaoSong9905/tvm | python/tvm/tir/op.py | Python | clz | clz | 757 | 771 | 757 | 757 | 1264dcb193532f4a6ade10b7761b46b6e5880b14 | bigcode/the-stack | train |
77ce52ad53524a398243da8d | train | function | def log1p(x):
"""Take log(x + 1) with respect to input x.
Parameters
----------
x : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.log1p", x)
| def log1p(x):
| """Take log(x + 1) with respect to input x.
Parameters
----------
x : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.log1p", x)
| (x):
"""Take log10 of input x.
Parameters
----------
x : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.log10", x)
def log1p(x):
| 64 | 64 | 69 | 6 | 58 | XiaoSong9905/tvm | python/tvm/tir/op.py | Python | log1p | log1p | 514 | 527 | 514 | 514 | d6678ea60ef20ea9781bcec7e509f21d2bac47d3 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.