code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class ExtendedInterpolationConfig(Config): <NEW_LINE> <INDENT> def _create_config_parser(self): <NEW_LINE> <INDENT> inter = configparser.ExtendedInterpolation() <NEW_LINE> return configparser.ConfigParser( defaults=self.create_defaults, interpolation=inter)
Configuration class extends using advanced interpolation with ``configparser.ExtendedInterpolation``.
62598fc73346ee7daa3377e2
class OrbitPointTransition(ParamTransition): <NEW_LINE> <INDENT> command_attributes = {'type': 'ORBPOINT'} <NEW_LINE> state_keys = ['orbit_point'] <NEW_LINE> transition_key = 'orbit_point' <NEW_LINE> cmd_param_key = 'event_type'
Orbit point state based on backstop ephemeris entries
62598fc7283ffb24f3cf3bba
class FontAlphabetsDataset(Dataset): <NEW_LINE> <INDENT> def __init__(self, folder_path,info_path = None,transform=None,custom_path=None): <NEW_LINE> <INDENT> self.root_dir = folder_path <NEW_LINE> self.transform = transform <NEW_LINE> self.im_width = 30 <NEW_LINE> self.im_height = 30 <NEW_LINE> path_pattern = '/*/single_alphabet/*.png' if custom_path is None else custom_path <NEW_LINE> self.im_paths = glob.glob(folder_path+path_pattern) <NEW_LINE> print ("Number of files:",len(self.im_paths)) <NEW_LINE> if custom_path is None: <NEW_LINE> <INDENT> self.names = [re.findall('/(.*)/single_alphabet',fname )[0] for fname in self.im_paths] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.names = [os.path.splitext(os.path.basename(fname))[0] for fname in self.im_paths] <NEW_LINE> <DEDENT> self.set_size() <NEW_LINE> <DEDENT> def set_size(self): <NEW_LINE> <INDENT> image = io.imread(self.im_paths[0],as_grey=True) <NEW_LINE> self.im_height,self.im_width = image.shape <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.im_paths) <NEW_LINE> <DEDENT> def __getitem__(self, idx): <NEW_LINE> <INDENT> image = io.imread(self.im_paths[idx],as_grey=True) <NEW_LINE> sample = {'image': image, 'name':self.names[idx], } <NEW_LINE> if self.transform: <NEW_LINE> <INDENT> sample = self.transform(sample) <NEW_LINE> <DEDENT> return sample
Create a Dataset class from from folder path.
62598fc7ad47b63b2c5a7b8d
class TruncateParams(BaseModel): <NEW_LINE> <INDENT> before: datetime <NEW_LINE> creator_name: Optional[str] <NEW_LINE> execution_id: Optional[str]
Parameters passed to DELETE /audit endpoint.
62598fc8ff9c53063f51a982
class ScanSceneHook(Hook): <NEW_LINE> <INDENT> def execute(self, **kwargs): <NEW_LINE> <INDENT> items = [] <NEW_LINE> scene_name = cmds.file(query=True, sn=True) <NEW_LINE> if not scene_name: <NEW_LINE> <INDENT> raise TankError("Please Save your file before Publishing") <NEW_LINE> <DEDENT> scene_path = os.path.abspath(scene_name) <NEW_LINE> scene_basename = os.path.basename(scene_path) <NEW_LINE> items.append({"type": "work_file", "name": scene_basename}) <NEW_LINE> self._add_render_files(scene_path, items) <NEW_LINE> return items <NEW_LINE> <DEDENT> def _add_render_files(self, path, items): <NEW_LINE> <INDENT> tk = tank.sgtk_from_path(path) <NEW_LINE> template = tk.template_from_path(path) <NEW_LINE> ctx = tk.context_from_path(path) <NEW_LINE> fields = template.get_fields(path) <NEW_LINE> version = fields["version"] <NEW_LINE> name = fields["name"] <NEW_LINE> if ctx.entity["type"] == "Asset": <NEW_LINE> <INDENT> type = fields["sg_asset_type"] <NEW_LINE> asset = fields["Asset"] <NEW_LINE> maya_asset_render = tk.templates["maya_asset_render"] <NEW_LINE> wip_renders = tk.paths_from_template(maya_asset_render, {"sg_asset_type": type, "Asset": asset, "name": name, "version": version}) <NEW_LINE> <DEDENT> elif ctx.entity["type"] == "Shot": <NEW_LINE> <INDENT> spot = fields["Sequence"] <NEW_LINE> shot = fields["Shot"] <NEW_LINE> maya_shot_render = tk.templates["maya_shot_render"] <NEW_LINE> wip_renders = tk.paths_from_template(maya_shot_render, {"Sequence": spot, "Shot": shot, "name": name, "version": version}) <NEW_LINE> <DEDENT> if wip_renders: <NEW_LINE> <INDENT> wip_render_path = wip_renders[0] <NEW_LINE> render_files = [name for name in os.listdir(wip_render_path)] <NEW_LINE> baseFilename = "" <NEW_LINE> for filename in render_files: <NEW_LINE> <INDENT> newBaseFilename = filename.split('.')[0] <NEW_LINE> if baseFilename != newBaseFilename: <NEW_LINE> <INDENT> items.append({"name": newBaseFilename, "type": "render_file", "description":filename, "other_params": {"source_folder": wip_render_path, "scene_path": path}}) <NEW_LINE> <DEDENT> baseFilename = newBaseFilename
Hook to scan scene for items to publish
62598fc850812a4eaa620d7f
class ChannelAwareMixin(object): <NEW_LINE> <INDENT> def get_channel(self): <NEW_LINE> <INDENT> memokey = '_cache_get_channel' <NEW_LINE> if not hasattr(self, memokey): <NEW_LINE> <INDENT> if self.kwargs.get('channel_slug', None) is not None: <NEW_LINE> <INDENT> channel = get_object_or_404(Channel, slug=self.kwargs['channel_slug']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> channel = None <NEW_LINE> <DEDENT> setattr(self, memokey, channel) <NEW_LINE> <DEDENT> return getattr(self, memokey)
Mixin to make views aware of channels with a ``get_channel`` method
62598fc89f28863672818a17
class ChannelDescription(db.JsonNode): <NEW_LINE> <INDENT> _discriminator_ = CHANNEL_DESCRIPTION
This ORM class represents channel descriptions.
62598fc8d486a94d0ba2c308
class NaiveBayes(Classifier): <NEW_LINE> <INDENT> def __init__(self, documents, k=1): <NEW_LINE> <INDENT> Classifier.__init__(self, documents) <NEW_LINE> self.vocabulary = self.get_vocabulary(documents) <NEW_LINE> self.class_vocabularies = self.get_class_vocabularies(documents) <NEW_LINE> self.class_word_counts = self.get_class_word_counts(self.class_vocabularies) <NEW_LINE> self.priors = self.get_priors() <NEW_LINE> self.k = k <NEW_LINE> <DEDENT> def get_vocabulary(self, documents): <NEW_LINE> <INDENT> vocabulary = {} <NEW_LINE> for document in documents: <NEW_LINE> <INDENT> for word in document.bag_of_words: <NEW_LINE> <INDENT> if word not in vocabulary: <NEW_LINE> <INDENT> vocabulary[word] = 0 <NEW_LINE> <DEDENT> vocabulary[word] += 1 <NEW_LINE> <DEDENT> <DEDENT> return vocabulary <NEW_LINE> <DEDENT> def get_class_vocabularies(self, documents): <NEW_LINE> <INDENT> class_vocabularies = {} <NEW_LINE> for document in documents: <NEW_LINE> <INDENT> c = document.c <NEW_LINE> if c not in class_vocabularies: <NEW_LINE> <INDENT> class_vocabularies[c] = {} <NEW_LINE> <DEDENT> for word in document.bag_of_words: <NEW_LINE> <INDENT> if word not in class_vocabularies[c]: <NEW_LINE> <INDENT> class_vocabularies[c][word] = 0 <NEW_LINE> <DEDENT> class_vocabularies[c][word] += 1 <NEW_LINE> <DEDENT> <DEDENT> return class_vocabularies <NEW_LINE> <DEDENT> def get_class_word_counts(self, class_vocabularies): <NEW_LINE> <INDENT> class_word_counts = {} <NEW_LINE> for c in class_vocabularies: <NEW_LINE> <INDENT> class_word_counts[c] = 0 <NEW_LINE> for word in class_vocabularies[c]: <NEW_LINE> <INDENT> class_word_counts[c] += class_vocabularies[c][word] <NEW_LINE> <DEDENT> <DEDENT> return class_word_counts <NEW_LINE> <DEDENT> def get_priors(self): <NEW_LINE> <INDENT> priors = {} <NEW_LINE> for c in self.classes: <NEW_LINE> <INDENT> count = 0 <NEW_LINE> total = 0 <NEW_LINE> for document in self.documents: <NEW_LINE> <INDENT> k = 1 <NEW_LINE> if document.c == c: <NEW_LINE> <INDENT> count += k <NEW_LINE> <DEDENT> total += k <NEW_LINE> <DEDENT> priors[c] = log(count / total) <NEW_LINE> <DEDENT> return priors <NEW_LINE> <DEDENT> def get_likelihood(self, word, c): <NEW_LINE> <INDENT> count = self.k <NEW_LINE> if word in self.class_vocabularies[c]: <NEW_LINE> <INDENT> count += self.class_vocabularies[c][word] <NEW_LINE> <DEDENT> total = self.class_word_counts[c] + len(self.vocabulary) * self.k <NEW_LINE> result = log(count / total) <NEW_LINE> return result <NEW_LINE> <DEDENT> def get_prediction(self, testing_document): <NEW_LINE> <INDENT> best_class = None <NEW_LINE> best_class_posterior = None <NEW_LINE> for c in self.classes: <NEW_LINE> <INDENT> prior = self.priors[c] <NEW_LINE> likelihood = 0 <NEW_LINE> for word in testing_document.bag_of_words: <NEW_LINE> <INDENT> word_likelihood = self.get_likelihood(word, c) <NEW_LINE> likelihood += word_likelihood <NEW_LINE> <DEDENT> if best_class is None or prior + likelihood > best_class_posterior: <NEW_LINE> <INDENT> best_class_posterior = prior + likelihood <NEW_LINE> best_class = c <NEW_LINE> <DEDENT> <DEDENT> return best_class
A Naive Bayes classifier; given the documents for training, it generates lists and dictionaries for probability estimation.
62598fc8f9cc0f698b1c546d
class RegistrationDetail(APIView): <NEW_LINE> <INDENT> def get_object(self, pk, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> obj=Registration.objects.get(pk=pk) <NEW_LINE> obj.inject_request(request) <NEW_LINE> return obj <NEW_LINE> <DEDENT> except Registration.DoesNotExist: <NEW_LINE> <INDENT> raise Http404 <NEW_LINE> <DEDENT> <DEDENT> def get(self, request, pk, format=None): <NEW_LINE> <INDENT> registration = self.get_object(pk,request) <NEW_LINE> serializer = RegistrationSerializer(registration,context={'request':request}) <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> def put(self, request, pk, format=None): <NEW_LINE> <INDENT> registration = self.get_object(pk,request) <NEW_LINE> serializer = RegistrationSerializer(registration, context={'request':request}, data=request.data) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> serializer.save() <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> def delete(self, request, pk, format=None): <NEW_LINE> <INDENT> registration = self.get_object(pk,request) <NEW_LINE> registration.delete() <NEW_LINE> return Response(status=status.HTTP_204_NO_CONTENT)
Retrieve, update? or delete??? a registration instance
62598fc8adb09d7d5dc0a8b1
class CircularArray(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.arr = [] <NEW_LINE> <DEDENT> def add_item(self, item): <NEW_LINE> <INDENT> self.arr.append(item) <NEW_LINE> <DEDENT> def get_by_index(self, index): <NEW_LINE> <INDENT> if index < len(self.arr): <NEW_LINE> <INDENT> return self.arr[index] <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def rotate(self, increment): <NEW_LINE> <INDENT> rotated = [] <NEW_LINE> rotate_by = abs(increment) % len(self.arr) <NEW_LINE> if increment > 0: <NEW_LINE> <INDENT> rotated.extend(self.arr[rotate_by:]) <NEW_LINE> rotated.extend(self.arr[:rotate_by]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rotated.extend(self.arr[-rotate_by:]) <NEW_LINE> rotated.extend(self.arr[:-rotate_by]) <NEW_LINE> <DEDENT> self.arr = rotated <NEW_LINE> <DEDENT> def print_array(self): <NEW_LINE> <INDENT> for item in self.arr: <NEW_LINE> <INDENT> print(item)
An array that may be rotated, and items retrieved by index
62598fc8be7bc26dc9251ff6
class ESRILayer(object): <NEW_LINE> <INDENT> def __init__(self, baseurl, **kwargs): <NEW_LINE> <INDENT> self.__dict__.update({"_" + k: v for k, v in diter(kwargs)}) <NEW_LINE> if hasattr(self, "_fields"): <NEW_LINE> <INDENT> self.variables = pd.DataFrame(self._fields) <NEW_LINE> <DEDENT> self._baseurl = baseurl + "/" + str(self._id) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return "(ESRILayer) " + self._name <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> <DEDENT> def query(self, raw=False, strict=False, **kwargs): <NEW_LINE> <INDENT> kwargs = {"".join(k.split("_")): v for k, v in diter(kwargs)} <NEW_LINE> self._basequery = copy.deepcopy(_basequery) <NEW_LINE> for k, v in diter(kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._basequery[k] = v <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise KeyError("Option '{k}' not recognized, check parameters") <NEW_LINE> <DEDENT> <DEDENT> qstring = "&".join(["{}={}".format(k, v) for k, v in diter(self._basequery)]) <NEW_LINE> self._last_query = self._baseurl + "/query?" + qstring <NEW_LINE> resp = r.get(self._last_query + "&f=json") <NEW_LINE> resp.raise_for_status() <NEW_LINE> datadict = resp.json() <NEW_LINE> if raw: <NEW_LINE> <INDENT> return datadict <NEW_LINE> <DEDENT> if kwargs.get("returnGeometry", "true") is "false": <NEW_LINE> <INDENT> return pd.DataFrame.from_records( [x["attributes"] for x in datadict["features"]] ) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> features = datadict["features"] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> code, msg = datadict["error"]["code"], datadict["error"]["message"] <NEW_LINE> details = datadict["error"]["details"] <NEW_LINE> if details is []: <NEW_LINE> <INDENT> details = "Mapserver provided no detailed error" <NEW_LINE> <DEDENT> raise KeyError( ( r"Response from API is malformed. You may have " r"submitted too many queries, formatted the request incorrectly, " r"or experienced significant network connectivity issues." r" Check to make sure that your inputs, like placenames, are spelled" r" correctly, and that your geographies match the level at which you" r" intend to query. The original error from the Census is:\n" r"(API ERROR {}:{}({}))".format(code, msg, details) ) ) <NEW_LINE> <DEDENT> todf = [] <NEW_LINE> for i, feature in enumerate(features): <NEW_LINE> <INDENT> locfeat = gpsr.__dict__[datadict["geometryType"]](feature) <NEW_LINE> todf.append(locfeat["properties"]) <NEW_LINE> todf[i].update({"geometry": locfeat["geometry"]}) <NEW_LINE> <DEDENT> df = pd.DataFrame(todf) <NEW_LINE> outdf = gpsr.convert_geometries(df, strict=strict) <NEW_LINE> outdf = GeoDataFrame(outdf) <NEW_LINE> crs = datadict.pop("spatialReference", None) <NEW_LINE> if crs is not None: <NEW_LINE> <INDENT> crs = crs.get("latestWkid", crs.get("wkid")) <NEW_LINE> crs = dict(init="epsg:{}".format(crs)) <NEW_LINE> <DEDENT> outdf.crs = crs <NEW_LINE> return outdf
The fundamental building block to access a single Geography/Layer in an ESRI MapService
62598fc8091ae35668704f5f
class OptionItem: <NEW_LINE> <INDENT> def __init__(self, opt): <NEW_LINE> <INDENT> self.short = opt.get("short") <NEW_LINE> self.long = opt.get("long") <NEW_LINE> self.target = self.long[2:].replace("-", "_") <NEW_LINE> self.help = opt.get("help") <NEW_LINE> self.status = opt.get("status") <NEW_LINE> self.func = opt.get("func") <NEW_LINE> self.action = opt.get("action") <NEW_LINE> self.type = opt.get("type") <NEW_LINE> self.dest = opt.get("dest") <NEW_LINE> self.choices = opt.get("choices") <NEW_LINE> <DEDENT> @property <NEW_LINE> def pargs(self): <NEW_LINE> <INDENT> pargs = [] <NEW_LINE> if self.short is not None: <NEW_LINE> <INDENT> pargs.append(self.short) <NEW_LINE> <DEDENT> if self.long is not None: <NEW_LINE> <INDENT> pargs.append(self.long) <NEW_LINE> <DEDENT> return pargs <NEW_LINE> <DEDENT> @property <NEW_LINE> def kwargs(self): <NEW_LINE> <INDENT> kwargs = {} <NEW_LINE> if self.help is not None: <NEW_LINE> <INDENT> kwargs["help"] = self.help <NEW_LINE> <DEDENT> if self.action is not None: <NEW_LINE> <INDENT> kwargs["action"] = self.action <NEW_LINE> <DEDENT> if self.type is not None: <NEW_LINE> <INDENT> kwargs["type"] = self.type <NEW_LINE> <DEDENT> if self.dest is not None: <NEW_LINE> <INDENT> kwargs["dest"] = self.dest <NEW_LINE> <DEDENT> if self.choices is not None: <NEW_LINE> <INDENT> kwargs["choices"] = self.choices <NEW_LINE> <DEDENT> return kwargs
class to hold module ArgumentParser options data
62598fc8a219f33f346c6b3e
class Grub2(Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin): <NEW_LINE> <INDENT> plugin_name = 'grub2' <NEW_LINE> profiles = ('boot',) <NEW_LINE> packages = ('grub2',) <NEW_LINE> def setup(self): <NEW_LINE> <INDENT> self.add_copy_spec([ "/boot/efi/EFI/*/grub.cfg", "/boot/grub2/grub.cfg", "/boot/grub2/grubenv", "/boot/grub/grub.cfg", "/etc/default/grub", "/etc/grub2.cfg", "/etc/grub.d" ]) <NEW_LINE> self.add_cmd_output("ls -lanR /boot") <NEW_LINE> env = {} <NEW_LINE> env['GRUB_DISABLE_OS_PROBER'] = 'true' <NEW_LINE> self.add_cmd_output("grub2-mkconfig", env=env) <NEW_LINE> <DEDENT> def postproc(self): <NEW_LINE> <INDENT> passwd_exp = r"(password )\s*(\S*)\s*(\S*)" <NEW_LINE> passwd_pbkdf2_exp = r"(password_pbkdf2)\s*(\S*)\s*(\S*)" <NEW_LINE> passwd_sub = r"\1 \2 ********" <NEW_LINE> passwd_pbkdf2_sub = r"\1 \2 grub.pbkdf2.********" <NEW_LINE> self.do_cmd_output_sub( "grub2-mkconfig", passwd_pbkdf2_exp, passwd_pbkdf2_sub ) <NEW_LINE> self.do_cmd_output_sub( "grub2-mkconfig", passwd_exp, passwd_sub ) <NEW_LINE> self.do_path_regex_sub( r".*\/grub\.", passwd_exp, passwd_sub ) <NEW_LINE> self.do_path_regex_sub( r".*\/grub\.", passwd_pbkdf2_exp, passwd_pbkdf2_sub )
GRUB2 bootloader
62598fc860cbc95b06364674
class Eof(Parser): <NEW_LINE> <INDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return "''" <NEW_LINE> <DEDENT> def parse(self, tokens: Tokens) -> Result: <NEW_LINE> <INDENT> if tokens: <NEW_LINE> <INDENT> raise CantParse(self, tokens) <NEW_LINE> <DEDENT> return Result(None, empty=True)
EOF checker.
62598fc8ad47b63b2c5a7b8f
class CaptureDataBase(Capture): <NEW_LINE> <INDENT> def __init__(self, data_name, callback=None): <NEW_LINE> <INDENT> self._data_name = data_name <NEW_LINE> def identity(x): <NEW_LINE> <INDENT> return x <NEW_LINE> <DEDENT> if not callback: <NEW_LINE> <INDENT> callback = identity <NEW_LINE> <DEDENT> routingKey = ("stats-yieldMetricsValue", "stats-yield-data") <NEW_LINE> Capture.__init__(self, routingKey, callback) <NEW_LINE> <DEDENT> @defer.inlineCallbacks <NEW_LINE> def consume(self, routingKey, msg): <NEW_LINE> <INDENT> build_data = msg['build_data'] <NEW_LINE> builder_info = yield self.master.data.get(("builders", build_data['builderid'])) <NEW_LINE> if self._builder_name_matches(builder_info) and self._data_name == msg['data_name']: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ret_val = self._callback(msg['post_data']) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise CaptureCallbackError("CaptureData failed for build %s of builder %s." " Exception generated: %s with message %s" % (build_data['number'], builder_info['name'], type(e).__name__, str(e))) <NEW_LINE> <DEDENT> post_data = ret_val <NEW_LINE> series_name = '%s-%s' % (builder_info['name'], self._data_name) <NEW_LINE> context = self._defaultContext(build_data, builder_info['name']) <NEW_LINE> yield self._store(post_data, series_name, context) <NEW_LINE> <DEDENT> <DEDENT> @abc.abstractmethod <NEW_LINE> def _builder_name_matches(self, builder_info): <NEW_LINE> <INDENT> pass
Base class for CaptureData methods.
62598fc87047854f4633f709
class TestComponentProperty_i(TestComponentProperty_base): <NEW_LINE> <INDENT> def initialize(self): <NEW_LINE> <INDENT> TestComponentProperty_base.initialize(self) <NEW_LINE> <DEDENT> def process(self): <NEW_LINE> <INDENT> self._log.debug("process() example log message") <NEW_LINE> return NOOP
<DESCRIPTION GOES HERE>
62598fc8377c676e912f6f11
@total_ordering <NEW_LINE> class EncryptConfig(object): <NEW_LINE> <INDENT> def __init__(self, encryptMode=None, encryptTarget=None): <NEW_LINE> <INDENT> self._encryptMode = None <NEW_LINE> self._encryptTarget = None <NEW_LINE> self.encryptMode = encryptMode <NEW_LINE> self.encryptTarget = encryptTarget <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "EncryptConfig(%s, %s)" % (self.encryptMode, self.encryptTarget) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.__repr__() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.__cmp__(other) == 0 <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> return self.__cmp__(other) < 0 <NEW_LINE> <DEDENT> def __gt__(self, other): <NEW_LINE> <INDENT> return self.__cmp__(other) > 0 <NEW_LINE> <DEDENT> def __cmp__(self, other): <NEW_LINE> <INDENT> if other is None: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> if self.encryptMode != other.encryptMode: <NEW_LINE> <INDENT> if str(self.encryptMode or "") < str(other.encryptMode or ""): <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> <DEDENT> if self.encryptTarget != other.encryptTarget: <NEW_LINE> <INDENT> if str(self.encryptTarget or "") < str(other.encryptTarget or ""): <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> <DEDENT> return 0 <NEW_LINE> <DEDENT> def _setEncryptMode(self, value): <NEW_LINE> <INDENT> if value is not None: <NEW_LINE> <INDENT> if value not in VALID_ENCRYPT_MODES: <NEW_LINE> <INDENT> raise ValueError("Encrypt mode must be one of %s." % VALID_ENCRYPT_MODES) <NEW_LINE> <DEDENT> <DEDENT> self._encryptMode = value <NEW_LINE> <DEDENT> def _getEncryptMode(self): <NEW_LINE> <INDENT> return self._encryptMode <NEW_LINE> <DEDENT> def _setEncryptTarget(self, value): <NEW_LINE> <INDENT> if value is not None: <NEW_LINE> <INDENT> if len(value) < 1: <NEW_LINE> <INDENT> raise ValueError("Encrypt target must be non-empty string.") <NEW_LINE> <DEDENT> <DEDENT> self._encryptTarget = value <NEW_LINE> <DEDENT> def _getEncryptTarget(self): <NEW_LINE> <INDENT> return self._encryptTarget <NEW_LINE> <DEDENT> encryptMode = property(_getEncryptMode, _setEncryptMode, None, doc="Encrypt mode.") <NEW_LINE> encryptTarget = property(_getEncryptTarget, _setEncryptTarget, None, doc="Encrypt target (i.e. GPG recipient).")
Class representing encrypt configuration. Encrypt configuration is used for encrypting staging directories. The following restrictions exist on data in this class: - The encrypt mode must be one of the values in ``VALID_ENCRYPT_MODES`` - The encrypt target value must be a non-empty string
62598fc897e22403b383b23c
class ReferralCodeCondition(CustomConditionMixin, Condition): <NEW_LINE> <INDENT> _description = "User used referral code." <NEW_LINE> def is_satisfied(self, offer, basket, request=None): <NEW_LINE> <INDENT> if request.user.is_authenticated and request.user.is_referral_code_used: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> referral_code = request.session.get(settings.REFERRAL_SESSION_KEY, None) <NEW_LINE> return referral_code is not None <NEW_LINE> <DEDENT> def check_compatibility(self, offer): <NEW_LINE> <INDENT> if offer.offer_type != ConditionalOffer.SESSION: <NEW_LINE> <INDENT> raise ConditionIncompatible( "Referral code condition could be used only with the session type offer." )
Custom condition, which allows referee (referral code applicant) to qualify for the discount.
62598fc8a8370b77170f0712
@add_start_docstrings( CAMEMBERT_START_DOCSTRING, ) <NEW_LINE> class CamembertForTokenClassification(RobertaForTokenClassification): <NEW_LINE> <INDENT> config_class = CamembertConfig
This class overrides [`RobertaForTokenClassification`]. Please check the superclass for the appropriate documentation alongside usage examples.
62598fc87c178a314d78d7d8
class SensorInfo(object): <NEW_LINE> <INDENT> def __init__(self, name, data_key, units, max_value, min_value, value_modifier): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.data_key = data_key <NEW_LINE> self.units = units <NEW_LINE> self.max = max_value <NEW_LINE> self.min = min_value <NEW_LINE> self.value_modifier = value_modifier
Xiaomi Sensor info
62598fc8091ae35668704f61
class ServiceEnvironmentSet(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.TotalCount = None <NEW_LINE> self.EnvironmentList = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.TotalCount = params.get("TotalCount") <NEW_LINE> if params.get("EnvironmentList") is not None: <NEW_LINE> <INDENT> self.EnvironmentList = [] <NEW_LINE> for item in params.get("EnvironmentList"): <NEW_LINE> <INDENT> obj = Environment() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.EnvironmentList.append(obj)
Details of environments bound to service
62598fc8cc40096d6161a374
class MediaLabelDataStatistics(Document): <NEW_LINE> <INDENT> media_type = StringField(required=False, verbose_name='媒体类型') <NEW_LINE> first_cate = StringField(default='', verbose_name='一级类目') <NEW_LINE> second_cate = StringField(default='', verbose_name='二级类目') <NEW_LINE> number = IntField(required=False, default=0,verbose_name='爬取数量') <NEW_LINE> add_time = DateTimeField( db_field='createtime', default=datetime.datetime.now, verbose_name='创建时间', ) <NEW_LINE> meta = { 'strict': False, 'index_background': True, "collection": "MediaLabelDataStatistics", "indexes": [ "first_cate", "second_cate", 'number', ] } <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return '%s %s %s %s %s' % (self.media_type, self.first_cate, self.second_cate, self.number, self.add_time, )
@summary: 媒体资源库
62598fc860cbc95b06364676
class JAVAC(Compiler): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(JAVAC, self).__init__("javac", "{base}") <NEW_LINE> self.add_args(r"{file}") <NEW_LINE> <DEDENT> def bin_file_name(self, src_filename=""): <NEW_LINE> <INDENT> return substitute("{base}", src_filename)
Javac
62598fc8bf627c535bcb17e2
class LabPlanProperties(LabPlanUpdateProperties): <NEW_LINE> <INDENT> _validation = { 'shared_gallery_id': {'max_length': 2000, 'min_length': 3}, 'linked_lms_instance': {'max_length': 2000, 'min_length': 3}, 'provisioning_state': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'default_connection_profile': {'key': 'defaultConnectionProfile', 'type': 'ConnectionProfile'}, 'default_auto_shutdown_profile': {'key': 'defaultAutoShutdownProfile', 'type': 'AutoShutdownProfile'}, 'default_network_profile': {'key': 'defaultNetworkProfile', 'type': 'LabPlanNetworkProfile'}, 'allowed_regions': {'key': 'allowedRegions', 'type': '[str]'}, 'shared_gallery_id': {'key': 'sharedGalleryId', 'type': 'str'}, 'support_info': {'key': 'supportInfo', 'type': 'SupportInfo'}, 'linked_lms_instance': {'key': 'linkedLmsInstance', 'type': 'str'}, 'provisioning_state': {'key': 'provisioningState', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, default_connection_profile: Optional["ConnectionProfile"] = None, default_auto_shutdown_profile: Optional["AutoShutdownProfile"] = None, default_network_profile: Optional["LabPlanNetworkProfile"] = None, allowed_regions: Optional[List[str]] = None, shared_gallery_id: Optional[str] = None, support_info: Optional["SupportInfo"] = None, linked_lms_instance: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(LabPlanProperties, self).__init__(default_connection_profile=default_connection_profile, default_auto_shutdown_profile=default_auto_shutdown_profile, default_network_profile=default_network_profile, allowed_regions=allowed_regions, shared_gallery_id=shared_gallery_id, support_info=support_info, linked_lms_instance=linked_lms_instance, **kwargs) <NEW_LINE> self.provisioning_state = None
Lab plan resource properties. Variables are only populated by the server, and will be ignored when sending a request. :ivar default_connection_profile: The default lab connection profile. This can be changed on a lab resource and only provides a default profile. :vartype default_connection_profile: ~azure.mgmt.labservices.models.ConnectionProfile :ivar default_auto_shutdown_profile: The default lab shutdown profile. This can be changed on a lab resource and only provides a default profile. :vartype default_auto_shutdown_profile: ~azure.mgmt.labservices.models.AutoShutdownProfile :ivar default_network_profile: The lab plan network profile. To enforce lab network policies they must be defined here and cannot be changed when there are existing labs associated with this lab plan. :vartype default_network_profile: ~azure.mgmt.labservices.models.LabPlanNetworkProfile :ivar allowed_regions: The allowed regions for the lab creator to use when creating labs using this lab plan. :vartype allowed_regions: list[str] :ivar shared_gallery_id: Resource ID of the Shared Image Gallery attached to this lab plan. When saving a lab template virtual machine image it will be persisted in this gallery. Shared images from the gallery can be made available to use when creating new labs. :vartype shared_gallery_id: str :ivar support_info: Support contact information and instructions for users of the lab plan. This information is displayed to lab owners and virtual machine users for all labs in the lab plan. :vartype support_info: ~azure.mgmt.labservices.models.SupportInfo :ivar linked_lms_instance: Base Url of the lms instance this lab plan can link lab rosters against. :vartype linked_lms_instance: str :ivar provisioning_state: Current provisioning state of the lab plan. Possible values include: "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Locked". :vartype provisioning_state: str or ~azure.mgmt.labservices.models.ProvisioningState
62598fc8099cdd3c6367557e
class MachineLearningServicer(BaseServicer): <NEW_LINE> <INDENT> def __init__( self, salary_model, social_ads_model, mall_customers_segmentation_model, campaign_ad_optimization_model, restaurant_review_prediction_model, bank_leaving_prediction_model, cat_or_dog_prediction_model, ): <NEW_LINE> <INDENT> self.__salary_model = salary_model <NEW_LINE> self.__social_ads_model = social_ads_model <NEW_LINE> self.__mall_customers_segmentation_model = mall_customers_segmentation_model <NEW_LINE> self.__campaign_ad_optimization_model = campaign_ad_optimization_model <NEW_LINE> self.__restaurant_review_prediction_model = restaurant_review_prediction_model <NEW_LINE> self.__bank_leaving_prediction_model = bank_leaving_prediction_model <NEW_LINE> self.__cat_or_dog_prediction_model = cat_or_dog_prediction_model <NEW_LINE> <DEDENT> def PredictSalary(self, request, context): <NEW_LINE> <INDENT> predictions = self.__salary_model.predict([[request.years]]) <NEW_LINE> return srv.PredictSalaryResponse(salary = predictions[0]) <NEW_LINE> <DEDENT> def PredictPurchase(self, request, context): <NEW_LINE> <INDENT> predictions = self.__social_ads_model.predict([[request.age, request.salary]]) <NEW_LINE> return srv.PredictPurchaseResponse(purchase = bool(predictions[0])) <NEW_LINE> <DEDENT> def PredictSegment(self, request, context): <NEW_LINE> <INDENT> predictions = self.__mall_customers_segmentation_model.predict([[request.annual_income, request.spending_score]]) <NEW_LINE> return srv.PredictSegmentResponse(segment = predictions[0] + 1) <NEW_LINE> <DEDENT> def GetOptimalCampaignAdOption(self, request, context): <NEW_LINE> <INDENT> option = self.__campaign_ad_optimization_model.optimal_option() <NEW_LINE> return srv.GetOptimalCampaignAdOptionResponse(ad = option + 1) <NEW_LINE> <DEDENT> def PredictReviewOutcome(self, request, context): <NEW_LINE> <INDENT> predictions = self.__restaurant_review_prediction_model.predict([[request.review]]) <NEW_LINE> return srv.PredictReviewOutcomeResponse(liked = bool(predictions[0])) <NEW_LINE> <DEDENT> def PredictCatOrDog(self, request, context): <NEW_LINE> <INDENT> img = preprocess_and_decode(request.img) <NEW_LINE> predictions = self.__cat_or_dog_prediction_model.predict(img, False) <NEW_LINE> return srv.PredictCatOrDogResponse(dog = bool(predictions[0])) <NEW_LINE> <DEDENT> def PredictBankLeaving(self, request, context): <NEW_LINE> <INDENT> predictions = self.__bank_leaving_prediction_model.predict([[ request.credit_score, request.geography, request.gender, request.age, request.tenure, request.balance, request.number_of_products, request.has_credit_card, request.is_active_member, request.estimated_salary, ]]) <NEW_LINE> return srv.PredictBankLeavingResponse(exited = bool(predictions[0]))
Provides methods that implement functionality of machine learning server.
62598fc863b5f9789fe854ae
class DMA_PWMServo (adapter.adapters.DMAAdapter): <NEW_LINE> <INDENT> mandatoryParameters = {'frequency': 50.0, 'rate': 50.0} <NEW_LINE> optionalParametes = {'value.inverse': False, 'millisecond.min': 1.0, 'millisecond.max' : 2.0 } <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> adapter.adapters.DMAAdapter.__init__(self) <NEW_LINE> pass <NEW_LINE> <DEDENT> def _calculateRate(self, v ): <NEW_LINE> <INDENT> if v < 0: <NEW_LINE> <INDENT> v = 0.0 <NEW_LINE> <DEDENT> if v > 100: <NEW_LINE> <INDENT> v = 100.0 <NEW_LINE> <DEDENT> vLow = self.getOptionalParameter('millisecond.min', 1.0 ) <NEW_LINE> vHigh = self.getOptionalParameter('millisecond.max', 2.0 ) <NEW_LINE> inverse = self.getOptionalParameter('value.inverse', 'false' ) <NEW_LINE> inverse = self.isTrue(inverse) <NEW_LINE> try: <NEW_LINE> <INDENT> vvLow = float(vLow) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> vvLow = 1.0 <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> vvHigh = float(vHigh) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> vvHigh = 2.0 <NEW_LINE> <DEDENT> if vvLow < 0.5: <NEW_LINE> <INDENT> vvLow = 0.5 <NEW_LINE> <DEDENT> if vvHigh > 2.5: <NEW_LINE> <INDENT> vvHigh = 2.5 <NEW_LINE> <DEDENT> pRate = ( vvLow + (vvHigh - vvLow) * v / 100.0 ) / 20.0 * 100.0 <NEW_LINE> if debug: <NEW_LINE> <INDENT> print(vLow, vHigh, vvLow, vvHigh, pRate) <NEW_LINE> <DEDENT> if inverse: <NEW_LINE> <INDENT> v = 100 - pRate <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> v = pRate <NEW_LINE> <DEDENT> return v <NEW_LINE> <DEDENT> def rate(self, value): <NEW_LINE> <INDENT> if debug: <NEW_LINE> <INDENT> logger.debug("%s %s %s", self.name, 'value', value) <NEW_LINE> <DEDENT> v = 0.0 <NEW_LINE> try: <NEW_LINE> <INDENT> v = float(value) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> logger.error('{name:s}: invalid value: {value:s}'.format(name=self.name, value=str( value))) <NEW_LINE> return <NEW_LINE> <DEDENT> v = self._calculateRate(v) <NEW_LINE> if self.active: <NEW_LINE> <INDENT> self.set_pwm (self.gpios[0], float(v)) <NEW_LINE> <DEDENT> <DEDENT> def setActive(self, state): <NEW_LINE> <INDENT> logger.info("Adapter, setActive " + self.name + ' ' + str(state) ) <NEW_LINE> adapter.adapters.DMAAdapter.setActive(self, state) <NEW_LINE> if state == True: <NEW_LINE> <INDENT> v = float(self.parameters['rate']) <NEW_LINE> v = self._calculateRate(v) <NEW_LINE> self.startPWM(self.gpios[0], frequency = float( self.parameters['frequency']), value=float( v )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.resetPWM(self.gpios[0])
outputs a pwm signal to a pin with attached servo. Output is inverse, as a transistor line driver with pullup is used. Input 'rate' : float, 0.0 to 100.0 Configuration 'frequency': float, [Hz] uses pwm-feature of RPi.GPIO-Library.
62598fc8377c676e912f6f12
class Command(BaseCommand): <NEW_LINE> <INDENT> help = 'Export hth flat pages as Hugo markdown files' <NEW_LINE> def add_arguments(self, parser): <NEW_LINE> <INDENT> parser.add_argument('output_dir', help='Output directory.') <NEW_LINE> <DEDENT> def handle(self, *args, **options): <NEW_LINE> <INDENT> for page in FlatPage.objects.all(): <NEW_LINE> <INDENT> header = { 'date': '2000-01-01', 'title': page.title.replace(':', ''), 'url': '/design/' + slugify(page.title) + '/', } <NEW_LINE> output_dir = args[0] <NEW_LINE> filename = '{slug}.markdown'.format(slug=slugify(page.title)) <NEW_LINE> content = page.content.encode('utf-8').replace('\r', '') <NEW_LINE> with open(os.path.join(output_dir, filename), 'w') as fp: <NEW_LINE> <INDENT> fp.write('---' + os.linesep) <NEW_LINE> for k, v in header.items(): <NEW_LINE> <INDENT> fp.write(smart_str('%s: %s%s' % (k, v, os.linesep))) <NEW_LINE> <DEDENT> fp.write('---' + os.linesep) <NEW_LINE> fp.write(smart_str(content))
Usage: 1. Put this file in: yourdjangoproject/ management/ commands/ djangoflatpage2hugo.py 2. Make sure there are __init__.py files in both management and commands folders 3. Run: python manage.py djangoflatpage2hugo /chosen/output/directory/ 4. Find the converted .md files in /chosen/output/directory
62598fc84c3428357761a5f7
class ZipCodeResource(object): <NEW_LINE> <INDENT> def __init__(self, model): <NEW_LINE> <INDENT> self.model = model <NEW_LINE> <DEDENT> def on_get(self, req, resp, zip_code=None): <NEW_LINE> <INDENT> limit = req.get_param('limit') <NEW_LINE> zipcodes = [] <NEW_LINE> if zip_code: <NEW_LINE> <INDENT> if validate_zipcode(zip_code): <NEW_LINE> <INDENT> zipcodes = self.model.find_by_zipcode(zip_code) <NEW_LINE> logger.info('%s found...' % ( zipcodes.get('zip_code') if zipcodes else None)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise falcon.HTTPError( falcon.HTTP_400, 'The `zip_code` param must be an integer valid zipcode ' 'with 8 digits.') <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> zipcodes = self.model.all(limit) <NEW_LINE> logger.info('%s resources found limited by %s...' % ( zipcodes.count(True), limit)) <NEW_LINE> <DEDENT> zipcodes = json_util.dumps(zipcodes) if zipcodes else [] <NEW_LINE> resp.body = zipcodes <NEW_LINE> resp.status = falcon.HTTP_200 <NEW_LINE> <DEDENT> @falcon.before(validate_zipcode_on_before) <NEW_LINE> def on_post(self, req, resp): <NEW_LINE> <INDENT> zipcode = req.get_param('zip_code') <NEW_LINE> data = self.model.find_by_zipcode(zipcode) <NEW_LINE> if data: <NEW_LINE> <INDENT> logger.info('%s already exists...' % zipcode) <NEW_LINE> resp.status = falcon.HTTP_201 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.info('%s does not exists...' % zipcode) <NEW_LINE> rq = postmon.get(zipcode) <NEW_LINE> if rq.content: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.model.insert(rq.json()) <NEW_LINE> resp.status = falcon.HTTP_201 <NEW_LINE> logger.info('%s zipcode inserted...' % zipcode) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.error(e) <NEW_LINE> raise falcon.HTTPError( falcon.HTTP_500, 'Error when saving a new data.') <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> logger.info('Postmon response is empty for %s...' % zipcode) <NEW_LINE> raise falcon.HTTPError( falcon.HTTP_400, 'It wasn`t possible to insert your zipcode. Try it again.') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def on_delete(self, req, resp, zip_code): <NEW_LINE> <INDENT> if not validate_zipcode(zip_code): <NEW_LINE> <INDENT> raise falcon.HTTPError( falcon.HTTP_400, 'The `zip_code` param must be an integer valid zipcode ' 'with 8 digits.') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.model.find_by_zipcode(zip_code): <NEW_LINE> <INDENT> self.model.delete(zip_code) <NEW_LINE> resp.status = falcon.HTTP_204 <NEW_LINE> logger.info('%s was removed...' % zip_code) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.info('%s doesn`t exists in the database...' % zip_code) <NEW_LINE> raise falcon.HTTPError( falcon.HTTP_400, 'The zipcode passed does not exists in our database.')
ZipCodeResource
62598fc84a966d76dd5ef210
@total_ordering <NEW_LINE> class Register: <NEW_LINE> <INDENT> def __init__(self, value=0): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> if isinstance(other, Register): <NEW_LINE> <INDENT> return self.value < other.value <NEW_LINE> <DEDENT> return self.value < other <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if isinstance(other, Register): <NEW_LINE> <INDENT> return self.value == other.value <NEW_LINE> <DEDENT> return self.value == other <NEW_LINE> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> if isinstance(other, Register): <NEW_LINE> <INDENT> return Register(self.value + other.value) <NEW_LINE> <DEDENT> return Register(self.value + other) <NEW_LINE> <DEDENT> def __sub__(self, other): <NEW_LINE> <INDENT> if isinstance(other, Register): <NEW_LINE> <INDENT> return Register(self.value - other.value) <NEW_LINE> <DEDENT> return Register(self.value - other) <NEW_LINE> <DEDENT> def write(self, other): <NEW_LINE> <INDENT> if isinstance(other, Register): <NEW_LINE> <INDENT> self.value = other.value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.value = other <NEW_LINE> <DEDENT> <DEDENT> def read(self): <NEW_LINE> <INDENT> return self.value <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'Register(%s)' % self.value
A Register capable of storing a single value. Args: value: Initial Register value.
62598fc84428ac0f6e658860
class DLV(rdtypes.dsbase.DSBase): <NEW_LINE> <INDENT> pass
DLV record
62598fc85fcc89381b2662ea
class User(Document): <NEW_LINE> <INDENT> username = StringField(max_length=30, required=True) <NEW_LINE> first_name = StringField(max_length=30) <NEW_LINE> last_name = StringField(max_length=30) <NEW_LINE> email = StringField() <NEW_LINE> password = StringField(max_length=128) <NEW_LINE> is_staff = BooleanField(default=False) <NEW_LINE> is_active = BooleanField(default=True) <NEW_LINE> is_superuser = BooleanField(default=False) <NEW_LINE> last_login = DateTimeField(default=datetime.datetime.now) <NEW_LINE> date_joined = DateTimeField(default=datetime.datetime.now) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.username <NEW_LINE> <DEDENT> def get_full_name(self): <NEW_LINE> <INDENT> full_name = u'%s %s' % (self.first_name or '', self.last_name or '') <NEW_LINE> return full_name.strip() <NEW_LINE> <DEDENT> def is_anonymous(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def is_authenticated(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def set_password(self, raw_password): <NEW_LINE> <INDENT> from random import random <NEW_LINE> algo = 'sha1' <NEW_LINE> salt = get_hexdigest(algo, str(random()), str(random()))[:5] <NEW_LINE> hash = get_hexdigest(algo, salt, raw_password) <NEW_LINE> self.password = '%s$%s$%s' % (algo, salt, hash) <NEW_LINE> self.save() <NEW_LINE> return self <NEW_LINE> <DEDENT> def check_password(self, raw_password): <NEW_LINE> <INDENT> algo, salt, hash = self.password.split('$') <NEW_LINE> return hash == get_hexdigest(algo, salt, raw_password) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def create_user(cls, username, email, password=None): <NEW_LINE> <INDENT> now = datetime.datetime.now() <NEW_LINE> try: <NEW_LINE> <INDENT> email_name, domain_part = email.strip().split('@', 1) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> email = '@'.join([email_name, domain_part.lower()]) <NEW_LINE> <DEDENT> user = User(username=username, email=email, is_staff=False, is_active=True, is_superuser=False, last_login=now, date_joined=now) <NEW_LINE> user.set_password(password) <NEW_LINE> user.save() <NEW_LINE> return user <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def create_superuser(cls, username, email, password): <NEW_LINE> <INDENT> u = cls.create_user(username, email, password) <NEW_LINE> u.is_staff = True <NEW_LINE> u.is_active = True <NEW_LINE> u.is_superuser = True <NEW_LINE> u.save() <NEW_LINE> return u <NEW_LINE> <DEDENT> def get_and_delete_messages(self): <NEW_LINE> <INDENT> return []
A User document that aims to mirror most of the API specified by Django at http://docs.djangoproject.com/en/dev/topics/auth/#users
62598fc89f28863672818a19
class Equal(Expression): <NEW_LINE> <INDENT> def execute(self, item): <NEW_LINE> <INDENT> return self.resolve_lhs(item) == self.resolve_rhs(item)
Equal expression class.
62598fc860cbc95b06364678
class TaskStepProperties(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'type': {'required': True}, 'base_image_dependencies': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'base_image_dependencies': {'key': 'baseImageDependencies', 'type': '[BaseImageDependency]'}, 'context_path': {'key': 'contextPath', 'type': 'str'}, 'context_access_token': {'key': 'contextAccessToken', 'type': 'str'}, } <NEW_LINE> _subtype_map = { 'type': {'Docker': 'DockerBuildStep', 'EncodedTask': 'EncodedTaskStep', 'FileTask': 'FileTaskStep'} } <NEW_LINE> def __init__( self, *, context_path: Optional[str] = None, context_access_token: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(TaskStepProperties, self).__init__(**kwargs) <NEW_LINE> self.type = None <NEW_LINE> self.base_image_dependencies = None <NEW_LINE> self.context_path = context_path <NEW_LINE> self.context_access_token = context_access_token
Base properties for any task step. You probably want to use the sub-classes and not this class directly. Known sub-classes are: DockerBuildStep, EncodedTaskStep, FileTaskStep. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar type: Required. The type of the step.Constant filled by server. Possible values include: "Docker", "FileTask", "EncodedTask". :vartype type: str or ~azure.mgmt.containerregistry.v2019_06_01_preview.models.StepType :ivar base_image_dependencies: List of base image dependencies for a step. :vartype base_image_dependencies: list[~azure.mgmt.containerregistry.v2019_06_01_preview.models.BaseImageDependency] :ivar context_path: The URL(absolute or relative) of the source context for the task step. :vartype context_path: str :ivar context_access_token: The token (git PAT or SAS token of storage account blob) associated with the context for a step. :vartype context_access_token: str
62598fc8fbf16365ca7943f3
class BaseCaseLogForm(forms.Form): <NEW_LINE> <INDENT> LOG_EVENT_KEY = None <NEW_LINE> NOTES_MANDATORY = False <NEW_LINE> notes = forms.CharField(required=False, max_length=5000) <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.case = kwargs.pop("case") <NEW_LINE> super(BaseCaseLogForm, self).__init__(*args, **kwargs) <NEW_LINE> if self.NOTES_MANDATORY: <NEW_LINE> <INDENT> self.fields["notes"].required = True <NEW_LINE> <DEDENT> <DEDENT> def get_event_key(self): <NEW_LINE> <INDENT> if self.LOG_EVENT_KEY: <NEW_LINE> <INDENT> return self.LOG_EVENT_KEY <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError( "LOG_EVENT must be set or this method must be " "overridden in a subclass to return the correct event" ) <NEW_LINE> <DEDENT> <DEDENT> def get_case(self): <NEW_LINE> <INDENT> return self.case <NEW_LINE> <DEDENT> def get_notes(self): <NEW_LINE> <INDENT> return self.cleaned_data["notes"] <NEW_LINE> <DEDENT> def get_kwargs(self): <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> def get_context(self): <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> def save_event(self, user): <NEW_LINE> <INDENT> event = event_registry.get_event(self.get_event_key())() <NEW_LINE> event.process( self.get_case(), created_by=user, notes=self.get_notes(), context=self.get_context(), **self.get_kwargs() ) <NEW_LINE> <DEDENT> def save(self, user): <NEW_LINE> <INDENT> self.save_event(user)
Use this class if your event is of one of these types: 1. one code event where something happens and you want an event log to get created 2. implicit code event where something happens and the system chooses which code to use. In this case, you need to override the `get_kwargs` method and add your logic. The same kwargs will be passed to the `Event.get_log_code`.
62598fc84527f215b58ea20a
class TitleWidget(forms.TextInput): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.model = kwargs.pop("model") <NEW_LINE> self.field = kwargs.pop("field") <NEW_LINE> super(TitleWidget, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def render(self, name, value, attrs): <NEW_LINE> <INDENT> if value: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> value = self.model.objects.get(pk=value) <NEW_LINE> value = getattr(value, self.field) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return super(TitleWidget, self).render(name, value, attrs)
A text widget that renders a property of the instance.
62598fc8bf627c535bcb17e4
class WebDBDirichletGroup(WebDirichletGroup, WebDBDirichlet): <NEW_LINE> <INDENT> headers = ['orbit label', 'order', 'primitive'] <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self._contents = None <NEW_LINE> self.maxrows = 30 <NEW_LINE> self.maxcols = 30 <NEW_LINE> self.rowtruncate = False <NEW_LINE> self.coltruncate = False <NEW_LINE> WebDBDirichlet.__init__(self, **kwargs) <NEW_LINE> self._set_groupelts() <NEW_LINE> <DEDENT> def add_row(self, chi): <NEW_LINE> <INDENT> mod = chi.modulus() <NEW_LINE> num = chi.number() <NEW_LINE> prim, order, orbit_label, valuepairs = self.char_dbdata(mod, num) <NEW_LINE> formatted_orbit_label = "{}.{}".format( mod, cremona_letter_code(int(orbit_label.partition(".")[-1]) - 1) ) <NEW_LINE> self._contents.append(( self._char_desc(num, mod=mod, prim=prim), (formatted_orbit_label, order, self.texbool(prim)), self._determine_values(valuepairs, order) )) <NEW_LINE> <DEDENT> def char_dbdata(self, mod, num): <NEW_LINE> <INDENT> db_data = db.char_dir_values.lookup( "{}.{}".format(mod, num) ) <NEW_LINE> is_prim = (db_data['label'] == db_data['prim_label']) <NEW_LINE> order = db_data['order'] <NEW_LINE> valuepairs = db_data['values'] <NEW_LINE> orbit_label = db_data['orbit_label'] <NEW_LINE> return is_prim, order, orbit_label, valuepairs <NEW_LINE> <DEDENT> def _compute(self): <NEW_LINE> <INDENT> WebDirichlet._compute(self) <NEW_LINE> logger.debug("WebDBDirichletGroup Computed") <NEW_LINE> <DEDENT> def _set_groupelts(self): <NEW_LINE> <INDENT> if self.modulus == 1: <NEW_LINE> <INDENT> self.groupelts = [1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> db_data = db.char_dir_values.lookup( "{}.{}".format(self.modulus, 1) ) <NEW_LINE> valuepairs = db_data['values'] <NEW_LINE> self.groupelts = [int(g) for g, v in valuepairs] <NEW_LINE> self.groupelts[0] = -1 <NEW_LINE> <DEDENT> <DEDENT> def _char_desc(self, num, mod=None, prim=None): <NEW_LINE> <INDENT> return (mod, num, self.char2tex(mod, num), prim) <NEW_LINE> <DEDENT> def _determine_values(self, valuepairs, order): <NEW_LINE> <INDENT> raw_values = [int(v) for g, v in valuepairs] <NEW_LINE> values = [ self._tex_value(v, order, texify=True) for v in raw_values ] <NEW_LINE> return values
A class using data stored in the database. Currently this is all Dirichlet characters with modulus up to 10000.
62598fc8167d2b6e312b72b2
class KeyActor(pykka.ThreadingActor): <NEW_LINE> <INDENT> use_daemon_thread = True <NEW_LINE> def __init__(self, hub_actor, motor_actor): <NEW_LINE> <INDENT> super(KeyActor, self).__init__() <NEW_LINE> self.hub_actor = hub_actor <NEW_LINE> self.motor_actor = motor_actor <NEW_LINE> self._working = False <NEW_LINE> <DEDENT> def is_working(self): <NEW_LINE> <INDENT> return self._working <NEW_LINE> <DEDENT> def _set_working(self, working): <NEW_LINE> <INDENT> logger.debug('KeyActor._set_working({})'.format(working)) <NEW_LINE> self._working = working <NEW_LINE> <DEDENT> def turn(self, status, callback): <NEW_LINE> <INDENT> logger.debug('KeyActor.turn({}, callback)'.format(status)) <NEW_LINE> if self.is_working(): <NEW_LINE> <INDENT> logger.debug("KeyActor working...") <NEW_LINE> <DEDENT> elif status == OPEN and self.get_status() != OPEN: <NEW_LINE> <INDENT> logger.debug("open key") <NEW_LINE> self._set_working(True) <NEW_LINE> self.motor_actor.open(lambda: (self._set_working(False), callback())) <NEW_LINE> <DEDENT> elif status == CLOSED and self.get_status() != CLOSED: <NEW_LINE> <INDENT> logger.debug("close key") <NEW_LINE> self._set_working(True) <NEW_LINE> self.motor_actor.close(lambda: (self._set_working(False), callback())) <NEW_LINE> <DEDENT> <DEDENT> def get_status(self, angle=None): <NEW_LINE> <INDENT> if angle is None: <NEW_LINE> <INDENT> angle = self.hub_actor.get_key_angle().get() <NEW_LINE> <DEDENT> if angle < KEY_OPEN_ANGLE + KEY_EPS_ANGLE and angle > KEY_OPEN_ANGLE - KEY_EPS_ANGLE: <NEW_LINE> <INDENT> return OPEN <NEW_LINE> <DEDENT> elif angle < KEY_EPS_ANGLE and angle > - KEY_EPS_ANGLE: <NEW_LINE> <INDENT> return CLOSED <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return UNKNOWN
鍵を扱うアクター
62598fc8ab23a570cc2d4f0b
class ToNumpyImage(object): <NEW_LINE> <INDENT> def __call__(self, pic): <NEW_LINE> <INDENT> return to_numpy_image(pic) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> format_string = self.__class__.__name__ <NEW_LINE> return format_string
Convert a tensor of shape C x H x W to ndarray image while preserving the value range.
62598fc8dc8b845886d538f6
class Card: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.part1 = {'Color': 'N', 'Dot': 'N'} <NEW_LINE> self.part2 = {'Color': 'N', 'Dot': 'N'} <NEW_LINE> self.rotation = None <NEW_LINE> <DEDENT> def _set_card_side(self, side1_color, side1_dot, side2_color, side2_dot): <NEW_LINE> <INDENT> self.part1['Color'] = side1_color <NEW_LINE> self.part1['Dot'] = side1_dot <NEW_LINE> self.part2['Color'] = side2_color <NEW_LINE> self.part2['Dot'] = side2_dot <NEW_LINE> <DEDENT> def rotate_card(self, rotation_value): <NEW_LINE> <INDENT> if rotation_value in ('1', '4'): <NEW_LINE> <INDENT> self._set_card_side('R', 'B', 'W', 'W') <NEW_LINE> <DEDENT> elif rotation_value in ('2', '3'): <NEW_LINE> <INDENT> self._set_card_side('W', 'W', 'R', 'B') <NEW_LINE> <DEDENT> elif rotation_value in ('5', '8'): <NEW_LINE> <INDENT> self._set_card_side('R', 'W', 'W', 'B') <NEW_LINE> <DEDENT> elif rotation_value in ('6', '7'): <NEW_LINE> <INDENT> self._set_card_side('W', 'B', 'R', 'W') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError(GameError.IRV.value) <NEW_LINE> <DEDENT> self.rotation = rotation_value
Instance represent a Card Object. =========== Description =========== Represent the card which will be placed by Players on the board.
62598fc8ad47b63b2c5a7b93
@attrs.define(kw_only=True) <NEW_LINE> class ItemPerk: <NEW_LINE> <INDENT> hash: typing.Optional[int] <NEW_LINE> icon: assets.Image <NEW_LINE> is_active: bool <NEW_LINE> is_visible: bool
Represents a Destiny 2 perk.
62598fc87c178a314d78d7dc
class Node(object): <NEW_LINE> <INDENT> def __init__(self, k): <NEW_LINE> <INDENT> self.key = k <NEW_LINE> self.children = []
A node in a tree.
62598fc8283ffb24f3cf3bc2
class PropertySelection(Selection): <NEW_LINE> <INDENT> token = 'prop' <NEW_LINE> ops = dict([ ('>', np.greater), ('<', np.less), ('>=', np.greater_equal), ('<=', np.less_equal), ('==', np.equal), ('!=', np.not_equal), ]) <NEW_LINE> _op_symbols = ('<=', '>=', '==', '!=', '<', '>') <NEW_LINE> opposite_ops = { '==': '==', '!=': '!=', '<': '>=', '>=': '<', '>': '<=', '<=': '>', } <NEW_LINE> props = {'mass', 'charge', 'x', 'y', 'z'} <NEW_LINE> def __init__(self, parser, tokens): <NEW_LINE> <INDENT> prop = tokens.popleft() <NEW_LINE> oper = None <NEW_LINE> value = None <NEW_LINE> if prop == "abs": <NEW_LINE> <INDENT> self.absolute = True <NEW_LINE> prop = tokens.popleft() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.absolute = False <NEW_LINE> <DEDENT> for possible in self._op_symbols: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> x, y = prop.split(possible) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> prop = x <NEW_LINE> oper = possible + y <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if oper is None: <NEW_LINE> <INDENT> oper = tokens.popleft() <NEW_LINE> <DEDENT> for possible in self._op_symbols: <NEW_LINE> <INDENT> if possible in oper: <NEW_LINE> <INDENT> x, y = oper.split(possible) <NEW_LINE> if y: <NEW_LINE> <INDENT> oper = possible <NEW_LINE> value = y <NEW_LINE> <DEDENT> break <NEW_LINE> <DEDENT> <DEDENT> if value is None: <NEW_LINE> <INDENT> value = tokens.popleft() <NEW_LINE> <DEDENT> if value in self.props: <NEW_LINE> <INDENT> prop, value = value, prop <NEW_LINE> oper = self.opposite_ops[oper] <NEW_LINE> <DEDENT> self.prop = prop <NEW_LINE> try: <NEW_LINE> <INDENT> self.operator = self.ops[oper] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise ValueError( "Invalid operator : '{0}' Use one of : '{1}'" "".format(oper, self.ops.keys())) <NEW_LINE> <DEDENT> self.value = float(value) <NEW_LINE> <DEDENT> def apply(self, group): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> col = {'x': 0, 'y': 1, 'z': 2}[self.prop] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> if self.prop == 'mass': <NEW_LINE> <INDENT> values = group.masses <NEW_LINE> <DEDENT> elif self.prop == 'charge': <NEW_LINE> <INDENT> values = group.charges <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise SelectionError( "Expected one of : {0}" "".format(['x', 'y', 'z', 'mass', 'charge'])) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> values = group.positions[:, col] <NEW_LINE> <DEDENT> if self.absolute: <NEW_LINE> <INDENT> values = np.abs(values) <NEW_LINE> <DEDENT> mask = self.operator(values, self.value) <NEW_LINE> return group[mask].unique
Some of the possible properties: x, y, z, radius, mass,
62598fc8fbf16365ca7943f5
class ImageNetPolicy(object): <NEW_LINE> <INDENT> def __init__(self, fillcolor=(128, 128, 128)): <NEW_LINE> <INDENT> self.policies = [ SubPolicy(0.4, "posterize", 8, 0.6, "rotate", 9, fillcolor), SubPolicy(0.6, "solarize", 5, 0.6, "autocontrast", 5, fillcolor), SubPolicy(0.8, "equalize", 8, 0.6, "equalize", 3, fillcolor), SubPolicy(0.6, "posterize", 7, 0.6, "posterize", 6, fillcolor), SubPolicy(0.4, "equalize", 7, 0.2, "solarize", 4, fillcolor), SubPolicy(0.4, "equalize", 4, 0.8, "rotate", 8, fillcolor), SubPolicy(0.6, "solarize", 3, 0.6, "equalize", 7, fillcolor), SubPolicy(0.8, "posterize", 5, 1.0, "equalize", 2, fillcolor), SubPolicy(0.2, "rotate", 3, 0.6, "solarize", 8, fillcolor), SubPolicy(0.6, "equalize", 8, 0.4, "posterize", 6, fillcolor), SubPolicy(0.8, "rotate", 8, 0.4, "color", 0, fillcolor), SubPolicy(0.4, "rotate", 9, 0.6, "equalize", 2, fillcolor), SubPolicy(0.0, "equalize", 7, 0.8, "equalize", 8, fillcolor), SubPolicy(0.6, "invert", 4, 1.0, "equalize", 8, fillcolor), SubPolicy(0.6, "color", 4, 1.0, "contrast", 8, fillcolor), SubPolicy(0.8, "rotate", 8, 1.0, "color", 2, fillcolor), SubPolicy(0.8, "color", 8, 0.8, "solarize", 7, fillcolor), SubPolicy(0.4, "sharpness", 7, 0.6, "invert", 8, fillcolor), SubPolicy(0.6, "shearX", 5, 1.0, "equalize", 9, fillcolor), SubPolicy(0.4, "color", 0, 0.6, "equalize", 3, fillcolor), SubPolicy(0.4, "equalize", 7, 0.2, "solarize", 4, fillcolor), SubPolicy(0.6, "solarize", 5, 0.6, "autocontrast", 5, fillcolor), SubPolicy(0.6, "invert", 4, 1.0, "equalize", 8, fillcolor), SubPolicy(0.6, "color", 4, 1.0, "contrast", 8, fillcolor) ] <NEW_LINE> <DEDENT> def __call__(self, img): <NEW_LINE> <INDENT> policy_idx = random.randint(0, len(self.policies) - 1) <NEW_LINE> return self.policies[policy_idx](img) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "AutoAugment ImageNet Policy"
Randomly choose one of the best 24 Sub-policies on ImageNet. Example: # >>> policy = ImageNetPolicy() # >>> transformed = policy(image) Example as a PyTorch Transform: # >>> transform=transforms.Compose([ # >>> transforms.Resize(256), # >>> ImageNetPolicy(), # >>> transforms.ToTensor()])
62598fc863b5f9789fe854b2
class PlacementAuthProtocol(auth_token.AuthProtocol): <NEW_LINE> <INDENT> def __init__(self, app, conf): <NEW_LINE> <INDENT> self._placement_app = app <NEW_LINE> super(PlacementAuthProtocol, self).__init__(app, conf) <NEW_LINE> <DEDENT> def __call__(self, environ, start_response): <NEW_LINE> <INDENT> if environ['PATH_INFO'] == '/': <NEW_LINE> <INDENT> return self._placement_app(environ, start_response) <NEW_LINE> <DEDENT> return super(PlacementAuthProtocol, self).__call__( environ, start_response)
A wrapper on Keystone auth_token middleware. Does not perform verification of authentication tokens for root in the API.
62598fc8099cdd3c63675580
class SurveillanceOutcome(AbstractNameList): <NEW_LINE> <INDENT> pass
SurveillanceOutcome kintrak table: lt_f691
62598fc85fc7496912d48418
class RecordIOWriterNotCompletedError(Exception): <NEW_LINE> <INDENT> def __init__(self, amount): <NEW_LINE> <INDENT> self.amount = amount <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return (u"RecordIOWriter failed to write %s entries" % (self.amount))
Gets raised if the not all changes were applied.
62598fc897e22403b383b242
class VerifyNodePublicKey(monitor_processors.NodeProcessor): <NEW_LINE> <INDENT> def process(self, context, node): <NEW_LINE> <INDENT> verified = identity_policy.verify_identity( node, public_key_models.PublicKeyIdentityConfig, context.identity.certificate or None, ) <NEW_LINE> if not verified: <NEW_LINE> <INDENT> events.IdentityVerificationFailed(node).post() <NEW_LINE> raise exceptions.NodeProcessorAbort("Node identity verification failed.") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> events.IdentityVerificationFailed(node).absent() <NEW_LINE> <DEDENT> return context
A processor that verifies a node's public key against the known identities. In case verification fails, further processing of this node is aborted. The processor expects a PEM-encoded X509 certificate or public key to be present in 'context.identity.certificate'.
62598fc850812a4eaa620d83
@python_2_unicode_compatible <NEW_LINE> class PaidTimeOff(models.Model): <NEW_LINE> <INDENT> MAX_INT_VALUE = 2**32-1 <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.user.__str__() + " PTO Summary: \n" + "\nSick Days Taken: " + str(self.sick_days_taken) + "\nSick Days Earned: " + str(self.sick_days_earned) + "\nPTO Taken: " + str(self.pto_taken) + "\n PTO Earned: " + str(self.pto_earned) <NEW_LINE> <DEDENT> sick_days_taken = models.PositiveIntegerField( validators=[MaxValueValidator(MAX_INT_VALUE)] ) <NEW_LINE> sick_days_earned = models.PositiveIntegerField( validators=[MaxValueValidator(MAX_INT_VALUE)] ) <NEW_LINE> pto_taken = models.PositiveIntegerField( validators=[MaxValueValidator(MAX_INT_VALUE)] ) <NEW_LINE> pto_earned = models.PositiveIntegerField( validators=[MaxValueValidator(MAX_INT_VALUE)] ) <NEW_LINE> user = models.ForeignKey('User', on_delete=models.CASCADE, related_name='pto') <NEW_LINE> created_at = models.DateTimeField() <NEW_LINE> updated_at = models.DateTimeField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = "app_paid_time_offs" <NEW_LINE> <DEDENT> def sick_days_remaining(self): <NEW_LINE> <INDENT> return self.sick_days_earned - self.sick_days_taken <NEW_LINE> <DEDENT> def pto_days_remaining(self): <NEW_LINE> <INDENT> return self.pto_earned - self.pto_taken <NEW_LINE> <DEDENT> def sick_days_taken_percentage(self): <NEW_LINE> <INDENT> return float(self.sick_days_taken)/float(self.sick_days_earned)*100.0 <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def validate_PTO_form(form): <NEW_LINE> <INDENT> err_list = [] <NEW_LINE> if len(form['event_name']) == 0: <NEW_LINE> <INDENT> err_list.append('Event Name cannot be empty') <NEW_LINE> <DEDENT> if len(form['event_description']) == 0: <NEW_LINE> <INDENT> err_list.append('Event Description cannot be empty') <NEW_LINE> <DEDENT> if len(form['date_begin']) == 0: <NEW_LINE> <INDENT> err_list.append('Event Dates cannot be empty') <NEW_LINE> <DEDENT> err_msg = " and ".join(err_list) <NEW_LINE> return err_msg
Class defining the PaidTimeOff model
62598fc87d847024c075c6fa
class CommentairesViewAdd(generics.CreateAPIView): <NEW_LINE> <INDENT> permission_classes = (IsauthenticatedD,) <NEW_LINE> queryset = Commentaires.objects.all() <NEW_LINE> serializer_class = CommentairesAddSerializer <NEW_LINE> def create(self, request): <NEW_LINE> <INDENT> serializer = self.get_serializer(data=request.data) <NEW_LINE> if not serializer.is_valid(raise_exception=False): <NEW_LINE> <INDENT> data_errors = {} <NEW_LINE> data_message = str('') <NEW_LINE> for P, M in serializer.errors.items(): <NEW_LINE> <INDENT> data_message += P + ": " + M[0].replace(".", '') <NEW_LINE> <DEDENT> data_errors['error'] = data_message <NEW_LINE> return Response({ 'error':'Ce champs est obligatoire' }, status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> profilutili=AccessToken.objects.filter(token=request.META['HTTP_AUTHORIZATION']).first() <NEW_LINE> serializer.save(utilisateur=profilutili.user) <NEW_LINE> return Response({'message':'Commentaire posté avec succès'}, status=status.HTTP_201_CREATED) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return Response({'error':'Rassurez vous que vous etes connecté'}, status=status.HTTP_400_BAD_REQUEST)
API endpoint that allows groups to be viewed or edited.
62598fc83617ad0b5ee06485
class EarlyStopping: <NEW_LINE> <INDENT> def __init__(self, patience: typing.Optional[int]=None, key: typing.Any=None): <NEW_LINE> <INDENT> self._patience = patience <NEW_LINE> self._key = key <NEW_LINE> self._best_so_far = 0 <NEW_LINE> self._epochs_with_no_improvement = 0 <NEW_LINE> self._is_best_so_far = False <NEW_LINE> self._early_stop = False <NEW_LINE> <DEDENT> def state_dict(self) -> typing.Dict[str, typing.Any]: <NEW_LINE> <INDENT> return { 'patience': self._patience, 'best_so_far': self._best_so_far, 'is_best_so_far': self._is_best_so_far, 'epochs_with_no_improvement': self._epochs_with_no_improvement } <NEW_LINE> <DEDENT> def load_state_dict(self, state_dict: typing.Dict[str, typing.Any]): <NEW_LINE> <INDENT> self._patience = state_dict['patience'] <NEW_LINE> self._is_best_so_far = state_dict['is_best_so_far'] <NEW_LINE> self._best_so_far = state_dict['best_so_far'] <NEW_LINE> self._epochs_with_no_improvement = state_dict['epochs_with_no_improvement'] <NEW_LINE> <DEDENT> def update(self, result: list): <NEW_LINE> <INDENT> score = result[self._key] <NEW_LINE> if score > self._best_so_far: <NEW_LINE> <INDENT> self._best_so_far = score <NEW_LINE> self._is_best_so_far = True <NEW_LINE> self._epochs_with_no_improvement = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._is_best_so_far = False <NEW_LINE> self._epochs_with_no_improvement += 1 <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def best_so_far(self) -> bool: <NEW_LINE> <INDENT> return self._best_so_far <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_best_so_far(self) -> bool: <NEW_LINE> <INDENT> return self._is_best_so_far <NEW_LINE> <DEDENT> @property <NEW_LINE> def should_stop_early(self) -> bool: <NEW_LINE> <INDENT> if not self._patience: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._epochs_with_no_improvement >= self._patience
EarlyStopping stops training if no improvement after a given patience.
62598fc84a966d76dd5ef214
class MySolution: <NEW_LINE> <INDENT> def twoSum(self, nums, target): <NEW_LINE> <INDENT> index = [] <NEW_LINE> for i in range(len(nums)): <NEW_LINE> <INDENT> for j in range(i + 1, len(nums)): <NEW_LINE> <INDENT> if nums[i] + nums[j] == target: <NEW_LINE> <INDENT> index.append(i) <NEW_LINE> index.append(j) <NEW_LINE> return index <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return [-1, -1]
my own solution
62598fc84428ac0f6e658864
class InitializeOAuthInputSet(InputSet): <NEW_LINE> <INDENT> def set_APIKey(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'APIKey', value) <NEW_LINE> <DEDENT> def set_AccountName(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'AccountName', value) <NEW_LINE> <DEDENT> def set_AppKeyName(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'AppKeyName', value) <NEW_LINE> <DEDENT> def set_AppKeyValue(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'AppKeyValue', value) <NEW_LINE> <DEDENT> def set_ForwardingURL(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'ForwardingURL', value) <NEW_LINE> <DEDENT> def set_SharedSecret(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'SharedSecret', value)
An InputSet with methods appropriate for specifying the inputs to the InitializeOAuth Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
62598fc8656771135c4899ae
class TestRwriteValue(JNTTFactory, JNTTFactoryConfigCommon): <NEW_LINE> <INDENT> entry_name='rwrite_value'
Test the value factory
62598fc8be7bc26dc9251ffa
class OptionMove(QtGui.QWidget): <NEW_LINE> <INDENT> def __init__(self, parent, project): <NEW_LINE> <INDENT> QtGui.QVBoxLayout .__init__(self) <NEW_LINE> self.project = project <NEW_LINE> self.noWrapRadio = QtGui.QRadioButton("no wrap", self) <NEW_LINE> self.noWrapRadio.pressed.connect(self.noWrapPressed) <NEW_LINE> self.noWrapRadio.setChecked(True) <NEW_LINE> self.wrapRadio = QtGui.QRadioButton("wrap", self) <NEW_LINE> self.wrapRadio.pressed.connect(self.wrapPressed) <NEW_LINE> layout = QtGui.QVBoxLayout() <NEW_LINE> layout.setSpacing(0) <NEW_LINE> layout.addWidget(self.noWrapRadio) <NEW_LINE> layout.addWidget(self.wrapRadio) <NEW_LINE> layout.addStretch() <NEW_LINE> layout.setContentsMargins(0, 0, 0, 0) <NEW_LINE> self.setLayout(layout) <NEW_LINE> <DEDENT> def noWrapPressed(self): <NEW_LINE> <INDENT> self.project.moveMode = "no_wrap" <NEW_LINE> <DEDENT> def wrapPressed(self): <NEW_LINE> <INDENT> self.project.moveMode = "wrap"
contextual option for the select tool
62598fc860cbc95b0636467c
class PlanasAdd( views.LoginRequiredMixin, views.FormValidMessageMixin, generic.edit.CreateView): <NEW_LINE> <INDENT> form_class = PlanasAddForm <NEW_LINE> form_valid_message = 'Įvestas naujas kodas: ' <NEW_LINE> template_name = 'planas_create.html' <NEW_LINE> success_url = reverse_lazy('planas_add') <NEW_LINE> def form_valid(self, form): <NEW_LINE> <INDENT> form.instance.organizatorius = self.request.user <NEW_LINE> self.form_valid_message += form.cleaned_data['kodas'] + ', ' + form.cleaned_data['preke'] + '. ' + 'Gali įvesti dar vieną kodą arba spausk viršutinį meniu mygtuką "Planas".' <NEW_LINE> return super(PlanasAdd, self).form_valid(form)
Naujo VP kodo pridejimo forma (planas_create.html).
62598fc87b180e01f3e491ef
class DummyController(MessageHandler): <NEW_LINE> <INDENT> def __init__(self, pipe_in, pipe_out, driver): <NEW_LINE> <INDENT> MessageHandler.__init__(self, pipe_in, pipe_out) <NEW_LINE> self.__dummy = driver <NEW_LINE> self.__value = 0 <NEW_LINE> self.__logger = logging.getLogger(LOGGER_NAME) <NEW_LINE> <DEDENT> def handle_data_message(self, header, message): <NEW_LINE> <INDENT> if message.HasExtension(dummy_pb2.enable): <NEW_LINE> <INDENT> self.__handle_set_enable(header, message) <NEW_LINE> <DEDENT> elif message.HasExtension(dummy_pb2.message): <NEW_LINE> <INDENT> self.__handle_set_message(header, message) <NEW_LINE> <DEDENT> elif message.HasExtension(dummy_pb2.get_status): <NEW_LINE> <INDENT> self.__handle_get_status(header, message) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__logger.warning('No recognizable request in message') <NEW_LINE> <DEDENT> <DEDENT> def __handle_set_enable(self, header, message): <NEW_LINE> <INDENT> value = message.Extensions[dummy_pb2.enable] <NEW_LINE> self.__logger.debug('Set enable to %s', value) <NEW_LINE> self.__dummy.enable = value <NEW_LINE> <DEDENT> def __handle_set_message(self, header, message): <NEW_LINE> <INDENT> value = message.Extensions[dummy_pb2.message] <NEW_LINE> self.__logger.debug('Set message to %s', value) <NEW_LINE> self.__dummy.message = value <NEW_LINE> <DEDENT> @MessageHandler.handle_and_response <NEW_LINE> def __handle_get_status(self, received_header, received_message, response_header, response_message): <NEW_LINE> <INDENT> self.__logger.debug('Get status') <NEW_LINE> DummyController.__fill_status(response_message, self.__dummy.enable, self.__dummy.message) <NEW_LINE> return response_header, response_message <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __fill_status(response_message, enable, message): <NEW_LINE> <INDENT> response_message.Extensions[dummy_pb2.enable] = enable <NEW_LINE> response_message.Extensions[dummy_pb2.message] = message <NEW_LINE> <DEDENT> def handle_subscribe_message(self, header, message): <NEW_LINE> <INDENT> self.__logger.debug('Subscribe action') <NEW_LINE> self.add_subscribers(header.clientIDs) <NEW_LINE> <DEDENT> def handle_unsubscribe_message(self, header, message): <NEW_LINE> <INDENT> self.__logger.debug('Unsubscribe action for clients %s', str(header.clientIDs)) <NEW_LINE> map(self.remove_subscriber, header.clientIDs) <NEW_LINE> <DEDENT> def handle_client_died_message(self, client_id): <NEW_LINE> <INDENT> self.__logger.info('Client %d died', client_id) <NEW_LINE> self.remove_subscriber(client_id) <NEW_LINE> <DEDENT> def fill_subscription_response(self, response_message): <NEW_LINE> <INDENT> self.__value += 1 <NEW_LINE> return DummyController.__fill_response(response_message, self.__value) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __fill_response(response_message, value): <NEW_LINE> <INDENT> response_message.Extensions[dummy_pb2.message] = 'Response %d' % value <NEW_LINE> return response_message
Example implementation of driver. Need to extends `MessageHandler` from `amber.driver.common.amber_pipes`.
62598fc8167d2b6e312b72b6
class FixedTypedArrayBase(FixedArrayBase): <NEW_LINE> <INDENT> kBasePointerOffset = FixedArrayBase.kHeaderSize <NEW_LINE> kExternalPointerOffset = kBasePointerOffset + kPointerSize <NEW_LINE> kHeaderSize = DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize) <NEW_LINE> kDataOffset = kHeaderSize <NEW_LINE> kSize = kHeaderSize <NEW_LINE> TYPED_ARRAYS = [('Uint8', 'uint8', 'UINT8', 'uint8_t', 1), ('Int8', 'int8', 'INT8', 'int8_t', 1), ('Uint16', 'uint16', 'UINT16', 'uint16_t', 2), ('Int16', 'int16', 'INT16', 'int16_t', 2), ('Uint32', 'uint32', 'UINT32', 'uint32_t', 4), ('Int32', 'int32', 'INT32', 'int32_t', 4), ('Float32', 'float32', 'FLOAT32', 'float', 4), ('Float64', 'float64', 'FLOAT64', 'double', 8), ('Uint8Clamped', 'uint8_clamped', 'UINT8_CLAMPED', 'uint8_t', 1)] <NEW_LINE> @staticmethod <NEW_LINE> def get_base_pointer_addr(data): <NEW_LINE> <INDENT> return get_dword(data, FixedTypedArrayBase.kBasePointerOffset) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_external_pointer_addr(data): <NEW_LINE> <INDENT> return get_dword(data, FixedTypedArrayBase.kExternalPointerOffset) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_data_ptr(data): <NEW_LINE> <INDENT> return FixedTypedArrayBase.get_base_pointer_addr(data) + FixedTypedArrayBase.get_external_pointer_addr(data) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_element_size_from_instance(instance_type_num): <NEW_LINE> <INDENT> instance_type_name = get_instance_type_name(instance_type_num) <NEW_LINE> for i in FixedTypedArrayBase.TYPED_ARRAYS: <NEW_LINE> <INDENT> if 'FIXED_%s_ARRAY_TYPE' % i[2] in instance_type_name: <NEW_LINE> <INDENT> return i[-1] <NEW_LINE> <DEDENT> <DEDENT> return 0 <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_data_size_from_instance(data, instance_type_num): <NEW_LINE> <INDENT> element_size = FixedTypedArrayBase.get_element_size_from_instance(instance_type_num) <NEW_LINE> return FixedArrayBase.get_length(data) * element_size <NEW_LINE> <DEDENT> def do_parse(self): <NEW_LINE> <INDENT> FixedArrayBase.do_parse(self) <NEW_LINE> self.append('kBasePointerAddr: 0x%x' % FixedTypedArrayBase.get_base_pointer_addr(self.data)) <NEW_LINE> self.append('kExternalPointerAddr: 0x%x' % FixedTypedArrayBase.get_external_pointer_addr(self.data))
class FixedTypedArrayBase: public FixedArrayBase;
62598fc8ab23a570cc2d4f0d
class GameboardView: <NEW_LINE> <INDENT> def __init__(self, board): <NEW_LINE> <INDENT> self._boardImage = pygame.image.load('tictacboard.png') <NEW_LINE> self._board = board <NEW_LINE> self._height = board.height * CELL_SIZE <NEW_LINE> self._width = board.width * CELL_SIZE <NEW_LINE> <DEDENT> def draw(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def check_coords_correct(self, x, y): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def get_coords(self, x, y): <NEW_LINE> <INDENT> return 0, 0
Gameboard's widget, shows board on the screen, and checks mouse's click's place in the board
62598fc8dc8b845886d538fa
class RemoteFontFamily(object): <NEW_LINE> <INDENT> name: str <NEW_LINE> fonts: List[RemoteFont] <NEW_LINE> def __init__(self, name: str, fonts: List[RemoteFont]) -> None: <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.fonts = fonts <NEW_LINE> <DEDENT> @property <NEW_LINE> def variants(self) -> List[FontAttribute]: <NEW_LINE> <INDENT> return [font.variant for font in self.fonts] <NEW_LINE> <DEDENT> def get_variants(self, variants: List[FontAttribute] = None) -> List[RemoteFont]: <NEW_LINE> <INDENT> if variants: <NEW_LINE> <INDENT> return [font for font in self.fonts if font.variant in variants] <NEW_LINE> <DEDENT> return self.fonts <NEW_LINE> <DEDENT> def generate_id(self, source: str) -> str: <NEW_LINE> <INDENT> unique_str = '{source}-{name}'.format(source=source, name=self.name) <NEW_LINE> return hashlib.md5(unique_str.encode('utf-8')).hexdigest()
Class to manage a remote font family.
62598fc8ad47b63b2c5a7b98
class Benchmark: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def run(function, runs, print_output=True): <NEW_LINE> <INDENT> timings = [] <NEW_LINE> if print_output: <NEW_LINE> <INDENT> print("Runs Median Mean Stddev") <NEW_LINE> <DEDENT> for i in range(runs): <NEW_LINE> <INDENT> startTime = time.time() <NEW_LINE> function() <NEW_LINE> seconds = time.time() - startTime <NEW_LINE> timings.append(seconds) <NEW_LINE> median = statistics.median(timings) <NEW_LINE> mean = statistics.mean(timings) <NEW_LINE> if print_output: <NEW_LINE> <INDENT> if i < 10 or i % 10 == 9: <NEW_LINE> <INDENT> print( "{0}\t{1:3.2f}\t{2:3.2f}\t{3:3.2f}".format( 1 + i, median, mean, statistics.stdev(timings, mean) if i > 1 else 0, ) ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return (median, mean, statistics.stdev(timings, mean))
This class runs a benchmark on a function passed to the run method. It calls the function a specified number of times and calculates the mean and standard deviation across all runs.
62598fc8099cdd3c63675581
class Component(api_types.Base): <NEW_LINE> <INDENT> assembly_uuid = wtypes.text <NEW_LINE> services = [service.Service] <NEW_LINE> operations = [operation.Operation] <NEW_LINE> sensors = [sensor.Sensor] <NEW_LINE> abbreviated = bool <NEW_LINE> components_ids = [wtypes.text] <NEW_LINE> resource_uri = common_types.Uri <NEW_LINE> @classmethod <NEW_LINE> def sample(cls): <NEW_LINE> <INDENT> return cls(uri='http://example.com/v1/components/php-web-app', name='php-web-app', type='component', description='A php web application component', tags=['group_xyz'], project_id='1dae5a09ef2b4d8cbf3594b0eb4f6b94', user_id='55f41cf46df74320b9486a35f5d28a11', assembly_id='b3e0d79c698ea7b1561075bcfbbd2206a23d19b9', abbreviated=True, components_ids=[], services=[], operations=[], sensors=[])
The Component resource represents one part of an Assembly. For example, an instance of a database service may be a Component. A Component resource may also represent a static artifact, such as an archive file that contains data for initializing your application. An Assembly may have different components that represent different processes that run. For example, you may have one Component that represents an API service process, and another that represents a web UI process that consumes that API service. The simplest case is when an Assembly has only one component. For example, your component may be named "PHP" and refers to the PHP Service offered by the platform for running a PHP application.
62598fc87047854f4633f711
class G2Source(object): <NEW_LINE> <INDENT> def __init__(self, area, timeslot): <NEW_LINE> <INDENT> areaSettings = ss.Area.objects.get(name=area) <NEW_LINE> sourceSettings = areaSettings.source <NEW_LINE> self.name = None <NEW_LINE> for specSource in sourceSettings.specificsource_set.all(): <NEW_LINE> <INDENT> if specSource.startDate <= timeslot < specSource.endDate: <NEW_LINE> <INDENT> self.name = specSource.name <NEW_LINE> if specSource.number is not None: <NEW_LINE> <INDENT> self.specificNumber = int(specSource.number) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.generalName = sourceSettings.name <NEW_LINE> self.area = areaSettings.name <NEW_LINE> for extraInfo in sourceSettings.sourceextrainfo_set.all(): <NEW_LINE> <INDENT> exec('self.%s = "%s"' % (extraInfo.name, extraInfo.string))
...
62598fc8d486a94d0ba2c312
class Series(Choreography): <NEW_LINE> <INDENT> def __init__(self, temboo_session): <NEW_LINE> <INDENT> Choreography.__init__(self, temboo_session, '/Library/NPR/StoryFinder/Series') <NEW_LINE> <DEDENT> def new_input_set(self): <NEW_LINE> <INDENT> return SeriesInputSet() <NEW_LINE> <DEDENT> def _make_result_set(self, result, path): <NEW_LINE> <INDENT> return SeriesResultSet(result, path) <NEW_LINE> <DEDENT> def _make_execution(self, session, exec_id, path): <NEW_LINE> <INDENT> return SeriesChoreographyExecution(session, exec_id, path)
Create a new instance of the Series Choreography. A TembooSession object, containing a valid set of Temboo credentials, must be supplied.
62598fc83d592f4c4edbb1f3
class AbstractItemCategory(models.Model): <NEW_LINE> <INDENT> item = models.ForeignKey('product.Item') <NEW_LINE> category = models.ForeignKey('product.Category') <NEW_LINE> is_canonical = models.BooleanField(default=False, db_index=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> ordering = ['-is_canonical'] <NEW_LINE> verbose_name_plural = 'Categories'
Joining model between items and categories.
62598fc8a219f33f346c6b49
class HelpCommand(Command): <NEW_LINE> <INDENT> @property <NEW_LINE> def short_name(self): <NEW_LINE> <INDENT> return 'help' <NEW_LINE> <DEDENT> async def exec(self, args): <NEW_LINE> <INDENT> global g_commands <NEW_LINE> for command in g_commands: <NEW_LINE> <INDENT> cmd = command() <NEW_LINE> print(' {:<22}: {}'.format( cmd.short_name, command.description())) <NEW_LINE> <DEDENT> print()
Show this help message.
62598fc8ad47b63b2c5a7b9a
class Consumer(Thread): <NEW_LINE> <INDENT> def __init__(self, thread_id: int, thread_name: str, modify_event: Event, queue:OwnQueue): <NEW_LINE> <INDENT> Thread.__init__(self) <NEW_LINE> self.thread_id = thread_id <NEW_LINE> self.thread_name = thread_name <NEW_LINE> self.modify_event = modify_event <NEW_LINE> self.queue = queue <NEW_LINE> self.pop_consumer = random.choice([True, False]) <NEW_LINE> println(self.__repr__()) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> while not self.modify_event.isSet(): <NEW_LINE> <INDENT> self.modify_event.set() <NEW_LINE> if not len(self.queue): <NEW_LINE> <INDENT> self.modify_event.wait() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.pop_consumer is True: <NEW_LINE> <INDENT> println('{} Popped Element {}'.format(self.__repr__(), self.queue.pop())) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> println('{} Peeked Element {}'.format(self.__repr__(), self.queue.peek())) <NEW_LINE> <DEDENT> <DEDENT> self.modify_event.clear() <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> pop_str = 'Peek' <NEW_LINE> if self.pop_consumer is True: <NEW_LINE> <INDENT> pop_str = 'Pop ' <NEW_LINE> <DEDENT> return '{} Consumer Thread Name: {}, Thread Id: {}'.format(pop_str, self.thread_name, self.thread_id)
Consumers are of 2 types: 1. Pop Consumers that pop the last element and modify the queue 2. Peek Consumers that peek the last element and do not modify the queue
62598fc8851cf427c66b85f5
class Object(object): <NEW_LINE> <INDENT> def __init__(self, fields): <NEW_LINE> <INDENT> self.fields = fields <NEW_LINE> <DEDENT> def get_field(self, name): <NEW_LINE> <INDENT> return self.fields.get(name)
Generic container for opensocial.* objects.
62598fc8bf627c535bcb17ea
class Team(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=200, primary_key=True) <NEW_LINE> logo = models.ImageField(upload_to='media/')
Model class for the cricket_app Teams
62598fc85fdd1c0f98e5e2cd
class ScaledDotProductAttention(nn.Module): <NEW_LINE> <INDENT> def __init__(self, d_model, n_head, attention_dropout): <NEW_LINE> <INDENT> super(ScaledDotProductAttention, self).__init__() <NEW_LINE> self.temper = np.power(d_model // n_head, 0.5) <NEW_LINE> self.attention_dropout = nn.Dropout(attention_dropout) <NEW_LINE> <DEDENT> def forward(self, q, k, v, attn_mask=None): <NEW_LINE> <INDENT> attn = torch.bmm(q, k.transpose(1, 2)) / self.temper <NEW_LINE> if attn_mask is not None: <NEW_LINE> <INDENT> assert attn_mask.size() == attn.size(), 'Attention mask shape {} mismatch ' 'with Attention logit tensor shape ' '{}.'.format(attn_mask.size(), attn.size()) <NEW_LINE> attn.data.masked_fill_(attn_mask, -float('inf')) <NEW_LINE> <DEDENT> attn = F.softmax(attn, dim=-1) <NEW_LINE> attn = self.attention_dropout(attn) <NEW_LINE> output = torch.bmm(attn, v) <NEW_LINE> return output, attn
Scaled Dot-Product Attention
62598fc8a05bb46b3848abad
class MapServiceBot(MapBaseServer): <NEW_LINE> <INDENT> service_bot = True <NEW_LINE> hidden = True
Represents a service bot.
62598fc87cff6e4e811b5d69
class Map: <NEW_LINE> <INDENT> __listScent = [] <NEW_LINE> def __init__(self, xSize, ySize): <NEW_LINE> <INDENT> self.xSize = xSize <NEW_LINE> self.ySize = ySize <NEW_LINE> <DEDENT> def addScent(self, Scent): <NEW_LINE> <INDENT> self.__listScent.append(Scent) <NEW_LINE> <DEDENT> def checkScent(self, Scent): <NEW_LINE> <INDENT> for i in range(len(self.__listScent)): <NEW_LINE> <INDENT> if self.__listScent[i].compareScent(Scent.xCoord, Scent.yCoord, Scent.orientation): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def printScent(self): <NEW_LINE> <INDENT> for i in range(len(self.__listScent)): <NEW_LINE> <INDENT> print(self.__listScent[i].xCoord, self.__listScent[i].yCoord)
Definition of the map
62598fc871ff763f4b5e7ac1
class PastebayDownloadQueue(RecentItemsDownloader): <NEW_LINE> <INDENT> def __init__(self, name, interval): <NEW_LINE> <INDENT> RecentItemsDownloader.__init__(self, name, interval) <NEW_LINE> self.download_url = 'http://www.pastebay.net/pastebay.php?dl={id}' <NEW_LINE> self.details_url = 'http://www.pastebay.net/{id}' <NEW_LINE> self.details_regexp = dict( user=r'<h1>Posted by (.*) on [^<]+<', posted_on=r'<h1>Posted by .* on ([^<]+)<', ) <NEW_LINE> self.session = requests.session() <NEW_LINE> return <NEW_LINE> <DEDENT> def process_id(self, id): <NEW_LINE> <INDENT> self.echo('processing %s [%u left]' % (id, len(self.queue))) <NEW_LINE> url = self.download_url.format(id=id) <NEW_LINE> r = self.session.post(url, **pbl.pollers.requestoptions) <NEW_LINE> if not r.ok: <NEW_LINE> <INDENT> self.echo('Problem downloading page %s, status=%s, error=%s' % (url, repr(r.status_code), repr(r.error))) <NEW_LINE> return False <NEW_LINE> <DEDENT> data = r.content <NEW_LINE> time.sleep(0.2) <NEW_LINE> url = self.details_url.format(id=id) <NEW_LINE> r = self.session.post(url, **pbl.pollers.requestoptions) <NEW_LINE> details = r.content <NEW_LINE> metadata = {} <NEW_LINE> metadata['uid'] = id <NEW_LINE> metadata['url'] = url <NEW_LINE> for rname in self.details_regexp: <NEW_LINE> <INDENT> m = re.search(self.details_regexp[rname], details, re.DOTALL) <NEW_LINE> if m: <NEW_LINE> <INDENT> metadata[rname] = m.group(1) <NEW_LINE> <DEDENT> <DEDENT> entry = PastebayEntry(data, metadata) <NEW_LINE> if entry.match(): <NEW_LINE> <INDENT> entry.keep() <NEW_LINE> <DEDENT> return True
Downloader thread for pastebin.
62598fc855399d3f0562685b
@six.add_metaclass(StoreType) <NEW_LINE> class Store(object): <NEW_LINE> <INDENT> key = None <NEW_LINE> service = None <NEW_LINE> abstract = True <NEW_LINE> manager = Manager() <NEW_LINE> def __init__(self, key, active=True, **kwargs): <NEW_LINE> <INDENT> super(Store, self).__init__() <NEW_LINE> key = key.lower() <NEW_LINE> if not is_filename_safe(key): <NEW_LINE> <INDENT> raise ValueError('Key is not safe for filename') <NEW_LINE> <DEDENT> self.key = key <NEW_LINE> if self.manager._started: <NEW_LINE> <INDENT> self._pre_start() <NEW_LINE> <DEDENT> for field_name, field in self._fields.items(): <NEW_LINE> <INDENT> field.contribute_to_instance(self, field_name) <NEW_LINE> <DEDENT> for field_name, value in kwargs.items(): <NEW_LINE> <INDENT> if field_name not in self._fields: <NEW_LINE> <INDENT> raise TypeError( "__init__() got an unexpected keyword argument '%s'" % field_name ) <NEW_LINE> <DEDENT> setattr(self, field_name, value) <NEW_LINE> <DEDENT> if active: <NEW_LINE> <INDENT> self.manager.add_active(self) <NEW_LINE> <DEDENT> <DEDENT> def _pre_start(self, event=None): <NEW_LINE> <INDENT> self._filename = os.path.join( self.manager.store_path, "%s.json" % self.key ) <NEW_LINE> <DEDENT> def to_dict(self, session=False): <NEW_LINE> <INDENT> data = {} <NEW_LINE> for name, field in self._fields.items(): <NEW_LINE> <INDENT> if not session and name not in self._permanent_fields: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> data[name] = field.serialise(self, name) <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> def from_dict(self, data, session=False): <NEW_LINE> <INDENT> for name, field in self._fields.items(): <NEW_LINE> <INDENT> if not session and name not in self._permanent_fields: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if name not in data: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> field.deserialise(self, name, data[name]) <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def to_json(self, session=False): <NEW_LINE> <INDENT> data = self.to_dict(session=session) <NEW_LINE> return json.dumps(data) <NEW_LINE> <DEDENT> def from_json(self, raw, session=False): <NEW_LINE> <INDENT> data = json.loads(raw) <NEW_LINE> self.from_dict(data, session=session) <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> store_path = self.manager.store_path <NEW_LINE> if not os.path.exists(store_path): <NEW_LINE> <INDENT> os.makedirs(store_path) <NEW_LINE> <DEDENT> filename = self._filename <NEW_LINE> raw = self.to_json() <NEW_LINE> self.service.log.store('Saving %s' % filename) <NEW_LINE> f = open(filename, 'w') <NEW_LINE> f.write(raw) <NEW_LINE> f.close() <NEW_LINE> <DEDENT> def load(self): <NEW_LINE> <INDENT> filename = self._filename <NEW_LINE> if not os.path.exists(filename): <NEW_LINE> <INDENT> self.service.log.store('Cannot load %s, does not exist' % filename) <NEW_LINE> return False <NEW_LINE> <DEDENT> self.service.log.store('Loading %s' % filename) <NEW_LINE> f = open(filename, 'r') <NEW_LINE> raw = f.read() <NEW_LINE> f.close() <NEW_LINE> self.from_json(raw) <NEW_LINE> return True
Abstract base class to implement session and stored data
62598fc87047854f4633f715
class AdditionalFightingStyle(FeatureSelector): <NEW_LINE> <INDENT> options = {'archery 2': Archery, 'defense 2': Defense, 'dueling 2': Dueling, 'great 2': GreatWeaponFighting, 'great-weapon fighting 2': GreatWeaponFighting, 'projection 2': Protection, 'two-weapon fighting 2': TwoWeaponFighting, 'two-weapon 2': TwoWeaponFighting, 'dual wield 2': TwoWeaponFighting} <NEW_LINE> name = "Fighting Style (Select One)" <NEW_LINE> source = "Fighter (Champion)"
Select a Fighting Style by choosing in feature_choices: archery 2 defense 2 dueling 2 great-weapon fighting 2 protection 2 two-weapon fighting 2
62598fc8d8ef3951e32c7ffd
class Array(Subconstruct): <NEW_LINE> <INDENT> def __init__(self, count, subcon, discard=False): <NEW_LINE> <INDENT> super().__init__(subcon) <NEW_LINE> self.count = count <NEW_LINE> self.discard = discard <NEW_LINE> <DEDENT> def _parse(self, stream, context, path): <NEW_LINE> <INDENT> count = evaluate(self.count, context) <NEW_LINE> if not 0 <= count: <NEW_LINE> <INDENT> raise RangeError("invalid count %s" % (count,), path=path) <NEW_LINE> <DEDENT> discard = self.discard <NEW_LINE> obj = ListContainer() <NEW_LINE> for i in range(count): <NEW_LINE> <INDENT> context._index = i <NEW_LINE> e = self.subcon._parsereport(stream, context, path) <NEW_LINE> if not discard: <NEW_LINE> <INDENT> obj.append(e) <NEW_LINE> <DEDENT> <DEDENT> return obj <NEW_LINE> <DEDENT> def _build(self, obj, stream, context, path): <NEW_LINE> <INDENT> count = evaluate(self.count, context) <NEW_LINE> if not 0 <= count: <NEW_LINE> <INDENT> raise RangeError("invalid count %s" % (count,), path=path) <NEW_LINE> <DEDENT> if not len(obj) == count: <NEW_LINE> <INDENT> raise RangeError("expected %d elements, found %d" % (count, len(obj)), path=path) <NEW_LINE> <DEDENT> discard = self.discard <NEW_LINE> retlist = ListContainer() <NEW_LINE> for i,e in enumerate(obj): <NEW_LINE> <INDENT> context._index = i <NEW_LINE> buildret = self.subcon._build(e, stream, context, path) <NEW_LINE> if not discard: <NEW_LINE> <INDENT> retlist.append(buildret) <NEW_LINE> <DEDENT> <DEDENT> return retlist <NEW_LINE> <DEDENT> def _sizeof(self, context, path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> count = evaluate(self.count, context) <NEW_LINE> <DEDENT> except (KeyError, AttributeError): <NEW_LINE> <INDENT> raise SizeofError("cannot calculate size, key not found in context", path=path) <NEW_LINE> <DEDENT> return count * self.subcon._sizeof(context, path) <NEW_LINE> <DEDENT> def _emitparse(self, code): <NEW_LINE> <INDENT> return f"ListContainer(({self.subcon._compileparse(code)}) for i in range({self.count}))" <NEW_LINE> <DEDENT> def _emitbuild(self, code): <NEW_LINE> <INDENT> return f"ListContainer(reuse(obj[i], lambda obj: ({self.subcon._compilebuild(code)})) for i in range({self.count}))" <NEW_LINE> <DEDENT> def _emitfulltype(self, ksy, bitwise): <NEW_LINE> <INDENT> return dict(type=self.subcon._compileprimitivetype(ksy, bitwise), repeat="expr", repeat_expr=self.count)
Homogenous array of elements, similar to C# generic T[]. Parses into a ListContainer (a list). Parsing and building processes an exact amount of elements. If given list has more or less than count elements, raises RangeError. Size is defined as count multiplied by subcon size, but only if subcon is fixed size. Operator [] can be used to make Array instances (recommended syntax). :param count: integer or context lambda, strict amount of elements :param subcon: Construct instance, subcon to process individual elements :param discard: optional, bool, if set then parsing returns empty list :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes :raises RangeError: specified count is not valid :raises RangeError: given object has different length than specified count Can propagate any exception from the lambdas, possibly non-ConstructError. Example:: >>> d = Array(5, Byte) or Byte[5] >>> d.build(range(5)) b'\x00\x01\x02\x03\x04' >>> d.parse(_) [0, 1, 2, 3, 4]
62598fc84c3428357761a601
class CollectionAJAXView(JSONResponseMixin, TemplateView, ContextDataMixin): <NEW_LINE> <INDENT> http_method_names = ('get',) <NEW_LINE> @method_decorator(dcolumn_login_required) <NEW_LINE> def dispatch(self, *args, **kwargs): <NEW_LINE> <INDENT> return super(CollectionAJAXView, self).dispatch(*args, **kwargs) <NEW_LINE> <DEDENT> def render_to_response(self, context, **response_kwargs): <NEW_LINE> <INDENT> context.pop('view', None) <NEW_LINE> return self.render_to_json_response(context, **response_kwargs) <NEW_LINE> <DEDENT> def get_data(self, **context): <NEW_LINE> <INDENT> log.debug("context: %s", context) <NEW_LINE> context['valid'] = True <NEW_LINE> try: <NEW_LINE> <INDENT> context.update(self.get_dynamic_column_context_data(**context)) <NEW_LINE> context.update(self.get_relation_context_data(**context)) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> context['valid'] = False <NEW_LINE> context['message'] = "Error occurred: {}".format(e) <NEW_LINE> log.error(context['message'], exc_info=True) <NEW_LINE> <DEDENT> return context
Web service endpoint used in the Django admin to format ``KeyValue`` values as per the ``DynamicColumn`` meta data.
62598fc83617ad0b5ee0648b
class TaskLog(BASE, NovaBase): <NEW_LINE> <INDENT> __tablename__ = 'task_log' <NEW_LINE> id = Column(Integer, primary_key=True, nullable=False, autoincrement=True) <NEW_LINE> task_name = Column(String(255), nullable=False) <NEW_LINE> state = Column(String(255), nullable=False) <NEW_LINE> host = Column(String(255)) <NEW_LINE> period_beginning = Column(String(255), default=timeutils.utcnow) <NEW_LINE> period_ending = Column(String(255), default=timeutils.utcnow) <NEW_LINE> message = Column(String(255), nullable=False) <NEW_LINE> task_items = Column(Integer(), default=0) <NEW_LINE> errors = Column(Integer(), default=0)
Audit log for background periodic tasks
62598fc87cff6e4e811b5d6b
class DeebotMopAttachedBinarySensor(BinarySensorEntity): <NEW_LINE> <INDENT> def __init__(self, vacbot: VacBot, device_id: str): <NEW_LINE> <INDENT> self._vacbot = vacbot <NEW_LINE> self._id = device_id <NEW_LINE> if self._vacbot.vacuum.get("nick", None) is not None: <NEW_LINE> <INDENT> self._vacbot_name = "{}".format(self._vacbot.vacuum["nick"]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._vacbot_name = "{}".format(self._vacbot.vacuum["did"]) <NEW_LINE> <DEDENT> self._name = self._vacbot_name + "_" + device_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_on(self): <NEW_LINE> <INDENT> return self._vacbot.mop_attached <NEW_LINE> <DEDENT> @property <NEW_LINE> def icon(self) -> Optional[str]: <NEW_LINE> <INDENT> return "mdi:water" if self.is_on else "mdi:water-off"
Deebot mop attached binary sensor
62598fc8a8370b77170f071f
class Event(object): <NEW_LINE> <INDENT> __slots__ = ['event_type', 'data', 'origin'] <NEW_LINE> def __init__(self, event_type, data=None, origin=EventOrigin.local): <NEW_LINE> <INDENT> self.event_type = event_type <NEW_LINE> self.data = data or {} <NEW_LINE> self.origin = origin <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if self.data: <NEW_LINE> <INDENT> return "<Event {}[{}]: {}>".format( self.event_type, str(self.origin)[0], util.repr_helper(self.data)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "<Event {}[{}]>".format(self.event_type, str(self.origin)[0])
Represents an event within the Bus.
62598fc860cbc95b06364682
class GenericPtrType(TypeGeneric): <NEW_LINE> <INDENT> def __getitem__(self, vtype): <NEW_LINE> <INDENT> if not isinstance(vtype, TypeGeneric): <NEW_LINE> <INDENT> raise TypeError(f"Ptr expects a type argument, but received {type(vtype).__name__}") <NEW_LINE> <DEDENT> return ConcreteType(tvm.ir.PointerType(vtype.evaluate()))
TVM script typing class generator for PtrType [] operator is overloaded, accepts a ConcreteType and returns a ConcreteType wrapping PtrType
62598fc863b5f9789fe854ba
class Event(EventItem): <NEW_LINE> <INDENT> objects = InheritanceManager() <NEW_LINE> e_title = CharField(max_length=128) <NEW_LINE> e_description = TextField() <NEW_LINE> blurb = TextField(blank=True) <NEW_LINE> duration = DurationField() <NEW_LINE> notes = TextField(blank=True) <NEW_LINE> event_id = AutoField(primary_key=True) <NEW_LINE> e_conference = ForeignKey( Conference, related_name="e_conference_set", blank=True, null=True) <NEW_LINE> default_location = ForeignKey(Room, blank=True, null=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.e_title <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_all_events(cls, conference): <NEW_LINE> <INDENT> events = cls.objects.filter( e_conference=conference, visible=True).select_subclasses() <NEW_LINE> return [event for event in events if getattr(event, 'accepted', 3) == 3 and getattr(event, 'type', 'X') not in ('Volunteer', 'Rehearsal Slot', 'Staff Area')] <NEW_LINE> <DEDENT> @property <NEW_LINE> def event_type(self): <NEW_LINE> <INDENT> return self.__class__.__name__ <NEW_LINE> <DEDENT> @property <NEW_LINE> def sched_duration(self): <NEW_LINE> <INDENT> return self.duration <NEW_LINE> <DEDENT> @property <NEW_LINE> def calendar_type(self): <NEW_LINE> <INDENT> return calendar_for_event[self.__class__.__name__] <NEW_LINE> <DEDENT> @property <NEW_LINE> def get_tickets(self): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_current(self): <NEW_LINE> <INDENT> return self.e_conference.status == "upcoming" <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> ordering = ['e_title'] <NEW_LINE> app_label = "gbe"
Event is the base class for any scheduled happening at the expo. Events fall broadly into "shows" and "classes". Classes break down further into master classes, panels, workshops, etc. Shows are not biddable (though the Acts comprising them are) , but classes arise from participant bids.
62598fc8a219f33f346c6b4d
class ListModelTest(TestCase): <NEW_LINE> <INDENT> def test_get_absolute_url(self): <NEW_LINE> <INDENT> ls = List.objects.create() <NEW_LINE> self.assertEqual(ls.get_absolute_url(), '/lists/%d/' % (ls.id)) <NEW_LINE> <DEDENT> def test_lists_can_have_owners(self): <NEW_LINE> <INDENT> user = User.objects.create(email='a@b.com') <NEW_LINE> ls = List.objects.create(user=user) <NEW_LINE> self.assertIn(ls, user.list_set.all()) <NEW_LINE> <DEDENT> def test_list_owner_is_optional(self): <NEW_LINE> <INDENT> List.objects.create() <NEW_LINE> <DEDENT> def test_list_name_is_the_first_todo(self): <NEW_LINE> <INDENT> ls = List.objects.create() <NEW_LINE> Todo.objects.create(list=ls, task='first todo') <NEW_LINE> Todo.objects.create(list=ls, task='second todo') <NEW_LINE> self.assertEqual(ls.name, 'first todo') <NEW_LINE> <DEDENT> def test_create_new_creates_list_and_first_todo(self): <NEW_LINE> <INDENT> List.create_new(first_todo='new todo') <NEW_LINE> todo = Todo.objects.last() <NEW_LINE> ls = List.objects.last() <NEW_LINE> self.assertEqual(todo.task, 'new todo') <NEW_LINE> self.assertEqual(todo.list, ls) <NEW_LINE> <DEDENT> def test_create_new_optionally_saves_user(self): <NEW_LINE> <INDENT> user = User.objects.create() <NEW_LINE> List.create_new('new one', user=user) <NEW_LINE> ls = List.objects.last() <NEW_LINE> self.assertEqual(ls.user, user) <NEW_LINE> <DEDENT> def test_list_can_have_user(self): <NEW_LINE> <INDENT> List(user=User()) <NEW_LINE> <DEDENT> def test_list_attribute_user_is_optional(self): <NEW_LINE> <INDENT> List().full_clean() <NEW_LINE> <DEDENT> def test_create_new_returns_new_list_instance(self): <NEW_LINE> <INDENT> return_value = List.create_new('new') <NEW_LINE> ls = List.objects.last() <NEW_LINE> self.assertEqual(return_value, ls)
test_get_absolute_url: get_absolute_url 返回 /lists/<id>
62598fc84527f215b58ea214
class ActionIoFileOutbound(BaseAction): <NEW_LINE> <INDENT> def execute(self): <NEW_LINE> <INDENT> if self.active(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> outbound = str(self.properties['comms']['file'].get('outbound')) <NEW_LINE> smp = self.properties['comms']['file']['semaphore_extension'] <NEW_LINE> msg = self.properties['comms']['file']['message_extension'] <NEW_LINE> <DEDENT> except KeyError as e: <NEW_LINE> <INDENT> self.logger.error(f'Failed to read [comms][file] entries from properties. KeyError ({e})') <NEW_LINE> raise <NEW_LINE> <DEDENT> sql = self.dao.prepare_parameterised_statement( f'SELECT message_id, recipient, sender, sender_id, action, payload ' f'FROM messages WHERE processed = ? AND direction = ?' ) <NEW_LINE> results = self.dao.execute_sql_query( sql, ( 0, 'outbound' ) ) <NEW_LINE> if not results: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for record in results: <NEW_LINE> <INDENT> send_time = int(time.time()) <NEW_LINE> message = { "message_id": record[0], "recipient": record[1], "sender": record[2], "sender_id": record[3], "action": record[4], "payload": json.dumps(record[5]), "sent": send_time } <NEW_LINE> with open(f'{outbound}{os.path.sep}{record[1]}_{record[3]}{msg}', 'w') as file: <NEW_LINE> <INDENT> file.write(json.dumps(message)) <NEW_LINE> <DEDENT> with open(f'{outbound}{os.path.sep}{record[1]}_{record[3]}{smp}', 'w') as file: <NEW_LINE> <INDENT> file.write('') <NEW_LINE> <DEDENT> sql = self.dao.prepare_parameterised_statement( 'UPDATE messages SET sent = ?, processed = ?' ) <NEW_LINE> self.dao.execute_sql_statement( sql, ( send_time, 1 ) )
Scan the messages table in the control DB for outbound messages and create an outbound file if any found. MSG Format: CREATE TABLE messages ( message_id INTEGER NOT NULL PRIMARY KEY, -- Record ID in recipient messages table sender TEXT NOT NULL, -- Return address of sender sender_id INTEGER NOT NULL, -- Record ID in sender messages table action TEXT NOT NULL, -- Name of the action that handles this message payload TEXT, -- Json body of msg payload sent TEXT NOT NULL, -- Timestamp msg sent by sender received TEXT NOT NULL DEFAULT (strftime('%s', 'now')), -- Timestamp ism loaded message into database direction TEXT NOT NULL DEFAULT 'inbound', -- In or outbound message processed BOOLEAN NOT NULL DEFAULT '0' -- Has the message been processed ); File Name Format: <recipient>_<sender_id>.json
62598fc8ad47b63b2c5a7b9e
class User(db.Model): <NEW_LINE> <INDENT> name = db.StringProperty(required=True) <NEW_LINE> pw_hash = db.StringProperty(required=True) <NEW_LINE> email = db.StringProperty() <NEW_LINE> @classmethod <NEW_LINE> def by_id(cls, uid): <NEW_LINE> <INDENT> return User.get_by_id(uid, parent=users_key()) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def by_name(cls, name): <NEW_LINE> <INDENT> u = User.all().filter('name =', name).get() <NEW_LINE> return u <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def register(cls, name, pw, email=None): <NEW_LINE> <INDENT> pw_hash = make_pw_hash(name, pw) <NEW_LINE> return User(parent=users_key(), name=name, pw_hash=pw_hash, email=email) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def login(cls, name, pw): <NEW_LINE> <INDENT> u = cls.by_name(name) <NEW_LINE> if u and valid_pw(name, pw, u.pw_hash): <NEW_LINE> <INDENT> return u
Creates a user class in the datastore, and creates class methods for accessing users by id or by name, also class method for user login
62598fc8ab23a570cc2d4f10
class NoDataReturned(TrumbaException): <NEW_LINE> <INDENT> pass
Exception when there is empty data in the response
62598fc8ec188e330fdf8bda
class VersionController(wsgi.Controller): <NEW_LINE> <INDENT> def __init__(self, options): <NEW_LINE> <INDENT> self.options = options <NEW_LINE> <DEDENT> @utils.wrap_error <NEW_LINE> def get_version_info(self, req, file="version"): <NEW_LINE> <INDENT> resp = Response() <NEW_LINE> resp.charset = 'UTF-8' <NEW_LINE> if utils.is_xml_response(req): <NEW_LINE> <INDENT> resp_file = os.path.join(possible_topdir, "keystone/content/%s.xml.tpl" % file) <NEW_LINE> resp.content_type = "application/xml" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> resp_file = os.path.join(possible_topdir, "keystone/content/%s.json.tpl" % file) <NEW_LINE> resp.content_type = "application/json" <NEW_LINE> <DEDENT> hostname = req.environ.get("SERVER_NAME") <NEW_LINE> port = req.environ.get("SERVER_PORT") <NEW_LINE> resp.unicode_body = template.template(resp_file, HOST=hostname, PORT=port, API_VERSION=keystone.API_VERSION, API_VERSION_STATUS=keystone.API_VERSION_STATUS, API_VERSION_DATE=keystone.API_VERSION_DATE) <NEW_LINE> return resp
Controller for version related methods
62598fc8167d2b6e312b72bc
class TestSubprocessJob(TestQless): <NEW_LINE> <INDENT> def test_basic(self): <NEW_LINE> <INDENT> job = mock.Mock(data={ 'command': 'date' }, sandbox='/tmp') <NEW_LINE> SubprocessJob.process(job) <NEW_LINE> self.assertTrue(job.complete.called) <NEW_LINE> <DEDENT> def test_fails(self): <NEW_LINE> <INDENT> job = mock.Mock(data={ 'command': 'bash', 'args': ['-c', 'exit 1'], 'retry': False }, sandbox='/tmp') <NEW_LINE> SubprocessJob.process(job) <NEW_LINE> self.assertTrue(job.fail.called) <NEW_LINE> <DEDENT> def test_failure_message(self): <NEW_LINE> <INDENT> stderr = 'This is stderr' <NEW_LINE> stdout = 'This is stdout' <NEW_LINE> job = mock.Mock(data={ 'command': 'bash', 'args': ['-c', '(>&2 echo %s); echo %s; exit 1' % (stderr, stdout)], 'retry': False }, sandbox='/tmp') <NEW_LINE> SubprocessJob.process(job) <NEW_LINE> group, message = job.fail.call_args[0] <NEW_LINE> self.assertIn(stderr, message) <NEW_LINE> self.assertIn(stdout, message) <NEW_LINE> <DEDENT> def test_retries(self): <NEW_LINE> <INDENT> job = mock.Mock(data={ 'command': 'bash', 'args': ['-c', 'exit 1'] }, sandbox='/tmp') <NEW_LINE> SubprocessJob.process(job) <NEW_LINE> self.assertTrue(job.retry.called) <NEW_LINE> <DEDENT> def test_retry_failure_message(self): <NEW_LINE> <INDENT> stderr = 'This is stderr' <NEW_LINE> stdout = 'This is stdout' <NEW_LINE> job = mock.Mock(data={ 'command': 'bash', 'args': ['-c', '(>&2 echo %s); echo %s; exit 1' % (stderr, stdout)], 'delay': 10 }, sandbox='/tmp') <NEW_LINE> SubprocessJob.process(job) <NEW_LINE> delay, group, message = job.retry.call_args[0] <NEW_LINE> self.assertEqual(delay, 10) <NEW_LINE> self.assertEqual(group, 'subprocess-failed') <NEW_LINE> self.assertIn(stderr, message) <NEW_LINE> self.assertIn(stdout, message)
Test the SubprocesJob.
62598fc85fdd1c0f98e5e2d1
@parametric(metaclass=IterableMeta) <NEW_LINE> class _ParametricIterable: <NEW_LINE> <INDENT> pass
Parametric iterable type.
62598fc85fc7496912d4841c
class Solution(ThermoPhase, Kinetics, Transport): <NEW_LINE> <INDENT> __slots__ = ()
A class for chemically-reacting solutions. Instances can be created to represent any type of solution -- a mixture of gases, a liquid solution, or a solid solution, for example. Class `Solution` derives from classes `ThermoPhase`, `Kinetics`, and `Transport`. It defines no methods of its own, and is provided so that a single object can be used to compute thermodynamic, kinetic, and transport properties of a solution. To skip initialization of the Transport object, pass the keyword argument ``transport_model=None`` to the `Solution` constructor. The most common way to instantiate `Solution` objects is by using a phase definition, species and reactions defined in an input file:: gas = ct.Solution('gri30.cti') If an input file defines multiple phases, the phase *name* (in CTI) or *id* (in XML) can be used to specify the desired phase:: gas = ct.Solution('diamond.cti', 'gas') diamond = ct.Solution('diamond.cti', 'diamond') `Solution` objects can also be constructed using `Species` and `Reaction` objects which can themselves either be imported from input files or defined directly in Python:: spec = ct.Species.listFromFile('gri30.cti') rxns = ct.Reaction.listFromFile('gri30.cti') gas = ct.Solution(thermo='IdealGas', kinetics='GasKinetics', species=spec, reactions=rxns) where the ``thermo`` and ``kinetics`` keyword arguments are strings specifying the thermodynamic and kinetics model, respectively, and ``species`` and ``reactions`` keyword arguments are lists of `Species` and `Reaction` objects, respectively. For non-trivial uses cases of this functionality, see the examples `extract_submechanism.py <https://cantera.org/examples/python/extract_submechanism.py.html>`_ and `mechanism_reduction.py <https://cantera.org/examples/python/mechanism_reduction.py.html>`_. In addition, `Solution` objects can be constructed by passing the text of the CTI or XML phase definition in directly, using the ``source`` keyword argument:: cti_def = ''' ideal_gas(name='gas', elements='O H Ar', species='gri30: all', reactions='gri30: all', options=['skip_undeclared_elements', 'skip_undeclared_species', 'skip_undeclared_third_bodies'], initial_state=state(temperature=300, pressure=101325))''' gas = ct.Solution(source=cti_def)
62598fc87cff6e4e811b5d6d
class CppCodeGen(CodeGenVisitor): <NEW_LINE> <INDENT> def visit_CppInclude(self, node): <NEW_LINE> <INDENT> if node.angled_brackets: <NEW_LINE> <INDENT> return "#include <%s>" % node.target <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '#include "%s"' % node.target <NEW_LINE> <DEDENT> <DEDENT> def visit_CppComment(self, node): <NEW_LINE> <INDENT> return "// " + ("\n" + self._tab() + "// ").join( node.text.splitlines()) <NEW_LINE> <DEDENT> def visit_CppDefine(self, node): <NEW_LINE> <INDENT> params = ", ".join(map(str, node.params)) <NEW_LINE> return "#define %s(%s) (%s)" % (node.name, params, node.body)
Visitor to generate C preprocessor directives.
62598fc8656771135c4899b6
class Positions(object): <NEW_LINE> <INDENT> def __init__(self, filePath, umToPix): <NEW_LINE> <INDENT> if not os.path.exists(filePath): <NEW_LINE> <INDENT> filePath = os.sep.join( [merlin.POSITION_HOME, filePath]) <NEW_LINE> <DEDENT> self.umToPix = umToPix <NEW_LINE> self.data = pandas.read_csv(filePath, names = ["x", "y"]) <NEW_LINE> self.data = self.data * self.umToPix <NEW_LINE> <DEDENT> def get_fov_xy(self, fov): <NEW_LINE> <INDENT> return self.data.loc[fov,:].values.tolist() <NEW_LINE> <DEDENT> def get_fov_xy_um(self, fov): <NEW_LINE> <INDENT> return [x/self.umToPix for x in self.data.loc[fov,:].values.tolist()] <NEW_LINE> <DEDENT> def get_number_positions(self): <NEW_LINE> <INDENT> return self.data.shape[0]
Provides positions of simulated images.
62598fc8adb09d7d5dc0a8c1
class Lorem(Cli): <NEW_LINE> <INDENT> def ipsum(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def sit(self): <NEW_LINE> <INDENT> pass
Lorem ipsum is placeholder text commonly used for previewing layouts and visual mockups.
62598fc855399d3f0562685f
class EntityTypeFilter(object): <NEW_LINE> <INDENT> swagger_types = { 'relation_type': 'str', 'entity_types': 'list[str]' } <NEW_LINE> attribute_map = { 'relation_type': 'relationType', 'entity_types': 'entityTypes' } <NEW_LINE> def __init__(self, relation_type=None, entity_types=None): <NEW_LINE> <INDENT> self._relation_type = None <NEW_LINE> self._entity_types = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.relation_type = relation_type <NEW_LINE> self.entity_types = entity_types <NEW_LINE> <DEDENT> @property <NEW_LINE> def relation_type(self): <NEW_LINE> <INDENT> return self._relation_type <NEW_LINE> <DEDENT> @relation_type.setter <NEW_LINE> def relation_type(self, relation_type): <NEW_LINE> <INDENT> if relation_type is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `relation_type`, must not be `None`") <NEW_LINE> <DEDENT> self._relation_type = relation_type <NEW_LINE> <DEDENT> @property <NEW_LINE> def entity_types(self): <NEW_LINE> <INDENT> return self._entity_types <NEW_LINE> <DEDENT> @entity_types.setter <NEW_LINE> def entity_types(self, entity_types): <NEW_LINE> <INDENT> if entity_types is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `entity_types`, must not be `None`") <NEW_LINE> <DEDENT> allowed_values = ["TENANT", "CUSTOMER", "USER", "RULE", "PLUGIN", "DASHBOARD", "ASSET", "DEVICE", "ALARM"] <NEW_LINE> if not set(entity_types).issubset(set(allowed_values)): <NEW_LINE> <INDENT> raise ValueError( "Invalid values for `entity_types` [{0}], must be a subset of [{1}]" .format(", ".join(map(str, set(entity_types)-set(allowed_values))), ", ".join(map(str, allowed_values))) ) <NEW_LINE> <DEDENT> self._entity_types = entity_types <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in 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> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return 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, EntityTypeFilter): <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.
62598fc8a8370b77170f0721
class BoldElement(Element): <NEW_LINE> <INDENT> def __init__(self, subelements): <NEW_LINE> <INDENT> super(BoldElement, self).__init__(subelements)
An Element object that represents bolded text
62598fc8be7bc26dc9251ffe
class VolcanoPolygonBuildingFunctionMetadata(ImpactFunctionMetadata): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def as_dict(): <NEW_LINE> <INDENT> dict_meta = { 'id': 'VolcanoPolygonBuildingFunction', 'name': tr('Polygon volcano on buildings'), 'impact': tr('Be affected'), 'title': tr('Be affected'), 'function_type': 'old-style', 'author': 'AIFDR', 'date_implemented': 'N/A', 'overview': tr( 'To assess the impacts of volcano eruption on building.'), 'detailed_description': '', 'hazard_input': tr( 'The hazard layer must be a polygon layer. This layer ' 'must have an attribute representing the volcano hazard ' 'zone that can be specified in the impact function option. ' 'There are three classes low, medium, and high. The default ' 'values are "Kawasan Rawan Bencana I" for low, "Kawasan Rawan ' 'Bencana II" for medium, and "Kawasan Rawan Bencana III for ' 'high." If you want to see the name of the volcano in the ' 'result, you need to specify the volcano name attribute in ' 'the Impact Function options.'), 'exposure_input': tr( 'Vector polygon layer extracted from OSM where each ' 'polygon represents the footprint of a building.'), 'output': tr( 'Vector layer contains Map of building exposed to ' 'volcanic hazard zones for each Kawasan Rawan Bencana.'), 'actions': tr( 'Provide details about the number of buildings that are ' 'within each hazard zone.'), 'limitations': [], 'citations': [], 'layer_requirements': { 'hazard': { 'layer_mode': layer_mode_classified, 'layer_geometries': [layer_geometry_polygon], 'hazard_categories': [ hazard_category_multiple_event, hazard_category_single_event ], 'hazard_types': [hazard_volcano], 'continuous_hazard_units': [], 'vector_hazard_classifications': [ volcano_vector_hazard_classes], 'raster_hazard_classifications': [], 'additional_keywords': [ volcano_name_field] }, 'exposure': { 'layer_mode': layer_mode_classified, 'layer_geometries': [ layer_geometry_polygon, layer_geometry_point ], 'exposure_types': [exposure_structure], 'exposure_units': [], 'exposure_class_fields': [structure_class_field], 'additional_keywords': [] } }, 'parameters': OrderedDict([ ('postprocessors', OrderedDict([( 'BuildingType', building_type_postprocessor())])) ]) } <NEW_LINE> return dict_meta
Metadata for VolcanoPolygonBuildingFunctionMetadata. .. versionadded:: 2.1 We only need to re-implement as_dict(), all other behaviours are inherited from the abstract base class.
62598fc863b5f9789fe854bb
class Option(peewee.Model): <NEW_LINE> <INDENT> name = peewee.TextField() <NEW_LINE> poll = peewee.ForeignKeyField(Poll, related_name='related_poll') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> database = PSQL_DB
DB model for poll options
62598fc860cbc95b06364684
@RequestType.UNKNOWN <NEW_LINE> class UVRequest(object): <NEW_LINE> <INDENT> __slots__ = ['__weakref__', 'loop', 'finished', 'base_request'] <NEW_LINE> uv_request_type = None <NEW_LINE> uv_request_init = None <NEW_LINE> def __init__(self, loop, arguments, uv_handle=None, request_init=None): <NEW_LINE> <INDENT> self.loop = loop <NEW_LINE> self.finished = False <NEW_LINE> if self.loop.closed: <NEW_LINE> <INDENT> self.finished = True <NEW_LINE> raise error.ClosedLoopError() <NEW_LINE> <DEDENT> self.base_request = base.BaseRequest(self, self.loop.base_loop, self.__class__.uv_request_type, request_init or self.__class__.uv_request_init, arguments, uv_handle=uv_handle) <NEW_LINE> self.set_pending() <NEW_LINE> <DEDENT> @property <NEW_LINE> def type(self): <NEW_LINE> <INDENT> return RequestType(self.base_request.uv_request.type).cls <NEW_LINE> <DEDENT> def cancel(self): <NEW_LINE> <INDENT> code = self.base_request.cancel() <NEW_LINE> if code != error.StatusCodes.SUCCESS: <NEW_LINE> <INDENT> raise error.UVError(code) <NEW_LINE> <DEDENT> <DEDENT> def set_pending(self): <NEW_LINE> <INDENT> self.loop.structure_set_pending(self) <NEW_LINE> <DEDENT> def clear_pending(self): <NEW_LINE> <INDENT> self.loop.structure_clear_pending(self)
The base class of all libuv based requests. :raises uv.LoopClosedError: loop has already been closed :param loop: loop where the request should run on :param arguments: arguments passed to the libuv request initializer :param uv_handle: libuv handle the requests belongs to :param request_init: libuv function for request initialization :type loop: Loop :type arguments: tuple :type uv_handle: ffi.CData :type request_init: callable
62598fc8ad47b63b2c5a7ba0
class File: <NEW_LINE> <INDENT> def __init__(self, url: urls.URL, id=None, verified=0, hash=None): <NEW_LINE> <INDENT> self.url = url <NEW_LINE> self.id = id <NEW_LINE> self.verified = verified <NEW_LINE> self.hash = hash <NEW_LINE> self.folder = None <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "File[{}]({})".format(self.id or 'new', self.url) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'File({})'.format(self.url)
Representation of a tracked file in a Source.
62598fc8cc40096d6161a37b
class LruMemoryStrategy(BaseStrategy): <NEW_LINE> <INDENT> def __init__(self, maxsize=None, maxcount=None): <NEW_LINE> <INDENT> super(LruMemoryStrategy, self).__init__(maxsize, maxcount) <NEW_LINE> self._keys = [] <NEW_LINE> self._lock = threading.RLock() <NEW_LINE> self._log = get_logger(self) <NEW_LINE> <DEDENT> def reset(self, key): <NEW_LINE> <INDENT> raise NotImplemented() <NEW_LINE> <DEDENT> def handle_set(self, key, value): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> while key in self._keys: <NEW_LINE> <INDENT> self._keys.remove(key) <NEW_LINE> <DEDENT> self._keys.insert(0, key) <NEW_LINE> <DEDENT> <DEDENT> def handle_hit(self, key, value): <NEW_LINE> <INDENT> self.handle_set(key, value) <NEW_LINE> <DEDENT> def remove_keys(self, storage): <NEW_LINE> <INDENT> while self.is_excess(storage) and self._keys: <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> to_rm = self._keys.pop() <NEW_LINE> storage.delete(to_rm) <NEW_LINE> <DEDENT> self._log.debug(u'清理缓存: %r', to_rm)
Least recently used strategy
62598fc826068e7796d4cca3
class GiveItemForm(asb.forms.CSRFTokenForm): <NEW_LINE> <INDENT> pokemon = asb.forms.MultiSubmitField(coerce=int)
A form for choosing a Pokémon to give a particular item or use an item on.
62598fc8a05bb46b3848abb3