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
cb21e3f12601be7aa84ded49
train
function
def receptive_field_size(kernel_size, depth): return 1 + 2 * (kernel_size - 1) * (2 ** depth - 1)
def receptive_field_size(kernel_size, depth):
return 1 + 2 * (kernel_size - 1) * (2 ** depth - 1)
for block in self.blocks: x = block(x) if not self.return_sequence: x = self.slice_layer(x) return x @property def receptive_field_size(self): return receptive_field_size(self.kernel_size, self.depth) def receptive_field_size(kernel_size, depth):
64
64
33
9
55
1044197988/TF.Keras-Commonly-used-models
Others/tcn.py
Python
receptive_field_size
receptive_field_size
136
137
136
136
7d311f98a7da35f57bbf8b64194ccd90a4927ff0
bigcode/the-stack
train
9b01798baeb3768fc0980ffd
train
class
class ResidualBlock(layers.Layer): """ A TCN Residual block stacking the dilated causal convolution :param filters: number of output filters in the convolution :param kernel_size: length of the 1D convolution window :param dilation_rate: dilation rate to use for dilated convolution :param dropou...
class ResidualBlock(layers.Layer):
""" A TCN Residual block stacking the dilated causal convolution :param filters: number of output filters in the convolution :param kernel_size: length of the 1D convolution window :param dilation_rate: dilation rate to use for dilated convolution :param dropout_rate: dropout rate :param act...
from typing import List from tensorflow.keras import Model, Input from tensorflow.keras import layers from datetime import datetime from pathlib import Path import tensorflow as tf from tensorflow.keras import losses, metrics from tensorflow.keras.callbacks import TensorBoard class ResidualBlock(layers.Layer):
58
155
517
8
49
1044197988/TF.Keras-Commonly-used-models
Others/tcn.py
Python
ResidualBlock
ResidualBlock
13
79
13
13
6fa26f9b2f8e3a5ef47f3eeb51fece1f4cdf312e
bigcode/the-stack
train
e8e083ef4967eb4adca2c8cf
train
function
def train(): depth = 6 filters = 25 block_filters = [filters] * depth print(block_filters) model = build_model(sequence_length=28 * 28, channels=1, num_classes=10, filters=block_filters, k...
def train():
depth = 6 filters = 25 block_filters = [filters] * depth print(block_filters) model = build_model(sequence_length=28 * 28, channels=1, num_classes=10, filters=block_filters, kernel_size=8)...
) train_dataset = tf.data.Dataset.from_tensor_slices((x_train_reshaped, y_train)).shuffle(1000) test_dataset = tf.data.Dataset.from_tensor_slices((x_test_reshaped, y_test)).shuffle(1000) return train_dataset, test_dataset def train():
64
64
169
3
60
1044197988/TF.Keras-Commonly-used-models
Others/tcn.py
Python
train
train
183
207
183
183
d6131d062a2232ca2b7d1709514e2362a425f394
bigcode/the-stack
train
3503c0d7ab6b5d6dc7486bac
train
function
def load_dataset(): (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() x_train_reshaped = 1/255 * x_train.reshape(-1, 28 * 28, 1) x_test_reshaped = 1/255 * x_test.reshape(-1, 28 * 28, 1) train_dataset = tf.data.Dataset.from_tensor_slices((x_train_reshaped, y_train)).shuffle(100...
def load_dataset():
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() x_train_reshaped = 1/255 * x_train.reshape(-1, 28 * 28, 1) x_test_reshaped = 1/255 * x_test.reshape(-1, 28 * 28, 1) train_dataset = tf.data.Dataset.from_tensor_slices((x_train_reshaped, y_train)).shuffle(1000) test_dataset ...
.Dense(num_classes, activation="softmax", name="output")(x) model = Model(inputs, outputs, name="tcn") print(f"Input sequence lenght: {sequence_length}, model receptive field: {tcn_block.receptive_field_size}") return model def load_dataset():
64
64
142
4
59
1044197988/TF.Keras-Commonly-used-models
Others/tcn.py
Python
load_dataset
load_dataset
172
180
172
172
49157251836fa7f3fc0f648eb144816312691b8a
bigcode/the-stack
train
d162506fe62edcfea15a67df
train
class
class DeleteStackInstancesRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'ROS', '2019-09-10', 'DeleteStackInstances','ROS') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_reg...
class DeleteStackInstancesRequest(RpcRequest):
def __init__(self): RpcRequest.__init__(self, 'ROS', '2019-09-10', 'DeleteStackInstances','ROS') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) ...
of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # sp...
117
117
390
9
107
jia-jerry/aliyun-openapi-python-sdk
aliyun-python-sdk-ros/aliyunsdkros/request/v20190910/DeleteStackInstancesRequest.py
Python
DeleteStackInstancesRequest
DeleteStackInstancesRequest
23
73
23
24
28e22b78755d0d691ab0aa8528a97919f696c533
bigcode/the-stack
train
fb96ab8324469ae6245b3ec6
train
function
def create_rcn_blstm(): model = Sequential() model.add(BLSTM(300, 300, init='he_normal',return_sequences=True,is_entity=False, regularize=True)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Embedding(300, 512,init='he_normal')) model.add(Dropout(0.5)) model.add(Embedding(5...
def create_rcn_blstm():
model = Sequential() model.add(BLSTM(300, 300, init='he_normal',return_sequences=True,is_entity=False, regularize=True)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Embedding(300, 512,init='he_normal')) model.add(Dropout(0.5)) model.add(Embedding(512, 4096,init='he_normal...
.add(Embedding(300, 512,init='he_normal')) model.add(Dropout(0.5)) model.add(Embedding(512, 4096,init='he_normal')) model.add(Dropout(0.7)) return model def create_rcn_blstm():
64
64
118
7
56
molingbo/crcn
load_models.py
Python
create_rcn_blstm
create_rcn_blstm
49
58
49
49
28694b2f7d0e3c172c205913ba6a93a1d8810aea
bigcode/the-stack
train
997d1a58e6a22942dae6c3b1
train
function
def create_crcn_blstm(): model = Sequential() model.add(BLSTM(300, 300, return_sequences=True,init='he_normal',is_entity=True, regularize=True)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Embedding(300, 512,init='he_normal')) model.add(Dropout(0.5)) model.add(Embedding(5...
def create_crcn_blstm():
model = Sequential() model.add(BLSTM(300, 300, return_sequences=True,init='he_normal',is_entity=True, regularize=True)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Embedding(300, 512,init='he_normal')) model.add(Dropout(0.5)) model.add(Embedding(512, 4096,init='he_normal'...
.add(Embedding(300, 512,init='he_normal')) model.add(Dropout(0.5)) model.add(Embedding(512, 4096,init='he_normal')) model.add(Dropout(0.7)) return model def create_crcn_blstm():
64
64
119
7
56
molingbo/crcn
load_models.py
Python
create_crcn_blstm
create_crcn_blstm
38
47
38
38
60259aa803525591b5de4a8b6183530e96e9e25e
bigcode/the-stack
train
996dc41e93f30ec88fcb72e5
train
function
def create_rcn(): model = Sequential() model.add(BRNN( 300, 300, return_sequences=True,init='he_normal', is_entity=False, regularize=False)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Embedding(300, 512,init='he_normal')) model.add(Dropout(0.5)) model.add...
def create_rcn():
model = Sequential() model.add(BRNN( 300, 300, return_sequences=True,init='he_normal', is_entity=False, regularize=False)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Embedding(300, 512,init='he_normal')) model.add(Dropout(0.5)) model.add(Embedding(512, 40...
model.add(Embedding(300, 512,init='he_normal')) model.add(Dropout(0.5)) model.add(Embedding(512, 4096,init='he_normal')) model.add(Dropout(0.7)) return model def create_rcn():
64
64
120
5
58
molingbo/crcn
load_models.py
Python
create_rcn
create_rcn
25
36
25
25
6985f6c18a7e74e70069c3cd4ab470113e90ce65
bigcode/the-stack
train
5297e79193e2e25cd3ba35b6
train
function
def create_crcn(): model = Sequential() model.add(BRNN( 300, 300, return_sequences=True,init='he_normal', is_entity=True, regularize=False)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Embedding(300, 512,init='he_normal')) model.add(Dropout(0.5)) model.add...
def create_crcn():
model = Sequential() model.add(BRNN( 300, 300, return_sequences=True,init='he_normal', is_entity=True, regularize=False)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Embedding(300, 512,init='he_normal')) model.add(Dropout(0.5)) model.add(Embedding(512, 409...
.models import Graph from keras.layers.embeddings import Embedding from keras.layers.core import * #from keras.layers.convolutional import Convolution2D, MaxPooling2D from keras.layers.normalization import BatchNormalization from keras.optimizers import SGD from keras.layers.recurrent import * def create_crcn():
64
64
120
5
59
molingbo/crcn
load_models.py
Python
create_crcn
create_crcn
12
23
12
12
c97df1f3bd98189604f44c16d139e4ef62a2ca3b
bigcode/the-stack
train
242549305cfaabc2df8cf3af
train
function
def test_tnr_some_correct(): y_true = [0, 0, 0, 0, 1] y_pred = [0, 0, 0, 1, 1] result = metrics.true_negative_rate(y_true, y_pred) assert result == 0.75
def test_tnr_some_correct():
y_true = [0, 0, 0, 0, 1] y_pred = [0, 0, 0, 1, 1] result = metrics.true_negative_rate(y_true, y_pred) assert result == 0.75
y_true = [0, 0, 0, 0, 1] y_pred = [1, 1, 1, 1, 0] result = metrics.true_negative_rate(y_true, y_pred) assert result == 0 def test_tnr_some_correct():
64
64
67
7
56
janhavi13/fairlearn
test/unit/metrics/test_extra_metrics.py
Python
test_tnr_some_correct
test_tnr_some_correct
26
31
26
26
98d0b9fbf119de2c61de86a43b6297baace01b5f
bigcode/the-stack
train
9db77c3849f9a290a871939d
train
function
def test_fnr_with_false_positive(): y_true = [0, 0, 0, 0, 1] y_pred = [0, 0, 0, 1, 1] result = metrics.false_negative_rate(y_true, y_pred) assert result == 0
def test_fnr_with_false_positive():
y_true = [0, 0, 0, 0, 1] y_pred = [0, 0, 0, 1, 1] result = metrics.false_negative_rate(y_true, y_pred) assert result == 0
_true = [0, 0, 0, 0, 1] y_pred = [1, 1, 1, 1, 0] result = metrics.false_negative_rate(y_true, y_pred) assert result == 1 def test_fnr_with_false_positive():
64
64
66
8
55
janhavi13/fairlearn
test/unit/metrics/test_extra_metrics.py
Python
test_fnr_with_false_positive
test_fnr_with_false_positive
61
66
61
61
6de48e150c25282741d30063d5e579a54d6cfdf3
bigcode/the-stack
train
03571254404e34ac38c8f70a
train
function
def test_tnr_all_correct(): y_true = [0, 0, 0, 0, 1] y_pred = [0, 0, 0, 0, 1] result = metrics.true_negative_rate(y_true, y_pred) assert result == 1
def test_tnr_all_correct():
y_true = [0, 0, 0, 0, 1] y_pred = [0, 0, 0, 0, 1] result = metrics.true_negative_rate(y_true, y_pred) assert result == 1
# Copyright (c) Microsoft Corporation and contributors. # Licensed under the MIT License. import fairlearn.metrics as metrics # ============================================== # True Negative Rate def test_tnr_all_correct():
40
64
65
7
32
janhavi13/fairlearn
test/unit/metrics/test_extra_metrics.py
Python
test_tnr_all_correct
test_tnr_all_correct
10
15
10
10
83d48a36e936451dda60469a06b2bfa37d6f6893
bigcode/the-stack
train
1cc8e68cd1aa72ceeae7fb3c
train
function
def test_tnr_some_correct_with_false_negative(): y_true = [0, 0, 0, 0, 1] y_pred = [0, 0, 1, 0, 0] result = metrics.true_negative_rate(y_true, y_pred) assert result == 0.75
def test_tnr_some_correct_with_false_negative():
y_true = [0, 0, 0, 0, 1] y_pred = [0, 0, 1, 0, 0] result = metrics.true_negative_rate(y_true, y_pred) assert result == 0.75
, 0, 0, 0, 1] y_pred = [0, 0, 0, 1, 1] result = metrics.true_negative_rate(y_true, y_pred) assert result == 0.75 def test_tnr_some_correct_with_false_negative():
64
64
70
10
53
janhavi13/fairlearn
test/unit/metrics/test_extra_metrics.py
Python
test_tnr_some_correct_with_false_negative
test_tnr_some_correct_with_false_negative
34
39
34
34
f21ccc3b359bc44db7a29eff74380a9ee19966bd
bigcode/the-stack
train
4a6ed837c4b98c4eb8e7c52d
train
function
def test_tnr_none_correct(): y_true = [0, 0, 0, 0, 1] y_pred = [1, 1, 1, 1, 0] result = metrics.true_negative_rate(y_true, y_pred) assert result == 0
def test_tnr_none_correct():
y_true = [0, 0, 0, 0, 1] y_pred = [1, 1, 1, 1, 0] result = metrics.true_negative_rate(y_true, y_pred) assert result == 0
y_true = [0, 0, 0, 0, 1] y_pred = [0, 0, 0, 0, 1] result = metrics.true_negative_rate(y_true, y_pred) assert result == 1 def test_tnr_none_correct():
64
64
65
7
56
janhavi13/fairlearn
test/unit/metrics/test_extra_metrics.py
Python
test_tnr_none_correct
test_tnr_none_correct
18
23
18
18
129be52a315307a70902003ace08568a59bc6283
bigcode/the-stack
train
1647cffcc81e2bc691feb67c
train
function
def test_fnr_none_correct(): y_true = [0, 0, 0, 0, 1] y_pred = [1, 1, 1, 1, 0] result = metrics.false_negative_rate(y_true, y_pred) assert result == 1
def test_fnr_none_correct():
y_true = [0, 0, 0, 0, 1] y_pred = [1, 1, 1, 1, 0] result = metrics.false_negative_rate(y_true, y_pred) assert result == 1
y_true = [0, 0, 0, 0, 1] y_pred = [0, 0, 0, 0, 1] result = metrics.false_negative_rate(y_true, y_pred) assert result == 0 def test_fnr_none_correct():
64
64
65
7
56
janhavi13/fairlearn
test/unit/metrics/test_extra_metrics.py
Python
test_fnr_none_correct
test_fnr_none_correct
53
58
53
53
38c95dc95dce3fd8a905ca7e89483af027c70ebf
bigcode/the-stack
train
8643831870f7f7416a2b9b73
train
function
def test_fnr_some_correct(): y_true = [1, 1, 1, 1, 0, 0] y_pred = [0, 0, 1, 0, 0, 1] result = metrics.false_negative_rate(y_true, y_pred) assert result == 0.75
def test_fnr_some_correct():
y_true = [1, 1, 1, 1, 0, 0] y_pred = [0, 0, 1, 0, 0, 1] result = metrics.false_negative_rate(y_true, y_pred) assert result == 0.75
y_true = [0, 0, 0, 0, 1] y_pred = [0, 0, 0, 1, 1] result = metrics.false_negative_rate(y_true, y_pred) assert result == 0 def test_fnr_some_correct():
64
64
73
7
56
janhavi13/fairlearn
test/unit/metrics/test_extra_metrics.py
Python
test_fnr_some_correct
test_fnr_some_correct
69
74
69
69
05cf8c80b43aa77994dc741f9cc4fc7582e1167a
bigcode/the-stack
train
c919e5bc8e86765f4e75598c
train
function
def test_fnr_all_correct(): y_true = [0, 0, 0, 0, 1] y_pred = [0, 0, 0, 0, 1] result = metrics.false_negative_rate(y_true, y_pred) assert result == 0
def test_fnr_all_correct():
y_true = [0, 0, 0, 0, 1] y_pred = [0, 0, 0, 0, 1] result = metrics.false_negative_rate(y_true, y_pred) assert result == 0
0, 0, 1] y_pred = [0, 0, 1, 0, 0] result = metrics.true_negative_rate(y_true, y_pred) assert result == 0.75 # ======================================== # False Negative Rate def test_fnr_all_correct():
64
64
65
7
56
janhavi13/fairlearn
test/unit/metrics/test_extra_metrics.py
Python
test_fnr_all_correct
test_fnr_all_correct
45
50
45
45
4d0b36db94e6f40840495fb101702a35634d10ba
bigcode/the-stack
train
88153b332643fb6c1a97270a
train
function
def test_fpr_none_correct(): y_true = [0, 0, 0, 0, 1] y_pred = [1, 1, 1, 1, 0] result = metrics.false_positive_rate(y_true, y_pred) assert result == 1
def test_fpr_none_correct():
y_true = [0, 0, 0, 0, 1] y_pred = [1, 1, 1, 1, 0] result = metrics.false_positive_rate(y_true, y_pred) assert result == 1
y_true = [0, 0, 0, 0, 1] y_pred = [0, 0, 0, 0, 1] result = metrics.false_positive_rate(y_true, y_pred) assert result == 0 def test_fpr_none_correct():
64
64
65
7
56
janhavi13/fairlearn
test/unit/metrics/test_extra_metrics.py
Python
test_fpr_none_correct
test_fpr_none_correct
88
93
88
88
8c6f311a2064e2fa4d027e805298f84b8a63fb3e
bigcode/the-stack
train
0f82724c5bd51288cfcadae6
train
function
def test_fpr_some_correct(): y_true = [0, 0, 0, 0, 1, 1, 1] y_pred = [0, 1, 1, 0, 0, 1, 0] result = metrics.false_positive_rate(y_true, y_pred) assert result == 0.5
def test_fpr_some_correct():
y_true = [0, 0, 0, 0, 1, 1, 1] y_pred = [0, 1, 1, 0, 0, 1, 0] result = metrics.false_positive_rate(y_true, y_pred) assert result == 0.5
y_true = [0, 0, 0, 0, 1] y_pred = [1, 1, 1, 1, 0] result = metrics.false_positive_rate(y_true, y_pred) assert result == 1 def test_fpr_some_correct():
64
64
79
7
56
janhavi13/fairlearn
test/unit/metrics/test_extra_metrics.py
Python
test_fpr_some_correct
test_fpr_some_correct
96
102
96
96
220624b12ba555c169135bbf1b10b68f2be01bd2
bigcode/the-stack
train
92f41415e7cb157a08e240a4
train
function
def test_fpr_all_correct(): y_true = [0, 0, 0, 0, 1] y_pred = [0, 0, 0, 0, 1] result = metrics.false_positive_rate(y_true, y_pred) assert result == 0
def test_fpr_all_correct():
y_true = [0, 0, 0, 0, 1] y_pred = [0, 0, 0, 0, 1] result = metrics.false_positive_rate(y_true, y_pred) assert result == 0
, 0] y_pred = [0, 0, 1, 0, 0, 1] result = metrics.false_negative_rate(y_true, y_pred) assert result == 0.75 # ============================ # False Positive Rate def test_fpr_all_correct():
64
64
65
7
56
janhavi13/fairlearn
test/unit/metrics/test_extra_metrics.py
Python
test_fpr_all_correct
test_fpr_all_correct
80
85
80
80
142a29b9e0b40b1adb7883229d02ac66ae5148a0
bigcode/the-stack
train
1ad80dc7596106501ef2ba4c
train
function
def load_tests(loader, tests, ignore): """Load the pyfakefs/example.py doctest tests into unittest.""" return fake_filesystem_unittest.load_doctests( loader, tests, ignore, example)
def load_tests(loader, tests, ignore):
"""Load the pyfakefs/example.py doctest tests into unittest.""" return fake_filesystem_unittest.load_doctests( loader, tests, ignore, example)
size of the file. """ import io import os import sys import unittest from pyfakefs import fake_filesystem_unittest from pyfakefs.extra_packages import use_scandir_package from pyfakefs.tests import example # The module under test def load_tests(loader, tests, ignore):
64
64
46
9
54
ale180192/google-ads-python-examples
.eggs/pyfakefs-3.5.8-py3.6.egg/pyfakefs/tests/example_test.py
Python
load_tests
load_tests
39
42
39
39
407913badfc63b2898549d51a7fd412bf41b00a8
bigcode/the-stack
train
99fc12f13abc99743027064f
train
class
class TestExample(fake_filesystem_unittest.TestCase): # pylint: disable=R0904 """Test the example module. The os and shutil modules have been replaced with the fake modules, so that all of the calls to os and shutil in the tested example code occur in the fake filesystem. """ d...
class TestExample(fake_filesystem_unittest.TestCase): # pylint: disable=R0904
"""Test the example module. The os and shutil modules have been replaced with the fake modules, so that all of the calls to os and shutil in the tested example code occur in the fake filesystem. """ def setUp(self): """Invoke the :py:class:`pyfakefs.fake_filesystem_unitt...
the License. """ Test the :py:class`pyfakefs.example` module to demonstrate the usage of the :py:class`pyfakefs.fake_filesystem_unittest.TestCase` base class. Fake filesystem functions like `create_file()`, `create_dir()` or `create_symlink()` are often used to set up file structures at the beginning of a te...
256
256
1,297
21
235
ale180192/google-ads-python-examples
.eggs/pyfakefs-3.5.8-py3.6.egg/pyfakefs/tests/example_test.py
Python
TestExample
TestExample
45
178
45
45
d5db92c8637646cf3035024b2b12b51e45152286
bigcode/the-stack
train
47dcc1c4ed01d6355c1d5e28
train
class
class DecoderState: """ Class using for maintain different chunks of data in one beam algorithm corresponding to one unique source. Note: after using State you should delete it, so dont reuse it Args: decoder (OnlineCTCBeamDecoder) - decoder you will use for decoding. """ def __init__(se...
class DecoderState:
""" Class using for maintain different chunks of data in one beam algorithm corresponding to one unique source. Note: after using State you should delete it, so dont reuse it Args: decoder (OnlineCTCBeamDecoder) - decoder you will use for decoding. """ def __init__(self, decoder): ...
_decode.get_max_order(self._scorer) if self._scorer else None def dict_size(self): return ctc_decode.get_dict_size(self._scorer) if self._scorer else None def reset_state(state): ctc_decode.paddle_release_state(state) class DecoderState:
64
64
149
4
60
vishnu-hue/ctcdecode
ctcdecode/__init__.py
Python
DecoderState
DecoderState
255
274
255
255
2f96232ecdca0638dc658a9301fb85e2cd29fc0e
bigcode/the-stack
train
de41dc87404f52e9bbb0b85c
train
class
class CTCBeamDecoder(object): """ PyTorch wrapper for DeepSpeech PaddlePaddle Beam Search Decoder. Args: labels (list): The tokens/vocab used to train your model. They should be in the same order as they are in your model's outputs. model_path (basestring): The path t...
class CTCBeamDecoder(object):
""" PyTorch wrapper for DeepSpeech PaddlePaddle Beam Search Decoder. Args: labels (list): The tokens/vocab used to train your model. They should be in the same order as they are in your model's outputs. model_path (basestring): The path to your external KenLM language...
import torch from ._ext import ctc_decode class CTCBeamDecoder(object):
19
256
1,295
7
11
vishnu-hue/ctcdecode
ctcdecode/__init__.py
Python
CTCBeamDecoder
CTCBeamDecoder
6
141
6
6
34095e6e5bac1324b4c4c45a082f902ad84f70ac
bigcode/the-stack
train
84ae967620a070731b6ee0e3
train
class
class OnlineCTCBeamDecoder(object): """ PyTorch wrapper for DeepSpeech PaddlePaddle Beam Search Decoder with interface for online decoding. Args: labels (list): The tokens/vocab used to train your model. They should be in the same order as they are in your model's outputs. ...
class OnlineCTCBeamDecoder(object):
""" PyTorch wrapper for DeepSpeech PaddlePaddle Beam Search Decoder with interface for online decoding. Args: labels (list): The tokens/vocab used to train your model. They should be in the same order as they are in your model's outputs. model_path (basestring): The p...
else: ctc_decode.paddle_beam_decode( probs, seq_lens, self._labels, self._num_labels, self._beam_width, self._num_processes, self._cutoff_prob, self.cutoff_top_n, ...
256
256
1,188
8
248
vishnu-hue/ctcdecode
ctcdecode/__init__.py
Python
OnlineCTCBeamDecoder
OnlineCTCBeamDecoder
144
252
144
144
dc1d0e5bb648bd49b67235f3dfc85dc7808d7763
bigcode/the-stack
train
6defefe5ecfbd3f5899cde26
train
class
class PageOfMalwareKit(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 (d...
class PageOfMalwareKit(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 name ...
JSON Hyper-Schema</a> <a target=\"_blank\" href=\"http://json-schema.org/latest/json-schema-hypermedia.html#rfc.section.5.2\">\"Link Description Object\"</a> formats. For example: ```json \"links\": [{ \"rel\": \"<relation>\", \"href\": \"<href>\" ... }] ``` Where appropriate link objects may also contain addi...
256
256
1,050
8
247
pdeardorff-r7/vm-console-client-python
rapid7vmconsole/models/page_of_malware_kit.py
Python
PageOfMalwareKit
PageOfMalwareKit
24
174
24
24
ba4fcb4e75fc3b69f0cce8c9950311c939d5a6a8
bigcode/the-stack
train
3ead53e6ad434c1d92b45414
train
function
def main(): """ While example. >>> i = 1 >>> while i <= 5: ... print(i, end='') ... i += 1 12345 >>> i = 5 >>> while i >= 1: ... print(i, end='') ... i -= 1 54321 """
def main():
""" While example. >>> i = 1 >>> while i <= 5: ... print(i, end='') ... i += 1 12345 >>> i = 5 >>> while i >= 1: ... print(i, end='') ... i -= 1 54321 """
def main():
3
64
83
3
0
examplehub/Python
basics/while_example.py
Python
main
main
1
16
1
1
680b5c85952ce901059ffe67ba6152e0a0006a38
bigcode/the-stack
train
3a7c61fbc972fb3ce20429aa
train
function
def verify_ip(addr): if sys.version_info[0] == 2: try: ipaddress.ip_address(bytearray(addr)) except ValueError: sys.exit("Input does not evaluate to an IP address for node " "%s, submitted IP is %s" % (nodeName,addr)) elif sys.version_info[0] >...
def verify_ip(addr):
if sys.version_info[0] == 2: try: ipaddress.ip_address(bytearray(addr)) except ValueError: sys.exit("Input does not evaluate to an IP address for node " "%s, submitted IP is %s" % (nodeName,addr)) elif sys.version_info[0] > 2: try: ...
to determine if input is a valid IP address, this works for IPv4 and IPv6 # This script explicity calls out Python v2 and above as valid and below v2 as unsupported # Changes to Python in the future could result in the script needing updated to address that def verify_ip(addr):
63
64
151
5
57
schubb2003/solidfire_cluster_auto_build
build_untested.py
Python
verify_ip
verify_ip
134
148
134
134
f817b531c60c14456dec65bcd7220b2fbe878715
bigcode/the-stack
train
17f48ff599b8bd440348e3c2
train
function
def drive_add(): drive_array = [] check_array = [] sfe_drive_add = ElementFactory.create(mvip_ip, sf_user, sf_user_pass, print_ascii_art=False) list_drives = sfe_drive_add.li...
def drive_add():
drive_array = [] check_array = [] sfe_drive_add = ElementFactory.create(mvip_ip, sf_user, sf_user_pass, print_ascii_art=False) list_drives = sfe_drive_add.list_drives() f...
_pass = args.pw update_dhcp_addr = args.ud network_converge = args.cm # Vars used later build_mipi = "" build_sipi = "" node_count = 0 node_array = [] # Function to build array of available drives and add them def drive_add():
64
64
188
4
59
schubb2003/solidfire_cluster_auto_build
build_untested.py
Python
drive_add
drive_add
92
113
92
92
0fcc85c4bd34b4b04e9994674e1dcbe87912a26a
bigcode/the-stack
train
32af6020ecc044957d090b6d
train
function
def test_ip(host): ping_loop_count = 0 if system_name().lower() == "windows": response = os.system("ping -n 2 " + host) else: response = os.system("ping -c 2 " + host) sys.stdout.write(response) while response != 0: sys.stdout.write("retrying...") ...
def test_ip(host):
ping_loop_count = 0 if system_name().lower() == "windows": response = os.system("ping -n 2 " + host) else: response = os.system("ping -c 2 " + host) sys.stdout.write(response) while response != 0: sys.stdout.write("retrying...") time.sleep(10) ...
check_array.append(disk.drive_id) if len(check_array) > 0: sys.stdout.write("Error assigning drives %s, " % check_array + \ "please double check drive status") # Function used to determine if the OS is Windows or Unix and test ping def test_ip(host):
64
64
123
5
58
schubb2003/solidfire_cluster_auto_build
build_untested.py
Python
test_ip
test_ip
116
129
116
116
0222988747d84e52f5d840b02d549e8e7c246f83
bigcode/the-stack
train
5c07a98da61f55b06b1a100e
train
function
def ipi_check(): net_int_loop_check = 0 get_cluster_config_result = sfe.get_cluster_config() build_mipi = get_cluster_config_result.cluster.mipi build_sipi = get_cluster_config_result.cluster.sipi net_int_loop_check += 1 if net_int_loop_check > 10: sys.exit("MVIP/SVIP verification...
def ipi_check():
net_int_loop_check = 0 get_cluster_config_result = sfe.get_cluster_config() build_mipi = get_cluster_config_result.cluster.mipi build_sipi = get_cluster_config_result.cluster.sipi net_int_loop_check += 1 if net_int_loop_check > 10: sys.exit("MVIP/SVIP verification exceeded 10 tries...
"%s, submitted IP is %s" % (nodeName,addr)) elif sys.version_info[0] < 2: sys.exit("Unsupported version of Python detected, script will exit") # Function to wait until mipi and sipi are on the proper networks def ipi_check():
64
64
108
5
58
schubb2003/solidfire_cluster_auto_build
build_untested.py
Python
ipi_check
ipi_check
151
160
151
151
3699c7587254560d1f7577c32b6d3c3e1324fa50
bigcode/the-stack
train
c7900133b396108367611f96
train
function
@javes.on(rekcah05(pattern=f"exec(?: |$)([\s\S]*)", allow_sudo=True)) async def run(run_q): if not FULL_SUDO: await query.reply(f"`{JAVES_NNAME}:` **Sorry , Normal Sudo cant acess this comand, active advance sudo by set FULL_SUDO as true in heroku var**") else: code = run_q.pattern_match.group(1) ...
@javes.on(rekcah05(pattern=f"exec(?: |$)([\s\S]*)", allow_sudo=True)) async def run(run_q):
if not FULL_SUDO: await query.reply(f"`{JAVES_NNAME}:` **Sorry , Normal Sudo cant acess this comand, active advance sudo by set FULL_SUDO as true in heroku var**") else: code = run_q.pattern_match.group(1) if not code: await run_q.reply(f"`{JAVES_NNAME}:` **At least a variable is requi...
.chat_id, "exec.txt", reply_to=run_q.id, caption="`Output too large, sending as file`", ) remove("exec.txt") return await run_q.edit("**Query: **\n`" f"{codepre}" "`\n**Result: *...
153
153
513
32
121
TAMILVIP007/javes-3.0
userbot/modules/script.py
Python
run
run
156
211
156
157
6912e830ad5ed380d848f3e35b9231f9c967db30
bigcode/the-stack
train
c4cc7784d5b73e33da72c095
train
function
@javes05(outgoing=True, pattern=r"^\!exec(?: |$)([\s\S]*)") async def run(run_q): code = run_q.pattern_match.group(1) if not code: await run_q.edit(f"`{JAVES_NNAME}:` **At least a variable is required to \ execute. Use !help script for an example.**") return if code in ("userbot.sessio...
@javes05(outgoing=True, pattern=r"^\!exec(?: |$)([\s\S]*)") async def run(run_q):
code = run_q.pattern_match.group(1) if not code: await run_q.edit(f"`{JAVES_NNAME}:` **At least a variable is required to \ execute. Use !help script for an example.**") return if code in ("userbot.session", "env", "printenv"): await run_q.edit(f"`{JAVES_NNAME}:` **Privacy Erro...
n`" if stdout or stderr: if not len(text) > 4096: return await rkp.edit(text) output = open("term.txt", "w+") output.write(text) output.close() await event.client.send_file(event.chat_id, "term.txt", reply_to=event.id, caption=f"`{JAVES_NNAME}:` **Output too large, sending ...
133
136
456
29
103
TAMILVIP007/javes-3.0
userbot/modules/script.py
Python
run
run
101
153
101
102
4b576f35e48a6531c315f944498a8ebb2bbeb4ae
bigcode/the-stack
train
8f86a29f44cabcb2657e9276
train
function
@javes.on(rekcah05(pattern=f"term(?: |$|\n)([\s\S]*)", allow_sudo=True)) async def evaluate(event): if not FULL_SUDO: await query.reply(f"`{JAVES_NNAME}:` **Sorry , Normal Sudo cant acess this comand, active advance sudo by set FULL_SUDO as true in heroku var**") else: rkp = await event.reply(f"**{JA...
@javes.on(rekcah05(pattern=f"term(?: |$|\n)([\s\S]*)", allow_sudo=True)) async def evaluate(event):
if not FULL_SUDO: await query.reply(f"`{JAVES_NNAME}:` **Sorry , Normal Sudo cant acess this comand, active advance sudo by set FULL_SUDO as true in heroku var**") else: rkp = await event.reply(f"**{JAVES_NNAME}**: `Running Terminal.....`") message = (str(event.chat_id) + ':' + str(event.message.id...
`" + stderr.decode('UTF-8').strip() + "\n`" if stdout or stderr: if not len(text) > 4096: return await event.edit(text) output = open("term.txt", "w+") output.write(text) output.close() await event.client.send_file(event.chat_id, "term.txt", reply_to=event.id, caption=f"`{J...
151
153
512
34
116
TAMILVIP007/javes-3.0
userbot/modules/script.py
Python
evaluate
evaluate
56
92
56
57
f19367cf52450516456f45d99c70399c6c82c144
bigcode/the-stack
train
b9b5fc2a6231700e912de30c
train
function
@javes.on(rekcah05(pattern=f"hash (.*)", allow_sudo=True)) async def gethash(hash_q): hashtxt_ = hash_q.pattern_match.group(1) hashtxt = open("hashdis.txt", "w+") hashtxt.write(hashtxt_) hashtxt.close() md5 = runapp(["md5sum", "hashdis.txt"], stdout=PIPE) md5 = md5.stdout.decode() sha1 = run...
@javes.on(rekcah05(pattern=f"hash (.*)", allow_sudo=True)) async def gethash(hash_q):
hashtxt_ = hash_q.pattern_match.group(1) hashtxt = open("hashdis.txt", "w+") hashtxt.write(hashtxt_) hashtxt.close() md5 = runapp(["md5sum", "hashdis.txt"], stdout=PIPE) md5 = md5.stdout.decode() sha1 = runapp(["sha1sum", "hashdis.txt"], stdout=PIPE) sha1 = sha1.stdout.decode() sha25...
hashfile.write(ans) hashfile.close() await hash_q.client.send_file( hash_q.chat_id, "hashes.txt", reply_to=hash_q.id, caption="`It's too big, sending a text file instead. `") runapp(["rm", "hashes.txt"], stdout=PIPE) else: await...
107
108
363
27
80
TAMILVIP007/javes-3.0
userbot/modules/script.py
Python
gethash
gethash
338
366
338
339
25ffbd3c5d8ef1dba355eef8994226beabb05418
bigcode/the-stack
train
e468f9894c49f7d488270a3c
train
function
@javes05(outgoing=True, pattern="^\!base64 (en|de) (.*)") async def endecrypt(query): if query.pattern_match.group(1) == "en": lething = str( pybase64.b64encode(bytes(query.pattern_match.group(2), "utf-8")))[2:] await query.reply("Encoded: `" + lethin...
@javes05(outgoing=True, pattern="^\!base64 (en|de) (.*)") async def endecrypt(query):
if query.pattern_match.group(1) == "en": lething = str( pybase64.b64encode(bytes(query.pattern_match.group(2), "utf-8")))[2:] await query.reply("Encoded: `" + lething[:-1] + "`") else: lething = str( pybase64.b64decode(bytes(qu...
big, sending a text file instead. `") runapp(["rm", "hashes.txt"], stdout=PIPE) else: await hash_q.reply(ans) @javes05(outgoing=True, pattern="^\!base64 (en|de) (.*)") async def endecrypt(query):
63
64
140
28
35
TAMILVIP007/javes-3.0
userbot/modules/script.py
Python
endecrypt
endecrypt
372
383
372
373
fb24eae88bd5b6a006cc1ad01abb2659ca45ec5b
bigcode/the-stack
train
87480501f26373bdc75598c0
train
function
@javes.on(rekcah05(pattern=f"eval(?: |$)(.*)", allow_sudo=True)) async def evaluate(query): if not FULL_SUDO: await query.reply(f"`{JAVES_NNAME}:` **Sorry , Normal Sudo cant acess this comand, active advance sudo by set FULL_SUDO as true in heroku var**") else: if query.pattern_match.group(1): ...
@javes.on(rekcah05(pattern=f"eval(?: |$)(.*)", allow_sudo=True)) async def evaluate(query):
if not FULL_SUDO: await query.reply(f"`{JAVES_NNAME}:` **Sorry , Normal Sudo cant acess this comand, active advance sudo by set FULL_SUDO as true in heroku var**") else: if query.pattern_match.group(1): expression = query.pattern_match.group(1) else: await query.reply(f"`{JAVES_NNAM...
" f"{evaluation}" "`") else: await query.edit("**Query: **\n`" f"{expression}" "`\n**Result: **\n`No Result Returned/False`") except Exception as err: await query.e...
118
119
398
28
90
TAMILVIP007/javes-3.0
userbot/modules/script.py
Python
evaluate
evaluate
256
300
256
257
6d203abf4d07173efab32e87528ff9b265e34dc2
bigcode/the-stack
train
4d7819410a18a893519e2fe1
train
function
@javes05(outgoing=True, pattern="^\!eval(?: |$)(.*)") async def evaluate(query): if query.pattern_match.group(1): expression = query.pattern_match.group(1) else: await query.edit(f"`{JAVES_NNAME}:` **Please give command type !help script for more info**") return if expression in ("u...
@javes05(outgoing=True, pattern="^\!eval(?: |$)(.*)") async def evaluate(query):
if query.pattern_match.group(1): expression = query.pattern_match.group(1) else: await query.edit(f"`{JAVES_NNAME}:` **Please give command type !help script for more info**") return if expression in ("userbot.session", "env", "printenv"): await query.edit(f"`{JAVES_NNAME}:` ...
_q.reply("**Query: **\n`" f"{codepre}" "`\n**Result: **\n`" f"{result}" "`") else: await run_q.reply("**Query: **\n`" f"{codepre}" "`\n**Result: **\n`No Resul...
102
102
340
24
78
TAMILVIP007/javes-3.0
userbot/modules/script.py
Python
evaluate
evaluate
213
254
213
214
7b9bfb7bfeab6877a51d2849b194073235aa05b6
bigcode/the-stack
train
5a91172b7d4699bb3f3713fa
train
function
@javes.on(rekcah05(pattern=f"base64 (en|de) (.*)", allow_sudo=True)) async def endecrypt(query): if query.pattern_match.group(1) == "en": lething = str( pybase64.b64encode(bytes(query.pattern_match.group(2), "utf-8")))[2:] await query.reply("Encoded: ...
@javes.on(rekcah05(pattern=f"base64 (en|de) (.*)", allow_sudo=True)) async def endecrypt(query):
if query.pattern_match.group(1) == "en": lething = str( pybase64.b64encode(bytes(query.pattern_match.group(2), "utf-8")))[2:] await query.reply("Encoded: `" + lething[:-1] + "`") else: lething = str( pybase64.b64decode(bytes(qu...
(2), "utf-8"), validate=True))[2:] await query.reply("Decoded: `" + lething[:-1] + "`") @javes.on(rekcah05(pattern=f"base64 (en|de) (.*)", allow_sudo=True)) async def endecrypt(query):
63
64
144
32
31
TAMILVIP007/javes-3.0
userbot/modules/script.py
Python
endecrypt
endecrypt
387
398
387
388
32b6a8bf4078de12b9fe4aa6192e4a50ca6f1683
bigcode/the-stack
train
bf795025066e5d234c1ffea8
train
function
@javes05(outgoing=True, pattern="^\!term(?: |$|\n)([\s\S]*)") async def evaluate(event): await event.edit(f"**{JAVES_NNAME}**: `Running Terminal.....`") message = (str(event.chat_id) + ':' + str(event.message.id)) if running_processes.get(message, False): await event.edit("A process for this event...
@javes05(outgoing=True, pattern="^\!term(?: |$|\n)([\s\S]*)") async def evaluate(event):
await event.edit(f"**{JAVES_NNAME}**: `Running Terminal.....`") message = (str(event.chat_id) + ':' + str(event.message.id)) if running_processes.get(message, False): await event.edit("A process for this event is already running!") return cmd = event.pattern_match.group(1).strip() ...
LOG, BOTLOG_CHATID from userbot.events import javes05, bot, rekcah05 javes = client = bot from userbot import CMD_HELP, ALIVE_NAME, PM_MESSAGE, JAVES_NAME, JAVES_MSG, ORI_MSG JAVES_NNAME = str(JAVES_NAME) if JAVES_NAME else str(JAVES_MSG) FULL_SUDO = os.environ.get("FULL_SUDO", None) import inspect running_processes: d...
133
134
448
30
103
TAMILVIP007/javes-3.0
userbot/modules/script.py
Python
evaluate
evaluate
19
52
19
20
e81caf790fc0e5084a20ca7e2e4b6666b8782412
bigcode/the-stack
train
29cfa04892d883e41d53ff86
train
function
@javes05(outgoing=True, pattern="^\!hash (.*)") async def gethash(hash_q): hashtxt_ = hash_q.pattern_match.group(1) hashtxt = open("hashdis.txt", "w+") hashtxt.write(hashtxt_) hashtxt.close() md5 = runapp(["md5sum", "hashdis.txt"], stdout=PIPE) md5 = md5.stdout.decode() sha1 = runapp(["sha1s...
@javes05(outgoing=True, pattern="^\!hash (.*)") async def gethash(hash_q):
hashtxt_ = hash_q.pattern_match.group(1) hashtxt = open("hashdis.txt", "w+") hashtxt.write(hashtxt_) hashtxt.close() md5 = runapp(["md5sum", "hashdis.txt"], stdout=PIPE) md5 = md5.stdout.decode() sha1 = runapp(["sha1sum", "hashdis.txt"], stdout=PIPE) sha1 = sha1.stdout.decode() sha25...
"`") else: await query.reply("**Query: **\n`" f"{expression}" "`\n**Result: **\n`No Result Returned/False`") except Exception as err: await query.reply("**Query: **\n`" f"{expression}" ...
106
107
359
23
83
TAMILVIP007/javes-3.0
userbot/modules/script.py
Python
gethash
gethash
304
332
304
305
84a726b8bf8300bd48b84f61179a0ee2d5fcb9e1
bigcode/the-stack
train
a9abcd0bffa656fcf75f3dd5
train
function
def decreasing_subroutine( bins: Bins, binsize: float, sorted_items: List[any], valueof: Callable[[Any], float] ): """ Run a simple bin-covering algorithm: it orders the items in descending order, and puts them into a bin until it is filled. This is a subroutine that accepts an already-...
def decreasing_subroutine( bins: Bins, binsize: float, sorted_items: List[any], valueof: Callable[[Any], float] ):
""" Run a simple bin-covering algorithm: it orders the items in descending order, and puts them into a bin until it is filled. This is a subroutine that accepts an already-initialized Bins structure, and already-sorted items list. """ for item in sorted_items: bins.add_item_to_bin(item, ...
of=valueof) bins.remove_bins(1) # the last bin is not full - remove it return bins def decreasing_subroutine( bins: Bins, binsize: float, sorted_items: List[any], valueof: Callable[[Any], float] ):
64
64
144
37
26
erelsgl/prtpy
prtpy/packing/greedy_covering.py
Python
decreasing_subroutine
decreasing_subroutine
52
66
52
57
50b1e3e0617a62f450de82830a5012c989fe0e5f
bigcode/the-stack
train
e261d42298d4ee0a3a24bd16
train
function
def decreasing( bins: Bins, binsize: float, items: List[any], valueof: Callable[[Any], float] = lambda x: x, ): """ Run a simple bin-covering algorithm: it orders the items in descending order, and puts them into a bin until it is filled. >>> from prtpy.bins import BinsKeepingContents, ...
def decreasing( bins: Bins, binsize: float, items: List[any], valueof: Callable[[Any], float] = lambda x: x, ):
""" Run a simple bin-covering algorithm: it orders the items in descending order, and puts them into a bin until it is filled. >>> from prtpy.bins import BinsKeepingContents, BinsKeepingSums >>> decreasing(BinsKeepingContents(), 10, [11,12,13]).bins # large items [[13], [12], [11]] >>> dec...
""" A simple greedy bin-covering algorithm AUTHOR: Erel Segal-Halevi SINCE: 2021-04 """ from prtpy import outputtypes as out, Bins from typing import Callable, List, Any def decreasing( bins: Bins, binsize: float, items: List[any], valueof: Callable[[Any], float] = lambda x: x, ):
90
196
655
39
50
erelsgl/prtpy
prtpy/packing/greedy_covering.py
Python
decreasing
decreasing
17
49
17
22
0b7745ce71c6deb99c431e5376db4f9fc42ba9ff
bigcode/the-stack
train
9c2270390dfbca21e6100f7d
train
class
@pulumi.input_type class UserPasswordArgs: def __init__(__self__, *, pgp_key: pulumi.Input[str], user: pulumi.Input[str], host: Optional[pulumi.Input[str]] = None): """ The set of arguments for constructing a UserPassword resource. :param pu...
@pulumi.input_type class UserPasswordArgs:
def __init__(__self__, *, pgp_key: pulumi.Input[str], user: pulumi.Input[str], host: Optional[pulumi.Input[str]] = None): """ The set of arguments for constructing a UserPassword resource. :param pulumi.Input[str] pgp_key: Either a base-64 e...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import ...
103
138
461
11
92
joesonw/pulumi-mysql
sdk/python/pulumi_mysql/user_password.py
Python
UserPasswordArgs
UserPasswordArgs
13
64
13
14
4bb50125123f027bfb897da6023bb9743bf9c924
bigcode/the-stack
train
5a47d10c3ff52d4c1f41c826
train
class
class UserPassword(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, host: Optional[pulumi.Input[str]] = None, pgp_key: Optional[pulumi.Input[str]] = None, ...
class UserPassword(pulumi.CustomResource): @overload
def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, host: Optional[pulumi.Input[str]] = None, pgp_key: Optional[pulumi.Input[str]] = None, user: Optional[pulumi.Input[str]] = None, ...
return pulumi.get(self, "key_fingerprint") @key_fingerprint.setter def key_fingerprint(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "key_fingerprint", value) @property @pulumi.getter(name="pgpKey") def pgp_key(self) -> Optional[pulumi.Input[str]]: """ ...
256
256
1,628
14
242
joesonw/pulumi-mysql
sdk/python/pulumi_mysql/user_password.py
Python
UserPassword
UserPassword
155
314
155
156
46d2667a151cee1280e2d5b56462ed4e14f8cee7
bigcode/the-stack
train
7ce27a7e8d2813e28516e9f0
train
class
@pulumi.input_type class _UserPasswordState: def __init__(__self__, *, encrypted_password: Optional[pulumi.Input[str]] = None, host: Optional[pulumi.Input[str]] = None, key_fingerprint: Optional[pulumi.Input[str]] = None, pgp_key: Optional[pulumi.I...
@pulumi.input_type class _UserPasswordState:
def __init__(__self__, *, encrypted_password: Optional[pulumi.Input[str]] = None, host: Optional[pulumi.Input[str]] = None, key_fingerprint: Optional[pulumi.Input[str]] = None, pgp_key: Optional[pulumi.Input[str]] = None, user: Opt...
encoded PGP public key, or a keybase username in the form `keybase:some_person_that_exists`. """ return pulumi.get(self, "pgp_key") @pgp_key.setter def pgp_key(self, value: pulumi.Input[str]): pulumi.set(self, "pgp_key", value) @property @pulumi.getter def user(self) -> pu...
240
240
803
12
228
joesonw/pulumi-mysql
sdk/python/pulumi_mysql/user_password.py
Python
_UserPasswordState
_UserPasswordState
67
152
67
68
4583aa9755b0ea8761fb33ff02bf5957ede4fd72
bigcode/the-stack
train
162652dbaa1efdc6fae3d8e6
train
function
def list_to_str(lst): string = "" i = 1 for l in lst: string = string + str(l) if i < len(lst): string = string + ", " i = i + 1 return string
def list_to_str(lst):
string = "" i = 1 for l in lst: string = string + str(l) if i < len(lst): string = string + ", " i = i + 1 return string
VIATIONS = [('Proceedings', 'Proc.'), ('Symposium', 'Symp.'), ('International', 'Int\'l'), ('Journal', 'J.'), ('Distributed', 'Distr.')] FUELLWOERTER = ['on', 'of', 'the'] def list_to_str(lst):
64
64
56
6
58
christopherosthues/python-bibtexchecker
bibtexchecker/bibtexchecker.py
Python
list_to_str
list_to_str
66
74
66
66
eacb197ac86ad5fcd1ab536fc72f07bbd775cb58
bigcode/the-stack
train
00e3fd10ec4cf05d3371ebe7
train
class
class BibtexChecker(object): def __init__(self, mute=False, errors=False, check_all=True, check_fields=True, check_abbrs=True, check_keys=True, check_names=True, check_editors=True): self.mute = mute self.errors = errors self.check_all = check_all if check_all: ...
class BibtexChecker(object):
def __init__(self, mute=False, errors=False, check_all=True, check_fields=True, check_abbrs=True, check_keys=True, check_names=True, check_editors=True): self.mute = mute self.errors = errors self.check_all = check_all if check_all: self.check_keys = True...
'year', 'type'], ['author', 'title', 'school', 'year', 'month', 'type']] FIELDS[TECHREPORT] = [['author', 'title', 'institution', 'year', 'month', 'type', 'number']] ABBREVIATE = dict() ABBREVIATE[ARTICLE] = ['journal'] ABBREVIATE[INPROCEEDINGS] = ['booktitle'] ABBREVIATE[BOOK] = list() ABBREVIAT...
256
256
887
6
249
christopherosthues/python-bibtexchecker
bibtexchecker/bibtexchecker.py
Python
BibtexChecker
BibtexChecker
77
177
77
77
c846c5b552673b8e9df06435390faaebf9750e75
bigcode/the-stack
train
2fd957c7f62f56e71bc48446
train
function
def test_analyze_post(empty_post): empty_post.text = """ Protecting accounts from credential stuffing attacks remains burdensome due to an asymmetry of knowledge: attackers have wide-scale access to billions of stolen usernames and passwords, while users and identity providers remain in the dark as ...
def test_analyze_post(empty_post):
empty_post.text = """ Protecting accounts from credential stuffing attacks remains burdensome due to an asymmetry of knowledge: attackers have wide-scale access to billions of stolen usernames and passwords, while users and identity providers remain in the dark as to which accounts require remediati...
(): """Case when there is less than 3 words and rank algo can't be used. """ text = "search page" doc = make_spacy_doc(text, lang=SPACY_MODEL) terms = nlp.extract_key_terms(doc, num_terms=5) assert 'search' == terms[0][0] assert 0.5 == terms[0][1] assert 'page' == terms[1][0] assert ...
116
116
388
8
108
ebursztein/SiteFab
tests/test_nlp.py
Python
test_analyze_post
test_analyze_post
73
101
73
73
d40143939880325925e34031488075cd986e52f7
bigcode/the-stack
train
d23724892c8454346e1fb40b
train
function
def test_two_term_behavhior(): """Case when there is less than 3 words and rank algo can't be used. """ text = "search page" doc = make_spacy_doc(text, lang=SPACY_MODEL) terms = nlp.extract_key_terms(doc, num_terms=5) assert 'search' == terms[0][0] assert 0.5 == terms[0][1] assert 'page'...
def test_two_term_behavhior():
"""Case when there is less than 3 words and rank algo can't be used. """ text = "search page" doc = make_spacy_doc(text, lang=SPACY_MODEL) terms = nlp.extract_key_terms(doc, num_terms=5) assert 'search' == terms[0][0] assert 0.5 == terms[0][1] assert 'page' == terms[1][0] assert 0.5 ...
doc = make_spacy_doc(text, lang=SPACY_MODEL) terms = nlp.extract_key_terms(doc, num_terms=5) assert terms[0][0] == 'elie' assert terms[0][1] == 1.0 def test_two_term_behavhior():
64
64
116
9
54
ebursztein/SiteFab
tests/test_nlp.py
Python
test_two_term_behavhior
test_two_term_behavhior
61
70
61
61
9d119d0c7855d4e95ca1a7abdcd90d093fae688d
bigcode/the-stack
train
dd5e2a61f1b71032ba26279c
train
function
def test_empty_stats(): text = "" doc = make_spacy_doc(text, lang=SPACY_MODEL) stats = nlp.compute_stats(doc) assert stats.counts.sentences == 0 assert stats.counts.words == 0 assert stats.readibility == None
def test_empty_stats():
text = "" doc = make_spacy_doc(text, lang=SPACY_MODEL) stats = nlp.compute_stats(doc) assert stats.counts.sentences == 0 assert stats.counts.words == 0 assert stats.readibility == None
"the quick fox and the cat. The turtle and the rabbit." doc = make_spacy_doc(text, lang=SPACY_MODEL) stats = nlp.compute_stats(doc) assert stats.counts.sentences == 2 assert stats.counts.words == 11 def test_empty_stats():
64
64
62
5
58
ebursztein/SiteFab
tests/test_nlp.py
Python
test_empty_stats
test_empty_stats
26
32
26
26
5bb88fcbb31945bca769d15a7ede4c2219714f55
bigcode/the-stack
train
2f7f8a2b2f112f14be9c47bc
train
function
def test_text_cleanup(): snips = [ """@test@""", " test ", " TeSt ", "-#, test, " ] for snip in snips: assert nlp.text_cleanup(snip) == 'test'
def test_text_cleanup():
snips = [ """@test@""", " test ", " TeSt ", "-#, test, " ] for snip in snips: assert nlp.text_cleanup(snip) == 'test'
from sitefab import nlp from sitefab.nlp import SPACY_MODEL from textacy import make_spacy_doc def test_text_cleanup():
31
64
56
5
25
ebursztein/SiteFab
tests/test_nlp.py
Python
test_text_cleanup
test_text_cleanup
6
15
6
6
82dd9f349acc93cac3a355b03d0afb664f2866f0
bigcode/the-stack
train
3aac39e15da38f40771f65e0
train
function
def test_single_term(): text = "elie" doc = make_spacy_doc(text, lang=SPACY_MODEL) terms = nlp.extract_key_terms(doc, num_terms=5) assert terms[0][0] == 'elie' assert terms[0][1] == 1.0
def test_single_term():
text = "elie" doc = make_spacy_doc(text, lang=SPACY_MODEL) terms = nlp.extract_key_terms(doc, num_terms=5) assert terms[0][0] == 'elie' assert terms[0][1] == 1.0
turtle' in terms assert 'rabbit' in terms def test_empty_terms(): text = "" doc = make_spacy_doc(text, lang=SPACY_MODEL) terms = nlp.extract_key_terms(doc, num_terms=5) assert terms == [] def test_single_term():
63
64
67
5
58
ebursztein/SiteFab
tests/test_nlp.py
Python
test_single_term
test_single_term
53
58
53
53
4238c9297bdb7ed6614ca3b4593e4a0082adcabc
bigcode/the-stack
train
f0c4e6b03f062963b6aec154
train
function
def test_terms(): text = "the quick fox and the cat. The turtle and the rabbit." doc = make_spacy_doc(text, lang=SPACY_MODEL) terms = nlp.extract_key_terms(doc, num_terms=5) terms = [t[0] for t in terms] # remove scores assert 'fox' in terms assert 'cat' in terms assert 'turtle' in terms ...
def test_terms():
text = "the quick fox and the cat. The turtle and the rabbit." doc = make_spacy_doc(text, lang=SPACY_MODEL) terms = nlp.extract_key_terms(doc, num_terms=5) terms = [t[0] for t in terms] # remove scores assert 'fox' in terms assert 'cat' in terms assert 'turtle' in terms assert 'rabbit' ...
_empty_stats(): text = "" doc = make_spacy_doc(text, lang=SPACY_MODEL) stats = nlp.compute_stats(doc) assert stats.counts.sentences == 0 assert stats.counts.words == 0 assert stats.readibility == None def test_terms():
64
64
102
4
59
ebursztein/SiteFab
tests/test_nlp.py
Python
test_terms
test_terms
35
43
35
35
ef288171f48cc31c1eb461d421e6ce53e2564efe
bigcode/the-stack
train
0c0e4ee5b73b8ef156c045d1
train
function
def test_empty_terms(): text = "" doc = make_spacy_doc(text, lang=SPACY_MODEL) terms = nlp.extract_key_terms(doc, num_terms=5) assert terms == []
def test_empty_terms():
text = "" doc = make_spacy_doc(text, lang=SPACY_MODEL) terms = nlp.extract_key_terms(doc, num_terms=5) assert terms == []
_terms(doc, num_terms=5) terms = [t[0] for t in terms] # remove scores assert 'fox' in terms assert 'cat' in terms assert 'turtle' in terms assert 'rabbit' in terms def test_empty_terms():
64
64
44
5
58
ebursztein/SiteFab
tests/test_nlp.py
Python
test_empty_terms
test_empty_terms
46
50
46
46
e454df32d2813d82589656ab9b87573ab2998def
bigcode/the-stack
train
5521208b3ebf7f3588ec1f15
train
function
def test_stats(): text = "the quick fox and the cat. The turtle and the rabbit." doc = make_spacy_doc(text, lang=SPACY_MODEL) stats = nlp.compute_stats(doc) assert stats.counts.sentences == 2 assert stats.counts.words == 11
def test_stats():
text = "the quick fox and the cat. The turtle and the rabbit." doc = make_spacy_doc(text, lang=SPACY_MODEL) stats = nlp.compute_stats(doc) assert stats.counts.sentences == 2 assert stats.counts.words == 11
_spacy_doc def test_text_cleanup(): snips = [ """@test@""", " test ", " TeSt ", "-#, test, " ] for snip in snips: assert nlp.text_cleanup(snip) == 'test' def test_stats():
64
64
66
4
60
ebursztein/SiteFab
tests/test_nlp.py
Python
test_stats
test_stats
18
23
18
18
8da0ab8f7c8a6de667fa8f6a1430b5d11c695477
bigcode/the-stack
train
f02bcb628d64d120c3e45307
train
function
def sendemail(subject, msg, html, *to): """Send an email.""" msg = EmailMultiAlternatives(subject, msg, '', to) msg.attach_alternative(html, "text/html") msg.send()
def sendemail(subject, msg, html, *to):
"""Send an email.""" msg = EmailMultiAlternatives(subject, msg, '', to) msg.attach_alternative(html, "text/html") msg.send()
# coding: utf-8 """Model module.""" from __future__ import unicode_literals from django.core.mail import EmailMultiAlternatives def sendemail(subject, msg, html, *to):
41
64
47
12
28
b3j0f/debate
django/app/utils.py
Python
sendemail
sendemail
8
12
8
8
cca84e18cd343d6a2ebdedd6737ba33987096f9e
bigcode/the-stack
train
cc04e695c9d9af4f037c3643
train
class
class Train: def __init__(self): self.data='./data' self.batch_size= 96 self.learning_rate= 0.025 self.momentum= 0.9 self.weight_decay = 3e-4 self.load_weights = 0 self.report_freq = 500 self.gpu = 0 self.epochs = 50 self.init_channels = 36 self.layers = 20 self.auxil...
class Train:
def __init__(self): self.data='./data' self.batch_size= 96 self.learning_rate= 0.025 self.momentum= 0.9 self.weight_decay = 3e-4 self.load_weights = 0 self.report_freq = 500 self.gpu = 0 self.epochs = 50 self.init_channels = 36 self.layers = 20 self.auxiliary = True ...
import os import sys sys.path.insert(0, os.getcwd()) import time import glob import numpy as np import random import torch import darts.cnn.utils as utils import logging import torch.nn as nn import darts.cnn.genotypes import torch.utils import torchvision.datasets as dset import torch.backends.cudnn as cudnn from coll...
99
256
2,062
3
95
fusiming3/arch2vec
darts/cnn/train_search.py
Python
Train
Train
20
244
20
21
5c1b01dc1b6215b18fa1ebb4237b092ced078edf
bigcode/the-stack
train
325e281417a20f827bdae19d
train
function
def reverse_func(apps, schema_editor): Calibration_Update = apps.get_model("range_calibration", "Calibration_Update") RawDataModel = apps.get_model("range_calibration", "RawDataModel") AdjustedDataModel = apps.get_model("range_calibration", "AdjustedDataModel") HeightDifferenceModel = apps.get_model...
def reverse_func(apps, schema_editor):
Calibration_Update = apps.get_model("range_calibration", "Calibration_Update") RawDataModel = apps.get_model("range_calibration", "RawDataModel") AdjustedDataModel = apps.get_model("range_calibration", "AdjustedDataModel") HeightDifferenceModel = apps.get_model("range_calibration", "HeightDifferenceM...
created = RangeParameters.objects.update_or_create(pin=p, **{m_text: round(mdiff2,5)}) # update calibration table for update_index in staff[:,0]: Calibration_Update.objects.filter(update_index=update_index).update(update_table=True) def reverse_func(apps, schema_editor):
64
64
141
9
55
Landgate/Staff-Calibration
range_calibration/migrations/0002_auto_20201113_1350.py
Python
reverse_func
reverse_func
396
407
396
396
df78bfc96a18044246ca589f19038458213a4423
bigcode/the-stack
train
48d40876579a1f06a48853a9
train
function
def upload_range_data(apps, schema_editor): Staff = apps.get_model("staffs", "Staff") DigitalLevel = apps.get_model("staffs", "DigitalLevel") Calibration_Update = apps.get_model("range_calibration", "Calibration_Update") RawDataModel = apps.get_model("range_calibration", "RawDataModel") Adj...
def upload_range_data(apps, schema_editor):
Staff = apps.get_model("staffs", "Staff") DigitalLevel = apps.get_model("staffs", "DigitalLevel") Calibration_Update = apps.get_model("range_calibration", "Calibration_Update") RawDataModel = apps.get_model("range_calibration", "RawDataModel") AdjustedDataModel = apps.get_model("range_calibrat...
np.sqrt(1./np.sqrt(np.diag(P).astype(float))**2) stdev_residual = np.sqrt(1./np.sqrt(np.diag(P).astype(float))**2 - 1./sqrt(np.matmul(np.transpose(A), np.matmul(P, A)))**2) uncertainty = (sqrt(1/np.matmul(np.transpose(A), np.matmul(P, A)))*1000*1.96) std_residual = np...
255
256
2,049
11
244
Landgate/Staff-Calibration
range_calibration/migrations/0002_auto_20201113_1350.py
Python
upload_range_data
upload_range_data
212
394
212
212
9cf4a5473f765a0eaf2ff0dbab1433cf07482dcf
bigcode/the-stack
train
2698463b93cc6a6dbaa8336a
train
function
def rawdata_to_table(dataset, T1, T2, staff_atrs): # cf, alpha, T_o): dCorrectionFactor = staff_atrs['dCorrectionFactor'] dThermalCoefficient = staff_atrs['dThermalCoefficient'] dStdTemperature = staff_atrs['dStdTemperature'] rawReportTable = [] for key, value in dataset.items(): if ...
def rawdata_to_table(dataset, T1, T2, staff_atrs): # cf, alpha, T_o):
dCorrectionFactor = staff_atrs['dCorrectionFactor'] dThermalCoefficient = staff_atrs['dThermalCoefficient'] dStdTemperature = staff_atrs['dStdTemperature'] rawReportTable = [] for key, value in dataset.items(): if key.startswith("Set1"): obs_set = 1 #print(va...
5f}'.format(obsi), '{:.5f}'.format(obsj), '{:.6f}'.format(dStdDeviation), '{:.5f}'.format(dMeasuredLength), '{:.5f}'.format(cMeasuredLength)]) return data_table # Correct staff readings def rawdata_to_table(dataset, T1, T2, staff_atrs): # cf, alpha, T_o):
83
83
277
25
57
Landgate/Staff-Calibration
range_calibration/migrations/0002_auto_20201113_1350.py
Python
rawdata_to_table
rawdata_to_table
142
159
142
142
706263e254192f8858270fd3c13e2e88f69d35ad
bigcode/the-stack
train
8c439bb9a341e4af170a8675
train
function
def Process_File(file_path): with open(file_path, 'r') as f: fileType = None for line in f: if "BFOD" in line: fileType = "BFOD" elif "Level Type" in line: fileType = "DNA03" break if fileType == "BFOD": r...
def Process_File(file_path):
with open(file_path, 'r') as f: fileType = None for line in f: if "BFOD" in line: fileType = "BFOD" elif "Level Type" in line: fileType = "DNA03" break if fileType == "BFOD": return ImportBFOD_v18(file_path...
float(Stdev)]) staff_data = pd.DataFrame(staff_data, columns=['PIN','READING','COUNT','STD_DEVIATION']) new_staff_reading.update({'Set'+str(j):staff_data}) # return data return new_staff_reading def Process_File(file_path):
64
64
103
6
57
Landgate/Staff-Calibration
range_calibration/migrations/0002_auto_20201113_1350.py
Python
Process_File
Process_File
108
120
108
108
ff37eb077b12ff69162e21ae6d16fac21c6c5b06
bigcode/the-stack
train
b4fb77855b28b190ebe2cca4
train
class
class Migration(migrations.Migration): dependencies = [ ('range_calibration', '0001_initial'), ('staffs', '0002_auto_20201112_1023'), ] operations = [ migrations.RunPython(upload_range_data, reverse_func), ]
class Migration(migrations.Migration):
dependencies = [ ('range_calibration', '0001_initial'), ('staffs', '0002_auto_20201112_1023'), ] operations = [ migrations.RunPython(upload_range_data, reverse_func), ]
apps.get_model("range_calibration", "RangeParameters") Calibration_Update.objects.all().delete() RawDataModel.objects.all().delete() AdjustedDataModel.objects.all().delete() HeightDifferenceModel.objects.all().delete() RangeParameters.objects.all().delete() class Migration(migrations.Migrat...
64
64
60
7
57
Landgate/Staff-Calibration
range_calibration/migrations/0002_auto_20201113_1350.py
Python
Migration
Migration
410
419
410
411
b73e559a3bd8236a37574b978898e2c5f043a221
bigcode/the-stack
train
a60870581933c8ac3cdac0cf
train
function
def adjustment(dataset, uniquelist): from math import sqrt dataset = np.array(dataset) # output output_adj = [] output_hdiff = [] for i in range(len(uniquelist)): x = uniquelist[i] if x in dataset[:,1]: dato = dataset[dataset[:,1]==x].tolist() if...
def adjustment(dataset, uniquelist):
from math import sqrt dataset = np.array(dataset) # output output_adj = [] output_hdiff = [] for i in range(len(uniquelist)): x = uniquelist[i] if x in dataset[:,1]: dato = dataset[dataset[:,1]==x].tolist() if len(dato) == 1: inte...
"): obs_set = 2 #print(value) set2 = calculate_length(value.values, dCorrectionFactor, dThermalCoefficient, dStdTemperature, T2, obs_set) # rawReportTable = pd.DataFrame(rawReportTable, columns=['SET','PIN','TEMPERATURE','FROM','TO', 'STD_DEVIATION', 'MEASURED', 'CORRECTED']...
198
198
662
7
190
Landgate/Staff-Calibration
range_calibration/migrations/0002_auto_20201113_1350.py
Python
adjustment
adjustment
172
210
172
172
60bb713ff7ed7ca99f39faaf84cf86b4be9b484a
bigcode/the-stack
train
62425a9ad04271a9b2f4e854
train
function
def ImportBFOD_v18(file_path): with open(file_path, 'r', newline='') as f: # # Start reading the level run and store them in blocks readerLines = f.readlines()# .decode('UTF-8') Blocks = []; block = [] for line in readerLines:# f: line = line.strip() col = ...
def ImportBFOD_v18(file_path):
with open(file_path, 'r', newline='') as f: # # Start reading the level run and store them in blocks readerLines = f.readlines()# .decode('UTF-8') Blocks = []; block = [] for line in readerLines:# f: line = line.strip() col = line.split('|')[1:] ...
# Generated by Django 3.1 on 2020-11-13 05:50 from django.db import migrations import os import pandas as pd import numpy as np import csv from datetime import datetime from django.db import IntegrityError, transaction def IsNumber(value): "Checks if string is a number" try: float(value...
104
134
447
9
95
Landgate/Staff-Calibration
range_calibration/migrations/0002_auto_20201113_1350.py
Python
ImportBFOD_v18
ImportBFOD_v18
21
62
21
21
cb4f2e695c5ca7ea0cc90f415e732854f485f3ff
bigcode/the-stack
train
3b031d3bf502126919b0fcc0
train
function
def ImportDNA(file_path): with open(file_path, 'r') as f: # Start reading the level run and store them in blocks readerLines = f.readlines()# .decode('UTF-8') Blocks = []; block = [] for line in readerLines: line = line.strip() col = line.split('|')[1:...
def ImportDNA(file_path):
with open(file_path, 'r') as f: # Start reading the level run and store them in blocks readerLines = f.readlines()# .decode('UTF-8') Blocks = []; block = [] for line in readerLines: line = line.strip() col = line.split('|')[1:] # Start leve...
dev = r[7]; elif IsNumber(r[2]): Pin = r[8]; Readings = r[2]; NoOfMeasurement = r[6]; Stdev = r[7]; staff_data.append([Pin, float(Readings), NoOfMeasurement, float(Stdev)]) #print(i) staff_data = pd.DataF...
131
131
437
6
124
Landgate/Staff-Calibration
range_calibration/migrations/0002_auto_20201113_1350.py
Python
ImportDNA
ImportDNA
64
106
64
64
fde5c34bfd04b3592665200c71354fcf28024ddc
bigcode/the-stack
train
09f00e59eae6a5d5ff9dde74
train
function
def unique_list(dataset): ulist = [] for d in dataset: if d[1] in ulist: pass else: ulist.append(d[1]) return ulist
def unique_list(dataset):
ulist = [] for d in dataset: if d[1] in ulist: pass else: ulist.append(d[1]) return ulist
rawReportTable = {'headers': ['SET','PIN','TEMPERATURE','FROM','TO', 'STD_DEVIATION', 'MEASURED', 'CORRECTED'], 'data': set1+set2} return rawReportTable# .to_dict() # Unique list def unique_list(dataset):
64
64
45
5
58
Landgate/Staff-Calibration
range_calibration/migrations/0002_auto_20201113_1350.py
Python
unique_list
unique_list
162
169
162
162
00ad0e76120565016136dc5c88d26f2cc2da4c6b
bigcode/the-stack
train
7d8a3c9f7b8d050320150896
train
function
def calculate_length(data, cf, alpha, t_0, t, oset): from math import sqrt data_table = [] # if data is array: for i in range(len(data)-1): pini, obsi, nmeasi, stdi= data[i] pinj, obsj, nmeasj, stdj = data[i+1] if stdi == 0: stdi = 10**-5 if stdj == ...
def calculate_length(data, cf, alpha, t_0, t, oset):
from math import sqrt data_table = [] # if data is array: for i in range(len(data)-1): pini, obsi, nmeasi, stdi= data[i] pinj, obsj, nmeasj, stdj = data[i+1] if stdi == 0: stdi = 10**-5 if stdj == 0: stdj = 10**-5 dMeasuredLength...
BFOD" elif "Level Type" in line: fileType = "DNA03" break if fileType == "BFOD": return ImportBFOD_v18(file_path) elif fileType == "DNA03": return ImportDNA(file_path) def calculate_length(data, cf, alpha, t_0, t, oset):
76
77
259
18
58
Landgate/Staff-Calibration
range_calibration/migrations/0002_auto_20201113_1350.py
Python
calculate_length
calculate_length
122
140
122
122
ef1309a13b2950ca3ac738be1b2b04c0949c9ec0
bigcode/the-stack
train
9892f916d709849e6f060465
train
function
def IsNumber(value): "Checks if string is a number" try: float(value) check = True except: check = False return(check)
def IsNumber(value):
"Checks if string is a number" try: float(value) check = True except: check = False return(check)
# Generated by Django 3.1 on 2020-11-13 05:50 from django.db import migrations import os import pandas as pd import numpy as np import csv from datetime import datetime from django.db import IntegrityError, transaction def IsNumber(value):
62
64
38
5
56
Landgate/Staff-Calibration
range_calibration/migrations/0002_auto_20201113_1350.py
Python
IsNumber
IsNumber
12
19
12
12
fe36324e3ab03a5b9b8a0d60c5f520bb26083638
bigcode/the-stack
train
a8925b6ea5ddbacfc9319590
train
class
class NDArrayExtension(Extension): name = 'ndarray' def __init__(self): if 'numpy' in sys.modules: import numpy as np self.cls = np.ndarray def match(self, s, v): # e.g. for nd arrays in JS return (hasattr(v, 'shape') and hasattr(v, 'dtype') and ...
class NDArrayExtension(Extension):
name = 'ndarray' def __init__(self): if 'numpy' in sys.modules: import numpy as np self.cls = np.ndarray def match(self, s, v): # e.g. for nd arrays in JS return (hasattr(v, 'shape') and hasattr(v, 'dtype') and hasattr(v, 'tobytes'))...
Error() class ComplexExtension(Extension): name = 'c' cls = complex def encode(self, s, v): return (v.real, v.imag) def decode(self, s, v): return complex(v[0], v[1]) class NDArrayExtension(Extension):
64
64
176
7
57
rajjamdar05/flexx
flexx/app/bsdf_lite.py
Python
NDArrayExtension
NDArrayExtension
497
523
497
498
61d8c75c9882114c871f41688ab460106cc1e19e
bigcode/the-stack
train
6e98094f063ef85de0c47fd7
train
class
class Extension(object): """ Base class to implement BSDF extensions for special data types. Extension classes are provided to the BSDF serializer, which instantiates the class. That way, the extension can be somewhat dynamic: e.g. the NDArrayExtension exposes the ndarray class only when numpy is i...
class Extension(object):
""" Base class to implement BSDF extensions for special data types. Extension classes are provided to the BSDF serializer, which instantiates the class. That way, the extension can be somewhat dynamic: e.g. the NDArrayExtension exposes the ndarray class only when numpy is imported. A extension...
should be < ours t = ('BSDF warning: reading file with higher minor version (%s) ' 'than the implementation (%s).') logger.warning(t % (file_version, __version__)) return self._decode(f) # %% Standard extensions # Defining extensions as a dict would be more compact ...
100
100
335
4
96
rajjamdar05/flexx
flexx/app/bsdf_lite.py
Python
Extension
Extension
443
482
443
443
9598316093162de269abed66c6f29482c620d1ae
bigcode/the-stack
train
599c3c760d2ae380a08a1c26
train
function
def lendecode(f): """ Decode an unsigned integer from a file. """ n = strunpack('<B', f.read(1))[0] if n == 253: n = strunpack('<Q', f.read(8))[0] # noqa return n
def lendecode(f):
""" Decode an unsigned integer from a file. """ n = strunpack('<B', f.read(1))[0] if n == 253: n = strunpack('<Q', f.read(8))[0] # noqa return n
9 bytes for collections with over 250 elements is marginal anyway. if x <= 250: return spack('<B', x) else: return spack('<BQ', 253, x) # Include len decoder for completeness; we've inlined it for performance. def lendecode(f):
64
64
63
5
59
rajjamdar05/flexx
flexx/app/bsdf_lite.py
Python
lendecode
lendecode
52
57
52
52
f39e7340f770cda60dd1c2755b8842c148e8e056
bigcode/the-stack
train
bc59671ed9851eb1c56bfc8c
train
function
def encode_type_id(b, ext_id): """ Encode the type identifier, with or without extension id. """ if ext_id is not None: bb = ext_id.encode('UTF-8') return b.upper() + lencode(len(bb)) + bb # noqa else: return b # noqa
def encode_type_id(b, ext_id):
""" Encode the type identifier, with or without extension id. """ if ext_id is not None: bb = ext_id.encode('UTF-8') return b.upper() + lencode(len(bb)) + bb # noqa else: return b # noqa
an unsigned integer from a file. """ n = strunpack('<B', f.read(1))[0] if n == 253: n = strunpack('<Q', f.read(8))[0] # noqa return n def encode_type_id(b, ext_id):
64
64
70
9
54
rajjamdar05/flexx
flexx/app/bsdf_lite.py
Python
encode_type_id
encode_type_id
60
67
60
60
7d435ba813d8ad2cef06e22583e3677af2307bf5
bigcode/the-stack
train
68eebd62e8120e2dabf38175
train
class
class BsdfLiteSerializer(object): """ Instances of this class represent a BSDF encoder/decoder. This is a lite variant of the Python BSDF serializer. It does not support lazy loading or streaming, but is otherwise fully functional, including support for custom extensions. It acts as a placeholder ...
class BsdfLiteSerializer(object):
""" Instances of this class represent a BSDF encoder/decoder. This is a lite variant of the Python BSDF serializer. It does not support lazy loading or streaming, but is otherwise fully functional, including support for custom extensions. It acts as a placeholder for a set of extensions and encodi...
= struct.pack strunpack = struct.unpack def lencode(x): """ Encode an unsigned integer into a variable sized blob of bytes. """ # We could support 16 bit and 32 bit as well, but the gain is low, since # 9 bytes for collections with over 250 elements is marginal anyway. if x <= 250: return...
256
256
3,436
7
248
rajjamdar05/flexx
flexx/app/bsdf_lite.py
Python
BsdfLiteSerializer
BsdfLiteSerializer
70
434
70
70
9669058262ba8030d1e27ecbdae53a289d58ac20
bigcode/the-stack
train
853b943082ad6f962716b10f
train
class
class ComplexExtension(Extension): name = 'c' cls = complex def encode(self, s, v): return (v.real, v.imag) def decode(self, s, v): return complex(v[0], v[1])
class ComplexExtension(Extension):
name = 'c' cls = complex def encode(self, s, v): return (v.real, v.imag) def decode(self, s, v): return complex(v[0], v[1])
%s>' % (self.name, hex(id(self))) def match(self, s, v): return isinstance(v, self.cls) def encode(self, s, v): raise NotImplementedError() def decode(self, s, v): raise NotImplementedError() class ComplexExtension(Extension):
64
64
55
6
58
rajjamdar05/flexx
flexx/app/bsdf_lite.py
Python
ComplexExtension
ComplexExtension
485
494
485
486
260bf34145f81b425939c5a4506d5b5baa62b891
bigcode/the-stack
train
227d7340a347214f55c775b1
train
function
def lencode(x): """ Encode an unsigned integer into a variable sized blob of bytes. """ # We could support 16 bit and 32 bit as well, but the gain is low, since # 9 bytes for collections with over 250 elements is marginal anyway. if x <= 250: return spack('<B', x) else: return sp...
def lencode(x):
""" Encode an unsigned integer into a variable sized blob of bytes. """ # We could support 16 bit and 32 bit as well, but the gain is low, since # 9 bytes for collections with over 250 elements is marginal anyway. if x <= 250: return spack('<B', x) else: return spack('<BQ', 253, ...
= logging.getLogger(__name__) VERSION = 2, 2, 1 __version__ = '.'.join(str(i) for i in VERSION) # %% The encoder and decoder implementation # Shorthands spack = struct.pack strunpack = struct.unpack def lencode(x):
64
64
91
5
58
rajjamdar05/flexx
flexx/app/bsdf_lite.py
Python
lencode
lencode
40
48
40
40
99df7de9f3a142fae57db963eeb3de12a77c30f5
bigcode/the-stack
train
e50f5016160e3b1930701299
train
class
@unittest.skipUnless( settings.DATABASES['default']['ENGINE'] in ('django.db.backends.mysql'), "only mysql", ) class Test(TestCase): def test_command(self): out = StringIO() call_command('dbcleanup', stdout=out, just='analyze') # there might be old tables in the testdb, do not assume...
@unittest.skipUnless( settings.DATABASES['default']['ENGINE'] in ('django.db.backends.mysql'), "only mysql", ) class Test(TestCase):
def test_command(self): out = StringIO() call_command('dbcleanup', stdout=out, just='analyze') # there might be old tables in the testdb, do not assume empty output... baseline = {x.split(' ')[1] for x in out.getvalue().splitlines()} # cannot create tables inside TransactionT...
get_user_model from django.core.management import call_command from django.urls import reverse from django.conf import settings from dbcleanup import utils, models, admin @unittest.skipUnless( settings.DATABASES['default']['ENGINE'] in ('django.db.backends.mysql'), "only mysql", ) class Test(TestCase):
68
68
229
34
33
surface-security/django-dbcleanup
testapp/tests/test_analyze.py
Python
Test
Test
15
33
15
19
095f7e0e55256813051882f81ba7e970b25dded0
bigcode/the-stack
train
517308ed98f92d8fcff46921
train
class
class PointsOfCorrespondence(tfds.core.GeneratorBasedBuilder): """Points of Correspondence Dataset.""" VERSION = tfds.core.Version("3.0.0") def _info(self): return tfds.core.DatasetInfo( builder=self, description=_DESCRIPTION, features=tfds.features.FeaturesDict({ _FULL_A...
class PointsOfCorrespondence(tfds.core.GeneratorBasedBuilder):
"""Points of Correspondence Dataset.""" VERSION = tfds.core.Version("3.0.0") def _info(self): return tfds.core.DatasetInfo( builder=self, description=_DESCRIPTION, features=tfds.features.FeaturesDict({ _FULL_ARTICLE: tfds.features.Text(), _FULL_SUMMARY: tfds.f...
Sentence_1_Index" _SENTENCE_2_INDEX = "Sentence_2_Index" _SENTENCE_FUSED_INDEX = "Sentence_Fused_Index" _POCS = "PoCs" _EXAMPLE_ID = "Example_Id" _SENTENCE_1_SELECTION = "Sentence_1_Selection" _SENTENCE_2_SELECTION = "Sentence_2_Selection" _SENTENCE_FUSED_SELECTION = "Sentence_Fused_Selection" _POC_TYPE = "PoC_Type" ...
135
135
452
13
122
loganlebanoff/datasets
tensorflow_datasets/summarization/points_of_correspondence.py
Python
PointsOfCorrespondence
PointsOfCorrespondence
75
128
75
75
2d532f18f928110590c61b03731ba21467e28505
bigcode/the-stack
train
cdc77ee8da5cfd685e578719
train
function
@register(outgoing=True, pattern="^.start$") async def amireallyalive(alive): """ For .start command, check if the bot is running. """ logo = ALIVE_LOGO uptime = await get_readable_time((time.time() - StartTime)) output = (f"`🤖 STATUS: ʙᴏᴛ ɪꜱ ᴀʟɪᴠᴇ ✅`\n" f"`ᴛᴇʟᴇᴛʜᴏɴ ᴠᴇʀꜱɪᴏɴ`: {version.__v...
@register(outgoing=True, pattern="^.start$") async def amireallyalive(alive):
""" For .start command, check if the bot is running. """ logo = ALIVE_LOGO uptime = await get_readable_time((time.time() - StartTime)) output = (f"`🤖 STATUS: ʙᴏᴛ ɪꜱ ᴀʟɪᴠᴇ ✅`\n" f"`ᴛᴇʟᴇᴛʜᴏɴ ᴠᴇʀꜱɪᴏɴ`: {version.__version__} \n" f"`ᴘʏᴛʜᴏɴ ᴠᴇʀꜱɪᴏɴ🐍`: {python_version()} \n" ...
remove("output.txt") return await pip.edit("**Query: **\n`" f"pip3 search {pipmodule}" "`\n**Result: **\n`" f"{pipout}" "`") els...
136
136
455
20
116
HariadyAz/oub-remix
userbot/modules/system_stats.py
Python
amireallyalive
amireallyalive
220
247
220
221
246516809ceba36727a1dbf9dbc0e3076c208e4b
bigcode/the-stack
train
29f04c7283a0ccd13e3fbc35
train
function
@register(outgoing=True, pattern=r"^\.spc") async def psu(event): uname = platform.uname() softw = "**System Information**\n" softw += f"`System : {uname.system}`\n" softw += f"`Release : {uname.release}`\n" softw += f"`Version : {uname.version}`\n" softw += f"`Machine : {uname.machine}`\n"...
@register(outgoing=True, pattern=r"^\.spc") async def psu(event):
uname = platform.uname() softw = "**System Information**\n" softw += f"`System : {uname.system}`\n" softw += f"`Release : {uname.release}`\n" softw += f"`Version : {uname.version}`\n" softw += f"`Machine : {uname.machine}`\n" # Boot Time boot_time_timestamp = psutil.boot_time() ...
up_time += ":".join(time_list) return up_time @register(outgoing=True, pattern="^.sysd$") async def sysdetails(sysd): """ For .sysd command, get system info using neofetch. """ if not sysd.text[0].isalpha() and sysd.text[0] not in ("/", "#", "@", "!"): try: fetch = await asyncrunapp...
200
200
669
20
180
HariadyAz/oub-remix
userbot/modules/system_stats.py
Python
psu
psu
76
123
76
77
0ca45f0ca85e376e1ae1770a143304b6eea83ff0
bigcode/the-stack
train
4a9a2208aa13dab0dacc1913
train
function
def get_size(bytes, suffix="B"): factor = 1024 for unit in ["", "K", "M", "G", "T", "P"]: if bytes < factor: return f"{bytes:.2f}{unit}{suffix}" bytes /= factor
def get_size(bytes, suffix="B"):
factor = 1024 for unit in ["", "K", "M", "G", "T", "P"]: if bytes < factor: return f"{bytes:.2f}{unit}{suffix}" bytes /= factor
f"{str(bw)}\n" help_string += "**Engine Info**\n" help_string += f"`Python {sys.version}`\n" help_string += f"`Telethon {__version__}`" await event.edit(help_string) def get_size(bytes, suffix="B"):
64
64
61
9
55
HariadyAz/oub-remix
userbot/modules/system_stats.py
Python
get_size
get_size
126
131
126
126
b20537fa170bcaa579717a35686b3d71b7498abd
bigcode/the-stack
train
008ee23eb9c00076e2e3f9cb
train
function
@register(outgoing=True, pattern="^.pip(?: |$)(.*)") async def pipcheck(pip): """ For .pip command, do a pip search. """ if not pip.text[0].isalpha() and pip.text[0] not in ("/", "#", "@", "!"): pipmodule = pip.pattern_match.group(1) if pipmodule: await pip.edit("`Searching . . .`") ...
@register(outgoing=True, pattern="^.pip(?: |$)(.*)") async def pipcheck(pip):
""" For .pip command, do a pip search. """ if not pip.text[0].isalpha() and pip.text[0] not in ("/", "#", "@", "!"): pipmodule = pip.pattern_match.group(1) if pipmodule: await pip.edit("`Searching . . .`") pipc = await asyncrunapp( "pip3", ...
revout = str(stdout.decode().strip()) \ + str(stderr.decode().strip()) await event.edit("`Userbot Version: " f"{verout}" "` \n" "`Revision: " f"{revout}" ...
107
107
357
23
84
HariadyAz/oub-remix
userbot/modules/system_stats.py
Python
pipcheck
pipcheck
176
218
176
177
8408d56b749259f85ecea8b0ca87c25788e328e1
bigcode/the-stack
train
41d34ec5cde45d51dbc8d478
train
function
@register(outgoing=True, pattern="^.aliveu") async def amireallyaliveuser(username): """ For .aliveu command, change the username in the .alive command. """ message = username.text output = '.aliveu [new user without brackets] nor can it be empty' if not (message == '.aliveu' or message[7:8] != ' '): ...
@register(outgoing=True, pattern="^.aliveu") async def amireallyaliveuser(username):
""" For .aliveu command, change the username in the .alive command. """ message = username.text output = '.aliveu [new user without brackets] nor can it be empty' if not (message == '.aliveu' or message[7:8] != ' '): newuser = message[8:] global DEFAULTUSER DEFAULTUSER = newuser ...
`The provided logo is invalid." "\nMake sure the link is directed to the logo picture`") else: await alive.edit(output) await asyncio.sleep(25) await alive.delete() @register(outgoing=True, pattern="^.aliveu") async def amireallyaliveuser(username):
64
64
132
21
43
HariadyAz/oub-remix
userbot/modules/system_stats.py
Python
amireallyaliveuser
amireallyaliveuser
249
259
249
250
d41b5b4d975b0d83878ac322b83697e4862710e9
bigcode/the-stack
train
d2274cf6bce6126272fbe101
train
function
@register(outgoing=True, pattern="^.botver$") async def bot_ver(event): """ For .botver command, get the bot version. """ if not event.text[0].isalpha() and event.text[0] not in ("/", "#", "@", "!"): if which("git") is not None: ve...
@register(outgoing=True, pattern="^.botver$") async def bot_ver(event):
""" For .botver command, get the bot version. """ if not event.text[0].isalpha() and event.text[0] not in ("/", "#", "@", "!"): if which("git") is not None: ver = await asyncrunapp( "git", "describe"...
_string) def get_size(bytes, suffix="B"): factor = 1024 for unit in ["", "K", "M", "G", "T", "P"]: if bytes < factor: return f"{bytes:.2f}{unit}{suffix}" bytes /= factor @register(outgoing=True, pattern="^.botver$") async def bot_ver(event):
81
82
276
18
62
HariadyAz/oub-remix
userbot/modules/system_stats.py
Python
bot_ver
bot_ver
134
173
134
135
6fcc418372be5231ff9042e892bd76712a047457
bigcode/the-stack
train
54ce1d373aa2d37913dc5644
train
function
async def get_readable_time(seconds: int) -> str: count = 0 up_time = "" time_list = [] time_suffix_list = ["s", "m", "h", "days"] while count < 4: count += 1 if count < 3: remainder, result = divmod(seconds, 60) else: remainder, result = divmod(secon...
async def get_readable_time(seconds: int) -> str:
count = 0 up_time = "" time_list = [] time_suffix_list = ["s", "m", "h", "days"] while count < 4: count += 1 if count < 3: remainder, result = divmod(seconds, 60) else: remainder, result = divmod(seconds, 24) if seconds == 0 and remainder == 0...
, ALIVE_NAME, BOT_VER, ALIVE_LOGO, bot, StartTime from userbot.events import register # ================= CONSTANT ================= DEFAULTUSER = str(ALIVE_NAME) if ALIVE_NAME else uname().node # ============================================ async def get_readable_time(seconds: int) -> str:
64
64
189
13
50
HariadyAz/oub-remix
userbot/modules/system_stats.py
Python
get_readable_time
get_readable_time
27
52
27
27
8c193623118aa7150fab1301b96837e6047f08c9
bigcode/the-stack
train
33bd4c32b8284612e23425ad
train
function
@register(outgoing=True, pattern="^.resetalive$") async def amireallyalivereset(ureset): """ For .resetalive command, reset the username in the .alive command. """ global DEFAULTUSER DEFAULTUSER = str(ALIVE_NAME) if ALIVE_NAME else uname().node await ureset.edit("`" "Successfully reset user for alive!" ...
@register(outgoing=True, pattern="^.resetalive$") async def amireallyalivereset(ureset):
""" For .resetalive command, reset the username in the .alive command. """ global DEFAULTUSER DEFAULTUSER = str(ALIVE_NAME) if ALIVE_NAME else uname().node await ureset.edit("`" "Successfully reset user for alive!" "`")
global DEFAULTUSER DEFAULTUSER = newuser output = 'Successfully changed user to ' + newuser + '!' await username.edit("`" f"{output}" "`") @register(outgoing=True, pattern="^.resetalive$") async def amireallyalivereset(ureset):
64
64
83
25
39
HariadyAz/oub-remix
userbot/modules/system_stats.py
Python
amireallyalivereset
amireallyalivereset
261
266
261
262
92f1d715b1ff15e3bbbbf40eef08686d02eaea41
bigcode/the-stack
train
ce3dce19c637e239a28baf68
train
function
@register(outgoing=True, pattern="^.sysd$") async def sysdetails(sysd): """ For .sysd command, get system info using neofetch. """ if not sysd.text[0].isalpha() and sysd.text[0] not in ("/", "#", "@", "!"): try: fetch = await asyncrunapp( "neofetch", "--stdout...
@register(outgoing=True, pattern="^.sysd$") async def sysdetails(sysd):
""" For .sysd command, get system info using neofetch. """ if not sysd.text[0].isalpha() and sysd.text[0] not in ("/", "#", "@", "!"): try: fetch = await asyncrunapp( "neofetch", "--stdout", stdout=asyncPIPE, stderr=asyncPIPE, ...
_suffix_list[x] if len(time_list) == 4: up_time += time_list.pop() + ", " time_list.reverse() up_time += ":".join(time_list) return up_time @register(outgoing=True, pattern="^.sysd$") async def sysdetails(sysd):
64
64
166
19
44
HariadyAz/oub-remix
userbot/modules/system_stats.py
Python
sysdetails
sysdetails
56
74
56
57
3b0f6bde0a738dfce1a54f2ce0033c532ef6511d
bigcode/the-stack
train
c310e1e73538ab0c978aca00
train
class
class Application(tornado.web.Application): def __init__(self): handlers = [(r"/?", MainPage), (r"/scribbles/?", Scribble) ] settings = dict(cookie_secret="GENERATE YOUR OWN SECRET MORE SECURE THAN THIS", login_url="/", ...
class Application(tornado.web.Application):
def __init__(self): handlers = [(r"/?", MainPage), (r"/scribbles/?", Scribble) ] settings = dict(cookie_secret="GENERATE YOUR OWN SECRET MORE SECURE THAN THIS", login_url="/", template_path=os.path.join(os.path.d...
from Imports import * # from Processor import Processor # Import all handlers from BaseHandler import BaseHandler from MainPage import MainPage from Scribble import Scribble class Application(tornado.web.Application):
43
64
127
7
35
JeremyRubin/Graffiti-codes
Graffiti-server/App.py
Python
Application
Application
8
22
8
8
3ec5dd01e67f8d4ad74dc2f8a6b3c534cc29854d
bigcode/the-stack
train
db2c708c6d3c8519184ac61a
train
class
class Das(object): site_url = 'https://www.dasdas.jp/' def __init__(self, video_no): self.video_no = video_no = video_no.lower().replace('-', '') self.url = url = 'https://www.dasdas.jp/works/detail/' + video_no + '/' self.session = session = requests.Session() self.headers = h...
class Das(object):
site_url = 'https://www.dasdas.jp/' def __init__(self, video_no): self.video_no = video_no = video_no.lower().replace('-', '') self.url = url = 'https://www.dasdas.jp/works/detail/' + video_no + '/' self.session = session = requests.Session() self.headers = headers = { ...
#!/usr/bin/envpython3 # -*-coding:utf-8-*- import requests from bs4 import BeautifulSoup class Das(object):
29
99
333
4
24
zcy0521/emby-metadata
jav/Das.py
Python
Das
Das
7
41
7
7
c4570d6d15d8140d8c8a4058f784ee5d8099c2ac
bigcode/the-stack
train
878d8d9713e790e45856b297
train
function
def clean_socket_close(sock): """Close a socket connection and logs its closure.""" _LOGGER.info("UPNP responder shutting down.") sock.close()
def clean_socket_close(sock):
"""Close a socket connection and logs its closure.""" _LOGGER.info("UPNP responder shutting down.") sock.close()
_socket.sendto(self.upnp_response, addr) resp_socket.close() def stop(self): """Stop the server.""" # Request for server self._interrupted = True os.write(self._interrupted_write_pipe, bytes([0])) self.join() def clean_socket_close(sock):
64
64
32
6
58
sbidoul/home-assistant
homeassistant/components/emulated_hue/upnp.py
Python
clean_socket_close
clean_socket_close
167
171
167
167
d4417dcc5b3516a8e8d6734c365fa7bb93bcec7a
bigcode/the-stack
train
166160a5c3abb9287d9dba17
train
class
class DescriptionXmlView(HomeAssistantView): """Handles requests for the description.xml file.""" url = '/description.xml' name = 'description:xml' requires_auth = False def __init__(self, config): """Initialize the instance of the view.""" self.config = config @core.callback ...
class DescriptionXmlView(HomeAssistantView):
"""Handles requests for the description.xml file.""" url = '/description.xml' name = 'description:xml' requires_auth = False def __init__(self, config): """Initialize the instance of the view.""" self.config = config @core.callback def get(self, request): """Handle...
"""Provides a UPNP discovery method that mimicks Hue hubs.""" import threading import socket import logging import os import select from aiohttp import web from homeassistant import core from homeassistant.components.http import HomeAssistantView _LOGGER = logging.getLogger(__name__) class DescriptionXmlView(HomeAss...
68
106
354
8
60
sbidoul/home-assistant
homeassistant/components/emulated_hue/upnp.py
Python
DescriptionXmlView
DescriptionXmlView
16
55
16
16
3d2600ed530ef105499fec24834e77b036ebd151
bigcode/the-stack
train
207b6218fde7e322ae1efc74
train
class
class UPNPResponderThread(threading.Thread): """Handle responding to UPNP/SSDP discovery requests.""" _interrupted = False def __init__(self, host_ip_addr, listen_port, upnp_bind_multicast): """Initialize the class.""" threading.Thread.__init__(self) self.host_ip_addr = host_ip_ad...
class UPNPResponderThread(threading.Thread):
"""Handle responding to UPNP/SSDP discovery requests.""" _interrupted = False def __init__(self, host_ip_addr, listen_port, upnp_bind_multicast): """Initialize the class.""" threading.Thread.__init__(self) self.host_ip_addr = host_ip_addr self.listen_port = listen_port ...
schemas-upnp-org:device-1-0"> <specVersion> <major>1</major> <minor>0</minor> </specVersion> <URLBase>http://{0}:{1}/</URLBase> <device> <deviceType>urn:schemas-upnp-org:device:Basic:1</deviceType> <friendlyName>HASS Bridge ({0})</friendlyName> <manufacturer>Royal Philips Electronics</manufacturer> <manufacturerURL>htt...
256
256
918
10
246
sbidoul/home-assistant
homeassistant/components/emulated_hue/upnp.py
Python
UPNPResponderThread
UPNPResponderThread
58
164
58
58
7911c09b56f2fde2fc645fa7631a4dddea2d080a
bigcode/the-stack
train
800324de0974bfa6cd375864
train
class
class MakeSimilarityData(gokart.TaskOnKart): task_namespace = 'redshells.word_item_similarity' word2items_task = gokart.TaskInstanceParameter(description='A task which outputs a mapping from word to items which includes the word.') similarity_task = gokart.TaskInstanceParameter(description='A task which out...
class MakeSimilarityData(gokart.TaskOnKart):
task_namespace = 'redshells.word_item_similarity' word2items_task = gokart.TaskInstanceParameter(description='A task which outputs a mapping from word to items which includes the word.') similarity_task = gokart.TaskInstanceParameter(description='A task which outputs a similarity data.') item_id_0_colum...
import itertools from logging import getLogger from typing import Dict, Any import luigi import numpy as np import pandas as pd import gokart logger = getLogger(__name__) class MakeSimilarityData(gokart.TaskOnKart):
52
256
1,000
11
41
hirosassa/redshells
redshells/app/word_item_similarity/make_similarity_data.py
Python
MakeSimilarityData
MakeSimilarityData
14
82
14
14
c167ae2188894c04be04f34ed6c864eec6b0b3dd
bigcode/the-stack
train
6f71fc5c852214369491e2da
train
class
class V1FailureEarlyStopping(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute...
class V1FailureEarlyStopping(object):
"""NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The...
#!/usr/bin/python # # Copyright 2018-2021 Polyaxon, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
242
256
872
8
233
onilton/polyaxon
sdks/python/http_client/v1/polyaxon_sdk/models/v1_failure_early_stopping.py
Python
V1FailureEarlyStopping
V1FailureEarlyStopping
38
165
38
38
21a7e96cfad90310bde77512b1994329633bb906
bigcode/the-stack
train
0a14005240dab7ffd52d2561
train
function
@click.group() @click.version_option(version=__version__) def cli(): pass
@click.group() @click.version_option(version=__version__) def cli():
pass
WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. # # ================================================================= __version__ = '0.12.dev0' import click from pygeoapi.config import config from pygeoapi.openapi import openapi @click.group() @click.version_option(version=__version__) def cli():
64
64
17
14
49
photonbit/pygeoapi
pygeoapi/__init__.py
Python
cli
cli
37
40
37
39
7944bc62a8f5598f587057b97cd058beca38c292
bigcode/the-stack
train
851d35d39b15889cb09fa052
train
function
@cli.command() @click.option('--flask', 'server', flag_value="flask", default=True) @click.option('--starlette', 'server', flag_value="starlette") @click.pass_context def serve(ctx, server): """Run the server with different daemon type (--flask is the default)""" if server == "flask": from pygeoapi.fla...
@cli.command() @click.option('--flask', 'server', flag_value="flask", default=True) @click.option('--starlette', 'server', flag_value="starlette") @click.pass_context def serve(ctx, server):
"""Run the server with different daemon type (--flask is the default)""" if server == "flask": from pygeoapi.flask_app import serve as serve_flask ctx.forward(serve_flask) ctx.invoke(serve_flask) elif server == "starlette": from pygeoapi.starlette_app import serve as serve_s...
@click.group() @click.version_option(version=__version__) def cli(): pass @cli.command() @click.option('--flask', 'server', flag_value="flask", default=True) @click.option('--starlette', 'server', flag_value="starlette") @click.pass_context def serve(ctx, server):
64
64
160
47
16
photonbit/pygeoapi
pygeoapi/__init__.py
Python
serve
serve
43
59
43
47
e7dd4b578d7df892b1db45fe5b60d8121e746d4a
bigcode/the-stack
train
b231a998124e9135a9321606
train
function
def mse(params, fac, n_closest, X, Y, x, y): y_hat, kernel = predict(params, fac, n_closest, X, Y, x) mse = (y_hat - y) ** 2 return mse[0]
def mse(params, fac, n_closest, X, Y, x, y):
y_hat, kernel = predict(params, fac, n_closest, X, Y, x) mse = (y_hat - y) ** 2 return mse[0]
ort()[:n_closest] kernel.fit(X[closest], Y[closest]) out = kernel.predict(x[None, :]) y_hat = out["y"][0] return y_hat, kernel def mse(params, fac, n_closest, X, Y, x, y):
64
64
58
18
45
anyoptimization/ezmodel
ezmodel/experimental/custom2/lgp.py
Python
mse
mse
26
29
26
26
fabd22c805e1c120dea7d3072b4e8fa33c68c543
bigcode/the-stack
train
1b7d81392d6d154a8e11daa4
train
function
def kernel_from_params(fac, params): theta = anp.exp(params[0]) kernel = fac.create(theta=theta) return kernel
def kernel_from_params(fac, params):
theta = anp.exp(params[0]) kernel = fac.create(theta=theta) return kernel
, fac, n_closest, X, Y, x, y): y_hat, kernel = predict(params, fac, n_closest, X, Y, x) mse = (y_hat - y) ** 2 return mse[0] def kernel_from_params(fac, params):
64
64
32
9
55
anyoptimization/ezmodel
ezmodel/experimental/custom2/lgp.py
Python
kernel_from_params
kernel_from_params
32
35
32
32
494d2c8c3704220abfc9e9d63cf4b094a186b074
bigcode/the-stack
train
4a62302aa46de59c28286ffe
train
function
def avg_mse(params, X, y, n_nearest, fac): _mse = [] for j in range(len(X)): m = np.full(len(X), True) m[j] = False __mse = mse(params, fac, n_nearest, X[m], y[m], X[j], y[j]) _mse.append(__mse) return np.array(_mse).mean()
def avg_mse(params, X, y, n_nearest, fac):
_mse = [] for j in range(len(X)): m = np.full(len(X), True) m[j] = False __mse = mse(params, fac, n_nearest, X[m], y[m], X[j], y[j]) _mse.append(__mse) return np.array(_mse).mean()
(y_hat - y) ** 2 return mse[0] def kernel_from_params(fac, params): theta = anp.exp(params[0]) kernel = fac.create(theta=theta) return kernel def avg_mse(params, X, y, n_nearest, fac):
64
64
92
16
47
anyoptimization/ezmodel
ezmodel/experimental/custom2/lgp.py
Python
avg_mse
avg_mse
38
47
38
38
be55ab662f65072e16f31741bbe2d49ca2ff14c8
bigcode/the-stack
train
55d65a8d16e84fec406442fd
train
function
def predict(params, fac, n_closest, X, Y, x): kernel = kernel_from_params(fac, params) d = kernel.D(x[None, :], X)[0] closest = d.argsort()[:n_closest] kernel.fit(X[closest], Y[closest]) out = kernel.predict(x[None, :]) y_hat = out["y"][0] return y_hat, kernel
def predict(params, fac, n_closest, X, Y, x):
kernel = kernel_from_params(fac, params) d = kernel.D(x[None, :], X)[0] closest = d.argsort()[:n_closest] kernel.fit(X[closest], Y[closest]) out = kernel.predict(x[None, :]) y_hat = out["y"][0] return y_hat, kernel
GaussianKernel, KernelFactory from ezmodel.custom2.optimizer import Adam from ezmodel.core.model import Model from ezmodel.core.transformation import NoNormalization from ezmodel.util.transformation.zero_to_one import ZeroToOneNormalization def predict(params, fac, n_closest, X, Y, x):
64
64
93
16
47
anyoptimization/ezmodel
ezmodel/experimental/custom2/lgp.py
Python
predict
predict
12
23
12
12
8c7f9692fd2887d8b6aa2763e088d18d4e94e506
bigcode/the-stack
train