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
47b14968c46a873757f33a21
train
class
class TestShowMPLSLSPNameDetail(unittest.TestCase): """ Unit test for: * show mpls lsp name {name} detail """ device = Device(name='aDevice') maxDiff = None empty_output = {'execute.return_value': ''} golden_output_1 = { 'execute.return_value': """Ingress LSP: 0 session...
class TestShowMPLSLSPNameDetail(unittest.TestCase):
""" Unit test for: * show mpls lsp name {name} detail """ device = Device(name='aDevice') maxDiff = None empty_output = {'execute.return_value': ''} golden_output_1 = { 'execute.return_value': """Ingress LSP: 0 sessions Total 0 displayed, Up 0, Down 0 E...
# Python import unittest from unittest.mock import Mock # ATS from pyats.topology import Device, loader # Metaparser from genie.metaparser.util.exceptions import SchemaEmptyParserError from genie.libs.parser.junos.show_mpls import ( ShowMPLSLSPNameDetail, ShowMPLSLSPNameExtensive) class TestShowMPLSLSPNameDetail...
85
256
1,491
13
72
nujo/genieparser
src/genie/libs/parser/junos/tests/test_show_mpls.py
Python
TestShowMPLSLSPNameDetail
TestShowMPLSLSPNameDetail
15
184
15
15
b981975781678002723c2e7eee515f9c8c01c16f
bigcode/the-stack
train
981e339781bc261332d30ae9
train
class
class Requestor: def __init__(self, account_id, auth_token, base_url=None): self._account_id = account_id self._auth_token = auth_token if base_url is None: self._base_url = "https://api.forecastapp.com" self._headers = { 'Forecast-Account-ID': self._account...
class Requestor:
def __init__(self, account_id, auth_token, base_url=None): self._account_id = account_id self._auth_token = auth_token if base_url is None: self._base_url = "https://api.forecastapp.com" self._headers = { 'Forecast-Account-ID': self._account_id, '...
from typing import Dict, Optional from timeit import default_timer as timer import requests import requests_cache requests_cache.install_cache(cache_name='forecast_cache', backend='sqlite', expire_after=180) class Requestor:
46
64
209
4
42
vafliik/pyforecast
forecast/requestor.py
Python
Requestor
Requestor
10
34
10
11
8e93988fef042b8cca40979040e5b0b082ce254e
bigcode/the-stack
train
44b921dfacaa935d2a394fbb
train
class
class Package(BinaryPackageBase): def __init__(self): BinaryPackageBase.__init__(self)
class Package(BinaryPackageBase):
def __init__(self): BinaryPackageBase.__init__(self)
) # the zip file does not have a bin dir, so we have to create it # This attribute is in prelimary state self.targetInstallPath['16.21'] = os.path.join("dev-utils", "bin") from Package.BinaryPackageBase import * class Package(BinaryPackageBase):
64
64
22
6
58
simont77/craft-blueprints-kde
dev-utils/_windows/procexp/procexp.py
Python
Package
Package
18
20
18
18
e7e69c87819324c28fb1f71465c2fc70a0843934
bigcode/the-stack
train
d1edd07c1e11e38f49c53e8c
train
class
class subinfo(info.infoclass): def setTargets(self): self.targets['16.21'] = 'http://download.sysinternals.com/files/ProcessExplorer.zip' self.defaultTarget = '16.21' self.targetDigests['16.21'] = ( ['9f32608a5f9ce2d2eb0fe9cdfe65ebc06f7c3c2b52d2b6b1bf3737af9a2d2bad'], CraftHash.H...
class subinfo(info.infoclass):
def setTargets(self): self.targets['16.21'] = 'http://download.sysinternals.com/files/ProcessExplorer.zip' self.defaultTarget = '16.21' self.targetDigests['16.21'] = ( ['9f32608a5f9ce2d2eb0fe9cdfe65ebc06f7c3c2b52d2b6b1bf3737af9a2d2bad'], CraftHash.HashAlgorithm.SHA256) # ...
import info class subinfo(info.infoclass):
11
64
166
8
2
simont77/craft-blueprints-kde
dev-utils/_windows/procexp/procexp.py
Python
subinfo
subinfo
4
12
4
4
33b334c3542764230f29b68d5c062cae525d534d
bigcode/the-stack
train
c07d4683f94032adc6c12f28
train
function
def add_phone_number_to_contact(contact_id, phone_number): client = hubspot.Client.create(api_key=os.environ.get("HUBSPOT_API_KEY")) properties = { "phone": phone_number, } simple_public_object_input = SimplePublicObjectInput(properties=properties) client.crm.contacts.basic_a...
def add_phone_number_to_contact(contact_id, phone_number):
client = hubspot.Client.create(api_key=os.environ.get("HUBSPOT_API_KEY")) properties = { "phone": phone_number, } simple_public_object_input = SimplePublicObjectInput(properties=properties) client.crm.contacts.basic_api.update(contact_id=contact_id, simple_public_object_input=simp...
str(e).split('{"status":"error","message":"Contact already exists. Existing ID: ') id_split_two = id_split_one[1].split('"') existing_contact_id = id_split_two[0] return existing_contact_id def add_phone_number_to_contact(contact_id, phone_number):
64
64
85
13
50
StoneMasons4106/clay-cabinet
hubspot_api_calls.py
Python
add_phone_number_to_contact
add_phone_number_to_contact
33
43
33
34
4abf8232df6d8efc0e9c304041843d97c4e824c3
bigcode/the-stack
train
a2648cda7fb922813f36f8c3
train
function
def create_new_deal(contact_id, deal_amount, full_name, order_no): tz = timezone(os.environ.get("TZ")) utcdt = utc.localize( datetime( year=datetime.now().year, month=datetime.now().month, day=datetime.now().day, hour=datetime.now().hour, min...
def create_new_deal(contact_id, deal_amount, full_name, order_no):
tz = timezone(os.environ.get("TZ")) utcdt = utc.localize( datetime( year=datetime.now().year, month=datetime.now().month, day=datetime.now().day, hour=datetime.now().hour, minute=datetime.now().minute, second=datetime.now().second,...
id"] def associate_note_with_contact(contact_id, note_id): url = f"https://api.hubapi.com/crm/v3/objects/notes/{note_id}/associations/contact/{contact_id}/202" querystring = {"hapikey":os.environ.get("HUBSPOT_API_KEY")} headers = {'accept': 'application/json'} requests.request("PUT", url, headers=...
108
108
360
17
91
StoneMasons4106/clay-cabinet
hubspot_api_calls.py
Python
create_new_deal
create_new_deal
90
152
90
91
6229ce66c23b0fa2223358ceec24c05c012237a5
bigcode/the-stack
train
502f37e76fc1153cc11efc31
train
function
def associate_note_with_deal(deal_id, note_id): url = f"https://api.hubapi.com/crm/v4/objects/notes/{note_id}/associations/deal/{deal_id}" querystring = {"hapikey":os.environ.get("HUBSPOT_API_KEY")} payload = "[{\"associationCategory\":\"HUBSPOT_DEFINED\",\"associationTypeId\":214}]" headers = { ...
def associate_note_with_deal(deal_id, note_id):
url = f"https://api.hubapi.com/crm/v4/objects/notes/{note_id}/associations/deal/{deal_id}" querystring = {"hapikey":os.environ.get("HUBSPOT_API_KEY")} payload = "[{\"associationCategory\":\"HUBSPOT_DEFINED\",\"associationTypeId\":214}]" headers = { 'accept': "application/json", 'conte...
" }, { "value": "newbusiness", "name": "dealtype" } ] }) response = requests.post(url, headers = headers, data = data) return response.json()["dealId"] def associate_note_with_deal(deal_id, note_id):
63
64
127
13
50
StoneMasons4106/clay-cabinet
hubspot_api_calls.py
Python
associate_note_with_deal
associate_note_with_deal
155
168
155
156
4e7b701f6a66965b38b47ea1b7e633bd9325b7b8
bigcode/the-stack
train
04bad1955ae71f85e7138d7f
train
function
def associate_note_with_contact(contact_id, note_id): url = f"https://api.hubapi.com/crm/v3/objects/notes/{note_id}/associations/contact/{contact_id}/202" querystring = {"hapikey":os.environ.get("HUBSPOT_API_KEY")} headers = {'accept': 'application/json'} requests.request("PUT", url, headers=headers...
def associate_note_with_contact(contact_id, note_id):
url = f"https://api.hubapi.com/crm/v3/objects/notes/{note_id}/associations/contact/{contact_id}/202" querystring = {"hapikey":os.environ.get("HUBSPOT_API_KEY")} headers = {'accept': 'application/json'} requests.request("PUT", url, headers=headers, params=querystring)
'accept': "application/json", 'content-type': "application/json", } response = requests.request("POST", url, data=payload, headers=headers, params=querystring) json = response.json() return json["id"] def associate_note_with_contact(contact_id, note_id):
63
64
88
11
52
StoneMasons4106/clay-cabinet
hubspot_api_calls.py
Python
associate_note_with_contact
associate_note_with_contact
79
87
79
80
5b9aedc34c1d4f17be4c9e24c40b9c47ac7b054d
bigcode/the-stack
train
a8e0ae4af90ab5a33ea9a246
train
function
def create_new_contact(email, first_name, last_name): client = hubspot.Client.create(api_key=os.environ.get("HUBSPOT_API_KEY")) properties = { "email": email, "firstname": first_name, "lastname": last_name, "hubspot_owner_id":os.environ.get("HUBSPOT_OWNER_ID"), } simpl...
def create_new_contact(email, first_name, last_name):
client = hubspot.Client.create(api_key=os.environ.get("HUBSPOT_API_KEY")) properties = { "email": email, "firstname": first_name, "lastname": last_name, "hubspot_owner_id":os.environ.get("HUBSPOT_OWNER_ID"), } simple_public_object_input = SimplePublicObjectInput(propert...
import hubspot import os import json from hubspot.crm.contacts import SimplePublicObjectInput, ApiException import requests from pytz import timezone, utc from datetime import datetime def create_new_contact(email, first_name, last_name):
52
64
182
12
39
StoneMasons4106/clay-cabinet
hubspot_api_calls.py
Python
create_new_contact
create_new_contact
10
30
10
11
0c4d1a86228a0b814207ff899df27e534c538742
bigcode/the-stack
train
9cf64cb465e0a36ef4d420df
train
function
def create_new_note(message): url = "https://api.hubapi.com/crm/v3/objects/notes" querystring = {"hapikey":os.environ.get("HUBSPOT_API_KEY")} tz = timezone(os.environ.get("TZ")) utcdt = utc.localize( datetime( year=datetime.now().year, month=datetime.now().month, ...
def create_new_note(message):
url = "https://api.hubapi.com/crm/v3/objects/notes" querystring = {"hapikey":os.environ.get("HUBSPOT_API_KEY")} tz = timezone(os.environ.get("TZ")) utcdt = utc.localize( datetime( year=datetime.now().year, month=datetime.now().month, day=datetime.now().day,...
_key=os.environ.get("HUBSPOT_API_KEY")) properties = { "phone": phone_number, } simple_public_object_input = SimplePublicObjectInput(properties=properties) client.crm.contacts.basic_api.update(contact_id=contact_id, simple_public_object_input=simple_public_object_input) def create_new...
70
70
234
6
64
StoneMasons4106/clay-cabinet
hubspot_api_calls.py
Python
create_new_note
create_new_note
46
76
46
47
4188e8a82d9f513dc0ad909b65a857301bd00f7f
bigcode/the-stack
train
082330fca2af677aec1a39ef
train
class
class Usages(object): def __init__(self, client): self.Sid = client.Sid self.AuthToken = client.AuthToken self.BaseUrl = client.BaseUrl def GetList(self): try: Url = self.BaseUrl+'/Accounts/'+self.Sid+'/Usage/Records/Daily.json' r1 = requests.get(Url,...
class Usages(object):
def __init__(self, client): self.Sid = client.Sid self.AuthToken = client.AuthToken self.BaseUrl = client.BaseUrl def GetList(self): try: Url = self.BaseUrl+'/Accounts/'+self.Sid+'/Usage/Records/Daily.json' r1 = requests.get(Url, auth=(self.Sid, self.A...
Email : nukles1.07@gmail.com ''' import requests import json class client(object): def __init__(self, Sid, AuthToken, BaseUrl): self.Sid = Sid self.AuthToken = AuthToken self.BaseUrl = BaseUrl class Usages(object):
64
64
215
5
58
jackdown/restcomm-sdk-python
Restcomm_Python_SDk/Restcomm/Usage/Usage.py
Python
Usages
Usages
37
67
37
38
22ffe83de72aba18e9fddea06e2fb29ca6e1baf1
bigcode/the-stack
train
7bb10ae18a95f7ed65c495f9
train
class
class client(object): def __init__(self, Sid, AuthToken, BaseUrl): self.Sid = Sid self.AuthToken = AuthToken self.BaseUrl = BaseUrl
class client(object):
def __init__(self, Sid, AuthToken, BaseUrl): self.Sid = Sid self.AuthToken = AuthToken self.BaseUrl = BaseUrl
Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. This code was generated by : Name: Md Sharique Email : nukles1.07@gmail.com ''' import requests import json class client(object):
64
64
42
4
59
jackdown/restcomm-sdk-python
Restcomm_Python_SDk/Restcomm/Usage/Usage.py
Python
client
client
29
35
29
30
f26b1218ea2f14aa72c49d98833a790f15973713
bigcode/the-stack
train
d6712b5d6f816e7bdb95f899
train
class
class VarianceApplicationStatusCode(AuditMixin, Base): __tablename__ = "variance_application_status_code" variance_application_status_code = db.Column(db.String, primary_key=True, nullable=False) description = db.Column(db.String, nullable=False) active_ind = db.Column(db.Boolean, nullable=False, server...
class VarianceApplicationStatusCode(AuditMixin, Base):
__tablename__ = "variance_application_status_code" variance_application_status_code = db.Column(db.String, primary_key=True, nullable=False) description = db.Column(db.String, nullable=False) active_ind = db.Column(db.Boolean, nullable=False, server_default=FetchedValue()) def __repr__(self): ...
from sqlalchemy.schema import FetchedValue from app.extensions import db from app.api.utils.models_mixins import AuditMixin, Base class VarianceApplicationStatusCode(AuditMixin, Base):
39
64
111
12
26
bcgov/mds
services/core-api/app/api/variances/models/variance_application_status_code.py
Python
VarianceApplicationStatusCode
VarianceApplicationStatusCode
7
18
7
7
5f79ec58166e62931980e475f762e2d53b8025d0
bigcode/the-stack
train
0e60958ee0991e83534905fc
train
function
def GaussInt(index, r0, m): """Function that takes a matrix and performs a Gaussian integral over the row and column specified by index and returns a new matrix. XXX what is different to rc_int above? """ r = sqrt(2 * pi / m[index, index]) * r0 # remove columns and rows from m that contain ...
def GaussInt(index, r0, m):
"""Function that takes a matrix and performs a Gaussian integral over the row and column specified by index and returns a new matrix. XXX what is different to rc_int above? """ r = sqrt(2 * pi / m[index, index]) * r0 # remove columns and rows from m that contain the subscript "index". m...
(theta), sin(theta)], [-sin(theta), cos(theta)]]) MP = S * MP * S.transpose() hwhm_xp = const / sqrt(MP[0, 0]) hwhm_yp = const / sqrt(MP[1, 1]) return hwhm_xp, hwhm_yp, theta def GaussInt(index, r0, m):
87
87
292
11
75
ess-dmsc/nicos
nicos/devices/tas/rescalc.py
Python
GaussInt
GaussInt
985
1,004
985
985
c8b31d3bf96383abe02ecbb0d73a4306cf1f82d2
bigcode/the-stack
train
6d82de85870de4e75316d0de
train
function
def rc_int(index, r0, m): """ported from MATLAB function that takes a matrix and performs a Gaussian integral over the row and column specified by index and returns a new matrix. Tested against maple integration. """ r = sqrt(2 * pi / m[index, index]) * r0 # remove columns and rows from m...
def rc_int(index, r0, m):
"""ported from MATLAB function that takes a matrix and performs a Gaussian integral over the row and column specified by index and returns a new matrix. Tested against maple integration. """ r = sqrt(2 * pi / m[index, index]) * r0 # remove columns and rows from m # that contain the su...
hwhm_xp, hwhm_yp, theta = calcEllipseAxis(MP) yws_x, yws_y = ellipse_coords(hwhm_xp, hwhm_yp, theta) return xy_x, xy_y, xys_x, xys_y, \ xw_x, xw_y, xws_x, xws_y, \ yw_x, yw_y, yws_x, yws_y def rc_int(index, r0, m):
105
105
352
10
94
ess-dmsc/nicos
nicos/devices/tas/rescalc.py
Python
rc_int
rc_int
942
969
942
942
36c339e0a44e792256bef6542ffa6bff2070dfb4
bigcode/the-stack
train
83c4828116936f941c2f35bf
train
class
class unitcell: """ Class which models a crystallographic unit cell from given lattice parameters and angles. Further it provides functions to make basic calculations with the lattice vectors in the crystallographic and in the standard cartesian coordinate system. """ def __init__(self, a,...
class unitcell:
""" Class which models a crystallographic unit cell from given lattice parameters and angles. Further it provides functions to make basic calculations with the lattice vectors in the crystallographic and in the standard cartesian coordinate system. """ def __init__(self, a, b, c, alpha, be...
without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Su...
256
256
2,271
4
251
ess-dmsc/nicos
nicos/devices/tas/rescalc.py
Python
unitcell
unitcell
41
235
41
41
25314da20aacc65cad30add37c1cba82126cbbac
bigcode/the-stack
train
30729012c98a44c9c8a92c71
train
class
class resmat: """Class which calculates the resolution matrix, and the renormalisation volume R0 for a given triple axis parameter set which describes a specific setup at a specific instrument by using the Popovici method (REF). Based on these two properties several others can be calculated. This ...
class resmat:
"""Class which calculates the resolution matrix, and the renormalisation volume R0 for a given triple axis parameter set which describes a specific setup at a specific instrument by using the Popovici method (REF). Based on these two properties several others can be calculated. This code was porte...
height (cm)", "=0 for circular detector, =1 for rectangular detector", "width/diameter of the detector (cm)", "height/diameter of the detector (cm)", "thickness of monochromator (cm)", "width of monochromator (cm)", "height of monochromator (cm)", "thickness of analyser (cm)", "width of...
256
256
9,274
4
252
ess-dmsc/nicos
nicos/devices/tas/rescalc.py
Python
resmat
resmat
276
939
276
276
edfd214701ef86041433b4c58af749f822f1656f
bigcode/the-stack
train
148abb871f0f34e003d8ed15
train
function
def calcEllipseAxis(MP): const = 1.17741 MP = matrix(MP) theta = 0.5 * arctan2(2 * MP[0, 1], MP[0, 0] - MP[1, 1]) S = matrix([[cos(theta), sin(theta)], [-sin(theta), cos(theta)]]) MP = S * MP * S.transpose() hwhm_xp = const / sqrt(MP[0, 0]) hwhm_yp = const / sqrt(MP[1, 1]) ...
def calcEllipseAxis(MP):
const = 1.17741 MP = matrix(MP) theta = 0.5 * arctan2(2 * MP[0, 1], MP[0, 0] - MP[1, 1]) S = matrix([[cos(theta), sin(theta)], [-sin(theta), cos(theta)]]) MP = S * MP * S.transpose() hwhm_xp = const / sqrt(MP[0, 0]) hwhm_yp = const / sqrt(MP[1, 1]) return hwhm_xp, hwhm_yp...
:len(mp)-1,0:len(mp)-1] mp = T mp = mp - 1 / (4 * m[index, index]) * b * b.transpose() return [r, mp] # functions for calculating ellipsoid cuts and projections def calcEllipseAxis(MP):
64
64
142
7
56
ess-dmsc/nicos
nicos/devices/tas/rescalc.py
Python
calcEllipseAxis
calcEllipseAxis
974
983
974
974
a96abcebcbbb3281c7d532d439f6c366e5d05951
bigcode/the-stack
train
a55510316a1199befdc9d224
train
function
def calc_MC(x, fit_par, sqw, resmat, NMC): """Calculates intensity of point in reciprocal space (qh,qk,ql,en) at takes into account the spectrometer resolution calculated by resolution class resmat (which uses the Popovici algorithm to do so). """ intensity = zeros(len(x)) j = 0 for QE in x:...
def calc_MC(x, fit_par, sqw, resmat, NMC):
"""Calculates intensity of point in reciprocal space (qh,qk,ql,en) at takes into account the spectrometer resolution calculated by resolution class resmat (which uses the Popovici algorithm to do so). """ intensity = zeros(len(x)) j = 0 for QE in x: resmat.calcResEllipsoid(*QE) ...
for ellipse with semiaxes a, b and rotated by phi.""" x0 = 0 y0 = 0 th = arange(0, 2 * pi + 2 * pi / 100, 2 * pi / 100) x = a * cos(th) y = b * sin(th) c = cos(phi) s = sin(phi) th = x * c - y * s + x0 y = x * s + y * c + y0 x = th return x, y def calc_MC(x, fit_par, sqw,...
141
141
473
17
123
ess-dmsc/nicos
nicos/devices/tas/rescalc.py
Python
calc_MC
calc_MC
1,024
1,061
1,024
1,024
5ea3e297a300a9c4b51bf954306f3d5684ff8420
bigcode/the-stack
train
2c454c69ce20e724a28eec34
train
function
def ellipse_coords(a, b, phi): """Return coordinates for ellipse with semiaxes a, b and rotated by phi.""" x0 = 0 y0 = 0 th = arange(0, 2 * pi + 2 * pi / 100, 2 * pi / 100) x = a * cos(th) y = b * sin(th) c = cos(phi) s = sin(phi) th = x * c - y * s + x0 y = x * s + y * c + y0...
def ellipse_coords(a, b, phi):
"""Return coordinates for ellipse with semiaxes a, b and rotated by phi.""" x0 = 0 y0 = 0 th = arange(0, 2 * pi + 2 * pi / 100, 2 * pi / 100) x = a * cos(th) y = b * sin(th) c = cos(phi) s = sin(phi) th = x * c - y * s + x0 y = x * s + y * c + y0 x = th return x, y
len(m) - 1] = m[index + 1:len(m), index + 1:len(m)] mp = mp - 1. / (4 * m[index, index]) * b.transpose() * b return r, mp def ellipse_coords(a, b, phi):
64
64
137
9
54
ess-dmsc/nicos
nicos/devices/tas/rescalc.py
Python
ellipse_coords
ellipse_coords
1,006
1,021
1,006
1,006
9c0b417e280e9816abbaa51f34f8aaf3ac451ba1
bigcode/the-stack
train
3d5a063e5153e0056da97ab3
train
function
def demosqw(qh, qk, ql, en, par, QE, sigma): """Simplest possible simulation of nuclear Bragg peak intensity plus 1-branch isotropic phonon dispersion to see something "realistic" in the demo's virtual detector. par[0] is a scaling factor. """ # get small q qqh = divmod(qh, 1)[1] if qqh...
def demosqw(qh, qk, ql, en, par, QE, sigma):
"""Simplest possible simulation of nuclear Bragg peak intensity plus 1-branch isotropic phonon dispersion to see something "realistic" in the demo's virtual detector. par[0] is a scaling factor. """ # get small q qqh = divmod(qh, 1)[1] if qqh > 0.5: qqh -= 1 qqk = divmod(qk,...
:] + resmat.par['en'] s = zeros(NMC) for i in range(NMC): # QE is provided to sqw function in case center of resolution # is needed for further calculations s[i] = sqw(qh[0, i], qk[0, i], ql[0, i], w[0, i], fit_par[1:], QE, sigma) s = sum(s) / NMC in...
148
148
495
20
127
ess-dmsc/nicos
nicos/devices/tas/rescalc.py
Python
demosqw
demosqw
1,064
1,101
1,064
1,064
bfe480d29d12553e2d1aff37aaf25986a1f8725b
bigcode/the-stack
train
a46c8144e927f8fb4720a8d4
train
class
class STP_TCN_BPDU(Base): __slots__ = () _SDM_NAME = 'stpTCNBPDU' _SDM_ATT_MAP = { 'Protocol identifier': 'stpTCNBPDU.header.protocolIdentifier', 'Protocol version identifier': 'stpTCNBPDU.header.protocolVersionIdentifier', 'BPDU type': 'stpTCNBPDU.header.bpduType', } def __...
class STP_TCN_BPDU(Base):
__slots__ = () _SDM_NAME = 'stpTCNBPDU' _SDM_ATT_MAP = { 'Protocol identifier': 'stpTCNBPDU.header.protocolIdentifier', 'Protocol version identifier': 'stpTCNBPDU.header.protocolVersionIdentifier', 'BPDU type': 'stpTCNBPDU.header.bpduType', } def __init__(self, parent): ...
from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files class STP_TCN_BPDU(Base):
27
84
281
9
17
Vibaswan/ixnetwork_restpy
ixnetwork_restpy/testplatform/sessions/ixnetwork/traffic/trafficitem/configelement/stack/stpTCNBPDU_template.py
Python
STP_TCN_BPDU
STP_TCN_BPDU
5
33
5
5
43b0ae52891c206dd9e6d308842e95236d41dd36
bigcode/the-stack
train
662b80a2feee9c14dfe18fb4
train
class
class DetailsModel(models.Model): """ This field serves no purpose, it only serves as an example for extending models and used for testing purposes. It will be inherited by all the models. """ details = models.CharField(max_length=64, blank=True, null=True) class Meta: abstract = T...
class DetailsModel(models.Model):
""" This field serves no purpose, it only serves as an example for extending models and used for testing purposes. It will be inherited by all the models. """ details = models.CharField(max_length=64, blank=True, null=True) class Meta: abstract = True
from django.db import models from openwisp_ipam.base.models import AbstractIpAddress, AbstractSubnet class DetailsModel(models.Model):
28
64
70
6
21
codesankalp/openwisp-ipam
tests/openwisp2/sample_ipam/models.py
Python
DetailsModel
DetailsModel
6
16
6
6
f84e3f5b80cb03b27a919a3bf779b6f498a76565
bigcode/the-stack
train
c9e1ce19f610368ee2010869
train
class
class IpAddress(DetailsModel, AbstractIpAddress): class Meta(AbstractIpAddress.Meta): abstract = False
class IpAddress(DetailsModel, AbstractIpAddress):
class Meta(AbstractIpAddress.Meta): abstract = False
serves as an example for extending models and used for testing purposes. It will be inherited by all the models. """ details = models.CharField(max_length=64, blank=True, null=True) class Meta: abstract = True class IpAddress(DetailsModel, AbstractIpAddress):
64
64
24
11
52
codesankalp/openwisp-ipam
tests/openwisp2/sample_ipam/models.py
Python
IpAddress
IpAddress
19
21
19
19
7b8a6dfa39c675a7c57126c563743667a19e78a3
bigcode/the-stack
train
ec5ad35680e46a3b3bd91b1c
train
class
class Subnet(DetailsModel, AbstractSubnet): class Meta(AbstractSubnet.Meta): abstract = False
class Subnet(DetailsModel, AbstractSubnet):
class Meta(AbstractSubnet.Meta): abstract = False
models. """ details = models.CharField(max_length=64, blank=True, null=True) class Meta: abstract = True class IpAddress(DetailsModel, AbstractIpAddress): class Meta(AbstractIpAddress.Meta): abstract = False class Subnet(DetailsModel, AbstractSubnet):
64
64
22
10
53
codesankalp/openwisp-ipam
tests/openwisp2/sample_ipam/models.py
Python
Subnet
Subnet
24
26
24
24
c8c58e181e296193bf15f2b9e60e87c3e8533756
bigcode/the-stack
train
953d4439428e7ac962be67ca
train
function
def can_be_dumped(filename): """" Check that symbols can be dumped from the given file """ st = os.lstat(filename) # File must be a regular file if not stat.S_ISREG(st.st_mode): return False # File must be an executable if sys.platform.startswith("linux"): return is_elf(filename)...
def can_be_dumped(filename):
"""" Check that symbols can be dumped from the given file """ st = os.lstat(filename) # File must be a regular file if not stat.S_ISREG(st.st_mode): return False # File must be an executable if sys.platform.startswith("linux"): return is_elf(filename) if sys.platform == "darw...
"rb") as fp: data = fp.read(2) fp.close() return data == '\xcf\xfa' def is_exe(filename): """ Check that a file is a Windows executable. """ return filename.endswith((".exe", ".dll")) def can_be_dumped(filename):
63
64
111
7
56
aldebaran/qibuild
python/qibuild/breakpad.py
Python
can_be_dumped
can_be_dumped
42
55
42
42
db49bc2272768a773f1406f799080a3821de3d7c
bigcode/the-stack
train
69baa2a1784c3ee044690d19
train
function
def gen_symbol_archive(base_dir=None, output=None, dump_exe=None, strip=True, strip_exe=None, strip_args=None, build_config=None): """ Generate a symbol archive from all the binaries in the base_dir """ with qisys.sh.TempDir() as pool_dir: dump_symbols_from_directory(base_dir, poo...
def gen_symbol_archive(base_dir=None, output=None, dump_exe=None, strip=True, strip_exe=None, strip_args=None, build_config=None):
""" Generate a symbol archive from all the binaries in the base_dir """ with qisys.sh.TempDir() as pool_dir: dump_symbols_from_directory(base_dir, pool_dir, dump_exe=dump_exe, strip=strip, strip_exe=strip_exe, strip_args=strip_args, build_config=build_config) ...
strip_binary(full_path, strip_executable=strip_exe, strip_args=strip_args, build_config=build_config) return pool_dir def gen_symbol_archive(base_dir=None, output=None, dump_exe=None, strip=True, strip_exe=None, strip_args=None, build_config=None):
64
64
123
33
30
aldebaran/qibuild
python/qibuild/breakpad.py
Python
gen_symbol_archive
gen_symbol_archive
159
166
159
160
a2e48bed86d4619302c17401fcb89581b038f5d4
bigcode/the-stack
train
962a5872021ff07c1a27e746
train
function
def gen_dsym(binary): """ Generate Dsym """ cmd = ["dsymutil", binary] qisys.command.call(cmd) return binary + ".dSYM"
def gen_dsym(binary):
""" Generate Dsym """ cmd = ["dsymutil", binary] qisys.command.call(cmd) return binary + ".dSYM"
_IRWXG | stat.S_IRWXO os.chmod(binary, mode_rw) rc = qisys.command.call(cmd, ignore_ret_code=True, build_config=build_config) if rc != 0: ui.warning("Failed to strip symbols for", binary) def gen_dsym(binary):
64
64
37
6
58
aldebaran/qibuild
python/qibuild/breakpad.py
Python
gen_dsym
gen_dsym
126
130
126
126
89b9b9145d6a143d0c1bbc9c87089f0e7831e1d6
bigcode/the-stack
train
1eb085a896800462c2eae0c4
train
function
def strip_binary(binary, strip_executable=None, strip_args=None, build_config=None): """ Strip Binary """ if not strip_executable: strip_executable = qisys.command.find_program("strip", raises=True, build_config=build_config) cmd = [strip_executable] if strip_args: cmd.extend(strip_args)...
def strip_binary(binary, strip_executable=None, strip_args=None, build_config=None):
""" Strip Binary """ if not strip_executable: strip_executable = qisys.command.find_program("strip", raises=True, build_config=build_config) cmd = [strip_executable] if strip_args: cmd.extend(strip_args) cmd.append(binary) with qisys.sh.PreserveFileMetadata(binary): mode_...
uuid) qisys.sh.mkdir(to_make, recursive=True) with open(os.path.join(to_make, basename + ".sym"), "w") as fp: fp.write(out) fp.close() return True def strip_binary(binary, strip_executable=None, strip_args=None, build_config=None):
64
64
157
18
45
aldebaran/qibuild
python/qibuild/breakpad.py
Python
strip_binary
strip_binary
110
123
110
110
5b664f00d644c42d883b9432dea159ebe502e258
bigcode/the-stack
train
25af54567fafa351a553a0e4
train
function
def is_elf(filename): """ Check that a file is in the elf format. """ with open(filename, "rb") as fp: data = fp.read(4) fp.close() return data == b'\x7fELF'
def is_elf(filename):
""" Check that a file is in the elf format. """ with open(filename, "rb") as fp: data = fp.read(4) fp.close() return data == b'\x7fELF'
""" from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function import os import sys import stat import subprocess import qisys.sh import qisys.archive import qisys.command from qisys import ui def is_elf(filename):
64
64
54
6
57
aldebaran/qibuild
python/qibuild/breakpad.py
Python
is_elf
is_elf
21
26
21
21
6d01b4a717994b4d7e45fdc384d23014b28dab1e
bigcode/the-stack
train
6d86b8856e2fbec44932b19d
train
function
def is_exe(filename): """ Check that a file is a Windows executable. """ return filename.endswith((".exe", ".dll"))
def is_exe(filename):
""" Check that a file is a Windows executable. """ return filename.endswith((".exe", ".dll"))
x7fELF' def is_macho(filename): """ Check that a file is in the Mach-O format. """ with open(filename, "rb") as fp: data = fp.read(2) fp.close() return data == '\xcf\xfa' def is_exe(filename):
64
64
29
6
58
aldebaran/qibuild
python/qibuild/breakpad.py
Python
is_exe
is_exe
37
39
37
37
c997c277aea55e95a46b97f6bf288069b22ede23
bigcode/the-stack
train
dbb4faf4b33c582d86a0bf7b
train
function
def dump_symbols_from_binary(binary, pool_dir, build_config=None, dump_syms=None): """ Dump symbols from the binary. Results can be found in <pool_dir>/<binary name>/<id>/<binary name>.sym """ if not dump_syms: dump_syms = qisys.command.find_program("dump_syms", raises=True, build_config...
def dump_symbols_from_binary(binary, pool_dir, build_config=None, dump_syms=None):
""" Dump symbols from the binary. Results can be found in <pool_dir>/<binary name>/<id>/<binary name>.sym """ if not dump_syms: dump_syms = qisys.command.find_program("dump_syms", raises=True, build_config=build_config) if sys.platform == "darwin": dsym = gen_dsym(binary) ...
".dll")) def can_be_dumped(filename): """" Check that symbols can be dumped from the given file """ st = os.lstat(filename) # File must be a regular file if not stat.S_ISREG(st.st_mode): return False # File must be an executable if sys.platform.startswith("linux"): return is_e...
134
134
447
19
114
aldebaran/qibuild
python/qibuild/breakpad.py
Python
dump_symbols_from_binary
dump_symbols_from_binary
58
107
58
58
4255efea6a1dfedb213e4ebbd92dd85501161032
bigcode/the-stack
train
a60ce7d9a0458f3c835faa90
train
function
def dump_symbols_from_directory(root_dir, pool_dir, dump_exe=None, strip=True, strip_exe=None, strip_args=None, build_config=None): """ Dump symbols for every binary in the root dir. Assumes that dump_syms is in $PATH. If strip is True, also strip the binaries. (assumes t...
def dump_symbols_from_directory(root_dir, pool_dir, dump_exe=None, strip=True, strip_exe=None, strip_args=None, build_config=None):
""" Dump symbols for every binary in the root dir. Assumes that dump_syms is in $PATH. If strip is True, also strip the binaries. (assumes that strip is in $PATH) """ for (root, __directories, filenames) in os.walk(root_dir): for filename in filenames: full_path = os.path.joi...
to strip symbols for", binary) def gen_dsym(binary): """ Generate Dsym """ cmd = ["dsymutil", binary] qisys.command.call(cmd) return binary + ".dSYM" def dump_symbols_from_directory(root_dir, pool_dir, dump_exe=None, strip=True, strip_exe=None, strip_args=None, build_c...
77
77
259
33
44
aldebaran/qibuild
python/qibuild/breakpad.py
Python
dump_symbols_from_directory
dump_symbols_from_directory
133
156
133
134
d7b5385a9af1a8632bb78d6f708480eddd3f1a10
bigcode/the-stack
train
258e2c3fcf6cdf9d8886d87c
train
function
def is_macho(filename): """ Check that a file is in the Mach-O format. """ with open(filename, "rb") as fp: data = fp.read(2) fp.close() return data == '\xcf\xfa'
def is_macho(filename):
""" Check that a file is in the Mach-O format. """ with open(filename, "rb") as fp: data = fp.read(2) fp.close() return data == '\xcf\xfa'
ys import ui def is_elf(filename): """ Check that a file is in the elf format. """ with open(filename, "rb") as fp: data = fp.read(4) fp.close() return data == b'\x7fELF' def is_macho(filename):
64
64
52
6
58
aldebaran/qibuild
python/qibuild/breakpad.py
Python
is_macho
is_macho
29
34
29
29
ce8734896b383295893a19fcf15167a5f65f4685
bigcode/the-stack
train
cd9e03e68b54d83b8657dcc4
train
class
@dataclass(frozen=True) class PandemicSimOpts: """Parameter options passed to the simulator.""" infection_spread_rate_mean: float = 0.021 """Mean for the bounded-gaussian infection spread rate distribution""" infection_spread_rate_sigma: float = 0.01 """Std for the bounded-gaussian infection sprea...
@dataclass(frozen=True) class PandemicSimOpts:
"""Parameter options passed to the simulator.""" infection_spread_rate_mean: float = 0.021 """Mean for the bounded-gaussian infection spread rate distribution""" infection_spread_rate_sigma: float = 0.01 """Std for the bounded-gaussian infection spread rate distribution""" spontaneous_testing...
# Confidential, Copyright 2020, Sony Corporation of America, All rights reserved. from dataclasses import dataclass __all__ = ['PandemicSimOpts'] @dataclass(frozen=True) class PandemicSimOpts:
45
92
307
11
34
alfred100p/PandemicSimulator
python/pandemic_simulator/environment/simulator_opts.py
Python
PandemicSimOpts
PandemicSimOpts
7
45
7
8
2293110013dba35a16bd7d0211a34d0f6c2f0927
bigcode/the-stack
train
745426568f285521d895770e
train
class
class AccountTtl(Object): """ Contains information about the period of inactivity after which the current user's account will automatically be deleted Attributes: ID (:obj:`str`): ``AccountTtl`` Args: days (:obj:`int`): Number of days of inactivity before the account will ...
class AccountTtl(Object):
""" Contains information about the period of inactivity after which the current user's account will automatically be deleted Attributes: ID (:obj:`str`): ``AccountTtl`` Args: days (:obj:`int`): Number of days of inactivity before the account will be flagged for deletion; s...
from ..utils import Object class AccountTtl(Object):
13
64
164
6
6
iTeam-co/pytglib
pytglib/api/types/account_ttl.py
Python
AccountTtl
AccountTtl
6
32
6
6
7dee263da7d75c756ba5cbe25679d5fe7aea8e43
bigcode/the-stack
train
1b3024096686316a79b884cb
train
function
@domain.command('forward', help='Forward a Domain or print the current forward domain.') @click.argument('user') @click.argument('password') @click.argument('domain') @click.option('-u', '--url', help="The forward url") @click.option('-m', '--mode', help='How to point to the domain either "301_redirect" or "cloak"', ...
@domain.command('forward', help='Forward a Domain or print the current forward domain.') @click.argument('user') @click.argument('password') @click.argument('domain') @click.option('-u', '--url', help="The forward url") @click.option('-m', '--mode', help='How to point to the domain either "301_redirect" or "cloak"', ...
freenom = freenom_dns_updater.Freenom() if not freenom.login(user, password): click.secho('Unable to login with the given credential', fg='red', bold=True) sys.exit(6) # search the domain for d in freenom.list_domains(): if d.name == domain: domain = d bre...
@domain.command('forward', help='Forward a Domain or print the current forward domain.') @click.argument('user') @click.argument('password') @click.argument('domain') @click.option('-u', '--url', help="The forward url") @click.option('-m', '--mode', help='How to point to the domain either "301_redirect" or "cloak"', ...
111
111
371
111
0
Schmetzler/Freenom-dns-updater
freenom_dns_updater/scripts/fdu.py
Python
domain_forward
domain_forward
396
434
396
404
036d333c7590f71c4e30858327557c44b27374d0
bigcode/the-stack
train
0dd148158da7591259c17d5e
train
function
@record.command('add', help='Add a record into a specified domain') @click.argument('user') @click.argument('password') @click.argument('domain') @click.option('-n', '--name', help='Record name. Used as subdomain in A records') @click.option('-t', '--type', help='Record type. A or AAAA for instance', type=click_record_...
@record.command('add', help='Add a record into a specified domain') @click.argument('user') @click.argument('password') @click.argument('domain') @click.option('-n', '--name', help='Record name. Used as subdomain in A records') @click.option('-t', '--type', help='Record type. A or AAAA for instance', type=click_record_...
d = {'login': user, 'password': password, 'record': []} record = {'domain': domain} if name: record['name'] = name if type: record['type'] = type if target: record['target'] = target if ttl: record['ttl'] = ttl d['record'].append(record) config = freenom_d...
@record.command('add', help='Add a record into a specified domain') @click.argument('user') @click.argument('password') @click.argument('domain') @click.option('-n', '--name', help='Record name. Used as subdomain in A records') @click.option('-t', '--type', help='Record type. A or AAAA for instance', type=click_record_...
169
99
331
169
0
Schmetzler/Freenom-dns-updater
freenom_dns_updater/scripts/fdu.py
Python
record_add
record_add
100
129
100
110
150ffd53e404019158558b9c82692cabfebcdfba
bigcode/the-stack
train
be63af906d3363d1a8ac9d39
train
function
def record_action(action: Callable[[Freenom, Record], None], config: Config, ignore_errors: bool): records = config.records if not records: click.secho('There is no record configured', fg='yellow', bold=True) freenom = Freenom() if not freenom.login(config.login, config.password): click....
def record_action(action: Callable[[Freenom, Record], None], config: Config, ignore_errors: bool):
records = config.records if not records: click.secho('There is no record configured', fg='yellow', bold=True) freenom = Freenom() if not freenom.login(config.login, config.password): click.secho('Unable to login with the given credential', fg='red', bold=True) sys.exit(6) dom...
', default='freenom.yml') @click.option('-i', '--ignore-errors', default=False, help='ignore errors when updating', is_flag=True) @click.help_option('--help', '-h') def update(config, ignore_errors): return _update(config, ignore_errors) def record_action(action: Callable[[Freenom, Record], None], config: Config, i...
80
80
269
24
56
Schmetzler/Freenom-dns-updater
freenom_dns_updater/scripts/fdu.py
Python
record_action
record_action
271
302
271
271
2f760e430f4cce5c0431c361fabceb580774a230
bigcode/the-stack
train
797ecdde197449fff45a6a27
train
function
@cli.command(help='''Regularly update records according to a configuration file''') @click.argument('config', default='freenom.yml' if is_windows else '/etc/freenom.yml') @click.option('-t', '--period', default=60 * 60, help='update period in second', type=click.IntRange(10, 2592000)) @click.option('-i', '--ignore-erro...
@cli.command(help='''Regularly update records according to a configuration file''') @click.argument('config', default='freenom.yml' if is_windows else '/etc/freenom.yml') @click.option('-t', '--period', default=60 * 60, help='update period in second', type=click.IntRange(10, 2592000)) @click.option('-i', '--ignore-erro...
config_src(config) ipv4 = '' ipv6 = '' last_renew_date: Optional[datetime.date] = None while 1: try: new_ipv4 = '' new_ipv6 = '' update_needed = True if cache: try: new_ipv4 = str(get_my_ipv4()) ...
@cli.command(help='''Regularly update records according to a configuration file''') @click.argument('config', default='freenom.yml' if is_windows else '/etc/freenom.yml') @click.option('-t', '--period', default=60 * 60, help='update period in second', type=click.IntRange(10, 2592000)) @click.option('-i', '--ignore-erro...
161
140
469
161
0
Schmetzler/Freenom-dns-updater
freenom_dns_updater/scripts/fdu.py
Python
process
process
464
520
464
471
f8c8684dee846069a80732b6320146913a41c306
bigcode/the-stack
train
c28de7768a4b8b87c09637f5
train
function
@record.command('ls', help='List records of a specified domain') @click.argument('user') @click.argument('password') @click.argument('domain') @click.option('-f', '--format', help='Output format', default='TEXT', type=click.Choice(("TEXT", "JSON", "YAML"))) @click.help_option('--help', '-h') def record_ls(user, passwor...
@record.command('ls', help='List records of a specified domain') @click.argument('user') @click.argument('password') @click.argument('domain') @click.option('-f', '--format', help='Output format', default='TEXT', type=click.Choice(("TEXT", "JSON", "YAML"))) @click.help_option('--help', '-h') def record_ls(user, passwor...
freenom = freenom_dns_updater.Freenom() if not freenom.login(user, password): click.secho('Unable to login with the given credential', fg='red', bold=True) sys.exit(6) # search the domain for d in freenom.list_domains(): if d.name == domain: domain = d bre...
@record.command('ls', help='List records of a specified domain') @click.argument('user') @click.argument('password') @click.argument('domain') @click.option('-f', '--format', help='Output format', default='TEXT', type=click.Choice(("TEXT", "JSON", "YAML"))) @click.help_option('--help', '-h') def record_ls(user, passwor...
82
66
220
82
0
Schmetzler/Freenom-dns-updater
freenom_dns_updater/scripts/fdu.py
Python
record_ls
record_ls
77
97
77
83
2200984ef4e57012d6dd31f5240c8f01d21ebbab
bigcode/the-stack
train
7d331303dcb8d995b479df47
train
function
def domain_action(action: Callable[[Freenom, Domain], None], config: Config, ignore_errors: bool): records = config.records if not records: click.secho('There is no record configured', fg='yellow', bold=True) freenom = Freenom() if not freenom.login(config.login, config.password): click....
def domain_action(action: Callable[[Freenom, Domain], None], config: Config, ignore_errors: bool):
records = config.records if not records: click.secho('There is no record configured', fg='yellow', bold=True) freenom = Freenom() if not freenom.login(config.login, config.password): click.secho('Unable to login with the given credential', fg='red', bold=True) sys.exit(6) dom...
.domain = rec_domain try: action(freenom, rec) except Exception: if not ignore_errors: raise warnings.warn(traceback.format_exc()) err_count += 1 else: ok_count += 1 return ok_count, err_count def domain_action(actio...
86
86
289
24
61
Schmetzler/Freenom-dns-updater
freenom_dns_updater/scripts/fdu.py
Python
domain_action
domain_action
305
340
305
305
a8c4841740ee4cdedce6e2588945beac11ea02d7
bigcode/the-stack
train
5b8eb03c301acc6a1f86b821
train
function
def format_data(data, formater='TEXT'): if isinstance(data, (list, tuple, set)): data = [format_data(x, None) for x in data] elif isinstance(data, dict): data = {format_data(k, None): format_data(v, None) for k, v in six.iteritems(data)} elif isinstance(data, freenom_dns_updater.Domain): ...
def format_data(data, formater='TEXT'):
if isinstance(data, (list, tuple, set)): data = [format_data(x, None) for x in data] elif isinstance(data, dict): data = {format_data(k, None): format_data(v, None) for k, v in six.iteritems(data)} elif isinstance(data, freenom_dns_updater.Domain): data = format_data({'name': data.na...
()) _format_map = { None: lambda x: x, 'TEXT': lambda x: pprint.pformat(x), 'JSON': lambda x: json.dumps(x, sort_keys=True), 'YAML': lambda x: yaml.safe_dump(x) } def format_data(data, formater='TEXT'):
64
64
201
10
54
Schmetzler/Freenom-dns-updater
freenom_dns_updater/scripts/fdu.py
Python
format_data
format_data
37
52
37
37
5d2aeb621f98c8befe5c54365317fd67878dc79b
bigcode/the-stack
train
79db076b474ae6c493910677
train
function
def _update(config, ignore_errors): config = freenom_dns_updater.Config(config_src(config)) ok_count = 0 try: ok_count, err_count = record_action(lambda freenom, rec: freenom.add_record(rec, True), config, ignore_errors) if not err_count: click.echo(f'Successfully Updated {ok_c...
def _update(config, ignore_errors):
config = freenom_dns_updater.Config(config_src(config)) ok_count = 0 try: ok_count, err_count = record_action(lambda freenom, rec: freenom.add_record(rec, True), config, ignore_errors) if not err_count: click.echo(f'Successfully Updated {ok_count} record{"s" if ok_count > 1 els...
ok_count, err_count = record_action(lambda freenom, rec: freenom.remove_record(rec), config, False) if ok_count: click.echo('Record successfully removed.') else: click.secho('No record removed', fg='yellow', bold=True) def _update(config, ignore_errors):
64
64
203
8
56
Schmetzler/Freenom-dns-updater
freenom_dns_updater/scripts/fdu.py
Python
_update
_update
203
221
203
203
6d4ef21940a86569bfbc403ed38f1aefe4a4c29e
bigcode/the-stack
train
d29164279522d251baa1fbb7
train
function
@cli.command('update', help='''Update records according to a configuration file''') @click.argument('config', default='freenom.yml') @click.option('-i', '--ignore-errors', default=False, help='ignore errors when updating', is_flag=True) @click.help_option('--help', '-h') def update(config, ignore_errors): return _u...
@cli.command('update', help='''Update records according to a configuration file''') @click.argument('config', default='freenom.yml') @click.option('-i', '--ignore-errors', default=False, help='ignore errors when updating', is_flag=True) @click.help_option('--help', '-h') def update(config, ignore_errors):
return _update(config, ignore_errors)
@cli.command('update', help='''Update records according to a configuration file''') @click.argument('config', default='freenom.yml') @click.option('-i', '--ignore-errors', default=False, help='ignore errors when updating', is_flag=True) @click.help_option('--help', '-h') def update(config, ignore_errors):
69
64
78
69
0
Schmetzler/Freenom-dns-updater
freenom_dns_updater/scripts/fdu.py
Python
update
update
263
268
263
267
c73a3fe401b0fed84572bbd13350c8869351b52a
bigcode/the-stack
train
47bc2f98112c0bb648e079da
train
function
@click.group() @click.version_option('1.0') @click.help_option('--help', '-h') def cli(): pass
@click.group() @click.version_option('1.0') @click.help_option('--help', '-h') def cli():
pass
datetime.date): data = str(data) return _format_map[formater](data) click_record_type = click.Choice([t.name for t in freenom_dns_updater.RecordType]) @click.group() @click.version_option('1.0') @click.help_option('--help', '-h') def cli():
64
64
26
23
41
Schmetzler/Freenom-dns-updater
freenom_dns_updater/scripts/fdu.py
Python
cli
cli
58
62
58
61
1b2833a142e9f5d383cd2a5eab6db0e7a1a69be5
bigcode/the-stack
train
753ed7b1f8ea8b82bdc985d9
train
function
@domain.command('nameserver', help='List or change current nameservers.') @click.argument('user') @click.argument('password') @click.argument('domain') @click.option('-n', '--nameserver', help="A nameserver to set (can be used up to 5 times)", multiple=True, is_flag=False, flag_value="None") @click.help_option('--help'...
@domain.command('nameserver', help='List or change current nameservers.') @click.argument('user') @click.argument('password') @click.argument('domain') @click.option('-n', '--nameserver', help="A nameserver to set (can be used up to 5 times)", multiple=True, is_flag=False, flag_value="None") @click.help_option('--help'...
freenom = freenom_dns_updater.Freenom() if not freenom.login(user, password): click.secho('Unable to login with the given credential', fg='red', bold=True) sys.exit(6) # search the domain for d in freenom.list_domains(): if d.name == domain: domain = d bre...
.exit(6) domains = freenom.list_domains() click.echo(format_data(domains, format)) @domain.command('nameserver', help='List or change current nameservers.') @click.argument('user') @click.argument('password') @click.argument('domain') @click.option('-n', '--nameserver', help="A nameserver to set (can be used up...
113
113
377
91
22
Schmetzler/Freenom-dns-updater
freenom_dns_updater/scripts/fdu.py
Python
domain_nameserver
domain_nameserver
357
393
357
363
43ba1ce85e1e819993aaa6b5dde96169f062daf0
bigcode/the-stack
train
dd42502fb26f848ae32c498f
train
function
@cli.group(help='''Manage records''') @click.help_option('--help', '-h') def record(): pass
@cli.group(help='''Manage records''') @click.help_option('--help', '-h') def record():
pass
.Choice([t.name for t in freenom_dns_updater.RecordType]) @click.group() @click.version_option('1.0') @click.help_option('--help', '-h') def cli(): pass @cli.group(help='''Manage records''') @click.help_option('--help', '-h') def record():
64
64
25
22
41
Schmetzler/Freenom-dns-updater
freenom_dns_updater/scripts/fdu.py
Python
record
record
65
68
65
67
f3f51be4b36262432ee8c0364a30b0697afa66e0
bigcode/the-stack
train
a5e76a9a1d80748b160024de
train
function
def config_src(config): url = urlparse(config) if url.scheme in ('file', 'http', 'https'): ret = requests.get(config, stream=True).raw else: # except a file ret = pathlib.Path(config) if not ret.is_file(): click.secho(f'File "{ret}" not found.', fg='red', bold=True) ...
def config_src(config):
url = urlparse(config) if url.scheme in ('file', 'http', 'https'): ret = requests.get(config, stream=True).raw else: # except a file ret = pathlib.Path(config) if not ret.is_file(): click.secho(f'File "{ret}" not found.', fg='red', bold=True) sys.exit(5) ...
click.echo(f"Update errors: {update_error.msgs}", err=True) except Exception as e: click.echo(f"Error while updating: {e}", err=True) if not ok_count: click.secho('No record updated', fg='yellow', bold=True) def config_src(config):
64
64
91
5
59
Schmetzler/Freenom-dns-updater
freenom_dns_updater/scripts/fdu.py
Python
config_src
config_src
251
260
251
251
3259c1daec48caf8f764ff3ea217abb8a18cb4a6
bigcode/the-stack
train
7e51fc94fbdbf5e1d59df248
train
function
@domain.command('ls', help='List domains') @click.argument('user') @click.argument('password') @click.option('-f', '--format', help='Output format', default='TEXT', type=click.Choice(("TEXT", "JSON", "YAML"))) @click.help_option('--help', '-h') def domain_ls(user, password, format): freenom = Freenom() if not f...
@domain.command('ls', help='List domains') @click.argument('user') @click.argument('password') @click.option('-f', '--format', help='Output format', default='TEXT', type=click.Choice(("TEXT", "JSON", "YAML"))) @click.help_option('--help', '-h') def domain_ls(user, password, format):
freenom = Freenom() if not freenom.login(user, password): click.secho('Unable to login with the given credential', fg='red', bold=True) sys.exit(6) domains = freenom.list_domains() click.echo(format_data(domains, format))
@domain.command('ls', help='List domains') @click.argument('user') @click.argument('password') @click.option('-f', '--format', help='Output format', default='TEXT', type=click.Choice(("TEXT", "JSON", "YAML"))) @click.help_option('--help', '-h') def domain_ls(user, password, format):
71
64
132
71
0
Schmetzler/Freenom-dns-updater
freenom_dns_updater/scripts/fdu.py
Python
domain_ls
domain_ls
343
354
343
348
e716392e83f6fe7006cd0565061713badcc060f7
bigcode/the-stack
train
1db09f23dc0c97dbdcca787f
train
function
@cli.group(help='''Manage domain''') @click.help_option('--help', '-h') def domain(): pass
@cli.group(help='''Manage domain''') @click.help_option('--help', '-h') def domain():
pass
0') @click.help_option('--help', '-h') def cli(): pass @cli.group(help='''Manage records''') @click.help_option('--help', '-h') def record(): pass @cli.group(help='''Manage domain''') @click.help_option('--help', '-h') def domain():
64
64
25
22
41
Schmetzler/Freenom-dns-updater
freenom_dns_updater/scripts/fdu.py
Python
domain
domain
71
74
71
73
b764a326863d3d57a613b1ab93d4b140b4e8b115
bigcode/the-stack
train
e7d18ab674c8b6282df97f30
train
function
@record.command('rm', help='Remove a record from a specified domain') @click.argument('user') @click.argument('password') @click.argument('domain') @click.option('-n', '--name', help='Record name. Used as subdomain in A records') @click.option('-t', '--type', help='Record type. A or AAAA for instance', type=click_recor...
@record.command('rm', help='Remove a record from a specified domain') @click.argument('user') @click.argument('password') @click.argument('domain') @click.option('-n', '--name', help='Record name. Used as subdomain in A records') @click.option('-t', '--type', help='Record type. A or AAAA for instance', type=click_recor...
d = {'login': user, 'password': password, 'record': []} record = {'domain': domain} if name: record['name'] = name if type: record['type'] = type if target: record['target'] = target if ttl: record['ttl'] = ttl d['record'].append(record) config = freenom_d...
@record.command('rm', help='Remove a record from a specified domain') @click.argument('user') @click.argument('password') @click.argument('domain') @click.option('-n', '--name', help='Record name. Used as subdomain in A records') @click.option('-t', '--type', help='Record type. A or AAAA for instance', type=click_recor...
169
95
319
169
0
Schmetzler/Freenom-dns-updater
freenom_dns_updater/scripts/fdu.py
Python
record_rm
record_rm
171
200
171
181
72c02ddcf1829e438feddd902eae980e0c3c2b67
bigcode/the-stack
train
44e1ba7f3dc86531d6079b7d
train
function
def _renew(config, ignore_errors): config = freenom_dns_updater.Config(config_src(config)) ok_count = 0 def action(freenom: Freenom, domain: Domain): if freenom.need_renew(domain): if not freenom.renew(domain): raise Exception(f"unable to renew {domain.name}") try:...
def _renew(config, ignore_errors):
config = freenom_dns_updater.Config(config_src(config)) ok_count = 0 def action(freenom: Freenom, domain: Domain): if freenom.need_renew(domain): if not freenom.renew(domain): raise Exception(f"unable to renew {domain.name}") try: ok_count, err_count = doma...
s): click.echo(f"Update errors: {update_error.msgs}", err=True) except Exception as e: click.echo(f"Error while updating: {e}", err=True) if not ok_count: click.secho('No record updated', fg='yellow', bold=True) def _renew(config, ignore_errors):
70
70
235
8
62
Schmetzler/Freenom-dns-updater
freenom_dns_updater/scripts/fdu.py
Python
_renew
_renew
224
248
224
224
d94b855c31d878f31a642243aa5f24358fef252a
bigcode/the-stack
train
d3c16bd521692c3971e75db4
train
function
@domain.command('renew', help='Renew a domain for X months') @click.argument('user') @click.argument('password') @click.argument('domain') @click.option('-p', '--period', help='number of months', type=click.IntRange(1, 12)) @click.help_option('--help', '-h') def domain_renew(user, password, domain, period): freenom...
@domain.command('renew', help='Renew a domain for X months') @click.argument('user') @click.argument('password') @click.argument('domain') @click.option('-p', '--period', help='number of months', type=click.IntRange(1, 12)) @click.help_option('--help', '-h') def domain_renew(user, password, domain, period):
freenom = Freenom() if not freenom.login(user, password): click.secho('Unable to login with the given credential', fg='red', bold=True) sys.exit(6) # search the domain domains = freenom.list_domains() domain_obj = next((d for d in domains if d.name.upper() == domain.upper()), None) ...
else: click.echo("Something went wrong!") @domain.command('renew', help='Renew a domain for X months') @click.argument('user') @click.argument('password') @click.argument('domain') @click.option('-p', '--period', help='number of months', type=click.IntRange(1, 12)) @click.help_option('--help', '-h') def domain...
86
87
293
76
10
Schmetzler/Freenom-dns-updater
freenom_dns_updater/scripts/fdu.py
Python
domain_renew
domain_renew
437
461
437
443
e4fe951d0744946044bec0e323fbc4c002392cae
bigcode/the-stack
train
43cabdc379ae8d7167077c45
train
function
@record.command('update', help='Update a record') @click.argument('user') @click.argument('password') @click.argument('domain') @click.option('-n', '--name', help='Record name. Used as subdomain in A records') @click.option('-t', '--type', help='Record type. A or AAAA for instance', type=click_record_type) @click.optio...
@record.command('update', help='Update a record') @click.argument('user') @click.argument('password') @click.argument('domain') @click.option('-n', '--name', help='Record name. Used as subdomain in A records') @click.option('-t', '--type', help='Record type. A or AAAA for instance', type=click_record_type) @click.optio...
d = {'login': user, 'password': password, 'record': []} record = {'domain': domain} if name: record['name'] = name if type: record['type'] = type if target: record['target'] = target if ttl: record['ttl'] = ttl d['record'].append(record) config = freenom_d...
@record.command('update', help='Update a record') @click.argument('user') @click.argument('password') @click.argument('domain') @click.option('-n', '--name', help='Record name. Used as subdomain in A records') @click.option('-t', '--type', help='Record type. A or AAAA for instance', type=click_record_type) @click.optio...
140
111
372
140
0
Schmetzler/Freenom-dns-updater
freenom_dns_updater/scripts/fdu.py
Python
record_update
record_update
132
168
132
141
ee23503baea81bc7e337fe3e08ee82f70b727129
bigcode/the-stack
train
344786a95c1c6e14ec4e07de
train
class
class ConfigFileSection(Enum): postgresql = 0 portfolio = 2 trader = 3 consumer = 4
class ConfigFileSection(Enum):
postgresql = 0 portfolio = 2 trader = 3 consumer = 4
from enum import Enum class ConfigFileSection(Enum):
11
64
31
6
4
Plazas87/trading_stocks_platform
trade_app/config/config_file_structure.py
Python
ConfigFileSection
ConfigFileSection
4
8
4
4
296b163617cdee08f4d8565c393f7a45cf715789
bigcode/the-stack
train
b243a5643a77c7d8df1e5b07
train
function
def train(training_data, learning_rate=1e-1, batch_size=256, epochs=30): total_values = len(training_data) print('---Training Model---') for epoch in range(epochs): print('Currently on epoch {}'.format(epoch+1)) np.random.shuffle(training_data) mini_batches = [training_data[k: k+batch_size] ...
def train(training_data, learning_rate=1e-1, batch_size=256, epochs=30):
total_values = len(training_data) print('---Training Model---') for epoch in range(epochs): print('Currently on epoch {}'.format(epoch+1)) np.random.shuffle(training_data) mini_batches = [training_data[k: k+batch_size] for k in range(0, total_values, batch_size)] training_cost = 0 f...
, parameters=params, grads=grads), allow_input_downcast=True) f_rebuilt = theano.function(inputs=[X], outputs=out_layer.output, allow_input_downcast=True) def train(training_data, learning_rate=1e-1, batch_size=256, epochs=30):
64
64
154
22
42
LukaszObara/Theano_AutoEncoder
AutoEncoder.py
Python
train
train
38
57
38
38
67d2d3ca17f2964e3003dcf0d33b9d3eea84875e
bigcode/the-stack
train
164342be7744f95cca1c9197
train
function
def main(): location = "E:\\Projects\\MNIST\\train.csv" data = pd.read_csv(location) data = data.sample(41984, random_state=35) images = data.iloc[:, 1:].values images = images.astype(theano.config.floatX) images = np.multiply(images, 1.0/255.0) train(images)
def main():
location = "E:\\Projects\\MNIST\\train.csv" data = pd.read_csv(location) data = data.sample(41984, random_state=35) images = data.iloc[:, 1:].values images = images.astype(theano.config.floatX) images = np.multiply(images, 1.0/255.0) train(images)
training_cost = 0 for mini_batch in mini_batches: cost_ij = f(mini_batch, learning_rate) training_cost += cost_ij print('The loss is: {}'.format(training_cost/batch_size)) print('--------------------------') def main():
63
64
78
3
60
LukaszObara/Theano_AutoEncoder
AutoEncoder.py
Python
main
main
60
69
60
60
ba57018f1063447dd36b99eb194bc7738cf5c725
bigcode/the-stack
train
832ea457351274720321efe5
train
class
class TestResourceCommand(unittest2.TestCase): def __init__(self, *args, **kwargs): super(TestResourceCommand, self).__init__(*args, **kwargs) self.parser = argparse.ArgumentParser() self.subparsers = self.parser.add_subparsers() self.branch = resource.ResourceBranch( bas...
class TestResourceCommand(unittest2.TestCase):
def __init__(self, *args, **kwargs): super(TestResourceCommand, self).__init__(*args, **kwargs) self.parser = argparse.ArgumentParser() self.subparsers = self.parser.add_subparsers() self.branch = resource.ResourceBranch( base.FakeResource, "Test Command", base.FakeApp(),...
Copyright 2019 Extreme Networks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
256
256
2,125
9
247
anirudhbagri/st2
st2client/tests/unit/test_commands.py
Python
TestResourceCommand
TestResourceCommand
41
296
41
41
2257f8801a6caa3564d662edf53ca493854f62c4
bigcode/the-stack
train
0cfa72cecb123eb7f877d408
train
class
class ResourceViewCommandTestCase(unittest2.TestCase): def setUp(self): ResourceViewCommand.display_attributes = [] def test_get_include_attributes(self): cls = namedtuple("Args", "attr") args = cls(attr=[]) result = ResourceViewCommand._get_include_attributes(args=args) ...
class ResourceViewCommandTestCase(unittest2.TestCase):
def setUp(self): ResourceViewCommand.display_attributes = [] def test_get_include_attributes(self): cls = namedtuple("Args", "attr") args = cls(attr=[]) result = ResourceViewCommand._get_include_attributes(args=args) self.assertEqual(result, []) args = cls(attr...
), 200, "OK") ), ) @mock.patch.object( httpclient.HTTPClient, "delete", mock.MagicMock( return_value=base.FakeResponse("", 500, "INTERNAL SERVER ERROR") ), ) def test_command_delete_failed(self): args = self.parser.parse_args(["fakeresource", "...
109
109
365
11
98
anirudhbagri/st2
st2client/tests/unit/test_commands.py
Python
ResourceViewCommandTestCase
ResourceViewCommandTestCase
299
342
299
299
318b070e873eab94d35aca0a7dbed8f2148f00a6
bigcode/the-stack
train
6a4d0c1b80a4300d98b2e0a6
train
class
class CommandsHelpStringTestCase(BaseCLITestCase): """ Test case which verifies that all the commands support -h / --help flag. """ capture_output = True # TODO: Automatically iterate all the available commands COMMANDS = [ # action ["action", "list"], ["action", "get"]...
class CommandsHelpStringTestCase(BaseCLITestCase):
""" Test case which verifies that all the commands support -h / --help flag. """ capture_output = True # TODO: Automatically iterate all the available commands COMMANDS = [ # action ["action", "list"], ["action", "get"], ["action", "create"], ["action", ...
self.assertEqual(result, ["result.stdout", "trigger_instance.id"]) ResourceViewCommand.display_attributes = ["id", "status"] args = cls(attr=[]) result = ResourceViewCommand._get_include_attributes(args=args) self.assertEqual(set(result), set(["id", "status"])) args = ...
138
138
462
11
127
anirudhbagri/st2
st2client/tests/unit/test_commands.py
Python
CommandsHelpStringTestCase
CommandsHelpStringTestCase
345
416
345
345
384b05531ba7623814ef03a6a63b5dc5240f76ce
bigcode/the-stack
train
f1b8bb74ac05b403a85b41a5
train
function
def slot_catch_error(*args, catch=Exception, on_exception_emit=None): """ This is a decorator for Slots where an exception in user code is caught, printed and a optional qtSignal with signature qtSignal(Exception, str) is emitted when that happens. Based on: https://stackoverflow.com/questi...
def slot_catch_error(*args, catch=Exception, on_exception_emit=None):
""" This is a decorator for Slots where an exception in user code is caught, printed and a optional qtSignal with signature qtSignal(Exception, str) is emitted when that happens. Based on: https://stackoverflow.com/questions/18740884/preventing-pyqt-to-silence-exceptions-occurring-in-slots ...
20): try: stack = inspect.stack()[i] callers += [f'{stack.function}[{stack.lineno}]'] except Exception as e: # pylint: disable=broad-except print("Exception during do_debug exception handling: " + e.__repr__()) calle...
121
121
405
17
104
kim5284/qiskit-metal
qiskit_metal/_gui/utility/_handle_qt_messages.py
Python
slot_catch_error
slot_catch_error
108
153
108
108
c62be51ccaa8fa51c9fa0f1cbf117c1ef06d2dda
bigcode/the-stack
train
ac41afb8ba68fe4bb7139b7f
train
function
def do_debug(msg, name='info'): """ Utility function used to print debug statements from PySide2 Socket calls A bit of a cludge Arguments: msg (str): Message to print or log to user name (str): info wran, debug, etc. Defaults to 'info'. """ if 0: # This just gives the ...
def do_debug(msg, name='info'):
""" Utility function used to print debug statements from PySide2 Socket calls A bit of a cludge Arguments: msg (str): Message to print or log to user name (str): info wran, debug, etc. Defaults to 'info'. """ if 0: # This just gives the qt main loop traceback. Not usef...
d, func: %s(), file: %s' % (context.line, context.function, context.file) + ' %s: %s\n' % (mode, message)) ####################################################################################### # Auxilary handlers - mostly for debug purposes def do_debug(msg, name='info'):
64
64
206
9
54
kim5284/qiskit-metal
qiskit_metal/_gui/utility/_handle_qt_messages.py
Python
do_debug
do_debug
81
105
81
81
0a69d83a9de97c266c1338ad3a80b1b59afd9220
bigcode/the-stack
train
ae2023813d14d0e04f57aaf1
train
function
def _qt_message_handler(mode, context, message): ''' The message handler is a function that prints out debug messages, warnings, critical and fatal error messages. The Qt library (debug mode) contains hundreds of warning messages that are printed when internal errors (usually invalid function argume...
def _qt_message_handler(mode, context, message):
''' The message handler is a function that prints out debug messages, warnings, critical and fatal error messages. The Qt library (debug mode) contains hundreds of warning messages that are printed when internal errors (usually invalid function arguments) occur. Qt built in release mode also con...
copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ This is a utility module used to handle qt error messages on slots and etc. """ import inspect import logging import traceback import types from functools import wraps from PySide2 import QtCo...
112
112
374
11
100
kim5284/qiskit-metal
qiskit_metal/_gui/utility/_handle_qt_messages.py
Python
_qt_message_handler
_qt_message_handler
35
74
35
35
55f8a9c7463f86918c98674b7e8159e4b08ce7f6
bigcode/the-stack
train
8dc4bb3a11bf31cb1b1d42ae
train
function
def test_collate_fn(data): records, video_features, word_ids, char_ids, *_ = zip(*data) # If BERT is used, pad individual components of the dictionary. if not isinstance(word_ids[0], list): pad_input_ids, _ = pad_seq([ii["input_ids"] for ii in word_ids]) pad_attention_mask, _ = pad_seq([ii["...
def test_collate_fn(data):
records, video_features, word_ids, char_ids, *_ = zip(*data) # If BERT is used, pad individual components of the dictionary. if not isinstance(word_ids[0], list): pad_input_ids, _ = pad_seq([ii["input_ids"] for ii in word_ids]) pad_attention_mask, _ = pad_seq([ii["attention_mask"] for ii in ...
(et + 1)] = 1 # convert to torch tensor vfeats = torch.tensor(vfeats, dtype=torch.float32) vfeat_lens = torch.tensor(vfeat_lens, dtype=torch.int64) s_labels = torch.tensor(s_labels, dtype=torch.int64) e_labels = torch.tensor(e_labels, dtype=torch.int64) h_labels = torch.tensor(h_labels, dtype=t...
128
128
428
7
120
emulhall/episodic-memory
NLQ/VSLNet/utils/data_loader.py
Python
test_collate_fn
test_collate_fn
80
111
80
80
993209644094509e43dc09ce234e0a0df3168b29
bigcode/the-stack
train
02cf22e2188f7e219981d08e
train
function
def get_train_loader(dataset, video_features, configs): train_set = Dataset(dataset=dataset, video_features=video_features) train_loader = torch.utils.data.DataLoader( dataset=train_set, batch_size=configs.batch_size, shuffle=True, collate_fn=train_collate_fn, ) return tr...
def get_train_loader(dataset, video_features, configs):
train_set = Dataset(dataset=dataset, video_features=video_features) train_loader = torch.utils.data.DataLoader( dataset=train_set, batch_size=configs.batch_size, shuffle=True, collate_fn=train_collate_fn, ) return train_loader
vfeats = torch.tensor(vfeats, dtype=torch.float32) vfeat_lens = torch.tensor(vfeat_lens, dtype=torch.int64) return records, vfeats, vfeat_lens, word_ids, char_ids def get_train_loader(dataset, video_features, configs):
64
64
69
11
52
emulhall/episodic-memory
NLQ/VSLNet/utils/data_loader.py
Python
get_train_loader
get_train_loader
114
122
114
114
8be3c7c220d565227b1da30e2d6ce74133fbb266
bigcode/the-stack
train
2e2ca1ee2f36b919c7521bb0
train
function
def train_collate_fn(data): records, video_features, word_ids, char_ids, s_inds, e_inds = zip(*data) # If BERT is used, pad individual components of the dictionary. if not isinstance(word_ids[0], list): pad_input_ids, _ = pad_seq([ii["input_ids"] for ii in word_ids]) pad_attention_mask, _ = ...
def train_collate_fn(data):
records, video_features, word_ids, char_ids, s_inds, e_inds = zip(*data) # If BERT is used, pad individual components of the dictionary. if not isinstance(word_ids[0], list): pad_input_ids, _ = pad_seq([ii["input_ids"] for ii in word_ids]) pad_attention_mask, _ = pad_seq([ii["attention_mask"...
import numpy as np import torch import torch.utils.data from utils.data_util import pad_seq, pad_char_seq, pad_video_seq class Dataset(torch.utils.data.Dataset): def __init__(self, dataset, video_features): super(Dataset, self).__init__() self.dataset = dataset self.video_features = video...
179
207
691
7
172
emulhall/episodic-memory
NLQ/VSLNet/utils/data_loader.py
Python
train_collate_fn
train_collate_fn
26
77
26
26
533083ff56ba3417b53026bc661367aeda6ee4ab
bigcode/the-stack
train
72e31f708483f25bdd76e627
train
class
class Dataset(torch.utils.data.Dataset): def __init__(self, dataset, video_features): super(Dataset, self).__init__() self.dataset = dataset self.video_features = video_features def __getitem__(self, index): record = self.dataset[index] video_feature = self.video_feature...
class Dataset(torch.utils.data.Dataset):
def __init__(self, dataset, video_features): super(Dataset, self).__init__() self.dataset = dataset self.video_features = video_features def __getitem__(self, index): record = self.dataset[index] video_feature = self.video_features[record["vid"]] s_ind, e_ind = i...
import numpy as np import torch import torch.utils.data from utils.data_util import pad_seq, pad_char_seq, pad_video_seq class Dataset(torch.utils.data.Dataset):
36
64
143
7
28
emulhall/episodic-memory
NLQ/VSLNet/utils/data_loader.py
Python
Dataset
Dataset
8
23
8
8
929f8b2582fb4ba647c72ace01ce3c1e2ca22fd9
bigcode/the-stack
train
97af1b912884729cadf4c3b0
train
function
def get_test_loader(dataset, video_features, configs): test_set = Dataset(dataset=dataset, video_features=video_features) test_loader = torch.utils.data.DataLoader( dataset=test_set, batch_size=configs.batch_size, shuffle=False, collate_fn=test_collate_fn, ) return test_l...
def get_test_loader(dataset, video_features, configs):
test_set = Dataset(dataset=dataset, video_features=video_features) test_loader = torch.utils.data.DataLoader( dataset=test_set, batch_size=configs.batch_size, shuffle=False, collate_fn=test_collate_fn, ) return test_loader
(dataset=dataset, video_features=video_features) train_loader = torch.utils.data.DataLoader( dataset=train_set, batch_size=configs.batch_size, shuffle=True, collate_fn=train_collate_fn, ) return train_loader def get_test_loader(dataset, video_features, configs):
64
64
69
11
52
emulhall/episodic-memory
NLQ/VSLNet/utils/data_loader.py
Python
get_test_loader
get_test_loader
125
133
125
125
45bcdf4d240ab96ee5855aabc10be22bddb71579
bigcode/the-stack
train
c5a8a3cc22de7a08f85f1611
train
class
class Trainable(object): """Interface for objects that are trainable by, e.g., `Experiment`. """ __metaclass__ = abc.ABCMeta @abc.abstractmethod def fit(self, x=None, y=None, input_fn=None, steps=None, batch_size=None, monitors=None, max_steps=None): """Trains a model given training data `x` pr...
class Trainable(object):
"""Interface for objects that are trainable by, e.g., `Experiment`. """ __metaclass__ = abc.ABCMeta @abc.abstractmethod def fit(self, x=None, y=None, input_fn=None, steps=None, batch_size=None, monitors=None, max_steps=None): """Trains a model given training data `x` predictions and `y` targets...
obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for...
127
127
426
5
121
rcelebi/android-elfali
jni-build/jni/include/tensorflow/contrib/learn/python/learn/trainable.py
Python
Trainable
Trainable
25
62
25
25
d93b51983bc4c0b2cf6badd07e9a270eb1ec586f
bigcode/the-stack
train
638fa63ca974e2845ab7f03d
train
function
def devicetreefromim4p(indata): outdata = der_decoder.decode(indata) return bytes(outdata[0][3])
def devicetreefromim4p(indata):
outdata = der_decoder.decode(indata) return bytes(outdata[0][3])
from pyasn1.codec.der import decoder as der_decoder def devicetreefromim4p(indata):
24
64
30
12
11
zhuowei/XNUQEMUScripts
devicetreefromim4p.py
Python
devicetreefromim4p
devicetreefromim4p
2
4
2
2
b37cef9cbc648d8c4c55e55f114e35eb783ecf9c
bigcode/the-stack
train
c928168966d7368a2a7337d2
train
function
@pytest.fixture(scope="function") def as_prosumer_user1(client): """ Login the default test prosumer and log him out afterwards. """ login(client, "test_prosumer_user@seita.nl", "testtest") yield logout(client)
@pytest.fixture(scope="function") def as_prosumer_user1(client):
""" Login the default test prosumer and log him out afterwards. """ login(client, "test_prosumer_user@seita.nl", "testtest") yield logout(client)
from flexmeasures.data.services.users import create_user from flexmeasures.data.models.assets import Asset from flexmeasures.data.models.weather import WeatherSensor, WeatherSensorType from flexmeasures.ui.tests.utils import login, logout @pytest.fixture(scope="function") def as_prosumer_user1(client):
64
64
58
15
48
FlexMeasures/flexmeasures
flexmeasures/ui/tests/conftest.py
Python
as_prosumer_user1
as_prosumer_user1
9
16
9
10
e22960526a50bc8b188a56192682229956a67a28
bigcode/the-stack
train
6d2fdabbe69d0ba0df027dfe
train
function
@pytest.fixture(scope="function") def as_admin(client): """ Login the admin user and log him out afterwards. """ login(client, "flexmeasures-admin@seita.nl", "testtest") yield logout(client)
@pytest.fixture(scope="function") def as_admin(client):
""" Login the admin user and log him out afterwards. """ login(client, "flexmeasures-admin@seita.nl", "testtest") yield logout(client)
") def as_prosumer_user1(client): """ Login the default test prosumer and log him out afterwards. """ login(client, "test_prosumer_user@seita.nl", "testtest") yield logout(client) @pytest.fixture(scope="function") def as_admin(client):
64
64
51
11
53
FlexMeasures/flexmeasures
flexmeasures/ui/tests/conftest.py
Python
as_admin
as_admin
19
26
19
20
483f6a0e8f57f1f81a8ab8c357eaba4d4431cf26
bigcode/the-stack
train
73069192a961246eb77bfe0b
train
function
@pytest.fixture(scope="module", autouse=True) def setup_ui_test_data( db, setup_accounts, setup_roles_users, setup_markets, setup_sources, setup_asset_types, ): """ Create another prosumer, without data, and an admin Also, a weather sensor (and sensor type). TODO: review if any ...
@pytest.fixture(scope="module", autouse=True) def setup_ui_test_data( db, setup_accounts, setup_roles_users, setup_markets, setup_sources, setup_asset_types, ):
""" Create another prosumer, without data, and an admin Also, a weather sensor (and sensor type). TODO: review if any of these are really needed (might be covered now by main conftest) """ print("Setting up data for UI tests on %s" % db.engine) create_user( username="Site Admin", ...
login(client, "test_prosumer_user@seita.nl", "testtest") yield logout(client) @pytest.fixture(scope="function") def as_admin(client): """ Login the admin user and log him out afterwards. """ login(client, "flexmeasures-admin@seita.nl", "testtest") yield logout(client) @pytest.fixtu...
120
120
403
43
77
FlexMeasures/flexmeasures
flexmeasures/ui/tests/conftest.py
Python
setup_ui_test_data
setup_ui_test_data
29
87
29
37
8e790fc6dba2152c0b4b94d63ec0559fa3d82c7e
bigcode/the-stack
train
e4182ac2bd8dac7cdb5fd755
train
function
def show_available_models(): """Displays available models """ print(list(__model_factory.keys()))
def show_available_models():
"""Displays available models """ print(list(__model_factory.keys()))
'stochastic_depth_resnet101': stochastic_depth_resnet101, 'stochastic_depth_resnet152': stochastic_depth_resnet152, 'wideresnet':wideresnet, 'xception': xception, 'dpn':DPN26 } def show_available_models():
64
64
21
5
59
TiffanyTseng54/SimpleCVReproduction
NAS/cifar100/models/__init__.py
Python
show_available_models
show_available_models
87
91
87
87
c734508b667a0ff81bb851d5e05cf02d00e8b0d6
bigcode/the-stack
train
bfb26b27247f6368501b29f3
train
function
def build_model(name, num_classes=100): avai_models = list(__model_factory.keys()) if name not in avai_models: raise KeyError( 'Unknown model: {}. Must be one of {}'.format(name, avai_models) ) return __model_factory[name](num_classes=num_classes)
def build_model(name, num_classes=100):
avai_models = list(__model_factory.keys()) if name not in avai_models: raise KeyError( 'Unknown model: {}. Must be one of {}'.format(name, avai_models) ) return __model_factory[name](num_classes=num_classes)
152, 'wideresnet':wideresnet, 'xception': xception, 'dpn':DPN26 } def show_available_models(): """Displays available models """ print(list(__model_factory.keys())) def build_model(name, num_classes=100):
63
64
68
10
53
TiffanyTseng54/SimpleCVReproduction
NAS/cifar100/models/__init__.py
Python
build_model
build_model
94
100
94
94
eb9b177415bf5afe115103c5aec64d97f0a1c9bf
bigcode/the-stack
train
9a51a8b9c20d9e15705ee9ba
train
function
@pytest.fixture def complete_event(): from mock import Mock return Mock()
@pytest.fixture def complete_event():
from mock import Mock return Mock()
_literals import pytest from prompt_toolkit.completion import Completion from prompt_toolkit.document import Document @pytest.fixture def completer(): import mycli.sqlcompleter as sqlcompleter return sqlcompleter.SQLCompleter(smart_completion=False) @pytest.fixture def complete_event():
64
64
17
7
57
steverobbins/mycli
tests/test_naive_completion.py
Python
complete_event
complete_event
11
14
11
12
093d74e48bf8e2d611b972bda5938782aea24024
bigcode/the-stack
train
00fe8776e998930a2f3100cb
train
function
def test_empty_string_completion(completer, complete_event): text = '' position = 0 result = set(completer.get_completions( Document(text=text, cursor_position=position), complete_event)) assert result == set(map(Completion, completer.all_completions))
def test_empty_string_completion(completer, complete_event):
text = '' position = 0 result = set(completer.get_completions( Document(text=text, cursor_position=position), complete_event)) assert result == set(map(Completion, completer.all_completions))
@pytest.fixture def completer(): import mycli.sqlcompleter as sqlcompleter return sqlcompleter.SQLCompleter(smart_completion=False) @pytest.fixture def complete_event(): from mock import Mock return Mock() def test_empty_string_completion(completer, complete_event):
64
64
64
12
52
steverobbins/mycli
tests/test_naive_completion.py
Python
test_empty_string_completion
test_empty_string_completion
16
22
16
16
bd433c242a531b6e1d2bcc7399b563393c509aab
bigcode/the-stack
train
c8ec4e54139f0f9637f9646b
train
function
def test_column_name_completion(completer, complete_event): text = 'SELECT FROM users' position = len('SELECT ') result = set(completer.get_completions( Document(text=text, cursor_position=position), complete_event)) assert result == set(map(Completion, completer.all_completions))
def test_column_name_completion(completer, complete_event):
text = 'SELECT FROM users' position = len('SELECT ') result = set(completer.get_completions( Document(text=text, cursor_position=position), complete_event)) assert result == set(map(Completion, completer.all_completions))
(completer.get_completions( Document(text=text, cursor_position=position), complete_event)) assert result == set([ Completion(text='MAX', start_position=-2), Completion(text='MAXEXTENTS', start_position=-2)]) def test_column_name_completion(completer, complete_event):
64
64
70
12
52
steverobbins/mycli
tests/test_naive_completion.py
Python
test_column_name_completion
test_column_name_completion
42
48
42
42
8fb315a7b5ed0dee8e0d67a5e6e86d3fce1c061d
bigcode/the-stack
train
f4ac4b20cd91c97542685ca1
train
function
@pytest.fixture def completer(): import mycli.sqlcompleter as sqlcompleter return sqlcompleter.SQLCompleter(smart_completion=False)
@pytest.fixture def completer():
import mycli.sqlcompleter as sqlcompleter return sqlcompleter.SQLCompleter(smart_completion=False)
from __future__ import unicode_literals import pytest from prompt_toolkit.completion import Completion from prompt_toolkit.document import Document @pytest.fixture def completer():
35
64
35
7
27
steverobbins/mycli
tests/test_naive_completion.py
Python
completer
completer
6
9
6
7
99bb1a09496408ee71e122c8fff43e16a8bd5535
bigcode/the-stack
train
c155f500a1c1ba925a4c04d8
train
function
def test_select_keyword_completion(completer, complete_event): text = 'SEL' position = len('SEL') result = set(completer.get_completions( Document(text=text, cursor_position=position), complete_event)) assert result == set([Completion(text='SELECT', start_position=-3)])
def test_select_keyword_completion(completer, complete_event):
text = 'SEL' position = len('SEL') result = set(completer.get_completions( Document(text=text, cursor_position=position), complete_event)) assert result == set([Completion(text='SELECT', start_position=-3)])
text = '' position = 0 result = set(completer.get_completions( Document(text=text, cursor_position=position), complete_event)) assert result == set(map(Completion, completer.all_completions)) def test_select_keyword_completion(completer, complete_event):
64
64
67
12
52
steverobbins/mycli
tests/test_naive_completion.py
Python
test_select_keyword_completion
test_select_keyword_completion
24
30
24
24
02b20e0890daa10590435d17c1ccc2cd108e351e
bigcode/the-stack
train
a44b8a70b4e81908c8fd7e3c
train
function
def test_function_name_completion(completer, complete_event): text = 'SELECT MA' position = len('SELECT MA') result = set(completer.get_completions( Document(text=text, cursor_position=position), complete_event)) assert result == set([ Completion(text='MAX', start_position=-2), ...
def test_function_name_completion(completer, complete_event):
text = 'SELECT MA' position = len('SELECT MA') result = set(completer.get_completions( Document(text=text, cursor_position=position), complete_event)) assert result == set([ Completion(text='MAX', start_position=-2), Completion(text='MAXEXTENTS', start_position=-2)])
'SEL' position = len('SEL') result = set(completer.get_completions( Document(text=text, cursor_position=position), complete_event)) assert result == set([Completion(text='SELECT', start_position=-3)]) def test_function_name_completion(completer, complete_event):
64
64
83
12
52
steverobbins/mycli
tests/test_naive_completion.py
Python
test_function_name_completion
test_function_name_completion
32
40
32
32
afb050ffad9527563fec4fdef7b700bae9c43a03
bigcode/the-stack
train
8d2c50d3ef31cf5951963220
train
class
class InlineQueryResult(Object): """One result of an inline query. Pyrogram currently supports results of the following types: - :obj:`~pyrogram.types.InlineQueryResultArticle` - :obj:`~pyrogram.types.InlineQueryResultPhoto` - :obj:`~pyrogram.types.InlineQueryResultAnimation` """ def __in...
class InlineQueryResult(Object):
"""One result of an inline query. Pyrogram currently supports results of the following types: - :obj:`~pyrogram.types.InlineQueryResultArticle` - :obj:`~pyrogram.types.InlineQueryResultPhoto` - :obj:`~pyrogram.types.InlineQueryResultAnimation` """ def __init__( self, ...
obj:`~pyrogram.types.InlineQueryResultPhoto` - :obj:`~pyrogram.types.InlineQueryResultVenue` - :obj:`~pyrogram.types.InlineQueryResultVideo` - :obj:`~pyrogram.types.InlineQueryResultVoice`""" class InlineQueryResult(Object):
64
64
169
6
58
appheap/social-media-analyzer
backend/pyrogram/types/inline_mode/inline_query_result.py
Python
InlineQueryResult
InlineQueryResult
45
70
45
45
f6990eb66f327a8c233b09a5b8595e794063db33
bigcode/the-stack
train
860ae741a58c35eb77aca0ea
train
function
def locate_pricer(module_name): return locate_class(CosinePricer)(module_name)
def locate_pricer(module_name):
return locate_class(CosinePricer)(module_name)
icers.base_pricer import CosinePricer # MODULE CLASSES def collate_feeds(modules): return collate_classes(CosineBaseFeed)(modules) def collate_pricers(modules): return collate_classes(CosinePricer)(modules) def locate_pricer(module_name):
64
64
20
7
57
oladotunr/cosine
cosine/pricing/__init__.py
Python
locate_pricer
locate_pricer
21
22
21
21
f7fee63648fe51f038ce756abce334c874ab865e
bigcode/the-stack
train
f8e59b61874d8728d65fd6a2
train
function
def collate_feeds(modules): return collate_classes(CosineBaseFeed)(modules)
def collate_feeds(modules):
return collate_classes(CosineBaseFeed)(modules)
""" __author__ = 'dotun rominiyi' # IMPORTS from cosine.core.utils import collate_classes, locate_class from .base_feed import CosineBaseFeed from .pricers.base_pricer import CosinePricer # MODULE CLASSES def collate_feeds(modules):
64
64
21
8
55
oladotunr/cosine
cosine/pricing/__init__.py
Python
collate_feeds
collate_feeds
15
16
15
15
3191818d8ab9024021c6c1d2724c36427dfbe1cc
bigcode/the-stack
train
f00488474d9f7ad5113b0009
train
function
def collate_pricers(modules): return collate_classes(CosinePricer)(modules)
def collate_pricers(modules):
return collate_classes(CosinePricer)(modules)
collate_classes, locate_class from .base_feed import CosineBaseFeed from .pricers.base_pricer import CosinePricer # MODULE CLASSES def collate_feeds(modules): return collate_classes(CosineBaseFeed)(modules) def collate_pricers(modules):
64
64
21
8
56
oladotunr/cosine
cosine/pricing/__init__.py
Python
collate_pricers
collate_pricers
18
19
18
18
9919e8e1fef1adebc80dc901d5aafdfc4a18dd42
bigcode/the-stack
train
d3ba90b3fb59a6f443367768
train
class
@unittest.skipIf(apiclient is None, 'GCP dependencies are not installed') class UtilTest(unittest.TestCase): @unittest.skip("Enable once BEAM-1080 is fixed.") def test_create_application_client(self): pipeline_options = PipelineOptions() apiclient.DataflowApplicationClient(pipeline_options) def test_pipe...
@unittest.skipIf(apiclient is None, 'GCP dependencies are not installed') class UtilTest(unittest.TestCase): @unittest.skip("Enable once BEAM-1080 is fixed.")
def test_create_application_client(self): pipeline_options = PipelineOptions() apiclient.DataflowApplicationClient(pipeline_options) def test_pipeline_url(self): pipeline_options = PipelineOptions([ '--subnetwork', '/regions/MY/subnetworks/SUBNETWORK', '--temp_location', ...
.pipeline_options import PipelineOptions from apache_beam.pipeline import Pipeline from apache_beam.portability import common_urns from apache_beam.portability.api import beam_runner_api_pb2 from apache_beam.runners.dataflow.internal import names from apache_beam.runners.dataflow.internal.clients import dataflow from a...
256
256
9,407
42
214
NicholasAzar/beam
sdks/python/apache_beam/runners/dataflow/internal/apiclient_test.py
Python
UtilTest
UtilTest
55
1,201
55
57
eb04d7a9670efd83992c8637f63ee1e04f3102db
bigcode/the-stack
train
342224ae755466586a71e4ae
train
function
async def sample_list_resources(): # Create a client client = mollusca_v1.SnippetsAsyncClient() # Initialize request argument(s) request = mollusca_v1.ListResourcesRequest( parent="parent_value", resource_with_wildcard="resource_with_wildcard_value", ) # Make the request pa...
async def sample_list_resources(): # Create a client
client = mollusca_v1.SnippetsAsyncClient() # Initialize request argument(s) request = mollusca_v1.ListResourcesRequest( parent="parent_value", resource_with_wildcard="resource_with_wildcard_value", ) # Make the request page_result = client.list_resources(request=request) as...
package dependency, execute the following: # python3 -m pip install animalia-mollusca # [START mollusca_generated_mollusca_v1_Snippets_ListResources_async] from animalia import mollusca_v1 async def sample_list_resources(): # Create a client
64
64
94
12
51
LaudateCorpus1/gapic-generator-python
tests/snippetgen/goldens/mollusca_generated_mollusca_v1_snippets_list_resources_async.py
Python
sample_list_resources
sample_list_resources
30
43
30
31
6bd3b9ba63ffed9c4194057f66f7592415bf3aff
bigcode/the-stack
train
9b319d1b470725c81ca38333
train
class
class Migration(migrations.Migration): dependencies = [ ('app', '0022_auto_20210710_1644'), ] operations = [ migrations.AddField( model_name='symbol', name='length', field=models.IntegerField(default=0), preserve_default=False, ), ...
class Migration(migrations.Migration):
dependencies = [ ('app', '0022_auto_20210710_1644'), ] operations = [ migrations.AddField( model_name='symbol', name='length', field=models.IntegerField(default=0), preserve_default=False, ), ]
# Generated by Django 3.2.5 on 2021-07-10 22:24 from django.db import migrations, models class Migration(migrations.Migration):
38
64
67
7
30
johntellsall/shotglass
shotglass/app/migrations/0023_add_length.py
Python
Migration
Migration
6
19
6
7
34c5ebcfbe57d1e6d7f347a1ef42f3d4d8b87d4c
bigcode/the-stack
train
e44812a33102eff847bdc5b3
train
class
class TestErrorTask(unittest.TestCase): def _makeOne(self, channel=None, request=None): if channel is None: channel = DummyChannel() if request is None: request = DummyParser() request.error = self._makeDummyError() from waitress.task import ErrorTask ...
class TestErrorTask(unittest.TestCase):
def _makeOne(self, channel=None, request=None): if channel is None: channel = DummyChannel() if request is None: request = DummyParser() request.error = self._makeDummyError() from waitress.task import ErrorTask return ErrorTask(channel, request) ...
self.assertEqual(environ["PATH_INFO"], "/") self.assertEqual(environ["QUERY_STRING"], "abc") self.assertEqual(environ["REMOTE_ADDR"], "127.0.0.1") self.assertEqual(environ["REMOTE_HOST"], "127.0.0.1") self.assertEqual(environ["REMOTE_PORT"], "39830") self.assertEqual(environ["CO...
253
253
845
8
245
flipmcf/waitress
tests/test_task.py
Python
TestErrorTask
TestErrorTask
843
925
843
843
76151d2034756aa97df99744fde7caf682811c03
bigcode/the-stack
train
590b797edf9bf781539cc70a
train
class
class DummyServer: server_name = "localhost" effective_port = 80 def __init__(self): self.adj = DummyAdj()
class DummyServer:
server_name = "localhost" effective_port = 80 def __init__(self): self.adj = DummyAdj()
self.serviced = True def cancel(self): self.cancelled = True class DummyAdj: log_socket_errors = True ident = "waitress" host = "127.0.0.1" port = 80 url_prefix = "" class DummyServer:
63
64
33
4
59
flipmcf/waitress
tests/test_task.py
Python
DummyServer
DummyServer
947
952
947
947
f7f13429df2477b4f47d378a23dfaa8e713a7693
bigcode/the-stack
train
d068c0273f4d6c2d07cdb072
train
class
class TestWSGITask(unittest.TestCase): def _makeOne(self, channel=None, request=None): if channel is None: channel = DummyChannel() if request is None: request = DummyParser() from waitress.task import WSGITask return WSGITask(channel, request) def test_...
class TestWSGITask(unittest.TestCase):
def _makeOne(self, channel=None, request=None): if channel is None: channel = DummyChannel() if request is None: request = DummyParser() from waitress.task import WSGITask return WSGITask(channel, request) def test_service(self): inst = self._mak...
ritten, b"abc") def test_write_header_not_written(self): inst = self._makeOne() inst.wrote_header = False inst.complete = True inst.write(b"abc") self.assertTrue(inst.channel.written) self.assertEqual(inst.wrote_header, True) def test_write_start_response_uncall...
256
256
3,591
10
246
flipmcf/waitress
tests/test_task.py
Python
TestWSGITask
TestWSGITask
376
840
376
376
dcff484bdf7f5042864ff98aac3cd21ff7e3bf98
bigcode/the-stack
train
e092503e75c414ca41030b43
train
class
class DummyLogger: def __init__(self): self.logged = [] def warning(self, msg, *args): self.logged.append(msg % args) def exception(self, msg, *args): self.logged.append(msg % args)
class DummyLogger:
def __init__(self): self.logged = [] def warning(self, msg, *args): self.logged.append(msg % args) def exception(self, msg, *args): self.logged.append(msg % args)
_scheme = "http" expect_continue = False headers_finished = False def __init__(self): self.headers = {} def get_body_stream(self): return "stream" def filter_lines(s): return list(filter(None, s.split(b"\r\n"))) class DummyLogger:
63
64
52
4
59
flipmcf/waitress
tests/test_task.py
Python
DummyLogger
DummyLogger
996
1,004
996
996
53ffd40d3ae0a45d308a1e08aa385016c125158a
bigcode/the-stack
train
789b9c39744583d373ab0ffa
train
class
class DummyTask: serviced = False cancelled = False def service(self): self.serviced = True def cancel(self): self.cancelled = True
class DummyTask:
serviced = False cancelled = False def service(self): self.serviced = True def cancel(self): self.cancelled = True
.assertTrue(lines[4]) self.assertEqual(lines[5], b"Server: waitress") self.assertEqual(lines[6], b"Too Ugly") self.assertEqual(lines[7], b"body") self.assertEqual(lines[8], b"(generated by waitress)") class DummyTask:
63
64
38
4
59
flipmcf/waitress
tests/test_task.py
Python
DummyTask
DummyTask
928
936
928
928
ac1f45f91a74527562eb6193d9f9bd937738639c
bigcode/the-stack
train
a90f7857a99c4f8fcd9a5fa8
train
class
class DummyParser: version = "1.0" command = "GET" path = "/" query = "" url_scheme = "http" expect_continue = False headers_finished = False def __init__(self): self.headers = {} def get_body_stream(self): return "stream"
class DummyParser:
version = "1.0" command = "GET" path = "/" query = "" url_scheme = "http" expect_continue = False headers_finished = False def __init__(self): self.headers = {} def get_body_stream(self): return "stream"
Server() self.server = server self.written = b"" self.otherdata = [] def write_soon(self, data): if isinstance(data, bytes): self.written += data else: self.otherdata.append(data) return len(data) class DummyParser:
64
64
70
4
60
flipmcf/waitress
tests/test_task.py
Python
DummyParser
DummyParser
976
989
976
976
b4cafcf615baadc0bcce23da19beff4dc9d6214a
bigcode/the-stack
train
1adb511a5548ee668be40868
train
class
class TestTask(unittest.TestCase): def _makeOne(self, channel=None, request=None): if channel is None: channel = DummyChannel() if request is None: request = DummyParser() from waitress.task import Task return Task(channel, request) def test_ctor_version...
class TestTask(unittest.TestCase):
def _makeOne(self, channel=None, request=None): if channel is None: channel = DummyChannel() if request is None: request = DummyParser() from waitress.task import Task return Task(channel, request) def test_ctor_version_not_in_known(self): reques...
.assertEqual(len(inst.queue_logger.logged), 0) def test_add_task_with_all_busy_threads(self): task = DummyTask() inst = self._makeOne() inst.queue_logger = DummyLogger() inst.add_task(task) self.assertEqual(len(inst.queue_logger.logged), 1) inst.add_task(task) ...
256
256
2,615
7
249
flipmcf/waitress
tests/test_task.py
Python
TestTask
TestTask
104
373
104
104
17373e793a72084233d4de3874f52702d37317c7
bigcode/the-stack
train
35305f6cce9cc512f5c7c9d6
train
class
class TestThreadedTaskDispatcher(unittest.TestCase): def _makeOne(self): from waitress.task import ThreadedTaskDispatcher return ThreadedTaskDispatcher() def test_handler_thread_task_raises(self): inst = self._makeOne() inst.threads.add(0) inst.logger = DummyLogger() ...
class TestThreadedTaskDispatcher(unittest.TestCase):
def _makeOne(self): from waitress.task import ThreadedTaskDispatcher return ThreadedTaskDispatcher() def test_handler_thread_task_raises(self): inst = self._makeOne() inst.threads.add(0) inst.logger = DummyLogger() class BadDummyTask(DummyTask): def...
import io import unittest class TestThreadedTaskDispatcher(unittest.TestCase):
16
215
717
10
5
flipmcf/waitress
tests/test_task.py
Python
TestThreadedTaskDispatcher
TestThreadedTaskDispatcher
5
101
5
5
e556b2e2e5dd57efed15b87e1172f3acfe732c23
bigcode/the-stack
train
f2d1eb829b5dca8750cb6c1c
train
class
class DummyAdj: log_socket_errors = True ident = "waitress" host = "127.0.0.1" port = 80 url_prefix = ""
class DummyAdj:
log_socket_errors = True ident = "waitress" host = "127.0.0.1" port = 80 url_prefix = ""
[7], b"body") self.assertEqual(lines[8], b"(generated by waitress)") class DummyTask: serviced = False cancelled = False def service(self): self.serviced = True def cancel(self): self.cancelled = True class DummyAdj:
64
64
41
4
59
flipmcf/waitress
tests/test_task.py
Python
DummyAdj
DummyAdj
939
944
939
939
beb4907b7c4296a09b7478f8ba6b6f58ac2a40a1
bigcode/the-stack
train
994486f9dc571a238339f0e8
train
class
class DummyChannel: closed_when_done = False adj = DummyAdj() creation_time = 0 addr = ("127.0.0.1", 39830) def __init__(self, server=None): if server is None: server = DummyServer() self.server = server self.written = b"" self.otherdata = [] def wri...
class DummyChannel:
closed_when_done = False adj = DummyAdj() creation_time = 0 addr = ("127.0.0.1", 39830) def __init__(self, server=None): if server is None: server = DummyServer() self.server = server self.written = b"" self.otherdata = [] def write_soon(self, data):...
waitress" host = "127.0.0.1" port = 80 url_prefix = "" class DummyServer: server_name = "localhost" effective_port = 80 def __init__(self): self.adj = DummyAdj() class DummyChannel:
64
64
120
4
60
flipmcf/waitress
tests/test_task.py
Python
DummyChannel
DummyChannel
955
973
955
955
248b3a30d87d180ddbfaee010ae394644cf0c95d
bigcode/the-stack
train
29c69a5f7c66d507f672bdbe
train
function
def filter_lines(s): return list(filter(None, s.split(b"\r\n")))
def filter_lines(s):
return list(filter(None, s.split(b"\r\n")))
" command = "GET" path = "/" query = "" url_scheme = "http" expect_continue = False headers_finished = False def __init__(self): self.headers = {} def get_body_stream(self): return "stream" def filter_lines(s):
64
64
18
5
59
flipmcf/waitress
tests/test_task.py
Python
filter_lines
filter_lines
992
993
992
992
24aa7a0f747f35143220235e1d0be81b197b8a99
bigcode/the-stack
train