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
e98fae5f051b845b933d577a
train
function
@given(u'输入 T = "{string_t}"') def step_impl(step, string_t): step.string_t = (string_t)
@given(u'输入 T = "{string_t}"') def step_impl(step, string_t):
step.string_t = (string_t)
given, when, then, step from pb115 import Solution @given(u'输入 S = "{string_s}"') def step_impl(step, string_s): step.string_s = (string_s) @given(u'输入 T = "{string_t}"') def step_impl(step, string_t):
64
64
29
20
44
biztudio/beetcode
problems/115/features/steps/step_pb115.py
Python
step_impl
step_impl
8
10
8
9
39d70287a6a1caec9a332001db1f0021123a6fff
bigcode/the-stack
train
5b5482f3e4847295f2d94aa7
train
function
@when(u'计算一个字符串的子序列') def step_impl(step): calKit = Solution() step.calculated_result = calKit.numDistinct(step.string_s, step.string_t)
@when(u'计算一个字符串的子序列') def step_impl(step):
calKit = Solution() step.calculated_result = calKit.numDistinct(step.string_s, step.string_t)
def step_impl(step, string_s): step.string_s = (string_s) @given(u'输入 T = "{string_t}"') def step_impl(step, string_t): step.string_t = (string_t) @when(u'计算一个字符串的子序列') def step_impl(step):
64
64
44
18
46
biztudio/beetcode
problems/115/features/steps/step_pb115.py
Python
step_impl
step_impl
12
15
12
13
f1893703a462452f55370ca25bba44d39c355b36
bigcode/the-stack
train
6f119ca1aa1506c7a673a199
train
function
@then(u'得到结果 {number:d}') def step_impl(step, number): assert step.calculated_result == number
@then(u'得到结果 {number:d}') def step_impl(step, number):
assert step.calculated_result == number
string_t) @when(u'计算一个字符串的子序列') def step_impl(step): calKit = Solution() step.calculated_result = calKit.numDistinct(step.string_s, step.string_t) @then(u'得到结果 {number:d}') def step_impl(step, number):
63
64
26
17
46
biztudio/beetcode
problems/115/features/steps/step_pb115.py
Python
step_impl
step_impl
17
19
17
18
7e5b71092fbbfe2b633e04cf28802f64d41b5253
bigcode/the-stack
train
a5dbab26184ef01d0984a6f6
train
function
@given(u'输入 S = "{string_s}"') def step_impl(step, string_s): step.string_s = (string_s)
@given(u'输入 S = "{string_s}"') def step_impl(step, string_s):
step.string_s = (string_s)
from behave import given, when, then, step from pb115 import Solution @given(u'输入 S = "{string_s}"') def step_impl(step, string_s):
38
64
29
20
17
biztudio/beetcode
problems/115/features/steps/step_pb115.py
Python
step_impl
step_impl
4
6
4
5
77f6451dd29195c9dcb5d25175889ed6a191d5b9
bigcode/the-stack
train
d3613908debcb8d60f1aa0b1
train
class
class TestArchiver(TestCase): def setUp(self): self.conn = psycopg2.connect(settings.DATABASE) with self.conn.cursor() as cur: cur.execute( """ CREATE TABLE events( id serial PRIMARY KEY NOT NULL, sender_id character...
class TestArchiver(TestCase):
def setUp(self): self.conn = psycopg2.connect(settings.DATABASE) with self.conn.cursor() as cur: cur.execute( """ CREATE TABLE events( id serial PRIMARY KEY NOT NULL, sender_id character varying(255) NOT NULL, ...
from datetime import date, datetime, timedelta, timezone from unittest import TestCase, mock import boto3 import psycopg2 from moto import mock_s3 from archiver import settings from archiver.delete import delete_day, delete_events class TestArchiver(TestCase):
60
210
702
7
52
praekeltfoundation/rasa-postgres-archiver
archiver/test_delete.py
Python
TestArchiver
TestArchiver
12
100
12
12
cb46ed0ef0c4995ad56f5f9d2de52dd9e00463c4
bigcode/the-stack
train
35d72f26686cab7a159e4e83
train
class
class Integrator(object): def __init__(self, image, geometry, angles, radii, intensities): ''' Constructor :param image: 2-d numpy array image array :param geometry: Geometry instance object that encapsulates geometry information about current ellipse ...
class Integrator(object):
def __init__(self, image, geometry, angles, radii, intensities): ''' Constructor :param image: 2-d numpy array image array :param geometry: Geometry instance object that encapsulates geometry information about current ellipse :param angles: list ...
from __future__ import division import math # integration modes NEAREST_NEIGHBOR = 'nearest_neighbor' BI_LINEAR = 'bi-linear' MEAN = 'mean' MEDIAN = 'median' class Integrator(object):
48
129
430
5
43
ibusko/isophote
ellipse/integrator.py
Python
Integrator
Integrator
12
78
12
13
00f38ff2e75ec0a5b74607ecfce696431bf6291e
bigcode/the-stack
train
6bc7de1c3bd2fb51e00149df
train
class
class BiLinearIntegrator(Integrator): def integrate(self, radius, phi): self._r = radius # Get image coordinates of (radius, phi) pixel x_ = radius * math.cos(phi + self._geometry.pa) + self._geometry.x0 y_ = radius * math.sin(phi + self._geometry.pa) + self._geometry.y0 i...
class BiLinearIntegrator(Integrator):
def integrate(self, radius, phi): self._r = radius # Get image coordinates of (radius, phi) pixel x_ = radius * math.cos(phi + self._geometry.pa) + self._geometry.x0 y_ = radius * math.sin(phi + self._geometry.pa) + self._geometry.y0 i = int(x_) j = int(y_) ...
def integrate(self, radius, phi): self._r = radius # Get image coordinates of (radius, phi) pixel i = int(radius * math.cos(phi + self._geometry.pa) + self._geometry.x0) j = int(radius * math.sin(phi + self._geometry.pa) + self._geometry.y0) # ignore data point if outside ima...
200
200
669
7
192
ibusko/isophote
ellipse/integrator.py
Python
BiLinearIntegrator
BiLinearIntegrator
113
178
113
114
35123278cc850450f2e239f71a4dd3dcccd73522
bigcode/the-stack
train
a1dc4d6f38ee85d240fde170
train
class
class MedianIntegrator(AreaIntegrator): def initialize_accumulator(self): accumulator = [] self._npix = 0 return accumulator def accumulate(self, pixel_value, accumulator): accumulator.append(pixel_value) self._npix += 1 return accumulator, self._npix def c...
class MedianIntegrator(AreaIntegrator):
def initialize_accumulator(self): accumulator = [] self._npix = 0 return accumulator def accumulate(self, pixel_value, accumulator): accumulator.append(pixel_value) self._npix += 1 return accumulator, self._npix def compute_sample_value(self, accumulator): ...
return accumulator def accumulate(self, pixel_value, accumulator): accumulator += pixel_value self._npix += 1 return accumulator, self._npix def compute_sample_value(self, accumulator): return accumulator / self._npix class MedianIntegrator(AreaIntegrator):
64
64
89
7
56
ibusko/isophote
ellipse/integrator.py
Python
MedianIntegrator
MedianIntegrator
296
310
296
297
b208a5361d8ce769c93d004f8140ce8dd19e9387
bigcode/the-stack
train
8eff92742ba057dd8bd0e954
train
class
class NearestNeighborIntegrator(Integrator): def integrate(self, radius, phi): self._r = radius # Get image coordinates of (radius, phi) pixel i = int(radius * math.cos(phi + self._geometry.pa) + self._geometry.x0) j = int(radius * math.sin(phi + self._geometry.pa) + self._geometr...
class NearestNeighborIntegrator(Integrator):
def integrate(self, radius, phi): self._r = radius # Get image coordinates of (radius, phi) pixel i = int(radius * math.cos(phi + self._geometry.pa) + self._geometry.x0) j = int(radius * math.sin(phi + self._geometry.pa) + self._geometry.y0) # ignore data point if outside ...
self._radii.append(radius) self._intensities.append(sample) def get_polar_angle_step(self): raise NotImplementedError def get_sector_area(self): raise NotImplementedError def is_area(self): raise NotImplementedError class NearestNeighborIntegrator(Integrator):
64
64
186
8
55
ibusko/isophote
ellipse/integrator.py
Python
NearestNeighborIntegrator
NearestNeighborIntegrator
81
107
81
82
70314926c33a23419eb3375d477a5780c2bb7897
bigcode/the-stack
train
059430d378398d020d2a94cf
train
class
class MeanIntegrator(AreaIntegrator): def initialize_accumulator(self): accumulator = 0. self._npix = 0 return accumulator def accumulate(self, pixel_value, accumulator): accumulator += pixel_value self._npix += 1 return accumulator, self._npix def compute_...
class MeanIntegrator(AreaIntegrator):
def initialize_accumulator(self): accumulator = 0. self._npix = 0 return accumulator def accumulate(self, pixel_value, accumulator): accumulator += pixel_value self._npix += 1 return accumulator, self._npix def compute_sample_value(self, accumulator): ...
sector_area def is_area(self): return True def initialize_accumulator(self): raise NotImplementedError def accumulate(self, pixel_value, accumulator): raise NotImplementedError def compute_sample_value(self, accumulator): raise NotImplementedError class MeanIntegrator...
64
64
85
7
56
ibusko/isophote
ellipse/integrator.py
Python
MeanIntegrator
MeanIntegrator
280
293
280
281
99f1a96c53132c335516b4cb33930fd712522b1f
bigcode/the-stack
train
e55df046459ec3cff434bc5f
train
class
class AreaIntegrator(Integrator): def __init__(self, image, geometry, angles, radii, intensities): super(AreaIntegrator, self).__init__(image, geometry, angles, radii, intensities) # build auxiliary bi-linear integrator to be used when # sector areas contain a too small number of valid pi...
class AreaIntegrator(Integrator):
def __init__(self, image, geometry, angles, radii, intensities): super(AreaIntegrator, self).__init__(image, geometry, angles, radii, intensities) # build auxiliary bi-linear integrator to be used when # sector areas contain a too small number of valid pixels. self._bi_linear_integ...
1] # z3 = image[j+1][i] # z4 = image[j+1][i+1] # # sum = 0. # a1 = z2 - z1 # a2 = z4 - z3 # a3 = 1./ NCELL # correction = 0.5 + a3 / 2. # for j in range(0, NCELL): # y = j * a3 + fy - correction # for i in range(0, NCELL): ...
256
256
904
6
249
ibusko/isophote
ellipse/integrator.py
Python
AreaIntegrator
AreaIntegrator
181
277
181
182
970dd60ec16ee188da1f58c88f2db3c56b27718f
bigcode/the-stack
train
f65d0aa238a608158ac3d736
train
class
class TcpWriter(object): """Write TCP file""" def __init__(self, filename, mode): """Initialise TCP file""" logging.info("Initialising new TcpWriter, file: %s, mode: %s" % (filename, mode)) # Confirm if path exists, create directories if needed if not os.path.isdir(os.p...
class TcpWriter(object):
"""Write TCP file""" def __init__(self, filename, mode): """Initialise TCP file""" logging.info("Initialising new TcpWriter, file: %s, mode: %s" % (filename, mode)) # Confirm if path exists, create directories if needed if not os.path.isdir(os.path.split(filename)[0]): ...
# TileCutter - .tcp file reading/writing functions import logging, json, os, pickle, traceback import config, project config = config.Config() class TcpWriter(object):
39
154
516
5
34
An-dz/tilecutter
tcp.py
Python
TcpWriter
TcpWriter
8
70
8
8
7c0b9c28ad398e980435d9fe7d4c96c51204f493
bigcode/the-stack
train
84f8059d849a79bc8fd9b326
train
class
class TcpReader(object): """The main application, pre-window launch stuff should go here""" def __init__(self, filename): """Get filename for other function calls""" logging.info("Initialising new TcpReader, file: %s" % filename) self.filename = filename def load(self, para...
class TcpReader(object):
"""The main application, pre-window launch stuff should go here""" def __init__(self, filename): """Get filename for other function calls""" logging.info("Initialising new TcpReader, file: %s" % filename) self.filename = filename def load(self, params): """Load obje...
} try: output_string = json.dumps(saveobj, ensure_ascii=False, sort_keys=True, indent=4) except Exception: logging.error("Error dumping json for saveobj") logging.error(traceback.format_exc()) # Any problems this h...
256
256
1,045
5
250
An-dz/tilecutter
tcp.py
Python
TcpReader
TcpReader
73
191
73
73
9f6998bed1a38305e0e71dfe757084cfed62dd33
bigcode/the-stack
train
32f6853d3e74209688f6271f
train
class
class displayParagraph(Famcy.FamcyBlock): """ Represents the block to display paragraph. """ def __init__(self): self.value = displayParagraph.generate_template_content() super(displayParagraph, self).__init__() self.init_block() @classmethod def generate_template_c...
class displayParagraph(Famcy.FamcyBlock):
""" Represents the block to display paragraph. """ def __init__(self): self.value = displayParagraph.generate_template_content() super(displayParagraph, self).__init__() self.init_block() @classmethod def generate_template_content(cls): return { ...
import markdown import Famcy import json class displayParagraph(Famcy.FamcyBlock):
21
121
405
11
9
nexuni/Famcy
Famcy/_items_/display/displayParagraph/displayParagraph.py
Python
displayParagraph
displayParagraph
5
51
5
5
f66d5639a81d9bda86c9f8667482c4beb0bace29
bigcode/the-stack
train
73c84259e6f011d3a242721c
train
function
def set_av_tags(s3_client, s3_object, scan_result, scan_signature, timestamp): curr_tags = s3_client.get_object_tagging( Bucket=s3_object.bucket_name, Key=s3_object.key )["TagSet"] new_tags = copy.copy(curr_tags) for tag in curr_tags: if tag["Key"] in [ AV_SIGNATURE_METADATA,...
def set_av_tags(s3_client, s3_object, scan_result, scan_signature, timestamp):
curr_tags = s3_client.get_object_tagging( Bucket=s3_object.bucket_name, Key=s3_object.key )["TagSet"] new_tags = copy.copy(curr_tags) for tag in curr_tags: if tag["Key"] in [ AV_SIGNATURE_METADATA, AV_STATUS_METADATA, AV_TIMESTAMP_METADATA, ]: ...
3_object.bucket_name, "Key": s3_object.key}, ExtraArgs={ "ContentType": content_type, "Metadata": metadata, "MetadataDirective": "REPLACE", }, ) def set_av_tags(s3_client, s3_object, scan_result, scan_signature, timestamp):
64
64
184
20
44
snehal-wadhwani/bucket-antivirus-function
scan.py
Python
set_av_tags
set_av_tags
133
150
133
133
af8ed3df039730a3b66867389dc4ab0716631e4a
bigcode/the-stack
train
e67eefe0365254d35981435a
train
function
def verify_s3_object_version(s3, s3_object): # validate that we only process the original version of a file, if asked to do so # security check to disallow processing of a new (possibly infected) object version # while a clean initial version is getting processed # downstream services may consume latest...
def verify_s3_object_version(s3, s3_object): # validate that we only process the original version of a file, if asked to do so # security check to disallow processing of a new (possibly infected) object version # while a clean initial version is getting processed # downstream services may consume latest...
bucket_versioning = s3.BucketVersioning(s3_object.bucket_name) if bucket_versioning.status == "Enabled": bucket = s3.Bucket(s3_object.bucket_name) versions = list(bucket.object_versions.filter(Prefix=s3_object.key)) if len(versions) > 1: raise Exception( "Dete...
def verify_s3_object_version(s3, s3_object): # validate that we only process the original version of a file, if asked to do so # security check to disallow processing of a new (possibly infected) object version # while a clean initial version is getting processed # downstream services may consume latest...
79
66
223
79
0
snehal-wadhwani/bucket-antivirus-function
scan.py
Python
verify_s3_object_version
verify_s3_object_version
80
98
80
84
9bad27b5e55e3101be90368b7c8d1aa882862507
bigcode/the-stack
train
2a39fa7b2b689f3bb777daee
train
function
def sns_start_scan(sns_client, s3_object, scan_start_sns_arn, timestamp): message = { "bucket": s3_object.bucket_name, "key": s3_object.key, "version": s3_object.version_id, AV_SCAN_START_METADATA: True, AV_TIMESTAMP_METADATA: timestamp, } sns_client.publish( ...
def sns_start_scan(sns_client, s3_object, scan_start_sns_arn, timestamp):
message = { "bucket": s3_object.bucket_name, "key": s3_object.key, "version": s3_object.version_id, AV_SCAN_START_METADATA: True, AV_TIMESTAMP_METADATA: timestamp, } sns_client.publish( TargetArn=scan_start_sns_arn, Message=json.dumps({"default": json....
AV_TIMESTAMP_METADATA, "Value": timestamp}) s3_client.put_object_tagging( Bucket=s3_object.bucket_name, Key=s3_object.key, Tagging={"TagSet": new_tags} ) def sns_start_scan(sns_client, s3_object, scan_start_sns_arn, timestamp):
64
64
107
21
43
snehal-wadhwani/bucket-antivirus-function
scan.py
Python
sns_start_scan
sns_start_scan
153
165
153
153
0268325393922101a77967ce13cf0a330b879c84
bigcode/the-stack
train
8bc07c81921d4c592e7744ac
train
function
def sns_scan_results( sns_client, s3_object, sns_arn, scan_result, scan_signature, timestamp ): # Don't publish if scan_result is CLEAN and CLEAN results should not be published if scan_result == AV_STATUS_CLEAN and not str_to_bool(AV_STATUS_SNS_PUBLISH_CLEAN): return # Don't publish if scan_res...
def sns_scan_results( sns_client, s3_object, sns_arn, scan_result, scan_signature, timestamp ): # Don't publish if scan_result is CLEAN and CLEAN results should not be published
if scan_result == AV_STATUS_CLEAN and not str_to_bool(AV_STATUS_SNS_PUBLISH_CLEAN): return # Don't publish if scan_result is INFECTED and INFECTED results should not be published if scan_result == AV_STATUS_INFECTED and not str_to_bool( AV_STATUS_SNS_PUBLISH_INFECTED ): return ...
sns_client.publish( TargetArn=scan_start_sns_arn, Message=json.dumps({"default": json.dumps(message)}), MessageStructure="json", ) def sns_scan_results( sns_client, s3_object, sns_arn, scan_result, scan_signature, timestamp ): # Don't publish if scan_result is CLEAN and CLEAN res...
79
79
264
43
36
snehal-wadhwani/bucket-antivirus-function
scan.py
Python
sns_scan_results
sns_scan_results
168
198
168
171
047742b40f62077a9881598c16201a9e2ac70341
bigcode/the-stack
train
deb2f920df335de99508498d
train
function
def lambda_handler(event, context): s3 = boto3.resource("s3") s3_client = boto3.client("s3") sns_client = boto3.client("sns") # Get some environment variables ENV = os.getenv("ENV", "") EVENT_SOURCE = os.getenv("EVENT_SOURCE", "S3") start_time = get_timestamp() print("Script starting a...
def lambda_handler(event, context):
s3 = boto3.resource("s3") s3_client = boto3.client("s3") sns_client = boto3.client("sns") # Get some environment variables ENV = os.getenv("ENV", "") EVENT_SOURCE = os.getenv("EVENT_SOURCE", "S3") start_time = get_timestamp() print("Script starting at %s\n" % (start_time)) s3_objec...
INFECTED and INFECTED results should not be published if scan_result == AV_STATUS_INFECTED and not str_to_bool( AV_STATUS_SNS_PUBLISH_INFECTED ): return message = { "bucket": s3_object.bucket_name, "key": s3_object.key, "version": s3_object.version_id, AV_SIG...
193
193
644
7
186
snehal-wadhwani/bucket-antivirus-function
scan.py
Python
lambda_handler
lambda_handler
201
270
201
201
60bb7a13f31c2974cd638d5e576e9a24dd18114f
bigcode/the-stack
train
664af4caece5a72aa3ff6599
train
function
def str_to_bool(s): return bool(strtobool(str(s)))
def str_to_bool(s):
return bool(strtobool(str(s)))
pass if str_to_bool(AV_DELETE_INFECTED_FILES) and scan_result == AV_STATUS_INFECTED: delete_s3_object(s3_object) stop_scan_time = get_timestamp() print("Script finished at %s\n" % stop_scan_time) def str_to_bool(s):
64
64
16
6
58
snehal-wadhwani/bucket-antivirus-function
scan.py
Python
str_to_bool
str_to_bool
273
274
273
273
5fac691c66e81f8b079c993239bfd6a54a783c14
bigcode/the-stack
train
ecaf2c35459af48440609801
train
function
def event_object(event, event_source="s3"): # SNS events are slightly different if event_source.upper() == "SNS": event = json.loads(event["Records"][0]["Sns"]["Message"]) # Break down the record records = event["Records"] if len(records) == 0: raise Exception("No records found in ...
def event_object(event, event_source="s3"): # SNS events are slightly different
if event_source.upper() == "SNS": event = json.loads(event["Records"][0]["Sns"]["Message"]) # Break down the record records = event["Records"] if len(records) == 0: raise Exception("No records found in event!") record = records[0] s3_obj = record["s3"] # Get the bucket nam...
from common import AV_STATUS_METADATA from common import AV_STATUS_SNS_ARN from common import AV_STATUS_SNS_PUBLISH_CLEAN from common import AV_STATUS_SNS_PUBLISH_INFECTED from common import AV_TIMESTAMP_METADATA from common import create_dir from common import get_timestamp def event_object(event, event_source="s3"): ...
81
81
272
20
60
snehal-wadhwani/bucket-antivirus-function
scan.py
Python
event_object
event_object
44
77
44
46
9f60b3992e52d9611d703b78f5d238d8074bbae2
bigcode/the-stack
train
e779fce9c38be70c3dcc1916
train
function
def set_av_metadata(s3_object, scan_result, scan_signature, timestamp): content_type = s3_object.content_type metadata = s3_object.metadata metadata[AV_SIGNATURE_METADATA] = scan_signature metadata[AV_STATUS_METADATA] = scan_result metadata[AV_TIMESTAMP_METADATA] = timestamp s3_object.copy( ...
def set_av_metadata(s3_object, scan_result, scan_signature, timestamp):
content_type = s3_object.content_type metadata = s3_object.metadata metadata[AV_SIGNATURE_METADATA] = scan_signature metadata[AV_STATUS_METADATA] = scan_result metadata[AV_TIMESTAMP_METADATA] = timestamp s3_object.copy( {"Bucket": s3_object.bucket_name, "Key": s3_object.key}, Ext...
.%s" % (s3_object.bucket_name, s3_object.key) ) else: print("Infected file deleted: %s.%s" % (s3_object.bucket_name, s3_object.key)) def set_av_metadata(s3_object, scan_result, scan_signature, timestamp):
64
64
121
16
48
snehal-wadhwani/bucket-antivirus-function
scan.py
Python
set_av_metadata
set_av_metadata
117
130
117
117
782fa72f3e06574bc3e7dc5e90c099d22a4366a1
bigcode/the-stack
train
f4ff8ee1da62cbebc2b3d287
train
function
def get_local_path(s3_object, local_prefix): return os.path.join(local_prefix, s3_object.bucket_name, s3_object.key)
def get_local_path(s3_object, local_prefix):
return os.path.join(local_prefix, s3_object.bucket_name, s3_object.key)
.bucket_name, s3_object.key) ) else: # misconfigured bucket, left with no or suspended versioning raise Exception( "Object versioning is not enabled in bucket %s" % s3_object.bucket_name ) def get_local_path(s3_object, local_prefix):
64
64
30
11
53
snehal-wadhwani/bucket-antivirus-function
scan.py
Python
get_local_path
get_local_path
101
102
101
101
a54751991673d8c68fe85b03fc1aa54248267de9
bigcode/the-stack
train
4c55d8d6d6105899f4bcc3e0
train
function
def delete_s3_object(s3_object): try: s3_object.delete() except Exception: raise Exception( "Failed to delete infected file: %s.%s" % (s3_object.bucket_name, s3_object.key) ) else: print("Infected file deleted: %s.%s" % (s3_object.bucket_name, s3_objec...
def delete_s3_object(s3_object):
try: s3_object.delete() except Exception: raise Exception( "Failed to delete infected file: %s.%s" % (s3_object.bucket_name, s3_object.key) ) else: print("Infected file deleted: %s.%s" % (s3_object.bucket_name, s3_object.key))
raise Exception( "Object versioning is not enabled in bucket %s" % s3_object.bucket_name ) def get_local_path(s3_object, local_prefix): return os.path.join(local_prefix, s3_object.bucket_name, s3_object.key) def delete_s3_object(s3_object):
64
64
84
9
55
snehal-wadhwani/bucket-antivirus-function
scan.py
Python
delete_s3_object
delete_s3_object
105
114
105
105
a22926dd361900ffb7a86e7e127a7dc6c7350647
bigcode/the-stack
train
838531eda67e87eba9a0c150
train
function
def read(*names): with open(os.path.join(os.path.dirname(__file__), *names)) as f: return f.read()
def read(*names):
with open(os.path.join(os.path.dirname(__file__), *names)) as f: return f.read()
#! /usr/bin/env python """Setup script for installing as a module.""" import re import ast import os from setuptools import setup, find_packages def read(*names):
38
64
28
5
32
rutherrp/jeff
setup.py
Python
read
read
10
12
10
10
e493b04318725edb11ca242d4951a433595b651f
bigcode/the-stack
train
cb3eab47c3d3c4e0b43deff4
train
class
class CourseFinderModelsTests(UniSimpleTestCase): def test_course_search_execute_function_appends_counts_and_list_of_courses_to_model_on_success(self): mock_data = SearchMocks.get_search_response_content() course_search = CourseSearch("Computing", None, 1, 20) error = course_search.execute(...
class CourseFinderModelsTests(UniSimpleTestCase):
def test_course_search_execute_function_appends_counts_and_list_of_courses_to_model_on_success(self): mock_data = SearchMocks.get_search_response_content() course_search = CourseSearch("Computing", None, 1, 20) error = course_search.execute() self.assertIsNone(error) self.ass...
from unittest.mock import patch from CMS.test.factories import PageFactory from CMS.test.mocks import SearchMocks from CMS.test.utils import UniSimpleTestCase from coursefinder.models import CourseSearch, CourseFinderChooseCountry, CourseFinderModeOfStudy, \ CourseFinderChooseSubject, CourseFinderNarrowSearch, Cou...
172
256
2,507
11
160
jaspotsangbam/wagtail-CMS
coursefinder/tests.py
Python
CourseFinderModelsTests
CourseFinderModelsTests
16
254
16
17
b6b7a2352410e2b1b7bc4ac741d85e26c4a104bf
bigcode/the-stack
train
3a11fd3100fe237622c1dfc8
train
class
class CourseFinderUtilsTests(UniSimpleTestCase): def test_choose_country_sibling_finder_returns_country_finder_if_in_list(self): course_finder_page = PageFactory.create_search_landing_page('Course Finder') PageFactory.create_country_finder_page(title='Country Finder', parent_page=course_finder_page)...
class CourseFinderUtilsTests(UniSimpleTestCase):
def test_choose_country_sibling_finder_returns_country_finder_if_in_list(self): course_finder_page = PageFactory.create_search_landing_page('Course Finder') PageFactory.create_country_finder_page(title='Country Finder', parent_page=course_finder_page) output = choose_country_sibling_finder(...
Equals(actual, expected) def test_base_search_show_previous_icon_returns_true_when_there_are_pages_to_the_left(self): base_search = BaseSearch(4, 20) base_search.total_institutions = 200 actual = base_search.show_previous_icon self.assertIsTrue(actual) def test_base_search_sho...
256
256
3,479
11
245
jaspotsangbam/wagtail-CMS
coursefinder/tests.py
Python
CourseFinderUtilsTests
CourseFinderUtilsTests
257
544
257
257
2377ae11d27ba7c4ed71bb4108e85f04c672ba35
bigcode/the-stack
train
bcb8698517d5bb056ef7e6a4
train
class
class ReplyKeyboardRemove(Object): """Upon receiving a message with this object, Telegram clients will remove the current custom keyboard and display the default letter-keyboard. By default, custom keyboards are displayed until a new keyboard is sent by a bot. An exception is made for one-time keyboards tha...
class ReplyKeyboardRemove(Object):
"""Upon receiving a message with this object, Telegram clients will remove the current custom keyboard and display the default letter-keyboard. By default, custom keyboards are displayed until a new keyboard is sent by a bot. An exception is made for one-time keyboards that are hidden immediately after the ...
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Pyrogram. If not, see <http://www.gnu.org/licenses/>. from pyrogram.api.core import Object from pyrogram.api.t...
82
82
276
6
75
block1o1/CryptoPredicted
ENV/lib/python3.5/site-packages/pyrogram/client/types/reply_markup/reply_keyboard_remove.py
Python
ReplyKeyboardRemove
ReplyKeyboardRemove
23
52
23
23
7cc14371ffba2efcfc1061f5ada051d725da1e48
bigcode/the-stack
train
91a974888f343bcd7c2cb61b
train
function
def Model_tl(): model = Sequential() model.add(Lambda(lambda x: x/127.5 - 1.,input_shape=(100,100,3))) model.add(Conv2D(filters=3,kernel_size = (1,1),strides=(1, 1),padding="valid")) model.add(Conv2D(filters=32,kernel_size = (3,3),strides=(1, 1),padding="valid")) model.add(Activation('relu...
def Model_tl():
model = Sequential() model.add(Lambda(lambda x: x/127.5 - 1.,input_shape=(100,100,3))) model.add(Conv2D(filters=3,kernel_size = (1,1),strides=(1, 1),padding="valid")) model.add(Conv2D(filters=32,kernel_size = (3,3),strides=(1, 1),padding="valid")) model.add(Activation('relu')) model.a...
from keras.models import Sequential, load_model from keras.layers import Dense, Dropout, Activation, Flatten, SpatialDropout2D from keras.layers import Conv2D, Cropping2D, MaxPooling2D from keras.layers.core import Lambda from keras.optimizers import SGD, Adam, RMSprop from keras.utils import np_utils, to_categorica...
89
132
443
5
83
pdigese/CarND-Capstone-team-5-june20
ros/src/tl_detector/light_classification/tools.py
Python
Model_tl
Model_tl
12
50
12
12
227ff702780566220bc2ba25c393c707362e0a20
bigcode/the-stack
train
bf96d010e1f314f4c39b2df7
train
class
class PgHbaRuleValueError(PgHbaRuleError): ''' This exception is raised when a new parsed rule is a changed version of an existing rule. '''
class PgHbaRuleValueError(PgHbaRuleError):
''' This exception is raised when a new parsed rule is a changed version of an existing rule. '''
parsed rule is a changed version of an existing rule. ''' class PgHbaValueError(PgHbaError): ''' This exception is raised when a new parsed rule is a changed version of an existing rule. ''' class PgHbaRuleValueError(PgHbaRuleError):
63
64
37
14
49
Stienvdh/statrick
intro-ansible/venv3/lib/python3.8/site-packages/ansible_collections/community/postgresql/plugins/modules/postgresql_pg_hba.py
Python
PgHbaRuleValueError
PgHbaRuleValueError
234
237
234
234
1d912052286f1d92fc764ae2fd353e0840e9fb79
bigcode/the-stack
train
0fd371cce6a49eba6c09786d
train
class
class PgHbaRule(dict): ''' This class represents one rule as defined in a line in a PgHbaFile. ''' def __init__(self, contype=None, databases=None, users=None, source=None, netmask=None, method=None, options=None, line=None): ''' This function can be called with a comma...
class PgHbaRule(dict):
''' This class represents one rule as defined in a line in a PgHbaFile. ''' def __init__(self, contype=None, databases=None, users=None, source=None, netmask=None, method=None, options=None, line=None): ''' This function can be called with a comma seperated list of data...
object ''' rules = sorted(self.rules.values()) for rule in rules: ret = {} for key, value in rule.items(): ret[key] = value if not with_lines: if 'line' in ret: del ret['line'] else: ...
255
256
2,402
7
248
Stienvdh/statrick
intro-ansible/venv3/lib/python3.8/site-packages/ansible_collections/community/postgresql/plugins/modules/postgresql_pg_hba.py
Python
PgHbaRule
PgHbaRule
402
654
402
402
76be324502ec6904f8fd12f53508b49a9855b3a2
bigcode/the-stack
train
01bed2f158adb615f9fd1c44
train
class
class PgHbaError(Exception): ''' This exception is raised when parsing the pg_hba file ends in an error. '''
class PgHbaError(Exception):
''' This exception is raised when parsing the pg_hba file ends in an error. '''
", "sud", "dsu", "dus", "usd", "uds"] PG_HBA_HDR = ['type', 'db', 'usr', 'src', 'mask', 'method', 'options'] WHITESPACES_RE = re.compile(r'\s+') class PgHbaError(Exception):
64
64
28
7
56
Stienvdh/statrick
intro-ansible/venv3/lib/python3.8/site-packages/ansible_collections/community/postgresql/plugins/modules/postgresql_pg_hba.py
Python
PgHbaError
PgHbaError
210
213
210
210
d884ef24f853f140117b9d93a49ef02836bb03c4
bigcode/the-stack
train
0b41427365b1fcaf5ab5cde6
train
class
class PgHbaValueError(PgHbaError): ''' This exception is raised when a new parsed rule is a changed version of an existing rule. '''
class PgHbaValueError(PgHbaError):
''' This exception is raised when a new parsed rule is a changed version of an existing rule. '''
when parsing the pg_hba file ends in an error. ''' class PgHbaRuleChanged(PgHbaRuleError): ''' This exception is raised when a new parsed rule is a changed version of an existing rule. ''' class PgHbaValueError(PgHbaError):
63
64
35
12
51
Stienvdh/statrick
intro-ansible/venv3/lib/python3.8/site-packages/ansible_collections/community/postgresql/plugins/modules/postgresql_pg_hba.py
Python
PgHbaValueError
PgHbaValueError
228
231
228
228
09ae1b4ac7c4f1a8f90cb7e9d4c6785a00ca373c
bigcode/the-stack
train
7d86561135037b3133f61c65
train
class
class PgHbaRuleChanged(PgHbaRuleError): ''' This exception is raised when a new parsed rule is a changed version of an existing rule. '''
class PgHbaRuleChanged(PgHbaRuleError):
''' This exception is raised when a new parsed rule is a changed version of an existing rule. '''
is raised when parsing the pg_hba file ends in an error. ''' class PgHbaRuleError(PgHbaError): ''' This exception is raised when parsing the pg_hba file ends in an error. ''' class PgHbaRuleChanged(PgHbaRuleError):
63
64
36
13
50
Stienvdh/statrick
intro-ansible/venv3/lib/python3.8/site-packages/ansible_collections/community/postgresql/plugins/modules/postgresql_pg_hba.py
Python
PgHbaRuleChanged
PgHbaRuleChanged
222
225
222
222
1ac1dce3fad91c7c64f8b22fb1d8472dda95e592
bigcode/the-stack
train
ff0d07d254ec811fac223765
train
class
class PgHba(object): """ PgHba object to read/write entries to/from. pg_hba_file - the pg_hba file almost always /etc/pg_hba """ def __init__(self, pg_hba_file=None, order="sdu", backup=False, create=False): if order not in PG_HBA_ORDERS: msg = "invalid order setting {0} (should ...
class PgHba(object):
""" PgHba object to read/write entries to/from. pg_hba_file - the pg_hba file almost always /etc/pg_hba """ def __init__(self, pg_hba_file=None, order="sdu", backup=False, create=False): if order not in PG_HBA_ORDERS: msg = "invalid order setting {0} (should be one of '{1}')." ...
hostssl", "hostnossl"] PG_HBA_ORDERS = ["sdu", "sud", "dsu", "dus", "usd", "uds"] PG_HBA_HDR = ['type', 'db', 'usr', 'src', 'mask', 'method', 'options'] WHITESPACES_RE = re.compile(r'\s+') class PgHbaError(Exception): ''' This exception is raised when parsing the pg_hba file ends in an error. ''' class...
255
256
1,331
6
249
Stienvdh/statrick
intro-ansible/venv3/lib/python3.8/site-packages/ansible_collections/community/postgresql/plugins/modules/postgresql_pg_hba.py
Python
PgHba
PgHba
240
399
240
240
b6e8f3d245b3f5fee42e8434117dd49693860021
bigcode/the-stack
train
35c83d1a4299424b0a6dbb35
train
class
class PgHbaRuleError(PgHbaError): ''' This exception is raised when parsing the pg_hba file ends in an error. '''
class PgHbaRuleError(PgHbaError):
''' This exception is raised when parsing the pg_hba file ends in an error. '''
', 'mask', 'method', 'options'] WHITESPACES_RE = re.compile(r'\s+') class PgHbaError(Exception): ''' This exception is raised when parsing the pg_hba file ends in an error. ''' class PgHbaRuleError(PgHbaError):
63
64
33
12
51
Stienvdh/statrick
intro-ansible/venv3/lib/python3.8/site-packages/ansible_collections/community/postgresql/plugins/modules/postgresql_pg_hba.py
Python
PgHbaRuleError
PgHbaRuleError
216
219
216
216
854c03f7b932ab55db773bda7a93b9bf7347d461
bigcode/the-stack
train
5720f63862ce5db17cba8649
train
function
def main(): ''' This function is the main function of this module ''' # argument_spec = postgres_common_argument_spec() argument_spec = dict() argument_spec.update( address=dict(type='str', default='samehost', aliases=['source', 'src']), backup=dict(type='bool', default=False), ...
def main():
''' This function is the main function of this module ''' # argument_spec = postgres_common_argument_spec() argument_spec = dict() argument_spec.update( address=dict(type='str', default='samehost', aliases=['source', 'src']), backup=dict(type='bool', default=False), backu...
sourceobj = self.source() if isinstance(sourceobj, ipaddress.IPv4Network): return 2 if isinstance(sourceobj, ipaddress.IPv6Network): return 1 if isinstance(sourceobj, str): return 0 raise PgHbaValueError('This source {0} is of an unknown type...
229
229
766
3
225
Stienvdh/statrick
intro-ansible/venv3/lib/python3.8/site-packages/ansible_collections/community/postgresql/plugins/modules/postgresql_pg_hba.py
Python
main
main
657
742
657
657
cf518f3e34c2fee6970b371a20ed55cd7aaf77a5
bigcode/the-stack
train
0e056059d57e5b43161f1dbf
train
class
class StringDisplayImpl(DisplayImpl): def __init__(self, string): self.string = string self.width = len(string) def rawOpen(self): self.printLine() def rawPrint(self): print("|{0}|".format(self.string)) def rawClose(self): self.printLine() def printLine(se...
class StringDisplayImpl(DisplayImpl):
def __init__(self, string): self.string = string self.width = len(string) def rawOpen(self): self.printLine() def rawPrint(self): print("|{0}|".format(self.string)) def rawClose(self): self.printLine() def printLine(self): print("+", end='') ...
from DisplayImpl import DisplayImpl class StringDisplayImpl(DisplayImpl):
14
64
97
7
6
fuqinshen/Python--
src/bridge/StringDisplayImpl.py
Python
StringDisplayImpl
StringDisplayImpl
4
22
4
4
f8a449f533b60d15354eb80fbcab02af7ebb34be
bigcode/the-stack
train
5d633a60bfef43339d0de772
train
class
class Solution: def decodeAtIndex(self, S: str, K: int) -> str: record = '' ans = '' index = 0 while index < len(S): if (S[index] >= '0' and S[index] <= '9'): num = '' num += S[index] while (index + 1 < len(S) and S[index + ...
class Solution:
def decodeAtIndex(self, S: str, K: int) -> str: record = '' ans = '' index = 0 while index < len(S): if (S[index] >= '0' and S[index] <= '9'): num = '' num += S[index] while (index + 1 < len(S) and S[index + 1] >= '0' and S[...
class Solution:
3
64
173
3
0
zzz0906/LeetCode
2020_December/20.py
Python
Solution
Solution
1
21
1
1
d91edeb60c5cf3cf430228073dc8ca404f587d08
bigcode/the-stack
train
ae77e9ec8c19a99c9f6bea69
train
class
class Vacancy: """ Базовый класс вакансии """ def __init__(self, raw_data): # генерация из JSON self.attr_01_id__ = int(raw_data.get('id')) self.attr_02_name = raw_data.get('name') self.attr_03_url_ = raw_data.get('alternate_url') salary = hh_handlers.handle_sala...
class Vacancy:
""" Базовый класс вакансии """ def __init__(self, raw_data): # генерация из JSON self.attr_01_id__ = int(raw_data.get('id')) self.attr_02_name = raw_data.get('name') self.attr_03_url_ = raw_data.get('alternate_url') salary = hh_handlers.handle_salary(raw_data) ...
# -*- coding: utf-8 -*- """ В этом модуле находится класс вакансии и его управляющий класс """ import time from colorama import Fore, init import hh_handlers, hh_internet, hh_excel, hh_html init(autoreset=True) class Vacancy:
60
133
446
3
57
IgorZyktin/headhunter
hh_parser/hh_vacancy.py
Python
Vacancy
Vacancy
15
56
15
15
a94a2fbc50f8bc210e0ce3a0bdd1f0eff716fdd7
bigcode/the-stack
train
b247f30b07f5edbf0f8bad5c
train
class
class VacancyManager: """ Класс-обработчик для Vacancy """ def __init__(self, keyword, area): """ Создание пустого менеджера """ self.keyword = keyword self._memory = {} raw_vacancies = hh_internet.load_vacancies(keyword, area) for raw_vacancy in r...
class VacancyManager:
""" Класс-обработчик для Vacancy """ def __init__(self, keyword, area): """ Создание пустого менеджера """ self.keyword = keyword self._memory = {} raw_vacancies = hh_internet.load_vacancies(keyword, area) for raw_vacancy in raw_vacancies: ...
.attr_10_description = description.attr_10_description self.attr_11_short_descr = description.attr_11_short_descr employer = hh_handlers.handle_employer(raw_data) self.attr_12_employer_id__ = employer.attr_12_employer_id__ self.attr_13_employer_url_ = employer.attr_13_employer_url_ ...
255
256
1,347
4
252
IgorZyktin/headhunter
hh_parser/hh_vacancy.py
Python
VacancyManager
VacancyManager
59
225
59
59
b57225e0fce16a7353f39803baedf9dc34635989
bigcode/the-stack
train
bb9795dbd1183b88daa68066
train
class
class RandomForestOptimization(InformedOptimizationProtocol): """Sequential optimization with random forest regressor decision trees""" def __init__( self, target_metric=None, iterations=1, verbose=1, read_experiments=True, reporter_parameters=None, base_estimator='RF', n_initial_points...
class RandomForestOptimization(InformedOptimizationProtocol):
"""Sequential optimization with random forest regressor decision trees""" def __init__( self, target_metric=None, iterations=1, verbose=1, read_experiments=True, reporter_parameters=None, base_estimator='RF', n_initial_points=10, acquisition_function='EI', acquisition_optimi...
imator=base_estimator, n_initial_points=n_initial_points, acquisition_function=acquisition_function, acquisition_optimizer=acquisition_optimizer, random_state=random_state, acquisition_function_kwargs=acquisition_function_kwargs, acquisition_optimizer_kwargs=acquisition_optimizer_kwargs, ...
87
87
292
9
78
cclauss/hyperparameter_hunter
hyperparameter_hunter/optimization.py
Python
RandomForestOptimization
RandomForestOptimization
88
110
88
88
b0c107507737f3f44e4afab2a168eefb70238c7d
bigcode/the-stack
train
3ebc9edd8a3ef1a2666cc4f3
train
class
class DummySearch(InformedOptimizationProtocol): """Random search by uniform sampling. Technically this is not "Informed", but it fits better as an Informed subclass due to its reliance on `Scikit-Optimize`""" def __init__( self, target_metric=None, iterations=1, verbose=1, read_experiments=Tru...
class DummySearch(InformedOptimizationProtocol):
"""Random search by uniform sampling. Technically this is not "Informed", but it fits better as an Informed subclass due to its reliance on `Scikit-Optimize`""" def __init__( self, target_metric=None, iterations=1, verbose=1, read_experiments=True, reporter_parameters=None, base_est...
, base_estimator=base_estimator, n_initial_points=n_initial_points, acquisition_function=acquisition_function, acquisition_optimizer=acquisition_optimizer, random_state=random_state, acquisition_function_kwargs=acquisition_function_kwargs, acquisition_optimizer_kwargs=acquisition_opt...
90
90
303
8
82
cclauss/hyperparameter_hunter
hyperparameter_hunter/optimization.py
Python
DummySearch
DummySearch
138
161
138
138
8674bc67edff597ec3bbe1f5e5c8fe2fa680966d
bigcode/the-stack
train
61a3e259958cb8441727fcd6
train
class
class RandomizedGridSearch(UninformedOptimizationProtocol): def __init__(self, target_metric=None, iterations=1, verbose=1, read_experiments=True, reporter_parameters=None): super().__init__( target_metric=target_metric, iterations=iterations, verbose=verbose, read_experiments=read_experiments, ...
class RandomizedGridSearch(UninformedOptimizationProtocol):
def __init__(self, target_metric=None, iterations=1, verbose=1, read_experiments=True, reporter_parameters=None): super().__init__( target_metric=target_metric, iterations=iterations, verbose=verbose, read_experiments=read_experiments, reporter_parameters=reporter_parameters, ...
parameter_space = ParameterGrid(self.search_bounds).__iter__() @property def search_space_size(self): if self._search_space_size is None: self._search_space_size = len(self.hyperparameter_space) return self._search_space_size class RandomizedGridSearch(UninformedOptimizationProtocol...
64
64
209
11
52
cclauss/hyperparameter_hunter
hyperparameter_hunter/optimization.py
Python
RandomizedGridSearch
RandomizedGridSearch
199
217
199
199
3af3c4f5dbb7815dc7379accf4647f75431d5c4d
bigcode/the-stack
train
14f8c4d5a7ef898daa37f8ba
train
class
class TreeStructuredParzenEstimatorsOptimization(InformedOptimizationProtocol): # FLAG: http://neupy.com/2016/12/17/hyperparameter_optimization_for_neural_networks.html#id24 pass
class TreeStructuredParzenEstimatorsOptimization(InformedOptimizationProtocol): # FLAG: http://neupy.com/2016/12/17/hyperparameter_optimization_for_neural_networks.html#id24
pass
_random_starts, callbacks=callbacks, base_estimator_kwargs=base_estimator_kwargs, ) class TreeStructuredParzenEstimatorsOptimization(InformedOptimizationProtocol): # FLAG: http://neupy.com/2016/12/17/hyperparameter_optimization_for_neural_networks.html#id24
64
64
47
44
20
cclauss/hyperparameter_hunter
hyperparameter_hunter/optimization.py
Python
TreeStructuredParzenEstimatorsOptimization
TreeStructuredParzenEstimatorsOptimization
164
166
164
165
af5577b5a3832e63b976246cd2049854de3aa69f
bigcode/the-stack
train
0dc2000c1ae24016c4870c9c
train
class
class GradientBoostedRegressionTreeOptimization(InformedOptimizationProtocol): """Sequential optimization with gradient boosted regression trees""" def __init__( self, target_metric=None, iterations=1, verbose=1, read_experiments=True, reporter_parameters=None, base_estimator='GBRT', n_...
class GradientBoostedRegressionTreeOptimization(InformedOptimizationProtocol):
"""Sequential optimization with gradient boosted regression trees""" def __init__( self, target_metric=None, iterations=1, verbose=1, read_experiments=True, reporter_parameters=None, base_estimator='GBRT', n_initial_points=10, acquisition_function='EI', acquisition_optimizer...
acquisition_optimizer=acquisition_optimizer, random_state=random_state, acquisition_function_kwargs=acquisition_function_kwargs, acquisition_optimizer_kwargs=acquisition_optimizer_kwargs, n_random_starts=n_random_starts, callbacks=callbacks, base_estimator_kwargs=base_estimator_kwargs, ...
90
90
302
12
78
cclauss/hyperparameter_hunter
hyperparameter_hunter/optimization.py
Python
GradientBoostedRegressionTreeOptimization
GradientBoostedRegressionTreeOptimization
63
85
63
63
4c36fbc82c870a36fbeb7af555d6d6f40fa94842
bigcode/the-stack
train
41b03b0cccfbc240aa0b930d
train
class
class EvolutionaryOptimization(InformedOptimizationProtocol): # FLAG: See TPOT's Genetic Programming approach pass
class EvolutionaryOptimization(InformedOptimizationProtocol): # FLAG: See TPOT's Genetic Programming approach
pass
zenEstimatorsOptimization(InformedOptimizationProtocol): # FLAG: http://neupy.com/2016/12/17/hyperparameter_optimization_for_neural_networks.html#id24 pass class EvolutionaryOptimization(InformedOptimizationProtocol): # FLAG: See TPOT's Genetic Programming approach
64
64
24
21
42
cclauss/hyperparameter_hunter
hyperparameter_hunter/optimization.py
Python
EvolutionaryOptimization
EvolutionaryOptimization
169
171
169
170
ea0f817e7fe7f8b185d1f6f6912ceb9ea3250b39
bigcode/the-stack
train
586ef52c31bf2c180446db01
train
class
class ParticleSwarmOptimization(InformedOptimizationProtocol): # FLAG: ... pass
class ParticleSwarmOptimization(InformedOptimizationProtocol): # FLAG: ...
pass
/2016/12/17/hyperparameter_optimization_for_neural_networks.html#id24 pass class EvolutionaryOptimization(InformedOptimizationProtocol): # FLAG: See TPOT's Genetic Programming approach pass class ParticleSwarmOptimization(InformedOptimizationProtocol): # FLAG: ...
64
64
18
15
48
cclauss/hyperparameter_hunter
hyperparameter_hunter/optimization.py
Python
ParticleSwarmOptimization
ParticleSwarmOptimization
174
176
174
175
0a90de655271d25fc2e1d58b9e17ad450d79d0d5
bigcode/the-stack
train
e66eebd413de23a2107bb916
train
class
class BayesianOptimization(InformedOptimizationProtocol): """Bayesian optimization with Gaussian Processes""" def __init__( self, target_metric=None, iterations=1, verbose=1, read_experiments=True, reporter_parameters=None, base_estimator='GP', n_initial_points=10, acquisiti...
class BayesianOptimization(InformedOptimizationProtocol):
"""Bayesian optimization with Gaussian Processes""" def __init__( self, target_metric=None, iterations=1, verbose=1, read_experiments=True, reporter_parameters=None, base_estimator='GP', n_initial_points=10, acquisition_function='gp_hedge', acquisition_optimizer='auto', rand...
ellaneous Assets ################################################## import numpy as np ################################################## # Import Learning Assets ################################################## from sklearn.model_selection import ParameterGrid, ParameterSampler from skopt.learning.gaussian_process....
97
97
325
8
89
cclauss/hyperparameter_hunter
hyperparameter_hunter/optimization.py
Python
BayesianOptimization
BayesianOptimization
33
60
33
33
cf84a435adb8080a2c3bf67d145ec54d824f308b
bigcode/the-stack
train
0cc353fe10e4130e3e69aada
train
class
class GridSearch(UninformedOptimizationProtocol): def __init__(self, target_metric=None, iterations=1, verbose=1, read_experiments=True, reporter_parameters=None): super().__init__( target_metric=target_metric, iterations=iterations, verbose=verbose, read_experiments=read_experiments, ...
class GridSearch(UninformedOptimizationProtocol):
def __init__(self, target_metric=None, iterations=1, verbose=1, read_experiments=True, reporter_parameters=None): super().__init__( target_metric=target_metric, iterations=iterations, verbose=verbose, read_experiments=read_experiments, reporter_parameters=reporter_parameters, ...
class EvolutionaryOptimization(InformedOptimizationProtocol): # FLAG: See TPOT's Genetic Programming approach pass class ParticleSwarmOptimization(InformedOptimizationProtocol): # FLAG: ... pass ################################################## # Uninformed Optimization Protocols ###############...
64
64
144
9
55
cclauss/hyperparameter_hunter
hyperparameter_hunter/optimization.py
Python
GridSearch
GridSearch
182
196
182
182
5bba1fc09da3962a88a4b4c91a7be02421907674
bigcode/the-stack
train
9ba299e7040e793b28ab3624
train
class
class ExtraTreesOptimization(InformedOptimizationProtocol): """Sequential optimization with extra trees regressor decision trees""" def __init__( self, target_metric=None, iterations=1, verbose=1, read_experiments=True, reporter_parameters=None, base_estimator='ET', n_initial_points=10,...
class ExtraTreesOptimization(InformedOptimizationProtocol):
"""Sequential optimization with extra trees regressor decision trees""" def __init__( self, target_metric=None, iterations=1, verbose=1, read_experiments=True, reporter_parameters=None, base_estimator='ET', n_initial_points=10, acquisition_function='EI', acquisition_optimize...
imator=base_estimator, n_initial_points=n_initial_points, acquisition_function=acquisition_function, acquisition_optimizer=acquisition_optimizer, random_state=random_state, acquisition_function_kwargs=acquisition_function_kwargs, acquisition_optimizer_kwargs=acquisition_optimizer_kwargs, ...
87
87
292
9
78
cclauss/hyperparameter_hunter
hyperparameter_hunter/optimization.py
Python
ExtraTreesOptimization
ExtraTreesOptimization
113
135
113
113
dfe473b66f86823e8a75d2a0646d221672b89151
bigcode/the-stack
train
fa2b4edc8c64e6134b0eec37
train
class
class Migration(migrations.Migration): dependencies = [ ('extractiontool', '0001_initial'), ] operations = [ migrations.AddField( model_name='cmisserver', name='date_creation', field=models.DateField(default=django.utils.timezone.now), ...
class Migration(migrations.Migration):
dependencies = [ ('extractiontool', '0001_initial'), ] operations = [ migrations.AddField( model_name='cmisserver', name='date_creation', field=models.DateField(default=django.utils.timezone.now), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone class Migration(migrations.Migration):
38
64
65
7
30
wandss/ExportingTool
fnetET/extractiontool/migrations/0002_cmisserver_date_creation.py
Python
Migration
Migration
8
20
8
9
f63519b73ab28dde0283f32c05cd58d13a925b50
bigcode/the-stack
train
2c82f23cb71dcb62fd4c738f
train
function
def get_routes(): """ Get all routes in the project. Return dict with key of service name, value of http route """ data = get_json("route") ret = {} for route in data.get("items", []): ret[route["metadata"]["name"]] = route["spec"]["host"] return ret
def get_routes():
""" Get all routes in the project. Return dict with key of service name, value of http route """ data = get_json("route") ret = {} for route in data.get("items", []): ret[route["metadata"]["name"]] = route["spec"]["host"] return ret
start deploying for _ in range(0, 60): if _get_revision() != old_revision: break log.info("Waiting for rollout on dc/%s to begin", dc_name) time.sleep(1) wait_for_ready("dc", dc_name) def get_routes():
64
64
73
4
60
carbonin/ocdeployer
ocdeployer/utils.py
Python
get_routes
get_routes
250
260
250
250
e562add9104e63b09c435a90227613097083b4f3
bigcode/the-stack
train
b2d43504002860a60f3c432b
train
function
def get_cfg_files_in_dir(path): """ Get a list of all .yml/.json files in a dir Ignore the special _cfg file """ files = list(glob.glob(os.path.join(path, "*.yaml"))) files.extend(list(glob.glob(os.path.join(path, "*.yml")))) files.extend(list(glob.glob(os.path.join(path, "*.json")))) r...
def get_cfg_files_in_dir(path):
""" Get a list of all .yml/.json files in a dir Ignore the special _cfg file """ files = list(glob.glob(os.path.join(path, "*.yaml"))) files.extend(list(glob.glob(os.path.join(path, "*.yml")))) files.extend(list(glob.glob(os.path.join(path, "*.json")))) return [f for f in files if not o...
_lower = string.lower() if string_lower in SHORTCUTS: return string_lower for resource_name, shortcut in SHORTCUTS.items(): if string_lower == shortcut: return resource_name raise ValueError("Unknown resource type: {}".format(string)) def get_cfg_files_in_dir(path):
64
64
103
8
56
carbonin/ocdeployer
ocdeployer/utils.py
Python
get_cfg_files_in_dir
get_cfg_files_in_dir
78
87
78
78
003bb8369c6c88e0bcd574c940359d1574ca10ce
bigcode/the-stack
train
bcbfa489900d3efe586c564b
train
function
def start_deployment(dc_name): if dc_ready(dc_name): log.info("Deployment '%s' already deployed and running, skipping deploy for it", dc_name) return log.info("Patching deployment config for '%s' to resume rollouts", dc_name) try: oc("rollout", "resume", "dc/{}".format(dc_name), _re...
def start_deployment(dc_name):
if dc_ready(dc_name): log.info("Deployment '%s' already deployed and running, skipping deploy for it", dc_name) return log.info("Patching deployment config for '%s' to resume rollouts", dc_name) try: oc("rollout", "resume", "dc/{}".format(dc_name), _reraise=True) except sh.Error...
be terminated".format(dc_name), timeout=180, delay=5, log_on_loop=True, ) def dc_ready(dc_name): dc_json = get_json("dc", dc_name) return _check_status_for_restype("dc", dc_json) and all_pods_running(dc_name) def start_deployment(dc_name):
72
72
240
7
65
carbonin/ocdeployer
ocdeployer/utils.py
Python
start_deployment
start_deployment
486
513
486
486
f3b6395ffa9d642bb93873ea63fb62ff55ac841c
bigcode/the-stack
train
54e2bd0708735eb3f20103e4
train
function
def wait_for_ready(restype, name, timeout=300, exit_on_err=False, _result_dict=None): """ Wait {timeout} for resource to be complete/ready/active. Args: restype: type of resource, which can be "build", "dc", "deploymentconfig" name: name of resource timeout: time in secs to wait for...
def wait_for_ready(restype, name, timeout=300, exit_on_err=False, _result_dict=None):
""" Wait {timeout} for resource to be complete/ready/active. Args: restype: type of resource, which can be "build", "dc", "deploymentconfig" name: name of resource timeout: time in secs to wait for resource to become ready exit_on_err: if resource fails to become ready, exit...
return False build = "{}-{}".format(name, last_version) log.debug("checking 'bc/%s' last triggered build: %s", name, build) return _check_status_for_restype("build", get_json("build", build)) else: raise ValueError( "Checking status for resource type {} is n...
106
106
355
23
83
carbonin/ocdeployer
ocdeployer/utils.py
Python
wait_for_ready
wait_for_ready
330
377
330
330
0c78767da0f45c6ee7da7f4d646a6ddc8c7f5bc5
bigcode/the-stack
train
ef76124d67298d9b14d5b13d
train
function
def object_merge(old, new): """ Recursively merge two data structures Thanks rsnyman :) https://github.com/rochacbruno/dynaconf/commit/458ffa6012f1de62fc4f68077f382ab420b43cfc#diff-c1b434836019ae32dc57d00dd1ae2eb9R15 """ if isinstance(old, list) and isinstance(new, list): for item in ol...
def object_merge(old, new):
""" Recursively merge two data structures Thanks rsnyman :) https://github.com/rochacbruno/dynaconf/commit/458ffa6012f1de62fc4f68077f382ab420b43cfc#diff-c1b434836019ae32dc57d00dd1ae2eb9R15 """ if isinstance(old, list) and isinstance(new, list): for item in old[::-1]: new.ins...
"rc", "secrets": None, "service": "svc", "serviceaccount": "sa", "persistentvolume": "pv", "persistentvolumeclaim": "pvc", "configmap": None, "route": None, } def object_merge(old, new):
64
64
162
7
57
carbonin/ocdeployer
ocdeployer/utils.py
Python
object_merge
object_merge
45
60
45
45
9f14e1a2bbb91e3731c255b3cd7f8f3ef6440123
bigcode/the-stack
train
22602ff7295fffa8372222da
train
function
def no_pods_running(dc_name): """ Return true if there are no pods running in the deployment """ return not all_pods_running(dc_name)
def no_pods_running(dc_name):
""" Return true if there are no pods running in the deployment """ return not all_pods_running(dc_name)
log.info("No pods found for dc %s", dc_name) return False statuses = [] for pod in pod_data["items"]: statuses.append(_check_status_for_restype("pod", pod)) return len(statuses) and all(statuses) def no_pods_running(dc_name):
64
64
35
8
56
carbonin/ocdeployer
ocdeployer/utils.py
Python
no_pods_running
no_pods_running
441
445
441
441
11afaaffdf7053d41b6c44570e36170a94f84b57
bigcode/the-stack
train
bc6dc70025945e5dd2dc1931
train
function
def oc(*args, **kwargs): """ Run 'sh.oc' and print the command, show output, catch errors, etc. Optional kwargs: _reraise: if ErrorReturnCode is hit, don't exit, re-raise it _exit_on_err: sys.exit(1) if this command fails (default True) _silent: don't print command or resulting stdo...
def oc(*args, **kwargs):
""" Run 'sh.oc' and print the command, show output, catch errors, etc. Optional kwargs: _reraise: if ErrorReturnCode is hit, don't exit, re-raise it _exit_on_err: sys.exit(1) if this command fails (default True) _silent: don't print command or resulting stdout (default False) ...
.extend(list(glob.glob(os.path.join(path, "*.json")))) return [f for f in files if not os.path.basename(f).startswith("_cfg")] def load_cfg_file(path): if not os.path.isfile(path): raise ValueError("Path '{}' is not a file or does not exist".format(path)) _, file_ext = os.path.splitext(path) ...
178
178
596
8
169
carbonin/ocdeployer
ocdeployer/utils.py
Python
oc
oc
110
183
110
110
4b7373aa5b56ba70505e81f3ef298723d5d54183
bigcode/the-stack
train
2e9b58a75980b3cfb62d3a73
train
function
def get_json(restype, name=None, label=None): """ Run 'oc get' for a given resource type/name/label and return the json output. If name is None all resources of this type are returned If label is not provided, then "oc get" will not be filtered on label """ restype = parse_restype(restype) ...
def get_json(restype, name=None, label=None):
""" Run 'oc get' for a given resource type/name/label and return the json output. If name is None all resources of this type are returned If label is not provided, then "oc get" will not be filtered on label """ restype = parse_restype(restype) args = ["get", restype] if name: ...
except ErrorReturnCode as err: log.error("Unable to get project '%s', trying to create it...", project) oc("new-project", project, _exit_on_err=True) oc("project", project, _exit_on_err=True) def get_json(restype, name=None, label=None):
64
64
179
12
52
carbonin/ocdeployer
ocdeployer/utils.py
Python
get_json
get_json
195
221
195
195
ebfb141b715284142985bddcfa7a151119796016
bigcode/the-stack
train
fa6b57654221371596546ad9
train
function
def all_pods_running(dc_name): """ Return true if all pods are running in the deployment config """ pod_data = get_json("pod", label="deploymentconfig={}".format(dc_name)) if not pod_data or not len(pod_data.get("items", [])): log.info("No pods found for dc %s", dc_name) return False...
def all_pods_running(dc_name):
""" Return true if all pods are running in the deployment config """ pod_data = get_json("pod", label="deploymentconfig={}".format(dc_name)) if not pod_data or not len(pod_data.get("items", [])): log.info("No pods found for dc %s", dc_name) return False statuses = [] for pod ...
_data.get("items", [])): log.info("No pods found for dc %s", dc_name) return False for pod in pod_data["items"]: if _check_status_for_restype("pod", pod): return True return False def all_pods_running(dc_name):
64
64
118
8
55
carbonin/ocdeployer
ocdeployer/utils.py
Python
all_pods_running
all_pods_running
427
438
427
427
a623f3aa0a8f7263ae5dd25ddb4aefa627ffde7e
bigcode/the-stack
train
3f14f666fde1b3cc8e14f50a
train
function
def switch_to_project(project): try: oc("get", "project", project, _reraise=True) except ErrorReturnCode as err: log.error("Unable to get project '%s', trying to create it...", project) oc("new-project", project, _exit_on_err=True) oc("project", project, _exit_on_err=True)
def switch_to_project(project):
try: oc("get", "project", project, _reraise=True) except ErrorReturnCode as err: log.error("Unable to get project '%s', trying to create it...", project) oc("new-project", project, _exit_on_err=True) oc("project", project, _exit_on_err=True)
immutable: log.warning("Ignoring immutable field errors") elif _reraise: raise elif _exit_on_err: log.error("Command failed! Aborting.") sys.exit(1) else: log.warning("Non-zero return code ignored") def switch_to_project(project):
64
64
78
6
58
carbonin/ocdeployer
ocdeployer/utils.py
Python
switch_to_project
switch_to_project
186
192
186
186
204943c809849741a7733116dddecc454e9fa1f6
bigcode/the-stack
train
1ef0cebac8d288e97dcff353
train
class
class StatusError(Exception): pass
class StatusError(Exception):
pass
Return dict with key of service name, value of http route """ data = get_json("route") ret = {} for route in data.get("items", []): ret[route["metadata"]["name"]] = route["spec"]["host"] return ret class StatusError(Exception):
64
64
8
5
58
carbonin/ocdeployer
ocdeployer/utils.py
Python
StatusError
StatusError
263
264
263
263
e81bb0aa4b360bddefe9929d0d4dd7c5f7bafd4b
bigcode/the-stack
train
c68f1f9e866724898d8079cd
train
function
def any_pods_running(dc_name): """ Return true if any pods are running in the deployment config """ pod_data = get_json("pod", label="deploymentconfig={}".format(dc_name)) if not pod_data or not len(pod_data.get("items", [])): log.info("No pods found for dc %s", dc_name) return False...
def any_pods_running(dc_name):
""" Return true if any pods are running in the deployment config """ pod_data = get_json("pod", label="deploymentconfig={}".format(dc_name)) if not pod_data or not len(pod_data.get("items", [])): log.info("No pods found for dc %s", dc_name) return False for pod in pod_data["items...
key, result in result_dict.items() if not result] if failed: log.info("Some resources failed to become ready: %s", ", ".join(failed)) if exit_on_err: sys.exit(1) return False return True def any_pods_running(dc_name):
64
64
110
8
55
carbonin/ocdeployer
ocdeployer/utils.py
Python
any_pods_running
any_pods_running
413
424
413
413
dbea2ab259994fcc45c12d9f89c755de1a2c14d3
bigcode/the-stack
train
387305ce95390c84e6840bca
train
function
def _check_status_for_restype(restype, json_data): """ Depending on the resource type, check that it is "ready" or "complete" Uses the status json from an 'oc get' Returns True if ready, False if not. """ try: status = json_data["status"] except KeyError: status = None ...
def _check_status_for_restype(restype, json_data):
""" Depending on the resource type, check that it is "ready" or "complete" Uses the status json from an 'oc get' Returns True if ready, False if not. """ try: status = json_data["status"] except KeyError: status = None try: name = json_data["metadata"]["name"] ...
get_revision() != old_revision: break log.info("Waiting for rollout on dc/%s to begin", dc_name) time.sleep(1) wait_for_ready("dc", dc_name) def get_routes(): """ Get all routes in the project. Return dict with key of service name, value of http route """ ...
137
137
458
13
123
carbonin/ocdeployer
ocdeployer/utils.py
Python
_check_status_for_restype
_check_status_for_restype
267
327
267
267
cd7068890fe704b102abb280b0ea747a5310d0a1
bigcode/the-stack
train
c6d4abb171919b95d8d2e458
train
function
def dc_ready(dc_name): dc_json = get_json("dc", dc_name) return _check_status_for_restype("dc", dc_json) and all_pods_running(dc_name)
def dc_ready(dc_name):
dc_json = get_json("dc", dc_name) return _check_status_for_restype("dc", dc_json) and all_pods_running(dc_name)
s' to terminate", dc_name) wait_for( no_pods_running, func_args=(dc_name,), message="wait for deployment '{}' to be terminated".format(dc_name), timeout=180, delay=5, log_on_loop=True, ) def dc_ready(dc_name):
64
64
40
6
58
carbonin/ocdeployer
ocdeployer/utils.py
Python
dc_ready
dc_ready
481
483
481
481
753dd6e2ef83c3dd64680f8b2d6d6a35610a2cf8
bigcode/the-stack
train
ace0080d818de1be49c61dcf
train
function
def parse_restype(string): """ Given a resource type or its shortcut, return the full resource type name. """ string_lower = string.lower() if string_lower in SHORTCUTS: return string_lower for resource_name, shortcut in SHORTCUTS.items(): if string_lower == shortcut: ...
def parse_restype(string):
""" Given a resource type or its shortcut, return the full resource type name. """ string_lower = string.lower() if string_lower in SHORTCUTS: return string_lower for resource_name, shortcut in SHORTCUTS.items(): if string_lower == shortcut: return resource_name ...
[::-1]: new.insert(0, item) if isinstance(old, dict) and isinstance(new, dict): for key, value in old.items(): if key not in new: new[key] = value else: object_merge(value, new[key]) def parse_restype(string):
64
64
84
6
58
carbonin/ocdeployer
ocdeployer/utils.py
Python
parse_restype
parse_restype
63
75
63
63
bd4b8bd36636a495ee5138580184cfdd6bd2385a
bigcode/the-stack
train
a3542e8e8be580ead6d68cbc
train
function
def rollout(dc_name): """Rollout a deployment, wait for new revision to start deploying, wait for it to go active.""" def _get_revision(): try: return get_json("dc", dc_name)["status"]["latestVersion"] except KeyError: return "error" old_revision = _get_revision() ...
def rollout(dc_name):
"""Rollout a deployment, wait for new revision to start deploying, wait for it to go active.""" def _get_revision(): try: return get_json("dc", dc_name)["status"]["latestVersion"] except KeyError: return "error" old_revision = _get_revision() try: oc("ro...
="json", _exit_on_err=False, _silent=True) except ErrorReturnCode as err: if "NotFound" in err.stderr: return {} try: parsed_json = json.loads(str(output)) except ValueError: return {} return parsed_json def rollout(dc_name):
64
64
189
5
58
carbonin/ocdeployer
ocdeployer/utils.py
Python
rollout
rollout
224
247
224
224
76b84e2ef6999d4f546a7c74cfbe3ff5028ff398
bigcode/the-stack
train
4eaa0910014db770ea9ab169
train
function
def stop_deployment(dc_name): """ Pause a deployment, delete all of its replication controllers, wait for all pods to shut down """ if not any_pods_running(dc_name): log.info("No pods running for dc '%s', nothing to stop", dc_name) log.info("Patching deployment config for '%s' to pause roll...
def stop_deployment(dc_name):
""" Pause a deployment, delete all of its replication controllers, wait for all pods to shut down """ if not any_pods_running(dc_name): log.info("No pods running for dc '%s', nothing to stop", dc_name) log.info("Patching deployment config for '%s' to pause rollouts", dc_name) try: ...
s", dc_name) return False statuses = [] for pod in pod_data["items"]: statuses.append(_check_status_for_restype("pod", pod)) return len(statuses) and all(statuses) def no_pods_running(dc_name): """ Return true if there are no pods running in the deployment """ return not al...
89
89
298
7
82
carbonin/ocdeployer
ocdeployer/utils.py
Python
stop_deployment
stop_deployment
448
478
448
448
b2ce84dfb11d69219139d2d5c79a9cadb3639978
bigcode/the-stack
train
c17a1e1c495b2aca048869ae
train
function
def wait_for_ready_threaded(restype_name_list, timeout=300, exit_on_err=False): """ Wait for multiple delpoyments in a threaded fashion. Args: restype_name_list: list of tuples with (resource_type, resource_name,) timeout: timeout for each thread exit_on_err: when all threads finish...
def wait_for_ready_threaded(restype_name_list, timeout=300, exit_on_err=False):
""" Wait for multiple delpoyments in a threaded fashion. Args: restype_name_list: list of tuples with (resource_type, resource_name,) timeout: timeout for each thread exit_on_err: when all threads finish, if any failed, exit Returns: True if all deployments are ready ...
_loop=True, ) return True except (TimedOutError, StatusError): log.exception("Hit error waiting on '%s'", key) if exit_on_err: sys.exit(1) return False def wait_for_ready_threaded(restype_name_list, timeout=300, exit_on_err=False):
68
68
227
20
47
carbonin/ocdeployer
ocdeployer/utils.py
Python
wait_for_ready_threaded
wait_for_ready_threaded
380
410
380
380
21488b8701bc58280c4d4fd5fabfc5466d86ac1a
bigcode/the-stack
train
649cf97b40ea377a912228a2
train
function
def load_cfg_file(path): if not os.path.isfile(path): raise ValueError("Path '{}' is not a file or does not exist".format(path)) _, file_ext = os.path.splitext(path) with open(path, "rb") as f: if file_ext == ".yaml" or file_ext == ".yml": content = yaml.safe_load(f) el...
def load_cfg_file(path):
if not os.path.isfile(path): raise ValueError("Path '{}' is not a file or does not exist".format(path)) _, file_ext = os.path.splitext(path) with open(path, "rb") as f: if file_ext == ".yaml" or file_ext == ".yml": content = yaml.safe_load(f) elif file_ext == ".json": ...
(path, "*.yaml"))) files.extend(list(glob.glob(os.path.join(path, "*.yml")))) files.extend(list(glob.glob(os.path.join(path, "*.json")))) return [f for f in files if not os.path.basename(f).startswith("_cfg")] def load_cfg_file(path):
63
64
136
6
57
carbonin/ocdeployer
ocdeployer/utils.py
Python
load_cfg_file
load_cfg_file
90
107
90
90
fa8e7ccd19d62a17a1de6f5de5837af6f5f79335
bigcode/the-stack
train
cdd075d92caa2a2d9296491a
train
class
class HeatSinkFin2(HeatSinkCommon): def __init__(self,name,origin): self.name = name if not isinstance(origin,Base.Vector): raise RuntimeError("origin is not a Vector!") self.origin = origin zExtrude = Base.Vector(0,0,self._Thickness) yExtrude = Base.Vector(0,-sel...
class HeatSinkFin2(HeatSinkCommon):
def __init__(self,name,origin): self.name = name if not isinstance(origin,Base.Vector): raise RuntimeError("origin is not a Vector!") self.origin = origin zExtrude = Base.Vector(0,0,self._Thickness) yExtrude = Base.Vector(0,-self._Thickness,0) xExtrude = B...
.fuseto2D(bottom) top = Part.makePlane(self._HSDepth,self._HSLength,\ self.origin.add(Base.Vector(-(self._HSDepth+self._Thickness),0,self._Thickness+self._HSHeight*.8))).extrude(zExtrude) self.fuseto3D(top) top = Part.makePlane(self._HSDepth,self._HSLength,\ ...
124
125
418
10
114
RobertPHeller/RPi-RRCircuits
PocketBeagleCommandStation/HeatSink.py
Python
HeatSinkFin2
HeatSinkFin2
323
356
323
323
9de410e51c7f79a0b587cab11719ca2e8516e053
bigcode/the-stack
train
2f3e2d60ff1d84bb55d51f07
train
class
class HeatSinkMainPanel(HeatSinkCommon): def __init__(self,name,origin): self.name = name if not isinstance(origin,Base.Vector): raise RuntimeError("origin is not a Vector!") self.origin = origin zExtrude = Base.Vector(0,0,self._Thickness) yExtrude = Base.Vector(0...
class HeatSinkMainPanel(HeatSinkCommon):
def __init__(self,name,origin): self.name = name if not isinstance(origin,Base.Vector): raise RuntimeError("origin is not a Vector!") self.origin = origin zExtrude = Base.Vector(0,0,self._Thickness) yExtrude = Base.Vector(0,-self._Thickness,0) xExtrude = B...
def TO220_Holes2D(self,origin): zExtrude = Base.Vector(0,0,self._Thickness) q13_mh = origin.add(Base.Vector(self._TO220_3_MinHoleHeight-self._Thickness,self._Q13CenterOffset,0)) self.cutfrom2D(Part.Face(Part.Wire(\ Part.makeCircle(self._Number6Shoulder_Diameter/2,q13_mh)))\ ...
256
256
1,995
10
246
RobertPHeller/RPi-RRCircuits
PocketBeagleCommandStation/HeatSink.py
Python
HeatSinkMainPanel
HeatSinkMainPanel
144
280
144
144
e5dff8b28a568d9855e124e212c044376df9f312
bigcode/the-stack
train
4f851ef32142fd12b2a05c7b
train
class
class HeatSinkFin1(HeatSinkCommon): def __init__(self,name,origin): self.name = name if not isinstance(origin,Base.Vector): raise RuntimeError("origin is not a Vector!") self.origin = origin zExtrude = Base.Vector(0,0,self._Thickness) yExtrude = Base.Vector(0,-sel...
class HeatSinkFin1(HeatSinkCommon):
def __init__(self,name,origin): self.name = name if not isinstance(origin,Base.Vector): raise RuntimeError("origin is not a Vector!") self.origin = origin zExtrude = Base.Vector(0,0,self._Thickness) yExtrude = Base.Vector(0,-self._Thickness,0) xExtrude = B...
self.cutfrom2D(Part.Face(Part.Wire(\ Part.makeCircle(self._FanMHoleDiameter/2.0,fanm2)))\ .extrude(zExtrude)) fanCY = -((self._HSDepth/2.0)+self._FanTabExtension+self._Thickness) fanCX = (self._HSDepth/2.0) fanHole = origin.add(Base.Vector(fanCX,fanCY,0)) ...
149
149
499
10
139
RobertPHeller/RPi-RRCircuits
PocketBeagleCommandStation/HeatSink.py
Python
HeatSinkFin1
HeatSinkFin1
282
321
282
282
e5f038e1423297c1adc472077d94e4a5f4ad3d60
bigcode/the-stack
train
f461c4a20550e104ec26aaaf
train
class
class HeatSinkCommon(object): __metaclass__ = ABCMeta _MHoleDiameter = 3.5 _BoardEdgeMHOffset = 3.810 _MHoleSpacingY = 52.070 _BoardEdgeToDeviceMountPlane = 16.51 _HSLength = 78.74 _HSHeight = 25 _HSDepth = 25 _Thickness = .05*25.4 # Fan _FanThick = 10 _FanMHoleDiameter ...
class HeatSinkCommon(object):
__metaclass__ = ABCMeta _MHoleDiameter = 3.5 _BoardEdgeMHOffset = 3.810 _MHoleSpacingY = 52.070 _BoardEdgeToDeviceMountPlane = 16.51 _HSLength = 78.74 _HSHeight = 25 _HSDepth = 25 _Thickness = .05*25.4 # Fan _FanThick = 10 _FanMHoleDiameter = 2.8 _FanMHoleCenters = 2...
01379-9728 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope ...
256
256
1,076
6
249
RobertPHeller/RPi-RRCircuits
PocketBeagleCommandStation/HeatSink.py
Python
HeatSinkCommon
HeatSinkCommon
59
142
59
59
771e26e97d06a8562eeaff3af916d7332acb7231
bigcode/the-stack
train
4a7acaded6cf05165462e865
train
class
class HeatSink(HeatSinkCommon): def show3D(self): self.main.show3D() self.fin1.show3D() self.fin2.show3D() def show2D(self): self.main.show2D() self.fin1.show2D() self.fin2.show2D() def __init__(self,name,origin): self.name = name if not isinst...
class HeatSink(HeatSinkCommon):
def show3D(self): self.main.show3D() self.fin1.show3D() self.fin2.show3D() def show2D(self): self.main.show2D() self.fin1.show2D() self.fin2.show2D() def __init__(self,name,origin): self.name = name if not isinstance(origin,Base.Vector): ...
*1),self._HSLength,\ self.sheetorigin.add(Base.Vector(-(self._HSDepth-self._Thickness*1)+self._HSHeight*.4,0,0)))\ .extrude(zExtrude) self.fuseto2D(bottom) class HeatSink(HeatSinkCommon):
63
64
159
8
55
RobertPHeller/RPi-RRCircuits
PocketBeagleCommandStation/HeatSink.py
Python
HeatSink
HeatSink
358
374
358
358
1b763756255e9452746e8d6ec55d8e6c5ba85add
bigcode/the-stack
train
e78eb884d45fe6e89ce412e8
train
class
class ContourItem(Qt.QTreeWidgetItem): def __init__(self, cp, parentImage=None): self.cp = cp Qt.QTreeWidgetItem.__init__(self) self.paramCombo = pg.ComboBox() self.thresholdSpin = pg.SpinBox(value=0.98, dec=True, step=0.1) self.maxCheck = Qt.QCheckBox() self.colorBtn...
class ContourItem(Qt.QTreeWidgetItem):
def __init__(self, cp, parentImage=None): self.cp = cp Qt.QTreeWidgetItem.__init__(self) self.paramCombo = pg.ComboBox() self.thresholdSpin = pg.SpinBox(value=0.98, dec=True, step=0.1) self.maxCheck = Qt.QCheckBox() self.colorBtn = ColorButton(color=(255,255,255)) ...
) self.canvas.removeItem(item.curveItem) def setArgList(self, args): """Sets the list of variable names available for computing contours""" self.argList = args for i in self.items: i.updateParamCombo(self.argList) def addParamArg(self, arg): i...
182
184
615
10
172
campagnola/acq4
acq4/util/ContourPlotter/ContourPlotter.py
Python
ContourItem
ContourItem
85
154
85
85
2316f20647e16157f41a225cea4ed942e305bf83
bigcode/the-stack
train
aafd9bdd389b59da20b42a31
train
class
class ContourPlotter(Qt.QWidget): sigChanged = Qt.Signal() def __init__(self, canvas=None, host=None): Qt.QWidget.__init__(self) self.canvas = canvas self.ui = Ui_Form() self.ui.setupUi(self) self.addBtn = Qt.QPushButton('Add New') item = Q...
class ContourPlotter(Qt.QWidget):
sigChanged = Qt.Signal() def __init__(self, canvas=None, host=None): Qt.QWidget.__init__(self) self.canvas = canvas self.ui = Ui_Form() self.ui.setupUi(self) self.addBtn = Qt.QPushButton('Add New') item = Qt.QTreeWidgetItem() self.ui.tre...
from __future__ import print_function from acq4.util import Qt import pyqtgraph as pg from pyqtgraph.widgets.SpinBox import SpinBox from pyqtgraph.widgets.ColorButton import ColorButton Ui_Form = Qt.importTemplate('.ContourPlotterTemplate') class ContourPlotter(Qt.QWidget):
68
149
498
10
58
campagnola/acq4
acq4/util/ContourPlotter/ContourPlotter.py
Python
ContourPlotter
ContourPlotter
10
81
10
11
335ef6dd894bb7901049d765e4ff812d6ea84b41
bigcode/the-stack
train
82275079ec511a36f466ed65
train
function
def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ExampleSite.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's insta...
def main():
"""Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ExampleSite.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " ...
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main():
26
64
99
3
22
Dotrar/Kookaburra
manage.py
Python
main
main
7
18
7
7
a5023248f70b1de9cb96f6013d7690c50e4d1e64
bigcode/the-stack
train
3090be074f831482e8236a02
train
class
class BasicImportsTestCase(TestCase): def test_if_resello_client_can_be_imported_from_top_level(self): """ Library API docs say: >>> import resello >>> client = resello.ReselloClient(reference='...', api_key='...') This should be true. """ import resello ...
class BasicImportsTestCase(TestCase):
def test_if_resello_client_can_be_imported_from_top_level(self): """ Library API docs say: >>> import resello >>> client = resello.ReselloClient(reference='...', api_key='...') This should be true. """ import resello self.assertIn('ReselloClient', di...
from unittest import TestCase class BasicImportsTestCase(TestCase):
14
64
81
8
5
duct-tape/reselllo
tests/test_imports.py
Python
BasicImportsTestCase
BasicImportsTestCase
4
15
4
4
afb2af6ad7003362dade3e41fb03b425a8084dd7
bigcode/the-stack
train
a83da9c89a06a5b380b0507b
train
function
def v(version): ret = () for i in version: if i < 10: ret = ret + (chr(ord('0') + i),) else: ret = ret + (chr(ord('A') + i - 10),) return ret
def v(version):
ret = () for i in version: if i < 10: ret = ret + (chr(ord('0') + i),) else: ret = ret + (chr(ord('A') + i - 10),) return ret
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 import os import sys import glob import re version = (int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4])) def v(version):
63
64
61
4
59
hueyjj/libtorrent
tools/set_version.py
Python
v
v
12
19
12
12
65d9fed21fe309b9b461c2728aa9f9e6ee2a60ed
bigcode/the-stack
train
65e91683f6348761a2f94b20
train
function
def substitute_file(name): subst = '' f = open(name) for line in f: if '#define LIBTORRENT_VERSION_MAJOR' in line and name.endswith('.hpp'): line = '#define LIBTORRENT_VERSION_MAJOR %d\n' % version[0] elif '#define LIBTORRENT_VERSION_MINOR' in line and name.endswith('.hpp'): ...
def substitute_file(name):
subst = '' f = open(name) for line in f: if '#define LIBTORRENT_VERSION_MAJOR' in line and name.endswith('.hpp'): line = '#define LIBTORRENT_VERSION_MAJOR %d\n' % version[0] elif '#define LIBTORRENT_VERSION_MINOR' in line and name.endswith('.hpp'): line = '#define LIB...
#!/usr/bin/env python # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 import os import sys import glob import re version = (int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4])) def v(version): ret = () for i in version: if i < 10: ret = ret + (chr(ord('0') + i),)...
151
195
650
5
146
hueyjj/libtorrent
tools/set_version.py
Python
substitute_file
substitute_file
25
60
25
25
b69f85f854134e5e09d49d7fc5fdf848b695e86f
bigcode/the-stack
train
6b06451075472722f440e3f9
train
class
class CheckFailed(Exception): """ Raise this exception if one of the checks in main fails. """ def __init__(self, msg: str, status_type=None): super().__init__() self.msg = str(msg) self.status_type = status_type self.status = status_type(self.msg)
class CheckFailed(Exception):
""" Raise this exception if one of the checks in main fails. """ def __init__(self, msg: str, status_type=None): super().__init__() self.msg = str(msg) self.status_type = status_type self.status = status_type(self.msg)
Resource, OCIImageResourceError from ops.charm import CharmBase from ops.main import main from ops.model import ActiveStatus, BlockedStatus, MaintenanceStatus, WaitingStatus from serialized_data_interface import ( NoCompatibleVersions, NoVersionsListed, get_interfaces, ) class CheckFailed(Exception):
64
64
64
5
59
canonical/tensorboards-operator
charms/tensorboards-web-app/src/charm.py
Python
CheckFailed
CheckFailed
18
26
18
18
f7757b3dd45f8cf8f873988b7389ff99394c4820
bigcode/the-stack
train
c2e78ddb803d9c5477cb58bf
train
class
class Operator(CharmBase): def __init__(self, *args): super().__init__(*args) self.log = logging.getLogger(__name__) self.image = OCIImageResource(self, "oci-image") for event in [ self.on.install, self.on.upgrade_charm, self.on.config_changed, ...
class Operator(CharmBase):
def __init__(self, *args): super().__init__(*args) self.log = logging.getLogger(__name__) self.image = OCIImageResource(self, "oci-image") for event in [ self.on.install, self.on.upgrade_charm, self.on.config_changed, self.on["ingress...
#!/usr/bin/env python3 # Copyright 2021 Canonical Ltd. # See LICENSE file for licensing details. import logging from oci_image import OCIImageResource, OCIImageResourceError from ops.charm import CharmBase from ops.main import main from ops.model import ActiveStatus, BlockedStatus, MaintenanceStatus, WaitingStatus fr...
163
225
752
6
157
canonical/tensorboards-operator
charms/tensorboards-web-app/src/charm.py
Python
Operator
Operator
29
152
29
29
5b6700cfd53dea0983254ac3b8a6275196c219bd
bigcode/the-stack
train
09ff15763feb10aa381b7dee
train
class
class QuotasGroupsApi(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Ref: https://github.com/swagger-api/swagger-codegen """ def __init__(self, api_client=None): config = Configuration() if api_client: ...
class QuotasGroupsApi(object):
""" NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Ref: https://github.com/swagger-api/swagger-codegen """ def __init__(self, api_client=None): config = Configuration() if api_client: self.api_client = api_cl...
# coding: utf-8 """ Pure Storage FlashBlade REST 1.10 Python SDK Pure Storage FlashBlade REST 1.10 Python SDK, developed by [Pure Storage, Inc](http://www.purestorage.com/). Documentations can be found at [purity-fb.readthedocs.io](http://purity-fb.readthedocs.io/). OpenAPI spec version: 1.10 Contact...
172
256
4,870
7
164
mabdelhafez/purity_fb_python_client
purity_fb/purity_fb_1dot10/apis/quotas_groups_api.py
Python
QuotasGroupsApi
QuotasGroupsApi
27
520
27
27
ed264ae780ab16115bd0c6a4bb1e5d60aede9cbb
bigcode/the-stack
train
1d235f7f00a82d98bc3d4ada
train
class
class AuditableQueryset(models.query.QuerySet): def active(self): return self.filter(is_deleted=True)
class AuditableQueryset(models.query.QuerySet):
def active(self): return self.filter(is_deleted=True)
from django.db import models from core.middleware.thread_user import CuserMiddleware current_user = CuserMiddleware.get_user() class AuditableQueryset(models.query.QuerySet):
35
64
23
10
25
jonaqp/heroku
core/queryset.py
Python
AuditableQueryset
AuditableQueryset
8
10
8
8
6cb542fb28eddf877ebb482033b71f223c92899e
bigcode/the-stack
train
b4ccfa2004f1b84498698003
train
class
class AuditableManager(models.Manager): def get_queryset(self): return AuditableQueryset(model=self.model, using=self._db, hints=self._hints) def active(self): return self.get_queryset().active()
class AuditableManager(models.Manager):
def get_queryset(self): return AuditableQueryset(model=self.model, using=self._db, hints=self._hints) def active(self): return self.get_queryset().active()
# def force_delete(self): # return self.delete() # # def update(self, **kwargs): # kwargs['modified_on'] = datetime() # kwargs['modified_by'] = current_user # return self.update(**kwargs) class AuditableManager(models.Manager):
64
64
47
7
57
jonaqp/heroku
core/queryset.py
Python
AuditableManager
AuditableManager
27
32
27
27
1260649c6b7f456b5e4a698685ab0809f3ab202c
bigcode/the-stack
train
b07a2dbd33d922bc8b264d36
train
class
class CppHeaderParser(object): def __init__(self, generate_umat_decls=False, generate_gpumat_decls=False): self._generate_umat_decls = generate_umat_decls self._generate_gpumat_decls = generate_gpumat_decls self.BLOCK_TYPE = 0 self.BLOCK_NAME = 1 self.PROCESS_FLAG = 2 ...
class CppHeaderParser(object):
def __init__(self, generate_umat_decls=False, generate_gpumat_decls=False): self._generate_umat_decls = generate_umat_decls self._generate_gpumat_decls = generate_gpumat_decls self.BLOCK_TYPE = 0 self.BLOCK_NAME = 1 self.PROCESS_FLAG = 2 self.PUBLIC_SECTION = 3 ...
ib3d/include/opencv2/calib3d.hpp", "../../features2d/include/opencv2/features2d.hpp", "../../video/include/opencv2/video/tracking.hpp", "../../video/include/opencv2/video/background_segm.hpp", "../../objdetect/include/opencv2/objdetect.hpp", "../../imgcodecs/include/opencv2/imgcodecs.hpp", "../../videoio/include/opencv...
256
256
9,042
7
249
kimSungIn/opencv
modules/python/src2/hdr_parser.py
Python
CppHeaderParser
CppHeaderParser
34
1,025
34
35
dc9fc98655c2b35060a8eaeb2e5b98f3cce2d574
bigcode/the-stack
train
bac6e96b5840ba7cc8db1d36
train
function
def read_lscpu(path: str): cpu = CPU() output = get_output(path) tmp_freq = None sockets = 1 for line in output.splitlines(): if "Architecture:" in line: architecture = line.split("Architecture:")[1].strip() if architecture == 'x86_64': cpu.architecture = 'x86-64' if architecture in ('i686', 'i586...
def read_lscpu(path: str):
cpu = CPU() output = get_output(path) tmp_freq = None sockets = 1 for line in output.splitlines(): if "Architecture:" in line: architecture = line.split("Architecture:")[1].strip() if architecture == 'x86_64': cpu.architecture = 'x86-64' if architecture in ('i686', 'i586', 'i486', 'i386'): cpu...
#!/usr/bin/env python3 import sys from InputFileNotFoundError import InputFileNotFoundError """ Read "lscpu" output """ class CPU: def __init__(self): self.type = "cpu" self.architecture = "" self.model = "" self.brand = "" self.n_cores = -1 # core-n on TARALLO self.n_threads = -1 # thread-n on TARA...
136
256
904
9
126
sofymunari/peracotta
read_lscpu.py
Python
read_lscpu
read_lscpu
24
117
24
24
311430f0ce558d3ff6e8907cdb973b7669aa0b73
bigcode/the-stack
train
eb5d5f858a8260d890652bcc
train
function
def get_output(path): try: with open(path, 'r') as f: output = f.read() except FileNotFoundError: raise InputFileNotFoundError(path) return output
def get_output(path):
try: with open(path, 'r') as f: output = f.read() except FileNotFoundError: raise InputFileNotFoundError(path) return output
.n_cores, "thread-n": cpu.n_threads, "frequency-hertz": cpu.frequency, "human_readable_frequency": cpu.human_readable_frequency, } if sockets > 1: result = [result] * sockets return result def get_output(path):
64
64
42
5
58
sofymunari/peracotta
read_lscpu.py
Python
get_output
get_output
120
126
120
120
c7c1e9bff8a34828f110b6c185a630ce7fe11777
bigcode/the-stack
train
b69147c8810df449cab2390a
train
class
class CPU: def __init__(self): self.type = "cpu" self.architecture = "" self.model = "" self.brand = "" self.n_cores = -1 # core-n on TARALLO self.n_threads = -1 # thread-n on TARALLO self.frequency = -1 self.human_readable_frequency = "N/A" # TODO: calculate it or remove it
class CPU:
def __init__(self): self.type = "cpu" self.architecture = "" self.model = "" self.brand = "" self.n_cores = -1 # core-n on TARALLO self.n_threads = -1 # thread-n on TARALLO self.frequency = -1 self.human_readable_frequency = "N/A" # TODO: calculate it or remove it
#!/usr/bin/env python3 import sys from InputFileNotFoundError import InputFileNotFoundError """ Read "lscpu" output """ class CPU:
36
64
94
3
33
sofymunari/peracotta
read_lscpu.py
Python
CPU
CPU
12
21
12
12
719d01f8748e010c1c73defc9943a66c51e24782
bigcode/the-stack
train
1cf3b941707359a052726d50
train
function
@pytest.fixture(scope='function') async def api_client(api_test_config: APITestSessionConfig): session_client = APISessionClient(api_test_config.base_uri) yield session_client await session_client.close()
@pytest.fixture(scope='function') async def api_client(api_test_config: APITestSessionConfig):
session_client = APISessionClient(api_test_config.base_uri) yield session_client await session_client.close()
import pytest from api_test_utils.api_session_client import APISessionClient from api_test_utils.api_test_session_config import APITestSessionConfig @pytest.fixture(scope='function') async def api_client(api_test_config: APITestSessionConfig):
49
64
44
19
29
uk-gov-mirror/nhsdigital.apim-test-utils
api_test_utils/fixtures.py
Python
api_client
api_client
7
14
7
9
d620a46c44c9550e6daec8411a660a6e48d4169b
bigcode/the-stack
train
9b27fb7dfa1c319284de5561
train
function
def generate_results(file): clean_gt_file = file.replace("source", "target") source_image = preprocess(file) noise_ground_truth = keras.utils.array_to_img(denormalize(source_image)) clean_ground_truth = keras.utils.array_to_img( denormalize(preprocess(clean_gt_file)) ) source_image = tf...
def generate_results(file):
clean_gt_file = file.replace("source", "target") source_image = preprocess(file) noise_ground_truth = keras.utils.array_to_img(denormalize(source_image)) clean_ground_truth = keras.utils.array_to_img( denormalize(preprocess(clean_gt_file)) ) source_image = tf.expand_dims(source_image, a...
_image) noiseimage_ocr_out = pytesseract.image_to_string(noise_image) predimage_ocr_out = pytesseract.image_to_string(prediction_image) noise_WER_score = fastwer.score_sent(noiseimage_ocr_out, reference) pred_WER_score = fastwer.score_sent(predimage_ocr_out, reference) return noise_WER_score, pred_W...
90
90
302
5
84
anish9/keras-io
examples/vision/text_image_denoiser.py
Python
generate_results
generate_results
259
288
259
259
ffa40f2de69a396b948508c9fafda8d2d5a23aba
bigcode/the-stack
train
e1103af9483bd7c6c1dace01
train
function
def denormalize(img_array): img_array += 1 img_array *= 127.5 return img_array
def denormalize(img_array):
img_array += 1 img_array *= 127.5 return img_array
image = tf.io.decode_png(tf.io.read_file(image), channels=3) image = tf.image.resize_with_pad( image=image, target_height=HEIGHT, target_width=WIDTH ) image = resnet_v2.preprocess_input(image) return image def denormalize(img_array):
64
64
28
7
56
anish9/keras-io
examples/vision/text_image_denoiser.py
Python
denormalize
denormalize
99
102
99
99
93f02d0d99668ceb41818d3a5e63eab5df0542ec
bigcode/the-stack
train
fff03520d5e2420116bda940
train
function
def upscale_unit(previous_input, current_input, target_channels=3, upscale_ratio=2): previous_low_scale = subpixel_upsample( previous_input, target_channels=target_channels, upscale_ratio=upscale_ratio ) current_high_scale = conv_unit(current_input, filters=target_channels) concat_scales = tf.co...
def upscale_unit(previous_input, current_input, target_channels=3, upscale_ratio=2):
previous_low_scale = subpixel_upsample( previous_input, target_channels=target_channels, upscale_ratio=upscale_ratio ) current_high_scale = conv_unit(current_input, filters=target_channels) concat_scales = tf.concat((previous_low_scale, current_high_scale), axis=-1) feature_manifold = conv_u...
= keras.layers.BatchNormalization()(x) x = keras.layers.LeakyReLU(0.2)(x) x = tf.nn.depth_to_space(x, block_size=upscale_ratio) return x def upscale_unit(previous_input, current_input, target_channels=3, upscale_ratio=2):
64
64
107
19
44
anish9/keras-io
examples/vision/text_image_denoiser.py
Python
upscale_unit
upscale_unit
161
168
161
161
6d21a01747b554bdc89c0dca4f30947457ed4625
bigcode/the-stack
train
1cc8f9c4e20e38b5b07dc57b
train
function
def get_callbacks(early_stopping_patience, best_ckpt_name): early_stop = keras.callbacks.EarlyStopping(patience=early_stopping_patience) model_ckpt = keras.callbacks.ModelCheckpoint( best_ckpt_name, save_best_only=True, save_weights_only=True, verbose=1 ) return [early_stop, model_ckpt]
def get_callbacks(early_stopping_patience, best_ckpt_name):
early_stop = keras.callbacks.EarlyStopping(patience=early_stopping_patience) model_ckpt = keras.callbacks.ModelCheckpoint( best_ckpt_name, save_best_only=True, save_weights_only=True, verbose=1 ) return [early_stop, model_ckpt]
.Conv2D(3, 5, padding="same", activation="sigmoid")(decode3) denoiser_model = keras.Model(base_model.input, out_conv, name="denoiser") return denoiser_model def get_callbacks(early_stopping_patience, best_ckpt_name):
64
64
76
15
48
anish9/keras-io
examples/vision/text_image_denoiser.py
Python
get_callbacks
get_callbacks
196
201
196
196
68d7b17a90e02399817a36329245a0b0248f0f1a
bigcode/the-stack
train
e2b1d95257f84e753b5aef67
train
function
def conv_unit(x, filters=64, padding="same"): x = keras.layers.Conv2D(filters=filters, kernel_size=3, padding=padding)(x) x = keras.layers.BatchNormalization()(x) x = keras.layers.Activation("relu")(x) return x
def conv_unit(x, filters=64, padding="same"):
x = keras.layers.Conv2D(filters=filters, kernel_size=3, padding=padding)(x) x = keras.layers.BatchNormalization()(x) x = keras.layers.Activation("relu")(x) return x
. In the Decoder part we use **Skip-Connection** and ```Sub-Pixel Layer``` forming the Upscaling path of U-Net. The model on its design aspect is kept light-weight with just **2.7 million** parameters. """ def conv_unit(x, filters=64, padding="same"):
64
64
62
13
51
anish9/keras-io
examples/vision/text_image_denoiser.py
Python
conv_unit
conv_unit
145
149
145
145
a5ab2aa606b6ccca05be8ad45f2c8ee5922abe89
bigcode/the-stack
train
be2da861cf42a5e3fd44042d
train
function
def word_error_rate(noise_image, reference_image, prediction_image): reference = pytesseract.image_to_string(reference_image) noiseimage_ocr_out = pytesseract.image_to_string(noise_image) predimage_ocr_out = pytesseract.image_to_string(prediction_image) noise_WER_score = fastwer.score_sent(noiseimage_oc...
def word_error_rate(noise_image, reference_image, prediction_image):
reference = pytesseract.image_to_string(reference_image) noiseimage_ocr_out = pytesseract.image_to_string(noise_image) predimage_ocr_out = pytesseract.image_to_string(prediction_image) noise_WER_score = fastwer.score_sent(noiseimage_ocr_out, reference) pred_WER_score = fastwer.score_sent(predimage_o...
a metric to evaluate the real-world performance. The following function ```generate_results``` will help plot the visual comparisons of outputs given the **raw noisy input** and **model restored input** to tesseract OCR engine. """ def word_error_rate(noise_image, reference_image, prediction_image):
64
64
109
14
50
anish9/keras-io
examples/vision/text_image_denoiser.py
Python
word_error_rate
word_error_rate
250
256
250
250
7aa917818603934239f4cd465dc80a0b6647f2ad
bigcode/the-stack
train
bd6e9e5a2dbff2411e669cb1
train
function
def preprocess(image): image = tf.io.decode_png(tf.io.read_file(image), channels=3) image = tf.image.resize_with_pad( image=image, target_height=HEIGHT, target_width=WIDTH ) image = resnet_v2.preprocess_input(image) return image
def preprocess(image):
image = tf.io.decode_png(tf.io.read_file(image), channels=3) image = tf.image.resize_with_pad( image=image, target_height=HEIGHT, target_width=WIDTH ) image = resnet_v2.preprocess_input(image) return image
"))[-80:] # height and width are chosen in a way that image features are not distorted. HEIGHT, WIDTH = 352, 608 BATCH_SIZE = 4 BUFFER_SIZE = int(len(train_source) * 0.2) AUTO = tf.data.AUTOTUNE def preprocess(image):
64
64
62
4
59
anish9/keras-io
examples/vision/text_image_denoiser.py
Python
preprocess
preprocess
90
96
90
90
b04c1a63dbe1b359fe07fe1ad3a4b0143664ae6f
bigcode/the-stack
train
0e50d3fdf9b20d4bdbd53012
train
function
def denoiser(height, width): base_model = resnet_v2.ResNet50V2( include_top=False, weights="imagenet", input_shape=(height, width, 3) ) encode0 = base_model.get_layer("input_1").output # (None,352,608,3) encode1 = base_model.get_layer("conv1_conv").output # (None,176,304,64) encode2 = base...
def denoiser(height, width):
base_model = resnet_v2.ResNet50V2( include_top=False, weights="imagenet", input_shape=(height, width, 3) ) encode0 = base_model.get_layer("input_1").output # (None,352,608,3) encode1 = base_model.get_layer("conv1_conv").output # (None,176,304,64) encode2 = base_model.get_layer("conv2_block...
( previous_input, target_channels=target_channels, upscale_ratio=upscale_ratio ) current_high_scale = conv_unit(current_input, filters=target_channels) concat_scales = tf.concat((previous_low_scale, current_high_scale), axis=-1) feature_manifold = conv_unit(concat_scales, filters=target_channels...
86
86
288
8
77
anish9/keras-io
examples/vision/text_image_denoiser.py
Python
denoiser
denoiser
171
193
171
171
ed690437675f03e982be3919233f9fb7c2b33e80
bigcode/the-stack
train