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
114319d60d95b5f048330015
train
function
def is_pAdicField(R): """ Returns ``True`` if and only if ``R`` is a `p`-adic field. EXAMPLES:: sage: is_pAdicField(Zp(17)) False sage: is_pAdicField(Qp(17)) True """ return isinstance(R, pAdicFieldGeneric)
def is_pAdicField(R):
""" Returns ``True`` if and only if ``R`` is a `p`-adic field. EXAMPLES:: sage: is_pAdicField(Zp(17)) False sage: is_pAdicField(Qp(17)) True """ return isinstance(R, pAdicFieldGeneric)
OUTPUT: - the Krull dimension of self. Since self is a `p`-adic ring, this is 1. EXAMPLES:: sage: Zp(5).krull_dimension() 1 """ return 1 def is_pAdicField(R):
64
64
80
8
55
vbraun/sage
src/sage/rings/padics/generic_nodes.py
Python
is_pAdicField
is_pAdicField
313
324
313
313
95e338396d27ce866aa2fcd03c9ac67dc73dce5b
bigcode/the-stack
train
897fd5e0d25e319b0d64e184
train
class
class CappedAbsoluteGeneric(LocalGeneric): def is_capped_absolute(self): """ Returns whether this `p`-adic ring bounds precision in a capped absolute fashion. The absolute precision of an element is the power of `p` modulo which that element is defined. In a capped absolute...
class CappedAbsoluteGeneric(LocalGeneric):
def is_capped_absolute(self): """ Returns whether this `p`-adic ring bounds precision in a capped absolute fashion. The absolute precision of an element is the power of `p` modulo which that element is defined. In a capped absolute ring, the absolute precision of el...
icGeneric from sage.rings.ring import EuclideanDomain, Field from sage.rings.padics.padic_base_generic import pAdicBaseGeneric from sage.rings.integer_ring import ZZ from sage.rings.rational_field import QQ from sage.rings.infinity import infinity, SignError class CappedAbsoluteGeneric(LocalGeneric):
71
71
239
8
62
vbraun/sage
src/sage/rings/padics/generic_nodes.py
Python
CappedAbsoluteGeneric
CappedAbsoluteGeneric
32
67
32
32
8740ed274b6d51a7c9fe33f126943dd2cca861e3
bigcode/the-stack
train
f79334ee398000e9c50dce8c
train
class
class FloatingPointGeneric(LocalGeneric): def is_floating_point(self): """ Returns whether this `p`-adic ring uses a floating point precision model. Elements in the floating point model are stored by giving a valuation and a unit part. Arithmetic is done where the unit part...
class FloatingPointGeneric(LocalGeneric):
def is_floating_point(self): """ Returns whether this `p`-adic ring uses a floating point precision model. Elements in the floating point model are stored by giving a valuation and a unit part. Arithmetic is done where the unit part is truncated modulo a fixed power of the ...
Returns whether this `p`-adic ring bounds precision in a fixed modulus fashion. The absolute precision of an element is the power of p modulo which that element is defined. In a fixed modulus ring, the absolute precision of every element is defined to be the precision c...
256
256
931
7
249
vbraun/sage
src/sage/rings/padics/generic_nodes.py
Python
FloatingPointGeneric
FloatingPointGeneric
144
254
144
144
f6dfbbda13752e7f9dc82b8eb15d23d59da00776
bigcode/the-stack
train
64e542c28023294fbe4ccd1c
train
class
class FloatingPointFieldGeneric(FloatingPointGeneric):#, sage.rings.ring.Field): pass
class FloatingPointFieldGeneric(FloatingPointGeneric):#, sage.rings.ring.Field):
pass
+ y) + z).is_equal_to(x + (y + z), min(x.precision_absolute(), y.precision_absolute(), z.precision_absolute()))) class FloatingPointRingGeneric(FloatingPointGeneric): pass class FloatingPointFieldGeneric(FloatingPointGeneric):#, sage.rings.ring.Field):
64
64
21
18
45
vbraun/sage
src/sage/rings/padics/generic_nodes.py
Python
FloatingPointFieldGeneric
FloatingPointFieldGeneric
258
259
258
258
307e218edecaf72234647cfeae6b6b0af65654e3
bigcode/the-stack
train
11def37e3e32ed6d1ab2af6c
train
class
class pAdicFieldGeneric(pAdicGeneric, Field): pass
class pAdicFieldGeneric(pAdicGeneric, Field):
pass
field. EXAMPLES:: sage: is_pAdicField(Zp(17)) False sage: is_pAdicField(Qp(17)) True """ return isinstance(R, pAdicFieldGeneric) class pAdicFieldGeneric(pAdicGeneric, Field):
64
64
16
13
51
vbraun/sage
src/sage/rings/padics/generic_nodes.py
Python
pAdicFieldGeneric
pAdicFieldGeneric
326
327
326
326
affc8a1b2af893a4c77323ad7dd42332e93fb279
bigcode/the-stack
train
88cda1aa48f8416e6737c2ae
train
class
class pAdicFloatingPointRingGeneric(pAdicRingGeneric, FloatingPointRingGeneric): pass
class pAdicFloatingPointRingGeneric(pAdicRingGeneric, FloatingPointRingGeneric):
pass
icCappedRelativeRingGeneric(pAdicRingGeneric, CappedRelativeRingGeneric): pass class pAdicCappedRelativeFieldGeneric(pAdicFieldGeneric, CappedRelativeFieldGeneric): pass class pAdicFloatingPointRingGeneric(pAdicRingGeneric, FloatingPointRingGeneric):
64
64
22
19
44
vbraun/sage
src/sage/rings/padics/generic_nodes.py
Python
pAdicFloatingPointRingGeneric
pAdicFloatingPointRingGeneric
367
368
367
367
af425ffd43146f1fff90c4c0282986065bce826f
bigcode/the-stack
train
6811f482ef84cd026eca6cd4
train
class
class pAdicFloatingPointFieldGeneric(pAdicFieldGeneric, FloatingPointFieldGeneric): pass
class pAdicFloatingPointFieldGeneric(pAdicFieldGeneric, FloatingPointFieldGeneric):
pass
pAdicCappedRelativeFieldGeneric(pAdicFieldGeneric, CappedRelativeFieldGeneric): pass class pAdicFloatingPointRingGeneric(pAdicRingGeneric, FloatingPointRingGeneric): pass class pAdicFloatingPointFieldGeneric(pAdicFieldGeneric, FloatingPointFieldGeneric):
64
64
22
19
44
vbraun/sage
src/sage/rings/padics/generic_nodes.py
Python
pAdicFloatingPointFieldGeneric
pAdicFloatingPointFieldGeneric
369
370
369
369
214184be686368afef7a362162e20fdfa86ee7e2
bigcode/the-stack
train
278ac5600e9a5a422830c7fc
train
class
class CappedRelativeRingGeneric(CappedRelativeGeneric): pass
class CappedRelativeRingGeneric(CappedRelativeGeneric):
pass
z), min(x.precision_absolute(), y.precision_absolute(), z.precision_absolute()))) class FloatingPointRingGeneric(FloatingPointGeneric): pass class FloatingPointFieldGeneric(FloatingPointGeneric):#, sage.rings.ring.Field): pass class CappedRelativeRingGeneric(CappedRelativeGeneric):
64
64
14
11
52
vbraun/sage
src/sage/rings/padics/generic_nodes.py
Python
CappedRelativeRingGeneric
CappedRelativeRingGeneric
260
261
260
260
a2da3afe843b8695d8b09bdd868ae42bda268f7c
bigcode/the-stack
train
8884635b4f20259ecd44d47a
train
function
def diagnose_index(info): failure_code = info.get('failure_code', 256) failure_prob = CODES.get(failure_code, 0) problems = [failure_prob] if failure_prob else [] options = {} subtrees = info.get('subtrees') _local_spots = info.get('local_indexed_spots') # not enough spots if info.get...
def diagnose_index(info):
failure_code = info.get('failure_code', 256) failure_prob = CODES.get(failure_code, 0) problems = [failure_prob] if failure_prob else [] options = {} subtrees = info.get('subtrees') _local_spots = info.get('local_indexed_spots') # not enough spots if info.get('spots') and 'selected_sp...
6, 'spot_accuracy', 'Spots deviate significantly from expected positions.'), (7, 'dimension_2d', 'Clusters are not 3-Dimensional.'), (8, 'few_spots', 'Insufficient spots available.'), (9, 'failed', 'Indexing failed for unknown reason.') ) CODES = { xds.SPOT_LIST_NOT_3D: PROBLEMS.dimension_2d, xds.I...
190
190
636
5
185
michel4j/auto-process
autoprocess/engine/indexing.py
Python
diagnose_index
diagnose_index
36
115
36
36
35997187eb90d315390a3be6c06b27903f11ad77
bigcode/the-stack
train
5267ed76b478e43609661713
train
function
def auto_index(data_info, options=None): options = options or {} os.chdir(data_info['working_directory']) step_descr = 'Determining lattice orientation and parameters' jobs = 'IDXREF' run_info = {'mode': options.get('mode')} run_info.update(data_info) if not misc.file_requirements('XDS.INP',...
def auto_index(data_info, options=None):
options = options or {} os.chdir(data_info['working_directory']) step_descr = 'Determining lattice orientation and parameters' jobs = 'IDXREF' run_info = {'mode': options.get('mode')} run_info.update(data_info) if not misc.file_requirements('XDS.INP', 'SPOT.XDS'): return {'step': 'in...
=False, filename='SPOT.XDS'): new_list = numpy.loadtxt(filename) if new_list.shape[1] < 5: return fmt = [" %0.2f"] + ["%0.2f"] * 2 + ["%0.0f."] if new_list.shape[1] > 7: fmt += ["%d"] * 4 else: fmt += ["%d"] * 3 new_sel = (new_list[:, 3] > sigma) if unindexed: ...
255
256
1,008
9
246
michel4j/auto-process
autoprocess/engine/indexing.py
Python
auto_index
auto_index
143
233
143
143
eb22e538b15d7e5edf9a37798d408fafaa7f2610
bigcode/the-stack
train
073bf1dee13fe3c52aa40a92
train
function
def harvest_index(): info = xds.parse_idxref() if info.get('failure_code') == 0: return {'step': 'indexing', 'success': True, 'data': info} else: return {'step': 'indexing', 'success': False, 'reason': info['failure']}
def harvest_index():
info = xds.parse_idxref() if info.get('failure_code') == 0: return {'step': 'indexing', 'success': True, 'data': info} else: return {'step': 'indexing', 'success': False, 'reason': info['failure']}
new_sel = new_sel & (new_list[:, -3] != 0) & (new_list[:, -3] != 0) & (new_list[:, -3] != 0) numpy.savetxt(filename, new_list[new_sel, :], fmt=fmt) def harvest_index():
64
64
68
4
60
michel4j/auto-process
autoprocess/engine/indexing.py
Python
harvest_index
harvest_index
135
140
135
135
ebd08eae75e7aff120bc31acfc85a4536fb35dc3
bigcode/the-stack
train
b95b9f77aa4796bca8767bf1
train
function
def _filter_spots(sigma=0, unindexed=False, filename='SPOT.XDS'): new_list = numpy.loadtxt(filename) if new_list.shape[1] < 5: return fmt = [" %0.2f"] + ["%0.2f"] * 2 + ["%0.0f."] if new_list.shape[1] > 7: fmt += ["%d"] * 4 else: fmt += ["%d"] * 3 new_sel = (new_list[:, ...
def _filter_spots(sigma=0, unindexed=False, filename='SPOT.XDS'):
new_list = numpy.loadtxt(filename) if new_list.shape[1] < 5: return fmt = [" %0.2f"] + ["%0.2f"] * 2 + ["%0.0f."] if new_list.shape[1] > 7: fmt += ["%d"] * 4 else: fmt += ["%d"] * 3 new_sel = (new_list[:, 3] > sigma) if unindexed: new_sel = new_sel & (new_lis...
0: problems.append(PROBLEMS.index_origin) options['beam_center'] = origin_deviation return { 'problems': set(problems), 'options': options } def _filter_spots(sigma=0, unindexed=False, filename='SPOT.XDS'):
64
64
190
21
43
michel4j/auto-process
autoprocess/engine/indexing.py
Python
_filter_spots
_filter_spots
118
132
118
118
62f4dfb3f0796a433f8c303e4cda63dc52208a99
bigcode/the-stack
train
a616b25d6fe7cf498b074b0b
train
function
def get_election_data(geo_code, geo_level, election, session): party_data, total_valid_votes = get_stat_data( ['party'], geo_level, geo_code, session, table_dataset=election['dataset'], recode=lambda f, v: make_party_acronym(v), order_by='-total') results = { 'name': ele...
def get_election_data(geo_code, geo_level, election, session):
party_data, total_valid_votes = get_stat_data( ['party'], geo_level, geo_code, session, table_dataset=election['dataset'], recode=lambda f, v: make_party_acronym(v), order_by='-total') results = { 'name': election['name'], 'party_distribution': party_data, } ...
the rest as 'Other' group_remainder(data[section]['party_distribution'], 9) if geo_level == 'country': add_elections_media_coverage(data) return data finally: session.close() def get_election_data(geo_code, geo_level, election, session):
64
64
216
16
48
Bhanditz/censusreporter
api/controller/elections.py
Python
get_election_data
get_election_data
81
103
81
81
928eae412111b90e4749e7a6006a2d8be5c71c56
bigcode/the-stack
train
a44e5256219d022d15ecc304
train
function
def add_elections_media_coverage(data): party_coverage = [ ('ANC', 37.78), ('DA', 25.51), ('EFF', 13.30), ('COPE', 4.15), ('AGANG', 3.24), ('IFP', 2.55), ('Other', 13.47), ] gender_coverage = [ ('Female', 22.02), ('Male', 77.98), ]...
def add_elections_media_coverage(data):
party_coverage = [ ('ANC', 37.78), ('DA', 25.51), ('EFF', 13.30), ('COPE', 4.15), ('AGANG', 3.24), ('IFP', 2.55), ('Other', 13.47), ] gender_coverage = [ ('Female', 22.02), ('Male', 77.98), ] # fold them in parties = Order...
registered voters'}) results['total_votes'], _ = table.get_stat_data( geo_level, geo_code, 'total_votes', percent=True, total='registered_voters', recode={'total_votes': 'Of registered voters cast their vote'}) return results def add_elections_media_coverage(data):
66
66
222
9
56
Bhanditz/censusreporter
api/controller/elections.py
Python
add_elections_media_coverage
add_elections_media_coverage
106
140
106
106
6d3f0196170d12fcdb529d30a15d21990e958fb1
bigcode/the-stack
train
984db3fed109b508ee5e29bb
train
function
def get_elections_profile(geo_code, geo_level): data = OrderedDict() session = get_session() try: geo_summary_levels = get_summary_geo_info(geo_code, geo_level, session) for election in ELECTIONS: section = election['name'].lower().replace(' ', '_') data[section] = g...
def get_elections_profile(geo_code, geo_level):
data = OrderedDict() session = get_session() try: geo_summary_levels = get_summary_geo_info(geo_code, geo_level, session) for election in ELECTIONS: section = election['name'].lower().replace(' ', '_') data[section] = get_election_data(geo_code, geo_level, election, ...
', 'BY', 'FOR', 'IN', 'OF', 'TO')) acronym = ''.join([w.lstrip()[0] for w in name.split(' ') if w.strip() and w.upper() not in ignore]) return acronym def get_elections_profile(geo_code, geo_level):
64
64
209
12
51
Bhanditz/censusreporter
api/controller/elections.py
Python
get_elections_profile
get_elections_profile
54
78
54
54
a66dbca5c15bf9ae97018d4afba90848665d8265
bigcode/the-stack
train
48d4daeda65e30e7c4712266
train
function
def make_party_acronym(name): ''' This is good enough since only 2 parties have the same acronym, and these are local parties in different provinces. ''' exceptions = { "AFRICAN CHRISTIAN ALLIANCE-AFRIKANER CHRISTEN ALLIANSIE": "ACA", "DEMOCRATIC ALLIANCE/DEMOKRATIESE ALLIANSIE": "DA...
def make_party_acronym(name):
''' This is good enough since only 2 parties have the same acronym, and these are local parties in different provinces. ''' exceptions = { "AFRICAN CHRISTIAN ALLIANCE-AFRIKANER CHRISTEN ALLIANSIE": "ACA", "DEMOCRATIC ALLIANCE/DEMOKRATIESE ALLIANSIE": "DA", "CAPE PARTY/ KAAPSE...
name': 'Provincial 2014', 'table_code': 'provincial_2014', 'dataset': '2014 Provincial Elections', }, { 'name': 'Municipal 2011', 'table_code': 'municipal_2011', 'dataset': '2011 Municipal Elections', }, ] def make_party_acronym(name):
81
81
271
8
73
Bhanditz/censusreporter
api/controller/elections.py
Python
make_party_acronym
make_party_acronym
28
51
28
28
f30f12e803319c30a7d5bf85a289631b7c3ab84b
bigcode/the-stack
train
c6657536e776ed8a5fa6d3d4
train
class
class Migration(migrations.Migration): dependencies = [ ('topography', '0002_event_information'), ] operations = [ migrations.AlterField( model_name='event', name='information', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.de...
class Migration(migrations.Migration):
dependencies = [ ('topography', '0002_event_information'), ] operations = [ migrations.AlterField( model_name='event', name='information', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='information.Containe...
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2017-10-27 15:41 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
61
64
74
7
53
campusmedius/campusmedius
backend/campusmedius/campusmedius/topography/migrations/0003_auto_20171027_1541.py
Python
Migration
Migration
9
21
9
10
dcb04e6b1fc1d07d2e4434cccbce3a063fb19409
bigcode/the-stack
train
0a2f2bfc76fbc75bf3082d37
train
function
def focal_loss(output, label): label = tf.cast(tf.greater(label, 0.5), tf.float32) p = tf.sigmoid(output) pos_p = tf.multiply(p, label) neg_p = tf.multiply((1.0 - p), (1.0 - label)) sum_p = pos_p + neg_p final_p = tf.clip_by_value(sum_p, 1e-12, (1.0 - 1e-12)) final_log = tf.multiply(-1.0, tf...
def focal_loss(output, label):
label = tf.cast(tf.greater(label, 0.5), tf.float32) p = tf.sigmoid(output) pos_p = tf.multiply(p, label) neg_p = tf.multiply((1.0 - p), (1.0 - label)) sum_p = pos_p + neg_p final_p = tf.clip_by_value(sum_p, 1e-12, (1.0 - 1e-12)) final_log = tf.multiply(-1.0, tf.log(final_p)) final_loss =...
_list()[0] flat_logits = tf.reshape(pred, [-1, tf.shape(pred)[0]]) flat_labels = tf.reshape(label, [-1, tf.shape(pred)[0]]) return tf.reduce_mean(tf.cast(tf.equal(flat_logits, flat_labels), tf.float32)) def focal_loss(output, label):
64
64
154
7
57
mintanwei/artificial-intelligence-for-classification-and-segmentation-of-esophagus-precancerous-lesions
Esophagus/MODEL.py
Python
focal_loss
focal_loss
355
364
355
355
fd08ea0bae21fbc3f730d526fb9f5fd60f3b616d
bigcode/the-stack
train
dc082432717233d62ad0df7b
train
function
def focal_loss_class_balanced(output, label): label = tf.cast(tf.greater(label, 0.5), tf.float32) num_labels_pos = tf.reduce_sum(label) num_labels_neg = tf.reduce_sum(1.0 - label) num_total = num_labels_pos + num_labels_neg p = tf.sigmoid(output) # p = output pos = tf.multiply(p, label) ...
def focal_loss_class_balanced(output, label):
label = tf.cast(tf.greater(label, 0.5), tf.float32) num_labels_pos = tf.reduce_sum(label) num_labels_neg = tf.reduce_sum(1.0 - label) num_total = num_labels_pos + num_labels_neg p = tf.sigmoid(output) # p = output pos = tf.multiply(p, label) neg = tf.multiply((1.0 - p), (1.0 - label)) ...
.0 - label)) sum_p = pos_p + neg_p final_p = tf.clip_by_value(sum_p, 1e-12, (1.0 - 1e-12)) final_log = tf.multiply(-1.0, tf.log(final_p)) final_loss = tf.multiply(0.25, tf.multiply((1.0 - final_p) ** 2, final_log)) return tf.reduce_sum(final_loss) def focal_loss_class_balanced(output, label):
105
105
350
10
95
mintanwei/artificial-intelligence-for-classification-and-segmentation-of-esophagus-precancerous-lesions
Esophagus/MODEL.py
Python
focal_loss_class_balanced
focal_loss_class_balanced
366
390
366
366
50bc80db4ff06d91e2c359e6c188fec0242e9a4f
bigcode/the-stack
train
ed2b9c4a739c3bfa8534d622
train
function
def class_balanced_cross_entropy_loss(output, label): """Define the class balanced cross entropy loss to train the network Args: output: Output of the network label: Ground truth label Returns: Tensor that evaluates the loss """ labels = tf.cast(tf.greater(label, 0.5), tf.float32) ...
def class_balanced_cross_entropy_loss(output, label):
"""Define the class balanced cross entropy loss to train the network Args: output: Output of the network label: Ground truth label Returns: Tensor that evaluates the loss """ labels = tf.cast(tf.greater(label, 0.5), tf.float32) num_labels_pos = tf.reduce_sum(labels) num_labels_...
.cast(tf.greater(label, 0.5), tf.float32) # p = output # pos = tf.multiply(p, label) # neg = tf.multiply((1.0 - p), (1.0 - label)) # final_p = pos + neg def class_balanced_cross_entropy_loss(output, label):
71
71
238
11
59
mintanwei/artificial-intelligence-for-classification-and-segmentation-of-esophagus-precancerous-lesions
Esophagus/MODEL.py
Python
class_balanced_cross_entropy_loss
class_balanced_cross_entropy_loss
400
424
400
400
db1f4a08317b833503f2c13e4093b28c6b4958b4
bigcode/the-stack
train
b77033d22ce6c5ad09f18e20
train
function
def loss_IOU(y_pred,y_true): H, W, _ = y_pred.get_shape().as_list()[1:] flat_logits = tf.reshape(y_pred, [-1, H * W]) flat_labels = tf.reshape(y_true, [-1, H * W]) intersection = tf.reduce_sum(flat_logits * flat_labels, axis=1) #沿着第一维相乘求和 denominator = tf.reduce_sum(flat_logits, axis=1) + tf.reduce_...
def loss_IOU(y_pred,y_true):
H, W, _ = y_pred.get_shape().as_list()[1:] flat_logits = tf.reshape(y_pred, [-1, H * W]) flat_labels = tf.reshape(y_true, [-1, H * W]) intersection = tf.reduce_sum(flat_logits * flat_labels, axis=1) #沿着第一维相乘求和 denominator = tf.reduce_sum(flat_logits, axis=1) + tf.reduce_sum(flat_labels, axis=1) - in...
cross_entropy = -tf.reduce_sum(tf.multiply(labels*tf.log(softmax+epsilon),loss_weight),axis=[1]) cross_entropy_mean = tf.reduce_mean(cross_entropy,name='cross_entropy')''' return cross_entropy_mean #IOU损失 def loss_IOU(y_pred,y_true):
64
64
143
9
54
mintanwei/artificial-intelligence-for-classification-and-segmentation-of-esophagus-precancerous-lesions
Esophagus/MODEL.py
Python
loss_IOU
loss_IOU
327
335
327
327
339bf4f167d26c347960fa785f2f02f002f1552b
bigcode/the-stack
train
92cafd480f60e1ec1c20294d
train
function
def loss_Class(y_pred, y_true): cross_entropy = tf.nn.sigmoid_cross_entropy_with_logits(labels=y_true, logits=y_pred) cross_entropy_mean = tf.reduce_mean(cross_entropy) return cross_entropy_mean
def loss_Class(y_pred, y_true):
cross_entropy = tf.nn.sigmoid_cross_entropy_with_logits(labels=y_true, logits=y_pred) cross_entropy_mean = tf.reduce_mean(cross_entropy) return cross_entropy_mean
tf.multiply(upscore_fuse, temp) return fc3, score_dsn6_up, score_dsn5_up, score_dsn4_up, score_dsn3_up, score_dsn2_up, score_dsn1_up, upscore_fuse def loss_Class(y_pred, y_true):
64
64
47
9
54
mintanwei/artificial-intelligence-for-classification-and-segmentation-of-esophagus-precancerous-lesions
Esophagus/MODEL.py
Python
loss_Class
loss_Class
280
284
280
280
010f4c6275f1c16b44df2292c5dc5b901aa60b02
bigcode/the-stack
train
6cfb82f4d1bafba0fb55a158
train
function
def loss_CE(y_pred,y_true): '''flat_logits = tf.reshape(y_pred,[-1,num_class]) flat_labels = tf.reshape(y_true,[-1,num_class]) class_weights = tf.constant(loss_weight,dtype=np.float32) weight_map = tf.multiply(flat_labels,class_weights) weight_map = tf.reduce_sum(weight_map,axis=1) loss_map = t...
def loss_CE(y_pred,y_true):
'''flat_logits = tf.reshape(y_pred,[-1,num_class]) flat_labels = tf.reshape(y_true,[-1,num_class]) class_weights = tf.constant(loss_weight,dtype=np.float32) weight_map = tf.multiply(flat_labels,class_weights) weight_map = tf.reduce_sum(weight_map,axis=1) loss_map = tf.nn.softmax_cross_entropy_w...
= tf.multiply(upscore_fuse, temp) return fc3, score_dsn6_up, score_dsn5_up, score_dsn4_up, score_dsn3_up, score_dsn2_up, score_dsn1_up, upscore_fuse def loss_Class(y_pred, y_true): cross_entropy = tf.nn.sigmoid_cross_entropy_with_logits(labels=y_true, logits=y_pred) cross_entropy_mean = tf.reduce_...
112
112
376
9
102
mintanwei/artificial-intelligence-for-classification-and-segmentation-of-esophagus-precancerous-lesions
Esophagus/MODEL.py
Python
loss_CE
loss_CE
286
324
286
286
d89afacc3b04e025d0d4c0f941db97c2d870e858
bigcode/the-stack
train
ce3aa5965794bbf36597e2cc
train
function
def get_bias(name, trainable): return tf.Variable(data_dict[name][1], trainable=trainable, name="biases")
def get_bias(name, trainable):
return tf.Variable(data_dict[name][1], trainable=trainable, name="biases")
, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name=name) def get_conv_filter(name, trainable): return tf.Variable(data_dict[name][0], trainable=trainable, name="filter") def get_bias(name, trainable):
64
64
28
8
56
mintanwei/artificial-intelligence-for-classification-and-segmentation-of-esophagus-precancerous-lesions
Esophagus/MODEL.py
Python
get_bias
get_bias
103
104
103
103
fb84b949e9e481608a6ba4b73e78920075c890b5
bigcode/the-stack
train
e53095af6b7431ad6f84ee6e
train
function
def train_op(loss, learning_rate, var_list): global_step = tf.train.get_or_create_global_step() optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) return optimizer.minimize(loss,global_step=global_step,var_list=var_list)
def train_op(loss, learning_rate, var_list):
global_step = tf.train.get_or_create_global_step() optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) return optimizer.minimize(loss,global_step=global_step,var_list=var_list)
loss_neg = tf.reduce_mean(-tf.multiply(1.0 - labels, loss_val)) final_loss = 2.0 * num_labels_neg / num_total * loss_pos + num_labels_pos / num_total * loss_neg return final_loss def train_op(loss, learning_rate, var_list):
64
64
55
11
52
mintanwei/artificial-intelligence-for-classification-and-segmentation-of-esophagus-precancerous-lesions
Esophagus/MODEL.py
Python
train_op
train_op
426
431
426
427
a6b9af0dded370d32ffbbe45948080ebb65abbc3
bigcode/the-stack
train
2d24a4bd6ee2787bae7a836c
train
function
def deconv2d(x,kernel,strides,training,name,output_shape,activation=None): kernel_shape=[kernel,kernel,1,1] strides=[1,strides,strides,1] kernel=tf.get_variable('weight_{}'.format(name),shape=kernel_shape,initializer=tf.random_normal_initializer(mean=0,stddev=1)) deconv = tf.nn.conv2d_transpose(x, kerne...
def deconv2d(x,kernel,strides,training,name,output_shape,activation=None):
kernel_shape=[kernel,kernel,1,1] strides=[1,strides,strides,1] kernel=tf.get_variable('weight_{}'.format(name),shape=kernel_shape,initializer=tf.random_normal_initializer(mean=0,stddev=1)) deconv = tf.nn.conv2d_transpose(x, kernel, strides=strides,output_shape=output_shape, padding='SAME', ...
d(x,pool_size,pool_stride,name): pool = tf.layers.max_pooling2d(x, pool_size, pool_stride, name='pool_{}'.format(name),padding='same') return pool def deconv2d(x,kernel,strides,training,name,output_shape,activation=None):
64
64
170
20
43
mintanwei/artificial-intelligence-for-classification-and-segmentation-of-esophagus-precancerous-lesions
Esophagus/MODEL.py
Python
deconv2d
deconv2d
37
49
37
37
c6022947a571c0efeb88ddeb726110ba6fdb25ec
bigcode/the-stack
train
19502d8ff72c2aa710a35db7
train
function
def pool2d(x,pool_size,pool_stride,name): pool = tf.layers.max_pooling2d(x, pool_size, pool_stride, name='pool_{}'.format(name),padding='same') return pool
def pool2d(x,pool_size,pool_stride,name):
pool = tf.layers.max_pooling2d(x, pool_size, pool_stride, name='pool_{}'.format(name),padding='same') return pool
= tf.layers.batch_normalization(conv,training=training,name='bn_{}'.format(index+1)) if activation == None: return conv conv = activation(conv,name='relu{}_{}'.format(name,index+1)) return conv def pool2d(x,pool_size,pool_stride,name):
64
64
47
13
50
mintanwei/artificial-intelligence-for-classification-and-segmentation-of-esophagus-precancerous-lesions
Esophagus/MODEL.py
Python
pool2d
pool2d
33
35
33
33
5518faa7bc4a8b0670f4efa5cce3bc2d398da1b2
bigcode/the-stack
train
bbccedfde9647b01bfcb0eab
train
function
def conv_layer(bottom, name, trainable=True): with tf.variable_scope(name): filt = get_conv_filter(name, trainable) conv = tf.nn.conv2d(bottom, filt, [1, 1, 1, 1], padding='SAME') conv_biases = get_bias(name, trainable) bias = tf.nn.bias_add(conv, conv_biases) relu = tf.nn...
def conv_layer(bottom, name, trainable=True):
with tf.variable_scope(name): filt = get_conv_filter(name, trainable) conv = tf.nn.conv2d(bottom, filt, [1, 1, 1, 1], padding='SAME') conv_biases = get_bias(name, trainable) bias = tf.nn.bias_add(conv, conv_biases) relu = tf.nn.relu(bias) return relu
32) shape_b = [output] initial_b = tf.constant(0, shape=shape_b, dtype=tf.float32) b = tf.Variable(initial_b, dtype=tf.float32) return act(tf.matmul(x, W) + b) def conv_layer(bottom, name, trainable=True):
64
64
98
11
53
mintanwei/artificial-intelligence-for-classification-and-segmentation-of-esophagus-precancerous-lesions
Esophagus/MODEL.py
Python
conv_layer
conv_layer
82
92
82
82
bb52277a8ad298c96d08c180bd810aeeef15664b
bigcode/the-stack
train
c584494dec67ab5fa864f02c
train
function
def conv2d(x,weight,n_filters,training,name,activation=tf.nn.relu): with tf.variable_scope('layer{}'.format(name)): for index,filter in enumerate(n_filters): conv = tf.layers.conv2d(x,filter,weight,strides=1,padding='same',activation=activation,name='conv_{}'.format(index+1)) conv = ...
def conv2d(x,weight,n_filters,training,name,activation=tf.nn.relu):
with tf.variable_scope('layer{}'.format(name)): for index,filter in enumerate(n_filters): conv = tf.layers.conv2d(x,filter,weight,strides=1,padding='same',activation=activation,name='conv_{}'.format(index+1)) conv = tf.layers.batch_normalization(conv,training=training,name='bn_{}'.fo...
103.939, 116.779, 123.68] vgg16_npy_path = "../vgg16.npy" data_dict = np.load(vgg16_npy_path, encoding='latin1').item() def conv2d(x,weight,n_filters,training,name,activation=tf.nn.relu):
64
64
127
18
46
mintanwei/artificial-intelligence-for-classification-and-segmentation-of-esophagus-precancerous-lesions
Esophagus/MODEL.py
Python
conv2d
conv2d
20
31
20
20
af97516f73e134e016dce4359b569ca7b70e1cd6
bigcode/the-stack
train
ad956afa45ee527987249f84
train
function
def loss_Pre_class(pred, label): # print(pred.get_shape()) # num = pred.get_shape().as_list()[0] flat_logits = tf.reshape(pred, [-1, tf.shape(pred)[0]]) flat_labels = tf.reshape(label, [-1, tf.shape(pred)[0]]) return tf.reduce_mean(tf.cast(tf.equal(flat_logits, flat_labels), tf.float32))
def loss_Pre_class(pred, label): # print(pred.get_shape()) # num = pred.get_shape().as_list()[0]
flat_logits = tf.reshape(pred, [-1, tf.shape(pred)[0]]) flat_labels = tf.reshape(label, [-1, tf.shape(pred)[0]]) return tf.reduce_mean(tf.cast(tf.equal(flat_logits, flat_labels), tf.float32))
intersection # iou = tf.reduce_mean((intersection + 1e-7) / (denominator + 1e-7)) # return iou def loss_Pre_class(pred, label): # print(pred.get_shape()) # num = pred.get_shape().as_list()[0]
64
64
81
28
35
mintanwei/artificial-intelligence-for-classification-and-segmentation-of-esophagus-precancerous-lesions
Esophagus/MODEL.py
Python
loss_Pre_class
loss_Pre_class
347
352
347
349
36a995e0f44bb9916ddbff4a1851f0e8952e5148
bigcode/the-stack
train
204aebdbb45de3a73cc19d78
train
function
def loss_Pre(pred, label): H, W, _ = pred.get_shape().as_list()[1:] flat_logits = tf.reshape(pred, [-1, H * W]) flat_labels = tf.reshape(label, [-1, H * W]) return tf.reduce_mean(tf.reduce_sum(tf.cast(tf.equal(flat_logits, flat_labels), tf.float32), axis= 1) / (H * W))
def loss_Pre(pred, label):
H, W, _ = pred.get_shape().as_list()[1:] flat_logits = tf.reshape(pred, [-1, H * W]) flat_labels = tf.reshape(label, [-1, H * W]) return tf.reduce_mean(tf.reduce_sum(tf.cast(tf.equal(flat_logits, flat_labels), tf.float32), axis= 1) / (H * W))
= tf.reduce_sum(flat_logits, axis=1) + tf.reduce_sum(flat_labels, axis=1) - intersection iou = tf.reduce_mean((intersection + 1e-7) / (denominator + 1e-7)) return iou def loss_Pre(pred, label):
64
64
86
7
56
mintanwei/artificial-intelligence-for-classification-and-segmentation-of-esophagus-precancerous-lesions
Esophagus/MODEL.py
Python
loss_Pre
loss_Pre
337
341
337
337
b4da435868f1e40bd1dc08a5c1b3a4b469987946
bigcode/the-stack
train
8eef9bc7e7b615ded4f59b55
train
function
def avg_pool(bottom, name): return tf.nn.avg_pool(bottom, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name=name)
def avg_pool(bottom, name):
return tf.nn.avg_pool(bottom, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name=name)
[1, 1, 1, 1], padding='SAME') conv_biases = get_bias(name, trainable) bias = tf.nn.bias_add(conv, conv_biases) relu = tf.nn.relu(bias) return relu def avg_pool(bottom, name):
64
64
50
7
56
mintanwei/artificial-intelligence-for-classification-and-segmentation-of-esophagus-precancerous-lesions
Esophagus/MODEL.py
Python
avg_pool
avg_pool
94
95
94
94
cbddcccb3bbd41c934d38ffa596fffa384bf015d
bigcode/the-stack
train
abafedc1417a6da9bdc7f99d
train
function
def max_pool(bottom, name): return tf.nn.max_pool(bottom, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name=name)
def max_pool(bottom, name):
return tf.nn.max_pool(bottom, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name=name)
ias) return relu def avg_pool(bottom, name): return tf.nn.avg_pool(bottom, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name=name) def max_pool(bottom, name):
64
64
50
7
57
mintanwei/artificial-intelligence-for-classification-and-segmentation-of-esophagus-precancerous-lesions
Esophagus/MODEL.py
Python
max_pool
max_pool
97
98
97
97
1aa58ab2da6732810b9256c77065e2c311d1092f
bigcode/the-stack
train
c1616540d29234feeb0998f7
train
function
def fc_layer(bottom, output, name, act=tf.nn.relu): with tf.variable_scope(name): shape = bottom.get_shape().as_list() dim = 1 for d in shape[1:]: dim *= d x = tf.reshape(bottom, [-1, dim]) shape_W = [dim, output] initial_W = tf.truncated_normal(shape_W, s...
def fc_layer(bottom, output, name, act=tf.nn.relu):
with tf.variable_scope(name): shape = bottom.get_shape().as_list() dim = 1 for d in shape[1:]: dim *= d x = tf.reshape(bottom, [-1, dim]) shape_W = [dim, output] initial_W = tf.truncated_normal(shape_W, stddev=0.1, dtype=tf.float32) W = tf.Variable...
,name): upsampling = upsampling_2d(input_A,name=name,size=(2,2)) up_concat = tf.concat([upsampling,input_B],axis=-1,name='up_concat_{}'.format(name)) return up_concat def fc_layer(bottom, output, name, act=tf.nn.relu):
64
64
159
14
49
mintanwei/artificial-intelligence-for-classification-and-segmentation-of-esophagus-precancerous-lesions
Esophagus/MODEL.py
Python
fc_layer
fc_layer
66
79
66
66
f23969420189c9809036aad5f8920c9499364853
bigcode/the-stack
train
2424e1be7fcdb651518b694e
train
function
def upsampling_concat(input_A,input_B,name): upsampling = upsampling_2d(input_A,name=name,size=(2,2)) up_concat = tf.concat([upsampling,input_B],axis=-1,name='up_concat_{}'.format(name)) return up_concat
def upsampling_concat(input_A,input_B,name):
upsampling = upsampling_2d(input_A,name=name,size=(2,2)) up_concat = tf.concat([upsampling,input_B],axis=-1,name='up_concat_{}'.format(name)) return up_concat
:] h_multi,w_multi = size h = h_multi * h_ w = w_multi * w_ target = tf.image.resize_nearest_neighbor(tensor,size=(h,w),name='deconv_{}'.format(name)) return target def upsampling_concat(input_A,input_B,name):
64
64
58
10
53
mintanwei/artificial-intelligence-for-classification-and-segmentation-of-esophagus-precancerous-lesions
Esophagus/MODEL.py
Python
upsampling_concat
upsampling_concat
61
64
61
61
91946a574c181b9b89469fda83902b5deaec6f86
bigcode/the-stack
train
f6a84bf153a38b21929e8aeb
train
function
def dss_model(input, y, training): # Convert RGB to BGR red, green, blue = tf.split(input, 3, 3) assert red.get_shape().as_list()[1:] == [h, w, 1] assert green.get_shape().as_list()[1:] == [h, w, 1] assert blue.get_shape().as_list()[1:] == [h, w, 1] bgr = tf.concat([ blue - VGG_MEAN[0], ...
def dss_model(input, y, training): # Convert RGB to BGR
red, green, blue = tf.split(input, 3, 3) assert red.get_shape().as_list()[1:] == [h, w, 1] assert green.get_shape().as_list()[1:] == [h, w, 1] assert blue.get_shape().as_list()[1:] == [h, w, 1] bgr = tf.concat([ blue - VGG_MEAN[0], green - VGG_MEAN[1], red - VGG_MEAN[2] ]...
(name): filt = get_conv_filter(name, trainable) conv = tf.nn.conv2d(bottom, filt, [1, 1, 1, 1], padding='SAME') conv_biases = get_bias(name, trainable) bias = tf.nn.bias_add(conv, conv_biases) relu = tf.nn.relu(bias) return relu def avg_pool(bottom, name): return ...
256
256
3,951
18
238
mintanwei/artificial-intelligence-for-classification-and-segmentation-of-esophagus-precancerous-lesions
Esophagus/MODEL.py
Python
dss_model
dss_model
106
277
106
107
e1ed8e40f9247ea36b919d9df8ea6b2d0cd76b5f
bigcode/the-stack
train
9993de7ef785d8f318a9530d
train
function
def get_conv_filter(name, trainable): return tf.Variable(data_dict[name][0], trainable=trainable, name="filter")
def get_conv_filter(name, trainable):
return tf.Variable(data_dict[name][0], trainable=trainable, name="filter")
AME', name=name) def max_pool(bottom, name): return tf.nn.max_pool(bottom, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name=name) def get_conv_filter(name, trainable):
64
64
28
9
55
mintanwei/artificial-intelligence-for-classification-and-segmentation-of-esophagus-precancerous-lesions
Esophagus/MODEL.py
Python
get_conv_filter
get_conv_filter
100
101
100
100
aaeb97a62f64762a44d9128bb5fa188d14db4284
bigcode/the-stack
train
c599264358e8a198ce687b52
train
function
def upsampling_2d(tensor,name,size=(2,2)): h_,w_,c_ = tensor.get_shape().as_list()[1:] h_multi,w_multi = size h = h_multi * h_ w = w_multi * w_ target = tf.image.resize_nearest_neighbor(tensor,size=(h,w),name='deconv_{}'.format(name)) return target
def upsampling_2d(tensor,name,size=(2,2)):
h_,w_,c_ = tensor.get_shape().as_list()[1:] h_multi,w_multi = size h = h_multi * h_ w = w_multi * w_ target = tf.image.resize_nearest_neighbor(tensor,size=(h,w),name='deconv_{}'.format(name)) return target
_normalization(deconv, training=training, name='bn{}'.format(name)) if activation == None: return deconv deconv = activation(deconv, name='sigmoid_{}'.format(name)) return deconv def upsampling_2d(tensor,name,size=(2,2)):
64
64
85
15
48
mintanwei/artificial-intelligence-for-classification-and-segmentation-of-esophagus-precancerous-lesions
Esophagus/MODEL.py
Python
upsampling_2d
upsampling_2d
52
59
52
52
73128de44f4a08316cec0a55e88728186c6269d1
bigcode/the-stack
train
f01179b2511301b843a3638e
train
function
def savePickle(index, flag ) : d= { "SELL_INDEX" : index, "SELL_FLAG" : flag } # Store data (serialize) with open('asd.pickle', 'wb') as handle: pickle.dump(d, handle) with open('sellDict.pickle', 'wb') as handle: pickle.dump({}, handle)
def savePickle(index, flag ) :
d= { "SELL_INDEX" : index, "SELL_FLAG" : flag } # Store data (serialize) with open('asd.pickle', 'wb') as handle: pickle.dump(d, handle) with open('sellDict.pickle', 'wb') as handle: pickle.dump({}, handle)
virginianae_23A_lg.jpg", "apple scab":"http://www.missouribotanicalgarden.org/Portals/0/Gardening/Gardening%20Help/images/Pests/Apple_Scab1411.jpg" } def savePickle(index, flag ) :
64
64
81
10
54
DefCon-007/test1
app.py
Python
savePickle
savePickle
33
45
33
34
cd61de1f4fb2b2efddf4dba9ea376ebd66bc264f
bigcode/the-stack
train
e6e2b4f5328509698db29b08
train
function
def getFertiliserResponse(data,img) : resp = { "attachment":{ "type":"template", "payload":{ "template_type":"generic", "elements":[ ] } } } for k,v in data.items(): item_to_sell = { "title":k, "subtitle":"{} KG/Ha".forma...
def getFertiliserResponse(data,img) :
resp = { "attachment":{ "type":"template", "payload":{ "template_type":"generic", "elements":[ ] } } } for k,v in data.items(): item_to_sell = { "title":k, "subtitle":"{} KG/Ha".format(v), "image_url":img, ...
type":"web_url", "url":"https://www.google.com/search?q=" + d["disease"], "title":"More info" }] } resp["attachment"]["payload"]["elements"].append(item_to_sell) return resp def getFertiliserResponse(data,img) :
64
64
148
11
52
DefCon-007/test1
app.py
Python
getFertiliserResponse
getFertiliserResponse
347
372
347
347
35a488e84438c037d766464e2ef630603bbeeb4a
bigcode/the-stack
train
0665a22f28bffd708dc65dd0
train
function
def get_user(sender_id): ''' The user_details dictionary will have following keys first_name : First name of user last_name : Last name of user profile_pic : Profile picture of user locale : Locale of the user on Facebook ''' base_url = "https://graph.facebook.com/v2.6/{}?fields=first_na...
def get_user(sender_id):
''' The user_details dictionary will have following keys first_name : First name of user last_name : Last name of user profile_pic : Profile picture of user locale : Locale of the user on Facebook ''' base_url = "https://graph.facebook.com/v2.6/{}?fields=first_name,last_name,profile_pic,...
", } ] } ], "buttons": [ { "title": "View More", "type": "postback", "payload": "payload" } ] } } } ...
64
64
123
6
57
DefCon-007/test1
app.py
Python
get_user
get_user
565
576
565
565
c2bc9f6e0efc1187dff61cf546d9da9d22f8d83c
bigcode/the-stack
train
2d697a99fb237a37993f4328
train
function
@app.route("/verify_facebook", methods=["POST", "GET"]) def verify_facebook(): try : VERIFY_TOKEN = "1234553asdcds3" mode = request.args.get("hub.mode") token = request.args.get("hub.verify_token") challenge = request.args.get("hub.challenge") if mode and token: ...
@app.route("/verify_facebook", methods=["POST", "GET"]) def verify_facebook():
try : VERIFY_TOKEN = "1234553asdcds3" mode = request.args.get("hub.mode") token = request.args.get("hub.verify_token") challenge = request.args.get("hub.challenge") if mode and token: # Verify if mode == 'subscribe' and token == VERIFY_TOKEN: ...
aa", unit_type="kg", available_item="200",price_per_unit="20",minimum_item="50",picture="https://cdn1.woolworths.media/content/wowproductimages/medium/144329.jpg",owner_id=1) # db.session.add(user1) # db.session.add(item1) # db.session.commit() # print(User.query.all()) # Valid routes @app.route("/") def main(): r...
111
111
371
19
92
DefCon-007/test1
app.py
Python
verify_facebook
verify_facebook
124
173
124
125
c127589778e49cce535d6358cf7ef6c51693a9c3
bigcode/the-stack
train
d5851c59cd33ab3afc6b52f1
train
function
def getPickleDict() : with open('asd.pickle', 'rb') as handle: unserialized_data = pickle.load(handle) return unserialized_data
def getPickleDict() :
with open('asd.pickle', 'rb') as handle: unserialized_data = pickle.load(handle) return unserialized_data
# Store data (serialize) with open('asd.pickle', 'wb') as handle: pickle.dump(d, handle) with open('sellDict.pickle', 'wb') as handle: pickle.dump({}, handle) savePickle(0, False) def getPickleDict() :
64
64
39
8
56
DefCon-007/test1
app.py
Python
getPickleDict
getPickleDict
48
51
48
48
14eca6dc2d5d2f95ea5f3c20cd63ca0b68fad8ee
bigcode/the-stack
train
976d015cb92e704ccc35276b
train
function
def sending_sender_action(recipient_id, sender_action): params = { "access_token": os.environ["PAGE_ACCESS_TOKEN"] } headers = { "Content-Type": "application/json" } data = json.dumps( { "recipient": { "id": recipient_id }, ...
def sending_sender_action(recipient_id, sender_action):
params = { "access_token": os.environ["PAGE_ACCESS_TOKEN"] } headers = { "Content-Type": "application/json" } data = json.dumps( { "recipient": { "id": recipient_id }, "sender_action": sender_action }) r = reques...
"id": psid }, "message": resp }) r = requests.post("https://graph.facebook.com/v2.6/me/messages", params=params, headers=headers, data=data) print(r) print(r.text) def sending_sender_action(recipient_id, sender_action):
64
64
104
11
53
DefCon-007/test1
app.py
Python
sending_sender_action
sending_sender_action
423
438
423
423
9a6d1685148e4313771d36e4e02070e2662b7f3b
bigcode/the-stack
train
831f44fa1a9387eb26ca3bf0
train
function
def updateSELLVALPick(d) : print("Dict to add") print(d) with open('sellDict.pickle', 'rb') as handle: data = pickle.load(handle) print("init dict") print(data) for k,v in d.items() : data[k] = v print("Final Dict") print(data) with open('sellDict.p...
def updateSELLVALPick(d) :
print("Dict to add") print(d) with open('sellDict.pickle', 'rb') as handle: data = pickle.load(handle) print("init dict") print(data) for k,v in d.items() : data[k] = v print("Final Dict") print(data) with open('sellDict.pickle', 'wb') as handle: ...
handle: pickle.dump({}, handle) savePickle(0, False) def getPickleDict() : with open('asd.pickle', 'rb') as handle: unserialized_data = pickle.load(handle) return unserialized_data def updateSELLVALPick(d) :
64
64
101
9
54
DefCon-007/test1
app.py
Python
updateSELLVALPick
updateSELLVALPick
53
65
53
53
a8241b543c25e9cc22ef57fb70bf43971133d3fa
bigcode/the-stack
train
0c2d280119b08a0af8ec0aad
train
function
def handleMessage(psid, msg) : global SELL_INDEX, SELL_LIST, SELL_IDS SELL_VAL_DICT = {} globDict = getPickleDict() resp = {} if "text" in msg.keys() : if globDict["SELL_FLAG"] : # updateSELLVALPick({SELL_IDS[globDict["SELL_INDEX"]] : msg["text"]}) addSel...
def handleMessage(psid, msg) :
global SELL_INDEX, SELL_LIST, SELL_IDS SELL_VAL_DICT = {} globDict = getPickleDict() resp = {} if "text" in msg.keys() : if globDict["SELL_FLAG"] : # updateSELLVALPick({SELL_IDS[globDict["SELL_INDEX"]] : msg["text"]}) addSellData(psid,SELL_IDS[globDict["SE...
request.json if body["object"] == "page" : for entry in body["entry"] : if entry.get("postback") : postb = entry["postback"] payload = postb["payload"] print(payload) return...
256
256
1,189
10
245
DefCon-007/test1
app.py
Python
handleMessage
handleMessage
176
278
176
176
a4ae0f997ab951c70380b035c8f95dbcdf80b228
bigcode/the-stack
train
5750e554d163ee6ef4414fc1
train
function
def UpdateFromDict(table, values, user_id): if table=="user": seller = db.session.query(User).get(user_id) unit = tables.Stock(**values) seller.user_stock.append(unit) db.session.add(unit) db.session.commit()
def UpdateFromDict(table, values, user_id):
if table=="user": seller = db.session.query(User).get(user_id) unit = tables.Stock(**values) seller.user_stock.append(unit) db.session.add(unit) db.session.commit()
1]["by"] = psid gist.write_database(oldDict) # seller = db.session.query(User).get(psid) # stck = seller.user_stock # setattr(stck, key, val) # db.session.commit() def UpdateFromDict(table, values, user_id):
64
64
56
11
53
DefCon-007/test1
app.py
Python
UpdateFromDict
UpdateFromDict
450
456
450
450
a5af22872678c606ab790d3ae05bbebe1c42cb58
bigcode/the-stack
train
6b5ab090795c84fdbdbea204
train
function
def getNews(): resp = { "attachment": { "type": "template", "payload": { "template_type": "list", "top_element_style": "large", "elements": [ { "title": "Farm loan waivers: What does it mean for economy?", "image...
def getNews():
resp = { "attachment": { "type": "template", "payload": { "template_type": "list", "top_element_style": "large", "elements": [ { "title": "Farm loan waivers: What does it mean for economy?", "image_url": "https:/...
(user_id) unit = tables.Stock(**values) seller.user_stock.append(unit) db.session.add(unit) db.session.commit() def ItemsList(): resp = { "attachment":{ "type":"template", "payload":{ "template_type":"generic", "elements":[ ] } ...
224
224
748
4
219
DefCon-007/test1
app.py
Python
getNews
getNews
491
564
491
491
b461040e3546cc4c010b1fbbbf2801379af4361d
bigcode/the-stack
train
b614b64858d631d5d7a4a504
train
function
def getBuyResp() : d = gist.read_database() prd = d["data"]["products"] resp = { "attachment":{ "type":"template", "payload":{ "template_type":"generic", "elements":[ ] } } } for i in prd : item_to_sell = { "title":i...
def getBuyResp() :
d = gist.read_database() prd = d["data"]["products"] resp = { "attachment":{ "type":"template", "payload":{ "template_type":"generic", "elements":[ ] } } } for i in prd : item_to_sell = { "title":i["prodName"], ...
."}) callSendAPI(psid, getFertiliserResponse(phos,"http://i.imgur.com/Ao1vPNe.jpg")) # print("attachmentUrl") # resp["text"] = attachmentUrl # callSendAPI(psid,resp) def getBuyResp() :
64
64
188
7
57
DefCon-007/test1
app.py
Python
getBuyResp
getBuyResp
282
309
282
282
2b7ac183a639a438de6631e98fdd015c870c9e98
bigcode/the-stack
train
c9cbca7b49e4f5ff3e2a5016
train
function
def getDiseaaseResponse(data) : resp = { "attachment":{ "type":"template", "payload":{ "template_type":"generic", "elements":[ ] } } } for d in data : item_to_sell = { "title":d["disease"], "subtitle":"Probability : {} %"...
def getDiseaaseResponse(data) :
resp = { "attachment":{ "type":"template", "payload":{ "template_type":"generic", "elements":[ ] } } } for d in data : item_to_sell = { "title":d["disease"], "subtitle":"Probability : {} %".format(d["score"]), "ima...
" r = requests.post(endpoint, {"image_url": sample_image_url}) content = json.loads(r.content.decode("utf-8"))['data'] # response = json.loads(str.encode("utf-8").strip())['data'] return content def getDiseaaseResponse(data) :
64
64
161
10
53
DefCon-007/test1
app.py
Python
getDiseaaseResponse
getDiseaaseResponse
321
345
321
321
f6344876b2d238458192e0253141f5eb7452ae4c
bigcode/the-stack
train
d74c61e7615c857bedf02202
train
function
def callSendAPI(psid, resp) : print(resp) params = { "access_token": os.environ["PAGE_ACCESS_TOKEN"] } headers = { "Content-Type": "application/json" } data = json.dumps({ "recipient": { "id": psid }, "message": resp }) r = requests.po...
def callSendAPI(psid, resp) :
print(resp) params = { "access_token": os.environ["PAGE_ACCESS_TOKEN"] } headers = { "Content-Type": "application/json" } data = json.dumps({ "recipient": { "id": psid }, "message": resp }) r = requests.post("https://graph.facebook.com/...
type":"postback", "payload":"address", "title":"Address" }, { "type":"postback", "payload":"phone", "title":"Phone number" } ] } }} return resp def callSendAPI(psid, resp) :
64
64
113
11
52
DefCon-007/test1
app.py
Python
callSendAPI
callSendAPI
404
421
404
404
e9d720364295d079486e25cf997706015bc4ff14
bigcode/the-stack
train
d4a113fdcb13252b04796b5d
train
function
def ItemsList(): resp = { "attachment":{ "type":"template", "payload":{ "template_type":"generic", "elements":[ ] } } } for instance in db.session.query(User).order_by(user_id): for it in instance.user_stock: item_to_sell = { ...
def ItemsList():
resp = { "attachment":{ "type":"template", "payload":{ "template_type":"generic", "elements":[ ] } } } for instance in db.session.query(User).order_by(user_id): for it in instance.user_stock: item_to_sell = { "titl...
db.session.commit() def UpdateFromDict(table, values, user_id): if table=="user": seller = db.session.query(User).get(user_id) unit = tables.Stock(**values) seller.user_stock.append(unit) db.session.add(unit) db.session.commit() def ItemsList():
63
64
190
4
59
DefCon-007/test1
app.py
Python
ItemsList
ItemsList
458
489
458
458
4f2e946129b4b0deff9d8eeb79d30e23ddbffc47
bigcode/the-stack
train
0c45206f38337a03e0ed2f7f
train
function
def addSellData(psid,key,val) : oldDict = gist.read_database() oldDict["data"]["products"][-1][key] = val oldDict["data"]["products"][-1]["by"] = psid gist.write_database(oldDict)
def addSellData(psid,key,val) :
oldDict = gist.read_database() oldDict["data"]["products"][-1][key] = val oldDict["data"]["products"][-1]["by"] = psid gist.write_database(oldDict)
{ "recipient": { "id": recipient_id }, "sender_action": sender_action }) r = requests.post("https://graph.facebook.com/v2.6/me/messages", params=params, headers=headers, data=data) def addSellData(psid,key,val) :
64
64
59
11
53
DefCon-007/test1
app.py
Python
addSellData
addSellData
440
444
440
440
643fe101194bf84293c8732fafd339eb306c4b83
bigcode/the-stack
train
e4cb0192ffc5502388856c1a
train
function
def getRegistrationDict() : resp = {"attachment":{ "type":"template", "payload":{ "template_type":"button", "text":"What do you want to do next?", "buttons":[ { "type":"postback", "payload":"user_name", "title":"Name" }, ...
def getRegistrationDict() :
resp = {"attachment":{ "type":"template", "payload":{ "template_type":"button", "text":"What do you want to do next?", "buttons":[ { "type":"postback", "payload":"user_name", "title":"Name" }, { "type":...
"buttons":[ { "type":"web_url", "url":"https://www.google.com/search?q=" + k, "title":"More info" }] } resp["attachment"]["payload"]["elements"].append(item_to_sell) return resp def getRegistrationDict() :
64
64
127
6
57
DefCon-007/test1
app.py
Python
getRegistrationDict
getRegistrationDict
374
400
374
374
f339562ad1d74968125c1e851653e7abcc9c84e5
bigcode/the-stack
train
245da0d9389aebbde00b9a44
train
function
@app.route("/") def main(): return "Hello"
@app.route("/") def main():
return "Hello"
picture="https://cdn1.woolworths.media/content/wowproductimages/medium/144329.jpg",owner_id=1) # db.session.add(user1) # db.session.add(item1) # db.session.commit() # print(User.query.all()) # Valid routes @app.route("/") def main():
64
64
11
6
57
DefCon-007/test1
app.py
Python
main
main
120
122
120
121
18e3ce38be693851e806355c0395634a14812305
bigcode/the-stack
train
66221d99e465d782163e2948
train
function
def getSellValDict(): with open('sellDict.pickle', 'rb') as handle: unserialized_data = pickle.load(handle) return unserialized_data
def getSellValDict():
with open('sellDict.pickle', 'rb') as handle: unserialized_data = pickle.load(handle) return unserialized_data
print("init dict") print(data) for k,v in d.items() : data[k] = v print("Final Dict") print(data) with open('sellDict.pickle', 'wb') as handle: pickle.dump(data, handle) def getSellValDict():
64
64
38
6
58
DefCon-007/test1
app.py
Python
getSellValDict
getSellValDict
66
69
66
66
21f684e88d860779f924c195a04d00ed3845365e
bigcode/the-stack
train
0eb3b200ed38d3dbb1979aea
train
function
def fetch_data_from_url(sample_image_url) : endpoint = "http://disection.herokuapp.com/disease_check" r = requests.post(endpoint, {"image_url": sample_image_url}) content = json.loads(r.content.decode("utf-8"))['data'] # response = json.loads(str.encode("utf-8").strip())['data'] return content
def fetch_data_from_url(sample_image_url) :
endpoint = "http://disection.herokuapp.com/disease_check" r = requests.post(endpoint, {"image_url": sample_image_url}) content = json.loads(r.content.decode("utf-8"))['data'] # response = json.loads(str.encode("utf-8").strip())['data'] return content
buttons":[ { "type":"web_url", "url":"https://www.google.com/", "title":"Buy Now" }] } resp["attachment"]["payload"]["elements"].append(item_to_sell) return resp def fetch_data_from_url(sample_image_url) :
64
64
80
12
51
DefCon-007/test1
app.py
Python
fetch_data_from_url
fetch_data_from_url
314
319
314
314
e445f1a810c9a9df69c158f630375cba7e28789a
bigcode/the-stack
train
d8cbaa584d24491f7e147b5f
train
class
class ReadOnly(object): """ A ``ReadOnly`` object wraps another object and prevents all the contained object's fields from being written. Example use: .. python:: from grizzled.misc import ReadOnly from grizzled.config import Configuration config = Configuration() conf...
class ReadOnly(object):
""" A ``ReadOnly`` object wraps another object and prevents all the contained object's fields from being written. Example use: .. python:: from grizzled.misc import ReadOnly from grizzled.config import Configuration config = Configuration() config.read('/path/to/some/f...
') # --------------------------------------------------------------------------- # Public classes # --------------------------------------------------------------------------- class ReadOnlyObjectError(ExceptionWithMessage): """ Thrown by ``ReadOnly`` to indicate an attempt to set a field. :IVariables: ...
116
116
388
5
110
brianrodri/google_appengine
lib/grizzled/grizzled/misc.py
Python
ReadOnly
ReadOnly
58
112
58
58
447cc5254e0074ac418d99d0f0682fca7354662f
bigcode/the-stack
train
c930da504202e39f8c808f21
train
class
class ReadOnlyObjectError(ExceptionWithMessage): """ Thrown by ``ReadOnly`` to indicate an attempt to set a field. :IVariables: field_name : str name of the read-only field that could not be set message : str message to associated with the exception """ def ...
class ReadOnlyObjectError(ExceptionWithMessage):
""" Thrown by ``ReadOnly`` to indicate an attempt to set a field. :IVariables: field_name : str name of the read-only field that could not be set message : str message to associated with the exception """ def __init__(self, field_name, message): Exce...
all__ = ['ReadOnly', 'ReadOnlyObjectError'] # --------------------------------------------------------------------------- # Constants # --------------------------------------------------------------------------- # --------------------------------------------------------------------------- # Logging # ----------------...
63
64
99
9
54
brianrodri/google_appengine
lib/grizzled/grizzled/misc.py
Python
ReadOnlyObjectError
ReadOnlyObjectError
43
56
43
43
fb4ae288e66b98ad572f698457b0ac50e771fa6c
bigcode/the-stack
train
a7acc3ce4af1a1cfeb720ae3
train
function
def bitcount(num): """ Count the number of bits in a numeric (integer or long) value. This method is adapted from the Hamming Weight algorithm, described (among other places) at http://en.wikipedia.org/wiki/Hamming_weight Works for up to 64 bits. :Parameters: num : int The ...
def bitcount(num):
""" Count the number of bits in a numeric (integer or long) value. This method is adapted from the Hamming Weight algorithm, described (among other places) at http://en.wikipedia.org/wiki/Hamming_weight Works for up to 64 bits. :Parameters: num : int The numeric value ...
else: raise ReadOnlyObjectError( thing, 'Attempt to access field "{0}" of read-only {1} object'.format( thing, self.wrapped.__class__.__name__ ) ) # ----------------------------------------------------------------------...
79
79
265
5
73
brianrodri/google_appengine
lib/grizzled/grizzled/misc.py
Python
bitcount
bitcount
121
146
121
121
9db1ff01acda7f073de824fa2eae71ce776cfef1
bigcode/the-stack
train
0a14a28f6877a802b346bbe8
train
function
def path_add_by_anchor(anchor, path): path_new = get_anchor_plus_regex_path(anchor, path) if (not (path_new in sys.path)): sys.path.append(path_new)
def path_add_by_anchor(anchor, path):
path_new = get_anchor_plus_regex_path(anchor, path) if (not (path_new in sys.path)): sys.path.append(path_new)
import chdir_by_anchor chdir_by_anchor("environment.yaml", "src/.+") chdir_by_anchor("environment.yaml", "src\.+") """ path_new = get_anchor_plus_regex_path(anchor, path) os.chdir(path_new) def path_add_by_anchor(anchor, path):
64
64
40
9
55
zeuscronos/python-othertools
othertools/path.py
Python
path_add_by_anchor
path_add_by_anchor
49
52
49
49
45db62dd3486e8397b2afba25ec3846e17900c75
bigcode/the-stack
train
df3bd44de34311ce0b980355
train
function
def chdir_by_anchor(anchor, path): """ Changes the working directory to the directory that contains the anchor file plus the path specified as a regular expression. Parameters: anchor: file name which will be used as a reference to locate the root directory path: path to move to o...
def chdir_by_anchor(anchor, path):
""" Changes the working directory to the directory that contains the anchor file plus the path specified as a regular expression. Parameters: anchor: file name which will be used as a reference to locate the root directory path: path to move to on top of the root directory Us...
elem in path_elems: files = os.listdir(path_current) for file in files: if (bool(re.match(elem, file))): path_current = os.path.realpath(os.path.join(path_current, file)) break return path_current def chdir_by_anchor(anchor, path):
64
64
135
9
54
zeuscronos/python-othertools
othertools/path.py
Python
chdir_by_anchor
chdir_by_anchor
29
47
29
29
0644f80a5ebe8a0519c8507b246e83e14411d968
bigcode/the-stack
train
d29b4e64565942f5a3473b33
train
function
def get_anchor_plus_regex_path(anchor, path): path_elems = re.findall("[^\\\/]+", path) path_root = get_anchor_path(anchor) path_current = path_root for elem in path_elems: files = os.listdir(path_current) for file in files: if (bool(re.match(elem, file))): pa...
def get_anchor_plus_regex_path(anchor, path):
path_elems = re.findall("[^\\\/]+", path) path_root = get_anchor_path(anchor) path_current = path_root for elem in path_elems: files = os.listdir(path_current) for file in files: if (bool(re.match(elem, file))): path_current = os.path.realpath(os.path.join(pat...
return None if (os.path.exists(os.path.join(path, anchor))): return path else: prev = path path = os.path.realpath(os.path.join(path, "..")) return get_anchor_path(anchor, path, prev) def get_anchor_plus_regex_path(anchor, path):
64
64
98
10
54
zeuscronos/python-othertools
othertools/path.py
Python
get_anchor_plus_regex_path
get_anchor_plus_regex_path
15
26
15
15
6930c890e2f71cbe417a89e2f442133422831426
bigcode/the-stack
train
12436df72ab47c8ad8ff96ee
train
function
def get_anchor_path(anchor, path = os.getcwd(), prev = ""): if (path == prev): return None if (os.path.exists(os.path.join(path, anchor))): return path else: prev = path path = os.path.realpath(os.path.join(path, "..")) return get_anchor_path(anchor, path, prev)
def get_anchor_path(anchor, path = os.getcwd(), prev = ""):
if (path == prev): return None if (os.path.exists(os.path.join(path, anchor))): return path else: prev = path path = os.path.realpath(os.path.join(path, "..")) return get_anchor_path(anchor, path, prev)
import sys import os import re def get_anchor_path(anchor, path = os.getcwd(), prev = ""):
24
64
77
15
8
zeuscronos/python-othertools
othertools/path.py
Python
get_anchor_path
get_anchor_path
5
13
5
5
8a617bedc371ba21c133381bf2b20222321bccb8
bigcode/the-stack
train
8de9588bf6fda2f8f71e5629
train
function
def get_formatter(name, primary_key_map, output_plugin, full_change, table_pat): formatter_f = getattr(sys.modules[__name__], '%sFormatter' % name) return formatter_f(primary_key_map, output_plugin, full_change, table_pat)
def get_formatter(name, primary_key_map, output_plugin, full_change, table_pat):
formatter_f = getattr(sys.modules[__name__], '%sFormatter' % name) return formatter_f(primary_key_map, output_plugin, full_change, table_pat)
fmt_msg = '{},{},{}'.format(CSVFormatter.VERSION, CSVFormatter.TYPE, json.dumps(change._asdict())) fmt_msg = fmt_msg.encode() return Message(change=change, fmt_msg=fmt_msg) def get_formatter(name, primary_key_map, output_plugin, full_change, table_pat):
64
64
54
18
46
seated-tech/pg2kinesis
pg2kinesis/formatter.py
Python
get_formatter
get_formatter
189
191
189
189
c026236989e801de14bd9a87a44bd51b6f2e9768
bigcode/the-stack
train
59222929ed44a023c84270d8
train
class
class CSVFormatter(Formatter): VERSION = 0 def produce_formatted_message(self, change): fmt_msg = '{},{},{},{},{},{}'.format(CSVFormatter.VERSION, CSVFormatter.TYPE, *change) fmt_msg = fmt_msg.encode() return Message(change=change, fmt_msg=fmt...
class CSVFormatter(Formatter):
VERSION = 0 def produce_formatted_message(self, change): fmt_msg = '{},{},{},{},{},{}'.format(CSVFormatter.VERSION, CSVFormatter.TYPE, *change) fmt_msg = fmt_msg.encode() return Message(change=change, fmt_msg=fmt_msg)
.output_plugin == 'wal2json': pp_changes = self._preprocess_wal2json_change(change) return [self.produce_formatted_message(pp_change) for pp_change in pp_changes] def produce_formatted_message(self, change): raise NotImplementedError class CSVFormatter(Formatter):
64
64
68
6
57
seated-tech/pg2kinesis
pg2kinesis/formatter.py
Python
CSVFormatter
CSVFormatter
171
177
171
171
1cd3a086c5ba4199480c81ec29aa055134c06f99
bigcode/the-stack
train
3c0d077e21c747847222d912
train
class
class CSVPayloadFormatter(Formatter): VERSION = 0 def produce_formatted_message(self, change): fmt_msg = '{},{},{}'.format(CSVFormatter.VERSION, CSVFormatter.TYPE, json.dumps(change._asdict())) fmt_msg = fmt_msg.encode() return Message(change=change, f...
class CSVPayloadFormatter(Formatter):
VERSION = 0 def produce_formatted_message(self, change): fmt_msg = '{},{},{}'.format(CSVFormatter.VERSION, CSVFormatter.TYPE, json.dumps(change._asdict())) fmt_msg = fmt_msg.encode() return Message(change=change, fmt_msg=fmt_msg)
def produce_formatted_message(self, change): fmt_msg = '{},{},{},{},{},{}'.format(CSVFormatter.VERSION, CSVFormatter.TYPE, *change) fmt_msg = fmt_msg.encode() return Message(change=change, fmt_msg=fmt_msg) class CSVPayloadFormatter(Formatter):
64
64
70
7
57
seated-tech/pg2kinesis
pg2kinesis/formatter.py
Python
CSVPayloadFormatter
CSVPayloadFormatter
180
186
180
180
b58027751cd3eff4dcb6256447ca3460fb4e079f
bigcode/the-stack
train
8e99044c79eae7001cbb3fc7
train
class
class Formatter(object): VERSION = 0 TYPE = 'CDC' IGNORED_CHANGES = {'COMMIT'} def __init__(self, primary_key_map, output_plugin='test_decoding', full_change=False, table_pat=None): self._primary_key_patterns = {} self.output_plugin = output_plugin self.primary...
class Formatter(object):
VERSION = 0 TYPE = 'CDC' IGNORED_CHANGES = {'COMMIT'} def __init__(self, primary_key_map, output_plugin='test_decoding', full_change=False, table_pat=None): self._primary_key_patterns = {} self.output_plugin = output_plugin self.primary_key_map = primary_key_ma...
from __future__ import unicode_literals import json import re import sys import logging from collections import namedtuple # Tuples representing changes as pulled from database Change = namedtuple('Change', 'xid, table, operation, pkey') FullChange = namedtuple('FullChange', 'xid, change') FullChange.operation = pro...
167
256
1,180
4
162
seated-tech/pg2kinesis
pg2kinesis/formatter.py
Python
Formatter
Formatter
22
168
22
22
72afbf3ab7d02a5bb6d9465fe47b85f1aee10b50
bigcode/the-stack
train
0cd86c8bb07fb5b067d7737a
train
function
def handler(event, context): if IAM_KEY_ROTATOR_TABLE is None: logger.error('IAM_KEY_ROTATOR_TABLE is required. Current value: {}'.format(IAM_KEY_ROTATOR_TABLE)) elif MAIL_FROM is None: logger.error('MAIL_FROM is required. Current value: {}'.format(MAIL_FROM)) else: destroy_user_keys...
def handler(event, context):
if IAM_KEY_ROTATOR_TABLE is None: logger.error('IAM_KEY_ROTATOR_TABLE is required. Current value: {}'.format(IAM_KEY_ROTATOR_TABLE)) elif MAIL_FROM is None: logger.error('MAIL_FROM is required. Current value: {}'.format(MAIL_FROM)) else: destroy_user_keys(event['Records'])
back to the database'.format(accessKey)) else: logger.info('Skipping as it is not a delete event') def destroy_user_keys(records): with concurrent.futures.ThreadPoolExecutor() as executor: [executor.submit(destroy_user_key(rec)) for rec in records] def handler(event, context):
64
64
76
6
58
skildops/aws-iam-key-rotator
src/destructor.py
Python
handler
handler
124
130
124
124
4d8b1b6df06535742db3e06287bb1848ac8c9fc9
bigcode/the-stack
train
067604c562032f5e4bbdaba5
train
function
def destroy_user_key(rec): if rec['eventName'] == 'REMOVE': key = rec['dynamodb']['OldImage'] userName = key['user']['S'] userEmail = key['email']['S'] accessKey = key['ak']['S'] try: logger.info('Deleting access key {} assocaited with user {}'.format(accessKey, u...
def destroy_user_key(rec):
if rec['eventName'] == 'REMOVE': key = rec['dynamodb']['OldImage'] userName = key['user']['S'] userEmail = key['email']['S'] accessKey = key['ak']['S'] try: logger.info('Deleting access key {} assocaited with user {}'.format(accessKey, userName)) iam.d...
mailgun_mailer.send_email(email, userName, mailSubject, MAIL_FROM, mailBodyPlain, mailBodyHtml) else: logger.error('{}: Invalid mail client. Supported mail clients: AWS SES and Mailgun'.format(MAIL_CLIENT)) except (Exception, ClientError) as ce: logger.error('Failed to send m...
95
95
319
6
89
skildops/aws-iam-key-rotator
src/destructor.py
Python
destroy_user_key
destroy_user_key
80
118
80
80
3376216facd2032bfcb84c37984ccf75e04efccd
bigcode/the-stack
train
7ac597413a6ba41604896427
train
function
def send_email(email, userName, existingAccessKey): mailSubject = 'Old Access Key Pair Deleted' mailBodyPlain = 'Hey {},\nAn existing access key pair associated to your username has been deleted because it reached End-Of-Life.\n\nAccount: {} ({})\nAccess Key: {}\n\nThanks,\nYour Security Team'.format(userName, ...
def send_email(email, userName, existingAccessKey):
mailSubject = 'Old Access Key Pair Deleted' mailBodyPlain = 'Hey {},\nAn existing access key pair associated to your username has been deleted because it reached End-Of-Life.\n\nAccount: {} ({})\nAccess Key: {}\n\nThanks,\nYour Security Team'.format(userName, shared_functions.fetch_account_info()['id'], shared_...
to delete the old key, how long should it wait before the next try RETRY_AFTER_MINS = os.environ.get('RETRY_AFTER_MINS', 5) # Mail client to use for sending new key creation or existing key deletion mail MAIL_CLIENT = os.environ.get('MAIL_CLIENT', 'ses') # From address to be used while sending mail MAIL_FROM = os.en...
177
177
592
12
165
skildops/aws-iam-key-rotator
src/destructor.py
Python
send_email
send_email
30
78
30
30
53d52cc69fdf132d795fc9466d1af8d913482bbc
bigcode/the-stack
train
a4ff14e7b0e7471a6774d57f
train
function
def destroy_user_keys(records): with concurrent.futures.ThreadPoolExecutor() as executor: [executor.submit(destroy_user_key(rec)) for rec in records]
def destroy_user_keys(records):
with concurrent.futures.ThreadPoolExecutor() as executor: [executor.submit(destroy_user_key(rec)) for rec in records]
(int(key['delete_on']['N']) + (RETRY_AFTER_MINS * 60)) } } ) logger.info('Access key {} added back to the database'.format(accessKey)) else: logger.info('Skipping as it is not a delete event') def destroy_user_keys(records):
64
64
33
6
58
skildops/aws-iam-key-rotator
src/destructor.py
Python
destroy_user_keys
destroy_user_keys
120
122
120
120
7763891469e8515f7c6fb1dfefe66719ec0c0dab
bigcode/the-stack
train
02e3a50dc87ae388e30859d4
train
class
@base.ReleaseTracks(base.ReleaseTrack.ALPHA) class Create(base.CreateCommand): """Create per instance config for managed instance group. *{command}* creates per instance config for instance controlled by a Google Compute Engine managed instance group. An instance with a per instance config will preserve given ...
@base.ReleaseTracks(base.ReleaseTrack.ALPHA) class Create(base.CreateCommand):
"""Create per instance config for managed instance group. *{command}* creates per instance config for instance controlled by a Google Compute Engine managed instance group. An instance with a per instance config will preserve given name and any listed disks during instance recreation and deletion. Preserved ...
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. """Command for creating per instance config.""" ...
256
256
1,051
17
238
bshaffer/google-cloud-sdk
lib/surface/compute/instance_groups/managed/instance_configs/create.py
Python
Create
Create
36
157
36
37
b9206aa7607f93d839979f772cd32c6f6c9bc406
bigcode/the-stack
train
b08620efe04ad5568d5a68f7
train
class
class IscsiEntityChangeableProperties(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self): """ IscsiEntityChangeableProperties - a model defined in Swagger :param dict swaggerTypes: The...
class IscsiEntityChangeableProperties(object):
""" NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self): """ IscsiEntityChangeableProperties - a model defined in Swagger :param dict swaggerTypes: The key is attribute name ...
and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of NetApp, Inc. nor the names of its contributors may be used...
256
256
2,473
10
245
NetApp/santricity-webapi-pythonsdk
netapp/santricity/models/symbol/iscsi_entity_changeable_properties.py
Python
IscsiEntityChangeableProperties
IscsiEntityChangeableProperties
25
280
25
25
038c831663ae5aecf06f4f5b1be412e9fbe402c8
bigcode/the-stack
train
9f7bf4675ed84739c32c89ea
train
class
class kl_div(Atom): """:math:`x\log(x/y) - x + y` """ def __init__(self, x, y): super(kl_div, self).__init__(x, y) @Atom.numpy_numeric def numeric(self, values): x = values[0] y = values[1] #TODO return inf outside the domain return xlogy(x, x/y) - x + y ...
class kl_div(Atom):
""":math:`x\log(x/y) - x + y` """ def __init__(self, x, y): super(kl_div, self).__init__(x, y) @Atom.numpy_numeric def numeric(self, values): x = values[0] y = values[1] #TODO return inf outside the domain return xlogy(x, x/y) - x + y def shape_from_arg...
the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CVXPY. If not, see <http://www.gnu.or...
132
132
440
6
125
riadnassiffe/Simulator
src/tools/ecos/cvxpy/cvxpy/atoms/kl_div.py
Python
kl_div
kl_div
27
92
27
27
a334988d3fd36753a73d99a67baab8737a7514aa
bigcode/the-stack
train
04020efbcab10dc3ecedee91
train
class
class TestSaveClassificationd(unittest.TestCase): def test_saved_content(self): with tempfile.TemporaryDirectory() as tempdir: data = [ { "pred": torch.zeros(8), "image_meta_dict": {"filename_or_obj": ["testfile" + str(i) for i in range(8)]...
class TestSaveClassificationd(unittest.TestCase):
def test_saved_content(self): with tempfile.TemporaryDirectory() as tempdir: data = [ { "pred": torch.zeros(8), "image_meta_dict": {"filename_or_obj": ["testfile" + str(i) for i in range(8)]}, }, { ...
Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed...
166
166
556
9
156
myron/MONAI
tests/test_save_classificationd.py
Python
TestSaveClassificationd
TestSaveClassificationd
24
89
24
24
bb1212e4cf2d4e8612af0e0f5e7cef5a123c1676
bigcode/the-stack
train
fca94d6da523298a3d23b7c9
train
function
def test_stratified_simclr_dataset(test_png_path, test_jpg_path): filepaths = 10*[test_png_path, test_jpg_path] labels = 10*["png", "jpg"] batch_size = 5 ds = _build_simclr_dataset(filepaths, imshape=(32,32), num_channels=3, norm=255, augm...
def test_stratified_simclr_dataset(test_png_path, test_jpg_path):
filepaths = 10*[test_png_path, test_jpg_path] labels = 10*["png", "jpg"] batch_size = 5 ds = _build_simclr_dataset(filepaths, imshape=(32,32), num_channels=3, norm=255, augment={}, single_channel=False, batch_...
assert x.shape[0] == 2*batch_size assert (y.numpy() == np.array([1,-1,1,-1,1,-1,1,-1,1,-1])).all() def test_stratified_simclr_dataset(test_png_path, test_jpg_path):
63
64
210
17
46
mediocretech/patchwork
patchwork/tests/test_feature_simclr.py
Python
test_stratified_simclr_dataset
test_stratified_simclr_dataset
34
54
34
34
526a9d76c8228aabe256873b68a9a06b0195ec60
bigcode/the-stack
train
cd648e6db497445f7987d32d
train
function
def test_build_embedding_model(): model = _build_embedding_model(fcn, (32,32), 3, 17, 11) assert isinstance(model, tf.keras.Model) assert model.output_shape[-1] == 11 assert len(model.layers) == 8
def test_build_embedding_model():
model = _build_embedding_model(fcn, (32,32), 3, 17, 11) assert isinstance(model, tf.keras.Model) assert model.output_shape[-1] == 11 assert len(model.layers) == 8
pairs, the batch size # is doubled assert x.shape[0] == 2*batch_size assert (y.numpy() == np.array([1,-1,1,-1,1,-1,1,-1,1,-1])).all() def test_build_embedding_model():
63
64
61
6
57
mediocretech/patchwork
patchwork/tests/test_feature_simclr.py
Python
test_build_embedding_model
test_build_embedding_model
94
98
94
94
5d3192180dd88a8c3ba7886e60a062ee56d8034b
bigcode/the-stack
train
ea24424be689e577aab743c7
train
function
def test_build_simclr_training_step(): model = _build_embedding_model(fcn, (32,32), 3, 5, 7) opt = tf.keras.optimizers.SGD() step = _build_simclr_training_step(model, opt, 0.1) x = tf.zeros((4,32,32,3), dtype=tf.float32) y = np.array([1,-1,1,-1]).astype(np.int32) lossdict = step(x,y) ...
def test_build_simclr_training_step():
model = _build_embedding_model(fcn, (32,32), 3, 5, 7) opt = tf.keras.optimizers.SGD() step = _build_simclr_training_step(model, opt, 0.1) x = tf.zeros((4,32,32,3), dtype=tf.float32) y = np.array([1,-1,1,-1]).astype(np.int32) lossdict = step(x,y) assert isinstance(lossdict["loss"].n...
(): model = _build_embedding_model(fcn, (32,32), 3, 17, 11) assert isinstance(model, tf.keras.Model) assert model.output_shape[-1] == 11 assert len(model.layers) == 8 def test_build_simclr_training_step():
64
64
142
8
55
mediocretech/patchwork
patchwork/tests/test_feature_simclr.py
Python
test_build_simclr_training_step
test_build_simclr_training_step
101
112
101
101
6c8645d8c2c399d75b5078fb7a0b189fe620d8db
bigcode/the-stack
train
a5d2d82d30818ebcda484006
train
function
def test_simclr_dataset_with_dual_inputs(test_png_path): filepaths = [10*[test_png_path],10*[test_png_path]] batch_size = 5 augment = {"flip_left_right":True, "zoom_scale":0.3} ds = _build_simclr_dataset(filepaths, imshape=((32,32),(17,29)), num_channels=3, norm=255, ...
def test_simclr_dataset_with_dual_inputs(test_png_path):
filepaths = [10*[test_png_path],10*[test_png_path]] batch_size = 5 augment = {"flip_left_right":True, "zoom_scale":0.3} ds = _build_simclr_dataset(filepaths, imshape=((32,32),(17,29)), num_channels=3, norm=255, augment=augment, single_channel=F...
since we're using a stratified dataset- each element of a particular # batch should be from one stratification category (which in this # case is an identical image) assert (x[0] == x[2]).all() def test_simclr_dataset_with_dual_inputs(test_png_path):
64
65
218
13
51
mediocretech/patchwork
patchwork/tests/test_feature_simclr.py
Python
test_simclr_dataset_with_dual_inputs
test_simclr_dataset_with_dual_inputs
57
73
57
57
2c852929295bc38717942888bc85c227c91d562d
bigcode/the-stack
train
6e74122a1dab09c4c582cd32
train
function
def test_build_simclr_training_step_with_weight_decay(): model = _build_embedding_model(fcn, (32,32), 3, 5, 7) opt = tf.keras.optimizers.SGD() step = _build_simclr_training_step(model, opt, 0.1, weight_decay=1e-6) x = tf.zeros((4,32,32,3), dtype=tf.float32) ...
def test_build_simclr_training_step_with_weight_decay():
model = _build_embedding_model(fcn, (32,32), 3, 5, 7) opt = tf.keras.optimizers.SGD() step = _build_simclr_training_step(model, opt, 0.1, weight_decay=1e-6) x = tf.zeros((4,32,32,3), dtype=tf.float32) y = np.array([1,-1,1,-1]).astype(np.int32) lossdict...
,1,-1]).astype(np.int32) lossdict = step(x,y) assert isinstance(lossdict["loss"].numpy(), np.float32) # should include loss and average cosine similarity assert len(lossdict) == 2 def test_build_simclr_training_step_with_weight_decay():
64
64
153
11
52
mediocretech/patchwork
patchwork/tests/test_feature_simclr.py
Python
test_build_simclr_training_step_with_weight_decay
test_build_simclr_training_step_with_weight_decay
115
127
115
115
7f19e895017cf1796ec8a081ededca70609859fe
bigcode/the-stack
train
2171db219cb388cf53cb0a45
train
function
def test_simclr_dataset_with_custom_dataset(): rawdata = np.zeros((10,32,32,3)).astype(np.float32) ds = tf.data.Dataset.from_tensor_slices(rawdata) batch_size = 5 ds = _build_simclr_dataset(ds, imshape=(32,32), num_channels=3, norm=255, augment...
def test_simclr_dataset_with_custom_dataset():
rawdata = np.zeros((10,32,32,3)).astype(np.float32) ds = tf.data.Dataset.from_tensor_slices(rawdata) batch_size = 5 ds = _build_simclr_dataset(ds, imshape=(32,32), num_channels=3, norm=255, augment=True, single_channel=False, ...
) assert x1.shape == (2*batch_size, 17, 29, 3) assert (y.numpy() == np.array([1,-1,1,-1,1,-1,1,-1,1,-1])).all() def test_simclr_dataset_with_custom_dataset():
63
64
174
9
54
mediocretech/patchwork
patchwork/tests/test_feature_simclr.py
Python
test_simclr_dataset_with_custom_dataset
test_simclr_dataset_with_custom_dataset
77
92
77
77
2e4bf36ecd2052be6cd0ccaebd5c74ed9d08ce8a
bigcode/the-stack
train
5ec0da930d6983c613636172
train
function
def test_simclr_dataset(test_png_path): filepaths = 10*[test_png_path] batch_size = 5 ds = _build_simclr_dataset(filepaths, imshape=(32,32), num_channels=3, norm=255, augment=True, single_channel=False, batch_size=batc...
def test_simclr_dataset(test_png_path):
filepaths = 10*[test_png_path] batch_size = 5 ds = _build_simclr_dataset(filepaths, imshape=(32,32), num_channels=3, norm=255, augment=True, single_channel=False, batch_size=batch_size) assert isinstance(ds, t...
tf.keras.layers.Input((None, None, 3)) net = tf.keras.layers.Conv2D(5,1)(inpt) net = tf.keras.layers.MaxPool2D(10,10)(net) fcn = tf.keras.Model(inpt, net) def test_simclr_dataset(test_png_path):
64
64
153
9
55
mediocretech/patchwork
patchwork/tests/test_feature_simclr.py
Python
test_simclr_dataset
test_simclr_dataset
18
32
18
18
6158d87cb46e4a59711b9efdc8c31449c3fc27ba
bigcode/the-stack
train
175d665659937ab8020d2f7e
train
function
def _get_mlflow_install_step(dockerfile_context_dir, mlflow_home): """ Get docker build commands for installing MLflow given a Docker context dir and optional source directory """ if mlflow_home: mlflow_dir = _copy_project(src_path=mlflow_home, dst_path=dockerfile_context_dir) return...
def _get_mlflow_install_step(dockerfile_context_dir, mlflow_home):
""" Get docker build commands for installing MLflow given a Docker context dir and optional source directory """ if mlflow_home: mlflow_dir = _copy_project(src_path=mlflow_home, dst_path=dockerfile_context_dir) return ( "COPY {mlflow_dir} /opt/mlflow\n" "RUN p...
p /miniconda && rm ./miniconda.sh ENV PATH="/miniconda/bin:$PATH" ENV JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64 ENV GUNICORN_CMD_ARGS="--timeout 60 --workers=3 -k gevent" # Set up the program in the image WORKDIR /opt/mlflow {install_mlflow} {custom_setup_steps} {entrypoint} """ def _get_mlflow_install_step(dockerf...
108
108
361
17
91
BLACKBUCK-LABS/mlflow
mlflow/models/docker_utils.py
Python
_get_mlflow_install_step
_get_mlflow_install_step
47
77
47
47
5914ff53fc45b9c70cfc9334f20bd39dfabbf5e5
bigcode/the-stack
train
060edb01b84ec08b8f298422
train
function
def _build_image(image_name, entrypoint, mlflow_home=None, custom_setup_steps_hook=None): """ Build an MLflow Docker image that can be used to serve a The image is built locally and it requires Docker to run. :param image_name: Docker image name. :param entry_point: String containing ENTRYPOINT dir...
def _build_image(image_name, entrypoint, mlflow_home=None, custom_setup_steps_hook=None):
""" Build an MLflow Docker image that can be used to serve a The image is built locally and it requires Docker to run. :param image_name: Docker image name. :param entry_point: String containing ENTRYPOINT directive for docker image :param mlflow_home: (Optional) Path to a local copy of the MLf...
dependency:copy" " -Dartifact=org.mlflow:mlflow-scoring:{version}:jar" " -DoutputDirectory=/opt/java/jars\n" "RUN cp /opt/java/mlflow-scoring-{version}.pom /opt/java/pom.xml\n" "RUN cd /opt/java && mvn " "--batch-mode dependency:copy-dependencies -DoutputDire...
121
121
405
21
100
BLACKBUCK-LABS/mlflow
mlflow/models/docker_utils.py
Python
_build_image
_build_image
80
117
80
80
0e41617a756863e9d0cda026c106eb85893a04a1
bigcode/the-stack
train
573820401180e73ad9348d39
train
function
@responses.activate def test_stream_comments(): repository_args_with_start_date = { "repositories": ["organization/repository"], "page_size_for_large_streams": 100, "start_date": "2022-02-02T10:10:03Z", } stream = Comments(**repository_args_with_start_date) data = [ {"...
@responses.activate def test_stream_comments():
repository_args_with_start_date = { "repositories": ["organization/repository"], "page_size_for_large_streams": 100, "start_date": "2022-02-02T10:10:03Z", } stream = Comments(**repository_args_with_start_date) data = [ {"id": 1, "updated_at": "2022-02-02T10:10:02Z"}, ...
00:00:00Z", }, { "column_id": 23, "id": 232, "name": "card_232", "project_id": 2, "repository": "organization/repository", "updated_at": "2022-06-01T00:00:00Z", }, { "column_id": 32, "id": 322...
150
151
505
9
141
cnry/airbyte
airbyte-integrations/connectors/source-github/unit_tests/test_stream.py
Python
test_stream_comments
test_stream_comments
567
611
567
569
0379747b5f780482eba9745ecc1b931fd2072ec3
bigcode/the-stack
train
521144ef2dda3fd2cc78a2e4
train
function
@responses.activate @patch("time.sleep") def test_internal_server_error_retry(time_mock): args = {"authenticator": None, "repositories": ["test_repo"], "start_date": "start_date", "page_size_for_large_streams": 30} stream = PullRequestCommentReactions(**args) stream_slice = {"repository": "test_repo", "comm...
@responses.activate @patch("time.sleep") def test_internal_server_error_retry(time_mock):
args = {"authenticator": None, "repositories": ["test_repo"], "start_date": "start_date", "page_size_for_large_streams": 30} stream = PullRequestCommentReactions(**args) stream_slice = {"repository": "test_repo", "comment_id": "id"} time_mock.reset_mock() responses.add( "GET", "http...
, Users, ) from .utils import ProjectsResponsesAPI, read_full_refresh, read_incremental, urlbase DEFAULT_BACKOFF_DELAYS = [5, 10, 20, 40, 80] @responses.activate @patch("time.sleep") def test_internal_server_error_retry(time_mock):
64
64
193
19
45
cnry/airbyte
airbyte-integrations/connectors/source-github/unit_tests/test_stream.py
Python
test_internal_server_error_retry
test_internal_server_error_retry
47
65
47
49
53710b395930a0d0be92fc1a2511a0cf5c1cd0e7
bigcode/the-stack
train
a66b9120a55b5820fc6ee86e
train
function
@responses.activate def test_stream_project_cards(): repository_args_with_start_date = { "repositories": ["organization/repository"], "page_size_for_large_streams": 100, "start_date": "2022-03-01T00:00:00Z", } projects_stream = Projects(**repository_args_with_start_date) projec...
@responses.activate def test_stream_project_cards():
repository_args_with_start_date = { "repositories": ["organization/repository"], "page_size_for_large_streams": 100, "start_date": "2022-03-01T00:00:00Z", } projects_stream = Projects(**repository_args_with_start_date) project_columns_stream = ProjectColumns(projects_stream, **r...
] ProjectsResponsesAPI.register(data) records = read_incremental(stream, stream_state=stream_state) assert records == [ {"id": 24, "name": "column_24", "project_id": 2, "repository": "organization/repository", "updated_at": "2022-04-01T10:00:00Z"}, {"id": 41, "name": "column_41", "project...
223
223
745
10
213
cnry/airbyte
airbyte-integrations/connectors/source-github/unit_tests/test_stream.py
Python
test_stream_project_cards
test_stream_project_cards
474
564
474
476
955f2f12117d03e91f24f64790eb29c27523a5a3
bigcode/the-stack
train
e1761f71b31197b4a92a9afc
train
function
@responses.activate @patch("time.sleep") def test_retry_after(time_mock): stream = Organizations(organizations=["airbytehq"]) responses.add("GET", "https://api.github.com/orgs/airbytehq", json={"login": "airbytehq"}, headers={"Retry-After": "10"}) read_full_refresh(stream) assert time_mock.call_args[0][...
@responses.activate @patch("time.sleep") def test_retry_after(time_mock):
stream = Organizations(organizations=["airbytehq"]) responses.add("GET", "https://api.github.com/orgs/airbytehq", json={"login": "airbytehq"}, headers={"Retry-After": "10"}) read_full_refresh(stream) assert time_mock.call_args[0][0] == 10 assert len(responses.calls) == 1 assert responses.calls[0...
_repo"], "start_date": "start_date", "page_size_for_large_streams": 30} stream = PullRequestCommentReactions(**args) assert stream.backoff_time(response_mock) == expected_backoff_time @responses.activate @patch("time.sleep") def test_retry_after(time_mock):
64
64
125
17
46
cnry/airbyte
airbyte-integrations/connectors/source-github/unit_tests/test_stream.py
Python
test_retry_after
test_retry_after
83
91
83
85
ae5ae3249ff6a18253a5083f12eac50560ae98df
bigcode/the-stack
train
42df78776c422da242d3d6bb
train
function
@responses.activate def test_stream_commits_incremental_read(): repository_args_with_start_date = { "repositories": ["organization/repository"], "page_size_for_large_streams": 100, "start_date": "2022-02-02T10:10:03Z", } default_branches = {"organization/repository": "master"} ...
@responses.activate def test_stream_commits_incremental_read():
repository_args_with_start_date = { "repositories": ["organization/repository"], "page_size_for_large_streams": 100, "start_date": "2022-02-02T10:10:03Z", } default_branches = {"organization/repository": "master"} branches_to_pull = {"organization/repository": ["branch"]} s...
_page": str(page_size), "direction": "desc", "page": "2"}, strict_match=False)], ) stream_state = {} records = read_incremental(stream, stream_state) assert [r["id"] for r in records] == [2, 3, 4] assert stream_state == {"organization/repository": {"updated_at": "2022-02-02T10:10:08Z"}} record...
165
165
553
13
151
cnry/airbyte
airbyte-integrations/connectors/source-github/unit_tests/test_stream.py
Python
test_stream_commits_incremental_read
test_stream_commits_incremental_read
266
310
266
268
0a355bafe84c29b97d54f1dc0f8fcc6373dcf32b
bigcode/the-stack
train
b1cbab9c939432d2bea609e8
train
function
@pytest.mark.parametrize( ("http_status", "response_text", "expected_backoff_time"), [ (HTTPStatus.BAD_GATEWAY, "", 60), ], ) def test_backoff_time(http_status, response_text, expected_backoff_time): response_mock = MagicMock() response_mock.status_code = http_status response_mock.text =...
@pytest.mark.parametrize( ("http_status", "response_text", "expected_backoff_time"), [ (HTTPStatus.BAD_GATEWAY, "", 60), ], ) def test_backoff_time(http_status, response_text, expected_backoff_time):
response_mock = MagicMock() response_mock.status_code = http_status response_mock.text = response_text args = {"authenticator": None, "repositories": ["test_repo"], "start_date": "start_date", "page_size_for_large_streams": 30} stream = PullRequestCommentReactions(**args) assert stream.backoff_t...
assert sleep_delays == DEFAULT_BACKOFF_DELAYS @pytest.mark.parametrize( ("http_status", "response_text", "expected_backoff_time"), [ (HTTPStatus.BAD_GATEWAY, "", 60), ], ) def test_backoff_time(http_status, response_text, expected_backoff_time):
64
64
137
52
11
cnry/airbyte
airbyte-integrations/connectors/source-github/unit_tests/test_stream.py
Python
test_backoff_time
test_backoff_time
68
80
68
74
f3c1f66d3ec3a112506038a3ce218706ac9aa3c3
bigcode/the-stack
train
9a322b85e234194731f6e62c
train
function
@responses.activate def test_stream_projects_disabled(): repository_args_with_start_date = {"start_date": "start_date", "page_size_for_large_streams": 30, "repositories": ["test_repo"]} stream = Projects(**repository_args_with_start_date) responses.add( "GET", "https://api.github.com/repos...
@responses.activate def test_stream_projects_disabled():
repository_args_with_start_date = {"start_date": "start_date", "page_size_for_large_streams": 30, "repositories": ["test_repo"]} stream = Projects(**repository_args_with_start_date) responses.add( "GET", "https://api.github.com/repos/test_repo/projects", status=requests.codes.GONE, ...
/orgs/org1/repos?per_page=100&sort=updated&direction=desc" assert responses.calls[1].request.url == "https://api.github.com/orgs/org2/repos?per_page=100&sort=updated&direction=desc" @responses.activate def test_stream_projects_disabled():
64
64
161
10
54
cnry/airbyte
airbyte-integrations/connectors/source-github/unit_tests/test_stream.py
Python
test_stream_projects_disabled
test_stream_projects_disabled
184
199
184
186
f970d2a774bc6550068e03f67decf81f0ff07db6
bigcode/the-stack
train
9542cf209398a6150ed5a1ed
train
function
@responses.activate def test_stream_team_members_full_refresh(): organization_args = {"organizations": ["org1"]} repository_args = {"repositories": [], "page_size_for_large_streams": 100} responses.add("GET", "https://api.github.com/orgs/org1/teams", json=[{"slug": "team1"}, {"slug": "team2"}]) respons...
@responses.activate def test_stream_team_members_full_refresh():
organization_args = {"organizations": ["org1"]} repository_args = {"repositories": [], "page_size_for_large_streams": 100} responses.add("GET", "https://api.github.com/orgs/org1/teams", json=[{"slug": "team1"}, {"slug": "team2"}]) responses.add("GET", "https://api.github.com/orgs/org1/teams/team1/membe...
== {"organization/repository": {"pull_request_updated_at": "2022-01-04T00:00:00Z"}} assert len(responses.calls) == 6 assert urlbase(responses.calls[0].request.url) == url_pulls # make sure parent stream PullRequests used ascending sorting for both HTTP requests assert responses.calls[0].request.params...
135
135
452
12
123
cnry/airbyte
airbyte-integrations/connectors/source-github/unit_tests/test_stream.py
Python
test_stream_team_members_full_refresh
test_stream_team_members_full_refresh
759
787
759
760
04a383377e9307bab65327365df33c442b89db70
bigcode/the-stack
train
41cfaab12abcd14e02a329ff
train
function
@responses.activate def test_stream_pull_requests_incremental_read(): page_size = 2 repository_args_with_start_date = { "repositories": ["organization/repository"], "page_size_for_large_streams": page_size, "start_date": "2022-02-02T10:10:03Z", } stream = PullRequests(**reposit...
@responses.activate def test_stream_pull_requests_incremental_read():
page_size = 2 repository_args_with_start_date = { "repositories": ["organization/repository"], "page_size_for_large_streams": page_size, "start_date": "2022-02-02T10:10:03Z", } stream = PullRequests(**repository_args_with_start_date) data = [ {"id": 1, "updated_at":...
.calls[1].request.url == "https://api.github.com/orgs/org2/repos?per_page=100&sort=updated&direction=desc" @responses.activate def test_stream_projects_disabled(): repository_args_with_start_date = {"start_date": "start_date", "page_size_for_large_streams": 30, "repositories": ["test_repo"]} stream = Projec...
206
206
687
13
193
cnry/airbyte
airbyte-integrations/connectors/source-github/unit_tests/test_stream.py
Python
test_stream_pull_requests_incremental_read
test_stream_pull_requests_incremental_read
202
263
202
204
65787c9169c3a0a4ce9dd8a5a576f19e4df820ef
bigcode/the-stack
train
bacaf18a4042bbba148c8468
train
function
@responses.activate def test_stream_pull_request_commits(): repository_args = { "repositories": ["organization/repository"], "page_size_for_large_streams": 100, } repository_args_with_start_date = {**repository_args, "start_date": "2022-02-02T10:10:02Z"} stream = PullRequestCommits(Pul...
@responses.activate def test_stream_pull_request_commits():
repository_args = { "repositories": ["organization/repository"], "page_size_for_large_streams": 100, } repository_args_with_start_date = {**repository_args, "start_date": "2022-02-02T10:10:02Z"} stream = PullRequestCommits(PullRequests(**repository_args_with_start_date), **repository_ar...
-02T10:10:02Z", "sha": "master"}, strict_match=False)], ) stream_state = {"organization/repository": {"created_at": "2022-02-02T10:10:02Z"}} records = read_incremental(stream, stream_state) assert [r["sha"] for r in records] == [2] assert stream_state == {"organization/repository": {"master": {"cre...
123
123
411
12
111
cnry/airbyte
airbyte-integrations/connectors/source-github/unit_tests/test_stream.py
Python
test_stream_pull_request_commits
test_stream_pull_request_commits
343
382
343
345
bcb02728d52c443ed0fd69fd58284832cba370c5
bigcode/the-stack
train
def560b1ae098a87a3e0e304
train
function
@responses.activate def test_stream_reviews_incremental_read(): url_pulls = "https://api.github.com/repos/organization/repository/pulls" repository_args_with_start_date = { "start_date": "2000-01-01T00:00:00Z", "page_size_for_large_streams": 30, "repositories": ["organization/repositor...
@responses.activate def test_stream_reviews_incremental_read():
url_pulls = "https://api.github.com/repos/organization/repository/pulls" repository_args_with_start_date = { "start_date": "2000-01-01T00:00:00Z", "page_size_for_large_streams": 30, "repositories": ["organization/repository"], } stream = Reviews(parent=PullRequests(**repository_...
(Collaborators, "https://api.github.com/repos/organization/repository/collaborators"), (Branches, "https://api.github.com/repos/organization/repository/branches"), ]: stream = cls(**repository_args) responses.add("GET", url, json=get_json_response(stream.cursor_field)) record...
255
256
954
12
243
cnry/airbyte
airbyte-integrations/connectors/source-github/unit_tests/test_stream.py
Python
test_stream_reviews_incremental_read
test_stream_reviews_incremental_read
675
756
675
677
89326bbe24c48342f01ac4be5fc637cfd9a965d7
bigcode/the-stack
train
f0a4bbefdbe47a26b2e99ff4
train
function
@responses.activate def test_stream_commits_state_upgrade(): repository_args_with_start_date = { "repositories": ["organization/repository"], "page_size_for_large_streams": 100, "start_date": "2022-02-02T10:10:02Z", } default_branches = {"organization/repository": "master"} bra...
@responses.activate def test_stream_commits_state_upgrade():
repository_args_with_start_date = { "repositories": ["organization/repository"], "page_size_for_large_streams": 100, "start_date": "2022-02-02T10:10:02Z", } default_branches = {"organization/repository": "master"} branches_to_pull = {"organization/repository": ["master"]} s...
/repository": {"branch": {"created_at": "2022-02-02T10:10:06Z"}}} records = read_incremental(stream, stream_state) assert [r["sha"] for r in records] == [4, 5] assert stream_state == {"organization/repository": {"branch": {"created_at": "2022-02-02T10:10:10Z"}}} @responses.activate def test_stream_commits_s...
101
101
339
12
89
cnry/airbyte
airbyte-integrations/connectors/source-github/unit_tests/test_stream.py
Python
test_stream_commits_state_upgrade
test_stream_commits_state_upgrade
313
340
313
315
febfcc18401fcfe7ae03d4a14c61e00a6c8aab8f
bigcode/the-stack
train
6df0a8451066362b2329e78b
train
function
@responses.activate def test_stream_teams_read(): organization_args = {"organizations": ["org1", "org2"]} stream = Teams(**organization_args) responses.add("GET", "https://api.github.com/orgs/org1/teams", json=[{"id": 1}, {"id": 2}]) responses.add("GET", "https://api.github.com/orgs/org2/teams", json=[{...
@responses.activate def test_stream_teams_read():
organization_args = {"organizations": ["org1", "org2"]} stream = Teams(**organization_args) responses.add("GET", "https://api.github.com/orgs/org1/teams", json=[{"id": 1}, {"id": 2}]) responses.add("GET", "https://api.github.com/orgs/org2/teams", json=[{"id": 3}]) records = read_full_refresh(stream)...
": 1}) responses.add("GET", "https://api.github.com/orgs/org2", json={"id": 2}) records = read_full_refresh(stream) assert records == [{"id": 1}, {"id": 2}] @responses.activate def test_stream_teams_read():
63
64
215
11
52
cnry/airbyte
airbyte-integrations/connectors/source-github/unit_tests/test_stream.py
Python
test_stream_teams_read
test_stream_teams_read
121
131
121
122
9dfa147ac889530372d84505bcf3d7f2c70cbd12
bigcode/the-stack
train
62563f51e737a522a230b442
train
function
@responses.activate def test_stream_project_columns(): repository_args_with_start_date = { "repositories": ["organization/repository"], "page_size_for_large_streams": 100, "start_date": "2022-02-01T00:00:00Z", } data = [ { "updated_at": "2022-01-01T10:00:00Z", ...
@responses.activate def test_stream_project_columns():
repository_args_with_start_date = { "repositories": ["organization/repository"], "page_size_for_large_streams": 100, "start_date": "2022-02-01T00:00:00Z", } data = [ { "updated_at": "2022-01-01T10:00:00Z", }, { "updated_at": "2022-03-0...
-02T10:10:04Z", "number": 2}, {"id": 3, "updated_at": "2022-02-02T10:10:06Z", "number": 3}, ], ) responses.add( "GET", "https://api.github.com/repos/organization/repository/pulls/2/commits", json=[{"sha": 1}, {"sha": 2}], ) responses.add( "GET", ...
255
256
981
10
245
cnry/airbyte
airbyte-integrations/connectors/source-github/unit_tests/test_stream.py
Python
test_stream_project_columns
test_stream_project_columns
385
471
385
387
09a875c12b4b780ce791e8945de0d40e2dc1c42f
bigcode/the-stack
train
362e92b942b92f5e919e3ca8
train
function
@responses.activate def test_stream_users_read(): organization_args = {"organizations": ["org1", "org2"]} stream = Users(**organization_args) responses.add("GET", "https://api.github.com/orgs/org1/members", json=[{"id": 1}, {"id": 2}]) responses.add("GET", "https://api.github.com/orgs/org2/members", jso...
@responses.activate def test_stream_users_read():
organization_args = {"organizations": ["org1", "org2"]} stream = Users(**organization_args) responses.add("GET", "https://api.github.com/orgs/org1/members", json=[{"id": 1}, {"id": 2}]) responses.add("GET", "https://api.github.com/orgs/org2/members", json=[{"id": 3}]) records = read_full_refresh(str...
responses.calls[0].request.url == "https://api.github.com/orgs/org1/teams?per_page=100" assert responses.calls[1].request.url == "https://api.github.com/orgs/org2/teams?per_page=100" @responses.activate def test_stream_users_read():
64
64
214
10
54
cnry/airbyte
airbyte-integrations/connectors/source-github/unit_tests/test_stream.py
Python
test_stream_users_read
test_stream_users_read
134
144
134
135
330e2d4310e9af2b16bafdf401ba333f6463a05e
bigcode/the-stack
train