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
bd69da94ce5e9adcfc20dbeb
train
function
def assert_consistent_resolve_parameters(val: Any): names = cirq.parameter_names(val) symbols = cirq.parameter_symbols(val) assert {symbol.name for symbol in symbols} == names if not cirq.is_parameterized(val): assert not names assert not symbols else: # Try to resolve all ...
def assert_consistent_resolve_parameters(val: Any):
names = cirq.parameter_names(val) symbols = cirq.parameter_symbols(val) assert {symbol.name for symbol in symbols} == names if not cirq.is_parameterized(val): assert not names assert not symbols else: # Try to resolve all parameters with numbers. This may fail if some of ...
# # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ...
87
87
293
11
75
BearerPipelineTest/Cirq
cirq-core/cirq/testing/consistent_resolve_parameters.py
Python
assert_consistent_resolve_parameters
assert_consistent_resolve_parameters
21
50
21
21
00d822497ec12d510cc8f9017e9df459e2b4a048
bigcode/the-stack
train
a63932bb18fdeff04b3a7ca7
train
class
class F3Scorer(CustomScorer): _binary = True _multiclass = True _maximize = True _perfect_score = 1 _display_name = "F3 Score" _threshold_optimizer = "f2" # closest match to F3 @staticmethod def _metric(tp, fp, tn, fn): precision = tp / (tp + fp) recall = tp / (tp + fn)...
class F3Scorer(CustomScorer):
_binary = True _multiclass = True _maximize = True _perfect_score = 1 _display_name = "F3 Score" _threshold_optimizer = "f2" # closest match to F3 @staticmethod def _metric(tp, fp, tn, fn): precision = tp / (tp + fp) recall = tp / (tp + fn) beta2 = 3**2 # F3 ...
"""F3 Score""" import typing import numpy as np from h2oaicore.metrics import CustomScorer, prep_actual_predicted from sklearn.preprocessing import label_binarize import h2o4gpu.util.metrics as daicx class F3Scorer(CustomScorer):
61
152
508
9
51
h2oai/driverlessai-recipes
scorers/classification/f3_score.py
Python
F3Scorer
F3Scorer
9
54
9
9
0ba8fb454c2c933c300033330b9a71c34a983f1e
bigcode/the-stack
train
40a775f0b1130c79b327c2bf
train
class
class SkinOnline: def __init__(self, info, textura): self.__infoSkin = info self.__texturaSkin = textura def getInfoSkin(self): return self.__infoSkin def setInfoSkin(self, nInfo): self.__infoSkin = nInfo def getTextura(self): return self.__texturaSkin def...
class SkinOnline:
def __init__(self, info, textura): self.__infoSkin = info self.__texturaSkin = textura def getInfoSkin(self): return self.__infoSkin def setInfoSkin(self, nInfo): self.__infoSkin = nInfo def getTextura(self): return self.__texturaSkin def setTextura(self, ...
class SkinOnline:
4
64
179
4
0
TanZng/patrones-combinados
4-Patron/python/SkinOnline.py
Python
SkinOnline
SkinOnline
1
25
1
1
073f9e8634179510a690c48ab64492f13ceff76c
bigcode/the-stack
train
a125914275c0ea6da85cc389
train
function
def check_sudoku(list_of_lists): index = (0,0) N = len(list_of_lists[0]) #O(N^3) for r in xrange(N): for c in xrange(N): index = (r,c) #check col wise for each_list_index in xrange(N): if (each_list_index, c) != index and \ list...
def check_sudoku(list_of_lists):
index = (0,0) N = len(list_of_lists[0]) #O(N^3) for r in xrange(N): for c in xrange(N): index = (r,c) #check col wise for each_list_index in xrange(N): if (each_list_index, c) != index and \ list_of_lists[each_list_index][c] == ...
def check_sudoku(list_of_lists):
8
64
158
8
0
codecakes/random_games
check_sudoku_soln.py
Python
check_sudoku
check_sudoku
1
18
1
1
b7b0f6a8a1acbbcbcaef475ae5e62b047c30e7f9
bigcode/the-stack
train
01a7b477a088f7cf2e8288ae
train
class
class RL_Trainer(object): def __init__(self, params): ############# ## INIT ############# # Get params, create logger self.params = params self.logger = Logger(self.params['logdir']) # Set random seeds seed = self.params['seed'] np.random.s...
class RL_Trainer(object):
def __init__(self, params): ############# ## INIT ############# # Get params, create logger self.params = params self.logger = Logger(self.params['logdir']) # Set random seeds seed = self.params['seed'] np.random.seed(seed) torch.man...
from collections import OrderedDict import pickle import os import sys import time import gym from gym import wrappers import numpy as np import torch from cs285.infrastructure import pytorch_util as ptu from cs285.infrastructure import utils from cs285.infrastructure.logger import Logger # how many rollouts to save...
102
256
2,170
6
95
JiaheXu/CS285_2020_pytorch
hw2/cs285/infrastructure/rl_trainer.py
Python
RL_Trainer
RL_Trainer
21
264
21
22
f5612957d28dfd548682bab97bdf0ec5dc3ad5f1
bigcode/the-stack
train
8066044f89089323be425151
train
function
def LoadFromDir(dir,datafile): if os.path.exists(datafile) == True: data = np.load(datafile) else: data = googlenet.LoadImageData(dir,extension,inputSize) np.save(datafile,data) return data
def LoadFromDir(dir,datafile):
if os.path.exists(datafile) == True: data = np.load(datafile) else: data = googlenet.LoadImageData(dir,extension,inputSize) np.save(datafile,data) return data
future__ import division, print_function, absolute_import import os,time from skimage import io,transform import numpy as np import googlenet import utils import tensorlayer as tl import tensorflow as tf extension=".jpg" inputSize=50 def LoadFromDir(dir,datafile):
64
64
57
8
55
yellowei/AI
tensorlayer/gtrain.py
Python
LoadFromDir
LoadFromDir
24
30
24
24
192f7823e8b9a87288c117b8a9885812f595f276
bigcode/the-stack
train
8a59c1f0ba5079d186ae229c
train
class
class PartialAsset(AssetMixin): """Represents a partial CDN asset, not necessarily from Discord's CDN. .. container:: operations .. describe:: str(x) Returns the URL of the CDN asset. .. describe:: len(x) Returns the length of the CDN asset's URL. .. des...
class PartialAsset(AssetMixin):
"""Represents a partial CDN asset, not necessarily from Discord's CDN. .. container:: operations .. describe:: str(x) Returns the URL of the CDN asset. .. describe:: len(x) Returns the length of the CDN asset's URL. .. describe:: x == y Chec...
/MPL/2.0/. """ # Custom Discord models that either fully or partially # mimic the ones found in discord.py. These are likely # only accessible through using custom converters and, # like any normal Discord model, are not intended for # manual creation and should be considered read-only. __all__ = ( "PartialAsse...
95
95
317
7
87
HitSyr/Sleepy
sleepy/mimics.py
Python
PartialAsset
PartialAsset
26
77
26
26
2c09887494bad0445ec27b96c7f1e157e94a8abd
bigcode/the-stack
train
c89cdf3bbcb9626d0c1d6684
train
class
class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('figures', '0003_pipelineerror'), ] operations = [ migrations.CreateModel( name='LearnerCourseGradeMetrics', fields=[ ('id', m...
class Migration(migrations.Migration):
dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('figures', '0003_pipelineerror'), ] operations = [ migrations.CreateModel( name='LearnerCourseGradeMetrics', fields=[ ('id', models.AutoField(verbose_name='ID', seria...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone from django.conf import settings import model_utils.fields class Migration(migrations.Migration):
48
90
301
7
40
bvenkatr/figures
figures/migrations/0004_learner_course_grade_metrics.py
Python
Migration
Migration
10
44
10
11
2400cd6cbe6d68e622b767ade6cdbf63dcd2206a
bigcode/the-stack
train
34153ec67a838a69f8ae1a50
train
function
def best_acc_weights(weights_folder): """ return the best acc .pth file in given folder, if no best acc weights file were found, return empty string """ files = os.listdir(weights_folder) if len(files) == 0: return '' regex_str = r'([A-Za-z0-9]+)-([0-9]+)-(regular|best)' ...
def best_acc_weights(weights_folder):
""" return the best acc .pth file in given folder, if no best acc weights file were found, return empty string """ files = os.listdir(weights_folder) if len(files) == 0: return '' regex_str = r'([A-Za-z0-9]+)-([0-9]+)-(regular|best)' best_files = [w for w in files if re....
])) return weight_files[-1] def last_epoch(weights_folder): weight_file = most_recent_weights(weights_folder) if not weight_file: raise Exception('no recent weights were found') resume_epoch = int(weight_file.split('-')[1]) return resume_epoch def best_acc_weights(weights_folder):
64
64
153
7
56
kingqiuol/pytorch-template
utils/utils.py
Python
best_acc_weights
best_acc_weights
52
67
52
52
25ffac6aa7e78fef887aa39ca714cd03261736ce
bigcode/the-stack
train
cf25d7a2948e327fe1b1bb1b
train
function
def most_recent_weights(weights_folder): """ return most recent created weights file if folder is empty return empty string """ weight_files = os.listdir(weights_folder) if len(weights_folder) == 0: return '' regex_str = r'([A-Za-z0-9]+)-([0-9]+)-(regular|best)' # sort ...
def most_recent_weights(weights_folder):
""" return most recent created weights file if folder is empty return empty string """ weight_files = os.listdir(weights_folder) if len(weights_folder) == 0: return '' regex_str = r'([A-Za-z0-9]+)-([0-9]+)-(regular|best)' # sort files by epoch weight_files = sorted(...
(os.listdir(os.path.join(net_weights, f)))] if len(folders) == 0: return '' # sort folders by folder created time folders = sorted(folders, key=lambda f: datetime.datetime.strptime(f, fmt)) return folders[-1] def most_recent_weights(weights_folder):
64
64
114
7
57
kingqiuol/pytorch-template
utils/utils.py
Python
most_recent_weights
most_recent_weights
28
42
28
28
dfbd94a369b2cfb1415fd15f57f41b8f6f6325fa
bigcode/the-stack
train
56d88926bb9854d90ce17927
train
function
def last_epoch(weights_folder): weight_file = most_recent_weights(weights_folder) if not weight_file: raise Exception('no recent weights were found') resume_epoch = int(weight_file.split('-')[1]) return resume_epoch
def last_epoch(weights_folder):
weight_file = most_recent_weights(weights_folder) if not weight_file: raise Exception('no recent weights were found') resume_epoch = int(weight_file.split('-')[1]) return resume_epoch
([A-Za-z0-9]+)-([0-9]+)-(regular|best)' # sort files by epoch weight_files = sorted(weight_files, key=lambda w: int(re.search(regex_str, w).groups()[1])) return weight_files[-1] def last_epoch(weights_folder):
64
64
49
6
58
kingqiuol/pytorch-template
utils/utils.py
Python
last_epoch
last_epoch
44
50
44
44
6697587389d3e5603462b0506fe93b2232a5a81c
bigcode/the-stack
train
d165e2c8b3e5563f69225470
train
function
def most_recent_folder(net_weights, fmt): """ return most recent created folder under net_weights if no none-empty folder were found, return empty folder """ # get subfolders in net_weights folders = os.listdir(net_weights) # filter out empty folders folders = [f for f in folder...
def most_recent_folder(net_weights, fmt):
""" return most recent created folder under net_weights if no none-empty folder were found, return empty folder """ # get subfolders in net_weights folders = os.listdir(net_weights) # filter out empty folders folders = [f for f in folders if len(os.listdir(os.path.join(net_weigh...
""" helper function author baiyu """ import os import re import datetime def most_recent_folder(net_weights, fmt):
27
64
128
9
17
kingqiuol/pytorch-template
utils/utils.py
Python
most_recent_folder
most_recent_folder
11
26
11
11
db8aad0d55e18b58b49dfe5e8b4e8071515be71f
bigcode/the-stack
train
6eeefd0a92bf115a82162ed3
train
class
class TestDryCosmeticChanges(TestCosmeticChanges): """Test cosmetic_changes not requiring a live wiki.""" dry = True def test_fixSelfInterwiki(self): """Test fixSelfInterwiki method.""" self.assertEqual('[[Foo bar]]', self.cct.fixSelfInterwiki('[[de:Foo bar]]')) ...
class TestDryCosmeticChanges(TestCosmeticChanges):
"""Test cosmetic_changes not requiring a live wiki.""" dry = True def test_fixSelfInterwiki(self): """Test fixSelfInterwiki method.""" self.assertEqual('[[Foo bar]]', self.cct.fixSelfInterwiki('[[de:Foo bar]]')) self.assertEqual('[[Foo bar]]', ...
#!/usr/bin/python3 """Test cosmetic_changes module.""" # # (C) Pywikibot team, 2015-2022 # # Distributed under the terms of the MIT license. # import unittest from contextlib import suppress from pywikibot import Page from pywikibot.cosmetic_changes import CANCEL, CosmeticChangesToolkit from pywikibot.site._namespace ...
185
256
1,510
11
174
Skhsouravhalder/newbot
tests/cosmetic_changes_tests.py
Python
TestDryCosmeticChanges
TestDryCosmeticChanges
32
182
32
33
82a399009c9f6f2aaba07cb4cd9b12293c86b227
bigcode/the-stack
train
baf6445639c9164c005b8f17
train
class
class TestCosmeticChangesPersian(TestCosmeticChanges): """Test cosmetic changes methods in Persian Wikipedia.""" family = 'wikipedia' code = 'fa' def test_fixArabicLetters_comma(self): """Test fixArabicLetters comma replacements.""" self.assertEqual(self.cct.fixArabicLetters(','), '،'...
class TestCosmeticChangesPersian(TestCosmeticChanges):
"""Test cosmetic changes methods in Persian Wikipedia.""" family = 'wikipedia' code = 'fa' def test_fixArabicLetters_comma(self): """Test fixArabicLetters comma replacements.""" self.assertEqual(self.cct.fixArabicLetters(','), '،') self.assertEqual(self.cct.fixArabicLetters('A,...
|name]] text', self.cct.cleanUpLinks('text[[ title | name ]]text')) self.assertEqual('text[[title|name]]text', self.cct.cleanUpLinks('text[[ title |name]]text')) self.assertEqual('text [[title|name]]text', self.cct.cleanUpLinks('...
156
157
525
12
144
Skhsouravhalder/newbot
tests/cosmetic_changes_tests.py
Python
TestCosmeticChangesPersian
TestCosmeticChangesPersian
499
544
499
500
13ecd24b46e97dacd0e03550f44d1274ad97ebcf
bigcode/the-stack
train
688b6f0a9ec98df7eb1e6bb0
train
class
class TestDryFixSyntaxSave(TestCosmeticChanges): """Test fixSyntaxSave not requiring a live wiki.""" dry = True @classmethod def setUpClass(cls): """Setup class for all tests.""" super().setUpClass() cls.cct.site._siteinfo._cache['general'] = ( {'articlepath': '/wi...
class TestDryFixSyntaxSave(TestCosmeticChanges):
"""Test fixSyntaxSave not requiring a live wiki.""" dry = True @classmethod def setUpClass(cls): """Setup class for all tests.""" super().setUpClass() cls.cct.site._siteinfo._cache['general'] = ( {'articlepath': '/wiki/$1'}, True) cls.cct.site._namespaces = ...
Test fixReferences method.""" self.assertEqual('<ref name="Foo" />', self.cct.fixReferences('<ref name= "Foo" />')) self.assertEqual('<ref name="Foo">bar</ref>', self.cct.fixReferences('<ref name ="Foo">bar</ref>')) self.assertEqual('<ref name="F...
256
256
1,324
11
245
Skhsouravhalder/newbot
tests/cosmetic_changes_tests.py
Python
TestDryFixSyntaxSave
TestDryFixSyntaxSave
185
302
185
186
2ecd8d5aa093f1a095aa87f4b72e0fab972d2bf4
bigcode/the-stack
train
63ae1a54f857b025243bb27f
train
class
class TestCosmeticChangesISBN(TestCosmeticChanges): """Test CosmeticChanges ISBN fix.""" dry = True ISBN_DIGITERROR_RE = 'ISBN [0-9]+ is not [0-9]+ digits long' ISBN_INVALIDERROR_RE = 'Invalid ISBN found' ISBN_CHECKSUMERROR_RE = 'ISBN checksum of [0-9]+ is incorrect' ISBN_INVALIDCHECKERROR_RE...
class TestCosmeticChangesISBN(TestCosmeticChanges):
"""Test CosmeticChanges ISBN fix.""" dry = True ISBN_DIGITERROR_RE = 'ISBN [0-9]+ is not [0-9]+ digits long' ISBN_INVALIDERROR_RE = 'Invalid ISBN found' ISBN_CHECKSUMERROR_RE = 'ISBN checksum of [0-9]+ is incorrect' ISBN_INVALIDCHECKERROR_RE = 'checksum or check digit is invalid' ISBN_INVA...
# A single quotation is a 'non-Farsi' character self.assertEqual(self.cct.fixArabicLetters("',b"), "',b") self.assertEqual(self.cct.fixArabicLetters("a,'"), "a,'") self.assertEqual(self.cct.fixArabicLetters("','"), "','") # A space is a 'non-Farsi' character self.assertEqual(se...
225
225
752
11
214
Skhsouravhalder/newbot
tests/cosmetic_changes_tests.py
Python
TestCosmeticChangesISBN
TestCosmeticChangesISBN
549
623
549
550
91c1084794f17140e41a25145febf466d878caf9
bigcode/the-stack
train
2cd2978b18fc050ec5a5a2be
train
class
class TestCosmeticChanges(TestCase): """Test cosmetic changes methods.""" family = 'wikipedia' code = 'de' @classmethod def setUpClass(cls): """Setup class for all tests.""" super().setUpClass() cls.cct = CosmeticChangesToolkit(Page(cls.site, 'Test'))
class TestCosmeticChanges(TestCase):
"""Test cosmetic changes methods.""" family = 'wikipedia' code = 'de' @classmethod def setUpClass(cls): """Setup class for all tests.""" super().setUpClass() cls.cct = CosmeticChangesToolkit(Page(cls.site, 'Test'))
suppress from pywikibot import Page from pywikibot.cosmetic_changes import CANCEL, CosmeticChangesToolkit from pywikibot.site._namespace import NamespacesDict from pywikibot.tools import has_module from tests.aspects import TestCase class TestCosmeticChanges(TestCase):
64
64
69
8
55
Skhsouravhalder/newbot
tests/cosmetic_changes_tests.py
Python
TestCosmeticChanges
TestCosmeticChanges
18
29
18
19
5213e034c938877752cd7ad752c513a3c20e459b
bigcode/the-stack
train
8431ee2f200d6227ace67c09
train
class
class TestLiveCosmeticChanges(TestCosmeticChanges): """Test cosmetic_changes requiring a live wiki.""" def test_removeEmptySections(self): """Test removeEmptySections method.""" content = '\nSome content' # same level self.assertEqual( '\n==Bar==' + content, ...
class TestLiveCosmeticChanges(TestCosmeticChanges):
"""Test cosmetic_changes requiring a live wiki.""" def test_removeEmptySections(self): """Test removeEmptySections method.""" content = '\nSome content' # same level self.assertEqual( '\n==Bar==' + content, self.cct.removeEmptySections('\n== Foo ==\n\n==B...
n' '[[:Category:Example|Description]]\n' '[[:Datei:Example.svg]]\n' '[[:File:Example.svg|Description]]\n' '[[:Category:Example]]\n' '[[:Kategorie:Example|Description]]\n' '[[:File:Example.svg]]\n' '[[:Datei:Example.svg|Description]]\n',...
255
256
2,088
11
244
Skhsouravhalder/newbot
tests/cosmetic_changes_tests.py
Python
TestLiveCosmeticChanges
TestLiveCosmeticChanges
305
496
305
306
a22b775081ede7f57930752c966a2e1bd6a88995
bigcode/the-stack
train
f59136eb18a5196e84acd7cf
train
class
class AccountInvoiceLine(models.Model): _inherit = ['account.move.line'] def get_digital_purchases(self): partner = self.env.user.partner_id # Get paid invoices purchases = self.sudo().search_read( domain=[ ('move_id.invoice_payment_state', '=', 'paid'), ...
class AccountInvoiceLine(models.Model):
_inherit = ['account.move.line'] def get_digital_purchases(self): partner = self.env.user.partner_id # Get paid invoices purchases = self.sudo().search_read( domain=[ ('move_id.invoice_payment_state', '=', 'paid'), ('move_id.partner_id', '=',...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class AccountInvoiceLine(models.Model):
37
65
219
7
29
VaibhavBhujade/Blockchain-ERP-interoperability
odoo-13.0/addons/website_sale_digital/models/account_invoice.py
Python
AccountInvoiceLine
AccountInvoiceLine
7
32
7
8
b49804190232ff3d27ed827eeb45296eedd1ef67
bigcode/the-stack
train
6c93990a2723e0cf6da3063c
train
function
def underscore_to_hyphen(data): if isinstance(data, list): for elem in data: elem = underscore_to_hyphen(elem) elif isinstance(data, dict): new_data = {} for k, v in data.items(): new_data[k.replace('_', '-')] = underscore_to_hyphen(v) data = new_data ...
def underscore_to_hyphen(data):
if isinstance(data, list): for elem in data: elem = underscore_to_hyphen(elem) elif isinstance(data, dict): new_data = {} for k, v in data.items(): new_data[k.replace('_', '-')] = underscore_to_hyphen(v) data = new_data return data
', 'default_command_log', 'log', 'name', 'shell_commands'] dictionary = {} for attribute in option_list: if attribute in json and json[attribute] is not None: dictionary[attribute] = json[attribute] return dictionary def underscore_to_hyphen(data):
64
64
79
8
55
fortinet-solutions-cse/ansible_fgt_modules
v6.0.6/ssh_filter/fortios_ssh_filter_profile.py
Python
underscore_to_hyphen
underscore_to_hyphen
318
328
318
318
fbdcd75a0a412e97e109411d03aac62c5bdbed76
bigcode/the-stack
train
07f29191c0f412eec3d75d5e
train
function
def login(data, fos): host = data['host'] username = data['username'] password = data['password'] ssl_verify = data['ssl_verify'] fos.debug('on') if 'https' in data and not data['https']: fos.https('off') else: fos.https('on') fos.login(host, username, password, verify=...
def login(data, fos):
host = data['host'] username = data['username'] password = data['password'] ssl_verify = data['ssl_verify'] fos.debug('on') if 'https' in data and not data['https']: fos.https('off') else: fos.https('on') fos.login(host, username, password, verify=ssl_verify)
.3" ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.connection import Connection from ansible.module_utils.network.fortios.fortios import FortiOSHandler from ansible.module_utils.network.fortimanager.common import FAIL_SOCKET_MSG def login(data, fos):
64
64
86
6
57
fortinet-solutions-cse/ansible_fgt_modules
v6.0.6/ssh_filter/fortios_ssh_filter_profile.py
Python
login
login
291
303
291
291
d2d6c6d6c852c3b07056af4740462b139cdffd4f
bigcode/the-stack
train
712717801e5a473cf465ff09
train
function
def is_successful_status(status): return status['status'] == "success" or \ status['http_method'] == "DELETE" and status['http_status'] == 404
def is_successful_status(status):
return status['status'] == "success" or \ status['http_method'] == "DELETE" and status['http_status'] == 404
fos.set('ssh-filter', 'profile', data=filtered_data, vdom=vdom) elif state == "absent": return fos.delete('ssh-filter', 'profile', mkey=filtered_data['name'], ...
64
64
39
7
57
fortinet-solutions-cse/ansible_fgt_modules
v6.0.6/ssh_filter/fortios_ssh_filter_profile.py
Python
is_successful_status
is_successful_status
355
357
355
355
a3e73e1b2b5e77311eef5ec7cab06d9275b33f85
bigcode/the-stack
train
57a7717d4696f456c4e62af4
train
function
def ssh_filter_profile(data, fos): vdom = data['vdom'] if 'state' in data and data['state']: state = data['state'] elif 'state' in data['ssh_filter_profile'] and data['ssh_filter_profile']: state = data['ssh_filter_profile']['state'] else: state = True ssh_filter_profile_data...
def ssh_filter_profile(data, fos):
vdom = data['vdom'] if 'state' in data and data['state']: state = data['state'] elif 'state' in data['ssh_filter_profile'] and data['ssh_filter_profile']: state = data['ssh_filter_profile']['state'] else: state = True ssh_filter_profile_data = data['ssh_filter_profile'] f...
= underscore_to_hyphen(elem) elif isinstance(data, dict): new_data = {} for k, v in data.items(): new_data[k.replace('_', '-')] = underscore_to_hyphen(v) data = new_data return data def ssh_filter_profile(data, fos):
64
64
173
8
55
fortinet-solutions-cse/ansible_fgt_modules
v6.0.6/ssh_filter/fortios_ssh_filter_profile.py
Python
ssh_filter_profile
ssh_filter_profile
331
352
331
331
9baba6d0407ca883c8db9b64eddef74d2aa76417
bigcode/the-stack
train
89504f403a7f447f71c4e875
train
function
def fortios_ssh_filter(data, fos): if data['ssh_filter_profile']: resp = ssh_filter_profile(data, fos) return not is_successful_status(resp), \ resp['status'] == "success", \ resp
def fortios_ssh_filter(data, fos):
if data['ssh_filter_profile']: resp = ssh_filter_profile(data, fos) return not is_successful_status(resp), \ resp['status'] == "success", \ resp
mkey=filtered_data['name'], vdom=vdom) def is_successful_status(status): return status['status'] == "success" or \ status['http_method'] == "DELETE" and status['http_status'] == 404 def fortios_ssh_filter(data, fos):
64
64
51
10
53
fortinet-solutions-cse/ansible_fgt_modules
v6.0.6/ssh_filter/fortios_ssh_filter_profile.py
Python
fortios_ssh_filter
fortios_ssh_filter
360
367
360
361
4cc0a610fc770a7b1a05c66817d45dbc193e4786
bigcode/the-stack
train
2d2ed3d69c079a8c06e3c44a
train
function
def main(): fields = { "host": {"required": False, "type": "str"}, "username": {"required": False, "type": "str"}, "password": {"required": False, "type": "str", "default": "", "no_log": True}, "vdom": {"required": False, "type": "str", "default": "root"}, "https": {"required...
def main():
fields = { "host": {"required": False, "type": "str"}, "username": {"required": False, "type": "str"}, "password": {"required": False, "type": "str", "default": "", "no_log": True}, "vdom": {"required": False, "type": "str", "default": "root"}, "https": {"required": False, "t...
state']: state = data['state'] elif 'state' in data['ssh_filter_profile'] and data['ssh_filter_profile']: state = data['ssh_filter_profile']['state'] else: state = True ssh_filter_profile_data = data['ssh_filter_profile'] filtered_data = underscore_to_hyphen(filter_ssh_filter_pro...
239
239
798
3
235
fortinet-solutions-cse/ansible_fgt_modules
v6.0.6/ssh_filter/fortios_ssh_filter_profile.py
Python
main
main
370
448
370
370
e4b9683fd8a3d3d9979695ec0aa539ed99c8c1c9
bigcode/the-stack
train
ac9f73ecc2fef16db806ca19
train
function
def filter_ssh_filter_profile_data(json): option_list = ['block', 'default_command_log', 'log', 'name', 'shell_commands'] dictionary = {} for attribute in option_list: if attribute in json and json[attribute] is not None: dictionary[attribute] = json[attribute] r...
def filter_ssh_filter_profile_data(json):
option_list = ['block', 'default_command_log', 'log', 'name', 'shell_commands'] dictionary = {} for attribute in option_list: if attribute in json and json[attribute] is not None: dictionary[attribute] = json[attribute] return dictionary
data['ssl_verify'] fos.debug('on') if 'https' in data and not data['https']: fos.https('off') else: fos.https('on') fos.login(host, username, password, verify=ssl_verify) def filter_ssh_filter_profile_data(json):
64
64
71
9
55
fortinet-solutions-cse/ansible_fgt_modules
v6.0.6/ssh_filter/fortios_ssh_filter_profile.py
Python
filter_ssh_filter_profile_data
filter_ssh_filter_profile_data
306
315
306
306
8446eaa97c6ef0807c9f4283f3a735e38063d899
bigcode/the-stack
train
de2c43da788901257c5e6431
train
class
class ExternalChallengeAdmin(ModelAdmin): readonly_fields = ("creator",) autocomplete_fields = ("publications",)
class ExternalChallengeAdmin(ModelAdmin):
readonly_fields = ("creator",) autocomplete_fields = ("publications",)
from django.contrib import admin from django.contrib.admin import ModelAdmin from grandchallenge.challenges.models import ( Challenge, ChallengeSeries, ExternalChallenge, ) class ChallengeAdmin(ModelAdmin): readonly_fields = ("creator",) autocomplete_fields = ("publications",) class ExternalChall...
64
64
24
7
57
amickan/grand-challenge.org
app/grandchallenge/challenges/admin.py
Python
ExternalChallengeAdmin
ExternalChallengeAdmin
16
18
16
16
367d4f99e3ebb1f30fb1a4ff1eecc3216651b393
bigcode/the-stack
train
ef9d602dda1541fca5fd17bb
train
class
class ChallengeAdmin(ModelAdmin): readonly_fields = ("creator",) autocomplete_fields = ("publications",)
class ChallengeAdmin(ModelAdmin):
readonly_fields = ("creator",) autocomplete_fields = ("publications",)
from django.contrib import admin from django.contrib.admin import ModelAdmin from grandchallenge.challenges.models import ( Challenge, ChallengeSeries, ExternalChallenge, ) class ChallengeAdmin(ModelAdmin):
40
64
23
6
34
amickan/grand-challenge.org
app/grandchallenge/challenges/admin.py
Python
ChallengeAdmin
ChallengeAdmin
11
13
11
11
6b958d8f5c8258c90e7b67bfe62d6f31fe3b4f0e
bigcode/the-stack
train
c2ced7cd6761ab3dfa02b5b5
train
function
def flush(chapter, header, chunk): fn = 'index.html' if chapter == 0 else str(chapter) + '.html' with open('split/' + fn, 'w') as out: out.write(header) links(out, chapter) out.write(chunk) links(out, chapter) out.write('</body></html>')
def flush(chapter, header, chunk):
fn = 'index.html' if chapter == 0 else str(chapter) + '.html' with open('split/' + fn, 'w') as out: out.write(header) links(out, chapter) out.write(chunk) links(out, chapter) out.write('</body></html>')
pass try: out.write('Next: <A HREF="' + str(chapter+1) +'.html">' + str(chapter+1) + '. ' + titles[chapter+1] + '</A>. ') except: pass def flush(chapter, header, chunk):
64
64
75
9
54
bhalevy/seastar
doc/htmlsplit.py
Python
flush
flush
44
51
44
44
8320aa43d3ca7ab8d0921d05831e05648cb51039
bigcode/the-stack
train
bbfb597e0df4f9542e2f0de7
train
function
def links(out, chapter): if chapter == 0: return out.write('<A HREF="index.html">Back to table of contents</A>. ') try: out.write('Previous: <A HREF="' + str(chapter-1) +'.html">' + str(chapter-1) + '. ' + titles[chapter-1] + '</A>. ') except: pass try: out.write('Nex...
def links(out, chapter):
if chapter == 0: return out.write('<A HREF="index.html">Back to table of contents</A>. ') try: out.write('Previous: <A HREF="' + str(chapter-1) +'.html">' + str(chapter-1) + '. ' + titles[chapter-1] + '</A>. ') except: pass try: out.write('Next: <A HREF="' + str(chapt...
the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import re titles = {} sections = {} def links(out, chapter):
64
64
142
6
58
bhalevy/seastar
doc/htmlsplit.py
Python
links
links
32
43
32
32
4e17c66d8193784b47d696e6e08bb2470ee94f0c
bigcode/the-stack
train
9b8d5058ebe4a871b4136c32
train
class
class BaseTest: @classmethod def setup_class(cls): cls.hash_key = "demoCHANGED" cls.vid = "demo" cls.order_id = "573737373673" cls.amount = 10 cls.test_number = "000000000000" cls.test_email = "write2sartim@gmail.com" cls.instance = Ipay(cls.hash_key) ...
class BaseTest: @classmethod
def setup_class(cls): cls.hash_key = "demoCHANGED" cls.vid = "demo" cls.order_id = "573737373673" cls.amount = 10 cls.test_number = "000000000000" cls.test_email = "write2sartim@gmail.com" cls.instance = Ipay(cls.hash_key) cls.callback_url = "https://p...
from collections import OrderedDict from ipay_sdk.gateway import Ipay class BaseTest: @classmethod
23
87
292
8
14
sartim/ipay-sdk
tests/base.py
Python
BaseTest
BaseTest
5
35
5
6
810a113d5914b0dbbc6186000a6278782a9918f0
bigcode/the-stack
train
166787d9bbdffa29c83fc186
train
class
class HIVE_BIN_HEADER(LittleEndianStructure): _fields_ = [ ("signature", c_char*4), ("offset", c_int), ("size", c_int), ("unknown1", c_int), ("unknown2", c_int), ...
class HIVE_BIN_HEADER(LittleEndianStructure):
_fields_ = [ ("signature", c_char*4), ("offset", c_int), ("size", c_int), ("unknown1", c_int), ("unknown2", c_int), ("timestamp", c_uby...
last_hbin_offset", c_int), ("unknown2", c_int), ("hivename", c_wchar*32), ("unknown3", c_char*396), ("checksum", c_int) ] class HIVE_BIN_HEADER(LittleEndianStructure):
63
64
88
10
53
jungheum/cfreds-2017-winreg
ugrd-assistance-tools_win/[cr]-03_last-half.py
Python
HIVE_BIN_HEADER
HIVE_BIN_HEADER
54
63
54
54
71742029eb6b6eaa35a7bf5b74d2f56c5c71144c
bigcode/the-stack
train
4e3cb0e6087c51da772ef8e4
train
function
def cr_type3(buffer, filesize): # get the offset of root cell (0x24 from the beginning of hive file) header = static_cast(buffer[:sizeof(HIVE_HEADER)], HIVE_HEADER) # traverse all hbin header cells hbins = [] offset = FIRST_HBIN_OFFSET while 1: hbin_header = static_cast(buffer[o...
def cr_type3(buffer, filesize): # get the offset of root cell (0x24 from the beginning of hive file)
header = static_cast(buffer[:sizeof(HIVE_HEADER)], HIVE_HEADER) # traverse all hbin header cells hbins = [] offset = FIRST_HBIN_OFFSET while 1: hbin_header = static_cast(buffer[offset:offset+sizeof(HIVE_BIN_HEADER)], HIVE_BIN_HEADER) if hbin_header.signature.decode("utf-8") ...
8), ("unknown3", c_int) ] def static_cast(buffer, structure): return cast(c_char_p(buffer), POINTER(structure)).contents def cr_type3(buffer, filesize): # get the offset of root cell (0x24 from the beginning of hive file)
63
64
184
27
35
jungheum/cfreds-2017-winreg
ugrd-assistance-tools_win/[cr]-03_last-half.py
Python
cr_type3
cr_type3
68
86
68
69
43a50b506ae634554d1ea7807f1648b6c4057200
bigcode/the-stack
train
9f513cb4b4eb8ae0c5bf4752
train
class
class HIVE_HEADER(LittleEndianStructure): _fields_ = [ ("signature", c_char*4), ("primary_sequence_number", c_int), ("secondary_sequence_number", c_int), ("timestamp", c_ubyte*8), ("major_version", c_int), ("min...
class HIVE_HEADER(LittleEndianStructure):
_fields_ = [ ("signature", c_char*4), ("primary_sequence_number", c_int), ("secondary_sequence_number", c_int), ("timestamp", c_ubyte*8), ("major_version", c_int), ("minor_version", c_int), (...
.argv) == 2 SIGNATURE_HIVE = "regf" SIGNATURE_HBIN = "hbin" FRAGMENT_HIVE_BLOCK = 0x1000 # normally 1 cluster in Windows OS FIRST_HBIN_OFFSET = FRAGMENT_HIVE_BLOCK class HIVE_HEADER(LittleEndianStructure):
64
64
159
9
54
jungheum/cfreds-2017-winreg
ugrd-assistance-tools_win/[cr]-03_last-half.py
Python
HIVE_HEADER
HIVE_HEADER
36
52
36
36
9c16c8e47ac41bc2224021622b65e799a0540138
bigcode/the-stack
train
17d4bb6c5bc1a8d707212055
train
function
def overwrite(fi, filename, c_list): fl = open(filename + '.txt', 'w', encoding='utf-8') for c_item in c_list: fi.seek(c_item[0], os.SEEK_SET) data = (b'NIST+CFTT+CFReDS' * int(c_item[1]/16)) fi.write(data) fl.write('offset %04d \t\t size %04d\n' % (c_item[0], c_item[1])) fl....
def overwrite(fi, filename, c_list):
fl = open(filename + '.txt', 'w', encoding='utf-8') for c_item in c_list: fi.seek(c_item[0], os.SEEK_SET) data = (b'NIST+CFTT+CFReDS' * int(c_item[1]/16)) fi.write(data) fl.write('offset %04d \t\t size %04d\n' % (c_item[0], c_item[1])) fl.close()
+= hbin_header.size # build corrupted fragment list (c_list) with specific conditions c_list = [] for i in range (int(len(hbins)/2), len(hbins)): c_list.append(hbins[i]) return c_list def overwrite(fi, filename, c_list):
64
64
110
9
54
jungheum/cfreds-2017-winreg
ugrd-assistance-tools_win/[cr]-03_last-half.py
Python
overwrite
overwrite
88
95
88
88
4fee5d2ad7347117890e3c2c4eb0452e43be71cb
bigcode/the-stack
train
6af470a133fcd6186dde3bf0
train
function
def static_cast(buffer, structure): return cast(c_char_p(buffer), POINTER(structure)).contents
def static_cast(buffer, structure):
return cast(c_char_p(buffer), POINTER(structure)).contents
c_int), ("size", c_int), ("unknown1", c_int), ("unknown2", c_int), ("timestamp", c_ubyte*8), ("unknown3", c_int) ] def static_cast(buffer, structure):
63
64
21
7
56
jungheum/cfreds-2017-winreg
ugrd-assistance-tools_win/[cr]-03_last-half.py
Python
static_cast
static_cast
65
66
65
65
ce235e5c6c947458335aaa974d19bad622751bfc
bigcode/the-stack
train
fca43a9323514e70cfb7d31b
train
class
class ABCTestCase(unittest.TestCase): def validate_abstract_methods(self, abc, *names): methodstubs = dict.fromkeys(names, lambda s, *args: 0) # everything should work will all required methods are present C = type('C', (abc,), methodstubs) C() # instantiation should fail ...
class ABCTestCase(unittest.TestCase):
def validate_abstract_methods(self, abc, *names): methodstubs = dict.fromkeys(names, lambda s, *args: 0) # everything should work will all required methods are present C = type('C', (abc,), methodstubs) C() # instantiation should fail if a required method is missing ...
_asdict self.assertEqual(t._asdict(), dict(zip(T._fields, values))) # test _replace t = T._make(values) newvalues = tuple(v*10 for v in values) newt = t._replace(**dict(zip(T._fields, newvalues))) self.assertEqual(newt, newvalues) # test _fields self.asse...
165
165
550
8
157
heamon7/CPython-2.7.8
Lib/test/test_collections.py
Python
ABCTestCase
ABCTestCase
261
328
261
262
5b00cffb65feafa79f114bd9128a644d05dbd587
bigcode/the-stack
train
1ad7812e06f841dddea56cbc
train
class
class TestCounter(unittest.TestCase): def test_basics(self): c = Counter('abcaba') self.assertEqual(c, Counter({'a':3 , 'b': 2, 'c': 1})) self.assertEqual(c, Counter(a=3, b=2, c=1)) self.assertIsInstance(c, dict) self.assertIsInstance(c, Mapping) self.assertTrue(issu...
class TestCounter(unittest.TestCase):
def test_basics(self): c = Counter('abcaba') self.assertEqual(c, Counter({'a':3 , 'b': 2, 'c': 1})) self.assertEqual(c, Counter(a=3, b=2, c=1)) self.assertIsInstance(c, dict) self.assertIsInstance(c, Mapping) self.assertTrue(issubclass(Counter, dict)) self.ass...
item__', '__delitem__') def test_Sequence(self): for sample in [tuple, list, str]: self.assertIsInstance(sample(), Sequence) self.assertTrue(issubclass(sample, Sequence)) self.assertTrue(issubclass(basestring, Sequence)) self.assertIsInstance(range(10), Sequence) ...
256
256
2,004
7
249
heamon7/CPython-2.7.8
Lib/test/test_collections.py
Python
TestCounter
TestCounter
834
998
834
835
84ac128842fff5829a89f6b97c36a7362539777f
bigcode/the-stack
train
2f4b2fa4c1f9bf7fa3572f19
train
class
class TestCollectionABCs(ABCTestCase): # XXX For now, we only test some virtual inheritance properties. # We should also test the proper behavior of the collection ABCs # as real base classes or mix-in classes. def test_Set(self): for sample in [set, frozenset]: self.assertIsInstan...
class TestCollectionABCs(ABCTestCase): # XXX For now, we only test some virtual inheritance properties. # We should also test the proper behavior of the collection ABCs # as real base classes or mix-in classes.
def test_Set(self): for sample in [set, frozenset]: self.assertIsInstance(sample(), Set) self.assertTrue(issubclass(sample, Set)) self.validate_abstract_methods(Set, '__contains__', '__iter__', '__len__') class MySet(Set): def __contains__(self, x): ...
): pass self.assertTrue(issubclass(C, B)) self.assertFalse(issubclass(int, C)) def test_registration(self): for B in Hashable, Iterable, Iterator, Sized, Container, Callable: class C: __metaclass__ = type __hash__ = None #...
256
256
2,816
50
206
heamon7/CPython-2.7.8
Lib/test/test_collections.py
Python
TestCollectionABCs
TestCollectionABCs
507
832
507
512
f378c8c72c1f483f5a156141946a4f45eb3731c7
bigcode/the-stack
train
d28e3e9a730bddf780f9971e
train
class
class TestOneTrickPonyABCs(ABCTestCase): def test_Hashable(self): # Check some non-hashables non_samples = [list(), set(), dict()] for x in non_samples: self.assertNotIsInstance(x, Hashable) self.assertFalse(issubclass(type(x), Hashable), repr(type(x))) # Che...
class TestOneTrickPonyABCs(ABCTestCase):
def test_Hashable(self): # Check some non-hashables non_samples = [list(), set(), dict()] for x in non_samples: self.assertNotIsInstance(x, Hashable) self.assertFalse(issubclass(type(x), Hashable), repr(type(x))) # Check some hashables samples = [None,...
(C, abc)) def validate_comparison(self, instance): ops = ['lt', 'gt', 'le', 'ge', 'ne', 'or', 'and', 'xor', 'sub'] operators = {} for op in ops: name = '__' + op + '__' operators[name] = getattr(operator, name) class Other: def __init__(self): ...
256
256
1,397
14
242
heamon7/CPython-2.7.8
Lib/test/test_collections.py
Python
TestOneTrickPonyABCs
TestOneTrickPonyABCs
330
485
330
331
7c5a78f0f792382e91e75d86fe0755905c5fbd6d
bigcode/the-stack
train
5427d5307a6e031bd7ab4c9a
train
class
class TestOrderedDict(unittest.TestCase): def test_init(self): with self.assertRaises(TypeError): OrderedDict([('a', 1), ('b', 2)], None) # too many args pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)] self.assertEqual(sorted(OrderedDic...
class TestOrderedDict(unittest.TestCase):
def test_init(self): with self.assertRaises(TypeError): OrderedDict([('a', 1), ('b', 2)], None) # too many args pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)] self.assertEqual(sorted(OrderedDict(dict(pairs)).items()), pairs) #...
def test_subtract(self): c = Counter(a=-5, b=0, c=5, d=10, e=15,g=40) c.subtract(a=1, b=2, c=-3, d=10, e=20, f=30, h=-50) self.assertEqual(c, Counter(a=-6, b=-2, c=8, d=0, e=-5, f=-30, g=40, h=50)) c = Counter(a=-5, b=0, c=5, d=10, e=15,g=40) c.subtract(Counter(a=1, b=2, c=-3...
256
256
3,076
8
248
heamon7/CPython-2.7.8
Lib/test/test_collections.py
Python
TestOrderedDict
TestOrderedDict
1,000
1,247
1,000
1,001
803d258e836a5154ec2422964409dc4fe3ab1cf5
bigcode/the-stack
train
79300260238c588c3a6c7992
train
class
class SubclassMappingTests(mapping_tests.BasicTestMappingProtocol): type2test = MyOrderedDict def test_popitem(self): d = self._empty_mapping() self.assertRaises(KeyError, d.popitem)
class SubclassMappingTests(mapping_tests.BasicTestMappingProtocol):
type2test = MyOrderedDict def test_popitem(self): d = self._empty_mapping() self.assertRaises(KeyError, d.popitem)
(mapping_tests.BasicTestMappingProtocol): type2test = OrderedDict def test_popitem(self): d = self._empty_mapping() self.assertRaises(KeyError, d.popitem) class MyOrderedDict(OrderedDict): pass class SubclassMappingTests(mapping_tests.BasicTestMappingProtocol):
64
64
47
12
51
heamon7/CPython-2.7.8
Lib/test/test_collections.py
Python
SubclassMappingTests
SubclassMappingTests
1,259
1,264
1,259
1,259
36b6206dc1c6eabef48e9f982c6b9818a02da1b9
bigcode/the-stack
train
65888a6c5fd115ef133c3ed0
train
class
class TestNamedTuple(unittest.TestCase): def test_factory(self): Point = namedtuple('Point', 'x y') self.assertEqual(Point.__name__, 'Point') self.assertEqual(Point.__slots__, ()) self.assertEqual(Point.__module__, __name__) self.assertEqual(Point.__getitem__, tuple.__getite...
class TestNamedTuple(unittest.TestCase):
def test_factory(self): Point = namedtuple('Point', 'x y') self.assertEqual(Point.__name__, 'Point') self.assertEqual(Point.__slots__, ()) self.assertEqual(Point.__module__, __name__) self.assertEqual(Point.__getitem__, tuple.__getitem__) self.assertEqual(Point._field...
, doctest, operator import inspect from test import test_support from collections import namedtuple, Counter, OrderedDict from test import mapping_tests import pickle, cPickle, copy from random import randrange, shuffle import keyword import re import sets import sys from collections import Hashable, Iterable, Iterator...
256
256
2,460
8
248
heamon7/CPython-2.7.8
Lib/test/test_collections.py
Python
TestNamedTuple
TestNamedTuple
58
259
58
59
986725945a6aca6187f168dd46ddcd7d2fa4ebab
bigcode/the-stack
train
87d6d1050597655282bcda13
train
function
def test_main(verbose=None): NamedTupleDocs = doctest.DocTestSuite(module=collections) test_classes = [TestNamedTuple, NamedTupleDocs, TestOneTrickPonyABCs, TestCollectionABCs, TestCounter, TestOrderedDict, GeneralMappingTests, SubclassMappingTests] test_support.run_u...
def test_main(verbose=None):
NamedTupleDocs = doctest.DocTestSuite(module=collections) test_classes = [TestNamedTuple, NamedTupleDocs, TestOneTrickPonyABCs, TestCollectionABCs, TestCounter, TestOrderedDict, GeneralMappingTests, SubclassMappingTests] test_support.run_unittest(*test_classes) te...
Dict(OrderedDict): pass class SubclassMappingTests(mapping_tests.BasicTestMappingProtocol): type2test = MyOrderedDict def test_popitem(self): d = self._empty_mapping() self.assertRaises(KeyError, d.popitem) import collections def test_main(verbose=None):
64
64
87
6
57
heamon7/CPython-2.7.8
Lib/test/test_collections.py
Python
test_main
test_main
1,268
1,274
1,268
1,268
4053d18abcf2d6f1bf3189a3122f5256c3d5ee3f
bigcode/the-stack
train
979437d05a0089a116c31f51
train
class
class MyOrderedDict(OrderedDict): pass
class MyOrderedDict(OrderedDict):
pass
.assertEqual(list(MyOD(items).items()), items) class GeneralMappingTests(mapping_tests.BasicTestMappingProtocol): type2test = OrderedDict def test_popitem(self): d = self._empty_mapping() self.assertRaises(KeyError, d.popitem) class MyOrderedDict(OrderedDict):
64
64
11
8
56
heamon7/CPython-2.7.8
Lib/test/test_collections.py
Python
MyOrderedDict
MyOrderedDict
1,256
1,257
1,256
1,256
88708a4f36b8c5f7c9008c698a9e4e90df8c1ec3
bigcode/the-stack
train
ca2fe334531905dd49c02771
train
class
class WithSet(MutableSet): def __init__(self, it=()): self.data = set(it) def __len__(self): return len(self.data) def __iter__(self): return iter(self.data) def __contains__(self, item): return item in self.data def add(self, item): self.data.add(item) ...
class WithSet(MutableSet):
def __init__(self, it=()): self.data = set(it) def __len__(self): return len(self.data) def __iter__(self): return iter(self.data) def __contains__(self, item): return item in self.data def add(self, item): self.data.add(item) def discard(self, item):...
__metaclass__ = type __hash__ = None # Make sure it isn't hashable by default self.assertFalse(issubclass(C, B), B.__name__) B.register(C) self.assertTrue(issubclass(C, B)) class WithSet(MutableSet):
64
64
93
7
57
heamon7/CPython-2.7.8
Lib/test/test_collections.py
Python
WithSet
WithSet
487
505
487
488
0b1df45f9a7acaf5ad6113631d8dea5f9e02cf71
bigcode/the-stack
train
b51988179db311148cbb9c64
train
class
class GeneralMappingTests(mapping_tests.BasicTestMappingProtocol): type2test = OrderedDict def test_popitem(self): d = self._empty_mapping() self.assertRaises(KeyError, d.popitem)
class GeneralMappingTests(mapping_tests.BasicTestMappingProtocol):
type2test = OrderedDict def test_popitem(self): d = self._empty_mapping() self.assertRaises(KeyError, d.popitem)
OrderedDict): def update(self, *args, **kwds): raise Exception() items = [('a', 1), ('c', 3), ('b', 2)] self.assertEqual(list(MyOD(items).items()), items) class GeneralMappingTests(mapping_tests.BasicTestMappingProtocol):
64
64
45
11
53
heamon7/CPython-2.7.8
Lib/test/test_collections.py
Python
GeneralMappingTests
GeneralMappingTests
1,249
1,254
1,249
1,249
a463bd39e022d94f633640697020c68e14f88281
bigcode/the-stack
train
317ce9454db1167d16b00276
train
function
def _unify_data_and_user_kwargs( data: LayerData, kwargs: Optional[dict] = None, layer_type: Optional[str] = None, fallback_name: str = None, ) -> FullLayerData: """Merge data returned from plugins with options specified by user. If ``data == (_data, _meta, _type)``. Then: - ``kwargs`` wi...
def _unify_data_and_user_kwargs( data: LayerData, kwargs: Optional[dict] = None, layer_type: Optional[str] = None, fallback_name: str = None, ) -> FullLayerData:
"""Merge data returned from plugins with options specified by user. If ``data == (_data, _meta, _type)``. Then: - ``kwargs`` will be used to update ``_meta`` - ``layer_type`` will replace ``_type`` and, if provided, ``_meta`` keys will be pruned to layer_type-appropriate kwargs - ``fallba...
dict", deferred=True, ) ) else: _data.append(dict()) if len(_data) > 2: if _data[2] not in layers.NAMES: raise ValueError( trans._( "The third item in a LayerData tuple must be one of: {layers!r}.", ...
163
163
546
49
113
0x00b1/napari
napari/components/viewer_model.py
Python
_unify_data_and_user_kwargs
_unify_data_and_user_kwargs
1,048
1,107
1,048
1,053
728eff98f7fcdcbf6415a8aeabec8b45452a491b
bigcode/the-stack
train
6ae421a224f4614384f6c630
train
function
@lru_cache(maxsize=1) def valid_add_kwargs() -> Dict[str, Set[str]]: """Return a dict where keys are layer types & values are valid kwargs.""" valid = dict() for meth in dir(ViewerModel): if not meth.startswith('add_') or meth[4:] == 'layer': continue params = inspect.signature(g...
@lru_cache(maxsize=1) def valid_add_kwargs() -> Dict[str, Set[str]]:
"""Return a dict where keys are layer types & values are valid kwargs.""" valid = dict() for meth in dir(ViewerModel): if not meth.startswith('add_') or meth[4:] == 'layer': continue params = inspect.signature(getattr(ViewerModel, meth)).parameters valid[meth[4:]] = set(p...
# get valid params for the corresponding add_<layer_type> method valid = valid_add_kwargs()[layer_type] return {k: v for k, v in kwargs.items() if k in valid} @lru_cache(maxsize=1) def valid_add_kwargs() -> Dict[str, Set[str]]:
64
64
110
21
43
0x00b1/napari
napari/components/viewer_model.py
Python
valid_add_kwargs
valid_add_kwargs
1,162
1,171
1,162
1,163
3685744b67464e2d2a94cb0420b6b6b007c55d3c
bigcode/the-stack
train
1b5d590a2acff28888e7ab1d
train
function
def prune_kwargs(kwargs: Dict[str, Any], layer_type: str) -> Dict[str, Any]: """Return copy of ``kwargs`` with only keys valid for ``add_<layer_type>`` Parameters ---------- kwargs : dict A key: value mapping where some or all of the keys are parameter names for the corresponding ``View...
def prune_kwargs(kwargs: Dict[str, Any], layer_type: str) -> Dict[str, Any]:
"""Return copy of ``kwargs`` with only keys valid for ``add_<layer_type>`` Parameters ---------- kwargs : dict A key: value mapping where some or all of the keys are parameter names for the corresponding ``Viewer.add_<layer_type>`` method. layer_type : str The type of layer ...
user did # *not* specify the layer_type. This means that if a user specified # both layer_type and additional keyword arguments to viewer.open(), # it is their responsibility to make sure the kwargs match the # layer_type. _meta.update(prune_kwargs(kwargs, _type) if not layer_ty...
127
127
424
21
106
0x00b1/napari
napari/components/viewer_model.py
Python
prune_kwargs
prune_kwargs
1,110
1,159
1,110
1,110
a8bd4ddeec5942a0c364ad6586fec6daaf63ea25
bigcode/the-stack
train
8901e0ee90f5d61bee80fcb4
train
function
def _normalize_layer_data(data: LayerData) -> FullLayerData: """Accepts any layerdata tuple, and returns a fully qualified tuple. Parameters ---------- data : LayerData 1-, 2-, or 3-tuple with (data, meta, layer_type). Returns ------- FullLayerData 3-tuple with (data, meta,...
def _normalize_layer_data(data: LayerData) -> FullLayerData:
"""Accepts any layerdata tuple, and returns a fully qualified tuple. Parameters ---------- data : LayerData 1-, 2-, or 3-tuple with (data, meta, layer_type). Returns ------- FullLayerData 3-tuple with (data, meta, layer_type) Raises ------ ValueError If...
' not in str(exc): raise exc bad_key = str(exc).split('keyword argument ')[-1] raise TypeError( trans._( "_add_layer_from_data received an unexpected keyword argument ({bad_key}) for layer type {layer_type}", deferred=True, ...
109
109
364
15
94
0x00b1/napari
napari/components/viewer_model.py
Python
_normalize_layer_data
_normalize_layer_data
996
1,045
996
996
bf8206550bec6074a03962226500b5e8871becf0
bigcode/the-stack
train
b8fd0dc3a910cee7079ea8cf
train
class
class ViewerModel(KeymapProvider, MousemapProvider, EventedModel): """Viewer containing the rendered scene, layers, and controlling elements including dimension sliders, and control bars for color limits. Parameters ---------- title : string The title of the viewer window. ndisplay : {2...
class ViewerModel(KeymapProvider, MousemapProvider, EventedModel):
"""Viewer containing the rendered scene, layers, and controlling elements including dimension sliders, and control bars for color limits. Parameters ---------- title : string The title of the viewer window. ndisplay : {2, 3} Number of displayed dimensions. order : tuple of i...
.events import Event, EventedModel, disconnect_events from ..utils.events.event import WarningEmitter from ..utils.key_bindings import KeymapProvider from ..utils.misc import is_sequence from ..utils.mouse_bindings import MousemapProvider from ..utils.theme import available_themes from ..utils.translations import trans...
256
256
7,799
15
240
0x00b1/napari
napari/components/viewer_model.py
Python
ViewerModel
ViewerModel
66
993
66
66
00b70fd00c5941431e56c2aa1851b147788de166
bigcode/the-stack
train
3c4fa4b43e01205c2845ce35
train
class
class KeyregNonparticipatingTxn(KeyregTxn): """ Represents a nonparticipating key registration transaction. nonpart is implicitly True for this transaction. Args: sender (str): address of sender sp (SuggestedParams): suggested params from algod note (bytes, optional): arbitrary ...
class KeyregNonparticipatingTxn(KeyregTxn):
""" Represents a nonparticipating key registration transaction. nonpart is implicitly True for this transaction. Args: sender (str): address of sender sp (SuggestedParams): suggested params from algod note (bytes, optional): arbitrary optional bytes lease (byte[32], opti...
nonpart=False) if not sp.flat_fee: self.fee = max(self.estimate_size() * self.fee, constants.min_txn_fee) @staticmethod def _undictify(d): args = {} return args def __eq__(self, other): if not isinstance(othe...
104
104
349
11
93
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
KeyregNonparticipatingTxn
KeyregNonparticipatingTxn
600
644
600
600
2d2e939dce0ea0f90e35dabf6c0cb7d5459566ab
bigcode/the-stack
train
090c6e2db84863bfb9541d47
train
class
class LogicSigTransaction: """ Represents a logic signed transaction Arguments: transaction (Transaction) lsig (LogicSig or LogicSigAccount) Attributes: transaction (Transaction) lsig (LogicSig) auth_addr (str, optional) """ def __init__(self, transacti...
class LogicSigTransaction:
""" Represents a logic signed transaction Arguments: transaction (Transaction) lsig (LogicSig or LogicSigAccount) Attributes: transaction (Transaction) lsig (LogicSig) auth_addr (str, optional) """ def __init__(self, transaction: Transaction, lsig: Unio...
This type of LogicSig has the authority to sign transactions on behalf of another account, called the delegating account. If the delegating account is a multisig account, use `sign_multisig` instead. Args: private_key (str): The private key of the delegating account. ...
193
193
645
5
188
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
LogicSigTransaction
LogicSigTransaction
2,350
2,446
2,350
2,350
eb1348dcbb7896776655c20efa29bf3531b9883f
bigcode/the-stack
train
56714201141cbba5a0dac36b
train
class
class AssetTransferTxn(Transaction): """ Represents a transaction for asset transfer. To begin accepting an asset, supply the same address as both sender and receiver, and set amount to 0 (or use AssetOptInTxn) To revoke an asset, set revocation_target, and issue the transaction from the asset...
class AssetTransferTxn(Transaction):
""" Represents a transaction for asset transfer. To begin accepting an asset, supply the same address as both sender and receiver, and set amount to 0 (or use AssetOptInTxn) To revoke an asset, set revocation_target, and issue the transaction from the asset's revocation manager account. A...
.fee = max(self.estimate_size() * self.fee, constants.min_txn_fee) def dictify(self): d = dict() if self.new_freeze_state: d["afrz"] = self.new_freeze_state d["fadd"] = encoding.decode_address(self.target) if self.index: d["faid"]...
256
256
919
6
250
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
AssetTransferTxn
AssetTransferTxn
1,070
1,181
1,070
1,070
14be659186729856a2fc2733e543c584a4d640b7
bigcode/the-stack
train
ae48fefde98b832424a8a648
train
class
class AssetDestroyTxn(AssetConfigTxn): """Represents a transaction for asset destruction. An asset destruction transaction can only be sent by the manager address, and only when the manager possseses all units of the asset. """ def __init__(self, sender, sp, index, note=None, ...
class AssetDestroyTxn(AssetConfigTxn):
"""Represents a transaction for asset destruction. An asset destruction transaction can only be sent by the manager address, and only when the manager possseses all units of the asset. """ def __init__(self, sender, sp, index, note=None, lease=None, rekey_to=None): sup...
freeze, clawback=clawback, unit_name=unit_name, asset_name=asset_name, url=url, metadata_hash=metadata_hash, note=note, lease=lease, rekey_to=rekey_to, strict_empty_address_check=False) class AssetDestroyTxn(AssetConfigT...
64
64
121
9
55
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
AssetDestroyTxn
AssetDestroyTxn
934
946
934
934
e955a7f5ca76e4ce4b45ac385de0efef3b0d3190
bigcode/the-stack
train
c87e12994e03a9f96fc3f4d4
train
class
class AssetConfigTxn(Transaction): """ Represents a transaction for asset creation, reconfiguration, or destruction. To create an asset, include the following: total, default_frozen, unit_name, asset_name, manager, reserve, freeze, clawback, url, metadata, decimals To destr...
class AssetConfigTxn(Transaction):
""" Represents a transaction for asset creation, reconfiguration, or destruction. To create an asset, include the following: total, default_frozen, unit_name, asset_name, manager, reserve, freeze, clawback, url, metadata, decimals To destroy an asset, include the following:...
transaction's valid rounds rekey_to (str, optional): additionally rekey the sender to this address Attributes: sender (str) fee (int) first_valid_round (int) last_valid_round (int) note (bytes) genesis_id (str) genesis_hash (str) group(bytes)...
256
256
1,900
6
250
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
AssetConfigTxn
AssetConfigTxn
647
876
647
647
c9437610408b28b27b6799ee5614db322e737a00
bigcode/the-stack
train
3cf93aa2ef9de517c1b3daf2
train
class
class MultisigSubsig: """ Attributes: public_key (bytes) signature (bytes) """ def __init__(self, public_key, signature=None): self.public_key = public_key self.signature = signature def dictify(self): od = OrderedDict() od["pk"] = self.public_key ...
class MultisigSubsig:
""" Attributes: public_key (bytes) signature (bytes) """ def __init__(self, public_key, signature=None): self.public_key = public_key self.signature = signature def dictify(self): od = OrderedDict() od["pk"] = self.public_key if self.signatur...
sigs] return pks def __eq__(self, other): if not isinstance(other, ( Multisig, transaction.Multisig)): return False return (self.version == other.version and self.threshold == other.threshold and self.subsigs == oth...
75
75
250
7
68
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
MultisigSubsig
MultisigSubsig
1,996
2,036
1,996
1,996
7872caddea819920ecf387d60d99930ebefbc6da
bigcode/the-stack
train
2e6bf9d8b0f26b2656f52254
train
class
class SignedTransaction: """ Represents a signed transaction. Args: transaction (Transaction): transaction that was signed signature (str): signature of a single address authorizing_address (str, optional): the address authorizing the signed transaction, if different from sender ...
class SignedTransaction:
""" Represents a signed transaction. Args: transaction (Transaction): transaction that was signed signature (str): signature of a single address authorizing_address (str, optional): the address authorizing the signed transaction, if different from sender Attributes: tra...
sender, sp, index, app_args=None, accounts=None, foreign_apps=None, foreign_assets=None, note=None, lease=None, rekey_to=None): ApplicationCallTxn.__init__(self, sender=sender, sp=sp, index=self.creatable_index(index), on_...
111
111
373
4
107
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
SignedTransaction
SignedTransaction
1,682
1,739
1,682
1,682
049a40a4814099bcda87f5ea659ecd17994f1625
bigcode/the-stack
train
e5bae810b5161d49c01734f9
train
class
class ApplicationCallTxn(Transaction): """ Represents a transaction that interacts with the application system. Args: sender (str): address of the sender sp (SuggestedParams): suggested params from algod index (int): index of the application to call; 0 if creating a new application ...
class ApplicationCallTxn(Transaction):
""" Represents a transaction that interacts with the application system. Args: sender (str): address of the sender sp (SuggestedParams): suggested params from algod index (int): index of the application to call; 0 if creating a new application on_complete (OnComplete): intEn...
_uints == other.num_uints and self.num_byte_slices == other.num_byte_slices) class OnComplete(IntEnum): # NoOpOC indicates that an application transaction will simply call its # ApprovalProgram NoOpOC = 0 # OptInOC indicates that an application transaction will allocate some # Loc...
256
256
1,667
6
249
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
ApplicationCallTxn
ApplicationCallTxn
1,299
1,465
1,299
1,299
e56f3964eda41e20996cdbaca8d9265a318c7fef
bigcode/the-stack
train
f57e83a398c384d136658b74
train
class
class OnComplete(IntEnum): # NoOpOC indicates that an application transaction will simply call its # ApprovalProgram NoOpOC = 0 # OptInOC indicates that an application transaction will allocate some # LocalState for the application in the sender's account OptInOC = 1 # CloseOutOC indicates...
class OnComplete(IntEnum): # NoOpOC indicates that an application transaction will simply call its # ApprovalProgram
NoOpOC = 0 # OptInOC indicates that an application transaction will allocate some # LocalState for the application in the sender's account OptInOC = 1 # CloseOutOC indicates that an application transaction will deallocate # some LocalState for the application from the user's account CloseO...
other): if not isinstance(other, StateSchema): return False return (self.num_uints == other.num_uints and self.num_byte_slices == other.num_byte_slices) class OnComplete(IntEnum): # NoOpOC indicates that an application transaction will simply call its # ApprovalProgr...
68
68
228
26
42
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
OnComplete
OnComplete
1,271
1,296
1,271
1,273
b5dc9288075e3c05d3c3fd0b36ccabc4e549b0ae
bigcode/the-stack
train
3a3832b12d0ec00b12f9bd78
train
class
class AssetFreezeTxn(Transaction): """ Represents a transaction for freezing or unfreezing an account's asset holdings. Must be issued by the asset's freeze manager. Args: sender (str): address of the sender, who must be the asset's freeze manager sp (SuggestedParams): sugg...
class AssetFreezeTxn(Transaction):
""" Represents a transaction for freezing or unfreezing an account's asset holdings. Must be issued by the asset's freeze manager. Args: sender (str): address of the sender, who must be the asset's freeze manager sp (SuggestedParams): suggested params from algod inde...
take units of this asset from any account note (bytes, optional): arbitrary optional bytes lease (byte[32], optional): specifies a lease, and no other transaction with the same sender and lease can be confirmed in this transaction's valid rounds rekey_to (str...
185
185
619
6
179
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
AssetFreezeTxn
AssetFreezeTxn
988
1,067
988
989
a4337795bfa595a7796994d1c737d52c7141d2cb
bigcode/the-stack
train
d4f67e818a6bba9ce277d72e
train
class
class Transaction: """ Superclass for various transaction types. """ def __init__(self, sender, sp, note, lease, txn_type, rekey_to): self.sender = sender self.fee = sp.fee self.first_valid_round = sp.first self.last_valid_round = sp.last self.note = self.as_note...
class Transaction:
""" Superclass for various transaction types. """ def __init__(self, sender, sp, note, lease, txn_type, rekey_to): self.sender = sender self.fee = sp.fee self.first_valid_round = sp.first self.last_valid_round = sp.last self.note = self.as_note(note) self...
group of N atomic transactions must still have a fee of at least N*min_txn_fee. first (int): first round for which the transaction is valid last (int): last round for which the transaction is valid gh (str): genesis hash gen (str, optional): genesis id flat_fee (bool...
256
256
1,854
3
252
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
Transaction
Transaction
55
289
55
55
4b51d0f6e7786a19b1b41722c4f95757a8a6e405
bigcode/the-stack
train
29b84b7e876da584ff049275
train
class
class LogicSig: """ Represents a logic signature NOTE: This type is deprecated. Use LogicSigAccount instead. Arguments: logic (bytes): compiled program args (list[bytes]): args are not signed, but are checked by logic Attributes: logic (bytes) sig (bytes) m...
class LogicSig:
""" Represents a logic signature NOTE: This type is deprecated. Use LogicSigAccount instead. Arguments: logic (bytes): compiled program args (list[bytes]): args are not signed, but are checked by logic Attributes: logic (bytes) sig (bytes) msig (Multisig) ...
igs) class MultisigSubsig: """ Attributes: public_key (bytes) signature (bytes) """ def __init__(self, public_key, signature=None): self.public_key = public_key self.signature = signature def dictify(self): od = OrderedDict() od["pk"] = self.public...
256
256
1,136
4
252
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
LogicSig
LogicSig
2,039
2,205
2,039
2,039
12ac0c6d7ca042a6f17924b3dca07ea4bbbe9259
bigcode/the-stack
train
cffb937c8787217898e13192
train
class
class KeyregOfflineTxn(KeyregTxn): """ Represents an offline key registration transaction. nonpart is implicitly False for this transaction. Args: sender (str): address of sender sp (SuggestedParams): suggested params from algod note (bytes, optional): arbitrary optional bytes ...
class KeyregOfflineTxn(KeyregTxn):
""" Represents an offline key registration transaction. nonpart is implicitly False for this transaction. Args: sender (str): address of sender sp (SuggestedParams): suggested params from algod note (bytes, optional): arbitrary optional bytes lease (byte[32], optional): ...
"votekey": votekey, "selkey": selkey, "votefst": votefst, "votelst": votelst, "votekd": votekd, } return args def __eq__(self, other): if not isinstance(other, KeyregOnlineTxn): return False return super(KeyregO...
102
102
341
9
93
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
KeyregOfflineTxn
KeyregOfflineTxn
553
597
553
553
7a013af254024eb0335f5d9bcf772f73b80b2796
bigcode/the-stack
train
bc3f553d8f3dd12bd2076576
train
class
class ApplicationOptInTxn(ApplicationCallTxn): """ Make a transaction that will opt in to an application Args: sender (str): address of sender sp (SuggestedParams): contains information such as fee and genesis hash index (int): the application to update app_args(list[bytes],...
class ApplicationOptInTxn(ApplicationCallTxn):
""" Make a transaction that will opt in to an application Args: sender (str): address of sender sp (SuggestedParams): contains information such as fee and genesis hash index (int): the application to update app_args(list[bytes], optional): any additional arguments to the app...
): ApplicationCallTxn.__init__(self, sender=sender, sp=sp, index=self.creatable_index(index, required=True), on_complete=OnComplete.DeleteApplicationOC, app_args=app_args, accounts=accounts, foreign_apps=...
87
87
293
9
78
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
ApplicationOptInTxn
ApplicationOptInTxn
1,569
1,594
1,569
1,569
df25ccb6ac955dc46a743058a242d33cfbdadcbb
bigcode/the-stack
train
b293561f1d3e5205c00d823b
train
function
def calculate_group_id(txns): """ Calculate group id for a given list of unsigned transactions Args: txns (list): list of unsigned transactions Returns: bytes: checksum value representing the group id """ if len(txns) > constants.tx_group_limit: raise error.TransactionG...
def calculate_group_id(txns):
""" Calculate group id for a given list of unsigned transactions Args: txns (list): list of unsigned transactions Returns: bytes: checksum value representing the group id """ if len(txns) > constants.tx_group_limit: raise error.TransactionGroupSizeError txids = [] ...
= txns def dictify(self): od = OrderedDict() od["txlist"] = self.transactions return od @staticmethod def undictify(d): txg = TxGroup(d["txlist"]) return txg def calculate_group_id(txns):
64
64
169
7
56
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
calculate_group_id
calculate_group_id
2,535
2,558
2,535
2,535
e1c5c0ef057a2a29f0ac9b54ae16babcf01d6d5d
bigcode/the-stack
train
5bdd2166584181d82ab65e85
train
class
class SuggestedParams: """ Contains various fields common to all transaction types. Args: fee (int): transaction fee (per byte if flat_fee is false). When flat_fee is true, fee may fall to zero but a group of N atomic transactions must still have a fee of at least N*min_txn...
class SuggestedParams:
""" Contains various fields common to all transaction types. Args: fee (int): transaction fee (per byte if flat_fee is false). When flat_fee is true, fee may fall to zero but a group of N atomic transactions must still have a fee of at least N*min_txn_fee. first (in...
from typing import List, Union import base64 from enum import IntEnum import msgpack from collections import OrderedDict from .. import account from .. import constants from .. import encoding from .. import error from .. import logic from .. import transaction from nacl.signing import SigningKey, VerifyKey from nacl.e...
82
90
303
4
77
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
SuggestedParams
SuggestedParams
16
52
16
16
d72c76dd6e5bf20fe57c9dd39d4d105672fedc15
bigcode/the-stack
train
750d5ce1a717b4b018c27f7a
train
class
class ApplicationDeleteTxn(ApplicationCallTxn): """ Make a transaction that will delete an application Args: sender (str): address of sender sp (SuggestedParams): contains information such as fee and genesis hash index (int): the application to update app_args(list[bytes], o...
class ApplicationDeleteTxn(ApplicationCallTxn):
""" Make a transaction that will delete an application Args: sender (str): address of sender sp (SuggestedParams): contains information such as fee and genesis hash index (int): the application to update app_args(list[bytes], optional): any additional arguments to the applic...
, sp=sp, index=self.creatable_index(index, required=True), on_complete=OnComplete.UpdateApplicationOC, approval_program=approval_program, clear_program=clear_program, app_args=...
86
86
289
8
78
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
ApplicationDeleteTxn
ApplicationDeleteTxn
1,540
1,566
1,540
1,540
434a06708424a1dc9a1b3aff7e75ea01f5ad6a72
bigcode/the-stack
train
dfb9b7d7c152c345bb334059
train
class
class ApplicationUpdateTxn(ApplicationCallTxn): """ Make a transaction that will change an application's approval and clear programs. Args: sender (str): address of sender sp (SuggestedParams): contains information such as fee and genesis hash index (int): the application to update ...
class ApplicationUpdateTxn(ApplicationCallTxn):
""" Make a transaction that will change an application's approval and clear programs. Args: sender (str): address of sender sp (SuggestedParams): contains information such as fee and genesis hash index (int): the application to update approval_program (bytes): the new compil...
, sender=sender, sp=sp, index=0, on_complete=on_complete, approval_program=self.required(approval_program), clear_program=self.required(clear_program), global_schema=global_schema, ...
103
103
346
8
95
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
ApplicationUpdateTxn
ApplicationUpdateTxn
1,507
1,537
1,507
1,507
3a0f49eb73d96c447a0fe121b53189ade010011b
bigcode/the-stack
train
7bf2934711415fb2cf5ca3ac
train
class
class MultisigTransaction: """ Represents a signed transaction. Args: transaction (Transaction): transaction that was signed multisig (Multisig): multisig account and signatures Attributes: transaction (Transaction) multisig (Multisig) auth_addr (str, optional) ...
class MultisigTransaction:
""" Represents a signed transaction. Args: transaction (Transaction): transaction that was signed multisig (Multisig): multisig account and signatures Attributes: transaction (Transaction) multisig (Multisig) auth_addr (str, optional) """ def __init__(s...
(self): """ Get the transaction's ID. Returns: str: transaction ID """ return self.transaction.get_txid() def dictify(self): od = OrderedDict() if self.signature: od["sig"] = base64.b64decode(self.signature) od["txn"] = self.t...
256
256
1,065
6
250
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
MultisigTransaction
MultisigTransaction
1,742
1,883
1,742
1,742
3dd8c65286f4ecf8ca37d9b0850e389da1ecfe7e
bigcode/the-stack
train
629374e67f8f8b7ca8b880c2
train
function
def assign_group_id(txns, address=None): """ Assign group id to a given list of unsigned transactions Args: txns (list): list of unsigned transactions address (str): optional sender address specifying which transaction return Returns: txns (list): list of unsigned t...
def assign_group_id(txns, address=None):
""" Assign group id to a given list of unsigned transactions Args: txns (list): list of unsigned transactions address (str): optional sender address specifying which transaction return Returns: txns (list): list of unsigned transactions with group property set "...
.append(encoding.checksum(to_hash)) group = TxGroup(txids) encoded = encoding.msgpack_encode(group) to_sign = constants.tgid_prefix + base64.b64decode(encoded) gid = encoding.checksum(to_sign) return gid def assign_group_id(txns, address=None):
64
64
139
10
53
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
assign_group_id
assign_group_id
2,561
2,581
2,561
2,561
7ce3ec71e0e94615ca99fdb76154312570068a28
bigcode/the-stack
train
350ec1df676a09f5b78849a2
train
class
class LogicSigAccount: """ Represents an account that can sign with a LogicSig program. """ def __init__(self, program: bytes, args: List[bytes] = None) -> None: """ Create a new LogicSigAccount. By default this will create an escrow LogicSig account. Call `sign` or `sign_multis...
class LogicSigAccount:
""" Represents an account that can sign with a LogicSig program. """ def __init__(self, program: bytes, args: List[bytes] = None) -> None: """ Create a new LogicSigAccount. By default this will create an escrow LogicSig account. Call `sign` or `sign_multisig` on the newly create...
private_key) else: if self.sig: raise error.LogicSigOverspecifiedSignature sig, index = LogicSig.single_sig_multisig(self.logic, private_key, multisig) multisig.subsigs[index].signature = base64.b64decode(...
256
256
1,085
5
251
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
LogicSigAccount
LogicSigAccount
2,207
2,348
2,207
2,207
74e5a33d7430e0d3ec72f202eff0156157a4b5bd
bigcode/the-stack
train
df000133582f0ecb1e26932f
train
class
class AssetCloseOutTxn(AssetTransferTxn): """ Make a transaction that will send all of an ASA away, and opt out of it. Args: sender (str): address of sender sp (SuggestedParams): contains information such as fee and genesis hash receiver (str): address of the receiver index ...
class AssetCloseOutTxn(AssetTransferTxn):
""" Make a transaction that will send all of an ASA away, and opt out of it. Args: sender (str): address of sender sp (SuggestedParams): contains information such as fee and genesis hash receiver (str): address of the receiver index (int): the ASA to opt into note(by...
index, note=None, lease=None, rekey_to=None): super().__init__(sender=sender, sp=sp, receiver=sender, amt=0, index=index, note=note, lease=lease, rekey_to=rekey_to) class AssetCloseOutTxn(AssetTransferTxn):
64
64
200
10
54
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
AssetCloseOutTxn
AssetCloseOutTxn
1,206
1,227
1,206
1,206
91b1106d7a09a24c3971d00037f54d784725bad3
bigcode/the-stack
train
058ee6b57c2ad78005b62ec2
train
class
class AssetUpdateTxn(AssetConfigTxn): """Represents a transaction for asset modification. To update asset configuration, include the following: index, manager, reserve, freeze, clawback. Keyword arguments are required, starting with the special addresses, to prevent argument reordinering error...
class AssetUpdateTxn(AssetConfigTxn):
"""Represents a transaction for asset modification. To update asset configuration, include the following: index, manager, reserve, freeze, clawback. Keyword arguments are required, starting with the special addresses, to prevent argument reordinering errors. Since the special addresses are...
asset destruction transaction can only be sent by the manager address, and only when the manager possseses all units of the asset. """ def __init__(self, sender, sp, index, note=None, lease=None, rekey_to=None): super().__init__(sender=sender, sp=sp, index=self.creatable_index...
109
109
364
9
100
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
AssetUpdateTxn
AssetUpdateTxn
948
985
948
948
7c48ffcefb5143e149ad256e8eb57bba00503045
bigcode/the-stack
train
5ee93b6e93762ad56863f402
train
class
class PaymentTxn(Transaction): """ Represents a payment transaction. Args: sender (str): address of the sender sp (SuggestedParams): suggested params from algod receiver (str): address of the receiver amt (int): amount in microAlgos to be sent close_remainder_to (str...
class PaymentTxn(Transaction):
""" Represents a payment transaction. Args: sender (str): address of the sender sp (SuggestedParams): suggested params from algod receiver (str): address of the receiver amt (int): amount in microAlgos to be sent close_remainder_to (str, optional): if nonempty, accou...
.type == other.type and self.rekey_to == other.rekey_to) @staticmethod def required(arg): if not arg: raise ValueError(f"{arg} supplied as a required argument") return arg @staticmethod def creatable_index(index, required=False): """Coerce an index f...
201
201
671
5
196
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
PaymentTxn
PaymentTxn
292
379
292
292
c35816bc59a02db617ce9f2fc12ca8955477d39e
bigcode/the-stack
train
b9c310cbaea52ab7e98d9143
train
function
def write_to_file(txns, path, overwrite=True): """ Write signed or unsigned transactions to a file. Args: txns (Transaction[], SignedTransaction[], or MultisigTransaction[]):\ can be a mix of the three path (str): file to write to overwrite (bool): whether or not to over...
def write_to_file(txns, path, overwrite=True):
""" Write signed or unsigned transactions to a file. Args: txns (Transaction[], SignedTransaction[], or MultisigTransaction[]):\ can be a mix of the three path (str): file to write to overwrite (bool): whether or not to overwrite what's already in the file; i...
and self.transaction == other.transaction) if isinstance(other, LogicSigTransaction): return (self.lsig == other.lsig and self.auth_addr == other.auth_addr and self.transaction == other.transaction) return False def write_to_file(txn...
64
64
212
12
51
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
write_to_file
write_to_file
2,449
2,478
2,449
2,449
1c527b66a4a2db2b37560ef1638049061027f4e8
bigcode/the-stack
train
bcf276b7460570b9b0860008
train
function
def retrieve_from_file(path): """ Retrieve signed or unsigned transactions from a file. Args: path (str): file to read from Returns: Transaction[], SignedTransaction[], or MultisigTransaction[]:\ can be a mix of the three """ f = open(path, "rb") txns = [] ...
def retrieve_from_file(path):
""" Retrieve signed or unsigned transactions from a file. Args: path (str): file to read from Returns: Transaction[], SignedTransaction[], or MultisigTransaction[]:\ can be a mix of the three """ f = open(path, "rb") txns = [] unp = msgpack.Unpacker(f, raw=...
): enc = msgpack.packb({"txn": txn.dictify()}, use_bin_type=True) f.write(enc) else: enc = msgpack.packb(txn.dictify(), use_bin_type=True) f.write(enc) f.close() return True def retrieve_from_file(path):
64
64
215
6
57
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
retrieve_from_file
retrieve_from_file
2,481
2,508
2,481
2,481
8c49dbae836eb1620cfbe9061edace3b97f5a01c
bigcode/the-stack
train
d40d1209b49beb1c1e2cf752
train
class
class StateSchema: """ Restricts state for an application call. Args: num_uints(int, optional): number of uints to store num_byte_slices(int, optional): number of byte slices to store Attributes: num_uints (int) num_byte_slices (int) """ def __init__(self, num_...
class StateSchema:
""" Restricts state for an application call. Args: num_uints(int, optional): number of uints to store num_byte_slices(int, optional): number of byte slices to store Attributes: num_uints (int) num_byte_slices (int) """ def __init__(self, num_uints=None, num_byt...
See AssetTransferTxn """ def __init__(self, sender, sp, receiver, index, note=None, lease=None, rekey_to=None): super().__init__(sender=sender, sp=sp, receiver=receiver, amt=0, index=index, close_assets_to=receiver, note=note, lease=le...
85
85
286
4
81
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
StateSchema
StateSchema
1,230
1,268
1,230
1,230
250ea7ccb5930b0a2dcf3c06dfe8ab44c2cb3d58
bigcode/the-stack
train
56f565b9dec4d5ba931fd3fd
train
class
class Multisig: """ Represents a multisig account and signatures. Args: version (int): currently, the version is 1 threshold (int): how many signatures are necessary addresses (str[]): addresses in the multisig account Attributes: version (int) threshold (int) ...
class Multisig:
""" Represents a multisig account and signatures. Args: version (int): currently, the version is 1 threshold (int): how many signatures are necessary addresses (str[]): addresses in the multisig account Attributes: version (int) threshold (int) subsigs (...
stx in part_stxs: if not msigstx: msigstx = stx else: for s in range(len(stx.multisig.subsigs)): if stx.multisig.subsigs[s].signature: if not msigstx.multisig.subsigs[s].signature: msigstx.mu...
243
243
812
5
237
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
Multisig
Multisig
1,886
1,993
1,886
1,886
8a60cad5ac27d0e03cdba5a1763337735da8eb74
bigcode/the-stack
train
f46ffabe4560c8cc59ed2e79
train
class
class ApplicationCloseOutTxn(ApplicationCallTxn): """ Make a transaction that will close out a user's state in an application Args: sender (str): address of sender sp (SuggestedParams): contains information such as fee and genesis hash index (int): the application to update ...
class ApplicationCloseOutTxn(ApplicationCallTxn):
""" Make a transaction that will close out a user's state in an application Args: sender (str): address of sender sp (SuggestedParams): contains information such as fee and genesis hash index (int): the application to update app_args(list[bytes], optional): any additional ar...
ApplicationCallTxn.__init__(self, sender=sender, sp=sp, index=self.creatable_index(index, required=True), on_complete=OnComplete.OptInOC, app_args=app_args, accounts=accounts, foreign_apps=foreign_apps, ...
87
87
292
9
78
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
ApplicationCloseOutTxn
ApplicationCloseOutTxn
1,597
1,622
1,597
1,597
4e47c2353fd1ce173a0d391510bd67b0422e43dc
bigcode/the-stack
train
d30776543bc286575570e474
train
class
class AssetCreateTxn(AssetConfigTxn): """Represents a transaction for asset creation. Keyword arguments are required, starting with the special addresses, to prevent errors, as type checks can't prevent simple confusion of similar typed arguments. Since the special addresses are required, strict_em...
class AssetCreateTxn(AssetConfigTxn):
"""Represents a transaction for asset creation. Keyword arguments are required, starting with the special addresses, to prevent errors, as type checks can't prevent simple confusion of similar typed arguments. Since the special addresses are required, strict_empty_address_check is turned off. ...
AssetConfigTxn, self).__eq__(other) and self.index == other.index and self.total == other.total and self.default_frozen == other.default_frozen and self.unit_name == other.unit_name and self.asset_name == other.asset_name and ...
172
172
575
9
162
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
AssetCreateTxn
AssetCreateTxn
880
932
880
880
065d914edd6641dd69b5197228df1d70de30653b
bigcode/the-stack
train
00601381ffafc5501354295e
train
class
class AssetOptInTxn(AssetTransferTxn): """ Make a transaction that will opt in to an ASA Args: sender (str): address of sender sp (SuggestedParams): contains information such as fee and genesis hash index (int): the ASA to opt into note(bytes, optional): transaction note fie...
class AssetOptInTxn(AssetTransferTxn):
""" Make a transaction that will opt in to an ASA Args: sender (str): address of sender sp (SuggestedParams): contains information such as fee and genesis hash index (int): the ASA to opt into note(bytes, optional): transaction note field lease(bytes, optional): tran...
).__eq__(other) and self.index == other.index and self.amount == other.amount and self.receiver == other.receiver and self.close_assets_to == other.close_assets_to and self.revocation_target == other.revocation_target) class AssetOptInTxn(A...
64
64
174
10
54
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
AssetOptInTxn
AssetOptInTxn
1,184
1,203
1,184
1,184
21078514042e5cd1cebbe0e8ee3676c143abcdfd
bigcode/the-stack
train
ee8382f263262e8279b099e6
train
class
class KeyregTxn(Transaction): """ Represents a key registration transaction. Args: sender (str): address of sender sp (SuggestedParams): suggested params from algod votekey (str): participation public key in base64 selkey (str): VRF public key in base64 votefst (int)...
class KeyregTxn(Transaction):
""" Represents a key registration transaction. Args: sender (str): address of sender sp (SuggestedParams): suggested params from algod votekey (str): participation public key in base64 selkey (str): VRF public key in base64 votefst (int): first round to vote ...
decoded_receiver = encoding.decode_address(self.receiver) if any(decoded_receiver): d["rcv"] = encoding.decode_address(self.receiver) d.update(super(PaymentTxn, self).dictify()) od = OrderedDict(sorted(d.items())) return od @staticmethod def _undictify(d): ...
226
226
756
6
220
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
KeyregTxn
KeyregTxn
382
466
382
382
a451b5437633afd53b59465ff6c519579021da91
bigcode/the-stack
train
8e01e2f9aef8f84df97bcbc5
train
class
class ApplicationNoOpTxn(ApplicationCallTxn): """ Make a transaction that will do nothing on application completion In other words, just call the application Args: sender (str): address of sender sp (SuggestedParams): contains information such as fee and genesis hash index (int...
class ApplicationNoOpTxn(ApplicationCallTxn):
""" Make a transaction that will do nothing on application completion In other words, just call the application Args: sender (str): address of sender sp (SuggestedParams): contains information such as fee and genesis hash index (int): the application to update app_args(...
, rekey_to=None): ApplicationCallTxn.__init__(self, sender=sender, sp=sp, index=self.creatable_index(index), on_complete=OnComplete.ClearStateOC, app_args=app_args, accounts=accounts, foreign_apps=foreign...
89
89
299
9
80
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
ApplicationNoOpTxn
ApplicationNoOpTxn
1,653
1,679
1,653
1,653
855cb25906d3bf4005560b42e35fb91274d87988
bigcode/the-stack
train
3a7776468456043250cf828e
train
class
class ApplicationClearStateTxn(ApplicationCallTxn): """ Make a transaction that will clear a user's state for an application Args: sender (str): address of sender sp (SuggestedParams): contains information such as fee and genesis hash index (int): the application to update a...
class ApplicationClearStateTxn(ApplicationCallTxn):
""" Make a transaction that will clear a user's state for an application Args: sender (str): address of sender sp (SuggestedParams): contains information such as fee and genesis hash index (int): the application to update app_args(list[bytes], optional): any additional argum...
key_to=None): ApplicationCallTxn.__init__(self, sender=sender, sp=sp, index=self.creatable_index(index), on_complete=OnComplete.CloseOutOC, app_args=app_args, accounts=accounts, foreign_apps=foreign_apps,...
87
87
291
9
78
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
ApplicationClearStateTxn
ApplicationClearStateTxn
1,625
1,650
1,625
1,625
89df6ab5ea1091f819831e40aa6affc9929bbb21
bigcode/the-stack
train
0572cf8c73785ada14253c97
train
class
class KeyregOnlineTxn(KeyregTxn): """ Represents an online key registration transaction. nonpart is implicitly False for this transaction. Args: sender (str): address of sender sp (SuggestedParams): suggested params from algod votekey (str): participation public key in base64 ...
class KeyregOnlineTxn(KeyregTxn):
""" Represents an online key registration transaction. nonpart is implicitly False for this transaction. Args: sender (str): address of sender sp (SuggestedParams): suggested params from algod votekey (str): participation public key in base64 selkey (str): VRF public key...
epk is not None: d["votekey"] = base64.b64decode(self.votepk) if self.votelst is not None: d["votelst"] = self.votelst if self.nonpart is not None: d["nonpart"] = self.nonpart d.update(super(KeyregTxn, self).dictify()) od = OrderedDict(sorted(d.items()...
221
221
738
9
212
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
KeyregOnlineTxn
KeyregOnlineTxn
469
550
469
469
fae83aa4267814dc38dcfc61fd5203153e58af4b
bigcode/the-stack
train
97b964bd99e8e683c5652e5a
train
class
class ApplicationCreateTxn(ApplicationCallTxn): """ Make a transaction that will create an application. Args: sender (str): address of sender sp (SuggestedParams): contains information such as fee and genesis hash on_complete (OnComplete): what application should so once the program...
class ApplicationCreateTxn(ApplicationCallTxn):
""" Make a transaction that will create an application. Args: sender (str): address of sender sp (SuggestedParams): contains information such as fee and genesis hash on_complete (OnComplete): what application should so once the program is done being run approval_program (byt...
eq__(other) and self.index == other.index and self.on_complete == other.on_complete and self.local_schema == other.local_schema and self.global_schema == other.global_schema and self.approval_program == other.approval_program and ...
127
129
431
8
119
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
ApplicationCreateTxn
ApplicationCreateTxn
1,469
1,504
1,469
1,469
1ded0c0368b38a744bd221ec86317271d6b8d3a5
bigcode/the-stack
train
f85db6836959aaed2f1cedb4
train
class
class TxGroup: def __init__(self, txns): assert isinstance(txns, list) """ Transactions specifies a list of transactions that must appear together, sequentially, in a block in order for the group to be valid. Each hash in the list is a hash of a transaction with the ...
class TxGroup:
def __init__(self, txns): assert isinstance(txns, list) """ Transactions specifies a list of transactions that must appear together, sequentially, in a block in order for the group to be valid. Each hash in the list is a hash of a transaction with the `Group` field o...
SigTransaction.undictify(txn)) elif "type" in txn: txns.append(Transaction.undictify(txn)) elif "txn" in txn: txns.append(Transaction.undictify(txn['txn'])) f.close() return txns class TxGroup:
64
64
159
4
59
Fkazi14/algorand-sdk
algosdk/future/transaction.py
Python
TxGroup
TxGroup
2,511
2,532
2,511
2,511
5c326a2c727f216384011cd4c6c3eb667bc6f6f2
bigcode/the-stack
train
18c95d067c75f24395bbbf4d
train
class
class Visitor(object): """Base class for visitors.""" def visit(self, node): """Visit a node. Calls ``visit_CLASSNAME`` on itself passing ``node``, where ``CLASSNAME`` is the node's class. If the visitor does not implement an appropriate visitation method, will go up the ...
class Visitor(object):
"""Base class for visitors.""" def visit(self, node): """Visit a node. Calls ``visit_CLASSNAME`` on itself passing ``node``, where ``CLASSNAME`` is the node's class. If the visitor does not implement an appropriate visitation method, will go up the `MRO <https://www.pyt...
A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. class Visi...
70
70
234
4
66
najma-amin/News-Highlights
virtual/lib/python3.6/site-packages/visitor/__init__.py
Python
Visitor
Visitor
22
51
22
22
803de38c14179cdf17d22131367723341ba1d121
bigcode/the-stack
train
a10e41af588ff0c19adb22a5
train
function
def replace_properties(node: Any, symrepl: Dict[symbolic.symbol, symbolic.SymbolicType], name: str, new_name: str): for propclass, propval in node.properties(): if propval is None: continue pname = propclass.attr_name...
def replace_properties(node: Any, symrepl: Dict[symbolic.symbol, symbolic.SymbolicType], name: str, new_name: str):
for propclass, propval in node.properties(): if propval is None: continue pname = propclass.attr_name if isinstance(propclass, properties.SymbolicProperty): setattr(node, pname, propval.subs(symrepl)) elif isinstance(propclass, properties.DataProperty): ...
_symbols): edge.data.subset = _replsym(edge.data.subset, symrepl) if (edge.data.other_subset is not None and name in edge.data.other_subset.free_symbols): edge.data.other_subset = _replsym(edge.data.other_subset, symrepl) if symname in edge.data.volume.free_symbol...
123
123
410
33
90
tobiasholenstein/dace
dace/sdfg/replace.py
Python
replace_properties
replace_properties
63
102
63
65
61ae9c94861097d1ec388e168b1dfc47cd12a004
bigcode/the-stack
train
8f41c578122cd8c985fc4146
train
function
def replace(subgraph: 'dace.sdfg.state.StateGraphView', name: str, new_name: str): """ Finds and replaces all occurrences of a symbol or array in the given subgraph. :param subgraph: The given graph or subgraph to replace in. :param name: Name to find. :param new_name: Na...
def replace(subgraph: 'dace.sdfg.state.StateGraphView', name: str, new_name: str):
""" Finds and replaces all occurrences of a symbol or array in the given subgraph. :param subgraph: The given graph or subgraph to replace in. :param name: Name to find. :param new_name: Name to replace. """ if str(name) == str(new_name): return symname = symbolic...
[i] = tuple( d.subs(symrepl) if symbolic.issymbolic(d) else d for d in dim) except TypeError: symlist[i] = (dim.subs(symrepl) if symbolic.issymbolic(dim) else dim) return symlist def replace(subgraph: 'dace.sdfg.state.StateGraphView', name: str, ...
92
92
308
26
65
tobiasholenstein/dace
dace/sdfg/replace.py
Python
replace
replace
28
60
28
29
1bb0feb3fb4bac5c504786a9e5af0fd1277b62ab
bigcode/the-stack
train
7466afdf56c9a3c025e7eb64
train
function
def _replsym(symlist, symrepl): """ Helper function to replace symbols in various symbolic expressions. """ if symlist is None: return None if isinstance(symlist, (symbolic.SymExpr, symbolic.symbol, sp.Basic)): return symlist.subs(symrepl) for i, dim in enumerate(symlist): try: ...
def _replsym(symlist, symrepl):
""" Helper function to replace symbols in various symbolic expressions. """ if symlist is None: return None if isinstance(symlist, (symbolic.SymExpr, symbolic.symbol, sp.Basic)): return symlist.subs(symrepl) for i, dim in enumerate(symlist): try: symlist[i] = tuple( ...
symbols in SDFGs. """ from dace import dtypes, properties, symbolic from dace.frontend.python.astutils import ASTFindReplace import re import sympy as sp from typing import Any, Dict, Union import warnings def _replsym(symlist, symrepl):
64
64
156
14
49
tobiasholenstein/dace
dace/sdfg/replace.py
Python
_replsym
_replsym
12
25
12
12
22d11a312f19b5e4ba468b499151942e3a98f0bd
bigcode/the-stack
train
d7eaa08a883b87d945e3db66
train
class
class VirtualMachineSizesOperations(object): """VirtualMachineSizesOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operati...
class VirtualMachineSizesOperations(object):
"""VirtualMachineSizesOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.compu...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
235
256
880
7
228
rsdoherty/azure-sdk-for-python
sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2021_03_01/operations/_virtual_machine_sizes_operations.py
Python
VirtualMachineSizesOperations
VirtualMachineSizesOperations
26
118
26
26
178d350fc3babdaea458531e0a1696b8b2ab1d6a
bigcode/the-stack
train
35c97b3e8fbddb62eb495317
train
class
class PaperTradingBrokerage(CloudBrokerage): """A CloudBrokerage implementation for paper trading.""" @classmethod def get_id(cls) -> str: return "QuantConnectBrokerage" @classmethod def get_name(cls) -> str: return "Paper Trading" @classmethod def build(cls, logger: Logge...
class PaperTradingBrokerage(CloudBrokerage):
"""A CloudBrokerage implementation for paper trading.""" @classmethod def get_id(cls) -> str: return "QuantConnectBrokerage" @classmethod def get_name(cls) -> str: return "Paper Trading" @classmethod def build(cls, logger: Logger) -> CloudBrokerage: return PaperTra...
CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Dict from lean.components.util.logger import Logger from lean.models.brokerages.cloud.base import CloudBrokerage class PaperTradingBrokerage(Clo...
64
64
111
10
53
InvestWeMust/lean-cli
lean/models/brokerages/cloud/paper_trading.py
Python
PaperTradingBrokerage
PaperTradingBrokerage
20
38
20
20
3e731f8c0ad117c4580c5ae8f4d05d67347fbf2e
bigcode/the-stack
train
ade8bfe13e9554555df62645
train
class
class LSTM(RNNBase): r"""Applies a multi-layer long short-term memory (LSTM) RNN to an input sequence. For each element in the input sequence, each layer computes the following function: .. math:: \begin{array}{ll} \\ i_t = \sigma(W_{ii} x_t + b_{ii} + W_{hi} h_{(t-1)} + b_{hi...
class LSTM(RNNBase):
r"""Applies a multi-layer long short-term memory (LSTM) RNN to an input sequence. For each element in the input sequence, each layer computes the following function: .. math:: \begin{array}{ll} \\ i_t = \sigma(W_{ii} x_t + b_{ii} + W_{hi} h_{(t-1)} + b_{hi}) \\ f_t...
initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where :math:`k = \frac{1}{\text{hidden\_size}}` .. include:: cudnn_persistent_rnn.rst Examples:: >>> rnn = nn.RNN(10, 20, 2) >>> input = torch.randn(5, 3, 10) >>> h0 = torch.randn(2, 3, 20) >>> output, hn = rnn...
256
256
1,622
7
249
YoNyeoSeok/Cityname_Classification-RNN-
rnn.py
Python
LSTM
LSTM
334
439
334
334
f7f1e64bcb0861c3d05aa370a079ff22dba5cda5
bigcode/the-stack
train
81a518a6e024432259ac3750
train
class
class GRU(RNNBase): r"""Applies a multi-layer gated recurrent unit (GRU) RNN to an input sequence. For each element in the input sequence, each layer computes the following function: .. math:: \begin{array}{ll} r_t = \sigma(W_{ir} x_t + b_{ir} + W_{hr} h_{(t-1)} + b_{hr}) \\ ...
class GRU(RNNBase):
r"""Applies a multi-layer gated recurrent unit (GRU) RNN to an input sequence. For each element in the input sequence, each layer computes the following function: .. math:: \begin{array}{ll} r_t = \sigma(W_{ir} x_t + b_{ir} + W_{hr} h_{(t-1)} + b_{hr}) \\ z_t = \sigma(...
of shape `(4*hidden_size)` bias_hh_l[k] : the learnable hidden-hidden bias of the :math:`\text{k}^{th}` layer `(b_hi|b_hf|b_hg|b_ho)`, of shape `(4*hidden_size)` .. note:: All the weights and biases are initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where :math:`k = ...
256
256
1,377
7
249
YoNyeoSeok/Cityname_Classification-RNN-
rnn.py
Python
GRU
GRU
443
536
443
443
6c5b77d9bd08452c95024cf6d1300a3a49b6188b
bigcode/the-stack
train
2b6c33e89c6e731c8486345e
train
class
class GRUCell(RNNCellBase): r"""A gated recurrent unit (GRU) cell .. math:: \begin{array}{ll} r = \sigma(W_{ir} x + b_{ir} + W_{hr} h + b_{hr}) \\ z = \sigma(W_{iz} x + b_{iz} + W_{hz} h + b_{hz}) \\ n = \tanh(W_{in} x + b_{in} + r * (W_{hn} h + b_{hn})) \\ h' = (1 - z)...
class GRUCell(RNNCellBase):
r"""A gated recurrent unit (GRU) cell .. math:: \begin{array}{ll} r = \sigma(W_{ir} x + b_{ir} + W_{hr} h + b_{hr}) \\ z = \sigma(W_{iz} x + b_{iz} + W_{hz} h + b_{hz}) \\ n = \tanh(W_{in} x + b_{in} + r * (W_{hn} h + b_{hn})) \\ h' = (1 - z) * n + z * h \end{ar...
>>> output = [] >>> for i in range(6): hx, cx = rnn(input[i], (hx, cx)) output.append(hx) """ def __init__(self, input_size, hidden_size, bias=True): super(LSTMCell, self).__init__(input_size, hidden_size, bias, num_chunks=4) def forward(self, input, hx=Non...
200
201
673
9
191
YoNyeoSeok/Cityname_Classification-RNN-
rnn.py
Python
GRUCell
GRUCell
741
806
741
741
c94d4671ed684c4658a937aaa046a705a3fbc321
bigcode/the-stack
train
8344929eac0faa482b897daf
train
class
class RNNCell(RNNCellBase): r"""An Elman RNN cell with tanh or ReLU non-linearity. .. math:: h' = \tanh(w_{ih} x + b_{ih} + w_{hh} h + b_{hh}) If :attr:`nonlinearity` is `'relu'`, then ReLU is used in place of tanh. Args: input_size: The number of expected features in the input `x`...
class RNNCell(RNNCellBase):
r"""An Elman RNN cell with tanh or ReLU non-linearity. .. math:: h' = \tanh(w_{ih} x + b_{ih} + w_{hh} h + b_{hh}) If :attr:`nonlinearity` is `'relu'`, then ReLU is used in place of tanh. Args: input_size: The number of expected features in the input `x` hidden_size: The nu...
.__dict__) def check_forward_input(self, input): if input.size(1) != self.input_size: raise RuntimeError( "input has inconsistent input_size: got {}, expected {}".format( input.size(1), self.input_size)) def check_forward_hidden(self, input, hx, hidden_l...
210
210
702
9
201
YoNyeoSeok/Cityname_Classification-RNN-
rnn.py
Python
RNNCell
RNNCell
588
658
588
588
14f40a8b055f0dbe3283031ff4b50521c71abc8e
bigcode/the-stack
train
55621ae0685bee3182891b8d
train
class
class RNNCellBase(Module): def __init__(self, input_size, hidden_size, bias, num_chunks): super(RNNCellBase, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.bias = bias self.weight_ih = Parameter(torch.Tensor(num_chunks * hidden_size, input_...
class RNNCellBase(Module):
def __init__(self, input_size, hidden_size, bias, num_chunks): super(RNNCellBase, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.bias = bias self.weight_ih = Parameter(torch.Tensor(num_chunks * hidden_size, input_size)) self.weight_h...
= \frac{1}{\text{hidden\_size}}` .. include:: cudnn_persistent_rnn.rst Examples:: >>> rnn = nn.GRU(10, 20, 2) >>> input = torch.randn(5, 3, 10) >>> h0 = torch.randn(2, 3, 20) >>> output, hn = rnn(input, h0) """ def __init__(self, *args, **kwargs): super(GRU, ...
132
132
441
7
125
YoNyeoSeok/Cityname_Classification-RNN-
rnn.py
Python
RNNCellBase
RNNCellBase
540
585
540
541
9706baead3825a369259867b47fd0f8e4009d184
bigcode/the-stack
train