code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class Cancel(TaskSpec): <NEW_LINE> <INDENT> def __init__(self, parent, name, success = False, **kwargs): <NEW_LINE> <INDENT> TaskSpec.__init__(self, parent, name, **kwargs) <NEW_LINE> self.cancel_successfully = success <NEW_LINE> <DEDENT> def test(self): <NEW_LINE> <INDENT> TaskSpec.test(self) <NEW_LINE> if len(self.outputs) > 0: <NEW_LINE> <INDENT> raise WorkflowException(self, 'Cancel with an output.') <NEW_LINE> <DEDENT> <DEDENT> def _on_complete_hook(self, my_task): <NEW_LINE> <INDENT> my_task.workflow.cancel(self.cancel_successfully) <NEW_LINE> TaskSpec._on_complete_hook(self, my_task) <NEW_LINE> <DEDENT> def serialize(self, serializer): <NEW_LINE> <INDENT> return serializer._serialize_cancel(self) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def deserialize(self, serializer, wf_spec, s_state): <NEW_LINE> <INDENT> return serializer._deserialize_cancel(wf_spec, s_state)
This class cancels a complete workflow. If more than one input is connected, the task performs an implicit multi merge. If more than one output is connected, the task performs an implicit parallel split.
62599054dc8b845886d54ae8
class SUSY_Dataset(torch.utils.data.Dataset): <NEW_LINE> <INDENT> def __init__(self, data_file, root_dir, dataset_size, train=True, transform=None, high_level_feats=None): <NEW_LINE> <INDENT> features=['SUSY','lepton 1 pT', 'lepton 1 eta', 'lepton 1 phi', 'lepton 2 pT', 'lepton 2 eta', 'lepton 2 phi', 'missing energy magnitude', 'missing energy phi', 'MET_rel', 'axial MET', 'M_R', 'M_TR_2', 'R', 'MT2', 'S_R', 'M_Delta_R', 'dPhi_r_b', 'cos(theta_r1)'] <NEW_LINE> low_features=['lepton 1 pT', 'lepton 1 eta', 'lepton 1 phi', 'lepton 2 pT', 'lepton 2 eta', 'lepton 2 phi', 'missing energy magnitude', 'missing energy phi'] <NEW_LINE> high_features=['MET_rel', 'axial MET', 'M_R', 'M_TR_2', 'R', 'MT2','S_R', 'M_Delta_R', 'dPhi_r_b', 'cos(theta_r1)'] <NEW_LINE> df = pd.read_csv(root_dir+data_file, header=None,nrows=dataset_size,engine='python') <NEW_LINE> df.columns=features <NEW_LINE> Y = df['SUSY'] <NEW_LINE> X = df[[col for col in df.columns if col!="SUSY"]] <NEW_LINE> train_size=int(0.8*dataset_size) <NEW_LINE> self.train=train <NEW_LINE> if self.train: <NEW_LINE> <INDENT> X=X[:train_size] <NEW_LINE> Y=Y[:train_size] <NEW_LINE> print("Training on {} examples".format(train_size)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> X=X[train_size:] <NEW_LINE> Y=Y[train_size:] <NEW_LINE> print("Testing on {} examples".format(dataset_size-train_size)) <NEW_LINE> <DEDENT> self.root_dir = root_dir <NEW_LINE> self.transform = transform <NEW_LINE> if high_level_feats is None: <NEW_LINE> <INDENT> self.data=(X.values.astype(np.float32),Y.values.astype(int)) <NEW_LINE> print("Using both high and low level features") <NEW_LINE> <DEDENT> elif high_level_feats is True: <NEW_LINE> <INDENT> self.data=(X[high_features].values.astype(np.float32),Y.values.astype(int)) <NEW_LINE> print("Using both high-level features only.") <NEW_LINE> <DEDENT> elif high_level_feats is False: <NEW_LINE> <INDENT> self.data=(X[low_features].values.astype(np.float32),Y.values.astype(int)) <NEW_LINE> print("Using both low-level features only.") <NEW_LINE> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.data[1]) <NEW_LINE> <DEDENT> def __getitem__(self, idx): <NEW_LINE> <INDENT> sample=(self.data[0][idx,...],self.data[1][idx]) <NEW_LINE> if self.transform: <NEW_LINE> <INDENT> sample=self.transform(sample) <NEW_LINE> <DEDENT> return sample
SUSY pytorch dataset.
6259905423849d37ff8525e8
class Level(object): <NEW_LINE> <INDENT> def __init__(self, player): <NEW_LINE> <INDENT> self.platform_list = pygame.sprite.Group() <NEW_LINE> self.enemy_list = pygame.sprite.Group() <NEW_LINE> self.player = player <NEW_LINE> self.background = None <NEW_LINE> self.world_shift = 0 <NEW_LINE> self.level_limit = -1000 <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.platform_list.update() <NEW_LINE> self.enemy_list.update() <NEW_LINE> <DEDENT> def draw(self, screen): <NEW_LINE> <INDENT> self.platform_list.draw(screen) <NEW_LINE> self.enemy_list.draw(screen) <NEW_LINE> <DEDENT> def shift_world(self, shift_x, enemy): <NEW_LINE> <INDENT> self.world_shift += shift_x <NEW_LINE> for platform in self.platform_list: <NEW_LINE> <INDENT> platform.rect.x += shift_x <NEW_LINE> <DEDENT> enemy.rect.x += shift_x
This is a generic super-class used to define a level.
62599054435de62698e9d327
class EnumParam(InputParam): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> InputParam.__init__(self, *args, **kwargs) <NEW_LINE> self._input = Gtk.ComboBoxText() <NEW_LINE> for option_name in self.param.options.values(): <NEW_LINE> <INDENT> self._input.append_text(option_name) <NEW_LINE> <DEDENT> self.param_values = list(self.param.options) <NEW_LINE> self._input.set_active(self.param_values.index(self.param.get_value())) <NEW_LINE> self._input.connect('changed', self._editing_callback) <NEW_LINE> self._input.connect('changed', self._apply_change) <NEW_LINE> self.pack_start(self._input, False, False, 0) <NEW_LINE> <DEDENT> def get_text(self): <NEW_LINE> <INDENT> return self.param_values[self._input.get_active()] <NEW_LINE> <DEDENT> def set_tooltip_text(self, text): <NEW_LINE> <INDENT> self._input.set_tooltip_text(text)
Provide an entry box for Enum types with a drop down menu.
6259905407d97122c42181cf
class Uppercase(AbstractFilter): <NEW_LINE> <INDENT> name = 'Majuscule' <NEW_LINE> description = "Passe le contenu d'une colonne en majuscule" <NEW_LINE> node_in = ['contenu'] <NEW_LINE> node_out = ['resultat'] <NEW_LINE> parameters = [ { 'name': 'Colonne', 'key': 'column', 'type': 'string' } ] <NEW_LINE> def run(self): <NEW_LINE> <INDENT> origin = self._flux_in['contenu'] <NEW_LINE> column = self._param('column') <NEW_LINE> column_id = origin['headers'].index(column) <NEW_LINE> self._flux_out['resultat'] = { 'headers': copy(origin['headers']), 'rows': [ [ value if ind != column_id else value.upper() for ind, value in enumerate(row) ] for row in origin['rows'] ] }
Switch a field to uppercase
6259905424f1403a92686361
class Category(Generic): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = _("category") <NEW_LINE> verbose_name_plural = _("categories") <NEW_LINE> <DEDENT> name = models.CharField(_("category"), max_length=255) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return unicode(self.name)
Categories who selected by admin
62599054462c4b4f79dbcf29
class AbstractVector(StructuredRecord): <NEW_LINE> <INDENT> _level = None <NEW_LINE> cutter = NotImplemented <NEW_LINE> def __new__(cls, *args, **kwargs): <NEW_LINE> <INDENT> cutter_check(cls.cutter, name=cls.__name__) <NEW_LINE> return super(AbstractVector, cls).__new__(cls) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def structure(cls): <NEW_LINE> <INDENT> downstream = cls.cutter.elucidate() <NEW_LINE> upstream = str(Seq(downstream).reverse_complement()) <NEW_LINE> return "".join( [ upstream.replace("^", ")(").replace("_", "("), "N*", downstream.replace("^", ")(").replace("_", ")"), ] ) <NEW_LINE> <DEDENT> def overhang_start(self): <NEW_LINE> <INDENT> return self._match.group(3).seq <NEW_LINE> <DEDENT> def overhang_end(self): <NEW_LINE> <INDENT> return self._match.group(1).seq <NEW_LINE> <DEDENT> def placeholder_sequence(self): <NEW_LINE> <INDENT> if self.cutter.is_3overhang(): <NEW_LINE> <INDENT> return self._match.group(2) + self.overhang_end() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.overhang_start() + self._match.group(2) <NEW_LINE> <DEDENT> <DEDENT> def target_sequence(self): <NEW_LINE> <INDENT> if self.cutter.is_3overhang(): <NEW_LINE> <INDENT> start, end = self._match.span(2)[0], self._match.span(3)[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> start, end = self._match.span(1)[0], self._match.span(2)[1] <NEW_LINE> <DEDENT> return add_as_source(self.record, (self.record << start)[end - start :]) <NEW_LINE> <DEDENT> @cached_property <NEW_LINE> def _match(self): <NEW_LINE> <INDENT> _match = super(AbstractVector, self)._match <NEW_LINE> if len(self.cutter.catalyse(_match.group(0).seq)) > 3: <NEW_LINE> <INDENT> raise errors.IllegalSite(self.seq) <NEW_LINE> <DEDENT> return _match <NEW_LINE> <DEDENT> def assemble(self, module, *modules, **kwargs): <NEW_LINE> <INDENT> mgr = AssemblyManager( vector=self, modules=[module] + list(modules), name=kwargs.get("name", "assembly"), id_=kwargs.get("id", "assembly"), ) <NEW_LINE> return mgr.assemble()
An abstract modular cloning vector.
62599054b57a9660fecd2fa0
class TrimmedTextResult(TextTestResult): <NEW_LINE> <INDENT> def __init__(self, *args,**kw): <NEW_LINE> <INDENT> super(TrimmedTextResult, self).__init__(*args, **kw) <NEW_LINE> self._error_lookup = {} <NEW_LINE> self._failure_lookup = {} <NEW_LINE> <DEDENT> def _error_identifier(self, err): <NEW_LINE> <INDENT> etype, value, tb = err <NEW_LINE> last_application_tb = tb <NEW_LINE> while tb is not None: <NEW_LINE> <INDENT> if not self._is_relevant_tb_level(tb): <NEW_LINE> <INDENT> last_application_tb = tb <NEW_LINE> <DEDENT> tb = tb.tb_next <NEW_LINE> <DEDENT> if last_application_tb is None: <NEW_LINE> <INDENT> eid = etype.__name__ <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> frame_info = inspect.getframeinfo(last_application_tb) <NEW_LINE> eid = etype.__name__, frame_info.filename, frame_info.lineno <NEW_LINE> <DEDENT> return eid <NEW_LINE> <DEDENT> def _isNewErr(self, err): <NEW_LINE> <INDENT> ename = self._error_identifier(err) <NEW_LINE> if ename in _errormap: <NEW_LINE> <INDENT> _errormap[ename] += 1 <NEW_LINE> return False <NEW_LINE> <DEDENT> _errormap[ename] = 1 <NEW_LINE> return True <NEW_LINE> <DEDENT> def addError(self, test, err): <NEW_LINE> <INDENT> if self._isNewErr(err): <NEW_LINE> <INDENT> super(TrimmedTextResult, self).addError(test, err) <NEW_LINE> self._error_lookup[len(self.errors) - 1] = self._error_identifier(err) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> super(TrimmedTextResult, self).addSkip(test, 'Error already seen') <NEW_LINE> <DEDENT> <DEDENT> def addFailure(self, test, err): <NEW_LINE> <INDENT> if self._isNewErr(err): <NEW_LINE> <INDENT> super(TrimmedTextResult, self).addFailure(test, err) <NEW_LINE> self._failure_lookup[len(self.failures) - 1] = self._error_identifier(err) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> super(TrimmedTextResult, self).addSkip(test, 'Error already seen') <NEW_LINE> <DEDENT> <DEDENT> def printErrors(self): <NEW_LINE> <INDENT> if self.dots or self.showAll: <NEW_LINE> <INDENT> self.stream.writeln() <NEW_LINE> <DEDENT> def get_error_count(lookup, index): <NEW_LINE> <INDENT> if index in lookup: <NEW_LINE> <INDENT> ename = lookup[index] <NEW_LINE> return _errormap[ename] <NEW_LINE> <DEDENT> <DEDENT> self.printErrorList('FAIL', self.failures, lambda i: get_error_count(self._failure_lookup, i)) <NEW_LINE> self.printErrorList('ERROR', self.errors, lambda i: get_error_count(self._error_lookup, i)) <NEW_LINE> <DEDENT> def printErrorList(self, flavor, errors, get_error_count): <NEW_LINE> <INDENT> messages = [] <NEW_LINE> for idx, (test, err) in enumerate(errors): <NEW_LINE> <INDENT> messages.append((get_error_count(idx), self.getDescription(test), err)) <NEW_LINE> <DEDENT> for count, description, err in sorted(messages): <NEW_LINE> <INDENT> self.stream.writeln(self.separator1) <NEW_LINE> self.stream.writeln("%s: %s" % (flavor, description)) <NEW_LINE> self.stream.writeln(self.separator2) <NEW_LINE> self.stream.writeln("%s" % err) <NEW_LINE> if count > 1: <NEW_LINE> <INDENT> self.stream.writeln(self.separator2) <NEW_LINE> self.stream.writeln("+ %s more" % (count - 1)) <NEW_LINE> self.stream.writeln(self.separator2) <NEW_LINE> self.stream.writeln()
A patched up version of nose.result.TextTestResult. working with Jason to try and get proper plugin hooks to accomplish this same thing without the monkey business.
62599054baa26c4b54d507c8
class GetRatesService(BaseFetchRatesService): <NEW_LINE> <INDENT> _api_endpoint = 'https://api.cryptonator.com/api/ticker/' <NEW_LINE> def __init__(self, currency_pairs: list): <NEW_LINE> <INDENT> self.currency_pairs = currency_pairs <NEW_LINE> <DEDENT> def _prepare_urls(self) -> list: <NEW_LINE> <INDENT> url_list = [ self._api_endpoint + f'{c[0].lower()}-{c[1].lower()}' for c in self.currency_pairs ] <NEW_LINE> return url_list <NEW_LINE> <DEDENT> @sync_to_async <NEW_LINE> def _update_currencies(self, data: dict) -> None: <NEW_LINE> <INDENT> ticker = data.get('ticker', {}) <NEW_LINE> if data.get('success'): <NEW_LINE> <INDENT> base_currency = Currency.objects.get(code=ticker.get('base')) <NEW_LINE> target_currency = Currency.objects.get(code=ticker.get('target')) <NEW_LINE> currency_pair = CurrencyPair.objects.filter( base_currency=base_currency, target_currency=target_currency ).first() <NEW_LINE> if currency_pair: <NEW_LINE> <INDENT> Rate.objects.create( currency_pair=currency_pair, price=Decimal(ticker.get('price')), timestamp=data.get('timestamp') ) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> error = ticker.get('error')
Service for fetching and saving in the DB rates for currencies currency_pairs: list of tuples (base, target), example [('BTC', 'USD'), ('USD', 'UAH')]
625990547cff6e4e811b6f66
class BridgeExtraInfoDescriptor(ExtraInfoDescriptor): <NEW_LINE> <INDENT> ATTRIBUTES = dict(ExtraInfoDescriptor.ATTRIBUTES, **{ 'ed25519_certificate_hash': (None, _parse_master_key_ed25519_line), 'router_digest_sha256': (None, _parse_router_digest_sha256_line), '_digest': (None, _parse_router_digest_line), }) <NEW_LINE> PARSER_FOR_LINE = dict(ExtraInfoDescriptor.PARSER_FOR_LINE, **{ 'master-key-ed25519': _parse_master_key_ed25519_line, 'router-digest-sha256': _parse_router_digest_sha256_line, 'router-digest': _parse_router_digest_line, }) <NEW_LINE> def digest(self): <NEW_LINE> <INDENT> return self._digest <NEW_LINE> <DEDENT> def _required_fields(self): <NEW_LINE> <INDENT> excluded_fields = [ 'router-signature', ] <NEW_LINE> included_fields = [ 'router-digest', ] <NEW_LINE> return tuple(included_fields + [f for f in REQUIRED_FIELDS if f not in excluded_fields]) <NEW_LINE> <DEDENT> def _last_keyword(self): <NEW_LINE> <INDENT> return None
Bridge extra-info descriptor (`bridge descriptor specification <https://collector.torproject.org/formats.html#bridge-descriptors>`_) :var str ed25519_certificate_hash: sha256 hash of the original identity-ed25519 :var str router_digest_sha256: sha256 digest of this document .. versionchanged:: 1.5.0 Added the ed25519_certificate_hash and router_digest_sha256 attributes.
6259905416aa5153ce401a0a
class BackgroundBaseZMQServer(BaseZMQServer, threading.Thread): <NEW_LINE> <INDENT> def __init__(self, namespace, port, context=None): <NEW_LINE> <INDENT> BaseZMQServer.__init__(self, namespace, port, context) <NEW_LINE> threading.Thread.__init__(self, name='background RPC server', daemon=True) <NEW_LINE> self.start()
ZMQ server that runs in a background thread.
6259905482261d6c5273095c
class ApplicationRunTests(testing.TestCase): <NEW_LINE> <INDENT> @testing.patch('cep.flaskapp.Application') <NEW_LINE> def test_create_application_curries_arguments(self, app_class): <NEW_LINE> <INDENT> cep.create_application() <NEW_LINE> app_class.assert_called_with() <NEW_LINE> cep.create_application(1, 2, 3) <NEW_LINE> app_class.assert_called_with(1,2,3) <NEW_LINE> cep.create_application(1, 2, three=3) <NEW_LINE> app_class.assert_called_with(1, 2, three=3) <NEW_LINE> <DEDENT> @testing.patch('flask.Flask.run') <NEW_LINE> def test_run_curries_arguments(self, flask_run): <NEW_LINE> <INDENT> inst = cep.create_application() <NEW_LINE> inst.run() <NEW_LINE> flask_run.assert_called_with(inst, host='0.0.0.0', port=5000, debug=False) <NEW_LINE> inst.run(42, foo='bar') <NEW_LINE> flask_run.assert_called_with(inst, 42, host='0.0.0.0', port=5000, debug=False, foo='bar') <NEW_LINE> <DEDENT> @testing.patch('flask.Flask.run') <NEW_LINE> def test_run_keywords_override_defaults(self, flask_run): <NEW_LINE> <INDENT> inst = cep.create_application() <NEW_LINE> inst.run(debug=True, host='127.0.0.1', port=6543) <NEW_LINE> flask_run.assert_called_with(inst, host='127.0.0.1', port=6543, debug=True)
Verify aspects of creating and running the application.
625990546e29344779b01b6f
class Edge(Filter): <NEW_LINE> <INDENT> def __init__(self, compat=False): <NEW_LINE> <INDENT> super(Edge, self).__init__(6, Edge.__inten.features) <NEW_LINE> self.__compat = compat <NEW_LINE> <DEDENT> def __call__(self, im, out=None, region=None, nthreads=1): <NEW_LINE> <INDENT> from ._base import get_image_region, replace_sym_padding, hypot <NEW_LINE> from ._correlate import correlate_xy <NEW_LINE> if self.__compat: <NEW_LINE> <INDENT> im, region = replace_sym_padding(im, 3, region, 6, nthreads) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> im, region = get_image_region(im, 6, region, nthreads=nthreads) <NEW_LINE> <DEDENT> imx = correlate_xy(im, Edge.__kernel[0], Edge.__kernel[1], nthreads=nthreads) <NEW_LINE> imy = correlate_xy(im, Edge.__kernel[1], Edge.__kernel[0], nthreads=nthreads) <NEW_LINE> hypot(imx, imy, imx, nthreads) <NEW_LINE> region = (region[0]-3, region[1]-3, region[2]-3, region[3]-3) <NEW_LINE> return Edge.__inten(imx, out=out, region=region, nthreads=nthreads) <NEW_LINE> <DEDENT> __kernel = None <NEW_LINE> __inten = None <NEW_LINE> @staticmethod <NEW_LINE> def __d2dgauss(n, sigma): <NEW_LINE> <INDENT> from numpy import ogrid, sqrt <NEW_LINE> n2 = -(n+1)/2+1 <NEW_LINE> ox, oy = ogrid[n2:n2+n, n2:n2+n] <NEW_LINE> h = Edge.__gauss(oy, sigma) * Edge.__dgauss(ox, sigma) <NEW_LINE> h /= sqrt((h*h).sum()) <NEW_LINE> h.flags.writeable = False <NEW_LINE> return h <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __gauss(x,std): from numpy import exp, sqrt, pi; return exp(-x*x/(2*std*std)) / (std*sqrt(2*pi)) <NEW_LINE> @staticmethod <NEW_LINE> def __dgauss(x,std): <NEW_LINE> <INDENT> return x * Edge.__gauss(x,std) / (std*std) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __static_init__(): <NEW_LINE> <INDENT> from ._base import separate_filter <NEW_LINE> from .intensity import Intensity <NEW_LINE> Edge.__kernel = separate_filter(Edge.__d2dgauss(7, 1.0)) <NEW_LINE> Edge.__inten = Intensity.Square(3)
Computes the edge features of the image. This calculates the gradient magnitude using a second derivative of the Gaussian with a sigma of 1.0 then returns all neighboring offsets in a 7x7 block. The compat flag causes a padding of 0s to be used when needed instead of reflection. This is not a good approach since a transition from 0s to the image data will be an edge. Also it takes extra effort and memory to do so because the FilterBank class adds reflection padding inherently, so we have to detect that and correct it. Uses O(2*im.size).
62599054004d5f362081fa7f
class WeChatView(View): <NEW_LINE> <INDENT> token = "" <NEW_LINE> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> logger.info('- New GET From WeChat -') <NEW_LINE> authenticated, data = self.authenticate(request, kwargs) <NEW_LINE> if authenticated: <NEW_LINE> <INDENT> if data['echostr']: <NEW_LINE> <INDENT> logger.info('sending response..') <NEW_LINE> logger.info('echostr: {}'.format(data['echostr'])) <NEW_LINE> return HttpResponse(data['echostr']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.info('WeChat Authenticated, but nonce is missing in a GET request, signature:{} timestamp:{} ' 'nonce:{}'.format(data['signature'], data['timestamp'], data['nonce'])) <NEW_LINE> return HttpResponse(status=200) <NEW_LINE> <DEDENT> <DEDENT> return HttpResponse(status=403) <NEW_LINE> <DEDENT> def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> logger.info('- New POST From WeChat -') <NEW_LINE> authenticated, data = self.authenticate(request, kwargs) <NEW_LINE> if authenticated: <NEW_LINE> <INDENT> logger.info('New message received: {}'.format(request.body)) <NEW_LINE> self.on_message(message=request.body) <NEW_LINE> return HttpResponse(status=201) <NEW_LINE> <DEDENT> return HttpResponse(status=403) <NEW_LINE> <DEDENT> def authenticate(self, request, kwargs): <NEW_LINE> <INDENT> data = dict() <NEW_LINE> try: <NEW_LINE> <INDENT> signature = request.GET['signature'] <NEW_LINE> timestamp = request.GET['timestamp'] <NEW_LINE> nonce = request.GET['nonce'] <NEW_LINE> echostr = request.GET.get('echostr', '') <NEW_LINE> <DEDENT> except MultiValueDictKeyError: <NEW_LINE> <INDENT> logger.error('missing parameters in WeChat request') <NEW_LINE> return False, data <NEW_LINE> <DEDENT> if not self.token: <NEW_LINE> <INDENT> logger.error('Token not set on class instance') <NEW_LINE> return False, data <NEW_LINE> <DEDENT> params = [self.token, timestamp, nonce] <NEW_LINE> params.sort() <NEW_LINE> auth_string = ''.join(params) <NEW_LINE> if self.validate_signature(auth_string, signature): <NEW_LINE> <INDENT> data.update({ 'signature': signature, 'timestamp': timestamp, 'nonce': nonce, 'echostr': echostr, 'token': self.token, }) <NEW_LINE> return True, data <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.info('WeChat Authentication failed, signature:{} timestamp:{} nonce:{}' .format(signature, timestamp, nonce)) <NEW_LINE> return False, data <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def validate_signature(auth_string, signature): <NEW_LINE> <INDENT> return hashlib.sha1(auth_string.encode()).hexdigest() == signature <NEW_LINE> <DEDENT> def on_message(self, message): <NEW_LINE> <INDENT> raise NotImplementedError('You need to do something with the message from WeChat')
WeChat API
625990544e696a045264e8b5
class Upper(Validator): <NEW_LINE> <INDENT> def __call__(self, value): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> return (value, None) <NEW_LINE> <DEDENT> return (to_native(to_unicode(value).upper()), None)
Converts to upper case
625990543cc13d1c6d466c63
class ExtractTableToStorageJob(_AsyncJob): <NEW_LINE> <INDENT> _JOB_TYPE = 'extract' <NEW_LINE> def __init__(self, name, source, destination_uris, client): <NEW_LINE> <INDENT> super(ExtractTableToStorageJob, self).__init__(name, client) <NEW_LINE> self.source = source <NEW_LINE> self.destination_uris = destination_uris <NEW_LINE> self._configuration = _ExtractConfiguration() <NEW_LINE> <DEDENT> compression = Compression('compression') <NEW_LINE> destination_format = DestinationFormat('destination_format') <NEW_LINE> field_delimiter = _TypedProperty('field_delimiter', six.string_types) <NEW_LINE> print_header = _TypedProperty('print_header', bool) <NEW_LINE> def _populate_config_resource(self, configuration): <NEW_LINE> <INDENT> if self.compression is not None: <NEW_LINE> <INDENT> configuration['compression'] = self.compression <NEW_LINE> <DEDENT> if self.destination_format is not None: <NEW_LINE> <INDENT> configuration['destinationFormat'] = self.destination_format <NEW_LINE> <DEDENT> if self.field_delimiter is not None: <NEW_LINE> <INDENT> configuration['fieldDelimiter'] = self.field_delimiter <NEW_LINE> <DEDENT> if self.print_header is not None: <NEW_LINE> <INDENT> configuration['printHeader'] = self.print_header <NEW_LINE> <DEDENT> <DEDENT> def _build_resource(self): <NEW_LINE> <INDENT> source_ref = { 'projectId': self.source.project, 'datasetId': self.source.dataset_name, 'tableId': self.source.name, } <NEW_LINE> resource = { 'jobReference': { 'projectId': self.project, 'jobId': self.name, }, 'configuration': { self._JOB_TYPE: { 'sourceTable': source_ref, 'destinationUris': self.destination_uris, }, }, } <NEW_LINE> configuration = resource['configuration'][self._JOB_TYPE] <NEW_LINE> self._populate_config_resource(configuration) <NEW_LINE> return resource <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_api_repr(cls, resource, client): <NEW_LINE> <INDENT> name, config = cls._get_resource_config(resource) <NEW_LINE> source_config = config['sourceTable'] <NEW_LINE> dataset = Dataset(source_config['datasetId'], client) <NEW_LINE> source = Table(source_config['tableId'], dataset) <NEW_LINE> destination_uris = config['destinationUris'] <NEW_LINE> job = cls(name, source, destination_uris, client=client) <NEW_LINE> job._set_properties(resource) <NEW_LINE> return job
Asynchronous job: extract data from a table into Cloud Storage. :type name: string :param name: the name of the job :type source: :class:`google.cloud.bigquery.table.Table` :param source: Table into which data is to be loaded. :type destination_uris: list of string :param destination_uris: URIs describing Cloud Storage blobs into which extracted data will be written, in format ``gs://<bucket_name>/<object_name_or_glob>``. :type client: :class:`google.cloud.bigquery.client.Client` :param client: A client which holds credentials and project configuration for the dataset (which requires a project).
62599054d7e4931a7ef3d5a4
class _FoolscapProxy(Protocol): <NEW_LINE> <INDENT> buffered = b"" <NEW_LINE> def dataReceived(self, data): <NEW_LINE> <INDENT> msg("_FoolscapProxy.dataReceived {!r}".format(data)) <NEW_LINE> self.buffered += data <NEW_LINE> if b"\r\n\r\n" in self.buffered: <NEW_LINE> <INDENT> header = self.buffered <NEW_LINE> self.buffered = b"" <NEW_LINE> self.handlePLAINTEXTServer(header) <NEW_LINE> <DEDENT> <DEDENT> def handlePLAINTEXTServer(self, header): <NEW_LINE> <INDENT> lines = header.split("\r\n") <NEW_LINE> if not lines[0].startswith("GET "): <NEW_LINE> <INDENT> raise BananaError("not right") <NEW_LINE> <DEDENT> command, url, version = lines[0].split() <NEW_LINE> if not url.startswith("/id/"): <NEW_LINE> <INDENT> raise BananaError("not right") <NEW_LINE> <DEDENT> targetTubID = url[4:] <NEW_LINE> Message.log(event_type=u"handlePLAINTEXTServer", tub_id=targetTubID) <NEW_LINE> if targetTubID == "": <NEW_LINE> <INDENT> raise NegotiationError("secure Tubs require encryption") <NEW_LINE> <DEDENT> if isSubstring("Upgrade: TLS/1.0\r\n", header): <NEW_LINE> <INDENT> wantEncrypted = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> wantEncrypted = False <NEW_LINE> <DEDENT> Message.log(event_type=u"handlePLAINTEXTServer", want_encrypted=wantEncrypted) <NEW_LINE> self._handleTubRequest(header, targetTubID) <NEW_LINE> <DEDENT> def _handleTubRequest(self, header, targetTubID): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _, (ip, port_number) = self.factory.route_mapping()[targetTubID] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise NegotiationError("unknown TubID %s" % (targetTubID,)) <NEW_LINE> <DEDENT> if not ip: <NEW_LINE> <INDENT> raise NegotiationError("TubID not yet available %s" % (targetTubID,)) <NEW_LINE> <DEDENT> proxy(self, TCP4ClientEndpoint(self.factory.reactor, ip, port_number), header)
A protocol which speaks just enough of the first part of a Foolscap conversation to extract the TubID so that a proxy target can be selected based on that value. :ivar bytes buffered: Data which has been received and buffered but not yet interpreted or passed on.
625990543617ad0b5ee0766d
class Client(): <NEW_LINE> <INDENT> def __init__(self, pid): <NEW_LINE> <INDENT> self.pid = pid <NEW_LINE> self.hwnd = self.get_hwnds() <NEW_LINE> self.name = self.get_name() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Flyff.Client %s>' % self.pid <NEW_LINE> <DEDENT> def get_hwnds(self): <NEW_LINE> <INDENT> def callback(hwnd, hwnds): <NEW_LINE> <INDENT> if IsWindowVisible (hwnd) and IsWindowEnabled(hwnd): <NEW_LINE> <INDENT> _, found_pid = GetWindowThreadProcessId(hwnd) <NEW_LINE> if found_pid == self.pid: <NEW_LINE> <INDENT> hwnds.append(hwnd) <NEW_LINE> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> hwnds = [] <NEW_LINE> EnumWindows(callback, hwnds) <NEW_LINE> return hwnds[0] <NEW_LINE> <DEDENT> def get_name(self): <NEW_LINE> <INDENT> return GetWindowText(self.hwnd).split(' ')[0]
A Flyff client object with hwnd attribute for handling sending keys to a window, and name attribute displaying the logged in character name for easy identification (PIDs and hWnds aren't very identifiable).
6259905471ff763f4b5e8cd5
class BaseActions(object): <NEW_LINE> <INDENT> def __init__(self, request): <NEW_LINE> <INDENT> self.ajax_response = {'rc': 0, 'response': 'ok', 'errors_list': []} <NEW_LINE> self.request = request <NEW_LINE> self.product_id = request.REQUEST.get('product') <NEW_LINE> <DEDENT> def get_testcases(self): <NEW_LINE> <INDENT> from tcms.testcases.views import get_selected_testcases <NEW_LINE> return get_selected_testcases(self.request)
Base class for all Actions
625990547b25080760ed8772
class TodoItem(Base): <NEW_LINE> <INDENT> __tablename__ = 'todoitems' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> task = Column(Text, nullable=False) <NEW_LINE> _due_date = Column('due_date', DateTime) <NEW_LINE> user = Column(Integer, ForeignKey('users.email')) <NEW_LINE> author = relationship('TodoUser') <NEW_LINE> tags = relationship("Tag", secondary=todoitemtag_table, backref="todos") <NEW_LINE> def __init__(self, user, task, tags=None, due_date=None): <NEW_LINE> <INDENT> self.user = user <NEW_LINE> self.task = task <NEW_LINE> self.due_date = due_date <NEW_LINE> if tags is not None: <NEW_LINE> <INDENT> self.apply_tags(tags) <NEW_LINE> <DEDENT> <DEDENT> def apply_tags(self, tags): <NEW_LINE> <INDENT> for tag_name in tags: <NEW_LINE> <INDENT> tag_name = self.sanitize_tag(tag_name) <NEW_LINE> tag = self._find_or_create_tag(tag_name) <NEW_LINE> self.tags.append(tag) <NEW_LINE> <DEDENT> <DEDENT> def sanitize_tag(self, tag_name): <NEW_LINE> <INDENT> tag = tag_name.strip().lower() <NEW_LINE> return tag <NEW_LINE> <DEDENT> def _find_or_create_tag(self, tag_name): <NEW_LINE> <INDENT> q = DBSession.query(Tag).filter_by(name=tag_name) <NEW_LINE> t = q.first() <NEW_LINE> if not(t): <NEW_LINE> <INDENT> t = Tag(tag_name) <NEW_LINE> <DEDENT> return t <NEW_LINE> <DEDENT> @property <NEW_LINE> def sorted_tags(self): <NEW_LINE> <INDENT> return sorted(self.tags, key=lambda x: x.name) <NEW_LINE> <DEDENT> @property <NEW_LINE> def past_due(self): <NEW_LINE> <INDENT> return self._due_date and self._due_date < datetime.utcnow() <NEW_LINE> <DEDENT> def universify_due_date(self, date): <NEW_LINE> <INDENT> if date is not None: <NEW_LINE> <INDENT> self._due_date = universify_datetime(date) <NEW_LINE> <DEDENT> <DEDENT> def localize_due_date(self): <NEW_LINE> <INDENT> if self._due_date is not None and hasattr(self.author, 'time_zone'): <NEW_LINE> <INDENT> due_dt = localize_datetime(self._due_date, self.author.time_zone) <NEW_LINE> return due_dt <NEW_LINE> <DEDENT> return self._due_date <NEW_LINE> <DEDENT> due_date = property(localize_due_date, universify_due_date) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return "TodoItem(%r, %r, %r, %r)" % (self.user, self.task, self.tags, self.due_date)
This is the main model in our application. This is what powers the tasks in the todo list.
62599054e76e3b2f99fd9f25
class nn_se_rReSpecMSE100(p40): <NEW_LINE> <INDENT> blstm_layers = 1 <NEW_LINE> lstm_layers = 1 <NEW_LINE> loss_name = ["real_net_reSpecMse"] <NEW_LINE> relative_loss_epsilon = 1.0/100.0
cnn1blstm1lstm
62599054dd821e528d6da406
class NDArrayDoc(object): <NEW_LINE> <INDENT> pass
The basic class
625990540a50d4780f706852
class ComputeDisksSetLabelsRequest(_messages.Message): <NEW_LINE> <INDENT> project = _messages.StringField(1, required=True) <NEW_LINE> requestId = _messages.StringField(2) <NEW_LINE> resource = _messages.StringField(3, required=True) <NEW_LINE> zone = _messages.StringField(4, required=True) <NEW_LINE> zoneSetLabelsRequest = _messages.MessageField('ZoneSetLabelsRequest', 5)
A ComputeDisksSetLabelsRequest object. Fields: project: Project ID for this request. requestId: An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). resource: Name of the resource for this request. zone: The name of the zone for this request. zoneSetLabelsRequest: A ZoneSetLabelsRequest resource to be passed as the request body.
625990548e7ae83300eea5bf
class ReactionCompoundMatch(object): <NEW_LINE> <INDENT> def __init__(self, parsed_name, parsed_coeff, parsed_phase, matches): <NEW_LINE> <INDENT> self.parsed_name = parsed_name <NEW_LINE> self.parsed_coeff = parsed_coeff <NEW_LINE> self.parsed_phase = parsed_phase <NEW_LINE> self.matches = matches <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '%d %s(%s), matches: %s' % (self.parsed_coeff, self.parsed_name, self.parsed_phase, ', '.join(self.matches)) <NEW_LINE> <DEDENT> def ParsedDataEqual(self, other): <NEW_LINE> <INDENT> return (self.parsed_coeff == other.parsed_coeff and self.parsed_name == other.parsed_name and self.parsed_phase == other.parsed_phase)
A match of a compound in a reaction. Contains the parsed name (what the user entered), the parsed stoichiometric coefficient, and a list of matcher.Match objects of the potential matches.
62599054a79ad1619776b551
class IAMGroup(Resource): <NEW_LINE> <INDENT> TYPE_VALUE: ClassVar = "AWS::IAM::Group" <NEW_LINE> Type: str = TYPE_VALUE <NEW_LINE> Properties: Optional[Resolvable[IAMGroupProperties]] <NEW_LINE> @property <NEW_LINE> def policy_documents(self) -> List[OptionallyNamedPolicyDocument]: <NEW_LINE> <INDENT> result = [] <NEW_LINE> policies = self.Properties.Policies if self.Properties and self.Properties.Policies else [] <NEW_LINE> for policy in policies: <NEW_LINE> <INDENT> result.append(OptionallyNamedPolicyDocument(name=policy.PolicyName, policy_document=policy.PolicyDocument)) <NEW_LINE> <DEDENT> return result
Properties: - Properties: A [IAM Group properties][pycfmodel.model.resources.iam_group.IAMGroupProperties] object. More info at [AWS Docs](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-group.html)
6259905455399d3f05627a46
class PowerSensors: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.ina = INA219(shunt_ohms=0.1, max_expected_amps=3.0, address=0x40) <NEW_LINE> self.ina.configure(voltage_range=self.ina.RANGE_16V, gain=self.ina.GAIN_AUTO, bus_adc=self.ina.ADC_128SAMP, shunt_adc=self.ina.ADC_128SAMP) <NEW_LINE> <DEDENT> def voltage(self): <NEW_LINE> <INDENT> return self.ina.voltage() <NEW_LINE> <DEDENT> def current(self): <NEW_LINE> <INDENT> return self.ina.current() <NEW_LINE> <DEDENT> def power(self): <NEW_LINE> <INDENT> return self.ina.power()
docblock
62599054d6c5a102081e3646
class InterStrokeDistance: <NEW_LINE> <INDENT> def __init__(self, filename="dist_between_strokes.csv"): <NEW_LINE> <INDENT> self.filename = prepare_file(filename) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "InterStrokeDistance(%s)" % self.filename <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "InterStrokeDistance(%s)" % self.filename <NEW_LINE> <DEDENT> def __call__(self, raw_datasets): <NEW_LINE> <INDENT> with open(self.filename, "a") as write_file: <NEW_LINE> <INDENT> write_file.write("speed\n") <NEW_LINE> print_data = [] <NEW_LINE> start_time = time.time() <NEW_LINE> for i, raw_dataset in enumerate(raw_datasets): <NEW_LINE> <INDENT> if i % 100 == 0 and i > 0: <NEW_LINE> <INDENT> utils.print_status(len(raw_datasets), i, start_time) <NEW_LINE> <DEDENT> pointlist = raw_dataset["handwriting"].get_sorted_pointlist() <NEW_LINE> for last_stroke, stroke in zip(pointlist, pointlist[1:]): <NEW_LINE> <INDENT> point1 = last_stroke[-1] <NEW_LINE> point2 = stroke[0] <NEW_LINE> space_dist = math.hypot( point1["x"] - point2["x"], point1["y"] - point2["y"] ) <NEW_LINE> print_data.append(space_dist) <NEW_LINE> <DEDENT> <DEDENT> print("100%") <NEW_LINE> print_data = sorted(print_data, reverse=True) <NEW_LINE> for value in print_data: <NEW_LINE> <INDENT> write_file.write("%0.8f\n" % (value)) <NEW_LINE> <DEDENT> logger.info("dist_between_strokes mean:\t%0.8fpx", numpy.mean(print_data)) <NEW_LINE> logger.info("dist_between_strokes std: \t%0.8fpx", numpy.std(print_data))
Analyze how much distance in px is between strokes.
6259905438b623060ffaa2e3
class NamespacesMapping(DictElement): <NEW_LINE> <INDENT> schema = Dict(type=NamespaceMapping)
An internal DSL element for mapping all the used blueprints import namespaces.
625990543539df3088ecd7ce
class TestSearchResultOfPostResponse(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testSearchResultOfPostResponse(self): <NEW_LINE> <INDENT> pass
SearchResultOfPostResponse unit test stubs
62599054cb5e8a47e493cc1b
class ResxSettingsDto(object): <NEW_LINE> <INDENT> swagger_types = { 'tag_regexp': 'str' } <NEW_LINE> attribute_map = { 'tag_regexp': 'tagRegexp' } <NEW_LINE> def __init__(self, tag_regexp=None): <NEW_LINE> <INDENT> self._tag_regexp = None <NEW_LINE> self.discriminator = None <NEW_LINE> if tag_regexp is not None: <NEW_LINE> <INDENT> self.tag_regexp = tag_regexp <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def tag_regexp(self): <NEW_LINE> <INDENT> return self._tag_regexp <NEW_LINE> <DEDENT> @tag_regexp.setter <NEW_LINE> def tag_regexp(self, tag_regexp): <NEW_LINE> <INDENT> self._tag_regexp = tag_regexp <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(ResxSettingsDto, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ResxSettingsDto): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
6259905421a7993f00c67496
class ConfigKeyList(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.keys = [] <NEW_LINE> <DEDENT> def addKey(self, key): <NEW_LINE> <INDENT> if isinstance(key, ConfigKey) and self.findKeyById(key.getId()) is None: <NEW_LINE> <INDENT> self.keys.append(key) <NEW_LINE> <DEDENT> <DEDENT> def getKeys(self): <NEW_LINE> <INDENT> return self.keys <NEW_LINE> <DEDENT> def findKeyById(self, id): <NEW_LINE> <INDENT> for k in self.getKeys(): <NEW_LINE> <INDENT> if str(k.getId()) == str(id): <NEW_LINE> <INDENT> return k <NEW_LINE> <DEDENT> <DEDENT> return None
A class representing a list of Form Tags.
62599054f7d966606f74934c
class _ClosedSets(Collection[Collection[T]]): <NEW_LINE> <INDENT> def __init__(self, topology: FiniteTopologyInterface[T]) -> None: <NEW_LINE> <INDENT> self._topology = topology <NEW_LINE> <DEDENT> def __len__(self) -> int: <NEW_LINE> <INDENT> return len(self._topology.open_sets) <NEW_LINE> <DEDENT> def __iter__(self) -> Iterator[Collection[T]]: <NEW_LINE> <INDENT> return ( self._topology.complement(open_set) for open_set in self._topology.open_sets ) <NEW_LINE> <DEDENT> def __contains__(self, item: object) -> bool: <NEW_LINE> <INDENT> return self._topology.complement( cast(Collection[T], item) ) in self._topology.open_sets <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> return '%s(topology=%s)' % ( self.__class__.__name__, self._topology )
Base class for the collection of closed sets
625990540fa83653e46f640d
class CIFARResNeXt(tf.keras.Model): <NEW_LINE> <INDENT> def __init__(self, channels, init_block_channels, cardinality, bottleneck_width, in_channels=3, in_size=(32, 32), classes=10, data_format="channels_last", **kwargs): <NEW_LINE> <INDENT> super(CIFARResNeXt, self).__init__(**kwargs) <NEW_LINE> self.in_size = in_size <NEW_LINE> self.classes = classes <NEW_LINE> self.data_format = data_format <NEW_LINE> self.features = SimpleSequential(name="features") <NEW_LINE> self.features.add(conv3x3_block( in_channels=in_channels, out_channels=init_block_channels, data_format=data_format, name="init_block")) <NEW_LINE> in_channels = init_block_channels <NEW_LINE> for i, channels_per_stage in enumerate(channels): <NEW_LINE> <INDENT> stage = SimpleSequential(name="stage{}".format(i + 1)) <NEW_LINE> for j, out_channels in enumerate(channels_per_stage): <NEW_LINE> <INDENT> strides = 2 if (j == 0) and (i != 0) else 1 <NEW_LINE> stage.add(ResNeXtUnit( in_channels=in_channels, out_channels=out_channels, strides=strides, cardinality=cardinality, bottleneck_width=bottleneck_width, data_format=data_format, name="unit{}".format(j + 1))) <NEW_LINE> in_channels = out_channels <NEW_LINE> <DEDENT> self.features.add(stage) <NEW_LINE> <DEDENT> self.features.add(nn.AveragePooling2D( pool_size=8, strides=1, data_format=data_format, name="final_pool")) <NEW_LINE> self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") <NEW_LINE> <DEDENT> def call(self, x, training=None): <NEW_LINE> <INDENT> x = self.features(x, training=training) <NEW_LINE> x = flatten(x, self.data_format) <NEW_LINE> x = self.output1(x) <NEW_LINE> return x
ResNeXt model for CIFAR from 'Aggregated Residual Transformations for Deep Neural Networks,' http://arxiv.org/abs/1611.05431. Parameters: ---------- channels : list of list of int Number of output channels for each unit. init_block_channels : int Number of output channels for the initial unit. cardinality: int Number of groups. bottleneck_width: int Width of bottleneck block. in_channels : int, default 3 Number of input channels. in_size : tuple of two ints, default (32, 32) Spatial size of the expected input image. classes : int, default 10 Number of classification classes. data_format : str, default 'channels_last' The ordering of the dimensions in tensors.
625990541f037a2d8b9e5300
class PrivateUserApiTests(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.user = create_user( email='[email protected]', password='test123', name='name' ) <NEW_LINE> self.client = APIClient() <NEW_LINE> self.client.force_authenticate(user=self.user) <NEW_LINE> <DEDENT> def test_retrieve_profile_success(self): <NEW_LINE> <INDENT> res = self.client.get(ME_URL) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK) <NEW_LINE> self.assertEqual(res.data, { 'name': self.user.name, 'email': self.user.email, }) <NEW_LINE> <DEDENT> def test_post_me_not_allowed(self): <NEW_LINE> <INDENT> res = self.client.post(ME_URL, {}) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) <NEW_LINE> <DEDENT> def test_update_user_profile(self): <NEW_LINE> <INDENT> payload = { 'name': 'new name', 'password': 'newpassword123' } <NEW_LINE> res = self.client.patch(ME_URL, payload) <NEW_LINE> self.user.refresh_from_db() <NEW_LINE> self.assertEqual(self.user.name, payload['name']) <NEW_LINE> self.assertTrue(self.user.check_password(payload['password'])) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK)
Test API requests that require authentication
62599054cad5886f8bdc5b15
class controller_dailythresh(object): <NEW_LINE> <INDENT> thresh_high_quant = 1 <NEW_LINE> thresh_low_quant = 0 <NEW_LINE> thresh_high_price = 1 <NEW_LINE> thresh_low_price = 0 <NEW_LINE> def __init__(self, df, thresh_high_quant, thresh_low_quant): <NEW_LINE> <INDENT> self.thresh_high_quant = thresh_high_quant <NEW_LINE> self.thresh_low_quant = thresh_low_quant <NEW_LINE> self.update_thresh(df) <NEW_LINE> <DEDENT> def update_thresh(self, df): <NEW_LINE> <INDENT> self.thresh_high_price = df["Apparent Price ($/kWh)"].quantile(self.thresh_high_quant) <NEW_LINE> self.thresh_low_price = df["Apparent Price ($/kWh)"].quantile(self.thresh_low_quant) <NEW_LINE> <DEDENT> def decide(self, df, cur_datetime, battery_obj): <NEW_LINE> <INDENT> if cur_datetime.hour == 0: <NEW_LINE> <INDENT> cur_timestring = str(cur_datetime.year)+ "-" + str(cur_datetime.month) + "-" + str(cur_datetime.day) <NEW_LINE> self.update_thresh(df.loc[cur_timestring]) <NEW_LINE> <DEDENT> cur_price = df["Apparent Price ($/kWh)"].loc[cur_datetime] <NEW_LINE> if cur_price > self.thresh_high_price: <NEW_LINE> <INDENT> request = -1*min(battery_obj.max_charge_rate, battery_obj.available_to_discharge, df['Usage (kWh)'].loc[cur_datetime]) <NEW_LINE> <DEDENT> elif cur_price < self.thresh_low_price: <NEW_LINE> <INDENT> request = min(battery_obj.max_charge_rate, battery_obj.available_store_cap) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> request = 0 <NEW_LINE> <DEDENT> return request
Describes a daily threshold battery controller and maintains pre-calculated variables. Attributes: thresh_high_price: float, the high threshold price, above which the battery discharges itself thresh_low_price: float, the low threshold price, below which the battery charges itself
6259905407f4c71912bb0963
class Prompt: <NEW_LINE> <INDENT> def __init__(self, str='h[%d] >>> '): <NEW_LINE> <INDENT> self.str = str; <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if _ not in [h[-1], None, h]: h.append(_); <NEW_LINE> <DEDENT> except NameError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return self.str % len(h); <NEW_LINE> <DEDENT> def __radd__(self, other): <NEW_LINE> <INDENT> return str(other) + str(self)
Create a prompt that stores results (i.e. _) in the array h.
62599054379a373c97d9a54d
class Place(BaseModel): <NEW_LINE> <INDENT> city_id = "" <NEW_LINE> user_id = "" <NEW_LINE> name = "" <NEW_LINE> description = "" <NEW_LINE> number_rooms = 0 <NEW_LINE> number_bathrooms = 0 <NEW_LINE> max_guest = 0 <NEW_LINE> price_by_night = 0 <NEW_LINE> latitude = 0.0 <NEW_LINE> longitude = 0.0 <NEW_LINE> amenity_ids = []
Place Class
625990548e7ae83300eea5c1
class RNAalignment: <NEW_LINE> <INDENT> def __init__(self, fn): <NEW_LINE> <INDENT> self.alignment = AlignIO.read(open(fn), "stockholm") <NEW_LINE> <DEDENT> def get_range(self, seqid, offset=0, verbose=True): <NEW_LINE> <INDENT> x = self.alignment[-1].seq <NEW_LINE> x_range = [] <NEW_LINE> seq_found = False <NEW_LINE> for record in self.alignment: <NEW_LINE> <INDENT> if record.id == seqid.strip(): <NEW_LINE> <INDENT> seq_found = True <NEW_LINE> spos = 0 <NEW_LINE> for xi, si in zip(x, record.seq): <NEW_LINE> <INDENT> if si != '-': <NEW_LINE> <INDENT> spos += 1 <NEW_LINE> <DEDENT> if xi != '-': <NEW_LINE> <INDENT> x_range.append(spos + offset) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> if not seq_found: <NEW_LINE> <INDENT> raise Exception('Seq not found in the alignment: %s' % seqid) <NEW_LINE> <DEDENT> if not x_range: <NEW_LINE> <INDENT> raise Exception('Seq not found or wrong x line') <NEW_LINE> <DEDENT> return x_range
RNAalignemnt
6259905482261d6c5273095e
@disruptor(tactics, dtype="ALT", weight=1, args={'conf': ("Change the configuration, with the one provided (by name), of " "all subnodes fetched by @path, one-by-one. [default value is set " "dynamically with the first-found existing alternate configuration]", None, str), 'path': ('Graph path regexp to select nodes on which ' 'the disruptor should apply.', None, str), 'recursive': ('Does the reachable nodes from the selected ' 'ones need also to be changed?', True, bool)}) <NEW_LINE> class d_switch_to_alternate_conf(Disruptor): <NEW_LINE> <INDENT> def setup(self, dm, user_input): <NEW_LINE> <INDENT> self.available_confs = dm.node_backend.get_all_confs() <NEW_LINE> if self.available_confs: <NEW_LINE> <INDENT> self.conf_fallback = self.available_confs[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.conf_fallback = None <NEW_LINE> <DEDENT> if self.conf is None: <NEW_LINE> <INDENT> self.conf = self.conf_fallback <NEW_LINE> self.provided_alt = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.provided_alt = True <NEW_LINE> <DEDENT> if self.conf in self.available_confs: <NEW_LINE> <INDENT> self.existing_conf = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.existing_conf = False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def disrupt_data(self, dm, target, prev_data): <NEW_LINE> <INDENT> prev_content = prev_data.content <NEW_LINE> if isinstance(prev_content, Node): <NEW_LINE> <INDENT> if not self.provided_alt and self.available_confs: <NEW_LINE> <INDENT> confs = prev_content.gather_alt_confs() <NEW_LINE> if confs: <NEW_LINE> <INDENT> self.conf_fallback = confs.pop() <NEW_LINE> self.conf = self.conf_fallback <NEW_LINE> self.provided_alt = True <NEW_LINE> self.existing_conf = True <NEW_LINE> <DEDENT> <DEDENT> if self.provided_alt and not self.existing_conf: <NEW_LINE> <INDENT> prev_data.add_info("NO ALTERNATE CONF '{!s}' AVAILABLE".format(self.conf)) <NEW_LINE> return prev_data <NEW_LINE> <DEDENT> if self.conf_fallback is None: <NEW_LINE> <INDENT> prev_data.add_info("NO ALTERNATE CONF AVAILABLE") <NEW_LINE> return prev_data <NEW_LINE> <DEDENT> prev_data.add_info("ALTERNATE CONF '{!s}' USED".format(self.conf)) <NEW_LINE> prev_content.set_current_conf(self.conf, recursive=self.recursive, root_regexp=self.path) <NEW_LINE> prev_content.unfreeze(recursive=True, reevaluate_constraints=True) <NEW_LINE> prev_content.freeze() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> prev_data.add_info('DONT_PROCESS_THIS_KIND_OF_DATA') <NEW_LINE> <DEDENT> return prev_data
Switch to an alternate configuration.
625990542ae34c7f260ac610
class GetTrackedBotHandler(tornado.web.RequestHandler): <NEW_LINE> <INDENT> def post(self): <NEW_LINE> <INDENT> tracked_bots = BaseStation().bot_manager. get_all_tracked_bots_names() <NEW_LINE> print('Bots Tracked: ' + str(tracked_bots)) <NEW_LINE> self.write(json.dumps(tracked_bots).encode())
Gets bot tracked by BotManager.
62599054ac7a0e7691f73a0a
class MAVLink_memory_vect_message(MAVLink_message): <NEW_LINE> <INDENT> id = MAVLINK_MSG_ID_MEMORY_VECT <NEW_LINE> name = 'MEMORY_VECT' <NEW_LINE> fieldnames = ['address', 'ver', 'type', 'value'] <NEW_LINE> ordered_fieldnames = ['address', 'ver', 'type', 'value'] <NEW_LINE> fieldtypes = ['uint16_t', 'uint8_t', 'uint8_t', 'int8_t'] <NEW_LINE> fielddisplays_by_name = {} <NEW_LINE> fieldenums_by_name = {} <NEW_LINE> fieldunits_by_name = {} <NEW_LINE> format = '<HBB32b' <NEW_LINE> native_format = bytearray('<HBBb', 'ascii') <NEW_LINE> orders = [0, 1, 2, 3] <NEW_LINE> lengths = [1, 1, 1, 32] <NEW_LINE> array_lengths = [0, 0, 0, 32] <NEW_LINE> crc_extra = 204 <NEW_LINE> unpacker = struct.Struct('<HBB32b') <NEW_LINE> def __init__(self, address, ver, type, value): <NEW_LINE> <INDENT> MAVLink_message.__init__(self, MAVLink_memory_vect_message.id, MAVLink_memory_vect_message.name) <NEW_LINE> self._fieldnames = MAVLink_memory_vect_message.fieldnames <NEW_LINE> self.address = address <NEW_LINE> self.ver = ver <NEW_LINE> self.type = type <NEW_LINE> self.value = value <NEW_LINE> <DEDENT> def pack(self, mav, force_mavlink1=False): <NEW_LINE> <INDENT> return MAVLink_message.pack(self, mav, 204, struct.pack('<HBB32b', self.address, self.ver, self.type, self.value[0], self.value[1], self.value[2], self.value[3], self.value[4], self.value[5], self.value[6], self.value[7], self.value[8], self.value[9], self.value[10], self.value[11], self.value[12], self.value[13], self.value[14], self.value[15], self.value[16], self.value[17], self.value[18], self.value[19], self.value[20], self.value[21], self.value[22], self.value[23], self.value[24], self.value[25], self.value[26], self.value[27], self.value[28], self.value[29], self.value[30], self.value[31]), force_mavlink1=force_mavlink1)
Send raw controller memory. The use of this message is discouraged for normal packets, but a quite efficient way for testing new messages and getting experimental debug output.
6259905415baa723494634bc
class GlobalSettings(object): <NEW_LINE> <INDENT> site_title = 'MxOnline在线教育系统后台管理' <NEW_LINE> site_footer = "Evan's demo"
X-admin 全局配置参数信息设置
6259905494891a1f408ba18b
class WebsiteUser(HttpLocust): <NEW_LINE> <INDENT> task_set = UserBehavior <NEW_LINE> min_wait = 1000 <NEW_LINE> max_wait = 3000
The Locust class (as well as HttpLocust since it’s a subclass) also allows one to specify minimum and maximum wait time—per simulated user—between the execution of tasks (min_wait and max_wait) as well as other user behaviours.
6259905407d97122c42181d4
class OnLoginView(APIView): <NEW_LINE> <INDENT> authentication_classes = (TokenAuthentication,) <NEW_LINE> permission_classes = (IsAuthenticated,) <NEW_LINE> def get(self, request): <NEW_LINE> <INDENT> if (request.user): <NEW_LINE> <INDENT> user = request.user <NEW_LINE> response_data = { 'first_name': user.first_name, 'avatar': None, 'pools': [] } <NEW_LINE> if user.profile.photo: <NEW_LINE> <INDENT> response_data['avatar'] = user.profile.photo.url <NEW_LINE> <DEDENT> pools = user.pool.all() <NEW_LINE> if pools: <NEW_LINE> <INDENT> for pool in pools: <NEW_LINE> <INDENT> response_data['pools'].append({ 'name': pool.name, 'address': pool.address }) <NEW_LINE> <DEDENT> response = create_response_scelet(u"success", "success", response_data) <NEW_LINE> return Response(response, status=status.HTTP_200_OK) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> response = create_response_scelet(u'failure', u'Unauthorized action', {}) <NEW_LINE> return Response(response, status=status.HTTP_401_UNAUTHORIZED)
User passes his telegram chat_id that he got from the chat bot after giving him his phone number
6259905471ff763f4b5e8cd9
class SOC(Constraint): <NEW_LINE> <INDENT> def __init__(self, t, X, axis=0, constr_id=None): <NEW_LINE> <INDENT> assert not t.shape or len(t.shape) == 1 <NEW_LINE> self.axis = axis <NEW_LINE> super(SOC, self).__init__([t, X], constr_id) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "SOC(%s, %s)" % (self.args[0], self.args[1]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def residual(self): <NEW_LINE> <INDENT> t = self.args[0].value <NEW_LINE> X = self.args[1].value <NEW_LINE> if t is None or X is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if self.axis == 0: <NEW_LINE> <INDENT> X = X.T <NEW_LINE> <DEDENT> norms = np.linalg.norm(X, ord=2, axis=1) <NEW_LINE> zero_indices = np.where(X <= -t)[0] <NEW_LINE> averaged_indices = np.where(X >= np.abs(t))[0] <NEW_LINE> X_proj = np.array(X) <NEW_LINE> t_proj = np.array(t) <NEW_LINE> X_proj[zero_indices] = 0 <NEW_LINE> t_proj[zero_indices] = 0 <NEW_LINE> avg_coeff = 0.5 * (1 + t/norms) <NEW_LINE> X_proj[averaged_indices] = avg_coeff * X[averaged_indices] <NEW_LINE> t_proj[averaged_indices] = avg_coeff * t[averaged_indices] <NEW_LINE> return np.linalg.norm(np.concatenate([X, t], axis=1) - np.concatenate([X_proj, t_proj], axis=1), ord=2, axis=1) <NEW_LINE> <DEDENT> def get_data(self): <NEW_LINE> <INDENT> return [self.axis] <NEW_LINE> <DEDENT> def format(self, eq_constr, leq_constr, dims, solver): <NEW_LINE> <INDENT> leq_constr += self.__format[1] <NEW_LINE> dims[s.SOC_DIM] += self.cone_sizes() <NEW_LINE> <DEDENT> @pu.lazyprop <NEW_LINE> def __format(self): <NEW_LINE> <INDENT> return ([], format_axis(self.args[0], self.args[1], self.axis)) <NEW_LINE> <DEDENT> def num_cones(self): <NEW_LINE> <INDENT> return np.prod(self.args[0].shape, dtype=int) <NEW_LINE> <DEDENT> @property <NEW_LINE> def size(self): <NEW_LINE> <INDENT> return sum(self.cone_sizes()) <NEW_LINE> <DEDENT> def cone_sizes(self): <NEW_LINE> <INDENT> cones = [] <NEW_LINE> cone_size = 1 + self.args[1].shape[self.axis] <NEW_LINE> for i in range(self.num_cones()): <NEW_LINE> <INDENT> cones.append(cone_size) <NEW_LINE> <DEDENT> return cones <NEW_LINE> <DEDENT> def is_dcp(self): <NEW_LINE> <INDENT> return all(arg.is_affine() for arg in self.args) <NEW_LINE> <DEDENT> def canonicalize(self): <NEW_LINE> <INDENT> t, t_cons = self.args[0].canonical_form <NEW_LINE> X, X_cons = self.args[1].canonical_form <NEW_LINE> new_soc = SOC(t, X, self.axis) <NEW_LINE> return (None, [new_soc] + t_cons + X_cons)
A second-order cone constraint for each row/column. Assumes ``t`` is a vector the same length as ``X``'s columns (rows) for ``axis == 0`` (``1``). Attributes: t: The scalar part of the second-order constraint. X: A matrix whose rows/columns are each a cone. axis: Slice by column 0 or row 1.
62599054f7d966606f74934d
class TcpListener(Listener): <NEW_LINE> <INDENT> def __init__(self, *args): <NEW_LINE> <INDENT> Listener.__init__(self, "TCP", *args) <NEW_LINE> <DEDENT> def create_socket(self): <NEW_LINE> <INDENT> return socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> <DEDENT> def identify(self, s, addr): <NEW_LINE> <INDENT> s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) <NEW_LINE> host, port = addr <NEW_LINE> return lookup_host_alias(host) or host
A specialization for TCP sockets. Can be used with fake identification.
6259905407f4c71912bb0964
@ZWaveMessage(COMMAND_CLASS_ASSOCIATION, ASSOCIATION_GROUPINGS_GET) <NEW_LINE> class GroupingsGet(Message): <NEW_LINE> <INDENT> NAME = "GROUPINGS_GET"
Command Class message COMMAND_CLASS_ASSOCIATION ASSOCIATION_GROUPINGS_GET
625990541f037a2d8b9e5301
class NovatelU740(NovatelWCDMADevicePlugin): <NEW_LINE> <INDENT> name = "Novatel U740" <NEW_LINE> version = "0.1" <NEW_LINE> author = "Adam King" <NEW_LINE> custom = NovatelU740Customizer() <NEW_LINE> __remote_name__ = "Merlin U740 (HW REV [0:33])" <NEW_LINE> __properties__ = { 'ID_VENDOR_ID': [0x1410], 'ID_MODEL_ID': [0x1400, 0x1410], } <NEW_LINE> conntype = WADER_CONNTYPE_PCMCIA <NEW_LINE> def preprobe_init(self, ports, info): <NEW_LINE> <INDENT> ser = serial.Serial(ports[0], timeout=1) <NEW_LINE> ser.write('AT$NWDMAT=1\r\n') <NEW_LINE> ser.close()
:class:`~core.plugin.DevicePlugin` for Novatel's U740
62599054097d151d1a2c2597
class BashCharmTemplate(CharmTemplate): <NEW_LINE> <INDENT> def create_charm(self, config, output_dir): <NEW_LINE> <INDENT> self._copy_files(output_dir) <NEW_LINE> for root, dirs, files in os.walk(output_dir): <NEW_LINE> <INDENT> for outfile in files: <NEW_LINE> <INDENT> if self.skip_template(outfile): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> self._template_file(config, path.join(root, outfile)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _copy_files(self, output_dir): <NEW_LINE> <INDENT> here = path.abspath(path.dirname(__file__)) <NEW_LINE> template_dir = path.join(here, 'files') <NEW_LINE> if os.path.exists(output_dir): <NEW_LINE> <INDENT> shutil.rmtree(output_dir) <NEW_LINE> <DEDENT> shutil.copytree(template_dir, output_dir) <NEW_LINE> <DEDENT> def _template_file(self, config, outfile): <NEW_LINE> <INDENT> if path.islink(outfile): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> mode = os.stat(outfile)[ST_MODE] <NEW_LINE> t = Template(file=outfile, searchList=(config)) <NEW_LINE> o = tempfile.NamedTemporaryFile( dir=path.dirname(outfile), delete=False) <NEW_LINE> os.chmod(o.name, mode) <NEW_LINE> st = str(t) <NEW_LINE> if sys.version_info >= (3, ): <NEW_LINE> <INDENT> st = st.encode('UTF-8') <NEW_LINE> <DEDENT> o.write(st) <NEW_LINE> o.close() <NEW_LINE> backupname = outfile + str(time.time()) <NEW_LINE> os.rename(outfile, backupname) <NEW_LINE> os.rename(o.name, outfile) <NEW_LINE> os.unlink(backupname)
Creates a bash-based charm
62599054097d151d1a2c2598
class TestExplainerWhyGranted: <NEW_LINE> <INDENT> @pytest.mark.client <NEW_LINE> @pytest.mark.e2e <NEW_LINE> @pytest.mark.explainer <NEW_LINE> def test_why_granted_permission_for_org(self, forseti_cli: ForsetiCli, forseti_model_readonly, forseti_server_service_account: str, organization_id: str): <NEW_LINE> <INDENT> model_name, _, _ = forseti_model_readonly <NEW_LINE> forseti_cli.model_use(model_name=model_name) <NEW_LINE> result = forseti_cli.explainer_why_granted( f'serviceaccount/{forseti_server_service_account}', f'organization/{organization_id}', permission='iam.serviceAccounts.get') <NEW_LINE> assert result.returncode == 0, f'Forseti stdout: {str(result.stdout)}' <NEW_LINE> assert re.search(r'roles\/iam.securityReviewer', str(result.stdout)) <NEW_LINE> <DEDENT> @pytest.mark.client <NEW_LINE> @pytest.mark.e2e <NEW_LINE> @pytest.mark.explainer <NEW_LINE> def test_why_granted_permission_for_project(self, forseti_cli: ForsetiCli, forseti_model_readonly, forseti_server_service_account: str, project_id: str): <NEW_LINE> <INDENT> model_name, _, _ = forseti_model_readonly <NEW_LINE> forseti_cli.model_use(model_name=model_name) <NEW_LINE> result = forseti_cli.explainer_why_granted( f'serviceaccount/{forseti_server_service_account}', f'project/{project_id}', permission='compute.instances.get') <NEW_LINE> assert result.returncode == 0, f'Forseti stdout: {str(result.stdout)}' <NEW_LINE> assert re.search(r'roles\/compute.networkViewer', str(result.stdout)) <NEW_LINE> <DEDENT> @pytest.mark.client <NEW_LINE> @pytest.mark.e2e <NEW_LINE> @pytest.mark.explainer <NEW_LINE> def test_why_granted_role_for_org(self, forseti_cli: ForsetiCli, forseti_model_readonly, forseti_server_service_account: str, organization_id: str): <NEW_LINE> <INDENT> model_name, _, _ = forseti_model_readonly <NEW_LINE> forseti_cli.model_use(model_name=model_name) <NEW_LINE> result = forseti_cli.explainer_why_granted( f'serviceaccount/{forseti_server_service_account}', f'organization/{organization_id}', role='roles/iam.securityReviewer') <NEW_LINE> assert result.returncode == 0, f'Forseti stdout: {str(result.stdout)}' <NEW_LINE> assert re.search(fr'organization\/{organization_id}', str(result.stdout)) <NEW_LINE> <DEDENT> @pytest.mark.client <NEW_LINE> @pytest.mark.e2e <NEW_LINE> @pytest.mark.explainer <NEW_LINE> def test_why_granted_role_for_project(self, forseti_cli: ForsetiCli, forseti_model_readonly, forseti_server_service_account: str, organization_id: str, project_id: str): <NEW_LINE> <INDENT> model_name, _, _ = forseti_model_readonly <NEW_LINE> forseti_cli.model_use(model_name=model_name) <NEW_LINE> result = forseti_cli.explainer_why_granted( f'serviceaccount/{forseti_server_service_account}', f'project/{project_id}', role='roles/cloudsql.client') <NEW_LINE> assert result.returncode == 0, f'Forseti stdout: {str(result.stdout)}' <NEW_LINE> assert re.search(fr'organization\/{organization_id}', str(result.stdout))
Explainer why_granted tests.
6259905407f4c71912bb0965
class VLblNceSentimentTrainer(SimpleVLblNceSentimentTrainer): <NEW_LINE> <INDENT> def create_model(self): <NEW_LINE> <INDENT> return VLblNce(self.batch_size, self.effective_vocab_size, self.left_context, self.right_context, self.word_embedding_size, self.k, self.unigram, l1_weight=self.l1_weight, l2_weight=self.l2_weight, nce_seed=self.nce_seed)
Create a vLBL model that trains special sentiment embeddings.
62599054b5575c28eb713761
class NaiveConvolutionalFeatureMap(BaseBPropComponent): <NEW_LINE> <INDENT> def __init__(self, fsize, imsize): <NEW_LINE> <INDENT> super(NaiveConvolutionalFeatureMap, self).__init__() <NEW_LINE> self.convolution = ConvolutionalPlane(fsize, imsize) <NEW_LINE> self.nonlinearity = TanhSigmoid(self.convolution.outsize) <NEW_LINE> <DEDENT> def fprop(self, inputs): <NEW_LINE> <INDENT> return self.nonlinearity.fprop(self.convolution.fprop(inputs)) <NEW_LINE> <DEDENT> def bprop(self, dout, inputs): <NEW_LINE> <INDENT> squash_inputs = self.convolution.fprop(inputs) <NEW_LINE> squash_derivs = self.nonlinearity.bprop(dout, squash_inputs) <NEW_LINE> return self.convolution.bprop(squash_derivs, inputs) <NEW_LINE> <DEDENT> def grad(self, dout, inputs): <NEW_LINE> <INDENT> squash_inputs = self.convolution.fprop(inputs) <NEW_LINE> squash_derivs = self.nonlinearity.bprop(dout, squash_inputs) <NEW_LINE> return self.convolution.grad(squash_derivs, inputs) <NEW_LINE> <DEDENT> def initialize(self): <NEW_LINE> <INDENT> self.convolution.initialize() <NEW_LINE> <DEDENT> @property <NEW_LINE> def outsize(self): <NEW_LINE> <INDENT> return self.convolution.outsize <NEW_LINE> <DEDENT> @property <NEW_LINE> def imsize(self): <NEW_LINE> <INDENT> return self.convolution.imsize <NEW_LINE> <DEDENT> @property <NEW_LINE> def fsize(self): <NEW_LINE> <INDENT> return self.convolution.filter.shape
One way to implement a standard feature map that takes input from a single lower-level image. This serves two purposes: to demonstrate how to write new learning modules by composing two existing modules, and to serve as a sanity check for the more efficient implementation, ConvolutionalFeatureMap. Has, as members, a ConvolutionalPlane with standard bias configuration and a TanhSigmoid object that does the squashing. This is a little wasteful since each of the modules has separate output array members. See FeatureMap for a slightly more memory efficient implementation that uses subclassing.
62599054dd821e528d6da40a
class UniformSampler(SingleVideoFrameSampler): <NEW_LINE> <INDENT> def __init__(self, offset, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> assert isinstance(offset, int), "`offset` must be an integer." <NEW_LINE> self._offset = offset <NEW_LINE> <DEDENT> def _sample(self, frames): <NEW_LINE> <INDENT> vid_len = len(frames) <NEW_LINE> cond1 = vid_len >= self._offset <NEW_LINE> cond2 = self._num_frames < (vid_len - self._offset) <NEW_LINE> if cond1 and cond2: <NEW_LINE> <INDENT> cc_idxs = list(range(self._offset, vid_len)) <NEW_LINE> random.shuffle(cc_idxs) <NEW_LINE> cc_idxs = cc_idxs[:self._num_frames] <NEW_LINE> return sorted(cc_idxs) <NEW_LINE> <DEDENT> return list(range(0, self._num_frames))
Uniformly sample video frames starting from an optional offset.
62599054e5267d203ee6ce1a
class KeywordPlanCampaignServiceStub(object): <NEW_LINE> <INDENT> def __init__(self, channel): <NEW_LINE> <INDENT> self.GetKeywordPlanCampaign = channel.unary_unary( '/google.ads.googleads.v1.services.KeywordPlanCampaignService/GetKeywordPlanCampaign', request_serializer=google_dot_ads_dot_googleads__v1_dot_proto_dot_services_dot_keyword__plan__campaign__service__pb2.GetKeywordPlanCampaignRequest.SerializeToString, response_deserializer=google_dot_ads_dot_googleads__v1_dot_proto_dot_resources_dot_keyword__plan__campaign__pb2.KeywordPlanCampaign.FromString, ) <NEW_LINE> self.MutateKeywordPlanCampaigns = channel.unary_unary( '/google.ads.googleads.v1.services.KeywordPlanCampaignService/MutateKeywordPlanCampaigns', request_serializer=google_dot_ads_dot_googleads__v1_dot_proto_dot_services_dot_keyword__plan__campaign__service__pb2.MutateKeywordPlanCampaignsRequest.SerializeToString, response_deserializer=google_dot_ads_dot_googleads__v1_dot_proto_dot_services_dot_keyword__plan__campaign__service__pb2.MutateKeywordPlanCampaignsResponse.FromString, )
Proto file describing the keyword plan campaign service. Service to manage Keyword Plan campaigns.
6259905416aa5153ce401a10
class BooleanFieldFilter(django_filters.Filter): <NEW_LINE> <INDENT> def filter(self, qs, value): <NEW_LINE> <INDENT> if value is not None: <NEW_LINE> <INDENT> lc_value = value.lower() <NEW_LINE> if lc_value in ('true', 't', 'yes', 'y', '1'): <NEW_LINE> <INDENT> value = True <NEW_LINE> <DEDENT> elif lc_value in ('false', 'f', 'no', 'n', '0'): <NEW_LINE> <INDENT> value = False <NEW_LINE> <DEDENT> return qs.filter(**{self.name: value}) <NEW_LINE> <DEDENT> return qs
This throws a `Validation Error` if a value that is not in the required boolean choices is provided. Choices are (case insensitive): ['true', 't', 'yes', 'y', '1', 'false', 'f', 'no', 'n', '0]
62599054435de62698e9d32e
@dataclass <NEW_LINE> class StandardMessage(Message): <NEW_LINE> <INDENT> level: Level <NEW_LINE> content: str <NEW_LINE> timestamp: datetime <NEW_LINE> topic: str <NEW_LINE> host: str
A message with standard attributes.
62599055b7558d58954649c0
class PrivateUserApiTests(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.user = create_user( email='test@kburakengin', password='test123', name='testuser' ) <NEW_LINE> self.client = APIClient() <NEW_LINE> self.client.force_authenticate(user=self.user) <NEW_LINE> <DEDENT> def test_retrieve_profile_success(self): <NEW_LINE> <INDENT> res = self.client.get(ME_URL) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK) <NEW_LINE> self.assertEqual(res.data, { 'name': self.user.name, 'email': self.user.email }) <NEW_LINE> <DEDENT> def test_post_me_not_allowed(self): <NEW_LINE> <INDENT> res = self.client.post(ME_URL, {}) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) <NEW_LINE> <DEDENT> def test_update_user_profile(self): <NEW_LINE> <INDENT> payload = { 'name': 'new name', 'password': 'newtest123' } <NEW_LINE> res = self.client.patch(ME_URL, payload) <NEW_LINE> self.user.refresh_from_db() <NEW_LINE> self.assertEqual(self.user.name, payload['name']) <NEW_LINE> self.assertTrue(self.user.check_password(payload['password'])) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK)
Test API requests that require authentication
6259905510dbd63aa1c7210e
class StopConversation(Exception): <NEW_LINE> <INDENT> pass
raise if conversation has terminated
6259905576d4e153a661dd11
class IdGeneratorMixIn: <NEW_LINE> <INDENT> def __init__(self, start_value=0): <NEW_LINE> <INDENT> self.id_count = start_value <NEW_LINE> <DEDENT> def init_counter(self, start_value=0): <NEW_LINE> <INDENT> self.id_count = start_value <NEW_LINE> <DEDENT> def generate_id(self): <NEW_LINE> <INDENT> self.id_count += 1 <NEW_LINE> return self.id_count
Mixin adding the ability to generate integer uid
625990558da39b475be04717
class _SearchChild(object): <NEW_LINE> <INDENT> def __init__(self, cgroupdir=None, fork=True): <NEW_LINE> <INDENT> self.pid = None <NEW_LINE> self.tempdir = mkdtemp(prefix='diamond-search-') <NEW_LINE> self._started = False <NEW_LINE> self._terminated = False <NEW_LINE> self._fork = fork <NEW_LINE> if fork and cgroupdir is not None: <NEW_LINE> <INDENT> self._cgroupdir = mkdtemp(dir=cgroupdir, prefix='diamond-') <NEW_LINE> self._taskfile = os.path.join(self._cgroupdir, 'tasks') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._cgroupdir = None <NEW_LINE> self._taskfile = None <NEW_LINE> <DEDENT> <DEDENT> def start(self): <NEW_LINE> <INDENT> assert not self._started <NEW_LINE> self._started = True <NEW_LINE> if self._fork: <NEW_LINE> <INDENT> self.pid = os.fork() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _log.info('Oneshot mode, running search in child') <NEW_LINE> self.pid = 0 <NEW_LINE> <DEDENT> if self.pid == 0: <NEW_LINE> <INDENT> os.environ['TMPDIR'] = self.tempdir <NEW_LINE> if self._taskfile is not None: <NEW_LINE> <INDENT> open(self._taskfile, 'w').write('%d\n' % os.getpid()) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> _log.info('Launching PID %d', self.pid) <NEW_LINE> <DEDENT> return self.pid <NEW_LINE> <DEDENT> def cleanup(self): <NEW_LINE> <INDENT> if not self._terminated: <NEW_LINE> <INDENT> self._terminated = True <NEW_LINE> if self._taskfile is not None: <NEW_LINE> <INDENT> killed = set() <NEW_LINE> while True: <NEW_LINE> <INDENT> pids = [int(pid) for pid in open(self._taskfile)] <NEW_LINE> if len(pids) == 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> for pid in pids: <NEW_LINE> <INDENT> if pid not in killed: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.kill(pid, signal.SIGKILL) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> killed.add(pid) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> for _i in range(3): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.rmdir(self._cgroupdir) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> time.sleep(0.001) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> _log.warning("Couldn't remove %s", self._cgroupdir) <NEW_LINE> <DEDENT> _log.info('PID %d exiting, killed %d processes', self.pid, len(killed)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _log.info('PID %d exiting', self.pid) <NEW_LINE> <DEDENT> shutil.rmtree(self.tempdir, True)
A forked search process.
62599055baa26c4b54d507cf
class Post(object): <NEW_LINE> <INDENT> def __init__(self, content, handler=None, **metadata): <NEW_LINE> <INDENT> self.content = str(content) <NEW_LINE> self.metadata = metadata <NEW_LINE> self.handler = handler <NEW_LINE> <DEDENT> def __getitem__(self, name): <NEW_LINE> <INDENT> return self.metadata[name] <NEW_LINE> <DEDENT> def __contains__(self, item): <NEW_LINE> <INDENT> return item in self.metadata <NEW_LINE> <DEDENT> def __setitem__(self, name, value): <NEW_LINE> <INDENT> self.metadata[name] = value <NEW_LINE> <DEDENT> def __delitem__(self, name): <NEW_LINE> <INDENT> del self.metadata[name] <NEW_LINE> <DEDENT> def __bytes__(self): <NEW_LINE> <INDENT> return self.content.encode("utf-8") <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.content <NEW_LINE> <DEDENT> def get(self, key, default=None): <NEW_LINE> <INDENT> return self.metadata.get(key, default) <NEW_LINE> <DEDENT> def keys(self): <NEW_LINE> <INDENT> return self.metadata.keys() <NEW_LINE> <DEDENT> def values(self): <NEW_LINE> <INDENT> return self.metadata.values() <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> d = self.metadata.copy() <NEW_LINE> d["content"] = self.content <NEW_LINE> return d
A post contains content and metadata from Front Matter. This is what gets returned by :py:func:`load <frontmatter.load>` and :py:func:`loads <frontmatter.loads>`. Passing this to :py:func:`dump <frontmatter.dump>` or :py:func:`dumps <frontmatter.dumps>` will turn it back into text. For convenience, metadata values are available as proxied item lookups.
6259905521a7993f00c6749a
class Operator(SparseMatrix): <NEW_LINE> <INDENT> def __init__(self, n_qubits : int=1, base = np.zeros((2,2))): <NEW_LINE> <INDENT> if n_qubits <= 0 : <NEW_LINE> <INDENT> raise ValueError('Operator must operate on at least 1 qubit!') <NEW_LINE> <DEDENT> self.n_qubits = n_qubits <NEW_LINE> self.size = 2 ** n_qubits <NEW_LINE> if self.size < len(base): <NEW_LINE> <INDENT> raise ValueError("Operator cannot act on the specified number" + "of qubits.") <NEW_LINE> <DEDENT> act_qubits = int(np.log2(len(base))) <NEW_LINE> base_matrix = SparseMatrix(*[len(base)]*2) <NEW_LINE> for i in range(0, len(base)): <NEW_LINE> <INDENT> for j in range(0, len(base)): <NEW_LINE> <INDENT> if base[i][j] != 0: <NEW_LINE> <INDENT> base_matrix.setElement(i, j, complex(base[i][j])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for i in range(0, n_qubits, act_qubits): <NEW_LINE> <INDENT> if i == 0: <NEW_LINE> <INDENT> result = base_matrix <NEW_LINE> continue <NEW_LINE> <DEDENT> result = result.outerProduct(base_matrix) <NEW_LINE> <DEDENT> super(Operator, self).__init__(self.size,self.size) <NEW_LINE> self.matrix = result.matrix <NEW_LINE> <DEDENT> def __mul__(self, rhs): <NEW_LINE> <INDENT> if isinstance(rhs, QuantumRegister): <NEW_LINE> <INDENT> result = QuantumRegister(n_qubits = self.n_qubits) <NEW_LINE> <DEDENT> elif isinstance(rhs, Operator): <NEW_LINE> <INDENT> result = Operator(n_qubits = self.n_qubits) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> raise TypeError('Multiplication not defined for Operator' + ' and {}.'.format(type(rhs))) <NEW_LINE> <DEDENT> if rhs.n_qubits != self.n_qubits: <NEW_LINE> <INDENT> raise ValueError( 'Number of states do not correspnd: rhs.n_qubits = {},' + ' lhs.n_qubits = {}'.format(rhs.n_qubits, self.n_qubits)) <NEW_LINE> <DEDENT> result.matrix = self.innerProduct(rhs).matrix <NEW_LINE> return result <NEW_LINE> <DEDENT> def __mod__(self, rhs): <NEW_LINE> <INDENT> if isinstance(rhs, Operator): <NEW_LINE> <INDENT> result = Operator(self.n_qubits + rhs.n_qubits) <NEW_LINE> result.matrix = self.outerProduct(rhs).matrix <NEW_LINE> return result <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError('Operation not defined between operator and ' + '{}.'.format(type(rhs)))
Operator class inherits from SparceMatrix
62599055adb09d7d5dc0ba96
class SNS(PushEventSource): <NEW_LINE> <INDENT> resource_type = 'SNS' <NEW_LINE> principal = 'sns.amazonaws.com' <NEW_LINE> property_types = { 'Topic': PropertyType(True, is_str()) } <NEW_LINE> def to_cloudformation(self, **kwargs): <NEW_LINE> <INDENT> function = kwargs.get('function') <NEW_LINE> if not function: <NEW_LINE> <INDENT> raise TypeError("Missing required keyword argument: function") <NEW_LINE> <DEDENT> return [self._construct_permission(function, source_arn=self.Topic), self._inject_subscription(function, self.Topic)] <NEW_LINE> <DEDENT> def _inject_subscription(self, function, topic): <NEW_LINE> <INDENT> subscription = SNSSubscription(self.logical_id) <NEW_LINE> subscription.Protocol = 'lambda' <NEW_LINE> subscription.Endpoint = function.get_runtime_attr("arn") <NEW_LINE> subscription.TopicArn = topic <NEW_LINE> return subscription
SNS topic event source for SAM Functions.
62599055097d151d1a2c259a
class Category(models.Model): <NEW_LINE> <INDENT> title = models.CharField(_("title"), max_length=200) <NEW_LINE> parent = models.ForeignKey( "self", blank=True, null=True, on_delete=models.CASCADE, related_name="children", limit_choices_to={"parent__isnull": True}, verbose_name=_("parent"), ) <NEW_LINE> slug = models.SlugField(_("slug"), max_length=150) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ["parent__title", "title"] <NEW_LINE> verbose_name = _("category") <NEW_LINE> verbose_name_plural = _("categories") <NEW_LINE> app_label = "medialibrary" <NEW_LINE> <DEDENT> objects = CategoryManager() <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> if self.parent_id: <NEW_LINE> <INDENT> return f"{self.parent.title} - {self.title}" <NEW_LINE> <DEDENT> return self.title <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if not self.slug: <NEW_LINE> <INDENT> self.slug = slugify(self.title) <NEW_LINE> <DEDENT> super().save(*args, **kwargs) <NEW_LINE> <DEDENT> save.alters_data = True <NEW_LINE> def path_list(self): <NEW_LINE> <INDENT> if self.parent is None: <NEW_LINE> <INDENT> return [self] <NEW_LINE> <DEDENT> p = self.parent.path_list() <NEW_LINE> p.append(self) <NEW_LINE> return p <NEW_LINE> <DEDENT> def path(self): <NEW_LINE> <INDENT> return " - ".join(f.title for f in self.path_list())
These categories are meant primarily for organizing media files in the library.
62599055cad5886f8bdc5b17
class Room: <NEW_LINE> <INDENT> def __init__(self, name, description, items = [], water_source=False): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.description = description <NEW_LINE> self.items = items <NEW_LINE> self.water_source = water_source <NEW_LINE> self.players = [] <NEW_LINE> <DEDENT> def is_here(self, player): <NEW_LINE> <INDENT> return player in [player.name for player in self.players] <NEW_LINE> <DEDENT> def remove_player(self, player): <NEW_LINE> <INDENT> who = None <NEW_LINE> for gamer in self.players: <NEW_LINE> <INDENT> if gamer.name == player.name: <NEW_LINE> <INDENT> who = gamer <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> self.players.remove(who) <NEW_LINE> return "\nPlayer %s left the %s" % (player, self.name) <NEW_LINE> <DEDENT> def add_player(self, player): <NEW_LINE> <INDENT> self.players.append(player) <NEW_LINE> return "\nPlayer %s join the %s" % (player, self.name) <NEW_LINE> <DEDENT> def describe_me(self): <NEW_LINE> <INDENT> description = "You are in %s. People in room: %s\n%s" % (self.name, ' '.join(map(str, self.players)), self.description) <NEW_LINE> if self.items: <NEW_LINE> <INDENT> description += "\nitems: %s" % (self.items,) <NEW_LINE> <DEDENT> if self.water_source: <NEW_LINE> <INDENT> description += "\nYou can take water from here!!" <NEW_LINE> <DEDENT> return description <NEW_LINE> <DEDENT> def get_item(self, name): <NEW_LINE> <INDENT> number = None <NEW_LINE> for no, elem in enumerate(self.items): <NEW_LINE> <INDENT> if elem.name == name: <NEW_LINE> <INDENT> number = no <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> return self.items.pop(number) if number is not None else None <NEW_LINE> <DEDENT> def drop_item(self, item): <NEW_LINE> <INDENT> self.items.append(item)
The room is on fire (maybe)
62599055e76e3b2f99fd9f2b
class IntUniformDistribution(BaseDistribution): <NEW_LINE> <INDENT> def __init__(self, low: int, high: int, step: int = 1) -> None: <NEW_LINE> <INDENT> if low > high: <NEW_LINE> <INDENT> raise ValueError( "The `low` value must be smaller than or equal to the `high` value " "(low={}, high={}).".format(low, high) ) <NEW_LINE> <DEDENT> if step <= 0: <NEW_LINE> <INDENT> raise ValueError( "The `step` value must be non-zero positive value, but step={}.".format(step) ) <NEW_LINE> <DEDENT> high = _adjust_int_uniform_high(low, high, step) <NEW_LINE> self.low = low <NEW_LINE> self.high = high <NEW_LINE> self.step = step <NEW_LINE> <DEDENT> def to_external_repr(self, param_value_in_internal_repr: float) -> int: <NEW_LINE> <INDENT> return int(param_value_in_internal_repr) <NEW_LINE> <DEDENT> def to_internal_repr(self, param_value_in_external_repr: int) -> float: <NEW_LINE> <INDENT> return float(param_value_in_external_repr) <NEW_LINE> <DEDENT> def single(self) -> bool: <NEW_LINE> <INDENT> if self.low == self.high: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return (self.high - self.low) < self.step <NEW_LINE> <DEDENT> def _contains(self, param_value_in_internal_repr: float) -> bool: <NEW_LINE> <INDENT> value = param_value_in_internal_repr <NEW_LINE> return self.low <= value <= self.high
A uniform distribution on integers. This object is instantiated by :func:`~optuna.trial.Trial.suggest_int`, and passed to :mod:`~optuna.samplers` in general. .. note:: If the range :math:`[\mathsf{low}, \mathsf{high}]` is not divisible by :math:`\mathsf{step}`, :math:`\mathsf{high}` will be replaced with the maximum of :math:`k \times \mathsf{step} + \mathsf{low} \lt \mathsf{high}`, where :math:`k` is an integer. Attributes: low: Lower endpoint of the range of the distribution. ``low`` is included in the range. high: Upper endpoint of the range of the distribution. ``high`` is included in the range. step: A step for spacing between values.
6259905501c39578d7f141ce
class EncoderClient(): <NEW_LINE> <INDENT> def __init__(self, host='0.0.0.0', port=3000): <NEW_LINE> <INDENT> self.channel = grpc.insecure_channel('%s:%d' % (host, port)) <NEW_LINE> self.stub = encoder_pb2.EncoderStub(self.channel) <NEW_LINE> <DEDENT> def encode(self, _url): <NEW_LINE> <INDENT> req = encoder_pb2.EncodeRequest(url=str(_url)) <NEW_LINE> return self.stub.encode(req) <NEW_LINE> <DEDENT> def decode(self, _id): <NEW_LINE> <INDENT> req = encoder_pb2.DecodeRequest(id=int(_id)) <NEW_LINE> return self.stub.decode(req)
EncoderClient is a proxy to GRPC EncoderServer.
62599055baa26c4b54d507d0
class UnknownMetaEvent(MetaEvent): <NEW_LINE> <INDENT> meta_command = None <NEW_LINE> name = 'Unknown' <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(UnknownMetaEvent, self).__init__(**kwargs) <NEW_LINE> self.meta_command = kwargs['meta_command']
Unknown Meta Event. Parameters ---------- meta_command : int Value of the meta command.
62599055b830903b9686ef14
class NoLimitLeduc(LeducRules, NoLimitPokerEnv): <NEW_LINE> <INDENT> RULES = LeducRules <NEW_LINE> IS_FIXED_LIMIT_GAME = False <NEW_LINE> IS_POT_LIMIT_GAME = False <NEW_LINE> SMALL_BLIND = 50 <NEW_LINE> BIG_BLIND = 100 <NEW_LINE> ANTE = 0 <NEW_LINE> DEFAULT_STACK_SIZE = 20000 <NEW_LINE> EV_NORMALIZER = 1000.0 / BIG_BLIND <NEW_LINE> WIN_METRIC = Poker.MeasureBB <NEW_LINE> def __init__(self, env_args, lut_holder, is_evaluating): <NEW_LINE> <INDENT> LeducRules.__init__(self) <NEW_LINE> NoLimitPokerEnv.__init__(self, env_args=env_args, lut_holder=lut_holder, is_evaluating=is_evaluating)
A variant of Leduc with no bet-cap in the no-limit format. It uses blinds instead of antes.
6259905545492302aabfda04
class TestSimilarityScorerConfig(BaseTest): <NEW_LINE> <INDENT> def test_config(self): <NEW_LINE> <INDENT> data_type = 'test:test' <NEW_LINE> index = 'test_index' <NEW_LINE> config = SimilarityScorerConfig(data_type=data_type, index=index) <NEW_LINE> compare_config = { 'index': '{0}'.format(index), 'data_type': '{0}'.format(data_type), 'query': 'data_type:"{0}"'.format(data_type), 'field': 'message', 'delimiters': [' ', '-', '/'], 'threshold': config.DEFAULT_THRESHOLD, 'num_perm': config.DEFAULT_PERMUTATIONS } <NEW_LINE> self.assertIsInstance(config, SimilarityScorerConfig) <NEW_LINE> for k, v in compare_config.items(): <NEW_LINE> <INDENT> self.assertEqual(v, getattr(config, k))
Tests for the functionality of the config object.
6259905521bff66bcd724192
class MAVLink_wind_message(MAVLink_message): <NEW_LINE> <INDENT> id = MAVLINK_MSG_ID_WIND <NEW_LINE> name = 'WIND' <NEW_LINE> fieldnames = ['direction', 'speed', 'speed_z'] <NEW_LINE> ordered_fieldnames = [ 'direction', 'speed', 'speed_z' ] <NEW_LINE> format = '<fff' <NEW_LINE> native_format = bytearray('<fff', 'ascii') <NEW_LINE> orders = [0, 1, 2] <NEW_LINE> lengths = [1, 1, 1] <NEW_LINE> array_lengths = [0, 0, 0] <NEW_LINE> crc_extra = 1 <NEW_LINE> def __init__(self, direction, speed, speed_z): <NEW_LINE> <INDENT> MAVLink_message.__init__(self, MAVLink_wind_message.id, MAVLink_wind_message.name) <NEW_LINE> self._fieldnames = MAVLink_wind_message.fieldnames <NEW_LINE> self.direction = direction <NEW_LINE> self.speed = speed <NEW_LINE> self.speed_z = speed_z <NEW_LINE> <DEDENT> def pack(self, mav): <NEW_LINE> <INDENT> return MAVLink_message.pack(self, mav, 1, struct.pack('<fff', self.direction, self.speed, self.speed_z))
Wind estimation
62599055004d5f362081fa83
class StemmerI(object): <NEW_LINE> <INDENT> def stem(self, token): <NEW_LINE> <INDENT> raise NotImplementedError()
A processing interface for removing morphological affixes from words. This process is known as X{stemming}.
62599055dc8b845886d54af2
class EmailChangeConfirmViewTests(ManifestTestCase): <NEW_LINE> <INDENT> user_data = ["john", "pass"] <NEW_LINE> def test_valid_confirmation(self): <NEW_LINE> <INDENT> user = get_user_model().objects.get(username=self.user_data[0]) <NEW_LINE> user.change_email("[email protected]") <NEW_LINE> self.assertEqual(user.email_unconfirmed, "[email protected]") <NEW_LINE> self.assertNotEqual(user.email, "[email protected]") <NEW_LINE> response = self.client.get( reverse( "email_change_confirm", kwargs={ "username": user.username, "token": user.email_confirmation_key, }, ) ) <NEW_LINE> self.assertRedirects(response, reverse("email_change_complete")) <NEW_LINE> user = get_user_model().objects.get(username=self.user_data[0]) <NEW_LINE> self.assertEqual(user.email, "[email protected]") <NEW_LINE> <DEDENT> def test_invalid_confirmation(self): <NEW_LINE> <INDENT> response = self.client.get( reverse( "email_change_confirm", kwargs={"username": "john", "token": "WRONG"}, ) ) <NEW_LINE> self.assertTemplateUsed(response, "manifest/email_change_confirm.html") <NEW_LINE> <DEDENT> def test_email_change_confirm_success_url(self): <NEW_LINE> <INDENT> user = get_user_model().objects.get(username=self.user_data[0]) <NEW_LINE> user.change_email("[email protected]") <NEW_LINE> response = self.client.get( reverse( "test_email_change_confirm_success_url", kwargs={ "username": user.username, "token": user.email_confirmation_key, }, ) ) <NEW_LINE> self.assertRedirects(response, TEST_SUCCESS_URL)
Tests for :class:`EmailChangeConfirmView <manifest.views.EmailChangeConfirmView>`.
625990553539df3088ecd7d4
class UserAgentMiddleware(object): <NEW_LINE> <INDENT> def __init__(self, user_agent='Scrapy'): <NEW_LINE> <INDENT> self.user_agent = random.choice(USER_AGENT_LIST) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_crawler(cls, crawler): <NEW_LINE> <INDENT> o = cls(crawler.settings['USER_AGENT']) <NEW_LINE> crawler.signals.connect(o.spider_opened, signal=signals.spider_opened) <NEW_LINE> return o <NEW_LINE> <DEDENT> def spider_opened(self, spider): <NEW_LINE> <INDENT> self.user_agent = getattr(spider, 'user_agent', self.user_agent) <NEW_LINE> <DEDENT> def process_request(self, request, spider): <NEW_LINE> <INDENT> if self.user_agent: <NEW_LINE> <INDENT> request.headers.setdefault(b'User-Agent', self.user_agent)
This middleware allows spiders to override the user_agent
625990558a43f66fc4bf36bb
class TicTacToe(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.matrix=[[' ' for i in range(3)] for j in range(3)] <NEW_LINE> <DEDENT> def line(self): <NEW_LINE> <INDENT> return('-----') <NEW_LINE> <DEDENT> def line1(self): <NEW_LINE> <INDENT> return self.matrix[0][0]+'|'+self.matrix[1][0]+'|'+self.matrix[2][0] <NEW_LINE> <DEDENT> def line2(self): <NEW_LINE> <INDENT> return self.matrix[0][1]+'|'+self.matrix[1][1]+'|'+self.matrix[2][1] <NEW_LINE> <DEDENT> def line3(self): <NEW_LINE> <INDENT> return self.matrix[0][2]+'|'+self.matrix[1][2]+'|'+self.matrix[2][2] <NEW_LINE> <DEDENT> def getBoard(self): <NEW_LINE> <INDENT> return self.line1()+"\n"+self.line()+'\n'+self.line2()+'\n'+ self.line()+'\n'+self.line3()+'\n'
plays a tic tac toe game
62599055d53ae8145f919990
class TestWidgetTest(WidgetTest): <NEW_LINE> <INDENT> def test_process_events_handles_timeouts(self): <NEW_LINE> <INDENT> with self.assertRaises(TimeoutError): <NEW_LINE> <INDENT> self.process_events(until=lambda: False, timeout=0) <NEW_LINE> <DEDENT> <DEDENT> def test_minimum_size(self): <NEW_LINE> <INDENT> return
Meta tests for widget test helpers
62599055d99f1b3c44d06bce
class LazySequence(Sequence): <NEW_LINE> <INDENT> _ref_lru = deque(maxlen=1000) <NEW_LINE> def __init__(self, seq=(), map_func=None): <NEW_LINE> <INDENT> if map_func is not None and not isinstance(map_func, Callable): <NEW_LINE> <INDENT> raise ValueError('LazySequence: map_func must be callable.') <NEW_LINE> <DEDENT> self._map_funcs = [] <NEW_LINE> if isinstance(seq, LazySequence): <NEW_LINE> <INDENT> self._base_seq = seq._base_seq <NEW_LINE> self._base_range = seq._base_range <NEW_LINE> self._weakref_cache = WeakValueDictionary() <NEW_LINE> self._map_funcs.extend(seq._map_funcs) <NEW_LINE> <DEDENT> elif isinstance(seq, Sequence): <NEW_LINE> <INDENT> self._base_seq = seq <NEW_LINE> self._base_range = range(len(seq)) <NEW_LINE> self._weakref_cache = WeakValueDictionary() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('LazySequence: seq must be a true sequence.') <NEW_LINE> <DEDENT> if map_func is not None: <NEW_LINE> <INDENT> self._map_funcs.append(map_func) <NEW_LINE> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._base_range) <NEW_LINE> <DEDENT> def _apply_maps(self, val): <NEW_LINE> <INDENT> for m in self._map_funcs: <NEW_LINE> <INDENT> val = m(val) <NEW_LINE> <DEDENT> return val <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> if isinstance(index, slice): <NEW_LINE> <INDENT> sub = LazySequence(self) <NEW_LINE> sub._base_range = self._base_range[index] <NEW_LINE> return sub <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ca = self._weakref_cache <NEW_LINE> item = ca[index] if index in ca else None <NEW_LINE> if item is None: <NEW_LINE> <INDENT> item = self._apply_maps(self._base_seq[self._base_range[index]]) <NEW_LINE> if hasattr(item, '__weakref__'): <NEW_LINE> <INDENT> self._weakref_cache[index] = item <NEW_LINE> self._ref_lru.append(item) <NEW_LINE> <DEDENT> <DEDENT> return item <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def base_sequence(self): <NEW_LINE> <INDENT> return self._base_seq <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def set_cache_size(cls, maxlen): <NEW_LINE> <INDENT> cls._ref_lru = deque(cls._weakref_lru, maxlen)
A Sequence that lazily calculates values when needed based on an underlying Sequence of values and a map function. LazySequences can be composed, sliced, copied, and they maintain a cache of both recently used values and all other values that have not yet been garbage collected.
62599055cb5e8a47e493cc1e
class Migrate(APIView): <NEW_LINE> <INDENT> def valid_iaas(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def valid_container(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get(self, request, container_id, to_iaas_id, format=None): <NEW_LINE> <INDENT> tasks.lxc_migration.delay(container_id, to_iaas_id) <NEW_LINE> return Response({"container": container_id, "to_iaas": to_iaas_id})
To be determined later
62599055009cb60464d02a67
class TestOptions(dict): <NEW_LINE> <INDENT> def __init__(self, indict=None, attribute=None): <NEW_LINE> <INDENT> if indict is None: <NEW_LINE> <INDENT> indict = {} <NEW_LINE> <DEDENT> self.attribute = attribute <NEW_LINE> dict.__init__(self, indict) <NEW_LINE> self.__initialised = True <NEW_LINE> <DEDENT> def __getattr__(self, item): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.__getitem__(item) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise AttributeError(item) <NEW_LINE> <DEDENT> <DEDENT> def __setattr__(self, item, value): <NEW_LINE> <INDENT> if not self.__dict__.has_key('_TestOptions__initialised'): <NEW_LINE> <INDENT> return dict.__setattr__(self, item, value) <NEW_LINE> <DEDENT> elif item in self: <NEW_LINE> <INDENT> dict.__setattr__(self, item, value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__setitem__(item, value)
Options for testing purposes. http://code.activestate.com/recipes/389916-example-setattr-getattr-overloading/
62599055adb09d7d5dc0ba98
class DocumentationError(ProjexError): <NEW_LINE> <INDENT> pass
Thrown during the docgen process.
6259905507f4c71912bb0969
class StudentRepo(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.__lst = [] <NEW_LINE> <DEDENT> def getAll(self): <NEW_LINE> <INDENT> return self.__lst <NEW_LINE> <DEDENT> def store(self, stud): <NEW_LINE> <INDENT> if stud in self.__lst: <NEW_LINE> <INDENT> raise ValueError('Studentul exista deja') <NEW_LINE> <DEDENT> self.__lst.append(stud) <NEW_LINE> <DEDENT> def remove(self, ID): <NEW_LINE> <INDENT> i = 0; <NEW_LINE> for i in range(0, len(self.__lst)): <NEW_LINE> <INDENT> if self.__lst[i].getId() == ID: <NEW_LINE> <INDENT> self.__lst.pop(i) <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> raise ValueError("Nu exista studentul") <NEW_LINE> <DEDENT> def find(self, ID): <NEW_LINE> <INDENT> for stud in self.__lst: <NEW_LINE> <INDENT> if stud.getId() == ID: <NEW_LINE> <INDENT> return stud <NEW_LINE> <DEDENT> <DEDENT> raise ValueError('Student inexistent')
Repository pentru student In aceasta clasa se stocheaza obiecte de tip Student
62599055a219f33f346c7d33
class Fedora19GenericJenkinsSlave( FedoraGenericJenkinsSlave, GenericFedora19Box ): <NEW_LINE> <INDENT> pass
Generic Jenkins slave for Fedora 19
625990554428ac0f6e659a68
class PadInvalidId(PadException): <NEW_LINE> <INDENT> pass
The given ``pad_id`` is invalid
62599055d486a94d0ba2d4f7
class Cnameframe(Templated): <NEW_LINE> <INDENT> def __init__(self, original_path, subreddit, sub_domain): <NEW_LINE> <INDENT> Templated.__init__(self, original_path=original_path) <NEW_LINE> if sub_domain and subreddit and original_path: <NEW_LINE> <INDENT> self.title = "%s - %s" % (subreddit.title, sub_domain) <NEW_LINE> u = UrlParser(subreddit.path + original_path) <NEW_LINE> u.hostname = get_domain(cname = False, subreddit = False) <NEW_LINE> u.update_query(**request.GET.copy()) <NEW_LINE> u.put_in_frame() <NEW_LINE> self.frame_target = u.unparse() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.title = "" <NEW_LINE> self.frame_target = None
The frame page.
62599055004d5f362081fa84
class WriterLineProtocol(WriterBase): <NEW_LINE> <INDENT> def __init__(self, handle): <NEW_LINE> <INDENT> super().__init__("InfluxDB", handle) <NEW_LINE> <DEDENT> def write(self, newline=True, **kwargs): <NEW_LINE> <INDENT> fields = kwargs.pop('fields', {}) <NEW_LINE> for field in ('unit', 'item', 'event', 'comment', 'uuid'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fields[field] = kwargs[field] <NEW_LINE> kwargs.pop(field) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> kwargs['fields'] = fields <NEW_LINE> try: <NEW_LINE> <INDENT> timestamp = kwargs['timestamp'] <NEW_LINE> if isinstance(timestamp, datetime.datetime): <NEW_LINE> <INDENT> kwargs['timestamp'] = ( "{}us" .format(int(timestamp.timestamp() * 1e6))) <NEW_LINE> <DEDENT> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> super().write(newline=newline, **kwargs) <NEW_LINE> <DEDENT> def format(self, **kwargs): <NEW_LINE> <INDENT> collection = kwargs.pop('collection', 'collection?') <NEW_LINE> tags = kwargs.pop('tags', {}) <NEW_LINE> fields = kwargs.pop('fields', {}) <NEW_LINE> timestamp = kwargs.pop('timestamp', None) <NEW_LINE> tags.update(kwargs) <NEW_LINE> return ( "{collection}{tags}{fields}{timestamp}" .format( collection=collection, tags=("" if not tags else ",{}" .format(format_dict(tags, tag=True))), fields=("" if not fields else " {}" .format(format_dict(fields))), timestamp=(" {}".format(timestamp) if timestamp else "")))
Write InfluxDB line protocol format log lines. Note: the tags and fields' keys and values must not contain spaces. If values have a space then the values need quoting. This function does not do that. '{collection},{tags} {fields} {timestamp}' Note that 'collection' here, is a 'measurement' in InfluxDB terms.
625990552ae34c7f260ac616
class PreviewPipeline: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.lookupTable = vtk.vtkLookupTable() <NEW_LINE> self.lookupTable.SetRampToLinear() <NEW_LINE> self.lookupTable.SetNumberOfTableValues(2) <NEW_LINE> self.lookupTable.SetTableRange(0, 1) <NEW_LINE> self.lookupTable.SetTableValue(0, 0, 0, 0, 0) <NEW_LINE> self.colorMapper = vtk.vtkImageMapToRGBA() <NEW_LINE> self.colorMapper.SetOutputFormatToRGBA() <NEW_LINE> self.colorMapper.SetLookupTable(self.lookupTable) <NEW_LINE> self.thresholdFilter = vtk.vtkImageThreshold() <NEW_LINE> self.thresholdFilter.SetInValue(1) <NEW_LINE> self.thresholdFilter.SetOutValue(0) <NEW_LINE> self.thresholdFilter.SetOutputScalarTypeToUnsignedChar() <NEW_LINE> self.mapper = vtk.vtkImageMapper() <NEW_LINE> self.dummyImage = vtk.vtkImageData() <NEW_LINE> self.dummyImage.AllocateScalars(vtk.VTK_UNSIGNED_INT, 1) <NEW_LINE> self.mapper.SetInputData(self.dummyImage) <NEW_LINE> self.actor = vtk.vtkActor2D() <NEW_LINE> self.actor.VisibilityOff() <NEW_LINE> self.actor.SetMapper(self.mapper) <NEW_LINE> self.mapper.SetColorWindow(255) <NEW_LINE> self.mapper.SetColorLevel(128) <NEW_LINE> self.colorMapper.SetInputConnection(self.thresholdFilter.GetOutputPort()) <NEW_LINE> self.mapper.SetInputConnection(self.colorMapper.GetOutputPort())
Visualization objects and pipeline for each slice view for threshold preview
62599055d6c5a102081e364d
class ResearchExperimentDescriptionBaseSerializer(ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = ResearchExperimentDescription <NEW_LINE> fields = [ 'id', 'experimentdescription', ]
Base serializer for DRY implementation.
62599055d7e4931a7ef3d5ae
class Registro0000(Registro): <NEW_LINE> <INDENT> campos = [ CampoFixo(1, 'REG', '0000'), CampoFixo(2, 'NOME_ESC', 'LECF'), CampoFixo(3, 'COD_VER', '0003'), CampoCNPJ(4, 'CNPJ', obrigatorio=True), CampoAlfanumerico(5, 'NOME', obrigatorio=True), CampoRegex(6, 'IND_SIT_INI_PER', obrigatorio=True, regex='[0-4]'), CampoRegex(7, 'SIT_ESPECIAL', obrigatorio=True, regex='[0-9]'), CampoNumerico(8, 'PAT_REMAN_CIS', precisao=2, minimo=Decimal(0), maximo=Decimal(100)), CampoData(9, 'DT_SIT_ESP'), CampoData(10, 'DT_INI', obrigatorio=True), CampoData(11, 'DT_FIN', obrigatorio=True), CampoRegex(12, 'RETIFICADORA', obrigatorio=True, regex='[SN]'), CampoAlfanumerico(13, 'NUM_REC', tamanho=41), CampoRegex(14, 'TIP_ECF', obrigatorio=True, regex='[0-2]'), CampoAlfanumerico(15, 'COD_SCP', tamanho=14) ]
Abertura do Arquivo Digital e Identificação da Pessoa Jurídica >>> r = Registro0000() >>> r.REG '0000' >>> r.NOME_ESC 'LECF' >>> line='|0000|LECF|0003|11111111000191|EMPRESA TESTE|0|0|||01012014|31122014|N||0||' >>> r = Registro0000(line) >>> r.as_line() '|0000|LECF|0003|11111111000191|EMPRESA TESTE|0|0|||01012014|31122014|N||0||' >>> r.REG '0000' >>> r.NOME_ESC 'LECF' >>> r.COD_VER '0003' >>> r.CNPJ '11111111000191' >>> r.NOME 'EMPRESA TESTE' >>> r.DT_INI datetime.date(2014, 1, 1) >>> r.NOME = 'EMPRESA DEMO' >>> r.NOME 'EMPRESA DEMO'
6259905576d4e153a661dd13
class PyWebkitServer(PythonPackage): <NEW_LINE> <INDENT> homepage = "https://github.com/niklasb/webkit-server" <NEW_LINE> url = "https://pypi.io/packages/source/w/webkit-server/webkit-server-1.0.tar.gz" <NEW_LINE> version('develop', git="https://github.com/niklasb/webkit-server", branch="master") <NEW_LINE> version('1.0', '8463245c2b4f0264d934c0ae20bd4654')
a Webkit-based, headless web client
625990558da39b475be0471b
class Resetcog: <NEW_LINE> <INDENT> def __init__(self, bot): <NEW_LINE> <INDENT> self.bot = bot <NEW_LINE> <DEDENT> @commands.command() <NEW_LINE> async def reset(self): <NEW_LINE> <INDENT> _3AM = datetime.time(hour=3) <NEW_LINE> _FRI = 4 <NEW_LINE> def next_friday_3am(now): <NEW_LINE> <INDENT> now += datetime.timedelta(days=7) <NEW_LINE> if now.time() < _3AM: <NEW_LINE> <INDENT> now = now.combine(now.date(),_3AM) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> now = now.combine(now.date(),_3AM) + datetime.timedelta(days=1) <NEW_LINE> return now + datetime.timedelta((_FRI - now.weekday()) % 7) <NEW_LINE> <DEDENT> <DEDENT> if __name__ == '__main__': <NEW_LINE> <INDENT> start = datetime.datetime.now() <NEW_LINE> for i in xrange(7*24*60*60): <NEW_LINE> <INDENT> now = start + datetime.timedelta(seconds=i) <NEW_LINE> then = next_friday_3am(now) <NEW_LINE> assert datetime.timedelta(days=7) < then - now <= datetime.timedelta(days=14) <NEW_LINE> assert then.weekday() == _FRI <NEW_LINE> assert then.time() == _3AM <NEW_LINE> await self.bot.say('Time until server reset - ' + i)
Responds with the time until the next server reset.
62599055baa26c4b54d507d3
class StructCombinedInputOutputBufferType(StructInputOutputBufferType): <NEW_LINE> <INDENT> def passOutput(self, name): <NEW_LINE> <INDENT> return "(%s *)memcpy((char *)%s__out__, (char *)%s__in__, %s)" % (self.type, name, name, self.size)
Like structure buffer -- but same parameter is input and output.
6259905538b623060ffaa2e7
class PathTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> assert not os.system("tar xzf testfiles.tar.gz > /dev/null 2>&1") <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> assert not os.system("rm -rf testfiles tempdir temp2.tar") <NEW_LINE> <DEDENT> def test_deltree(self): <NEW_LINE> <INDENT> assert not os.system("rm -rf testfiles/output") <NEW_LINE> assert not os.system("cp -pR testfiles/deltree testfiles/output") <NEW_LINE> p = Path("testfiles/output") <NEW_LINE> assert p.isdir() <NEW_LINE> p.deltree() <NEW_LINE> assert not p.type, p.type <NEW_LINE> <DEDENT> def test_quote(self): <NEW_LINE> <INDENT> p = Path("hello") <NEW_LINE> assert p.quote() == '"hello"' <NEW_LINE> assert p.quote("\\") == '"\\\\"', p.quote("\\") <NEW_LINE> assert p.quote("$HELLO") == '"\\$HELLO"' <NEW_LINE> <DEDENT> def test_unquote(self): <NEW_LINE> <INDENT> p = Path("foo") <NEW_LINE> def t(s): <NEW_LINE> <INDENT> quoted_version = p.quote(s) <NEW_LINE> unquoted = p.unquote(quoted_version) <NEW_LINE> assert unquoted == s, (unquoted, s) <NEW_LINE> <DEDENT> t("\\") <NEW_LINE> t("$HELLO") <NEW_LINE> t(" aoe aoe \\ \n`") <NEW_LINE> <DEDENT> def test_canonical(self): <NEW_LINE> <INDENT> c = Path(".").get_canonical() <NEW_LINE> assert c == ".", c <NEW_LINE> c = Path("//foo/bar/./").get_canonical() <NEW_LINE> assert c == "/foo/bar", c <NEW_LINE> <DEDENT> def test_compare_verbose(self): <NEW_LINE> <INDENT> vft = Path("testfiles/various_file_types") <NEW_LINE> assert vft.compare_verbose(vft) <NEW_LINE> reg_file = vft.append("regular_file") <NEW_LINE> assert not vft.compare_verbose(reg_file) <NEW_LINE> assert reg_file.compare_verbose(reg_file) <NEW_LINE> file2 = vft.append("executable") <NEW_LINE> assert not file2.compare_verbose(reg_file) <NEW_LINE> assert file2.compare_verbose(file2)
Test basic path functions
6259905515baa723494634c2
class le(ColumnOperator): <NEW_LINE> <INDENT> def compare(self, value): <NEW_LINE> <INDENT> return self.column <= value
Return ``<=`` filter function using ORM column field.
6259905523849d37ff8525f4
class FeatureSupportRequest(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'feature_type': {'required': True}, } <NEW_LINE> _attribute_map = { 'feature_type': {'key': 'featureType', 'type': 'str'}, } <NEW_LINE> _subtype_map = { 'feature_type': {'AzureBackupGoals': 'AzureBackupGoalFeatureSupportRequest', 'AzureVMResourceBackup': 'AzureVMResourceFeatureSupportRequest'} } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(FeatureSupportRequest, self).__init__(**kwargs) <NEW_LINE> self.feature_type = None
Base class for feature request. You probably want to use the sub-classes and not this class directly. Known sub-classes are: AzureBackupGoalFeatureSupportRequest, AzureVMResourceFeatureSupportRequest. All required parameters must be populated in order to send to Azure. :ivar feature_type: Required. backup support feature type.Constant filled by server. :vartype feature_type: str
6259905530dc7b76659a0d17
class PageBaseForm(Form): <NEW_LINE> <INDENT> title = StringField( label=_("Title"), validators=[validators.InputRequired()], render_kw={'autofocus': ''} )
Defines the base form for all pages.
62599055435de62698e9d333
class Collectible(object): <NEW_LINE> <INDENT> def __init__(self, logf): <NEW_LINE> <INDENT> self.logf = logf <NEW_LINE> <DEDENT> def readline(self, logdir): <NEW_LINE> <INDENT> path = os.path.join(logdir, self.logf) <NEW_LINE> if os.path.exists(path): <NEW_LINE> <INDENT> return genio.read_one_line(path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ""
Abstract class for representing collectibles by sysinfo.
625990558da39b475be0471c
class FacultyEntityAutocompleteView(PermissionRequiredMixin, autocomplete.Select2QuerySetView): <NEW_LINE> <INDENT> login_url = 'access_denied' <NEW_LINE> permission_required = 'partnership.can_access_partnerships' <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> qs = ( EntityProxy.objects .only_valid() .with_title() .with_acronym_path() .with_path_as_string() .filter(organization__type=MAIN) .order_by('path_as_string') ) <NEW_LINE> if self.q: <NEW_LINE> <INDENT> qs = qs.filter( Q(path_as_string__icontains=self.q) | Q(title__icontains=self.q) ) <NEW_LINE> <DEDENT> return qs.distinct() <NEW_LINE> <DEDENT> def get_result_label(self, result): <NEW_LINE> <INDENT> parts = result.acronym_path <NEW_LINE> path = parts[1:] if len(parts) > 1 else parts <NEW_LINE> return '{} - {}'.format(' / '.join(path), result.title)
Autocomplete for entities on UCLManagementEntity form
625990552ae34c7f260ac617
class OwnerWriteableMapping(MAP): <NEW_LINE> <INDENT> def __init__( self, dict_: Dict[str, Any] = None, parent: "OwnerWriteableMapping" = None ): <NEW_LINE> <INDENT> super().__init__(dict_, parent) <NEW_LINE> <DEDENT> def _find_owner(self) -> (contract.Contracted, int): <NEW_LINE> <INDENT> for frame in stack_frames(3): <NEW_LINE> <INDENT> if isinstance(frame.f_locals.get("self"), contract.Contracted): <NEW_LINE> <INDENT> contracted = frame.f_locals["self"] <NEW_LINE> log.debug(f"Found contract '{contracted.__name__}'") <NEW_LINE> break <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> lineno = frame.f_lineno <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> contracted = None <NEW_LINE> lineno = -1 <NEW_LINE> <DEDENT> return contracted, lineno <NEW_LINE> <DEDENT> def _set(self, k: str, v: Any): <NEW_LINE> <INDENT> owner, lineno = self._find_owner() <NEW_LINE> cur = self._store.get(k) <NEW_LINE> if cur is None or cur.owner is owner: <NEW_LINE> <INDENT> if isinstance(v, abc.Mapping): <NEW_LINE> <INDENT> v = self.__class__(dict_=v, parent=self) <NEW_LINE> <DEDENT> elif isinstance(v, Iterable) and not isinstance( v, (tuple, str, bytes, UninitializedValue) ): <NEW_LINE> <INDENT> v = tuple(v) <NEW_LINE> <DEDENT> super()._set(k, WriteLockInfo(v, owner, lineno)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> file = inspect.getsourcefile(cur.owner.func) <NEW_LINE> raise WriteLockError( f"'{k}' was previously assigned by '{cur.owner.__name__}' ({file}:{cur.lineno})" ) <NEW_LINE> <DEDENT> <DEDENT> def _get(self, k: str, create: bool = False) -> Any: <NEW_LINE> <INDENT> v = super()._get(k, create) <NEW_LINE> if not isinstance(v, UninitializedValue): <NEW_LINE> <INDENT> v = v.val <NEW_LINE> <DEDENT> return v <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return str(self._dict()) <NEW_LINE> <DEDENT> def _dict(self): <NEW_LINE> <INDENT> vals = {} <NEW_LINE> for k, v in self._store.items(): <NEW_LINE> <INDENT> if isinstance(v.val, self.__class__): <NEW_LINE> <INDENT> vals[k] = v.val._dict() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> vals[k] = v.val <NEW_LINE> <DEDENT> <DEDENT> return vals
A MAP variant that is write-locked to the first Contracted function that writes to a given key (becoming the owner). Attempts to write to that key from other functions will receive a WriteLockError showing the owning Contracted function.
625990554e4d562566373937
class UserRegistrationForm(UserCreationForm): <NEW_LINE> <INDENT> password1 = forms.CharField( label="Password", widget=forms.PasswordInput) <NEW_LINE> password2 = forms.CharField( label="Password Confirmation", widget=forms.PasswordInput) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = User <NEW_LINE> fields = ['email', 'username', 'password1', 'password2'] <NEW_LINE> <DEDENT> def clean_email(self): <NEW_LINE> <INDENT> email = self.cleaned_data.get('email') <NEW_LINE> username = self.cleaned_data.get('username') <NEW_LINE> if User.objects.filter(email=email).exclude(username=username): <NEW_LINE> <INDENT> raise forms.ValidationError(u'Email address must be unique') <NEW_LINE> <DEDENT> return email <NEW_LINE> <DEDENT> def clean_password2(self): <NEW_LINE> <INDENT> password1 = self.cleaned_data.get('password1') <NEW_LINE> password2 = self.cleaned_data.get('password2') <NEW_LINE> if not password1 or not password2: <NEW_LINE> <INDENT> raise ValidationError("Please confirm your password") <NEW_LINE> <DEDENT> if password1 != password2: <NEW_LINE> <INDENT> raise ValidationError("Passwords must match") <NEW_LINE> <DEDENT> return password2
Form to be used to register a new user
6259905576e4537e8c3f0abc
class PinData(BaseModel): <NEW_LINE> <INDENT> ecu_name = ForeignKeyField(EcuType, backref="ecu") <NEW_LINE> ecu_ref_number = CharField() <NEW_LINE> ecu_db_number = IntegerField() <NEW_LINE> pin_reading_msgpack = BlobField()
PIN DATA MODEL CLASS
625990557cff6e4e811b6f72