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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
de747b34e68450fec3a28a5f | train | class | class ListTransactionsTest(BitcoinTestFramework):
def __init__(self):
super().__init__()
self.num_nodes = 4
self.setup_clean_chain = False
def setup_nodes(self):
#This test requires mocktime
enable_mocktime()
return start_nodes(self.num_nodes, self.options.tmpdir... | class ListTransactionsTest(BitcoinTestFramework):
| def __init__(self):
super().__init__()
self.num_nodes = 4
self.setup_clean_chain = False
def setup_nodes(self):
#This test requires mocktime
enable_mocktime()
return start_nodes(self.num_nodes, self.options.tmpdir)
def run_test(self):
# Simple send, ... | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Exercise the listtransactions API
from test_framework.test_framework import BitcoinTestFramework
from ... | 134 | 256 | 2,459 | 9 | 124 | quasarcoin/quasar | qa/rpc-tests/listtransactions.py | Python | ListTransactionsTest | ListTransactionsTest | 19 | 200 | 19 | 19 | a7b60665478475c7cbf807d2c2a635bcfa86ce2f | bigcode/the-stack | train |
c7144fd2c900ad762cbfc3b3 | train | function | def txFromHex(hexstring):
tx = CTransaction()
f = BytesIO(hex_str_to_bytes(hexstring))
tx.deserialize(f)
return tx
| def txFromHex(hexstring):
| tx = CTransaction()
f = BytesIO(hex_str_to_bytes(hexstring))
tx.deserialize(f)
return tx
|
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Exercise the listtransactions API
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
from test_framework.mininode import CTransaction, COIN
from io import BytesIO
def txFromHex(hexstring):
| 64 | 64 | 34 | 7 | 56 | quasarcoin/quasar | qa/rpc-tests/listtransactions.py | Python | txFromHex | txFromHex | 13 | 17 | 13 | 13 | 502eb134d4398e7f1348d170642bd6351194b4c0 | bigcode/the-stack | train |
3953c797b275a6298f19a0f0 | train | class | class Migration(migrations.Migration):
dependencies = [
('bibtex', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='entry',
name='author',
field=models.CharField(default='', max_length=200),
preserve_default=False,
)... | class Migration(migrations.Migration):
| dependencies = [
('bibtex', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='entry',
name='author',
field=models.CharField(default='', max_length=200),
preserve_default=False,
),
migrations.AddField(
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
| 31 | 64 | 99 | 7 | 23 | RTSYork/bibtex | bibtex/migrations/0002_auto_20141013_2248.py | Python | Migration | Migration | 7 | 26 | 7 | 8 | d99c6ccf55d12685f5227301dffbb74ba048a6b2 | bigcode/the-stack | train |
637c501188f4950c32b2b945 | train | class | class Procno:
"""
Parse a Procno lines to extract the optimized parameters
class variables:
procno : the procno number where optimization is done
params : a list containning the optimized parameters
params[i] is a dict with keys (name, values, optmode, optgroup)
... | class Procno:
| """
Parse a Procno lines to extract the optimized parameters
class variables:
procno : the procno number where optimization is done
params : a list containning the optimized parameters
params[i] is a dict with keys (name, values, optmode, optgroup)
name : name o... | ):
self.lines = lines
# retrieve the name of expno where 2D ser is stored
for l in lines:
if l.find("Target directory for serfile:") == 0:
self.serDir = l.split(':')[1].strip()
#split report in procnos
#search index where a procno starts in lines
... | 202 | 202 | 674 | 4 | 198 | jtrebosc/JTutils | CpyLib/PoptProtocol.py | Python | Procno | Procno | 97 | 153 | 97 | 97 | 58bc971a9c50aa17e3060b86758ea4868d14ed3a | bigcode/the-stack | train |
8a566eaba34a042716085887 | train | class | class PoptProtocol:
"""
Parse a popt.protocol file then split it into reports
class variables:
reports : a list of Report instances
"""
def __init__(self, lines):
""" splits a popt.protocol into reports lines. Reports are splitted according to the line starting with Report
... | class PoptProtocol:
| """
Parse a popt.protocol file then split it into reports
class variables:
reports : a list of Report instances
"""
def __init__(self, lines):
""" splits a popt.protocol into reports lines. Reports are splitted according to the line starting with Report
"""
#sea... | values']
Data access through PoptProtocol.reports[i].procnos[j].tableIndex[k]['index'|'params[l]['name']]
"""
from __future__ import division, print_function
import numpy as n
# split popt.protocol in poptau reports in Report list
class PoptProtocol:
| 64 | 64 | 178 | 5 | 58 | jtrebosc/JTutils | CpyLib/PoptProtocol.py | Python | PoptProtocol | PoptProtocol | 46 | 65 | 46 | 46 | fc6aea9fd8c7e10caf9e9f0ff7b8ebb40450a07d | bigcode/the-stack | train |
81496f7c2bc66faf389311ac | train | class | class Report:
"""
Parse a Report lines then split it into procnos
class variables:
procnos : a list of Procno instances
serDir : path to dataset where 2D fids are stored
"""
def __init__(self, lines):
self.lines = lines
# retrieve the name of expno where 2D ser is ... | class Report:
| """
Parse a Report lines then split it into procnos
class variables:
procnos : a list of Procno instances
serDir : path to dataset where 2D fids are stored
"""
def __init__(self, lines):
self.lines = lines
# retrieve the name of expno where 2D ser is stored
... | in lines :
if l.find("Report") == 0 : ls.append(i)
i += 1
ls.append(len(lines)) # appends the last line as last index
self.reports = []
for i in range(len(ls)-1):
self.reports.append(Report(lines[ls[i]:ls[i+1]]))
class Report:
| 77 | 78 | 261 | 3 | 74 | jtrebosc/JTutils | CpyLib/PoptProtocol.py | Python | Report | Report | 68 | 94 | 68 | 68 | 04f5d833c60d47fd7f9b7d1e7f7f4c978c6517b1 | bigcode/the-stack | train |
72e4817164ed988a0441e782 | train | class | class Solution(object):
def findContentChildren(self, children, s):
"""
:type g: List[int]
:type s: List[int]
:rtype: int
"""
if not s:
return 0
cookies = Counter(s)
it = iter(sorted(cookies))
cur = it.next()
children.sort()... | class Solution(object):
| def findContentChildren(self, children, s):
"""
:type g: List[int]
:type s: List[int]
:rtype: int
"""
if not s:
return 0
cookies = Counter(s)
it = iter(sorted(cookies))
cur = it.next()
children.sort()
ans = 0
... | from collections import Counter
class Solution(object):
| 9 | 64 | 135 | 4 | 4 | ckclark/leetcode | py/assign-cookies.py | Python | Solution | Solution | 2 | 24 | 2 | 2 | 4d01dfea51e405d3ce83a0488ed09de324f6dc34 | bigcode/the-stack | train |
416a8cc7e47ed089dc8741d7 | train | function | @editor_blueprint.route('/editor/import', methods=['POST'])
@admin_login_required
def import_engine():
# Checks to make sure a file was uploaded
if 'file' not in request.files:
return {'success': False}, 500
file = request.files['file']
# Checks to make sure the file has an actual name and not j... | @editor_blueprint.route('/editor/import', methods=['POST'])
@admin_login_required
def import_engine():
# Checks to make sure a file was uploaded
| if 'file' not in request.files:
return {'success': False}, 500
file = request.files['file']
# Checks to make sure the file has an actual name and not just empty
if file.filename == '':
return {'success': False}, 500
# Checks to make sure the file extension/type is allowed
if '.' ... | _id).get().get('story_name'))
db.collection('stories').document(engine_id).delete()
return {'success': True}, 200
@editor_blueprint.route('/editor/import', methods=['POST'])
@admin_login_required
def import_engine():
# Checks to make sure a file was uploaded
| 64 | 64 | 202 | 33 | 30 | bugenelu/JIB-0330 | server/src/editor_blueprint.py | Python | import_engine | import_engine | 155 | 173 | 155 | 158 | c04ca668440b4faa5fb775c0264d173b55f3515d | bigcode/the-stack | train |
d9bf4dbd7ce93725876dcac5 | train | function | @editor_blueprint.route('/import_uploads')
@admin_login_required
def import_files():
file_data = json.load(open(os.path.join('import_uploads', secure_filename('upload.json'))))
os.remove(os.path.join('import_uploads', secure_filename('upload.json')))
return json.dumps(file_data) | @editor_blueprint.route('/import_uploads')
@admin_login_required
def import_files():
| file_data = json.load(open(os.path.join('import_uploads', secure_filename('upload.json'))))
os.remove(os.path.join('import_uploads', secure_filename('upload.json')))
return json.dumps(file_data) | specified upload folder
file.save(os.path.join('import_uploads', filename))
#flash('File uploaded successfully')
return {'success': False}, 200
return {'success': False}, 500
@editor_blueprint.route('/import_uploads')
@admin_login_required
def import_files():
| 64 | 64 | 65 | 19 | 44 | bugenelu/JIB-0330 | server/src/editor_blueprint.py | Python | import_files | import_files | 176 | 181 | 176 | 178 | 386e057d472cb600e4aa401e0aa26ea36a40ffc9 | bigcode/the-stack | train |
7b85ed31f838b586f325cc89 | train | function | @editor_blueprint.route('/editor/update_live_story', methods=['POST'])
def update_live_story():
if current_user is not None and current_user.admin == True:
new_live_story = request.form['new_live_story']
live_story_data = {'active_story_id': new_live_story,
'active_story_ref':... | @editor_blueprint.route('/editor/update_live_story', methods=['POST'])
def update_live_story():
| if current_user is not None and current_user.admin == True:
new_live_story = request.form['new_live_story']
live_story_data = {'active_story_id': new_live_story,
'active_story_ref': db.collection('stories').document(new_live_story)}
app_states = db.collection('applicati... | ('story_name')
except KeyError:
print('No Live Story Field')
return {'story_id': live_story, 'story_name': story_name}, 200
return None, 200
@editor_blueprint.route('/editor/update_live_story', methods=['POST'])
def update_live_story():
| 64 | 64 | 115 | 21 | 42 | bugenelu/JIB-0330 | server/src/editor_blueprint.py | Python | update_live_story | update_live_story | 81 | 90 | 81 | 82 | e4d39b4d6603cbceca392e442c3391c10e35f2c6 | bigcode/the-stack | train |
74c26dfe5e269cd9f653768a | train | function | @editor_blueprint.route('/editor/save_story', methods=['POST'])
def save_story():
if current_user is not None and current_user.admin == True:
story_id = request.form['story_id']
story_data = json.loads(request.form['story_data'])
confirm_save = request.form['confirm_save'] != 'false'
... | @editor_blueprint.route('/editor/save_story', methods=['POST'])
def save_story():
| if current_user is not None and current_user.admin == True:
story_id = request.form['story_id']
story_data = json.loads(request.form['story_data'])
confirm_save = request.form['confirm_save'] != 'false'
live_story_id = db.collection('application_states').document('application_state')... | list': new_live_story}, 200
@editor_blueprint.route('/editor/open_story/<story_id>', methods=['GET'])
def open_story(story_id):
if current_user is not None and current_user.admin == True:
story_data = db.collection('stories').document(story_id)
if story_data.get().exists:
# return story... | 148 | 148 | 495 | 19 | 128 | bugenelu/JIB-0330 | server/src/editor_blueprint.py | Python | save_story | save_story | 102 | 137 | 102 | 103 | 8e9a65cc7a63bd5a7ff05db67034b3eff19980ef | bigcode/the-stack | train |
92c0e9795a9a196b8e497eee | train | function | @editor_blueprint.route('/editor/open_story/<story_id>', methods=['GET'])
def open_story(story_id):
if current_user is not None and current_user.admin == True:
story_data = db.collection('stories').document(story_id)
if story_data.get().exists:
# return story_data # should return some su... | @editor_blueprint.route('/editor/open_story/<story_id>', methods=['GET'])
def open_story(story_id):
| if current_user is not None and current_user.admin == True:
story_data = db.collection('stories').document(story_id)
if story_data.get().exists:
# return story_data # should return some success code
# return json.dumps({'success': True}), 200, story_data.get().to_dict()
... | (new_live_story)}
app_states = db.collection('application_states')
app_states.document('application_state').update(live_story_data)
return {'list': new_live_story}, 200
@editor_blueprint.route('/editor/open_story/<story_id>', methods=['GET'])
def open_story(story_id):
| 64 | 64 | 120 | 24 | 39 | bugenelu/JIB-0330 | server/src/editor_blueprint.py | Python | open_story | open_story | 92 | 100 | 92 | 93 | 3662e8dd5fd2a34bbf4b2801f7661ed70c880408 | bigcode/the-stack | train |
73191abfcebfda040e9e54b5 | train | function | @editor_blueprint.route('/editor/view_live_story', methods=['GET'])
def view_live_story():
if current_user is not None and current_user.admin == True:
app_states = db.collection('application_states')
# all_stories = [story for story in stories]
app_state = list(app_states.list_documents())[0... | @editor_blueprint.route('/editor/view_live_story', methods=['GET'])
def view_live_story():
| if current_user is not None and current_user.admin == True:
app_states = db.collection('application_states')
# all_stories = [story for story in stories]
app_state = list(app_states.list_documents())[0]
live_story = 'NONE'
try:
live_story = app_state.get().get('ac... | in stories]
child_doc = list(stories.list_documents())
child_doc = [child.id for child in child_doc]
return {'list': child_doc}, 200
return None, 500
@editor_blueprint.route('/editor/view_live_story', methods=['GET'])
def view_live_story():
| 64 | 64 | 153 | 20 | 43 | bugenelu/JIB-0330 | server/src/editor_blueprint.py | Python | view_live_story | view_live_story | 66 | 79 | 66 | 67 | 90bc282ec233271441bf25f04b3a31362e04b752 | bigcode/the-stack | train |
a4c6ada43425ee996745b41e | train | function | @editor_blueprint.route('/editor/get_all_stories', methods=['GET'])
def get_all_stories():
if current_user is not None and current_user.admin == True:
stories = db.collection('stories')
# all_stories = [story for story in stories]
child_doc = list(stories.list_documents())
child_doc ... | @editor_blueprint.route('/editor/get_all_stories', methods=['GET'])
def get_all_stories():
| if current_user is not None and current_user.admin == True:
stories = db.collection('stories')
# all_stories = [story for story in stories]
child_doc = list(stories.list_documents())
child_doc = [child.id for child in child_doc]
story_names = []
for doc in child_doc:
... | ', __name__)
# editor = Editor(db)
@editor_blueprint.route('/editor/init_editor', methods=['GET', 'POST'])
def init_editor():
return f'initialized editor with {db}'
@editor_blueprint.route('/editor/get_all_stories', methods=['GET'])
def get_all_stories():
| 63 | 64 | 138 | 22 | 41 | bugenelu/JIB-0330 | server/src/editor_blueprint.py | Python | get_all_stories | get_all_stories | 40 | 53 | 40 | 41 | 5f07aadf57593bf4b4e5bcb35087388db2220e1f | bigcode/the-stack | train |
c42b2d69d268467736132693 | train | function | @editor_blueprint.route('/editor/load_all_stories', methods=['GET'])
def load_all_stories():
if current_user is not None and current_user.admin == True:
stories = db.collection('stories')
# all_stories = [story for story in stories]
child_doc = list(stories.list_documents())
child_do... | @editor_blueprint.route('/editor/load_all_stories', methods=['GET'])
def load_all_stories():
| if current_user is not None and current_user.admin == True:
stories = db.collection('stories')
# all_stories = [story for story in stories]
child_doc = list(stories.list_documents())
child_doc = [child.id for child in child_doc]
return {'list': child_doc}, 200
return... | (db.collection('stories').document(doc).get().get('story_name'))
return {'story_id': child_doc, 'story_name': story_names}, 200
return None, 500
@editor_blueprint.route('/editor/load_all_stories', methods=['GET'])
def load_all_stories():
| 64 | 64 | 98 | 22 | 41 | bugenelu/JIB-0330 | server/src/editor_blueprint.py | Python | load_all_stories | load_all_stories | 55 | 64 | 55 | 56 | 144ba4621e92829532b8d4a0573e8c510b6a9ab5 | bigcode/the-stack | train |
de24c89f0f5d37e77f078bd5 | train | function | @editor_blueprint.route('/editor/delete_engine', methods=['POST'])
def delete_engine():
if current_user is not None and current_user.admin == True:
live_story = db.collection('application_states').document('application_state').get().get('active_story_id')
engine_id = request.form['engine_id']
... | @editor_blueprint.route('/editor/delete_engine', methods=['POST'])
def delete_engine():
| if current_user is not None and current_user.admin == True:
live_story = db.collection('application_states').document('application_state').get().get('active_story_id')
engine_id = request.form['engine_id']
if engine_id == live_story:
return {'success': False}, 200
... | else:
stories.document(story_id).set(story_data)
return {'success': True, 'retry': False, 'msg': 'Story successfully saved'}, 200, {'ContentType': 'application/json'}
@editor_blueprint.route('/editor/delete_engine', methods=['POST'])
def delete_engine():
| 63 | 64 | 128 | 18 | 45 | bugenelu/JIB-0330 | server/src/editor_blueprint.py | Python | delete_engine | delete_engine | 140 | 152 | 140 | 141 | 306023c776b38e66486b413b47b8fdab60cd1465 | bigcode/the-stack | train |
5d36fd1c58104437435df164 | train | function | @editor_blueprint.route('/editor/init_editor', methods=['GET', 'POST'])
def init_editor():
return f'initialized editor with {db}'
| @editor_blueprint.route('/editor/init_editor', methods=['GET', 'POST'])
def init_editor():
| return f'initialized editor with {db}'
| # from story_editing.Editor import Editor
from utils import db
from users import current_user, admin_login_required
editor_blueprint = Blueprint('editor_blueprint', __name__)
# editor = Editor(db)
@editor_blueprint.route('/editor/init_editor', methods=['GET', 'POST'])
def init_editor():
| 64 | 64 | 31 | 21 | 43 | bugenelu/JIB-0330 | server/src/editor_blueprint.py | Python | init_editor | init_editor | 36 | 38 | 36 | 37 | c25f13786055b077f3e4153c5f832fef85d26462 | bigcode/the-stack | train |
408f8af2ecb658c4146367c1 | train | function | def generate_input_data (input_dataset,input_data_nm):
##for the training dataset
X, y = load_data(input_dataset) # sequences, labels
# print(X) ##Note: X is the ['AA','BB','CC]
# print(y) ##Note: y is the ['C1','C2','C3']
X = generate_mats(X) # convert to array of represent... | def generate_input_data (input_dataset,input_data_nm):
##for the training dataset
| X, y = load_data(input_dataset) # sequences, labels
# print(X) ##Note: X is the ['AA','BB','CC]
# print(y) ##Note: y is the ['C1','C2','C3']
X = generate_mats(X) # convert to array of representation matrices
# convert to integer labels
y = conv_labels(y, input_data_nm)
... | epoch_' + eval_name + '.txt', 'w+') as opt:
for eachepoch in epoch_dic:
opt.write(eachepoch + '\t' + epoch_dic[eachepoch] + '\n')
def generate_input_data (input_dataset,input_data_nm):
##for the training dataset
| 63 | 64 | 154 | 18 | 45 | LiLabAtVT/DeepTE | example_train_script/classify_TE_keras_model_predict_kmer.py | Python | generate_input_data | generate_input_data | 45 | 61 | 45 | 47 | 2331b36161a8669bb382f1b201eb6802e375b1da | bigcode/the-stack | train |
39b131b1c47d5b902ed43351 | train | function | def train_model (input_train_dataset,input_test_dataset,input_store_class_report_dir,store_all_score_dic):
##get the name of input train data set
mt = re.match('.+\/shuffle_(.+)_CNN_data.txt',input_train_dataset)
input_data_nm = mt.group(1)
##change the class_num according to the input_data_nm
c... | def train_model (input_train_dataset,input_test_dataset,input_store_class_report_dir,store_all_score_dic):
##get the name of input train data set
| mt = re.match('.+\/shuffle_(.+)_CNN_data.txt',input_train_dataset)
input_data_nm = mt.group(1)
##change the class_num according to the input_data_nm
class_num = 0 ##input the class number which is a binary classification
#['All', 'ClassI', 'ClassII', 'LTR', 'noLTR', 'DNA', 'MITE', 'noMITE']
if... | )
##write out results
with open(input_store_class_report_dir + '/' + input_data_nm + '_epoch_' + eval_name + '.txt', 'w+') as opt:
for eachepoch in epoch_dic:
opt.write(eachepoch + '\t' + epoch_dic[eachepoch] + '\n')
def generate_input_data (input_dataset,input_data_nm):
##for the tr... | 256 | 256 | 1,925 | 33 | 223 | LiLabAtVT/DeepTE | example_train_script/classify_TE_keras_model_predict_kmer.py | Python | train_model | train_model | 64 | 258 | 64 | 67 | 4d2fa2ff8df1e6947aeb310692ea8a7c107b474b | bigcode/the-stack | train |
5294963fc199a99b15cc7a3d | train | function | def write_acc_epoch (input_eval_list,input_store_class_report_dir,input_data_nm,eval_name):
##store the accuracy, and loss to the opt
epoch_dic = {}
epoch_acc_count = 0
for eacheval in input_eval_list:
epoch_acc_count += 1
epoch_dic[str(epoch_acc_count)] = str(eacheval)
##write out ... | def write_acc_epoch (input_eval_list,input_store_class_report_dir,input_data_nm,eval_name):
##store the accuracy, and loss to the opt
| epoch_dic = {}
epoch_acc_count = 0
for eacheval in input_eval_list:
epoch_acc_count += 1
epoch_dic[str(epoch_acc_count)] = str(eacheval)
##write out results
with open(input_store_class_report_dir + '/' + input_data_nm + '_epoch_' + eval_name + '.txt', 'w+') as opt:
for eachep... |
import matplotlib.pyplot as plt
import re
##import classification_report helps us to detect the accuracy for each specific class
from sklearn.metrics import classification_report
def write_acc_epoch (input_eval_list,input_store_class_report_dir,input_data_nm,eval_name):
##store the accuracy, and loss to the opt... | 64 | 64 | 144 | 32 | 31 | LiLabAtVT/DeepTE | example_train_script/classify_TE_keras_model_predict_kmer.py | Python | write_acc_epoch | write_acc_epoch | 30 | 41 | 30 | 32 | 853c023e1f524413fc7b86484c703b8b8ce48f01 | bigcode/the-stack | train |
8f76ab70fa6df91bf46a50d4 | train | function | def main():
if '--total' in sys.argv:
total = sys.argv[sys.argv.index('--total')+1]
else:
total = None
if '--pb' in sys.argv and total is not None:
from pyprogress import ThreadedProgressBar
c = ThreadedProgressBar(int(total), timecount=True, completionprediction=True, color... | def main():
| if '--total' in sys.argv:
total = sys.argv[sys.argv.index('--total')+1]
else:
total = None
if '--pb' in sys.argv and total is not None:
from pyprogress import ThreadedProgressBar
c = ThreadedProgressBar(int(total), timecount=True, completionprediction=True, colored=True)
... | #! /usr/bin/python
# -*- coding: utf-8 -*-
import sys
def main():
| 20 | 64 | 184 | 3 | 16 | mouckatron/pyprogress | pyprogress/countoutput.py | Python | main | main | 7 | 38 | 7 | 7 | 4e5554f1ccc504e8128787b06cfb8de4ff6fbbef | bigcode/the-stack | train |
090db598207280489e5f1031 | train | function | async def on_startup(app):
await postgresql.initialize(app['config']['database'])
| async def on_startup(app):
| await postgresql.initialize(app['config']['database'])
|
from aiohttp import web
from tt_web import log
from tt_web import postgresql
async def on_startup(app):
| 27 | 64 | 18 | 7 | 19 | al-arz/the-tale | src/tt_events_log/tt_events_log/service.py | Python | on_startup | on_startup | 8 | 9 | 8 | 8 | 6837aae9d17ae269de888e645b8bad52583d938d | bigcode/the-stack | train |
676aec3221f2988365d1bd08 | train | function | def create_application(config, loop=None):
app = web.Application()
app['config'] = config
log.initilize(config['log'])
app.on_startup.append(on_startup)
app.on_cleanup.append(on_cleanup)
register_routers(app)
return app
| def create_application(config, loop=None):
| app = web.Application()
app['config'] = config
log.initilize(config['log'])
app.on_startup.append(on_startup)
app.on_cleanup.append(on_cleanup)
register_routers(app)
return app
| app.router.add_post('/add-event', handlers.add_event)
app.router.add_post('/get-events', handlers.get_events)
app.router.add_post('/get-last-events', handlers.get_last_events)
app.router.add_post('/debug-clear-service', handlers.debug_clear_service)
def create_application(config, loop=None):
| 64 | 64 | 59 | 8 | 56 | al-arz/the-tale | src/tt_events_log/tt_events_log/service.py | Python | create_application | create_application | 26 | 38 | 26 | 26 | 6479d48d3840380baf8eef9b10420317ce99f425 | bigcode/the-stack | train |
0b076b64e5b5a9b62adecacd | train | function | def register_routers(app):
from . import handlers
app.router.add_post('/add-event', handlers.add_event)
app.router.add_post('/get-events', handlers.get_events)
app.router.add_post('/get-last-events', handlers.get_last_events)
app.router.add_post('/debug-clear-service', handlers.debug_clear_service... | def register_routers(app):
| from . import handlers
app.router.add_post('/add-event', handlers.add_event)
app.router.add_post('/get-events', handlers.get_events)
app.router.add_post('/get-last-events', handlers.get_last_events)
app.router.add_post('/debug-clear-service', handlers.debug_clear_service)
|
from aiohttp import web
from tt_web import log
from tt_web import postgresql
async def on_startup(app):
await postgresql.initialize(app['config']['database'])
async def on_cleanup(app):
await postgresql.deinitialize()
def register_routers(app):
| 58 | 64 | 68 | 6 | 52 | al-arz/the-tale | src/tt_events_log/tt_events_log/service.py | Python | register_routers | register_routers | 16 | 23 | 16 | 16 | 00e0497a1e3ec35b5e0dd8cab35e9b856c70ee2c | bigcode/the-stack | train |
7bb0c49ed103b2c7dde9f084 | train | function | async def on_cleanup(app):
await postgresql.deinitialize()
| async def on_cleanup(app):
| await postgresql.deinitialize()
|
from aiohttp import web
from tt_web import log
from tt_web import postgresql
async def on_startup(app):
await postgresql.initialize(app['config']['database'])
async def on_cleanup(app):
| 44 | 64 | 13 | 6 | 38 | al-arz/the-tale | src/tt_events_log/tt_events_log/service.py | Python | on_cleanup | on_cleanup | 12 | 13 | 12 | 12 | 699cd20b949a24ba4e2a7a3358846d41e24fab20 | bigcode/the-stack | train |
fd99e0a2f4594e71bfa84a91 | train | function | def typecheck(value: Any, expected: Union[Type, Tuple[Type, ...]]) -> None:
if not isinstance(value, expected):
raise ValueError(f"Expected a value of type {expected}, got value of type {type(value)}")
| def typecheck(value: Any, expected: Union[Type, Tuple[Type, ...]]) -> None:
| if not isinstance(value, expected):
raise ValueError(f"Expected a value of type {expected}, got value of type {type(value)}")
| NettingChannelState,
NetworkState,
UnlockPartialProofState,
)
MYPY_ANNOTATION = "This assert is used to tell mypy what is the type of the variable"
def typecheck(value: Any, expected: Union[Type, Tuple[Type, ...]]) -> None:
| 64 | 64 | 53 | 22 | 42 | tirkarthi/raiden | raiden/utils/typing.py | Python | typecheck | typecheck | 63 | 65 | 63 | 63 | 15d8a428ef17aa6e1d7b7237ace574dc7414a759 | bigcode/the-stack | train |
dac480460e5eb255c896e801 | train | class | class BatchView(APIView):
permission_classes = []
def get_requests_consumer_class(self):
mod, inst = app_settings.REQUESTS_CONSUMER_BACKEND.rsplit('.', 1)
mod = import_module(mod)
return getattr(mod, inst)
def get_requests_consumer(self):
return self.get_requests_consumer_c... | class BatchView(APIView):
| permission_classes = []
def get_requests_consumer_class(self):
mod, inst = app_settings.REQUESTS_CONSUMER_BACKEND.rsplit('.', 1)
mod = import_module(mod)
return getattr(mod, inst)
def get_requests_consumer(self):
return self.get_requests_consumer_class()()
@transaction... | import django
from importlib import import_module
from django.db import transaction
from rest_framework.response import Response
from rest_framework.views import APIView
from drf_batch_requests import settings as app_settings
from drf_batch_requests.exceptions import RequestAttributeError
from drf_batch_requests.gra... | 130 | 148 | 495 | 6 | 123 | 1844144/drf-batch-requests | drf_batch_requests/views.py | Python | BatchView | BatchView | 22 | 95 | 22 | 22 | cbc0d93e570fd5e61c0b907a13f70be07f860c75 | bigcode/the-stack | train |
a50d7e7dbccec8133868c7fc | train | class | class AssignmentTransformation(BaseObject):
""" Transform GitHub Assignments into the Cendant Field Structure """
def __init__(self,
issue_id: int or str,
parent_id: str,
manifest_name: str,
repo_name: str,
svcresult: dict,
... | class AssignmentTransformation(BaseObject):
| """ Transform GitHub Assignments into the Cendant Field Structure """
def __init__(self,
issue_id: int or str,
parent_id: str,
manifest_name: str,
repo_name: str,
svcresult: dict,
is_debug: bool = False):
... | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
from base import BaseObject
from base import DataTypeError
from base import FieldStructure
from base import MandatoryParamError
from base import RecordStructure
class AssignmentTransformation(BaseObject):
| 53 | 208 | 695 | 6 | 46 | jiportilla/ontology | python/datagit/ingest/github/dmo/assignment_transformation.py | Python | AssignmentTransformation | AssignmentTransformation | 12 | 108 | 12 | 12 | fcde1de99694c40ad4b5f38688bf7eea1331e1fb | bigcode/the-stack | train |
357ad37fc534f99e01f6bb8b | train | function | @app.route('/add_transaction', methods = ['POST'])
def add_transaction():
json = request.get_json()
transaction_keys = ['sender','receiver','amount']
if not all(key in json for key in transaction_keys):
return 'Have elements missing!',400
index = blockchain.add_transaction(json['sender'],j... | @app.route('/add_transaction', methods = ['POST'])
def add_transaction():
| json = request.get_json()
transaction_keys = ['sender','receiver','amount']
if not all(key in json for key in transaction_keys):
return 'Have elements missing!',400
index = blockchain.add_transaction(json['sender'],json['receiver'],json['amount'])
response = {'message': f'This transacti... | chain.chain)
if is_valid:
response = {'message': 'All Ok, this blockchain is valid!'}
else:
response = {'message': 'This Blockchain is not valid!'}
return jsonify(response), 200
@app.route('/add_transaction', methods = ['POST'])
def add_transaction():
| 64 | 64 | 100 | 15 | 48 | wilianfialho/FeatherNEXT-Blockchain | FeatherNEXT CryptoCoin/FeatherNext.py | Python | add_transaction | add_transaction | 126 | 134 | 126 | 127 | 253f26154ae1706e18dd6859d6f8480fd982897b | bigcode/the-stack | train |
1bc9bfe9bcca07f587c4a710 | train | function | @app.route('/mine_block', methods = ['GET'])
def mine_block():
previous_block = blockchain.get_previous_block()
previous_proof = previous_block['proof']
proof = blockchain.proof_of_work(previous_proof)
previous_hash = blockchain.hash(previous_block)
blockchain.add_transaction(sender = node_add... | @app.route('/mine_block', methods = ['GET'])
def mine_block():
| previous_block = blockchain.get_previous_block()
previous_proof = previous_block['proof']
proof = blockchain.proof_of_work(previous_proof)
previous_hash = blockchain.hash(previous_block)
blockchain.add_transaction(sender = node_address, receiver = 'Wilian', amount = 1)
block = blockchain.cr... | longest_chain = chain
if longest_chain:
self.chain = longest_chain
return True
return False
app = Flask(__name__)
node_address = str(uuid4()).replace('-', '')
blockchain = Blockchain()
@app.route('/mine_block', methods = ['GET'])
def mine_block()... | 64 | 64 | 154 | 15 | 49 | wilianfialho/FeatherNEXT-Blockchain | FeatherNEXT CryptoCoin/FeatherNext.py | Python | mine_block | mine_block | 95 | 109 | 95 | 96 | 2332c97747039e6d2f48ca3d767e7501156433f8 | bigcode/the-stack | train |
3939ddabd1a50ab2654212d5 | train | function | @app.route('/is_valid', methods = ['GET'])
def is_valid():
is_valid = blockchain.is_chain_valid(blockchain.chain)
if is_valid:
response = {'message': 'All Ok, this blockchain is valid!'}
else:
response = {'message': 'This Blockchain is not valid!'}
return jsonify(response), 200
| @app.route('/is_valid', methods = ['GET'])
def is_valid():
| is_valid = blockchain.is_chain_valid(blockchain.chain)
if is_valid:
response = {'message': 'All Ok, this blockchain is valid!'}
else:
response = {'message': 'This Blockchain is not valid!'}
return jsonify(response), 200
| return jsonify(response), 200
@app.route('/get_chain', methods = ['GET'])
def get_chain():
response = {'chain': blockchain.chain,
'length': len(blockchain.chain)}
return jsonify(response), 200
@app.route('/is_valid', methods = ['GET'])
def is_valid():
| 64 | 64 | 73 | 15 | 48 | wilianfialho/FeatherNEXT-Blockchain | FeatherNEXT CryptoCoin/FeatherNext.py | Python | is_valid | is_valid | 117 | 124 | 117 | 118 | 301d5167c2d81b2a5aecb09af856833aa2146cda | bigcode/the-stack | train |
d6c2de8738381e3007e2d01b | train | class | class Blockchain:
def __init__(self):
self.chain = []
self.transactions = []
self.create_block(proof = 1, previous_hash = '0')
self.nodes = set()
def create_block(self, proof, previous_hash):
block = {'index': len(self.chain) + 1,
'tim... | class Blockchain:
| def __init__(self):
self.chain = []
self.transactions = []
self.create_block(proof = 1, previous_hash = '0')
self.nodes = set()
def create_block(self, proof, previous_hash):
block = {'index': len(self.chain) + 1,
'timestamp': str(datetime... | import datetime
import hashlib
import json
from flask import Flask, jsonify, request
import requests
from uuid import uuid4
from urllib.parse import urlparse
class Blockchain:
| 37 | 175 | 584 | 3 | 33 | wilianfialho/FeatherNEXT-Blockchain | FeatherNEXT CryptoCoin/FeatherNext.py | Python | Blockchain | Blockchain | 9 | 87 | 9 | 10 | b24476d9fce2cd95278e8b3a435b6a07dfa7b587 | bigcode/the-stack | train |
8c9bf6f93756d0b46e3f05a4 | train | function | @app.route('/connect_node', methods = ['POST'])
def connect_node():
json = request.get_json()
nodes = json.get('nodes')
if nodes is None:
return "Empty", 400
for node in nodes:
blockchain.add_node(node)
response = {'message': 'All Nodes Connected, blockchain have this blocks:... | @app.route('/connect_node', methods = ['POST'])
def connect_node():
| json = request.get_json()
nodes = json.get('nodes')
if nodes is None:
return "Empty", 400
for node in nodes:
blockchain.add_node(node)
response = {'message': 'All Nodes Connected, blockchain have this blocks:',
'total_nodes': list(blockchain.nodes)}
return... | missing!',400
index = blockchain.add_transaction(json['sender'],json['receiver'],json['amount'])
response = {'message': f'This transaction will be put in next block{index}'}
return jsonify(response),201
@app.route('/connect_node', methods = ['POST'])
def connect_node():
| 64 | 64 | 90 | 15 | 48 | wilianfialho/FeatherNEXT-Blockchain | FeatherNEXT CryptoCoin/FeatherNext.py | Python | connect_node | connect_node | 136 | 146 | 136 | 137 | e6671e6e9f0f5b4c6355846cad83fafb2288e0e5 | bigcode/the-stack | train |
530aced34a5ca18faa4b31c5 | train | function | @app.route('/replace_chain',methods= ['GET'])
def replace_chain():
is_chain_replaced = blockchain.replace_chain()
if is_chain_replaced:
response = {'message': 'The nodes have other chains, else substituted. ',
'new_chain' : blockchain.chain}
else:
response = {'mess... | @app.route('/replace_chain',methods= ['GET'])
def replace_chain():
| is_chain_replaced = blockchain.replace_chain()
if is_chain_replaced:
response = {'message': 'The nodes have other chains, else substituted. ',
'new_chain' : blockchain.chain}
else:
response = {'message': 'All ok, not need substitution. ',
'actual... | 400
for node in nodes:
blockchain.add_node(node)
response = {'message': 'All Nodes Connected, blockchain have this blocks:',
'total_nodes': list(blockchain.nodes)}
return jsonify(response),201
@app.route('/replace_chain',methods= ['GET'])
def replace_chain():
| 64 | 64 | 95 | 15 | 48 | wilianfialho/FeatherNEXT-Blockchain | FeatherNEXT CryptoCoin/FeatherNext.py | Python | replace_chain | replace_chain | 148 | 157 | 148 | 149 | 72f3a9365efdfd9571c639e55e509a1e12c62516 | bigcode/the-stack | train |
cc250abe393c34c756879c62 | train | function | @app.route('/get_chain', methods = ['GET'])
def get_chain():
response = {'chain': blockchain.chain,
'length': len(blockchain.chain)}
return jsonify(response), 200
| @app.route('/get_chain', methods = ['GET'])
def get_chain():
| response = {'chain': blockchain.chain,
'length': len(blockchain.chain)}
return jsonify(response), 200
| index': block['index'],
'timestamp': block['timestamp'],
'proof': block['proof'],
'previous_hash': block['previous_hash'],
'transactions': block['transactions']}
return jsonify(response), 200
@app.route('/get_chain', methods = ['GET'])
def get_ch... | 64 | 64 | 41 | 15 | 48 | wilianfialho/FeatherNEXT-Blockchain | FeatherNEXT CryptoCoin/FeatherNext.py | Python | get_chain | get_chain | 111 | 115 | 111 | 112 | 1efcfbf93aa51a46405b0638b89c8c936f14ed69 | bigcode/the-stack | train |
a8da652c9f483112cbc1a1c1 | train | class | class TzScanRewardApi(RewardApi):
def __init__(self, nw, baking_address):
super().__init__()
self.api = API[nw['NAME']]
if self.api is None:
raise Exception("Unknown network {}".format(nw))
self.baking_address = baking_address
def get_nb_delegators(self, cycle):
... | class TzScanRewardApi(RewardApi):
| def __init__(self, nw, baking_address):
super().__init__()
self.api = API[nw['NAME']]
if self.api is None:
raise Exception("Unknown network {}".format(nw))
self.baking_address = baking_address
def get_nb_delegators(self, cycle):
resp = requests.get(self.api... | scan.io/v1/'.format(api_mirror)},
'ALPHANET': {'API_URL': 'http://alphanet-api.tzscan.io/v1/'},
'ZERONET': {'API_URL': 'http://zeronet-api.tzscan.io/v1/'}
}
class TzScanRewardApi(RewardApi):
| 72 | 72 | 243 | 10 | 62 | tezosland/tezos-reward-distributer | TzScanRewardApi.py | Python | TzScanRewardApi | TzScanRewardApi | 18 | 45 | 18 | 19 | e0fe17e8567c69baf0c3133229f2c42d3a522553 | bigcode/the-stack | train |
0e42f490a01daf5b24b4fa0a | train | class | class Migration(migrations.Migration):
dependencies = [
('api', '0016_auto_20180928_0635'),
]
operations = [
migrations.AlterField(
model_name='accommodation',
name='title',
field=models.CharField(default=uuid.UUID('1f0da4fc-a572-4eed-b763-7acd1466f75f')... | class Migration(migrations.Migration):
| dependencies = [
('api', '0016_auto_20180928_0635'),
]
operations = [
migrations.AlterField(
model_name='accommodation',
name='title',
field=models.CharField(default=uuid.UUID('1f0da4fc-a572-4eed-b763-7acd1466f75f'), max_length=100),
),
]
| # Generated by Django 2.1.1 on 2018-09-28 06:35
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
| 41 | 64 | 91 | 7 | 33 | seannguyn/airbnb | airbnbClone/api/migrations/0017_auto_20180928_0635.py | Python | Migration | Migration | 7 | 19 | 7 | 8 | f741770572d112d53ea2c8706382e69fa77fc3d1 | bigcode/the-stack | train |
fae0c948ea4fb8b697653d84 | train | class | class TwoStageBetween(TwoStagePyDDM):
def __init__(self, dt=0.01, dx=0.01, T_dur=3, agentVars=None, label=None):
"""[summary]
Parameters
----------
Agent : [type]
[description]
agentVars : [type], optional
[description], by default None
"""
... | class TwoStageBetween(TwoStagePyDDM):
| def __init__(self, dt=0.01, dx=0.01, T_dur=3, agentVars=None, label=None):
"""[summary]
Parameters
----------
Agent : [type]
[description]
agentVars : [type], optional
[description], by default None
"""
super().__init__(agentVars=agent... | from ddm import BoundConstant, Drift, Fittable, Model, NoiseConstant
from src.models.ddms.pyddmTwoStage import TwoStagePyDDM
class TwoStageBetween(TwoStagePyDDM):
| 46 | 211 | 704 | 11 | 34 | moltaire/gaze-choice-causality | src/models/ddms/TwoStageBetween.py | Python | TwoStageBetween | TwoStageBetween | 6 | 95 | 6 | 6 | 59b103e3406a940bb7e6b7fb6e804b1605fcab04 | bigcode/the-stack | train |
595e460832d3bb5c4a981167 | train | class | class TwoStageBetweenDrift(Drift):
"""Drift class for the Two-Stage Within-alternative integration pyDDM."""
name = "Gaze-biased between-alternative integration Stage II drift"
required_parameters = ["wp", "eta", "v", "b_last"]
required_conditions = [
"p0",
"p1",
"m0",
"... | class TwoStageBetweenDrift(Drift):
| """Drift class for the Two-Stage Within-alternative integration pyDDM."""
name = "Gaze-biased between-alternative integration Stage II drift"
required_parameters = ["wp", "eta", "v", "b_last"]
required_conditions = [
"p0",
"p1",
"m0",
"m1",
"gp",
"gm",
... | 001, maxval=4)),
bound=BoundConstant(B=1),
dx=self.dx,
dt=self.dt,
T_dur=self.T_dur,
)
self.model = model
self.required_conditions = [
"p0",
"p1",
"m0",
"m1",
"gp",
"gm",
... | 105 | 105 | 350 | 10 | 94 | moltaire/gaze-choice-causality | src/models/ddms/TwoStageBetween.py | Python | TwoStageBetweenDrift | TwoStageBetweenDrift | 98 | 136 | 98 | 98 | 9b5e2b1d59358cc44a576de4c00427abee61a9e1 | bigcode/the-stack | train |
1e3168723c352861a2860e86 | train | function | def build_backbone(cfg):
return build_from_config(cfg, BACKBONES)
| def build_backbone(cfg):
| return build_from_config(cfg, BACKBONES)
| OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import paddle.vision.models as models
from ...utils.registry import Registry, build_from_config
BACKBONES = Registry("BACKBONE")
def build_backbone(cfg):
| 64 | 64 | 17 | 6 | 58 | juneweng/PASSL | passl/modeling/backbones/builder.py | Python | build_backbone | build_backbone | 22 | 23 | 22 | 22 | 0642f63e79ec1750227f84336cd6b5fd86df945a | bigcode/the-stack | train |
b7ef25e2bf17606ea2e1f974 | train | class | class Discovery(SimpleTestCase):
def test_precedence(self):
"""
Apps listed first in INSTALLED_APPS have precedence.
"""
with self.settings(INSTALLED_APPS=['admin_scripts.complex_app',
'admin_scripts.simple_app',
... | class Discovery(SimpleTestCase):
| def test_precedence(self):
"""
Apps listed first in INSTALLED_APPS have precedence.
"""
with self.settings(INSTALLED_APPS=['admin_scripts.complex_app',
'admin_scripts.simple_app',
'django.contrib.au... | "EXECUTE:LabelCommand label=anotherlabel, options=[('force_color', "
"False), ('no_color', False), ('pythonpath', None), "
"('settings', None), ('traceback', False), ('verbosity', 1)]"
)
class Discovery(SimpleTestCase):
| 64 | 64 | 161 | 6 | 58 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | Discovery | Discovery | 1,799 | 1,818 | 1,799 | 1,800 | 56c321dc08b16e5070a83de7d8a22158e672ef60 | bigcode/the-stack | train |
ff87aac1b7926ffdf94ee970 | train | class | class Dumpdata(AdminScriptTestCase):
"""Tests for dumpdata management command."""
def setUp(self):
super().setUp()
self.write_settings('settings.py')
def test_pks_parsing(self):
"""Regression for #20509
Test would raise an exception rather than printing an error message.
... | class Dumpdata(AdminScriptTestCase):
| """Tests for dumpdata management command."""
def setUp(self):
super().setUp()
self.write_settings('settings.py')
def test_pks_parsing(self):
"""Regression for #20509
Test would raise an exception rather than printing an error message.
"""
args = ['dumpdata'... | out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, " APPEND_SLASH = True")
self.assertOutput(out, "+ FOO = 'bar'")
self.assertOutput(out, "- SECRET_KEY = ''")
class Dumpdata(AdminScriptTestCase):
| 64 | 64 | 118 | 8 | 56 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | Dumpdata | Dumpdata | 2,245 | 2,260 | 2,245 | 2,245 | 3ffc6d1b66ed39993828f60aa272003d854b75fb | bigcode/the-stack | train |
2a1e31c9ed54cf1b289fde08 | train | class | class DjangoAdminAlternateSettings(AdminScriptTestCase):
"""A series of tests for django-admin.py when using a settings file
with a name other than 'settings.py'.
"""
def setUp(self):
super().setUp()
self.write_settings('alternate_settings.py')
def test_builtin_command(self):
... | class DjangoAdminAlternateSettings(AdminScriptTestCase):
| """A series of tests for django-admin.py when using a settings file
with a name other than 'settings.py'.
"""
def setUp(self):
super().setUp()
self.write_settings('alternate_settings.py')
def test_builtin_command(self):
"alternate: django-admin builtin commands fail with an ... | NoOutput(out)
self.assertOutput(err, "No Django settings specified")
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_settings(self):
"minimal: django-admin can't execute user commands, even if settings are provided as argument"
args = ['noarg... | 194 | 195 | 652 | 10 | 185 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | DjangoAdminAlternateSettings | DjangoAdminAlternateSettings | 410 | 473 | 410 | 410 | cd6af2854301723787ffdda7208811ab70915546 | bigcode/the-stack | train |
5d27de74b905109617c266e4 | train | class | class ManageRunserverMigrationWarning(TestCase):
def setUp(self):
self.stdout = StringIO()
self.runserver_command = RunserverCommand(stdout=self.stdout)
@override_settings(INSTALLED_APPS=["admin_scripts.app_waiting_migration"])
def test_migration_warning_one_app(self):
self.runserv... | class ManageRunserverMigrationWarning(TestCase):
| def setUp(self):
self.stdout = StringIO()
self.runserver_command = RunserverCommand(stdout=self.stdout)
@override_settings(INSTALLED_APPS=["admin_scripts.app_waiting_migration"])
def test_migration_warning_one_app(self):
self.runserver_command.check_migrations()
output = sel... | .check_migrations() doesn't choke when a database is read-only.
"""
with mock.patch.object(MigrationRecorder, 'has_table', return_value=False):
self.cmd.check_migrations()
# You have # ...
self.assertIn('unapplied migration(s)', self.output.getvalue())
class ManageRunserverMi... | 69 | 69 | 230 | 9 | 60 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | ManageRunserverMigrationWarning | ManageRunserverMigrationWarning | 1,313 | 1,339 | 1,313 | 1,314 | 9f154590e0762e0ed985e116273fc7eabbc13aed | bigcode/the-stack | train |
933de18e6fc00a33339580a4 | train | class | class StartApp(AdminScriptTestCase):
def test_invalid_name(self):
"""startapp validates that app name is a valid Python identifier."""
for bad_name in ('7testproject', '../testproject'):
with self.subTest(app_name=bad_name):
args = ['startapp', bad_name]
... | class StartApp(AdminScriptTestCase):
| def test_invalid_name(self):
"""startapp validates that app name is a valid Python identifier."""
for bad_name in ('7testproject', '../testproject'):
with self.subTest(app_name=bad_name):
args = ['startapp', bad_name]
testproject_dir = os.path.join(self.te... | (custom_templates_dir, 'project_template')
args = ['startproject', '--template', template_path, '--extension=txt', 'customtestproject']
testproject_dir = os.path.join(self.test_dir, 'customtestproject')
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertT... | 155 | 156 | 523 | 8 | 147 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | StartApp | StartApp | 2,110 | 2,171 | 2,110 | 2,111 | 074f10c858b2e1a2df3dbf5eee899f31c3ca4226 | bigcode/the-stack | train |
0163e7af22c9c10fe937fa1b | train | class | class DjangoAdminMinimalSettings(AdminScriptTestCase):
"""A series of tests for django-admin.py when using a settings.py file that
doesn't contain the test application.
"""
def setUp(self):
super().setUp()
self.write_settings('settings.py', apps=['django.contrib.auth', 'django.contrib.co... | class DjangoAdminMinimalSettings(AdminScriptTestCase):
| """A series of tests for django-admin.py when using a settings.py file that
doesn't contain the test application.
"""
def setUp(self):
super().setUp()
self.write_settings('settings.py', apps=['django.contrib.auth', 'django.contrib.contenttypes'])
def test_builtin_command(self):
... | .run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "No Django settings specified")
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_settings(self):
"fulldefault: django-admin can execute user commands if settings are provi... | 202 | 202 | 675 | 10 | 192 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | DjangoAdminMinimalSettings | DjangoAdminMinimalSettings | 344 | 407 | 344 | 344 | acdafa4bea06d35f0f36adbbd3b1f2bfdc995eb9 | bigcode/the-stack | train |
832d773d166399a4da8a439c | train | class | class ColorCommand(BaseCommand):
requires_system_checks = False
def handle(self, *args, **options):
self.stdout.write('Hello, world!', self.style.ERROR)
self.stderr.write('Hello, world!', self.style.ERROR)
| class ColorCommand(BaseCommand):
| requires_system_checks = False
def handle(self, *args, **options):
self.stdout.write('Hello, world!', self.style.ERROR)
self.stderr.write('Hello, world!', self.style.ERROR)
| _handler=True,
use_threading=connection.features.test_db_allows_multiple_connections,
verbosity=1,
)
##########################################################################
# COMMAND PROCESSING TESTS
# user-space commands are correctly handled - in particular, arguments to
# the com... | 64 | 64 | 50 | 6 | 58 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | ColorCommand | ColorCommand | 1,401 | 1,406 | 1,401 | 1,401 | ac85cc0273b55c387d96aabc2b7bbd1005eb6489 | bigcode/the-stack | train |
60838451b53c52225e24b7d2 | train | class | class ArgumentOrder(AdminScriptTestCase):
"""Tests for 2-stage argument parsing scheme.
django-admin command arguments are parsed in 2 parts; the core arguments
(--settings, --traceback and --pythonpath) are parsed using a basic parser,
ignoring any unknown options. Then the full settings are
passe... | class ArgumentOrder(AdminScriptTestCase):
| """Tests for 2-stage argument parsing scheme.
django-admin command arguments are parsed in 2 parts; the core arguments
(--settings, --traceback and --pythonpath) are parsed using a basic parser,
ignoring any unknown options. Then the full settings are
passed to the command parser, which extracts co... | """
Apps listed first in INSTALLED_APPS have precedence.
"""
with self.settings(INSTALLED_APPS=['admin_scripts.complex_app',
'admin_scripts.simple_app',
'django.contrib.auth',
... | 156 | 156 | 521 | 8 | 148 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | ArgumentOrder | ArgumentOrder | 1,821 | 1,871 | 1,821 | 1,821 | 24b55965b4bd822af066a3d71195b9f102ef6f76 | bigcode/the-stack | train |
1499b268032b6ffc3dcbf507 | train | class | class ManageRunserverEmptyAllowedHosts(AdminScriptTestCase):
def setUp(self):
super().setUp()
self.write_settings('settings.py', sdict={
'ALLOWED_HOSTS': [],
'DEBUG': False,
})
def test_empty_allowed_hosts_error(self):
out, err = self.run_manage(['runserv... | class ManageRunserverEmptyAllowedHosts(AdminScriptTestCase):
| def setUp(self):
super().setUp()
self.write_settings('settings.py', sdict={
'ALLOWED_HOSTS': [],
'DEBUG': False,
})
def test_empty_allowed_hosts_error(self):
out, err = self.run_manage(['runserver'])
self.assertNoOutput(out)
self.assertOut... | value()
self.assertIn('You have 2 unapplied migration(s)', output)
self.assertIn(
'apply the migrations for app(s): another_app_waiting_migration, '
'app_waiting_migration.', output
)
class ManageRunserverEmptyAllowedHosts(AdminScriptTestCase):
| 64 | 64 | 102 | 12 | 52 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | ManageRunserverEmptyAllowedHosts | ManageRunserverEmptyAllowedHosts | 1,342 | 1,353 | 1,342 | 1,342 | 016f0124802e61156bef87bfc76df3c2e215dca0 | bigcode/the-stack | train |
baf62c92cba607e817166a55 | train | class | class AdminScriptTestCase(SimpleTestCase):
def setUp(self):
tmpdir = tempfile.TemporaryDirectory()
self.addCleanup(tmpdir.cleanup)
# os.path.realpath() is required for temporary directories on macOS,
# where `/var` is a symlink to `/private/var`.
self.test_dir = os.path.realp... | class AdminScriptTestCase(SimpleTestCase):
| def setUp(self):
tmpdir = tempfile.TemporaryDirectory()
self.addCleanup(tmpdir.cleanup)
# os.path.realpath() is required for temporary directories on macOS,
# where `/var` is a symlink to `/private/var`.
self.test_dir = os.path.realpath(os.path.join(tmpdir.name, 'test_project... | """
A series of tests to establish that the command-line management tools work as
advertised - especially with regards to the handling of the
DJANGO_SETTINGS_MODULE and default settings.py files.
"""
import os
import re
import shutil
import socket
import subprocess
import sys
import tempfile
import unittest
from io imp... | 239 | 256 | 1,201 | 9 | 230 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | AdminScriptTestCase | AdminScriptTestCase | 41 | 167 | 41 | 41 | db0e8a01f0b0a35dea3c677c74214167510492f2 | bigcode/the-stack | train |
2df7f1c29e145f79efc058a0 | train | class | class ManageMultipleSettings(AdminScriptTestCase):
"""A series of tests for manage.py when multiple settings files
(including the default 'settings.py') are available. The default settings
file is insufficient for performing the operations described, so the
alternate settings must be used by the running... | class ManageMultipleSettings(AdminScriptTestCase):
| """A series of tests for manage.py when multiple settings files
(including the default 'settings.py') are available. The default settings
file is insufficient for performing the operations described, so the
alternate settings must be used by the running script.
"""
def setUp(self):
super... | "EXECUTE: noargs_command options=[('force_color', False), "
"('no_color', False), ('pythonpath', None), ('settings', None), "
"('traceback', False), ('verbosity', 1)]"
)
self.assertNoOutput(err)
def test_custom_command_output_color(self):
"alternate: mana... | 199 | 199 | 666 | 9 | 190 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | ManageMultipleSettings | ManageMultipleSettings | 953 | 1,018 | 953 | 953 | c9b94169e032cd82ba5a07570417f7c885848999 | bigcode/the-stack | train |
4b97d86fc759a582f6517834 | train | class | class ManageRunserver(SimpleTestCase):
def setUp(self):
def monkey_run(*args, **options):
return
self.output = StringIO()
self.cmd = RunserverCommand(stdout=self.output)
self.cmd.run = monkey_run
def assertServerSettings(self, addr, port, ipv6=False, raw_ipv6=False)... | class ManageRunserver(SimpleTestCase):
| def setUp(self):
def monkey_run(*args, **options):
return
self.output = StringIO()
self.cmd = RunserverCommand(stdout=self.output)
self.cmd.run = monkey_run
def assertServerSettings(self, addr, port, ipv6=False, raw_ipv6=False):
self.assertEqual(self.cmd.add... | : Hint\n"
"\n"
"System check identified 3 issues (0 silenced).\n"
)
self.assertEqual(err, expected_err)
self.assertNoOutput(out)
def test_warning_does_not_halt(self):
"""
When there are only warnings or less serious messages, then Django
shoul... | 256 | 256 | 870 | 8 | 248 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | ManageRunserver | ManageRunserver | 1,226 | 1,310 | 1,226 | 1,226 | 09d164ae4bff36402060398e93f3417c84d8df38 | bigcode/the-stack | train |
337b072465e5908733d484ff | train | class | class DjangoAdminFullPathDefaultSettings(AdminScriptTestCase):
"""A series of tests for django-admin.py when using a settings.py file that
contains the test application specified using a full path.
"""
def setUp(self):
super().setUp()
self.write_settings('settings.py', ['django.contrib.a... | class DjangoAdminFullPathDefaultSettings(AdminScriptTestCase):
| """A series of tests for django-admin.py when using a settings.py file that
contains the test application specified using a full path.
"""
def setUp(self):
super().setUp()
self.write_settings('settings.py', ['django.contrib.auth', 'django.contrib.contenttypes',
... | args_command']
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "No Django settings specified")
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_settings(self):
"default: django-admin can execute u... | 207 | 207 | 693 | 12 | 195 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | DjangoAdminFullPathDefaultSettings | DjangoAdminFullPathDefaultSettings | 277 | 341 | 277 | 277 | d71b4e89d687ad6cf9f42ae9ac10680ae585d452 | bigcode/the-stack | train |
ee827b6842aa3a83fb5c1216 | train | class | class CommandTypes(AdminScriptTestCase):
"Tests for the various types of base command types that can be defined."
def setUp(self):
super().setUp()
self.write_settings('settings.py')
def test_version(self):
"version is handled as a special case"
args = ['version']
out... | class CommandTypes(AdminScriptTestCase):
| "Tests for the various types of base command types that can be defined."
def setUp(self):
super().setUp()
self.write_settings('settings.py')
def test_version(self):
"version is handled as a special case"
args = ['version']
out, err = self.run_manage(args)
sel... | mock_runserver_handle, mock_loaddata_handle, mock_create_test_db):
out = StringIO()
call_command('testserver', 'blah.json', stdout=out)
mock_runserver_handle.assert_called_with(
addrport='',
force_color=False,
insecure_serving=False,
no_color=Fals... | 256 | 256 | 3,685 | 8 | 248 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | CommandTypes | CommandTypes | 1,409 | 1,796 | 1,409 | 1,409 | 7b3ff47216d8ca9fc9713501b63e3ddfa882de4c | bigcode/the-stack | train |
428d279ca639829efbba8864 | train | class | class DjangoAdminSuggestions(AdminScriptTestCase):
def setUp(self):
super().setUp()
self.write_settings('settings.py')
def test_suggestions(self):
args = ['rnserver', '--settings=test_project.settings']
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
... | class DjangoAdminSuggestions(AdminScriptTestCase):
| def setUp(self):
super().setUp()
self.write_settings('settings.py')
def test_suggestions(self):
args = ['rnserver', '--settings=test_project.settings']
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "Unknown command: 'rnser... | _out)
def test_program_name_in_help(self):
out, err = self.run_test('-m', ['django', 'help'])
self.assertOutput(out, "Type 'python -m django help <subcommand>' for help on a specific subcommand.")
class DjangoAdminSuggestions(AdminScriptTestCase):
| 63 | 64 | 141 | 9 | 54 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | DjangoAdminSuggestions | DjangoAdminSuggestions | 2,276 | 2,291 | 2,276 | 2,276 | f1a6ce918a2f64e26bb85a66c10d8fb0437fc828 | bigcode/the-stack | train |
0c1c9b558a13bd5c4c521dd4 | train | class | class DjangoAdminSettingsDirectory(AdminScriptTestCase):
"""
A series of tests for django-admin.py when the settings file is in a
directory. (see #9751).
"""
def setUp(self):
super().setUp()
self.write_settings('settings', is_dir=True)
def test_setup_environ(self):
"dir... | class DjangoAdminSettingsDirectory(AdminScriptTestCase):
| """
A series of tests for django-admin.py when the settings file is in a
directory. (see #9751).
"""
def setUp(self):
super().setUp()
self.write_settings('settings', is_dir=True)
def test_setup_environ(self):
"directory: startapp creates the correct directory"
a... | (out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_custom_command(self):
"alternate: django-admin can't execute user commands unless settings are provided"
args = ['noargs_command']
out, err = self.run_django_admin(args)
self.assertNoOutput... | 256 | 256 | 884 | 10 | 246 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | DjangoAdminSettingsDirectory | DjangoAdminSettingsDirectory | 544 | 628 | 544 | 544 | 4d647e8d2407ee22c8b031df1dadfb3a3994705c | bigcode/the-stack | train |
0622ad0b45ddc3c07ff73ec5 | train | class | class ManageFullPathDefaultSettings(AdminScriptTestCase):
"""A series of tests for manage.py when using a settings.py file that
contains the test application specified using a full path.
"""
def setUp(self):
super().setUp()
self.write_settings('settings.py', ['django.contrib.auth', 'djan... | class ManageFullPathDefaultSettings(AdminScriptTestCase):
| """A series of tests for manage.py when using a settings.py file that
contains the test application specified using a full path.
"""
def setUp(self):
super().setUp()
self.write_settings('settings.py', ['django.contrib.auth', 'django.contrib.contenttypes', 'admin_scripts'])
def test_... | settings are appropriate"
args = ['noargs_command']
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command_with_settings(self):
"default: manage.py can execute user commands when settings are provi... | 195 | 195 | 652 | 11 | 184 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | ManageFullPathDefaultSettings | ManageFullPathDefaultSettings | 736 | 798 | 736 | 736 | 9df1dae1dc207e850b570a0d11b513dce9a25966 | bigcode/the-stack | train |
a9316d6201cc2a37f062bb5f | train | class | class ManageMinimalSettings(AdminScriptTestCase):
"""A series of tests for manage.py when using a settings.py file that
doesn't contain the test application.
"""
def setUp(self):
super().setUp()
self.write_settings('settings.py', apps=['django.contrib.auth', 'django.contrib.contenttypes'... | class ManageMinimalSettings(AdminScriptTestCase):
| """A series of tests for manage.py when using a settings.py file that
doesn't contain the test application.
"""
def setUp(self):
super().setUp()
self.write_settings('settings.py', apps=['django.contrib.auth', 'django.contrib.contenttypes'])
def test_builtin_command(self):
"m... | args = ['noargs_command']
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command_with_settings(self):
"fulldefault: manage.py can execute user commands when settings are provided as argument"
args ... | 194 | 194 | 649 | 9 | 185 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | ManageMinimalSettings | ManageMinimalSettings | 801 | 863 | 801 | 801 | 765c1ddadb0718b89170fb5a64d45154ec729c1c | bigcode/the-stack | train |
94c6349057a2448c71afefda | train | class | class ManageDefaultSettings(AdminScriptTestCase):
"""A series of tests for manage.py when using a settings.py file that
contains the test application.
"""
def setUp(self):
super().setUp()
self.write_settings('settings.py')
def test_builtin_command(self):
"default: manage.py ... | class ManageDefaultSettings(AdminScriptTestCase):
| """A series of tests for manage.py when using a settings.py file that
contains the test application.
"""
def setUp(self):
super().setUp()
self.write_settings('settings.py')
def test_builtin_command(self):
"default: manage.py builtin commands succeed when default settings are... | named '?(test_project\.)?settings'?", regex=True)
def test_builtin_with_bad_settings(self):
"no settings: manage.py builtin commands fail if settings file (from argument) doesn't exist"
args = ['check', '--settings=bad_settings', 'admin_scripts']
out, err = self.run_manage(args)
se... | 181 | 181 | 606 | 9 | 172 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | ManageDefaultSettings | ManageDefaultSettings | 671 | 733 | 671 | 671 | 4d9399cff17d6a0bf2530d25f9f43abb575eac44 | bigcode/the-stack | train |
a243351bfd5085e9a6bb339b | train | class | class DjangoAdminDefaultSettings(AdminScriptTestCase):
"""A series of tests for django-admin.py when using a settings.py file that
contains the test application.
"""
def setUp(self):
super().setUp()
self.write_settings('settings.py')
def test_builtin_command(self):
"default:... | class DjangoAdminDefaultSettings(AdminScriptTestCase):
| """A series of tests for django-admin.py when using a settings.py file that
contains the test application.
"""
def setUp(self):
super().setUp()
self.write_settings('settings.py')
def test_builtin_command(self):
"default: django-admin builtin commands fail with an error when ... | .assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
"no settings: django-admin builtin commands fail if settings file (from environment) doesn't exist"
args = ['check', 'admin_scripts']
out, err = s... | 192 | 192 | 642 | 10 | 182 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | DjangoAdminDefaultSettings | DjangoAdminDefaultSettings | 211 | 274 | 211 | 211 | 2f2890e21a4133ecd5f20d485baa8c69e39f9ff4 | bigcode/the-stack | train |
e1a01ce61d971e30e25f2324 | train | class | class ManageCheck(AdminScriptTestCase):
def test_nonexistent_app(self):
"""check reports an error on a nonexistent app in INSTALLED_APPS."""
self.write_settings(
'settings.py',
apps=['admin_scriptz.broken_app'],
sdict={'USE_I18N': False},
)
args = ... | class ManageCheck(AdminScriptTestCase):
| def test_nonexistent_app(self):
"""check reports an error on a nonexistent app in INSTALLED_APPS."""
self.write_settings(
'settings.py',
apps=['admin_scriptz.broken_app'],
sdict={'USE_I18N': False},
)
args = ['check']
out, err = self.run_ma... | settings (#18845).
"""
self.write_settings('settings.py', sdict={'BAD_VAR': 'INSTALLED_APPS.crash'})
args = ['collectstatic', 'admin_scripts']
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "AttributeError: 'list' object has no at... | 256 | 256 | 1,000 | 8 | 248 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | ManageCheck | ManageCheck | 1,078 | 1,223 | 1,078 | 1,078 | 695b9b46632983c707f0faac5c6604f4e4e4af81 | bigcode/the-stack | train |
cbb3024809ab6e499ae5dc42 | train | class | class ManageNoSettings(AdminScriptTestCase):
"A series of tests for manage.py when there is no settings.py file."
def test_builtin_command(self):
"no settings: manage.py builtin commands fail with an error when no settings provided"
args = ['check', 'admin_scripts']
out, err = self.run_... | class ManageNoSettings(AdminScriptTestCase):
| "A series of tests for manage.py when there is no settings.py file."
def test_builtin_command(self):
"no settings: manage.py builtin commands fail with an error when no settings provided"
args = ['check', 'admin_scripts']
out, err = self.run_manage(args)
self.assertNoOutput(out)... | .configure()."""
def test_non_existent_command_output(self):
out, err = self.run_manage(['invalid_command'], manage_py='configured_settings_manage.py')
self.assertNoOutput(out)
self.assertOutput(err, "Unknown command: 'invalid_command'")
self.assertNotInOutput(err, 'No Django setting... | 77 | 77 | 259 | 9 | 68 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | ManageNoSettings | ManageNoSettings | 646 | 668 | 646 | 646 | b2c71d12339ac553ebf38fed0efe16be6fa95f77 | bigcode/the-stack | train |
e06ed0c939b9be4d1c29f6ee | train | class | @override_settings(ROOT_URLCONF='admin_scripts.urls')
class StartProject(LiveServerTestCase, AdminScriptTestCase):
available_apps = [
'admin_scripts',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
]
def test_wrong_args(self):
"Make... | @override_settings(ROOT_URLCONF='admin_scripts.urls')
class StartProject(LiveServerTestCase, AdminScriptTestCase):
| available_apps = [
'admin_scripts',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
]
def test_wrong_args(self):
"Make sure passing the wrong kinds of arguments outputs an error and prints usage"
out, err = self.run_django_adm... | handled. """
args = ['base_command', 'testlabel', '-a', 'x', '--settings=alternate_settings']
self._test(args)
def test_option_then_setting_then_option(self):
""" Options are correctly handled when they are passed before and after
a setting. """
args = ['base_command', 'tes... | 256 | 256 | 2,381 | 25 | 231 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | StartProject | StartProject | 1,874 | 2,107 | 1,874 | 1,876 | 80762b8cc8548c7db4c316a14fb02f4e3b2595c4 | bigcode/the-stack | train |
3c5ad6b1d1b7cfe6276a6aa6 | train | class | class ManageManullyConfiguredSettings(AdminScriptTestCase):
"""Customized manage.py calling settings.configure()."""
def test_non_existent_command_output(self):
out, err = self.run_manage(['invalid_command'], manage_py='configured_settings_manage.py')
self.assertNoOutput(out)
self.assert... | class ManageManullyConfiguredSettings(AdminScriptTestCase):
| """Customized manage.py calling settings.configure()."""
def test_non_existent_command_output(self):
out, err = self.run_manage(['invalid_command'], manage_py='configured_settings_manage.py')
self.assertNoOutput(out)
self.assertOutput(err, "Unknown command: 'invalid_command'")
se... | test_project.settings')
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
##########################################################################
# MANAGE.PY TESTS
# This next series of test classes checks the environment processing
# of the generated manage.py script
##############... | 64 | 64 | 86 | 11 | 53 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | ManageManullyConfiguredSettings | ManageManullyConfiguredSettings | 637 | 643 | 637 | 637 | 0cd3115d6d9d14bb992da928a39ddfc9f1d83e47 | bigcode/the-stack | train |
6bc2be9c3db07c09f0c14f9f | train | class | class ManageTestserver(SimpleTestCase):
@mock.patch.object(TestserverCommand, 'handle', return_value='')
def test_testserver_handle_params(self, mock_handle):
out = StringIO()
call_command('testserver', 'blah.json', stdout=out)
mock_handle.assert_called_with(
'blah.json',
... | class ManageTestserver(SimpleTestCase):
@mock.patch.object(TestserverCommand, 'handle', return_value='')
| def test_testserver_handle_params(self, mock_handle):
out = StringIO()
call_command('testserver', 'blah.json', stdout=out)
mock_handle.assert_called_with(
'blah.json',
stdout=out, settings=None, pythonpath=None, verbosity=1,
traceback=False, addrport='', n... | self.write_settings('settings.py', sdict={
'ALLOWED_HOSTS': [],
'DEBUG': False,
})
def test_empty_allowed_hosts_error(self):
out, err = self.run_manage(['runserver'])
self.assertNoOutput(out)
self.assertOutput(err, 'CommandError: You must set settings.ALLOWE... | 100 | 101 | 339 | 23 | 77 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | ManageTestserver | ManageTestserver | 1,356 | 1,393 | 1,356 | 1,358 | 80e1bb2eea2895eaa3aecf6527ca41bc3935457d | bigcode/the-stack | train |
58cf99512511da4f39b853b5 | train | class | class ManageSettingsWithSettingsErrors(AdminScriptTestCase):
"""
Tests for manage.py when using the default settings.py file containing
runtime errors.
"""
def write_settings_with_import_error(self, filename):
settings_file_path = os.path.join(self.test_dir, filename)
with open(setti... | class ManageSettingsWithSettingsErrors(AdminScriptTestCase):
| """
Tests for manage.py when using the default settings.py file containing
runtime errors.
"""
def write_settings_with_import_error(self, filename):
settings_file_path = os.path.join(self.test_dir, filename)
with open(settings_file_path, 'w') as settings_file:
settings_fi... | "multiple: manage.py can execute user commands if settings are provided as argument"
args = ['noargs_command', '--settings=alternate_settings']
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command... | 142 | 142 | 476 | 11 | 131 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | ManageSettingsWithSettingsErrors | ManageSettingsWithSettingsErrors | 1,021 | 1,075 | 1,021 | 1,021 | 4d88c465f6af8472978a977697547111bdcf7107 | bigcode/the-stack | train |
e8eedd967c16c401a42d823a | train | class | class DiffSettings(AdminScriptTestCase):
"""Tests for diffsettings management command."""
def test_basic(self):
"""Runs without error and emits settings diff."""
self.write_settings('settings_to_diff.py', sdict={'FOO': '"bar"'})
args = ['diffsettings', '--settings=settings_to_diff']
... | class DiffSettings(AdminScriptTestCase):
| """Tests for diffsettings management command."""
def test_basic(self):
"""Runs without error and emits settings diff."""
self.write_settings('settings_to_diff.py', sdict={'FOO': '"bar"'})
args = ['diffsettings', '--settings=settings_to_diff']
out, err = self.run_manage(args)
... | Test(bad_target):
_, err = self.run_django_admin(['startapp', 'app', bad_target])
self.assertOutput(
err,
"CommandError: '%s' is not a valid app directory. Please "
"make sure the directory is a valid identifier." % bad_target
... | 225 | 225 | 753 | 8 | 217 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | DiffSettings | DiffSettings | 2,174 | 2,242 | 2,174 | 2,174 | 62b1ec21178c0676d9f65531132fb3346e83054a | bigcode/the-stack | train |
eaecd008a4f456f348ca9e5e | train | class | class MainModule(AdminScriptTestCase):
"""python -m django works like django-admin."""
def test_runs_django_admin(self):
cmd_out, _ = self.run_django_admin(['--version'])
mod_out, _ = self.run_test('-m', ['django', '--version'])
self.assertEqual(mod_out, cmd_out)
def test_program_n... | class MainModule(AdminScriptTestCase):
| """python -m django works like django-admin."""
def test_runs_django_admin(self):
cmd_out, _ = self.run_django_admin(['--version'])
mod_out, _ = self.run_test('-m', ['django', '--version'])
self.assertEqual(mod_out, cmd_out)
def test_program_name_in_help(self):
out, err = s... | printing an error message.
"""
args = ['dumpdata', '--pks=1']
out, err = self.run_manage(args)
self.assertOutput(err, "You can only use --pks option with one model")
self.assertNoOutput(out)
class MainModule(AdminScriptTestCase):
| 64 | 64 | 123 | 8 | 56 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | MainModule | MainModule | 2,263 | 2,273 | 2,263 | 2,263 | d7b0c7056503db513de566ad57706ca0d97701e1 | bigcode/the-stack | train |
ea1349308e3d6e575127c209 | train | class | class DjangoAdminMultipleSettings(AdminScriptTestCase):
"""A series of tests for django-admin.py when multiple settings files
(including the default 'settings.py') are available. The default settings
file is insufficient for performing the operations described, so the
alternate settings must be used by ... | class DjangoAdminMultipleSettings(AdminScriptTestCase):
| """A series of tests for django-admin.py when multiple settings files
(including the default 'settings.py') are available. The default settings
file is insufficient for performing the operations described, so the
alternate settings must be used by the running script.
"""
def setUp(self):
... | _command']
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "No Django settings specified")
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_settings(self):
"alternate: django-admin can execute use... | 208 | 208 | 694 | 10 | 198 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | DjangoAdminMultipleSettings | DjangoAdminMultipleSettings | 476 | 541 | 476 | 476 | c0a2c4ca06f7c66b17f643287707a7b73d56bc2c | bigcode/the-stack | train |
2d1b84cfcdaab79a0bde048c | train | class | class DjangoAdminNoSettings(AdminScriptTestCase):
"A series of tests for django-admin.py when there is no settings.py file."
def test_builtin_command(self):
"no settings: django-admin builtin commands fail with an error when no settings provided"
args = ['check', 'admin_scripts']
out, e... | class DjangoAdminNoSettings(AdminScriptTestCase):
| "A series of tests for django-admin.py when there is no settings.py file."
def test_builtin_command(self):
"no settings: django-admin builtin commands fail with an error when no settings provided"
args = ['check', 'admin_scripts']
out, err = self.run_django_admin(args)
self.asse... | msg, stream))
def assertNotInOutput(self, stream, msg):
"Utility assertion: assert that the given message doesn't exist in the output"
self.assertNotIn(msg, stream, "'%s' matches actual output text '%s'" % (msg, stream))
##########################################################################
# ... | 99 | 100 | 335 | 10 | 89 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | DjangoAdminNoSettings | DjangoAdminNoSettings | 176 | 208 | 176 | 176 | e397482681f8ae8892661c1f56780b70e371c1ee | bigcode/the-stack | train |
148031d00432f03aaa4058eb | train | class | class ManageAlternateSettings(AdminScriptTestCase):
"""A series of tests for manage.py when using a settings file
with a name other than 'settings.py'.
"""
def setUp(self):
super().setUp()
self.write_settings('alternate_settings.py')
def test_builtin_command(self):
"alternat... | class ManageAlternateSettings(AdminScriptTestCase):
| """A series of tests for manage.py when using a settings file
with a name other than 'settings.py'.
"""
def setUp(self):
super().setUp()
self.write_settings('alternate_settings.py')
def test_builtin_command(self):
"alternate: manage.py builtin commands fail with an error whe... | err = self.run_manage(args, 'bad_settings')
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_custom_command(self):
"minimal: manage.py can't execute user commands without appropriate settings"
args = ['noargs_command']
... | 255 | 256 | 854 | 9 | 247 | elikkatzgit/django | tests/admin_scripts/tests.py | Python | ManageAlternateSettings | ManageAlternateSettings | 866 | 950 | 866 | 866 | a58f44e996329618c0fad2929de5a379f079a567 | bigcode/the-stack | train |
92f06309c2e581daf2f78267 | train | function | def top_k_top_p_filtering(logits, top_k=0, top_p=0.0, filter_value=-float('Inf')):
""" Filter a distribution of logits using top-k and/or nucleus (top-p) filtering
Args:
logits: logits distribution shape (vocabulary size)
top_k > 0: keep only top k tokens with highest probability (to... | def top_k_top_p_filtering(logits, top_k=0, top_p=0.0, filter_value=-float('Inf')):
| """ Filter a distribution of logits using top-k and/or nucleus (top-p) filtering
Args:
logits: logits distribution shape (vocabulary size)
top_k > 0: keep only top k tokens with highest probability (top-k filtering).
top_p > 0.0: keep the top tokens with cumulative probab... | is chased outside and beaten. Twenty years later, Rasputin sees a vision of
the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous,
with people, even a bishop, begging for his blessing. <eod> </s> <eos>"""
def set_seed(args):
np.random.seed(args.seed)
torch.manual_seed(args.seed)
... | 126 | 126 | 423 | 29 | 97 | SeanBE/transformers | examples/run_generation.py | Python | top_k_top_p_filtering | top_k_top_p_filtering | 77 | 105 | 77 | 77 | 8dd1b81d5ae3cce5ce1fe0d932c3b271c01805ae | bigcode/the-stack | train |
9697b533fa20e6e9fd526aa6 | train | function | def main():
parser = argparse.ArgumentParser()
parser.add_argument("--model_type", default=None, type=str, required=True,
help="Model type selected in the list: " + ", ".join(MODEL_CLASSES.keys()))
parser.add_argument("--model_name_or_path", default=None, type=str, required=True,
... | def main():
| parser = argparse.ArgumentParser()
parser.add_argument("--model_type", default=None, type=str, required=True,
help="Model type selected in the list: " + ", ".join(MODEL_CLASSES.keys()))
parser.add_argument("--model_name_or_path", default=None, type=str, required=True,
... | see last token
target_mapping = torch.zeros((1, 1, input_ids.shape[1]), dtype=torch.float, device=device)
target_mapping[0, 0, -1] = 1.0 # predict last token
inputs = {'input_ids': input_ids, 'perm_mask': perm_mask, 'target_mapping': target_mapping}
if xlm_... | 245 | 245 | 818 | 3 | 241 | SeanBE/transformers | examples/run_generation.py | Python | main | main | 138 | 216 | 138 | 138 | b517daa628799108445d27f6695b5e5cc2009230 | bigcode/the-stack | train |
86a1eb0666d712521d01ea37 | train | function | def sample_sequence(model, length, context, num_samples=1, temperature=1, top_k=0, top_p=0.0, is_xlnet=False,
xlm_lang=None, device='cpu'):
context = torch.tensor(context, dtype=torch.long, device=device)
context = context.unsqueeze(0).repeat(num_samples, 1)
generated = context
with ... | def sample_sequence(model, length, context, num_samples=1, temperature=1, top_k=0, top_p=0.0, is_xlnet=False,
xlm_lang=None, device='cpu'):
| context = torch.tensor(context, dtype=torch.long, device=device)
context = context.unsqueeze(0).repeat(num_samples, 1)
generated = context
with torch.no_grad():
for _ in trange(length):
inputs = {'input_ids': generated}
if is_xlnet:
# XLNet is a direct (... | cumulative probability above the threshold
sorted_indices_to_remove = cumulative_probs > top_p
# Shift the indices to the right to keep also the first token above the threshold
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
sorted_indices_to_remove[..., 0... | 143 | 143 | 478 | 46 | 96 | SeanBE/transformers | examples/run_generation.py | Python | sample_sequence | sample_sequence | 108 | 135 | 108 | 109 | 36edb2f0fcceb92c6764f2ed7d8e5c7fb80ff9fd | bigcode/the-stack | train |
1f7a1795eba18e272da1658c | train | function | def set_seed(args):
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
| def set_seed(args):
| np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
| chased outside and beaten. Twenty years later, Rasputin sees a vision of
the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous,
with people, even a bishop, begging for his blessing. <eod> </s> <eos>"""
def set_seed(args):
| 64 | 64 | 37 | 5 | 59 | SeanBE/transformers | examples/run_generation.py | Python | set_seed | set_seed | 70 | 74 | 70 | 70 | bf0dd6818fc942a332b22c01533509ab7184fcef | bigcode/the-stack | train |
84c6aa7ffa8d920fc34c914f | train | class | class ChatbotCreator():
def __init__(
self,
model_file_name_to_save,
lang_model="en_core_web_md"
):
self.model_name = model_file_name_to_save
self.lang_model = lang_model
def createData(self, json_file_path):
self.train_x = []
... | class ChatbotCreator():
| def __init__(
self,
model_file_name_to_save,
lang_model="en_core_web_md"
):
self.model_name = model_file_name_to_save
self.lang_model = lang_model
def createData(self, json_file_path):
self.train_x = []
self.train_y = []
... | import pandas as pd
from nltk.tokenize import word_tokenize
from nltk.stem import PorterStemmer
import time
import sys
import pickle
import spacy
from sklearn.preprocessing import LabelEncoder
import numpy as np
import os
import warnings
warnings.filterwarnings("ignore")
class ChatbotCreator():
| 66 | 256 | 1,126 | 6 | 60 | pranav377/chatbot-creator | ChatbotCreator/cc.py | Python | ChatbotCreator | ChatbotCreator | 14 | 141 | 14 | 15 | 48f496150f3f074b8203dbb76c6b344ce0a84d5e | bigcode/the-stack | train |
a238029c06f7fe6b1288a99e | train | function | def run(device, source, struct_ver=True, raw_bit=False, pdcfile=None):
"""
Run radiant.sh with a given device name and source Verilog file
"""
env = os.environ.copy()
if struct_ver:
env["STRUCT_VER"] = "1"
if raw_bit:
env["GEN_RBT"] = "1"
dsh_path = path.join(database.get_oxi... | def run(device, source, struct_ver=True, raw_bit=False, pdcfile=None):
| """
Run radiant.sh with a given device name and source Verilog file
"""
env = os.environ.copy()
if struct_ver:
env["STRUCT_VER"] = "1"
if raw_bit:
env["GEN_RBT"] = "1"
dsh_path = path.join(database.get_oxide_root(), "radiant.sh")
return subprocess.run(["bash",dsh_path,dev... | """
Python wrapper for `radiant.sh`
"""
from os import path
import os
import subprocess
import database
def run(device, source, struct_ver=True, raw_bit=False, pdcfile=None):
| 43 | 64 | 113 | 19 | 23 | mmicko/prjoxide | util/common/radiant.py | Python | run | run | 10 | 20 | 10 | 10 | 82bf8d5b13b0411d2282116e0b7d5b56eca03c6f | bigcode/the-stack | train |
02678099797e30344581e67b | train | function | @pytest.mark.parametrize('code', [
'if a in {1, 2}: ...',
'if a in {1: "a", 2: "b"}: ...',
'if a in [1, 2]: ... ',
'if a in (1, 2): ... ',
'if a in "ab": ... ',
'if a in {1, *a}: ... ',
'if a in {1: "a", **a}: ... ',
])
def test_multi_item_contrainer(
assert_errors,
parse_ast_tree,
... | @pytest.mark.parametrize('code', [
'if a in {1, 2}: ...',
'if a in {1: "a", 2: "b"}: ...',
'if a in [1, 2]: ... ',
'if a in (1, 2): ... ',
'if a in "ab": ... ',
'if a in {1, *a}: ... ',
'if a in {1: "a", **a}: ... ',
])
def test_multi_item_contrainer(
assert_errors,
parse_ast_tree,
... | """Compares allow ``in`` with multi items containers."""
tree = parse_ast_tree(code)
visitor = InCompareSanityVisitor(default_options, tree=tree)
visitor.run()
assert_errors(
visitor,
[],
ignored_types=(WrongInCompareTypeViolation,),
)
| @pytest.mark.parametrize('code', [
'if a in {1, 2}: ...',
'if a in {1: "a", 2: "b"}: ...',
'if a in [1, 2]: ... ',
'if a in (1, 2): ... ',
'if a in "ab": ... ',
'if a in {1, *a}: ... ',
'if a in {1: "a", **a}: ... ',
])
def test_multi_item_contrainer(
assert_errors,
parse_ast_tree,
... | 135 | 64 | 196 | 135 | 0 | JazabC/wemake-python-styleguide | tests/test_visitors/test_ast/test_compares/test_in_with_single_item_container.py | Python | test_multi_item_contrainer | test_multi_item_contrainer | 41 | 67 | 41 | 56 | 030d6beabfa3504cf97ccf1819f6e132af1843ee | bigcode/the-stack | train |
9bb1ddfa4f0e4c5b94cf21e6 | train | function | @pytest.mark.parametrize('code', [
'if a in {1}: ...',
'if a in {1: "a"}: ...',
'if a in [1]: ... ',
'if a in (1,): ... ',
'if a in "a": ... ',
'if a in {*a}: ... ',
'if a in {**a}: ... ',
])
def test_single_item_container(
assert_errors,
parse_ast_tree,
code,
default_options... | @pytest.mark.parametrize('code', [
'if a in {1}: ...',
'if a in {1: "a"}: ...',
'if a in [1]: ... ',
'if a in (1,): ... ',
'if a in "a": ... ',
'if a in {*a}: ... ',
'if a in {**a}: ... ',
])
def test_single_item_container(
assert_errors,
parse_ast_tree,
code,
default_options... | """Compares forbid ``in`` with single item containers."""
tree = parse_ast_tree(code)
visitor = InCompareSanityVisitor(default_options, tree=tree)
visitor.run()
assert_errors(
visitor,
[InCompareWithSingleItemContainerViolation],
ignored_types=(WrongInCompareTypeViolation,)... | @pytest.mark.parametrize('code', [
'if a in {1}: ...',
'if a in {1: "a"}: ...',
'if a in [1]: ... ',
'if a in (1,): ... ',
'if a in "a": ... ',
'if a in {*a}: ... ',
'if a in {**a}: ... ',
])
def test_single_item_container(
assert_errors,
parse_ast_tree,
code,
default_options... | 112 | 64 | 181 | 112 | 0 | JazabC/wemake-python-styleguide | tests/test_visitors/test_ast/test_compares/test_in_with_single_item_container.py | Python | test_single_item_container | test_single_item_container | 12 | 38 | 12 | 27 | 33650218e58b8d63722ad84efb2dcd39018b32a4 | bigcode/the-stack | train |
7f22362753f5be8e0efbb405 | train | function | def get_weights_from_arch(arch, model):
adjacency_matrix, node_list = arch
num_ops = len(PRIMITIVES)
# Assign the sampled ops to the mixed op weights.
# These are not optimized
alphas_mixed_op = Variable(torch.zeros(model._steps, num_ops).cuda(), requires_grad=False)
for idx, op in enumerate(no... | def get_weights_from_arch(arch, model):
| adjacency_matrix, node_list = arch
num_ops = len(PRIMITIVES)
# Assign the sampled ops to the mixed op weights.
# These are not optimized
alphas_mixed_op = Variable(torch.zeros(model._steps, num_ops).cuda(), requires_grad=False)
for idx, op in enumerate(node_list):
alphas_mixed_op[idx][P... | _shot_model(config=args.__dict__,
model=arch_filename)
index = np.random.choice(list(range(3)))
logging.info('TEST ERROR: %.3f | VALID ERROR: %.3f | RUNTIME: %f | PARAMS: %d'
% (test[index],
v... | 97 | 97 | 326 | 10 | 87 | liamcli/nasbench-1shot1 | nasbench_analysis/single_architecture_training/train.py | Python | get_weights_from_arch | get_weights_from_arch | 191 | 224 | 191 | 191 | 3098a11dc359cc86c6846e919e757dbcffabc335 | bigcode/the-stack | train |
6c0c49ea5ff2ea8486fb614c | train | function | def train(train_queue, valid_queue, model, architect, criterion, optimizer, lr, epoch):
objs = utils.AvgrageMeter()
top1 = utils.AvgrageMeter()
top5 = utils.AvgrageMeter()
for step, (input, target) in enumerate(train_queue):
model.train()
n = input.size(0)
input = input.cuda()
... | def train(train_queue, valid_queue, model, architect, criterion, optimizer, lr, epoch):
| objs = utils.AvgrageMeter()
top1 = utils.AvgrageMeter()
top5 = utils.AvgrageMeter()
for step, (input, target) in enumerate(train_queue):
model.train()
n = input.size(0)
input = input.cuda()
target = target.cuda(non_blocking=True)
# get a minibatch from the sear... | alpha_input.shape[1], alpha_input.shape[1]])
for idx, label in enumerate(connectivity_pattern):
alpha_input[0][idx] = label
# Total architecture parameters
arch_parameters = [
alphas_mixed_op,
alphas_output,
*alphas_inputs
]
return arch_parameters
def train(t... | 90 | 90 | 301 | 20 | 69 | liamcli/nasbench-1shot1 | nasbench_analysis/single_architecture_training/train.py | Python | train | train | 227 | 264 | 227 | 227 | 31d92c32dfcf388ba114ec8b6c50bf7eca0a0804 | bigcode/the-stack | train |
6cb04ae84eac9392b824e59d | train | function | def infer(valid_queue, model, criterion):
objs = utils.AvgrageMeter()
top1 = utils.AvgrageMeter()
top5 = utils.AvgrageMeter()
model.eval()
for step, (input, target) in enumerate(valid_queue):
input = input.cuda()
target = target.cuda(non_blocking=True)
logits = model(input,... | def infer(valid_queue, model, criterion):
| objs = utils.AvgrageMeter()
top1 = utils.AvgrageMeter()
top5 = utils.AvgrageMeter()
model.eval()
for step, (input, target) in enumerate(valid_queue):
input = input.cuda()
target = target.cuda(non_blocking=True)
logits = model(input, discrete=True)
loss = criterion(l... | if step % args.report_freq == 0:
logging.info('train %03d %e %f %f', step, objs.avg, top1.avg, top5.avg)
if args.debug:
break
return top1.avg, objs.avg
def infer(valid_queue, model, criterion):
| 64 | 64 | 211 | 9 | 54 | liamcli/nasbench-1shot1 | nasbench_analysis/single_architecture_training/train.py | Python | infer | infer | 267 | 291 | 267 | 267 | 91abfb9035bd5729d5c8650b5e68221f2d6db15f | bigcode/the-stack | train |
ecbd0848c3e0dbaafd753576 | train | function | def main():
# Select the search space to search in
if args.search_space == '1':
search_space = SearchSpace1()
elif args.search_space == '2':
search_space = SearchSpace2()
elif args.search_space == '3':
search_space = SearchSpace3()
else:
raise ValueError('Unknown sear... | def main():
# Select the search space to search in
| if args.search_space == '1':
search_space = SearchSpace1()
elif args.search_space == '2':
search_space = SearchSpace2()
elif args.search_space == '3':
search_space = SearchSpace3()
else:
raise ValueError('Unknown search space')
if not torch.cuda.is_available():
... | _start_epochs', type=int, default=0,
help='Warm start one-shot model before starting architecture updates.')
args = parser.parse_args()
args.save = 'experiments/independent_training/search_space_{}/search-{}-{}-{}-{}'.format(args.search_space,
... | 256 | 256 | 936 | 13 | 242 | liamcli/nasbench-1shot1 | nasbench_analysis/single_architecture_training/train.py | Python | main | main | 83 | 188 | 83 | 84 | 7364a6c3d84720e379488c3a7c64102104392faf | bigcode/the-stack | train |
8ca924b6d62ffabf997eb426 | train | function | def evaluate_split(model, processor, args, split='dev'):
evaluator = HRBertEvaluator(model, processor, args, split)
start_time = time.time()
accuracy, precision, recall, f1, avg_loss = evaluator.get_scores(silent=True)[0]
print("Inference time", time.time() - start_time)
print('\n' + LOG_HEADER)
... | def evaluate_split(model, processor, args, split='dev'):
| evaluator = HRBertEvaluator(model, processor, args, split)
start_time = time.time()
accuracy, precision, recall, f1, avg_loss = evaluator.get_scores(silent=True)[0]
print("Inference time", time.time() - start_time)
print('\n' + LOG_HEADER)
print(LOG_TEMPLATE.format(split.upper(), accuracy, preci... | Dev/Loss'
LOG_TEMPLATE = ' '.join('{:>5s},{:>9.4f},{:>8.4f},{:8.4f},{:8.4f},{:10.4f}'.split(','))
def evaluate_split(model, processor, args, split='dev'):
| 64 | 64 | 99 | 13 | 51 | Ji-Xin/bovina | models/diff_token/bert/__main__.py | Python | evaluate_split | evaluate_split | 22 | 28 | 22 | 22 | 44dc5607e23643613b1c047211ba4843624e70f8 | bigcode/the-stack | train |
b8dcce914e8883711a2f1f6b | train | function | def test_model1D():
raytracing_start_time = time.time()
vp = np.array([1200, 1500, 1800, 2100])
vs = np.array([600, 750, 900, 1050])
rho = np.array([1600, 1700, 1800, 1900])
h = np.array([500, 1000, 1500], 'int')
refl_flags = [0, 1, 0]
model = SeismicModel1D.from_vp_vs_rho(h, vp, vs, rho, ... | def test_model1D():
| raytracing_start_time = time.time()
vp = np.array([1200, 1500, 1800, 2100])
vs = np.array([600, 750, 900, 1050])
rho = np.array([1600, 1700, 1800, 1900])
h = np.array([500, 1000, 1500], 'int')
refl_flags = [0, 1, 0]
model = SeismicModel1D.from_vp_vs_rho(h, vp, vs, rho, refl_flags)
dz =... | import matplotlib.pyplot as plt
import numpy as np
import time
from objects.Models.Models import SeismicModel1D
from objects.seismic.observation import Observation, Source, Receiver
from objects.seismic.waves import OWT
from fmodeling.seismic.ray_tracing.case_1D.forward_tracing1D import calculate_rays
from fmodeling.s... | 127 | 168 | 560 | 6 | 120 | lomonosouv/rpsi | Tests/test_RayTracing1D.py | Python | test_model1D | test_model1D | 14 | 63 | 14 | 14 | a7c711c7a2a24c83ecb741b0a6df52e8fb98dea8 | bigcode/the-stack | train |
982be61fde817dbe302f98ff | train | class | class TokenClient(Client):
"""
Manipulate files managed by Gopublish
"""
def create(self, username="", password=""):
"""
Get token
:type username: str
:param username: Username
:type password: str
:param password: Optional password for library compatibi... | class TokenClient(Client):
| """
Manipulate files managed by Gopublish
"""
def create(self, username="", password=""):
"""
Get token
:type username: str
:param username: Username
:type password: str
:param password: Optional password for library compatibility
:rtype: dict
... | division
from __future__ import print_function
from __future__ import unicode_literals
import getpass
from future import standard_library
from gopublic.golib.client import Client
from gopublic.golib.exceptions import GopublishParameterError
standard_library.install_aliases()
class TokenClient(Client):
| 65 | 65 | 217 | 5 | 60 | mboudet/gopublish_cli | gopublic/golib/token/__init__.py | Python | TokenClient | TokenClient | 16 | 53 | 16 | 16 | c228088c6acdb8ac188e955c3f5c4d666aef8207 | bigcode/the-stack | train |
1c494d2872ce1e504acf3f4e | train | function | def unpackEIS(cntlr, eisFile, unpackToDir):
from arelle.FileSource import openFileSource
filesource = openFileSource(eisFile, cntlr, checkIfXmlIsEis=True)
if not filesource.isArchive:
cntlr.addToLog("[info:unpackEIS] Not recognized as an EIS file: " + eisFile)
return
import os, io
... | def unpackEIS(cntlr, eisFile, unpackToDir):
| from arelle.FileSource import openFileSource
filesource = openFileSource(eisFile, cntlr, checkIfXmlIsEis=True)
if not filesource.isArchive:
cntlr.addToLog("[info:unpackEIS] Not recognized as an EIS file: " + eisFile)
return
import os, io
unpackedFiles = []
for file in f... | pack SEC EIS File is an example of a plug-in to the GUI menu
that will save the unpacked contents of an SEC EIS File in a directory.
(c) Copyright 2012 Mark V Systems Limited, All rights reserved.
'''
def unpackEIS(cntlr, eisFile, unpackToDir):
| 64 | 64 | 194 | 14 | 50 | gmongelli/Arelle | arelle/plugin/unpackSecEisFile.py | Python | unpackEIS | unpackEIS | 8 | 25 | 8 | 8 | 4e5ccc9eca8c0120dbf52d8b1f8022b1a04496c9 | bigcode/the-stack | train |
2d2dee83ec0d75e280d0e067 | train | function | def unpackSecEisMenuEntender(cntlr, menu):
def askUnpackDirectory():
eisFile = cntlr.uiFileDialog("open",
title=_("arelle - Open SEC EIS file"),
initialdir=cntlr.config.setdefault("openSecEisFileDir","."),
... | def unpackSecEisMenuEntender(cntlr, menu):
| def askUnpackDirectory():
eisFile = cntlr.uiFileDialog("open",
title=_("arelle - Open SEC EIS file"),
initialdir=cntlr.config.setdefault("openSecEisFileDir","."),
filetypes=[(_("Compressed EIS file... | File,file))
with open(os.path.join(unpackToDir, file), "w", encoding=encoding) as fOut:
fOut.write(fIn.read())
unpackedFiles.append(file)
fIn.close()
cntlr.addToLog("[info:unpackEIS] Unpacked files " + ', '.join(unpackedFiles))
def unpackSecEisMenuEntender(cn... | 87 | 87 | 291 | 13 | 74 | gmongelli/Arelle | arelle/plugin/unpackSecEisFile.py | Python | unpackSecEisMenuEntender | unpackSecEisMenuEntender | 27 | 50 | 27 | 27 | b6ace401c09f6fb9c4a21b2a01debc1c2020743f | bigcode/the-stack | train |
ca1b9b0ccb99c16bf3151dc0 | train | function | def test_formfields_exception(client, mock_env):
# pylint: disable=unused-argument
# mock_env is a fixture and creates a false positive for pylint
"""Test pdfgenerator exception """
| def test_formfields_exception(client, mock_env):
# pylint: disable=unused-argument
# mock_env is a fixture and creates a false positive for pylint
| """Test pdfgenerator exception """
| : disable=unused-argument
# mock_env is a fixture and creates a false positive for pylint
"""Test export message response"""
def test_formfields_exception(client, mock_env):
# pylint: disable=unused-argument
# mock_env is a fixture and creates a false positive for pylint
| 64 | 64 | 42 | 35 | 29 | SFDigitalServices/pdf-generator | tests/test_formfields.py | Python | test_formfields_exception | test_formfields_exception | 35 | 38 | 35 | 37 | 3c307ff908b692625131860617d8cb827189f8f4 | bigcode/the-stack | train |
96bf22eb99669da0ad4e8cf2 | train | function | @pytest.fixture()
def client():
""" client fixture """
return testing.TestClient(app=service.microservice.start_service())
| @pytest.fixture()
def client():
| """ client fixture """
return testing.TestClient(app=service.microservice.start_service())
| testing
from service.resources.formfields import FormFieldDef
import service.microservice
CLIENT_HEADERS = {
"ACCESS_KEY": "1234567"
}
CLIENT_ENV = {
"ACCESS_KEY": CLIENT_HEADERS["ACCESS_KEY"],
"SENDGRID_API_KEY": "abc",
}
@pytest.fixture()
def client():
| 64 | 64 | 24 | 6 | 58 | SFDigitalServices/pdf-generator | tests/test_formfields.py | Python | client | client | 18 | 21 | 18 | 19 | aa52c297fe75faf2082e60a9b7bafdb30418e81f | bigcode/the-stack | train |
c3b536c3af9c15746f025243 | train | function | def test_formfields(client, mock_env):
# pylint: disable=unused-argument
# mock_env is a fixture and creates a false positive for pylint
"""Test export message response"""
| def test_formfields(client, mock_env):
# pylint: disable=unused-argument
# mock_env is a fixture and creates a false positive for pylint
| """Test export message response"""
| _env(monkeypatch):
""" mock environment access key """
for key in CLIENT_ENV:
monkeypatch.setenv(key, CLIENT_ENV[key])
def test_formfields(client, mock_env):
# pylint: disable=unused-argument
# mock_env is a fixture and creates a false positive for pylint
| 64 | 64 | 41 | 34 | 30 | SFDigitalServices/pdf-generator | tests/test_formfields.py | Python | test_formfields | test_formfields | 29 | 32 | 29 | 31 | 9ab3245210d2725e1d52e34c8d565d5235f89f5d | bigcode/the-stack | train |
9273062e13cade9a3ca086ef | train | function | @pytest.fixture
def mock_env(monkeypatch):
""" mock environment access key """
for key in CLIENT_ENV:
monkeypatch.setenv(key, CLIENT_ENV[key])
| @pytest.fixture
def mock_env(monkeypatch):
| """ mock environment access key """
for key in CLIENT_ENV:
monkeypatch.setenv(key, CLIENT_ENV[key])
| 4567"
}
CLIENT_ENV = {
"ACCESS_KEY": CLIENT_HEADERS["ACCESS_KEY"],
"SENDGRID_API_KEY": "abc",
}
@pytest.fixture()
def client():
""" client fixture """
return testing.TestClient(app=service.microservice.start_service())
@pytest.fixture
def mock_env(monkeypatch):
| 64 | 64 | 35 | 10 | 54 | SFDigitalServices/pdf-generator | tests/test_formfields.py | Python | mock_env | mock_env | 23 | 27 | 23 | 24 | 13375eb0d5f5518b260b9db623754dfae0f758fa | bigcode/the-stack | train |
880aea3cdbfd7f973a38e1e8 | train | function | def test_reversion() -> None:
with temporary_dir() as dest_dir:
# Download an input whl.
name_template = "virtualenv-{}-py2.py3-none-any.whl"
input_name = name_template.format("15.1.0")
url = (
"https://files.pythonhosted.org/packages/6f/86/"
"3dc328ee7b1a6419... | def test_reversion() -> None:
| with temporary_dir() as dest_dir:
# Download an input whl.
name_template = "virtualenv-{}-py2.py3-none-any.whl"
input_name = name_template.format("15.1.0")
url = (
"https://files.pythonhosted.org/packages/6f/86/"
"3dc328ee7b1a6419ebfac7896d882fba83c48e3561d22d... | # Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
import shutil
import requests
from pex.bin import pex as pex_main
from reversion import reversion
from pants.util.contextutil import temporary_dir
def test_reversion() -> None:... | 74 | 92 | 308 | 8 | 65 | rcuza/pants | build-support/bin/reversion_test.py | Python | test_reversion | test_reversion | 14 | 39 | 14 | 14 | b48cc8fb211845c0f657562ab5a8b8fad45bb697 | bigcode/the-stack | train |
0e7e550d646a54419528c77a | train | function | def list_devices():
device_list = []
for id in range(8):
device_list.append({"id": str(id), "un": "-", "type": "-", "file": "-"})
output = subprocess.run(["rasctl", "-l"], capture_output=True).stdout.decode(
"utf-8"
)
for line in output.splitlines():
# Valid line to process, ... | def list_devices():
| device_list = []
for id in range(8):
device_list.append({"id": str(id), "un": "-", "type": "-", "file": "-"})
output = subprocess.run(["rasctl", "-l"], capture_output=True).stdout.decode(
"utf-8"
)
for line in output.splitlines():
# Valid line to process, continue
if ... | /raspberrypi/setup_bridge.sh", interface],
capture_output=True,
)
def rascsi_service(action):
# start/stop/restart
return (
subprocess.run(["sudo", "/bin/systemctl", action, "rascsi.service"]).returncode
== 0
)
def list_devices():
| 69 | 69 | 232 | 4 | 65 | hsiboy/RASCSI | src/web/ractl_cmds.py | Python | list_devices | list_devices | 136 | 164 | 136 | 136 | 67ef651802d41ebdf0d6f8ea814bde4af3faf64c | bigcode/the-stack | train |
d29e9270b9f8a86da25f2c50 | train | function | def attach_daynaport(scsi_id):
return subprocess.run(
["rasctl", "-i", scsi_id, "-c", "attach", "-t", "daynaport"],
capture_output=True,
)
| def attach_daynaport(scsi_id):
| return subprocess.run(
["rasctl", "-i", scsi_id, "-c", "attach", "-t", "daynaport"],
capture_output=True,
)
| ", scsi_id, "-c", "eject"])
def insert(scsi_id, image):
return subprocess.run(
["rasctl", "-i", scsi_id, "-c", "insert", "-f", image], capture_output=True
)
def attach_daynaport(scsi_id):
| 64 | 64 | 47 | 9 | 55 | hsiboy/RASCSI | src/web/ractl_cmds.py | Python | attach_daynaport | attach_daynaport | 106 | 110 | 106 | 106 | d5b040d8b77c9c9f9d61b86aba74af3f4989674c | bigcode/the-stack | train |
ff2a0fc12af62d95c17a9435 | train | function | def rascsi_service(action):
# start/stop/restart
return (
subprocess.run(["sudo", "/bin/systemctl", action, "rascsi.service"]).returncode
== 0
)
| def rascsi_service(action):
# start/stop/restart
| return (
subprocess.run(["sudo", "/bin/systemctl", action, "rascsi.service"]).returncode
== 0
)
| return True
return False
def daynaport_setup_bridge(interface):
return subprocess.run(
[f"{base_dir}../RASCSI/src/raspberrypi/setup_bridge.sh", interface],
capture_output=True,
)
def rascsi_service(action):
# start/stop/restart
| 64 | 64 | 47 | 15 | 49 | hsiboy/RASCSI | src/web/ractl_cmds.py | Python | rascsi_service | rascsi_service | 128 | 133 | 128 | 129 | be852980dc8d7bd93e8503a69280b788d2d1da71 | bigcode/the-stack | train |
b8023fb320e3887321051751 | train | function | def list_config_files():
files_list = []
for root, dirs, files in os.walk(base_dir):
for file in files:
if file.endswith(".csv"):
files_list.append(file)
return files_list
| def list_config_files():
| files_list = []
for root, dirs, files in os.walk(base_dir):
for file in files:
if file.endswith(".csv"):
files_list.append(file)
return files_list
| : move formatting to template
"{:,.0f}".format(
os.path.getsize(os.path.join(path, file)) / float(1 << 20)
)
+ " MB",
)
for file in files
]
)
return files_list
def list_config_file... | 64 | 64 | 47 | 5 | 58 | hsiboy/RASCSI | src/web/ractl_cmds.py | Python | list_config_files | list_config_files | 40 | 46 | 40 | 40 | d4c56eb93486372f46275f5c2b6f1d95d624aac1 | bigcode/the-stack | train |
3012ae8fdf110b95be50c036 | train | function | def attach_image(scsi_id, image, device_type):
if device_type == "SCCD" and get_type(scsi_id) == "SCCD":
return insert(scsi_id, image)
elif device_type == "SCDP":
attach_daynaport(scsi_id)
else:
if device_type == "SCCD":
device_type = "cd"
return subprocess.run(
... | def attach_image(scsi_id, image, device_type):
| if device_type == "SCCD" and get_type(scsi_id) == "SCCD":
return insert(scsi_id, image)
elif device_type == "SCDP":
attach_daynaport(scsi_id)
else:
if device_type == "SCCD":
device_type = "cd"
return subprocess.run(
["rasctl", "-c", "attach", "-t", dev... | valid_list = list(range(8))
for id in invalid_list:
valid_list.remove(id)
valid_list.reverse()
return valid_list
def get_type(scsi_id):
return list_devices()[int(scsi_id)]["type"]
def attach_image(scsi_id, image, device_type):
| 63 | 64 | 121 | 12 | 51 | hsiboy/RASCSI | src/web/ractl_cmds.py | Python | attach_image | attach_image | 67 | 78 | 67 | 67 | afc9b5f2f160f8f57c6e572f8ae20b6b9ff05e5b | bigcode/the-stack | train |
39b9ba391ba0f472b5e5c931 | train | function | def insert(scsi_id, image):
return subprocess.run(
["rasctl", "-i", scsi_id, "-c", "insert", "-f", image], capture_output=True
)
| def insert(scsi_id, image):
| return subprocess.run(
["rasctl", "-i", scsi_id, "-c", "insert", "-f", image], capture_output=True
)
| (
["rasctl", "-c", "disconnect", "-i", scsi_id], capture_output=True
)
def eject_by_id(scsi_id):
return subprocess.run(["rasctl", "-i", scsi_id, "-c", "eject"])
def insert(scsi_id, image):
| 63 | 64 | 42 | 8 | 55 | hsiboy/RASCSI | src/web/ractl_cmds.py | Python | insert | insert | 100 | 103 | 100 | 100 | e04254c854058e7f547465b79aa347e3c018ddd8 | bigcode/the-stack | train |
879d1f5b9f9596a375c5ae64 | train | function | def detach_by_id(scsi_id):
return subprocess.run(["rasctl", "-c" "detach", "-i", scsi_id], capture_output=True)
| def detach_by_id(scsi_id):
| return subprocess.run(["rasctl", "-c" "detach", "-i", scsi_id], capture_output=True)
| if device_type == "SCCD":
device_type = "cd"
return subprocess.run(
["rasctl", "-c", "attach", "-t", device_type, "-i", scsi_id, "-f", image],
capture_output=True,
)
def detach_by_id(scsi_id):
| 64 | 64 | 33 | 8 | 56 | hsiboy/RASCSI | src/web/ractl_cmds.py | Python | detach_by_id | detach_by_id | 81 | 82 | 81 | 81 | e4d9673a124c262d556d8884ed5d2014b002647f | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.