code stringlengths 281 23.7M |
|---|
class OptionSeriesScatter3dDataDatalabels(Options):
def align(self):
return self._config_get('center')
def align(self, text: str):
self._config(text, js_type=False)
def allowOverlap(self):
return self._config_get(False)
def allowOverlap(self, flag: bool):
self._config(fla... |
def progress_bar(text, finish_tasks_number, tasks_number):
percentage = round(((finish_tasks_number / tasks_number) * 100))
num = round(((finish_tasks_number / tasks_number) * 50))
process = (('\r' + text) + (' %3s%%: |%-50s |' % (percentage, ('' * num))))
print(process, end='', flush=True) |
class AffectsAverageColumn(ObjectColumn):
menu = Menu(Action(name='Add', action='column.add(object)'), Action(name='Sub', action='column.sub(object)'))
horizontal_alignment = 'center'
width = 0.09
editable = False
def add(self, object):
setattr(object, self.name, (getattr(object, self.name) ... |
class TestBooleanEditorSimpleDemo(unittest.TestCase):
def test_boolean_editor_simple_demo(self):
demo = runpy.run_path(DEMO_PATH)['demo']
tester = UITester()
with tester.create_ui(demo) as ui:
simple = tester.find_by_id(ui, 'simple')
readonly = tester.find_by_id(ui, '... |
class OptionSeriesSankeySonificationDefaultinstrumentoptionsMappingHighpassFrequency(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self,... |
_page.route('/table/hidden_rows', methods=['POST'])
def hidden_ids():
res = check_uuid(all_data['uuid'], request.json['uuid'])
if (res != None):
return jsonify(res)
ids = request.json['ids']
all_data['hidden_rows'].clear()
for id in ids:
all_data['hidden_rows'][id] = 1
return jso... |
class TestStreamline(TestCase):
def make_data(self):
s = numpy.arange(0.0, 10.0, 0.01)
s = numpy.reshape(s, (10, 10, 10))
s = numpy.transpose(s)
v = numpy.zeros(3000, 'd')
v[::3] = 1.0
v = numpy.reshape(v, (10, 10, 10, 3))
return (s, v)
def test(self):
... |
class GroovedEdgeBase(BaseEdge):
def is_inverse(self) -> bool:
return (self.settings.inverse != self.inverse)
def groove_arc(self, width, angle: float=90.0, inv: float=(- 1.0)) -> None:
side_length = ((width / math.sin(math.radians(angle))) / 2)
self.corner((inv * (- angle)))
sel... |
class StorageTestCaseBase(TestCaseBase):
def setUp(self):
super().setUp()
StorageFactory.initialize(self.config)
default_storage_name = self.config.get('defaultStorage', types=str)
self.storage = StorageFactory.get_by_name(default_storage_name)
for block_uid in self.storage.l... |
def principal_axis_factor(input_matrix, n_factors, initial_guess=None, max_iterations=2000, tolerance=0.001):
if (initial_guess is None):
initial_guess = np.zeros(input_matrix.shape[0])
args = (input_matrix, n_factors)
unique_variance = fixed_point(_paf_fixed_point_iterate, initial_guess, args=args,... |
def test___setitem__checks_the_given_data_14():
wh = WorkingHours()
with pytest.raises(TypeError) as cm:
wh['mon'] = [[2, 'a']]
assert (str(cm.value) == "WorkingHours.working_hours value should be a list of lists of two integers between and the range of integers should be 0-1440, not [[2, 'a']]") |
class PersonApi(PersonApiabstohr):
permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
authentication_classes = [JSONWebTokenAuthentication, SessionAuthentication]
def get_queryset(self):
user = self.request.user
return Article.objects.filter(authors_id=self.request.user.id).filter(is_... |
class SRAMWriterDriver():
def __init__(self, obj):
self.obj = obj
def wait_available(self):
while (not (yield self.obj.ev.available.pending)):
(yield)
def clear_available(self):
(yield self.obj.ev.pending.re.eq(1))
(yield self.obj.ev.pending.r.eq(1))
(yiel... |
.parametrize('elasticapm_client', [{'span_compression_enabled': True, 'span_compression_same_kind_max_duration': '5ms', 'span_compression_exact_match_max_duration': '5ms'}], indirect=True)
def test_nested_spans(elasticapm_client):
transaction = elasticapm_client.begin_transaction('test')
with elasticapm.capture... |
def get_all_configs():
return [get_baseline_and_optimization_config(True, True), get_baseline_and_optimization_config(False, True), get_baseline_and_optimization_config(True, False), get_baseline_and_optimization_config(False, False), get_RC_and_optimization_config(True, False), get_RC_and_optimization_config(False... |
def Send_Email(msg, SMTPServer):
print(3)
mailserver = smtplib.SMTP(SMTPServer, 25, timeout=7)
mailserver.ehlo('localhost')
mailserver.starttls()
resp = mailserver.sendmail(msg['From'], [msg['To']], msg.as_string())
print('[+] Email successfully sent to {}'.format(msg['To']))
print(resp)
... |
class DefinitionsPage(Webpage):
def __init__(self):
self.filepath = 'build/html/definitions.html'
self.title = 'All symbol definitions'
self.pagetitle = 'All symbol definitions'
def start(self):
Webpage.start(self)
self.fp.write('<p style="text-align:center"><a href="inde... |
def test_cose_cbor(config_env: Dict):
if (CONFIG_ERROR in config_env.keys()):
fail(f'Config Error: {config_env[CONFIG_ERROR]}')
if (EXPECTED_DECODE not in config_env[EXPECTED_RESULTS].keys()):
skip(f'Test not requested: {EXPECTED_DECODE}')
if (not ({CBOR, COSE} <= config_env.keys())):
... |
class Paraphrase(TransformBase):
def __init__(self, model: Optional[str]=OPENAI_CHAT_COMPLETION, num_perturbations: int=5, temperature: float=0.0, api_key: Optional[str]=None, api_version: Optional[str]=None) -> None:
self._init_key(api_key)
self._init_model(model, api_version)
self.num_pert... |
(repr=False, slots=True, hash=True)
class _IsFileValidator():
type = attr.attrib()
check_access = attr.attrib()
def __call__(self, inst: _C, attr: attr.Attribute, value: str) -> None:
_is_file(self.type, check_access=self.check_access, attr=attr, value=value)
def __repr__(self) -> str:
r... |
def main():
data = pd.read_csv('mlfromscratch/data/TempLinkoping2016.txt', sep='\t')
time = np.atleast_2d(data['time'].values).T
temp = data['temp'].values
X = time
y = temp
(X_train, X_test, y_train, y_test) = train_test_split(X, y, test_size=0.4)
poly_degree = 13
model = ElasticNet(deg... |
def _copy_lines_between_files(in_, fout, n=None, skip=0, mode='a', terminal_line='', lines=None):
mtimesleep()
if (terminal_line is not None):
terminal_line = uni_bytes(terminal_line)
if isinstance(in_, str):
fin = open(in_, 'rb')
else:
fin = in_
for i in range(skip):
... |
class TypeCaster(ATypeCaster):
def __init__(self, frame: typing.Optional[FrameType]=None):
self.cache: typing.Dict[(typing.Union[(type, PythonType)], PythonType)] = {}
self.frame = frame
def _to_canon(self, t):
to_canon = self.to_canon
if isinstance(t, (base_types.Type, Validator... |
def test_resolve_overrides():
config = {'cfg': {'one': 1, 'two': {'three': {'': 'catsie.v1', 'evil': True, 'cute': False}}}}
overrides = {'cfg.two.three.evil': False}
result = my_registry.resolve(config, overrides=overrides, validate=True)
assert (result['cfg']['two']['three'] == 'meow')
overrides =... |
class AbstractPage(TreeNode):
is_active = models.BooleanField(_('is active'), default=True)
title = models.CharField(_('title'), max_length=200)
slug = models.SlugField(_('slug'))
position = models.PositiveIntegerField(db_index=True, editable=False, validators=[MinValueValidator(limit_value=1, message=_... |
('cuda.padded_dense_to_jagged.func_decl')
def padded_dense_to_jagged_gen_function_decl(func_attrs) -> str:
x = func_attrs['inputs'][0]
y = func_attrs['outputs'][0]
jagged_int_var = func_attrs['jagged_int_var']
func_name = func_attrs['name']
backend_spec = CUDASpec()
return FUNC_DECL_TEMPLATE.ren... |
def extractSocialweebWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type... |
class TestClusterEnvironmentInfo():
('esrally.metrics.EsMetricsStore.add_meta_info')
def test_stores_cluster_level_metrics_on_attach(self, metrics_store_add_meta_info):
nodes_info = {'nodes': collections.OrderedDict()}
nodes_info['nodes']['FCFjozkeTiOpN-SI88YEcg'] = {'name': 'rally0', 'host': '1... |
def proc_reward(validator_index: uint256, reward: decimal((wei / sf))):
self.validators[validator_index].deposit += reward
start_dynasty: uint256 = self.validators[validator_index].start_dynasty
end_dynasty: uint256 = self.validators[validator_index].end_dynasty
current_dynasty: uint256 = self.dynasty
... |
class OptionSeriesParetoDragdropGuideboxDefault(Options):
def className(self):
return self._config_get('highcharts-drag-box-default')
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get('rgba(0, 0, 0, 0.1)')
def color(self, t... |
class CustomerTests(unittest.TestCase):
def test_unicode(self):
customer = Customer()
customer.DisplayName = 'test'
self.assertEqual(str(customer), 'test')
def test_to_ref(self):
customer = Customer()
customer.DisplayName = 'test'
customer.Id = 100
ref = c... |
class Description():
__slots__ = ('_values', 'data_model')
def __init__(self, values: Mapping[(str, ATTRIBUTE_TYPES)], data_model: Optional[DataModel]=None, data_model_name: str='') -> None:
_values = deepcopy(values)
self._values = _values
if (data_model is not None):
self.d... |
def evaluate(url: str, resource_type: str, fides_key: str, tag: str, message: str, headers: Dict[(str, str)]) -> requests.Response:
resource_url = generate_resource_url(url, resource_type)
url = f'{resource_url}evaluate/{fides_key}'
return requests.get(url, headers=headers, params={'tag': tag, 'message': me... |
class _LtMatcher(_Matcher):
def _matches(self, value):
try:
if (value is None):
value = 0
else:
value = float(value)
content = float(self.content)
except (TypeError, ValueError):
return False
return (value < cont... |
def test_thread_parse_participants(session):
nodes = [{'messaging_actor': {'__typename': 'User', 'id': '1234'}}, {'messaging_actor': {'__typename': 'User', 'id': '2345'}}, {'messaging_actor': {'__typename': 'Page', 'id': '3456'}}, {'messaging_actor': {'__typename': 'MessageThread', 'id': '4567'}}, {'messaging_actor... |
class OptionSeriesSankeyDatalabelsFilter(Options):
def operator(self):
return self._config_get(None)
def operator(self, value: Any):
self._config(value, js_type=False)
def property(self):
return self._config_get(None)
def property(self, text: str):
self._config(text, js_t... |
def test():
assert (len(doc1.ents) == 2), 'doc12'
assert ((doc1.ents[0].label_ == 'WEBSITE') and (doc1.ents[0].text == 'Reddit')), 'doc11'
assert ((doc1.ents[1].label_ == 'WEBSITE') and (doc1.ents[1].text == 'Patreon')), 'doc12'
assert (len(doc2.ents) == 1), 'doc21'
assert ((doc2.ents[0].label_ == '... |
def extractShirokunsCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Living in this World with Cut & Paste', 'Living in this World with Cut & Paste', 'translated'), ('Althou... |
def delete_shelf_tab(shelf_name, confirm=True):
try:
shelf_top_level_path = pm.melGlobals['gShelfTopLevel']
except KeyError:
return
shelf_top_level = pm.windows.tabLayout(shelf_top_level_path, e=1)
if (len(shelf_top_level.children()) < 0):
return
if confirm:
response ... |
class TestCacheSerializerData():
def test_cache_serializer_data(self):
class ExampleSerializer(serializers.Serializer):
field1 = serializers.CharField()
field2 = serializers.CharField()
serializer = ExampleSerializer({'field1': 'a', 'field2': 'b'})
pickled = pickle.du... |
def groups_from_pairs(pairs):
groups = {}
for (element, other_element) in pairs:
group = groups.setdefault(element, [element])
other_group = groups.get(other_element, [other_element])
if (other_group is not group):
group.extend(other_group)
for member in other_gro... |
class StreamingLLMOperator(BaseLLM, StreamifyAbsOperator[(ModelRequest, ModelOutput)], ABC):
def __init__(self, llm_client: Optional[LLMClient]=None, **kwargs):
super().__init__(llm_client=llm_client)
StreamifyAbsOperator.__init__(self, **kwargs)
async def streamify(self, request: ModelRequest) ... |
class TestCreatePolicies():
(scope='function')
def url(self, oauth_client: ClientDetail, policy) -> str:
return (V1_URL_PREFIX + POLICY_CREATE_URI)
(scope='function')
def payload(self, storage_config):
return [{'name': 'policy 1', 'action_type': 'erasure', 'data_category': DataCategory('... |
class TestOFPDescStatsReply(unittest.TestCase):
class Datapath(object):
ofproto = ofproto
ofproto_parser = ofproto_v1_0_parser
c = OFPDescStatsReply(Datapath)
def setUp(self):
pass
def tearDown(self):
pass
def test_init(self):
pass
def test_parser(self):
... |
class OptionPlotoptionsAreasplinerangeDatalabels(Options):
def align(self):
return self._config_get('undefined')
def align(self, text: str):
self._config(text, js_type=False)
def allowOverlap(self):
return self._config_get(False)
def allowOverlap(self, flag: bool):
self._... |
def main():
rolling_out = fixed_out = 0
(args, _extra) = arg_opts()
if args.json_log:
grok_json(args)
return
if _debug:
print('args', args)
print('_extra', _extra)
if args.input_file:
with open(args.input_file, 'r', encoding='UTF-8') as fd:
(xx, yy... |
(scope='function')
def privacy_experience_france_overlay(db: Session, experience_config_overlay) -> Generator:
privacy_experience = PrivacyExperience.create(db=db, data={'component': ComponentType.overlay, 'region': PrivacyNoticeRegion.fr, 'experience_config_id': experience_config_overlay.id})
(yield privacy_ex... |
class TestBodhiConfigLoadConfig():
('bodhi.server.config.get_appsettings')
def test_loads_defaults(self, get_appsettings):
c = config.BodhiConfig()
c.load_config({'session.secret': 'secret', 'authtkt.secret': 'secret'})
assert (c['top_testers_timeframe'] == 7)
('bodhi.server.config.g... |
def test():
assert ('spacy.load("fr_core_news_md")' in __solution__), 'Charges-tu correctement le pipeline moyen ?'
assert ('doc[1].vector' in __solution__), 'Obtiens-tu le bon vecteur ?'
__msg__.good("Bien joue ! Dans l'exercice suivant, tu vas utiliser spaCy pour predire des similarites entre des document... |
class CustomizationView(QWidget):
def __init__(self):
QWidget.__init__(self)
self._layout = QFormLayout()
self.setLayout(self._layout)
self._widgets = {}
def addRow(self, title, widget):
self._layout.addRow(title, widget)
def addLineEdit(self, attribute_name, title, t... |
def test_matcher_from_usage_docs(en_vocab):
text = 'Wow This is really cool! '
doc = Doc(en_vocab, words=text.split(' '))
pos_emoji = ['', '', '', '', '', '']
pos_patterns = [[{'ORTH': emoji}] for emoji in pos_emoji]
def label_sentiment(matcher, doc, i, matches):
(match_id, start, end) = m... |
def test_create_single_namespace():
test_registry = catalogue.create('test')
assert (catalogue.REGISTRY == {})
_registry.register('a')
def a():
pass
def b():
pass
test_registry.register('b', func=b)
items = test_registry.get_all()
assert (len(items) == 2)
assert (item... |
def delete_transactions(client: Elasticsearch, config: dict, task_id: str='Sync DB Deletes', fabs_external_data_load_date_key: str='fabs', fpds_external_data_load_date_key: str='fpds') -> int:
deleted_tx_keys = _gather_deleted_transaction_keys(config, fabs_external_data_load_date_key, fpds_external_data_load_date_k... |
def sanity_test(mh, filename):
mh.register_file(filename)
with open(filename, 'r', encoding='UTF-8') as fd:
content = fd.read()
try:
language = MATLAB_Latest_Language()
lexer = MATLAB_Lexer(language, mh, content, filename)
lexer.debug_comma = True
while True:
... |
class SortMultiOptionValidator(object):
def __init__(self, values):
self.values = values
def __call__(self, sort_arg_value_list):
for sort_arg_value in sort_arg_value_list:
if (sort_arg_value.lstrip('-') not in self.values):
raise exceptions.ApiError('Cannot sort on v... |
def request_screenshot_permission(dialog_title: str='Error', macos_dialog_text: str=DEFAULT_MACOS_DIALOG_TEXT, linux_dialog_text: str=DEFAULT_LINUX_DIALOG_TEXT) -> None:
if (sys.platform == 'win32'):
logger.debug('Not necessary to request screenshot permission on Windows. Skipping.')
return
if (... |
class VIEW3D_MT_submenu_align(Menu):
bl_label = 'Align'
bl_idname = 'VIEW3D_MT_submenu_align'
def draw(self, context):
layout = self.layout
layout.operator(op_align.op.bl_idname, text='', icon_value=icon_get('op_align_left')).direction = 'left'
layout.operator(op_align.op.bl_idname, ... |
class Factors():
def __init__(self, *args, **kwargs):
self.binary = kwargs['binary']
self.factors = set()
def add_phi_factor(self, nodes):
if (len(nodes) > 1):
node_type = make_node_type(coarse(nodes[0]), self.binary)
nodes.append(node_type)
factors = ... |
class OptionSeriesLollipopSonificationTracksMappingHighpassFrequency(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
def _mock_gcs():
def _mock_gcs_get_buckets(projectid):
if (projectid in results.GCS_GET_BUCKETS):
return results.GCS_GET_BUCKETS[projectid]
return []
def _mock_gcs_get_objects(bucket_name):
if (bucket_name in results.GCS_GET_OBJECTS):
return results.GCS_GET_OBJECT... |
class OptionSeriesAreasplineMarkerStates(Options):
def hover(self) -> 'OptionSeriesAreasplineMarkerStatesHover':
return self._config_sub_data('hover', OptionSeriesAreasplineMarkerStatesHover)
def normal(self) -> 'OptionSeriesAreasplineMarkerStatesNormal':
return self._config_sub_data('normal', O... |
def extractApprenticetranslationsCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_t... |
(IDockPane)
class DockPane(TaskPane, MDockPane):
size = Property(Tuple)
_receiving = Bool(False)
def create(self, parent):
self.control = control = QtGui.QDockWidget(parent)
control.setObjectName(((self.task.id + ':') + self.id))
control.setAttribute(QtCore.Qt.WidgetAttribute.WA_MacA... |
class OptionSeriesSolidgaugeSonificationDefaultinstrumentoptions(Options):
def activeWhen(self) -> 'OptionSeriesSolidgaugeSonificationDefaultinstrumentoptionsActivewhen':
return self._config_sub_data('activeWhen', OptionSeriesSolidgaugeSonificationDefaultinstrumentoptionsActivewhen)
def instrument(self)... |
class OptionPlotoptionsVectorSonificationDefaultspeechoptionsMappingPitch(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get('undefined')
def mapTo(self, tex... |
def diag_quadrupole3d_13(ax, da, A, bx, db, B, R):
result = numpy.zeros((3, 3, 10), dtype=float)
x0 = ((ax + bx) ** (- 1.0))
x1 = (3.0 * x0)
x2 = (x0 * ((ax * A[0]) + (bx * B[0])))
x3 = (- x2)
x4 = (x3 + A[0])
x5 = (x3 + B[0])
x6 = (x4 * x5)
x7 = (2.0 * x6)
x8 = (x3 + R[0])
x... |
def register_cosmology(cosmocls, name=None):
if (not name):
name = cosmocls.__name__
name = name.lower().replace('cosmology', '')
try:
if (not issubclass(cosmocls, Cosmology)):
raise TypeError('Supplied object is not a subclass of Cosmology')
except TypeError:
raise T... |
class group_mod_failed_error_msg(error_msg):
version = 4
type = 1
err_type = 6
def __init__(self, xid=None, code=None, data=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (code != None):
self.code = code
else:
... |
class Queen(Piece):
def __init__(self, x, y, c):
super().__init__(x, y, c)
self.set_letter('')
def draw_moves(self, pieces):
fake_piece = Queen(self.start_x, self.start_y, self.color)
directions = [[10, 10], [(- 10), (- 10)], [10, (- 10)], [(- 10), 10], [0, 10], [0, (- 10)], [10,... |
class MailLog(models.Model):
EVENT_TYPE_CHOICES = [(value, value) for (name, value) in sorted(vars(EventType).items()) if (not name.startswith('_'))]
metadata = JSONField(null=True, blank=True)
recipient = models.CharField(max_length=254, db_index=True)
tags = ArrayField(models.CharField(max_length=100,... |
class OptionSeriesItemLabel(Options):
def boxesToAvoid(self):
return self._config_get(None)
def boxesToAvoid(self, value: Any):
self._config(value, js_type=False)
def connectorAllowed(self):
return self._config_get(False)
def connectorAllowed(self, flag: bool):
self._conf... |
class chunk(split):
def __init__(self):
super().__init__()
self._attrs['op'] = 'split'
def __call__(self, input: Tensor, chunks: int, dim: int=0) -> List[Tensor]:
if (chunks < 1):
raise RuntimeError(f'chunks must be >= 1 but got chunks={chunks!r}')
input_shape = input... |
class Header(nn.Module):
def __init__(self, num_classes, mode='train'):
super(Header, self).__init__()
self.mode = mode
self.header_heatmaps = nn.Sequential(*[dw_conv3(24, 96), nn.Conv2d(96, num_classes, 1, 1, 0, bias=True), HardSigmoid()])
self.header_centers = nn.Sequential(*[dw_co... |
class OptionSeriesBoxplotSonificationContexttracksMappingTremolo(Options):
def depth(self) -> 'OptionSeriesBoxplotSonificationContexttracksMappingTremoloDepth':
return self._config_sub_data('depth', OptionSeriesBoxplotSonificationContexttracksMappingTremoloDepth)
def speed(self) -> 'OptionSeriesBoxplotS... |
_os(*metadata.platforms)
def main():
cmd_path = 'c:\\windows\\system32\\cmd.exe'
binaries = ['adobe.exe', 'winword.exe', 'outlook.exe', 'excel.exe', 'powerpnt.exe']
for binary in binaries:
common.copy_file(cmd_path, binary)
common.execute(['adobe.exe', '/c', 'regsvr32.exe', '/s', '/?'], timeout=... |
class SearchBox(Component):
css_classes = ['ms-SearchBox']
name = 'Fabric UI SearchBox'
str_repr = '\n<div {attrs}>\n <input class="ms-SearchBox-field" type="text" value="">\n <label class="ms-SearchBox-label">\n <i class="ms-SearchBox-icon ms-Icon ms-Icon--Search"></i>\n <span class="ms-SearchBox-t... |
class EmbyhubMonitor(Monitor):
name = 'EmbyHub'
chat_name = 'emby_hub'
chat_user = 'ednovas'
chat_keyword = ''
bot_username = 'EdHubot'
notify_create_name = True
async def on_trigger(self, message: Message, key, reply):
(await self.client.send_message(self.bot_username, f'/create {se... |
def test():
assert (doc.text == 'La foret est peuplee de loups gris et renards roux.'), "Es-tu certain d'avoir traite correctement le texte ?"
assert (first_token == doc[0]), "Es-tu certain d'avoir selectionne le premier token ?"
assert ('print(first_token.text)' in __solution__), 'Affiches-tu le texte du t... |
class OptionSeriesErrorbarDataDragdropDraghandle(Options):
def className(self):
return self._config_get('highcharts-drag-handle')
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get('#fff')
def color(self, text: str):
... |
def _desc_locations(attr, die):
cu = die.cu
di = cu.dwarfinfo
if (not hasattr(di, '_loclists')):
di._loclists = di.location_lists()
if (not hasattr(di, '_locparser')):
di._locparser = LocationParser(di._loclists)
loclist = di._locparser.parse_from_attribute(attr, cu.header.version, d... |
class State():
_state: typing.Dict[(str, typing.Any)]
def __init__(self, state: typing.Optional[typing.Dict[(str, typing.Any)]]=None):
if (state is None):
state = {}
super().__setattr__('_state', state)
def __setattr__(self, key: typing.Any, value: typing.Any) -> None:
se... |
class TestTopicPagesInlineListTag(BaseConversationTagsTestCase):
def test_provides_the_number_of_pages_of_a_topic(self):
def get_rendered(topic):
t = Template((self.loadstatement + '{% topic_pages_inline_list topic %}'))
c = Context({'topic': topic})
rendered = t.render(c... |
def _fused_elementwise_ops_are_equal(op1: Operator, op2: Operator) -> bool:
op1_elementwise_ops = op1._attrs['elementwise_ops']
op2_elementwise_ops = op2._attrs['elementwise_ops']
(op1_inputs, op2_inputs) = (op1._attrs['inputs'], op2._attrs['inputs'])
op1_input_accessors = op1._attrs['input_accessors']
... |
class PluginCreator():
def __init__(self, tmp_path: Path, monkeypatch):
self.tmp_path = tmp_path
self.monkeypatch = monkeypatch
def add_plugin(self, name: str, entry_points: str, init: str):
plugin = (self.tmp_path / name)
plugin.mkdir(mode=511)
plugin_egg = plugin.with_s... |
def set_alias(self, userName, alias):
oldFriendInfo = utils.search_dict_list(self.memberList, 'UserName', userName)
if (oldFriendInfo is None):
return ReturnValue({'BaseResponse': {'Ret': (- 1001)}})
url = ('%s/webwxoplog?lang=%s&pass_ticket=%s' % (self.loginInfo['url'], 'zh_CN', self.loginInfo['pas... |
def test_dt_serving_latency(dummy_titanic):
(X_train, y_train, X_test, y_test) = dummy_titanic
dt = DecisionTree(depth_limit=10)
dt.fit(X_train, y_train)
latency_array = np.array([predict_with_time(dt, X_test)[1] for i in range(200)])
latency_p99 = np.quantile(latency_array, 0.99)
assert (latenc... |
class IOSPlatformTest(unittest.TestCase):
def setUp(self):
self.tempdir = tempfile.mkdtemp(prefix='aibench')
device = {'-AB901C': 'A012BC'}
idb = IDB(device, self.tempdir)
with patch('platforms.ios.ios_platform.IOSPlatform.setPlatformHash'), patch('platforms.ios.ios_platform.getArgs'... |
class RollingRawUrlStartTrigger(RawArchiver.TimedTriggers.TriggerBase.TriggerBaseClass):
pluginName = 'RollingRewalk Trigger'
loggerPath = 'Main.RollingRawRewalker'
def retrigger_urls(self, url_list):
self.log.info('Retrigging %s urls', len(url_list))
with self.db.session_context(override_ti... |
def add_notification_instance():
def _add_notification_instance(fledge_url, delivery_plugin, delivery_branch, rule_config={}, delivery_config={}, rule_plugin='Threshold', rule_branch=None, rule_plugin_discovery_name=None, delivery_plugin_discovery_name=None, installation_type='make', notification_type='one shot', n... |
def get_tcf_base_query_and_filters(db: Session) -> Tuple[(Query, BinaryExpression, BinaryExpression)]:
legal_basis_override_subquery = get_legal_basis_override_subquery(db)
consent_legal_basis_filter: BinaryExpression = (legal_basis_override_subquery.c.overridden_legal_basis_for_processing == LegalBasisForProce... |
def _check_with_retries(condition: Callable[([], bool)], max_attempts: int=3, delay_seconds: int=5) -> bool:
attempts = 0
while True:
if condition():
return True
attempts += 1
if (attempts >= max_attempts):
return False
sleep(delay_seconds) |
def test_suite_html_execute(**context):
reference_data = context.get('ti').xcom_pull(key='reference')
current_data = context.get('ti').xcom_pull(key='current')
data_quality_suite = context.get('ti').xcom_pull(key='test_suite')
data_quality_suite.run(reference_data=reference_data, current_data=current_da... |
def dump_json():
parser = argparse.ArgumentParser()
parser.add_argument('--attrs-file', help='JSON output path', required=True)
args = parser.parse_args()
data = OrderedDict()
for param in boolean_params:
data[param[0]] = {'type': 'BOOL', 'values': ['FALSE', 'TRUE'], 'digits': param[1]}
... |
def _get_kwargs(*, client: Client) -> Dict[(str, Any)]:
url = '{}/billing/user_details'.format(client.base_url)
headers: Dict[(str, str)] = client.get_headers()
cookies: Dict[(str, Any)] = client.get_cookies()
return {'method': 'get', 'url': url, 'headers': headers, 'cookies': cookies, 'timeout': client... |
class ButtonFilter(Html.Html):
name = 'Button Filter'
_option_cls = OptButton.OptionsButtonFilter
tag = 'div'
def __init__(self, page: primitives.PageModel, text: str, width: tuple, height: tuple, html_code: str, tooltip: str, profile: Optional[Union[(bool, dict)]], options: Optional[dict], verbose: boo... |
def libp2p_log_on_failure(fn: Callable) -> Callable:
(fn)
def wrapper(self, *args, **kwargs):
try:
return fn(self, *args, **kwargs)
except Exception:
for log_file in self.log_files:
print('libp2p log file {}'.format(log_file))
try:
... |
def construct_response(results: list, pagination: Pagination, strip_total_budgetary_resources=True):
object_classes = ObjectClassResults()
for row in results:
major_code = row.pop('major_code')
major_class = MajorClass(id=major_code, code=major_code, award_count=0, description=row.pop('major_des... |
def test_gold_user_access(client, msend):
r = client.post('/register', data={'email': '', 'password': 'banana'})
user = User.query.filter_by(email='').first()
user.plan = Plan.gold
DB.session.add(user)
DB.session.commit()
r = client.post('/api-int/forms', headers={'Accept': 'application/json', '... |
def upgrade():
op.add_column('settings', sa.Column('facebook_url', sa.String(), nullable=True))
op.add_column('settings', sa.Column('github_url', sa.String(), nullable=True))
op.add_column('settings', sa.Column('google_url', sa.String(), nullable=True))
op.add_column('settings', sa.Column('support_url',... |
class TestRename(TestData):
def test_single_rename(self):
ed_field_mappings = FieldMappings(client=ES_TEST_CLIENT, index_pattern=FLIGHTS_INDEX_NAME)
pd_flights_column_series = self.pd_flights().columns.to_series()
assert (pd_flights_column_series.index.to_list() == ed_field_mappings.display_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.