repo_name
stringlengths
5
100
path
stringlengths
4
231
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
6
947k
score
float64
0
0.34
prefix
stringlengths
0
8.16k
middle
stringlengths
3
512
suffix
stringlengths
0
8.17k
ptrendx/mxnet
example/ssd/train.py
Python
apache-2.0
8,626
0.004637
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 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 Licen...
default='80, 160', help='refactor learning rate at specified epochs') parser.add_argument('--lr-factor', dest='lr_refactor_ratio', type=float, default=0.1, help='ratio to refactor learning rate') parser.add_argument('--freeze', dest='freeze_pattern', type=str, def...
ser.add_argument('--log', dest='log_file', type=str, default="train.log", help='save training log to file') parser.add_argument('--monitor', dest='monitor', type=int, default=0, help='log network parameters every N iters if larger than 0') parser.add_argument('--p...
indautgrp/frappe
frappe/model/utils/rename_field.py
Python
mit
4,528
0.024514
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe import json from frappe.model import no_value_fields from frappe.utils.password import rename_password_field def rename_field(doctype, old_fieldname, new_fieldname...
_by reports = frappe.db.sql("""select name, ref_doctype, json from tabReport where report_type = 'Report Builder' and ifnull(is_standard, 'No') = 'No' and json like %s and json like %s""", ('%%%s%%' % old_fieldname , '%%%s%%' % doctype), as_dict=True) for r in reports: report_dict = json.loads(r.json) # ...
== doctype and f[1] == old_fieldname: new_filters.append([doctype, new_fieldname, f[2], f[3]]) report_dict["updated"] = True else: new_filters.append(f) # update columns new_columns = [] for c in report_dict.get("columns"): if c and len(c) > 1 and c[0] == old_fieldname and c[1] == doctype: ...
lisatn/workload-automation
wa/workloads/openssl/__init__.py
Python
apache-2.0
6,494
0.000616
# Copyright 2018 ARM Limited # # 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 writin...
'''), Parameter('use_system_binary', kind=bool, default=True, description=''' If ``True``, the system Openssl binary will be used. Otherwise, use the binary provided in the workload resources. '''), ] aliases ...
W + CIPHER_PKI] @once def initialize(self, context): if self.use_system_binary: try: cmd = '{0} md5sum < $({0} which openssl)' output = self.target.execute(cmd.format(self.target.busybox)) md5hash = output.split()[0] version = ...
Nozdi/webpage-similarity
similarity/__init__.py
Python
mit
39
0
from si
milarity.webpage import WebPage
ghchinoy/tensorflow
tensorflow/python/keras/utils/conv_utils.py
Python
apache-2.0
13,585
0.006846
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
es" or "kernel_size". This is only used to format error messages. Returns: A tuple of n integers. Raises: ValueError: If something else than an int/long or iterable thereof was passed. """ if isinstance(value, int): return (value,) *
n else: try: value_tuple = tuple(value) except TypeError: raise ValueError('The `' + name + '` argument must be a tuple of ' + str(n) + ' integers. Received: ' + str(value)) if len(value_tuple) != n: raise ValueError('The `' + name + '` argument must be a tuple of...
devclone/enigma2-9f38fd6
lib/python/Components/InputDevice.py
Python
gpl-2.0
9,159
0.026313
from os import listdir, open as os_open, close as os_close, write as os_write, O_RDWR, O_NONBLOCK from fcntl import ioctl from boxbranding import getBoxType, getBrandOEM import struct from config import config, ConfigSubsection, ConfigInteger, ConfigYesNo, ConfigText, ConfigSlider from Tools.Directories import pathExi...
+ ".enabled.addNotifier(self.
inputDevicesEnabledChanged,config.inputDevices." + device + ".enabled)" exec cmd cmd = "config.inputDevices." + device + '.name = ConfigText(default="")' exec cmd cmd = "config.inputDevices." + device + ".name.addNotifier(self.inputDevicesNameChanged,config.inputDevices." + device + ".name)" exec cmd if box...
hughperkins/kgsgo-dataset-preprocessor
thirdparty/future/src/future/backports/test/pystone.py
Python
mpl-2.0
7,427
0.004309
#!/usr/bin/env python3 """ "PYSTONE" Benchmark Program Version: Python/1.1 (corresponds to C/1.1 plus 2 Pystone fixes) Author: Reinhold P. Weicker, CACM Vol 27, No 10, 10/84 pg. 1013. Translated from ADA to C by Rick Richardson. Every method to preserve ADA-likeness h...
rGlb.Dis
cr = Ident1 PtrGlb.EnumComp = Ident3 PtrGlb.IntComp = 40 PtrGlb.StringComp = "DHRYSTONE PROGRAM, SOME STRING" String1Loc = "DHRYSTONE PROGRAM, 1'ST STRING" Array2Glob[8][7] = 10 starttime = clock() for i in range(loops): Proc5() Proc4() IntLoc1 = 2 IntLoc2 =...
anhstudios/swganh
data/scripts/templates/object/tangible/lair/base/shared_poi_all_lair_nest_small_evil_fire_small.py
Python
mit
464
0.047414
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result
= Tangible() result.template = "object/tangible/lair/base/shared_poi_all_lair_nest_small_evil_fire_small.iff" result.attribute_template_id = -1 result.stfName("lair_n","nest") #### BEGIN MODIFICATIONS #### #### END MO
DIFICATIONS #### return result
nickaigi/django-pesapal
manage.py
Python
mit
257
0
#!/u
sr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_pesapal.settings") from django.core.management import execute_from_comm
and_line execute_from_command_line(sys.argv)
StellarCN/py-stellar-base
stellar_sdk/xdr/ledger_upgrade_type.py
Python
apache-2.0
1,727
0.000579
# This is an automatically generated file. # DO NOT EDIT or your changes may be overwritten import base64 from enum import IntEnum from xdrlib import Packer, Unpacker from ..__version__ import __issues__ from ..type_checked import type_checked __all__ = ["LedgerUpgradeType"] @type_checked class LedgerUpgradeType(In...
XDR Source Code:: enum LedgerUpgradeType { LEDGER_UPGRADE_VERSION = 1, LEDGER_UPGRADE_BASE_FEE = 2, LEDGER_UPGRADE_MAX_TX_SET_SIZE = 3, LEDGER_UPGRADE_BASE_RESERVE = 4 }; """ LEDGER_UPGRADE_VERSION = 1 LEDGER_UPGRADE_BASE_FEE = 2 ...
@classmethod def unpack(cls, unpacker: Unpacker) -> "LedgerUpgradeType": value = unpacker.unpack_int() return cls(value) def to_xdr_bytes(self) -> bytes: packer = Packer() self.pack(packer) return packer.get_buffer() @classmethod def from_xdr_bytes(cls, xdr: ...
eciis/web
backend/test/request_handlers_test/user_request_collection_handler_test.py
Python
gpl-3.0
4,935
0.001824
# -*- coding: utf-8 -*- """User request handler collection test.""" import json from .. import mocks from ..test_base_handler import TestBaseHandler from models import User from models import Institution from models import Address from models import Invite from handlers.user_request_collection_handler import UserReque...
ata": data} with self.assertRaises(Exception) as ex: self.testapp.post_json( "/api/institutions/" + self.inst_test.key.urlsafe() + "/reques
ts/user", body, headers=self.headers ) exception_message = self.get_message_exception(ex.exception.message) self.assertEqual( 'Error! The type must be REQUEST_USER', exception_message, "Expected error message is Error! The ...
blue-yonder/tsfresh
tests/integrations/test_full_pipeline.py
Python
mit
2,570
0.000778
# -*- coding: utf-8 -*- # This file as well as the whole tsfresh package are licenced under the MIT licence (see the LICENCE.txt) # Maximilian Christ (maximilianchrist.com), Blue Yonder Gmbh, 2016 import os import shutil import tempfile from unittest import TestCase import pandas as pd from sklearn.pipeline import Pi...
mers import RelevantFeatureAugmenter class FullPipelineTestCa
se_robot_failures(TestCase): def setUp(self): self.temporary_folder = tempfile.mkdtemp() temporary_file = os.path.join(self.temporary_folder, "data") download_robot_execution_failures(file_name=temporary_file) self.timeseries, self.y = load_robot_execution_failures( file...
viktorbahr/jaer
server/client.py
Python
lgpl-2.1
3,600
0.011948
from __future__ import print_function, division import json import socket import random import time import numpy as np class Client(object): SYNC_ON = b'1' SYNC_OFF = b'2' EVENT_ON = b'A' EVENT_OFF = b'D' ACQ = b'Y' QUIT = b'X' def __init__(self, cfgfile='servic...
n microsec self.latency.append(stop - start) if self.showresponse ==
True: print(resp) if self.interactive == True: print("value={}".format("ON" if value == True else "OFF")) def close(self): if self.closed == False: self.socket.send(Client.QUIT) self.socket.close() self.closed = True if self.t...
AutorestCI/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_11_01/models/operation_display.py
Python
mit
1,498
0.000668
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights rese
rved. # Licensed under the MIT License. See License.txt in
the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class Oper...
jds2001/ocp-checkbox
plainbox/plainbox/impl/exporter/test_text.py
Python
gpl-3.0
1,478
0
# This file is part of Checkbox. # # Copyright 2012 Canonical Ltd. # Written by: # Zygmunt Krynicki <[email protected]> # Daniel Manrique <[email protected]> # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # th...
======================= Test definitions for plainbox.impl.exporter.text module """ from io import BytesIO from unittest import TestCase from plainbox.impl.exporter.text import TextSessionStateExporter class TextSessionStateExporterTests(TestCase): def test_default_dump(self): exporter = TextSessionSt...
ata format data = {'result_map': {'job_name': {'outcome': 'fail'}}} stream = BytesIO() exporter.dump(data, stream) expected_bytes = "job_name: fail\n".encode('UTF-8') self.assertEqual(stream.getvalue(), expected_bytes)
tensorflow/tpu
models/official/retinanet/retinanet_segmentation_main.py
Python
apache-2.0
10,349
0.004058
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
, 'Location of model_dir') flags.DEFINE_string('resnet_checkpoint', None, 'Location of the ResNet50 checkpoint to use for mode
l ' 'initialization.') flags.DEFINE_string('hparams', '', 'Comma separated k=v pairs of hyperparameters.') flags.DEFINE_integer( 'num_shards', default=8, help='Number of shards (TPU cores)') flags.DEFINE_integer('train_batch_size', 64, 'training batch size') flags.DEFINE_inte...
cbertinato/pandas
pandas/io/excel/_xlsxwriter.py
Python
bsd-3-clause
7,727
0
import pandas._libs.json as json from pandas.io.excel._base import ExcelWriter from pandas.io.excel._util import _validate_freeze_panes class _XlsxStyler: # Map from openpyxl-oriented styles to flatter xlsxwriter representation # Ordering necessary for both determinism and because some are keyed by # pre...
props['font_script'] = ['baseline', 'superscript', 'subscript'].index(props['font_script']) if isinstance(props.get('underline'), str): props['underline'] = {'none': 0, 'single': 1, 'double': 2, 'singleAccounting': 33, ...
}[props['underline']] return props class _XlsxWriter(ExcelWriter): engine = 'xlsxwriter' supported_extensions = ('.xlsx',) def __init__(self, path, engine=None, date_format=None, datetime_format=None, mode='w', **engine_kwargs): # Use the xlsxwriter modu...
FFMG/myoddweb.piger
monitor/api/python/Python-3.7.2/Lib/dataclasses.py
Python
gpl-2.0
48,530
0.000927
import re import sys import copy import types import inspect import keyword import builtins import functools import _thread __all__ = ['dataclass', 'field', 'Field', 'FrozenInstanceError', 'InitVar', 'MISSING', # Helper functions. 'fields',...
.type = None self.default = default self.default_factory = default_factory self.init = init self.repr = repr self.hash = hash self.compare = compare self.metadata = (_EMPTY_METADATA if metadata is None or len(metadata) == 0 else ...
ProxyType(metadata)) self._field_type = None
jebai0521/easy_thumbnail_sample
src/Photo/settings.py
Python
apache-2.0
2,259
0.000443
""" Django settings for Photo project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) impo...
h.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'k8%b02eaonf@nsylxt%4e-p@0@b9%c9&%x@-+^^=wq@h&#crdw' # SECURITY ...
ango.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Photo', 'easy_thumbnails', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.mi...
wangjiezhe/note_for_python
Graph/mincut_maxflow.py
Python
gpl-3.0
898
0
#!/usr/bin/env python import networkx as nx from networkx.algorithms.flow import edmonds_karp def main():
g = nx.DiGraph() g.add_edge('s', 'v1', capacity=5) g.add_edge('s', 'v2', capacity=22) g.add_edge('s', 'v3', capacity=15) g.add_edge('v1', 'v4', capacity=10) g.add_edge('v2', 'v1', capacity=4) g.add_edge('v2', 'v3', capacity=5) g.add_edge('v2', 'v4', capacit
y=5) g.add_edge('v2', 'v5', capacity=9) g.add_edge('v3', 'v5', capacity=6) g.add_edge('v4', 'v5', capacity=15) g.add_edge('v4', 't', capacity=30) g.add_edge('v5', 'v4', capacity=18) g.add_edge('v5', 't', capacity=10) flow = nx.maximum_flow(g, 's', 't') print(flow) print(nx.minimum_cu...
mozvip/Sick-Beard
sickbeard/providers/piratebay/__init__.py
Python
gpl-3.0
15,509
0.01296
# Author: Mr_Orange <[email protected]> # URL: http://code.google.com/p/sickbeard/ # # This file is part of Sick Beard. # # Sick Beard is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3...
TorrentProvider): def __init__(self): generic.TorrentProvider.__init__(self, "PirateBay") self.supportsBacklog = True self.cache = ThePirateBayCache(self) self.proxy = ThePirateBayWebproxy() self.url = 'http://thepiratebay.se/' ...
ent/(?P<id>\d+)/(?P<title>.*?)//1".+?(?P<url>magnet.*?)//1".+?(?P<seeders>\d+)</td>.+?(?P<leechers>\d+)</td>' def isEnabled(self): return sickbeard.THEPIRATEBAY def imageName(self): return 'piratebay.png' def getQuality(self, item): quality = Quality...
TheWeiTheTruthAndTheLight/senior-design
src/get_unique.py
Python
mit
2,936
0.003065
""" get_unique.py USAGE: get_unique.py [-h] [--sarcastic_path SARCASTIC_PATH] [--non_sarcastic_path NON_SARCASTIC_PATH] Create one json file with unique tweets optional arguments: -h, --help show this help message and exit --sarcastic_path path to directory...
FN_HASH = "hash_dict.json" FN_UNIQUE = "unique.json" # Populate list with paths to jsons j
son_paths_lst = [glob.glob(p + "*-*-*_*-*-*.json") for p in top_lvl_paths_lst] # Find and save unique tweets and updated hash dict for json_paths, top_lvl_path in zip(json_paths_lst, top_lvl_paths_lst): # load in existing list of unique tweets if it exists unique_tweets_lst = [] if os.p...
bootphon/abkhazia
abkhazia/corpus/corpus_filter.py
Python
gpl-3.0
13,553
0.000295
# Copyright 2016 Thomas Schatz, Xuan-Nga Cao, Mathieu Bernard # # This file is part of abkhazia: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Abkh...
append([utt, utt_start]) for spkr in self.speakers: spk2utts_temp[spkr] = sorted(spk2utts_temp[spkr], key=lambda x: x[1]) spk2utts[spkr] = [utt for utt, utt_start in spk2utts_temp[spkr]] # create lists of utterances we wa
nt to keep, # utterances we don't want to keep for speaker in names: utt_and_dur = zip(spk2utts[speaker], [utt2dur[utt] for utt in spk2utts[speaker]]) decreasing_utts = sorted(utt_and_dur, ...
ClearCorp/knowledge
document_page_approval/models/document_page_history_workflow.py
Python
agpl-3.0
6,036
0
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 Savoir-faire Linux (<http://www.savoirfairelinux.com>). # # This program is free software: you can redistribute it and/or modify # it under...
else: res = [] res.extend(self.get_approvers_guids_for_page(page.parent_id)) else: res = [] return res @api.multi def _get_approvers_email(self): """Get the approvers email.""" for page in self: emails = '' guids...
= self.env['res.users'].browse(uids) for user in users: if user.email: emails += user.email emails += ',' else: empl = self.env['hr.employee'].search([ ('login', '=', user.login) ...
ryfeus/lambda-packs
Keras_tensorflow_nightly/source2.7/tensorflow/python/__init__.py
Python
mit
10,498
0.000476
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
ort('HistogramProto')(HistogramProto) tf_export('LogMessage')(LogMessage) tf_export('MetaGraphDef')(MetaGraphDef) tf_export('NameAttrList')(NameAttrList) tf_export('NodeDef')(NodeDef) tf_export('OptimizerOptions')(OptimizerOptions) tf_export('RunMetadata'
)(RunMetadata) tf_export('RunOptions')(RunOptions) tf_export('SessionLog', 'summary.SessionLog')(SessionLog) tf_export('Summary', 'summary.Summary')(Summary) tf_export('summary.SummaryDescription')(SummaryDescription) tf_export('SummaryMetadata')(SummaryMetadata) tf_export('summary.TaggedRunMetadata')(TaggedRunMetadata...
AltarBeastiful/rateItSeven
rateItSeven/scan/legacy/moviescanner.py
Python
gpl-3.0
1,660
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # === This file is part of RateItSeven === # # Copyright 2015, Paolo de Vathaire <[email protected]> # # RateItSeven is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free...
# import guessit from rateItSeven.scan.legacy.filescanner import FileScanner from rateItSeven.scan.legacy.containers.movieguess import MovieGuess class MovieScanner(object): """ Scan file system dire
ctories for video files Find info for each file wrapped into a MovieGuess """ def __init__(self, dir_paths: list): self.dir_paths = dir_paths def list_movies(self): return self.list_videos_in_types(["movie"]) def list_episodes(self): return self.list_videos_in_types(["epis...
GeeXboX/mplayer-ui
TOOLS/subfont-c/osd/gen.py
Python
gpl-2.0
8,012
0.021468
#!/usr/bin/python from math import * import sys import string k = (sqrt(2.)-1.)*4./3. chars = [] encoding = [] count = 1 first = 1 def append(s): chars.append(s) def rint(x): return int(round(x)) """ if x>=0: return int(x+0.5) else: return int(x-0.5) """ class vec: def __init__(self, x, y=0)...
in('contrast', 0x07, hsb2, width) movebase(r, r) circle(r+over) circle(-(r+over-80), half=1) end()
######################################## begin('saturation', 0x08, hsb2, width) movebase(r, r) circle(r+over) circle(-(r+over-80)) v = pvec(160, pi/2) movebase(v.x, v.y) circle(80) moveback() v = pvec(160, pi/2+pi*2/3) movebase(v.x, v.y) circle(80) moveback() v = pvec(160, pi/2-pi*2/3) movebase(v.x, v.y) circle(80) ...
hfp/tensorflow-xsmm
tensorflow/python/ops/control_flow_util.py
Python
apache-2.0
12,264
0.0106
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
putContext(i.op) is_cond_merge = is_cond_merge and ctxt is not None an
d ctxt.IsCondContext() return is_cond_merge def IsLoopSwitch(op): """Return true if `op` is the Switch for a while loop.""" if IsSwitch(op): ctxt = op._get_control_flow_context() # pylint: disable=protected-access return ctxt is not None and ctxt.IsWhileContext() and not IsCondSwitch(op) return False...
nijinashok/sos
sos/plugins/manageiq.py
Python
gpl-2.0
3,030
0
# -*- python -*- # -*- coding: utf-8 -*- # Copyright (C) 2015 Red Hat, Inc., Pep Turró Mauri <[email protected]> # This file is part of the sos project: https://github.com/sosreport/sos # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and c...
n.log', 'rhevm.log', 'scvmm.log', 'top_output.log', 'vim.log', 'vmdb_restart.log', 'vmstat_output.log', 'vmstat_output.log', 'apache/miq_apache.log', 'apache/ssl_access.log', 'apache/ssl_error.log', 'apache/ssl_request.log', ...
he/ssl_mirror_request.log', 'apache/ssl_mirror_error.log', 'apache/ssl_mirror_access_error.log', 'gem_list.txt', 'last_startup.txt', 'package_list_rpm.txt', 'vendor_gems.txt' ] def setup(self): if self.get_option("all_logs"): # turn all log fi...
martbhell/wasthereannhlgamelastnight
src/lib/pyasn1_modules/rfc7906.py
Python
mit
18,921
0.002537
# # This file is part of pyasn1-modules software. # # Created by Russ Housley. # # Copyright (c) 2019, Vigil Security, LLC # License: http://snmplabs.com/pyasn1/license.html # # NSA's CMS Key Management Attributes # # ASN.1 source from: # https://www.rfc-editor.org/rfc/rfc7906.txt # https://www.rfc-editor.org/errata/ei...
).subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1))), namedtype.OptionalNamedType('crcAlg', univ.ObjectIdentifier().subtype(
implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 2))) ) aa_keyAlgorithm = Attribute() aa_keyAlgorithm['attrType'] = id_kma_keyAlgorithm aa_keyAlgorithm['attrValues'][0] = KeyAlgorithm() # User Certificate Attribute id_at_userCertificate = univ.ObjectIdentifier('2.5.4.36') aa_userCertificate = At...
pybee/toga-iOS
toga_iOS/window.py
Python
bsd-3-clause
1,335
0.002247
from toga.interface.window import Window as WindowInterface from .container import Container from .libs import * from . import dialogs class Window(WindowInterface): _IMPL_CLASS = UIWindow _CONTAINER_CLASS = Container _DIALOG_MODULE = dialogs def __init__(self, title=None, position=(100, 100), size=...
ef _set_content(self, widget): self._controller.view = self._container._impl def _set_title(self, title): pass def show(self): self._impl.makeKeyAndVisible() # self._impl.visualizeConstraints_(self._impl.contentView().constraints()) # Do the
first layout render. self.content._update_layout( width=self._screen.bounds.size.width, height=self._screen.bounds.size.height )
appop/bitcoin
qa/rpc-tests/prioritise_transaction.py
Python
mit
5,996
0.003169
#!/usr/bin/env python3 # Copyright (c) 2015-2016 The nealcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the prioritisetransaction mining RPC.""" from test_framework.test_framework import nealcoinTestF...
es[0].getrawmempool() assert(high_fee_tx in mempool) # Now verify the modified-high feerate transaction isn't mined before # the other high fee transactions. Keep mining until our mempool has # decreased by all the high fee size that we calculated above. while (self.nodes[0].get...
self.nodes[0].generate(1) # High fee transaction should not have been mined, but other high fee rate # transactions should have been. mempool = self.nodes[0].getrawmempool() print("Assert that de-prioritised transaction is still in mempool") assert(high_fee_tx in mempool) ...
rhyswhitley/savanna_iav
src/figures/modchecks/test_phenology.py
Python
cc0-1.0
3,041
0.005919
#!/usr/bin/env python2 import numpy as np import pandas as pd import datetime as dt import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from os.path import expanduser import scipy def treegrass_frac(ndvi, day_rs): """ Process based on Donohue et al. (2009) to separate out tree and grass cov...
-half: # fold back into the beginning of the time-series twin[im] = _fun(np.hstack([tseries[im-half:tlen],\ tseries[0:half-(tlen-im)]])) else: twin[im] = _fun(tseries[im-half:im+half]) return twin def import_one_year(file_name): ...
abels time_label = ['Month', 'Day', 'Hour', 'Min'] # import data clim_raw = pd.read_csv(clim_met_file) # fix column names clim_raw.columns = time_label + list(clim_raw.columns[4:]) # datetime column clim_raw['DT'] = pd.date_range("2004-01-01", periods=len(clim_raw), freq="30min") # index...
BrightnessMonitor/BrightnessMonitorClient
src/brightnessmonitorclient/raspberry/dbController.py
Python
mit
2,396
0.002087
#!/usr/bin/python # -*- coding: utf-8 -*- import sqlite3 as lite import sys import time sqlite_file = '/var/db/BrightnessMonitor/db.sqlite' table = 'data' vartime = 'time' vardata = 'data' con = None cur = None def create(): ''' Creates database table 'data' with Integer values time and data '''...
: print "delete: Error %s:" % e.args[0] sys.exit(1) with con: cur.execute("DROP TABLE IF EXI
STS data")
tseaver/google-cloud-python
monitoring/tests/unit/gapic/v3/test_metric_service_client_v3.py
Python
apache-2.0
16,399
0.000915
# -*- coding: utf-8 -*- # # Copyright 2019 Google 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
with patch as create_channel: create_channel.return_value = channel client = monitoring_v3.MetricServiceClient() # Setup Request name = client.monitored_resource_descriptor_path( "[PROJECT]", "[MONITORED_RESOURCE_DESCRIP
TOR]" ) response = client.get_monitored_resource_descriptor(name) assert expected_response == response assert len(channel.requests) == 1 expected_request = metric_service_pb2.GetMonitoredResourceDescriptorRequest( name=name ) actual_request = channel...
gkotian/zulip
zerver/test_signup.py
Python
apache-2.0
20,333
0.00182
# -*- coding: utf-8 -*- from django.conf import settings from django.test import TestCase from zilencer.models import Deployment from zerver.models import ( get_realm, get_user_profile_by_email, PreregistrationUser, Realm, ScheduledJob, UserProfile, ) from zerver.lib.actions import ( create_stream_if_nee...
e this Django test mechanism doesn't go # through Tornado. get_urls = {200: ["/accounts/home/", "/accounts/login/"], 302: ["/"], 401: ["/api/v1/streams/Denmark/members", "/api/v1/users/me/subscriptions", "/api/v1...
/login/"], 302: ["/accounts/logout/"], 401: ["/json/get_public_streams", "/json/get_old_messages", "/json/update_pointer", "/json/send_message", "/json/invite_users", ...
start-jsk/jsk_apc
jsk_2016_01_baxter_apc/node_scripts/fcn_mask_for_label_names.py
Python
bsd-3-clause
5,525
0
#!/usr/bin/env python from __future__ import absolute_import from __future__ import division from __future__ import print_function import cv2 from chainer import cuda import chainer.serializers as S from chainer import Variable from fcn.models import FCN32s import numpy as np import cv_bridge import jsk_ap
c2016_common from jsk_topic_tools import ConnectionBasedTransport from jsk_topic_tools.log_utils import logwarn_throttle from jsk_topic_tools.log_utils import jsk_logwarn import message_filters import rospy from sensor_msgs.msg import Image from skimage.color import label2rgb from skimage.transform import resize clas
s FCNMaskForLabelNames(ConnectionBasedTransport): mean_bgr = np.array((104.00698793, 116.66876762, 122.67891434)) def __init__(self): super(self.__class__, self).__init__() # set target_names self.target_names = ['background'] + \ [datum['name'] for datum in j...
mohamedhagag/dvit-odoo8
hr_annual_increase/__init__.py
Python
agpl-3.0
90
0.022222
##python package initial
ization # -*- coding: utf-8 -*- import models #import calcula
tion
kubernetes-client/python
kubernetes/client/models/v2beta2_metric_spec.py
Python
apache-2.0
7,901
0
# coding: utf-8 """ Kubernetes No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: release-1.23 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import si...
e is json key in definition. """ openapi_types = { 'container_resource': 'V2beta2ContainerResourceMetricSource'
, 'external': 'V2beta2ExternalMetricSource', 'object': 'V2beta2ObjectMetricSource', 'pods': 'V2beta2PodsMetricSource', 'resource': 'V2beta2ResourceMetricSource', 'type': 'str' } attribute_map = { 'container_resource': 'containerResource', 'external': 'ext...
28064212D/Prueba
Prueba.py
Python
gpl-2.0
1,593
0.03076
import urllib2 def sumaDos(): print 10*20 def division(a,b): result=a/b print result def cast(): i=10 f=10.5 int(10.6) print "Funcion: " def main(): sumaDos() division(10, 20) def cast(): lista=[1,2,3,"Hola",{"key1":"K","key2":"John"},(1,2,3)] tupla=(1,2,3) ...
else: return False def EXCEPTION(): try: 3/0 except Exception: print "Error" def main(): e=Estudiante("K"
, 20) print "Hola %s" % e.hola() if e.esMayor(): print "Es mayor de edad" else: print "No es mayor de edad" contador=0 while contador<=10: print contador contador +=1 EXCEPTION() def getWeb(): try: web = urllib2.urlopen("http://itjiquilpan.edu.mx/...
industrydive/premailer
premailer/__init__.py
Python
bsd-3-clause
124
0
from __future__ import absolute_import, uni
code_literals from .premailer import Premailer, transform __version__ = '2.9.
4'
anhstudios/swganh
data/scripts/templates/object/building/poi/shared_dathomir_singingmtnclanpatrol_large2.py
Python
mit
467
0.047109
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY
BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Building() result.template = "object/building/poi/shared_dathom
ir_singingmtnclanpatrol_large2.iff" result.attribute_template_id = -1 result.stfName("poi_n","base_poi_building") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
SchrodingersGat/kicad-footprint-generator
scripts/Connector/Connector_Molex/conn_molex_micro-fit-3.0_tht_top_dual_row.py
Python
gpl-3.0
11,943
0.007117
#!/usr/bin/env python ''' kicad-footprint-generator is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. kicad-footprint-generator is distribute...
hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPO
SE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with kicad-footprint-generator. If not, see < http://www.gnu.org/licenses/ >. ''' import sys import os #sys.path.append(os.path.join(sys.path[0],"..","..","kicad_mod")) # load kicad_mod pa...
albertoconnor/website
wordpress_importer/__init__.py
Python
mit
74
0
default_
app_config = 'wordpress_importer.apps.WordpressImporterAppConfig'
sasha-gitg/python-aiplatform
google/cloud/aiplatform_v1beta1/services/index_endpoint_service/async_client.py
Python
apache-2.0
35,143
0.001366
# -*- coding: utf-8 -*- # Copyright 2020 Google 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...
xceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ self._client = IndexEndpointServiceClient( credentials=credentials, transport=transport, client_options=client_options, client_info=client_info, ...
point_service.CreateIndexEndpointRe
rtucker-mozilla/mozilla_inventory
mozdns/mozbind/tests/build_tests.py
Python
bsd-3-clause
10,431
0.000096
# These tests are similar to the ones in the scripts directory. They not ran on # real data so the testing db needs to be filled with info. import os from django.test.client import Client from django.test import TestCase from mozdns.soa.models import SOA from mozdns.domain.models import Domain from mozdns.address_reco...
t. self.assertEqual( SOA.objects.get(pk=root_domain.soa.pk).serial, tmp_seria
l + 1 ) self.assertEqual((0, 0), b.svn_lines_changed(b.PROD_DIR)) # no lines should have changed if we would have built again self.assertFalse(SOA.objects.get(pk=root_domain.soa.pk).dirty) tmp_serial = SOA.objects.get(pk=root_domain.soa.pk).serial b.PUSH_TO_PROD = False...
googleinterns/nlu-seq2graph
src/trainer.py
Python
apache-2.0
15,345
0.007559
""" Copyright 2020 Google 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 https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distr...
t32) exact_accuracy.update_state(tf.ones_like(exact_match), exact_match) return loss, predictions, beam_predictions def train(model_type, epochs, train_set, dev_set, src_vocab, tgt_vocab, hparams, save_model_path): optimizer = tf.keras.optimizers.Adam( learning_rate=NoamSchedule(FLAGS.model_...
pass os.mkdir(save_model_path) best_token_accuracy_train = 0 best_token_accuracy_train_epoch = 0 best_token_accuracy_dev = 0 best_token_accuracy_dev_epoch = 0 for epoch in range(epochs): train_start = time.time() total_train_loss = 0 token_accuracy_train = tf.keras.metrics.Accuracy() e...
danleyb2/Instagram-API
InstagramAPI/src/http/Response/Objects/Comment.py
Python
mit
1,671
0
from .User import User class Comment(object): def __init__(self, commentData): self.status = None self.username_id = None self.created_at_utc = None self.created_at = None self.b
it_flags = None self.user = None self.comment = None self.pk = None self.type = None self.media_id = None self.status = commentData['status'] if 'user_id' in commentData and commentData['user_id']: self.username_id = commentData['user_id'] sel...
ntData['created_at'] if 'bit_flags' in commentData and commentData['bit_flags']: self.bit_flags = commentData['bit_flags'] self.user = User(commentData['user']) self.comment = commentData['text'] self.pk = commentData['pk'] if 'type' in commentData and commentData['ty...
smithchristian/arcpy-create-chainages
main.py
Python
mit
2,746
0.005462
#------------------------------------------------------------------------------- # Name: Main.py # Purpose: This script creates chainages from a single or mutile line # # Author: smithc5 # # Created: 10/02/2015 # Copyright: (c) smithc5 2015 # Licence: <your licence> #------------------------...
source alignment. database_locatio
n = arcpy.GetParameterAsText(1) # Variable to store the location where the database is created to store the. # feature classes. chainage_distance = arcpy.GetParameterAsText(2) new_fc_name = os.path.basename(source_align_location[:-4]) # New name for the copied feature class. Original name minus file extension ...
cysuncn/python
spark/crm/PROC_A_SUBJECT_D002015.py
Python
gpl-3.0
3,179
0.015479
#coding=UTF-8 from pyspark import SparkContext, SparkConf, SQLContext, Row, HiveContext from pyspark.sql.types import * from datetime import date, datetime, timedelta import sys, re, os st = datetime.now() conf = SparkConf().setAppName('PROC_A_SUBJECT_D002015').setMaster(sys.argv[2]) sc = SparkContext(conf = conf) sc....
YP AS VARCHAR(5)) AS CUST_TYPE ,CAST(A.FR_ID AS VARCHAR(5)) AS FR_ID FROM ACRM_F_CI_ASSET_BUSI
_PROTO A WHERE A.BAL > 0 AND A.LN_APCL_FLG = 'N' AND(A.PRODUCT_ID LIKE '1010%' OR A.PRODUCT_ID LIKE '1030%' OR A.PRODUCT_ID LIKE '1040%' OR A.PRODUCT_ID LIKE '1050%' OR A.PRODUCT_ID LIKE '1060%' OR A.P...
mick-d/nipype
nipype/interfaces/ants/utils.py
Python
bsd-3-clause
11,113
0.00189
# -*- coding: utf-8 -*- """ANTS Apply Transforms interface Change directory to provide relative paths for doctests >>> import os >>> filepath = os.path.dirname( os.path.realpath( __file__ ) ) >>> datadir = os.path.realpath(os.path.join(filepath, '../../testing/data')) >>> os.chdir(datadir) """ from __fu...
4, desc='return the geometric jacobian') class CreateJacobianDeterminantImageOutputSpec(TraitedSpec): jacobian_image = File(exists=True, desc='jacobian image') class CreateJacobianDeterminantImage(ANTSCommand): """ Examples -------- >>> from nipype.interfaces.ants ...
CreateJacobianDeterminantImage() >>> jacobian.inputs.imageDimension = 3 >>> jacobian.inputs.deformationField = 'ants_Warp.nii.gz' >>> jacobian.inputs.outputImage = 'out_name.nii.gz' >>> jacobian.cmdline # doctest: +ALLOW_UNICODE 'CreateJacobianDeterminantImage 3 ants_Warp.nii.gz out_name.nii.gz' ...
DailyActie/Surrogate-Model
01-codes/tensorflow-master/tensorflow/python/kernel_tests/matrix_solve_ls_op_test.py
Python
mit
9,206
0.000978
# Copyright 2015 Google Inc. All Rights Reserved. # # 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 a...
p.dot(a, b) # Get the number of matrices. n
= np.prod(a.shape[:-2]) assert n == np.prod(b.shape[:-2]) a_flat = np.reshape(a, tuple([n]) + a.shape[-2:]) b_flat = np.reshape(b, tuple([n]) + b.shape[-2:]) c_flat_shape = [n, a.shape[-2], b.shape[-1]] c_flat = np.empty(c_flat_shape) for i in range(n): c_flat[i, :, :] = np.dot(a_flat[i...
philterphactory/prosthetic-runner
base_prosthetic.py
Python
mit
3,132
0.008301
# Copyright (C) 2011 Philter Phactory Ltd. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publi...
["foo"] = "bar" return "persisted state!" """ def wrap(self, *args, **argv): if self.token.data: self.state = json.loads(self.token.data) else: self.state = {}
try: ret = f(self, *args, **argv) finally: self.token.data = json.dumps(self.state) # we can rely on the runner to save the token return ret return wrap
Microvellum/Fluid-Designer
win64-vc/2.78/python/lib/test/test_property.py
Python
gpl-3.0
8,501
0.002823
# Test case for property # more tests are in test_descr import sys import unittest class PropertyBase(Exception): pass class PropertyGet(PropertyBase): pass class PropertySet(PropertyBase): pass class PropertyDel(PropertyBase): pass class BaseClass(object): def __init__(self): self._sp...
rtyDocBase.spam.getter def spam(self): """The decorator does not use this doc string""" return self._spam class PropertySubNewGetter(BaseClass): @BaseClass.spam.getter def spam(self): """new docstring""" return 5 class PropertyNewGetter(object): @property def spam(s...
tyWritableDoc(object): @property def spam(self): """Eggs""" return "eggs" class PropertyTests(unittest.TestCase): def test_property_decorator_baseclass(self): # see #1620 base = BaseClass() self.assertEqual(base.spam, 5) self.assertEqual(base._spam, 5) ...
nikdoof/test-auth
app/eve_api/models/corporation.py
Python
bsd-3-clause
3,689
0.002982
from django.db import models from django.contrib.auth.models import Group from gargoyle import gargoyle from eve_api.models import EVEAPIModel from eve_api.app_defines import * class EVEPlayerCorporation(EVEAPIModel): """ Represents a player-controlled corporation. Updated from a mixture of the alliance...
s.Fl
oatField(blank=True, null=True) member_count = models.IntegerField(blank=True, null=True) shares = models.IntegerField(blank=True, null=True) # Logo generation stuff logo_graphic_id = models.IntegerField(blank=True, null=True) logo_shape1 = models.IntegerField(blank=True, null=True) logo_shape2...
jainanisha90/WeVoteServer
elected_office/urls.py
Python
mit
1,030
0.007767
# elected_office/urls.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- from django.conf.urls import url from . import views_admin urlpatterns = [ # views_admin url(r'^$', views_admin.elected_office_list_view, name='elected_office_list', ), url(r'^delete/$', views_admin.elected_office_dele...
ice_update_view, name='elected_office_update'), url(r'^real_time
_status/$', views_admin.elected_office_update_status, name='elected_office_update_status'), url(r'^(?P<elected_office_id>[0-9]+)/edit/$', views_admin.elected_office_edit_view, name='elected_office_edit'), url(r'^(?P<elected_office_id>[0-9]+)/summary/$', views_admin.elected_office_summary_view, name='ele...
jeremiah-c-leary/vhdl-style-guide
vsg/rules/instantiation/rule_024.py
Python
gpl-3.0
526
0.001901
from vsg import deprecated_rule class rule_024(deprecated_rule.Rule): ''' This rule has been split in
to: * `generic_map_008 <generic_map_rules.html#generic-map-008>`_ * `port_map_008 <port_map_rules.html#port-map-008>`_ ''' def __init__(self): deprecated_rule.Rule.__init__(self, 'instantiation', '024') self.message.append('Rule ' + s
elf.unique_id + ' has been split into rules:') self.message.append(' generic_map_008') self.message.append(' rule port_map_005')
matthiask/django-content-editor
content_editor/contents.py
Python
bsd-3-clause
2,812
0.000356
from itertools import chain from operator import attrgetter __all__ = ("Contents", "contents_for_items", "contents_for_item") class Contents: def __init__(self, regions): self.regions = regions self._sorted = False self._contents = {region.key: [] for region in self.regions} self...
queryset = queryset.filter(region__in=[region.key for region in regions]) queryset._known_related_objects.setdefault( plugin._meta.get_field("parent"), {} ).update(items_dict) for obj in queryset: contents[obj.parent].add(ob
j) return contents def contents_for_item(item, plugins, *, inherit_from=None, regions=None): inherit_from = list(inherit_from) if inherit_from else [] all_contents = contents_for_items( [item] + inherit_from, plugins=plugins, regions=regions ) contents = all_contents[item] for item in ...
Horta/limix
limix/sh/_hash.py
Python
apache-2.0
582
0
from __future__ import division # # TODO: document those functions # def array_hash(X): # wr
iteable = X.flags.writeable # X.flags.writeable = False # h = hash(X.tobytes()) # X.flags.writeable = writeable # return h def filehash(filepath): r"""Compute sha256 from a given file.""" import hashlib BUF_SIZE = 65536 sha256 = hashlib.sha256() with open(filepath, "rb") as f: ...
while True: data = f.read(BUF_SIZE) if not data: break sha256.update(data) return sha256.hexdigest()
bettocr/rpi-proyecto-final
opt/luz.py
Python
bsd-3-clause
874
0.052632
#!/usr/bin/env python # Realizado por: Roberto Arias (@bettocr) # # Permite encender y apagar luces leds # import RPi.GPIO as GPIO, time, os GPIO.setmode(GPIO.BCM) on = 0 # luces encendidas MAX=5200 # luminocidad maxima antes de encender el led, entre mayor mas oscuro PIN=23 # pin al relay PINRC=24 #pin qu...
reading = 0 GPIO.setup(RCpin, GPIO.OUT) GPIO.output(RCpin, GPIO.LOW) time.sleep(0.1) GPIO.setup(RCpin, GPIO.IN)
while (GPIO.input(RCpin) == GPIO.LOW): reading += 1 return reading while True: #print RCtime(24) luz = RCtime(PINRC) if luz > MAX: GPIO.output(PIN,True) on = 1 if luz < MAX and on == 1: GPIO.output(PIN,False) on ...
ging/keystone
keystone/tests/ksfixtures/appserver.py
Python
apache-2.0
2,648
0
# Copyright 2013 OpenStack Foundation # # 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, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import import fixtures from paste import deploy from keystone.common import environment from keystone import config CONF = config.CONF M...
lordwolfchild/subnetmapper
pySubnetMapConvert.py
Python
gpl-3.0
4,646
0.016143
#!/usr/bin/python from plistlib import * import socket, struct from ctypes import * from optparse import OptionParser usage = "usage: %prog [options] infile outfile" parser = OptionParser(usage) (options,args)=parser.parse_args() if len(args)!=2: parser.error("incorrect number of arguments") try: with open(...
olor_str = "<color>#{0:02X}{1:02X}{2:02X}</color>".format(color_r,color_g,color_b); # Ok, I lied a little bit, another interesting part is the ip address # and the netma
sk. In the original fileformat they are saved as integers # and need to be converted into strings in the classical 4-byte long, # dot-seperated format. # get the integer ip_int=pl['$objects'][sn_IP_index] # convert it into a ctype uint32 and get a pointer to it i = c_uint32(ip_int) ...
google/uncertainty-baselines
baselines/jft/experiments/jft300m_vit_base16_finetune_cifar100.py
Python
apache-2.0
4,319
0.017365
# coding=utf-8 # Copyright 2022 The Uncertainty Baselines Authors. # # 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 ap...
ict() conf
ig.model.transformer.attention_dropout_rate = 0. config.model.transformer.dropout_rate = 0. config.model.transformer.mlp_dim = 3072 config.model.transformer.num_heads = 12 config.model.transformer.num_layers = 12 config.model.classifier = 'token' # Or 'gap' # This is "no head" fine-tuning, which we use by...
Azure/azure-sdk-for-python
sdk/automanage/azure-mgmt-automanage/azure/mgmt/automanage/operations/_configuration_profile_preferences_operations.py
Python
mit
22,341
0.004431
# 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 may ...
body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'ConfigurationProfilePreference') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_res...
map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize(models.ErrorResponse, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = ...
chriszs/redash
redash/query_runner/influx_db.py
Python
bsd-2-clause
2,575
0
import logging from redash.query_runner import * from redash.utils import json_dumps logger = logging.getLogger(__name__) try: from influxdb import InfluxDBClusterClient enabled = True except ImportError: enabled = False def _transform_result(results): result_columns = [] result_rows = [] ...
}) class InfluxDB(BaseQueryRunner): noop_query = "show measurements limit 1" @classmethod def configuration_schema(cls): return { 'type': 'object', 'properties': { 'url': { 'type': 'string' } }
, 'required': ['url'] } @classmethod def enabled(cls): return enabled @classmethod def annotate_query(cls): return False @classmethod def type(cls): return "influxdb" def run_query(self, query, user): client = InfluxDBClusterClient.from...
zhaogp/oxygen
oxygen/wsgi.py
Python
mit
390
0
""" WSGI config for oxygen project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setd
efault("DJANGO_SETTIN
GS_MODULE", "oxygen.settings") application = get_wsgi_application()
open-craft/edx-analytics-dashboard
analytics_dashboard/courses/tests/test_views/test_csv.py
Python
agpl-3.0
5,748
0.002088
from ddt import ddt, data from django.core.urlresolvers import reverse from django.test import TestCase import mock from analyticsclient.exceptions import NotFoundError from courses.tests import SwitchMixin from courses.tests.test_views import ViewTestMixin, DEMO_COURSE_ID, DEPRECATED_DEMO_COURSE_ID from courses.tests...
course_id = 'fakeOrg/soFake/Fake_Course' self.grant_
permission(self.user, course_id) path = reverse(self.viewname, kwargs={'course_id': course_id}) with mock.patch(self.api_method, side_effect=NotFoundError): response = self.client.get(path, follow=True) self.assertEqual(response.status_code, 404) class CourseEnrollmentByCountr...
hermanschaaf/mafan
bin/mafan_download.py
Python
mit
291
0.003436
from mafan import download_data if __name__ == '__main__': confirm = i
nput( "You are about to download all dicti
onary files. Could be up to 50MB in total. Are you sure?\n (y/n) ") if confirm == 'y' or confirm == 'yes': download_data.download_traditional_word_list()
fpischedda/django-messages
django_messages/admin.py
Python
bsd-3-clause
4,053
0.00074
from django import forms from django.conf import settings from django.utils.translation import gettext_lazy as _ from django.contrib import admin from django.contrib.auth.models import Group from django_messages.utils import get_user_model User = get_user_model() if "notification" in settings.INSTALLED_APPS: from...
recipient and looks in the form instance for other possible recipients. Prevents duplication by excludin the origin
al recipient from the list of optional recipients. When changing an existing message and choosing optional recipients, the message is effectively resent to those users. """ obj.save() if notification: # Getting the appropriate notice labels for the sender and ...
shearern/PyWizard
src/py_wizard/console_wiz_iface/ConsoleNameQuestion.py
Python
mit
276
0.007246
''' Creat
ed on Sep 20, 2013 @author: nshearer ''' from ConsoleSimpleQuestion import ConsoleSimpleQuestion class ConsoleNameQuestion(ConsoleSimpleQuestion): def __init__(self, question)
: super(ConsoleNameQuestion, self).__init__(question)
cuducos/getgist
getgist/local.py
Python
mit
2,630
0
import os from click import confirm from getgist import GetGistCommons class LocalTools(GetGistCommons): """Helpers to deal with local files and local file system""" def __init__(self, filename, assume_yes=False): """ Sets the file name to be used by the instance. :param filename: (...
tf-8") handler.write(content) self.yeah("Done!") def backup(self): """Backups files with the same name of the instance filename""" count = 0 name = "{}.bkp".format(self.filename) backup = os.path.join(self.cwd, name) while os.path.exists(backup): ...
ing {} to {}".format(self.filename, name)) os.rename(os.path.join(self.cwd, self.filename), backup) def read(self, file_path=None): """ Read the contents of a file. :param filename: (str) path to a file in the local file system :return: (str) contents of the file, or (False)...
psf/black
tests/data/fmtonoff.py
Python
mit
9,645
0.015034
#!/usr/bin/env python3 import asyncio import sys from third_party import X, Y, Z from library import some_connection, \ some_decorator # fmt: off from third_party import (X, Y, Z) # fmt: on f'trigger 3.6 mode' # Comment 1 # Comment 2 # fmt: off def func_no_args(): a; b...
a = ( unnecessary_brack
et() ) # fmt: on _type_comment_re = re.compile( r""" ^ [\t ]* \#[ ]type:[ ]* (?P<type> [^#\t\n]+?
harrijs/gns3-server
gns3server/web/response.py
Python
gpl-3.0
3,573
0.001679
# -*- coding: utf-8 -*- # # Copyright (C) 2015 GNS3 Technologies Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. ...
self, template_filename, **kwargs): """ Render a template :params template: Template name :params kwargs: Template parameters """ template = renderer.get_template(template_filename)
kwargs["gns3_version"] = __version__ kwargs["gns3_host"] = self._request.host self.html(template.render(**kwargs)) def json(self, answer): """ Set the response content type to application/json and serialize the content. :param anwser The response as a Python obj...
thaim/ansible
lib/ansible/modules/crypto/openssh_cert.py
Python
mit
22,137
0.003072
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2018, David Kainz <[email protected]> <[email protected]> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { 'metadat...
ertificate that is valid from 21.1.2001 to 21.1.2019 - openssh_cert:
type: host signing_key: /path/to/private_key public_key: /path/to/public_key.pub path: /path/to/certificate valid_from: "2001-01-21" valid_to: "2019-01-21" # Generate an OpenSSH user Certificate with clear and force-command option: - openssh_cert: type: user signing_key: /path/to/priva...
mottosso/pyblish
pyblish/__init__.py
Python
lgpl-3.0
720
0
"""Pyblish initialisation Attributes: _registered_paths: Currently registered plug-in paths. _registered_plugins: Currently registered plug-ins. """ from .version import version, version_info, __version__ _registered_paths = list() _registered_callbacks = dict() _registered_plugins = dict() _registered_ser...
"_registered_targets", "_registe
red_gui", ]
bmcfee/gordon
gordon/db/gordon_db.py
Python
gpl-3.0
29,325
0.023257
#!/usr/bin/env python # Copyright (C) 2010 Douglas Eck # # This file is part of Gordon. # # Gordon is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any la...
raw_sql) #from gordon.db.config import DEF_GORDON_DIR, DEF_DBUSER, DEF_DBPASS, DEF_DBHOST from gordon.db import config from gordon.i
o import AudioFile log = logging.getLogger('gordon') log.info('Using gordon directory %s', config.DEF_GORDON_DIR) #------------------ #Helper functions #------------------- #we have some values cached (album.trackcount, artist.trackcount) #after we do our cascading deletes we need to update those thing...
molly/brandeis
tests/testvalidator.py
Python
gpl-3.0
3,946
0.007856
# -*- coding: utf-8 -*- # Brandeis - A tool to convert plaintext court cases (from the lochner # tool: http://gitorious.org/lochner/) to wikitext. # # Copyright (C) 2013 Molly White # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as
published by # the Free So
ftware Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License ...
cloudbase/compute-hyperv
hyperv/tests/unit/test_migrationops.py
Python
apache-2.0
25,443
0
# Copyright 2014 IBM Corp. # # 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 ...
cleanup): instance_path = 'fake/instance/path' fake_dest_path = '%s_tmp' % instance_path self._migrationops._pathutils.get_instance_dir.return_value = ( instance_path) get_revert_dir = ( self._migrationops._pathutils.get_instance_migr_revert_dir) self._mig...
el.dest_path] self._migrationops._pathutils.copy.side_effect = IOError( "Expected exception.") self.assertRaises(IOError, self._migrationops._migrate_disk_files, instance_name=mock.sentinel.instance_name, disk_files=[self._FAKE_DISK], ...
paplorinc/intellij-community
python/testData/inspections/PyTypeCheckerInspection/NamedTupleBaseClass.py
Python
apache-2.0
186
0.010753
from collections im
port namedtuple class C(namedtupl
e('C', ['foo', 'bar'])): pass def f(x): return x.foo, x.bar def g(): x = C(foo=0, bar=1) return f(x) print(g())
korbonits/kaggle-tau-to-three-muons
ensemble_model.py
Python
mit
5,133
0.003117
import numpy as np import pandas as pd from sklearn.ensemble import RandomForestClassifier import xgboost as xgb from keras.models import Sequential from keras.layers.core import Dense, Activation, Dropout from keras.layers.advanced_activations import PReLU from keras.models import Sequential from keras.utils import np...
, y = get_training_data() print('Data shape:', X.shape) # shuffle the data np.random.s
eed(248) np.random.shuffle(X) np.random.seed(248) np.random.shuffle(y) print('Signal ratio:', np.sum(y) / y.shape[0]) # preprocess the data X, scaler = preprocess_data(X) y = np_utils.to_categorical(y) # split into training / evaluation data nb_train_sample = int(len(y) * 0.97) X_train = X[:nb_train_sample] X_eval =...
JohannesV/Fall_Prevention_2013
Data and scripts/plot_acc_vector.py
Python
apache-2.0
1,112
0.022482
import matplotlib.pyplot as plt import math import peak_algorithm as pa z_data = [] x_data = [] y_data = [] with open('a_z.txt') as file: for line in file: line = line.strip() z_data.append(float(line)) w
ith open('a_x.txt') as file: for line in file: line = line.strip() x_data.append(float(line)) with open('a_y.txt') as file: for line in file: line = line.strip() y_data.append(float(line)) vector = [] for i in xrange(len(z_data)): length = math.sqrt(x_data[i]**2 + z_data[i]**2 + y_data[i]**2) vector.append...
g(vector, 3) plt.plot(s_vector_3) #s_vector_4 = pa.smooth_moving(vector, 4) #plt.plot(s_vector_4) #s_vector_5 = pa.smooth_moving(vector, 5) #plt.plot(s_vector_5) #peaks = pa.find_peaks(time_series=s_vector_5) #plt.plot(peaks) #plt.hlines(th, 0, 4500) # Print peaks #for peak in peaks: # plt.vlines(peak, min(vector), ...
ericstalbot/movespy
movespy/ratetable.py
Python
bsd-2-clause
8,746
0.01635
# Copyright (c) 2013, Resource Systems Group, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # - Redistributions of source code must retain the above copyright notice, # this...
e_ids, sour
cetypeshare) link['opmode_distr'] = dict.fromkeys(source_type_ids, {opmode:1.0}) links[linkid] = link linkid += 1 activity['links'] = links options2 = {'detail':'opmode', 'breakdown':['source']} if 'process' in options.get('breakdown',[]): options2['brea...
enthought/graystruct
setup.py
Python
bsd-3-clause
4,358
0
# -*- coding: utf-8 -*- # Copyright (c) 2015 Simon Jagoe and Enthought Ltd # All rights reserved. # # This software may be modified and distributed under the terms # of the 3-clause BSD license. See the LICENSE.txt file for details. import os import subprocess from setuptools import setup MAJOR = 0 MINOR = 1 MICRO ...
git_r
evision = "Unknown" try: out = _minimal_ext_cmd(['git', 'describe', '--long']) out = out.strip().decode('ascii') if len(out) == 0: git_count = _fallback() else: last_tag, git_count, _ = out.split('-') except OSError: git_count = '0' return gi...
helfertool/helfertool
src/registration/feeds.py
Python
agpl-3.0
1,186
0.001686
from django.conf import settings from django.urls import reverse from django_ical.views import ICalFeed from registration.utils import get_or_404 class HelperFeed(ICalFeed): timezone = settings.TIME_ZONE product_id = "-//helfertool.org//Helfertool" def get_object(self, request, event_url_name, helper_p...
t.job.name) def item_description(self, shift): return "" def item_link(self, shift)
: return self._registered_link def item_start_datetime(self, shift): return shift.begin def item_end_datetime(self, shift): return shift.end def item_guid(self, shift): return "{}#{}".format(self.item_link(shift), shift.pk)
rmadapur/networking-brocade
networking_brocade/vdx/tests/unit/ml2/drivers/brocade/test_brocade_l3_plugin.py
Python
apache-2.0
2,112
0
# Copyright (c) 2014 OpenStack Foundation # # 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 ...
tExtensionTestCase,
BrocadeSVIPlugin_TestCases): pass
rgtjf/Semantic-Texual-Similarity-Toolkits
stst/modules/features.py
Python
mit
5,022
0.001799
# coding: utf8 from __future__ import print_function import json import os import pyprind from stst import utils from stst import config class Feature(object): def __init__(self, load=True, dimension=None, **kwargs): self.load = load self.featu...
.txt' return self.load_instances(train_instances) def load_instances(self, train_instances): """ extract features from train_set """ if self.load is False or not os.path.isfile(self.feature_file):
print(self.feature_file) ''' extract features to features ''' features, infos = self.extract_instances(train_instances) ''' write features to file ''' Feature.write_feature_to_file(self.feature_file, features, infos) ''' load features from file '''...
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/media/audio/PRESUBMIT.py
Python
gpl-3.0
1,539
0.008447
# Copyright (c) 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Top-level presubmit script for media/audi
o/. See http://dev.chromium.org/developers/how-tos/depottools/presub
mit-scripts for more details about the presubmit API built into depot_tools. """ import re def PostUploadHook(cl, change, output_api): """git cl upload will call this hook after the issue is created/modified. This hook modifies the CL description in order to run extra GPU tests (in particular, the WebGL 2.0 co...
jdahlin/pygobject
tests/test_signal.py
Python
lgpl-2.1
12,201
0.001229
# -*- Mode: Python -*- import gc import unittest import sys from gi.repository import GObject try: import testhelper except ImportError: testhelper = None from compathelper import _long class C(GObject.GObject): __gsignals__ = {'my_signal': (GObject.SignalFlags.RUN_FIRST, None, ...
e.status = 2 def _callback(self, e): if self.hook: self.assertEqual(e.status, 2) else: self.assertEqual(e.status, 1) e.status = 3 def testCallbackReturnFalse(self): self.hook = False obj = F() def _emission_hook(obj): ob...
self.assertEqual(obj.status, 3) def testCallbackReturnTrue(self): self.hook = False obj = F() def _emission_hook(obj): obj.status += 1 return True hook_id = GObject.add_emission_hook(obj, "signal", _emission_hook) obj.emit('signal') ob...
waipu/bakawipe
lib/sup/special.py
Python
gpl-3.0
2,073
0.00193
from io import BytesIO try: import simplejson as json except ImportError: import json try: import msgpack has_msgpack = True except ImportError: has_msgpack = False class SpecialBase(object): def __init__(self, *args, **kvargs): self.encoding = 'utf-8' def json(self, *args, **kvarg...
encoding if encoding else self.encoding b = SpecialBytes(str.encode(self, e, errors)) b.encoding = e return b class SpecialBytesIO(BytesIO): def __init__(self, *args, **kvargs): self.encoding = 'utf-8' super().__init__(*args, **kvargs) def s_getvalue(self) -> SpecialByt...
s = SpecialBytes(self.getbuffer()) s.encoding = self.encoding return s
vuolter/pyload
src/pyload/plugins/accounts/RapidfileshareNet.py
Python
agpl-3.0
532
0.00188
# -*- coding: utf-8 -*- from ..base.xfs_account import XFSAccount clas
s RapidfileshareNet(XFSAccount): __name__ = "RapidfileshareNet" __type__ = "account" __version__ = "0.11" __statu
s__ = "testing" __description__ = """Rapidfileshare.net account plugin""" __license__ = "GPLv3" __authors__ = [("guidobelix", "[email protected]")] PLUGIN_DOMAIN = "rapidfileshare.net" TRAFFIC_LEFT_PATTERN = r'>Traffic available today:</TD><TD><label for="name">\s*(?P<S>[\d.,]+)\s*(?:(?P<U>[\...
bjodah/chempy
chempy/equilibria.py
Python
bsd-2-clause
16,931
0.000886
# -*- coding: utf-8 -*- """ Module collecting classes and functions for dealing with (multiphase) chemical equilibria. .. Note:: This module is provisional at the moment, i.e. the API is not stable and may break without a deprecation cycle. """ import warnings import numpy as np from .chemistry import equilib...
ew_concs = concs.copy() for r in self.rxns: if r.has_precipitates(self.substances): net_stoich = np.asarray(r.net_stoich(self.substances)) s_net, s_sto
ich, s_idx = r.precipitate_stoich(self.substances) new_concs -= new_concs[s_idx] / s_stoich * net_stoich return new_concs def _fw_cond_factory(self, ri, rtol=1e-14): rxn = self.rxns[ri] def fw_cond(x, p): precip_stoich_coeff, precip_idx = rxn.precipitate_stoich(...
frucker/CryoTUM
sub_vi-s/Equipment/PPMS/PPMSLabView/Socket_Server/qdinstrument.py
Python
gpl-3.0
2,308
0.001733
import win32com.client import pythoncom class QDInstrument: def __init__(self, instrument_type): instrument_type = instrument_type.upper() if instrument_type == 'DYNACOOL': self._class_id = 'QD.MULTIVU.DYNACOOL.1' elif instrument_type == 'PPMS': self._class_id = 'QD...
1 = win32com.client.VARIANT(pythoncom.VT_BYREF | pythoncom.VT_I4, 0) err = self._mvu.GetField(arg0, arg1) # win32com reverses the arguments, so: return err, arg1.value, arg0.value def set_chamber(self, code): """Sets chamber and returns MultiVu error code""" err = self._mvu....
atus and returns (MultiVu error, status)""" arg0 = win32com.client.VARIANT(pythoncom.VT_BYREF | pythoncom.VT_I4, 0) err = self._mvu.GetChamber(arg0) return err, arg0.value
ScienceMob/vmicroc
data/views.py
Python
gpl-2.0
1,284
0.000779
from django import forms from django.contrib import messages from django.contrib.admin.views.decorators import staff_member_required from django.shortcuts import render from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from data.models import ImportTask class ImportTaskForm(fo...
mport_task_form.is_valid(): import_task = import_task_form.save() import_task.enqueue()
messages.info(request, 'Data file queued for processing') return HttpResponseRedirect(reverse('data_upload')) else: import_task_form = ImportTaskForm() return render(request, 'data/upload.html', { 'import_task_form': import_task_form, }) @staff_member_require...
paulboal/pexpect-curses
demo/demo3.py
Python
mit
1,476
0.023035
#!/usr/bin/python import pexpect import sys import logging import vt102 import os import time def termcheck(child, timeout=0): time.sleep(0.05) try: logging.debug("Waiting for EOF or timeout=%d"%timeout) child.expect(pexpect.EOF, timeout=timeout) except pexpect.exceptions.TIMEOUT: logging.debug("Hit timeout...
s = termcheck(child) logging.debug("Sending child.before (len=%d) text to vt102 stream"%len(child.before)) stream.process(child.before) logging.debug("vt102 screen dump") logging.debug(screen) termkey(child, stre
am, screen, "a") termkey(child, stream, screen, "1") logging.debug("Quiting...")
isomer/faucet
faucet/valve_of.py
Python
apache-2.0
11,359
0.000264
"""Utility functions to parse/create OpenFlow messages.""" # Copyright (C) 2013 Nippon Telegraph and Telephone Corporation. # Copyright (C) 2015 Brad Cowie, Christopher Lorier and Joe Stringer. # Copyright (C) 2015 Research and Education Advanced Network New Zealand Ltd. # Copyright (C) 2015--2017 The Contributors # #...
t. Returns: ryu.ofproto.ofproto_v1_3_parser.OFPActionOutput. """ return output_port(ofp.OFPP_IN_PORT) def output_controller(): """Return OpenFlow action
to packet in to the controller (max 128 bytes). Returns: ryu.ofproto.ofproto_v1_3_parser.OFPActionOutput: packet in action. """ return output_port(ofp.OFPP_CONTROLLER, 128) def packetout(port_num, data): """Return OpenFlow action to packet out to dataplane from controller. Args: ...
shuaizi/leetcode
leetcode-python/num315.py
Python
apache-2.0
1,742
0.000574
__author__ = 'shuai' class Solution(object): def countSmaller(self, nums): """ :type nums: List[int] :rtype: List[int] """ count = [] ret = [0] * len(nums) for i in range(len(nums)): count.append({'index': i, 'value': num...
> end: tmp[k] = nums[i] ret[tmp[k].get('index')] += jump i += 1 elif nums[i].get('value') <= nums[j].get('value'): tmp[k] = nums[i] ret[tmp[k].get('index')] += jump i += 1
else: tmp[k] = nums[j] j += 1 jump += 1 k += 1 while i <= mid: tmp[k] = nums[i] i += 1 k += 1 while j <= end: tmp[k] = nums[j] j += 1 k += 1 k = 0 ...
mooster311/Gigabot
cogs/events.py
Python
mit
4,025
0.004969
import discord import injector import database import pymongo class Events: """Events""" def __init__(self, bot): self.bot = bot async def on_connect(self): try: await database.client.server_info() except pymongo.errors.ServerSelectionTimeoutError as error: ...
print('------------') # Retrieve the playing status options in 'options.json' playing_status = injector.get_options()['other']['playing_status'] # Set the bot's playing status await self.bot.change_presence(game=discord.Game(name=playing_status['name'], url=playing_status['url'], ...
type=playing_status['type'])) async def on_command(self, command): """Logs all commands that are sent""" # Get the command name only name = command.message.content[1:] name = name.rsplit(' ', 1)[0] # Define guild_id and Command...
FeiZhan/Algo-Collection
answers/other/in sap/Pascal's Triangle.py
Python
mit
470
0.031915
class Solution(object): def generate(self, numRows): """ :type numRows: int :
rtype: List[List[int]] """ pascal = [] if numRows >= 1: pascal.append([1]) for i in range(1, numRows): pascal.append([pascal[-1][0]]) for j in range(1, len(pascal[-2])): pascal[-1].append(pascal[-2][j - 1] + pascal[-2][j]) pascal[-1]...
ascal
pizzapanther/Neutron-Sync
nsync_server/nstore/apps.py
Python
mit
153
0.013072
from django.apps import AppConfig class NstoreConfig(AppConfig): default_auto_field = 'd
jango.db.models.BigAutoField' name = 'nsync_s
erver.nstore'
pixelated-project/pixelated-dispatcher
pixelated/test/integration/smoke_test.py
Python
agpl-3.0
7,956
0.003394
# # Copyright (c) 2014 ThoughtWorks Deutschland GmbH # # Pixelated is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Pixelated...
(self.get('https://localhost:4443/agents'), json_body={ 'agents': [{'name': 'test', 'state': 'stopped', 'uri': 'http://localhost:4443/agents/test'}]}) self.assertSuccess( self.put('https://localhost:4443/agents/test/state', json_data={'state': 'running'})) self.as...
et('https://localhost:4443/agents/test/runtime'), json_body={'state': 'running', 'port': 5000}) time.sleep(2) # let mailpile start self.assertSuccess(self.get('http://localhost:5000/')) self.assertSuccess( self.put('https://localhost:44...