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
b2b5db20187d40a3c6e07bc5
train
function
def server() -> None: """The main processing loop for the websockets server.""" log.info("Apologies server started") log.info("Configuration: %s", config().to_json()) loop = asyncio.get_event_loop() stop = _add_signal_handlers(loop) _schedule_tasks(loop) _run_server(loop, stop) log.info(...
def server() -> None:
"""The main processing loop for the websockets server.""" log.info("Apologies server started") log.info("Configuration: %s", config().to_json()) loop = asyncio.get_event_loop() stop = _add_signal_handlers(loop) _schedule_tasks(loop) _run_server(loop, stop) log.info("Apologies server fini...
port = config().server_port close_timeout_sec = config().close_timeout_sec / 4 loop.run_until_complete(_websocket_server(stop=stop, host=host, port=port, close_timeout_sec=close_timeout_sec)) loop.stop() loop.close() def server() -> None:
64
64
81
6
58
pronovic/apologies-server
src/apologiesserver/server.py
Python
server
server
217
225
217
217
e54a49b4f91c10bc9b30423c767b556f4255f7ec
bigcode/the-stack
train
0ebff6583e5fa4e08bc80659
train
function
async def _handle_exception(exception: Exception, websocket: WebSocketServerProtocol) -> None: """Handle an exception by sending a request failed event.""" try: disconnect = False try: log.error("Handling exception: %s", str(exception), exc_info=True) raise exception ...
async def _handle_exception(exception: Exception, websocket: WebSocketServerProtocol) -> None:
"""Handle an exception by sending a request failed event.""" try: disconnect = False try: log.error("Handling exception: %s", str(exception), exc_info=True) raise exception except ProcessingError as e: disconnect = e.reason == FailureReason.WEBSOCKET_L...
: handler.handle_websocket_connected_event(websocket) await handler.execute_tasks() async def _handle_disconnect(websocket: WebSocketServerProtocol) -> None: """Handle a disconnected client.""" with EventHandler(manager()) as handler: async with handler.manager.lock: ha...
108
108
361
19
88
pronovic/apologies-server
src/apologiesserver/server.py
Python
_handle_exception
_handle_exception
109
138
109
109
11406755b629a7a31f333da1e33062301f2545be
bigcode/the-stack
train
dfa8722b8cbecab37b233f14
train
function
def _lookup_method(handler: EventHandler, message: MessageType) -> Callable[[RequestContext], None]: """Lookup the handler method to invoke for a message type.""" if message == MessageType.REREGISTER_PLAYER: return handler.handle_reregister_player_request elif message == MessageType.UNREGISTER_PLAYE...
def _lookup_method(handler: EventHandler, message: MessageType) -> Callable[[RequestContext], None]:
"""Lookup the handler method to invoke for a message type.""" if message == MessageType.REREGISTER_PLAYER: return handler.handle_reregister_player_request elif message == MessageType.UNREGISTER_PLAYER: return handler.handle_unregister_player_request elif message == MessageType.LIST_PLAYE...
win32": SHUTDOWN_SIGNALS = (signal.SIGTERM, signal.SIGINT) else: SHUTDOWN_SIGNALS = (signal.SIGHUP, signal.SIGTERM, signal.SIGINT) # pylint: disable=no-member # pylint: disable=too-many-return-statements,too-many-branches def _lookup_method(handler: EventHandler, message: MessageType) -> Callable[[RequestCont...
92
92
309
22
69
pronovic/apologies-server
src/apologiesserver/server.py
Python
_lookup_method
_lookup_method
30
59
30
30
3d08e69b2b58da47fb7907b141dc9b148b988ee1
bigcode/the-stack
train
bef30a3e651516de913bcdd7
train
function
def _run_server(loop: AbstractEventLoop, stop: "Future[Any]") -> None: """Run the websocket server, stopping and closing the event loop when the server completes.""" # Websockets has this to say about closing connections: # # The close_timeout parameter defines a maximum wait time in seconds for ...
def _run_server(loop: AbstractEventLoop, stop: "Future[Any]") -> None:
"""Run the websocket server, stopping and closing the event loop when the server completes.""" # Websockets has this to say about closing connections: # # The close_timeout parameter defines a maximum wait time in seconds for # completing the closing handshake and terminating the TCP connecti...
else: loop.add_signal_handler(sig, stop.set_result, None) return stop def _schedule_tasks(loop: AbstractEventLoop) -> None: """Schedule all of the scheduled tasks.""" log.info("Scheduling tasks...") for task in scheduled_tasks(): loop.create_task(task()) def _run_server(loop: Abst...
81
81
271
20
61
pronovic/apologies-server
src/apologiesserver/server.py
Python
_run_server
_run_server
192
214
192
193
66bd21ad1c3131915a095cec0d01076fbc05fbc9
bigcode/the-stack
train
c4768e487fd5fa636478ac62
train
function
async def _websocket_server(stop: "Future[Any]", host: str, port: int, close_timeout_sec: float) -> None: """Websocket server.""" log.info("Completed starting websocket server") # ok, it's a bit of a lie async with serve(_handle_connection, host=host, port=port, close_timeout=close_timeout_sec): aw...
async def _websocket_server(stop: "Future[Any]", host: str, port: int, close_timeout_sec: float) -> None:
"""Websocket server.""" log.info("Completed starting websocket server") # ok, it's a bit of a lie async with serve(_handle_connection, host=host, port=port, close_timeout=close_timeout_sec): await stop await _handle_shutdown()
"""Handle server shutdown.""" with EventHandler(manager()) as handler: async with handler.manager.lock: handler.handle_server_shutdown_event() await handler.execute_tasks() async def _websocket_server(stop: "Future[Any]", host: str, port: int, close_timeout_sec: float) -> None:
64
64
88
29
35
pronovic/apologies-server
src/apologiesserver/server.py
Python
_websocket_server
_websocket_server
165
170
165
165
2e72da5ea6e066ece397291f1cba19b132cccdc2
bigcode/the-stack
train
8680805922a4c01005a342d2
train
function
async def _handle_shutdown() -> None: """Handle server shutdown.""" with EventHandler(manager()) as handler: async with handler.manager.lock: handler.handle_server_shutdown_event() await handler.execute_tasks()
async def _handle_shutdown() -> None:
"""Handle server shutdown.""" with EventHandler(manager()) as handler: async with handler.manager.lock: handler.handle_server_shutdown_event() await handler.execute_tasks()
try: await _handle_data(data, websocket) except Exception as e: await _handle_exception(e, websocket) except ConnectionClosed: # we get this if the connection closes for any reason pass await _handle_disconnect(websocket) async def _handle_shutdown() -> None...
64
64
44
9
55
pronovic/apologies-server
src/apologiesserver/server.py
Python
_handle_shutdown
_handle_shutdown
157
162
157
157
7d5439242175d5d6371eb1a6d0fb5c85646ff92d
bigcode/the-stack
train
00e7077ee5d4b346b66b3757
train
function
async def _handle_data(data: Union[str, bytes], websocket: WebSocketServerProtocol) -> None: """Handle data received from a websocket client.""" log.debug("Received raw data for websocket %s:\n%s", id(websocket), mask(data)) message = Message.for_json(str(data)) with EventHandler(manager()) as handler: ...
async def _handle_data(data: Union[str, bytes], websocket: WebSocketServerProtocol) -> None:
"""Handle data received from a websocket client.""" log.debug("Received raw data for websocket %s:\n%s", id(websocket), mask(data)) message = Message.for_json(str(data)) with EventHandler(manager()) as handler: async with handler.manager.lock: _handle_message(handler, message, websoc...
game = handler.manager.lookup_game(game_id=player.game_id) request = RequestContext(message, websocket, player, game) method = _lookup_method(handler, request.message.message) method(request) async def _handle_data(data: Union[str, bytes], websocket: WebSocketServerProtocol) -> None...
64
64
95
22
42
pronovic/apologies-server
src/apologiesserver/server.py
Python
_handle_data
_handle_data
81
88
81
81
0fc82a404fd1e0ca42f364438db599d2fc23000a
bigcode/the-stack
train
88172e90fd3626455cfafd32
train
function
def _schedule_tasks(loop: AbstractEventLoop) -> None: """Schedule all of the scheduled tasks.""" log.info("Scheduling tasks...") for task in scheduled_tasks(): loop.create_task(task())
def _schedule_tasks(loop: AbstractEventLoop) -> None:
"""Schedule all of the scheduled tasks.""" log.info("Scheduling tasks...") for task in scheduled_tasks(): loop.create_task(task())
in SHUTDOWN_SIGNALS: if sys.platform == "win32": signal.signal(sig, lambda s, f: stop.set_result(None)) else: loop.add_signal_handler(sig, stop.set_result, None) return stop def _schedule_tasks(loop: AbstractEventLoop) -> None:
64
64
42
13
50
pronovic/apologies-server
src/apologiesserver/server.py
Python
_schedule_tasks
_schedule_tasks
185
189
185
185
3b96d708119a591dff5cbbb48112647fbaf7c0dc
bigcode/the-stack
train
c60fc40e514b83eebc3f3ec5
train
function
async def _handle_connection(websocket: WebSocketServerProtocol, _path: str) -> None: """Handle a client connection, invoked once for each client that connects to the server.""" await _handle_connect(websocket) try: async for data in websocket: try: await _handle_data(dat...
async def _handle_connection(websocket: WebSocketServerProtocol, _path: str) -> None:
"""Handle a client connection, invoked once for each client that connects to the server.""" await _handle_connect(websocket) try: async for data in websocket: try: await _handle_data(data, websocket) except Exception as e: await _handle_excepti...
error, # which doesn't seem quite right, either. log.error("Failed to handle exception: %s", str(e)) # pylint: disable=broad-except # noinspection PyBroadException async def _handle_connection(websocket: WebSocketServerProtocol, _path: str) -> None:
64
64
113
21
42
pronovic/apologies-server
src/apologiesserver/server.py
Python
_handle_connection
_handle_connection
143
154
143
143
4b1cf610965189238ebfada512810c9898975101
bigcode/the-stack
train
0a2195259ec11bcff725694b
train
function
def _add_signal_handlers(loop: AbstractEventLoop) -> "Future[Any]": """Add signal handlers so shutdown can be handled normally, returning the stop future.""" log.info("Adding signal handlers...") stop = loop.create_future() for sig in SHUTDOWN_SIGNALS: if sys.platform == "win32": sig...
def _add_signal_handlers(loop: AbstractEventLoop) -> "Future[Any]":
"""Add signal handlers so shutdown can be handled normally, returning the stop future.""" log.info("Adding signal handlers...") stop = loop.create_future() for sig in SHUTDOWN_SIGNALS: if sys.platform == "win32": signal.signal(sig, lambda s, f: stop.set_result(None)) else: ...
websocket server") # ok, it's a bit of a lie async with serve(_handle_connection, host=host, port=port, close_timeout=close_timeout_sec): await stop await _handle_shutdown() def _add_signal_handlers(loop: AbstractEventLoop) -> "Future[Any]":
64
64
103
17
47
pronovic/apologies-server
src/apologiesserver/server.py
Python
_add_signal_handlers
_add_signal_handlers
173
182
173
173
6467fa8b8ed9d5568f5f3e726146b6010bbcad0e
bigcode/the-stack
train
dff525de06376d3377890ac4
train
function
async def _handle_disconnect(websocket: WebSocketServerProtocol) -> None: """Handle a disconnected client.""" with EventHandler(manager()) as handler: async with handler.manager.lock: handler.handle_websocket_disconnected_event(websocket) await handler.execute_tasks()
async def _handle_disconnect(websocket: WebSocketServerProtocol) -> None:
"""Handle a disconnected client.""" with EventHandler(manager()) as handler: async with handler.manager.lock: handler.handle_websocket_disconnected_event(websocket) await handler.execute_tasks()
WebSocketServerProtocol) -> None: """Handle a newly-connected client.""" with EventHandler(manager()) as handler: async with handler.manager.lock: handler.handle_websocket_connected_event(websocket) await handler.execute_tasks() async def _handle_disconnect(websocket: WebSocketServe...
64
64
56
16
48
pronovic/apologies-server
src/apologiesserver/server.py
Python
_handle_disconnect
_handle_disconnect
99
104
99
99
017ce04b05f951e51d25086ea729e1f142c98396
bigcode/the-stack
train
1f6ee620931b9b43d8bee9d1
train
function
def _handle_message(handler: EventHandler, message: Message, websocket: WebSocketServerProtocol) -> None: """Handle a valid message received from a websocket client, assumed to be within the handler's lock.""" if message.message == MessageType.REGISTER_PLAYER: handler.handle_register_player_request(mess...
def _handle_message(handler: EventHandler, message: Message, websocket: WebSocketServerProtocol) -> None:
"""Handle a valid message received from a websocket client, assumed to be within the handler's lock.""" if message.message == MessageType.REGISTER_PLAYER: handler.handle_register_player_request(message, websocket) else: player = handler.manager.lookup_player(player_id=message.player_id) ...
elif message == MessageType.SEND_MESSAGE: return handler.handle_send_message_request else: raise ProcessingError(FailureReason.INTERNAL_ERROR, comment="Invalid request %s" % message.name) def _handle_message(handler: EventHandler, message: Message, websocket: WebSocketServerProtocol) -> None:
64
64
211
23
41
pronovic/apologies-server
src/apologiesserver/server.py
Python
_handle_message
_handle_message
62
78
62
62
f57d00c01f0452b54941378e00f0cb044dbda657
bigcode/the-stack
train
609cfbd232c8f077777ca9b4
train
function
async def _handle_connect(websocket: WebSocketServerProtocol) -> None: """Handle a newly-connected client.""" with EventHandler(manager()) as handler: async with handler.manager.lock: handler.handle_websocket_connected_event(websocket) await handler.execute_tasks()
async def _handle_connect(websocket: WebSocketServerProtocol) -> None:
"""Handle a newly-connected client.""" with EventHandler(manager()) as handler: async with handler.manager.lock: handler.handle_websocket_connected_event(websocket) await handler.execute_tasks()
id(websocket), mask(data)) message = Message.for_json(str(data)) with EventHandler(manager()) as handler: async with handler.manager.lock: _handle_message(handler, message, websocket) await handler.execute_tasks() async def _handle_connect(websocket: WebSocketServerProtocol) -> None...
64
64
56
16
48
pronovic/apologies-server
src/apologiesserver/server.py
Python
_handle_connect
_handle_connect
91
96
91
91
b17e638f15595daee05702f1ef2ea8a5820231cf
bigcode/the-stack
train
002b0393f9bac279690389d9
train
function
def alert(): """ makes sound on client using javascript (works with remote server) """ framerate = 44100 duration=0.6 freq=300 t = np.linspace(0,duration,framerate*duration) data = np.sin(2*np.pi*freq*t) d(Audio(data,rate=framerate, autoplay=True))
def alert():
""" makes sound on client using javascript (works with remote server) """ framerate = 44100 duration=0.6 freq=300 t = np.linspace(0,duration,framerate*duration) data = np.sin(2*np.pi*freq*t) d(Audio(data,rate=framerate, autoplay=True))
import numpy as np from IPython.display import Audio from IPython.display import display as d def alert():
24
64
80
3
20
Lewington-pitsos/mlutils
lepmlutils/general/audio.py
Python
alert
alert
5
12
5
5
bf54993b814d62edd347d9d42300b1f74b468b44
bigcode/the-stack
train
309121eacc9f97783e0eaa9d
train
function
def install_i18n(): """Install i18n.""" locale_dir = os.path.join(data_path(), 'locale') if not os.path.isdir(locale_dir): # find locale in module path qdc_converter_module = importlib.util.find_spec('qdc-converter') if qdc_converter_module: for path in qdc_converter_modu...
def install_i18n():
"""Install i18n.""" locale_dir = os.path.join(data_path(), 'locale') if not os.path.isdir(locale_dir): # find locale in module path qdc_converter_module = importlib.util.find_spec('qdc-converter') if qdc_converter_module: for path in qdc_converter_module.submodule_search_...
dp, _, fn in os.walk(root_path) for f in fn] for f in files: if any(f.endswith(ext) for ext in exts): full_path_f = os.path.join(root_path, f) result.append(full_path_f) return result def install_i18n():
64
64
119
6
57
interlark/qdc-converter
qdc_converter/utils.py
Python
install_i18n
install_i18n
98
110
98
98
e7b089a720b1f6c55e17ccc8392ea361e8377f3e
bigcode/the-stack
train
84694f21030fe723d577a040
train
function
def image_path(image_name): """Get package's data path. Args: image_name (str): Image basename. Returns: Image full path. """ return os.path.join(data_path(), 'images', image_name)
def image_path(image_name):
"""Get package's data path. Args: image_name (str): Image basename. Returns: Image full path. """ return os.path.join(data_path(), 'images', image_name)
data_path(): """Returns data path.""" if '_MEIPASS2' in os.environ: here = os.environ['_MEIPASS2'] else: here = os.path.dirname(os.path.abspath(__file__)) return os.path.join(here, 'data') def image_path(image_name):
64
64
50
6
58
interlark/qdc-converter
qdc_converter/utils.py
Python
image_path
image_path
42
51
42
42
4feba95a084b3b6d71b50ff85421399aebe6cea3
bigcode/the-stack
train
7c7ccb9436e71f97cd5cfe0e
train
function
def patch_tqdm(tqdm, message_queue): """Patch tqdm to make it dublicate progress to `message_queue`. Args: tqdm (tqdm.tqdm) Tqdm class to be patched. message_queue (multiprocessing.Queue): Message queue. """ original_update = tqdm.update original_close = tqdm.close def new_upda...
def patch_tqdm(tqdm, message_queue):
"""Patch tqdm to make it dublicate progress to `message_queue`. Args: tqdm (tqdm.tqdm) Tqdm class to be patched. message_queue (multiprocessing.Queue): Message queue. """ original_update = tqdm.update original_close = tqdm.close def new_update(tqdm_self, *args, **kwargs): ...
data') def image_path(image_name): """Get package's data path. Args: image_name (str): Image basename. Returns: Image full path. """ return os.path.join(data_path(), 'images', image_name) def patch_tqdm(tqdm, message_queue):
64
64
190
12
52
interlark/qdc-converter
qdc_converter/utils.py
Python
patch_tqdm
patch_tqdm
54
73
54
54
f4e54e7255abad198ecf75fe2d00b352a911c7a2
bigcode/the-stack
train
bbae6c9a49da1ac518d8935e
train
function
def print_error(error_msg, message_queue=None): """Print error message to `stderr` and dublicate it to `message_queue` if it's been passed. Args: error_msg (str): Error message. message_queue (multiprocessing.Queue): Message queue. """ print(error_msg, file=sys.stderr) if messag...
def print_error(error_msg, message_queue=None):
"""Print error message to `stderr` and dublicate it to `message_queue` if it's been passed. Args: error_msg (str): Error message. message_queue (multiprocessing.Queue): Message queue. """ print(error_msg, file=sys.stderr) if message_queue: # Send error message up to the ...
: if e.name != 'PySimpleGUI': # GUI was installed, but failed to load # due to tkinter missing or other dependencies. warnings.warn('Failed to load GUI: %s' % e.msg) GUI_ENABLED = False def print_error(error_msg, message_queue=None):
64
64
97
10
53
interlark/qdc-converter
qdc_converter/utils.py
Python
print_error
print_error
19
30
19
19
a8b582249d8bf9b79c799d43e48d9257c06bcf35
bigcode/the-stack
train
25c7571bf8baec0930cb8404
train
function
def data_path(): """Returns data path.""" if '_MEIPASS2' in os.environ: here = os.environ['_MEIPASS2'] else: here = os.path.dirname(os.path.abspath(__file__)) return os.path.join(here, 'data')
def data_path():
"""Returns data path.""" if '_MEIPASS2' in os.environ: here = os.environ['_MEIPASS2'] else: here = os.path.dirname(os.path.abspath(__file__)) return os.path.join(here, 'data')
Args: error_msg (str): Error message. message_queue (multiprocessing.Queue): Message queue. """ print(error_msg, file=sys.stderr) if message_queue: # Send error message up to the message queue message_queue.put(('#Error', error_msg)) def data_path():
64
64
59
4
60
interlark/qdc-converter
qdc_converter/utils.py
Python
data_path
data_path
33
39
33
33
ba5e5a778a68ad138c668ef22f1b3684bfb77756
bigcode/the-stack
train
5d39e5c4e5df3b5ed14c61d1
train
function
def get_files_recursively(root_path, exts): """Recursively search for files with the extension specified in `exts`. Args: root_path (str): Root path. exts (str): Files extension. Returns: List of found files. """ if type(exts) not in (list, tuple): exts = (exts,...
def get_files_recursively(root_path, exts):
"""Recursively search for files with the extension specified in `exts`. Args: root_path (str): Root path. exts (str): Files extension. Returns: List of found files. """ if type(exts) not in (list, tuple): exts = (exts,) result = [] files = [os.path.join(...
, **kwargs): message_queue.put(('#UpdateProgressBar', (tqdm_self.n, tqdm_self.total))) original_close(tqdm_self, *args, **kwargs) tqdm.update = new_update tqdm.close = new_close def get_files_recursively(root_path, exts):
64
64
156
11
52
interlark/qdc-converter
qdc_converter/utils.py
Python
get_files_recursively
get_files_recursively
76
95
76
76
147cbc084d9ab3e34bba325687b30900cd477ad7
bigcode/the-stack
train
09f937fdf13d330532596300
train
class
class GameSprite(sprite.Sprite): def __init__(self, player_image, player_speed, start_x, start_y, sprite_hight, sprite_weight, hp, sprite_class): super().__init__() self.sprite_class = sprite_class self.HP = hp self.sprite_hight = sprite_hight self.sprite_weight = sprit...
class GameSprite(sprite.Sprite):
def __init__(self, player_image, player_speed, start_x, start_y, sprite_hight, sprite_weight, hp, sprite_class): super().__init__() self.sprite_class = sprite_class self.HP = hp self.sprite_hight = sprite_hight self.sprite_weight = sprite_weight self.image = tra...
import pygame from pygame import * FPS = 60 Color = (127, 255, 0) class GameSprite(sprite.Sprite):
30
64
157
6
24
USER-MATVEY/Simpl-Ping-Pong-game
Ping-Pong game.py
Python
GameSprite
GameSprite
8
23
8
8
b88f3f7f8e34c19fff69b92639205fd1e38e7ac5
bigcode/the-stack
train
9ff2243fe338525c55811ed0
train
class
class Ball(sprite.Sprite): def __init__(self, ball_image, width, height, rect_x, rect_y, speed): super().__init__() self.width = width self.height = height self.image = transform.scale(image.load(ball_image), (self.height, self.width)) self.rect = self.image.get_rect() ...
class Ball(sprite.Sprite):
def __init__(self, ball_image, width, height, rect_x, rect_y, speed): super().__init__() self.width = width self.height = height self.image = transform.scale(image.load(ball_image), (self.height, self.width)) self.rect = self.image.get_rect() self.rect.x = rect_...
self.rect.y -= self.speed if keys_pressed[self.key_down] and self.rect.y < window_hight - 160: self.rect.y += self.speed def draw_player(self): main_win.blit(self.image, (self.rect.x, self.rect.y)) class Ball(sprite.Sprite):
63
64
124
5
58
USER-MATVEY/Simpl-Ping-Pong-game
Ping-Pong game.py
Python
Ball
Ball
53
66
53
53
a110807dbf6898bc11fcbdd5fb6f4f9102ce5d38
bigcode/the-stack
train
310d370d787852a466569f66
train
class
class Player(sprite.Sprite): def __init__(self, color, width, height, rect_x, rect_y, speed, K_Up, K_Down): super().__init__() self.color = color self.width = width self.height = height self.image = Surface((self.width, self.height)) self.image.fill(self.color)...
class Player(sprite.Sprite):
def __init__(self, color, width, height, rect_x, rect_y, speed, K_Up, K_Down): super().__init__() self.color = color self.width = width self.height = height self.image = Surface((self.width, self.height)) self.image.fill(self.color) self.rect = self.ima...
.speed = player_speed self.rect = self.image.get_rect() self.rect.x = start_x self.rect.y = start_y self.flag = True def show_sprite(self): main_win.blit(self.image, (self.rect.x, self.rect.y)) class Player(sprite.Sprite):
63
64
214
5
58
USER-MATVEY/Simpl-Ping-Pong-game
Ping-Pong game.py
Python
Player
Player
26
50
26
26
0448bfb517b98f277212c6542b01d7f2adab0994
bigcode/the-stack
train
42f295c76be1313e2a240bb9
train
class
class Edit(forms.Form): # Article content title = forms.CharField( label="Title", help_text="Title of the article." ) preview = forms.CharField( label="Preview", help_text="The article preview.", widget=forms.Textarea(attrs={ 'class' : 'pagedownBootstrap', 'row...
class Edit(forms.Form): # Article content
title = forms.CharField( label="Title", help_text="Title of the article." ) preview = forms.CharField( label="Preview", help_text="The article preview.", widget=forms.Textarea(attrs={ 'class' : 'pagedownBootstrap', 'rows' : '5' }) ) content = forms.CharF...
article" ) content = forms.CharField( label="Article", widget=forms.Textarea(attrs={'rows' : '10'}) ) # Author info author = forms.CharField( label="Author", help_text="Author's name" ) email = forms.EmailField( label="Email" ) coverletter = forms.CharField( label...
128
128
427
10
118
F483/trainlessmagazine.com
article/forms.py
Python
Edit
Edit
36
97
36
38
bfa973818c518ceb00076a17dbf1a1251f18ddec
bigcode/the-stack
train
1874e2a8b9c2fcdb67a35981
train
class
class Submit(forms.Form): # Article content title = forms.CharField( label="Title", help_text="Title of the article" ) content = forms.CharField( label="Article", widget=forms.Textarea(attrs={'rows' : '10'}) ) # Author info author = forms.CharField( label="Author", he...
class Submit(forms.Form): # Article content
title = forms.CharField( label="Title", help_text="Title of the article" ) content = forms.CharField( label="Article", widget=forms.Textarea(attrs={'rows' : '10'}) ) # Author info author = forms.CharField( label="Author", help_text="Author's name" ) email = forms.Ema...
from django import forms from article.models import Issue from article.models import Category from captcha.fields import CaptchaField class Submit(forms.Form): # Article content
35
64
147
10
24
F483/trainlessmagazine.com
article/forms.py
Python
Submit
Submit
7
33
7
9
bffd118d86ef090df50c1f182b5d84f70efe30cc
bigcode/the-stack
train
e7426618e7411febf5800a0b
train
class
class Solution(object): def distinctEchoSubstrings(self, text): """ :type text: str :rtype: int """ def KMP(text, l, result): prefix = [-1]*(len(text)-l) j = -1 for i in range(1, len(prefix)): while j > -1 and text[l+j+1] !=...
class Solution(object):
def distinctEchoSubstrings(self, text): """ :type text: str :rtype: int """ def KMP(text, l, result): prefix = [-1]*(len(text)-l) j = -1 for i in range(1, len(prefix)): while j > -1 and text[l+j+1] != text[l+i]: ...
# Time: O(n^2 + d), d is the duplicated of result substrings size # Space: O(r), r is the size of result substrings set class Solution(object):
41
87
290
4
36
sm2774us/leetcode_interview_prep_2021
Python/distinct-echo-substrings.py
Python
Solution
Solution
4
31
4
4
f10a36ac1f5fec03a62c6eced57a8e56f9411907
bigcode/the-stack
train
2a6029b24c89d75f8559c486
train
class
class Solution3(object): def distinctEchoSubstrings(self, text): """ :type text: str :rtype: int """ MOD = 10**9+7 D = 27 # a-z and '' result = set() for i in range(len(text)-1): left, right, pow_D = 0, 0, 1 for l in range(1, m...
class Solution3(object):
def distinctEchoSubstrings(self, text): """ :type text: str :rtype: int """ MOD = 10**9+7 D = 27 # a-z and '' result = set() for i in range(len(text)-1): left, right, pow_D = 0, 0, 1 for l in range(1, min(i+2, len(text)-i)): ...
result.add(text[len(text)-2*l:len(text)-2*l+l]) return len(result) # Time: O(n^2 + d), d is the duplicated of result substrings size # Space: O(r), r is the size of result substrings set class Solution3(object):
64
64
189
5
58
sm2774us/leetcode_interview_prep_2021
Python/distinct-echo-substrings.py
Python
Solution3
Solution3
56
73
56
56
f9175335e83b3501b94ead82fb8d6ed428eac714
bigcode/the-stack
train
b93ee73536401ed84ae3fd1e
train
class
class Solution_TLE(object): def distinctEchoSubstrings(self, text): """ :type text: str :rtype: int """ def compare(text, l, s1, s2): for i in range(l): if text[s1+i] != text[s2+i]: return False return True ...
class Solution_TLE(object):
def distinctEchoSubstrings(self, text): """ :type text: str :rtype: int """ def compare(text, l, s1, s2): for i in range(l): if text[s1+i] != text[s2+i]: return False return True MOD = 10**9+7 D = 27...
: # assumed no collision result.add(left) pow_D = (pow_D*D) % MOD return len(result) # Time: O(n^3 + d), d is the duplicated of result substrings size # Space: O(r), r is the size of result substrings set class Solution_TLE(object):
73
73
244
6
66
sm2774us/leetcode_interview_prep_2021
Python/distinct-echo-substrings.py
Python
Solution_TLE
Solution_TLE
78
101
78
78
af8f462d471c04e3acadcfff0c27835bd7922aca
bigcode/the-stack
train
406f5aba275b3574c3544793
train
class
class Solution2(object): def distinctEchoSubstrings(self, text): """ :type text: str :rtype: int """ result = set() for l in range(1, len(text)//2+1): count = sum(text[i] == text[i+l] for i in range(l)) for i in range(len(text)-2*l): ...
class Solution2(object):
def distinctEchoSubstrings(self, text): """ :type text: str :rtype: int """ result = set() for l in range(1, len(text)//2+1): count = sum(text[i] == text[i+l] for i in range(l)) for i in range(len(text)-2*l): if count == l: ...
, i + KMP(text, i, result)); i += 1 return len(result) # Time: O(n^2 + d), d is the duplicated of result substrings size # Space: O(r), r is the size of result substrings set class Solution2(object):
64
64
147
5
58
sm2774us/leetcode_interview_prep_2021
Python/distinct-echo-substrings.py
Python
Solution2
Solution2
36
51
36
36
10e0f0724eb3806348ff7d07454620fb0ed1101f
bigcode/the-stack
train
48bd8938db03540f8e5652ca
train
function
@click.command() def main(args=None): """Console script for hydra.""" click.echo("Replace this message by putting your code into " "hydra.cli.main") click.echo("See click documentation at https://click.palletsprojects.com/") return 0
@click.command() def main(args=None):
"""Console script for hydra.""" click.echo("Replace this message by putting your code into " "hydra.cli.main") click.echo("See click documentation at https://click.palletsprojects.com/") return 0
"""Console script for hydra.""" import sys import click @click.command() def main(args=None):
21
64
58
8
12
kforti/Hydra
hydra/cli.py
Python
main
main
6
12
6
7
095ec8decb7762196664617972de7024629de58b
bigcode/the-stack
train
37e34bac48270c808e0d8d05
train
function
def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table("dashboard_data")
def downgrade(): # ### commands auto generated by Alembic - please adjust! ###
op.drop_table("dashboard_data")
sa.Column("name", sa.String(), nullable=True), sa.Column("data", postgresql.JSONB(), nullable=True), sa.PrimaryKeyConstraint("id"), ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ###
63
64
27
19
44
eclecticiq/eiq-er-ce
plgx-esp/migrations/versions/88ded24e39c7_.py
Python
downgrade
downgrade
33
36
33
35
f17293405f580bb667ee86c1c3d87d290a47373f
bigcode/the-stack
train
f01a4b30f1b51663fa41808b
train
function
def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "dashboard_data", sa.Column("id", sa.Integer(), nullable=False), sa.Column("created_at", sa.DateTime(), nullable=False), sa.Column("updated_at", sa.DateTime(), nullable=False), s...
def upgrade(): # ### commands auto generated by Alembic - please adjust! ###
op.create_table( "dashboard_data", sa.Column("id", sa.Integer(), nullable=False), sa.Column("created_at", sa.DateTime(), nullable=False), sa.Column("updated_at", sa.DateTime(), nullable=False), sa.Column("name", sa.String(), nullable=True), sa.Column("data", postgresq...
ic. revision = "88ded24e39c7" down_revision = "8fbff117e23d" import sqlalchemy as sa from alembic import op from sqlalchemy.dialects import postgresql def upgrade(): # ### commands auto generated by Alembic - please adjust! ###
64
64
104
18
45
eclecticiq/eiq-er-ce
plgx-esp/migrations/versions/88ded24e39c7_.py
Python
upgrade
upgrade
18
28
18
19
9711b0c44e26f671a5e03f27018477e9f4d94755
bigcode/the-stack
train
a07200da5e6de343f636e4b8
train
function
def args_runner(args): return ModificationSummary( modifications=args.modifications, alignmentSummary=args.alignmentSummary, outfile=args.gff_out).run()
def args_runner(args):
return ModificationSummary( modifications=args.modifications, alignmentSummary=args.alignmentSummary, outfile=args.gff_out).run()
in self.knownModificationEvents]) rec.modsrev = ",".join( # pylint: disable=assigning-non-slot [str(cRev[x]) for x in self.knownModificationEvents]) print(str(rec), file=summaryWriter) return 0 def args_runner(args):
64
64
33
5
58
zxgsy520/kineticsTools
kineticsTools/summarizeModifications.py
Python
args_runner
args_runner
130
134
130
130
10d6d98a4f1e90a405ab7a67c2d44b5314987943
bigcode/the-stack
train
7ee6507314f3cf7fc549bc8d
train
class
class Constants(object): TOOL_ID = "kinetics_tools.tasks.summarize_modifications" DRIVER_EXE = "python -m kineticsTools.summarizeModifications --resolved-tool-contract"
class Constants(object):
TOOL_ID = "kinetics_tools.tasks.summarize_modifications" DRIVER_EXE = "python -m kineticsTools.summarizeModifications --resolved-tool-contract"
import logging import sys from pbcommand.cli import get_default_argparser_with_base_opts, pacbio_args_runner from pbcommand.utils import setup_log from pbcore.io import GffReader, Gff3Record # Version info... __version__ = "1.0" class Constants(object):
64
64
40
4
60
zxgsy520/kineticsTools
kineticsTools/summarizeModifications.py
Python
Constants
Constants
22
24
22
22
0eb4a4ac76a1e64e612ff509ee23222e375607a3
bigcode/the-stack
train
74752e4bb21d1b6120cef35e
train
class
class ModificationSummary(object): def __init__(self, modifications, alignmentSummary, outfile): self.modifications = modifications self.alignmentSummary = alignmentSummary self.outfile = outfile def run(self, profile=False): self.knownModificationEvents = ["modified_base", "m6A...
class ModificationSummary(object):
def __init__(self, modifications, alignmentSummary, outfile): self.modifications = modifications self.alignmentSummary = alignmentSummary self.outfile = outfile def run(self, profile=False): self.knownModificationEvents = ["modified_base", "m6A", "m4C", "m5C"] if profile...
#!/usr/bin/env python3 """ Summarizes kinetic modifications in the alignment_summary.gff file. """ import cProfile from itertools import groupby import functools import os import logging import sys from pbcommand.cli import get_default_argparser_with_base_opts, pacbio_args_runner from pbcommand.utils import setup_lo...
142
256
863
5
137
zxgsy520/kineticsTools
kineticsTools/summarizeModifications.py
Python
ModificationSummary
ModificationSummary
27
127
27
27
56ae57be2175ed6c8c220beae83ed0c257a936be
bigcode/the-stack
train
62ee456c47a0f69d4a3da8b2
train
function
def get_parser(): p = get_default_argparser_with_base_opts( version=__version__, description=__doc__, default_level="INFO") p.add_argument("modifications", help="Base modification GFF file") p.add_argument("alignmentSummary", help="Alignment summary GFF") p.add...
def get_parser():
p = get_default_argparser_with_base_opts( version=__version__, description=__doc__, default_level="INFO") p.add_argument("modifications", help="Base modification GFF file") p.add_argument("alignmentSummary", help="Alignment summary GFF") p.add_argument("gff_out...
Rev[x]) for x in self.knownModificationEvents]) print(str(rec), file=summaryWriter) return 0 def args_runner(args): return ModificationSummary( modifications=args.modifications, alignmentSummary=args.alignmentSummary, outfile=args.gff_out).run() def get_par...
64
64
100
4
60
zxgsy520/kineticsTools
kineticsTools/summarizeModifications.py
Python
get_parser
get_parser
137
147
137
137
f9ea20a5581a1490de7cdfd23416b674f9117f2d
bigcode/the-stack
train
33335ddbae6b2e7f7ef6a17b
train
function
def main(argv=sys.argv): setup_log_ = functools.partial(setup_log, str_formatter='%(asctime)s [%(levelname)s] %(message)s') return pacbio_args_runner( argv=argv[1:], parser=get_parser(), args_runner_func=args_runner, alog=logging.getLogger(__nam...
def main(argv=sys.argv):
setup_log_ = functools.partial(setup_log, str_formatter='%(asctime)s [%(levelname)s] %(message)s') return pacbio_args_runner( argv=argv[1:], parser=get_parser(), args_runner_func=args_runner, alog=logging.getLogger(__name__), setup_log_f...
help="Base modification GFF file") p.add_argument("alignmentSummary", help="Alignment summary GFF") p.add_argument("gff_out", help="Coverage summary for regions (bins) spanning the reference with basemod results for each region") return p def main(argv=sys.argv):
64
64
80
6
57
zxgsy520/kineticsTools
kineticsTools/summarizeModifications.py
Python
main
main
150
158
150
150
ad4d6e319b9d7e15b10e15e6be1aa40736a25b55
bigcode/the-stack
train
2c1f9f252d80bc27908ce847
train
function
def _convert(obj, attributes, skip): s = {} for key in attributes: val = getattr(obj, key, False) if not val: continue if isinstance(val, string_types): s[key] = val else: try: s[key] = [rep(v, skip) for v in iter(val)] ...
def _convert(obj, attributes, skip):
s = {} for key in attributes: val = getattr(obj, key, False) if not val: continue if isinstance(val, string_types): s[key] = val else: try: s[key] = [rep(v, skip) for v in iter(val)] except TypeError: ...
name__, ", ".join(itertools.chain( (str(_) for _ in func.args), ("%s=%s" % (key, value) for key, value in iteritems(func.keywords if func.keywords else {}))))) return str(func) def _convert(obj, attributes, skip):
64
64
94
9
55
meysam81/transitions
transitions/extensions/markup.py
Python
_convert
_convert
150
163
150
150
b56bca532048640a546be8d460e5279022d100d0
bigcode/the-stack
train
891afcdadfb39dc1228a2c5f
train
function
def rep(func, skip_references=False): """ Return a string representation for `func`. """ if isinstance(func, string_types): return func if isinstance(func, numbers.Number): return str(func) if skip_references: return None try: return func.__name__ except Attribute...
def rep(func, skip_references=False):
""" Return a string representation for `func`. """ if isinstance(func, string_types): return func if isinstance(func, numbers.Number): return str(func) if skip_references: return None try: return func.__name__ except AttributeError: pass if isinstance(...
_is_auto_transition(self, event): if event.name.startswith('to_') and len(event.transitions) == len(self.states): state_name = event.name[len('to_'):] if state_name in self.states: return True return False def rep(func, skip_references=False):
64
64
147
9
54
meysam81/transitions
transitions/extensions/markup.py
Python
rep
rep
128
147
128
128
d5d9f33435f1c2a18bf9c95acdd5f9cfafd9efb2
bigcode/the-stack
train
3db53f64b62c9403ad655186
train
class
class MarkupMachine(Machine): # Special attributes such as NestedState._name/_parent or Transition._condition are handled differently state_attributes = ['on_exit', 'on_enter', 'ignore_invalid_triggers', 'timeout', 'on_timeout', 'tags'] transition_attributes = ['source', 'dest', 'prepare', 'before', 'after...
class MarkupMachine(Machine): # Special attributes such as NestedState._name/_parent or Transition._condition are handled differently
state_attributes = ['on_exit', 'on_enter', 'ignore_invalid_triggers', 'timeout', 'on_timeout', 'tags'] transition_attributes = ['source', 'dest', 'prepare', 'before', 'after'] def __init__(self, *args, **kwargs): self._markup = kwargs.pop('markup', {}) self._auto_transitions_markup = kwargs...
from six import string_types, iteritems from functools import partial import itertools import importlib from collections import defaultdict from ..core import Machine import numbers class MarkupMachine(Machine): # Special attributes such as NestedState._name/_parent or Transition._condition are handled differentl...
62
256
1,244
27
34
meysam81/transitions
transitions/extensions/markup.py
Python
MarkupMachine
MarkupMachine
11
125
11
13
b95483ca600af55b2da193a59030423d9111e643
bigcode/the-stack
train
44cce5a33b73a357dad24180
train
function
def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'abc_bank.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installe...
def main():
"""Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'abc_bank.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " ...
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main():
26
64
99
3
22
jmothiki/abc_bank
manage.py
Python
main
main
7
18
7
7
29f62ce45fc63922e92540cac76145c71d065b35
bigcode/the-stack
train
5a2a468ec19c275aad849b9f
train
class
class User(): def __init__(self, fname, lname, email,title='Mrs',org = 'ORG',mobile_number=123456, connection=None): self.fname = fname.lower() self.lname = lname.lower() self.fname = fname.capitalize() self.lname = lname.capitalize() self.email = email self.mobile_nu...
class User():
def __init__(self, fname, lname, email,title='Mrs',org = 'ORG',mobile_number=123456, connection=None): self.fname = fname.lower() self.lname = lname.lower() self.fname = fname.capitalize() self.lname = lname.capitalize() self.email = email self.mobile_number = mobile_...
import ldap3 from ldap3 import HASHED_SALTED_SHA, MODIFY_REPLACE, ALL from ldap3.utils.hashed import hashed import string import random class User():
39
256
858
3
35
rajdudhare1/create-ldap-users
utils/ldap.py
Python
User
User
8
95
8
8
80daa29010c24aa7bb0d5744316d09a0fc5a03c9
bigcode/the-stack
train
21e7f426249da2cc69d1a672
train
class
class LDAPConnection(): def __init__(self): self.conn = None self.search_base = None self.search_filter = None self.search_attrs= None def create_connection(self, servername,user, password,search_base,search_filter = '(objectClass=inetOrgPerson)',search_attrs=['*'],port="389"): ...
class LDAPConnection():
def __init__(self): self.conn = None self.search_base = None self.search_filter = None self.search_attrs= None def create_connection(self, servername,user, password,search_base,search_filter = '(objectClass=inetOrgPerson)',search_attrs=['*'],port="389"): server_uri = 'ld...
else: self.__password_generator() self.__getNextAvailableGid() self.__generate_user_config() self.conn.add(self.userdn,attributes=self.attributes) self.modify_user_password() return self.password else: ...
63
64
154
4
59
rajdudhare1/create-ldap-users
utils/ldap.py
Python
LDAPConnection
LDAPConnection
97
113
97
97
340de4a4fdc6dd682c1e6febbfc47e76fdadaa21
bigcode/the-stack
train
1966a0ce330be6634ca0ce8d
train
function
def bitwise_xor(s: str, t: str) -> str: length = len(s) res = [] for i in range(length): res.append(str(int(s[i]) ^ int(t[i]))) return ''.join(res[::-1])
def bitwise_xor(s: str, t: str) -> str:
length = len(s) res = [] for i in range(length): res.append(str(int(s[i]) ^ int(t[i]))) return ''.join(res[::-1])
Register from qiskit import BasicAer, execute, transpile from pprint import pprint from qiskit.test.mock import FakeVigo from math import log2 import numpy as np import networkx as nx def bitwise_xor(s: str, t: str) -> str:
64
64
54
16
47
UCLA-SEAL/QDiff
benchmark/startQiskit_Class3101.py
Python
bitwise_xor
bitwise_xor
14
19
14
14
643dca80c9054c8a7c10bfe226d5dd994f1f8215
bigcode/the-stack
train
11197e10be8a6a1a60f22aa6
train
function
def make_circuit(n:int,f) -> QuantumCircuit: # circuit begin input_qubit = QuantumRegister(n,"qc") classical = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classical) prog.h(input_qubit[3]) # number=30 prog.cz(input_qubit[0],input_qubit[3]) # number=31 prog.h(input_qubit[3])...
def make_circuit(n:int,f) -> QuantumCircuit: # circuit begin
input_qubit = QuantumRegister(n,"qc") classical = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classical) prog.h(input_qubit[3]) # number=30 prog.cz(input_qubit[0],input_qubit[3]) # number=31 prog.h(input_qubit[3]) # number=32 prog.h(input_qubit[3]) # number=37 prog.cz(i...
ates # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate controls = QuantumRegister(n, "ofc") target = QuantumRegister(1, "oft") oracle = QuantumCircuit(controls, target, name="Of") for i in range(2 ** n): rep = np.binary_repr(i, n) i...
188
188
627
17
170
UCLA-SEAL/QDiff
benchmark/startQiskit_Class3101.py
Python
make_circuit
make_circuit
51
97
51
52
8d626d565f72af48e304e02e54481417667a37da
bigcode/the-stack
train
bcf354d95c976cfc1466fe1c
train
function
def build_oracle(n: int, f) -> QuantumCircuit: # implement the oracle O_f # NOTE: use multi_control_toffoli_gate ('noancilla' mode) # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html # https://quantumcomputing.stackexchange.com/questions/3943/how-do-yo...
def build_oracle(n: int, f) -> QuantumCircuit: # implement the oracle O_f # NOTE: use multi_control_toffoli_gate ('noancilla' mode) # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html # https://quantumcomputing.stackexchange.com/questions/3943/how-do-yo...
controls = QuantumRegister(n, "ofc") target = QuantumRegister(1, "oft") oracle = QuantumCircuit(controls, target, name="Of") for i in range(2 ** n): rep = np.binary_repr(i, n) if f(rep) == "1": for j in range(n): if rep[j] == "0": oracle.x(...
def build_oracle(n: int, f) -> QuantumCircuit: # implement the oracle O_f # NOTE: use multi_control_toffoli_gate ('noancilla' mode) # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html # https://quantumcomputing.stackexchange.com/questions/3943/how-do-yo...
138
83
278
138
0
UCLA-SEAL/QDiff
benchmark/startQiskit_Class3101.py
Python
build_oracle
build_oracle
29
49
29
34
b7a8ed7a88aaeae13a59b1564c24bee83d544220
bigcode/the-stack
train
c2bc83d68025841d084659b2
train
function
def bitwise_dot(s: str, t: str) -> str: length = len(s) res = 0 for i in range(length): res += int(s[i]) * int(t[i]) return str(res % 2)
def bitwise_dot(s: str, t: str) -> str:
length = len(s) res = 0 for i in range(length): res += int(s[i]) * int(t[i]) return str(res % 2)
(s: str, t: str) -> str: length = len(s) res = [] for i in range(length): res.append(str(int(s[i]) ^ int(t[i]))) return ''.join(res[::-1]) def bitwise_dot(s: str, t: str) -> str:
64
64
54
15
49
UCLA-SEAL/QDiff
benchmark/startQiskit_Class3101.py
Python
bitwise_dot
bitwise_dot
22
27
22
22
078fbe078cfdf1766c9b9ac20f7a3207be47445c
bigcode/the-stack
train
e58173da55d6222eda238f75
train
function
def build_key_word(path): # 通过词频产生特征 d = {} with open(path, encoding="utf-8") as fp: for line in fp: for word in jieba.cut(line.strip()): p = re.compile(r'\w', re.L) result = p.sub("", word) if not result or result == ' ': # 空字符 ...
def build_key_word(path): # 通过词频产生特征
d = {} with open(path, encoding="utf-8") as fp: for line in fp: for word in jieba.cut(line.strip()): p = re.compile(r'\w', re.L) result = p.sub("", word) if not result or result == ' ': # 空字符 continue if len...
from os import path d = path.dirname(__file__) stop = [line.strip() for line in open('../ad/stop.txt', 'r', encoding='utf-8').readlines()] # 停用词 def build_key_word(path): # 通过词频产生特征
64
64
214
16
47
wu546300070/weiboanalysis
word_cloud/draw_word.py
Python
build_key_word
build_key_word
9
27
9
9
bbe8621765079db3d8b8fd3e68597b19d9c531e0
bigcode/the-stack
train
40f5391a98026ed86866e19b
train
function
def get_public_api(): if CUSTOM_URL is not None: return CUSTOM_URL else: return PUBLIC_API_URL
def get_public_api():
if CUSTOM_URL is not None: return CUSTOM_URL else: return PUBLIC_API_URL
NETRC_HOST_NAME = 'api.juiceboxdata.com' PUBLIC_API_URL = 'https://api.juiceboxdata.com' CUSTOM_URL = None def get_public_api():
39
64
27
5
33
juiceinc/juicebox-cli
juicebox_cli/config.py
Python
get_public_api
get_public_api
6
10
6
6
1bbd0b6a0a51c3263f1449e47f27fc1629ddef61
bigcode/the-stack
train
d8783dd68afb8aa458361444
train
class
class YadiConan(ConanFile): name = "yasi" version = "0.1" license = "<Put the package license here>" url = "<Package recipe repository url here, for issues about the package>" description = "<Description of Yadi here>" settings = "os", "compiler", "build_type", "arch" generators = "cmake" ...
class YadiConan(ConanFile):
name = "yasi" version = "0.1" license = "<Put the package license here>" url = "<Package recipe repository url here, for issues about the package>" description = "<Description of Yadi here>" settings = "os", "compiler", "build_type", "arch" generators = "cmake" requires = "yadi/0.1@ebcla...
from conans import ConanFile, CMake, tools class YadiConan(ConanFile):
22
95
318
10
11
ebclark2/yasi
conanfile.py
Python
YadiConan
YadiConan
4
33
4
4
794c6ac8ab2aa3124fc07b690547dd33cd1fea74
bigcode/the-stack
train
7ca85815122139a47f7d961c
train
function
def euclidean_distance(x1, x2): d = np.sqrt(np.sum((x1 - x2) ** 2, axis=1)) return d
def euclidean_distance(x1, x2):
d = np.sqrt(np.sum((x1 - x2) ** 2, axis=1)) return d
import numpy as np def euclidean_distance(x1, x2):
15
64
36
10
4
abrosua/ml-with-numpy
models/knn/_math.py
Python
euclidean_distance
euclidean_distance
4
6
4
4
bcca507cd30f57b3847700ccb60898ea1f12f4b6
bigcode/the-stack
train
76ba45b3c6c257177288a834
train
function
def manhattan_distance(x1, x2): d = np.sum(np.abs(x1 - x2), axis=1) return d
def manhattan_distance(x1, x2):
d = np.sum(np.abs(x1 - x2), axis=1) return d
import numpy as np def euclidean_distance(x1, x2): d = np.sqrt(np.sum((x1 - x2) ** 2, axis=1)) return d def manhattan_distance(x1, x2):
51
64
31
10
40
abrosua/ml-with-numpy
models/knn/_math.py
Python
manhattan_distance
manhattan_distance
9
11
9
9
f45f028bb5a28aabb2f6721d35993f6a088a57d0
bigcode/the-stack
train
43680105bd5699ce971dec0a
train
class
class Task: global_id = 0 def create(description, done, due): Task.global_id = Task.global_id + 1 return Task(Task.global_id, str(uuid.uuid1()), description, done, due, datetime.datetime.now()) def __init__(self, id, uuid, description, done, due, created_at): self.id = id s...
class Task:
global_id = 0 def create(description, done, due): Task.global_id = Task.global_id + 1 return Task(Task.global_id, str(uuid.uuid1()), description, done, due, datetime.datetime.now()) def __init__(self, id, uuid, description, done, due, created_at): self.id = id self.uuid = u...
import os import pickle import pyotherside import random import threading import time import uuid import datetime DEFAULT_SAVE_PATH="~/.harbour-tothem.pickle" class Task:
43
64
168
3
40
FAMM/harbour-tothem
qml/backend/app.py
Python
Task
Task
12
35
12
12
c307433b46bd14de118508d79cdf356581627324
bigcode/the-stack
train
6fbd16e14afb0d1df9810275
train
class
class TaskList: def __init__(self): self._tasks = [] pyotherside.send('finished') def get_tasks(self): return [task.to_dict() for task in self._tasks] def add_task(self, description, done, due): task = Task.create(description, done, due) self._tasks.append(task) ...
class TaskList:
def __init__(self): self._tasks = [] pyotherside.send('finished') def get_tasks(self): return [task.to_dict() for task in self._tasks] def add_task(self, description, done, due): task = Task.create(description, done, due) self._tasks.append(task) pyotherside...
_id + 1 return Task(Task.global_id, str(uuid.uuid1()), description, done, due, datetime.datetime.now()) def __init__(self, id, uuid, description, done, due, created_at): self.id = id self.uuid = uuid self.done = done self.description = description self.due = due ...
146
146
489
4
142
FAMM/harbour-tothem
qml/backend/app.py
Python
TaskList
TaskList
37
103
37
37
077cc603263e6f75424bd9ca2f03890272087ff6
bigcode/the-stack
train
0205bbdd035e74cece4d816c
train
class
class SecularMultipleInterface(CodeInterface): """ SecularMultiple -- by Adrian Hamers, based on 2016MNRAS.459.2827H A code to compute the secular (orbit-averaged) gravitational dynamics of hierarchical multiple systems composed of nested binary orbits (simplex-type systems). with any configuration and...
class SecularMultipleInterface(CodeInterface):
""" SecularMultiple -- by Adrian Hamers, based on 2016MNRAS.459.2827H A code to compute the secular (orbit-averaged) gravitational dynamics of hierarchical multiple systems composed of nested binary orbits (simplex-type systems). with any configuration and any number of bodies. A particle can repesent ...
from amuse.community import * from amuse.units import units,constants ### units used in the legacy code ### ### numerical values are defined in src/types.h ### unit_l = units.AU unit_m = units.MSun unit_t = 1.0e6*units.yr unit_h = unit_m*unit_l**2/unit_t ### specific angular momentum unit_e = unit_m*unit_l**2/(unit_t*...
121
256
15,364
8
113
rknop/amuse
src/amuse/community/secularmultiple/interface.py
Python
SecularMultipleInterface
SecularMultipleInterface
15
1,412
15
15
6b635724c64b96cd56889370b14ca4886a30787b
bigcode/the-stack
train
94c5e31583f0a21975540429
train
class
class SecularMultiple(InCodeComponentImplementation): def __init__(self, **options): InCodeComponentImplementation.__init__(self, SecularMultipleInterface(**options), **options) self.model_time = 0.0 | units.Myr self.particles_committed = False self.initial_hamiltonian = 0...
class SecularMultiple(InCodeComponentImplementation):
def __init__(self, **options): InCodeComponentImplementation.__init__(self, SecularMultipleInterface(**options), **options) self.model_time = 0.0 | units.Myr self.particles_committed = False self.initial_hamiltonian = 0.0 | unit_e self.hamiltonian = 0.0 | unit_e ...
@legacy_function def get_include_hexadecupole_order_binary_pair_terms(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legac...
256
256
3,279
9
246
rknop/amuse
src/amuse/community/secularmultiple/interface.py
Python
SecularMultiple
SecularMultiple
1,414
1,708
1,414
1,415
b2f72f68de1154160a0334271a7acda382f647c2
bigcode/the-stack
train
cf420cf0bc79a45a193de9c1
train
function
def generate_fontconfig_pattern(d): """ Given a dictionary of key/value pairs, generates a fontconfig pattern string. """ props = [] families = '' size = '' for key in 'family style variant weight stretch file size'.split(): val = getattr(d, 'get_' + key)() if val is not ...
def generate_fontconfig_pattern(d):
""" Given a dictionary of key/value pairs, generates a fontconfig pattern string. """ props = [] families = '' size = '' for key in 'family style variant weight stretch file size'.split(): val = getattr(d, 'get_' + key)() if val is not None and val != []: if t...
[0]] self._properties.setdefault(key, []).append(val) else: key = tokens[0] val = tokens[1:] self._properties.setdefault(key, []).extend(val) return [] parse_fontconfig_pattern = FontconfigPatternParser().parse def generate_fontconfig_pattern(d):
64
64
148
7
56
pierre-haessig/matplotlib
lib/matplotlib/fontconfig_pattern.py
Python
generate_fontconfig_pattern
generate_fontconfig_pattern
174
190
174
174
93831e86991d0492b46ecff990534a83bec09f79
bigcode/the-stack
train
507a008b884aaac2f1b7eede
train
class
class FontconfigPatternParser: """A simple pyparsing-based parser for fontconfig-style patterns. See the `fontconfig pattern specification <http://www.fontconfig.org/fontconfig-user.html>`_ for more information. """ _constants = { 'thin' : ('weight', 'light'), 'extral...
class FontconfigPatternParser:
"""A simple pyparsing-based parser for fontconfig-style patterns. See the `fontconfig pattern specification <http://www.fontconfig.org/fontconfig-user.html>`_ for more information. """ _constants = { 'thin' : ('weight', 'light'), 'extralight' : ('weight', 'light')...
The font manager (:file:`font_manager.py`) # It probably logically belongs in :file:`font_manager.py`, but # placing it in any of these places would have created cyclical # dependency problems, or an undesired dependency on traits even # when the traits-based config framework is not used. from __future__ import prin...
256
256
1,063
6
249
pierre-haessig/matplotlib
lib/matplotlib/fontconfig_pattern.py
Python
FontconfigPatternParser
FontconfigPatternParser
39
170
39
39
cde71235c9f1c261195d9f0d706fdcf26e86d874
bigcode/the-stack
train
5b5437b787d86fca41a3a490
train
class
class SpellingChecker(Activatable): __metaclass__ = ABCMeta def __init__(self, spelling_config=None): Activatable.__init__(self) self.spelling_config = spelling_config def initialise(self, storage_factory): pass @abstractmethod def correct(self, phrase): raise NotI...
class SpellingChecker(Activatable):
__metaclass__ = ABCMeta def __init__(self, spelling_config=None): Activatable.__init__(self) self.spelling_config = spelling_config def initialise(self, storage_factory): pass @abstractmethod def correct(self, phrase): raise NotImplementedError() @staticmethod...
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNE...
124
124
415
8
115
johnlito123/Xuez_AI
src/xuex-ai/spelling/base.py
Python
SpellingChecker
SpellingChecker
25
79
25
25
0b63d2ba22f2b78592263f1b69bf9a2da9c010e3
bigcode/the-stack
train
a0bd975468862ec7b3f92746
train
class
class myGreatCommand(lxu.command.BasicCommand): def __init__(self): lxu.command.BasicCommand.__init__(self) # command accepts an argument self.dyna_Add('time', lx.symbol.sTYPE_STRING) self.dyna_Add('frames', lx.symbol.sTYPE_STRING) self.dyna_Add('usePasses', lx.symbol.sTYPE...
class myGreatCommand(lxu.command.BasicCommand):
def __init__(self): lxu.command.BasicCommand.__init__(self) # command accepts an argument self.dyna_Add('time', lx.symbol.sTYPE_STRING) self.dyna_Add('frames', lx.symbol.sTYPE_STRING) self.dyna_Add('usePasses', lx.symbol.sTYPE_BOOLEAN) def basic_Execute(self, msg, flags...
import lx import lxu.command import traceback import monkey, modo, time, os DEFAULT_TIME = '00:30:00' DEFAULT_FRAMES = '1' DEFAULT_USE_PASSES = 0 BLESS = 'monkey.renderProg' class myGreatCommand(lxu.command.BasicCommand):
64
256
944
10
54
ShawnFrueh/mecco_renderMonkey
lxserv/rm_render.py
Python
myGreatCommand
myGreatCommand
12
118
12
13
6c38f35e6f7779133dca6e4ba45275e67a37e2ae
bigcode/the-stack
train
c4538d3eb1298eb777bbf7bd
train
class
class GlobalSettingsViewSet(ViewSet): def get_object(self): return GlobalSettings.load() def get_permissions(self): if self.request.method == 'GET' or self.request.method == 'POST': return [IsAuthenticated()] else: return [IsSuperUser()] @swagger_auto_schema...
class GlobalSettingsViewSet(ViewSet):
def get_object(self): return GlobalSettings.load() def get_permissions(self): if self.request.method == 'GET' or self.request.method == 'POST': return [IsAuthenticated()] else: return [IsSuperUser()] @swagger_auto_schema( method='GET', respon...
, status from rest_framework.decorators import action from rest_framework.permissions import BasePermission, IsAuthenticated from rest_framework.response import Response from rest_framework.viewsets import ViewSet from miqa.core.models import GlobalSettings from miqa.core.tasks import export_data, import_data class ...
119
119
399
8
111
knowledgevis/miqa
miqa/core/rest/global_settings.py
Python
GlobalSettingsViewSet
GlobalSettingsViewSet
23
83
23
23
f3af765d291e7c6bf5ff4faf67972c116afd1b87
bigcode/the-stack
train
3eb4f2f75ac5e51c0a832bdc
train
class
class GlobalSettingsSerializer(serializers.ModelSerializer): class Meta: model = GlobalSettings exclude = ['id']
class GlobalSettingsSerializer(serializers.ModelSerializer):
class Meta: model = GlobalSettings exclude = ['id']
.viewsets import ViewSet from miqa.core.models import GlobalSettings from miqa.core.tasks import export_data, import_data class IsSuperUser(BasePermission): def has_permission(self, request, view): return bool(request.user and request.user.is_superuser) class GlobalSettingsSerializer(serializers.ModelSer...
64
64
24
8
56
knowledgevis/miqa
miqa/core/rest/global_settings.py
Python
GlobalSettingsSerializer
GlobalSettingsSerializer
17
20
17
17
dd14856ca24f483d95a614fadf2f5653512dffec
bigcode/the-stack
train
2329d9de3a5e74b9a9de7e13
train
class
class IsSuperUser(BasePermission): def has_permission(self, request, view): return bool(request.user and request.user.is_superuser)
class IsSuperUser(BasePermission):
def has_permission(self, request, view): return bool(request.user and request.user.is_superuser)
status from rest_framework.decorators import action from rest_framework.permissions import BasePermission, IsAuthenticated from rest_framework.response import Response from rest_framework.viewsets import ViewSet from miqa.core.models import GlobalSettings from miqa.core.tasks import export_data, import_data class IsS...
64
64
29
7
56
knowledgevis/miqa
miqa/core/rest/global_settings.py
Python
IsSuperUser
IsSuperUser
12
14
12
12
cdc66d6928f8f0e0103083ebfbb4c792dc419f27
bigcode/the-stack
train
06cfed4ee749db4e8b387905
train
function
def _get_parser(): parser = argparse.ArgumentParser(description="Grab cell from TSV file.") parser.add_argument( "--dset", dest="dset", required=True, help="Dataset name.", ) parser.add_argument( "--subject", dest="subject", required=True, ...
def _get_parser():
parser = argparse.ArgumentParser(description="Grab cell from TSV file.") parser.add_argument( "--dset", dest="dset", required=True, help="Dataset name.", ) parser.add_argument( "--subject", dest="subject", required=True, help="Subject ident...
_files[0] # Generate and compile nuisance regressors for aCompCor, GSR, and the nuisance model compile_nuisance_regressors( medn_file, mask_file, seg_file, cgm_file, confounds_file, ) def _get_parser():
64
64
83
5
59
NBCLab/power-replication
processing/05_generate_single-echo_confounds.py
Python
_get_parser
_get_parser
204
218
204
204
af042e3e660e8a4be0fa2ace6089d216081d6a2f
bigcode/the-stack
train
4aa5676c4b6d1f449bfd5457
train
function
def main(project_dir, dset, subject): """Run the confound-generation workflow. Notes ----- Example physio file: /home/data/nbc/misc-projects/Salo_PowerReplication/dset-dupre/sub-01/\ func/sub-01_task-rest_run-01_physio.tsv.gz Example physio metadata file: /home/data/nbc/misc-projects/Salo_P...
def main(project_dir, dset, subject):
"""Run the confound-generation workflow. Notes ----- Example physio file: /home/data/nbc/misc-projects/Salo_PowerReplication/dset-dupre/sub-01/\ func/sub-01_task-rest_run-01_physio.tsv.gz Example physio metadata file: /home/data/nbc/misc-projects/Salo_PowerReplication/dset-dupre/\ s...
brain_mask=mask_file, ) gsr_signal = masking.apply_mask(medn_file, cgm_mask) gsr_signal = np.mean(gsr_signal, axis=1) confounds_df["GSRRegression_CorticalRibbon"] = gsr_signal confounds_metadata["GSRRegression_CorticalRibbon"] = { "Sources": [medn_file, cgm_file, mask_file], "Descri...
167
167
559
10
156
NBCLab/power-replication
processing/05_generate_single-echo_confounds.py
Python
main
main
142
201
142
142
14b4270b660cc2afe67e36064f846605a5e63950
bigcode/the-stack
train
d83942437ab26a0f8ed8a7ff
train
function
def compile_nuisance_regressors( medn_file, mask_file, seg_file, cgm_file, confounds_file, ): """Generate regressors for aCompCor, GSR, and the nuisance model and write out to file.""" confounds_json = confounds_file.replace(".tsv", ".json") # ######### # Load data # ######### ...
def compile_nuisance_regressors( medn_file, mask_file, seg_file, cgm_file, confounds_file, ):
"""Generate regressors for aCompCor, GSR, and the nuisance model and write out to file.""" confounds_json = confounds_file.replace(".tsv", ".json") # ######### # Load data # ######### confounds_df = pd.read_table(confounds_file) with open(confounds_json, "r") as fo: confounds_metada...
""" Perform standard denoising (not TE-dependent denoising). Methods: - Global signal regression with custom code (integrated in tedana, but we do it separately here because the approach is very different) - Dynamic global signal regression with rapidtide - aCompCor with custom code - GODEC with the ME-ICA...
153
256
1,103
33
119
NBCLab/power-replication
processing/05_generate_single-echo_confounds.py
Python
compile_nuisance_regressors
compile_nuisance_regressors
22
139
22
28
b8dcf376bcfe6ac9e5961e803f4442b3ad66a560
bigcode/the-stack
train
3474c1f5e39438eb46b0d3d0
train
function
def _main(argv=None): options = _get_parser().parse_args(argv) kwargs = vars(options) project_dir = "/home/data/nbc/misc-projects/Salo_PowerReplication/" main(project_dir=project_dir, **kwargs)
def _main(argv=None):
options = _get_parser().parse_args(argv) kwargs = vars(options) project_dir = "/home/data/nbc/misc-projects/Salo_PowerReplication/" main(project_dir=project_dir, **kwargs)
"--dset", dest="dset", required=True, help="Dataset name.", ) parser.add_argument( "--subject", dest="subject", required=True, help="Subject identifier, with the sub- prefix.", ) return parser def _main(argv=None):
64
64
54
6
57
NBCLab/power-replication
processing/05_generate_single-echo_confounds.py
Python
_main
_main
221
225
221
221
b4827d2d19e692aa0920b7e6140ed668f7896de3
bigcode/the-stack
train
161a031a5acd5b0bbcd5d3c4
train
function
@requires_qt @requires_astropy def test_load_simple_tables_04(): # This loads a session file made with Glue v0.4. In this session, we have # loaded four tables. The first two are from the same file, but one loaded # via the auto loader and the other via the Astropy FITS table loader. The # second two w...
@requires_qt @requires_astropy def test_load_simple_tables_04(): # This loads a session file made with Glue v0.4. In this session, we have # loaded four tables. The first two are from the same file, but one loaded # via the auto loader and the other via the Astropy FITS table loader. The # second two w...
with open(os.path.join(DATA, 'simple_tables.glu'), 'r') as f: template = f.read() content = template.replace('{DATA_PATH}', (DATA + os.sep).replace('\\', '\\\\')) state = GlueUnSerializer.loads(content) ga = state.object('__main__') dc = ga.session.data_collection # All tables should...
@requires_qt @requires_astropy def test_load_simple_tables_04(): # This loads a session file made with Glue v0.4. In this session, we have # loaded four tables. The first two are from the same file, but one loaded # via the auto loader and the other via the Astropy FITS table loader. The # second two w...
140
139
465
140
0
Jerry-Ma/glue
glue/tests/test_session_back_compat.py
Python
test_load_simple_tables_04
test_load_simple_tables_04
16
57
16
26
76f557a9f3fd50fa771e320be42c2d656efea616
bigcode/the-stack
train
f967ee99caebe87c2b90a07f
train
function
@requires_qt def test_load_pixel_components_07(): # This loads a session file made with Glue v0.7. In 0.7 and before, # PixelComponentID did not exist, so we need to make sure that when loading # in such files, we transform the appropriate ComponentIDs to # PixelComponentIDs. with open(os.path.joi...
@requires_qt def test_load_pixel_components_07(): # This loads a session file made with Glue v0.7. In 0.7 and before, # PixelComponentID did not exist, so we need to make sure that when loading # in such files, we transform the appropriate ComponentIDs to # PixelComponentIDs.
with open(os.path.join(DATA, 'glue_v0.7_pixel_roi_selection.glu'), 'r') as f: content = f.read() state = GlueUnSerializer.loads(content) ga = state.object('__main__') assert isinstance(ga.data_collection[0].pixel_component_ids[0], PixelComponentID) assert isinstance(ga.data_collection[0]....
@requires_qt def test_load_pixel_components_07(): # This loads a session file made with Glue v0.7. In 0.7 and before, # PixelComponentID did not exist, so we need to make sure that when loading # in such files, we transform the appropriate ComponentIDs to # PixelComponentIDs.
75
64
166
75
0
Jerry-Ma/glue
glue/tests/test_session_back_compat.py
Python
test_load_pixel_components_07
test_load_pixel_components_07
151
167
151
158
581f8af4c06342e440fc3656bc554cf5fa9c598c
bigcode/the-stack
train
77611c0dc118999876016654
train
function
@requires_qt @requires_h5py def test_load_hdf5_grids_04(): # This loads a session file made with Glue v0.4. In this session, we have # loaded two gridded datasets from an HDF5 datafile: the first one loaded # via the auto loader and the other via the FITS/HDF5 loader. with open(os.path.join(DATA, 'sim...
@requires_qt @requires_h5py def test_load_hdf5_grids_04(): # This loads a session file made with Glue v0.4. In this session, we have # loaded two gridded datasets from an HDF5 datafile: the first one loaded # via the auto loader and the other via the FITS/HDF5 loader.
with open(os.path.join(DATA, 'simple_hdf5_grid.glu'), 'r') as f: template = f.read() content = template.replace('{DATA_PATH}', (DATA + os.sep).replace('\\', '\\\\')) state = GlueUnSerializer.loads(content) ga = state.object('__main__') dc = ga.session.data_collection assert len(dc) =...
@requires_qt @requires_h5py def test_load_hdf5_grids_04(): # This loads a session file made with Glue v0.4. In this session, we have # loaded two gridded datasets from an HDF5 datafile: the first one loaded # via the auto loader and the other via the FITS/HDF5 loader.
83
71
237
83
0
Jerry-Ma/glue
glue/tests/test_session_back_compat.py
Python
test_load_hdf5_grids_04
test_load_hdf5_grids_04
60
86
60
67
5faad522bc4df663aadc48370a107b99db438e3a
bigcode/the-stack
train
2f373854d213e8676f6536b5
train
function
@requires_qt @requires_astropy def test_load_viewers_04(): # This loads a session file made with Glue v0.4. In this session, we have # three viewers: one scatter viewer, one image viewer, and one histogram # viewer. with open(os.path.join(DATA, 'simple_viewers.glu'), 'r') as f: content = f.rea...
@requires_qt @requires_astropy def test_load_viewers_04(): # This loads a session file made with Glue v0.4. In this session, we have # three viewers: one scatter viewer, one image viewer, and one histogram # viewer.
with open(os.path.join(DATA, 'simple_viewers.glu'), 'r') as f: content = f.read() state = GlueUnSerializer.loads(content) ga = state.object('__main__') assert len(ga.viewers[0]) == 3 labels = sorted([x.LABEL for x in ga.viewers[0]]) assert labels == ['1D Histogram', '2D Image Viewer'...
open(os.path.join(DATA, 'session_links.glu'), 'r') as f: content = f.read() state = GlueUnSerializer.loads(content) ga = state.object('__main__') @requires_qt @requires_astropy def test_load_viewers_04(): # This loads a session file made with Glue v0.4. In this session, we have # three viewe...
103
103
344
61
42
Jerry-Ma/glue
glue/tests/test_session_back_compat.py
Python
test_load_viewers_04
test_load_viewers_04
106
148
106
113
23f6f54afdd24fec606d20eefdf9e09af666b9e7
bigcode/the-stack
train
811481f9ef9e1cb51fdedd2a
train
function
@requires_qt @requires_astropy def test_load_link_helpers_04(): # This loads a session file made with Glue v0.4. In this session, we have # two tables, and we use all the celestial link functions that were present # in Glue v0.4. We now check that the paths are patched when loading the # session (since...
@requires_qt @requires_astropy def test_load_link_helpers_04(): # This loads a session file made with Glue v0.4. In this session, we have # two tables, and we use all the celestial link functions that were present # in Glue v0.4. We now check that the paths are patched when loading the # session (since...
with open(os.path.join(DATA, 'session_links.glu'), 'r') as f: content = f.read() state = GlueUnSerializer.loads(content) ga = state.object('__main__')
@requires_qt @requires_astropy def test_load_link_helpers_04(): # This loads a session file made with Glue v0.4. In this session, we have # two tables, and we use all the celestial link functions that were present # in Glue v0.4. We now check that the paths are patched when loading the # session (since...
93
64
137
93
0
Jerry-Ma/glue
glue/tests/test_session_back_compat.py
Python
test_load_link_helpers_04
test_load_link_helpers_04
89
103
89
97
703d91b5e30d0ee1a13c571265a6913ccc16a540
bigcode/the-stack
train
a60388626ba27d5267e37114
train
class
class ViewTest(BaseTestCase): """ Tests Linguist views. """ @before def setup(self): obj = self.translated_instance # noqa def _check_language(self, response): lang = translation.get_language() self.assertEqual(response.status_code, 200) dct = json.loads(respon...
class ViewTest(BaseTestCase):
""" Tests Linguist views. """ @before def setup(self): obj = self.translated_instance # noqa def _check_language(self, response): lang = translation.get_language() self.assertEqual(response.status_code, 200) dct = json.loads(response.content.decode("utf-8")) ...
# -*- coding: utf-8 -*- import json from django.utils import translation from django.conf import settings from exam.decorators import before from .base import BaseTestCase class ViewTest(BaseTestCase):
44
64
195
7
36
Dj-Denis/django-linguist
linguist/tests/test_views.py
Python
ViewTest
ViewTest
12
40
12
12
d458e09d16754492fed735e7d78440de7aef0774
bigcode/the-stack
train
8155cb15f53591bf01c53e54
train
class
class RequestHandler: headers = {} cookies = {} context = {} __response = None def __init__(self, headers=None, cookies=None): self.headers = headers self.cookies = cookies @property def get_response(self): return self.__response async def session(self, **kwarg...
class RequestHandler:
headers = {} cookies = {} context = {} __response = None def __init__(self, headers=None, cookies=None): self.headers = headers self.cookies = cookies @property def get_response(self): return self.__response async def session(self, **kwargs): async with...
from aiohttp import ClientSession from src.core.logging import log class RequestHandler:
18
64
168
4
13
matheuslins/easydarf
src/core/request.py
Python
RequestHandler
RequestHandler
6
32
6
6
aaea2b7c57496befb55bacf1686206c3fa7888eb
bigcode/the-stack
train
ec613b167919913c28181d54
train
function
def page_rank(G, d=0.85, tolerance=0.01, max_iterations=50): """Returns the PageRank of the nodes in the graph. :param dict G: the graph :param float d: the damping factor :param flat tol: tolerance to determine algorithm convergence :param int max_iter: max number of iterations """ N = len...
def page_rank(G, d=0.85, tolerance=0.01, max_iterations=50):
"""Returns the PageRank of the nodes in the graph. :param dict G: the graph :param float d: the damping factor :param flat tol: tolerance to determine algorithm convergence :param int max_iter: max number of iterations """ N = len(G) pr = dict.fromkeys(G, 1.0) print("======= Initial...
"""A python implementation of the PageRank algorithm. Requirements: ------------ None Usage: ------------ python3 page_rank.py NB: this code was developed and tested with python 3.7 Disclaimer: this code is intended for teaching purposes only. """ def page_rank(G, d=0.85, tolerance=0.01, max_iterations=50):
75
89
298
22
53
PacktPublishing/Hands-On-Graph-Analytics-with-Neo4j
Chapter06/page_rank.py
Python
page_rank
page_rank
19
50
19
19
56ab2771e56861ea0f5ab60472625c6b9b2ec028
bigcode/the-stack
train
c59e9db63ae7cc5c2908dcfa
train
function
def simple_french_qcm(): """ Builds a simple French :epkg:`QCM` about mathématiques. """ math_sixieme = Notion('not-math-1', 'not-math-1', 'fr', domain='maths', level='6A') objs = [ QuestionChoice('ch1', '2prem', 'fr', 'Le nombre 2 est-il un nombre premier ?', ...
def simple_french_qcm():
""" Builds a simple French :epkg:`QCM` about mathématiques. """ math_sixieme = Notion('not-math-1', 'not-math-1', 'fr', domain='maths', level='6A') objs = [ QuestionChoice('ch1', '2prem', 'fr', 'Le nombre 2 est-il un nombre premier ?', notion...
# -*- coding: utf-8 -*- """ @file @brief Shortcut to *tests*. """ import math from ..activities import Notion, QuestionChoice, ActivityGroup def simple_french_qcm():
44
256
879
7
36
sdpython/mathenjeu
src/mathenjeu/tests/qcms.py
Python
simple_french_qcm
simple_french_qcm
10
69
10
10
6a12acce4de8159cb41a83e7aa77be20e46e65b6
bigcode/the-stack
train
b8e519f870e179ae6f9b1845
train
function
def ml_french_qcm(): """ Builds a simple French :epkg:`QCM` about machine learning. """ niveau = Notion('not-math-2', 'not-math-2', 'fr', domain='maths', level='20A') objs = [ QuestionChoice('ch1', 'pen', 'fr', 'Si ce dessin vous inspire quelques mots...', ...
def ml_french_qcm():
""" Builds a simple French :epkg:`QCM` about machine learning. """ niveau = Notion('not-math-2', 'not-math-2', 'fr', domain='maths', level='20A') objs = [ QuestionChoice('ch1', 'pen', 'fr', 'Si ce dessin vous inspire quelques mots...', notion=nivea...
7', 'tva', 'fr', 'Vous avez acheté un produit à 10 euros. La TVA est à 20%, quel est le prix sans la TVA ?', notion=math_sixieme, answers=['8 euros', '9.2', '10 * 0.8', '10 / 1.2', '7.8', '10 / 1.2'], expected_answers=[...
256
256
1,576
7
249
sdpython/mathenjeu
src/mathenjeu/tests/qcms.py
Python
ml_french_qcm
ml_french_qcm
72
195
72
72
091c47d7fbaf25f8017943b7415a529aff3d9366
bigcode/the-stack
train
49634fe65e409d390fbdf02b
train
function
def simple_cinema_qcm(): """ Builds a simple French :epkg:`QCM` about movies. """ cinema_seconde = Notion('not-cinema-1', 'not-cinema-1', 'fr', domain='cinema', level='2A') objs = [ QuestionChoice( 'ch1', 'hp', 'fr', 'Quel est la deuxieme épreuve de l...
def simple_cinema_qcm():
""" Builds a simple French :epkg:`QCM` about movies. """ cinema_seconde = Notion('not-cinema-1', 'not-cinema-1', 'fr', domain='cinema', level='2A') objs = [ QuestionChoice( 'ch1', 'hp', 'fr', 'Quel est la deuxieme épreuve de la coupe de feu ?', ...
QuestionChoice('ch14', 'apple', 'fr', "Votre père ne comprend pas pourquoi Apple sait qu'il a la grippe.", notion=niveau, answers=["Vous lui demandez comment il le sait.", "Vous lui recommandez de prendre un téléphone avec l'OS de Firefox.",...
234
234
780
7
227
sdpython/mathenjeu
src/mathenjeu/tests/qcms.py
Python
simple_cinema_qcm
simple_cinema_qcm
198
261
198
198
fad3385a1f455dddd3330d93487ea48d71599ecb
bigcode/the-stack
train
e6e7b6af406e3acb65cb36bd
train
function
def readme(): with open('Readme.md') as f: return f.read()
def readme():
with open('Readme.md') as f: return f.read()
from setuptools import setup, find_packages def readme():
12
64
20
4
7
K0IN/pastebin-as-file
setup.py
Python
readme
readme
3
5
3
3
f366e0705255ef06f68491c92967b9be8ee8fff3
bigcode/the-stack
train
afcead794649af7747dba64e
train
function
def move_up (alt): # 1 degree -> 111,111 km # 1m = 0,000009 degree print ("Move Up") gps = vehicle.location.global_relative_frame gps.lon += 0.000009 go_to(gps) detect1 = distance (GPIO_TRIGGER1,GPIO_ECHO1) detect2 = distance (GPIO_TRIGGER2,GPIO_ECHO2) if detect1 == True or detect2 =...
def move_up (alt): # 1 degree -> 111,111 km # 1m = 0,000009 degree
print ("Move Up") gps = vehicle.location.global_relative_frame gps.lon += 0.000009 go_to(gps) detect1 = distance (GPIO_TRIGGER1,GPIO_ECHO1) detect2 = distance (GPIO_TRIGGER2,GPIO_ECHO2) if detect1 == True or detect2 == True : move_down (alt) else : land (alt)
True : move_up(altitude) else : print ("Landing") change_alt (-0.5) altitude -= 0.5 def move_up (alt): # 1 degree -> 111,111 km # 1m = 0,000009 degree
64
64
119
31
32
BasileAmeeuw/DroneDelivreur
Algorithme de vol/main.py
Python
move_up
move_up
95
107
95
97
3deb23da0b80d56c9192466d353e902fc3369beb
bigcode/the-stack
train
22173097fbd41205c940416c
train
function
def arm_and_takeoff(aTargetAltitude): """ Arms vehicle and fly to aTargetAltitude. """ print("Basic pre-arm checks") # Don't try to arm until autopilot is ready while not vehicle.is_armable: print(" Waiting for vehicle to initialise...") time.sleep(1) print("Arming motors")...
def arm_and_takeoff(aTargetAltitude):
""" Arms vehicle and fly to aTargetAltitude. """ print("Basic pre-arm checks") # Don't try to arm until autopilot is ready while not vehicle.is_armable: print(" Waiting for vehicle to initialise...") time.sleep(1) print("Arming motors") # Copter should arm in GUIDED mod...
from dronekit import connect, VehicleMode, LocationGlobalRelative import time import os, re import pyrebase import firebase_admin from firebase_admin import credentials from google.cloud import firestore import board import adafruit_hcsr04 def arm_and_takeoff(aTargetAltitude):
61
76
255
9
51
BasileAmeeuw/DroneDelivreur
Algorithme de vol/main.py
Python
arm_and_takeoff
arm_and_takeoff
11
44
11
11
f786fc5f835c0b5edb499b60cf081f6ad4089b09
bigcode/the-stack
train
ab5c1865bb70de5c3a74f772
train
function
def move_right (alt) : print ("Move Right") gps = vehicle.location.global_relative_frame gps.lat += 0.000009 *2 go_to(gps) detect1 = distance (GPIO_TRIGGER1,GPIO_ECHO1) detect2 = distance (GPIO_TRIGGER2,GPIO_ECHO2) if detect1 == True or detect2 == True : print ("No possibility") ...
def move_right (alt) :
print ("Move Right") gps = vehicle.location.global_relative_frame gps.lat += 0.000009 *2 go_to(gps) detect1 = distance (GPIO_TRIGGER1,GPIO_ECHO1) detect2 = distance (GPIO_TRIGGER2,GPIO_ECHO2) if detect1 == True or detect2 == True : print ("No possibility") else : land (a...
detect1 = distance (GPIO_TRIGGER1,GPIO_ECHO1) detect2 = distance (GPIO_TRIGGER2,GPIO_ECHO2) if detect1 == True or detect2 == True : move_right (alt) else : land (alt) def move_right (alt) :
64
64
97
7
57
BasileAmeeuw/DroneDelivreur
Algorithme de vol/main.py
Python
move_right
move_right
134
144
134
134
982cd2343a8dcec54e5852a66732e0eaefe3942b
bigcode/the-stack
train
13ec7020642f62d16899886e
train
function
def db_connection (config): firebase=pyrebase.initialize_app(firebaseConfig) storage=firebase.storage() try: firebase_admin.get_app() print('firebase intialized.') except ValueError as e: print('firebase not initialized. initialize.') cred = credentials.Certificate("serv...
def db_connection (config):
firebase=pyrebase.initialize_app(firebaseConfig) storage=firebase.storage() try: firebase_admin.get_app() print('firebase intialized.') except ValueError as e: print('firebase not initialized. initialize.') cred = credentials.Certificate("serviceAccountKey.json") ...
time.sleep (0.5) print (str(sonar.distance) + " cm") if sonar.distance <= 20 : return True else : return False def armed_off(): if vehicle.armed : vehicle.armed = False def db_connection (config):
64
64
97
6
57
BasileAmeeuw/DroneDelivreur
Algorithme de vol/main.py
Python
db_connection
db_connection
167
181
167
167
11f63ad60b2916f9cba1e53f5f0991b2cde82e19
bigcode/the-stack
train
6eae49da72de4c6b5355c1f8
train
function
def move_left (alt) : print ("Move Left") gps = vehicle.location.global_relative_frame gps.lon += 0.000009 gps.lat -= 0.000009 go_to(gps) detect1 = distance (GPIO_TRIGGER1,GPIO_ECHO1) detect2 = distance (GPIO_TRIGGER2,GPIO_ECHO2) if detect1 == True or detect2 == True : move_righ...
def move_left (alt) :
print ("Move Left") gps = vehicle.location.global_relative_frame gps.lon += 0.000009 gps.lat -= 0.000009 go_to(gps) detect1 = distance (GPIO_TRIGGER1,GPIO_ECHO1) detect2 = distance (GPIO_TRIGGER2,GPIO_ECHO2) if detect1 == True or detect2 == True : move_right (alt) else : ...
detect1 = distance (GPIO_TRIGGER1,GPIO_ECHO1) detect2 = distance (GPIO_TRIGGER2,GPIO_ECHO2) if detect1 == True or detect2 == True : move_left (alt) else : land (alt) def move_left (alt) :
64
64
105
7
57
BasileAmeeuw/DroneDelivreur
Algorithme de vol/main.py
Python
move_left
move_left
121
132
121
121
4e0f7683dfd525b20b3aeb9a54e6bd0aaa4d02e5
bigcode/the-stack
train
4fea3cf870b5d0cfad86e8df
train
function
def move_down (alt) : print ("Move Down") gps = vehicle.location.global_relative_frame gps.lon -= 0.000009 *2 go_to(gps) detect1 = distance (GPIO_TRIGGER1,GPIO_ECHO1) detect2 = distance (GPIO_TRIGGER2,GPIO_ECHO2) if detect1 == True or detect2 == True : move_left (alt) else : ...
def move_down (alt) :
print ("Move Down") gps = vehicle.location.global_relative_frame gps.lon -= 0.000009 *2 go_to(gps) detect1 = distance (GPIO_TRIGGER1,GPIO_ECHO1) detect2 = distance (GPIO_TRIGGER2,GPIO_ECHO2) if detect1 == True or detect2 == True : move_left (alt) else : land (alt)
detect1 = distance (GPIO_TRIGGER1,GPIO_ECHO1) detect2 = distance (GPIO_TRIGGER2,GPIO_ECHO2) if detect1 == True or detect2 == True : move_down (alt) else : land (alt) def move_down (alt) :
64
64
97
7
57
BasileAmeeuw/DroneDelivreur
Algorithme de vol/main.py
Python
move_down
move_down
109
119
109
109
bf349e60795b42c25f24553274b99bc2c4fc5b63
bigcode/the-stack
train
c35171c7dd491c73469093e0
train
function
def distance(TRIGGER, ECHO): sonar = adafruit_hcsr04.HCSR04(trigger_pin=TRIGGER, echo_pin=ECHO) while sonar.distance == 0 : try: print(sonar.distance) except: print("Retrying!") time.sleep (0.5) print (str(sonar.distance) + " cm") if sonar.d...
def distance(TRIGGER, ECHO):
sonar = adafruit_hcsr04.HCSR04(trigger_pin=TRIGGER, echo_pin=ECHO) while sonar.distance == 0 : try: print(sonar.distance) except: print("Retrying!") time.sleep (0.5) print (str(sonar.distance) + " cm") if sonar.distance <= 20 : retur...
detect1 = distance (GPIO_TRIGGER1,GPIO_ECHO1) detect2 = distance (GPIO_TRIGGER2,GPIO_ECHO2) if detect1 == True or detect2 == True : print ("No possibility") else : land (alt) def distance(TRIGGER, ECHO):
64
64
100
8
56
BasileAmeeuw/DroneDelivreur
Algorithme de vol/main.py
Python
distance
distance
146
161
146
146
6b5315d85e961799a68c11b3ca10df2286a40577
bigcode/the-stack
train
63a7ba2107cf408f4912ac3a
train
function
def land (alt): altitude = alt alt_initial = vehicle.location.global_relative_frame.alt for i in range (1,int((alt+0.5)*2)): detect1 = distance (GPIO_TRIGGER1,GPIO_ECHO1) detect2 = distance (GPIO_TRIGGER2,GPIO_ECHO2) if detect1 == True or detect2 == True : move_up(altitud...
def land (alt):
altitude = alt alt_initial = vehicle.location.global_relative_frame.alt for i in range (1,int((alt+0.5)*2)): detect1 = distance (GPIO_TRIGGER1,GPIO_ECHO1) detect2 = distance (GPIO_TRIGGER2,GPIO_ECHO2) if detect1 == True or detect2 == True : move_up(altitude) else ...
) : print("Target Reached") break time.sleep(3) else: print ("Vehicule is not Armed") def rtl (alt): if vehicle.armed : go_to(alt) else: print ("Vehicule is not Armed") def land (alt):
64
64
111
5
59
BasileAmeeuw/DroneDelivreur
Algorithme de vol/main.py
Python
land
land
82
93
82
82
e33c86ed8830f1313c60cbaf712fda692db503b6
bigcode/the-stack
train
c502095f7c488149078d5b3f
train
function
def go_to (relative_coord): if vehicle.armed : vehicle.simple_goto (relative_coord, groundspeed = 10) while True : print(" Vehicule is at: ", vehicle.location.global_relative_frame) if (vehicle.location.global_relative_frame.lon >= relative_coord.lon - 0.00001 and vehicle.loc...
def go_to (relative_coord):
if vehicle.armed : vehicle.simple_goto (relative_coord, groundspeed = 10) while True : print(" Vehicule is at: ", vehicle.location.global_relative_frame) if (vehicle.location.global_relative_frame.lon >= relative_coord.lon - 0.00001 and vehicle.location.global_relative_frame....
.global_relative_frame.alt >= final_alt - 0.02 and vehicle.location.global_relative_frame.alt <= final_alt + 0.02 : print("Reached target altitude") break time.sleep(1) else: print ("Vehicule is not Armed") def go_to (relative_coord):
64
64
149
7
57
BasileAmeeuw/DroneDelivreur
Algorithme de vol/main.py
Python
go_to
go_to
64
74
64
64
e85ef83147d8ee8c0d8696743c41a4ecc3cdfaa4
bigcode/the-stack
train
ea3a02ecc48e6981dc3a893e
train
function
def armed_off(): if vehicle.armed : vehicle.armed = False
def armed_off():
if vehicle.armed : vehicle.armed = False
try: print(sonar.distance) except: print("Retrying!") time.sleep (0.5) print (str(sonar.distance) + " cm") if sonar.distance <= 20 : return True else : return False def armed_off():
64
64
17
4
59
BasileAmeeuw/DroneDelivreur
Algorithme de vol/main.py
Python
armed_off
armed_off
163
165
163
163
98231c8e487c351533b2fe5d5ed8669dc160654b
bigcode/the-stack
train
312c16e4e46c143efa35d52f
train
function
def rtl (alt): if vehicle.armed : go_to(alt) else: print ("Vehicule is not Armed")
def rtl (alt):
if vehicle.armed : go_to(alt) else: print ("Vehicule is not Armed")
_frame.lat >= relative_coord.lat - 0.00001 and vehicle.location.global_relative_frame.lat <= relative_coord.lat + 0.00001) : print("Target Reached") break time.sleep(3) else: print ("Vehicule is not Armed") def rtl (alt):
64
64
29
5
59
BasileAmeeuw/DroneDelivreur
Algorithme de vol/main.py
Python
rtl
rtl
76
80
76
76
cbca96608f041f6323f9e428f13121ba3cc3b96c
bigcode/the-stack
train
328d5ceef6e474b1bf8b4579
train
function
def change_alt (altitude): print ("Changing Altitude") if vehicle.armed : location = vehicle.location.global_relative_frame final_alt = location.alt + altitude location.alt = final_alt vehicle.simple_goto(location) while True: print(" Altitude: ", vehicle.loca...
def change_alt (altitude):
print ("Changing Altitude") if vehicle.armed : location = vehicle.location.global_relative_frame final_alt = location.alt + altitude location.alt = final_alt vehicle.simple_goto(location) while True: print(" Altitude: ", vehicle.location.global_relative_frame....
Altitude: ", vehicle.location.global_relative_frame.alt) # Break and return from function just below target altitude. if vehicle.location.global_relative_frame.alt >= aTargetAltitude * 0.95: print("Reached target altitude") break time.sleep(3) def change_alt (altitude):
64
64
143
7
57
BasileAmeeuw/DroneDelivreur
Algorithme de vol/main.py
Python
change_alt
change_alt
46
62
46
46
0491c2b611621fa83b09a27b1403e05ad5b38501
bigcode/the-stack
train
596e3779fb9c1defdfcc15ba
train
class
class GATest(): def __init__(self,S=32,P=200,I=50): #problem parameters self.ProblemSize=S #number of cities self.PopulationSize=P self.NumIteration=I self.DistanceMatrix=np.zeros((self.ProblemSize,self.ProblemSize)) #parameters of the algorithm self...
class GATest():
def __init__(self,S=32,P=200,I=50): #problem parameters self.ProblemSize=S #number of cities self.PopulationSize=P self.NumIteration=I self.DistanceMatrix=np.zeros((self.ProblemSize,self.ProblemSize)) #parameters of the algorithm self.KeepRatio=0.05 #...
import matplotlib import numpy as np import random import matplotlib.pyplot as plt import itertools as it import copy class GATest():
30
256
2,423
5
24
Al-Afandi/Adaptive-Gene-Level-Mutation
tsp.py
Python
GATest
GATest
9
227
9
9
6049de72e20d96e107028825868925eff8f2f08a
bigcode/the-stack
train
7d1a53f6ee2fa2ea519a8c87
train
function
def create_model(): model = Sequential() model.add(Dense(12, input_dim=8, activation='relu')) model.add(Dense(8, activation='relu')) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) return model
def create_model():
model = Sequential() model.add(Dense(12, input_dim=8, activation='relu')) model.add(Dense(8, activation='relu')) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) return model
from keras.models import Sequential from keras.layers import Dense from keras.wrappers.scikit_learn import KerasClassifier from sklearn.model_selection import StratifiedKFold from sklearn.model_selection import cross_val_score import numpy # Create the model required for KerasClassifier def create_model():
62
64
69
4
57
andreagrandi/dl-python-book
chapter_9/cross_validation.py
Python
create_model
create_model
10
16
10
10
41b065f72e5e65607dbdba9d305f532175517d18
bigcode/the-stack
train
a01ff6ac0a94b28b056a617c
train
class
class TestStreamTaggerContract(TestCase, TestStreamResultContract): def _make_result(self): return StreamTagger([StreamResult()], add=set(), discard=set())
class TestStreamTaggerContract(TestCase, TestStreamResultContract):
def _make_result(self): return StreamTagger([StreamResult()], add=set(), discard=set())
Case, TestStreamResultContract): def _make_result(self): return ResourcedToStreamDecorator(StreamResult()) class TestStreamSummaryResultContract(TestCase, TestStreamResultContract): def _make_result(self): return StreamSummary() class TestStreamTaggerContract(TestCase, TestStreamResultContra...
64
64
36
14
50
zaneb/testtools
testtools/tests/test_testresult.py
Python
TestStreamTaggerContract
TestStreamTaggerContract
607
610
607
608
c1a20b5e5e29fac873450fac8cd32f1d409edbad
bigcode/the-stack
train
7efc4d293b849e78f5965a5f
train
class
class TestTestResultContract(TestCase, StartTestRunContract): run_test_with = FullStackRunTest def makeResult(self): return TestResult()
class TestTestResultContract(TestCase, StartTestRunContract):
run_test_with = FullStackRunTest def makeResult(self): return TestResult()
_startTestRun_resets_errors(self): result = self.makeResult() result.startTest(self) result.addError(self, an_exc_info) result.stopTest(self) result.startTestRun() self.assertTrue(result.wasSuccessful()) class TestTestResultContract(TestCase, StartTestRunContract):
64
64
34
13
51
zaneb/testtools
testtools/tests/test_testresult.py
Python
TestTestResultContract
TestTestResultContract
414
419
414
415
a0e9ec404ea73fb5d38078310d3b4369c568b2af
bigcode/the-stack
train
5043ba7182f323dca0665c8f
train
class
class Python27Contract(Python26Contract): def test_addExpectedFailure(self): # Calling addExpectedFailure(test, exc_info) completes ok. result = self.makeResult() result.startTest(self) result.addExpectedFailure(self, an_exc_info) def test_addExpectedFailure_is_success(self): ...
class Python27Contract(Python26Contract):
def test_addExpectedFailure(self): # Calling addExpectedFailure(test, exc_info) completes ok. result = self.makeResult() result.startTest(self) result.addExpectedFailure(self, an_exc_info) def test_addExpectedFailure_is_success(self): # addExpectedFailure does not fail t...
_info) result.stopTest(self) self.assertFalse(result.wasSuccessful()) def test_addFailure_is_failure(self): # addFailure fails the test run. result = self.makeResult() result.startTest(self) result.addFailure(self, an_exc_info) result.stopTest(self) s...
133
133
445
9
124
zaneb/testtools
testtools/tests/test_testresult.py
Python
Python27Contract
Python27Contract
187
246
187
188
432f6608837aed5bf7218768fb2e151b2d665eae
bigcode/the-stack
train
f51161ba67537e11bf0f645b
train
class
class TestStreamToDictContract(TestCase, TestStreamResultContract): def _make_result(self): return StreamToDict(lambda x:None)
class TestStreamToDictContract(TestCase, TestStreamResultContract):
def _make_result(self): return StreamToDict(lambda x:None)
Contract): def _make_result(self): return StreamSummary() class TestStreamTaggerContract(TestCase, TestStreamResultContract): def _make_result(self): return StreamTagger([StreamResult()], add=set(), discard=set()) class TestStreamToDictContract(TestCase, TestStreamResultContract):
64
64
31
14
50
zaneb/testtools
testtools/tests/test_testresult.py
Python
TestStreamToDictContract
TestStreamToDictContract
613
616
613
614
94fc92883230ca498ac7d6573022c5a1c412749a
bigcode/the-stack
train
710899012036089cdb49268d
train
class
class DetailsContract(TagsContract): """Tests for the details API of TestResults.""" def test_addExpectedFailure_details(self): # Calling addExpectedFailure(test, details=xxx) completes ok. result = self.makeResult() result.startTest(self) result.addExpectedFailure(self, details...
class DetailsContract(TagsContract):
"""Tests for the details API of TestResults.""" def test_addExpectedFailure_details(self): # Calling addExpectedFailure(test, details=xxx) completes ok. result = self.makeResult() result.startTest(self) result.addExpectedFailure(self, details={}) def test_addError_details(s...
): # Tags removed during tests are restored once that test has finished. result = self.makeResult() result.startTestRun() result.tags(set(['foo']), set()) result.startTest(self) result.tags(set(), set(['foo'])) result.addSuccess(self) result.stopTest(self)...
83
83
278
7
76
zaneb/testtools
testtools/tests/test_testresult.py
Python
DetailsContract
DetailsContract
327
364
327
327
74c9fc64ee184e1a6a44e4ab3e888ce8d838d189
bigcode/the-stack
train
fd81ba3e4475d9058268a7ed
train
class
class TestNonAsciiResultsWithUnittest(TestNonAsciiResults): """Test that running under unittest produces clean ascii strings""" def _run(self, stream, test): from unittest import TextTestRunner as _Runner return _Runner(stream).run(test) def _as_output(self, text): if str_is_unicod...
class TestNonAsciiResultsWithUnittest(TestNonAsciiResults):
"""Test that running under unittest produces clean ascii strings""" def _run(self, stream, test): from unittest import TextTestRunner as _Runner return _Runner(stream).run(test) def _as_output(self, text): if str_is_unicode: return text return text.encode("utf-8...
'\\s*\\^ = 0 # %s\n' + ' ' * self._error_on_character + '\\s*\\^\n' 'SyntaxError:.*') % text), re.M | re.S) ) class TestNonAsciiResultsWithUnittest(TestNonAsciiResults):
64
64
83
13
51
zaneb/testtools
testtools/tests/test_testresult.py
Python
TestNonAsciiResultsWithUnittest
TestNonAsciiResultsWithUnittest
2,766
2,776
2,766
2,766
479ade54ab0b57d0fe4d394eacae3a68620202b3
bigcode/the-stack
train
332925088932a0ce5363fc1c
train
class
class TestCopyStreamResultCopies(TestCase): def setUp(self): super(TestCopyStreamResultCopies, self).setUp() self.target1 = LoggingStreamResult() self.target2 = LoggingStreamResult() self.targets = [self.target1._events, self.target2._events] self.result = CopyStreamResult([...
class TestCopyStreamResultCopies(TestCase):
def setUp(self): super(TestCopyStreamResultCopies, self).setUp() self.target1 = LoggingStreamResult() self.target2 = LoggingStreamResult() self.targets = [self.target1._events, self.target2._events] self.result = CopyStreamResult([self.target1, self.target2]) def test_st...
.now(utc) result.status("foo", "success", test_tags=set(['tag']), runnable=False, route_code='abc', timestamp=now) self.assertEqual( [('startTestRun',), ('status', 'foo', 'success', set(['tag']), False, None, None, False, None, 'abc', now)], result._event...
87
87
290
9
78
zaneb/testtools
testtools/tests/test_testresult.py
Python
TestCopyStreamResultCopies
TestCopyStreamResultCopies
680
709
680
681
9f6424e15ba268fd9f66c5d162d0d4d63fe0c3aa
bigcode/the-stack
train