code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class Isb(Instruction): <NEW_LINE> <INDENT> sets_negative_bit = True <NEW_LINE> sets_zero_bit = True <NEW_LINE> @classmethod <NEW_LINE> def write(cls, cpu, memory_address, value): <NEW_LINE> <INDENT> updated_value = Inc.write(cpu, memory_address, value) <NEW_LINE> return Sbc.write(cpu, memory_address, updated_value) | inc then sbc
N Z C I D V
+ + - - - - | 62598fb75166f23b2e2434ed |
class SwitchMenuScreen(PygameScreen): <NEW_LINE> <INDENT> def __init__(self, menu): <NEW_LINE> <INDENT> PygameScreen.__init__(self) <NEW_LINE> self.menu = menu <NEW_LINE> self.menuView = SwitchMenuWidget(menu, self.width, self.height) <NEW_LINE> self.statViews = [] <NEW_LINE> width = self.width*.9/self.menu.columns <NEW_LINE> height = self.height*.9/self.menu.columns <NEW_LINE> for entry in menu.entries: <NEW_LINE> <INDENT> statView = PokemonStatsView(width, height, pokemonMenuEntry=entry) <NEW_LINE> self.statViews.append(statView) <NEW_LINE> <DEDENT> self.menuView.entries = self.statViews <NEW_LINE> <DEDENT> def drawSurface(self): <NEW_LINE> <INDENT> bottomSurface = self.menuView.draw() <NEW_LINE> self.drawOnSurface(bottomSurface, left=0, top=0) | View for the Switch Menu Screen | 62598fb7aad79263cf42e8e5 |
class TestGameCreateForm: <NEW_LINE> <INDENT> @pytest.mark.parametrize('winner', ['white', 'black']) <NEW_LINE> @pytest.mark.parametrize('handicap', [0, 8]) <NEW_LINE> @pytest.mark.parametrize('komi', [0, 7]) <NEW_LINE> @pytest.mark.parametrize('season', [1]) <NEW_LINE> @pytest.mark.parametrize('episode', [1]) <NEW_LINE> def test_validate_success(self, players, winner, handicap, komi, season, episode, season_choices, episode_choices): <NEW_LINE> <INDENT> form = GameCreateForm(white_id=players[0].id, black_id=players[1].id, winner=winner, handicap=handicap, komi=komi, season=season, episode=episode) <NEW_LINE> player_choices = [(player.id, player.full_name) for player in players] <NEW_LINE> form.white_id.choices = player_choices <NEW_LINE> form.black_id.choices = player_choices <NEW_LINE> form.season.choices = season_choices <NEW_LINE> form.episode.choices = episode_choices <NEW_LINE> assert form.validate() is True, ('Validation failed: {}' ''.format(form.errors)) | Game create form. | 62598fb791f36d47f2230f31 |
class MessageRegion (Region): <NEW_LINE> <INDENT> messages = None <NEW_LINE> @decorators.extends(Region.__init__) <NEW_LINE> def __init__ (self, *args, **kwargs): <NEW_LINE> <INDENT> super(MessageRegion, self).__init__(*args, **kwargs) <NEW_LINE> self.messages = [] <NEW_LINE> <DEDENT> def append (self, message): <NEW_LINE> <INDENT> self.messages.append(message) <NEW_LINE> <DEDENT> def as_shape (self, padding=" "): <NEW_LINE> <INDENT> new_shape = shape.Shape(self.width(), self.height()) <NEW_LINE> lines = [] <NEW_LINE> for line in self.messages[-self.height():]: <NEW_LINE> <INDENT> lines.extend(textwrap.wrap(line, self.width())) <NEW_LINE> <DEDENT> for y, line in enumerate(lines[-self.height():]): <NEW_LINE> <INDENT> if len(line) < self.width(): <NEW_LINE> <INDENT> line += padding * (self.width() - len(line)) <NEW_LINE> <DEDENT> for x, char in enumerate(line): <NEW_LINE> <INDENT> new_shape[x][y] = char <NEW_LINE> <DEDENT> <DEDENT> return new_shape <NEW_LINE> <DEDENT> def blit (self, bshape=None): <NEW_LINE> <INDENT> if bshape is None: <NEW_LINE> <INDENT> super(MessageRegion, self).blit(self.as_shape()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> super(MessageRegion, self).blit(bshape) | A message region is a buffer of strings contained within a list. The latest
strings are displayed at the bottom of the region, with older strings above
that, until it runs out of space; thus, you will always have the most
recent message on the screen. | 62598fb71b99ca400228f5b9 |
class DomainSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> owner = serializers.Field(source='owner.username') <NEW_LINE> app = serializers.SlugRelatedField(slug_field='id') <NEW_LINE> created = serializers.DateTimeField(format=settings.DEIS_DATETIME_FORMAT, read_only=True) <NEW_LINE> updated = serializers.DateTimeField(format=settings.DEIS_DATETIME_FORMAT, read_only=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = models.Domain <NEW_LINE> fields = ('domain', 'owner', 'created', 'updated', 'app') <NEW_LINE> <DEDENT> def validate_domain(self, attrs, source): <NEW_LINE> <INDENT> value = attrs[source] <NEW_LINE> match = re.match( r'^(\*\.)?(' + settings.APP_URL_REGEX + r'\.)*([a-z0-9-]+)\.([a-z0-9]{2,})$', value) <NEW_LINE> if not match: <NEW_LINE> <INDENT> raise serializers.ValidationError( "Hostname does not look like a valid hostname. " "Only lowercase characters are allowed.") <NEW_LINE> <DEDENT> if models.Domain.objects.filter(domain=value).exists(): <NEW_LINE> <INDENT> raise serializers.ValidationError( "The domain {} is already in use by another app".format(value)) <NEW_LINE> <DEDENT> domain_parts = value.split('.') <NEW_LINE> if domain_parts[0] == '*': <NEW_LINE> <INDENT> raise serializers.ValidationError( "Adding a wildcard subdomain is currently not supported".format(value)) <NEW_LINE> <DEDENT> return attrs | Serialize a :class:`~api.models.Domain` model. | 62598fb7851cf427c66b83c8 |
class ImageResizeLayer(Layer): <NEW_LINE> <INDENT> def __init__( self, incoming=None, scale=2, resize_method=tf.image.ResizeMethod.BILINEAR, name=None, make_logs=False, ): <NEW_LINE> <INDENT> self.incoming = incoming <NEW_LINE> self.scale = scale <NEW_LINE> self.resize_method = resize_method <NEW_LINE> self.name = name <NEW_LINE> self.make_logs = make_logs <NEW_LINE> <DEDENT> def fit(self, Xs_inc, ys, **kwargs): <NEW_LINE> <INDENT> _, height, width, _ = get_shape(Xs_inc) <NEW_LINE> scale_height, scale_width = as_tuple(self.scale, 2) <NEW_LINE> self.new_height_ = int(scale_height * height) <NEW_LINE> self.new_width_ = int(scale_width * width) <NEW_LINE> return self <NEW_LINE> <DEDENT> def transform(self, Xs_inc, **kwargs): <NEW_LINE> <INDENT> return tf.image.resize_images( images=Xs_inc, new_height=self.new_height_, new_width=self.new_width_, method=self.resize_method, ) | TODO | 62598fb7627d3e7fe0e06fc2 |
class MailListManager: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.path_to_lists = "" <NEW_LINE> self.maillists = [] <NEW_LINE> self.load() <NEW_LINE> <DEDENT> def create(self, list_name): <NEW_LINE> <INDENT> list_handler = MailListAdapter(list_name) <NEW_LINE> self.maillists.append((list_name, list_handler)) <NEW_LINE> <DEDENT> def search_email(self, list_id): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def show_lists(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def merge_lists(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def load(self): <NEW_LINE> <INDENT> pass | docstring for Interface def __init__(self, arg) | 62598fb75fc7496912d48304 |
class Slice(JSONPath): <NEW_LINE> <INDENT> def __init__(self, start=None, end=None, step=None): <NEW_LINE> <INDENT> self.start = start <NEW_LINE> self.end = end <NEW_LINE> self.step = step <NEW_LINE> <DEDENT> def find(self, datum): <NEW_LINE> <INDENT> datum = DatumInContext.wrap(datum) <NEW_LINE> if (isinstance(datum.value, dict) or isinstance(datum.value, six.integer_types) or isinstance(datum.value, six.string_types)): <NEW_LINE> <INDENT> return self.find(DatumInContext([datum.value], path=datum.path, context=datum.context)) <NEW_LINE> <DEDENT> if self.start == None and self.end == None and self.step == None: <NEW_LINE> <INDENT> return [DatumInContext(datum.value[i], path=Index(i), context=datum) for i in xrange(0, len(datum.value))] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [DatumInContext(datum.value[i], path=Index(i), context=datum) for i in range(0, len(datum.value))[self.start:self.end:self.step]] <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self.start == None and self.end == None and self.step == None: <NEW_LINE> <INDENT> return '[*]' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '[%s%s%s]' % (self.start or '', ':%d'%self.end if self.end else '', ':%d'%self.step if self.step else '') <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '%s(start=%r,end=%r,step=%r)' % (self.__class__.__name__, self.start, self.end, self.step) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, Slice) and other.start == self.start and self.end == other.end and other.step == self.step | JSONPath matching a slice of an array.
Because of a mismatch between JSON and XML when schema-unaware,
this always returns an iterable; if the incoming data
was not a list, then it returns a one element list _containing_ that
data.
Consider these two docs, and their schema-unaware translation to JSON:
<a><b>hello</b></a> ==> {"a": {"b": "hello"}}
<a><b>hello</b><b>goodbye</b></a> ==> {"a": {"b": ["hello", "goodbye"]}}
If there were a schema, it would be known that "b" should always be an
array (unless the schema were wonky, but that is too much to fix here)
so when querying with JSON if the one writing the JSON knows that it
should be an array, they can write a slice operator and it will coerce
a non-array value to an array.
This may be a bit unfortunate because it would be nice to always have
an iterator, but dictionaries and other objects may also be iterable,
so this is the compromise. | 62598fb763d6d428bbee28c1 |
class Runtime(context.Runtime): <NEW_LINE> <INDENT> @property <NEW_LINE> def Node(self): <NEW_LINE> <INDENT> from .graph import Node <NEW_LINE> return Node <NEW_LINE> <DEDENT> @property <NEW_LINE> def InfoTable(self): <NEW_LINE> <INDENT> from .graph import InfoTable <NEW_LINE> return InfoTable <NEW_LINE> <DEDENT> @property <NEW_LINE> def evaluate(self): <NEW_LINE> <INDENT> from .evaluator import Evaluator <NEW_LINE> return lambda *args, **kwds: Evaluator(*args, **kwds).evaluate() <NEW_LINE> <DEDENT> def get_interpreter_state(self, interp): <NEW_LINE> <INDENT> return interp._its <NEW_LINE> <DEDENT> def init_interpreter_state(self, interp): <NEW_LINE> <INDENT> from .state import InterpreterState <NEW_LINE> interp._its = InterpreterState(interp) <NEW_LINE> <DEDENT> @property <NEW_LINE> def lookup_builtin_module(self): <NEW_LINE> <INDENT> from .currylib import index <NEW_LINE> return index.lookup <NEW_LINE> <DEDENT> def single_step(self, interp, expr): <NEW_LINE> <INDENT> from .evaluator import Evaluator <NEW_LINE> expr = getattr(expr, 'raw_expr', expr) <NEW_LINE> evaluator = Evaluator(interp, expr) <NEW_LINE> expr.info.step(evaluator.rts, expr) <NEW_LINE> return expr | Implementation of the runtime system interface for the Python backend. Used
by the Interpreter object. | 62598fb7d58c6744b42dc363 |
@optplan.register_node_type() <NEW_LINE> class FabricationConstraint(optplan.Function): <NEW_LINE> <INDENT> type = schema_utils.polymorphic_model_type( "function.fabrication_constraint") <NEW_LINE> minimum_curvature_diameter = types.FloatType() <NEW_LINE> minimum_gap = types.FloatType() <NEW_LINE> simulation_space = optplan.ReferenceType(optplan.SimulationSpaceBase) <NEW_LINE> method = types.StringType(choices=("gap", "curv", "gap_and_curve")) <NEW_LINE> apply_factors = types.BooleanType() | Defines fabrication constraint penalty function.
Attributes:
type: Must be "function.fabrication_constraint"
minimum_curvature_diameter: Smallest allowed curvature.
minimum_gap: Smallest allowed gap.
simulation_space: Simulation space where the fabrication constraint is evaluated.
oversample: Oversample the fine grid by this value to evaluate the penalty.
method:
gap: only applies the gap constraint,
curv: only apply the curvature constraint,
gapAndCurve: apply the gap and curvature constraint.
apply_weights: To meet the constraint you typically need to go for a slightly more
stringent gap and curvature values. If true then weigth factor are applied that
take care of this.(default: True) | 62598fb726068e7796d4ca6a |
class InvoiceCreateView(LoginRequiredMixin, libs_mixins.CompanyRequiredMixin, CreateView): <NEW_LINE> <INDENT> model = invoices_models.Invoice <NEW_LINE> template_name = 'invoice/invoice_create.html' <NEW_LINE> form_class = invoices_forms.InvoiceCreateForm <NEW_LINE> success_url = reverse_lazy('invoices:invoice_list') <NEW_LINE> def get_initial(self, *args, **kwargs): <NEW_LINE> <INDENT> initial_data = super(InvoiceCreateView, self).get_initial(*args, **kwargs) <NEW_LINE> customer_id = self.kwargs.get('customer_id') <NEW_LINE> if customer_id: <NEW_LINE> <INDENT> initial_data.update({'customer': int(customer_id)}) <NEW_LINE> <DEDENT> initial_data.update({ 'company': self.user_company, 'date': datetime.date.today().strftime('%Y-%m-%d') }) <NEW_LINE> return initial_data <NEW_LINE> <DEDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> data = super(InvoiceCreateView, self).get_context_data(**kwargs) <NEW_LINE> data['invoice_items_formset'] = invoices_forms.InvoiceItemFormSet(self.request.POST) if self.request.POST else invoices_forms.InvoiceItemFormSet() <NEW_LINE> return data <NEW_LINE> <DEDENT> def form_valid(self, form): <NEW_LINE> <INDENT> context = self.get_context_data() <NEW_LINE> invoice_items_formset = context['invoice_items_formset'] <NEW_LINE> if invoice_items_formset.is_valid(): <NEW_LINE> <INDENT> self.object = form.save() <NEW_LINE> invoice_items_formset.instance = self.object <NEW_LINE> invoice_items_formset.save() <NEW_LINE> messages.success(self.request, 'Invoice with sequence-no. [%s] created successfully.' % self.object.seq_number) <NEW_LINE> return HttpResponseRedirect(self.get_success_url()) <NEW_LINE> <DEDENT> return self.render_to_response(context) | View to create an invoice | 62598fb74527f215b58e9fe9 |
class EventRegistrationAnswer(models.Model): <NEW_LINE> <INDENT> _name = 'event.registration.answer' <NEW_LINE> _description = 'Event Registration Answer' <NEW_LINE> question_id = fields.Many2one( 'event.question', ondelete='restrict', required=True, domain="[('event_id', '=', event_id)]") <NEW_LINE> registration_id = fields.Many2one('event.registration', required=True, ondelete='cascade') <NEW_LINE> partner_id = fields.Many2one('res.partner', related='registration_id.partner_id') <NEW_LINE> event_id = fields.Many2one('event.event', related='registration_id.event_id') <NEW_LINE> question_type = fields.Selection(related='question_id.question_type') <NEW_LINE> value_answer_id = fields.Many2one('event.question.answer', string="Suggested answer") <NEW_LINE> value_text_box = fields.Text('Text answer') <NEW_LINE> _sql_constraints = [ ('value_check', "CHECK(value_answer_id IS NOT NULL OR COALESCE(value_text_box, '') <> '')", "There must be a suggested value or a text value.") ] | Represents the user input answer for a single event.question | 62598fb7009cb60464d01635 |
class UnreachableRule(object): <NEW_LINE> <INDENT> def __init__(self, rule): <NEW_LINE> <INDENT> self.rule = rule | A rule entry that can't be reached. | 62598fb771ff763f4b5e788a |
class KNearestNeighbor(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def train(self, X, y): <NEW_LINE> <INDENT> self.X_train = X <NEW_LINE> self.y_train = y <NEW_LINE> <DEDENT> def predict(self, X, k=1, num_loops=0): <NEW_LINE> <INDENT> if num_loops == 0: <NEW_LINE> <INDENT> dists = self.compute_distances_no_loops(X) <NEW_LINE> <DEDENT> elif num_loops == 1: <NEW_LINE> <INDENT> dists = self.compute_distances_one_loop(X) <NEW_LINE> <DEDENT> elif num_loops == 2: <NEW_LINE> <INDENT> dists = self.compute_distances_two_loops(X) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Invalid value %d for num_loops' % num_loops) <NEW_LINE> <DEDENT> return self.predict_labels(dists, k=k) <NEW_LINE> <DEDENT> def compute_distances_two_loops(self, X): <NEW_LINE> <INDENT> num_test = X.shape[0] <NEW_LINE> num_train = self.X_train.shape[0] <NEW_LINE> dists = np.zeros((num_test, num_train)) <NEW_LINE> for i in range(num_test): <NEW_LINE> <INDENT> for j in range(num_train): <NEW_LINE> <INDENT> dists[i, j] = np.sum((X[i] - self.X_train[j])**2) <NEW_LINE> <DEDENT> <DEDENT> return dists <NEW_LINE> <DEDENT> def compute_distances_one_loop(self, X): <NEW_LINE> <INDENT> num_test = X.shape[0] <NEW_LINE> num_train = self.X_train.shape[0] <NEW_LINE> dists = np.zeros((num_test, num_train)) <NEW_LINE> for i in range(num_test): <NEW_LINE> <INDENT> dists[i, :] = np.sum((self.X_train - X[i])**2, axis=1) <NEW_LINE> <DEDENT> return dists <NEW_LINE> <DEDENT> def compute_distances_no_loops(self, X): <NEW_LINE> <INDENT> num_test = X.shape[0] <NEW_LINE> num_train = self.X_train.shape[0] <NEW_LINE> dists = np.zeros((num_test, num_train)) <NEW_LINE> dists = np.sum((self.X_train[np.newaxis, :, :] - X[:, np.newaxis, :])**2, axis=2) <NEW_LINE> pass <NEW_LINE> return dists <NEW_LINE> <DEDENT> def predict_labels(self, dists, k=1): <NEW_LINE> <INDENT> num_test = dists.shape[0] <NEW_LINE> y_pred = np.zeros(num_test) <NEW_LINE> for i in range(num_test): <NEW_LINE> <INDENT> closest_y = [] <NEW_LINE> idx_sorted = np.argsort(dists[i]) <NEW_LINE> closest_y = self.y_train[idx_sorted[0:k]] <NEW_LINE> y_pred[i] = np.sort(stats.mode(closest_y).mode)[0] <NEW_LINE> <DEDENT> return y_pred | a kNN classifier with L2 distance | 62598fb77047854f4633f4e9 |
class ToolGrid(_ToolGridBase): <NEW_LINE> <INDENT> description = 'Toggle major grids' <NEW_LINE> default_keymap = rcParams['keymap.grid'] <NEW_LINE> def _get_next_grid_states(self, ax): <NEW_LINE> <INDENT> if None in map(self._get_uniform_grid_state, [ax.xaxis.minorTicks, ax.yaxis.minorTicks]): <NEW_LINE> <INDENT> raise ValueError <NEW_LINE> <DEDENT> x_state, y_state = map(self._get_uniform_grid_state, [ax.xaxis.majorTicks, ax.yaxis.majorTicks]) <NEW_LINE> cycle = self._cycle <NEW_LINE> x_state, y_state = ( cycle[(cycle.index((x_state, y_state)) + 1) % len(cycle)]) <NEW_LINE> return (x_state, "major" if x_state else "both", y_state, "major" if y_state else "both") | Tool to toggle the major grids of the figure | 62598fb74a966d76dd5eefeb |
class EmptyArray(MatrixUtilsError): <NEW_LINE> <INDENT> pass | Empty array can't be used | 62598fb7aad79263cf42e8e7 |
class Crc32: <NEW_LINE> <INDENT> def __init__(self, data=b''): <NEW_LINE> <INDENT> self.name = "crc32" <NEW_LINE> self.data = data <NEW_LINE> <DEDENT> def update(self, data=b''): <NEW_LINE> <INDENT> self.data += data <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> return Crc32(self.data) <NEW_LINE> <DEDENT> def digest(self): <NEW_LINE> <INDENT> return binascii.crc32(self.data) & 0xFFFFFFFF <NEW_LINE> <DEDENT> def hexdigest(self): <NEW_LINE> <INDENT> buf = (binascii.crc32(self.data) & 0xFFFFFFFF) <NEW_LINE> return ("%08X" % buf).lower() | This class is an api for the crc32 function that is compatible with mor | 62598fb77b180e01f3e490db |
class ParticleFilter(InferenceModule): <NEW_LINE> <INDENT> def __init__(self, ghostAgent, numParticles=300): <NEW_LINE> <INDENT> InferenceModule.__init__(self, ghostAgent); <NEW_LINE> self.setNumParticles(numParticles) <NEW_LINE> <DEDENT> def setNumParticles(self, numParticles): <NEW_LINE> <INDENT> self.numParticles = numParticles <NEW_LINE> <DEDENT> def initializeUniformly(self, gameState): <NEW_LINE> <INDENT> particleDistribution = self.numParticles/len(self.legalPositions) <NEW_LINE> self.particles = self.legalPositions * particleDistribution <NEW_LINE> <DEDENT> def observe(self, observation, gameState): <NEW_LINE> <INDENT> noisyDistance = observation <NEW_LINE> emissionModel = busters.getObservationDistribution(noisyDistance) <NEW_LINE> pacmanPosition = gameState.getPacmanPosition() <NEW_LINE> if noisyDistance is None: <NEW_LINE> <INDENT> self.particles = [self.getJailPosition()] * self.numParticles <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> beliefDist = self.getBeliefDistribution() <NEW_LINE> for particle in beliefDist: <NEW_LINE> <INDENT> trueDistance = util.manhattanDistance(pacmanPosition,particle) <NEW_LINE> beliefDist[particle] *= emissionModel[trueDistance] <NEW_LINE> <DEDENT> if not beliefDist.totalCount(): <NEW_LINE> <INDENT> self.initializeUniformly(gameState) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> beliefDist.normalize() <NEW_LINE> self.particles = [util.sample(beliefDist) for _ in xrange(self.numParticles)] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def elapseTime(self, gameState): <NEW_LINE> <INDENT> newParticles = [] <NEW_LINE> for particle in self.particles: <NEW_LINE> <INDENT> newPostDist = self.getPositionDistribution(self.setGhostPosition(gameState, particle)) <NEW_LINE> newParticles.append(util.sample(newPostDist)) <NEW_LINE> <DEDENT> self.particles = newParticles <NEW_LINE> <DEDENT> def getBeliefDistribution(self): <NEW_LINE> <INDENT> beliefDist = util.Counter() <NEW_LINE> for each_particle in self.particles: <NEW_LINE> <INDENT> beliefDist[each_particle] +=1.0 <NEW_LINE> <DEDENT> beliefDist.normalize() <NEW_LINE> return beliefDist | A particle filter for approximately tracking a single ghost.
Useful helper functions will include random.choice, which chooses an element
from a list uniformly at random, and util.sample, which samples a key from a
Counter by treating its values as probabilities. | 62598fb75fdd1c0f98e5e0a2 |
class Dispatcher: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.manifest_manager = ManifestManager() <NEW_LINE> self.ip = self.manifest_manager.get_from_manifest("Ip") <NEW_LINE> self.topic = self.manifest_manager.get_from_manifest("Topic") <NEW_LINE> <DEDENT> def dispatch(self, formatted_messages_list): <NEW_LINE> <INDENT> publisher = self.create_publisher() <NEW_LINE> for i in formatted_messages_list: <NEW_LINE> <INDENT> publisher.publish(self.topic, i) <NEW_LINE> <DEDENT> <DEDENT> def create_publisher(self): <NEW_LINE> <INDENT> publisher = mqtt.Client() <NEW_LINE> publisher.connect(self.ip) <NEW_LINE> return publisher | Dispatcher Class | 62598fb7d7e4931a7ef3c1a9 |
class DescribeUHostInstanceSnapshotResponseSchema(schema.ResponseSchema): <NEW_LINE> <INDENT> fields = { "SnapshotSet": fields.List( models.UHostSnapshotSetSchema(), required=False, load_from="SnapshotSet", ), "UhostId": fields.Str(required=False, load_from="UhostId"), } | DescribeUHostInstanceSnapshot - 获取已经存在的UHost实例的存储快照列表。
| 62598fb7bd1bec0571e1514c |
class ClassProperty(property): <NEW_LINE> <INDENT> def __get__(self, obj, obj_type=None): <NEW_LINE> <INDENT> return super(ClassProperty, self).__get__(obj_type) <NEW_LINE> <DEDENT> def __set__(self, obj, value): <NEW_LINE> <INDENT> super(ClassProperty, self).__set__(type(obj), value) <NEW_LINE> <DEDENT> def __delete__(self, obj): <NEW_LINE> <INDENT> super(ClassProperty, self).__delete__(type(obj)) | Python doesn't have class properties (yet?), but this should do the trick.
We need this to keep track of known (previously seen) series. | 62598fb7d268445f26639c0e |
class BadCriteriaError(Exception): <NEW_LINE> <INDENT> pass | Failed to find results with given criteria | 62598fb7283ffb24f3cf399d |
class Deck(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.deck = [] <NEW_LINE> <DEDENT> def populateDeck(self): <NEW_LINE> <INDENT> for hoeveelheid in [1, 2, 3]: <NEW_LINE> <INDENT> for kleur in [1, 2, 3]: <NEW_LINE> <INDENT> for vorm in [1, 2, 3]: <NEW_LINE> <INDENT> for vulling in [1, 2, 3]: <NEW_LINE> <INDENT> self.addCard( SetKaart(hoeveelheid, kleur, vorm, vulling) ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def shuffleDeck(self): <NEW_LINE> <INDENT> random.shuffle(self.deck) <NEW_LINE> <DEDENT> def addCard(self, card): <NEW_LINE> <INDENT> self.deck.append(card) <NEW_LINE> <DEDENT> def drawCard(self): <NEW_LINE> <INDENT> return self.deck.pop() <NEW_LINE> <DEDENT> def printDeck(self): <NEW_LINE> <INDENT> cardnum = 1 <NEW_LINE> for card in self.deck: <NEW_LINE> <INDENT> print (card) <NEW_LINE> cardnum = cardnum + 1 <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> return self.deck[key] | Een Deck bestaat uit 81 unique SetKaart-objecten. Als een kaart getrokken
wordt, wordt deze overgebracht naar het speelveld. | 62598fb73346ee7daa3376d2 |
class MCTS(object): <NEW_LINE> <INDENT> def __init__(self, policy_value_fn, c_puct=5, n_playout=10000): <NEW_LINE> <INDENT> self._root = TreeNode(None, 1.0) <NEW_LINE> self._policy = policy_value_fn <NEW_LINE> self._c_puct = c_puct <NEW_LINE> self._n_playout = n_playout <NEW_LINE> <DEDENT> def _playout(self, state): <NEW_LINE> <INDENT> node = self._root <NEW_LINE> while(1): <NEW_LINE> <INDENT> if node.is_leaf(): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> action, node = node.select(self._c_puct) <NEW_LINE> state.do_move(action) <NEW_LINE> <DEDENT> action_probs, _ = self._policy(state) <NEW_LINE> end, winner = state.game_end() <NEW_LINE> if not end: <NEW_LINE> <INDENT> node.expand(action_probs) <NEW_LINE> <DEDENT> leaf_value = self._evaluate_rollout(state) <NEW_LINE> node.update_recursive(leaf_value,-leaf_value,0) <NEW_LINE> <DEDENT> def _evaluate_rollout(self, state, limit=1000): <NEW_LINE> <INDENT> player = state.get_current_player() <NEW_LINE> for i in range(limit): <NEW_LINE> <INDENT> end, winner = state.game_end() <NEW_LINE> if end: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> action_probs = rollout_policy_fn(state) <NEW_LINE> max_action = max(action_probs, key=itemgetter(1))[0] <NEW_LINE> state.do_move(max_action) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("WARNING: rollout reached move limit") <NEW_LINE> <DEDENT> if winner == -1: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if winner == state.config.get_before_player(player): <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_move(self, state): <NEW_LINE> <INDENT> for n in range(self._n_playout): <NEW_LINE> <INDENT> state_copy = copy.deepcopy(state) <NEW_LINE> self._playout(state_copy) <NEW_LINE> <DEDENT> return max(self._root._children.items(), key=lambda act_node: act_node[1]._n_visits)[0] <NEW_LINE> <DEDENT> def update_with_move(self, last_move): <NEW_LINE> <INDENT> if last_move in self._root._children: <NEW_LINE> <INDENT> self._root = self._root._children[last_move] <NEW_LINE> self._root._parent = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._root = TreeNode(None, 1.0) <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "MCTS" | A simple implementation of Monte Carlo Tree Search. | 62598fb7dc8b845886d536cc |
class DiffKindChange(object): <NEW_LINE> <INDENT> def __init__(self, differs): <NEW_LINE> <INDENT> self.differs = differs <NEW_LINE> <DEDENT> def finish(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_diff_tree(klass, diff_tree): <NEW_LINE> <INDENT> return klass(diff_tree.differs) <NEW_LINE> <DEDENT> def diff(self, old_path, new_path, old_kind, new_kind): <NEW_LINE> <INDENT> if None in (old_kind, new_kind): <NEW_LINE> <INDENT> return DiffPath.CANNOT_DIFF <NEW_LINE> <DEDENT> result = DiffPath._diff_many( self.differs, old_path, new_path, old_kind, None) <NEW_LINE> if result is DiffPath.CANNOT_DIFF: <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> return DiffPath._diff_many( self.differs, old_path, new_path, None, new_kind) | Special differ for file kind changes.
Represents kind change as deletion + creation. Uses the other differs
to do this. | 62598fb73d592f4c4edbafd5 |
class Links(Region): <NEW_LINE> <INDENT> _security_log_link_locator = ( By.CSS_SELECTOR, '[href$=security_log]') <NEW_LINE> _oauth_application_link_locator = ( By.CSS_SELECTOR, '[href*=oauth]') <NEW_LINE> _fine_print_link_locator = ( By.CSS_SELECTOR, '[href$=fine_print]') <NEW_LINE> _accounts_api_link_locator = ( By.CSS_SELECTOR, '[href*="/api"]') <NEW_LINE> def view_api_documentation(self) -> APIDocumentation: <NEW_LINE> <INDENT> return self._link_loader( self._accounts_api_link_locator, APIDocumentation) <NEW_LINE> <DEDENT> def view_contracts(self) -> Contracts: <NEW_LINE> <INDENT> return self._link_loader( self._fine_print_link_locator, Contracts) <NEW_LINE> <DEDENT> def view_oauth_applications(self) -> Doorkeeper: <NEW_LINE> <INDENT> return self._link_loader( self._oauth_application_link_locator, Doorkeeper) <NEW_LINE> <DEDENT> def view_security_log(self) -> Security: <NEW_LINE> <INDENT> return self._link_loader( self._security_log_link_locator, Security) <NEW_LINE> <DEDENT> def _link_loader(self, locator: Selector, destination: Page) -> Page: <NEW_LINE> <INDENT> link = self.find_element(*locator) <NEW_LINE> base_url = Utility.parent_page(self).base_url <NEW_LINE> Utility.click_option(self.driver, element=link) <NEW_LINE> return go_to_(destination(self.driver, base_url=base_url)) | Accounts program links section. | 62598fb7009cb60464d01637 |
class FirewalldPnaicMode(APIView): <NEW_LINE> <INDENT> def get(self, request, format=None): <NEW_LINE> <INDENT> fm = FirewallManger() <NEW_LINE> panic_mode = fm.get_firewall_panic_mode() <NEW_LINE> return Response(panic_mode, status=status.HTTP_200_OK) <NEW_LINE> <DEDENT> def put(self, request, format=None): <NEW_LINE> <INDENT> fm = FirewallManger() <NEW_LINE> mode = request.DATA.get('panic_mode') <NEW_LINE> mode_struct = ['on', 'off'] <NEW_LINE> if mode not in mode_struct: <NEW_LINE> <INDENT> return Response('Arguments is not invalid!') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = fm.set_panic_mode(mode) <NEW_LINE> if result: <NEW_LINE> <INDENT> return Response("Config Success!", status=status.HTTP_200_OK) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Response("Config failed!", status=status.HTTP_500_INTERNAL_SERVER_ERROR) | Dynamic firewall configuration: runtime and permanent | 62598fb75fdd1c0f98e5e0a3 |
class MockSession: <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def return_status_code(cls, status_code): <NEW_LINE> <INDENT> return MockResponse(status_code, text='Failed because test') <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def return_token_text(cls): <NEW_LINE> <INDENT> return MockResponse(200, ('{"access_token":' '"eDdX8Kr6gmS1Axvp1iPDWuSsPOofOe", "token_type":' '"Bearer", "expires_in": 3600, "scope":' '"read write"}')) | Mock functions that return a MockResponse for mimicking
requests.Session. | 62598fb757b8e32f525081a7 |
class CMSAllinkBaseFormPlugin(CMSPluginBase): <NEW_LINE> <INDENT> form_class = None <NEW_LINE> url_name = None <NEW_LINE> def render(self, context, instance, placeholder): <NEW_LINE> <INDENT> context = super().render(context, instance, placeholder) <NEW_LINE> context.update({ 'form': self.form_class(), 'action': self.get_form_action(instance), }) <NEW_LINE> return context <NEW_LINE> <DEDENT> @property <NEW_LINE> def view_name(self): <NEW_LINE> <INDENT> return '{}:{}'.format(self.model._meta.app_label, self.url_name) <NEW_LINE> <DEDENT> def get_form_action(self, instance): <NEW_LINE> <INDENT> return reverse(self.view_name, kwargs={'plugin_id': instance.id}) | Use this BasePlugin for plugins, which display a form.
example implementation:
class CMSLivingSignupPlugin(CMSAllinkBaseFormPlugin):
name = 'Living Signup Plugin'
model = LivingSignupPlugin
render_template = 'living/plugins/signup/content.html'
form_class = LivingSignupForm
url_name = 'signup' | 62598fb771ff763f4b5e788c |
@keras_export('keras.layers.experimental.preprocessing.Resizing') <NEW_LINE> class Resizing(PreprocessingLayer): <NEW_LINE> <INDENT> def __init__(self, height, width, interpolation='bilinear', **kwargs): <NEW_LINE> <INDENT> self.target_height = height <NEW_LINE> self.target_width = width <NEW_LINE> self.interpolation = interpolation <NEW_LINE> self._interpolation_method = get_interpolation(interpolation) <NEW_LINE> self.input_spec = InputSpec(ndim=4) <NEW_LINE> super(Resizing, self).__init__(**kwargs) <NEW_LINE> base_preprocessing_layer.keras_kpl_gauge.get_cell('Resizing').set(True) <NEW_LINE> <DEDENT> def call(self, inputs): <NEW_LINE> <INDENT> outputs = image_ops.resize_images_v2( images=inputs, size=[self.target_height, self.target_width], method=self._interpolation_method) <NEW_LINE> return outputs <NEW_LINE> <DEDENT> def compute_output_shape(self, input_shape): <NEW_LINE> <INDENT> input_shape = tensor_shape.TensorShape(input_shape).as_list() <NEW_LINE> return tensor_shape.TensorShape( [input_shape[0], self.target_height, self.target_width, input_shape[3]]) <NEW_LINE> <DEDENT> def get_config(self): <NEW_LINE> <INDENT> config = { 'height': self.target_height, 'width': self.target_width, 'interpolation': self.interpolation, } <NEW_LINE> base_config = super(Resizing, self).get_config() <NEW_LINE> return dict(list(base_config.items()) + list(config.items())) | Image resizing layer.
Resize the batched image input to target height and width. The input should
be a 4-D tensor in the format of NHWC.
Args:
height: Integer, the height of the output shape.
width: Integer, the width of the output shape.
interpolation: String, the interpolation method. Defaults to `bilinear`.
Supports `bilinear`, `nearest`, `bicubic`, `area`, `lanczos3`, `lanczos5`,
`gaussian`, `mitchellcubic` | 62598fb7a8370b77170f04f3 |
class TrafficLightScenario(BasicScenario): <NEW_LINE> <INDENT> category = "TrafficLightScenario" <NEW_LINE> def __init__(self, world, ego_vehicle, config, randomize=False, debug_mode=False, timeout=35 * 60): <NEW_LINE> <INDENT> self.config = config <NEW_LINE> self.debug = debug_mode <NEW_LINE> self.timeout = timeout <NEW_LINE> super(TrafficLightScenario, self).__init__("TrafficLightScenario", ego_vehicle, config, world, debug_mode, terminate_on_failure=True, criteria_enable=True) <NEW_LINE> <DEDENT> def _create_behavior(self): <NEW_LINE> <INDENT> sequence = py_trees.composites.Sequence("Sequence Behavior") <NEW_LINE> traffic_manipulator = TrafficLightManipulator(self.ego_vehicle, debug=self.debug) <NEW_LINE> sequence.add_child(traffic_manipulator) <NEW_LINE> return sequence <NEW_LINE> <DEDENT> def _create_test_criteria(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> self.remove_all_actors() | This scenario controls traffic lights at intersection to create interesting situations, e.g.:
- vehicles running red lights
- yielding to traffic | 62598fb7f548e778e596b6ba |
class Sphere(Benchmark): <NEW_LINE> <INDENT> def __init__(self, dimensions=2): <NEW_LINE> <INDENT> Benchmark.__init__(self, dimensions) <NEW_LINE> self.bounder = ec.Bounder([-5.12] * self.dimensions, [5.12] * self.dimensions) <NEW_LINE> self.maximize = False <NEW_LINE> self.global_optimum = [0 for _ in range(self.dimensions)] <NEW_LINE> <DEDENT> def generator(self, random, args): <NEW_LINE> <INDENT> return [random.uniform(-5.12, 5.12) for _ in range(self.dimensions)] <NEW_LINE> <DEDENT> def evaluator(self, candidates, args): <NEW_LINE> <INDENT> fitness = [] <NEW_LINE> for c in candidates: <NEW_LINE> <INDENT> fitness.append(sum([x**2 for x in c])) <NEW_LINE> <DEDENT> return fitness | Defines the Sphere benchmark problem.
This class defines the Sphere global optimization problem, also called
the "first function of De Jong's" or "De Jong's F1." It is continuous,
convex, and unimodal, and it is defined as follows:
.. math::
f(x) = \sum_{i=1}^n x_i^2
Here, :math:`n` represents the number of dimensions and :math:`x_i \in [-5.12, 5.12]` for :math:`i=1,...,n`.
.. figure:: http://www-optima.amp.i.kyoto-u.ac.jp/member/student/hedar/Hedar_files/TestGO_files/image11981.jpg
:alt: Sphere function
:align: center
Two-dimensional Sphere function
(`image source <http://www-optima.amp.i.kyoto-u.ac.jp/member/student/hedar/Hedar_files/TestGO_files/Page1113.htm>`__)
Public Attributes:
- *global_optimum* -- the problem input that produces the optimum output.
Here, this corresponds to [0, 0, ..., 0]. | 62598fb7cc0a2c111447b122 |
class BetaJobServiceServicer(object): <NEW_LINE> <INDENT> def CreateJob(self, request, context): <NEW_LINE> <INDENT> context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) <NEW_LINE> <DEDENT> def ListJobs(self, request, context): <NEW_LINE> <INDENT> context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) <NEW_LINE> <DEDENT> def GetJob(self, request, context): <NEW_LINE> <INDENT> context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) <NEW_LINE> <DEDENT> def CancelJob(self, request, context): <NEW_LINE> <INDENT> context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) | The Beta API is deprecated for 0.15.0 and later.
It is recommended to use the GA API (classes and functions in this
file not marked beta) for all further purposes. This class was generated
only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0. | 62598fb756b00c62f0fb29cf |
class ExpectimaxAgent(MultiAgentSearchAgent): <NEW_LINE> <INDENT> def getAction(self, gameState): <NEW_LINE> <INDENT> return self.maximize(gameState, 1, 0)[1] <NEW_LINE> <DEDENT> def getNodeValue(self, gameState, currDepth, agentIndex): <NEW_LINE> <INDENT> if gameState.isWin() or gameState.isLose(): <NEW_LINE> <INDENT> return self.evaluationFunction(gameState) <NEW_LINE> <DEDENT> if agentIndex == gameState.getNumAgents(): <NEW_LINE> <INDENT> agentIndex = 0 <NEW_LINE> currDepth += 1 <NEW_LINE> if currDepth > self.depth: <NEW_LINE> <INDENT> return self.evaluationFunction(gameState) <NEW_LINE> <DEDENT> <DEDENT> if agentIndex == 0: <NEW_LINE> <INDENT> return self.maximize(gameState, currDepth, agentIndex)[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.average(gameState, currDepth, agentIndex) <NEW_LINE> <DEDENT> <DEDENT> def getSuccessorValues(self, gameState, currDepth, agentIndex): <NEW_LINE> <INDENT> legalActions = gameState.getLegalActions(agentIndex) <NEW_LINE> successorNodes = [ (gameState.generateSuccessor(agentIndex, action), action) for action in legalActions ] <NEW_LINE> return [ (self.getNodeValue(successor, currDepth, agentIndex + 1), action) for (successor, action) in successorNodes ] <NEW_LINE> <DEDENT> def maximize(self, gameState, currDepth, agentIndex): <NEW_LINE> <INDENT> successorValues = self.getSuccessorValues(gameState, currDepth, agentIndex) <NEW_LINE> maxValue = max(successorValues)[0] <NEW_LINE> equalBest = [ action for (value, action) in successorValues if value == maxValue ] <NEW_LINE> randSelection = random.randint(0, len(equalBest) - 1) <NEW_LINE> return (maxValue, equalBest[randSelection]) <NEW_LINE> <DEDENT> def average(self, gameState, currDepth, agentIndex): <NEW_LINE> <INDENT> successorValues = [ value[0] for value in self.getSuccessorValues(gameState, currDepth, agentIndex)] <NEW_LINE> return sum(successorValues) * 1.0 / len(successorValues) | Your expectimax agent (question 4) | 62598fb78a349b6b43686351 |
class PathEntry(SuccessEntry): <NEW_LINE> <INDENT> PATH_TYPES = ( ("device", "Device"), ("directory", "Directory"), ("hardlink", "Hard Link"), ("nonexistent", "Non Existent"), ("permissions", "Permissions"), ("symlink", "Symlink"), ) <NEW_LINE> DETAIL_UNUSED = 0 <NEW_LINE> DETAIL_DIFF = 1 <NEW_LINE> DETAIL_BINARY = 2 <NEW_LINE> DETAIL_SENSITIVE = 3 <NEW_LINE> DETAIL_SIZE_LIMIT = 4 <NEW_LINE> DETAIL_VCS = 5 <NEW_LINE> DETAIL_PRUNED = 6 <NEW_LINE> DETAIL_CHOICES = ( (DETAIL_UNUSED, 'Unused'), (DETAIL_DIFF, 'Diff'), (DETAIL_BINARY, 'Binary'), (DETAIL_SENSITIVE, 'Sensitive'), (DETAIL_SIZE_LIMIT, 'Size limit exceeded'), (DETAIL_VCS, 'VCS output'), (DETAIL_PRUNED, 'Pruned paths'), ) <NEW_LINE> path_type = models.CharField(max_length=128, choices=PATH_TYPES) <NEW_LINE> target_perms = models.ForeignKey(FilePerms, related_name="+") <NEW_LINE> current_perms = models.ForeignKey(FilePerms, related_name="+") <NEW_LINE> acls = models.ManyToManyField(FileAcl) <NEW_LINE> detail_type = models.IntegerField(default=0, choices=DETAIL_CHOICES) <NEW_LINE> details = models.TextField(default='') <NEW_LINE> ENTRY_TYPE = r"Path" <NEW_LINE> def mode_problem(self): <NEW_LINE> <INDENT> if self.current_perms.empty(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> elif self.target_perms.mode != self.current_perms.mode: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def has_detail(self): <NEW_LINE> <INDENT> return self.detail_type != PathEntry.DETAIL_UNUSED <NEW_LINE> <DEDENT> def is_diff(self): <NEW_LINE> <INDENT> return self.detail_type == PathEntry.DETAIL_DIFF <NEW_LINE> <DEDENT> def is_sensitive(self): <NEW_LINE> <INDENT> return self.detail_type == PathEntry.DETAIL_SENSITIVE <NEW_LINE> <DEDENT> def is_binary(self): <NEW_LINE> <INDENT> return self.detail_type == PathEntry.DETAIL_BINARY <NEW_LINE> <DEDENT> def is_too_large(self): <NEW_LINE> <INDENT> return self.detail_type == PathEntry.DETAIL_SIZE_LIMIT <NEW_LINE> <DEDENT> def short_list(self): <NEW_LINE> <INDENT> rv = super(PathEntry, self).short_list() <NEW_LINE> if self.is_extra(): <NEW_LINE> <INDENT> return rv <NEW_LINE> <DEDENT> if self.mode_problem(): <NEW_LINE> <INDENT> rv.append("File mode") <NEW_LINE> <DEDENT> if self.detail_type == PathEntry.DETAIL_PRUNED: <NEW_LINE> <INDENT> rv.append("Directory has extra files") <NEW_LINE> <DEDENT> elif self.detail_type != PathEntry.DETAIL_UNUSED: <NEW_LINE> <INDENT> rv.append("Incorrect data") <NEW_LINE> <DEDENT> if hasattr(self, 'linkentry') and self.linkentry and self.linkentry.target_path != self.linkentry.current_path: <NEW_LINE> <INDENT> rv.append("Incorrect target") <NEW_LINE> <DEDENT> return rv | reason why modified or bad entry did not verify, or changed. | 62598fb72ae34c7f260ab1f2 |
class Node(object): <NEW_LINE> <INDENT> def __init__(self, *args): <NEW_LINE> <INDENT> self._children = [] <NEW_LINE> <DEDENT> def AppendChild(self, child): <NEW_LINE> <INDENT> self._children.append(child) <NEW_LINE> <DEDENT> @property <NEW_LINE> def children(self): <NEW_LINE> <INDENT> return self._children | Represents a node in the suite tree structure. | 62598fb71b99ca400228f5bb |
class Settings(): <NEW_LINE> <INDENT> settings = None <NEW_LINE> def __init__(self, view): <NEW_LINE> <INDENT> settings_key = 'phpunit_skelgen.sublime-settings' <NEW_LINE> self.settings = sublime.load_settings(settings_key) <NEW_LINE> self.project_settings = {} <NEW_LINE> if sublime.active_window() is not None: <NEW_LINE> <INDENT> project_settings = view.settings() <NEW_LINE> if project_settings.has("phpunit_skelgen"): <NEW_LINE> <INDENT> self.project_settings = project_settings.get('phpunit_skelgen') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get(self, key): <NEW_LINE> <INDENT> if key in self.project_settings: <NEW_LINE> <INDENT> return self.project_settings.get(key) <NEW_LINE> <DEDENT> return self.settings.get(key) | Class that loads the necessary setting for running the generate_test
command. | 62598fb755399d3f0562662b |
class Var(object): <NEW_LINE> <INDENT> def __init__(self, val=0): <NEW_LINE> <INDENT> self.__val = val <NEW_LINE> <DEDENT> @property <NEW_LINE> def val(self): <NEW_LINE> <INDENT> return self.__val <NEW_LINE> <DEDENT> @val.setter <NEW_LINE> def val(self, new_val): <NEW_LINE> <INDENT> self.__val = new_val | Generic variable type use in the Hylozoic 3 system
This provides a standard interface for all variables within the system.
This allows all variables, including those of immutable types, to be passed by refernce through this mutable object.
Parameters
------------
val (default = 0)
Value of the variable
Attributes
------------
__val
Value of the variable
Examples
------------
>>> a = Var((1, 2, 3))
>>> a.val = {a_dict: (9, 8, 7)}
>>> print(a.val['a_dict']) | 62598fb701c39578d7f12e90 |
class AttrVI_ATTR_RSRC_MANF_NAME(Attribute): <NEW_LINE> <INDENT> resources = AllSessionTypes <NEW_LINE> py_name = "resource_manufacturer_name" <NEW_LINE> visa_name = "VI_ATTR_RSRC_MANF_NAME" <NEW_LINE> visa_type = "ViString" <NEW_LINE> default = NotAvailable <NEW_LINE> read, write, local = True, False, False | Manufacturer name of the vendor that implemented the VISA library.
This attribute is not related to the device manufacturer attributes.
Note The value of this attribute is for display purposes only and not for
programmatic decisions, as the value can differ between VISA implementations
and/or revisions. | 62598fb78a43f66fc4bf2290 |
class Snapshot(MarketDataBase): <NEW_LINE> <INDENT> class UpdateType: <NEW_LINE> <INDENT> NONE = 0 <NEW_LINE> ORDER_BOOK = 1 <NEW_LINE> TRADES = 2 <NEW_LINE> <DEDENT> def __init__(self, exchange, instmt_name): <NEW_LINE> <INDENT> MarketDataBase.__init__(self) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def columns(is_name=True): <NEW_LINE> <INDENT> if is_name: <NEW_LINE> <INDENT> return ['exchange', 'instmt', 'trade_px', 'trade_volume', 'b1', 'b2', 'b3', 'b4', 'b5', 'a1', 'a2', 'a3', 'a4', 'a5', 'bq1', 'bq2', 'bq3', 'bq4', 'bq5', 'aq1', 'aq2', 'aq3', 'aq4', 'aq5', 'order_date_time', 'trades_date_time', 'update_type'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ['trade_px', 'trade_volume', 'b1', 'b2', 'b3', 'b4', 'b5', 'a1', 'a2', 'a3', 'a4', 'a5', 'bq1', 'bq2', 'bq3', 'bq4', 'bq5', 'aq1', 'aq2', 'aq3', 'aq4', 'aq5', 'order_date_time', 'trades_date_time', 'update_type'] <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def types(is_name=True): <NEW_LINE> <INDENT> if is_name: <NEW_LINE> <INDENT> return ['varchar(20)', 'varchar(20)', 'decimal(20,8)', 'decimal(20,8)'] + ['decimal(20,8)'] * 10 + ['decimal(20,8)'] * 10 + ['varchar(25)', 'varchar(25)', 'int'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ['decimal(20,8)', 'decimal(20,8)'] + ['decimal(20,8)'] * 10 + ['decimal(20,8)'] * 10 + ['varchar(25)', 'varchar(25)', 'int'] <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def values(exchange_name='', instmt_name='', l2_depth=None, last_trade=None, update_type=UpdateType.NONE): <NEW_LINE> <INDENT> assert l2_depth is not None and last_trade is not None, "L2 depth and last trade must not be none." <NEW_LINE> return ([exchange_name] if exchange_name else []) + ([instmt_name] if instmt_name else []) + [last_trade.trade_price, last_trade.trade_volume] + [b.price for b in l2_depth.bids[0:5]] + [a.price for a in l2_depth.asks[0:5]] + [b.volume for b in l2_depth.bids[0:5]] + [a.volume for a in l2_depth.asks[0:5]] + [l2_depth.date_time, last_trade.date_time, update_type] | Market price snapshot | 62598fb763d6d428bbee28c5 |
class Stack(object): <NEW_LINE> <INDENT> def __init__(self, limit = 10): <NEW_LINE> <INDENT> self.stack = [] <NEW_LINE> self.limit = limit <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return ' '.join([str(i) for i in self.stack]) <NEW_LINE> <DEDENT> def push(self, data): <NEW_LINE> <INDENT> if len(self.stack) >= self.limit: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.stack.append(data) <NEW_LINE> <DEDENT> <DEDENT> def pop(self): <NEW_LINE> <INDENT> if len(self.stack) <= 0: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.stack.pop() <NEW_LINE> <DEDENT> <DEDENT> def peek(self): <NEW_LINE> <INDENT> if len(self.stack) <= 0: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.stack[len(self.stack) - 1] <NEW_LINE> <DEDENT> <DEDENT> def is_empty(self): <NEW_LINE> <INDENT> return self.size() == 0 <NEW_LINE> <DEDENT> def size(self): <NEW_LINE> <INDENT> return len(self.stack) <NEW_LINE> <DEDENT> def get_code(self): <NEW_LINE> <INDENT> import inspect <NEW_LINE> return inspect.getsource(Stack) | Python implementation of Stack | 62598fb7cc40096d6161a264 |
class SeverityColumnGenerator(DiscreteColumnGenerator): <NEW_LINE> <INDENT> def __init__(self) -> None: <NEW_LINE> <INDENT> names = ["severity", "importance"] <NEW_LINE> possible_values = ["minor", "normal", "major", "critical"] <NEW_LINE> super().__init__(names, possible_values, max_discrete_values=3) | A discrete data type representing a severity level. | 62598fb723849d37ff8511c9 |
class TagInfo(object): <NEW_LINE> <INDENT> def __init__(self, ref, revision, object_=None, message=None, tagger=None): <NEW_LINE> <INDENT> self.ref = ref <NEW_LINE> self.revision = revision <NEW_LINE> self.object_ = object_ <NEW_LINE> self.message = message <NEW_LINE> self.tagger = tagger <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dict(cls, dict_): <NEW_LINE> <INDENT> return cls(ref=dict_.get('ref', None), revision=dict_.get('revision', None), object_=dict_.get('object', None), message=dict_.get('message', None), tagger=GitPersonInfo.from_dict(dict_.get('tagger', {}))) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<TagInfo[ref:{0} revision:{1}]>'.format(self.ref, self.revision) | http://192.168.10.48/Documentation/rest-api-projects.html#tag-info
parsed output example:
{u'message': u'tag before change CXLite_H3713_HiOS2.0.0_N branch base to E31_H375_HiOS2.0.0_N_DEV.xml',
u'object': u'f448fedb534efc74501306cedc287d229479794c',
u'ref': u'refs/tags/CXLite_H3713_HiOS2.0.0_N_BEFORE_TAG_20161217',
u'revision': u'3b9ad67ba003908ba1e6790488c909522cc9d960',
u'tagger': {u'date': u'2016-12-17 08:15:44.000000000',
u'email': u'haobin.zhang@reallytek.com',
u'name': u'haobin.zhang',
u'tz': 480}} | 62598fb797e22403b383b01c |
class RandomQuestion(ListAPIView): <NEW_LINE> <INDENT> serializer_class = QuestionSerializer <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> category = self.request.GET.get('category',None) <NEW_LINE> level = self.request.GET.get('level', None) <NEW_LINE> user = self.request.user <NEW_LINE> if user.is_anonymous(): <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> answered_questions = Answer.objects.filter(user = user, is_correct = True).values('question') <NEW_LINE> questions = None <NEW_LINE> if category is None and level is None: <NEW_LINE> <INDENT> questions = Question.objects.all().exclude(id__in = answered_questions) <NEW_LINE> <DEDENT> elif category is None: <NEW_LINE> <INDENT> questions = Question.objects.filter(level = level).exclude(id__in = answered_questions) <NEW_LINE> <DEDENT> elif level is None: <NEW_LINE> <INDENT> questions = Question.objects.filter(category = category).exclude(id__in = answered_questions) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> questions = Question.objects.filter(category = category, level = level).exclude(id__in = answered_questions) <NEW_LINE> <DEDENT> count = len(questions) <NEW_LINE> if(count == 0): <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> position = random.randint(0, count-1) <NEW_LINE> return [questions[position],] | Returns a random question to the User | 62598fb7f548e778e596b6bb |
class RNN_ENCODER(nn.Module): <NEW_LINE> <INDENT> def __init__(self, ntoken, ninput=300, drop_prob=0.5, nhidden=128, nlayers=1, bidirectional=True): <NEW_LINE> <INDENT> super(RNN_ENCODER, self).__init__() <NEW_LINE> """What is the use and meaning of n_steps""" <NEW_LINE> self.n_steps = cfg.TEXT.WORDS_NUM <NEW_LINE> self.ntoken = ntoken <NEW_LINE> self.ninput = ninput <NEW_LINE> self.drop_prob = drop_prob <NEW_LINE> self.nlayers = nlayers <NEW_LINE> self.bidirectional = bidirectional <NEW_LINE> self.rnn_type = cfg.RNN_TYPE <NEW_LINE> if bidirectional: <NEW_LINE> <INDENT> self.num_directions = 2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.num_directions = 1 <NEW_LINE> <DEDENT> self.nhidden = nhidden // self.num_directions <NEW_LINE> self.define_module() <NEW_LINE> self.init_weights() <NEW_LINE> <DEDENT> def define_module(self): <NEW_LINE> <INDENT> self.encoder = nn.Embedding(self.ntoken, self.ninput) <NEW_LINE> self.drop = nn.Dropout(self.drop_prob) <NEW_LINE> if self.rnn_type == 'LSTM': <NEW_LINE> <INDENT> self.rnn = nn.LSTM(self.ninput, self.nhidden, self.nlayers, batch_first=True, dropout=self.drop_prob, bidirectional=self.bidirectional) <NEW_LINE> <DEDENT> elif self.rnn_type == 'GRU': <NEW_LINE> <INDENT> self.rnn = nn.GRU(self.ninput, self.nhidden, self.nlayers, batch_first=True, dropout=self.drop_prob, bidirectional=self.bidirectional) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> <DEDENT> def init_weights(self): <NEW_LINE> <INDENT> initrange = 0.1 <NEW_LINE> self.encoder.weight.data.uniform_(-initrange, initrange) <NEW_LINE> <DEDENT> def init_hidden(self, bsz): <NEW_LINE> <INDENT> weight = next(self.parameters()).data <NEW_LINE> if self.rnn_type == 'LSTM': <NEW_LINE> <INDENT> return (Variable(weight.new(self.nlayers * self.num_directions, bsz, self.nhidden).zero_()), Variable(weight.new(self.nlayers * self.num_directions, bsz, self.nhidden).zero_())) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Variable(weight.new(self.nlayers * self.num_directions, bsz, self.nhidden).zero_()) <NEW_LINE> <DEDENT> <DEDENT> def forward(self, captions, cap_lens, hidden, mask=None): <NEW_LINE> <INDENT> emb = self.drop(self.encoder(captions)) <NEW_LINE> cap_lens = cap_lens.data.tolist() <NEW_LINE> emb = pack_padded_sequence(emb, cap_lens, batch_first=True) <NEW_LINE> output, hidden = self.rnn(emb, hidden) <NEW_LINE> output = pad_packed_sequence(output, batch_first=True)[0] <NEW_LINE> words_emb = output.transpose(1, 2) <NEW_LINE> if self.rnn_type == 'LSTM': <NEW_LINE> <INDENT> sent_emb = hidden[0].transpose(0, 1).contiguous() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sent_emb = hidden.transpose(0, 1).contiguous() <NEW_LINE> <DEDENT> sent_emb = sent_emb.view(-1, self.nhidden * self.num_directions) <NEW_LINE> return words_emb, sent_emb | How is it working ?? | 62598fb7498bea3a75a57c38 |
class PopulationFilterBackend(OrderingFilter, DjangoFilterBackend): <NEW_LINE> <INDENT> def filter_queryset(self, request, queryset, view): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> filterable = getattr(view, 'filter_fields', []) <NEW_LINE> filters = dict([(k, v) for k, v in request.GET.items() if k in filterable]) <NEW_LINE> mid1 = filters.get('marker', 'rs2476601') <NEW_LINE> dataset = filters.get('dataset', 'EUR').replace('-', '') <NEW_LINE> query = ElasticQuery(BoolQuery(must_arr=[Query.term("id", mid1)]), sources=['seqid', 'start']) <NEW_LINE> elastic = Search(search_query=query, idx=ElasticSettings.idx('MARKER', 'MARKER'), size=1) <NEW_LINE> doc = elastic.search().docs[0] <NEW_LINE> seqid = getattr(doc, 'seqid') <NEW_LINE> rserve = getattr(settings, 'RSERVE') <NEW_LINE> conn = pyRserve.connect(host=rserve.get('HOST'), port=rserve.get('PORT')) <NEW_LINE> pop_str = conn.r.get_pop(dataset, seqid, mid1) <NEW_LINE> pops = json.loads(str(pop_str)) <NEW_LINE> populations = [] <NEW_LINE> for pop in pops: <NEW_LINE> <INDENT> pops[pop]['population'] = pop <NEW_LINE> populations.append(pops[pop]) <NEW_LINE> <DEDENT> conn.close() <NEW_LINE> return [ElasticObject(initial={'populations': populations, 'marker': mid1})] <NEW_LINE> <DEDENT> except (TypeError, ValueError, IndexError, ConnectionError): <NEW_LINE> <INDENT> return [ElasticObject(initial={'populations': None, 'marker': mid1})] | Extend L{DjangoFilterBackend} for filtering LD resources. | 62598fb73539df3088ecc3c3 |
class TestShardVertex(unittest.TestCase): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def setup_class(self): <NEW_LINE> <INDENT> if _cfg.server_backend == 'cassandra': <NEW_LINE> <INDENT> clear_graph() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> Gremlin().gremlin_post('graph.truncateBackend();') <NEW_LINE> <DEDENT> InsertData(gremlin='gremlin_hlm.txt').gremlin_graph() <NEW_LINE> <DEDENT> def test_reqiured_params(self): <NEW_LINE> <INDENT> json = {'start': 'hzE65Y+y5YCZ', 'end': 'ijI66LW15aeo5aiYAA=='} <NEW_LINE> code, res = Traverser().get_shard_vertex(json, auth=auth) <NEW_LINE> print(code, res) <NEW_LINE> self.assertEqual(code, 200) <NEW_LINE> self.assertEqual(41, len(res['vertices'])) | 通过指定的分片信息批量查询顶点 | 62598fb732920d7e50bc6165 |
class Script: <NEW_LINE> <INDENT> def __init__(self, lines): <NEW_LINE> <INDENT> self.lines = lines <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_script(cls, stream): <NEW_LINE> <INDENT> lines = [] <NEW_LINE> for i, data in enumerate(stream.readlines()): <NEW_LINE> <INDENT> if i % 2 == 0: <NEW_LINE> <INDENT> comment = data.strip() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> content = data.strip() <NEW_LINE> lines.append(Line(content, comment)) <NEW_LINE> <DEDENT> <DEDENT> return cls(lines) <NEW_LINE> <DEDENT> def to_script(self, stream): <NEW_LINE> <INDENT> stream.write(str(self)) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "\n".join(str(line) for line in self.lines) + "\n" <NEW_LINE> <DEDENT> def translate(self, to): <NEW_LINE> <INDENT> contents = [annotated(line.content) for line in self.lines] <NEW_LINE> translations = [deannotated(t) for t in translate(contents, to=to)] <NEW_LINE> translated_lines = [ Line(t, l.comment) for t, l in zip(translations, self.lines) ] <NEW_LINE> return self.__class__(translated_lines) <NEW_LINE> <DEDENT> def roundtrip(self, via, n=1): <NEW_LINE> <INDENT> raise NotImplementedError | Contains the contents of a script ripped from a ROM | 62598fb760cbc95b06364455 |
class MockAppTestCase(tornado.testing.AsyncTestCase): <NEW_LINE> <INDENT> mockappargs = {} <NEW_LINE> @classmethod <NEW_LINE> def setUpClass(cla): <NEW_LINE> <INDENT> cla.app = MockApplication(**cla.mockappargs) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def tearDownClass(cla): <NEW_LINE> <INDENT> cla.app.disconnect() <NEW_LINE> cla.app = None <NEW_LINE> <DEDENT> def get_new_ioloop(self): <NEW_LINE> <INDENT> return tornado.ioloop.IOLoop.instance() <NEW_LINE> <DEDENT> @tornado.gen.coroutine <NEW_LINE> def get_db_prop(self, tup): <NEW_LINE> <INDENT> query = two.propcache.PropCache.query_for_tuple(tup) <NEW_LINE> res = yield motor.Op(self.app.mongodb[tup[0]].find_one, query) <NEW_LINE> if res is None: <NEW_LINE> <INDENT> return NotFound <NEW_LINE> <DEDENT> return res['val'] <NEW_LINE> <DEDENT> @tornado.gen.coroutine <NEW_LINE> def resetTables(self): <NEW_LINE> <INDENT> yield motor.Op(self.app.mongodb.instanceprop.remove, {}) | Base class for Tworld test cases that need an Application to run in.
The mockappargs dict determines the setup parameters of the
MockApplication. | 62598fb75fdd1c0f98e5e0a5 |
class RestFulClient: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.app_logger = AppLogger.instance().logger <NEW_LINE> pass <NEW_LINE> <DEDENT> def delete(self, url, headers={}): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.app_logger.debug('request : {}'.format(url)) <NEW_LINE> response = requests.delete(url, headers=headers) <NEW_LINE> if (response.status_code == 200): <NEW_LINE> <INDENT> self.app_logger.debug("request successful") <NEW_LINE> return response <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.app_logger.debug( "request unsucessful code {0} : {1}".format(response.status_code, response.text)) <NEW_LINE> response = {} <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.app_logger.error(e) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> return response <NEW_LINE> <DEDENT> <DEDENT> def get(self, url, headers={}): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.app_logger.debug('request : {}'.format(url)) <NEW_LINE> response = requests.request(_GET, url, headers=headers) <NEW_LINE> if (response.status_code == 200): <NEW_LINE> <INDENT> self.app_logger.debug("request successful") <NEW_LINE> return response <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.app_logger.debug( "request unsucessful code {0} : {1}".format(response.status_code, response.text)) <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.app_logger.error(e) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> return response <NEW_LINE> <DEDENT> <DEDENT> def post(self, url, headers={}, payload='{}'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.app_logger.debug('request : {0} headers {1} '.format(url, headers)) <NEW_LINE> response = requests.request(_POST, url, data=payload, headers=headers) <NEW_LINE> if (response.status_code in [200, 201]): <NEW_LINE> <INDENT> self.app_logger.debug("request successful") <NEW_LINE> return response <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.app_logger.debug( "request unsucessful code {0} : {1}".format(response.status_code, response.text)) <NEW_LINE> response = {} <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.app_logger.error(e) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> return response | This method will be helpful in executing the http requests | 62598fb7f9cc0f698b1c5358 |
class SourceVertexSet(collections.abc.MutableSet, GraphComponent): <NEW_LINE> <INDENT> def __init__(self, vid: VertexID, graph_store: GraphStore): <NEW_LINE> <INDENT> GraphComponent.__init__(self, graph_store) <NEW_LINE> self._vid = vid <NEW_LINE> <DEDENT> def __contains__(self, vertex: VertexOrID) -> bool: <NEW_LINE> <INDENT> vid = self._to_vid(vertex, self._graph_store) <NEW_LINE> eid = DirectedEdgeID(vid, self._vid) <NEW_LINE> return self._graph_store.has_edge(eid) <NEW_LINE> <DEDENT> def __iter__(self) -> Iterator['Vertex']: <NEW_LINE> <INDENT> for eid in self._graph_store.iter_inbound(self._vid): <NEW_LINE> <INDENT> yield Vertex(eid.source, self._graph_store) <NEW_LINE> <DEDENT> <DEDENT> def __len__(self) -> int: <NEW_LINE> <INDENT> return self._graph_store.count_inbound(self._vid) <NEW_LINE> <DEDENT> def add(self, vertex: VertexOrID) -> 'Vertex': <NEW_LINE> <INDENT> vid = self._to_vid(vertex, self._graph_store) <NEW_LINE> eid = DirectedEdgeID(vid, self._vid) <NEW_LINE> self._graph_store.add_edge(eid) <NEW_LINE> return Vertex(vid, self._graph_store) <NEW_LINE> <DEDENT> def remove(self, vertex: VertexOrID) -> None: <NEW_LINE> <INDENT> vid = self._to_vid(vertex, self._graph_store) <NEW_LINE> eid = DirectedEdgeID(vid, self._vid) <NEW_LINE> if not self._graph_store.discard_edge(eid): <NEW_LINE> <INDENT> raise KeyError(vid) <NEW_LINE> <DEDENT> <DEDENT> def discard(self, vertex: VertexOrID) -> None: <NEW_LINE> <INDENT> vid = self._to_vid(vertex, self._graph_store) <NEW_LINE> eid = DirectedEdgeID(vid, self._vid) <NEW_LINE> self._graph_store.discard_edge(eid) | The set containing every vertex which is the source of an edge that shares the same given sink. | 62598fb755399d3f0562662d |
class Schaffer6(TestProblem): <NEW_LINE> <INDENT> def __init__(self, phenome_preprocessor=None, **kwargs): <NEW_LINE> <INDENT> self.num_variables = 2 <NEW_LINE> self._min_bounds = [-100.0, -100.0] <NEW_LINE> self._max_bounds = [100.0, 100.0] <NEW_LINE> bounds = (self.min_bounds, self.max_bounds) <NEW_LINE> self.bound_constraints_checker = BoundConstraintsChecker(bounds, phenome_preprocessor) <NEW_LINE> TestProblem.__init__(self, schaffer6, phenome_preprocessor=self.bound_constraints_checker, **kwargs) <NEW_LINE> self.is_deterministic = True <NEW_LINE> self.do_maximize = False <NEW_LINE> <DEDENT> @property <NEW_LINE> def min_bounds(self): <NEW_LINE> <INDENT> return self._min_bounds <NEW_LINE> <DEDENT> @min_bounds.setter <NEW_LINE> def min_bounds(self, bounds): <NEW_LINE> <INDENT> self._min_bounds = bounds <NEW_LINE> self.bound_constraints_checker.min_bounds = bounds <NEW_LINE> <DEDENT> @property <NEW_LINE> def max_bounds(self): <NEW_LINE> <INDENT> return self._max_bounds <NEW_LINE> <DEDENT> @max_bounds.setter <NEW_LINE> def max_bounds(self, bounds): <NEW_LINE> <INDENT> self._max_bounds = bounds <NEW_LINE> self.bound_constraints_checker.max_bounds = bounds <NEW_LINE> <DEDENT> def get_optimal_solutions(self, max_number=None): <NEW_LINE> <INDENT> return [Individual([0.0] * self.num_variables)] | Schaffer's test problem 6.
This problem is radially symmetric. Thus it does not possess a discrete
set of local optima. It was defined for two dimensions in
[Schaffer1989]_. The global optimum is the origin and the search space
is :math:`[-100, 100] \times [-100, 100]`.
References
----------
.. [Schaffer1989] Schaffer, J. David; Caruana, Richard A.; Eshelman,
Larry J.; Das, Rajarshi (1989). A study of control parameters
affecting online performance of genetic algorithms for function
optimization. In: Proceedings of the third international
conference on genetic algorithms, pp. 51-60, Morgan Kaufmann. | 62598fb7460517430c4320e9 |
class RboInput(TextInput): <NEW_LINE> <INDENT> defaultBackground = [.05, .05, .05, 1] <NEW_LINE> defaultForeground = [1, 1, 1, 1] <NEW_LINE> invalidForeground = [1, 0, 0, 1] <NEW_LINE> defaultHint = [.7, .7, .7, 1] <NEW_LINE> invalidHint = [.5, 0, 0, 1] <NEW_LINE> disabledForeground = [.6, .6, .6, 1] <NEW_LINE> disabledBackground = [.1, .1, .1, 1] <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super().__init__(background_color=RboInput.defaultBackground, foreground_color=RboInput.defaultForeground, hint_text_color=RboInput.defaultHint, **kwargs) <NEW_LINE> <DEDENT> def valid(self) -> bool: <NEW_LINE> <INDENT> return len(self.text) != 0 <NEW_LINE> <DEDENT> def on_is_focusable(self, _: EventDispatcher, focusable: bool): <NEW_LINE> <INDENT> if focusable: <NEW_LINE> <INDENT> self.foreground_color = RboInput.defaultForeground <NEW_LINE> self.background_color = RboInput.defaultBackground <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.foreground_color = RboInput.disabledForeground <NEW_LINE> self.background_color = RboInput.disabledBackground | Zone de saisie dans un formulaire de connexion ou de configuration, conforme au thème de l'appliction. | 62598fb7adb09d7d5dc0a6a5 |
class log_tpool(SolverLog): <NEW_LINE> <INDENT> min_args = 1 <NEW_LINE> def __init__(self, env): <NEW_LINE> <INDENT> from optparse import OptionGroup <NEW_LINE> super(log_tpool, self).__init__(env) <NEW_LINE> op = self.op <NEW_LINE> opg = OptionGroup(op, 'Show Tpool') <NEW_LINE> opg.add_option('-k', action='store', dest='plotkeys', default='', help='Keys to plot.', ) <NEW_LINE> opg.add_option('--lloc', action='store', dest='lloc', default=None, help='Legend location. Default is None (by plot).', ) <NEW_LINE> opg.add_option('--scale', action='store', type=int, dest='scale', default=0.6, help='The scale when having more than one subplot.' ' Default is 0.6.', ) <NEW_LINE> op.add_option_group(opg) <NEW_LINE> self.opg_arrangement = opg <NEW_LINE> <DEDENT> def _init_mpl(self, nplot): <NEW_LINE> <INDENT> import matplotlib <NEW_LINE> ops, args = self.opargs <NEW_LINE> figsize = matplotlib.rcParams['figure.figsize'] <NEW_LINE> top = matplotlib.rcParams['figure.subplot.top'] <NEW_LINE> bottom = matplotlib.rcParams['figure.subplot.bottom'] <NEW_LINE> if nplot > 1: <NEW_LINE> <INDENT> upscale = nplot*ops.scale <NEW_LINE> top = 1.0 - (1.0-top)*(1.0-top)/((1.0-top)*upscale) <NEW_LINE> bottom = bottom*bottom/(bottom*upscale) <NEW_LINE> figsize = figsize[0], figsize[1]*upscale <NEW_LINE> <DEDENT> matplotlib.rcParams.update({ 'backend': ops.backend, 'figure.figsize': figsize, 'figure.subplot.top': top, 'figure.subplot.bottom': bottom, }) <NEW_LINE> matplotlib.use(ops.backend) <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> import os, sys <NEW_LINE> from .anchor import TpoolStatAnchor <NEW_LINE> ops, args = self.opargs <NEW_LINE> plotkeys = ops.plotkeys.split(',') <NEW_LINE> nplot = len(plotkeys) <NEW_LINE> self._init_mpl(nplot) <NEW_LINE> from matplotlib import pyplot as plt <NEW_LINE> datas = self._get_datas() <NEW_LINE> for lines, src, dst in datas: <NEW_LINE> <INDENT> if nplot: <NEW_LINE> <INDENT> fig = plt.figure() <NEW_LINE> <DEDENT> iplot = 1 <NEW_LINE> for key in plotkeys: <NEW_LINE> <INDENT> ax = fig.add_subplot(nplot, 1, iplot) <NEW_LINE> kws = { 'showx': iplot==nplot, } <NEW_LINE> if ops.lloc != None: <NEW_LINE> <INDENT> kws['lloc'] = ops.lloc <NEW_LINE> <DEDENT> TpoolStatAnchor.plot(key, lines, ax, **kws) <NEW_LINE> iplot += 1 <NEW_LINE> <DEDENT> if nplot: <NEW_LINE> <INDENT> sys.stdout.write('%s processed' % src) <NEW_LINE> if dst != None: <NEW_LINE> <INDENT> plt.savefig(dst) <NEW_LINE> sys.stdout.write(' and written to %s.' % dst) <NEW_LINE> <DEDENT> sys.stdout.write('\n') <NEW_LINE> <DEDENT> <DEDENT> if nplot and ops.filename == None: <NEW_LINE> <INDENT> plt.show() | Show output from TpoolStatAnchor. | 62598fb701c39578d7f12e92 |
class TestMain(unittest.TestCase): <NEW_LINE> <INDENT> def test_tp3_example(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.remove("output.txt") <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> main("input.txt", "output.txt") <NEW_LINE> data = open("output.txt").read().split('\n') <NEW_LINE> self.assertEqual(data[0].strip(), 'confidencia 3') <NEW_LINE> self.assertEqual(data[1].strip(), 'fantasias 5') <NEW_LINE> self.assertEqual(data[2].strip(), 'historia 2') <NEW_LINE> self.assertEqual(data[3].strip(), 'ignoro 3') <NEW_LINE> self.assertEqual(data[4].strip(), 'livro 1 3') <NEW_LINE> self.assertEqual(data[5].strip(), 'precederam 1') <NEW_LINE> self.assertEqual(data[6].strip(), 'quadros 1 4 5') <NEW_LINE> self.assertEqual(data[7].strip(), 'sombrear 4') <NEW_LINE> self.assertEqual(data[8].strip(), 'verdadeira 1 2') | Como para um programa feito em memoria eh algo muito simples, apenas um
teste geral eh suficiente. | 62598fb730dc7b766599f965 |
class classy(SlikPlugin): <NEW_LINE> <INDENT> name_mapping = { 'ombh2':'omega_b', 'omch2':'omega_cdm', 'omnuh2':'omega_ncdm', 'tau':'tau_reio', 'H0':'H0', 'massive_neutrinos':'N_ncdm', 'massless_neutrinos':'N_ur', 'Yp':'YHe', 'pivot_scalar':'k_pivot', 'Tcmb':'T_cmb', 'omk':'Omega_k', 'phi0':'custom1', 'm6':'custom2' } <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(classy,self).__init__() <NEW_LINE> try: <NEW_LINE> <INDENT> from classy import Class <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> raise Exception("Failed to import CLASS python wrapper 'Classy'.") <NEW_LINE> <DEDENT> self.model = Class() <NEW_LINE> <DEDENT> def __call__(self, ombh2, omch2, H0, tau, phi0, m6, As = None, ns = None, k_c = None, alpha_exp = None, w=None, r=None, nrun=None, omk=0, Yp=None, Tcmb=2.7255, massless_neutrinos=3.046, l_max_scalar=3000, l_max_tensor=500, pivot_scalar=0.05, outputs=[], **kwargs): <NEW_LINE> <INDENT> d={self.name_mapping[k]:v for k,v in locals().items() if k in self.name_mapping and v is not None} <NEW_LINE> d['P_k_ini type']='external_Pk' <NEW_LINE> self.model.set(output='tCl, lCl, pCl', lensing='yes', l_max_scalars=l_max_scalar, command = '../LSODA/pk', **d) <NEW_LINE> self.model.compute() <NEW_LINE> ell = arange(l_max_scalar+1) <NEW_LINE> self.cmb_result = {'cl_%s'%x:(self.model.lensed_cl(l_max_scalar)[x.lower()])*Tcmb**2*1e12*ell*(ell+1)/2/pi for x in ['TT','TE','EE','BB','PP','TP']} <NEW_LINE> self.model.struct_cleanup() <NEW_LINE> self.model.empty() <NEW_LINE> return self.cmb_result <NEW_LINE> <DEDENT> def get_bao_observables(self, z): <NEW_LINE> <INDENT> return {'H':self.model.Hubble(z), 'D_A':self.model.angular_distance(z), 'c':1.0, 'r_d':(self.model.get_current_derived_parameters(['rs_rec']))['rs_rec']} | Plugin for CLASS.
Credit: Brent Follin, Teresa Hamill, Andy Scacco | 62598fb79c8ee823130401ff |
class WebAPIResponse(HttpResponse): <NEW_LINE> <INDENT> def __init__(self, request, obj={}, stat='ok', api_format="json"): <NEW_LINE> <INDENT> if api_format == "json": <NEW_LINE> <INDENT> if request.FILES: <NEW_LINE> <INDENT> mimetype = "text/plain" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mimetype = "application/json" <NEW_LINE> <DEDENT> <DEDENT> elif api_format == "xml": <NEW_LINE> <INDENT> mimetype = "application/xml" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Http404 <NEW_LINE> <DEDENT> super(WebAPIResponse, self).__init__(mimetype=mimetype) <NEW_LINE> self.callback = request.GET.get('callback', None) <NEW_LINE> self.api_data = {'stat': stat} <NEW_LINE> self.api_data.update(obj) <NEW_LINE> self.api_format = api_format <NEW_LINE> self.content_set = False <NEW_LINE> <DEDENT> def _get_content(self): <NEW_LINE> <INDENT> class MultiEncoder(WebAPIEncoder): <NEW_LINE> <INDENT> def encode(self, o): <NEW_LINE> <INDENT> for encoder in get_registered_encoders(): <NEW_LINE> <INDENT> result = encoder.encode(o) <NEW_LINE> if result is not None: <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> <DEDENT> if not self.content_set: <NEW_LINE> <INDENT> adapter = None <NEW_LINE> encoder = MultiEncoder() <NEW_LINE> if self.api_format == "json": <NEW_LINE> <INDENT> adapter = JSONEncoderAdapter(encoder) <NEW_LINE> <DEDENT> elif self.api_format == "xml": <NEW_LINE> <INDENT> adapter = XMLEncoderAdapter(encoder) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Http404 <NEW_LINE> <DEDENT> content = adapter.encode(self.api_data) <NEW_LINE> if self.callback != None: <NEW_LINE> <INDENT> content = "%s(%s);" % (self.callback, content) <NEW_LINE> <DEDENT> self.content = content <NEW_LINE> self.content_set = True <NEW_LINE> <DEDENT> return super(WebAPIResponse, self)._get_content() <NEW_LINE> <DEDENT> def _set_content(self, value): <NEW_LINE> <INDENT> super(WebAPIResponse, self)._set_content(value) <NEW_LINE> <DEDENT> content = property(_get_content, _set_content) | An API response, formatted for the desired file format. | 62598fb77cff6e4e811b5b38 |
class CampusAdmin(admin.OSMGeoAdmin): <NEW_LINE> <INDENT> openlayers_url = '/static/feti/js/libs/OpenLayers-2.13.1/OpenLayers.js' <NEW_LINE> inlines = [AddressAdminInline] <NEW_LINE> list_display = ('id', 'campus', 'primary_institution', '_complete',) <NEW_LINE> list_filter = ['provider__primary_institution', '_complete'] <NEW_LINE> search_fields = ['campus', 'provider__primary_institution'] <NEW_LINE> readonly_fields = ['provider_url'] <NEW_LINE> fieldsets = ( ('General Information', { 'fields': ('provider_url', 'campus', 'location', 'courses') }), ) <NEW_LINE> exclude = ('_long_description', '_complete', '_campus_popup', 'address', 'provider') <NEW_LINE> filter_horizontal = ['courses'] <NEW_LINE> related_lookup_fields = { 'fk': ['provider'], 'm2m': ['courses'] } <NEW_LINE> def has_add_permission(self, request): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def provider_url(self, instance): <NEW_LINE> <INDENT> return mark_safe('{}<br/><a href="{}">Go to edit page</a>').format( instance.provider, reverse('admin:feti_provider_change', args=( instance.provider.id,)), ) <NEW_LINE> <DEDENT> provider_url.allow_tags = True <NEW_LINE> provider_url.short_description = 'Primary institute url' | Admin Class for Campus Model. | 62598fb72c8b7c6e89bd38dd |
class CommonEqualityMixin(object): <NEW_LINE> <INDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return (isinstance(other, self.__class__) and self.__dict__ == other.__dict__) <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self.__eq__(other) | Enable subclasses of this class to do equality comparison.
Code taken from http://stackoverflow.com/questions/390250/elegant-ways-to-support-equivalence-equality-in-python-classes | 62598fb797e22403b383b01e |
class ButtonOne(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "scene.dostuff" <NEW_LINE> bl_label = "Calc Length" <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> get_length(context) <NEW_LINE> return{'FINISHED'} | Defines a button | 62598fb766673b3332c304e7 |
class Intangible(Thing): <NEW_LINE> <INDENT> _validation = { '_type': {'required': True}, 'id': {'readonly': True}, 'read_link': {'readonly': True}, 'web_search_url': {'readonly': True}, 'name': {'readonly': True}, 'url': {'readonly': True}, 'image': {'readonly': True}, 'description': {'readonly': True}, 'alternate_name': {'readonly': True}, 'bing_id': {'readonly': True}, } <NEW_LINE> _attribute_map = { '_type': {'key': '_type', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'read_link': {'key': 'readLink', 'type': 'str'}, 'web_search_url': {'key': 'webSearchUrl', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'}, 'image': {'key': 'image', 'type': 'ImageObject'}, 'description': {'key': 'description', 'type': 'str'}, 'alternate_name': {'key': 'alternateName', 'type': 'str'}, 'bing_id': {'key': 'bingId', 'type': 'str'}, } <NEW_LINE> _subtype_map = { '_type': {'StructuredValue': 'StructuredValue'} } <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(Intangible, self).__init__(**kwargs) <NEW_LINE> self._type = 'Intangible' | A utility class that serves as the umbrella for a number of 'intangible'
things such as quantities, structured values, etc.
You probably want to use the sub-classes and not this class directly. Known
sub-classes are: StructuredValue
Variables are only populated by the server, and will be ignored when
sending a request.
All required parameters must be populated in order to send to Azure.
:param _type: Required. Constant filled by server.
:type _type: str
:ivar id: A String identifier.
:vartype id: str
:ivar read_link: The URL that returns this resource. To use the URL,
append query parameters as appropriate and include the
Ocp-Apim-Subscription-Key header.
:vartype read_link: str
:ivar web_search_url: The URL to Bing's search result for this item.
:vartype web_search_url: str
:ivar name: The name of the thing represented by this object.
:vartype name: str
:ivar url: The URL to get more information about the thing represented by
this object.
:vartype url: str
:ivar image: An image of the item.
:vartype image:
~azure.cognitiveservices.search.visualsearch.models.ImageObject
:ivar description: A short description of the item.
:vartype description: str
:ivar alternate_name: An alias for the item.
:vartype alternate_name: str
:ivar bing_id: An ID that uniquely identifies this item.
:vartype bing_id: str | 62598fb7009cb60464d0163b |
class ThreatsProperties(GroupsProperties): <NEW_LINE> <INDENT> def __init__(self, base_uri='v2', http_method=PropertiesAction.GET): <NEW_LINE> <INDENT> super(ThreatsProperties, self).__init__(base_uri, http_method) <NEW_LINE> self._resource_key = 'threat' <NEW_LINE> self._resource_pagination = True <NEW_LINE> self._resource_type = ResourceType.THREATS <NEW_LINE> self._resource_uri_attribute += '/threats' <NEW_LINE> self._object_attributes.remove(ResourceMethods.type_attr) <NEW_LINE> self._filter_methods.remove('add_threat_id') <NEW_LINE> self._filter_methods.append('add_id') | URIs:
/<api version>/groups/threats
/<api version>/indicators/<indicator type>/<value>/groups/threats
/<api version>/groups/adversaries/<ID>/groups/threats
/<api version>/groups/emails/<ID>/groups/threats
/<api version>/groups/incidents/<ID>/groups/threats
/<api version>/groups/signatures/<ID>/groups/threats
/<api version>/securityLabels/<security label>/groups/threats
/<api version>/tags/<tag name>/groups/threats
/<api version>/victims/<ID>/groups/threats
JSON Data:
{"id" : 63359,
"name" : "2104-03-05:Threat",
"ownerName" : "Acme Corp",
"dateAdded" : "2014-03-05T13:19:57Z",
"webLink" : "https://app.threatconnect.com/tc/auth/threat/
threat.xhtml?threat=63359"} | 62598fb7167d2b6e312b708c |
class List(Container): <NEW_LINE> <INDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'List({!r})'.format(self._data) <NEW_LINE> <DEDENT> def _load_from_mongo(self, data): <NEW_LINE> <INDENT> self._data = [] <NEW_LINE> for item in data: <NEW_LINE> <INDENT> if hasattr(self._field.item_field, 'from_mongo'): <NEW_LINE> <INDENT> value = self._field.item_field.from_mongo(self.__parent__, item) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> value = self._prepare_value(item) <NEW_LINE> <DEDENT> self._data.append(value) <NEW_LINE> <DEDENT> <DEDENT> def append(self, item): <NEW_LINE> <INDENT> self._data.append(self._prepare_value(item)) <NEW_LINE> self._set_changed() <NEW_LINE> <DEDENT> def remove(self, item): <NEW_LINE> <INDENT> self._data.remove(item) <NEW_LINE> self._set_changed() <NEW_LINE> <DEDENT> def push(self, item): <NEW_LINE> <INDENT> item = self._prepare_value(item) <NEW_LINE> if hasattr(self._field.item_field, 'to_mongo'): <NEW_LINE> <INDENT> data = self._field.item_field.to_mongo(self.__document__, item) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data = item <NEW_LINE> <DEDENT> qs = self._get_queryset() <NEW_LINE> qs.update({'$push': {self.__field_name__: data}}, multi=False) <NEW_LINE> self._data.append(item) <NEW_LINE> <DEDENT> def pull(self, query, reload=True): <NEW_LINE> <INDENT> qs = self._get_queryset() <NEW_LINE> qs.update({'$pull': {self.__field_name__: query}}, multi=False) <NEW_LINE> if reload: <NEW_LINE> <INDENT> doc = qs.find_one() <NEW_LINE> self._load_from_mongo(self.__get_value__(doc)) | Container for list
| 62598fb760cbc95b06364457 |
class InboundShipmentResponse(__BaseDictObject): <NEW_LINE> <INDENT> def __init__(self, data): <NEW_LINE> <INDENT> super().__init__(data) <NEW_LINE> if "payload" in data: <NEW_LINE> <INDENT> self.payload: InboundShipmentResult = self._get_value(InboundShipmentResult, "payload") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.payload: InboundShipmentResult = None <NEW_LINE> <DEDENT> if "errors" in data: <NEW_LINE> <INDENT> self.errors: ErrorList = self._get_value(ErrorList, "errors") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.errors: ErrorList = None | The response schema for this operation. | 62598fb7fff4ab517ebcd900 |
class ViewTestCase(TestCase): <NEW_LINE> <INDENT> fixtures = ["sodes_tests.json"] <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> self.sode = Sode.objects.get(pk=1) <NEW_LINE> self.client = Client() <NEW_LINE> self.test_user = User.objects.get(pk=1) <NEW_LINE> <DEDENT> def test_superuser_view_unpublished(self): <NEW_LINE> <INDENT> self.sode.date = datetime.now() + timedelta(days=1) <NEW_LINE> self.sode.save() <NEW_LINE> self.client.login(username=self.test_user.username, password="asdf") <NEW_LINE> resp = self.client.get(self.sode.get_absolute_url()) <NEW_LINE> self.assertEquals(resp.status_code, 200) <NEW_LINE> self.test_user.is_superuser = False <NEW_LINE> self.test_user.save() <NEW_LINE> resp = self.client.get(self.sode.get_absolute_url()) <NEW_LINE> self.assertEquals(resp.status_code, 404) | Test things in the views | 62598fb757b8e32f525081a9 |
class PublicIPAddressListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[PublicIPAddress]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(PublicIPAddressListResult, self).__init__(**kwargs) <NEW_LINE> self.value = kwargs.get('value', None) <NEW_LINE> self.next_link = kwargs.get('next_link', None) | Response for ListPublicIpAddresses API service call.
:param value: A list of public IP addresses that exists in a resource group.
:type value: list[~azure.mgmt.network.v2018_08_01.models.PublicIPAddress]
:param next_link: The URL to get the next set of results.
:type next_link: str | 62598fb74428ac0f6e65863b |
class RegistrationForm(forms.Form): <NEW_LINE> <INDENT> username = forms.RegexField(regex=r'^\w+$', max_length=30, widget=forms.TextInput(attrs=attrs_dict), label=_("Username"), error_messages={'invalid': _("This value must contain only letters, numbers and underscores.")}) <NEW_LINE> email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=75)), label=_("Email address")) <NEW_LINE> password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), label=_("Password")) <NEW_LINE> def clean_username(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user = User.objects.get(username__iexact=self.cleaned_data['username']) <NEW_LINE> <DEDENT> except User.DoesNotExist: <NEW_LINE> <INDENT> return self.cleaned_data['username'] <NEW_LINE> <DEDENT> raise forms.ValidationError(_("A user with that username already exists.")) <NEW_LINE> <DEDENT> def clean(self): <NEW_LINE> <INDENT> return self.cleaned_data | Form for registering a new user account.
Validates that the requested username is not already in use, and
requires the password to be entered twice to catch typos.
Subclasses should feel free to add any additional validation they
need, but should avoid defining a ``save()`` method -- the actual
saving of collected user data is delegated to the active
registration backend. | 62598fb74f88993c371f0599 |
class PipeInput(Input): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._r, self._w = os.pipe() <NEW_LINE> <DEDENT> def fileno(self): <NEW_LINE> <INDENT> return self._r <NEW_LINE> <DEDENT> def read(self): <NEW_LINE> <INDENT> return os.read(self._r) <NEW_LINE> <DEDENT> def send_text(self, data): <NEW_LINE> <INDENT> os.write(self._w, data.encode('utf-8')) <NEW_LINE> <DEDENT> send = send_text <NEW_LINE> def raw_mode(self): <NEW_LINE> <INDENT> return DummyContext() <NEW_LINE> <DEDENT> def cooked_mode(self): <NEW_LINE> <INDENT> return DummyContext() <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> os.close(self._r) <NEW_LINE> os.close(self._w) <NEW_LINE> self._r = None <NEW_LINE> self._w = None | Input that is send through a pipe.
This is useful if we want to send the input programatically into the
interface, but still use the eventloop.
Usage::
input = PipeInput()
input.send('inputdata') | 62598fb74a966d76dd5eeff1 |
class ModelTests(TestCase): <NEW_LINE> <INDENT> def test_create_user_with_email_successful(self): <NEW_LINE> <INDENT> payload = {'email': 'pudgeinvonyx@gmail.com', 'password': '1111qqqq='} <NEW_LINE> user = get_user_model().objects.create_user( email=payload['email'], password=payload['password'] ) <NEW_LINE> self.assertEqual(user.email, payload['email']) <NEW_LINE> self.assertTrue(user.check_password(payload['password'])) <NEW_LINE> <DEDENT> def test_create_user_with_lowercase_email(self): <NEW_LINE> <INDENT> payload = {'email': 'pudgeinvonyx@GMAIL.com', 'password': '1111qqqq='} <NEW_LINE> user = get_user_model().objects.create_user( email=payload['email'], password=payload['password'] ) <NEW_LINE> self.assertEqual(user.email, payload['email'].lower()) <NEW_LINE> <DEDENT> def test_create_user_with_invalid_email(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> get_user_model().objects.create_user(None, "1234325") <NEW_LINE> <DEDENT> <DEDENT> def test_create_superuser_is_successful(self): <NEW_LINE> <INDENT> user = get_user_model().objects.create_superuser("pudge@com.com", '1234') <NEW_LINE> self.assertTrue(user.is_superuser) <NEW_LINE> self.assertTrue(user.is_staff) | Test creating a new user with an email is successful | 62598fb78a349b6b43686355 |
class ApplicationGatewayPrivateEndpointConnection(SubResource): <NEW_LINE> <INDENT> _validation = { 'etag': {'readonly': True}, 'type': {'readonly': True}, 'private_endpoint': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'link_identifier': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'private_endpoint': {'key': 'properties.privateEndpoint', 'type': 'PrivateEndpoint'}, 'private_link_service_connection_state': {'key': 'properties.privateLinkServiceConnectionState', 'type': 'PrivateLinkServiceConnectionState'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'link_identifier': {'key': 'properties.linkIdentifier', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(ApplicationGatewayPrivateEndpointConnection, self).__init__(**kwargs) <NEW_LINE> self.name = kwargs.get('name', None) <NEW_LINE> self.etag = None <NEW_LINE> self.type = None <NEW_LINE> self.private_endpoint = None <NEW_LINE> self.private_link_service_connection_state = kwargs.get('private_link_service_connection_state', None) <NEW_LINE> self.provisioning_state = None <NEW_LINE> self.link_identifier = None | Private Endpoint connection on an application gateway.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of the private endpoint connection on an application gateway.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:ivar private_endpoint: The resource of private end point.
:vartype private_endpoint: ~azure.mgmt.network.v2020_06_01.models.PrivateEndpoint
:param private_link_service_connection_state: A collection of information about the state of
the connection between service consumer and provider.
:type private_link_service_connection_state:
~azure.mgmt.network.v2020_06_01.models.PrivateLinkServiceConnectionState
:ivar provisioning_state: The provisioning state of the application gateway private endpoint
connection resource. Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_06_01.models.ProvisioningState
:ivar link_identifier: The consumer link id.
:vartype link_identifier: str | 62598fb7f548e778e596b6be |
class Myo(RapidAPI): <NEW_LINE> <INDENT> battery_level = Read(BATTERY_CHRC) <NEW_LINE> vibrate = Write(CONTROL_SERVICE, accept=[VIB_STRONG]) <NEW_LINE> set_mode = Write(CONTROL_SERVICE, accept=[EMG_MODE]) <NEW_LINE> subscribe_to_emg = Notify(ALL_EMG_CHRCS) | Myo armband API | 62598fb7236d856c2adc94cc |
class BrazilSerraCityTest(BrazilEspiritoSantoTest): <NEW_LINE> <INDENT> cal_class = BrazilSerraCity <NEW_LINE> test_include_immaculate_conception = True <NEW_LINE> def test_year_2017_city(self): <NEW_LINE> <INDENT> holidays = self.cal.holidays_set(2017) <NEW_LINE> self.assertIn(date(2017, 6, 29), holidays) <NEW_LINE> self.assertIn(date(2017, 12, 8), holidays) <NEW_LINE> self.assertIn(date(2017, 12, 26), holidays) <NEW_LINE> self.assertIn(date(2017, 2, 27), holidays) <NEW_LINE> self.assertIn(date(2017, 2, 28), holidays) <NEW_LINE> ash_wednesday = date(2017, 3, 1) <NEW_LINE> self.assertIn(ash_wednesday, holidays) <NEW_LINE> self.assertEqual( self.cal.get_holiday_label(ash_wednesday), "Quarta-feira de cinzas", ) <NEW_LINE> good_friday = date(2017, 4, 14) <NEW_LINE> self.assertIn(good_friday, holidays) <NEW_LINE> self.assertEqual( self.cal.get_holiday_label(good_friday), "Paixão do Cristo", ) <NEW_LINE> <DEDENT> def test_carnaval_label(self): <NEW_LINE> <INDENT> holidays = self.cal.holidays(2017) <NEW_LINE> holidays_dict = dict(holidays) <NEW_LINE> label_carnaval = holidays_dict[date(2017, 2, 28)] <NEW_LINE> self.assertEqual(label_carnaval, "Carnaval") | Serra city is in the Espírito Santo state | 62598fb755399d3f0562662f |
class Singleton(type): <NEW_LINE> <INDENT> def __init__(cls, name, bases, dct): <NEW_LINE> <INDENT> cls.__instance = None <NEW_LINE> type.__init__(cls, name, bases, dct) <NEW_LINE> <DEDENT> def __call__(cls, *args, **kw): <NEW_LINE> <INDENT> if cls.__instance is None: <NEW_LINE> <INDENT> cls.__instance = type.__call__(cls, *args,**kw) <NEW_LINE> <DEDENT> return cls.__instance | Singleton metaclass. | 62598fb75fcc89381b2661d9 |
class Meta: <NEW_LINE> <INDENT> database = DB <NEW_LINE> table_name = 'proposals' <NEW_LINE> legacy_table_names = False | This is the meta class for OldTrans. | 62598fb73317a56b869be5da |
class ConfigurationForm(forms.Form): <NEW_LINE> <INDENT> name = forms.CharField( label=ugettext(u'Name'), ) <NEW_LINE> configuration_type = forms.ModelChoiceField( label=ugettext(u'Configuration type'), queryset=ConfigurationType.objects.all(), empty_label=None, ) <NEW_LINE> value_type = forms.ModelChoiceField( label=ugettext(u'Value type'), queryset=ValueType.objects.all(), empty_label=None, ) <NEW_LINE> parent = forms.ModelChoiceField( label=ugettext(u'Parent configuration'), queryset=Configuration.objects.all(), required=False, ) | Form for editing of annotations. | 62598fb797e22403b383b01f |
class Cc(Email): <NEW_LINE> <INDENT> pass | A cc email address with an optional name. | 62598fb7283ffb24f3cf39a1 |
class BBBLeNet(nn.Module): <NEW_LINE> <INDENT> def __init__(self, outputs, inputs): <NEW_LINE> <INDENT> super(BBBLeNet, self).__init__() <NEW_LINE> self.conv1 = BBBConv2d(inputs,6, 5, stride=1) <NEW_LINE> self.soft1 = nn.Softplus() <NEW_LINE> self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2) <NEW_LINE> self.conv2 = BBBConv2d(6, 16, 5, stride=1) <NEW_LINE> self.soft2 = nn.Softplus() <NEW_LINE> self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2) <NEW_LINE> self.flatten = FlattenLayer(5 * 5 * 16) <NEW_LINE> self.fc1 = BBBLinearFactorial(5 * 5 * 16, 120) <NEW_LINE> self.soft3 = nn.Softplus() <NEW_LINE> self.fc2 = BBBLinearFactorial(120, 84) <NEW_LINE> self.soft4 = nn.Softplus() <NEW_LINE> self.fc3 = BBBLinearFactorial(84, outputs) <NEW_LINE> layers = [self.conv1, self.soft1, self.pool1, self.conv2, self.soft2, self.pool2, self.flatten, self.fc1, self.soft3, self.fc2, self.soft4, self.fc3] <NEW_LINE> self.layers = nn.ModuleList(layers) <NEW_LINE> <DEDENT> def probforward(self, x): <NEW_LINE> <INDENT> kl = 0 <NEW_LINE> for layer in self.layers: <NEW_LINE> <INDENT> if hasattr(layer, 'convprobforward') and callable(layer.convprobforward): <NEW_LINE> <INDENT> x, _kl, = layer.convprobforward(x) <NEW_LINE> kl += _kl <NEW_LINE> <DEDENT> elif hasattr(layer, 'fcprobforward') and callable(layer.fcprobforward): <NEW_LINE> <INDENT> x, _kl, = layer.fcprobforward(x) <NEW_LINE> kl += _kl <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x = layer(x) <NEW_LINE> <DEDENT> <DEDENT> logits = x <NEW_LINE> return logits, kl | The architecture of LeNet with Bayesian Layers | 62598fb763d6d428bbee28c8 |
class County(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=300) <NEW_LINE> slug = models.SlugField(null=True) <NEW_LINE> state = models.ForeignKey('State', null=True) <NEW_LINE> state_fips_code = models.CharField(max_length=2) <NEW_LINE> county_fips_code = models.CharField(max_length=3) <NEW_LINE> fips_code = models.CharField(max_length=5) <NEW_LINE> polygon_4269 = models.MultiPolygonField(srid=4269) <NEW_LINE> simple_polygon_4269 = models.MultiPolygonField(srid=4269, null=True, blank=True) <NEW_LINE> polygon_900913 = models.MultiPolygonField(srid=900913, null=True, blank=True) <NEW_LINE> simple_polygon_900913 = models.MultiPolygonField(srid=900913, null=True, blank=True) <NEW_LINE> created = models.DateTimeField(auto_now_add=True) <NEW_LINE> last_changed = models.DateTimeField(auto_now=True) <NEW_LINE> objects = models.GeoManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ('name',) <NEW_LINE> verbose_name_plural = 'Counties' <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def set_simple_polygons(self, tolerance=200): <NEW_LINE> <INDENT> from django.contrib.gis.gdal import OGRGeometry, OGRGeomType <NEW_LINE> srid_list = [4269, 900913] <NEW_LINE> for srid in srid_list: <NEW_LINE> <INDENT> source_field_name = 'polygon_%s' % str(srid) <NEW_LINE> source = getattr(self, source_field_name) <NEW_LINE> target_field_name = 'simple_%s' % source_field_name <NEW_LINE> target = getattr(self, target_field_name) <NEW_LINE> copy = source.transform(900913, clone=True) <NEW_LINE> simple = copy.simplify(tolerance, True) <NEW_LINE> if simple.geom_type == 'Polygon': <NEW_LINE> <INDENT> mp = OGRGeometry(OGRGeomType('MultiPolygon')) <NEW_LINE> simple.transform(srid) <NEW_LINE> mp.add(simple.wkt) <NEW_LINE> target = mp.wkt <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> simple.transform(srid) <NEW_LINE> target = simple.wkt <NEW_LINE> <DEDENT> setattr(self, target_field_name, target) <NEW_LINE> <DEDENT> self.save() <NEW_LINE> return True | An administrative unit created by one of our fine state governments. | 62598fb7cc40096d6161a266 |
class PKCS115_Cipher: <NEW_LINE> <INDENT> def __init__(self, key, randfunc): <NEW_LINE> <INDENT> self._key = key <NEW_LINE> self._randfunc = randfunc <NEW_LINE> <DEDENT> def can_encrypt(self): <NEW_LINE> <INDENT> return self._key.can_encrypt() <NEW_LINE> <DEDENT> def can_decrypt(self): <NEW_LINE> <INDENT> return self._key.can_decrypt() <NEW_LINE> <DEDENT> def encrypt(self, message): <NEW_LINE> <INDENT> modBits = Cryptodome.Util.number.size(self._key.n) <NEW_LINE> k = ceil_div(modBits,8) <NEW_LINE> mLen = len(message) <NEW_LINE> if mLen > k-11: <NEW_LINE> <INDENT> raise ValueError("Plaintext is too long.") <NEW_LINE> <DEDENT> ps = [] <NEW_LINE> while len(ps) != k - mLen - 3: <NEW_LINE> <INDENT> new_byte = self._randfunc(1) <NEW_LINE> if bord(new_byte[0]) == 0x00: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> ps.append(new_byte) <NEW_LINE> <DEDENT> ps = b("").join(ps) <NEW_LINE> assert(len(ps) == k - mLen - 3) <NEW_LINE> em = b('\x00\x02') + ps + bchr(0x00) + message <NEW_LINE> em_int = bytes_to_long(em) <NEW_LINE> m_int = self._key._encrypt(em_int) <NEW_LINE> c = long_to_bytes(m_int, k) <NEW_LINE> return c <NEW_LINE> <DEDENT> def decrypt(self, ciphertext, sentinel): <NEW_LINE> <INDENT> modBits = Cryptodome.Util.number.size(self._key.n) <NEW_LINE> k = ceil_div(modBits,8) <NEW_LINE> if len(ciphertext) != k: <NEW_LINE> <INDENT> raise ValueError("Ciphertext with incorrect length.") <NEW_LINE> <DEDENT> ct_int = bytes_to_long(ciphertext) <NEW_LINE> m_int = self._key._decrypt(ct_int) <NEW_LINE> em = long_to_bytes(m_int, k) <NEW_LINE> sep = em.find(bchr(0x00),2) <NEW_LINE> if not em.startswith(b('\x00\x02')) or sep<10: <NEW_LINE> <INDENT> return sentinel <NEW_LINE> <DEDENT> return em[sep+1:] | This cipher can perform PKCS#1 v1.5 RSA encryption or decryption.
Do not instantiate directly. Use :func:`Cryptodome.Cipher.PKCS1_v1_5.new` instead. | 62598fb7bd1bec0571e1514f |
class IArticle(ArticleSchema, IBaseArticle, IImageScaleTraversable): <NEW_LINE> <INDENT> pass | Interface for content type: collective.cart.core.Article | 62598fb797e22403b383b020 |
class getStruct_result: <NEW_LINE> <INDENT> thrift_spec = ( (0, TType.STRUCT, 'success', (SharedStruct, SharedStruct.thrift_spec), None, ), ) <NEW_LINE> def __init__(self, success=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.success = SharedStruct() <NEW_LINE> self.success.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('getStruct_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.STRUCT, 0) <NEW_LINE> self.success.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- success | 62598fb792d797404e388bf0 |
class VtOrderReq(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.symbol = EMPTY_STRING <NEW_LINE> self.exchange = EMPTY_STRING <NEW_LINE> self.vtSymbol = EMPTY_STRING <NEW_LINE> self.price = EMPTY_FLOAT <NEW_LINE> self.volume = EMPTY_INT <NEW_LINE> self.priceType = EMPTY_STRING <NEW_LINE> self.direction = EMPTY_STRING <NEW_LINE> self.offset = EMPTY_STRING <NEW_LINE> self.productClass = EMPTY_UNICODE <NEW_LINE> self.currency = EMPTY_STRING <NEW_LINE> self.expiry = EMPTY_STRING <NEW_LINE> self.strikePrice = EMPTY_FLOAT <NEW_LINE> self.optionType = EMPTY_UNICODE <NEW_LINE> self.lastTradeDateOrContractMonth = EMPTY_STRING <NEW_LINE> self.multiplier = EMPTY_STRING <NEW_LINE> self.contracttype = EMPTY_STRING <NEW_LINE> self.type = EMPTY_INT <NEW_LINE> self.matchprice = EMPTY_STRING <NEW_LINE> self.leverrate = EMPTY_STRING | 发单时传入的对象类 | 62598fb710dbd63aa1c70cd2 |
class enumValue2Type(asn1.Enumerated): <NEW_LINE> <INDENT> class Value(asn1.Enumerated.Value): <NEW_LINE> <INDENT> NONE = None <NEW_LINE> truism = 0 <NEW_LINE> falsism = 1 <NEW_LINE> <DEDENT> __simple__ = Value <NEW_LINE> def init_value(self): <NEW_LINE> <INDENT> return self.Value.truism <NEW_LINE> <DEDENT> REQUIRED_BYTES_FOR_ENCODING = 1 <NEW_LINE> REQUIRED_BITS_FOR_ENCODING = 1 <NEW_LINE> def uper_encode(self, bit_stream): <NEW_LINE> <INDENT> if self._value == self.Value.truism: <NEW_LINE> <INDENT> bit_stream.encode_constraint_number(0, 0, 1) <NEW_LINE> <DEDENT> elif self._value == self.Value.falsism: <NEW_LINE> <INDENT> bit_stream.encode_constraint_number(1, 0, 1) <NEW_LINE> <DEDENT> <DEDENT> def uper_decode(self, bit_stream): <NEW_LINE> <INDENT> enum_index = bit_stream.decode_constraint_number(0, 1) <NEW_LINE> if enum_index == 0: <NEW_LINE> <INDENT> value = self.Value.truism <NEW_LINE> <DEDENT> elif enum_index == 1: <NEW_LINE> <INDENT> value = self.Value.falsism <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise asn1.UnexpectedOptionIndex(type(self), enum_index) <NEW_LINE> <DEDENT> self.set(value) | Derived from Enumerated | 62598fb7d486a94d0ba2c0e7 |
class RMLightSource(lightsource.LightSource): <NEW_LINE> <INDENT> protocols.advise(instancesProvide=[ISceneItem, ribexport.ILightSource]) <NEW_LINE> def __init__(self, name = "RMLightSource", shader = None, **params): <NEW_LINE> <INDENT> lightsource.LightSource.__init__(self, name=name, **params) <NEW_LINE> if isinstance(shader, str): <NEW_LINE> <INDENT> shader = RMShader(shader) <NEW_LINE> <DEDENT> self.shader = shader <NEW_LINE> if self.shader==None: <NEW_LINE> <INDENT> self.shader = RMShader() <NEW_LINE> <DEDENT> <DEDENT> def protocols(self): <NEW_LINE> <INDENT> return [ISceneItem, ribexport.ILightSource] <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> if name[-5:]=="_slot": <NEW_LINE> <INDENT> slotname = name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> slotname = "%s_slot"%name <NEW_LINE> <DEDENT> if hasattr(self.shader, slotname): <NEW_LINE> <INDENT> return getattr(self.shader, name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise AttributeError('light source "%s" has no attribute "%s"'%(self.name, name)) <NEW_LINE> <DEDENT> <DEDENT> def __setattr__(self, name, val): <NEW_LINE> <INDENT> slotname = "%s_slot"%name <NEW_LINE> shd = self.__dict__.get("shader", None) <NEW_LINE> if hasattr(shd, slotname): <NEW_LINE> <INDENT> setattr(srf, name, val) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> material.Material.__setattr__(self, name, val) <NEW_LINE> <DEDENT> <DEDENT> def createPasses(self): <NEW_LINE> <INDENT> return self.shader.getPasses() <NEW_LINE> <DEDENT> def shaderName(self): <NEW_LINE> <INDENT> return self.shader.shaderName() <NEW_LINE> <DEDENT> def shaderSource(self): <NEW_LINE> <INDENT> return self.shader.loadShaderSource() <NEW_LINE> <DEDENT> def shaderParams(self, passes): <NEW_LINE> <INDENT> return self.shader.params(passes) | RenderMan light source.
Use this light source class if you want to write the RenderMan light shader
yourself in an external source file or if you want to use an external
shader that you will compile manually.
The shader source file (or only the shader name) is passed via a
RMShader instances as argument to the constructor. If the RMShader
instance points to a file, the light source will take care of the
compilation of the file. Otherwise, it is up to you to compile the
shader and make sure that the renderer can find it.
The parameters of the shader are made available as attributes of
the light source object. The corresponding slots can be obtained
by adding the suffix \c _slot to the name.
\see RMShader | 62598fb7167d2b6e312b708e |
class MGTank(Tank): <NEW_LINE> <INDENT> name = "MGTank" <NEW_LINE> def FireGun(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> trigger = self.triggerIterator.next() <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> self.triggerIterator = iter(self.triggers) <NEW_LINE> trigger = self.triggerIterator.next() <NEW_LINE> <DEDENT> self.Input(trigger, 0, 1) | Machinegun Tank | 62598fb7796e427e5384e8af |
class ValueIterationAgent(ValueEstimationAgent): <NEW_LINE> <INDENT> def __init__(self, mdp, discount = 0.9, iterations = 100): <NEW_LINE> <INDENT> self.mdp = mdp <NEW_LINE> self.discount = discount <NEW_LINE> self.iterations = iterations <NEW_LINE> self.values = util.Counter() <NEW_LINE> "*** YOUR CODE HERE ***" <NEW_LINE> times = self.iterations <NEW_LINE> states = self.mdp.getStates() <NEW_LINE> while (times != 0): <NEW_LINE> <INDENT> V = util.Counter() <NEW_LINE> for state in states: <NEW_LINE> <INDENT> if not self.mdp.isTerminal(state): <NEW_LINE> <INDENT> optimal = -sys.maxint <NEW_LINE> actions = self.mdp.getPossibleActions(state) <NEW_LINE> for action in actions: <NEW_LINE> <INDENT> totalValue = 0 <NEW_LINE> stateProPairs = self.mdp.getTransitionStatesAndProbs(state,action) <NEW_LINE> for stateProPair in stateProPairs: <NEW_LINE> <INDENT> rVknextstate = self.discount * self.values[stateProPair[0]] <NEW_LINE> reward = self.mdp.getReward(state,action,stateProPair[0]) <NEW_LINE> totalValue += stateProPair[1] * (reward + rVknextstate) <NEW_LINE> <DEDENT> optimal = max(totalValue, optimal) <NEW_LINE> V[state] = optimal <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> V[state] = 0 <NEW_LINE> <DEDENT> <DEDENT> times -= 1 <NEW_LINE> self.values = V <NEW_LINE> <DEDENT> <DEDENT> def getValue(self, state): <NEW_LINE> <INDENT> return self.values[state] <NEW_LINE> <DEDENT> def computeQValueFromValues(self, state, action): <NEW_LINE> <INDENT> totalValue = 0 <NEW_LINE> stateProbPairs = self.mdp.getTransitionStatesAndProbs(state,action) <NEW_LINE> for stateProbPair in stateProbPairs: <NEW_LINE> <INDENT> rVknextstate = self.discount * self.values[stateProbPair[0]] <NEW_LINE> reward = self.mdp.getReward(state,action,stateProbPair[0]) <NEW_LINE> totalValue += stateProbPair[1] * ( reward + rVknextstate) <NEW_LINE> <DEDENT> return totalValue <NEW_LINE> <DEDENT> def computeActionFromValues(self, state): <NEW_LINE> <INDENT> while self.mdp.isTerminal(state): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> Actions = self.mdp.getPossibleActions(state) <NEW_LINE> valuesForActions = util.Counter() <NEW_LINE> decision = "north" <NEW_LINE> optimalV = -sys.maxint <NEW_LINE> actionQ = {} <NEW_LINE> for action in Actions: <NEW_LINE> <INDENT> qV = self.computeQValueFromValues(state, action) <NEW_LINE> actionQ [action] = qV <NEW_LINE> <DEDENT> decision =max(actionQ.items(), key=lambda x: x[1])[0] <NEW_LINE> return decision <NEW_LINE> <DEDENT> def getPolicy(self, state): <NEW_LINE> <INDENT> return self.computeActionFromValues(state) <NEW_LINE> <DEDENT> def getAction(self, state): <NEW_LINE> <INDENT> return self.computeActionFromValues(state) <NEW_LINE> <DEDENT> def getQValue(self, state, action): <NEW_LINE> <INDENT> return self.computeQValueFromValues(state, action) | * Please read learningAgents.py before reading this.*
A ValueIterationAgent takes a Markov decision process
(see mdp.py) on initialization and runs value iteration
for a given number of iterations using the supplied
discount factor. | 62598fb7fff4ab517ebcd902 |
class ShelfComments(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'shelf_comments' <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> user_id = db.Column(db.Integer, db.ForeignKey('user.id')) <NEW_LINE> shelf_id = db.Column(db.Integer, db.ForeignKey('shelf.id')) <NEW_LINE> content = db.Column(db.Text) <NEW_LINE> timestamp = db.Column(db.Integer, default=int(time())) <NEW_LINE> shelf = db.relationship('Shelf', backref=db.backref('comments', cascade='all, delete-orphan')) <NEW_LINE> user = db.relationship('User', backref=db.backref('shelf_comments', cascade='all, delete-orphan')) <NEW_LINE> def __init__(self, content, user, shelf=None): <NEW_LINE> <INDENT> self.content = content <NEW_LINE> self.user = user <NEW_LINE> self.shelf = shelf <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> db.session.add(self) <NEW_LINE> db.session.commit() | 书架留言 | 62598fb7aad79263cf42e8ee |
class Watershed(Simple): <NEW_LINE> <INDENT> title = 'Binary Watershed 3D' <NEW_LINE> note = ['8-bit', 'stack3d'] <NEW_LINE> para = {'tor':2, 'con':False} <NEW_LINE> view = [(int, 'tor', (0,255), 0, 'tolerance', 'value'), (bool, 'con', 'full connectivity')] <NEW_LINE> def run(self, ips, imgs, para = None): <NEW_LINE> <INDENT> imgs[:] = imgs > 0 <NEW_LINE> dist = -ndimg.distance_transform_edt(imgs) <NEW_LINE> pts = find_maximum(dist, para['tor'], False) <NEW_LINE> buf = np.zeros(imgs.shape, dtype=np.uint32) <NEW_LINE> buf[pts[:,0], pts[:,1], pts[:,2]] = 2 <NEW_LINE> imgs[pts[:,0], pts[:,1], pts[:,2]] = 2 <NEW_LINE> markers, n = ndimg.label(buf, np.ones((3, 3, 3))) <NEW_LINE> line = watershed(dist, markers, line=True, conn=para['con']+1) <NEW_LINE> msk = apply_hysteresis_threshold(imgs, 0, 1) <NEW_LINE> imgs[:] = imgs>0; imgs *= 255; imgs *= ~((line==0) & msk) | Mark class plugin with events callback functions | 62598fb7379a373c97d99130 |
class AccountRequest(BaseAccountRequest): <NEW_LINE> <INDENT> objects = AccountRequestManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> proxy = True <NEW_LINE> <DEDENT> @property <NEW_LINE> def harvard_key(self): <NEW_LINE> <INDENT> result = self.getDataField('harvard_key') <NEW_LINE> if not result: <NEW_LINE> <INDENT> harvard_key_login = self.getLogin('Harvard Key') <NEW_LINE> if harvard_key_login: <NEW_LINE> <INDENT> result = harvard_key_login.username <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> @harvard_key.setter <NEW_LINE> def harvard_key(self, harvard_key): <NEW_LINE> <INDENT> self.setDataField('harvard_key', harvard_key) | Account requests for {{project_name}} | 62598fb74527f215b58e9ff0 |
class Layout: <NEW_LINE> <INDENT> def __init__(self, layoutText): <NEW_LINE> <INDENT> rewards = [int(i) for i in layoutText[0].split()] <NEW_LINE> self.wall_punishment = rewards[0] <NEW_LINE> assert self.wall_punishment < 0, 'wall punishment must be negative' <NEW_LINE> self.outRange_punishment = rewards[1] <NEW_LINE> assert self.outRange_punishment < 0, 'outRange punishment must be negative' <NEW_LINE> self.rewards = rewards[2:] <NEW_LINE> layoutText = layoutText[1:] <NEW_LINE> self.width = len(layoutText[0]) <NEW_LINE> self.height = len(layoutText) <NEW_LINE> self.walls = Grid(self.width, self.height, False) <NEW_LINE> self.bonus = Grid(self.width, self.height, 0) <NEW_LINE> self.agentPosition = None <NEW_LINE> self.goalPosition = None <NEW_LINE> self.layoutText = layoutText <NEW_LINE> self.processLayoutText(layoutText) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> x, y = self.agentPosition <NEW_LINE> layout = copy.deepcopy(self.layoutText) <NEW_LINE> layout[self.height-1-y] = layout[self.height-1-y][:x] + 'P' + layout[self.height-1-y][x+1:] <NEW_LINE> return "\n".join(layout) <NEW_LINE> <DEDENT> def processLayoutText(self, layoutText): <NEW_LINE> <INDENT> maxY = self.height - 1 <NEW_LINE> for y in range(self.height): <NEW_LINE> <INDENT> for x in range(self.width): <NEW_LINE> <INDENT> layoutChar = layoutText[maxY - y][x] <NEW_LINE> self.processLayoutChar(x, y, layoutChar) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def processLayoutChar(self, x, y, layoutChar): <NEW_LINE> <INDENT> if layoutChar == '%': <NEW_LINE> <INDENT> self.walls[x][y] = True <NEW_LINE> self.bonus[x][y] = self.wall_punishment <NEW_LINE> <DEDENT> elif layoutChar == ' ': <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> elif layoutChar == 'P': <NEW_LINE> <INDENT> assert self.agentPosition is None, 'multiple start position' <NEW_LINE> self.agentPosition = np.array((x, y)) <NEW_LINE> self.layoutText[self.height-1-y] = self.layoutText[self.height-1-y].replace('P', ' ') <NEW_LINE> <DEDENT> elif layoutChar == 'G': <NEW_LINE> <INDENT> assert self.goalPosition is None, 'multiple goal position' <NEW_LINE> self.goalPosition = (x, y) <NEW_LINE> <DEDENT> elif layoutChar in [str(i) for i in range(len(self.rewards))]: <NEW_LINE> <INDENT> ind = int(layoutChar) <NEW_LINE> self.bonus[x][y] = self.rewards[ind] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Layout char illegal!') | A Layout manages the static information about the game board. | 62598fb7ff9c53063f51a769 |
class EncoderLayer(tf.keras.layers.Layer): <NEW_LINE> <INDENT> def __init__(self, config, name="encoder_layer"): <NEW_LINE> <INDENT> super().__init__(name=name) <NEW_LINE> self.self_attention = MultiHeadAttention(config) <NEW_LINE> self.norm1 = tf.keras.layers.LayerNormalization(epsilon=config["layernorm_epsilon"]) <NEW_LINE> self.ffn = PositionWiseFeedForward(config) <NEW_LINE> self.norm2 = tf.keras.layers.LayerNormalization(epsilon=config["layernorm_epsilon"]) <NEW_LINE> self.dropout = tf.keras.layers.Dropout(config["dropout"]) <NEW_LINE> <DEDENT> def call(self, enc_embed, self_mask): <NEW_LINE> <INDENT> self_attn_val = self.self_attention(enc_embed, enc_embed, enc_embed, self_mask) <NEW_LINE> norm1_val = self.norm1(enc_embed + self.dropout(self_attn_val)) <NEW_LINE> ffn_val = self.ffn(norm1_val) <NEW_LINE> enc_out = self.norm2(norm1_val + self.dropout(ffn_val)) <NEW_LINE> return enc_out | Encoder Layer Class | 62598fb744b2445a339b6a01 |
class TemporaryDirectory(object): <NEW_LINE> <INDENT> def __init__(self, suffix="", prefix=None, dir=None): <NEW_LINE> <INDENT> if "RAM_DISK" in os.environ: <NEW_LINE> <INDENT> import uuid <NEW_LINE> name = uuid.uuid4().hex <NEW_LINE> dir_name = os.path.join(os.environ["RAM_DISK"].strip(), name) <NEW_LINE> os.mkdir(dir_name) <NEW_LINE> self.name = dir_name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> suffix = suffix if suffix else "" <NEW_LINE> if not prefix: <NEW_LINE> <INDENT> self.name = mkdtemp(suffix=suffix, dir=dir) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.name = mkdtemp(suffix, prefix, dir) <NEW_LINE> <DEDENT> <DEDENT> self._finalizer = finalize( self, self._cleanup, self.name, warn_message="Implicitly cleaning up {!r}".format(self), ) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _rmtree(cls, name): <NEW_LINE> <INDENT> from .path import rmtree <NEW_LINE> rmtree(name) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _cleanup(cls, name, warn_message): <NEW_LINE> <INDENT> cls._rmtree(name) <NEW_LINE> warnings.warn(warn_message, ResourceWarning) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<{} {!r}>".format(self.__class__.__name__, self.name) <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, exc, value, tb): <NEW_LINE> <INDENT> self.cleanup() <NEW_LINE> <DEDENT> def cleanup(self): <NEW_LINE> <INDENT> if self._finalizer.detach(): <NEW_LINE> <INDENT> self._rmtree(self.name) | Create and return a temporary directory. This has the same
behavior as mkdtemp but can be used as a context manager. For
example:
with TemporaryDirectory() as tmpdir:
...
Upon exiting the context, the directory and everything contained
in it are removed. | 62598fb799fddb7c1ca62e79 |
class GNNOGBPredictor(nn.Module): <NEW_LINE> <INDENT> def __init__(self, in_edge_feats, num_node_types=1, hidden_feats=300, n_layers=5, n_tasks=1, batchnorm=True, activation=F.relu, dropout=0., gnn_type='gcn', virtual_node=True, residual=False, jk=False, readout='mean'): <NEW_LINE> <INDENT> super(GNNOGBPredictor, self).__init__() <NEW_LINE> assert gnn_type in ['gcn', 'gin'], "Expect gnn_type to be 'gcn' or 'gin', got {}".format(gnn_type) <NEW_LINE> assert readout in ['mean', 'sum', 'max'], "Expect readout to be in ['mean', 'sum', 'max'], got {}".format(readout) <NEW_LINE> self.gnn = GNNOGB(in_edge_feats=in_edge_feats, num_node_types=num_node_types, hidden_feats=hidden_feats, n_layers=n_layers, batchnorm=batchnorm, activation=activation, dropout=dropout, gnn_type=gnn_type, virtual_node=virtual_node, residual=residual, jk=jk) <NEW_LINE> if readout == 'mean': <NEW_LINE> <INDENT> self.readout = AvgPooling() <NEW_LINE> <DEDENT> if readout == 'sum': <NEW_LINE> <INDENT> self.readout = SumPooling() <NEW_LINE> <DEDENT> if readout == 'max': <NEW_LINE> <INDENT> self.readout = MaxPooling() <NEW_LINE> <DEDENT> self.predict = nn.Linear(hidden_feats, n_tasks) <NEW_LINE> <DEDENT> def reset_parameters(self): <NEW_LINE> <INDENT> self.gnn.reset_parameters() <NEW_LINE> self.predict.reset_parameters() <NEW_LINE> <DEDENT> def forward(self, g, node_feats, edge_feats): <NEW_LINE> <INDENT> node_feats = self.gnn(g, node_feats, edge_feats) <NEW_LINE> graph_feats = self.readout(g, node_feats) <NEW_LINE> return self.predict(graph_feats) | Variant of GCN/GIN from `Open Graph Benchmark: Datasets for Machine Learning on Graphs
<https://arxiv.org/abs/2005.00687>`__ for graph property prediction
Parameters
----------
in_edge_feats : int
Number of input edge features.
num_node_types : int
Number of node types to embed. (Default: 1)
hidden_feats : int
Size for hidden representations. (Default: 300)
n_layers : int
Number of GNN layers to use. (Default: 5)
n_tasks : int
Number of output tasks. (Default: 1)
batchnorm : bool
Whether to apply batch normalization. (Default: True)
activation : callable or None
Activation function to apply to the output of each GNN layer except for the last layer.
If None, no activation will be applied. (Default: ReLU)
dropout : float
The probability for dropout. (Default: 0, i.e. no dropout)
gnn_type : str
The GNN type to use, which can be either 'gcn' or 'gin'. (Default: 'gcn')
virtual_node : bool
Whether to use virtual node. (Default: True)
residual : bool
Whether to apply residual connections for virtual node embeddings. (Default: False)
jk : bool
Whether to sum over the output of all GNN layers as in
`JK networks <https://arxiv.org/abs/1806.03536>`__. (Default: False)
readout : str
The readout function for computing graph-level representations out of node
representations, which can be 'mean', 'sum' or 'max'. (Default: 'mean') | 62598fb767a9b606de5460ec |
class RafflePrizeTests(TransactionTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> test_utils.set_competition_round() <NEW_LINE> self.user = User.objects.create_user("user", "user@test.com", password="changeme") <NEW_LINE> image_path = os.path.join(settings.PROJECT_ROOT, "fixtures", "test_images", "test.jpg") <NEW_LINE> image = ImageFile(open(image_path, "r")) <NEW_LINE> self.prize = RafflePrize( title="Super prize!", description="A test prize", image=image, round=RoundSetting.objects.get(name="Round 1"), value=5, ) <NEW_LINE> <DEDENT> def testTicketAllocation(self): <NEW_LINE> <INDENT> self.prize.round = RoundSetting.objects.get(name="Round 1") <NEW_LINE> self.prize.save() <NEW_LINE> profile = self.user.get_profile() <NEW_LINE> profile.add_points(25, datetime.datetime.today(), "test") <NEW_LINE> profile.save() <NEW_LINE> self.assertEqual(RaffleTicket.available_tickets(self.user), 1, "User should have one raffle ticket.") <NEW_LINE> self.prize.add_ticket(self.user) <NEW_LINE> self.assertEqual(RaffleTicket.available_tickets(self.user), 0, "User should not have any raffle tickets.") <NEW_LINE> self.assertEqual(self.prize.allocated_tickets(), 1, "1 ticket should be allocated to this prize.") <NEW_LINE> self.assertEqual(self.prize.allocated_tickets(self.user), 1, "1 ticket should be allocated by this user to this prize.") <NEW_LINE> user2 = User.objects.create_user("user2", "user2@test.com", password="changeme") <NEW_LINE> profile = user2.get_profile() <NEW_LINE> profile.add_points(25, datetime.datetime.today(), "test") <NEW_LINE> profile.save() <NEW_LINE> self.prize.add_ticket(user2) <NEW_LINE> self.assertEqual(self.prize.allocated_tickets(), 2, "2 tickets should be allocated to this prize.") <NEW_LINE> self.assertEqual(self.prize.allocated_tickets(user2), 1, "1 ticket should be allocated by this user to this prize.") <NEW_LINE> profile.add_points(25, datetime.datetime.today(), "test") <NEW_LINE> profile.save() <NEW_LINE> self.prize.add_ticket(user2) <NEW_LINE> self.assertEqual(self.prize.allocated_tickets(), 3, "3 tickets should be allocated to this prize.") <NEW_LINE> self.assertEqual(self.prize.allocated_tickets(user2), 2, "2 tickets should be allocated by this user to this prize.") <NEW_LINE> self.prize.remove_ticket(self.user) <NEW_LINE> self.assertEqual(self.prize.allocated_tickets(), 2, "2 tickets should be allocated to this prize.") <NEW_LINE> self.assertEqual(self.prize.allocated_tickets(self.user), 0, "No tickets should be allocated by this user to this prize.") <NEW_LINE> self.prize.remove_ticket(user2) <NEW_LINE> self.assertEqual(self.prize.allocated_tickets(), 1, "1 ticket should be allocated to this prize.") <NEW_LINE> self.assertEqual(self.prize.allocated_tickets(user2), 1, "1 ticket should be allocated by this user to this prize.") <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.prize.image.delete() <NEW_LINE> self.prize.delete() | Tests the RafflePrize model. | 62598fb7adb09d7d5dc0a6a8 |
class InvalidField(BadRequest): <NEW_LINE> <INDENT> def __init__(self, errors: Any, *args: Any) -> None: <NEW_LINE> <INDENT> self.errors = errors <NEW_LINE> super().__init__(http.HTTPStatus.UNPROCESSABLE_ENTITY, *args) | A field in the request is invalid.
Represented by a 422 HTTP Response. Details of what fields were
invalid are stored in the errors attribute. | 62598fb799cbb53fe6830ff2 |
class NBytesSummary(RequestHandler): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> out = defaultdict(lambda: 0) <NEW_LINE> for k, v in self.server.data.items(): <NEW_LINE> <INDENT> out[key_split(k)] += sizeof(v) <NEW_LINE> <DEDENT> self.write(dict(out)) | Basic info about the worker | 62598fb756ac1b37e6302307 |
class Flatten(nn.Module): <NEW_LINE> <INDENT> def forward(self, input): <NEW_LINE> <INDENT> return input.view(input.size(0), -1) | Utility class for PyTorch models, please add this in place of any flattening you use in your model for use with LRP | 62598fb7442bda511e95c576 |
class BiosVfCbsCmnCpuSmee(ManagedObject): <NEW_LINE> <INDENT> consts = BiosVfCbsCmnCpuSmeeConsts() <NEW_LINE> naming_props = set([]) <NEW_LINE> mo_meta = { "classic": MoMeta("BiosVfCbsCmnCpuSmee", "biosVfCbsCmnCpuSmee", "cpu-smee", VersionMeta.Version421a, "InputOutput", 0x1f, [], ["admin"], ['biosPlatformDefaults', 'biosSettings'], [], [None]), } <NEW_LINE> prop_meta = { "classic": { "child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version421a, MoPropertyMeta.INTERNAL, None, None, None, None, [], []), "dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version421a, MoPropertyMeta.READ_WRITE, 0x2, 0, 255, None, [], []), "rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version421a, MoPropertyMeta.READ_WRITE, 0x4, 0, 255, None, [], []), "status": MoPropertyMeta("status", "status", "string", VersionMeta.Version421a, MoPropertyMeta.READ_WRITE, 0x8, None, None, None, ["", "created", "deleted", "modified", "removed"], []), "vp_cbs_cmn_cpu_smee": MoPropertyMeta("vp_cbs_cmn_cpu_smee", "vpCbsCmnCpuSmee", "string", VersionMeta.Version421a, MoPropertyMeta.READ_WRITE, 0x10, None, None, None, ["Auto", "Disabled", "Enabled", "disabled", "enabled", "platform-default"], []), }, } <NEW_LINE> prop_map = { "classic": { "childAction": "child_action", "dn": "dn", "rn": "rn", "status": "status", "vpCbsCmnCpuSmee": "vp_cbs_cmn_cpu_smee", }, } <NEW_LINE> def __init__(self, parent_mo_or_dn, **kwargs): <NEW_LINE> <INDENT> self._dirty_mask = 0 <NEW_LINE> self.child_action = None <NEW_LINE> self.status = None <NEW_LINE> self.vp_cbs_cmn_cpu_smee = None <NEW_LINE> ManagedObject.__init__(self, "BiosVfCbsCmnCpuSmee", parent_mo_or_dn, **kwargs) | This is BiosVfCbsCmnCpuSmee class. | 62598fb701c39578d7f12e96 |
class DomainExists(DnsMetricsNotificationBase): <NEW_LINE> <INDENT> event_types = ['%s.domain.exists' % SERVICE] <NEW_LINE> def process_notification(self, message): <NEW_LINE> <INDENT> period_start = timeutils.normalize_time(timeutils.parse_isotime( message['payload']['audit_period_beginning'])) <NEW_LINE> period_end = timeutils.normalize_time(timeutils.parse_isotime( message['payload']['audit_period_ending'])) <NEW_LINE> period_difference = timeutils.delta_seconds(period_start, period_end) <NEW_LINE> yield sample.Sample.from_notification( name=message['event_type'], type=sample.TYPE_CUMULATIVE, unit='s', volume=period_difference, resource_id=message['payload']['id'], user_id=message['_context_user'], project_id=message['payload']['tenant_id'], message=message) | Handles DNS domain exists notification.
Emits a sample for a measurable audit interval. | 62598fb7627d3e7fe0e06fcc |
class GroupOptions_widget(OptionsWidget): <NEW_LINE> <INDENT> def __init__(self, groups, ui_js = bootstrap_select_min_js, ui_css = bootstrap_select_min_css): <NEW_LINE> <INDENT> if not ui_js in response.files: <NEW_LINE> <INDENT> response.files.append(ui_js) <NEW_LINE> <DEDENT> if not ui_css in response.files: <NEW_LINE> <INDENT> response.files.append(ui_css) <NEW_LINE> <DEDENT> self.groups = groups <NEW_LINE> <DEDENT> def widget(self, field, value,**attributes): <NEW_LINE> <INDENT> attr = OptionsWidget._attributes(field, {'value':value}, **attributes) <NEW_LINE> opts = [OPTION('')] + [ OPTGROUP( _label=group, *[OPTION(v, _value=k) for (k, v) in options.items()]) for group, options in self.groups.items() ] <NEW_LINE> wrapper = SELECT(*opts, **attr) <NEW_LINE> scr = SCRIPT('$(".selectpicker").selectpicker();') <NEW_LINE> wrapper.append(scr) <NEW_LINE> return wrapper | An GroupOptions using BootStrap | 62598fb7cc40096d6161a267 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.