code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class ConcatTimeWindow(TimeWindow): <NEW_LINE> <INDENT> def __init__(self, windows): <NEW_LINE> <INDENT> if len(windows) < 1: <NEW_LINE> <INDENT> raise ValueError('At least one window should be given.') <NEW_LINE> <DEDENT> self.windows = windows <NEW_LINE> starts = [w.absolute_start for w in self.windows[1:]] <NEW_LINE> ends = self._ends()[:-1] <NEW_LINE> if max([abs(a - b) for a, b in zip(ends, starts)] + [0]) > TOL: <NEW_LINE> <INDENT> raise ValueError('Windows are not consecutive. ' 'Consider using ConcatTimeWindow.align.') <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def absolute_start(self): <NEW_LINE> <INDENT> return self.windows[0].absolute_start <NEW_LINE> <DEDENT> @property <NEW_LINE> def absolute_end(self): <NEW_LINE> <INDENT> return self.windows[-1].absolute_end <NEW_LINE> <DEDENT> def move(self, delta_t): <NEW_LINE> <INDENT> for w in self.windows: <NEW_LINE> <INDENT> w.move(delta_t) <NEW_LINE> <DEDENT> <DEDENT> def get_subwindow(self, t_start, t_end): <NEW_LINE> <INDENT> i_start = self._get_file_index_from_time(t_start) <NEW_LINE> i_end = self._get_file_index_from_time(t_end) <NEW_LINE> new_windows = [w.copy() for w in self.windows[i_start:1 + i_end]] <NEW_LINE> new_windows[0] = new_windows[0].get_subwindow( t_start, new_windows[0].absolute_end) <NEW_LINE> new_windows[-1] = new_windows[-1].get_subwindow( new_windows[-1].absolute_start, t_end) <NEW_LINE> return self.__class__(new_windows) <NEW_LINE> <DEDENT> def to_array_window(self): <NEW_LINE> <INDENT> array_windows = [win.to_array_window() for win in self.windows] <NEW_LINE> return ArrayTimeWindow.concatenate(array_windows) <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> return self.__class__([win.copy() for win in self.windows]) <NEW_LINE> <DEDENT> def get_subwindow_at(self, t): <NEW_LINE> <INDENT> return self.windows[self._get_file_index_from_time(t)] <NEW_LINE> <DEDENT> def _ends(self): <NEW_LINE> <INDENT> return [win.absolute_end for win in self.windows] <NEW_LINE> <DEDENT> def _get_file_index_from_time(self, t): <NEW_LINE> <INDENT> self.check_time(t) <NEW_LINE> return bisect.bisect_left(self._ends(), t) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def align(cls, windows, start=None): <NEW_LINE> <INDENT> if start is None: <NEW_LINE> <INDENT> start = windows[0].absolute_start <NEW_LINE> <DEDENT> t = start <NEW_LINE> for w in windows: <NEW_LINE> <INDENT> w.move(t - w.absolute_start) <NEW_LINE> t += w.duration() <NEW_LINE> <DEDENT> return windows | Sequence of consecutive time windows. | 6259904d91af0d3eaad3b263 |
class LimitExceededException(DatahubException): <NEW_LINE> <INDENT> def __init__(self, status_code, request_id, error_code, error_msg): <NEW_LINE> <INDENT> super(LimitExceededException, self).__init__(status_code, request_id, error_code, error_msg) | Too many request. | 6259904dbe383301e0254c5a |
@ppd.distribute() <NEW_LINE> class HelmholtzSystem(object): <NEW_LINE> <INDENT> def __init__(self, computationinfo, alpha=0.5,beta=0.5,delta=0.5): <NEW_LINE> <INDENT> self.alpha = alpha <NEW_LINE> self.beta = beta <NEW_LINE> self.delta = delta <NEW_LINE> self.internalassembly = computationinfo.faceAssembly() <NEW_LINE> self.volumeassembly = computationinfo.volumeAssembly() <NEW_LINE> self.weightedassembly = computationinfo.volumeAssembly(True) <NEW_LINE> self.problem = computationinfo.problem <NEW_LINE> self.computationinfo = computationinfo <NEW_LINE> self.boundaries = [self.getBoundary(entity, bdyinfo) for (entity, bdyinfo) in self.problem.bdyinfo.items()] <NEW_LINE> <DEDENT> def getBoundary(self, entity, bdyinfo): <NEW_LINE> <INDENT> return HelmholtzBoundary(self.computationinfo, entity, bdyinfo, self.delta) <NEW_LINE> <DEDENT> @ppd.parallelmethod(None, ppd.tuplesum) <NEW_LINE> def getSystem(self, dovolumes = False): <NEW_LINE> <INDENT> SI = self.internalStiffness() <NEW_LINE> SB = sum([b.stiffness() for b in self.boundaries]) <NEW_LINE> S = SI + SB <NEW_LINE> G = sum([b.load() for b in self.boundaries]) <NEW_LINE> if dovolumes: <NEW_LINE> <INDENT> S+=self.volumeStiffness() <NEW_LINE> <DEDENT> return S,G <NEW_LINE> <DEDENT> def internalStiffness(self): <NEW_LINE> <INDENT> jk = 1j * self.problem.k <NEW_LINE> AJ = pms.AveragesAndJumps(self.problem.mesh) <NEW_LINE> B = self.problem.mesh.boundary <NEW_LINE> SI = self.internalassembly.assemble([[jk * self.alpha * AJ.JD, -AJ.AN - B], [AJ.AD + B, -(self.beta / jk) * AJ.JN]]) <NEW_LINE> SFSI = pms.sumfaces(self.problem.mesh,SI) <NEW_LINE> return SFSI <NEW_LINE> <DEDENT> def volumeStiffness(self): <NEW_LINE> <INDENT> E = pms.ElementMatrices(self.problem.mesh) <NEW_LINE> L2K = self.weightedassembly.assemble([[E.I, E.Z],[E.Z, E.Z]]) <NEW_LINE> H1 = self.volumeassembly.assemble([[E.Z,E.Z],[E.Z, E.I]]) <NEW_LINE> AJ = pms.AveragesAndJumps(self.problem.mesh) <NEW_LINE> B = pms.sumfaces(self.problem.mesh, self.internalassembly.assemble([[AJ.Z,AJ.Z],[AJ.I,AJ.Z]])) <NEW_LINE> return H1 - L2K - B <NEW_LINE> <DEDENT> boundaryclass = HelmholtzBoundary | Assemble a system to solve a Helmholtz problem using the DG formulation of Gittelson et al.
It's parallelised so will only assemble the relevant bits of the system for the partition managed by
this process. | 6259904da219f33f346c7c41 |
class BindServiceView(ServiceView): <NEW_LINE> <INDENT> service_id = managed_services[0] <NEW_LINE> diagnostics_module_name = "bind" <NEW_LINE> description = description <NEW_LINE> show_status_block = True <NEW_LINE> form_class = BindForm <NEW_LINE> def get_initial(self): <NEW_LINE> <INDENT> initial = super().get_initial() <NEW_LINE> initial.update(get_default()) <NEW_LINE> return initial <NEW_LINE> <DEDENT> def form_valid(self, form): <NEW_LINE> <INDENT> data = form.cleaned_data <NEW_LINE> old_config = get_default() <NEW_LINE> if old_config['set_forwarding'] != data['set_forwarding']: <NEW_LINE> <INDENT> value = 'true' if data['set_forwarding'] else 'false' <NEW_LINE> actions.superuser_run( 'bind', ['configure', '--set-forwarding', value]) <NEW_LINE> messages.success(self.request, _('Set forwarding configuration updated')) <NEW_LINE> <DEDENT> if old_config['enable_dnssec'] != data['enable_dnssec']: <NEW_LINE> <INDENT> value = 'true' if data['enable_dnssec'] else 'false' <NEW_LINE> actions.superuser_run( 'bind', ['configure', '--enable-dnssec', value]) <NEW_LINE> messages.success(self.request, _('Enable DNSSEC configuration updated')) <NEW_LINE> <DEDENT> if old_config['forwarders'] != data['forwarders'] and old_config['forwarders'] is not '': <NEW_LINE> <INDENT> actions.superuser_run( 'bind', ['dns', '--set', data['forwarders']]) <NEW_LINE> messages.success(self.request, _('DNS server configuration updated')) <NEW_LINE> <DEDENT> elif old_config['forwarders'] is '' and old_config['forwarders'] != data['forwarders']: <NEW_LINE> <INDENT> messages.error( self.request, _('Enable forwarding to set forwarding DNS servers')) <NEW_LINE> <DEDENT> return super().form_valid(form) | A specialized view for configuring Bind. | 6259904d3eb6a72ae038ba9b |
class ValidationError(Exception): <NEW_LINE> <INDENT> def __init__(self, message=None): <NEW_LINE> <INDENT> self.message = message | This exception is used in tasks to indicate that a requirement has not been met. | 6259904d16aa5153ce40192d |
class ProtoError(Exception): <NEW_LINE> <INDENT> pass | Generic errors. | 6259904d07d97122c42180e3 |
class ComplexFormation(MEReaction): <NEW_LINE> <INDENT> def __init__(self, id): <NEW_LINE> <INDENT> MEReaction.__init__(self, id) <NEW_LINE> self._complex_id = None <NEW_LINE> self.complex_data_id = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def complex(self): <NEW_LINE> <INDENT> return self._model.metabolites.get_by_id(self._complex_id) <NEW_LINE> <DEDENT> def update(self, verbose=True): <NEW_LINE> <INDENT> self.clear_metabolites() <NEW_LINE> stoichiometry = defaultdict(float) <NEW_LINE> metabolites = self._model.metabolites <NEW_LINE> modifications = self._model.modification_data <NEW_LINE> complex_info = self._model.complex_data.get_by_id(self.complex_data_id) <NEW_LINE> try: <NEW_LINE> <INDENT> complex_met = metabolites.get_by_id(self._complex_id) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> complex_met = create_component(self._complex_id, default_type=Complex) <NEW_LINE> self._model.add_metabolites([complex_met]) <NEW_LINE> <DEDENT> stoichiometry[complex_met.id] = 1 <NEW_LINE> for component_id, value in iteritems(complex_info.stoichiometry): <NEW_LINE> <INDENT> stoichiometry[component_id] -= value <NEW_LINE> <DEDENT> stoichiometry = self.add_modifications(complex_info.id, stoichiometry) <NEW_LINE> object_stoichiometry = self.get_components_from_ids( stoichiometry, default_type=Complex, verbose=verbose) <NEW_LINE> elements = defaultdict(int) <NEW_LINE> cofactor_biomass = 0. <NEW_LINE> for component, value in iteritems(object_stoichiometry): <NEW_LINE> <INDENT> if isinstance(value, Basic): <NEW_LINE> <INDENT> value = value.subs(mu, 0) <NEW_LINE> <DEDENT> if component == complex_met: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for e, n in iteritems(component.elements): <NEW_LINE> <INDENT> elements[e] += n * -int(value) <NEW_LINE> <DEDENT> if len(modifications.query('mod_' + component.id)) > 0 and value < 0.: <NEW_LINE> <INDENT> cofactor_biomass += component.formula_weight / 1000. * -value <NEW_LINE> <DEDENT> <DEDENT> if cofactor_biomass > 0: <NEW_LINE> <INDENT> self.add_metabolites({self._model._biomass: cofactor_biomass}) <NEW_LINE> <DEDENT> complex_met.formula = "".join(stringify(e, n) for e, n in sorted(iteritems(elements))) <NEW_LINE> self.add_metabolites(object_stoichiometry, combine=False, add_to_container_model=False) | Formation of a functioning enzyme complex that can act as a catalyst for
metabolic reactions or other reactions involved in gene expression.
This reaction class produces a reaction that combines the protein subunits
and any cofactors or prosthetic groups into a complete enzyme complex.
:param str _complex_id:
Name of the complex being produced by the complex formation reaction
:param str complex_data_id:
Name of ComplexData that defines the subunit stoichiometry or
modifications. This will not always be the same as the _complex_id.
Sometimes complexes can be modified using different processes/enzymes | 6259904d0a50d4780f7067dd |
class LocatedElementPermission(permissions.BasePermission): <NEW_LINE> <INDENT> message = 'Adding customers not allowed.' <NEW_LINE> def has_object_permission(self, request, view, obj): <NEW_LINE> <INDENT> print('perm', request.method, view) <NEW_LINE> return isinstance(obj, LocatedElement) | Located element permission. | 6259904dbaa26c4b54d506eb |
class ExistFileHandler(Base): <NEW_LINE> <INDENT> async def get(self): <NEW_LINE> <INDENT> md5 = self.get_argument("md5") <NEW_LINE> suffix = self.get_argument("suffix") <NEW_LINE> file_context = syncFile.Component("files") <NEW_LINE> try: <NEW_LINE> <INDENT> self.write_dict({"ieExist": file_context.is_exist_md5(md5, suffix)}) <NEW_LINE> <DEDENT> except AssertionError as ae: <NEW_LINE> <INDENT> self.throw(406, "非法请求") | 获取md5文件是否存在
文件分块上传接口::
http://127.0.0.1:8095/file/exist
get:访问
需要参数:md5,suffix
suffix标识后缀名,如png mp4 jpg等 | 6259904d8da39b475be04631 |
class AutoencoderWrapper(WrapperBase): <NEW_LINE> <INDENT> def __init__(self, batch_env): <NEW_LINE> <INDENT> super(AutoencoderWrapper, self).__init__(batch_env) <NEW_LINE> batch_size, height, width, _ = self._batch_env.observ.get_shape().as_list() <NEW_LINE> ae_height = int(math.ceil(height / self.autoencoder_factor)) <NEW_LINE> ae_width = int(math.ceil(width / self.autoencoder_factor)) <NEW_LINE> ae_channels = 24 <NEW_LINE> observ_shape = (batch_size, ae_height, ae_width, ae_channels) <NEW_LINE> self._observ = self._observ = tf.Variable( tf.zeros(observ_shape, tf.float32), trainable=False) <NEW_LINE> with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE): <NEW_LINE> <INDENT> autoencoder_hparams = autoencoders.autoencoder_discrete_pong() <NEW_LINE> self.autoencoder_model = autoencoders.AutoencoderOrderedDiscrete( autoencoder_hparams, tf.estimator.ModeKeys.EVAL) <NEW_LINE> <DEDENT> self.autoencoder_model.set_mode(tf.estimator.ModeKeys.EVAL) <NEW_LINE> <DEDENT> @property <NEW_LINE> def autoencoder_factor(self): <NEW_LINE> <INDENT> hparams = autoencoders.autoencoder_discrete_pong() <NEW_LINE> return 2**hparams.num_hidden_layers <NEW_LINE> <DEDENT> def simulate(self, action): <NEW_LINE> <INDENT> reward, done = self._batch_env.simulate(action) <NEW_LINE> with tf.control_dependencies([reward, done]): <NEW_LINE> <INDENT> with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE): <NEW_LINE> <INDENT> ret = self.autoencoder_model.encode(self._batch_env.observ) <NEW_LINE> assign_op = self._observ.assign(ret) <NEW_LINE> with tf.control_dependencies([assign_op]): <NEW_LINE> <INDENT> return tf.identity(reward), tf.identity(done) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def _reset_non_empty(self, indices): <NEW_LINE> <INDENT> with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE): <NEW_LINE> <INDENT> new_values = self._batch_env._reset_non_empty(indices) <NEW_LINE> ret = self.autoencoder_model.encode(new_values) <NEW_LINE> assign_op = tf.scatter_update(self._observ, indices, ret) <NEW_LINE> with tf.control_dependencies([assign_op]): <NEW_LINE> <INDENT> return tf.gather(self.observ, indices) | Transforms the observations taking the bottleneck
state of an autoencoder | 6259904d21a7993f00c673a9 |
class NSNitroNserrDigestupdateFailed(NSNitroGslbErrors): <NEW_LINE> <INDENT> pass | Nitro error code 1988
Digest update before RSA Sign operation returned error | 6259904dd10714528d69f0ae |
class Sinusoid(Signal): <NEW_LINE> <INDENT> def __init__(self, freq=440, amp=1.0, offset=0, func=np.sin): <NEW_LINE> <INDENT> self.freq = freq <NEW_LINE> self.amp = amp <NEW_LINE> self.offset = offset <NEW_LINE> self.func = func <NEW_LINE> <DEDENT> @property <NEW_LINE> def period(self): <NEW_LINE> <INDENT> return 1.0 / self.freq <NEW_LINE> <DEDENT> def evaluate(self, ts): <NEW_LINE> <INDENT> ts = np.asarray(ts) <NEW_LINE> phases = PI2 * self.freq * ts + self.offset <NEW_LINE> ys = self.amp * self.func(phases) <NEW_LINE> return ys | Represents a sinusoidal signal. | 6259904dec188e330fdf9ce0 |
class TallyRoles(enum.IntEnum): <NEW_LINE> <INDENT> screenIndexRole = Qt.UserRole + 1 <NEW_LINE> tallyIndexRole = Qt.UserRole + 2 <NEW_LINE> RhTallyRole = Qt.UserRole + 3 <NEW_LINE> TxtTallyRole = Qt.UserRole + 4 <NEW_LINE> LhTallyRole = Qt.UserRole + 5 <NEW_LINE> TextRole = int(Qt.DisplayRole) <NEW_LINE> def get_tally_prop(self) -> str: <NEW_LINE> <INDENT> prop = self.name.split('Role')[0] <NEW_LINE> if prop == 'screenIndex': <NEW_LINE> <INDENT> return 'screen.index' <NEW_LINE> <DEDENT> elif prop == 'tallyIndex': <NEW_LINE> <INDENT> return 'index' <NEW_LINE> <DEDENT> elif 'Tally' in prop: <NEW_LINE> <INDENT> s = prop.split('Tally')[0].lower() <NEW_LINE> return f'{s}_tally' <NEW_LINE> <DEDENT> return prop.lower() <NEW_LINE> <DEDENT> def get_tally_prop_value(self, tally: Tally) -> Any: <NEW_LINE> <INDENT> prop = self.get_tally_prop() <NEW_LINE> if '.' in prop: <NEW_LINE> <INDENT> obj = tally <NEW_LINE> for attr in prop.split('.'): <NEW_LINE> <INDENT> obj = getattr(obj, attr) <NEW_LINE> <DEDENT> return obj <NEW_LINE> <DEDENT> return getattr(tally, prop) <NEW_LINE> <DEDENT> def get_qt_prop(self) -> str: <NEW_LINE> <INDENT> prop = self.name.split('Role')[0] <NEW_LINE> if 'Index' in prop: <NEW_LINE> <INDENT> return prop <NEW_LINE> <DEDENT> if 'Tally' in prop: <NEW_LINE> <INDENT> s = prop.split('Tally')[0].lower() <NEW_LINE> return f'{s}Tally' <NEW_LINE> <DEDENT> return prop.lower() | Role definitions to specify column mapping in :class:`TallyListModel` to
a ``QtQuick.TableView`` | 6259904dbe383301e0254c5c |
class RicciScalar(object): <NEW_LINE> <INDENT> def __init__(self,Ric,g): <NEW_LINE> <INDENT> self.Ric = Ric <NEW_LINE> self.g = g <NEW_LINE> <DEDENT> def value(self): <NEW_LINE> <INDENT> Ric = self.Ric <NEW_LINE> g = self.g <NEW_LINE> RS = 0 <NEW_LINE> for mu in [0,1,2,3]: <NEW_LINE> <INDENT> for nu in [0,1,2,3]: <NEW_LINE> <INDENT> RS += g.uu(mu,nu)*Ric.dd(mu,nu) <NEW_LINE> <DEDENT> <DEDENT> return RS.simplify() | Calculate Ricci scalar from Ricci tensor | 6259904d0a366e3fb87dde27 |
class UITestCase(unittest.TestCase): <NEW_LINE> <INDENT> net = False <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> super(UITestCase, self).setUp() <NEW_LINE> patch() <NEW_LINE> pywikibot.config.colorized_output = True <NEW_LINE> pywikibot.config.transliterate = False <NEW_LINE> pywikibot.ui.transliteration_target = None <NEW_LINE> pywikibot.ui.encoding = 'utf-8' <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> super(UITestCase, self).tearDown() <NEW_LINE> unpatch() <NEW_LINE> <DEDENT> def _encode(self, string, encoding='utf-8'): <NEW_LINE> <INDENT> if not PY2: <NEW_LINE> <INDENT> return string <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return string.encode(encoding) | UI tests. | 6259904d4e696a045264e841 |
class CreateCustomerGatewayRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.CustomerGatewayName = None <NEW_LINE> self.IpAddress = None <NEW_LINE> self.Tags = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.CustomerGatewayName = params.get("CustomerGatewayName") <NEW_LINE> self.IpAddress = params.get("IpAddress") <NEW_LINE> if params.get("Tags") is not None: <NEW_LINE> <INDENT> self.Tags = [] <NEW_LINE> for item in params.get("Tags"): <NEW_LINE> <INDENT> obj = Tag() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.Tags.append(obj) | CreateCustomerGateway请求参数结构体
| 6259904dcb5e8a47e493cba7 |
class M3_OT_export(bpy.types.Operator, ExportHelper): <NEW_LINE> <INDENT> bl_idname = "m3.export" <NEW_LINE> bl_label = "Export M3 Model" <NEW_LINE> bl_options = {'UNDO'} <NEW_LINE> filename_ext = ".m3" <NEW_LINE> filter_glob = StringProperty(default="*.m3", options={'HIDDEN'}) <NEW_LINE> filepath = bpy.props.StringProperty( name="File Path", description="Path of the file that should be created", maxlen= 1024, default= "") <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> print("Export", self.properties.filepath) <NEW_LINE> scene = context.scene <NEW_LINE> if not "m3export" in locals(): <NEW_LINE> <INDENT> from . import m3export <NEW_LINE> <DEDENT> scene.m3_export_options.path = self.properties.filepath <NEW_LINE> m3export.export(scene, self.properties.filepath) <NEW_LINE> return {'FINISHED'} <NEW_LINE> <DEDENT> def invoke(self, context, event): <NEW_LINE> <INDENT> context.window_manager.fileselect_add(self) <NEW_LINE> return {'RUNNING_MODAL'} | Export a M3 file | 6259904d29b78933be26aae3 |
class AdvancedEditForm(AdagiosForm): <NEW_LINE> <INDENT> register = forms.CharField( required=False, help_text=_("Set to 1 if you want this object enabled.")) <NEW_LINE> name = forms.CharField(required=False, label=_("Generic Name"), help_text=_("This name is used if you want other objects to inherit (with the use attribute) what you have defined here.")) <NEW_LINE> use = forms.CharField(required=False, label=_("Use"), help_text=_("Inherit all settings from another object")) <NEW_LINE> __prefix = "advanced" <NEW_LINE> def save(self): <NEW_LINE> <INDENT> for k in self.changed_data: <NEW_LINE> <INDENT> value = smart_str(self.cleaned_data[k]) <NEW_LINE> if self.pynag_object[k] == value: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if value == '': <NEW_LINE> <INDENT> value = None <NEW_LINE> <DEDENT> self.pynag_object[k] = value <NEW_LINE> <DEDENT> self.pynag_object.save() <NEW_LINE> <DEDENT> def clean(self): <NEW_LINE> <INDENT> cleaned_data = super(AdvancedEditForm, self).clean() <NEW_LINE> for k, v in cleaned_data.items(): <NEW_LINE> <INDENT> cleaned_data[k] = smart_str(v) <NEW_LINE> <DEDENT> return cleaned_data <NEW_LINE> <DEDENT> def __init__(self, pynag_object, *args, **kwargs): <NEW_LINE> <INDENT> self.pynag_object = pynag_object <NEW_LINE> super(AdvancedEditForm, self).__init__( *args, prefix=self.__prefix, **kwargs) <NEW_LINE> object_type = pynag_object['object_type'] <NEW_LINE> all_attributes = sorted(object_definitions.get(object_type).keys()) <NEW_LINE> for field_name in self.pynag_object.keys() + all_attributes: <NEW_LINE> <INDENT> if field_name in PYNAG_ATTRIBUTES: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> help_text = "" <NEW_LINE> if field_name in object_definitions[object_type]: <NEW_LINE> <INDENT> help_text = object_definitions[object_type][field_name].get( 'help_text', _("No help available for this item")) <NEW_LINE> <DEDENT> self.fields[field_name] = forms.CharField( required=False, label=field_name, help_text=help_text) <NEW_LINE> <DEDENT> self.fields.keyOrder = sorted(self.fields.keys()) | A form for pynag.Model.Objectdefinition
This form will display a charfield for every attribute of the objectdefinition
"Every" attribute means:
* Every defined attribute
* Every inherited attribute
* Every attribute that is defined in nagios object definition html | 6259904de64d504609df9df0 |
class HTTP1ServerConnection(object): <NEW_LINE> <INDENT> def __init__(self, stream, params=None, context=None): <NEW_LINE> <INDENT> self.stream = stream <NEW_LINE> if params is None: <NEW_LINE> <INDENT> params = HTTP1ConnectionParameters() <NEW_LINE> <DEDENT> self.params = params <NEW_LINE> self.context = context <NEW_LINE> self._serving_future = None <NEW_LINE> <DEDENT> @gen.coroutine <NEW_LINE> def close(self): <NEW_LINE> <INDENT> self.stream.close() <NEW_LINE> try: <NEW_LINE> <INDENT> yield self._serving_future <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def start_serving(self, delegate): <NEW_LINE> <INDENT> assert isinstance(delegate, httputil.HTTPServerConnectionDelegate) <NEW_LINE> self._serving_future = self._server_request_loop(delegate) <NEW_LINE> self.stream.io_loop.add_future(self._serving_future, lambda f: f.result()) <NEW_LINE> <DEDENT> @gen.coroutine <NEW_LINE> def _server_request_loop(self, delegate): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> conn = HTTP1Connection(self.stream, False, self.params, self.context) <NEW_LINE> request_delegate = delegate.start_request(self, conn) <NEW_LINE> try: <NEW_LINE> <INDENT> ret = yield conn.read_response(request_delegate) <NEW_LINE> <DEDENT> except (iostream.StreamClosedError, iostream.UnsatisfiableReadError): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> except _QuietException: <NEW_LINE> <INDENT> conn.close() <NEW_LINE> return <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> gen_log.error("Uncaught exception", exc_info=True) <NEW_LINE> conn.close() <NEW_LINE> return <NEW_LINE> <DEDENT> if not ret: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> yield gen.moment <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> delegate.on_close(self) | An HTTP/1.x server. | 6259904d498bea3a75a58f62 |
class UserProfileForm(forms.ModelForm): <NEW_LINE> <INDENT> first_name = forms.CharField(label='First Name', required=False) <NEW_LINE> last_name = forms.CharField(label='Last Name', required=False) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = UserProfile <NEW_LINE> exclude = ('clients', 'user', 'active', 'created_by') | Lets a user edit its profile. | 6259904d004d5f362081fa09 |
class PriceSheetApi(LogisticsMessageApi): <NEW_LINE> <INDENT> def freight_list(self, url, method): <NEW_LINE> <INDENT> resp = request(url=f"{Admin_Host}{url}", method=method, headers=json_header, cookies=self.cookie) <NEW_LINE> return resp <NEW_LINE> <DEDENT> def freight_add(self, url, method, in_body, channel_id): <NEW_LINE> <INDENT> in_body = json.loads(in_body) <NEW_LINE> in_body['channelIds'] = [channel_id] <NEW_LINE> resp = request(url=f"{Admin_Host}{url}", method=method, data=in_body, headers=json_header, cookies=self.cookie) <NEW_LINE> return resp <NEW_LINE> <DEDENT> def freight_read(self, url, method, freight_id): <NEW_LINE> <INDENT> resp = request(url=f"{Admin_Host}{url}{freight_id}", method=method, headers=json_header, cookies=self.cookie) <NEW_LINE> return resp <NEW_LINE> <DEDENT> def freight_edit(self, url, method, in_body, freight_id, channel_id): <NEW_LINE> <INDENT> in_body = json.loads(in_body) <NEW_LINE> in_body['id'] = freight_id <NEW_LINE> in_body['channelIds'] = channel_id <NEW_LINE> resp = request(url=f"{Admin_Host}{url}", method=method, data=in_body, headers=json_header, cookies=self.cookie) <NEW_LINE> return resp <NEW_LINE> <DEDENT> def freight_page(self, url, method, in_body): <NEW_LINE> <INDENT> resp = request( url=f"{Admin_Host}{url}", method=method, data=json.loads(in_body), headers=json_header, cookies=self.cookie) <NEW_LINE> return resp <NEW_LINE> <DEDENT> def freight_del(self, url, method, freight_id): <NEW_LINE> <INDENT> resp = request(url=f"{Admin_Host}{url}", method=method, data=freight_id, headers=json_header, cookies=self.cookie) <NEW_LINE> return resp | 报价单 | 6259904de76e3b2f99fd9e42 |
class AdjustArmatureOrigin(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "object.adjust_armature_origin" <NEW_LINE> bl_label = "[Urchin] Adjust Armature Origin" <NEW_LINE> bl_options = {'REGISTER', 'UNDO'} <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> bpy.ops.object.select_by_type(type='ARMATURE') <NEW_LINE> bpy.ops.object.transform_apply(location=False, rotation=True, scale=True) <NEW_LINE> bpy.ops.view3d.snap_cursor_to_center() <NEW_LINE> bpy.ops.view3d.snap_selected_to_cursor() <NEW_LINE> return {'FINISHED'} | Adjust Armature Origin: move armature to world origin | 6259904d50485f2cf55dc3ce |
class Sites(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._sites = [] <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return repr(self._sites) <NEW_LINE> <DEDENT> def set_defaults(self, section): <NEW_LINE> <INDENT> self.base_content = section.get('base_content', 'site#content.base') <NEW_LINE> self.timezone = section.get('timezone', 'UTC') <NEW_LINE> self.user_timezone = section.get_bool('user_timezone', True) <NEW_LINE> self.append_slash = section.get_bool('append_slash', False) <NEW_LINE> self.locale = section.get('locale', 'en_US.UTF-8') <NEW_LINE> self.language = section.get('language', 'en-US') <NEW_LINE> self.datetime_format = section.get('datetime_format', 'medium') <NEW_LINE> self.date_format = section.get('date_format', 'medium') <NEW_LINE> self.time_format = section.get('time_format', 'medium') <NEW_LINE> self.timespan_format = section.get('timespan_format', 'medium') <NEW_LINE> <DEDENT> def add_from_section(self, domains, section): <NEW_LINE> <INDENT> kwargs = { "base_content": section.get('base_content', self.base_content), "timezone": section.get('timezone', self.timezone), "user_timezone": section.get_bool('user_timezone', self.user_timezone), "append_slash": section.get('append_slash', self.append_slash), "language": section.get('language', self.language), "locale": section.get('locale', self.locale), "datetime_format": section.get('datetime_format', self.datetime_format), "date_format": section.get('date_format', self.date_format), "time_format": section.get('time_format', self.time_format), 'timespan_format': section.get('timespan_format', self.timespan_format) } <NEW_LINE> data = {} <NEW_LINE> for k, v in iteritems(section): <NEW_LINE> <INDENT> if k.startswith('data-'): <NEW_LINE> <INDENT> data_k = k.split('-', 1)[1] <NEW_LINE> data[data_k] = v <NEW_LINE> <DEDENT> <DEDENT> for domain in domains.split(','): <NEW_LINE> <INDENT> domain = domain.strip() <NEW_LINE> site = Site(domain, data=data, **kwargs) <NEW_LINE> self._sites.append(site) <NEW_LINE> <DEDENT> <DEDENT> def add(self, domains, **data): <NEW_LINE> <INDENT> for domain in domains.split(','): <NEW_LINE> <INDENT> domain = domain.strip() <NEW_LINE> site = Site(domain, data=data) <NEW_LINE> self._sites.append(site) <NEW_LINE> <DEDENT> <DEDENT> def match(self, domain): <NEW_LINE> <INDENT> for site in self._sites: <NEW_LINE> <INDENT> site_data = site.match(domain) <NEW_LINE> if site_data is not None: <NEW_LINE> <INDENT> return SiteMatch(site, site_data) <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def __contains__(self, domain): <NEW_LINE> <INDENT> return self.match(domain) is not None | A container that maps site wild-cards on to a dictionary | 6259904d50485f2cf55dc3cf |
class Tariff(models.Model): <NEW_LINE> <INDENT> id = fields.UUIDField(pk=True) <NEW_LINE> cargo_type = fields.ForeignKeyField('models.CargoType') <NEW_LINE> date = fields.DateField(index=True) <NEW_LINE> rate = fields.FloatField() | Модель тарифа | 6259904d07f4c71912bb0877 |
class PostDetailView(LoginRequiredMixin, DetailView): <NEW_LINE> <INDENT> template_name = 'posts/post_detail.html' <NEW_LINE> slug_field = 'id' <NEW_LINE> slug_url_kwarg = 'post_id' <NEW_LINE> queryset = Post.objects.all() <NEW_LINE> context_object_name = 'post' | Return a detail view about one post | 6259904d21a7993f00c673ab |
class Gaussian(Noise): <NEW_LINE> <INDENT> def __init__(self, offset=0., scale=1.): <NEW_LINE> <INDENT> Noise.__init__(self) <NEW_LINE> self.scale = scale <NEW_LINE> self.offset = offset <NEW_LINE> self.variance = scale*scale <NEW_LINE> <DEDENT> def log_likelihood(self, mu, varsigma, y): <NEW_LINE> <INDENT> n = y.shape[0] <NEW_LINE> d = y.shape[1] <NEW_LINE> varsigma = varsigma + self.scale*self.scale <NEW_LINE> for i in range(d): <NEW_LINE> <INDENT> mu[:, i] += self.offset[i] <NEW_LINE> <DEDENT> arg = (y - mu); <NEW_LINE> arg = arg*arg/varsigma <NEW_LINE> return - 0.5*(log(varsigma).sum() + arg.sum() + n*d*log(2*pi)) <NEW_LINE> <DEDENT> def grad_vals(self, mu, varsigma, y): <NEW_LINE> <INDENT> d = y.shape[1] <NEW_LINE> nu = 1/(self.scale*self.scale+varsigma) <NEW_LINE> dlnZ_dmu = zeros(nu.shape) <NEW_LINE> for i in range(d): <NEW_LINE> <INDENT> dlnZ_dmu[:, i] = y[:, i] - mu[:, i] - self.offset[i] <NEW_LINE> <DEDENT> dlnZ_dmu = dlnZ_dmu*nu <NEW_LINE> dlnZ_dvs = 0.5*(dlnZ_dmu*dlnZ_dmu - nu) <NEW_LINE> return dlnZ_dmu, dlnZ_dvs | Gaussian Noise Model. | 6259904d3c8af77a43b6895f |
class Recipe(models.Model): <NEW_LINE> <INDENT> user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) <NEW_LINE> title = models.CharField(max_length=255) <NEW_LINE> time_minutes = models.IntegerField() <NEW_LINE> price = models.DecimalField(max_digits=5,decimal_places=2) <NEW_LINE> link = models.CharField(max_length=255,blank=True) <NEW_LINE> ingredients = models.ManyToManyField('Ingredient') <NEW_LINE> tags = models.ManyToManyField('Tag') <NEW_LINE> image = models.ImageField(null=True,upload_to=recipe_image_file_path) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.title | recipe object model | 6259904d63d6d428bbee3c0e |
class PlotLine(object): <NEW_LINE> <INDENT> def __init__(self, mesh, mapping): <NEW_LINE> <INDENT> hmin = MPI.min(None, mesh.hmin()) <NEW_LINE> self.mesh = UnitIntervalMesh(int(1.0/hmin)) <NEW_LINE> self.V = FunctionSpace(self.mesh, "CG", 1) <NEW_LINE> self.F = {} <NEW_LINE> self.mapping = mapping <NEW_LINE> <DEDENT> def __call__(self, expr, title): <NEW_LINE> <INDENT> if not expr in self.F: <NEW_LINE> <INDENT> self.F[expr] = Function(self.V) <NEW_LINE> <DEDENT> v = self.F[expr].vector() <NEW_LINE> index_map = dof_to_vertex_map(self.V) <NEW_LINE> for i,x in enumerate(self.mesh.coordinates()[index_map]): <NEW_LINE> <INDENT> v[i] = expr(self.mapping(x)) <NEW_LINE> <DEDENT> plot(self.F[expr], title=title) | Line plot along x=[0,1] in a domain of any dimension. The mapping
argument maps from the interval [0,1] to a xD coordinate (a list when
dim>1). | 6259904dec188e330fdf9ce2 |
class ReplicapoolupdaterZoneOperationsListRequest(_messages.Message): <NEW_LINE> <INDENT> filter = _messages.StringField(1) <NEW_LINE> maxResults = _messages.IntegerField(2, variant=_messages.Variant.UINT32, default=500) <NEW_LINE> pageToken = _messages.StringField(3) <NEW_LINE> project = _messages.StringField(4, required=True) <NEW_LINE> zone = _messages.StringField(5, required=True) | A ReplicapoolupdaterZoneOperationsListRequest object.
Fields:
filter: Optional. Filter expression for filtering listed resources.
maxResults: Optional. Maximum count of results to be returned. Maximum
value is 500 and default value is 500.
pageToken: Optional. Tag returned by a previous list request truncated by
maxResults. Used to continue a previous list request.
project: Name of the project scoping this request.
zone: Name of the zone scoping this request. | 6259904d26068e7796d4dd87 |
class UnzipFunction(Function): <NEW_LINE> <INDENT> name = 'unzip' <NEW_LINE> def __call__(self, filename, flags=''): <NEW_LINE> <INDENT> sh = ShellFunction(self.build, self.log, self.verbose, self.message) <NEW_LINE> if 'o' not in flags: <NEW_LINE> <INDENT> flags += 'o' <NEW_LINE> <DEDENT> if flags: <NEW_LINE> <INDENT> flags = '-' + flags + ' ' <NEW_LINE> <DEDENT> sh('unzip %s%s' % (flags, filename)) <NEW_LINE> paths = {} <NEW_LINE> _in = False <NEW_LINE> result = check_output('unzip -l %s' % filename, shell=True, cwd=os.getcwd(), universal_newlines=True) <NEW_LINE> for line in result.splitlines(): <NEW_LINE> <INDENT> line = line.lstrip() <NEW_LINE> if line.lstrip().startswith('----'): <NEW_LINE> <INDENT> if not _in: <NEW_LINE> <INDENT> _in = True <NEW_LINE> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if not _in: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> p = line.split()[3].split('/', 1)[0] <NEW_LINE> paths[p] = paths.setdefault(p, 0) + 1 <NEW_LINE> <DEDENT> <DEDENT> if not paths: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> if len(paths) == 1: <NEW_LINE> <INDENT> return list(paths.keys())[0] <NEW_LINE> <DEDENT> for x, y in reversed([(v, k) for k, v in paths.items()]): <NEW_LINE> <INDENT> return y | Execute unzip command, default is 'unzip filename', and it'll guess the extracted
directory and return it. It'll overwrite existed by default. | 6259904d379a373c97d9a46e |
class LoadedMod: <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> self.__name__ = name <NEW_LINE> self._vars = {} <NEW_LINE> self._funcs = {} <NEW_LINE> self._classes = {} <NEW_LINE> self._attrs = {} <NEW_LINE> <DEDENT> def __getattr__(self, item): <NEW_LINE> <INDENT> if item in self._attrs: <NEW_LINE> <INDENT> return self._attrs[item] <NEW_LINE> <DEDENT> raise AttributeError(item) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> keys = sorted(self._funcs) <NEW_LINE> ret = [] <NEW_LINE> for key in keys: <NEW_LINE> <INDENT> ret.append(self._funcs[key]) <NEW_LINE> <DEDENT> return iter(ret) <NEW_LINE> <DEDENT> def __dir__(self): <NEW_LINE> <INDENT> ret = list(self._attrs.keys()) <NEW_LINE> ret.extend(["__name__", "_vars", "_funcs", "_classes", "_attrs"]) <NEW_LINE> return ret | The LoadedMod class allows for the module loaded onto the sub to return
custom sequencing, for instance it can be iterated over to return all
functions | 6259904dd6c5a102081e3561 |
class Context(Token): <NEW_LINE> <INDENT> def __init__(self, label, certain=False): <NEW_LINE> <INDENT> self.label = [p or None for p in label] <NEW_LINE> self.certain = certain <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Context([ %s , certain=%s ])" % ( ', '.join(_none_str(l) for l in self.label), self.certain) | Represents a bit of context for the paragraphs. This gets compressed
with the paragraph tokens to define the full scope of a paragraph. To
complicate matters, sometimes what looks like a Context is actually the
entity which is being modified (i.e. a paragraph). If we are certain
that this is only context, (e.g. "In Subpart A"), use 'certain' | 6259904d23e79379d538d940 |
class NormalizeScanOrder(ProjectSpecificMixin, APIView): <NEW_LINE> <INDENT> parser_classes = (JSONParser,) <NEW_LINE> permission_classes = (ProjectSpecificPermissions,) <NEW_LINE> permissions = { 'POST': ('main.change_document',) } <NEW_LINE> def get_object(self): <NEW_LINE> <INDENT> qs = Document.objects .filter(project__id=self.request.project.id, id=self.kwargs.get('document_id')) .select_related('scans') <NEW_LINE> return get_object_or_404(qs) <NEW_LINE> <DEDENT> def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> document = self.get_object() <NEW_LINE> self.check_object_permissions(self.request, document) <NEW_LINE> step = int(request.GET.get('step', 100)) <NEW_LINE> document.scans.normalize_ordering_values('ordering', step=step, fill_in_empty=True) <NEW_LINE> return Response([ { 'id': _id, 'ordering': ordering } for _id, ordering in document.scans.values_list('id', 'ordering') ]) | Normalize the order of a document's scans. Items will remain in the same
order, but their `ordering` property will be equally spaced out.
@param step: integer indicating the step between each ordering value.
Default 100. | 6259904d30c21e258be99c49 |
class MetroDateInput(DateInput): <NEW_LINE> <INDENT> input_type = 'text' <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> kwargs['attrs'] = {'class': 'metrodatepicker input-control'} <NEW_LINE> super(MetroDateInput, self).__init__(*args, **kwargs) | A date input, Date ranging from yesterday to last day of this timeslot. Using Y-m-d
converted to a nice picker using jquery datetimepicker in genericForm.html | 6259904d3cc13d1c6d466b7c |
class AdaptedDTPHandler(DTPHandler): <NEW_LINE> <INDENT> file_path = None <NEW_LINE> _new_file_id = None <NEW_LINE> _file_uploader = None <NEW_LINE> @property <NEW_LINE> def file_obj(self): <NEW_LINE> <INDENT> if self.file_path is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> elif self._file_uploader is None: <NEW_LINE> <INDENT> self._file_uploader = FileUploader(self.cmd_channel.fs.file_system_view, self.file_path, self._new_file_id) <NEW_LINE> <DEDENT> return self._file_uploader <NEW_LINE> <DEDENT> @file_obj.setter <NEW_LINE> def file_obj(self, obj): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self, sock, cmd_channel): <NEW_LINE> <INDENT> super(AdaptedDTPHandler, self).__init__(sock, cmd_channel) <NEW_LINE> <DEDENT> def _posix_ascii_data_wrapper(self, chunk): <NEW_LINE> <INDENT> return chunk <NEW_LINE> <DEDENT> def enable_receiving(self, type, cmd): <NEW_LINE> <INDENT> self.file_path = self.cmd_channel.upload_path <NEW_LINE> file_system_view = self.cmd_channel.fs.file_system_view <NEW_LINE> self._new_file_id = file_system_view.create_new_file() <NEW_LINE> super(AdaptedDTPHandler, self).enable_receiving(type, cmd) <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> if not self._closed and self.file_obj != None: <NEW_LINE> <INDENT> file_system_view = self.cmd_channel.fs.file_system_view <NEW_LINE> if self.transfer_finished: <NEW_LINE> <INDENT> file_system_view.commit_new_file(self._new_file_id, self.file_path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> file_system_view.flush_new_file(self._new_file_id) <NEW_LINE> <DEDENT> self._file_uploader = None <NEW_LINE> <DEDENT> self.cmd_channel._on_dtp_close() <NEW_LINE> super(AdaptedDTPHandler, self).close() | DTPHandler is the class handling data transfer between the server and the clients.
AdaptedDTPHandler inherits from it to adapt the file upload process (from the FTP client
to the server) to the use of cloudalpha.file_system.FileSystem subclasses. | 6259904d0fa83653e46f6322 |
class AuthModeUnknown(CFMEException): <NEW_LINE> <INDENT> pass | Raised if an invalid authenctication mode is passed to
:py:func:`cfme.configure.configuration.ServerAuthentication.configure_auth` | 6259904d8e7ae83300eea4d8 |
class OfflineRequest(DummyRequest): <NEW_LINE> <INDENT> implements(IRequest) | Use this in places where you don't have an HTTP request to get alternate
registration of IContextURL. | 6259904d23e79379d538d941 |
class Matyas(Problem2D): <NEW_LINE> <INDENT> def init_tensors(self, seed=None): <NEW_LINE> <INDENT> return [tf.random_uniform(shape, minval=-10, maxval=10, seed=seed) for shape in self.param_shapes] <NEW_LINE> <DEDENT> def objective(self, params, data=None, labels=None): <NEW_LINE> <INDENT> x, y = tf.split(params[0], 2, axis=0) <NEW_LINE> obj = 0.26 * (x ** 2 + y ** 2) - 0.48 * x * y <NEW_LINE> return tf.squeeze(obj) | Matyas function (a function with a single global minimum in a valley). | 6259904dd4950a0f3b111865 |
class ShowChassisHardwareSchema(MetaParser): <NEW_LINE> <INDENT> schema = { Optional("@xmlns:junos"): str, "chassis-inventory": { Optional("@xmlns"): str, "chassis": { Optional("@junos:style"): str, Optional("chassis-module"): ListOf({ Optional("chassis-re-dimm-module"): ListOf({ "die-rev": str, "mfr-id": str, "name": str, "part-number": str, "pcb-rev": str, }), Optional("chassis-re-disk-module"): ListOf({ "description": str, "disk-size": str, "model": str, "name": str, "serial-number": str }), Optional("chassis-re-usb-module"): ListOf({ Optional("description"): str, "name": str, "product": str, "product-number": str, "vendor": str, }), Optional("chassis-sub-module"): ListOf({ Optional("chassis-sub-sub-module"): ListOf({ Optional("description"): str, Optional("name"): str, Optional("part-number"): str, Optional("serial-number"): str, Optional("chassis-sub-sub-sub-module"): ListOf({ Optional("description"): str, Optional("name"): str, Optional("part-number"): str, Optional("serial-number"): str, Optional("version"): str }) }), Optional("description"): str, Optional("name"): str, Optional("part-number"): str, Optional("serial-number"): str, Optional("version"): str }), Optional("description"): str, Optional("name"): str, Optional("part-number"): str, Optional("serial-number"): str, Optional("version"): str, }), Optional("description"): str, Optional("name"): str, Optional("serial-number"): str } } } | schema = {
Optional("@xmlns:junos"): str,
"chassis-inventory": {
Optional("@xmlns"): str,
"chassis": {
Optional("@junos:style"): str,
"chassis-module": [
{
"chassis-sub-module": [
{
"chassis-sub-sub-module": {
"description": str,
"name": str,
"part-number": str,
"serial-number": str
},
"description": str,
"name": str,
"part-number": str,
"serial-number": str,
"version": str
}
],
"description": str,
"name": str
}
],
"description": str,
"name": str,
"serial-number": str
}
}
} | 6259904d8e71fb1e983bcf09 |
@dataclasses.dataclass <NEW_LINE> class VisualPoint(Point): <NEW_LINE> <INDENT> token : str = 'X' <NEW_LINE> fore : str = '' <NEW_LINE> back : str = '' <NEW_LINE> style : str = '' <NEW_LINE> def __post_init__(self): <NEW_LINE> <INDENT> super().__post_init__() <NEW_LINE> if len(self.token) != 1: <NEW_LINE> <INDENT> raise ValueError('token length must be of size 1') <NEW_LINE> <DEDENT> <DEDENT> def tokenize(self) -> color.ColoredString: <NEW_LINE> <INDENT> return color.ColoredString( value = self.token, fore = self.fore, back = self.back, style = self.style, ) | VisualPoint dataclass that holds the point 'token' and the point 'color'. | 6259904d462c4b4f79dbce45 |
class Encoder256(tf.Module): <NEW_LINE> <INDENT> def __init__(self, base_depth, feature_size, name=None): <NEW_LINE> <INDENT> super(Encoder256, self).__init__(name=name) <NEW_LINE> self.feature_size = feature_size <NEW_LINE> conv = functools.partial( tf.keras.layers.Conv2D, padding="SAME", activation=tf.nn.leaky_relu) <NEW_LINE> self.conv1 = conv(base_depth, 5, 2) <NEW_LINE> self.conv2 = conv(2 * base_depth, 3, 2) <NEW_LINE> self.conv3 = conv(4 * base_depth, 3, 2) <NEW_LINE> self.conv4 = conv(8 * base_depth, 3, 2) <NEW_LINE> self.conv5 = conv(8 * base_depth, 3, 2) <NEW_LINE> self.conv6 = conv(8 * base_depth, 3, 2) <NEW_LINE> self.conv7 = conv(8 * base_depth, 4, padding="VALID") <NEW_LINE> <DEDENT> def __call__(self, image): <NEW_LINE> <INDENT> image_shape = tf.shape(image)[-3:] <NEW_LINE> collapsed_shape = tf.concat(([-1], image_shape), axis=0) <NEW_LINE> out = tf.reshape(image, collapsed_shape) <NEW_LINE> out = self.conv1(out) <NEW_LINE> out = self.conv2(out) <NEW_LINE> out = self.conv3(out) <NEW_LINE> out = self.conv4(out) <NEW_LINE> out = self.conv5(out) <NEW_LINE> out = self.conv6(out) <NEW_LINE> out = self.conv7(out) <NEW_LINE> expanded_shape = tf.concat((tf.shape(image)[:-3], [self.feature_size]), axis=0) <NEW_LINE> return tf.reshape(out, expanded_shape) | Feature extractor for input image size 256*256.
| 6259904dd10714528d69f0b0 |
class RemoveRoleCmd(Command): <NEW_LINE> <INDENT> aliases = ('@rem-role',) <NEW_LINE> syntax = "<role> from <player>" <NEW_LINE> lock = 'perm(grant roles)' <NEW_LINE> def run(self, this, actor, args): <NEW_LINE> <INDENT> from mudslingcore.objects import Player <NEW_LINE> try: <NEW_LINE> <INDENT> role = self.game.db.match_role(args['role']) <NEW_LINE> <DEDENT> except MatchError as e: <NEW_LINE> <INDENT> actor.msg(e.message) <NEW_LINE> return <NEW_LINE> <DEDENT> matches = actor.match_obj_of_type(args['player'], cls=Player) <NEW_LINE> if self.match_failed(matches, args['player'], 'player', show=True): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> player = matches[0] <NEW_LINE> if player.has_role(role): <NEW_LINE> <INDENT> player.remove_role(role) <NEW_LINE> actor.msg("{m%s {yrole removed from {c%s{y." % (role.name, player.nn)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> actor.msg("{c%s {ydoes not have the {m%s {yrole." % (player.nn, role.name)) | @rem-role <role> from <player>
Removes a role from a player. | 6259904d15baa723494633d1 |
class TemplateStore: <NEW_LINE> <INDENT> def __init__(self, config): <NEW_LINE> <INDENT> self._config = config <NEW_LINE> self._templates = [] <NEW_LINE> self._listeners = [] <NEW_LINE> <DEDENT> def getTemplates(self): <NEW_LINE> <INDENT> return self._templates <NEW_LINE> <DEDENT> def getTemplate(self, name): <NEW_LINE> <INDENT> for template in self._templates: <NEW_LINE> <INDENT> if template.name == name: <NEW_LINE> <INDENT> return template <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def delTemplate(self, template): <NEW_LINE> <INDENT> if (template in self._templates): <NEW_LINE> <INDENT> self._templates.remove(template) <NEW_LINE> for listener in self._listeners: <NEW_LINE> <INDENT> listener.delTemplate(template) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def addTemplate(self, template): <NEW_LINE> <INDENT> if (template not in self._templates): <NEW_LINE> <INDENT> self._templates.append(template) <NEW_LINE> for listener in self._listeners: <NEW_LINE> <INDENT> listener.addTemplate(template) <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def register(self, listener): <NEW_LINE> <INDENT> self._listeners.append(listener) <NEW_LINE> <DEDENT> def load(self): <NEW_LINE> <INDENT> log.debug("loadTemplates from %s" % self._config.templatesDir) <NEW_LINE> for templatePath in self._config.templatesDir.files(): <NEW_LINE> <INDENT> if templatePath.basename().splitext()[1] == '.elt': <NEW_LINE> <INDENT> template = Template(templatePath) <NEW_LINE> if template.isValid(): <NEW_LINE> <INDENT> self.addTemplate(template) | TemplateStore is responsible for managing the Templates which the eXe server
has loaded, and loading and saving them | 6259904d4428ac0f6e659977 |
class ImportServiceClassTest(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.import_name_patcher = patch( "{src}.import_name".format(**PATH), autospec=True, ) <NEW_LINE> self.import_name = self.import_name_patcher.start() <NEW_LINE> self.addCleanup(self.import_name_patcher.stop) <NEW_LINE> <DEDENT> def test_nominal_abbreviated_path(self): <NEW_LINE> <INDENT> cls = Mock() <NEW_LINE> self.import_name.side_effect = (ImportError(), cls) <NEW_LINE> name = "ModelerService" <NEW_LINE> path = "ModelerService" <NEW_LINE> fullpath = "Products.ZenHub.services.ModelerService" <NEW_LINE> service = import_service_class(path) <NEW_LINE> self.assertIs(cls, service) <NEW_LINE> self.import_name.assert_has_calls(( call(path, name), call(fullpath, name), )) <NEW_LINE> <DEDENT> def test_nominal_full_path(self): <NEW_LINE> <INDENT> cls = Mock() <NEW_LINE> self.import_name.return_value = cls <NEW_LINE> name = "PythonConfig" <NEW_LINE> path = "ZenPacks.zenoss.PythonCollector.services.PythonConfig" <NEW_LINE> service = import_service_class(path) <NEW_LINE> self.assertIs(cls, service) <NEW_LINE> self.import_name.assert_called_once_with(path, name) <NEW_LINE> <DEDENT> def test_bad_path(self): <NEW_LINE> <INDENT> error = ImportError("boom") <NEW_LINE> self.import_name.side_effect = (error, error) <NEW_LINE> name = "Baz" <NEW_LINE> path = "Foo.Bar.Baz" <NEW_LINE> with self.assertRaises(UnknownServiceError): <NEW_LINE> <INDENT> import_service_class(path) <NEW_LINE> <DEDENT> self.import_name.assert_has_calls(( call(path, name), call("Products.ZenHub.services.Foo.Bar.Baz", name), )) | Test the import_service_class function. | 6259904d45492302aabfd919 |
@ns.route('/complete/<int:id>') <NEW_LINE> @ns.response(404, 'Todo not found') <NEW_LINE> @ns.param('id', "The task identifier") <NEW_LINE> class TodoCompleted(Resource): <NEW_LINE> <INDENT> @ns.marshal_with(todo, code=201) <NEW_LINE> @ns.doc('complete_todo') <NEW_LINE> def put(self,id): <NEW_LINE> <INDENT> return DAO.complete(id), 201 | View completed todos and mark uncompleted todos as complete | 6259904df7d966606f7492da |
class ErrorResponse(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'error': {'key': 'error', 'type': 'ErrorDefinition'}, } <NEW_LINE> def __init__( self, *, error: Optional["ErrorDefinition"] = None, **kwargs ): <NEW_LINE> <INDENT> super(ErrorResponse, self).__init__(**kwargs) <NEW_LINE> self.error = error | Error response.
:param error: Error description.
:type error: ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.ErrorDefinition | 6259904dd6c5a102081e3562 |
class AnalyzerConfig(command.ProcessCommandConfig): <NEW_LINE> <INDENT> def __init__(self, status, driver, script, description, max_depth=5, just_config=False): <NEW_LINE> <INDENT> super(AnalyzerConfig, self).__init__(driver, script, description, max_depth, just_config) <NEW_LINE> self.output_path_components = lambda race, run=None: status.analysis_result_path_components(race, None, run) | Gathers configuration information for the Analyzer | 6259904ddc8b845886d54a02 |
class CreateVpnGatewayRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.VpcId = None <NEW_LINE> self.VpnGatewayName = None <NEW_LINE> self.InternetMaxBandwidthOut = None <NEW_LINE> self.InstanceChargeType = None <NEW_LINE> self.InstanceChargePrepaid = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.VpcId = params.get("VpcId") <NEW_LINE> self.VpnGatewayName = params.get("VpnGatewayName") <NEW_LINE> self.InternetMaxBandwidthOut = params.get("InternetMaxBandwidthOut") <NEW_LINE> self.InstanceChargeType = params.get("InstanceChargeType") <NEW_LINE> if params.get("InstanceChargePrepaid") is not None: <NEW_LINE> <INDENT> self.InstanceChargePrepaid = InstanceChargePrepaid() <NEW_LINE> self.InstanceChargePrepaid._deserialize(params.get("InstanceChargePrepaid")) | CreateVpnGateway请求参数结构体
| 6259904dd6c5a102081e3563 |
class ProjectLoader(object): <NEW_LINE> <INDENT> help = "Load project record." <NEW_LINE> def __init__(self) -> None: <NEW_LINE> <INDENT> self.cvterm_contained_in = Cvterm.objects.get( name="contained in", cv__name="relationship" ) <NEW_LINE> <DEDENT> def store_project(self, name: str, filename: str) -> Project: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> project, created = Project.objects.get_or_create(name=name) <NEW_LINE> self.store_projectprop( project=project, type_id=self.cvterm_contained_in.cvterm_id, value=filename, ) <NEW_LINE> <DEDENT> except IntegrityError as e: <NEW_LINE> <INDENT> raise ImportingError(e) <NEW_LINE> <DEDENT> return project <NEW_LINE> <DEDENT> def store_projectprop( self, project: Project, type_id: int, value: str, rank: int = 0 ) -> None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> projectprop, created = Projectprop.objects.get_or_create( project=project, type_id=type_id, value=value, rank=rank ) <NEW_LINE> <DEDENT> except IntegrityError as e: <NEW_LINE> <INDENT> raise ImportingError(e) | Load project. | 6259904d4e696a045264e843 |
class _Counter(collections.defaultdict): <NEW_LINE> <INDENT> def __init__(self, iterable=(), **kwargs): <NEW_LINE> <INDENT> super(_Counter, self).__init__(int, **kwargs) <NEW_LINE> self.update(iterable) <NEW_LINE> <DEDENT> def most_common(self): <NEW_LINE> <INDENT> return sorted(six.iteritems(self), key=itemgetter(1), reverse=True) <NEW_LINE> <DEDENT> def update(self, other): <NEW_LINE> <INDENT> if isinstance(other, self.__class__): <NEW_LINE> <INDENT> for x, n in six.iteritems(other): <NEW_LINE> <INDENT> self[x] += n <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for x in other: <NEW_LINE> <INDENT> self[x] += 1 | Partial replacement for Python 2.7 collections.Counter. | 6259904d6e29344779b01a88 |
class TestArgumentParsing(TestCase): <NEW_LINE> <INDENT> @parameterized.expand([ ([], Namespace(domain='lobby.wildfiregames.com', login='xpartamupp', log_level=30, xserver=None, xdisabletls=False, nickname='WFGBot', password='XXXXXX', room='arena')), (['--debug'], Namespace(domain='lobby.wildfiregames.com', login='xpartamupp', log_level=10, xserver=None, xdisabletls=False, nickname='WFGBot', password='XXXXXX', room='arena')), (['--quiet'], Namespace(domain='lobby.wildfiregames.com', login='xpartamupp', log_level=40, xserver=None, xdisabletls=False, nickname='WFGBot', password='XXXXXX', room='arena')), (['--verbose'], Namespace(domain='lobby.wildfiregames.com', login='xpartamupp', log_level=20, xserver=None, xdisabletls=False, nickname='WFGBot', password='XXXXXX', room='arena')), (['-m', 'lobby.domain.tld'], Namespace(domain='lobby.domain.tld', login='xpartamupp', log_level=30, nickname='WFGBot', xserver=None, xdisabletls=False, password='XXXXXX', room='arena')), (['--domain=lobby.domain.tld'], Namespace(domain='lobby.domain.tld', login='xpartamupp', log_level=30, nickname='WFGBot', xserver=None, xdisabletls=False, password='XXXXXX', room='arena')), (['-m' 'lobby.domain.tld', '-l', 'bot', '-p', '123456', '-n', 'Bot', '-r', 'arena123', '-v'], Namespace(domain='lobby.domain.tld', login='bot', log_level=20, xserver=None, xdisabletls=False, nickname='Bot', password='123456', room='arena123')), (['--domain=lobby.domain.tld', '--login=bot', '--password=123456', '--nickname=Bot', '--room=arena123', '--verbose'], Namespace(domain='lobby.domain.tld', login='bot', log_level=20, xserver=None, xdisabletls=False, nickname='Bot', password='123456', room='arena123')), ]) <NEW_LINE> def test_valid(self, cmd_args, expected_args): <NEW_LINE> <INDENT> self.assertEqual(parse_args(cmd_args), expected_args) <NEW_LINE> <DEDENT> @parameterized.expand([ (['-f'],), (['--foo'],), (['--debug', '--quiet'],), (['--quiet', '--verbose'],), (['--debug', '--verbose'],), (['--debug', '--quiet', '--verbose'],), ]) <NEW_LINE> def test_invalid(self, cmd_args): <NEW_LINE> <INDENT> with self.assertRaises(SystemExit): <NEW_LINE> <INDENT> parse_args(cmd_args) | Test handling of parsing command line parameters. | 6259904d71ff763f4b5e8bed |
class Graph: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.nodes = [] <NEW_LINE> <DEDENT> def add_node(self, payload): <NEW_LINE> <INDENT> self.nodes.append(Node(len(self.nodes), payload)) <NEW_LINE> return len(self.nodes) - 1 <NEW_LINE> <DEDENT> def add_edge(self, node_i, node_j): <NEW_LINE> <INDENT> self.nodes[node_i].neighbors.append(self.nodes[node_j]) <NEW_LINE> self.nodes[node_j].neighbors.append(self.nodes[node_i]) <NEW_LINE> <DEDENT> def get_connected_nodes(self): <NEW_LINE> <INDENT> remaining_graph_nodes = list(range(len(self.nodes))) <NEW_LINE> segments = [] <NEW_LINE> while len(remaining_graph_nodes) > 0: <NEW_LINE> <INDENT> node_nr = remaining_graph_nodes.pop() <NEW_LINE> segment = [] <NEW_LINE> queued = [node_nr] <NEW_LINE> while len(queued) > 0: <NEW_LINE> <INDENT> current = queued.pop() <NEW_LINE> segment.append(current) <NEW_LINE> remaining_graph_nodes.remove(current) <NEW_LINE> queued = [ n.identifier for n in self.nodes[current].neighbors if n.identifier in remaining_graph_nodes ] <NEW_LINE> <DEDENT> segments.append(segment) <NEW_LINE> <DEDENT> return segments <NEW_LINE> <DEDENT> def generate_euclidean_edges(self): <NEW_LINE> <INDENT> n = len(self.nodes) <NEW_LINE> self.w = np.zeros(shape=(n, n)) <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> for j in range(n): <NEW_LINE> <INDENT> self.w[i][j] = self.nodes[i].get().dist_to(self.nodes[j].get()) | A graph class. It has nodes and vertices. | 6259904d23e79379d538d943 |
class CategoryMenu(CMSAttachMenu): <NEW_LINE> <INDENT> name = _('Zinnia Category Menu') <NEW_LINE> def get_nodes(self, request): <NEW_LINE> <INDENT> nodes = [] <NEW_LINE> nodes.append(NavigationNode(_('Categories'), reverse('zinnia_category_list'), 'categories')) <NEW_LINE> for category in Category.objects.all(): <NEW_LINE> <INDENT> nodes.append(NavigationNode(category.title, category.get_absolute_url(), category.pk, 'categories')) <NEW_LINE> <DEDENT> return nodes | Menu for the categories | 6259904d8da39b475be04636 |
class Map: <NEW_LINE> <INDENT> def GET(self): <NEW_LINE> <INDENT> pass <NEW_LINE> return render.addr() | 百度地图
GET()
return spage.addr() | 6259904d73bcbd0ca4bcb6cf |
class RSA(DSLdapObject): <NEW_LINE> <INDENT> def __init__(self, conn, dn=None): <NEW_LINE> <INDENT> assert dn is None <NEW_LINE> super(RSA, self).__init__(instance=conn) <NEW_LINE> self._dn = 'cn=RSA,cn=encryption,%s' % DN_CONFIG <NEW_LINE> self._create_objectclasses = ['top', 'nsEncryptionModule'] <NEW_LINE> self._rdn_attribute = 'cn' <NEW_LINE> self._must_attributes = ['cn'] <NEW_LINE> self._protected = True <NEW_LINE> <DEDENT> def _validate(self, rdn, properties, basedn): <NEW_LINE> <INDENT> (dn, valid_props) = super(RSA, self)._validate(rdn, properties, basedn) <NEW_LINE> assert(self._dn == dn) <NEW_LINE> return (dn, valid_props) <NEW_LINE> <DEDENT> def create(self, rdn=None, properties={'cn': 'RSA', 'nsSSLPersonalitySSL': 'Server-Cert', 'nsSSLActivation': 'on', 'nsSSLToken': 'internal (software)'}): <NEW_LINE> <INDENT> if rdn is not None: <NEW_LINE> <INDENT> self._log.debug("dn on cn=Rsa create request is not None. This is a mistake.") <NEW_LINE> <DEDENT> super(RSA, self).create(properties=properties) | Manage the "cn=RSA,cn=encryption,cn=config" object
- Set the certificate name
- Database path
- ssl token name | 6259904d8e71fb1e983bcf0b |
class SubException(Exception): <NEW_LINE> <INDENT> pass | A basic exception class. | 6259904d462c4b4f79dbce47 |
class IOLoopKernelRestarter(KernelRestarter): <NEW_LINE> <INDENT> loop = Instance('tornado.ioloop.IOLoop') <NEW_LINE> def _loop_default(self): <NEW_LINE> <INDENT> warnings.warn("IOLoopKernelRestarter.loop is deprecated in jupyter-client 5.2", DeprecationWarning, stacklevel=4, ) <NEW_LINE> return ioloop.IOLoop.current() <NEW_LINE> <DEDENT> _pcallback = None <NEW_LINE> def start(self): <NEW_LINE> <INDENT> if self._pcallback is None: <NEW_LINE> <INDENT> self._pcallback = ioloop.PeriodicCallback( self.poll, 1000*self.time_to_dead, ) <NEW_LINE> self._pcallback.start() <NEW_LINE> <DEDENT> <DEDENT> def stop(self): <NEW_LINE> <INDENT> if self._pcallback is not None: <NEW_LINE> <INDENT> self._pcallback.stop() <NEW_LINE> self._pcallback = None | Monitor and autorestart a kernel. | 6259904d63d6d428bbee3c12 |
class PackageLoader(object): <NEW_LINE> <INDENT> def __init__(self, system, package_manager): <NEW_LINE> <INDENT> self._system = system <NEW_LINE> self._package_manager = package_manager <NEW_LINE> self._repositories = {} <NEW_LINE> logger.debug("The system repository location is %s" % self._system.get_repositories_path()) <NEW_LINE> for dir in os.listdir(self._system.get_repositories_path()): <NEW_LINE> <INDENT> location = os.path.join(self._system.get_repositories_path(), dir) <NEW_LINE> if os.path.isdir(location): <NEW_LINE> <INDENT> logger.info("Found %s in system repositories" % dir) <NEW_LINE> self._repositories[dir] = location <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def load(self): <NEW_LINE> <INDENT> for repository in self._repositories: <NEW_LINE> <INDENT> for module in os.listdir(self._repositories[repository]): <NEW_LINE> <INDENT> if module[-3:] == '.py': <NEW_LINE> <INDENT> module = imp.load_source(module[:-3], os.path.join(self._repositories[repository], module)) <NEW_LINE> for package in module.versions: <NEW_LINE> <INDENT> self._package_manager.register_package(package(self._system, repository)) <NEW_LINE> logger.debug("Loaded package %s" % package.__name__) | Loads nusoft packages from a repository.
:param _system: The system
:param _package_manager: The package manager to load packages into | 6259904d596a897236128fd2 |
class MSG(BaseMSG): <NEW_LINE> <INDENT> def parse(self): <NEW_LINE> <INDENT> c = self.get("B") <NEW_LINE> if c == 240: <NEW_LINE> <INDENT> self.offset += 5 <NEW_LINE> c = self.get("B") <NEW_LINE> <DEDENT> self.msgtype = c <NEW_LINE> try: <NEW_LINE> <INDENT> msgcls = MSGType(self.msgtype).cls <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> self.data = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.data = msgcls(self.buf, self.offset) <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if self.data is not None: <NEW_LINE> <INDENT> return repr(self.data) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return repr(self.msgtype) | All messages.
This class identify the specific message type and calls the proper
parser. | 6259904da8ecb03325872659 |
class StoreDoesNotExistError(RuntimeError): <NEW_LINE> <INDENT> pass | Raised if you attempt to read a store that doesn't exist | 6259904d91af0d3eaad3b26b |
class Event: <NEW_LINE> <INDENT> def __init__(self, e_type, active, passive, detail): <NEW_LINE> <INDENT> self.e_type = e_type <NEW_LINE> self.active = active <NEW_LINE> self.passive = passive <NEW_LINE> self.detail = detail | An event in a GameRec. These have a type and some clarifying values
e_types active passive detail
START players None (game_num, rules)
VOTE voter votee ...
DECIDE voters victim ...
KILL (live)mafia victim ...
TARGET actor target ...
WIN winners losers (alive,winning_team)
REVEAL revealer None (day,time,n_players) | 6259904d0c0af96317c57784 |
class Suppress(object): <NEW_LINE> <INDENT> def __init__(self, exception_type): <NEW_LINE> <INDENT> self.type = exception_type <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_val, exc_tb): <NEW_LINE> <INDENT> if not exc_val or isinstance(exc_val, self.type): <NEW_LINE> <INDENT> return True | IGNORE EXCEPTIONS | 6259904dec188e330fdf9ce6 |
class LoginRoleDeleteTestCase(BaseTestGenerator): <NEW_LINE> <INDENT> scenarios = [ ('Check Role Node', dict(url='/browser/role/obj/')) ] <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> self.role_name = "role_delete_%s" % str(uuid.uuid4())[1:8] <NEW_LINE> self.role_id = roles_utils.create_role(self.server, self.role_name) <NEW_LINE> self.server_id = parent_node_dict["server"][-1]["server_id"] <NEW_LINE> role_dict = {"server_id": self.server_id, "role_id": self.role_id, "role_name": self.role_name} <NEW_LINE> utils.write_node_info("lrid", role_dict) <NEW_LINE> <DEDENT> def runTest(self): <NEW_LINE> <INDENT> response = self.tester.delete( self.url + str(utils.SERVER_GROUP) + '/' + str(self.server_id) + '/' + str(self.role_id), follow_redirects=True) <NEW_LINE> self.assertEquals(response.status_code, 200) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> connection = utils.get_db_connection(self.server['db'], self.server['username'], self.server['db_password'], self.server['host'], self.server['port'], self.server['sslmode']) <NEW_LINE> roles_utils.delete_role(connection, self.role_name) | This class has delete role scenario | 6259904ddc8b845886d54a04 |
class BlockResource(resource.Resource): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(BlockResource, self).__init__() <NEW_LINE> self.content = ("This is the resource's default content. It is padded " "with numbers to be large enough to trigger blockwise " "transfer.\n" + "0123456789\n" * 100).encode("ascii") <NEW_LINE> <DEDENT> async def render_get(self, request): <NEW_LINE> <INDENT> global token <NEW_LINE> x, y, z = mc.player.getPos() <NEW_LINE> send_data = (x, y, z, token) <NEW_LINE> send_pickle = pickle.dumps(send_data) <NEW_LINE> return aiocoap.Message(payload=send_pickle) <NEW_LINE> <DEDENT> async def render_put(self, request): <NEW_LINE> <INDENT> global counter <NEW_LINE> global token <NEW_LINE> token += 1 <NEW_LINE> counter += 1 <NEW_LINE> if token > 3: <NEW_LINE> <INDENT> token = 1 <NEW_LINE> <DEDENT> print('PUT payload: %s' % request.payload) <NEW_LINE> self.content = request.payload <NEW_LINE> data_back = pickle.loads(request.payload) <NEW_LINE> token_new = data_back[0] <NEW_LINE> x = data_back[1] <NEW_LINE> y = data_back[2] <NEW_LINE> z = data_back[3] <NEW_LINE> block_type = data_back[4] <NEW_LINE> print(counter) <NEW_LINE> print(x, y, z, block_type) <NEW_LINE> if counter < 10: <NEW_LINE> <INDENT> mc.setBlock(x, y, z, block_type) <NEW_LINE> mc.player.setPos(x - 1, y, z + 1) <NEW_LINE> <DEDENT> elif counter == 10: <NEW_LINE> <INDENT> mc.setBlock(x, y, z, block_type) <NEW_LINE> mc.player.setPos(x - 1, y, z) <NEW_LINE> <DEDENT> elif counter < 21: <NEW_LINE> <INDENT> mc.setBlock(x, y + 1, z, block_type) <NEW_LINE> mc.player.setPos(x - 1, y, z - 1) <NEW_LINE> <DEDENT> elif counter == 21: <NEW_LINE> <INDENT> token = 4 <NEW_LINE> token_new = 4 <NEW_LINE> mc.postToChat("Finished Building Wall!") <NEW_LINE> <DEDENT> LEDLight(token_new) <NEW_LINE> payload = ("I've accepted the new payload. You may inspect it here in " "Python's repr format:\n\n%r"%self.content).encode('utf8') <NEW_LINE> return aiocoap.Message(payload=payload) <NEW_LINE> sys.exit() | Example resource which supports GET and PUT methods. It sends large
responses, which trigger blockwise transfer. | 6259904de76e3b2f99fd9e47 |
class AzureTableStorageConfiguration(Configuration): <NEW_LINE> <INDENT> def __init__(self, url, **kwargs): <NEW_LINE> <INDENT> if url is None: <NEW_LINE> <INDENT> raise ValueError("Parameter 'url' must not be None.") <NEW_LINE> <DEDENT> super(AzureTableStorageConfiguration, self).__init__(**kwargs) <NEW_LINE> self.url = url <NEW_LINE> self.version = "2018-10-10" <NEW_LINE> self.version = "2018-10-10" <NEW_LINE> self.version = "2018-10-10" <NEW_LINE> self.version = "2018-10-10" <NEW_LINE> self.version = "2018-10-10" <NEW_LINE> self.version = "2018-10-10" <NEW_LINE> self.version = "2018-10-10" <NEW_LINE> self.version = "2018-10-10" <NEW_LINE> self.version = "2018-10-10" <NEW_LINE> self.version = "2018-10-10" <NEW_LINE> self.version = "2018-10-10" <NEW_LINE> self.version = "2018-10-10" <NEW_LINE> self.version = "2018-10-10" <NEW_LINE> self.credential_scopes = ['https://storage.azure.com/.default'] <NEW_LINE> self._configure(**kwargs) <NEW_LINE> self.user_agent_policy.add_user_agent('azsdk-python-azuretablestorage/{}'.format(VERSION)) <NEW_LINE> <DEDENT> def _configure(self, **kwargs): <NEW_LINE> <INDENT> self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) <NEW_LINE> self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) <NEW_LINE> self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) <NEW_LINE> self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) <NEW_LINE> self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) <NEW_LINE> self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) <NEW_LINE> self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) <NEW_LINE> self.authentication_policy = kwargs.get('authentication_policy') | Configuration for AzureTableStorage
Note that all parameters used to create this instance are saved as instance
attributes.
:param url: The URL of the service account or table that is the targe of the desired operation.
:type url: str | 6259904d82261d6c527308ea |
class SpecialFileError(EnvironmentError): <NEW_LINE> <INDENT> pass | Raised when trying to do a kind of operation (e.g. copying) which is
not supported on a special file (e.g. a named pipe) | 6259904d6e29344779b01a8a |
@export <NEW_LINE> class Biaxial001(CartesianStrain): <NEW_LINE> <INDENT> def __init__(self, C11, C12, C44, zeta): <NEW_LINE> <INDENT> exx = eyy = 1 <NEW_LINE> ezz = -2 * C12 / C11 <NEW_LINE> super(Biaxial001, self).__init__(deformation_matrix=np.diag([exx, eyy, ezz])) | Bi-axial [001] strain for III-V semiconductors. | 6259904de76e3b2f99fd9e48 |
class GetSessionIdRequest(JDCloudRequest): <NEW_LINE> <INDENT> def __init__(self, parameters, header=None, version="v1"): <NEW_LINE> <INDENT> super(GetSessionIdRequest, self).__init__( '/captcha:getsessionid', 'POST', header, version) <NEW_LINE> self.parameters = parameters | 获取会话id | 6259904dd486a94d0ba2d40d |
class VoiceEqualityDynamicsFeature(featuresModule.FeatureExtractor): <NEW_LINE> <INDENT> id = 'T6' <NEW_LINE> def __init__(self, dataOrStream=None, *arguments, **keywords): <NEW_LINE> <INDENT> featuresModule.FeatureExtractor.__init__(self, dataOrStream=dataOrStream, *arguments, **keywords) <NEW_LINE> self.name = 'Voice Equality - Dynamics' <NEW_LINE> self.description = 'Standard deviation of the average volume of notes in each channel that contains at least one note.' <NEW_LINE> self.isSequential = True <NEW_LINE> self.dimensions = 1 | Not implemented
TODO: implement | 6259904d50485f2cf55dc3d5 |
class Like(db.Model): <NEW_LINE> <INDENT> post_id = db.IntegerProperty(required=True) <NEW_LINE> username = db.StringProperty(required=True) <NEW_LINE> created = db.DateTimeProperty(auto_now_add=True) <NEW_LINE> @classmethod <NEW_LINE> def by_name(cls, name): <NEW_LINE> <INDENT> return cls.all().filter("username =", name).get() | Like is a model class which has the following attributes
post_id: The associted posts's id
username: Author of the like
created: Timestamp of the creation of teh like | 6259904dd4950a0f3b111867 |
class InvalidSize(Exception): <NEW_LINE> <INDENT> pass | Raised when a string cannot be parsed into a file size.
For example:
>>> from humanfriendly import parse_size
>>> parse_size('5 Z')
Traceback (most recent call last):
File "humanfriendly/__init__.py", line 267, in parse_size
raise InvalidSize(format(msg, size, tokens))
humanfriendly.InvalidSize: Failed to parse size! (input '5 Z' was tokenized as [5, 'Z']) | 6259904d8da39b475be04637 |
class TemporaryDirectory(object): <NEW_LINE> <INDENT> def __init__(self, suffix="", prefix=None, dir=None): <NEW_LINE> <INDENT> if "RAM_DISK" in os.environ: <NEW_LINE> <INDENT> import uuid <NEW_LINE> name = uuid.uuid4().hex <NEW_LINE> dir_name = os.path.join(os.environ["RAM_DISK"].strip(), name) <NEW_LINE> os.mkdir(dir_name) <NEW_LINE> self.name = dir_name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> suffix = suffix if suffix else "" <NEW_LINE> if not prefix: <NEW_LINE> <INDENT> self.name = mkdtemp(suffix=suffix, dir=dir) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.name = mkdtemp(suffix, prefix, dir) <NEW_LINE> <DEDENT> <DEDENT> self._finalizer = finalize( self, self._cleanup, self.name, warn_message="Implicitly cleaning up {!r}".format(self), ) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _cleanup(cls, name, warn_message): <NEW_LINE> <INDENT> from .path import rmtree <NEW_LINE> rmtree(name) <NEW_LINE> warnings.warn(warn_message, ResourceWarning) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<{} {!r}>".format(self.__class__.__name__, self.name) <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, exc, value, tb): <NEW_LINE> <INDENT> self.cleanup() <NEW_LINE> <DEDENT> def cleanup(self): <NEW_LINE> <INDENT> from .path import rmtree <NEW_LINE> if self._finalizer.detach(): <NEW_LINE> <INDENT> rmtree(self.name) | Create and return a temporary directory. This has the same
behavior as mkdtemp but can be used as a context manager. For
example:
with TemporaryDirectory() as tmpdir:
...
Upon exiting the context, the directory and everything contained
in it are removed. | 6259904d76d4e153a661dc9c |
class Doulist(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.doulist_id = -99999 <NEW_LINE> self.url_id = 0 <NEW_LINE> self.url_increment = 25 <NEW_LINE> self.item_type = '' <NEW_LINE> return <NEW_LINE> <DEDENT> def init(self): <NEW_LINE> <INDENT> self.doulist_id = input('please enter the id of the doulist\n') <NEW_LINE> while not(self.item_type in ['movies', 'books']): <NEW_LINE> <INDENT> self.item_type = input('please enter the type of the doulist\n (movies/books)\n') <NEW_LINE> <DEDENT> if self.item_type == 'movies': <NEW_LINE> <INDENT> self.item = Movie() <NEW_LINE> <DEDENT> elif self.item_type == 'books': <NEW_LINE> <INDENT> self.item = Book() <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def retrive(self): <NEW_LINE> <INDENT> while(1): <NEW_LINE> <INDENT> print('..processing page %d' % (self.url_id+1)) <NEW_LINE> ItemCrawler = Crawler() <NEW_LINE> ItemCrawler.url = 'http://www.douban.com/doulist/%s/?start=%d&sort=seq' % (self.doulist_id, self.url_id*self.url_increment) <NEW_LINE> ItemCrawler.pattern = {'name':'div', 'attrs':{'class':'doulist-item'}} <NEW_LINE> try: <NEW_LINE> <INDENT> ItemCrawler.retrive() <NEW_LINE> item_id = 1 <NEW_LINE> if ItemCrawler.content: <NEW_LINE> <INDENT> print('....there are %d items in this page %d' % (len(ItemCrawler.content), self.url_id+1)) <NEW_LINE> for foo in ItemCrawler.content: <NEW_LINE> <INDENT> print('....processing page %d %s %d' % (self.url_id+1, self.item_type, item_id)) <NEW_LINE> try: <NEW_LINE> <INDENT> SubCrawler = Crawler() <NEW_LINE> SubCrawler.url = re.findall('<a href="(\S*)" target="_blank">', str(foo))[0] <NEW_LINE> SubCrawler.pattern = {'name':'div', 'attrs':{'id':'wrapper'}} <NEW_LINE> SubCrawler.retrive() <NEW_LINE> global g_soup; g_soup = SubCrawler.content[0]; <NEW_LINE> self.item.parse(SubCrawler.content[0], SubCrawler.url) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print('......failed extract %s homepage' % self.item_type) <NEW_LINE> <DEDENT> item_id += 1 <NEW_LINE> <DEDENT> self.url_id += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('..Done') <NEW_LINE> self.item.write() <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> print('open doulist url failed') <NEW_LINE> info = sys.exc_info() <NEW_LINE> print(info[0], ':', info[1]) <NEW_LINE> <DEDENT> <DEDENT> return | instruct how to crawl the doulist page | 6259904d462c4b4f79dbce48 |
class AliasPathType(Model): <NEW_LINE> <INDENT> _attribute_map = { 'path': {'key': 'path', 'type': 'str'}, 'api_versions': {'key': 'apiVersions', 'type': '[str]'}, } <NEW_LINE> def __init__(self, path=None, api_versions=None): <NEW_LINE> <INDENT> self.path = path <NEW_LINE> self.api_versions = api_versions | The type of the paths for alias. .
:param path: The path of an alias.
:type path: str
:param api_versions: The API versions.
:type api_versions: list[str] | 6259904dd99f1b3c44d06ae2 |
class IntExtState(object): <NEW_LINE> <INDENT> def __init__(self, internal_state, external_state): <NEW_LINE> <INDENT> self.external_state = external_state <NEW_LINE> self.internal_state = internal_state <NEW_LINE> <DEDENT> @property <NEW_LINE> def meta(self): <NEW_LINE> <INDENT> return self.external_state.meta <NEW_LINE> <DEDENT> @property <NEW_LINE> def num_actions(self): <NEW_LINE> <INDENT> return self.external_state.num_actions <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> return IntExtState(self.internal_state, self.external_state) <NEW_LINE> <DEDENT> @property <NEW_LINE> def size(self): <NEW_LINE> <INDENT> return self.external_state.size <NEW_LINE> <DEDENT> @property <NEW_LINE> def array_dtype(self): <NEW_LINE> <INDENT> return self.external_state.array_dtype <NEW_LINE> <DEDENT> def as_array(self): <NEW_LINE> <INDENT> return self.external_state.as_array() | Represents a State which is also the state of a finite state machine | 6259904d596a897236128fd3 |
class Delegated(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.delegate = Delegate() <NEW_LINE> <DEDENT> def subscribe(self, functor): <NEW_LINE> <INDENT> self.delegate.subscribe(functor) <NEW_LINE> <DEDENT> def unsubscribe(self, functor): <NEW_LINE> <INDENT> self.delegate.unsubscribe(functor) | A base class for delegated classes | 6259904d91af0d3eaad3b26d |
class TrackingOverlay(): <NEW_LINE> <INDENT> def __init__(self, shell): <NEW_LINE> <INDENT> self._local = TrackedVariablesConfig(shell=shell) <NEW_LINE> self._global = TrackedVariablesConfig(global_scope=True) <NEW_LINE> <DEDENT> def flush(self, global_scope=False): <NEW_LINE> <INDENT> if global_scope: <NEW_LINE> <INDENT> self._global.flush() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._local.flush() <NEW_LINE> <DEDENT> <DEDENT> def track(self, variable, global_scope=False): <NEW_LINE> <INDENT> if global_scope: <NEW_LINE> <INDENT> self._global.track(variable) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._local.track(variable) <NEW_LINE> <DEDENT> <DEDENT> def ignore(self, variable, global_scope=False): <NEW_LINE> <INDENT> if global_scope: <NEW_LINE> <INDENT> self._global.ignore(variable) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._local.ignore(variable) <NEW_LINE> <DEDENT> <DEDENT> def make_default(self, variable, global_scope=False): <NEW_LINE> <INDENT> if global_scope: <NEW_LINE> <INDENT> self._global.make_default(variable) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._local.make_default(variable) <NEW_LINE> <DEDENT> <DEDENT> def is_tracked(self, variable): <NEW_LINE> <INDENT> if self._local.is_explicitly_configured(variable): <NEW_LINE> <INDENT> return self._local.is_tracked(variable) <NEW_LINE> <DEDENT> if self._global.is_explicitly_configured(variable): <NEW_LINE> <INDENT> return self._global.is_tracked(variable) <NEW_LINE> <DEDENT> return self._local.default <NEW_LINE> <DEDENT> def set_default(self, default, global_scope=False): <NEW_LINE> <INDENT> if global_scope: <NEW_LINE> <INDENT> self._global.default = default <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._local.default = default | Represents an overlay of tracking configuration, which contains the global
scope shadowed by the configuration of the local (shell) scope. | 6259904dbe383301e0254c64 |
class EntryMonth(EntryArchiveMixin, BaseMonthArchiveView): <NEW_LINE> <INDENT> @property <NEW_LINE> def private_context_data(self): <NEW_LINE> <INDENT> year = self.kwargs['year'] <NEW_LINE> month = self.kwargs['month'] <NEW_LINE> ttl = '%s年%s月' % (year, month) <NEW_LINE> breadcrumbs = [Link('%s年' % year, reverse('blog:archives:year', args=[year])), Link('%s月' % month)] <NEW_LINE> return {'ttl': ttl, 'breadcrumbs': breadcrumbs, 'labels': []} | Mixin month. | 6259904db830903b9686ee9f |
class BandwidthInfoSchema(schema.ResponseSchema): <NEW_LINE> <INDENT> fields = { "CdnBandwidth": fields.Float(required=False, load_from="CdnBandwidth"), "Time": fields.Int(required=False, load_from="Time"), } | BandwidthInfo - BandwidthInfo | 6259904d379a373c97d9a474 |
class Unprintable_Card(Card): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return "<unprintable>" | A card that won't reveal its rank or suit wheen printed | 6259904d24f1403a926862f2 |
class FirewallPolicy(neutron.NeutronResource): <NEW_LINE> <INDENT> PROPERTIES = ( NAME, DESCRIPTION, SHARED, AUDITED, FIREWALL_RULES, ) = ( 'name', 'description', 'shared', 'audited', 'firewall_rules', ) <NEW_LINE> ATTRIBUTES = ( NAME_ATTR, DESCRIPTION_ATTR, FIREWALL_RULES_ATTR, SHARED_ATTR, AUDITED_ATTR, TENANT_ID, ) = ( 'name', 'description', 'firewall_rules', 'shared', 'audited', 'tenant_id', ) <NEW_LINE> properties_schema = { NAME: properties.Schema( properties.Schema.STRING, _('Name for the firewall policy.'), update_allowed=True ), DESCRIPTION: properties.Schema( properties.Schema.STRING, _('Description for the firewall policy.'), update_allowed=True ), SHARED: properties.Schema( properties.Schema.BOOLEAN, _('Whether this policy should be shared across all tenants.'), default=False, update_allowed=True ), AUDITED: properties.Schema( properties.Schema.BOOLEAN, _('Whether this policy should be audited. When set to True, ' 'each time the firewall policy or the associated firewall ' 'rules are changed, this attribute will be set to False and ' 'will have to be explicitly set to True through an update ' 'operation.'), default=False, update_allowed=True ), FIREWALL_RULES: properties.Schema( properties.Schema.LIST, _('An ordered list of firewall rules to apply to the firewall.'), required=True, update_allowed=True ), } <NEW_LINE> attributes_schema = { NAME_ATTR: attributes.Schema( _('Name for the firewall policy.') ), DESCRIPTION_ATTR: attributes.Schema( _('Description of the firewall policy.') ), FIREWALL_RULES_ATTR: attributes.Schema( _('List of firewall rules in this firewall policy.') ), SHARED_ATTR: attributes.Schema( _('Shared status of this firewall policy.') ), AUDITED_ATTR: attributes.Schema( _('Audit status of this firewall policy.') ), TENANT_ID: attributes.Schema( _('Id of the tenant owning the firewall policy.') ), } <NEW_LINE> def _show_resource(self): <NEW_LINE> <INDENT> return self.neutron().show_firewall_policy(self.resource_id)[ 'firewall_policy'] <NEW_LINE> <DEDENT> def handle_create(self): <NEW_LINE> <INDENT> props = self.prepare_properties( self.properties, self.physical_resource_name()) <NEW_LINE> firewall_policy = self.neutron().create_firewall_policy( {'firewall_policy': props})['firewall_policy'] <NEW_LINE> self.resource_id_set(firewall_policy['id']) <NEW_LINE> <DEDENT> def handle_update(self, json_snippet, tmpl_diff, prop_diff): <NEW_LINE> <INDENT> if prop_diff: <NEW_LINE> <INDENT> self.neutron().update_firewall_policy( self.resource_id, {'firewall_policy': prop_diff}) <NEW_LINE> <DEDENT> <DEDENT> def handle_delete(self): <NEW_LINE> <INDENT> client = self.neutron() <NEW_LINE> try: <NEW_LINE> <INDENT> client.delete_firewall_policy(self.resource_id) <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> self.client_plugin().ignore_not_found(ex) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._delete_task() | A resource for the FirewallPolicy resource in Neutron FWaaS. | 6259904db5575c28eb7136ee |
class DescribeQuotaResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.QuotaSet = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> if params.get("QuotaSet") is not None: <NEW_LINE> <INDENT> self.QuotaSet = [] <NEW_LINE> for item in params.get("QuotaSet"): <NEW_LINE> <INDENT> obj = Quota() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.QuotaSet.append(obj) <NEW_LINE> <DEDENT> <DEDENT> self.RequestId = params.get("RequestId") | DescribeQuota返回参数结构体
| 6259904d3cc13d1c6d466b82 |
class ProfileUpdateView(UpdateView): <NEW_LINE> <INDENT> profile = None <NEW_LINE> def get_initial(self): <NEW_LINE> <INDENT> data = model_to_dict(self.object) <NEW_LINE> data.update(model_to_dict(self.object.profile.user)) <NEW_LINE> data.update(model_to_dict(self.object.profile)) <NEW_LINE> return data <NEW_LINE> <DEDENT> def get_form(self, form_class=None): <NEW_LINE> <INDENT> if isinstance(self.object, IndividualProfile): <NEW_LINE> <INDENT> return CommunityIndividualProfileForm(**self.get_form_kwargs()) <NEW_LINE> <DEDENT> elif isinstance(self.object, BusinessProfile): <NEW_LINE> <INDENT> return CommunityBusinessProfileForm(**self.get_form_kwargs()) <NEW_LINE> <DEDENT> elif isinstance(self.object, InstitutionProfile): <NEW_LINE> <INDENT> return CommunityInstitutionProfileForm(**self.get_form_kwargs()) <NEW_LINE> <DEDENT> elif isinstance(self.object, CharityProfile): <NEW_LINE> <INDENT> return CommunityCharityProfileForm(**self.get_form_kwargs()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super(ProfileUpdateView, self).get_context_data(**kwargs) <NEW_LINE> context['cc3_profile'] = self.profile <NEW_LINE> context['map_centre_lat'] = getattr( settings, 'MARKETPLACE_MAP_CENTER_LAT', 0) <NEW_LINE> context['map_centre_lng'] = getattr( settings, 'MARKETPLACE_MAP_CENTER_LNG', 0) <NEW_LINE> return context | Generic class to update member profiles. | 6259904d07d97122c42180ed |
class IsOwnerOrAdmin(permissions.BasePermission): <NEW_LINE> <INDENT> def has_object_permission(self, request, view, obj): <NEW_LINE> <INDENT> if request.user.is_staff: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if request.data.get('is_staff', False): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return request.user.username == obj.username | Custom permission to only allow owners of an object to edit it.
We also ensure non-staff users are not allowed to elevate their privileges | 6259904dd53ae8145f9198ab |
class SumO2K(ReduceLayerO2K): <NEW_LINE> <INDENT> def call(self, inputs, **kwargs): <NEW_LINE> <INDENT> return K.sum(inputs, self._axes, self._keepdims) | Custom Keras Sum layer generated by onnx2keras. | 6259904d71ff763f4b5e8bf1 |
class BaseAuthException(Exception): <NEW_LINE> <INDENT> code = 0 | Базовый класс исключений | 6259904d0a50d4780f7067e2 |
@registry.register_problem <NEW_LINE> class QuoraQuestionPairs(text_problems.TextConcat2ClassProblem): <NEW_LINE> <INDENT> _QQP_URL = ("https://firebasestorage.googleapis.com/v0/b/" "mtl-sentence-representations.appspot.com/o/" "data%2FQQP.zip?alt=media&token=700c6acf-160d-" "4d89-81d1-de4191d02cb5") <NEW_LINE> @property <NEW_LINE> def is_generate_per_split(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> @property <NEW_LINE> def dataset_splits(self): <NEW_LINE> <INDENT> return [{ "split": problem.DatasetSplit.TRAIN, "shards": 100, }, { "split": problem.DatasetSplit.EVAL, "shards": 1, }] <NEW_LINE> <DEDENT> @property <NEW_LINE> def approx_vocab_size(self): <NEW_LINE> <INDENT> return 2**15 <NEW_LINE> <DEDENT> @property <NEW_LINE> def num_classes(self): <NEW_LINE> <INDENT> return 2 <NEW_LINE> <DEDENT> def class_labels(self, data_dir): <NEW_LINE> <INDENT> del data_dir <NEW_LINE> return ["not_duplicate", "duplicate"] <NEW_LINE> <DEDENT> def _maybe_download_corpora(self, tmp_dir): <NEW_LINE> <INDENT> qqp_filename = "QQP.zip" <NEW_LINE> qqp_finalpath = os.path.join(tmp_dir, "QQP") <NEW_LINE> if not tf.gfile.Exists(qqp_finalpath): <NEW_LINE> <INDENT> zip_filepath = generator_utils.maybe_download( tmp_dir, qqp_filename, self._QQP_URL) <NEW_LINE> zip_ref = zipfile.ZipFile(zip_filepath, "r") <NEW_LINE> zip_ref.extractall(tmp_dir) <NEW_LINE> zip_ref.close() <NEW_LINE> <DEDENT> return qqp_finalpath <NEW_LINE> <DEDENT> def example_generator(self, filename): <NEW_LINE> <INDENT> skipped = 0 <NEW_LINE> for idx, line in enumerate(tf.gfile.Open(filename, "rb")): <NEW_LINE> <INDENT> if idx == 0: continue <NEW_LINE> line = text_encoder.to_unicode_utf8(line.strip()) <NEW_LINE> split_line = line.split("\t") <NEW_LINE> if len(split_line) < 6: <NEW_LINE> <INDENT> skipped += 1 <NEW_LINE> tf.logging.info("Skipping %d" % skipped) <NEW_LINE> continue <NEW_LINE> <DEDENT> s1, s2, l = split_line[3:] <NEW_LINE> inputs = [[s1, s2], [s2, s1]] <NEW_LINE> for inp in inputs: <NEW_LINE> <INDENT> yield { "inputs": inp, "label": int(l) } <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def generate_samples(self, data_dir, tmp_dir, dataset_split): <NEW_LINE> <INDENT> qqp_dir = self._maybe_download_corpora(tmp_dir) <NEW_LINE> if dataset_split == problem.DatasetSplit.TRAIN: <NEW_LINE> <INDENT> filesplit = "train.tsv" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> filesplit = "dev.tsv" <NEW_LINE> <DEDENT> filename = os.path.join(qqp_dir, filesplit) <NEW_LINE> for example in self.example_generator(filename): <NEW_LINE> <INDENT> yield example | Quora duplicate question pairs binary classification problems. | 6259904d8e7ae83300eea4de |
class CreateExclude(command.Command): <NEW_LINE> <INDENT> def get_parser(self, prog_name): <NEW_LINE> <INDENT> parser = super(CreateExclude, self).get_parser(prog_name) <NEW_LINE> parser.add_argument( 'id', metavar='<osvmexclude-object-id>', help=_('Id of the element to exclude (domain, project, user)') ) <NEW_LINE> parser.add_argument( 'type', metavar='<osvmexclude-object-type>', help=_('Type of the element to exclude [domain, project, user]') ) <NEW_LINE> return parser <NEW_LINE> <DEDENT> def take_action(self, parsed_args): <NEW_LINE> <INDENT> columns = EXCLUDE_COLUMNS <NEW_LINE> return pretty_print(columns, [self._create(parsed_args.id, parsed_args.type)]) <NEW_LINE> <DEDENT> def _create(self, exclude_id, exclude_type): <NEW_LINE> <INDENT> exclude_type_int = -1 <NEW_LINE> if exclude_type == 'domain': <NEW_LINE> <INDENT> exclude_type_int = 0 <NEW_LINE> <DEDENT> elif exclude_type == 'project': <NEW_LINE> <INDENT> exclude_type_int = 1 <NEW_LINE> <DEDENT> elif exclude_type == 'user': <NEW_LINE> <INDENT> exclude_type_int = 2 <NEW_LINE> <DEDENT> endpoint = get_endpoint(self.app.client_manager) <NEW_LINE> headers = { 'Content-Type': 'application/json', 'X-Auth-Token': self.app.client_manager.auth_ref.auth_token } <NEW_LINE> req = requests.post( endpoint + '/vmexcludes/' + exclude_id, headers=headers, json={ 'id': exclude_id, 'type': exclude_type_int } ) <NEW_LINE> if not req.status_code == 202: <NEW_LINE> <INDENT> raise osvmexpire_exc.HTTPNotFound('creation failed') <NEW_LINE> <DEDENT> res = req.json() <NEW_LINE> if 'vmexclude' not in res: <NEW_LINE> <INDENT> raise osvmexpire_exc.HTTPNotFound('no exclude created') <NEW_LINE> <DEDENT> return res['vmexclude'] | Create osvmexclude | 6259904de76e3b2f99fd9e4a |
class ReadINI(object): <NEW_LINE> <INDENT> def __init__(self, *dir_paths): <NEW_LINE> <INDENT> self.config = configparser.ConfigParser() <NEW_LINE> self.config.optionxform = str <NEW_LINE> for d in dir_paths: <NEW_LINE> <INDENT> f = os.path.join(d, "config.ini") <NEW_LINE> if os.path.exists(f): <NEW_LINE> <INDENT> self.config.read(f) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get(self, section_name, prop_name): <NEW_LINE> <INDENT> if section_name not in self.config.sections(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.config.get(section_name, prop_name) | Read ini file | 6259904dd4950a0f3b111868 |
class StinoImportLibraryCommand(sublime_plugin.TextCommand): <NEW_LINE> <INDENT> def run(self, edit, library_path): <NEW_LINE> <INDENT> if stino.arduino_info['init_done']: <NEW_LINE> <INDENT> stino.import_lib(self.view, edit, library_path) <NEW_LINE> <DEDENT> <DEDENT> def is_enabled(self): <NEW_LINE> <INDENT> state = False <NEW_LINE> if stino.arduino_info['init_done']: <NEW_LINE> <INDENT> file_path = self.view.file_name() <NEW_LINE> if file_path: <NEW_LINE> <INDENT> if stino.c_file.is_cpp_file(file_path): <NEW_LINE> <INDENT> state = True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return state | Import Library. | 6259904d1f037a2d8b9e5291 |
class ProductDetail(DetailView): <NEW_LINE> <INDENT> model = Product <NEW_LINE> template_name = 'shop/list_detail.html' <NEW_LINE> context_object_name = 'product' | Карточка товара | 6259904d21a7993f00c673b3 |
class ddbTestObject(PerlWrapper): <NEW_LINE> <INDENT> __metaclass__ = ddb_api <NEW_LINE> __table__ = 'test' <NEW_LINE> _attr_data = { '_id' : ['','read/write'], '_test' : [0,'read/write'], '_test_readonly' : [0,'read'] } <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> PerlWrapper.__init__( self, 'DDB::PROTEIN') <NEW_LINE> for attr in self.__class__._attr_data: <NEW_LINE> <INDENT> setattr( self, attr, self.__class__._attr_data[attr][0] ) <NEW_LINE> pass <NEW_LINE> <DEDENT> self._sequence_loaded = False <NEW_LINE> <DEDENT> def get_id(self): <NEW_LINE> <INDENT> print('here in own test id fxn') <NEW_LINE> return self._id <NEW_LINE> <DEDENT> id = property(fget=get_id ) <NEW_LINE> def getx(self): <NEW_LINE> <INDENT> print('here in Python get x') <NEW_LINE> return self._x <NEW_LINE> <DEDENT> def setx(self, val): <NEW_LINE> <INDENT> print('here in Python set x') <NEW_LINE> self._x = val <NEW_LINE> <DEDENT> x = property(getx, setx) | DDB test object. | 6259904d07f4c71912bb087f |
class AdminConsole(validation.Validated): <NEW_LINE> <INDENT> ATTRIBUTES = { PAGES: validation.Optional(validation.Repeated(AdminConsolePage)), } | Class representing admin console directives in application info.
| 6259904db57a9660fecd2ec7 |
class TestModelsBackOffDecreaseType(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testModelsBackOffDecreaseType(self): <NEW_LINE> <INDENT> pass | ModelsBackOffDecreaseType unit test stubs | 6259904d76d4e153a661dc9d |
@python_2_unicode_compatible <NEW_LINE> class IntervalSchedule(models.Model): <NEW_LINE> <INDENT> DAYS = DAYS <NEW_LINE> HOURS = HOURS <NEW_LINE> MINUTES = MINUTES <NEW_LINE> SECONDS = SECONDS <NEW_LINE> MICROSECONDS = MICROSECONDS <NEW_LINE> PERIOD_CHOICES = PERIOD_CHOICES <NEW_LINE> every = models.IntegerField(_('every'), null=False) <NEW_LINE> period = models.CharField( _('period'), max_length=24, choices=PERIOD_CHOICES, ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = '时间间隔' <NEW_LINE> verbose_name_plural = verbose_name <NEW_LINE> ordering = ['period', 'every'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def schedule(self): <NEW_LINE> <INDENT> return schedules.schedule( timedelta(**{self.period: self.every}), nowfun=lambda: make_aware(now()) ) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_schedule(cls, schedule, period=SECONDS): <NEW_LINE> <INDENT> every = max(schedule.run_every.total_seconds(), 0) <NEW_LINE> try: <NEW_LINE> <INDENT> return cls.objects.get(every=every, period=period) <NEW_LINE> <DEDENT> except cls.DoesNotExist: <NEW_LINE> <INDENT> return cls(every=every, period=period) <NEW_LINE> <DEDENT> except MultipleObjectsReturned: <NEW_LINE> <INDENT> cls.objects.filter(every=every, period=period).delete() <NEW_LINE> return cls(every=every, period=period) <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self.every == 1: <NEW_LINE> <INDENT> return _('every {0.period_singular}').format(self) <NEW_LINE> <DEDENT> return _('every {0.every} {0.period}').format(self) <NEW_LINE> <DEDENT> @property <NEW_LINE> def period_singular(self): <NEW_LINE> <INDENT> return self.period[:-1] | Schedule executing every n seconds. | 6259904dd99f1b3c44d06ae4 |
class GsLogByAuthorCommand(LogMixin, WindowCommand, GitCommand): <NEW_LINE> <INDENT> def run_async(self, **kwargs): <NEW_LINE> <INDENT> email = self.git("config", "user.email").strip() <NEW_LINE> self._entries = [] <NEW_LINE> commiter_str = self.git("shortlog", "-sne", "HEAD") <NEW_LINE> for line in commiter_str.split('\n'): <NEW_LINE> <INDENT> m = re.search('\s*(\d*)\s*(.*)\s<(.*)>', line) <NEW_LINE> if m is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> commit_count, author_name, author_email = m.groups() <NEW_LINE> author_text = "{} <{}>".format(author_name, author_email) <NEW_LINE> self._entries.append((commit_count, author_name, author_email, author_text)) <NEW_LINE> <DEDENT> self.window.show_quick_panel( [entry[3] for entry in self._entries], lambda index: self.on_author_selection(index, **kwargs), flags=sublime.MONOSPACE_FONT, selected_index=(list(line[2] for line in self._entries)).index(email) ) <NEW_LINE> <DEDENT> def on_author_selection(self, index, **kwargs): <NEW_LINE> <INDENT> if index == -1: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._selected_author = self._entries[index][3] <NEW_LINE> super().run_async(**kwargs) <NEW_LINE> <DEDENT> def log(self, **kwargs): <NEW_LINE> <INDENT> return super().log(author=self._selected_author, **kwargs) | Open a quick panel containing all committers for the active
repository, ordered by most commits, Git name, and email.
Once selected, display a quick panel with all commits made
by the specified author. | 6259904d009cb60464d02983 |
class EventManager: <NEW_LINE> <INDENT> bus = EventBus() <NEW_LINE> @classmethod <NEW_LINE> def add_event_handler(cls, handler: EventHandler) -> None: <NEW_LINE> <INDENT> for event in handler.events: <NEW_LINE> <INDENT> cls.bus.subscribe(event, handler.func) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def remove_event_handler(cls, handler: EventHandler) -> None: <NEW_LINE> <INDENT> for event in handler.events: <NEW_LINE> <INDENT> cls.bus.unsubscribe(event, handler.func) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def switch_event_handler_global(cls, handler: EventHandler, state: Optional[bool] = None) -> None: <NEW_LINE> <INDENT> for event in handler.events: <NEW_LINE> <INDENT> if handler.func in cls.bus._subscribers[event] and not state: <NEW_LINE> <INDENT> cls.bus.unsubscribe(event, handler.func) <NEW_LINE> <DEDENT> elif handler.func not in cls.bus._subscribers[ event] and state is not False: <NEW_LINE> <INDENT> cls.bus.subscribe(event, handler.func) | INTERNAL API | 6259904d097d151d1a2c24ba |
class TestUtils(unittest.TestCase): <NEW_LINE> <INDENT> def test_has_attribute(self): <NEW_LINE> <INDENT> obj = self.get_test_obj() <NEW_LINE> actual1 = utils.has_attribute(obj, "value") <NEW_LINE> actual2 = utils.has_attribute(obj, "one.value") <NEW_LINE> actual3 = utils.has_attribute(obj, "one.two.Three.value") <NEW_LINE> self.assertEqual(actual1, True, "value attribute should be there") <NEW_LINE> self.assertEqual(actual2, True, "one.value attribute should be there") <NEW_LINE> self.assertEqual(actual3, True, "one.two.three.value attribute should be there") <NEW_LINE> <DEDENT> def test_get_attribute(self): <NEW_LINE> <INDENT> obj = self.get_test_obj() <NEW_LINE> actual1 = utils.get_attribute(obj, "value") <NEW_LINE> actual2 = utils.get_attribute(obj, "one.value") <NEW_LINE> actual3 = utils.get_attribute(obj, "one.two.three.value") <NEW_LINE> self.assertEqual(actual1, 44, "value attribute should be 44") <NEW_LINE> self.assertEqual(actual2, 45, "one.value attribute should 45") <NEW_LINE> self.assertEqual(actual3, 47, "one.two.three.value attribute should be 47") <NEW_LINE> <DEDENT> def get_test_obj(self): <NEW_LINE> <INDENT> child3 = type("obj", (object,), {"value": 47}) <NEW_LINE> child2 = type("obj", (object,), {"three": child3, "value": 46}) <NEW_LINE> child1 = type("obj", (object,), {"Two": child2, "value": 45}) <NEW_LINE> obj = type("obj", (object,), {"one": child1, "value": 44}) <NEW_LINE> return obj | Tests for function utils | 6259904d3539df3088ecd6ee |
class TreeBuilderWithComment(etree.TreeBuilder): <NEW_LINE> <INDENT> def comment(self, data): <NEW_LINE> <INDENT> self.start(etree.Comment, {}) <NEW_LINE> self.data(data) <NEW_LINE> self.end(etree.Comment) | Class to parse comment nodes with ElementTree | 6259904d596a897236128fd4 |
class TestK8sIoApimachineryPkgApisMetaV1Preconditions(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testK8sIoApimachineryPkgApisMetaV1Preconditions(self): <NEW_LINE> <INDENT> pass | K8sIoApimachineryPkgApisMetaV1Preconditions unit test stubs | 6259904ea8ecb0332587265d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.