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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cb2a4e9c5aaf02e5cce73019 | train | function | def test_empty_list_array():
array = ak._v2.Array([[], [], []])
data_frame = ak._v2.to_rdataframe({"empty_list_array": array})
assert data_frame.GetColumnType("empty_list_array") == "ROOT::VecOps::RVec<double>"
assert data_frame.Count().GetValue() == 3
| def test_empty_list_array():
| array = ak._v2.Array([[], [], []])
data_frame = ak._v2.to_rdataframe({"empty_list_array": array})
assert data_frame.GetColumnType("empty_list_array") == "ROOT::VecOps::RVec<double>"
assert data_frame.Count().GetValue() == 3
| _empty_array():
array = ak._v2.Array([])
data_frame = ak._v2.to_rdataframe({"empty_array": array})
assert data_frame.GetColumnType("empty_array") == "double"
assert data_frame.Count().GetValue() == 0
def test_empty_list_array():
| 64 | 64 | 74 | 6 | 57 | jpivarski/awkward-1.0 | tests/v2/test_1374-to-rdataframe.py | Python | test_empty_list_array | test_empty_list_array | 288 | 292 | 288 | 288 | 2cd5e4360bb34f881bf4ffbb2275b08bc3cb7605 | bigcode/the-stack | train |
cb5ba297f3253680c3016cb8 | train | function | def test_empty_array():
array = ak._v2.Array([])
data_frame = ak._v2.to_rdataframe({"empty_array": array})
assert data_frame.GetColumnType("empty_array") == "double"
assert data_frame.Count().GetValue() == 0
| def test_empty_array():
| array = ak._v2.Array([])
data_frame = ak._v2.to_rdataframe({"empty_array": array})
assert data_frame.GetColumnType("empty_array") == "double"
assert data_frame.Count().GetValue() == 0
| done is True
f_one = ROOT.check_one[data_frame.GetColumnType("one")]()
f_two = ROOT.check_two[data_frame.GetColumnType("two")]()
data_frame.Foreach(f_one, ["one"])
data_frame.Foreach(f_two, ["two"])
def test_empty_array():
| 63 | 64 | 60 | 5 | 58 | jpivarski/awkward-1.0 | tests/v2/test_1374-to-rdataframe.py | Python | test_empty_array | test_empty_array | 281 | 285 | 281 | 281 | fb9e0e1b0fbfc923f9914a581fa5aa4b8bafb1c7 | bigcode/the-stack | train |
2207fedb1a1e99a7f3ef7fd4 | train | function | def test_list_array():
ak_array = ak._v2.Array([[1.1], [2.2, 3.3, 4.4], [5.5, 6.6]])
data_frame = ak._v2.to_rdataframe({"x": ak_array})
assert data_frame.GetColumnType("x") == "ROOT::VecOps::RVec<double>"
done = compiler(
"""
int64_t row = 0;
ROOT::VecOps::RVec<ROOT::VecOps::... | def test_list_array():
| ak_array = ak._v2.Array([[1.1], [2.2, 3.3, 4.4], [5.5, 6.6]])
data_frame = ak._v2.to_rdataframe({"x": ak_array})
assert data_frame.GetColumnType("x") == "ROOT::VecOps::RVec<double>"
done = compiler(
"""
int64_t row = 0;
ROOT::VecOps::RVec<ROOT::VecOps::RVec<double>> row_vals ... | [iy++]);
}}
}};
"""
)
assert done is True
f_x = ROOT.CheckX[data_frame.GetColumnType("x")]()
f_y = ROOT.CheckY[data_frame.GetColumnType("y")]()
data_frame.Foreach(f_x, ["x"])
data_frame.Foreach(f_y, ["y"])
def test_list_array():
| 77 | 78 | 263 | 5 | 72 | jpivarski/awkward-1.0 | tests/v2/test_1374-to-rdataframe.py | Python | test_list_array | test_list_array | 80 | 111 | 80 | 80 | 07d68fd6d1a87910f32d056e1c7e72277c0ad406 | bigcode/the-stack | train |
131c5ab5ce9be2447be156a5 | train | function | def test_jims_example1():
array = ak._v2.Array([{"x": 1.1}, {"x": 2.2}, {"x": 3.3}, {"x": 4.4}, {"x": 5.5}])
data_frame = ak._v2.to_rdataframe({"some_array": array})
assert set(data_frame.GetColumnNames()) == {"some_array"}
data_frame_y = data_frame.Define("y", "some_array.x()")
assert set(data_fram... | def test_jims_example1():
| array = ak._v2.Array([{"x": 1.1}, {"x": 2.2}, {"x": 3.3}, {"x": 4.4}, {"x": 5.5}])
data_frame = ak._v2.to_rdataframe({"some_array": array})
assert set(data_frame.GetColumnNames()) == {"some_array"}
data_frame_y = data_frame.Define("y", "some_array.x()")
assert set(data_frame_y.GetColumnNames()) == {... | Value() == 5
data_frame2 = data_frame.Filter("one > 2.5")
data_frame2_transformed = ROOT.MyTransformation[data_frame.GetColumnType("one")](
ROOT.RDF.AsRNode(data_frame2)
)
assert data_frame2_transformed.Count().GetValue() == 3
def test_jims_example1():
| 77 | 77 | 259 | 7 | 69 | jpivarski/awkward-1.0 | tests/v2/test_1374-to-rdataframe.py | Python | test_jims_example1 | test_jims_example1 | 194 | 220 | 194 | 194 | 83d3d304b2b98d9c83d808c94d96224cfe4bde52 | bigcode/the-stack | train |
cf3699ba1ff0b20fe47b51ca | train | function | def test_two_columns_as_vecs():
ak_array_1 = ak._v2.Array([1.1, 2.2, 3.3, 4.4, 5.5])
ak_array_2 = ak._v2.Array(
[{"x": 1.1}, {"x": 2.2}, {"x": 3.3}, {"x": 4.4}, {"x": 5.5}]
)
data_frame = ak._v2.operations.to_rdataframe(
{"x": ak_array_1, "y": ak_array_2}, flatlist_as_rvec=False
)
... | def test_two_columns_as_vecs():
| ak_array_1 = ak._v2.Array([1.1, 2.2, 3.3, 4.4, 5.5])
ak_array_2 = ak._v2.Array(
[{"x": 1.1}, {"x": 2.2}, {"x": 3.3}, {"x": 4.4}, {"x": 5.5}]
)
data_frame = ak._v2.operations.to_rdataframe(
{"x": ak_array_1, "y": ak_array_2}, flatlist_as_rvec=False
)
assert set(data_frame.GetColu... | 4.4 },
{ 5.5, 6.6 }
};
template<typename T>
struct MyFunctor_RVec {
void operator()(T const& x) {
for( int64_t j = 0; j < x.size(); j++ ) {
R__ASSERT(x[j] == row_vals[row][j]);
}
row++;
}
... | 131 | 132 | 443 | 8 | 123 | jpivarski/awkward-1.0 | tests/v2/test_1374-to-rdataframe.py | Python | test_two_columns_as_vecs | test_two_columns_as_vecs | 114 | 159 | 114 | 114 | 9ee448f93e4fbdba9aa0803c792f8b674e251da8 | bigcode/the-stack | train |
c3461c4c436e5ea5ae56fc5e | train | function | def test_two_columns_transform_filter():
example1 = ak._v2.Array([1.1, 2.2, 3.3, 4.4, 5.5])
example2 = ak._v2.Array(
[{"x": 1.1}, {"x": 2.2}, {"x": 3.3}, {"x": 4.4}, {"x": 5.5}]
)
data_frame = ak._v2.to_rdataframe({"one": example1, "two": example2})
assert set(data_frame.GetColumnNames()) =... | def test_two_columns_transform_filter():
| example1 = ak._v2.Array([1.1, 2.2, 3.3, 4.4, 5.5])
example2 = ak._v2.Array(
[{"x": 1.1}, {"x": 2.2}, {"x": 3.3}, {"x": 4.4}, {"x": 5.5}]
)
data_frame = ak._v2.to_rdataframe({"one": example1, "two": example2})
assert set(data_frame.GetColumnNames()) == {"one", "two"}
compiler(
"... | R__ASSERT(y.x() == yv_val[i_yv++]);
}}
}};
"""
)
assert done is True
f_x = ROOT.MyFunctorX_Vec[data_frame.GetColumnType("x")]()
f_y = ROOT.MyFunctorY_Vec[data_frame.GetColumnType("y")]()
data_frame.Foreach(f_x, ["x"])
data_frame.Foreach(f_y, ["y"])
def test_two_col... | 96 | 97 | 326 | 7 | 89 | jpivarski/awkward-1.0 | tests/v2/test_1374-to-rdataframe.py | Python | test_two_columns_transform_filter | test_two_columns_transform_filter | 162 | 191 | 162 | 162 | 6e3904f0bf3cd743bb44bb3bb357dd72d4141053 | bigcode/the-stack | train |
55afdad22331dc8964ecf61d | train | class | class AutoEmailReport(Document):
def autoname(self):
self.name = _(self.report)
if frappe.db.exists('Auto Email Report', self.name):
self.name = append_number_if_name_exists('Auto Email Report', self.name)
def validate(self):
self.validate_report_count()
self.validate_emails()
self.validate_report_forma... | class AutoEmailReport(Document):
| def autoname(self):
self.name = _(self.report)
if frappe.db.exists('Auto Email Report', self.name):
self.name = append_number_if_name_exists('Auto Email Report', self.name)
def validate(self):
self.validate_report_count()
self.validate_emails()
self.validate_report_format()
def validate_emails(self):
... | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import calendar
from datetime import timedelta
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.utils i... | 153 | 256 | 1,283 | 6 | 146 | this-gavagai/frappe | frappe/email/doctype/auto_email_report/auto_email_report.py | Python | AutoEmailReport | AutoEmailReport | 22 | 178 | 22 | 22 | a39a0556c34c21f0670a15f9e65133f63a958831 | bigcode/the-stack | train |
e8401783d16f8b21487f3d76 | train | function | def send_daily():
'''Check reports to be sent daily'''
current_day = calendar.day_name[now_datetime().weekday()]
enabled_reports = frappe.get_all('Auto Email Report',
filters={'enabled': 1, 'frequency': ('in', ('Daily', 'Weekdays', 'Weekly'))})
for report in enabled_reports:
auto_email_report = frappe.get_doc... | def send_daily():
| '''Check reports to be sent daily'''
current_day = calendar.day_name[now_datetime().weekday()]
enabled_reports = frappe.get_all('Auto Email Report',
filters={'enabled': 1, 'frequency': ('in', ('Daily', 'Weekdays', 'Weekly'))})
for report in enabled_reports:
auto_email_report = frappe.get_doc('Auto Email Repor... | "download"
frappe.local.response.filename = auto_email_report.get_file_name()
@frappe.whitelist()
def send_now(name):
'''Send Auto Email report now'''
auto_email_report = frappe.get_doc('Auto Email Report', name)
auto_email_report.check_permission()
auto_email_report.send()
def send_daily():
| 64 | 64 | 183 | 4 | 60 | this-gavagai/frappe | frappe/email/doctype/auto_email_report/auto_email_report.py | Python | send_daily | send_daily | 202 | 222 | 202 | 202 | 2b3f6907f26ab6c4f22b937d7167b3ba42ef1ea3 | bigcode/the-stack | train |
40e2d84599a26280d826b6e3 | train | function | def send_monthly():
'''Check reports to be sent monthly'''
for report in frappe.get_all('Auto Email Report', {'enabled': 1, 'frequency': 'Monthly'}):
frappe.get_doc('Auto Email Report', report.name).send()
| def send_monthly():
| '''Check reports to be sent monthly'''
for report in frappe.get_all('Auto Email Report', {'enabled': 1, 'frequency': 'Monthly'}):
frappe.get_doc('Auto Email Report', report.name).send()
| .frequency == 'Weekly':
if auto_email_report.day_of_week != current_day:
continue
try:
auto_email_report.send()
except Exception as e:
frappe.log_error(e, _('Failed to send {0} Auto Email Report').format(auto_email_report.name))
def send_monthly():
| 64 | 64 | 53 | 5 | 59 | this-gavagai/frappe | frappe/email/doctype/auto_email_report/auto_email_report.py | Python | send_monthly | send_monthly | 225 | 228 | 225 | 225 | 72c7fdcbc6aa573e0c30c7c43c22d2abc76b4266 | bigcode/the-stack | train |
bd03eeda9271876631785188 | train | function | @frappe.whitelist()
def download(name):
'''Download report locally'''
auto_email_report = frappe.get_doc('Auto Email Report', name)
auto_email_report.check_permission()
data = auto_email_report.get_report_content()
if not data:
frappe.msgprint(_('No Data'))
return
frappe.local.response.filecontent = data
f... | @frappe.whitelist()
def download(name):
| '''Download report locally'''
auto_email_report = frappe.get_doc('Auto Email Report', name)
auto_email_report.check_permission()
data = auto_email_report.get_report_content()
if not data:
frappe.msgprint(_('No Data'))
return
frappe.local.response.filecontent = data
frappe.local.response.type = "download"
... | = message,
attachments = attachments,
reference_doctype = self.doctype,
reference_name = self.name
)
def dynamic_date_filters_set(self):
return self.dynamic_date_period and self.from_date_field and self.to_date_field
@frappe.whitelist()
def download(name):
| 64 | 64 | 92 | 10 | 53 | this-gavagai/frappe | frappe/email/doctype/auto_email_report/auto_email_report.py | Python | download | download | 180 | 193 | 180 | 181 | 1bc14106dde4874a31f8806b065e71e06256e82f | bigcode/the-stack | train |
709b944a9b56af724b2d8145 | train | function | def update_field_types(columns):
for col in columns:
if col.fieldtype in ("Link", "Dynamic Link", "Currency") and col.options != "Currency":
col.fieldtype = "Data"
col.options = ""
return columns | def update_field_types(columns):
| for col in columns:
if col.fieldtype in ("Link", "Dynamic Link", "Currency") and col.options != "Currency":
col.fieldtype = "Data"
col.options = ""
return columns | ) and row.get(col.options):
row[col.fieldname] = get_link_to_form(row[col.options], row[col.fieldname])
elif col.fieldtype == "Currency":
row[col.fieldname] = frappe.format_value(row[col.fieldname], col)
return columns, data
def update_field_types(columns):
| 64 | 64 | 51 | 6 | 57 | this-gavagai/frappe | frappe/email/doctype/auto_email_report/auto_email_report.py | Python | update_field_types | update_field_types | 244 | 249 | 244 | 244 | f740246ffb52e7c363973275398e7e160a9e27fb | bigcode/the-stack | train |
e542876bf8ba4db916e05a8e | train | function | def make_links(columns, data):
for row in data:
for col in columns:
if col.fieldtype == "Link" and col.options != "Currency":
if col.options and row.get(col.fieldname):
row[col.fieldname] = get_link_to_form(col.options, row[col.fieldname])
elif col.fieldtype == "Dynamic Link":
if col.options and r... | def make_links(columns, data):
| for row in data:
for col in columns:
if col.fieldtype == "Link" and col.options != "Currency":
if col.options and row.get(col.fieldname):
row[col.fieldname] = get_link_to_form(col.options, row[col.fieldname])
elif col.fieldtype == "Dynamic Link":
if col.options and row.get(col.fieldname) and row.g... | _email_report.name))
def send_monthly():
'''Check reports to be sent monthly'''
for report in frappe.get_all('Auto Email Report', {'enabled': 1, 'frequency': 'Monthly'}):
frappe.get_doc('Auto Email Report', report.name).send()
def make_links(columns, data):
| 64 | 64 | 142 | 7 | 57 | this-gavagai/frappe | frappe/email/doctype/auto_email_report/auto_email_report.py | Python | make_links | make_links | 230 | 242 | 230 | 230 | b894e1092e5b9e5ce9220e295872d0b6e8e76508 | bigcode/the-stack | train |
77292fd174fe24bc509bcdba | train | function | @frappe.whitelist()
def send_now(name):
'''Send Auto Email report now'''
auto_email_report = frappe.get_doc('Auto Email Report', name)
auto_email_report.check_permission()
auto_email_report.send()
| @frappe.whitelist()
def send_now(name):
| '''Send Auto Email report now'''
auto_email_report = frappe.get_doc('Auto Email Report', name)
auto_email_report.check_permission()
auto_email_report.send()
| _email_report.get_report_content()
if not data:
frappe.msgprint(_('No Data'))
return
frappe.local.response.filecontent = data
frappe.local.response.type = "download"
frappe.local.response.filename = auto_email_report.get_file_name()
@frappe.whitelist()
def send_now(name):
| 64 | 64 | 44 | 11 | 53 | this-gavagai/frappe | frappe/email/doctype/auto_email_report/auto_email_report.py | Python | send_now | send_now | 195 | 200 | 195 | 196 | f232b3eb63a1add8640faeec942f230cf999a18b | bigcode/the-stack | train |
dd70b08122e9f60623a522a8 | train | function | def test_time_optimize(args, model, meta_state_dict, tto_view):
"""
quicky optimize the meta trained model to a target appearance
and return the corresponding network weights
"""
model.load_state_dict(meta_state_dict)
optim = torch.optim.SGD(model.parameters(), args.tto_lr)
pixels ... | def test_time_optimize(args, model, meta_state_dict, tto_view):
| """
quicky optimize the meta trained model to a target appearance
and return the corresponding network weights
"""
model.load_state_dict(meta_state_dict)
optim = torch.optim.SGD(model.parameters(), args.tto_lr)
pixels = tto_view['img'].reshape(-1, 3)
rays_o, rays_d = get_rays_t... | import copy
import numpy as np
import imageio
import torch
import torch.nn.functional as F
from models.rendering import get_rays_tourism, sample_points, volume_render
def test_time_optimize(args, model, meta_state_dict, tto_view):
| 57 | 97 | 324 | 17 | 39 | ThisIsIsaac/nerf-meta | utils/tour_video.py | Python | test_time_optimize | test_time_optimize | 9 | 40 | 9 | 9 | e588698fa7cd6ed66c5b99e816ecbeb634e0b1fc | bigcode/the-stack | train |
6cc29d5635e7d4979ccb9f1c | train | function | def interpolate_views(args, model, prev, next):
"""
generate new views by interpolating between aspect ratio,
focal length, camera pose and scene appearance of two views
"""
synth_views = []
for t in np.linspace(0, 1, 60):
H = int(prev['H']*(1-t) + next['H']*t)
W = int(prev['W']... | def interpolate_views(args, model, prev, next):
| """
generate new views by interpolating between aspect ratio,
focal length, camera pose and scene appearance of two views
"""
synth_views = []
for t in np.linspace(0, 1, 60):
H = int(prev['H']*(1-t) + next['H']*t)
W = int(prev['W']*(1-t) + next['W']*t)
focal = prev['foca... | _batchsize):
rgbs_batch, sigmas_batch = model(xyz[i:i+args.test_batchsize])
color_batch = volume_render(rgbs_batch, sigmas_batch, t_vals[i:i+args.test_batchsize])
synth.append(color_batch)
synth = torch.cat(synth, dim=0).reshape(H, W, 3)
return synth
def interpolate_views... | 89 | 89 | 298 | 11 | 77 | ThisIsIsaac/nerf-meta | utils/tour_video.py | Python | interpolate_views | interpolate_views | 64 | 88 | 64 | 64 | 232195d4888f207a7abf22b1b73b2f4cfac286a9 | bigcode/the-stack | train |
7e5adb638f60730703c257e5 | train | function | def resize_video(video_frames, max_H, max_W):
"""
downsample the frames by two and pad the frame boundaries
to have the same shape
Note: downsampling is done without anti-aliasing
"""
max_H = max_H//2 + 5 # add a five pixel margin
max_W = max_W//2 + 5
padded_frames = []
for frame i... | def resize_video(video_frames, max_H, max_W):
| """
downsample the frames by two and pad the frame boundaries
to have the same shape
Note: downsampling is done without anti-aliasing
"""
max_H = max_H//2 + 5 # add a five pixel margin
max_W = max_W//2 + 5
padded_frames = []
for frame in video_frames:
frame = frame[::2, ::2... | name in next['state_dict']
}
model.load_state_dict(state_dict)
view = synthesize_view(args, model, H, W, kinv, pose, bound)
synth_views.append(view.cpu().numpy())
return synth_views
def resize_video(video_frames, max_H, max_W):
| 64 | 64 | 205 | 12 | 51 | ThisIsIsaac/nerf-meta | utils/tour_video.py | Python | resize_video | resize_video | 91 | 113 | 91 | 91 | 08130ffcf77b8de208fec92e27ed459fd5dfa68f | bigcode/the-stack | train |
cde2eca59b1c510d56a1c134 | train | function | def synthesize_view(args, model, H, W, kinv, pose, bound):
"""
given camera intrinsics and camera pose, synthesize a novel view
"""
rays_o, rays_d = get_rays_tourism(H, W, kinv, pose)
rays_o, rays_d = rays_o.reshape(-1, 3), rays_d.reshape(-1, 3)
t_vals, xyz = sample_points(rays_o, rays_d, bound... | def synthesize_view(args, model, H, W, kinv, pose, bound):
| """
given camera intrinsics and camera pose, synthesize a novel view
"""
rays_o, rays_d = get_rays_tourism(H, W, kinv, pose)
rays_o, rays_d = rays_o.reshape(-1, 3), rays_d.reshape(-1, 3)
t_vals, xyz = sample_points(rays_o, rays_d, bound[0], bound[1],
args.num_sam... | colors = volume_render(rgbs, sigmas, t_vals)
loss = F.mse_loss(colors, pixelbatch)
loss.backward()
optim.step()
state_dict = copy.deepcopy(model.state_dict())
return state_dict
def synthesize_view(args, model, H, W, kinv, pose, bound):
| 68 | 69 | 230 | 19 | 48 | ThisIsIsaac/nerf-meta | utils/tour_video.py | Python | synthesize_view | synthesize_view | 43 | 61 | 43 | 43 | 7640dfa05b7331ffca860120bef750e3e08fac6a | bigcode/the-stack | train |
badd6548aff0d531e7a1f315 | train | function | def create_interpolation_video(args, model, meta_state_dict, test_set, device):
"""
create interpolation video like the original project demo
https://www.matthewtancik.com/learnit
"""
heights = []
widths = []
view_idx = args.interpolate[0]
img, pose, kinv, bound = test_set[view_idx]
... | def create_interpolation_video(args, model, meta_state_dict, test_set, device):
| """
create interpolation video like the original project demo
https://www.matthewtancik.com/learnit
"""
heights = []
widths = []
view_idx = args.interpolate[0]
img, pose, kinv, bound = test_set[view_idx]
prev = {}
prev['view_idx'] = view_idx
prev['H'], prev['W'] = img.s... | + 5
padded_frames = []
for frame in video_frames:
frame = frame[::2, ::2]
H, W, C = frame.shape
# create a white canvas
canvas = np.ones([max_H, max_W, C])
# calculate center offset
off_H, off_W = (max_H - H)//2, (max_W - W)//2
# paste the frame in the ... | 148 | 148 | 495 | 18 | 129 | ThisIsIsaac/nerf-meta | utils/tour_video.py | Python | create_interpolation_video | create_interpolation_video | 116 | 168 | 116 | 116 | 744f7eb0cdea7dfa38e1950bdecb8447679d8685 | bigcode/the-stack | train |
c6d66fb1eef63d62578fc86b | train | class | class Server():
'Class to contain server object along with additional variables and methods'
def __init__(self, email):
self.email = email
self.data_path = ".emails/%s" % (email)
#Get password
with open("%s/.password.txt" % (self.data_path), "r") as pass_file:
self.pa... | class Server():
| 'Class to contain server object along with additional variables and methods'
def __init__(self, email):
self.email = email
self.data_path = ".emails/%s" % (email)
#Get password
with open("%s/.password.txt" % (self.data_path), "r") as pass_file:
self.password = pass_fi... | import smtplib, threading, time, random, traceback
class Server():
| 16 | 175 | 586 | 3 | 12 | TheMadCoder1/Spambot | classes/server.py | Python | Server | Server | 3 | 58 | 3 | 3 | df34ccb574689b85f23f4003941336f61adc1b06 | bigcode/the-stack | train |
e3daa5a4813527a2d3534318 | train | class | class ServerThread(threading.Thread):
'Class to make a separate server thread that will spam outside of main thread'
SECONDS_IN_A_DAY = 24*60*60
DAILY_LIMIT = 500
def __init__(self, server_object):
threading.Thread.__init__(self)
self.exitFlag = 0
self.server_object = server_obj... | class ServerThread(threading.Thread):
| 'Class to make a separate server thread that will spam outside of main thread'
SECONDS_IN_A_DAY = 24*60*60
DAILY_LIMIT = 500
def __init__(self, server_object):
threading.Thread.__init__(self)
self.exitFlag = 0
self.server_object = server_object
self.server_object.current... | _to_messages_sent()
self.write_to_log("%s sent to %s" % (self.email, target))
except smtplib.SMTPServerDisconnected:
self.write_to_log("Disconnected by ban, email %s" % (self.email))
self.initialize_server()
self.write_to_log("Logged in again to %s" % (self.email)... | 105 | 105 | 351 | 7 | 97 | TheMadCoder1/Spambot | classes/server.py | Python | ServerThread | ServerThread | 62 | 90 | 62 | 62 | d1b542c71e9d53a95e1cf0147ecccfc84c35fa3e | bigcode/the-stack | train |
89506d83e4ffe4952fc43cbc | train | class | class TestTelnet(TestCase):
def setUp(self):
self.stdin = six.StringIO()
self.stdout = six.StringIO()
class t(telnet):
sent = six.StringIO()
def _send(self, line):
self.sent.write(line.decode('utf-8'))
self.t = t(6899, self.stdin, self.stdo... | class TestTelnet(TestCase):
| def setUp(self):
self.stdin = six.StringIO()
self.stdout = six.StringIO()
class t(telnet):
sent = six.StringIO()
def _send(self, line):
self.sent.write(line.decode('utf-8'))
self.t = t(6899, self.stdin, self.stdout)
def char(self, char)... | from unittest import TestCase
import six
from sdb import telnet
class TestTelnet(TestCase):
| 23 | 217 | 724 | 7 | 15 | ghjm/sdb | tests/test_telnet.py | Python | TestTelnet | TestTelnet | 8 | 97 | 8 | 9 | f4c9b8b3a4d3b5afb90d41f55b1eb77c85f91b4a | bigcode/the-stack | train |
a64b10658ce1ca17c18e2b8c | train | function | def _render_schema_testcase(project_package, prefix):
return """
from h1st.schema.testing import setup_schema_tests
from {project_package}.graph import {prefix}Graph
setup_schema_tests({prefix}Graph(), globals())
""".format(prefix=prefix, project_package=project_package)
| def _render_schema_testcase(project_package, prefix):
| return """
from h1st.schema.testing import setup_schema_tests
from {project_package}.graph import {prefix}Graph
setup_schema_tests({prefix}Graph(), globals())
""".format(prefix=prefix, project_package=project_package)
| prefix}Model
class {prefix}Graph(h1.Graph):
def __init__(self):
super().__init__()
self.start()
self.add({prefix}Model())
self.end()
""".format(prefix=prefix, model_module=model_module)
def _render_schema_testcase(project_package, prefix):
| 64 | 64 | 60 | 11 | 53 | Mou-Ikkai/h1st | h1st/h1st/cli/project.py | Python | _render_schema_testcase | _render_schema_testcase | 175 | 182 | 175 | 175 | 43a5274b211f2caf0e78928913508b9f46ae1b50 | bigcode/the-stack | train |
a0dd3b06a7e51db43ab5e19c | train | function | def new_project(project_name, base_path):
"""
Create a new project under the given base path
:param project_name: name of the project
:param base_path: target folder to create the project
"""
project_name_camel_case, project_name_snake_case = _clean_name(project_name)
class_prefix = projec... | def new_project(project_name, base_path):
| """
Create a new project under the given base path
:param project_name: name of the project
:param base_path: target folder to create the project
"""
project_name_camel_case, project_name_snake_case = _clean_name(project_name)
class_prefix = project_name_camel_case
path = pathlib.Path... | not model_path.exists():
raise ValueError('Please run this command in the package folder')
class_name, module_name = _clean_name(model_name)
if not class_name.lower().endswith("model"):
class_name = f"{class_name}Model"
new_model(
class_name,
p... | 151 | 151 | 506 | 9 | 142 | Mou-Ikkai/h1st | h1st/h1st/cli/project.py | Python | new_project | new_project | 71 | 135 | 71 | 71 | 44c79da4093a5c93825d4da51531e58791ccb90b | bigcode/the-stack | train |
06956b19d3b30f4d60e854ba | train | function | def _render_init_graph_class(model_module, prefix):
return """import h1st as h1
from .models.{model_module} import {prefix}Model
class {prefix}Graph(h1.Graph):
def __init__(self):
super().__init__()
self.start()
self.add({prefix}Model())
self.end()
""".format(prefix=prefix, mo... | def _render_init_graph_class(model_module, prefix):
| return """import h1st as h1
from .models.{model_module} import {prefix}Model
class {prefix}Graph(h1.Graph):
def __init__(self):
super().__init__()
self.start()
self.add({prefix}Model())
self.end()
""".format(prefix=prefix, model_module=model_module)
| py")
if model_file.exists():
raise ValueError(f'File {module_name}.py already exists')
with open(model_file, "w") as f:
f.write(_render_model_class(
name,
project_package,
))
def _render_init_graph_class(model_module, prefix):
| 63 | 64 | 84 | 11 | 52 | Mou-Ikkai/h1st | h1st/h1st/cli/project.py | Python | _render_init_graph_class | _render_init_graph_class | 160 | 172 | 160 | 160 | a05ec8142c7b43559f9a23e5a558f769edb864aa | bigcode/the-stack | train |
9521af6a7fbba120d225207d | train | function | def _clean_name(name):
# keep only valid character
name = re.sub(r"[^a-zA-Z0-9]", "_", name)
snake_case = "".join(['_' + i.lower() if i.isupper() else i for i in name]).lstrip('_')
camel_case = "".join([i.title() for i in snake_case.split("_")])
return camel_case, snake_case
| def _clean_name(name):
# keep only valid character
| name = re.sub(r"[^a-zA-Z0-9]", "_", name)
snake_case = "".join(['_' + i.lower() if i.isupper() else i for i in name]).lstrip('_')
camel_case = "".join([i.title() for i in snake_case.split("_")])
return camel_case, snake_case
| raise NotImplementedError()
def evaluate(self, data):
raise NotImplementedError()
def predict(self, data):
# Implement your predict function
raise NotImplementedError()
""".format(name=name, base_package=base_package)
def _clean_name(name):
# keep only valid character
| 64 | 64 | 88 | 13 | 51 | Mou-Ikkai/h1st | h1st/h1st/cli/project.py | Python | _clean_name | _clean_name | 211 | 216 | 211 | 212 | 954193d306027f1da7dd4b2a365532321d61e790 | bigcode/the-stack | train |
f8a0ea380bc6d7d3a74c3d8f | train | function | def _render_model_class(name, base_package):
return """import h1st as h1
class {name}(h1.Model):
def get_data(self):
# Implement code to retrieve your data here
return dict()
def prep_data(self, data):
# Implement code to prepare your data here
return data
def train(s... | def _render_model_class(name, base_package):
| return """import h1st as h1
class {name}(h1.Model):
def get_data(self):
# Implement code to retrieve your data here
return dict()
def prep_data(self, data):
# Implement code to prepare your data here
return data
def train(self, prepared_data):
# Implement your... | (project_package, prefix):
return """
from h1st.schema.testing import setup_schema_tests
from {project_package}.graph import {prefix}Graph
setup_schema_tests({prefix}Graph(), globals())
""".format(prefix=prefix, project_package=project_package)
def _render_model_class(name, base_package):
| 64 | 64 | 137 | 10 | 54 | Mou-Ikkai/h1st | h1st/h1st/cli/project.py | Python | _render_model_class | _render_model_class | 185 | 208 | 185 | 185 | 66abe4173c0c9540de879d9b0e3fcb870c701919 | bigcode/the-stack | train |
390d20beb258981447f1855a | train | function | def new_model(name, project_path, project_package, module_name=None):
"""
Create a new model template under the project path
:param name: model name
:param project_path: path to the project directory
:param project_package: package name of the project
:param module_name: module name for the mod... | def new_model(name, project_path, project_package, module_name=None):
| """
Create a new model template under the project path
:param name: model name
:param project_path: path to the project directory
:param project_package: package name of the project
:param module_name: module name for the model. By default it is model name in snake case format
"""
asser... | _case,
)
shutil.move(tmpdir, project_module)
return project_module, project_name
except:
try:
dir_util.remove_tree(tmpdir)
except:
pass # safe to ignore
raise
def new_model(name, project_path, project_package, module_name=None):
| 64 | 64 | 167 | 15 | 48 | Mou-Ikkai/h1st | h1st/h1st/cli/project.py | Python | new_model | new_model | 138 | 157 | 138 | 138 | b08f25275902c63a6e2464e89f65bca36aa19afc | bigcode/the-stack | train |
386e7020f9ddca12833cf1b6 | train | function | @click.command('new-model')
@click.argument('model_name')
def new_model_cli(model_name):
"""
CLI command to create new model
"""
try:
path = pathlib.Path('.').absolute()
model_path = (path / 'models')
# TODO: try to figure out the project folder if possible
if not model... | @click.command('new-model')
@click.argument('model_name')
def new_model_cli(model_name):
| """
CLI command to create new model
"""
try:
path = pathlib.Path('.').absolute()
model_path = (path / 'models')
# TODO: try to figure out the project folder if possible
if not model_path.exists():
raise ValueError('Please run this command in the package fold... | project_name,
attr('reset')
))
except Exception as ex:
print('%sError:%s %s' % (
fg('red'),
attr('reset'),
ex,
))
@click.command('new-model')
@click.argument('model_name')
def new_model_cli(model_name):
| 63 | 64 | 211 | 19 | 44 | Mou-Ikkai/h1st | h1st/h1st/cli/project.py | Python | new_model_cli | new_model_cli | 32 | 69 | 32 | 34 | 5d50a5976e73e29434ed095876d6c22438a184b0 | bigcode/the-stack | train |
c33e978102a1602850ac14b1 | train | function | @click.command('new-project')
@click.argument('project_name',)
def new_project_cli(project_name):
"""
CLI command to create new project
"""
try:
new_project(project_name, '.')
print('Project %s%s%s is created successfully.' % (
attr('bold'),
project_name,
... | @click.command('new-project')
@click.argument('project_name',)
def new_project_cli(project_name):
| """
CLI command to create new project
"""
try:
new_project(project_name, '.')
print('Project %s%s%s is created successfully.' % (
attr('bold'),
project_name,
attr('reset')
))
except Exception as ex:
print('%sError:%s %s' % (
... | import pathlib
import tempfile
import shutil
import re
from distutils import dir_util
import click
from colored import attr, fg
@click.command('new-project')
@click.argument('project_name',)
def new_project_cli(project_name):
| 49 | 64 | 106 | 20 | 28 | Mou-Ikkai/h1st | h1st/h1st/cli/project.py | Python | new_project_cli | new_project_cli | 11 | 29 | 11 | 13 | fb9f4d272249487a31bce431a032f33a9dadd519 | bigcode/the-stack | train |
e69f5525b2be0825206dd947 | train | class | class OpenImagesV4BoundingBox(OpenImagesV4, ObjectDetectionBase):
task_extend = "bounding_boxes"
available_subsets = ["train", "validation", "test"]
def __init__(self,
class_level=0,
*args,
**kwargs):
super(OpenImagesV4BoundingBox, self).__init__(... | class OpenImagesV4BoundingBox(OpenImagesV4, ObjectDetectionBase):
| task_extend = "bounding_boxes"
available_subsets = ["train", "validation", "test"]
def __init__(self,
class_level=0,
*args,
**kwargs):
super(OpenImagesV4BoundingBox, self).__init__(*args, **kwargs)
self._class_level = class_level
@pr... | 'class-descriptions.csv')
@property
@functools.lru_cache(maxsize=None)
def _classes_meta(self):
classes_meta = OrderedDict()
with open(self.class_descriptions_csv, 'r') as f:
reader = csv.reader(f)
for row in reader:
class_name = re.sub('\W', '', row... | 256 | 256 | 1,026 | 16 | 239 | takecore/blueoil | lmnet/lmnet/datasets/open_images_v4.py | Python | OpenImagesV4BoundingBox | OpenImagesV4BoundingBox | 90 | 220 | 90 | 90 | 299b64f485f1c70e567b0e58dddfacfa22f7b686 | bigcode/the-stack | train |
743a86c4e19bea0e8f63ce81 | train | class | class OpenImagesV4Classification(OpenImagesV4):
task_extend = "classification"
available_subsets = ["train", "validation", "test"]
def __init__(
self,
batch_size=100,
*args,
**kwargs
):
super().__init__(
batch_size=batch_size,
... | class OpenImagesV4Classification(OpenImagesV4):
| task_extend = "classification"
available_subsets = ["train", "validation", "test"]
def __init__(
self,
batch_size=100,
*args,
**kwargs
):
super().__init__(
batch_size=batch_size,
*args,
**kwargs,
)
... | 0, image size].
gt_boxes = np.stack([
gt_boxes[:, 0] * width,
gt_boxes[:, 1] * height,
gt_boxes[:, 2] * width,
gt_boxes[:, 3] * height,
gt_boxes[:, 4],
], axis=1)
gt_boxes = self._fill_dummy_boxes(gt_boxes)
return (image, gt_b... | 110 | 110 | 369 | 11 | 98 | takecore/blueoil | lmnet/lmnet/datasets/open_images_v4.py | Python | OpenImagesV4Classification | OpenImagesV4Classification | 223 | 275 | 223 | 223 | 0b1098cfc3d348cd2df034e406ece391759da886 | bigcode/the-stack | train |
aee4529c4cdbb2d68d5bc02b | train | class | class OpenImagesV4BoundingBoxBase(StoragePathCustomizable, OpenImagesV4BoundingBox):
"""Abstract class of dataset Open Images v4 format dataset.
structure like
$DATA_DIR/extend_dir/class-descriptions.csv
$DATA_DIR/extend_dir/annotations-bbox.csv
$DATA_DIR/extend_dir/images/xxxa.jpeg
... | class OpenImagesV4BoundingBoxBase(StoragePathCustomizable, OpenImagesV4BoundingBox):
| """Abstract class of dataset Open Images v4 format dataset.
structure like
$DATA_DIR/extend_dir/class-descriptions.csv
$DATA_DIR/extend_dir/annotations-bbox.csv
$DATA_DIR/extend_dir/images/xxxa.jpeg
$DATA_DIR/extend_dir/images/yyyb.png
$DATA_DIR/extend_dir/images/123.jpg... | Confidence"]])
for row in reader:
label_id = self._classes_meta[row[indexing["LabelName"]]]
if int(row[indexing["Confidence"]]) == 1 and label_id in self.classes:
files.append(os.path.join(self.images_dir, "{}.jpg".format(row[indexing["ImageID"]])))
... | 186 | 186 | 622 | 20 | 165 | takecore/blueoil | lmnet/lmnet/datasets/open_images_v4.py | Python | OpenImagesV4BoundingBoxBase | OpenImagesV4BoundingBoxBase | 278 | 362 | 278 | 278 | 6714eed6ca5d9b0599d1b78e0fbf3471fa85e3a8 | bigcode/the-stack | train |
7d94039b6ce865a33f23024b | train | class | class OpenImagesV4(Base):
extend_dir = "open_images_v4"
available_subsets = ["train", "validation", "test"]
task_extend = ""
def __init__(
self,
is_shuffle=True,
*args,
**kwargs
):
super().__init__(*args, **kwargs)
self.is_shuffle = ... | class OpenImagesV4(Base):
| extend_dir = "open_images_v4"
available_subsets = ["train", "validation", "test"]
task_extend = ""
def __init__(
self,
is_shuffle=True,
*args,
**kwargs
):
super().__init__(*args, **kwargs)
self.is_shuffle = is_shuffle
@property
... | .
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================
import csv
import functools
import json
import os
import os.path
import re
from collections import OrderedDict
import numpy as np
fro... | 102 | 102 | 342 | 7 | 94 | takecore/blueoil | lmnet/lmnet/datasets/open_images_v4.py | Python | OpenImagesV4 | OpenImagesV4 | 32 | 87 | 32 | 32 | fa4d2c50a39465f1619d70d18079eba9dd47ce45 | bigcode/the-stack | train |
767d4ee75e2c7fb3b7f18b64 | train | class | class GeoJsonFeed(Generic[T_FEED_ENTRY], ABC):
"""Geo JSON feed base class."""
def __init__(
self,
websession: ClientSession,
home_coordinates: Tuple[float, float],
url: str,
filter_radius: float = None,
):
"""Initialise this service."""
self._websess... | class GeoJsonFeed(Generic[T_FEED_ENTRY], ABC):
| """Geo JSON feed base class."""
def __init__(
self,
websession: ClientSession,
home_coordinates: Tuple[float, float],
url: str,
filter_radius: float = None,
):
"""Initialise this service."""
self._websession = websession
self._home_coordinates... | """GeoJSON Feed."""
import asyncio
import logging
from abc import ABC, abstractmethod
from datetime import datetime
from json import JSONDecodeError
from typing import Callable, Dict, Generic, List, Optional, Tuple
import aiohttp
import geojson
from aiohttp import ClientSession, client_exceptions
from geojson import F... | 131 | 256 | 1,282 | 12 | 119 | exxamalte/python-aio-geojson-client | aio_geojson_client/feed.py | Python | GeoJsonFeed | GeoJsonFeed | 26 | 194 | 26 | 26 | 0f77275f8d1fd55c80d1403ef687ddafc2a1770e | bigcode/the-stack | train |
a02564d0e8e00010899e1048 | train | class | class FeatureImportancePlotGenerator(object):
def __init__(self):
self.generator_name = ''
def generate_plot(self, preprocessed_data_set: PreprocessedDataSetInfo):
pass
| class FeatureImportancePlotGenerator(object):
| def __init__(self):
self.generator_name = ''
def generate_plot(self, preprocessed_data_set: PreprocessedDataSetInfo):
pass
| from data_set_info_data_class.data_class.preprocessed_data_set_info import PreprocessedDataSetInfo
class FeatureImportancePlotGenerator(object):
| 27 | 64 | 40 | 7 | 19 | Sale1996/automatization_of_data_mining_project | automatization_of_data_mining_project/feature_importance_statistic_generator/classes/feature_importance_plot_generator/feature_importance_plot_generator.py | Python | FeatureImportancePlotGenerator | FeatureImportancePlotGenerator | 4 | 9 | 4 | 4 | 6f172fbb9c29d2539a505536c4de85a42e6b75f6 | bigcode/the-stack | train |
3ff4710518d280b38c4ae48e | train | function | async def base_test(
hass,
config_device,
device_name,
entity_domain,
array_name_discovery,
array_name_old_config,
register_words,
expected,
method_discovery=False,
check_config_only=False,
config_modbus=None,
scan_interval=None,
expect_init_to_fail=False,
):
"""R... | async def base_test(
hass,
config_device,
device_name,
entity_domain,
array_name_discovery,
array_name_old_config,
register_words,
expected,
method_discovery=False,
check_config_only=False,
config_modbus=None,
scan_interval=None,
expect_init_to_fail=False,
):
| """Run test on device for given config."""
if config_modbus is None:
config_modbus = {
DOMAIN: {
CONF_NAME: DEFAULT_HUB,
CONF_TYPE: "tcp",
CONF_HOST: "modbusTest",
CONF_PORT: 5001,
},
}
mock_sync = mock... | ):
yield mock_pb
@pytest.fixture
async def mock_modbus(hass, mock_pymodbus):
"""Load integration modbus using mocked pymodbus."""
config = {
DOMAIN: [
{
CONF_TYPE: "tcp",
CONF_HOST: "modbusTestHost",
CONF_PORT: 5501,
... | 230 | 230 | 767 | 70 | 159 | provinzio/core | tests/components/modbus/conftest.py | Python | base_test | base_test | 69 | 174 | 69 | 83 | b8c64126b3325168472536711c2fb56cbcf5a6bc | bigcode/the-stack | train |
1f5a43d793505aff9a6f2e49 | train | function | @pytest.fixture
async def mock_modbus(hass, mock_pymodbus):
"""Load integration modbus using mocked pymodbus."""
config = {
DOMAIN: [
{
CONF_TYPE: "tcp",
CONF_HOST: "modbusTestHost",
CONF_PORT: 5501,
CONF_NAME: TEST_MODBUS_NAME,... | @pytest.fixture
async def mock_modbus(hass, mock_pymodbus):
| """Load integration modbus using mocked pymodbus."""
config = {
DOMAIN: [
{
CONF_TYPE: "tcp",
CONF_HOST: "modbusTestHost",
CONF_PORT: 5501,
CONF_NAME: TEST_MODBUS_NAME,
}
]
}
assert await async_setup_... | bus.modbus.ModbusSerialClient",
return_value=mock_pb,
), mock.patch(
"homeassistant.components.modbus.modbus.ModbusUdpClient", return_value=mock_pb
):
yield mock_pb
@pytest.fixture
async def mock_modbus(hass, mock_pymodbus):
| 64 | 64 | 112 | 17 | 46 | provinzio/core | tests/components/modbus/conftest.py | Python | mock_modbus | mock_modbus | 42 | 57 | 42 | 43 | 37832043a3e5df540439499d227b1c3d99dad882 | bigcode/the-stack | train |
a4d3a75fe7f50a99d05f4fde | train | function | async def base_config_test(
hass,
config_device,
device_name,
entity_domain,
array_name_discovery,
array_name_old_config,
method_discovery=False,
config_modbus=None,
expect_init_to_fail=False,
):
"""Check config of device for given config."""
await base_test(
hass,
... | async def base_config_test(
hass,
config_device,
device_name,
entity_domain,
array_name_discovery,
array_name_old_config,
method_discovery=False,
config_modbus=None,
expect_init_to_fail=False,
):
| """Check config of device for given config."""
await base_test(
hass,
config_device,
device_name,
entity_domain,
array_name_discovery,
array_name_old_config,
None,
None,
method_discovery=method_discovery,
check_config_only=True,
... | }"
return hass.states.get(entity_id).state
async def base_config_test(
hass,
config_device,
device_name,
entity_domain,
array_name_discovery,
array_name_old_config,
method_discovery=False,
config_modbus=None,
expect_init_to_fail=False,
):
| 64 | 64 | 137 | 53 | 10 | provinzio/core | tests/components/modbus/conftest.py | Python | base_config_test | base_config_test | 177 | 203 | 177 | 187 | 2eaddd2598fcee5d2d78750782c668794728a85a | bigcode/the-stack | train |
6d84dc63b21c8f8828ec0548 | train | function | @pytest.fixture
def mock_pymodbus():
"""Mock pymodbus."""
mock_pb = mock.MagicMock()
with mock.patch(
"homeassistant.components.modbus.modbus.ModbusTcpClient", return_value=mock_pb
), mock.patch(
"homeassistant.components.modbus.modbus.ModbusSerialClient",
return_value=mock_pb,
... | @pytest.fixture
def mock_pymodbus():
| """Mock pymodbus."""
mock_pb = mock.MagicMock()
with mock.patch(
"homeassistant.components.modbus.modbus.ModbusTcpClient", return_value=mock_pb
), mock.patch(
"homeassistant.components.modbus.modbus.ModbusSerialClient",
return_value=mock_pb,
), mock.patch(
"homeassist... | _SCAN_INTERVAL,
CONF_TYPE,
)
from homeassistant.setup import async_setup_component
import homeassistant.util.dt as dt_util
from tests.common import async_fire_time_changed
TEST_MODBUS_NAME = "modbusTest"
_LOGGER = logging.getLogger(__name__)
@pytest.fixture
def mock_pymodbus():
| 64 | 64 | 109 | 10 | 54 | provinzio/core | tests/components/modbus/conftest.py | Python | mock_pymodbus | mock_pymodbus | 27 | 39 | 27 | 28 | 17cf06436afbcc31a37f8e87f4577c07cce5f4be | bigcode/the-stack | train |
c25578578e35d5976cc68d88 | train | class | class ReadResult:
"""Storage class for register read results."""
def __init__(self, register_words):
"""Init."""
self.registers = register_words
self.bits = register_words
| class ReadResult:
| """Storage class for register read results."""
def __init__(self, register_words):
"""Init."""
self.registers = register_words
self.bits = register_words
| busTestHost",
CONF_PORT: 5501,
CONF_NAME: TEST_MODBUS_NAME,
}
]
}
assert await async_setup_component(hass, DOMAIN, config) is True
await hass.async_block_till_done()
yield mock_pymodbus
class ReadResult:
| 64 | 64 | 42 | 4 | 59 | provinzio/core | tests/components/modbus/conftest.py | Python | ReadResult | ReadResult | 60 | 66 | 60 | 60 | 0ffead49fa2ca00b14a2375e0a5af7113600b8d6 | bigcode/the-stack | train |
406b98e93db8fa37d5f2e81b | train | function | def readme():
with open('README.md', 'r') as f:
return f.read()
| def readme():
| with open('README.md', 'r') as f:
return f.read()
| in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from setuptools import setup, find_packages
def rea... | 64 | 64 | 22 | 4 | 59 | acoque/pyFmask | setup.py | Python | readme | readme | 18 | 20 | 18 | 18 | f7843527c14d3a9d4d186bfb0eb250e7afb8db45 | bigcode/the-stack | train |
a1f73482bbe422429d71c261 | train | function | @app.route('/monster/<name>')
def get_identicon(name):
image = cache.get(name)
if image is None:
print("Cache miss (промах кэша)", flush = True)
r = requests.get('http://dnmonster:8080/monster/' + name + '?size=80')
image = r.content
cache.set(name, image)
return Response(... | @app.route('/monster/<name>')
def get_identicon(name):
| image = cache.get(name)
if image is None:
print("Cache miss (промах кэша)", flush = True)
r = requests.get('http://dnmonster:8080/monster/' + name + '?size=80')
image = r.content
cache.set(name, image)
return Response(image, mimetype = 'image/png')
| submit">
</form>
<p>You really look like a:
<img src="/monster/{1}"/>
'''.format(name, name_hash)
footer = '</body></html>'
return header + body + footer
@app.route('/monster/<name>')
def get_identicon(name):
| 64 | 64 | 92 | 13 | 50 | amironyuk/image-dist | app/identidock.py | Python | get_identicon | get_identicon | 36 | 47 | 36 | 38 | 4e841fc588f0b961adf215c9a57209b10cc80ad0 | bigcode/the-stack | train |
5362bdb95079f8a25eb15e45 | train | function | @app.route('/', methods=['GET', 'POST'])
def mainpage():
name = default_name
if request.method == 'POST':
name = request.form['name']
salted_name = salt + name
name_hash = hashlib.sha256(salted_name.encode()).hexdigest()
header = '<html><head><title>Identicon</title></head><body>'
b... | @app.route('/', methods=['GET', 'POST'])
def mainpage():
| name = default_name
if request.method == 'POST':
name = request.form['name']
salted_name = salt + name
name_hash = hashlib.sha256(salted_name.encode()).hexdigest()
header = '<html><head><title>Identicon</title></head><body>'
body = '''<form method="POST">
Hello <input t... |
import hashlib
import redis
app = Flask(__name__)
cache = redis.StrictRedis(host = 'redis', port = 6379, db = 0)
salt = "UNIQUE SALT"
default_name = 'Joe Bloggs'
@app.route('/', methods=['GET', 'POST'])
def mainpage():
| 64 | 64 | 165 | 14 | 50 | amironyuk/image-dist | app/identidock.py | Python | mainpage | mainpage | 11 | 34 | 11 | 13 | a498f12d9ef14233e2b6aec2b12e7b0e9bb7130c | bigcode/the-stack | train |
b96eb931eba342f395fede82 | train | class | class NetTopologyMesh(Base):
"""mesh topology
The NetTopologyMesh class encapsulates a list of netTopologyMesh resources that are managed by the user.
A list of resources can be retrieved from the server using the NetTopologyMesh.find() method.
The list can be managed by using the NetTopologyMesh.add() ... | class NetTopologyMesh(Base):
| """mesh topology
The NetTopologyMesh class encapsulates a list of netTopologyMesh resources that are managed by the user.
A list of resources can be retrieved from the server using the NetTopologyMesh.find() method.
The list can be managed by using the NetTopologyMesh.add() and NetTopologyMesh.remove() ... | IA Keysight
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# an... | 256 | 256 | 1,215 | 6 | 249 | OpenIxia/ixnetwork_restpy | uhd_restpy/testplatform/sessions/ixnetwork/topology/nettopologymesh_517b38131e86c1d1de945da2a10cb914.py | Python | NetTopologyMesh | NetTopologyMesh | 27 | 175 | 27 | 27 | 5bfb84ab984900ccb559fb19dc6fdcc40676ad92 | bigcode/the-stack | train |
ca3f015abb4ec3d0470933d0 | train | function | def write_root(root, filename):
indent(root)
result_str = etree.tostring(root, encoding="UTF-8")
xml_declaration = b"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
result_str = xml_declaration + result_str
output_file = open(filename, "wb")
output_file.write(result_str)
output_file.close()
| def write_root(root, filename):
| indent(root)
result_str = etree.tostring(root, encoding="UTF-8")
xml_declaration = b"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
result_str = xml_declaration + result_str
output_file = open(filename, "wb")
output_file.write(result_str)
output_file.close()
| .strip():
elem.tail = i
if more_sibs:
elem.tail += empty_spaces
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
if more_sibs:
elem.tail += empty_spaces
def write_root(root, filename):
| 64 | 64 | 83 | 7 | 56 | oleks-k/python-snippets-misc | flare-scan-snippets.py | Python | write_root | write_root | 75 | 82 | 75 | 75 | fd44ccf433965367b8d34463212893d51a8bc75f | bigcode/the-stack | train |
70d2f82dbd74b7e77bc74ea6 | train | function | def scan_long_names(path):
global_snippet_list = []
file_snippet_modified_list = []
for root_dir, dirs, files in os.walk(path):
root_dir = root_dir.replace(os.path.sep, dir_sep)
for filename in files:
if filename.endswith('.htm'):
current_filepath = root_dir + dir... | def scan_long_names(path):
| global_snippet_list = []
file_snippet_modified_list = []
for root_dir, dirs, files in os.walk(path):
root_dir = root_dir.replace(os.path.sep, dir_sep)
for filename in files:
if filename.endswith('.htm'):
current_filepath = root_dir + dir_sep + filename
... | (ui_snippet_prefix):
has_no_ui_snippet_prefix = True
src_split[-1] = ui_snippet_prefix + tmp_string + ".flsnp"
# TODO: move this outside of this loop (no time to test now)
elem.attrib["src"] = dir_sep.join(src_split)
... | 141 | 141 | 472 | 6 | 134 | oleks-k/python-snippets-misc | flare-scan-snippets.py | Python | scan_long_names | scan_long_names | 131 | 168 | 131 | 131 | 6612f9dcce9529743c1df08d6b0886082ce3a832 | bigcode/the-stack | train |
b9cf39b4101f3eab905e59c9 | train | function | def scan_files(path):
global_snippet_list = []
file_snippet_modified_list = []
for root_dir, dirs, files in os.walk(path):
root_dir = root_dir.replace(os.path.sep, dir_sep)
for filename in files:
if filename.endswith('.htm'):
current_filepath = root_dir + dir_sep ... | def scan_files(path):
| global_snippet_list = []
file_snippet_modified_list = []
for root_dir, dirs, files in os.walk(path):
root_dir = root_dir.replace(os.path.sep, dir_sep)
for filename in files:
if filename.endswith('.htm'):
current_filepath = root_dir + dir_sep + filename
... | i
if more_sibs:
elem.tail += empty_spaces
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
if more_sibs:
elem.tail += empty_spaces
def write_root(root, filename):
indent(root)
result_str = etree.tostring... | 151 | 151 | 506 | 5 | 145 | oleks-k/python-snippets-misc | flare-scan-snippets.py | Python | scan_files | scan_files | 85 | 127 | 85 | 85 | 32db6d616c97e6d7b90282ac4242a1ade845d67b | bigcode/the-stack | train |
a09c5b5c40f6b8db69f9ce41 | train | function | def indent(elem, level=0, more_sibs=False):
i = "\n"
empty_spaces = " "
if level:
i += (level - 1) * empty_spaces
num_children = len(elem)
if num_children:
if not elem.text or not elem.text.strip():
if elem.getchildren()[0].tag not in inline_tags:
elem.... | def indent(elem, level=0, more_sibs=False):
| i = "\n"
empty_spaces = " "
if level:
i += (level - 1) * empty_spaces
num_children = len(elem)
if num_children:
if not elem.text or not elem.text.strip():
if elem.getchildren()[0].tag not in inline_tags:
elem.text = i + empty_spaces
if l... | _trunc.append(temp_str.lower()[0:120])
# searching for duplicates
seen = set()
unique = []
duplicates = []
for x in po_key_list_trunc:
if x in seen:
duplicates.append(x)
seen.add(x)
def indent(elem, level=0, more_sibs=False):
| 64 | 64 | 210 | 13 | 51 | oleks-k/python-snippets-misc | flare-scan-snippets.py | Python | indent | indent | 47 | 72 | 47 | 47 | 4bf2f1439c12cd10d20f5f79ba5cfbbdee87e5e1 | bigcode/the-stack | train |
ca58f9450d9b68ee6605cf1e | train | class | class ShutdownServer(ICommand):
def set_command_state(self, state: dict) -> None:
pass
def get_command_state(self) -> dict:
return {}
| class ShutdownServer(ICommand):
| def set_command_state(self, state: dict) -> None:
pass
def get_command_state(self) -> dict:
return {}
|
'''
Created on Oct 2020
@author: Bassem Girgis
@copyright: MIT license, see http://opensource.org/licenses/MIT
'''
from .ICommand import ICommand
class ShutdownServer(ICommand):
| 46 | 64 | 36 | 6 | 39 | brgirgis/pyzmqrpc3 | zmqrpc/command/ShutdownServer.py | Python | ShutdownServer | ShutdownServer | 15 | 21 | 15 | 16 | b8c4e7f4f0c2cef815726b8cdfe71e0bf9be2839 | bigcode/the-stack | train |
27b816102754702f7094b5f1 | train | function | def draw_acc(acc: torch.Tensor, title):
im, cb = heatmap(acc, cbar=True, cmap="binary",
row_labels=[f'{x + 1}' for x in range(acc.shape[0])],
col_labels=[f'{x + 1}' for x in range(acc.shape[1])],
show_axis_labels=True
)
im.set_c... | def draw_acc(acc: torch.Tensor, title):
| im, cb = heatmap(acc, cbar=True, cmap="binary",
row_labels=[f'{x + 1}' for x in range(acc.shape[0])],
col_labels=[f'{x + 1}' for x in range(acc.shape[1])],
show_axis_labels=True
)
im.set_clim(0, 1)
plt.xlabel('heads')
pl... | def __init__(self) -> None:
super().__init__()
self.label_correct = dict()
self.label_count = Counter()
def finalize(self):
for label, count in self.label_count.items():
self.label_correct[label] /= count
def draw_acc(acc: torch.Tensor, title):
| 64 | 64 | 105 | 10 | 53 | emorynlp/stem-cell-hypothesis | stem_cell_hypothesis/en_deberta_base/head/dep.py | Python | draw_acc | draw_acc | 45 | 54 | 45 | 45 | c2e2c9b5c4b3b8b62e98c59fbf637d07472c3404 | bigcode/the-stack | train |
b62bec387feaabdf9618a12c | train | function | def calc_acc(save_dir, folder):
tasks = {
# 'pos': TransformerTagging(
# ONTONOTES5_POS_ENGLISH_TRAIN,
# ONTONOTES5_POS_ENGLISH_DEV,
# ONTONOTES5_POS_ENGLISH_TEST,
# SortingSamplerBuilder(batch_size=64, batch_max_tokens=6400),
# lr=1e-3,
# ... | def calc_acc(save_dir, folder):
| tasks = {
# 'pos': TransformerTagging(
# ONTONOTES5_POS_ENGLISH_TRAIN,
# ONTONOTES5_POS_ENGLISH_DEV,
# ONTONOTES5_POS_ENGLISH_TEST,
# SortingSamplerBuilder(batch_size=64, batch_max_tokens=6400),
# lr=1e-3,
# ),
# 'ner': BiaffineName... | _deberta_base_en/all/lw/2'
# save_dir = 'data/model/mtl/ontonotes_deberta_base_en/pairwise/dep_srl/lw/2'
folder = 'joint-dep'
# folder = 'single'
# folder = 'static'
print(save_dir, folder)
records = calc_acc(save_dir, folder)
records.finalize()
overall = torch.zeros((12, 12))
# prin... | 256 | 256 | 929 | 8 | 248 | emorynlp/stem-cell-hypothesis | stem_cell_hypothesis/en_deberta_base/head/dep.py | Python | calc_acc | calc_acc | 85 | 172 | 85 | 85 | c9b3bbccafd788a69776efe6ab2082726789b4f6 | bigcode/the-stack | train |
dfbd11e97fd9ea9a64899737 | train | function | def main():
cdroot()
# save_dir = 'data/model/mtl/ontonotes_deberta_base_en/dep/2'
save_dir = 'data/model/mtl/ontonotes_deberta_base_en/all/lw/2'
# save_dir = 'data/model/mtl/ontonotes_deberta_base_en/pairwise/dep_srl/lw/2'
folder = 'joint-dep'
# folder = 'single'
# folder = 'static'
pri... | def main():
| cdroot()
# save_dir = 'data/model/mtl/ontonotes_deberta_base_en/dep/2'
save_dir = 'data/model/mtl/ontonotes_deberta_base_en/all/lw/2'
# save_dir = 'data/model/mtl/ontonotes_deberta_base_en/pairwise/dep_srl/lw/2'
folder = 'joint-dep'
# folder = 'single'
# folder = 'static'
print(save_dir,... | 1}' for x in range(acc.shape[0])],
col_labels=[f'{x + 1}' for x in range(acc.shape[1])],
show_axis_labels=True
)
im.set_clim(0, 1)
plt.xlabel('heads')
plt.ylabel('layers')
plt.title(title)
def main():
| 72 | 72 | 243 | 3 | 69 | emorynlp/stem-cell-hypothesis | stem_cell_hypothesis/en_deberta_base/head/dep.py | Python | main | main | 57 | 78 | 57 | 57 | c43163fb2d20ac02341795ca24989a96a489f80d | bigcode/the-stack | train |
1f876febae5b5c38750b5352 | train | class | class DepAcc(object):
def __init__(self) -> None:
super().__init__()
self.label_correct = dict()
self.label_count = Counter()
def finalize(self):
for label, count in self.label_count.items():
self.label_correct[label] /= count
| class DepAcc(object):
| def __init__(self) -> None:
super().__init__()
self.label_correct = dict()
self.label_count = Counter()
def finalize(self):
for label, count in self.label_count.items():
self.label_correct[label] /= count
| elit.layers.embeddings.contextual_word_embedding import ContextualWordEmbedding
from elit.metrics.mtl import MetricDict
from elit.utils.log_util import cprint
from elit.utils.time_util import CountdownTimer
from hanlp_common.constant import ROOT
from stem_cell_hypothesis import cdroot
class DepAcc(object):
| 64 | 64 | 59 | 5 | 58 | emorynlp/stem-cell-hypothesis | stem_cell_hypothesis/en_deberta_base/head/dep.py | Python | DepAcc | DepAcc | 33 | 42 | 33 | 34 | 65bfd36cbb2c54ff180a550bba7c86e758bcc52a | bigcode/the-stack | train |
4e2eb3c3dc598c2549f44bae | train | class | class LearnLessonPreprocessor(Preprocessor):
# NB: This is the only overridden Preprocessor method. All other methods are custom.
def preprocess(self, nb, resources):
# See render.py for how resources as populated.
self.track = resources['track_meta']
# May be None for notebooks with t... | class LearnLessonPreprocessor(Preprocessor):
# NB: This is the only overridden Preprocessor method. All other methods are custom.
| def preprocess(self, nb, resources):
# See render.py for how resources as populated.
self.track = resources['track_meta']
# May be None for notebooks with type='extra'
self.lesson = resources['lesson']
# Corresponds to track_config.yaml
track_cfg = resources['track_c... | import re
import logging
import os
import subprocess
import nbformat
from nbconvert.preprocessors import Preprocessor
from nb_utils.macro_processing import MacroProcessor
DEBUG = 0
if DEBUG:
logging.basicConfig(level=logging.DEBUG)
IGNORE_UNKNOWN_MACROS = 0
class UnrecognizedMacroException(Exception):
pass... | 142 | 256 | 2,574 | 28 | 114 | amitbcp/machine_learning_with_Scikit_Learn_and_TensorFlow | tensorflow_1_x/7_kaggle/notebooks/nb_utils/lesson_preprocessor.py | Python | LearnLessonPreprocessor | LearnLessonPreprocessor | 25 | 294 | 25 | 27 | cf8917471245b85c4badb4bd52e1444ddd55af16 | bigcode/the-stack | train |
5a72c510a9fcd73e98675907 | train | function | def get_git_branch():
"""Return the current git branch as a string"""
return subprocess.check_output(["git", "symbolic-ref", "--short", "HEAD"])\
.decode('utf8').strip()
| def get_git_branch():
| """Return the current git branch as a string"""
return subprocess.check_output(["git", "symbolic-ref", "--short", "HEAD"])\
.decode('utf8').strip()
| subprocess
import nbformat
from nbconvert.preprocessors import Preprocessor
from nb_utils.macro_processing import MacroProcessor
DEBUG = 0
if DEBUG:
logging.basicConfig(level=logging.DEBUG)
IGNORE_UNKNOWN_MACROS = 0
class UnrecognizedMacroException(Exception):
pass
def get_git_branch():
| 64 | 64 | 45 | 5 | 58 | amitbcp/machine_learning_with_Scikit_Learn_and_TensorFlow | tensorflow_1_x/7_kaggle/notebooks/nb_utils/lesson_preprocessor.py | Python | get_git_branch | get_git_branch | 20 | 23 | 20 | 20 | c21997e6500e42990f825234ee68f92fcdb35241 | bigcode/the-stack | train |
2ce9a30a8fa2c6ffec8be164 | train | class | class UnrecognizedMacroException(Exception):
pass
| class UnrecognizedMacroException(Exception):
| pass
|
import logging
import os
import subprocess
import nbformat
from nbconvert.preprocessors import Preprocessor
from nb_utils.macro_processing import MacroProcessor
DEBUG = 0
if DEBUG:
logging.basicConfig(level=logging.DEBUG)
IGNORE_UNKNOWN_MACROS = 0
class UnrecognizedMacroException(Exception):
| 64 | 64 | 10 | 7 | 56 | amitbcp/machine_learning_with_Scikit_Learn_and_TensorFlow | tensorflow_1_x/7_kaggle/notebooks/nb_utils/lesson_preprocessor.py | Python | UnrecognizedMacroException | UnrecognizedMacroException | 17 | 18 | 17 | 17 | 7d895cdf5e8b522434be4afffd0d685c34f672b4 | bigcode/the-stack | train |
2f3235cf245884d95d22b5bc | train | function | def test_function():
"""Docstring for test_function."""
pass
| def test_function():
| """Docstring for test_function."""
pass
| """Tests for doc generator traversal."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
from tensorflow.python.platform import googletest
from tensorflow.tools.docs import generate_lib
from tensorflow.tools.docs import parser
def test... | 64 | 64 | 15 | 4 | 59 | PaulWang1905/tensorflow | tensorflow/tools/docs/generate_lib_test.py | Python | test_function | test_function | 29 | 31 | 29 | 29 | 03b03ba4ba896d7fe2b381597a0fbd9b303f80be | bigcode/the-stack | train |
6317cdb5e994b86a499b1e30 | train | class | class GenerateTest(googletest.TestCase):
def get_test_objects(self):
# These are all mutable objects, so rebuild them for each test.
# Don't cache the objects.
module = sys.modules[__name__]
index = {
'tf': sys, # Can be any module, this test doesn't care about content.
'tf.TestModu... | class GenerateTest(googletest.TestCase):
| def get_test_objects(self):
# These are all mutable objects, so rebuild them for each test.
# Don't cache the objects.
module = sys.modules[__name__]
index = {
'tf': sys, # Can be any module, this test doesn't care about content.
'tf.TestModule': module,
'tf.test_function': t... | obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for... | 256 | 256 | 1,671 | 10 | 245 | PaulWang1905/tensorflow | tensorflow/tools/docs/generate_lib_test.py | Python | GenerateTest | GenerateTest | 52 | 247 | 52 | 53 | 67a374f762c98df1587b0a529cf9dd8c02bef669 | bigcode/the-stack | train |
11cf4b9dd1bb89731b83db38 | train | class | class DummyVisitor(object):
def __init__(self, index, duplicate_of):
self.index = index
self.duplicate_of = duplicate_of
| class DummyVisitor(object):
| def __init__(self, index, duplicate_of):
self.index = index
self.duplicate_of = duplicate_of
| string for test_function."""
pass
class TestClass(object):
"""Docstring for TestClass itself."""
class ChildClass(object):
"""Docstring for a child class."""
class GrandChildClass(object):
"""Docstring for a child of a child class."""
pass
class DummyVisitor(object):
| 64 | 64 | 32 | 5 | 58 | PaulWang1905/tensorflow | tensorflow/tools/docs/generate_lib_test.py | Python | DummyVisitor | DummyVisitor | 45 | 49 | 45 | 46 | 6ac349bf7ba8fd72474be58a07c5a6d07e54811a | bigcode/the-stack | train |
10d1621d69f8b39296ab5046 | train | class | class TestClass(object):
"""Docstring for TestClass itself."""
class ChildClass(object):
"""Docstring for a child class."""
class GrandChildClass(object):
"""Docstring for a child of a child class."""
pass
| class TestClass(object):
| """Docstring for TestClass itself."""
class ChildClass(object):
"""Docstring for a child class."""
class GrandChildClass(object):
"""Docstring for a child of a child class."""
pass
| __future__ import division
from __future__ import print_function
import os
import sys
from tensorflow.python.platform import googletest
from tensorflow.tools.docs import generate_lib
from tensorflow.tools.docs import parser
def test_function():
"""Docstring for test_function."""
pass
class TestClass(object):
| 64 | 64 | 51 | 5 | 58 | PaulWang1905/tensorflow | tensorflow/tools/docs/generate_lib_test.py | Python | TestClass | TestClass | 34 | 42 | 34 | 34 | 7308b8ae7e954e528a09b041bc6baf003c013763 | bigcode/the-stack | train |
0defe5fc0e026b98fb0fa060 | train | class | class MorrisSensitivity:
@beartype
def __init__(
self,
runmodel_object: RunModel,
distributions: Union[JointIndependent, Union[list, tuple]],
n_levels: Annotated[int, Is[lambda x: x >= 3]],
delta: Union[float, int] = None,
random_state: Ran... | class MorrisSensitivity:
@beartype
| def __init__(
self,
runmodel_object: RunModel,
distributions: Union[JointIndependent, Union[list, tuple]],
n_levels: Annotated[int, Is[lambda x: x >= 3]],
delta: Union[float, int] = None,
random_state: RandomStateType = None,
n_traj... | """This module contains functionality for sensitivity analysis in ``UQpy``.
The module currently contains the following classes:
- ``Morris``: Class to compute sensitivity indices based on the Morris method.
"""
from typing import Union, Annotated
from beartype import beartype
from beartype.vale import Is
from UQpy... | 138 | 256 | 2,879 | 10 | 127 | SURGroup/UncertaintyQuantification | src/UQpy/sensitivity/MorrisSensitivity.py | Python | MorrisSensitivity | MorrisSensitivity | 20 | 226 | 20 | 21 | 101062b5f9ea35f24c6a068f68545462d4f266cb | bigcode/the-stack | train |
dc35bb6550274977316ba923 | train | function | def turn(left):
# increments setting for the turn
direction = 1
if left:
direction = -1
# MAJOR TURN
leftMotor.run_to_rel_pos(position_sp=wheel_turn_rotations_per_turn * direction, speed_sp=200, ramp_down_sp=90)
rightMotor.run_to_rel_pos(position_sp=-wheel_turn_rotations_per_turn * dire... | def turn(left):
# increments setting for the turn
| direction = 1
if left:
direction = -1
# MAJOR TURN
leftMotor.run_to_rel_pos(position_sp=wheel_turn_rotations_per_turn * direction, speed_sp=200, ramp_down_sp=90)
rightMotor.run_to_rel_pos(position_sp=-wheel_turn_rotations_per_turn * direction, speed_sp=200, ramp_down_sp=90)
# hold unti... | state
btn = Button()
wheel_turn_rotations_per_turn = 360 * 0.89 * 1
def stop_motors():
# leftMotor.reset()
leftMotor.stop()
# rightMotor.reset()
rightMotor.stop()
def turn(left):
# increments setting for the turn
| 64 | 64 | 117 | 12 | 52 | senornosketchy/ENGG1000-R2R | testFilesForDocumentation/TurnGuessTesting.py | Python | turn | turn | 47 | 60 | 47 | 48 | dffcda241e614716abf3430012c8630dac65fa50 | bigcode/the-stack | train |
9e3b83fa9486aafed772e5a6 | train | function | def stop_motors():
# leftMotor.reset()
leftMotor.stop()
# rightMotor.reset()
rightMotor.stop()
| def stop_motors():
# leftMotor.reset()
| leftMotor.stop()
# rightMotor.reset()
rightMotor.stop()
| ()
gs = GyroSensor(INPUT_3)
assert gs.connected
print("Gyro sensor connected")
print()
# Checking EV3 buttons state
btn = Button()
wheel_turn_rotations_per_turn = 360 * 0.89 * 1
def stop_motors():
# leftMotor.reset()
| 64 | 64 | 28 | 12 | 51 | senornosketchy/ENGG1000-R2R | testFilesForDocumentation/TurnGuessTesting.py | Python | stop_motors | stop_motors | 40 | 44 | 40 | 41 | 1efaa78b379c256f703eb1d3bf3b0b29031026a3 | bigcode/the-stack | train |
f3446fa7158f92329d423fea | train | class | class CampaignCustomizer(proto.Message):
r"""A customizer value for the associated CustomizerAttribute at
the Campaign level.
Attributes:
resource_name (str):
Immutable. The resource name of the campaign customizer.
Campaign customizer resource names have the form:
... | class CampaignCustomizer(proto.Message):
| r"""A customizer value for the associated CustomizerAttribute at
the Campaign level.
Attributes:
resource_name (str):
Immutable. The resource name of the campaign customizer.
Campaign customizer resource names have the form:
``customers/{customer_id}/campaignCus... | the specific language governing permissions and
# limitations under the License.
#
import proto # type: ignore
from google.ads.googleads.v10.common.types import customizer_value
from google.ads.googleads.v10.enums.types import customizer_value_status
__protobuf__ = proto.module(
package="google.ads.googleads.v... | 93 | 93 | 312 | 6 | 87 | JakobSteixner/google-ads-python | google/ads/googleads/v10/resources/types/campaign_customizer.py | Python | CampaignCustomizer | CampaignCustomizer | 29 | 65 | 29 | 29 | 8f15f1b6be0883eff8bc2507bfe610cb537daf86 | bigcode/the-stack | train |
a1cfca576ba95b31e96e9a97 | train | class | class JoyentNodeDriver(NodeDriver):
"""
Joyent node driver class.
"""
type = Provider.JOYENT
name = 'Joyent'
website = 'http://www.joyentcloud.com'
connectionCls = JoyentConnection
features = {'create_node': ['generates_password']}
def __init__(self, key, secret=None, secure=True, ... | class JoyentNodeDriver(NodeDriver):
| """
Joyent node driver class.
"""
type = Provider.JOYENT
name = 'Joyent'
website = 'http://www.joyentcloud.com'
connectionCls = JoyentConnection
features = {'create_node': ['generates_password']}
def __init__(self, key, secret=None, secure=True, host=None, port=None,
... | 1'
]
DEFAULT_REGION = 'us-east-1'
class JoyentResponse(JsonResponse):
"""
Joyent response class.
"""
valid_response_codes = [httplib.OK, httplib.ACCEPTED, httplib.CREATED,
httplib.NO_CONTENT]
def parse_error(self):
if self.status == httplib.UNAUTHORIZED:
... | 256 | 256 | 1,141 | 8 | 247 | Matir/libcloud | libcloud/compute/drivers/joyent.py | Python | JoyentNodeDriver | JoyentNodeDriver | 95 | 248 | 95 | 95 | e985b674a5086fea3e16d32439a9a5dcf7c27891 | bigcode/the-stack | train |
c62744c6906e69b74ed48b0b | train | class | class JoyentResponse(JsonResponse):
"""
Joyent response class.
"""
valid_response_codes = [httplib.OK, httplib.ACCEPTED, httplib.CREATED,
httplib.NO_CONTENT]
def parse_error(self):
if self.status == httplib.UNAUTHORIZED:
data = self.parse_body()
... | class JoyentResponse(JsonResponse):
| """
Joyent response class.
"""
valid_response_codes = [httplib.OK, httplib.ACCEPTED, httplib.CREATED,
httplib.NO_CONTENT]
def parse_error(self):
if self.status == httplib.UNAUTHORIZED:
data = self.parse_body()
raise InvalidCredsError(data... | }
VALID_REGIONS = [
'us-east-1', 'us-east-2', 'us-east-3',
'us-west-1',
'us-sw-1',
'eu-ams-1'
]
DEFAULT_REGION = 'us-east-1'
class JoyentResponse(JsonResponse):
| 64 | 64 | 104 | 7 | 57 | Matir/libcloud | libcloud/compute/drivers/joyent.py | Python | JoyentResponse | JoyentResponse | 58 | 73 | 58 | 58 | b1e9ddc6568fd0ef6277036e3036b0319ab075f1 | bigcode/the-stack | train |
95f67341a3611371b9b75beb | train | class | class JoyentConnection(ConnectionUserAndKey):
"""
Joyent connection class.
"""
responseCls = JoyentResponse
allow_insecure = False
def add_default_headers(self, headers):
headers['Accept'] = 'application/json'
headers['Content-Type'] = 'application/json; charset=UTF-8'
... | class JoyentConnection(ConnectionUserAndKey):
| """
Joyent connection class.
"""
responseCls = JoyentResponse
allow_insecure = False
def add_default_headers(self, headers):
headers['Accept'] = 'application/json'
headers['Content-Type'] = 'application/json; charset=UTF-8'
headers['X-Api-Version'] = API_VERSION
... | if self.status == httplib.UNAUTHORIZED:
data = self.parse_body()
raise InvalidCredsError(data['code'] + ': ' + data['message'])
return self.body
def success(self):
return self.status in self.valid_response_codes
class JoyentConnection(ConnectionUserAndKey):
| 64 | 64 | 132 | 9 | 54 | Matir/libcloud | libcloud/compute/drivers/joyent.py | Python | JoyentConnection | JoyentConnection | 76 | 92 | 76 | 76 | 2443261ca7631e905fff07b2ec06713e7dec9b63 | bigcode/the-stack | train |
482b997571cbbf745a5d8a48 | train | function | def read_obs_dataset(variq,dataset_obs,numOfEns,lensalso,randomalso,ravelyearsbinary,ravelbinary,shuffletype,lat_bounds=lat_bounds,lon_bounds=lon_bounds):
data_obs,lats_obs,lons_obs = df.readFiles(variq,dataset_obs,monthlychoice,numOfEns,lensalso,randomalso,ravelyearsbinary,ravelbinary,shuffletype,timeper)
data... | def read_obs_dataset(variq,dataset_obs,numOfEns,lensalso,randomalso,ravelyearsbinary,ravelbinary,shuffletype,lat_bounds=lat_bounds,lon_bounds=lon_bounds):
| data_obs,lats_obs,lons_obs = df.readFiles(variq,dataset_obs,monthlychoice,numOfEns,lensalso,randomalso,ravelyearsbinary,ravelbinary,shuffletype,timeper)
data_obs,lats_obs,lons_obs = df.getRegion(data_obs,lats_obs,lons_obs,lat_bounds,lon_bounds)
print('our OBS dataset: ',dataset_obs,' is shaped',data_ob... | ',dataset,' is shaped',data.shape)
return datar,lats,lons
def read_obs_dataset(variq,dataset_obs,numOfEns,lensalso,randomalso,ravelyearsbinary,ravelbinary,shuffletype,lat_bounds=lat_bounds,lon_bounds=lon_bounds):
| 64 | 64 | 152 | 46 | 17 | zmlabe/predictGMSTrate | Dark_Scripts/plo_TestingPredition_RawHiatus_OHClevels-lag-EDA_v2.py | Python | read_obs_dataset | read_obs_dataset | 108 | 113 | 108 | 108 | e65fdad5cd95e2463a96954cbbefe6b6e45b71b5 | bigcode/the-stack | train |
cf348c4858c41075e7b76ad5 | train | function | def read_primary_dataset(variq,dataset,monthlychoice,numOfEns,lensalso,randomalso,ravelyearsbinary,ravelbinary,shuffletype,timeper,lat_bounds=lat_bounds,lon_bounds=lon_bounds):
data,lats,lons = df.readFiles(variq,dataset,monthlychoice,numOfEns,lensalso,randomalso,ravelyearsbinary,ravelbinary,shuffletype,timeper)
... | def read_primary_dataset(variq,dataset,monthlychoice,numOfEns,lensalso,randomalso,ravelyearsbinary,ravelbinary,shuffletype,timeper,lat_bounds=lat_bounds,lon_bounds=lon_bounds):
| data,lats,lons = df.readFiles(variq,dataset,monthlychoice,numOfEns,lensalso,randomalso,ravelyearsbinary,ravelbinary,shuffletype,timeper)
datar,lats,lons = df.getRegion(data,lats,lons,lat_bounds,lon_bounds)
print('\nOur dataset: ',dataset,' is shaped',data.shape)
return datar,lats,lons
| ###
### Function to read in predictor variables (SST/OHC)
def read_primary_dataset(variq,dataset,monthlychoice,numOfEns,lensalso,randomalso,ravelyearsbinary,ravelbinary,shuffletype,timeper,lat_bounds=lat_bounds,lon_bounds=lon_bounds):
| 64 | 64 | 142 | 50 | 14 | zmlabe/predictGMSTrate | Dark_Scripts/plo_TestingPredition_RawHiatus_OHClevels-lag-EDA_v2.py | Python | read_primary_dataset | read_primary_dataset | 102 | 106 | 102 | 102 | cf6eee954cd09ffd47fd91ddbf58f0fb9943adf2 | bigcode/the-stack | train |
7b03a56942f33ea8e9d812c5 | train | function | def upgrade():
print('Upgrading... pip')
call([python_ver, '-m', 'pip', 'install', '--upgrade', 'pip'])
| def upgrade():
| print('Upgrading... pip')
call([python_ver, '-m', 'pip', 'install', '--upgrade', 'pip'])
| import pip
from subprocess import call
python_ver = 'python3'
def install(package):
print('Installing... ' + package)
pip.main(['install', package])
def uninstall(package):
print('Uninstalling... ' + package)
pip.main(['uninstall', package])
def upgrade():
| 63 | 64 | 32 | 3 | 60 | TheShellLand/python | v3/Libraries/pip/Install package.py | Python | upgrade | upgrade | 16 | 18 | 16 | 16 | 200b415b32110f98c002f97db3800907441afc57 | bigcode/the-stack | train |
96bde9facb5a5b99ca0befaa | train | function | def install(package):
print('Installing... ' + package)
pip.main(['install', package])
| def install(package):
| print('Installing... ' + package)
pip.main(['install', package])
| import pip
from subprocess import call
python_ver = 'python3'
def install(package):
| 19 | 64 | 21 | 4 | 15 | TheShellLand/python | v3/Libraries/pip/Install package.py | Python | install | install | 8 | 10 | 8 | 8 | e611ac359346d013c5eb6ee09bf63ca0f8c952d0 | bigcode/the-stack | train |
5536b6742813ebeb5bafb7d0 | train | function | def uninstall(package):
print('Uninstalling... ' + package)
pip.main(['uninstall', package])
| def uninstall(package):
| print('Uninstalling... ' + package)
pip.main(['uninstall', package])
| import pip
from subprocess import call
python_ver = 'python3'
def install(package):
print('Installing... ' + package)
pip.main(['install', package])
def uninstall(package):
| 40 | 64 | 24 | 4 | 36 | TheShellLand/python | v3/Libraries/pip/Install package.py | Python | uninstall | uninstall | 12 | 14 | 12 | 12 | adfd31f3e7daf6576c79ab9cf226019290e6925a | bigcode/the-stack | train |
646237665782cd2a80c02577 | train | function | def main():
while True:
package = input('Type in a package: ')
#print('length: ' + len(package).__str__())
if len(package) > 0:
break
while True:
print('1. Install\n' + '2. Uninstall\n' + '\n' + '3. Upgrade pip')
action = input('Choose an option: ').__str__()... | def main():
| while True:
package = input('Type in a package: ')
#print('length: ' + len(package).__str__())
if len(package) > 0:
break
while True:
print('1. Install\n' + '2. Uninstall\n' + '\n' + '3. Upgrade pip')
action = input('Choose an option: ').__str__()
#pr... | install', package])
def uninstall(package):
print('Uninstalling... ' + package)
pip.main(['uninstall', package])
def upgrade():
print('Upgrading... pip')
call([python_ver, '-m', 'pip', 'install', '--upgrade', 'pip'])
def main():
| 63 | 64 | 179 | 3 | 60 | TheShellLand/python | v3/Libraries/pip/Install package.py | Python | main | main | 21 | 52 | 21 | 21 | df0560dfeb9643d0c79ded977740189e97b45008 | bigcode/the-stack | train |
c85da8ce889a28b67812b733 | train | class | class Store(Collection[_V], Generic[_V]):
"""
A collection of all values under a single unique index key.
Multiple objects can yield the same keys, so all their values
are accumulated into collections. When an object is deleted
or stops matching the filters, all associated values are discarded.
... | class Store(Collection[_V], Generic[_V]):
| """
A collection of all values under a single unique index key.
Multiple objects can yield the same keys, so all their values
are accumulated into collections. When an object is deleted
or stops matching the filters, all associated values are discarded.
The order of values is not guaranteed.
... | (str(e))
def __getattr__(self, key: str) -> Any:
try:
return self[key]
except KeyError as e:
raise AttributeError(str(e))
_K = TypeVar('_K')
_V = TypeVar('_V')
class Store(Collection[_V], Generic[_V]):
| 64 | 64 | 143 | 10 | 54 | tavaresrodrigo/kopf | kopf/_cogs/structs/ephemera.py | Python | Store | Store | 55 | 74 | 55 | 55 | 2ca5c773412b23da87fb9e95c68411ed35bfd8b5 | bigcode/the-stack | train |
ae35c76999ceb6b7a9d0e329 | train | class | class Memo(Dict[Any, Any]):
"""
A container to hold arbitrary keys-values assigned by operator developers.
It is used in the :kwarg:`memo` kwarg to all resource handlers, isolated
per individual resource object (not the resource kind).
The values can be accessed either as dictionary keys (the memo... | class Memo(Dict[Any, Any]):
| """
A container to hold arbitrary keys-values assigned by operator developers.
It is used in the :kwarg:`memo` kwarg to all resource handlers, isolated
per individual resource object (not the resource kind).
The values can be accessed either as dictionary keys (the memo is a ``dict``
under the... | Type, TypeVar
# For users, memos are exposed as `Any`, though usually used with `kopf.Memo`.
# However, the framework cannot rely on any methods/properties of it, so it is
# declared as a nearly empty `object` for stricter internal type-checking.
AnyMemo = NewType('AnyMemo', object)
class Memo(Dict[Any, Any]):
| 81 | 81 | 271 | 8 | 73 | tavaresrodrigo/kopf | kopf/_cogs/structs/ephemera.py | Python | Memo | Memo | 9 | 48 | 9 | 9 | efea36a7f4d2d6d7375b5d3840487eb718adbd0e | bigcode/the-stack | train |
1ecb8df84a9658b0fa08e00d | train | class | class Index(Mapping[_K, Store[_V]], Generic[_K, _V]):
"""
A mapping of index keys to collections of values indexed under those keys.
A single index is identified by a handler id and is populated by values
usually from a single indexing function (the ``@kopf.index()`` decorator).
.. note::
... | class Index(Mapping[_K, Store[_V]], Generic[_K, _V]):
| """
A mapping of index keys to collections of values indexed under those keys.
A single index is identified by a handler id and is populated by values
usually from a single indexing function (the ``@kopf.index()`` decorator).
.. note::
This class is only an abstract interface of an index.
... | functions.
.. note::
This class is only an abstract interface of an indexed store.
The actual implementation is in `.indexing.Store`.
.. seealso:
:doc:`/indexing`.
"""
class Index(Mapping[_K, Store[_V]], Generic[_K, _V]):
| 63 | 64 | 110 | 18 | 45 | tavaresrodrigo/kopf | kopf/_cogs/structs/ephemera.py | Python | Index | Index | 77 | 90 | 77 | 77 | 9561b2784fb0ef803a30c36b2ae72af31b0d319a | bigcode/the-stack | train |
6b8a7cb70f3402bd24232b54 | train | function | def permutation_test(a, b, num_samples, statistic):
"""
Permutation test.
Return p-value that statistic for a is different
from statistc for b.
"""
observed_diff = abs(statistic(b) - statistic(a))
num_a = len(a)
combined = np.concatenate([a, b])
diffs = []
for i in range(num_sa... | def permutation_test(a, b, num_samples, statistic):
| """
Permutation test.
Return p-value that statistic for a is different
from statistc for b.
"""
observed_diff = abs(statistic(b) - statistic(a))
num_a = len(a)
combined = np.concatenate([a, b])
diffs = []
for i in range(num_samples):
xs = npr.permutation(combined)
... | np.mean(xs[num_case:])
diffs.append(diff)
pval = (np.sum(diffs > observed_diff) +
np.sum(diffs < -observed_diff))/float(num_samples)
return pval, observed_diff, diffs
def permutation_test(a, b, num_samples, statistic):
| 64 | 64 | 149 | 12 | 51 | MadsJensen/malthe_alpha_project | source_connectivity_permutation.py | Python | permutation_test | permutation_test | 41 | 59 | 41 | 41 | debd4f436a9f3c4cd902fea34b04f8ca0957db0c | bigcode/the-stack | train |
8e738323034722aa20965f1a | train | function | def permutation_resampling(case, control, num_samples, statistic):
"""
Permutation test.
Return p-value that statistic for case is different
from statistc for control.
"""
observed_diff = abs(statistic(case) - statistic(control))
num_case = len(case)
combined = np.concatenate([case, co... | def permutation_resampling(case, control, num_samples, statistic):
| """
Permutation test.
Return p-value that statistic for case is different
from statistc for control.
"""
observed_diff = abs(statistic(case) - statistic(control))
num_case = len(case)
combined = np.concatenate([case, control])
diffs = []
for i in range(num_samples):
xs ... | as npr
import os
import socket
import mne
# import pandas as pd
from mne.connectivity import spectral_connectivity
from mne.minimum_norm import (apply_inverse_epochs, read_inverse_operator)
# Permutation test.
def permutation_resampling(case, control, num_samples, statistic):
| 64 | 64 | 156 | 13 | 51 | MadsJensen/malthe_alpha_project | source_connectivity_permutation.py | Python | permutation_resampling | permutation_resampling | 19 | 38 | 19 | 19 | e7370c0da9bf02209d8b0d68319ea93b0df81af7 | bigcode/the-stack | train |
28db8802de3051faa8c15443 | train | function | def main(client):
# Initialize appropriate service.
ad_unit_service = client.GetService('InventoryService', version='v202108')
# Create a statement to select ad units.
statement = ad_manager.StatementBuilder(version='v202108')
# Retrieve a small amount of ad units at a time, paging
# through until all ad ... | def main(client):
# Initialize appropriate service.
| ad_unit_service = client.GetService('InventoryService', version='v202108')
# Create a statement to select ad units.
statement = ad_manager.StatementBuilder(version='v202108')
# Retrieve a small amount of ad units at a time, paging
# through until all ad units have been retrieved.
while True:
response ... | OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example gets all ad units.
"""
# Import appropriate modules from the client library.
from googleads import ad_manager
def main(client):
# Initialize ap... | 64 | 64 | 195 | 10 | 53 | timgates42/googleads-python-lib | examples/ad_manager/v202108/inventory_service/get_all_ad_units.py | Python | main | main | 23 | 43 | 23 | 24 | 1cd9390355186c9470f92e74ebc2a3733ccb5bbc | bigcode/the-stack | train |
f73017872428a3bd64e3b571 | train | function | @pytest.fixture
def atts_denormalise():
return np.zeros((3, 2, 2))
| @pytest.fixture
def atts_denormalise():
| return np.zeros((3, 2, 2))
| 4.0, 5.0, -1.0])
@pytest.fixture
def atts_normalise_2():
return np.array([1.0, 2.0, 3.0, 4.0, 5.0])
@pytest.fixture
def atts_denormalise():
| 64 | 64 | 23 | 10 | 54 | sebastian-lapuschkin/Quantus | tests/helpers/test_normalise_func.py | Python | atts_denormalise | atts_denormalise | 22 | 24 | 22 | 23 | cb40e51ead02efc38772d9311c6f1df42f6efd43 | bigcode/the-stack | train |
5b0c2e9822cdd2d6d7529904 | train | function | @pytest.fixture
def atts_normalise_2():
return np.array([1.0, 2.0, 3.0, 4.0, 5.0])
| @pytest.fixture
def atts_normalise_2():
| return np.array([1.0, 2.0, 3.0, 4.0, 5.0])
| .helpers import *
@pytest.fixture
def atts_normalise_1():
return np.array([1.0, 2.0, 3.0, 4.0, 4.0, 5.0, -1.0])
@pytest.fixture
def atts_normalise_2():
| 64 | 64 | 40 | 11 | 53 | sebastian-lapuschkin/Quantus | tests/helpers/test_normalise_func.py | Python | atts_normalise_2 | atts_normalise_2 | 17 | 19 | 17 | 18 | 0838aa7464e99edc29561e95a5c7153660e692ab | bigcode/the-stack | train |
70d9d60c7ca889fbeed0094e | train | function | @pytest.mark.normalise_func
@pytest.mark.parametrize(
"data,params,expected",
[
(
lazy_fixture("atts_denormalise"),
{},
np.array(
[
[[0.485, 0.485], [0.485, 0.485]],
[[0.456, 0.456], [0.456, 0.456]],
... | @pytest.mark.normalise_func
@pytest.mark.parametrize(
"data,params,expected",
[
(
lazy_fixture("atts_denormalise"),
{},
np.array(
[
[[0.485, 0.485], [0.485, 0.485]],
[[0.456, 0.456], [0.456, 0.456]],
... | out = denormalise(img=data, **params)
assert np.all(
o == e for o, e in zip(np.array(out).flatten(), np.array(expected).flatten())
), "Test failed."
| @pytest.mark.normalise_func
@pytest.mark.parametrize(
"data,params,expected",
[
(
lazy_fixture("atts_denormalise"),
{},
np.array(
[
[[0.485, 0.485], [0.485, 0.485]],
[[0.456, 0.456], [0.456, 0.456]],
... | 158 | 64 | 203 | 158 | 0 | sebastian-lapuschkin/Quantus | tests/helpers/test_normalise_func.py | Python | test_denormalise | test_denormalise | 62 | 90 | 62 | 86 | b5ede01408abb87a8cbc7dfae9007b6821865e6c | bigcode/the-stack | train |
12893146ec0cefba021deead | train | function | @pytest.fixture
def atts_normalise_1():
return np.array([1.0, 2.0, 3.0, 4.0, 4.0, 5.0, -1.0])
| @pytest.fixture
def atts_normalise_1():
| return np.array([1.0, 2.0, 3.0, 4.0, 4.0, 5.0, -1.0])
| from typing import Union
import numpy as np
import pytest
import torch
from pytest_lazyfixture import lazy_fixture
from ..fixtures import *
from ...quantus.helpers import *
@pytest.fixture
def atts_normalise_1():
| 47 | 64 | 50 | 11 | 36 | sebastian-lapuschkin/Quantus | tests/helpers/test_normalise_func.py | Python | atts_normalise_1 | atts_normalise_1 | 12 | 14 | 12 | 13 | 59390080e4c8b2d4547c27a72923c5c25edde194 | bigcode/the-stack | train |
6f209864eeaf7662e3806793 | train | function | @pytest.mark.normalise_func
@pytest.mark.parametrize(
"data,params,expected",
[(lazy_fixture("atts_normalise_2"), {}, np.array([0.2, 0.4, 0.6, 0.8, 1.0]))],
)
def test_normalise_if_negative(
data: np.ndarray, params: dict, expected: Union[float, dict, bool]
):
out = normalise_by_negative(a=data)
ass... | @pytest.mark.normalise_func
@pytest.mark.parametrize(
"data,params,expected",
[(lazy_fixture("atts_normalise_2"), {}, np.array([0.2, 0.4, 0.6, 0.8, 1.0]))],
)
def test_normalise_if_negative(
data: np.ndarray, params: dict, expected: Union[float, dict, bool]
):
| out = normalise_by_negative(a=data)
assert all(o == e for o, e in zip(out, expected)), "Test failed."
| @pytest.mark.normalise_func
@pytest.mark.parametrize(
"data,params,expected",
[(lazy_fixture("atts_normalise_2"), {}, np.array([0.2, 0.4, 0.6, 0.8, 1.0]))],
)
def test_normalise_if_negative(
data: np.ndarray, params: dict, expected: Union[float, dict, bool]
):
| 87 | 64 | 117 | 87 | 0 | sebastian-lapuschkin/Quantus | tests/helpers/test_normalise_func.py | Python | test_normalise_if_negative | test_normalise_if_negative | 50 | 59 | 50 | 57 | 21b29336097ef4bbb265980d4d597fccbd4407d8 | bigcode/the-stack | train |
3e28abfdcdd2ca0ce25ba356 | train | function | @pytest.mark.normalise_func
@pytest.mark.parametrize(
"data,params,expected",
[
(
lazy_fixture("atts_normalise_1"),
{},
np.array([0.2, 0.4, 0.6, 0.8, 0.8, 1.0, -0.2]),
)
],
)
def test_normalise_by_max(
data: np.ndarray, params: dict, expected: Union[fl... | @pytest.mark.normalise_func
@pytest.mark.parametrize(
"data,params,expected",
[
(
lazy_fixture("atts_normalise_1"),
{},
np.array([0.2, 0.4, 0.6, 0.8, 0.8, 1.0, -0.2]),
)
],
)
def test_normalise_by_max(
data: np.ndarray, params: dict, expected: Union[fl... | out = normalise_by_max(a=data)
assert all(o == e for o, e in zip(out, expected)), "Test failed."
| @pytest.mark.normalise_func
@pytest.mark.parametrize(
"data,params,expected",
[
(
lazy_fixture("atts_normalise_1"),
{},
np.array([0.2, 0.4, 0.6, 0.8, 0.8, 1.0, -0.2]),
)
],
)
def test_normalise_by_max(
data: np.ndarray, params: dict, expected: Union[fl... | 105 | 64 | 135 | 105 | 0 | sebastian-lapuschkin/Quantus | tests/helpers/test_normalise_func.py | Python | test_normalise_by_max | test_normalise_by_max | 32 | 47 | 32 | 45 | dd9bb02487c13aebffad13833df026413102b520 | bigcode/the-stack | train |
66721a3572cf42d6fc4d4428 | train | function | @pytest.fixture
def atts_denormalise_torch():
return torch.tensor(np.zeros((3, 2, 2)))
| @pytest.fixture
def atts_denormalise_torch():
| return torch.tensor(np.zeros((3, 2, 2)))
| return np.array([1.0, 2.0, 3.0, 4.0, 5.0])
@pytest.fixture
def atts_denormalise():
return np.zeros((3, 2, 2))
@pytest.fixture
def atts_denormalise_torch():
| 64 | 64 | 27 | 12 | 52 | sebastian-lapuschkin/Quantus | tests/helpers/test_normalise_func.py | Python | atts_denormalise_torch | atts_denormalise_torch | 27 | 29 | 27 | 28 | 77a34838a76041f6a701394463ed34354601def4 | bigcode/the-stack | train |
601e446ac66ff8077f374a48 | train | function | def clean_text(text):
""" Cleans the text in the only argument in various steps
ARGUMENTS: text: content/title, string
RETURNS: cleaned text, string"""
# Replace newlines by space. We want only one doc vector.
text = text.replace('\n', ' ').lower()
# Remove URLs
#text = re.sub(r"http\S+", "... | def clean_text(text):
| """ Cleans the text in the only argument in various steps
ARGUMENTS: text: content/title, string
RETURNS: cleaned text, string"""
# Replace newlines by space. We want only one doc vector.
text = text.replace('\n', ' ').lower()
# Remove URLs
#text = re.sub(r"http\S+", "", text)
# Expand ... | from gensim.parsing import preprocessing
from gensim.utils import simple_preprocess
import contractions
import pickle
from tqdm import tqdm
with open('papers_with_50_citations.pickle', 'rb') as pick:
papers_with_50_citations = pickle.load(pick)
def clean_text(text):
| 64 | 64 | 159 | 5 | 59 | ashwath92/MastersThesis | ProgsByDataset/MAG/create_mag_file_50citationsonly.py | Python | clean_text | clean_text | 14 | 30 | 14 | 14 | 9dcad166ec2e336fd246659890dfb6f72ab1d929 | bigcode/the-stack | train |
d69dde7529f83d01cd981f6f | train | class | class Elgamal:
def __init__(self, curve = curves.P192):
if not isinstance(curve, curves.Curve):
raise Exception("curve must be instance of Curve")
else:
self.curve = curve
self.secret = None
self.public = None
@property
def publicKey(self):
... | class Elgamal:
| def __init__(self, curve = curves.P192):
if not isinstance(curve, curves.Curve):
raise Exception("curve must be instance of Curve")
else:
self.curve = curve
self.secret = None
self.public = None
@property
def publicKey(self):
if self.p... | import ecc.curves as curves
import secrets
import ecc.point as point
class Elgamal:
| 21 | 69 | 232 | 5 | 15 | AlexBerg/playingwithpython | ecc/elgamal.py | Python | Elgamal | Elgamal | 6 | 37 | 6 | 6 | c437ee78edc1b19ddce1af6b7cb6a8c12704347e | bigcode/the-stack | train |
332cb2c720891aac7827f95d | train | function | def render_javascript_catalog(catalog=None, plural=None):
template = Template(js_catalog_template)
indent = lambda s: s.replace('\n', '\n ')
context = Context({
'catalog_str': indent(json.dumps(
catalog, sort_keys=True, indent=2)) if catalog else None,
'formats_str': indent(json... | def render_javascript_catalog(catalog=None, plural=None):
| template = Template(js_catalog_template)
indent = lambda s: s.replace('\n', '\n ')
context = Context({
'catalog_str': indent(json.dumps(
catalog, sort_keys=True, indent=2)) if catalog else None,
'formats_str': indent(json.dumps(
get_formats(), sort_keys=True, indent=... | = django.gettext_noop;
globals.pgettext = django.pgettext;
globals.npgettext = django.npgettext;
globals.interpolate = django.interpolate;
globals.get_format = django.get_format;
}(this));
{% endautoescape %}
"""
def render_javascript_catalog(catalog=None, plural=None):
| 64 | 64 | 107 | 12 | 52 | saukrIppl/newsea | thirdpart/django_statici18n-1.1.3-py2.7.egg/statici18n/compat.py | Python | render_javascript_catalog | render_javascript_catalog | 158 | 169 | 158 | 158 | d27a466d112b87af731a403f902a584ad7055238 | bigcode/the-stack | train |
d71068d3dfc512b74399e4fb | train | function | def get_formats():
"""
Returns all formats strings required for i18n to work
"""
FORMAT_SETTINGS = (
'DATE_FORMAT', 'DATETIME_FORMAT', 'TIME_FORMAT',
'YEAR_MONTH_FORMAT', 'MONTH_DAY_FORMAT', 'SHORT_DATE_FORMAT',
'SHORT_DATETIME_FORMAT', 'FIRST_DAY_OF_WEEK', 'DECIMAL_SEPARATOR',
... | def get_formats():
| """
Returns all formats strings required for i18n to work
"""
FORMAT_SETTINGS = (
'DATE_FORMAT', 'DATETIME_FORMAT', 'TIME_FORMAT',
'YEAR_MONTH_FORMAT', 'MONTH_DAY_FORMAT', 'SHORT_DATE_FORMAT',
'SHORT_DATETIME_FORMAT', 'FIRST_DAY_OF_WEEK', 'DECIMAL_SEPARATOR',
'THOUSAND_SE... | Error:
def upath(path):
"""
Always return a unicode path.
"""
if six.PY2 and not isinstance(path, six.text_type):
fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
return path.decode(fs_encoding)
return path
def get_formats():
| 64 | 64 | 205 | 4 | 59 | saukrIppl/newsea | thirdpart/django_statici18n-1.1.3-py2.7.egg/statici18n/compat.py | Python | get_formats | get_formats | 28 | 49 | 28 | 28 | 79c95561b9805c79e2b24f6d5a76496f325398f7 | bigcode/the-stack | train |
5339e933abefaef976fa4afe | train | function | def get_javascript_catalog(locale, domain, packages):
default_locale = to_locale(settings.LANGUAGE_CODE)
packages = [p for p in packages if p == 'django.conf' or p in settings.INSTALLED_APPS]
t = {}
paths = []
en_selected = locale.startswith('en')
en_catalog_missing = True
# paths of request... | def get_javascript_catalog(locale, domain, packages):
| default_locale = to_locale(settings.LANGUAGE_CODE)
packages = [p for p in packages if p == 'django.conf' or p in settings.INSTALLED_APPS]
t = {}
paths = []
en_selected = locale.startswith('en')
en_catalog_missing = True
# paths of requested packages
for package in packages:
p = i... | ) == 'undefined') {
return format_type;
} else {
return value;
}
};
/* add to global namespace */
globals.pluralidx = django.pluralidx;
globals.gettext = django.gettext;
globals.ngettext = django.ngettext;
globals.gettext_noop = django.gettext_noop;
globals.pgettext = django.pgettext;... | 235 | 235 | 786 | 11 | 224 | saukrIppl/newsea | thirdpart/django_statici18n-1.1.3-py2.7.egg/statici18n/compat.py | Python | get_javascript_catalog | get_javascript_catalog | 172 | 254 | 172 | 172 | d4758a2858680246fbb5b6d4630707f345df3a96 | bigcode/the-stack | train |
ce8f836395af4617c5194076 | train | function | def geterror():
return sys.exc_info()[1]
| def geterror():
| return sys.exc_info()[1]
| ord_', 'unichr_',
'unicode_', 'raw_input_', 'as_bytes', 'as_unicode',
'bytes_', 'next_', 'imap_', 'PY_MAJOR_VERSION', 'PY_MINOR_VERSION']
PY_MAJOR_VERSION, PY_MINOR_VERSION = sys.version_info[0:2]
def geterror():
| 64 | 64 | 12 | 4 | 60 | CiubucAlexandra/Theremine-Projet-Micriprocesseurs | pygame/lib/compat.py | Python | geterror | geterror | 13 | 14 | 13 | 13 | a6c86ba8f02ebf25a8f77c9762fadae9180fdc75 | bigcode/the-stack | train |
5f6267bc059583a999967e87 | train | function | def ord_(o):
try:
return ord(o)
except TypeError:
return o
| def ord_(o):
| try:
return ord(o)
except TypeError:
return o
| """
return string
def as_unicode(rstring):
""" r'<Unicode literal>' => u'<Unicode literal>' """
return rstring.decode('unicode_escape', 'strict')
def get_BytesIO():
return BytesIO
def get_StringIO():
return StringIO
def ord_(o):
| 64 | 64 | 22 | 5 | 58 | CiubucAlexandra/Theremine-Projet-Micriprocesseurs | pygame/lib/compat.py | Python | ord_ | ord_ | 82 | 86 | 82 | 82 | e80d6fa3da3c3297394a93423403fe1a915c565e | bigcode/the-stack | train |
39597930eada480cc908d7cf | train | function | def filesystem_encode(u):
fsencoding = sys.getfilesystemencoding()
if fsencoding.lower() in ['ascii', 'ansi_x3.4-1968'] and sys.platform.startswith('linux'):
# Don't believe Linux systems claiming ASCII-only filesystems. In
# practice, arbitrary bytes are allowed, and most things expect UTF-8.
... | def filesystem_encode(u):
| fsencoding = sys.getfilesystemencoding()
if fsencoding.lower() in ['ascii', 'ansi_x3.4-1968'] and sys.platform.startswith('linux'):
# Don't believe Linux systems claiming ASCII-only filesystems. In
# practice, arbitrary bytes are allowed, and most things expect UTF-8.
fsencoding = 'utf-8... | ):
try:
return ord(o)
except TypeError:
return o
if sys.platform == 'win32':
filesystem_errors = "replace"
elif PY_MAJOR_VERSION >= 3:
filesystem_errors = "surrogateescape"
else:
filesystem_errors = "strict"
def filesystem_encode(u):
| 64 | 64 | 91 | 5 | 59 | CiubucAlexandra/Theremine-Projet-Micriprocesseurs | pygame/lib/compat.py | Python | filesystem_encode | filesystem_encode | 96 | 102 | 96 | 96 | a85679d68bb0cada79bf9f2fa86678862d651c14 | bigcode/the-stack | train |
a8a10f196f9479730513cd1b | train | function | def get_BytesIO():
return BytesIO
| def get_BytesIO():
| return BytesIO
| 3.x
def as_bytes(string):
""" '<binary literal>' => '<binary literal>' """
return string
def as_unicode(rstring):
""" r'<Unicode literal>' => u'<Unicode literal>' """
return rstring.decode('unicode_escape', 'strict')
def get_BytesIO():
| 64 | 64 | 11 | 6 | 58 | CiubucAlexandra/Theremine-Projet-Micriprocesseurs | pygame/lib/compat.py | Python | get_BytesIO | get_BytesIO | 74 | 75 | 74 | 74 | bd0d92ae0a53eab6e7b5afb40772f3cb215492ec | bigcode/the-stack | train |
11f71b6d2a9ef76ae925e1f2 | train | function | def get_StringIO():
return StringIO
| def get_StringIO():
| return StringIO
| """ '<binary literal>' => '<binary literal>' """
return string
def as_unicode(rstring):
""" r'<Unicode literal>' => u'<Unicode literal>' """
return rstring.decode('unicode_escape', 'strict')
def get_BytesIO():
return BytesIO
def get_StringIO():
| 64 | 64 | 10 | 5 | 58 | CiubucAlexandra/Theremine-Projet-Micriprocesseurs | pygame/lib/compat.py | Python | get_StringIO | get_StringIO | 78 | 79 | 78 | 78 | 290d7d9ccddfc2fb91bd169be7f27815f2b4e921 | bigcode/the-stack | train |
8bf957ff3a1218574fd7c895 | train | function | def nlp_prefilter(query):
"""
Prefilter user query
:param str query: User text
:return: Improved query for further processing
:rtype: str
"""
query_lower = query.lower()
# TODO: support in sentence replacements and more cases
if query_lower == "today":
return datetime.date... | def nlp_prefilter(query):
| """
Prefilter user query
:param str query: User text
:return: Improved query for further processing
:rtype: str
"""
query_lower = query.lower()
# TODO: support in sentence replacements and more cases
if query_lower == "today":
return datetime.datetime.today().strftime("%m/... | # Tokenize the raw text
token_list = word_tokenize(raw_text_rejoined)
# Remove stop words and punctuation
cleaned_and_tokenized_list = [w for w in token_list if w not in stop_words_list]
return cleaned_and_tokenized_list
def nlp_prefilter(query):
| 64 | 64 | 119 | 7 | 56 | jvm123/botstory | botstory/nlp.py | Python | nlp_prefilter | nlp_prefilter | 64 | 82 | 64 | 64 | 3c3c17f17faaa739a37cea25f3f0081b38890d74 | bigcode/the-stack | train |
68e9907f4f2bf96843223d36 | train | function | def identify_word_classes(tokens, word_classes):
"""
Match word classes to the token list
:param list tokens: List of tokens
:param dict word_classes: Dictionary of word lists to find and tag with the
respective dictionary key
:return: Matched word classes
:rtype: list
"""
if w... | def identify_word_classes(tokens, word_classes):
| """
Match word classes to the token list
:param list tokens: List of tokens
:param dict word_classes: Dictionary of word lists to find and tag with the
respective dictionary key
:return: Matched word classes
:rtype: list
"""
if word_classes is None:
word_classes = []
... | continue
if not current:
current = word
else:
# If multiple NN* tags follow, combine the word back into a single noun
current += " " + word
if current:
nouns.append(current)
return nouns
def identify_word_classes(tokens, word_classes):
| 64 | 64 | 119 | 9 | 54 | jvm123/botstory | botstory/nlp.py | Python | identify_word_classes | identify_word_classes | 155 | 174 | 155 | 155 | d3d51e4445cc015b518560d13b5a86fee07ae53f | bigcode/the-stack | train |
66a541fc27ebcb4558fd4c54 | train | function | def cleaned_episode(raw_text, custom_stop_words = False):
"""
Tokenize a string
Adapted from Alex Mitrani at https://gist.githubusercontent.com/amitrani6/24116fbb08d315799492cdac36de833e/raw/f686cec899c941a45449c316328aee6e4999b40d/NLTK_script_cleaning_function.py
:param str raw_string: Input text
... | def cleaned_episode(raw_text, custom_stop_words = False):
| """
Tokenize a string
Adapted from Alex Mitrani at https://gist.githubusercontent.com/amitrani6/24116fbb08d315799492cdac36de833e/raw/f686cec899c941a45449c316328aee6e4999b40d/NLTK_script_cleaning_function.py
:param str raw_string: Input text
:param bool custom_stop_words: Additional stop words to us... | """
(C) 2021 Julian von Mendel <prog@derjulian.net>
nlp.py
====================================
NLP functions
"""
import re
import string
import datetime
import nltk
import dateutil.parser
from nltk.corpus import stopwords
from nltk import word_tokenize
def cleaned_episode(raw_text, custom_stop_words = False):
| 73 | 135 | 450 | 12 | 60 | jvm123/botstory | botstory/nlp.py | Python | cleaned_episode | cleaned_episode | 17 | 62 | 17 | 17 | 5ce546c97c2f6ea4de48550f24928cedb29445f4 | bigcode/the-stack | train |
68d8dfa85faa692c7eb30de4 | train | function | def nlp_analyze(query, word_classes = None, skip_words_in_nlp = 0):
"""
Run a number of NLP tasks on a given sentence
:param str query: Input text
:param dict word_classes: Dictionary of word lists to find and tag with the
respective dictionary key
:param int skip_words_in_nlp: Parameter fo... | def nlp_analyze(query, word_classes = None, skip_words_in_nlp = 0):
| """
Run a number of NLP tasks on a given sentence
:param str query: Input text
:param dict word_classes: Dictionary of word lists to find and tag with the
respective dictionary key
:param int skip_words_in_nlp: Parameter for find_nouns()
:return: Dict of format { 'query': cleaned_query,... | " + word
if current:
nouns.append(current)
return nouns
def identify_word_classes(tokens, word_classes):
"""
Match word classes to the token list
:param list tokens: List of tokens
:param dict word_classes: Dictionary of word lists to find and tag with the
respective diction... | 157 | 157 | 524 | 21 | 135 | jvm123/botstory | botstory/nlp.py | Python | nlp_analyze | nlp_analyze | 176 | 237 | 176 | 176 | a4996ca580cd54c50abcb0d6d315ca7a11f69a65 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.