code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class ChangeEmail(generic.UpdateView): <NEW_LINE> <INDENT> model = User <NEW_LINE> fields = ["email"] <NEW_LINE> template_name = "user/email_change_form.html" <NEW_LINE> def get_success_url(self): <NEW_LINE> <INDENT> return reverse("user:email_change_done") <NEW_LINE> <DEDENT> def get_object(self, queryset=None): <NEW_LINE> <INDENT> return self.request.user | Change or add user email. | 625990704e4d562566373cbd |
class Sfixed32Field(Field): <NEW_LINE> <INDENT> type = 15 <NEW_LINE> cpp_type = 1 <NEW_LINE> default_value = 0 | sfixed32类型 | 6259907066673b3332c31cb5 |
class PanelRendu(bpy.types.Panel): <NEW_LINE> <INDENT> bl_label = "Setup render" <NEW_LINE> bl_idname = "OBJECT_PT_Créer_Des_trous" <NEW_LINE> bl_space_type = 'PROPERTIES' <NEW_LINE> bl_region_type = 'WINDOW' <NEW_LINE> def draw(self, context): <NEW_LINE> <INDENT> layout = self.layout <NEW_LINE> layout.prop(context.scene, "my_string_prop") <NEW_LINE> layout.prop(context.scene, "my_string_material") <NEW_LINE> layout.operator("object.rendersetup") <NEW_LINE> layout.operator("object.playblastsetup") <NEW_LINE> layout.operator("object.materialtsetup") | Ce Panel contient l'Operator qui crée un trou sur une sélection | 6259907099cbb53fe68327a1 |
class NotWellFormedOSMDataException(Exception): <NEW_LINE> <INDENT> pass | OSM data structure is not well-formed. | 62599070627d3e7fe0e0873f |
class GoString(object): <NEW_LINE> <INDENT> def __init__(self, color, stones, liberties): <NEW_LINE> <INDENT> self.color = color <NEW_LINE> self.stones = set(stones) <NEW_LINE> self.liberties = set(liberties) <NEW_LINE> <DEDENT> def remove_liberty(self, point): <NEW_LINE> <INDENT> self.liberties.remove(point) <NEW_LINE> <DEDENT> def add_liberty(self, point): <NEW_LINE> <INDENT> self.liberties.add(point) <NEW_LINE> <DEDENT> def merged_with(self, go_string): <NEW_LINE> <INDENT> assert go_string.color == self.color <NEW_LINE> combined_stones = self.stones | go_string.stones <NEW_LINE> return GoString( self.color, combined_stones, (self.liberties | go_string.liberties) - combined_stones) <NEW_LINE> <DEDENT> @property <NEW_LINE> def num_liberties(self): <NEW_LINE> <INDENT> return len(self.liberties) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, GoString) and self.color == other.color and self.stones == other.stones and self.liberties == other.liberties | Stones that are linked by a chain of connected stones of the
same color. | 6259907071ff763f4b5e9060 |
class precision(layer): <NEW_LINE> <INDENT> def __init__(self, name="precision", **kwargs): <NEW_LINE> <INDENT> super(precision, self).__init__(name=name, **kwargs) <NEW_LINE> self.tp = true_positive(**kwargs) <NEW_LINE> self.fp = false_positive(**kwargs) <NEW_LINE> <DEDENT> def reset_states(self): <NEW_LINE> <INDENT> self.tp.reset_states() <NEW_LINE> self.fp.reset_states() <NEW_LINE> <DEDENT> def __call__(self, y_true, y_pred): <NEW_LINE> <INDENT> if self.epsilon is None: <NEW_LINE> <INDENT> self.init_tensors() <NEW_LINE> <DEDENT> tp = self.tp(y_true, y_pred) <NEW_LINE> fp = self.fp(y_true, y_pred) <NEW_LINE> self.add_update(self.tp.updates) <NEW_LINE> self.add_update(self.fp.updates) <NEW_LINE> tp = K.cast(tp, self.epsilon.dtype) <NEW_LINE> fp = K.cast(fp, self.epsilon.dtype) <NEW_LINE> return truediv(tp, tp + fp + self.epsilon) | Create a metric for model's precision calculation.
Precision measures proportion of positives identifications that were
actually correct. | 6259907092d797404e3897b7 |
class ExecutableRuntimeError(Exception): <NEW_LINE> <INDENT> def __init__(self, cmd, err): <NEW_LINE> <INDENT> message = "Command '%s' failed with error:\n%s" % (cmd, err) <NEW_LINE> super(ExecutableRuntimeError, self).__init__(message) | Exception raised when an executable call throws a runtime error. | 62599070bf627c535bcb2d84 |
class Eq_21(SoftwoodVolumeEquation): <NEW_LINE> <INDENT> def calc_cvts(self, dbh, ht): <NEW_LINE> <INDENT> cvts = (0.005454154 * (0.30708901 + 0.00086157622 * ht - 0.0037255243 * dbh * ht / (ht - 4.5)) * dbh**2 * ht * (ht / (ht - 4.5))**2).clip(0,) <NEW_LINE> cvts[np.logical_or(dbh <= 0, ht <= 0)] = 0 <NEW_LINE> return cvts <NEW_LINE> <DEDENT> def calc_tarif(self, dbh, ht): <NEW_LINE> <INDENT> ba = 0.005454154 * (dbh**2) <NEW_LINE> cvts = self.calc_cvts(dbh, ht) <NEW_LINE> tarif = (cvts * 0.912733) / ( (1.033 * (1.0 + 1.382937 * np.exp(-4.015292 * dbh))) * (ba + 0.087266) - 0.174533) <NEW_LINE> tarif[np.logical_or(dbh <= 0, ht <= 0)] = 0 <NEW_LINE> return tarif <NEW_LINE> <DEDENT> def calc_cv4(self, dbh, ht): <NEW_LINE> <INDENT> cvts = self.calc_cvts(dbh, ht) <NEW_LINE> cv4 = (cvts + 3.48) / (1.18052 + 0.32736 * np.exp(-0.1 * dbh)) - 2.948 <NEW_LINE> cv4[np.logical_or(dbh <= 0, ht <= 0)] = 0 <NEW_LINE> return cv4 <NEW_LINE> <DEDENT> def calc_cvt(self, dbh, ht): <NEW_LINE> <INDENT> ba = 0.005454154 * (dbh**2) <NEW_LINE> tarif = self.calc_tarif(dbh, ht) <NEW_LINE> cvt = tarif * (0.9679 - 0.1051 * 0.5523**(dbh - 1.5)) * ( (1.033 * (1.0 + 1.382937 * np.exp(-4.015292 * (dbh / 10.0)))) * (ba + 0.087266) - 0.174533) / 0.912733 <NEW_LINE> cvt[np.logical_or(dbh <= 0, ht <= 0)] = 0 <NEW_LINE> return cvt | Western juniper (CHITTESTER,1984)
Chittester, Judith and Colin MacLean. 1984. Cubic-foot tree-volume
equations and tables for western juniper. Research Note, PNW-420. Pacific
Northwest Forest and Range Experiment Station. Portland, Oregon. 8p. | 625990702ae34c7f260ac9a2 |
class Variable(object): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> <DEDENT> @trace <NEW_LINE> def eval(self,env): <NEW_LINE> <INDENT> print(self.name) <NEW_LINE> print('var called env') <NEW_LINE> return env[self.name] | 变量符号类
| 62599070e5267d203ee6d019 |
class BLOG_NOT_FOUND(Exception): <NEW_LINE> <INDENT> def __init__(*args, **kwargs): <NEW_LINE> <INDENT> Exception.__init__(*args, **kwargs) | - **API Code** : 1202
- **API Message** : ``Unknown`` | 625990707047854f46340c70 |
class User(object): <NEW_LINE> <INDENT> def __init__(self, email, name=None, login=None): <NEW_LINE> <INDENT> if not email: <NEW_LINE> <INDENT> raise RuntimeError( "Email required for user initialization.") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> parts = EMAIL_REGEXP.search(email) <NEW_LINE> self.email = parts.groups()[1] <NEW_LINE> self.login = login or self.email.split('@')[0] <NEW_LINE> self.name = name or parts.groups()[0] or u"Unknown" <NEW_LINE> <DEDENT> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return u"{0} <{1}>".format(self.name, self.email) | User info | 62599070aad79263cf43006e |
class account_tax(osv.osv): <NEW_LINE> <INDENT> _inherit = 'account.tax' <NEW_LINE> _columns = { 'tax_discount': fields.boolean('Discount this Tax in Prince', help="Mark it for (ICMS, PIS e etc.)."), 'base_reduction': fields.float('Redution', required=True, digits=0, help="Um percentual decimal em % entre 0-1."), 'amount_mva': fields.float('MVA Percent', required=True, digits=0, help="Um percentual decimal em % entre 0-1."), } <NEW_LINE> _defaults = TAX_DEFAULTS | Add fields used to define some brazilian taxes | 62599070ec188e330fdfa15b |
class TextUnit: <NEW_LINE> <INDENT> def __init__(self, text, italicized=False, bold=False): <NEW_LINE> <INDENT> if isinstance(text, Node): <NEW_LINE> <INDENT> self.text = text.name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.text = text <NEW_LINE> <DEDENT> self.italic = italicized <NEW_LINE> self.bold = bold | A unit of text with formatting. | 6259907038b623060ffaa4b0 |
class SharedMessageDialog() : <NEW_LINE> <INDENT> def showError(self, title, message): <NEW_LINE> <INDENT> QMessageBox.critical(self, title, message) <NEW_LINE> <DEDENT> def showErrors(self, title, errors): <NEW_LINE> <INDENT> errors = self.flatten(errors) <NEW_LINE> errors = "\n".join(errors) <NEW_LINE> self.showError(title, errors) <NEW_LINE> <DEDENT> def flatten(self, l): <NEW_LINE> <INDENT> for el in l: <NEW_LINE> <INDENT> if isinstance(el, collections.Iterable) and not isinstance(el, basestring): <NEW_LINE> <INDENT> for sub in self.flatten(el): <NEW_LINE> <INDENT> yield sub <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> yield el <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def showWarning(self, title, message): <NEW_LINE> <INDENT> QMessageBox.warning(self, title, message) <NEW_LINE> <DEDENT> def showInfo(self, title, message): <NEW_LINE> <INDENT> QMessageBox.information(self, title, message) <NEW_LINE> <DEDENT> def showQuestion(self, title, question_text): <NEW_LINE> <INDENT> return QMessageBox.question(self, title, question_text, QMessageBox.Yes|QMessageBox.No) | Prototype for a shared message dialog system | 625990707d847024c075dc91 |
class res_municipios(osv.osv): <NEW_LINE> <INDENT> _name = 'res.municipios' <NEW_LINE> _rec_name = 'municipio' <NEW_LINE> _columns = { 'municipio': fields.char('Municipio', size=50, required=True, help='Nombre del Municipio'), 'codigo': fields.char('Codigo', size=3, required=True, help='Codigo del Municipio'), 'estado_id': fields.many2one('res.estados', 'Estado', help='Estado que esta asociado al Municipio'), 'active': fields.boolean('Activo'), } <NEW_LINE> _defaults = { 'active':True, } | Nombre de los Municipios | 62599070796e427e53850031 |
class AbstractBoard(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.matrix = None <NEW_LINE> self.parent = None <NEW_LINE> self.M = None <NEW_LINE> self.N = None <NEW_LINE> <DEDENT> def create_matrix(self, rows, cols): <NEW_LINE> <INDENT> self.M = rows <NEW_LINE> self.N = cols <NEW_LINE> self.matrix = [[0 for col in range(cols)] for row in range(rows)] <NEW_LINE> <DEDENT> def get_rows(self): <NEW_LINE> <INDENT> return self.matrix <NEW_LINE> <DEDENT> def get_cols(self): <NEW_LINE> <INDENT> return [[self.matrix[y][x] for y in xrange(self.M)] for x in xrange(self.N)] <NEW_LINE> <DEDENT> def get_diags(self): <NEW_LINE> <INDENT> left_up = [] <NEW_LINE> right_up = [] <NEW_LINE> for p in xrange(0, self.M * 2 - 1): <NEW_LINE> <INDENT> diag_left = [] <NEW_LINE> diag_right = [] <NEW_LINE> for q in xrange(max(0, p - self.M + 1), min(p, self.M - 1) + 1): <NEW_LINE> <INDENT> diag_right.append(self.matrix[p - q][q]) <NEW_LINE> diag_left.append(self.matrix[p - q][self.M - 1 - q]) <NEW_LINE> <DEDENT> if diag_left: <NEW_LINE> <INDENT> left_up.append(diag_left) <NEW_LINE> <DEDENT> if diag_right: <NEW_LINE> <INDENT> right_up.append(diag_right) <NEW_LINE> <DEDENT> <DEDENT> return left_up, right_up <NEW_LINE> <DEDENT> def get_diag_coords(self): <NEW_LINE> <INDENT> left_up = [] <NEW_LINE> right_up = [] <NEW_LINE> for p in xrange(0, self.M * 2 - 1): <NEW_LINE> <INDENT> diag_left = [] <NEW_LINE> diag_right = [] <NEW_LINE> for q in xrange(max(0, p - self.M + 1), min(p, self.M - 1) + 1): <NEW_LINE> <INDENT> diag_right.append((p - q, q)) <NEW_LINE> diag_left.append((p - q, self.M - 1 - q)) <NEW_LINE> <DEDENT> if diag_left: <NEW_LINE> <INDENT> left_up.append(diag_left) <NEW_LINE> <DEDENT> if diag_right: <NEW_LINE> <INDENT> right_up.append(diag_right) <NEW_LINE> <DEDENT> <DEDENT> return left_up, right_up | Abstract board representation | 6259907099fddb7c1ca63a2f |
class MusicAlbumSchema(SchemaObject): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.schema = 'MusicAlbum' | Schema Mixin for MusicAlbum
Usage: place after django model in class definition, schema will return the schema.org url for the object
A collection of music tracks. | 62599070be8e80087fbc0948 |
class PickupObject(object): <NEW_LINE> <INDENT> def __init__(self, ): <NEW_LINE> <INDENT> self.pickup_client = None <NEW_LINE> <DEDENT> def activate(self): <NEW_LINE> <INDENT> self.pickup_client = actionlib.SimpleActionClient('/object_manipulator/object_manipulator_pickup', PickupAction) <NEW_LINE> self.pickup_client.wait_for_server() <NEW_LINE> rospy.loginfo("Pickup server ready") <NEW_LINE> <DEDENT> def execute(self, graspable_object, graspable_object_name, collision_support_surface_name, pickup_direction=None, arm_name="right_arm", desired_approach_distance = 0.05, min_approach_distance = 0.02, desired_lift_distance = 0.25, min_lift_distance = 0.2): <NEW_LINE> <INDENT> pickup_goal = PickupGoal() <NEW_LINE> pickup_goal.target = graspable_object <NEW_LINE> pickup_goal.collision_object_name = graspable_object_name <NEW_LINE> pickup_goal.collision_support_surface_name = collision_support_surface_name <NEW_LINE> pickup_goal.arm_name = arm_name <NEW_LINE> pickup_goal.desired_approach_distance = desired_approach_distance <NEW_LINE> pickup_goal.min_approach_distance = min_approach_distance <NEW_LINE> if pickup_direction != None: <NEW_LINE> <INDENT> pickup_goal.lift.direction = pickup_direction <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pickup_direction = Vector3Stamped() <NEW_LINE> pickup_direction.header.stamp = rospy.get_rostime() <NEW_LINE> pickup_direction.header.frame_id = "/base_link"; <NEW_LINE> pickup_direction.vector.x = 0; <NEW_LINE> pickup_direction.vector.y = 0; <NEW_LINE> pickup_direction.vector.z = 1; <NEW_LINE> pickup_goal.lift.direction = pickup_direction; <NEW_LINE> <DEDENT> pickup_goal.lift.desired_distance = desired_lift_distance <NEW_LINE> pickup_goal.lift.min_distance = min_lift_distance <NEW_LINE> pickup_goal.use_reactive_lift = True; <NEW_LINE> pickup_goal.use_reactive_execution = True; <NEW_LINE> self.pickup_client.send_goal(pickup_goal) <NEW_LINE> self.pickup_client.wait_for_result(timeout=rospy.Duration.from_sec(90.0)) <NEW_LINE> rospy.loginfo("Got Pickup results") <NEW_LINE> pickup_result = self.pickup_client.get_result() <NEW_LINE> if self.pickup_client.get_state() != GoalStatus.SUCCEEDED: <NEW_LINE> <INDENT> rospy.logerr("The pickup action has failed: " + str(pickup_result.manipulation_result.value) ) <NEW_LINE> return -1 <NEW_LINE> <DEDENT> return pickup_result | Pickup a given object, this class is instantiated in the SrPickupObjectStateMachine. | 62599070a05bb46b3848bd88 |
class ExpressRouteCircuitRoutesTable(Model): <NEW_LINE> <INDENT> _validation = { 'next_hop_type': {'required': True}, } <NEW_LINE> _attribute_map = { 'address_prefix': {'key': 'addressPrefix', 'type': 'str'}, 'next_hop_type': {'key': 'nextHopType', 'type': 'str'}, 'next_hop_ip': {'key': 'nextHopIP', 'type': 'str'}, 'as_path': {'key': 'asPath', 'type': 'str'}, } <NEW_LINE> def __init__(self, next_hop_type, address_prefix=None, next_hop_ip=None, as_path=None): <NEW_LINE> <INDENT> self.address_prefix = address_prefix <NEW_LINE> self.next_hop_type = next_hop_type <NEW_LINE> self.next_hop_ip = next_hop_ip <NEW_LINE> self.as_path = as_path | The routes table associated with the ExpressRouteCircuit.
:param address_prefix: Gets AddressPrefix.
:type address_prefix: str
:param next_hop_type: Gets NextHopType. Possible values include:
'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance',
'None'
:type next_hop_type: str or
~azure.mgmt.network.v2015_06_15.models.RouteNextHopType
:param next_hop_ip: Gets NextHopIP.
:type next_hop_ip: str
:param as_path: Gets AsPath.
:type as_path: str | 6259907023849d37ff85296f |
class CommunityTagsColumn(TextColumn): <NEW_LINE> <INDENT> def __init__(self, col_name, key, model_class=None, model_tag_association_class=None, filterable=None, grid_name=None): <NEW_LINE> <INDENT> GridColumn.__init__(self, col_name, key=key, model_class=model_class, nowrap=True, filterable=filterable, sortable=False) <NEW_LINE> self.model_tag_association_class = model_tag_association_class <NEW_LINE> self.grid_name = grid_name <NEW_LINE> <DEDENT> def get_value(self, trans, grid, item): <NEW_LINE> <INDENT> return trans.fill_template("/tagging_common.mako", tag_type="community", trans=trans, user=trans.get_user(), tagged_item=item, elt_context=self.grid_name, in_form=True, input_size="20", tag_click_fn="add_tag_to_grid_filter", use_toggle_link=True) <NEW_LINE> <DEDENT> def filter(self, trans, user, query, column_filter): <NEW_LINE> <INDENT> if column_filter == "All": <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif column_filter: <NEW_LINE> <INDENT> query = query.filter(self.get_filter(trans, user, column_filter)) <NEW_LINE> <DEDENT> return query <NEW_LINE> <DEDENT> def get_filter(self, trans, user, column_filter): <NEW_LINE> <INDENT> if isinstance(column_filter, list): <NEW_LINE> <INDENT> column_filter = ",".join(column_filter) <NEW_LINE> <DEDENT> raw_tags = trans.app.tag_handler.parse_tags(column_filter.encode("utf-8")) <NEW_LINE> clause_list = [] <NEW_LINE> for name, value in raw_tags: <NEW_LINE> <INDENT> if name: <NEW_LINE> <INDENT> clause_list.append(self.model_class.tags.any(func.lower(self.model_tag_association_class.user_tname).like("%" + name.lower() + "%"))) <NEW_LINE> if value: <NEW_LINE> <INDENT> clause_list.append(self.model_class.tags.any(func.lower(self.model_tag_association_class.user_value).like("%" + value.lower() + "%"))) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return and_(*clause_list) | Column that supports community tags. | 625990704e4d562566373cbf |
class Write(Command): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.finished = False <NEW_LINE> <DEDENT> def execute(self): <NEW_LINE> <INDENT> if self.finished: <NEW_LINE> <INDENT> self.character.lower_arm() <NEW_LINE> return self <NEW_LINE> <DEDENT> self.finished = self.character.write() | Command that controls Eric while he's writing on a blackboard. | 62599070f548e778e596ce46 |
class WNLITask(AbstractGlueTask): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> is_pair = True <NEW_LINE> class_labels = ['0', '1'] <NEW_LINE> metric = Accuracy() <NEW_LINE> super(WNLITask, self).__init__(class_labels, metric, is_pair) <NEW_LINE> <DEDENT> def get_dataset(self, segment='train'): <NEW_LINE> <INDENT> return GlueWNLI(segment=segment) | The Winograd NLI task on GLUE benchmark. | 6259907066673b3332c31cb7 |
class Recurrent_block(Model): <NEW_LINE> <INDENT> def __init__(self, out_ch, t=2): <NEW_LINE> <INDENT> super(Recurrent_block, self).__init__() <NEW_LINE> self.t = t <NEW_LINE> self.out_ch = out_ch <NEW_LINE> self.conv = Sequential([ Conv2D(out_ch, kernel_size=(3, 3), strides=1, padding='same'), BatchNormalization(), Activation('relu') ]) <NEW_LINE> <DEDENT> def call(self, x): <NEW_LINE> <INDENT> for i in range(self.t): <NEW_LINE> <INDENT> if i == 0: <NEW_LINE> <INDENT> x = self.conv(x) <NEW_LINE> <DEDENT> out = self.conv(x + x) <NEW_LINE> <DEDENT> return out | Recurrent Block for R2Unet_CNN | 625990701f037a2d8b9e54c7 |
class Search(CategoryRegion, ListView): <NEW_LINE> <INDENT> def get_queryset(self): <NEW_LINE> <INDENT> queryset = Hike.objects.filter(title__icontains=self.request.GET.get("search"), draft=False) <NEW_LINE> return queryset.values('title', 'tagline', 'url', 'image') <NEW_LINE> <DEDENT> def get_context_data(self, *args, **kwargs): <NEW_LINE> <INDENT> context = super().get_context_data(*args, **kwargs) <NEW_LINE> context["search"] = f'search={self.request.GET.get("search")}&' <NEW_LINE> return context | Search for hikes | 6259907097e22403b383c7bd |
class NumericInput(Component): <NEW_LINE> <INDENT> @_explicitize_args <NEW_LINE> def __init__(self, id=Component.UNDEFINED, value=Component.UNDEFINED, size=Component.UNDEFINED, min=Component.UNDEFINED, max=Component.UNDEFINED, disabled=Component.UNDEFINED, theme=Component.UNDEFINED, label=Component.UNDEFINED, labelPosition=Component.UNDEFINED, className=Component.UNDEFINED, style=Component.UNDEFINED, persistence=Component.UNDEFINED, persisted_props=Component.UNDEFINED, persistence_type=Component.UNDEFINED, **kwargs): <NEW_LINE> <INDENT> self._prop_names = ['id', 'className', 'disabled', 'label', 'labelPosition', 'max', 'min', 'persisted_props', 'persistence', 'persistence_type', 'size', 'style', 'theme', 'value'] <NEW_LINE> self._type = 'NumericInput' <NEW_LINE> self._namespace = 'dash_daq' <NEW_LINE> self._valid_wildcard_attributes = [] <NEW_LINE> self.available_properties = ['id', 'className', 'disabled', 'label', 'labelPosition', 'max', 'min', 'persisted_props', 'persistence', 'persistence_type', 'size', 'style', 'theme', 'value'] <NEW_LINE> self.available_wildcard_properties = [] <NEW_LINE> _explicit_args = kwargs.pop('_explicit_args') <NEW_LINE> _locals = locals() <NEW_LINE> _locals.update(kwargs) <NEW_LINE> args = {k: _locals[k] for k in _explicit_args if k != 'children'} <NEW_LINE> for k in []: <NEW_LINE> <INDENT> if k not in args: <NEW_LINE> <INDENT> raise TypeError( 'Required argument `' + k + '` was not specified.') <NEW_LINE> <DEDENT> <DEDENT> super(NumericInput, self).__init__(**args) | A NumericInput component.
A numeric input component that can be
set to a value between some range.
Keyword arguments:
- id (string; optional):
The ID used to identify this compnent in Dash callbacks.
- className (string; optional):
Class to apply to the root component element.
- disabled (boolean; optional):
If True, numeric input cannot changed.
- label (dict; optional):
Description to be displayed alongside the control. To control
styling, pass an object with label and style properties.
`label` is a string | dict with keys:
- label (string; optional)
- style (dict; optional)
- labelPosition (a value equal to: 'top', 'bottom'; default 'top'):
Where the numeric input label is positioned.
- max (number; default 10):
The maximum value of the numeric input.
- min (number; default 0):
The minimum value of the numeric input.
- persisted_props (list of a value equal to: 'value's; default ['value']):
Properties whose user interactions will persist after refreshing
the component or the page. Since only `value` is allowed this prop
can normally be ignored.
- persistence (boolean | string | number; optional):
Used to allow user interactions in this component to be persisted
when the component - or the page - is refreshed. If `persisted` is
truthy and hasn't changed from its previous value, a `value` that
the user has changed while using the app will keep that change, as
long as the new `value` also matches what was given originally.
Used in conjunction with `persistence_type`.
- persistence_type (a value equal to: 'local', 'session', 'memory'; default 'local'):
Where persisted user changes will be stored: memory: only kept in
memory, reset on page refresh. local: window.localStorage, data is
kept after the browser quit. session: window.sessionStorage, data
is cleared once the browser quit.
- size (number; optional):
The size (length) of the numeric input in pixels.
- style (dict; default { display: 'flex', justifyContent: 'center' }):
Style to apply to the root component element.
- theme (dict; default light):
Theme configuration to be set by a ThemeProvider.
- value (number; optional):
The value of numeric input. | 62599070d268445f2663a7ba |
class Reward(object): <NEW_LINE> <INDENT> def __init__(self, base_reward_elements: Tuple, shaping_reward_elements: Tuple): <NEW_LINE> <INDENT> self.base_reward_elements = base_reward_elements <NEW_LINE> self.shaping_reward_elements = shaping_reward_elements <NEW_LINE> if not self.base_reward_elements: <NEW_LINE> <INDENT> raise ValueError('base agent_reward cannot be empty') <NEW_LINE> <DEDENT> <DEDENT> def agent_reward(self) -> float: <NEW_LINE> <INDENT> sum_reward = sum(self.base_reward_elements) + sum(self.shaping_reward_elements) <NEW_LINE> num_reward_components = len(self.base_reward_elements) + len(self.shaping_reward_elements) <NEW_LINE> return sum_reward / num_reward_components <NEW_LINE> <DEDENT> def assessment_reward(self) -> float: <NEW_LINE> <INDENT> return sum(self.base_reward_elements) / len(self.base_reward_elements) <NEW_LINE> <DEDENT> def is_shaping(self): <NEW_LINE> <INDENT> return bool(self.shaping_reward_elements) | Immutable class storing an RL reward.
We decompose rewards into tuples of component values, reflecting contributions
from different goals. Separate tuples are maintained for the assessment (non-shaping)
components and the shaping components. It is intended that the
Scalar reward values are retrieved by calling .reward() or non_shaping_reward().
The scalar value is the mean of the components. | 6259907067a9b606de547700 |
class JSONEncoder(json.JSONEncoder): <NEW_LINE> <INDENT> def default(self, o): <NEW_LINE> <INDENT> if isinstance(o, datetime.datetime): <NEW_LINE> <INDENT> r = o.isoformat() <NEW_LINE> if o.microsecond: <NEW_LINE> <INDENT> r = r[:23] + r[26:] <NEW_LINE> <DEDENT> if r.endswith('+00:00'): <NEW_LINE> <INDENT> r = r[:-6] + 'Z' <NEW_LINE> <DEDENT> return r <NEW_LINE> <DEDENT> elif isinstance(o, datetime.date): <NEW_LINE> <INDENT> return o.isoformat() <NEW_LINE> <DEDENT> elif isinstance(o, datetime.time): <NEW_LINE> <INDENT> if is_aware(o): <NEW_LINE> <INDENT> raise ValueError("JSON can't represent timezone-aware times.") <NEW_LINE> <DEDENT> r = o.isoformat() <NEW_LINE> if o.microsecond: <NEW_LINE> <INDENT> r = r[:12] <NEW_LINE> <DEDENT> return r <NEW_LINE> <DEDENT> elif isinstance(o, datetime.timedelta): <NEW_LINE> <INDENT> return duration_iso_string(o) <NEW_LINE> <DEDENT> elif isinstance(o, decimal.Decimal): <NEW_LINE> <INDENT> return str(o) <NEW_LINE> <DEDENT> elif isinstance(o, uuid.UUID): <NEW_LINE> <INDENT> return str(o) <NEW_LINE> <DEDENT> elif isinstance(o, decimal.Decimal): <NEW_LINE> <INDENT> return float(o) <NEW_LINE> <DEDENT> elif isinstance(o, Model): <NEW_LINE> <INDENT> return OrderedDict(o) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return super().default(o) | JSONEncoder subclass that knows how to encode date/time, decimal types and UUIDs. | 62599070460517430c432cb4 |
class SimpleReportedForm(GAErrorReportingMixin, TestForm): <NEW_LINE> <INDENT> ga_tracking_id = settings.GOOGLE_ANALYTICS_ID | Minimal form - sets the tracking ID class-wide | 625990708e7ae83300eea94b |
class Condition22(Condition): <NEW_LINE> <INDENT> def check(self, instance): <NEW_LINE> <INDENT> raise NotImplementedError('%s not implemented' % ( str(self))) | Message->Sent->On any message to peer
Parameters:
0: Subchannel (-1 for any) (EXPRESSION, ExpressionParameter) | 62599070aad79263cf430070 |
class AdditionalProperty(messages.Message): <NEW_LINE> <INDENT> key = messages.StringField(1) <NEW_LINE> value = messages.MessageField('DisksScopedList', 2) | An additional property for a ItemsValue object.
Fields:
key: Name of the additional property.
value: A DisksScopedList attribute. | 625990708da39b475be04aa9 |
class FlowControlMessage(DepecheMessage): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> DepecheMessage.__init__(self) <NEW_LINE> self.type = None <NEW_LINE> <DEDENT> def serialize(self, d={}): <NEW_LINE> <INDENT> return DepecheMessage.serialize(self, d) | This is the superclass of all flow control messages needed to
regulate the message exchange process. Flow control messages
should never require persistence, and should only be used
during the message exchange sequence to regulate flow of
data/files between the nodes. | 62599070796e427e53850033 |
class ConsoleOutputNoLegacyNoScopePolicyTest(ConsoleOutputPolicyTest): <NEW_LINE> <INDENT> without_deprecated_rules = True <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> super(ConsoleOutputNoLegacyNoScopePolicyTest, self).setUp() <NEW_LINE> self.project_member_authorized_contexts = [ self.project_admin_context, self.project_member_context] | Test Server Console Output APIs policies with no legacy deprecated
rule and no scope check. | 62599070be8e80087fbc094a |
class ExecutionFSA(): <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def is_valid(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def is_in_action(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def world_state(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def valid_feeds(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def peek_complete_action(self, action, arg1, arg2): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def feed_complete_action(self, action, arg1, arg2): <NEW_LINE> <INDENT> pass | Abstract class for an FSA that can execute various actions. | 625990705fdd1c0f98e5f842 |
class gr_check_counting_s_sptr(object): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __init__(self, *args): <NEW_LINE> <INDENT> this = _gnuradio_core_general.new_gr_check_counting_s_sptr(*args) <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this <NEW_LINE> <DEDENT> def __deref__(self): <NEW_LINE> <INDENT> return _gnuradio_core_general.gr_check_counting_s_sptr___deref__(self) <NEW_LINE> <DEDENT> __swig_destroy__ = _gnuradio_core_general.delete_gr_check_counting_s_sptr <NEW_LINE> __del__ = lambda self : None; <NEW_LINE> def history(self): <NEW_LINE> <INDENT> return _gnuradio_core_general.gr_check_counting_s_sptr_history(self) <NEW_LINE> <DEDENT> def output_multiple(self): <NEW_LINE> <INDENT> return _gnuradio_core_general.gr_check_counting_s_sptr_output_multiple(self) <NEW_LINE> <DEDENT> def relative_rate(self): <NEW_LINE> <INDENT> return _gnuradio_core_general.gr_check_counting_s_sptr_relative_rate(self) <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> return _gnuradio_core_general.gr_check_counting_s_sptr_start(self) <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> return _gnuradio_core_general.gr_check_counting_s_sptr_stop(self) <NEW_LINE> <DEDENT> def nitems_read(self, *args, **kwargs): <NEW_LINE> <INDENT> return _gnuradio_core_general.gr_check_counting_s_sptr_nitems_read(self, *args, **kwargs) <NEW_LINE> <DEDENT> def nitems_written(self, *args, **kwargs): <NEW_LINE> <INDENT> return _gnuradio_core_general.gr_check_counting_s_sptr_nitems_written(self, *args, **kwargs) <NEW_LINE> <DEDENT> def detail(self): <NEW_LINE> <INDENT> return _gnuradio_core_general.gr_check_counting_s_sptr_detail(self) <NEW_LINE> <DEDENT> def set_detail(self, *args, **kwargs): <NEW_LINE> <INDENT> return _gnuradio_core_general.gr_check_counting_s_sptr_set_detail(self, *args, **kwargs) <NEW_LINE> <DEDENT> def name(self): <NEW_LINE> <INDENT> return _gnuradio_core_general.gr_check_counting_s_sptr_name(self) <NEW_LINE> <DEDENT> def input_signature(self): <NEW_LINE> <INDENT> return _gnuradio_core_general.gr_check_counting_s_sptr_input_signature(self) <NEW_LINE> <DEDENT> def output_signature(self): <NEW_LINE> <INDENT> return _gnuradio_core_general.gr_check_counting_s_sptr_output_signature(self) <NEW_LINE> <DEDENT> def unique_id(self): <NEW_LINE> <INDENT> return _gnuradio_core_general.gr_check_counting_s_sptr_unique_id(self) <NEW_LINE> <DEDENT> def to_basic_block(self): <NEW_LINE> <INDENT> return _gnuradio_core_general.gr_check_counting_s_sptr_to_basic_block(self) <NEW_LINE> <DEDENT> def check_topology(self, *args, **kwargs): <NEW_LINE> <INDENT> return _gnuradio_core_general.gr_check_counting_s_sptr_check_topology(self, *args, **kwargs) | Proxy of C++ boost::shared_ptr<(gr_check_counting_s)> class | 6259907076e4537e8c3f0e3a |
class Plugin: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def headbar(self, context): <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> def links(self, context): <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> def sidebar(self, context): <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> def tools(self, context, post): <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> def parse(self, value): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> def post_list(self, value, request, user_name): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> def posting(self, request, post): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def posted(self, request, post): <NEW_LINE> <INDENT> pass | Base class for every plugin for sweetter. It provides default
behavior for all the hooks the sweetter core calls. For adding
behavior, just define the methods you want to hook in in the plugin
class. | 62599070283ffb24f3cf5164 |
class ResultsView(generic.DetailView): <NEW_LINE> <INDENT> model = Question <NEW_LINE> template_name = 'polls/results.html' | View for results page. | 625990704e4d562566373cc1 |
class OptDir(Seqable): <NEW_LINE> <INDENT> pass | Only allowed as the last parser (in linear terms). Allows an optional
trailing slash on a URI. | 62599070ad47b63b2c5a9109 |
class RatingRule(UrlRule.UrlRule): <NEW_LINE> <INDENT> def __init__(self, sid=None, titles=None, descriptions=None, disable=0, matchurls=None, nomatchurls=None, use_extern=0): <NEW_LINE> <INDENT> super(RatingRule, self).__init__(sid=sid, titles=titles, descriptions=descriptions, disable=disable, matchurls=matchurls, nomatchurls=nomatchurls) <NEW_LINE> self.rating = Rating() <NEW_LINE> self.url = "" <NEW_LINE> self.use_extern = use_extern <NEW_LINE> self.attrnames.append('use_extern') <NEW_LINE> self.intattrs.append('use_extern') <NEW_LINE> <DEDENT> def fill_attrs(self, attrs, name): <NEW_LINE> <INDENT> super(RatingRule, self).fill_attrs(attrs, name) <NEW_LINE> if name == 'limit': <NEW_LINE> <INDENT> self._name = attrs.get('name') <NEW_LINE> <DEDENT> <DEDENT> def end_data(self, name): <NEW_LINE> <INDENT> super(RatingRule, self).end_data(name) <NEW_LINE> if name == 'limit': <NEW_LINE> <INDENT> self.rating[self._name] = self._data <NEW_LINE> <DEDENT> elif name == 'url': <NEW_LINE> <INDENT> self.url = self._data <NEW_LINE> <DEDENT> <DEDENT> def compile_data(self): <NEW_LINE> <INDENT> super(RatingRule, self).compile_data() <NEW_LINE> self.compile_values() <NEW_LINE> <DEDENT> def compile_values(self): <NEW_LINE> <INDENT> ratingservice.rating_compile(self.rating) <NEW_LINE> self.values = {} <NEW_LINE> for ratingformat in ratingservice.ratingformats: <NEW_LINE> <INDENT> name = ratingformat.name <NEW_LINE> self.values[name] = {} <NEW_LINE> if ratingformat.iterable: <NEW_LINE> <INDENT> for value in ratingformat.values: <NEW_LINE> <INDENT> value = str(value) <NEW_LINE> self.values[name][value] = value == self.rating[name] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def toxml(self): <NEW_LINE> <INDENT> s = u'%s\n use_extern="%d">' % (super(RatingRule, self).toxml(), self.use_extern) <NEW_LINE> s += u"\n"+self.title_desc_toxml(prefix=u" ") <NEW_LINE> if self.matchurls or self.nomatchurls: <NEW_LINE> <INDENT> s += u"\n"+self.matchestoxml(prefix=u" ") <NEW_LINE> <DEDENT> if self.url: <NEW_LINE> <INDENT> s += u"\n <url>%s</url>" % xmlquote(self.url) <NEW_LINE> <DEDENT> for name, value in self.rating.iteritems(): <NEW_LINE> <INDENT> value = xmlquote(str(value)) <NEW_LINE> name = xmlquoteattr(name) <NEW_LINE> s += u"\n <limit name=\"%s\">%s</limit>" % (name, value) <NEW_LINE> <DEDENT> s += u"\n</%s>" % self.name <NEW_LINE> return s | Holds a rating to match against when checking for allowance of
the rating system.
Also stored is the url to display should a rating deny a page.
The use_extern flag determines if the filters should parse and use
external rating data from HTTP headers or HTML <meta> tags. | 625990707047854f46340c72 |
class DataProcessor(object): <NEW_LINE> <INDENT> def get_train_examples(self, data_dir): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def get_dev_examples(self, data_dir): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def get_labels(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _read_tsv(cls, input_file, quotechar=None): <NEW_LINE> <INDENT> data = [] <NEW_LINE> for file in input_file: <NEW_LINE> <INDENT> data += readfile(file) <NEW_LINE> <DEDENT> return data | Base class for data converters for sequence classification data sets. | 6259907055399d3f05627dd4 |
class CalendarLink(ContactsBase): <NEW_LINE> <INDENT> _tag = 'calendarLink' <NEW_LINE> _children = ContactsBase._children.copy() <NEW_LINE> _attributes = ContactsBase._attributes.copy() <NEW_LINE> _attributes['href'] = 'href' <NEW_LINE> _attributes['label'] = 'label' <NEW_LINE> _attributes['primary'] = 'primary' <NEW_LINE> _attributes['rel'] = 'rel' <NEW_LINE> def __init__(self, href=None, label=None, primary='false', rel=None): <NEW_LINE> <INDENT> ContactsBase.__init__(self) <NEW_LINE> self.href = href <NEW_LINE> self.label = label <NEW_LINE> self.primary = primary <NEW_LINE> self.rel = rel | The gContact:calendarLink element. | 625990708e7ae83300eea94c |
@register_class <NEW_LINE> class WorldCup25Id1(WorldCup25): <NEW_LINE> <INDENT> relations_involved = [['场上'], None, ['球员', '球星', '队员', '人'], ['离婚'], ['次数'], ['最'], ['多']] <NEW_LINE> selects = [] | 场上哪个球员离婚次数最多 | 6259907092d797404e3897b9 |
class Map(BinaryOperator): <NEW_LINE> <INDENT> operator = "/@" <NEW_LINE> precedence = 620 <NEW_LINE> grouping = "Right" <NEW_LINE> options = { "Heads": "False", } <NEW_LINE> def apply_invalidlevel(self, f, expr, ls, evaluation, options={}): <NEW_LINE> <INDENT> evaluation.message("Map", "level", ls) <NEW_LINE> <DEDENT> def apply_level(self, f, expr, ls, evaluation, options={}): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> start, stop = python_levelspec(ls) <NEW_LINE> <DEDENT> except InvalidLevelspecError: <NEW_LINE> <INDENT> evaluation.message("Map", "level", ls) <NEW_LINE> return <NEW_LINE> <DEDENT> def callback(level): <NEW_LINE> <INDENT> return Expression(f, level) <NEW_LINE> <DEDENT> heads = self.get_option(options, "Heads", evaluation).is_true() <NEW_LINE> result, depth = walk_levels(expr, start, stop, heads=heads, callback=callback) <NEW_LINE> return result | <dl>
<dt>'Map[$f$, $expr$]' or '$f$ /@ $expr$'
<dd>applies $f$ to each part on the first level of $expr$.
<dt>'Map[$f$, $expr$, $levelspec$]'
<dd>applies $f$ to each level specified by $levelspec$ of $expr$.
</dl>
>> f /@ {1, 2, 3}
= {f[1], f[2], f[3]}
>> #^2& /@ {1, 2, 3, 4}
= {1, 4, 9, 16}
Map $f$ on the second level:
>> Map[f, {{a, b}, {c, d, e}}, {2}]
= {{f[a], f[b]}, {f[c], f[d], f[e]}}
Include heads:
>> Map[f, a + b + c, Heads->True]
= f[Plus][f[a], f[b], f[c]]
#> Map[f, expr, a+b, Heads->True]
: Level specification a + b is not of the form n, {n}, or {m, n}.
= Map[f, expr, a + b, Heads -> True] | 62599070a17c0f6771d5d808 |
class CodeBreakpoint (Breakpoint): <NEW_LINE> <INDENT> typeName = 'code breakpoint' <NEW_LINE> if win32.arch in (win32.ARCH_I386, win32.ARCH_AMD64): <NEW_LINE> <INDENT> bpInstruction = b'\xCC' <NEW_LINE> <DEDENT> def __init__(self, address, condition = True, action = None): <NEW_LINE> <INDENT> if win32.arch not in (win32.ARCH_I386, win32.ARCH_AMD64): <NEW_LINE> <INDENT> msg = "Code breakpoints not supported for %s" % win32.arch <NEW_LINE> raise NotImplementedError(msg) <NEW_LINE> <DEDENT> Breakpoint.__init__(self, address, len(self.bpInstruction), condition, action) <NEW_LINE> self.__previousValue = self.bpInstruction <NEW_LINE> <DEDENT> def __set_bp(self, aProcess): <NEW_LINE> <INDENT> address = self.get_address() <NEW_LINE> self.__previousValue = aProcess.read(address, len(self.bpInstruction)) <NEW_LINE> if self.__previousValue == self.bpInstruction: <NEW_LINE> <INDENT> msg = "Possible overlapping code breakpoints at %s" <NEW_LINE> msg = msg % HexDump.address(address) <NEW_LINE> warnings.warn(msg, BreakpointWarning) <NEW_LINE> <DEDENT> aProcess.write(address, self.bpInstruction) <NEW_LINE> <DEDENT> def __clear_bp(self, aProcess): <NEW_LINE> <INDENT> address = self.get_address() <NEW_LINE> currentValue = aProcess.read(address, len(self.bpInstruction)) <NEW_LINE> if currentValue == self.bpInstruction: <NEW_LINE> <INDENT> aProcess.write(self.get_address(), self.__previousValue) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__previousValue = currentValue <NEW_LINE> msg = "Overwritten code breakpoint at %s" <NEW_LINE> msg = msg % HexDump.address(address) <NEW_LINE> warnings.warn(msg, BreakpointWarning) <NEW_LINE> <DEDENT> <DEDENT> def disable(self, aProcess, aThread): <NEW_LINE> <INDENT> if not self.is_disabled() and not self.is_running(): <NEW_LINE> <INDENT> self.__clear_bp(aProcess) <NEW_LINE> <DEDENT> super(CodeBreakpoint, self).disable(aProcess, aThread) <NEW_LINE> <DEDENT> def enable(self, aProcess, aThread): <NEW_LINE> <INDENT> if not self.is_enabled() and not self.is_one_shot(): <NEW_LINE> <INDENT> self.__set_bp(aProcess) <NEW_LINE> <DEDENT> super(CodeBreakpoint, self).enable(aProcess, aThread) <NEW_LINE> <DEDENT> def one_shot(self, aProcess, aThread): <NEW_LINE> <INDENT> if not self.is_enabled() and not self.is_one_shot(): <NEW_LINE> <INDENT> self.__set_bp(aProcess) <NEW_LINE> <DEDENT> super(CodeBreakpoint, self).one_shot(aProcess, aThread) <NEW_LINE> <DEDENT> def running(self, aProcess, aThread): <NEW_LINE> <INDENT> if self.is_enabled(): <NEW_LINE> <INDENT> self.__clear_bp(aProcess) <NEW_LINE> aThread.set_tf() <NEW_LINE> <DEDENT> super(CodeBreakpoint, self).running(aProcess, aThread) | Code execution breakpoints (using an int3 opcode).
@see: L{Debug.break_at}
@type bpInstruction: str
@cvar bpInstruction: Breakpoint instruction for the current processor. | 6259907067a9b606de547701 |
class AsyncExecutor(): <NEW_LINE> <INDENT> DEFAULT_WORKERS = utils.get_env_as('STREAMLINE_WORKER_COUNT', int, default=20) <NEW_LINE> def __init__(self, executor=None, workers=DEFAULT_WORKERS, loop=None): <NEW_LINE> <INDENT> self.executor = executor <NEW_LINE> self.output_queue = asyncio.Queue() <NEW_LINE> self.worker_count = workers or self.DEFAULT_WORKERS <NEW_LINE> self.entry_count = 0 <NEW_LINE> self.complete_count = 0 <NEW_LINE> self.active_count = 0 <NEW_LINE> self.loop = loop or asyncio.get_event_loop() <NEW_LINE> <DEDENT> def _save_result(self, entry): <NEW_LINE> <INDENT> self.complete_count += 1 <NEW_LINE> self.output_queue.put_nowait(entry) <NEW_LINE> <DEDENT> async def stream(self, source): <NEW_LINE> <INDENT> self.source = source <NEW_LINE> all_read = False <NEW_LINE> pending = 0 <NEW_LINE> next_input = None <NEW_LINE> next_output = None <NEW_LINE> while True: <NEW_LINE> <INDENT> if all_read and pending == 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if not next_input and not all_read and pending < self.worker_count: <NEW_LINE> <INDENT> next_input = asyncio.create_task(self.source.__anext__()) <NEW_LINE> <DEDENT> if not next_output: <NEW_LINE> <INDENT> next_output = asyncio.create_task(self.output_queue.get()) <NEW_LINE> <DEDENT> awaitables = [aw for aw in (next_input, next_output) if aw] <NEW_LINE> tasks_done, tasks_pending = await asyncio.wait(awaitables, return_when=asyncio.FIRST_COMPLETED) <NEW_LINE> if next_input in tasks_done: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> entry = next_input.result() <NEW_LINE> next_input = None <NEW_LINE> entry_future = asyncio.create_task(self.handle(entry)) <NEW_LINE> pending += 1 <NEW_LINE> <DEDENT> except StopAsyncIteration: <NEW_LINE> <INDENT> all_read = True <NEW_LINE> <DEDENT> <DEDENT> if next_output in tasks_done: <NEW_LINE> <INDENT> pending -= 1 <NEW_LINE> yield next_output.result() <NEW_LINE> self.output_queue.task_done() <NEW_LINE> next_output = None <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> async def handle(self, entry): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if asyncio.iscoroutinefunction(self.executor): <NEW_LINE> <INDENT> entry.value = await self.executor(entry.value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> def executor_wrapper(): <NEW_LINE> <INDENT> return self.executor(entry.value) <NEW_LINE> <DEDENT> entry.value = await self.loop.run_in_executor(None, executor_wrapper) <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> entry.error(e) <NEW_LINE> <DEDENT> self._save_result(entry) <NEW_LINE> self.active_count -= 1 | :: Worker-oriented event loop processor
Workers are no longer a necessary concept in an asynchronous world. However, the concept can still be very
helpful for controlling resource usage on the host machine or remote systems used by the job. For this reason
I'm re-implementing a worker-style executor pool which could be used with jobs that are threaded or async. | 625990701f5feb6acb1644ae |
class Character(Enum): <NEW_LINE> <INDENT> MARIO = 0x00 <NEW_LINE> FOX = 0x01 <NEW_LINE> CPTFALCON = 0x02 <NEW_LINE> DK = 0x03 <NEW_LINE> KIRBY = 0x04 <NEW_LINE> BOWSER = 0x05 <NEW_LINE> LINK = 0x06 <NEW_LINE> SHEIK = 0x07 <NEW_LINE> NESS = 0x08 <NEW_LINE> PEACH = 0x09 <NEW_LINE> POPO = 0x0a <NEW_LINE> NANA = 0x0b <NEW_LINE> PIKACHU = 0x0c <NEW_LINE> SAMUS = 0x0d <NEW_LINE> YOSHI = 0x0e <NEW_LINE> JIGGLYPUFF = 0x0f <NEW_LINE> MEWTWO = 0x10 <NEW_LINE> LUIGI = 0x11 <NEW_LINE> MARTH = 0x12 <NEW_LINE> ZELDA = 0x13 <NEW_LINE> YLINK = 0x14 <NEW_LINE> DOC = 0x15 <NEW_LINE> FALCO = 0x16 <NEW_LINE> PICHU = 0x17 <NEW_LINE> GAMEANDWATCH = 0x18 <NEW_LINE> GANONDORF = 0x19 <NEW_LINE> ROY = 0x1a <NEW_LINE> WIREFRAME_MALE = 0x1d <NEW_LINE> WIREFRAME_FEMALE = 0x1e <NEW_LINE> GIGA_BOWSER = 0x1f <NEW_LINE> SANDBAG = 0x20 <NEW_LINE> UNKNOWN_CHARACTER = 0xff | A Melee character ID.
Note:
Numeric values are 'internal' IDs. | 625990704c3428357761bb71 |
class ListEnv(cli.CLI): <NEW_LINE> <INDENT> name = 'list' <NEW_LINE> def setup_parser(self, parser): <NEW_LINE> <INDENT> parser.add_argument( 'filters', help='Environment filters like --name="My*".', nargs=argparse.REMAINDER, ) <NEW_LINE> <DEDENT> def parse_filters(self, filters): <NEW_LINE> <INDENT> pattern = ( r'-{1,2}(?P<param>[a-zA-Z0-9_]+)=*\s*' r'"?(?P<value>.+)"?' ) <NEW_LINE> kwargs = {} <NEW_LINE> for arg in filters: <NEW_LINE> <INDENT> match = re.search(pattern, arg) <NEW_LINE> param = match.group('param') <NEW_LINE> raw_value = '"%s"' % match.group('value').strip() <NEW_LINE> value = cli.safe_eval(raw_value) <NEW_LINE> kwargs[param] = value <NEW_LINE> <DEDENT> return kwargs <NEW_LINE> <DEDENT> def run(self, args): <NEW_LINE> <INDENT> filters = self.parse_filters(args.filters) <NEW_LINE> cli.echo() <NEW_LINE> found_environments = False <NEW_LINE> for repo in api.get_repos(): <NEW_LINE> <INDENT> environments = repo.list_environments(filters) <NEW_LINE> env_names = sorted([env.name for env in environments]) <NEW_LINE> if env_names: <NEW_LINE> <INDENT> found_environments = True <NEW_LINE> if repo.name != repo.path: <NEW_LINE> <INDENT> header = repo.name + ' - ' + repo.path <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> header = repo.name <NEW_LINE> <DEDENT> cli.echo(cli.format_columns( header, env_names, indent=' ', )) <NEW_LINE> cli.echo() <NEW_LINE> <DEDENT> <DEDENT> if not found_environments: <NEW_LINE> <INDENT> cli.echo('No Environments are were found.') <NEW_LINE> cli.echo('Use "cpenv env save <name>" to save an Environment.') | List available Environments.
Environments are like Aliases for a list of module requirements. They
can be Activated using a single name rather than providing a full list of
module requirements. | 62599070796e427e53850035 |
class DetailedUserSchema(BaseUserSchema): <NEW_LINE> <INDENT> class Meta(BaseUserSchema.Meta): <NEW_LINE> <INDENT> fields = BaseUserSchema.Meta.fields + ( User.email.key, User.created.key, User.updated.key, User.is_active.fget.__name__, User.is_readonly.fget.__name__, User.is_admin.fget.__name__, ) | Detailed user schema exposes all useful fields. | 62599070d486a94d0ba2d87b |
class CnnL2h128(DnaModel): <NEW_LINE> <INDENT> def __init__(self, nb_hidden=128, *args, **kwargs): <NEW_LINE> <INDENT> super(CnnL2h128, self).__init__(*args, **kwargs) <NEW_LINE> self.nb_hidden = nb_hidden <NEW_LINE> <DEDENT> def __call__(self, inputs): <NEW_LINE> <INDENT> x = inputs[0] <NEW_LINE> kernel_regularizer = kr.L1L2(l1=self.l1_decay, l2=self.l2_decay) <NEW_LINE> x = kl.Conv1D(128, 11, kernel_initializer=self.init, kernel_regularizer=kernel_regularizer)(x) <NEW_LINE> x = kl.Activation('relu')(x) <NEW_LINE> x = kl.MaxPooling1D(4)(x) <NEW_LINE> kernel_regularizer = kr.L1L2(l1=self.l1_decay, l2=self.l2_decay) <NEW_LINE> x = kl.Conv1D(256, 3, kernel_initializer=self.init, kernel_regularizer=kernel_regularizer)(x) <NEW_LINE> x = kl.Activation('relu')(x) <NEW_LINE> x = kl.MaxPooling1D(2)(x) <NEW_LINE> x = kl.Flatten()(x) <NEW_LINE> kernel_regularizer = kr.L1L2(l1=self.l1_decay, l2=self.l2_decay) <NEW_LINE> x = kl.Dense(self.nb_hidden, kernel_initializer=self.init, kernel_regularizer=kernel_regularizer)(x) <NEW_LINE> x = kl.Activation('relu')(x) <NEW_LINE> x = kl.Dropout(self.dropout)(x) <NEW_LINE> return self._build(inputs, x) | CNN with two convolutional and one fully-connected layer with 128 units.
.. code::
Parameters: 4,100,000
Specification: conv[128@11]_mp[4]_conv[256@3]_mp[2]_fc[128]_do | 62599070ac7a0e7691f73da5 |
class ArrayDataset: <NEW_LINE> <INDENT> def __init__(self, dataset_name): <NEW_LINE> <INDENT> data = np.load(dataset_name) <NEW_LINE> self.items = data["imgs"], data['gtLandmarks'] <NEW_LINE> <DEDENT> def __call__(self, batch_size, shuffle, repeat_num): <NEW_LINE> <INDENT> imgs, gt = self.items <NEW_LINE> img_dataset = tf.data.Dataset.from_tensor_slices(imgs) <NEW_LINE> gt_dataset = tf.data.Dataset.from_tensor_slices(gt) <NEW_LINE> dataset = tf.data.Dataset.zip((img_dataset, gt_dataset)) <NEW_LINE> if shuffle: <NEW_LINE> <INDENT> dataset = dataset.shuffle(buffer_size=1000) <NEW_LINE> <DEDENT> dataset = dataset.batch(batch_size).repeat(repeat_num) <NEW_LINE> dataset = dataset.prefetch(1) <NEW_LINE> return dataset <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.items[0]) | Creates an instance of tf.data.Dataset from numpy Array in a npz file generated by DAN's ImageServer
See https://github.com/MarekKowalski/DeepAlignmentNetwork/blob/master/DeepAlignmentNetwork/ImageServer.py | 62599070fff4ab517ebcf0d7 |
class AddressCandidates(list): <NEW_LINE> <INDENT> last_processed = None <NEW_LINE> def sort_by_correctness_precision(self): <NEW_LINE> <INDENT> self.sort(lambda a, b: cmp(b.correctness_rank + b.precision_rank, a.correctness_rank + a.precision_rank)) <NEW_LINE> AddressCandidates.last_processed = self <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> r = u"" <NEW_LINE> for candidate in self: <NEW_LINE> <INDENT> r += u"{0}[c:{1},p:{2}] ".format(candidate.address, candidate.correctness_rank, candidate.precision_rank) <NEW_LINE> <DEDENT> return r | List of address candidates extrated from source string. | 6259907055399d3f05627dd5 |
class BaseConfig(object): <NEW_LINE> <INDENT> DEBUG = False <NEW_LINE> TESTING = False <NEW_LINE> SECRET_KEY = os.environ.get( 'SECRET_KEY', '\xa6TQ5\xc9\xf942\x9cx\x9b\xed\xa4\xc7\x95\xcc\xfd\xb8Q\xa1\x80\x99Z%') <NEW_LINE> WTF_CSRF_SECRET_KEY = os.environ.get( 'WTF_CSRF_SECRET_KEY', '\xc9\xcc\x91{\xd9\x9a\x18\x92\xaa\xb4\x9e\x80\x07\x13\x92-\x1ciH\x86\xecz:[') <NEW_LINE> SQLALCHEMY_TRACK_MODIFICATIONS = False <NEW_LINE> if not os.path.isdir('db/sqlite'): <NEW_LINE> <INDENT> os.makedirs('db/sqlite') <NEW_LINE> <DEDENT> SQLALCHEMY_DATABASE_URI = os.environ.get( 'DATABASE_URL', 'sqlite:///' + os.path.join(basedir, 'db/sqlite/myapp.db')) <NEW_LINE> google_client_id, google_client_secret = get_secrets_from_json( provider_name='google', filename=os.path.join( basedir, 'myapp/oauth2/google_client_secrets.json')) <NEW_LINE> facebook_app_id, facebook_app_secret = get_secrets_from_json( provider_name='facebook', filename=os.path.join( basedir, 'myapp/oauth2/facebook_client_secrets.json')) <NEW_LINE> OAUTH2_PROVIDERS = { 'google': { 'client_id': google_client_id, 'client_secret': google_client_secret }, 'facebook': { 'client_id': facebook_app_id, 'client_secret': facebook_app_secret } } | BaseConfig holds the default configuration for myapp
Use environmental variables, consider autoenv
export APP_SETTINGS="config.DevConfig"
app.config.from_object(os.environ['APP_SETTINGS'])
http://flask.pocoo.org/docs/0.12/config/ | 6259907091f36d47f2231aed |
class UI(): <NEW_LINE> <INDENT> def __init__(self, client): <NEW_LINE> <INDENT> self.client = client <NEW_LINE> self.keep_running = True <NEW_LINE> <DEDENT> def startEventLoop(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> while self.keep_running: <NEW_LINE> <INDENT> self.client.tick() <NEW_LINE> time.sleep(0.1) <NEW_LINE> <DEDENT> <DEDENT> except KeyboardInterrupt: <NEW_LINE> <INDENT> pass | Headless implementation of the UI interface. | 625990701f037a2d8b9e54c9 |
class Solution: <NEW_LINE> <INDENT> def checkValidString(self, s): <NEW_LINE> <INDENT> return self.dfs(s, 0, 0) <NEW_LINE> <DEDENT> def dfs(self, s, idx, left_count): <NEW_LINE> <INDENT> if left_count < 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if idx == len(s): <NEW_LINE> <INDENT> return left_count == 0 <NEW_LINE> <DEDENT> if s[idx] == "*": <NEW_LINE> <INDENT> return self.dfs(s, idx + 1, left_count + 1) or self.dfs(s, idx + 1, left_count - 1) or self.dfs(s, idx + 1, left_count) <NEW_LINE> <DEDENT> if s[idx] == "(": <NEW_LINE> <INDENT> left_count += 1 <NEW_LINE> <DEDENT> if s[idx] == ")": <NEW_LINE> <INDENT> left_count -= 1 <NEW_LINE> <DEDENT> return self.dfs(s, idx + 1, left_count) | @param s: the given string
@return: whether this string is valid | 625990700a50d4780f706a20 |
class TLoopPerspective(Perspective): <NEW_LINE> <INDENT> name = 'Time Loop' <NEW_LINE> enabled = True <NEW_LINE> show_editor_area = True <NEW_LINE> TLOOPMNGR_VIEW = 'ibvpy.plugins.tloop_service.tloop_service' <NEW_LINE> contents = [ PerspectiveItem(id=TLOOPMNGR_VIEW, position='left'), ] | An default perspective for the app. | 6259907197e22403b383c7c1 |
class ComReadAndxResponse(Payload): <NEW_LINE> <INDENT> PAYLOAD_STRUCT_FORMAT = '<BBHHHHHHHHHHH' <NEW_LINE> PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) <NEW_LINE> def decode(self, message): <NEW_LINE> <INDENT> assert message.command == SMB_COM_READ_ANDX <NEW_LINE> if not message.status.hasError: <NEW_LINE> <INDENT> if len(message.parameters_data) < self.PAYLOAD_STRUCT_SIZE: <NEW_LINE> <INDENT> raise ProtocolError('Not enough data to decode SMB_COM_READ_ANDX parameters', message.raw_data, message) <NEW_LINE> <DEDENT> _, _, _, _, _, _, self.data_length, data_offset, _, _, _, _, _ = struct.unpack(self.PAYLOAD_STRUCT_FORMAT, message.parameters_data[:self.PAYLOAD_STRUCT_SIZE]) <NEW_LINE> offset = data_offset - message.HEADER_STRUCT_SIZE - self.PAYLOAD_STRUCT_SIZE - 2 <NEW_LINE> self.data = message.data[offset:offset+self.data_length] <NEW_LINE> assert len(self.data) == self.data_length | References:
===========
- [MS-CIFS]: 2.2.4.42.2
- [MS-SMB]: 2.2.4.2.2 | 62599071dd821e528d6da5e0 |
class FcNet(nn.Module): <NEW_LINE> <INDENT> def __init__(self, input_dim, hidden_dims, output_dim, stdv=None, dropout_p=0.0): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.input_dim = input_dim <NEW_LINE> self.hidden_dims = hidden_dims <NEW_LINE> self.output_dim = output_dim <NEW_LINE> self.dropout_p = dropout_p <NEW_LINE> self.dims = [self.input_dim] <NEW_LINE> self.dims.extend(hidden_dims) <NEW_LINE> self.dims.append(self.output_dim) <NEW_LINE> self.layers = nn.ModuleList([]) <NEW_LINE> for i in range(len(self.dims) - 1): <NEW_LINE> <INDENT> ip_dim = self.dims[i] <NEW_LINE> op_dim = self.dims[i + 1] <NEW_LINE> self.layers.append( nn.Linear(ip_dim, op_dim, bias=True) ) <NEW_LINE> <DEDENT> self.__init_net_weights__(stdv) <NEW_LINE> <DEDENT> def __init_net_weights__(self, stdv): <NEW_LINE> <INDENT> if stdv == -1: <NEW_LINE> <INDENT> for m in self.layers: <NEW_LINE> <INDENT> m.weight.data.normal_(0.0, 0.1) <NEW_LINE> m.bias.data.fill_(0.1) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for m in self.layers: <NEW_LINE> <INDENT> if stdv is None: <NEW_LINE> <INDENT> stdv = 1. / math.sqrt(m.weight.size(1)) <NEW_LINE> <DEDENT> m.weight.data.uniform_(-stdv, stdv) <NEW_LINE> if m.bias is not None: <NEW_LINE> <INDENT> m.bias.data.uniform_(-stdv, stdv) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> x = x.view(-1, self.input_dim) <NEW_LINE> for i, layer in enumerate(self.layers): <NEW_LINE> <INDENT> x = layer(x) <NEW_LINE> if i < (len(self.layers) - 1): <NEW_LINE> <INDENT> x = F.relu(x) <NEW_LINE> <DEDENT> if i < (len(self.layers) - 1): <NEW_LINE> <INDENT> x = F.dropout(x, p=self.dropout_p, training=self.training) <NEW_LINE> <DEDENT> <DEDENT> return x | Fully connected network for MNIST classification | 625990717b25080760ed8942 |
class TargetedPlacer(Placer): <NEW_LINE> <INDENT> def check(self): <NEW_LINE> <INDENT> self.requireTarget() <NEW_LINE> validators.validate_data(self.metadata, 'file.json', 'input', 'POST', optional=True) <NEW_LINE> <DEDENT> def process_file_field(self, field, file_attrs): <NEW_LINE> <INDENT> if self.metadata: <NEW_LINE> <INDENT> file_attrs.update(self.metadata) <NEW_LINE> <DEDENT> self.save_file(field, file_attrs) <NEW_LINE> self.saved.append(file_attrs) <NEW_LINE> <DEDENT> def finalize(self): <NEW_LINE> <INDENT> self.recalc_session_compliance() <NEW_LINE> return self.saved | A placer that can accept 1 file to a specific container (acquisition, etc). | 62599071a17c0f6771d5d809 |
class RedisDict(BaseStorage): <NEW_LINE> <INDENT> def __init__(self, namespace: str, collection_name: str = None, connection=None, **kwargs): <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> connection_kwargs = get_valid_kwargs(Redis, kwargs) <NEW_LINE> self.connection = connection or StrictRedis(**connection_kwargs) <NEW_LINE> self.namespace = namespace <NEW_LINE> <DEDENT> def _bkey(self, key: str) -> bytes: <NEW_LINE> <INDENT> return encode(f'{self.namespace}:{key}') <NEW_LINE> <DEDENT> def _bkeys(self, keys: Iterable[str]): <NEW_LINE> <INDENT> return [self._bkey(key) for key in keys] <NEW_LINE> <DEDENT> def __contains__(self, key) -> bool: <NEW_LINE> <INDENT> return bool(self.connection.exists(self._bkey(key))) <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> result = self.connection.get(self._bkey(key)) <NEW_LINE> if result is None: <NEW_LINE> <INDENT> raise KeyError <NEW_LINE> <DEDENT> return self.serializer.loads(result) <NEW_LINE> <DEDENT> def __setitem__(self, key, item): <NEW_LINE> <INDENT> if getattr(item, 'ttl', None): <NEW_LINE> <INDENT> self.connection.setex(self._bkey(key), item.ttl, self.serializer.dumps(item)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.connection.set(self._bkey(key), self.serializer.dumps(item)) <NEW_LINE> <DEDENT> <DEDENT> def __delitem__(self, key): <NEW_LINE> <INDENT> if not self.connection.delete(self._bkey(key)): <NEW_LINE> <INDENT> raise KeyError <NEW_LINE> <DEDENT> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> yield from self.keys() <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(list(self.keys())) <NEW_LINE> <DEDENT> def bulk_delete(self, keys: Iterable[str]): <NEW_LINE> <INDENT> if keys: <NEW_LINE> <INDENT> self.connection.delete(*self._bkeys(keys)) <NEW_LINE> <DEDENT> <DEDENT> def clear(self): <NEW_LINE> <INDENT> self.bulk_delete(self.keys()) <NEW_LINE> <DEDENT> def keys(self): <NEW_LINE> <INDENT> return [ decode(key).replace(f'{self.namespace}:', '') for key in self.connection.keys(f'{self.namespace}:*') ] <NEW_LINE> <DEDENT> def items(self): <NEW_LINE> <INDENT> return [(k, self[k]) for k in self.keys()] <NEW_LINE> <DEDENT> def values(self): <NEW_LINE> <INDENT> return [self.serializer.loads(v) for v in self.connection.mget(*self._bkeys(self.keys()))] | A dictionary-like interface for Redis operations.
**Notes:**
* All keys will be encoded as bytes, and all values will be serialized
* Supports TTL | 62599071435de62698e9d6c4 |
class fast: <NEW_LINE> <INDENT> iden = None <NEW_LINE> comment = None <NEW_LINE> seq = None <NEW_LINE> qual = [] | This class contains the string values for identity, comment and bases of an individual sequence.
Quality scores of the sequence are kept in a list, maintaining order of corresponding bases | 62599071d268445f2663a7bc |
class UndoGenericQtmacsScintilla(QtmacsUndoCommand): <NEW_LINE> <INDENT> @type_check <NEW_LINE> def __init__(self, qteWidget): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.qteWidget = qteWidget <NEW_LINE> self.baseClass = super(type(qteWidget), qteWidget) <NEW_LINE> self.textAfter = None <NEW_LINE> line, col = self.qteWidget.getNumLinesAndColumns() <NEW_LINE> text, style = self.qteWidget.SCIGetStyledText((0, 0, line, col)) <NEW_LINE> self.styleBefore = style <NEW_LINE> self.textBefore = text.decode('utf-8') <NEW_LINE> self.origPosition = self.qteWidget.getCursorPosition() <NEW_LINE> <DEDENT> def placeCursor(self, line, col): <NEW_LINE> <INDENT> num_lines, num_col = self.qteWidget.getNumLinesAndColumns() <NEW_LINE> if line >= num_lines: <NEW_LINE> <INDENT> line, col = num_lines, num_col <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> text = self.qteWidget.text(line) <NEW_LINE> if col >= len(text): <NEW_LINE> <INDENT> col = len(text) - 1 <NEW_LINE> <DEDENT> <DEDENT> self.qteWidget.setCursorPosition(line, col) <NEW_LINE> <DEDENT> def commit(self): <NEW_LINE> <INDENT> if self.textAfter is None: <NEW_LINE> <INDENT> line, col = self.qteWidget.getNumLinesAndColumns() <NEW_LINE> text, style = self.qteWidget.SCIGetStyledText((0, 0, line, col)) <NEW_LINE> self.styleAfter = style <NEW_LINE> self.textAfter = text.decode('utf-8') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.baseClass.setText(self.textAfter) <NEW_LINE> self.qteWidget.SCISetStylingEx(0, 0, self.styleAfter) <NEW_LINE> <DEDENT> self.placeCursor(*self.origPosition) <NEW_LINE> <DEDENT> def reverseCommit(self): <NEW_LINE> <INDENT> self.baseClass.setText(self.textBefore) <NEW_LINE> self.qteWidget.SCISetStylingEx(0, 0, self.styleBefore) | Generic undo-object to revert an arbitrary change in the document.
This undo command takes snapshot of the current document state
(including style) at instantiation, and a second snapshot at
the time it is pushed onto the stack.
Example::
# Instantiate the undo object to get a snapshot.
undoObj = UndoGenericQtmacsScintilla(self.qteWidget)
# ... arbitrary changes to the text in self.qteWidget.
# Push the undo object to automatically generate another
# snapshot.
self.qteWidget.qteUndoStack.push(undoObj)
|Args|
* ``qteWidget`` (**QWidget**): the widget to use.
|Raises|
* **QtmacsArgumentError** if at least one argument has an invalid type. | 625990718a43f66fc4bf3a52 |
class ContainsTests(TestCase): <NEW_LINE> <INDENT> def test_returns_true_if_first_value_contains_second_value(self): <NEW_LINE> <INDENT> self.assertTrue(fl.contains('go team', 'team')) <NEW_LINE> <DEDENT> def test_returns_true_if_first_list_contains_second_list(self): <NEW_LINE> <INDENT> self.assertTrue(fl.contains([1, 2], 2)) <NEW_LINE> <DEDENT> def test_returns_false_if_first_value_does_not_contain_second(self): <NEW_LINE> <INDENT> self.assertFalse(fl.contains([1, 2], 3)) | FieldLookup.contains() | 625990718e7ae83300eea94f |
class ArgManager(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.parser = argparse.ArgumentParser( description="Manage apollo data recording.") <NEW_LINE> self.parser.add_argument('--start', default=False, action="store_true", help='Start recorder. It is the default ' 'action if no other actions are triggered. In ' 'that case, the False value is ignored.') <NEW_LINE> self.parser.add_argument('--stop', default=False, action="store_true", help='Stop recorder.') <NEW_LINE> self.parser.add_argument('--additional_topics', action='append', help='Record additional topics.') <NEW_LINE> self.parser.add_argument('--all', default=False, action="store_true", help='Record all topics even without high ' 'performance disks.') <NEW_LINE> self.parser.add_argument('--small', default=False, action="store_true", help='Record samll topics only.') <NEW_LINE> self.parser.add_argument('--split_duration', default="1m", help='Duration to split bags, will be applied ' 'as parameter to "rosbag record --duration".') <NEW_LINE> self._args = None <NEW_LINE> <DEDENT> def args(self): <NEW_LINE> <INDENT> if self._args is None: <NEW_LINE> <INDENT> self._args = self.parser.parse_args() <NEW_LINE> <DEDENT> return self._args | Arguments manager. | 62599071ec188e330fdfa161 |
class StdCellTemplate(StdCellBase): <NEW_LINE> <INDENT> def __init__(self, temp_db, lib_name, params, used_names, **kwargs): <NEW_LINE> <INDENT> StdCellBase.__init__(self, temp_db, lib_name, params, used_names, **kwargs) <NEW_LINE> self._sch_params = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def sch_params(self): <NEW_LINE> <INDENT> return self._sch_params <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_params_info(cls): <NEW_LINE> <INDENT> return dict( cell_name='standard cell cell name.', config_file='standard cell configuration file name.', ) <NEW_LINE> <DEDENT> def get_layout_basename(self): <NEW_LINE> <INDENT> return 'stdcell_%s' % self.params['cell_name'] <NEW_LINE> <DEDENT> def compute_unique_key(self): <NEW_LINE> <INDENT> cell_params = self.get_cell_params(self.params['cell_name']) <NEW_LINE> return 'stdcell_%s_%s' % (cell_params['lib_name'], cell_params['cell_name']) <NEW_LINE> <DEDENT> def get_sch_master_info(self): <NEW_LINE> <INDENT> cell_params = self.get_cell_params(self.params['cell_name']) <NEW_LINE> return cell_params['lib_name'], cell_params['cell_name'] <NEW_LINE> <DEDENT> def draw_layout(self): <NEW_LINE> <INDENT> cell_params = self.get_cell_params(self.params['cell_name']) <NEW_LINE> lib_name = cell_params['lib_name'] <NEW_LINE> cell_name = cell_params['cell_name'] <NEW_LINE> size = cell_params['size'] <NEW_LINE> ports = cell_params['ports'] <NEW_LINE> self.update_routing_grid() <NEW_LINE> self.add_instance_primitive(lib_name, cell_name, (0, 0)) <NEW_LINE> self.set_std_size(size) <NEW_LINE> res = self.grid.resolution <NEW_LINE> for port_name, pin_list in ports.items(): <NEW_LINE> <INDENT> for pin in pin_list: <NEW_LINE> <INDENT> port_lay_id = pin['layer'] <NEW_LINE> bbox = pin['bbox'] <NEW_LINE> layer_dir = self.grid.get_direction(port_lay_id) <NEW_LINE> if layer_dir == 'x': <NEW_LINE> <INDENT> intv = bbox[1], bbox[3] <NEW_LINE> lower, upper = bbox[0], bbox[2] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> intv = bbox[0], bbox[2] <NEW_LINE> lower, upper = bbox[1], bbox[3] <NEW_LINE> <DEDENT> tr_idx, tr_w = self.grid.interval_to_track(port_lay_id, intv) <NEW_LINE> warr = WireArray(TrackID(port_lay_id, tr_idx, width=tr_w), lower, upper, res=res, unit_mode=False) <NEW_LINE> self.add_pin(port_name, warr, show=False) <NEW_LINE> <DEDENT> <DEDENT> self._sch_params = cell_params.get('sch_params', None) | A template wrapper around a standard cell block.
Parameters
----------
temp_db : TemplateDB
the template database.
lib_name : str
the layout library name.
params : Dict[str, Any]
the parameter values.
used_names : Set[str]
a set of already used cell names.
**kwargs :
dictionary of optional parameters. See documentation of
:class:`bag.layout.template.TemplateBase` for details. | 62599071baa26c4b54d50b69 |
class EncryptionServices(Model): <NEW_LINE> <INDENT> _validation = { 'table': {'readonly': True}, 'queue': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'blob': {'key': 'blob', 'type': 'EncryptionService'}, 'file': {'key': 'file', 'type': 'EncryptionService'}, 'table': {'key': 'table', 'type': 'EncryptionService'}, 'queue': {'key': 'queue', 'type': 'EncryptionService'}, } <NEW_LINE> def __init__(self, *, blob=None, file=None, **kwargs) -> None: <NEW_LINE> <INDENT> super(EncryptionServices, self).__init__(**kwargs) <NEW_LINE> self.blob = blob <NEW_LINE> self.file = file <NEW_LINE> self.table = None <NEW_LINE> self.queue = None | A list of services that support encryption.
Variables are only populated by the server, and will be ignored when
sending a request.
:param blob: The encryption function of the blob storage service.
:type blob:
~azure.mgmt.storage.v2018_03_01_preview.models.EncryptionService
:param file: The encryption function of the file storage service.
:type file:
~azure.mgmt.storage.v2018_03_01_preview.models.EncryptionService
:ivar table: The encryption function of the table storage service.
:vartype table:
~azure.mgmt.storage.v2018_03_01_preview.models.EncryptionService
:ivar queue: The encryption function of the queue storage service.
:vartype queue:
~azure.mgmt.storage.v2018_03_01_preview.models.EncryptionService | 6259907132920d7e50bc7905 |
class DataMyneSplitDateTimeWidget(MultiWidget): <NEW_LINE> <INDENT> def __init__(self, attrs=None, date_format=None, time_format=None): <NEW_LINE> <INDENT> date_class = attrs['date_class'] <NEW_LINE> time_class = attrs['time_class'] <NEW_LINE> del attrs['date_class'] <NEW_LINE> del attrs['time_class'] <NEW_LINE> time_attrs = attrs.copy() <NEW_LINE> time_attrs['class'] = time_class <NEW_LINE> date_attrs = attrs.copy() <NEW_LINE> date_attrs['class'] = date_class <NEW_LINE> widgets = (DateInput(attrs=date_attrs, format=date_format), TimeInput(attrs=time_attrs), ) <NEW_LINE> super(DataMyneSplitDateTimeWidget, self).__init__(widgets, attrs) <NEW_LINE> <DEDENT> def decompress(self, value): <NEW_LINE> <INDENT> if value: <NEW_LINE> <INDENT> d = strftime("%Y-%m-%d", value.timetuple()) <NEW_LINE> t = strftime("%H:%M", value.timetuple()) <NEW_LINE> return (d, t) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (None, None) <NEW_LINE> <DEDENT> <DEDENT> def format_output(self, rendered_widgets): <NEW_LINE> <INDENT> return "Date: %s<br/>Time: %s" % (rendered_widgets[0], rendered_widgets[1]) <NEW_LINE> <DEDENT> class Media: <NEW_LINE> <INDENT> css = ( "js/jquery-ui-timepicker.css", ) <NEW_LINE> js = ( "js/jquery.ui.timepicker.js", ) | based on: http://copiesofcopies.org/webl/2010/04/26/a-better-datetime-widget-for-django/ | 625990715fdd1c0f98e5f846 |
class SingleCycleLinkList(object): <NEW_LINE> <INDENT> def __init__(self, node=None): <NEW_LINE> <INDENT> self.__head = node <NEW_LINE> <DEDENT> def is_empty(self): <NEW_LINE> <INDENT> return self.__head is None <NEW_LINE> <DEDENT> def length(self): <NEW_LINE> <INDENT> if self.is_empty(): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> cur = self.__head <NEW_LINE> count = 1 <NEW_LINE> while cur.next != self.__head: <NEW_LINE> <INDENT> count += 1 <NEW_LINE> cur = cur.next <NEW_LINE> <DEDENT> return count <NEW_LINE> <DEDENT> def travel(self): <NEW_LINE> <INDENT> if self.is_empty(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> cur = self.__head <NEW_LINE> print(cur.item) <NEW_LINE> while cur.next != self.__head: <NEW_LINE> <INDENT> cur = cur.next <NEW_LINE> print(cur.item) <NEW_LINE> <DEDENT> print("") <NEW_LINE> <DEDENT> def add(self, item): <NEW_LINE> <INDENT> node = SingleNode(item) <NEW_LINE> if self.is_empty(): <NEW_LINE> <INDENT> self.__head = node <NEW_LINE> node.next = self.__head <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> node.next = self.__head <NEW_LINE> cur = self.__head <NEW_LINE> while cur.next != self.__head: <NEW_LINE> <INDENT> cur = cur.next <NEW_LINE> <DEDENT> cur.next = node <NEW_LINE> self.__head = node <NEW_LINE> <DEDENT> <DEDENT> def append(self, item): <NEW_LINE> <INDENT> node = SingleNode(item) <NEW_LINE> if self.is_empty(): <NEW_LINE> <INDENT> self.__head = node <NEW_LINE> node.next = self.__head <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cur = self.__head <NEW_LINE> while cur.next != self.__head: <NEW_LINE> <INDENT> cur = cur.next <NEW_LINE> <DEDENT> cur.next = node <NEW_LINE> node.next = self.__head <NEW_LINE> <DEDENT> <DEDENT> def insert(self, pos, item): <NEW_LINE> <INDENT> if pos <= 0: <NEW_LINE> <INDENT> self.add(item) <NEW_LINE> <DEDENT> elif pos > (self.length()-1): <NEW_LINE> <INDENT> self.append(item) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> node = SingleNode(item) <NEW_LINE> count = 0 <NEW_LINE> pre = self.__head <NEW_LINE> while count < (pos-1): <NEW_LINE> <INDENT> count += 1 <NEW_LINE> pre = pre.next <NEW_LINE> <DEDENT> node.next = pre.next <NEW_LINE> pre.next = node <NEW_LINE> <DEDENT> <DEDENT> def remove(self, item): <NEW_LINE> <INDENT> if self.is_empty(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> cur = self.__head <NEW_LINE> pre = None <NEW_LINE> if cur.item == item: <NEW_LINE> <INDENT> if cur.next != self.__head: <NEW_LINE> <INDENT> while cur.next != self.__head: <NEW_LINE> <INDENT> cur = cur.next <NEW_LINE> <DEDENT> cur.next = self.__head.next <NEW_LINE> self.__head = self.__head.next <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__head = None <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> pre = self.__head <NEW_LINE> while cur.next != self.__head: <NEW_LINE> <INDENT> if cur.item == item: <NEW_LINE> <INDENT> pre.next = cur.next <NEW_LINE> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pre = cur <NEW_LINE> cur = cur.next <NEW_LINE> <DEDENT> <DEDENT> if cur.item == item: <NEW_LINE> <INDENT> pre.next = cur.next <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def search(self, item): <NEW_LINE> <INDENT> if self.is_empty(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> cur = self.__head <NEW_LINE> if cur.item == item: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> while cur.next != self.__head: <NEW_LINE> <INDENT> if cur.item == item: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False | 单向循环链表 | 62599071f9cc0f698b1c5f2a |
class ZMQInteractiveShell(InteractiveShell): <NEW_LINE> <INDENT> displayhook_class = Type(ZMQShellDisplayHook) <NEW_LINE> display_pub_class = Type(ZMQDisplayPublisher) <NEW_LINE> colors_force = CBool(True) <NEW_LINE> readline_use = CBool(False) <NEW_LINE> autoindent = CBool(False) <NEW_LINE> exiter = Instance(ZMQExitAutocall) <NEW_LINE> def _exiter_default(self): <NEW_LINE> <INDENT> return ZMQExitAutocall(self) <NEW_LINE> <DEDENT> def _exit_now_changed(self, name, old, new): <NEW_LINE> <INDENT> if new: <NEW_LINE> <INDENT> loop = ioloop.IOLoop.instance() <NEW_LINE> loop.add_timeout(time.time()+0.1, loop.stop) <NEW_LINE> <DEDENT> <DEDENT> keepkernel_on_exit = None <NEW_LINE> from .eventloops import enable_gui <NEW_LINE> enable_gui = staticmethod(enable_gui) <NEW_LINE> def init_environment(self): <NEW_LINE> <INDENT> env = os.environ <NEW_LINE> env['TERM'] = 'xterm-color' <NEW_LINE> env['CLICOLOR'] = '1' <NEW_LINE> env['PAGER'] = 'cat' <NEW_LINE> env['GIT_PAGER'] = 'cat' <NEW_LINE> install_payload_page() <NEW_LINE> <DEDENT> def auto_rewrite_input(self, cmd): <NEW_LINE> <INDENT> new = self.prompt_manager.render('rewrite') + cmd <NEW_LINE> payload = dict( source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input', transformed_input=new, ) <NEW_LINE> self.payload_manager.write_payload(payload) <NEW_LINE> <DEDENT> def ask_exit(self): <NEW_LINE> <INDENT> self.exit_now = True <NEW_LINE> payload = dict( source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit', exit=True, keepkernel=self.keepkernel_on_exit, ) <NEW_LINE> self.payload_manager.write_payload(payload) <NEW_LINE> <DEDENT> def _showtraceback(self, etype, evalue, stb): <NEW_LINE> <INDENT> exc_content = { u'traceback' : stb, u'ename' : unicode(etype.__name__), u'evalue' : safe_unicode(evalue) } <NEW_LINE> dh = self.displayhook <NEW_LINE> topic = None <NEW_LINE> if dh.topic: <NEW_LINE> <INDENT> topic = dh.topic.replace(b'pyout', b'pyerr') <NEW_LINE> <DEDENT> exc_msg = dh.session.send(dh.pub_socket, u'pyerr', json_clean(exc_content), dh.parent_header, ident=topic) <NEW_LINE> exc_content[u'status'] = u'error' <NEW_LINE> self._reply_content = exc_content <NEW_LINE> return exc_content <NEW_LINE> <DEDENT> def set_next_input(self, text): <NEW_LINE> <INDENT> payload = dict( source='IPython.zmq.zmqshell.ZMQInteractiveShell.set_next_input', text=text ) <NEW_LINE> self.payload_manager.write_payload(payload) <NEW_LINE> <DEDENT> def init_magics(self): <NEW_LINE> <INDENT> super(ZMQInteractiveShell, self).init_magics() <NEW_LINE> self.register_magics(KernelMagics) <NEW_LINE> self.run_line_magic('alias_magic', 'ed edit') | A subclass of InteractiveShell for ZMQ. | 62599071460517430c432cb6 |
class Product(models.Model): <NEW_LINE> <INDENT> sub_category_child = models.ForeignKey(SubCategoryChild,null=False,blank=False) <NEW_LINE> title = models.CharField(max_length=120,null=False, blank=False) <NEW_LINE> image = models.ImageField(upload_to='products/images',default="",blank=False,null=False) <NEW_LINE> description = models.TextField(null=True,blank=True) <NEW_LINE> slug = models.SlugField(unique=True) <NEW_LINE> active = models.BooleanField(default=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.title <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> unique_together = ('title', 'slug') | Product class. | 625990714527f215b58eb5ff |
class PublishManifestListsStep(publish_step.UnitModelPluginStep): <NEW_LINE> <INDENT> def __init__(self, repo_content_unit_q=None): <NEW_LINE> <INDENT> super(PublishManifestListsStep, self).__init__( step_type=constants.PUBLISH_STEP_MANIFEST_LISTS, model_classes=[models.ManifestList], repo_content_unit_q=repo_content_unit_q) <NEW_LINE> self.description = _('Publishing Manifest Lists.') <NEW_LINE> <DEDENT> def process_main(self, item): <NEW_LINE> <INDENT> misc.create_symlink(item._storage_path, os.path.join(self.get_manifests_directory(), constants.MANIFEST_LIST_TYPE, item.unit_key['digest'])) <NEW_LINE> redirect_data = self.parent.redirect_data <NEW_LINE> redirect_data[constants.MANIFEST_LIST_TYPE].add(item.unit_key['digest']) <NEW_LINE> if item.amd64_digest: <NEW_LINE> <INDENT> tags = models.Tag.objects.filter(manifest_digest=item.digest, repo_id=self.get_repo().id) <NEW_LINE> for tag in tags: <NEW_LINE> <INDENT> redirect_data['amd64'][tag.name] = (item.amd64_digest, item.amd64_schema_version) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_manifests_directory(self): <NEW_LINE> <INDENT> return os.path.join(self.parent.get_working_dir(), 'manifests') | Publish ManifestLists. | 625990711b99ca4002290195 |
class Airport: <NEW_LINE> <INDENT> prop_names = ('id', 'name', 'city', 'country', 'iata', 'icao', 'lat', 'long', 'alt', 'utc_offset', 'dst_rule', 'tz', 'type', 'source') <NEW_LINE> def __init__(self, csv_entry): <NEW_LINE> <INDENT> assert len(csv_entry) == len(Airport.prop_names) <NEW_LINE> self.__dict__.update(dict(zip(Airport.prop_names, csv_entry))) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "{0.iata} ({0.name})".format(self) | Airport as represented in airports.dat | 62599071ad47b63b2c5a910d |
class assert_subnet(Assert): <NEW_LINE> <INDENT> def wrap(self, testcase, *args, **kwargs): <NEW_LINE> <INDENT> name = self.func.__name__[5:] <NEW_LINE> alias = self.translator.ALIASES_REVMAP.get(name) <NEW_LINE> for item in (name, alias): <NEW_LINE> <INDENT> if item is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for val in ('127.0.0.1/32', '::1/128'): <NEW_LINE> <INDENT> log.debug('Verifying \'%s\' is a valid subnet', val) <NEW_LINE> testcase.assertEqual( salt.utils.docker.translate_input( self.translator, validate_ip_addrs=True, **{item: val} ), testcase.apply_defaults({name: val}) ) <NEW_LINE> <DEDENT> for val in ('127.0.0.1', '999.999.999.999/24', '10.0.0.0/33', '::1', 'feaz::1/128', '::1/129'): <NEW_LINE> <INDENT> log.debug('Verifying \'%s\' is not a valid subnet', val) <NEW_LINE> with testcase.assertRaisesRegex( CommandExecutionError, "'{0}' is not a valid subnet".format(val)): <NEW_LINE> <INDENT> salt.utils.docker.translate_input( self.translator, validate_ip_addrs=True, **{item: val} ) <NEW_LINE> <DEDENT> <DEDENT> val = 'foo' <NEW_LINE> testcase.assertEqual( salt.utils.docker.translate_input( self.translator, validate_ip_addrs=False, **{item: val} ), testcase.apply_defaults({name: val}) ) <NEW_LINE> <DEDENT> if alias is not None: <NEW_LINE> <INDENT> test_kwargs = {name: '10.0.0.0/24', alias: '192.168.50.128/25'} <NEW_LINE> testcase.assertEqual( salt.utils.docker.translate_input( self.translator, ignore_collisions=True, **test_kwargs ), testcase.apply_defaults({name: test_kwargs[name]}) ) <NEW_LINE> with testcase.assertRaisesRegex( CommandExecutionError, 'is an alias for.+cannot both be used'): <NEW_LINE> <INDENT> salt.utils.docker.translate_input( self.translator, ignore_collisions=False, **test_kwargs ) <NEW_LINE> <DEDENT> <DEDENT> return self.func(testcase, *args, **kwargs) | Test an IPv4 or IPv6 subnet | 6259907166673b3332c31cbd |
class Courselist(ModelViewSet): <NEW_LINE> <INDENT> queryset = models.Course.objects.all() <NEW_LINE> serializer_class = CourseSerializer | 课程类的API | 625990712ae34c7f260ac9a9 |
class TrackerResponse: <NEW_LINE> <INDENT> def __init__(self, response: dict): <NEW_LINE> <INDENT> self.response_raw = response <NEW_LINE> self.peers = self._generate_peer_list(response.get(b'peers', "")) <NEW_LINE> <DEDENT> @property <NEW_LINE> def failure(self): <NEW_LINE> <INDENT> if b'failure reason' in self.response_raw: <NEW_LINE> <INDENT> return self.response_raw[b'failure reason'].decode('utf-8') <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> @property <NEW_LINE> def interval(self) -> int: <NEW_LINE> <INDENT> return self.response_raw.get(b'interval', 0) <NEW_LINE> <DEDENT> @property <NEW_LINE> def complete(self) -> int: <NEW_LINE> <INDENT> return self.response_raw.get(b'complete', 0) <NEW_LINE> <DEDENT> @property <NEW_LINE> def incomplete(self) -> int: <NEW_LINE> <INDENT> return self.response_raw.get(b'incomplete', 0) <NEW_LINE> <DEDENT> def _generate_peer_list(self, peers_binary) -> List: <NEW_LINE> <INDENT> if type(peers_binary) == list: <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> peers = [peers_binary[i:i+6] for i in range(0, len(peers_binary), 6)] <NEW_LINE> tuple_list = [] <NEW_LINE> for p in peers: <NEW_LINE> <INDENT> tuple_list.append( Peer( socket.inet_ntoa(p[:4]), _decode_port(p[4:]), None ) ) <NEW_LINE> <DEDENT> return tuple_list | Represents a tracker response for a torrent. | 625990717d43ff2487428072 |
class Permutation(Function): <NEW_LINE> <INDENT> def __init__(self, params, dims): <NEW_LINE> <INDENT> if not len(params) == 1: <NEW_LINE> <INDENT> raise Exception("Number of parameters does not equal 1.") <NEW_LINE> <DEDENT> beta = np.array(params.beta) <NEW_LINE> if np.isscalar(beta): <NEW_LINE> <INDENT> raise Exception("Beta paramater must always be a scalar value.") <NEW_LINE> <DEDENT> self.dims = dims <NEW_LINE> self.beta = beta <NEW_LINE> self.bound = [-dims, dims] <NEW_LINE> <DEDENT> def __call__(self, x): <NEW_LINE> <INDENT> x = np.array(x) <NEW_LINE> ks = np.array(range(1, self.dims + 1)) <NEW_LINE> i = np.array(range(1, self.dims + 1)) <NEW_LINE> value = np.array([np.sum((i ** k + self.beta) * ((x / i) ** k - 1), axis=0) for k in ks]) <NEW_LINE> value = np.sum(value ** 2) <NEW_LINE> return value | beta is a non-negative parameter. The smaller beta, the more difficult problem becomes since the global minimum
is difficult to distinguish from local minima near permuted solutions. For beta=0, every permuted solution is a
global minimum, too.
This problem therefore appear useful to test the ability of a global minimization algorithm to reach the global
minimum successfully and to discriminate it from other local minima.
reference: http://solon.cma.univie.ac.at/glopt/my_problems.html
:param params: Instance of :func:`~collections.namedtuple` :class:`PermutationParameters`
:param dims: dimensionality of the function | 62599071fff4ab517ebcf0da |
class InteractionType(enum.IntEnum): <NEW_LINE> <INDENT> INTERACTION_TYPE_UNSPECIFIED = 0 <NEW_LINE> DISCUSSION = 1 <NEW_LINE> PRESENTATION = 2 <NEW_LINE> PHONE_CALL = 3 <NEW_LINE> VOICEMAIL = 4 <NEW_LINE> PROFESSIONALLY_PRODUCED = 5 <NEW_LINE> VOICE_SEARCH = 6 <NEW_LINE> VOICE_COMMAND = 7 <NEW_LINE> DICTATION = 8 | Use case categories that the audio recognition request can be described
by.
Attributes:
INTERACTION_TYPE_UNSPECIFIED (int): Use case is either unknown or is something other than one of the other
values below.
DISCUSSION (int): Multiple people in a conversation or discussion. For example in a
meeting with two or more people actively participating. Typically all
the primary people speaking would be in the same room (if not, see
PHONE\_CALL)
PRESENTATION (int): One or more persons lecturing or presenting to others, mostly
uninterrupted.
PHONE_CALL (int): A phone-call or video-conference in which two or more people, who are
not in the same room, are actively participating.
VOICEMAIL (int): A recorded message intended for another person to listen to.
PROFESSIONALLY_PRODUCED (int): Professionally produced audio (eg. TV Show, Podcast).
VOICE_SEARCH (int): Transcribe spoken questions and queries into text.
VOICE_COMMAND (int): Transcribe voice commands, such as for controlling a device.
DICTATION (int): Transcribe speech to text to create a written document, such as a
text-message, email or report. | 6259907197e22403b383c7c3 |
class TitleCreator(BaseEstimator, TransformerMixin): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def fit(self, X): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def transform(self, X): <NEW_LINE> <INDENT> df = X.copy() <NEW_LINE> df['Title'] = df.Name.str.extract(' ([A-Za-z]+)\.', expand=False) <NEW_LINE> df['Title'] = df['Title'].replace(['Lady', 'Countess','Capt', 'Col','Don', 'Dr', 'Major', 'Rev','Sir','Jonkheer','Dona'], 'Rare') <NEW_LINE> df['Title'] = df['Title'].replace('Mlle', 'Miss') <NEW_LINE> df['Title'] = df['Title'].replace('Ms', 'Miss') <NEW_LINE> df['Title'] = df['Title'].replace('Mme', 'Mrs') <NEW_LINE> df['Title'] = df['Title'].fillna(np.nan) <NEW_LINE> return df | Generates Title column | 62599071dd821e528d6da5e1 |
class SharezoneFormTest(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.content = { "name" : "Test Sharezone", "description" : "Test description", } <NEW_LINE> <DEDENT> def test_standard_valid(self): <NEW_LINE> <INDENT> form = SharezoneForm(self.content) <NEW_LINE> self.assertTrue(form.is_valid()) <NEW_LINE> <DEDENT> def test_name_only(self): <NEW_LINE> <INDENT> del self.content['description'] <NEW_LINE> form = SharezoneForm(self.content) <NEW_LINE> self.assertTrue(form.is_valid()) <NEW_LINE> <DEDENT> def test_description_only(self): <NEW_LINE> <INDENT> del self.content['name'] <NEW_LINE> form = SharezoneForm(self.content) <NEW_LINE> self.assertFalse(form.is_valid()) <NEW_LINE> <DEDENT> def test_no_content(self): <NEW_LINE> <INDENT> form = SharezoneForm() <NEW_LINE> self.assertFalse(form.is_valid()) | Tests to make sure the SharezoneForm is valid if a name is given
or if a name AND description is given. | 6259907155399d3f05627dd8 |
class SuiteInfoClient(PyroClient): <NEW_LINE> <INDENT> target_server_object = PYRO_INFO_OBJ_NAME <NEW_LINE> def get_info(self, *args): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.call_server_func("get", *args) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> command = back_compat[args[0]] <NEW_LINE> args = tuple([command]) + args[1:] <NEW_LINE> return self.call_server_func("get", *args) <NEW_LINE> <DEDENT> <DEDENT> def set_use_scan_hash(self): <NEW_LINE> <INDENT> self._hash_name = SCAN_HASH <NEW_LINE> <DEDENT> def _get_proxy(self, hash_name=None): <NEW_LINE> <INDENT> if hash_name is None and hasattr(self, "_hash_name"): <NEW_LINE> <INDENT> hash_name = self._hash_name <NEW_LINE> <DEDENT> return super(SuiteInfoClient, self)._get_proxy(hash_name=hash_name) | Client-side suite information interface. | 625990713317a56b869bf1a4 |
class VibratoTypeSequenceEvent(SequenceEvent): <NEW_LINE> <INDENT> dataLength = 2 <NEW_LINE> class Value(enum.IntEnum): <NEW_LINE> <INDENT> PITCH = 0 <NEW_LINE> VOLUME = 1 <NEW_LINE> PAN = 2 <NEW_LINE> <DEDENT> def __init__(self, value): <NEW_LINE> <INDENT> super().__init__(0xCC) <NEW_LINE> self.value = self.Value(value) <NEW_LINE> <DEDENT> def save(self, eventsToOffsets=None): <NEW_LINE> <INDENT> return super().save() + self.value.to_bytes(1, 'little') <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def fromData(cls, type, data, startOffset=0): <NEW_LINE> <INDENT> return cls(data[startOffset + 1]) <NEW_LINE> <DEDENT> def _valueName(self): <NEW_LINE> <INDENT> if self.value in [0, 1, 2]: <NEW_LINE> <INDENT> return ['pitch', 'volume', 'pan'][self.value] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return str(self.value) <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f'<vibrato type {self._valueName()}>' <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return f'{type(self).__name__}({self.value!r})' | A sequence event that sets the current vibrato type. This is
sequence event type 0xCC. | 625990718a43f66fc4bf3a54 |
class EmuCompassCommand(PebbleCommand): <NEW_LINE> <INDENT> command = 'emu-compass' <NEW_LINE> valid_connections = {'qemu', 'emulator'} <NEW_LINE> def __call__(self, args): <NEW_LINE> <INDENT> super(EmuCompassCommand, self).__call__(args) <NEW_LINE> calibrated = QemuCompass.Calibration.Complete <NEW_LINE> if args.uncalibrated: <NEW_LINE> <INDENT> calibrated = QemuCompass.Calibration.Uncalibrated <NEW_LINE> <DEDENT> elif args.calibrating: <NEW_LINE> <INDENT> calibrated = QemuCompass.Calibration.Refining <NEW_LINE> <DEDENT> elif args.calibrated: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> max_angle_radians = 0x10000 <NEW_LINE> max_angle_degrees = 360 <NEW_LINE> heading = math.ceil(args.heading % 360 * max_angle_radians / max_angle_degrees) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> heading = None <NEW_LINE> <DEDENT> compass_input = QemuCompass(heading=heading, calibrated=calibrated) <NEW_LINE> send_data_to_qemu(self.pebble.transport, compass_input) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def add_parser(cls, parser): <NEW_LINE> <INDENT> parser = super(EmuCompassCommand, cls).add_parser(parser) <NEW_LINE> parser.add_argument('--heading', type=int, default=0, help="Set the emulator compass heading (0 to 359)") <NEW_LINE> calib_options = parser.add_mutually_exclusive_group() <NEW_LINE> calib_options.add_argument('--uncalibrated', action='store_true', help="Set compass to uncalibrated") <NEW_LINE> calib_options.add_argument('--calibrating', action='store_true', help="Set compass to calibrating mode") <NEW_LINE> calib_options.add_argument('--calibrated', action='store_true', help="Set compass to calibrated") <NEW_LINE> return parser | Sets the emulated compass heading and calibration state. | 625990718e7ae83300eea951 |
class WordRecallTest(Widget): <NEW_LINE> <INDENT> option_length = fields.PositiveSmallIntegerField(default=5) <NEW_LINE> @classmethod <NEW_LINE> def new(cls, start_msg, option_length): <NEW_LINE> <INDENT> return cls._new(start_msg = start_msg, option_length = option_length) <NEW_LINE> <DEDENT> @property <NEW_LINE> def widget_data(self): <NEW_LINE> <INDENT> return dict(start_msg = self.start_msg, option_length = self.option_length) | This simple widget presents the subject a list of options where they can
recall the words they rememember. | 625990711f5feb6acb1644b2 |
class Person(dict): <NEW_LINE> <INDENT> def __init__(self, job, _id, name, character, url, thumb): <NEW_LINE> <INDENT> self['job'] = job <NEW_LINE> self['id'] = _id <NEW_LINE> self['name'] = name <NEW_LINE> self['character'] = character <NEW_LINE> self['url'] = url <NEW_LINE> self['thumb'] = thumb <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if self['character'] is None or self['character'] == "": <NEW_LINE> <INDENT> return "<%(job)s (id %(id)s): %(name)s>" % self <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "<%(job)s (id %(id)s): %(name)s (as %(character)s)>" % self | Stores information about a specific member of cast
| 625990717d847024c075dc99 |
class componentSettings(MayaQWidgetDockableMixin, guide.componentMainSettings): <NEW_LINE> <INDENT> def __init__(self, parent=None): <NEW_LINE> <INDENT> self.toolName = TYPE <NEW_LINE> pyqt.deleteInstances(self, MayaQDockWidget) <NEW_LINE> super(self.__class__, self).__init__(parent=parent) <NEW_LINE> self.settingsTab = settingsTab() <NEW_LINE> self.setup_componentSettingWindow() <NEW_LINE> self.create_componentControls() <NEW_LINE> self.populate_componentControls() <NEW_LINE> self.create_componentLayout() <NEW_LINE> self.create_componentConnections() <NEW_LINE> <DEDENT> def setup_componentSettingWindow(self): <NEW_LINE> <INDENT> self.mayaMainWindow = pyqt.maya_main_window() <NEW_LINE> self.setObjectName(self.toolName) <NEW_LINE> self.setWindowFlags(QtCore.Qt.Window) <NEW_LINE> self.setWindowTitle(TYPE) <NEW_LINE> self.resize(280, 350) <NEW_LINE> <DEDENT> def create_componentControls(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def populate_componentControls(self): <NEW_LINE> <INDENT> self.tabs.insertTab(1, self.settingsTab, "Component Settings") <NEW_LINE> self.populateCheck(self.settingsTab.useRollCtl_checkBox, "useRollCtl") <NEW_LINE> for cnx in Guide.connectors: <NEW_LINE> <INDENT> self.mainSettingsTab.connector_comboBox.addItem(cnx) <NEW_LINE> <DEDENT> cBox = self.mainSettingsTab.connector_comboBox <NEW_LINE> self.connector_items = [cBox.itemText(i) for i in range(cBox.count())] <NEW_LINE> currentConnector = self.root.attr("connector").get() <NEW_LINE> if currentConnector not in self.connector_items: <NEW_LINE> <INDENT> self.mainSettingsTab.connector_comboBox.addItem(currentConnector) <NEW_LINE> self.connector_items.append(currentConnector) <NEW_LINE> pm.displayWarning("The current connector: %s, is not a valid " "connector for this component. " "Build will Fail!!") <NEW_LINE> <DEDENT> comboIndex = self.connector_items.index(currentConnector) <NEW_LINE> self.mainSettingsTab.connector_comboBox.setCurrentIndex(comboIndex) <NEW_LINE> <DEDENT> def create_componentLayout(self): <NEW_LINE> <INDENT> self.settings_layout = QtWidgets.QVBoxLayout() <NEW_LINE> self.settings_layout.addWidget(self.tabs) <NEW_LINE> self.settings_layout.addWidget(self.close_button) <NEW_LINE> self.setLayout(self.settings_layout) <NEW_LINE> <DEDENT> def create_componentConnections(self): <NEW_LINE> <INDENT> self.settingsTab.useRollCtl_checkBox.stateChanged.connect( partial(self.updateCheck, self.settingsTab.useRollCtl_checkBox, "neutralpose")) <NEW_LINE> self.mainSettingsTab.connector_comboBox.currentIndexChanged.connect( partial(self.updateConnector, self.mainSettingsTab.connector_comboBox, self.connector_items)) <NEW_LINE> <DEDENT> def dockCloseEventTriggered(self): <NEW_LINE> <INDENT> pyqt.deleteInstances(self, MayaQDockWidget) | Create the component setting window | 6259907132920d7e50bc7907 |
class _FixupStream(object): <NEW_LINE> <INDENT> def __init__(self, stream): <NEW_LINE> <INDENT> self._stream = stream <NEW_LINE> self._prevent_close = False <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> return getattr(self._stream, name) <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> if not self._prevent_close: <NEW_LINE> <INDENT> self._stream.close() <NEW_LINE> <DEDENT> <DEDENT> def read1(self, size): <NEW_LINE> <INDENT> f = getattr(self._stream, 'read1', None) <NEW_LINE> if f is not None: <NEW_LINE> <INDENT> return f(size) <NEW_LINE> <DEDENT> return self._stream.readline(size) <NEW_LINE> <DEDENT> def readable(self): <NEW_LINE> <INDENT> x = getattr(self._stream, 'readable', None) <NEW_LINE> if x is not None: <NEW_LINE> <INDENT> return x <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self._stream.read(0) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def writable(self): <NEW_LINE> <INDENT> x = getattr(self._stream, 'writable', None) <NEW_LINE> if x is not None: <NEW_LINE> <INDENT> return x <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self._stream.write('') <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._stream.write(b'') <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> def seekable(self): <NEW_LINE> <INDENT> x = getattr(self._stream, 'seekable', None) <NEW_LINE> if x is not None: <NEW_LINE> <INDENT> return x <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self._stream.seek(self._stream.tell()) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True | The new io interface needs more from streams than streams
traditionally implement. As such this fixup stuff is necessary in
some circumstances. | 62599071e1aae11d1e7cf46d |
class Node(object): <NEW_LINE> <INDENT> def __init__(self, data): <NEW_LINE> <INDENT> self.data = data <NEW_LINE> self.next = None <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<Node object. Data: %s; Next: %s>" % ( self.data, self.next.data if self.next else None, ) | Node in a linked list. | 625990713d592f4c4edbc7a2 |
class NumpyState(base.Trackable): <NEW_LINE> <INDENT> def _lookup_dependency(self, name): <NEW_LINE> <INDENT> value = super(NumpyState, self)._lookup_dependency(name) <NEW_LINE> if value is None: <NEW_LINE> <INDENT> value = _NumpyWrapper(numpy.array([])) <NEW_LINE> new_reference = base.TrackableReference(name=name, ref=value) <NEW_LINE> self._unconditional_checkpoint_dependencies.append(new_reference) <NEW_LINE> self._unconditional_dependency_names[name] = value <NEW_LINE> super(NumpyState, self).__setattr__(name, value) <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def __getattribute__(self, name): <NEW_LINE> <INDENT> value = super(NumpyState, self).__getattribute__(name) <NEW_LINE> if isinstance(value, _NumpyWrapper): <NEW_LINE> <INDENT> return value.array <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def __setattr__(self, name, value): <NEW_LINE> <INDENT> if isinstance(value, (numpy.ndarray, numpy.generic)): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> existing = super(NumpyState, self).__getattribute__(name) <NEW_LINE> existing.array = value <NEW_LINE> return <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> value = _NumpyWrapper(value) <NEW_LINE> self._track_trackable(value, name=name, overwrite=True) <NEW_LINE> <DEDENT> <DEDENT> elif (name not in ("_setattr_tracking", "_update_uid") and getattr(self, "_setattr_tracking", True)): <NEW_LINE> <INDENT> raise NotImplementedError( ("Assigned %s to the %s property of %s, which is not a NumPy array. " "Currently mixing NumPy arrays and other trackable objects is " "not supported. File a feature request if this limitation bothers " "you.") % (value, name, self)) <NEW_LINE> <DEDENT> super(NumpyState, self).__setattr__(name, value) | A trackable object whose NumPy array attributes are saved/restored.
Example usage:
```python
arrays = tf.contrib.checkpoint.NumpyState()
checkpoint = tf.train.Checkpoint(numpy_arrays=arrays)
arrays.x = numpy.zeros([3, 4])
save_path = checkpoint.save("/tmp/ckpt")
arrays.x[1, 1] = 4.
checkpoint.restore(save_path)
assert (arrays.x == numpy.zeros([3, 4])).all()
second_checkpoint = tf.train.Checkpoint(
numpy_arrays=tf.contrib.checkpoint.NumpyState())
# Attributes of NumpyState objects are created automatically by restore()
second_checkpoint.restore(save_path)
assert (second_checkpoint.numpy_arrays.x == numpy.zeros([3, 4])).all()
```
Note that `NumpyState` objects re-create the attributes of the previously
saved object on `restore()`. This is in contrast to TensorFlow variables, for
which a `Variable` object must be created and assigned to an attribute.
This snippet works both when graph building and when executing eagerly. On
save, the NumPy array(s) are fed as strings to be saved in the checkpoint (via
a placeholder when graph building, or as a string constant when executing
eagerly). When restoring they skip the TensorFlow graph entirely, and so no
restore ops need be run. This means that restoration always happens eagerly,
rather than waiting for `checkpoint.restore(...).run_restore_ops()` like
TensorFlow variables when graph building. | 6259907156b00c62f0fb4190 |
class FSStatus(object): <NEW_LINE> <INDENT> def __init__(self, mon_manager): <NEW_LINE> <INDENT> self.mon = mon_manager <NEW_LINE> self.map = json.loads(self.mon.raw_cluster_cmd("fs", "dump", "--format=json")) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return json.dumps(self.map, indent = 2, sort_keys = True) <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> return self.map[key] <NEW_LINE> <DEDENT> def get_filesystems(self): <NEW_LINE> <INDENT> for fs in self.map['filesystems']: <NEW_LINE> <INDENT> yield fs <NEW_LINE> <DEDENT> <DEDENT> def get_all(self): <NEW_LINE> <INDENT> for info in self.get_standbys(): <NEW_LINE> <INDENT> yield info <NEW_LINE> <DEDENT> for fs in self.map['filesystems']: <NEW_LINE> <INDENT> for info in fs['mdsmap']['info'].values(): <NEW_LINE> <INDENT> yield info <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_standbys(self): <NEW_LINE> <INDENT> for info in self.map['standbys']: <NEW_LINE> <INDENT> yield info <NEW_LINE> <DEDENT> <DEDENT> def get_fsmap(self, fscid): <NEW_LINE> <INDENT> for fs in self.map['filesystems']: <NEW_LINE> <INDENT> if fscid is None or fs['id'] == fscid: <NEW_LINE> <INDENT> return fs <NEW_LINE> <DEDENT> <DEDENT> raise RuntimeError("FSCID {0} not in map".format(fscid)) <NEW_LINE> <DEDENT> def get_fsmap_byname(self, name): <NEW_LINE> <INDENT> for fs in self.map['filesystems']: <NEW_LINE> <INDENT> if name is None or fs['mdsmap']['fs_name'] == name: <NEW_LINE> <INDENT> return fs <NEW_LINE> <DEDENT> <DEDENT> raise RuntimeError("FS {0} not in map".format(name)) <NEW_LINE> <DEDENT> def get_replays(self, fscid): <NEW_LINE> <INDENT> fs = self.get_fsmap(fscid) <NEW_LINE> for info in fs['mdsmap']['info'].values(): <NEW_LINE> <INDENT> if info['state'] == 'up:standby-replay': <NEW_LINE> <INDENT> yield info <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_ranks(self, fscid): <NEW_LINE> <INDENT> fs = self.get_fsmap(fscid) <NEW_LINE> for info in fs['mdsmap']['info'].values(): <NEW_LINE> <INDENT> if info['rank'] >= 0: <NEW_LINE> <INDENT> yield info <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_rank(self, fscid, rank): <NEW_LINE> <INDENT> for info in self.get_ranks(fscid): <NEW_LINE> <INDENT> if info['rank'] == rank: <NEW_LINE> <INDENT> return info <NEW_LINE> <DEDENT> <DEDENT> raise RuntimeError("FSCID {0} has no rank {1}".format(fscid, rank)) <NEW_LINE> <DEDENT> def get_mds(self, name): <NEW_LINE> <INDENT> for info in self.get_all(): <NEW_LINE> <INDENT> if info['name'] == name: <NEW_LINE> <INDENT> return info <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def get_mds_addr(self, name): <NEW_LINE> <INDENT> info = self.get_mds(name) <NEW_LINE> if info: <NEW_LINE> <INDENT> return info['addr'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log.warn(json.dumps(list(self.get_all()), indent=2)) <NEW_LINE> raise RuntimeError("MDS id '{0}' not found in map".format(name)) | Operations on a snapshot of the FSMap. | 62599071ac7a0e7691f73da9 |
class CloudNetworkClient(BaseClient): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(CloudNetworkClient, self).__init__(*args, **kwargs) <NEW_LINE> self.name = "Cloud Networks" <NEW_LINE> self.PUBLIC_NET_ID = PUBLIC_NET_ID <NEW_LINE> self.SERVICE_NET_ID = SERVICE_NET_ID <NEW_LINE> self.PSEUDO_NETWORKS = PSEUDO_NETWORKS <NEW_LINE> <DEDENT> def _configure_manager(self): <NEW_LINE> <INDENT> self._manager = CloudNetworkManager(self, resource_class=CloudNetwork, response_key="network", uri_base="os-networksv2") <NEW_LINE> <DEDENT> def create(self, label=None, name=None, cidr=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return super(CloudNetworkClient, self).create(label=label, name=name, cidr=cidr) <NEW_LINE> <DEDENT> except exc.BadRequest as e: <NEW_LINE> <INDENT> msg = e.message <NEW_LINE> if "too many networks" in msg: <NEW_LINE> <INDENT> raise exc.NetworkCountExceeded("Cannot create network; the " "maximum number of isolated networks already exist.") <NEW_LINE> <DEDENT> elif "does not contain enough" in msg: <NEW_LINE> <INDENT> raise exc.NetworkCIDRInvalid("Networks must contain two or " "more hosts; the CIDR '%s' is too restrictive." % cidr) <NEW_LINE> <DEDENT> elif "CIDR is malformed" in msg: <NEW_LINE> <INDENT> raise exc.NetworkCIDRMalformed("The CIDR '%s' is not valid." % cidr) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def delete(self, network): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return super(CloudNetworkClient, self).delete(network) <NEW_LINE> <DEDENT> except exc.Forbidden as e: <NEW_LINE> <INDENT> raise exc.NetworkInUse("Cannot delete a network in use by a server.") <NEW_LINE> <DEDENT> <DEDENT> def find_network_by_label(self, label): <NEW_LINE> <INDENT> networks = self.list() <NEW_LINE> match = [network for network in networks if network.label == label] <NEW_LINE> if not match: <NEW_LINE> <INDENT> raise exc.NetworkNotFound("No network with the label '%s' exists" % label) <NEW_LINE> <DEDENT> elif len(match) > 1: <NEW_LINE> <INDENT> raise exc.NetworkLabelNotUnique("There were %s matches for the label " "'%s'." % (len(match), label)) <NEW_LINE> <DEDENT> return match[0] <NEW_LINE> <DEDENT> find_network_by_name = find_network_by_label <NEW_LINE> def get_server_networks(self, network, public=False, private=False): <NEW_LINE> <INDENT> return _get_server_networks(network, public=public, private=private) | This is the base client for creating and managing Cloud Networks. | 62599071f9cc0f698b1c5f2b |
class BigFontToken (BlockToken): <NEW_LINE> <INDENT> def __init__ (self, parser): <NEW_LINE> <INDENT> BlockToken.__init__ (self, parser) <NEW_LINE> <DEDENT> def getToken (self): <NEW_LINE> <INDENT> return Regex (r"\[(?P<count>\+{1,5})(?P<text>.*?)\1\]", re.MULTILINE | re.UNICODE | re.DOTALL).setParseAction (self.__parse)("big") <NEW_LINE> <DEDENT> def __parse (self, s, l, t): <NEW_LINE> <INDENT> size = 100 + len (t["count"]) * 20 <NEW_LINE> return u'<span style="font-size:{size}%">{text}</span>'.format (size=size, text=self.parser.parseWikiMarkup (t["text"])) | Токен для крупного шрифта | 62599071e76e3b2f99fda2c3 |
class SingleObjectPermissionMixin: <NEW_LINE> <INDENT> permission = None <NEW_LINE> on_fail = permission_denied <NEW_LINE> class KeeperCBVPermissionDenied(Exception): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def dispatch(self, request, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return super().dispatch(request, *args, **kwargs) <NEW_LINE> <DEDENT> except self.KeeperCBVPermissionDenied: <NEW_LINE> <INDENT> return self.on_fail(request, *args, **kwargs) <NEW_LINE> <DEDENT> <DEDENT> def get_object(self): <NEW_LINE> <INDENT> obj = super().get_object() <NEW_LINE> permissions = detect_permissions(obj, self.request) <NEW_LINE> if self.permission not in permissions: <NEW_LINE> <INDENT> raise self.KeeperCBVPermissionDenied <NEW_LINE> <DEDENT> self.k_permissions = permissions <NEW_LINE> return obj | Mixin to check permission for get_object method.
This Mixin can be used with DetailView, UpdateView, DeleteView and so on.
```
class MyUpdateView(SingleObjectPermissionMixin, UpdateView):
permission = 'edit'
on_fail = not_found
...
``` | 625990714f6381625f19a109 |
class Answer(ndb.Model): <NEW_LINE> <INDENT> text = ndb.StringProperty() <NEW_LINE> more_info_enabled = ndb.BooleanProperty() <NEW_LINE> placeholder_text = ndb.StringProperty() <NEW_LINE> @classmethod <NEW_LINE> def create(cls, text, more_info_enabled=False, placeholder_text=None): <NEW_LINE> <INDENT> if bool(more_info_enabled) ^ bool(placeholder_text): <NEW_LINE> <INDENT> raise ValueError(_MORE_INFO_MSG) <NEW_LINE> <DEDENT> return cls( text=text, more_info_enabled=more_info_enabled, placeholder_text=placeholder_text) | Database model representing a survey question_text's answer.
Attributes:
text: str, The text to be displayed for the answer.
more_info_enabled: bool, Indicating whether or not more info can be provided
for this answer.
placeholder_text: str, The text to be displayed in the more info box as a
place holder. | 6259907116aa5153ce401d9a |
class UploadCoverage(ShellCommand): <NEW_LINE> <INDENT> flunkOnFailure = True <NEW_LINE> description = ["upload cov"] <NEW_LINE> name = "upload cov" <NEW_LINE> def __init__(self, upload_furlfile=None, *args, **kwargs): <NEW_LINE> <INDENT> kwargs['command'] = 'flappclient --furlfile %s upload-file cov-*.tar.bz2' % (upload_furlfile,) <NEW_LINE> ShellCommand.__init__(self, *args, **kwargs) <NEW_LINE> self.addFactoryArguments(upload_furlfile=upload_furlfile) | Use the 'flappclient' tool to upload the coverage archive. | 6259907199fddb7c1ca63a33 |
class TaskCreateView(LoginRequiredMixin, CreateView): <NEW_LINE> <INDENT> form_class = TaskForm <NEW_LINE> template_name = 'tasks/create_or_update_task.html' <NEW_LINE> success_url = reverse_lazy('tasks_list') | Форма создания задачи. | 62599071f548e778e596ce4e |
class ReadStdoutGitProxy(GitProxy): <NEW_LINE> <INDENT> __call__ = GitProxy._read_output | A proxy object to wrap calls to git.
Calls to git return the stdout of git and raise an error on a non-zero exit
code. Output to stderr is supressed.
EXAMPLES::
sage: dev.git.status() # not tested | 62599071fff4ab517ebcf0dc |
class Solution: <NEW_LINE> <INDENT> def partition(self, s): <NEW_LINE> <INDENT> result = [] <NEW_LINE> if s is None or len(s) == 0: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> subset = [] <NEW_LINE> index = 0 <NEW_LINE> self.dfs(result, subset, index, s) <NEW_LINE> return result <NEW_LINE> <DEDENT> def dfs(self, result, subset, index, s): <NEW_LINE> <INDENT> if index == len(s): <NEW_LINE> <INDENT> result.append(subset[:]) <NEW_LINE> return <NEW_LINE> <DEDENT> for i in range(index, len(s)): <NEW_LINE> <INDENT> substr = s[index:i+1] <NEW_LINE> if not self.isPalindrome(substr): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> subset.append(substr) <NEW_LINE> self.dfs(result, subset, i+1, s) <NEW_LINE> subset.pop() <NEW_LINE> <DEDENT> <DEDENT> def isPalindrome(self, s): <NEW_LINE> <INDENT> start, end = 0, len(s)-1 <NEW_LINE> while start < end: <NEW_LINE> <INDENT> if s[start] != s[end]: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> start += 1 <NEW_LINE> end -= 1 <NEW_LINE> <DEDENT> return True | @param: s: A string
@return: A list of lists of string | 625990715fc7496912d48ec9 |
class Display: <NEW_LINE> <INDENT> def setMode(self, mode, w, h): <NEW_LINE> <INDENT> _psp.displaySetMode(mode, w, h) <NEW_LINE> <DEDENT> def getMode(self): <NEW_LINE> <INDENT> return _psp.displayGetMode() <NEW_LINE> <DEDENT> def getVcount(self): <NEW_LINE> <INDENT> return _psp.displayGetVcount() <NEW_LINE> <DEDENT> def waitVblankStart(self): <NEW_LINE> <INDENT> _psp.displayWaitVblankStart() | Display interface | 625990719c8ee82313040de8 |
class BaseHandler(tornado.web.RequestHandler, TemplateRendering): <NEW_LINE> <INDENT> def initializa(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_json(self): <NEW_LINE> <INDENT> args = json.load(self.request.body) <NEW_LINE> return args if args else None <NEW_LINE> <DEDENT> def get_json_argument(self, name, default = None): <NEW_LINE> <INDENT> args = json.load(self.request.body) <NEW_LINE> name = to_unicode(name) <NEW_LINE> if name in args: <NEW_LINE> <INDENT> return args[name] <NEW_LINE> <DEDENT> elif default is not None: <NEW_LINE> <INDENT> return default <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise MissingArgumentError(name) <NEW_LINE> <DEDENT> <DEDENT> def get_current_user(self): <NEW_LINE> <INDENT> user = self.get_secure_cookie('user') <NEW_LINE> return user if user else None <NEW_LINE> <DEDENT> def render_html(self, template_name, **kwargs): <NEW_LINE> <INDENT> kwargs.update({ 'settings': self.settings, 'STATIC_URL': self.settings.get('static_url_prefix', '/static/'), 'request': self.request, 'current_user': self.current_user, 'xsrf_token': self.xsrf_token, 'xsrf_form_html': self.xsrf_form_html, }) <NEW_LINE> content = self.render_template(template_name, **kwargs) <NEW_LINE> self.write(content) <NEW_LINE> <DEDENT> def get_error_html(self, status_code, **kwargs): <NEW_LINE> <INDENT> reason = kwargs.get('reason', "Server Error") <NEW_LINE> exception = kwargs.get('exception', "") <NEW_LINE> return self.render_template("error.html", code=str(status_code), reason=str(reason), exception=str(exception)) | 定义公共函数
| 625990713317a56b869bf1a5 |
class LatexIncrementalDecoder(LatexIncrementalLexer): <NEW_LINE> <INDENT> inputenc = "ascii" <NEW_LINE> def __init__(self, errors: str = 'strict') -> None: <NEW_LINE> <INDENT> super(LatexIncrementalDecoder, self).__init__(errors) <NEW_LINE> self.decoder = codecs.getincrementaldecoder(self.inputenc)(errors) <NEW_LINE> <DEDENT> def decode_token(self, token: Token) -> str: <NEW_LINE> <INDENT> text = token.text <NEW_LINE> return text if token.name != u'control_word' else text + u' ' <NEW_LINE> <DEDENT> def get_unicode_tokens(self, chars: str, final: bool = False ) -> Iterator[str]: <NEW_LINE> <INDENT> for token in self.get_tokens(chars, final=final): <NEW_LINE> <INDENT> yield self.decode_token(token) <NEW_LINE> <DEDENT> <DEDENT> def udecode(self, bytes_: str, final: bool = False) -> str: <NEW_LINE> <INDENT> return ''.join(self.get_unicode_tokens(bytes_, final=final)) <NEW_LINE> <DEDENT> def decode(self, bytes_: bytes, final: bool = False) -> str: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> chars = self.decoder.decode(bytes_, final=final) <NEW_LINE> <DEDENT> except UnicodeDecodeError as e: <NEW_LINE> <INDENT> raise ValueError(e) <NEW_LINE> <DEDENT> return self.udecode(chars, final) | Simple incremental decoder. Transforms lexed LaTeX tokens into
unicode.
To customize decoding, subclass and override
:meth:`get_unicode_tokens`. | 625990714f88993c371f1181 |
class EditSpecificationSubscription(AuthorizationBase): <NEW_LINE> <INDENT> permission = 'launchpad.Edit' <NEW_LINE> usedfor = ISpecificationSubscription <NEW_LINE> def checkAuthenticated(self, user): <NEW_LINE> <INDENT> if self.obj.specification.goal is not None: <NEW_LINE> <INDENT> if user.isOneOfDrivers(self.obj.specification.goal): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if user.isOneOfDrivers(self.obj.specification.target): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return (user.inTeam(self.obj.person) or user.isOneOf( self.obj.specification, ['owner', 'drafter', 'assignee', 'approver']) or user.in_admin) | The subscriber, and people related to the spec or the target of the
spec can determine who is essential. | 625990714a966d76dd5f07ac |
class RegistrationTemplateView(TemplateView): <NEW_LINE> <INDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super(RegistrationTemplateView, self).get_context_data( **kwargs ) <NEW_LINE> context['title'] = _('User registration') <NEW_LINE> return context | Class for rendering registration pages. | 6259907144b2445a339b75bf |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.