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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a4cb8ae133c6708167d73045 | train | function | def schedule_filter(semester=SEMESTER, academic_year=ACADEMIC_YEAR, user_category=USER_CATEGORY, user_specialization=USER_SPECIALIZATION, num_credits=NUM_CREDITS, user_days=USER_DAYS):
url="https://www.stern.nyu.edu/registrar/shim2.cgi?studtype=PT2&tm=" + academic_year + semester
# Make a GET request to fetch... | def schedule_filter(semester=SEMESTER, academic_year=ACADEMIC_YEAR, user_category=USER_CATEGORY, user_specialization=USER_SPECIALIZATION, num_credits=NUM_CREDITS, user_days=USER_DAYS):
| url="https://www.stern.nyu.edu/registrar/shim2.cgi?studtype=PT2&tm=" + academic_year + semester
# Make a GET request to fetch the raw HTML content
html_content = requests.get(url).text
# Parse the html content
soup = BeautifulSoup(html_content, "html.parser")
class_list = soup.find(id="schedu... | # app/schedule.py
from bs4 import BeautifulSoup
import bs4 # needed for element type identification
import requests
import pandas as pd
import re # importing regular expression
# Below are default values for the variables; users will get to specify their own values through the webpage
SEMESTER = "F"
ACADEMIC_YEAR = "... | 164 | 256 | 1,350 | 48 | 116 | TL81-NYUSTERN/stern-course-scheduler | app/schedule.py | Python | schedule_filter | schedule_filter | 18 | 146 | 18 | 19 | 494a0e3e826ca1b8b0b60bf86571354318a8c2d8 | bigcode/the-stack | train |
490b5811dd05c7a001b913f2 | train | function | def entropy(pk, qk=None, base=None):
"""Calculate the entropy of a distribution for given probability values.
If only probabilities `pk` are given, the entropy is calculated as
``S = -sum(pk * log(pk), axis=0)``.
If `qk` is not None, then compute the Kullback-Leibler divergence
``S = sum(pk * log(... | def entropy(pk, qk=None, base=None):
| """Calculate the entropy of a distribution for given probability values.
If only probabilities `pk` are given, the entropy is calculated as
``S = -sum(pk * log(pk), axis=0)``.
If `qk` is not None, then compute the Kullback-Leibler divergence
``S = sum(pk * log(pk / qk), axis=0)``.
This routin... |
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
... | 114 | 114 | 381 | 11 | 102 | tomzhang/mars-1 | mars/tensor/stats/entropy.py | Python | entropy | entropy | 23 | 67 | 23 | 23 | f88cef0b93ae1031a231f3037e4b9f60208f49f0 | bigcode/the-stack | train |
d6fc89cc04993b2293e06ff9 | train | function | @benchmark_only
@pytest.mark.benchmark(
group="benchmark_single_param",
)
@pytest.mark.parametrize(
"benchmark_data",
[(10 * s, 10 * s) for s in list(range(0, 101, 10))[1:]],
indirect=["benchmark_data"],
)
def test_benchmark_workaround_590_x_only(
benchmark,
benchmark_data,
workaround_590_im... | @benchmark_only
@pytest.mark.benchmark(
group="benchmark_single_param",
)
@pytest.mark.parametrize(
"benchmark_data",
[(10 * s, 10 * s) for s in list(range(0, 101, 10))[1:]],
indirect=["benchmark_data"],
)
def test_benchmark_workaround_590_x_only(
benchmark,
benchmark_data,
workaround_590_im... | benchmark.pedantic(
workaround_590_impl,
kwargs={"X": benchmark_data, "Y": None},
warmup_rounds=WARMUP_ROUNDS,
iterations=ITERATIONS,
rounds=ROUNDS,
)
| @benchmark_only
@pytest.mark.benchmark(
group="benchmark_single_param",
)
@pytest.mark.parametrize(
"benchmark_data",
[(10 * s, 10 * s) for s in list(range(0, 101, 10))[1:]],
indirect=["benchmark_data"],
)
def test_benchmark_workaround_590_x_only(
benchmark,
benchmark_data,
workaround_590_im... | 91 | 64 | 141 | 91 | 0 | JamesRH/umap | umap/tests/test_chunked_parallel_spatial_metric.py | Python | test_benchmark_workaround_590_x_only | test_benchmark_workaround_590_x_only | 257 | 279 | 257 | 272 | e2f55261e9b124d5f59d4a6629306d712865616b | bigcode/the-stack | train |
4e0bdcb4ba36c475bf345a76 | train | function | @benchmark_only
@pytest.mark.benchmark(
group="benchmark_X_Y_params",
)
@pytest.mark.parametrize(
"benchmark_data",
[(10 * s, 10 * s) for s in list(range(0, 101, 10))[1:]],
indirect=["benchmark_data"],
)
def test_benchmark_chunked_parallel_special_metric_x_y(
benchmark,
benchmark_data,
):
#... | @benchmark_only
@pytest.mark.benchmark(
group="benchmark_X_Y_params",
)
@pytest.mark.parametrize(
"benchmark_data",
[(10 * s, 10 * s) for s in list(range(0, 101, 10))[1:]],
indirect=["benchmark_data"],
)
def test_benchmark_chunked_parallel_special_metric_x_y(
benchmark,
benchmark_data,
):
#... | benchmark.pedantic(
dist.chunked_parallel_special_metric,
kwargs={"X": benchmark_data, "Y": benchmark_data},
warmup_rounds=WARMUP_ROUNDS,
iterations=ITERATIONS,
rounds=ROUNDS,
)
| @benchmark_only
@pytest.mark.benchmark(
group="benchmark_X_Y_params",
)
@pytest.mark.parametrize(
"benchmark_data",
[(10 * s, 10 * s) for s in list(range(0, 101, 10))[1:]],
indirect=["benchmark_data"],
)
def test_benchmark_chunked_parallel_special_metric_x_y(
benchmark,
benchmark_data,
):
#... | 87 | 64 | 140 | 87 | 0 | JamesRH/umap | umap/tests/test_chunked_parallel_spatial_metric.py | Python | test_benchmark_chunked_parallel_special_metric_x_y | test_benchmark_chunked_parallel_special_metric_x_y | 287 | 308 | 287 | 301 | 4e4ece9d7b8c0236b1fbe3057575a7cb34910650 | bigcode/the-stack | train |
d27e555d37b5c617f5a58709 | train | function | @pytest.fixture(scope="function")
def workaround_590_impl():
@numba.njit(parallel=True, nogil=True)
def chunked_parallel_special_metric(
X, Y=None, metric=dist.named_distances["hellinger"], chunk_size=16
):
if Y is None:
size = X.shape[0]
result = np.zeros((size, size... | @pytest.fixture(scope="function")
def workaround_590_impl():
@numba.njit(parallel=True, nogil=True)
| def chunked_parallel_special_metric(
X, Y=None, metric=dist.named_distances["hellinger"], chunk_size=16
):
if Y is None:
size = X.shape[0]
result = np.zeros((size, size), dtype=np.float32)
n_row_chunks = (size // chunk_size) + 1
for chunk_idx in nu... | _chunks):
n = chunk_idx * chunk_size
chunk_end_n = min(n + chunk_size, row_size)
for m in range(0, col_size, chunk_size):
chunk_end_m = min(m + chunk_size, col_size)
for i in range(n, chunk_end_n):
for j in r... | 134 | 134 | 448 | 26 | 107 | JamesRH/umap | umap/tests/test_chunked_parallel_spatial_metric.py | Python | workaround_590_impl | workaround_590_impl | 71 | 117 | 71 | 73 | 38c1dd6b8646df4f6da1acdba0d3c181db0c3c6c | bigcode/the-stack | train |
016e9bda99bd6dd10a0a5f53 | train | function | @benchmark_only
@pytest.mark.benchmark(
group="benchmark_single_param",
)
@pytest.mark.parametrize(
"benchmark_data",
[(10 * s, 10 * s) for s in list(range(0, 101, 10))[1:]],
indirect=["benchmark_data"],
)
def test_benchmark_chunked_parallel_special_metric_x_only(
benchmark,
benchmark_data,
):
... | @benchmark_only
@pytest.mark.benchmark(
group="benchmark_single_param",
)
@pytest.mark.parametrize(
"benchmark_data",
[(10 * s, 10 * s) for s in list(range(0, 101, 10))[1:]],
indirect=["benchmark_data"],
)
def test_benchmark_chunked_parallel_special_metric_x_only(
benchmark,
benchmark_data,
):
... | benchmark.pedantic(
dist.chunked_parallel_special_metric,
kwargs={"X": benchmark_data, "Y": None},
warmup_rounds=WARMUP_ROUNDS,
iterations=ITERATIONS,
rounds=ROUNDS,
)
| @benchmark_only
@pytest.mark.benchmark(
group="benchmark_single_param",
)
@pytest.mark.parametrize(
"benchmark_data",
[(10 * s, 10 * s) for s in list(range(0, 101, 10))[1:]],
indirect=["benchmark_data"],
)
def test_benchmark_chunked_parallel_special_metric_x_only(
benchmark,
benchmark_data,
):
... | 86 | 64 | 138 | 86 | 0 | JamesRH/umap | umap/tests/test_chunked_parallel_spatial_metric.py | Python | test_benchmark_chunked_parallel_special_metric_x_only | test_benchmark_chunked_parallel_special_metric_x_only | 233 | 254 | 233 | 247 | 3d34fd9ba81a30b09718df2e83069e00ba957774 | bigcode/the-stack | train |
c3b44f82fb9c71eee9b4c098 | train | function | @benchmark_only
def test_chunked_parallel_alternative_implementations(
spatial_data, workaround_590_impl
):
# Base tests that must pass!
dist_matrix_x = workaround_590_impl(np.abs(spatial_data[:-2]))
dist_matrix_xy = workaround_590_impl(
np.abs(spatial_data[:-2]), np.abs(spatial_data[:-2])
)... | @benchmark_only
def test_chunked_parallel_alternative_implementations(
spatial_data, workaround_590_impl
):
# Base tests that must pass!
| dist_matrix_x = workaround_590_impl(np.abs(spatial_data[:-2]))
dist_matrix_xy = workaround_590_impl(
np.abs(spatial_data[:-2]), np.abs(spatial_data[:-2])
)
dist_matrix_x_full = dist.chunked_parallel_special_metric(np.abs(spatial_data[:-2]))
dist_matrix_xy_full = dist.chunked_parallel_specia... | = request.param
spatial_data = np.random.randn(*shape).astype(np.float32)
return np.abs(spatial_data)
# ---------------------------------------------------------------
@benchmark_only
def test_chunked_parallel_alternative_implementations(
spatial_data, workaround_590_impl
):
# Base tests that must pa... | 63 | 64 | 191 | 33 | 30 | JamesRH/umap | umap/tests/test_chunked_parallel_spatial_metric.py | Python | test_chunked_parallel_alternative_implementations | test_chunked_parallel_alternative_implementations | 130 | 155 | 130 | 134 | fedfae8932b2a09bbd529432253c8a2b6c4587e5 | bigcode/the-stack | train |
2abe4fa37113c52656ef44d5 | train | function | @pytest.fixture(scope="function")
def benchmark_data(request):
shape = request.param
spatial_data = np.random.randn(*shape).astype(np.float32)
return np.abs(spatial_data)
| @pytest.fixture(scope="function")
def benchmark_data(request):
| shape = request.param
spatial_data = np.random.randn(*shape).astype(np.float32)
return np.abs(spatial_data)
| for i in range(n, chunk_end_n):
for j in range(m, chunk_end_m):
d = metric(X[i], Y[j])
result[i, j] = d
return result
return chunked_parallel_special_metric
@pytest.fixture(scope="function")
def benchmark_data(request):
| 64 | 64 | 40 | 11 | 52 | JamesRH/umap | umap/tests/test_chunked_parallel_spatial_metric.py | Python | benchmark_data | benchmark_data | 120 | 124 | 120 | 121 | 987a5d2d1af9ec65c06f5ebe6872d833fa6e031c | bigcode/the-stack | train |
be52a55700b157ce2e8528bc | train | function | @benchmark_only
@pytest.mark.benchmark(
group="benchmark_X_Y_params",
)
@pytest.mark.parametrize(
"benchmark_data",
[(10 * s, 10 * s) for s in list(range(0, 101, 10))[1:]],
indirect=["benchmark_data"],
)
def test_benchmark_workaround_590_x_y(
benchmark,
benchmark_data,
workaround_590_impl,
)... | @benchmark_only
@pytest.mark.benchmark(
group="benchmark_X_Y_params",
)
@pytest.mark.parametrize(
"benchmark_data",
[(10 * s, 10 * s) for s in list(range(0, 101, 10))[1:]],
indirect=["benchmark_data"],
)
def test_benchmark_workaround_590_x_y(
benchmark,
benchmark_data,
workaround_590_impl,
)... | benchmark.pedantic(
workaround_590_impl,
kwargs={"X": benchmark_data, "Y": benchmark_data},
warmup_rounds=WARMUP_ROUNDS,
iterations=ITERATIONS,
rounds=ROUNDS,
)
| @benchmark_only
@pytest.mark.benchmark(
group="benchmark_X_Y_params",
)
@pytest.mark.parametrize(
"benchmark_data",
[(10 * s, 10 * s) for s in list(range(0, 101, 10))[1:]],
indirect=["benchmark_data"],
)
def test_benchmark_workaround_590_x_y(
benchmark,
benchmark_data,
workaround_590_impl,
)... | 92 | 64 | 143 | 92 | 0 | JamesRH/umap | umap/tests/test_chunked_parallel_spatial_metric.py | Python | test_benchmark_workaround_590_x_y | test_benchmark_workaround_590_x_y | 311 | 333 | 311 | 326 | 282da0214d8d5c052e04ea5e778e80907cdd04cf | bigcode/the-stack | train |
d6bb532beecdd217f5ed8be2 | train | function | @benchmark_only
def test_chunked_parallel_special_metric_implementation_hellinger(
spatial_data,
stashed_previous_impl_for_regression_test,
):
# Base tests that must pass!
dist_matrix_x = dist.chunked_parallel_special_metric(np.abs(spatial_data[:-2]))
dist_matrix_xy = dist.chunked_parallel_special_... | @benchmark_only
def test_chunked_parallel_special_metric_implementation_hellinger(
spatial_data,
stashed_previous_impl_for_regression_test,
):
# Base tests that must pass!
| dist_matrix_x = dist.chunked_parallel_special_metric(np.abs(spatial_data[:-2]))
dist_matrix_xy = dist.chunked_parallel_special_metric(
np.abs(spatial_data[:-2]), np.abs(spatial_data[:-2])
)
test_matrix = np.array(
[
[
dist.hellinger_grad(np.abs(spatial_data[i]... | _full = dist.chunked_parallel_special_metric(np.abs(spatial_data[:-2]))
dist_matrix_xy_full = dist.chunked_parallel_special_metric(
np.abs(spatial_data[:-2]), np.abs(spatial_data[:-2])
)
assert_array_equal(
dist_matrix_x_full,
dist_matrix_x,
err_msg="Distances don't match fo... | 148 | 148 | 495 | 40 | 108 | JamesRH/umap | umap/tests/test_chunked_parallel_spatial_metric.py | Python | test_chunked_parallel_special_metric_implementation_hellinger | test_chunked_parallel_special_metric_implementation_hellinger | 158 | 224 | 158 | 164 | ce6587158ba79d86731f3922c12fba89aaafcf7d | bigcode/the-stack | train |
3f04a03632e57b65eb4723db | train | function | @pytest.fixture(scope="function")
def stashed_previous_impl_for_regression_test():
@numba.njit(parallel=True, nogil=True)
def stashed_chunked_parallel_special_metric(
X, Y=None, metric=dist.named_distances["hellinger"], chunk_size=16
):
if Y is None:
row_size = col_size = X.shape... | @pytest.fixture(scope="function")
def stashed_previous_impl_for_regression_test():
@numba.njit(parallel=True, nogil=True)
| def stashed_chunked_parallel_special_metric(
X, Y=None, metric=dist.named_distances["hellinger"], chunk_size=16
):
if Y is None:
row_size = col_size = X.shape[0]
else:
row_size = X.shape[0]
col_size = Y.shape[0]
result = np.zeros((row_size, col... | import pytest
import numba
import os
import numpy as np
from numpy.testing import assert_array_equal
from umap import distances as dist
benchmark_only = pytest.mark.skipif(
"BENCHARM_TEST" not in os.environ, reason="Benchmark tests skipped"
)
# Constants for benchmark
WARMUP_ROUNDS = 5
ITERATIONS = 10
ROUNDS = 10
... | 123 | 138 | 461 | 30 | 92 | JamesRH/umap | umap/tests/test_chunked_parallel_spatial_metric.py | Python | stashed_previous_impl_for_regression_test | stashed_previous_impl_for_regression_test | 21 | 68 | 21 | 23 | daad03795404f2294baeae0db45e010ff73d15b0 | bigcode/the-stack | train |
8b871f1d26c215f51633d513 | train | class | class OrderedCreditInline(generic.GenericTabularInline):
verbose_name = _('author or source')
verbose_name_plural = _('authors or sources')
classes = ('collapse open',)
model = OrderedCredit
raw_id_fields = ('credit',)
related_lookup_fields = {
'fk': ['credit'],
}
ex... | class OrderedCreditInline(generic.GenericTabularInline):
| verbose_name = _('author or source')
verbose_name_plural = _('authors or sources')
classes = ('collapse open',)
model = OrderedCredit
raw_id_fields = ('credit',)
related_lookup_fields = {
'fk': ['credit'],
}
extra = 0
# formfield_overrides = {
# Posi... | interface.
'''
from django.contrib import admin
from django.contrib.contenttypes import generic
from django.forms.widgets import HiddenInput
from django.db.models import PositiveIntegerField
from django.utils.translation import ugettext as _
from models import Credit, OrderedCredit
class OrderedCreditInline(generi... | 64 | 64 | 110 | 11 | 52 | nathangeffen/tbonline3 | tbonlineproject/credit/admin.py | Python | OrderedCreditInline | OrderedCreditInline | 14 | 30 | 14 | 14 | f518d944527f816fd46dac47225afdf3ab54e372 | bigcode/the-stack | train |
e083687e0513162ed18ee89c | train | class | class OrderedCreditAdmin(admin.ModelAdmin):
list_display = ('id', 'content_type', 'object_id', 'content_object', 'position', 'credit')
| class OrderedCreditAdmin(admin.ModelAdmin):
| list_display = ('id', 'content_type', 'object_id', 'content_object', 'position', 'credit')
| ','last_name')
list_display = ('id', 'first_names', 'last_name', 'is_person', 'url')
list_editable = ('first_names', 'last_name', 'is_person', 'url')
list_filter = ('is_person',)
class OrderedCreditAdmin(admin.ModelAdmin):
| 63 | 64 | 33 | 8 | 55 | nathangeffen/tbonline3 | tbonlineproject/credit/admin.py | Python | OrderedCreditAdmin | OrderedCreditAdmin | 38 | 39 | 38 | 38 | ca27d03100e2266805c77ac3567eb07280804ab2 | bigcode/the-stack | train |
cc70f2128947e24f6ad8ba79 | train | class | class CreditAdmin(admin.ModelAdmin):
search_fields = ('first_names','last_name')
list_display = ('id', 'first_names', 'last_name', 'is_person', 'url')
list_editable = ('first_names', 'last_name', 'is_person', 'url')
list_filter = ('is_person',)
| class CreditAdmin(admin.ModelAdmin):
| search_fields = ('first_names','last_name')
list_display = ('id', 'first_names', 'last_name', 'is_person', 'url')
list_editable = ('first_names', 'last_name', 'is_person', 'url')
list_filter = ('is_person',)
| ',)
related_lookup_fields = {
'fk': ['credit'],
}
extra = 0
# formfield_overrides = {
# PositiveIntegerField: {'widget': HiddenInput},
# }
sortable_field_name = 'position'
class CreditAdmin(admin.ModelAdmin):
| 64 | 64 | 70 | 7 | 57 | nathangeffen/tbonline3 | tbonlineproject/credit/admin.py | Python | CreditAdmin | CreditAdmin | 32 | 36 | 32 | 32 | f7f724fdd12040891e68dad35aaf1e49c86a61b2 | bigcode/the-stack | train |
36e63545e6e7c92e1fd51fdb | train | class | class BoxmodeValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(self, plotly_name="boxmode", parent_name="layout", **kwargs):
super(BoxmodeValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type",... | class BoxmodeValidator(_plotly_utils.basevalidators.EnumeratedValidator):
| def __init__(self, plotly_name="boxmode", parent_name="layout", **kwargs):
super(BoxmodeValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
role=kwargs.pop("role", "info"),
values=... | import _plotly_utils.basevalidators
class BoxmodeValidator(_plotly_utils.basevalidators.EnumeratedValidator):
| 23 | 64 | 107 | 15 | 7 | acrucetta/Chicago_COVI_WebApp | env/lib/python3.8/site-packages/plotly/validators/layout/_boxmode.py | Python | BoxmodeValidator | BoxmodeValidator | 4 | 13 | 4 | 4 | 3fcd7d26595180b98decb2476798f74b2b8e215b | bigcode/the-stack | train |
5a7dc51500c74095ceb75294 | train | function | def process_img(image):
chess_board_imgs = os.listdir('camera_cal')
prepro = CameraPreprocessing(chess_board_imgs)
undistorted_img = prepro.undistort(image)
cg = ColorAndGradient(undistorted_img)
cg_comb_binary = cg.combined()
warping = WarpAndFindLane(cg_comb_binary)
warped_img, M, Minv ... | def process_img(image):
| chess_board_imgs = os.listdir('camera_cal')
prepro = CameraPreprocessing(chess_board_imgs)
undistorted_img = prepro.undistort(image)
cg = ColorAndGradient(undistorted_img)
cg_comb_binary = cg.combined()
warping = WarpAndFindLane(cg_comb_binary)
warped_img, M, Minv = warping.warp()
hi... |
from camera_calibration import CameraPreprocessing
from color_and_gradient import ColorAndGradient
from warp_find_lane import WarpAndFindLane
from find_lane_pixels import FindLanePixels
from offset_and_curve import OffsetAndCurve
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))
fig.tight_layout()
def process_im... | 81 | 81 | 273 | 5 | 76 | koki1610168/CarNd-Advanced-Lane-Lines | main.py | Python | process_img | process_img | 18 | 43 | 18 | 18 | b023b0ff4198887f3b0838d5bd8157b0e676da3e | bigcode/the-stack | train |
e717d01956b9f26257de3c15 | train | class | class FileInfo(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict... | class FileInfo(object):
| """
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute ... | # coding: utf-8
"""
Copyright (c) 2021 Aspose.Cells Cloud
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, ... | 246 | 256 | 972 | 5 | 240 | aspose-cells-cloud/aspose-cells-cloud-python | asposecellscloud/models/file_info.py | Python | FileInfo | FileInfo | 29 | 206 | 29 | 29 | ae6c3caf951abd4349c5b7937c114d295071be4f | bigcode/the-stack | train |
1f86ec24957f65c0ef545c89 | train | function | def _get_all_setlists(date,sl_type):
try:
sls = sldb.Setlist.select().where(sldb.Setlist.date == date,
sldb.Setlist.sl_type==sl_type)
except Exception:
raise falcon.HTTPError(falcon.HTTP_400, '{"Error":"No records"}')
slf = []
for sl in sls:
... | def _get_all_setlists(date,sl_type):
| try:
sls = sldb.Setlist.select().where(sldb.Setlist.date == date,
sldb.Setlist.sl_type==sl_type)
except Exception:
raise falcon.HTTPError(falcon.HTTP_400, '{"Error":"No records"}')
slf = []
for sl in sls:
slf.append(_get_setlist(sl.uuid)... | ":"'+s.title+'","seq":"'+str(s.seq)+'"},'
sl_json = sl_json[:-1] #get rid of extra trailling comma
sl_json += ']}'
return sl_json
#return list of json
def _get_all_setlists(date,sl_type):
| 64 | 64 | 96 | 11 | 52 | Hiromi-nee/ds_setlist | setlists.py | Python | _get_all_setlists | _get_all_setlists | 25 | 35 | 25 | 25 | 54049cde7e2be073f73e0cf9732999a1678ffa0f | bigcode/the-stack | train |
57ac94abc458c819d198bd23 | train | class | class Retrieve(object):
def on_get(self,req,resp,date,sl_type,sl_no):
f_date = date[:2]+"/"+date[2:4]+"/"+date[4:]
rbody = ''
if sl_no == "0":
rbody = ','.join(_get_all_setlists(f_date,sl_type))
else:
rbody = _get_setlist(date+"_"+sl_type+"_"+sl_no)
if... | class Retrieve(object):
| def on_get(self,req,resp,date,sl_type,sl_no):
f_date = date[:2]+"/"+date[2:4]+"/"+date[4:]
rbody = ''
if sl_no == "0":
rbody = ','.join(_get_all_setlists(f_date,sl_type))
else:
rbody = _get_setlist(date+"_"+sl_type+"_"+sl_no)
if rbody == None:
... | _no']+" "+p_json['location']+" "+p_json['sl_size']+"\n"
for x in p_json['songs']:
pbody += x['seq']+" "+x['artiste']+" "+x['title']+"\n"
resp.body = pbody
class Retrieve(object):
| 64 | 64 | 130 | 4 | 59 | Hiromi-nee/ds_setlist | setlists.py | Python | Retrieve | Retrieve | 87 | 98 | 87 | 87 | db74ee93d9bf5c929c4f6e0bb2a5b19f852ca54c | bigcode/the-stack | train |
be367e4fc77fcb72aa6f4210 | train | class | class Create(object):
def on_get(self,req,resp):
resp.body = '{"error":"No method"}'
resp.status = falcon.HTTP_200
def on_post(self, req, resp,usrid):
if usrid != 'hiromi':
raise falcon.HTTPError(falcon.HTTP_753, 'No auth')
temp = req.stream.read()
try:
... | class Create(object):
| def on_get(self,req,resp):
resp.body = '{"error":"No method"}'
resp.status = falcon.HTTP_200
def on_post(self, req, resp,usrid):
if usrid != 'hiromi':
raise falcon.HTTPError(falcon.HTTP_753, 'No auth')
temp = req.stream.read()
try:
p_json = json.l... | _json = sl_json[:-1] #get rid of extra trailling comma
sl_json += ']}'
return sl_json
#return list of json
def _get_all_setlists(date,sl_type):
try:
sls = sldb.Setlist.select().where(sldb.Setlist.date == date,
sldb.Setlist.sl_type==sl_type)
e... | 136 | 136 | 455 | 4 | 131 | Hiromi-nee/ds_setlist | setlists.py | Python | Create | Create | 38 | 85 | 38 | 38 | e5e4a702e69e75d13f0577d09b560809f10bc482 | bigcode/the-stack | train |
fd602560ba3287651ab9f415 | train | function | def _get_setlist(uuid):
try:
sngs = sldb.Song.select().join(sldb.Setlist).where(sldb.Setlist.uuid == uuid)
sl = sldb.Setlist.select().where(sldb.Setlist.uuid == uuid)[0]
except IndexError:
raise falcon.HTTPError(falcon.HTTP_400, '{"Error":"No records"}')
sl_json = '{"date":"'+sl.date... | def _get_setlist(uuid):
| try:
sngs = sldb.Song.select().join(sldb.Setlist).where(sldb.Setlist.uuid == uuid)
sl = sldb.Setlist.select().where(sldb.Setlist.uuid == uuid)[0]
except IndexError:
raise falcon.HTTPError(falcon.HTTP_400, '{"Error":"No records"}')
sl_json = '{"date":"'+sl.date+'","sl_type":"'+sl.sl_t... | import sldb
import re
import falcon
import json
from playhouse.shortcuts import *
import utils
#return json
def _get_setlist(uuid):
| 34 | 64 | 200 | 7 | 26 | Hiromi-nee/ds_setlist | setlists.py | Python | _get_setlist | _get_setlist | 9 | 20 | 9 | 9 | 522d529535175a87d9d775cf116e319ce52b45ed | bigcode/the-stack | train |
157c8910433fb68133369728 | train | function | def test_reqs(requirements_files):
assert requirements_files.get("req1.txt")
| def test_reqs(requirements_files):
| assert requirements_files.get("req1.txt")
| def test_reqs(requirements_files):
| 8 | 64 | 18 | 8 | 0 | magnologan/pipup | tests/test_setup.py | Python | test_reqs | test_reqs | 1 | 2 | 1 | 1 | 20cca83de2a26d87e818aaae96afba0f31b00273 | bigcode/the-stack | train |
03517e99f7ee6b522b4d9987 | train | class | class Migration(migrations.Migration):
dependencies = [
('nobility', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='ticket',
old_name='assetTag',
new_name='asset',
),
]
| class Migration(migrations.Migration):
| dependencies = [
('nobility', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='ticket',
old_name='assetTag',
new_name='asset',
),
]
| # Generated by Django 4.0.1 on 2022-02-08 21:29
from django.db import migrations
class Migration(migrations.Migration):
| 36 | 64 | 57 | 7 | 28 | snowskeleton/djangoIdun | nobility/migrations/0002_rename_assettag_ticket_asset.py | Python | Migration | Migration | 6 | 18 | 6 | 7 | e874b296cfe1aabcfcbeb9e5f4c7afa6e5635897 | bigcode/the-stack | train |
35fd74bf46f15d5356bbe165 | train | function | @app.task
def send_mail_to_subs(new_book_id):
book = Book.objects.get(id=new_book_id)
subject = 'Oповещение'
msg = (
'{sub}, Добрый день!\n'
'На нашем портале доступна новая книга {book.name} от автора {book.author}!\n\n'
)
from_email=settings.DEFAULT_FROM_EMAIL,
messages = [
... | @app.task
def send_mail_to_subs(new_book_id):
| book = Book.objects.get(id=new_book_id)
subject = 'Oповещение'
msg = (
'{sub}, Добрый день!\n'
'На нашем портале доступна новая книга {book.name} от автора {book.author}!\n\n'
)
from_email=settings.DEFAULT_FROM_EMAIL,
messages = [
(subject, msg.format(sub=sub, book=book),... | # Create your tasks here
from library.celery import app
from django.core.mail import send_mass_mail
from django.conf import settings
from api.models import Subscriber, Book
@app.task
def send_mail_to_subs(new_book_id):
| 50 | 64 | 124 | 13 | 36 | e-trp/library | api/tasks.py | Python | send_mail_to_subs | send_mail_to_subs | 7 | 21 | 7 | 8 | 9a8862301c6f159c92793d3bc322585eced145de | bigcode/the-stack | train |
8513c209329515078c34f83b | train | function | def book_list(request):
books = Book.objects.all()
books_with_reviews = []
for book in books:
reviews = book.review_set.all()
if reviews:
book_rating = average_rating([review.rating for review in reviews])
number_of_reviews = len(reviews)
else:
boo... | def book_list(request):
| books = Book.objects.all()
books_with_reviews = []
for book in books:
reviews = book.review_set.all()
if reviews:
book_rating = average_rating([review.rating for review in reviews])
number_of_reviews = len(reviews)
else:
book_rating = None
... | .models import Book
from .utils import average_rating
def index(request):
return render(request, "base.html")
def book_search(request):
search_text = request.GET.get("search", "")
return render(request, "reviews/search-results.html", {"search_text": search_text})
def book_list(request):
| 64 | 64 | 130 | 5 | 59 | PacktPublishing/Web-Development-Projects-with-Django | Chapter05/final/bookr/reviews/views.py | Python | book_list | book_list | 16 | 32 | 16 | 16 | ce5ed24a797923e278c92756c5d1e64600651a27 | bigcode/the-stack | train |
be18c7a8359a205fba0ab3bb | train | function | def book_detail(request, pk):
book = get_object_or_404(Book, pk=pk)
reviews = book.review_set.all()
if reviews:
book_rating = average_rating([review.rating for review in reviews])
context = {
"book": book,
"book_rating": book_rating,
"reviews": reviews
... | def book_detail(request, pk):
| book = get_object_or_404(Book, pk=pk)
reviews = book.review_set.all()
if reviews:
book_rating = average_rating([review.rating for review in reviews])
context = {
"book": book,
"book_rating": book_rating,
"reviews": reviews
}
else:
conte... | 0
books_with_reviews.append({"book": book, "book_rating": book_rating, "number_of_reviews": number_of_reviews})
context = {
"book_list": books_with_reviews
}
return render(request, "reviews/book_list.html", context)
def book_detail(request, pk):
| 64 | 64 | 114 | 7 | 57 | PacktPublishing/Web-Development-Projects-with-Django | Chapter05/final/bookr/reviews/views.py | Python | book_detail | book_detail | 35 | 51 | 35 | 35 | a4bc1892b851bc2234687c7c638cb459f0290bd6 | bigcode/the-stack | train |
cf55e7e270939d5690df7fbb | train | function | def book_search(request):
search_text = request.GET.get("search", "")
return render(request, "reviews/search-results.html", {"search_text": search_text})
| def book_search(request):
| search_text = request.GET.get("search", "")
return render(request, "reviews/search-results.html", {"search_text": search_text})
| from django.shortcuts import render, get_object_or_404
from .models import Book
from .utils import average_rating
def index(request):
return render(request, "base.html")
def book_search(request):
| 43 | 64 | 34 | 5 | 38 | PacktPublishing/Web-Development-Projects-with-Django | Chapter05/final/bookr/reviews/views.py | Python | book_search | book_search | 11 | 13 | 11 | 11 | 159bdc49818a4fd2271751349bbbe54abad516ba | bigcode/the-stack | train |
ba07a266a20202d67d333c5f | train | function | def index(request):
return render(request, "base.html")
| def index(request):
| return render(request, "base.html")
| from django.shortcuts import render, get_object_or_404
from .models import Book
from .utils import average_rating
def index(request):
| 29 | 64 | 13 | 4 | 24 | PacktPublishing/Web-Development-Projects-with-Django | Chapter05/final/bookr/reviews/views.py | Python | index | index | 7 | 8 | 7 | 7 | bae3ce6491e1587011d01c8f3a37165994d9bc5a | bigcode/the-stack | train |
1a0a92d6df1d39a6b806929e | train | function | def _format_record(
record: 'loguru.Record',
log_format: str,
) -> str:
"""Format loguru log record according to specified format.
Uses pprint.pformat() to log any additional data passed in as extra
payload. Example:
>>> payload = [{"users":[{"name": "Nick", "age": 87}], "count": 1}]
>>> lo... | def _format_record(
record: 'loguru.Record',
log_format: str,
) -> str:
| """Format loguru log record according to specified format.
Uses pprint.pformat() to log any additional data passed in as extra
payload. Example:
>>> payload = [{"users":[{"name": "Nick", "age": 87}], "count": 1}]
>>> logger.bind(payload=payload).debug("users payload")
>>> [ { 'count': 1,
... | WPS609
frame = frame.f_back # type: ignore
depth += 1
logger.opt(
depth=depth,
exception=record.exc_info,
).log(
level,
record.getMessage(),
)
def _format_record(
record: 'loguru.Record',
log_format: str,
) -> str... | 75 | 75 | 253 | 23 | 52 | FraBle/minigugl | minigugl/log.py | Python | _format_record | _format_record | 62 | 91 | 62 | 65 | 4c7ac9d165e6b0330496f0eee1937957b70a72b1 | bigcode/the-stack | train |
c89afe961c2eaa4d1245a926 | train | function | def setup_logging(log_level: str, log_format: str = LOGURU_FORMAT) -> None:
"""Set up loguru to be the sole logging mechanism.
Register a custom InterceptHandler based on loguru as sole handler for the
root logger. Further, remove all registered logger handlers and set
corresponding loggers to propogat... | def setup_logging(log_level: str, log_format: str = LOGURU_FORMAT) -> None:
| """Set up loguru to be the sole logging mechanism.
Register a custom InterceptHandler based on loguru as sole handler for the
root logger. Further, remove all registered logger handlers and set
corresponding loggers to propogate up the the root logger now handled by
loguru. A custom dict can be pas... | payload'] = pformat(
record['extra']['payload'], indent=4, compact=True, width=100,
)
format_string = '{0}{1}'.format(
format_string,
'<level>{extra[payload]}</level>\n',
)
return format_string
def setup_logging(log_level: str, log_format: str = LOGURU_FOR... | 80 | 80 | 268 | 20 | 59 | FraBle/minigugl | minigugl/log.py | Python | setup_logging | setup_logging | 94 | 124 | 94 | 94 | 86872a9ae33d1742a1173f33b27619f1f5ce86ef | bigcode/the-stack | train |
bc2e4d2bf50f2af79a228d9b | train | class | class InterceptHandler(logging.Handler):
"""Custom handler to integrate with standard lib `logging`.
Based on example from loguru docs:
https://loguru.readthedocs.io/en/stable/overview.html
"""
loglevel_mapping = {
50: 'CRITICAL',
40: 'ERROR',
30: 'WARNING',
20: 'IN... | class InterceptHandler(logging.Handler):
| """Custom handler to integrate with standard lib `logging`.
Based on example from loguru docs:
https://loguru.readthedocs.io/en/stable/overview.html
"""
loglevel_mapping = {
50: 'CRITICAL',
40: 'ERROR',
30: 'WARNING',
20: 'INFO',
10: 'DEBUG',
0: 'NOT... | -version
"""
import logging
import sys
from pprint import pformat
# Type hints with loguru:
# https://loguru.readthedocs.io/en/stable/api/type_hints.html
import loguru
from loguru import logger # noqa: WPS458
from loguru._defaults import LOGURU_FORMAT # noqa: WPS436
class InterceptHandler(logging.Handler):
| 82 | 82 | 275 | 7 | 74 | FraBle/minigugl | minigugl/log.py | Python | InterceptHandler | InterceptHandler | 19 | 59 | 19 | 19 | 60dff25342c3348567cf238e04070c6d6c34cdd3 | bigcode/the-stack | train |
ca2143ebb3d8c30dc623ef24 | train | function | def simple_model():
model = Sequential()
model.add(Embedding(input_dim=MAXFEAT, output_dim=64))
model.add(LSTM(64, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(4, activation='softmax'))
model.summary()
model.compile(
loss='categorical_crossentropy',
optimizer='adam',
... | def simple_model():
| model = Sequential()
model.add(Embedding(input_dim=MAXFEAT, output_dim=64))
model.add(LSTM(64, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(4, activation='softmax'))
model.summary()
model.compile(
loss='categorical_crossentropy',
optimizer='adam',
metrics=[categor... | Flatten, Input, \
LSTM, CuDNNLSTM, Conv1D, MaxPooling1D, AveragePooling1D, concatenate
from keras.metrics import categorical_accuracy
from constants import MAXLEN, MAXFEAT, FULL_INPUTS
from utils import get_available_gpus
def simple_model():
| 64 | 64 | 93 | 4 | 59 | tristaaan/mtg-rarity-predict | rnn_model.py | Python | simple_model | simple_model | 14 | 25 | 14 | 14 | 38fb99a90491d7c3fa050d31395dbf0652499c4a | bigcode/the-stack | train |
d7c460d71f01b5310c99bfbf | train | function | def full_model(embedding_matrix=None, variant='lstm'):
# mana, type, description pipeline
shape = len(FULL_INPUTS)
mana_input = Input(shape=(shape,), name='costs')
x = Dense(64, activation='relu', name='costs_fc_1')(mana_input)
x = Dense(64, activation='relu', name='costs_fc_2')(x)
x = Dense(64,... | def full_model(embedding_matrix=None, variant='lstm'):
# mana, type, description pipeline
| shape = len(FULL_INPUTS)
mana_input = Input(shape=(shape,), name='costs')
x = Dense(64, activation='relu', name='costs_fc_1')(mana_input)
x = Dense(64, activation='relu', name='costs_fc_2')(x)
x = Dense(64, activation='relu', name='costs_fc_3')(x)
mana_pipeline = Dense(64, activation='relu', nam... | import Sequential, Model
from keras.layers import Dense, Dropout, Embedding, Flatten, Input, \
LSTM, CuDNNLSTM, Conv1D, MaxPooling1D, AveragePooling1D, concatenate
from keras.metrics import categorical_accuracy
from constants import MAXLEN, MAXFEAT, FULL_INPUTS
from utils import get_available_gpus
def simple_mod... | 192 | 192 | 643 | 22 | 169 | tristaaan/mtg-rarity-predict | rnn_model.py | Python | full_model | full_model | 27 | 87 | 27 | 28 | 3bd073c848a5d5c2046c37559c168d28e4a27260 | bigcode/the-stack | train |
5f193c674a3075e149a55308 | train | function | def main():
"""This task consists of one agent, model or MTurk worker, talking to an
MTurk worker to negotiate a deal.
"""
argparser = ParlaiParser(False, False)
argparser.add_parlai_data_path()
argparser.add_mturk_args()
argparser.add_argument('-min_t', '--min_turns', default=5, type=int,
... | def main():
| """This task consists of one agent, model or MTurk worker, talking to an
MTurk worker to negotiate a deal.
"""
argparser = ParlaiParser(False, False)
argparser.add_parlai_data_path()
argparser.add_mturk_args()
argparser.add_argument('-min_t', '--min_turns', default=5, type=int,
... | #!/usr/bin/env python3
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
fro... | 130 | 249 | 830 | 3 | 126 | markr-fu-berlin/ParlAI | projects/personachat/mturk/personachat_eval/run.py | Python | main | main | 17 | 117 | 17 | 17 | 18d30cef9c3c90bf7a7ca5a005c79767bce4ce49 | bigcode/the-stack | train |
690e9478d97976c2d4db958e | train | function | def fetch():
retval = {}
content = retrieve_content(__url__)
if __check__ in content:
for line in content.split('\n'):
line = line.strip()
if not line or line.startswith('#') or '.' not in line:
continue
retval[line.strip()] = (__info__, __referen... | def fetch():
| retval = {}
content = retrieve_content(__url__)
if __check__ in content:
for line in content.split('\n'):
line = line.strip()
if not line or line.startswith('#') or '.' not in line:
continue
retval[line.strip()] = (__info__, __reference__)
re... | altrail/)
See the file 'LICENSE' for copying permission
"""
from core.common import retrieve_content
__url__ = "http://www.urlvir.com/export-hosts/"
__check__ = "Updated on"
__info__ = "malware"
__reference__ = "urlvir.com"
def fetch():
| 64 | 64 | 72 | 3 | 61 | gallypette/maltrail | trails/feeds/urlvir.py | Python | fetch | fetch | 15 | 26 | 15 | 15 | 81d6df83fb967b9d710085eee47b90544ca2345d | bigcode/the-stack | train |
9da011bf58f84092b620c84c | train | class | @init_model_state_from_kwargs
class EnableHostInsightDetails(object):
"""
The information about the host to be analyzed.
"""
#: A constant which can be used with the entity_source property of a EnableHostInsightDetails.
#: This constant has a value of "MACS_MANAGED_EXTERNAL_HOST"
ENTITY_SOURCE_... | @init_model_state_from_kwargs
class EnableHostInsightDetails(object):
| """
The information about the host to be analyzed.
"""
#: A constant which can be used with the entity_source property of a EnableHostInsightDetails.
#: This constant has a value of "MACS_MANAGED_EXTERNAL_HOST"
ENTITY_SOURCE_MACS_MANAGED_EXTERNAL_HOST = "MACS_MANAGED_EXTERNAL_HOST"
def __i... | # coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | 147 | 188 | 628 | 14 | 132 | Manny27nyc/oci-python-sdk | src/oci/opsi/models/enable_host_insight_details.py | Python | EnableHostInsightDetails | EnableHostInsightDetails | 10 | 100 | 10 | 11 | 6849df46cdc2de0fc85129ec409b88cd836ef681 | bigcode/the-stack | train |
56e798376ddddd0c3204246e | train | class | class ApiConfigTest(TestCase):
def setUp(self):
if not os.path.exists(os.path.dirname(TEST_KEY_FILE)):
try:
os.makedirs(os.path.dirname(TEST_KEY_FILE))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
... | class ApiConfigTest(TestCase):
| def setUp(self):
if not os.path.exists(os.path.dirname(TEST_KEY_FILE)):
try:
os.makedirs(os.path.dirname(TEST_KEY_FILE))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
def tearDown(sel... | # flake8: noqa
import os
from unittest import TestCase, mock
from nasdaqdatalink.api_config import *
TEST_KEY_FILE = os.path.join(
os.path.dirname(os.path.realpath(__file__)), ".nasdaq-config", "testkeyfile"
)
TEST_DEFAULT_FILE = os.path.join(
os.path.dirname(os.path.realpath(__file__)), ".nasdaq-config", "defau... | 97 | 147 | 490 | 7 | 90 | edvn0/data-link-python | test/test_api_config.py | Python | ApiConfigTest | ApiConfigTest | 16 | 76 | 16 | 16 | c30d92b5d7484987a20e38fff1dcf8a0840823a0 | bigcode/the-stack | train |
934a8943aa94b0ecb240e461 | train | function | def location(preference):
"""
Flips a weighted coin to decide between two locations to meet
In this example, we assume that Alice and Bob share a prior preference
for one location over another, reflected in the value of preference below.
"""
return pyro.sample("loc", Bernoulli(preference))
| def location(preference):
| """
Flips a weighted coin to decide between two locations to meet
In this example, we assume that Alice and Bob share a prior preference
for one location over another, reflected in the value of preference below.
"""
return pyro.sample("loc", Bernoulli(preference))
| recursively reasoning about one another.
Taken from: http://forestdb.org/models/schelling.html
"""
import argparse
import torch
import pyro
import pyro.poutine as poutine
from pyro.distributions import Bernoulli
from search_inference import HashingMarginal, Search
def location(preference):
| 64 | 64 | 67 | 5 | 58 | patrickeganfoley/pyro | examples/rsa/schelling.py | Python | location | location | 22 | 28 | 22 | 22 | cc7a613e45d6a1f89b2a5c2fd4c3162d646f48fc | bigcode/the-stack | train |
df4b4dbac1531269dd7de8ad | train | function | def alice(preference, depth):
"""
Alice decides where to go by reasoning about Bob's choice
"""
alice_prior = location(preference)
with poutine.block():
bob_marginal = HashingMarginal(Search(bob).run(preference, depth - 1))
return pyro.sample("bob_choice", bob_marginal, obs=alice_prior)
| def alice(preference, depth):
| """
Alice decides where to go by reasoning about Bob's choice
"""
alice_prior = location(preference)
with poutine.block():
bob_marginal = HashingMarginal(Search(bob).run(preference, depth - 1))
return pyro.sample("bob_choice", bob_marginal, obs=alice_prior)
| a weighted coin to decide between two locations to meet
In this example, we assume that Alice and Bob share a prior preference
for one location over another, reflected in the value of preference below.
"""
return pyro.sample("loc", Bernoulli(preference))
def alice(preference, depth):
| 64 | 64 | 79 | 7 | 57 | patrickeganfoley/pyro | examples/rsa/schelling.py | Python | alice | alice | 31 | 38 | 31 | 31 | b537b3b625e75a23cb1f490d6439c946cd2dfc0d | bigcode/the-stack | train |
ee77901d02a3ff672a4c7c69 | train | function | def bob(preference, depth):
"""
Bob decides where to go by reasoning about Alice's choice
"""
bob_prior = location(preference)
if depth > 0:
with poutine.block():
alice_marginal = HashingMarginal(Search(alice).run(preference, depth))
return pyro.sample("alice_choice", ali... | def bob(preference, depth):
| """
Bob decides where to go by reasoning about Alice's choice
"""
bob_prior = location(preference)
if depth > 0:
with poutine.block():
alice_marginal = HashingMarginal(Search(alice).run(preference, depth))
return pyro.sample("alice_choice", alice_marginal, obs=bob_prior)
... | """
alice_prior = location(preference)
with poutine.block():
bob_marginal = HashingMarginal(Search(bob).run(preference, depth - 1))
return pyro.sample("bob_choice", bob_marginal, obs=alice_prior)
def bob(preference, depth):
| 64 | 64 | 91 | 7 | 57 | patrickeganfoley/pyro | examples/rsa/schelling.py | Python | bob | bob | 41 | 51 | 41 | 41 | 6e79dab9e075c6b5f09fa03ecddfbf1cce96454b | bigcode/the-stack | train |
56eb943bb334e4ba285bc207 | train | function | def main(args):
# Here Alice and Bob slightly prefer one location over the other a priori
shared_preference = torch.tensor([args.preference])
bob_depth = args.depth
num_samples = args.num_samples
# We sample Bob's choice of location by marginalizing
# over his decision process.
bob_decisio... | def main(args):
# Here Alice and Bob slightly prefer one location over the other a priori
| shared_preference = torch.tensor([args.preference])
bob_depth = args.depth
num_samples = args.num_samples
# We sample Bob's choice of location by marginalizing
# over his decision process.
bob_decision = HashingMarginal(Search(bob).run(shared_preference, bob_depth))
bob_prob = bob_decision... | _marginal = HashingMarginal(Search(alice).run(preference, depth))
return pyro.sample("alice_choice", alice_marginal, obs=bob_prior)
else:
return bob_prior
def main(args):
# Here Alice and Bob slightly prefer one location over the other a priori
| 64 | 64 | 207 | 20 | 43 | patrickeganfoley/pyro | examples/rsa/schelling.py | Python | main | main | 54 | 75 | 54 | 55 | e090bc1bf5d62caf4b4e0f0e0b265413f470382c | bigcode/the-stack | train |
11d2f3fbd94e52d3de7bea32 | train | class | @pytest.mark.supported(
only_if=lambda backend: backend.cipher_supported(
algorithms.ARC4(b"\x00" * 16), None
),
skip_message="Does not support ARC4",
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestARC4(object):
test_rfc = generate_stream_encryption_test(
lo... | @pytest.mark.supported(
only_if=lambda backend: backend.cipher_supported(
algorithms.ARC4(b"\x00" * 16), None
),
skip_message="Does not support ARC4",
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestARC4(object):
| test_rfc = generate_stream_encryption_test(
load_nist_vectors,
os.path.join("ciphers", "ARC4"),
[
"rfc-6229-40.txt",
"rfc-6229-56.txt",
"rfc-6229-64.txt",
"rfc-6229-80.txt",
"rfc-6229-128.txt",
"rfc-6229-192.txt",
... | ist_vectors
@pytest.mark.supported(
only_if=lambda backend: backend.cipher_supported(
algorithms.ARC4(b"\x00" * 16), None
),
skip_message="Does not support ARC4",
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestARC4(object):
| 64 | 64 | 198 | 61 | 2 | dvaerum/cryptography | tests/hazmat/primitives/test_arc4.py | Python | TestARC4 | TestARC4 | 19 | 41 | 19 | 26 | d456e50b8327bece92351d7a9cfeeb6bf4f3aa16 | bigcode/the-stack | train |
b96d74cd4821f817a202094a | train | class | class TestSwagger(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.client = server.test_client()
def test_get_spec(self):
""" The GET on /spec should return a 200 """
with warnings.catch_warnings():
warnings.filterwarnings("ignore", message="unclosed file")
... | class TestSwagger(unittest.TestCase):
@classmethod
| def setUpClass(cls):
cls.client = server.test_client()
def test_get_spec(self):
""" The GET on /spec should return a 200 """
with warnings.catch_warnings():
warnings.filterwarnings("ignore", message="unclosed file")
response = self.client.get('/application/spec'... | import unittest
import json
import warnings
from server import server
class TestSwagger(unittest.TestCase):
@classmethod
| 25 | 64 | 171 | 11 | 13 | dajuguan/arxanapi | test/test_swagger.py | Python | TestSwagger | TestSwagger | 8 | 30 | 8 | 9 | 00fe554302fd2e48d60f50743b4a8171298cc8e6 | bigcode/the-stack | train |
ffada08132da1296c4067da4 | train | function | def readme():
with open('README.rst') as f:
return f.read()
| def readme():
| with open('README.rst') as f:
return f.read()
| """
dumdum
-------------
Create fake HTTP servers with simple stanzas.
"""
from setuptools import setup
def readme():
| 26 | 64 | 20 | 4 | 21 | jar-o/dumdum | setup.py | Python | readme | readme | 9 | 11 | 9 | 9 | a4a5443306d457c32e065eac77bdff78c35db20d | bigcode/the-stack | train |
46041306b641c1bb4107ca97 | train | function | async def symbol_search(symbol: str, session: TastyAPISession):
"""
Performs a symbol search using Tastyworks API.
This returns a list of symbols that are similar to the symbol passed in
the parameters. This does not provide any details except the related
symbols and their descriptions.
Args:
... | async def symbol_search(symbol: str, session: TastyAPISession):
| """
Performs a symbol search using Tastyworks API.
This returns a list of symbols that are similar to the symbol passed in
the parameters. This does not provide any details except the related
symbols and their descriptions.
Args:
symbol (string): A base symbol to search for similar sym... | import aiohttp
from tastyworks.models.session import TastyAPISession
async def symbol_search(symbol: str, session: TastyAPISession):
| 32 | 64 | 200 | 16 | 15 | Graeme22/tastyworks-api | tastyworks/tastyworks_api/symbol_search.py | Python | symbol_search | symbol_search | 6 | 31 | 6 | 6 | 62ecf347ed5fa5cd28953d4f8099a2b290cf0cbb | bigcode/the-stack | train |
3a2fb3ecff6d432e18716d80 | train | class | class CheckLinuxDiskMountsReadOnly(NagiosPlugin):
def __init__(self):
# Python 2.x
super(CheckLinuxDiskMountsReadOnly, self).__init__()
# Python 3.x
# super().__init__()
self.include = None
self.exclude = None
self.msg = 'Mounts message not defined yet'
... | class CheckLinuxDiskMountsReadOnly(NagiosPlugin):
| def __init__(self):
# Python 2.x
super(CheckLinuxDiskMountsReadOnly, self).__init__()
# Python 3.x
# super().__init__()
self.include = None
self.exclude = None
self.msg = 'Mounts message not defined yet'
def add_options(self):
super(CheckLinuxDisk... | filesystem
from corruption
Reads /proc/mounts as this is much more reliable than the 'mount' command which doesn't get updated
in this scenario due to its use of /etc/mtab which merely contains the last mount options executed, not
the current state of mounts as updated by the Linux kernel
See also check_disk_write.p... | 256 | 256 | 896 | 13 | 243 | adolci/nagios-plugins | check_linux_disk_mounts_read_only.py | Python | CheckLinuxDiskMountsReadOnly | CheckLinuxDiskMountsReadOnly | 61 | 156 | 61 | 62 | dbe724cd1e96609318ac182cf5c5664fb2b3d516 | bigcode/the-stack | train |
23427c92db45a994d90ffadf | train | function | def joblib_cache(ds,
dirname,
version,
numpy_keys=None,
mmap_mode=None,
eager=True):
"""
chunks data together, converting values in `keys` into numpy arrays,
(for more efficient storage) then dechunks them afterwards
d... | def joblib_cache(ds,
dirname,
version,
numpy_keys=None,
mmap_mode=None,
eager=True):
| """
chunks data together, converting values in `keys` into numpy arrays,
(for more efficient storage) then dechunks them afterwards
dirname:
directory where to store the cache
keys:
which keys should be converted into numpy arrays
"""
if numpy_keys is None:
numpy_keys = []
... | be seen as a testing ground for future DatasetDSL operators
"""
import itertools
from .. import random_utils
from .. import parallel
from .. import utils
from . import dsl
def joblib_cache(ds,
dirname,
version,
numpy_keys=None,
mmap_mode=None,
... | 64 | 64 | 145 | 26 | 37 | diogo149/doo | du/dataset/patterns.py | Python | joblib_cache | joblib_cache | 17 | 45 | 17 | 22 | c3c8b81599b8c76b145e5822f918aaf724766d8c | bigcode/the-stack | train |
7954472be77009da9e1a74d2 | train | function | def subdataset_apply(ds, fn, key=None, out=None, args=None, kwargs=None):
"""
treats each element as its own dataset for the duration of the given
function
useful when you want to apply transformations that affect multiple
elements
"""
return ds.mapcat(
fn=utils.partial(_fn_to_subda... | def subdataset_apply(ds, fn, key=None, out=None, args=None, kwargs=None):
| """
treats each element as its own dataset for the duration of the given
function
useful when you want to apply transformations that affect multiple
elements
"""
return ds.mapcat(
fn=utils.partial(_fn_to_subdataset_apply_fn, fn, args, kwargs),
key=key,
out=out,
)... | (
[in_datamap]
).apply(
fn=fn,
args=args,
kwargs=kwargs,
)
with ds as g:
for data in g:
yield data
def subdataset_apply(ds, fn, key=None, out=None, args=None, kwargs=None):
| 64 | 64 | 94 | 20 | 43 | diogo149/doo | du/dataset/patterns.py | Python | subdataset_apply | subdataset_apply | 130 | 142 | 130 | 130 | 3b324229f505e77ff39c7595a803cbe22e3c48df | bigcode/the-stack | train |
bdeae59cb02c5ac42fcd7be8 | train | function | def parallel_copies(ds,
n_copies,
dirname=None,
try_shm=True,
mmap_mode=None):
"""
runs dataset on other process, reading it in to the main process on a
separate thread
if dirname is given, also serializes the dataset with ... | def parallel_copies(ds,
n_copies,
dirname=None,
try_shm=True,
mmap_mode=None):
| """
runs dataset on other process, reading it in to the main process on a
separate thread
if dirname is given, also serializes the dataset with joblib before
sending to other processes
"""
if n_copies == -1:
return ds
if dirname is not None:
ds = ds.to_joblib_serialized(... | ).cache(
dirname=dirname,
version=version,
backend="joblib",
eager=eager,
mmap_mode=mmap_mode
).dechunk(
)
def parallel_copies(ds,
n_copies,
dirname=None,
try_shm=True,
mmap_mode=None):
| 64 | 64 | 154 | 26 | 38 | diogo149/doo | du/dataset/patterns.py | Python | parallel_copies | parallel_copies | 48 | 72 | 48 | 52 | 7a22cf295fe136399a1a50f07d33f6c826fba021 | bigcode/the-stack | train |
fc4d08d976176a73d77c46eb | train | function | def papply(ds,
fn,
args=None,
kwargs=None,
n_jobs=1,
try_shm=True,
mmap_mode=None):
"""
applies the transformations of a function from DatasetDSL to DatasetDSL in
parallel
WARNING: will reorder the items
"""
random_key = random_u... | def papply(ds,
fn,
args=None,
kwargs=None,
n_jobs=1,
try_shm=True,
mmap_mode=None):
| """
applies the transformations of a function from DatasetDSL to DatasetDSL in
parallel
WARNING: will reorder the items
"""
random_key = random_utils.rand_alnum(15)
return ds.zip_assoc(
out=random_key,
iterator=itertools.count(),
).filter(
key=random_key,
... | ]
total_processes = parallel.multiprocessing_generator.PROCESS_NUMS[-1]
return (count % total_processes) == process_idx
def papply(ds,
fn,
args=None,
kwargs=None,
n_jobs=1,
try_shm=True,
mmap_mode=None):
| 64 | 64 | 183 | 33 | 30 | diogo149/doo | du/dataset/patterns.py | Python | papply | papply | 81 | 114 | 81 | 87 | ad597d3066f6a5bf08334ff180687b06628cbc62 | bigcode/the-stack | train |
1971588262b57668244cd16f | train | function | def _fn_to_subdataset_apply_fn(fn, args, kwargs, in_datamap):
ds = dsl.from_list(
[in_datamap]
).apply(
fn=fn,
args=args,
kwargs=kwargs,
)
with ds as g:
for data in g:
yield data
| def _fn_to_subdataset_apply_fn(fn, args, kwargs, in_datamap):
| ds = dsl.from_list(
[in_datamap]
).apply(
fn=fn,
args=args,
kwargs=kwargs,
)
with ds as g:
for data in g:
yield data
| =kwargs,
).apply(
fn=parallel_copies,
kwargs=dict(
n_copies=n_jobs,
try_shm=try_shm,
mmap_mode=mmap_mode,
)
)
def _fn_to_subdataset_apply_fn(fn, args, kwargs, in_datamap):
| 64 | 64 | 70 | 19 | 45 | diogo149/doo | du/dataset/patterns.py | Python | _fn_to_subdataset_apply_fn | _fn_to_subdataset_apply_fn | 117 | 127 | 117 | 117 | 8cdb7658800bbd9eae13e0aaf163d23ab7f151e9 | bigcode/the-stack | train |
2fd2e9ac0f35c97fa5db8fb3 | train | function | def _does_count_match_process_num(count):
process_idx = parallel.multiprocessing_generator.PROCESS_IDXS[-1]
total_processes = parallel.multiprocessing_generator.PROCESS_NUMS[-1]
return (count % total_processes) == process_idx
| def _does_count_match_process_num(count):
| process_idx = parallel.multiprocessing_generator.PROCESS_IDXS[-1]
total_processes = parallel.multiprocessing_generator.PROCESS_NUMS[-1]
return (count % total_processes) == process_idx
| lib_serialized(
directory=dirname,
mmap_mode=None,
)
return ds.to_other_process(
n_jobs=n_copies,
try_shm=try_shm,
mmap_mode=mmap_mode,
).to_threaded_reader(
)
def _does_count_match_process_num(count):
| 64 | 64 | 55 | 9 | 55 | diogo149/doo | du/dataset/patterns.py | Python | _does_count_match_process_num | _does_count_match_process_num | 75 | 78 | 75 | 75 | 23d12c3476caae8b5a03a2668bac441e6e4965a2 | bigcode/the-stack | train |
4adaa7aff15cec9f8db3edf6 | train | class | class UpdateHistoryItemAdmin(admin.ModelAdmin):
search_fields = ('update_history__name', 'update_history__machine__hostname')
list_display = ('update_history', 'recorded', 'status')
date_hierarchy = 'recorded'
| class UpdateHistoryItemAdmin(admin.ModelAdmin):
| search_fields = ('update_history__name', 'update_history__machine__hostname')
list_display = ('update_history', 'recorded', 'status')
date_hierarchy = 'recorded'
| [UpdateHistoryItemInline, ]
list_display = ('name', 'machine', 'update_type', 'version')
list_filter = ('update_type', BusinessUnitFilter, MachineGroupFilter)
search_fields = ('name', 'machine__hostname', 'version')
class UpdateHistoryItemAdmin(admin.ModelAdmin):
| 64 | 64 | 51 | 9 | 55 | lfaraone/sal | server/admin.py | Python | UpdateHistoryItemAdmin | UpdateHistoryItemAdmin | 223 | 226 | 223 | 223 | 5784d16aa8a2a8135adb2a7b964f0c4bc0298c47 | bigcode/the-stack | train |
eeeea34316f4709f57ff8f9f | train | class | class UserProfileInline(admin.StackedInline):
model = UserProfile
| class UserProfileInline(admin.StackedInline):
| model = UserProfile
| ularInline):
model = MachineGroup
class PluginScriptRowInline(admin.StackedInline):
model = PluginScriptRow
extra = 0
class UpdateHistoryItemInline(admin.TabularInline):
model = UpdateHistoryItem
extra = 0
class UserProfileInline(admin.StackedInline):
| 64 | 64 | 15 | 9 | 54 | lfaraone/sal | server/admin.py | Python | UserProfileInline | UserProfileInline | 50 | 51 | 50 | 50 | c8f4d27cbbba219203650f36e1702c7fdc134bdb | bigcode/the-stack | train |
a09e5fd7d12150a6c60a78e7 | train | class | class BusinessUnitForm(ModelForm):
class Meta:
model = BusinessUnit
fields = ['name', 'users']
users = ModelMultipleChoiceField(
queryset=User.objects.exclude(userprofile__level='GA'),
label=('Members'),
required=False,
widget=admin.widgets.FilteredSelectMultipl... | class BusinessUnitForm(ModelForm):
| class Meta:
model = BusinessUnit
fields = ['name', 'users']
users = ModelMultipleChoiceField(
queryset=User.objects.exclude(userprofile__level='GA'),
label=('Members'),
required=False,
widget=admin.widgets.FilteredSelectMultiple(verbose_name="Users", is_stacked=F... | Inline(admin.StackedInline):
model = PluginScriptRow
extra = 0
class UpdateHistoryItemInline(admin.TabularInline):
model = UpdateHistoryItem
extra = 0
class UserProfileInline(admin.StackedInline):
model = UserProfile
class BusinessUnitForm(ModelForm):
| 64 | 64 | 75 | 7 | 56 | lfaraone/sal | server/admin.py | Python | BusinessUnitForm | BusinessUnitForm | 54 | 64 | 54 | 55 | c585bcc5a2e5feb155fda4b8c989e7b10374eebb | bigcode/the-stack | train |
288d382599007d6655d3ec79 | train | class | class PluginScriptSubmissionAdmin(admin.ModelAdmin):
inlines = [PluginScriptRowInline, ]
list_display = ('plugin', 'machine', 'recorded', 'historical')
list_filter = (BusinessUnitFilter, MachineGroupFilter, 'plugin', 'historical', 'recorded')
search_fields = ('plugin', 'machine__hostname')
date_hier... | class PluginScriptSubmissionAdmin(admin.ModelAdmin):
| inlines = [PluginScriptRowInline, ]
list_display = ('plugin', 'machine', 'recorded', 'historical')
list_filter = (BusinessUnitFilter, MachineGroupFilter, 'plugin', 'historical', 'recorded')
search_fields = ('plugin', 'machine__hostname')
date_hierarchy = 'recorded'
| .
Views listing Plugins must first update the list of
installed plugins.
"""
reload_plugins_model()
return super(PluginAdmin, self).get_queryset(request)
class PluginScriptRowAdmin(admin.ModelAdmin):
search_fields = ('pluginscript_name',)
class PluginScriptSubmissionAdmin(... | 64 | 64 | 83 | 9 | 55 | lfaraone/sal | server/admin.py | Python | PluginScriptSubmissionAdmin | PluginScriptSubmissionAdmin | 187 | 192 | 187 | 187 | ee89c7e6f566da68dfff6a58bbd466ed2ffdc4ee | bigcode/the-stack | train |
a1a3cf79b5d678955c9d68f3 | train | class | class InstalledUpdateAdmin(admin.ModelAdmin):
list_display = ('update', 'display_name', 'machine', 'update_version', 'installed')
list_filter = (BusinessUnitFilter, MachineGroupFilter, 'update')
search_fields = ('machine__hostname', 'display_name', 'update')
| class InstalledUpdateAdmin(admin.ModelAdmin):
| list_display = ('update', 'display_name', 'machine', 'update_version', 'installed')
list_filter = (BusinessUnitFilter, MachineGroupFilter, 'update')
search_fields = ('machine__hostname', 'display_name', 'update')
| 'fact_data', 'machine', 'fact_recorded')
list_filter = (BusinessUnitFilter, MachineGroupFilter, 'fact_name')
search_fields = ('fact_name', 'fact_data', 'machine__hostname')
date_hierarchy = 'fact_recorded'
class InstalledUpdateAdmin(admin.ModelAdmin):
| 64 | 64 | 61 | 8 | 56 | lfaraone/sal | server/admin.py | Python | InstalledUpdateAdmin | InstalledUpdateAdmin | 117 | 120 | 117 | 117 | 4fc8e319b3cd46cdb06c4eefe961e9a97b7e2bc5 | bigcode/the-stack | train |
e26938be55032bfb1c984412 | train | class | class MachineGroupAdmin(admin.ModelAdmin):
list_display = ('name', 'business_unit', number_of_machines)
list_filter = (BusinessUnitFilter,)
fields = ('name', 'business_unit', number_of_machines, 'key')
readonly_fields = (number_of_machines, 'key')
| class MachineGroupAdmin(admin.ModelAdmin):
| list_display = ('name', 'business_unit', number_of_machines)
list_filter = (BusinessUnitFilter,)
fields = ('name', 'business_unit', number_of_machines, 'key')
readonly_fields = (number_of_machines, 'key')
| def get_queryset(self, request):
"""Update db prior to retrieving plugins.
Views listing MachineDetailPlugins must first update the list of
installed plugins.
"""
reload_plugins_model()
return super(MachineDetailPluginAdmin, self).get_queryset(request)
class MachineG... | 64 | 64 | 64 | 8 | 56 | lfaraone/sal | server/admin.py | Python | MachineGroupAdmin | MachineGroupAdmin | 157 | 161 | 157 | 157 | e6c229f3e99b5b667e0087952d9064b851dced68 | bigcode/the-stack | train |
38f169756cc8472dde926be5 | train | class | class MachineGroupInline(admin.TabularInline):
model = MachineGroup
| class MachineGroupInline(admin.TabularInline):
| model = MachineGroup
| , model_admin):
return ((mg.name, mg.name) for mg in MachineGroup.objects.all())
def queryset(self, request, queryset):
if self.value():
return queryset.filter(machine__machine_group__name=self.value())
else:
return queryset
class MachineGroupInline(admin.TabularInli... | 64 | 64 | 15 | 9 | 54 | lfaraone/sal | server/admin.py | Python | MachineGroupInline | MachineGroupInline | 36 | 37 | 36 | 36 | 989f8018cd4720a8901a2d2f31e6669ce270e8e7 | bigcode/the-stack | train |
73d7cc80eeb667ae49755c29 | train | class | class PendingUpdateAdmin(admin.ModelAdmin):
list_filter = (BusinessUnitFilter, MachineGroupFilter)
list_display = ('update', 'display_name', 'update_version', 'machine')
search_fields = ('update', 'display_name', 'machine__hostname')
| class PendingUpdateAdmin(admin.ModelAdmin):
| list_filter = (BusinessUnitFilter, MachineGroupFilter)
list_display = ('update', 'display_name', 'update_version', 'machine')
search_fields = ('update', 'display_name', 'machine__hostname')
| list_display = ('name', 'business_unit', number_of_machines)
list_filter = (BusinessUnitFilter,)
fields = ('name', 'business_unit', number_of_machines, 'key')
readonly_fields = (number_of_machines, 'key')
class PendingUpdateAdmin(admin.ModelAdmin):
| 64 | 64 | 55 | 8 | 56 | lfaraone/sal | server/admin.py | Python | PendingUpdateAdmin | PendingUpdateAdmin | 164 | 167 | 164 | 164 | b19631364faed092ce462ffc492b89eb416b4115 | bigcode/the-stack | train |
bf1f0c188217c37773978594 | train | class | class MachineGroupFilter(admin.SimpleListFilter):
title = 'Machine Group'
parameter_name = 'machine_group'
def lookups(self, request, model_admin):
return ((mg.name, mg.name) for mg in MachineGroup.objects.all())
def queryset(self, request, queryset):
if self.value():
retur... | class MachineGroupFilter(admin.SimpleListFilter):
| title = 'Machine Group'
parameter_name = 'machine_group'
def lookups(self, request, model_admin):
return ((mg.name, mg.name) for mg in MachineGroup.objects.all())
def queryset(self, request, queryset):
if self.value():
return queryset.filter(machine__machine_group__name=sel... | ):
return ((bu.name, bu.name) for bu in BusinessUnit.objects.all())
def queryset(self, request, queryset):
if self.value():
return queryset.filter(machine__machine_group__business_unit__name=self.value())
else:
return queryset
class MachineGroupFilter(admin.SimpleLis... | 64 | 64 | 86 | 9 | 54 | lfaraone/sal | server/admin.py | Python | MachineGroupFilter | MachineGroupFilter | 22 | 33 | 22 | 22 | 2ced70cd78996761bbbd659f2927a69a644aac19 | bigcode/the-stack | train |
ffb1b7735c411c7622870e0b | train | class | class ConditionAdmin(admin.ModelAdmin):
list_filter = (BusinessUnitFilter, MachineGroupFilter, 'condition_name')
list_display = ('condition_name', 'condition_data', 'machine')
search_fields = ('condition_name', 'condition_data', 'machine__hostname')
| class ConditionAdmin(admin.ModelAdmin):
| list_filter = (BusinessUnitFilter, MachineGroupFilter, 'condition_name')
list_display = ('condition_name', 'condition_data', 'machine')
search_fields = ('condition_name', 'condition_data', 'machine__hostname')
| number_of_users, number_of_machine_groups, number_of_machines)
fields = (('name', number_of_users, number_of_machine_groups, number_of_machines), 'users')
readonly_fields = (number_of_users, number_of_machine_groups, number_of_machines)
class ConditionAdmin(admin.ModelAdmin):
| 64 | 64 | 56 | 7 | 57 | lfaraone/sal | server/admin.py | Python | ConditionAdmin | ConditionAdmin | 98 | 101 | 98 | 98 | 89e095284cd5d7245436192fd0961fb186b5c92b | bigcode/the-stack | train |
2fdb18579a2dc69f6ff7f25b | train | class | class BusinessUnitFilter(admin.SimpleListFilter):
title = 'Business Unit'
parameter_name = 'business_unit'
def lookups(self, request, model_admin):
return ((bu.name, bu.name) for bu in BusinessUnit.objects.all())
def queryset(self, request, queryset):
if self.value():
retur... | class BusinessUnitFilter(admin.SimpleListFilter):
| title = 'Business Unit'
parameter_name = 'business_unit'
def lookups(self, request, model_admin):
return ((bu.name, bu.name) for bu in BusinessUnit.objects.all())
def queryset(self, request, queryset):
if self.value():
return queryset.filter(machine__machine_group__business... | from django.contrib import admin
from django.forms import ModelForm, ModelMultipleChoiceField
from server.models import *
from server.utils import reload_plugins_model
class BusinessUnitFilter(admin.SimpleListFilter):
| 40 | 64 | 89 | 9 | 30 | lfaraone/sal | server/admin.py | Python | BusinessUnitFilter | BusinessUnitFilter | 8 | 19 | 8 | 8 | 2475821bf8f3c1bff7ede6a1a2e7ed41ebc34162 | bigcode/the-stack | train |
86ce5bf20ad85c7bc49de1cb | train | class | class PluginAdmin(admin.ModelAdmin):
list_display = ('name',)
def get_queryset(self, request):
"""Update db prior to retrieving plugins.
Views listing Plugins must first update the list of
installed plugins.
"""
reload_plugins_model()
return super(PluginAdmin, s... | class PluginAdmin(admin.ModelAdmin):
| list_display = ('name',)
def get_queryset(self, request):
"""Update db prior to retrieving plugins.
Views listing Plugins must first update the list of
installed plugins.
"""
reload_plugins_model()
return super(PluginAdmin, self).get_queryset(request)
| key')
class PendingUpdateAdmin(admin.ModelAdmin):
list_filter = (BusinessUnitFilter, MachineGroupFilter)
list_display = ('update', 'display_name', 'update_version', 'machine')
search_fields = ('update', 'display_name', 'machine__hostname')
class PluginAdmin(admin.ModelAdmin):
| 64 | 64 | 67 | 7 | 57 | lfaraone/sal | server/admin.py | Python | PluginAdmin | PluginAdmin | 170 | 180 | 170 | 170 | bc7fad87bd25f73da4c683075532b77617399706 | bigcode/the-stack | train |
d0acad05716257df99bcca40 | train | class | class ReportAdmin(admin.ModelAdmin):
list_display = ('name',)
def get_queryset(self, request):
"""Update db prior to retrieving plugins.
Views listing MachineDetailPlugins must first update the list of
installed plugins.
"""
reload_plugins_model()
return super(R... | class ReportAdmin(admin.ModelAdmin):
| list_display = ('name',)
def get_queryset(self, request):
"""Update db prior to retrieving plugins.
Views listing MachineDetailPlugins must first update the list of
installed plugins.
"""
reload_plugins_model()
return super(ReportAdmin, self).get_queryset(reques... | ', 'machine', 'recorded', 'historical')
list_filter = (BusinessUnitFilter, MachineGroupFilter, 'plugin', 'historical', 'recorded')
search_fields = ('plugin', 'machine__hostname')
date_hierarchy = 'recorded'
class ReportAdmin(admin.ModelAdmin):
| 64 | 64 | 69 | 7 | 57 | lfaraone/sal | server/admin.py | Python | ReportAdmin | ReportAdmin | 195 | 205 | 195 | 195 | 78a3f9d7e55aa066061441481bfe3170ac9ffefc | bigcode/the-stack | train |
5928e44246c2fb38e6872c2e | train | class | class ApiKeyAdmin(admin.ModelAdmin):
list_display = ('name', 'public_key', 'private_key')
| class ApiKeyAdmin(admin.ModelAdmin):
| list_display = ('name', 'public_key', 'private_key')
| achines(obj):
if isinstance(obj, MachineGroup):
return Machine.objects.filter(machine_group=obj).count()
else:
return Machine.objects.filter(machine_group__in=obj.machinegroup_set.all()).count()
def business_unit(obj):
return obj.machine_group.business_unit.name
class ApiKeyAdmin(admin.Mod... | 64 | 64 | 23 | 8 | 55 | lfaraone/sal | server/admin.py | Python | ApiKeyAdmin | ApiKeyAdmin | 86 | 87 | 86 | 86 | b4859edf48f723373f3b815356cc032eedbc9c89 | bigcode/the-stack | train |
5ec56fc02ac73c466487ac6d | train | function | def business_unit(obj):
return obj.machine_group.business_unit.name
| def business_unit(obj):
| return obj.machine_group.business_unit.name
| _of_machine_groups(obj):
return obj.machinegroup_set.count()
def number_of_machines(obj):
if isinstance(obj, MachineGroup):
return Machine.objects.filter(machine_group=obj).count()
else:
return Machine.objects.filter(machine_group__in=obj.machinegroup_set.all()).count()
def business_unit(o... | 64 | 64 | 14 | 5 | 59 | lfaraone/sal | server/admin.py | Python | business_unit | business_unit | 82 | 83 | 82 | 82 | dd8b8c04dd3e4d304af7ea00b0ed7efa203a455e | bigcode/the-stack | train |
badb8d0677a484adb8248f6b | train | function | def number_of_machine_groups(obj):
return obj.machinegroup_set.count()
| def number_of_machine_groups(obj):
| return obj.machinegroup_set.count()
| MultipleChoiceField(
queryset=User.objects.exclude(userprofile__level='GA'),
label=('Members'),
required=False,
widget=admin.widgets.FilteredSelectMultiple(verbose_name="Users", is_stacked=False))
def number_of_users(obj):
return obj.users.count()
def number_of_machine_groups(obj):... | 64 | 64 | 15 | 7 | 57 | lfaraone/sal | server/admin.py | Python | number_of_machine_groups | number_of_machine_groups | 71 | 72 | 71 | 71 | c5f27059214490ac091d3d4ad74d836c234401f0 | bigcode/the-stack | train |
d203dccfe72b98ba71522c1a | train | class | class HistoricalFactAdmin(admin.ModelAdmin):
list_display = ('fact_name', 'fact_data', 'machine', 'fact_recorded')
list_filter = (BusinessUnitFilter, MachineGroupFilter, 'fact_name')
search_fields = ('fact_name', 'fact_data', 'machine__hostname')
date_hierarchy = 'fact_recorded'
| class HistoricalFactAdmin(admin.ModelAdmin):
| list_display = ('fact_name', 'fact_data', 'machine', 'fact_recorded')
list_filter = (BusinessUnitFilter, MachineGroupFilter, 'fact_name')
search_fields = ('fact_name', 'fact_data', 'machine__hostname')
date_hierarchy = 'fact_recorded'
| class FactAdmin(admin.ModelAdmin):
list_display = ('fact_name', 'fact_data', 'machine')
list_filter = (BusinessUnitFilter, MachineGroupFilter, 'fact_name')
search_fields = ('fact_name', 'fact_data', 'machine__hostname')
class HistoricalFactAdmin(admin.ModelAdmin):
| 64 | 64 | 72 | 8 | 56 | lfaraone/sal | server/admin.py | Python | HistoricalFactAdmin | HistoricalFactAdmin | 110 | 114 | 110 | 110 | bdb2634c31b8780e3bf904947b1540da1716a308 | bigcode/the-stack | train |
af2cfe0caca3f366b73bc64d | train | class | class PluginScriptRowInline(admin.StackedInline):
model = PluginScriptRow
extra = 0
| class PluginScriptRowInline(admin.StackedInline):
| model = PluginScriptRow
extra = 0
| MachineGroup.objects.all())
def queryset(self, request, queryset):
if self.value():
return queryset.filter(machine__machine_group__name=self.value())
else:
return queryset
class MachineGroupInline(admin.TabularInline):
model = MachineGroup
class PluginScriptRowInline(... | 64 | 64 | 23 | 10 | 53 | lfaraone/sal | server/admin.py | Python | PluginScriptRowInline | PluginScriptRowInline | 40 | 42 | 40 | 40 | b668ef805d4c8b038ab9d91bc59631bcec13910c | bigcode/the-stack | train |
aeb2a852bbf42bf30118533a | train | function | def number_of_users(obj):
return obj.users.count()
| def number_of_users(obj):
| return obj.users.count()
| fields = ['name', 'users']
users = ModelMultipleChoiceField(
queryset=User.objects.exclude(userprofile__level='GA'),
label=('Members'),
required=False,
widget=admin.widgets.FilteredSelectMultiple(verbose_name="Users", is_stacked=False))
def number_of_users(obj):
| 64 | 64 | 12 | 6 | 58 | lfaraone/sal | server/admin.py | Python | number_of_users | number_of_users | 67 | 68 | 67 | 67 | 872c2096fae1868663d2af5ae2ba1d56a40957e4 | bigcode/the-stack | train |
17c43ef80e0e7fbdb3eecb47 | train | class | class PluginScriptRowAdmin(admin.ModelAdmin):
search_fields = ('pluginscript_name',)
| class PluginScriptRowAdmin(admin.ModelAdmin):
| search_fields = ('pluginscript_name',)
| name',)
def get_queryset(self, request):
"""Update db prior to retrieving plugins.
Views listing Plugins must first update the list of
installed plugins.
"""
reload_plugins_model()
return super(PluginAdmin, self).get_queryset(request)
class PluginScriptRowAdmin(admi... | 64 | 64 | 19 | 9 | 55 | lfaraone/sal | server/admin.py | Python | PluginScriptRowAdmin | PluginScriptRowAdmin | 183 | 184 | 183 | 183 | c362648ff8ef907d9a6d0be93cdf8e727c647017 | bigcode/the-stack | train |
a2783d2522f7445d13f2c28b | train | class | class MachineDetailPluginAdmin(admin.ModelAdmin):
list_display = ('name',)
def get_queryset(self, request):
"""Update db prior to retrieving plugins.
Views listing MachineDetailPlugins must first update the list of
installed plugins.
"""
reload_plugins_model()
r... | class MachineDetailPluginAdmin(admin.ModelAdmin):
| list_display = ('name',)
def get_queryset(self, request):
"""Update db prior to retrieving plugins.
Views listing MachineDetailPlugins must first update the list of
installed plugins.
"""
reload_plugins_model()
return super(MachineDetailPluginAdmin, self).get_qu... | sal_version', 'deployed', 'broken_client', 'activity'),
'report'
)
readonly_fields = (business_unit, 'first_checkin', 'last_checkin', 'last_puppet_run')
search_fields = ('hostname', 'console_user')
class MachineDetailPluginAdmin(admin.ModelAdmin):
| 64 | 64 | 73 | 9 | 55 | lfaraone/sal | server/admin.py | Python | MachineDetailPluginAdmin | MachineDetailPluginAdmin | 144 | 154 | 144 | 144 | b4e026be272d1a934a2791343fc410208c2460e4 | bigcode/the-stack | train |
14ffa1f5d22984171ca18e64 | train | class | class UpdateHistoryAdmin(admin.ModelAdmin):
inlines = [UpdateHistoryItemInline, ]
list_display = ('name', 'machine', 'update_type', 'version')
list_filter = ('update_type', BusinessUnitFilter, MachineGroupFilter)
search_fields = ('name', 'machine__hostname', 'version')
| class UpdateHistoryAdmin(admin.ModelAdmin):
| inlines = [UpdateHistoryItemInline, ]
list_display = ('name', 'machine', 'update_type', 'version')
list_filter = ('update_type', BusinessUnitFilter, MachineGroupFilter)
search_fields = ('name', 'machine__hostname', 'version')
| reload_plugins_model()
return super(ReportAdmin, self).get_queryset(request)
class SalSettingAdmin(admin.ModelAdmin):
list_display = ('name', 'value')
class FriendlyNameCacheAdmin(admin.ModelAdmin):
list_display = ('serial_stub', 'friendly_name')
class UpdateHistoryAdmin(admin.ModelAdmin):
| 64 | 64 | 67 | 8 | 56 | lfaraone/sal | server/admin.py | Python | UpdateHistoryAdmin | UpdateHistoryAdmin | 216 | 220 | 216 | 216 | 5b03c2d86545ce76c24f0b0b31eaf894356ee903 | bigcode/the-stack | train |
133003c1dccf3d9b031c0b6d | train | class | class SalSettingAdmin(admin.ModelAdmin):
list_display = ('name', 'value')
| class SalSettingAdmin(admin.ModelAdmin):
| list_display = ('name', 'value')
| ',)
def get_queryset(self, request):
"""Update db prior to retrieving plugins.
Views listing MachineDetailPlugins must first update the list of
installed plugins.
"""
reload_plugins_model()
return super(ReportAdmin, self).get_queryset(request)
class SalSettingAdmin(... | 64 | 64 | 18 | 8 | 56 | lfaraone/sal | server/admin.py | Python | SalSettingAdmin | SalSettingAdmin | 208 | 209 | 208 | 208 | 43eafd92c209f97c1a4b8ca82f354768ad2ff6d9 | bigcode/the-stack | train |
b4084d0c9e326285b0e7b067 | train | class | class FactAdmin(admin.ModelAdmin):
list_display = ('fact_name', 'fact_data', 'machine')
list_filter = (BusinessUnitFilter, MachineGroupFilter, 'fact_name')
search_fields = ('fact_name', 'fact_data', 'machine__hostname')
| class FactAdmin(admin.ModelAdmin):
| list_display = ('fact_name', 'fact_data', 'machine')
list_filter = (BusinessUnitFilter, MachineGroupFilter, 'fact_name')
search_fields = ('fact_name', 'fact_data', 'machine__hostname')
| )
class ConditionAdmin(admin.ModelAdmin):
list_filter = (BusinessUnitFilter, MachineGroupFilter, 'condition_name')
list_display = ('condition_name', 'condition_data', 'machine')
search_fields = ('condition_name', 'condition_data', 'machine__hostname')
class FactAdmin(admin.ModelAdmin):
| 64 | 64 | 56 | 7 | 57 | lfaraone/sal | server/admin.py | Python | FactAdmin | FactAdmin | 104 | 107 | 104 | 104 | 26d803c41263dd6ae41021bfbb191a38512ee504 | bigcode/the-stack | train |
afc18ea9f1ca7a217c81340a | train | class | class UpdateHistoryItemInline(admin.TabularInline):
model = UpdateHistoryItem
extra = 0
| class UpdateHistoryItemInline(admin.TabularInline):
| model = UpdateHistoryItem
extra = 0
| (machine__machine_group__name=self.value())
else:
return queryset
class MachineGroupInline(admin.TabularInline):
model = MachineGroup
class PluginScriptRowInline(admin.StackedInline):
model = PluginScriptRow
extra = 0
class UpdateHistoryItemInline(admin.TabularInline):
| 64 | 64 | 23 | 10 | 53 | lfaraone/sal | server/admin.py | Python | UpdateHistoryItemInline | UpdateHistoryItemInline | 45 | 47 | 45 | 45 | 716f669538f7d55a74b22bd6c746258373c64716 | bigcode/the-stack | train |
c8daf278136caede5b583e1a | train | class | class MachineAdmin(admin.ModelAdmin):
list_display = ('hostname', 'serial', 'machine_model', 'operating_system', 'deployed')
list_filter = (BusinessUnitFilter, MachineGroupFilter, 'operating_system', 'os_family',
'machine_model', 'last_checkin', 'errors', 'warnings', 'puppet_errors',
... | class MachineAdmin(admin.ModelAdmin):
| list_display = ('hostname', 'serial', 'machine_model', 'operating_system', 'deployed')
list_filter = (BusinessUnitFilter, MachineGroupFilter, 'operating_system', 'os_family',
'machine_model', 'last_checkin', 'errors', 'warnings', 'puppet_errors',
'deployed')
fields = (
... | ierarchy = 'fact_recorded'
class InstalledUpdateAdmin(admin.ModelAdmin):
list_display = ('update', 'display_name', 'machine', 'update_version', 'installed')
list_filter = (BusinessUnitFilter, MachineGroupFilter, 'update')
search_fields = ('machine__hostname', 'display_name', 'update')
class MachineAdmin(a... | 75 | 75 | 252 | 7 | 68 | lfaraone/sal | server/admin.py | Python | MachineAdmin | MachineAdmin | 123 | 141 | 123 | 123 | 478e449f63ed1c7a55845d90f95a5b4f86b9535e | bigcode/the-stack | train |
8fd44ea9c7307f9ef0719f22 | train | class | class FriendlyNameCacheAdmin(admin.ModelAdmin):
list_display = ('serial_stub', 'friendly_name')
| class FriendlyNameCacheAdmin(admin.ModelAdmin):
| list_display = ('serial_stub', 'friendly_name')
| Views listing MachineDetailPlugins must first update the list of
installed plugins.
"""
reload_plugins_model()
return super(ReportAdmin, self).get_queryset(request)
class SalSettingAdmin(admin.ModelAdmin):
list_display = ('name', 'value')
class FriendlyNameCacheAdmin(admin.... | 64 | 64 | 21 | 9 | 55 | lfaraone/sal | server/admin.py | Python | FriendlyNameCacheAdmin | FriendlyNameCacheAdmin | 212 | 213 | 212 | 212 | fff1db323acde5ea8eacc906f72beac8a585db4f | bigcode/the-stack | train |
4ada32685352f96a8923b042 | train | function | def number_of_machines(obj):
if isinstance(obj, MachineGroup):
return Machine.objects.filter(machine_group=obj).count()
else:
return Machine.objects.filter(machine_group__in=obj.machinegroup_set.all()).count()
| def number_of_machines(obj):
| if isinstance(obj, MachineGroup):
return Machine.objects.filter(machine_group=obj).count()
else:
return Machine.objects.filter(machine_group__in=obj.machinegroup_set.all()).count()
| GA'),
label=('Members'),
required=False,
widget=admin.widgets.FilteredSelectMultiple(verbose_name="Users", is_stacked=False))
def number_of_users(obj):
return obj.users.count()
def number_of_machine_groups(obj):
return obj.machinegroup_set.count()
def number_of_machines(obj):
| 64 | 64 | 46 | 7 | 57 | lfaraone/sal | server/admin.py | Python | number_of_machines | number_of_machines | 75 | 79 | 75 | 75 | 3aa4f09b7379a1f1879450387410aea3c90993a1 | bigcode/the-stack | train |
eab81d4a01501cdf51b968a0 | train | class | class BusinessUnitAdmin(admin.ModelAdmin):
inlines = [MachineGroupInline, ]
form = BusinessUnitForm
list_display = ('name', number_of_users, number_of_machine_groups, number_of_machines)
fields = (('name', number_of_users, number_of_machine_groups, number_of_machines), 'users')
readonly_fields = (nu... | class BusinessUnitAdmin(admin.ModelAdmin):
| inlines = [MachineGroupInline, ]
form = BusinessUnitForm
list_display = ('name', number_of_users, number_of_machine_groups, number_of_machines)
fields = (('name', number_of_users, number_of_machine_groups, number_of_machines), 'users')
readonly_fields = (number_of_users, number_of_machine_groups, nu... | else:
return Machine.objects.filter(machine_group__in=obj.machinegroup_set.all()).count()
def business_unit(obj):
return obj.machine_group.business_unit.name
class ApiKeyAdmin(admin.ModelAdmin):
list_display = ('name', 'public_key', 'private_key')
class BusinessUnitAdmin(admin.ModelAdmin):
| 64 | 64 | 89 | 8 | 56 | lfaraone/sal | server/admin.py | Python | BusinessUnitAdmin | BusinessUnitAdmin | 90 | 95 | 90 | 90 | 3a731fa962fb65b09dec655458ffb48c171b3554 | bigcode/the-stack | train |
0dcfa7f8ead3405ad789fdf4 | train | class | class CustomUserAdmin(admin.ModelAdmin):
inlines = (UserProfileInline,)
list_display = ('username', 'profile_level', 'last_login')
list_filter = ('userprofile__level',)
search_fields = ('username', )
fields = (
('username', 'first_name', 'last_name', 'email'),
('is_staff', 'is_active... | class CustomUserAdmin(admin.ModelAdmin):
| inlines = (UserProfileInline,)
list_display = ('username', 'profile_level', 'last_login')
list_filter = ('userprofile__level',)
search_fields = ('username', )
fields = (
('username', 'first_name', 'last_name', 'email'),
('is_staff', 'is_active', 'is_superuser'),
('last_login'... | hostname', 'version')
class UpdateHistoryItemAdmin(admin.ModelAdmin):
search_fields = ('update_history__name', 'update_history__machine__hostname')
list_display = ('update_history', 'recorded', 'status')
date_hierarchy = 'recorded'
class CustomUserAdmin(admin.ModelAdmin):
| 64 | 64 | 111 | 8 | 56 | lfaraone/sal | server/admin.py | Python | CustomUserAdmin | CustomUserAdmin | 229 | 241 | 229 | 229 | 6e1ee0f0a183cb48ee2e4b8f9101247c994bc37b | bigcode/the-stack | train |
7052e556fe2dc784741ec12c | train | class | class _FakeModel(object):
"""
An object of this class can pass itself off as a model instance
when used as an arguments to Field.pre_save method (item_fields
of iterable fields are not actually fields of any model).
"""
def __init__(self, field, value):
setattr(self, field.attname, valu... | class _FakeModel(object):
| """
An object of this class can pass itself off as a model instance
when used as an arguments to Field.pre_save method (item_fields
of iterable fields are not actually fields of any model).
"""
def __init__(self, field, value):
setattr(self, field.attname, value)
| import copy
from django import forms
from django.db import models
from django.core.exceptions import ValidationError, ImproperlyConfigured
from django.db.models.fields.subclassing import Creator
from djangae.forms.fields import ListFormField
from django.utils.text import capfirst
class _FakeModel(object):
| 63 | 64 | 73 | 6 | 56 | oleksa-pavlenko/gae-django-project-template | djangae/fields/iterable.py | Python | _FakeModel | _FakeModel | 10 | 18 | 10 | 10 | 0a115de666df1179f8650855c6e2b7c6e68a5ce0 | bigcode/the-stack | train |
63507d69052719ae3c8d6428 | train | class | class IterableField(models.Field):
__metaclass__ = models.SubfieldBase
@property
def _iterable_type(self): raise NotImplementedError()
def db_type(self, connection):
return 'list'
def get_prep_lookup(self, lookup_type, value):
if hasattr(value, 'prepare'):
return value... | class IterableField(models.Field):
| __metaclass__ = models.SubfieldBase
@property
def _iterable_type(self): raise NotImplementedError()
def db_type(self, connection):
return 'list'
def get_prep_lookup(self, lookup_type, value):
if hasattr(value, 'prepare'):
return value.prepare()
if hasattr(value... | import copy
from django import forms
from django.db import models
from django.core.exceptions import ValidationError, ImproperlyConfigured
from django.db.models.fields.subclassing import Creator
from djangae.forms.fields import ListFormField
from django.utils.text import capfirst
class _FakeModel(object):
"""
... | 136 | 256 | 1,700 | 6 | 130 | oleksa-pavlenko/gae-django-project-template | djangae/fields/iterable.py | Python | IterableField | IterableField | 21 | 213 | 21 | 21 | c2fa69aca1f99a5d9615d41ab8a3a3c4e26119d2 | bigcode/the-stack | train |
92ff4c0ed5351256014c00ed | train | class | class ListField(IterableField):
def __init__(self, *args, **kwargs):
self.ordering = kwargs.pop('ordering', None)
if self.ordering is not None and not callable(self.ordering):
raise TypeError("'ordering' has to be a callable or None, "
"not of type %r." % type... | class ListField(IterableField):
| def __init__(self, *args, **kwargs):
self.ordering = kwargs.pop('ordering', None)
if self.ordering is not None and not callable(self.ordering):
raise TypeError("'ordering' has to be a callable or None, "
"not of type %r." % type(self.ordering))
super(L... | _field_class = forms.MultipleChoiceField
defaults['choices'] = self.get_choices(include_blank=False) #no empty value on a multi-select
else:
form_field_class = ListFormField
defaults.update(**kwargs)
return form_field_class(**defaults)
class ListField(IterableField):
| 64 | 64 | 198 | 7 | 57 | oleksa-pavlenko/gae-django-project-template | djangae/fields/iterable.py | Python | ListField | ListField | 216 | 239 | 216 | 216 | 07eab20d380a4a6f81dc49f9bcf69807fb900600 | bigcode/the-stack | train |
c2fc8473391ea2a1c858d9f3 | train | class | class SetField(IterableField):
@property
def _iterable_type(self):
return set
def db_type(self, connection):
return 'set'
def get_db_prep_save(self, *args, **kwargs):
ret = super(SetField, self).get_db_prep_save(*args, **kwargs)
if ret:
ret = list(ret)
... | class SetField(IterableField):
@property
| def _iterable_type(self):
return set
def db_type(self, connection):
return 'set'
def get_db_prep_save(self, *args, **kwargs):
ret = super(SetField, self).get_db_prep_save(*args, **kwargs)
if ret:
ret = list(ret)
return ret
def get_db_prep_lookup(sel... | iterable_type(self):
return list
def deconstruct(self):
name, path, args, kwargs = super(ListField, self).deconstruct()
kwargs['ordering'] = self.ordering
return name, path, args, kwargs
class SetField(IterableField):
@property
| 64 | 64 | 176 | 11 | 52 | oleksa-pavlenko/gae-django-project-template | djangae/fields/iterable.py | Python | SetField | SetField | 241 | 266 | 241 | 242 | 5ebf0ea2ec5c1a1964e1648d74e9040750880c1b | bigcode/the-stack | train |
06018cc054d9fb7a1bf59547 | train | function | def get_window_mgr_on_windows():
if HAS_WIN32GUI:
return WindowMgrWindowsWin32Gui
elif HAS_AHK:
return WindowMgrWindowsAHK
else:
log.error("No Window Manager found for Windows")
| def get_window_mgr_on_windows():
| if HAS_WIN32GUI:
return WindowMgrWindowsWin32Gui
elif HAS_AHK:
return WindowMgrWindowsAHK
else:
log.error("No Window Manager found for Windows")
| import logging
from .win32gui_manager import WindowMgrWindowsWin32Gui, HAS_WIN32GUI
from .ahk_manager import WindowMgrWindowsAHK, HAS_AHK
log = logging.getLogger(__name__)
def get_window_mgr_on_windows():
| 53 | 64 | 51 | 7 | 46 | Efemache/Mercenaries-Hearthstone-game-bot | modules/platform/window_managers/windows/factory.py | Python | get_window_mgr_on_windows | get_window_mgr_on_windows | 9 | 15 | 9 | 9 | 232c3744b6628a234aafe92ac187fddf7164e8b7 | bigcode/the-stack | train |
d5f833f31a9efba466f8a188 | train | class | class BokehBlueprint(flask.Blueprint):
def __init__(self, *args, **kwargs):
super(BokehBlueprint, self).__init__(*args, **kwargs)
self.debugjs = None
def setup(self, backend, backbone_storage, servermodel_storage,
authentication):
self.backend = backend
self.backb... | class BokehBlueprint(flask.Blueprint):
| def __init__(self, *args, **kwargs):
super(BokehBlueprint, self).__init__(*args, **kwargs)
self.debugjs = None
def setup(self, backend, backbone_storage, servermodel_storage,
authentication):
self.backend = backend
self.backbone_storage = backbone_storage
s... | by the Bokeh Development Team.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-----------------------------------------------------------------------------
from __future__ import absolute_import
from os import walk
from os.path import join
from bokeh.settings import settings
import... | 64 | 64 | 208 | 9 | 54 | rothnic/bokeh | bokeh/server/app.py | Python | BokehBlueprint | BokehBlueprint | 16 | 41 | 16 | 17 | 86c3c948757984eb4f64faa551dfed1c37c31d86 | bigcode/the-stack | train |
ef1ed8953cdfa57573f97bc9 | train | function | def _assets_response_handle(assets_json, ticker=None):
# if no ticker is given, return a dict of asset objects
if ticker is None:
assets_dict = {Asset(asset_obj).ticker: Asset(asset_obj)
for asset_obj in assets_json}
# if ticker sumbol is given
elif ticker is not None:
... | def _assets_response_handle(assets_json, ticker=None):
# if no ticker is given, return a dict of asset objects
| if ticker is None:
assets_dict = {Asset(asset_obj).ticker: Asset(asset_obj)
for asset_obj in assets_json}
# if ticker sumbol is given
elif ticker is not None:
assets_dict = Asset(assets_json[0])
return assets_dict
| ticker': ticker}
response = ses.get(base_url + "/assets", params=payload)
_validate_response(response)
assets_json = response.json()
return assets_json
def _assets_response_handle(assets_json, ticker=None):
# if no ticker is given, return a dict of asset objects
| 64 | 64 | 89 | 27 | 36 | SamSamhuns/RIT-trading-python | ritpytrading/assets.py | Python | _assets_response_handle | _assets_response_handle | 89 | 98 | 89 | 90 | fce967eede8cc9d5d26ca4471a04fd2f395ac054 | bigcode/the-stack | train |
dbeb8ee3dff0b24a163f2372 | train | function | def assets_dict(ses):
""" function that returns a dictionary of the assets object """
return _assets_response_handle(_get_assets_json(ses))
| def assets_dict(ses):
| """ function that returns a dictionary of the assets object """
return _assets_response_handle(_get_assets_json(ses))
| _json[0])
return assets_dict
def asset(ses, ticker_sym):
""" function that returns a single asset object given for a given ticker
"""
return _assets_response_handle(_get_assets_json(
ses, ticker=ticker_sym), ticker=ticker_sym)
def assets_dict(ses):
| 64 | 64 | 31 | 6 | 58 | SamSamhuns/RIT-trading-python | ritpytrading/assets.py | Python | assets_dict | assets_dict | 108 | 110 | 108 | 108 | 0f5dd1ccf9ff3c3f7147234c4123aa83c8181d8e | bigcode/the-stack | train |
fa3c813d473ed7a0896b32b3 | train | class | class Asset():
""" case_response is a json obj returned from the API get request """
def __init__(self, asset_response):
self.ticker = asset_response["ticker"]
self.type = asset_response["type"]
self.description = asset_response["description"]
self.total_quantity = asset_respons... | class Asset():
| """ case_response is a json obj returned from the API get request """
def __init__(self, asset_response):
self.ticker = asset_response["ticker"]
self.type = asset_response["type"]
self.description = asset_response["description"]
self.total_quantity = asset_response["total_quanti... | the news GET HTTP request
# - ticker string(query)
from ._response_validation import _validate_response
# Make sure the RIT client uses the same 9999 port
host_url = 'http://localhost:9999'
base_path = '/v1'
base_url = host_url + base_path
class Asset():
| 68 | 68 | 228 | 3 | 64 | SamSamhuns/RIT-trading-python | ritpytrading/assets.py | Python | Asset | Asset | 47 | 70 | 47 | 47 | fbcdc7edfabb2ab3f1fac10885c24e0429945b1b | bigcode/the-stack | train |
c7a862dd606f9a4cbee30d98 | train | function | def asset(ses, ticker_sym):
""" function that returns a single asset object given for a given ticker
"""
return _assets_response_handle(_get_assets_json(
ses, ticker=ticker_sym), ticker=ticker_sym)
| def asset(ses, ticker_sym):
| """ function that returns a single asset object given for a given ticker
"""
return _assets_response_handle(_get_assets_json(
ses, ticker=ticker_sym), ticker=ticker_sym)
| assets_dict = {Asset(asset_obj).ticker: Asset(asset_obj)
for asset_obj in assets_json}
# if ticker sumbol is given
elif ticker is not None:
assets_dict = Asset(assets_json[0])
return assets_dict
def asset(ses, ticker_sym):
| 64 | 64 | 49 | 8 | 55 | SamSamhuns/RIT-trading-python | ritpytrading/assets.py | Python | asset | asset | 101 | 105 | 101 | 101 | 428a4589119e4bdab1586fd3279b0f973cf75937 | bigcode/the-stack | train |
1c4485e73f9f7cdab337dd24 | train | function | def assets_list(ses):
""" returns a list of JSON formatted output for assets object """
return _get_assets_json(ses)
| def assets_list(ses):
| """ returns a list of JSON formatted output for assets object """
return _get_assets_json(ses)
|
"""
return _assets_response_handle(_get_assets_json(
ses, ticker=ticker_sym), ticker=ticker_sym)
def assets_dict(ses):
""" function that returns a dictionary of the assets object """
return _assets_response_handle(_get_assets_json(ses))
def assets_list(ses):
| 64 | 64 | 28 | 6 | 58 | SamSamhuns/RIT-trading-python | ritpytrading/assets.py | Python | assets_list | assets_list | 113 | 115 | 113 | 113 | ab2055681fe6ab50cd173012b888b389b7d2e81d | bigcode/the-stack | train |
d5fb0515fb44a2f75953f21b | train | function | def _get_assets_json(ses, ticker=None):
""" function requires a requests.Session() object
as the ses argument with a loaded API_KEY
ticker = ticker sumbol
returns a JSON obj with params given at the top
"""
payload = {}
if ticker is not None:
payload = {'ticker': ticker}
respons... | def _get_assets_json(ses, ticker=None):
| """ function requires a requests.Session() object
as the ses argument with a loaded API_KEY
ticker = ticker sumbol
returns a JSON obj with params given at the top
"""
payload = {}
if ticker is not None:
payload = {'ticker': ticker}
response = ses.get(base_url + "/assets", params... | self.stop_period = asset_response["stop_period"]
def __repr__(self):
return self.ticker + ' ' + self.type + ' Asset'
def __eq__(self, other):
return self.__dict__ == other.__dict__
def _get_assets_json(ses, ticker=None):
| 63 | 64 | 106 | 11 | 52 | SamSamhuns/RIT-trading-python | ritpytrading/assets.py | Python | _get_assets_json | _get_assets_json | 73 | 86 | 73 | 73 | cdfb9df6d7fbe7eaa91fd79a1f72a5fea592c3ab | bigcode/the-stack | train |
349385ebe8edd59eb8aa937f | train | function | def test_times_sparse_operand_reduce_multiple_axes():
from .. import times
vocab_size = 3
additional_axis_dim1 = 2
additional_axis_dim2 = 3
out_dim = 2
w_init = np.float32(np.random.rand(vocab_size, additional_axis_dim2, out_dim))
input_shape = (additional_axis_dim1, additional_axis_dim2, v... | def test_times_sparse_operand_reduce_multiple_axes():
| from .. import times
vocab_size = 3
additional_axis_dim1 = 2
additional_axis_dim2 = 3
out_dim = 2
w_init = np.float32(np.random.rand(vocab_size, additional_axis_dim2, out_dim))
input_shape = (additional_axis_dim1, additional_axis_dim2, vocab_size)
a = C.input_variable(shape=input_shape... | weights_with_dense_input_i = weights_i.value
weights_with_dense_input_h = weights_h.value
assert np.allclose(weights_with_sparse_input_i, weights_with_dense_input_i)
assert np.allclose(weights_with_sparse_input_h, weights_with_dense_input_h)
def test_times_sparse_operand_reduce_multiple_axes():
| 64 | 64 | 131 | 9 | 55 | burhandodhy/CNTK | bindings/python/cntk/ops/tests/sparse_test.py | Python | test_times_sparse_operand_reduce_multiple_axes | test_times_sparse_operand_reduce_multiple_axes | 181 | 195 | 181 | 181 | c09b139df122263e47937a3dedabb0230460537c | bigcode/the-stack | train |
3316511b3bea0de0b807d129 | train | function | def test_sparse_block_row_input(device_id):
dev = cntk_device(device_id)
num_classes = 3
w_init = np.asarray([[0,1],[2,3],[4,5]]).astype(np.float32)
w = C.parameter(init=w_init, device=dev)
x = C.input_variable(())
sparse_one_hot = C.one_hot(x, num_classes, sparse_output=True)
t = C.times(... | def test_sparse_block_row_input(device_id):
| dev = cntk_device(device_id)
num_classes = 3
w_init = np.asarray([[0,1],[2,3],[4,5]]).astype(np.float32)
w = C.parameter(init=w_init, device=dev)
x = C.input_variable(())
sparse_one_hot = C.one_hot(x, num_classes, sparse_output=True)
t = C.times(sparse_one_hot, w)
indices = np.asarray(... | ]], dtype=np.float32))]
result = t.eval({features : features_data}, device=dev)
assert np.array_equal(result, [[[.5, 1], [-.5, 2]], [[1, 1.5], [.5, 1]]])
def test_sparse_block_row_input(device_id):
| 66 | 66 | 223 | 9 | 57 | burhandodhy/CNTK | bindings/python/cntk/ops/tests/sparse_test.py | Python | test_sparse_block_row_input | test_sparse_block_row_input | 268 | 283 | 268 | 268 | 57d9f4fa185fa7c05d19e46ad240f6d983eb46d5 | bigcode/the-stack | train |
9293cf162c409276f751adf2 | train | function | def test_training_3d_sparse_sequence_with_recurrence(device_id):
from .. import times, times_transpose, reshape
from cntk.losses import cross_entropy_with_softmax
dev = cntk_device(device_id)
vocab_size = 3
additional_axis_dim1 = 2
additional_axis_dim2 = 3
out_dim = 2
w_init_i = np.floa... | def test_training_3d_sparse_sequence_with_recurrence(device_id):
| from .. import times, times_transpose, reshape
from cntk.losses import cross_entropy_with_softmax
dev = cntk_device(device_id)
vocab_size = 3
additional_axis_dim1 = 2
additional_axis_dim2 = 3
out_dim = 2
w_init_i = np.float32(np.random.rand(vocab_size, out_dim))
w_init_h = np.float3... | dev)
weights_with_sparse_input = weights.value
# Run with dense inputs
i1 = np.eye(vocab_size, dtype=np.float32)
dense_input = [i1[input_sparse_indices[0]], i1[input_sparse_indices[1]], i1[input_sparse_indices[2]]]
i2 = np.eye(out_dim, dtype=np.float32)
dense_label = [i2[label_sparse_indices[0]... | 256 | 256 | 855 | 15 | 241 | burhandodhy/CNTK | bindings/python/cntk/ops/tests/sparse_test.py | Python | test_training_3d_sparse_sequence_with_recurrence | test_training_3d_sparse_sequence_with_recurrence | 120 | 178 | 120 | 120 | 35c436f645a3682e6f91201df5507eacac4553a8 | bigcode/the-stack | train |
99125b746777b72c9dfed577 | train | function | def test_training_2d_sparse_sequence_operand(device_id):
from .. import times
from cntk.losses import cross_entropy_with_softmax
dev = cntk_device(device_id)
vocab_size = 6
additional_axis_dim = 2
out_dim = 4
w_init = np.float32(np.random.rand(vocab_size, out_dim))
input_shape = (additi... | def test_training_2d_sparse_sequence_operand(device_id):
| from .. import times
from cntk.losses import cross_entropy_with_softmax
dev = cntk_device(device_id)
vocab_size = 6
additional_axis_dim = 2
out_dim = 4
w_init = np.float32(np.random.rand(vocab_size, out_dim))
input_shape = (additional_axis_dim, vocab_size)
label_shape = (additional_... | = np.eye(vocab_size, dtype=np.float32)
w = C.parameter(init=w_init, device=dev)
a_dense = times(a, w)
# TODO: Also test the results from grad
grad = a_dense.grad({a : input_data}, [w, a], as_numpy=False, device=dev)
res = a_dense.eval({a : input_data}, device=dev)
expected = [w_init[input_spa... | 189 | 190 | 635 | 12 | 177 | burhandodhy/CNTK | bindings/python/cntk/ops/tests/sparse_test.py | Python | test_training_2d_sparse_sequence_operand | test_training_2d_sparse_sequence_operand | 72 | 117 | 72 | 72 | c895534e1d49d7deca2c8a846cdab37e6f065bdc | bigcode/the-stack | train |
9d2881e929ee8a28ffd7d22f | train | function | def test_gather_2D_using_one_hot_and_times():
i = C.sequence.input_variable((1,))
indices = [[2, 0], [1]]
sparse_one_hot = C.one_hot(i, num_classes=3, sparse_output=True)
w = C.parameter((-1, 2, 3), init=C.glorot_uniform())
t = C.times(sparse_one_hot, w, output_rank=2)
result = t.eval({i : indic... | def test_gather_2D_using_one_hot_and_times():
| i = C.sequence.input_variable((1,))
indices = [[2, 0], [1]]
sparse_one_hot = C.one_hot(i, num_classes=3, sparse_output=True)
w = C.parameter((-1, 2, 3), init=C.glorot_uniform())
t = C.times(sparse_one_hot, w, output_rank=2)
result = t.eval({i : indices})
w_value = w.value
expected_result... | = np.asarray([2, 0, 1])
result = sparse_one_hot.eval({i : indices})
result_indices = result.dot(np.array([0, 1, 2]))
assert np.array_equal(result_indices, indices)
def test_gather_2D_using_one_hot_and_times():
| 64 | 64 | 168 | 13 | 51 | burhandodhy/CNTK | bindings/python/cntk/ops/tests/sparse_test.py | Python | test_gather_2D_using_one_hot_and_times | test_gather_2D_using_one_hot_and_times | 206 | 216 | 206 | 206 | 384ca9d876a3bf12f21ab074e7a3e9fbd12dc598 | bigcode/the-stack | train |
66d80ecd4c28a0d912399668 | train | function | def test_gather_implementation_using_one_hot_and_times():
num_classes = 4
w_init = np.asarray([[0,1],[2,3],[4,5],[6,7]]).astype(np.float32)
w = C.parameter(init=w_init)
x = C.input_variable((2,))
sparse_one_hot = C.one_hot(x, num_classes, sparse_output=True)
t = C.times(sparse_one_hot, w)
... | def test_gather_implementation_using_one_hot_and_times():
| num_classes = 4
w_init = np.asarray([[0,1],[2,3],[4,5],[6,7]]).astype(np.float32)
w = C.parameter(init=w_init)
x = C.input_variable((2,))
sparse_one_hot = C.one_hot(x, num_classes, sparse_output=True)
t = C.times(sparse_one_hot, w)
indices = np.asarray([[0,3],[2,1]], dtype=np.float32)
... | , True)
assert np.array_equal(result_dense[0], np.eye(num_classes, dtype=np.float32)[indices[0]])
assert np.array_equal(result_dense[1], np.eye(num_classes, dtype=np.float32)[indices[1]])
def test_gather_implementation_using_one_hot_and_times():
| 63 | 64 | 174 | 12 | 51 | burhandodhy/CNTK | bindings/python/cntk/ops/tests/sparse_test.py | Python | test_gather_implementation_using_one_hot_and_times | test_gather_implementation_using_one_hot_and_times | 242 | 254 | 242 | 242 | 9b77a343a5e44c1d5b5679609bc88c0c06c0f03c | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.