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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
863542ac6b2826498826026b | train | function | def test_csv_serialise():
m = MockFile()
write_csv(
m,
{"f1": Field("f1", ""), "f2": Field("f2", '')},
[
{"f1": 12, "f2": NumericRange(1.0, 2.0)},
{"f1": datetime.datetime(2014, 7, 26, 23, 48, 0, tzinfo=tz.tzutc()), "f2": Range(-1.0, 2.0)},
{"f1": date... | def test_csv_serialise():
| m = MockFile()
write_csv(
m,
{"f1": Field("f1", ""), "f2": Field("f2", '')},
[
{"f1": 12, "f2": NumericRange(1.0, 2.0)},
{"f1": datetime.datetime(2014, 7, 26, 23, 48, 0, tzinfo=tz.tzutc()), "f2": Range(-1.0, 2.0)},
{"f1": datetime.datetime(2014, 7, 26,... | acube.scripts.search_tool import write_csv, write_pretty
class MockFile():
def __init__(self):
self.vals = []
def write(self, s):
self.vals.append(s)
def flush(self):
pass
def getvalue(self):
return ''.join(self.vals)
def test_csv_serialise():
| 73 | 73 | 245 | 6 | 67 | Kirill888/datacube-core | tests/scripts/test_search_tool.py | Python | test_csv_serialise | test_csv_serialise | 29 | 49 | 29 | 29 | e2133fb46b2f74769fef840fbd6685a64a4a5ad1 | bigcode/the-stack | train |
15db5d666f3ae2dd78069c5e | train | function | def test_pretty_serialise():
m = MockFile()
write_pretty(
m,
{"f1": Field("f1", ""), "field 2": Field("f2", '')},
[
{"f1": 12, "field 2": NumericRange(1.0, 2.0)},
{"f1": datetime.datetime(2014, 7, 26, 23, 48, 0, tzinfo=tz.tzutc()), "field 2": Range(-1.0, 2.0)},
... | def test_pretty_serialise():
| m = MockFile()
write_pretty(
m,
{"f1": Field("f1", ""), "field 2": Field("f2", '')},
[
{"f1": 12, "field 2": NumericRange(1.0, 2.0)},
{"f1": datetime.datetime(2014, 7, 26, 23, 48, 0, tzinfo=tz.tzutc()), "field 2": Range(-1.0, 2.0)},
{"f1": datetime.dat... | () == '\r\n'.join(
[
'f1,f2',
'12,1.0 to 2.0',
'2014-07-26T23:48:00+00:00,-1.0 to 2.0',
'2014-07-26T23:48:00+00:00,landsat',
''
]
)
def test_pretty_serialise():
| 93 | 93 | 311 | 7 | 86 | Kirill888/datacube-core | tests/scripts/test_search_tool.py | Python | test_pretty_serialise | test_pretty_serialise | 52 | 78 | 52 | 52 | d12e7ea992e47278ef6b40375e12b975c00ff722 | bigcode/the-stack | train |
c7721abcce53549cf9b7ed59 | train | class | class MockFile():
def __init__(self):
self.vals = []
def write(self, s):
self.vals.append(s)
def flush(self):
pass
def getvalue(self):
return ''.join(self.vals)
| class MockFile():
| def __init__(self):
self.vals = []
def write(self, s):
self.vals.append(s)
def flush(self):
pass
def getvalue(self):
return ''.join(self.vals)
| # coding=utf-8
"""
Module
"""
import datetime
from dateutil import tz
from psycopg2._range import Range, NumericRange
from datacube.index.fields import Field
from datacube.scripts.search_tool import write_csv, write_pretty
class MockFile():
| 61 | 64 | 53 | 4 | 56 | Kirill888/datacube-core | tests/scripts/test_search_tool.py | Python | MockFile | MockFile | 15 | 26 | 15 | 15 | c233e796c45e44b926ffea0096cbc1431ab22fd8 | bigcode/the-stack | train |
5bf6925420ed5281a9771751 | train | class | class SampleInput(unittest.TestCase):
'''Problem statement sample inputs and outputs'''
def test_sample_input_1(self):
'''Run and assert problem statement sample 1 input and output.'''
inputs = '3\n'
outputs = '2.666666666666667\n'
with patch('sys.stdin', io.StringIO(inputs)) a... | class SampleInput(unittest.TestCase):
| '''Problem statement sample inputs and outputs'''
def test_sample_input_1(self):
'''Run and assert problem statement sample 1 input and output.'''
inputs = '3\n'
outputs = '2.666666666666667\n'
with patch('sys.stdin', io.StringIO(inputs)) as stdin,\
patch('sys.stdo... | import io
import unittest
from unittest.mock import patch
from kattis import k_eulersnumber
###############################################################################
class SampleInput(unittest.TestCase):
| 30 | 65 | 217 | 7 | 23 | ivanlyon/exercises | test/test_k_eulersnumber.py | Python | SampleInput | SampleInput | 8 | 31 | 8 | 8 | 6f82e5e40eef773ec185fe62293910c4499be3d5 | bigcode/the-stack | train |
e867e3ef347c54ba1f2fa5e9 | train | function | @app.route('/')
def hello_world():
return 'Hello, World!'
| @app.route('/')
def hello_world():
| return 'Hello, World!'
| from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
| 18 | 64 | 14 | 7 | 11 | vguhesan/python-hello-world-with-unit-test | src/sample_flask_app.py | Python | hello_world | hello_world | 4 | 6 | 4 | 5 | 63b2c167c789306da2c759ea26643828bec2b2e4 | bigcode/the-stack | train |
af8f71d79cd050dc49c9779c | train | class | class OlfaEditorDialog(QDialog, Ui_Dialog):
def __init__(self, olfaConfigFileName=None, parent=None):
super().__init__()
self.setupUi(self)
self.olfaConfigFile = olfaConfigFileName
if self.olfaConfigFile:
with open(self.olfaConfigFile, 'r') as olfa_config:
... | class OlfaEditorDialog(QDialog, Ui_Dialog):
| def __init__(self, olfaConfigFileName=None, parent=None):
super().__init__()
self.setupUi(self)
self.olfaConfigFile = olfaConfigFileName
if self.olfaConfigFile:
with open(self.olfaConfigFile, 'r') as olfa_config:
self.olfaConfigDict = json.load(olfa_confi... | import json
import logging
from PyQt5.QtWidgets import QDialog, QMessageBox, QFileDialog, QDialogButtonBox
from ui_files.olfa_editor_dialog_ui import Ui_Dialog
logging.basicConfig(format="%(message)s", level=logging.INFO)
class OlfaEditorDialog(QDialog, Ui_Dialog):
| 65 | 256 | 15,087 | 12 | 53 | mohamedelgohary1/PyBpodGUI | olfaEditorDialog.py | Python | OlfaEditorDialog | OlfaEditorDialog | 10 | 804 | 10 | 11 | 5b63a7677b95ef0b57fd5cd2042f35a9e6c40504 | bigcode/the-stack | train |
34220cf94b0be759ac4cdb6a | train | class | class TestDatastoreUpdate(tests.WsgiAppCase):
sysadmin_user = None
normal_user = None
p.load('datastore')
@classmethod
def setup_class(cls):
if not tests.is_datastore_supported():
raise nose.SkipTest("Datastore not supported")
p.load('datastore')
ctd.CreateTestDa... | class TestDatastoreUpdate(tests.WsgiAppCase):
| sysadmin_user = None
normal_user = None
p.load('datastore')
@classmethod
def setup_class(cls):
if not tests.is_datastore_supported():
raise nose.SkipTest("Datastore not supported")
p.load('datastore')
ctd.CreateTestData.create()
cls.sysadmin_user = model.... | =postparams,
extra_environ=auth, status=409)
res_dict = json.loads(res.body)
assert res_dict['success'] is False
def test_insert_basic(self):
hhguide = u"hitchhiker's guide to the galaxy"
data = {
'resource_id': self.data['resource_id'],
... | 256 | 256 | 1,631 | 12 | 243 | SpazioDati/ckan | ckanext/datastore/tests/test_upsert.py | Python | TestDatastoreUpdate | TestDatastoreUpdate | 345 | 528 | 345 | 345 | c2de17b1a7a25743fcbf19bbbc799751d18893fe | bigcode/the-stack | train |
47ed70e9bde665ecce037336 | train | class | class TestDatastoreInsert(tests.WsgiAppCase):
sysadmin_user = None
normal_user = None
p.load('datastore')
@classmethod
def setup_class(cls):
if not tests.is_datastore_supported():
raise nose.SkipTest("Datastore not supported")
p.load('datastore')
ctd.CreateTestDa... | class TestDatastoreInsert(tests.WsgiAppCase):
| sysadmin_user = None
normal_user = None
p.load('datastore')
@classmethod
def setup_class(cls):
if not tests.is_datastore_supported():
raise nose.SkipTest("Datastore not supported")
p.load('datastore')
ctd.CreateTestData.create()
cls.sysadmin_user = model.... | resource_id': self.data['resource_id'],
'method': 'upsert',
'records': [{'author': 'tolkien'}]
}
postparams = '%s=1' % json.dumps(data)
auth = {'Authorization': str(self.sysadmin_user.apikey)}
res = self.app.post('/api/action/datastore_upsert', params=postparams,... | 256 | 256 | 902 | 12 | 243 | SpazioDati/ckan | ckanext/datastore/tests/test_upsert.py | Python | TestDatastoreInsert | TestDatastoreInsert | 242 | 342 | 242 | 242 | 5911720a738e1d78dbc6d83e3f654f1da7c60d9b | bigcode/the-stack | train |
375050d0dd1693134f46d73f | train | class | class TestDatastoreUpsert(tests.WsgiAppCase):
sysadmin_user = None
normal_user = None
p.load('datastore')
@classmethod
def setup_class(cls):
if not tests.is_datastore_supported():
raise nose.SkipTest("Datastore not supported")
p.load('datastore')
ctd.CreateTestDa... | class TestDatastoreUpsert(tests.WsgiAppCase):
| sysadmin_user = None
normal_user = None
p.load('datastore')
@classmethod
def setup_class(cls):
if not tests.is_datastore_supported():
raise nose.SkipTest("Datastore not supported")
p.load('datastore')
ctd.CreateTestData.create()
cls.sysadmin_user = model.... | import json
import nose
import datetime
import sqlalchemy.orm as orm
import ckan.plugins as p
import ckan.lib.create_test_data as ctd
import ckan.model as model
import ckan.tests as tests
import ckanext.datastore.db as db
from ckanext.datastore.tests.helpers import rebuild_all_dbs
class TestDatastoreUpsert(tests.Wsg... | 84 | 256 | 2,001 | 13 | 70 | SpazioDati/ckan | ckanext/datastore/tests/test_upsert.py | Python | TestDatastoreUpsert | TestDatastoreUpsert | 16 | 239 | 16 | 16 | c89ad9dfe70fb7efd4c0615b9a47cef4fa6afc4f | bigcode/the-stack | train |
0eacc109ad23e5466fd6ce01 | train | class | class PointNetCls(nn.Module):
def __init__(self, k = 2):
super(PointNetCls, self).__init__()
self.feat = PointNetfeat(global_feat=True)
self.fc1 = nn.Linear(1024, 512)
self.fc2 = nn.Linear(512, 256)
self.fc3 = nn.Linear(256, k)
self.bn1 = nn.BatchNorm1d(512)
s... | class PointNetCls(nn.Module):
| def __init__(self, k = 2):
super(PointNetCls, self).__init__()
self.feat = PointNetfeat(global_feat=True)
self.fc1 = nn.Linear(1024, 512)
self.fc2 = nn.Linear(512, 256)
self.fc3 = nn.Linear(256, k)
self.bn1 = nn.BatchNorm1d(512)
self.bn2 = nn.BatchNorm1d(256)
... | 4)
if self.global_feat:
return x, trans
else:
x = x.view(-1, 1024, 1).repeat(1, 1, n_pts)
return torch.cat([x, pointfeat], 1), trans
class PointNetCls(nn.Module):
| 64 | 64 | 179 | 7 | 56 | jiangwei221/pointnet.pytorch | pointnet.py | Python | PointNetCls | PointNetCls | 108 | 123 | 108 | 108 | 4af764ee65a432084ba73a203aef6f008e3d16e4 | bigcode/the-stack | train |
2f94fecabe4b01596facff9a | train | class | class STN3d(nn.Module):
def __init__(self):
super(STN3d, self).__init__()
self.conv1 = torch.nn.Conv1d(3, 64, 1)
self.conv2 = torch.nn.Conv1d(64, 128, 1)
self.conv3 = torch.nn.Conv1d(128, 1024, 1)
self.fc1 = nn.Linear(1024, 512)
self.fc2 = nn.Linear(512, 256)
... | class STN3d(nn.Module):
| def __init__(self):
super(STN3d, self).__init__()
self.conv1 = torch.nn.Conv1d(3, 64, 1)
self.conv2 = torch.nn.Conv1d(64, 128, 1)
self.conv3 = torch.nn.Conv1d(128, 1024, 1)
self.fc1 = nn.Linear(1024, 512)
self.fc2 = nn.Linear(512, 256)
self.fc3 = nn.Linear(256... | from __future__ import print_function
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.utils as vutils
from torch.aut... | 106 | 120 | 401 | 8 | 97 | jiangwei221/pointnet.pytorch | pointnet.py | Python | STN3d | STN3d | 21 | 56 | 21 | 21 | 34166a41b05637bb2e4c9a80027e928e201adfec | bigcode/the-stack | train |
a15068bf2c76ceb3a9e809ee | train | class | class PointNetDenseCls(nn.Module):
def __init__(self, k = 2):
super(PointNetDenseCls, self).__init__()
self.k = k
self.feat = PointNetfeat(global_feat=False)
self.conv1 = torch.nn.Conv1d(1088, 512, 1)
self.conv2 = torch.nn.Conv1d(512, 256, 1)
self.conv3 = torch.nn.Con... | class PointNetDenseCls(nn.Module):
| def __init__(self, k = 2):
super(PointNetDenseCls, self).__init__()
self.k = k
self.feat = PointNetfeat(global_feat=False)
self.conv1 = torch.nn.Conv1d(1088, 512, 1)
self.conv2 = torch.nn.Conv1d(512, 256, 1)
self.conv3 = torch.nn.Conv1d(256, 128, 1)
self.conv4... | nn.BatchNorm1d(256)
self.relu = nn.ReLU()
def forward(self, x):
x, trans = self.feat(x)
x = F.relu(self.bn1(self.fc1(x)))
x = F.relu(self.bn2(self.fc2(x)))
x = self.fc3(x)
return F.log_softmax(x, dim=0), trans
class PointNetDenseCls(nn.Module):
| 89 | 89 | 298 | 8 | 80 | jiangwei221/pointnet.pytorch | pointnet.py | Python | PointNetDenseCls | PointNetDenseCls | 125 | 149 | 125 | 125 | 101f5dd9e507dbe5a2b0eb31149aca0eeabeadc0 | bigcode/the-stack | train |
6ad8c212fde68847ed634024 | train | class | class PointNetfeat(nn.Module):
def __init__(self, global_feat = True):
super(PointNetfeat, self).__init__()
self.stn = STN3d()
self.conv1 = torch.nn.Conv1d(3, 64, 1)
self.conv2 = torch.nn.Conv1d(64, 128, 1)
self.conv3 = torch.nn.Conv1d(128, 1024, 1)
self.bn1 = nn.Batc... | class PointNetfeat(nn.Module):
| def __init__(self, global_feat = True):
super(PointNetfeat, self).__init__()
self.stn = STN3d()
self.conv1 = torch.nn.Conv1d(3, 64, 1)
self.conv2 = torch.nn.Conv1d(64, 128, 1)
self.conv3 = torch.nn.Conv1d(128, 1024, 1)
self.bn1 = nn.BatchNorm1d(64)
self.bn2 = ... | = torch.max(x, 2, keepdim=True)[0]
x = x.view(-1, 1024)
x = F.relu(self.bn4(self.fc1(x)))
x = F.relu(self.bn5(self.fc2(x)))
x = self.fc3(x)
iden = Variable(torch.from_numpy(np.array([1,0,0,0,1,0,0,0,1]).astype(np.float32))).view(1,9).repeat(batchsize,1)
if x.is_cuda:
... | 153 | 153 | 511 | 7 | 145 | jiangwei221/pointnet.pytorch | pointnet.py | Python | PointNetfeat | PointNetfeat | 59 | 106 | 59 | 59 | b6b72b7def09add9f82e697432dc62cc891238ff | bigcode/the-stack | train |
b8629a4e7c0638fd871b28bd | train | function | @app.route('/select', methods=['post'])
def select():
req = request.json
table = req['table']
where = req['where']
query = QueryBuilder.build_query(where)
sql = f"SELECT * FROM {table} WHERE ({query['query']})"
with SimpleMySQL() as cur:
cur.execute(sql, query['params'])
return ... | @app.route('/select', methods=['post'])
def select():
| req = request.json
table = req['table']
where = req['where']
query = QueryBuilder.build_query(where)
sql = f"SELECT * FROM {table} WHERE ({query['query']})"
with SimpleMySQL() as cur:
cur.execute(sql, query['params'])
return jsonify(cur.fetchall())
| * from {table} {where_str}")
cur.execute(sql, query['params'])
result = cur.fetchall()
sql = f"DELETE FROM {table} {where_str}"
cur.execute(sql, query['params'])
return jsonify(result)
@app.route('/select', methods=['post'])
def select():
| 64 | 64 | 84 | 12 | 52 | ht68rohit/mysql | app.py | Python | select | select | 192 | 202 | 192 | 193 | c78b09c68fe41b345f541065a5a1acd8ed223216 | bigcode/the-stack | train |
2ee836ef749f754e47f9db5a | train | class | class SimpleMySQL:
"""
Provides a cursor to a connection to a MySQL instance
in a 'with' context.
"""
def __enter__(self):
"""
Starts a connection to a MySQL instance
"""
self.conn = MySQLdb.connect(
host=os.environ.get("MYSQL_HOST"),
user=os.... | class SimpleMySQL:
| """
Provides a cursor to a connection to a MySQL instance
in a 'with' context.
"""
def __enter__(self):
"""
Starts a connection to a MySQL instance
"""
self.conn = MySQLdb.connect(
host=os.environ.get("MYSQL_HOST"),
user=os.environ.get("MYSQL_... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import traceback
import json
from flask import Flask, jsonify, request
import MySQLdb
app = Flask(__name__)
class SimpleMySQL:
| 48 | 64 | 214 | 5 | 43 | ht68rohit/mysql | app.py | Python | SimpleMySQL | SimpleMySQL | 13 | 44 | 13 | 13 | e1b34b1ff184910132d5b3d2fa223e278dfe616d | bigcode/the-stack | train |
009de83c7eb94eacd390a320 | train | function | @app.route('/health', methods=['GET'])
def health():
return jsonify({'message': 'ok'}), 200
| @app.route('/health', methods=['GET'])
def health():
| return jsonify({'message': 'ok'}), 200
| {table} ({columns_str})"
with SimpleMySQL() as cur:
cur.execute(sql)
return jsonify({})
def app_error(e):
print(traceback.format_exc())
return jsonify({'message': repr(e)}), 400
@app.route('/health', methods=['GET'])
def health():
| 64 | 64 | 25 | 12 | 51 | ht68rohit/mysql | app.py | Python | health | health | 263 | 265 | 263 | 264 | 3feada24fb7145516ab72888c99d97e835018000 | bigcode/the-stack | train |
d835b98c8da10ed94fb6a485 | train | class | class InsertBuilder:
"""
Builds an insert query string for one or more insert instructions
"""
def __init__(self):
self.params = []
self.value_strs = []
self.first_item = None
def add(self, values):
values = json.loads(values)
items = sorted(values.items())... | class InsertBuilder:
| """
Builds an insert query string for one or more insert instructions
"""
def __init__(self):
self.params = []
self.value_strs = []
self.first_item = None
def add(self, values):
values = json.loads(values)
items = sorted(values.items())
# save the f... | self.conn.close()
@app.route('/execute', methods=['post'])
def execute():
req = request.json
query = req['query']
args = req.get('data', {})
with SimpleMySQL() as cur:
cur.execute(query, args)
return jsonify(cur.fetchall())
class InsertBuilder:
| 64 | 64 | 170 | 4 | 60 | ht68rohit/mysql | app.py | Python | InsertBuilder | InsertBuilder | 57 | 82 | 57 | 57 | fe1f00fbf5fb35f0ed2370f0aeb8ac8767cb2326 | bigcode/the-stack | train |
ce62b8b8625464536620cca5 | train | function | @app.route('/tables/drop', methods=['post'])
def tables_drop():
req = request.json
table = req['table']
sql = f"DROP TABLE {table}"
with SimpleMySQL() as cur:
cur.execute(sql)
return jsonify([])
| @app.route('/tables/drop', methods=['post'])
def tables_drop():
| req = request.json
table = req['table']
sql = f"DROP TABLE {table}"
with SimpleMySQL() as cur:
cur.execute(sql)
return jsonify([])
| cur:
cur.execute(sql, update_params)
# MySQL doesn't support RETURNING
sql = (f"SELECT * from {table} {where_str}")
cur.execute(sql, query['params'])
return jsonify(cur.fetchall())
@app.route('/tables/drop', methods=['post'])
def tables_drop():
| 64 | 64 | 55 | 14 | 50 | ht68rohit/mysql | app.py | Python | tables_drop | tables_drop | 230 | 238 | 230 | 231 | dd89c00adc6370388778d9fa6e6b65fad781a927 | bigcode/the-stack | train |
3bff99f8b758ae13f6aa4031 | train | function | @app.route('/execute', methods=['post'])
def execute():
req = request.json
query = req['query']
args = req.get('data', {})
with SimpleMySQL() as cur:
cur.execute(query, args)
return jsonify(cur.fetchall())
| @app.route('/execute', methods=['post'])
def execute():
| req = request.json
query = req['query']
args = req.get('data', {})
with SimpleMySQL() as cur:
cur.execute(query, args)
return jsonify(cur.fetchall())
| raise
# the exceptions.
# However, we need to make sure that all connections and cursors
# are properly closed
except Exception as e:
raise e
finally:
self.cursor.close()
self.conn.close()
@app.route('/execute', methods=['post'])
def execute():... | 64 | 64 | 56 | 12 | 52 | ht68rohit/mysql | app.py | Python | execute | execute | 47 | 54 | 47 | 48 | 0ca3771d0c0147139641ceb490a21b54925ca827 | bigcode/the-stack | train |
a658f95db7f53acbfffd05eb | train | function | def app_error(e):
print(traceback.format_exc())
return jsonify({'message': repr(e)}), 400
| def app_error(e):
| print(traceback.format_exc())
return jsonify({'message': repr(e)}), 400
| .items()):
columns_params.append(f"{k} {str(v)}")
columns_str = ','.join(columns_params)
sql = f"CREATE TABLE {table} ({columns_str})"
with SimpleMySQL() as cur:
cur.execute(sql)
return jsonify({})
def app_error(e):
| 63 | 64 | 25 | 5 | 59 | ht68rohit/mysql | app.py | Python | app_error | app_error | 258 | 260 | 258 | 258 | 7e0bf4b17e02c3055836bb2574a6626ac0131a3a | bigcode/the-stack | train |
9b60e69d48ee910f3b96016c | train | function | @app.route('/update', methods=['post'])
def update():
req = request.json
table = req['table']
where = req.get('where', {})
values = sorted(req['values'].items())
update_params = list(map(lambda x: x[1], values))
update_str = ','.join(map(lambda x: f'{x[0]} = %s', values))
# use an optional ... | @app.route('/update', methods=['post'])
def update():
| req = request.json
table = req['table']
where = req.get('where', {})
values = sorted(req['values'].items())
update_params = list(map(lambda x: x[1], values))
update_str = ','.join(map(lambda x: f'{x[0]} = %s', values))
# use an optional select string
query = QueryBuilder.build_query(whe... | query = QueryBuilder.build_query(where)
sql = f"SELECT * FROM {table} WHERE ({query['query']})"
with SimpleMySQL() as cur:
cur.execute(sql, query['params'])
return jsonify(cur.fetchall())
@app.route('/update', methods=['post'])
def update():
| 64 | 64 | 213 | 12 | 52 | ht68rohit/mysql | app.py | Python | update | update | 205 | 227 | 205 | 206 | 7648f16defd1d62a7c75197db8beb37fe14be0c3 | bigcode/the-stack | train |
dd25d1d84e6b137333f26415 | train | function | @app.route('/insert', methods=['post'])
def insert():
builder = InsertBuilder()
req = request.json
table = req['table']
values = req['values']
# allow one or multiple insert entries
if isinstance(values, list):
for e in values:
builder.add(e)
else:
builder.add(val... | @app.route('/insert', methods=['post'])
def insert():
| builder = InsertBuilder()
req = request.json
table = req['table']
values = req['values']
# allow one or multiple insert entries
if isinstance(values, list):
for e in values:
builder.add(e)
else:
builder.add(values)
sql = (f"INSERT INTO {table} ({builder.names(... | join(map(lambda x: '%s', values))})")
def names(self):
return ','.join(map(lambda x: f'{x[0]}', self.first_item))
def values(self):
return ','.join(self.value_strs)
@app.route('/insert', methods=['post'])
def insert():
| 64 | 64 | 195 | 12 | 52 | ht68rohit/mysql | app.py | Python | insert | insert | 85 | 109 | 85 | 86 | 58d8d983e133f4e076b25bc679342b14cee8a569 | bigcode/the-stack | train |
23e280b2178c5c9943eacf02 | train | function | @app.route('/tables/create', methods=['post'])
def tables_create():
req = request.json
table = req['table']
columns = req['columns']
columns_params = []
for k, v in sorted(columns.items()):
columns_params.append(f"{k} {str(v)}")
columns_str = ','.join(columns_params)
sql = f"CREATE... | @app.route('/tables/create', methods=['post'])
def tables_create():
| req = request.json
table = req['table']
columns = req['columns']
columns_params = []
for k, v in sorted(columns.items()):
columns_params.append(f"{k} {str(v)}")
columns_str = ','.join(columns_params)
sql = f"CREATE TABLE {table} ({columns_str})"
with SimpleMySQL() as cur:
... | methods=['post'])
def tables_drop():
req = request.json
table = req['table']
sql = f"DROP TABLE {table}"
with SimpleMySQL() as cur:
cur.execute(sql)
return jsonify([])
@app.route('/tables/create', methods=['post'])
def tables_create():
| 63 | 64 | 105 | 14 | 50 | ht68rohit/mysql | app.py | Python | tables_create | tables_create | 241 | 255 | 241 | 242 | d6137491cd2c5d84197530ae09cd02c3f8f8e18f | bigcode/the-stack | train |
b7b7d1036881f5360069ccc8 | train | function | @app.route('/delete', methods=['post'])
def delete():
req = request.json
table = req['table']
where = req['where']
query = QueryBuilder.build_query(where)
where_str = ""
if len(query['query']) > 0:
where_str = f"WHERE ({query['query']}) "
with SimpleMySQL() as cur:
# MySQL d... | @app.route('/delete', methods=['post'])
def delete():
| req = request.json
table = req['table']
where = req['where']
query = QueryBuilder.build_query(where)
where_str = ""
if len(query['query']) > 0:
where_str = f"WHERE ({query['query']}) "
with SimpleMySQL() as cur:
# MySQL doesn't support RETURNING, so fetch the rows before rem... | .params.append(v)
return query
@staticmethod
def build_query(where):
builder = QueryBuilder()
query = builder.group(where, 'AND')
return {
'query': query,
'params': builder.params
}
@app.route('/delete', methods=['post'])
def delete():
| 64 | 64 | 155 | 12 | 52 | ht68rohit/mysql | app.py | Python | delete | delete | 172 | 189 | 172 | 173 | 5a8a6d45568829cafe2dc91146cd6256a074e3d0 | bigcode/the-stack | train |
d54e3ad699edab5a0b9d20e7 | train | class | class QueryBuilder:
"""
Builds a simple select query string
"""
operators = {
"$gt": ">",
"$gte": ">=",
"$lt": "<",
"$lte": "<=",
"$eq": "=",
}
def __init__(self):
self.params = []
self.current_column = None
def group(self, value, ac... | class QueryBuilder:
| """
Builds a simple select query string
"""
operators = {
"$gt": ">",
"$gte": ">=",
"$lt": "<",
"$lte": "<=",
"$eq": "=",
}
def __init__(self):
self.params = []
self.current_column = None
def group(self, value, action):
query... | "VALUES {builder.values()}")
with SimpleMySQL() as cur:
cur.execute(sql, builder.params)
# MySQL doesn't support RETURNING
sql = (f"SELECT * from {table} WHERE id "
f"BETWEEN {cur.lastrowid} AND "
f"{cur.lastrowid + cur.rowcount - 1}")
cur.execute(sql)
... | 107 | 107 | 357 | 4 | 103 | ht68rohit/mysql | app.py | Python | QueryBuilder | QueryBuilder | 112 | 169 | 112 | 112 | fd630f5efcf9e1083f8174f667c1f3d752a20fd0 | bigcode/the-stack | train |
14e1769cd7325b825ddce610 | train | function | def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'moscow_places.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's ins... | def main():
| """Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'moscow_places.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "... | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
| 26 | 64 | 100 | 3 | 22 | stasyao/dvmn | manage.py | Python | main | main | 7 | 18 | 7 | 7 | 1a6c6392b8e84a1222b8c6e0028a6f09ac56acf0 | bigcode/the-stack | train |
51a89f5228d8d7648a89be9e | train | function | def cross_entropy(pred, label, weight=None, reduction='mean', avg_factor=None):
"""Calculate the CrossEntropy loss.
Args:
pred (torch.Tensor): The prediction with shape (N, C), C is the number
of classes.
label (torch.Tensor): The gt label of the prediction.
weight (torch.Te... | def cross_entropy(pred, label, weight=None, reduction='mean', avg_factor=None):
| """Calculate the CrossEntropy loss.
Args:
pred (torch.Tensor): The prediction with shape (N, C), C is the number
of classes.
label (torch.Tensor): The gt label of the prediction.
weight (torch.Tensor, optional): Sample-wise loss weight.
reduction (str): The method us... | import torch.nn as nn
import torch.nn.functional as F
from ..builder import LOSSES
from .utils import weight_reduce_loss
def cross_entropy(pred, label, weight=None, reduction='mean', avg_factor=None):
| 46 | 64 | 199 | 18 | 27 | agim-a/mmclassification | mmcls/models/losses/cross_entropy_loss.py | Python | cross_entropy | cross_entropy | 8 | 32 | 8 | 8 | f7ac275cea994cd5802d9f8b9a0fe5c778b93759 | bigcode/the-stack | train |
af0834944b36de5917793dc8 | train | function | def binary_cross_entropy(pred,
label,
weight=None,
reduction='mean',
avg_factor=None):
"""Calculate the binary CrossEntropy loss with logits.
Args:
pred (torch.Tensor): The prediction with shape (N, *).
... | def binary_cross_entropy(pred,
label,
weight=None,
reduction='mean',
avg_factor=None):
| """Calculate the binary CrossEntropy loss with logits.
Args:
pred (torch.Tensor): The prediction with shape (N, *).
label (torch.Tensor): The gt label with shape (N, *).
weight (torch.Tensor, optional): Element-wise weight of loss with shape
(N, ). Defaults to None.
... | label * F.log_softmax(pred, dim=-1)
# apply weights and do the reduction
if weight is not None:
weight = weight.float()
loss = weight_reduce_loss(
loss, weight=weight, reduction=reduction, avg_factor=avg_factor)
return loss
def binary_cross_entropy(pred,
label,... | 85 | 85 | 284 | 23 | 61 | agim-a/mmclassification | mmcls/models/losses/cross_entropy_loss.py | Python | binary_cross_entropy | binary_cross_entropy | 67 | 100 | 67 | 71 | d646c0594acfba69a3e606ebe9ad2cf3ff744e48 | bigcode/the-stack | train |
bfb4dd7d075db0950edfea40 | train | class | @LOSSES.register_module()
class CrossEntropyLoss(nn.Module):
"""Cross entropy loss
Args:
use_sigmoid (bool): Whether the prediction uses sigmoid
of softmax. Defaults to False.
use_soft (bool): Whether to use the soft version of CrossEntropyLoss.
Defaults to False.
... | @LOSSES.register_module()
class CrossEntropyLoss(nn.Module):
| """Cross entropy loss
Args:
use_sigmoid (bool): Whether the prediction uses sigmoid
of softmax. Defaults to False.
use_soft (bool): Whether to use the soft version of CrossEntropyLoss.
Defaults to False.
reduction (str): The method used to reduce the loss.
... | .dim()
loss = F.binary_cross_entropy_with_logits(pred, label, reduction='none')
# apply weights and do the reduction
if weight is not None:
assert weight.dim() == 1
weight = weight.float()
if pred.dim() > 1:
weight = weight.reshape(-1, 1)
loss = weight_reduce_loss(
... | 111 | 111 | 373 | 13 | 97 | agim-a/mmclassification | mmcls/models/losses/cross_entropy_loss.py | Python | CrossEntropyLoss | CrossEntropyLoss | 103 | 156 | 103 | 104 | 8b401f8da035f1cf11e233083b3025022809aa25 | bigcode/the-stack | train |
9be9faa8e33715e2c4fb54cc | train | function | def soft_cross_entropy(pred,
label,
weight=None,
reduction='mean',
avg_factor=None):
"""Calculate the Soft CrossEntropy loss. The label can be float.
Args:
pred (torch.Tensor): The prediction with shape (N, C), ... | def soft_cross_entropy(pred,
label,
weight=None,
reduction='mean',
avg_factor=None):
| """Calculate the Soft CrossEntropy loss. The label can be float.
Args:
pred (torch.Tensor): The prediction with shape (N, C), C is the number
of classes.
label (torch.Tensor): The gt label of the prediction with shape (N, C).
When using "mixup", the label can be float.
... | and do the reduction
if weight is not None:
weight = weight.float()
loss = weight_reduce_loss(
loss, weight=weight, reduction=reduction, avg_factor=avg_factor)
return loss
def soft_cross_entropy(pred,
label,
weight=None,
... | 69 | 69 | 232 | 23 | 45 | agim-a/mmclassification | mmcls/models/losses/cross_entropy_loss.py | Python | soft_cross_entropy | soft_cross_entropy | 35 | 64 | 35 | 39 | c349b1749cb08efded799897bf5a0e2239aa094c | bigcode/the-stack | train |
86cb59196d22b17916c590f1 | train | class | class TestCmdImport(TestDvc):
def test(self):
ret = main(["import-url", self.FOO, "import"])
self.assertEqual(ret, 0)
self.assertTrue(os.path.exists("import.dvc"))
ret = main(["import-url", "non-existing-file", "import"])
self.assertNotEqual(ret, 0)
def test_unsupported... | class TestCmdImport(TestDvc):
| def test(self):
ret = main(["import-url", self.FOO, "import"])
self.assertEqual(ret, 0)
self.assertTrue(os.path.exists("import.dvc"))
ret = main(["import-url", "non-existing-file", "import"])
self.assertNotEqual(ret, 0)
def test_unsupported(self):
ret = main(["i... | import filecmp
import os
from uuid import uuid4
import pytest
from mock import patch
import dvc
from dvc.main import main
from dvc.utils import makedirs
from tests.basic_env import TestDvc
from tests.utils import spy
class TestCmdImport(TestDvc):
| 64 | 64 | 110 | 8 | 55 | kacmak7/dvc | tests/func/test_import_url.py | Python | TestCmdImport | TestCmdImport | 15 | 26 | 15 | 15 | c7227f3ee146f6a7487c2df6ef78b933c10b28bf | bigcode/the-stack | train |
6c310a6fdf4f1c6389b65c80 | train | class | class TestDefaultOutput(TestDvc):
def test(self):
tmpdir = self.mkdtemp()
filename = str(uuid4())
tmpfile = os.path.join(tmpdir, filename)
with open(tmpfile, "w") as fd:
fd.write("content")
ret = main(["import-url", tmpfile])
self.assertEqual(ret, 0)
... | class TestDefaultOutput(TestDvc):
| def test(self):
tmpdir = self.mkdtemp()
filename = str(uuid4())
tmpfile = os.path.join(tmpdir, filename)
with open(tmpfile, "w") as fd:
fd.write("content")
ret = main(["import-url", tmpfile])
self.assertEqual(ret, 0)
self.assertTrue(os.path.exist... | import-url", "non-existing-file", "import"])
self.assertNotEqual(ret, 0)
def test_unsupported(self):
ret = main(["import-url", "unsupported://path", "import_unsupported"])
self.assertNotEqual(ret, 0)
class TestDefaultOutput(TestDvc):
| 64 | 64 | 106 | 8 | 56 | kacmak7/dvc | tests/func/test_import_url.py | Python | TestDefaultOutput | TestDefaultOutput | 29 | 42 | 29 | 29 | 37ef4a946243a1ba6e63d71e34ace3cd19e4c50f | bigcode/the-stack | train |
212c06071b93aeaf9dcf97e0 | train | class | class TestImportFilename(TestDvc):
def setUp(self):
super().setUp()
tmp_dir = self.mkdtemp()
self.external_source = os.path.join(tmp_dir, "file")
with open(self.external_source, "w") as fobj:
fobj.write("content")
def test(self):
ret = main(["import-url", "-f... | class TestImportFilename(TestDvc):
| def setUp(self):
super().setUp()
tmp_dir = self.mkdtemp()
self.external_source = os.path.join(tmp_dir, "file")
with open(self.external_source, "w") as fobj:
fobj.write("content")
def test(self):
ret = main(["import-url", "-f", "bar.dvc", self.external_source]... | .object(
dvc.stage.Stage, "remove_outs", remove_outs_call_counter
):
ret = main(["import-url", self.external_source])
self.assertEqual(0, ret)
self.assertEqual(1, remove_outs_call_counter.mock.call_count)
class TestImportFilename(TestDvc):
| 66 | 66 | 222 | 8 | 58 | kacmak7/dvc | tests/func/test_import_url.py | Python | TestImportFilename | TestImportFilename | 64 | 89 | 64 | 64 | 46b7937e31c12af9d2aca277f66bb4a975d8ff29 | bigcode/the-stack | train |
02783bdd73c8b8391df4cacc | train | function | @pytest.mark.parametrize("dname", [".", "dir", "dir/subdir"])
def test_import_url_to_dir(dname, repo_dir, dvc_repo):
src = repo_dir.DATA
makedirs(dname, exist_ok=True)
stage = dvc_repo.imp_url(src, dname)
dst = os.path.join(dname, os.path.basename(src))
assert stage.outs[0].fspath == os.path.abs... | @pytest.mark.parametrize("dname", [".", "dir", "dir/subdir"])
def test_import_url_to_dir(dname, repo_dir, dvc_repo):
| src = repo_dir.DATA
makedirs(dname, exist_ok=True)
stage = dvc_repo.imp_url(src, dname)
dst = os.path.join(dname, os.path.basename(src))
assert stage.outs[0].fspath == os.path.abspath(dst)
assert os.path.isdir(dname)
assert filecmp.cmp(repo_dir.DATA, dst, shallow=False)
| import-url", "--file", path, self.external_source])
self.assertEqual(0, ret)
self.assertTrue(os.path.exists(path))
@pytest.mark.parametrize("dname", [".", "dir", "dir/subdir"])
def test_import_url_to_dir(dname, repo_dir, dvc_repo):
| 64 | 64 | 118 | 34 | 30 | kacmak7/dvc | tests/func/test_import_url.py | Python | test_import_url_to_dir | test_import_url_to_dir | 92 | 104 | 92 | 93 | c493952986d194341b8dff2ce040b4a716d17502 | bigcode/the-stack | train |
a1312e7c98b017fe1391ed61 | train | class | class TestShouldRemoveOutsBeforeImport(TestDvc):
def setUp(self):
super().setUp()
tmp_dir = self.mkdtemp()
self.external_source = os.path.join(tmp_dir, "file")
with open(self.external_source, "w") as fobj:
fobj.write("content")
def test(self):
remove_outs_cal... | class TestShouldRemoveOutsBeforeImport(TestDvc):
| def setUp(self):
super().setUp()
tmp_dir = self.mkdtemp()
self.external_source = os.path.join(tmp_dir, "file")
with open(self.external_source, "w") as fobj:
fobj.write("content")
def test(self):
remove_outs_call_counter = spy(dvc.stage.Stage.remove_outs)
... | fd.write("content")
ret = main(["import-url", tmpfile])
self.assertEqual(ret, 0)
self.assertTrue(os.path.exists(filename))
with open(filename) as fd:
self.assertEqual(fd.read(), "content")
class TestShouldRemoveOutsBeforeImport(TestDvc):
| 64 | 64 | 150 | 12 | 52 | kacmak7/dvc | tests/func/test_import_url.py | Python | TestShouldRemoveOutsBeforeImport | TestShouldRemoveOutsBeforeImport | 45 | 61 | 45 | 45 | ef6e66daf87ff47a9dd6208400ccd173ec6cf456 | bigcode/the-stack | train |
db47b67ccc578513fbf8e305 | train | function | def semilogy(x_vals, y_vals, x_label, y_label, x2_vals=None, y2_vals=None,
legend=None, figsize=(3.5, 2.5)):
"""定义作图函数semilogy,其中 y轴使用了对数尺度"""
d2l.set_figsize(figsize)
d2l.plt.xlabel(x_label)
d2l.plt.ylabel(y_label)
d2l.plt.semilogy(x_vals, y_vals)
if x2_vals and y2_vals:
d2... | def semilogy(x_vals, y_vals, x_label, y_label, x2_vals=None, y2_vals=None,
legend=None, figsize=(3.5, 2.5)):
| """定义作图函数semilogy,其中 y轴使用了对数尺度"""
d2l.set_figsize(figsize)
d2l.plt.xlabel(x_label)
d2l.plt.ylabel(y_label)
d2l.plt.semilogy(x_vals, y_vals)
if x2_vals and y2_vals:
d2l.plt.semilogy(x2_vals, y2_vals, linestyle=':')
d2l.plt.legend(legend)
d2l.plt.show()
| , shape=labels.shape)
# 3.11.4.2 定义、训练和测试模型
def semilogy(x_vals, y_vals, x_label, y_label, x2_vals=None, y2_vals=None,
legend=None, figsize=(3.5, 2.5)):
| 64 | 64 | 151 | 41 | 22 | KDbob/d2l-study-notes | learning/3-basic/3_11-underfit-overfit.py | Python | semilogy | semilogy | 14 | 24 | 14 | 15 | 58661268b8e8cd84d73ab4b9fc4be7e49eb60dbf | bigcode/the-stack | train |
37510fc4ce1eedece0f3fdd4 | train | function | def fit_and_plot(train_features, test_features, train_labels, test_labels):
net = nn.Sequential()
net.add(nn.Dense(1))
net.initialize()
batch_size = min(10, train_labels.shape[0])
train_iter = gdata.DataLoader(gdata.ArrayDataset(
train_features, train_labels), batch_size, shuffle=True
)
... | def fit_and_plot(train_features, test_features, train_labels, test_labels):
| net = nn.Sequential()
net.add(nn.Dense(1))
net.initialize()
batch_size = min(10, train_labels.shape[0])
train_iter = gdata.DataLoader(gdata.ArrayDataset(
train_features, train_labels), batch_size, shuffle=True
)
trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': 0... | (x_vals, y_vals)
if x2_vals and y2_vals:
d2l.plt.semilogy(x2_vals, y2_vals, linestyle=':')
d2l.plt.legend(legend)
d2l.plt.show()
num_epochs, loss = 100, gloss.L2Loss(),
def fit_and_plot(train_features, test_features, train_labels, test_labels):
| 83 | 84 | 281 | 16 | 67 | KDbob/d2l-study-notes | learning/3-basic/3_11-underfit-overfit.py | Python | fit_and_plot | fit_and_plot | 29 | 51 | 29 | 29 | bb26421dbce0095e538ec69044099bf8e739347e | bigcode/the-stack | train |
d72b4a2fbb12007b87058fd6 | train | class | class ZendeskSellStream(Stream):
"""Zendesk Sell sync stream class."""
address_properties = {
"line1": {
"type": ["string", "null"],
"description": "Line 1 of the address.",
},
"city": {"type": ["string", "null"], "description": "City name."},
"postal_cod... | class ZendeskSellStream(Stream):
| """Zendesk Sell sync stream class."""
address_properties = {
"line1": {
"type": ["string", "null"],
"description": "Line 1 of the address.",
},
"city": {"type": ["string", "null"], "description": "City name."},
"postal_code": {
"type": ["strin... | """Zendesk Sell Base Stream class."""
from typing import Dict, Iterable, Optional, Tuple, Union
import basecrm
from singer_sdk.streams import Stream
from singer_sdk.tap_base import Tap
class ZendeskSellStream(Stream):
| 48 | 220 | 736 | 7 | 40 | leag/tap-zendesk-sell | tap_zendesk_sell/client.py | Python | ZendeskSellStream | ZendeskSellStream | 10 | 101 | 10 | 10 | f3c184dc7c1b2590ac5007c05d4c7d8805887c02 | bigcode/the-stack | train |
e3601abbd271d05873a2961e | train | class | class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]
list_display = ('question_text', 'pub_date', 'was_published_recently')
list_fi... | class QuestionAdmin(admin.ModelAdmin):
| fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]
list_display = ('question_text', 'pub_date', 'was_published_recently')
list_filter = ['pub_date']
search_fields =... | from django.contrib import admin
from .models import Choice, Question
# class ChoiceInline(admin.TabularInline):
# model = Choice
# extra = 3
class ChoiceInline(admin.StackedInline):
model = Choice
extra = 3
class QuestionAdmin(admin.ModelAdmin):
| 62 | 64 | 89 | 7 | 54 | maryowibisono/FirstDjangoApp | mysite/polls/admin.py | Python | QuestionAdmin | QuestionAdmin | 14 | 22 | 14 | 14 | 1a2f4404ef5fe78ee5c3761b788c44ecff43cf4c | bigcode/the-stack | train |
dc7271f0ea424c1fe6907ed1 | train | class | class ChoiceInline(admin.StackedInline):
model = Choice
extra = 3
| class ChoiceInline(admin.StackedInline):
| model = Choice
extra = 3
| from django.contrib import admin
from .models import Choice, Question
# class ChoiceInline(admin.TabularInline):
# model = Choice
# extra = 3
class ChoiceInline(admin.StackedInline):
| 44 | 64 | 19 | 8 | 35 | maryowibisono/FirstDjangoApp | mysite/polls/admin.py | Python | ChoiceInline | ChoiceInline | 9 | 11 | 9 | 9 | a5ab3cfebc209ef2b36ab3202d92b8839416c81b | bigcode/the-stack | train |
f2aaa805e727bdb3fd130424 | train | function | def get_junctions_bed12(line):
junctions = set()
chrstart = int(line[1])
starts = [int(n) + chrstart + 1 for n in line[11].split(',')[:-1]]
sizes = [int(n) - 1 for n in line[10].split(',')[:-1]]
if len(starts) == 1:
return
for b in range(len(starts)-1): # block
junctions.add((starts[b]+sizes[b], starts[b+1]))... | def get_junctions_bed12(line):
| junctions = set()
chrstart = int(line[1])
starts = [int(n) + chrstart + 1 for n in line[11].split(',')[:-1]]
sizes = [int(n) - 1 for n in line[10].split(',')[:-1]]
if len(starts) == 1:
return
for b in range(len(starts)-1): # block
junctions.add((starts[b]+sizes[b], starts[b+1]))
return junctions
| # for indexing pupropses
if len(starts) == 1:
return
for b in range(len(starts)-1): # block
junctions.add((starts[b]+sizes[b], starts[b+1]))
return junctions
def get_junctions_bed12(line):
| 64 | 64 | 120 | 10 | 53 | bharathananth/flair | bin/identify_gene_isoform.py | Python | get_junctions_bed12 | get_junctions_bed12 | 30 | 39 | 30 | 30 | 3bd849bd056b506edb69782a0e3c629a752b709a | bigcode/the-stack | train |
d5d274a8d6767d8b7cbfccf2 | train | function | def overlapping_bases(coords0, coords1):
""" complete coverage of coords0 by coords1, and coords0 can be tol larger.
if coords0 is contained by coords1, then return the number of
overlapping basepairs """
if coords0[1] > coords1[0] and coords1[1] > coords0[0]:
return min(coords1[1], coords0[1]) - max(coords1[0],... | def overlapping_bases(coords0, coords1):
| """ complete coverage of coords0 by coords1, and coords0 can be tol larger.
if coords0 is contained by coords1, then return the number of
overlapping basepairs """
if coords0[1] > coords1[0] and coords1[1] > coords0[0]:
return min(coords1[1], coords0[1]) - max(coords1[0], coords0[0])
return
| i = int(round((i + upper)/2))
elif data[i][0] > query[1]:
upper = i
i = int(round((lower + i)/2))
else: # found
break
return i
def overlapping_bases(coords0, coords1):
| 64 | 64 | 101 | 10 | 53 | bharathananth/flair | bin/identify_gene_isoform.py | Python | overlapping_bases | overlapping_bases | 60 | 66 | 60 | 60 | c8b399ec3f81ee038ef827481423f3a813afeed1 | bigcode/the-stack | train |
746ef02ff9d56074396f9a50 | train | function | def bin_search(query, data):
""" Query is a coordinate interval. Binary search for the query in sorted data,
which is a list of coordinates. Finishes when an overlapping value of query and
data exists and returns the index in data. """
i = int(round(len(data)/2)) # binary search prep
lower, upper = 0, len(data)... | def bin_search(query, data):
| """ Query is a coordinate interval. Binary search for the query in sorted data,
which is a list of coordinates. Finishes when an overlapping value of query and
data exists and returns the index in data. """
i = int(round(len(data)/2)) # binary search prep
lower, upper = 0, len(data)
while True:
if upper - lo... | in line[10].split(',')[:-1]]
if len(starts) == 1:
return
for b in range(len(starts)-1): # block
junctions.add((starts[b]+sizes[b], starts[b+1]))
return junctions
def bin_search(query, data):
| 64 | 64 | 176 | 7 | 56 | bharathananth/flair | bin/identify_gene_isoform.py | Python | bin_search | bin_search | 41 | 58 | 41 | 41 | 743aa4818c814501b3164adb59e2a10d9472c392 | bigcode/the-stack | train |
5d8244f39dc36f2ad190df78 | train | function | def update_gene_dicts(chrom, j, gene, junctions, gene_unique_juncs, junc_to_gene):
junctions.add(j)
if prev_gene not in gene_unique_juncs:
gene_unique_juncs[prev_gene] = set()
gene_unique_juncs[gene].add(j)
if j not in junc_to_gene[chrom]:
junc_to_gene[chrom][j] = set()
junc_to_gene[chrom][j].add(gene)
return... | def update_gene_dicts(chrom, j, gene, junctions, gene_unique_juncs, junc_to_gene):
| junctions.add(j)
if prev_gene not in gene_unique_juncs:
gene_unique_juncs[prev_gene] = set()
gene_unique_juncs[gene].add(j)
if j not in junc_to_gene[chrom]:
junc_to_gene[chrom][j] = set()
junc_to_gene[chrom][j].add(gene)
return junctions, gene_unique_juncs, junc_to_gene
| ][j] = set()
junc_to_tn[chrom][j].add(prev_transcript)
return junc_to_tn, tn_to_juncs, all_se
def update_gene_dicts(chrom, j, gene, junctions, gene_unique_juncs, junc_to_gene):
| 64 | 64 | 121 | 26 | 37 | bharathananth/flair | bin/identify_gene_isoform.py | Python | update_gene_dicts | update_gene_dicts | 84 | 92 | 84 | 84 | e6184405f762047f9eec8af61380c33619d9a14e | bigcode/the-stack | train |
655eeb9c8ece3b628ae6c7af | train | function | def update_tn_dicts(chrom, junctions, prev_transcript, prev_exon, junc_to_tn, \
tn_to_juncs, all_se):
if chrom not in junc_to_tn:
junc_to_tn[chrom] = {}
tn_to_juncs[chrom] = {}
all_se[chrom] = []
if not junctions:
all_se[chrom] += [prev_exon]
else:
tn_to_juncs[chrom][prev_transcript] = junctions
for j i... | def update_tn_dicts(chrom, junctions, prev_transcript, prev_exon, junc_to_tn, \
tn_to_juncs, all_se):
| if chrom not in junc_to_tn:
junc_to_tn[chrom] = {}
tn_to_juncs[chrom] = {}
all_se[chrom] = []
if not junctions:
all_se[chrom] += [prev_exon]
else:
tn_to_juncs[chrom][prev_transcript] = junctions
for j in junctions:
if j not in junc_to_tn[chrom]:
junc_to_tn[chrom][j] = set()
junc_to_tn[chrom][j]... | return min(coords1[1], coords0[1]) - max(coords1[0], coords0[0])
return
def update_tn_dicts(chrom, junctions, prev_transcript, prev_exon, junc_to_tn, \
tn_to_juncs, all_se):
| 64 | 64 | 181 | 37 | 26 | bharathananth/flair | bin/identify_gene_isoform.py | Python | update_tn_dicts | update_tn_dicts | 68 | 82 | 68 | 69 | 7e209e974f0b94d0315b9480bb3e678108c4aada | bigcode/the-stack | train |
c7135cf962477ef61a2150d3 | train | function | def get_junctions(line):
junctions = set()
starts = [int(n) + 1 for n in line[20].split(',')[:-1]]
sizes = [int(n) - 1 for n in line[18].split(',')[:-1]] # for indexing pupropses
if len(starts) == 1:
return
for b in range(len(starts)-1): # block
junctions.add((starts[b]+sizes[b], starts[b+1]))
return junctio... | def get_junctions(line):
| junctions = set()
starts = [int(n) + 1 for n in line[20].split(',')[:-1]]
sizes = [int(n) - 1 for n in line[18].split(',')[:-1]] # for indexing pupropses
if len(starts) == 1:
return
for b in range(len(starts)-1): # block
junctions.add((starts[b]+sizes[b], starts[b+1]))
return junctions
| gene\n')
sys.stderr.write('optional argument: proportion should be a decimal < 1 specifying the % of an' +
'annotated single-exon gene a FLAIR isoform has to cover (default=0.8)\n')
sys.exit(1)
def get_junctions(line):
| 64 | 64 | 113 | 7 | 57 | bharathananth/flair | bin/identify_gene_isoform.py | Python | get_junctions | get_junctions | 20 | 28 | 20 | 20 | 4b44c3f8a0c62145c1d4bdcb2cd63547b56b92ba | bigcode/the-stack | train |
c3be104f3229eedf7c749e2f | train | function | def from_aiter(iterator, feedback: Optional[Observable] = None):
# noinspection PyUnusedLocal
def on_subscribe(observer: Observer, scheduler):
async def _aio_next():
try:
event = await iterator.__anext__()
if isinstance(event, OnNext):
obs... | def from_aiter(iterator, feedback: Optional[Observable] = None):
# noinspection PyUnusedLocal
| def on_subscribe(observer: Observer, scheduler):
async def _aio_next():
try:
event = await iterator.__anext__()
if isinstance(event, OnNext):
observer.on_next(event.value)
elif isinstance(event, OnError):
ob... | ait(i)
observable.pipe(materialize()).subscribe(
on_next=on_next
)
while True:
value = await queue.get()
yield value
queue.task_done()
def from_aiter(iterator, feedback: Optional[Observable] = None):
# noinspection PyUnusedLocal
| 64 | 64 | 168 | 24 | 40 | Precognize/rsocket-py | rsocket/rx_support/back_pressure_publisher.py | Python | from_aiter | from_aiter | 33 | 59 | 33 | 34 | 995d946876dab0f3ff7cdfb551ee35b5b99d0bf0 | bigcode/the-stack | train |
4049911f23b0e7506885dd0c | train | function | async def observable_to_async_event_generator(observable: Observable):
queue = asyncio.Queue()
def on_next(i):
queue.put_nowait(i)
observable.pipe(materialize()).subscribe(
on_next=on_next
)
while True:
value = await queue.get()
yield value
queue.task_done(... | async def observable_to_async_event_generator(observable: Observable):
| queue = asyncio.Queue()
def on_next(i):
queue.put_nowait(i)
observable.pipe(materialize()).subscribe(
on_next=on_next
)
while True:
value = await queue.get()
yield value
queue.task_done()
| from rx.operators import materialize
from rx.subject import Subject
from reactivestreams.subscriber import Subscriber
from rsocket.helpers import DefaultPublisherSubscription
from rsocket.logger import logger
from rsocket.rx_support.subscriber_adapter import SubscriberAdapter
async def observable_to_async_event_genera... | 64 | 64 | 68 | 12 | 51 | Precognize/rsocket-py | rsocket/rx_support/back_pressure_publisher.py | Python | observable_to_async_event_generator | observable_to_async_event_generator | 17 | 30 | 17 | 17 | de578eed9536e5e49b6fdaa74a7e6d9408e052db | bigcode/the-stack | train |
b0c8f033ca6cce3d78a4473d | train | class | class BackPressurePublisher(DefaultPublisherSubscription):
def __init__(self, wrapped_observable: Observable):
self._wrapped_observable = wrapped_observable
self._feedback = None
def subscribe(self, subscriber: Subscriber):
super().subscribe(subscriber)
self._feedback = Subject(... | class BackPressurePublisher(DefaultPublisherSubscription):
| def __init__(self, wrapped_observable: Observable):
self._wrapped_observable = wrapped_observable
self._feedback = None
def subscribe(self, subscriber: Subscriber):
super().subscribe(subscriber)
self._feedback = Subject()
async_iterator = observable_to_async_event_genera... | logger().error(str(exception), exc_info=True)
observer.on_error(exception)
def create_next_task():
asyncio.create_task(_aio_next())
return feedback.subscribe(
on_next=lambda i: create_next_task()
)
return rx.create(on_subscribe)
clas... | 64 | 64 | 135 | 8 | 56 | Precognize/rsocket-py | rsocket/rx_support/back_pressure_publisher.py | Python | BackPressurePublisher | BackPressurePublisher | 62 | 78 | 62 | 62 | f912d449f11a7a0104e376b7ed36200e84ed1167 | bigcode/the-stack | train |
d6ceb5376f000c8fb27cff20 | train | class | class EventTeamManipulator(ManipulatorBase[EventTeam]):
"""
Handle EventTeam database writes.
"""
"""
@classmethod
def getCacheKeysAndControllers(cls, affected_refs):
return CacheClearer.get_eventteam_cache_keys_and_controllers(affected_refs)
"""
@classmethod
def updateMerg... | class EventTeamManipulator(ManipulatorBase[EventTeam]):
| """
Handle EventTeam database writes.
"""
"""
@classmethod
def getCacheKeysAndControllers(cls, affected_refs):
return CacheClearer.get_eventteam_cache_keys_and_controllers(affected_refs)
"""
@classmethod
def updateMerge(
cls,
new_event_team: EventTeam,
... | from backend.common.manipulators.manipulator_base import ManipulatorBase
from backend.common.models.event_team import EventTeam
class EventTeamManipulator(ManipulatorBase[EventTeam]):
| 36 | 64 | 134 | 11 | 24 | guineawheek/ftc-data-take-2 | src/backend/common/manipulators/event_team_manipulator.py | Python | EventTeamManipulator | EventTeamManipulator | 5 | 27 | 5 | 5 | 8a187f73752466c3731675a04e8ba4910c7109cc | bigcode/the-stack | train |
0d954ff47afa403170f373c7 | train | function | @pytest.fixture
def client():
client = KerasClient()
return client
| @pytest.fixture
def client():
| client = KerasClient()
return client
| .models import Sequential
from keras.layers.core import Dense, Activation
from keras.optimizers import SGD
from grid.clients.keras import KerasClient
from grid.workers.compute import GridCompute
import time
from threading import Thread
import pytest
client = None
compute_id = None
@pytest.fixture
def client():
| 64 | 64 | 17 | 6 | 57 | cthorey/Grid | tests/test_integration.py | Python | client | client | 15 | 18 | 15 | 16 | 525d89b342739da4915ddddd170746572297a0c0 | bigcode/the-stack | train |
a534a646a5f875b2be1bad1d | train | function | def test_integration(client):
compute_id = wait_for_discovery(client)
assert(compute_id is not None)
input = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
target = np.array([[0], [1], [1], [0]])
model = Sequential()
model.add(Dense(8, input_dim=2))
model.add(Activation('tanh'))
model.add... | def test_integration(client):
| compute_id = wait_for_discovery(client)
assert(compute_id is not None)
input = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
target = np.array([[0], [1], [1], [0]])
model = Sequential()
model.add(Dense(8, input_dim=2))
model.add(Activation('tanh'))
model.add(Dense(1))
model.add(Activ... | (15)
else:
assert(compute_id is not None)
# TODO probably shouldn't have to try again
for stats in client.stats:
if ipfs_id[1] in stats['id']:
compute_id = stats['id']
return compute_id
def test_integration(client):
| 64 | 64 | 176 | 6 | 57 | cthorey/Grid | tests/test_integration.py | Python | test_integration | test_integration | 45 | 68 | 45 | 45 | 72dfc81c22c3cc1af91ef5a1292d1d5a61b5c287 | bigcode/the-stack | train |
eabd585ac60b2dd77d4e4910 | train | function | def wait_for_discovery(client):
ipfs_id = client.id.split(":")
compute_id = None
time.sleep(30)
print(client.stats)
for stats in client.stats:
if ipfs_id[1] in stats['id']:
compute_id = stats['id']
if compute_id is None:
time.sleep(15)
else:
assert(comp... | def wait_for_discovery(client):
| ipfs_id = client.id.split(":")
compute_id = None
time.sleep(30)
print(client.stats)
for stats in client.stats:
if ipfs_id[1] in stats['id']:
compute_id = stats['id']
if compute_id is None:
time.sleep(15)
else:
assert(compute_id is not None)
# TODO ... | SGD
from grid.clients.keras import KerasClient
from grid.workers.compute import GridCompute
import time
from threading import Thread
import pytest
client = None
compute_id = None
@pytest.fixture
def client():
client = KerasClient()
return client
def wait_for_discovery(client):
| 64 | 64 | 130 | 7 | 56 | cthorey/Grid | tests/test_integration.py | Python | wait_for_discovery | wait_for_discovery | 21 | 42 | 21 | 21 | d0733f524a7628f6409e038fc43f265348ebd7a8 | bigcode/the-stack | train |
a2f6fe9ccf323b56ee5d2b36 | train | function | def button_click(char):
curr = display_slot.get()
display_slot.delete(0, END)
display_slot.insert(0, str(curr) + str(char))
| def button_click(char):
| curr = display_slot.get()
display_slot.delete(0, END)
display_slot.insert(0, str(curr) + str(char))
| ()
root.wm_title("Calculator")
display_slot = Entry(root, width=35, borderwidth=5)
display_slot.grid(row=0, column=0, columnspan=3, padx=10, pady=10)
# Adding display_slot functionality - referring it as a string
def button_click(char):
| 64 | 64 | 35 | 5 | 58 | oshratS/python-calc | UI.py | Python | button_click | button_click | 13 | 16 | 13 | 13 | 2f7e020d56e0b8e1c7619cfc5c6cf2e6b0459ad8 | bigcode/the-stack | train |
d51b449a889b973201e07ca6 | train | function | def clear_button():
display_slot.delete(0, END)
| def clear_button():
| display_slot.delete(0, END)
| columnspan=3, padx=10, pady=10)
# Adding display_slot functionality - referring it as a string
def button_click(char):
curr = display_slot.get()
display_slot.delete(0, END)
display_slot.insert(0, str(curr) + str(char))
def clear_button():
| 64 | 64 | 13 | 4 | 60 | oshratS/python-calc | UI.py | Python | clear_button | clear_button | 19 | 20 | 19 | 19 | 359a1e6f9687a22c94dd55859feafa45e1aff358 | bigcode/the-stack | train |
5bc0a3c237472f027348efe0 | train | function | def subtraction_button():
sub_operator = '-'
str_subtraction = 'subtraction'
display_slot.insert(END, sub_operator)
| def subtraction_button():
| sub_operator = '-'
str_subtraction = 'subtraction'
display_slot.insert(END, sub_operator)
| _operation
add_operator = '+'
str_addition = "addition"
#first_num = num
#display_slot.delete(0, END)
display_slot.insert(END, add_operator)
#print(display_slot.get())
#display_slot.delete(0, END)
def subtraction_button():
| 64 | 64 | 29 | 4 | 60 | oshratS/python-calc | UI.py | Python | subtraction_button | subtraction_button | 36 | 39 | 36 | 36 | 50324674dc5e0614bb8d120cddbd8da04007978e | bigcode/the-stack | train |
74b5075d9ac11a5cf1814f8b | train | function | def addition_button():
num = display_slot.get()
global math_operation
add_operator = '+'
str_addition = "addition"
#first_num = num
#display_slot.delete(0, END)
display_slot.insert(END, add_operator)
| def addition_button():
| num = display_slot.get()
global math_operation
add_operator = '+'
str_addition = "addition"
#first_num = num
#display_slot.delete(0, END)
display_slot.insert(END, add_operator)
| # Adding display_slot functionality - referring it as a string
def button_click(char):
curr = display_slot.get()
display_slot.delete(0, END)
display_slot.insert(0, str(curr) + str(char))
def clear_button():
display_slot.delete(0, END)
def addition_button():
| 64 | 64 | 57 | 4 | 60 | oshratS/python-calc | UI.py | Python | addition_button | addition_button | 23 | 31 | 23 | 24 | f81fbb471d65c3fe9bdf3e3cc1a534bcd14fcc6d | bigcode/the-stack | train |
cf69d49eba05332b57cd3f81 | train | function | def solve_constraints(vars: List[int], constraints: List[Constraint]) -> List[Type]:
"""Solve type constraints.
Return the best type(s) for type variables; each type can be None if the value of the variable
could not be solved. If a variable has no constraints, arbitrarily pick NoneTyp as the value of
... | def solve_constraints(vars: List[int], constraints: List[Constraint]) -> List[Type]:
| """Solve type constraints.
Return the best type(s) for type variables; each type can be None if the value of the variable
could not be solved. If a variable has no constraints, arbitrarily pick NoneTyp as the value of
the type variable.
"""
# Collect a list of constraints for each type variable... | """Type inference constraint solving"""
from typing import List, Dict
from mypy.types import Type, Void, NoneTyp, AnyType, ErrorType
from mypy.constraints import Constraint, SUPERTYPE_OF
from mypy.join import join_types
from mypy.meet import meet_types
from mypy.subtypes import is_subtype
def solve_constraints(vars: ... | 89 | 126 | 423 | 19 | 69 | spkersten/mypy | mypy/solve.py | Python | solve_constraints | solve_constraints | 12 | 68 | 12 | 12 | 8f9a34bc11dc6d65081107f7e9941d53011ecfa6 | bigcode/the-stack | train |
b704ee7996bcf08144fb5a37 | train | function | def loadImage(f):
""" Load NIfTI image.
"""
img = nib.load(f)
mat = img.get_data()
aff = img.get_affine()
return mat, aff, img
| def loadImage(f):
| """ Load NIfTI image.
"""
img = nib.load(f)
mat = img.get_data()
aff = img.get_affine()
return mat, aff, img
| #!/usr/bin/env python
# coding : utf-8
"""
Utilities.
"""
import numpy as np
import nibabel as nib
import re
def loadImage(f):
| 36 | 64 | 45 | 5 | 30 | spikefairway/VOIAnalyzer | utils.py | Python | loadImage | loadImage | 12 | 19 | 12 | 12 | 5aeb9cbdc8dadc6a3fdc6d9e3cd7a8e342bb3e9f | bigcode/the-stack | train |
756e1f4eda648e4f68a03a5a | train | function | def readLUTLine(line):
""" Read line in VOI look-up table file.
"""
reg = re.compile(r"(\d+)\s+(\S+)")
res = reg.match(line)
grps = res.groups()
return {int(grps[0]) : grps[1]}
| def readLUTLine(line):
| """ Read line in VOI look-up table file.
"""
reg = re.compile(r"(\d+)\s+(\S+)")
res = reg.match(line)
grps = res.groups()
return {int(grps[0]) : grps[1]}
| as np
import nibabel as nib
import re
def loadImage(f):
""" Load NIfTI image.
"""
img = nib.load(f)
mat = img.get_data()
aff = img.get_affine()
return mat, aff, img
def readLUTLine(line):
| 64 | 64 | 67 | 7 | 56 | spikefairway/VOIAnalyzer | utils.py | Python | readLUTLine | readLUTLine | 21 | 28 | 21 | 21 | f06836cda266e59e4c913edf1718bfffad9bee4a | bigcode/the-stack | train |
6391a0535820f9df3897a98f | train | function | def loadLUT(f):
""" Load VOI look-up table file.
Format for look-up table file.
<VOI No.> <VOI name>
for example,
1 GM
2 WM
3 CSF
if above, voxels with 1, 2 and 3 indicate gray matter (GM),
white matter (WM) and cerebrospinal fluid (CSF).
It outputs ... | def loadLUT(f):
| """ Load VOI look-up table file.
Format for look-up table file.
<VOI No.> <VOI name>
for example,
1 GM
2 WM
3 CSF
if above, voxels with 1, 2 and 3 indicate gray matter (GM),
white matter (WM) and cerebrospinal fluid (CSF).
It outputs dictionary {<VOI... | line in VOI look-up table file.
"""
reg = re.compile(r"(\d+)\s+(\S+)")
res = reg.match(line)
grps = res.groups()
return {int(grps[0]) : grps[1]}
def loadLUT(f):
| 63 | 64 | 160 | 6 | 57 | spikefairway/VOIAnalyzer | utils.py | Python | loadLUT | loadLUT | 30 | 53 | 30 | 30 | f984b4e31fe5104b945430c4936e0fbd5e0555dc | bigcode/the-stack | train |
0adeec9a314b35b55bc6c480 | train | function | @pytest.fixture
def mock_login_request(requests_mock):
requests_mock.post(LOGIN_URL, json={"key": TOKEN}, request_headers=REQUEST_HEADERS)
requests_mock.post(f"{API_URL}/v1/auth/logout", request_headers=REQUEST_HEADERS)
yield requests_mock
| @pytest.fixture
def mock_login_request(requests_mock):
| requests_mock.post(LOGIN_URL, json={"key": TOKEN}, request_headers=REQUEST_HEADERS)
requests_mock.post(f"{API_URL}/v1/auth/logout", request_headers=REQUEST_HEADERS)
yield requests_mock
| _credentials(monkeypatch):
monkeypatch.setitem(os.environ, "ELIS_URL", API_URL)
monkeypatch.setitem(os.environ, "ELIS_USERNAME", "some")
monkeypatch.setitem(os.environ, "ELIS_PASSWORD", "secret")
@pytest.fixture
def mock_login_request(requests_mock):
| 64 | 64 | 56 | 11 | 53 | tbots/elisctl | tests/conftest.py | Python | mock_login_request | mock_login_request | 41 | 45 | 41 | 42 | 186e36303ade8f2ecdc570575b36528218318b81 | bigcode/the-stack | train |
3d631fb3aeb0a6bb89944486 | train | function | @pytest.fixture
def mock_get_schema(request: FixtureRequest, requests_mock):
schema_id = getattr(request.module, "schema_id", "1")
schema_content = getattr(request.module, "schema_content", [])
requests_mock.get(
f"{SCHEMAS_URL}/{schema_id}",
json={
"content": schema_content,
... | @pytest.fixture
def mock_get_schema(request: FixtureRequest, requests_mock):
| schema_id = getattr(request.module, "schema_id", "1")
schema_content = getattr(request.module, "schema_content", [])
requests_mock.get(
f"{SCHEMAS_URL}/{schema_id}",
json={
"content": schema_content,
"name": "test",
"queues": [f"{API_URL}/v1/queues/{i}" f... | (requests_mock):
requests_mock.post(LOGIN_URL, json={"key": TOKEN}, request_headers=REQUEST_HEADERS)
requests_mock.post(f"{API_URL}/v1/auth/logout", request_headers=REQUEST_HEADERS)
yield requests_mock
@pytest.fixture
def mock_get_schema(request: FixtureRequest, requests_mock):
| 64 | 64 | 125 | 15 | 48 | tbots/elisctl | tests/conftest.py | Python | mock_get_schema | mock_get_schema | 48 | 62 | 48 | 49 | 9bf4c900bddb6c9f3690f5867ee9eb29c51751be | bigcode/the-stack | train |
8ba22b8f8d17c1a547da93a2 | train | function | @pytest.fixture
def mock_organization_urls(request: FixtureRequest, requests_mock):
organization_id = getattr(request.module, "ORGANIZATION_ID", "1")
organization_url = getattr(
request.module, "ORGANIZATION_URL", f"{ORGANIZATIONS_URL}/{organization_id}"
)
user_url = f"{USERS_URL}/1"
reques... | @pytest.fixture
def mock_organization_urls(request: FixtureRequest, requests_mock):
| organization_id = getattr(request.module, "ORGANIZATION_ID", "1")
organization_url = getattr(
request.module, "ORGANIZATION_URL", f"{ORGANIZATIONS_URL}/{organization_id}"
)
user_url = f"{USERS_URL}/1"
requests_mock.get(
organization_url,
json={"url": organization_url, "id": ... | "queues": [f"{API_URL}/v1/queues/{i}" for i in range(1, 3)],
},
request_headers={"Authorization": f"Token {TOKEN}"},
)
yield requests_mock
@pytest.fixture
def mock_organization_urls(request: FixtureRequest, requests_mock):
| 64 | 64 | 185 | 16 | 47 | tbots/elisctl | tests/conftest.py | Python | mock_organization_urls | mock_organization_urls | 65 | 87 | 65 | 66 | e7ad048e184250ae9b22f1f17fbff3663dca369c | bigcode/the-stack | train |
bce82656483f1153de7b8908 | train | function | def match_uploaded_data(filename: str, request: Request) -> bool:
return filename in request.text
| def match_uploaded_data(filename: str, request: Request) -> bool:
| return filename in request.text
| _path / "empty_file.pdf"
invoice_sample.write_bytes(_EMPTY_PDF_FILE)
yield invoice_sample
def match_uploaded_json(uploaded_json: dict, request: Request) -> bool:
return request.json() == uploaded_json
def match_uploaded_data(filename: str, request: Request) -> bool:
| 64 | 64 | 22 | 15 | 48 | tbots/elisctl | tests/conftest.py | Python | match_uploaded_data | match_uploaded_data | 101 | 102 | 101 | 101 | b6fac6c346f86ebf1e9319936cdeee8711b9481e | bigcode/the-stack | train |
27bdd6c4e768c93db449b4e0 | train | function | def match_uploaded_values(values: dict, request: Request) -> bool:
return values == json.loads(parse_multipart_message(request)["values"][1])
| def match_uploaded_values(values: dict, request: Request) -> bool:
| return values == json.loads(parse_multipart_message(request)["values"][1])
|
def match_uploaded_json(uploaded_json: dict, request: Request) -> bool:
return request.json() == uploaded_json
def match_uploaded_data(filename: str, request: Request) -> bool:
return filename in request.text
def match_uploaded_values(values: dict, request: Request) -> bool:
| 64 | 64 | 31 | 15 | 48 | tbots/elisctl | tests/conftest.py | Python | match_uploaded_values | match_uploaded_values | 105 | 106 | 105 | 105 | 2254a58433068af460be479cdda34857f17f78d1 | bigcode/the-stack | train |
b91100e52a680c04de7109c7 | train | function | @pytest.fixture
def mock_file(tmp_path):
invoice_sample = tmp_path / "empty_file.pdf"
invoice_sample.write_bytes(_EMPTY_PDF_FILE)
yield invoice_sample
| @pytest.fixture
def mock_file(tmp_path):
| invoice_sample = tmp_path / "empty_file.pdf"
invoice_sample.write_bytes(_EMPTY_PDF_FILE)
yield invoice_sample
| url": user_url, "organization": organization_url}
)
requests_mock.get(
re.compile(fr"{WORKSPACES_URL}/\d$"),
json={"organization": organization_url},
request_headers={"Authorization": f"Token {TOKEN}"},
)
@pytest.fixture
def mock_file(tmp_path):
| 64 | 64 | 37 | 9 | 55 | tbots/elisctl | tests/conftest.py | Python | mock_file | mock_file | 90 | 94 | 90 | 91 | 6a8b35cf3c4dd35d584998c5dcf50abe32aae108 | bigcode/the-stack | train |
216eeb7278c4b5ba33ef8888 | train | function | @pytest.fixture
def elis_credentials(monkeypatch):
monkeypatch.setitem(os.environ, "ELIS_URL", API_URL)
monkeypatch.setitem(os.environ, "ELIS_USERNAME", "some")
monkeypatch.setitem(os.environ, "ELIS_PASSWORD", "secret")
| @pytest.fixture
def elis_credentials(monkeypatch):
| monkeypatch.setitem(os.environ, "ELIS_URL", API_URL)
monkeypatch.setitem(os.environ, "ELIS_USERNAME", "some")
monkeypatch.setitem(os.environ, "ELIS_PASSWORD", "secret")
| /login"
CONNECTORS_URL = f"{API_URL}/v1/connectors"
WEBHOOKS_URL = f"{API_URL}/v1/webhooks"
REQUEST_HEADERS = {"User-Agent": f"elisctl/{__version__} ({platform()})"}
@pytest.fixture
def elis_credentials(monkeypatch):
| 63 | 64 | 59 | 11 | 52 | tbots/elisctl | tests/conftest.py | Python | elis_credentials | elis_credentials | 34 | 38 | 34 | 35 | 85d9ce397ae857a420ef0aa740d6a265b31f9cfa | bigcode/the-stack | train |
99acec5f0d6555856a036c0e | train | function | def match_uploaded_json(uploaded_json: dict, request: Request) -> bool:
return request.json() == uploaded_json
| def match_uploaded_json(uploaded_json: dict, request: Request) -> bool:
| return request.json() == uploaded_json
| ": f"Token {TOKEN}"},
)
@pytest.fixture
def mock_file(tmp_path):
invoice_sample = tmp_path / "empty_file.pdf"
invoice_sample.write_bytes(_EMPTY_PDF_FILE)
yield invoice_sample
def match_uploaded_json(uploaded_json: dict, request: Request) -> bool:
| 64 | 64 | 26 | 17 | 46 | tbots/elisctl | tests/conftest.py | Python | match_uploaded_json | match_uploaded_json | 97 | 98 | 97 | 97 | 091062b98f6f80968474403ce1cdbeed8d8deb5a | bigcode/the-stack | train |
e1544fe64e6c857b8d4cb393 | train | function | def parse_multipart_message(request: Request) -> Dict[str, Tuple[Dict[str, str], str]]:
epost_data = f"""\
MIME-Version: 1.0
Content-Type: {request.headers['Content-Type']}
{request.body.decode()}"""
msg = email.message_from_string(epost_data)
assert msg.is_multipart()
return {
params["name"... | def parse_multipart_message(request: Request) -> Dict[str, Tuple[Dict[str, str], str]]:
| epost_data = f"""\
MIME-Version: 1.0
Content-Type: {request.headers['Content-Type']}
{request.body.decode()}"""
msg = email.message_from_string(epost_data)
assert msg.is_multipart()
return {
params["name"]: (params, contents)
for params, contents in map(
lambda part: (dic... | ) -> bool:
return filename in request.text
def match_uploaded_values(values: dict, request: Request) -> bool:
return values == json.loads(parse_multipart_message(request)["values"][1])
def parse_multipart_message(request: Request) -> Dict[str, Tuple[Dict[str, str], str]]:
| 64 | 64 | 123 | 22 | 42 | tbots/elisctl | tests/conftest.py | Python | parse_multipart_message | parse_multipart_message | 109 | 126 | 109 | 109 | f3d1653a31e4c61c87726049c8646733bcd6a529 | bigcode/the-stack | train |
9a6f42399801ab187ddf373d | train | function | def directive_analysis(line_segment, label='.none'):
'''
Checks what lc3 directive was used, returns the label
of the line that directive sits on, and the number of
lines that directive will take up. If no label exists,
'.none' is returned.
:param line_segment: the part of the line of code that
starts wit... | def directive_analysis(line_segment, label='.none'):
| '''
Checks what lc3 directive was used, returns the label
of the line that directive sits on, and the number of
lines that directive will take up. If no label exists,
'.none' is returned.
:param line_segment: the part of the line of code that
starts with an assembler directive
:param label: the label of... | pseudo_ops
'''
from lc3_keywords import opcodes
for opcode in opcodes:
if opcode == token.lower():
return True
from lc3_keywords import pseudo_ops
for opcode in pseudo_ops:
if opcode == token.lower():
return True
return False
def directive_analysis(line_segment, label='.none'):
| 73 | 73 | 244 | 10 | 62 | pegurnee/2015-01-341 | projects/project2_lc3_symbol_table_python/lc3_asm_reader.py | Python | directive_analysis | directive_analysis | 46 | 70 | 46 | 46 | 9407db744dc8bc4ab37dd17ca189f62965e3f321 | bigcode/the-stack | train |
99f402592d4adc0e8afe602a | train | function | def decode_line(line):
'''
Takes in a line of code and returns the relevant symbol
table information: label (if applicable) and number of lines
the label takes up.
:param line: the line of code to interpret
'''
line = line.strip();
if line[0] == ';':
return '.none', 0
if line[0] == '.':
retu... | def decode_line(line):
| '''
Takes in a line of code and returns the relevant symbol
table information: label (if applicable) and number of lines
the label takes up.
:param line: the line of code to interpret
'''
line = line.strip();
if line[0] == ';':
return '.none', 0
if line[0] == '.':
return directive_analysis(l... | return label, 1
elif directive == '.blkw':
return label, int(rest_of_line.split()[0])
elif directive == '.stringz':
return label, len(rest_of_line[1:rest_of_line.index('"', 1)]) + 1
def decode_line(line):
| 64 | 64 | 160 | 5 | 58 | pegurnee/2015-01-341 | projects/project2_lc3_symbol_table_python/lc3_asm_reader.py | Python | decode_line | decode_line | 72 | 93 | 72 | 72 | 998b77a75bf89fdc6758fa717736009732474a4b | bigcode/the-stack | train |
65f6880d024397bb6f35fcba | train | function | def is_lc3_instruction(token):
'''
Returns true if a given token is an lc3 opcode or
pseudo_op.
:param token: a string to test against the list of
opcodes and pseudo_ops
'''
from lc3_keywords import opcodes
for opcode in opcodes:
if opcode == token.lower():
return True
from lc3_keywords impo... | def is_lc3_instruction(token):
| '''
Returns true if a given token is an lc3 opcode or
pseudo_op.
:param token: a string to test against the list of
opcodes and pseudo_ops
'''
from lc3_keywords import opcodes
for opcode in opcodes:
if opcode == token.lower():
return True
from lc3_keywords import pseudo_ops
for opcode in p... | lines = decode_line(line)
if label[0] != '.':
if not symbol_table.add(label, current_line):
print("Error adding label: '%s', already exists in table" % label)
current_line += numlines
return symbol_table
def is_lc3_instruction(token):
| 64 | 64 | 109 | 8 | 55 | pegurnee/2015-01-341 | projects/project2_lc3_symbol_table_python/lc3_asm_reader.py | Python | is_lc3_instruction | is_lc3_instruction | 29 | 44 | 29 | 29 | 423a8035d6d545d6b3fb3fb6b9e529550750f508 | bigcode/the-stack | train |
9027c5836f6d37dc5dedbcca | train | function | def get_symbol_table(filename, absolute_flag='r'):
'''
Returns a SymbolTable object from a given file.
:param filename: the name of the file to generate a
symbol table
:param absolute_flag: if the flag is set to absolute then
the filename string is absolute
'''
from lc3_symbol_table import SymbolTable
... | def get_symbol_table(filename, absolute_flag='r'):
| '''
Returns a SymbolTable object from a given file.
:param filename: the name of the file to generate a
symbol table
:param absolute_flag: if the flag is set to absolute then
the filename string is absolute
'''
from lc3_symbol_table import SymbolTable
symbol_table = SymbolTable(filename)
if absolut... | def get_symbol_table(filename, absolute_flag='r'):
| 11 | 64 | 213 | 11 | 0 | pegurnee/2015-01-341 | projects/project2_lc3_symbol_table_python/lc3_asm_reader.py | Python | get_symbol_table | get_symbol_table | 1 | 27 | 1 | 1 | 7a221f9a78f9da37cc3b2cecd6fb441737a3f8c6 | bigcode/the-stack | train |
51cda4480b50405b884ffa8e | train | class | class PostForm(forms.ModelForm):
content = forms.CharField(widget=PagedownWidget(attrs={"show_preview":False}))
publish = forms.DateField(widget=forms.SelectDateWidget)
class Meta:
model = Post
fields = [
"title",
"content",
"image",
"draft",
... | class PostForm(forms.ModelForm):
| content = forms.CharField(widget=PagedownWidget(attrs={"show_preview":False}))
publish = forms.DateField(widget=forms.SelectDateWidget)
class Meta:
model = Post
fields = [
"title",
"content",
"image",
"draft",
"publish",
] | from django import forms
from pagedown.widgets import PagedownWidget
from .models import Post
class PostForm(forms.ModelForm):
| 29 | 64 | 72 | 7 | 21 | zemeister2332/videoUploadRestDjango | src/posts/forms.py | Python | PostForm | PostForm | 8 | 19 | 8 | 8 | 31a145c5159cb743d4ba8f886ae91191cd5d244c | bigcode/the-stack | train |
504abab6db610bb67dac83a3 | train | class | class Tagger(PartialTagger):
def outval(self, tag):
return tag._POS
| class Tagger(PartialTagger):
| def outval(self, tag):
return tag._POS
| ammeme']),
features.Pattern([-1, 'GrammemePair']),
features.Pattern([+1, 'GrammemePair']),
# features.Pattern([-1, 'GrammemePair'], [0, 'GrammemePair']),
],
)
class Tagger(PartialTagger):
| 64 | 64 | 22 | 8 | 56 | kmike/morphine | morphine/pos_model.py | Python | Tagger | Tagger | 49 | 51 | 49 | 49 | 2bdc3cfcc7f42b27ed527656ce6125e16488b883 | bigcode/the-stack | train |
3f25186d95a71dfa3466b9bb | train | class | class POSFeatureExtractor(FeatureExtractor):
IGNORE = {
'Arch', 'intg', 'real', '1per', '2per', '3per', 'GNdr', 'Ms-f',
'anim', 'inan',
'masc', 'femn', 'neut',
'Geox', 'Name',
} | OpencorporaTag.CASES | OpencorporaTag.NUMBERS | OpencorporaTag.MOODS \
| OpencorporaTag.INVOLV... | class POSFeatureExtractor(FeatureExtractor):
| IGNORE = {
'Arch', 'intg', 'real', '1per', '2per', '3per', 'GNdr', 'Ms-f',
'anim', 'inan',
'masc', 'femn', 'neut',
'Geox', 'Name',
} | OpencorporaTag.CASES | OpencorporaTag.NUMBERS | OpencorporaTag.MOODS \
| OpencorporaTag.INVOLVEMENT
def __init__(self):
super(... | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from morphine import features
from morphine.feature_extractor import FeatureExtractor
from morphine.basetagger import PartialTagger
from pymorphy2.tagset import OpencorporaTag
class POSFeatureExtractor(FeatureExtractor):
| 65 | 99 | 330 | 8 | 56 | kmike/morphine | morphine/pos_model.py | Python | POSFeatureExtractor | POSFeatureExtractor | 10 | 46 | 10 | 10 | 1874f0148c74bc1ec0a95993410cfd89959f8a96 | bigcode/the-stack | train |
cdb932d77b56f4b025f4b2ab | train | class | class SplitView(object):
def __init__(self, controller):
self.controller = controller
controller.events.after_dispatch += self.on_after_dispatch
controller.events.before_dispatch += self.on_before_dispatch
controller.events.scaffold_before_apply += self.on_scaffold_before_apply
... | class SplitView(object):
| def __init__(self, controller):
self.controller = controller
controller.events.after_dispatch += self.on_after_dispatch
controller.events.before_dispatch += self.on_before_dispatch
controller.events.scaffold_before_apply += self.on_scaffold_before_apply
def on_before_dispatch(se... | import logging
from ferris.core.response_handlers import ResponseHandler
import types
class NoneHandler(ResponseHandler):
type = types.NoneType
def process(self, handler, result):
if handler.meta.view.auto_render:
handler._clear_redirect()
handler.response = handler.meta.view.... | 71 | 242 | 808 | 5 | 65 | harshp8l/deep-learning-lang-detection | data/train/python/de23129f509cbda732ab6b2fad9cf3e8f787cff7split_view.py | Python | SplitView | SplitView | 16 | 119 | 16 | 17 | a7efc592b57f65d9f59e8e628d80fde0bb20f6f6 | bigcode/the-stack | train |
1ab35033296f1715337f2d9e | train | class | class NoneHandler(ResponseHandler):
type = types.NoneType
def process(self, handler, result):
if handler.meta.view.auto_render:
handler._clear_redirect()
handler.response = handler.meta.view.render()
return handler.response
| class NoneHandler(ResponseHandler):
| type = types.NoneType
def process(self, handler, result):
if handler.meta.view.auto_render:
handler._clear_redirect()
handler.response = handler.meta.view.render()
return handler.response
| import logging
from ferris.core.response_handlers import ResponseHandler
import types
class NoneHandler(ResponseHandler):
| 22 | 64 | 50 | 6 | 15 | harshp8l/deep-learning-lang-detection | data/train/python/de23129f509cbda732ab6b2fad9cf3e8f787cff7split_view.py | Python | NoneHandler | NoneHandler | 6 | 13 | 6 | 6 | 98c01be32c1e352ce5f08eff061b26f84f89b0f1 | bigcode/the-stack | train |
56e316095c75ffc9d815cdad | train | class | class SyntaxErrorInOwnersFile(Exception):
def __init__(self, path, lineno, msg):
super(SyntaxErrorInOwnersFile, self).__init__((path, lineno, msg))
self.path = path
self.lineno = lineno
self.msg = msg
def __str__(self):
return '%s:%d syntax error: %s' % (self.path, self.lineno, self.msg)
| class SyntaxErrorInOwnersFile(Exception):
| def __init__(self, path, lineno, msg):
super(SyntaxErrorInOwnersFile, self).__init__((path, lineno, msg))
self.path = path
self.lineno = lineno
self.msg = msg
def __str__(self):
return '%s:%d syntax error: %s' % (self.path, self.lineno, self.msg)
| member
# pylint: disable=no-member
if hasattr(collections_abc, 'Iterable') and hasattr(collections_abc, 'Sized'):
assert (isinstance(obj, collections_abc.Iterable) and
isinstance(obj, collections_abc.Sized))
class SyntaxErrorInOwnersFile(Exception):
| 64 | 64 | 93 | 8 | 56 | khanhdd26/deport_tool | owners.py | Python | SyntaxErrorInOwnersFile | SyntaxErrorInOwnersFile | 98 | 106 | 98 | 98 | 65cc371bac3f585ec1247c76eef5774e0ccccc03 | bigcode/the-stack | train |
7aa926d4cac1dbce19ef4ce2 | train | function | def _assert_is_collection(obj):
assert not isinstance(obj, str)
# Module 'collections' has no 'Iterable' member
# pylint: disable=no-member
if hasattr(collections_abc, 'Iterable') and hasattr(collections_abc, 'Sized'):
assert (isinstance(obj, collections_abc.Iterable) and
isinstance(obj, collect... | def _assert_is_collection(obj):
| assert not isinstance(obj, str)
# Module 'collections' has no 'Iterable' member
# pylint: disable=no-member
if hasattr(collections_abc, 'Iterable') and hasattr(collections_abc, 'Sized'):
assert (isinstance(obj, collections_abc.Iterable) and
isinstance(obj, collections_abc.Sized))
| %\.]+\@[\w\-\+\%\.]+$'
# Key for global comments per email address. Should be unlikely to be a
# pathname.
GLOBAL_STATUS = '*'
# Returned if there is no owner and anyone +1
ANYONE='<anyone>'
def _assert_is_collection(obj):
| 63 | 64 | 82 | 7 | 56 | khanhdd26/deport_tool | owners.py | Python | _assert_is_collection | _assert_is_collection | 89 | 95 | 89 | 89 | 500965ff67fa841de13652bd40def76d8d65c05c | bigcode/the-stack | train |
009850caa117208a4a3ce514 | train | class | class Database(object):
"""A database of OWNERS files for a repository.
This class allows you to find a suggested set of reviewers for a list
of changed files, and see if a list of changed files is covered by a
list of reviewers."""
def __init__(self, root, fopen, os_path):
"""Args:
root: the path... | class Database(object):
| """A database of OWNERS files for a repository.
This class allows you to find a suggested set of reviewers for a list
of changed files, and see if a list of changed files is covered by a
list of reviewers."""
def __init__(self, root, fopen, os_path):
"""Args:
root: the path to the root of the Repo... | email addresses. Very simplistic.
BASIC_EMAIL_REGEXP = r'^[\w\-\+\%\.]+\@[\w\-\+\%\.]+$'
# Key for global comments per email address. Should be unlikely to be a
# pathname.
GLOBAL_STATUS = '*'
# Returned if there is no owner and anyone +1
ANYONE='<anyone>'
def _assert_is_collection(obj):
assert not isinstance(o... | 256 | 256 | 4,687 | 4 | 252 | khanhdd26/deport_tool | owners.py | Python | Database | Database | 109 | 645 | 109 | 109 | 695a0d4d7748265bea0174450ff8e10d9d26ffe2 | bigcode/the-stack | train |
10608b00f1185e4610eb9e60 | train | class | class ROI(Group):
"""
Class that defines a Region-Of-Interest (ROI)
Attributes:
-----------
* left # Left channel
* right # Right channel
* name # Name of the ROI
* address # Address of the ROI (PV name, for example)
* bgr_width # Number of channels to use for backgr... | class ROI(Group):
| """
Class that defines a Region-Of-Interest (ROI)
Attributes:
-----------
* left # Left channel
* right # Right channel
* name # Name of the ROI
* address # Address of the ROI (PV name, for example)
* bgr_width # Number of channels to use for background subtraction
... | Mark Rivers, GSECARS
* Modified for Tdl, tpt
* simplified, modified for larch, M Newville
"""
import numpy as np
from larch import Group
MODDOC = '''
X-ray Fluorescence Routines
The functions here include (but are not limited too):
function descrption
------------ ------------------------------
create_... | 227 | 227 | 758 | 4 | 222 | bruceravel/xraylarch | plugins/xrf/roi.py | Python | ROI | ROI | 40 | 123 | 40 | 40 | 041d5837c582715b8717a3dec8168b8a98a36aca | bigcode/the-stack | train |
709575bb73b62869df89525b | train | function | def registerLarchPlugin():
return ('_xrf', {'create_roi': create_roi})
| def registerLarchPlugin():
| return ('_xrf', {'create_roi': create_roi})
| gr_width=bgr_width, address=address)
def initializeLarchPlugin(_larch=None):
"""initialize _io"""
if _larch is not None:
mod = getattr(_larch.symtable, '_xrf')
mod.__doc__ = MODDOC
def registerLarchPlugin():
| 64 | 64 | 20 | 6 | 57 | bruceravel/xraylarch | plugins/xrf/roi.py | Python | registerLarchPlugin | registerLarchPlugin | 154 | 155 | 154 | 154 | af724c8be46341374dddaac2e32b8c381b6de182 | bigcode/the-stack | train |
c1b86a2f30243b812cd5075d | train | function | def split_roiname(name):
words = name.split()
elem = words[0].title()
line = 'ka'
if len(words) > 1:
line = words[1]
line = line.title()
if line == 'Ka': line = 'Ka1'
if line == 'Kb': line = 'Kb1'
if line == 'La': line = 'La1'
if line == 'Lb': line = 'Lb1'
return elem, li... | def split_roiname(name):
| words = name.split()
elem = words[0].title()
line = 'ka'
if len(words) > 1:
line = words[1]
line = line.title()
if line == 'Ka': line = 'Ka1'
if line == 'Kb': line = 'Kb1'
if line == 'La': line = 'La1'
if line == 'Lb': line = 'Lb1'
return elem, line
| are not limited too):
function descrption
------------ ------------------------------
create_roi create an ROI
read_xmap_netcdf read netcdf file from XIA XMap DXP
read_xrfmap read GSE XRF Map (HDF5) file
'''
def split_roiname(name):
| 64 | 64 | 107 | 6 | 58 | bruceravel/xraylarch | plugins/xrf/roi.py | Python | split_roiname | split_roiname | 27 | 38 | 27 | 27 | 4d6866e1c435ee9db909fad2b4e546419199d1cb | bigcode/the-stack | train |
aa2c86d234e27c8996ca1fec | train | function | def create_roi(name, left, right, bgr_width=3, address='', _larch=None):
"""create an ROI, a named portion of an MCA spectra defined by index
Parameters:
------------
name: roi name
left: left index
right: right index
bgr_width (optional) background width (default=3)
... | def create_roi(name, left, right, bgr_width=3, address='', _larch=None):
| """create an ROI, a named portion of an MCA spectra defined by index
Parameters:
------------
name: roi name
left: left index
right: right index
bgr_width (optional) background width (default=3)
address (optional) address (PV name) for ROI
Returns:
... | +1].sum()
self.net = self.total - bgr_counts*(self.right-self.left)
out = self.total
if net:
out = self.net
return out
def create_roi(name, left, right, bgr_width=3, address='', _larch=None):
| 64 | 64 | 171 | 22 | 41 | bruceravel/xraylarch | plugins/xrf/roi.py | Python | create_roi | create_roi | 125 | 145 | 125 | 125 | c87854adb67d566f78e6ade8d95341210107bc9d | bigcode/the-stack | train |
463d1ea01b9723ccf91fe70e | train | function | def initializeLarchPlugin(_larch=None):
"""initialize _io"""
if _larch is not None:
mod = getattr(_larch.symtable, '_xrf')
mod.__doc__ = MODDOC
| def initializeLarchPlugin(_larch=None):
| """initialize _io"""
if _larch is not None:
mod = getattr(_larch.symtable, '_xrf')
mod.__doc__ = MODDOC
| , width, bgr_width
and methods
set_bounds(left, right)
get_counts(data, net=False)
"""
return ROI(name=name, left=left, right=right,
bgr_width=bgr_width, address=address)
def initializeLarchPlugin(_larch=None):
| 64 | 64 | 48 | 10 | 54 | bruceravel/xraylarch | plugins/xrf/roi.py | Python | initializeLarchPlugin | initializeLarchPlugin | 148 | 152 | 148 | 148 | 845eb8ed6b953542fd8e3c7651a5f83dc56976a0 | bigcode/the-stack | train |
2ecb12aff31882987994d3b8 | train | class | class TranslationSchema(ma.ModelSchema):
""" Translation Marshmallow schema """
# Make term_id required
term_id = field_for(Translation, 'term_id',
required=True,
)
translation = field_for(Translation, 'translation',
required=Tr... | class TranslationSchema(ma.ModelSchema):
| """ Translation Marshmallow schema """
# Make term_id required
term_id = field_for(Translation, 'term_id',
required=True,
)
translation = field_for(Translation, 'translation',
required=True,
validate=... | # If the tag does not exist, create it and yield the new tag's ID
new_tag = Tag(name=tag_name)
db.session.add(new_tag)
db.session.commit()
yield new_tag.id
else:
# If the tag exists, return it's ID
yield tag.id
class TranslationSchema(ma.M... | 72 | 72 | 243 | 7 | 64 | adyouri/lafza | project/schemas.py | Python | TranslationSchema | TranslationSchema | 32 | 66 | 32 | 32 | 612de830fd3953cf211d7adbab09d6900b470722 | bigcode/the-stack | train |
89d2fe69c5a4197d6a2347c5 | train | function | def tags_to_tag_ids(tags):
"""
A generator that takes a list of string tag names
and yields IDs of these tags if they exist
or creates new tags and returns their IDs
:param: tags: a list of string tag names
"""
for tag_name in tags:
# Query the tag
tag = Tag.query.filter_by(n... | def tags_to_tag_ids(tags):
| """
A generator that takes a list of string tag names
and yields IDs of these tags if they exist
or creates new tags and returns their IDs
:param: tags: a list of string tag names
"""
for tag_name in tags:
# Query the tag
tag = Tag.query.filter_by(name=tag_name).one_or_none()... | marshmallow import pre_dump, validate, pre_load, post_load
from project.models import db, Term, Translation, Tag, User
from project.auth import guard
from flask_marshmallow import Marshmallow
from marshmallow_sqlalchemy import field_for
ma = Marshmallow()
def tags_to_tag_ids(tags):
| 64 | 64 | 157 | 7 | 57 | adyouri/lafza | project/schemas.py | Python | tags_to_tag_ids | tags_to_tag_ids | 11 | 29 | 11 | 11 | a775ea5216b1725c8655ccf085fecd9c17f4e759 | bigcode/the-stack | train |
c20c2e9c1a15b755f63e2987 | train | class | class TermSchema(ma.ModelSchema):
term = field_for(Term, 'term',
required=True,
validate=validate.Length(min=2, max=100))
full_term = field_for(Term, 'full_term',
validate=validate.Length(min=2, max=100))
# Flask-Marshmallow SQLAlchemy in... | class TermSchema(ma.ModelSchema):
| term = field_for(Term, 'term',
required=True,
validate=validate.Length(min=2, max=100))
full_term = field_for(Term, 'full_term',
validate=validate.Length(min=2, max=100))
# Flask-Marshmallow SQLAlchemy integration
class Meta:
... | modified data
return data
@pre_load
def load_translation(self, data):
if 'tags' in data.keys() and data['tags']:
data = self.add_translation_tags(data)
else:
data['tags'] = []
return data
class TermSchema(ma.ModelSchema):
| 64 | 64 | 154 | 7 | 56 | adyouri/lafza | project/schemas.py | Python | TermSchema | TermSchema | 69 | 91 | 69 | 69 | 82ddabe1d3e00c9bd784fb57fad13fa96045c38b | bigcode/the-stack | train |
bfa8f4e5b4a6d2ded3fb3827 | train | class | class UserSchema(ma.ModelSchema):
class Meta:
model = User
username = field_for(User, 'username',
required=True,
validate=validate.Length(min=3, max=25),
)
password = field_for(User, 'password',
req... | class UserSchema(ma.ModelSchema):
| class Meta:
model = User
username = field_for(User, 'username',
required=True,
validate=validate.Length(min=3, max=25),
)
password = field_for(User, 'password',
required=True,
... | downvoters',
'upvoters'),
)
@pre_dump()
def make_acronym(self, data):
""" Convert acronyms to uppercase """
if data and data.is_acronym:
data.term = data.term.upper()
return data
class UserSchema(ma.ModelSche... | 64 | 64 | 149 | 7 | 56 | adyouri/lafza | project/schemas.py | Python | UserSchema | UserSchema | 94 | 120 | 94 | 94 | 58e9a6d4f882b275cb12e976466bc10639c2e212 | bigcode/the-stack | train |
51604b4c6c297fb908653117 | train | function | def main():
with open(f"{getcwd()}/2021/day09/input.txt") as file:
heightmap = [[c for c in line.strip()] for line in file]
lowPoints = []
for y, hl in enumerate(heightmap):
for x, h in enumerate(hl):
adjacents = adjacent(x, y, len(hl), len(heightmap))
if a... | def main():
| with open(f"{getcwd()}/2021/day09/input.txt") as file:
heightmap = [[c for c in line.strip()] for line in file]
lowPoints = []
for y, hl in enumerate(heightmap):
for x, h in enumerate(hl):
adjacents = adjacent(x, y, len(hl), len(heightmap))
if all(heightmap[... | xs, y + ys)
for xs, ys in [(0, 1), (1, 0), (0, -1), (-1, 0)]
if 0 <= x + xs < maxX and 0 <= y + ys < maxY
]
def main():
| 63 | 64 | 132 | 3 | 60 | kilbouri/advent-of-code | 2021/day09/part1.py | Python | main | main | 12 | 24 | 12 | 12 | bf45c27c2210f702cd28dc03128ccfa0a7a59f3a | bigcode/the-stack | train |
8dea18a0153663908e73d8f2 | train | function | def adjacent(x, y, maxX, maxY):
return [
(x + xs, y + ys)
for xs, ys in [(0, 1), (1, 0), (0, -1), (-1, 0)]
if 0 <= x + xs < maxX and 0 <= y + ys < maxY
]
| def adjacent(x, y, maxX, maxY):
| return [
(x + xs, y + ys)
for xs, ys in [(0, 1), (1, 0), (0, -1), (-1, 0)]
if 0 <= x + xs < maxX and 0 <= y + ys < maxY
]
| from os import getcwd
def adjacent(x, y, maxX, maxY):
| 18 | 64 | 79 | 12 | 5 | kilbouri/advent-of-code | 2021/day09/part1.py | Python | adjacent | adjacent | 4 | 9 | 4 | 4 | 0b6db13a3e56c3852f88b1d1e9cf7b08248969c9 | bigcode/the-stack | train |
57089cedc28bf3ab69041f9d | train | class | @skip("Confirmation page feature doesn't support 1.0.x yet")
class ModerationConfirmationFormSubmissionTest(BaseTestCase):
def setUp(self):
self.cp = ConfirmationPage.objects.create(name="Checklist Form")
self.role1.confirmation_page = self.cp
self.role1.save()
def test_throws_exception... | @skip("Confirmation page feature doesn't support 1.0.x yet")
class ModerationConfirmationFormSubmissionTest(BaseTestCase):
| def setUp(self):
self.cp = ConfirmationPage.objects.create(name="Checklist Form")
self.role1.confirmation_page = self.cp
self.role1.save()
def test_throws_exception_when_form_data_is_invalid(self):
with self.assertRaises(ValueError) as context:
moderation_confirmatio... | .cms_plugins import (
ModerationFormPlugin,
)
from djangocms_moderation.handlers import moderation_confirmation_form_submission
from djangocms_moderation.models import ConfirmationFormSubmission, ConfirmationPage
from .utils.base import BaseTestCase
@skip("Confirmation page feature doesn't support 1.0.x yet")
clas... | 78 | 78 | 260 | 26 | 51 | adam-murray/djangocms-moderation | tests/test_handlers.py | Python | ModerationConfirmationFormSubmissionTest | ModerationConfirmationFormSubmissionTest | 12 | 44 | 12 | 13 | 43d56b6c012b92bd3ab4cc715721ca225ff2f0b8 | bigcode/the-stack | train |
78158d82f40840896e51dd56 | train | function | @fixture
def make_config():
def _inner(override: dict = None):
config = ConfigParser(DEFAULTS)
config.add_section("snapshottest")
if override:
config.read_dict({"snapshottest": override})
return config
return _inner
| @fixture
def make_config():
| def _inner(override: dict = None):
config = ConfigParser(DEFAULTS)
config.add_section("snapshottest")
if override:
config.read_dict({"snapshottest": override})
return config
return _inner
| from configparser import ConfigParser
from pytest import fixture
from snapshottest.config import DEFAULTS
pytest_plugins = "pytester"
@fixture
def make_config():
| 35 | 64 | 59 | 7 | 28 | kam193/snapshottest | tests/conftest.py | Python | make_config | make_config | 10 | 19 | 10 | 11 | 5c46faa71972c13a867348046328fe0cce8e386e | bigcode/the-stack | train |
67119a6e10b974b24de79be5 | train | function | def test_ordered_links():
d = dict_fuller(60)
links = ordered_links(d, 0, 1)
nand = num_active_nodes(d, links)
assert nand == 10
| def test_ordered_links():
| d = dict_fuller(60)
links = ordered_links(d, 0, 1)
nand = num_active_nodes(d, links)
assert nand == 10
| sys
sys.path.insert(0,'../src')
from active_nodes import (ordered_links, num_active_nodes, ip_ordered_vertices,
ip_list_objects_from_vlist, ip_get_dn, ip_num_active_elements)
from domains import ZZ
from graphs_gen import dict_fuller
def test_ordered_links():
| 64 | 64 | 45 | 6 | 57 | pernici/hobj | tests/test_active_nodes.py | Python | test_ordered_links | test_ordered_links | 9 | 13 | 9 | 9 | 355d64935a85113eabfabf98f9abffce3e25a211 | bigcode/the-stack | train |
baaa245c41473289b2fa1755 | train | function | def test_ip_num_active_elements1():
d = dict_fuller(60)
dn = ip_get_dn(d)
links0 = [0, d[0][0]]
vlist = ip_ordered_vertices(d, *links0)
objects = ip_list_objects_from_vlist(d, vlist)
nu = ip_num_active_elements(objects)
assert nu == 11
| def test_ip_num_active_elements1():
| d = dict_fuller(60)
dn = ip_get_dn(d)
links0 = [0, d[0][0]]
vlist = ip_ordered_vertices(d, *links0)
objects = ip_list_objects_from_vlist(d, vlist)
nu = ip_num_active_elements(objects)
assert nu == 11
| import ZZ
from graphs_gen import dict_fuller
def test_ordered_links():
d = dict_fuller(60)
links = ordered_links(d, 0, 1)
nand = num_active_nodes(d, links)
assert nand == 10
def test_ip_num_active_elements1():
| 64 | 64 | 82 | 8 | 55 | pernici/hobj | tests/test_active_nodes.py | Python | test_ip_num_active_elements1 | test_ip_num_active_elements1 | 15 | 22 | 15 | 15 | 87506c6ff8a98091d5277b8c0dc4ddb23867af9f | bigcode/the-stack | train |
12c3984b0e8a12c3e109af44 | train | function | def test_ip_num_active_elements2():
d = dict_fuller(36)
dn = ip_get_dn(d)
links0 = [0, d[0][0]]
vlist = ip_ordered_vertices(d, *links0)
objects = ip_list_objects_from_vlist(d, vlist)
nu = ip_num_active_elements(objects)
assert nu == 8
| def test_ip_num_active_elements2():
| d = dict_fuller(36)
dn = ip_get_dn(d)
links0 = [0, d[0][0]]
vlist = ip_ordered_vertices(d, *links0)
objects = ip_list_objects_from_vlist(d, vlist)
nu = ip_num_active_elements(objects)
assert nu == 8
| links0 = [0, d[0][0]]
vlist = ip_ordered_vertices(d, *links0)
objects = ip_list_objects_from_vlist(d, vlist)
nu = ip_num_active_elements(objects)
assert nu == 11
def test_ip_num_active_elements2():
| 64 | 64 | 82 | 8 | 55 | pernici/hobj | tests/test_active_nodes.py | Python | test_ip_num_active_elements2 | test_ip_num_active_elements2 | 25 | 32 | 25 | 25 | 05a5b1cbe19bea1ead4592e8092ce685cbffb055 | bigcode/the-stack | train |
41ebb2f6852d70d6f573d137 | train | class | class SentenceAugmenter(Augmenter):
def __init__(
self,
action,
name="Sentence_Aug",
stopwords=None,
tokenizer=None,
reverse_tokenizer=None,
device="cuda",
include_detail=False,
parallelable=True,
verbose=0,
):
super().__ini... | class SentenceAugmenter(Augmenter):
| def __init__(
self,
action,
name="Sentence_Aug",
stopwords=None,
tokenizer=None,
reverse_tokenizer=None,
device="cuda",
include_detail=False,
parallelable=True,
verbose=0,
):
super().__init__(
name=name,
... | import re
from nlpaug.util import Method
from nlpaug.util.text.tokenizer import Tokenizer
from nlpaug import Augmenter
class SentenceAugmenter(Augmenter):
| 42 | 67 | 226 | 10 | 31 | lucidworks/nlpaug | nlpaug/augmenter/sentence/sentence_augmenter.py | Python | SentenceAugmenter | SentenceAugmenter | 8 | 47 | 8 | 8 | d30fee958b72972f8c0b242b1d5866b9ae5e99c9 | bigcode/the-stack | train |
5cc093afbf225f7e4055634b | train | class | class Solution:
def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
min_heap = []
heapq.heapify(min_heap)
for x, y in points:
dist = x ** 2 + y ** 2
heapq.heappush(min_heap, [dist, x, y])
ans = []
for _ in range(K):
dist... | class Solution:
| def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
min_heap = []
heapq.heapify(min_heap)
for x, y in points:
dist = x ** 2 + y ** 2
heapq.heappush(min_heap, [dist, x, y])
ans = []
for _ in range(K):
dist, x, y = heapq.h... | # https://leetcode.com/problems/k-closest-points-to-origin
import heapq
class Solution:
| 21 | 64 | 112 | 3 | 17 | Wattyyy/LeetCode | submissions/k-closest-points-to-origin/solution.py | Python | Solution | Solution | 6 | 17 | 6 | 6 | fcb7787df3fda5d8b45011d4ef9096fe782ce0b1 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.