code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class UsecaseList(ListResource): <NEW_LINE> <INDENT> def __init__(self, version): <NEW_LINE> <INDENT> super(UsecaseList, self).__init__(version) <NEW_LINE> self._solution = {} <NEW_LINE> self._uri = '/Services/Usecases'.format(**self._solution) <NEW_LINE> <DEDENT> def fetch(self): <NEW_LINE> <INDENT> payload = self._version.fetch(method='GET', uri=self._uri, ) <NEW_LINE> return UsecaseInstance(self._version, payload, ) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Twilio.Messaging.V1.UsecaseList>' | PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. | 625990573539df3088ecd81d |
class ChromePreferencesParser(interface.SingleFileBaseParser): <NEW_LINE> <INDENT> NAME = 'chrome_preferences' <NEW_LINE> DESCRIPTION = u'Parser for Chrome Preferences files.' <NEW_LINE> REQUIRED_KEYS = frozenset(('browser', 'extensions')) <NEW_LINE> def _ExtractExtensionInstallationEvents(self, settings_dict): <NEW_LINE> <INDENT> for extension_id, extension in settings_dict.iteritems(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> install_time = int(extension.get(u'install_time', u'0'), 10) <NEW_LINE> <DEDENT> except ValueError as exception: <NEW_LINE> <INDENT> logging.warning( u'Extension ID {0:s} is missing timestamp: {1:s}'.format( extension_id, exception)) <NEW_LINE> continue <NEW_LINE> <DEDENT> manifest = extension.get(u'manifest') <NEW_LINE> if manifest: <NEW_LINE> <INDENT> extension_name = manifest.get(u'name') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> extension_name = None <NEW_LINE> <DEDENT> path = extension.get(u'path') <NEW_LINE> yield install_time, extension_id, extension_name, path <NEW_LINE> <DEDENT> <DEDENT> def ParseFileObject(self, parser_mediator, file_object, **kwargs): <NEW_LINE> <INDENT> file_object.seek(0, os.SEEK_SET) <NEW_LINE> if file_object.read(1) != b'{': <NEW_LINE> <INDENT> raise errors.UnableToParseFile(( u'[{0:s}] {1:s} is not a valid Preference file, ' u'missing opening brace.').format( self.NAME, parser_mediator.GetDisplayName())) <NEW_LINE> <DEDENT> file_object.seek(0, os.SEEK_SET) <NEW_LINE> try: <NEW_LINE> <INDENT> json_dict = json.load(file_object) <NEW_LINE> <DEDENT> except ValueError as exception: <NEW_LINE> <INDENT> raise errors.UnableToParseFile( u'[{0:s}] Unable to parse file {1:s} as ' u'JSON: {2:s}'.format( self.NAME, parser_mediator.GetDisplayName(), exception)) <NEW_LINE> <DEDENT> except IOError as exception: <NEW_LINE> <INDENT> raise errors.UnableToParseFile( u'[{0:s}] Unable to open file {1:s} for parsing as' u'JSON: {2:s}'.format( self.NAME, parser_mediator.GetDisplayName(), exception)) <NEW_LINE> <DEDENT> if not set(self.REQUIRED_KEYS).issubset(set(json_dict.keys())): <NEW_LINE> <INDENT> raise errors.UnableToParseFile(u'File does not contain Preference data.') <NEW_LINE> <DEDENT> extensions_setting_dict = json_dict.get(u'extensions') <NEW_LINE> if not extensions_setting_dict: <NEW_LINE> <INDENT> raise errors.UnableToParseFile( u'[{0:s}] {1:s} is not a valid Preference file, ' u'does not contain extensions value.'.format( self.NAME, parser_mediator.GetDisplayName())) <NEW_LINE> <DEDENT> extensions_dict = extensions_setting_dict.get(u'settings') <NEW_LINE> if not extensions_dict: <NEW_LINE> <INDENT> raise errors.UnableToParseFile( u'[{0:s}] {1:s} is not a valid Preference file, ' u'does not contain extensions settings value.'.format( self.NAME, parser_mediator.GetDisplayName())) <NEW_LINE> <DEDENT> callback = self._ExtractExtensionInstallationEvents <NEW_LINE> for install_time, extension_id, extension_name, path in callback( extensions_dict): <NEW_LINE> <INDENT> event_object = ChromeExtensionInstallationEvent( install_time, extension_id, extension_name, path) <NEW_LINE> parser_mediator.ProduceEvent(event_object) | Parses Chrome Preferences files. | 62599057dd821e528d6da43b |
class UDPTracer(pyuavcan.transport.Tracer): <NEW_LINE> <INDENT> def __init__(self) -> None: <NEW_LINE> <INDENT> self._sessions: typing.Dict[AlienSessionSpecifier, _AlienSession] = {} <NEW_LINE> <DEDENT> def update(self, cap: Capture) -> typing.Optional[Trace]: <NEW_LINE> <INDENT> if not isinstance(cap, UDPCapture): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> parsed = cap.parse() <NEW_LINE> if not parsed: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> spec, frame = parsed <NEW_LINE> return self._get_session(spec).update(cap.timestamp, frame) <NEW_LINE> <DEDENT> def _get_session(self, specifier: AlienSessionSpecifier) -> _AlienSession: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._sessions[specifier] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> self._sessions[specifier] = _AlienSession(specifier) <NEW_LINE> <DEDENT> return self._sessions[specifier] | This is like a Wireshark dissector but UAVCAN-focused.
Return types from :meth:`update`:
- :class:`pyuavcan.transport.TransferTrace`
- :class:`UDPErrorTrace` | 62599057b57a9660fecd2ff2 |
class JdxCreateOrderRequest(JDCloudRequest): <NEW_LINE> <INDENT> def __init__(self, parameters, header=None, version="v1"): <NEW_LINE> <INDENT> super(JdxCreateOrderRequest, self).__init__( '/regions/{regionId}/jdxCreateOrder', 'POST', header, version) <NEW_LINE> self.parameters = parameters | 下单接口 | 625990578e71fb1e983bd040 |
class mep_abs24(mep_imm): <NEW_LINE> <INDENT> parser = abs24_deref_parser <NEW_LINE> def decode(self, v): <NEW_LINE> <INDENT> v = v & self.lmask <NEW_LINE> abs24 = (v << 8) + ((self.parent.imm6.value & 0x3F) << 2) <NEW_LINE> self.expr = ExprMem(ExprInt(abs24, 32), 32) <NEW_LINE> return True <NEW_LINE> <DEDENT> def encode(self): <NEW_LINE> <INDENT> if not (isinstance(self.expr, ExprMem) and isinstance(self.expr.ptr, ExprInt)): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> v = int(self.expr.ptr.arg) <NEW_LINE> if v > 0xffffff: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> self.parent.imm6.value = (v & 0xFF) >> 2 <NEW_LINE> self.value = v >> 8 <NEW_LINE> return True | Toshiba MeP-c4 abs24 immediate
| 62599057a17c0f6771d5d65c |
class RenderArgs(UnityIntrospectionObject): <NEW_LINE> <INDENT> pass | An emulator class for interacting with the RenderArgs class. | 6259905773bcbd0ca4bcb809 |
class UserRegister(Resource): <NEW_LINE> <INDENT> parser = reqparse.RequestParser() <NEW_LINE> parser.add_argument( 'username', type=str, required=True, help="This field cannot be blank." ) <NEW_LINE> parser.add_argument( 'password', type=str, required=True, help="This field cannot be blank." ) <NEW_LINE> def post(self): <NEW_LINE> <INDENT> data = UserRegister.parser.parse_args() <NEW_LINE> if UserModel.find_by_username(data['username']): <NEW_LINE> <INDENT> return {'message': 'A user with that username already exists'}, 400 <NEW_LINE> <DEDENT> user = UserModel(**data) <NEW_LINE> user.save_to_db() <NEW_LINE> return {'message': 'User created successfully.'}, 201 | This resource allows user to register by sending a
POST request with their username and password. | 62599057be8e80087fbc05fa |
class TestONONOSConfig(object): <NEW_LINE> <INDENT> def __init__(self, label, address, port, intent_ip=None, intent_port=None, intent_url=None): <NEW_LINE> <INDENT> self.label = label <NEW_LINE> self.address = address <NEW_LINE> self.port = port <NEW_LINE> self.cid = self.label <NEW_LINE> self.intent_ip = intent_ip <NEW_LINE> self.intent_port = intent_port <NEW_LINE> self.intent_url = intent_url <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return ("<TestONONOSConfig: label=%s, address=%s, port=%s, cid=%s " "intent_ip=%s, intend_port=%s, intent_url=%s" % (self.label, self.address, self.port, self.cid, self.intent_ip, self.intent_port, self.intent_url)) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.__repr__() | TestON ONOS specific configurations | 625990573cc13d1c6d466cb6 |
class MacroDef: <NEW_LINE> <INDENT> def __init__(self, name, elems=None, eqs=None): <NEW_LINE> <INDENT> self.all_elems = dict() <NEW_LINE> self.all_eqs = dict() <NEW_LINE> self.macname = name <NEW_LINE> if elems: <NEW_LINE> <INDENT> self.add(elems) <NEW_LINE> <DEDENT> if eqs: <NEW_LINE> <INDENT> self.add_eqs(eqs) <NEW_LINE> <DEDENT> <DEDENT> def add(self, elems): <NEW_LINE> <INDENT> for elm in elems: <NEW_LINE> <INDENT> if elm.get_name() in self.all_elems: <NEW_LINE> <INDENT> print("MacroDef {0}: element with the name '{1}' already in the macro!".format( self.macname, elm.get_name())) <NEW_LINE> <DEDENT> self.all_elems[elm.get_name()] = elm <NEW_LINE> <DEDENT> <DEDENT> def add_eqs(self, eqs): <NEW_LINE> <INDENT> for eq in eqs: <NEW_LINE> <INDENT> if eq.get_name() in self.all_eqs: <NEW_LINE> <INDENT> print("MacroDef {0}: eq with the name '{1}' already in the macro!".format( self.macname, eq.get_name())) <NEW_LINE> <DEDENT> self.all_eqs[eq.get_name()] = eq | Macros are subgraphs, expanded when instantiated.
| 625990577047854f46340936 |
class OntologyID(Base): <NEW_LINE> <INDENT> def __init__(self, text): <NEW_LINE> <INDENT> assert text.count(":") <= 1, "ID {} is misformatted!".format(text) <NEW_LINE> assert "|" not in text <NEW_LINE> if ":" in text: <NEW_LINE> <INDENT> self.uid_type, self.uid = text.split(":") <NEW_LINE> if self.uid_type == "MESH": <NEW_LINE> <INDENT> assert is_MeSH_id(self.uid), "{} not MeSH!".format(text) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.uid = text <NEW_LINE> self.uid_type = "MESH" if is_MeSH_id(self.uid) else "unknown" <NEW_LINE> <DEDENT> self.flat_repr = "{}:{}".format(self.uid_type, self.uid) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<{}>: {}".format(self.__class__.__name__, self.flat_repr) <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(self.flat_repr) | A single identifier from an existing biomedical ontology.
Training PMID 7265370 has the chemical D014527+D012492, but since it doesn't
show up in any gold standard relation we will ignore it. | 6259905710dbd63aa1c72135 |
class StandardPassword(Password): <NEW_LINE> <INDENT> host = "host" <NEW_LINE> username = "username" | A subclass of `Password` in which ``host`` is set to ``"host"`` and
``username`` is set to ``"username"`` | 62599057d6c5a102081e3697 |
class RequestRenderable(object): <NEW_LINE> <INDENT> implements(IRenderable) <NEW_LINE> def __init__(self, renderable, request): <NEW_LINE> <INDENT> self.renderable = renderable <NEW_LINE> self.request = request <NEW_LINE> <DEDENT> def render(self, request=None): <NEW_LINE> <INDENT> request = request <NEW_LINE> if request is None: <NEW_LINE> <INDENT> request = self.request <NEW_LINE> <DEDENT> return self.renderable.render(request=request) | Provides a renderable that doesn't require a request.
| 62599057460517430c432b0d |
class PatternAnalyzer(BaseSentimentAnalyzer): <NEW_LINE> <INDENT> kind = CONTINUOUS <NEW_LINE> RETURN_TYPE = namedtuple('Sentiment', ['polarity', 'subjectivity']) <NEW_LINE> def analyze(self, text, keep_assessments=False): <NEW_LINE> <INDENT> if keep_assessments: <NEW_LINE> <INDENT> Sentiment = namedtuple('Sentiment', ['polarity', 'subjectivity', 'assessments']) <NEW_LINE> assessments = pattern_sentiment(text).assessments <NEW_LINE> polarity, subjectivity = pattern_sentiment(text) <NEW_LINE> return Sentiment(polarity, subjectivity, assessments) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> Sentiment = namedtuple('Sentiment', ['polarity', 'subjectivity']) <NEW_LINE> return Sentiment(*pattern_sentiment(text)) | Sentiment analyzer that uses the same implementation as the
pattern library. Returns results as a named tuple of the form:
``Sentiment(polarity, subjectivity, [assessments])``
where [assessments] is a list of the assessed tokens and their
polarity and subjectivity scores | 6259905707d97122c4218222 |
class TestConfig(Configuration): <NEW_LINE> <INDENT> TESTING = True <NEW_LINE> DEBUG = True <NEW_LINE> SQLALCHEMY_DATABASE_URI = os.getenv("TEST_DATABASE_URI") | Testing instance configuration class | 6259905782261d6c52730986 |
@inherit_doc <NEW_LINE> class PredictionModel(Model, _PredictorParams): <NEW_LINE> <INDENT> __metaclass__ = ABCMeta <NEW_LINE> @since("3.0.0") <NEW_LINE> def setFeaturesCol(self, value): <NEW_LINE> <INDENT> return self._set(featuresCol=value) <NEW_LINE> <DEDENT> @since("3.0.0") <NEW_LINE> def setPredictionCol(self, value): <NEW_LINE> <INDENT> return self._set(predictionCol=value) <NEW_LINE> <DEDENT> @abstractproperty <NEW_LINE> @since("2.1.0") <NEW_LINE> def numFeatures(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> @since("3.0.0") <NEW_LINE> def predict(self, value): <NEW_LINE> <INDENT> raise NotImplementedError() | Model for prediction tasks (regression and classification). | 62599057a8ecb0332587278f |
class StationBasin(Garea, GGRS87Mixin, BasinMixin): <NEW_LINE> <INDENT> river_basin = models.ForeignKey(RiverBasin, on_delete=models.CASCADE) <NEW_LINE> station = models.OneToOneField(Station, on_delete=models.CASCADE) | A subbasin defined by a measuring station. | 6259905763b5f9789fe866eb |
class FailSubscriberTest(TestCase): <NEW_LINE> <INDENT> def assertFailSubscribe(self, j, m=''): <NEW_LINE> <INDENT> u = FauxUserInfo() <NEW_LINE> with self.assertRaises(CannotJoin) as e: <NEW_LINE> <INDENT> j.subscribe(u, '[email protected]', None) <NEW_LINE> <DEDENT> if m: <NEW_LINE> <INDENT> msg = str(e.exception) <NEW_LINE> self.assertIn(m, msg) <NEW_LINE> <DEDENT> <DEDENT> def test_odd_subscribe_fail(self): <NEW_LINE> <INDENT> j = OddSubscriber(FauxVisibility()) <NEW_LINE> j.groupVisibility.isOdd = True <NEW_LINE> self.assertFailSubscribe(j, 'cannot') <NEW_LINE> <DEDENT> def test_secret_subscribe_fail(self): <NEW_LINE> <INDENT> j = SecretSubscriber(FauxVisibility()) <NEW_LINE> j.groupVisibility.isSecret = True <NEW_LINE> self.assertFailSubscribe(j, 'invited') <NEW_LINE> <DEDENT> def test_private_join_fail(self): <NEW_LINE> <INDENT> j = PrivateSubscriber(FauxVisibility()) <NEW_LINE> j.groupVisibility.isPrivate = True <NEW_LINE> self.assertFailSubscribe(j, 'request') | Test the Subscribers that always prevent joining. | 6259905799cbb53fe6832457 |
class JoinAPI(View, API): <NEW_LINE> <INDENT> def post(self, request): <NEW_LINE> <INDENT> if request.method == 'POST': <NEW_LINE> <INDENT> game_id = request.POST.get('game_id') <NEW_LINE> player_id = request.POST.get('player_id') <NEW_LINE> game = self._check_game_id_valid(game_id) <NEW_LINE> session = self._get_or_create_session(game) <NEW_LINE> self._assign_questions_to_session(session) <NEW_LINE> player = self._check_player_id_valid(player_id) <NEW_LINE> self._add_player_to_session(session, player) <NEW_LINE> return self._return_as_json(session) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._throw_api_error('We need a POST request') <NEW_LINE> <DEDENT> <DEDENT> def _add_player_to_session(self, session, player): <NEW_LINE> <INDENT> session.players.add(player) <NEW_LINE> if (len(session.players.all())) >= 6: <NEW_LINE> <INDENT> session.status = 'ready' <NEW_LINE> session.save() <NEW_LINE> <DEDENT> <DEDENT> def _assign_questions_to_session(self, session): <NEW_LINE> <INDENT> questions = Question.objects.all().order_by('?')[:NUM_QUESTIONS_PER_SESSION] <NEW_LINE> session.questions.set(questions) <NEW_LINE> <DEDENT> def _get_or_create_session(self, game): <NEW_LINE> <INDENT> available_session = Session.objects.annotate(players_count=Count('players')).filter(players_count__lte=7).count() <NEW_LINE> if available_session: <NEW_LINE> <INDENT> session = Session.objects.filter(pk=available_session)[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> session = Session.objects.create(game=game) <NEW_LINE> <DEDENT> return session | Class based viewed for /join endpoint | 6259905776e4537e8c3f0b04 |
class Confyg(object): <NEW_LINE> <INDENT> __source__ = None <NEW_LINE> __config_store__ = None <NEW_LINE> __transformation__ = None <NEW_LINE> @classmethod <NEW_LINE> def load(cls): <NEW_LINE> <INDENT> cls.__config_store__ = cls.load_store() <NEW_LINE> for k, vk in confyg_attributes_values(cls): <NEW_LINE> <INDENT> v = cls.get(vk) <NEW_LINE> cls.set(k, v) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def load_store(cls): <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get(cls, key): <NEW_LINE> <INDENT> if cls.__transformation__ is not None: <NEW_LINE> <INDENT> tf = cls.__transformation__ <NEW_LINE> key = tf(key) <NEW_LINE> <DEDENT> return cls.__config_store__[ key ] <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def set(cls, key, val): <NEW_LINE> <INDENT> setattr(cls, key, val) | The base configuration class implementing the common
functionality. Subclassing this class should make
it easy to add new configuration sources. | 62599057ac7a0e7691f73a59 |
class ModifyPublicIPSwitchStatusRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.FireWallPublicIP = None <NEW_LINE> self.Status = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.FireWallPublicIP = params.get("FireWallPublicIP") <NEW_LINE> self.Status = params.get("Status") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set)) | ModifyPublicIPSwitchStatus请求参数结构体
| 62599057e76e3b2f99fd9f77 |
class ExplicitEuler(PricingWithPDEs): <NEW_LINE> <INDENT> def __init__(self, dx, dt, xmin, xmax, tmax, r, sigma, payoff, functionLeft, functionRight): <NEW_LINE> <INDENT> self.sigma = sigma <NEW_LINE> self.r = r <NEW_LINE> super().__init__(dx, dt, xmin, xmax, tmax, payoff, functionLeft, functionRight) <NEW_LINE> self.__initializeTerms() <NEW_LINE> <DEDENT> def __initializeTerms(self): <NEW_LINE> <INDENT> self.multiplyTermFirstDerivative = 0.5 * self.dt/self.dx <NEW_LINE> self.multiplySecondDerivative = self.dt/(self.dx*self.dx) <NEW_LINE> <DEDENT> def getSolutionAtNextTime(self): <NEW_LINE> <INDENT> uPast = self.uPast <NEW_LINE> u = np.zeros((len(uPast))) <NEW_LINE> u[0] = self.functionLeft(self.x[0], self.currentTime) <NEW_LINE> firstDerivatives = self.multiplyTermFirstDerivative * (uPast[2:]-uPast[:-2]) <NEW_LINE> secondDerivatives = self.multiplySecondDerivative * (uPast[2:]-2*uPast[1:-1]+uPast[:-2]) <NEW_LINE> u[1:-1] = uPast[1:-1] + 0.5 * secondDerivatives * self.sigma(self.x[1:-1])**2 + firstDerivatives * self.r * self.x[1:-1] - self.dt * self.r * uPast[1:-1] <NEW_LINE> u[-1] = self.functionRight(self.x[-1], self.currentTime) <NEW_LINE> return u | This class is devoted to numerically solve the PDE
U_t(x,t) - 1/2 x^2 sigma^2(x,t)U_{xx}(x,t) - r U_{x}(x,t) + r U(x,t) = 0,
via Explicit Euler.
This is the PDE corresponding to a local volatility model.
Boundary conditions given as attributes of the class are applied at both ends
of the domain. An initial condition is applied at t = 0. This can be seen
as the payoff of an option. In this case, time represents maturity.
Attributes
----------
dx : float
discretization step on the space
dt : float
discretization step on the time
xmin : float
left end of the space domain
xmax : float
right end of the space domain
tmax : float
right end of the time domain
x : float
the dsicretized space domain
numberOfSpaceSteps : int
the number of intervals of the space domain
numberOfTimeSteps : int
the number of intervals of the time domain
sigma : function
the volatility function, depending on time and space
r : float
the interest rate
payoff : function
the initial condition. Called in this way because it corresponds to
payoff of an option seeing time as maturity
functionLeft : function
the condition at the left end of the space domain.
functionRight : function
the condition at the right end of the space domain.
currentTime : int
the current time. The PDE is solved going forward in time. Here the
current time is used to plot the solution dynamically and to compute
the solution at the next time step in the derived classes.
Methods
-------
getSolutionAtNextTime():
It returns the solution at the next time step
solveAndPlot():
It solves the PDE and dynamically plots the solution at every time step
of length 0.1. It does not store the solution in a matrix
solveAndSave():
It solves the PDE and store the solution as a matrix in the self.solution
attribute of the class. It also returns it.
getSolutionForGivenMaturityAndValue(time, space):
It returns the solution at given time and given space | 6259905721bff66bcd7241dd |
class RBNode(object): <NEW_LINE> <INDENT> def __init__(self,data): <NEW_LINE> <INDENT> self.red = False <NEW_LINE> self.parent = None <NEW_LINE> self.data = data <NEW_LINE> self.left = NIL <NEW_LINE> self.right = NIL | Class for implementing the nodes that the tree will use
For self.color:
red == False
black == True
If the node is a leaf it will either | 625990574e4d562566373980 |
class AnchorLabeler(object): <NEW_LINE> <INDENT> def __init__(self, anchor, match_threshold=0.5, unmatched_threshold=0.5): <NEW_LINE> <INDENT> similarity_calc = keras_cv.ops.IouSimilarity() <NEW_LINE> matcher = argmax_matcher.ArgMaxMatcher( match_threshold, unmatched_threshold=unmatched_threshold, negatives_lower_than_unmatched=True, force_match_for_each_row=True) <NEW_LINE> box_coder = faster_rcnn_box_coder.FasterRcnnBoxCoder() <NEW_LINE> self._target_assigner = target_assigner.TargetAssigner( similarity_calc, matcher, box_coder) <NEW_LINE> self._anchor = anchor <NEW_LINE> self._match_threshold = match_threshold <NEW_LINE> self._unmatched_threshold = unmatched_threshold <NEW_LINE> <DEDENT> def label_anchors(self, gt_boxes, gt_labels): <NEW_LINE> <INDENT> gt_box_list = box_list.BoxList(gt_boxes) <NEW_LINE> anchor_box_list = box_list.BoxList(self._anchor.boxes) <NEW_LINE> cls_targets, _, box_targets, _, matches = self._target_assigner.assign( anchor_box_list, gt_box_list, gt_labels) <NEW_LINE> match_results = tf.expand_dims(matches.match_results, axis=1) <NEW_LINE> cls_targets = tf.cast(cls_targets, tf.int32) <NEW_LINE> cls_targets = tf.where( tf.equal(match_results, -1), -tf.ones_like(cls_targets), cls_targets) <NEW_LINE> cls_targets = tf.where( tf.equal(match_results, -2), -2 * tf.ones_like(cls_targets), cls_targets) <NEW_LINE> cls_targets_dict = self._anchor.unpack_labels(cls_targets) <NEW_LINE> box_targets_dict = self._anchor.unpack_labels(box_targets) <NEW_LINE> num_positives = tf.reduce_sum( input_tensor=tf.cast(tf.greater(matches.match_results, -1), tf.float32)) <NEW_LINE> return cls_targets_dict, box_targets_dict, num_positives | Labeler for dense object detector. | 625990577b25080760ed879b |
class TestBooleanEnum(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_BooleanEnum(self): <NEW_LINE> <INDENT> pass | BooleanEnum unit test stubs | 62599057507cdc57c63a631d |
class ParseBatcher(ParseBase): <NEW_LINE> <INDENT> ENDPOINT_ROOT = '/'.join((API_ROOT, 'batch')) <NEW_LINE> def batch(self, methods): <NEW_LINE> <INDENT> methods = list(methods) <NEW_LINE> if not methods: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> queries, callbacks = list(zip(*[m(batch=True) for m in methods])) <NEW_LINE> responses = self.execute("", "POST", requests=queries) <NEW_LINE> batched_errors = [] <NEW_LINE> for callback, response in zip(callbacks, responses): <NEW_LINE> <INDENT> if "success" in response: <NEW_LINE> <INDENT> callback(response["success"]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> batched_errors.append(response["error"]) <NEW_LINE> <DEDENT> <DEDENT> if batched_errors: <NEW_LINE> <INDENT> raise core.ParseBatchError(batched_errors) <NEW_LINE> <DEDENT> <DEDENT> def batch_save(self, objects): <NEW_LINE> <INDENT> self.batch(o.save for o in objects) <NEW_LINE> <DEDENT> def batch_delete(self, objects): <NEW_LINE> <INDENT> self.batch(o.delete for o in objects) | Batch together create, update or delete operations | 625990578e71fb1e983bd042 |
class MLPDecoder(nn.Module): <NEW_LINE> <INDENT> def __init__(self, n_in_node, edge_types, msg_hid, msg_out, n_hid, do_prob=0., skip_first=False): <NEW_LINE> <INDENT> super(MLPDecoder, self).__init__() <NEW_LINE> self.msg_fc1 = nn.Linear(2 * n_in_node, msg_hid) <NEW_LINE> self.msg_fc2 = nn.Linear(msg_hid, msg_out) <NEW_LINE> self.msg_out_shape = msg_out <NEW_LINE> self.skip_first_edge_type = skip_first <NEW_LINE> self.out_fc1 = nn.Linear(n_in_node + msg_out, n_hid) <NEW_LINE> self.out_fc2 = nn.Linear(n_hid, n_hid) <NEW_LINE> self.out_fc3 = nn.Linear(n_hid, n_in_node) <NEW_LINE> print('Using learned interaction net decoder.') <NEW_LINE> self.dropout_prob = do_prob <NEW_LINE> <DEDENT> def single_step_forward(self, single_timestep_inputs, rel_rec, rel_send): <NEW_LINE> <INDENT> receivers = torch.matmul(rel_rec, single_timestep_inputs) <NEW_LINE> senders = torch.matmul(rel_send, single_timestep_inputs) <NEW_LINE> pre_msg = torch.cat([senders, receivers], dim=1) <NEW_LINE> all_msgs = Variable(torch.zeros(pre_msg.size(0), self.msg_out_shape)) <NEW_LINE> if single_timestep_inputs.is_cuda: <NEW_LINE> <INDENT> all_msgs = all_msgs.cuda() <NEW_LINE> <DEDENT> if self.skip_first_edge_type: <NEW_LINE> <INDENT> start_idx = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> start_idx = 0 <NEW_LINE> <DEDENT> msg = F.relu(self.msg_fc1(pre_msg)) <NEW_LINE> msg = F.dropout(msg, p=self.dropout_prob) <NEW_LINE> msg = F.relu(self.msg_fc2(msg)) <NEW_LINE> all_msgs += msg <NEW_LINE> agg_msgs = all_msgs.transpose(-2, -1).matmul(rel_rec).transpose(-2, -1) <NEW_LINE> agg_msgs = agg_msgs.contiguous() <NEW_LINE> aug_inputs = torch.cat([single_timestep_inputs, agg_msgs], dim=-1) <NEW_LINE> pred = F.dropout(F.relu(self.out_fc1(aug_inputs)), p=self.dropout_prob) <NEW_LINE> pred = F.dropout(F.relu(self.out_fc2(pred)), p=self.dropout_prob) <NEW_LINE> pred = self.out_fc3(pred) <NEW_LINE> return single_timestep_inputs + pred <NEW_LINE> <DEDENT> def forward(self, inputs, rel_rec, rel_send, pred_steps=1): <NEW_LINE> <INDENT> last_pred = inputs <NEW_LINE> last_pred = self.single_step_forward(last_pred, rel_rec, rel_send) <NEW_LINE> sizes = [last_pred.size(0), last_pred.size(1)] <NEW_LINE> output = Variable(torch.zeros(sizes)) <NEW_LINE> if inputs.is_cuda: <NEW_LINE> <INDENT> output = output.cuda() <NEW_LINE> <DEDENT> output = last_pred <NEW_LINE> return output | MLP decoder module. | 62599057adb09d7d5dc0bae3 |
class TestLoadPluginModules: <NEW_LINE> <INDENT> def test_load_default_plugins(self): <NEW_LINE> <INDENT> default_plugin_qualnames = plugin.get_qualified_module_names( _repobee.ext.defaults ) <NEW_LINE> modules = plugin.load_plugin_modules( default_plugin_qualnames, allow_qualified=True ) <NEW_LINE> module_names = [mod.__name__ for mod in modules] <NEW_LINE> assert module_names == default_plugin_qualnames <NEW_LINE> <DEDENT> def test_load_bundled_plugins(self): <NEW_LINE> <INDENT> bundled_plugin_qualnames = plugin.get_qualified_module_names( _repobee.ext ) <NEW_LINE> bundled_plugin_names = plugin.get_module_names(_repobee.ext) <NEW_LINE> modules = plugin.load_plugin_modules(bundled_plugin_names) <NEW_LINE> module_names = [mod.__name__ for mod in modules] <NEW_LINE> assert module_names == bundled_plugin_qualnames <NEW_LINE> <DEDENT> def test_load_no_plugins(self, no_config_mock): <NEW_LINE> <INDENT> modules = plugin.load_plugin_modules([]) <NEW_LINE> assert not modules <NEW_LINE> <DEDENT> def test_raises_when_loading_invalid_module(self, empty_config_mock): <NEW_LINE> <INDENT> plugin_name = "this_plugin_does_not_exist" <NEW_LINE> with pytest.raises(exception.PluginLoadError) as exc_info: <NEW_LINE> <INDENT> plugin.load_plugin_modules([plugin_name]) <NEW_LINE> <DEDENT> assert "failed to load plugin module " + plugin_name in str( exc_info.value ) <NEW_LINE> <DEDENT> def test_raises_when_loading_default_plugins_without_allow_qualified(self): <NEW_LINE> <INDENT> default_plugin_qualnames = plugin.get_qualified_module_names( _repobee.ext.defaults ) <NEW_LINE> with pytest.raises(exception.PluginLoadError) as exc_info: <NEW_LINE> <INDENT> plugin.load_plugin_modules(default_plugin_qualnames) <NEW_LINE> <DEDENT> assert "failed to load plugin module" in str(exc_info.value) | Tests for load_plugin_modules. | 6259905773bcbd0ca4bcb80b |
class UserSharedItem(object): <NEW_LINE> <INDENT> swagger_types = { 'error_details': 'ErrorDetails', 'shared': 'str', 'user': 'UserInfo' } <NEW_LINE> attribute_map = { 'error_details': 'errorDetails', 'shared': 'shared', 'user': 'user' } <NEW_LINE> def __init__(self, _configuration=None, **kwargs): <NEW_LINE> <INDENT> if _configuration is None: <NEW_LINE> <INDENT> _configuration = Configuration() <NEW_LINE> <DEDENT> self._configuration = _configuration <NEW_LINE> self._error_details = None <NEW_LINE> self._shared = None <NEW_LINE> self._user = None <NEW_LINE> self.discriminator = None <NEW_LINE> setattr(self, "_{}".format('error_details'), kwargs.get('error_details', None)) <NEW_LINE> setattr(self, "_{}".format('shared'), kwargs.get('shared', None)) <NEW_LINE> setattr(self, "_{}".format('user'), kwargs.get('user', None)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def error_details(self): <NEW_LINE> <INDENT> return self._error_details <NEW_LINE> <DEDENT> @error_details.setter <NEW_LINE> def error_details(self, error_details): <NEW_LINE> <INDENT> self._error_details = error_details <NEW_LINE> <DEDENT> @property <NEW_LINE> def shared(self): <NEW_LINE> <INDENT> return self._shared <NEW_LINE> <DEDENT> @shared.setter <NEW_LINE> def shared(self, shared): <NEW_LINE> <INDENT> self._shared = shared <NEW_LINE> <DEDENT> @property <NEW_LINE> def user(self): <NEW_LINE> <INDENT> return self._user <NEW_LINE> <DEDENT> @user.setter <NEW_LINE> def user(self, user): <NEW_LINE> <INDENT> self._user = user <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(UserSharedItem, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, UserSharedItem): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, UserSharedItem): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict() | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62599057e5267d203ee6ce68 |
class Installator(object): <NEW_LINE> <INDENT> def install(self, url, targetPath, key=None, ui=None): <NEW_LINE> <INDENT> if ui: <NEW_LINE> <INDENT> ui.progressText.append('Starting downloading files...') <NEW_LINE> <DEDENT> download = Download.Download(url, key, ui=ui) <NEW_LINE> download.download() <NEW_LINE> downloadedPath = download.getExtractedPath() or download.getFileDownloaded() <NEW_LINE> if ui: <NEW_LINE> <INDENT> ui.progressText.append('Installing the files...') <NEW_LINE> <DEDENT> install = Install.Install(downloadedPath, targetPath, ui=ui) <NEW_LINE> install.install() <NEW_LINE> if ui: <NEW_LINE> <INDENT> ui.progressText.append('Installation successful') <NEW_LINE> ui.progressBar.setValue(100) <NEW_LINE> <DEDENT> <DEDENT> def update(self, url, currentVersion, key=None, fileName=None, targetPath=None, install=False): <NEW_LINE> <INDENT> update = Update.Update(url, currentVersion) <NEW_LINE> updateUrl = update.checkUpdates() <NEW_LINE> if not updateUrl: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> return updateUrl | Main class. | 625990577047854f46340938 |
class UniqueAppendConstAction(UniqueAppendAction): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> kwargs['nargs'] = 0 <NEW_LINE> super().__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def _get_values(self, values): <NEW_LINE> <INDENT> return self.const | Append const value to a list and make sure there are no duplicates.
.. code-block:: python
:caption: Example usage
parser = argparse.ArgumentParser()
parser.add_argument(
'-f', '--failed', const='failed', dest='filter',
action=UniqueAppendConstAction, help='Show failed items.'
)
parser.add_argument(
'-a', '--aborted', const='aborted', dest='filter',
action=UniqueAppendConstAction, help='Show aborted items.'
)
parser.add_argument(
'-s', '--successful', const='success', dest='filter',
action=UniqueAppendConstAction, help='Show successful items.'
)
args = parser.parse_args(['-f', '-a', '-s', '-f'])
print(args.filter)
# -> ['failed', 'aborted', 'success'] | 62599057d6c5a102081e3699 |
class VLANManager: <NEW_LINE> <INDENT> def __init__(self, zone: str): <NEW_LINE> <INDENT> ibmcloud_oc_vlan_ls_command_args = ["oc", "vlan", "ls", "--json", "--zone", zone] <NEW_LINE> ibmcloud_oc_vlan_ls_command_result = execute_ibmcloud_command( ibmcloud_oc_vlan_ls_command_args, capture_output=True ) <NEW_LINE> ibmcloud_oc_vlan_ls_command_result_json = json.loads(ibmcloud_oc_vlan_ls_command_result.stdout) <NEW_LINE> self._default_private_vlan = self._get_default_vlan_id( ibmcloud_oc_vlan_ls_command_result, ibmcloud_oc_vlan_ls_command_result_json, "private", zone, ) <NEW_LINE> self._default_public_vlan = self._get_default_vlan_id( ibmcloud_oc_vlan_ls_command_result, ibmcloud_oc_vlan_ls_command_result_json, "public", zone, ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def default_private_vlan(self) -> str: <NEW_LINE> <INDENT> return self._default_private_vlan <NEW_LINE> <DEDENT> @property <NEW_LINE> def default_public_vlan(self) -> str: <NEW_LINE> <INDENT> return self._default_public_vlan <NEW_LINE> <DEDENT> def _get_default_vlan_id( self, ibmcloud_oc_vlan_ls_command_result: ProcessResult, ibmcloud_oc_vlan_ls_command_result_json: Any, vlan_type: str, zone: str, ) -> str: <NEW_LINE> <INDENT> vlan_id: Optional[str] = None <NEW_LINE> for vlan in ibmcloud_oc_vlan_ls_command_result_json: <NEW_LINE> <INDENT> if vlan["type"] == vlan_type and vlan["properties"]["vlan_type"] == "standard": <NEW_LINE> <INDENT> vlan_id = vlan["id"] <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if vlan_id is None: <NEW_LINE> <INDENT> self._raise_error(ibmcloud_oc_vlan_ls_command_result, vlan_type, zone) <NEW_LINE> <DEDENT> return vlan_id <NEW_LINE> <DEDENT> def _raise_error( self, ibmcloud_oc_vlan_ls_command_result: ProcessResult, vlan_type: str, zone: str, ): <NEW_LINE> <INDENT> logging.info("Returned VLAN information:\n" + ibmcloud_oc_vlan_ls_command_result.stdout) <NEW_LINE> raise DataGateCLIException(f"Could not obtain default {vlan_type} VLAN ID for zone {zone}") | Determines available public and private VLANs for a zone in IBM
Cloud | 625990573617ad0b5ee076c3 |
class Nettle(Package): <NEW_LINE> <INDENT> homepage = "http://www.example.com" <NEW_LINE> url = "http://ftp.gnu.org/gnu/nettle/nettle-2.7.1.tar.gz" <NEW_LINE> version('2.7', '2caa1bd667c35db71becb93c5d89737f') <NEW_LINE> depends_on('gmp') <NEW_LINE> def install(self, spec, prefix): <NEW_LINE> <INDENT> configure("--prefix=%s" % prefix) <NEW_LINE> make() <NEW_LINE> make("install") | The Nettle package contains the low-level cryptographic library
that is designed to fit easily in many contexts. | 6259905730dc7b76659a0d3c |
class IChargeData(Interface): <NEW_LINE> <INDENT> title = Attribute( """unicode: the title of the charge""") <NEW_LINE> price = Attribute( """flaot: the price""") | An additional charge for an order
| 6259905791af0d3eaad3b3a3 |
class MoleProTest(unittest.TestCase): <NEW_LINE> <INDENT> def testLoadDzFromMoleProLog_F12(self): <NEW_LINE> <INDENT> log=MoleProLog(os.path.join(os.path.dirname(__file__),'test','ethylene_f12_dz.out')) <NEW_LINE> E0=log.loadCCSDEnergy() <NEW_LINE> self.assertAlmostEqual(E0 / constants.Na / constants.E_h, -78.474353559604, 5) <NEW_LINE> <DEDENT> def testLoadQzFromMoleProLog_F12(self): <NEW_LINE> <INDENT> log=MoleProLog(os.path.join(os.path.dirname(__file__),'test','ethylene_f12_qz.out')) <NEW_LINE> E0=log.loadCCSDEnergy() <NEW_LINE> self.assertAlmostEqual(E0 / constants.Na / constants.E_h, -78.472682755635, 5) <NEW_LINE> <DEDENT> def testLoadRadFromMoleProLog_F12(self): <NEW_LINE> <INDENT> log=MoleProLog(os.path.join(os.path.dirname(__file__),'test','OH_f12.out')) <NEW_LINE> E0=log.loadCCSDEnergy() <NEW_LINE> self.assertAlmostEqual(E0 / constants.Na / constants.E_h, -75.663696424380, 5) | Contains unit tests for the chempy.io.gaussian module, used for reading
and writing Molepro files. | 62599057baa26c4b54d5081f |
class PlainText(sprite.Sprite): <NEW_LINE> <INDENT> def __init__(self, font_name, font_size, text, font_color, pos) -> None: <NEW_LINE> <INDENT> self._font = font.Font(font_name, font_size) <NEW_LINE> self._text = text <NEW_LINE> self._font_color = font_color <NEW_LINE> self._pos = pos <NEW_LINE> super().__init__() <NEW_LINE> <DEDENT> @property <NEW_LINE> def image(self) -> pygame.Surface: <NEW_LINE> <INDENT> return self._font.render(self._text, True, self._font_color) <NEW_LINE> <DEDENT> @property <NEW_LINE> def rect(self) -> pygame.Rect: <NEW_LINE> <INDENT> return self.image.get_rect(center=self._pos) | Handle on-screen texts as sprites. | 625990573c8af77a43b689fd |
class silk_meta_profiler: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.start_time = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def _should_meta_profile(self): <NEW_LINE> <INDENT> return SilkyConfig().SILKY_META <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> if self._should_meta_profile: <NEW_LINE> <INDENT> self.start_time = timezone.now() <NEW_LINE> <DEDENT> <DEDENT> def __exit__(self, exc_type, exc_val, exc_tb): <NEW_LINE> <INDENT> if self._should_meta_profile: <NEW_LINE> <INDENT> end_time = timezone.now() <NEW_LINE> exception_raised = exc_type is not None <NEW_LINE> if exception_raised: <NEW_LINE> <INDENT> logger.error('Exception when performing meta profiling, dumping trace below') <NEW_LINE> traceback.print_exception(exc_type, exc_val, exc_tb) <NEW_LINE> <DEDENT> request = getattr(DataCollector().local, 'request', None) <NEW_LINE> if request: <NEW_LINE> <INDENT> curr = request.meta_time or 0 <NEW_LINE> request.meta_time = curr + _time_taken(self.start_time, end_time) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __call__(self, target): <NEW_LINE> <INDENT> if self._should_meta_profile: <NEW_LINE> <INDENT> def wrapped_target(*args, **kwargs): <NEW_LINE> <INDENT> request = DataCollector().request <NEW_LINE> if request: <NEW_LINE> <INDENT> start_time = timezone.now() <NEW_LINE> result = target(*args, **kwargs) <NEW_LINE> end_time = timezone.now() <NEW_LINE> curr = request.meta_time or 0 <NEW_LINE> request.meta_time = curr + _time_taken(start_time, end_time) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = target(*args, **kwargs) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> return wrapped_target <NEW_LINE> <DEDENT> return target | Used in the profiling of Silk itself. | 62599057ac7a0e7691f73a5b |
class ConvBN(nn.Module): <NEW_LINE> <INDENT> def __init__(self, nIn, nOut, norm_layer, kernel_size, padding=0, stride=1): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.norm_layer = norm_layer <NEW_LINE> if norm_layer == 'none' or norm_layer == 'instance': <NEW_LINE> <INDENT> self.cb = nn.Sequential(nn.Conv2d(nIn, nOut, (kernel_size, kernel_size), stride=stride, padding=(padding, padding), bias=False) ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.cb = nn.Sequential(nn.Conv2d(nIn, nOut, (kernel_size, kernel_size), stride=stride, padding=(padding, padding), bias=False), nn.BatchNorm2d(nOut, eps=1e-03) ) <NEW_LINE> <DEDENT> <DEDENT> def forward(self, input): <NEW_LINE> <INDENT> output = self.cb(input) <NEW_LINE> return output <NEW_LINE> <DEDENT> def fuse_model(self): <NEW_LINE> <INDENT> if self.norm_layer == 'none': <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> torch.quantization.fuse_modules(self.cb, ['0', '1'], inplace=True) | This class defines the convolution layer with batch normalization | 62599057b57a9660fecd2ff6 |
class Solution: <NEW_LINE> <INDENT> def removeElement(self, A, elem): <NEW_LINE> <INDENT> cur = 0 <NEW_LINE> for i in A: <NEW_LINE> <INDENT> if i != elem: <NEW_LINE> <INDENT> A[cur] = i <NEW_LINE> cur += 1 <NEW_LINE> <DEDENT> <DEDENT> return cur | @param A: A list of integers
@param elem: An integer
@return: The new length after remove | 6259905794891a1f408ba1b3 |
class MessageType(Enum): <NEW_LINE> <INDENT> GENERIC = 1 <NEW_LINE> ERROR = 2 <NEW_LINE> DEBUG = 3 | Enum for message logging | 62599057b5575c28eb713789 |
class TransformedBbox(BboxBase): <NEW_LINE> <INDENT> def __init__(self, bbox, transform): <NEW_LINE> <INDENT> assert bbox.is_bbox <NEW_LINE> assert isinstance(transform, Transform) <NEW_LINE> assert transform.input_dims == 2 <NEW_LINE> assert transform.output_dims == 2 <NEW_LINE> BboxBase.__init__(self) <NEW_LINE> self._bbox = bbox <NEW_LINE> self._transform = transform <NEW_LINE> self.set_children(bbox, transform) <NEW_LINE> self._points = None <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "TransformedBbox(%s, %s)" % (self._bbox, self._transform) <NEW_LINE> <DEDENT> __str__ = __repr__ <NEW_LINE> def get_points(self): <NEW_LINE> <INDENT> if self._invalid: <NEW_LINE> <INDENT> points = self._transform.transform(self._bbox.get_points()) <NEW_LINE> points = np.ma.filled(points, 0.0) <NEW_LINE> self._points = points <NEW_LINE> self._invalid = 0 <NEW_LINE> <DEDENT> return self._points <NEW_LINE> <DEDENT> get_points.__doc__ = Bbox.get_points.__doc__ <NEW_LINE> if DEBUG: <NEW_LINE> <INDENT> _get_points = get_points <NEW_LINE> def get_points(self): <NEW_LINE> <INDENT> points = self._get_points() <NEW_LINE> self._check(points) <NEW_LINE> return points | A :class:`Bbox` that is automatically transformed by a given
transform. When either the child bounding box or transform
changes, the bounds of this bbox will update accordingly. | 62599057379a373c97d9a59f |
@attr.s <NEW_LINE> class QuantifiedGraph(Graph): <NEW_LINE> <INDENT> quantifiers: List[Quantifier] = attr.ib(factory=list) | A graph which is quantified over as in predicate logic
:attribute universal_quantification_variables:
variables over which the whole graph, as a statement, is universally quantified.
For a concrete range of quantification, the QuantifiedGraph
is a cartesian product of loops over the quantification variables. However,
the range may be abstract, and we may not want to look at the fully expanded
graph in any case.
NB: "comprehension" is from list comprehensions in CS.
Example
--------
Trust relationships and flows are separated by locking variables.
For example, actors and data types can have the locking variable "tenant".
If an actor and a data type with the "tenant" locking variable show up
in a flow, this implies the concrete data flows are separated by
tenant. This same separation applies to requirements. | 625990571f037a2d8b9e5329 |
class LookupChannel(object): <NEW_LINE> <INDENT> model = None <NEW_LINE> plugin_options = {} <NEW_LINE> min_length = 1 <NEW_LINE> def get_query(self, object_id , q, request): <NEW_LINE> <INDENT> kwargs = { "%s__icontains" % self.search_field : q } <NEW_LINE> if object_id: <NEW_LINE> <INDENT> kwargs = {'pk':object_id} <NEW_LINE> <DEDENT> return self.model.objects.filter(**kwargs).order_by(self.search_field) <NEW_LINE> <DEDENT> def get_result(self,obj): <NEW_LINE> <INDENT> return unicode(obj) <NEW_LINE> <DEDENT> def format_match(self,obj): <NEW_LINE> <INDENT> return unicode(obj) <NEW_LINE> <DEDENT> def format_item_display(self,obj): <NEW_LINE> <INDENT> return unicode(obj) <NEW_LINE> <DEDENT> def get_objects(self,ids): <NEW_LINE> <INDENT> ids = [int(id) for id in ids] <NEW_LINE> things = self.model.objects.in_bulk(ids) <NEW_LINE> return [things[aid] for aid in ids if things.has_key(aid)] <NEW_LINE> <DEDENT> def can_add(self,user,argmodel): <NEW_LINE> <INDENT> ctype = ContentType.objects.get_for_model(argmodel) <NEW_LINE> return user.has_perm("%s.add_%s" % (ctype.app_label,ctype.model)) <NEW_LINE> <DEDENT> def check_auth(self,request): <NEW_LINE> <INDENT> if not request.user.is_staff: <NEW_LINE> <INDENT> raise PermissionDenied | Subclass this, setting model and overiding the methods below to taste | 62599057be383301e0254d4a |
class InternalCollector(Collector): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.buf = [] <NEW_LINE> <DEDENT> def collect(self, a: Any): <NEW_LINE> <INDENT> self.buf.append((2, a)) <NEW_LINE> <DEDENT> def clear(self): <NEW_LINE> <INDENT> self.buf.clear() | Internal implementation of the Collector. It uses a buffer list to store data to be emitted.
There will be a header flag for each data type. 0 means it is a proc time timer registering
request, while 1 means it is an event time timer and 2 means it is a normal data. When
registering a timer, it must take along with the corresponding key for it.
For a ProcessFunction, it will only collect normal data. | 62599057379a373c97d9a5a0 |
class Entity(object): <NEW_LINE> <INDENT> def __init__(self, shape, speed): <NEW_LINE> <INDENT> self._shape = shape <NEW_LINE> self.setSpeed(speed) <NEW_LINE> self._last_direction = "" <NEW_LINE> <DEDENT> def move(self, direction): <NEW_LINE> <INDENT> self._last_direction = direction <NEW_LINE> self._shape.move(direction, self._speed) <NEW_LINE> <DEDENT> def getPosition(self, ): <NEW_LINE> <INDENT> return self._shape.getPosition() <NEW_LINE> <DEDENT> def setPosition(self, new_pos): <NEW_LINE> <INDENT> self._shape.setPosition(new_pos) <NEW_LINE> <DEDENT> def getShape(self): <NEW_LINE> <INDENT> return self._shape <NEW_LINE> <DEDENT> def setShape(self, new_shape): <NEW_LINE> <INDENT> self._shape = new_shape <NEW_LINE> <DEDENT> def getSpeed(self): <NEW_LINE> <INDENT> return self._speed <NEW_LINE> <DEDENT> def setSpeed(self, new_speed): <NEW_LINE> <INDENT> self._speed = float(new_speed) <NEW_LINE> <DEDENT> @property <NEW_LINE> def x(self): <NEW_LINE> <INDENT> return self.getPosition()[0] <NEW_LINE> <DEDENT> @property <NEW_LINE> def y(self): <NEW_LINE> <INDENT> return self.getPosition()[1] <NEW_LINE> <DEDENT> @property <NEW_LINE> def radius(self): <NEW_LINE> <INDENT> return self._shape.getRadius() <NEW_LINE> <DEDENT> @property <NEW_LINE> def size(self): <NEW_LINE> <INDENT> return self._shape.getSize() | An entity in the simulation.
| 62599057d486a94d0ba2d543 |
class NodeMan(object): <NEW_LINE> <INDENT> def __init__(self, grid_obj): <NEW_LINE> <INDENT> if grid_obj.grid is None: <NEW_LINE> <INDENT> raise Exception('Grid object is not initialized!') <NEW_LINE> <DEDENT> self.grid = grid_obj <NEW_LINE> self.nodevals = {} <NEW_LINE> self.metadata = {} <NEW_LINE> self.index = -1 <NEW_LINE> <DEDENT> def _get_next_index(self): <NEW_LINE> <INDENT> self.index += 1 <NEW_LINE> return self.index <NEW_LINE> <DEDENT> def add_data(self, data): <NEW_LINE> <INDENT> subdata = np.atleast_2d(data) <NEW_LINE> if subdata.shape[1] != self.grid.nr_of_nodes: <NEW_LINE> <INDENT> if subdata.shape[0] == self.grid.nr_of_nodes: <NEW_LINE> <INDENT> subdata = subdata.T <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception( 'Number of values does not match the number of ' + 'nodes in the grid {0} grid nodes vs {1} data'.format( self.grid.nr_of_nodes, subdata.shape, ) ) <NEW_LINE> <DEDENT> <DEDENT> return_ids = [] <NEW_LINE> for dataset in subdata: <NEW_LINE> <INDENT> cid = self._get_next_index() <NEW_LINE> self.nodevals[cid] = dataset.copy() <NEW_LINE> return_ids.append(cid) <NEW_LINE> <DEDENT> if len(return_ids) == 1: <NEW_LINE> <INDENT> return return_ids[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return return_ids | manage one or more node value sets for a given
:class:`crtomo.grid.crt_grid` object | 62599057e5267d203ee6ce6a |
class HacsOptionsFlowHandler(config_entries.OptionsFlow): <NEW_LINE> <INDENT> def __init__(self, config_entry): <NEW_LINE> <INDENT> self.config_entry = config_entry <NEW_LINE> <DEDENT> async def async_step_init(self, user_input=None): <NEW_LINE> <INDENT> return await self.async_step_user() <NEW_LINE> <DEDENT> async def async_step_user(self, user_input=None): <NEW_LINE> <INDENT> if user_input is not None: <NEW_LINE> <INDENT> return self.async_create_entry(title="", data=user_input) <NEW_LINE> <DEDENT> if Hacs.configuration.config_type == "yaml": <NEW_LINE> <INDENT> schema = {vol.Optional("not_in_use", default=""): str} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> schema = hacs_config_option_schema(self.config_entry.options) <NEW_LINE> <DEDENT> return self.async_show_form(step_id="user", data_schema=vol.Schema(schema)) | HACS config flow options handler. | 6259905715baa7234946350e |
class AMQPObject(object): <NEW_LINE> <INDENT> NAME = 'AMQPObject' <NEW_LINE> INDEX = None <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> items = list() <NEW_LINE> for key, value in self.__dict__.items(): <NEW_LINE> <INDENT> if getattr(self.__class__, key, None) != value: <NEW_LINE> <INDENT> items.append('%s=%s' % (key, value)) <NEW_LINE> <DEDENT> <DEDENT> if not items: <NEW_LINE> <INDENT> return "<%s>" % self.NAME <NEW_LINE> <DEDENT> return "<%s(%s)>" % (self.NAME, items) | Base object that is extended by AMQP low level frames and AMQP classes
and methods. | 62599057be8e80087fbc05fe |
class tcMensagemRetorno (pyxb.binding.basis.complexTypeDefinition): <NEW_LINE> <INDENT> _TypeDefinition = None <NEW_LINE> _ContentTypeTag = pyxb.binding.basis.complexTypeDefinition._CT_ELEMENT_ONLY <NEW_LINE> _Abstract = False <NEW_LINE> _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'tcMensagemRetorno') <NEW_LINE> _XSDLocation = pyxb.utils.utility.Location('/home/leonardo/Projetos/PyNFe/nfse_v202.xsd', 671, 1) <NEW_LINE> _ElementMap = {} <NEW_LINE> _AttributeMap = {} <NEW_LINE> __Codigo = pyxb.binding.content.ElementDeclaration(pyxb.namespace.ExpandedName(Namespace, 'Codigo'), 'Codigo', '__httpwww_betha_com_bre_nota_contribuinte_ws_tcMensagemRetorno_httpwww_betha_com_bre_nota_contribuinte_wsCodigo', False, pyxb.utils.utility.Location('/home/leonardo/Projetos/PyNFe/nfse_v202.xsd', 673, 3), ) <NEW_LINE> Codigo = property(__Codigo.value, __Codigo.set, None, None) <NEW_LINE> __Mensagem = pyxb.binding.content.ElementDeclaration(pyxb.namespace.ExpandedName(Namespace, 'Mensagem'), 'Mensagem', '__httpwww_betha_com_bre_nota_contribuinte_ws_tcMensagemRetorno_httpwww_betha_com_bre_nota_contribuinte_wsMensagem', False, pyxb.utils.utility.Location('/home/leonardo/Projetos/PyNFe/nfse_v202.xsd', 675, 3), ) <NEW_LINE> Mensagem = property(__Mensagem.value, __Mensagem.set, None, None) <NEW_LINE> __Correcao = pyxb.binding.content.ElementDeclaration(pyxb.namespace.ExpandedName(Namespace, 'Correcao'), 'Correcao', '__httpwww_betha_com_bre_nota_contribuinte_ws_tcMensagemRetorno_httpwww_betha_com_bre_nota_contribuinte_wsCorrecao', False, pyxb.utils.utility.Location('/home/leonardo/Projetos/PyNFe/nfse_v202.xsd', 677, 3), ) <NEW_LINE> Correcao = property(__Correcao.value, __Correcao.set, None, None) <NEW_LINE> _ElementMap.update({ __Codigo.name() : __Codigo, __Mensagem.name() : __Mensagem, __Correcao.name() : __Correcao }) <NEW_LINE> _AttributeMap.update({ }) | Complex type {http://www.betha.com.br/e-nota-contribuinte-ws}tcMensagemRetorno with content type ELEMENT_ONLY | 625990577cff6e4e811b6fbe |
class NoModuleNameError(Error): <NEW_LINE> <INDENT> def __init__(self, moduleName): <NEW_LINE> <INDENT> Error.__init__(self, 'No module name: %r' % (moduleName,)) <NEW_LINE> self.moduleName = moduleName | Raised when no module name matches | 6259905763d6d428bbee3d45 |
class AssociationControl(object): <NEW_LINE> <INDENT> changeAP = False <NEW_LINE> def __init__(self, intf, ap_intf, ac): <NEW_LINE> <INDENT> if ac in dir(self): <NEW_LINE> <INDENT> self.__getattribute__(ac)(intf, ap_intf) <NEW_LINE> <DEDENT> <DEDENT> def llf(self, intf, ap_intf): <NEW_LINE> <INDENT> apref = intf.associatedTo <NEW_LINE> if apref: <NEW_LINE> <INDENT> ref_llf = len(apref.associatedStations) <NEW_LINE> if len(ap_intf.associatedStations) + 2 < ref_llf: <NEW_LINE> <INDENT> intf.disconnect_pexec(apref) <NEW_LINE> self.changeAP = True <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.changeAP = True <NEW_LINE> <DEDENT> return self.changeAP <NEW_LINE> <DEDENT> def ssf(self, intf, ap_intf): <NEW_LINE> <INDENT> dist = intf.node.get_distance_to(intf.associatedTo.node) <NEW_LINE> rssi = intf.get_rssi(ap_intf, dist) <NEW_LINE> ref_dist = intf.node.get_distance_to(ap_intf.node) <NEW_LINE> ref_rssi = intf.get_rssi(ap_intf, ref_dist) <NEW_LINE> if float(ref_rssi) > float(rssi + 0.1): <NEW_LINE> <INDENT> intf.disconnect_pexec(ap_intf) <NEW_LINE> self.changeAP = True <NEW_LINE> <DEDENT> return self.changeAP | Mechanisms that optimize the use of the APs | 625990578e71fb1e983bd045 |
class RectangularArenaTwoByOne(RectangularArena): <NEW_LINE> <INDENT> def __init__(self, x_range: range, y_range: range, z: int, dist_type: str) -> None: <NEW_LINE> <INDENT> super().__init__([ArenaExtent(Vector3D(x, y, z)) for x in x_range for y in y_range], dist_type=dist_type) | Define arenas that vary in size for each combination of extents in the specified X range and
Y range, where the X dimension is always twices as large as the Y dimension. | 6259905707f4c71912bb09b6 |
class ClasseFonction(Fonction): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def init_types(cls): <NEW_LINE> <INDENT> cls.ajouter_types(cls.niveau_principal, "Personnage") <NEW_LINE> cls.ajouter_types(cls.niveau_secondaire, "Personnage", "str") <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def niveau_principal(personnage): <NEW_LINE> <INDENT> return Fraction(personnage.niveau) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def niveau_secondaire(personnage, niveau): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> niveau = importeur.perso.get_niveau_par_nom(niveau) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise ErreurExecution("Niveau inconnu : {}".format(niveau)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Fraction(personnage.niveaux.get(niveau.cle, 1)) | Retourne le niveau d'un personnage. | 6259905763b5f9789fe866ef |
@six.add_metaclass(abc.ABCMeta) <NEW_LINE> class Service(service.Service): <NEW_LINE> <INDENT> def __init__(self, threads=None): <NEW_LINE> <INDENT> threads = threads or 1000 <NEW_LINE> super(Service, self).__init__(threads) <NEW_LINE> self._host = CONF.host <NEW_LINE> self._service_config = CONF['service:%s' % self.service_name] <NEW_LINE> policy.init() <NEW_LINE> if not rpc.initialized(): <NEW_LINE> <INDENT> rpc.init(CONF) <NEW_LINE> <DEDENT> <DEDENT> @abc.abstractproperty <NEW_LINE> def service_name(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> super(Service, self).start() <NEW_LINE> LOG.info(_('Starting %(name)s service (version: %(version)s)') % {'name': self.service_name, 'version': version.version_info.version_string()}) <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> LOG.info(_('Stopping %(name)s service') % {'name': self.service_name}) <NEW_LINE> super(Service, self).stop() | Service class to be shared among the diverse service inside of Designate. | 62599057097d151d1a2c25e7 |
class Cell: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.northwest = None <NEW_LINE> self.north = None <NEW_LINE> self.northeast = None <NEW_LINE> self.east = None <NEW_LINE> self.southeast = None <NEW_LINE> self.south = None <NEW_LINE> self.southwest = None <NEW_LINE> self.west = None <NEW_LINE> <DEDENT> def propagate_light(self, source_direction, source_coordinates, max_distance): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def neighbour(self, direction): <NEW_LINE> <INDENT> if direction == "NW": <NEW_LINE> <INDENT> return self.northwest <NEW_LINE> <DEDENT> elif direction == "N": <NEW_LINE> <INDENT> return self.north <NEW_LINE> <DEDENT> elif direction == "NE": <NEW_LINE> <INDENT> return self.northeast <NEW_LINE> <DEDENT> elif direction == "E": <NEW_LINE> <INDENT> return self.east <NEW_LINE> <DEDENT> elif direction == "SE": <NEW_LINE> <INDENT> return self.southeast <NEW_LINE> <DEDENT> elif direction == "S": <NEW_LINE> <INDENT> return self.south <NEW_LINE> <DEDENT> elif direction == "SW": <NEW_LINE> <INDENT> return self.southwest <NEW_LINE> <DEDENT> elif direction == "W": <NEW_LINE> <INDENT> return self.west <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert(False) | A generic Hall of Mirrors cell. | 6259905799cbb53fe683245b |
class DelimiterToken(SimpleTokenClass, Enum): <NEW_LINE> <INDENT> QUOTE = '"' <NEW_LINE> COLON = ":" <NEW_LINE> COMMA = "," <NEW_LINE> AT = "@" <NEW_LINE> EQUALS = "=" <NEW_LINE> EXCLAMATION_MARK = "!" <NEW_LINE> RANGE = ".." <NEW_LINE> SEMICOLON = ";" <NEW_LINE> NUMBER_SIGN = "#" <NEW_LINE> OPEN_PARENTHESES = "(" <NEW_LINE> CLOSE_PARENTHESES = ")" <NEW_LINE> OPEN_SQUARE_BRACKET = "[" <NEW_LINE> CLOSE_SQUARE_BRACKET = "]" <NEW_LINE> OPEN_CURLY_BRACKET = "{" <NEW_LINE> CLOSE_CURLY_BRACKET = "}" | Contains the type and value | 62599057009cb60464d02ab1 |
class Templater(L.NodeTransformer): <NEW_LINE> <INDENT> def __init__(self, subst): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.name_subst = {} <NEW_LINE> self.ident_subst = {} <NEW_LINE> self.code_subst = {} <NEW_LINE> for k, v in subst.items(): <NEW_LINE> <INDENT> if k.startswith('<c>'): <NEW_LINE> <INDENT> suffix = k[len('<c>'):] <NEW_LINE> self.code_subst[suffix] = v <NEW_LINE> <DEDENT> elif isinstance(v, str): <NEW_LINE> <INDENT> self.ident_subst[k] = v <NEW_LINE> <DEDENT> elif isinstance(v, L.expr): <NEW_LINE> <INDENT> self.name_subst[k] = v <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError('Bad template mapping: {} -> {}'.format( k, v)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def ident_helper(self, node, field): <NEW_LINE> <INDENT> old = getattr(node, field) <NEW_LINE> if isinstance(old, tuple): <NEW_LINE> <INDENT> new = tuple(self.ident_subst.get(v, v) for v in old) <NEW_LINE> <DEDENT> elif isinstance(old, str): <NEW_LINE> <INDENT> new = self.ident_subst.get(old, old) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert() <NEW_LINE> <DEDENT> if new != old: <NEW_LINE> <INDENT> node = node._replace(**{field: new}) <NEW_LINE> <DEDENT> return node <NEW_LINE> <DEDENT> def generic_visit(self, node): <NEW_LINE> <INDENT> node = super().generic_visit(node) <NEW_LINE> id_fields = L.ident_fields.get(node.__class__.__name__, []) <NEW_LINE> for f in id_fields: <NEW_LINE> <INDENT> node = self.ident_helper(node, f) <NEW_LINE> <DEDENT> return node <NEW_LINE> <DEDENT> def visit_Name(self, node): <NEW_LINE> <INDENT> if node.id in self.name_subst: <NEW_LINE> <INDENT> node = self.name_subst[node.id] <NEW_LINE> <DEDENT> elif node.id in self.ident_subst: <NEW_LINE> <INDENT> node = node._replace(id=self.ident_subst[node.id]) <NEW_LINE> <DEDENT> return node <NEW_LINE> <DEDENT> def visit_Expr(self, node): <NEW_LINE> <INDENT> if (isinstance(node.value, L.Name) and node.value.id in self.code_subst): <NEW_LINE> <INDENT> node = self.code_subst[node.value.id] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> node = self.generic_visit(node) <NEW_LINE> <DEDENT> return node | Transformer for instantiating placeholders with different names
or arbitrary code. Analogous to iast.python.python34.Templater.
The templater takes in a mapping whose keys are strings.
The following kinds of entries are recognized:
IDENT -> EXPR
Replace Name nodes having IDENT as their id with an
arbitrary expression AST.
IDENT1 -> IDENT2
Replace all occurrences of IDENT1 with IDENT2. This includes
non-Name occurrences such as attribute identifiers, function
identifiers, and relation operations.
<c>IDENT -> CODE
Replace all occurrences of Expr nodes directly containing
a Name node having IDENT as its id, with the statement or
sequence of statements CODE.
Template substitution is not recursive, i.e., replacement code
is used as-is. | 6259905755399d3f05627a9b |
class SimpleSCardAppEventObserver: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.selectedcard = None <NEW_LINE> self.selectedreader = None <NEW_LINE> <DEDENT> def OnActivateCard(self, card): <NEW_LINE> <INDENT> self.selectedcard = card <NEW_LINE> <DEDENT> def OnActivateReader(self, reader): <NEW_LINE> <INDENT> self.selectedreader = reader <NEW_LINE> <DEDENT> def OnDeactivateCard(self, card): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def OnDeselectCard(self, card): <NEW_LINE> <INDENT> self.selectedcard = None <NEW_LINE> <DEDENT> def OnSelectCard(self, card): <NEW_LINE> <INDENT> self.selectedcard = card <NEW_LINE> <DEDENT> def OnSelectReader(self, reader): <NEW_LINE> <INDENT> self.selectedreader = reader | This interface defines the event handlers called by the SimpleSCardApp. | 6259905721a7993f00c674e9 |
class UnknownLocation(Location): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__(name='Unknown Location', entitytype=UNKNOWN_LOCATION) <NEW_LINE> <DEDENT> def visit(self): <NEW_LINE> <INDENT> assert False, "Should never be able to visit() the (conceptual, abstract) UnknownLocation" <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_known(self): <NEW_LINE> <INDENT> assert self._discovered is False <NEW_LINE> return False <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "<Unknown Location>[" + str(', '.join([item.name for item in self.entities]))+"]" <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str(self) | Holder for entities that we know about, but don't (yet) know where they are. | 62599057b57a9660fecd2ff7 |
class DefaultNodeDoesNotExistError(NodeDoesNotExistError): <NEW_LINE> <INDENT> pass | Missing default node for currency. | 625990572ae34c7f260ac663 |
class IImportStepDirective(Interface): <NEW_LINE> <INDENT> name = zope.schema.TextLine( title=u'Name', description=u'', required=True) <NEW_LINE> title = MessageID( title=u'Title', description=u'', required=True) <NEW_LINE> description = MessageID( title=u'Description', description=u'', required=True) <NEW_LINE> handler = GlobalObject( title=u'Handler', description=u'', required=True) | Register import steps with the global registry.
| 6259905707f4c71912bb09b7 |
class Parser(): <NEW_LINE> <INDENT> def __init__(self, raw_string): <NEW_LINE> <INDENT> self.raw_string = raw_string <NEW_LINE> <DEDENT> def format_lrs(self, legacy_format=False): <NEW_LINE> <INDENT> equilibria = [] <NEW_LINE> from sage.misc.sage_eval import sage_eval <NEW_LINE> from itertools import groupby, dropwhile <NEW_LINE> lines = iter(self.raw_string) <NEW_LINE> if legacy_format: <NEW_LINE> <INDENT> while not next(lines).startswith("*****"): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> lines = dropwhile(lambda line: line.startswith('*'), lines) <NEW_LINE> <DEDENT> for collection in [list(x[1]) for x in groupby(lines, lambda x: x == '\n')]: <NEW_LINE> <INDENT> if collection[0].startswith('2'): <NEW_LINE> <INDENT> s1 = tuple([sage_eval(k) for k in collection[-1].split()][1:-1]) <NEW_LINE> for s2 in collection[:-1]: <NEW_LINE> <INDENT> s2 = tuple([sage_eval(k) for k in s2.split()][1:-1]) <NEW_LINE> equilibria.append([s1, s2]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return equilibria <NEW_LINE> <DEDENT> def format_gambit(self, gambit_game): <NEW_LINE> <INDENT> nice_stuff = [] <NEW_LINE> for gambitstrategy in self.raw_string: <NEW_LINE> <INDENT> gambitstrategy = list(gambitstrategy) <NEW_LINE> profile = [tuple(gambitstrategy[:len(gambit_game.players[int(0)].strategies)])] <NEW_LINE> for player in list(gambit_game.players)[1:]: <NEW_LINE> <INDENT> previousplayerstrategylength = len(profile[-1]) <NEW_LINE> profile.append(tuple(gambitstrategy[previousplayerstrategylength: previousplayerstrategylength + len(player.strategies)])) <NEW_LINE> <DEDENT> nice_stuff.append(profile) <NEW_LINE> <DEDENT> return nice_stuff | A class for parsing the outputs of different algorithms called in other
software packages.
Two parsers are included, one for the ``'lrs'`` algorithm and another for
the ``'LCP'`` algorithm. | 62599057cb5e8a47e493cc45 |
class BooleanArrayIndexer(Indexer): <NEW_LINE> <INDENT> def __init__(self, context, builder, idxty, idxary): <NEW_LINE> <INDENT> self.context = context <NEW_LINE> self.builder = builder <NEW_LINE> self.idxty = idxty <NEW_LINE> self.idxary = idxary <NEW_LINE> assert idxty.ndim == 1 <NEW_LINE> self.ll_intp = self.context.get_value_type(types.intp) <NEW_LINE> self.zero = Constant.int(self.ll_intp, 0) <NEW_LINE> <DEDENT> def prepare(self): <NEW_LINE> <INDENT> builder = self.builder <NEW_LINE> self.size = cgutils.unpack_tuple(builder, self.idxary.shape)[0] <NEW_LINE> self.idx_index = cgutils.alloca_once(builder, self.ll_intp) <NEW_LINE> self.count = cgutils.alloca_once(builder, self.ll_intp) <NEW_LINE> self.bb_start = builder.append_basic_block() <NEW_LINE> self.bb_tail = builder.append_basic_block() <NEW_LINE> self.bb_end = builder.append_basic_block() <NEW_LINE> <DEDENT> def get_size(self): <NEW_LINE> <INDENT> builder = self.builder <NEW_LINE> count = cgutils.alloca_once_value(builder, self.zero) <NEW_LINE> with cgutils.for_range(builder, self.size) as loop: <NEW_LINE> <INDENT> c = builder.load(count) <NEW_LINE> pred = _getitem_array1d(self.context, builder, self.idxty, self.idxary, loop.index, wraparound=False) <NEW_LINE> c = builder.add(c, builder.zext(pred, c.type)) <NEW_LINE> builder.store(c, count) <NEW_LINE> <DEDENT> return builder.load(count) <NEW_LINE> <DEDENT> def get_shape(self): <NEW_LINE> <INDENT> return (self.get_size(),) <NEW_LINE> <DEDENT> def get_index_bounds(self): <NEW_LINE> <INDENT> return (self.ll_intp(0), self.size) <NEW_LINE> <DEDENT> def loop_head(self): <NEW_LINE> <INDENT> builder = self.builder <NEW_LINE> self.builder.store(self.zero, self.idx_index) <NEW_LINE> self.builder.store(self.zero, self.count) <NEW_LINE> builder.branch(self.bb_start) <NEW_LINE> builder.position_at_end(self.bb_start) <NEW_LINE> cur_index = builder.load(self.idx_index) <NEW_LINE> cur_count = builder.load(self.count) <NEW_LINE> with builder.if_then(builder.icmp_signed('>=', cur_index, self.size), likely=False): <NEW_LINE> <INDENT> builder.branch(self.bb_end) <NEW_LINE> <DEDENT> pred = _getitem_array1d(self.context, builder, self.idxty, self.idxary, cur_index, wraparound=False) <NEW_LINE> with builder.if_then(builder.not_(pred)): <NEW_LINE> <INDENT> builder.branch(self.bb_tail) <NEW_LINE> <DEDENT> next_count = cgutils.increment_index(builder, cur_count) <NEW_LINE> builder.store(next_count, self.count) <NEW_LINE> return cur_index, cur_count <NEW_LINE> <DEDENT> def loop_tail(self): <NEW_LINE> <INDENT> builder = self.builder <NEW_LINE> builder.branch(self.bb_tail) <NEW_LINE> builder.position_at_end(self.bb_tail) <NEW_LINE> next_index = cgutils.increment_index(builder, builder.load(self.idx_index)) <NEW_LINE> builder.store(next_index, self.idx_index) <NEW_LINE> builder.branch(self.bb_start) <NEW_LINE> builder.position_at_end(self.bb_end) | Compute indices from an array of boolean predicates. | 6259905710dbd63aa1c72138 |
class Output: <NEW_LINE> <INDENT> plot = FileField(label="QC multiplot") <NEW_LINE> summary = FileField(label="QC summary") <NEW_LINE> qorts_data = FileField(label="QoRTs report data") | Output fields. | 625990578a43f66fc4bf370b |
class MalformattedLocationKeyError(BaseException): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return(u"Malformatted location key: the location key must be an integer number and must be " u"entered as such.") | The location key is malformatted. This is raised when a primary (non-POI) location key is entered that does not fit
the formal specifications. | 62599057462c4b4f79dbcf82 |
class Pipelines(cli_base.Group): <NEW_LINE> <INDENT> commands = [ (_ListPipeline, "actions") ] <NEW_LINE> def setup(self): <NEW_LINE> <INDENT> parser = self._parser.add_parser( "pipeline", help="Operations related to pipeline management.") <NEW_LINE> actions = parser.add_subparsers() <NEW_LINE> self._register_parser("actions", actions) | Group for all the available pipelines actions. | 62599057d6c5a102081e369d |
class EventViewer(urwid.WidgetWrap): <NEW_LINE> <INDENT> def __init__(self, conf, collection): <NEW_LINE> <INDENT> self.conf = conf <NEW_LINE> self.collection = collection <NEW_LINE> pile = CPile([]) <NEW_LINE> urwid.WidgetWrap.__init__(self, pile) | Base Class for EventEditor and EventDisplay | 62599057460517430c432b10 |
class ActivateUserForm1(forms.Form): <NEW_LINE> <INDENT> username = forms.CharField(max_length=30, label=_("Username"), required=True) <NEW_LINE> new_password1 = forms.CharField(label=_("New password"), widget=forms.PasswordInput) <NEW_LINE> new_password2 = forms.CharField( label=_("New password confirmation"), widget=forms.PasswordInput ) <NEW_LINE> error_messages = { "password_mismatch": _("The two password fields didn't match."), } <NEW_LINE> def clean_username(self): <NEW_LINE> <INDENT> username = self.cleaned_data.get("username") <NEW_LINE> if " " in username: <NEW_LINE> <INDENT> raise ValidationError(_("Whitespace not allowed.")) <NEW_LINE> <DEDENT> users = User.objects.filter(username=username) <NEW_LINE> if users.exists(): <NEW_LINE> <INDENT> raise ValidationError(_("{} is already taken.").format(username)) <NEW_LINE> <DEDENT> return username <NEW_LINE> <DEDENT> def clean_new_password1(self): <NEW_LINE> <INDENT> password1 = self.cleaned_data.get("new_password1") <NEW_LINE> validate_password(password1) <NEW_LINE> return password1 <NEW_LINE> <DEDENT> def clean_new_password2(self): <NEW_LINE> <INDENT> password1 = self.cleaned_data.get("new_password1") <NEW_LINE> password2 = self.cleaned_data.get("new_password2") <NEW_LINE> if password1 and password2: <NEW_LINE> <INDENT> if password1 != password2: <NEW_LINE> <INDENT> raise ValidationError(self.error_messages["password_mismatch"]) <NEW_LINE> <DEDENT> <DEDENT> return password2 | Form used by a user to activate his/her account. | 62599057d99f1b3c44d06c1e |
class TwoLayerNet(object): <NEW_LINE> <INDENT> def __init__(self, input_dim=3*32*32, hidden_dim=100, num_classes=10, weight_scale=1e-3, reg=0.0): <NEW_LINE> <INDENT> self.params = {} <NEW_LINE> self.reg = reg <NEW_LINE> self.params['W1'] = weight_scale * np.random.randn(input_dim, hidden_dim) <NEW_LINE> self.params['b1'] = np.zeros(hidden_dim) <NEW_LINE> self.params['W2'] = weight_scale * np.random.randn(hidden_dim, num_classes) <NEW_LINE> self.params['b2'] = np.zeros(num_classes) <NEW_LINE> <DEDENT> def loss(self, X, y=None): <NEW_LINE> <INDENT> scores = None <NEW_LINE> out_1, cache_1 = affine_relu_forward(X, self.params['W1'], self.params['b1']) <NEW_LINE> out_2, cache_2 = affine_forward(out_1, self.params['W2'], self.params['b2']) <NEW_LINE> scores = out_2 <NEW_LINE> if y is None: <NEW_LINE> <INDENT> return scores <NEW_LINE> <DEDENT> loss, grads = 0, {} <NEW_LINE> loss, dscores = softmax_loss(scores, y) <NEW_LINE> loss += 0.5 * self.reg * (np.sum(self.params["W1"] ** 2) + np.sum(self.params["W2"] ** 2)) <NEW_LINE> dx2, grads["W2"], grads["b2"] = affine_backward(dscores, cache_2) <NEW_LINE> dx1, grads["W1"], grads["b1"] = affine_relu_backward(dx2, cache_1) <NEW_LINE> grads["W1"] += self.reg * self.params['W1'] <NEW_LINE> grads["W2"] += self.reg * self.params['W2'] <NEW_LINE> return loss, grads | A two-layer fully-connected neural network with ReLU nonlinearity and
softmax loss that uses a modular layer design. We assume an input dimension
of D, a hidden dimension of H, and perform classification over C classes.
The architecure should be affine - relu - affine - softmax.
Note that this class does not implement gradient descent; instead, it
will interact with a separate Solver object that is responsible for running
optimization.
The learnable parameters of the model are stored in the dictionary
self.params that maps parameter names to numpy arrays. | 625990578e7ae83300eea60b |
class Perceptron: <NEW_LINE> <INDENT> def __init__(self, input_size, output_size): <NEW_LINE> <INDENT> self.h1 = tf.Variable(tf.truncated_normal([input_size, output_size])) <NEW_LINE> self.b1 = tf.Variable(tf.zeros([output_size])) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "h1%s b1%s" % (self.h1.eval().flatten(), self.b1.eval().flatten()) <NEW_LINE> <DEDENT> @property <NEW_LINE> def weights(self): <NEW_LINE> <INDENT> return [self.h1, self.b1] <NEW_LINE> <DEDENT> def predict(self, x): <NEW_LINE> <INDENT> return tf.matmul(x, self.h1) + self.b1 | Single layer perceptron network
| 62599057baa26c4b54d50823 |
class FlipLR(Scale): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__([-1, 1], 1) | Flip left-right. | 62599057f7d966606f749377 |
class Menu: <NEW_LINE> <INDENT> def prompt_valid(self, reverseorder=False, definedquestion='',allowlong=False): <NEW_LINE> <INDENT> if definedquestion: <NEW_LINE> <INDENT> self.question = definedquestion <NEW_LINE> <DEDENT> options = '\n '.join("{!s}: {!s}".format(key,val) for (key,val) in sorted(self.validanswers.items())) <NEW_LINE> question = "{}\n{}{}\n>".format(self.question,' ',options) <NEW_LINE> if reverseorder: <NEW_LINE> <INDENT> options = '\n '.join("{!s}: {!s}".format(key,val) for (key,val) in sorted(self.validanswers.items())) <NEW_LINE> question = "{}{}\n\n\n{}\n>".format('\n ', options, self.question) <NEW_LINE> <DEDENT> self.answer=input(question) <NEW_LINE> while self.answer not in self.validanswers.keys(): <NEW_LINE> <INDENT> if allowlong and len(self.answer) > 3: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> self.answer = input("Please give a valid answer.\n {}".format(question)) <NEW_LINE> <DEDENT> return self.answer <NEW_LINE> <DEDENT> def prompt(self): <NEW_LINE> <INDENT> question = "{}".format(self.question) <NEW_LINE> self.answer=input(question) <NEW_LINE> return self.answer | Any command line menus that are used to ask the user for input | 6259905763b5f9789fe866f1 |
class rpmvalidation(module_framework.AvocadoTest): <NEW_LINE> <INDENT> fhs_base_paths_workaound = [ '/var/kerberos', '/var/db' ] <NEW_LINE> fhs_base_paths = [ '/bin', '/boot', '/dev', '/etc', '/home', '/lib', '/lib64', '/media', '/mnt', '/opt', '/proc', '/root', '/run', '/sbin', '/sys', '/srv', '/tmp', '/usr/bin', '/usr/include', '/usr/lib', '/usr/libexec', '/usr/lib64', '/usr/local', '/usr/sbin', '/usr/share', '/usr/src', '/var/account', '/var/cache', '/var/crash', '/var/games', '/var/lib', '/var/lock', '/var/log', '/var/mail', '/var/opt', '/var/run', '/var/spool', '/var/tmp', '/var/yp' ] + fhs_base_paths_workaound <NEW_LINE> def _compare_fhs(self, filepath): <NEW_LINE> <INDENT> if '(contains no files)' in filepath or filepath in self.fhs_base_paths: <NEW_LINE> <INDENT> self.log.info("no files there (trivial case), or this is filesystem package") <NEW_LINE> return True <NEW_LINE> <DEDENT> for path in self.fhs_base_paths: <NEW_LINE> <INDENT> if filepath.startswith(path): <NEW_LINE> <INDENT> self.log.info("%s starts with FSH %s" % (filepath, path)) <NEW_LINE> return True <NEW_LINE> <DEDENT> <DEDENT> self.log.info("%s not found in %s" % (filepath, self.fhs_base_paths)) <NEW_LINE> return False <NEW_LINE> <DEDENT> def test(self): <NEW_LINE> <INDENT> allpackages = filter(bool, self.run("rpm -qa").stdout.split("\n")) <NEW_LINE> common.print_debug(allpackages) <NEW_LINE> for package in allpackages: <NEW_LINE> <INDENT> if 'filesystem' in package: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for package_file in filter(bool, self.run("rpm -ql %s" % package).stdout.split("\n")): <NEW_LINE> <INDENT> if not self._compare_fhs(package_file): <NEW_LINE> <INDENT> self.fail("(%s): File [%s] violates the FHS." % (package, package_file)) | Provide a list of acceptable file paths based on
http://refspecs.linuxfoundation.org/FHS_3.0/fhs/index.html
:avocado: enable | 625990574e4d562566373985 |
class edi_company_importation(orm.Model): <NEW_LINE> <INDENT> _name = 'edi.company.importation' <NEW_LINE> _description = 'EDI Company importation' <NEW_LINE> _columns = { 'name': fields.char('Importation type', size=20, required=True), 'code': fields.char('Code', size=10), 'object': fields.char('Object', size=64, required=True), 'note': fields.char('Note'), } | This class elements are populated with extra modules:
account_trip_edi_c* | 62599057baa26c4b54d50822 |
class Profile(models.Model): <NEW_LINE> <INDENT> USER_CLIENT = 0 <NEW_LINE> USER_ADMIN = 1 <NEW_LINE> USER_MR = 0 <NEW_LINE> USER_MS = 1 <NEW_LINE> USER_MRS = 2 <NEW_LINE> USER_MISS = 3 <NEW_LINE> USER_DR = 4 <NEW_LINE> USER_TYPES = ( (USER_CLIENT, _('Client')), (USER_ADMIN, _('Admin')), ) <NEW_LINE> USER_TITLES = ( (USER_MR, _('Mr.')), (USER_MS, _('Ms.')), (USER_MRS, _('Mrs.')), (USER_MISS, _('Miss.')), (USER_DR, _('Dr.')) ) <NEW_LINE> user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) <NEW_LINE> GENDER_MALE = 1 <NEW_LINE> GENDER_FEMALE = 2 <NEW_LINE> title = models.IntegerField(choices=USER_TITLES, default=USER_MR) <NEW_LINE> first_name = models.CharField(max_length=100, null=True, blank=True) <NEW_LINE> last_name = models.CharField(max_length=100, null=True, blank=True) <NEW_LINE> phone = models.CharField(max_length=50, null=True, blank=True) <NEW_LINE> mobile_phone = models.CharField(max_length=50, null=True, blank=True) <NEW_LINE> address_1 = models.CharField(max_length=255, null=True, blank=True) <NEW_LINE> address_2 = models.CharField(max_length=255, null=True, blank=True) <NEW_LINE> address_3 = models.CharField(max_length=255, null=True, blank=True) <NEW_LINE> city = models.CharField(max_length=255, null=True, blank=True) <NEW_LINE> zipcode = models.CharField(max_length=10, null=True) <NEW_LINE> country = models.CharField(max_length=255, null=True, blank=True) <NEW_LINE> type = models.IntegerField(choices=USER_TYPES, default=USER_CLIENT) <NEW_LINE> created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) <NEW_LINE> updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) | User profile model - main user entry object | 62599057596a89723612906f |
class LiquidNode(Node): <NEW_LINE> <INDENT> __slots__ = ("tok", "block") <NEW_LINE> def __init__(self, tok: Token, block: BlockNode): <NEW_LINE> <INDENT> self.tok = tok <NEW_LINE> self.block = block <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return str(self.block) <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> return f"LiquidNode(tok={self.tok}, block={self.block!r})" <NEW_LINE> <DEDENT> def render_to_output(self, context: Context, buffer: TextIO) -> Optional[bool]: <NEW_LINE> <INDENT> return self.block.render(context, buffer) <NEW_LINE> <DEDENT> async def render_to_output_async( self, context: Context, buffer: TextIO ) -> Optional[bool]: <NEW_LINE> <INDENT> return await self.block.render_async(context, buffer) | Parse tree node for the built-in "liquid" tag. | 625990573c8af77a43b689ff |
class Convocacao(models.Model): <NEW_LINE> <INDENT> envioemail = models.NullBooleanField( u'Email', ) <NEW_LINE> presente = models.NullBooleanField( u'Presente', ) <NEW_LINE> anotacao = models.TextField( u'Anotação', blank=True, null=True ) <NEW_LINE> reuniao = models.ForeignKey( 'Reuniao', models.DO_NOTHING, blank=False, null=False ) <NEW_LINE> aluno = models.ForeignKey( 'sca.Aluno', models.DO_NOTHING, blank=False, null=False ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> managed = True <NEW_LINE> db_table = 'convocacao' <NEW_LINE> app_label = 'cadd' | Classe de uso do sistema para a guarda dos alunos convocados às reuniões | 6259905745492302aabfda56 |
class Personne(Fact): <NEW_LINE> <INDENT> pass | Info about the patient | 625990577b25080760ed879e |
class ElpyRPCServer(JSONRPCServer): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(ElpyRPCServer, self).__init__() <NEW_LINE> for cls in [RopeBackend, JediBackend, NativeBackend]: <NEW_LINE> <INDENT> backend = cls() <NEW_LINE> if backend is not None: <NEW_LINE> <INDENT> self.backend = backend <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def rpc_echo(self, *args): <NEW_LINE> <INDENT> return args <NEW_LINE> <DEDENT> def rpc_get_traceback(self): <NEW_LINE> <INDENT> return self.last_traceback <NEW_LINE> <DEDENT> def rpc_set_backend(self, backend_name): <NEW_LINE> <INDENT> backend_cls = BACKEND_MAP.get(backend_name) <NEW_LINE> if backend_cls is None: <NEW_LINE> <INDENT> raise ValueError("Unknown backend {}" .format(backend_name)) <NEW_LINE> <DEDENT> backend = backend_cls() <NEW_LINE> if backend is None: <NEW_LINE> <INDENT> raise ValueError("Backend {} could not find the " "required Python library" .format(backend_name)) <NEW_LINE> <DEDENT> self.backend = backend <NEW_LINE> <DEDENT> def rpc_get_backend(self): <NEW_LINE> <INDENT> return self.backend.name <NEW_LINE> <DEDENT> def rpc_get_available_backends(self): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for cls in BACKEND_MAP.values(): <NEW_LINE> <INDENT> backend = cls() <NEW_LINE> if backend is not None: <NEW_LINE> <INDENT> result.append(backend.name) <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def rpc_before_save(self, project_root, filename): <NEW_LINE> <INDENT> return self.backend.rpc_before_save( project_root, filename) <NEW_LINE> <DEDENT> def rpc_after_save(self, project_root, filename): <NEW_LINE> <INDENT> return self.backend.rpc_after_save( project_root, filename) <NEW_LINE> <DEDENT> def rpc_get_completions(self, project_root, filename, source, offset): <NEW_LINE> <INDENT> return self.backend.rpc_get_completions( project_root, filename, source, offset) <NEW_LINE> <DEDENT> def rpc_get_definition(self, project_root, filename, source, offset): <NEW_LINE> <INDENT> return self.backend.rpc_get_definition( project_root, filename, source, offset) <NEW_LINE> <DEDENT> def rpc_get_calltip(self, project_root, filename, source, offset): <NEW_LINE> <INDENT> return self.backend.rpc_get_calltip( project_root, filename, source, offset) <NEW_LINE> <DEDENT> def rpc_get_docstring(self, project_root, filename, source, offset): <NEW_LINE> <INDENT> return self.backend.rpc_get_docstring( project_root, filename, source, offset) | The RPC server for elpy.
See the rpc_* methods for exported method documentation. | 6259905723e79379d538da7a |
class TopicDistVectorizer(IdComposer): <NEW_LINE> <INDENT> def __init__(self, corpus, models=None): <NEW_LINE> <INDENT> self.corpus = resolveIds(corpus) <NEW_LINE> self.models = '_'.join(str(m) for m in models) if models else None <NEW_LINE> IdComposer.__init__(self) <NEW_LINE> self.__modelTopicOrder = {} <NEW_LINE> self.__models = models <NEW_LINE> self.__ctiCache = {} <NEW_LINE> <DEDENT> def __call__(self, textId, model=None): <NEW_LINE> <INDENT> if self.models: models = self.__models <NEW_LINE> else: models = [model] <NEW_LINE> vecs = [] <NEW_LINE> for modelId in models: <NEW_LINE> <INDENT> cti = self.__getCorpusTopicIndex(modelId) <NEW_LINE> topicVals = cti.textTopics(textId) <NEW_LINE> model = resolve(modelId) <NEW_LINE> vecs.append(self.__topics2vector(topicVals, model)) <NEW_LINE> <DEDENT> return np.concatenate(vecs) <NEW_LINE> <DEDENT> def __getCorpusTopicIndex(self, modelId): <NEW_LINE> <INDENT> if not modelId in self.__ctiCache: <NEW_LINE> <INDENT> ctiBuilder = resolve('corpus_topic_index_builder') <NEW_LINE> cti = ctiBuilder(corpus=self.corpus, model=modelId) <NEW_LINE> self.__ctiCache[modelId] = cti <NEW_LINE> <DEDENT> return self.__ctiCache[modelId] <NEW_LINE> <DEDENT> def __topics2vector(self, topicVals, model): <NEW_LINE> <INDENT> if model.id not in self.__modelTopicOrder: <NEW_LINE> <INDENT> ids = model.topicIds() <NEW_LINE> mto = { tid : i for i, tid in enumerate(ids) } <NEW_LINE> self.__modelTopicOrder[model.id] = mto <NEW_LINE> <DEDENT> mto = self.__modelTopicOrder[model.id] <NEW_LINE> v = np.empty(len(mto), dtype=np.float64) <NEW_LINE> for tid, tv in topicVals.iteritems(): <NEW_LINE> <INDENT> v[mto[tid]] = tv <NEW_LINE> <DEDENT> return v | Vectorizes texts by either concatenating topic distributions for the text
from several predefined topic models, or using a models passed at
vectorization time together with the text. | 6259905724f1403a9268638e |
class Record(TimeModel): <NEW_LINE> <INDENT> room = models.ForeignKey(Room, verbose_name=_('Room')) <NEW_LINE> period = models.ForeignKey(Period, verbose_name=_('Period')) <NEW_LINE> tenant = models.ForeignKey(Tenant, blank=True, null=True, verbose_name=_('Tenant')) <NEW_LINE> electricity = models.FloatField(default=0, verbose_name=_('Quantity of electricity')) <NEW_LINE> watermeter = models.FloatField(default=0, verbose_name=_('Quantity of water')) <NEW_LINE> electric_fee = models.FloatField(default=0, verbose_name=_('Electirc fee')) <NEW_LINE> water_fee = models.FloatField(default=0, verbose_name=_('Water fee')) <NEW_LINE> rent_fee = models.IntegerField(default=0, verbose_name=_('Rent fee')) <NEW_LINE> internet_fee = models.IntegerField(default=0, verbose_name=_('Internet fee')) <NEW_LINE> charge_fee = models.IntegerField(default=0, verbose_name=_('Charge fee')) <NEW_LINE> tv_fee = models.IntegerField(default=0, verbose_name=_('TV fee')) <NEW_LINE> special_fee = models.IntegerField(default=0, verbose_name=_('Specail fee')) <NEW_LINE> total_fee = models.FloatField(default=0, verbose_name=_('Total fee')) <NEW_LINE> is_get_money = models.BooleanField(default=True, verbose_name=_('Is get money')) <NEW_LINE> remark = models.CharField(blank=True, max_length=512, verbose_name=_('Record remark')) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return u'%s-¥%s' % (self.room, self.total_fee) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> unique_together = ("room", "period", "tenant") <NEW_LINE> verbose_name = _('Record') <NEW_LINE> verbose_name_plural = _('Records') | Money记录(账单记录) | 62599057b5575c28eb71378b |
class X_Cosmo(FlatLambdaCDM): <NEW_LINE> <INDENT> def __init__(self, H0=70, Om0=0.3): <NEW_LINE> <INDENT> FlatLambdaCDM.__init__(self,H0,Om0) <NEW_LINE> <DEDENT> def physical_distance(self,z): <NEW_LINE> <INDENT> from astropy import units as u <NEW_LINE> from astropy import constants as const <NEW_LINE> if not isiterable(z): <NEW_LINE> <INDENT> return self.lookback_time(z) * const.c.to(u.Mpc/u.Gyr) <NEW_LINE> <DEDENT> out = ( [(self.lookback_time(redshift)*const.c.to(u.Mpc/u.Gyr)) for redshift in z] ) <NEW_LINE> return u.Mpc * np.array( [tmp.value for tmp in out] ) | A class for extending the astropy Class
-- Deprecated.. | 62599057adb09d7d5dc0bae9 |
class VnetInfo(ProxyOnlyResource): <NEW_LINE> <INDENT> _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'cert_thumbprint': {'readonly': True}, 'routes': {'readonly': True}, 'resync_required': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'kind': {'key': 'kind', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'vnet_resource_id': {'key': 'properties.vnetResourceId', 'type': 'str'}, 'cert_thumbprint': {'key': 'properties.certThumbprint', 'type': 'str'}, 'cert_blob': {'key': 'properties.certBlob', 'type': 'bytearray'}, 'routes': {'key': 'properties.routes', 'type': '[VnetRoute]'}, 'resync_required': {'key': 'properties.resyncRequired', 'type': 'bool'}, 'dns_servers': {'key': 'properties.dnsServers', 'type': 'str'}, } <NEW_LINE> def __init__(self, kind=None, vnet_resource_id=None, cert_blob=None, dns_servers=None): <NEW_LINE> <INDENT> super(VnetInfo, self).__init__(kind=kind) <NEW_LINE> self.vnet_resource_id = vnet_resource_id <NEW_LINE> self.cert_thumbprint = None <NEW_LINE> self.cert_blob = cert_blob <NEW_LINE> self.routes = None <NEW_LINE> self.resync_required = None <NEW_LINE> self.dns_servers = dns_servers | Virtual Network information contract.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: Resource Id.
:vartype id: str
:ivar name: Resource Name.
:vartype name: str
:param kind: Kind of resource.
:type kind: str
:ivar type: Resource type.
:vartype type: str
:param vnet_resource_id: The Virtual Network's resource ID.
:type vnet_resource_id: str
:ivar cert_thumbprint: The client certificate thumbprint.
:vartype cert_thumbprint: str
:param cert_blob: A certificate file (.cer) blob containing the public key
of the private key used to authenticate a
Point-To-Site VPN connection.
:type cert_blob: bytearray
:ivar routes: The routes that this Virtual Network connection uses.
:vartype routes: list[~azure.mgmt.web.models.VnetRoute]
:ivar resync_required: <code>true</code> if a resync is required;
otherwise, <code>false</code>.
:vartype resync_required: bool
:param dns_servers: DNS servers to be used by this Virtual Network. This
should be a comma-separated list of IP addresses.
:type dns_servers: str | 625990571f037a2d8b9e532b |
class DNS_Ops(object): <NEW_LINE> <INDENT> def __init__ (self, host_name): <NEW_LINE> <INDENT> self.ip_addresses = set() <NEW_LINE> self.name_servers = [] <NEW_LINE> self.host_name = host_name <NEW_LINE> self.dns_records = {} <NEW_LINE> <DEDENT> def get_Name_Servers(self): <NEW_LINE> <INDENT> if self.host_name.startswith('www.'): <NEW_LINE> <INDENT> self.hname = self.host_name[4:] <NEW_LINE> <DEDENT> else: self.hname = self.host_name <NEW_LINE> try: <NEW_LINE> <INDENT> self.nservers = dns.resolver.query(self.hname, 'NS') <NEW_LINE> <DEDENT> except(dns.resolver.NXDOMAIN): <NEW_LINE> <INDENT> sys.exit("Cannot resolve the domain.") <NEW_LINE> <DEDENT> except(dns.resolver.NoAnswer): <NEW_LINE> <INDENT> sys.exit("Cannot get the NS records.") <NEW_LINE> <DEDENT> except(dns.exception.Timeout): <NEW_LINE> <INDENT> sys.exit() <NEW_LINE> <DEDENT> return self.nservers <NEW_LINE> <DEDENT> def host_Resolve(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.a_records = dns.resolver.query(self.host_name, 'A') <NEW_LINE> <DEDENT> except(dns.resolver.NXDOMAIN): <NEW_LINE> <INDENT> self.ip_addresses.add(self.host_name) <NEW_LINE> return self.unique(self.ip_addresses) <NEW_LINE> <DEDENT> except(dns.exception.Timeout): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> for ipaddr in self.a_records: <NEW_LINE> <INDENT> self.ip_addresses.add(ipaddr.to_text(ipaddr)) <NEW_LINE> <DEDENT> return self.ip_addresses <NEW_LINE> <DEDENT> def zone_Transfer(self): <NEW_LINE> <INDENT> self.records = set() <NEW_LINE> if self.host_name.startswith('www.'): <NEW_LINE> <INDENT> self.hname = self.host_name[4:] <NEW_LINE> <DEDENT> else: self.hname = self.host_name <NEW_LINE> for i in self.get_Name_Servers(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ztransfer = dns.zone.from_xfr(dns.query.xfr(str(i), self.hname)) <NEW_LINE> for res in ztransfer: <NEW_LINE> <INDENT> record = str(res) + '.' + self.hname <NEW_LINE> self.records.add(record.replace('@.', '')) <NEW_LINE> self.dns_records[str(i)] = self.records <NEW_LINE> <DEDENT> <DEDENT> except dns.exception.FormError as e: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> except EOFError as neterr: <NEW_LINE> <INDENT> print("-> Unexpected reply from {}.").format(i) <NEW_LINE> pass <NEW_LINE> <DEDENT> except socket.error as e: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> return self.dns_records | DNS Operations | 62599057fff4ab517ebceda3 |
class GetInputSet(InputSet): <NEW_LINE> <INDENT> def set_AccessToken(self, value): <NEW_LINE> <INDENT> super(GetInputSet, self)._set_input('AccessToken', value) <NEW_LINE> <DEDENT> def set_ClientID(self, value): <NEW_LINE> <INDENT> super(GetInputSet, self)._set_input('ClientID', value) <NEW_LINE> <DEDENT> def set_ClientSecret(self, value): <NEW_LINE> <INDENT> super(GetInputSet, self)._set_input('ClientSecret', value) <NEW_LINE> <DEDENT> def set_CommentID(self, value): <NEW_LINE> <INDENT> super(GetInputSet, self)._set_input('CommentID', value) <NEW_LINE> <DEDENT> def set_Fields(self, value): <NEW_LINE> <INDENT> super(GetInputSet, self)._set_input('Fields', value) <NEW_LINE> <DEDENT> def set_FileID(self, value): <NEW_LINE> <INDENT> super(GetInputSet, self)._set_input('FileID', value) <NEW_LINE> <DEDENT> def set_IncludeDeleted(self, value): <NEW_LINE> <INDENT> super(GetInputSet, self)._set_input('IncludeDeleted', value) <NEW_LINE> <DEDENT> def set_RefreshToken(self, value): <NEW_LINE> <INDENT> super(GetInputSet, self)._set_input('RefreshToken', value) <NEW_LINE> <DEDENT> def set_ReplyID(self, value): <NEW_LINE> <INDENT> super(GetInputSet, self)._set_input('ReplyID', value) | An InputSet with methods appropriate for specifying the inputs to the Get
Choreo. The InputSet object is used to specify input parameters when executing this Choreo. | 6259905732920d7e50bc75c6 |
class About(SerializableBase): <NEW_LINE> <INDENT> _props_req = [ 'version', ] <NEW_LINE> _props = [ 'extensions', ] <NEW_LINE> _props.extend(_props_req) <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self._version = None <NEW_LINE> self._extensions = None <NEW_LINE> super().__init__(*args, **kwargs) <NEW_LINE> <DEDENT> @property <NEW_LINE> def version(self): <NEW_LINE> <INDENT> return self._version <NEW_LINE> <DEDENT> @version.setter <NEW_LINE> def version(self, value): <NEW_LINE> <INDENT> def check_version(version): <NEW_LINE> <INDENT> if version in ['1.0.3','1.0.2', '1.0.1', '1.0.0', '0.95', '0.9']: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if isinstance(value, (list, tuple)): <NEW_LINE> <INDENT> value_str = repr(version) + ' in ' + repr(value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> value_str = repr(version) <NEW_LINE> <DEDENT> msg = ( "Tried to set property 'version' in a 'tincan.%s' object " "with an invalid value: %s\n" "Allowed versions are: %s" % ( self.__class__.__name__, value_str, ', '.join(map(repr, Version.supported)), ) ) <NEW_LINE> raise ValueError(msg) <NEW_LINE> <DEDENT> if value is None: <NEW_LINE> <INDENT> self._version = [Version.latest] <NEW_LINE> <DEDENT> elif isinstance(value, str): <NEW_LINE> <INDENT> check_version(value) <NEW_LINE> self._version = [value] <NEW_LINE> <DEDENT> elif isinstance(value, (list, tuple)): <NEW_LINE> <INDENT> for v in value: <NEW_LINE> <INDENT> check_version(v) <NEW_LINE> <DEDENT> self._version = list(value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError( "Property 'version' in a 'tincan.%s' object must be set with a " "list, tuple, str, unicode or None. Tried to set it with: %s" % ( self.__class__.__name__, repr(value), )) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def extensions(self): <NEW_LINE> <INDENT> return self._extensions <NEW_LINE> <DEDENT> @extensions.setter <NEW_LINE> def extensions(self, value): <NEW_LINE> <INDENT> if isinstance(value, Extensions): <NEW_LINE> <INDENT> self._extensions = value <NEW_LINE> <DEDENT> elif value is None: <NEW_LINE> <INDENT> self._extensions = Extensions() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._extensions = Extensions(value) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> msg = ( "Property 'extensions' in a 'tincan.%s' object must be set with a " "tincan.Extensions, dict, or None.\n\n" % self.__class__.__name__, ) <NEW_LINE> msg += e.message <NEW_LINE> raise TypeError(msg) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @extensions.deleter <NEW_LINE> def extensions(self): <NEW_LINE> <INDENT> del self._extensions | Stores info about this installation of `tincan`.
:param version: The versions supported. This attribute is required.
:type version: list of unicode
:param extensions: Custom user data. This attribute is optional.
:type extensions: :class:`tincan.Extensions` | 62599057e64d504609df9e8f |
class HelpItem(models.Model): <NEW_LINE> <INDENT> help = models.ForeignKey(Help) <NEW_LINE> title = models.CharField(_('Title'), max_length=200) <NEW_LINE> link = models.CharField(_('Link'), max_length=200, help_text=_('The Link should be relative, e.g. /admin/blog/.')) <NEW_LINE> body = models.TextField(_('Body')) <NEW_LINE> order = PositionField(unique_for_field='help') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> app_label = "grappelli" <NEW_LINE> verbose_name = _('Help Entry') <NEW_LINE> verbose_name_plural = _('Help Entries') <NEW_LINE> ordering = ['help', 'order'] <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return u"%s" % (self.title) <NEW_LINE> <DEDENT> save = transaction.commit_on_success(models.Model.save) | Help Entry Item. | 6259905710dbd63aa1c72139 |
class Qualia(object): <NEW_LINE> <INDENT> def __init__(self, glframe, formulas=None): <NEW_LINE> <INDENT> self.glframe = glframe <NEW_LINE> self.formulas = formulas <NEW_LINE> if formulas is None: <NEW_LINE> <INDENT> verb = self.glframe.glverbclass.ID.split('-')[0] <NEW_LINE> self.formulas = [Pred(verb, [Var('e')])] <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "%s" % ' & '.join([str(f) for f in self.formulas]) <NEW_LINE> <DEDENT> def add(self, formula): <NEW_LINE> <INDENT> self.formulas.append(formula) <NEW_LINE> <DEDENT> def add_multiple(self, formulas): <NEW_LINE> <INDENT> self.formulas.extend(formulas) <NEW_LINE> <DEDENT> def html(self): <NEW_LINE> <INDENT> return "%s" % '<br>\n'.join([f.html() for f in self.formulas]) | Represents the verbframe's qualia structure, which is a list of formulas
(actually, it is a list of predicates and oppositions, the latter technically
not being a formula). | 62599057435de62698e9d383 |
class Status: <NEW_LINE> <INDENT> def __init__(self, parent: Union["Status", None] = None, children: List["Status"] = []): <NEW_LINE> <INDENT> self.parent = None <NEW_LINE> self.children = [] <NEW_LINE> if parent is not None: <NEW_LINE> <INDENT> self.set_parent(parent) <NEW_LINE> <DEDENT> if children: <NEW_LINE> <INDENT> self.add_children(children) <NEW_LINE> <DEDENT> <DEDENT> def add_child(self, child: "Status"): <NEW_LINE> <INDENT> self.children.append(child) <NEW_LINE> child.parent = self <NEW_LINE> <DEDENT> def set_parent(self, parent: "Status"): <NEW_LINE> <INDENT> parent.add_child(self) <NEW_LINE> <DEDENT> def add_children(self, children: List["Status"]): <NEW_LINE> <INDENT> for child in children: <NEW_LINE> <INDENT> self.add_child(child) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def is_leaf(self) -> bool: <NEW_LINE> <INDENT> return not self.children <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_root(self) -> bool: <NEW_LINE> <INDENT> return self.parent is None | 多层次状态管理类 | 6259905738b623060ffaa30e |
class CellOutOfRange(Exception): <NEW_LINE> <INDENT> pass | Dummy Exception | 6259905763d6d428bbee3d47 |
class Event: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> ret = str(self.__class__) <NEW_LINE> return ret[ret.find(".") + 1:] <NEW_LINE> <DEDENT> def enqueue(self): <NEW_LINE> <INDENT> exported.myengine._enqueue(self) <NEW_LINE> <DEDENT> def execute(self): <NEW_LINE> <INDENT> pass | This is the basic Event class. It has an enqueue method
which enqueues the event in the event queue (in the engine
module). It also has an execute method which is executed
when the event is dequeued and handled. Override the
'execute' function for your functionality to get executed. | 62599057d99f1b3c44d06c20 |
class NPBoolean(types.TypeDecorator, types.SchemaType): <NEW_LINE> <INDENT> impl = types.Boolean <NEW_LINE> def __init__(self, **kw): <NEW_LINE> <INDENT> types.TypeDecorator.__init__(self, **kw) <NEW_LINE> types.SchemaType.__init__(self, **kw) <NEW_LINE> <DEDENT> def load_dialect_impl(self, dialect): <NEW_LINE> <INDENT> if _is_mysql(dialect): <NEW_LINE> <INDENT> return mysql.ENUM('Y', 'N', charset='ascii', collation='ascii_bin') <NEW_LINE> <DEDENT> return types.Boolean(name='ck_boolean') <NEW_LINE> <DEDENT> def compare_against_backend(self, dialect, conn_type): <NEW_LINE> <INDENT> if _is_mysql(dialect): <NEW_LINE> <INDENT> if not isinstance(conn_type, mysql.ENUM): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if tuple(conn_type.enums) == ('Y', 'N'): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> return isinstance(conn_type, types.Boolean) <NEW_LINE> <DEDENT> def _should_create_constraint(self, compiler): <NEW_LINE> <INDENT> return (not compiler.dialect.supports_native_boolean and not _is_mysql(compiler.dialect)) <NEW_LINE> <DEDENT> def _set_table(self, column, table): <NEW_LINE> <INDENT> e = schema.CheckConstraint( column.in_([0, 1]), name=self.name, _create_rule=util.portable_instancemethod( self._should_create_constraint)) <NEW_LINE> table.append_constraint(e) <NEW_LINE> <DEDENT> @property <NEW_LINE> def python_type(self): <NEW_LINE> <INDENT> return bool <NEW_LINE> <DEDENT> def bind_processor(self, dialect): <NEW_LINE> <INDENT> if _is_mysql(dialect): <NEW_LINE> <INDENT> return processors.boolean_to_enum <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def result_processor(self, dialect, coltype): <NEW_LINE> <INDENT> if _is_mysql(dialect): <NEW_LINE> <INDENT> return processors.enum_to_boolean <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> class comparator_factory(types.Boolean.Comparator): <NEW_LINE> <INDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if isinstance(other, bool): <NEW_LINE> <INDENT> other = type_coerce(other, NPBoolean) <NEW_LINE> <DEDENT> return types.Boolean.Comparator.__eq__(self, other) <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if isinstance(other, bool): <NEW_LINE> <INDENT> other = type_coerce(other, NPBoolean) <NEW_LINE> <DEDENT> return types.Boolean.Comparator.__ne__(self, other) <NEW_LINE> <DEDENT> def is_(self, other): <NEW_LINE> <INDENT> if other is None: <NEW_LINE> <INDENT> return types.Boolean.Comparator.is_(self, other) <NEW_LINE> <DEDENT> if isinstance(other, bool): <NEW_LINE> <INDENT> other = type_coerce(other, NPBoolean) <NEW_LINE> <DEDENT> return types.Boolean.Comparator.__eq__(self, other) <NEW_LINE> <DEDENT> def isnot(self, other): <NEW_LINE> <INDENT> if other is None: <NEW_LINE> <INDENT> return types.Boolean.Comparator.isnot(self, other) <NEW_LINE> <DEDENT> if isinstance(other, bool): <NEW_LINE> <INDENT> other = type_coerce(other, NPBoolean) <NEW_LINE> <DEDENT> return types.Boolean.Comparator.__ne__(self, other) <NEW_LINE> <DEDENT> <DEDENT> def process_literal_param(self, value, dialect): <NEW_LINE> <INDENT> if isinstance(value, bool): <NEW_LINE> <INDENT> if _is_mysql(dialect): <NEW_LINE> <INDENT> if value: <NEW_LINE> <INDENT> return 'Y' <NEW_LINE> <DEDENT> return 'N' <NEW_LINE> <DEDENT> <DEDENT> return value | An almost-normal boolean type with a special case for MySQL. | 625990573617ad0b5ee076c9 |
class Mockimportlib(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def BgpRouteStub(self, *args): <NEW_LINE> <INDENT> args = args <NEW_LINE> return self <NEW_LINE> <DEDENT> def bgprouteadd(self, *args, **kwargs): <NEW_LINE> <INDENT> args = args <NEW_LINE> kwargs = kwargs <NEW_LINE> return True <NEW_LINE> <DEDENT> def bgprouteinitialize(self, *args, **kwargs): <NEW_LINE> <INDENT> args = args <NEW_LINE> kwargs = kwargs <NEW_LINE> return True <NEW_LINE> <DEDENT> def test_api(self, *args, **kwargs): <NEW_LINE> <INDENT> args = args <NEW_LINE> kwargs = kwargs <NEW_LINE> return True | DOC | 625990578e7ae83300eea60d |
class MroCtxPds3LabelNaifSpiceDriver(LineScanner, Pds3Label, NaifSpice, RadialDistortion, Driver): <NEW_LINE> <INDENT> @property <NEW_LINE> def instrument_id(self): <NEW_LINE> <INDENT> id_lookup = { 'CONTEXT CAMERA':'MRO_CTX', 'CTX':'MRO_CTX' } <NEW_LINE> return id_lookup[super().instrument_id] <NEW_LINE> <DEDENT> @property <NEW_LINE> def spacecraft_name(self): <NEW_LINE> <INDENT> name_lookup = { 'MARS_RECONNAISSANCE_ORBITER': 'MRO' } <NEW_LINE> return name_lookup[super().spacecraft_name] <NEW_LINE> <DEDENT> @property <NEW_LINE> def detector_start_sample(self): <NEW_LINE> <INDENT> return self.label.get('SAMPLE_FIRST_PIXEL', 0) <NEW_LINE> <DEDENT> @property <NEW_LINE> def detector_center_sample(self): <NEW_LINE> <INDENT> return super().detector_center_sample - 0.5 <NEW_LINE> <DEDENT> @property <NEW_LINE> def sensor_model_version(self): <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> @property <NEW_LINE> def platform_name(self): <NEW_LINE> <INDENT> return self.label['SPACECRAFT_NAME'] | Driver for reading CTX PDS3 labels. Requires a Spice mixin to acquire addtional
ephemeris and instrument data located exclusively in spice kernels. | 62599057a8ecb03325872797 |
class HighWaterMarkChangeDetectionPolicy(DataChangeDetectionPolicy): <NEW_LINE> <INDENT> _validation = { 'odata_type': {'required': True}, 'high_water_mark_column_name': {'required': True}, } <NEW_LINE> _attribute_map = { 'odata_type': {'key': '@odata\\.type', 'type': 'str'}, 'high_water_mark_column_name': {'key': 'highWaterMarkColumnName', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, high_water_mark_column_name: str, **kwargs ): <NEW_LINE> <INDENT> super(HighWaterMarkChangeDetectionPolicy, self).__init__(**kwargs) <NEW_LINE> self.odata_type = '#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy' <NEW_LINE> self.high_water_mark_column_name = high_water_mark_column_name | Defines a data change detection policy that captures changes based on the value of a high water mark column.
All required parameters must be populated in order to send to Azure.
:ivar odata_type: Required. Identifies the concrete type of the data change detection
policy.Constant filled by server.
:vartype odata_type: str
:ivar high_water_mark_column_name: Required. The name of the high water mark column.
:vartype high_water_mark_column_name: str | 625990574428ac0f6e659abb |
class DashboardView(BrowserView): <NEW_LINE> <INDENT> @memoize <NEW_LINE> def can_edit(self): <NEW_LINE> <INDENT> return bool(getSecurityManager().checkPermission('Portlets: Manage own portlets', self.context)) <NEW_LINE> <DEDENT> @memoize <NEW_LINE> def empty(self): <NEW_LINE> <INDENT> dashboards = [getUtility(IPortletManager, name=name) for name in ['plone.dashboard1', 'plone.dashboard2', 'plone.dashboard3', 'plone.dashboard4']] <NEW_LINE> portal_membership = getToolByName(self.context, 'portal_membership') <NEW_LINE> member = portal_membership.getAuthenticatedMember() <NEW_LINE> userid = member.getId() <NEW_LINE> num_portlets = 0 <NEW_LINE> for dashboard in dashboards: <NEW_LINE> <INDENT> num_portlets += len(dashboard.get(USER_CATEGORY, {}).get(userid, {})) <NEW_LINE> for groupid in member.getGroups(): <NEW_LINE> <INDENT> num_portlets += len(dashboard.get(GROUP_CATEGORY, {}).get(groupid, {})) <NEW_LINE> <DEDENT> <DEDENT> return num_portlets == 0 | Power the dashboard
| 6259905745492302aabfda57 |
class OUNoise: <NEW_LINE> <INDENT> def __init__(self, size, config): <NEW_LINE> <INDENT> self.config = config <NEW_LINE> self.mu = self.config.mu * np.ones(size) <NEW_LINE> self.theta = self.config.theta <NEW_LINE> self.sigma = self.config.sigma <NEW_LINE> self.seed = random.seed(self.config.random_seed) <NEW_LINE> self.noise_func = self.config.noise_func <NEW_LINE> self.reset() <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.state = copy.copy(self.mu) <NEW_LINE> <DEDENT> def sample(self): <NEW_LINE> <INDENT> x = self.state <NEW_LINE> dx = self.theta * (self.mu - x) + self.sigma * self.noise_func(len(x)) <NEW_LINE> self.state = x + dx <NEW_LINE> return self.state | Ornstein-Uhlenbeck process. | 625990574e4d562566373987 |
@prettify_class <NEW_LINE> class WorkerInfo(object): <NEW_LINE> <INDENT> __slots__ = ("name", "input", "output", "process", "local", "pending_results") <NEW_LINE> def __init__(self, name, input, output, process=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.input = input <NEW_LINE> self.output = output <NEW_LINE> self.process = process <NEW_LINE> self.local = bool(process is not None) <NEW_LINE> self.pending_results = 0 <NEW_LINE> <DEDENT> def __info__(self): <NEW_LINE> <INDENT> proc = "" <NEW_LINE> if self.local: <NEW_LINE> <INDENT> proc = "pid={}, ".format(self.process.pid) <NEW_LINE> <DEDENT> return "{} ({}pending_results={})".format(self.name, proc, self.pending_results) | Object bundling together all the information concerning a single worker that is relevant
for a dispatcher. | 6259905721bff66bcd7241e5 |
class Student: <NEW_LINE> <INDENT> def __init__(self, cwid, name, major, course_grade): <NEW_LINE> <INDENT> self.cwid = cwid <NEW_LINE> self.name = name <NEW_LINE> self.major = major <NEW_LINE> self.course_grade = course_grade | store informaton of students | 62599057009cb60464d02ab5 |
class FileFullEaInformation(Structure): <NEW_LINE> <INDENT> INFO_TYPE = InfoType.SMB2_0_INFO_FILE <NEW_LINE> INFO_CLASS = FileInformationClass.FILE_FULL_EA_INFORMATION <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.fields = OrderedDict([ ('next_entry_offset', IntField(size=4)), ('flags', IntField(size=1)), ('ea_name_length', IntField( size=1, default=lambda s: len(s['ea_name']), )), ('ea_value_length', IntField( size=2, default=lambda s: len(s['ea_value']), )), ('ea_name', BytesField( size=lambda s: s['ea_name_length'].get_value(), )), ('ea_name_padding', IntField(size=1)), ('ea_value', BytesField( size=lambda s: s['ea_value_length'].get_value(), )), ]) <NEW_LINE> super(FileFullEaInformation, self).__init__() | [MS-FSCC] 2.4.15 FileFullEaInformation
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-fscc/0eb94f48-6aac-41df-a878-79f4dcfd8989 | 62599057dd821e528d6da440 |
class SessionNotCreatedException(WebDriverException): <NEW_LINE> <INDENT> pass | A new session could not be created. | 62599057ac7a0e7691f73a61 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.