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
0dea704e03f9fb509c3131f4
train
class
class KnowEventTypeView(wwwutils.DataProfilingMixin, AirflowModelView): pass
class KnowEventTypeView(wwwutils.DataProfilingMixin, AirflowModelView):
pass
_date', 'reported_by', 'description') column_list = ( 'label', 'event_type', 'start_date', 'end_date', 'reported_by') column_default_sort = ("start_date", True) class KnowEventTypeView(wwwutils.DataProfilingMixin, AirflowModelView):
64
64
20
17
47
change/incubator-airflow
airflow/www/views.py
Python
KnowEventTypeView
KnowEventTypeView
2,115
2,116
2,115
2,115
58dcb64486ffcb74248dab3b01b77f4d9b315eee
bigcode/the-stack
train
5a29fd4b936069ea24c5892d
train
class
class ConnectionModelView(wwwutils.SuperUserMixin, AirflowModelView): create_template = 'airflow/conn_create.html' edit_template = 'airflow/conn_edit.html' list_template = 'airflow/conn_list.html' form_columns = ( 'conn_id', 'conn_type', 'host', 'schema', 'login',...
class ConnectionModelView(wwwutils.SuperUserMixin, AirflowModelView):
create_template = 'airflow/conn_create.html' edit_template = 'airflow/conn_edit.html' list_template = 'airflow/conn_list.html' form_columns = ( 'conn_id', 'conn_type', 'host', 'schema', 'login', 'password', 'port', 'extra', 'extra__...
(TI).filter(TI.task_id == task_id, TI.dag_id == dag_id, TI.execution_date == execution_date).delete() session.commit() flash("{count} task instances were deleted".format(**locals())) excep...
212
212
707
15
197
change/incubator-airflow
airflow/www/views.py
Python
ConnectionModelView
ConnectionModelView
2,431
2,518
2,431
2,431
3af082be0554cb162aa9014be56ef7bd1e06bdaa
bigcode/the-stack
train
280cdb4645ec03495b354172
train
function
def dag_link(v, c, m, p): url = url_for( 'airflow.graph', dag_id=m.dag_id) return Markup( '<a href="{url}">{m.dag_id}</a>'.format(**locals()))
def dag_link(v, c, m, p):
url = url_for( 'airflow.graph', dag_id=m.dag_id) return Markup( '<a href="{url}">{m.dag_id}</a>'.format(**locals()))
', 'apikey', 'access_token', ) if conf.getboolean('webserver', 'FILTER_BY_OWNER'): # filter_by_owner if authentication is enabled and filter_by_owner is true FILTER_BY_OWNER = not current_app.config['LOGIN_DISABLED'] def dag_link(v, c, m, p):
64
64
55
11
53
change/incubator-airflow
airflow/www/views.py
Python
dag_link
dag_link
104
109
104
104
45d129b1bb2470eaee5cbb9168c50292c49da867
bigcode/the-stack
train
02e2396190d19b5b62f48c2e
train
function
def pygment_html_render(s, lexer=lexers.TextLexer): return highlight( s, lexer(), HtmlFormatter(linenos=True), )
def pygment_html_render(s, lexer=lexers.TextLexer):
return highlight( s, lexer(), HtmlFormatter(linenos=True), )
def pool_link(v, c, m, p): url = '/admin/taskinstance/?flt1_pool_equals=' + m.pool return Markup("<a href='{url}'>{m.pool}</a>".format(**locals())) def pygment_html_render(s, lexer=lexers.TextLexer):
63
64
34
14
49
change/incubator-airflow
airflow/www/views.py
Python
pygment_html_render
pygment_html_render
186
191
186
186
618fc4026a3dcf39398e9fdd6c9c9bdf122e06f9
bigcode/the-stack
train
8ea28eda59cb93f4d80b6771
train
class
class VersionView(wwwutils.SuperUserMixin, LoggingMixin, BaseView): @expose('/') def version(self): # Look at the version from setup.py try: airflow_version = pkg_resources.require("airflow")[0].version except Exception as e: airflow_version = None sel...
class VersionView(wwwutils.SuperUserMixin, LoggingMixin, BaseView): @expose('/')
def version(self): # Look at the version from setup.py try: airflow_version = pkg_resources.require("airflow")[0].version except Exception as e: airflow_version = None self.logger.error(e) # Get the Git repo and git hash git_version = None...
field.data = value class UserModelView(wwwutils.SuperUserMixin, AirflowModelView): verbose_name = "User" verbose_name_plural = "Users" column_default_sort = 'username' class VersionView(wwwutils.SuperUserMixin, LoggingMixin, BaseView): @expose('/')
64
64
176
20
44
change/incubator-airflow
airflow/www/views.py
Python
VersionView
VersionView
2,527
2,550
2,527
2,528
9fe8f80b87f1bd3c12d549d346fc2d8440211d75
bigcode/the-stack
train
53894fafda9e68b5bdbd92d3
train
function
def worker(c): for i in range(2): # pause = random.random() # print("Sleeping {}".format(pause)) # time.sleep(pause) c.increment() print("Hilo: {} ({})".format(threading.current_thread().getName(), c.value)) print("Hilo: {} (Done)".format(threading.current_thread().getName()))
def worker(c):
for i in range(2): # pause = random.random() # print("Sleeping {}".format(pause)) # time.sleep(pause) c.increment() print("Hilo: {} ({})".format(threading.current_thread().getName(), c.value)) print("Hilo: {} (Done)".format(threading.current_thread().getName()))
lock)".format(threading.current_thread().getName())) self.lock.acquire() try: print("Hilo: {} (Acquired lock)".format(threading.current_thread().getName())) self.value = self.value + 1 finally: self.lock.release() def worker(c):
64
64
83
4
60
win7/ConcurrentParallelProgramming
concurrent/sc_mutex.py
Python
worker
worker
21
28
21
21
50ba0b540d76a0e7b4b0265a9f02155c4ea1d1ad
bigcode/the-stack
train
699eab4c67da5bd2c83432a6
train
class
class Counter: def __init__(self, start=0): self.lock = threading.Lock() self.value = start def increment(self): print("Hilo: {} (Waiting for lock)".format(threading.current_thread().getName())) self.lock.acquire() try: print("Hilo: {} (Acquired lock)".format(threading.current_thread().getName())) s...
class Counter:
def __init__(self, start=0): self.lock = threading.Lock() self.value = start def increment(self): print("Hilo: {} (Waiting for lock)".format(threading.current_thread().getName())) self.lock.acquire() try: print("Hilo: {} (Acquired lock)".format(threading.current_thread().getName())) self.value = self...
import logging import random import threading import time class Counter:
15
64
100
3
11
win7/ConcurrentParallelProgramming
concurrent/sc_mutex.py
Python
Counter
Counter
6
19
6
7
38a34436b89f9e50507195921e579dc25f8a58b9
bigcode/the-stack
train
873d0ab61c14415f9fcef24b
train
function
async def _stream_logs(creator_name, execution_id, since, timeout, logger, client): if not hasattr(client.auditlog, 'stream'): raise CloudifyCliError('Streaming requires Python>=3.6.') logg...
async def _stream_logs(creator_name, execution_id, since, timeout, logger, client):
if not hasattr(client.auditlog, 'stream'): raise CloudifyCliError('Streaming requires Python>=3.6.') logger.info('Streaming audit log entries...') response = await client.auditlog.stream(timeout=timeout, creator_name=creator_name, ...
loop = asyncio.get_event_loop() loop.run_until_complete(_stream_logs(creator_name, execution_id, since, timeout, logger, ...
64
64
139
25
39
tirkarthi/cloudify-cli
cloudify_cli/async_commands/audit_log.py
Python
_stream_logs
_stream_logs
24
42
24
29
9a2970ddd624af3b80a0d64ba24b617571d30b29
bigcode/the-stack
train
ae68597512cd5cacd3d0f7d6
train
function
def _streamed_audit_log(data): line = data.strip().decode(errors='ignore') if line: yield json.loads(line)
def _streamed_audit_log(data):
line = data.strip().decode(errors='ignore') if line: yield json.loads(line)
_id, since=since) async for data in response.content: for audit_log in _streamed_audit_log(data): if get_global_json_output(): print(audit_log) else: print(_format_audit_log(audit_log)) def _streamed_audit_lo...
64
64
30
9
55
tirkarthi/cloudify-cli
cloudify_cli/async_commands/audit_log.py
Python
_streamed_audit_log
_streamed_audit_log
45
48
45
45
7f201a177ef60d09ddc8c45652cce9c02f4d75b4
bigcode/the-stack
train
c0417730ceb6c81802ec3da2
train
function
def _format_audit_log(data): result = f"[{data['created_at']}]" if 'creator_name' in data and data['creator_name']: result = f"{result} user {data['creator_name']}" if 'execution_id' in data and data['execution_id']: result = f"{result} execution {data['execution_id']}" result = f"{resul...
def _format_audit_log(data):
result = f"[{data['created_at']}]" if 'creator_name' in data and data['creator_name']: result = f"{result} user {data['creator_name']}" if 'execution_id' in data and data['execution_id']: result = f"{result} execution {data['execution_id']}" result = f"{result} {data['operation'].upper()...
if get_global_json_output(): print(audit_log) else: print(_format_audit_log(audit_log)) def _streamed_audit_log(data): line = data.strip().decode(errors='ignore') if line: yield json.loads(line) def _format_audit_log(data):
64
64
119
8
56
tirkarthi/cloudify-cli
cloudify_cli/async_commands/audit_log.py
Python
_format_audit_log
_format_audit_log
51
59
51
51
329479501688570c9298f1b7c4a553cdb2d7171c
bigcode/the-stack
train
5b2542052f6cc9be072f958d
train
function
def stream_logs(creator_name, execution_id, since, timeout, logger, client): loop = asyncio.get_event_loop() loop.run_until_complete(_stream_logs(creator_name, execution_id, ...
def stream_logs(creator_name, execution_id, since, timeout, logger, client):
loop = asyncio.get_event_loop() loop.run_until_complete(_stream_logs(creator_name, execution_id, since, timeout, logger, ...
import asyncio import json from ..exceptions import CloudifyCliError from ..logger import get_global_json_output def stream_logs(creator_name, execution_id, since, timeout, logger, client):
47
64
63
23
23
tirkarthi/cloudify-cli
cloudify_cli/async_commands/audit_log.py
Python
stream_logs
stream_logs
8
21
8
13
48757f863f3a0ebcc7a60d4c06bec25c2bfec9fc
bigcode/the-stack
train
45ffa7237f5a6ce472e29f17
train
class
class GeneticSolution: ''' Identify the solution for the sudoku problem where some of the values are not provided in the 9x9 sudoku matrix using Genetic Algorithm ''' def __init__(self, number_of_missing_values ,sample_size): ''' number_of_missing_values : number of value...
class GeneticSolution:
''' Identify the solution for the sudoku problem where some of the values are not provided in the 9x9 sudoku matrix using Genetic Algorithm ''' def __init__(self, number_of_missing_values ,sample_size): ''' number_of_missing_values : number of values missing in the proble...
''' Solve sudoku using Genetic Algorithm ''' import random import numpy as np from generator import Generator GENERATOR = Generator() class GeneticSolution:
31
256
1,432
4
27
anandpathak/sudoku-solve
ga_solve_sudoku.py
Python
GeneticSolution
GeneticSolution
9
148
9
9
123583ec6df93e9b11b21303a259fe3307fb4282
bigcode/the-stack
train
9d64b641a36b2d3db3cd69a9
train
class
class GaussianProcess(RandomProcess): def __init__(self, size, std): self.size = size self.std = std def sample(self): return np.random.randn(*self.size) * self.std()
class GaussianProcess(RandomProcess):
def __init__(self, size, std): self.size = size self.std = std def sample(self): return np.random.randn(*self.size) * self.std()
tong Zhang(zhangshangtong.cpp@gmail.com) # # Permission given to modify the code as long as you keep this # # declaration at the top # ####################################################################### import numpy as np class RandomProcess(object): def...
64
64
47
6
57
kw90/drlnd_continuous-control
random_process.py
Python
GaussianProcess
GaussianProcess
15
21
15
15
9ce2435cf7145023c5432cbdc25c8aa87d820df0
bigcode/the-stack
train
ddc98fa1dc576d8056b7f832
train
class
class OrnsteinUhlenbeckProcess(RandomProcess): def __init__(self, size, std, theta=.15, dt=1e-2, x0=None): self.theta = theta self.mu = 0 self.std = std self.dt = dt self.x0 = x0 self.size = size self.reset_states() def sample(self): x = self.x_pr...
class OrnsteinUhlenbeckProcess(RandomProcess):
def __init__(self, size, std, theta=.15, dt=1e-2, x0=None): self.theta = theta self.mu = 0 self.std = std self.dt = dt self.x0 = x0 self.size = size self.reset_states() def sample(self): x = self.x_prev + self.theta * (self.mu - self.x_prev) * sel...
reset_states(self): pass class GaussianProcess(RandomProcess): def __init__(self, size, std): self.size = size self.std = std def sample(self): return np.random.randn(*self.size) * self.std() class OrnsteinUhlenbeckProcess(RandomProcess):
64
64
164
10
54
kw90/drlnd_continuous-control
random_process.py
Python
OrnsteinUhlenbeckProcess
OrnsteinUhlenbeckProcess
24
41
24
24
cf58e7cafd23c870950c5eafccb73a979f263b59
bigcode/the-stack
train
672d8e4edfb4c75e0971356f
train
class
class RandomProcess(object): def reset_states(self): pass
class RandomProcess(object):
def reset_states(self): pass
####################################################################### # Copyright (C) 2017 Shangtong Zhang(zhangshangtong.cpp@gmail.com) # # Permission given to modify the code as long as you keep this # # declaration at the top # ################################...
61
64
14
5
55
kw90/drlnd_continuous-control
random_process.py
Python
RandomProcess
RandomProcess
10
12
10
10
f28d8b9cf7709e0bf9570e18fc8b1861125f2c00
bigcode/the-stack
train
ab26c68d74fc285d8baa0e89
train
class
@DETECTORS.register_module() class QueryInst(TwoStageDetector): r"""Implementation of `QueryInst: Parallelly Supervised Mask Query for Instance Segmentation <https://arxiv.org/abs/2105.01928>`, based on SparseRCNN detector. """ def __init__(self, *args, **kwargs): super(QueryInst, self)....
@DETECTORS.register_module() class QueryInst(TwoStageDetector):
r"""Implementation of `QueryInst: Parallelly Supervised Mask Query for Instance Segmentation <https://arxiv.org/abs/2105.01928>`, based on SparseRCNN detector. """ def __init__(self, *args, **kwargs): super(QueryInst, self).__init__(*args, **kwargs) assert self.with_rpn, 'QueryIn...
from ..builder import DETECTORS from .two_stage import TwoStageDetector @DETECTORS.register_module() class QueryInst(TwoStageDetector):
32
256
1,047
15
16
ruiningTang/mmdetection
mmdet/models/detectors/queryinst.py
Python
QueryInst
QueryInst
5
124
5
6
c28aa1c69d4cddab71347e1f5a2d274c1c9c793c
bigcode/the-stack
train
3a4914cc6063cd55adbcf8a6
train
class
class Manhole(recvline.HistoricRecvLine): """ Mediator between a fancy line source and an interactive interpreter. This accepts lines from its transport and passes them on to a L{ManholeInterpreter}. Control commands (^C, ^D, ^\) are also handled with something approximating their normal terminal-...
class Manhole(recvline.HistoricRecvLine):
""" Mediator between a fancy line source and an interactive interpreter. This accepts lines from its transport and passes them on to a L{ManholeInterpreter}. Control commands (^C, ^D, ^\) are also handled with something approximating their normal terminal-mode behavior. It can optionally be c...
obj is not None: self.write(repr(obj)) def _cbDisplayDeferred(self, result, k, obj): self.write("Deferred #%d called back: %r" % (k, result), True) del self._pendingDeferreds[id(obj)] return result def _ebDisplayDeferred(self, failure, k, obj): self.write("Deferr...
197
198
662
12
185
lmsugar/ip_test
Lib/site-packages/twisted/conch/manhole.py
Python
Manhole
Manhole
168
266
168
168
e998428767cbb465200c57493ecc0fd7e5462eb5
bigcode/the-stack
train
feac6de1c0cc28801d390cea
train
function
def lastColorizedLine(source): """ Tokenize and colorize the given Python source. Returns a VT102-format colorized version of the last line of C{source}. @param source: Python source code @type source: L{str} or L{bytes} @return: L{bytes} of colorized source """ if not isinstance(sourc...
def lastColorizedLine(source):
""" Tokenize and colorize the given Python source. Returns a VT102-format colorized version of the last line of C{source}. @param source: Python source code @type source: L{str} or L{bytes} @return: L{bytes} of colorized source """ if not isinstance(source, bytes): source = sou...
) def __bytes__(self): s = b''.join(self.written) return s.strip(b'\n').splitlines()[-1] if bytes == str: # Compat with Python 2.7 __str__ = __bytes__ def lastColorizedLine(source):
63
64
164
7
56
lmsugar/ip_test
Lib/site-packages/twisted/conch/manhole.py
Python
lastColorizedLine
lastColorizedLine
319
339
319
319
fe30b23d4a2c2c6bb920fe63984b50f6b6e20de6
bigcode/the-stack
train
6cda1b07b43dd24c54cf46ef
train
class
class ManholeInterpreter(code.InteractiveInterpreter): """ Interactive Interpreter with special output and Deferred support. Aside from the features provided by L{code.InteractiveInterpreter}, this class captures sys.stdout output and redirects it to the appropriate location (the Manhole protocol i...
class ManholeInterpreter(code.InteractiveInterpreter):
""" Interactive Interpreter with special output and Deferred support. Aside from the features provided by L{code.InteractiveInterpreter}, this class captures sys.stdout output and redirects it to the appropriate location (the Manhole protocol instance). It also treats Deferreds which reach the...
c) Twisted Matrix Laboratories. # See LICENSE for details. """ Line-input oriented interactive interpreter loop. Provides classes for handling Python source input and arbitrary output interactively from a Twisted application. Also included is syntax coloring code with support for VT102 terminals, control code handli...
255
256
859
9
246
lmsugar/ip_test
Lib/site-packages/twisted/conch/manhole.py
Python
ManholeInterpreter
ManholeInterpreter
53
155
53
53
359e426893a919b47e4c4ac88baafd4f656e7a3a
bigcode/the-stack
train
9463cb7245d6d5ff31a30448
train
class
class FileWrapper: """ Minimal write-file-like object. Writes are translated into addOutput calls on an object passed to __init__. Newlines are also converted from network to local style. """ softspace = 0 state = 'normal' def __init__(self, o): self.o = o def flush(sel...
class FileWrapper:
""" Minimal write-file-like object. Writes are translated into addOutput calls on an object passed to __init__. Newlines are also converted from network to local style. """ softspace = 0 state = 'normal' def __init__(self, o): self.o = o def flush(self): pass ...
and reasonable handling of Deferreds. @author: Jp Calderone """ import code, sys, tokenize from io import BytesIO from twisted.conch import recvline from twisted.internet import defer from twisted.python.compat import _tokenize from twisted.python.htmlizer import TokenPrinter class FileWrapper:
64
64
119
4
59
lmsugar/ip_test
Lib/site-packages/twisted/conch/manhole.py
Python
FileWrapper
FileWrapper
25
49
25
25
27022b59c3ef929fdb71f35a3044c1ac413e5a86
bigcode/the-stack
train
97580969ac15285ac7a7ba63
train
class
class ColoredManhole(Manhole): """ A REPL which syntax colors input as users type it. """ def getSource(self): """ Return a string containing the currently entered source. This is only the code which will be considered for execution next. """ return (b'\...
class ColoredManhole(Manhole):
""" A REPL which syntax colors input as users type it. """ def getSource(self): """ Return a string containing the currently entered source. This is only the code which will be considered for execution next. """ return (b'\n'.join(self.interpreter.buffer...
L{bytes} @return: L{bytes} of colorized source """ if not isinstance(source, bytes): source = source.encode("utf-8") w = VT102Writer() p = TokenPrinter(w.write).printtoken s = BytesIO(source) for token in _tokenize(s.readline): (tokenType, string, start, end, line) = token ...
114
114
380
8
106
lmsugar/ip_test
Lib/site-packages/twisted/conch/manhole.py
Python
ColoredManhole
ColoredManhole
343
396
343
343
ce4e88a7d4a9ee52b72eafa31ad317c4af6f7f85
bigcode/the-stack
train
086655eb5d1081baa02d7c5e
train
class
class VT102Writer: """ Colorizer for Python tokens. A series of tokens are written to instances of this object. Each is colored in a particular way. The final line of the result of this is generally added to the output. """ typeToColor = { 'identifier': b'\x1b[31m', 'keyw...
class VT102Writer:
""" Colorizer for Python tokens. A series of tokens are written to instances of this object. Each is colored in a particular way. The final line of the result of this is generally added to the output. """ typeToColor = { 'identifier': b'\x1b[31m', 'keyword': b'\x1b[32m', ...
]) if self.lineBuffer: oldBuffer = self.lineBuffer self.lineBuffer = [] self.lineBufferIndex = 0 self._deliverBuffer(oldBuffer) def lineReceived(self, line): more = self.interpreter.push(line) self.pn = bool(more) ...
95
96
321
5
90
lmsugar/ip_test
Lib/site-packages/twisted/conch/manhole.py
Python
VT102Writer
VT102Writer
270
315
270
270
c94cee04f368d6a7f2a30c96233c2ee2c4bbc309
bigcode/the-stack
train
b726dc2c413f0eb5b135ca77
train
class
class downloadPython37: IDEName = 'Python 3.7.6' directoryName = 'Python376' def download32bit(self): url32bit = 'https://www.python.org/ftp/python/3.7.6/python-3.7.6-embed-win32.zip' Downloader(self.directoryName,self.IDEName,url32bit) def download64bit(self): url64bit = 'https...
class downloadPython37:
IDEName = 'Python 3.7.6' directoryName = 'Python376' def download32bit(self): url32bit = 'https://www.python.org/ftp/python/3.7.6/python-3.7.6-embed-win32.zip' Downloader(self.directoryName,self.IDEName,url32bit) def download64bit(self): url64bit = 'https://www.python.org/ftp/py...
from bs4 import BeautifulSoup from urllib.request import urlopen import zipfile from io import BytesIO import subprocess import requests import platform import os import time from Downloader import Downloader #This module directory dirNow = os.getcwd() class downloadPython37:
60
64
133
5
55
J-hoplin1/IDE-Auto-Downloader
IDEDownloaderModuleSpecificCode/Python37Downloader.py
Python
downloadPython37
downloadPython37
15
24
15
15
00b0d716bdd6fe5a4179ad2a9b923ef7b5f9b9f8
bigcode/the-stack
train
4d8c7be48ad7d37a19be45ca
train
function
def solution(ar): c_endpoints = [] for c, r in enumerate(ar): c_endpoints += [(c-r, True), (c+r, False)] # print(c_endpoints) c_endpoints.sort(key=lambda x: (x[0], not x[1])) # print(c_endpoints) i, active_circle = 0, 0 for _, is_begining in c_endpoints: if is_begining: ...
def solution(ar):
c_endpoints = [] for c, r in enumerate(ar): c_endpoints += [(c-r, True), (c+r, False)] # print(c_endpoints) c_endpoints.sort(key=lambda x: (x[0], not x[1])) # print(c_endpoints) i, active_circle = 0, 0 for _, is_begining in c_endpoints: if is_begining: i += act...
def solution(ar):
4
64
139
4
0
Jagrmi-C/jagrmitest
codility.com/sorting/number_of_disc_intersections_test.py
Python
solution
solution
1
20
1
1
85463e332ad204cba8ff0adf8ce9dab7e02c3f77
bigcode/the-stack
train
1e047dd61b423ae38e0a2104
train
class
class Project(models.Model): name = models.CharField(max_length=128) billable = models.BooleanField(default=True) active = models.BooleanField(default=True) created_at = models.DateField(auto_now_add=True) def __str__(self): return self.name class Meta: ordering = ["name"] ...
class Project(models.Model):
name = models.CharField(max_length=128) billable = models.BooleanField(default=True) active = models.BooleanField(default=True) created_at = models.DateField(auto_now_add=True) def __str__(self): return self.name class Meta: ordering = ["name"] verbose_name_plural = "pr...
.validators import MinValueValidator from django.db import models from rest_framework import serializers def validate_duration(value): if value % 15 != 0: raise serializers.ValidationError('only even quarters allowed, for example: 15, 45, 180, 105') class Project(models.Model):
64
64
185
5
59
madr/cautious-octo-succotash
tajm/core/models.py
Python
Project
Project
14
40
14
14
ea871ca3b8c1aa017e45b118bce5c39aa744dcec
bigcode/the-stack
train
fc69aff2f95cb73e02323390
train
class
class Progress(models.Model): user = models.ForeignKey(TajmUser) duration = models.IntegerField(default=15, validators=[MinValueValidator(15), validate_duration]) note = models.TextField() done_at = models.DateField(default=datetime.date.today) created_at = models.DateField(auto_now_add=True) st...
class Progress(models.Model):
user = models.ForeignKey(TajmUser) duration = models.IntegerField(default=15, validators=[MinValueValidator(15), validate_duration]) note = models.TextField() done_at = models.DateField(default=datetime.date.today) created_at = models.DateField(auto_now_add=True) started_at = models.TimeField(de...
] = [0, progress.user] users[progress.user_id][0] += int(progress.duration) most_active_users = sorted(users.items(), key=lambda x: int(x[1][0]), reverse=True) return [mau for id, mau in most_active_users] class Progress(models.Model):
64
64
143
5
59
madr/cautious-octo-succotash
tajm/core/models.py
Python
Progress
Progress
106
124
106
106
89f5e581fb9082ebedbfb67aeca421bc3b3daa84
bigcode/the-stack
train
91bd70aac7eb58fb317a4206
train
class
class Deadline(models.Model): projects = models.ManyToManyField(Project) label = models.CharField(max_length=128) starts_at = models.DateField(null=True, blank=True) ends_at = models.DateField(null=True, blank=True) hour_amount = models.IntegerField(null=True, blank=True, validators=[MinValueValidat...
class Deadline(models.Model):
projects = models.ManyToManyField(Project) label = models.CharField(max_length=128) starts_at = models.DateField(null=True, blank=True) ends_at = models.DateField(null=True, blank=True) hour_amount = models.IntegerField(null=True, blank=True, validators=[MinValueValidator(1)]) class Meta: ...
[progress.user_id][0] += int(progress.duration) most_active_users = sorted(users.items(), key=lambda x: int(x[1][0]), reverse=True) return [mau for id, mau in most_active_users] class TajmUser(User): class Meta: proxy = True def project_set(self): projects = list(set([p.proj...
111
111
372
5
105
madr/cautious-octo-succotash
tajm/core/models.py
Python
Deadline
Deadline
53
103
53
53
a81cd4e17b651ea97a93a109462a7011e82f67ed
bigcode/the-stack
train
98393f834967b3334d3acdd6
train
class
class TajmUser(User): class Meta: proxy = True def project_set(self): projects = list(set([p.project_id for p in self.progress_set.all()])) project_set = Project.objects.filter(pk__in=projects) return project_set
class TajmUser(User):
class Meta: proxy = True def project_set(self): projects = list(set([p.project_id for p in self.progress_set.all()])) project_set = Project.objects.filter(pk__in=projects) return project_set
= [0, progress.user] users[progress.user_id][0] += int(progress.duration) most_active_users = sorted(users.items(), key=lambda x: int(x[1][0]), reverse=True) return [mau for id, mau in most_active_users] class TajmUser(User):
64
64
57
6
58
madr/cautious-octo-succotash
tajm/core/models.py
Python
TajmUser
TajmUser
43
50
43
43
b889c895403d6bc9fe66ff241aaadc34856e43e9
bigcode/the-stack
train
5a2117ff3e36fa735f52b922
train
class
class Absence(models.Model): user = models.ForeignKey(TajmUser) duration = models.IntegerField(default=480, validators=[MinValueValidator(15), validate_duration]) note = models.TextField(default='', blank=True) done_at = models.DateField(default=datetime.date.today) started_at = models.TimeField(def...
class Absence(models.Model):
user = models.ForeignKey(TajmUser) duration = models.IntegerField(default=480, validators=[MinValueValidator(15), validate_duration]) note = models.TextField(default='', blank=True) done_at = models.DateField(default=datetime.date.today) started_at = models.TimeField(default='00:00:00') created_...
active = models.BooleanField(default=True) created_at = models.DateField(auto_now_add=True) def __str__(self): return self.name class Meta: ordering = ["name"] class JSONAPIMeta: resource_name = "absence_categories" class Absence(models.Model):
64
64
148
6
58
madr/cautious-octo-succotash
tajm/core/models.py
Python
Absence
Absence
142
160
142
142
d56463918732ac2a73b487e8af9e84e6940d4891
bigcode/the-stack
train
746ff8eac8d19eb8d09bece9
train
function
def validate_duration(value): if value % 15 != 0: raise serializers.ValidationError('only even quarters allowed, for example: 15, 45, 180, 105')
def validate_duration(value):
if value % 15 != 0: raise serializers.ValidationError('only even quarters allowed, for example: 15, 45, 180, 105')
import datetime from django.contrib.auth.models import User from django.core.validators import MinValueValidator from django.db import models from rest_framework import serializers def validate_duration(value):
37
64
41
5
31
madr/cautious-octo-succotash
tajm/core/models.py
Python
validate_duration
validate_duration
9
11
9
9
ecb8cf5b2e7fbe59ef40a865e32e4c21a986062d
bigcode/the-stack
train
1298b33491f259c54a3d28b6
train
class
class AbsenceCategory(models.Model): name = models.CharField(max_length=128) active = models.BooleanField(default=True) created_at = models.DateField(auto_now_add=True) def __str__(self): return self.name class Meta: ordering = ["name"] class JSONAPIMeta: resource_name...
class AbsenceCategory(models.Model):
name = models.CharField(max_length=128) active = models.BooleanField(default=True) created_at = models.DateField(auto_now_add=True) def __str__(self): return self.name class Meta: ordering = ["name"] class JSONAPIMeta: resource_name = "absence_categories"
models.ForeignKey(Project) def __str__(self): return self.note class Meta: ordering = ["-done_at", 'created_at'] verbose_name_plural = "progresses" class JSONAPIMeta: resource_name = "progresses" class AbsenceCategory(models.Model):
64
64
76
7
57
madr/cautious-octo-succotash
tajm/core/models.py
Python
AbsenceCategory
AbsenceCategory
127
139
127
127
af8d62ca68fe638a23d5f0585d7c34ac37fc4b5a
bigcode/the-stack
train
93840036c25ed326fa3b54a8
train
class
class AmplitudesDataset(Dataset): def __init__(self, detectors=DETECTORS): self.detectors = detectors self.origin_amplitudes = self._get_amplitudes() self.scaler = MinMaxScaler() self.amplitudes = self.scaler.fit_transform(self.origin_amplitudes) def _get_amplitudes(self): ...
class AmplitudesDataset(Dataset):
def __init__(self, detectors=DETECTORS): self.detectors = detectors self.origin_amplitudes = self._get_amplitudes() self.scaler = MinMaxScaler() self.amplitudes = self.scaler.fit_transform(self.origin_amplitudes) def _get_amplitudes(self): signals = [get_detector_trainin...
import numpy as np import torch from torch.utils.data import Dataset from sklearn.preprocessing import MinMaxScaler from generation.config import SIGNAL_DIM, DETECTORS from generation.dataset.data_utils import get_detector_training_data class AmplitudesDataset(Dataset):
53
64
178
8
44
whiteRa2bit/hep_generative_models
generation/dataset/amplitudes_dataset.py
Python
AmplitudesDataset
AmplitudesDataset
10
28
10
10
4f58e56b35dfc29a45a8fdec5a8c1af39986527c
bigcode/the-stack
train
68d93ddb18143f4b500ac138
train
function
def handle_plugins(config, plugins, staged): successful = True for name, plugin in plugins.items(): try: result = plugin['pre-commit'](config, staged) status = mothermayi.colors.green("PASSED") except mothermayi.errors.FailHook as e: result = str(e) ...
def handle_plugins(config, plugins, staged):
successful = True for name, plugin in plugins.items(): try: result = plugin['pre-commit'](config, staged) status = mothermayi.colors.green("PASSED") except mothermayi.errors.FailHook as e: result = str(e) status = mothermayi.colors.red("FAILED") ...
import logging import mothermayi.entryway import mothermayi.errors import mothermayi.git import mothermayi.colors LOGGER = logging.getLogger(__name__) def handle_plugins(config, plugins, staged):
45
64
121
9
36
EliRibble/mothermayi
mothermayi/pre_commit.py
Python
handle_plugins
handle_plugins
9
23
9
9
03ec8ae701fb3c8050ba786790fad5e8992fce8b
bigcode/the-stack
train
baf6275acb207b33ed05b8b8
train
function
def run(config): with mothermayi.git.stash(): staged = mothermayi.git.get_staged() if not staged: return plugins = mothermayi.entryway.get_plugins('pre-commit') if not handle_plugins(config, plugins, staged): return 1 return 0
def run(config):
with mothermayi.git.stash(): staged = mothermayi.git.get_staged() if not staged: return plugins = mothermayi.entryway.get_plugins('pre-commit') if not handle_plugins(config, plugins, staged): return 1 return 0
e: result = str(e) status = mothermayi.colors.red("FAILED") successful = False message = "{0:<10}...[{1:<7}]".format(name, status) print(message) if result: print(result) return successful def run(config):
64
64
68
4
59
EliRibble/mothermayi
mothermayi/pre_commit.py
Python
run
run
25
33
25
25
3cf68a6eb3dbcced3c4950c568ae7f37bd1a62f4
bigcode/the-stack
train
48d8630e6cb79ae9ba36e948
train
function
def draw(canvas, cw, ch): for drawCommand in drawList: if len(drawCommand) == 6: (x0, y0, x1, y1, color, shape) = drawCommand else: (color, shape) = drawCommand (x0, y0, x1, y1) = getRandomSquareCoordinates(canvasWidth, canvasHeight) if shape == "re...
def draw(canvas, cw, ch):
for drawCommand in drawList: if len(drawCommand) == 6: (x0, y0, x1, y1, color, shape) = drawCommand else: (color, shape) = drawCommand (x0, y0, x1, y1) = getRandomSquareCoordinates(canvasWidth, canvasHeight) if shape == "rectangle": canv...
fum".split() becomes ["fee", "fi", "fo", "fum"] drawCommandList = drawCommand.split() (color, shape) = (drawCommandList[0], drawCommandList[1]) drawList.append((color, shape)) def draw(canvas, cw, ch):
63
64
151
8
55
google/teknowledge
curriculum/05_lists_02_generated_art_2_DAYS/05_lists_03_generated_art_day_2/05_03_03_generated_art.py
Python
draw
draw
36
48
36
36
fb4f8a2dee264a8ca1572d32f561b1cb0dad72ab
bigcode/the-stack
train
20d300f576e746a4c11e6e39
train
function
def processDrawCommand(drawCommand): # the .split() function turns a string of words (with spaces in between) # into a list of words of separate elements. # example: "fee fi fo fum".split() becomes ["fee", "fi", "fo", "fum"] drawCommandList = drawCommand.split() (color, shape) = (drawCommandLis...
def processDrawCommand(drawCommand): # the .split() function turns a string of words (with spaces in between) # into a list of words of separate elements. # example: "fee fi fo fum".split() becomes ["fee", "fi", "fo", "fum"]
drawCommandList = drawCommand.split() (color, shape) = (drawCommandList[0], drawCommandList[1]) drawList.append((color, shape))
runDrawing() def processDrawCommand(drawCommand): # the .split() function turns a string of words (with spaces in between) # into a list of words of separate elements. # example: "fee fi fo fum".split() becomes ["fee", "fi", "fo", "fum"]
64
64
99
61
3
google/teknowledge
curriculum/05_lists_02_generated_art_2_DAYS/05_lists_03_generated_art_day_2/05_03_03_generated_art.py
Python
processDrawCommand
processDrawCommand
27
33
27
30
a4bf6dd70f71faf2b13ef14a951065f2509534a4
bigcode/the-stack
train
bafaa5daa22433ff7595b880
train
function
def runDrawing(width=canvasWidth, height=canvasHeight): root = Tk() canvas = Canvas(root, width=width, height=height, highlightthickness=0) canvas.pack() draw(canvas, width, height) root.mainloop()
def runDrawing(width=canvasWidth, height=canvasHeight):
root = Tk() canvas = Canvas(root, width=width, height=height, highlightthickness=0) canvas.pack() draw(canvas, width, height) root.mainloop()
squareWidth) y0 = randint(0, ch - squareWidth) x1 = x0 + squareWidth y1 = y0 + squareWidth return (x0, y0, x1, y1) def runDrawing(width=canvasWidth, height=canvasHeight):
64
64
54
13
51
google/teknowledge
curriculum/05_lists_02_generated_art_2_DAYS/05_lists_03_generated_art_day_2/05_03_03_generated_art.py
Python
runDrawing
runDrawing
60
65
60
60
de8b00cf1f3a3e44f3d769b539f9dc9a00db624c
bigcode/the-stack
train
efae1fe95ab02c9f8028ee00
train
function
def makeIterativeArt(): while (True): print('What would you like to add to the drawing?') print('(examples: "red rectangle", "blue oval")') print('type "ready" when you are ready to view your creation.') drawCommand = input("> ") if (drawCommand == "ready"): ...
def makeIterativeArt():
while (True): print('What would you like to add to the drawing?') print('(examples: "red rectangle", "blue oval")') print('type "ready" when you are ready to view your creation.') drawCommand = input("> ") if (drawCommand == "ready"): break proc...
from random import randint from tkinter import * # add any shapes here that you wish to be part of the drawing from the start drawList = [] canvasWidth = 200 canvasHeight = 200 def makeIterativeArt():
51
64
102
6
44
google/teknowledge
curriculum/05_lists_02_generated_art_2_DAYS/05_lists_03_generated_art_day_2/05_03_03_generated_art.py
Python
makeIterativeArt
makeIterativeArt
11
24
11
11
d14f193693382e02044ebca95d3bb3ec00a7da13
bigcode/the-stack
train
a12d994fe2514e439f42a8ff
train
function
def getRandomSquareCoordinates(cw, ch): squareWidth = 10 x0 = randint(0, cw - squareWidth) y0 = randint(0, ch - squareWidth) x1 = x0 + squareWidth y1 = y0 + squareWidth return (x0, y0, x1, y1)
def getRandomSquareCoordinates(cw, ch):
squareWidth = 10 x0 = randint(0, cw - squareWidth) y0 = randint(0, ch - squareWidth) x1 = x0 + squareWidth y1 = y0 + squareWidth return (x0, y0, x1, y1)
(x0, y0, x1, y1, fill=color) elif shape == "oval": canvas.create_oval(x0, y0, x1, y1, fill=color) else: print("Couldn't draw:", drawCommand) def getRandomSquareCoordinates(cw, ch):
64
64
78
10
54
google/teknowledge
curriculum/05_lists_02_generated_art_2_DAYS/05_lists_03_generated_art_day_2/05_03_03_generated_art.py
Python
getRandomSquareCoordinates
getRandomSquareCoordinates
51
57
51
51
c608b79d16c15b6222fabe2451013c93e71cadfb
bigcode/the-stack
train
4c405e36bc7656a23adfa89d
train
class
class OSNet(nn.Module): """Omni-Scale Network. Reference: - Zhou et al. Omni-Scale Feature Learning for Person Re-Identification. ICCV, 2019. - Zhou et al. Learning Generalisable Omni-Scale Representations for Person Re-Identification. arXiv preprint, 2019. """ def __init...
class OSNet(nn.Module):
"""Omni-Scale Network. Reference: - Zhou et al. Omni-Scale Feature Learning for Person Re-Identification. ICCV, 2019. - Zhou et al. Learning Generalisable Omni-Scale Representations for Person Re-Identification. arXiv preprint, 2019. """ def __init__( self, ...
Conv1x1(in_channels, mid_channels) self.conv2 = nn.ModuleList() for t in range(1, T + 1): self.conv2 += [LightConvStream(mid_channels, mid_channels, t)] self.gate = ChannelGate(mid_channels) self.conv3 = Conv1x1Linear(mid_channels, out_channels, bn=False) self.downsa...
256
256
1,111
6
250
12-malak/Pose-Estimation
trackers/ReidModels/osnet_ain.py
Python
OSNet
OSNet
300
439
300
300
9ee2e6a60d7b80b488be89ff2078c71356d9f075
bigcode/the-stack
train
790f83179660c97d94bce5b7
train
function
def init_pretrained_weights(model, key=''): """Initializes model with pretrained weights. Layers that don't match with pretrained layers in name or size are kept unchanged. """ import os import errno import gdown from collections import OrderedDict def _get_torch_home(): EN...
def init_pretrained_weights(model, key=''):
"""Initializes model with pretrained weights. Layers that don't match with pretrained layers in name or size are kept unchanged. """ import os import errno import gdown from collections import OrderedDict def _get_torch_home(): ENV_TORCH_HOME = 'TORCH_HOME' ENV_XDG_...
self.conv4(x) x = self.conv5(x) return x def forward(self, x, return_featuremaps=False): x = self.featuremaps(x) if return_featuremaps: return x v = self.global_avgpool(x) v = v.view(v.size(0), -1) if self.fc is not None: v = self.fc(...
156
156
522
10
146
12-malak/Pose-Estimation
trackers/ReidModels/osnet_ain.py
Python
init_pretrained_weights
init_pretrained_weights
442
517
442
442
3aaf2544eb3cc096b468de5904462fef38db2448
bigcode/the-stack
train
10fefc0c5f7d390e4949141e
train
class
class OSBlock(nn.Module): """Omni-scale feature learning block.""" def __init__(self, in_channels, out_channels, reduction=4, T=4, **kwargs): super(OSBlock, self).__init__() assert T >= 1 assert out_channels >= reduction and out_channels % reduction == 0 mid_channels = out_chann...
class OSBlock(nn.Module):
"""Omni-scale feature learning block.""" def __init__(self, in_channels, out_channels, reduction=4, T=4, **kwargs): super(OSBlock, self).__init__() assert T >= 1 assert out_channels >= reduction and out_channels % reduction == 0 mid_channels = out_channels // reduction ...
self.global_avgpool(x) x = self.fc1(x) if self.norm1 is not None: x = self.norm1(x) x = self.relu(x) x = self.fc2(x) if self.gate_activation is not None: x = self.gate_activation(x) if self.return_gates: return x return input *...
88
88
294
6
81
12-malak/Pose-Estimation
trackers/ReidModels/osnet_ain.py
Python
OSBlock
OSBlock
229
259
229
229
bf57bdb1032fedc3dfbc019a2dfc6f28bd298004
bigcode/the-stack
train
230e4ff1fed296cb868c6e62
train
class
class Conv1x1Linear(nn.Module): """1x1 convolution + bn (w/o non-linearity).""" def __init__(self, in_channels, out_channels, stride=1, bn=True): super(Conv1x1Linear, self).__init__() self.conv = nn.Conv2d( in_channels, out_channels, 1, stride=stride, padding=0, bias=False )...
class Conv1x1Linear(nn.Module):
"""1x1 convolution + bn (w/o non-linearity).""" def __init__(self, in_channels, out_channels, stride=1, bn=True): super(Conv1x1Linear, self).__init__() self.conv = nn.Conv2d( in_channels, out_channels, 1, stride=stride, padding=0, bias=False ) self.bn = None ...
, groups=groups ) self.bn = nn.BatchNorm2d(out_channels) self.relu = nn.ReLU() def forward(self, x): x = self.conv(x) x = self.bn(x) return self.relu(x) class Conv1x1Linear(nn.Module):
64
64
145
9
55
12-malak/Pose-Estimation
trackers/ReidModels/osnet_ain.py
Python
Conv1x1Linear
Conv1x1Linear
76
92
76
76
e8d7bde4ea247404161dba48f83052e1eca7e77e
bigcode/the-stack
train
b01a672dca7082f8c0997c65
train
function
def osnet_ain_x1_0( num_classes=1000, pretrained=True, loss='softmax', **kwargs ): model = OSNet( num_classes, blocks=[ [OSBlockINin, OSBlockINin], [OSBlock, OSBlockINin], [OSBlockINin, OSBlock] ], layers=[2, 2, 2], channels=[64, 256, 384, 512], ...
def osnet_ain_x1_0( num_classes=1000, pretrained=True, loss='softmax', **kwargs ):
model = OSNet( num_classes, blocks=[ [OSBlockINin, OSBlockINin], [OSBlock, OSBlockINin], [OSBlockINin, OSBlock] ], layers=[2, 2, 2], channels=[64, 256, 384, 512], loss=loss, conv1_IN=True, **kwargs ) if pretrained: ...
The following layers are discarded ' 'due to unmatched keys or layer size: {}'. format(discarded_layers) ) ########## # Instantiation ########## def osnet_ain_x1_0( num_classes=1000, pretrained=True, loss='softmax', **kwargs ):
64
64
142
29
35
12-malak/Pose-Estimation
trackers/ReidModels/osnet_ain.py
Python
osnet_ain_x1_0
osnet_ain_x1_0
523
540
523
525
304718073724a06287f438679bbf6829a6bd2665
bigcode/the-stack
train
d46ef59dce3e7f86dd8817c4
train
class
class LightConv3x3(nn.Module): """Lightweight 3x3 convolution. 1x1 (linear) + dw 3x3 (nonlinear). """ def __init__(self, in_channels, out_channels): super(LightConv3x3, self).__init__() self.conv1 = nn.Conv2d( in_channels, out_channels, 1, stride=1, padding=0, bias=False ...
class LightConv3x3(nn.Module):
"""Lightweight 3x3 convolution. 1x1 (linear) + dw 3x3 (nonlinear). """ def __init__(self, in_channels, out_channels): super(LightConv3x3, self).__init__() self.conv1 = nn.Conv2d( in_channels, out_channels, 1, stride=1, padding=0, bias=False ) self.conv2 = nn....
, groups=groups ) self.bn = nn.BatchNorm2d(out_channels) self.relu = nn.ReLU() def forward(self, x): x = self.conv(x) x = self.bn(x) return self.relu(x) class LightConv3x3(nn.Module):
64
64
198
9
55
12-malak/Pose-Estimation
trackers/ReidModels/osnet_ain.py
Python
LightConv3x3
LightConv3x3
118
144
118
118
3792f28fc79dc7663ed76d8063623ff27832799e
bigcode/the-stack
train
688aac10dce8e9eba5831b58
train
class
class Conv3x3(nn.Module): """3x3 convolution + bn + relu.""" def __init__(self, in_channels, out_channels, stride=1, groups=1): super(Conv3x3, self).__init__() self.conv = nn.Conv2d( in_channels, out_channels, 3, stride=stride, padding...
class Conv3x3(nn.Module):
"""3x3 convolution + bn + relu.""" def __init__(self, in_channels, out_channels, stride=1, groups=1): super(Conv3x3, self).__init__() self.conv = nn.Conv2d( in_channels, out_channels, 3, stride=stride, padding=1, bias=False...
) self.bn = None if bn: self.bn = nn.BatchNorm2d(out_channels) def forward(self, x): x = self.conv(x) if self.bn is not None: x = self.bn(x) return x class Conv3x3(nn.Module):
64
64
142
8
55
12-malak/Pose-Estimation
trackers/ReidModels/osnet_ain.py
Python
Conv3x3
Conv3x3
95
115
95
95
88acff1e36ff782fd3f5adbf956c70f62ce4ec06
bigcode/the-stack
train
8c42c65c9703f61ee21b8b82
train
class
class Conv1x1(nn.Module): """1x1 convolution + bn + relu.""" def __init__(self, in_channels, out_channels, stride=1, groups=1): super(Conv1x1, self).__init__() self.conv = nn.Conv2d( in_channels, out_channels, 1, stride=stride, padding...
class Conv1x1(nn.Module):
"""1x1 convolution + bn + relu.""" def __init__(self, in_channels, out_channels, stride=1, groups=1): super(Conv1x1, self).__init__() self.conv = nn.Conv2d( in_channels, out_channels, 1, stride=stride, padding=0, bias=False...
(out_channels, affine=True) else: self.bn = nn.BatchNorm2d(out_channels) self.relu = nn.ReLU() def forward(self, x): x = self.conv(x) x = self.bn(x) return self.relu(x) class Conv1x1(nn.Module):
64
64
142
8
56
12-malak/Pose-Estimation
trackers/ReidModels/osnet_ain.py
Python
Conv1x1
Conv1x1
53
73
53
53
02d940ee4ee9b594412d28cb641c2c0238801994
bigcode/the-stack
train
feb2901e81e68cb107f8fe07
train
class
class OSBlockINin(nn.Module): """Omni-scale feature learning block with instance normalization.""" def __init__(self, in_channels, out_channels, reduction=4, T=4, **kwargs): super(OSBlockINin, self).__init__() assert T >= 1 assert out_channels >= reduction and out_channels % reduction =...
class OSBlockINin(nn.Module):
"""Omni-scale feature learning block with instance normalization.""" def __init__(self, in_channels, out_channels, reduction=4, T=4, **kwargs): super(OSBlockINin, self).__init__() assert T >= 1 assert out_channels >= reduction and out_channels % reduction == 0 mid_channels = out...
x1 = self.conv1(x) x2 = 0 for conv2_t in self.conv2: x2_t = conv2_t(x1) x2 = x2 + self.gate(x2_t) x3 = self.conv3(x2) if self.downsample is not None: identity = self.downsample(identity) out = x3 + identity return F.relu(out) class OSB...
99
99
333
8
91
12-malak/Pose-Estimation
trackers/ReidModels/osnet_ain.py
Python
OSBlockINin
OSBlockINin
262
294
262
262
9ce305db9365a4ddaeb86f02a29c5c5688b3f516
bigcode/the-stack
train
dcf6efebe7b964ad02fae59e
train
class
class ChannelGate(nn.Module): """A mini-network that generates channel-wise gates conditioned on input tensor.""" def __init__( self, in_channels, num_gates=None, return_gates=False, gate_activation='sigmoid', reduction=16, layer_norm=False ): ...
class ChannelGate(nn.Module):
"""A mini-network that generates channel-wise gates conditioned on input tensor.""" def __init__( self, in_channels, num_gates=None, return_gates=False, gate_activation='sigmoid', reduction=16, layer_norm=False ): super(ChannelGate, self).__in...
Stream, self).__init__() assert depth >= 1, 'depth must be equal to or larger than 1, but got {}'.format( depth ) layers = [] layers += [LightConv3x3(in_channels, out_channels)] for i in range(depth - 1): layers += [LightConv3x3(out_channels, out_channels)...
120
120
403
6
114
12-malak/Pose-Estimation
trackers/ReidModels/osnet_ain.py
Python
ChannelGate
ChannelGate
168
226
168
168
deb616e3211c13c503e422b4fc8fa61d009ecca3
bigcode/the-stack
train
a8b261e054f0dbb42f84148c
train
class
class LightConvStream(nn.Module): """Lightweight convolution stream.""" def __init__(self, in_channels, out_channels, depth): super(LightConvStream, self).__init__() assert depth >= 1, 'depth must be equal to or larger than 1, but got {}'.format( depth ) layers = [] ...
class LightConvStream(nn.Module):
"""Lightweight convolution stream.""" def __init__(self, in_channels, out_channels, depth): super(LightConvStream, self).__init__() assert depth >= 1, 'depth must be equal to or larger than 1, but got {}'.format( depth ) layers = [] layers += [LightConv3x3(in...
) self.bn = nn.BatchNorm2d(out_channels) self.relu = nn.ReLU() def forward(self, x): x = self.conv1(x) x = self.conv2(x) x = self.bn(x) return self.relu(x) class LightConvStream(nn.Module):
64
64
135
7
57
12-malak/Pose-Estimation
trackers/ReidModels/osnet_ain.py
Python
LightConvStream
LightConvStream
147
162
147
147
6864f5c3a4f5760cc6bad073389a01de16cf1b10
bigcode/the-stack
train
9ef32f0930c54164c0fa6e1b
train
class
class ConvLayer(nn.Module): """Convolution layer (conv + bn + relu).""" def __init__( self, in_channels, out_channels, kernel_size, stride=1, padding=0, groups=1, IN=False ): super(ConvLayer, self).__init__() self.conv = nn.Con...
class ConvLayer(nn.Module):
"""Convolution layer (conv + bn + relu).""" def __init__( self, in_channels, out_channels, kernel_size, stride=1, padding=0, groups=1, IN=False ): super(ConvLayer, self).__init__() self.conv = nn.Conv2d( in_channels...
_urls = { 'osnet_ain_x1_0': 'https://drive.google.com/uc?id=1-CaioD9NaqbHK_kzSMW8VE4_3KcsRjEo' } ########## # Basic layers ########## class ConvLayer(nn.Module):
64
64
182
6
58
12-malak/Pose-Estimation
trackers/ReidModels/osnet_ain.py
Python
ConvLayer
ConvLayer
18
50
18
18
96666fbf16d412dde56f49722e3ea7e3fb818be9
bigcode/the-stack
train
1baf8e79791ca5284dc9747c
train
class
class MoneyFst(GraphFst): """ Finite state transducer for classifying money, e.g. "5руб." -> money { "пять рублей" } Args: cardinal: CardinalFst decimal: DecimalFst deterministic: if True will provide a single transduction option, for False multiple transduction ...
class MoneyFst(GraphFst):
""" Finite state transducer for classifying money, e.g. "5руб." -> money { "пять рублей" } Args: cardinal: CardinalFst decimal: DecimalFst deterministic: if True will provide a single transduction option, for False multiple transduction are generated (used for au...
# # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under ...
217
217
725
8
208
madhukarkm/NeMo
nemo_text_processing/text_normalization/ru/taggers/money.py
Python
MoneyFst
MoneyFst
27
101
27
27
0cf0d149822031c3e64cf3f4eebe134ae82cc8a9
bigcode/the-stack
train
f9899c099f5ce262ef0067bb
train
class
class Issue(GiteaApiObject): GET_API_OBJECT = """/repos/{owner}/{repo}/issues/{number}""" # <owner, repo, index> GET_TIME = """/repos/%s/%s/issues/%s/times""" # <owner, repo, index> GET_COMMENTS = """/repos/%s/%s/issues/comments""" CREATE_ISSUE = """/repos/{owner}/{repo}/issues""" OPENED = "open"...
class Issue(GiteaApiObject):
GET_API_OBJECT = """/repos/{owner}/{repo}/issues/{number}""" # <owner, repo, index> GET_TIME = """/repos/%s/%s/issues/%s/times""" # <owner, repo, index> GET_COMMENTS = """/repos/%s/%s/issues/comments""" CREATE_ISSUE = """/repos/{owner}/{repo}/issues""" OPENED = "open" CLOSED = "closed" d...
patchable_fields = {"body"} class Commit(GiteaApiObject): def __init__(self, gitea, id: int): super(Commit, self).__init__(gitea, id=id) fields_to_parsers = { # NOTE: do not try to parse gitea-users from git-committers/authors, as # they are not necessarily users of gitea as well ...
237
237
793
8
228
Langenfeld/py-gitea
gitea/gitea.py
Python
Issue
Issue
484
565
484
484
812774aee787990e9959b06ac939f8cb0857bc43
bigcode/the-stack
train
89cd41e014a41e73686d6b36
train
class
class Repository(GiteaApiObject): REPO_IS_COLLABORATOR = ( """/repos/%s/%s/collaborators/%s""" # <owner>, <reponame>, <username> ) GET_API_OBJECT = """/repos/{owner}/{name}""" # <owner>, <reponame> REPO_SEARCH = """/repos/search/%s""" # <reponame> REPO_BRANCHES = """/repos/%s/%s/branches"...
class Repository(GiteaApiObject):
REPO_IS_COLLABORATOR = ( """/repos/%s/%s/collaborators/%s""" # <owner>, <reponame>, <username> ) GET_API_OBJECT = """/repos/{owner}/{name}""" # <owner>, <reponame> REPO_SEARCH = """/repos/search/%s""" # <reponame> REPO_BRANCHES = """/repos/%s/%s/branches""" # <owner>, <reponame> REPO...
= mail["email"] def delete(self): """ Deletes this User. Also deletes all Repositories he owns.""" self.gitea.requests_delete(User.ADMIN_DELETE_USER % self.username) self.deleted = True def get_heatmap(self) -> List[Tuple[datetime, int]]: results = self.gitea.requests_get(User...
256
256
1,698
8
248
Langenfeld/py-gitea
gitea/gitea.py
Python
Repository
Repository
228
408
228
228
43ea6938b1c51c7427ebdf30c33c59036ebe666e
bigcode/the-stack
train
74bca7940729a07aebc02d85
train
class
class Commit(GiteaApiObject): def __init__(self, gitea, id: int): super(Commit, self).__init__(gitea, id=id) fields_to_parsers = { # NOTE: do not try to parse gitea-users from git-committers/authors, as # they are not necessarily users of gitea as well } @classmethod def re...
class Commit(GiteaApiObject):
def __init__(self, gitea, id: int): super(Commit, self).__init__(gitea, id=id) fields_to_parsers = { # NOTE: do not try to parse gitea-users from git-committers/authors, as # they are not necessarily users of gitea as well } @classmethod def request(cls, gitea, owner, repo)...
a, r: User.parse_response(gitea, r), "created_at": lambda gitea, t: Util.convert_time(t), "updated_at": lambda gitea, t: Util.convert_time(t), } patchable_fields = {"body"} class Commit(GiteaApiObject):
65
66
220
8
57
Langenfeld/py-gitea
gitea/gitea.py
Python
Commit
Commit
461
481
461
461
9843a8420d5bd73ede52882aef192fa67f2299b4
bigcode/the-stack
train
c59af221bb652febe1866929
train
class
class Branch(GiteaApiObject): GET_API_OBJECT = """/repos/%s/%s/branches/%s""" # <owner>, <repo>, <ref> def __init__(self, gitea, id: int): super(Branch, self).__init__(gitea, id=id) fields_to_parsers = { "commit": lambda gitea, c: Commit.parse_response(gitea, c) } @classmethod ...
class Branch(GiteaApiObject):
GET_API_OBJECT = """/repos/%s/%s/branches/%s""" # <owner>, <repo>, <ref> def __init__(self, gitea, id: int): super(Branch, self).__init__(gitea, id=id) fields_to_parsers = { "commit": lambda gitea, c: Commit.parse_response(gitea, c) } @classmethod def request(cls, gitea, owne...
List[Tuple[datetime, int]]: results = self.gitea.requests_get(User.USER_HEATMAP % self.username) results = [ (datetime.fromtimestamp(result["timestamp"]), result["contributions"]) for result in results ] return results class Branch(GiteaApiObject):
64
64
139
8
55
Langenfeld/py-gitea
gitea/gitea.py
Python
Branch
Branch
213
225
213
213
b31e807cf91510dfe984b5bab435da1a5813044e
bigcode/the-stack
train
b0e2aa708f2a7b69999899b7
train
class
class Gitea: """ Object to establish a session with Gitea. """ ADMIN_CREATE_USER = """/admin/users""" GET_USERS_ADMIN = """/admin/users""" ADMIN_REPO_CREATE = """/admin/users/%s/repos""" # <ownername> GITEA_VERSION = """/version""" GET_USER = """/user""" CREATE_ORG = """/admin/users/%s/org...
class Gitea:
""" Object to establish a session with Gitea. """ ADMIN_CREATE_USER = """/admin/users""" GET_USERS_ADMIN = """/admin/users""" ADMIN_REPO_CREATE = """/admin/users/%s/repos""" # <ownername> GITEA_VERSION = """/version""" GET_USER = """/user""" CREATE_ORG = """/admin/users/%s/orgs""" # <user...
.id) return [User.parse_response(self.gitea, result) for result in results] def get_repos(self): """ Get all repos of this Team.""" results = self.gitea.requests_get(Team.GET_REPOS % self.id) return [Repository.parse_response(self.gitea, result) for result in results] def delet...
256
256
3,578
5
251
Langenfeld/py-gitea
gitea/gitea.py
Python
Gitea
Gitea
624
1,113
624
624
6728dc380c048b3cb8e30dd03a42827600e43ac1
bigcode/the-stack
train
d27ba00a2dcdf8d9e26dd582
train
class
class Team(GiteaApiObject): GET_API_OBJECT = """/teams/{id}""" # <id> ADD_USER = """/teams/%s/members/%s""" # <id, username to add> ADD_REPO = """/teams/%s/repos/%s/%s""" # <id, org, repo> TEAM_DELETE = """/teams/%s""" # <id> GET_MEMBERS = """/teams/%s/members""" # <id> GET_REPOS = """/team...
class Team(GiteaApiObject):
GET_API_OBJECT = """/teams/{id}""" # <id> ADD_USER = """/teams/%s/members/%s""" # <id, username to add> ADD_REPO = """/teams/%s/repos/%s/%s""" # <id, org, repo> TEAM_DELETE = """/teams/%s""" # <id> GET_MEMBERS = """/teams/%s/members""" # <id> GET_REPOS = """/teams/%s/repos""" # <id> d...
int(time), "user_name": user_name} ) def get_comments(self) -> List[GiteaApiObject]: results = self.gitea.requests_get( Issue.GET_COMMENTS % (self.owner.username, self.repo) ) allProjectComments = [ Comment.parse_response(self.gitea, result) for result in re...
138
139
465
8
130
Langenfeld/py-gitea
gitea/gitea.py
Python
Team
Team
568
611
568
568
3b466d2f00dd70aa8443a06d17b3a5f1b69eea34
bigcode/the-stack
train
c4036a2e5d3575f436ff78d7
train
class
class Organization(GiteaApiObject): """see https://try.gitea.io/api/swagger#/organization/orgGetAll""" GET_API_OBJECT = """/orgs/{name}""" # <org> PATCH_API_OBJECT = """/orgs/{name}""" # <org> ORG_REPOS_REQUEST = """/orgs/%s/repos""" # <org> ORG_TEAMS_REQUEST = """/orgs/%s/teams""" # <org> ...
class Organization(GiteaApiObject):
"""see https://try.gitea.io/api/swagger#/organization/orgGetAll""" GET_API_OBJECT = """/orgs/{name}""" # <org> PATCH_API_OBJECT = """/orgs/{name}""" # <org> ORG_REPOS_REQUEST = """/orgs/%s/repos""" # <org> ORG_TEAMS_REQUEST = """/orgs/%s/teams""" # <org> ORG_TEAMS_CREATE = """/orgs/%s/teams...
import json import logging import uuid from datetime import datetime from typing import List, Tuple, Dict, Sequence, Optional import requests from httpcache import CachingHTTPAdapter from .basicGiteaApiObject import BasicGiteaApiObject from .exceptions import * from .giteaApiObject import GiteaApiObject class Organiz...
82
256
908
8
73
Langenfeld/py-gitea
gitea/gitea.py
Python
Organization
Organization
15
111
15
15
4e174b345a798ca7c6427beebc0aed4fffdc8a5a
bigcode/the-stack
train
25246547930170452284c691
train
class
class Util: @staticmethod def convert_time(time: str) -> datetime: """ Parsing of strange Gitea time format ("%Y-%m-%dT%H:%M:%S:%z" but with ":" in time zone notation)""" try: return datetime.strptime(time[:-3] + "00", "%Y-%m-%dT%H:%M:%S%z") except ValueError: ret...
class Util: @staticmethod
def convert_time(time: str) -> datetime: """ Parsing of strange Gitea time format ("%Y-%m-%dT%H:%M:%S:%z" but with ":" in time zone notation)""" try: return datetime.strptime(time[:-3] + "00", "%Y-%m-%dT%H:%M:%S%z") except ValueError: return datetime.strptime(time[:-3...
.gitea.requests_delete(Team.TEAM_DELETE % self.id) self.deleted = True def remove_team_member(self, user_name: str): url = f"/teams/{self.id}/members/{user_name}" self.gitea.requests_delete(url) class Util: @staticmethod
64
64
115
7
57
Langenfeld/py-gitea
gitea/gitea.py
Python
Util
Util
614
621
614
615
c822e86e5de880f623a81a99b73f04f8963fa099
bigcode/the-stack
train
525c4ce3e290901c4b1a9d19
train
class
class Milestone(GiteaApiObject): GET_API_OBJECT = ( """/repos/{owner}/{repo}/milestones/{number}""" # <owner, repo, id> ) def __init__(self, gitea, id: int): super(Milestone, self).__init__(gitea, id=id) fields_to_parsers = { "closed_at": lambda gitea, t: Util.convert_time(t),...
class Milestone(GiteaApiObject):
GET_API_OBJECT = ( """/repos/{owner}/{repo}/milestones/{number}""" # <owner, repo, id> ) def __init__(self, gitea, id: int): super(Milestone, self).__init__(gitea, id=id) fields_to_parsers = { "closed_at": lambda gitea, t: Util.convert_time(t), "due_on": lambda gitea, ...
url = f"/repos/{self.owner.username}/{self.name}/collaborators/{user_name}" self.gitea.requests_delete(url) def delete(self): self.gitea.requests_delete( Repository.REPO_DELETE % (self.owner.username, self.name) ) self.deleted = True class Milestone(GiteaApiObjec...
74
74
248
9
64
Langenfeld/py-gitea
gitea/gitea.py
Python
Milestone
Milestone
411
443
411
411
3ab3b996268d313ff065e3d22bec6758ef6d9d2d
bigcode/the-stack
train
9c0acae94125389152c03739
train
class
class Comment(BasicGiteaApiObject): PATCH_API_OBJECT = "/repos/{owner}/{repo}/issues/comments/{id}" def __init__(self, gitea, id: int): super(Comment, self).__init__(gitea, id=id) fields_to_parsers = { "user": lambda gitea, r: User.parse_response(gitea, r), "created_at": lambda git...
class Comment(BasicGiteaApiObject):
PATCH_API_OBJECT = "/repos/{owner}/{repo}/issues/comments/{id}" def __init__(self, gitea, id: int): super(Comment, self).__init__(gitea, id=id) fields_to_parsers = { "user": lambda gitea, r: User.parse_response(gitea, r), "created_at": lambda gitea, t: Util.convert_time(t), ...
", "private", "website", } @classmethod def request(cls, gitea, owner, repo, number): return cls._request(gitea, {"owner": owner, "repo": repo, "number": number}) class Comment(BasicGiteaApiObject):
64
64
128
10
54
Langenfeld/py-gitea
gitea/gitea.py
Python
Comment
Comment
446
458
446
446
e70d608da8a285e2d15803e3d59278cecbf0999d
bigcode/the-stack
train
558b5788740936f54ea8e96e
train
class
class User(GiteaApiObject): GET_API_OBJECT = """/users/{name}""" # <org> USER_MAIL = """/user/emails?sudo=%s""" # <name> USER_PATCH = """/admin/users/%s""" # <username> ADMIN_DELETE_USER = """/admin/users/%s""" # <username> ADMIN_EDIT_USER = """/admin/users/{username}""" # <username> USER_H...
class User(GiteaApiObject):
GET_API_OBJECT = """/users/{name}""" # <org> USER_MAIL = """/user/emails?sudo=%s""" # <name> USER_PATCH = """/admin/users/%s""" # <username> ADMIN_DELETE_USER = """/admin/users/%s""" # <username> ADMIN_EDIT_USER = """/admin/users/{username}""" # <username> USER_HEATMAP = """/users/%s/heatma...
result) for result in results] def is_member(self, username) -> bool: if isinstance(username, User): username = username.username try: # returns 204 if its ok, 404 if its not self.gitea.requests_get( Organization.ORG_IS_MEMBER % (self.username, u...
256
256
860
8
247
Langenfeld/py-gitea
gitea/gitea.py
Python
User
User
114
210
114
114
d729ffb421d55d3102c0c22bd42ba9952d900d14
bigcode/the-stack
train
bebedc837f533229a69dc797
train
class
class GTFS_processor: def __init__(self, gtfs_path): path = gtfs_path stop_times = pd.read_csv(path + "stop_times.txt", sep=',', index_col = "trip_id") trips = pd.read_csv(path + 'trips.txt', sep=',', index_col = 'trip_id') test = stop_times.join(trips, how='left') test...
class GTFS_processor:
def __init__(self, gtfs_path): path = gtfs_path stop_times = pd.read_csv(path + "stop_times.txt", sep=',', index_col = "trip_id") trips = pd.read_csv(path + 'trips.txt', sep=',', index_col = 'trip_id') test = stop_times.join(trips, how='left') test['tripid'] = test.index...
import pandas as pd import os import numpy as np import sys import traci import random class GTFS_processor:
29
256
2,702
5
23
smarttransit-ai/transit-gym
src/transsim/GTFS_processor.py
Python
GTFS_processor
GTFS_processor
9
191
9
9
7f9fae8b03e42316fb16829772569f881defb01d
bigcode/the-stack
train
129b368b608e3bb401a75e47
train
function
def single_qubit_process_tomography( operation, n_measurements=2000, n_particles=4000 ): """ :param operation: A Q# operation of type ((Pauli, Pauli) => Result) whose inputs are named `prep` and `meas` (respectively), representing a state preparation, evolution, and measurement. ...
def single_qubit_process_tomography( operation, n_measurements=2000, n_particles=4000 ):
""" :param operation: A Q# operation of type ((Pauli, Pauli) => Result) whose inputs are named `prep` and `meas` (respectively), representing a state preparation, evolution, and measurement. """ if qt is None: raise ImportError("This function requires QuTiP.") if qi is None: ...
# Licensed under the MIT License. ## ## IMPORTS ## import qsharp import numpy as np try: import qinfer as qi except ImportError: qi = None try: import qutip as qt except ImportError: qt = None def projector(P): if qt is None: raise ImportError("This function requires QuTiP.") retur...
126
126
423
28
97
vxfield/iqsharp
src/Python/qsharp-core/qsharp/tomography.py
Python
single_qubit_process_tomography
single_qubit_process_tomography
31
79
31
35
c875b742939a29d2e16c35f1360538d534e28131
bigcode/the-stack
train
feef7c19ef0953ca54c72cd9
train
function
def projector(P): if qt is None: raise ImportError("This function requires QuTiP.") return (qt.qeye(2) + P) / 2.0
def projector(P):
if qt is None: raise ImportError("This function requires QuTiP.") return (qt.qeye(2) + P) / 2.0
reserved. # Licensed under the MIT License. ## ## IMPORTS ## import qsharp import numpy as np try: import qinfer as qi except ImportError: qi = None try: import qutip as qt except ImportError: qt = None def projector(P):
64
64
40
4
59
vxfield/iqsharp
src/Python/qsharp-core/qsharp/tomography.py
Python
projector
projector
25
29
25
25
00a7dd5e2e14d82ddaf694f1140ed4d55a40f401
bigcode/the-stack
train
92de8ec05d7be5fe33817eb3
train
class
class TestMypyArgs: def test_correct(self, new_project): config = {'mypy-args': ['foo']} build_dir = new_project / 'dist' build_hook = MypycBuildHook(str(new_project), config, None, None, str(build_dir), 'wheel') assert build_hook.config_mypy_args == ['foo'] def test_not_array(...
class TestMypyArgs:
def test_correct(self, new_project): config = {'mypy-args': ['foo']} build_dir = new_project / 'dist' build_hook = MypycBuildHook(str(new_project), config, None, None, str(build_dir), 'wheel') assert build_hook.config_mypy_args == ['foo'] def test_not_array(self, new_project): ...
# SPDX-FileCopyrightText: 2021-present Ofek Lev <oss@ofek.dev> # # SPDX-License-Identifier: MIT import pytest from hatchling.builders.config import BuilderConfig from hatch_mypyc.plugin import MypycBuildHook class TestMypyArgs:
60
114
383
6
53
ofek/hatch-mypyc
tests/test_config.py
Python
TestMypyArgs
TestMypyArgs
10
44
10
10
a0a0879e65568c22ecea65e9550a15c279645260
bigcode/the-stack
train
d12d3e3072a9e6988d226ae8
train
class
class TestPatternMatching: def test_no_include(self, new_project): build_dir = new_project / 'dist' config = {} target_config = {} build_config = BuilderConfig(None, str(new_project), 'wheel', {}, target_config) build_hook = MypycBuildHook(str(new_project), config, build_conf...
class TestPatternMatching:
def test_no_include(self, new_project): build_dir = new_project / 'dist' config = {} target_config = {} build_config = BuilderConfig(None, str(new_project), 'wheel', {}, target_config) build_hook = MypycBuildHook(str(new_project), config, build_config, None, str(build_dir), '...
_dir), 'wheel') with pytest.raises(TypeError, match='Option `exclude` for build hook `mypyc` must be an array'): _ = build_hook.config_exclude def test_pattern_not_string(self, new_project): config = {'exclude': [9000]} build_dir = new_project / 'dist' build_hook = Mypy...
237
237
792
5
231
ofek/hatch-mypyc
tests/test_config.py
Python
TestPatternMatching
TestPatternMatching
134
203
134
134
9f333c34cb6f43ac4e49c53e039fdca1e151a72b
bigcode/the-stack
train
4b57ed0458ca151f94a81f07
train
class
class TestPackageSource: def test_none(self, new_project): build_dir = new_project / 'dist' config = {} target_config = {'packages': ['foo']} build_config = BuilderConfig(None, str(new_project), 'wheel', {}, target_config) build_hook = MypycBuildHook(str(new_project), config,...
class TestPackageSource:
def test_none(self, new_project): build_dir = new_project / 'dist' config = {} target_config = {'packages': ['foo']} build_config = BuilderConfig(None, str(new_project), 'wheel', {}, target_config) build_hook = MypycBuildHook(str(new_project), config, build_config, None, str(...
, None, str(build_dir), 'wheel') assert not build_hook.include_path('foo/bar.py') assert not build_hook.include_path('foo/baz.py') assert build_hook.include_path('bar/foo.py') assert not build_hook.include_path('bar/baz.py') class TestPackageSource:
64
64
182
5
59
ofek/hatch-mypyc
tests/test_config.py
Python
TestPackageSource
TestPackageSource
206
223
206
206
d1ba80c443a293f593bbdb43102fd47947895703
bigcode/the-stack
train
db5dc197edc3663f75480307
train
class
class TestExclude: def test_correct(self, new_project): config = {'exclude': ['foo']} build_dir = new_project / 'dist' build_hook = MypycBuildHook(str(new_project), config, None, None, str(build_dir), 'wheel') assert build_hook.config_exclude == ['foo'] def test_not_array(self,...
class TestExclude:
def test_correct(self, new_project): config = {'exclude': ['foo']} build_dir = new_project / 'dist' build_hook = MypycBuildHook(str(new_project), config, None, None, str(build_dir), 'wheel') assert build_hook.config_exclude == ['foo'] def test_not_array(self, new_project): ...
_hook.config_include def test_pattern_empty_string(self, new_project): config = {'include': ['']} build_dir = new_project / 'dist' build_hook = MypycBuildHook(str(new_project), config, None, None, str(build_dir), 'wheel') with pytest.raises( ValueError, match='Pattern #...
105
105
352
4
100
ofek/hatch-mypyc
tests/test_config.py
Python
TestExclude
TestExclude
99
131
99
99
503d3d6a9b47ea27611a41ad6a66e78f555df151
bigcode/the-stack
train
6c41645cff89933dc46d0d2d
train
class
class TestOptions: def test_correct(self, new_project): config = {'options': {'opt_level': '3'}} build_dir = new_project / 'dist' build_hook = MypycBuildHook(str(new_project), config, None, None, str(build_dir), 'wheel') assert build_hook.config_options == {'opt_level': '3'} de...
class TestOptions:
def test_correct(self, new_project): config = {'options': {'opt_level': '3'}} build_dir = new_project / 'dist' build_hook = MypycBuildHook(str(new_project), config, None, None, str(build_dir), 'wheel') assert build_hook.config_options == {'opt_level': '3'} def test_not_table(se...
config, None, None, str(build_dir), 'wheel') with pytest.raises( ValueError, match='Argument #1 of option `mypy-args` for build hook `mypyc` cannot be an empty string' ): _ = build_hook.config_mypy_args class TestOptions:
64
64
165
4
59
ofek/hatch-mypyc
tests/test_config.py
Python
TestOptions
TestOptions
47
61
47
47
4c07a08ce9371e75b630223d6ed9356c67c89c6e
bigcode/the-stack
train
d018ed507efb92f691b11e8f
train
function
def test_coverage(new_project): build_config = BuilderConfig(None, str(new_project), 'wheel', {}, {'include': ['foo']}) build_hook = MypycBuildHook(str(new_project), {}, build_config, None, str(new_project / 'dist'), 'wheel') assert build_hook.config_mypy_args is build_hook.config_mypy_args assert buil...
def test_coverage(new_project):
build_config = BuilderConfig(None, str(new_project), 'wheel', {}, {'include': ['foo']}) build_hook = MypycBuildHook(str(new_project), {}, build_config, None, str(new_project / 'dist'), 'wheel') assert build_hook.config_mypy_args is build_hook.config_mypy_args assert build_hook.config_options is build_h...
packages': ['src/foo']} build_config = BuilderConfig(None, str(new_project), 'wheel', {}, target_config) build_hook = MypycBuildHook(str(new_project), config, build_config, None, str(build_dir), 'wheel') assert build_hook.package_source == 'src' def test_coverage(new_project):
69
69
231
7
62
ofek/hatch-mypyc
tests/test_config.py
Python
test_coverage
test_coverage
226
241
226
226
53da76428e4db1afa67c1a7ba107a7e47e10157d
bigcode/the-stack
train
2f001483b1f320257c633710
train
class
class TestInclude: def test_correct(self, new_project): config = {'include': ['foo']} build_dir = new_project / 'dist' build_hook = MypycBuildHook(str(new_project), config, None, None, str(build_dir), 'wheel') assert build_hook.config_include == ['foo'] def test_not_array(self,...
class TestInclude:
def test_correct(self, new_project): config = {'include': ['foo']} build_dir = new_project / 'dist' build_hook = MypycBuildHook(str(new_project), config, None, None, str(build_dir), 'wheel') assert build_hook.config_include == ['foo'] def test_not_array(self, new_project): ...
_hook.config_options == {'opt_level': '3'} def test_not_table(self, new_project): config = {'options': 9000} build_dir = new_project / 'dist' build_hook = MypycBuildHook(str(new_project), config, None, None, str(build_dir), 'wheel') with pytest.raises(TypeError, match='Option `opti...
104
104
348
4
99
ofek/hatch-mypyc
tests/test_config.py
Python
TestInclude
TestInclude
64
96
64
64
41a34b5b1c47c1d1f2d49d24015013387644b393
bigcode/the-stack
train
7cc1c999e168a254c08ddc71
train
class
class SequenceValidator(Validator): """ Colection of methods for the validation of sequences and sequence files """ _label = "SequenceValidator" _formats = ["fasta", "fastq"] _qformats = { "sanger": [0, 40, 33], "solexa": [-5, 40, 64], "illumina": [0, 41, 33] # 1.8+ } _sequence_indicators = { "fast...
class SequenceValidator(Validator):
""" Colection of methods for the validation of sequences and sequence files """ _label = "SequenceValidator" _formats = ["fasta", "fastq"] _qformats = { "sanger": [0, 40, 33], "solexa": [-5, 40, 64], "illumina": [0, 41, 33] # 1.8+ } _sequence_indicators = { "fasta": ">", "fastq": "@" } _alpha...
__author__ = 'hofmann' __version__ = '0.0.6' import io import os import string import StringIO from Bio import SeqIO from Bio.Alphabet import IUPAC from Bio.Seq import Seq from validator import Validator # Todo: allow for multiple sequence_type class SequenceValidator(Validator):
74
256
2,629
6
67
blue-moon22/CAMISIM
scripts/Validator/sequencevalidator.py
Python
SequenceValidator
SequenceValidator
16
317
16
16
04d3f7584865f3ea305a4a4832807bd41d875b81
bigcode/the-stack
train
1e5bcdc049af030aad46a861
train
class
class Logic(base.Logic): """Logic methods for the Notification model. """ def __init__(self, model=soc.models.notification.Notification, base_model=None, scope_logic=user_logic): """Defines the name, key_name and model for this entity. """ super(Logic, self).__init__(model=model, base_...
class Logic(base.Logic):
"""Logic methods for the Notification model. """ def __init__(self, model=soc.models.notification.Notification, base_model=None, scope_logic=user_logic): """Defines the name, key_name and model for this entity. """ super(Logic, self).__init__(model=model, base_model=base_model, ...
limitations under the License. """Notification (Model) query functions. """ __authors__ = [ '"Lennard de Rijk" <ljvderijk@gmail.com>', ] from google.appengine.ext import db from soc.cache import sidebar from soc.logic.helper import notifications from soc.logic.models import base from soc.logic.models import u...
88
88
296
6
81
MatthewWilkes/mw4068-packaging
src/melange/src/soc/logic/models/notification.py
Python
Logic
Logic
35
75
35
35
2d1af9cc95297db7b59501a328bd52b99b9bec87
bigcode/the-stack
train
a5cc3828cee82774477fb947
train
function
def ln_prior(theta, parameters_to_fit): """priors - we only reject obviously wrong models""" if theta[parameters_to_fit.index("t_E")] < 0.: return -np.inf return 0.0
def ln_prior(theta, parameters_to_fit):
"""priors - we only reject obviously wrong models""" if theta[parameters_to_fit.index("t_E")] < 0.: return -np.inf return 0.0
likelihood functions def ln_like(theta, event, parameters_to_fit): """likelihood function""" for key, val in enumerate(parameters_to_fit): setattr(event.model.parameters, val, theta[key]) return -0.5 * event.get_chi2() def ln_prior(theta, parameters_to_fit):
64
64
51
9
55
meethari/MulensModel
examples/example_12_fit_satellite_parallax_EMCEE.py
Python
ln_prior
ln_prior
36
40
36
36
48f9e7cc60c7c38b3d86586ba966c689bd9f7aea
bigcode/the-stack
train
ed1d448a8ee3364cf7947bb0
train
function
def ln_like(theta, event, parameters_to_fit): """likelihood function""" for key, val in enumerate(parameters_to_fit): setattr(event.model.parameters, val, theta[key]) return -0.5 * event.get_chi2()
def ln_like(theta, event, parameters_to_fit):
"""likelihood function""" for key, val in enumerate(parameters_to_fit): setattr(event.model.parameters, val, theta[key]) return -0.5 * event.get_chi2()
imported.") print("Get it from: http://dfm.io/emcee/current/user/install/") print("and re-run the script") sys.exit(1) import matplotlib.pyplot as plt import MulensModel as mm # Define likelihood functions def ln_like(theta, event, parameters_to_fit):
64
64
52
11
52
meethari/MulensModel
examples/example_12_fit_satellite_parallax_EMCEE.py
Python
ln_like
ln_like
29
33
29
29
2297254a2cd6cb8d2446fd9483496b23562d9c82
bigcode/the-stack
train
52f13f6f573174bc1b8ca4fd
train
function
def ln_prob(theta, event, parameters_to_fit): """combines likelihood and priors""" ln_prior_ = ln_prior(theta, parameters_to_fit) if not np.isfinite(ln_prior_): return -np.inf ln_like_ = ln_like(theta, event, parameters_to_fit) # In the cases that source fluxes are negative we want to retur...
def ln_prob(theta, event, parameters_to_fit):
"""combines likelihood and priors""" ln_prior_ = ln_prior(theta, parameters_to_fit) if not np.isfinite(ln_prior_): return -np.inf ln_like_ = ln_like(theta, event, parameters_to_fit) # In the cases that source fluxes are negative we want to return # these as if they were not in priors. ...
2() def ln_prior(theta, parameters_to_fit): """priors - we only reject obviously wrong models""" if theta[parameters_to_fit.index("t_E")] < 0.: return -np.inf return 0.0 def ln_prob(theta, event, parameters_to_fit):
64
64
117
11
52
meethari/MulensModel
examples/example_12_fit_satellite_parallax_EMCEE.py
Python
ln_prob
ln_prob
43
55
43
43
0e02db21073889c7f75a51c2c4356895821bf27b
bigcode/the-stack
train
ddf7eb10db17306963363b6f
train
function
@pytest.mark.parametrize('array,expected', [ ('0 1 2 3', '3 2 1 0\n'), ('1 4 3 2', '2 3 4 1\n'), ]) def test_reverse_array(array, expected, capsys): reverse_array(array=array) assert capsys.readouterr().out == expected
@pytest.mark.parametrize('array,expected', [ ('0 1 2 3', '3 2 1 0\n'), ('1 4 3 2', '2 3 4 1\n'), ]) def test_reverse_array(array, expected, capsys):
reverse_array(array=array) assert capsys.readouterr().out == expected
reverse_array @pytest.mark.parametrize('array,expected', [ ('0 1 2 3', '3 2 1 0\n'), ('1 4 3 2', '2 3 4 1\n'), ]) def test_reverse_array(array, expected, capsys):
64
64
79
61
2
IamGianluca/hackerrank
tests/test_reverse_array.py
Python
test_reverse_array
test_reverse_array
6
12
6
10
dbc849325e8ad87bf23b72dcbcddabd4fb396f11
bigcode/the-stack
train
d04a44053aac5a9cfe175f2c
train
class
class TestVariableElimination(unittest.TestCase): def setUp(self): self.bayesian_model = BayesianModel([('A', 'J'), ('R', 'J'), ('J', 'Q'), ('J', 'L'), ('G', 'L')]) cpd_a = TabularCPD('A', 2, [[0.2], [0.8]]) cpd_r = TabularCPD('R', 2, [[0.4], [0.6...
class TestVariableElimination(unittest.TestCase):
def setUp(self): self.bayesian_model = BayesianModel([('A', 'J'), ('R', 'J'), ('J', 'Q'), ('J', 'L'), ('G', 'L')]) cpd_a = TabularCPD('A', 2, [[0.2], [0.8]]) cpd_r = TabularCPD('R', 2, [[0.4], [0.6]]) cpd_j = TabularCPD('J', 2, ...
import unittest import numpy as np import numpy.testing as np_test from pgmpy.inference import VariableElimination from pgmpy.inference import BeliefPropagation from pgmpy.models import BayesianModel from pgmpy.models import JunctionTree from pgmpy.factors import TabularCPD from pgmpy.factors import Factor class TestVa...
85
256
1,213
9
75
jaidevd/pgmpy
pgmpy/tests/test_inference/test_ExactInference.py
Python
TestVariableElimination
TestVariableElimination
12
102
12
12
e55bc58a2acbd9f72eb9772dbbf3c495bd6fd6de
bigcode/the-stack
train
c446b2d0c812239e1b5c55b8
train
class
class TestBeliefPropagation(unittest.TestCase): def setUp(self): self.junction_tree = JunctionTree([(('A', 'B'), ('B', 'C')), (('B', 'C'), ('C', 'D'))]) phi1 = Factor(['A', 'B'], [2, 3], range(6)) phi2 = Factor(['B', 'C'], [3, 2], range(6)) ...
class TestBeliefPropagation(unittest.TestCase):
def setUp(self): self.junction_tree = JunctionTree([(('A', 'B'), ('B', 'C')), (('B', 'C'), ('C', 'D'))]) phi1 = Factor(['A', 'B'], [2, 3], range(6)) phi2 = Factor(['B', 'C'], [3, 2], range(6)) phi3 = Factor(['C', 'D'], [2, 2], range(4)) ...
self.bayesian_inference.map_query(['A', 'R', 'L'], {'J': 0, 'Q': 1, 'G': 0}) self.assertDictEqual(map_query, {'A': 1, 'R': 0, 'L': 0}) def test_induced_graph(self): induced_graph = self.bayesian_inference.induced_graph(['G', 'Q', 'A', 'J', 'L',...
256
256
2,205
9
246
jaidevd/pgmpy
pgmpy/tests/test_inference/test_ExactInference.py
Python
TestBeliefPropagation
TestBeliefPropagation
105
251
105
105
bc8e7b0e874efea663c8f15c9af00660ce649a61
bigcode/the-stack
train
8968d04400af78dfd80c40fe
train
function
def send(event, context, responseStatus, response_data, physicalResourceId=None, noEcho=False): """ From: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-lambda-function-code-cfnresponsemodule.html """ log = ContextLog.get_logger('send') responseUrl = event['ResponseURL'] re...
def send(event, context, responseStatus, response_data, physicalResourceId=None, noEcho=False):
""" From: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-lambda-function-code-cfnresponsemodule.html """ log = ContextLog.get_logger('send') responseUrl = event['ResponseURL'] responseBody = {} responseBody['Status'] = responseStatus responseBody['Reason'] = 'See th...
('resources/logging.yaml', 'r') as log_config_file: logging.config.dictConfig(yaml.safe_load(log_config_file)) COGNITO_IDP_CLIENT = boto3.client('cognito-idp') SECRETSMANAGER_CLIENT = boto3.client('secretsmanager') SUCCESS = "SUCCESS" FAILED = "FAILED" def send(event, context, responseStatus, response_data, physi...
89
89
298
21
68
virtuability/aws-auth
aws/application/CustomCognitoUserPoolDomain/main.py
Python
send
send
20
53
20
20
e2e45992f1581de94b5433d904de911b1f22296e
bigcode/the-stack
train
1e0cec508540e44378914fb1
train
function
def delete_user_pool_domain(domain): """ Function to delete user pool domain """ log = ContextLog.get_logger('delete_user_pool_domain') response = COGNITO_IDP_CLIENT.describe_user_pool_domain( Domain=domain ) if 'UserPoolId' in response['DomainDescription']: log.info('domai...
def delete_user_pool_domain(domain):
""" Function to delete user pool domain """ log = ContextLog.get_logger('delete_user_pool_domain') response = COGNITO_IDP_CLIENT.describe_user_pool_domain( Domain=domain ) if 'UserPoolId' in response['DomainDescription']: log.info('domain exists - deleting: %s', domain) ...
%s', event['RequestType']) except Exception as ex: log.exception('Unexpected exception') send(event, context, FAILED, {'Data' : str(ex)}) raise finally: ContextLog.put_end_time() log.info('Request: end') def delete_user_pool_domain(domain):
64
64
114
7
57
virtuability/aws-auth
aws/application/CustomCognitoUserPoolDomain/main.py
Python
delete_user_pool_domain
delete_user_pool_domain
146
161
146
146
171961d894c808366d389fb60720ef2669549a87
bigcode/the-stack
train
b4e6c4b229a94e305c4d0f16
train
function
def handler(event, context): """ Lambda main handler """ log = ContextLog.get_logger('handler', True) ContextLog.put_start_time() ContextLog.put_request_id(context.aws_request_id) try: log.info('Request: start - event %s', json.dumps(event)) user_pool_id = event['ResourceP...
def handler(event, context):
""" Lambda main handler """ log = ContextLog.get_logger('handler', True) ContextLog.put_start_time() ContextLog.put_request_id(context.aws_request_id) try: log.info('Request: start - event %s', json.dumps(event)) user_pool_id = event['ResourceProperties']['UserPoolId'] ...
responseBody = {} responseBody['Status'] = responseStatus responseBody['Reason'] = 'See the details in CloudWatch Log Stream: ' + context.log_stream_name responseBody['PhysicalResourceId'] = physicalResourceId or context.log_stream_name responseBody['StackId'] = event['StackId'] responseBody['Reque...
231
231
770
6
225
virtuability/aws-auth
aws/application/CustomCognitoUserPoolDomain/main.py
Python
handler
handler
55
144
55
55
41535b5f56b62bc2839fe70baf3f7596c76f4f31
bigcode/the-stack
train
252024a30ef37199de9c01b5
train
class
class TestIntrospection(tb.QueryTestCase): SCHEMA = os.path.join(os.path.dirname(__file__), 'schemas', 'issues.esdl') SETUP = """ """ TEARDOWN = """ """ async def test_edgeql_introspection_schema_not_objects_01(self): # Test to make sure that no types in the ...
class TestIntrospection(tb.QueryTestCase):
SCHEMA = os.path.join(os.path.dirname(__file__), 'schemas', 'issues.esdl') SETUP = """ """ TEARDOWN = """ """ async def test_edgeql_introspection_schema_not_objects_01(self): # Test to make sure that no types in the schema are derived # from std::Obje...
# # This source file is part of the EdgeDB open source project. # # Copyright 2016-present MagicStack Inc. and the EdgeDB authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http...
177
256
7,551
9
167
dmgolembiowski/edgedb
tests/test_edgeql_introspection.py
Python
TestIntrospection
TestIntrospection
25
1,406
25
25
11352b926164998cdf8bf27bc3f8e5c10b98b247
bigcode/the-stack
train
e4e547a2d61275fee45c1738
train
function
def read(*files): here = os.path.abspath(os.path.dirname(__file__)) content = '' for f in files: content += codecs.open(os.path.join(here, f), 'r').read() return content
def read(*files):
here = os.path.abspath(os.path.dirname(__file__)) content = '' for f in files: content += codecs.open(os.path.join(here, f), 'r').read() return content
= os.path.realpath(os.path.join(os.path.dirname(__file__))) init = os.path.join(ROOT, 'src', 'wss_ui', '__init__.py') app = imp.load_source('wss_ui', init) reqs = 'src/requirements/install.any.pip' def read(*files):
64
64
49
5
59
wfp/wfp-ui-reactjs
demo/setup.py
Python
read
read
18
23
18
18
650ae42cd4725f0e4c4d7a10cc35e5293ada7256
bigcode/the-stack
train
0d37c9e086efd9f91201043e
train
function
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Open-Meteo from a config entry.""" session = async_get_clientsession(hass) open_meteo = OpenMeteo(session=session) async def async_update_forecast() -> Forecast: if (zone := hass.states.get(entry.data[CONF_Z...
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Open-Meteo from a config entry.""" session = async_get_clientsession(hass) open_meteo = OpenMeteo(session=session) async def async_update_forecast() -> Forecast: if (zone := hass.states.get(entry.data[CONF_ZONE])) is None: raise UpdateFailed(f"Zone '{entry.data[CONF_ZONE]}...
, WindSpeedUnit, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ATTR_LATITUDE, ATTR_LONGITUDE, CONF_ZONE, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.update_coordina...
113
113
377
19
94
MrDelik/core
homeassistant/components/open_meteo/__init__.py
Python
async_setup_entry
async_setup_entry
25
67
25
25
dcc47d34a1cf704908b9f2c910d576553a77201c
bigcode/the-stack
train
3406d8e941ee3c32480ec55a
train
function
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload Open-Meteo config entry.""" unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) if unload_ok: del hass.data[DOMAIN][entry.entry_id] return unload_ok
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload Open-Meteo config entry.""" unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) if unload_ok: del hass.data[DOMAIN][entry.entry_id] return unload_ok
await coordinator.async_config_entry_first_refresh() hass.data.setdefault(DOMAIN, {})[entry.entry_id] = coordinator hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
64
64
71
20
43
MrDelik/core
homeassistant/components/open_meteo/__init__.py
Python
async_unload_entry
async_unload_entry
70
75
70
70
b71f0ed70cae2942e76e57c8714b011aa4fd3bd8
bigcode/the-stack
train
7513bb8f743a17f1483baf81
train
class
class Solution(object): def wiggleSort(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ c = list(nums) c.sort() index = 0 if len(nums) % 2 == 0: i = len(nums) - 2 whil...
class Solution(object):
def wiggleSort(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ c = list(nums) c.sort() index = 0 if len(nums) % 2 == 0: i = len(nums) - 2 while index < len(nums): ...
''' Leetcode problem No 324 Wiggle Sort II Solution written by Xuqiang Fang on 25 May, 2018 ''' class Solution(object):
33
64
176
4
29
danyfang/SourceCode
py/leetcode/WiggleSort.py
Python
Solution
Solution
6
30
6
6
281e6386a2d56ba3cf0df5b5f688b8b794851d9d
bigcode/the-stack
train
02558f66036be1d2ecc0cecc
train
function
def main(): s = Solution() nums = [1, 5, 1, 1, 6, 4] vec = [4,5,5,5,5,6,6,6] s.wiggleSort(nums) s.wiggleSort(vec) print(nums) print(vec)
def main():
s = Solution() nums = [1, 5, 1, 1, 6, 4] vec = [4,5,5,5,5,6,6,6] s.wiggleSort(nums) s.wiggleSort(vec) print(nums) print(vec)
i = len(nums) - 1 else: i = 0 while index < len(nums): nums[i] = c[index] index += 1 i = i + 2 if i >= len(nums): i = 1 def main():
64
64
73
3
60
danyfang/SourceCode
py/leetcode/WiggleSort.py
Python
main
main
31
38
31
31
d7a0448e94ff90ea797702a2641126246ec6eeb5
bigcode/the-stack
train
f600f11a17b54de0efc30d4b
train
class
class AbstractParser(ABC): def parse_data(self, data: str) -> Tuple[Key, Value]: data = self.deserialize_data(data) if isinstance(data, list): key, value = data else: key = data value = None return key, value @abstractmethod def deserial...
class AbstractParser(ABC):
def parse_data(self, data: str) -> Tuple[Key, Value]: data = self.deserialize_data(data) if isinstance(data, list): key, value = data else: key = data value = None return key, value @abstractmethod def deserialize_data(self, data: str) ->...
from abc import ABC, abstractmethod from typing import Tuple, Union from tgbotcallbackdata.types import Key, Value class AbstractParser(ABC):
33
64
90
6
26
Abstract-X/tgbotcallbackdata
tgbotcallbackdata/parsers/base.py
Python
AbstractParser
AbstractParser
7
21
7
8
885a0fb965745160e3a8d17174a439c93cf06d82
bigcode/the-stack
train
c991c7827acc72592cc768df
train
function
def _check_flip(origin_imgs, result_imgs): """Check if the origin_imgs are flipped correctly.""" h, w, c = origin_imgs.shape for i in range(h): for j in range(w): for k in range(c): if result_imgs[i, j, k] != origin_imgs[i, w - 1 - j, k]: return False ...
def _check_flip(origin_imgs, result_imgs):
"""Check if the origin_imgs are flipped correctly.""" h, w, c = origin_imgs.shape for i in range(h): for j in range(w): for k in range(c): if result_imgs[i, j, k] != origin_imgs[i, w - 1 - j, k]: return False return True
TopDownRandomFlip, TopDownRandomTranslation, ToTensor) def _check_keys_contain(result_keys, target_keys): """Check if all elements in target_keys is in result_keys.""" return set(target_keys).issubset(set(result_keys)) def _check_fl...
64
64
85
10
54
EricChan-OC/mmpose
tests/test_pipelines/test_top_down_pipelines.py
Python
_check_flip
_check_flip
23
31
23
23
d0e54abab382bd654f03500871e96dde87f404cf
bigcode/the-stack
train
f7e1fe6e010565f77a8b10c9
train
function
def test_random_translation(): results = dict( center=np.zeros([2]), scale=1, ) pipeline = TopDownRandomTranslation() results = pipeline(results) assert results['center'].shape == (2, )
def test_random_translation():
results = dict( center=np.zeros([2]), scale=1, ) pipeline = TopDownRandomTranslation() results = pipeline(results) assert results['center'].shape == (2, )
', 'scale', 'rotation', 'bbox_score', 'flip_pairs' ]) results_final = collect(results_target) assert 'img_size' not in results_final['img_metas'].data assert 'image_file' in results_final['img_metas'].data def test_random_translation():
64
64
50
5
58
EricChan-OC/mmpose
tests/test_pipelines/test_top_down_pipelines.py
Python
test_random_translation
test_random_translation
215
222
215
215
ff371cc4e363e63a6267cf1fe7458b440a4eb375
bigcode/the-stack
train
d869eb4e06ee80eae28d7468
train
function
def _check_rot90(origin_imgs, result_imgs): if origin_imgs.shape[0] == result_imgs.shape[1] and \ origin_imgs.shape[1] == result_imgs.shape[0]: return True else: return False
def _check_rot90(origin_imgs, result_imgs):
if origin_imgs.shape[0] == result_imgs.shape[1] and \ origin_imgs.shape[1] == result_imgs.shape[0]: return True else: return False
for i in range(h): for j in range(w): for k in range(c): if result_imgs[i, j, k] != origin_imgs[i, w - 1 - j, k]: return False return True def _check_rot90(origin_imgs, result_imgs):
64
64
53
11
52
EricChan-OC/mmpose
tests/test_pipelines/test_top_down_pipelines.py
Python
_check_rot90
_check_rot90
34
39
34
34
228a8990bf1b62cd69173213ca289efcf88b19b7
bigcode/the-stack
train
76b5d323aec405c18a6b3623
train
function
def _box2cs(box, image_size): x, y, w, h = box[:4] aspect_ratio = 1. * image_size[0] / image_size[1] center = np.zeros((2), dtype=np.float32) center[0] = x + w * 0.5 center[1] = y + h * 0.5 if w > aspect_ratio * h: h = w * 1.0 / aspect_ratio elif w < aspect_ratio * h: w = h...
def _box2cs(box, image_size):
x, y, w, h = box[:4] aspect_ratio = 1. * image_size[0] / image_size[1] center = np.zeros((2), dtype=np.float32) center[0] = x + w * 0.5 center[1] = y + h * 0.5 if w > aspect_ratio * h: h = w * 1.0 / aspect_ratio elif w < aspect_ratio * h: w = h * aspect_ratio scale = np...
result_imgs.copy() for i in range(3): target_imgs[i] *= norm_cfg['std'][i] target_imgs[i] += norm_cfg['mean'][i] assert_array_almost_equal(origin_imgs, target_imgs, decimal=4) def _box2cs(box, image_size):
64
64
175
10
54
EricChan-OC/mmpose
tests/test_pipelines/test_top_down_pipelines.py
Python
_box2cs
_box2cs
52
66
52
52
f627d5372aaab0f60ee059babfba2522b3ce182e
bigcode/the-stack
train
d9516df4c829898e1dea0b7a
train
function
def _check_normalize(origin_imgs, result_imgs, norm_cfg): """Check if the origin_imgs are normalized correctly into result_imgs in a given norm_cfg.""" target_imgs = result_imgs.copy() for i in range(3): target_imgs[i] *= norm_cfg['std'][i] target_imgs[i] += norm_cfg['mean'][i] asser...
def _check_normalize(origin_imgs, result_imgs, norm_cfg):
"""Check if the origin_imgs are normalized correctly into result_imgs in a given norm_cfg.""" target_imgs = result_imgs.copy() for i in range(3): target_imgs[i] *= norm_cfg['std'][i] target_imgs[i] += norm_cfg['mean'][i] assert_array_almost_equal(origin_imgs, target_imgs, decimal=4)
_rot90(origin_imgs, result_imgs): if origin_imgs.shape[0] == result_imgs.shape[1] and \ origin_imgs.shape[1] == result_imgs.shape[0]: return True else: return False def _check_normalize(origin_imgs, result_imgs, norm_cfg):
64
64
93
14
49
EricChan-OC/mmpose
tests/test_pipelines/test_top_down_pipelines.py
Python
_check_normalize
_check_normalize
42
49
42
42
a3ad65f42462fffd59887924f3047f08f97ba1f8
bigcode/the-stack
train
4e4fc26cd6ff9dc4e6d3347c
train
function
def _check_keys_contain(result_keys, target_keys): """Check if all elements in target_keys is in result_keys.""" return set(target_keys).issubset(set(result_keys))
def _check_keys_contain(result_keys, target_keys):
"""Check if all elements in target_keys is in result_keys.""" return set(target_keys).issubset(set(result_keys))
(Collect, LoadImageFromFile, NormalizeTensor, TopDownAffine, TopDownGenerateTarget, TopDownGetRandomScaleRotation, TopDownHalfBodyTransform, ...
64
64
39
12
52
EricChan-OC/mmpose
tests/test_pipelines/test_top_down_pipelines.py
Python
_check_keys_contain
_check_keys_contain
18
20
18
18
bd16ba603cad7d0173b68eb7a75df7fba3e5444b
bigcode/the-stack
train
b73abff98a2a1a35ad36f95b
train
function
def test_top_down_pipeline(): # test loading data_prefix = 'tests/data/coco/' ann_file = osp.join(data_prefix, 'test_coco.json') coco = COCO(ann_file) results = dict(image_file=osp.join(data_prefix, '000000000785.jpg')) transform = LoadImageFromFile() results = transform(copy.deepcopy(resul...
def test_top_down_pipeline(): # test loading
data_prefix = 'tests/data/coco/' ann_file = osp.join(data_prefix, 'test_coco.json') coco = COCO(ann_file) results = dict(image_file=osp.join(data_prefix, '000000000785.jpg')) transform = LoadImageFromFile() results = transform(copy.deepcopy(results)) assert results['image_file'] == osp.join...
correctly into result_imgs in a given norm_cfg.""" target_imgs = result_imgs.copy() for i in range(3): target_imgs[i] *= norm_cfg['std'][i] target_imgs[i] += norm_cfg['mean'][i] assert_array_almost_equal(origin_imgs, target_imgs, decimal=4) def _box2cs(box, image_size): x, y, w, h...
256
256
1,722
11
244
EricChan-OC/mmpose
tests/test_pipelines/test_top_down_pipelines.py
Python
test_top_down_pipeline
test_top_down_pipeline
69
212
69
70
e8d1908a7344def583c487ff880d99383c92be96
bigcode/the-stack
train
f1bbd348392fd3f130e8b0b6
train
function
def evolve_particle_in_potential(single_star, potential, t_end): time = 0 | units.Myr dt_min = 0.1*t_end while time < t_end: acc = potential.get_gravity_at_point(single_star.position) dt = min(dt_min, 0.1*single_star.velocity.length()/acc.length()) single_star.velocity += acc*dt ...
def evolve_particle_in_potential(single_star, potential, t_end):
time = 0 | units.Myr dt_min = 0.1*t_end while time < t_end: acc = potential.get_gravity_at_point(single_star.position) dt = min(dt_min, 0.1*single_star.velocity.length()/acc.length()) single_star.velocity += acc*dt single_star.position += single_star.velocity*dt time ...
pos, vel): single_star = Particle() single_star.mass = mass single_star.position = pos single_star.velocity = vel single_star.radius = 1.0 | units.RSun return single_star def evolve_particle_in_potential(single_star, potential, t_end):
64
64
100
14
49
joshuawall/amuse
examples/simple/orbit_in_potential.py
Python
evolve_particle_in_potential
evolve_particle_in_potential
89
97
89
89
12baf346ebb53d317c63492ee22425e4db4c5936
bigcode/the-stack
train
b37cd0534399cdc4a3a8f697
train
function
def evolve_particle_trajectory_in_potential( single_star, potential, dt_diag, t_end): time = 0 | units.Myr x = [] | size_unit y = [] | size_unit z = [] | size_unit while time < t_end: evolve_particle_in_potential(single_star, potential, dt_diag) time += dt_diag print(...
def evolve_particle_trajectory_in_potential( single_star, potential, dt_diag, t_end):
time = 0 | units.Myr x = [] | size_unit y = [] | size_unit z = [] | size_unit while time < t_end: evolve_particle_in_potential(single_star, potential, dt_diag) time += dt_diag print( "time=", time, single_star.position.length().as_quantity_in(u...
= min(dt_min, 0.1*single_star.velocity.length()/acc.length()) single_star.velocity += acc*dt single_star.position += single_star.velocity*dt time += dt def evolve_particle_trajectory_in_potential( single_star, potential, dt_diag, t_end):
64
64
134
21
42
joshuawall/amuse
examples/simple/orbit_in_potential.py
Python
evolve_particle_trajectory_in_potential
evolve_particle_trajectory_in_potential
100
115
100
101
4d2bb8b5b5f494df4244ac844e44424b2a65df4d
bigcode/the-stack
train