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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
631c1bd1179acfc9b10d8b6d | train | function | def main():
util.run_wsgi_app(app)
| def main():
| util.run_wsgi_app(app)
| .response.out.write('%sfibonacci(%d) == %d # computed in %.3f\n' %
(memo_type, num, ans, t1-t0))
urls = [
('/fibo', FiboHandler),
]
app = webapp.WSGIApplication(urls)
def main():
| 64 | 64 | 10 | 3 | 61 | wmv/appengine-ndb-experiment | demo/fibo.py | Python | main | main | 84 | 85 | 84 | 84 | 5aa298c372e7dc8365a2c62924b1378e3367b90d | bigcode/the-stack | train |
c9d63738f65d69938db60038 | train | class | class FibonacciMemo(ndb.Model):
arg = ndb.IntegerProperty()
value = ndb.IntegerProperty()
| class FibonacciMemo(ndb.Model):
| arg = ndb.IntegerProperty()
value = ndb.IntegerProperty()
| .tasklet
def fibonacci(n):
"""A recursive Fibonacci to exercise task switching."""
if n <= 1:
raise ndb.Return(n)
a, b = yield fibonacci(n-1),fibonacci(n-2)
raise ndb.Return(a + b)
class FibonacciMemo(ndb.Model):
| 64 | 64 | 23 | 7 | 57 | wmv/appengine-ndb-experiment | demo/fibo.py | Python | FibonacciMemo | FibonacciMemo | 24 | 26 | 24 | 24 | dd119d356f803fa5f7a0aa13098df54e5fd96c8a | bigcode/the-stack | train |
2e50289c4e8640d86b3933f9 | train | class | class FiboHandler(webapp.RequestHandler):
@ndb.toplevel
def get(self):
num = 10
try:
num = int(self.request.get('num'))
except Exception:
pass
if self.request.get('reset') in TRUE_VALUES:
logging.info('flush')
yield ndb.delete_multi_async(x.key for x in FibonacciMemo.query()... | class FiboHandler(webapp.RequestHandler):
@ndb.toplevel
| def get(self):
num = 10
try:
num = int(self.request.get('num'))
except Exception:
pass
if self.request.get('reset') in TRUE_VALUES:
logging.info('flush')
yield ndb.delete_multi_async(x.key for x in FibonacciMemo.query())
t0 = time.time()
if self.request.get('memo') in T... | n, memo.value)
yield memo.put_async(ndb_should_cache=False)
raise ndb.Return(ans)
TRUE_VALUES = frozenset(['1', 'on', 't', 'true', 'y', 'yes'])
class FiboHandler(webapp.RequestHandler):
@ndb.toplevel
| 63 | 64 | 177 | 16 | 47 | wmv/appengine-ndb-experiment | demo/fibo.py | Python | FiboHandler | FiboHandler | 53 | 74 | 53 | 55 | 464025cffd19c02ba860c93159c24500eccfdb52 | bigcode/the-stack | train |
716eb749511e9bfa2b27d498 | train | function | @ndb.tasklet
def fibonacci(n):
"""A recursive Fibonacci to exercise task switching."""
if n <= 1:
raise ndb.Return(n)
a, b = yield fibonacci(n-1),fibonacci(n-2)
raise ndb.Return(a + b)
| @ndb.tasklet
def fibonacci(n):
| """A recursive Fibonacci to exercise task switching."""
if n <= 1:
raise ndb.Return(n)
a, b = yield fibonacci(n-1),fibonacci(n-2)
raise ndb.Return(a + b)
| """A web app to test multi-threading."""
import logging
import sys
import threading
import time
from google.appengine.api import memcache
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import ndb
@ndb.tasklet
def fibonacci(n):
| 64 | 64 | 60 | 10 | 53 | wmv/appengine-ndb-experiment | demo/fibo.py | Python | fibonacci | fibonacci | 15 | 21 | 15 | 16 | b60264b31846c9968c3c0200682a94eabee9302b | bigcode/the-stack | train |
b70c59f5179c2f39ccfdf284 | train | class | class TestComponentHistory(unittest.TestCase):
"""Test History component."""
def setUp(self): # pylint: disable=invalid-name
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def tearDown(self): # pylint: disable=invalid-name
"""Stop ever... | class TestComponentHistory(unittest.TestCase):
| """Test History component."""
def setUp(self): # pylint: disable=invalid-name
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def tearDown(self): # pylint: disable=invalid-name
"""Stop everything that was started."""
self.hass.s... | """The tests the History component."""
# pylint: disable=protected-access,invalid-name
from datetime import timedelta
import json
import unittest
from homeassistant.components import history, recorder
from homeassistant.components.recorder.models import process_timestamp
import homeassistant.core as ha
from homeassist... | 140 | 256 | 5,287 | 8 | 131 | gwijsman/home-assistant | tests/components/history/test_init.py | Python | TestComponentHistory | TestComponentHistory | 23 | 733 | 23 | 23 | 2a24f58b6c7601e161de73709d6ceef4199646f1 | bigcode/the-stack | train |
0caf5cc2c048ea1444213c1c | train | function | async def test_fetch_period_api_with_use_include_order(hass, hass_client):
"""Test the fetch period view for history with include order."""
await hass.async_add_executor_job(init_recorder_component, hass)
await async_setup_component(
hass, "history", {history.DOMAIN: {history.CONF_ORDER: True}}
... | async def test_fetch_period_api_with_use_include_order(hass, hass_client):
| """Test the fetch period view for history with include order."""
await hass.async_add_executor_job(init_recorder_component, hass)
await async_setup_component(
hass, "history", {history.DOMAIN: {history.CONF_ORDER: True}}
)
await hass.async_add_job(hass.data[recorder.DATA_INSTANCE].block_till... | .data[recorder.DATA_INSTANCE].block_till_done)
client = await hass_client()
response = await client.get(f"/api/history/period/{dt_util.utcnow().isoformat()}")
assert response.status == 200
async def test_fetch_period_api_with_use_include_order(hass, hass_client):
| 64 | 64 | 126 | 16 | 47 | gwijsman/home-assistant | tests/components/history/test_init.py | Python | test_fetch_period_api_with_use_include_order | test_fetch_period_api_with_use_include_order | 746 | 755 | 746 | 746 | 642a2bbb70119b668c2599f48e951d67de733ae1 | bigcode/the-stack | train |
2e8247a33ff235359128f084 | train | function | async def test_fetch_period_api_with_minimal_response(hass, hass_client):
"""Test the fetch period view for history with minimal_response."""
await hass.async_add_executor_job(init_recorder_component, hass)
await async_setup_component(hass, "history", {})
await hass.async_add_job(hass.data[recorder.DATA... | async def test_fetch_period_api_with_minimal_response(hass, hass_client):
| """Test the fetch period view for history with minimal_response."""
await hass.async_add_executor_job(init_recorder_component, hass)
await async_setup_component(hass, "history", {})
await hass.async_add_job(hass.data[recorder.DATA_INSTANCE].block_till_done)
client = await hass_client()
response ... | .data[recorder.DATA_INSTANCE].block_till_done)
client = await hass_client()
response = await client.get(f"/api/history/period/{dt_util.utcnow().isoformat()}")
assert response.status == 200
async def test_fetch_period_api_with_minimal_response(hass, hass_client):
| 64 | 64 | 118 | 16 | 47 | gwijsman/home-assistant | tests/components/history/test_init.py | Python | test_fetch_period_api_with_minimal_response | test_fetch_period_api_with_minimal_response | 758 | 767 | 758 | 758 | d152edcb082b34fd95751d614b9a6f340d11f91a | bigcode/the-stack | train |
8c7f9ac74e360a6d390d73ce | train | function | async def test_fetch_period_api_with_include_order(hass, hass_client):
"""Test the fetch period view for history."""
await hass.async_add_executor_job(init_recorder_component, hass)
await async_setup_component(
hass,
"history",
{
"history": {
"use_include_... | async def test_fetch_period_api_with_include_order(hass, hass_client):
| """Test the fetch period view for history."""
await hass.async_add_executor_job(init_recorder_component, hass)
await async_setup_component(
hass,
"history",
{
"history": {
"use_include_order": True,
"include": {"entities": ["light.kitchen"]... | ].block_till_done)
client = await hass_client()
response = await client.get(
f"/api/history/period/{dt_util.utcnow().isoformat()}?minimal_response"
)
assert response.status == 200
async def test_fetch_period_api_with_include_order(hass, hass_client):
| 64 | 64 | 162 | 15 | 48 | gwijsman/home-assistant | tests/components/history/test_init.py | Python | test_fetch_period_api_with_include_order | test_fetch_period_api_with_include_order | 770 | 789 | 770 | 770 | fc8692c956ef47967cc0a5b021756628d5b40c00 | bigcode/the-stack | train |
6ac8c735a50d7e0098422ed9 | train | function | async def test_fetch_period_api(hass, hass_client):
"""Test the fetch period view for history."""
await hass.async_add_executor_job(init_recorder_component, hass)
await async_setup_component(hass, "history", {})
await hass.async_add_job(hass.data[recorder.DATA_INSTANCE].block_till_done)
client = awa... | async def test_fetch_period_api(hass, hass_client):
| """Test the fetch period view for history."""
await hass.async_add_executor_job(init_recorder_component, hass)
await async_setup_component(hass, "history", {})
await hass.async_add_job(hass.data[recorder.DATA_INSTANCE].block_till_done)
client = await hass_client()
response = await client.get(f"/... | attributes={"current_temperature": 20})
)
# state will be skipped since entity is hidden
set_state(therm, 22, attributes={"current_temperature": 21, "hidden": True})
return zero, four, states
async def test_fetch_period_api(hass, hass_client):
| 64 | 64 | 104 | 12 | 51 | gwijsman/home-assistant | tests/components/history/test_init.py | Python | test_fetch_period_api | test_fetch_period_api | 736 | 743 | 736 | 736 | 81d1135ed85f65fa162ddcef65f469768a2aa29e | bigcode/the-stack | train |
58d47a34df54a0750a4e6b7c | train | function | @pytest.fixture(autouse=True)
def app_context(app):
"""Creates a flask app context"""
with app.app_context():
yield app
| @pytest.fixture(autouse=True)
def app_context(app):
| """Creates a flask app context"""
with app.app_context():
yield app
| ,)
POSTGRES_PREFIX = '/usr/lib/postgresql/{version}/bin'.format(version='.'.join(map(str, POSTGRES_VERSION)))
@pytest.fixture(scope='session')
def app():
"""Creates the flask app"""
return create_app(testing=True)
@pytest.fixture(autouse=True)
def app_context(app):
| 64 | 64 | 30 | 12 | 52 | indico/ursh | ursh/testing/conftest.py | Python | app_context | app_context | 25 | 29 | 25 | 26 | 21f6b3723ad49cf5fdc6e7d80b561214cc884f4a | bigcode/the-stack | train |
c50ba6c08e3565059aaa9d0f | train | function | @pytest.fixture(scope='session')
def app():
"""Creates the flask app"""
return create_app(testing=True)
| @pytest.fixture(scope='session')
def app():
| """Creates the flask app"""
return create_app(testing=True)
| ursh.core.db import db as db_
POSTGRES_MIN_VERSION = (9, 6)
POSTGRES_VERSION = (12,)
POSTGRES_PREFIX = '/usr/lib/postgresql/{version}/bin'.format(version='.'.join(map(str, POSTGRES_VERSION)))
@pytest.fixture(scope='session')
def app():
| 63 | 64 | 24 | 9 | 54 | indico/ursh | ursh/testing/conftest.py | Python | app | app | 19 | 22 | 19 | 20 | 62b4456bfd1872a37d31d7ca68fd449b6bce0420 | bigcode/the-stack | train |
5e01ae72615eab08caa54d42 | train | function | @pytest.fixture
def request_context(app_context):
"""Creates a flask request context"""
with app_context.test_request_context():
yield
| @pytest.fixture
def request_context(app_context):
| """Creates a flask request context"""
with app_context.test_request_context():
yield
| )
@pytest.fixture(scope='session')
def app():
"""Creates the flask app"""
return create_app(testing=True)
@pytest.fixture(autouse=True)
def app_context(app):
"""Creates a flask app context"""
with app.app_context():
yield app
@pytest.fixture
def request_context(app_context):
| 64 | 64 | 28 | 9 | 54 | indico/ursh | ursh/testing/conftest.py | Python | request_context | request_context | 32 | 36 | 32 | 33 | 75baf44f7dd5ad0abef9e21501345e93f9d0201c | bigcode/the-stack | train |
178343dc01f01975c37b3cf0 | train | function | @pytest.fixture(scope='session')
def database(app, postgresql):
"""Creates a test database which is destroyed afterwards
Used only internally, if you need to access the database use `db` instead to ensure
your modifications are not persistent!
"""
app.config['SQLALCHEMY_DATABASE_URI'] = postgresql
... | @pytest.fixture(scope='session')
def database(app, postgresql):
| """Creates a test database which is destroyed afterwards
Used only internally, if you need to access the database use `db` instead to ensure
your modifications are not persistent!
"""
app.config['SQLALCHEMY_DATABASE_URI'] = postgresql
db_.init_app(app)
if 'URSH_TEST_DATABASE_URI' in os.envir... | )
pytest.skip('Could not stop postgresql; killed it instead: {}'.format(e))
except Exception as e:
pytest.skip('Could not stop/kill postgresql: {}'.format(e))
finally:
shutil.rmtree(temp_dir)
@pytest.fixture(scope='session')
def database(app, postgresql):
| 64 | 64 | 132 | 13 | 51 | indico/ursh | ursh/testing/conftest.py | Python | database | database | 102 | 118 | 102 | 103 | fe7849784d6f6dfd6d749b983158984c2be90b40 | bigcode/the-stack | train |
05fc9e630b87fda059ef25f4 | train | function | @pytest.fixture(scope='session')
def postgresql():
"""Provides a clean temporary PostgreSQL server/database.
If the environment variable `URSH_TEST_DATABASE_URI` is set, this fixture
will do nothing and simply return the connection string from that variable
"""
# Use existing database
if 'URSH_... | @pytest.fixture(scope='session')
def postgresql():
| """Provides a clean temporary PostgreSQL server/database.
If the environment variable `URSH_TEST_DATABASE_URI` is set, this fixture
will do nothing and simply return the connection string from that variable
"""
# Use existing database
if 'URSH_TEST_DATABASE_URI' in os.environ:
yield os.... |
import pytest
from ursh.core.app import create_app
from ursh.core.db import db as db_
POSTGRES_MIN_VERSION = (9, 6)
POSTGRES_VERSION = (12,)
POSTGRES_PREFIX = '/usr/lib/postgresql/{version}/bin'.format(version='.'.join(map(str, POSTGRES_VERSION)))
@pytest.fixture(scope='session')
def app():
"""Creates the fl... | 174 | 174 | 580 | 10 | 164 | indico/ursh | ursh/testing/conftest.py | Python | postgresql | postgresql | 44 | 99 | 44 | 45 | c72d9e63b3f888446aca57a1027167d91bbcf728 | bigcode/the-stack | train |
a21aec03952716e789570a98 | train | function | @pytest.fixture
def client(app):
yield app.test_client()
| @pytest.fixture
def client(app):
| yield app.test_client()
| .fixture(autouse=True)
def app_context(app):
"""Creates a flask app context"""
with app.app_context():
yield app
@pytest.fixture
def request_context(app_context):
"""Creates a flask request context"""
with app_context.test_request_context():
yield
@pytest.fixture
def client(app):
| 64 | 64 | 13 | 7 | 56 | indico/ursh | ursh/testing/conftest.py | Python | client | client | 39 | 41 | 39 | 40 | 4b960470a973fbb7302901bac84f534fb4d6c2fc | bigcode/the-stack | train |
9ddb6bd52a4fd5127efefb85 | train | function | @pytest.fixture
def db(database, monkeypatch):
"""Provides database access and ensures changes do not persist"""
# Prevent database/session modifications
monkeypatch.setattr(database.session, 'commit', database.session.flush)
monkeypatch.setattr(database.session, 'remove', lambda: None)
yield databa... | @pytest.fixture
def db(database, monkeypatch):
| """Provides database access and ensures changes do not persist"""
# Prevent database/session modifications
monkeypatch.setattr(database.session, 'commit', database.session.flush)
monkeypatch.setattr(database.session, 'remove', lambda: None)
yield database
database.session.rollback()
database... | URSH_TEST_DATABASE_URI' in os.environ == '1':
yield db_
return
with app.app_context():
db_.create_all()
yield db_
db_.session.remove()
with app.app_context():
db_.drop_all()
@pytest.fixture
def db(database, monkeypatch):
| 64 | 64 | 73 | 10 | 54 | indico/ursh | ursh/testing/conftest.py | Python | db | db | 121 | 129 | 121 | 122 | 5f1b6eb58b4e6007d9e2d55406dbc2701b2e6900 | bigcode/the-stack | train |
6f0054309195c71af771100c | train | function | def test_integrate():
outs = []
for inp in inputs:
res = Balancer(inp).balance()
outs.append(res)
assert outs == expected_outs
| def test_integrate():
| outs = []
for inp in inputs:
res = Balancer(inp).balance()
outs.append(res)
assert outs == expected_outs
| (HO)2 => 2NH4 + 2HO",
"3FeSO4 + 2K3(Fe(CN)6) => Fe3(Fe(CN)6)2 + 3K2SO4",
'I cant balance it!'
]
def test_integrate():
| 64 | 64 | 37 | 5 | 59 | hamidb80/chem-balancer | python/test.py | Python | test_integrate | test_integrate | 34 | 41 | 34 | 34 | 8e02ce43eb554f51e6e8cdd909c26d495ac196e7 | bigcode/the-stack | train |
18fba9e64d2ae336834dcd0d | train | function | def create_files_from_yaml(fs, files):
create_files(fs, files)
| def create_files_from_yaml(fs, files):
| create_files(fs, files)
| def create_files_from_yaml(fs, files):
| 9 | 64 | 16 | 9 | 0 | Cogmob/tag | src/python/create_files_from_yaml/create_files_from_yaml.py | Python | create_files_from_yaml | create_files_from_yaml | 1 | 2 | 1 | 1 | 002db015b40fa77f2499051464fe620f1c7a280c | bigcode/the-stack | train |
9dc0861f755d4c63791f98da | train | function | def create_files(fs, files):
if 'folders' in files:
for child_folder_name, data in files['folders'].items():
fs.makedir(child_folder_name)
create_files(fs.opendir(child_folder_name), data)
if 'files' in files:
for child_file_name, data in files['files'].items():
... | def create_files(fs, files):
| if 'folders' in files:
for child_folder_name, data in files['folders'].items():
fs.makedir(child_folder_name)
create_files(fs.opendir(child_folder_name), data)
if 'files' in files:
for child_file_name, data in files['files'].items():
fs.setcontents(child_file... | def create_files_from_yaml(fs, files):
create_files(fs, files)
def create_files(fs, files):
| 23 | 64 | 81 | 7 | 16 | Cogmob/tag | src/python/create_files_from_yaml/create_files_from_yaml.py | Python | create_files | create_files | 4 | 12 | 4 | 4 | c62d8a3686271bc172e9841cf1f85ae93e2fffa3 | bigcode/the-stack | train |
9a08036d65079fc6b16d9758 | train | class | class Measurement(MeasurementBase):
params = {
'Vdss': Sweep([10e-3]),
'Vg1s': Sweep([0.1]),
'Vg2s': Sweep([0.]),
'commongate': Boolean(False),
'Rg2': 100e3,
'Rds': 2.2e3,
'stabilise_time': 0.05,
'comment': String(''),
'data_dir': Folder(r'D:\M... | class Measurement(MeasurementBase):
| params = {
'Vdss': Sweep([10e-3]),
'Vg1s': Sweep([0.1]),
'Vg2s': Sweep([0.]),
'commongate': Boolean(False),
'Rg2': 100e3,
'Rds': 2.2e3,
'stabilise_time': 0.05,
'comment': String(''),
'data_dir': Folder(r'D:\MeasurementJANIS\Holger\test'),
... | from __future__ import print_function
from P13pt.mascril.measurement import MeasurementBase
from P13pt.mascril.parameter import Sweep, String, Folder, Boolean
from P13pt.drivers.bilt import Bilt, BiltVoltageSource, BiltVoltMeter
from P13pt.drivers.anritsuvna import AnritsuVNA
from P13pt.drivers.si9700 import SI9700
im... | 112 | 256 | 1,197 | 6 | 105 | green-mercury/P13pt | P13pt/mascril/modules/vna2gates.py | Python | Measurement | Measurement | 14 | 138 | 14 | 14 | bc43821653241fc59ee53e3c7c0640d512339086 | bigcode/the-stack | train |
d168e62b6c0feb188ddc75ea | train | class | class CryptoNewsDataset(torch.utils.data.Dataset):
def __init__(self, samples: List[Dict[str, torch.Tensor]]):
self.samples = samples
def __getitem__(self, key):
if isinstance(key, int) or isinstance(key, slice):
return self.samples[key]
else:
raise TypeError("Cr... | class CryptoNewsDataset(torch.utils.data.Dataset):
| def __init__(self, samples: List[Dict[str, torch.Tensor]]):
self.samples = samples
def __getitem__(self, key):
if isinstance(key, int) or isinstance(key, slice):
return self.samples[key]
else:
raise TypeError("CryptoNewsDataset.__getitem__() invalid key type")
... | from typing import Dict, List
import torch.utils.data
class CryptoNewsDataset(torch.utils.data.Dataset):
| 21 | 64 | 93 | 9 | 11 | UrosOgrizovic/CryptoNewsSummarization | crypto_news_dataset.py | Python | CryptoNewsDataset | CryptoNewsDataset | 6 | 17 | 6 | 6 | 870330a1c5d327402fac4b6fd8b0775376b40de9 | bigcode/the-stack | train |
3e39baa3df0b92abc50e2483 | train | class | class PreviewCreateGameServerClusterRequest(proto.Message):
r"""Request message for
GameServerClustersService.PreviewCreateGameServerCluster.
Attributes:
parent (str):
Required. The parent resource name, in the following form:
``projects/{project}/locations/{location}/realms... | class PreviewCreateGameServerClusterRequest(proto.Message):
| r"""Request message for
GameServerClustersService.PreviewCreateGameServerCluster.
Attributes:
parent (str):
Required. The parent resource name, in the following form:
``projects/{project}/locations/{location}/realms/{realm}``.
game_server_cluster_id (str):
... | .types.GameServerCluster):
Required. The game server cluster resource to
be created.
"""
parent = proto.Field(proto.STRING, number=1,)
game_server_cluster_id = proto.Field(proto.STRING, number=2,)
game_server_cluster = proto.Field(
proto.MESSAGE, number=3, message="GameS... | 82 | 82 | 276 | 10 | 72 | renovate-bot/python-game-servers | google/cloud/gaming_v1/types/game_server_clusters.py | Python | PreviewCreateGameServerClusterRequest | PreviewCreateGameServerClusterRequest | 171 | 201 | 171 | 171 | 0224d94fad3e992d4e24d89b3529c086c6a9bf24 | bigcode/the-stack | train |
d20ac259786b15cd4d1d681c | train | class | class KubernetesClusterState(proto.Message):
r"""The state of the Kubernetes cluster.
Attributes:
agones_version_installed (str):
Output only. The version of Agones currently
installed in the registered Kubernetes cluster.
kubernetes_version_installed (str):
... | class KubernetesClusterState(proto.Message):
| r"""The state of the Kubernetes cluster.
Attributes:
agones_version_installed (str):
Output only. The version of Agones currently
installed in the registered Kubernetes cluster.
kubernetes_version_installed (str):
Output only. The version of Kubernetes that
... | proto.Field(proto.STRING, number=1,)
create_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,)
update_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,)
labels = proto.MapField(proto.STRING, proto.STRING, number=4,)
connection_info = proto.Field(
... | 146 | 146 | 489 | 7 | 139 | renovate-bot/python-game-servers | google/cloud/gaming_v1/types/game_server_clusters.py | Python | KubernetesClusterState | KubernetesClusterState | 429 | 477 | 429 | 429 | 957aafd23ddb401f915c122acd936a837f999ab2 | bigcode/the-stack | train |
0f40574615425f5f0ecbe326 | train | class | class ListGameServerClustersRequest(proto.Message):
r"""Request message for
GameServerClustersService.ListGameServerClusters.
Attributes:
parent (str):
Required. The parent resource name, in the
following form:
"projects/{project}/locations/{location}/realms/{rea... | class ListGameServerClustersRequest(proto.Message):
| r"""Request message for
GameServerClustersService.ListGameServerClusters.
Attributes:
parent (str):
Required. The parent resource name, in the
following form:
"projects/{project}/locations/{location}/realms/{realm}".
page_size (int):
Optional.... | "PreviewDeleteGameServerClusterRequest",
"PreviewDeleteGameServerClusterResponse",
"UpdateGameServerClusterRequest",
"PreviewUpdateGameServerClusterRequest",
"PreviewUpdateGameServerClusterResponse",
"GameServerClusterConnectionInfo",
"GkeClusterReference",
... | 127 | 127 | 425 | 9 | 117 | renovate-bot/python-game-servers | google/cloud/gaming_v1/types/game_server_clusters.py | Python | ListGameServerClustersRequest | ListGameServerClustersRequest | 54 | 96 | 54 | 54 | 6def61b97de77765d53a2177a749045edc35c2e6 | bigcode/the-stack | train |
b44f13fcaa76332a37a47b93 | train | class | class DeleteGameServerClusterRequest(proto.Message):
r"""Request message for
GameServerClustersService.DeleteGameServerCluster.
Attributes:
name (str):
Required. The name of the game server cluster to delete, in
the following form:
``projects/{project}/locations/... | class DeleteGameServerClusterRequest(proto.Message):
| r"""Request message for
GameServerClustersService.DeleteGameServerCluster.
Attributes:
name (str):
Required. The name of the game server cluster to delete, in
the following form:
``projects/{project}/locations/{location}/gameServerClusters/{cluster}``.
"""
... | etag = proto.Field(proto.STRING, number=2,)
target_state = proto.Field(proto.MESSAGE, number=3, message=common.TargetState,)
cluster_state = proto.Field(
proto.MESSAGE, number=4, message="KubernetesClusterState",
)
class DeleteGameServerClusterRequest(proto.Message):
| 64 | 64 | 85 | 9 | 55 | renovate-bot/python-game-servers | google/cloud/gaming_v1/types/game_server_clusters.py | Python | DeleteGameServerClusterRequest | DeleteGameServerClusterRequest | 226 | 237 | 226 | 226 | 55a3bd196ece02a38cafa2ea992a02262d09fff7 | bigcode/the-stack | train |
85a31dda7dd70e013e57216c | train | class | class PreviewUpdateGameServerClusterRequest(proto.Message):
r"""Request message for
GameServerClustersService.UpdateGameServerCluster.
Attributes:
game_server_cluster (google.cloud.gaming_v1.types.GameServerCluster):
Required. The game server cluster to be updated. Only fields
... | class PreviewUpdateGameServerClusterRequest(proto.Message):
| r"""Request message for
GameServerClustersService.UpdateGameServerCluster.
Attributes:
game_server_cluster (google.cloud.gaming_v1.types.GameServerCluster):
Required. The game server cluster to be updated. Only fields
specified in update_mask are updated.
update_mask... | /reference/google.protobuf#fieldmask
"""
game_server_cluster = proto.Field(
proto.MESSAGE, number=1, message="GameServerCluster",
)
update_mask = proto.Field(
proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask,
)
class PreviewUpdateGameServerClusterRequest(proto.Message):
| 69 | 69 | 233 | 10 | 59 | renovate-bot/python-game-servers | google/cloud/gaming_v1/types/game_server_clusters.py | Python | PreviewUpdateGameServerClusterRequest | PreviewUpdateGameServerClusterRequest | 298 | 324 | 298 | 298 | de8c16a1c7d2afa23591d350363c4e6e05a41838 | bigcode/the-stack | train |
b868a1755defd25faf4af593 | train | class | class ListGameServerClustersResponse(proto.Message):
r"""Response message for
GameServerClustersService.ListGameServerClusters.
Attributes:
game_server_clusters (Sequence[google.cloud.gaming_v1.types.GameServerCluster]):
The list of game server clusters.
next_page_token (str):
... | class ListGameServerClustersResponse(proto.Message):
| r"""Response message for
GameServerClustersService.ListGameServerClusters.
Attributes:
game_server_clusters (Sequence[google.cloud.gaming_v1.types.GameServerCluster]):
The list of game server clusters.
next_page_token (str):
Token to retrieve the next page of results... | proto.Field(proto.STRING, number=3,)
filter = proto.Field(proto.STRING, number=4,)
order_by = proto.Field(proto.STRING, number=5,)
view = proto.Field(proto.ENUM, number=6, enum="GameServerClusterView",)
class ListGameServerClustersResponse(proto.Message):
| 64 | 64 | 173 | 9 | 55 | renovate-bot/python-game-servers | google/cloud/gaming_v1/types/game_server_clusters.py | Python | ListGameServerClustersResponse | ListGameServerClustersResponse | 99 | 122 | 99 | 99 | f3b2a8c020a961f5f8af423aefa5e367629b98c4 | bigcode/the-stack | train |
691ae41ff317ce77337e8e75 | train | class | class GameServerClusterConnectionInfo(proto.Message):
r"""The game server cluster connection information.
Attributes:
gke_cluster_reference (google.cloud.gaming_v1.types.GkeClusterReference):
Reference to the GKE cluster where the game
servers are installed.
namespace (s... | class GameServerClusterConnectionInfo(proto.Message):
| r"""The game server cluster connection information.
Attributes:
gke_cluster_reference (google.cloud.gaming_v1.types.GkeClusterReference):
Reference to the GKE cluster where the game
servers are installed.
namespace (str):
Namespace designated on the game serv... | .
target_state (google.cloud.gaming_v1.types.TargetState):
The target state.
"""
etag = proto.Field(proto.STRING, number=2,)
target_state = proto.Field(proto.MESSAGE, number=3, message=common.TargetState,)
class GameServerClusterConnectionInfo(proto.Message):
| 63 | 64 | 146 | 9 | 54 | renovate-bot/python-game-servers | google/cloud/gaming_v1/types/game_server_clusters.py | Python | GameServerClusterConnectionInfo | GameServerClusterConnectionInfo | 342 | 362 | 342 | 342 | 1db9f45aabf1fb84be802b8ac1433a1becae07cd | bigcode/the-stack | train |
3653d22f614177c8b29ab1f9 | train | class | class PreviewDeleteGameServerClusterRequest(proto.Message):
r"""Request message for
GameServerClustersService.PreviewDeleteGameServerCluster.
Attributes:
name (str):
Required. The name of the game server cluster to delete, in
the following form:
``projects/{proje... | class PreviewDeleteGameServerClusterRequest(proto.Message):
| r"""Request message for
GameServerClustersService.PreviewDeleteGameServerCluster.
Attributes:
name (str):
Required. The name of the game server cluster to delete, in
the following form:
``projects/{project}/locations/{location}/gameServerClusters/{cluster}``.
... | str):
Required. The name of the game server cluster to delete, in
the following form:
``projects/{project}/locations/{location}/gameServerClusters/{cluster}``.
"""
name = proto.Field(proto.STRING, number=1,)
class PreviewDeleteGameServerClusterRequest(proto.Message):
| 63 | 64 | 136 | 10 | 53 | renovate-bot/python-game-servers | google/cloud/gaming_v1/types/game_server_clusters.py | Python | PreviewDeleteGameServerClusterRequest | PreviewDeleteGameServerClusterRequest | 240 | 257 | 240 | 240 | baa952652e558e54f5d2b4da5721dcdb34d93da5 | bigcode/the-stack | train |
42a486337e2c2fa90872f313 | train | class | class CreateGameServerClusterRequest(proto.Message):
r"""Request message for
GameServerClustersService.CreateGameServerCluster.
Attributes:
parent (str):
Required. The parent resource name, in the following form:
``projects/{project}/locations/{location}/realms/{realm-id}``.... | class CreateGameServerClusterRequest(proto.Message):
| r"""Request message for
GameServerClustersService.CreateGameServerCluster.
Attributes:
parent (str):
Required. The parent resource name, in the following form:
``projects/{project}/locations/{location}/realms/{realm-id}``.
game_server_cluster_id (str):
Re... | SPECIFIED, same as BASIC, which
does not return the ``cluster_state`` field.
"""
name = proto.Field(proto.STRING, number=1,)
view = proto.Field(proto.ENUM, number=6, enum="GameServerClusterView",)
class CreateGameServerClusterRequest(proto.Message):
| 64 | 64 | 172 | 9 | 55 | renovate-bot/python-game-servers | google/cloud/gaming_v1/types/game_server_clusters.py | Python | CreateGameServerClusterRequest | CreateGameServerClusterRequest | 148 | 168 | 148 | 148 | be6df7b8d449b825f6a59ffd4ad4cd211c970acf | bigcode/the-stack | train |
1cdb8727dcb3cbfe0839ea61 | train | class | class PreviewUpdateGameServerClusterResponse(proto.Message):
r"""Response message for
GameServerClustersService.PreviewUpdateGameServerCluster
Attributes:
etag (str):
The ETag of the game server cluster.
target_state (google.cloud.gaming_v1.types.TargetState):
The ta... | class PreviewUpdateGameServerClusterResponse(proto.Message):
| r"""Response message for
GameServerClustersService.PreviewUpdateGameServerCluster
Attributes:
etag (str):
The ETag of the game server cluster.
target_state (google.cloud.gaming_v1.types.TargetState):
The target state.
"""
etag = proto.Field(proto.STRING, num... | Cluster",
)
update_mask = proto.Field(
proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask,
)
preview_time = proto.Field(
proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,
)
class PreviewUpdateGameServerClusterResponse(proto.Message):
| 64 | 64 | 101 | 10 | 54 | renovate-bot/python-game-servers | google/cloud/gaming_v1/types/game_server_clusters.py | Python | PreviewUpdateGameServerClusterResponse | PreviewUpdateGameServerClusterResponse | 327 | 339 | 327 | 327 | 46517822d97465f264f65cb444cc7658dacd6940 | bigcode/the-stack | train |
b1749141f76e1b95909dd7d9 | train | class | class GkeClusterReference(proto.Message):
r"""A reference to a GKE cluster.
Attributes:
cluster (str):
The full or partial name of a GKE cluster, using one of the
following forms:
- ``projects/{project}/locations/{location}/clusters/{cluster}``
- ``loc... | class GkeClusterReference(proto.Message):
| r"""A reference to a GKE cluster.
Attributes:
cluster (str):
The full or partial name of a GKE cluster, using one of the
following forms:
- ``projects/{project}/locations/{location}/clusters/{cluster}``
- ``locations/{location}/clusters/{cluster}``
... | be validated during creation.
"""
gke_cluster_reference = proto.Field(
proto.MESSAGE,
number=7,
oneof="cluster_reference",
message="GkeClusterReference",
)
namespace = proto.Field(proto.STRING, number=5,)
class GkeClusterReference(proto.Message):
| 63 | 64 | 136 | 8 | 55 | renovate-bot/python-game-servers | google/cloud/gaming_v1/types/game_server_clusters.py | Python | GkeClusterReference | GkeClusterReference | 365 | 381 | 365 | 365 | dc4c889180031159f89d70441d09d9568b776e47 | bigcode/the-stack | train |
9039c04ed423a308bda3aefa | train | class | class GameServerClusterView(proto.Enum):
r"""A view for GameServerCluster objects."""
GAME_SERVER_CLUSTER_VIEW_UNSPECIFIED = 0
BASIC = 1
FULL = 2
| class GameServerClusterView(proto.Enum):
| r"""A view for GameServerCluster objects."""
GAME_SERVER_CLUSTER_VIEW_UNSPECIFIED = 0
BASIC = 1
FULL = 2
| "UpdateGameServerClusterRequest",
"PreviewUpdateGameServerClusterRequest",
"PreviewUpdateGameServerClusterResponse",
"GameServerClusterConnectionInfo",
"GkeClusterReference",
"GameServerCluster",
"KubernetesClusterState",
},
)
class GameServerClusterView(proto.Enum):... | 64 | 64 | 43 | 8 | 56 | renovate-bot/python-game-servers | google/cloud/gaming_v1/types/game_server_clusters.py | Python | GameServerClusterView | GameServerClusterView | 47 | 51 | 47 | 47 | 399581ddb2b73c7abe9dcca6803b3d92d7eb30b5 | bigcode/the-stack | train |
08a345b197a4a58a1b9eb9c4 | train | class | class GetGameServerClusterRequest(proto.Message):
r"""Request message for
GameServerClustersService.GetGameServerCluster.
Attributes:
name (str):
Required. The name of the game server cluster to retrieve,
in the following form:
``projects/{project}/locations/{loc... | class GetGameServerClusterRequest(proto.Message):
| r"""Request message for
GameServerClustersService.GetGameServerCluster.
Attributes:
name (str):
Required. The name of the game server cluster to retrieve,
in the following form:
``projects/{project}/locations/{location}/realms/{realm-id}/gameServerClusters/{clust... |
game_server_clusters = proto.RepeatedField(
proto.MESSAGE, number=1, message="GameServerCluster",
)
next_page_token = proto.Field(proto.STRING, number=2,)
unreachable = proto.RepeatedField(proto.STRING, number=4,)
class GetGameServerClusterRequest(proto.Message):
| 64 | 65 | 217 | 9 | 55 | renovate-bot/python-game-servers | google/cloud/gaming_v1/types/game_server_clusters.py | Python | GetGameServerClusterRequest | GetGameServerClusterRequest | 125 | 145 | 125 | 125 | 17b1d59a83615fbd0473466fb60e55d709889a9f | bigcode/the-stack | train |
7bc12b17915dde6d6e271c97 | train | class | class PreviewCreateGameServerClusterResponse(proto.Message):
r"""Response message for
GameServerClustersService.PreviewCreateGameServerCluster.
Attributes:
etag (str):
The ETag of the game server cluster.
target_state (google.cloud.gaming_v1.types.TargetState):
The t... | class PreviewCreateGameServerClusterResponse(proto.Message):
| r"""Response message for
GameServerClustersService.PreviewCreateGameServerCluster.
Attributes:
etag (str):
The ETag of the game server cluster.
target_state (google.cloud.gaming_v1.types.TargetState):
The target state.
cluster_state (google.cloud.gaming_v1.ty... | , message="GameServerCluster",
)
preview_time = proto.Field(
proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp,
)
view = proto.Field(proto.ENUM, number=6, enum="GameServerClusterView",)
class PreviewCreateGameServerClusterResponse(proto.Message):
| 64 | 64 | 180 | 10 | 54 | renovate-bot/python-game-servers | google/cloud/gaming_v1/types/game_server_clusters.py | Python | PreviewCreateGameServerClusterResponse | PreviewCreateGameServerClusterResponse | 204 | 223 | 204 | 204 | a0f9dd890554da95146faae6f3601d50f7a4fb5c | bigcode/the-stack | train |
3129527e0f3d568eb96116ef | train | class | class PreviewDeleteGameServerClusterResponse(proto.Message):
r"""Response message for
GameServerClustersService.PreviewDeleteGameServerCluster.
Attributes:
etag (str):
The ETag of the game server cluster.
target_state (google.cloud.gaming_v1.types.TargetState):
The t... | class PreviewDeleteGameServerClusterResponse(proto.Message):
| r"""Response message for
GameServerClustersService.PreviewDeleteGameServerCluster.
Attributes:
etag (str):
The ETag of the game server cluster.
target_state (google.cloud.gaming_v1.types.TargetState):
The target state.
"""
etag = proto.Field(proto.STRING, nu... | 2.Timestamp):
Optional. The target timestamp to compute the
preview.
"""
name = proto.Field(proto.STRING, number=1,)
preview_time = proto.Field(
proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,
)
class PreviewDeleteGameServerClusterResponse(proto.Message):
| 64 | 64 | 101 | 10 | 54 | renovate-bot/python-game-servers | google/cloud/gaming_v1/types/game_server_clusters.py | Python | PreviewDeleteGameServerClusterResponse | PreviewDeleteGameServerClusterResponse | 260 | 272 | 260 | 260 | 70873d60381c03d1ad03630a4afc38df7a2af9f6 | bigcode/the-stack | train |
ec34e066b65d517a16166dd6 | train | class | class GameServerCluster(proto.Message):
r"""A game server cluster resource.
Attributes:
name (str):
Required. The resource name of the game server cluster, in
the following form:
``projects/{project}/locations/{location}/realms/{realm}/gameServerClusters/{cluster}``.... | class GameServerCluster(proto.Message):
| r"""A game server cluster resource.
Attributes:
name (str):
Required. The resource name of the game server cluster, in
the following form:
``projects/{project}/locations/{location}/realms/{realm}/gameServerClusters/{cluster}``.
For example,
``... | a GKE cluster.
Attributes:
cluster (str):
The full or partial name of a GKE cluster, using one of the
following forms:
- ``projects/{project}/locations/{location}/clusters/{cluster}``
- ``locations/{location}/clusters/{cluster}``
- ``{cluster... | 129 | 130 | 435 | 7 | 122 | renovate-bot/python-game-servers | google/cloud/gaming_v1/types/game_server_clusters.py | Python | GameServerCluster | GameServerCluster | 384 | 426 | 384 | 384 | e2db39519a93a6eb0b504fde1e70f331aea3477c | bigcode/the-stack | train |
4d7bea87efbf65c9e163a67c | train | class | class UpdateGameServerClusterRequest(proto.Message):
r"""Request message for
GameServerClustersService.UpdateGameServerCluster.
Attributes:
game_server_cluster (google.cloud.gaming_v1.types.GameServerCluster):
Required. The game server cluster to be updated. Only fields
spec... | class UpdateGameServerClusterRequest(proto.Message):
| r"""Request message for
GameServerClustersService.UpdateGameServerCluster.
Attributes:
game_server_cluster (google.cloud.gaming_v1.types.GameServerCluster):
Required. The game server cluster to be updated. Only fields
specified in update_mask are updated.
update_mask... | .
target_state (google.cloud.gaming_v1.types.TargetState):
The target state.
"""
etag = proto.Field(proto.STRING, number=2,)
target_state = proto.Field(proto.MESSAGE, number=3, message=common.TargetState,)
class UpdateGameServerClusterRequest(proto.Message):
| 63 | 64 | 184 | 9 | 54 | renovate-bot/python-game-servers | google/cloud/gaming_v1/types/game_server_clusters.py | Python | UpdateGameServerClusterRequest | UpdateGameServerClusterRequest | 275 | 295 | 275 | 275 | e0b4418d0edbdd60cf25f4090bd812016f0c5016 | bigcode/the-stack | train |
03d396dc68ccf646821e2268 | train | function | @task(
help={
'username': 'User name to create, e.g., nick',
'full-name': 'Name to give to the user, e.g., Nick Durant',
'public-key-file': 'Path to the file to upload, e.g., ~/ssh_keyfiles/nick.pub',
'sudoer': 'If Sudo access should be given, e.g., True',
}
)
def add_user(connec... | @task(
help={
'username': 'User name to create, e.g., nick',
'full-name': 'Name to give to the user, e.g., Nick Durant',
'public-key-file': 'Path to the file to upload, e.g., ~/ssh_keyfiles/nick.pub',
'sudoer': 'If Sudo access should be given, e.g., True',
}
)
def add_user(connec... | """
Add a user to a server, optionally giving them sudo access.
Tested with Ubuntu 20.04.3 LTS, using an official AWS EC2 AMI.
Example usage:
If we want to add the user "nick" to the host "middle-prod-2", and had the user's ssh keyfile at
/Users/adam/ssh_keyfiles/nick.pub, we would use the fo... | from fabric import task
from invoke.exceptions import UnexpectedExit
@task(
help={
'username': 'User name to create, e.g., nick',
'full-name': 'Name to give to the user, e.g., Nick Durant',
'public-key-file': 'Path to the file to upload, e.g., ~/ssh_keyfiles/nick.pub',
'sudoer': 'If ... | 117 | 252 | 842 | 105 | 11 | eastside/admin-utils | fabfile.py | Python | add_user | add_user | 5 | 86 | 5 | 13 | 67bb15593a84882efbd028d7368c4f3532e95be0 | bigcode/the-stack | train |
5558a356f68e2353c7b9dcd6 | train | function | def update_token():
data = {
"mobile": int(NUMBER),
# "secret": "U2FsdGVkX1/cvoue2qat3566bxHk79jZlZiy25mf+APCgU9rVOi7mNhAdg3BQfLOWDBsLxU+3VRVX/ZrTO/v9w=="
"secret": "U2FsdGVkX1/36L9pmOjvT9PNfjf21XQhOFH3T6tEikNJCtzvh7N0JOTBguSBTgiQTkTi4z6IBlKpTwbj43SCSA=="
}
response = requests.post(... | def update_token():
| data = {
"mobile": int(NUMBER),
# "secret": "U2FsdGVkX1/cvoue2qat3566bxHk79jZlZiy25mf+APCgU9rVOi7mNhAdg3BQfLOWDBsLxU+3VRVX/ZrTO/v9w=="
"secret": "U2FsdGVkX1/36L9pmOjvT9PNfjf21XQhOFH3T6tEikNJCtzvh7N0JOTBguSBTgiQTkTi4z6IBlKpTwbj43SCSA=="
}
response = requests.post("https://cdn-api.co-... | seconds")
time.sleep(TIME_PERIOD)
return get_calendar()
return response.json()
def display_message(center):
top = tk.Tk()
top.withdraw()
messagebox.showinfo("Cowin registration", f"{center}", master=top)
top.destroy()
def authenticated_request_header():
return {
"Au... | 107 | 107 | 359 | 4 | 103 | yolocusharma/cowin | cowin.py | Python | update_token | update_token | 45 | 71 | 45 | 45 | 14309cbd53eeee8299e442b3203368ed1731979a | bigcode/the-stack | train |
b5a58a049932f33247d4d73b | train | function | def get_calendar():
response = requests.get(
f"https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?pincode={PINCODE}&date={date.today().strftime('%d-%m-%Y')}",
headers=public_request_header())
if response.status_code != 200:
print(
f"{datetime.datetime... | def get_calendar():
| response = requests.get(
f"https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?pincode={PINCODE}&date={date.today().strftime('%d-%m-%Y')}",
headers=public_request_header())
if response.status_code != 200:
print(
f"{datetime.datetime.now()} Invalid resp... | import datetime
import time
import tkinter as tk
from datetime import date
from hashlib import sha256
from tkinter import messagebox
import requests
def get_calendar():
| 35 | 64 | 117 | 4 | 30 | yolocusharma/cowin | cowin.py | Python | get_calendar | get_calendar | 11 | 22 | 11 | 11 | 450d8a4442ca324426d2be236b256c8eddfc7a7a | bigcode/the-stack | train |
eba1b3d9d325aa2ad9349a1f | train | function | def public_request_header():
return {
"user-agent": USER_AGENT
}
| def public_request_header():
| return {
"user-agent": USER_AGENT
}
| = tk.Tk()
top.withdraw()
messagebox.showinfo("Cowin registration", f"{center}", master=top)
top.destroy()
def authenticated_request_header():
return {
"Authorization": f"Bearer {token}",
"user-agent": USER_AGENT
}
def public_request_header():
| 64 | 64 | 18 | 5 | 59 | yolocusharma/cowin | cowin.py | Python | public_request_header | public_request_header | 39 | 42 | 39 | 39 | f544ecf9d79294ae37a62614bcc7b316de1692d4 | bigcode/the-stack | train |
04ed85b8e5966a6530fff549 | train | function | def check_and_book_appointment(beneficiary_reference_id, calendar):
for center in calendar["centers"]:
if center["fee_type"] != "Free":
continue
center_id = center['center_id']
for session in center["sessions"]:
if session["available_capacity"] > 0 and session["mi... | def check_and_book_appointment(beneficiary_reference_id, calendar):
| for center in calendar["centers"]:
if center["fee_type"] != "Free":
continue
center_id = center['center_id']
for session in center["sessions"]:
if session["available_capacity"] > 0 and session["min_age_limit"] == MIN_AGE_LIMIT:
print(f"Attempting ... | beneficiaries"]:
if NAME == beneficiary["name"]:
return beneficiary["beneficiary_reference_id"]
names.append(beneficiary["name"])
raise ValueError(f"Input beneficiary name does not match the registered beneficiaries: {names}")
def check_and_book_appointment(beneficiary_reference_id, cal... | 63 | 64 | 201 | 14 | 49 | yolocusharma/cowin | cowin.py | Python | check_and_book_appointment | check_and_book_appointment | 95 | 124 | 95 | 95 | 82e4055ca5f8a86a7bec2479e3a9276776ca9c1b | bigcode/the-stack | train |
fcc892a5b68ce6ab23d0d2c0 | train | function | def display_message(center):
top = tk.Tk()
top.withdraw()
messagebox.showinfo("Cowin registration", f"{center}", master=top)
top.destroy()
| def display_message(center):
| top = tk.Tk()
top.withdraw()
messagebox.showinfo("Cowin registration", f"{center}", master=top)
top.destroy()
| if response.status_code != 200:
print(
f"{datetime.datetime.now()} Invalid response code while finding by pincode: {response.status_code}. Retrying in {TIME_PERIOD} seconds")
time.sleep(TIME_PERIOD)
return get_calendar()
return response.json()
def display_message(center):
| 64 | 64 | 38 | 5 | 59 | yolocusharma/cowin | cowin.py | Python | display_message | display_message | 25 | 29 | 25 | 25 | 7d935b6a20b83a107961cb873209fbe80787314d | bigcode/the-stack | train |
24bfe6e476ec412f81185c44 | train | function | def get_beneficiary_reference_id():
response = requests.get(
"https://cdn-api.co-vin.in/api/v2/appointment/beneficiaries", headers=authenticated_request_header())
if response.status_code == 401:
update_token()
response = requests.get(
"https://cdn-api.co-vin.in/api/v2/appoin... | def get_beneficiary_reference_id():
| response = requests.get(
"https://cdn-api.co-vin.in/api/v2/appointment/beneficiaries", headers=authenticated_request_header())
if response.status_code == 401:
update_token()
response = requests.get(
"https://cdn-api.co-vin.in/api/v2/appointment/beneficiaries", headers=authen... | headers=public_request_header())
if response.status_code != 200:
raise ValueError(f"Invalid response while validating OTP: {response.json()}")
global token
token = response.json()["token"]
print(f"Generated token: {token}")
def get_beneficiary_reference_id():
| 63 | 64 | 171 | 8 | 55 | yolocusharma/cowin | cowin.py | Python | get_beneficiary_reference_id | get_beneficiary_reference_id | 74 | 92 | 74 | 74 | bd373556a3fa9c52a1622c370a1019e96ca19d88 | bigcode/the-stack | train |
a58e5932a0542fffc987e9b2 | train | function | def book_with_retry(booking_request):
response = requests.post("https://cdn-api.co-vin.in/api/v2/appointment/schedule",
headers=authenticated_request_header(),
json=booking_request)
if response.status_code == 401:
print("Token Expired")
u... | def book_with_retry(booking_request):
| response = requests.post("https://cdn-api.co-vin.in/api/v2/appointment/schedule",
headers=authenticated_request_header(),
json=booking_request)
if response.status_code == 401:
print("Token Expired")
update_token()
response = reque... | _id': session_id,
'slot': slot
}
booked = book_with_retry(booking_request)
if booked:
print(f"Appointment booked for {slot}")
display_message(f"Appointment booked for {slot}")
... | 64 | 64 | 132 | 8 | 55 | yolocusharma/cowin | cowin.py | Python | book_with_retry | book_with_retry | 127 | 142 | 127 | 127 | 5920fbaa6b242c5be2b685b4e7cc8e5e04d1cb70 | bigcode/the-stack | train |
85ca33db21d02a3ad35770f9 | train | function | def authenticated_request_header():
return {
"Authorization": f"Bearer {token}",
"user-agent": USER_AGENT
}
| def authenticated_request_header():
| return {
"Authorization": f"Bearer {token}",
"user-agent": USER_AGENT
}
| _PERIOD} seconds")
time.sleep(TIME_PERIOD)
return get_calendar()
return response.json()
def display_message(center):
top = tk.Tk()
top.withdraw()
messagebox.showinfo("Cowin registration", f"{center}", master=top)
top.destroy()
def authenticated_request_header():
| 64 | 64 | 28 | 5 | 59 | yolocusharma/cowin | cowin.py | Python | authenticated_request_header | authenticated_request_header | 32 | 36 | 32 | 32 | 7cc37b7fecfe411709bff1aa677288b623ad70ab | bigcode/the-stack | train |
1262ac0f089dfef756a79174 | train | function | def run():
update_token()
beneficiary_reference_id = get_beneficiary_reference_id()
print(f"Beneficiary id is {beneficiary_reference_id}")
while True:
calendar = get_calendar()
if check_and_book_appointment(beneficiary_reference_id, calendar):
return
print(f"{dateti... | def run():
| update_token()
beneficiary_reference_id = get_beneficiary_reference_id()
print(f"Beneficiary id is {beneficiary_reference_id}")
while True:
calendar = get_calendar()
if check_and_book_appointment(beneficiary_reference_id, calendar):
return
print(f"{datetime.datetime... | cdn-api.co-vin.in/api/v2/appointment/schedule",
headers=authenticated_request_header(),
json=booking_request)
booked = response.status_code == 200
if not booked:
print(f"Could not book.. Response: {response.json()}")
return booked
d... | 64 | 64 | 85 | 3 | 60 | yolocusharma/cowin | cowin.py | Python | run | run | 145 | 156 | 145 | 145 | 68f038ffb556b6b1719e99d4a714097a06b2aee2 | bigcode/the-stack | train |
f998b2270044597ddcada0d4 | train | function | def _dequantized_var_name(var_name):
"""
Return dequantized variable name for the input `var_name`.
"""
return "%s.dequantized" % (var_name)
| def _dequantized_var_name(var_name):
| """
Return dequantized variable name for the input `var_name`.
"""
return "%s.dequantized" % (var_name)
| = ['conv2d', 'depthwise_conv2d', 'mul']
def _quantized_var_name(var_name):
"""
Return quantized variable name for the input `var_name`.
"""
return "%s.quantized" % (var_name)
def _dequantized_var_name(var_name):
| 64 | 64 | 41 | 10 | 54 | L-Net-1992/Paddle | python/paddle/fluid/contrib/quantize/quantize_transpiler.py | Python | _dequantized_var_name | _dequantized_var_name | 41 | 45 | 41 | 41 | 219403d408bcb0a107511dc095293a1774e22c41 | bigcode/the-stack | train |
824d7adec774760f4b5eea9c | train | function | def _original_var_name(var_name):
"""
Return the original variable name.
"""
if var_name.endswith('.quantized.dequantized'):
return var_name[:-len('.quantized.dequantized')]
if var_name.endswith('.quantized'):
return var_name[:-len('.quantized')]
if var_name.endswith('.dequantize... | def _original_var_name(var_name):
| """
Return the original variable name.
"""
if var_name.endswith('.quantized.dequantized'):
return var_name[:-len('.quantized.dequantized')]
if var_name.endswith('.quantized'):
return var_name[:-len('.quantized')]
if var_name.endswith('.dequantized'):
return var_name[:-len... | `var_name`.
"""
return "%s.dequantized" % (var_name)
def _quantized_scale_name(var_name):
"""
Return quantized variable name for the input `var_name`.
"""
return "%s.scale" % (var_name)
def _original_var_name(var_name):
| 64 | 64 | 109 | 8 | 56 | L-Net-1992/Paddle | python/paddle/fluid/contrib/quantize/quantize_transpiler.py | Python | _original_var_name | _original_var_name | 55 | 68 | 55 | 55 | bdfac0221db578ecf7e9afd28c83676810ec96d3 | bigcode/the-stack | train |
c470a1f2cda853227a24d0b1 | train | function | def quant(x, scale, num_bits):
y = np.round(x / scale * ((1 << (num_bits - 1)) - 1))
return y
| def quant(x, scale, num_bits):
| y = np.round(x / scale * ((1 << (num_bits - 1)) - 1))
return y
| var_name[:-len('.dequantized')]
if var_name.endswith('.scale'):
return var_name[:-len('.scale')]
else:
return var_name
def _is_float(v):
return isinstance(v, float) or isinstance(v, np.float32)
def quant(x, scale, num_bits):
| 64 | 64 | 36 | 9 | 55 | L-Net-1992/Paddle | python/paddle/fluid/contrib/quantize/quantize_transpiler.py | Python | quant | quant | 75 | 77 | 75 | 75 | fbb58e82b5af20a3a5856ce8239b062c9dc0d70e | bigcode/the-stack | train |
4b4058571b22c42841e77055 | train | function | def _is_float(v):
return isinstance(v, float) or isinstance(v, np.float32)
| def _is_float(v):
| return isinstance(v, float) or isinstance(v, np.float32)
| ized'):
return var_name[:-len('.quantized')]
if var_name.endswith('.dequantized'):
return var_name[:-len('.dequantized')]
if var_name.endswith('.scale'):
return var_name[:-len('.scale')]
else:
return var_name
def _is_float(v):
| 64 | 64 | 21 | 6 | 57 | L-Net-1992/Paddle | python/paddle/fluid/contrib/quantize/quantize_transpiler.py | Python | _is_float | _is_float | 71 | 72 | 71 | 71 | 87979abdf9e1ca5385011ca1d0282ea0eed3c484 | bigcode/the-stack | train |
441464e778a491ad852c094a | train | class | class QuantizeTranspiler(object):
def __init__(self,
weight_bits=8,
activation_bits=8,
activation_quantize_type='abs_max',
weight_quantize_type='abs_max',
window_size=10000,
moving_rate=0.9):
"""
C... | class QuantizeTranspiler(object):
| def __init__(self,
weight_bits=8,
activation_bits=8,
activation_quantize_type='abs_max',
weight_quantize_type='abs_max',
window_size=10000,
moving_rate=0.9):
"""
Convert and rewrite the fluid Progra... | (var_name)
def _dequantized_var_name(var_name):
"""
Return dequantized variable name for the input `var_name`.
"""
return "%s.dequantized" % (var_name)
def _quantized_scale_name(var_name):
"""
Return quantized variable name for the input `var_name`.
"""
return "%s.scale" % (var_name... | 256 | 256 | 4,006 | 8 | 247 | L-Net-1992/Paddle | python/paddle/fluid/contrib/quantize/quantize_transpiler.py | Python | QuantizeTranspiler | QuantizeTranspiler | 80 | 556 | 80 | 81 | 3705743ce5f8fbf2309220a5d26ca4e5410d1ee6 | bigcode/the-stack | train |
c741aa7230940adb6ef718fe | train | function | def _quantized_scale_name(var_name):
"""
Return quantized variable name for the input `var_name`.
"""
return "%s.scale" % (var_name)
| def _quantized_scale_name(var_name):
| """
Return quantized variable name for the input `var_name`.
"""
return "%s.scale" % (var_name)
| """
return "%s.quantized" % (var_name)
def _dequantized_var_name(var_name):
"""
Return dequantized variable name for the input `var_name`.
"""
return "%s.dequantized" % (var_name)
def _quantized_scale_name(var_name):
| 64 | 64 | 37 | 9 | 55 | L-Net-1992/Paddle | python/paddle/fluid/contrib/quantize/quantize_transpiler.py | Python | _quantized_scale_name | _quantized_scale_name | 48 | 52 | 48 | 48 | 547037bcfff61a65d209c7d0e5840fc96bdbebd2 | bigcode/the-stack | train |
97987030efa17dd6832173b3 | train | function | def _quantized_var_name(var_name):
"""
Return quantized variable name for the input `var_name`.
"""
return "%s.quantized" % (var_name)
| def _quantized_var_name(var_name):
| """
Return quantized variable name for the input `var_name`.
"""
return "%s.quantized" % (var_name)
| oincreased_step_counter
from paddle.fluid.framework import Variable
from paddle.fluid.executor import global_scope
__all__ = ['QuantizeTranspiler']
_QUANTIZABLE_OP_TYPES = ['conv2d', 'depthwise_conv2d', 'mul']
def _quantized_var_name(var_name):
| 64 | 64 | 38 | 9 | 55 | L-Net-1992/Paddle | python/paddle/fluid/contrib/quantize/quantize_transpiler.py | Python | _quantized_var_name | _quantized_var_name | 34 | 38 | 34 | 34 | 4beb6f75cf327f7dbd71e619e1fb154245e4c917 | bigcode/the-stack | train |
6cd36af2fd5500af213fbacd | train | function | def test_main():
with patch("sys.argv", ["bare_python_package", "--url", "demo"]) as mock_sysargv:
with patch("bare_python_package.main.process_url") as mock_process_url:
main()
mock_process_url.assert_called_once()
assert mock_process_url.call_args.args == ('demo',)
| def test_main():
| with patch("sys.argv", ["bare_python_package", "--url", "demo"]) as mock_sysargv:
with patch("bare_python_package.main.process_url") as mock_process_url:
main()
mock_process_url.assert_called_once()
assert mock_process_url.call_args.args == ('demo',)
| from unittest.mock import patch
import pytest
import logging
from bare_python_package.main import main
def test_main():
| 24 | 64 | 67 | 4 | 19 | jepma/bare-python-package | tests/unittests/test_main.py | Python | test_main | test_main | 7 | 15 | 7 | 8 | 6c7285fa81e2d4f9e7124f5303e518e49ef60dc3 | bigcode/the-stack | train |
65f14ddd5c693bd281ebc69d | train | class | class RPCError(Exception):
'''Error thrown when standard_kaldi returns an error (in-band)'''
def __init__(self, status, why):
self.status = status
self.why = why
def __str__(self):
return 'standard_kaldi: error %d: %s' % (self.status, self.why)
| class RPCError(Exception):
| '''Error thrown when standard_kaldi returns an error (in-band)'''
def __init__(self, status, why):
self.status = status
self.why = why
def __str__(self):
return 'standard_kaldi: error %d: %s' % (self.status, self.why)
| data.split('\n', 1)
status = int(status_str)
except IOError as _:
raise IOError("Lost connection with standard_kaldi subprocess")
if status < 200 or status >= 300:
raise RPCError(status, body)
return body, status
class RPCError(Exception):
| 64 | 64 | 75 | 5 | 58 | andrewwhwang/gentle | gentle/rpc.py | Python | RPCError | RPCError | 68 | 74 | 68 | 68 | 1886c048e393469ddc27fb673bb62ad0713a5105 | bigcode/the-stack | train |
54ceeb0e76049bab265e8512 | train | class | class RPCProtocol(object):
'''RPCProtocol is the wire protocol we use to communicate with the
standard_kaldi subprocess. It's a mixed text/binary protocol
because we need to send binary audio chunks, but text is simpler.'''
def __init__(self, send_pipe, recv_pipe):
'''Initializes the RPCProtoco... | class RPCProtocol(object):
| '''RPCProtocol is the wire protocol we use to communicate with the
standard_kaldi subprocess. It's a mixed text/binary protocol
because we need to send binary audio chunks, but text is simpler.'''
def __init__(self, send_pipe, recv_pipe):
'''Initializes the RPCProtocol and reads from recv_pipe ... | class RPCProtocol(object):
| 5 | 149 | 498 | 5 | 0 | andrewwhwang/gentle | gentle/rpc.py | Python | RPCProtocol | RPCProtocol | 1 | 66 | 1 | 1 | f0be8115e331bfa351a8a107c54847a405b089c3 | bigcode/the-stack | train |
f0e8b61b34c82c69687af2e9 | train | class | class TimeAttr(AnyDateTimeAttr):
def __init__(self, attr):
AnyDateTimeAttr.__init__(self, attr)
| class TimeAttr(AnyDateTimeAttr):
| def __init__(self, attr):
AnyDateTimeAttr.__init__(self, attr)
| from .AnyDateTimeAttr import AnyDateTimeAttr
class TimeAttr(AnyDateTimeAttr):
| 21 | 64 | 30 | 9 | 11 | PeaceWorksTechnologySolutions/w4py3-middlekit | webware/MiddleKit/Core/TimeAttr.py | Python | TimeAttr | TimeAttr | 4 | 7 | 4 | 5 | e6ecc4032f094a929500d14f0df244509167dab5 | bigcode/the-stack | train |
80736cbaeaae4adc02922e4f | train | class | class Dut(BaseApi):
"""
Dut class
"""
@property
def count(self):
"""
Getter for dut count
:return: Integer
"""
return self.get("count")
@count.setter
@setter_rules(value_type=int)
def count(self, value):
"""
Setter for dut count
... | class Dut(BaseApi):
| """
Dut class
"""
@property
def count(self):
"""
Getter for dut count
:return: Integer
"""
return self.get("count")
@count.setter
@setter_rules(value_type=int)
def count(self, value):
"""
Setter for dut count
:param value:... | """
OpentTMI module for DUT (Device under test)
"""
from opentmi_client.utils.Base import BaseApi
from opentmi_client.utils.decorators import setter_rules
from opentmi_client.api.result.Provider import Provider
class Dut(BaseApi):
| 49 | 200 | 669 | 5 | 43 | OpenTMI/opentmi-pyclient | opentmi_client/api/result/Dut.py | Python | Dut | Dut | 9 | 155 | 9 | 9 | bd19a677250ed54dadac7cd2b44008e3b7fd923f | bigcode/the-stack | train |
796ede603de26c4a10494829 | train | class | class Root(object):
__slots__ = ['_ctx']
def __init__(self, context=None):
self._ctx = context
@route('/user') # These just set fn.__route__ to this value.
def root(self):
return "I'm all people."
@route('/user/{username:[a-zA-Z]+}')
def user(self, username):
return "Hi, I'm " + username
@route('/... | class Root(object):
| __slots__ = ['_ctx']
def __init__(self, context=None):
self._ctx = context
@route('/user') # These just set fn.__route__ to this value.
def root(self):
return "I'm all people."
@route('/user/{username:[a-zA-Z]+}')
def user(self, username):
return "Hi, I'm " + username
@route('/user/{username:[a-zA... | # encoding: utf-8
from web.dispatch.route import route
class Root(object):
| 18 | 64 | 122 | 4 | 13 | marrow/web.dispatch.route | test/sample.py | Python | Root | Root | 6 | 22 | 6 | 6 | 38c273e00614573c88c254fcec9639a043953c4f | bigcode/the-stack | train |
6eaee59543fd262da093b83f | train | class | class CSVParser(ParserBase):
def get_all(self, url: str) -> typing.List[pd.DataFrame]:
return [pd.read_csv(url)] | class CSVParser(ParserBase):
| def get_all(self, url: str) -> typing.List[pd.DataFrame]:
return [pd.read_csv(url)] | from datamart.materializers.parsers.parser_base import *
class CSVParser(ParserBase):
| 17 | 64 | 32 | 6 | 11 | juancroldan/datamart | datamart/materializers/parsers/csv_parser.py | Python | CSVParser | CSVParser | 4 | 7 | 4 | 5 | a11a7fc4204700de8693b5e5fc9d734f00817c6a | bigcode/the-stack | train |
5b685a86c4eefb33feb22511 | train | function | def piazza_alieno():
'''
Il limite di 50 pixel è definito per evitare che l'immagine
sia parzialmente fuori schermo
Alieno ha size 64x64
'''
alieno.x = randint(50, WIDTH-50)
alieno.y = randint(50, HEIGHT-50)
| def piazza_alieno():
| '''
Il limite di 50 pixel è definito per evitare che l'immagine
sia parzialmente fuori schermo
Alieno ha size 64x64
'''
alieno.x = randint(50, WIDTH-50)
alieno.y = randint(50, HEIGHT-50)
| HEIGHT = 600
alieno = Actor("alieno")
messaggio = ""
def draw():
screen.clear()
screen.fill(color=(128,0,0))
alieno.draw()
screen.draw.text(messaggio, center=(400,40), fontsize=20)
def piazza_alieno():
| 64 | 64 | 72 | 6 | 58 | PythonBiellaGroup/LearningPythonWithGames | game01/3_2_message.py | Python | piazza_alieno | piazza_alieno | 19 | 26 | 19 | 19 | 15db3d4713676f1f23b1968a7630aa334569ded4 | bigcode/the-stack | train |
1bc07230d37f28d42e02dd85 | train | function | def draw():
screen.clear()
screen.fill(color=(128,0,0))
alieno.draw()
screen.draw.text(messaggio, center=(400,40), fontsize=20)
| def draw():
| screen.clear()
screen.fill(color=(128,0,0))
alieno.draw()
screen.draw.text(messaggio, center=(400,40), fontsize=20)
| # pgzrun è importato tutto
import pgzrun
# random: modulo per numeri casuali
from random import randint
TITLE = "Colpisci l'alieno"
WIDTH = 800
HEIGHT = 600
alieno = Actor("alieno")
messaggio = ""
def draw():
| 64 | 64 | 41 | 3 | 61 | PythonBiellaGroup/LearningPythonWithGames | game01/3_2_message.py | Python | draw | draw | 13 | 17 | 13 | 13 | 1baf0fa85988a8dc37e16bffe5812f89200164b9 | bigcode/the-stack | train |
0778ddfe6fc5121a3ca4816c | train | function | def on_mouse_down(pos):
global messaggio
if alieno.collidepoint(pos):
messaggio = "Bel colpo!"
piazza_alieno()
| def on_mouse_down(pos):
| global messaggio
if alieno.collidepoint(pos):
messaggio = "Bel colpo!"
piazza_alieno()
| pixel è definito per evitare che l'immagine
sia parzialmente fuori schermo
Alieno ha size 64x64
'''
alieno.x = randint(50, WIDTH-50)
alieno.y = randint(50, HEIGHT-50)
def on_mouse_down(pos):
| 64 | 64 | 35 | 6 | 58 | PythonBiellaGroup/LearningPythonWithGames | game01/3_2_message.py | Python | on_mouse_down | on_mouse_down | 28 | 32 | 28 | 28 | 06f738267d6f0583b946ab6444eebd7c6959ee3c | bigcode/the-stack | train |
34a7e9e1e6114868d891e198 | train | class | class LoadBalancersOperations(object):
"""LoadBalancersOperations operations.
You should not instantiate directly this class, but create a Client instance that will create it for you and attach it as attribute.
:param client: Client for service requests.
:param config: Configuration of service client.... | class LoadBalancersOperations(object):
| """LoadBalancersOperations operations.
You should not instantiate directly this class, but create a Client instance that will create it for you and attach it as attribute.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model... | # 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 ... | 139 | 256 | 4,731 | 7 | 131 | iscai-msft/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_02_01/operations/_load_balancers_operations.py | Python | LoadBalancersOperations | LoadBalancersOperations | 21 | 526 | 21 | 21 | 4e270575dfb33f7db43bcaa3e93253ab86e22b55 | bigcode/the-stack | train |
3d9eaced3f8a8ee304d3134d | train | class | class SSEHandler(tornado.web.RequestHandler):
"""
Handles Server-Sent Events (SSE) requests as specified in
http://dev.w3.org/html5/eventsource/.
This handlers gives the option to to the user to use SSE or any other
regular MIME types in the same same handler. If the MINE type of the
request is... | class SSEHandler(tornado.web.RequestHandler):
| """
Handles Server-Sent Events (SSE) requests as specified in
http://dev.w3.org/html5/eventsource/.
This handlers gives the option to to the user to use SSE or any other
regular MIME types in the same same handler. If the MINE type of the
request is 'text/event-stream' by default this handler i... | # =============================================================================
# periscope-ps (unis)
#
# Copyright (c) 2012-2016, Trustees of Indiana University,
# All rights reserved.
#
# This software may be modified and distributed under the terms of the BSD
# license. See the COPYING file for details.
#
# T... | 122 | 219 | 733 | 9 | 112 | periscope-ps/unis | periscope/handlers/ssehandler.py | Python | SSEHandler | SSEHandler | 19 | 110 | 19 | 19 | f31daef825d969a7677fdfed4c467d170716a80c | bigcode/the-stack | train |
28023b51babd27daeb1581af | train | class | class PosTaggingStanford(PosTagging):
"""
Concrete class of PosTagging using StanfordPOSTokenizer and StanfordPOSTagger
tokenizer contains the default nltk tokenizer (PhunktSentenceTokenizer).
tagger contains the StanfordPOSTagger object (which also trigger word tokenization see : -tokenize option in ... | class PosTaggingStanford(PosTagging):
| """
Concrete class of PosTagging using StanfordPOSTokenizer and StanfordPOSTagger
tokenizer contains the default nltk tokenizer (PhunktSentenceTokenizer).
tagger contains the StanfordPOSTagger object (which also trigger word tokenization see : -tokenize option in Java).
"""
def __init__(self... | 1', '/Users/user1/direct/text2'] , suffix = _POS)
will create
/Users/user1/text1_POS
/Users/user1/direct/text2_POS
:param list_of_path: list containing the path (as string) of each file to POS Tag
:param suffix: suffix to append at the end of the original filename for the result... | 150 | 150 | 500 | 10 | 140 | AnzorGozalishvili/embedrank_serving | swisscom_ai/research_keyphrase/preprocessing/postagging.py | Python | PosTaggingStanford | PosTaggingStanford | 114 | 158 | 114 | 114 | feb4d36475792ec57250848923110bf1126fbfac | bigcode/the-stack | train |
a8741addad96ac58272b609a | train | class | class PosTaggingCoreNLP(PosTagging):
"""
Concrete class of PosTagging using a CoreNLP server
Provides a faster way to process several documents using since it doesn't require to load the model each time.
"""
def __init__(self, host='localhost', port=9000, separator='|'):
self.parser = Core... | class PosTaggingCoreNLP(PosTagging):
| """
Concrete class of PosTagging using a CoreNLP server
Provides a faster way to process several documents using since it doesn't require to load the model each time.
"""
def __init__(self, host='localhost', port=9000, separator='|'):
self.parser = CoreNLPParser(url=f'http://{host}:{port}'... | text).strip() # Convert multiple whitespaces into one
doc = self.nlp(text)
if as_tuple_list:
return [[(token.text, token.tag_) for token in sent] for sent in doc.sents]
return '[ENDSENT]'.join(
' '.join(self.separator.join([token.text, token.tag_]) for token in sent) f... | 96 | 96 | 322 | 11 | 85 | AnzorGozalishvili/embedrank_serving | swisscom_ai/research_keyphrase/preprocessing/postagging.py | Python | PosTaggingCoreNLP | PosTaggingCoreNLP | 192 | 222 | 192 | 192 | e7d782d1c29a73784a175ae8986251a836588900 | bigcode/the-stack | train |
d5933467f85c3a336319d5af | train | class | class PosTaggingSpacy(PosTagging):
"""
Concrete class of PosTagging using StanfordPOSTokenizer and StanfordPOSTagger
"""
def __init__(self, nlp=None, separator='|', lang='en'):
if not nlp:
print('Loading Spacy model')
# self.nlp = spacy.load(lang, entity=False)
... | class PosTaggingSpacy(PosTagging):
| """
Concrete class of PosTagging using StanfordPOSTokenizer and StanfordPOSTagger
"""
def __init__(self, nlp=None, separator='|', lang='en'):
if not nlp:
print('Loading Spacy model')
# self.nlp = spacy.load(lang, entity=False)
print('Spacy model loaded '... | """
tagged_text = self.tagger.tag_sents([self.sent_tokenizer.sentences_from_text(text)])
if as_tuple_list:
return tagged_text
return '[ENDSENT]'.join(
[' '.join([tuple2str(tagged_token, self.separator) for tagged_token in sent]) for sent in tagged_text])
class Po... | 80 | 80 | 268 | 10 | 70 | AnzorGozalishvili/embedrank_serving | swisscom_ai/research_keyphrase/preprocessing/postagging.py | Python | PosTaggingSpacy | PosTaggingSpacy | 161 | 189 | 161 | 161 | fea4bdaeba76e77d6d789d1458e6ea8bd1ca5a59 | bigcode/the-stack | train |
d969435115795ed4b9d39999 | train | class | class PosTagging(ABC):
@abstractmethod
def pos_tag_raw_text(self, text, as_tuple_list=True):
"""
Tokenize and POS tag a string
Sentence level is kept in the result :
Either we have a list of list (for each sentence a list of tuple (word,tag))
Or a separator [ENDSENT] if w... | class PosTagging(ABC):
@abstractmethod
| def pos_tag_raw_text(self, text, as_tuple_list=True):
"""
Tokenize and POS tag a string
Sentence level is kept in the result :
Either we have a list of list (for each sentence a list of tuple (word,tag))
Or a separator [ENDSENT] if we are requesting a string by putting as_tup... | # Copyright (c) 2017-present, Swisscom (Schweiz) AG.
# All rights reserved.
#
# Authors: Kamil Bennani-Smires, Yann Savary
import argparse
import os
import re
import warnings
from abc import ABC, abstractmethod
# NLTK imports
import nltk
from nltk.tag.util import tuple2str
from nltk.parse import CoreNLPParser
import... | 158 | 256 | 867 | 12 | 145 | AnzorGozalishvili/embedrank_serving | swisscom_ai/research_keyphrase/preprocessing/postagging.py | Python | PosTagging | PosTagging | 25 | 111 | 25 | 26 | 0824fce15a13c12ac233907dcd3ff77bf61731ac | bigcode/the-stack | train |
2dfb0965b5045a0321b82509 | train | function | def main(args=None):
"""Updates the files corresponding to LOCAL_FECONF_PATH and
LOCAL_CONSTANTS_PATH after doing the prerequisite checks.
"""
options = _PARSER.parse_args(args=args)
# Do prerequisite checks.
feconf_config_path = os.path.join(
options.deploy_data_path, 'feconf_updates.c... | def main(args=None):
| """Updates the files corresponding to LOCAL_FECONF_PATH and
LOCAL_CONSTANTS_PATH after doing the prerequisite checks.
"""
options = _PARSER.parse_args(args=args)
# Do prerequisite checks.
feconf_config_path = os.path.join(
options.deploy_data_path, 'feconf_updates.config')
constants... | MAILCHIMP_API_KEY = None\n' in feconf_lines, error_text
with python_utils.open_file(release_feconf_path, 'w') as f:
for line in feconf_lines:
if line == 'MAILCHIMP_API_KEY = None\n':
line = line.replace('None', '\'%s\'' % mailchimp_api_key)
f.write(line)
def main(arg... | 86 | 86 | 287 | 5 | 81 | nbaddam/oppia | scripts/release_scripts/update_configs.py | Python | main | main | 261 | 293 | 261 | 261 | aaf0e208997457326234e13297e5d26e36d32fe0 | bigcode/the-stack | train |
0dc6f4bf6cb998d29852b228 | train | function | def apply_changes_based_on_config(
local_filepath, config_filepath, expected_config_line_regex):
"""Updates the local file based on the deployment configuration specified
in the config file.
Each line of the config file should match the expected config line regex.
Args:
local_filepath:... | def apply_changes_based_on_config(
local_filepath, config_filepath, expected_config_line_regex):
| """Updates the local file based on the deployment configuration specified
in the config file.
Each line of the config file should match the expected config line regex.
Args:
local_filepath: str. Absolute path of the local file to be modified.
config_filepath: str. Absolute path of the ... | _data_path',
help='Path for deploy data directory.',
required=True)
_PARSER.add_argument(
'--personal_access_token',
dest='personal_access_token',
help='The personal access token for the GitHub id of user.',
default=None)
_PARSER.add_argument(
'--prompt_for_mailgun_and_terms_update',
act... | 125 | 126 | 423 | 19 | 106 | nbaddam/oppia | scripts/release_scripts/update_configs.py | Python | apply_changes_based_on_config | apply_changes_based_on_config | 74 | 119 | 74 | 75 | c19229643c249c5279d85015d04503b8ebc03892 | bigcode/the-stack | train |
d699418c6755c2a2c6d7b7fe | train | function | def verify_feconf(release_feconf_path, verify_email_api_keys):
"""Verifies that feconf is updated correctly to include
mailgun api key, mailchimp api key and redishost.
Args:
release_feconf_path: str. The path to feconf file in release
directory.
verify_email_api_keys: bool. Whe... | def verify_feconf(release_feconf_path, verify_email_api_keys):
| """Verifies that feconf is updated correctly to include
mailgun api key, mailchimp api key and redishost.
Args:
release_feconf_path: str. The path to feconf file in release
directory.
verify_email_api_keys: bool. Whether to verify both mailgun and
mailchimp api keys.... | if line.startswith('REGISTRATION_PAGE_LAST_UPDATED_UTC'):
line = (
'REGISTRATION_PAGE_LAST_UPDATED_UTC = '
'datetime.datetime(%s, %s, %s, %s, %s, %s)\n' % (
time_tuple))
f.write(line)
def veri... | 78 | 78 | 261 | 15 | 63 | nbaddam/oppia | scripts/release_scripts/update_configs.py | Python | verify_feconf | verify_feconf | 170 | 195 | 170 | 170 | 57fc454bf598d88291601485b941a5a51633024f | bigcode/the-stack | train |
e70e88652e8c1d05e3e986aa | train | function | def add_mailchimp_api_key(release_feconf_path):
"""Adds mailchimp api key to feconf config file.
Args:
release_feconf_path: str. The path to feconf file in release
directory.
"""
mailchimp_api_key = getpass.getpass(
prompt=('Enter mailchimp api key from the release process d... | def add_mailchimp_api_key(release_feconf_path):
| """Adds mailchimp api key to feconf config file.
Args:
release_feconf_path: str. The path to feconf file in release
directory.
"""
mailchimp_api_key = getpass.getpass(
prompt=('Enter mailchimp api key from the release process doc.'))
mailchimp_api_key = mailchimp_api_key... | in feconf_lines, 'Missing mailgun API key'
with python_utils.open_file(release_feconf_path, 'w') as f:
for line in feconf_lines:
if line == 'MAILGUN_API_KEY = None\n':
line = line.replace('None', '\'%s\'' % mailgun_api_key)
f.write(line)
def add_mailchimp_api_key(re... | 88 | 88 | 294 | 12 | 76 | nbaddam/oppia | scripts/release_scripts/update_configs.py | Python | add_mailchimp_api_key | add_mailchimp_api_key | 229 | 258 | 229 | 229 | cc535970f11eb99c3f268ad97bf59b64017bffb7 | bigcode/the-stack | train |
e42bbc3d368ce6e3dc3ecd9a | train | function | def add_mailgun_api_key(release_feconf_path):
"""Adds mailgun api key to feconf config file.
Args:
release_feconf_path: str. The path to feconf file in release
directory.
"""
mailgun_api_key = getpass.getpass(
prompt=('Enter mailgun api key from the release process doc.'))
... | def add_mailgun_api_key(release_feconf_path):
| """Adds mailgun api key to feconf config file.
Args:
release_feconf_path: str. The path to feconf file in release
directory.
"""
mailgun_api_key = getpass.getpass(
prompt=('Enter mailgun api key from the release process doc.'))
mailgun_api_key = mailgun_api_key.strip()
... | 'MAILCHIMP_API_KEY = None' in feconf_contents):
raise Exception(
'The mailchimp API key must be added before deployment.')
if ('REDISHOST' not in feconf_contents or
'REDISHOST = \'localhost\'' in feconf_contents):
raise Exception('REDISHOST must be updated before deployment... | 85 | 86 | 287 | 12 | 73 | nbaddam/oppia | scripts/release_scripts/update_configs.py | Python | add_mailgun_api_key | add_mailgun_api_key | 198 | 226 | 198 | 198 | 01d097f5e06dbad839a89ba84cc5625f83b341c4 | bigcode/the-stack | train |
6056e518bb360cd4d45dcafc | train | function | def check_updates_to_terms_of_service(
release_feconf_path, personal_access_token):
"""Checks if updates are made to terms of service and updates
REGISTRATION_PAGE_LAST_UPDATED_UTC in feconf.py if there are updates.
Args:
release_feconf_path: str. The path to feconf file in release
... | def check_updates_to_terms_of_service(
release_feconf_path, personal_access_token):
| """Checks if updates are made to terms of service and updates
REGISTRATION_PAGE_LAST_UPDATED_UTC in feconf.py if there are updates.
Args:
release_feconf_path: str. The path to feconf file in release
directory.
personal_access_token: str. The personal access token for the
... | line.startswith(match_result.group(1))]
assert len(matching_local_line_numbers) == 1, (
'Could not find correct number of lines in %s matching: %s' %
(local_filename, config_line))
local_line_numbers.append(matching_local_line_numbers[0])
# Then, apply the changes.
for ... | 144 | 144 | 483 | 18 | 126 | nbaddam/oppia | scripts/release_scripts/update_configs.py | Python | check_updates_to_terms_of_service | check_updates_to_terms_of_service | 122 | 167 | 122 | 123 | dc0a436858998861895aefa66f2b988680838099 | bigcode/the-stack | train |
1abb9d58bfcb86066581bb06 | train | function | def RCScan():
"""Return a prototype Scanner instance for scanning RC source files"""
res_re= r'^(?:\s*#\s*(?:include)|' \
'.*?\s+(?:ICON|BITMAP|CURSOR|HTML|FONT|MESSAGETABLE|TYPELIB|REGISTRY|D3DFX)' \
'\s*.*?)' \
'\s*(<|"| )([^>"\s]+)(?:[>" ])*$'
resScanner = SCons.Scan... | def RCScan():
| """Return a prototype Scanner instance for scanning RC source files"""
res_re= r'^(?:\s*#\s*(?:include)|' \
'.*?\s+(?:ICON|BITMAP|CURSOR|HTML|FONT|MESSAGETABLE|TYPELIB|REGISTRY|D3DFX)' \
'\s*.*?)' \
'\s*(<|"| )([^>"\s]+)(?:[>" ])*$'
resScanner = SCons.Scanner.ClassicCPP... | OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Scanner/RC.py 5023 2010/06/14 22:05:46 scons"
import SCons.Node.FS
import SCons.Scanner
import re
def RCScan():
| 64 | 64 | 140 | 4 | 59 | smartshowltd/zxing | cpp/scons/scons-local-2.0.0.final.0/SCons/Scanner/RC.py | Python | RCScan | RCScan | 37 | 49 | 37 | 37 | 2a852beb9acc18e2f3c0f22baf58387d875d84b4 | bigcode/the-stack | train |
7402df42e80a22d10ec03aba | train | class | @auto_sr(["id"], repr_=False)
class Student1(Person2):
def __init__(self, id, *args):
super(Student1, self).__init__(*args)
self.id = id
| @auto_sr(["id"], repr_=False)
class Student1(Person2):
| def __init__(self, id, *args):
super(Student1, self).__init__(*args)
self.id = id
| age):
self.name = name
self.surname = surname
self.age = age
class Student0(Person2):
def __init__(self, *args):
super(Student0, self).__init__(*args)
@auto_sr(["id"], repr_=False)
class Student1(Person2):
| 64 | 64 | 45 | 16 | 48 | mavnt/auto_sr | auto_sr/auto_sr_test.py | Python | Student1 | Student1 | 33 | 37 | 33 | 34 | 88c902194ea8cb5c171146f43ec0eb2a1737b43c | bigcode/the-stack | train |
05eff2c34e9aab39bdab01eb | train | class | class Student0(Person2):
def __init__(self, *args):
super(Student0, self).__init__(*args)
| class Student0(Person2):
| def __init__(self, *args):
super(Student0, self).__init__(*args)
| name
self.surname = surname
self.age = age
@auto_sr(["surname"])
class Person2(object):
def __init__(self, name, surname, age):
self.name = name
self.surname = surname
self.age = age
class Student0(Person2):
| 64 | 64 | 27 | 6 | 57 | mavnt/auto_sr | auto_sr/auto_sr_test.py | Python | Student0 | Student0 | 28 | 30 | 28 | 28 | 12df6e685f10c4202e2f4a3e89ca837b816192ef | bigcode/the-stack | train |
44cafcab78734ee870f3a225 | train | class | @auto_sr(["surname"])
class Person2(object):
def __init__(self, name, surname, age):
self.name = name
self.surname = surname
self.age = age
| @auto_sr(["surname"])
class Person2(object):
| def __init__(self, name, surname, age):
self.name = name
self.surname = surname
self.age = age
| self.surname = surname
self.age = age
@auto_sr()
class Person1(object):
def __init__(self, name, surname, age):
self.name = name
self.surname = surname
self.age = age
@auto_sr(["surname"])
class Person2(object):
| 64 | 64 | 43 | 11 | 52 | mavnt/auto_sr | auto_sr/auto_sr_test.py | Python | Person2 | Person2 | 20 | 25 | 20 | 21 | 543174dcf63cae6d7cd60fc7b9b93bbeace48dfe | bigcode/the-stack | train |
3dccefe077f812097be22cb6 | train | class | @auto_sr()
class Person1(object):
def __init__(self, name, surname, age):
self.name = name
self.surname = surname
self.age = age
| @auto_sr()
class Person1(object):
| def __init__(self, name, surname, age):
self.name = name
self.surname = surname
self.age = age
| # coding=utf-8
from .auto_sr import auto_sr
class Person0(object):
def __init__(self, name, surname, age):
self.name = name
self.surname = surname
self.age = age
@auto_sr()
class Person1(object):
| 60 | 64 | 41 | 9 | 50 | mavnt/auto_sr | auto_sr/auto_sr_test.py | Python | Person1 | Person1 | 12 | 17 | 12 | 13 | 5c2590af17526c15336f44524a32321e56007987 | bigcode/the-stack | train |
cad12a2a199c6eedb2cebcb8 | train | class | class Person0(object):
def __init__(self, name, surname, age):
self.name = name
self.surname = surname
self.age = age
| class Person0(object):
| def __init__(self, name, surname, age):
self.name = name
self.surname = surname
self.age = age
| # coding=utf-8
from .auto_sr import auto_sr
class Person0(object):
| 19 | 64 | 37 | 5 | 13 | mavnt/auto_sr | auto_sr/auto_sr_test.py | Python | Person0 | Person0 | 5 | 9 | 5 | 5 | 3865e88611fbcc3cbd909c89827306c77a21b67c | bigcode/the-stack | train |
a84728c278027f1f31ba5334 | train | function | def demo() -> None:
# standard
p0 = Person0("John", "Smith", 55)
print(p0, [p0])
# all
p1 = Person1("John", "Smith", 55)
print(p1, [p1])
# surname only
p2 = Person2("John", "Smith", 55)
print(p2, [p2])
# surname only, inherited from Person2
s0 = Student0("John", "Smith", 5... | def demo() -> None:
# standard
| p0 = Person0("John", "Smith", 55)
print(p0, [p0])
# all
p1 = Person1("John", "Smith", 55)
print(p1, [p1])
# surname only
p2 = Person2("John", "Smith", 55)
print(p2, [p2])
# surname only, inherited from Person2
s0 = Student0("John", "Smith", 55)
print(s0, [s0])
# id (S... | (Student0, self).__init__(*args)
@auto_sr(["id"], repr_=False)
class Student1(Person2):
def __init__(self, id, *args):
super(Student1, self).__init__(*args)
self.id = id
def demo() -> None:
# standard
| 64 | 64 | 160 | 10 | 53 | mavnt/auto_sr | auto_sr/auto_sr_test.py | Python | demo | demo | 40 | 59 | 40 | 41 | 7ba5d924f9c53bf52745ec2cd5c9b2e980696401 | bigcode/the-stack | train |
8aceb45d4aa73392d1003f51 | train | class | class TestApp(unittest.TestCase):
def test_app_instance(self):
app = xw.App()
wb = render_template('template_with_links.xlsx', 'output.xlsx', app=app, book_settings={'update_links': False}, **data)
self.assertEqual(wb.sheets[0]['M1'].value, 'Text for update_links')
wb.app.quit()
| class TestApp(unittest.TestCase):
| def test_app_instance(self):
app = xw.App()
wb = render_template('template_with_links.xlsx', 'output.xlsx', app=app, book_settings={'update_links': False}, **data)
self.assertEqual(wb.sheets[0]['M1'].value, 'Text for update_links')
wb.app.quit()
| def test_update_links_true(self):
wb = render_template('template_with_links.xlsx', 'output.xlsx', book_settings={'update_links': True}, **data)
self.assertEqual(wb.sheets[0]['M1'].value, 'Updated Text for update_links')
class TestApp(unittest.TestCase):
| 64 | 64 | 78 | 7 | 57 | conan-hdk/xlwings | tests/reports/test_report.py | Python | TestApp | TestApp | 124 | 130 | 124 | 125 | c677eccc35ef799fb654900fc75b9bdcc7fac362 | bigcode/the-stack | train |
f8ef5be20288d7e92f2c805b | train | class | class TestFrames(unittest.TestCase):
def tearDown(self):
xw.Book('output.xlsx').app.quit()
def test_one_frame(self):
df = pd.DataFrame([[1., 2.], [3., 4.]],
columns=['c1', 'c2'],
index=['r1', 'r2'])
wb = render_template('template_one_... | class TestFrames(unittest.TestCase):
| def tearDown(self):
xw.Book('output.xlsx').app.quit()
def test_one_frame(self):
df = pd.DataFrame([[1., 2.], [3., 4.]],
columns=['c1', 'c2'],
index=['r1', 'r2'])
wb = render_template('template_one_frame.xlsx', 'output.xlsx', df=df.rese... | class TestBookSettings(unittest.TestCase):
def tearDown(self):
xw.Book('output.xlsx').app.quit()
def test_update_links_false(self):
wb = render_template('template_with_links.xlsx', 'output.xlsx', book_settings={'update_links': False}, **data)
self.assertEqual(wb.sheets[0]['M1'].value, ... | 256 | 256 | 1,276 | 7 | 249 | conan-hdk/xlwings | tests/reports/test_report.py | Python | TestFrames | TestFrames | 133 | 218 | 133 | 134 | 399088916355bd01eabc93b9cd05ecf93f0898bc | bigcode/the-stack | train |
cb7c3d8852ab81a84907542f | train | class | class TestCreateReport(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.wb = render_template('template1.xlsx', 'output.xlsx', **data)
@classmethod
def tearDownClass(cls):
xw.Book('output.xlsx').app.quit()
def test_string(self):
self.assertEqual(self.wb.sheets[0]['... | class TestCreateReport(unittest.TestCase):
@classmethod
| def setUpClass(cls):
cls.wb = render_template('template1.xlsx', 'output.xlsx', **data)
@classmethod
def tearDownClass(cls):
xw.Book('output.xlsx').app.quit()
def test_string(self):
self.assertEqual(self.wb.sheets[0]['A1'].value, 'stringtest')
def test_float(self):
... | 1, 2, 3, 4, 5])
df1 = pd.DataFrame(index=['r0', 'r1'], columns=['c0', 'c1'], data=[[1., 1.], [1., 1.]])
df2 = pd.DataFrame({'name': ['a', 'b', 'c', 'd', 'e'],
'b': [4, 2, 6, 6, 9],
'c': [1, 2, 5, 7, 8],
'd': [1, 1, 1, 6, 7]})
data = dict(mystring='stringtest'... | 243 | 243 | 811 | 12 | 231 | conan-hdk/xlwings | tests/reports/test_report.py | Python | TestCreateReport | TestCreateReport | 46 | 106 | 46 | 48 | 9cb860b408a3a4a1dc431b1bd616c1f65b6007da | bigcode/the-stack | train |
46479632b031580851b28cd6 | train | class | class TestBookSettings(unittest.TestCase):
def tearDown(self):
xw.Book('output.xlsx').app.quit()
def test_update_links_false(self):
wb = render_template('template_with_links.xlsx', 'output.xlsx', book_settings={'update_links': False}, **data)
self.assertEqual(wb.sheets[0]['M1'].value, ... | class TestBookSettings(unittest.TestCase):
| def tearDown(self):
xw.Book('output.xlsx').app.quit()
def test_update_links_false(self):
wb = render_template('template_with_links.xlsx', 'output.xlsx', book_settings={'update_links': False}, **data)
self.assertEqual(wb.sheets[0]['M1'].value, 'Text for update_links')
@unittest.skip... | _shape(self):
self.assertEqual(self.wb.sheets['Sheet6'].shapes[0].text,
'Title\nText bold and italic\n\n• a first bullet\n• a second bullet\n\nAnother title\nthis has a line break\nnew line')
class TestBookSettings(unittest.TestCase):
| 64 | 64 | 171 | 8 | 56 | conan-hdk/xlwings | tests/reports/test_report.py | Python | TestBookSettings | TestBookSettings | 109 | 121 | 109 | 110 | 39c690b0d22a6f34dc19ebbe69558b8042222955 | bigcode/the-stack | train |
8e83e0ac7dddfd04ca0b76dc | train | class | class TestDataFrameFilters(unittest.TestCase):
def tearDown(self):
xw.Book('output.xlsx').app.quit()
def test_df_filters(self):
wb = render_template('template1.xlsx', 'output.xlsx', **data)
self.assertEqual(wb.sheets['df_filters']['A1:E140'].value, wb.sheets['df_filters']['G1:K140'].va... | class TestDataFrameFilters(unittest.TestCase):
| def tearDown(self):
xw.Book('output.xlsx').app.quit()
def test_df_filters(self):
wb = render_template('template1.xlsx', 'output.xlsx', **data)
self.assertEqual(wb.sheets['df_filters']['A1:E140'].value, wb.sheets['df_filters']['G1:K140'].value)
def test_df_filters_in_frames(self):
... | '].color, (221, 235, 247))
self.assertEqual(sheet['F35:I39'].color, (221, 235, 247))
# borders
# TODO: pending Border implementation in xlwings
if sys.platform.startswith('darwin'):
from appscript import k as kw
for cell in ['A4', 'A14', 'D20', 'A28', 'D36', 'F4'... | 193 | 193 | 645 | 9 | 183 | conan-hdk/xlwings | tests/reports/test_report.py | Python | TestDataFrameFilters | TestDataFrameFilters | 222 | 260 | 222 | 223 | 2af9868f6a21992b00b08bf360d2c514ede0ff3c | bigcode/the-stack | train |
0c0aa6c65eda651289991dc1 | train | class | class BinaryFiles(DataLoader):
def __init__(self, reader: ByteIO):
self.reader = reader
self.items = []
def read(self):
reader = self.reader
count = reader.read_uint32()
if self.settings.get('VERBOSE', False):
print(f'Found {count} BinaryFiles!')
sel... | class BinaryFiles(DataLoader):
| def __init__(self, reader: ByteIO):
self.reader = reader
self.items = []
def read(self):
reader = self.reader
count = reader.read_uint32()
if self.settings.get('VERBOSE', False):
print(f'Found {count} BinaryFiles!')
self.items = [BinaryItem(reader)
... | ByteIO):
self.reader = reader
self.name = None
self.data = None
def read(self):
reader = self.reader
self.name = reader.read_wide_string(reader.read_uint16())
self.data = reader.read_bytes(reader.read_uint16())
class BinaryFiles(DataLoader):
| 64 | 64 | 86 | 6 | 58 | lab313ru/ClicktfDecompiler | Chunks/yves.py | Python | BinaryFiles | BinaryFiles | 23 | 35 | 23 | 24 | 1f5718d8ffdcb9663314694414f5d0c3d462f9c3 | bigcode/the-stack | train |
638933168a017fb3ce34f6af | train | class | class AppIcon(DataLoader):
width = 16
height = 16
def __init__(self, reader: ByteIO):
self.reader = reader
self.points = None
self.alpha = []
def read(self):
print('Dumping app icon')
reader = self.reader
reader.read_bytes(reader.read_int32() - 4)
... | class AppIcon(DataLoader):
| width = 16
height = 16
def __init__(self, reader: ByteIO):
self.reader = reader
self.points = None
self.alpha = []
def read(self):
print('Dumping app icon')
reader = self.reader
reader.read_bytes(reader.read_int32() - 4)
color_indexes = []
... | _string(reader.read_uint16())
self.data = reader.read_bytes(reader.read_uint16())
class BinaryFiles(DataLoader):
def __init__(self, reader: ByteIO):
self.reader = reader
self.items = []
def read(self):
reader = self.reader
count = reader.read_uint32()
if self.... | 110 | 111 | 370 | 6 | 104 | lab313ru/ClicktfDecompiler | Chunks/yves.py | Python | AppIcon | AppIcon | 38 | 82 | 38 | 38 | 94a61360bba1418ca8fe350eccbbfebea088fda5 | bigcode/the-stack | train |
eb7e0b6cce34692e34cb5600 | train | class | class BinaryItem(DataLoader):
def __init__(self, reader: ByteIO):
self.reader = reader
self.name = None
self.data = None
def read(self):
reader = self.reader
self.name = reader.read_wide_string(reader.read_uint16())
self.data = reader.read_bytes(reader.read_uint... | class BinaryItem(DataLoader):
| def __init__(self, reader: ByteIO):
self.reader = reader
self.name = None
self.data = None
def read(self):
reader = self.reader
self.name = reader.read_wide_string(reader.read_uint16())
self.data = reader.read_bytes(reader.read_uint16())
| import os
from PIL import Image
import byteflag
from CTF_ByteIO import ByteIO
from Loader import DataLoader
class BinaryItem(DataLoader):
| 34 | 64 | 73 | 6 | 27 | lab313ru/ClicktfDecompiler | Chunks/yves.py | Python | BinaryItem | BinaryItem | 10 | 20 | 10 | 11 | bd6d9cc18f72dfd54b9424c98fa8bd1a249987bf | bigcode/the-stack | train |
f7919310d69d56dc5345dec5 | train | function | def anyMonth(numTrials):
any48 = 0
for j in range(numTrials):
monthB = 0
for i in range(446):
if random.randint(1,12) == 6:
monthB += 1
if monthB >= 46:
any48 += 1
mProb = any48/float(numTrials)
print('more than 48 births p... | def anyMonth(numTrials):
| any48 = 0
for j in range(numTrials):
monthB = 0
for i in range(446):
if random.randint(1,12) == 6:
monthB += 1
if monthB >= 46:
any48 += 1
mProb = any48/float(numTrials)
print('more than 48 births prob for any month', mProb)... | -*-
"""
Spyder Editor
Calculate the probability of more than 46 births in any month for 446 births. 446/12 is around 37, and 46 births means 30% more than 'average rate'
This is a temporary script file.
"""
import random
def anyMonth(numTrials):
| 64 | 64 | 99 | 6 | 57 | arvindkarir/python-pandas-code | Py exercises/ProbabilityOfMonthBirth.py | Python | anyMonth | anyMonth | 9 | 20 | 9 | 9 | 63e9228fe1c68078ccc41ddd1aace2e97d6865a5 | bigcode/the-stack | train |
9728dde43fc4e957967b74e1 | train | class | class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
#####
res = ''
a = list(a)
b = list(b)
carry = 0
while a or b or carry:
if a:
carry += int(a.pop())
... | class Solution(object):
| def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
#####
res = ''
a = list(a)
b = list(b)
carry = 0
while a or b or carry:
if a:
carry += int(a.pop())
if b:
... | """67. Add Binary"""
class Solution(object):
| 10 | 64 | 193 | 4 | 6 | wilbertgeng/LeetCode_exercise | 67.py | Python | Solution | Solution | 3 | 40 | 3 | 3 | 748c7ccefced3166d0eb9a3524ecfc710d0a47c3 | bigcode/the-stack | train |
d1616d9224c793e2d46b2707 | train | class | class OCPAzureInstanceTypeView(OCPAzureView):
"""Get OpenShift on Azure instance usage data."""
report = "instance_type"
| class OCPAzureInstanceTypeView(OCPAzureView):
| """Get OpenShift on Azure instance usage data."""
report = "instance_type"
|
query_handler = OCPAzureReportQueryHandler
tag_handler = [OCPAzureTagsSummary]
class OCPAzureCostView(OCPAzureView):
"""Get OpenShift on Azure cost usage data."""
report = "costs"
class OCPAzureInstanceTypeView(OCPAzureView):
| 64 | 64 | 30 | 12 | 52 | rubik-ai/koku | koku/api/report/azure/openshift/view.py | Python | OCPAzureInstanceTypeView | OCPAzureInstanceTypeView | 31 | 34 | 31 | 31 | 9e810d2f80ca27749e8bb5fc57c690b30b0a8db7 | bigcode/the-stack | train |
ce09fd96ec1898f4cfb3af2f | train | class | class OCPAzureCostView(OCPAzureView):
"""Get OpenShift on Azure cost usage data."""
report = "costs"
| class OCPAzureCostView(OCPAzureView):
| """Get OpenShift on Azure cost usage data."""
report = "costs"
| = [AzureAccessPermission, OpenShiftAccessPermission]
provider = Provider.OCP_AZURE
serializer = OCPAzureQueryParamSerializer
query_handler = OCPAzureReportQueryHandler
tag_handler = [OCPAzureTagsSummary]
class OCPAzureCostView(OCPAzureView):
| 64 | 64 | 29 | 11 | 53 | rubik-ai/koku | koku/api/report/azure/openshift/view.py | Python | OCPAzureCostView | OCPAzureCostView | 25 | 28 | 25 | 25 | 53e6ffb5f72ef8ce3ee20da133890c847a149bc3 | bigcode/the-stack | train |
79d55b059952eab3abe1d092 | train | class | class OCPAzureView(ReportView):
"""OCP+Azure Base View."""
permission_classes = [AzureAccessPermission, OpenShiftAccessPermission]
provider = Provider.OCP_AZURE
serializer = OCPAzureQueryParamSerializer
query_handler = OCPAzureReportQueryHandler
tag_handler = [OCPAzureTagsSummary]
| class OCPAzureView(ReportView):
| """OCP+Azure Base View."""
permission_classes = [AzureAccessPermission, OpenShiftAccessPermission]
provider = Provider.OCP_AZURE
serializer = OCPAzureQueryParamSerializer
query_handler = OCPAzureReportQueryHandler
tag_handler = [OCPAzureTagsSummary]
| api.models import Provider
from api.report.azure.openshift.query_handler import OCPAzureReportQueryHandler
from api.report.azure.openshift.serializers import OCPAzureQueryParamSerializer
from api.report.view import ReportView
from reporting.models import OCPAzureTagsSummary
class OCPAzureView(ReportView):
| 64 | 64 | 74 | 9 | 54 | rubik-ai/koku | koku/api/report/azure/openshift/view.py | Python | OCPAzureView | OCPAzureView | 15 | 22 | 15 | 15 | 404440060edc31348849abea2c9f92f78de540b3 | bigcode/the-stack | train |
0367f5c40558478b29106323 | train | class | class OCPAzureStorageView(OCPAzureView):
"""Get OpenShift on Azure storage usage data."""
report = "storage"
| class OCPAzureStorageView(OCPAzureView):
| """Get OpenShift on Azure storage usage data."""
report = "storage"
| (OCPAzureView):
"""Get OpenShift on Azure cost usage data."""
report = "costs"
class OCPAzureInstanceTypeView(OCPAzureView):
"""Get OpenShift on Azure instance usage data."""
report = "instance_type"
class OCPAzureStorageView(OCPAzureView):
| 64 | 64 | 28 | 11 | 53 | rubik-ai/koku | koku/api/report/azure/openshift/view.py | Python | OCPAzureStorageView | OCPAzureStorageView | 37 | 40 | 37 | 37 | ea7f87d3eb4de1f9caead68e7d1279e84cb88201 | bigcode/the-stack | train |
f618635e272feeae005afdad | train | function | def ConvertToLLVMFormat(vixl_instruction, triple):
"""
Take an string representing an instruction and convert it to assembly syntax
for LLVM. VIXL's test generation framework will print instruction
representations as a space seperated list. The first element is the mnemonic
and the following elements are oper... | def ConvertToLLVMFormat(vixl_instruction, triple):
| """
Take an string representing an instruction and convert it to assembly syntax
for LLVM. VIXL's test generation framework will print instruction
representations as a space seperated list. The first element is the mnemonic
and the following elements are operands.
"""
# Dictionnary of patterns. The key i... | , r2 @ encoding: [0x12,0x0f,0x6f,0x01]
The script will finally extract the encoding and compare it to what VIXL
generated.
"""
import argparse
import subprocess
import os
import re
import itertools
import types
def BuildOptions():
result = argparse.ArgumentParser(
description = 'Use `llvm-mc... | 255 | 256 | 2,366 | 12 | 243 | Componolit/android_external_vixl | tools/verify_assembler_traces.py | Python | ConvertToLLVMFormat | ConvertToLLVMFormat | 135 | 318 | 135 | 135 | 3f6b9ec558d14ea0116eb9aca12c07e4e27ac762 | bigcode/the-stack | train |
006ce237479723505ae15807 | train | function | def ReadTrace(trace):
"""
Receive the content of an assembler trace, extract the relevant information
and return it as a list of tuples. The first part of each typle is a string
representing the instruction. The second part is a list of bytes representing
the encoding.
For example:
[
("Clz e... | def ReadTrace(trace):
| """
Receive the content of an assembler trace, extract the relevant information
and return it as a list of tuples. The first part of each typle is a string
representing the instruction. The second part is a list of bytes representing
the encoding.
For example:
[
("Clz eq r0 r0", ["0x10", "0x... | result` is a string, use it as the format string.
assert(isinstance(result, str))
llvm_instruction.append(result.format(*match.groups()))
break
if llvm_instruction:
return "\n".join(llvm_instruction)
# No converters worked so raise an exception.
raise Exception("Unsupported instr... | 76 | 76 | 254 | 5 | 71 | Componolit/android_external_vixl | tools/verify_assembler_traces.py | Python | ReadTrace | ReadTrace | 321 | 343 | 321 | 321 | 711d51dd5f8aa932a94d4906f9be017d685a7a1f | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.