code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
@inherit_doc <NEW_LINE> class StringIndexer(JavaEstimator, HasInputCol, HasOutputCol, HasHandleInvalid, JavaMLReadable, JavaMLWritable): <NEW_LINE> <INDENT> @keyword_only <NEW_LINE> def __init__(self, inputCol=None, outputCol=None, handleInvalid="error"): <NEW_LINE> <INDENT> super(StringIndexer, self).__init__() <NEW_LINE> self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.StringIndexer", self.uid) <NEW_LINE> self._setDefault(handleInvalid="error") <NEW_LINE> kwargs = self._input_kwargs <NEW_LINE> self.setParams(**kwargs) <NEW_LINE> <DEDENT> @keyword_only <NEW_LINE> @since("1.4.0") <NEW_LINE> def setParams(self, inputCol=None, outputCol=None, handleInvalid="error"): <NEW_LINE> <INDENT> kwargs = self._input_kwargs <NEW_LINE> return self._set(**kwargs) <NEW_LINE> <DEDENT> def _create_model(self, java_model): <NEW_LINE> <INDENT> return StringIndexerModel(java_model)
A label indexer that maps a string column of labels to an ML column of label indices. If the input column is numeric, we cast it to string and index the string values. The indices are in [0, numLabels), ordered by label frequencies. So the most frequent label gets index 0. >>> stringIndexer = StringIndexer(inputCol="label", outputCol="indexed", handleInvalid='error') >>> model = stringIndexer.fit(stringIndDf) >>> td = model.transform(stringIndDf) >>> sorted(set([(i[0], i[1]) for i in td.select(td.id, td.indexed).collect()]), ... key=lambda x: x[0]) [(0, 0.0), (1, 2.0), (2, 1.0), (3, 0.0), (4, 0.0), (5, 1.0)] >>> inverter = IndexToString(inputCol="indexed", outputCol="label2", labels=model.labels) >>> itd = inverter.transform(td) >>> sorted(set([(i[0], str(i[1])) for i in itd.select(itd.id, itd.label2).collect()]), ... key=lambda x: x[0]) [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'a'), (4, 'a'), (5, 'c')] >>> stringIndexerPath = temp_path + "/string-indexer" >>> stringIndexer.save(stringIndexerPath) >>> loadedIndexer = StringIndexer.load(stringIndexerPath) >>> loadedIndexer.getHandleInvalid() == stringIndexer.getHandleInvalid() True >>> modelPath = temp_path + "/string-indexer-model" >>> model.save(modelPath) >>> loadedModel = StringIndexerModel.load(modelPath) >>> loadedModel.labels == model.labels True >>> indexToStringPath = temp_path + "/index-to-string" >>> inverter.save(indexToStringPath) >>> loadedInverter = IndexToString.load(indexToStringPath) >>> loadedInverter.getLabels() == inverter.getLabels() True .. versionadded:: 1.4.0
62598fa5a8ecb033258710d4
class Singleton(ManagedProperties): <NEW_LINE> <INDENT> def __init__(cls, name, bases, dict_): <NEW_LINE> <INDENT> super(Singleton, cls).__init__(cls, name, bases, dict_) <NEW_LINE> for ancestor in cls.mro(): <NEW_LINE> <INDENT> if '__new__' in ancestor.__dict__: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> if isinstance(ancestor, Singleton) and ancestor is not cls: <NEW_LINE> <INDENT> ctor = ancestor._new_instance <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ctor = cls.__new__ <NEW_LINE> <DEDENT> cls._new_instance = staticmethod(ctor) <NEW_LINE> the_instance = ctor(cls) <NEW_LINE> def __new__(cls): <NEW_LINE> <INDENT> return the_instance <NEW_LINE> <DEDENT> cls.__new__ = staticmethod(__new__) <NEW_LINE> setattr(S, name, the_instance) <NEW_LINE> def __getnewargs__(self): <NEW_LINE> <INDENT> return () <NEW_LINE> <DEDENT> cls.__getnewargs__ = __getnewargs__
Metaclass for singleton classes. A singleton class has only one instance which is returned every time the class is instantiated. Additionally, this instance can be accessed through the global registry object S as S.<class_name>. Examples ======== >>> from sympy import S, Basic >>> from sympy.core.singleton import Singleton >>> from sympy.core.compatibility import with_metaclass >>> class MySingleton(with_metaclass(Singleton, Basic)): ... pass >>> Basic() is Basic() False >>> MySingleton() is MySingleton() True >>> S.MySingleton is MySingleton() True ** Developer notes ** The class is instantiated immediately at the point where it is defined by calling cls.__new__(cls). This instance is cached and cls.__new__ is rebound to return it directly. The original constructor is also cached to allow subclasses to access it and have their own instance.
62598fa53539df3088ecc17a
class APITestCase(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> API.config['TESTING'] = True <NEW_LINE> self.API = API.test_client() <NEW_LINE> <DEDENT> def test_index(self): <NEW_LINE> <INDENT> expected = b'Infoset API v1.0 Operational.\n' <NEW_LINE> response = self.API.get('/infoset/api/v1/status') <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertEqual(response.data, expected)
Checks all functions and methods.
62598fa58e71fb1e983bb978
class toy(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> f = open('toy.txt') <NEW_LINE> self.f_content = json.loads(f.read()) <NEW_LINE> self.state = self.f_content['state'] <NEW_LINE> f.close() <NEW_LINE> <DEDENT> def on(self): <NEW_LINE> <INDENT> f = open('toy.txt','w') <NEW_LINE> self.f_content['state'] = 'ON' <NEW_LINE> f.write(json.dumps(self.f_content)) <NEW_LINE> f.close() <NEW_LINE> return 'The toy is ON' <NEW_LINE> <DEDENT> def off(self): <NEW_LINE> <INDENT> f = open('toy.txt','w') <NEW_LINE> self.f_content['state'] = 'OFF' <NEW_LINE> f.write(json.dumps(self.f_content)) <NEW_LINE> f.close() <NEW_LINE> return 'The toy is OFF' <NEW_LINE> <DEDENT> def check(self): <NEW_LINE> <INDENT> f = open('toy.txt','r') <NEW_LINE> self.f_content = json.loads(f.read()) <NEW_LINE> state = self.f_content['state'] <NEW_LINE> f.close() <NEW_LINE> return 'The toy is %s' % state
this class manages the state of the toy, that is simply a json
62598fa510dbd63aa1c70a77
class ForwarderCode(Forwarder): <NEW_LINE> <INDENT> name = 'use-code-string' <NEW_LINE> args_joiner = ':' <NEW_LINE> def __init__(self, script, func, *, modifier=None): <NEW_LINE> <INDENT> modifier = modifier or ModifierWsgi <NEW_LINE> super().__init__(modifier.code, script, func)
Forwards requests to nodes returned by a function. This allows using user defined functions to calculate. Function must accept key (domain). * http://uwsgi.readthedocs.io/en/latest/Fastrouter.html#way-5-fastrouter-use-code-string .. warning:: Remember to not put blocking code in your functions. The router is totally non-blocking, do not ruin it!
62598fa545492302aabfc396
class reify(object): <NEW_LINE> <INDENT> def __init__(self, wrapped): <NEW_LINE> <INDENT> self.wrapped = wrapped <NEW_LINE> try: <NEW_LINE> <INDENT> self.__doc__ = wrapped.__doc__ <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def __get__(self, inst, objtype=None): <NEW_LINE> <INDENT> if inst is None: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> val = self.wrapped(inst) <NEW_LINE> setattr(inst, self.wrapped.__name__, val) <NEW_LINE> return val
Use as a class method decorator. It operates almost exactly like the Python ``@property`` decorator, but it puts the result of the method it decorates into the instance dict after the first call, effectively replacing the function it decorates with an instance variable. It is, in Python parlance, a non-data descriptor. An example: .. code-block:: python class Foo(object): @reify def jammy(self): print('jammy called') return 1 And usage of Foo: >> f = Foo() >> v = f.jammy 'jammy called' >> print(v) 1 >> f.jammy 1 >> # jammy func not called the second time; it replaced itself with 1
62598fa52ae34c7f260aafa8
class DownloadZipError(bb.Union): <NEW_LINE> <INDENT> _catch_all = 'other' <NEW_LINE> too_large = None <NEW_LINE> too_many_files = None <NEW_LINE> other = None <NEW_LINE> @classmethod <NEW_LINE> def path(cls, val): <NEW_LINE> <INDENT> return cls('path', val) <NEW_LINE> <DEDENT> def is_path(self): <NEW_LINE> <INDENT> return self._tag == 'path' <NEW_LINE> <DEDENT> def is_too_large(self): <NEW_LINE> <INDENT> return self._tag == 'too_large' <NEW_LINE> <DEDENT> def is_too_many_files(self): <NEW_LINE> <INDENT> return self._tag == 'too_many_files' <NEW_LINE> <DEDENT> def is_other(self): <NEW_LINE> <INDENT> return self._tag == 'other' <NEW_LINE> <DEDENT> def get_path(self): <NEW_LINE> <INDENT> if not self.is_path(): <NEW_LINE> <INDENT> raise AttributeError("tag 'path' not set") <NEW_LINE> <DEDENT> return self._value <NEW_LINE> <DEDENT> def _process_custom_annotations(self, annotation_type, field_path, processor): <NEW_LINE> <INDENT> super(DownloadZipError, self)._process_custom_annotations(annotation_type, field_path, processor)
This class acts as a tagged union. Only one of the ``is_*`` methods will return true. To get the associated value of a tag (if one exists), use the corresponding ``get_*`` method. :ivar files.DownloadZipError.too_large: The folder or a file is too large to download. :ivar files.DownloadZipError.too_many_files: The folder has too many files to download.
62598fa5435de62698e9bcbb
class SelectionInitInterval(VegaLiteSchema): <NEW_LINE> <INDENT> _schema = {'$ref': '#/definitions/SelectionInitInterval'} <NEW_LINE> def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> super(SelectionInitInterval, self).__init__(*args, **kwds)
SelectionInitInterval schema wrapper anyOf(List([boolean, boolean]), List([float, float]), List([string, string]), List([:class:`DateTime`, :class:`DateTime`]))
62598fa54e4d5625663722eb
class PodSecurityPolicyList(_kuber_definitions.Collection): <NEW_LINE> <INDENT> def __init__( self, items: typing.List["PodSecurityPolicy"] = None, metadata: "ListMeta" = None, ): <NEW_LINE> <INDENT> super(PodSecurityPolicyList, self).__init__( api_version="policy/v1beta1", kind="PodSecurityPolicyList" ) <NEW_LINE> self._properties = { "items": items if items is not None else [], "metadata": metadata if metadata is not None else ListMeta(), } <NEW_LINE> self._types = { "apiVersion": (str, None), "items": (list, PodSecurityPolicy), "kind": (str, None), "metadata": (ListMeta, None), } <NEW_LINE> <DEDENT> @property <NEW_LINE> def items(self) -> typing.List["PodSecurityPolicy"]: <NEW_LINE> <INDENT> return typing.cast( typing.List["PodSecurityPolicy"], self._properties.get("items"), ) <NEW_LINE> <DEDENT> @items.setter <NEW_LINE> def items( self, value: typing.Union[typing.List["PodSecurityPolicy"], typing.List[dict]] ): <NEW_LINE> <INDENT> cleaned: typing.List[PodSecurityPolicy] = [] <NEW_LINE> for item in value: <NEW_LINE> <INDENT> if isinstance(item, dict): <NEW_LINE> <INDENT> item = typing.cast( PodSecurityPolicy, PodSecurityPolicy().from_dict(item), ) <NEW_LINE> <DEDENT> cleaned.append(typing.cast(PodSecurityPolicy, item)) <NEW_LINE> <DEDENT> self._properties["items"] = cleaned <NEW_LINE> <DEDENT> @property <NEW_LINE> def metadata(self) -> "ListMeta": <NEW_LINE> <INDENT> return typing.cast( "ListMeta", self._properties.get("metadata"), ) <NEW_LINE> <DEDENT> @metadata.setter <NEW_LINE> def metadata(self, value: typing.Union["ListMeta", dict]): <NEW_LINE> <INDENT> if isinstance(value, dict): <NEW_LINE> <INDENT> value = typing.cast( ListMeta, ListMeta().from_dict(value), ) <NEW_LINE> <DEDENT> self._properties["metadata"] = value <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_resource_api( api_client: client.ApiClient = None, **kwargs ) -> "client.PolicyV1beta1Api": <NEW_LINE> <INDENT> if api_client: <NEW_LINE> <INDENT> kwargs["apl_client"] = api_client <NEW_LINE> <DEDENT> return client.PolicyV1beta1Api(**kwargs) <NEW_LINE> <DEDENT> def __enter__(self) -> "PodSecurityPolicyList": <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_val, exc_tb): <NEW_LINE> <INDENT> return False
PodSecurityPolicyList is a list of PodSecurityPolicy objects.
62598fa57b25080760ed7371
class UnknownCommandError(ParserException): <NEW_LINE> <INDENT> pass
Called when an unknown command is used.
62598fa5a219f33f346c66df
class UpdateBarStatus(ql.QuerySpec): <NEW_LINE> <INDENT> args_spec = [ ('barID', ID), ('statusUpdate', StatusUpdate), ('authToken', str) ] <NEW_LINE> result_spec = [ ('bar_status', BarStatusResult), ] <NEW_LINE> @classmethod <NEW_LINE> def resolve(cls, args, result_fields): <NEW_LINE> <INDENT> userID = auth.validate_token(args['authToken']) <NEW_LINE> barID = args['barID'] <NEW_LINE> status_update = args['statusUpdate'] <NEW_LINE> if not profile.is_bar_owner(userID, barID): <NEW_LINE> <INDENT> raise ValueError("You have not been approved as an owner of this bar (yet).") <NEW_LINE> <DEDENT> if 'TakingOrders' in status_update: <NEW_LINE> <INDENT> model.upsert(model.Bars, model.BarStatus({ 'id': barID, 'taking_orders': status_update['TakingOrders'], })) <NEW_LINE> <DEDENT> if 'SetTableService' in status_update: <NEW_LINE> <INDENT> model.upsert(model.Bars, model.BarStatus({ 'id': barID, 'table_service': status_update['SetTableService'], })) <NEW_LINE> <DEDENT> if 'AddBar' in status_update: <NEW_LINE> <INDENT> command = status_update['AddBar'] <NEW_LINE> model.run( model.Bars.get(barID).update( model.BarStatus({ 'pickup_locations': { command['name']: { 'open': False, 'list_position': command['listPosition'], }, } }) ) ) <NEW_LINE> <DEDENT> if 'SetBarOpen' in status_update: <NEW_LINE> <INDENT> command = status_update['SetBarOpen'] <NEW_LINE> model.run( model.Bars.get(barID).update( model.BarStatus({ 'pickup_locations': { command['name']: { 'open': command['open'], }, } }) ) ) <NEW_LINE> <DEDENT> return UpdateBarStatus.make( BarStatus.query({'barID': barID}, result_fields) )
Change the bar status: - disable/enable order taking - disable/enable table service specify whether table service is available for food, drinks, or both - add a bar (for pickup) - open/close a bar (for pickup)
62598fa5e64d504609df931c
class BlendingTransformer: <NEW_LINE> <INDENT> def __init__(self, metric, maximize, optimizer='greedy'): <NEW_LINE> <INDENT> self.metric = metric <NEW_LINE> self.X = None <NEW_LINE> self.y = None <NEW_LINE> def _func(*weights): <NEW_LINE> <INDENT> return self.metric(self.y, np.average(self.X, axis=0, weights=weights)) <NEW_LINE> <DEDENT> if isinstance(optimizer, str): <NEW_LINE> <INDENT> if optimizer.lower() == 'pso': <NEW_LINE> <INDENT> self.optimizer = mlopt.optimization.ParticleSwarmOptimizer(func=_func, maximize=maximize) <NEW_LINE> <DEDENT> elif optimizer.lower() == 'greedy': <NEW_LINE> <INDENT> self.optimizer = mlopt.optimization.GreedyOptimizer(func=_func, maximize=maximize) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if hasattr(optimizer, 'optimize'): <NEW_LINE> <INDENT> self.optimizer = optimizer <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise AttributeError('Provided optimizer does not have a optimize method.') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def weights(self): <NEW_LINE> <INDENT> return self.optimizer.coords <NEW_LINE> <DEDENT> @property <NEW_LINE> def score(self): <NEW_LINE> <INDENT> return self.optimizer.score <NEW_LINE> <DEDENT> def fit(self, X, y, iterations=100, random_state=None, params=None): <NEW_LINE> <INDENT> self.X = X <NEW_LINE> self.y = y <NEW_LINE> if params is None: <NEW_LINE> <INDENT> params = {'x' + str(i): (0, 1) for i in range(np.shape(X)[0])} <NEW_LINE> <DEDENT> self.optimizer.optimize(params=params, iterations=iterations, random_state=random_state) <NEW_LINE> return self <NEW_LINE> <DEDENT> def transform(self, X): <NEW_LINE> <INDENT> return np.average(X, axis=0, weights=self.optimizer.coords) <NEW_LINE> <DEDENT> def fit_transform(self, X, y, **kwargs): <NEW_LINE> <INDENT> return self.fit(X=X, y=y, **kwargs).transform(X=X)
Optimizer to minimize or maximize an objective metric using Particle Swarm Optimization. :param metric: Callable function to optimize. :param maximize: Boolean indicating whether `metric` wants to be maximized or minimized. :param optimizer: Optimizer to use for optimizing blending weights. Can be either `greedy`, `pso` or a custom object with `optimize` method.
62598fa51b99ca400228f492
class AlphaBetaAgent(MultiAgentSearchAgent): <NEW_LINE> <INDENT> def getAction(self, gameState): <NEW_LINE> <INDENT> def min_value(state, depth, agent, alpha, beta): <NEW_LINE> <INDENT> if agent == state.getNumAgents(): <NEW_LINE> <INDENT> return max_value(state, depth + 1, 0, alpha, beta) <NEW_LINE> <DEDENT> val = None <NEW_LINE> for action in state.getLegalActions(agent): <NEW_LINE> <INDENT> next_state = min_value(state.generateSuccessor(agent, action), depth, agent + 1, alpha, beta) <NEW_LINE> val = next_state if val is None else min(val, next_state) <NEW_LINE> if alpha is not None and val < alpha: <NEW_LINE> <INDENT> return val <NEW_LINE> <DEDENT> beta = val if beta is None else min(beta, val) <NEW_LINE> <DEDENT> if val is None: <NEW_LINE> <INDENT> return self.evaluationFunction(state) <NEW_LINE> <DEDENT> return val <NEW_LINE> <DEDENT> def max_value(state, depth, agent, alpha, beta): <NEW_LINE> <INDENT> if depth > self.depth: <NEW_LINE> <INDENT> return self.evaluationFunction(state) <NEW_LINE> <DEDENT> val = None <NEW_LINE> for action in state.getLegalActions(agent): <NEW_LINE> <INDENT> next_state = min_value(state.generateSuccessor(agent, action), depth, agent + 1, alpha, beta) <NEW_LINE> val = max(val, next_state) <NEW_LINE> if beta is not None and val > beta: <NEW_LINE> <INDENT> return val <NEW_LINE> <DEDENT> alpha = max(alpha, val) <NEW_LINE> <DEDENT> if val is None: <NEW_LINE> <INDENT> return self.evaluationFunction(state) <NEW_LINE> <DEDENT> return val <NEW_LINE> <DEDENT> val, alpha, beta, best = None, None, None, None <NEW_LINE> for action in gameState.getLegalActions(0): <NEW_LINE> <INDENT> val = max(val, min_value(gameState.generateSuccessor(0, action), 1, 1, alpha, beta)) <NEW_LINE> if alpha is None: <NEW_LINE> <INDENT> alpha, best = val, action <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> alpha, best = max(val, alpha), action if val > alpha else best <NEW_LINE> <DEDENT> <DEDENT> return best <NEW_LINE> util.raiseNotDefined()
Your minimax agent with alpha-beta pruning (question 3)
62598fa52c8b7c6e89bd368b
class GreedyHeuristic(Heuristic): <NEW_LINE> <INDENT> def __init__(self, decoder_args, cache_estimates = True): <NEW_LINE> <INDENT> super(GreedyHeuristic, self).__init__() <NEW_LINE> self.cache_estimates = cache_estimates <NEW_LINE> self.decoder = GreedyDecoder(decoder_args) <NEW_LINE> self.cache = SimpleTrie() <NEW_LINE> <DEDENT> def set_predictors(self, predictors): <NEW_LINE> <INDENT> self.predictors = predictors <NEW_LINE> self.decoder.predictors = predictors <NEW_LINE> <DEDENT> def initialize(self, src_sentence): <NEW_LINE> <INDENT> self.cache = SimpleTrie() <NEW_LINE> <DEDENT> def estimate_future_cost(self, hypo): <NEW_LINE> <INDENT> if self.cache_estimates: <NEW_LINE> <INDENT> return self.estimate_future_cost_with_cache(hypo) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.estimate_future_cost_without_cache(hypo) <NEW_LINE> <DEDENT> <DEDENT> def estimate_future_cost_with_cache(self, hypo): <NEW_LINE> <INDENT> cached_cost = self.cache.get(hypo.trgt_sentence) <NEW_LINE> if not cached_cost is None: <NEW_LINE> <INDENT> return cached_cost <NEW_LINE> <DEDENT> old_states = self.decoder.get_predictor_states() <NEW_LINE> self.decoder.set_predictor_states(copy.deepcopy(old_states)) <NEW_LINE> trgt_word = hypo.trgt_sentence[-1] <NEW_LINE> scores = [] <NEW_LINE> words = [] <NEW_LINE> while trgt_word != utils.EOS_ID: <NEW_LINE> <INDENT> self.decoder.consume(trgt_word) <NEW_LINE> posterior,_ = self.decoder.apply_predictors() <NEW_LINE> trgt_word = utils.argmax(posterior) <NEW_LINE> scores.append(posterior[trgt_word]) <NEW_LINE> words.append(trgt_word) <NEW_LINE> <DEDENT> for i in range(1, len(scores)): <NEW_LINE> <INDENT> self.cache.add(hypo.trgt_sentence + words[:i], -sum(scores[i:])) <NEW_LINE> <DEDENT> self.decoder.set_predictor_states(old_states) <NEW_LINE> return -sum(scores) <NEW_LINE> <DEDENT> def estimate_future_cost_without_cache(self, hypo): <NEW_LINE> <INDENT> old_states = self.decoder.get_predictor_states() <NEW_LINE> self.decoder.set_predictor_states(copy.deepcopy(old_states)) <NEW_LINE> trgt_word = hypo.trgt_sentence[-1] <NEW_LINE> score = 0.0 <NEW_LINE> while trgt_word != utils.EOS_ID: <NEW_LINE> <INDENT> self.decoder.consume(trgt_word) <NEW_LINE> posterior,_ = self.decoder.apply_predictors() <NEW_LINE> trgt_word = utils.argmax(posterior) <NEW_LINE> score += posterior[trgt_word] <NEW_LINE> <DEDENT> self.decoder.set_predictor_states(old_states) <NEW_LINE> return -score
This heuristic performs greedy decoding to get future cost estimates. This is expensive but can lead to very close estimates.
62598fa597e22403b383add2
class Agent(object): <NEW_LINE> <INDENT> def __init__(self, agent_id,agent_type=None): <NEW_LINE> <INDENT> self.disposition=randint(low=0,high=2) <NEW_LINE> self.wealth=pareto(3.) <NEW_LINE> if type(agent_id) is not int: <NEW_LINE> <INDENT> raise ValueError("Agent IDs must be integers") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.my_id=agent_id <NEW_LINE> <DEDENT> self.adj_list=list() <NEW_LINE> if agent_type is None: <NEW_LINE> <INDENT> self.type=randint(low=0,high=5) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if type(agent_type)is int and agent_type>=0 and agent_type<5: <NEW_LINE> <INDENT> self.type=agent_type <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Agent type must be an int between 0 and 4") <NEW_LINE> <DEDENT> <DEDENT> self.contrib=None <NEW_LINE> self.mnet=None <NEW_LINE> <DEDENT> def make_tie(self, tie_agent): <NEW_LINE> <INDENT> self.adj_list.append(tie_agent.get_id()) <NEW_LINE> <DEDENT> def get_id(self): <NEW_LINE> <INDENT> return self.my_id <NEW_LINE> <DEDENT> def get_neighbors(self): <NEW_LINE> <INDENT> return self.adj_list <NEW_LINE> <DEDENT> def get_egonet(self, as_graph=False): <NEW_LINE> <INDENT> if as_graph: <NEW_LINE> <INDENT> return nx.Graph(data=zip([(self.my_id) for i in self.adj_list],self.adj_list)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return zip([self.get_id() for n in self.get_neighbors()],self.get_neighbors()) <NEW_LINE> <DEDENT> <DEDENT> def get_disposition(self): <NEW_LINE> <INDENT> return self.disposition <NEW_LINE> <DEDENT> def get_wealth(self): <NEW_LINE> <INDENT> return self.wealth <NEW_LINE> <DEDENT> def set_contrib(self,contrib_level): <NEW_LINE> <INDENT> if contrib_level>=0 and contrib_level <=1: <NEW_LINE> <INDENT> self.contrib=contrib_level <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Contribution level must be \in[0,1]") <NEW_LINE> <DEDENT> <DEDENT> def get_contrib(self): <NEW_LINE> <INDENT> return self.contrib <NEW_LINE> <DEDENT> def get_type(self): <NEW_LINE> <INDENT> return self.type <NEW_LINE> <DEDENT> def set_mnet(self,mnet): <NEW_LINE> <INDENT> self.mnet=mnet <NEW_LINE> <DEDENT> def get_mnet(self): <NEW_LINE> <INDENT> return self.mnet <NEW_LINE> <DEDENT> def info(self): <NEW_LINE> <INDENT> print("Agent: "+str(self.get_id())) <NEW_LINE> print("Wealth: "+str(self.get_wealth())) <NEW_LINE> print("Dispo: "+str(self.get_disposition())) <NEW_LINE> print("Type: "+str(self.get_type())) <NEW_LINE> print("Neigh: "+str(self.get_neighbors())) <NEW_LINE> print("Contrib: "+str(self.get_contrib()))
Agent objet Parameters agent_id: Unique integer identifier for each agent
62598fa50c0af96317c56249
class AudioEncoding(object): <NEW_LINE> <INDENT> ENCODING_UNSPECIFIED = 0 <NEW_LINE> LINEAR16 = 1 <NEW_LINE> FLAC = 2 <NEW_LINE> MULAW = 3 <NEW_LINE> AMR = 4 <NEW_LINE> AMR_WB = 5
Audio encoding of the data sent in the audio message. All encodings support only 1 channel (mono) audio. Only ``FLAC`` includes a header that describes the bytes of audio that follow the header. The other encodings are raw audio bytes with no header. For best results, the audio source should be captured and transmitted using a lossless encoding (``FLAC`` or ``LINEAR16``). Recognition accuracy may be reduced if lossy codecs (such as AMR, AMR_WB and MULAW) are used to capture or transmit the audio, particularly if background noise is present. Attributes: ENCODING_UNSPECIFIED (int): Not specified. Will return result ``google.rpc.Code.INVALID_ARGUMENT``. LINEAR16 (int): Uncompressed 16-bit signed little-endian samples (Linear PCM). This is the only encoding that may be used by ``AsyncRecognize``. FLAC (int): This is the recommended encoding for ``SyncRecognize`` and ``StreamingRecognize`` because it uses lossless compression; therefore recognition accuracy is not compromised by a lossy codec. The stream FLAC (Free Lossless Audio Codec) encoding is specified at: http://flac.sourceforge.net/documentation.html. 16-bit and 24-bit samples are supported. Not all fields in STREAMINFO are supported. MULAW (int): 8-bit samples that compand 14-bit audio samples using G.711 PCMU/mu-law. AMR (int): Adaptive Multi-Rate Narrowband codec. ``sample_rate`` must be 8000 Hz. AMR_WB (int): Adaptive Multi-Rate Wideband codec. ``sample_rate`` must be 16000 Hz.
62598fa532920d7e50bc5f1d
class ManagementPolicyVersion(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'tier_to_cool': {'key': 'tierToCool', 'type': 'DateAfterCreation'}, 'tier_to_archive': {'key': 'tierToArchive', 'type': 'DateAfterCreation'}, 'delete': {'key': 'delete', 'type': 'DateAfterCreation'}, } <NEW_LINE> def __init__( self, *, tier_to_cool: Optional["DateAfterCreation"] = None, tier_to_archive: Optional["DateAfterCreation"] = None, delete: Optional["DateAfterCreation"] = None, **kwargs ): <NEW_LINE> <INDENT> super(ManagementPolicyVersion, self).__init__(**kwargs) <NEW_LINE> self.tier_to_cool = tier_to_cool <NEW_LINE> self.tier_to_archive = tier_to_archive <NEW_LINE> self.delete = delete
Management policy action for blob version. :ivar tier_to_cool: The function to tier blob version to cool storage. Support blob version currently at Hot tier. :vartype tier_to_cool: ~azure.mgmt.storage.v2019_06_01.models.DateAfterCreation :ivar tier_to_archive: The function to tier blob version to archive storage. Support blob version currently at Hot or Cool tier. :vartype tier_to_archive: ~azure.mgmt.storage.v2019_06_01.models.DateAfterCreation :ivar delete: The function to delete the blob version. :vartype delete: ~azure.mgmt.storage.v2019_06_01.models.DateAfterCreation
62598fa5b7558d58954634f6
class Account: <NEW_LINE> <INDENT> def __init__(self, name, balance): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.balance = balance <NEW_LINE> print("Account created for " + self.name) <NEW_LINE> <DEDENT> def deposit(self, amount): <NEW_LINE> <INDENT> if amount > 0: <NEW_LINE> <INDENT> self.balance += amount <NEW_LINE> <DEDENT> <DEDENT> def withdraw(self, amount): <NEW_LINE> <INDENT> if amount > 0: <NEW_LINE> <INDENT> self.balance -= amount <NEW_LINE> <DEDENT> <DEDENT> def show_balance(self): <NEW_LINE> <INDENT> print("Balance is {}".format(self.balance))
Simple account class with balance
62598fa556b00c62f0fb2779
class Object(AvenewObject, EventObject): <NEW_LINE> <INDENT> repr = "representations.objects.ObjectRepr" <NEW_LINE> @lazy_property <NEW_LINE> def attributes(self): <NEW_LINE> <INDENT> return SharedAttributeHandler(self) <NEW_LINE> <DEDENT> @lazy_property <NEW_LINE> def types(self): <NEW_LINE> <INDENT> return TypeHandler(self) <NEW_LINE> <DEDENT> def return_appearance(self, looker): <NEW_LINE> <INDENT> for type in self.types: <NEW_LINE> <INDENT> if hasattr(type, "return_appearance"): <NEW_LINE> <INDENT> return type.return_appearance(looker)
Default objects.
62598fa5097d151d1a2c0eee
class Struct(_Object): <NEW_LINE> <INDENT> _keys = ("name", "body") <NEW_LINE> def __init__(self, name, body): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> self._body = body <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def body(self): <NEW_LINE> <INDENT> return self._body
struct.
62598fa5cb5e8a47e493c0db
class Actor(nn.Module): <NEW_LINE> <INDENT> def __init__(self, state_size, action_size, seed, fc1_units=400, fc2_units=300): <NEW_LINE> <INDENT> super(Actor, self).__init__() <NEW_LINE> self.seed = torch.manual_seed(seed) <NEW_LINE> self.fc1 = nn.Linear(state_size, fc1_units) <NEW_LINE> self.fc2 = nn.Linear(fc1_units, fc2_units) <NEW_LINE> self.fc3 = nn.Linear(fc2_units, action_size) <NEW_LINE> self.reset_parameters() <NEW_LINE> <DEDENT> def reset_parameters(self): <NEW_LINE> <INDENT> self.fc1.weight.data.uniform_(*hidden_init(self.fc1)) <NEW_LINE> self.fc2.weight.data.uniform_(*hidden_init(self.fc2)) <NEW_LINE> self.fc3.weight.data.uniform_(-3e-3, 3e-3) <NEW_LINE> <DEDENT> def forward(self, state): <NEW_LINE> <INDENT> x = F.relu(self.fc1(state)) <NEW_LINE> x = F.relu(self.fc2(x)) <NEW_LINE> return F.tanh(self.fc3(x))
Actor (Policy) Model.
62598fa556ac1b37e63020b4
class Corpora(Fragment): <NEW_LINE> <INDENT> def __init__(self, text, kind=""): <NEW_LINE> <INDENT> Fragment.PATTERN[Agregator.WORD_PATTERN] = Pattern() <NEW_LINE> super().__init__(text, kind) <NEW_LINE> <DEDENT> def tokenize(self): <NEW_LINE> <INDENT> gen_cnt, text_types = Z.GEN_CNT, Z.TXT_TYPES <NEW_LINE> self._kind = [] <NEW_LINE> _texts = list() <NEW_LINE> for x in text_types: <NEW_LINE> <INDENT> self._kind.extend([x] * gen_cnt) <NEW_LINE> <DEDENT> _corp = [TextC( open(os.path.join(os.path.join(Z.TXT_DIR, textype), _text), "r").read()[Z.TXT_OFF:Z.TXT_CUT], kind=textype, name=_text) for textype in text_types for _, _dir, _texts in os.walk(os.path.join(Z.TXT_DIR, textype)) for _, _text in zip(range(gen_cnt), _texts) ] <NEW_LINE> return _corp
Collection of texts representing a literate language
62598fa5d6c5a102081e200e
class UpnpStatusBinarySensor(UpnpEntity, BinarySensorEntity): <NEW_LINE> <INDENT> _attr_device_class = DEVICE_CLASS_CONNECTIVITY <NEW_LINE> def __init__( self, coordinator: UpnpDataUpdateCoordinator, ) -> None: <NEW_LINE> <INDENT> super().__init__(coordinator) <NEW_LINE> self._attr_name = f"{coordinator.device.name} wan status" <NEW_LINE> self._attr_unique_id = f"{coordinator.device.udn}_wanstatus" <NEW_LINE> <DEDENT> @property <NEW_LINE> def available(self) -> bool: <NEW_LINE> <INDENT> return super().available and self.coordinator.data.get(WANSTATUS) <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_on(self) -> bool: <NEW_LINE> <INDENT> return self.coordinator.data[WANSTATUS] == "Connected"
Class for UPnP/IGD binary sensors.
62598fa585dfad0860cbf9d8
class EnMob: <NEW_LINE> <INDENT> def __init__(self,lvl,health,a,d,g,iX,iY): <NEW_LINE> <INDENT> self.level = lvl <NEW_LINE> self.hp = health <NEW_LINE> self.attack = a <NEW_LINE> self.deff = d <NEW_LINE> self.gold = g <NEW_LINE> self.x = iX*32 <NEW_LINE> self.y = iY*32 <NEW_LINE> self.rect = pygame.Rect(self.x,self.y, 32,32) <NEW_LINE> self.limitXp = (iX*32)+32 <NEW_LINE> self.limitYp = (iY*32)+32 <NEW_LINE> self.limitXn = (iX*32)-32 <NEW_LINE> self.limitYn = (iY*32)-32 <NEW_LINE> self.step = 64 <NEW_LINE> self.adir = -1 <NEW_LINE> self.lastmove = 0 <NEW_LINE> self.moveopt = [0,1,2,3,4] <NEW_LINE> self.ismoving = False <NEW_LINE> self.countstep = 0 <NEW_LINE> <DEDENT> def draw(self,win): <NEW_LINE> <INDENT> if self.ismoving == False: <NEW_LINE> <INDENT> self.adir = randint(0,4) <NEW_LINE> self.premove() <NEW_LINE> <DEDENT> self.move() <NEW_LINE> self.lastmove = self.moveopt[self.adir] <NEW_LINE> pygame.draw.rect(win,(0,0,0),self.rect,2) <NEW_LINE> <DEDENT> def premove(self): <NEW_LINE> <INDENT> if self.lastmove == self.adir: <NEW_LINE> <INDENT> tmp = self.moveopt[::] <NEW_LINE> tmp.remove(self.lastmove) <NEW_LINE> rand = randint(0,3) <NEW_LINE> self.adir = tmp[rand] <NEW_LINE> <DEDENT> <DEDENT> def move(self): <NEW_LINE> <INDENT> self.ismoving = True <NEW_LINE> if self.adir == 0: <NEW_LINE> <INDENT> self.countstep +=1 <NEW_LINE> if self.countstep == self.step: <NEW_LINE> <INDENT> self.ismoving = False <NEW_LINE> self.countstep = 0 <NEW_LINE> <DEDENT> <DEDENT> if self.adir == 1: <NEW_LINE> <INDENT> self.rect.x -=1 <NEW_LINE> self.countstep +=1 <NEW_LINE> if self.countstep == self.step: <NEW_LINE> <INDENT> self.ismoving = False <NEW_LINE> self.countstep = 0 <NEW_LINE> <DEDENT> <DEDENT> if self.adir == 2: <NEW_LINE> <INDENT> self.rect.x +=1 <NEW_LINE> self.countstep +=1 <NEW_LINE> if self.countstep == self.step: <NEW_LINE> <INDENT> self.ismoving = False <NEW_LINE> self.countstep = 0 <NEW_LINE> <DEDENT> <DEDENT> if self.adir == 3: <NEW_LINE> <INDENT> self.rect.y -=1 <NEW_LINE> self.countstep +=1 <NEW_LINE> if self.countstep == self.step: <NEW_LINE> <INDENT> self.ismoving = False <NEW_LINE> self.countstep = 0 <NEW_LINE> <DEDENT> <DEDENT> if self.adir == 4: <NEW_LINE> <INDENT> self.rect.y +=1 <NEW_LINE> self.countstep +=1 <NEW_LINE> if self.countstep == self.step: <NEW_LINE> <INDENT> self.ismoving = False <NEW_LINE> self.countstep = 0 <NEW_LINE> <DEDENT> <DEDENT> if self.rect.x <= self.limitXn: <NEW_LINE> <INDENT> self.rect.left = self.limitXn <NEW_LINE> <DEDENT> if self.rect.x >= self.limitXp: <NEW_LINE> <INDENT> self.rect.right = self.limitXp+32 <NEW_LINE> <DEDENT> if self.rect.y <= self.limitYn: <NEW_LINE> <INDENT> self.rect.top = self.limitYn <NEW_LINE> <DEDENT> if self.rect.y >= self.limitYp: <NEW_LINE> <INDENT> self.rect.bottom = self.limitYp+32
This should be the class all other mobs inherit from: Level : lvl HP : health Attack : a Defense: d Gold : g Initial X: iX Initial Y: iY
62598fa591af0d3eaad39cd6
class VersionMismatchError(Error): <NEW_LINE> <INDENT> MDB_NAME = 'MDB_VERSION_MISMATCH'
Database environment version mismatch.
62598fa5009cb60464d013ec
class TilixExtension(Extension): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(TilixExtension, self).__init__() <NEW_LINE> self.subscribe(KeywordQueryEvent, KeywordQueryEventListener()) <NEW_LINE> self.subscribe(ItemEnterEvent, ItemEnterEventListener())
Main Extension Class
62598fa58e71fb1e983bb97a
class Update(db.Model): <NEW_LINE> <INDENT> query_class = VectorQuery <NEW_LINE> __tablename__ = 'updates' <NEW_LINE> pk_id = db.Column(db.Text(), primary_key=True) <NEW_LINE> date_created = db.Column(db.Date()) <NEW_LINE> title = db.Column(db.Text()) <NEW_LINE> tag = db.Column(db.Text()) <NEW_LINE> body = db.Column(db.Text()) <NEW_LINE> image_url = db.Column(db.Text()) <NEW_LINE> advisor_id = db.Column(db.Text, db.ForeignKey('advisors.pk_id')) <NEW_LINE> advisor = db.relationship('Advisor') <NEW_LINE> def __init__(self, **data): <NEW_LINE> <INDENT> self.pk_id = str(uuid.uuid4()) <NEW_LINE> self.date_created = date.today() <NEW_LINE> self.title = data.get('title', '') <NEW_LINE> self.tag = data.get('tag', '') <NEW_LINE> self.body = data.get('body', '') <NEW_LINE> self.image_url = data.get('image_url','') <NEW_LINE> self.advisor_id = data.get('advisor_id', None) <NEW_LINE> self.advisor = data.get('advisor', None) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return u'<{} - {} - {}>'.format(self.pk_id, self.title, self.date_created) <NEW_LINE> <DEDENT> def to_json(self): <NEW_LINE> <INDENT> return { "id": self.pk_id, "title": self.title, "date_created": self.date_created.strftime('%a %B %e, %Y'), "tag": self.tag, "body": self.body, "image_url": self.image_url, "author_id": { "id": self.advisor.pk_id, "email": self.advisor.email, "firstName": self.advisor.first_name or self.advisor.linkedin_first_name, "lastName": self.advisor.last_name or self.advisor.linkedin_last_name, "authorProfilePicUrl": self.advisor.profile_pic_url} if self.advisor is not None else {} }
Project class with initializer to document models
62598fa5f548e778e596b46c
class Projectile(Sprite): <NEW_LINE> <INDENT> def __init__(self, screen, hero, direc, current_spell): <NEW_LINE> <INDENT> pygame.sprite.Sprite.__init__(self) <NEW_LINE> self.screen = screen <NEW_LINE> self.direction = direc <NEW_LINE> self.fire = pygame.image.load('data/spells/Fire.png').convert_alpha() <NEW_LINE> self.water = pygame.image.load('data/spells/Water.png').convert_alpha() <NEW_LINE> self.air = pygame.image.load('data/spells/Air.png').convert_alpha() <NEW_LINE> self.dark = pygame.image.load('data/spells/Dark.png').convert_alpha() <NEW_LINE> spells = [pygame.transform.scale(self.air, (8, 8)), pygame.transform.scale(self.fire, (8, 8)), pygame.transform.scale(self.water, (8, 8)), pygame.transform.scale(self.dark, (8, 8))] <NEW_LINE> self.image = spells[current_spell] <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect.centerx = hero.rect.centerx <NEW_LINE> self.rect.centery = hero.rect.centery <NEW_LINE> self.name = 'projectile' <NEW_LINE> self.y = float(self.rect.y) <NEW_LINE> self.x = float(self.rect.x) <NEW_LINE> self.speed_factor = 160 <NEW_LINE> <DEDENT> def update(self, dt): <NEW_LINE> <INDENT> if self.direction == 'UP': <NEW_LINE> <INDENT> self.y -= self.speed_factor * dt <NEW_LINE> <DEDENT> elif self.direction == 'DOWN': <NEW_LINE> <INDENT> self.y += self.speed_factor * dt <NEW_LINE> <DEDENT> elif self.direction == 'RIGHT': <NEW_LINE> <INDENT> self.x += self.speed_factor * dt <NEW_LINE> <DEDENT> elif self.direction == 'LEFT': <NEW_LINE> <INDENT> self.x -= self.speed_factor * dt <NEW_LINE> <DEDENT> self.rect.y = self.y <NEW_LINE> self.rect.x = self.x <NEW_LINE> <DEDENT> def change_sprite(self, which): <NEW_LINE> <INDENT> if which == 1: <NEW_LINE> <INDENT> self.image = self.fire <NEW_LINE> <DEDENT> elif which == 2: <NEW_LINE> <INDENT> self.image == self.water <NEW_LINE> <DEDENT> elif which == 3: <NEW_LINE> <INDENT> self.image == self.air <NEW_LINE> <DEDENT> elif which == 4: <NEW_LINE> <INDENT> self.image == self.dark
A class to manage projectiles fired from the hero
62598fa510dbd63aa1c70a79
class FizzBuzz: <NEW_LINE> <INDENT> FIZZ = 'fizz' <NEW_LINE> BUZZ = 'buzz' <NEW_LINE> FIZZ_MULTIPLE = 3 <NEW_LINE> BUZZ_MULTIPLE = 5 <NEW_LINE> def get(self, number): <NEW_LINE> <INDENT> return self._calculate_output(number) <NEW_LINE> <DEDENT> def _calculate_output(self, number): <NEW_LINE> <INDENT> output = number <NEW_LINE> if self._is_fizz(number): <NEW_LINE> <INDENT> output = self.FIZZ <NEW_LINE> <DEDENT> if self._is_buzz(number): <NEW_LINE> <INDENT> if isinstance(output, str): <NEW_LINE> <INDENT> output += self.BUZZ <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> output = self.BUZZ <NEW_LINE> <DEDENT> <DEDENT> return output <NEW_LINE> <DEDENT> def _is_fizz(self, number): <NEW_LINE> <INDENT> return number % self.FIZZ_MULTIPLE == 0 <NEW_LINE> <DEDENT> def _is_buzz(self, number): <NEW_LINE> <INDENT> return number % self.BUZZ_MULTIPLE == 0
The FizzBuzz Game Class.
62598fa5b7558d58954634f7
class CellTimings ( object ): <NEW_LINE> <INDENT> def __init__ ( self, cell ): <NEW_LINE> <INDENT> self.cell = cell <NEW_LINE> self.drive = 0.0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def name ( self ): return self.cell.getName() <NEW_LINE> def __str__ ( self ): <NEW_LINE> <INDENT> return '<CellTimings "{}" drive:{}>'.format(self.name, self.drive)
Contains the timing data related to a Cell.
62598fa52c8b7c6e89bd368d
class Xml2Obj(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.root = None <NEW_LINE> self.nodeStack = [] <NEW_LINE> self.elementInventory=[] <NEW_LINE> <DEDENT> def StartElement(self, name, attributes): <NEW_LINE> <INDENT> import CC3DXML <NEW_LINE> element = CC3DXML.CC3DXMLElement(name.encode(), dictionaryToMapStrStr(attributes)) <NEW_LINE> if self.nodeStack: <NEW_LINE> <INDENT> parent = self.nodeStack[-1] <NEW_LINE> parent.addChild(element) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.root = element <NEW_LINE> <DEDENT> self.nodeStack.append(element) <NEW_LINE> self.elementInventory.append(element) <NEW_LINE> <DEDENT> def EndElement(self, name): <NEW_LINE> <INDENT> self.nodeStack.pop() <NEW_LINE> <DEDENT> def CharacterData(self, data): <NEW_LINE> <INDENT> if data.strip(): <NEW_LINE> <INDENT> data = data.encode() <NEW_LINE> element = self.nodeStack[-1] <NEW_LINE> element.cdata += data <NEW_LINE> <DEDENT> <DEDENT> def Parse(self, filename): <NEW_LINE> <INDENT> Parser = expat.ParserCreate() <NEW_LINE> Parser.StartElementHandler = self.StartElement <NEW_LINE> Parser.EndElementHandler = self.EndElement <NEW_LINE> Parser.CharacterDataHandler = self.CharacterData <NEW_LINE> file=open(filename) <NEW_LINE> ParserStatus = Parser.Parse(open(filename).read(),1) <NEW_LINE> file.close() <NEW_LINE> return self.root <NEW_LINE> <DEDENT> def ParseString(self, _string): <NEW_LINE> <INDENT> Parser = expat.ParserCreate() <NEW_LINE> Parser.StartElementHandler = self.StartElement <NEW_LINE> Parser.EndElementHandler = self.EndElement <NEW_LINE> Parser.CharacterDataHandler = self.CharacterData <NEW_LINE> ParserStatus = Parser.Parse(_string,1) <NEW_LINE> return self.root
XML to Object converter
62598fa5796e427e5384e65b
class Orbital(object): <NEW_LINE> <INDENT> def __init__(self, onsite, label): <NEW_LINE> <INDENT> self.onsite = onsite <NEW_LINE> self.label = label <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "{} with onsite {}\n".format(self.label, self.onsite)
Orbital object with a onsite energy
62598fa5236d856c2adc939f
class GeneratorAvailabilityRebid(GeneratorAvailabilityBid): <NEW_LINE> <INDENT> def __init__(self, sender_id, settlement_date, rebid_explanation='N/A', availability_bid_by_trading_interval_date=None): <NEW_LINE> <INDENT> super(GeneratorAvailabilityRebid, self).__init__(sender_id, settlement_date, availability_bid_by_trading_interval_date) <NEW_LINE> self.rebid_explanation = rebid_explanation
Defines a modification to a generator's availabilities per trading interval for a specified trading day, with an explanation of why the modification was made. The trading day is identified by the settlement day of the bid.
62598fa501c39578d7f12c48
class Rescale(object): <NEW_LINE> <INDENT> def __init__(self, output_size): <NEW_LINE> <INDENT> assert isinstance(output_size, (int, tuple)) <NEW_LINE> self.output_size = output_size <NEW_LINE> <DEDENT> def __call__(self, sample): <NEW_LINE> <INDENT> image, cls, label = sample['image'],sample['class'], sample['label'] <NEW_LINE> h, w = image.shape[:2] <NEW_LINE> if isinstance(self.output_size, int): <NEW_LINE> <INDENT> if h > w: <NEW_LINE> <INDENT> new_h, new_w = self.output_size * h / w, self.output_size <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_h, new_w = self.output_size, self.output_size * w / h <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> new_h, new_w = self.output_size <NEW_LINE> <DEDENT> new_h, new_w = int(new_h), int(new_w) <NEW_LINE> img = transform.resize(image, (new_h, new_w)) <NEW_LINE> return {'image': img, 'class': cls, 'label': label}
Rescale the image in a sample to a given size. Args: output_size (tuple or int): Desired output size. If tuple, output is matched to output_size. If int, smaller of image edges is matched to output_size keeping aspect ratio the same.
62598fa5379a373c97d98ed9
class PluginInterface: <NEW_LINE> <INDENT> def create_context(self): <NEW_LINE> <INDENT> return Context() <NEW_LINE> <DEDENT> def validate_args(self, args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_commands(self): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> def get_listeners(self): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> def get_magics(self): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> def get_opts_parser(self, add_help=True): <NEW_LINE> <INDENT> epilog = ( "NOTES: LIST types are given as comma separated values, " "eg. a,b,c,d. DICT types are given as semicolon separated " "key:value pairs (or key=value), e.g., a:b;c:d and if a dict " "takes a list as value it look like a:1,2;b:1" ) <NEW_LINE> opts_parser = argparse.ArgumentParser( description="A Generic Shell Utility", epilog=epilog, formatter_class=argparse.ArgumentDefaultsHelpFormatter, add_help=add_help, ) <NEW_LINE> opts_parser.add_argument( "--verbose", "-v", action="count", default=0, help="Increase verbosity, can be specified multiple times", ) <NEW_LINE> opts_parser.add_argument( "--stderr", "-s", action="store_true", help="By default the logging output goes to a " "temporary file. This disables this feature " "by sending the logging output to stderr", ) <NEW_LINE> opts_parser.add_argument( "--command-timeout", required=False, type=int, default=DEFAULT_COMMAND_TIMEOUT, help="Timeout for commands (default %ds)" % DEFAULT_COMMAND_TIMEOUT, ) <NEW_LINE> return opts_parser <NEW_LINE> <DEDENT> def get_completion_datasource_for_global_argument(self, name): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def get_status_bar(self, context): <NEW_LINE> <INDENT> return statusbar.StatusBar(context) <NEW_LINE> <DEDENT> def get_prompt_tokens(self, context: Context) -> List[Tuple[Any, str]]: <NEW_LINE> <INDENT> return context.get_prompt_tokens() <NEW_LINE> <DEDENT> def setup_logging(self, root_logger, args): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def create_usage_logger(self, context): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def getBlacklistPlugin(self): <NEW_LINE> <INDENT> return CommandBlacklist() <NEW_LINE> <DEDENT> def update_ipython_kwargs( self, ctx: Context, kwargs: MutableMapping[str, Any] ) -> None: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_session_logger(self, context): <NEW_LINE> <INDENT> return None
The PluginInterface class is a way to customize nubia for every customer use case. It allowes custom argument validation, control over command loading, custom context objects, and much more.
62598fa5435de62698e9bcbd
class Graph: <NEW_LINE> <INDENT> __slots__ = 'vertList', 'numVertices' <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.vertList = {} <NEW_LINE> self.numVertices = 0 <NEW_LINE> <DEDENT> def addVertex(self, vertex): <NEW_LINE> <INDENT> if self.getVertex(vertex.id) == None: <NEW_LINE> <INDENT> self.numVertices += 1 <NEW_LINE> <DEDENT> self.vertList[vertex.id] = vertex <NEW_LINE> <DEDENT> def getVertex(self, key): <NEW_LINE> <INDENT> if key in self.vertList: <NEW_LINE> <INDENT> return self.vertList[key] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def __contains__(self, key): <NEW_LINE> <INDENT> return key in self.vertList <NEW_LINE> <DEDENT> def addEdge(self, src, dest, cost=0): <NEW_LINE> <INDENT> if src not in self.vertList: <NEW_LINE> <INDENT> self.addVertex(src) <NEW_LINE> <DEDENT> if dest not in self.vertList: <NEW_LINE> <INDENT> self.addVertex(dest) <NEW_LINE> <DEDENT> self.vertList[src].addNeighbor(self.vertList[dest]) <NEW_LINE> <DEDENT> def getVertices(self): <NEW_LINE> <INDENT> return self.vertList.keys() <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self.vertList.values())
A graph implemented as an adjacency list of vertices. :slot: vertList (dict): A dictionary that maps a vertex key to a Vertex object :slot: numVertices (int): The total number of vertices in the graph
62598fa5d486a94d0ba2be96
class Movie(): <NEW_LINE> <INDENT> def __init__(self, movie_title, movie_poster, movie_trailer): <NEW_LINE> <INDENT> self.title = movie_title <NEW_LINE> self.poster_image_url = movie_poster <NEW_LINE> self.trailer_youtube_url = movie_trailer
A class representing a movie Attributes: Title Poster Trailer URL
62598fa57047854f4633f2a1
class UnloggedinCmdSet(default_cmds.UnloggedinCmdSet): <NEW_LINE> <INDENT> key = "DefaultUnloggedin" <NEW_LINE> def at_cmdset_creation(self): <NEW_LINE> <INDENT> super(UnloggedinCmdSet, self).at_cmdset_creation()
Command set available to the Session before being logged in. This holds commands like creating a new account, logging in, etc.
62598fa5aad79263cf42e69d
class WeChatComponentClient(WeChatClient): <NEW_LINE> <INDENT> def __init__(self, appid, component, access_token=None, refresh_token=None, session=None, timeout=None): <NEW_LINE> <INDENT> super(WeChatComponentClient, self).__init__( appid, '', access_token, session, timeout ) <NEW_LINE> self.appid = appid <NEW_LINE> self.component = component <NEW_LINE> if access_token: <NEW_LINE> <INDENT> self.session.set(self.access_token_key, access_token, 7200) <NEW_LINE> <DEDENT> if refresh_token: <NEW_LINE> <INDENT> self.session.set(self.refresh_token_key, refresh_token, 7200) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def access_token_key(self): <NEW_LINE> <INDENT> return '{0}_access_token'.format(self.appid) <NEW_LINE> <DEDENT> @property <NEW_LINE> def refresh_token_key(self): <NEW_LINE> <INDENT> return '{0}_refresh_token'.format(self.appid) <NEW_LINE> <DEDENT> @property <NEW_LINE> def access_token(self): <NEW_LINE> <INDENT> access_token = self.session.get(self.access_token_key) <NEW_LINE> if not access_token: <NEW_LINE> <INDENT> self.fetch_access_token() <NEW_LINE> access_token = self.session.get(self.access_token_key) <NEW_LINE> <DEDENT> return access_token <NEW_LINE> <DEDENT> @property <NEW_LINE> def refresh_token(self): <NEW_LINE> <INDENT> return self.session.get(self.refresh_token_key) <NEW_LINE> <DEDENT> def fetch_access_token(self): <NEW_LINE> <INDENT> expires_in = 7200 <NEW_LINE> result = self.component.refresh_authorizer_token( self.appid, self.refresh_token) <NEW_LINE> if 'expires_in' in result: <NEW_LINE> <INDENT> expires_in = result['expires_in'] <NEW_LINE> <DEDENT> self.session.set( self.access_token_key, result['authorizer_access_token'], expires_in ) <NEW_LINE> self.session.set( self.refresh_token_key, result['authorizer_refresh_token'], expires_in ) <NEW_LINE> self.expires_at = int(time.time()) + expires_in <NEW_LINE> return result
开放平台代公众号调用客户端
62598fa556ac1b37e63020b5
class OutputRedirector(threading.Thread): <NEW_LINE> <INDENT> def __init__(self, fileno, bufsize = 8192): <NEW_LINE> <INDENT> threading.Thread.__init__(self) <NEW_LINE> self.setDaemon(True) <NEW_LINE> self.__fileno = fileno <NEW_LINE> self.__bufsize = bufsize <NEW_LINE> <DEDENT> def getfile(self): <NEW_LINE> <INDENT> raise "Not implemented" <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> pushy.util.logger.debug("Entered output redirector") <NEW_LINE> try: <NEW_LINE> <INDENT> data = os.read(self.__fileno, self.__bufsize) <NEW_LINE> while len(data) > 0: <NEW_LINE> <INDENT> self.getfile().write(data) <NEW_LINE> data = os.read(self.__fileno, self.__bufsize) <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> self.getfile().flush() <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> pushy.util.logger.debug("Leaving output redirector") <NEW_LINE> pass
A class for reading data from a file and passing it to the "write" method of an object.
62598fa53539df3088ecc17d
class HostReachProtocolEnum(Enum): <NEW_LINE> <INDENT> bgp = 1 <NEW_LINE> @staticmethod <NEW_LINE> def _meta_info(): <NEW_LINE> <INDENT> from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_tunnel_nve_cfg as meta <NEW_LINE> return meta._meta_table['HostReachProtocolEnum']
HostReachProtocolEnum Host reach protocol .. data:: bgp = 1 Use BGP EVPN for VxLAN tunnel endpoint reachability
62598fa56e29344779b00525
class FormCriterion(object): <NEW_LINE> <INDENT> interface.implements(interfaces.IFormCriterion) <NEW_LINE> schema = atapi.Schema(( schemata.ATContentTypeSchema['title'], schemata.ATContentTypeSchema['description'], atapi.LinesField( 'formFields', widget=atapi.MultiSelectionWidget( label=u'Form Fields', description=( u'Select any fields for this criterion that should' u'appear on a search form'), format='checkbox')),)) <NEW_LINE> makeFormKey = form.makeFormKey <NEW_LINE> def Title(self): <NEW_LINE> <INDENT> return self.title or getToolByName(self, 'portal_atct').getFriendlyName( self.Field()) <NEW_LINE> <DEDENT> def getFormFieldValue(self, field_name, raw=False, REQUEST=None, **kw): <NEW_LINE> <INDENT> field = self.getField(field_name) <NEW_LINE> if field_name not in self.getFormFields(): <NEW_LINE> <INDENT> if raw: <NEW_LINE> <INDENT> return field.getRaw(self, **kw) <NEW_LINE> <DEDENT> return field.get(self, **kw) <NEW_LINE> <DEDENT> if REQUEST is None: <NEW_LINE> <INDENT> REQUEST = self.REQUEST <NEW_LINE> <DEDENT> full_name = self.makeFormKey(self.getId(), field_name) <NEW_LINE> form = dict( (key.replace(full_name, field_name, 1), REQUEST[key]) for key in REQUEST.keys() if key.startswith(full_name)) <NEW_LINE> if not form: <NEW_LINE> <INDENT> if raw: <NEW_LINE> <INDENT> return field.getRaw(self, **kw) <NEW_LINE> <DEDENT> return field.get(self, **kw) <NEW_LINE> <DEDENT> result = field.widget.process_form( self, field, form, empty_marker=missing, emptyReturnsMarker=True) <NEW_LINE> if result is missing: <NEW_LINE> <INDENT> if raw: <NEW_LINE> <INDENT> return field.getRaw(self, **kw) <NEW_LINE> <DEDENT> return field.get(self, **kw) <NEW_LINE> <DEDENT> value, mutator_kw = result <NEW_LINE> return value <NEW_LINE> <DEDENT> def Value(self, **kw): <NEW_LINE> <INDENT> return self.getFormFieldValue('value', **kw) <NEW_LINE> <DEDENT> def getRawValue(self, **kw): <NEW_LINE> <INDENT> return self.getFormFieldValue('value', raw=True, **kw) <NEW_LINE> <DEDENT> def getOperator(self, **kw): <NEW_LINE> <INDENT> return self.getFormFieldValue('operator', **kw)
A criterion that generates a search form field.
62598fa5aad79263cf42e69e
class Die(): <NEW_LINE> <INDENT> def __init__(self, num_sides=8): <NEW_LINE> <INDENT> self.num_sides = num_sides <NEW_LINE> <DEDENT> def roll(self): <NEW_LINE> <INDENT> return randint(1, self.num_sides)
A class representing a single die.
62598fa5435de62698e9bcbe
class ValidationError(SpecError): <NEW_LINE> <INDENT> def __init__(self, spec, *parts): <NEW_LINE> <INDENT> self.spec = spec <NEW_LINE> super().__init__(f'invalid value for {typename(spec)}', *parts)
Error raised when a value fails Spec validation.
62598fa58e7ae83300ee8f6a
class Subscriptionattr(object): <NEW_LINE> <INDENT> swagger_types = { 'msisdn': 'str', 'events': 'list[str]', 'carrier_name': 'str' } <NEW_LINE> attribute_map = { 'msisdn': 'msisdn', 'events': 'events', 'carrier_name': 'carrierName' } <NEW_LINE> def __init__(self, msisdn=None, events=None, carrier_name=None): <NEW_LINE> <INDENT> self._msisdn = None <NEW_LINE> self._events = None <NEW_LINE> self._carrier_name = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.msisdn = msisdn <NEW_LINE> self.events = events <NEW_LINE> self.carrier_name = carrier_name <NEW_LINE> <DEDENT> @property <NEW_LINE> def msisdn(self): <NEW_LINE> <INDENT> return self._msisdn <NEW_LINE> <DEDENT> @msisdn.setter <NEW_LINE> def msisdn(self, msisdn): <NEW_LINE> <INDENT> if msisdn is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `msisdn`, must not be `None`") <NEW_LINE> <DEDENT> self._msisdn = msisdn <NEW_LINE> <DEDENT> @property <NEW_LINE> def events(self): <NEW_LINE> <INDENT> return self._events <NEW_LINE> <DEDENT> @events.setter <NEW_LINE> def events(self, events): <NEW_LINE> <INDENT> if events is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `events`, must not be `None`") <NEW_LINE> <DEDENT> self._events = events <NEW_LINE> <DEDENT> @property <NEW_LINE> def carrier_name(self): <NEW_LINE> <INDENT> return self._carrier_name <NEW_LINE> <DEDENT> @carrier_name.setter <NEW_LINE> def carrier_name(self, carrier_name): <NEW_LINE> <INDENT> if carrier_name is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `carrier_name`, must not be `None`") <NEW_LINE> <DEDENT> self._carrier_name = carrier_name <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, Subscriptionattr): <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.
62598fa5eab8aa0e5d30bc52
class SuspicionOfHiding(Belief): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return "我觉得有人把 %s 藏起来了" % ( self.subject.render() )
This character suspects some other character of hiding this thing.
62598fa56fb2d068a7693d9a
class Robot(object): <NEW_LINE> <INDENT> def __init__(self, room, speed): <NEW_LINE> <INDENT> self.room = room <NEW_LINE> self.speed = speed <NEW_LINE> self.position = room.getRandomPosition() <NEW_LINE> self.d = random.randint(0, 359) <NEW_LINE> <DEDENT> def getRobotPosition(self): <NEW_LINE> <INDENT> return self.position <NEW_LINE> <DEDENT> def getRobotDirection(self): <NEW_LINE> <INDENT> return self.d <NEW_LINE> <DEDENT> def setRobotPosition(self, position): <NEW_LINE> <INDENT> self.position = position <NEW_LINE> <DEDENT> def setRobotDirection(self, direction): <NEW_LINE> <INDENT> self.d = direction <NEW_LINE> <DEDENT> def updatePositionAndClean(self): <NEW_LINE> <INDENT> raise NotImplementedError
Represents a robot cleaning a particular room. At all times the robot has a particular position and direction in the room. The robot also has a fixed speed. Subclasses of Robot should provide movement strategies by implementing updatePositionAndClean(), which simulates a single time-step.
62598fa5a79ad16197769f2b
class fhb(Base): <NEW_LINE> <INDENT> __tablename__ = 'fhb' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> data = Column(String)
SQLAlchemy Model DB Model
62598fa53eb6a72ae038a50e
class NotWithRule(Rule): <NEW_LINE> <INDENT> name = "not_with" <NEW_LINE> stop = True <NEW_LINE> def passes(self, field: str, value: Any, parameters: List[str], validator) -> bool: <NEW_LINE> <INDENT> other = parameters[0] <NEW_LINE> data = validator.data <NEW_LINE> self.message_fields = dict(field=field, other=other) <NEW_LINE> if not missing(data, field) and not missing(data, other): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> @property <NEW_LINE> def message(self) -> str: <NEW_LINE> <INDENT> return errors.NOT_WITH_ERROR
Not with other field
62598fa55f7d997b871f9345
class ThreadedHTTPServer(object): <NEW_LINE> <INDENT> def __init__(self, host, port, request_handler=SimpleHTTPRequestHandler): <NEW_LINE> <INDENT> socketserver.TCPServer.allow_reuse_address = True <NEW_LINE> self.server = socketserver.TCPServer((host, int(port)), request_handler) <NEW_LINE> self.server_thread = threading.Thread(target=self.server.serve_forever) <NEW_LINE> self.server_thread.daemon = True <NEW_LINE> self.server_thread.start() <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.server.shutdown() <NEW_LINE> self.server.server_close()
Runs SimpleHTTPServer in a thread Lets you start and stop an instance of SimpleHTTPServer.
62598fa5e5267d203ee6b7d7
class MapStdOut(MapStdX): <NEW_LINE> <INDENT> _func = "stdout"
An object that helps implement a map's sequence over its ``stdout``. Don't both instantiating one yourself: use the ``Map.stdout`` attribute instead.
62598fa53539df3088ecc17e
class Pvector(_Common): <NEW_LINE> <INDENT> _NAMES = ('pvector', 'frame', 'scalar') <NEW_LINE> def __init__(self, pvector, frame, scalar=None): <NEW_LINE> <INDENT> if scalar is None: <NEW_LINE> <INDENT> scalar = np.shape(pvector)[1] == 1 <NEW_LINE> <DEDENT> self.pvector = pvector <NEW_LINE> self.frame = frame <NEW_LINE> self.scalar = scalar <NEW_LINE> <DEDENT> def _is_equal_to(self, other, rtol=1e-12, atol=1e-14): <NEW_LINE> <INDENT> options = dict(rtol=rtol, atol=atol) <NEW_LINE> return (allclose(self.pvector, other.pvector, **options) and self.frame == other.frame) <NEW_LINE> <DEDENT> def to_ecef_vector(self): <NEW_LINE> <INDENT> n_frame = self.frame <NEW_LINE> p_AB_N = self.pvector <NEW_LINE> p_AB_E = mdot(n_frame.R_EN, p_AB_N[:, None, ...]).reshape(3, -1) <NEW_LINE> return ECEFvector(p_AB_E, frame=n_frame.nvector.frame, scalar=self.scalar) <NEW_LINE> <DEDENT> def to_nvector(self): <NEW_LINE> <INDENT> return self.to_ecef_vector().to_nvector() <NEW_LINE> <DEDENT> def to_geo_point(self): <NEW_LINE> <INDENT> return self.to_ecef_vector().to_geo_point() <NEW_LINE> <DEDENT> delta_to = _delta <NEW_LINE> @property <NEW_LINE> def length(self): <NEW_LINE> <INDENT> lengths = norm(self.pvector, axis=0) <NEW_LINE> if self.scalar: <NEW_LINE> <INDENT> return lengths[0] <NEW_LINE> <DEDENT> return lengths <NEW_LINE> <DEDENT> @property <NEW_LINE> def azimuth_deg(self): <NEW_LINE> <INDENT> return deg(self.azimuth) <NEW_LINE> <DEDENT> @property <NEW_LINE> def azimuth(self): <NEW_LINE> <INDENT> p_AB_N = self.pvector <NEW_LINE> if self.scalar: <NEW_LINE> <INDENT> return np.arctan2(p_AB_N[1], p_AB_N[0])[0] <NEW_LINE> <DEDENT> return np.arctan2(p_AB_N[1], p_AB_N[0]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def elevation_deg(self): <NEW_LINE> <INDENT> return deg(self.elevation) <NEW_LINE> <DEDENT> @property <NEW_LINE> def elevation(self): <NEW_LINE> <INDENT> z = self.pvector[2] <NEW_LINE> if self.scalar: <NEW_LINE> <INDENT> return np.arcsin(z / self.length)[0] <NEW_LINE> <DEDENT> return np.arcsin(z / self.length)
Geographical position given as cartesian position vector in a frame.
62598fa58c0ade5d55dc35f5
class NoAuthProvider(BaseProvider, abc.ABC): <NEW_LINE> <INDENT> async def authorize(self, *args, **kwargs): <NEW_LINE> <INDENT> pass
Provider that does not perform any global authorization (implementation must handle on each request)
62598fa576e4537e8c3ef476
class Zvijezda(RegularanIzraz): <NEW_LINE> <INDENT> def __init__(self, ri): <NEW_LINE> <INDENT> assert isinstance(ri, RegularanIzraz) <NEW_LINE> self.ispod = ri <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '{}*'.format(self.ispod) <NEW_LINE> <DEDENT> def prazan(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def trivijalan(self): <NEW_LINE> <INDENT> return self.ispod.trivijalan() <NEW_LINE> <DEDENT> def konačan(self): <NEW_LINE> <INDENT> return self.trivijalan() <NEW_LINE> <DEDENT> def korišteni_znakovi(self): <NEW_LINE> <INDENT> return self.ispod.korišteni_znakovi() <NEW_LINE> <DEDENT> def NKA(self, Σ=None): <NEW_LINE> <INDENT> if Σ is None: <NEW_LINE> <INDENT> Σ = self.korišteni_znakovi() <NEW_LINE> <DEDENT> return self.ispod.NKA(Σ).zvijezda() <NEW_LINE> <DEDENT> def enumerator(self): <NEW_LINE> <INDENT> yield from Unija(epsilon, Plus(self.ispod))
L* := ε ∪ L ∪ LL ∪ LLL ∪ ....
62598fa530dc7b766599f717
class TCWrongControllingSensorNumber(TemperatureControllerErrors): <NEW_LINE> <INDENT> def __init__(self, sensor_number): <NEW_LINE> <INDENT> self.code = 'ITCERROR5' <NEW_LINE> self.name = 'ITC_WRONG_SENSOR_NUMBER' <NEW_LINE> self.message = 'ERROR: The given value ({0:G}) for the controlling sensor number is out of the acceptable range (integers from 1 to 3).'.format(channel_number)
This error will be rised when the user tries to set the heater controlling sensor to a number outside the available sensor number range (integers from 1 to 3).
62598fa54e4d5625663722ee
class UnitCategoricalSample(CategoricalSample): <NEW_LINE> <INDENT> def __init__(self, k=1, seed=1): <NEW_LINE> <INDENT> super(UnitCategoricalSample, self).__init__(seed=seed) <NEW_LINE> self.k = k <NEW_LINE> <DEDENT> def sample(self, shape): <NEW_LINE> <INDENT> if self.k == shape[-1]: <NEW_LINE> <INDENT> return super(UnitCategoricalSample, self).sample(T.ones(shape) / self.k) <NEW_LINE> <DEDENT> raise ValueError("self.k and shape don't match.") <NEW_LINE> <DEDENT> def log_likelihood(self, samples): <NEW_LINE> <INDENT> return super(UnitCategoricalSample, self).log_likelihood(samples, T.ones_like(samples) / self.k)
Unit Categorical distribution
62598fa5e5267d203ee6b7d8
class ConvLSTMCell(tf.nn.rnn_cell.RNNCell): <NEW_LINE> <INDENT> def __init__(self, shape, filters, kernel, forget_bias=1.0, activation=tf.tanh, normalize=True, peephole=True, data_format='channels_last', reuse=None): <NEW_LINE> <INDENT> super(ConvLSTMCell, self).__init__(_reuse=reuse) <NEW_LINE> self._kernel = kernel <NEW_LINE> self._filters = filters <NEW_LINE> self._forget_bias = forget_bias <NEW_LINE> self._activation = activation <NEW_LINE> self._normalize = normalize <NEW_LINE> self._peephole = peephole <NEW_LINE> if data_format == 'channels_last': <NEW_LINE> <INDENT> self._size = tf.TensorShape(shape + [self._filters]) <NEW_LINE> self._feature_axis = self._size.ndims <NEW_LINE> self._data_format = None <NEW_LINE> <DEDENT> elif data_format == 'channels_first': <NEW_LINE> <INDENT> self._size = tf.TensorShape([self._filters] + shape) <NEW_LINE> self._feature_axis = 0 <NEW_LINE> self._data_format = 'NC' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Unknown data_format') <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def state_size(self): <NEW_LINE> <INDENT> return tf.nn.rnn_cell.LSTMStateTuple(self._size, self._size) <NEW_LINE> <DEDENT> @property <NEW_LINE> def output_size(self): <NEW_LINE> <INDENT> return self._size <NEW_LINE> <DEDENT> def call(self, x, state): <NEW_LINE> <INDENT> c, h = state <NEW_LINE> x = tf.concat([x, h], axis=self._feature_axis) <NEW_LINE> n = x.shape[-1].value <NEW_LINE> m = 4 * self._filters if self._filters > 1 else 4 <NEW_LINE> W = tf.get_variable('kernel', self._kernel + [n, m]) <NEW_LINE> y = tf.nn.convolution(x, W, 'SAME', data_format=self._data_format) <NEW_LINE> if not self._normalize: <NEW_LINE> <INDENT> y += tf.get_variable('bias', [m], initializer=tf.zeros_initializer()) <NEW_LINE> <DEDENT> j, i, f, o = tf.split(y, 4, axis=self._feature_axis) <NEW_LINE> if self._peephole: <NEW_LINE> <INDENT> i += tf.get_variable('W_ci', c.shape[1:]) * c <NEW_LINE> f += tf.get_variable('W_cf', c.shape[1:]) * c <NEW_LINE> <DEDENT> if self._normalize: <NEW_LINE> <INDENT> j = tf.contrib.layers.layer_norm(j) <NEW_LINE> i = tf.contrib.layers.layer_norm(i) <NEW_LINE> f = tf.contrib.layers.layer_norm(f) <NEW_LINE> <DEDENT> f = tf.sigmoid(f + self._forget_bias) <NEW_LINE> i = tf.sigmoid(i) <NEW_LINE> c = c * f + i * self._activation(j) <NEW_LINE> if self._peephole: <NEW_LINE> <INDENT> o += tf.get_variable('W_co', c.shape[1:]) * c <NEW_LINE> <DEDENT> if self._normalize: <NEW_LINE> <INDENT> o = tf.contrib.layers.layer_norm(o) <NEW_LINE> c = tf.contrib.layers.layer_norm(c) <NEW_LINE> <DEDENT> o = tf.sigmoid(o) <NEW_LINE> h = o * self._activation(c) <NEW_LINE> state = tf.nn.rnn_cell.LSTMStateTuple(c, h) <NEW_LINE> return h, state
From: https://github.com/carlthome/tensorflow-convlstm-cell/blob/master/cell.py A LSTM cell with convolutions instead of multiplications. Reference: Xingjian, S. H. I., et al. "Convolutional LSTM network: A machine learning approach for precipitation nowcasting." Advances in Neural Information Processing Systems. 2015.
62598fa5379a373c97d98edc
class ChimeraLoss(nn.Module): <NEW_LINE> <INDENT> def __init__(self, alpha=0.1): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> assert alpha >= 0, "Negative alpha values don't make sense." <NEW_LINE> assert alpha <= 1, "Alpha values above 1 don't make sense." <NEW_LINE> self.src_mse = PITLossWrapper(pairwise_mse, pit_from="pw_mtx") <NEW_LINE> self.alpha = alpha <NEW_LINE> <DEDENT> def forward(self, est_embeddings, target_indices, est_src=None, target_src=None, mix_spec=None): <NEW_LINE> <INDENT> if self.alpha != 0 and (est_src is None or target_src is None): <NEW_LINE> <INDENT> raise ValueError( "Expected target and estimated spectrograms to " "compute the PIT loss, found None." ) <NEW_LINE> <DEDENT> binary_mask = None <NEW_LINE> if mix_spec is not None: <NEW_LINE> <INDENT> binary_mask = ebased_vad(mix_spec) <NEW_LINE> <DEDENT> dc_loss = deep_clustering_loss( embedding=est_embeddings, tgt_index=target_indices, binary_mask=binary_mask ) <NEW_LINE> src_pit_loss = self.src_mse(est_src, target_src) <NEW_LINE> tot = self.alpha * dc_loss.mean() + (1 - self.alpha) * src_pit_loss <NEW_LINE> loss_dict = dict(dc_loss=dc_loss.mean(), pit_loss=src_pit_loss) <NEW_LINE> return tot, loss_dict
Combines Deep clustering loss and mask inference loss for ChimeraNet. Args: alpha (float): loss weight. Total loss will be : `alpha` * dc_loss + (1 - `alpha`) * mask_mse_loss.
62598fa5fff4ab517ebcd6af
class SecurityProfile(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'uefi_settings': {'key': 'uefiSettings', 'type': 'UefiSettings'}, 'encryption_at_host': {'key': 'encryptionAtHost', 'type': 'bool'}, 'security_type': {'key': 'securityType', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, uefi_settings: Optional["UefiSettings"] = None, encryption_at_host: Optional[bool] = None, security_type: Optional[Union[str, "SecurityTypes"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(SecurityProfile, self).__init__(**kwargs) <NEW_LINE> self.uefi_settings = uefi_settings <NEW_LINE> self.encryption_at_host = encryption_at_host <NEW_LINE> self.security_type = security_type
Specifies the Security profile settings for the virtual machine or virtual machine scale set. :ivar uefi_settings: Specifies the security settings like secure boot and vTPM used while creating the virtual machine. :code:`<br>`:code:`<br>`Minimum api-version: 2020-12-01. :vartype uefi_settings: ~azure.mgmt.compute.v2021_03_01.models.UefiSettings :ivar encryption_at_host: This property can be used by user in the request to enable or disable the Host Encryption for the virtual machine or virtual machine scale set. This will enable the encryption for all the disks including Resource/Temp disk at host itself. :code:`<br>`:code:`<br>` Default: The Encryption at host will be disabled unless this property is set to true for the resource. :vartype encryption_at_host: bool :ivar security_type: Specifies the SecurityType of the virtual machine. It is set as TrustedLaunch to enable UefiSettings. :code:`<br>`:code:`<br>` Default: UefiSettings will not be enabled unless this property is set as TrustedLaunch. Possible values include: "TrustedLaunch". :vartype security_type: str or ~azure.mgmt.compute.v2021_03_01.models.SecurityTypes
62598fa51b99ca400228f494
class RoleListView(SuperPermissionsMixin, DokumenListView): <NEW_LINE> <INDENT> template_name = 'role/list.html' <NEW_LINE> model = Role <NEW_LINE> context_object_name = 'role_data' <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> queryset = super(RoleListView, self).get_queryset() <NEW_LINE> return queryset
Role List View. Attributes: context_object_name (str): Description model (TYPE): Description template_name (str): Description
62598fa524f1403a92685818
class Quaggan: <NEW_LINE> <INDENT> def __init__(self, bot): <NEW_LINE> <INDENT> self.bot = bot; <NEW_LINE> self.settings = dataIO.load_json(SETTINGS) <NEW_LINE> <DEDENT> @commands.command(pass_context=True) <NEW_LINE> async def quaggan(self, ctx, *quag): <NEW_LINE> <INDENT> link = "https://api.guildwars2.com/v2/quaggans" <NEW_LINE> quagganList = eval(requests.get(link).text) <NEW_LINE> if quag == (): <NEW_LINE> <INDENT> qRand = quagganList[random.randint(0, len(quagganList))] <NEW_LINE> selectQuaggan = "https://api.guildwars2.com/v2/quaggans/{}".format(qRand) <NEW_LINE> link = selectQuaggan <NEW_LINE> qImage = eval(requests.get(link).text)["url"] <NEW_LINE> async with aiohttp.get(qImage) as image: <NEW_LINE> <INDENT> await self.bot.upload(io.BytesIO(await image.read()), filename=qImage) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> quag = "".join(quag) <NEW_LINE> selectQuaggan = "https://api.guildwars2.com/v2/quaggans/{}".format(quag) <NEW_LINE> nLink = selectQuaggan <NEW_LINE> qImage = eval(requests.get(nLink).text)["url"] <NEW_LINE> async with aiohttp.get(qImage) as image: <NEW_LINE> <INDENT> await self.bot.upload(io.BytesIO(await image.read()), filename=qImage) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @commands.command(pass_context=True) <NEW_LINE> async def quaggans(self, ctx): <NEW_LINE> <INDENT> link = "https://api.guildwars2.com/v2/quaggans" <NEW_LINE> quagganList = eval(requests.get(link).text) <NEW_LINE> qString = "" <NEW_LINE> for q in quagganList: <NEW_LINE> <INDENT> qString += ("*" + q.lower() + "*, ") <NEW_LINE> <DEDENT> embed = discord.Embed(colour=0x3399FF, description="") <NEW_LINE> embed.add_field(name="Quaggans", value=qString) <NEW_LINE> await self.bot.send_message(ctx.message.author, embed=embed)
Cog to give the calling user a specified or otherwise random picture of a quaggan
62598fa5adb09d7d5dc0a455
class trellis_paths(object): <NEW_LINE> <INDENT> def __init__(self,Ns,D): <NEW_LINE> <INDENT> self.Ns = Ns <NEW_LINE> self.decision_depth = D <NEW_LINE> self.traceback_states = np.zeros((Ns,self.decision_depth),dtype=int) <NEW_LINE> self.cumulative_metric = np.zeros((Ns,self.decision_depth),dtype=float) <NEW_LINE> self.traceback_bits = np.zeros((Ns,self.decision_depth),dtype=int)
A structure to hold the trellis paths in terms of traceback_states, cumulative_metrics, and traceback_bits. A full decision depth history of all this infomation is not essential, but does allow the graphical depiction created by the method traceback_plot(). Ns is the number of states = 2**(K-1) and D is the decision depth. As a rule, D should be about 5 times K.
62598fa556ac1b37e63020b7
class OutputRegister(Register): <NEW_LINE> <INDENT> pass
Semantic class for object generation
62598fa5ac7a0e7691f723d5
class WDBPunch: <NEW_LINE> <INDENT> def __init__(self, code=0, time=0): <NEW_LINE> <INDENT> self.code = code <NEW_LINE> self.time = time <NEW_LINE> <DEDENT> def parse_bytes(self, byte_array): <NEW_LINE> <INDENT> byteorder = get_wdb_byteorder() <NEW_LINE> self.code = int.from_bytes(byte_array[0:1], byteorder) <NEW_LINE> self.time = int.from_bytes(byte_array[4:8], byteorder) <NEW_LINE> <DEDENT> def get_bytes(self): <NEW_LINE> <INDENT> byteorder = get_wdb_byteorder() <NEW_LINE> code = 0 <NEW_LINE> if str(self.code).isdigit(): <NEW_LINE> <INDENT> code = int(self.code) <NEW_LINE> <DEDENT> return code.to_bytes(4, byteorder) + self.time.to_bytes(4, byteorder)
Class, describing 1 punch - code and time. Used for start, finish, check, clear and control point.
62598fa51f037a2d8b9e3fb5
class IsOwnerOrReadOnly(permissions.BasePermission): <NEW_LINE> <INDENT> def has_object_permission(self, request, view, obj): <NEW_LINE> <INDENT> if request.method in permissions.SAFE_METHODS: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if request.user.user_type == 'SystemAdmin': <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return obj.created_by == request.user.id
Object-level permission to only allow owners of an object to edit it. Assumes the model instance has an `created_by` attribute.
62598fa56e29344779b00527
class point_pillars_net(nn.Module): <NEW_LINE> <INDENT> def __init__(self, device=None): <NEW_LINE> <INDENT> super(point_pillars_net, self).__init__() <NEW_LINE> self.pillar_feature_net = pillar_feature_net() <NEW_LINE> self.backbone = backbone() <NEW_LINE> self.detection_head = detection_head() <NEW_LINE> if device: <NEW_LINE> <INDENT> self.pillar_feature_net.to(device) <NEW_LINE> self.backbone.to(device) <NEW_LINE> self.detection_head.to(device) <NEW_LINE> <DEDENT> <DEDENT> def forward(self, pillar_points, pillar_indices): <NEW_LINE> <INDENT> x = self.pillar_feature_net(pillar_points, pillar_indices) <NEW_LINE> x = self.backbone(x) <NEW_LINE> occ, loc, angle, size, heading, clf= self.detection_head(x) <NEW_LINE> return occ, loc, size, angle, heading, clf
overall model return: occ, loc, angle, size, heading, clf return shape: 4*252*252*(4, 4*3, 4, 4*3, 4, 4*4)
62598fa5b7558d58954634fa
class finalProcessedTweets(ndb.Model): <NEW_LINE> <INDENT> Tweet = ndb.StringProperty() <NEW_LINE> Job_List = ndb.StringProperty(repeated=True) <NEW_LINE> Company_Name = ndb.StringProperty() <NEW_LINE> Location = ndb.StringProperty() <NEW_LINE> Job_Url = ndb.StringProperty(repeated=True) <NEW_LINE> created_at = ndb.DateTimeProperty()
Define the Tweet model.
62598fa5d7e4931a7ef3bf66
class MatrixProductOperator(scipy.sparse.linalg.LinearOperator): <NEW_LINE> <INDENT> def __init__(self, A, B): <NEW_LINE> <INDENT> if A.ndim != 2 or B.ndim != 2: <NEW_LINE> <INDENT> raise ValueError('expected ndarrays representing matrices') <NEW_LINE> <DEDENT> if A.shape[1] != B.shape[0]: <NEW_LINE> <INDENT> raise ValueError('incompatible shapes') <NEW_LINE> <DEDENT> self.A = A <NEW_LINE> self.B = B <NEW_LINE> self.ndim = 2 <NEW_LINE> self.shape = (A.shape[0], B.shape[1]) <NEW_LINE> <DEDENT> def _matvec(self, x): <NEW_LINE> <INDENT> return np.dot(self.A, np.dot(self.B, x)) <NEW_LINE> <DEDENT> def _rmatvec(self, x): <NEW_LINE> <INDENT> return np.dot(np.dot(x, self.A), self.B) <NEW_LINE> <DEDENT> def _matmat(self, X): <NEW_LINE> <INDENT> return np.dot(self.A, np.dot(self.B, X)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def T(self): <NEW_LINE> <INDENT> return MatrixProductOperator(self.B.T, self.A.T)
This is purely for onenormest testing.
62598fa599cbb53fe6830da0
class FakeMetrics(object): <NEW_LINE> <INDENT> connection = None <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.calls = [] <NEW_LINE> <DEDENT> def meter(self, name, count): <NEW_LINE> <INDENT> self.calls.append(("meter", name, count)) <NEW_LINE> <DEDENT> def gauge(self, name, value): <NEW_LINE> <INDENT> self.calls.append(("gauge", name, value))
Fake Metrics object that records calls.
62598fa56fb2d068a7693d9b
class EmptyAnalysis(actions.Step): <NEW_LINE> <INDENT> NAME = "EmptyAnalysis" <NEW_LINE> DESCRIPTION = "Analyses nothing." <NEW_LINE> def __init__(self, project: Project, experiment_handle: ExperimentHandle): <NEW_LINE> <INDENT> super().__init__(obj=project, action_fn=self.analyze) <NEW_LINE> self.__experiment_handle = experiment_handle <NEW_LINE> <DEDENT> def analyze(self) -> actions.StepResult: <NEW_LINE> <INDENT> if not self.obj: <NEW_LINE> <INDENT> return actions.StepResult.ERROR <NEW_LINE> <DEDENT> project = self.obj <NEW_LINE> vara_result_folder = get_varats_result_folder(project) <NEW_LINE> for binary in project.binaries: <NEW_LINE> <INDENT> result_file = self.__experiment_handle.get_file_name( EmptyReport.shorthand(), project_name=str(project.name), binary_name=binary.name, project_revision=project.version_of_primary, project_uuid=str(project.run_uuid), extension_type=FSE.SUCCESS ) <NEW_LINE> run_cmd = touch["{res_folder}/{res_file}".format( res_folder=vara_result_folder, res_file=result_file )] <NEW_LINE> exec_func_with_pe_error_handler( run_cmd, create_default_analysis_failure_handler( self.__experiment_handle, project, EmptyReport, Path(vara_result_folder) ) ) <NEW_LINE> <DEDENT> return actions.StepResult.OK
Empty analysis step for testing.
62598fa556ac1b37e63020b8
class HomepageUI1(QWidget): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(HomepageUI1, self).__init__(*args, **kwargs) <NEW_LINE> layout = QVBoxLayout() <NEW_LINE> label = QLabel("期货分析助手", self) <NEW_LINE> label.setAlignment(Qt.AlignCenter) <NEW_LINE> label.setStyleSheet("color:rgb(250,20,10);font-size:30px") <NEW_LINE> layout.addWidget(label) <NEW_LINE> self.setLayout(layout) <NEW_LINE> <DEDENT> def paintEvent(self, event): <NEW_LINE> <INDENT> painter = QPainter(self) <NEW_LINE> painter.drawPixmap(self.rect(), QPixmap("media/home_bg.png"), QRect())
首页UI
62598fa526068e7796d4c824
class RunDeviceStreamRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Tids = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Tids = params.get("Tids")
RunDeviceStream请求参数结构体
62598fa56aa9bd52df0d4d95
class AkismetAPIError(Exception): <NEW_LINE> <INDENT> pass
Raised when there's an error with the Akismet API.
62598fa55fdd1c0f98e5de63
class Zip: <NEW_LINE> <INDENT> def create_zip(self, db, submission, request, logger, passwd=None, mat_dir=None, no_subdirs=None): <NEW_LINE> <INDENT> if db(db.material.leak_id==submission.id).select().first(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> filedir = str(db(db.submission.leak_id==submission.id).select( db.submission.dirname).first().dirname) <NEW_LINE> filedir = os.path.join(request.folder, "material", filedir) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> logger.error('create_zip: invalid filedir') <NEW_LINE> return dict(error='invalid filedir') <NEW_LINE> <DEDENT> err = None <NEW_LINE> try: <NEW_LINE> <INDENT> if not mat_dir: <NEW_LINE> <INDENT> mat_dir = filedir <NEW_LINE> <DEDENT> splitted = os.path.split(mat_dir) <NEW_LINE> if splitted[-1].isdigit(): <NEW_LINE> <INDENT> filedir = "%s-%s" % (splitted[-2], splitted[-1]) <NEW_LINE> <DEDENT> if no_subdirs: <NEW_LINE> <INDENT> save_file = filedir + "-0" <NEW_LINE> files = [f for f in os.listdir(mat_dir) if not os.path.isdir(os.path.join(mat_dir, f))] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> save_file = filedir <NEW_LINE> files = os.listdir(mat_dir) <NEW_LINE> <DEDENT> if passwd and os.path.exists(mat_dir): <NEW_LINE> <INDENT> logger.error('Encrypted ZIP function disabled, due to security redesign needs') <NEW_LINE> return 0 <NEW_LINE> <DEDENT> elif not passwd and os.path.exists(mat_dir): <NEW_LINE> <INDENT> zipf = zipfile.ZipFile(save_file+'.zip', 'w') <NEW_LINE> for f in files: <NEW_LINE> <INDENT> path = os.path.join(mat_dir, f) <NEW_LINE> zipf.write(path, f) <NEW_LINE> subdirs = os.walk(path) <NEW_LINE> for subdir in subdirs: <NEW_LINE> <INDENT> inner_subdir = os.path.split(subdir[0])[-1] <NEW_LINE> if not inner_subdir.isdigit(): <NEW_LINE> <INDENT> inner_subdir = "" <NEW_LINE> <DEDENT> for subfile in subdir[2]: <NEW_LINE> <INDENT> zipf.write(os.path.join(subdir[0], subfile), os.path.join(inner_subdir,subfile)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> logger.error('create_zip: invalid path') <NEW_LINE> <DEDENT> <DEDENT> except RuntimeError as err: <NEW_LINE> <INDENT> logger.error('create_zip: error in creating zip') <NEW_LINE> try: <NEW_LINE> <INDENT> zipf.close() <NEW_LINE> <DEDENT> except (RuntimeError, zipfile.error) as err: <NEW_LINE> <INDENT> logger.info('create_zip: error when trying to save zip') <NEW_LINE> <DEDENT> <DEDENT> except subprocess.CalledProcessError as err : <NEW_LINE> <INDENT> logger.error('create_zip: error in creating zip') <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> return dict(error=err) if err else None
Class that creates the material archive.
62598fa58a43f66fc4bf2048
class rule_103(single_space_between_tokens): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> single_space_between_tokens.__init__(self, 'loop_statement', '103', token.loop_label, token.label_colon) <NEW_LINE> self.solution = 'Ensure a single space between label and :.'
This rule checks if a label exists that a single space exists between the label and the colon. **Violation** .. code-block:: vhdl label: for index in 4 to 23 loop label : for index in 0 to 100 loop **Fix** .. code-block:: vhdl label : for index in 4 to 23 loop label : for index in 0 to 100 loop
62598fa53cc13d1c6d465637
class JsonResModelFormMixin(ModelFormMixin, JsonResponseMixin): <NEW_LINE> <INDENT> def form_valid(self, form): <NEW_LINE> <INDENT> self.object = form.save() <NEW_LINE> return self.render_json_to_response(status=1, msg='success') <NEW_LINE> <DEDENT> def form_invalid(self, form): <NEW_LINE> <INDENT> return self.render_json_to_response(status=0, msg=','.join(form.errors.popitem()[1]))
与 JsonResFormMixin 不同的是,这里封装的 form_valid 默认会调用 ModelForm 的 save() 方法做数据保存操作
62598fa5e5267d203ee6b7d9
class ClouderApplication(models.Model): <NEW_LINE> <INDENT> _name = 'clouder.application' <NEW_LINE> container_price_partner_month = fields.Float('Price partner/month') <NEW_LINE> container_price_user_month = fields.Float('Price partner/month') <NEW_LINE> container_price_user_payer = fields.Selection( [('partner', 'Partner'), ('user', 'User')], 'Payer for users') <NEW_LINE> service_price_partner_month = fields.Float('Price partner/month') <NEW_LINE> service_price_user_month = fields.Float('Price partner/month') <NEW_LINE> service_price_user_payer = fields.Selection( [('partner', 'Partner'), ('user', 'User')], 'Payer for users') <NEW_LINE> base_price_partner_month = fields.Float('Price partner/month') <NEW_LINE> base_price_user_month = fields.Float('Price partner/month') <NEW_LINE> base_price_user_payer = fields.Selection( [('partner', 'Partner'), ('user', 'User')], 'Payer for users')
Add the default price configuration in application.
62598fa5498bea3a75a579ee
class Camp(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=256) <NEW_LINE> start_at = models.DateTimeField() <NEW_LINE> end_at = models.DateTimeField() <NEW_LINE> created_at = models.DateTimeField(auto_now_add=True, null=True) <NEW_LINE> updated_at = models.DateTimeField(auto_now=True, null=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = 'camp' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return u'{}'.format(self.name)
Camp is the thing everyone goes to in the summer to have fun
62598fa54428ac0f6e6583ed
class ASPathList(object): <NEW_LINE> <INDENT> def __init__(self, list_id, access, as_paths): <NEW_LINE> <INDENT> assert isinstance(list_id, int) <NEW_LINE> assert isinstance(as_paths, Iterable) <NEW_LINE> assert isinstance(access, Access) <NEW_LINE> if not is_empty(as_paths): <NEW_LINE> <INDENT> for as_path in as_paths: <NEW_LINE> <INDENT> assert is_empty(as_path) or isinstance(as_path, int) <NEW_LINE> <DEDENT> <DEDENT> self._list_id = list_id <NEW_LINE> self._access = access <NEW_LINE> self._as_paths = as_paths <NEW_LINE> <DEDENT> @property <NEW_LINE> def list_id(self): <NEW_LINE> <INDENT> return self._list_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def access(self): <NEW_LINE> <INDENT> return self._access <NEW_LINE> <DEDENT> @property <NEW_LINE> def as_paths(self): <NEW_LINE> <INDENT> return self._as_paths <NEW_LINE> <DEDENT> @as_paths.setter <NEW_LINE> def as_paths(self, value): <NEW_LINE> <INDENT> if not is_empty(self._as_paths): <NEW_LINE> <INDENT> raise ValueError("AS Paths already set to %s" % self._as_paths) <NEW_LINE> <DEDENT> for as_path in value: <NEW_LINE> <INDENT> assert isinstance(as_path, int) <NEW_LINE> <DEDENT> self._as_paths = value <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ASPathList): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> path_eq = set(self.as_paths) == set(other.as_paths) <NEW_LINE> access_eq = self.access == other.access <NEW_LINE> id_eq = self.list_id == other.list_id <NEW_LINE> return id_eq and access_eq and path_eq <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "ASPathList(id=%s, access=%s, as_path=%s)" % (self.list_id, self.access, self.as_paths) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__str__()
Represents a list of as paths in a match
62598fa52ae34c7f260aafad
class MultiHeadAttention(nn.Module): <NEW_LINE> <INDENT> def __init__(self,d_model=512,n_heads=8,d_k=32,d_v=32,drop_out=0.): <NEW_LINE> <INDENT> super(MultiHeadAttention,self).__init__() <NEW_LINE> self.n_heads = n_heads <NEW_LINE> self.d_k = d_k <NEW_LINE> self.d_v = d_v <NEW_LINE> self.projections = nn.ModuleDict(dict([('q_proj',nn.Linear(d_model,d_k*n_heads)), ('k_proj',nn.Linear(d_model,d_k*n_heads)), ('v_proj',nn.Linear(d_model,d_v*n_heads))])) <NEW_LINE> self.attention = ScaledDotProductAttention(drop_out) <NEW_LINE> self.fc = nn.Linear(n_heads*d_v,d_model) <NEW_LINE> self.norm = nn.LayerNorm(d_model) <NEW_LINE> self.dropout = nn.Dropout(drop_out) <NEW_LINE> for k,m in self.projections.items(): <NEW_LINE> <INDENT> nn.init.xavier_normal_(m.weight) <NEW_LINE> <DEDENT> nn.init.xavier_normal_(self.fc.weight) <NEW_LINE> <DEDENT> def forward(self, q,k,v): <NEW_LINE> <INDENT> q_n,q_l,q_h =q.size() <NEW_LINE> k_n,k_l,k_h = k.size() <NEW_LINE> v_n,v_l,v_h = v.size() <NEW_LINE> assert k.size() == v.size(), 'key value must be same size' <NEW_LINE> residual = q <NEW_LINE> q_proj = self.projections['q_proj'](q).view(q_n, q_l, self.d_k, self.n_heads).permute(0,3,1,2) <NEW_LINE> k_proj = self.projections['k_proj'](k).view(k_n, k_l, self.d_k, self.n_heads).permute(0,3,1,2) <NEW_LINE> v_proj = self.projections['v_proj'](v).view(v_n, v_l, self.d_v, self.n_heads).permute(0,3,1,2) <NEW_LINE> q_proj = q_proj.contiguous().view(-1, q_l, self.d_k) <NEW_LINE> k_proj = k_proj.contiguous().view(-1, k_l, self.d_k) <NEW_LINE> v_proj = v_proj.contiguous().view(-1, v_l, self.d_v) <NEW_LINE> mulhead_out = self.attention(q_proj,k_proj,v_proj) <NEW_LINE> mulhead_out=mulhead_out.view(q_n,self.n_heads,q_l,self.d_k).permute(0,2,1,3) <NEW_LINE> mulhead_out = mulhead_out.contiguous().view(q_n,q_l,-1) <NEW_LINE> mulhead_out = self.dropout(mulhead_out) <NEW_LINE> fc = self.fc(mulhead_out) <NEW_LINE> ret = self.norm(fc+residual) <NEW_LINE> return ret
implementation multihead attention
62598fa53d592f4c4edbad99
class Chain(_msys.Chain): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> def __init__(self, ptr, id): <NEW_LINE> <INDENT> super().__init__(ptr, id) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<Chain %s>" % self.name <NEW_LINE> <DEDENT> @property <NEW_LINE> def system(self): <NEW_LINE> <INDENT> return System(self._ptr) <NEW_LINE> <DEDENT> def addResidue(self): <NEW_LINE> <INDENT> return Residue(self._ptr, super().addResidue()) <NEW_LINE> <DEDENT> @property <NEW_LINE> def residues(self): <NEW_LINE> <INDENT> return [Residue(self._ptr, i) for i in super().residues()] <NEW_LINE> <DEDENT> def selectResidue(self, resid=None, name=None, insertion=None): <NEW_LINE> <INDENT> residues = [ r for r in self.residues if (resid is None or r.resid == resid) and (name is None or r.name == name) and (insertion is None or r.insertion == insertion) ] <NEW_LINE> if not residues: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if len(residues) == 1: <NEW_LINE> <INDENT> return residues[0] <NEW_LINE> <DEDENT> raise ValueError( "Found %d residues with given resid, name or insertion" % (len(residues)) ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def ct(self): <NEW_LINE> <INDENT> return Ct(self._ptr, self.ctId()) <NEW_LINE> <DEDENT> @ct.setter <NEW_LINE> def ct(self, ct): <NEW_LINE> <INDENT> self.setCtId(ct.id)
Represents a chain (of Residues) in a System
62598fa5d268445f26639ae9
class HumanAgent(Agent): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(HumanAgent).__init__() <NEW_LINE> self._is_on_reverse = False <NEW_LINE> <DEDENT> def _get_keyboard_control(self, keys): <NEW_LINE> <INDENT> control = VehicleControl() <NEW_LINE> if keys[K_LEFT] or keys[K_a]: <NEW_LINE> <INDENT> control.steer = -1.0 <NEW_LINE> <DEDENT> if keys[K_RIGHT] or keys[K_d]: <NEW_LINE> <INDENT> control.steer = 1.0 <NEW_LINE> <DEDENT> if keys[K_UP] or keys[K_w]: <NEW_LINE> <INDENT> control.throttle = 1.0 <NEW_LINE> <DEDENT> if keys[K_DOWN] or keys[K_s]: <NEW_LINE> <INDENT> control.brake = 1.0 <NEW_LINE> <DEDENT> if keys[K_SPACE]: <NEW_LINE> <INDENT> control.hand_brake = True <NEW_LINE> <DEDENT> if keys[K_q]: <NEW_LINE> <INDENT> self._is_on_reverse = not self._is_on_reverse <NEW_LINE> <DEDENT> control.reverse = self._is_on_reverse <NEW_LINE> return control <NEW_LINE> <DEDENT> def run_step(self, measurements, sensor_data, directions, target): <NEW_LINE> <INDENT> for event in pygame.event.get(): <NEW_LINE> <INDENT> if event.type == pygame.QUIT: <NEW_LINE> <INDENT> return VehicleControl() <NEW_LINE> <DEDENT> <DEDENT> return self._get_keyboard_control(pygame.key.get_pressed())
Derivation of Agent Class for human control,
62598fa510dbd63aa1c70a7c
class RestrictedCharFieldAccessor(FieldAccessor): <NEW_LINE> <INDENT> def __set__(self, instance: Model, value: Optional[str]): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> return super().__set__(instance, value) <NEW_LINE> <DEDENT> return super().__set__(instance, self.field.check(value))
Accessor class for HTML data.
62598fa5236d856c2adc93a1
class disable(): <NEW_LINE> <INDENT> def __init__(self, region_name=""): <NEW_LINE> <INDENT> self.region_name = region_name <NEW_LINE> if region_name == "": <NEW_LINE> <INDENT> self.user_region_name = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.user_region_name = True <NEW_LINE> <DEDENT> self.module_name = "" <NEW_LINE> self.func = None <NEW_LINE> <DEDENT> def _recreate_cm(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __call__(self, func): <NEW_LINE> <INDENT> self.__enter__() <NEW_LINE> try: <NEW_LINE> <INDENT> @functools.wraps(func) <NEW_LINE> def inner(*args, **kwds): <NEW_LINE> <INDENT> with self._recreate_cm(): <NEW_LINE> <INDENT> return func(*args, **kwds) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> self.__exit__() <NEW_LINE> <DEDENT> return inner <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self.tracer_registered = get_instrumenter().get_registered() <NEW_LINE> if self.tracer_registered: <NEW_LINE> <INDENT> get_instrumenter().unregister() <NEW_LINE> if self.user_region_name: <NEW_LINE> <INDENT> self.module_name = "user_instrumenter" <NEW_LINE> frame = inspect.currentframe().f_back <NEW_LINE> file_name = frame.f_globals.get('__file__', None) <NEW_LINE> line_number = frame.f_lineno <NEW_LINE> if file_name is not None: <NEW_LINE> <INDENT> full_file_name = os.path.abspath(file_name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> full_file_name = "None" <NEW_LINE> <DEDENT> get_instrumenter().region_begin( self.module_name, self.region_name, full_file_name, line_number) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __exit__(self, exc_type=None, exc_value=None, traceback=None): <NEW_LINE> <INDENT> if self.tracer_registered: <NEW_LINE> <INDENT> if self.user_region_name: <NEW_LINE> <INDENT> get_instrumenter().region_end( self.module_name, self.region_name) <NEW_LINE> <DEDENT> get_instrumenter().register()
Context manager to disable tracing in a certain region: ``` with disable(): do stuff ``` This overides --noinstrumenter (--nopython legacy) If a region name is given, the region the contextmanager is active will be marked in the trace or profile
62598fa530dc7b766599f719
class KNACSource(PersonSource): <NEW_LINE> <INDENT> pass
An automobile club
62598fa54e4d5625663722f0
class Singleton(object): <NEW_LINE> <INDENT> _instance = None <NEW_LINE> def __new__(cls, *args, **kwargs): <NEW_LINE> <INDENT> if not Singleton._instance: <NEW_LINE> <INDENT> Singleton._instance = super(Singleton, cls).__new__(cls, *args, **kwargs) <NEW_LINE> <DEDENT> return Singleton._instance
Classic Singleton
62598fa57b25080760ed7377
class create_prod_dict: <NEW_LINE> <INDENT> def __init__(self, df, key_colName='ProductId', val_colName='ProductName', val_colName_2='CSPC', val_colName_3='UnitSizeML', val_colName_4='RetailPrice'): <NEW_LINE> <INDENT> self.df = df <NEW_LINE> self.key = key_colName <NEW_LINE> self.val = val_colName <NEW_LINE> self.val_2 = val_colName_2 <NEW_LINE> self.val_3 = val_colName_3 <NEW_LINE> self.val_4 = val_colName_4 <NEW_LINE> <DEDENT> def create_dict(self): <NEW_LINE> <INDENT> product_dict = {} <NEW_LINE> for i in self.df[self.key].unique(): <NEW_LINE> <INDENT> product_dict[i] = [('Name', self.df.loc[self.df[self.key] == i, self.val].unique()[0]), ('CSPC', self.df.loc[self.df[self.key] == i, self.val_2].unique()[0]), ('Size ml', self.df.loc[self.df[self.key] == i, self.val_3].unique()[0]), ('Price', self.df.loc[self.df[self.key] == i, self.val_4].unique()[0]), ] <NEW_LINE> <DEDENT> return product_dict
Create a dictionary based on a dataframe, key, and value column names
62598fa5be8e80087fbbef2e
class MeasureS21(MeasureActiveReactive): <NEW_LINE> <INDENT> @property <NEW_LINE> def values(self): <NEW_LINE> <INDENT> values = {} <NEW_LINE> try: <NEW_LINE> <INDENT> get = self.objectified.get <NEW_LINE> values = self.active_reactive(self.objectified, 'a') <NEW_LINE> values.update( { 'timestamp': self._get_timestamp('Fh'), 'active_quadrant': get_integer_value(get('Ca')), 'current_sum_3_phases': get_float_value(get('I3')), 'voltage1': get_integer_value(get('L1v')), 'current1': get_float_value(get('L1i')), 'active_power_import1': get_integer_value(get('Pimp1')), 'active_power_export1': get_integer_value(get('Pexp1')), 'reactive_power_import1': get_integer_value(get('Qimp1')), 'reactive_power_export1': get_integer_value(get('Qexp1')), 'power_factor1': get_float_value(get('PF1')), 'active_quadrant_phase1': get_integer_value(get('Ca1')), 'voltage2': get_integer_value(get('L2v')), 'current2': get_float_value(get('L2i')), 'active_power_import2': get_integer_value(get('Pimp2')), 'active_power_export2': get_integer_value(get('Pexp2')), 'reactive_power_import2': get_integer_value(get('Qimp2')), 'reactive_power_export2': get_integer_value(get('Qexp2')), 'power_factor2': get_float_value(get('PF2')), 'active_quadrant_phase2': get_integer_value(get('Ca2')), 'voltage3': get_integer_value(get('L3v')), 'current3': get_float_value(get('L3i')), 'active_power_import3': get_integer_value(get('Pimp3')), 'active_power_export3': get_integer_value(get('Pexp3')), 'reactive_power_import3': get_integer_value(get('Qimp3')), 'reactive_power_export3': get_integer_value(get('Qexp3')), 'power_factor3': get_float_value(get('PF3')), 'active_quadrant_phase3': get_integer_value(get('Ca3')), 'phase_presence': [get_integer_value(i) for i in (get('PP')).split(",")], 'meter_phase': get_integer_value(get('Fc')), 'current_switch_state': get_integer_value(get('Eacti')), 'previous_switch_state': get_integer_value(get('Eanti')), } ) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self._warnings.append('ERROR: Thrown exception: {}'.format(e)) <NEW_LINE> return [] <NEW_LINE> <DEDENT> return [values]
Class for a set of measures of report S21.
62598fa5e5267d203ee6b7da
class OpenImagesDetectionEvaluator(ObjectDetectionEvaluator): <NEW_LINE> <INDENT> def __init__(self, categories, matching_iou_threshold=0.5, evaluate_corlocs=False, metric_prefix='OpenImagesV2', group_of_weight=0.0): <NEW_LINE> <INDENT> super(OpenImagesDetectionEvaluator, self).__init__( categories, matching_iou_threshold, evaluate_corlocs, metric_prefix=metric_prefix, group_of_weight=group_of_weight) <NEW_LINE> self._expected_keys = set([ standard_fields.InputDataFields.key, standard_fields.InputDataFields.groundtruth_boxes, standard_fields.InputDataFields.groundtruth_classes, standard_fields.InputDataFields.groundtruth_group_of, standard_fields.DetectionResultFields.detection_boxes, standard_fields.DetectionResultFields.detection_scores, standard_fields.DetectionResultFields.detection_classes, ]) <NEW_LINE> <DEDENT> def add_single_ground_truth_image_info(self, image_id, groundtruth_dict): <NEW_LINE> <INDENT> if image_id in self._image_ids: <NEW_LINE> <INDENT> raise ValueError('Image with id {} already added.'.format(image_id)) <NEW_LINE> <DEDENT> groundtruth_classes = ( groundtruth_dict[standard_fields.InputDataFields.groundtruth_classes] - self._label_id_offset) <NEW_LINE> if (standard_fields.InputDataFields.groundtruth_group_of in groundtruth_dict.keys() and (groundtruth_dict[standard_fields.InputDataFields.groundtruth_group_of] .size or not groundtruth_classes.size)): <NEW_LINE> <INDENT> groundtruth_group_of = groundtruth_dict[ standard_fields.InputDataFields.groundtruth_group_of] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> groundtruth_group_of = None <NEW_LINE> if not len(self._image_ids) % 1000: <NEW_LINE> <INDENT> logging.warn( 'image %s does not have groundtruth group_of flag specified', image_id) <NEW_LINE> <DEDENT> <DEDENT> self._evaluation.add_single_ground_truth_image_info( image_id, groundtruth_dict[standard_fields.InputDataFields.groundtruth_boxes], groundtruth_classes, groundtruth_is_difficult_list=None, groundtruth_is_group_of_list=groundtruth_group_of) <NEW_LINE> self._image_ids.update([image_id])
A class to evaluate detections using Open Images V2 metrics. Open Images V2 introduce group_of type of bounding boxes and this metric handles those boxes appropriately.
62598fa5d7e4931a7ef3bf67
class UserSecretStoreFragment(Model): <NEW_LINE> <INDENT> _attribute_map = { 'key_vault_uri': {'key': 'keyVaultUri', 'type': 'str'}, 'key_vault_id': {'key': 'keyVaultId', 'type': 'str'}, } <NEW_LINE> def __init__(self, key_vault_uri=None, key_vault_id=None): <NEW_LINE> <INDENT> super(UserSecretStoreFragment, self).__init__() <NEW_LINE> self.key_vault_uri = key_vault_uri <NEW_LINE> self.key_vault_id = key_vault_id
Properties of a user's secret store. :param key_vault_uri: The URI of the user's Key vault. :type key_vault_uri: str :param key_vault_id: The ID of the user's Key vault. :type key_vault_id: str
62598fa52ae34c7f260aafae
class Card(QtCore.QObject): <NEW_LINE> <INDENT> SUITE_LOOKUP = dict(d='diamonds', s='spades', c='clubs', h='hearts') <NEW_LINE> SUITES = ['s', 'd', 'h', 'c'] <NEW_LINE> FACES = range(2,11) + list('jqka') <NEW_LINE> def __init__(self, face, suite): <NEW_LINE> <INDENT> super(Card, self).__init__() <NEW_LINE> self.face = face <NEW_LINE> self.suite = suite <NEW_LINE> image_path = ":/img/img/%s-%s-75.png" % (self.SUITE_LOOKUP[suite], face) <NEW_LINE> self.pixmap_item = QtGui.QGraphicsPixmapItem(QtGui.QPixmap(image_path)) <NEW_LINE> self.pixmap_item.setCacheMode(QtGui.QGraphicsItem.DeviceCoordinateCache) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "%s%s" % (str(self.face).upper(), self.suite) <NEW_LINE> <DEDENT> def __cmp__(self, other): <NEW_LINE> <INDENT> suite_cmp = cmp(self.suite_idx, other.suite_idx) <NEW_LINE> if suite_cmp == 0: <NEW_LINE> <INDENT> return cmp(self.face_idx, other.face_idx) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return suite_cmp <NEW_LINE> <DEDENT> <DEDENT> def set_pos(self, pos): <NEW_LINE> <INDENT> self.pixmap_item.setPos(pos) <NEW_LINE> <DEDENT> def get_pos(self): <NEW_LINE> <INDENT> return self.pixmap_item.pos() <NEW_LINE> <DEDENT> pos = QtCore.Property(QtCore.QPointF, get_pos, set_pos) <NEW_LINE> @property <NEW_LINE> def suite_idx(self): <NEW_LINE> <INDENT> return self.SUITES.index(self.suite) <NEW_LINE> <DEDENT> @property <NEW_LINE> def face_idx(self): <NEW_LINE> <INDENT> return self.FACES.index(self.face)
Wrapper around a QGraphicsPixmapItem representing a playing card
62598fa5a219f33f346c66e5
class Meta: <NEW_LINE> <INDENT> model = UserSecurityToken <NEW_LINE> fields = ('email', 'otp')
Meta information for OTP validation serializer
62598fa5009cb60464d013f1
class guard(object): <NEW_LINE> <INDENT> def __init__(self, message, payload=None): <NEW_LINE> <INDENT> self.message = message <NEW_LINE> self.payload = payload <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_value, exc_traceback): <NEW_LINE> <INDENT> if isinstance(exc_value, Error): <NEW_LINE> <INDENT> exc_value.wrap(self.message, self.payload)
Adds a paragraph to exceptions leaving the wrapped ``with`` block.
62598fa51f5feb6acb162aee
class MinimaxPlayer(IsolationPlayer): <NEW_LINE> <INDENT> def get_move(self, game, time_left): <NEW_LINE> <INDENT> self.time_left = time_left <NEW_LINE> best_move = (-1, -1) <NEW_LINE> try: <NEW_LINE> <INDENT> return self.minimax(game, self.search_depth) <NEW_LINE> <DEDENT> except SearchTimeout: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return best_move <NEW_LINE> <DEDENT> def terminal_test(self, game): <NEW_LINE> <INDENT> return not game.get_legal_moves() <NEW_LINE> <DEDENT> def minimax(self, game, depth): <NEW_LINE> <INDENT> if self.time_left() < self.TIMER_THRESHOLD: <NEW_LINE> <INDENT> raise SearchTimeout() <NEW_LINE> <DEDENT> return max(game.get_legal_moves(), key=lambda m: self.min_value(game.forecast_move(m), depth)) <NEW_LINE> <DEDENT> def max_value(self, game, depth): <NEW_LINE> <INDENT> if self.time_left() < self.TIMER_THRESHOLD: <NEW_LINE> <INDENT> raise SearchTimeout() <NEW_LINE> <DEDENT> if depth <= 0: <NEW_LINE> <INDENT> return self.score(game, game.active_player) <NEW_LINE> <DEDENT> if self.terminal_test(game): <NEW_LINE> <INDENT> return self.score(game, game.active_player) <NEW_LINE> <DEDENT> v = float("-inf") <NEW_LINE> legal_moves = game.get_legal_moves() <NEW_LINE> for move in legal_moves: <NEW_LINE> <INDENT> score = self.min_value(game.forecast_move(move), depth - 1) <NEW_LINE> if score > v: <NEW_LINE> <INDENT> v = score <NEW_LINE> <DEDENT> <DEDENT> return v <NEW_LINE> <DEDENT> def min_value(self, game, depth): <NEW_LINE> <INDENT> if self.time_left() < self.TIMER_THRESHOLD: <NEW_LINE> <INDENT> raise SearchTimeout() <NEW_LINE> <DEDENT> if depth <= 0: <NEW_LINE> <INDENT> return self.score(game, game.active_player) <NEW_LINE> <DEDENT> if self.terminal_test(game): <NEW_LINE> <INDENT> return self.score(game, game.active_player) <NEW_LINE> <DEDENT> v = float("inf") <NEW_LINE> legal_moves = game.get_legal_moves() <NEW_LINE> for move in legal_moves: <NEW_LINE> <INDENT> score = self.max_value(game.forecast_move(move), depth - 1) <NEW_LINE> if score < v: <NEW_LINE> <INDENT> v = score <NEW_LINE> <DEDENT> <DEDENT> return v
Game-playing agent that chooses a move using depth-limited minimax search. You must finish and test this player to make sure it properly uses minimax to return a good move before the search time limit expires.
62598fa5ac7a0e7691f723d7
class MachineMap_Item(models.Model): <NEW_LINE> <INDENT> ORIENTATION_CHOICES = ( ('H', 'Horizontal'), ('V', 'Vertical'), ) <NEW_LINE> machine = models.ForeignKey(c_models.Item) <NEW_LINE> view = models.ForeignKey(MachineMap) <NEW_LINE> size = models.ForeignKey(MachineMap_Size) <NEW_LINE> xpos = models.IntegerField() <NEW_LINE> ypos = models.IntegerField() <NEW_LINE> orientation = models.CharField(max_length=1, choices=ORIENTATION_CHOICES, default='H') <NEW_LINE> date_added = models.DateTimeField(auto_now_add=True) <NEW_LINE> last_modified = models.DateTimeField(auto_now=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return "%s -- %s (%d, %d)" % (self.view, self.machine, self.xpos, self.ypos) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> app_label = "Viewer" <NEW_LINE> unique_together = ( ('machine', 'view') )
This table is used by the machine map view to determine where computers are located
62598fa599fddb7c1ca62d4e
class nginx_conf(nginx_conf_base): <NEW_LINE> <INDENT> name = "${PRJ_NAME}_${SYS_NAME}_${USER}.conf" <NEW_LINE> src = "${PRJ_ROOT}/conf/used/nginx.conf" <NEW_LINE> tpl = "${PRJ_ROOT}/conf/options/nginx.conf" <NEW_LINE> dst = "/usr/local/nginx/conf/include/" <NEW_LINE> bin = "/sbin/service nginx"
!R.nginx_conf tpl : "${PRJ_ROOT}/conf/options/nginx.conf"
62598fa53539df3088ecc181
class absolute_SSS_difference_from_DDD(abstract_absolute_SSS_difference_from_DDD): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> abstract_absolute_SSS_difference_from_DDD.__init__(self, *args, package_name='urbansim')
difference of variable SSS (current year - baseyear)
62598fa53317a56b869be4b0
class ImageListQueryDemo(object): <NEW_LINE> <INDENT> API_URL = "http://as.dun.163.com/v1/image/list/pageQuery" <NEW_LINE> VERSION = "v1.0" <NEW_LINE> def __init__(self, secret_id, secret_key, business_id): <NEW_LINE> <INDENT> self.secret_id = secret_id <NEW_LINE> self.secret_key = secret_key <NEW_LINE> self.business_id = business_id <NEW_LINE> <DEDENT> def gen_signature(self, params=None): <NEW_LINE> <INDENT> buff = "" <NEW_LINE> for k in sorted(params.keys()): <NEW_LINE> <INDENT> buff += str(k) + str(params[k]) <NEW_LINE> <DEDENT> buff += self.secret_key <NEW_LINE> if "signatureMethod" in params.keys() and params["signatureMethod"] == "SM3": <NEW_LINE> <INDENT> return sm3.sm3_hash(func.bytes_to_list(bytes(buff, encoding='utf8'))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return hashlib.md5(buff.encode("utf8")).hexdigest() <NEW_LINE> <DEDENT> <DEDENT> def query(self, params): <NEW_LINE> <INDENT> params["secretId"] = self.secret_id <NEW_LINE> params["businessId"] = self.business_id <NEW_LINE> params["version"] = self.VERSION <NEW_LINE> params["timestamp"] = int(time.time() * 1000) <NEW_LINE> params["nonce"] = int(random.random() * 100000000) <NEW_LINE> params["signature"] = self.gen_signature(params) <NEW_LINE> try: <NEW_LINE> <INDENT> params = urlparse.urlencode(params).encode("utf8") <NEW_LINE> request = urlrequest.Request(self.API_URL, params) <NEW_LINE> content = urlrequest.urlopen(request, timeout=10).read() <NEW_LINE> return json.loads(content) <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> print("调用API接口失败:", str(ex))
易盾反垃圾云服务图片名单查询接口python示例代码
62598fa544b2445a339b68d5
class EvalString(Evaluator): <NEW_LINE> <INDENT> __slots__ = ["value", "eval"] <NEW_LINE> def build(self, tokens, _decode=decode_string): <NEW_LINE> <INDENT> value = self.value = _decode(tokens[0][1:-1]) <NEW_LINE> self.eval = lambda context: value
Class to evaluate a string
62598fa5d6c5a102081e2014
class Job(resource.Resource, display.Display): <NEW_LINE> <INDENT> show_column_names = [ "Id", "Type", "Begin Time", "End Time", "Entities", "Status", ] <NEW_LINE> column_2_property = { "Id": "job_id", "Type": "job_type", } <NEW_LINE> formatter = { "Entities": utils.format_dict } <NEW_LINE> def get_show_column_names(self): <NEW_LINE> <INDENT> column_names = self.show_column_names[:] <NEW_LINE> if "fail_reason" in self.original and self.fail_reason: <NEW_LINE> <INDENT> column_names.insert(5, "Fail Reason") <NEW_LINE> <DEDENT> if "error_code" in self.original and self.error_code: <NEW_LINE> <INDENT> column_names.insert(5, "Error Code") <NEW_LINE> <DEDENT> return column_names
Volume Backup Job resource instance
62598fa5f548e778e596b471