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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fc95b5f1873ef9a64c6a9ac3 | train | function | def isTimeAvailable(_order):
bookingData = roomTable.scan()["Items"]
_order["isAvailable"] = True
_order["alternative"] = []
for _bookingData in bookingData:
for _slot in _bookingData["slots"]:
if _slot["date"] == _order["date"]:
__stime = _stime = datetime.datetime.s... | def isTimeAvailable(_order):
| bookingData = roomTable.scan()["Items"]
_order["isAvailable"] = True
_order["alternative"] = []
for _bookingData in bookingData:
for _slot in _bookingData["slots"]:
if _slot["date"] == _order["date"]:
__stime = _stime = datetime.datetime.strptime(
... | import json
import datetime
import isodate
import boto3
# Create clients
sns = boto3.client('sns')
dynamodb = boto3.resource('dynamodb', region_name='eu-west-1')
roomTable = dynamodb.Table('myrecords')
# Check if is there any booking fot that day
def isTimeAvailable(_order):
| 73 | 93 | 311 | 7 | 65 | p-sk/AlexaMeetingRoomBooking | main-back.py | Python | isTimeAvailable | isTimeAvailable | 15 | 41 | 15 | 15 | f6b5d36360f966c3f3b06ffa2040ea32f54e5253 | bigcode/the-stack | train |
681a32660c58f9e8cd2ef15b | train | function | def bookSlot(_order):
_slot = [{
"date": _order["date"],
"endTime": _order["endTime"],
"startTime": _order["startTime"]
}]
try:
roomTable.update_item(
Key={
'room': _order["room"]
},
UpdateExpression="set slots = list_append... | def bookSlot(_order):
| _slot = [{
"date": _order["date"],
"endTime": _order["endTime"],
"startTime": _order["startTime"]
}]
try:
roomTable.update_item(
Key={
'room': _order["room"]
},
UpdateExpression="set slots = list_append(slots, :i)",
... | ["room"])
else:
if _bookingData["room"] != _order["room"]:
if _bookingData["room"] not in _order["alternative"]:
_order["alternative"].append(_bookingData["room"])
return _order
# Book the Slot
def bookSlot(_order):
| 64 | 64 | 145 | 6 | 57 | p-sk/AlexaMeetingRoomBooking | main-back.py | Python | bookSlot | bookSlot | 45 | 66 | 45 | 45 | cfea48cef630ead2689c0302fd876d636db68587 | bigcode/the-stack | train |
a09429f8f838cacbfcec37ce | train | function | def main(event, context):
# TODO implement
# Publish a simple message to the specified SNS topic
print(event)
if event["request"]["type"] == "IntentRequest":
if event["request"]["intent"]["name"] == "BookRoom":
if event["request"]["dialogState"] == "COMPLETED":
return... | def main(event, context):
# TODO implement
# Publish a simple message to the specified SNS topic
| print(event)
if event["request"]["type"] == "IntentRequest":
if event["request"]["intent"]["name"] == "BookRoom":
if event["request"]["dialogState"] == "COMPLETED":
return bookRoom(event, event["session"]["attributes"])
elif event["request"]["dialogState"] == "STA... | "value": _order["room"],
"resolutions": {},
"confirmationStatus": "NONE"
}
}
}
}
... | 64 | 64 | 174 | 23 | 40 | p-sk/AlexaMeetingRoomBooking | main-back.py | Python | main | main | 357 | 374 | 357 | 359 | 43106e7a5b054b262b5c3f34c7a9098f45a4c24f | bigcode/the-stack | train |
b07fe5c50e902c849ffb3f95 | train | function | def conformation(_order):
res = {"version": "1.0",
"sessionAttributes": _order,
"shouldEndSession": False,
"response": {
"outputSpeech": {
"type": "PlainText",
"text": "Ok Your request is for "+_order["room"]+" on "+_order["date"]... | def conformation(_order):
| res = {"version": "1.0",
"sessionAttributes": _order,
"shouldEndSession": False,
"response": {
"outputSpeech": {
"type": "PlainText",
"text": "Ok Your request is for "+_order["room"]+" on "+_order["date"]+" from "+_order["startTim... | "resolutions": {"resolutionsPerAuthority": [{
"authority": "amzn1.er-authority.echo-sdk.amzn1.ask.skill.49b043a1-f602-4f73-9d17-817f11a2a81e.AMAZON.Room"}
]
},
... | 107 | 107 | 358 | 6 | 100 | p-sk/AlexaMeetingRoomBooking | main-back.py | Python | conformation | conformation | 120 | 168 | 120 | 120 | 366ea826e8a0cb86ede5a97c138f8c671ffae0c3 | bigcode/the-stack | train |
8646eb4640eaf1ae981788c0 | train | function | def askAgain(msg, key, _order):
res = {"version": "1.0",
"sessionAttributes": _order,
"shouldEndSession": False,
"response": {
"outputSpeech": {
"type": "PlainText",
"text": msg
},
"directives": [
... | def askAgain(msg, key, _order):
| res = {"version": "1.0",
"sessionAttributes": _order,
"shouldEndSession": False,
"response": {
"outputSpeech": {
"type": "PlainText",
"text": msg
},
"directives": [
{
... | room': _order["room"]
},
UpdateExpression="set slots = list_append(slots, :i)",
ExpressionAttributeValues={
':i': _slot
},
ReturnValues="UPDATED_NEW"
)
_order["status"] = "COMPLETED"
except Exception as e:
print(e)
... | 97 | 97 | 325 | 10 | 86 | p-sk/AlexaMeetingRoomBooking | main-back.py | Python | askAgain | askAgain | 69 | 117 | 69 | 69 | 7cb9cea572b8e4a50b08b8f9daca8e9ccbc477c2 | bigcode/the-stack | train |
799872f602a949458a67a5fa | train | function | def slotValidation(event):
bookingData = roomTable.scan()["Items"]
order = {
"room": '',
"date": '',
"startTime": '',
"duration": ''
}
if event["request"]["intent"]["slots"]["room"]["value"]!= '':
_room = event["request"]["intent"]["slots"]["room"]["value"]
... | def slotValidation(event):
| bookingData = roomTable.scan()["Items"]
order = {
"room": '',
"date": '',
"startTime": '',
"duration": ''
}
if event["request"]["intent"]["slots"]["room"]["value"]!= '':
_room = event["request"]["intent"]["slots"]["room"]["value"]
for rooms in bookingData:... | Status": "NONE"
},
"time": {
"name": "time",
"value": _order["startTime"],
"confirmationStatus": "NONE"
... | 163 | 163 | 544 | 5 | 157 | p-sk/AlexaMeetingRoomBooking | main-back.py | Python | slotValidation | slotValidation | 171 | 221 | 171 | 171 | d680b138a02217e5f1e7c52a522cb24ade16aa14 | bigcode/the-stack | train |
73de758b3b99b839213753ef | train | function | def DTQPy_DEFECTS(A,B,G,d,internal,opts):
# Trapezoidal rule
if opts.dt.defects == 'TR':
[Aeq,beq] = DTQPy_DEFECTS_TR(A,B,G,d,internal,opts)
return Aeq,beq | def DTQPy_DEFECTS(A,B,G,d,internal,opts):
# Trapezoidal rule
| if opts.dt.defects == 'TR':
[Aeq,beq] = DTQPy_DEFECTS_TR(A,B,G,d,internal,opts)
return Aeq,beq | Primary Contributor: Daniel R. Herber (danielrherber on Github)
"""
from src.defects.DTQPy_DEFECTS_TR import DTQPy_DEFECTS_TR
def DTQPy_DEFECTS(A,B,G,d,internal,opts):
# Trapezoidal rule
| 64 | 64 | 68 | 25 | 38 | AthulKrishnaSundarrajan/dt-qp-py-project | src/defects/DTQPy_DEFECTS.py | Python | DTQPy_DEFECTS | DTQPy_DEFECTS | 12 | 18 | 12 | 14 | cde9a7b6659763705c2c7d8d994459b5ed13f1d9 | bigcode/the-stack | train |
c86f9a6566f79033021ae3c2 | train | class | class Migration(migrations.Migration):
dependencies = [
('core', '0004_recipe'),
]
operations = [
migrations.AddField(
model_name='recipe',
name='image',
field=models.ImageField(null=True, upload_to=core.models.recipe_image_file_path),
),
]
| class Migration(migrations.Migration):
| dependencies = [
('core', '0004_recipe'),
]
operations = [
migrations.AddField(
model_name='recipe',
name='image',
field=models.ImageField(null=True, upload_to=core.models.recipe_image_file_path),
),
]
| # Generated by Django 3.0.8 on 2020-07-10 21:55
import core.models
from django.db import migrations, models
class Migration(migrations.Migration):
| 42 | 64 | 64 | 7 | 34 | maenibreigheth/recipe-app-api | app/core/migrations/0005_recipe_image.py | Python | Migration | Migration | 7 | 19 | 7 | 8 | 6dbe54315c1e6af6c1fbead68f8c85a22067bbae | bigcode/the-stack | train |
76f7803ec54e2da365bf3acb | train | class | class Loss(Metric):
"""
Calculates the average loss according to the passed loss_fn.
Args:
loss_fn (callable): a callable taking a prediction tensor, a target
tensor, optionally other arguments, and returns the average loss
over all observations in the batch.
output_... | class Loss(Metric):
| """
Calculates the average loss according to the passed loss_fn.
Args:
loss_fn (callable): a callable taking a prediction tensor, a target
tensor, optionally other arguments, and returns the average loss
over all observations in the batch.
output_transform (callable)... | from __future__ import division
from ignite.exceptions import NotComputableError
from ignite.metrics.metric import Metric
class Loss(Metric):
| 28 | 132 | 443 | 5 | 22 | Mxbonn/ignite | ignite/metrics/loss.py | Python | Loss | Loss | 7 | 57 | 7 | 7 | 0577aa9429e6bf22c53de329ab7dde1ce7206ab6 | bigcode/the-stack | train |
a04286f3a756f0daa36222cf | train | class | class GpsInfo:
def __init__(self):
self.name = 'unknown'
self.latitude = 0.0
self.longitude = 0.0
def setName(self, name):
self.name = name
def setPosition(self, latitude, longitude):
self.latitude = latitude
self.longitude = longitude
def postGps(... | class GpsInfo:
| def __init__(self):
self.name = 'unknown'
self.latitude = 0.0
self.longitude = 0.0
def setName(self, name):
self.name = name
def setPosition(self, latitude, longitude):
self.latitude = latitude
self.longitude = longitude
def postGps(self, url):
... | import urllib.request
import json
class GpsInfo:
| 13 | 65 | 217 | 6 | 6 | yhs3434/SmartCarrier | RaspberryPi/gps_info.py | Python | GpsInfo | GpsInfo | 4 | 37 | 4 | 5 | 2e8c531f256aaded426e35c2ab47888ea53b2f69 | bigcode/the-stack | train |
9fc2485216e9a4e809f41153 | train | function | def parse_reference(url):
"""
Retrieve info from a url to a work item.
Examples:
```python
url = "https://dev.azure.com/MyOrganization/MyProject/_workitems/edit/73554"
parse_reference() == ('MyOrganization','MyProject','73554')
url = "https://dev.azure.com/MyOrganization/MyProject/_boards/... | def parse_reference(url):
| """
Retrieve info from a url to a work item.
Examples:
```python
url = "https://dev.azure.com/MyOrganization/MyProject/_workitems/edit/73554"
parse_reference() == ('MyOrganization','MyProject','73554')
url = "https://dev.azure.com/MyOrganization/MyProject/_boards/board/t/"
url += "MyTe... | -cli\n\n")
yaml.dump(required_params, file)
console.print("[dark_orange3]>[/dark_orange3] Create new .doing-cli-config.yml file")
console.print(
f"\t[dark_orange3]>[/dark_orange3] Filled in required parameters using reference work item #{item_id}"
)
def parse_reference(url):
| 75 | 75 | 251 | 5 | 70 | MHeus/doing-cli | src/doing/init/_init.py | Python | parse_reference | parse_reference | 64 | 98 | 64 | 64 | b9da3278f7425d70fc562302f44d7a1faf86c1ef | bigcode/the-stack | train |
a3e41245ea6a9bec3809cf34 | train | function | def cmd_init(reference_issue: str = ""):
"""
Create a .doing-cli-config file.
Empty file if no reference_url is specified.
Args:
reference_issue: URL of work item to use as reference
"""
if os.path.exists(".doing-cli-config.yml"):
console.print("File '.doing-cli-config.yml' alr... | def cmd_init(reference_issue: str = ""):
| """
Create a .doing-cli-config file.
Empty file if no reference_url is specified.
Args:
reference_issue: URL of work item to use as reference
"""
if os.path.exists(".doing-cli-config.yml"):
console.print("File '.doing-cli-config.yml' already exists.")
return
if not... | from doing.utils import run_command
from rich.console import Console
import os
import yaml
from urllib.parse import urlparse
console = Console()
def cmd_init(reference_issue: str = ""):
| 40 | 143 | 477 | 10 | 30 | MHeus/doing-cli | src/doing/init/_init.py | Python | cmd_init | cmd_init | 10 | 61 | 10 | 10 | 14623ed5cfcc771d99c3575fc2fb7dbc8527ab00 | bigcode/the-stack | train |
4c38efa9777795533b624637 | train | function | def parse_url(url):
url = urlparse(url)
kwargs = {}
for name, value in parse_qs(url.query).items():
if value and len(value) > 0:
value = unquote(value[0])
parser = URL_QUERY_ARGUMENT_PARSERS.get(name)
if parser:
try:
kwargs[nam... | def parse_url(url):
| url = urlparse(url)
kwargs = {}
for name, value in parse_qs(url.query).items():
if value and len(value) > 0:
value = unquote(value[0])
parser = URL_QUERY_ARGUMENT_PARSERS.get(name)
if parser:
try:
kwargs[name] = parser(value)
... | if value is None or value == '':
return None
if isinstance(value, str) and value.upper() in FALSE_STRINGS:
return False
return bool(value)
URL_QUERY_ARGUMENT_PARSERS = {
'db': int,
'socket_timeout': float,
'socket_connect_timeout': float,
'socket_keepalive': to_bool,
'retr... | 114 | 114 | 383 | 5 | 109 | Pigrenok/redis-py | redis/connection.py | Python | parse_url | parse_url | 950 | 1,000 | 950 | 950 | 69a80825e5f628b64ea45bd22dc949cad367f271 | bigcode/the-stack | train |
3123920fabb68a011f944123 | train | class | class BaseParser:
EXCEPTION_CLASSES = {
'ERR': {
'max number of clients reached': ConnectionError,
'Client sent AUTH, but no password is set': AuthenticationError,
'invalid password': AuthenticationError,
# some Redis server versions report invalid command syn... | class BaseParser:
| EXCEPTION_CLASSES = {
'ERR': {
'max number of clients reached': ConnectionError,
'Client sent AUTH, but no password is set': AuthenticationError,
'invalid password': AuthenticationError,
# some Redis server versions report invalid command syntax
# ... | , str):
value = value.encode(self.encoding, self.encoding_errors)
return value
def decode(self, value, force=False):
"Return a unicode string from the bytes-like representation"
if self.decode_responses or force:
if isinstance(value, memoryview):
valu... | 93 | 93 | 312 | 4 | 88 | Pigrenok/redis-py | redis/connection.py | Python | BaseParser | BaseParser | 130 | 166 | 130 | 130 | 7a6c7195448a6f4516b27e2b31c756dffc75951e | bigcode/the-stack | train |
f1ce3931a80b0416c64e5566 | train | function | def to_bool(value):
if value is None or value == '':
return None
if isinstance(value, str) and value.upper() in FALSE_STRINGS:
return False
return bool(value)
| def to_bool(value):
| if value is None or value == '':
return None
if isinstance(value, str) and value.upper() in FALSE_STRINGS:
return False
return bool(value)
| [0])
else:
return "Error %s connecting to unix socket: %s. %s." % \
(exception.args[0], self.path, exception.args[1])
FALSE_STRINGS = ('0', 'F', 'FALSE', 'N', 'NO')
def to_bool(value):
| 64 | 64 | 43 | 5 | 59 | Pigrenok/redis-py | redis/connection.py | Python | to_bool | to_bool | 930 | 935 | 930 | 930 | 9a0a99423ccb8196708b6dd9cfab85e338f20923 | bigcode/the-stack | train |
1ff42ec0cfdada68098a38dc | train | class | class HiredisParser(BaseParser):
"Parser class for connections using Hiredis"
def __init__(self, socket_read_size):
if not HIREDIS_AVAILABLE:
raise RedisError("Hiredis is not installed")
self.socket_read_size = socket_read_size
if HIREDIS_USE_BYTE_BUFFER:
self._b... | class HiredisParser(BaseParser):
| "Parser class for connections using Hiredis"
def __init__(self, socket_read_size):
if not HIREDIS_AVAILABLE:
raise RedisError("Hiredis is not installed")
self.socket_read_size = socket_read_size
if HIREDIS_USE_BYTE_BUFFER:
self._buffer = bytearray(socket_read_siz... | response = response.decode('utf-8', errors='replace')
error = self.parse_error(response)
# if the error is a ConnectionError, raise immediately so the user
# is notified
if isinstance(error, ConnectionError):
raise error
# otherwise... | 256 | 256 | 975 | 8 | 247 | Pigrenok/redis-py | redis/connection.py | Python | HiredisParser | HiredisParser | 368 | 487 | 368 | 368 | d2fafc45a4d993955477cfa49b0624edf75c1188 | bigcode/the-stack | train |
e77db724fa5f320786e060c8 | train | class | class Encoder:
"Encode strings to bytes-like and decode bytes-like to strings"
def __init__(self, encoding, encoding_errors, decode_responses):
self.encoding = encoding
self.encoding_errors = encoding_errors
self.decode_responses = decode_responses
def encode(self, value):
... | class Encoder:
| "Encode strings to bytes-like and decode bytes-like to strings"
def __init__(self, encoding, encoding_errors, decode_responses):
self.encoding = encoding
self.encoding_errors = encoding_errors
self.decode_responses = decode_responses
def encode(self, value):
"Return a bytes... | = 'Error loading the extension. ' \
'Please check the server logs.'
NO_SUCH_MODULE_ERROR = 'Error unloading module: no such module with that name'
MODULE_UNLOAD_NOT_POSSIBLE_ERROR = 'Error unloading module: operation not ' \
'possible.'
MODULE_EXPORTS_DATA_TYPES_E... | 94 | 94 | 315 | 3 | 91 | Pigrenok/redis-py | redis/connection.py | Python | Encoder | Encoder | 93 | 127 | 93 | 93 | 33e45508a692da56d8ca65beda85a749965227e3 | bigcode/the-stack | train |
3b402f9443c0294d1b5041a0 | train | class | class SocketBuffer:
def __init__(self, socket, socket_read_size, socket_timeout):
self._sock = socket
self.socket_read_size = socket_read_size
self.socket_timeout = socket_timeout
self._buffer = io.BytesIO()
# number of bytes written to the buffer from the socket
self... | class SocketBuffer:
| def __init__(self, socket, socket_read_size, socket_timeout):
self._sock = socket
self.socket_read_size = socket_read_size
self.socket_timeout = socket_timeout
self._buffer = io.BytesIO()
# number of bytes written to the buffer from the socket
self.bytes_written = 0
... | # in lowercase
'wrong number of arguments for \'auth\' command':
AuthenticationWrongNumberOfArgsError,
# some Redis server versions report invalid command syntax
# in uppercase
'wrong number of arguments for \'AUTH\' command':
A... | 256 | 256 | 854 | 4 | 252 | Pigrenok/redis-py | redis/connection.py | Python | SocketBuffer | SocketBuffer | 169 | 286 | 169 | 169 | 30ee51e72d17a87b6ffe108c822557593e887886 | bigcode/the-stack | train |
105c6d2ca8d4b09aef4af5db | train | class | class SSLConnection(Connection):
def __init__(self, ssl_keyfile=None, ssl_certfile=None,
ssl_cert_reqs='required', ssl_ca_certs=None,
ssl_check_hostname=False, **kwargs):
if not ssl_available:
raise RedisError("Python wasn't built with SSL support")
su... | class SSLConnection(Connection):
| def __init__(self, ssl_keyfile=None, ssl_certfile=None,
ssl_cert_reqs='required', ssl_ca_certs=None,
ssl_check_hostname=False, **kwargs):
if not ssl_available:
raise RedisError("Python wasn't built with SSL support")
super().__init__(**kwargs)
... | if (buffer_length > buffer_cutoff or chunklen > buffer_cutoff
or isinstance(chunk, memoryview)):
output.append(SYM_EMPTY.join(pieces))
buffer_length = 0
pieces = []
if chunklen > buffer_cutoff or isinstance(chunk, memo... | 103 | 103 | 344 | 5 | 97 | Pigrenok/redis-py | redis/connection.py | Python | SSLConnection | SSLConnection | 833 | 873 | 833 | 834 | 64e690dc24bca26f4cf825e53c93dd71fc296d62 | bigcode/the-stack | train |
a2e136b5b33d3f0c8e7aa864 | train | class | class Connection:
"Manages TCP communication to and from a Redis server"
def __init__(self, host='localhost', port=6379, db=0, password=None,
socket_timeout=None, socket_connect_timeout=None,
socket_keepalive=False, socket_keepalive_options=None,
socket_type=0... | class Connection:
| "Manages TCP communication to and from a Redis server"
def __init__(self, host='localhost', port=6379, db=0, password=None,
socket_timeout=None, socket_connect_timeout=None,
socket_keepalive=False, socket_keepalive_options=None,
socket_type=0, retry_on_timeout... | is not False:
response = self._next_response
self._next_response = False
return response
response = self._reader.gets()
while response is False:
self.read_from_socket()
response = self._reader.gets()
# if an older version of hiredis i... | 256 | 256 | 2,641 | 3 | 252 | Pigrenok/redis-py | redis/connection.py | Python | Connection | Connection | 496 | 830 | 496 | 496 | 1f7306d15eab5f5aada2f9b1ca677ace74299b93 | bigcode/the-stack | train |
23deb0c1619a6ccd66e033a1 | train | class | class ConnectionPool:
"""
Create a connection pool. ``If max_connections`` is set, then this
object raises :py:class:`~redis.ConnectionError` when the pool's
limit is reached.
By default, TCP connections are created unless ``connection_class``
is specified. Use :py:class:`~redis.UnixDomainSocke... | class ConnectionPool:
| """
Create a connection pool. ``If max_connections`` is set, then this
object raises :py:class:`~redis.ConnectionError` when the pool's
limit is reached.
By default, TCP connections are created unless ``connection_class``
is specified. Use :py:class:`~redis.UnixDomainSocketConnection` for
u... | (url.username)
if url.password:
kwargs['password'] = unquote(url.password)
# We only support redis://, rediss:// and unix:// schemes.
if url.scheme == 'unix':
if url.path:
kwargs['path'] = unquote(url.path)
kwargs['connection_class'] = UnixDomainSocketConnection
eli... | 256 | 256 | 2,150 | 4 | 251 | Pigrenok/redis-py | redis/connection.py | Python | ConnectionPool | ConnectionPool | 1,003 | 1,241 | 1,003 | 1,003 | 5bab248008d4787f85ddb6c9eaec07d6a3fbc03b | bigcode/the-stack | train |
08344a4012ded90431a9d5dc | train | class | class PythonParser(BaseParser):
"Plain Python parsing class"
def __init__(self, socket_read_size):
self.socket_read_size = socket_read_size
self.encoder = None
self._sock = None
self._buffer = None
def __del__(self):
try:
self.on_disconnect()
exce... | class PythonParser(BaseParser):
| "Plain Python parsing class"
def __init__(self, socket_read_size):
self.socket_read_size = socket_read_size
self.encoder = None
self._sock = None
self._buffer = None
def __del__(self):
try:
self.on_disconnect()
except Exception:
pass
... | == self.bytes_written:
self.purge()
return data[:-2]
def purge(self):
self._buffer.seek(0)
self._buffer.truncate()
self.bytes_written = 0
self.bytes_read = 0
def close(self):
try:
self.purge()
self._buffer.close()
ex... | 162 | 162 | 541 | 6 | 155 | Pigrenok/redis-py | redis/connection.py | Python | PythonParser | PythonParser | 289 | 365 | 289 | 289 | ebc14f765d0bd8288ba0186af177b7cfd406bfcf | bigcode/the-stack | train |
2fb0215f2ff692d674d88ac0 | train | class | class UnixDomainSocketConnection(Connection):
def __init__(self, path='', db=0, username=None, password=None,
socket_timeout=None, encoding='utf-8',
encoding_errors='strict', decode_responses=False,
retry_on_timeout=False,
parser_class=DefaultPars... | class UnixDomainSocketConnection(Connection):
| def __init__(self, path='', db=0, username=None, password=None,
socket_timeout=None, encoding='utf-8',
encoding_errors='strict', decode_responses=False,
retry_on_timeout=False,
parser_class=DefaultParser, socket_read_size=65536,
he... | self.check_hostname = ssl_check_hostname
def _connect(self):
"Wrap the socket with SSL support"
sock = super()._connect()
context = ssl.create_default_context()
context.check_hostname = self.check_hostname
context.verify_mode = self.cert_reqs
if self.certfile... | 123 | 123 | 412 | 7 | 116 | Pigrenok/redis-py | redis/connection.py | Python | UnixDomainSocketConnection | UnixDomainSocketConnection | 876 | 924 | 876 | 877 | af2c5fbd12b6c8fd1d4caa78728c95709db967ba | bigcode/the-stack | train |
6efc098aa843931d334e2b4d | train | class | class BlockingConnectionPool(ConnectionPool):
"""
Thread-safe blocking connection pool::
>>> from redis.client import Redis
>>> client = Redis(connection_pool=BlockingConnectionPool())
It performs the same function as the default
:py:class:`~redis.ConnectionPool` implementation, in tha... | class BlockingConnectionPool(ConnectionPool):
| """
Thread-safe blocking connection pool::
>>> from redis.client import Redis
>>> client = Redis(connection_pool=BlockingConnectionPool())
It performs the same function as the default
:py:class:`~redis.ConnectionPool` implementation, in that,
it maintains a pool of reusable connect... | ._lock:
try:
self._in_use_connections.remove(connection)
except KeyError:
# Gracefully fail when a connection is returned to this pool
# that the pool doesn't actually own
pass
if self.owns_connection(connection):
... | 256 | 256 | 1,244 | 7 | 249 | Pigrenok/redis-py | redis/connection.py | Python | BlockingConnectionPool | BlockingConnectionPool | 1,244 | 1,395 | 1,244 | 1,244 | 424c83c7ff1d6897ffc397979284ab08b98b8942 | bigcode/the-stack | train |
dc7f8dfd7473a3b942b7e1fd | train | class | class DnsRecord(AWSProperty):
props = {
'TTL': (basestring, True),
'Type': (basestring, True),
}
| class DnsRecord(AWSProperty):
| props = {
'TTL': (basestring, True),
'Type': (basestring, True),
}
| FailureThreshold': (float, False),
'ResourcePath': (basestring, False),
'Type': (basestring, True),
}
class HealthCheckCustomConfig(AWSProperty):
props = {
'FailureThreshold': (float, True)
}
class DnsRecord(AWSProperty):
| 64 | 64 | 34 | 8 | 56 | DrLuke/troposphere | troposphere/servicediscovery.py | Python | DnsRecord | DnsRecord | 52 | 56 | 52 | 52 | 7e2dddf7ae6d74a80b0dbaa98c87aa58f210ac70 | bigcode/the-stack | train |
581ed1f6128f6e9149c69b07 | train | class | class HealthCheckCustomConfig(AWSProperty):
props = {
'FailureThreshold': (float, True)
}
| class HealthCheckCustomConfig(AWSProperty):
| props = {
'FailureThreshold': (float, True)
}
| Name': (basestring, True),
}
class HealthCheckConfig(AWSProperty):
props = {
'FailureThreshold': (float, False),
'ResourcePath': (basestring, False),
'Type': (basestring, True),
}
class HealthCheckCustomConfig(AWSProperty):
| 64 | 64 | 25 | 9 | 55 | DrLuke/troposphere | troposphere/servicediscovery.py | Python | HealthCheckCustomConfig | HealthCheckCustomConfig | 46 | 49 | 46 | 46 | 01f02d06d0759b376c9b3fbd37b62795bcb3f763 | bigcode/the-stack | train |
0e3cde98ced88c1b7cfd9d84 | train | class | class Service(AWSObject):
resource_type = "AWS::ServiceDiscovery::Service"
props = {
'Description': (basestring, False),
'DnsConfig': (DnsConfig, True),
'HealthCheckConfig': (HealthCheckConfig, False),
'HealthCheckCustomConfig': (HealthCheckCustomConfig, False),
'Name': ... | class Service(AWSObject):
| resource_type = "AWS::ServiceDiscovery::Service"
props = {
'Description': (basestring, False),
'DnsConfig': (DnsConfig, True),
'HealthCheckConfig': (HealthCheckConfig, False),
'HealthCheckCustomConfig': (HealthCheckCustomConfig, False),
'Name': (basestring, False),
... | 'Type': (basestring, True),
}
class DnsConfig(AWSProperty):
props = {
'DnsRecords': ([DnsRecord], True),
'NamespaceId': (basestring, True),
'RoutingPolicy': (basestring, False),
}
class Service(AWSObject):
| 64 | 64 | 94 | 6 | 58 | DrLuke/troposphere | troposphere/servicediscovery.py | Python | Service | Service | 67 | 77 | 67 | 67 | 564c021b0220459a0ef1bca9ffcfd36f9f09f319 | bigcode/the-stack | train |
d8539893aff028c92fab8640 | train | class | class Instance(AWSObject):
resource_type = "AWS::ServiceDiscovery::Instance"
props = {
'InstanceAttributes': (dict, True),
'InstanceId': (basestring, False),
'ServiceId': (basestring, True),
}
| class Instance(AWSObject):
| resource_type = "AWS::ServiceDiscovery::Instance"
props = {
'InstanceAttributes': (dict, True),
'InstanceId': (basestring, False),
'ServiceId': (basestring, True),
}
| # Copyright (c) 2012-2017, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty
class Instance(AWSObject):
| 49 | 64 | 56 | 6 | 42 | DrLuke/troposphere | troposphere/servicediscovery.py | Python | Instance | Instance | 9 | 16 | 9 | 9 | 60f134d9c9a8ab58a1431bf1b48b594257f79460 | bigcode/the-stack | train |
c35d65c65a6cf15e8ad6c60d | train | class | class HealthCheckConfig(AWSProperty):
props = {
'FailureThreshold': (float, False),
'ResourcePath': (basestring, False),
'Type': (basestring, True),
}
| class HealthCheckConfig(AWSProperty):
| props = {
'FailureThreshold': (float, False),
'ResourcePath': (basestring, False),
'Type': (basestring, True),
}
| (basestring, True),
}
class PublicDnsNamespace(AWSObject):
resource_type = "AWS::ServiceDiscovery::PublicDnsNamespace"
props = {
'Description': (basestring, False),
'Name': (basestring, True),
}
class HealthCheckConfig(AWSProperty):
| 64 | 64 | 45 | 8 | 56 | DrLuke/troposphere | troposphere/servicediscovery.py | Python | HealthCheckConfig | HealthCheckConfig | 38 | 43 | 38 | 38 | 6c8ab910c75cac2c6604ee98a19cda3332238da2 | bigcode/the-stack | train |
58a85718d4dabc7fbca4b447 | train | class | class PublicDnsNamespace(AWSObject):
resource_type = "AWS::ServiceDiscovery::PublicDnsNamespace"
props = {
'Description': (basestring, False),
'Name': (basestring, True),
}
| class PublicDnsNamespace(AWSObject):
| resource_type = "AWS::ServiceDiscovery::PublicDnsNamespace"
props = {
'Description': (basestring, False),
'Name': (basestring, True),
}
| DnsNamespace(AWSObject):
resource_type = "AWS::ServiceDiscovery::PrivateDnsNamespace"
props = {
'Description': (basestring, False),
'Name': (basestring, True),
'Vpc': (basestring, True),
}
class PublicDnsNamespace(AWSObject):
| 64 | 64 | 48 | 8 | 56 | DrLuke/troposphere | troposphere/servicediscovery.py | Python | PublicDnsNamespace | PublicDnsNamespace | 29 | 35 | 29 | 29 | 4f777ff79faf8ee9928e8863194dca469bf1192a | bigcode/the-stack | train |
ac54995bd955bca7157482c8 | train | class | class DnsConfig(AWSProperty):
props = {
'DnsRecords': ([DnsRecord], True),
'NamespaceId': (basestring, True),
'RoutingPolicy': (basestring, False),
}
| class DnsConfig(AWSProperty):
| props = {
'DnsRecords': ([DnsRecord], True),
'NamespaceId': (basestring, True),
'RoutingPolicy': (basestring, False),
}
| CustomConfig(AWSProperty):
props = {
'FailureThreshold': (float, True)
}
class DnsRecord(AWSProperty):
props = {
'TTL': (basestring, True),
'Type': (basestring, True),
}
class DnsConfig(AWSProperty):
| 64 | 64 | 47 | 8 | 56 | DrLuke/troposphere | troposphere/servicediscovery.py | Python | DnsConfig | DnsConfig | 59 | 64 | 59 | 59 | 3ea37096a2eec13b695b29e94865e61a5f797813 | bigcode/the-stack | train |
e401e85ec6ebdd41eaacaede | train | class | class HttpNamespace(AWSObject):
resource_type = "AWS::ServiceDiscovery::HttpNamespace"
props = {
'Description': (basestring, False),
'Name': (basestring, True),
}
| class HttpNamespace(AWSObject):
| resource_type = "AWS::ServiceDiscovery::HttpNamespace"
props = {
'Description': (basestring, False),
'Name': (basestring, True),
}
| (DnsConfig, True),
'HealthCheckConfig': (HealthCheckConfig, False),
'HealthCheckCustomConfig': (HealthCheckCustomConfig, False),
'Name': (basestring, False),
'NamespaceId': (basestring, False),
}
class HttpNamespace(AWSObject):
| 64 | 64 | 46 | 7 | 57 | DrLuke/troposphere | troposphere/servicediscovery.py | Python | HttpNamespace | HttpNamespace | 80 | 86 | 80 | 80 | dc5d9610071a4d5f1ca0a680d1e3aca98b9c6f9b | bigcode/the-stack | train |
875530f266b618a3cfe9b4f8 | train | class | class PrivateDnsNamespace(AWSObject):
resource_type = "AWS::ServiceDiscovery::PrivateDnsNamespace"
props = {
'Description': (basestring, False),
'Name': (basestring, True),
'Vpc': (basestring, True),
}
| class PrivateDnsNamespace(AWSObject):
| resource_type = "AWS::ServiceDiscovery::PrivateDnsNamespace"
props = {
'Description': (basestring, False),
'Name': (basestring, True),
'Vpc': (basestring, True),
}
| class Instance(AWSObject):
resource_type = "AWS::ServiceDiscovery::Instance"
props = {
'InstanceAttributes': (dict, True),
'InstanceId': (basestring, False),
'ServiceId': (basestring, True),
}
class PrivateDnsNamespace(AWSObject):
| 64 | 64 | 58 | 8 | 56 | DrLuke/troposphere | troposphere/servicediscovery.py | Python | PrivateDnsNamespace | PrivateDnsNamespace | 19 | 26 | 19 | 19 | eab81e927893301407c6202bd80bf1b1ad804026 | bigcode/the-stack | train |
199d5657b538468ab4eb7ba5 | train | class | class IPItem(scrapy.Item):
ip = scrapy.Field(
input_processor=MapCompose(str, str.strip),
output_processor=TakeFirst()
)
port = scrapy.Field(
input_processor=MapCompose(str, str.strip),
output_processor=TakeFirst()
)
protocol = scrapy.Field(
input_processor=Ma... | class IPItem(scrapy.Item):
| ip = scrapy.Field(
input_processor=MapCompose(str, str.strip),
output_processor=TakeFirst()
)
port = scrapy.Field(
input_processor=MapCompose(str, str.strip),
output_processor=TakeFirst()
)
protocol = scrapy.Field(
input_processor=MapCompose(str, str.strip, st... | """
author: thomaszdxsn
"""
import scrapy
from scrapy.loader.processors import TakeFirst, MapCompose, Join
__all__ = ("IPItem",)
class IPItem(scrapy.Item):
| 43 | 64 | 141 | 7 | 36 | thomaszdxsn/SpiderNest | SpiderNest/items/ip.py | Python | IPItem | IPItem | 10 | 30 | 10 | 10 | 2ce71ce108a5e966c4f84b2a4d4e1dcc3c1d56c8 | bigcode/the-stack | train |
1969ffc634c670953d9b606f | train | class | class txttoxml():
'''
Esta clases se encarga de convertir un txt separado por un caracter especificado a xml
'''
def __init__(self):
'''
Constructor
'''
"""Funcion para procesar los datos de un txt y convertirlo a xml
Parametros
filesource: Nombre del archivo de or... | class txttoxml():
| '''
Esta clases se encarga de convertir un txt separado por un caracter especificado a xml
'''
def __init__(self):
'''
Constructor
'''
"""Funcion para procesar los datos de un txt y convertirlo a xml
Parametros
filesource: Nombre del archivo de origen
filedesti... | __author__ = 'Ariel Anthieni'
'''
Created on 20/04/2015
'''
#Cargo las librerias
import xml.dom.minidom
class txttoxml():
| 41 | 256 | 1,414 | 5 | 35 | elcoloo/metadata-tools | conversor.py | Python | txttoxml | txttoxml | 12 | 188 | 12 | 12 | af992371786c3f2bd4747827ecc4d99b6de4dcb2 | bigcode/the-stack | train |
9c26a283000de1ea67dec587 | train | class | class QueryStrParam(ParamInterpreter):
"""Evaluate the 'q' parameter."""
def apply(self, identity, search, params):
"""Evaluate the query str on the search."""
query_str = params.get('q')
if not query_str:
return search
try:
parser_cls = self.config.quer... | class QueryStrParam(ParamInterpreter):
| """Evaluate the 'q' parameter."""
def apply(self, identity, search, params):
"""Evaluate the query str on the search."""
query_str = params.get('q')
if not query_str:
return search
try:
parser_cls = self.config.query_parser_cls
query = parser... | string into a Elasticsearch DSL Q object."""
def __init__(self, identity=None):
"""Initialise the parser."""
self.identity = identity
def parse(self, query_str):
"""Parse the query."""
return Q('query_string', query=query_str)
class QueryStrParam(ParamInterpreter):
| 64 | 64 | 113 | 8 | 56 | jrcastro2/invenio-records-resources | invenio_records_resources/services/records/params/querystr.py | Python | QueryStrParam | QueryStrParam | 28 | 43 | 28 | 28 | e73919fe86d15f66b143cb02756fd016c9dc2b75 | bigcode/the-stack | train |
c6215a8f932995703b614b49 | train | class | class QueryParser:
"""Parse query string into a Elasticsearch DSL Q object."""
def __init__(self, identity=None):
"""Initialise the parser."""
self.identity = identity
def parse(self, query_str):
"""Parse the query."""
return Q('query_string', query=query_str)
| class QueryParser:
| """Parse query string into a Elasticsearch DSL Q object."""
def __init__(self, identity=None):
"""Initialise the parser."""
self.identity = identity
def parse(self, query_str):
"""Parse the query."""
return Q('query_string', query=query_str)
| # Invenio-Records-Resources is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see LICENSE file for more
# details.
"""Query parameter interpreter API."""
from elasticsearch_dsl import Q
from .base import ParamInterpreter
class QueryParser:
| 64 | 64 | 64 | 4 | 59 | jrcastro2/invenio-records-resources | invenio_records_resources/services/records/params/querystr.py | Python | QueryParser | QueryParser | 16 | 25 | 16 | 16 | 9f181a212c11c75e061e8e3e31b9fcae66d6cdff | bigcode/the-stack | train |
9ff075a55af527310678706f | train | function | def training():
global count
model.train()
bar = progressbar.ProgressBar(max_value=len(train_loader))
for i, sample in enumerate(train_loader):
# forward steps
# output
xdata = Variable(sample['xdata'].cuda())
label = Variable(sample['label']).cuda()
ydata_bin = Variable(sample['ydata_bin']).cuda().squeez... | def training():
| global count
model.train()
bar = progressbar.ProgressBar(max_value=len(train_loader))
for i, sample in enumerate(train_loader):
# forward steps
# output
xdata = Variable(sample['xdata'].cuda())
label = Variable(sample['label']).cuda()
ydata_bin = Variable(sample['ydata_bin']).cuda().squeeze()
ydata = Va... | optimizer.zero_grad()
loss.backward()
optimizer.step()
# store
count += 1
writer.add_scalar('train_loss', loss.item(), count)
# cleanup
del xdata, ydata_bin, ydata_res, output, loss, Lc, Lr
bar.update(i+1)
def training():
| 78 | 78 | 263 | 3 | 75 | zawlin/multi-modal-regression | learnObjectnetModel.py | Python | training | training | 170 | 197 | 170 | 170 | a02c13736781ab4fe1352d6f08f91b1f4850df77 | bigcode/the-stack | train |
297b947771de30f15c1e7c65 | train | function | def testing():
model.eval()
ypred = []
ytrue = []
labels = []
bar = progressbar.ProgressBar(max_value=len(test_loader))
for i, sample in enumerate(test_loader):
xdata = Variable(sample['xdata'].cuda())
label = Variable(sample['label'].cuda())
output = model(xdata, label)
ypred_bin = np.argmax(output[0].da... | def testing():
| model.eval()
ypred = []
ytrue = []
labels = []
bar = progressbar.ProgressBar(max_value=len(test_loader))
for i, sample in enumerate(test_loader):
xdata = Variable(sample['xdata'].cuda())
label = Variable(sample['label'].cuda())
output = model(xdata, label)
ypred_bin = np.argmax(output[0].data.cpu().numpy(... | optimizer.step()
# store
count += 1
writer.add_scalar('train_loss', loss.item(), count)
# cleanup
del xdata, ydata_bin, ydata, output, y, Lr, Lc, loss, ind
bar.update(i+1)
def testing():
| 69 | 69 | 233 | 3 | 66 | zawlin/multi-modal-regression | learnObjectnetModel.py | Python | testing | testing | 200 | 223 | 200 | 200 | 4237807bccd72929443bba6e095ac86ec4aa9a62 | bigcode/the-stack | train |
e28168b0f8037a747691241c | train | class | class TestImages(Dataset):
def __init__(self, data_path, classes):
self.db_path = data_path
self.classes = classes
self.num_classes = len(self.classes)
self.list_image_names = []
self.list_labels = []
for i in range(self.num_classes):
tmp = spio.loadmat(os.path.join(self.db_path, self.classes[i] + '_inf... | class TestImages(Dataset):
| def __init__(self, data_path, classes):
self.db_path = data_path
self.classes = classes
self.num_classes = len(self.classes)
self.list_image_names = []
self.list_labels = []
for i in range(self.num_classes):
tmp = spio.loadmat(os.path.join(self.db_path, self.classes[i] + '_info'), squeeze_me=True)
im... | ]])
cluster_centers_ = Variable(torch.from_numpy(kmeans_dict).float()).cuda()
num_clusters = 16
# loss
mse_loss = nn.MSELoss().cuda()
ce_loss = nn.CrossEntropyLoss().cuda()
gve_loss = geodesic_loss().cuda()
# DATA
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
preprocess = tr... | 125 | 125 | 417 | 6 | 119 | zawlin/multi-modal-regression | learnObjectnetModel.py | Python | TestImages | TestImages | 79 | 115 | 79 | 79 | d6c5cc859dbe3e8f4837eba9560c76da4a1757f9 | bigcode/the-stack | train |
8e1b01ebfae9624006936e27 | train | function | def training_init():
global count
model.train()
bar = progressbar.ProgressBar(max_value=len(train_loader))
for i, sample in enumerate(train_loader):
# forward steps
# outputs
xdata = Variable(sample['xdata'].cuda())
label = Variable(sample['label']).cuda()
ydata_bin = Variable(sample['ydata_bin']).cuda().... | def training_init():
| global count
model.train()
bar = progressbar.ProgressBar(max_value=len(train_loader))
for i, sample in enumerate(train_loader):
# forward steps
# outputs
xdata = Variable(sample['xdata'].cuda())
label = Variable(sample['label']).cuda()
ydata_bin = Variable(sample['ydata_bin']).cuda().squeeze()
ydata_res... | .Adam(model.parameters(), lr=args.init_lr)
scheduler = optim.lr_scheduler.LambdaLR(optimizer, lambda ep: (10**-(ep//10))/(1+ep%10))
# store stuff
writer = SummaryWriter(log_dir)
count = 0
val_loss = []
# OPTIMIZATION functions
def training_init():
| 68 | 68 | 228 | 4 | 63 | zawlin/multi-modal-regression | learnObjectnetModel.py | Python | training_init | training_init | 142 | 167 | 142 | 142 | 2fc05aaa3244050e8485970d65688db298fedbbc | bigcode/the-stack | train |
38559f9e55faf8575bb8deb1 | train | function | def save_checkpoint(filename):
torch.save(model.state_dict(), filename)
| def save_checkpoint(filename):
| torch.save(model.state_dict(), filename)
| del xdata, label, output, sample
gc.collect()
bar.update(i+1)
ypred = np.concatenate(ypred)
ytrue = np.concatenate(ytrue)
labels = np.concatenate(labels)
model.train()
return ytrue, ypred, labels
def save_checkpoint(filename):
| 64 | 64 | 14 | 5 | 58 | zawlin/multi-modal-regression | learnObjectnetModel.py | Python | save_checkpoint | save_checkpoint | 226 | 227 | 226 | 226 | aee93a5e4548a36e18ef2f4c3f2a5004bf262e54 | bigcode/the-stack | train |
206e1b4527d218ef5b809fc8 | train | function | def standard_normal_cdf(x):
result = (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0
return result
| def standard_normal_cdf(x):
| result = (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0
return result
| import math
import sys
def standard_normal_cdf(x):
| 13 | 64 | 37 | 7 | 5 | zeyger/Hackerrank-solutions | 10 days of statistics/Day 6/The Central Limit Theorem I-II.py | Python | standard_normal_cdf | standard_normal_cdf | 5 | 7 | 5 | 5 | 0790656f6632df7b2dece88d48facbbc348bcda0 | bigcode/the-stack | train |
5ddab390343b987adc6a5d03 | train | function | def normal_cdf(x, mean, std):
x = standardize_value(x, mean, std)
return standard_normal_cdf(x)
| def normal_cdf(x, mean, std):
| x = standardize_value(x, mean, std)
return standard_normal_cdf(x)
| _cdf(x):
result = (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0
return result
def standardize_value(value, mean, std):
return (value - mean) / std
def normal_cdf(x, mean, std):
| 64 | 64 | 30 | 10 | 53 | zeyger/Hackerrank-solutions | 10 days of statistics/Day 6/The Central Limit Theorem I-II.py | Python | normal_cdf | normal_cdf | 14 | 16 | 14 | 14 | 8b6c07b5e9b6b029fe1dfabf8ac38e0257e84356 | bigcode/the-stack | train |
e29e0df9a2c8e2066b9958fa | train | function | def main():
capability = float(sys.stdin.readline())
count = int(sys.stdin.readline())
atom_mean = float(sys.stdin.readline())
atom_std = float(sys.stdin.readline())
new_mean = count * atom_mean
new_std = math.sqrt(count) * atom_std
result = normal_cdf(capability, new_mean, new_std)
pri... | def main():
| capability = float(sys.stdin.readline())
count = int(sys.stdin.readline())
atom_mean = float(sys.stdin.readline())
atom_std = float(sys.stdin.readline())
new_mean = count * atom_mean
new_std = math.sqrt(count) * atom_std
result = normal_cdf(capability, new_mean, new_std)
print("{0:.4f}"... | ))) / 2.0
return result
def standardize_value(value, mean, std):
return (value - mean) / std
def normal_cdf(x, mean, std):
x = standardize_value(x, mean, std)
return standard_normal_cdf(x)
def main():
| 64 | 64 | 84 | 3 | 61 | zeyger/Hackerrank-solutions | 10 days of statistics/Day 6/The Central Limit Theorem I-II.py | Python | main | main | 19 | 28 | 19 | 19 | 60668232f66db1e976d5ddfdd7641914b32856bb | bigcode/the-stack | train |
d2f16ec10cf9f00b1e4e579e | train | function | def standardize_value(value, mean, std):
return (value - mean) / std
| def standardize_value(value, mean, std):
| return (value - mean) / std
| import math
import sys
def standard_normal_cdf(x):
result = (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0
return result
def standardize_value(value, mean, std):
| 53 | 64 | 20 | 10 | 42 | zeyger/Hackerrank-solutions | 10 days of statistics/Day 6/The Central Limit Theorem I-II.py | Python | standardize_value | standardize_value | 10 | 11 | 10 | 10 | b51b683de3915ee4bf24a58a4eba6e056aae7a0e | bigcode/the-stack | train |
d590b281e9505a9d91d761da | train | function | def getContours(img,imgContour):
contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for cnt in contours:
area = cv2.contourArea(cnt)
areaMin = cv2.getTrackbarPos("Area", "Parameters")
if area > areaMin:
cv2.drawContours(imgContour, cnt... | def getContours(img,imgContour):
| contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for cnt in contours:
area = cv2.contourArea(cnt)
areaMin = cv2.getTrackbarPos("Area", "Parameters")
if area > areaMin:
cv2.drawContours(imgContour, cnt, -1, (255, 0, 255), 7)
... | (imgArray[x], (imgArray[0].shape[1], imgArray[0].shape[0]), None,scale, scale)
if len(imgArray[x].shape) == 2: imgArray[x] = cv2.cvtColor(imgArray[x], cv2.COLOR_GRAY2BGR)
hor= np.hstack(imgArray)
ver = hor
return ver
def getContours(img,imgContour):
| 88 | 88 | 295 | 7 | 80 | LasalJayawardena/CNN-Projects | Real_Time_Shape_Contour_Detection/mai.py | Python | getContours | getContours | 50 | 66 | 50 | 50 | 0c8e2727e80f9d4142ac9d80f246619c03851193 | bigcode/the-stack | train |
f1152b8549b498be2b8eaf74 | train | function | def stackImages(scale,imgArray):
rows = len(imgArray)
cols = len(imgArray[0])
rowsAvailable = isinstance(imgArray[0], list)
width = imgArray[0][0].shape[1]
height = imgArray[0][0].shape[0]
if rowsAvailable:
for x in range ( 0, rows):
for y in range(0, cols):
... | def stackImages(scale,imgArray):
| rows = len(imgArray)
cols = len(imgArray[0])
rowsAvailable = isinstance(imgArray[0], list)
width = imgArray[0][0].shape[1]
height = imgArray[0][0].shape[0]
if rowsAvailable:
for x in range ( 0, rows):
for y in range(0, cols):
if imgArray[x][y].shape[:2... | import cv2
import numpy as np
frameWidth = 640
frameHeight = 480
cap = cv2.VideoCapture(0)
cap.set(3, frameWidth)
cap.set(4, frameHeight)
def empty(a):
pass
cv2.namedWindow("Parameters")
cv2.resizeWindow("Parameters",640,240)
cv2.createTrackbar("Threshold1","Parameters",23,255,empty)
cv2.createTra... | 130 | 134 | 449 | 7 | 123 | LasalJayawardena/CNN-Projects | Real_Time_Shape_Contour_Detection/mai.py | Python | stackImages | stackImages | 19 | 48 | 19 | 19 | cb720293f856b40deb0791e44475888a7390fbbf | bigcode/the-stack | train |
e477e34156cbdd962254d8e1 | train | function | def empty(a):
pass
| def empty(a):
| pass
| import cv2
import numpy as np
frameWidth = 640
frameHeight = 480
cap = cv2.VideoCapture(0)
cap.set(3, frameWidth)
cap.set(4, frameHeight)
def empty(a):
| 50 | 64 | 7 | 4 | 46 | LasalJayawardena/CNN-Projects | Real_Time_Shape_Contour_Detection/mai.py | Python | empty | empty | 10 | 11 | 10 | 10 | 7081a1586b1437e36f54c11717ecfd98bd5eb0e8 | bigcode/the-stack | train |
c98b5fdaca8c48a4fde74ed8 | train | class | class BaseTestCase(unittest.TestCase):
TEST_UNIQUE_ID = 1
TESTNAME_PREFIX = 'test_regrtest_'
TESTNAME_REGEX = r'test_[a-zA-Z0-9_]+'
def setUp(self):
self.testdir = os.path.realpath(os.path.dirname(__file__))
self.tmptestdir = tempfile.mkdtemp()
self.addCleanup(support.rmtree, s... | class BaseTestCase(unittest.TestCase):
| TEST_UNIQUE_ID = 1
TESTNAME_PREFIX = 'test_regrtest_'
TESTNAME_REGEX = r'test_[a-zA-Z0-9_]+'
def setUp(self):
self.testdir = os.path.realpath(os.path.dirname(__file__))
self.tmptestdir = tempfile.mkdtemp()
self.addCleanup(support.rmtree, self.tmptestdir)
def create_test(se... | )
def test_two_options(self):
ns = libregrtest._parse_args(['--quiet', '--exclude'])
self.assertTrue(ns.quiet)
self.assertEqual(ns.verbose, 0)
self.assertTrue(ns.exclude)
def test_option_with_empty_string_value(self):
ns = libregrtest._parse_args(['--start', ''])
... | 256 | 256 | 1,544 | 8 | 248 | chexca/cpython | Lib/test/test_regrtest.py | Python | BaseTestCase | BaseTestCase | 357 | 547 | 357 | 357 | 90102cbed179ea3bc4e0ddbed7de5b2eafdaa6e4 | bigcode/the-stack | train |
ee99c8129b6b7f45a8c3d1ee | train | class | class ParseArgsTestCase(unittest.TestCase):
"""
Test regrtest's argument parsing, function _parse_args().
"""
def checkError(self, args, msg):
with support.captured_stderr() as err, self.assertRaises(SystemExit):
libregrtest._parse_args(args)
self.assertIn(msg, err.getvalue(... | class ParseArgsTestCase(unittest.TestCase):
| """
Test regrtest's argument parsing, function _parse_args().
"""
def checkError(self, args, msg):
with support.captured_stderr() as err, self.assertRaises(SystemExit):
libregrtest._parse_args(args)
self.assertIn(msg, err.getvalue())
def test_help(self):
for opt... | """
Tests of regrtest.py.
Note: test_regrtest cannot be run twice in parallel.
"""
import contextlib
import glob
import io
import os.path
import platform
import re
import subprocess
import sys
import sysconfig
import tempfile
import textwrap
import unittest
from test import libregrtest
from test import support
from t... | 222 | 256 | 2,994 | 9 | 213 | chexca/cpython | Lib/test/test_regrtest.py | Python | ParseArgsTestCase | ParseArgsTestCase | 39 | 354 | 39 | 39 | 9752b2c1fc72cc2dd2b1170369b0d8733b3eff3a | bigcode/the-stack | train |
3a99e06df9efc5b967a99839 | train | class | class ProgramsTestCase(BaseTestCase):
"""
Test various ways to run the Python test suite. Use options close
to options used on the buildbot.
"""
NTEST = 4
def setUp(self):
super().setUp()
# Create NTEST tests doing nothing
self.tests = [self.create_test() for index in ... | class ProgramsTestCase(BaseTestCase):
| """
Test various ways to run the Python test suite. Use options close
to options used on the buildbot.
"""
NTEST = 4
def setUp(self):
super().setUp()
# Create NTEST tests doing nothing
self.tests = [self.create_test() for index in range(self.NTEST)]
self.pytho... | def test_finds_expected_number_of_tests(self):
args = ['-Wd', '-E', '-bb', '-m', 'test.regrtest', '--list-tests']
output = self.run_python(args)
rough_number_of_tests_found = len(output.splitlines())
actual_testsuite_glob = os.path.join(os.path.dirname(__file__),
... | 255 | 256 | 1,084 | 8 | 247 | chexca/cpython | Lib/test/test_regrtest.py | Python | ProgramsTestCase | ProgramsTestCase | 575 | 686 | 575 | 575 | eb8bfd2cecbdfa924c12c13773146c3a84a773d8 | bigcode/the-stack | train |
9a4dc6c9abfe61bc7f07a448 | train | class | class ArgsTestCase(BaseTestCase):
"""
Test arguments of the Python test suite.
"""
def run_tests(self, *testargs, **kw):
cmdargs = ['-m', 'test', '--testdir=%s' % self.tmptestdir, *testargs]
return self.run_python(cmdargs, **kw)
def test_failing_test(self):
# test a failing... | class ArgsTestCase(BaseTestCase):
| """
Test arguments of the Python test suite.
"""
def run_tests(self, *testargs, **kw):
cmdargs = ['-m', 'test', '--testdir=%s' % self.tmptestdir, *testargs]
return self.run_python(cmdargs, **kw)
def test_failing_test(self):
# test a failing test
code = textwrap.dede... | if not Py_DEBUG:
test_args.append('+d') # Release build, use python.exe
self.run_batch(script, *test_args, *self.tests)
@unittest.skipUnless(sys.platform == 'win32', 'Windows only')
def test_pcbuild_rt(self):
# PCbuild\rt.bat
script = os.path.join(ROOT_DIR, r'PCb... | 256 | 256 | 4,598 | 8 | 248 | chexca/cpython | Lib/test/test_regrtest.py | Python | ArgsTestCase | ArgsTestCase | 689 | 1,277 | 689 | 689 | df6e563ae61705f8a333b98c726426eb5b596566 | bigcode/the-stack | train |
b8308c819ffbe394e30c9780 | train | class | class TestUtils(unittest.TestCase):
def test_format_duration(self):
self.assertEqual(utils.format_duration(0),
'0 ms')
self.assertEqual(utils.format_duration(1e-9),
'1 ms')
self.assertEqual(utils.format_duration(10e-3),
... | class TestUtils(unittest.TestCase):
| def test_format_duration(self):
self.assertEqual(utils.format_duration(0),
'0 ms')
self.assertEqual(utils.format_duration(1e-9),
'1 ms')
self.assertEqual(utils.format_duration(10e-3),
'10 ms')
self.assertEqual... | = [dirname, filename]
cmdargs = ['-m', 'test',
'--tempdir=%s' % self.tmptestdir,
'--cleanup']
self.run_python(cmdargs)
for name in names:
self.assertFalse(os.path.exists(name), name)
class TestUtils(unittest.TestCase):
| 65 | 65 | 219 | 7 | 58 | chexca/cpython | Lib/test/test_regrtest.py | Python | TestUtils | TestUtils | 1,280 | 1,301 | 1,280 | 1,280 | 07f7dc0668475c9dfeeda74934a3a7c04d267a43 | bigcode/the-stack | train |
9d723c919f6517acd875ac7f | train | class | class CheckActualTests(BaseTestCase):
"""
Check that regrtest appears to find the expected set of tests.
"""
def test_finds_expected_number_of_tests(self):
args = ['-Wd', '-E', '-bb', '-m', 'test.regrtest', '--list-tests']
output = self.run_python(args)
rough_number_of_tests_fou... | class CheckActualTests(BaseTestCase):
| """
Check that regrtest appears to find the expected set of tests.
"""
def test_finds_expected_number_of_tests(self):
args = ['-Wd', '-E', '-bb', '-m', 'test.regrtest', '--list-tests']
output = self.run_python(args)
rough_number_of_tests_found = len(output.splitlines())
... | "
"%s"
"---\n"
% proc.stderr)
self.fail(msg)
return proc
def run_python(self, args, **kw):
args = [sys.executable, '-X', 'faulthandler', '-I', *args]
proc = self.run_command(args, **kw)
return proc.s... | 82 | 82 | 274 | 8 | 73 | chexca/cpython | Lib/test/test_regrtest.py | Python | CheckActualTests | CheckActualTests | 550 | 572 | 550 | 550 | d50d5a8757062c9f93553f143a9ef29b9260c84b | bigcode/the-stack | train |
0bdbd24320ff7a9b251bf4cd | train | class | class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("members", "0015_auto_20200928_1757"),
]
operations = [
migrations.AlterField(
model_name="member",
name="user",
field=models.Fore... | class Migration(migrations.Migration):
| dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("members", "0015_auto_20200928_1757"),
]
operations = [
migrations.AlterField(
model_name="member",
name="user",
field=models.ForeignKey(
blank=True,
... | # Generated by Django 3.1.1 on 2020-09-29 14:41
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| 51 | 64 | 103 | 7 | 43 | NUMBART/officialWebsite | officialWebsite/members/migrations/0016_auto_20200929_1441.py | Python | Migration | Migration | 8 | 27 | 8 | 9 | 872398ae5feff0bfcbe9354f916b7cbec137f8a2 | bigcode/the-stack | train |
12ed4c1f9500b5973a00de7c | train | class | class Migration(migrations.Migration):
dependencies = [
('catalog', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='bookinstance',
old_name='imprint',
new_name='member',
),
]
| class Migration(migrations.Migration):
| dependencies = [
('catalog', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='bookinstance',
old_name='imprint',
new_name='member',
),
]
| # Generated by Django 3.0.4 on 2020-03-15 13:52
from django.db import migrations
class Migration(migrations.Migration):
| 36 | 64 | 56 | 7 | 28 | FuYuuSub1/CAS30Web | catalog/migrations/0002_auto_20200315_2152.py | Python | Migration | Migration | 6 | 18 | 6 | 7 | f5f7ab2811d7b95c421ccae355b2a8c455641ec6 | bigcode/the-stack | train |
0256007372bdf8bafab504e4 | train | class | class LogrotateTest(oeRuntimeTest):
@skipUnlessPassed("test_ssh")
def test_1_logrotate_setup(self):
(status, output) = self.target.run('mkdir $HOME/logrotate_dir')
self.assertEqual(status, 0, msg = "Could not create logrotate_dir. Output: %s" % output)
(status, output) = self.target.run... | class LogrotateTest(oeRuntimeTest):
@skipUnlessPassed("test_ssh")
| def test_1_logrotate_setup(self):
(status, output) = self.target.run('mkdir $HOME/logrotate_dir')
self.assertEqual(status, 0, msg = "Could not create logrotate_dir. Output: %s" % output)
(status, output) = self.target.run("sed -i \"s#wtmp {#wtmp {\\n olddir $HOME/logrotate_dir#\" /etc/log... | _case.cgi?case_id=289 testcase
# Note that the image under test must have logrotate installed
import unittest
from oeqa.oetest import oeRuntimeTest, skipModule
from oeqa.utils.decorators import *
def setUpModule():
if not oeRuntimeTest.hasPackage("logrotate"):
skipModule("No logrotate package in image")
c... | 92 | 92 | 307 | 19 | 73 | prakhya/luv_sai | meta/lib/oeqa/runtime/logrotate.py | Python | LogrotateTest | LogrotateTest | 13 | 28 | 13 | 15 | 34abcd105fb10cec91ffe9805f5ad6228214adf1 | bigcode/the-stack | train |
cdc8fb6abfe7444aa964198e | train | function | def setUpModule():
if not oeRuntimeTest.hasPackage("logrotate"):
skipModule("No logrotate package in image")
| def setUpModule():
| if not oeRuntimeTest.hasPackage("logrotate"):
skipModule("No logrotate package in image")
| This test should cover https://bugzilla.yoctoproject.org/tr_show_case.cgi?case_id=289 testcase
# Note that the image under test must have logrotate installed
import unittest
from oeqa.oetest import oeRuntimeTest, skipModule
from oeqa.utils.decorators import *
def setUpModule():
| 64 | 64 | 28 | 5 | 59 | prakhya/luv_sai | meta/lib/oeqa/runtime/logrotate.py | Python | setUpModule | setUpModule | 8 | 10 | 8 | 8 | 4d59333f9aeecc003dace1846684c41fb3a7f8cc | bigcode/the-stack | train |
0ffc4be872325a64e3676839 | train | class | class Session(object):
"""
CORE session manager.
"""
def __init__(self, _id, config=None, mkdir=True):
"""
Create a Session instance.
:param int _id: session id
:param dict config: session configuration
:param bool mkdir: flag to determine if a directory should ... | class Session(object):
| """
CORE session manager.
"""
def __init__(self, _id, config=None, mkdir=True):
"""
Create a Session instance.
:param int _id: session id
:param dict config: session configuration
:param bool mkdir: flag to determine if a directory should be made
"""
... | roker import CoreBroker
from core.emane.emanemanager import EmaneManager
from core.emulator.data import EventData, NodeData
from core.emulator.data import ExceptionData
from core.emulator.emudata import LinkOptions, NodeOptions
from core.emulator.emudata import IdGen
from core.emulator.emudata import is_net_node
from c... | 256 | 256 | 12,562 | 4 | 251 | lmerat46/core | daemon/core/emulator/session.py | Python | Session | Session | 48 | 1,659 | 48 | 48 | 0221ad8237e5557985c2f671bffd4d1f1331062a | bigcode/the-stack | train |
934ac1e0c81b4396ebcca392 | train | class | class RegisterSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email', 'password')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
user = User.objects.create_user(validated_data['username'], valida... | class RegisterSerializer(serializers.ModelSerializer):
| class Meta:
model = User
fields = ('id', 'username', 'email', 'password')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
user = User.objects.create_user(validated_data['username'], validated_data['email'], validated_data['password'])
... | _only': True}}
def create(self, validated_data):
user = User(
email=validated_data['email'],
username=validated_data['username']
)
user.set_password(validated_data['password'])
user.save()
return user
# Register Serializer
class RegisterSerializer(ser... | 64 | 64 | 78 | 7 | 56 | Jorge-DevOps/API_HealthTech | Apps/LoginUsuarios/serializers.py | Python | RegisterSerializer | RegisterSerializer | 20 | 29 | 20 | 20 | 4b8fd6d14e2168f5574832d134e467080042387a | bigcode/the-stack | train |
9c5efc1189f40d8fc6f0c178 | train | class | class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email','password')
extra_kwargs = {'password':{'write_only': True}}
def create(self, validated_data):
user = User(
email=validated_data['email'],
usern... | class UserSerializer(serializers.ModelSerializer):
| class Meta:
model = User
fields = ('id', 'username', 'email','password')
extra_kwargs = {'password':{'write_only': True}}
def create(self, validated_data):
user = User(
email=validated_data['email'],
username=validated_data['username']
)
us... | from rest_framework import serializers
from django.contrib.auth.models import User
# User Serializer
class UserSerializer(serializers.ModelSerializer):
| 25 | 64 | 92 | 7 | 17 | Jorge-DevOps/API_HealthTech | Apps/LoginUsuarios/serializers.py | Python | UserSerializer | UserSerializer | 5 | 17 | 5 | 5 | 2b93cf9a83d5f053ace5e49cc594ac55263523e9 | bigcode/the-stack | train |
984f609b06d9f55670db1c2f | train | class | class TestRefreshIpOperation(TestCase):
def setUp(self):
self.ec2_session = Mock()
self.instance_service = Mock()
self.refresh_ip_operation = RefreshIpOperation(self.instance_service)
self.instance = Mock()
self.cloudshell_session = Mock()
self.cloudshell_session.Set... | class TestRefreshIpOperation(TestCase):
| def setUp(self):
self.ec2_session = Mock()
self.instance_service = Mock()
self.refresh_ip_operation = RefreshIpOperation(self.instance_service)
self.instance = Mock()
self.cloudshell_session = Mock()
self.cloudshell_session.SetAttributeValue = Mock()
self.clo... | from unittest import TestCase
from mock import Mock
from cloudshell.cp.aws.domain.ami_management.operations.refresh_ip_operation import RefreshIpOperation
class TestRefreshIpOperation(TestCase):
| 37 | 177 | 590 | 8 | 28 | DYeag/AWS-Shell | package/tests/test_ami_management/test_operations/test_refresh_ip_operation.py | Python | TestRefreshIpOperation | TestRefreshIpOperation | 7 | 76 | 7 | 7 | 255fcd56810750ef5fe2285a502380941a19be66 | bigcode/the-stack | train |
c07408d7646fc136d1912772 | train | function | def gather_cell(node):
"""Create a variable node of Gather cell.
Args:
node: A DeepHyper variable node object.
Returns:
A variable node of Gather cell.
"""
for functions in [GlobalSumPool, GlobalMaxPool, GlobalAvgPool]:
for axis in [-1, -2]: # Pool in terms of no... | def gather_cell(node):
| """Create a variable node of Gather cell.
Args:
node: A DeepHyper variable node object.
Returns:
A variable node of Gather cell.
"""
for functions in [GlobalSumPool, GlobalMaxPool, GlobalAvgPool]:
for axis in [-1, -2]: # Pool in terms of nodes or features
... | _op(SPARSE_MPNN(state_dim=state_dim,
T=T,
attn_method=attn_method,
attn_head=attn_head,
aggr... | 64 | 64 | 134 | 5 | 58 | deephyper/nas-gcn | nas_gcn_new_deepchem/search_space_utils.py | Python | gather_cell | gather_cell | 53 | 69 | 53 | 53 | e2fa035cd539115afb40ef291d02c204ea50917a | bigcode/the-stack | train |
8149ed8ca9a27e8597a111a9 | train | function | def mpnn_cell(node):
"""Create a variable node of MPNN cell.
Args:
node: A DeepHyper variable node object.
Returns:
A variable node of MPNN cell.
"""
state_dims = [4, 8, 16, 32]
Ts = [1, 2, 3, 4]
attn_methods = ['const', 'gcn', 'gat', 'sym-gat', 'linear', 'gen-li... | def mpnn_cell(node):
| """Create a variable node of MPNN cell.
Args:
node: A DeepHyper variable node object.
Returns:
A variable node of MPNN cell.
"""
state_dims = [4, 8, 16, 32]
Ts = [1, 2, 3, 4]
attn_methods = ['const', 'gcn', 'gat', 'sym-gat', 'linear', 'gen-linear', 'cos']
att... | as.model.space.op.merge import AddByProjecting
from nas_gcn.search.stack_mpnn import GlobalAvgPool, GlobalSumPool, GlobalMaxPool, SPARSE_MPNN, GlobalAttentionPool, GlobalAttentionSumPool
from deephyper.search.nas.model.space.op.op1d import Dense, Flatten
from deephyper.search.nas.model.space.op.connect import Connec... | 99 | 99 | 333 | 6 | 92 | deephyper/nas-gcn | nas_gcn_new_deepchem/search_space_utils.py | Python | mpnn_cell | mpnn_cell | 12 | 50 | 12 | 12 | dd6639e4ea96ec9f832d8d7fc45b28c9a4239234 | bigcode/the-stack | train |
bf3087f809a055c0018ae193 | train | function | def create_search_space(input_shape=None,
output_shape=None,
num_mpnn_cells=3,
num_dense_layers=2,
**kwargs):
"""Create a search space containing multiple Keras architectures
Args:
input_shape (list)... | def create_search_space(input_shape=None,
output_shape=None,
num_mpnn_cells=3,
num_dense_layers=2,
**kwargs):
| """Create a search space containing multiple Keras architectures
Args:
input_shape (list): the input shapes, e.g. [(3, 4), (5, 2)].
output_shape (tuple): the output shape, e.g. (12, ).
num_mpnn_cells (int): the number of MPNN cells.
num_dense_layers (int): the number of De... | n_heads:
for aggr_method in aggr_methods:
for update_method in update_methods:
for activation in activations:
node.add_op(SPARSE_MPNN(state_dim=state_dim,
... | 256 | 256 | 1,024 | 32 | 223 | deephyper/nas-gcn | nas_gcn_new_deepchem/search_space_utils.py | Python | create_search_space | create_search_space | 72 | 163 | 72 | 76 | a3edd35e0ae9ac6be6748d81b1bc935646a7ad72 | bigcode/the-stack | train |
a8e013bdbb6c0680df62ba4a | train | class | class webserver:
def __init__(self, request_timeout=3, max_concurrency=3, backlog=16, debug=False):
"""Tiny Web Server class.
Keyword arguments:
request_timeout - Time for client to send complete request
after that connection will be closed.
max... | class webserver:
| def __init__(self, request_timeout=3, max_concurrency=3, backlog=16, debug=False):
"""Tiny Web Server class.
Keyword arguments:
request_timeout - Time for client to send complete request
after that connection will be closed.
max_concurrency - How... | # Response is HTTP/1.1 with Connection: close
resp.version = '1.1'
resp.add_header('Connection', 'close')
resp.add_header('Content-Type', 'application/json')
resp.add_header('Transfer-Encoding', 'chunked')
resp.add_access_control_headers()
await resp._send_headers()
... | 256 | 256 | 2,607 | 4 | 252 | mwilco03/tinyweb | tinyweb/server.py | Python | webserver | webserver | 369 | 691 | 369 | 370 | 89262f89fbfcc292b23257f677fb005dfd05b3a7 | bigcode/the-stack | train |
6d20bbdecf5d6ff22ec72e34 | train | function | async def restful_resource_handler(req, resp, param=None):
"""Handler for RESTful API endpoins"""
# Gather data - query string, JSON in request body...
data = await req.read_parse_form_data()
# Add parameters from URI query string as well
# This one is actually for simply development of RestAPI
... | async def restful_resource_handler(req, resp, param=None):
| """Handler for RESTful API endpoins"""
# Gather data - query string, JSON in request body...
data = await req.read_parse_form_data()
# Add parameters from URI query string as well
# This one is actually for simply development of RestAPI
if req.query_string != b'':
data.update(parse_query... | tell browser to cache it, however, you can always
# override it by setting max_age to zero
self.add_header('Cache-Control', 'max-age={}, public'.format(max_age))
with open(filename) as f:
await self._send_headers()
gc.collect()
buf = b... | 162 | 162 | 541 | 12 | 149 | mwilco03/tinyweb | tinyweb/server.py | Python | restful_resource_handler | restful_resource_handler | 309 | 366 | 309 | 309 | 82c3bd4f0174abf935351f05bd1b15268c2866dd | bigcode/the-stack | train |
df859bfc211ded622a9463e4 | train | class | class HTTPException(Exception):
"""HTTP protocol exceptions"""
def __init__(self, code=400):
self.code = code
| class HTTPException(Exception):
| """HTTP protocol exceptions"""
def __init__(self, code=400):
self.code = code
| pairs:
vals = [urldecode_plus(x) for x in p.split('=', 1)]
if len(vals) == 1:
res[vals[0]] = ''
else:
res[vals[0]] = vals[1]
return res
class HTTPException(Exception):
| 64 | 64 | 28 | 5 | 58 | mwilco03/tinyweb | tinyweb/server.py | Python | HTTPException | HTTPException | 60 | 64 | 60 | 60 | fa6e2f60638abf6c180bc473249e6b9a25f4dc4c | bigcode/the-stack | train |
fe60db9cde67e835d8c44e40 | train | function | def urldecode_plus(s):
"""Decode urlencoded string (including '+' char).
Returns decoded string
"""
s = s.replace('+', ' ')
arr = s.split('%')
res = arr[0]
for it in arr[1:]:
if len(it) >= 2:
res += chr(int(it[:2], 16)) + it[2:]
elif len(it) == 0:
res... | def urldecode_plus(s):
| """Decode urlencoded string (including '+' char).
Returns decoded string
"""
s = s.replace('+', ' ')
arr = s.split('%')
res = arr[0]
for it in arr[1:]:
if len(it) >= 2:
res += chr(int(it[:2], 16)) + it[2:]
elif len(it) == 0:
res += '%'
else:
... | subtle
# but breaking changes. See also https://github.com/peterhinch/micropython-async/blob/master/v3/README.md
IS_UASYNCIO_V3 = hasattr(asyncio, "__version__") and asyncio.__version__ >= (3,)
def urldecode_plus(s):
| 63 | 64 | 109 | 7 | 56 | mwilco03/tinyweb | tinyweb/server.py | Python | urldecode_plus | urldecode_plus | 26 | 41 | 26 | 26 | 0e4cdfcdb3194f0007b8948091e71d43a48b3647 | bigcode/the-stack | train |
71057d7c4aa20695740caf5f | train | class | class request:
"""HTTP Request class"""
def __init__(self, _reader):
self.reader = _reader
self.headers = {}
self.method = b''
self.path = b''
self.query_string = b''
async def read_request_line(self):
"""Read and parse first line (AKA HTTP Request Line).
... | class request:
| """HTTP Request class"""
def __init__(self, _reader):
self.reader = _reader
self.headers = {}
self.method = b''
self.path = b''
self.query_string = b''
async def read_request_line(self):
"""Read and parse first line (AKA HTTP Request Line).
Function ... | .replace('+', ' ')
arr = s.split('%')
res = arr[0]
for it in arr[1:]:
if len(it) >= 2:
res += chr(int(it[:2], 16)) + it[2:]
elif len(it) == 0:
res += '%'
else:
res += it
return res
def parse_query_string(s):
"""Parse urlencoded string int... | 206 | 206 | 688 | 3 | 202 | mwilco03/tinyweb | tinyweb/server.py | Python | request | request | 67 | 154 | 67 | 67 | 688abedbbe99471ad82fabd7f58207f03eb66f79 | bigcode/the-stack | train |
9d7d89de2ba77fea25112919 | train | function | def parse_query_string(s):
"""Parse urlencoded string into dict.
Returns dict
"""
res = {}
pairs = s.split('&')
for p in pairs:
vals = [urldecode_plus(x) for x in p.split('=', 1)]
if len(vals) == 1:
res[vals[0]] = ''
else:
res[vals[0]] = vals[1]
... | def parse_query_string(s):
| """Parse urlencoded string into dict.
Returns dict
"""
res = {}
pairs = s.split('&')
for p in pairs:
vals = [urldecode_plus(x) for x in p.split('=', 1)]
if len(vals) == 1:
res[vals[0]] = ''
else:
res[vals[0]] = vals[1]
return res
| in arr[1:]:
if len(it) >= 2:
res += chr(int(it[:2], 16)) + it[2:]
elif len(it) == 0:
res += '%'
else:
res += it
return res
def parse_query_string(s):
| 64 | 64 | 95 | 6 | 57 | mwilco03/tinyweb | tinyweb/server.py | Python | parse_query_string | parse_query_string | 44 | 57 | 44 | 44 | ef169f73d50c84a56e2db8bc0bf8e552d1f1855c | bigcode/the-stack | train |
2b480f4d7f9e184284ca79a1 | train | class | class response:
"""HTTP Response class"""
def __init__(self, _writer):
self.writer = _writer
self.send = _writer.awrite
self.code = 200
self.version = '1.0'
self.headers = {}
async def _send_headers(self):
"""Compose and send:
- HTTP request line
... | class response:
| """HTTP Response class"""
def __init__(self, _writer):
self.writer = _writer
self.send = _writer.awrite
self.code = 200
self.version = '1.0'
self.headers = {}
async def _send_headers(self):
"""Compose and send:
- HTTP request line
- HTTP head... | - None in case of no form data present
"""
# TODO: Probably there is better solution how to handle
# request body, at least for simple urlencoded forms - by processing
# chunks instead of accumulating payload.
gc.collect()
if b'Content-Length' not in self.headers:
... | 256 | 256 | 1,081 | 3 | 253 | mwilco03/tinyweb | tinyweb/server.py | Python | response | response | 157 | 306 | 157 | 157 | 32c855804673c8737cf14f2454757352945777d0 | bigcode/the-stack | train |
f11ff0a7f589440ca7082b98 | train | class | class TestSequentialEventContainer(unittest.TestCase):
root = ET.fromstring('''
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg"
id="root_id">
<path id="path0"/>
<path id="path1"/>
</svg>
''')
paths = SvgUtils.svg_paths... | class TestSequentialEventContainer(unittest.TestCase):
| root = ET.fromstring('''
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg"
id="root_id">
<path id="path0"/>
<path id="path1"/>
</svg>
''')
paths = SvgUtils.svg_paths(root)
def test_ctor(self):
buff = io.Stri... | from svganimator import SvgUtils
from svganimator.PathEvent import PathEvent
from svganimator.SequentialEventContainer import SequentialEventContainer
import io
import unittest
import xml.etree.ElementTree as ET
class TestSequentialEventContainer(unittest.TestCase):
| 54 | 87 | 290 | 9 | 44 | felipepiovezan/svg_html_animation | tests/test_SequentialEventContainer.py | Python | TestSequentialEventContainer | TestSequentialEventContainer | 9 | 40 | 9 | 9 | 1f3d2c61c3fd91d2a9faf17513149e7cd662953e | bigcode/the-stack | train |
92e11f5a949b54a7cf4977cd | train | class | class PerlAlienLibxml2(PerlPackage):
"""This module provides libxml2 for other modules to use."""
homepage = "https://metacpan.org/pod/Alien::Libxml2"
url = "https://cpan.metacpan.org/authors/id/P/PL/PLICEASE/Alien-Libxml2-0.10_01.tar.gz"
version('0.10_01', sha256='2f45b308b33503292f48bf46a75fe1e... | class PerlAlienLibxml2(PerlPackage):
| """This module provides libxml2 for other modules to use."""
homepage = "https://metacpan.org/pod/Alien::Libxml2"
url = "https://cpan.metacpan.org/authors/id/P/PL/PLICEASE/Alien-Libxml2-0.10_01.tar.gz"
version('0.10_01', sha256='2f45b308b33503292f48bf46a75fe1e653d6b209ba5caf0628d8cc103f8d61ac')
... | Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PerlAlienLibxml2(PerlPackage):
| 64 | 64 | 168 | 11 | 53 | LiamBindle/spack | var/spack/repos/builtin/packages/perl-alien-libxml2/package.py | Python | PerlAlienLibxml2 | PerlAlienLibxml2 | 9 | 19 | 9 | 9 | 45d1ff4fb586afc0c19d58d977b45cf814e59cee | bigcode/the-stack | train |
7b26c0942df940a80467a8f4 | train | function | def ReadDevice(port):
"""
ReadDevice(Port)
Port - String - name of serial port
"""
ser = serial.Serial(port)
ser.flushInput()
while True:
try:
ser_bytes = ser.readline()
reading = ser_bytes[0:len(ser_bytes)-2].decode("utf-8")
... | def ReadDevice(port):
| """
ReadDevice(Port)
Port - String - name of serial port
"""
ser = serial.Serial(port)
ser.flushInput()
while True:
try:
ser_bytes = ser.readline()
reading = ser_bytes[0:len(ser_bytes)-2].decode("utf-8")
return... | jh
"""
import serial
def isOpen(port):
try:
erm = serial.Serial(port, timeout=1)
if erm.read():
return "ready"
else:
return "not_ready"
except:
return "not_connected"
def ReadDevice(port):
| 63 | 64 | 92 | 6 | 57 | ajharvie/LockInSensor | Frontend/communicator.py | Python | ReadDevice | ReadDevice | 24 | 46 | 24 | 25 | e12e034eeb101ca0bdcf1f41eec35fb60a7c3ecc | bigcode/the-stack | train |
10352b9f229947289cf0c220 | train | function | def isOpen(port):
try:
erm = serial.Serial(port, timeout=1)
if erm.read():
return "ready"
else:
return "not_ready"
except:
return "not_connected"
| def isOpen(port):
| try:
erm = serial.Serial(port, timeout=1)
if erm.read():
return "ready"
else:
return "not_ready"
except:
return "not_connected"
| # -*- coding: utf-8 -*-
"""
Created on Mon Nov 26 12:40:38 2018
@author: andrewjh
"""
import serial
def isOpen(port):
| 41 | 64 | 51 | 5 | 35 | ajharvie/LockInSensor | Frontend/communicator.py | Python | isOpen | isOpen | 10 | 22 | 10 | 10 | c18b50f9abcf11f509901b13e4c84a965a1b50f1 | bigcode/the-stack | train |
c481c1193af36682cd308fb0 | train | class | class PackageSource:
def __init__(self, name=None, url=None, fname=None, recipe=None):
self.name = name
self.url = url
self.fname = fname
self.recipe = recipe
def to_name(self):
return self.name or self.url or self.to_fname()
def to_fname(self):
if self.fnam... | class PackageSource:
| def __init__(self, name=None, url=None, fname=None, recipe=None):
self.name = name
self.url = url
self.fname = fname
self.recipe = recipe
def to_name(self):
return self.name or self.url or self.to_fname()
def to_fname(self):
if self.fname is None: self.fname... | six, dirhash, hashlib, os
import cget.util as util
def encode_url(url):
x = six.b(url[url.find('://')+3:])
return '_url_' + base64.urlsafe_b64encode(x).decode('utf-8').replace('=', '_')
def decode_url(url):
s = url.replace('_', '=')[5:]
return base64.urlsafe_b64decode(str(s)).decode('utf-8')
class Pa... | 99 | 99 | 332 | 4 | 95 | pixelwise/cget | cget/package.py | Python | PackageSource | PackageSource | 12 | 53 | 12 | 12 | e6668b85ae1573a3241201261cc8298f85730d67 | bigcode/the-stack | train |
8c0d4a1779b1948e7c54077c | train | class | class PackageBuild:
def __init__(self, pkg_src=None, define=None, parent=None, test=False, hash=None, build=None, cmake=None, variant=None, requirements=None, file=None):
self.pkg_src = pkg_src
self.define = define or []
self.parent = parent
self.test = test
self.build = buil... | class PackageBuild:
| def __init__(self, pkg_src=None, define=None, parent=None, test=False, hash=None, build=None, cmake=None, variant=None, requirements=None, file=None):
self.pkg_src = pkg_src
self.define = define or []
self.parent = parent
self.test = test
self.build = build
self.hash ... | .path.join(dirpath, filename)
data[key] = util.lines_of_file(fullpath)
return data
elif self.url:
return self.url
raise Exception("no url or recipe: %s" % self.__dict__)
def fname_to_pkg(fname):
if fname.startswith('_url_'): return PackageSource(name=deco... | 99 | 99 | 332 | 4 | 95 | pixelwise/cget | cget/package.py | Python | PackageBuild | PackageBuild | 59 | 100 | 59 | 59 | daee9cff23d2842bd1d2ad09f2f3fdaed437341d | bigcode/the-stack | train |
91f592e3920a4adb5d69aab3 | train | function | def encode_url(url):
x = six.b(url[url.find('://')+3:])
return '_url_' + base64.urlsafe_b64encode(x).decode('utf-8').replace('=', '_')
| def encode_url(url):
| x = six.b(url[url.find('://')+3:])
return '_url_' + base64.urlsafe_b64encode(x).decode('utf-8').replace('=', '_')
| import base64, copy, argparse, six, dirhash, hashlib, os
import cget.util as util
def encode_url(url):
| 29 | 64 | 45 | 5 | 23 | pixelwise/cget | cget/package.py | Python | encode_url | encode_url | 4 | 6 | 4 | 4 | ec8e6db49436cabd745ea58ef8d107b0460f8052 | bigcode/the-stack | train |
62ab9e9e5241a6d56aeb416e | train | function | def decode_url(url):
s = url.replace('_', '=')[5:]
return base64.urlsafe_b64decode(str(s)).decode('utf-8')
| def decode_url(url):
| s = url.replace('_', '=')[5:]
return base64.urlsafe_b64decode(str(s)).decode('utf-8')
| dirhash, hashlib, os
import cget.util as util
def encode_url(url):
x = six.b(url[url.find('://')+3:])
return '_url_' + base64.urlsafe_b64encode(x).decode('utf-8').replace('=', '_')
def decode_url(url):
| 64 | 64 | 34 | 5 | 59 | pixelwise/cget | cget/package.py | Python | decode_url | decode_url | 8 | 10 | 8 | 8 | 6957a24c7f7a1e85fed12a705606dd37ca281ab8 | bigcode/the-stack | train |
c1354d140260cde67cf40383 | train | function | def parse_pkg_build_tokens(args):
parser = argparse.ArgumentParser()
parser.add_argument('pkg_src', nargs='?')
parser.add_argument('-D', '--define', action='append', default=[])
parser.add_argument('-H', '--hash')
parser.add_argument('-X', '--cmake')
parser.add_argument('-f', '--file')
parse... | def parse_pkg_build_tokens(args):
| parser = argparse.ArgumentParser()
parser.add_argument('pkg_src', nargs='?')
parser.add_argument('-D', '--define', action='append', default=[])
parser.add_argument('-H', '--hash')
parser.add_argument('-X', '--cmake')
parser.add_argument('-f', '--file')
parser.add_argument('-t', '--test', act... | ):
if isinstance(self.pkg_src, PackageSource): return self.pkg_src.to_fname()
else: return self.pkg_src
def to_name(self):
if isinstance(self.pkg_src, PackageSource): return self.pkg_src.to_name()
else: return self.pkg_src
def parse_pkg_build_tokens(args):
| 64 | 64 | 117 | 7 | 56 | pixelwise/cget | cget/package.py | Python | parse_pkg_build_tokens | parse_pkg_build_tokens | 102 | 111 | 102 | 102 | b8923e941643782c2d7bd1191259aa11cc5b40b3 | bigcode/the-stack | train |
598203f844fdef45f5eb64d7 | train | function | def fname_to_pkg(fname):
if fname.startswith('_url_'): return PackageSource(name=decode_url(fname), fname=fname)
else: return PackageSource(name=fname.replace('__', '/'), fname=fname)
| def fname_to_pkg(fname):
| if fname.startswith('_url_'): return PackageSource(name=decode_url(fname), fname=fname)
else: return PackageSource(name=fname.replace('__', '/'), fname=fname)
| ), filename)
fullpath = os.path.join(dirpath, filename)
data[key] = util.lines_of_file(fullpath)
return data
elif self.url:
return self.url
raise Exception("no url or recipe: %s" % self.__dict__)
def fname_to_pkg(fname):
| 64 | 64 | 45 | 6 | 58 | pixelwise/cget | cget/package.py | Python | fname_to_pkg | fname_to_pkg | 55 | 57 | 55 | 55 | 4abe99bd2107d045470b9ed2efa019cbb246e76b | bigcode/the-stack | train |
96f37639c8606ad5c06bf3ac | train | class | class StarRatedReviewManager(ReviewManager):
def get_queryset(self):
return super(StarRatedReviewManager, self).get_queryset().filter(rating__type__name=STAR_RATING_TYPE)
| class StarRatedReviewManager(ReviewManager):
| def get_queryset(self):
return super(StarRatedReviewManager, self).get_queryset().filter(rating__type__name=STAR_RATING_TYPE)
| .get_queryset().filter(
content_type=ContentType.objects.get_for_model(klass))
def for_instance(self, instance):
return self.get_queryset().filter(
content_type=ContentType.objects.get_for_model(instance),
object_id=instance.id
)
class StarRatedReviewManager(Revi... | 64 | 64 | 42 | 9 | 55 | founders4schools/django-surveys | src/surveys/managers.py | Python | StarRatedReviewManager | StarRatedReviewManager | 19 | 21 | 19 | 19 | ee042833a32ad2805a47bba024c96a98cdb49ea3 | bigcode/the-stack | train |
bf5b8c4aa2844d0b06ccc842 | train | class | class ReviewManager(models.Manager):
def for_model(self, klass):
return self.get_queryset().filter(
content_type=ContentType.objects.get_for_model(klass))
def for_instance(self, instance):
return self.get_queryset().filter(
content_type=ContentType.objects.get_for_model(... | class ReviewManager(models.Manager):
| def for_model(self, klass):
return self.get_queryset().filter(
content_type=ContentType.objects.get_for_model(klass))
def for_instance(self, instance):
return self.get_queryset().filter(
content_type=ContentType.objects.get_for_model(instance),
object_id=inst... | from django.contrib.contenttypes.models import ContentType
from django.db import models
from .constants import STAR_RATING_TYPE
class ReviewManager(models.Manager):
| 31 | 64 | 72 | 6 | 24 | founders4schools/django-surveys | src/surveys/managers.py | Python | ReviewManager | ReviewManager | 7 | 16 | 7 | 7 | 194fd4b732a47cac0e7bb0dcaf1bf46ce8b6b747 | bigcode/the-stack | train |
faf2cf0cc82e74fa804fc75c | train | class | class DrawTool:
def __init__(self, *args, **kwargs):
self.points = []
self.color = QtGui.QColor(255,0,0,0)
self.editing_color = QtGui.QColor(255,0,0,96)
@property
def Points(self): return self.points
@property
def Color(self): return self.color
@property
def EditingCo... | class DrawTool:
| def __init__(self, *args, **kwargs):
self.points = []
self.color = QtGui.QColor(255,0,0,0)
self.editing_color = QtGui.QColor(255,0,0,96)
@property
def Points(self): return self.points
@property
def Color(self): return self.color
@property
def EditingColor(self): retur... | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys, os, numpy, PIL, csv
from PySide2 import QtCore, QtGui, QtWidgets
from PIL import Image, ImagePalette, ImageQt, ImageSequence
from abc import ABCMeta, abstractmethod
class DrawTool:
| 66 | 68 | 228 | 4 | 61 | ytyaru/Python.Pixpeer.Rectangle.Ellipse.20200520093810 | src/drawtools.py | Python | DrawTool | DrawTool | 8 | 31 | 8 | 8 | 0ad901c62df2022c6f50e8c93cb9e6b4294fd014 | bigcode/the-stack | train |
1e2cb63aafa81b0c76964b4b | train | class | class RectangleTool(DrawTool):
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
self.Points.append([0,0])
self.Points.append([0,0])
self.pen = QtGui.QPen()
self.pen.setStyle(QtCore.Qt.SolidLine)
self.pen.setWidth(1)
# s... | class RectangleTool(DrawTool):
| def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
self.Points.append([0,0])
self.Points.append([0,0])
self.pen = QtGui.QPen()
self.pen.setStyle(QtCore.Qt.SolidLine)
self.pen.setWidth(1)
# self.pen.setColor(QtGui.QColor(2... | .setPen(color)
painter.setCompositionMode(QtGui.QPainter.CompositionMode_Source)
if 1 == len(self.points):
painter.drawLine(self.points[0][0], self.points[0][1], self.points[0][0], self.points[0][1])
elif 1 < len(self.points):
for i in range(len(self.points)-1):
... | 122 | 122 | 407 | 7 | 115 | ytyaru/Python.Pixpeer.Rectangle.Ellipse.20200520093810 | src/drawtools.py | Python | RectangleTool | RectangleTool | 116 | 147 | 116 | 116 | 30b7acaaeb5069737cb69588d96a692807aa6c31 | bigcode/the-stack | train |
9c7c720234f960babc199d52 | train | class | class SelectRectangleTool(DrawTool):
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
self.Points.append([0,0])
self.Points.append([0,0])
self.pen = QtGui.QPen()
self.pen.setStyle(QtCore.Qt.DashDotLine)
self.pen.setWidth(3)
... | class SelectRectangleTool(DrawTool):
| def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
self.Points.append([0,0])
self.Points.append([0,0])
self.pen = QtGui.QPen()
self.pen.setStyle(QtCore.Qt.DashDotLine)
self.pen.setWidth(3)
self.pen.setColor(QtGui.QColor(... | if isinstance(value, QtGui.QColor): self.color = value
@EditingColor.setter
def EditingColor(self, value):
if isinstance(value, QtGui.QColor): self.editing_color = value
def begin(self, x, y, pixmap):
self.points.clear()
self.editing(x, y, pixmap)
def editing(self, x, y, pixmap)... | 123 | 123 | 411 | 8 | 115 | ytyaru/Python.Pixpeer.Rectangle.Ellipse.20200520093810 | src/drawtools.py | Python | SelectRectangleTool | SelectRectangleTool | 33 | 64 | 33 | 33 | d90ae75bc893ba8a6a1e62986e2d1ebead2e0e83 | bigcode/the-stack | train |
3093e1ab44455f469533d383 | train | class | class PenTool(DrawTool):
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
def editing(self, x, y, pixmap):
super(self.__class__, self).editing(x, y, pixmap)
self.__draw(pixmap, self.EditingColor)
def end(self, x, y, pixmap):
super(sel... | class PenTool(DrawTool):
| def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
def editing(self, x, y, pixmap):
super(self.__class__, self).editing(x, y, pixmap)
self.__draw(pixmap, self.EditingColor)
def end(self, x, y, pixmap):
super(self.__class__, self).end(x,... | 1], self.points[0][0], self.points[0][1])
elif 1 < len(self.points):
for i in range(len(self.points)-1):
painter.drawRect(self.points[i][0], self.points[i][1], self.points[i+1][0], self.points[i+1][1])
painter.end()
class PenTool(DrawTool):
| 79 | 79 | 265 | 7 | 72 | ytyaru/Python.Pixpeer.Rectangle.Ellipse.20200520093810 | src/drawtools.py | Python | PenTool | PenTool | 66 | 86 | 66 | 66 | 91a5b1482909a1f6c31950faa82088f8e9b5ebed | bigcode/the-stack | train |
7f91966942338e0d648bca67 | train | class | class EllipseTool(DrawTool):
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
self.Points.append([0,0])
self.Points.append([0,0])
self.pen = QtGui.QPen()
self.pen.setStyle(QtCore.Qt.SolidLine)
self.pen.setWidth(1)
# sel... | class EllipseTool(DrawTool):
| def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
self.Points.append([0,0])
self.Points.append([0,0])
self.pen = QtGui.QPen()
self.pen.setStyle(QtCore.Qt.SolidLine)
self.pen.setWidth(1)
# self.pen.setColor(QtGui.QColor(2... | self.pen.setColor(color)
painter.setPen(self.pen)
painter.setCompositionMode(QtGui.QPainter.CompositionMode_Source)
if 1 == len(self.points):
painter.drawLine(self.points[0][0], self.points[0][1], self.points[0][0], self.points[0][1])
elif 1 < len(self.points):
... | 122 | 122 | 408 | 8 | 114 | ytyaru/Python.Pixpeer.Rectangle.Ellipse.20200520093810 | src/drawtools.py | Python | EllipseTool | EllipseTool | 149 | 180 | 149 | 149 | 75c9f39f635b490c4c427bbc62576a1e05b0ba03 | bigcode/the-stack | train |
dd1dee14326200753d4a5dc2 | train | class | class LineTool(DrawTool):
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
self.Points.append([0,0])
self.Points.append([0,0])
def begin(self, x, y, pixmap):
self.Points[0][0], self.Points[0][1] = x, y
self.Points[1][0], self.Poin... | class LineTool(DrawTool):
| def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
self.Points.append([0,0])
self.Points.append([0,0])
def begin(self, x, y, pixmap):
self.Points[0][0], self.Points[0][1] = x, y
self.Points[1][0], self.Points[1][1] = x, y
def __... | _Source)
if 1 == len(self.points):
painter.drawLine(self.points[0][0], self.points[0][1], self.points[0][0], self.points[0][1])
elif 1 < len(self.points):
for i in range(len(self.points)-1):
painter.drawLine(self.points[i][0], self.points[i][1], self.points[i+1][0... | 106 | 106 | 356 | 7 | 99 | ytyaru/Python.Pixpeer.Rectangle.Ellipse.20200520093810 | src/drawtools.py | Python | LineTool | LineTool | 88 | 114 | 88 | 88 | e4cb5a420e6f26cf03ae2959de25cd2e01e1eea4 | bigcode/the-stack | train |
a89b2461e0de8314f82c1856 | train | function | def main():
sTree, SimTreeID, VMpool = SimTree()
print('SimTreeID: ', SimTreeID)
# print(Tree_to_eChartsJSON(sTree))
sTree.show()
write2db(SimTreeID, sTree, VMpool)
# for item in VMpool:
# print("VMID: ", item["VMID"])
print("pause.")
| def main():
| sTree, SimTreeID, VMpool = SimTree()
print('SimTreeID: ', SimTreeID)
# print(Tree_to_eChartsJSON(sTree))
sTree.show()
write2db(SimTreeID, sTree, VMpool)
# for item in VMpool:
# print("VMID: ", item["VMID"])
print("pause.")
| =Data["VMID"], count=count)
else:
# 船已经相遇,仿真停止,不再分支
pass
return tree
tree = CreatVMTree(tree, data, parent, count)
return tree, SimTreeID, VMpool
def main():
| 64 | 64 | 87 | 3 | 60 | CarlosJones/ADS-IDAC-SimPy | src/server/model/SimTree.py | Python | main | main | 131 | 139 | 131 | 131 | c2a3172094ee332a92ea54fe7113ae5a263afdc5 | bigcode/the-stack | train |
7a8c9462e3ed083825f785b5 | train | function | def SimTree():
count = [0]
SimTreeID = "10" + time.strftime("%y%m%d%H%M%S") + str(random.randint(1000, 9999))
tree = Tree()
VMpool = []
data = {'probability': 1, 'status': [
{'time': 0, 'shipid': '10086', 'lon': 123, 'lat': 30.9900001, 'speed': 7, 'heading': 75, 'interval': 100},
{'... | def SimTree():
| count = [0]
SimTreeID = "10" + time.strftime("%y%m%d%H%M%S") + str(random.randint(1000, 9999))
tree = Tree()
VMpool = []
data = {'probability': 1, 'status': [
{'time': 0, 'shipid': '10086', 'lon': 123, 'lat': 30.9900001, 'speed': 7, 'heading': 75, 'interval': 100},
{'time': 0, 'ship... | 的对象
with open(filename,'rb') as f:
return pickle.load(f)
def Tree_to_eChartsJSON(tree):
#Transform the whole tree into an eCharts_JSON.
def to_dict(tree, nid):
ntag = tree[nid].tag
tree_dict = {'name': ntag, 'value': int(nid), "children": []}
#if tree[nid].expanded:
... | 256 | 256 | 1,228 | 4 | 251 | CarlosJones/ADS-IDAC-SimPy | src/server/model/SimTree.py | Python | SimTree | SimTree | 54 | 128 | 54 | 54 | e084659f348b44b8e046960f71532aaf4e9b3531 | bigcode/the-stack | train |
ed4c6b3c36963f548b6f95b6 | train | function | def write2db(SimTreeID, sTree, VMpool):
JSONTree = Tree_to_eChartsJSON(sTree)
opt_db.insert_into_simtree(SimTreeID, JSONTree)
for item in VMpool:
opt_db.insert_into_simvm(item["VMID"], json.dumps(item))
print("已经将仿真树和其中的结点数据写入数据库.")
pass
| def write2db(SimTreeID, sTree, VMpool):
| JSONTree = Tree_to_eChartsJSON(sTree)
opt_db.insert_into_simtree(SimTreeID, JSONTree)
for item in VMpool:
opt_db.insert_into_simvm(item["VMID"], json.dumps(item))
print("已经将仿真树和其中的结点数据写入数据库.")
pass
| ["children"]) == 0:
tree_dict.pop('children', None)
return tree_dict
eChartsDict = {'data': [to_dict(tree, tree.root)]}
return json.dumps(eChartsDict)
pass
def write2db(SimTreeID, sTree, VMpool):
| 64 | 64 | 87 | 15 | 48 | CarlosJones/ADS-IDAC-SimPy | src/server/model/SimTree.py | Python | write2db | write2db | 46 | 52 | 46 | 46 | 546be5201667924ebde892c608cadf052b4e4fcd | bigcode/the-stack | train |
ef158e0b0fb39850fc853bda | train | function | def grab(filename):
# 反序列化,从本地文件读出原有的对象
with open(filename,'rb') as f:
return pickle.load(f)
| def grab(filename):
# 反序列化,从本地文件读出原有的对象
| with open(filename,'rb') as f:
return pickle.load(f)
| import opt_db
def store(data, filename):
# 序列化,写到本地磁盘文件
with open(filename,'wb') as f:
pickle.dump(data, f)
def grab(filename):
# 反序列化,从本地文件读出原有的对象
| 64 | 64 | 38 | 22 | 42 | CarlosJones/ADS-IDAC-SimPy | src/server/model/SimTree.py | Python | grab | grab | 26 | 29 | 26 | 27 | c232aae75bf001254df451bc04a89726008cbe2a | bigcode/the-stack | train |
bc34f81ee9b41293423ffde6 | train | function | def store(data, filename):
# 序列化,写到本地磁盘文件
with open(filename,'wb') as f:
pickle.dump(data, f)
| def store(data, filename):
# 序列化,写到本地磁盘文件
| with open(filename,'wb') as f:
pickle.dump(data, f)
| -------------------------------------------------------------------------------
import sys
sys.path.append(".")
sys.path.append("..")
from treelib import Node, Tree
import pickle, json, copy, time, random
import SimVM
import opt_db
def store(data, filename):
# 序列化,写到本地磁盘文件
| 64 | 64 | 38 | 21 | 42 | CarlosJones/ADS-IDAC-SimPy | src/server/model/SimTree.py | Python | store | store | 21 | 24 | 21 | 22 | 1924563957ee43090dafb4f57c008d715eb9e52f | bigcode/the-stack | train |
bc788aa73aa79ab5963fd0d3 | train | function | def Tree_to_eChartsJSON(tree):
#Transform the whole tree into an eCharts_JSON.
def to_dict(tree, nid):
ntag = tree[nid].tag
tree_dict = {'name': ntag, 'value': int(nid), "children": []}
#if tree[nid].expanded:
for elem in tree.children(nid):
tree_dict["children"].appe... | def Tree_to_eChartsJSON(tree):
#Transform the whole tree into an eCharts_JSON.
| def to_dict(tree, nid):
ntag = tree[nid].tag
tree_dict = {'name': ntag, 'value': int(nid), "children": []}
#if tree[nid].expanded:
for elem in tree.children(nid):
tree_dict["children"].append(to_dict(tree, elem.identifier))
if len(tree_dict["children"]) == 0:
... | pickle.dump(data, f)
def grab(filename):
# 反序列化,从本地文件读出原有的对象
with open(filename,'rb') as f:
return pickle.load(f)
def Tree_to_eChartsJSON(tree):
#Transform the whole tree into an eCharts_JSON.
| 64 | 64 | 146 | 20 | 44 | CarlosJones/ADS-IDAC-SimPy | src/server/model/SimTree.py | Python | Tree_to_eChartsJSON | Tree_to_eChartsJSON | 31 | 44 | 31 | 32 | 205fe9ea6278ec7813caae4fac6c04ad89e8ee8e | bigcode/the-stack | train |
ff8085e6aaf2cb264af71ce1 | train | function | def save_file(attachment, mtime):
f_name = attachment.get_filename()
dest = os.path.join('./reports', f_name)
if os.path.exists(dest):
return
with open(dest, 'wb') as f:
f.write(attachment.get_payload(decode=True))
os.utime(dest, (mtime, mtime))
| def save_file(attachment, mtime):
| f_name = attachment.get_filename()
dest = os.path.join('./reports', f_name)
if os.path.exists(dest):
return
with open(dest, 'wb') as f:
f.write(attachment.get_payload(decode=True))
os.utime(dest, (mtime, mtime))
|
import dmarc
import email
import os
ACCEPTED_MIME = [
'application/gzip',
'application/x-gzip',
'application/zip',
'application/x-zip-compressed',
'application/octet-stream',
]
def save_file(attachment, mtime):
| 64 | 64 | 73 | 9 | 55 | cjeanneret/dmarc-report | extract.py | Python | save_file | save_file | 15 | 22 | 15 | 15 | 7fbe053225202e9d08678dc4c89744f8993a3653 | bigcode/the-stack | train |
524cd423180a219994e77a2c | train | class | class Network(object):
PROP_DELAY = 0.03
PROP_JITTER = 0.02
def __init__(self, seed, pause=False):
self.nodes = {}
self.rnd = random.Random(seed)
self.pause = pause
self.timers = []
self.now = 1000.0
self.logger = logging.getLogger('network')
def new_no... | class Network(object):
| PROP_DELAY = 0.03
PROP_JITTER = 0.02
def __init__(self, seed, pause=False):
self.nodes = {}
self.rnd = random.Random(seed)
self.pause = pause
self.timers = []
self.now = 1000.0
self.logger = logging.getLogger('network')
def new_node(self):
node =... | ))
self.network.send(destinations, action, **kwargs)
def register(self, component):
self.components.append(component)
def unregister(self, component):
self.components.remove(component)
def receive(self, action, kwargs):
import sys
for comp in self.components[:]:
... | 113 | 113 | 378 | 4 | 109 | superbigzhang/500lines | cluster/deterministic_network.py | Python | Network | Network | 51 | 104 | 51 | 52 | 5806e0ae652c9597390a3997a0a9e3ee1dc10591 | bigcode/the-stack | train |
cff5d958c223ef32a5e4ae5d | train | class | class Node(object):
unique_ids = xrange(1000).__iter__()
def __init__(self, network):
self.network = network
self.unique_id = self.unique_ids.next()
self.address = 'N%d' % self.unique_id
self.components = []
self.logger = logging.getLogger(self.address)
self.log... | class Node(object):
| unique_ids = xrange(1000).__iter__()
def __init__(self, network):
self.network = network
self.unique_id = self.unique_ids.next()
self.address = 'N%d' % self.unique_id
self.components = []
self.logger = logging.getLogger(self.address)
self.logger.info('starting')
... | import time
import logging
import heapq
import random
class Node(object):
| 17 | 86 | 288 | 4 | 12 | superbigzhang/500lines | cluster/deterministic_network.py | Python | Node | Node | 6 | 48 | 6 | 7 | 3c11d320a6327d31a58de5325af96fc0eede3b5d | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.