code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class Encoder: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.encode_dict = {} <NEW_LINE> <DEDENT> def fit(self, data, features): <NEW_LINE> <INDENT> m, n = data.shape <NEW_LINE> for f in features: <NEW_LINE> <INDENT> for t in range(m): <NEW_LINE> <INDENT> val = data[t][f] <NEW_LINE> if self.get_code(val, f) is None: <NEW_LINE> <INDENT> self.create_code(val, f) <NEW_LINE> <DEDENT> data[t][f] = self.get_code(val, f) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def encode_label(self, data, label, label_code): <NEW_LINE> <INDENT> m, n = data.shape <NEW_LINE> for t in range(m): <NEW_LINE> <INDENT> data[t][label] = label_code[data[t][label]] <NEW_LINE> <DEDENT> <DEDENT> def get_code(self, val, f): <NEW_LINE> <INDENT> if val == '?': <NEW_LINE> <INDENT> return 'NaN' <NEW_LINE> <DEDENT> if f not in self.encode_dict: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if val not in self.encode_dict[f]: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.encode_dict[f][val] <NEW_LINE> <DEDENT> def create_code(self, val, f): <NEW_LINE> <INDENT> if f not in self.encode_dict: <NEW_LINE> <INDENT> self.encode_dict[f] = {} <NEW_LINE> <DEDENT> self.encode_dict[f][val] = len(self.encode_dict[f])
A Encoder will fit the given data set with discrete features. For all values in given features, it will replace the string value to a int value so that the data set can fit into the np.array(float)
62599035d99f1b3c44d067d5
class ShuffleDataset(UnaryUnchangedStructureDataset): <NEW_LINE> <INDENT> def __init__(self, input_dataset, buffer_size, seed=None, reshuffle_each_iteration=None, name=None): <NEW_LINE> <INDENT> self._input_dataset = input_dataset <NEW_LINE> self._buffer_size = ops.convert_to_tensor( buffer_size, dtype=dtypes.int64, name="buffer_size") <NEW_LINE> self._seed, self._seed2 = random_seed.get_seed(seed) <NEW_LINE> if reshuffle_each_iteration is None: <NEW_LINE> <INDENT> reshuffle_each_iteration = True <NEW_LINE> <DEDENT> self._reshuffle_each_iteration = reshuffle_each_iteration <NEW_LINE> self._metadata = dataset_metadata_pb2.Metadata() <NEW_LINE> if name: <NEW_LINE> <INDENT> self._metadata.name = _validate_and_encode(name) <NEW_LINE> <DEDENT> if (tf2.enabled() and (context.executing_eagerly() or ops.inside_function())): <NEW_LINE> <INDENT> variant_tensor = gen_dataset_ops.shuffle_dataset_v3( input_dataset._variant_tensor, buffer_size=self._buffer_size, seed=self._seed, seed2=self._seed2, seed_generator=gen_dataset_ops.dummy_seed_generator(), reshuffle_each_iteration=self._reshuffle_each_iteration, **self._common_args) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> variant_tensor = gen_dataset_ops.shuffle_dataset( input_dataset._variant_tensor, buffer_size=self._buffer_size, seed=self._seed, seed2=self._seed2, reshuffle_each_iteration=self._reshuffle_each_iteration, **self._common_args) <NEW_LINE> <DEDENT> super(ShuffleDataset, self).__init__(input_dataset, variant_tensor)
A `Dataset` that randomly shuffles the elements of its input.
6259903576d4e153a661db0a
class Connections(OADict): <NEW_LINE> <INDENT> class ConnectionsEntries(OAList): <NEW_LINE> <INDENT> class ConnectionsEntry(OADict): <NEW_LINE> <INDENT> def connection(self): <NEW_LINE> <INDENT> if self.oneall: <NEW_LINE> <INDENT> return self.oneall.connection(self.connection_token) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> each = ConnectionsEntry <NEW_LINE> <DEDENT> @property <NEW_LINE> def entries(self): <NEW_LINE> <INDENT> return getattr(self, '_entries', []) <NEW_LINE> <DEDENT> @entries.setter <NEW_LINE> def entries(self, value): <NEW_LINE> <INDENT> self._entries = Connections.ConnectionsEntries(value)
Represents the /connections/ OneAll API call
6259903582261d6c5273075d
class FirewallPolicyIntrusionDetectionBypassTrafficSpecifications(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'protocol': {'key': 'protocol', 'type': 'str'}, 'source_addresses': {'key': 'sourceAddresses', 'type': '[str]'}, 'destination_addresses': {'key': 'destinationAddresses', 'type': '[str]'}, 'destination_ports': {'key': 'destinationPorts', 'type': '[str]'}, 'source_ip_groups': {'key': 'sourceIpGroups', 'type': '[str]'}, 'destination_ip_groups': {'key': 'destinationIpGroups', 'type': '[str]'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(FirewallPolicyIntrusionDetectionBypassTrafficSpecifications, self).__init__(**kwargs) <NEW_LINE> self.name = kwargs.get('name', None) <NEW_LINE> self.description = kwargs.get('description', None) <NEW_LINE> self.protocol = kwargs.get('protocol', None) <NEW_LINE> self.source_addresses = kwargs.get('source_addresses', None) <NEW_LINE> self.destination_addresses = kwargs.get('destination_addresses', None) <NEW_LINE> self.destination_ports = kwargs.get('destination_ports', None) <NEW_LINE> self.source_ip_groups = kwargs.get('source_ip_groups', None) <NEW_LINE> self.destination_ip_groups = kwargs.get('destination_ip_groups', None)
Intrusion detection bypass traffic specification. :param name: Name of the bypass traffic rule. :type name: str :param description: Description of the bypass traffic rule. :type description: str :param protocol: The rule bypass protocol. Possible values include: "TCP", "UDP", "ICMP", "ANY". :type protocol: str or ~azure.mgmt.network.v2020_08_01.models.FirewallPolicyIntrusionDetectionProtocol :param source_addresses: List of source IP addresses or ranges for this rule. :type source_addresses: list[str] :param destination_addresses: List of destination IP addresses or ranges for this rule. :type destination_addresses: list[str] :param destination_ports: List of destination ports or ranges. :type destination_ports: list[str] :param source_ip_groups: List of source IpGroups for this rule. :type source_ip_groups: list[str] :param destination_ip_groups: List of destination IpGroups for this rule. :type destination_ip_groups: list[str]
62599035d10714528d69ef25
class ExporterXslList(APIView): <NEW_LINE> <INDENT> permission_classes = (IsAuthenticated,) <NEW_LINE> def get(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> exporter_list = xsl_api.get_all() <NEW_LINE> return_value = ExporterXslSerializer(exporter_list, many=True) <NEW_LINE> return Response(return_value.data) <NEW_LINE> <DEDENT> except Exception as api_exception: <NEW_LINE> <INDENT> content = {"message": str(api_exception)} <NEW_LINE> return Response(content, status=status.HTTP_500_INTERNAL_SERVER_ERROR) <NEW_LINE> <DEDENT> <DEDENT> @method_decorator(api_staff_member_required()) <NEW_LINE> def post(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> xsl_serializer = ExporterXslSerializer(data=request.data) <NEW_LINE> xsl_serializer.is_valid(True) <NEW_LINE> xsl_serializer.save() <NEW_LINE> return Response(xsl_serializer.data, status=status.HTTP_201_CREATED) <NEW_LINE> <DEDENT> except ValidationError as validation_exception: <NEW_LINE> <INDENT> content = {"message": validation_exception.detail} <NEW_LINE> return Response(content, status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> except Exception as api_exception: <NEW_LINE> <INDENT> content = {"message": str(api_exception)} <NEW_LINE> return Response(content, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
List all XSL Exporters, or create
6259903530c21e258be9993f
class Server(common.JSONConfigurable): <NEW_LINE> <INDENT> _attrs = collections.OrderedDict([ ('name', None), ('host', None), ('port', None), ('channels', Channel), ('all_channels', Channel), ('locked', None), ('pause', None), ('fast', None), ('uptime', None) ]) <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self.connected = False <NEW_LINE> self.client = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def addr(self): <NEW_LINE> <INDENT> return (self.host, self.port)
Client implementation of server
6259903523e79379d538d63d
class CollectCurrentFile(pyblish.api.ContextPlugin): <NEW_LINE> <INDENT> order = pyblish.api.CollectorOrder <NEW_LINE> def process(self, context): <NEW_LINE> <INDENT> project = context.data('activeProject') <NEW_LINE> context.set_data('currentFile', value=project.path())
Inject the current working file into context
62599035a8ecb03325872351
class Descendants(JSONPath): <NEW_LINE> <INDENT> def __init__(self, left, right): <NEW_LINE> <INDENT> self.left = left <NEW_LINE> self.right = right <NEW_LINE> <DEDENT> def find(self, datum): <NEW_LINE> <INDENT> left_matches = self.left.find(datum) <NEW_LINE> if not isinstance(left_matches, list): <NEW_LINE> <INDENT> left_matches = [left_matches] <NEW_LINE> <DEDENT> def match_recursively(datum): <NEW_LINE> <INDENT> right_matches = self.right.find(datum) <NEW_LINE> if isinstance(datum.value, list): <NEW_LINE> <INDENT> recursive_matches = [submatch for i in range(0, len(datum.value)) for submatch in match_recursively(DatumInContext(datum.value[i], context=datum, path=Index(i)))] <NEW_LINE> <DEDENT> elif isinstance(datum.value, dict): <NEW_LINE> <INDENT> recursive_matches = [submatch for field in datum.value.keys() for submatch in match_recursively(DatumInContext(datum.value[field], context=datum, path=Fields(field)))] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> recursive_matches = [] <NEW_LINE> <DEDENT> return right_matches + list(recursive_matches) <NEW_LINE> <DEDENT> return [submatch for left_match in left_matches for submatch in match_recursively(left_match)] <NEW_LINE> <DEDENT> def is_singular(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def update(self, data, val): <NEW_LINE> <INDENT> left_matches = self.left.find(data) <NEW_LINE> if not isinstance(left_matches, list): <NEW_LINE> <INDENT> left_matches = [left_matches] <NEW_LINE> <DEDENT> def update_recursively(data): <NEW_LINE> <INDENT> if not (isinstance(data, list) or isinstance(data, dict)): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.right.update(data, val) <NEW_LINE> if isinstance(data, list): <NEW_LINE> <INDENT> for i in range(0, len(data)): <NEW_LINE> <INDENT> update_recursively(data[i]) <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(data, dict): <NEW_LINE> <INDENT> for field in data.keys(): <NEW_LINE> <INDENT> update_recursively(data[field]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for submatch in left_matches: <NEW_LINE> <INDENT> update_recursively(submatch.value) <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '%s..%s' % (self.left, self.right) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, Descendants) and self.left == other.left and self.right == other.right
JSONPath that matches first the left expression then any descendant of it which matches the right expression.
625990358a43f66fc4bf32be
class Ceilometer(monasca_setup.detection.ServicePlugin): <NEW_LINE> <INDENT> def __init__(self, template_dir, overwrite=True, args=None): <NEW_LINE> <INDENT> service_params = { 'template_dir': template_dir, 'overwrite': overwrite, 'service_name': 'telemetry', 'process_names': ['ceilometer-agent-compute', 'ceilometer-agent-central', 'ceilometer-agent-notification', 'ceilometer-collector', 'ceilometer-alarm-notifier', 'ceilometer-alarm-evaluator', 'ceilometer-api'], 'service_api_url': '', 'search_pattern': '' } <NEW_LINE> super(Ceilometer, self).__init__(service_params)
Detect Ceilometer daemons and setup configuration to monitor them.
6259903571ff763f4b5e88cd
class UnknownServiceEnvironmentNotConfiguredError(Exception): <NEW_LINE> <INDENT> pass
Raised when unknown service-environment is not configured for plugin.
62599035be8e80087fbc01b2
class WebSearchAdminWebPagesAvailabilityTest(InvenioTestCase): <NEW_LINE> <INDENT> def test_websearch_admin_interface_pages_availability(self): <NEW_LINE> <INDENT> baseurl = cfg['CFG_SITE_URL'] + '/admin/websearch/websearchadmin.py' <NEW_LINE> _exports = ['', '?mtype=perform_showall', '?mtype=perform_addcollection', '?mtype=perform_addcollectiontotree', '?mtype=perform_modifycollectiontree', '?mtype=perform_checkwebcollstatus', '?mtype=perform_checkcollectionstatus',] <NEW_LINE> error_messages = [] <NEW_LINE> for url in [baseurl + page for page in _exports]: <NEW_LINE> <INDENT> error_messages.extend(test_web_page_content(url, username='guest', expected_text= 'Authorization failure')) <NEW_LINE> error_messages.extend(test_web_page_content(url, username='admin')) <NEW_LINE> <DEDENT> if error_messages: <NEW_LINE> <INDENT> self.fail(merge_error_messages(error_messages)) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def test_websearch_admin_guide_availability(self): <NEW_LINE> <INDENT> url = cfg['CFG_SITE_URL'] + '/help/admin/websearch-admin-guide' <NEW_LINE> error_messages = test_web_page_content(url, expected_text="WebSearch Admin Guide") <NEW_LINE> if error_messages: <NEW_LINE> <INDENT> self.fail(merge_error_messages(error_messages)) <NEW_LINE> <DEDENT> return
Check WebSearch Admin web pages whether they are up or not.
625990358c3a8732951f768c
class StringUI(TextUI): <NEW_LINE> <INDENT> def __init__(self, parameter): <NEW_LINE> <INDENT> super(StringUI, self).__init__(parameter) <NEW_LINE> self.value.textEdited.connect(self.parameter.push_value)
The String is a Text based UI that display a string
625990353eb6a72ae038b79b
class SSH: <NEW_LINE> <INDENT> def __init__(self, ssh_keyfile): <NEW_LINE> <INDENT> self._ssh_keyfile = ssh_keyfile <NEW_LINE> <DEDENT> def connect(self, instance): <NEW_LINE> <INDENT> client = sshclient.SSHClient() <NEW_LINE> client.set_missing_host_key_policy(sshclient.AutoAddPolicy()) <NEW_LINE> client.connect(instance.ip_address, username="core", key_filename=self._ssh_keyfile) <NEW_LINE> return client <NEW_LINE> <DEDENT> def _send_file(self, sftp, local_obj, remote_file): <NEW_LINE> <INDENT> base_dir = os.path.dirname(remote_file) <NEW_LINE> makedirs(sftp, base_dir) <NEW_LINE> sftp.putfo(local_obj, remote_file) <NEW_LINE> <DEDENT> def upload_file(self, instance, local_obj, remote_file): <NEW_LINE> <INDENT> client = self.connect(instance) <NEW_LINE> try: <NEW_LINE> <INDENT> sftp = client.open_sftp() <NEW_LINE> try: <NEW_LINE> <INDENT> self._send_file(sftp, local_obj, remote_file) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> sftp.close() <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> client.close() <NEW_LINE> <DEDENT> <DEDENT> async def reload_sysctl(self, collection): <NEW_LINE> <INDENT> def _reload(inst): <NEW_LINE> <INDENT> client = self.connect(inst.instance) <NEW_LINE> try: <NEW_LINE> <INDENT> stdin, stdout, stderr = client.exec_command( "sudo sysctl -p /etc/sysctl.conf") <NEW_LINE> output = stdout.channel.recv(4096) <NEW_LINE> stdin.close() <NEW_LINE> stdout.close() <NEW_LINE> stderr.close() <NEW_LINE> return output <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> client.close() <NEW_LINE> <DEDENT> <DEDENT> await collection.map(_reload)
SSH client to communicate with instances.
62599035c432627299fa412b
class FakeFunction(_ReturnValues): <NEW_LINE> <INDENT> def __init__(self, name, code, func_globals = {}, varnames = None) : <NEW_LINE> <INDENT> _ReturnValues.__init__(self) <NEW_LINE> self.func_name = self.__name__ = name <NEW_LINE> self.func_doc = self.__doc__ = "ignore" <NEW_LINE> self.func_code = FakeCode(code, varnames) <NEW_LINE> self.func_defaults = None <NEW_LINE> self.func_globals = func_globals <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.func_name <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '%s from %r' % (self.func_name, self.func_code.co_filename)
This is a holder class for turning non-scoped code (for example at module-global level, or generator expressions) into a function. Pretends to be a normal callable and can be used as constructor argument to L{Function}
62599035d99f1b3c44d067d7
class PersonalityList(generics.ListAPIView): <NEW_LINE> <INDENT> model = Personality <NEW_LINE> queryset = Personality.objects.all() <NEW_LINE> serializer_class = PersonalitySerializer <NEW_LINE> authentication_classes = (JSONWebTokenAuthentication,) <NEW_LINE> permission_classes = ( permissions.IsAdminUser, )
https://themoviebook.herokuapp.com/movies/personalities/
62599035ac7a0e7691f7361c
class Solution(): <NEW_LINE> <INDENT> def dailyTemperatures(self, T): <NEW_LINE> <INDENT> nxt = [float('inf')] * 102 <NEW_LINE> ans = [0] * len(T) <NEW_LINE> for i in range(len(T) - 1, -1, -1): <NEW_LINE> <INDENT> warmer_index = min(nxt[t] for t in range(T[i]+1, 102)) <NEW_LINE> if warmer_index < float('inf'): <NEW_LINE> <INDENT> ans[i] = warmer_index - i <NEW_LINE> <DEDENT> nxt[T[i]] = i <NEW_LINE> <DEDENT> return ans
从后向前遍历,时O(nm),m是温度范围长度
62599035b57a9660fecd2bb2
class CodeGenerationStage(Stage): <NEW_LINE> <INDENT> def __init__(self, control): <NEW_LINE> <INDENT> super().__init__(control) <NEW_LINE> <DEDENT> def command_line_args(self, args): <NEW_LINE> <INDENT> self.control.stage('CompilerConfigurationStage').emitters.command_line_args(args) <NEW_LINE> <DEDENT> def command_line_flags(self, parser): <NEW_LINE> <INDENT> parser.add_argument_group('\033[1mCode Generation Configuration\033[0m') <NEW_LINE> self.control.stage('CompilerConfigurationStage').emitters.command_line_flags(parser) <NEW_LINE> <DEDENT> def process(self): <NEW_LINE> <INDENT> self._status = 'Running' <NEW_LINE> self.color = self.control.stage('CompilerConfigurationStage').color <NEW_LINE> self.emitters = self.control.stage('CompilerConfigurationStage').emitter <NEW_LINE> self._status = 'Completed' <NEW_LINE> for emitter in self.emitters: <NEW_LINE> <INDENT> emitter = self.control.stage('CompilerConfigurationStage').emitters.emitter( emitter ) <NEW_LINE> emitter.process() <NEW_LINE> emitter.output() <NEW_LINE> if not emitter.check(): <NEW_LINE> <INDENT> self._status = 'Incomplete'
Code Generation Stage * Generates code for the given firmware backend * Backend is selected in the Compiler Configuration Stage * Uses the specified emitter to generate the code
625990354e696a045264e6bc
class GetCompanyFilingsResultSet(ResultSet): <NEW_LINE> <INDENT> def getJSONFromString(self, str): <NEW_LINE> <INDENT> return json.loads(str) <NEW_LINE> <DEDENT> def get_Response(self): <NEW_LINE> <INDENT> return self._output.get('Response', None)
A ResultSet with methods tailored to the values returned by the GetCompanyFilings Choreo. The ResultSet object is used to retrieve the results of a Choreo execution.
625990358c3a8732951f768d
class NeuralBagOfWordsModel(model.TFModel): <NEW_LINE> <INDENT> def __init__(self, config, vocab, label_space_size): <NEW_LINE> <INDENT> super(NeuralBagOfWordsModel, self).__init__(config, vocab, label_space_size) <NEW_LINE> self.notes = tf.placeholder(tf.int32, [config.batch_size, None], name='notes') <NEW_LINE> self.lengths = tf.placeholder(tf.int32, [config.batch_size], name='lengths') <NEW_LINE> self.labels = tf.placeholder(tf.float32, [config.batch_size, label_space_size], name='labels') <NEW_LINE> with tf.device('/cpu:0'): <NEW_LINE> <INDENT> init_width = 0.5 / config.word_emb_size <NEW_LINE> self.embeddings = tf.get_variable('embeddings', [len(vocab.vocab), config.word_emb_size], initializer=tf.random_uniform_initializer(-init_width, init_width), trainable=config.train_embs) <NEW_LINE> embed = tf.nn.embedding_lookup(self.embeddings, self.notes) <NEW_LINE> <DEDENT> embed *= tf.to_float(tf.expand_dims(tf.greater(self.notes, 0), -1)) <NEW_LINE> data = self.summarize(embed) <NEW_LINE> logits = util.linear(data, self.label_space_size) <NEW_LINE> self.probs = tf.sigmoid(logits) <NEW_LINE> self.loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=self.labels)) <NEW_LINE> self.train_op = self.minimize_loss(self.loss) <NEW_LINE> <DEDENT> def summarize(self, embed, normalize=False): <NEW_LINE> <INDENT> added = tf.reduce_sum(embed, 1) <NEW_LINE> if normalize: <NEW_LINE> <INDENT> added = tf.nn.l2_normalize(added, 1) <NEW_LINE> <DEDENT> return added
A neural bag of words model.
6259903516aa5153ce401621
class DataObject(object): <NEW_LINE> <INDENT> def __init__(self, C, ID): <NEW_LINE> <INDENT> self.C = C <NEW_LINE> self.ID = ID <NEW_LINE> self.U = self <NEW_LINE> self.D = self <NEW_LINE> self.L = self <NEW_LINE> self.R = self
Describes a data object in the Dancing Links algorithm.
6259903507d97122c4217dd9
class EELandsat(object): <NEW_LINE> <INDENT> def list(self, bounds): <NEW_LINE> <INDENT> bbox = ee.Feature.Rectangle( *[float(i.strip()) for i in bounds.split(',')]) <NEW_LINE> images = ee.ImageCollection('LANDSAT/LE7_L1T').filterBounds(bbox).getInfo() <NEW_LINE> if 'features' in images: <NEW_LINE> <INDENT> return [x['id'] for x in images['features']] <NEW_LINE> <DEDENT> return [] <NEW_LINE> <DEDENT> def mapid(self, start, end): <NEW_LINE> <INDENT> MAP_IMAGE_BANDS = ['B3', 'B2', 'B1'] <NEW_LINE> PREVIEW_GAIN = 500 <NEW_LINE> return _get_raw_mapid(_get_landsat_toa(start, end).mosaic().getMapId({ 'bands': ','.join(MAP_IMAGE_BANDS), 'gain': PREVIEW_GAIN }))
A helper for accessing Landsat 7 images.
62599035dc8b845886d546e8
class DownloadWindow(QDialog): <NEW_LINE> <INDENT> def __init__(self, url, version, win_parent=None): <NEW_LINE> <INDENT> self.win_parent = win_parent <NEW_LINE> self.url = url <NEW_LINE> self.version = version <NEW_LINE> QDialog.__init__(self, win_parent) <NEW_LINE> self.setWindowTitle('pyNastran Update') <NEW_LINE> self.create_widgets() <NEW_LINE> self.create_layout() <NEW_LINE> self.set_connections() <NEW_LINE> <DEDENT> def create_widgets(self): <NEW_LINE> <INDENT> self.name = QLabel("Version %s is now available." % self.version) <NEW_LINE> if qt_version == 4: <NEW_LINE> <INDENT> self.link = ClickableQLabel(self.url) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.link = QPushButton(self.url) <NEW_LINE> self.link.setFlat(True) <NEW_LINE> <DEDENT> font = QtGui.QFont() <NEW_LINE> font.setUnderline(True) <NEW_LINE> self.link.setFont(font) <NEW_LINE> self.link.setStyleSheet("QLabel {color : blue}") <NEW_LINE> self.close_button = QPushButton("Close") <NEW_LINE> <DEDENT> def create_layout(self): <NEW_LINE> <INDENT> grid = QGridLayout() <NEW_LINE> grid.addWidget(self.name, 0, 0) <NEW_LINE> grid.addWidget(self.link, 1, 0) <NEW_LINE> close_box = QHBoxLayout() <NEW_LINE> close_box.addWidget(self.close_button) <NEW_LINE> vbox = QVBoxLayout() <NEW_LINE> vbox.addLayout(grid) <NEW_LINE> vbox.addStretch() <NEW_LINE> vbox.addLayout(close_box) <NEW_LINE> self.setLayout(vbox) <NEW_LINE> <DEDENT> def set_connections(self): <NEW_LINE> <INDENT> if qt_version == 4: <NEW_LINE> <INDENT> self.connect(self.link, QtCore.SIGNAL('clicked()'), self.on_download) <NEW_LINE> self.connect(self, QtCore.SIGNAL('triggered()'), self.closeEvent) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.link.clicked.connect(self.on_download) <NEW_LINE> <DEDENT> self.close_button.clicked.connect(self.on_cancel) <NEW_LINE> <DEDENT> def keyPressEvent(self, event): <NEW_LINE> <INDENT> if event.key() == QtCore.Qt.Key_Escape: <NEW_LINE> <INDENT> self.close() <NEW_LINE> <DEDENT> <DEDENT> def closeEvent(self, event): <NEW_LINE> <INDENT> event.accept() <NEW_LINE> <DEDENT> def on_download(self): <NEW_LINE> <INDENT> webbrowser.open(self.url, new=0, autoraise=True) <NEW_LINE> <DEDENT> def on_ok(self): <NEW_LINE> <INDENT> passed = self.on_apply() <NEW_LINE> if passed: <NEW_LINE> <INDENT> self.close() <NEW_LINE> <DEDENT> <DEDENT> def on_cancel(self): <NEW_LINE> <INDENT> self.close()
+-------------------+ | Legend Properties | +-----------------------+ | Title ______ Default | | Min ______ Default | | Max ______ Default | | Format ______ Default | | Scale ______ Default | | Number of Colors ____ | (TODO) | Number of Labels ____ | (TODO) | Label Size ____ | (TODO) | | | x Min/Max (Blue->Red) | | o Max/Min (Red->Blue) | | | | x Vertical/Horizontal | | x Show/Hide | | | | Apply OK Cancel | +-----------------------+
625990353eb6a72ae038b79d
class SonosNodeServer(SimpleNodeServer): <NEW_LINE> <INDENT> controller = [] <NEW_LINE> speakers = [] <NEW_LINE> def setup(self): <NEW_LINE> <INDENT> super(SimpleNodeServer, self).setup() <NEW_LINE> manifest = self.config.get('manifest',{}) <NEW_LINE> self.controller = SonosControl(self,'sonoscontrol','Sonos Control', True, manifest) <NEW_LINE> self.poly.logger.info("FROM Poly ISYVER: " + self.poly.isyver) <NEW_LINE> self.controller._discover() <NEW_LINE> self.update_config() <NEW_LINE> <DEDENT> def poll(self): <NEW_LINE> <INDENT> if len(self.speakers) >= 1: <NEW_LINE> <INDENT> for i in self.speakers: <NEW_LINE> <INDENT> i.update_info() <NEW_LINE> <DEDENT> <DEDENT> pass <NEW_LINE> <DEDENT> def long_poll(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def report_drivers(self): <NEW_LINE> <INDENT> if len(self.speakers) >= 1: <NEW_LINE> <INDENT> for i in self.speakers: <NEW_LINE> <INDENT> i.report_driver()
Sonos Node Server
62599035d6c5a102081e325c
class NGramModelSet(_object): <NEW_LINE> <INDENT> __swig_setmethods__ = {} <NEW_LINE> __setattr__ = lambda self, name, value: _swig_setattr(self, NGramModelSet, name, value) <NEW_LINE> __swig_getmethods__ = {} <NEW_LINE> __getattr__ = lambda self, name: _swig_getattr(self, NGramModelSet, name) <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __iter__(self): <NEW_LINE> <INDENT> return _sphinxbase.NGramModelSet___iter__(self) <NEW_LINE> <DEDENT> def __init__(self, config, logmath, path): <NEW_LINE> <INDENT> this = _sphinxbase.new_NGramModelSet(config, logmath, path) <NEW_LINE> try: <NEW_LINE> <INDENT> self.this.append(this) <NEW_LINE> <DEDENT> except __builtin__.Exception: <NEW_LINE> <INDENT> self.this = this <NEW_LINE> <DEDENT> <DEDENT> __swig_destroy__ = _sphinxbase.delete_NGramModelSet <NEW_LINE> __del__ = lambda self: None <NEW_LINE> def count(self): <NEW_LINE> <INDENT> return _sphinxbase.NGramModelSet_count(self) <NEW_LINE> <DEDENT> def add(self, model, name, weight, reuse_widmap): <NEW_LINE> <INDENT> return _sphinxbase.NGramModelSet_add(self, model, name, weight, reuse_widmap) <NEW_LINE> <DEDENT> def select(self, name): <NEW_LINE> <INDENT> return _sphinxbase.NGramModelSet_select(self, name) <NEW_LINE> <DEDENT> def lookup(self, name): <NEW_LINE> <INDENT> return _sphinxbase.NGramModelSet_lookup(self, name) <NEW_LINE> <DEDENT> def current(self): <NEW_LINE> <INDENT> return _sphinxbase.NGramModelSet_current(self)
Proxy of C NGramModelSet struct.
6259903576d4e153a661db0c
class types: <NEW_LINE> <INDENT> server = String <NEW_LINE> port = Integer(optional=True, default=25) <NEW_LINE> user = String(optional=True, default=None) <NEW_LINE> password = String(optional=True, default=None) <NEW_LINE> local_hostname = String(optional=True, default=None)
Only the server is required; all other parameters are optionally.
62599035596a897236128dd4
class Habit(): <NEW_LINE> <INDENT> def __init__(self, config_obj, store): <NEW_LINE> <INDENT> self.config = config_obj <NEW_LINE> self.name = config_obj['name'] <NEW_LINE> self.tag = config_obj['tag'] <NEW_LINE> self.code = config_obj['name'] <NEW_LINE> self.store = store <NEW_LINE> <DEDENT> def per_interval(self): <NEW_LINE> <INDENT> return int(self.config['interval'].split('/')[0]) <NEW_LINE> <DEDENT> def interval_length(self): <NEW_LINE> <INDENT> return int(self.config['interval'].split('/')[1]) <NEW_LINE> <DEDENT> def interval_for_print(self): <NEW_LINE> <INDENT> candidate = self.config.get('interval', '7/7') <NEW_LINE> if candidate != '7/7': <NEW_LINE> <INDENT> return candidate <NEW_LINE> <DEDENT> return '' <NEW_LINE> <DEDENT> def stats(self): <NEW_LINE> <INDENT> results = [] <NEW_LINE> today = today_date() <NEW_LINE> for i in range(0, 30): <NEW_LINE> <INDENT> day = today - timedelta(days=i) <NEW_LINE> stats = get_stats_for(self, day) <NEW_LINE> if stats: <NEW_LINE> <INDENT> results.append(stats) <NEW_LINE> <DEDENT> elif self.reached_limit(day): <NEW_LINE> <INDENT> results.append({'code': 'auto'}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> results.append(None) <NEW_LINE> <DEDENT> <DEDENT> return results <NEW_LINE> <DEDENT> def reached_limit(self, day=None): <NEW_LINE> <INDENT> if 'interval' not in self.config: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if day is None: <NEW_LINE> <INDENT> day = today_date() <NEW_LINE> <DEDENT> stats = [get_stats_for(self, day - timedelta(days=i)) for i in range(0, self.interval_length()-1)] <NEW_LINE> return len([s for s in stats if s]) >= self.per_interval() <NEW_LINE> <DEDENT> def is_ok(self): <NEW_LINE> <INDENT> if get_stats_for(self, today_date()): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if self.reached_limit(): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def skip(self): <NEW_LINE> <INDENT> self.store.data.append({'code': self.code, 'date': str(today_date()), 'skip': True}) <NEW_LINE> <DEDENT> def toggle(self): <NEW_LINE> <INDENT> if self.is_ok(): <NEW_LINE> <INDENT> self.remove_today() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.store.data.append({'code': self.code, 'date': str(today_date())}) <NEW_LINE> <DEDENT> <DEDENT> def done(self): <NEW_LINE> <INDENT> self.store.data.append({'code': self.code, 'date': str(today_date())}) <NEW_LINE> <DEDENT> def undone(self): <NEW_LINE> <INDENT> self.remove_today() <NEW_LINE> <DEDENT> def remove_today(self): <NEW_LINE> <INDENT> for log in self.store.data: <NEW_LINE> <INDENT> if log['code'] == self.code: <NEW_LINE> <INDENT> if log['date'] == str(today_date()): <NEW_LINE> <INDENT> self.store.data.remove(log)
Привычка
6259903571ff763f4b5e88d1
class Solution(object): <NEW_LINE> <INDENT> def func(self, n): <NEW_LINE> <INDENT> tmp = [] <NEW_LINE> def total(x): <NEW_LINE> <INDENT> for _ in range(2*x): tmp.append(['(', ')']) <NEW_LINE> from itertools import product <NEW_LINE> for i in product(*tmp): <NEW_LINE> <INDENT> yield i <NEW_LINE> <DEDENT> <DEDENT> res = [] <NEW_LINE> for s in total(n): <NEW_LINE> <INDENT> counter = i = 0 <NEW_LINE> while i < 2*n: <NEW_LINE> <INDENT> if s[i] == '(': counter += 1 <NEW_LINE> else: counter -= 1 <NEW_LINE> if counter < 0 or counter > n: break <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> if counter == 0 and i == 2*n: res.append(s) <NEW_LINE> <DEDENT> return res
Solution description
62599035d53ae8145f91959b
class TestIO(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.path = os.path.dirname(os.path.abspath(__file__)) <NEW_LINE> self.file_ = 'pt_test_data.hdf5' <NEW_LINE> shutil.copy(os.path.join(self.path, self.file_), self.file_) <NEW_LINE> self.assertTrue(os.path.exists(self.file_)) <NEW_LINE> self.label = 'test_io_data' <NEW_LINE> with tb.File(self.file_, mode='r') as h5_file: <NEW_LINE> <INDENT> self.reference_rho = h5_file.get_node( '/' + self.label + '/phase_transition').read() <NEW_LINE> <DEDENT> self.default_delta = np.linspace(0, 1, len(self.reference_rho) + 1)[1:] <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> if os.path.exists(self.file_): <NEW_LINE> <INDENT> os.remove(self.file_) <NEW_LINE> <DEDENT> self.assertFalse(os.path.exists(self.file_)) <NEW_LINE> <DEDENT> def test_default(self): <NEW_LINE> <INDENT> delta, rho = magni.cs.phase_transition.io.load_phase_transition( self.file_, label=self.label) <NEW_LINE> self.assertTrue(np.allclose(delta, self.default_delta)) <NEW_LINE> self.assertTrue(np.allclose(rho, self.reference_rho)) <NEW_LINE> <DEDENT> def test_custom_delta(self): <NEW_LINE> <INDENT> custom_delta = np.ones(self.reference_rho.shape) <NEW_LINE> delta, rho = magni.cs.phase_transition.io.load_phase_transition( self.file_, label=self.label, delta=custom_delta) <NEW_LINE> self.assertTrue(np.allclose(delta, custom_delta)) <NEW_LINE> self.assertTrue(np.allclose(rho, self.reference_rho)) <NEW_LINE> <DEDENT> def test_invalid_delta(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> magni.cs.phase_transition.io.load_phase_transition( self.file_, label=self.label, delta=np.zeros(1)) <NEW_LINE> <DEDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> magni.cs.phase_transition.io.load_phase_transition( self.file_, label=self.label, delta=3 * np.ones(self.reference_rho.shape))
Tests of the io module. **Testing Strategy** Input/Output values are compared to a reference.
6259903573bcbd0ca4bcb3bf
class PurchaseOrder(BaseModel): <NEW_LINE> <INDENT> STATUS = Choices((0, 'draft', ('Draft')), (1, 'assigned', ('Assigned')), (2, 'done', ('Done')), (3, 'cancelled', ('Cancelled')) ) <NEW_LINE> purchaser = models.ForeignKey(Facility, related_name='%(app_label)s_%(class)s_purchaser') <NEW_LINE> supplier = models.ForeignKey(Facility, related_name='%(app_label)s_%(class)s_supplier') <NEW_LINE> status = models.IntegerField(choices=STATUS, default=STATUS.draft) <NEW_LINE> emergency = models.BooleanField(default=False) <NEW_LINE> order_date = models.DateField() <NEW_LINE> expected_date = models.DateField(blank=True, null=True)
PurchaseOrder: is used to place a formal request for supply of products listed in the purchase order lines by the purchasing facility(purchaser). it can be generated by the LMIS system, edited by the store manager or CCO then forwarded for the Supplying Facility
625990351d351010ab8f4c52
class EntryAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> fieldsets = [ ('Title', {'fields': ['headline']}), ('Content', {'fields': ['body_text']}), ]
fieldsets = [ (None, {'fields': ['question_text']}), ('Date information', {'fields': ['pub_date']}), ]
62599035cad5886f8bdc5917
class ExportStatistics(Operator, ExportHelper): <NEW_LINE> <INDENT> bl_idname = "export_stats.tofile" <NEW_LINE> bl_label = "Export statistics to file" <NEW_LINE> filename_ext = ".csv" <NEW_LINE> filter_glob: StringProperty( default="*.csv", options={'HIDDEN'}, maxlen=255, ) <NEW_LINE> groups: BoolProperty( name="add collection name", description="Add collection name from viewport (usefull to cluser grooups)", default=True, ) <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> return write_stats_on_disk(context, self.filepath, self.groups)
This appears in the tooltip of the operator and in the generated docs
625990350a366e3fb87ddb1e
class ModelDefinitionException(NeomodelException): <NEW_LINE> <INDENT> def __init__(self, db_node_class, current_node_class_registry): <NEW_LINE> <INDENT> self.db_node_class = db_node_class <NEW_LINE> self.current_node_class_registry = current_node_class_registry
Abstract exception to handle error conditions related to the node-to-class registry.
6259903526068e7796d4da80
class vonmises_gen(rv_continuous): <NEW_LINE> <INDENT> def _rvs(self, b): <NEW_LINE> <INDENT> return mtrand.vonmises(0.0, b, size=self._size) <NEW_LINE> <DEDENT> def _pdf(self, x, b): <NEW_LINE> <INDENT> return exp(b*cos(x)) / (2*pi*special.i0(b)) <NEW_LINE> <DEDENT> def _cdf(self, x, b): <NEW_LINE> <INDENT> return vonmises_cython.von_mises_cdf(b,x) <NEW_LINE> <DEDENT> def _stats_skip(self, b): <NEW_LINE> <INDENT> return 0, None, 0, None
A Von Mises continuous random variable. %(before_notes)s Notes ----- If `x` is not in range or `loc` is not in range it assumes they are angles and converts them to [-pi, pi] equivalents. The probability density function for `vonmises` is:: vonmises.pdf(x, b) = exp(b*cos(x)) / (2*pi*I[0](b)) for ``-pi <= x <= pi``, ``b > 0``. See Also -------- vonmises_line : The same distribution, defined on a [-pi, pi] segment of the real line. %(example)s
625990354e696a045264e6be
class Transformation(Getter): <NEW_LINE> <INDENT> name = None <NEW_LINE> arity = 1 <NEW_LINE> args = ['expression'] <NEW_LINE> def __init__(self, inner): <NEW_LINE> <INDENT> self.inner = inner <NEW_LINE> <DEDENT> def get(self, raw_doc): <NEW_LINE> <INDENT> inner_values = self.inner.get(raw_doc) <NEW_LINE> assert isinstance(inner_values, list), 'get() should always return a list' <NEW_LINE> return self.transform(inner_values) <NEW_LINE> <DEDENT> def transform(self, values): <NEW_LINE> <INDENT> raise NotImplementedError(self.transform)
A transformation on a value from another Getter.
62599035d4950a0f3b1116db
class FieldComparatorExactString(FieldComparator): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> FieldComparator.__init__(self, kwargs) <NEW_LINE> self.log() <NEW_LINE> <DEDENT> def compare(self, val1, val2): <NEW_LINE> <INDENT> if (val1 in self.missing_values) or (val2 in self.missing_values): <NEW_LINE> <INDENT> return self.missing_weight <NEW_LINE> <DEDENT> elif (val1 == val2): <NEW_LINE> <INDENT> return self.__calc_freq_agree_weight__(val1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.disagree_weight
A field comparator based on exact string comparison.
625990358e05c05ec3f6f6f7
class ChangInShareOfOwnerEquitiInSu(HandleIndexContent): <NEW_LINE> <INDENT> def __init__(self, stk_cd_id, acc_per, indexno, indexcontent): <NEW_LINE> <INDENT> super(ChangInShareOfOwnerEquitiInSu, self).__init__(stk_cd_id, acc_per, indexno, indexcontent) <NEW_LINE> <DEDENT> def recognize(self): <NEW_LINE> <INDENT> indexnos = ['0b090201'] <NEW_LINE> pass <NEW_LINE> <DEDENT> def converse(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def logic(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> df, unit, instructi = recognize_instucti(self.indexcontent) <NEW_LINE> save_combine_instructi(instructi, models.ComprehensNote, self.stk_cd_id, self.acc_per,'A', 'chang_share_of_owner_equiti_in_subsidiari')
在子公司所有者权益份额发生变化的情况说明
62599035d18da76e235b79eb
class PredictionQueryTag(Model): <NEW_LINE> <INDENT> _validation = { 'id': {'readonly': True}, 'min_threshold': {'readonly': True}, 'max_threshold': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'min_threshold': {'key': 'minThreshold', 'type': 'float'}, 'max_threshold': {'key': 'maxThreshold', 'type': 'float'}, } <NEW_LINE> def __init__(self, **kwargs) -> None: <NEW_LINE> <INDENT> super(PredictionQueryTag, self).__init__(**kwargs) <NEW_LINE> self.id = None <NEW_LINE> self.min_threshold = None <NEW_LINE> self.max_threshold = None
PredictionQueryTag. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: :vartype id: str :ivar min_threshold: :vartype min_threshold: float :ivar max_threshold: :vartype max_threshold: float
6259903521bff66bcd723d9f
class FindOverlapInOneLayer(QgsProcessingAlgorithm): <NEW_LINE> <INDENT> INPUT = 'INPUT' <NEW_LINE> OUTPUT = 'OUTPUT' <NEW_LINE> TABLE = 'TABLE' <NEW_LINE> PRIMARY_KEY = 'PRIMARY_KEY' <NEW_LINE> def tr(self, string): <NEW_LINE> <INDENT> return QCoreApplication.translate('Processing', string) <NEW_LINE> <DEDENT> def createInstance(self): <NEW_LINE> <INDENT> return FindOverlapInOneLayer() <NEW_LINE> <DEDENT> def name(self): <NEW_LINE> <INDENT> return 'findoverlapinonelayer' <NEW_LINE> <DEDENT> def displayName(self): <NEW_LINE> <INDENT> return self.tr('Find Overlap In One Layer') <NEW_LINE> <DEDENT> def group(self): <NEW_LINE> <INDENT> return self.tr('Topology Scripts') <NEW_LINE> <DEDENT> def groupId(self): <NEW_LINE> <INDENT> return 'topologyscripts' <NEW_LINE> <DEDENT> def shortHelpString(self): <NEW_LINE> <INDENT> return self.tr("Find overlap of distinct polygons in one layer. It works for layers in sql databases, like postgis and geopackage, " "with the geometry field named geom. \n" "The Input layer is one layer with the connection to the database. The Table parameter is the table name. For schema-based databases, " " it must be qualified by the schema, e.g., foo.test." ) <NEW_LINE> <DEDENT> def initAlgorithm(self, config=None): <NEW_LINE> <INDENT> self.addParameter( QgsProcessingParameterFeatureSource( self.INPUT, self.tr('Input layer (connection)'), [QgsProcessing.TypeVectorPolygon] ) ) <NEW_LINE> self.addParameter( QgsProcessingParameterFeatureSink( self.OUTPUT, self.tr('Output layer') ) ) <NEW_LINE> self.addParameter(QgsProcessingParameterString(self.TABLE, self.tr('Table'), defaultValue='')) <NEW_LINE> self.addParameter(QgsProcessingParameterString(self.PRIMARY_KEY, self.tr('Primary Key'), defaultValue='id')) <NEW_LINE> <DEDENT> def processAlgorithm(self, parameters, context, feedback): <NEW_LINE> <INDENT> sql = ('SELECT geom FROM (SELECT (ST_Dump(ST_Intersection(T1.geom, T2.geom))).geom FROM ' f'{parameters[self.TABLE]} AS T1 JOIN {parameters[self.TABLE]} AS T2 ' 'ON (ST_Intersects(T1.geom, T2.geom) AND NOT ST_Touches(T1.geom, T2.geom)) ' f'AND T1.{parameters[self.PRIMARY_KEY]} > T2.{parameters[self.PRIMARY_KEY]}) AS sobreposicao ' 'WHERE ST_Dimension(geom) = 2 AND ST_Area(geom) > 0.0000001') <NEW_LINE> feedback.pushInfo(sql) <NEW_LINE> find_pseudo = processing.run("gdal:executesql", {'INPUT': parameters['INPUT'], 'SQL':sql, 'OUTPUT': parameters['OUTPUT']}, context=context, feedback=feedback, is_child_algorithm=True) <NEW_LINE> return {self.OUTPUT: find_pseudo['OUTPUT']}
This is an example algorithm that takes a vector layer and creates a new identical one. It is meant to be used as an example of how to create your own algorithms and explain methods and variables used to do it. An algorithm like this will be available in all elements, and there is not need for additional work. All Processing algorithms should extend the QgsProcessingAlgorithm class.
62599035711fe17d825e1538
class BitSet(object): <NEW_LINE> <INDENT> __slots__ = ('capacity', 'integers') <NEW_LINE> def __init__(self, capacity): <NEW_LINE> <INDENT> true_capacity = math.ceil(capacity / 32) <NEW_LINE> self.capacity = capacity <NEW_LINE> self.integers = [0] * true_capacity <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self.capacity <NEW_LINE> <DEDENT> def get(self, index): <NEW_LINE> <INDENT> if index >= self.capacity: <NEW_LINE> <INDENT> raise IndexError <NEW_LINE> <DEDENT> byte = index >> 5 <NEW_LINE> pos = index & MODULO <NEW_LINE> return (self.integers[byte] >> pos) & 1 <NEW_LINE> <DEDENT> def has(self, index): <NEW_LINE> <INDENT> return self.get(index) == 1 <NEW_LINE> <DEDENT> def test(self, index): <NEW_LINE> <INDENT> return self.has(index) <NEW_LINE> <DEDENT> def set(self, index, value=1): <NEW_LINE> <INDENT> if index >= self.capacity: <NEW_LINE> <INDENT> raise IndexError <NEW_LINE> <DEDENT> byte = index >> 5 <NEW_LINE> pos = index & MODULO <NEW_LINE> if not value: <NEW_LINE> <INDENT> self.integers[byte] &= ~(1 << pos) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.integers[byte] |= (1 << pos) <NEW_LINE> <DEDENT> <DEDENT> def update(self, iterable): <NEW_LINE> <INDENT> for index in iterable: <NEW_LINE> <INDENT> self.set(index) <NEW_LINE> <DEDENT> <DEDENT> def reset(self, index): <NEW_LINE> <INDENT> if index >= self.capacity: <NEW_LINE> <INDENT> raise IndexError <NEW_LINE> <DEDENT> byte = index >> 5 <NEW_LINE> pos = index & MODULO <NEW_LINE> self.integers[byte] &= ~(1 << pos) <NEW_LINE> <DEDENT> def add(self, index): <NEW_LINE> <INDENT> return self.set(index) <NEW_LINE> <DEDENT> def delete(self, index): <NEW_LINE> <INDENT> return self.reset(index) <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> return self.get(index) <NEW_LINE> <DEDENT> def __contains__(self, index): <NEW_LINE> <INDENT> return self.has(index) <NEW_LINE> <DEDENT> def __setitem__(self, index, value): <NEW_LINE> <INDENT> return self.set(index, value) <NEW_LINE> <DEDENT> def __delitem__(self, index): <NEW_LINE> <INDENT> return self.reset(index) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<%s capacity=%i>' % (self.__class__.__name__, self.capacity)
The BitSet class. Args: capacity (number): Capacity of the bitset.
62599035a8ecb03325872357
@register_cmd("echo") <NEW_LINE> class Echo(BaseCommand): <NEW_LINE> <INDENT> def __init__(self, args=[]): <NEW_LINE> <INDENT> super(Echo, self).__init__() <NEW_LINE> self.args = args <NEW_LINE> <DEDENT> def call(self,*args,**kwargs): <NEW_LINE> <INDENT> input_generator = self.get_input_generator() <NEW_LINE> def output_generator(): <NEW_LINE> <INDENT> for args in self.args: <NEW_LINE> <INDENT> yield TreeNode(args.encode("utf-8")) <NEW_LINE> <DEDENT> for node in input_generator: <NEW_LINE> <INDENT> line = node.data <NEW_LINE> yield TreeNode(line) <NEW_LINE> <DEDENT> <DEDENT> return output_generator
Echoes anything from the command line arguments as well as input from the previous command.
6259903566673b3332c3152d
class IwatchedVariablesBox(Interface): <NEW_LINE> <INDENT> pass
This view will allow the user to enter custom variables to be watched through the execution of the debugger.
6259903594891a1f408b9f96
class SpeechServiceStub(object): <NEW_LINE> <INDENT> def __init__(self, channel): <NEW_LINE> <INDENT> self.ListenSpeechEvent = channel.unary_stream( '/speechService.SpeechService/ListenSpeechEvent', request_serializer=speech__pb2.ListenSpeechEventRequest.SerializeToString, response_deserializer=speech__pb2.ListenSpeechEventResponse.FromString, ) <NEW_LINE> self.TextToSpeech = channel.unary_unary( '/speechService.SpeechService/TextToSpeech', request_serializer=speech__pb2.TextToSpeechRequest.SerializeToString, response_deserializer=speech__pb2.TextToSpeechResponse.FromString, ) <NEW_LINE> self.SpeechStop = channel.unary_unary( '/speechService.SpeechService/SpeechStop', request_serializer=speech__pb2.SpeechStopRequest.SerializeToString, response_deserializer=speech__pb2.SpeechStopResponse.FromString, ) <NEW_LINE> self.WakeUp = channel.unary_unary( '/speechService.SpeechService/WakeUp', request_serializer=speech__pb2.WakeUpRequest.SerializeToString, response_deserializer=speech__pb2.WakeUpResponse.FromString, ) <NEW_LINE> self.Hibernate = channel.unary_unary( '/speechService.SpeechService/Hibernate', request_serializer=speech__pb2.HibernateRequest.SerializeToString, response_deserializer=speech__pb2.HibernateResponse.FromString, ) <NEW_LINE> self.SetVoiceVolume = channel.unary_unary( '/speechService.SpeechService/SetVoiceVolume', request_serializer=speech__pb2.SetVoiceVolumeRequest.SerializeToString, response_deserializer=speech__pb2.SetVoiceVolumeResponse.FromString, ) <NEW_LINE> self.GetVoiceVolume = channel.unary_unary( '/speechService.SpeechService/GetVoiceVolume', request_serializer=speech__pb2.GetVoiceVolumeRequest.SerializeToString, response_deserializer=speech__pb2.GetVoiceVolumeResponse.FromString, ) <NEW_LINE> self.SetParams = channel.unary_unary( '/speechService.SpeechService/SetParams', request_serializer=speech__pb2.SetParamsRequest.SerializeToString, response_deserializer=speech__pb2.SetParamsResponse.FromString, )
speechService.SpeechService 语音服务 开发管理平台功能参考: http://10.10.10.2/speech
625990358c3a8732951f7692
class BitmapShape(RectangleShape): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> RectangleShape.__init__(self, 100, 50) <NEW_LINE> self._filename = "" <NEW_LINE> <DEDENT> def OnDraw(self, dc): <NEW_LINE> <INDENT> if not self._bitmap.IsOk(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> x = self._xpos - self._bitmap.GetWidth() / 2.0 <NEW_LINE> y = self._ypos - self._bitmap.GetHeight() / 2.0 <NEW_LINE> dc.DrawBitmap(self._bitmap, x, y, True) <NEW_LINE> <DEDENT> def SetSize(self, w, h, recursive = True): <NEW_LINE> <INDENT> if self._bitmap.IsOk(): <NEW_LINE> <INDENT> w = self._bitmap.GetWidth() <NEW_LINE> h = self._bitmap.GetHeight() <NEW_LINE> <DEDENT> self.SetAttachmentSize(w, h) <NEW_LINE> self._width = w <NEW_LINE> self._height = h <NEW_LINE> self.SetDefaultRegionSize() <NEW_LINE> <DEDENT> def GetBitmap(self): <NEW_LINE> <INDENT> return self._bitmap <NEW_LINE> <DEDENT> def SetBitmap(self, bitmap): <NEW_LINE> <INDENT> self._bitmap = bitmap <NEW_LINE> if self._bitmap.IsOk(): <NEW_LINE> <INDENT> self.SetSize(self._bitmap.GetWidth(), self._bitmap.GetHeight()) <NEW_LINE> <DEDENT> <DEDENT> def SetFilename(self, f): <NEW_LINE> <INDENT> self._filename = f <NEW_LINE> <DEDENT> def GetFilename(self): <NEW_LINE> <INDENT> return self._filename
The :class:`BitmapShape` class draws a bitmap (non-resizable).
6259903526238365f5fadc8d
class MarkupPreview(View): <NEW_LINE> <INDENT> http_method_names = ['post'] <NEW_LINE> def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> markup_type = self.request.POST.get('markup_type') <NEW_LINE> if not markup_type: <NEW_LINE> <INDENT> return HttpResponse("", content_type='text/html') <NEW_LINE> <DEDENT> markup = markup_pool.get_markup(markup_type) <NEW_LINE> text = self.request.POST.get('text', "") <NEW_LINE> converted = markup(text, request=request) <NEW_LINE> return HttpResponse(converted, content_type='text/html')
Renders markup content to HTML for preview purposes.
6259903573bcbd0ca4bcb3c1
class ScriptProblemTypeTestNonRandomized(ScriptProblemTypeBase, NonRandomizedProblemTypeTestMixin): <NEW_LINE> <INDENT> shard = 8 <NEW_LINE> def get_problem(self): <NEW_LINE> <INDENT> return XBlockFixtureDesc( 'problem', self.problem_name, data=self.factory.build_xml(**self.factory_kwargs), metadata={'rerandomize': 'never', 'show_reset_button': True} )
Tests for non-randomized Script problem
625990356e29344779b0178b
class ThreadLocals(object): <NEW_LINE> <INDENT> def process_request(self, request): <NEW_LINE> <INDENT> _thread_locals.user = getattr(request, 'user', None) <NEW_LINE> _thread_locals.logs = {} <NEW_LINE> _thread_locals.entrys = {}
Middleware that gets various objects from the request object and saves them in thread local storage.
6259903576d4e153a661db0e
class OpenLatchImpl(AbstractCommandImpl[OpenLatchParams, OpenLatchResult]): <NEW_LINE> <INDENT> def __init__(self, **kwargs: object) -> None: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> async def execute(self, params: OpenLatchParams) -> OpenLatchResult: <NEW_LINE> <INDENT> raise NotImplementedError("Heater-Shaker open latch not yet implemented.")
Execution implementation of a Heater-Shaker's open latch command.
62599035b57a9660fecd2bb6
class PyErrorLog(_BaseErrorLog): <NEW_LINE> <INDENT> def copy(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def log(self, log_entry, message, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def receive(self, log_entry): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self, logger_name=None, logger=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __new__(*args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> level_map = property(lambda self: object(), lambda self, v: None, lambda self: None) <NEW_LINE> __pyx_vtable__ = None
PyErrorLog(self, logger_name=None, logger=None) A global error log that connects to the Python stdlib logging package. The constructor accepts an optional logger name or a readily instantiated logger instance. If you want to change the mapping between libxml2's ErrorLevels and Python logging levels, you can modify the level_map dictionary from a subclass. The default mapping is:: ErrorLevels.WARNING = logging.WARNING ErrorLevels.ERROR = logging.ERROR ErrorLevels.FATAL = logging.CRITICAL You can also override the method ``receive()`` that takes a LogEntry object and calls ``self.log(log_entry, format_string, arg1, arg2, ...)`` with appropriate data.
625990354e696a045264e6bf
class OracleTypeSource(OraclePLSQLSource): <NEW_LINE> <INDENT> pass
Source code of type
62599035d10714528d69ef29
class InValidator(BaseValidator): <NEW_LINE> <INDENT> code = 'in_validator' <NEW_LINE> message = _('The selected {key} is invalid.') <NEW_LINE> def __init__(self, *choices): <NEW_LINE> <INDENT> super(InValidator, self).__init__() <NEW_LINE> self.choices = {choice.lower() for choice in choices} <NEW_LINE> <DEDENT> def clean(self, value): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> return str(value).lower() <NEW_LINE> <DEDENT> def is_valid(self, value, params): <NEW_LINE> <INDENT> return value in self.choices
Check if the value is in the choices list.
62599035711fe17d825e1539
class ErrorDetails(BaseModel): <NEW_LINE> <INDENT> model_types = { 'request_id': 'str', '_date': 'datetime' } <NEW_LINE> attribute_map = { 'request_id': 'requestId', '_date': 'date' } <NEW_LINE> def __init__(self, request_id=None, _date=None): <NEW_LINE> <INDENT> self._request_id = None <NEW_LINE> self.__date = None <NEW_LINE> if request_id is not None: <NEW_LINE> <INDENT> self.request_id = request_id <NEW_LINE> <DEDENT> self._date = _date <NEW_LINE> <DEDENT> @property <NEW_LINE> def request_id(self): <NEW_LINE> <INDENT> return self._request_id <NEW_LINE> <DEDENT> @request_id.setter <NEW_LINE> def request_id(self, request_id): <NEW_LINE> <INDENT> self._request_id = request_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def _date(self): <NEW_LINE> <INDENT> return self.__date <NEW_LINE> <DEDENT> @_date.setter <NEW_LINE> def _date(self, _date): <NEW_LINE> <INDENT> if _date is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `_date`, must not be `None`") <NEW_LINE> <DEDENT> self.__date = _date
Attributes: model_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition.
6259903594891a1f408b9f97
class InlineOffset(Block): <NEW_LINE> <INDENT> def __init__(self, joints, name='offset', controlShape=Ctrl.ARROWS4, **kwargs): <NEW_LINE> <INDENT> super(InlineOffset,self).__init__(name=name,controlShape=controlShape, **kwargs) <NEW_LINE> if type(joints) != list: <NEW_LINE> <INDENT> joints = [joints] <NEW_LINE> <DEDENT> self.joints = joints <NEW_LINE> self.build() <NEW_LINE> <DEDENT> def build(self): <NEW_LINE> <INDENT> for joint in self.joints: <NEW_LINE> <INDENT> joint = pm.PyNode(joint) <NEW_LINE> parent = joint.getParent() <NEW_LINE> ctrl = Ctrl(xform = joint, name = joint.name() + '_' + d.CTRL, shape = self.controlShape, radius = self.controlRadius, normal = [0,1,0], color = self.controlColor, group = False).ctrl <NEW_LINE> ctrl.setParent(parent) <NEW_LINE> pm.makeIdentity(ctrl, apply=True) <NEW_LINE> joint.setParent(ctrl) <NEW_LINE> self.controls.append(ctrl)
Inserts control shapes into the scene hierarchy above the given jnts.
62599035be8e80087fbc01ba
class InlineResponse20032Payload(object): <NEW_LINE> <INDENT> swagger_types = { 'colour_code': 'ColourCode', 'percent_of_total': 'float', 'minutes': 'float' } <NEW_LINE> attribute_map = { 'colour_code': 'colour_code', 'percent_of_total': 'percent_of_total', 'minutes': 'minutes' } <NEW_LINE> def __init__(self, colour_code=None, percent_of_total=None, minutes=None): <NEW_LINE> <INDENT> self._colour_code = None <NEW_LINE> self._percent_of_total = None <NEW_LINE> self._minutes = None <NEW_LINE> self.discriminator = None <NEW_LINE> if colour_code is not None: <NEW_LINE> <INDENT> self.colour_code = colour_code <NEW_LINE> <DEDENT> if percent_of_total is not None: <NEW_LINE> <INDENT> self.percent_of_total = percent_of_total <NEW_LINE> <DEDENT> if minutes is not None: <NEW_LINE> <INDENT> self.minutes = minutes <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def colour_code(self): <NEW_LINE> <INDENT> return self._colour_code <NEW_LINE> <DEDENT> @colour_code.setter <NEW_LINE> def colour_code(self, colour_code): <NEW_LINE> <INDENT> self._colour_code = colour_code <NEW_LINE> <DEDENT> @property <NEW_LINE> def percent_of_total(self): <NEW_LINE> <INDENT> return self._percent_of_total <NEW_LINE> <DEDENT> @percent_of_total.setter <NEW_LINE> def percent_of_total(self, percent_of_total): <NEW_LINE> <INDENT> self._percent_of_total = percent_of_total <NEW_LINE> <DEDENT> @property <NEW_LINE> def minutes(self): <NEW_LINE> <INDENT> return self._minutes <NEW_LINE> <DEDENT> @minutes.setter <NEW_LINE> def minutes(self, minutes): <NEW_LINE> <INDENT> self._minutes = minutes <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(InlineResponse20032Payload, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, InlineResponse20032Payload): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62599035287bf620b6272d24
class IPv4If(_IpBase): <NEW_LINE> <INDENT> def __init__(self, logger): <NEW_LINE> <INDENT> version = IpVersion.kIPv4 <NEW_LINE> _IpBase.__init__(self, logger, version)
An IPv4 network object.
62599035d164cc61758220af
class FunctionCacheKey(trace.TraceType): <NEW_LINE> <INDENT> def __init__(self, function_signature: trace.TraceType, call_context: ExecutionContext): <NEW_LINE> <INDENT> self.function_signature = function_signature <NEW_LINE> self.call_context = call_context <NEW_LINE> <DEDENT> def is_subtype_of(self, other: trace.TraceType) -> bool: <NEW_LINE> <INDENT> if not isinstance(other, FunctionCacheKey): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.call_context != other.call_context: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.function_signature.is_subtype_of(other.function_signature) <NEW_LINE> <DEDENT> def most_specific_common_supertype( self, others: Sequence[trace.TraceType]) -> Optional["FunctionCacheKey"]: <NEW_LINE> <INDENT> if not all( isinstance(other, FunctionCacheKey) and self.call_context == other.call_context for other in others): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> common = self.function_signature.most_specific_common_supertype( [other.function_signature for other in others]) <NEW_LINE> if common is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return FunctionCacheKey(common, self.call_context) <NEW_LINE> <DEDENT> def __hash__(self) -> int: <NEW_LINE> <INDENT> return hash((self.call_context, self.function_signature)) <NEW_LINE> <DEDENT> def __eq__(self, other) -> bool: <NEW_LINE> <INDENT> if not isinstance(other, trace.TraceType): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> if not isinstance(other, FunctionCacheKey): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return (self.call_context == other.call_context and self.function_signature == other.function_signature) <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> return ( f"{type(self).__name__}(function_signature={repr(self.function_signature)}," f" call_context={repr(self.call_context)})")
The unique key associated with a concrete function. Attributes: function_signature: A TraceType corresponding to the function arguments. call_context: The ExecutionContext for when the function_signature was generated.
625990353eb6a72ae038b7a3
class BlockchainDB(JSBASE): <NEW_LINE> <INDENT> def __init__(self, name, db): <NEW_LINE> <INDENT> JSBASE.__init__(self) <NEW_LINE> self.name <NEW_LINE> self.db
a blockchain modeled on a DB
62599035d99f1b3c44d067df
class muglue(glue): <NEW_LINE> <INDENT> units = ['m']
Class used for muglue values
6259903576d4e153a661db0f
class _FinalStateViaOption(str, Enum): <NEW_LINE> <INDENT> AZURE_ASYNC_OPERATION_FINAL_STATE = "azure-async-operation" <NEW_LINE> LOCATION_FINAL_STATE = "location" <NEW_LINE> OPERATION_LOCATION_FINAL_STATE = "operation-location"
Possible final-state-via options.
62599035d6c5a102081e3261
class SetupBasicTests(unittest.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> cls.console = logging.StreamHandler() <NEW_LINE> cls.console.setLevel(logging.INFO) <NEW_LINE> logger.addHandler(cls.console) <NEW_LINE> logger.info('Running unit tests for main routine ..') <NEW_LINE> cls.json_chart1 = os.path.join(SRCPATH, 'tests', 'inputs', 'chart_test1.json') <NEW_LINE> cls.json_chart2 = os.path.join(SRCPATH, 'tests', 'inputs', 'chart_test2.json') <NEW_LINE> cls.json_chart3 = os.path.join(SRCPATH, 'tests', 'inputs', 'chart_test3.json') <NEW_LINE> <DEDENT> def test_solve(self): <NEW_LINE> <INDENT> mock_args = MagicMock() <NEW_LINE> mock_args.chart = SetupBasicTests.json_chart1 <NEW_LINE> self.assertEqual(escape.solve(mock_args), [1,1,1]) <NEW_LINE> mock_args.chart = SetupBasicTests.json_chart2 <NEW_LINE> self.assertEqual(escape.solve(mock_args), [0,1,1,1,1]) <NEW_LINE> mock_args.chart = SetupBasicTests.json_chart3 <NEW_LINE> self.assertEqual(escape.solve(mock_args), []) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def tearDownClass(cls): <NEW_LINE> <INDENT> logger.removeHandler(cls.console)
Sets up unit tests for basic helper routines inside lib
62599035ac7a0e7691f73624
class HermitePoly: <NEW_LINE> <INDENT> def __init__(self, N, mu=0, sig=1): <NEW_LINE> <INDENT> self.mu = mu <NEW_LINE> self.sig = sig <NEW_LINE> self.N = N <NEW_LINE> self.C = np.zeros((N, N)) <NEW_LINE> h_coefs(self.C, N) <NEW_LINE> h_normalize(self.C, N) <NEW_LINE> <DEDENT> def __call__(self, i, x): <NEW_LINE> <INDENT> x = (x - self.mu) / self.sig <NEW_LINE> if np.isscalar(x): <NEW_LINE> <INDENT> return h_eval(self.C, i, x) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x = x.flatten() <NEW_LINE> out_vec = np.empty(len(x)) <NEW_LINE> h_vec_eval(self.C, i, x, out_vec) <NEW_LINE> return out_vec <NEW_LINE> <DEDENT> <DEDENT> def eval_all(self, x): <NEW_LINE> <INDENT> x = (x - self.mu) / self.sig <NEW_LINE> if np.isscalar(x): <NEW_LINE> <INDENT> out_vec = np.empty(self.N) <NEW_LINE> h_eval_over_idx(self.C, self.N, x, out_vec) <NEW_LINE> return out_vec <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x = x.flatten() <NEW_LINE> out_mat = np.empty((self.N, len(x))) <NEW_LINE> h_vec_idx_eval(self.C, self.N, x, out_mat) <NEW_LINE> return out_mat <NEW_LINE> <DEDENT> <DEDENT> def inner_prod(self, f, i, quad_size=40): <NEW_LINE> <INDENT> integrand = lambda x: f(x) * self.__call__(i, x) * norm.pdf(x, loc=self.mu, scale=self.sig) <NEW_LINE> std_devs = 5 <NEW_LINE> a = self.mu - self.sig * std_devs <NEW_LINE> b = self.mu + self.sig * std_devs <NEW_LINE> return fixed_quad(integrand, a, b, n=quad_size)[0]
The purpose of this class is to provide fast evaluations of the form h_i(x) where h_i is the i-th normalized probabilist's Hermite polynomial. The evaluations are vectorized. The class also provides a function to evaluate the inner product \int f(x) h_i(x) \pi(x) dx where f is a supplied function and \pi is the standard normal distribution.
6259903530c21e258be99949
class NotInterestedMessage(BasePeerMessage): <NEW_LINE> <INDENT> pass
Format: <len=0001><id=3>
625990358a349b6b4368737c
class HelloWorld: <NEW_LINE> <INDENT> def index(self): <NEW_LINE> <INDENT> return "Hello world!" <NEW_LINE> <DEDENT> index.exposed = True
Sample request handler class.
62599035507cdc57c63a5ed7
class KitchenDot(pydot.Dot): <NEW_LINE> <INDENT> def __init__(self, *argsl, **argsd): <NEW_LINE> <INDENT> super(KitchenDot, self).__init__(*argsl, **argsd) <NEW_LINE> self.p = None <NEW_LINE> <DEDENT> def create(self, prog=None, format='ps'): <NEW_LINE> <INDENT> if prog is None: <NEW_LINE> <INDENT> prog = self.prog <NEW_LINE> <DEDENT> if isinstance(prog, (list, tuple)): <NEW_LINE> <INDENT> prog, args = prog[0], prog[1:] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> args = [] <NEW_LINE> <DEDENT> if self.progs is None: <NEW_LINE> <INDENT> self.progs = pydot.find_graphviz() <NEW_LINE> if self.progs is None: <NEW_LINE> <INDENT> raise pydot.InvocationException( 'GraphViz\'s executables not found') <NEW_LINE> <DEDENT> <DEDENT> if not prog in self.progs: <NEW_LINE> <INDENT> raise pydot.InvocationException( 'GraphViz\'s executable "{0}" not found'.format(prog)) <NEW_LINE> <DEDENT> if (not os.path.exists(self.progs[prog]) or not os.path.isfile(self.progs[prog])): <NEW_LINE> <INDENT> raise pydot.InvocationException( 'GraphViz\'s executable "{0}" is not a file ' 'or doesn\'t exist'.format(self.progs[prog])) <NEW_LINE> <DEDENT> tmp_fd, tmp_name = tempfile.mkstemp() <NEW_LINE> os.close(tmp_fd) <NEW_LINE> self.write(tmp_name) <NEW_LINE> tmp_dir = os.path.dirname(tmp_name) <NEW_LINE> for img in self.shape_files: <NEW_LINE> <INDENT> f = file(img, 'rb') <NEW_LINE> f_data = f.read() <NEW_LINE> f.close() <NEW_LINE> f = file(os.path.join(tmp_dir, os.path.basename(img)), 'wb') <NEW_LINE> f.write(f_data) <NEW_LINE> f.close() <NEW_LINE> <DEDENT> cmdline = [self.progs[prog], '-T' + format, tmp_name] + args <NEW_LINE> self.p = subprocess.Popen( cmdline, cwd=tmp_dir, stderr=subprocess.PIPE, stdout=subprocess.PIPE ) <NEW_LINE> stderr = self.p.stderr <NEW_LINE> stdout = self.p.stdout <NEW_LINE> stdout_output = list() <NEW_LINE> while True: <NEW_LINE> <INDENT> data = stdout.read() <NEW_LINE> if not data: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> stdout_output.append(data) <NEW_LINE> <DEDENT> stdout.close() <NEW_LINE> stdout_output = ''.join(stdout_output) <NEW_LINE> if not stderr.closed: <NEW_LINE> <INDENT> stderr_output = list() <NEW_LINE> while True: <NEW_LINE> <INDENT> data = stderr.read() <NEW_LINE> if not data: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> stderr_output.append(data) <NEW_LINE> <DEDENT> stderr.close() <NEW_LINE> if stderr_output: <NEW_LINE> <INDENT> stderr_output = ''.join(stderr_output) <NEW_LINE> <DEDENT> <DEDENT> status = self.p.wait() <NEW_LINE> if status != 0: <NEW_LINE> <INDENT> raise pydot.InvocationException( 'Program terminated with status: {0}. ' 'stderr follows: {1}'.format(status, stderr_output)) <NEW_LINE> <DEDENT> elif stderr_output: <NEW_LINE> <INDENT> log.error(stderr_output) <NEW_LINE> <DEDENT> for img in self.shape_files: <NEW_LINE> <INDENT> os.unlink(os.path.join(tmp_dir, os.path.basename(img))) <NEW_LINE> <DEDENT> os.unlink(tmp_name) <NEW_LINE> return stdout_output
Inherits from the pydot library Dot class, and makes the subprocess as an attribute for being killed from outside
6259903521bff66bcd723da3
class AbstractProvider: <NEW_LINE> <INDENT> __type__ = None <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.env_resolver = EnvVarResolver() <NEW_LINE> self.shell_exec = None <NEW_LINE> self.git_exec = None <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def deploy_by_git_push(self, app, env): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def deploy_by_image(self, app, env): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def app_url(self, resource): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def deploy(self, app, env): <NEW_LINE> <INDENT> assert self.shell_exec <NEW_LINE> print("...Beginning deploy on %s" % env.type) <NEW_LINE> print("Environment name: %s" % env.name) <NEW_LINE> print("Environment deploy host: %s" % env.deploy_host) <NEW_LINE> print("Environment app url file: %s" % env.app_deployment_file_url) <NEW_LINE> print("App name: %s" % app.name) <NEW_LINE> print("App deploy name: %s" % app.deploy_name) <NEW_LINE> print("App group: %s" % app.group) <NEW_LINE> print("App image: %s" % app.image) <NEW_LINE> print("App repository: %s" % app.repository) <NEW_LINE> app.env_vars = self._resolve_env_vars(app.env_vars) <NEW_LINE> if app.image: <NEW_LINE> <INDENT> self.deploy_by_image(app, env) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.deploy_by_git_push(app, env) <NEW_LINE> <DEDENT> <DEDENT> @abstractmethod <NEW_LINE> def undeploy(self, app, env): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _resolve_env_vars(self, env_vars): <NEW_LINE> <INDENT> return self.env_resolver.resolve_vars(env_vars, self, services) <NEW_LINE> <DEDENT> def set_shell_exec(self, shell_exec): <NEW_LINE> <INDENT> self.shell_exec = shell_exec <NEW_LINE> <DEDENT> def set_git_exec(self, git_exec): <NEW_LINE> <INDENT> self.git_exec = git_exec <NEW_LINE> <DEDENT> def get_image_tag(self): <NEW_LINE> <INDENT> assert self.app.image, "can only be used if app has image" <NEW_LINE> tokens = self.app.image.split(":") <NEW_LINE> assert len(tokens) == 1 or len(tokens) == 2, "url should have only one ':' or not have at all" <NEW_LINE> return tokens[1] if ":" in self.app.image else "latest" <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def prepare_env_vars(env_vars): <NEW_LINE> <INDENT> env_vars_as_str = ' '.join('{}="{}"'.format(k, str(v).replace('\"', '\\"')) for k, v in sorted(env_vars.items())) <NEW_LINE> return env_vars_as_str <NEW_LINE> <DEDENT> def get_branch_name_and_repository(self, repository): <NEW_LINE> <INDENT> repo = repository.split(self.DELIMITER_BRANCH_NAME) <NEW_LINE> repository = repo[0] <NEW_LINE> branch_name = repo[-1] if len(repo) > 1 else None <NEW_LINE> return repository, branch_name
Classe abstrata que define o que um provider precisa ter implementado para possibilitar o deploy de aplicações.
6259903594891a1f408b9f98
class Votes(models.Model): <NEW_LINE> <INDENT> project = models.ForeignKey('app_projects.Project') <NEW_LINE> user = models.ForeignKey('app_users.UserProfile')
Model for a `Vote`, a many-to-many relationship between projects (:class:`app_projects.models.Project`) and users (:class:`app_users.models.UserProfile`) :project: the project of interest :users: the users that have voted the project
62599035287bf620b6272d26
class _NeuralNetwork(NeuralNetwork): <NEW_LINE> <INDENT> def _forward(self, input_data, weights): <NEW_LINE> <INDENT> batch_size = input_data.shape[0] if input_data is not None else 1 <NEW_LINE> return np.zeros((batch_size, *self.output_shape)) <NEW_LINE> <DEDENT> def _backward(self, input_data, weights): <NEW_LINE> <INDENT> input_grad = None <NEW_LINE> batch_size = input_data.shape[0] if input_data is not None else 1 <NEW_LINE> if self.num_inputs > 0: <NEW_LINE> <INDENT> input_grad = np.zeros((batch_size, *self.output_shape, self.num_inputs)) <NEW_LINE> <DEDENT> weight_grad = None <NEW_LINE> if self.num_weights > 0: <NEW_LINE> <INDENT> weight_grad = np.zeros((batch_size, *self.output_shape, self.num_weights)) <NEW_LINE> <DEDENT> return input_grad, weight_grad
Dummy implementation to test the abstract neural network class.
62599035d6c5a102081e3263
class SysterUser(models.Model): <NEW_LINE> <INDENT> user = models.OneToOneField(User) <NEW_LINE> country = CountryField(blank=True, null=True) <NEW_LINE> blog_url = models.URLField(max_length=255, blank=True) <NEW_LINE> homepage_url = models.URLField(max_length=255, blank=True) <NEW_LINE> profile_picture = models.ImageField(upload_to='photos/', default='photos/dummy.jpeg', blank=True, null=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> firstname = self.user.first_name <NEW_LINE> lastname = self.user.last_name <NEW_LINE> if firstname and lastname: <NEW_LINE> <INDENT> return "{0} {1}".format(self.user.first_name, self.user.last_name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.user.username
Profile model to store additional information about a user
625990351d351010ab8f4c58
class GdkCursor( gobject__GObject.GObject): <NEW_LINE> <INDENT> def __init__( self, cursor_type, obj = None): <NEW_LINE> <INDENT> if obj: self._object = obj <NEW_LINE> else: <NEW_LINE> <INDENT> libgtk3.gdk_cursor_new.restype = POINTER(c_void_p) <NEW_LINE> libgtk3.gdk_cursor_new.argtypes = [GdkCursorType] <NEW_LINE> self._object = libgtk3.gdk_cursor_new(cursor_type, ) <NEW_LINE> <DEDENT> <DEDENT> """Methods""" <NEW_LINE> def get_cursor_type( self, ): <NEW_LINE> <INDENT> return libgtk3.gdk_cursor_get_cursor_type( self._object ) <NEW_LINE> <DEDENT> def ref( self, ): <NEW_LINE> <INDENT> from .gobject import GdkCursor <NEW_LINE> return GdkCursor( obj=libgtk3.gdk_cursor_ref( self._object ) or POINTER(c_void_p)()) <NEW_LINE> <DEDENT> def unref( self, ): <NEW_LINE> <INDENT> libgtk3.gdk_cursor_unref( self._object ) <NEW_LINE> <DEDENT> def get_display( self, ): <NEW_LINE> <INDENT> from .gobject import GdkDisplay <NEW_LINE> return GdkDisplay( obj=libgtk3.gdk_cursor_get_display( self._object ) or POINTER(c_void_p)()) <NEW_LINE> <DEDENT> def get_image( self, ): <NEW_LINE> <INDENT> from .gobject import GdkPixbuf <NEW_LINE> return GdkPixbuf( obj=libgtk3.gdk_cursor_get_image( self._object ) or POINTER(c_void_p)()) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def new_from_pixbuf( display, pixbuf, x, y,): <NEW_LINE> <INDENT> if display: display = display._object <NEW_LINE> else: display = POINTER(c_void_p)() <NEW_LINE> if pixbuf: pixbuf = pixbuf._object <NEW_LINE> else: pixbuf = POINTER(c_void_p)() <NEW_LINE> from .gobject import GdkCursor <NEW_LINE> return GdkCursor(None, obj= libgtk3.gdk_cursor_new_from_pixbuf(display, pixbuf, x, y, ) or POINTER(c_void_p)()) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def new_from_name( display, name,): <NEW_LINE> <INDENT> if display: display = display._object <NEW_LINE> else: display = POINTER(c_void_p)() <NEW_LINE> from .gobject import GdkCursor <NEW_LINE> return GdkCursor(None, obj= libgtk3.gdk_cursor_new_from_name(display, name, ) or POINTER(c_void_p)()) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def new_for_display( display, cursor_type,): <NEW_LINE> <INDENT> if display: display = display._object <NEW_LINE> else: display = POINTER(c_void_p)() <NEW_LINE> from .gobject import GdkCursor <NEW_LINE> return GdkCursor(None, obj= libgtk3.gdk_cursor_new_for_display(display, cursor_type, ) or POINTER(c_void_p)())
Class GdkCursor Constructors
62599035cad5886f8bdc591a
class CppPIDController(pm.CppBase, pm.Controller): <NEW_LINE> <INDENT> public_settings = OrderedDict([ ("Kp", st.Kp), ("Ti", st.Ti), ("Td", st.Td), ("dt [s]", 0.1), ("output_limits", st.limits_ctrl), ("input_state", st.input_ctrl), ("tick divider", 1), ]) <NEW_LINE> def __init__(self, settings): <NEW_LINE> <INDENT> settings.update(input_order=0) <NEW_LINE> settings.update(output_dim=1) <NEW_LINE> settings.update(input_type="system_state") <NEW_LINE> m_path = os.path.dirname(__file__) <NEW_LINE> if 'tanksystem' not in m_path: <NEW_LINE> <INDENT> m_path += '/pymoskito/examples/tanksystem/src/' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> m_path += '/src/' <NEW_LINE> <DEDENT> addLib = "add_library(pybind11 INTERFACE)\n" <NEW_LINE> addLib += "target_include_directories(pybind11 INTERFACE $(VENV)/lib/$(PYVERS)/site-packages/pybind11/include/)\n" <NEW_LINE> pm.Controller.__init__(self, settings) <NEW_LINE> pm.CppBase.__init__(self, module_path=m_path, module_name='Controller', binding_class_name="binding_Controller", ) <NEW_LINE> self.last_time = 0 <NEW_LINE> self.last_u = 0 <NEW_LINE> self.pid = self.get_class_from_module().PIDController(self._settings["Kp"], self._settings["Ti"], self._settings["Td"], self._settings["output_limits"][0], self._settings["output_limits"][1], self._settings['dt [s]']) <NEW_LINE> <DEDENT> def _control(self, time, trajectory_values=None, feedforward_values=None, input_values=None, **kwargs): <NEW_LINE> <INDENT> dt = time - self.last_time <NEW_LINE> x = np.zeros((len(self._settings["input_state"]),)) <NEW_LINE> for idx, state in enumerate(self._settings["input_state"]): <NEW_LINE> <INDENT> x[idx] = input_values[int(state)] <NEW_LINE> <DEDENT> if np.isclose(dt, self._settings['dt [s]']): <NEW_LINE> <INDENT> self.last_time = time <NEW_LINE> yd = trajectory_values <NEW_LINE> u = self.pid.compute(x, yd) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> u = self.last_u <NEW_LINE> <DEDENT> self.last_u = u <NEW_LINE> return u
PID Controller implemented in cpp with pybind11
62599035b57a9660fecd2bb9
class ButtonMappingButton(ButtonMappingKey): <NEW_LINE> <INDENT> def __init__(self, name, id_num, joy_name): <NEW_LINE> <INDENT> super(ButtonMappingButton, self).__init__(name, id_num) <NEW_LINE> self.joy_device_name = joy_name <NEW_LINE> self.map_type = con.BUTTON_MAP_BUTTON <NEW_LINE> <DEDENT> def get_json(self): <NEW_LINE> <INDENT> d = super(ButtonMappingButton, self).get_json() <NEW_LINE> d[con.JOY_DEVICE] = self.joy_device_name <NEW_LINE> return d <NEW_LINE> <DEDENT> def is_pressed(self): <NEW_LINE> <INDENT> return self.get_device().get_button(self.id_num)
This Mapping subclass corresponds to a button on an associated USB joystick device and is used to yield input for the controllers.Button object
6259903530c21e258be9994a
class RPCCoverage(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.dir = tempfile.mkdtemp(prefix="coverage") <NEW_LINE> self.flag = '--coveragedir=%s' % self.dir <NEW_LINE> <DEDENT> def report_rpc_coverage(self): <NEW_LINE> <INDENT> uncovered = self._get_uncovered_rpc_commands() <NEW_LINE> if uncovered: <NEW_LINE> <INDENT> print("Uncovered RPC commands:") <NEW_LINE> print("".join((" - %s\n" % i) for i in sorted(uncovered))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("All RPC commands covered.") <NEW_LINE> <DEDENT> <DEDENT> def cleanup(self): <NEW_LINE> <INDENT> return shutil.rmtree(self.dir) <NEW_LINE> <DEDENT> def _get_uncovered_rpc_commands(self): <NEW_LINE> <INDENT> REFERENCE_FILENAME = 'rpc_interface.txt' <NEW_LINE> COVERAGE_FILE_PREFIX = 'coverage.' <NEW_LINE> coverage_ref_filename = os.path.join(self.dir, REFERENCE_FILENAME) <NEW_LINE> coverage_filenames = set() <NEW_LINE> all_cmds = set() <NEW_LINE> covered_cmds = set() <NEW_LINE> if not os.path.isfile(coverage_ref_filename): <NEW_LINE> <INDENT> raise RuntimeError("No coverage reference found") <NEW_LINE> <DEDENT> with open(coverage_ref_filename, 'r') as f: <NEW_LINE> <INDENT> all_cmds.update([i.strip() for i in f.readlines()]) <NEW_LINE> <DEDENT> for root, dirs, files in os.walk(self.dir): <NEW_LINE> <INDENT> for filename in files: <NEW_LINE> <INDENT> if filename.startswith(COVERAGE_FILE_PREFIX): <NEW_LINE> <INDENT> coverage_filenames.add(os.path.join(root, filename)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for filename in coverage_filenames: <NEW_LINE> <INDENT> with open(filename, 'r') as f: <NEW_LINE> <INDENT> covered_cmds.update([i.strip() for i in f.readlines()]) <NEW_LINE> <DEDENT> <DEDENT> return all_cmds - covered_cmds
Coverage reporting utilities for pull-tester. Coverage calculation works by having each test script subprocess write coverage files into a particular directory. These files contain the RPC commands invoked during testing, as well as a complete listing of RPC commands per `aethercoin-cli help` (`rpc_interface.txt`). After all tests complete, the commands run are combined and diff'd against the complete list to calculate uncovered RPC commands. See also: qa/rpc-tests/test_framework/coverage.py
62599035b830903b9686ed18
class XnatProject(Base): <NEW_LINE> <INDENT> def __init__(self, rest_client, project_id, project_name, secondary_id, description): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.rest_client = rest_client <NEW_LINE> self.project_id = project_id <NEW_LINE> self.project_name = project_name <NEW_LINE> self.secondary_id = secondary_id <NEW_LINE> self.description = description <NEW_LINE> self.subject_map = None <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def create_from_server_object(rest_client, server_object): <NEW_LINE> <INDENT> project_name = Utilities.get_optional_dict_value(server_object, 'name') <NEW_LINE> project_id = Utilities.get_optional_dict_value(server_object, 'id') <NEW_LINE> secondary_id = Utilities.get_optional_dict_value(server_object, 'secondary_id') <NEW_LINE> description = Utilities.get_optional_dict_value(server_object, 'description') <NEW_LINE> return XnatProject(rest_client, project_id, project_name, secondary_id, description) <NEW_LINE> <DEDENT> def get_subject_map(self): <NEW_LINE> <INDENT> self._populate_subject_map_if_necessary() <NEW_LINE> return self.subject_map <NEW_LINE> <DEDENT> def get_subject(self, patient_id): <NEW_LINE> <INDENT> if patient_id is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> self._populate_subject_map_if_necessary() <NEW_LINE> if not (patient_id in self.subject_map): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.subject_map[patient_id] <NEW_LINE> <DEDENT> <DEDENT> def get_resource_for_series_uid(self, patient_id, series_uid): <NEW_LINE> <INDENT> subject = self.get_subject(patient_id) <NEW_LINE> if subject is not None: <NEW_LINE> <INDENT> scan = subject.find_scan(series_uid) <NEW_LINE> if scan is not None: <NEW_LINE> <INDENT> resources = scan.get_resources() <NEW_LINE> if len(resources) > 0: <NEW_LINE> <INDENT> resource = resources[0] <NEW_LINE> return resource <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> resource = None <NEW_LINE> return resource <NEW_LINE> <DEDENT> def _populate_subject_map_if_necessary(self): <NEW_LINE> <INDENT> if self.subject_map is None: <NEW_LINE> <INDENT> self.subject_map = self.rest_client.get_subject_map(self.project_id)
Describes an XNAT project
625990358c3a8732951f7697
class XmlProcessingError(Exception): <NEW_LINE> <INDENT> _filename = None <NEW_LINE> _line = None <NEW_LINE> _col = None <NEW_LINE> def __init__(self, msg, node=None): <NEW_LINE> <INDENT> super(XmlProcessingError, self).__init__() <NEW_LINE> self._msg = msg <NEW_LINE> if node and hasattr(node, "parse_position"): <NEW_LINE> <INDENT> self.set_pos(node.parse_position) <NEW_LINE> <DEDENT> <DEDENT> def set_pos(self, pos): <NEW_LINE> <INDENT> self._filename = pos["file"] <NEW_LINE> self._line = pos["line"] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> line = "" <NEW_LINE> col = "" <NEW_LINE> sep = "" <NEW_LINE> pos = "" <NEW_LINE> filename = "<unknown>" <NEW_LINE> if self._filename: <NEW_LINE> <INDENT> filename = self._filename <NEW_LINE> <DEDENT> if self._line: <NEW_LINE> <INDENT> line = "%d" % self._line <NEW_LINE> sep = ":" <NEW_LINE> <DEDENT> if self._col: <NEW_LINE> <INDENT> col = "%s%d" % (sep, self._col) <NEW_LINE> <DEDENT> if self._line or self._col: <NEW_LINE> <INDENT> pos = "%s%s:" % (line, col) <NEW_LINE> <DEDENT> return "XmlProcessingError:%s:%s %s" % (filename, pos, self._msg)
Exception thrown on parsing errors
6259903516aa5153ce40162b
class CrossHairWidget: <NEW_LINE> <INDENT> def __init__(self, profile=0, radius=2): <NEW_LINE> <INDENT> if not radius: <NEW_LINE> <INDENT> self.radius = Globals.renderProps["sphereSize"] * 1.1 <NEW_LINE> <DEDENT> else: self.radius = radius <NEW_LINE> self.z = 0 <NEW_LINE> self.data = vtk.vtkPolyData() <NEW_LINE> self.sphere = vtk.vtkSphereSource() <NEW_LINE> self.sphere.SetRadius( Globals.referenceSize * self.radius ) <NEW_LINE> self.sphere.SetPhiResolution( Globals.renderProps["spherePhiResolution"] ) <NEW_LINE> self.sphere.SetThetaResolution( Globals.renderProps["sphereThetaResolution"] ) <NEW_LINE> self.glyphPoints = vtk.vtkGlyph3D() <NEW_LINE> self.glyphPoints.SetInput( self.data ) <NEW_LINE> self.glyphPoints.SetSource( self.sphere.GetOutput() ) <NEW_LINE> self.mapper = vtk.vtkPolyDataMapper() <NEW_LINE> self.mapper.SetInputConnection( self.glyphPoints.GetOutputPort() ) <NEW_LINE> self.actor = vtk.vtkActor() <NEW_LINE> self.actor.SetMapper(self.mapper) <NEW_LINE> if profile: <NEW_LINE> <INDENT> self.actor.GetProperty().SetColor(0,0,1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.actor.GetProperty().SetColor(1,1,0) <NEW_LINE> <DEDENT> Globals.ren.AddActor(self.actor) <NEW_LINE> <DEDENT> def SetPosition(self, x,y): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = y <NEW_LINE> point = vtk.vtkPoints() <NEW_LINE> point.SetNumberOfPoints(1) <NEW_LINE> point.SetPoint(0, x,y,0) <NEW_LINE> self.data.SetPoints(point) <NEW_LINE> <DEDENT> def Hide(self): <NEW_LINE> <INDENT> Globals.ren.RemoveActor(self.actor) <NEW_LINE> <DEDENT> def Show(self): <NEW_LINE> <INDENT> Globals.ren.AddActor(self.actor) <NEW_LINE> <DEDENT> def UpdateProperties(self): <NEW_LINE> <INDENT> self.radius = Globals.renderProps["sphereSize"] * 1.1 <NEW_LINE> self.sphere.SetRadius( Globals.referenceSize * self.radius ) <NEW_LINE> self.sphere.Update() <NEW_LINE> self.glyphPoints.Modified()
navigation cursor the coordinates of this actor will be in 2D, i.e. the last coordinate will always be zero
62599035b57a9660fecd2bba
class Tweet(Base): <NEW_LINE> <INDENT> __tablename__ = "tweet" <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> text = Column(String(length=500)) <NEW_LINE> lon = Column(Float()) <NEW_LINE> lat = Column(Float()) <NEW_LINE> retweet_count = Column(Integer()) <NEW_LINE> tweet_id = Column(String(20)) <NEW_LINE> created_at = Column(DateTime) <NEW_LINE> user_id = Column(String(20), index=True)
Table, that stores following information about tweet: ["text"], ["coordinates"] -> [lon][lat], ["retweet_count"], ["id"], ["created_at"], ["user"]["id"].
6259903582261d6c52730763
class ResultError(RemouladeError): <NEW_LINE> <INDENT> pass
Base class for result errors.
6259903571ff763f4b5e88d9
class Mpileaks(AutotoolsPackage): <NEW_LINE> <INDENT> homepage = "https://github.com/hpc/mpileaks" <NEW_LINE> url = "https://github.com/hpc/mpileaks/releases/download/v1.0/mpileaks-1.0.tar.gz" <NEW_LINE> version('1.0', '8838c574b39202a57d7c2d68692718aa') <NEW_LINE> depends_on('mpi') <NEW_LINE> depends_on('adept-utils') <NEW_LINE> depends_on('callpath') <NEW_LINE> def configure_args(self): <NEW_LINE> <INDENT> args = [] <NEW_LINE> return args
Tool to detect and report MPI objects like MPI_Requests and MPI_Datatypes.
62599035d164cc61758220b3
class NeuralNetwork: <NEW_LINE> <INDENT> ParametersContainer = namedtuple("ParametersContainer", ["alpha"]) <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.__layer_list = list() <NEW_LINE> self.__network_parameters = None <NEW_LINE> <DEDENT> def add_layer(self, layer_to_add): <NEW_LINE> <INDENT> self.__layer_list.append(layer_to_add) <NEW_LINE> return self <NEW_LINE> <DEDENT> def set_network_parameters(self, parameters_to_set): <NEW_LINE> <INDENT> self.__network_parameters = parameters_to_set <NEW_LINE> <DEDENT> def learn_network(self, input_data, data_labels): <NEW_LINE> <INDENT> normalized_data = self.__normalize_data(input_data) <NEW_LINE> data_from_forward_propagation = self.__do_forward_propagation(normalized_data) <NEW_LINE> last_layer_output = data_from_forward_propagation[-1].data_after_activation <NEW_LINE> last_layer_deltas = last_layer_output - data_labels <NEW_LINE> delta_list = self.__do_backward_propagation(last_layer_deltas, data_from_forward_propagation) <NEW_LINE> <DEDENT> def propagate_data_through_network(self, input_data): <NEW_LINE> <INDENT> data_for_next_layer = self.__normalize_data(input_data) <NEW_LINE> for layer in self.__layer_list: <NEW_LINE> <INDENT> propagated_data = layer.forward_propagation(data_for_next_layer) <NEW_LINE> data_for_next_layer = propagated_data.data_after_activation <NEW_LINE> <DEDENT> return data_for_next_layer <NEW_LINE> <DEDENT> def __do_forward_propagation(self, input_data): <NEW_LINE> <INDENT> result_list = list() <NEW_LINE> data_for_next_layer = input_data <NEW_LINE> for layer in self.__layer_list: <NEW_LINE> <INDENT> propagated_data = layer.forward_propagation(data_for_next_layer) <NEW_LINE> data_for_next_layer = propagated_data.data_after_activation <NEW_LINE> result_list.append(propagated_data) <NEW_LINE> <DEDENT> return result_list <NEW_LINE> <DEDENT> def __do_backward_propagation(self, input_data, forward_data_list): <NEW_LINE> <INDENT> result_list = list() <NEW_LINE> data_for_next_layer = input_data <NEW_LINE> for layer_index in range(len(self.__layer_list) - 1, 0, -1): <NEW_LINE> <INDENT> layer = self.__layer_list[layer_index] <NEW_LINE> data_for_next_layer = layer.backward_propagation(data_for_next_layer, forward_data_list[layer_index - 1].data_before_activation) <NEW_LINE> result_list.append(data_for_next_layer) <NEW_LINE> <DEDENT> result_list.reverse() <NEW_LINE> return result_list <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __normalize_data(data_to_normalize): <NEW_LINE> <INDENT> max_number = numpy.max(data_to_normalize) <NEW_LINE> min_number = numpy.min(data_to_normalize) <NEW_LINE> difference = max_number - min_number <NEW_LINE> normalized_data = (data_to_normalize - min_number) / difference - 0.5 <NEW_LINE> return normalized_data
Class used as neural network. To create instance of this class use :class:`NeuralNetworkDirector`.
62599035c432627299fa4137
class ProxyAuthenticationRequired(ClientError): <NEW_LINE> <INDENT> status_code = 407 <NEW_LINE> status_phrase = "Proxy Authentication Required"
This code is similar to 401 (Unauthorized), but indicates that the client must first authenticate itself with the proxy.
625990353eb6a72ae038b7a7
class ExcelDataReader(object): <NEW_LINE> <INDENT> __pasta = os.path.dirname(os.path.abspath(__file__)).split("xlsxreader")[0] <NEW_LINE> def __init__(self, arquivo_excel, l1, usecols=()): <NEW_LINE> <INDENT> self.arquivo = arquivo_excel <NEW_LINE> self.usecols = usecols <NEW_LINE> self.l1 = l1 <NEW_LINE> <DEDENT> @property <NEW_LINE> def arquivo(self): <NEW_LINE> <INDENT> return self.__arquivo <NEW_LINE> <DEDENT> @arquivo.setter <NEW_LINE> def arquivo(self, arquivo): <NEW_LINE> <INDENT> arq = os.path.join(self.__pasta, arquivo) <NEW_LINE> self.__arquivo = arq <NEW_LINE> <DEDENT> def dados(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sheet = load_workbook(self.arquivo, read_only=True) <NEW_LINE> act_sheet = sheet.active <NEW_LINE> linhas = act_sheet.rows <NEW_LINE> if self.l1 != 0: <NEW_LINE> <INDENT> linhas = islice(linhas, self.l1, None) <NEW_LINE> <DEDENT> dados = [] <NEW_LINE> for linha in linhas: <NEW_LINE> <INDENT> if isinstance(self.usecols, tuple): <NEW_LINE> <INDENT> conteudo = [linha[valor].value for valor in self.usecols] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> conteudo = [linha[self.usecols].value] <NEW_LINE> <DEDENT> if conteudo[0] is not None: <NEW_LINE> <INDENT> dados.append(conteudo) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except InvalidFileException: <NEW_LINE> <INDENT> book = xlrd.open_workbook(self.arquivo) <NEW_LINE> sheet = book.sheet_by_index(0) <NEW_LINE> dados = [] <NEW_LINE> for linha in range(self.l1, sheet.nrows, 1): <NEW_LINE> <INDENT> conteudo = [sheet.row(linha)[valor].value if isinstance(sheet.row(linha)[valor].value, float) else 0.0 for valor in self.usecols] <NEW_LINE> dados.append(conteudo) <NEW_LINE> <DEDENT> <DEDENT> return dados
Objeto para leitura e parseamento de arquivos do excel
62599035287bf620b6272d29
class CmdEntity(CmdPositioner): <NEW_LINE> <INDENT> def __init__(self, connection): <NEW_LINE> <INDENT> CmdPositioner.__init__(self, connection, b"entity") <NEW_LINE> <DEDENT> def getName(self, id): <NEW_LINE> <INDENT> return self.conn.sendReceive(b"entity.getName", id)
Methods for entities
6259903576d4e153a661db11
class Tree(object): <NEW_LINE> <INDENT> def __init__(self, namespace='', access_key=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _NormalizeDirectoryPath(path): <NEW_LINE> <INDENT> if path and path[-1] != '/': <NEW_LINE> <INDENT> return path + '/' <NEW_LINE> <DEDENT> return path <NEW_LINE> <DEDENT> def IsMutable(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def GetFileContents(self, path): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def GetFileSize(self, path): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def GetFileLastModified(self, path): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def HasFile(self, path): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def MoveFile(self, path, newpath): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def DeletePath(self, path): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def SetFile(self, path, contents): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def Clear(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def HasDirectory(self, path): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def ListDirectory(self, path): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def Files(self, path): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def PutFiles(self, files): <NEW_LINE> <INDENT> raise NotImplementedError
An abstract base class for accessing a tree of files. At minimum subclasses must implement GetFileContents() and HasFile(). Additionally, mutable trees should override IsMutable() to return True and provide implementations of SetFile() and Clear().
62599035ec188e330fdf99d5
class conv_ln(LayerMaster): <NEW_LINE> <INDENT> def __init__(self, rng, trng, n_in, n_out, n_batches, activation, old_weights=None,go_backwards=False): <NEW_LINE> <INDENT> self.go_backwards = go_backwards <NEW_LINE> self.activation = activation <NEW_LINE> self.rng = rng <NEW_LINE> self.trng = trng <NEW_LINE> if old_weights == None: <NEW_LINE> <INDENT> np_weights = OrderedDict() <NEW_LINE> np_weights['w_in_hidden'] = self.rec_uniform_sqrt(rng, n_in, n_out) <NEW_LINE> np_weights['w_hidden_hidden'] = self.sqr_ortho(rng, n_out) <NEW_LINE> np_weights['b_act'] = np.zeros(n_out) <NEW_LINE> np_weights['ln_s1'] = np.ones(n_out) <NEW_LINE> np_weights['ln_b1'] = np.zeros(n_out) <NEW_LINE> np_weights['ln_s2'] = np.ones(n_out) <NEW_LINE> np_weights['ln_b2'] = np.zeros(n_out) <NEW_LINE> self.weights = [] <NEW_LINE> for kk, pp in np_weights.items(): <NEW_LINE> <INDENT> self.weights.append(theano.shared(name=kk, value=pp.astype(T.config.floatX))) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.weights = [] <NEW_LINE> for pp in old_weights: <NEW_LINE> <INDENT> self.weights.append(theano.shared(value=pp.astype(T.config.floatX))) <NEW_LINE> <DEDENT> <DEDENT> init_hidden = np.zeros([n_batches, n_out]).astype(dtype=theano.config.floatX) <NEW_LINE> self.t_init_hidden = theano.shared(name='init_hidden', value=init_hidden.astype(T.config.floatX)) <NEW_LINE> <DEDENT> def t_forward_step(self, mask, cur_w_in_sig, pre_out_sig, w_hidden_hidden, b_act, ln_s1, ln_b1, ln_s2, ln_b2): <NEW_LINE> <INDENT> pre_w_sig = T.dot(pre_out_sig, w_hidden_hidden) <NEW_LINE> inner_act = self.activation <NEW_LINE> pre_w_sig_ln = self.ln(pre_w_sig, ln_b1, ln_s1) <NEW_LINE> cur_w_in_sig_ln = self.ln(cur_w_in_sig, ln_b2, ln_s2) <NEW_LINE> out_sig = inner_act(T.add(cur_w_in_sig_ln, pre_w_sig_ln, b_act)) <NEW_LINE> mask = T.addbroadcast(mask, 1) <NEW_LINE> out_sig_m = mask * out_sig + (1. - mask) * pre_out_sig <NEW_LINE> return [out_sig_m] <NEW_LINE> <DEDENT> def sequence_iteration(self, in_seq, mask, use_dropout, dropout_value=1): <NEW_LINE> <INDENT> in_seq_d = T.switch(use_dropout, (in_seq * self.trng.binomial(in_seq.shape, p=dropout_value, n=1, dtype=in_seq.dtype)), in_seq) <NEW_LINE> w_in_seq = T.dot(in_seq_d, self.weights[0]) <NEW_LINE> out_seq, updates = theano.scan( fn=self.t_forward_step, sequences=[mask, w_in_seq], outputs_info=[self.t_init_hidden], non_sequences=self.weights[1:], go_backwards=self.go_backwards, truncate_gradient=-1, strict=True, allow_gc=False, ) <NEW_LINE> return out_seq
Hyperbolic tangent or rectified linear unit layer
62599035d6c5a102081e3266
class urlopenNetworkTests(unittest.TestCase): <NEW_LINE> <INDENT> def urlopen(self, *args): <NEW_LINE> <INDENT> return _open_with_retry(urllib.request.urlopen, *args) <NEW_LINE> <DEDENT> def test_basic(self): <NEW_LINE> <INDENT> open_url = self.urlopen("http://www.python.org/") <NEW_LINE> for attr in ("read", "readline", "readlines", "fileno", "close", "info", "geturl"): <NEW_LINE> <INDENT> self.assertTrue(hasattr(open_url, attr), "object returned from " "urlopen lacks the %s attribute" % attr) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.assertTrue(open_url.read(), "calling 'read' failed") <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> open_url.close() <NEW_LINE> <DEDENT> <DEDENT> def test_readlines(self): <NEW_LINE> <INDENT> open_url = self.urlopen("http://www.python.org/") <NEW_LINE> try: <NEW_LINE> <INDENT> self.assertTrue(isinstance(open_url.readline(), bytes), "readline did not return bytes") <NEW_LINE> self.assertTrue(isinstance(open_url.readlines(), list), "readlines did not return a list") <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> open_url.close() <NEW_LINE> <DEDENT> <DEDENT> def test_info(self): <NEW_LINE> <INDENT> open_url = self.urlopen("http://www.python.org/") <NEW_LINE> try: <NEW_LINE> <INDENT> info_obj = open_url.info() <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> open_url.close() <NEW_LINE> self.assertTrue(isinstance(info_obj, email.message.Message), "object returned by 'info' is not an instance of " "email.message.Message") <NEW_LINE> self.assertEqual(info_obj.get_content_subtype(), "html") <NEW_LINE> <DEDENT> <DEDENT> def test_geturl(self): <NEW_LINE> <INDENT> URL = "http://www.python.org/" <NEW_LINE> open_url = self.urlopen(URL) <NEW_LINE> try: <NEW_LINE> <INDENT> gotten_url = open_url.geturl() <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> open_url.close() <NEW_LINE> <DEDENT> self.assertEqual(gotten_url, URL) <NEW_LINE> <DEDENT> def test_getcode(self): <NEW_LINE> <INDENT> URL = "http://www.python.org/XXXinvalidXXX" <NEW_LINE> open_url = urllib.request.FancyURLopener().open(URL) <NEW_LINE> try: <NEW_LINE> <INDENT> code = open_url.getcode() <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> open_url.close() <NEW_LINE> <DEDENT> self.assertEqual(code, 404) <NEW_LINE> <DEDENT> def test_fileno(self): <NEW_LINE> <INDENT> if sys.platform in ('win32',): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> open_url = self.urlopen("http://www.python.org/") <NEW_LINE> fd = open_url.fileno() <NEW_LINE> FILE = os.fdopen(fd, encoding='utf-8') <NEW_LINE> try: <NEW_LINE> <INDENT> self.assertTrue(FILE.read(), "reading from file created using fd " "returned by fileno failed") <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> FILE.close() <NEW_LINE> <DEDENT> <DEDENT> def test_bad_address(self): <NEW_LINE> <INDENT> self.assertRaises(IOError, urllib.request.urlopen, "http://sadflkjsasf.i.nvali.d/")
Tests urllib.reqest.urlopen using the network. These tests are not exhaustive. Assuming that testing using files does a good job overall of some of the basic interface features. There are no tests exercising the optional 'data' and 'proxies' arguments. No tests for transparent redirection have been written. setUp is not used for always constructing a connection to http://www.python.org/ since there a few tests that don't use that address and making a connection is expensive enough to warrant minimizing unneeded connections.
625990356fece00bbacccaea
class GenericSH(BaseSH): <NEW_LINE> <INDENT> PROG = None <NEW_LINE> def highlightBlock(self, text): <NEW_LINE> <INDENT> text = str(text) <NEW_LINE> self.setFormat(0, len(text), self.formats["normal"]) <NEW_LINE> match = self.PROG.search(text) <NEW_LINE> index = 0 <NEW_LINE> while match: <NEW_LINE> <INDENT> for key, value in match.groupdict().items(): <NEW_LINE> <INDENT> if value: <NEW_LINE> <INDENT> start, end = match.span(key) <NEW_LINE> index += end - start <NEW_LINE> self.setFormat(start, end - start, self.formats[key]) <NEW_LINE> <DEDENT> <DEDENT> match = self.PROG.search(text, match.end())
Generic Syntax Highlighter
6259903563f4b57ef0086613
class Node(object): <NEW_LINE> <INDENT> def __init__(self, val, priority): <NEW_LINE> <INDENT> self.val = val <NEW_LINE> self.priority = priority <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.priority == other.priority <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> return self.priority < other.priority <NEW_LINE> <DEDENT> def __gt__(self, other): <NEW_LINE> <INDENT> return self.priority > other.priority <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return ('(val:' + repr(self.val) + ' pri:' + repr(self.priority) + ')')
Node for use in a Priority Queue.
6259903530c21e258be9994c
class Montage(object): <NEW_LINE> <INDENT> def __init__(self, pos, ch_names, kind, selection): <NEW_LINE> <INDENT> self.pos = pos <NEW_LINE> self.ch_names = ch_names <NEW_LINE> self.kind = kind <NEW_LINE> self.selection = selection <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> s = '<Montage | %s - %d Channels: %s ...>' <NEW_LINE> s %= self.kind, len(self.ch_names), ', '.join(self.ch_names[:3]) <NEW_LINE> return s <NEW_LINE> <DEDENT> def plot(self, scale_factor=1.5, show_names=False): <NEW_LINE> <INDENT> return plot_montage(self, scale_factor=scale_factor, show_names=show_names)
Montage for EEG cap Montages are typically loaded from a file using read_montage. Only use this class directly if you're constructing a new montage. Parameters ---------- pos : array, shape (n_channels, 3) The positions of the channels in 3d. ch_names : list The channel names. kind : str The type of montage (e.g. 'standard_1005'). selection : array of int The indices of the selected channels in the montage file.
6259903573bcbd0ca4bcb3c8
class ReservableResource(BaseResource): <NEW_LINE> <INDENT> def __init__(self, name, sync, flag=None): <NEW_LINE> <INDENT> super(ReservableResource, self).__init__(name, flag=flag) <NEW_LINE> self.sync = sync
Describe a reservable resource.
62599035d10714528d69ef2c
class ImageHarbor(object): <NEW_LINE> <INDENT> def __init__(self, harbor_url, username=None, password=None, api_version='v2', cacert=None, insecure=False, ): <NEW_LINE> <INDENT> self.username = username <NEW_LINE> self.password = password <NEW_LINE> self.harbor_url = harbor_url <NEW_LINE> self.api_version = api_version <NEW_LINE> if not urlparse(harbor_url).scheme: <NEW_LINE> <INDENT> self.harbor_url = 'http://' + harbor_url <NEW_LINE> <DEDENT> parsed_url = urlparse(self.harbor_url) <NEW_LINE> self.protocol = parsed_url.scheme <NEW_LINE> self.host = parsed_url.hostname <NEW_LINE> self.port = parsed_url.port <NEW_LINE> self.session_id = None <NEW_LINE> self.user_agent = 'python-harborclient' <NEW_LINE> if insecure: <NEW_LINE> <INDENT> self.verify_cert = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if cacert: <NEW_LINE> <INDENT> self.verify_cert = cacert <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.verify_cert = True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def unauthenticate(self): <NEW_LINE> <INDENT> if not self.session_id: <NEW_LINE> <INDENT> requests.get( '%s://%s/logout' % (self.protocol, self.host), cookies={'beegosessionID': self.session_id}, verify=self.verify_cert ) <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def authenticate(self): <NEW_LINE> <INDENT> if not self.username or not self.password: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> resp = requests.post( self.harbor_url + '/login', data={ 'principal': self.username, 'password': self.password }, verify=self.verify_cert ) <NEW_LINE> if resp.status_code == 200: <NEW_LINE> <INDENT> self.session_id = resp.cookies.get('beegosessionID') <NEW_LINE> <DEDENT> if resp.status_code >= 400: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> except SSLError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def get_all_repositories(self): <NEW_LINE> <INDENT> info = [] <NEW_LINE> if not self.session_id: <NEW_LINE> <INDENT> repositories = self.request('GET', '/repositories/top') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> repositories = self.request('GET', '/repositories/top', cookies={'beegosessionID': self.session_id}) <NEW_LINE> <DEDENT> for repository in repositories: <NEW_LINE> <INDENT> info.append({ 'name': repository.get('name'), 'description': repository.get('description'), 'pull_count': repository.get('pull_count'), 'star_count': repository.get('star_count'), 'update_time': repository.get('update_time') }) <NEW_LINE> <DEDENT> return {'message': info, 'status': True} <NEW_LINE> <DEDENT> def request(self, method, url, **kwargs): <NEW_LINE> <INDENT> url = self.harbor_url + '/api' + url <NEW_LINE> kwargs.setdefault('headers', kwargs.get('headers', {})) <NEW_LINE> kwargs['headers']['User-Agent'] = self.user_agent <NEW_LINE> kwargs['headers']['Accept'] = 'application/json' <NEW_LINE> kwargs['headers']['Content-Type'] = 'application/json' <NEW_LINE> kwargs["headers"]['Harbor-API-Version'] = self.api_version <NEW_LINE> resp = requests.request(method, url, verify=self.verify_cert, **kwargs) <NEW_LINE> if resp.status_code >= 400: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> value = json.loads(resp.text) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> value = [] <NEW_LINE> <DEDENT> return value
处理harbor请求
625990358c3a8732951f7699
class ItemQueueProducer(QueueProducer): <NEW_LINE> <INDENT> def __init__(self, queue_object): <NEW_LINE> <INDENT> super(ItemQueueProducer, self).__init__(queue_object) <NEW_LINE> self._number_of_produced_items = 0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def number_of_produced_items(self): <NEW_LINE> <INDENT> return self._number_of_produced_items <NEW_LINE> <DEDENT> def _FlushQueue(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def ProduceItem(self, item): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._number_of_produced_items += 1 <NEW_LINE> self._queue.PushItem(item) <NEW_LINE> <DEDENT> except errors.QueueFull: <NEW_LINE> <INDENT> self._FlushQueue() <NEW_LINE> <DEDENT> <DEDENT> def ProduceItems(self, items): <NEW_LINE> <INDENT> for item in items: <NEW_LINE> <INDENT> self.ProduceItem(item) <NEW_LINE> <DEDENT> <DEDENT> def Close(self): <NEW_LINE> <INDENT> self._queue.Close()
Class that implements an item queue producer. The producer generates updates on the queue.
6259903516aa5153ce40162d
class EnumConverter: <NEW_LINE> <INDENT> def __init__(self, enum: Type[Enum]): <NEW_LINE> <INDENT> self._enum = enum <NEW_LINE> <DEDENT> def loads(self, value: Any) -> Enum: <NEW_LINE> <INDENT> return self._enum(value) <NEW_LINE> <DEDENT> def dumps(self, value: Enum) -> Any: <NEW_LINE> <INDENT> if not isinstance(value, self._enum): <NEW_LINE> <INDENT> value = self._enum[value] <NEW_LINE> <DEDENT> return value.value
Convert values to and from an enum.
625990351d351010ab8f4c5b
class SpinneretResource(Resource, object): <NEW_LINE> <INDENT> def _adaptToResource(self, result): <NEW_LINE> <INDENT> if result is None: <NEW_LINE> <INDENT> return NotFound() <NEW_LINE> <DEDENT> renderable = IRenderable(result, None) <NEW_LINE> if renderable is not None: <NEW_LINE> <INDENT> return _RenderableResource(renderable) <NEW_LINE> <DEDENT> resource = IResource(result, None) <NEW_LINE> if resource is not None: <NEW_LINE> <INDENT> return resource <NEW_LINE> <DEDENT> if isinstance(result, URLPath): <NEW_LINE> <INDENT> return Redirect(str(result)) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def getChildWithDefault(self, path, request): <NEW_LINE> <INDENT> def _setSegments(result): <NEW_LINE> <INDENT> result, segments = result <NEW_LINE> request.postpath[:] = segments <NEW_LINE> return result <NEW_LINE> <DEDENT> segments = request.prepath[-1:] + request.postpath <NEW_LINE> d = maybeDeferred(self.locateChild, request, segments) <NEW_LINE> d.addCallback(_setSegments) <NEW_LINE> d.addCallback(self._adaptToResource) <NEW_LINE> return DeferredResource(d) <NEW_LINE> <DEDENT> def _handleRenderResult(self, request, result): <NEW_LINE> <INDENT> def _requestFinished(result, cancel): <NEW_LINE> <INDENT> cancel() <NEW_LINE> return result <NEW_LINE> <DEDENT> if not isinstance(result, Deferred): <NEW_LINE> <INDENT> result = succeed(result) <NEW_LINE> <DEDENT> def _whenDone(result): <NEW_LINE> <INDENT> render = getattr(result, 'render', lambda request: result) <NEW_LINE> renderResult = render(request) <NEW_LINE> if renderResult != NOT_DONE_YET: <NEW_LINE> <INDENT> request.write(renderResult) <NEW_LINE> request.finish() <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> request.notifyFinish().addBoth(_requestFinished, result.cancel) <NEW_LINE> result.addCallback(self._adaptToResource) <NEW_LINE> result.addCallback(_whenDone) <NEW_LINE> result.addErrback(request.processingFailed) <NEW_LINE> return NOT_DONE_YET <NEW_LINE> <DEDENT> def render(self, request): <NEW_LINE> <INDENT> return self._handleRenderResult( request, super(SpinneretResource, self).render(request)) <NEW_LINE> <DEDENT> def locateChild(self, request, segments): <NEW_LINE> <INDENT> return NotFound(), []
Web resource convenience base class. Child resource location is done by `SpinneretResource.locateChild`, which gives a slightly higher level interface than `IResource.getChildWithDefault <twisted:twisted.web.resource.IResource.getChildWithDefault>`.
6259903521bff66bcd723da7
class Texture(Structure): <NEW_LINE> <INDENT> _fields_ = [ ("mWidth", c_uint), ("mHeight", c_uint), ("achFormatHint", c_char*9), ("pcData", POINTER(Texel)), ("mFilename", String), ]
See 'texture.h' for details.
62599035dc8b845886d546f3
class RenderNoeud(ecs.System): <NEW_LINE> <INDENT> def __init__(self, canvas): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.canvas=canvas <NEW_LINE> <DEDENT> def init(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def update(self, dt): <NEW_LINE> <INDENT> with self.canvas: <NEW_LINE> <INDENT> for entity, noeud in self.entity_manager.pairs_for_type(Noeud): <NEW_LINE> <INDENT> Color((noeud.coloris >> 24 & 0xFF)/255.0, (noeud.coloris >> 16 & 0xFF)/255.0, (noeud.coloris >> 8 & 0xFF)/255.0, (noeud.coloris & 0xFF)/255.0) <NEW_LINE> Rectangle(pos=noeud.box.pos, size=noeud.box.size) <NEW_LINE> Color(0,0,0,1) <NEW_LINE> Line(rectangle=noeud.box.pos+noeud.box.size)
Systeme pour le rendering des noeuds via coloriage.
62599035796e427e5384f8bc
class Plagiarist(object): <NEW_LINE> <INDENT> def observe(self, document): <NEW_LINE> <INDENT> raise NotImplementedError()
Given a sequence of documents, produce scores indicating how much "plagiarism" (i.e. how many ideas were borrowed) from each of the preceding documents. Note that getting a high score doesn't really mean there was plagiarism since citations, etc. are not analyzed.
62599035e76e3b2f99fd9b4d
class Question(models.Model): <NEW_LINE> <INDENT> question_text = models.CharField(max_length=200) <NEW_LINE> pub_date = models.DateTimeField('date published') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.question_text <NEW_LINE> <DEDENT> def was_published_recently(self): <NEW_LINE> <INDENT> return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
The Question model contains three fields: question_text: to input text for question_text pub_date: uses date time to designate data/time. IF USED, PLEASE IMPORT timezone
62599035507cdc57c63a5edb
@req_cmd(Roundup) <NEW_LINE> class _GetItemRequest(Multicall): <NEW_LINE> <INDENT> def __init__(self, *, ids, fields=None, **kw): <NEW_LINE> <INDENT> super().__init__(command='display', **kw) <NEW_LINE> if ids is None: <NEW_LINE> <INDENT> raise ValueError(f'No {self.service.item.type} ID(s) specified') <NEW_LINE> <DEDENT> if fields is None: <NEW_LINE> <INDENT> fields = self.service.item.attributes.keys() <NEW_LINE> <DEDENT> self.params = (chain([f'issue{i}'], fields) for i in ids) <NEW_LINE> self.ids = ids <NEW_LINE> <DEDENT> def parse(self, data): <NEW_LINE> <INDENT> issues = super().parse(data) <NEW_LINE> for i, issue in enumerate(issues): <NEW_LINE> <INDENT> yield self.service.item(self.service, **issue)
Construct an item request.
62599035287bf620b6272d2b
class Conda(PythonEnvironment): <NEW_LINE> <INDENT> def venv_path(self): <NEW_LINE> <INDENT> return os.path.join(self.project.doc_path, 'conda', self.version.slug) <NEW_LINE> <DEDENT> def setup_base(self): <NEW_LINE> <INDENT> conda_env_path = os.path.join(self.project.doc_path, 'conda') <NEW_LINE> version_path = os.path.join(conda_env_path, self.version.slug) <NEW_LINE> if os.path.exists(version_path): <NEW_LINE> <INDENT> self._log('Removing existing conda directory') <NEW_LINE> shutil.rmtree(version_path) <NEW_LINE> <DEDENT> self.build_env.run( 'conda', 'env', 'create', '--name', self.version.slug, '--file', self.config.conda_file, bin_path=None, ) <NEW_LINE> <DEDENT> def install_core_requirements(self): <NEW_LINE> <INDENT> requirements = [ 'mock', 'pillow', ] <NEW_LINE> pip_requirements = [ 'recommonmark', ] <NEW_LINE> if self.project.documentation_type == 'mkdocs': <NEW_LINE> <INDENT> pip_requirements.append('mkdocs') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pip_requirements.append('readthedocs-sphinx-ext') <NEW_LINE> requirements.extend(['sphinx', 'sphinx-rtd-theme']) <NEW_LINE> <DEDENT> cmd = [ 'conda', 'install', '--yes', '--name', self.version.slug, ] <NEW_LINE> cmd.extend(requirements) <NEW_LINE> self.build_env.run( *cmd ) <NEW_LINE> pip_cmd = [ 'python', self.venv_bin(filename='pip'), 'install', '-U', '--cache-dir', self.project.pip_cache_path, ] <NEW_LINE> pip_cmd.extend(pip_requirements) <NEW_LINE> self.build_env.run( *pip_cmd, bin_path=self.venv_bin() ) <NEW_LINE> <DEDENT> def install_user_requirements(self): <NEW_LINE> <INDENT> pass
A Conda_ environment. .. _Conda: https://conda.io/docs/
62599035be383301e0254956
class UserProfile(models.Model): <NEW_LINE> <INDENT> website = models.URLField(default="", verify_exists=False, max_length=news_settings.NEWS_MAX_URL_LENGTH) <NEW_LINE> comment_points = models.IntegerField(default=0) <NEW_LINE> user = models.ForeignKey(User, unique=True) <NEW_LINE> date_created = models.DateTimeField(default=datetime.datetime.now) <NEW_LINE> about = models.TextField(default="") <NEW_LINE> option_show_email = models.BooleanField(default=False) <NEW_LINE> option_use_javascript = models.BooleanField(default=False) <NEW_LINE> option_show_dead = models.BooleanField(default=False) <NEW_LINE> created_from_ip = models.IPAddressField(null=True) <NEW_LINE> last_login_ip = models.IPAddressField(null=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.user.username <NEW_LINE> <DEDENT> def _get_username(self): <NEW_LINE> <INDENT> return self.user.username <NEW_LINE> <DEDENT> username = property(_get_username)
This is a profile to a user. It is intrinsically linked to django's default User model. This UserProfile holds additional info about the user.
62599036cad5886f8bdc591c
class DescribeAIAnalysisTemplatesResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.TotalCount = None <NEW_LINE> self.AIAnalysisTemplateSet = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.TotalCount = params.get("TotalCount") <NEW_LINE> if params.get("AIAnalysisTemplateSet") is not None: <NEW_LINE> <INDENT> self.AIAnalysisTemplateSet = [] <NEW_LINE> for item in params.get("AIAnalysisTemplateSet"): <NEW_LINE> <INDENT> obj = AIAnalysisTemplateItem() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.AIAnalysisTemplateSet.append(obj) <NEW_LINE> <DEDENT> <DEDENT> self.RequestId = params.get("RequestId")
DescribeAIAnalysisTemplates返回参数结构体
62599036b57a9660fecd2bbd