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
e9183b51ca6a5938c9d798b8
train
function
@app.endpoint('views.home') def home(): return render_template('home.html', recent=expand_recent_bins())
@app.endpoint('views.home') def home():
return render_template('home.html', recent=expand_recent_bins())
session: session['recent'] = [] recent = [] for name in session['recent']: try: recent.append(db.lookup_bin(name)) except KeyError: session['recent'].remove(name) session.modified = True return recent @app.endpoint('views.home') def home():
64
64
23
9
54
derekjc/requestbin
requestbin/views.py
Python
home
home
29
31
29
30
87ea42039fc8eefd199d2e4b2595809e9f4e1314
bigcode/the-stack
train
9fb26998d0a6b386d52dc74a
train
class
class DefaultSocialAccountAdapter(object): error_messages = { "email_taken": _( "An account already exists with this e-mail address." " Please sign in to that account first, then connect" " your %s account." ) } def __init__(self, request=None): ...
class DefaultSocialAccountAdapter(object):
error_messages = { "email_taken": _( "An account already exists with this e-mail address." " Please sign in to that account first, then connect" " your %s account." ) } def __init__(self, request=None): self.request = request def pre_social_l...
from __future__ import absolute_import from django.core.exceptions import ValidationError from django.urls import reverse from django.utils.translation import gettext_lazy as _ from ..account import app_settings as account_settings from ..account.adapter import get_adapter as get_account_adapter from ..account.app_se...
128
256
1,392
7
120
iarp/django-allauth
allauth/socialaccount/adapter.py
Python
DefaultSocialAccountAdapter
DefaultSocialAccountAdapter
22
205
22
23
5ac2496da89a5906bc56fe7128e5904fb975e10a
bigcode/the-stack
train
914b710d0a79e672fc3680a3
train
function
def get_adapter(request=None): return import_attribute(app_settings.ADAPTER)(request)
def get_adapter(request=None):
return import_attribute(app_settings.ADAPTER)(request)
config: app = SocialApp(provider=provider) for field in ["client_id", "secret", "key", "certificate_key"]: setattr(app, field, config.get(field)) else: app = SocialApp.objects.get_current(provider, request) return app def get_adapter(request=None):
64
64
17
6
57
iarp/django-allauth
allauth/socialaccount/adapter.py
Python
get_adapter
get_adapter
208
209
208
208
cf4123e0f88cad34229daa836709b7ffe3931791
bigcode/the-stack
train
66570e47d124d6b5c517b768
train
function
async def hello(websocket, path): name = await websocket.recv() print(f"< {name}") greeting = f"Hello {name}!" await websocket.send(greeting) print(f"> {greeting}")
async def hello(websocket, path):
name = await websocket.recv() print(f"< {name}") greeting = f"Hello {name}!" await websocket.send(greeting) print(f"> {greeting}")
#!/usr/bin/env python3 import sys import asyncio import websockets async def hello(websocket, path):
25
64
47
8
16
shkaph/sudoku_py
main.py
Python
hello
hello
7
14
7
7
b4ccbcf603d5b1ed6ef65777efc109268f9917ff
bigcode/the-stack
train
162ea910ec81259819ba9801
train
function
def readCSV(): # Creating a list to contain restaurant objects restaurants = [] # opening file to read with open('restaurants.csv', 'r') as read_obj: csv_reader = csv.reader(read_obj) # skip header next(csv_reader, None) # iterate through each row for row in cs...
def readCSV(): # Creating a list to contain restaurant objects
restaurants = [] # opening file to read with open('restaurants.csv', 'r') as read_obj: csv_reader = csv.reader(read_obj) # skip header next(csv_reader, None) # iterate through each row for row in csv_reader: # setting variables to pass to restaurant cons...
name, price_opt, diet_opt, delivery_opt, distance_opt): self.name = name self.price = price_opt self.diet = diet_opt self.delivery = delivery_opt self.distance = distance_opt def readCSV(): # Creating a list to contain restaurant objects
64
64
182
15
48
nicholasfalconi/Restaurant-modeling-project
csvReader.py
Python
readCSV
readCSV
21
43
21
22
3d2801945a095a8e9375c29d6bd737d459a4a9c2
bigcode/the-stack
train
6c05a982458799946514c97d
train
class
class restaurant: def __init__(self, name, price_opt, diet_opt, delivery_opt, distance_opt): self.name = name self.price = price_opt self.diet = diet_opt self.delivery = delivery_opt self.distance = distance_opt
class restaurant:
def __init__(self, name, price_opt, diet_opt, delivery_opt, distance_opt): self.name = name self.price = price_opt self.diet = diet_opt self.delivery = delivery_opt self.distance = distance_opt
''' Restaurant class Used to create a class containing information on a resaurant. Makes it easier to track data involving each restaurant actually will be implemented in the csv reader so this is irrelavant ''' import csv # restaurant object for use in run.py class restaurant:
57
64
59
3
53
nicholasfalconi/Restaurant-modeling-project
csvReader.py
Python
restaurant
restaurant
12
18
12
12
fd4fbc3a5424f6e3e0ef13445dfc1feb3abb8499
bigcode/the-stack
train
4572d77e2c3b3a644ed61be5
train
class
class DataMining(PostProcessor): """ DataMiningPostProcessor class. It will apply the specified KDD algorithms in the models to a dataset, each specified algorithm's output can be loaded to dataObject. """ @classmethod def getInputSpecification(cls): """ Method to get a reference to a cla...
class DataMining(PostProcessor):
""" DataMiningPostProcessor class. It will apply the specified KDD algorithms in the models to a dataset, each specified algorithm's output can be loaded to dataObject. """ @classmethod def getInputSpecification(cls): """ Method to get a reference to a class that specifies the input data ...
elle Energy Alliance, LLC # # 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 law or agreed to in writing, softwar...
255
256
9,659
6
249
mattdon/raven
framework/PostProcessors/DataMining.py
Python
DataMining
DataMining
39
913
39
39
bcd59ccb00d854ca8355ba129ca7eb79aeeb7fc7
bigcode/the-stack
train
194130e1c123d2033b2a5836
train
function
def _agg_cv_result(raw_results, eval_train_metric=False): """Aggregate cross-validation results.""" cvmap = collections.OrderedDict() metric_type = {} for one_result in raw_results: for one_line in one_result: if eval_train_metric: key = "{} {}".format(one_line[0], on...
def _agg_cv_result(raw_results, eval_train_metric=False):
"""Aggregate cross-validation results.""" cvmap = collections.OrderedDict() metric_type = {} for one_result in raw_results: for one_line in one_result: if eval_train_metric: key = "{} {}".format(one_line[0], one_line[1]) else: key = one_lin...
=train_set, gp_model=gp_model_train) if eval_train_metric: cvbooster.add_valid(train_set, 'train') cvbooster.add_valid(valid_set, 'valid') ret.append(cvbooster) return ret def _agg_cv_result(raw_results, eval_train_metric=False):
64
64
142
13
50
stanpcf/GPBoost
python-package/gpboost/engine.py
Python
_agg_cv_result
_agg_cv_result
448
461
448
448
203436ab49f4a795482ea5b7293c4ef855833685
bigcode/the-stack
train
5b682f05a67d6289931f97f9
train
function
def cv(params, train_set, num_boost_round=100, gp_model=None, train_gp_model_cov_pars=True, use_gp_model_for_validation=False, folds=None, nfold=5, stratified=False, shuffle=True, metrics=None, fobj=None, feval=None, init_model=None, feature_name='auto', categorical_feature='auto', ...
def cv(params, train_set, num_boost_round=100, gp_model=None, train_gp_model_cov_pars=True, use_gp_model_for_validation=False, folds=None, nfold=5, stratified=False, shuffle=True, metrics=None, fobj=None, feval=None, init_model=None, feature_name='auto', categorical_feature='auto', ...
"""Perform the cross-validation with given paramaters. Parameters ---------- params : dict Parameters for Booster. train_set : Dataset Data to be trained on. num_boost_round : int, optional (default=100) Number of boosting iterations. gp_model : GPModel or None, opti...
_agg_cv_result(raw_results, eval_train_metric=False): """Aggregate cross-validation results.""" cvmap = collections.OrderedDict() metric_type = {} for one_result in raw_results: for one_line in one_result: if eval_train_metric: key = "{} {}".format(one_line[0], one_l...
255
256
2,546
114
141
stanpcf/GPBoost
python-package/gpboost/engine.py
Python
cv
cv
464
699
464
472
e31453f9b27e359013e502c7819a53bec6e2cecd
bigcode/the-stack
train
159a6c97a443647f2a8ad97e
train
function
def train(params, train_set, num_boost_round=100, gp_model=None, train_gp_model_cov_pars=True, valid_sets=None, valid_names=None, fobj=None, feval=None, init_model=None, feature_name='auto', categorical_feature='auto', early_stopping_rounds=None, evals_result=None, ...
def train(params, train_set, num_boost_round=100, gp_model=None, train_gp_model_cov_pars=True, valid_sets=None, valid_names=None, fobj=None, feval=None, init_model=None, feature_name='auto', categorical_feature='auto', early_stopping_rounds=None, evals_result=None, ...
"""Perform the training with given parameters. Parameters ---------- params : dict Parameters for training, see Parameters.rst for more information. train_set : Dataset Data to be trained on. num_boost_round : int, optional (default=100) Number of boosting iterations. ...
# coding: utf-8 # pylint: disable = invalid-name, W0105 """Library with training routines of GPBoost.""" from __future__ import absolute_import import collections import copy import warnings from operator import attrgetter import numpy as np from . import callback from .basic import Booster, Dataset, GPBoostError, _...
223
256
2,994
100
123
stanpcf/GPBoost
python-package/gpboost/engine.py
Python
train
train
19
307
19
27
39a0680408390d19e5688db52f73f45dffa0c5c6
bigcode/the-stack
train
61a3c2304e2ea790edc74246
train
function
def _make_n_folds(full_data, folds, nfold, params, seed, gp_model=None, use_gp_model_for_validation=False, fpreproc=None, stratified=False, shuffle=True, eval_train_metric=False): """Make a n-fold list of Booster from random indices.""" full_data = full_data.construct() num_data = full_dat...
def _make_n_folds(full_data, folds, nfold, params, seed, gp_model=None, use_gp_model_for_validation=False, fpreproc=None, stratified=False, shuffle=True, eval_train_metric=False):
"""Make a n-fold list of Booster from random indices.""" full_data = full_data.construct() num_data = full_data.num_data() if folds is not None: if not hasattr(folds, '__iter__') and not hasattr(folds, 'split'): raise AttributeError("folds should be a generator or iterator of (train_...
for dataset_name, eval_name, score, _ in evaluation_result_list: booster.best_score[dataset_name][eval_name] = score if not keep_training_booster: booster.model_from_string(booster.model_to_string(), False).free_dataset() return booster class _CVBooster(object): """Auxiliary data struc...
256
256
1,338
47
208
stanpcf/GPBoost
python-package/gpboost/engine.py
Python
_make_n_folds
_make_n_folds
332
445
332
333
0a58ceb6f9769d37630c156a8b4672ab1ea8c33a
bigcode/the-stack
train
f995cbf72aae93deb9a3f1fa
train
class
class _CVBooster(object): """Auxiliary data struct to hold all boosters of CV.""" def __init__(self): self.boosters = [] self.best_iteration = -1 def append(self, booster): """Add a booster to _CVBooster.""" self.boosters.append(booster) def __getattr__(self, name): ...
class _CVBooster(object):
"""Auxiliary data struct to hold all boosters of CV.""" def __init__(self): self.boosters = [] self.best_iteration = -1 def append(self, booster): """Add a booster to _CVBooster.""" self.boosters.append(booster) def __getattr__(self, name): """Redirect methods ...
dataset_name, eval_name, score, _ in evaluation_result_list: booster.best_score[dataset_name][eval_name] = score if not keep_training_booster: booster.model_from_string(booster.model_to_string(), False).free_dataset() return booster class _CVBooster(object):
64
64
150
7
56
stanpcf/GPBoost
python-package/gpboost/engine.py
Python
_CVBooster
_CVBooster
310
329
310
310
6309e559c9499f638a8b80c172f9048f4ff9fd98
bigcode/the-stack
train
d2db53547c8a34fe7ef31140
train
class
class ControlFlowV1OpsTest(LiteTest): def testConverterErrorOnControlFlowV1Ops(self): graph_def_file = resource_loader.get_path_to_datafile( 'testdata/control_flow_v1.pbtxt') input_arrays = ['a', 'b', 'c', 'd'] output_arrays = ['Merge'] converter = lite.TFLiteConverter.from_frozen_graph(grap...
class ControlFlowV1OpsTest(LiteTest):
def testConverterErrorOnControlFlowV1Ops(self): graph_def_file = resource_loader.get_path_to_datafile( 'testdata/control_flow_v1.pbtxt') input_arrays = ['a', 'b', 'c', 'd'] output_arrays = ['Merge'] converter = lite.TFLiteConverter.from_frozen_graph(graph_def_file, ...
None(converter.drop_control_dependency) # Assert dumping extra information is disabled by default. self.assertIsNone(converter.dump_graphviz_dir) self.assertFalse(converter.dump_graphviz_video) self.assertIsNone(converter.conversion_summary_dir) class ControlFlowV1OpsTest(LiteTest):
64
64
169
11
53
computationalartist/tensorflow
tensorflow/lite/python/lite_test.py
Python
ControlFlowV1OpsTest
ControlFlowV1OpsTest
2,913
2,929
2,913
2,914
b4cbbb3a9a9670bb37ff26087278d5cc2b4271d5
bigcode/the-stack
train
22987d37188ad4c40e73fb50
train
class
class LiteTest(test_util.TensorFlowTestCase): """Base class of all the tests in this module."""
class LiteTest(test_util.TensorFlowTestCase):
"""Base class of all the tests in this module."""
.ops.variables import global_variables_initializer as _global_variables_initializer from tensorflow.python.platform import gfile from tensorflow.python.platform import resource_loader from tensorflow.python.platform import test from tensorflow.python.saved_model import saved_model from tensorflow.python.training.traini...
64
64
22
10
53
computationalartist/tensorflow
tensorflow/lite/python/lite_test.py
Python
LiteTest
LiteTest
60
61
60
60
701202afbc461f932f044b6031287890476ffeee
bigcode/the-stack
train
395e76addad4296b48120dfd
train
class
class FromFrozenGraphFile(LiteTest): def testFloat(self): with ops.Graph().as_default(): in_tensor = array_ops.placeholder( shape=[1, 16, 16, 3], dtype=dtypes.float32) _ = in_tensor + in_tensor sess = session.Session() # Write graph to file. graph_def_file = os.path.join(self...
class FromFrozenGraphFile(LiteTest):
def testFloat(self): with ops.Graph().as_default(): in_tensor = array_ops.placeholder( shape=[1, 16, 16, 3], dtype=dtypes.float32) _ = in_tensor + in_tensor sess = session.Session() # Write graph to file. graph_def_file = os.path.join(self.get_temp_dir(), 'model.pb') write...
in the model. sess = session.Session() sess.run(variables.variables_initializer([variable_node])) converter = lite.TFLiteConverter.from_session(sess, [placeholder], [output_node]) converter.convert() self.assertValidDebugInfo(converter._debug_i...
256
256
2,209
9
247
computationalartist/tensorflow
tensorflow/lite/python/lite_test.py
Python
FromFrozenGraphFile
FromFrozenGraphFile
1,673
1,906
1,673
1,674
4079560c861922c98002bb12c3dcca92c3f27703
bigcode/the-stack
train
e012aabd73928d9ae3655df6
train
class
class TestModels(LiteTest): def assertValidDebugInfo(self, debug_info): """Verify the DebugInfo is valid.""" file_names = set() for file_path in debug_info.files: file_names.add(os.path.basename(file_path)) # To make the test independent on how the nodes are created, we only assert # the na...
class TestModels(LiteTest):
def assertValidDebugInfo(self, debug_info): """Verify the DebugInfo is valid.""" file_names = set() for file_path in debug_info.files: file_names.add(os.path.basename(file_path)) # To make the test independent on how the nodes are created, we only assert # the name of this test file. sel...
from tensorflow.python.platform import resource_loader from tensorflow.python.platform import test from tensorflow.python.saved_model import saved_model from tensorflow.python.training.training_util import write_graph class LiteTest(test_util.TensorFlowTestCase): """Base class of all the tests in this module.""" cl...
63
64
106
7
56
computationalartist/tensorflow
tensorflow/lite/python/lite_test.py
Python
TestModels
TestModels
64
74
64
65
5e6b3eae62574b8178518fb385b7277f1c1b5200
bigcode/the-stack
train
5220a0e7217afecbb0259245
train
class
class FromConstructor(TestModels): # Tests invalid constructors using a dummy value for the GraphDef. def testInvalidConstructor(self): message = ( 'If input_tensors and output_tensors are None, both ' 'input_arrays_with_shape and output_arrays|control_output_arrays must ' 'be defined.'...
class FromConstructor(TestModels): # Tests invalid constructors using a dummy value for the GraphDef.
def testInvalidConstructor(self): message = ( 'If input_tensors and output_tensors are None, both ' 'input_arrays_with_shape and output_arrays|control_output_arrays must ' 'be defined.') # `output_arrays` is not defined. with self.assertRaises(ValueError) as error: lite.TFLi...
_array_ops from tensorflow.python.ops import logging_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn_ops from tensorflow.python.ops import random_ops from tensorflow.python.ops import variable_scope from tensorflow.python.ops import variables from tensorflow.python.ops.variables impo...
256
256
1,408
20
236
computationalartist/tensorflow
tensorflow/lite/python/lite_test.py
Python
FromConstructor
FromConstructor
77
222
77
79
2ab5c9add8ef70aa2293b5d4f8a99b7be1d8e54e
bigcode/the-stack
train
0b734222ed4b0aa9bf471a71
train
class
class MyAddLayer(keras.layers.Layer): def __init__(self, increment, **kwargs): super(MyAddLayer, self).__init__(**kwargs) self._increment = increment def call(self, inputs): return inputs + self._increment def get_config(self): config = super(MyAddLayer, self).get_config() config['increment...
class MyAddLayer(keras.layers.Layer):
def __init__(self, increment, **kwargs): super(MyAddLayer, self).__init__(**kwargs) self._increment = increment def call(self, inputs): return inputs + self._increment def get_config(self): config = super(MyAddLayer, self).get_config() config['increment'] = self._increment return config
.""" saved_model_dir = self._createSavedModel(shape=[1, 16, 16, 3]) converter = lite.TFLiteConverter.from_saved_model(saved_model_dir) converter.convert() self.assertValidDebugInfo(converter._debug_info) class MyAddLayer(keras.layers.Layer):
64
64
89
9
55
computationalartist/tensorflow
tensorflow/lite/python/lite_test.py
Python
MyAddLayer
MyAddLayer
2,292
2,304
2,292
2,293
231607d58d82dc86b2b9f6960f3be52c9e97f4b1
bigcode/the-stack
train
7b9d910ed607125a191a99ba
train
class
class DefaultConverterAttrsTest(LiteTest): def testAttrs(self): with ops.Graph().as_default(): in_tensor = array_ops.placeholder(shape=[2, 2], dtype=dtypes.float32) out_tensor = in_tensor + in_tensor sess = session.Session() # Convert model. converter = lite.TFLiteConverter.from_sessio...
class DefaultConverterAttrsTest(LiteTest):
def testAttrs(self): with ops.Graph().as_default(): in_tensor = array_ops.placeholder(shape=[2, 2], dtype=dtypes.float32) out_tensor = in_tensor + in_tensor sess = session.Session() # Convert model. converter = lite.TFLiteConverter.from_session(sess, [in_tensor], ...
(sess, [in_tensor], [out_tensor]) tflite_model = converter.convert() # Check values from converted model. interpreter = Interpreter(model_content=tflite_model) interpreter.allocate_tensors() input_details = interpreter.get_input_details() self....
87
88
294
9
78
computationalartist/tensorflow
tensorflow/lite/python/lite_test.py
Python
DefaultConverterAttrsTest
DefaultConverterAttrsTest
2,876
2,910
2,876
2,877
f3a01f3346f6e7f9d0da196f5f035c143efb9507
bigcode/the-stack
train
a2ae237bd52f25006357df92
train
class
class FromSessionTest(TestModels, parameterized.TestCase): def testFloatModel(self): with ops.Graph().as_default(): in_tensor = array_ops.placeholder( shape=[1, 16, 16, 3], dtype=dtypes.float32) out_tensor = in_tensor + in_tensor sess = session.Session() # Convert model and ensur...
class FromSessionTest(TestModels, parameterized.TestCase):
def testFloatModel(self): with ops.Graph().as_default(): in_tensor = array_ops.placeholder( shape=[1, 16, 16, 3], dtype=dtypes.float32) out_tensor = in_tensor + in_tensor sess = session.Session() # Convert model and ensure model is not None. converter = lite.TFLiteConverter.fr...
and ensure model is not None. converter = lite.TFLiteConverter(frozen_graph_def, None, None, [('in_tensor_a', [2, 16, 16, 3])], ['add']) # There is an unhandled Placeholder op. with self.assertRaises(ConverterError): converter.convert() def testInvalidShapeOver...
256
256
14,816
12
244
computationalartist/tensorflow
tensorflow/lite/python/lite_test.py
Python
FromSessionTest
FromSessionTest
225
1,670
225
226
9a1051332c8b02c139e0a1cfe570a9e70c0a4bff
bigcode/the-stack
train
39a4ae616fc7a3b3d80f463e
train
class
class QuantizationModeTest(LiteTest, parameterized.TestCase): @parameterized.named_parameters( ('size', lite.Optimize.OPTIMIZE_FOR_SIZE), ('latency', lite.Optimize.OPTIMIZE_FOR_LATENCY)) def testDeprecatedOptionWarning(self, optimization): """Test if the warning message when using TOCO is logged.""...
class QuantizationModeTest(LiteTest, parameterized.TestCase): @parameterized.named_parameters( ('size', lite.Optimize.OPTIMIZE_FOR_SIZE), ('latency', lite.Optimize.OPTIMIZE_FOR_LATENCY))
def testDeprecatedOptionWarning(self, optimization): """Test if the warning message when using TOCO is logged.""" log = io.StringIO() handler = logging.StreamHandler(log) logging.root.addHandler(handler) warning_message = 'please use optimizations=[Optimize.DEFAULT] instead.' lite.Quantization...
/v1/enable_control_flow_v2.', str(error.exception)) class QuantizationModeTest(LiteTest, parameterized.TestCase): @parameterized.named_parameters( ('size', lite.Optimize.OPTIMIZE_FOR_SIZE), ('latency', lite.Optimize.OPTIMIZE_FOR_LATENCY))
64
64
148
51
13
computationalartist/tensorflow
tensorflow/lite/python/lite_test.py
Python
QuantizationModeTest
QuantizationModeTest
2,932
2,945
2,932
2,936
dcc0437bcb23588ddab20614d4592adb66c8b3bc
bigcode/the-stack
train
1d7310353f6e7e1e71cdce82
train
class
class FromKerasFile(TestModels, parameterized.TestCase): def setUp(self): super(FromKerasFile, self).setUp() self._keras_file = None self._custom_objects = None if not context.executing_eagerly(): keras.backend.clear_session() def tearDown(self): if self._keras_file: os.remove(self...
class FromKerasFile(TestModels, parameterized.TestCase):
def setUp(self): super(FromKerasFile, self).setUp() self._keras_file = None self._custom_objects = None if not context.executing_eagerly(): keras.backend.clear_session() def tearDown(self): if self._keras_file: os.remove(self._keras_file) super(FromKerasFile, self).tearDown() ...
16, 16, 3]) # Convert model and ensure model is not None. converter = lite.TocoConverter.from_saved_model(saved_model_dir) tflite_model = converter.convert() self.assertIsNotNone(tflite_model) # Ensure the model is able to load. interpreter = Interpreter(model_content=tflite_model) interp...
256
256
4,466
13
242
computationalartist/tensorflow
tensorflow/lite/python/lite_test.py
Python
FromKerasFile
FromKerasFile
2,307
2,781
2,307
2,308
71e9e1c39e00da8baddc860c9c4ef4581dd52cbf
bigcode/the-stack
train
a471a5f24fb70e97ca0967ae
train
class
class FromFrozenGraphObjectDetection(LiteTest): def _initObjectDetectionArgs(self): # Initializes the arguments required for the object detection model. # Looks for the model file which is saved in a different location internally # and externally. filename = resource_loader.get_path_to_datafile('test...
class FromFrozenGraphObjectDetection(LiteTest):
def _initObjectDetectionArgs(self): # Initializes the arguments required for the object detection model. # Looks for the model file which is saved in a different location internally # and externally. filename = resource_loader.get_path_to_datafile('testdata/tflite_graph.pb') if not os.path.exists(...
model is not None. converter = lite.TocoConverter.from_frozen_graph(graph_def_file, ['Placeholder'], ['add']) tflite_model = converter.convert() self.assertIsNotNone(tflite_model) # Ensure the model is able to load. interpreter = Interpreter(mod...
256
256
1,483
10
246
computationalartist/tensorflow
tensorflow/lite/python/lite_test.py
Python
FromFrozenGraphObjectDetection
FromFrozenGraphObjectDetection
1,909
2,058
1,909
1,910
1f668f40226a0deece537633ee48310272696abf
bigcode/the-stack
train
a4611e70028b491413ffc439
train
class
class GrapplerTest(TestModels, parameterized.TestCase): def testConstantFolding(self): ops.disable_eager_execution() # Constant folding handles the tf.broadcast_to operation which was not # supported by the TFLite at the time this test was added. with ops.Graph().as_default(): in_tensor = array...
class GrapplerTest(TestModels, parameterized.TestCase):
def testConstantFolding(self): ops.disable_eager_execution() # Constant folding handles the tf.broadcast_to operation which was not # supported by the TFLite at the time this test was added. with ops.Graph().as_default(): in_tensor = array_ops.placeholder(shape=[3, 3], dtype=dtypes.float32) ...
.named_parameters(('_graph', context.graph_mode), ('_eager', context.eager_mode)) def testGraphDebugInfo(self, test_context): """Test a Sequential tf.keras model has debug info captured.""" with test_context(): self._getSequentialModel() converter = lite.TFLiteCon...
253
253
845
12
241
computationalartist/tensorflow
tensorflow/lite/python/lite_test.py
Python
GrapplerTest
GrapplerTest
2,784
2,873
2,784
2,785
d3064c6219adc4270b40e837e81f396a2027c424
bigcode/the-stack
train
054dd8904497774d9532c152
train
class
class FromSavedModelTest(TestModels): def _createSavedModel(self, shape): """Create a simple SavedModel.""" saved_model_dir = os.path.join(self.get_temp_dir(), 'simple_savedmodel') with ops.Graph().as_default(): with session.Session() as sess: in_tensor_1 = array_ops.placeholder( ...
class FromSavedModelTest(TestModels):
def _createSavedModel(self, shape): """Create a simple SavedModel.""" saved_model_dir = os.path.join(self.get_temp_dir(), 'simple_savedmodel') with ops.Graph().as_default(): with session.Session() as sess: in_tensor_1 = array_ops.placeholder( shape=shape, dtype=dtypes.float32, na...
converter.target_spec.supported_ops = {lite.OpsSet.TFLITE_BUILTINS_INT8} converter.inference_type = dtypes.int8 converter.inference_input_type = dtypes.uint8 converter.inference_output_type = dtypes.uint8 converter.experimental_new_quantizer = True converter.quantized_input_stats = { 'n...
256
256
2,488
8
248
computationalartist/tensorflow
tensorflow/lite/python/lite_test.py
Python
FromSavedModelTest
FromSavedModelTest
2,061
2,289
2,061
2,062
4cf898c5623ec75ff7ba360b6077ceeddcf9ae8a
bigcode/the-stack
train
a1c291b07c294bcddb405cd0
train
class
class Map(keplergl.KeplerGl): """The Map class inherits keplergl.KeperGl. Returns: object: keplergl.KeperGl map object. """ def __init__(self, **kwargs): if "center" not in kwargs: kwargs["center"] = [20, 0] if "zoom" not in kwargs: kwargs["zoom"] = 1....
class Map(keplergl.KeplerGl):
"""The Map class inherits keplergl.KeperGl. Returns: object: keplergl.KeperGl map object. """ def __init__(self, **kwargs): if "center" not in kwargs: kwargs["center"] = [20, 0] if "zoom" not in kwargs: kwargs["zoom"] = 1.3 if "height" not in ...
import json import os import sys import requests import ipywidgets as widgets import pandas as pd from IPython.display import display, HTML from .common import * from .osm import * try: import keplergl if "google.colab" in sys.modules: from google.colab import output output.enable_custom_widg...
147
256
3,681
12
135
aplitest/leafmap
leafmap/kepler.py
Python
Map
Map
24
521
24
24
100d30da7623efdd870b57c6b0db2feb0fe90b6b
bigcode/the-stack
train
b8bd6d639fc1b4157976f4cf
train
function
@tf.function def delta_accelerate(audio: tf.Tensor, text: Optional[tf.Tensor] = None): """ Append delta and deltas from audio feature. :param audio: audio data shaped [TimeStep, AudioDim, 1] :param text: text data :return: enhanced audio feature shaped [TimeStep, AudioDim, 3] """ zero_head ...
@tf.function def delta_accelerate(audio: tf.Tensor, text: Optional[tf.Tensor] = None):
""" Append delta and deltas from audio feature. :param audio: audio data shaped [TimeStep, AudioDim, 1] :param text: text data :return: enhanced audio feature shaped [TimeStep, AudioDim, 3] """ zero_head = tf.zeros_like(audio[:1]) delta = audio - tf.concat([zero_head, audio[:-1]], axis=...
(mask, audio.dtype)[:, tf.newaxis, tf.newaxis] audio *= mask if text is None: return audio return audio, text return _wrapper @tf.function def delta_accelerate(audio: tf.Tensor, text: Optional[tf.Tensor] = None):
64
64
177
24
39
cosmoquester/speech-recognition
speech_recognition/data.py
Python
delta_accelerate
delta_accelerate
310
328
310
311
2d94b496cb1b6358dbd617e84a881e8b616c1e0b
bigcode/the-stack
train
6bdbd9cb4a0d5dfc77a0f631
train
function
def get_dataset( dataset_paths: str, file_format: str, sample_rate: int, tokenizer: text.SentencepieceTokenizer, shuffle: bool = False, resample: Optional[int] = None, ) -> tf.data.Dataset: """ Load dataset from tsv file. The dataset file has to header. The first column has audio fil...
def get_dataset( dataset_paths: str, file_format: str, sample_rate: int, tokenizer: text.SentencepieceTokenizer, shuffle: bool = False, resample: Optional[int] = None, ) -> tf.data.Dataset:
""" Load dataset from tsv file. The dataset file has to header. The first column has audio file path and second column has recognized sentence. :param dataset_paths: dataset file path glob pattern. :param file_format: audio file format. one of ["wav", "flac", "mp3", "pcm"] :param sample_rate: a...
import os import random from functools import partial from typing import Callable, Optional, Tuple import tensorflow as tf import tensorflow_addons as tfa import tensorflow_io as tfio import tensorflow_text as text def get_dataset( dataset_paths: str, file_format: str, sample_rate: int, tokenizer: text...
100
135
450
54
45
cosmoquester/speech-recognition
speech_recognition/data.py
Python
get_dataset
get_dataset
12
61
12
19
a1ac662c7a1779241365a10636d3c427823bf1ea
bigcode/the-stack
train
0bc4427b0c8d5fb4199d23dc
train
function
def spec_augment( v: int, W: Optional[int] = None, F: Optional[int] = None, m_F: Optional[int] = None, T: Optional[int] = None, p: Optional[float] = None, m_T: Optional[int] = None, ): """ Make function wrapper to apply SpecAugment. The parameter names follow papers augment param...
def spec_augment( v: int, W: Optional[int] = None, F: Optional[int] = None, m_F: Optional[int] = None, T: Optional[int] = None, p: Optional[float] = None, m_T: Optional[int] = None, ):
""" Make function wrapper to apply SpecAugment. The parameter names follow papers augment parameter names. Using time warping, the number of boundary points is different from paper. This function uses 8 point as boundary points because cannot set 6 points. :param v: the number of frequency chan...
el_bins, num_spectrogram_bins, sample_rate, lower_edge_hertz, upper_edge_hertz ) # Sahpe: [NumFrame, NumMelFilterbank] mel_spectrogram = tf.matmul(tf.square(spectrogram), mel_filterbank) log_mel_spectrogram = tf.math.log(mel_spectrogram + epsilon) # Sahpe: [NumFrame, NumMFCC] ...
213
213
711
68
144
cosmoquester/speech-recognition
speech_recognition/data.py
Python
spec_augment
spec_augment
244
307
244
252
9818d2c0bc1da0ce38c3a2867a8e843e86c8cf49
bigcode/the-stack
train
7e939a2a65b3439a2b4062e1
train
function
def make_spectrogram(frame_length: int, frame_step: int, fft_length=None): """ Make function wrapper to convert to spectrogram from PCM audio dataset. :param frame_length: window length in samples :param frame_step: number of samples to step :param fft_length: size of the FFT to apply. By default, ...
def make_spectrogram(frame_length: int, frame_step: int, fft_length=None):
""" Make function wrapper to convert to spectrogram from PCM audio dataset. :param frame_length: window length in samples :param frame_step: number of samples to step :param fft_length: size of the FFT to apply. By default, uses the smallest power of 2 enclosing frame_length :return: spectrogra...
audio = tfio.audio.resample(audio, sample_rate, resample, name="resampling") # Reduce Channel audio = tf.reduce_mean(audio, 1) return audio return _wrapper def make_spectrogram(frame_length: int, frame_step: int, fft_length=None):
64
64
203
19
44
cosmoquester/speech-recognition
speech_recognition/data.py
Python
make_spectrogram
make_spectrogram
122
142
122
122
581cf7bba8e9a77765ab8ec34f7db044aa674ae5
bigcode/the-stack
train
74110dc88518cae52ad1b361
train
function
def slice_example(max_audio_length, max_token_length): """Slice examples whose sequence length is over than the max""" def _wrapper(dataset): @tf.function def slice_fn(audio, text): return audio[:max_audio_length], text[:max_token_length] return dataset.map(slice_fn) r...
def slice_example(max_audio_length, max_token_length):
"""Slice examples whose sequence length is over than the max""" def _wrapper(dataset): @tf.function def slice_fn(audio, text): return audio[:max_audio_length], text[:max_token_length] return dataset.map(slice_fn) return _wrapper
(dataset): @tf.function def filter_fn(audio, text): return tf.math.logical_and(tf.shape(audio)[0] <= max_audio_length, tf.size(text) <= max_token_length) return dataset.filter(filter_fn) return _wrapper def slice_example(max_audio_length, max_token_length):
64
64
69
11
52
cosmoquester/speech-recognition
speech_recognition/data.py
Python
slice_example
slice_example
344
354
344
344
6d2c57e9814aa57c180804542c5da1a7632fce7d
bigcode/the-stack
train
53842e28560c68d9395e3458
train
function
def get_tfrecord_dataset(dataset_paths: str) -> tf.data.Dataset: """Read TFRecord dataset file and construct tensorflow dataset""" dataset_list = tf.io.gfile.glob(dataset_paths) decompose = tf.function( lambda serialized_example: ( tf.io.parse_tensor(serialized_example[0], tf.float32), ...
def get_tfrecord_dataset(dataset_paths: str) -> tf.data.Dataset:
"""Read TFRecord dataset file and construct tensorflow dataset""" dataset_list = tf.io.gfile.glob(dataset_paths) decompose = tf.function( lambda serialized_example: ( tf.io.parse_tensor(serialized_example[0], tf.float32), tf.io.parse_tensor(serialized_example[1], tf.int32), ...
tf.string], header=True, field_delim="\t", use_quote_delim=False ).map(load_example) return dataset return dataset.interleave(_to_dataset, num_parallel_calls=tf.data.experimental.AUTOTUNE) def get_tfrecord_dataset(dataset_paths: str) -> tf.data.Dataset:
64
64
132
16
48
cosmoquester/speech-recognition
speech_recognition/data.py
Python
get_tfrecord_dataset
get_tfrecord_dataset
64
79
64
64
169f9fca5031f5ebf8da7864fe935427d615b804
bigcode/the-stack
train
501a8d5ae67978616b3f1743
train
function
def make_log_mel_spectrogram( sample_rate: int, frame_length: int, frame_step: int, fft_length: int, num_mel_bins: int = 80, lower_edge_hertz: float = 80.0, upper_edge_hertz: float = 7600.0, epsilon: float = 1e-12, ): """ Make function wrapper to convert to log mel spectrogram fr...
def make_log_mel_spectrogram( sample_rate: int, frame_length: int, frame_step: int, fft_length: int, num_mel_bins: int = 80, lower_edge_hertz: float = 80.0, upper_edge_hertz: float = 7600.0, epsilon: float = 1e-12, ):
""" Make function wrapper to convert to log mel spectrogram from PCM audio dataset. :param sample_rate: sampling rate of audio :param frame_length: window length in samples :param frame_step: number of samples to step :param fft_length: size of the FFT to apply. By default, uses the smallest po...
FFTUniqueBins] spectrogram = tf.signal.stft(audio, frame_length, frame_step, fft_length) spectrogram = tf.abs(spectrogram)[:, :, tf.newaxis] if text is None: return spectrogram return spectrogram, text return _wrapper def make_log_mel_spectrogram( sample_rate: int, ...
145
145
486
83
61
cosmoquester/speech-recognition
speech_recognition/data.py
Python
make_log_mel_spectrogram
make_log_mel_spectrogram
145
189
145
154
003ab102e440f789be45ed2cd24e39a420a8ef84
bigcode/the-stack
train
baa6efbcb43ff44377907aff
train
function
def make_mfcc( sample_rate: int, frame_length: int, frame_step: int, fft_length: int, num_mel_bins: int = 80, num_mfcc: int = 40, lower_edge_hertz: float = 80.0, upper_edge_hertz: float = 7600.0, epsilon: float = 1e-12, ): """ Make function wrapper to convert to dct-2 type mf...
def make_mfcc( sample_rate: int, frame_length: int, frame_step: int, fft_length: int, num_mel_bins: int = 80, num_mfcc: int = 40, lower_edge_hertz: float = 80.0, upper_edge_hertz: float = 7600.0, epsilon: float = 1e-12, ):
""" Make function wrapper to convert to dct-2 type mfcc from PCM audio dataset. :param sample_rate: sampling rate of audio :param frame_length: window length in samples :param frame_step: number of samples to step :param fft_length: size of the FFT to apply. By default, uses the smallest power ...
mel_spectrogram = tf.matmul(tf.square(spectrogram), mel_filterbank) log_mel_spectrogram = tf.math.log(mel_spectrogram + epsilon)[:, :, tf.newaxis] if text is None: return log_mel_spectrogram return log_mel_spectrogram, text return _wrapper def make_mfcc( sample_rate: int, ...
162
162
541
89
72
cosmoquester/speech-recognition
speech_recognition/data.py
Python
make_mfcc
make_mfcc
192
241
192
202
24227637b6d603012f584f53a4cb7bdb13d87815
bigcode/the-stack
train
727f85ac51a3bff8341931ce
train
function
def load_audio_file( sample_rate: int, file_format: str, resample: Optional[float] = None ) -> Callable[[tf.Tensor], tf.Tensor]: """ Make function wrapper to load audio file and tokenize sentence. :param sample_rate: sample rate of audio :param file_format: audio format, one of [flac, wav, pcm, mp3...
def load_audio_file( sample_rate: int, file_format: str, resample: Optional[float] = None ) -> Callable[[tf.Tensor], tf.Tensor]:
""" Make function wrapper to load audio file and tokenize sentence. :param sample_rate: sample rate of audio :param file_format: audio format, one of [flac, wav, pcm, mp3] :param resample: resample rate if it needs, else None :return: loaded audio tensor shaped [TimeStep] """ @tf.funct...
serialized_example: ( tf.io.parse_tensor(serialized_example[0], tf.float32), tf.io.parse_tensor(serialized_example[1], tf.int32), ) ) dataset = ( tf.data.TFRecordDataset(dataset_list, "GZIP") .map(partial(tf.io.parse_tensor, out_type=tf.string)) .map(deco...
119
119
397
36
82
cosmoquester/speech-recognition
speech_recognition/data.py
Python
load_audio_file
load_audio_file
82
119
82
84
f3a358007951fa0da6f25a80f2c22641fa834686
bigcode/the-stack
train
2b79f1c5c9d77056895c177e
train
function
def filter_example(max_audio_length, max_token_length): """Filter examples whose sequence length is over than the max""" def _wrapper(dataset): @tf.function def filter_fn(audio, text): return tf.math.logical_and(tf.shape(audio)[0] <= max_audio_length, tf.size(text) <= max_token_leng...
def filter_example(max_audio_length, max_token_length):
"""Filter examples whose sequence length is over than the max""" def _wrapper(dataset): @tf.function def filter_fn(audio, text): return tf.math.logical_and(tf.shape(audio)[0] <= max_audio_length, tf.size(text) <= max_token_length) return dataset.filter(filter_fn) retur...
delta[:-1]], axis=0) # [TimeStep, AudioDim, 3] audio = tf.concat([audio, delta, deltas], axis=2) if text is None: return audio return audio, text def filter_example(max_audio_length, max_token_length):
64
64
81
11
52
cosmoquester/speech-recognition
speech_recognition/data.py
Python
filter_example
filter_example
331
341
331
331
666a26dc573e7429f5834d036334d96648c56a58
bigcode/the-stack
train
21e48d1002120cf3fee76e0f
train
function
def bfs(numbers, walls): # breadth first search: the first path to reach another number is # by definition the shortest path between those numbers lengths = {} for n in numbers: loc = numbers[n] paths = [[loc]] seen = set() seen.add(loc) while paths: ...
def bfs(numbers, walls): # breadth first search: the first path to reach another number is # by definition the shortest path between those numbers
lengths = {} for n in numbers: loc = numbers[n] paths = [[loc]] seen = set() seen.add(loc) while paths: curr_path = paths.pop(0) x,y = curr_path[-1] if (x, y) in numbers.values() and len(curr_path) > 1: lengths[(n, get_n...
return numbers, walls def get_num_from_pos(numbers, pos): for n in numbers: if numbers[n] == pos: return n def bfs(numbers, walls): # breadth first search: the first path to reach another number is # by definition the shortest path between those numbers
64
64
213
32
31
ambertests/adventofcode
aoc_2016/src/day24.py
Python
bfs
bfs
20
40
20
22
b5d76fb188899d4ba1449e328910aaa34b398878
bigcode/the-stack
train
c5e170a208a8d9b274ed83d4
train
function
def get_num_from_pos(numbers, pos): for n in numbers: if numbers[n] == pos: return n
def get_num_from_pos(numbers, pos):
for n in numbers: if numbers[n] == pos: return n
file).readlines()]): for x in range(len(line)): char = line[x] if char == '#': walls.add((x,y)) elif char.isdigit(): numbers[int(char)] = (x,y) return numbers, walls def get_num_from_pos(numbers, pos):
64
64
27
9
54
ambertests/adventofcode
aoc_2016/src/day24.py
Python
get_num_from_pos
get_num_from_pos
15
18
15
15
7c723e663c26b58f5bb5a742e4e0207689b3e09c
bigcode/the-stack
train
a613aa803207ee2f979bc690
train
function
def process_ducts(file): numbers = {} walls = set() for y, line in enumerate([line.strip() for line in open("input/%s.txt" % file).readlines()]): for x in range(len(line)): char = line[x] if char == '#': walls.add((x,y)) elif char.isdigit(): ...
def process_ducts(file):
numbers = {} walls = set() for y, line in enumerate([line.strip() for line in open("input/%s.txt" % file).readlines()]): for x in range(len(line)): char = line[x] if char == '#': walls.add((x,y)) elif char.isdigit(): numbers[int(cha...
from itertools import permutations def process_ducts(file):
12
64
93
7
4
ambertests/adventofcode
aoc_2016/src/day24.py
Python
process_ducts
process_ducts
3
13
3
3
c822ef206108d969261b34d4bda541f0c3bd666a
bigcode/the-stack
train
7b8b866757998e07be1d843c
train
function
def solve(file): lengths = {} distances1 = [] distances2 = [] numbers, walls = process_ducts(file) lengths = bfs(numbers, walls) for path in permutations(range(1, 8)): path = (0,) + path + (0,) distance = 0 for i in range(len(path) - 2): distance += lengths[(...
def solve(file):
lengths = {} distances1 = [] distances2 = [] numbers, walls = process_ducts(file) lengths = bfs(numbers, walls) for path in permutations(range(1, 8)): path = (0,) + path + (0,) distance = 0 for i in range(len(path) - 2): distance += lengths[(path[i], path[i+1...
+1),(x, y-1)] for dx, dy in moves: if (dx,dy) not in walls and (dx,dy) not in seen: paths.append(curr_path + [(dx, dy)]) seen.add((dx, dy)) return lengths def solve(file):
64
64
140
4
59
ambertests/adventofcode
aoc_2016/src/day24.py
Python
solve
solve
42
56
42
42
6634a6ad2b489e405b9a50faf9c36d1bfe7e9d3a
bigcode/the-stack
train
9f1ca9a9b96bfb22ea61d14c
train
function
def IsInt(v) -> bool: """ Check if the parameter can be int. v: Variable to check. SUCCESS Returns ``True``. FAILURE Returns ``False``. """ try: int(v) return True except Exception as ex: print(ex) return False
def IsInt(v) -> bool:
""" Check if the parameter can be int. v: Variable to check. SUCCESS Returns ``True``. FAILURE Returns ``False``. """ try: int(v) return True except Exception as ex: print(ex) return False
0, # to know if id has been warned warned=False, ) def CleanFloodDict(): global flood flood = dict() scheduler.add_job( CleanFloodDict, trigger=CronTrigger(hour=3, timezone=utc), ) def IsInt(v) -> bool:
64
64
68
8
56
annihilatorrrr/BotForReported
utils.py
Python
IsInt
IsInt
53
69
53
53
ea3b8933a4eb0406165f0ac7cfa6d7c97450da4d
bigcode/the-stack
train
6d816061648e867ac18d3c80
train
function
def CleanFloodDict(): global flood flood = dict()
def CleanFloodDict():
global flood flood = dict()
( times=list(), flood_wait_expiry_date=0, # from 0 to X minutes of wait depending on how much of an idiot is the user flood_wait_minutes=0, # to know if id has been warned warned=False, ) def CleanFloodDict():
63
64
14
5
58
annihilatorrrr/BotForReported
utils.py
Python
CleanFloodDict
CleanFloodDict
42
44
42
42
9b45e584a23862c5e3854cb3e322a29103995a60
bigcode/the-stack
train
01975ca12b57375b81d6f5ad
train
function
def SendBackup(client: pyrogram.Client): tmp_msg = client.send_message( chat_id=config["master"], text="I am preparing the automatic backup.", disable_notification=True, ) backup_name = Backup() client.send_document( chat_id=config["master"], document...
def SendBackup(client: pyrogram.Client):
tmp_msg = client.send_message( chat_id=config["master"], text="I am preparing the automatic backup.", disable_notification=True, ) backup_name = Backup() client.send_document( chat_id=config["master"], document=backup_name, disable_notificatio...
.endswith(".session-journal") ): # exclude current backup and session files file_path = os.path.join(folder_name, filename) print(file_path) f_tar_xz.add(file_path) db_management.DB.start() ...
64
64
100
9
54
annihilatorrrr/BotForReported
utils.py
Python
SendBackup
SendBackup
168
183
168
168
fec0da9a529c208b4e00d405c8f3acad5b492c76
bigcode/the-stack
train
d3d5f2a9448164475c8cc12e
train
function
def TimeFormatter(milliseconds: int) -> str: """ Adjust the time from milliseconds to the right measure. milliseconds (``int``): Number of milliseconds. SUCCESS Returns the adjusted measure (``str``). """ seconds, milliseconds = divmod(int(milliseconds), 1000) minutes, seconds =...
def TimeFormatter(milliseconds: int) -> str:
""" Adjust the time from milliseconds to the right measure. milliseconds (``int``): Number of milliseconds. SUCCESS Returns the adjusted measure (``str``). """ seconds, milliseconds = divmod(int(milliseconds), 1000) minutes, seconds = divmod(seconds, 60) hours, minutes = div...
MB else "") + ((f"{KB}KB, ") if KB else "") + ((f"{B}B, ") if B else "") + ((f"{b}b, ") if b else "") ) return tmp[:-2] def TimeFormatter(milliseconds: int) -> str:
63
64
178
10
53
annihilatorrrr/BotForReported
utils.py
Python
TimeFormatter
TimeFormatter
233
253
233
233
ff3e92206906e3808e6dbfd2a921ea7959df31f9
bigcode/the-stack
train
a0bb99d46d755e36ecc8b06f
train
function
def DFromUToTelegramProgress( current: int, total: int, msg: pyrogram.types.Message, text: str, start: float ) -> None: """ Use this method to update the progress of a download from/an upload to Telegram, this method is called every 512KB. Update message every ~4 seconds. client (:class:`Cli...
def DFromUToTelegramProgress( current: int, total: int, msg: pyrogram.types.Message, text: str, start: float ) -> None:
""" Use this method to update the progress of a download from/an upload to Telegram, this method is called every 512KB. Update message every ~4 seconds. client (:class:`Client <pyrogram.Client>`): The Client itself. current (``int``): Currently downloaded/uploaded bytes. total (``int`...
) minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) tmp = ( ((f"{days}d, ") if days else "") + ((f"{hours}h, ") if hours else "") + ((f"{minutes}m, ") if minutes else "") + ((f"{seconds}s, ") if seconds els...
153
154
516
36
117
annihilatorrrr/BotForReported
utils.py
Python
DFromUToTelegramProgress
DFromUToTelegramProgress
256
305
256
258
bed462db811fc9b0a875c0f64cadf2deea121dd7
bigcode/the-stack
train
6b219af8a92b572466bee515
train
function
def Backup() -> str: # empty downloads folder for filename in os.listdir("./downloads"): file_path = os.path.join("./downloads", filename) try: if os.path.isfile(file_path) or os.path.islink(file_path): os.unlink(file_path) elif os.path.isdir(file_p...
def Backup() -> str: # empty downloads folder
for filename in os.listdir("./downloads"): file_path = os.path.join("./downloads", filename) try: if os.path.isfile(file_path) or os.path.islink(file_path): os.unlink(file_path) elif os.path.isdir(file_path): shutil.rmtree(file_path) ...
pyrogram.types.Message>` itself. flags (``int``, *optional*): RegEx flags. """ def f(filter_, callback_query): matches = [i for i in filter_.regex.finditer(callback_query.data)] return bool(matches) return pyrogram.filters.create(f, regex=re.compile(pattern, ...
87
88
296
12
75
annihilatorrrr/BotForReported
utils.py
Python
Backup
Backup
133
165
133
134
ece5c6f4a0ceecb611a8ae60a25f7186d3cef04c
bigcode/the-stack
train
9b8b67aaefcc484880c9990d
train
function
def ExtractMedia(msg: pyrogram.types.Message) -> object: """Extract the media from a :obj:`Message <pyrogram.types.Message>`. msg (:obj:`Message <pyrogram.types.Message>`): Message from which you want to extract the media SUCCESS Returns the media (``object``). FAILURE Returns ``None``. ...
def ExtractMedia(msg: pyrogram.types.Message) -> object:
"""Extract the media from a :obj:`Message <pyrogram.types.Message>`. msg (:obj:`Message <pyrogram.types.Message>`): Message from which you want to extract the media SUCCESS Returns the media (``object``). FAILURE Returns ``None``. """ media = None if msg: if msg.media ...
), ) def IsInt(v) -> bool: """ Check if the parameter can be int. v: Variable to check. SUCCESS Returns ``True``. FAILURE Returns ``False``. """ try: int(v) return True except Exception as ex: print(ex) return False def ExtractMed...
83
83
277
13
69
annihilatorrrr/BotForReported
utils.py
Python
ExtractMedia
ExtractMedia
72
101
72
72
2d3d5ac0743c66ba9a6e1f59aa08a56ace223d25
bigcode/the-stack
train
9f29009a5f22ffcde9946dc8
train
function
def PrintUser(user: typing.Union[pyrogram.types.Chat, pyrogram.types.User]) -> str: return ( (user.first_name + (f" {user.last_name}" if user.last_name else "")) + " (" + (f"@{user.username} " if user.username else "") + f"#user{user.id})" )
def PrintUser(user: typing.Union[pyrogram.types.Chat, pyrogram.types.User]) -> str:
return ( (user.first_name + (f" {user.last_name}" if user.last_name else "")) + " (" + (f"@{user.username} " if user.username else "") + f"#user{user.id})" )
_type.MessageMediaType.VIDEO_NOTE: media = msg.video_note elif msg.media == pyrogram.enums.message_media_type.MessageMediaType.VOICE: media = msg.voice return media def PrintUser(user: typing.Union[pyrogram.types.Chat, pyrogram.types.User]) -> str:
64
64
79
22
41
annihilatorrrr/BotForReported
utils.py
Python
PrintUser
PrintUser
104
110
104
104
50ac3e777d8c3afc5262eb1e03ba44d71c89f267
bigcode/the-stack
train
0f46c217df6882a836197fdd
train
function
def GetDrives(): return [drive for drive in string.ascii_uppercase if os.path.exists(drive + ":\\")]
def GetDrives():
return [drive for drive in string.ascii_uppercase if os.path.exists(drive + ":\\")]
backup_name = Backup() client.send_document( chat_id=config["master"], document=backup_name, disable_notification=True, progress=DFromUToTelegramProgress, progress_args=(tmp_msg, "I am sending the automatic backup.", time.time()), ) def GetDrives():
63
64
27
5
58
annihilatorrrr/BotForReported
utils.py
Python
GetDrives
GetDrives
186
187
186
186
60aff7c4894815bf8885a4d036ad936aee428d07
bigcode/the-stack
train
156f2126bc4121c89a74652c
train
function
def filter_callback_regex(pattern: str, flags=None): """Filter messages that match a given RegEx pattern. Args: pattern (``str``): The RegEx pattern as string, it will be applied to the text of a message. When a pattern matches, all the `Match Objects <https://docs.python....
def filter_callback_regex(pattern: str, flags=None):
"""Filter messages that match a given RegEx pattern. Args: pattern (``str``): The RegEx pattern as string, it will be applied to the text of a message. When a pattern matches, all the `Match Objects <https://docs.python.org/3/library/re.html#match-objects>`_ ar...
user.first_name + (f" {user.last_name}" if user.last_name else "")) + " (" + (f"@{user.username} " if user.username else "") + f"#user{user.id})" ) def filter_callback_regex(pattern: str, flags=None):
63
64
171
11
52
annihilatorrrr/BotForReported
utils.py
Python
filter_callback_regex
filter_callback_regex
113
130
113
113
247a092c2bbee195475787c678b3f6a653752cd7
bigcode/the-stack
train
c198dbcbfe1df32b7e27f355
train
function
def InstantiateFloodDictionary(chat_id: int): # if chat_id not registered into the flood table register it if chat_id not in flood: flood[chat_id] = dict( times=list(), flood_wait_expiry_date=0, # from 0 to X minutes of wait depending on how much of an idiot is ...
def InstantiateFloodDictionary(chat_id: int): # if chat_id not registered into the flood table register it
if chat_id not in flood: flood[chat_id] = dict( times=list(), flood_wait_expiry_date=0, # from 0 to X minutes of wait depending on how much of an idiot is the user flood_wait_minutes=0, # to know if id has been warned warned=Fals...
(timezone=utc) scheduler.start() config = None with open(file="config.json", encoding="utf-8") as f: config = json.load(fp=f) flood = dict() def InstantiateFloodDictionary(chat_id: int): # if chat_id not registered into the flood table register it
64
64
97
23
41
annihilatorrrr/BotForReported
utils.py
Python
InstantiateFloodDictionary
InstantiateFloodDictionary
29
39
29
30
118304cd2771a7fc5ce7670c595b59f87d8047c5
bigcode/the-stack
train
f12045c4a4c4356cf7da3027
train
function
def SizeFormatter(b: int, human_readable: bool = False) -> str: """ Adjust the size from biys to the right measure. b (``int``): Number of bits. SUCCESS Returns the adjusted measure (``str``). """ if human_readable: B = float(b / 8) KB = float(1024) MB = fl...
def SizeFormatter(b: int, human_readable: bool = False) -> str:
""" Adjust the size from biys to the right measure. b (``int``): Number of bits. SUCCESS Returns the adjusted measure (``str``). """ if human_readable: B = float(b / 8) KB = float(1024) MB = float(pow(KB, 2)) GB = float(pow(KB, 3)) TB = flo...
disable_notification=True, ) backup_name = Backup() client.send_document( chat_id=config["master"], document=backup_name, disable_notification=True, progress=DFromUToTelegramProgress, progress_args=(tmp_msg, "I am sending the automatic backup.", time.time...
111
112
375
18
93
annihilatorrrr/BotForReported
utils.py
Python
SizeFormatter
SizeFormatter
190
230
190
190
d69bc85d19798f45f56f25d55cd9ac9ace99ffee
bigcode/the-stack
train
73b06f5e5627999002792e16
train
class
class WinRMListener(Model): """Describes Protocol and thumbprint of Windows Remote Management listener. :param protocol: Specifies the protocol of listener. <br><br> Possible values are: <br>**http** <br><br> **https**. Possible values include: 'Http', 'Https' :type protocol: str or ~azure.m...
class WinRMListener(Model):
"""Describes Protocol and thumbprint of Windows Remote Management listener. :param protocol: Specifies the protocol of listener. <br><br> Possible values are: <br>**http** <br><br> **https**. Possible values include: 'Http', 'Https' :type protocol: str or ~azure.mgmt.compute.v2015_06_15.mode...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
89
100
334
6
82
v-Ajnava/azure-sdk-for-python
azure-mgmt-compute/azure/mgmt/compute/v2015_06_15/models/win_rm_listener.py
Python
WinRMListener
WinRMListener
15
42
15
15
0e7975c9ff495ec7bcf43f4a8b47b47269d00125
bigcode/the-stack
train
f8368e8c4dd8842a36c7eb59
train
class
class UserNameList(ModelSimple): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The v...
class UserNameList(ModelSimple):
"""NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict with a c...
atomic, ie will succeed in their entirety or fail and have changed nothing. - If it returns a 40X status then it will have made no change to the system even if ome subset of the request would have succeeded. - If this contract cannot be met for any reason then this is an error and the response code will be 50X. # no...
256
256
1,995
7
248
symphony-mariacristina/symphony-bdk-python
symphony/bdk/gen/pod_model/user_name_list.py
Python
UserNameList
UserNameList
36
281
36
36
09bdef292d049a7fd2f49edc1cad88ba80912a5d
bigcode/the-stack
train
4daeb24dfc137c26a3964877
train
class
class KiboshService(Service): """ Kibosh is a fault-injecting FUSE filesystem. Attributes: INSTALL_ROOT The path of where Kibosh is installed. BINARY_NAME The Kibosh binary name. BINARY_PATH The path to the kibosh binary. ...
class KiboshService(Service):
""" Kibosh is a fault-injecting FUSE filesystem. Attributes: INSTALL_ROOT The path of where Kibosh is installed. BINARY_NAME The Kibosh binary name. BINARY_PATH The path to the kibosh binary. """ INSTALL_ROOT = "/opt...
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
196
256
1,317
6
189
aiven/kafka
tests/kafkatest/services/trogdor/kibosh.py
Python
KiboshService
KiboshService
23
153
23
23
c4dde7e2c0a4186c0f5e51e4fc513d18da4a6db3
bigcode/the-stack
train
19dc8a47b09f121584b1d913
train
function
def gen123(): yield 1 yield 2 yield 3
def gen123():
yield 1 yield 2 yield 3
__license__ = "MIT" __version__ = "1.0.0" __email__ = "priklygrayp@gmail.com" __status__ = "Development" '''Specift iterable sequences are lazy evaluated can model infinite sequences are composable into pipelines ''' def gen123():
64
64
19
4
60
PriklyGrayp/Noitacude.PY
Python - Fundamentals/Gernerators.py
Python
gen123
gen123
13
16
13
13
8a020009bcaa5830d10f4e80175c5cfa3a635651
bigcode/the-stack
train
0051966441be39f3f3d2da01
train
function
def gen246(): print('About to yield 2') yield 2 print('About to yield 4') yield 4 print('About to yield 6') yield 6 print('About to return')
def gen246():
print('About to yield 2') yield 2 print('About to yield 4') yield 4 print('About to yield 6') yield 6 print('About to return')
model infinite sequences are composable into pipelines ''' def gen123(): yield 1 yield 2 yield 3 g = gen123() print(g) print(next(g)) print(next(g)) print(next(g)) for v in gen123(): print(v) def gen246():
64
64
53
4
60
PriklyGrayp/Noitacude.PY
Python - Fundamentals/Gernerators.py
Python
gen246
gen246
27
34
27
27
3721c78134ed50e27941184bf490124423b048ac
bigcode/the-stack
train
3a9bbc97ca617a30e14c69f8
train
class
class RecordRelationsParentChild(RecordRelations): """Add/Remove operations for Parent-Child relations.""" allowed_metadata = ["volume"] def __init__(self): """Constructor.""" self.relation_types = PARENT_CHILD_RELATION_TYPES def _validate_relation_between_records(self, parent, child,...
class RecordRelationsParentChild(RecordRelations):
"""Add/Remove operations for Parent-Child relations.""" allowed_metadata = ["volume"] def __init__(self): """Constructor.""" self.relation_types = PARENT_CHILD_RELATION_TYPES def _validate_relation_between_records(self, parent, child, relation_name): """Validate relation betwe...
RecordRelations(object): """Record relations object.""" relation_types = [] def _validate_relation_type(self, relation_type): """Validate the given relation type.""" if relation_type not in self.relation_types: rel_names = ",".join([rt.name for rt in self.relation_types]) ...
194
194
649
9
184
topless/invenio-app-ils
invenio_app_ils/records_relations/api.py
Python
RecordRelationsParentChild
RecordRelationsParentChild
135
220
135
135
74b8968fe03a76bcbbbe16e04857a238a332c011
bigcode/the-stack
train
9e3492a03acaea5d38d2b452
train
class
class RecordRelations(object): """Record relations object.""" relation_types = [] def _validate_relation_type(self, relation_type): """Validate the given relation type.""" if relation_type not in self.relation_types: rel_names = ",".join([rt.name for rt in self.relation_types])...
class RecordRelations(object):
"""Record relations object.""" relation_types = [] def _validate_relation_type(self, relation_type): """Validate the given relation type.""" if relation_type not in self.relation_types: rel_names = ",".join([rt.name for rt in self.relation_types]) raise RecordRelati...
if not remaining_relations: del record[field][relation_name] else: record[field][relation_name] = remaining_relations # if there are 0 extra metadata left, delete the field if not record[field]: del record[fiel...
64
64
186
5
59
topless/invenio-app-ils
invenio_app_ils/records_relations/api.py
Python
RecordRelations
RecordRelations
109
132
109
109
85f5cb831cd61942716b4730aa3a2af4a86f75cc
bigcode/the-stack
train
20092e0903192b3b181e9225
train
class
class IlsRecordWithRelations(IlsRecord): """Add relations functionalities to records.""" @property def relations(self): """Get record relations.""" from .retriever import get_relations return get_relations(self) def clear(self): """Clear IlsRecordWithRelations record.""...
class IlsRecordWithRelations(IlsRecord):
"""Add relations functionalities to records.""" @property def relations(self): """Get record relations.""" from .retriever import get_relations return get_relations(self) def clear(self): """Clear IlsRecordWithRelations record.""" extra_metadata_field_name = Rec...
_type): """Remove sequence relation between previous and next records.""" self._validate_relation_type(relation_type) sequence_relation = SequenceRelation(relation_type) sequence_relation.remove( previous_pid=previous_rec.pid, next_pid=next_rec.pid ) class IlsRecordWi...
64
64
208
9
55
topless/invenio-app-ils
invenio_app_ils/records_relations/api.py
Python
IlsRecordWithRelations
IlsRecordWithRelations
405
433
405
405
6fffaa6b21dd9c7fa4451f4ab352521de42ed6c4
bigcode/the-stack
train
d6be69f80c19f2c969c85eff
train
class
class RecordRelationsSiblings(RecordRelations): """Add/Remove operations for Siblings relations.""" allowed_metadata = ["note"] def __init__(self): """Constructor.""" self.relation_types = SIBLINGS_RELATION_TYPES def _validate_relation_between_records(self, first, second, relation_nam...
class RecordRelationsSiblings(RecordRelations):
"""Add/Remove operations for Siblings relations.""" allowed_metadata = ["note"] def __init__(self): """Constructor.""" self.relation_types = SIBLINGS_RELATION_TYPES def _validate_relation_between_records(self, first, second, relation_name): """Validate relation between type of...
# check for allowed relation metadata (e.g. `volume`) has_allowed_metadata = any( [kwargs.get(metadata) for metadata in self.allowed_metadata] ) if relation_allows_metadata and has_allowed_metadata: # filter and keep only allowed metadata allowed = { ...
256
256
948
9
246
topless/invenio-app-ils
invenio_app_ils/records_relations/api.py
Python
RecordRelationsSiblings
RecordRelationsSiblings
223
348
223
223
e7119ed57255dbab62dad7b5ace74fdacf84464e
bigcode/the-stack
train
66e05a168feb12873d44ce29
train
class
class RecordRelationsExtraMetadata(object): """Utilities to manage the extra metadata field.""" _field_name = "relations_extra_metadata" @classmethod def field_name(cls): """Return field name property.""" return cls._field_name @classmethod def build_metadata_object(cls, pid_v...
class RecordRelationsExtraMetadata(object):
"""Utilities to manage the extra metadata field.""" _field_name = "relations_extra_metadata" @classmethod def field_name(cls): """Return field name property.""" return cls._field_name @classmethod def build_metadata_object(cls, pid_value, pid_type, **kwargs): """Build ...
# -*- coding: utf-8 -*- # # Copyright (C) 2019-2020 CERN. # # invenio-app-ils is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """APIs for CRUD operations around Records Relations.""" from copy import deepcopy from invenio_app_ils.err...
171
183
612
7
164
topless/invenio-app-ils
invenio_app_ils/records_relations/api.py
Python
RecordRelationsExtraMetadata
RecordRelationsExtraMetadata
24
106
24
24
ac25d4bec41eb8dbb0deba81580234feaa1767c1
bigcode/the-stack
train
7093c08795f6949019de550c
train
class
class RecordRelationsSequence(RecordRelations): """Add/Remove operations for Sequence relations.""" def __init__(self): """Constructor.""" self.relation_types = SEQUENCE_RELATION_TYPES def _validate_relation_between_records( self, previous_rec, next_rec, relation_name ): ...
class RecordRelationsSequence(RecordRelations):
"""Add/Remove operations for Sequence relations.""" def __init__(self): """Constructor.""" self.relation_types = SEQUENCE_RELATION_TYPES def _validate_relation_between_records( self, previous_rec, next_rec, relation_name ): """Validate relation between type of records."...
iblingsRelation(relation_type) sr.remove(pid=second.pid) # remove any metadata for this relation, if any # both first and second could have metadata for the relation RecordRelationsExtraMetadata.remove_extra_metadata_from( first, relation_type.name, second.pid.pid_value, sec...
111
111
370
8
102
topless/invenio-app-ils
invenio_app_ils/records_relations/api.py
Python
RecordRelationsSequence
RecordRelationsSequence
351
402
351
351
8a5d9091b98da999d0d614088b4bc69406cb498b
bigcode/the-stack
train
a6207fcf824a1422e0434b6d
train
class
class Output: def __init__(self, indent_string, baseIndentString=''): self.indent_string = indent_string self.baseIndentString = baseIndentString self.indent_cache = [baseIndentString] self.baseIndentLength = len(baseIndentString) self.indent_length = len(indent_string) ...
class Output:
def __init__(self, indent_string, baseIndentString=''): self.indent_string = indent_string self.baseIndentString = baseIndentString self.indent_cache = [baseIndentString] self.baseIndentLength = len(baseIndentString) self.indent_length = len(indent_string) self.raw =...
_count += len(item) self.__empty = False def pop(self): item = None if not self.is_empty(): item = self.__items.pop() self.__character_count -= len(item) self.__empty = len(self.__items) == 0 return item def remove_indent(self): if se...
202
202
674
3
198
bitwiseman/beautifier.io
python/jsbeautifier/core/output.py
Python
Output
Output
90
190
90
90
cdcd42635b745cd01991ad187ad363f4ca3f21da
bigcode/the-stack
train
1198f6b74ac11e985b68679a
train
class
class OutputLine: def __init__(self, parent): self.__parent = parent self.__character_count = 0 self.__indent_count = -1 self.__items = [] self.__empty = True def get_character_count(self): return self.__character_count def is_empty(self): return se...
class OutputLine:
def __init__(self, parent): self.__parent = parent self.__character_count = 0 self.__indent_count = -1 self.__items = [] self.__empty = True def get_character_count(self): return self.__character_count def is_empty(self): return self.__empty de...
BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH T...
107
107
358
4
102
bitwiseman/beautifier.io
python/jsbeautifier/core/output.py
Python
OutputLine
OutputLine
31
87
31
31
5f2d4d63c5e761f262a49b31cec4e6c998c54824
bigcode/the-stack
train
44bdcc49f7b0aee2b4012303
train
class
class WeatherConstraint(Constraint): def __init__(self, start_time, end_time, cloud_threshold, cloud_average_threshold, rain_threshold): """Custom dynamic constraint that evaluates current weather conditions """ today_date = datetime.utcnow().date() start_datetime = datetime.strpti...
class WeatherConstraint(Constraint):
def __init__(self, start_time, end_time, cloud_threshold, cloud_average_threshold, rain_threshold): """Custom dynamic constraint that evaluates current weather conditions """ today_date = datetime.utcnow().date() start_datetime = datetime.strptime(start_time,'%Y-%m-%d %H:%M') ...
from tso.importer.weather_importer import WeatherImporter as WeImp from astroplan import Constraint from datetime import datetime, timedelta, timezone """ Weather Constraint Determines if it is possible to observe with regards to the current weather conditions """ class WeatherConstraint(Constraint):
56
243
811
6
50
elijah-ward/TSO
src/tso/scheduler/weather_constraint.py
Python
WeatherConstraint
WeatherConstraint
12
114
12
13
86549391ae53ed9eb722c5534fa49f621f16fe44
bigcode/the-stack
train
4c13e019d9a072d43193b2e0
train
function
def generate_gif(env, policy, filepath, resize_to=None, duration=50): """ Store a gif from the episode frames. Parameters ---------- env : gym environment The environment to record from. policy : keras-gym policy object The policy that is used to take actions. filepath :...
def generate_gif(env, policy, filepath, resize_to=None, duration=50):
""" Store a gif from the episode frames. Parameters ---------- env : gym environment The environment to record from. policy : keras-gym policy object The policy that is used to take actions. filepath : str Location of the output gif file. resize_to : tuple ...
---------- env : gym environment A potentially wrapped environment. attr : str The attribute name. max_depth : positive int, optional The maximum depth of wrappers to traverse. """ e = env for i in range(max_depth): if hasattr(e, attr): return g...
131
131
439
18
112
axb2035/keras-gym
keras_gym/utils/helpers.py
Python
generate_gif
generate_gif
634
701
634
634
6faa2d709744d1d8d7e214b7c338dc7075c96e2d
bigcode/the-stack
train
35fc0f543a865e82453d0bdf
train
function
def is_policy(obj, check_updateable=False): """ Check whether an object is a :term:`state value function`, or V-function. Parameters ---------- obj Object to check. check_updateable : bool, optional If the obj is a policy, also check whether or not the policy is updat...
def is_policy(obj, check_updateable=False):
""" Check whether an object is a :term:`state value function`, or V-function. Parameters ---------- obj Object to check. check_updateable : bool, optional If the obj is a policy, also check whether or not the policy is updateable. Returns ------- bool ...
(obj, BaseQTypeI) elif qtype in (2, 2., '2', 'ii', 'II'): return isinstance(obj, BaseQTypeII) else: raise ValueError("unexpected qtype: {}".format(qtype)) def is_policy(obj, check_updateable=False):
64
64
160
10
54
axb2035/keras-gym
keras_gym/utils/helpers.py
Python
is_policy
is_policy
762
790
762
762
000c2625fb94a3216332ca67d2689410f1efe2a0
bigcode/the-stack
train
7705e86f0f82b132df10d456
train
function
def idx(arr, axis=0): """ Given a numpy array, return its corresponding integer index array. Parameters ---------- arr : array Input array. axis : int, optional The axis along which we'd like to get an index. Returns ------- index : 1d array, shape: arr.shape[axis]...
def idx(arr, axis=0):
""" Given a numpy array, return its corresponding integer index array. Parameters ---------- arr : array Input array. axis : int, optional The axis along which we'd like to get an index. Returns ------- index : 1d array, shape: arr.shape[axis] An index arra...
a = env.action_space.sample() a_next = env.action_space.sample() s_next, r, done, info = env.step(a) return s, a, r, s_next, a_next, done, info finally: env.close() def idx(arr, axis=0):
64
64
114
8
56
axb2035/keras-gym
keras_gym/utils/helpers.py
Python
idx
idx
143
162
143
143
16c0bf4af0e4d85925d84ad733f84da52429a7fb
bigcode/the-stack
train
4c5abeddef8d4ac05a7294a5
train
function
def check_numpy_array( arr, ndim=None, ndim_min=None, dtype=None, shape=None, axis_size=None, axis=None): """ This helper function is mostly for internal use. It allows you to check a few common properties of a numpy array. Raises ------ N...
def check_numpy_array( arr, ndim=None, ndim_min=None, dtype=None, shape=None, axis_size=None, axis=None):
""" This helper function is mostly for internal use. It allows you to check a few common properties of a numpy array. Raises ------ NumpyArrayCheckError If one of the checks fails, it raises a :class:`NumpyArrayCheckError`. """ if not isinstance(arr, np.ndarray): rais...
): """ Given a numpy array, return its corresponding integer index array. Parameters ---------- arr : array Input array. axis : int, optional The axis along which we'd like to get an index. Returns ------- index : 1d array, shape: arr.shape[axis] An index a...
141
141
473
34
107
axb2035/keras-gym
keras_gym/utils/helpers.py
Python
check_numpy_array
check_numpy_array
165
221
165
172
ad0b423f659b1d785a445a3a25b1e23989cf2b7e
bigcode/the-stack
train
9f63ba47867276a1abe83f95
train
function
def check_tensor( tensor, ndim=None, ndim_min=None, dtype=None, int_shape=None, axis_size=None, axis=None): """ This helper function is mostly for internal use. It allows you to check a few common properties of a numpy array. Raises ------ ...
def check_tensor( tensor, ndim=None, ndim_min=None, dtype=None, int_shape=None, axis_size=None, axis=None):
""" This helper function is mostly for internal use. It allows you to check a few common properties of a numpy array. Raises ------ TensorCheckError If one of the checks fails, it raises a :class:`TensorCheckError`. """ if not isinstance(tensor, tf.Tensor): raise Tens...
None and axis is not None sizes = [axis_size] if not isinstance(axis_size, (list, tuple, set)) else axis_size # noqa: E501 if check and arr.shape[axis] not in sizes: raise NumpyArrayCheckError( "expected input with size(s) {} along axis {}, got shape: {}" .format(axis_size, axi...
120
120
400
34
86
axb2035/keras-gym
keras_gym/utils/helpers.py
Python
check_tensor
check_tensor
224
277
224
231
fd89c019bd7a0cf07c55424755a9348fb83f4f52
bigcode/the-stack
train
f59887118d2d1541e2d58966
train
function
def is_vfunction(obj): """ Check whether an object is a :term:`state value function`, or V-function. Parameters ---------- obj Object to check. Returns ------- bool Whether ``obj`` is a V-function. """ # import at runtime to avoid circular dependence from...
def is_vfunction(obj):
""" Check whether an object is a :term:`state value function`, or V-function. Parameters ---------- obj Object to check. Returns ------- bool Whether ``obj`` is a V-function. """ # import at runtime to avoid circular dependence from ..function_approximato...
frames.append(frame) # generate gif frames[0].save( fp=filepath, format='GIF', append_images=frames[1:], save_all=True, duration=duration, loop=0) logger.info("recorded episode to: {}".format(filepath)) def is_vfunction(obj):
64
64
90
6
58
axb2035/keras-gym
keras_gym/utils/helpers.py
Python
is_vfunction
is_vfunction
704
723
704
704
c2485cb593fb651d2d59f48238dae9b2ddd2cad0
bigcode/the-stack
train
7146a63abc7314a542b2ee56
train
function
def feature_vector(x, space): """ Create a feature vector out of a state observation :math:`s` or an action :math:`a`. This is used in the :class:`DefaultPreprocessor`. Parameters ---------- x : state or action A state observation :math:`s` or an action :math:`a`. space : gym spac...
def feature_vector(x, space):
""" Create a feature vector out of a state observation :math:`s` or an action :math:`a`. This is used in the :class:`DefaultPreprocessor`. Parameters ---------- x : state or action A state observation :math:`s` or an action :math:`a`. space : gym space A gym space, e.g. :...
than `i`. dtype : str or datatype The output data type, default is `'float'`. Returns ------- x : 1d array of length n The dense one-hot encoded vector. """ if not 0 <= i < n: raise ValueError("i must be a non-negative and smaller than n") x = np.zeros(int(n), d...
109
109
365
7
101
axb2035/keras-gym
keras_gym/utils/helpers.py
Python
feature_vector
feature_vector
70
109
70
70
283568c4fe5562a8fccb1ab4bd9c82e0f60811d5
bigcode/the-stack
train
730f3ecba1a5c0d05234d780
train
function
def softmax(arr, axis=-1): """ Compute the softmax (normalized point-wise exponential). **Note:** This is the *numpy* implementation. Parameters ---------- arr : numpy array The input array. axis : int, optional The axis along which to normalize, default is 0. Retur...
def softmax(arr, axis=-1):
""" Compute the softmax (normalized point-wise exponential). **Note:** This is the *numpy* implementation. Parameters ---------- arr : numpy array The input array. axis : int, optional The axis along which to normalize, default is 0. Returns ------- out : ar...
------- index_array : ndarray of ints Array of indices into the array. It has the same shape as `a.shape` with the dimension along `axis` removed. """ return argmin(-arr, axis=axis, random_state=random_state) def softmax(arr, axis=-1):
64
64
200
9
55
axb2035/keras-gym
keras_gym/utils/helpers.py
Python
softmax
softmax
412
442
412
412
7bab7a5336db7b92c334b5afa7c845cb41de3c0a
bigcode/the-stack
train
fd959d24e6ff02e56cf726a8
train
function
def has_env_attr(env, attr, max_depth=100): """ Check if a potentially wrapped environment has a given attribute. Parameters ---------- env : gym environment A potentially wrapped environment. attr : str The attribute name. max_depth : positive int, optional The...
def has_env_attr(env, attr, max_depth=100):
""" Check if a potentially wrapped environment has a given attribute. Parameters ---------- env : gym environment A potentially wrapped environment. attr : str The attribute name. max_depth : positive int, optional The maximum depth of wrappers to traverse. ...
for j in range(i + 1): k = num_frames - j - 1 M[k, i] = pow(-1, j) * binom(i, j) return K.constant(M, dtype=dtype) def has_env_attr(env, attr, max_depth=100):
64
64
120
13
51
axb2035/keras-gym
keras_gym/utils/helpers.py
Python
has_env_attr
has_env_attr
566
593
566
566
fc93c9770dcddad35fc32f1f0b74465a203689d8
bigcode/the-stack
train
f1923b77bfafd92c1d35adf2
train
function
def log_softmax_tf(Z, axis=-1): """ Compute the log-softmax. **Note:** This is the *tensorflow* implementation. Parameters ---------- Z : Tensor The input logits. axis : int, optional The axis along which to normalize, default is 0. Returns ------- out : Ten...
def log_softmax_tf(Z, axis=-1):
""" Compute the log-softmax. **Note:** This is the *tensorflow* implementation. Parameters ---------- Z : Tensor The input logits. axis : int, optional The axis along which to normalize, default is 0. Returns ------- out : Tensor of same shape as input ...
# center before clipping Z = np.clip(Z, -30, 30) # avoid over/underflow log_P = Z - np.log(np.sum(np.exp(Z), axis=axis, keepdims=True)) return log_P def log_softmax_tf(Z, axis=-1):
64
64
171
11
52
axb2035/keras-gym
keras_gym/utils/helpers.py
Python
log_softmax_tf
log_softmax_tf
476
503
476
476
7dd49c4ffd6ca53e2e95aa3853cddcb488f386b1
bigcode/the-stack
train
ccc09178737ea8d38858f328
train
function
def get_env_attr(env, attr, default='__ERROR__', max_depth=100): """ Get the given attribute from a potentially wrapped environment. Note that the wrapped envs are traversed from the outside in. Once the attribute is found, the search stops. This means that an inner wrapped env may carry the same (...
def get_env_attr(env, attr, default='__ERROR__', max_depth=100):
""" Get the given attribute from a potentially wrapped environment. Note that the wrapped envs are traversed from the outside in. Once the attribute is found, the search stops. This means that an inner wrapped env may carry the same (possibly conflicting) attribute. This situation is *not* reso...
e = env for i in range(max_depth): if hasattr(e, attr): return True if not hasattr(e, 'env'): break e = e.env return False def get_env_attr(env, attr, default='__ERROR__', max_depth=100):
64
64
208
19
44
axb2035/keras-gym
keras_gym/utils/helpers.py
Python
get_env_attr
get_env_attr
596
631
596
596
5ed9f417ca1b3a1cfbf2cad3741c72b829796ab4
bigcode/the-stack
train
ae4f8ad9eb4e2bc47a9ce601
train
function
def project_onto_actions_tf(Y, A): """ Project tensor onto specific actions taken: **tensorflow** implementation. **Note**: This only applies to discrete action spaces. Parameters ---------- Y : 2d Tensor, shape: [batch_size, num_actions] The tensor to project down. A : 1d Tensor...
def project_onto_actions_tf(Y, A):
""" Project tensor onto specific actions taken: **tensorflow** implementation. **Note**: This only applies to discrete action spaces. Parameters ---------- Y : 2d Tensor, shape: [batch_size, num_actions] The tensor to project down. A : 1d Tensor, shape: [batch_size] The ...
check_numpy_array(Y, ndim=2) check_numpy_array(A, ndim=1, dtype='int') check_numpy_array(Y, axis_size=A.shape[0], axis=0) # same batch size return Y[idx(Y), A] def project_onto_actions_tf(Y, A):
64
64
209
10
54
axb2035/keras-gym
keras_gym/utils/helpers.py
Python
project_onto_actions_tf
project_onto_actions_tf
309
337
309
309
3defd2ad2b0018bac070e712bc1290ab2fb74ee2
bigcode/the-stack
train
3073a7f538368cc14053df4d
train
function
def diff_transform_matrix(num_frames, dtype='float32'): """ A helper function that implements discrete differentiation for stacked state observations. Let's say we have a feature vector :math:`X` consisting of four stacked frames, i.e. the shape would be: ``[batch_size, height, width, 4]``. Fo...
def diff_transform_matrix(num_frames, dtype='float32'):
""" A helper function that implements discrete differentiation for stacked state observations. Let's say we have a feature vector :math:`X` consisting of four stacked frames, i.e. the shape would be: ``[batch_size, height, width, 4]``. For instance, diff-transform matrix with ``num_frames=4`` ...
:** This is the *tensorflow* implementation. Parameters ---------- Z : Tensor The input logits. axis : int, optional The axis along which to normalize, default is 0. Returns ------- out : Tensor of same shape as input The entries may be interpreted as log-probab...
160
160
535
12
147
axb2035/keras-gym
keras_gym/utils/helpers.py
Python
diff_transform_matrix
diff_transform_matrix
506
563
506
506
011c85bd6e1ab7689cf14361747413aff8ab2c11
bigcode/the-stack
train
6bd405c64ae07dfa19b1258d
train
function
def project_onto_actions_np(Y, A): """ Project tensor onto specific actions taken: **numpy** implementation. **Note**: This only applies to discrete action spaces. Parameters ---------- Y : 2d array, shape: [batch_size, num_actions] The tensor to project down. A : 1d array, shape...
def project_onto_actions_np(Y, A):
""" Project tensor onto specific actions taken: **numpy** implementation. **Note**: This only applies to discrete action spaces. Parameters ---------- Y : 2d array, shape: [batch_size, num_actions] The tensor to project down. A : 1d array, shape: [batch_size] The batch o...
None if check and K.int_shape(tensor)[axis] != axis_size: raise TensorCheckError( "expected input with size {} along axis {}, got shape: {}" .format(axis_size, axis, K.int_shape(tensor))) def project_onto_actions_np(Y, A):
63
64
177
10
53
axb2035/keras-gym
keras_gym/utils/helpers.py
Python
project_onto_actions_np
project_onto_actions_np
280
306
280
280
78d69bfaac14171a2d2d88794200baa1f7cc704e
bigcode/the-stack
train
042b709832ac634760d955c7
train
function
def one_hot(i, n, dtype='float'): """ Create a dense one-hot encoded vector. Parameters ---------- i : int The index of the non-zero entry. n : int The dimensionality of the dense vector. Note that `n` must be greater than `i`. dtype : str or datatype Th...
def one_hot(i, n, dtype='float'):
""" Create a dense one-hot encoded vector. Parameters ---------- i : int The index of the non-zero entry. n : int The dimensionality of the dense vector. Note that `n` must be greater than `i`. dtype : str or datatype The output data type, default is `'f...
', 'is_qfunction', 'is_vfunction', 'log_softmax', 'log_softmax_tf', 'one_hot', 'project_onto_actions_np', 'project_onto_actions_tf', 'softmax', ) def one_hot(i, n, dtype='float'):
64
64
167
11
53
axb2035/keras-gym
keras_gym/utils/helpers.py
Python
one_hot
one_hot
37
67
37
37
021309dd7b9526df800e79ddf22165c8fbea8fcd
bigcode/the-stack
train
50a7325cfab48db3a2b67eb4
train
function
def argmax(arr, axis=None, random_state=None): """ This is a little hack to ensure that argmax breaks ties randomly, which is something that :func:`numpy.argmax` doesn't do. *Note: random tie breaking is only done for 1d arrays; for multidimensional inputs, we fall back to the numpy version.* ...
def argmax(arr, axis=None, random_state=None):
""" This is a little hack to ensure that argmax breaks ties randomly, which is something that :func:`numpy.argmax` doesn't do. *Note: random tie breaking is only done for 1d arrays; for multidimensional inputs, we fall back to the numpy version.* Parameters ---------- a : array_like ...
not isinstance(random_state, np.random.RandomState): # treat input random_state as seed random_state = np.random.RandomState(random_state) return random_state.choice(candidates) else: return np.argmin(arr, axis=axis) def argmax(arr, axis=None, random_state=None):
64
64
210
12
52
axb2035/keras-gym
keras_gym/utils/helpers.py
Python
argmax
argmax
381
409
381
381
d5df70120f59530f7344767587c08776c07d6e3b
bigcode/the-stack
train
9a356315891ab989f24501f4
train
function
def get_transition(env): """ Generate a transition from the environment. This basically does a single step on the environment and then closes it. Parameters ---------- env : gym environment A gym environment. Returns ------- s, a, r, s_next, a_next, done, info : tuple...
def get_transition(env):
""" Generate a transition from the environment. This basically does a single step on the environment and then closes it. Parameters ---------- env : gym environment A gym environment. Returns ------- s, a, r, s_next, a_next, done, info : tuple A single transi...
else: raise NotImplementedError( "haven't implemented a preprocessor for space type: {}" .format(type(space))) assert x.ndim == 1, "x must be 1d array, got shape: {}".format(x.shape) return x def get_transition(env):
64
64
167
5
58
axb2035/keras-gym
keras_gym/utils/helpers.py
Python
get_transition
get_transition
112
140
112
112
0ed1ac18fec2ff26c8230d78c74d68cee5eb990f
bigcode/the-stack
train
e129e2a185845a5ad31edfe6
train
function
def argmin(arr, axis=None, random_state=None): """ This is a little hack to ensure that argmin breaks ties randomly, which is something that :func:`numpy.argmin` doesn't do. *Note: random tie breaking is only done for 1d arrays; for multidimensional inputs, we fall back to the numpy version.* ...
def argmin(arr, axis=None, random_state=None):
""" This is a little hack to ensure that argmin breaks ties randomly, which is something that :func:`numpy.argmin` doesn't do. *Note: random tie breaking is only done for 1d arrays; for multidimensional inputs, we fall back to the numpy version.* Parameters ---------- a : array_like ...
if there's a better way to do this. batch_size = tf.cast(K.shape(A)[0], tf.int64) idx = tf.range(batch_size, dtype=A.dtype) indices = tf.stack([idx, A], axis=1) Y_projected = tf.gather_nd(Y, indices) # shape: [batch_size] return Y_projected def argmin(arr, axis=None, random_state=None):
90
90
300
12
77
axb2035/keras-gym
keras_gym/utils/helpers.py
Python
argmin
argmin
340
378
340
340
e726419911171ca7cd5b108dc629c3d72cdea4fa
bigcode/the-stack
train
50f9fdcff0e3bfc15f739e17
train
function
def log_softmax(arr, axis=-1): """ Compute the log-softmax. **Note:** This is the *numpy* implementation. Parameters ---------- arr : numpy array The input array. axis : int, optional The axis along which to normalize, default is 0. Returns ------- out : arr...
def log_softmax(arr, axis=-1):
""" Compute the log-softmax. **Note:** This is the *numpy* implementation. Parameters ---------- arr : numpy array The input array. axis : int, optional The axis along which to normalize, default is 0. Returns ------- out : array of same shape The e...
clipping Z = np.clip(Z, -30, 30) # avoid over/underflow exp_Z = np.exp(Z) p = exp_Z / np.sum(exp_Z, axis=axis, keepdims=True) return p def log_softmax(arr, axis=-1):
64
64
179
10
53
axb2035/keras-gym
keras_gym/utils/helpers.py
Python
log_softmax
log_softmax
445
473
445
445
3ccf7b60a82be98c8670322c15905fd3ec082b15
bigcode/the-stack
train
e312e8a52d37bddfc147e572
train
function
def is_qfunction(obj, qtype=None): """ Check whether an object is a state-action value function, or Q-function. Parameters ---------- obj Object to check. qtype : 1 or 2, optional Check for specific Q-function type, i.e. :term:`type-I <type-I state-action value functi...
def is_qfunction(obj, qtype=None):
""" Check whether an object is a state-action value function, or Q-function. Parameters ---------- obj Object to check. qtype : 1 or 2, optional Check for specific Q-function type, i.e. :term:`type-I <type-I state-action value function>` or :term:`type-II <type-II sta...
. Parameters ---------- obj Object to check. Returns ------- bool Whether ``obj`` is a V-function. """ # import at runtime to avoid circular dependence from ..function_approximators.base import BaseV return isinstance(obj, BaseV) def is_qfunction(obj, qtype=N...
75
75
252
10
65
axb2035/keras-gym
keras_gym/utils/helpers.py
Python
is_qfunction
is_qfunction
726
759
726
726
87eea2e472d68f16099438615f42c95f3bdc60f7
bigcode/the-stack
train
be854bd3902e7ce872895ce6
train
class
class InnerOpsDescribeAccessControlListsRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Slb', '2014-05-15', 'InnerOpsDescribeAccessControlLists','asdfdsf') def get_access_key_id(self): return self.get_query_params().get('access_key_id') def set_access_key_id(self,access_key_id): se...
class InnerOpsDescribeAccessControlListsRequest(RpcRequest):
def __init__(self): RpcRequest.__init__(self, 'Slb', '2014-05-15', 'InnerOpsDescribeAccessControlLists','asdfdsf') def get_access_key_id(self): return self.get_query_params().get('access_key_id') def set_access_key_id(self,access_key_id): self.add_query_param('access_key_id',access_key_id) def get_...
this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIO...
127
127
426
12
114
sdk-team/aliyun-openapi-python-sdk
aliyun-python-sdk-slb/aliyunsdkslb/request/v20140515/InnerOpsDescribeAccessControlListsRequest.py
Python
InnerOpsDescribeAccessControlListsRequest
InnerOpsDescribeAccessControlListsRequest
21
78
21
22
fb90daf7195284fe3efc5b6b2b04027e98b6451c
bigcode/the-stack
train
223849382728ea33c2e97189
train
function
def _fuzzy_match(query, arr): """ will compare all elements in @arr against the @query to see if they are similar similar implies one is a substring of the other or the two words are 1 change apart Ex. bird and bord are similar Ex. bird and birdwaj are similar Ex. bird and bead are not similar...
def _fuzzy_match(query, arr):
""" will compare all elements in @arr against the @query to see if they are similar similar implies one is a substring of the other or the two words are 1 change apart Ex. bird and bord are similar Ex. bird and birdwaj are similar Ex. bird and bead are not similar """ def similar_word(...
cp value attached """ storage_name_without_hcp, _, _ = normalized_fqdn.partition('-hcp-') if len(storage_name_without_hcp) > CONST_CONTAINER_NAME_MAX_LENGTH: storage_name_without_hcp = storage_name_without_hcp[:CONST_CONTAINER_NAME_MAX_LENGTH] return storage_name_without_hcp.rstrip('-') def ...
81
81
271
9
72
haroonf/azure-cli-extensions
src/aks-preview/azext_aks_preview/_helpers.py
Python
_fuzzy_match
_fuzzy_match
26
67
26
26
e79f40b2f2161ce76763217c5b9e3a167bd50bea
bigcode/the-stack
train
047398339fd85fb805493824
train
function
def _trim_fqdn_name_containing_hcp(normalized_fqdn: str) -> str: """ Trims the storage blob name and takes everything prior to "-hcp-". Currently it is displayed wrong: i.e. at time of creation cli has following limitation: https://docs.microsoft.com/en-us/azure/azure-resource-manager/templates/ ...
def _trim_fqdn_name_containing_hcp(normalized_fqdn: str) -> str:
""" Trims the storage blob name and takes everything prior to "-hcp-". Currently it is displayed wrong: i.e. at time of creation cli has following limitation: https://docs.microsoft.com/en-us/azure/azure-resource-manager/templates/ error-storage-account-name :param normalized_fqdn: storage ...
c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- from ._consts import CONST_CONTAINER_NAME_MAX_LENGTH def _trim_fqdn_name_containing...
64
64
182
22
41
haroonf/azure-cli-extensions
src/aks-preview/azext_aks_preview/_helpers.py
Python
_trim_fqdn_name_containing_hcp
_trim_fqdn_name_containing_hcp
8
23
8
8
597119bbbdf4e64bfeef79b8943c05c32b72a2af
bigcode/the-stack
train
20c90b01609254547dee98fc
train
function
def create_app(): app = Flask(__name__, instance_relative_config = False) app.config.from_object('config.Config') db.init_app(app) login_manager.init_app(app) bcrypt.init_app(app) migrate.init_app(app, db) with app.app_context(): from saien.level0.views import l...
def create_app():
app = Flask(__name__, instance_relative_config = False) app.config.from_object('config.Config') db.init_app(app) login_manager.init_app(app) bcrypt.init_app(app) migrate.init_app(app, db) with app.app_context(): from saien.level0.views import level0 from...
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_bcrypt import Bcrypt from flask_migrate import Migrate db = SQLAlchemy() migrate = Migrate() login_manager = LoginManager() bcrypt = Bcrypt() def create_app():
62
64
120
4
58
B46qqq/saien
saien/__init__.py
Python
create_app
create_app
12
32
12
12
f976f750a0271d1a1f0c19a57109df1f57b732d0
bigcode/the-stack
train
f5f7306db95ee641d8ff788a
train
function
def create_folder(folder_name): if not os.path.exists(folder_name): os.mkdir(folder_name)
def create_folder(folder_name):
if not os.path.exists(folder_name): os.mkdir(folder_name)
detector = dlib.get_frontal_face_detector() shape_predictor = dlib.shape_predictor("models/shape_predictor_68_face_landmarks.dat") face_aligner = FaceAligner(shape_predictor, desiredFaceWidth=200) FACE_DIR = "incept/" def create_folder(folder_name):
63
64
21
6
57
TheGithubMafia/TheGithubMafia_9c406a97-d178-4f18-945d-d11c981452c3
create_face.py
Python
create_folder
create_folder
15
17
15
15
544bb315eb6623d080df9307ea7fe2a21b2264be
bigcode/the-stack
train
d33c5482efe6923d3f295f5c
train
function
def main(): create_folder(FACE_DIR) while True: name=input("EnterName: ") face_id = input("Enter id for face: ") try: face_id = int(face_id) face_folder = FACE_DIR + str(face_id) + "/" create_folder(face_folder) break except: ...
def main():
create_folder(FACE_DIR) while True: name=input("EnterName: ") face_id = input("Enter id for face: ") try: face_id = int(face_id) face_folder = FACE_DIR + str(face_id) + "/" create_folder(face_folder) break except: print(...
import cv2 import numpy as numpy import os, time import dlib from imutils import face_utils from imutils.face_utils import FaceAligner detector = dlib.get_frontal_face_detector() shape_predictor = dlib.shape_predictor("models/shape_predictor_68_face_landmarks.dat") face_aligner = FaceAligner(shape_predictor, desiredFa...
117
118
396
3
114
TheGithubMafia/TheGithubMafia_9c406a97-d178-4f18-945d-d11c981452c3
create_face.py
Python
main
main
20
69
20
20
a19ebad6100a880a7e60432800a4e471aa5a8223
bigcode/the-stack
train
a1de6b571c3a4d8284e9b959
train
function
def _hook(name,value,out): if name == 'drop': if len(value) <= 0 : out.write("{}") return True all_drop_item = value.split('|') out.write("{"); for i in range(len(all_drop_item)): out.write(all_drop_item[i] + ",") out.write("}") return True return False
def _hook(name,value,out):
if name == 'drop': if len(value) <= 0 : out.write("{}") return True all_drop_item = value.split('|') out.write("{"); for i in range(len(all_drop_item)): out.write(all_drop_item[i] + ",") out.write("}") return True return False
import os import sys def _hook(name,value,out):
13
64
77
7
5
yzx4036/xlua-framework-ugui-comblock
ConfigData/trunk/tools/hook/item_hook.py
Python
_hook
_hook
4
15
4
4
93032afa81c14c2d01229abffea19130aca791cb
bigcode/the-stack
train
e7e0cca6df134c454638d4b5
train
function
def _declare_flags(): """Declare flags; not invoked when this module is imported as a library.""" flags.DEFINE_enum('method', None, models_lib.METHODS, 'Name of modeling method.') flags.DEFINE_string('output_dir', None, 'Output directory.') flags.DEFINE_integer('test_level', 0, 'Testing leve...
def _declare_flags():
"""Declare flags; not invoked when this module is imported as a library.""" flags.DEFINE_enum('method', None, models_lib.METHODS, 'Name of modeling method.') flags.DEFINE_string('output_dir', None, 'Output directory.') flags.DEFINE_integer('test_level', 0, 'Testing level.') flags.DEFINE_in...
uq_benchmark_2019 import experiment_utils from uq_benchmark_2019.criteo import data_lib from uq_benchmark_2019.criteo import hparams_lib from uq_benchmark_2019.criteo import models_lib FLAGS = flags.FLAGS def _declare_flags():
64
64
109
5
58
kiss2u/google-research
uq_benchmark_2019/criteo/run_train.py
Python
_declare_flags
_declare_flags
36
43
36
36
563f950024456d17138530fec0c95aac5ad9c560
bigcode/the-stack
train
6b4a12258964d250ea9651e9
train
function
def run(method, output_dir, num_epochs, fake_data=False, fake_training=False): """Trains a model and records its predictions on configured datasets. Args: method: Modeling method to experiment with. output_dir: Directory to record the trained model and output stats. num_epochs: Number of training epoch...
def run(method, output_dir, num_epochs, fake_data=False, fake_training=False):
"""Trains a model and records its predictions on configured datasets. Args: method: Modeling method to experiment with. output_dir: Directory to record the trained model and output stats. num_epochs: Number of training epochs. fake_data: If true, use fake data. fake_training: If true, train for...
, models_lib.METHODS, 'Name of modeling method.') flags.DEFINE_string('output_dir', None, 'Output directory.') flags.DEFINE_integer('test_level', 0, 'Testing level.') flags.DEFINE_integer('train_epochs', 1, 'Number of epochs for training.') flags.DEFINE_integer('task', 0, 'Task number.') def...
97
98
328
18
79
kiss2u/google-research
uq_benchmark_2019/criteo/run_train.py
Python
run
run
46
80
46
46
48e61e48e47b6236ff9b9bda67300a075e007fcf
bigcode/the-stack
train
0ab23aee2e856f8abaf0f54f
train
function
def main(argv): if len(argv) > 1: raise app.UsageError('Too many command-line arguments.') run(FLAGS.method, FLAGS.output_dir, num_epochs=FLAGS.train_epochs, fake_data=FLAGS.test_level > 1, fake_training=FLAGS.test_level > 0)
def main(argv):
if len(argv) > 1: raise app.UsageError('Too many command-line arguments.') run(FLAGS.method, FLAGS.output_dir, num_epochs=FLAGS.train_epochs, fake_data=FLAGS.test_level > 1, fake_training=FLAGS.test_level > 0)
model.save_weights(output_dir + '/model.ckpt') # TODO(yovadia): Looks like Keras save_model does not work with Python3. # (e.g. see b/129323565). # experiment_utils.save_model(model, output_dir) return model def main(argv):
64
64
67
4
59
kiss2u/google-research
uq_benchmark_2019/criteo/run_train.py
Python
main
main
83
90
83
83
68dcb5419d0bb8ff64f9fb179e21acbfa5e8ada8
bigcode/the-stack
train
8bae526c757f47e8a9dd190e
train
function
def lookup_ssh_host_config(hostname, config): """ Provided only as a backward-compatible wrapper around `.SSHConfig`. """ return config.lookup(hostname)
def lookup_ssh_host_config(hostname, config):
""" Provided only as a backward-compatible wrapper around `.SSHConfig`. """ return config.lookup(hostname)
.hostkeys import HostKeys return HostKeys(filename) def parse_ssh_config(file_obj): """ Provided only as a backward-compatible wrapper around `.SSHConfig`. """ config = SSHConfig() config.parse(file_obj) return config def lookup_ssh_host_config(hostname, config):
64
64
35
11
52
parth5795/iOT-benchmarking
AI-env/lib/python3.7/site-packages/paramiko/util.py
Python
lookup_ssh_host_config
lookup_ssh_host_config
203
207
203
203
6221603c148cc0b307715f12aef005fb61c92ed8
bigcode/the-stack
train
d1edfdb0b1de765ad15508e1
train
function
def deflate_long(n, add_sign_padding=True): """turns a long-int into a normalized byte string (adapted from Crypto.Util.number)""" # after much testing, this algorithm was deemed to be the fastest s = bytes() n = long(n) while (n != 0) and (n != -1): s = struct.pack(">I", n & xffffffff) ...
def deflate_long(n, add_sign_padding=True):
"""turns a long-int into a normalized byte string (adapted from Crypto.Util.number)""" # after much testing, this algorithm was deemed to be the fastest s = bytes() n = long(n) while (n != 0) and (n != -1): s = struct.pack(">I", n & xffffffff) + s n >>= 32 # strip off leading...
out = (out << 32) + struct.unpack(">I", s[i : i + 4])[0] if negative: out -= long(1) << (8 * len(s)) return out deflate_zero = zero_byte if PY2 else 0 deflate_ff = max_byte if PY2 else 0xff def deflate_long(n, add_sign_padding=True):
84
84
283
11
72
parth5795/iOT-benchmarking
AI-env/lib/python3.7/site-packages/paramiko/util.py
Python
deflate_long
deflate_long
62
90
62
62
2e9372b4465fcbd8d1253ff050c69be876b9036e
bigcode/the-stack
train
68525ca4bd94aadb129b46ee
train
function
def clamp_value(minimum, val, maximum): return max(minimum, min(val, maximum))
def clamp_value(minimum, val, maximum):
return max(minimum, min(val, maximum))
res |= byte_ord(a[i]) ^ byte_ord(b[i]) return res == 0 class ClosingContextManager(object): def __enter__(self): return self def __exit__(self, type, value, traceback): self.close() def clamp_value(minimum, val, maximum):
64
64
21
10
54
parth5795/iOT-benchmarking
AI-env/lib/python3.7/site-packages/paramiko/util.py
Python
clamp_value
clamp_value
304
305
304
304
a4559d4f255992f0f4562bada8f606f537f7d43e
bigcode/the-stack
train
170ed1f11b45abbfe9e087a4
train
function
def tb_strings(): return "".join(traceback.format_exception(*sys.exc_info())).split("\n")
def tb_strings():
return "".join(traceback.format_exception(*sys.exc_info())).split("\n")
_ord(norm[0]) if hbyte == 0: return 1 bitlen = len(norm) * 8 while not (hbyte & 0x80): hbyte <<= 1 bitlen -= 1 return bitlen def tb_strings():
64
64
21
4
59
parth5795/iOT-benchmarking
AI-env/lib/python3.7/site-packages/paramiko/util.py
Python
tb_strings
tb_strings
138
139
138
138
c1687556f3d124d90918e3f23a7a1a59540fbc5f
bigcode/the-stack
train