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
d5c26d74300fed4c644bad59
train
class
class PartClassPin(object): """ Pin of a Part, but no particular Part instance. Contains general information about the pin (but it could be for any part of that type), nothing related to a specific part instance. """ well_name = None def __init__(self, names, numbers, type=PinType.UNKNOWN, ...
class PartClassPin(object):
""" Pin of a Part, but no particular Part instance. Contains general information about the pin (but it could be for any part of that type), nothing related to a specific part instance. """ well_name = None def __init__(self, names, numbers, type=PinType.UNKNOWN, well=None): self.nam...
so the functional (second) name is first. Used as a :func:`Part._postprocess_pin filter<pcbdl.Part._postprocess_pin>`. """ pin.names = pin.names[1:] + (pin.names[0],) Pin = PinFragment class PartClassPin(object):
64
64
169
6
57
maxschommer/pcbdl
pcbdl/base.py
Python
PartClassPin
PartClassPin
338
364
338
338
64f6d4570a3b4339f01f8cad863089a9339d36ce
bigcode/the-stack
train
32b5d03d3df97d9a1bc47e56
train
class
class Part(object): """ This is the :ref:`base class<python:tut-inheritance>` for any new Part the writer of a schematic or a part librarian has to make. :: class Transistor(Part): REFDES_PREFIX = "Q" PINS = ["B", "C", "E"] """ PINS = [] """ This is how the pins...
class Part(object):
""" This is the :ref:`base class<python:tut-inheritance>` for any new Part the writer of a schematic or a part librarian has to make. :: class Transistor(Part): REFDES_PREFIX = "Q" PINS = ["B", "C", "E"] """ PINS = [] """ This is how the pins of a part are defin...
: # don't let the net property create a new one, # we want to dictate the direction to that Net net = Net() #defined_at: not here net <<= self return net >> others def __str__(self): return "%r.%s" % (self.part, self.name) __repr__ = __str__ clas...
256
256
1,799
4
252
maxschommer/pcbdl
pcbdl/base.py
Python
Part
Part
459
661
459
459
727a2b0bffb37f66b37b32d22e3de45333b87895
bigcode/the-stack
train
6f730fb0b9ceba77663704e9
train
class
class Plugin(object): def __new__(cls, instance): self = super(Plugin,cls).__new__(cls) self.instance = instance return self @staticmethod def register(plugin_targets): if not isinstance(plugin_targets, collections.abc.Iterable): plugin_targets = (plugin_targets,...
class Plugin(object):
def __new__(cls, instance): self = super(Plugin,cls).__new__(cls) self.instance = instance return self @staticmethod def register(plugin_targets): if not isinstance(plugin_targets, collections.abc.Iterable): plugin_targets = (plugin_targets,) def wrapper...
either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import collections import copy import enum import itertools __all__ = [ "PinType", "ConnectDirection", "Net", "Part", "Pin" ] class Plugin(object):
64
64
176
4
60
maxschommer/pcbdl
pcbdl/base.py
Python
Plugin
Plugin
24
54
24
24
3dcc2aef356bc4c6c651339c880570c59e45e0ea
bigcode/the-stack
train
c9e797a8ff3938d98efd8723
train
class
class PinFragment(object): """ This is the fully featured (as opposed to just a tuple of parameters) element of :attr:`PINS<pcbdl.Part.PINS>` at the time of writing a :class:`Part<pcbdl.Part>`. Saves all parameters it's given, merges later once the Part is fully defined. .. warning:: Just like ...
class PinFragment(object):
""" This is the fully featured (as opposed to just a tuple of parameters) element of :attr:`PINS<pcbdl.Part.PINS>` at the time of writing a :class:`Part<pcbdl.Part>`. Saves all parameters it's given, merges later once the Part is fully defined. .. warning:: Just like the name implies this is ju...
.upper() self.has_name = True @property def connections(self): """ A :class:`tuple` of pins connected to this net. Useful in the interpreter and/or when you want to inspect your schematic:: >>> gnd.connections (U1.GND, VREG1.GND, U2.GND, VREG2.GND) ...
256
256
951
5
251
maxschommer/pcbdl
pcbdl/base.py
Python
PinFragment
PinFragment
222
335
222
222
c7f779c93d19f392a533285dfba46fdcf7f7191d
bigcode/the-stack
train
007bc07128d192c9aa615cb5
train
function
def magic_calculation(a, b): result = 0 for i in range(1, 3): try: if i > a: raise Exception("Too far") result += (a ** b) / i except Exception: result = b + a break return result
def magic_calculation(a, b):
result = 0 for i in range(1, 3): try: if i > a: raise Exception("Too far") result += (a ** b) / i except Exception: result = b + a break return result
#!/usr/bin/python3 def magic_calculation(a, b):
14
64
70
8
5
Nahi-Terefe/alx-higher_level_programming
0x05-python-exceptions/102-magic_calculation.py
Python
magic_calculation
magic_calculation
2
12
2
2
1d811576ed3d173a6749123fc18b08a09933c5e2
bigcode/the-stack
train
e13829ee8ce2f4962efa338b
train
class
class MetricsPolicyReadModel(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_...
class MetricsPolicyReadModel(object):
"""NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name ...
# coding: utf-8 """ Wavefront REST API Documentation <p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the W...
174
256
1,378
7
166
httpsgithu/python-client
wavefront_api_client/models/metrics_policy_read_model.py
Python
MetricsPolicyReadModel
MetricsPolicyReadModel
22
209
22
22
2292e684e9ca4cc0cb5a7bf249c555d487328810
bigcode/the-stack
train
9d66b91d0b787cadb4c8c4d7
train
function
def main(): parser = argparse.ArgumentParser() parser.add_argument("email", help="the email address to log in to Favro with") parser.add_argument("password", help="the password to log in to Favro with") parser.add_argument("organization_id", help="the id of the Favro organization") parser.add_argume...
def main():
parser = argparse.ArgumentParser() parser.add_argument("email", help="the email address to log in to Favro with") parser.add_argument("password", help="the password to log in to Favro with") parser.add_argument("organization_id", help="the id of the Favro organization") parser.add_argument("collecti...
from lib.app.app import App import argparse def main():
13
64
136
3
9
RobPethick/Favrobot
main.py
Python
main
main
4
18
4
4
00eca853e2e366c84dee5ecdf95d47332fe13bd0
bigcode/the-stack
train
5d8df5386f8b877a12647717
train
function
def _set_tcp_keepalive(zmq_socket, opts): """ Ensure that TCP keepalives are set as specified in "opts". Warning: Failure to set TCP keepalives on the salt-master can result in not detecting the loss of a minion when the connection is lost or when its host has been terminated without first closing ...
def _set_tcp_keepalive(zmq_socket, opts):
""" Ensure that TCP keepalives are set as specified in "opts". Warning: Failure to set TCP keepalives on the salt-master can result in not detecting the loss of a minion when the connection is lost or when its host has been terminated without first closing the socket. Salt's Presence System dep...
a ".format(self.__class__.__name__) if signum == signal.SIGINT: msg += "SIGINT" elif signum == signal.SIGTERM: msg += "SIGTERM" msg += ". Exiting" log.debug(msg) self.close() sys.exit(salt.defaults.exitcodes.EX_OK) def _set_tcp_keepalive(zmq_socke...
82
82
276
12
70
babs/salt
salt/transport/zeromq.py
Python
_set_tcp_keepalive
_set_tcp_keepalive
915
936
915
915
cfb64b82cee3dc05770667782a61b406e075636c
bigcode/the-stack
train
b7dc5266ed1240d4eadf945d
train
class
class AsyncZeroMQReqChannel(salt.transport.client.ReqChannel): """ Encapsulate sending routines to ZeroMQ. ZMQ Channels default to 'crypt=aes' """ # This class is only a singleton per minion/master pair # mapping of io_loop -> {key -> channel} instance_map = weakref.WeakKeyDictionary() ...
class AsyncZeroMQReqChannel(salt.transport.client.ReqChannel):
""" Encapsulate sending routines to ZeroMQ. ZMQ Channels default to 'crypt=aes' """ # This class is only a singleton per minion/master pair # mapping of io_loop -> {key -> channel} instance_map = weakref.WeakKeyDictionary() async_methods = [ "crypted_transfer_decode_dictentry",...
source_port: master_uri = "tcp://{source_ip}:0;{master_ip}:{master_port}".format( source_ip=ip_bracket(source_ip), master_ip=ip_bracket(master_ip), master_port=master_port, ) elif source_port and not source_ip: ...
256
256
2,614
14
241
babs/salt
salt/transport/zeromq.py
Python
AsyncZeroMQReqChannel
AsyncZeroMQReqChannel
124
446
124
124
76a1b626e5f38f4792f7b64460c4c35fdf7a416a
bigcode/the-stack
train
c88441aabe0baadff44bb2dd
train
class
class ZeroMQSocketMonitor: __EVENT_MAP = None def __init__(self, socket): """ Create ZMQ monitor sockets More information: http://api.zeromq.org/4-0:zmq-socket-monitor """ self._socket = socket self._monitor_socket = self._socket.get_monitor_socket()...
class ZeroMQSocketMonitor:
__EVENT_MAP = None def __init__(self, socket): """ Create ZMQ monitor sockets More information: http://api.zeromq.org/4-0:zmq-socket-monitor """ self._socket = socket self._monitor_socket = self._socket.get_monitor_socket() self._monitor_stre...
self.io_loop.add_callback(callback, response) future.add_done_callback(handle_future) # Add this future to the mapping self.send_future_map[message] = future if self.opts.get("detect_mode") is True: timeout = 1 if timeout is not None: ...
137
137
458
6
130
babs/salt
salt/transport/zeromq.py
Python
ZeroMQSocketMonitor
ZeroMQSocketMonitor
1,415
1,474
1,415
1,415
cbaac5ed355770d0a397c7c43d3a8f86e6e0eed4
bigcode/the-stack
train
acc9218d6f37ee0f538715f9
train
class
class AsyncZeroMQPubChannel( salt.transport.mixins.auth.AESPubClientMixin, salt.transport.client.AsyncPubChannel ): """ A transport channel backed by ZeroMQ for a Salt Publisher to use to publish commands to connected minions """ async_methods = [ "connect", "_decode_messages", ...
class AsyncZeroMQPubChannel( salt.transport.mixins.auth.AESPubClientMixin, salt.transport.client.AsyncPubChannel ):
""" A transport channel backed by ZeroMQ for a Salt Publisher to use to publish commands to connected minions """ async_methods = [ "connect", "_decode_messages", ] close_methods = [ "close", ] def __init__(self, opts, **kwargs): self.opts = opts ...
def _uncrypted_transfer(self, load, tries=3, timeout=60): """ Send a load across the wire in cleartext :param dict load: A load to send across the wire :param int tries: The number of times to make before failure :param int timeout: The number of seconds on a response before fa...
256
256
1,690
27
229
babs/salt
salt/transport/zeromq.py
Python
AsyncZeroMQPubChannel
AsyncZeroMQPubChannel
449
668
449
451
44d7e36854adb93f75e53ae19f50167382c611fa
bigcode/the-stack
train
b46a1bce75ee13bb478d525b
train
class
class AsyncReqMessageClientPool(salt.transport.MessageClientPool): """ Wrapper class of AsyncReqMessageClientPool to avoid blocking waiting while writing data to socket. """ def __init__(self, opts, args=None, kwargs=None): self._closing = False super().__init__(AsyncReqMessageClient, o...
class AsyncReqMessageClientPool(salt.transport.MessageClientPool):
""" Wrapper class of AsyncReqMessageClientPool to avoid blocking waiting while writing data to socket. """ def __init__(self, opts, args=None, kwargs=None): self._closing = False super().__init__(AsyncReqMessageClient, opts, args=args, kwargs=kwargs) def close(self): if sel...
jid=%s size=%d", load.get("jid", None), len(payload), ) if not self.pub_sock: self.pub_connect() self.pub_sock.send(payload) log.debug("Sent payload to publish daemon.") class AsyncReqMessageClientPool(salt.transport.MessageClientPool):
63
64
186
13
50
babs/salt
salt/transport/zeromq.py
Python
AsyncReqMessageClientPool
AsyncReqMessageClientPool
1,181
1,207
1,181
1,181
801d2feb582f47e33a14392d70f98d1535f074f3
bigcode/the-stack
train
316af671f1b3c3b6bdc32cf3
train
class
class AsyncReqMessageClient: """ This class wraps the underlying zeromq REQ socket and gives a future-based interface to sending and recieving messages. This works around the primary limitation of serialized send/recv on the underlying socket by queueing the message sends in this class. In the futur...
class AsyncReqMessageClient:
""" This class wraps the underlying zeromq REQ socket and gives a future-based interface to sending and recieving messages. This works around the primary limitation of serialized send/recv on the underlying socket by queueing the message sends in this class. In the future if we decide to attempt to ...
"Sending payload to publish daemon. jid=%s size=%d", load.get("jid", None), len(payload), ) if not self.pub_sock: self.pub_connect() self.pub_sock.send(payload) log.debug("Sent payload to publish daemon.") class AsyncReqMessageClientPool(salt.transp...
256
256
1,564
6
250
babs/salt
salt/transport/zeromq.py
Python
AsyncReqMessageClient
AsyncReqMessageClient
1,211
1,412
1,211
1,211
d70b6278389db54132565652b2d8a64ed982fd71
bigcode/the-stack
train
6a1145c62cdd605c4a92010d
train
class
class ZeroMQPubServerChannel(salt.transport.server.PubServerChannel): """ Encapsulate synchronous operations for a publisher channel """ _sock_data = threading.local() def __init__(self, opts): self.opts = opts self.serial = salt.payload.Serial(self.opts) # TODO: in init? ...
class ZeroMQPubServerChannel(salt.transport.server.PubServerChannel):
""" Encapsulate synchronous operations for a publisher channel """ _sock_data = threading.local() def __init__(self, opts): self.opts = opts self.serial = salt.payload.Serial(self.opts) # TODO: in init? self.ckminions = salt.utils.minions.CkMinions(self.opts) def conn...
keepalives on the salt-master can result in not detecting the loss of a minion when the connection is lost or when its host has been terminated without first closing the socket. Salt's Presence System depends on this connection status to know if a minion is "present". Warning: Failure to set TCP k...
255
256
2,154
15
240
babs/salt
salt/transport/zeromq.py
Python
ZeroMQPubServerChannel
ZeroMQPubServerChannel
939
1,178
939
939
bac11ac05bd6c4deddb9bbc7578110c791278e2b
bigcode/the-stack
train
66b45dea8ab119aa029ad079
train
function
def _get_master_uri(master_ip, master_port, source_ip=None, source_port=None): """ Return the ZeroMQ URI to connect the Minion to the Master. It supports different source IP / port, given the ZeroMQ syntax: // Connecting using a IP address and bind to an IP address rc = zmq_connect(socket, "tcp://19...
def _get_master_uri(master_ip, master_port, source_ip=None, source_port=None):
""" Return the ZeroMQ URI to connect the Minion to the Master. It supports different source IP / port, given the ZeroMQ syntax: // Connecting using a IP address and bind to an IP address rc = zmq_connect(socket, "tcp://192.168.1.17:5555;192.168.1.1:5555"); assert (rc == 0); Source: http://api.ze...
SaltException, SaltReqTimeoutError from salt.utils.zeromq import ( LIBZMQ_VERSION_INFO, ZMQ_VERSION_INFO, ZMQDefaultLoop, install_zmq, zmq, ) try: import zmq.utils.monitor HAS_ZMQ_MONITOR = True except ImportError: HAS_ZMQ_MONITOR = False try: from M2Crypto import RSA HAS_M...
172
172
574
19
153
babs/salt
salt/transport/zeromq.py
Python
_get_master_uri
_get_master_uri
69
121
69
69
3a9e7d61e6e4b38ddeb94cd270d20783233d6bbe
bigcode/the-stack
train
79d323c302577336dcd6e823
train
class
class ZeroMQReqServerChannel( salt.transport.mixins.auth.AESReqServerMixin, salt.transport.server.ReqServerChannel ): def __init__(self, opts): salt.transport.server.ReqServerChannel.__init__(self, opts) self._closing = False self._monitor = None self._w_monitor = None def z...
class ZeroMQReqServerChannel( salt.transport.mixins.auth.AESReqServerMixin, salt.transport.server.ReqServerChannel ):
def __init__(self, opts): salt.transport.server.ReqServerChannel.__init__(self, opts) self._closing = False self._monitor = None self._w_monitor = None def zmq_device(self): """ Multiprocessing target for the zmq queue device """ self.__setup_sign...
_len)) ) # Yield control back to the caller. When the payload has been decoded, assign # the decoded payload to 'ret' and resume operation ret = yield self._decode_payload(payload) raise salt.ext.tornado.gen.Return(ret) @property def stream(self): """ ...
256
256
2,116
28
228
babs/salt
salt/transport/zeromq.py
Python
ZeroMQReqServerChannel
ZeroMQReqServerChannel
671
912
671
673
2e5fc5a7b4659be88b6b50ab1e7db32dab400618
bigcode/the-stack
train
fceb6e6b349c527eb3262835
train
class
class ModelGAN(ModelBase): """Train with pixel-VGG-GAN loss""" def __init__(self, opt): super(ModelGAN, self).__init__(opt) # ------------------------------------ # define network # ------------------------------------ self.netG = define_G(opt).to(self.device) sel...
class ModelGAN(ModelBase):
"""Train with pixel-VGG-GAN loss""" def __init__(self, opt): super(ModelGAN, self).__init__(opt) # ------------------------------------ # define network # ------------------------------------ self.netG = define_G(opt).to(self.device) self.netG = DataParallel(self....
from collections import OrderedDict import torch import torch.nn as nn from torch.optim import lr_scheduler from torch.optim import Adam from torch.nn.parallel import DataParallel # , DistributedDataParallel from models.select_network import define_G, define_D, define_F from models.model_base import ModelBase from mo...
87
256
2,547
6
80
Easonrust/Image_Denoising_Zoo
models/model_gan.py
Python
ModelGAN
ModelGAN
14
306
14
14
a60ce586a5049caa821c4ac64a26e9952bf29942
bigcode/the-stack
train
d92ac4d2aaccaa0667729ed9
train
function
def main(): fig, ax = plt.subplots(2, 2, sharex='col', sharey='row') X = np.random.normal(0, 1, (2, 100)) for i in range(2): for j in range(2): points = ax[1 - i, j].scatter(X[i], X[j]) plugins.connect(fig, plugins.LinkedBrush(points)) return fig
def main():
fig, ax = plt.subplots(2, 2, sharex='col', sharey='row') X = np.random.normal(0, 1, (2, 100)) for i in range(2): for j in range(2): points = ax[1 - i, j].scatter(X[i], X[j]) plugins.connect(fig, plugins.LinkedBrush(points)) return fig
import mpld3 from mpld3 import plugins import matplotlib.pyplot as plt import numpy as np def main():
26
64
92
3
22
silky/mpld3
test_plots/test_linkedbrush.py
Python
main
main
6
16
6
6
4f0450347d53975e18e629c888f6d82f6c62ad74
bigcode/the-stack
train
e2eabdc8ccae676ca3816b0c
train
class
class User(db.Model): __tablename__ = 'usr_info' id = db.Column(db.String(40),primary_key=True) password = db.Column(db.String(40)) name = db.Column(db.String(40),unique=False,nullable=False) email = db.Column(db.String(40),unique=False,nullable=False) dir_path = db.Column(db.String(200),u...
class User(db.Model):
__tablename__ = 'usr_info' id = db.Column(db.String(40),primary_key=True) password = db.Column(db.String(40)) name = db.Column(db.String(40),unique=False,nullable=False) email = db.Column(db.String(40),unique=False,nullable=False) dir_path = db.Column(db.String(200),unique=False,nullable=Tr...
from flask import current_app from flask_sqlalchemy import SQLAlchemy import pymysql db = SQLAlchemy(current_app) class User(db.Model):
30
64
160
5
25
Ekkosun/INC
db.py
Python
User
User
9
29
9
9
2cb228746a4e489d9d5ef074ea48ef5d0fc2e163
bigcode/the-stack
train
ffa484526bc8e261d14e1644
train
class
class Example(db.Model): __tablename__ = 'example' id = db.Column(db.String(40),unique=False) name = db.Column(db.String(40),unique=False) description = db.Column(db.String(40),unique=False,nullable=False) dir_path = db.Column(db.String(200),primary_key=True) def __repr__(self): ...
class Example(db.Model):
__tablename__ = 'example' id = db.Column(db.String(40),unique=False) name = db.Column(db.String(40),unique=False) description = db.Column(db.String(40),unique=False,nullable=False) dir_path = db.Column(db.String(200),primary_key=True) def __repr__(self): return '<id %r>' % self.i...
% self.id def add(id,password,name,email): user_obj = User(id=id,password=password,name=name,dir_path="",email=email) db.session.add(user_obj) db.session.commit() def find(id): find = User.query.get(id) return find class Example(db.Model):
64
64
175
5
58
Ekkosun/INC
db.py
Python
Example
Example
31
54
31
31
34346858cde07237a9a9f3bd0f08762f2a04bad1
bigcode/the-stack
train
8c789e6697a21ef893865fb0
train
function
@app.route('/think/') def think_handler(): thoughts = requests.get('http://thinker:8000/', headers={ 'x-datadog-trace-id': str(tracer.current_span().trace_id), 'x-datadog-parent-id': str(tracer.current_span().span_id), }, params={ 'subject': flask_request.args.getlist('subject', str...
@app.route('/think/') def think_handler():
thoughts = requests.get('http://thinker:8000/', headers={ 'x-datadog-trace-id': str(tracer.current_span().trace_id), 'x-datadog-parent-id': str(tracer.current_span().span_id), }, params={ 'subject': flask_request.args.getlist('subject', str), }).content return Response(thoughts,...
from ddtrace import tracer from ddtrace.contrib.flask import TraceMiddleware # Tracer configuration tracer.configure(hostname='datadog') app = Flask('API') traced_app = TraceMiddleware(app, tracer, service='thinker-api') @app.route('/think/') def think_handler():
64
64
100
10
54
l0k0ms/TrainingEnvironment
logsintro/app/api.py
Python
think_handler
think_handler
18
28
18
20
4feca88570e74ba7452318c03b0ac8752b1c2579
bigcode/the-stack
train
e3ae4c89568890aec6bc000f
train
function
def farmer_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='signup'): ''' Decorator for views that checks that the logged in user is a student, redirects to the log-in page if necessary. ''' actual_decorator = user_passes_test( lambda u: u.is_active and (not u.is_f...
def farmer_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='signup'):
''' Decorator for views that checks that the logged in user is a student, redirects to the log-in page if necessary. ''' actual_decorator = user_passes_test( lambda u: u.is_active and (not u.is_farmer), login_url=login_url, redirect_field_name=redirect_field_name ) if...
from django.contrib.auth import REDIRECT_FIELD_NAME from django.contrib.auth.decorators import user_passes_test def farmer_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='signup'):
41
64
110
20
20
Harshvartak/TSEC-Codestorm
FarmerApp/decorators.py
Python
farmer_required
farmer_required
5
17
5
5
af8a1d393e804a903e0c8a8c3fa421b0e1a08f58
bigcode/the-stack
train
1d324fbca4d74b7a13726b9f
train
function
def buyer_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='signup'): ''' Decorator for views that checks that the logged in user is a teacher, redirects to the log-in page if necessary. ''' actual_decorator = user_passes_test( lambda u: u.is_active and u.is_buyer, ...
def buyer_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='signup'):
''' Decorator for views that checks that the logged in user is a teacher, redirects to the log-in page if necessary. ''' actual_decorator = user_passes_test( lambda u: u.is_active and u.is_buyer, login_url=login_url, redirect_field_name=redirect_field_name ) if functi...
_active and (not u.is_farmer), login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator def buyer_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='signup'):
64
64
108
20
43
Harshvartak/TSEC-Codestorm
FarmerApp/decorators.py
Python
buyer_required
buyer_required
19
31
19
19
589031f480ca2579a84e1c4a9542ecb73d4e9d6a
bigcode/the-stack
train
c22b7bedfafb3bc2d36fea87
train
class
class FileTest(TestCase): def assertSameFile(self, a, b, exclude=set(), seen=None): if seen is None: seen = set() seen.add(id(a)) self.assertEqual(type(a), type(b)) keys = ((set(a.__dict__.keys()) | set(b.__dict__.keys())) - exclude - {'creator', 'post_in...
class FileTest(TestCase):
def assertSameFile(self, a, b, exclude=set(), seen=None): if seen is None: seen = set() seen.add(id(a)) self.assertEqual(type(a), type(b)) keys = ((set(a.__dict__.keys()) | set(b.__dict__.keys())) - exclude - {'creator', 'post_install'}) for i in...
bfg9000 import file_types from bfg9000.builtins import builtin from bfg9000.build_inputs import BuildInputs from bfg9000.path import Path, Root class AlwaysEqual: def __eq__(self, rhs): return True class FileTest(TestCase):
64
64
183
6
57
Mattlk13/bfg9000
test/unit/builtins/common.py
Python
FileTest
FileTest
14
33
14
14
faee7ab8ef381af804c82229d63c2da4d70b3855
bigcode/the-stack
train
a999fcf7bbdab2445314dc7c
train
class
class BuiltinTest(FileTest): def setUp(self): self.env = make_env() self.build, self.context = self._make_context(self.env) self.bfgfile = file_types.File(self.build.bfgpath) def _make_context(self, env): build = BuildInputs(env, Path('build.bfg', Root.srcdir)) context =...
class BuiltinTest(FileTest):
def setUp(self): self.env = make_env() self.build, self.context = self._make_context(self.env) self.bfgfile = file_types.File(self.build.bfgpath) def _make_context(self, env): build = BuildInputs(env, Path('build.bfg', Root.srcdir)) context = builtin.BuildContext(env, bu...
) ): if not id(ai) in seen: self.assertSameFile(ai, bi, exclude, seen) else: self.assertEqual( ai, bi, '{!r}: {!r} != {!r}'.format(i, ai, bi) ) class BuiltinTest(FileTest):
64
64
112
7
57
Mattlk13/bfg9000
test/unit/builtins/common.py
Python
BuiltinTest
BuiltinTest
36
48
36
36
a8dc687c6e34d6d3ff8b1c1b45258f9f20a8a045
bigcode/the-stack
train
788111ac1520ebcc44e618cb
train
class
class AlwaysEqual: def __eq__(self, rhs): return True
class AlwaysEqual:
def __eq__(self, rhs): return True
from .. import AttrDict, make_env, TestCase # noqa from bfg9000 import file_types from bfg9000.builtins import builtin from bfg9000.build_inputs import BuildInputs from bfg9000.path import Path, Root class AlwaysEqual:
61
64
17
4
56
Mattlk13/bfg9000
test/unit/builtins/common.py
Python
AlwaysEqual
AlwaysEqual
9
11
9
9
737e17d947c5ca6c5b9ca7f3f7b3d254899a2b91
bigcode/the-stack
train
aa51c9aab25cf4ef5a493039
train
class
class Application(models.Model): sno = models.AutoField(primary_key=True) name = models.CharField(max_length=40) email = models.CharField(max_length=60) desc = models.TextField() phone = models.CharField(max_length=10, default="") position = models.CharField(max_length=20, default="NOT SPECIFIED") def __str__(s...
class Application(models.Model):
sno = models.AutoField(primary_key=True) name = models.CharField(max_length=40) email = models.CharField(max_length=60) desc = models.TextField() phone = models.CharField(max_length=10, default="") position = models.CharField(max_length=20, default="NOT SPECIFIED") def __str__(self): return self.name
09, 2020") tag = models.CharField(max_length=30, default="General") read_time = models.CharField(max_length=11, default="7 MIN READ") slug = models.CharField(max_length=100) def __str__(self): return self.title class Application(models.Model):
64
64
81
5
58
pranjalbareth/codeplay
blog/models.py
Python
Application
Application
21
30
21
21
557fc1ba171e4cd67d01533e3ca4e35b96b0708c
bigcode/the-stack
train
c8be1f90f917c992f41482ff
train
class
class Blog(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE) sno = models.AutoField(primary_key=True) title = models.CharField(max_length=200) content = models.TextField() short_desc = models.CharField(max_length=300, default="") poster = models.ImageField(defa...
class Blog(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE) sno = models.AutoField(primary_key=True) title = models.CharField(max_length=200) content = models.TextField() short_desc = models.CharField(max_length=300, default="") poster = models.ImageField(default="") created = models...
from django.db import models from datetime import date from django.conf import settings # Create your models here. class Blog(models.Model):
28
64
147
5
23
pranjalbareth/codeplay
blog/models.py
Python
Blog
Blog
6
19
6
6
bb1188af9c2387377bc6145f25848c15327b482c
bigcode/the-stack
train
2fdddb689b98c05cfbe270c2
train
class
class Convert: def __init__(self, options: Options, ) -> None: self.options: Options = options def process(self): from_schemes: Schemes = self.options.from_schemes to_schemes: Schemes = self.options.to_schemes version: str = self.options.versio...
class Convert:
def __init__(self, options: Options, ) -> None: self.options: Options = options def process(self): from_schemes: Schemes = self.options.from_schemes to_schemes: Schemes = self.options.to_schemes version: str = self.options.version if not...
from __future__ import annotations from FlexioFlow.Options import Options from Schemes.DevPrefix import DevPrefix from Schemes.Schemes import Schemes from typing import Dict class Convert:
42
64
123
3
38
flexiooss/flexio-flow
src/FlexioFlow/Actions/Convert.py
Python
Convert
Convert
9
26
9
10
2f6d12ddec5c5686dfa1a32a7d012dd985361ed0
bigcode/the-stack
train
0a256b19fab3277eb72f8f5d
train
function
def get_args(): parser = argparse.ArgumentParser("Deep Q Network") parser.add_argument("--device", default=device, help="GPU or CPU") parser.add_argument("--seed", type=int, default=123, help="random seed") parser.add_argument("--env-name", type=str, default="LunarLanderContinuous-v2", help="name of t...
def get_args():
parser = argparse.ArgumentParser("Deep Q Network") parser.add_argument("--device", default=device, help="GPU or CPU") parser.add_argument("--seed", type=int, default=123, help="random seed") parser.add_argument("--env-name", type=str, default="LunarLanderContinuous-v2", help="name of the scenario scri...
# Copyright (c) 2021: Zhiyuan Nan (namjw@hanyang.ac.kr). # # This work is licensed under the terms of the MIT license. # For a copy, see <https://opensource.org/licenses/MIT>. import argparse import torch as T device = T.device('cuda:0' if T.cuda.is_available() else 'cpu') def get_args():
83
204
680
4
79
namjiwon1023/Code_With_RL
tutorials/SAC/utils/arguments.py
Python
get_args
get_args
11
55
11
11
345af5e21774856beb8d525ae838bc56f72c9275
bigcode/the-stack
train
b19a8a3ee5a1c0746af30aab
train
function
def create_site(apps, schema_editor): Site = apps.get_model("sites", "Site") custom_domain = "ideapros-llc-graffi-31959.botics.co" site_params = { "name": "IdeaPros LLC - Graffiti", } if custom_domain: site_params["domain"] = custom_domain Site.objects.update_or_create(defaults...
def create_site(apps, schema_editor):
Site = apps.get_model("sites", "Site") custom_domain = "ideapros-llc-graffi-31959.botics.co" site_params = { "name": "IdeaPros LLC - Graffiti", } if custom_domain: site_params["domain"] = custom_domain Site.objects.update_or_create(defaults=site_params, id=1)
from django.db import migrations def create_site(apps, schema_editor):
15
64
92
9
5
crowdbotics-apps/ideapros-llc-graffi-31959
backend/home/migrations/0001_load_initial_data.py
Python
create_site
create_site
4
14
4
4
bc2a35ba75a1c7589cf9bf1e29a4f549c574c815
bigcode/the-stack
train
3b0a58031b70ff23bdfd2235
train
class
class Migration(migrations.Migration): dependencies = [ ("sites", "0002_alter_domain_unique"), ] operations = [ migrations.RunPython(create_site), ]
class Migration(migrations.Migration):
dependencies = [ ("sites", "0002_alter_domain_unique"), ] operations = [ migrations.RunPython(create_site), ]
-31959.botics.co" site_params = { "name": "IdeaPros LLC - Graffiti", } if custom_domain: site_params["domain"] = custom_domain Site.objects.update_or_create(defaults=site_params, id=1) class Migration(migrations.Migration):
64
64
38
7
57
crowdbotics-apps/ideapros-llc-graffi-31959
backend/home/migrations/0001_load_initial_data.py
Python
Migration
Migration
17
25
17
18
a00e759b1f365f6ee5c2b777b5b85c800f49887b
bigcode/the-stack
train
f13fbd7d74e25e9c84eedc02
train
function
def log_proj(run, proj_path): try: from jammy.utils import git except ImportError: return None proj_sha, proj_diff = git.log_repo(proj_path) with open("proj_change.patch", "w") as f: f.write(proj_diff) run.save("proj_change.patch") return proj_sha
def log_proj(run, proj_path):
try: from jammy.utils import git except ImportError: return None proj_sha, proj_diff = git.log_repo(proj_path) with open("proj_change.patch", "w") as f: f.write(proj_diff) run.save("proj_change.patch") return proj_sha
except ImportError: return None jam_sha, jam_diff = get_jam_repo_git() with open("jam_change.patch", "w") as f: f.write(jam_diff) run.save("jam_change.patch") return jam_sha def log_proj(run, proj_path):
64
64
76
8
55
qshzh/lightning-hydra-template
src/logger/jam_wandb.py
Python
log_proj
log_proj
61
70
61
61
f3a6c1d5116ddfcff30135f375fdbcd39ebb3c9a
bigcode/the-stack
train
7dfbcb15fc4712187527074e
train
function
def log_hydra(run): shutil.copyfile( os.path.join(os.getcwd(), ".hydra/config.yaml"), os.path.join(os.getcwd(), ".hydra/hydra-config.yaml"), ) run.save(os.path.join(os.getcwd(), ".hydra/hydra-config.yaml")) run.save(os.path.join(os.getcwd(), ".hydra/overrides.yaml"))
def log_hydra(run):
shutil.copyfile( os.path.join(os.getcwd(), ".hydra/config.yaml"), os.path.join(os.getcwd(), ".hydra/hydra-config.yaml"), ) run.save(os.path.join(os.getcwd(), ".hydra/hydra-config.yaml")) run.save(os.path.join(os.getcwd(), ".hydra/overrides.yaml"))
except ImportError: return None proj_sha, proj_diff = git.log_repo(proj_path) with open("proj_change.patch", "w") as f: f.write(proj_diff) run.save("proj_change.patch") return proj_sha def log_hydra(run):
64
64
78
7
56
qshzh/lightning-hydra-template
src/logger/jam_wandb.py
Python
log_hydra
log_hydra
73
79
73
73
8171c40c3001b418e5d6b4800c9a1e91dac32f87
bigcode/the-stack
train
24f7c587671ba7250fde42a1
train
class
class JamWandb: g_cfg = None run = None @property def cfg(self): return JamWandb.g_cfg @cfg.setter def cfg(self, g_cfg): JamWandb.g_cfg = g_cfg @staticmethod def prep_cfg(dump_meta=True): if JamWandb.g_cfg is None: raise RuntimeError("Set JamWandb g...
class JamWandb:
g_cfg = None run = None @property def cfg(self): return JamWandb.g_cfg @cfg.setter def cfg(self, g_cfg): JamWandb.g_cfg = g_cfg @staticmethod def prep_cfg(dump_meta=True): if JamWandb.g_cfg is None: raise RuntimeError("Set JamWandb g_cfg firstly") ...
with open("proj_change.patch", "w") as f: f.write(proj_diff) run.save("proj_change.patch") return proj_sha def log_hydra(run): shutil.copyfile( os.path.join(os.getcwd(), ".hydra/config.yaml"), os.path.join(os.getcwd(), ".hydra/hydra-config.yaml"), ) run.save(os.path.join(o...
117
118
394
6
111
qshzh/lightning-hydra-template
src/logger/jam_wandb.py
Python
JamWandb
JamWandb
82
135
82
82
72b966ec747265f0a3120a5efb9f8bffa97c348c
bigcode/the-stack
train
3a39f680a710795324194c5b
train
function
def log_jam(run): try: from jammy import get_jam_repo_git except ImportError: return None jam_sha, jam_diff = get_jam_repo_git() with open("jam_change.patch", "w") as f: f.write(jam_diff) run.save("jam_change.patch") return jam_sha
def log_jam(run):
try: from jammy import get_jam_repo_git except ImportError: return None jam_sha, jam_diff = get_jam_repo_git() with open("jam_change.patch", "w") as f: f.write(jam_diff) run.save("jam_change.patch") return jam_sha
msg += "{}: {}\n".format(k.upper(), v) msg += "=================================================================================================================================\n" # noqa: E501 return msg def to_dict(self): return {k.upper(): v for k, v in self.__dict__.items()} def log_ja...
63
64
76
6
57
qshzh/lightning-hydra-template
src/logger/jam_wandb.py
Python
log_jam
log_jam
48
58
48
48
501ee064d34f7d9d67f202dae57914b64c03dd7d
bigcode/the-stack
train
52dbc826dccf82ffb2f222bd
train
class
class WandbUrls: # pylint: disable=too-few-public-methods def __init__(self, url): url_hash = url.split("/")[-1] project = url.split("/")[-3] entity = url.split("/")[-4] self.weight_url = url self.log_url = "https://app.wandb.ai/{}/{}/runs/{}/logs".format( enti...
class WandbUrls: # pylint: disable=too-few-public-methods
def __init__(self, url): url_hash = url.split("/")[-1] project = url.split("/")[-3] entity = url.split("/")[-4] self.weight_url = url self.log_url = "https://app.wandb.ai/{}/{}/runs/{}/logs".format( entity, project, url_hash ) self.chart_url = "h...
import os import shutil import socket from omegaconf import OmegaConf class WandbUrls: # pylint: disable=too-few-public-methods
36
106
355
18
17
qshzh/lightning-hydra-template
src/logger/jam_wandb.py
Python
WandbUrls
WandbUrls
8
45
8
8
fdbce45cd712ceab27a0b9b346ab03deff2d7bf9
bigcode/the-stack
train
d639c884dff7379a0c597da6
train
class
class TaasExtensionManager(object): def get_resources(self): ext_taas.RESOURCE_ATTRIBUTE_MAP['tap_flows'].update( ext_taas_vlan_filter.EXTENDED_ATTRIBUTES_2_0['tap_flows']) return ext_taas.Taas.get_resources() def get_actions(self): return [] def get_request_extensions...
class TaasExtensionManager(object):
def get_resources(self): ext_taas.RESOURCE_ATTRIBUTE_MAP['tap_flows'].update( ext_taas_vlan_filter.EXTENDED_ATTRIBUTES_2_0['tap_flows']) return ext_taas.Taas.get_resources() def get_actions(self): return [] def get_request_extensions(self): return []
_TAAS_PLUGIN_KLASS = ('neutron_taas.services.taas.taas_plugin.TaasPlugin') MN_TAAS_DRIVER_KLASS = ('midonet.neutron.services.taas.service_drivers.' 'taas_midonet.MidonetTaasDriver') class TaasExtensionManager(object):
64
64
76
7
57
NeCTAR-RC/networking-midonet
midonet/neutron/tests/unit/test_extension_taas.py
Python
TaasExtensionManager
TaasExtensionManager
43
54
43
44
971b76bd9fa2a41b2a7274d9897407a1cc4b9ef1
bigcode/the-stack
train
1ca5886daf832115ecc52b16
train
class
class TestMidonetTaasCaseML2(TestMidonetTaasCaseMixin, test_mn_ml2.MidonetPluginML2TestCase): pass
class TestMidonetTaasCaseML2(TestMidonetTaasCaseMixin, test_mn_ml2.MidonetPluginML2TestCase):
pass
.assert_called_with(mock.ANY, tf['id']) self.client_mock.delete_tap_service.assert_called_with(mock.ANY, ts['id']) class TestMidonetTaasCaseML2(TestMidonetTaasCaseMixin, test_mn_ml2.MidonetPluginML2TestCase):
63
64
35
32
31
NeCTAR-RC/networking-midonet
midonet/neutron/tests/unit/test_extension_taas.py
Python
TestMidonetTaasCaseML2
TestMidonetTaasCaseML2
252
254
252
253
958341d6f2cf3c5c6eba667446981a7260f02618
bigcode/the-stack
train
e2a2bc19d24117771b2b87ac
train
class
class TestMidonetTaasCaseMixin(object): resource_prefix_map = dict( (k, TAAS_PREFIX) for k in ext_taas.RESOURCE_ATTRIBUTE_MAP.keys() ) def setUp(self, plugin=None, service_plugins=None, ext_mgr=None): ext_mgr = TaasExtensionManager() service_plugins = {'taas_plugin_name': DB...
class TestMidonetTaasCaseMixin(object):
resource_prefix_map = dict( (k, TAAS_PREFIX) for k in ext_taas.RESOURCE_ATTRIBUTE_MAP.keys() ) def setUp(self, plugin=None, service_plugins=None, ext_mgr=None): ext_mgr = TaasExtensionManager() service_plugins = {'taas_plugin_name': DB_TAAS_PLUGIN_KLASS} taas_provide...
test_ex from neutron_taas.common import constants as taas_const from neutron_taas.extensions import taas as ext_taas from neutron_taas.extensions import vlan_filter as ext_taas_vlan_filter from neutron_taas.tests.unit.services.taas import test_taas_plugin # noqa from midonet.neutron.tests.unit import test_midonet_pl...
255
256
1,988
10
245
NeCTAR-RC/networking-midonet
midonet/neutron/tests/unit/test_extension_taas.py
Python
TestMidonetTaasCaseMixin
TestMidonetTaasCaseMixin
57
249
57
57
c11390cc67108e5273728d18935232286d34e1f2
bigcode/the-stack
train
d4bec640f8c840ba49555f17
train
class
class tfl_op: """Class to implement the decorator to register handlers that map tflite to tf or onnx.""" def __init__(self, name, domain=constants.ONNX_DOMAIN, **kwargs): """Called decorator from decorator. :param name: The name (or list of names) of the tflite operator. :param domain:...
class tfl_op:
"""Class to implement the decorator to register handlers that map tflite to tf or onnx.""" def __init__(self, name, domain=constants.ONNX_DOMAIN, **kwargs): """Called decorator from decorator. :param name: The name (or list of names) of the tflite operator. :param domain: The domain th...
there is a custom op that overrides a onnx op ... :param name: The operator name. :param domain: The domain to use (optional). """ if domain is None: map_info = tf_op._MAPPING.get(name) else: map_info = tf_op._DOMAIN_MAPPING[domain].get(name) ...
94
94
316
5
88
tensorleap/tensorflow-onnx
tf2onnxnightly/handler.py
Python
tfl_op
tfl_op
125
152
125
125
4ee8130fdf4e291d792206fbefe27d0ea7c348e6
bigcode/the-stack
train
a97f0c4fc548f4a0bb7d4832
train
class
class tf_op: """Class to implement the decorator to register handlers that map tf to onnx.""" # Maps domains (string) to lists (idx represents opset) of dicts (key = op to handle, value = handler) _OPSETS = collections.OrderedDict() # Cache of mapping for current domain and opset. Maps op names to hand...
class tf_op:
"""Class to implement the decorator to register handlers that map tf to onnx.""" # Maps domains (string) to lists (idx represents opset) of dicts (key = op to handle, value = handler) _OPSETS = collections.OrderedDict() # Cache of mapping for current domain and opset. Maps op names to handlers [(func, ...
# SPDX-License-Identifier: Apache-2.0 """Opset registry.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import collections import inspect from tf2onnxnightly import constants # pylint: disable=unused-argument,...
83
256
938
4
78
tensorleap/tensorflow-onnx
tf2onnxnightly/handler.py
Python
tf_op
tf_op
19
122
19
19
d13bd12c98084b701a1b38966b708c455f51ea48
bigcode/the-stack
train
30ed04c246a07b833a72b28f
train
function
def readfile(filename): try: fileHandle = open(filename,'r+') text = fileHandle.read().splitlines() fileHandle.close() return text except IOError as error: print('Read file Error:' + str(error)) sys.exit()
def readfile(filename):
try: fileHandle = open(filename,'r+') text = fileHandle.read().splitlines() fileHandle.close() return text except IOError as error: print('Read file Error:' + str(error)) sys.exit()
import sys try: textfile1 = sys.argv[1] textfile2 = sys.argv[2] except Exception as e: print("Error:" + str(e)) print("Usage: python3 didd_file.py filename1 filename2") sys.exit() def readfile(filename):
64
64
58
5
59
cywd/some_crawler_use_python
python_ crawler/diff_file.py
Python
readfile
readfile
16
24
16
16
04afbc3258228871ef0b1cd2de8332c99c14de4e
bigcode/the-stack
train
fa111e67aac17c14deae5503
train
class
class Client(object): """ Class to act as a client for the Linkedin API. """ # Settings for general Linkedin API calls API_BASE_URL = "https://www.linkedin.com/voyager/api" REQUEST_HEADERS = { "user-agent": " ".join( [ "Mozilla/5.0 (X11; Linux x86_64)", ...
class Client(object):
""" Class to act as a client for the Linkedin API. """ # Settings for general Linkedin API calls API_BASE_URL = "https://www.linkedin.com/voyager/api" REQUEST_HEADERS = { "user-agent": " ".join( [ "Mozilla/5.0 (X11; Linux x86_64)", "AppleWebKi...
import requests import logging from linkedin_api.cookie_repository import CookieRepository logger = logging.getLogger(__name__) class ChallengeException(Exception): pass class UnauthorizedException(Exception): pass class Client(object):
43
256
933
4
38
aeciorc/linkedin-api
linkedin_api/client.py
Python
Client
Client
16
133
16
16
dbc80698d5cb306dfed2ee5f6c43d0fb19cfc10a
bigcode/the-stack
train
7048f0f922506a63e3728f18
train
class
class UnauthorizedException(Exception): pass
class UnauthorizedException(Exception):
pass
import requests import logging from linkedin_api.cookie_repository import CookieRepository logger = logging.getLogger(__name__) class ChallengeException(Exception): pass class UnauthorizedException(Exception):
36
64
8
5
30
aeciorc/linkedin-api
linkedin_api/client.py
Python
UnauthorizedException
UnauthorizedException
12
13
12
12
f609ee19847be8379ed22e5cf9055aa7ecc60f75
bigcode/the-stack
train
6fec87835e97301f37e25cde
train
class
class ChallengeException(Exception): pass
class ChallengeException(Exception):
pass
import requests import logging from linkedin_api.cookie_repository import CookieRepository logger = logging.getLogger(__name__) class ChallengeException(Exception):
28
64
8
5
23
aeciorc/linkedin-api
linkedin_api/client.py
Python
ChallengeException
ChallengeException
8
9
8
8
4a012708a575d66d49e57571599f54583bd58705
bigcode/the-stack
train
e1321d405b683fbc0922b0ea
train
function
def _haskell_travis_impl(ctx): ctx.actions.expand_template( template = ctx.file._template, output = ctx.outputs.source_file, substitutions = { "{PACKAGE}": ctx.attr.package, }, ) outs = [ctx.outputs.source_file] return DefaultInfo(files = depset(outs), runfil...
def _haskell_travis_impl(ctx):
ctx.actions.expand_template( template = ctx.file._template, output = ctx.outputs.source_file, substitutions = { "{PACKAGE}": ctx.attr.package, }, ) outs = [ctx.outputs.source_file] return DefaultInfo(files = depset(outs), runfiles = ctx.runfiles(files = outs)...
"""Defines a project macro used in every TokTok sub-project. It checks constraints such as the use of the correct license and the presence and correctness of the license text. """ def _haskell_travis_impl(ctx):
45
64
78
9
36
TokTok/toktok-stack
tools/project/build_defs.bzl
Python
_haskell_travis_impl
_haskell_travis_impl
7
17
7
7
bac4724722bcfdc706187a6aaa5643c4d12463e4
bigcode/the-stack
train
e2024f952db8b93b39139800
train
function
def project(license = "gpl3", standard_travis = False): """Adds some checks to make sure the project is uniform.""" native.sh_test( name = "license_test", size = "small", srcs = ["//tools/project:diff_test.sh"], args = [ "$(location LICENSE)", "$(location ...
def project(license = "gpl3", standard_travis = False):
"""Adds some checks to make sure the project is uniform.""" native.sh_test( name = "license_test", size = "small", srcs = ["//tools/project:diff_test.sh"], args = [ "$(location LICENSE)", "$(location //tools:LICENSE.%s)" % license, ], data ...
_package, ) native.sh_test( name = "travis_test", size = "small", srcs = ["//tools/project:diff_test.sh"], data = [ ".travis.yml", ":travis", ], args = [ "$(location .travis.yml)", ...
92
92
309
16
76
TokTok/toktok-stack
tools/project/build_defs.bzl
Python
project
project
68
108
68
68
7363fb1b709033146a793c3ed97d70027cc0f446
bigcode/the-stack
train
8439ba28a9ff347dfb0713f1
train
function
def _haskell_project(standard_travis = True): haskell_package = native.package_name()[3:] cabal_file = haskell_package + ".cabal" native.sh_test( name = "cabal_test", size = "small", srcs = ["//tools/project:cabal_test.py"], args = [ "$(location BUILD.bazel)", ...
def _haskell_project(standard_travis = True):
haskell_package = native.package_name()[3:] cabal_file = haskell_package + ".cabal" native.sh_test( name = "cabal_test", size = "small", srcs = ["//tools/project:cabal_test.py"], args = [ "$(location BUILD.bazel)", "$(location %s)" % cabal_file, ...
.label( default = Label("//tools/project:haskell_travis.yml.in"), allow_single_file = True, ), }, outputs = {"source_file": ".travis-expected.yml"}, implementation = _haskell_travis_impl, ) def _haskell_project(standard_travis = True):
64
64
215
12
52
TokTok/toktok-stack
tools/project/build_defs.bzl
Python
_haskell_project
_haskell_project
31
66
31
31
a6b0234e2fccf3dd8b4014ac774608dae72a5f45
bigcode/the-stack
train
1a892fd73d40e1d66ac7a166
train
function
def workspace(projects): native.sh_test( name = "git_modules_test", size = "small", srcs = [":git_modules_test.pl"], args = [ "$(location gitmodules)", "$(location git-remotes)", ] + projects, data = [ "gitmodules", "git...
def workspace(projects):
native.sh_test( name = "git_modules_test", size = "small", srcs = [":git_modules_test.pl"], args = [ "$(location gitmodules)", "$(location git-remotes)", ] + projects, data = [ "gitmodules", "git-remotes", ], ...
[".github/settings.yml"], ) if (native.package_name().startswith("hs-") and any([f for f in native.glob(["*"]) if f.endswith(".cabal")])): _haskell_project( standard_travis = standard_travis, ) def workspace(projects):
64
64
210
5
59
TokTok/toktok-stack
tools/project/build_defs.bzl
Python
workspace
workspace
110
147
110
110
74d497b4825966b7b039b204c3ac809a8e3ffa1b
bigcode/the-stack
train
d486db48e7d5da9058579f04
train
class
@HOOKS.register_module() class ExpMomentumEMAHook(BaseEMAHook): """EMAHook using exponential momentum strategy. Args: total_iter (int): The total number of iterations of EMA momentum. Defaults to 2000. """ def __init__(self, total_iter=2000, **kwargs): super(ExpMomentumEMAHo...
@HOOKS.register_module() class ExpMomentumEMAHook(BaseEMAHook):
"""EMAHook using exponential momentum strategy. Args: total_iter (int): The total number of iterations of EMA momentum. Defaults to 2000. """ def __init__(self, total_iter=2000, **kwargs): super(ExpMomentumEMAHook, self).__init__(**kwargs) self.momentum_fun = lambda ...
name, value in self.model_parameters.items(): temp = value.data.clone() ema_buffer = self.model_buffers[self.param_ema_buffer[name]] value.data.copy_(ema_buffer.data) ema_buffer.data.copy_(temp) @HOOKS.register_module() class ExpMomentumEMAHook(BaseEMAHook):
64
64
122
17
47
tycoer/rfvision-1
rfvision/core/hook/ema.py
Python
ExpMomentumEMAHook
ExpMomentumEMAHook
103
115
103
104
7c482d4d7f9ef8b3faf498e4aa2f744b67aa6178
bigcode/the-stack
train
c60f2adc86bfb0706ebab98b
train
class
@HOOKS.register_module() class LinearMomentumEMAHook(BaseEMAHook): """EMAHook using linear momentum strategy. Args: warm_up (int): During first warm_up steps, we may use smaller decay to update ema parameters more slowly. Defaults to 100. """ def __init__(self, warm_up=100, **kwarg...
@HOOKS.register_module() class LinearMomentumEMAHook(BaseEMAHook):
"""EMAHook using linear momentum strategy. Args: warm_up (int): During first warm_up steps, we may use smaller decay to update ema parameters more slowly. Defaults to 100. """ def __init__(self, warm_up=100, **kwargs): super(LinearMomentumEMAHook, self).__init__(**kwargs) ...
EMAHook, self).__init__(**kwargs) self.momentum_fun = lambda x: (1 - self.momentum) * math.exp(-( 1 + x) / total_iter) + self.momentum @HOOKS.register_module() class LinearMomentumEMAHook(BaseEMAHook):
64
64
124
17
46
tycoer/rfvision-1
rfvision/core/hook/ema.py
Python
LinearMomentumEMAHook
LinearMomentumEMAHook
118
130
118
119
eef1b6011a720c057094df572cf86c85fbd0fbd1
bigcode/the-stack
train
29eb2595c127a76c008fe50a
train
class
class BaseEMAHook(Hook): """Exponential Moving Average Hook. Use Exponential Moving Average on all parameters of model in training process. All parameters have a ema backup, which update by the formula as below. EMAHook takes priority over EvalHook and CheckpointHook. Note, the original model param...
class BaseEMAHook(Hook):
"""Exponential Moving Average Hook. Use Exponential Moving Average on all parameters of model in training process. All parameters have a ema backup, which update by the formula as below. EMAHook takes priority over EvalHook and CheckpointHook. Note, the original model parameters are actually saved ...
# Copyright (c) OpenMMLab. All rights reserved. import math from rflib.parallel import is_module_wrapper from rflib.runner.hooks import HOOKS, Hook class BaseEMAHook(Hook):
49
240
802
8
40
tycoer/rfvision-1
rfvision/core/hook/ema.py
Python
BaseEMAHook
BaseEMAHook
8
100
8
8
f3e61ae268bfc8a7da9bb71c646d1dc975907892
bigcode/the-stack
train
3fc6c84e15421a98bb68bc0d
train
class
class Migration(migrations.Migration): dependencies = [ ('store', '0002_category'), ] operations = [ migrations.AddField( model_name='product', name='category', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='store.cat...
class Migration(migrations.Migration):
dependencies = [ ('store', '0002_category'), ] operations = [ migrations.AddField( model_name='product', name='category', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='store.category'), ), ]
# Generated by Django 3.1.3 on 2020-11-25 10:59 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
45
64
70
7
37
deepchatterjeevns/Green-veggies-ECommerce-App
store/migrations/0003_product_category.py
Python
Migration
Migration
7
19
7
8
9c7f435348e1391e3eb04a152abb75e98053ffa7
bigcode/the-stack
train
dd1a97e62a3d816f63aef417
train
function
def _test_len(store): s = store # just to be able to use shorthand "s" _delete_keys_from_store(s, ['_foo', '_hello']) n = len(s) # remember how many items there are s['_foo'] = 'bar' # store 'bar' in '_foo' assert len(s) == n + 1, "You should have an extra item in the store" s['_hello'] =...
def _test_len(store):
s = store # just to be able to use shorthand "s" _delete_keys_from_store(s, ['_foo', '_hello']) n = len(s) # remember how many items there are s['_foo'] = 'bar' # store 'bar' in '_foo' assert len(s) == n + 1, "You should have an extra item in the store" s['_hello'] = 'world' # store 'wor...
put it back except DeletionsNotAllowed: pass # wraped in try/except in case overwriting is not allowed try: s['_foo'] = 'a different value' assert s['_foo'] == 'a different value' except OverWritesNotAllowedError: pass _delete_keys_from_store(s, ['_foo', '_hello'])...
89
90
301
6
83
Perfect111/i2mint-py2store
py2store/test/simple.py
Python
_test_len
_test_len
81
114
81
81
cbf9fad211e4d127ef57cad7dca059ecb4e35667
bigcode/the-stack
train
5578f986641a577049925a67
train
function
def test_local_file_ops(): rootdir = os.path.join(gettempdir(), 'py_store_tests') # empty and recreate rootdir if necessary if os.path.isdir(rootdir): shutil.rmtree(rootdir) os.mkdir(rootdir) from py2store.stores.local_store import RelativePathFormatStore as cls _test_path_format_local_...
def test_local_file_ops():
rootdir = os.path.join(gettempdir(), 'py_store_tests') # empty and recreate rootdir if necessary if os.path.isdir(rootdir): shutil.rmtree(rootdir) os.mkdir(rootdir) from py2store.stores.local_store import RelativePathFormatStore as cls _test_path_format_local_file_ops(cls) from py2...
os.path.join(gettempdir(), 'py_store_tests') # empty and recreate rootdir if necessary if os.path.isdir(rootdir): shutil.rmtree(rootdir) os.mkdir(rootdir) store = cls(path_format=rootdir) _multi_test(store) def test_local_file_ops():
64
64
108
6
58
Perfect111/i2mint-py2store
py2store/test/simple.py
Python
test_local_file_ops
test_local_file_ops
155
166
155
155
aab51fb7c34cecf379a3c8f351b2991ba7527338
bigcode/the-stack
train
25663c781fc870ac78223ce2
train
function
def _multi_test(store): _test_ops_on_store(store) _test_len(store)
def _multi_test(store):
_test_ops_on_store(store) _test_len(store)
'a different value' assert len(s) == n + 2 except OverWritesNotAllowedError: pass _delete_keys_from_store(s, ['_foo', '_hello']) # # @fixture # def empty_dict_store(): # return {} def _multi_test(store):
64
64
20
6
58
Perfect111/i2mint-py2store
py2store/test/simple.py
Python
_multi_test
_multi_test
121
123
121
121
5c51dceb134a50f257002a7d22923bad44614c8d
bigcode/the-stack
train
9a0ffc53c9bdf5c79f4bbe5c
train
function
def _delete_keys_from_store(store, keys_to_delete): for k in keys_to_delete: if k in store: # if key already in s, delete it del store[k]
def _delete_keys_from_store(store, keys_to_delete):
for k in keys_to_delete: if k in store: # if key already in s, delete it del store[k]
store.test.util import get_s3_test_access_info_from_env_vars # from collections.abc import MutableMapping # from py2store.base import AbstractObjStore # import typing # # Store = typing.Union(AbstractObjStore, MutableMapping) def _delete_keys_from_store(store, keys_to_delete):
64
64
42
12
52
Perfect111/i2mint-py2store
py2store/test/simple.py
Python
_delete_keys_from_store
_delete_keys_from_store
15
18
15
15
bfc0ca9bc08b151f30bf666ca2a9b00075d8fb3c
bigcode/the-stack
train
808db1b13413124d501545f3
train
function
def _test_ops_on_store(store): s = store # just to be able to use shorthand "s" _delete_keys_from_store(s, ['_foo', '_hello', '_non_existing_key_']) # test "not in" assert '_non_existing_key_' not in s, \ "I really wasn't expecting that key to be in there!" s['_foo'] = 'bar' # store 'ba...
def _test_ops_on_store(store):
s = store # just to be able to use shorthand "s" _delete_keys_from_store(s, ['_foo', '_hello', '_non_existing_key_']) # test "not in" assert '_non_existing_key_' not in s, \ "I really wasn't expecting that key to be in there!" s['_foo'] = 'bar' # store 'bar' in '_foo' assert "_foo" ...
import pytest import os import shutil from tempfile import gettempdir from py2store.errors import OverWritesNotAllowedError, DeletionsNotAllowed from py2store.test.util import get_s3_test_access_info_from_env_vars # from collections.abc import MutableMapping # from py2store.base import AbstractObjStore # import typin...
139
171
571
8
131
Perfect111/i2mint-py2store
py2store/test/simple.py
Python
_test_ops_on_store
_test_ops_on_store
21
78
21
21
746f454bde83c5383f39215ec7daa7e8e256093e
bigcode/the-stack
train
441db4749ae39f62b8208142
train
function
def test_dict_ops(): store = dict() _multi_test(store)
def test_dict_ops():
store = dict() _multi_test(store)
WritesNotAllowedError: pass _delete_keys_from_store(s, ['_foo', '_hello']) # # @fixture # def empty_dict_store(): # return {} def _multi_test(store): _test_ops_on_store(store) _test_len(store) def test_dict_ops():
64
64
16
5
59
Perfect111/i2mint-py2store
py2store/test/simple.py
Python
test_dict_ops
test_dict_ops
126
128
126
126
8e9ad51283a06b6b511be0841fc0d1ff8142e8b7
bigcode/the-stack
train
20ef69dfd1cfad90498f3278
train
function
def _test_path_format_local_file_ops(cls): rootdir = os.path.join(gettempdir(), 'py_store_tests') # empty and recreate rootdir if necessary if os.path.isdir(rootdir): shutil.rmtree(rootdir) os.mkdir(rootdir) store = cls(path_format=rootdir) _multi_test(store)
def _test_path_format_local_file_ops(cls):
rootdir = os.path.join(gettempdir(), 'py_store_tests') # empty and recreate rootdir if necessary if os.path.isdir(rootdir): shutil.rmtree(rootdir) os.mkdir(rootdir) store = cls(path_format=rootdir) _multi_test(store)
# shutil.rmtree(rootdir) # os.mkdir(rootdir) # # store = RelativePathFormatStore(path_format=rootdir) # # store._obj_of_data = partial(str, encoding='utf-8') # _multi_test(store) def _test_path_format_local_file_ops(cls):
64
64
72
10
54
Perfect111/i2mint-py2store
py2store/test/simple.py
Python
_test_path_format_local_file_ops
_test_path_format_local_file_ops
144
152
144
144
d90bc962454de1f478ea023f9b11aead2f15aeed
bigcode/the-stack
train
6afdcf23a61b0b603ba704cb
train
function
def _paths_parser(helpful: "helpful.HelpfulArgumentParser") -> None: add = helpful.add verb: Union[str, bool] = helpful.verb if verb == "help": verb = helpful.help_arg cpkwargs = { "type": os.path.abspath, "help": "Path to where certificate is saved (with certonly --csr), instal...
def _paths_parser(helpful: "helpful.HelpfulArgumentParser") -> None:
add = helpful.add verb: Union[str, bool] = helpful.verb if verb == "help": verb = helpful.help_arg cpkwargs = { "type": os.path.abspath, "help": "Path to where certificate is saved (with certonly --csr), installed " "from, or revoked" } if verb == "certon...
"""This is a module that adds configuration to the argument parser regarding paths for certificates""" from typing import TYPE_CHECKING from typing import Union from certbot._internal.cli.cli_utils import config_help from certbot._internal.cli.cli_utils import flag_default from certbot.compat import os if TYPE_CHECKI...
94
122
407
18
75
vivithemage/certbot
certbot/certbot/_internal/cli/paths_parser.py
Python
_paths_parser
_paths_parser
14
50
14
14
2c97a8b475e9e4897f89aa3799c8d5b9f361e252
bigcode/the-stack
train
e03f46deac7c11b12fe54906
train
class
class NKCorrelation(treecorr.BinnedCorr2): """This class handles the calculation and storage of a 2-point count-kappa correlation function. Ojects of this class holds the following attributes: :nbins: The number of bins in logr :bin_size: The size of the bins in logr :min_sep:...
class NKCorrelation(treecorr.BinnedCorr2):
"""This class handles the calculation and storage of a 2-point count-kappa correlation function. Ojects of this class holds the following attributes: :nbins: The number of bins in logr :bin_size: The size of the bins in logr :min_sep: The minimum separation being considered ...
# Copyright (c) 2003-2015 by Mike Jarvis # # TreeCorr is free software: redistribution and use in source and binary forms, # with or without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of condi...
155
256
3,927
10
144
kstoreyf/TreeCorr
treecorr/nkcorrelation.py
Python
NKCorrelation
NKCorrelation
22
384
22
22
8f454b02560a23698ed23250ab571f78a0da4b75
bigcode/the-stack
train
2a76a6d993630e1234dbbe24
train
function
def _get_merging_map(a, b, b_name_pos: int = 7) -> dict: """Intersect BED files to obtain a dict with b names as keys and overlapped a names for each b in values as list """ joined = a.intersect(b, wao=True) res = {x.name: [] for x in b} for i in joined: if i[b_name_pos] != '.': ...
def _get_merging_map(a, b, b_name_pos: int = 7) -> dict:
"""Intersect BED files to obtain a dict with b names as keys and overlapped a names for each b in values as list """ joined = a.intersect(b, wao=True) res = {x.name: [] for x in b} for i in joined: if i[b_name_pos] != '.': res[i[b_name_pos]].append(i.name) return res
[1].split('-')[0], j[1].split('-')[1], i] out.append('\t'.join(o)) return BedTool('\n'.join(out), from_string=True) def _get_merging_map(a, b, b_name_pos: int = 7) -> dict:
64
64
108
22
42
gitter-badger/scarf-1
scarf/meld_assay.py
Python
_get_merging_map
_get_merging_map
100
109
100
100
42f54787231da170308c83c361f1941ba0882862
bigcode/the-stack
train
a2e0c9eb10cfbe6e7f7a39f7
train
function
def meld_assay(assay, reference_bed, out_name: str, nthreads: int, peaks_col: str = 'ids', ignore_ids: List[str] = None): if ignore_ids is None: ignore_ids = {} else: ignore_ids = {x: None for x in ignore_ids} peaks_bed = _create_bed_from_coord_ids(assay.feats.fetch_all(peaks_...
def meld_assay(assay, reference_bed, out_name: str, nthreads: int, peaks_col: str = 'ids', ignore_ids: List[str] = None):
if ignore_ids is None: ignore_ids = {} else: ignore_ids = {x: None for x in ignore_ids} peaks_bed = _create_bed_from_coord_ids(assay.feats.fetch_all(peaks_col), invalid_ids=ignore_ids) cross_idx_map = _convert_ids_to_idx(pd.Series(assay.feats.fetch_all(peaks_col)), ...
[:, cross_idx_map[i]].sum(axis=1) out_store[c_pos_start:c_pos_end, :] = b c_pos_start = c_pos_end return None def meld_assay(assay, reference_bed, out_name: str, nthreads: int, peaks_col: str = 'ids', ignore_ids: List[str] = None):
78
78
261
40
37
gitter-badger/scarf-1
scarf/meld_assay.py
Python
meld_assay
meld_assay
142
155
142
143
0855e5fc6c2dbc76be74d2a27a84f46d4e7ff4be
bigcode/the-stack
train
cd23b5d20c166c7766ba8eb1
train
function
def _create_counts_mat(assay, out_store, feat_order: list, cross_idx_map: dict, nthreads: int) -> None: c_pos_start = 0 for a in tqdm(assay.rawData.blocks, total=assay.rawData.numblocks[0]): a = controlled_compute(a, nthreads) b = np.zeros((a.shape[0], len(feat_order))) c_pos_end = c_pos...
def _create_counts_mat(assay, out_store, feat_order: list, cross_idx_map: dict, nthreads: int) -> None:
c_pos_start = 0 for a in tqdm(assay.rawData.blocks, total=assay.rawData.numblocks[0]): a = controlled_compute(a, nthreads) b = np.zeros((a.shape[0], len(feat_order))) c_pos_end = c_pos_start + a.shape[0] for n, i in enumerate(feat_order): if i in cross_idx_map and len...
null_ids += 1 logger.info(f"{null_ids}/{len(cross_id_map)} ids did not have a cross id") return idx def _create_counts_mat(assay, out_store, feat_order: list, cross_idx_map: dict, nthreads: int) -> None:
64
64
177
31
32
gitter-badger/scarf-1
scarf/meld_assay.py
Python
_create_counts_mat
_create_counts_mat
128
139
128
128
e23035834a65c1e8427961264a1bd701ab29231f
bigcode/the-stack
train
ee78838db3902161b16b3b38
train
function
def _create_bed_from_coord_ids(ids: List[str], invalid_ids: Dict[str, None]): """convert list of 'chr:start-end' format strings to pybedtools object""" try: # noinspection PyUnresolvedReferences from pybedtools import BedTool except ImportError: raise ImportError("ERROR: pybedtools i...
def _create_bed_from_coord_ids(ids: List[str], invalid_ids: Dict[str, None]):
"""convert list of 'chr:start-end' format strings to pybedtools object""" try: # noinspection PyUnresolvedReferences from pybedtools import BedTool except ImportError: raise ImportError("ERROR: pybedtools is not installed") out = [] for i in ids: if i in invalid_ids:...
they were not present in the valid_ids") logger.info(f"{unknown_ids} genes were ignored as they did not have gene_id column") return BedTool('\n'.join(out), from_string=True) def _create_bed_from_coord_ids(ids: List[str], invalid_ids: Dict[str, None]):
64
64
157
21
43
gitter-badger/scarf-1
scarf/meld_assay.py
Python
_create_bed_from_coord_ids
_create_bed_from_coord_ids
82
97
82
82
121bcf9988d2505a26de488eb9806e4174b7b19f
bigcode/the-stack
train
3604f3eef013b21e5cf874b6
train
function
def make_bed_from_gff(gff: str, up_offset: int = 2000, valid_ids: List[str] = None, flavour: str = 'body'): """Create pybedtools object for genes from a GFF file. Gene coordinates are promoter extended""" try: from pybedtools import BedTool except ImportError: raise Imp...
def make_bed_from_gff(gff: str, up_offset: int = 2000, valid_ids: List[str] = None, flavour: str = 'body'):
"""Create pybedtools object for genes from a GFF file. Gene coordinates are promoter extended""" try: from pybedtools import BedTool except ImportError: raise ImportError("pybedtools is not installed. Check out this link to install" " https://daler.github.io/pybedto...
from tqdm import tqdm from typing import List, Dict import pandas as pd import numpy as np from .writers import create_zarr_count_assay from .utils import controlled_compute from .logging_utils import logger __all__ = ['meld_assay', 'make_bed_from_gff'] def make_bed_from_gff(gff: str, up_offset: int = 2000, ...
102
211
705
38
64
gitter-badger/scarf-1
scarf/meld_assay.py
Python
make_bed_from_gff
make_bed_from_gff
12
79
12
13
14da685d71e51069f66a9f07fb8fc3cd826d402a
bigcode/the-stack
train
c6711582566a6e9eeb97b2e6
train
function
def _convert_ids_to_idx(ids: pd.Series, cross_id_map: dict) -> dict: """ convert ids to indices from scarf feats table """ ref = {v: k for k, v in ids.to_dict().items()} idx = {x: [] for x in cross_id_map} null_ids = 0 for i in cross_id_map: if len(cross_id_map[i]) > 0: i...
def _convert_ids_to_idx(ids: pd.Series, cross_id_map: dict) -> dict:
""" convert ids to indices from scarf feats table """ ref = {v: k for k, v in ids.to_dict().items()} idx = {x: [] for x in cross_id_map} null_ids = 0 for i in cross_id_map: if len(cross_id_map[i]) > 0: idx[i] = [ref[x] for x in cross_id_map[i]] else: n...
res = {x.name: [] for x in b} for i in joined: if i[b_name_pos] != '.': res[i[b_name_pos]].append(i.name) return res def _convert_ids_to_idx(ids: pd.Series, cross_id_map: dict) -> dict:
64
64
147
20
43
gitter-badger/scarf-1
scarf/meld_assay.py
Python
_convert_ids_to_idx
_convert_ids_to_idx
112
125
112
112
247bb32167a1fae41c860cf137974fd9f5b25580
bigcode/the-stack
train
b75b625cf9f882e8a0716756
train
class
class UserRPWorkspaceShareSubscriptionOperations(object): """UserRPWorkspaceShareSubscriptionOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model cl...
class UserRPWorkspaceShareSubscriptionOperations(object):
"""UserRPWorkspaceShareSubscriptionOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~osc...
# coding=utf-8 # -------------------------------------------------------------------------- # Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.2.1, generator: {generator}) # Changes may cause incorrect behavior and will be lost if the code is regenerated. # ------------------------------------------...
202
231
771
9
193
Mannan2812/azure-cli-extensions
src/tipsextension/azext_tipsextension/vendored_sdks/oscp/controlplane/operations/_user_rp_workspace_share_subscription_operations.py
Python
UserRPWorkspaceShareSubscriptionOperations
UserRPWorkspaceShareSubscriptionOperations
22
104
22
22
35e5148fe9ab2f8f8bb6f1370d220b52927e88f7
bigcode/the-stack
train
f6a2ec8ec0bf6abe31cf6146
train
function
def exists(env): return findIt('bcc32', env)
def exists(env):
return findIt('bcc32', env)
'] = '-I' env['INCSUFFIX'] = '' env['SHOBJSUFFIX'] = '.dll' env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 0 env['CFILESUFFIX'] = '.cpp' def exists(env):
64
64
14
4
60
luaman/twilight
scons-local-0.96.90/SCons/Tool/bcc32.py
Python
exists
exists
78
79
78
78
05d7521afb6a5a0dd3011f01ff8851ca5d400bc4
bigcode/the-stack
train
40ca5f5f36066a1f04961d1a
train
function
def findIt(program, env): # First search in the SCons path and then the OS path: borwin = env.WhereIs(program) or SCons.Util.WhereIs(program) if borwin: dir = os.path.dirname(borwin) path = env['ENV'].get('PATH', []) if not path: path = [] if SCons.Util.is_String(...
def findIt(program, env): # First search in the SCons path and then the OS path:
borwin = env.WhereIs(program) or SCons.Util.WhereIs(program) if borwin: dir = os.path.dirname(borwin) path = env['ENV'].get('PATH', []) if not path: path = [] if SCons.Util.is_String(path): path = string.split(path, os.pathsep) env['ENV']['PATH'] =...
001 2005/02/15 20:11:37 knight" import os import os.path import string import SCons.Defaults import SCons.Tool import SCons.Util def findIt(program, env): # First search in the SCons path and then the OS path:
64
64
119
22
41
luaman/twilight
scons-local-0.96.90/SCons/Tool/bcc32.py
Python
findIt
findIt
40
51
40
41
6286800760151a92b61a664b66e5e9ad444a87d8
bigcode/the-stack
train
395ef446c538821d57a99764
train
function
def generate(env): findIt('bcc32', env) """Add Builders and construction variables for bcc to an Environment.""" static_obj, shared_obj = SCons.Tool.createObjBuilders(env) for suffix in ['.c', '.cpp']: static_obj.add_action(suffix, SCons.Defaults.CAction) shared_obj.add_action(suffix...
def generate(env):
findIt('bcc32', env) """Add Builders and construction variables for bcc to an Environment.""" static_obj, shared_obj = SCons.Tool.createObjBuilders(env) for suffix in ['.c', '.cpp']: static_obj.add_action(suffix, SCons.Defaults.CAction) shared_obj.add_action(suffix, SCons.Defaults.Sh...
: borwin = env.WhereIs(program) or SCons.Util.WhereIs(program) if borwin: dir = os.path.dirname(borwin) path = env['ENV'].get('PATH', []) if not path: path = [] if SCons.Util.is_String(path): path = string.split(path, os.pathsep) env['ENV']['PATH']...
102
102
343
4
97
luaman/twilight
scons-local-0.96.90/SCons/Tool/bcc32.py
Python
generate
generate
53
76
53
53
95b35bcfd8ff2e933d6e846445ac2c40d8954190
bigcode/the-stack
train
26af603bcc1c1062f84e6b52
train
function
@app.route('/') def home(): return render_template('home.html')
@app.route('/') def home():
return render_template('home.html')
from flask import Flask, render_template app = Flask(__name__) app.config["DEBUG"] = True @app.route('/') def home():
28
64
14
6
21
john-judge/VisualChessWebApp
flask_app.py
Python
home
home
6
8
6
7
972af16ea37332325cf932623047748a42349e4f
bigcode/the-stack
train
46818012311dfaa86903c788
train
class
class BaseEcologyEnv(gym.Env): metadata = {"render.modes": ["human"]} def __init__( self, params={ "r": 0.3, "K": 1, "sigma": 0.0, "x0": 0.1, "cost": 2.0, "benefit": 1.0, }, Tmax=500, file="render.cs...
class BaseEcologyEnv(gym.Env):
metadata = {"render.modes": ["human"]} def __init__( self, params={ "r": 0.3, "K": 1, "sigma": 0.0, "x0": 0.1, "cost": 2.0, "benefit": 1.0, }, Tmax=500, file="render.csv", ): # parameter...
import gym import numpy as np from gym import spaces from gym_conservation.envs.shared_env import ( csv_entry, estimate_policyfn, plot_mdp, plot_policyfn, simulate_mdp, ) class BaseEcologyEnv(gym.Env):
57
256
1,160
9
48
boettiger-lab/gym_conservation
gym_conservation/envs/base_env.py
Python
BaseEcologyEnv
BaseEcologyEnv
14
171
14
14
c9d43e202378c80165ff83197a382310be02943c
bigcode/the-stack
train
59a287ab7d352b072684c9ca
train
class
class BotMessageTest(TestCase): ''' Tests different kinds of message handling. ''' def setUp(self): self.bot = bot.SecurityBot(None, None, None) self.bot.messages['bad_command'] = 'bad-command' self.bot.users = {'id': {'id': 'id', 'name': 'name'}} def test_handle_messages_co...
class BotMessageTest(TestCase):
''' Tests different kinds of message handling. ''' def setUp(self): self.bot = bot.SecurityBot(None, None, None) self.bot.messages['bad_command'] = 'bad-command' self.bot.users = {'id': {'id': 'id', 'name': 'name'}} def test_handle_messages_command(self): '''Test rec...
format(name) assert isinstance(getattr(commands, items['fn'], None), types.FunctionType), \ '{0}: {1} is not a function'.format(name, items['fn']) def test_messages(self): '''Tests messages.yaml.''' with open(MESSAGE_CONFIG) as f: config = yaml.safe_l...
102
102
340
7
95
gurpradeep/securitybot
tests/bot_test.py
Python
BotMessageTest
BotMessageTest
68
104
68
68
bab2e36435c52d2ae088d9b68966682e6353f7dc
bigcode/the-stack
train
fd7f6cbc59489be8fcb4337f
train
class
class BotTaskTest(TestCase): ''' Tests handling of tasks. ''' @patch('securitybot.tasker.tasker.Task') @patch('securitybot.tasker.tasker.Tasker', autospec=True) def setUp(self, tasker, patch_task): self.bot = bot.SecurityBot(tasker, None, None) self.bot.greet_user = Mock() ...
class BotTaskTest(TestCase):
''' Tests handling of tasks. ''' @patch('securitybot.tasker.tasker.Task') @patch('securitybot.tasker.tasker.Tasker', autospec=True) def setUp(self, tasker, patch_task): self.bot = bot.SecurityBot(tasker, None, None) self.bot.greet_user = Mock() self.bot.blacklist = Mock(...
': 'test-user'} b.handle_command(user, 'test command') mock_command.assert_called_with(b, user, ['command']) b.chat.message_user.assert_called_with(user, 'success_msg') def test_command_failure(self): b = bot.SecurityBot(None, None, None) mock_command = Mock() mock_c...
156
156
523
7
149
gurpradeep/securitybot
tests/bot_test.py
Python
BotTaskTest
BotTaskTest
131
193
131
131
cedb0bb7d5d0656c2c023debee6e9cc8b92eadaf
bigcode/the-stack
train
8fcdc2d5dd072566bebef3d3
train
class
class BotHelperTest(TestCase): ''' Test cases for help functions in the bot that don't require actually constructing a bot properly. ''' # User handling tests def test_user_lookup(self): '''Tests user lookup on ID.''' sb = bot.SecurityBot(None, None, None) user = {'id': ...
class BotHelperTest(TestCase):
''' Test cases for help functions in the bot that don't require actually constructing a bot properly. ''' # User handling tests def test_user_lookup(self): '''Tests user lookup on ID.''' sb = bot.SecurityBot(None, None, None) user = {'id': 'id', 'name': 'user'} s...
self.task.set_verifying.assert_called_with() def test_no_user_task(self): '''Tests a task assigned to an unknown or invalid username.''' self.task.username = 'another user' self.bot.handle_new_tasks() assert self.task.comment == 'invalid user' self.task.set_verifying...
256
256
1,065
7
249
gurpradeep/securitybot
tests/bot_test.py
Python
BotHelperTest
BotHelperTest
219
329
219
219
f642349bb90d768ac93098bd18268967929e8c24
bigcode/the-stack
train
c8c082b71c96e38669e46a9a
train
class
class BotCommandTest(TestCase): ''' Tests handling a command. ''' def test_command_success(self): b = bot.SecurityBot(None, None, None) mock_command = Mock() mock_command.return_value = True b.commands = {'test': {'fn': mock_command, 'success_msg': 'success_msg'}} ...
class BotCommandTest(TestCase):
''' Tests handling a command. ''' def test_command_success(self): b = bot.SecurityBot(None, None, None) mock_command = Mock() mock_command.return_value = True b.commands = {'test': {'fn': mock_command, 'success_msg': 'success_msg'}} user = {'id': '123', 'name': '...
_handle_messages_not_dm(self): '''Test receiving a message that's not from a DM channel.''' self.bot.user_lookup = Mock() self.bot.chat.get_messages.return_value = [] self.bot.handle_messages() assert not self.bot.user_lookup.called, 'No user should have been looked up' class Bot...
69
69
231
7
62
gurpradeep/securitybot
tests/bot_test.py
Python
BotCommandTest
BotCommandTest
106
129
106
106
8d695b68674d4a3ae8bf3dbca6de5c6d158f01aa
bigcode/the-stack
train
a72e1ae3ac168e46c6a04fb9
train
class
class ConfigTest(TestCase): # Validate configuration files def test_config(self): '''Tests bot.yaml.''' with open(MAIN_CONFIG) as f: config = yaml.safe_load(f) for path in [s + '_path' for s in ['messages', 'commands']]: assert path in config, 'No {0} prov...
class ConfigTest(TestCase): # Validate configuration files
def test_config(self): '''Tests bot.yaml.''' with open(MAIN_CONFIG) as f: config = yaml.safe_load(f) for path in [s + '_path' for s in ['messages', 'commands']]: assert path in config, 'No {0} provided'.format(path.replace('_', ' ')) # Test tha...
datetime.min.replace(tzinfo=pytz.utc) self._last_report = datetime.min.replace(tzinfo=pytz.utc) self.chat = client self.users = {} self.users_by_name = {} self.active_users = {} self.commands = {} self.messages = {} bot.SecurityBot.__init__ = fake_init class ConfigTest(TestCase): #...
84
84
280
12
71
gurpradeep/securitybot
tests/bot_test.py
Python
ConfigTest
ConfigTest
40
66
40
41
16760036cfa226bd235428f8f96f6fcc20acc66f
bigcode/the-stack
train
0b64ebab76b4ee792d437dfe
train
function
@patch('securitybot.chat.chat.Chat', autospec=True) def fake_init(self, tasker, auth_builder, reporting_channel, client): self.username = 'testing-bot' self.tasker = tasker self.auth_builder = auth_builder self.reporting_channel = reporting_channel self._last_task_poll = datetime.min.replace(tzinfo=...
@patch('securitybot.chat.chat.Chat', autospec=True) def fake_init(self, tasker, auth_builder, reporting_channel, client):
self.username = 'testing-bot' self.tasker = tasker self.auth_builder = auth_builder self.reporting_channel = reporting_channel self._last_task_poll = datetime.min.replace(tzinfo=pytz.utc) self._last_report = datetime.min.replace(tzinfo=pytz.utc) self.chat = client self.users = {} s...
bot.user import securitybot.chat.chat MAIN_CONFIG = 'config/bot.yaml' COMMAND_CONFIG = 'config/commands.yaml' MESSAGE_CONFIG = 'config/messages.yaml' @patch('securitybot.chat.chat.Chat', autospec=True) def fake_init(self, tasker, auth_builder, reporting_channel, client):
64
64
131
29
35
gurpradeep/securitybot
tests/bot_test.py
Python
fake_init
fake_init
19
36
19
20
7d1cb00401b13f999437dda7ba6048da1d901005
bigcode/the-stack
train
7380784e5ffdaf7ec2693c44
train
class
class BotUserTest(TestCase): def test_populate(self): ''' Tests populating users. ''' sb = bot.SecurityBot(None, lambda *args: None, None) user = {'id': 'id', 'name': 'name'} sb._api_call = Mock() sb.chat.get_users.return_value = [user] sb._populate_us...
class BotUserTest(TestCase):
def test_populate(self): ''' Tests populating users. ''' sb = bot.SecurityBot(None, lambda *args: None, None) user = {'id': 'id', 'name': 'name'} sb._api_call = Mock() sb.chat.get_users.return_value = [user] sb._populate_users() sb.chat.get_use...
def test_no_user_task(self): '''Tests a task assigned to an unknown or invalid username.''' self.task.username = 'another user' self.bot.handle_new_tasks() assert self.task.comment == 'invalid user' self.task.set_verifying.assert_called_with() class BotUserTest(TestCase):
64
64
181
7
57
gurpradeep/securitybot
tests/bot_test.py
Python
BotUserTest
BotUserTest
195
217
195
195
b2e9f87292b411b4d694d11da1c7c4601625d1be
bigcode/the-stack
train
db79a6c3738c5c030636873a
train
class
@pytest.mark.cdn_whitelist class Test_CDN_Whitelist: """Tests all functions within the ROAs Parser class.""" @pytest.fixture(autouse=True) def parser(self): """Parser setup and table deleted before every test""" CDN_Whitelist_Table(clear=True) return CDN_Whitelist_Parser() def ...
@pytest.mark.cdn_whitelist class Test_CDN_Whitelist:
"""Tests all functions within the ROAs Parser class.""" @pytest.fixture(autouse=True) def parser(self): """Parser setup and table deleted before every test""" CDN_Whitelist_Table(clear=True) return CDN_Whitelist_Parser() def test_run(self, parser): """Tests the _run fun...
is checked in another file """ __authors__ = ["Justin Furuness", "Tony Zheng"] __credits__ = ["Justin Furuness", "Tony Zheng"] __Lisence__ = "BSD" __maintainer__ = "Justin Furuness" __email__ = "jfuruness@gmail.com" __status__ = "Development" import pytest from os import path from unittest.mock import patch from .....
129
129
430
14
114
jfuruness/lib_bgp_data
lib_bgp_data/collectors/cdn_whitelist/tests/test_cdn_whitelist.py
Python
Test_CDN_Whitelist
Test_CDN_Whitelist
26
88
26
27
88f5a35cd9789e7562253f41dbe9243c8307ff56
bigcode/the-stack
train
99266d9d9d7e782cfa3c5f94
train
class
class GooglecrawlerSpider(scrapy.Spider): ''' A spider for crawling paper information and pdf from GoogleScholar. Problems remaining to be solved: crawl citations Parameters: keywords (str): spaced by ' ', e.g., 'land entitlement'. directory (str): directory of PDF files. Using alias as...
class GooglecrawlerSpider(scrapy.Spider):
''' A spider for crawling paper information and pdf from GoogleScholar. Problems remaining to be solved: crawl citations Parameters: keywords (str): spaced by ' ', e.g., 'land entitlement'. directory (str): directory of PDF files. Using alias as `~` is prohibited. Use `/Users/xxxx/` ins...
import scrapy import unicodedata from konbini.items import KonbiniItem import logging import numpy as np import time import wget import os import urllib from selenium import webdriver class GooglecrawlerSpider(scrapy.Spider):
53
256
978
9
43
meander-why/konbini
konbini/spiders/googlecrawler.py
Python
GooglecrawlerSpider
GooglecrawlerSpider
12
104
12
12
1b2dd62ce8145850ca896021de84e03884580f39
bigcode/the-stack
train
30d37719d0f8b80befae9c81
train
class
class PoolUpgradeOSParameter(Model): """Options for upgrading the operating system of compute nodes in a pool. All required parameters must be populated in order to send to Azure. :param target_os_version: Required. The Azure Guest OS version to be installed on the virtual machines in the pool. :...
class PoolUpgradeOSParameter(Model):
"""Options for upgrading the operating system of compute nodes in a pool. All required parameters must be populated in order to send to Azure. :param target_os_version: Required. The Azure Guest OS version to be installed on the virtual machines in the pool. :type target_os_version: str """ ...
License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serializat...
64
64
165
7
56
NMijat1024/azure-sdk-for-python
azure-batch/azure/batch/models/pool_upgrade_os_parameter_py3.py
Python
PoolUpgradeOSParameter
PoolUpgradeOSParameter
15
35
15
15
235dbc1456bf9fad46a81d861d55df7734370bd4
bigcode/the-stack
train
ad941f437516d05f4982baae
train
class
class TradfriRemoteControl(AdapterWithBattery): def __init__(self, devices): super().__init__(devices) self.switch = ToggleSwitch(devices, 'switch', 'action') self.arrow_left = SelectorSwitch(devices, 'arrowL', 'action', ' (Left Arrow)') self.arrow_left.add_level('Off', None) ...
class TradfriRemoteControl(AdapterWithBattery):
def __init__(self, devices): super().__init__(devices) self.switch = ToggleSwitch(devices, 'switch', 'action') self.arrow_left = SelectorSwitch(devices, 'arrowL', 'action', ' (Left Arrow)') self.arrow_left.add_level('Off', None) self.arrow_left.add_level('Click', 'arrow_lef...
from adapters.adapter_with_battery import AdapterWithBattery from devices.switch.selector_switch import SelectorSwitch from devices.switch.toggle_switch import ToggleSwitch class TradfriRemoteControl(AdapterWithBattery):
38
219
733
9
28
wini83/domoticz-zigbee2mqtt-plugin
adapters/ikea/tradfri_remote_control.py
Python
TradfriRemoteControl
TradfriRemoteControl
6
82
6
6
f55b736e0713fa6bd8e201187bbcd4cf09493fe8
bigcode/the-stack
train
5165389b93be86f29f6456c2
train
class
class ReportMgrBase(object): """ Report Manager Base class Inherited classes should override: * `_report_training` * `_report_step` """ def __init__(self, report_every, start_time=-1.): """ Args: report_every(int): Report status every this many sentences ...
class ReportMgrBase(object):
""" Report Manager Base class Inherited classes should override: * `_report_training` * `_report_step` """ def __init__(self, report_every, start_time=-1.): """ Args: report_every(int): Report status every this many sentences start_time(float)...
import onmt from onmt.utils.logging import logger def build_report_manager(opt, gpu_rank): if opt.tensorboard and gpu_rank == 0: from torch.utils.tensorboard import SummaryWriter tensorboard_log_dir = opt.tensorboard_log_dir if not opt.train_from: tensorboard_log_dir += dat...
142
142
474
6
135
BradLin0819/kg2text
graph2text/onmt/utils/report_manager.py
Python
ReportMgrBase
ReportMgrBase
28
97
28
28
4dd2783b03f84f466b46da540e24c6374bbf1bb3
bigcode/the-stack
train
fdb417bab4943e396f05d7c4
train
function
def build_report_manager(opt, gpu_rank): if opt.tensorboard and gpu_rank == 0: from torch.utils.tensorboard import SummaryWriter tensorboard_log_dir = opt.tensorboard_log_dir if not opt.train_from: tensorboard_log_dir += datetime.now().strftime("/%b-%d_%H-%M-%S") writer...
def build_report_manager(opt, gpu_rank):
if opt.tensorboard and gpu_rank == 0: from torch.utils.tensorboard import SummaryWriter tensorboard_log_dir = opt.tensorboard_log_dir if not opt.train_from: tensorboard_log_dir += datetime.now().strftime("/%b-%d_%H-%M-%S") writer = SummaryWriter(tensorboard_log_dir, com...
""" Report manager utility """ from __future__ import print_function import time from datetime import datetime import onmt from onmt.utils.logging import logger def build_report_manager(opt, gpu_rank):
42
64
123
9
32
BradLin0819/kg2text
graph2text/onmt/utils/report_manager.py
Python
build_report_manager
build_report_manager
11
25
11
11
58b7666dcf553bc39c2c34aea1e199bdc0e123b0
bigcode/the-stack
train
aaed95126a8ba4809dbdd59d
train
class
class ReportMgr(ReportMgrBase): def __init__(self, report_every, start_time=-1., tensorboard_writer=None): """ A report manager that writes statistics on standard output as well as (optionally) TensorBoard Args: report_every(int): Report status every this many sentences ...
class ReportMgr(ReportMgrBase):
def __init__(self, report_every, start_time=-1., tensorboard_writer=None): """ A report manager that writes statistics on standard output as well as (optionally) TensorBoard Args: report_every(int): Report status every this many sentences tensorboard_writer(:...
_report_training(self, *args, **kwargs): """ To be overridden """ raise NotImplementedError() def report_step(self, lr, step, train_stats=None, valid_stats=None): """ Report stats of a step Args: train_stats(Statistics): training stats valid_stats(S...
130
130
436
8
122
BradLin0819/kg2text
graph2text/onmt/utils/report_manager.py
Python
ReportMgr
ReportMgr
100
158
100
100
061904a2d49122d67a73d2ae7c96f44f1be2b4d0
bigcode/the-stack
train
4b4570844bed44328c74ea5e
train
function
def main(): # The layout. output_field = TextArea(style='class:output-field', text=help_text) input_field = TextArea(height=1, prompt='>>> ', style='class:input-field') container = HSplit([ output_field, Window(height=1, char='-', style='class:line'), input_field ]) # T...
def main(): # The layout.
output_field = TextArea(style='class:output-field', text=help_text) input_field = TextArea(height=1, prompt='>>> ', style='class:input-field') container = HSplit([ output_field, Window(height=1, char='-', style='class:line'), input_field ]) # The key bindings. kb = KeyB...
kit.document import Document from prompt_toolkit.filters import has_focus from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.layout.containers import HSplit, Window from prompt_toolkit.layout.layout import Layout from prompt_toolkit.styles import Style from prompt_toolkit.widgets import TextArea he...
101
101
337
8
93
rokn/python-prompt-toolkit
examples/full-screen/calculator.py
Python
main
main
23
72
23
24
e25f56a1cf5e9a231e3e19eaf887542c8bb20e9d
bigcode/the-stack
train
4e8b18e1a50116f1a9cd3bb0
train
class
class BinanceTests(unittest.TestCase): ############################ #### setup and teardown #### ############################ # executed prior to each test def setUp(self): self.exchange = Binance() self.exchange.addCredentials("invalid_api_key", "invalid_secret_key") # executed after each test def tear...
class BinanceTests(unittest.TestCase): ############################ #### setup and teardown #### ############################ # executed prior to each test
def setUp(self): self.exchange = Binance() self.exchange.addCredentials("invalid_api_key", "invalid_secret_key") # executed after each test def tearDown(self): pass ############### #### tests #### ############### def test_AddCredentials(self): self.assertEqual(self.exchange.has_credentials, True, "Exch...
# app/tests/test_basic.py import os import sys import unittest curr_path = os.path.abspath(__file__) root_path = os.path.abspath( os.path.join(curr_path, os.path.pardir, os.path.pardir)) sys.path.insert(1, root_path) # Import all Created exchanges here from pyjuque.Exchanges.Binance import Binance from tests.utils ...
122
141
473
31
90
pimpmypixel/pyjuque
tests/test_Binance.py
Python
BinanceTests
BinanceTests
17
72
17
23
4f536d8c9f27a789ae33eb52e27c5bdbed150f66
bigcode/the-stack
train
2c90edbad8ee5f1eba574588
train
class
class ParameterValue(AWSProperty): props = { 'Id': (str, True), 'StringValue': (str, True), }
class ParameterValue(AWSProperty):
props = { 'Id': (str, True), 'StringValue': (str, True), }
props = { 'Key': (str, True), 'StringValue': (str, False), } class ParameterObject(AWSProperty): props = { 'Attributes': ([ParameterObjectAttribute], True), 'Id': (str, True), } class ParameterValue(AWSProperty):
64
64
32
7
57
mrsaicharan1/Alexa-BestBuy
venv/lib/python3.6/site-packages/troposphere/datapipeline.py
Python
ParameterValue
ParameterValue
19
23
19
19
40083382bf0c59670633076a64dec49f7733c3b1
bigcode/the-stack
train
934805165a804d3979d791d7
train
class
class ParameterObjectAttribute(AWSProperty): props = { 'Key': (str, True), 'StringValue': (str, False), }
class ParameterObjectAttribute(AWSProperty):
props = { 'Key': (str, True), 'StringValue': (str, False), }
from . import AWSObject, AWSProperty from .validators import boolean class ParameterObjectAttribute(AWSProperty):
23
64
33
8
14
mrsaicharan1/Alexa-BestBuy
venv/lib/python3.6/site-packages/troposphere/datapipeline.py
Python
ParameterObjectAttribute
ParameterObjectAttribute
5
9
5
5
9e897bbd4c77a93ea16b4bc60db026f9734767c4
bigcode/the-stack
train
e4e9fbed7c562185fb075c6d
train
class
class PipelineObject(AWSProperty): props = { 'Fields': ([ObjectField], True), 'Id': (str, True), 'Name': (str, True), }
class PipelineObject(AWSProperty):
props = { 'Fields': ([ObjectField], True), 'Id': (str, True), 'Name': (str, True), }
, True), 'StringValue': (str, True), } class ObjectField(AWSProperty): props = { 'Key': (str, True), 'RefValue': (str, False), 'StringValue': (str, False), } class PipelineObject(AWSProperty):
64
64
41
7
57
mrsaicharan1/Alexa-BestBuy
venv/lib/python3.6/site-packages/troposphere/datapipeline.py
Python
PipelineObject
PipelineObject
34
39
34
34
ebb7c84a04c09ab7662527bb45463de9e8a7f72e
bigcode/the-stack
train
f6e920a6e70c8a9f90778c2a
train
class
class PipelineTag(AWSProperty): props = { 'Key': (str, True), 'Value': (str, True), }
class PipelineTag(AWSProperty):
props = { 'Key': (str, True), 'Value': (str, True), }
str, False), 'StringValue': (str, False), } class PipelineObject(AWSProperty): props = { 'Fields': ([ObjectField], True), 'Id': (str, True), 'Name': (str, True), } class PipelineTag(AWSProperty):
64
64
31
7
57
mrsaicharan1/Alexa-BestBuy
venv/lib/python3.6/site-packages/troposphere/datapipeline.py
Python
PipelineTag
PipelineTag
42
46
42
42
d6ec0a39964ef8e29f28422de0f3c4cad34ec258
bigcode/the-stack
train
bc21ea895b3fce89f81cb615
train
class
class Pipeline(AWSObject): resource_type = "AWS::DataPipeline::Pipeline" props = { 'Activate': (boolean, False), 'Description': (str, False), 'Name': (str, True), 'ParameterObjects': ([ParameterObject], False), 'ParameterValues': ([ParameterValue], False), 'Pipel...
class Pipeline(AWSObject):
resource_type = "AWS::DataPipeline::Pipeline" props = { 'Activate': (boolean, False), 'Description': (str, False), 'Name': (str, True), 'ParameterObjects': ([ParameterObject], False), 'ParameterValues': ([ParameterValue], False), 'PipelineObjects': ([PipelineObje...
': ([ObjectField], True), 'Id': (str, True), 'Name': (str, True), } class PipelineTag(AWSProperty): props = { 'Key': (str, True), 'Value': (str, True), } class Pipeline(AWSObject):
64
64
95
6
58
mrsaicharan1/Alexa-BestBuy
venv/lib/python3.6/site-packages/troposphere/datapipeline.py
Python
Pipeline
Pipeline
49
60
49
49
8ac33e074ae728b1b381736520f3c89dc48f4546
bigcode/the-stack
train
b1899702b444d00940706ac6
train
class
class ParameterObject(AWSProperty): props = { 'Attributes': ([ParameterObjectAttribute], True), 'Id': (str, True), }
class ParameterObject(AWSProperty):
props = { 'Attributes': ([ParameterObjectAttribute], True), 'Id': (str, True), }
from . import AWSObject, AWSProperty from .validators import boolean class ParameterObjectAttribute(AWSProperty): props = { 'Key': (str, True), 'StringValue': (str, False), } class ParameterObject(AWSProperty):
55
64
33
7
48
mrsaicharan1/Alexa-BestBuy
venv/lib/python3.6/site-packages/troposphere/datapipeline.py
Python
ParameterObject
ParameterObject
12
16
12
12
a66b68e2269552fc5d0a6de6651ee364fe3d9a66
bigcode/the-stack
train
4c9297cdda3531a470c4d1d2
train
class
class ObjectField(AWSProperty): props = { 'Key': (str, True), 'RefValue': (str, False), 'StringValue': (str, False), }
class ObjectField(AWSProperty):
props = { 'Key': (str, True), 'RefValue': (str, False), 'StringValue': (str, False), }
props = { 'Attributes': ([ParameterObjectAttribute], True), 'Id': (str, True), } class ParameterValue(AWSProperty): props = { 'Id': (str, True), 'StringValue': (str, True), } class ObjectField(AWSProperty):
64
64
42
7
57
mrsaicharan1/Alexa-BestBuy
venv/lib/python3.6/site-packages/troposphere/datapipeline.py
Python
ObjectField
ObjectField
26
31
26
26
19f88834a6d03d347103762d8aabac5ead7b8668
bigcode/the-stack
train
43094d115263a5f70d7166d8
train
function
def set_start_method(method: Optional[str] = DEFAULT_START_METHOD) -> None: """ Set the start method and context used for future processes/pools. When given no parameters (`set_context()`), will default to using the "spawn" method as this provides a predictable set of features and compatibility across ...
def set_start_method(method: Optional[str] = DEFAULT_START_METHOD) -> None:
""" Set the start method and context used for future processes/pools. When given no parameters (`set_context()`), will default to using the "spawn" method as this provides a predictable set of features and compatibility across all major platforms, and trades a small cost on process startup for pote...
Logger(__name__) def get_manager() -> multiprocessing.managers.SyncManager: """Return a singleton shared manager.""" global _manager if _manager is None: _manager = context.Manager() return _manager def set_start_method(method: Optional[str] = DEFAULT_START_METHOD) -> None:
64
64
204
17
46
graingert/aiomultiprocess
aiomultiprocess/core.py
Python
set_start_method
set_start_method
34
53
34
34
c70f6bc856f83c55c05be1977e3bc0077dbac5e2
bigcode/the-stack
train
93a8f0678ccb2f6ac1b59a0e
train
class
class Process: """Execute a coroutine on a separate process.""" def __init__( self, group: None = None, target: Callable = None, name: str = None, args: Sequence[Any] = None, kwargs: Dict[str, Any] = None, *, daemon: bool = None, initializ...
class Process:
"""Execute a coroutine on a separate process.""" def __init__( self, group: None = None, target: Callable = None, name: str = None, args: Sequence[Any] = None, kwargs: Dict[str, Any] = None, *, daemon: bool = None, initializer: Optional[Ca...
an explicit string (eg, "fork") will force aiomultiprocess to use the given start method instead of "spawn". Passing an explicit `None` value will force aiomultiprocess to use CPython's default start method for the current platform rather than defaulting to "spawn". See the official multiprocessing d...
243
243
812
3
240
graingert/aiomultiprocess
aiomultiprocess/core.py
Python
Process
Process
77
197
77
77
96d46dd1b1b93e39b163dc92d38f3b7b80f8b10e
bigcode/the-stack
train