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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3c143eece24136be226b0d5f | train | function | def main_parser(): # type: () -> argparse.ArgumentParser
'''
Constructs the main parser
'''
cwd = os.getcwd()
out = os.path.join(cwd, 'dist')
parser = argparse.ArgumentParser()
parser.add_argument('srcdir',
type=str, nargs='?', metavar='.', default=cwd,
... | def main_parser(): # type: () -> argparse.ArgumentParser
| '''
Constructs the main parser
'''
cwd = os.getcwd()
out = os.path.join(cwd, 'dist')
parser = argparse.ArgumentParser()
parser.add_argument('srcdir',
type=str, nargs='?', metavar='.', default=cwd,
help='source directory (defaults to current dir... | _dependencies)
except BuildException as e:
_error(str(e))
except BuildBackendException as e:
if sys.version_info >= (3, 5):
print(traceback.format_exc(-1))
else:
print(traceback.format_exc())
_error(str(e))
def main_parser(): # type: () -> argparse.Argume... | 74 | 74 | 247 | 14 | 60 | di/python-build | src/build/__main__.py | Python | main_parser | main_parser | 93 | 121 | 93 | 93 | 0535b498cbe2d29b97fff1c04f6aa7de4d29fdbc | bigcode/the-stack | train |
42aeb5ca26a64719e7149d36 | train | function | def _showwarning(message, category, filename, lineno, file=None, line=None): # pragma: no cover
# type: (str, Type[Warning], str, int, Optional[TextIO], Optional[str]) -> None
prefix = 'WARNING'
if sys.stdout.isatty():
prefix = '\33[93m' + prefix + '\33[0m'
print('{} {}'.format(prefix, message)... | def _showwarning(message, category, filename, lineno, file=None, line=None): # pragma: no cover
# type: (str, Type[Warning], str, int, Optional[TextIO], Optional[str]) -> None
| prefix = 'WARNING'
if sys.stdout.isatty():
prefix = '\33[93m' + prefix + '\33[0m'
print('{} {}'.format(prefix, message))
| __ = ['build', 'main', 'main_parser']
def _showwarning(message, category, filename, lineno, file=None, line=None): # pragma: no cover
# type: (str, Type[Warning], str, int, Optional[TextIO], Optional[str]) -> None
| 64 | 64 | 93 | 52 | 12 | di/python-build | src/build/__main__.py | Python | _showwarning | _showwarning | 18 | 23 | 18 | 19 | 8f74d252e6cc150ac663b5b6ff808af7bab52ecc | bigcode/the-stack | train |
edbd37ccbafa3b5aa9bed28f | train | function | def build(srcdir, outdir, distributions, config_settings=None, isolation=True, skip_dependencies=False):
# type: (str, str, List[str], Optional[ConfigSettings], bool, bool) -> None
'''
Runs the build process
:param srcdir: Source directory
:param outdir: Output directory
:param distributions: D... | def build(srcdir, outdir, distributions, config_settings=None, isolation=True, skip_dependencies=False):
# type: (str, str, List[str], Optional[ConfigSettings], bool, bool) -> None
| '''
Runs the build process
:param srcdir: Source directory
:param outdir: Output directory
:param distributions: Distributions to build (sdist and/or wheel)
:param config_settings: Configuration settings to be passed to the backend
:param isolation: Isolate the build in a separate environme... | _error('Missing dependencies:' + ''.join(['\n\t' + dep for dep in missing]))
builder.build(dist, outdir)
def build(srcdir, outdir, distributions, config_settings=None, isolation=True, skip_dependencies=False):
# type: (str, str, List[str], Optional[ConfigSettings], bool, bool) -> None
| 75 | 75 | 251 | 45 | 30 | di/python-build | src/build/__main__.py | Python | build | build | 61 | 90 | 61 | 62 | 35662846ea2e86932f78ee03a0aaadd0dfb3cd2a | bigcode/the-stack | train |
b116e416f70eb0382d942b2f | train | function | def _build_in_isolated_env(builder, outdir, distributions): # type: (ProjectBuilder, str, List[str]) -> None
with IsolatedEnvironment() as env:
env.install(builder.build_dependencies)
for distribution in distributions:
builder.build(distribution, outdir)
| def _build_in_isolated_env(builder, outdir, distributions): # type: (ProjectBuilder, str, List[str]) -> None
| with IsolatedEnvironment() as env:
env.install(builder.build_dependencies)
for distribution in distributions:
builder.build(distribution, outdir)
| atty():
prefix = '\33[91m' + prefix + '\33[0m'
print('{} {}'.format(prefix, msg))
exit(code)
def _build_in_isolated_env(builder, outdir, distributions): # type: (ProjectBuilder, str, List[str]) -> None
| 64 | 64 | 61 | 30 | 34 | di/python-build | src/build/__main__.py | Python | _build_in_isolated_env | _build_in_isolated_env | 43 | 47 | 43 | 43 | c09637bb9c498fed94b5f9e05f970b4652aac076 | bigcode/the-stack | train |
48c169252d42b1948cdfddfa | train | function | def _error(msg, code=1): # type: (str, int) -> None # pragma: no cover
'''
Prints an error message and exits. Will color the output when writting to a TTY.
:param msg: Error message
:param code: Error code
'''
prefix = 'ERROR'
if sys.stdout.isatty():
prefix = '\33[91m' + prefix + ... | def _error(msg, code=1): # type: (str, int) -> None # pragma: no cover
| '''
Prints an error message and exits. Will color the output when writting to a TTY.
:param msg: Error message
:param code: Error code
'''
prefix = 'ERROR'
if sys.stdout.isatty():
prefix = '\33[91m' + prefix + '\33[0m'
print('{} {}'.format(prefix, msg))
exit(code)
| ty():
prefix = '\33[93m' + prefix + '\33[0m'
print('{} {}'.format(prefix, message))
warnings.showwarning = _showwarning
def _error(msg, code=1): # type: (str, int) -> None # pragma: no cover
| 64 | 64 | 112 | 27 | 36 | di/python-build | src/build/__main__.py | Python | _error | _error | 29 | 40 | 29 | 29 | c8da2220c7a998dd48151090779418548fe6cd9c | bigcode/the-stack | train |
0396ea3a2ed106ddd07afbbc | train | function | def supervisor():
signal = Signal()
spinner = threading.Thread(target=spin, args=('thinking!', signal))
print('spinner object:', spinner)
spinner.start()
result = slow_function()
signal.go = False
spinner.join()
return result
| def supervisor():
| signal = Signal()
spinner = threading.Thread(target=spin, args=('thinking!', signal))
print('spinner object:', spinner)
spinner.start()
result = slow_function()
signal.go = False
spinner.join()
return result
| )
flush()
write('\x08' * len(status))
time.sleep(.1)
if not signal.go:
break
write(' ' * len(status) + '\x08' * len(status))
def slow_function():
time.sleep(3)
return 42
def supervisor():
| 64 | 64 | 55 | 3 | 60 | Lin0818/py-study-notebook | notebook/spinner_thread.py | Python | supervisor | supervisor | 26 | 34 | 26 | 26 | 7f120fe41c699d71826026a498452fd0a8126adc | bigcode/the-stack | train |
9a9bc72369de0421a435ceb5 | train | class | class Signal:
go = True
| class Signal:
| go = True
| # spinner_thread.py
import threading
import itertools
import time
import sys
class Signal:
| 20 | 64 | 8 | 3 | 16 | Lin0818/py-study-notebook | notebook/spinner_thread.py | Python | Signal | Signal | 7 | 8 | 7 | 7 | 8a385829aae3517c786d354638522d297e160c90 | bigcode/the-stack | train |
8e4fa463a96972a6b2ffac0d | train | function | def spin(msg, signal):
write, flush = sys.stdout.write, sys.stdout.flush
for char in itertools.cycle('|/-\\'):
status = char + ' ' + msg
write(status)
flush()
write('\x08' * len(status))
time.sleep(.1)
if not signal.go:
break
write(' ' * len(status... | def spin(msg, signal):
| write, flush = sys.stdout.write, sys.stdout.flush
for char in itertools.cycle('|/-\\'):
status = char + ' ' + msg
write(status)
flush()
write('\x08' * len(status))
time.sleep(.1)
if not signal.go:
break
write(' ' * len(status) + '\x08' * len(status... | # spinner_thread.py
import threading
import itertools
import time
import sys
class Signal:
go = True
def spin(msg, signal):
| 31 | 64 | 89 | 6 | 24 | Lin0818/py-study-notebook | notebook/spinner_thread.py | Python | spin | spin | 10 | 20 | 10 | 10 | b36ebf0430633ba545e6d2e70e7c249f12232c13 | bigcode/the-stack | train |
2ba3a244a79c824a4038f457 | train | function | def slow_function():
time.sleep(3)
return 42
| def slow_function():
| time.sleep(3)
return 42
| '):
status = char + ' ' + msg
write(status)
flush()
write('\x08' * len(status))
time.sleep(.1)
if not signal.go:
break
write(' ' * len(status) + '\x08' * len(status))
def slow_function():
| 64 | 64 | 15 | 4 | 60 | Lin0818/py-study-notebook | notebook/spinner_thread.py | Python | slow_function | slow_function | 22 | 24 | 22 | 22 | 38ef43433f7fff71d253d345772277c479536eae | bigcode/the-stack | train |
74311179bd11fc14da89715c | train | function | def main():
result = supervisor()
print('Answer:', result)
| def main():
| result = supervisor()
print('Answer:', result)
| )
return 42
def supervisor():
signal = Signal()
spinner = threading.Thread(target=spin, args=('thinking!', signal))
print('spinner object:', spinner)
spinner.start()
result = slow_function()
signal.go = False
spinner.join()
return result
def main():
| 64 | 64 | 15 | 3 | 60 | Lin0818/py-study-notebook | notebook/spinner_thread.py | Python | main | main | 36 | 38 | 36 | 36 | 4046ece17d382cbe155cbd95d952a45f2d8a8e1a | bigcode/the-stack | train |
d90a4135c17cb207925697dd | train | class | class Migration(migrations.Migration):
dependencies = [
('places', '0053_auto_20180212_2017'),
]
operations = [
migrations.AddField(
model_name='place',
name='populartimes_updated_at',
field=models.DateTimeField(blank=True, null=True, verbose_name=django... | class Migration(migrations.Migration):
| dependencies = [
('places', '0053_auto_20180212_2017'),
]
operations = [
migrations.AddField(
model_name='place',
name='populartimes_updated_at',
field=models.DateTimeField(blank=True, null=True, verbose_name=django.db.models.fields.DateTimeField),
... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-02-14 12:07
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.fields
class Migration(migrations.Migration):
| 60 | 64 | 81 | 7 | 52 | jasmine92122/NightClubBackend | good_spot/places/migrations/0054_place_populartimes_updated_at.py | Python | Migration | Migration | 9 | 21 | 9 | 10 | 447d1f0e88c78a03cd31a2287845ed5c0846d57e | bigcode/the-stack | train |
cb278d7f9dc2c26de8876626 | train | class | class TestTableDisplayAPI_seStringFormatMethod(unittest.TestCase):
def test_should_set_string_format_default_for_time(self):
# given
df = pd.read_csv(os.path.dirname(__file__) + "/resources/" + 'interest-rates.csv')
table = TableDisplay(df)
# when
table.setStringFormatForTyp... | class TestTableDisplayAPI_seStringFormatMethod(unittest.TestCase):
| def test_should_set_string_format_default_for_time(self):
# given
df = pd.read_csv(os.path.dirname(__file__) + "/resources/" + 'interest-rates.csv')
table = TableDisplay(df)
# when
table.setStringFormatForType(ColumnType.Time, TableDisplayStringFormat.getTimeFormat())
... | at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language gov... | 137 | 137 | 458 | 13 | 124 | Ben-Epstein/beakerx | beakerx_tabledisplay/beakerx_tabledisplay/tests/test_tabledisplay_api_set_string_format_method.py | Python | TestTableDisplayAPI_seStringFormatMethod | TestTableDisplayAPI_seStringFormatMethod | 26 | 70 | 26 | 27 | 0573f799d9345b9218479977c83c5f6ee6635cbc | bigcode/the-stack | train |
117f4cfca43a206a16cd72ba | train | function | def test_file(file_regression):
md = MarkdownIt("commonmark")
file_regression.check(md.render(SPEC_INPUT.read_text()), extension=".html")
| def test_file(file_regression):
| md = MarkdownIt("commonmark")
file_regression.check(md.render(SPEC_INPUT.read_text()), extension=".html")
| github.com/commonmark/CommonMark.git.
"""
import json
from pathlib import Path
import pytest
from markdown_it import MarkdownIt
SPEC_INPUT = Path(__file__).parent.joinpath("spec.md")
TESTS_INPUT = Path(__file__).parent.joinpath("commonmark.json")
def test_file(file_regression):
| 64 | 64 | 33 | 7 | 57 | tadeu/markdown-it-py | tests/test_cmark_spec/test_spec.py | Python | test_file | test_file | 15 | 17 | 15 | 15 | 0eca7778025c293dcf81154d1b0d076bd09a3050 | bigcode/the-stack | train |
5376e2a59f3d778da9fca0c0 | train | function | @pytest.mark.parametrize("entry", json.loads(TESTS_INPUT.read_text()))
def test_spec(entry):
md = MarkdownIt("commonmark")
output = md.render(entry["markdown"])
expected = entry["html"]
if entry["example"] == 593:
# this doesn't have any bearing on the output
output = output.replace("ma... | @pytest.mark.parametrize("entry", json.loads(TESTS_INPUT.read_text()))
def test_spec(entry):
| md = MarkdownIt("commonmark")
output = md.render(entry["markdown"])
expected = entry["html"]
if entry["example"] == 593:
# this doesn't have any bearing on the output
output = output.replace("mailto", "MAILTO")
if entry["example"] in [187, 209, 210]:
# this doesn't have any ... | Path(__file__).parent.joinpath("commonmark.json")
def test_file(file_regression):
md = MarkdownIt("commonmark")
file_regression.check(md.render(SPEC_INPUT.read_text()), extension=".html")
@pytest.mark.parametrize("entry", json.loads(TESTS_INPUT.read_text()))
def test_spec(entry):
| 64 | 64 | 131 | 19 | 45 | tadeu/markdown-it-py | tests/test_cmark_spec/test_spec.py | Python | test_spec | test_spec | 20 | 35 | 20 | 21 | b4fec48f647b60f7ea1e7cd514836eab5c63faa4 | bigcode/the-stack | train |
7c6e0f8b25d8a432c6463f58 | train | function | @manager.shell
def make_shell_context():
return dict(app = app,db = db,User = User, Role = Role )
| @manager.shell
def make_shell_context():
| return dict(app = app,db = db,User = User, Role = Role )
| )
manager.add_command('db',MigrateCommand)
@manager.command
def test():
"""Run the unit tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
@manager.shell
def make_shell_context():
| 63 | 64 | 28 | 9 | 54 | kasparov-creat/Vividly-Pitchology | manage.py | Python | make_shell_context | make_shell_context | 22 | 24 | 22 | 23 | d3e2034387c80c6144f55af00bf9096e287a27fd | bigcode/the-stack | train |
35acfd390c29206019df1f26 | train | function | @manager.command
def test():
"""Run the unit tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
| @manager.command
def test():
| """Run the unit tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
| , MigrateCommand
from app.models import User,Role
# Creating app instance
app = create_app('production')
manager = Manager(app)
migrate = Migrate(app,db)
manager.add_command('server',Server)
manager.add_command('db',MigrateCommand)
@manager.command
def test():
| 64 | 64 | 43 | 7 | 57 | kasparov-creat/Vividly-Pitchology | manage.py | Python | test | test | 15 | 20 | 15 | 16 | 098573fa28931e3576c9a791c3f9efbb1dddeefe | bigcode/the-stack | train |
d99207aba0ee4d2512fb9dcc | train | class | class Search(BaseBackend):
def init_app(self, app):
app.config.setdefault('MSEARCH_BACKEND', 'whoosh')
msearch_backend = app.config['MSEARCH_BACKEND']
if msearch_backend == 'simple':
from .simple_backend import SimpleSearch
self._backend = SimpleSearch(app, self.db, s... | class Search(BaseBackend):
| def init_app(self, app):
app.config.setdefault('MSEARCH_BACKEND', 'whoosh')
msearch_backend = app.config['MSEARCH_BACKEND']
if msearch_backend == 'simple':
from .simple_backend import SimpleSearch
self._backend = SimpleSearch(app, self.db, self.analyzer)
elif ... | : 2017-04-15 20:03:18 (CST)
# Last Update:星期三 2017-8-16 12:51:15 (CST)
# By:
# Description:
# **************************************************************************
from .backends import BaseBackend
class Search(BaseBackend):
| 64 | 64 | 150 | 5 | 58 | huangcun666/blog | venv/lib/python3.5/site-packages/flask_msearch/__init__.py | Python | Search | Search | 16 | 30 | 16 | 16 | 1df97437bb508b563f178282fcad998902de3fda | bigcode/the-stack | train |
012a49bd647327d6945c192c | train | class | class EHNamespaceSchemaRegistry(ScenarioTest):
from azure.cli.testsdk.scenario_tests import AllowLargeResponse
@AllowLargeResponse()
@ResourceGroupPreparer(name_prefix='cli_test_eh_namespace')
def test_eventhub_schema_registry(self, resource_group):
self.kwargs.update({
'loc': 'west... | class EHNamespaceSchemaRegistry(ScenarioTest):
| from azure.cli.testsdk.scenario_tests import AllowLargeResponse
@AllowLargeResponse()
@ResourceGroupPreparer(name_prefix='cli_test_eh_namespace')
def test_eventhub_schema_registry(self, resource_group):
self.kwargs.update({
'loc': 'westus2',
'rg': resource_group,
... | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | 99 | 256 | 929 | 9 | 89 | ZengTaoxu/azure-cli | src/azure-cli/azure/cli/command_modules/eventhubs/tests/latest/test_eventhub_namespace_schema_registry.py | Python | EHNamespaceSchemaRegistry | EHNamespaceSchemaRegistry | 17 | 84 | 17 | 17 | 9c50e0a44e97af3d68f6a5356571f02dec6f71fc | bigcode/the-stack | train |
f290ef3032141a685bc4de60 | train | function | def sudo_remove_dirtree(dir_name):
"""Removes directory tree as a superuser.
Args:
dir_name: name of the directory to remove.
This function is necessary to cleanup directories created from inside a
Docker, since they usually written as a root, thus have to be removed as a
root.
"""
t... | def sudo_remove_dirtree(dir_name):
| """Removes directory tree as a superuser.
Args:
dir_name: name of the directory to remove.
This function is necessary to cleanup directories created from inside a
Docker, since they usually written as a root, thus have to be removed as a
root.
"""
try:
subprocess.check_output... | docker",
"run",
"-v",
"{0}:/output_dir".format(dirname),
"busybox:1.27.2",
"chmod",
"-R",
"a+rwx",
"/output_dir",
]
)
def sudo_remove_dirtree(dir_name):
| 64 | 64 | 120 | 9 | 55 | saumya0303/cleverhans | cleverhans_v3.1.0/examples/nips17_adversarial_competition/eval_infra/code/worker.py | Python | sudo_remove_dirtree | sudo_remove_dirtree | 122 | 135 | 122 | 122 | d5e668612e10da6f92a27afc5a2ce2b173d85908 | bigcode/the-stack | train |
fb2cd6f890bfc92dc0476dee | train | class | class EvaluationWorker(object):
"""Class which encapsulate logit of the worker.
Main entry point of this class is EvaluationWorker.run_work method which
performs cleanup of temporary directories, then runs
EvaluationWorker.run_attacks and EvaluationWorker.run_defenses
"""
def __init__(
... | class EvaluationWorker(object):
| """Class which encapsulate logit of the worker.
Main entry point of this class is EvaluationWorker.run_work method which
performs cleanup of temporary directories, then runs
EvaluationWorker.run_attacks and EvaluationWorker.run_defenses
"""
def __init__(
self,
worker_id,
... | def run(self, input_dir, output_file_path):
"""Runs defense inside Docker.
Args:
input_dir: directory with input (adversarial images).
output_file_path: path of the output file.
Returns:
how long it took to run submission in seconds
"""
logging... | 256 | 256 | 3,884 | 5 | 250 | saumya0303/cleverhans | cleverhans_v3.1.0/examples/nips17_adversarial_competition/eval_infra/code/worker.py | Python | EvaluationWorker | EvaluationWorker | 539 | 1,027 | 539 | 539 | cd377d52a0bb44ac08193f272d382baf969b776c | bigcode/the-stack | train |
706123d2ca414a0548e14086 | train | function | def kill_docker_container(container_name):
"""Kills given docker container."""
docker_id = get_id_of_running_docker(container_name)
shell_call([DOCKER_BINARY, "stop", docker_id])
| def kill_docker_container(container_name):
| """Kills given docker container."""
docker_id = get_id_of_running_docker(container_name)
shell_call([DOCKER_BINARY, "stop", docker_id])
| DOCKER_BINARY, "ps", "-q", "--filter=name={}".format(container_name)]
).strip()
def is_docker_still_running(container_name):
"""Returns whether given Docker container is still running."""
return bool(get_id_of_running_docker(container_name))
def kill_docker_container(container_name):
| 64 | 64 | 42 | 8 | 56 | saumya0303/cleverhans | cleverhans_v3.1.0/examples/nips17_adversarial_competition/eval_infra/code/worker.py | Python | kill_docker_container | kill_docker_container | 177 | 180 | 177 | 177 | 2733d64152070d5d5044830dc49329ba48bba42a | bigcode/the-stack | train |
e7645ac4431b590c088fe73f | train | class | class WorkerError(Exception):
"""Error which happen during evaluation of submission.
To simplify error handling, worker only raises this type of exception.
Exceptions of different types raised by other modules encapsulated
into WorkerError by the worker.
"""
def __init__(self, message, exc=Non... | class WorkerError(Exception):
| """Error which happen during evaluation of submission.
To simplify error handling, worker only raises this type of exception.
Exceptions of different types raised by other modules encapsulated
into WorkerError by the worker.
"""
def __init__(self, message, exc=None):
"""Initializes Wor... | be removed as a
root.
"""
try:
subprocess.check_output(["sudo", "rm", "-rf", dir_name])
except subprocess.CalledProcessError as e:
raise WorkerError("Can" "t remove directory {0}".format(dir_name), e)
class WorkerError(Exception):
| 64 | 64 | 161 | 5 | 59 | saumya0303/cleverhans | cleverhans_v3.1.0/examples/nips17_adversarial_competition/eval_infra/code/worker.py | Python | WorkerError | WorkerError | 138 | 162 | 138 | 138 | 2bb05021c3ef75984c05c64b8eb3894adda9582d | bigcode/the-stack | train |
66e41094e21672acd4a866a4 | train | function | def main(args):
"""Main function which runs worker."""
title = "## Starting evaluation of round {0} ##".format(args.round_name)
logging.info(
"\n"
+ "#" * len(title)
+ "\n"
+ "#" * len(title)
+ "\n"
+ "##"
+ " " * (len(title) - 2)
+ "##"
... | def main(args):
| """Main function which runs worker."""
title = "## Starting evaluation of round {0} ##".format(args.round_name)
logging.info(
"\n"
+ "#" * len(title)
+ "\n"
+ "#" * len(title)
+ "\n"
+ "##"
+ " " * (len(title) - 2)
+ "##"
+ "\n"
... | .warning(
"Can" 't update work "%s" as completed by worker %d',
work_id,
self.worker_id,
)
need_reload_work = True
logging.info("******** Finished evaluation of defenses ********")
def run_work(self):
"""Run... | 103 | 103 | 345 | 4 | 99 | saumya0303/cleverhans | cleverhans_v3.1.0/examples/nips17_adversarial_competition/eval_infra/code/worker.py | Python | main | main | 1,030 | 1,075 | 1,030 | 1,030 | 443aeb8c4334993e85730d9f231f9f8e784d27c6 | bigcode/the-stack | train |
9e461ec38e3da514879f9e54 | train | class | class ExecutableSubmission(object):
"""Base class which is used to run submissions."""
def __init__(self, submission_id, submissions, storage_bucket):
"""Initializes ExecutableSubmission.
Args:
submission_id: ID of the submissions
submissions: instance of CompetitionSubmiss... | class ExecutableSubmission(object):
| """Base class which is used to run submissions."""
def __init__(self, submission_id, submissions, storage_bucket):
"""Initializes ExecutableSubmission.
Args:
submission_id: ID of the submissions
submissions: instance of CompetitionSubmissions with all submissions
... | by other modules encapsulated
into WorkerError by the worker.
"""
def __init__(self, message, exc=None):
"""Initializes WorkerError.
Args:
message: error message
exc: optional underlying exception.
"""
super(WorkerError, self).__init__()
self.ms... | 256 | 256 | 1,936 | 6 | 250 | saumya0303/cleverhans | cleverhans_v3.1.0/examples/nips17_adversarial_competition/eval_infra/code/worker.py | Python | ExecutableSubmission | ExecutableSubmission | 183 | 419 | 183 | 183 | 19574736ca07fa159e80ed004873be04ace74677 | bigcode/the-stack | train |
eb05069d66eb556b35032d14 | train | class | class AttackSubmission(ExecutableSubmission):
"""Class to run attack submissions."""
def __init__(self, submission_id, submissions, storage_bucket):
"""Initializes AttackSubmission.
Args:
submission_id: ID of the submission
submissions: instance of CompetitionSubmissions wi... | class AttackSubmission(ExecutableSubmission):
| """Class to run attack submissions."""
def __init__(self, submission_id, submissions, storage_bucket):
"""Initializes AttackSubmission.
Args:
submission_id: ID of the submission
submissions: instance of CompetitionSubmissions with all submissions
storage_bucket: s... | () - start_time)
if elapsed_time_sec < time_limit:
time.sleep(1)
else:
kill_docker_container(container_name)
logging.warning("Submission was killed because run out of time")
logging.info("Elapsed time of submission: %d", elapsed_time_sec)
... | 123 | 123 | 410 | 7 | 115 | saumya0303/cleverhans | cleverhans_v3.1.0/examples/nips17_adversarial_competition/eval_infra/code/worker.py | Python | AttackSubmission | AttackSubmission | 422 | 478 | 422 | 422 | 4937abcd1a6bc9b17ae648d6e1c3a3b6875bdeaf | bigcode/the-stack | train |
1ba215d6b6227f1b32d936a0 | train | function | def is_docker_still_running(container_name):
"""Returns whether given Docker container is still running."""
return bool(get_id_of_running_docker(container_name))
| def is_docker_still_running(container_name):
| """Returns whether given Docker container is still running."""
return bool(get_id_of_running_docker(container_name))
| return self.msg
def get_id_of_running_docker(container_name):
"""Returns ID of running docker container."""
return shell_call(
[DOCKER_BINARY, "ps", "-q", "--filter=name={}".format(container_name)]
).strip()
def is_docker_still_running(container_name):
| 64 | 64 | 33 | 10 | 54 | saumya0303/cleverhans | cleverhans_v3.1.0/examples/nips17_adversarial_competition/eval_infra/code/worker.py | Python | is_docker_still_running | is_docker_still_running | 172 | 174 | 172 | 172 | 11e94624d181aa7e7f5e97dcd6384e3e3bc38090 | bigcode/the-stack | train |
bb564fead66dcbc817955825 | train | function | def get_id_of_running_docker(container_name):
"""Returns ID of running docker container."""
return shell_call(
[DOCKER_BINARY, "ps", "-q", "--filter=name={}".format(container_name)]
).strip()
| def get_id_of_running_docker(container_name):
| """Returns ID of running docker container."""
return shell_call(
[DOCKER_BINARY, "ps", "-q", "--filter=name={}".format(container_name)]
).strip()
| = exc
def __str__(self):
"""Returns human readable string representation of the exception."""
if self.exc:
return "{0}\nUnderlying exception:\n{1}".format(self.msg, self.exc)
else:
return self.msg
def get_id_of_running_docker(container_name):
| 64 | 64 | 49 | 10 | 53 | saumya0303/cleverhans | cleverhans_v3.1.0/examples/nips17_adversarial_competition/eval_infra/code/worker.py | Python | get_id_of_running_docker | get_id_of_running_docker | 165 | 169 | 165 | 165 | 6cefc05156388b699d52dfac08841968c4940d5d | bigcode/the-stack | train |
84e16eca85fc0211f5f32157 | train | function | def make_directory_writable(dirname):
"""Makes directory readable and writable by everybody.
If you run something inside Docker container and it writes files, then
these files will be written as root user with restricted permissions.
So to be able to read/modify these files outside of Docker you have t... | def make_directory_writable(dirname):
| """Makes directory readable and writable by everybody.
If you run something inside Docker container and it writes files, then
these files will be written as root user with restricted permissions.
So to be able to read/modify these files outside of Docker you have to change
permissions to be world r... | _TYPE = "type"
# Mapping from submission type in metadata to submission type used in worker
METADATA_JSON_TYPE_TO_TYPE = {
"attack": TYPE_NONTARGETED,
"targeted_attack": TYPE_TARGETED,
"defense": TYPE_DEFENSE,
}
def make_directory_writable(dirname):
| 64 | 64 | 160 | 7 | 57 | saumya0303/cleverhans | cleverhans_v3.1.0/examples/nips17_adversarial_competition/eval_infra/code/worker.py | Python | make_directory_writable | make_directory_writable | 93 | 119 | 93 | 93 | 8f9c6efa0fe1da65d3cb3917d35f1d89139f7683 | bigcode/the-stack | train |
618e8f23ce24e32b1015f6db | train | class | class DefenseSubmission(ExecutableSubmission):
"""Helper class to run one defense submission."""
def __init__(self, submission_id, submissions, storage_bucket):
"""Initializes DefenseSubmission.
Args:
submission_id: ID of the submission
submissions: instance of CompetitionS... | class DefenseSubmission(ExecutableSubmission):
| """Helper class to run one defense submission."""
def __init__(self, submission_id, submissions, storage_bucket):
"""Initializes DefenseSubmission.
Args:
submission_id: ID of the submission
submissions: instance of CompetitionSubmissions with all submissions
stora... | "{0}:/input_images:ro".format(input_dir),
"-v",
"{0}:/output_images".format(output_dir),
"-v",
"{0}:/code".format(tmp_run_dir),
"-w",
"/code",
self.container_name,
"./" + self.entry_point,
"/input_images",
... | 118 | 118 | 394 | 7 | 110 | saumya0303/cleverhans | cleverhans_v3.1.0/examples/nips17_adversarial_competition/eval_infra/code/worker.py | Python | DefenseSubmission | DefenseSubmission | 481 | 536 | 481 | 481 | f8563a79c41f6dc0989b7014048ef65e10b6f186 | bigcode/the-stack | train |
0ae743883353d1f22b86056a | train | class | class TestOvercloudCredentials(test_plugin.TestPluginV1):
def setUp(self):
super(TestOvercloudCredentials, self).setUp()
self.cmd = overcloud_credentials.OvercloudCredentials(self.app, None)
self.tripleoclient = mock.Mock()
self.app.client_manager.tripleoclient = self.tripleoclient... | class TestOvercloudCredentials(test_plugin.TestPluginV1):
| def setUp(self):
super(TestOvercloudCredentials, self).setUp()
self.cmd = overcloud_credentials.OvercloudCredentials(self.app, None)
self.tripleoclient = mock.Mock()
self.app.client_manager.tripleoclient = self.tripleoclient
@mock.patch("tripleoclient.utils.run_ansible_playbook... | KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import shutil
import tempfile
from unittest import mock
from tripleoclient.tests.v1 import test_plugin
from tripleoclient.v1 import overcloud_credentials
class TestOvercloudCrede... | 73 | 73 | 246 | 12 | 60 | paramite/python-tripleoclient | tripleoclient/tests/test_overcloud_credentials.py | Python | TestOvercloudCredentials | TestOvercloudCredentials | 22 | 52 | 22 | 23 | ce0c00ed860451427b5b4afb73db2a7f34ae428a | bigcode/the-stack | train |
c2a6167a5ff67aeeede7c380 | train | class | class AddressAdmin(admin.ModelAdmin):
search_fields = ('name',)
| class AddressAdmin(admin.ModelAdmin):
| search_fields = ('name',)
| ', 'code')
admin.site.register(models.State, StateAdmin)
class LocalityAdmin(admin.ModelAdmin):
search_fields = ('name', 'postal_code')
list_display = ('state', 'postal_code', 'name')
admin.site.register(models.Locality, LocalityAdmin)
class AddressAdmin(admin.ModelAdmin):
| 64 | 64 | 15 | 7 | 57 | jacinda/django-address | address/admin.py | Python | AddressAdmin | AddressAdmin | 24 | 25 | 24 | 24 | 2b09f27cd4dc7a35b82fda72f5c4f528a3643727 | bigcode/the-stack | train |
e3725782dbeff9f06ab92dcc | train | class | class LocalityAdmin(admin.ModelAdmin):
search_fields = ('name', 'postal_code')
list_display = ('state', 'postal_code', 'name')
| class LocalityAdmin(admin.ModelAdmin):
| search_fields = ('name', 'postal_code')
list_display = ('state', 'postal_code', 'name')
|
import models
class CountryAdmin(admin.ModelAdmin):
search_fields = ('name', 'code')
admin.site.register(models.Country, CountryAdmin)
class StateAdmin(admin.ModelAdmin):
search_fields = ('name', 'code')
admin.site.register(models.State, StateAdmin)
class LocalityAdmin(admin.ModelAdmin):
| 64 | 64 | 33 | 8 | 56 | jacinda/django-address | address/admin.py | Python | LocalityAdmin | LocalityAdmin | 17 | 19 | 17 | 17 | 7dfd0c2efc26e42ff207ec663fcea42dc588f7a4 | bigcode/the-stack | train |
085044172fc831c6e6b98641 | train | class | class CountryAdmin(admin.ModelAdmin):
search_fields = ('name', 'code')
| class CountryAdmin(admin.ModelAdmin):
| search_fields = ('name', 'code')
| from django.contrib import admin
import models
class CountryAdmin(admin.ModelAdmin):
| 16 | 64 | 17 | 7 | 8 | jacinda/django-address | address/admin.py | Python | CountryAdmin | CountryAdmin | 5 | 6 | 5 | 5 | 78ec987bfe016326651f467320646594c4a8bc55 | bigcode/the-stack | train |
885358b1dd069a77ca6a3074 | train | class | class StateAdmin(admin.ModelAdmin):
search_fields = ('name', 'code')
| class StateAdmin(admin.ModelAdmin):
| search_fields = ('name', 'code')
| from django.contrib import admin
import models
class CountryAdmin(admin.ModelAdmin):
search_fields = ('name', 'code')
admin.site.register(models.Country, CountryAdmin)
class StateAdmin(admin.ModelAdmin):
| 42 | 64 | 17 | 7 | 35 | jacinda/django-address | address/admin.py | Python | StateAdmin | StateAdmin | 11 | 12 | 11 | 11 | 72d63d0485495f18adda56d928dcdadf881678e9 | bigcode/the-stack | train |
b25130a2641131aa09b7345d | train | class | class TransferDocsTest(BaseWebTest, MockWebTestMixin):
AppClass = DumpsWebTestApp
relative_to = os.path.dirname(__file__)
def setUp(self):
super(TransferDocsTest, self).setUp()
self.setUpMock()
def tearDown(self):
self.tearDownMock()
super(TransferDocsTest, self).tearD... | class TransferDocsTest(BaseWebTest, MockWebTestMixin):
| AppClass = DumpsWebTestApp
relative_to = os.path.dirname(__file__)
def setUp(self):
super(TransferDocsTest, self).setUp()
self.setUpMock()
def tearDown(self):
self.tearDownMock()
super(TransferDocsTest, self).tearDown()
def test_tenders_docs(self):
data = ... | # -*- coding: utf-8 -*-
import os
from copy import deepcopy
from datetime import timedelta
from uuid import uuid4
from hashlib import sha512
from openprocurement.api.tests.base import BaseWebTest
from openprocurement.tender.belowthreshold.tests.base import test_tender_data
from openprocurement.contracting.api.tests.b... | 144 | 256 | 4,206 | 13 | 130 | ProzorroUKR/openprocurement-docs | tests/test_relocation.py | Python | TransferDocsTest | TransferDocsTest | 19 | 415 | 19 | 19 | 2466bc838356d0cf53163d29c390c19e4be0b419 | bigcode/the-stack | train |
0dfb16310ab76aa16b57e52f | train | class | class Migration(migrations.Migration):
dependencies = [
("checkout", "0024_auto_20200120_0154"),
]
operations = [
migrations.RenameField(
model_name="checkout",
old_name="meta",
new_name="metadata",
),
migrations.RenameField(
... | class Migration(migrations.Migration):
| dependencies = [
("checkout", "0024_auto_20200120_0154"),
]
operations = [
migrations.RenameField(
model_name="checkout",
old_name="meta",
new_name="metadata",
),
migrations.RenameField(
model_name="checkout",
old_n... | # Generated by Django 2.2.10 on 2020-02-21 08:57
from django.db import migrations
class Migration(migrations.Migration):
| 36 | 64 | 89 | 7 | 28 | fairhopeweb/saleor | saleor/checkout/migrations/0025_auto_20200221_0257.py | Python | Migration | Migration | 6 | 23 | 6 | 7 | 8a760cf7738abe73aa831a5133704c3edc80fe41 | bigcode/the-stack | train |
f77079142488e021a685d0be | train | class | class ViscousDrag(om.ExplicitComponent):
"""
Compute the skin friction drag if the with_viscous option is True.
If not, the CDv is 0.
This component exists for each lifting surface.
Parameters
----------
re : float
Dimensionalized (1/length) Reynolds number. This is used to... | class ViscousDrag(om.ExplicitComponent):
| """
Compute the skin friction drag if the with_viscous option is True.
If not, the CDv is 0.
This component exists for each lifting surface.
Parameters
----------
re : float
Dimensionalized (1/length) Reynolds number. This is used to compute the
local Reynolds numbe... | import numpy as np
import openmdao.api as om
class ViscousDrag(om.ExplicitComponent):
| 24 | 256 | 3,004 | 11 | 12 | eyarbasi3/OpenAeroStruct | openaerostruct/aerodynamics/viscous_drag.py | Python | ViscousDrag | ViscousDrag | 6 | 247 | 6 | 6 | 803c6cf7f2536f5d229e786a27ceb4fba8172b0d | bigcode/the-stack | train |
1cc1d625581413833a53ff27 | train | class | class _(list):
current = None
async def __aenter__(self):
if self.__class__.current is None:
self.__class__.current = aioctx(0, None)
self.append(self.__class__.current)
self.__class__.current = None
if self[-1].coro is not None:
pdb("__aenter__ awaiting"... | class _(list):
| current = None
async def __aenter__(self):
if self.__class__.current is None:
self.__class__.current = aioctx(0, None)
self.append(self.__class__.current)
self.__class__.current = None
if self[-1].coro is not None:
pdb("__aenter__ awaiting", self[-1].coro... | ()
def __exit__(self, type, value, traceback):
embed.os_showloop()
aio.hide = _()
class _:
def __enter__(self):
embed.os_showloop()
def __exit__(self, type, value, traceback):
embed.os_hideloop()
aio.show = _()
class aioctx:
def __init__(self, delta, coro):
self... | 112 | 112 | 374 | 4 | 107 | pmp-p/wapy-pack | wapy-lib/pythons/__init__.py | Python | _ | _ | 392 | 442 | 392 | 392 | 5701e1cbe0a3c8765f2263b38ef8b8228c11d11f | bigcode/the-stack | train |
145c1dde031834ae7cbd55ba | train | class | class _:
def __enter__(self):
embed.disable_irq()
def __exit__(self, type, value, traceback):
embed.enable_irq()
| class _:
| def __enter__(self):
embed.disable_irq()
def __exit__(self, type, value, traceback):
embed.enable_irq()
| return undefined
finally:
core_kw.clear()
core_argv.clear()
def core_pyv(v):
# print('(CorePy)added', v)
core_argv.append(v)
embed.set_ffpy(core_py)
embed.set_ffpy_add(core_pyv)
class _:
| 64 | 64 | 33 | 3 | 61 | pmp-p/wapy-pack | wapy-lib/pythons/__init__.py | Python | _ | _ | 352 | 357 | 352 | 352 | 5e54d7215c2fd8b3a8954a797343f4ccb5b2002b | bigcode/the-stack | train |
06842ed26eb73985d08dcfd9 | train | class | class _:
def __enter__(self):
embed.os_showloop()
def __exit__(self, type, value, traceback):
embed.os_hideloop()
| class _:
| def __enter__(self):
embed.os_showloop()
def __exit__(self, type, value, traceback):
embed.os_hideloop()
| __(self, type, value, traceback):
embed.enable_irq()
aio.block = _()
class _:
def __enter__(self):
embed.os_hideloop()
def __exit__(self, type, value, traceback):
embed.os_showloop()
aio.hide = _()
class _:
| 64 | 64 | 37 | 3 | 61 | pmp-p/wapy-pack | wapy-lib/pythons/__init__.py | Python | _ | _ | 374 | 379 | 374 | 374 | 2277499dba2a4a96d48ce9bf704dd9fa0c74330b | bigcode/the-stack | train |
78c557072d7998e912b8eea1 | train | function | def pdb(*argv, **kw):
kw["file"] = sys.stderr
print("\033[31mPYDEBUG>\033[0m ", *argv, **kw)
| def pdb(*argv, **kw):
| kw["file"] = sys.stderr
print("\033[31mPYDEBUG>\033[0m ", *argv, **kw)
|
# if you don't agree, continue to write all your imports as usual :)
# carefull order matters a lot in this file
import sys
import builtins
builtins.sys = sys
builtins.builtins = builtins
builtins.LOGS = []
def pdb(*argv, **kw):
| 63 | 64 | 38 | 8 | 55 | pmp-p/wapy-pack | wapy-lib/pythons/__init__.py | Python | pdb | pdb | 18 | 20 | 18 | 18 | 67da6563ce696985ede8e64212c6df057f5dc8d5 | bigcode/the-stack | train |
fcdf47b411e2cb9d8c9f97df | train | class | class _:
def __enter__(self):
embed.os_hideloop()
def __exit__(self, type, value, traceback):
embed.os_showloop()
| class _:
| def __enter__(self):
embed.os_hideloop()
def __exit__(self, type, value, traceback):
embed.os_showloop()
| _argv.append(v)
embed.set_ffpy(core_py)
embed.set_ffpy_add(core_pyv)
class _:
def __enter__(self):
embed.disable_irq()
def __exit__(self, type, value, traceback):
embed.enable_irq()
aio.block = _()
class _:
| 64 | 64 | 37 | 3 | 61 | pmp-p/wapy-pack | wapy-lib/pythons/__init__.py | Python | _ | _ | 363 | 368 | 363 | 363 | e9eda2c9489b0547659472df60ccb24c77097ab0 | bigcode/the-stack | train |
a9fa54935b456269baab66d3 | train | class | class aioctx:
def __init__(self, delta, coro):
self.coro = coro
self.tnext = Time.time() + delta
self.tmout = 0
| class aioctx:
| def __init__(self, delta, coro):
self.coro = coro
self.tnext = Time.time() + delta
self.tmout = 0
| , type, value, traceback):
embed.os_showloop()
aio.hide = _()
class _:
def __enter__(self):
embed.os_showloop()
def __exit__(self, type, value, traceback):
embed.os_hideloop()
aio.show = _()
class aioctx:
| 64 | 64 | 41 | 4 | 60 | pmp-p/wapy-pack | wapy-lib/pythons/__init__.py | Python | aioctx | aioctx | 385 | 389 | 385 | 385 | 86f2b5bfb8845a8a32da9e765f4a9f7c7c341bc3 | bigcode/the-stack | train |
19e2a35b42846fa50b2c334e | train | function | def pycore(fn):
global pyc_jump
pyc_jump[fn.__name__] = fn
| def pycore(fn):
| global pyc_jump
pyc_jump[fn.__name__] = fn
| pyv( mp_obj_get_type(ex) );
# pyv( MP_OBJ_FROM_PTR(ex) );
# pyv( MP_ROM_NONE );
# mp_obj_t result = pycore("pyc_excepthook");
#
pyc_jump = {"": undefined}
def pycore(fn):
| 64 | 64 | 24 | 5 | 59 | pmp-p/wapy-pack | wapy-lib/pythons/__init__.py | Python | pycore | pycore | 247 | 249 | 247 | 247 | 4875851f99e02bbb456bb236008c7e2a1a415145 | bigcode/the-stack | train |
a669ac9fd3107e3eacbd0457 | train | function | def overloaded(i, *attrs):
for attr in attrs:
if attr in i.__class__.__dict__:
if attr in i.__dict__:
return True
return False
| def overloaded(i, *attrs):
| for attr in attrs:
if attr in i.__class__.__dict__:
if attr in i.__dict__:
return True
return False
| return 0
def __call__(self, *argv, **kw):
if len(argv) and argv[0] is self:
return True
print("Null Pointer Exception")
sentinel = sentinel()
builtins.undefined = sentinel
del sentinel
def overloaded(i, *attrs):
| 64 | 64 | 41 | 7 | 56 | pmp-p/wapy-pack | wapy-lib/pythons/__init__.py | Python | overloaded | overloaded | 108 | 113 | 108 | 108 | f35ee35f5f7ce5cd0d64ed92af243b27c47bb597 | bigcode/the-stack | train |
671022e595d3b06c540f0762 | train | class | class OnTraceElement_TraceElementWise(FrozenOnly):
def __init__(self, vf):
self._vf_ = vf
self._freeze_self_()
def __call__(self, xi, eta, sigma, ravel, i):
"""
:param xi:
:param eta:
:param ravel:
:param i:
1) self.ftype == 'standard':
... | class OnTraceElement_TraceElementWise(FrozenOnly):
| def __init__(self, vf):
self._vf_ = vf
self._freeze_self_()
def __call__(self, xi, eta, sigma, ravel, i):
"""
:param xi:
:param eta:
:param ravel:
:param i:
1) self.ftype == 'standard':
Do the reconstruction in mesh element #i... | from screws.freeze.base import FrozenOnly
class OnTraceElement_TraceElementWise(FrozenOnly):
| 20 | 145 | 486 | 12 | 7 | mathischeap/mifem | objects/CSCG/_3d/fields/vector/do/reconstruct/trace_element/trace_element_wise.py | Python | OnTraceElement_TraceElementWise | OnTraceElement_TraceElementWise | 4 | 64 | 4 | 4 | 107ace2b601e46a258d7f16ccf800aa819895654 | bigcode/the-stack | train |
c08ce021774dc66c5fd59148 | train | function | def unloadFriendsList():
global globalFriendsList
if globalFriendsList != None:
globalFriendsList.unload()
globalFriendsList = None
return
| def unloadFriendsList():
| global globalFriendsList
if globalFriendsList != None:
globalFriendsList.unload()
globalFriendsList = None
return
| (globalFriendsList, 'closeCommand'):
globalFriendsList.close['command'] = globalFriendsList.closeCommand
globalFriendsList.exit()
return
def isFriendsListShown():
if globalFriendsList != None:
return globalFriendsList.isEntered
return 0
def unloadFriendsList():
| 64 | 64 | 36 | 5 | 58 | CrankySupertoon01/Toontown-2 | toontown/friends/FriendsListPanel.py | Python | unloadFriendsList | unloadFriendsList | 64 | 69 | 64 | 64 | a9fb72e8da613a82c9b93bd70cb9a3cfbfb30d01 | bigcode/the-stack | train |
5f792d55677953be6e27a7b6 | train | function | def showFriendsList():
global globalFriendsList
if globalFriendsList == None:
globalFriendsList = FriendsListPanel()
globalFriendsList.enter()
return
| def showFriendsList():
| global globalFriendsList
if globalFriendsList == None:
globalFriendsList = FriendsListPanel()
globalFriendsList.enter()
return
| 1, f2):
name1 = determineFriendName(f1)
name2 = determineFriendName(f2)
if name1 > name2:
return 1
elif name1 == name2:
return 0
else:
return -1
def showFriendsList():
| 64 | 64 | 37 | 5 | 58 | CrankySupertoon01/Toontown-2 | toontown/friends/FriendsListPanel.py | Python | showFriendsList | showFriendsList | 31 | 36 | 31 | 31 | ad8880d4adbd8eefc329ec7f74dba2530e153194 | bigcode/the-stack | train |
f6a31f1d849480f201a759da | train | function | def isFriendsListShown():
if globalFriendsList != None:
return globalFriendsList.isEntered
return 0
| def isFriendsListShown():
| if globalFriendsList != None:
return globalFriendsList.isEntered
return 0
| ['command'] = None
return
def hideFriendsListTutorial():
if globalFriendsList != None:
if hasattr(globalFriendsList, 'closeCommand'):
globalFriendsList.close['command'] = globalFriendsList.closeCommand
globalFriendsList.exit()
return
def isFriendsListShown():
| 64 | 64 | 27 | 6 | 57 | CrankySupertoon01/Toontown-2 | toontown/friends/FriendsListPanel.py | Python | isFriendsListShown | isFriendsListShown | 59 | 62 | 59 | 59 | d90d56fe4677deabcc6dbf62beae022c51250e80 | bigcode/the-stack | train |
f75c9aca87f65e3622696614 | train | class | class FriendsListPanel(DirectFrame, StateData.StateData):
def __init__(self):
self.leftmostPanel = FLPPets
self.rightmostPanel = FLPAll
DirectFrame.__init__(self, relief=None)
self.listScrollIndex = [0,
0,
0,
0,
0,
0,
0,
... | class FriendsListPanel(DirectFrame, StateData.StateData):
| def __init__(self):
self.leftmostPanel = FLPPets
self.rightmostPanel = FLPAll
DirectFrame.__init__(self, relief=None)
self.listScrollIndex = [0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
... |
else:
return -1
def showFriendsList():
global globalFriendsList
if globalFriendsList == None:
globalFriendsList = FriendsListPanel()
globalFriendsList.enter()
return
def hideFriendsList():
if globalFriendsList != None:
globalFriendsList.exit()
return
def showFrien... | 256 | 256 | 2,768 | 13 | 242 | CrankySupertoon01/Toontown-2 | toontown/friends/FriendsListPanel.py | Python | FriendsListPanel | FriendsListPanel | 71 | 311 | 71 | 72 | bf70954bc674290b3cad80c7d05eaff9fdb97624 | bigcode/the-stack | train |
d3e96ef7f76bd398ee8fd21a | train | function | def determineFriendName(friendId):
handle = base.cr.identifyFriend(friendId)
return handle.getName() if handle else ''
| def determineFriendName(friendId):
| handle = base.cr.identifyFriend(friendId)
return handle.getName() if handle else ''
| otp.nametag.NametagGroup import *
from otp.nametag.NametagConstants import *
from otp.otpbase import OTPGlobals
FLPPets = 1
FLPOnline = 2
FLPAll = 3
globalFriendsList = None
def determineFriendName(friendId):
| 64 | 64 | 28 | 7 | 56 | CrankySupertoon01/Toontown-2 | toontown/friends/FriendsListPanel.py | Python | determineFriendName | determineFriendName | 16 | 19 | 16 | 16 | ff3f92a02cd26dd3db0919b314aac90fecc408e5 | bigcode/the-stack | train |
847a4db0960256ca3aa61fcb | train | function | def showFriendsListTutorial():
global globalFriendsList
if globalFriendsList == None:
globalFriendsList = FriendsListPanel()
globalFriendsList.enter()
globalFriendsList.closeCommand = globalFriendsList.close['command']
globalFriendsList.close['command'] = None
return
| def showFriendsListTutorial():
| global globalFriendsList
if globalFriendsList == None:
globalFriendsList = FriendsListPanel()
globalFriendsList.enter()
globalFriendsList.closeCommand = globalFriendsList.close['command']
globalFriendsList.close['command'] = None
return
| showFriendsList():
global globalFriendsList
if globalFriendsList == None:
globalFriendsList = FriendsListPanel()
globalFriendsList.enter()
return
def hideFriendsList():
if globalFriendsList != None:
globalFriendsList.exit()
return
def showFriendsListTutorial():
| 64 | 64 | 63 | 6 | 57 | CrankySupertoon01/Toontown-2 | toontown/friends/FriendsListPanel.py | Python | showFriendsListTutorial | showFriendsListTutorial | 43 | 50 | 43 | 43 | 023175ad1dcffcdf9b845cae8496c877da357cf6 | bigcode/the-stack | train |
978d87c9612f0df5788620a4 | train | function | def hideFriendsList():
if globalFriendsList != None:
globalFriendsList.exit()
return
| def hideFriendsList():
| if globalFriendsList != None:
globalFriendsList.exit()
return
|
elif name1 == name2:
return 0
else:
return -1
def showFriendsList():
global globalFriendsList
if globalFriendsList == None:
globalFriendsList = FriendsListPanel()
globalFriendsList.enter()
return
def hideFriendsList():
| 64 | 64 | 22 | 5 | 58 | CrankySupertoon01/Toontown-2 | toontown/friends/FriendsListPanel.py | Python | hideFriendsList | hideFriendsList | 38 | 41 | 38 | 38 | 82f0d6a5cd0cdf1f4d25afdbdcfab68a83663346 | bigcode/the-stack | train |
50b559313bb426644bb86c38 | train | function | def hideFriendsListTutorial():
if globalFriendsList != None:
if hasattr(globalFriendsList, 'closeCommand'):
globalFriendsList.close['command'] = globalFriendsList.closeCommand
globalFriendsList.exit()
return
| def hideFriendsListTutorial():
| if globalFriendsList != None:
if hasattr(globalFriendsList, 'closeCommand'):
globalFriendsList.close['command'] = globalFriendsList.closeCommand
globalFriendsList.exit()
return
| ():
global globalFriendsList
if globalFriendsList == None:
globalFriendsList = FriendsListPanel()
globalFriendsList.enter()
globalFriendsList.closeCommand = globalFriendsList.close['command']
globalFriendsList.close['command'] = None
return
def hideFriendsListTutorial():
| 64 | 64 | 49 | 6 | 57 | CrankySupertoon01/Toontown-2 | toontown/friends/FriendsListPanel.py | Python | hideFriendsListTutorial | hideFriendsListTutorial | 52 | 57 | 52 | 52 | 66168a119e83de799381f4da3ff50c019210cf3c | bigcode/the-stack | train |
70a970955fcfc3eb63df9adc | train | function | def compareFriends(f1, f2):
name1 = determineFriendName(f1)
name2 = determineFriendName(f2)
if name1 > name2:
return 1
elif name1 == name2:
return 0
else:
return -1
| def compareFriends(f1, f2):
| name1 = determineFriendName(f1)
name2 = determineFriendName(f2)
if name1 > name2:
return 1
elif name1 == name2:
return 0
else:
return -1
| FLPPets = 1
FLPOnline = 2
FLPAll = 3
globalFriendsList = None
def determineFriendName(friendId):
handle = base.cr.identifyFriend(friendId)
return handle.getName() if handle else ''
def compareFriends(f1, f2):
| 64 | 64 | 63 | 9 | 55 | CrankySupertoon01/Toontown-2 | toontown/friends/FriendsListPanel.py | Python | compareFriends | compareFriends | 21 | 29 | 21 | 21 | 608531990ec2be465cb4c041ce58abedd5690628 | bigcode/the-stack | train |
7662b6a9c0feea7250f69a65 | train | class | class SecondaryIndexingScanTests(BaseSecondaryIndexingTests):
def setUp(self):
super(SecondaryIndexingScanTests, self).setUp()
self.key = "test_query_doc"
self.sync_write_abort_pattern = \
self.input.param("sync_write_abort_pattern",
"all_aborts")
... | class SecondaryIndexingScanTests(BaseSecondaryIndexingTests):
| def setUp(self):
super(SecondaryIndexingScanTests, self).setUp()
self.key = "test_query_doc"
self.sync_write_abort_pattern = \
self.input.param("sync_write_abort_pattern",
"all_aborts")
self.create_index_during = self.input.param("create_index... | from Cb_constants import CbServer
from base_2i import BaseSecondaryIndexingTests
from cb_tools.cbstats import Cbstats
from couchbase_helper.documentgenerator import doc_generator
from couchbase_helper.durability_helper import DurabilityHelper
from couchbase_helper.query_definitions import QueryDefinition, \
FULL_SC... | 116 | 256 | 3,447 | 12 | 103 | sumedhpb/TAF | pytests/secondary_index/indexscans_2i.py | Python | SecondaryIndexingScanTests | SecondaryIndexingScanTests | 12 | 382 | 12 | 12 | ae2ce30a7b5c201695cb0c0f2df730ed77684687 | bigcode/the-stack | train |
a5d2e0a1ffd4064355764697 | train | class | class DiscreteDesignVariableType(Enum):
INTEGER = 1 # Ordering and differences make sense
CATEGORICAL = 2 # No notion of ordering or differences
| class DiscreteDesignVariableType(Enum):
| INTEGER = 1 # Ordering and differences make sense
CATEGORICAL = 2 # No notion of ordering or differences
| DecodedValue, None, None]:
if n_cont <= 1:
yield (self.bounds[0]+self.bounds[1])/2.
else:
values = np.linspace(self.bounds[0], self.bounds[1], n_cont)
yield from values
class DiscreteDesignVariableType(Enum):
| 64 | 64 | 38 | 8 | 55 | jbussemaker/OpenTurbofanArchitecting | open_turb_arch/architecting/opt_defs.py | Python | DiscreteDesignVariableType | DiscreteDesignVariableType | 97 | 99 | 97 | 97 | d666e9aced195c31aa5b2b8d81b4f4e435e27e24 | bigcode/the-stack | train |
15aa374eddb4a483c300d5e6 | train | class | @dataclass
class ContinuousDesignVariable(DesignVariable):
bounds: Tuple[float, float]
fixed_value: float = None
def encode(self, value: DecodedValue) -> EncodedValue:
return value
def decode(self, value: EncodedValue) -> DecodedValue:
return value
@property
def is_fixed(self)... | @dataclass
class ContinuousDesignVariable(DesignVariable):
| bounds: Tuple[float, float]
fixed_value: float = None
def encode(self, value: DecodedValue) -> EncodedValue:
return value
def decode(self, value: EncodedValue) -> DecodedValue:
return value
@property
def is_fixed(self):
return self.fixed_value is not None
def get_... | ) -> EncodedValue:
raise NotImplementedError
def get_random_value(self) -> DecodedValue:
raise NotImplementedError
def iter_values(self, n_cont: int = 5) -> Generator[DecodedValue, None, None]:
raise NotImplementedError
@dataclass
class ContinuousDesignVariable(DesignVariable):
| 71 | 71 | 239 | 11 | 59 | jbussemaker/OpenTurbofanArchitecting | open_turb_arch/architecting/opt_defs.py | Python | ContinuousDesignVariable | ContinuousDesignVariable | 65 | 94 | 65 | 66 | 9d4f69feaec8df6e4becb67e6c69bbbe6986cec9 | bigcode/the-stack | train |
5bb0c1b624d6536687985351 | train | class | @dataclass
class DesignVariable:
name: str
def encode(self, value: DecodedValue) -> EncodedValue:
raise NotImplementedError
def decode(self, value: EncodedValue) -> DecodedValue:
raise NotImplementedError
@property
def is_fixed(self) -> bool:
raise NotImplementedError
... | @dataclass
class DesignVariable:
| name: str
def encode(self, value: DecodedValue) -> EncodedValue:
raise NotImplementedError
def decode(self, value: EncodedValue) -> DecodedValue:
raise NotImplementedError
@property
def is_fixed(self) -> bool:
raise NotImplementedError
def get_fixed_value(self) -> Dec... | Condition', 'DesignCondition', 'EvaluateCondition']
EncodedValue = Union[float, int]
DecodedValue = Union[float, Any]
DesignVector = List[EncodedValue]
DecodedDesignVector = List[DecodedValue]
OperatingMetricsMap = Dict[OperatingCondition, OperatingMetrics]
@dataclass
class DesignVariable:
| 64 | 64 | 160 | 7 | 57 | jbussemaker/OpenTurbofanArchitecting | open_turb_arch/architecting/opt_defs.py | Python | DesignVariable | DesignVariable | 38 | 62 | 38 | 39 | 2679c1eed1157c47c99d8792ebc1c65baa1b167a | bigcode/the-stack | train |
568984c88a833bcc9a1e52d1 | train | class | @dataclass
class Constraint(OutputMetric):
dir: ConstraintDirection
limit_value: float
| @dataclass
class Constraint(OutputMetric):
| dir: ConstraintDirection
limit_value: float
| ObjectiveDirection(Enum):
MINIMIZE = -1
MAXIMIZE = 1
@dataclass
class Objective(OutputMetric):
dir: ObjectiveDirection
class ConstraintDirection(Enum):
LOWER_EQUAL_THAN = -1
GREATER_EQUAL_THAN = 1
@dataclass
class Constraint(OutputMetric):
| 64 | 64 | 20 | 8 | 55 | jbussemaker/OpenTurbofanArchitecting | open_turb_arch/architecting/opt_defs.py | Python | Constraint | Constraint | 162 | 165 | 162 | 163 | 5105505804bc9b8de5127ab4074f12159938e5a5 | bigcode/the-stack | train |
1fe5f08bf699f67324080512 | train | class | @dataclass
class OutputMetric:
name: str
| @dataclass
class OutputMetric:
| name: str
| odedValue:
return 0
def get_random_value(self) -> DecodedValue:
return random.choice(self.values)
def iter_values(self, n_cont: int = 5) -> Generator[DecodedValue, None, None]:
yield from self.values
@dataclass
class OutputMetric:
| 64 | 64 | 12 | 7 | 56 | jbussemaker/OpenTurbofanArchitecting | open_turb_arch/architecting/opt_defs.py | Python | OutputMetric | OutputMetric | 142 | 144 | 142 | 143 | d213a425226baef39d13a84c6df26686131599ff | bigcode/the-stack | train |
09481cd4a02b56d8b248e8ff | train | class | class ConstraintDirection(Enum):
LOWER_EQUAL_THAN = -1
GREATER_EQUAL_THAN = 1
| class ConstraintDirection(Enum):
| LOWER_EQUAL_THAN = -1
GREATER_EQUAL_THAN = 1
| Value, None, None]:
yield from self.values
@dataclass
class OutputMetric:
name: str
class ObjectiveDirection(Enum):
MINIMIZE = -1
MAXIMIZE = 1
@dataclass
class Objective(OutputMetric):
dir: ObjectiveDirection
class ConstraintDirection(Enum):
| 64 | 64 | 22 | 5 | 58 | jbussemaker/OpenTurbofanArchitecting | open_turb_arch/architecting/opt_defs.py | Python | ConstraintDirection | ConstraintDirection | 157 | 159 | 157 | 157 | c49ffd1171410779671d9bb598f1e69764f100c9 | bigcode/the-stack | train |
89d5ca2b2877e28a6985d992 | train | class | @dataclass
class DiscreteDesignVariable(DesignVariable):
type: DiscreteDesignVariableType
values: list
fixed_value: Any = None # The fixed VALUE (should be in the values list!)
def encode(self, value: DecodedValue) -> EncodedValue:
try:
return self.values.index(value)
excep... | @dataclass
class DiscreteDesignVariable(DesignVariable):
| type: DiscreteDesignVariableType
values: list
fixed_value: Any = None # The fixed VALUE (should be in the values list!)
def encode(self, value: DecodedValue) -> EncodedValue:
try:
return self.values.index(value)
except ValueError:
raise ValueError('Value %r not ... | if n_cont <= 1:
yield (self.bounds[0]+self.bounds[1])/2.
else:
values = np.linspace(self.bounds[0], self.bounds[1], n_cont)
yield from values
class DiscreteDesignVariableType(Enum):
INTEGER = 1 # Ordering and differences make sense
CATEGORICAL = 2 # No notion of ... | 98 | 98 | 327 | 12 | 85 | jbussemaker/OpenTurbofanArchitecting | open_turb_arch/architecting/opt_defs.py | Python | DiscreteDesignVariable | DiscreteDesignVariable | 102 | 139 | 102 | 103 | cbebca6809278130b0c077ccd15ce89afc03ef28 | bigcode/the-stack | train |
5bb226b94dba01efbd209b29 | train | class | @dataclass
class Objective(OutputMetric):
dir: ObjectiveDirection
| @dataclass
class Objective(OutputMetric):
| dir: ObjectiveDirection
| _cont: int = 5) -> Generator[DecodedValue, None, None]:
yield from self.values
@dataclass
class OutputMetric:
name: str
class ObjectiveDirection(Enum):
MINIMIZE = -1
MAXIMIZE = 1
@dataclass
class Objective(OutputMetric):
| 64 | 64 | 14 | 8 | 55 | jbussemaker/OpenTurbofanArchitecting | open_turb_arch/architecting/opt_defs.py | Python | Objective | Objective | 152 | 154 | 152 | 153 | 2eb52941957f67a7a9aecbe1d9f85056b52e913a | bigcode/the-stack | train |
d6f7d2437186db0dffc53d8b | train | class | class ObjectiveDirection(Enum):
MINIMIZE = -1
MAXIMIZE = 1
| class ObjectiveDirection(Enum):
| MINIMIZE = -1
MAXIMIZE = 1
| get_random_value(self) -> DecodedValue:
return random.choice(self.values)
def iter_values(self, n_cont: int = 5) -> Generator[DecodedValue, None, None]:
yield from self.values
@dataclass
class OutputMetric:
name: str
class ObjectiveDirection(Enum):
| 64 | 64 | 21 | 5 | 58 | jbussemaker/OpenTurbofanArchitecting | open_turb_arch/architecting/opt_defs.py | Python | ObjectiveDirection | ObjectiveDirection | 147 | 149 | 147 | 147 | 295ba025b661e2ccb569c0d2ce1ef17566472206 | bigcode/the-stack | train |
b1ee9cbcb8ddfa08d00bd5e9 | train | function | def prepare_data(
path,
):
global csk_triples, csk_entities, raw_vocab, kb_dict
with open("%s/resource.txt" % path) as f:
d = json.loads(f.readline())
csk_triples = d["csk_triples"]
csk_entities = d["csk_entities"]
raw_vocab = d["vocab_dict"]
kb_dict = d["dict_csk"]
return csk_tr... | def prepare_data(
path,
):
| global csk_triples, csk_entities, raw_vocab, kb_dict
with open("%s/resource.txt" % path) as f:
d = json.loads(f.readline())
csk_triples = d["csk_triples"]
csk_entities = d["csk_entities"]
raw_vocab = d["vocab_dict"]
kb_dict = d["dict_csk"]
return csk_triples, csk_entities, raw_vocab,... | sk"
self.do_lower_case = True
config = Config()
csk_triples, csk_entities, raw_vocab, kb_dict = [], [], [], []
tokenizer = BertTokenizer.from_pretrained(config.bert_model_voc, do_lower_case=config.do_lower_case)
def prepare_data(
path,
):
| 64 | 64 | 108 | 8 | 56 | Wchoward/CskER | generate_triple_dataset.py | Python | prepare_data | prepare_data | 34 | 44 | 34 | 36 | ab61804775d9cdb69f216aacc05ef2f2e42decd1 | bigcode/the-stack | train |
145036ac518bfac3d6a910ba | train | function | def get_triple_json(tokens):
"""
Args:
tokens : [List] tokenize后的句子的list ['CLS', 'I', 'am', 'happy', 'SEP']
"""
d = {}
sent_triples, all_entities, all_triples = [], [], []
idx = 0
for token in tokens:
entities, triples = [], []
if token in kb_dict:
idx += ... | def get_triple_json(tokens):
| """
Args:
tokens : [List] tokenize后的句子的list ['CLS', 'I', 'am', 'happy', 'SEP']
"""
d = {}
sent_triples, all_entities, all_triples = [], [], []
idx = 0
for token in tokens:
entities, triples = [], []
if token in kb_dict:
idx += 1
sent_triples.ap... | if i != len(lst) - 1:
f.write("\n")
def tokenize(txt):
tokens_t = tokenizer.tokenize(txt)
tokens = []
tokens.append("[CLS]")
for token in tokens_t:
tokens.append(token)
tokens.append("[SEP]")
return tokens
def get_triple_json(tokens):
| 68 | 68 | 227 | 7 | 60 | Wchoward/CskER | generate_triple_dataset.py | Python | get_triple_json | get_triple_json | 80 | 105 | 80 | 80 | fc7be1f1d2520dece9b7d231eba38f531a23f41c | bigcode/the-stack | train |
73c6bb2e3bd424dbe2d20c13 | train | function | def tokenize(txt):
tokens_t = tokenizer.tokenize(txt)
tokens = []
tokens.append("[CLS]")
for token in tokens_t:
tokens.append(token)
tokens.append("[SEP]")
return tokens
| def tokenize(txt):
| tokens_t = tokenizer.tokenize(txt)
tokens = []
tokens.append("[CLS]")
for token in tokens_t:
tokens.append(token)
tokens.append("[SEP]")
return tokens
| )
return data
def save_file(filepath, lst):
with open(filepath, "w", encoding="utf-8") as f:
for i in range(len(lst)):
f.write(lst[i])
if i != len(lst) - 1:
f.write("\n")
def tokenize(txt):
| 64 | 64 | 45 | 4 | 60 | Wchoward/CskER | generate_triple_dataset.py | Python | tokenize | tokenize | 70 | 77 | 70 | 70 | 57e829ae57226854c32487779076d9c50797c735 | bigcode/the-stack | train |
025e439bd0e64ba6b5f34d42 | train | function | def get_dataset_examples(
file_path,
):
f = open(file_path, "r", encoding="utf-8")
data = []
for line in f.readlines():
line = line.replace("\n", "").split("\t")
text_a = str(line[1])
label = str(line[0])
tokens_a = tokenize(text_a)
# print(tokens_a)
data.... | def get_dataset_examples(
file_path,
):
| f = open(file_path, "r", encoding="utf-8")
data = []
for line in f.readlines():
line = line.replace("\n", "").split("\t")
text_a = str(line[1])
label = str(line[0])
tokens_a = tokenize(text_a)
# print(tokens_a)
data.append(tokens_a)
return data
| ["csk_triples"]
csk_entities = d["csk_entities"]
raw_vocab = d["vocab_dict"]
kb_dict = d["dict_csk"]
return csk_triples, csk_entities, raw_vocab, kb_dict
def get_dataset_examples(
file_path,
):
| 64 | 64 | 91 | 10 | 53 | Wchoward/CskER | generate_triple_dataset.py | Python | get_dataset_examples | get_dataset_examples | 47 | 59 | 47 | 49 | 470a1f900d76ee9a2df0cfb804ec4d28c82b99ee | bigcode/the-stack | train |
f5b91db3d8194c8e186cadd8 | train | function | def main():
prepare_data(config.csk_dir)
generate_dataset(config.data_dir + "/data_train.txt", config.data_dir + "/trainset.txt")
generate_dataset(config.data_dir + "/data_val.txt", config.data_dir + "/validset.txt")
generate_dataset(config.data_dir + "/data_test.txt", config.data_dir + "/testset.txt")
| def main():
| prepare_data(config.csk_dir)
generate_dataset(config.data_dir + "/data_train.txt", config.data_dir + "/trainset.txt")
generate_dataset(config.data_dir + "/data_val.txt", config.data_dir + "/validset.txt")
generate_dataset(config.data_dir + "/data_test.txt", config.data_dir + "/testset.txt")
|
def generate_dataset(file_in_path, file_out_path):
all_data = get_dataset_examples(file_in_path)
out_data_lst = []
for data in tqdm(all_data):
out_data_lst.append(json.dumps(get_triple_json(data)))
save_file(file_out_path, out_data_lst)
def main():
| 64 | 64 | 74 | 3 | 61 | Wchoward/CskER | generate_triple_dataset.py | Python | main | main | 116 | 120 | 116 | 116 | 537d00261bf57d70e90093982a69d7eb586e89a5 | bigcode/the-stack | train |
d19f50c0f4f11580661829e2 | train | function | def generate_dataset(file_in_path, file_out_path):
all_data = get_dataset_examples(file_in_path)
out_data_lst = []
for data in tqdm(all_data):
out_data_lst.append(json.dumps(get_triple_json(data)))
save_file(file_out_path, out_data_lst)
| def generate_dataset(file_in_path, file_out_path):
| all_data = get_dataset_examples(file_in_path)
out_data_lst = []
for data in tqdm(all_data):
out_data_lst.append(json.dumps(get_triple_json(data)))
save_file(file_out_path, out_data_lst)
| sent_triples.append(0)
d["sent_triples"] = sent_triples
d["all_entities"] = all_entities
d["all_triples"] = all_triples
d["sentence"] = tokens
return d
def generate_dataset(file_in_path, file_out_path):
| 64 | 64 | 60 | 11 | 52 | Wchoward/CskER | generate_triple_dataset.py | Python | generate_dataset | generate_dataset | 108 | 113 | 108 | 108 | c1ec2dba3ac1f50c3a0ec7958f20ec58a1eff88f | bigcode/the-stack | train |
49726cfc6bc4c1f5b58615e4 | train | function | def save_file(filepath, lst):
with open(filepath, "w", encoding="utf-8") as f:
for i in range(len(lst)):
f.write(lst[i])
if i != len(lst) - 1:
f.write("\n")
| def save_file(filepath, lst):
| with open(filepath, "w", encoding="utf-8") as f:
for i in range(len(lst)):
f.write(lst[i])
if i != len(lst) - 1:
f.write("\n")
| f.readlines():
line = line.replace("\n", "").split("\t")
text_a = str(line[1])
label = str(line[0])
tokens_a = tokenize(text_a)
# print(tokens_a)
data.append(tokens_a)
return data
def save_file(filepath, lst):
| 64 | 64 | 55 | 7 | 56 | Wchoward/CskER | generate_triple_dataset.py | Python | save_file | save_file | 62 | 67 | 62 | 62 | db827eeb4559a6f97c9643cac8536e7710fba0dc | bigcode/the-stack | train |
55a2604f1194696098b96091 | train | class | class Config:
def __init__(self):
self.language = "eng"
if self.language == "eng":
# eng
self.bert_model = "/home/ssm/project/wch/pretrained_models/bert_base_uncased_eng/pytorch_model.bin"
self.bert_model_config = "/home/ssm/project/wch/pretrained_models/bert_base... | class Config:
| def __init__(self):
self.language = "eng"
if self.language == "eng":
# eng
self.bert_model = "/home/ssm/project/wch/pretrained_models/bert_base_uncased_eng/pytorch_model.bin"
self.bert_model_config = "/home/ssm/project/wch/pretrained_models/bert_base_uncased_eng/c... | # -*- coding:utf-8 -*-
import torch
from transformers import BertModel, BertTokenizer
from tqdm import tqdm, trange
import argparse
import numpy as np
from Data_Processors import *
class Config:
| 44 | 70 | 236 | 3 | 41 | Wchoward/CskER | generate_triple_dataset.py | Python | Config | Config | 10 | 26 | 10 | 10 | fce4c05b7c56a08b59df882015a381e181eed4ce | bigcode/the-stack | train |
ec50e4de9794ac40ee435082 | train | function | def find_fixpoint(state):
prev_state = state
next_state = get_next_state(state)
count = 0
while next_state != prev_state:
count += 1
prev_state = next_state
next_state = get_next_state(prev_state)
return count_seats(next_state, occupied)
| def find_fixpoint(state):
| prev_state = state
next_state = get_next_state(state)
count = 0
while next_state != prev_state:
count += 1
prev_state = next_state
next_state = get_next_state(prev_state)
return count_seats(next_state, occupied)
| floor = "."
empty = "L"
occupied = "#"
def find_fixpoint(state):
| 19 | 64 | 68 | 6 | 12 | Ingomancer/AoC2020 | 11/11.2.py | Python | find_fixpoint | find_fixpoint | 5 | 13 | 5 | 5 | eeadb4eaa37c4c5443b84edd5e9c66538a574c50 | bigcode/the-stack | train |
b8f6613b7d9458aa10399dc5 | train | function | def count_seats(state, seat):
count = 0
for i in state:
for j in i:
count += 1 if j == seat else 0
return count
| def count_seats(state, seat):
| count = 0
for i in state:
for j in i:
count += 1 if j == seat else 0
return count
| 0 <= y < len(state[x]):
if state[x][y] == occupied:
return 1
elif state[x][y] == empty:
return 0
x += delta_x
y += delta_y
return 0
def count_seats(state, seat):
| 64 | 64 | 43 | 8 | 55 | Ingomancer/AoC2020 | 11/11.2.py | Python | count_seats | count_seats | 65 | 70 | 65 | 65 | 3d78b6b9f43c6b4896cee2a4d4921faf72cf2a95 | bigcode/the-stack | train |
44f40724b432e92183f4adcc | train | function | def count_visibly_occupied(state, x, y):
count = 0
for direction in directions:
count += look_in_direction(state, *direction, x, y)
return count
| def count_visibly_occupied(state, x, y):
| count = 0
for direction in directions:
count += look_in_direction(state, *direction, x, y)
return count
| , 1], # right
[-1, -1], # up left
[-1, 1], # up right
[1, -1], # down left
[1, 1], # down right
]
def count_visibly_occupied(state, x, y):
| 64 | 64 | 43 | 12 | 52 | Ingomancer/AoC2020 | 11/11.2.py | Python | count_visibly_occupied | count_visibly_occupied | 47 | 51 | 47 | 47 | fd616e563fe7ff9fcdfa18a208dfb1469c136109 | bigcode/the-stack | train |
7341a2b3877210e64fd85240 | train | function | def get_next_state(state):
next_state = []
for i in range(len(state)):
sublist = []
for j in range(len(state[i])):
neighbours = count_visibly_occupied(state, i, j)
if state[i][j] == floor:
sublist.append(floor)
elif state[i][j] == empty:
... | def get_next_state(state):
| next_state = []
for i in range(len(state)):
sublist = []
for j in range(len(state[i])):
neighbours = count_visibly_occupied(state, i, j)
if state[i][j] == floor:
sublist.append(floor)
elif state[i][j] == empty:
if neighbours == ... | state
next_state = get_next_state(state)
count = 0
while next_state != prev_state:
count += 1
prev_state = next_state
next_state = get_next_state(prev_state)
return count_seats(next_state, occupied)
def get_next_state(state):
| 64 | 64 | 135 | 6 | 58 | Ingomancer/AoC2020 | 11/11.2.py | Python | get_next_state | get_next_state | 15 | 34 | 15 | 15 | e2e98c9a4630bac68142312145c1670b523772c5 | bigcode/the-stack | train |
f73dd58c5b77863c401b202d | train | function | def look_in_direction(state, delta_x, delta_y, x, y):
x += delta_x
y += delta_y
while 0 <= x < len(state) and 0 <= y < len(state[x]):
if state[x][y] == occupied:
return 1
elif state[x][y] == empty:
return 0
x += delta_x
y += delta_y
return 0
| def look_in_direction(state, delta_x, delta_y, x, y):
| x += delta_x
y += delta_y
while 0 <= x < len(state) and 0 <= y < len(state[x]):
if state[x][y] == occupied:
return 1
elif state[x][y] == empty:
return 0
x += delta_x
y += delta_y
return 0
| # down right
]
def count_visibly_occupied(state, x, y):
count = 0
for direction in directions:
count += look_in_direction(state, *direction, x, y)
return count
def look_in_direction(state, delta_x, delta_y, x, y):
| 64 | 64 | 95 | 16 | 47 | Ingomancer/AoC2020 | 11/11.2.py | Python | look_in_direction | look_in_direction | 53 | 63 | 53 | 53 | 9da98fb3aab6731cc5e4a0c7064083e33a816646 | bigcode/the-stack | train |
a724e9b1eaa3d748b66f42b7 | train | class | class Command(BaseCommand):
help = 'Informer'
def __init__(self, *args, **kw):
super(Command, self).__init__(*args, **kw)
def add_arguments(self, parser):
parser.add_argument('--cid', type=int, help='Contest id', required=True)
parser.add_argument('--tid', type=int, help='Telegram ... | class Command(BaseCommand):
| help = 'Informer'
def __init__(self, *args, **kw):
super(Command, self).__init__(*args, **kw)
def add_arguments(self, parser):
parser.add_argument('--cid', type=int, help='Contest id', required=True)
parser.add_argument('--tid', type=int, help='Telegram id for info', required=True)... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import logging
import os
import re
import subprocess
import time
from datetime import timedelta
from pprint import pprint # noqa
import coloredlogs
import humanize
from attrdict import AttrDict
from django.core.management.base import BaseCommand
from django.u... | 143 | 256 | 1,724 | 5 | 138 | horacexd/clist | ranking/management/commands/informer.py | Python | Command | Command | 29 | 237 | 29 | 29 | f568e52be53b44402d2b136ae99fa4db76dab82d | bigcode/the-stack | train |
2683563fcac87ba98f9ba72a | train | function | def generator_scrubber(diagnostics: List[str], common: bool = True) -> str:
current_diag = diagnostics
for i in range(len(diagnostics[0])):
if len(current_diag) == 1:
break
rare = most_least_common(current_diag)[0 if common else 1]
current_diag = list(filter(lambda x: x[i] ==... | def generator_scrubber(diagnostics: List[str], common: bool = True) -> str:
| current_diag = diagnostics
for i in range(len(diagnostics[0])):
if len(current_diag) == 1:
break
rare = most_least_common(current_diag)[0 if common else 1]
current_diag = list(filter(lambda x: x[i] == rare[i], current_diag))
return ''.join(current_diag)
| '0' for i in vals]) # most common
epsilon = ''.join(['1' if i == '0' else '0' for i in gamma]) #least common
return gamma, epsilon
def generator_scrubber(diagnostics: List[str], common: bool = True) -> str:
| 64 | 64 | 92 | 19 | 44 | tsalgie/advent_of_code_2021 | 03/puzzle.py | Python | generator_scrubber | generator_scrubber | 12 | 19 | 12 | 12 | 28ccb4075c098b24d2e45610d75ffc5a02ba4c79 | bigcode/the-stack | train |
d5541f6a45aa70ed19fe8e76 | train | function | def most_least_common(diagnostics: List[str]) -> Tuple[str, str]:
vals = [0] * len(diagnostics[0])
for diag in diagnostics:
for i, c in enumerate(diag):
vals[i] += 1 if c == '1' else -1
gamma = ''.join(['1' if i >= 0 else '0' for i in vals]) # most common
epsilon = ''.join(['1' if i ... | def most_least_common(diagnostics: List[str]) -> Tuple[str, str]:
| vals = [0] * len(diagnostics[0])
for diag in diagnostics:
for i, c in enumerate(diag):
vals[i] += 1 if c == '1' else -1
gamma = ''.join(['1' if i >= 0 else '0' for i in vals]) # most common
epsilon = ''.join(['1' if i == '0' else '0' for i in gamma]) #least common
return gamma, e... | from typing import List, Tuple
def most_least_common(diagnostics: List[str]) -> Tuple[str, str]:
| 24 | 64 | 122 | 17 | 6 | tsalgie/advent_of_code_2021 | 03/puzzle.py | Python | most_least_common | most_least_common | 3 | 10 | 3 | 3 | 45fc636353332de3e98b28d78a9c63b4cb8441cd | bigcode/the-stack | train |
edb677288182be5534490db5 | train | function | def puzzle_02(diagnostics = List[str]) -> int:
generator = generator_scrubber(diagnostics)
scrubber = generator_scrubber(diagnostics, False)
return int(generator, 2) * int(scrubber, 2)
| def puzzle_02(diagnostics = List[str]) -> int:
| generator = generator_scrubber(diagnostics)
scrubber = generator_scrubber(diagnostics, False)
return int(generator, 2) * int(scrubber, 2)
| ], current_diag))
return ''.join(current_diag)
def puzzle(diagnostics: List[str]) -> int:
gamma, epsilon = most_least_common(diagnostics)
return int(gamma, 2) * int(epsilon, 2)
def puzzle_02(diagnostics = List[str]) -> int:
| 64 | 64 | 50 | 13 | 51 | tsalgie/advent_of_code_2021 | 03/puzzle.py | Python | puzzle_02 | puzzle_02 | 25 | 28 | 25 | 25 | 545aa3614614905eeb558cae9e9293e41e4456af | bigcode/the-stack | train |
aaa85dc11a64fd3d985c72f6 | train | function | def puzzle(diagnostics: List[str]) -> int:
gamma, epsilon = most_least_common(diagnostics)
return int(gamma, 2) * int(epsilon, 2)
| def puzzle(diagnostics: List[str]) -> int:
| gamma, epsilon = most_least_common(diagnostics)
return int(gamma, 2) * int(epsilon, 2)
| (current_diag) == 1:
break
rare = most_least_common(current_diag)[0 if common else 1]
current_diag = list(filter(lambda x: x[i] == rare[i], current_diag))
return ''.join(current_diag)
def puzzle(diagnostics: List[str]) -> int:
| 64 | 64 | 40 | 11 | 53 | tsalgie/advent_of_code_2021 | 03/puzzle.py | Python | puzzle | puzzle | 21 | 23 | 21 | 21 | df1895c4b8ce7a6bfbc52f69f45288e92fd78afb | bigcode/the-stack | train |
71b1783f0cbd22760074f87c | train | function | def convert_examples_to_features(examples, seq_length, tokenizer):
"""Loads a data file into a list of `InputBatch`s."""
features = []
for (ex_index, example) in enumerate(examples):
tokens_a = tokenizer.tokenize(example.text_a)
tokens_b = None
if example.text_b:
tokens_... | def convert_examples_to_features(examples, seq_length, tokenizer):
| """Loads a data file into a list of `InputBatch`s."""
features = []
for (ex_index, example) in enumerate(examples):
tokens_a = tokenizer.tokenize(example.text_a)
tokens_b = None
if example.text_b:
tokens_b = tokenizer.tokenize(example.text_b)
if tokens_b:
... | text encoding
class InputExample(object):
def __init__(self, unique_id, text_a, text_b):
self.unique_id = unique_id
self.text_a = text_a
self.text_b = text_b
class InputFeatures(object):
"""A single set of features of data."""
def __init__(self, unique_id, tokens, input_ids, input_... | 138 | 138 | 461 | 13 | 124 | zigonk/ReSC | dataset/data_loader.py | Python | convert_examples_to_features | convert_examples_to_features | 83 | 141 | 83 | 83 | 897b2d8095560d607ff336aec2f140f65181582c | bigcode/the-stack | train |
7dc8bb3c08f0815de1ea6576 | train | class | class InputFeatures(object):
"""A single set of features of data."""
def __init__(self, unique_id, tokens, input_ids, input_mask, input_type_ids):
self.unique_id = unique_id
self.tokens = tokens
self.input_ids = input_ids
self.input_mask = input_mask
self.input_type_ids =... | class InputFeatures(object):
| """A single set of features of data."""
def __init__(self, unique_id, tokens, input_ids, input_mask, input_type_ids):
self.unique_id = unique_id
self.tokens = tokens
self.input_ids = input_ids
self.input_mask = input_mask
self.input_type_ids = input_type_ids
| _id += 1
return examples
## Bert text encoding
class InputExample(object):
def __init__(self, unique_id, text_a, text_b):
self.unique_id = unique_id
self.text_a = text_a
self.text_b = text_b
class InputFeatures(object):
| 64 | 64 | 77 | 5 | 58 | zigonk/ReSC | dataset/data_loader.py | Python | InputFeatures | InputFeatures | 74 | 81 | 74 | 74 | 42ccde7e47ec5236b60c8a1f08e594930ef98b10 | bigcode/the-stack | train |
09203da271065df17434ce89 | train | class | class ReferDataset(data.Dataset):
SUPPORTED_DATASETS = {
'referit': {'splits': ('train', 'val', 'trainval', 'test')},
'unc': {
'splits': ('train', 'val', 'trainval', 'testA', 'testB'),
'params': {'dataset': 'refcoco', 'split_by': 'unc'}
},
'unc+': {
... | class ReferDataset(data.Dataset):
| SUPPORTED_DATASETS = {
'referit': {'splits': ('train', 'val', 'trainval', 'test')},
'unc': {
'splits': ('train', 'val', 'trainval', 'testA', 'testB'),
'params': {'dataset': 'refcoco', 'split_by': 'unc'}
},
'unc+': {
'splits': ('train', 'val', 'trai... | for token in tokens_a:
tokens.append(token)
input_type_ids.append(0)
tokens.append("[SEP]")
input_type_ids.append(0)
if tokens_b:
for token in tokens_b:
tokens.append(token)
input_type_ids.append(1)
tokens.append("... | 256 | 256 | 2,011 | 6 | 249 | zigonk/ReSC | dataset/data_loader.py | Python | ReferDataset | ReferDataset | 146 | 324 | 146 | 146 | a87e9f35b405e657f79520af71a86d7a9eddd077 | bigcode/the-stack | train |
be83dcaa457db20493f7541e | train | class | class DatasetNotFoundError(Exception):
pass
| class DatasetNotFoundError(Exception):
| pass
|
assert len(input_type_ids) == seq_length
features.append(
InputFeatures(
unique_id=example.unique_id,
tokens=tokens,
input_ids=input_ids,
input_mask=input_mask,
input_type_ids=input_type_ids))
return feature... | 64 | 64 | 10 | 7 | 56 | zigonk/ReSC | dataset/data_loader.py | Python | DatasetNotFoundError | DatasetNotFoundError | 143 | 144 | 143 | 143 | 866f4e4b4b7d6273bd9749a3cf402d2e6ae35420 | bigcode/the-stack | train |
c82c24d7c56ecbd19d20100a | train | class | class InputExample(object):
def __init__(self, unique_id, text_a, text_b):
self.unique_id = unique_id
self.text_a = text_a
self.text_b = text_b
| class InputExample(object):
| def __init__(self, unique_id, text_a, text_b):
self.unique_id = unique_id
self.text_a = text_a
self.text_b = text_b
| :
text_a = m.group(1)
text_b = m.group(2)
examples.append(
InputExample(unique_id=unique_id, text_a=text_a, text_b=text_b))
# unique_id += 1
return examples
## Bert text encoding
class InputExample(object):
| 64 | 64 | 45 | 5 | 58 | zigonk/ReSC | dataset/data_loader.py | Python | InputExample | InputExample | 68 | 72 | 68 | 68 | a3b4dc152927d019bec71a50db5c254710ebeac1 | bigcode/the-stack | train |
a49629d9326a3d1f568d999a | train | function | def read_examples(input_line, unique_id):
"""Read a list of `InputExample`s from an input file."""
examples = []
# unique_id = 0
line = input_line #reader.readline()
# if not line:
# break
line = line.strip()
text_a = None
text_b = None
m = re.match(r"^(.*) \|\|\| (.*)$", lin... | def read_examples(input_line, unique_id):
| """Read a list of `InputExample`s from an input file."""
examples = []
# unique_id = 0
line = input_line #reader.readline()
# if not line:
# break
line = line.strip()
text_a = None
text_b = None
m = re.match(r"^(.*) \|\|\| (.*)$", line)
if m is None:
text_a = line... | ization import BertTokenizer
from pytorch_pretrained_bert.modeling import BertModel
# from transformers import BertTokenizer,BertModel
from utils.transforms import letterbox, random_affine
sys.modules['utils'] = utils
cv2.setNumThreads(0)
def read_examples(input_line, unique_id):
| 64 | 64 | 162 | 9 | 55 | zigonk/ReSC | dataset/data_loader.py | Python | read_examples | read_examples | 46 | 65 | 46 | 46 | a69a7ccca7602f568768c5d73ce4d94b10c6856e | bigcode/the-stack | train |
e641b53a7f678a1efe358b75 | train | function | def get_token(key='API_TOKEN'):
return os.getenv(key, default=None)
| def get_token(key='API_TOKEN'):
| return os.getenv(key, default=None)
| import os
def get_token(key='API_TOKEN'):
| 11 | 64 | 17 | 8 | 2 | SerhatTeker/twpy | twpy/utilities.py | Python | get_token | get_token | 4 | 5 | 4 | 4 | d063286733a93c29d006b70f7c2db5c14e4e9b5c | bigcode/the-stack | train |
adbf399032d93099b4916d24 | train | function | @click.command()
@click.pass_context
@cli_options.OPTION_FILE()
@cli_options.OPTION_DIRECTORY()
@cli_options.OPTION_ELASTICSEARCH()
@cli_options.OPTION_ES_USERNAME()
@cli_options.OPTION_ES_PASSWORD()
@cli_options.OPTION_ES_IGNORE_CERTS()
def add(ctx, file_, directory, es, username, password, ignore_certs):
"""Add h... | @click.command()
@click.pass_context
@cli_options.OPTION_FILE()
@cli_options.OPTION_DIRECTORY()
@cli_options.OPTION_ELASTICSEARCH()
@cli_options.OPTION_ES_USERNAME()
@cli_options.OPTION_ES_PASSWORD()
@cli_options.OPTION_ES_IGNORE_CERTS()
def add(ctx, file_, directory, es, username, password, ignore_certs):
| """Add hurricane data to Elasticsearch"""
if all([file_ is None, directory is None]):
raise click.ClickException('Missing --file/-f or --dir/-d option')
conn_config = configure_es_connection(es, username, password, ignore_certs)
files_to_process = []
if file_ is not None:
files_t... | pass
@click.command()
@click.pass_context
@cli_options.OPTION_FILE()
@cli_options.OPTION_DIRECTORY()
@cli_options.OPTION_ELASTICSEARCH()
@cli_options.OPTION_ES_USERNAME()
@cli_options.OPTION_ES_PASSWORD()
@cli_options.OPTION_ES_IGNORE_CERTS()
def add(ctx, file_, directory, es, username, password, ignore_certs):
| 76 | 76 | 255 | 74 | 1 | cpomer10/msc-pygeoapi | msc_pygeoapi/loader/hurricanes_realtime.py | Python | add | add | 477 | 507 | 477 | 485 | 697d8679dcdf5b4852a827830ee52da6d1496902 | bigcode/the-stack | train |
d862bc07e6505d93252cabe7 | train | class | class HurricanesRealtimeLoader(BaseLoader):
"""Hurricanes Real-time loader"""
def __init__(self, conn_config={}):
"""initializer"""
BaseLoader.__init__(self)
self.conn = ElasticsearchConnector(conn_config)
self.filepath = None
self.date_ = None
self.fh = None
... | class HurricanesRealtimeLoader(BaseLoader):
| """Hurricanes Real-time loader"""
def __init__(self, conn_config={}):
"""initializer"""
BaseLoader.__init__(self)
self.conn = ElasticsearchConnector(conn_config)
self.filepath = None
self.date_ = None
self.fh = None
self.storm_name = None
self.s... | 'type': 'text',
'fields': {
'raw': {'type': 'keyword'}
}
},
'STORMTYPE': {
'type': 'byte'
},
'BASIN': {
'type': 'text',
'fields': {
'raw': {'type': 'keyword'}
}
},
'ac... | 256 | 256 | 1,240 | 7 | 249 | cpomer10/msc-pygeoapi | msc_pygeoapi/loader/hurricanes_realtime.py | Python | HurricanesRealtimeLoader | HurricanesRealtimeLoader | 289 | 468 | 289 | 289 | 20ae87ce8307d6f721661c944da5714a01a6d671 | bigcode/the-stack | train |
67fb93dbeaf5c46aafc21adc | train | function | @click.command()
@click.pass_context
@click.option('--index_name', '-i',
type=click.Choice(INDICES),
help='msc-geousage elasticsearch index name to delete')
@cli_options.OPTION_ELASTICSEARCH()
@cli_options.OPTION_ES_USERNAME()
@cli_options.OPTION_ES_PASSWORD()
@cli_options.OPTION_ES_IGNORE_C... | @click.command()
@click.pass_context
@click.option('--index_name', '-i',
type=click.Choice(INDICES),
help='msc-geousage elasticsearch index name to delete')
@cli_options.OPTION_ELASTICSEARCH()
@cli_options.OPTION_ES_USERNAME()
@cli_options.OPTION_ES_PASSWORD()
@cli_options.OPTION_ES_IGNORE_C... | """
Delete a particular ES index with a given name as argument or all if no
argument is passed
"""
conn_config = configure_es_connection(es, username, password, ignore_certs)
conn = ElasticsearchConnector(conn_config)
if index_name:
if click.confirm(
'Are you sure yo... | @click.command()
@click.pass_context
@click.option('--index_name', '-i',
type=click.Choice(INDICES),
help='msc-geousage elasticsearch index name to delete')
@cli_options.OPTION_ELASTICSEARCH()
@cli_options.OPTION_ES_USERNAME()
@cli_options.OPTION_ES_PASSWORD()
@cli_options.OPTION_ES_IGNORE_C... | 93 | 83 | 277 | 93 | 0 | cpomer10/msc-pygeoapi | msc_pygeoapi/loader/hurricanes_realtime.py | Python | delete_indexes | delete_indexes | 543 | 575 | 543 | 552 | 91f6399f8ae5227ceda6089d6b35c8b6e9539bae | bigcode/the-stack | train |
905d8ded30b026d4ca83fac4 | train | function | @click.group()
def hurricanes():
"""Manages hurricanes indices"""
pass
| @click.group()
def hurricanes():
| """Manages hurricanes indices"""
pass
| geojson features
package = self.generate_geojson_features()
self.conn.submit_elastic_package(package, request_size=80000)
return True
else:
LOGGER.debug("All Shapefile dependencies not found. Ignoring "
"file...")
return Fal... | 64 | 64 | 16 | 6 | 57 | cpomer10/msc-pygeoapi | msc_pygeoapi/loader/hurricanes_realtime.py | Python | hurricanes | hurricanes | 471 | 474 | 471 | 472 | fbb8b082e2d2ad091e900defebe5de5175a3733a | bigcode/the-stack | train |
5dc451ea46ca9c9ea88b3ece | train | function | @click.command()
@click.pass_context
@cli_options.OPTION_DAYS(
required=True,
help='Delete documents older than n days'
)
@cli_options.OPTION_ELASTICSEARCH()
@cli_options.OPTION_ES_USERNAME()
@cli_options.OPTION_ES_PASSWORD()
@cli_options.OPTION_ES_IGNORE_CERTS()
def deactivate(ctx, days, es, username, password... | @click.command()
@click.pass_context
@cli_options.OPTION_DAYS(
required=True,
help='Delete documents older than n days'
)
@cli_options.OPTION_ELASTICSEARCH()
@cli_options.OPTION_ES_USERNAME()
@cli_options.OPTION_ES_PASSWORD()
@cli_options.OPTION_ES_IGNORE_CERTS()
def deactivate(ctx, days, es, username, password... | """deactivate hurricane forecasts older than N days"""
conn_config = configure_es_connection(es, username, password, ignore_certs)
conn = ElasticsearchConnector(conn_config)
for index in INDICES:
query = {
"script": "ctx._source.properties.active=false",
"query": {
... | @click.command()
@click.pass_context
@cli_options.OPTION_DAYS(
required=True,
help='Delete documents older than n days'
)
@cli_options.OPTION_ELASTICSEARCH()
@cli_options.OPTION_ES_USERNAME()
@cli_options.OPTION_ES_PASSWORD()
@cli_options.OPTION_ES_IGNORE_CERTS()
def deactivate(ctx, days, es, username, password... | 81 | 64 | 195 | 81 | 0 | cpomer10/msc-pygeoapi | msc_pygeoapi/loader/hurricanes_realtime.py | Python | deactivate | deactivate | 510 | 540 | 510 | 520 | de83a0ff6d77e6164a342285cf104013f566a03e | bigcode/the-stack | train |
c1f802eac68abe6b0371e102 | train | class | class EgoDriver(XYSeperateDriver):
def __init__(self,
x_sigma, y_sigma,
**kwargs):
x_driver = IDMDriver(sigma=x_sigma, v_des=0.0, s_des=0.7, s_min=0.5, axis=0, min_overlap=0., **kwargs)
y_driver = PDDriver(sigma=y_sigma, p_des=0.0, a_max=1.0, axis=1, **kwargs)
... | class EgoDriver(XYSeperateDriver):
| def __init__(self,
x_sigma, y_sigma,
**kwargs):
x_driver = IDMDriver(sigma=x_sigma, v_des=0.0, s_des=0.7, s_min=0.5, axis=0, min_overlap=0., **kwargs)
y_driver = PDDriver(sigma=y_sigma, p_des=0.0, a_max=1.0, axis=1, **kwargs)
super(EgoDriver, self).__init__... | [0],0.5]
else:
self.car._color = [*RED_COLORS[0],0.5]
self.car._arr_color = [0.8, 0.8, 0.8, 0.5]
class EgoDriver(XYSeperateDriver):
| 64 | 64 | 179 | 9 | 55 | maxiaoba/rlk | tests/Traffic/traffic/scenarios/highway_2.py | Python | EgoDriver | EgoDriver | 96 | 110 | 96 | 96 | 9bb995ac7f68255e81d099a98901a32001c5af2c | bigcode/the-stack | train |
ce1397f2b4e80262fce41a0d | train | class | class EnvDriver(XYSeperateDriver):
def __init__(self,
aggressive,
x_sigma, y_sigma,
car,
**kwargs):
self.aggressive = aggressive
self.target_lane = None
self.car = car
if self.aggressive:
v_des = np.random.u... | class EnvDriver(XYSeperateDriver):
| def __init__(self,
aggressive,
x_sigma, y_sigma,
car,
**kwargs):
self.aggressive = aggressive
self.target_lane = None
self.car = car
if self.aggressive:
v_des = np.random.uniform(0.5, 1.0)
s_des ... | import random
import itertools
import numpy as np
from gym import spaces
from traffic.traffic_env import TrafficEnv
from traffic.road import Road, RoadSegment
from traffic.car import Car
from traffic.drivers.driver import Driver, XYSeperateDriver
from traffic.drivers.oned_drivers import IDMDriver, PDDriver, PDriver
fr... | 100 | 256 | 972 | 9 | 91 | maxiaoba/rlk | tests/Traffic/traffic/scenarios/highway_2.py | Python | EnvDriver | EnvDriver | 14 | 94 | 14 | 14 | 9b117d569c39f81f0b3b63d78d19eb9890914b31 | bigcode/the-stack | train |
81d107f9c0e8d6c9069fa5ee | train | class | class HighWay(TrafficEnv):
def __init__(self,
obs_noise=0.,
x_actions=[0.,0.5,3.],
y_actions=[0,1],
driver_sigma = 0.,
control_cost=0.01,
collision_cost=2.,
survive_reward=0.01,
go... | class HighWay(TrafficEnv):
| def __init__(self,
obs_noise=0.,
x_actions=[0.,0.5,3.],
y_actions=[0,1],
driver_sigma = 0.,
control_cost=0.01,
collision_cost=2.,
survive_reward=0.01,
goal_reward=2.,
... | .aggressive:
self.car._color = [*GREEN_COLORS[0],0.5]
else:
self.car._color = [*RED_COLORS[0],0.5]
self.car._arr_color = [0.8, 0.8, 0.8, 0.5]
class EgoDriver(XYSeperateDriver):
def __init__(self,
x_sigma, y_sigma,
**kwargs):
x_driver... | 256 | 256 | 3,107 | 8 | 247 | maxiaoba/rlk | tests/Traffic/traffic/scenarios/highway_2.py | Python | HighWay | HighWay | 112 | 431 | 112 | 112 | 2fa57bf44840d2c014d1726220cfb816e90f24ca | bigcode/the-stack | train |
ca4531b4509157a7e31871ec | train | class | class ObjectReprABC(object):
"""
The abstract base class of an object representer.
.. automethod:: __call__
"""
def __repr__(self):
"""
Return string representation.
OUTPUT:
String.
EXAMPLES::
sage: from sage.repl.display.fancy_repr import Ob... | class ObjectReprABC(object):
| """
The abstract base class of an object representer.
.. automethod:: __call__
"""
def __repr__(self):
"""
Return string representation.
OUTPUT:
String.
EXAMPLES::
sage: from sage.repl.display.fancy_repr import ObjectReprABC
sage:... | 2014 Volker Braun <vbraun.name@gmail.com>
#
# Distributed under the terms of the GNU General Public License (GPL)
# as published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.
# https://www.gnu.org/licenses/
# ******************************... | 130 | 130 | 436 | 7 | 123 | sensen1/sage | src/sage/repl/display/fancy_repr.py | Python | ObjectReprABC | ObjectReprABC | 27 | 102 | 27 | 27 | f5fb708ee70e517f6b8f0ee2a9cf1010fd0a0402 | bigcode/the-stack | train |
9ae1dface8bc03b7e96f2435 | train | class | class SomeIPythonRepr(ObjectReprABC):
def __init__(self):
"""
Some selected representers from IPython
EXAMPLES::
sage: from sage.repl.display.fancy_repr import SomeIPythonRepr
sage: SomeIPythonRepr()
SomeIPythonRepr pretty printer
.. automethod... | class SomeIPythonRepr(ObjectReprABC):
| def __init__(self):
"""
Some selected representers from IPython
EXAMPLES::
sage: from sage.repl.display.fancy_repr import SomeIPythonRepr
sage: SomeIPythonRepr()
SomeIPythonRepr pretty printer
.. automethod:: __call__
"""
type_re... | ObjectReprABC.__call__ is abstract'
"""
from sage.repl.display.pretty_print import SagePrettyPrinter
stream = StringIO()
p = SagePrettyPrinter(stream, 79, '\n')
ok = self(obj, p, False)
if ok:
p.flush()
return stream.getvalue()
else:
... | 95 | 95 | 319 | 11 | 84 | sensen1/sage | src/sage/repl/display/fancy_repr.py | Python | SomeIPythonRepr | SomeIPythonRepr | 105 | 155 | 105 | 106 | 04f054052703cd24aa0e2af0731fb71e97c8b2ae | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.