code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class QPinchGesture(QGesture): <NEW_LINE> <INDENT> def centerPoint(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def changeFlags(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def childEvent(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def connectNotify(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def customEvent(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def disconnectNotify(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def isSignalConnected(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def lastCenterPoint(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def lastRotationAngle(self): <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDENT> def lastScaleFactor(self): <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDENT> def receivers(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def rotationAngle(self): <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDENT> def scaleFactor(self): <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDENT> def sender(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def senderSignalIndex(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def setCenterPoint(self, Union, QPointF=None, QPoint=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def setChangeFlags(self, Union, QPinchGesture_ChangeFlags=None, QPinchGesture_ChangeFlag=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def setLastCenterPoint(self, Union, QPointF=None, QPoint=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def setLastRotationAngle(self, p_float): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def setLastScaleFactor(self, p_float): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def setRotationAngle(self, p_float): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def setScaleFactor(self, p_float): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def setStartCenterPoint(self, Union, QPointF=None, QPoint=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def setTotalChangeFlags(self, Union, QPinchGesture_ChangeFlags=None, QPinchGesture_ChangeFlag=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def setTotalRotationAngle(self, p_float): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def setTotalScaleFactor(self, p_float): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def startCenterPoint(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def timerEvent(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def totalChangeFlags(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def totalRotationAngle(self): <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDENT> def totalScaleFactor(self): <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDENT> def __init__(self, parent=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> CenterPointChanged = 4 <NEW_LINE> RotationAngleChanged = 2 <NEW_LINE> ScaleFactorChanged = 1 | QPinchGesture(parent: QObject = None) | 62598fca4428ac0f6e6588b6 |
class InfoRequestMessage(InfoMessage): <NEW_LINE> <INDENT> def __init__(self, info_type=InfoMessage.INFO_PROFILE): <NEW_LINE> <INDENT> InfoMessage.__init__(self, Message.TYPE_INFO_REQUEST, info_type) <NEW_LINE> <DEDENT> def get_body_fields(self): <NEW_LINE> <INDENT> return [self.FIELD_INFOTYPE] <NEW_LINE> <DEDENT> def get_required_body_fields(self): <NEW_LINE> <INDENT> return [self.FIELD_INFOTYPE] | An info request can be a request for a profile, or for a list of friends | 62598fca283ffb24f3cf3c14 |
class WinRMListener(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'protocol': {'key': 'protocol', 'type': 'str'}, 'certificate_url': {'key': 'certificateUrl', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, protocol: Optional[Union[str, "ProtocolTypes"]] = None, certificate_url: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(WinRMListener, self).__init__(**kwargs) <NEW_LINE> self.protocol = protocol <NEW_LINE> self.certificate_url = certificate_url | Describes Protocol and thumbprint of Windows Remote Management listener.
:ivar protocol: Specifies the protocol of listener. :code:`<br>`:code:`<br>` Possible values
are: :code:`<br>`\ **http** :code:`<br>`:code:`<br>` **https**. Possible values include:
"Http", "Https".
:vartype protocol: str or ~azure.mgmt.compute.v2019_03_01.models.ProtocolTypes
:ivar certificate_url: This is the URL of a certificate that has been uploaded to Key Vault as
a secret. For adding a secret to the Key Vault, see `Add a key or secret to the key vault
<https://docs.microsoft.com/azure/key-vault/key-vault-get-started/#add>`_. In this case, your
certificate needs to be It is the Base64 encoding of the following JSON Object which is encoded
in UTF-8: :code:`<br>`:code:`<br>` {:code:`<br>`
"data":":code:`<Base64-encoded-certificate>`",:code:`<br>` "dataType":"pfx",:code:`<br>`
"password":":code:`<pfx-file-password>`":code:`<br>`}.
:vartype certificate_url: str | 62598fca63b5f9789fe85505 |
class enlace(object): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> self.fisica = fisica(name) <NEW_LINE> self.rx = RX(self.fisica) <NEW_LINE> self.tx = TX(self.fisica) <NEW_LINE> self.connected = False <NEW_LINE> <DEDENT> def enable(self): <NEW_LINE> <INDENT> self.fisica.open() <NEW_LINE> self.rx.threadStart() <NEW_LINE> self.tx.threadStart() <NEW_LINE> <DEDENT> def disable(self): <NEW_LINE> <INDENT> self.rx.threadKill() <NEW_LINE> self.tx.threadKill() <NEW_LINE> time.sleep(1) <NEW_LINE> self.fisica.close() <NEW_LINE> <DEDENT> def sendData(self, data): <NEW_LINE> <INDENT> self.tx.sendBuffer(data) <NEW_LINE> <DEDENT> def makePackages(self, msgType, filename, errorNumPackage): <NEW_LINE> <INDENT> package = self.tx.createPackages(msgType, filename,errorNumPackage) <NEW_LINE> return package <NEW_LINE> <DEDENT> def getData(self): <NEW_LINE> <INDENT> data = self.rx.getNData() <NEW_LINE> return (data) <NEW_LINE> <DEDENT> def supposedTime(self, filesize): <NEW_LINE> <INDENT> time = (filesize*11*1024)/(self.fisica.baudrate) <NEW_LINE> return time <NEW_LINE> <DEDENT> def receiveData(self): <NEW_LINE> <INDENT> return self.rx.receivedData <NEW_LINE> <DEDENT> def getMsgType(self, data): <NEW_LINE> <INDENT> return (self.rx.verifyMsgType(data)) <NEW_LINE> <DEDENT> def verifyFileIntegrity(self, data): <NEW_LINE> <INDENT> return self.rx.verifyFileIntegrity(data) <NEW_LINE> <DEDENT> def getPackageNumber(self,data): <NEW_LINE> <INDENT> return self.rx.getPackageNumber(data) <NEW_LINE> <DEDENT> def getNumberOfPackages(self, data): <NEW_LINE> <INDENT> total = self.rx.getNumberOfPackages(data) <NEW_LINE> return total <NEW_LINE> <DEDENT> def getPackageByNum(self, packageNum): <NEW_LINE> <INDENT> return self.tx.getPackageByNum(packageNum) <NEW_LINE> <DEDENT> def getPayload(self, data): <NEW_LINE> <INDENT> return self.rx.getPayload(data) <NEW_LINE> <DEDENT> def cleanStuffing(self, data): <NEW_LINE> <INDENT> return self.rx.cleanStuffing(data) <NEW_LINE> <DEDENT> def getType8Addon(self, data): <NEW_LINE> <INDENT> addon = self.rx.getType8Addon(data) <NEW_LINE> return addon <NEW_LINE> <DEDENT> def crc16(self, data): <NEW_LINE> <INDENT> return self.tx.crc16(data) <NEW_LINE> <DEDENT> def getCRCResult(self, data): <NEW_LINE> <INDENT> return self.rx.getCRCResult(data) | This class implements methods to the interface between Enlace and Application
| 62598fcaa05bb46b3848abfa |
class User: <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def get(cls, user_id: int): <NEW_LINE> <INDENT> user = UserModel.find_by_id(user_id) <NEW_LINE> if not user: <NEW_LINE> <INDENT> return {"message": gettext("user_not_found")}, 404 <NEW_LINE> <DEDENT> return user_schema.dump(user), 200 <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def delete(cls, user_id: int): <NEW_LINE> <INDENT> user = UserModel.find_by_id(user_id) <NEW_LINE> if not user: <NEW_LINE> <INDENT> return {"message": gettext("user_not_found")}, 404 <NEW_LINE> <DEDENT> user.delete_from_db() <NEW_LINE> return {"message": gettext("user_deleted")}, 200 | Resource to be used for testing purposes only. Do not expose in routes. | 62598fca5fdd1c0f98e5e31b |
class DescribeCloneListRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.InstanceId = None <NEW_LINE> self.Offset = None <NEW_LINE> self.Limit = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.InstanceId = params.get("InstanceId") <NEW_LINE> self.Offset = params.get("Offset") <NEW_LINE> self.Limit = params.get("Limit") | DescribeCloneList请求参数结构体
| 62598fca60cbc95b063646cc |
class deck_2(deck): <NEW_LINE> <INDENT> deck_2_list = [0] <NEW_LINE> def __init__(self, x, y): <NEW_LINE> <INDENT> deck.__init__(self, x, y) <NEW_LINE> self.x = x <NEW_LINE> self.y = y <NEW_LINE> self.hidden = [] <NEW_LINE> <DEDENT> def extend_list(self, lst): <NEW_LINE> <INDENT> for i in lst: <NEW_LINE> <INDENT> deck_2.deck_2_list.append(i) <NEW_LINE> <DEDENT> <DEDENT> def draw_card(self, screen, card_set): <NEW_LINE> <INDENT> card_img = deck_2.deck_2_list[-1] <NEW_LINE> card_img_str = str(card_img) <NEW_LINE> first_ = card_img_str.find("_") <NEW_LINE> last_ = card_img_str.rfind("_") <NEW_LINE> card_name = "playing_cards/" + card_img_str[first_ + 1:last_ + 1] + card_img_str[:first_] + ".png" <NEW_LINE> card = pygame.image.load(card_name) <NEW_LINE> screen.blit(card, (750, 300)) | pile of cards | 62598fca851cf427c66b8643 |
class AlphaBetaPlayer(IsolationPlayer): <NEW_LINE> <INDENT> def get_move(self, game, time_left): <NEW_LINE> <INDENT> self.time_left = time_left <NEW_LINE> best_move = (-1, -1) <NEW_LINE> depth = self.search_depth <NEW_LINE> try: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> best_move = self.alphabeta(game, depth) <NEW_LINE> depth += 1 <NEW_LINE> <DEDENT> <DEDENT> except SearchTimeout: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return best_move <NEW_LINE> <DEDENT> def alphabeta(self, game, depth, alpha=float("-inf"), beta=float("inf")): <NEW_LINE> <INDENT> if self.time_left() < self.TIMER_THRESHOLD: <NEW_LINE> <INDENT> raise SearchTimeout() <NEW_LINE> <DEDENT> best_move = (-1, -1) <NEW_LINE> for m in game.get_legal_moves(): <NEW_LINE> <INDENT> v = self.min_value(game.forecast_move(m), depth - 1, alpha, beta) <NEW_LINE> if v > alpha: <NEW_LINE> <INDENT> best_move, alpha = m, v <NEW_LINE> <DEDENT> <DEDENT> return best_move <NEW_LINE> <DEDENT> def terminal_test(self, game): <NEW_LINE> <INDENT> if self.time_left() < self.TIMER_THRESHOLD: <NEW_LINE> <INDENT> raise SearchTimeout() <NEW_LINE> <DEDENT> return not bool(game.get_legal_moves()) <NEW_LINE> <DEDENT> def min_value(self, game, depth, alpha, beta): <NEW_LINE> <INDENT> if self.time_left() < self.TIMER_THRESHOLD: <NEW_LINE> <INDENT> raise SearchTimeout() <NEW_LINE> <DEDENT> if self.terminal_test(game): <NEW_LINE> <INDENT> return game.utility(self) <NEW_LINE> <DEDENT> if depth == 0: <NEW_LINE> <INDENT> return self.score(game, self) <NEW_LINE> <DEDENT> v = float("inf") <NEW_LINE> for m in game.get_legal_moves(): <NEW_LINE> <INDENT> v = min(v, self.max_value(game.forecast_move(m), depth - 1, alpha, beta)) <NEW_LINE> if v <= alpha: <NEW_LINE> <INDENT> return v <NEW_LINE> <DEDENT> beta = min(beta, v) <NEW_LINE> <DEDENT> return v <NEW_LINE> <DEDENT> def max_value(self, game, depth, alpha, beta): <NEW_LINE> <INDENT> if self.time_left() < self.TIMER_THRESHOLD: <NEW_LINE> <INDENT> raise SearchTimeout() <NEW_LINE> <DEDENT> if self.terminal_test(game): <NEW_LINE> <INDENT> return game.utility(self) <NEW_LINE> <DEDENT> if depth == 0: <NEW_LINE> <INDENT> return self.score(game, self) <NEW_LINE> <DEDENT> v = float("-inf") <NEW_LINE> for m in game.get_legal_moves(): <NEW_LINE> <INDENT> v = max(v, self.min_value(game.forecast_move(m), depth - 1, alpha, beta)) <NEW_LINE> if v >= beta: <NEW_LINE> <INDENT> return v <NEW_LINE> <DEDENT> alpha = max(alpha, v) <NEW_LINE> <DEDENT> return v | Game-playing agent that chooses a move using iterative deepening minimax
search with alpha-beta pruning. You must finish and test this player to
make sure it returns a good move before the search time limit expires. | 62598fca9f28863672818a44 |
class DummymailCommand(TestCase): <NEW_LINE> <INDENT> def _call_dummymail(self, *args, **kwargs): <NEW_LINE> <INDENT> mock_process = mock.Mock() <NEW_LINE> mock_time = mock.Mock() <NEW_LINE> mock_time.sleep.side_effect = KeyboardInterrupt <NEW_LINE> with mock.patch.multiple(u'poleno.dummymail.management.commands.dummymail', Process=mock_process, time=mock_time): <NEW_LINE> <INDENT> with collect_stdout(): <NEW_LINE> <INDENT> call_command(u'dummymail', *args, **kwargs) <NEW_LINE> <DEDENT> <DEDENT> return mock_process <NEW_LINE> <DEDENT> def test_with_default_ports(self): <NEW_LINE> <INDENT> mock_process = self._call_dummymail() <NEW_LINE> self.assertItemsEqual(mock_process.mock_calls, [ mock.call(target=localmail.run, args=(1025, 1143)), mock.call().start(), mock.call(target=localmail.run, args=(2025, 2143)), mock.call().start(), ]) <NEW_LINE> <DEDENT> def test_with_explicit_ports(self): <NEW_LINE> <INDENT> mock_process = self._call_dummymail( outgoing_smtp_port=1001, outgoing_imap_port=1002, incoming_smtp_port=1003, incoming_imap_port=1004) <NEW_LINE> self.assertItemsEqual(mock_process.mock_calls, [ mock.call(target=localmail.run, args=(1001, 1002)), mock.call().start(), mock.call(target=localmail.run, args=(1003, 1004)), mock.call().start(), ]) | Tests ``dummymail`` management command. Only checks if ``localmail`` processes are spawned with
``multiprocessing`` module. Does not chech if ``localmail`` works. | 62598fca283ffb24f3cf3c15 |
class WnliProcessor(DataProcessor): <NEW_LINE> <INDENT> def get_example_from_tensor_dict(self, tensor_dict): <NEW_LINE> <INDENT> return InputExample( tensor_dict["idx"].numpy(), tensor_dict["sentence1"].numpy().decode("utf-8"), tensor_dict["sentence2"].numpy().decode("utf-8"), str(tensor_dict["label"].numpy()), ) <NEW_LINE> <DEDENT> def get_train_examples(self, data_dir): <NEW_LINE> <INDENT> return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") <NEW_LINE> <DEDENT> def get_dev_examples(self, data_dir): <NEW_LINE> <INDENT> return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") <NEW_LINE> <DEDENT> def get_labels(self): <NEW_LINE> <INDENT> return ["0", "1"] <NEW_LINE> <DEDENT> def _create_examples(self, lines, set_type): <NEW_LINE> <INDENT> examples = [] <NEW_LINE> for (i, line) in enumerate(lines): <NEW_LINE> <INDENT> if i == 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> guid = "%s-%s" % (set_type, line[0]) <NEW_LINE> text_a = line[1] <NEW_LINE> text_b = line[2] <NEW_LINE> label = line[-1] <NEW_LINE> examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) <NEW_LINE> <DEDENT> return examples | Processor for the WNLI data set (GLUE version). | 62598fca3d592f4c4edbb244 |
class TraditionalBorda(BordaBase): <NEW_LINE> <INDENT> def __init__(self, fieldsize): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.fieldsize = fieldsize <NEW_LINE> <DEDENT> def transform(self, response): <NEW_LINE> <INDENT> transformed = dict() <NEW_LINE> points = self.fieldsize - 1 <NEW_LINE> for choice in response: <NEW_LINE> <INDENT> transformed[choice] = points <NEW_LINE> points -= 1 <NEW_LINE> <DEDENT> return transformed | In a field of N choices, the highest-ranked is awarded N-1 points,
next highest-ranked N-2 points, ..., and lowest or unranked are
awarded 0. | 62598fcabe7bc26dc9252023 |
class Serial(object): <NEW_LINE> <INDENT> def __init__(self, clb): <NEW_LINE> <INDENT> self.clb = clb <NEW_LINE> self.comm = serial.Serial(port='/dev/ttyUSB0', baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=None, xonxoff=False, rtscts=False, writeTimeout=None, dsrdtr=False, interCharTimeout=None, ) <NEW_LINE> <DEDENT> def listen_forever(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> measurement = self.comm.readline() <NEW_LINE> self.clb(measurement) <NEW_LINE> <DEDENT> <DEDENT> def _generate_random_data(self): <NEW_LINE> <INDENT> import random <NEW_LINE> while True: <NEW_LINE> <INDENT> measurement = str(random.randint(-30000, 50000)) + "\n" <NEW_LINE> self.clb(measurement) <NEW_LINE> <DEDENT> <DEDENT> def read_line(self): <NEW_LINE> <INDENT> self.comm.readline() | Serial duplex communication. | 62598fca63b5f9789fe85507 |
class Question(Environment): <NEW_LINE> <INDENT> pass | Base class for all question environments. | 62598fca7cff6e4e811b5db7 |
class FastTextTrainner: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.train_data_path = "content/text.txt" <NEW_LINE> self.model_path = "model/ft.model.bin" <NEW_LINE> <DEDENT> def train(self): <NEW_LINE> <INDENT> print(f'Build sentences from {self.train_data_path}') <NEW_LINE> sentences = word2vec.Text8Corpus(self.train_data_path) <NEW_LINE> model = FastText( sentences, size=100, window=5, min_count=10, workers=6, ) <NEW_LINE> model.save(self.model_path) <NEW_LINE> print( f'Finish train model FastText\n' f'save to {self.model_path}' ) | FastText model's trinner. | 62598fca851cf427c66b8645 |
class PretrainingConfig(object): <NEW_LINE> <INDENT> def __init__(self, model_name, data_dir, **kwargs): <NEW_LINE> <INDENT> self.model_name = model_name <NEW_LINE> self.debug = False <NEW_LINE> self.do_train = True <NEW_LINE> self.do_eval = False <NEW_LINE> self.mask_prob = 0.15 <NEW_LINE> self.learning_rate = 5e-4 <NEW_LINE> self.lr_decay_power = 1.0 <NEW_LINE> self.weight_decay_rate = 0.01 <NEW_LINE> self.num_warmup_steps = 10000 <NEW_LINE> self.iterations_per_loop = 200 <NEW_LINE> self.save_checkpoints_steps = 1000 <NEW_LINE> self.num_train_steps = 1000000 <NEW_LINE> self.num_eval_steps = 100 <NEW_LINE> self.model_size = "small" <NEW_LINE> self.model_hparam_overrides = ( kwargs["model_hparam_overrides"] if "model_hparam_overrides" in kwargs else {}) <NEW_LINE> self.embedding_size = None <NEW_LINE> self.vocab_size = 30522 <NEW_LINE> self.do_lower_case = False <NEW_LINE> self.untied_generator = True <NEW_LINE> self.disallow_correct = False <NEW_LINE> self.temperature = 1.0 <NEW_LINE> self.max_seq_length = 128 <NEW_LINE> self.train_batch_size = 128 <NEW_LINE> self.eval_batch_size = 128 <NEW_LINE> self.use_tpu = False <NEW_LINE> self.num_tpu_cores = 1 <NEW_LINE> self.tpu_job_name = None <NEW_LINE> self.tpu_name = None <NEW_LINE> self.tpu_zone = None <NEW_LINE> self.gcp_project = None <NEW_LINE> self.pretrain_tfrecords = os.path.join( data_dir, "pretrain_tfrecords/pretrain_data.tfrecord*") <NEW_LINE> self.vocab_file = os.path.join(data_dir, "vocab.txt") <NEW_LINE> self.model_dir = os.path.join(data_dir, "models", model_name) <NEW_LINE> results_dir = os.path.join(self.model_dir, "results") <NEW_LINE> self.results_txt = os.path.join(results_dir, "unsup_results.txt") <NEW_LINE> self.results_pkl = os.path.join(results_dir, "unsup_results.pkl") <NEW_LINE> self.masking_strategy = "random" <NEW_LINE> self.init_checkpoint = None <NEW_LINE> self.teacher_update_rate = 0.5 <NEW_LINE> self.teacher_rate_update_step = 1000 <NEW_LINE> self.teacher_rate_decay = 0.963 <NEW_LINE> self.teacher_learning_rate = 5e-5 <NEW_LINE> self.teacher_size = "small" <NEW_LINE> self.ratio_file="" <NEW_LINE> self.update(kwargs) <NEW_LINE> self.max_predictions_per_seq = int((self.mask_prob + 0.005) * self.max_seq_length) <NEW_LINE> if self.debug: <NEW_LINE> <INDENT> self.train_batch_size = 8 <NEW_LINE> self.num_train_steps = 20 <NEW_LINE> self.eval_batch_size = 4 <NEW_LINE> self.iterations_per_loop = 1 <NEW_LINE> self.num_eval_steps = 2 <NEW_LINE> <DEDENT> if self.model_size == "small": <NEW_LINE> <INDENT> self.embedding_size = 128 <NEW_LINE> <DEDENT> self.update(kwargs) <NEW_LINE> <DEDENT> def update(self, kwargs): <NEW_LINE> <INDENT> for k, v in kwargs.items(): <NEW_LINE> <INDENT> if k not in self.__dict__: <NEW_LINE> <INDENT> raise ValueError("Unknown hparam " + k) <NEW_LINE> <DEDENT> self.__dict__[k] = v | Defines pre-training hyperparameters. | 62598fca4c3428357761a64f |
class Message: <NEW_LINE> <INDENT> def __init__(self, message): <NEW_LINE> <INDENT> self.raw_message = message <NEW_LINE> self._data = OrderedDict() <NEW_LINE> self.log = logging.getLogger('Katari') <NEW_LINE> if message: <NEW_LINE> <INDENT> self.method_line, self.headers = message.decode().split("\r\n", 1) <NEW_LINE> self._parser(self.headers) <NEW_LINE> self.sip_type = self.get_method(self.method_line) <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, item): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._data[item] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def _parser(self, message): <NEW_LINE> <INDENT> reg=re.compile('([a-zA-Z-]+):(.*)') <NEW_LINE> for header, value in dict(reg.findall(message)).items(): <NEW_LINE> <INDENT> value = value.replace('\n\r', '') <NEW_LINE> try: <NEW_LINE> <INDENT> if header.lower() == "to": <NEW_LINE> <INDENT> self._data[header.lower()] = URI(value) <NEW_LINE> <DEDENT> elif header.lower() == "from": <NEW_LINE> <INDENT> self._data[header.lower()] = URI(value) <NEW_LINE> <DEDENT> elif header.lower() == "contact": <NEW_LINE> <INDENT> self._data[header.lower()] = URI(value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._data[header.lower()] = value <NEW_LINE> <DEDENT> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> self.log.exception(err) <NEW_LINE> self.log.debug(header, value) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_method(self, methodline): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return methodline.split()[0] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass | Base message | 62598fca60cbc95b063646ce |
class TestBuildCommand(TestCase): <NEW_LINE> <INDENT> def test_command_env(self): <NEW_LINE> <INDENT> env = {'FOOBAR': 'foobar', 'BIN_PATH': 'foobar'} <NEW_LINE> cmd = BuildCommand('echo', environment=env) <NEW_LINE> for key in list(env.keys()): <NEW_LINE> <INDENT> self.assertEqual(cmd.environment[key], env[key]) <NEW_LINE> <DEDENT> <DEDENT> def test_result(self): <NEW_LINE> <INDENT> cmd = BuildCommand('true') <NEW_LINE> cmd.run() <NEW_LINE> self.assertTrue(cmd.successful) <NEW_LINE> cmd = BuildCommand('false') <NEW_LINE> cmd.run() <NEW_LINE> self.assertTrue(cmd.failed) <NEW_LINE> <DEDENT> def test_missing_command(self): <NEW_LINE> <INDENT> path = os.path.join('non-existant', str(uuid.uuid4())) <NEW_LINE> self.assertFalse(os.path.exists(path)) <NEW_LINE> cmd = BuildCommand(path) <NEW_LINE> cmd.run() <NEW_LINE> missing_re = re.compile(r'(?:No such file or directory|not found)') <NEW_LINE> self.assertRegexpMatches(cmd.error, missing_re) <NEW_LINE> <DEDENT> def test_input(self): <NEW_LINE> <INDENT> cmd = BuildCommand('/bin/cat', input_data='FOOBAR') <NEW_LINE> cmd.run() <NEW_LINE> self.assertEqual(cmd.output, 'FOOBAR') <NEW_LINE> <DEDENT> def test_output(self): <NEW_LINE> <INDENT> cmd = BuildCommand(['/bin/bash', '-c', 'echo -n FOOBAR']) <NEW_LINE> cmd.run() <NEW_LINE> self.assertEqual(cmd.output, "FOOBAR") <NEW_LINE> <DEDENT> def test_error_output(self): <NEW_LINE> <INDENT> cmd = BuildCommand(['/bin/bash', '-c', 'echo -n FOOBAR 1>&2']) <NEW_LINE> cmd.run() <NEW_LINE> self.assertEqual(cmd.output, 'FOOBAR') <NEW_LINE> self.assertIsNone(cmd.error) <NEW_LINE> cmd = BuildCommand(['/bin/bash', '-c', 'echo -n FOOBAR 1>&2'], combine_output=False) <NEW_LINE> cmd.run() <NEW_LINE> self.assertEqual(cmd.output, '') <NEW_LINE> self.assertEqual(cmd.error, 'FOOBAR') <NEW_LINE> <DEDENT> @patch('subprocess.Popen') <NEW_LINE> def test_unicode_output(self, mock_subprocess): <NEW_LINE> <INDENT> mock_process = Mock(**{ 'communicate.return_value': (SAMPLE_UTF8_BYTES, b''), }) <NEW_LINE> mock_subprocess.return_value = mock_process <NEW_LINE> cmd = BuildCommand(['echo', 'test'], cwd='/tmp/foobar') <NEW_LINE> cmd.run() <NEW_LINE> self.assertEqual( cmd.output, u'H\xe9r\xc9 \xee\xdf s\xf6m\xea \xfcn\xef\xe7\xf3\u2202\xe9') | Test build command creation | 62598fcaaad79263cf42eb60 |
class namedPersonIdType (pyxb.binding.basis.complexTypeDefinition): <NEW_LINE> <INDENT> _TypeDefinition = None <NEW_LINE> _ContentTypeTag = pyxb.binding.basis.complexTypeDefinition._CT_ELEMENT_ONLY <NEW_LINE> _Abstract = False <NEW_LINE> _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'namedPersonIdType') <NEW_LINE> _XSDLocation = pyxb.utils.utility.Location('http://www.ech.ch/xmlns/eCH-0044/1/eCH-0044-1-1.xsd', 13, 1) <NEW_LINE> _ElementMap = {} <NEW_LINE> _AttributeMap = {} <NEW_LINE> __personIdCategory = pyxb.binding.content.ElementDeclaration(pyxb.namespace.ExpandedName(Namespace, 'personIdCategory'), 'personIdCategory', '__httpwww_ech_chxmlnseCH_00441_namedPersonIdType_httpwww_ech_chxmlnseCH_00441personIdCategory', False, pyxb.utils.utility.Location('http://www.ech.ch/xmlns/eCH-0044/1/eCH-0044-1-1.xsd', 15, 3), ) <NEW_LINE> personIdCategory = property(__personIdCategory.value, __personIdCategory.set, None, None) <NEW_LINE> __personId = pyxb.binding.content.ElementDeclaration(pyxb.namespace.ExpandedName(Namespace, 'personId'), 'personId', '__httpwww_ech_chxmlnseCH_00441_namedPersonIdType_httpwww_ech_chxmlnseCH_00441personId', False, pyxb.utils.utility.Location('http://www.ech.ch/xmlns/eCH-0044/1/eCH-0044-1-1.xsd', 16, 3), ) <NEW_LINE> personId = property(__personId.value, __personId.set, None, None) <NEW_LINE> _ElementMap.update({ __personIdCategory.name() : __personIdCategory, __personId.name() : __personId }) <NEW_LINE> _AttributeMap.update({ }) | Complex type {http://www.ech.ch/xmlns/eCH-0044/1}namedPersonIdType with content type ELEMENT_ONLY | 62598fca50812a4eaa620dad |
class XRef: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.xref = 0 <NEW_LINE> self.xref_str = None <NEW_LINE> <DEDENT> def __call__(self, s): <NEW_LINE> <INDENT> value = s.strip() <NEW_LINE> if value.isdigit() and int(value): <NEW_LINE> <INDENT> self.xref = int(value) <NEW_LINE> self.xref_str = value <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.xref = 0 <NEW_LINE> self.xref_str = '' <NEW_LINE> return False <NEW_LINE> <DEDENT> <DEDENT> def get_xref(self, line: str) -> int: <NEW_LINE> <INDENT> if not line: <NEW_LINE> <INDENT> log.error("xref string is empty") <NEW_LINE> return 0 <NEW_LINE> <DEDENT> if not line.isdigit(): <NEW_LINE> <INDENT> log.error(f"xref string has invalid symbols: {line}") <NEW_LINE> return 0 <NEW_LINE> <DEDENT> self.xref = int(line) | This can be turned into a simple parse in Info | 62598fca7b180e01f3e49219 |
class QueueBindOK(Method): <NEW_LINE> <INDENT> method_type = (50, 21) <NEW_LINE> field_info = () <NEW_LINE> synchronous = True | This method confirms that the bind was successful.
| 62598fca956e5f7376df5847 |
class Transform(Result): <NEW_LINE> <INDENT> _data = delegate_ro('transform') <NEW_LINE> def transform(self, data): <NEW_LINE> <INDENT> return self._data.transform(data) | Array sub-type that represents the result of an scikit learn transform
object. | 62598fcabe7bc26dc9252024 |
class QStyleOptionTitleBar(QStyleOptionComplex): <NEW_LINE> <INDENT> def __init__(self, QStyleOptionTitleBar=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> Type = 983045 <NEW_LINE> Version = 1 | QStyleOptionTitleBar()
QStyleOptionTitleBar(QStyleOptionTitleBar) | 62598fcaa05bb46b3848abfe |
class IterationTimer(HookBase): <NEW_LINE> <INDENT> def __init__(self, warmup_iter=3): <NEW_LINE> <INDENT> self._warmup_iter = warmup_iter <NEW_LINE> self._step_timer = Timer() <NEW_LINE> self._start_time = time.perf_counter() <NEW_LINE> self._total_timer = Timer() <NEW_LINE> <DEDENT> def before_train(self): <NEW_LINE> <INDENT> self._start_time = time.perf_counter() <NEW_LINE> self._total_timer.reset() <NEW_LINE> self._total_timer.pause() <NEW_LINE> <DEDENT> def after_train(self): <NEW_LINE> <INDENT> logger = logging.getLogger(__name__) <NEW_LINE> total_time = time.perf_counter() - self._start_time <NEW_LINE> total_time_minus_hooks = self._total_timer.seconds() <NEW_LINE> hook_time = total_time - total_time_minus_hooks <NEW_LINE> num_iter = self.trainer.iter + 1 - self.trainer.start_iter - self._warmup_iter <NEW_LINE> if num_iter > 0 and total_time_minus_hooks > 0: <NEW_LINE> <INDENT> logger.info( "Overall training speed: {} iterations in {} ({:.4f} s / it)".format( num_iter, str(datetime.timedelta(seconds=int(total_time_minus_hooks))), total_time_minus_hooks / num_iter, ) ) <NEW_LINE> <DEDENT> logger.info( "Total training time: {} ({} on hooks)".format( str(datetime.timedelta(seconds=int(total_time))), str(datetime.timedelta(seconds=int(hook_time))), ) ) <NEW_LINE> <DEDENT> def before_step(self): <NEW_LINE> <INDENT> self._step_timer.reset() <NEW_LINE> self._total_timer.resume() <NEW_LINE> <DEDENT> def after_step(self): <NEW_LINE> <INDENT> iter_done = self.trainer.iter - self.trainer.start_iter + 1 <NEW_LINE> if iter_done >= self._warmup_iter: <NEW_LINE> <INDENT> sec = self._step_timer.seconds() <NEW_LINE> self.trainer.storage.put_scalars(time=sec) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._start_time = time.perf_counter() <NEW_LINE> self._total_timer.reset() <NEW_LINE> <DEDENT> self._total_timer.pause() | Track the time spent for each iteration (each run_step call in the trainer).
Print a summary in the end of training.
This hook uses the time between the call to its :meth:`before_step`
and :meth:`after_step` methods.
Under the convention that :meth:`before_step` of all hooks should only
take negligible amount of time, the :class:`IterationTimer` hook should be
placed at the beginning of the list of hooks to obtain accurate timing. | 62598fca4c3428357761a650 |
class ServiceEndpointPolicyDefinitionListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[ServiceEndpointPolicyDefinition]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(ServiceEndpointPolicyDefinitionListResult, self).__init__(**kwargs) <NEW_LINE> self.value = kwargs.get('value', None) <NEW_LINE> self.next_link = kwargs.get('next_link', None) | Response for ListServiceEndpointPolicyDefinition API service call. Retrieves all service endpoint policy definition that belongs to a service endpoint policy.
:param value: The service endpoint policy definition in a service endpoint policy.
:type value: list[~azure.mgmt.network.v2019_04_01.models.ServiceEndpointPolicyDefinition]
:param next_link: The URL to get the next set of results.
:type next_link: str | 62598fca4527f215b58ea263 |
class PositiveNaiveBayesClassifier(NLTKClassifier): <NEW_LINE> <INDENT> nltk_class = nltk.classify.PositiveNaiveBayesClassifier <NEW_LINE> def __init__(self, positive_set, unlabeled_set, feature_extractor=contains_extractor, positive_prob_prior=0.5, **kwargs): <NEW_LINE> <INDENT> self.feature_extractor = feature_extractor <NEW_LINE> self.positive_set = positive_set <NEW_LINE> self.unlabeled_set = unlabeled_set <NEW_LINE> self.positive_features = [self.extract_features(d) for d in self.positive_set] <NEW_LINE> self.unlabeled_features = [self.extract_features(d) for d in self.unlabeled_set] <NEW_LINE> self.positive_prob_prior = positive_prob_prior <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> class_name = self.__class__.__name__ <NEW_LINE> return "<{cls} trained on {n_pos} labeled and {n_unlabeled} unlabeled instances>" .format(cls=class_name, n_pos=len(self.positive_set), n_unlabeled=len(self.unlabeled_set)) <NEW_LINE> <DEDENT> def train(self, *args, **kwargs): <NEW_LINE> <INDENT> self.classifier = self.nltk_class.train(self.positive_features, self.unlabeled_features, self.positive_prob_prior) <NEW_LINE> return self.classifier <NEW_LINE> <DEDENT> def update(self, new_positive_data=None, new_unlabeled_data=None, positive_prob_prior=0.5, *args, **kwargs): <NEW_LINE> <INDENT> self.positive_prob_prior = positive_prob_prior <NEW_LINE> if new_positive_data: <NEW_LINE> <INDENT> self.positive_set += new_positive_data <NEW_LINE> self.positive_features += [self.extract_features(d) for d in new_positive_data] <NEW_LINE> <DEDENT> if new_unlabeled_data: <NEW_LINE> <INDENT> self.unlabeled_set += new_unlabeled_data <NEW_LINE> self.unlabeled_features += [self.extract_features(d) for d in new_unlabeled_data] <NEW_LINE> <DEDENT> self.classifier = self.nltk_class.train(self.positive_features, self.unlabeled_features, self.positive_prob_prior, *args, **kwargs) <NEW_LINE> return True | A variant of the Naive Bayes Classifier that performs binary
classification with partially-labeled training sets, i.e. when only
one class is labeled and the other is not. Assuming a prior distribution
on the two labels, uses the unlabeled set to estimate the frequencies of
the features.
Example usage:
::
>>> from text.classifiers import PositiveNaiveBayesClassifier
>>> sports_sentences = ['The team dominated the game',
... 'They lost the ball',
... 'The game was intense',
... 'The goalkeeper catched the ball',
... 'The other team controlled the ball']
>>> various_sentences = ['The President did not comment',
... 'I lost the keys',
... 'The team won the game',
... 'Sara has two kids',
... 'The ball went off the court',
... 'They had the ball for the whole game',
... 'The show is over']
>>> classifier = PositiveNaiveBayesClassifier(positive_set=sports_sentences,
... unlabeled_set=various_sentences)
>>> classifier.classify("My team lost the game")
True
>>> classifier.classify("And now for something completely different.")
False
:param positive_set: A collection of strings that have the positive label.
:param unlabeled_set: A collection of unlabeled strings.
:param feature_extractor: A feature extractor function.
:param positive_prob_prior: A prior estimate of the probability of the
label ``True``.
.. versionadded:: 0.7.0 | 62598fca283ffb24f3cf3c1a |
class ResourceSerializer(NsotSerializer): <NEW_LINE> <INDENT> attributes = JSONDictField( required=False, help_text='Dictionary of attributes to set.' ) <NEW_LINE> def create(self, validated_data, commit=True): <NEW_LINE> <INDENT> attributes = validated_data.pop('attributes', {}) <NEW_LINE> obj = super(ResourceSerializer, self).create(validated_data) <NEW_LINE> try: <NEW_LINE> <INDENT> obj.set_attributes(attributes) <NEW_LINE> <DEDENT> except exc.ValidationError: <NEW_LINE> <INDENT> obj.delete() <NEW_LINE> raise <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if commit: <NEW_LINE> <INDENT> obj.save() <NEW_LINE> <DEDENT> <DEDENT> return obj <NEW_LINE> <DEDENT> def update(self, instance, validated_data, commit=True): <NEW_LINE> <INDENT> attributes = validated_data.pop('attributes', None) <NEW_LINE> obj = super(ResourceSerializer, self).update( instance, validated_data ) <NEW_LINE> obj.set_attributes(attributes, partial=self.partial) <NEW_LINE> if commit: <NEW_LINE> <INDENT> obj.save() <NEW_LINE> <DEDENT> return obj | For any object that can have attributes. | 62598fcad486a94d0ba2c367 |
class Gmetric: <NEW_LINE> <INDENT> type = ('', 'string', 'uint16', 'int16', 'uint32', 'int32', 'float', 'double', 'timestamp') <NEW_LINE> protocol = ('udp', 'multicast') <NEW_LINE> def __init__(self, host, port, protocol): <NEW_LINE> <INDENT> if protocol not in self.protocol: <NEW_LINE> <INDENT> raise ValueError("Protocol must be one of: " + str(self.protocol)) <NEW_LINE> <DEDENT> self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) <NEW_LINE> if protocol == 'multicast': <NEW_LINE> <INDENT> self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 20) <NEW_LINE> <DEDENT> self.hostport = (host, int(port)) <NEW_LINE> <DEDENT> def send(self, NAME, VAL, TYPE='', UNITS='', SLOPE='both', TMAX=60, DMAX=0, GROUP="", SPOOF=""): <NEW_LINE> <INDENT> if SLOPE not in slope_str2int: <NEW_LINE> <INDENT> raise ValueError("Slope must be one of: " + str(self.slope.keys())) <NEW_LINE> <DEDENT> if TYPE not in self.type: <NEW_LINE> <INDENT> raise ValueError("Type must be one of: " + str(self.type)) <NEW_LINE> <DEDENT> if len(NAME) == 0: <NEW_LINE> <INDENT> raise ValueError("Name must be non-empty") <NEW_LINE> <DEDENT> ( meta_msg, data_msg ) = gmetric_write(NAME, VAL, TYPE, UNITS, SLOPE, TMAX, DMAX, GROUP, SPOOF) <NEW_LINE> self.socket.sendto(meta_msg, self.hostport) <NEW_LINE> self.socket.sendto(data_msg, self.hostport) | Class to send gmetric/gmond 3.X packets
Thread safe | 62598fca851cf427c66b8649 |
class _module(ModuleType): <NEW_LINE> <INDENT> def __getattr__(self, name: str) -> Any: <NEW_LINE> <INDENT> if name in object_origins: <NEW_LINE> <INDENT> module = __import__( object_origins[name], None, None, [name]) <NEW_LINE> for extra_name in all_by_module[module.__name__]: <NEW_LINE> <INDENT> setattr(self, extra_name, getattr(module, extra_name)) <NEW_LINE> <DEDENT> return getattr(module, name) <NEW_LINE> <DEDENT> return ModuleType.__getattribute__(self, name) <NEW_LINE> <DEDENT> def __dir__(self) -> Sequence[str]: <NEW_LINE> <INDENT> result = list(new_module.__all__) <NEW_LINE> result.extend(('__file__', '__path__', '__doc__', '__all__', '__docformat__', '__name__', '__path__', 'VERSION', 'version_info_t', 'version_info', '__package__', '__version__', '__author__', '__contact__', '__homepage__', '__docformat__')) <NEW_LINE> return result | Customized Python module. | 62598fcafbf16365ca79444f |
class _ModerationBase: <NEW_LINE> <INDENT> def _make_resource(self, request_id): <NEW_LINE> <INDENT> requests = IListRequests(self._mlist) <NEW_LINE> results = requests.get_request(request_id) <NEW_LINE> if results is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> key, data = results <NEW_LINE> resource = dict(key=key, request_id=request_id) <NEW_LINE> resource.update(data) <NEW_LINE> request_type = RequestType[resource.pop('_request_type')] <NEW_LINE> if request_type is not RequestType.held_message: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> resource['type'] = RequestType.held_message.name <NEW_LINE> resource.pop('id', None) <NEW_LINE> return resource | Common base class. | 62598fca23849d37ff851447 |
class MatrixCalculus(MatrixCommon): <NEW_LINE> <INDENT> def diff(self, *args, **kwargs): <NEW_LINE> <INDENT> from sympy.tensor.array.array_derivatives import ArrayDerivative <NEW_LINE> kwargs.setdefault('evaluate', True) <NEW_LINE> deriv = ArrayDerivative(self, *args, evaluate=True) <NEW_LINE> if not isinstance(self, Basic): <NEW_LINE> <INDENT> return deriv.as_mutable() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return deriv <NEW_LINE> <DEDENT> <DEDENT> def _eval_derivative(self, arg): <NEW_LINE> <INDENT> return self.applyfunc(lambda x: x.diff(arg)) <NEW_LINE> <DEDENT> def integrate(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.applyfunc(lambda x: x.integrate(*args, **kwargs)) <NEW_LINE> <DEDENT> def jacobian(self, X): <NEW_LINE> <INDENT> if not isinstance(X, MatrixBase): <NEW_LINE> <INDENT> X = self._new(X) <NEW_LINE> <DEDENT> if self.shape[0] == 1: <NEW_LINE> <INDENT> m = self.shape[1] <NEW_LINE> <DEDENT> elif self.shape[1] == 1: <NEW_LINE> <INDENT> m = self.shape[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError("``self`` must be a row or a column matrix") <NEW_LINE> <DEDENT> if X.shape[0] == 1: <NEW_LINE> <INDENT> n = X.shape[1] <NEW_LINE> <DEDENT> elif X.shape[1] == 1: <NEW_LINE> <INDENT> n = X.shape[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError("X must be a row or a column matrix") <NEW_LINE> <DEDENT> return self._new(m, n, lambda j, i: self[j].diff(X[i])) <NEW_LINE> <DEDENT> def limit(self, *args): <NEW_LINE> <INDENT> return self.applyfunc(lambda x: x.limit(*args)) | Provides calculus-related matrix operations. | 62598fca3346ee7daa337812 |
class DagsterTypeLoader(ABC): <NEW_LINE> <INDENT> @property <NEW_LINE> @abstractmethod <NEW_LINE> def schema_type(self) -> ConfigType: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @property <NEW_LINE> def loader_version(self) -> Optional[str]: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def compute_loaded_input_version(self, _config_value: object) -> Optional[str]: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def construct_from_config_value( self, _context: "StepExecutionContext", config_value: object ) -> object: <NEW_LINE> <INDENT> return config_value <NEW_LINE> <DEDENT> def required_resource_keys(self) -> AbstractSet[str]: <NEW_LINE> <INDENT> return frozenset() | Dagster type loaders are used to load unconnected inputs of the dagster type they are attached
to.
The recommended way to define a type loader is with the
:py:func:`@dagster_type_loader <dagster_type_loader>` decorator. | 62598fca0fa83653e46f527c |
class SVM(): <NEW_LINE> <INDENT> def __init__(self, C=1, kernel="rbf", gamma=1.0, num_iters=100): <NEW_LINE> <INDENT> self.kernel = kernel <NEW_LINE> self.gamma = gamma <NEW_LINE> self.alpha = None <NEW_LINE> self.bias = 0 <NEW_LINE> self.kernel_matrix = None <NEW_LINE> self.C = C <NEW_LINE> self.tol= 0.001 <NEW_LINE> self.num_train = None <NEW_LINE> self.num_iters = num_iters <NEW_LINE> self.support_vectors = None <NEW_LINE> <DEDENT> def hypothesis_func(self, x): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def evaluate_kernel_value(self, x, z): <NEW_LINE> <INDENT> if self.gamma == 0: <NEW_LINE> <INDENT> raise Exception("The gamma value of 0.0 is inavlid, you can try set gamma to a value of 1/n_features default") <NEW_LINE> <DEDENT> if self.kernel == "rbf": <NEW_LINE> <INDENT> return np.exp((x - z).dot((x - z).T) / (-2.0 * self.gamma**2)) <NEW_LINE> <DEDENT> elif self.kernel == "polynomial": <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif self.kernel == "linear": <NEW_LINE> <INDENT> return x.dot(z.T) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("The kernel type of %s is not supported" % opt) <NEW_LINE> <DEDENT> <DEDENT> def gen_kernel_matrix(self, X): <NEW_LINE> <INDENT> self.kernel_matrix = np.ones((self.num_train, self.num_train)) <NEW_LINE> for i in range(self.num_train): <NEW_LINE> <INDENT> x_i = X[i] <NEW_LINE> for j in range(i, self.num_train): <NEW_LINE> <INDENT> x_j = X[j] <NEW_LINE> self.kernel_matrix[i, j] = self.evaluate_kernel_value(x_i, x_j) <NEW_LINE> self.kernel_matrix[j, i] = self.kernel_matrix[i, j] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def train(self, X, Y): <NEW_LINE> <INDENT> self.num_train = X.shape[0] <NEW_LINE> self.alpha = np.zeros((self.num_train, 1)) <NEW_LINE> self.gen_kernel_matrix(X) <NEW_LINE> smo = SMO(self.alpha, self.bias, self.kernel_matrix, self.C, self.num_train, self.num_iters, self.tol, Y) <NEW_LINE> self.alpha, self.bias = smo.optimize() <NEW_LINE> sv_idx = np.nonzero((self.alpha > 0) * (self.alpha < self.C))[0] <NEW_LINE> self.support_vectors = X[sv_idx] | Support Vector Machine | 62598fca50812a4eaa620daf |
class Player(Actuator): <NEW_LINE> <INDENT> class States(Enum): <NEW_LINE> <INDENT> playing = 0, <NEW_LINE> stopped = 1, <NEW_LINE> paused = 2, <NEW_LINE> unknown = None <NEW_LINE> <DEDENT> __COMMAND_LIST = ("toggle", "activate", "deactivate", "set_volume", "play", "stop", "pause", "next", "prev", "seek") <NEW_LINE> def __init__(self, con_instance, con_params, metadata=None): <NEW_LINE> <INDENT> super().__init__(con_instance, con_params, metadata) <NEW_LINE> <DEDENT> @property <NEW_LINE> def actions(self) -> tuple: <NEW_LINE> <INDENT> return self.__COMMAND_LIST <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_active(self) -> bool: <NEW_LINE> <INDENT> return self.state == self.States.playing <NEW_LINE> <DEDENT> @property <NEW_LINE> def volume(self) -> int: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @property <NEW_LINE> def source(self) -> str: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @property <NEW_LINE> def title(self) -> str: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @property <NEW_LINE> def artist(self) -> str or None: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @property <NEW_LINE> def album(self) -> str or None: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @property <NEW_LINE> def elapsed(self) -> float: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @property <NEW_LINE> def duration(self) -> float: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def to_dict(self) -> dict: <NEW_LINE> <INDENT> result = super().to_dict() <NEW_LINE> result["volume"] = self.volume <NEW_LINE> result["source"] = self.source <NEW_LINE> result["title"] = self.title <NEW_LINE> result["artist"] = self.artist <NEW_LINE> result["album"] = self.album <NEW_LINE> result["elapsed"] = self.elapsed <NEW_LINE> result["duration"] = self.duration <NEW_LINE> return result <NEW_LINE> <DEDENT> def set_volume(self, value: int) -> Actuator.ExecutionResult: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def play(self) -> Actuator.ExecutionResult: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def stop(self) -> Actuator.ExecutionResult: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def pause(self) -> Actuator.ExecutionResult: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def next(self) -> Actuator.ExecutionResult: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def prev(self) -> Actuator.ExecutionResult: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def seek(self, track_pos: float) -> Actuator.ExecutionResult: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def activate(self) -> Actuator.ExecutionResult: <NEW_LINE> <INDENT> return self.play() <NEW_LINE> <DEDENT> def deactivate(self) -> Actuator.ExecutionResult: <NEW_LINE> <INDENT> return self.pause() <NEW_LINE> <DEDENT> def toggle(self) -> Actuator.ExecutionResult: <NEW_LINE> <INDENT> if self.state == self.States.unknown: <NEW_LINE> <INDENT> warnings.warn("Unknown state handling may be deleted", FutureWarning) <NEW_LINE> logger.debug( "Unable to toggle %s object from %s state", self, self.state ) <NEW_LINE> return Actuator.ExecutionResult.IGNORED_BAD_STATE <NEW_LINE> <DEDENT> return super().toggle() | Плеер. Объект, который проигрывает медиафайлы | 62598fca63b5f9789fe8550d |
class TaskItem(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=200) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name | 読書、勉強、執筆等
| 62598fca71ff763f4b5e7b17 |
class customerProp(SchemaProperty): <NEW_LINE> <INDENT> _prop_schema = 'customer' <NEW_LINE> _expected_schema = 'Organization' <NEW_LINE> _enum = False <NEW_LINE> _format_as = "ForeignKey" | SchemaField for customer
Usage: Include in SchemaObject SchemaFields as your_django_field = customerProp()
schema.org description:Party placing the order or paying the invoice.
prop_schema returns just the property without url#
format_as is used by app templatetags based upon schema.org datatype
used to reference Organization | 62598fca377c676e912f6f42 |
class UrlPostHandler(webapp2.RequestHandler): <NEW_LINE> <INDENT> form_fields = { 'first_name': 'Albert', 'last_name': 'Johnson', } <NEW_LINE> def get(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> form_data = urllib.urlencode(UrlPostHandler.form_fields) <NEW_LINE> headers = {'Content-Type': 'application/x-www-form-urlencoded'} <NEW_LINE> result = urlfetch.fetch( url='http://localhost:8080/submit_form', payload=form_data, method=urlfetch.POST, headers=headers) <NEW_LINE> self.response.write(result.content) <NEW_LINE> <DEDENT> except urlfetch.Error: <NEW_LINE> <INDENT> logging.exception('Caught exception fetching url') | Demonstrates an HTTP POST form query using urlfetch | 62598fcb283ffb24f3cf3c1d |
class DictAction(Action): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def _parse_int_float_bool(val): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return int(val) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return float(val) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> if val.lower() in ['true', 'false']: <NEW_LINE> <INDENT> return True if val.lower() == 'true' else False <NEW_LINE> <DEDENT> return val <NEW_LINE> <DEDENT> def __call__(self, parser, namespace, values, option_string=None): <NEW_LINE> <INDENT> options = {} <NEW_LINE> for kv in values: <NEW_LINE> <INDENT> key, val = kv.split('=', maxsplit=1) <NEW_LINE> val = [self._parse_int_float_bool(v) for v in val.split(',')] <NEW_LINE> if len(val) == 1: <NEW_LINE> <INDENT> val = val[0] <NEW_LINE> <DEDENT> options[key] = val <NEW_LINE> <DEDENT> setattr(namespace, self.dest, options) | argparse action to split an argument into KEY=VALUE form
on the first = and append to a dictionary. List options should
be passed as comma separated values, i.e KEY=V1,V2,V3 | 62598fcb0fa83653e46f527e |
class Handler: <NEW_LINE> <INDENT> async def get_all_records(self, request) -> Response: <NEW_LINE> <INDENT> offset = request.rel_url.query.get('offset', 0) <NEW_LINE> limit = request.rel_url.query.get('limit', 10) <NEW_LINE> async with request.app['pool'].acquire() as connection: <NEW_LINE> <INDENT> result = await models.get_all_records(connection, int(limit), int(offset)) <NEW_LINE> <DEDENT> return Response(status=200, body=json.dumps({ 'records': result }), content_type='application/json') <NEW_LINE> <DEDENT> async def post_record(self, request) -> Response: <NEW_LINE> <INDENT> data = await request.json() <NEW_LINE> record_date = data['applicable_date'] <NEW_LINE> async with request.app['pool'].acquire() as connection: <NEW_LINE> <INDENT> instance = await models.get_record_by_date(connection, record_date) <NEW_LINE> if instance: <NEW_LINE> <INDENT> return Response( status=422, body=json.dumps({'Record already exists': 422}), content_type='application/json') <NEW_LINE> <DEDENT> res = await models.insert_record(connection, data) <NEW_LINE> <DEDENT> if not res[0]: <NEW_LINE> <INDENT> return Response(status=500, body=json.dumps({res[1]: 500}), content_type='application/json') <NEW_LINE> <DEDENT> return Response(status=201, body=json.dumps({'success': 201}), content_type='application/json') <NEW_LINE> <DEDENT> async def get_record(self, request) -> Response: <NEW_LINE> <INDENT> today = datetime.datetime.today().strftime( request.app['config']['date_const']['str_date_db']) <NEW_LINE> instance_date = request.match_info.get('date', today) <NEW_LINE> async with request.app['pool'].acquire() as connection: <NEW_LINE> <INDENT> instance = await models.get_record_by_date(connection, instance_date) <NEW_LINE> <DEDENT> if not instance: <NEW_LINE> <INDENT> return Response(status=404, body=json.dumps({'not found': 404}), content_type='application/json') <NEW_LINE> <DEDENT> return Response(status=200, body=json.dumps({'records': instance}), content_type='application/json') <NEW_LINE> <DEDENT> async def put_record(self, request) -> Response: <NEW_LINE> <INDENT> data = await request.json() <NEW_LINE> instance_date = request.match_info.get('date', None) <NEW_LINE> async with request.app['pool'].acquire() as connection: <NEW_LINE> <INDENT> instance = await models.get_record_by_date(connection, instance_date) <NEW_LINE> <DEDENT> if not instance: <NEW_LINE> <INDENT> return Response(status=404, body=json.dumps({'not found': 404}), content_type='application/json') <NEW_LINE> <DEDENT> async with request.app['pool'].acquire() as connection: <NEW_LINE> <INDENT> instance = await models.update_record(connection, data) <NEW_LINE> <DEDENT> return Response(status=201, body=json.dumps(instance), content_type='application/json') <NEW_LINE> <DEDENT> async def delete_record(self, request) -> Response: <NEW_LINE> <INDENT> instance_date = request.match_info.get('date', None) <NEW_LINE> async with request.app['pool'].acquire() as connection: <NEW_LINE> <INDENT> instance = await models.get_record_by_date(connection, instance_date) <NEW_LINE> if not instance: <NEW_LINE> <INDENT> return Response(status=404, body=json.dumps({'not found': 404}), content_type='application/json') <NEW_LINE> <DEDENT> await models.delete_record(connection, instance_date) <NEW_LINE> <DEDENT> return Response(status=204, body=json.dumps({'Success': 204}), content_type='application/json') | handler to routes | 62598fcbdc8b845886d53954 |
class AnyURLScheme(object): <NEW_LINE> <INDENT> def __contains__(self, item): <NEW_LINE> <INDENT> if not item or not re.match(r'^[a-z][0-9a-z+\-.]*$', item.lower()): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True | A fake URL list which "contains" all scheme names abiding by the syntax defined in RFC 3986 section 3.1 | 62598fcb71ff763f4b5e7b19 |
class AttrsMixin(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def node_attributes_dict(self, x): <NEW_LINE> <INDENT> return dict(self.node_attributes(x)) <NEW_LINE> <DEDENT> def edge_attributes_dict(self, x): <NEW_LINE> <INDENT> return dict(self.edge_attributes(x)) <NEW_LINE> <DEDENT> def _attrs(self, x): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def type(self, x): <NEW_LINE> <INDENT> return self._attrs(x)['type'] <NEW_LINE> <DEDENT> def is_cdu(self, x): <NEW_LINE> <INDENT> return self.type(x) == 'CDU' <NEW_LINE> <DEDENT> def is_edu(self, x): <NEW_LINE> <INDENT> return self.type(x) == 'EDU' <NEW_LINE> <DEDENT> def is_relation(self, x): <NEW_LINE> <INDENT> return self.type(x) == 'rel' <NEW_LINE> <DEDENT> def annotation(self, x): <NEW_LINE> <INDENT> return self._attrs(x)['annotation'] <NEW_LINE> <DEDENT> def mirror(self, x): <NEW_LINE> <INDENT> return self._attrs(x)['mirror'] <NEW_LINE> <DEDENT> def node(self, x): <NEW_LINE> <INDENT> return self.nodeform(x) <NEW_LINE> <DEDENT> def nodeform(self, x): <NEW_LINE> <INDENT> if self.has_node(x): <NEW_LINE> <INDENT> return x <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.mirror(x) <NEW_LINE> <DEDENT> <DEDENT> def edgeform(self, x): <NEW_LINE> <INDENT> if self.has_edge(x): <NEW_LINE> <INDENT> return x <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.mirror(x) | Attributes common to both the hypergraph and directed graph
representation of discourse structure | 62598fcbadb09d7d5dc0a913 |
class PyupgradeRunner(ToolRunner): <NEW_LINE> <INDENT> def _validate_config(self: PyupgradeRunner) -> None: <NEW_LINE> <INDENT> if "min_version" in self.config and not re.match( r"^[0-9].[0-9]", self.config["min_version"] ): <NEW_LINE> <INDENT> raise ValueError("min_version must be a valid Python version!") <NEW_LINE> <DEDENT> <DEDENT> def run(self: PyupgradeRunner) -> ToolResult: <NEW_LINE> <INDENT> self._validate_config() <NEW_LINE> logger: ToolLogger = self.make_logger(TextIOLogger, logging.INFO) <NEW_LINE> with patch("sys.stdout", logger), patch("sys.stderr", logger): <NEW_LINE> <INDENT> retcode: int = 0 <NEW_LINE> for src_path in self.src_paths: <NEW_LINE> <INDENT> retcode |= pyupgrade_fix_file( src_path, Namespace( exit_zero_even_if_changed=self.config.get( "exit_zero_even_if_changed", None ), keep_mock=self.config.get("keep_mock", None), keep_percent_format=self.config.get( "keep_percent_format", None ), keep_runtime_typing=self.config.get( "keep_runtime_typing", None ), min_version=tuple( int(v) for v in cast( str, self.config.get("min_version", "2.7") ).split(".") ), ), ) <NEW_LINE> <DEDENT> return ToolResult.SUCCESS if retcode == 0 else ToolResult.FAILURE | Runs Pyupgrade.
Pyupgrade automatically upgrades Python syntax to the latest for the
specified Python version. | 62598fcbcc40096d6161a3a4 |
class ConfigureForm(form.PageForm): <NEW_LINE> <INDENT> base_template = form.EditForm.template <NEW_LINE> template = ViewPageTemplateFile('configure.pt') <NEW_LINE> subforms = [] <NEW_LINE> form_fields = form.Fields( schema.List(__name__=u'pluginNames', title=u'Plugin Names', value_type=schema.Choice( __name__=u'pluginName', title=_(u'Plugin Name'), vocabulary="Configurator Plugin Names") )) <NEW_LINE> workDone = False <NEW_LINE> @property <NEW_LINE> def _pluginNames(self): <NEW_LINE> <INDENT> names = self.request.form.get(self.prefix + '.pluginNames') <NEW_LINE> if names and not type(names) is type([]): <NEW_LINE> <INDENT> return [names] <NEW_LINE> <DEDENT> return names <NEW_LINE> <DEDENT> def setUpWidgets(self, ignore_request=False): <NEW_LINE> <INDENT> if self._pluginNames: <NEW_LINE> <INDENT> plugins = configurator.requiredPlugins(self.context, self._pluginNames) <NEW_LINE> self.subforms = [] <NEW_LINE> for name, factory in plugins: <NEW_LINE> <INDENT> plugin = factory(self.context) <NEW_LINE> if not interfaces.ISchemaConfigurationPlugin.providedBy( plugin): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> subform = PluginSchemaForm(context=self.context, request=self.request, plugin=plugin, prefix=name) <NEW_LINE> subform.form_fields = form.Fields(plugin.schema) <NEW_LINE> self.subforms.append(subform) <NEW_LINE> <DEDENT> <DEDENT> super(ConfigureForm, self).setUpWidgets(ignore_request=ignore_request) <NEW_LINE> <DEDENT> @form.action(_("Update")) <NEW_LINE> def handleUpdate(self, action, data): <NEW_LINE> <INDENT> if not self._pluginNames: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.setUpWidgets(ignore_request=False) <NEW_LINE> result = self.template() <NEW_LINE> return result <NEW_LINE> <DEDENT> def _pluginsSelected(self, action): <NEW_LINE> <INDENT> return not not self.request.form.get(self.prefix + '.pluginNames') <NEW_LINE> <DEDENT> @form.action(_("Apply"), condition='_pluginsSelected') <NEW_LINE> def handleApply(self, action, data): <NEW_LINE> <INDENT> configuratorData = {} <NEW_LINE> for subform in self.subforms: <NEW_LINE> <INDENT> subform.update() <NEW_LINE> formData = {} <NEW_LINE> errors = form.getWidgetsData(subform.widgets, subform.prefix, formData) <NEW_LINE> configuratorData[subform.prefix] = formData <NEW_LINE> <DEDENT> configurator.configure(self.context, configuratorData, names=self._pluginNames, useNameSpaces=True) <NEW_LINE> self.status = u'Applied: %s' % u' '.join(self._pluginNames) | Configurator Plugin form | 62598fcb5fc7496912d48446 |
class OrderModelTests(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.mockTable = mommy.make("table.Table") <NEW_LINE> self.mockFood = mommy.make("menu.Food") <NEW_LINE> self.validOrder = Order(table=self.mockTable, food=self.mockFood) <NEW_LINE> <DEDENT> def testConstructor(self): <NEW_LINE> <INDENT> self.assertEqual(self.validOrder.table, self.mockTable) <NEW_LINE> self.assertEqual(self.validOrder.food, self.mockFood) | Unit tests for the Booking model class. | 62598fcb63b5f9789fe85511 |
class insertManufacturer_result(object): <NEW_LINE> <INDENT> def __init__(self, success=None, error=None, error2=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> self.error = error <NEW_LINE> self.error2 = error2 <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.success = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.error = DatabaseError() <NEW_LINE> self.error.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.error2 = ValidationError() <NEW_LINE> self.error2.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('insertManufacturer_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.STRING, 0) <NEW_LINE> oprot.writeString(self.success.encode('utf-8') if sys.version_info[0] == 2 else self.success) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.error is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('error', TType.STRUCT, 1) <NEW_LINE> self.error.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.error2 is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('error2', TType.STRUCT, 2) <NEW_LINE> self.error2.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- success
- error
- error2 | 62598fcba05bb46b3848ac06 |
class SpecialException01(Exception): <NEW_LINE> <INDENT> pass | Special exception type. | 62598fcb55399d3f056268b4 |
class RPolspline(RPackage): <NEW_LINE> <INDENT> homepage = "https://cloud.r-project.org/package=polspline" <NEW_LINE> url = "https://cloud.r-project.org/src/contrib/polspline_1.1.18.tar.gz" <NEW_LINE> list_url = "https://cloud.r-project.org/src/contrib/Archive/polspline" <NEW_LINE> version('1.1.19', sha256='953e3c4d007c3ef86ac2af3c71b272a99e8e35b194bdd58575785558c6711f66') <NEW_LINE> version('1.1.18', sha256='df250ee144bfff154249ba50308f46863107ef3efb2333ad908e599ed0eb0102') <NEW_LINE> version('1.1.17', sha256='d67b269d01105d4a6ea774737e921e66e065a859d1931ae38a70f88b6fb7ee30') <NEW_LINE> version('1.1.16', sha256='aa3b5a1560008a1a401a65a25f19a27ba6f0a6ea185b6d093acd40e4e2818934') <NEW_LINE> version('1.1.15', sha256='8cdbaa5ee672055a4d02f965025199ce764958f84bfa159e853feba7ee24faa7') | Polynomial Spline Routines
Routines for the polynomial spline fitting routines hazard regression,
hazard estimation with flexible tails, logspline, lspec, polyclass, and
polymars, by C. Kooperberg and co-authors. | 62598fcb3346ee7daa337815 |
class RatingStar(models.Model): <NEW_LINE> <INDENT> value = models.SmallIntegerField('Значение', default=0) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return f'{self.value}' <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = 'Звезда рейтинга' <NEW_LINE> verbose_name_plural = 'Звезды рейтинга' <NEW_LINE> ordering = ['-value'] | Звезды рейтинга | 62598fcb8a349b6b436865dc |
class TestTlogRec: <NEW_LINE> <INDENT> orig_hostname = socket.gethostname() <NEW_LINE> tempdir = mkdtemp(prefix='/tmp/TestTlogRec.') <NEW_LINE> user1 = TLOG_TEST_LOCAL_USER <NEW_LINE> admin1 = TLOG_TEST_LOCAL_ADMIN <NEW_LINE> os.chmod(tempdir, stat.S_IRWXU + stat.S_IRWXG + stat.S_IRWXO + stat.S_ISUID + stat.S_ISGID + stat.S_ISVTX) <NEW_LINE> def test_conf_file_var(self, rec_env_config_setup): <NEW_LINE> <INDENT> logfile = mklogfile(self.tempdir) <NEW_LINE> msg = inspect.stack()[0][3] <NEW_LINE> tmp_conf_file = TMP_TLOG_REC_CONF <NEW_LINE> recclass_system = TlogRecConfig(writer="journal") <NEW_LINE> recclass_system.generate_config(SYSTEM_TLOG_REC_CONF) <NEW_LINE> recclass_tmp = TlogRecConfig(writer="file", file_writer_path=logfile) <NEW_LINE> recclass_tmp.generate_config(tmp_conf_file) <NEW_LINE> shell = ssh_pexpect(self.user1, 'Secret123', 'localhost') <NEW_LINE> shell.sendline(f'export TLOG_REC_CONF_FILE={tmp_conf_file}') <NEW_LINE> shell.sendline(TLOG_REC_PROG + f"-c echo {msg}") <NEW_LINE> check_recording(shell, msg, logfile) <NEW_LINE> shell.close() <NEW_LINE> <DEDENT> def test_conf_text_var(self, rec_env_config_setup): <NEW_LINE> <INDENT> logfile = mklogfile(self.tempdir) <NEW_LINE> msg = inspect.stack()[0][3] <NEW_LINE> tmp_conf_file = TMP_TLOG_REC_CONF <NEW_LINE> recclass_system = TlogRecConfig(writer="journal") <NEW_LINE> recclass_system.generate_config(SYSTEM_TLOG_REC_CONF) <NEW_LINE> recclass_tmp = TlogRecSessionConfig(writer="syslog") <NEW_LINE> recclass_tmp.generate_config(tmp_conf_file) <NEW_LINE> shell = ssh_pexpect(self.user1, 'Secret123', 'localhost') <NEW_LINE> shell.sendline(f'export TLOG_REC_CONF_FILE={tmp_conf_file}') <NEW_LINE> shell.sendline('export TLOG_REC_CONF_TEXT=\'{"writer":"file"}\'') <NEW_LINE> shell.sendline(TLOG_REC_PROG + f"-c echo {msg}") <NEW_LINE> check_recording(shell, msg, logfile) <NEW_LINE> shell.close() <NEW_LINE> <DEDENT> def test_conf_shell_var(self, session_env_config_setup): <NEW_LINE> <INDENT> input_shell = "/bin/tcsh" <NEW_LINE> recclass = TlogRecConfig(writer="journal") <NEW_LINE> recclass.generate_config(SYSTEM_TLOG_REC_CONF) <NEW_LINE> shell = ssh_pexpect(self.user1, 'Secret123', 'localhost') <NEW_LINE> shell.sendline(f'export SHELL={input_shell}') <NEW_LINE> shell.sendline(TLOG_REC_PROG) <NEW_LINE> shell.sendline("echo $SHELL") <NEW_LINE> shell.expect(input_shell) <NEW_LINE> shell.sendline('exit') <NEW_LINE> shell.close() | tlog-rec tests | 62598fcbab23a570cc2d4f3c |
class RecruitSpider(scrapy.Spider): <NEW_LINE> <INDENT> name = "tencent" <NEW_LINE> allowed_domains = ["hr.tencent.com"] <NEW_LINE> start_urls = [ "https://hr.tencent.com/position.php?&start=0#a", ] <NEW_LINE> def parse(self,response): <NEW_LINE> <INDENT> for sel in response.xpath('//*[@class="even"]'): <NEW_LINE> <INDENT> name = sel.xpath("./td[1]/a/text()").extract_first() <NEW_LINE> detailLink = sel.xpath("./td[1]/a/@href").extract_first() <NEW_LINE> catalog = sel.xpath("./td[2]/text()").extract_first() <NEW_LINE> recruitNumber = sel.xpath('./td[3]/text()').extract_first() <NEW_LINE> workLocation = sel.xpath('./td[4]/text()').extract_first() <NEW_LINE> publishTime = sel.xpath('./td[5]/text()').extract_first() <NEW_LINE> item = RecruitItem() <NEW_LINE> item['name'] = name <NEW_LINE> item['detailLink'] = detailLink <NEW_LINE> item['catalog'] = catalog <NEW_LINE> item['recruitNumber'] = recruitNumber <NEW_LINE> item['workLocation'] = workLocation <NEW_LINE> item['publishTime'] = publishTime <NEW_LINE> yield item <NEW_LINE> <DEDENT> next = response.css('.pagenav #next::attr(href)').extract_first() <NEW_LINE> url = "https://hr.tencent.com/" + next <NEW_LINE> yield scrapy.Request(url,self.parse) | 创建一个Spider,继承自scrapy.Spider | 62598fcb3617ad0b5ee064e4 |
class GenericTest(TestCase): <NEW_LINE> <INDENT> def test_version(self): <NEW_LINE> <INDENT> self.assertEqual(sys.modules['postman'].__version__, "2.1.1") | Usual generic tests. | 62598fcb283ffb24f3cf3c22 |
class Student: <NEW_LINE> <INDENT> def __init__(self, line): <NEW_LINE> <INDENT> studentInfo = line.split(",") <NEW_LINE> if len(studentInfo) != 6: <NEW_LINE> <INDENT> sys.exit("Error: Invalid student file format") <NEW_LINE> <DEDENT> self.line = line <NEW_LINE> self.stLastName = studentInfo[0] <NEW_LINE> self.stFirstName = studentInfo[1] <NEW_LINE> self.grade = studentInfo[2] <NEW_LINE> self.classroom = studentInfo[3] <NEW_LINE> self.bus = studentInfo[4] <NEW_LINE> self.gpa = float(studentInfo[5]) <NEW_LINE> self.teachers = None <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> teach_string = "" <NEW_LINE> for teacher in self.teachers: <NEW_LINE> <INDENT> teach_string += teacher.__repr__() <NEW_LINE> <DEDENT> return "\n\t("+self.line+", "+ teach_string + ")\n" | class for student object | 62598fcb377c676e912f6f45 |
class TestXmlRpc(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> from django.core.files.base import ContentFile <NEW_LINE> self.dummy_file = ContentFile("gibberish") <NEW_LINE> self.dummy_user = User.objects.create(username='bobby', password='tables', email='bobby@tables.com') <NEW_LINE> self.pkg = Package.objects.create(name='foo') <NEW_LINE> self.pkg.owners.add(self.dummy_user) <NEW_LINE> self.release = Release.objects.create(package=self.pkg, version="1.0") <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.release.delete() <NEW_LINE> self.pkg.delete() <NEW_LINE> self.dummy_user.delete() <NEW_LINE> <DEDENT> def test_list_package(self): <NEW_LINE> <INDENT> pypi = xmlrpclib.ServerProxy("http://localhost/pypi/", ProxiedTransport()) <NEW_LINE> pypi_hits = pypi.list_packages() <NEW_LINE> expected = ['foo'] <NEW_LINE> self.assertEqual(pypi_hits, expected) <NEW_LINE> <DEDENT> def test_package_releases(self): <NEW_LINE> <INDENT> pypi = xmlrpclib.ServerProxy("http://localhost/pypi/", ProxiedTransport()) <NEW_LINE> pypi_hits = pypi.package_releases('foo') <NEW_LINE> expected = ['1.0'] <NEW_LINE> self.assertEqual(pypi_hits, expected) | Test that the server responds to xmlrpc requests | 62598fcb4c3428357761a65a |
class EchoError(Exception): <NEW_LINE> <INDENT> pass | Something wrong connecting to echobox | 62598fcb5fdd1c0f98e5e32a |
class GetFxNBP(GetFX): <NEW_LINE> <INDENT> def __init__(self, currency=DEFAULT_CURRENCY, date=None): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._get_response(currency, date) <NEW_LINE> <DEDENT> def _delete(self): <NEW_LINE> <INDENT> print("--Teardown--") <NEW_LINE> <DEDENT> def _get_request_url(self, currency, date): <NEW_LINE> <INDENT> if date: <NEW_LINE> <INDENT> url = "/".join([NBP_API_URL, currency, date]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> url = "/".join([NBP_API_URL, currency]) <NEW_LINE> <DEDENT> return url <NEW_LINE> <DEDENT> def _store_response(self, resp): <NEW_LINE> <INDENT> api_resp = resp.json()["rates"][0] <NEW_LINE> self._table_number = api_resp["no"] <NEW_LINE> self._effective_date = api_resp["effectiveDate"] <NEW_LINE> self._rate = api_resp["mid"] <NEW_LINE> self._currency_code = resp.json()["code"] <NEW_LINE> <DEDENT> def _get_response(self, currency, date=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> resp = requests.get(self._get_request_url(currency, date)) <NEW_LINE> self._store_response(resp) <NEW_LINE> <DEDENT> except requests.exceptions.ConnectionError: <NEW_LINE> <INDENT> print("No connection to NBP API!") <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if resp.status_code == 404: <NEW_LINE> <INDENT> raise ValueError( "Incorrect currency code: {} or date: {}".format( currency, date ) ) | Subclass of :py:class:`~getfx.getfx.GetFX` class to implement NBP
specific FX retrieval logic.
It does not provide public methods, instead it is assumed when instance is
created, NBP API is invoked and FX rate retrieved. Access to retrieved rate
is achieved via printing the instance using overridden: :py:meth:`.__str__`
method. | 62598fcbfbf16365ca794457 |
class Debugger(nn.Module): <NEW_LINE> <INDENT> def forward(self,x:Tensor) -> Tensor: <NEW_LINE> <INDENT> set_trace() <NEW_LINE> return x | A module to debug inside a model | 62598fcb5fc7496912d48448 |
class SPI(object): <NEW_LINE> <INDENT> __LOCK_TIMEOUT = 10.0 <NEW_LINE> def __init__(self, bus, device, mode, max_speed): <NEW_LINE> <INDENT> self.__bus = bus <NEW_LINE> self.__device = device <NEW_LINE> self.__mode = mode <NEW_LINE> self.__max_speed = max_speed <NEW_LINE> self.__connection = None <NEW_LINE> <DEDENT> def open(self): <NEW_LINE> <INDENT> Lock.acquire(SPI.__name__ + str(self.__bus), SPI.__LOCK_TIMEOUT) <NEW_LINE> self.__connection = ASPI(self.__bus, self.__device) <NEW_LINE> self.__connection.mode = self.__mode <NEW_LINE> self.__connection.msh = self.__max_speed <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> if self.__connection is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.__connection.close() <NEW_LINE> self.__connection = None <NEW_LINE> Lock.release(SPI.__name__ + str(self.__bus)) <NEW_LINE> <DEDENT> def xfer(self, args): <NEW_LINE> <INDENT> self.__connection.xfer(args) <NEW_LINE> <DEDENT> def read_bytes(self, count): <NEW_LINE> <INDENT> return self.__connection.readbytes(count) <NEW_LINE> <DEDENT> def __str__(self, *args, **kwargs): <NEW_LINE> <INDENT> return "SPI:{bus:%d, device:%s, mode:%d, max_speed:%d, connection:%s}" % (self.__bus, self.__device, self.__mode, self.__max_speed, self.__connection) | classdocs | 62598fcb7b180e01f3e4921e |
class MethodRequest(_urllib.request.Request): <NEW_LINE> <INDENT> def set_method(self, method): <NEW_LINE> <INDENT> self.method = method.upper() <NEW_LINE> <DEDENT> def get_method(self): <NEW_LINE> <INDENT> return getattr(self, 'method', _urllib.request.Request.get_method(self)) | Used to create HEAD/PUT/DELETE/... requests with urllib | 62598fcb50812a4eaa620db3 |
class TestCSUpdateOrganisationResponse(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testCSUpdateOrganisationResponse(self): <NEW_LINE> <INDENT> pass | CSUpdateOrganisationResponse unit test stubs | 62598fcb8a349b6b436865de |
class DeleteDigitsTestSuite(unittest.TestCase): <NEW_LINE> <INDENT> def test_clean_string(self): <NEW_LINE> <INDENT> string = "this is a clean string" <NEW_LINE> expected = "this is a clean string" <NEW_LINE> res = textprocessor.convert_caps(string) <NEW_LINE> self.assertEqual(res, expected, "Strings do not match") <NEW_LINE> <DEDENT> def test_caps_string(self): <NEW_LINE> <INDENT> string = "THIS IS A STRING" <NEW_LINE> expected = "this is a string" <NEW_LINE> res = textprocessor.convert_caps(string) <NEW_LINE> self.assertEqual(res, expected, "Strings do not match") <NEW_LINE> <DEDENT> def test_caps_unicode_string(self): <NEW_LINE> <INDENT> string = u"THIS IS A STRING" <NEW_LINE> expected = "this is a string" <NEW_LINE> res = textprocessor.convert_caps(string) <NEW_LINE> self.assertEqual(res, expected, "Strings do not match") <NEW_LINE> <DEDENT> def test_clean_unicode_string(self): <NEW_LINE> <INDENT> string = u'this is a clean string' <NEW_LINE> expected = "this is a clean string" <NEW_LINE> res = textprocessor.convert_caps(string) <NEW_LINE> self.assertEqual(res, expected, "Strings do not match") <NEW_LINE> <DEDENT> def test_mix_upper_and_lower_string(self): <NEW_LINE> <INDENT> string = 'ThIs iS A cLeaN sTring' <NEW_LINE> expected = "this is a clean string" <NEW_LINE> res = textprocessor.convert_caps(string) <NEW_LINE> self.assertEqual(res, expected, "Strings do not match") | Test cases for Delete Punctuation Signs | 62598fcba05bb46b3848ac0a |
class AllowTokenAnnotation(AllowCorrections): <NEW_LINE> <INDENT> def annotations(self,Class,set=None): <NEW_LINE> <INDENT> found = False <NEW_LINE> for e in self.select(Class,set,True,default_ignore_annotations): <NEW_LINE> <INDENT> found = True <NEW_LINE> yield e <NEW_LINE> <DEDENT> if not found: <NEW_LINE> <INDENT> raise NoSuchAnnotation() <NEW_LINE> <DEDENT> <DEDENT> def hasannotation(self,Class,set=None): <NEW_LINE> <INDENT> return sum( 1 for _ in self.select(Class,set,True,default_ignore_annotations)) <NEW_LINE> <DEDENT> def annotation(self, type, set=None): <NEW_LINE> <INDENT> for e in self.select(type,set,True,default_ignore_annotations): <NEW_LINE> <INDENT> return e <NEW_LINE> <DEDENT> raise NoSuchAnnotation() <NEW_LINE> <DEDENT> def alternatives(self, Class=None, set=None): <NEW_LINE> <INDENT> for e in self.select(Alternative,None, True, []): <NEW_LINE> <INDENT> if Class is None: <NEW_LINE> <INDENT> yield e <NEW_LINE> <DEDENT> elif len(e) >= 1: <NEW_LINE> <INDENT> for e2 in e: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if isinstance(e2, Class): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if set is None or e2.set == set: <NEW_LINE> <INDENT> yield e <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> continue | Elements that allow token annotation (including extended annotation) must inherit from this class | 62598fcbec188e330fdf8c36 |
class BoxOfficeSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> movie = BoxOfficeDetailSerializer(read_only=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = BoxOfficeMovie <NEW_LINE> fields = ( 'rank', 'movie', 'movie_title', 'release_date', 'ticketing_rate', ) | 박스오피스 직렬화
영화정보 nested | 62598fcb63b5f9789fe85517 |
class ExcludeAlert(object): <NEW_LINE> <INDENT> def __init__(self, row): <NEW_LINE> <INDENT> self._row = row <NEW_LINE> self.alert_source = row[ALERT_SOURCE] <NEW_LINE> self.alert_search = row[ALERT_SEARCH] <NEW_LINE> return None | Information about alerts that exist to exclude results from our
search results. These searches exist to identify pubs we don't want.
Why? Because it was just easier and shorter to create separate,
*negative* alerts for things we kept seeing as false positives. The
alternative was to include the excluded terms in all searches, and
that was intractable, unreadable, and hit search string length limits. | 62598fcb3617ad0b5ee064e8 |
class JournalListView(LoginRequiredMixin, generic.ListView): <NEW_LINE> <INDENT> template_name = 'journal/entry_list.html' <NEW_LINE> model = JournalEntry <NEW_LINE> context_object_name = 'entries' <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> return (JournalEntry.objects.filter(author=self.request.user) .order_by('-date')) | View a list of recent journal entries. | 62598fcbab23a570cc2d4f3e |
class DeepLook_STIS(DeepLook): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(DeepLook_STIS, self).__init__() | Generic class for all STIS rules
| 62598fcb283ffb24f3cf3c26 |
class NoAddressesError(ApiError): <NEW_LINE> <INDENT> pass | The device name has no addresses associated with it. | 62598fcbd486a94d0ba2c373 |
class SetEnumPattern(VdmslNode): <NEW_LINE> <INDENT> _fields = ('ptn_list',) <NEW_LINE> def __init__(self, ptn_list, lineno, lexpos): <NEW_LINE> <INDENT> self.ptn_list = ptn_list <NEW_LINE> self.__setattr__('lineno', lineno) <NEW_LINE> self.__setattr__('lexpos', lexpos) <NEW_LINE> <DEDENT> def toPy(self): <NEW_LINE> <INDENT> elts = [ ptn.toPy() for ptn in self.ptn_list ] <NEW_LINE> return pyast.Set(elts) | 集合列挙パターン | 62598fcbcc40096d6161a3a8 |
class Handle_Rawebp(Data_Handler): <NEW_LINE> <INDENT> def __init__(self, always_load_color=True, QUALITY=95): <NEW_LINE> <INDENT> if always_load_color: <NEW_LINE> <INDENT> self.cv2_IMREAD_FLAG = cv2.IMREAD_COLOR <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.cv2_IMREAD_FLAG = cv2.IMREAD_UNCHANGED <NEW_LINE> <DEDENT> self.QUALITY = QUALITY <NEW_LINE> <DEDENT> def pack(self, imgID, imgpath): <NEW_LINE> <INDENT> rawbytes = open(imgpath, 'rb').read() <NEW_LINE> key = imgID.encode('utf8') <NEW_LINE> value = rawbytes <NEW_LINE> return key, value <NEW_LINE> <DEDENT> def pack_from_npyarr(self, imgID, npyarr): <NEW_LINE> <INDENT> retval, buf = cv2.imencode('.webp', npyarr, [cv2.IMWRITE_WEBP_QUALITY, self.QUALITY]) <NEW_LINE> assert retval==True <NEW_LINE> rawbytes = buf.tostring() <NEW_LINE> key = imgID.encode('utf8') <NEW_LINE> value = rawbytes <NEW_LINE> return key, value <NEW_LINE> <DEDENT> def unpack(self, data_bytes): <NEW_LINE> <INDENT> data_npyarr = np.frombuffer(data_bytes, np.uint8) <NEW_LINE> img = cv2.imdecode(data_npyarr, self.cv2_IMREAD_FLAG) <NEW_LINE> return img | Webp format for storage.
In comparison to the lossless compression of PNG,
or lossy compression of JPEG, Webp has noticeably advantage.
QUALITY from 0 to 100 (the higher is the better). Default value is 95. | 62598fcb0fa83653e46f5288 |
class IndividualReportsTestForms(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.client = Client() <NEW_LINE> self.user = User.objects.create_user('test', 'test@test.com', 'testpassword') <NEW_LINE> self.client.force_login(self.user) <NEW_LINE> Tag.objects.create(name='Test tag') <NEW_LINE> <DEDENT> def test_generate_individual_report(self): <NEW_LINE> <INDENT> form_data = { 'date_from': '2021-01-10', 'date_to': '2021-01-10', 'tags': [1], } <NEW_LINE> response = self.client.post(reverse('individual_report'), data=form_data) <NEW_LINE> self.assertEqual(response.status_code, HTTPStatus.OK) <NEW_LINE> self.assertEquals(response.get('Content-Disposition'), 'attachment; filename=individual_report.csv') <NEW_LINE> <DEDENT> def test_wrong_date_generate_individual_report(self): <NEW_LINE> <INDENT> wrong_form_data = { 'date_from': '2021-01-20', 'date_to': '2021-01-10', 'tags': [1], } <NEW_LINE> response = self.client.post(reverse('individual_report'), data=wrong_form_data) <NEW_LINE> self.assertFormError(response, 'form', 'date_from', 'Дата "От" не может быть больше даты "До"') <NEW_LINE> <DEDENT> def test_wrong_tags_generate_individual_report(self): <NEW_LINE> <INDENT> wrong_form_data = { 'date_from': '2021-01-20', 'date_to': '2021-01-23', 'tags': [], } <NEW_LINE> response = self.client.post(reverse('individual_report'), data=wrong_form_data) <NEW_LINE> self.assertFormError(response, 'form', 'tags', 'Обязательное поле.') | Тесты форм. | 62598fcb5fcc89381b26631e |
class CreateFolderBatchLaunch(async_.LaunchResultBase): <NEW_LINE> <INDENT> _catch_all = 'other' <NEW_LINE> other = None <NEW_LINE> @classmethod <NEW_LINE> def complete(cls, val): <NEW_LINE> <INDENT> return cls('complete', val) <NEW_LINE> <DEDENT> def is_complete(self): <NEW_LINE> <INDENT> return self._tag == 'complete' <NEW_LINE> <DEDENT> def is_other(self): <NEW_LINE> <INDENT> return self._tag == 'other' <NEW_LINE> <DEDENT> def get_complete(self): <NEW_LINE> <INDENT> if not self.is_complete(): <NEW_LINE> <INDENT> raise AttributeError("tag 'complete' not set") <NEW_LINE> <DEDENT> return self._value <NEW_LINE> <DEDENT> def _process_custom_annotations(self, annotation_type, field_path, processor): <NEW_LINE> <INDENT> super(CreateFolderBatchLaunch, self)._process_custom_annotations(annotation_type, field_path, processor) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'CreateFolderBatchLaunch(%r, %r)' % (self._tag, self._value) | Result returned by :meth:`dropbox.dropbox.Dropbox.files_create_folder_batch`
that may either launch an asynchronous job or complete synchronously.
This class acts as a tagged union. Only one of the ``is_*`` methods will
return true. To get the associated value of a tag (if one exists), use the
corresponding ``get_*`` method. | 62598fcbbe7bc26dc925202c |
class ShowSwitchDetailSchema(MetaParser): <NEW_LINE> <INDENT> schema = { 'switch': { 'mac_address': str, Optional('mac_persistency_wait_time'): str, 'stack': { Any(): { 'role': str, 'mac_address': str, 'priority': str, Optional('hw_ver'): str, 'state': str, 'ports': { Any(): { 'stack_port_status': str, 'neighbors_num': Or(int, str) }, } }, } } } | Schema for show switch detail | 62598fcb23849d37ff851455 |
class Task(object): <NEW_LINE> <INDENT> def __init__(self, delay,priority,action,argument): <NEW_LINE> <INDENT> self.delay = delay <NEW_LINE> self.priority = priority <NEW_LINE> self.action = action <NEW_LINE> self.argument = argument <NEW_LINE> <DEDENT> def set_scheduler(self,scheduler): <NEW_LINE> <INDENT> self.scheduler = scheduler <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> self.action() <NEW_LINE> self.scheduler.enter(self.delay,self.priority,self.start,self.argument) | docstring for task | 62598fcb283ffb24f3cf3c29 |
class SSA(BaseEvent): <NEW_LINE> <INDENT> pass | Training Sessions held by EESTEC Trainers . | 62598fcb5fc7496912d4844b |
class RouteFilter(Resource): <NEW_LINE> <INDENT> _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'etag': {'readonly': True}, 'provisioning_state': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'etag': {'key': 'etag', 'type': 'str'}, 'rules': {'key': 'properties.rules', 'type': '[RouteFilterRule]'}, 'peerings': {'key': 'properties.peerings', 'type': '[ExpressRouteCircuitPeering]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, id: Optional[str] = None, location: Optional[str] = None, tags: Optional[Dict[str, str]] = None, rules: Optional[List["RouteFilterRule"]] = None, peerings: Optional[List["ExpressRouteCircuitPeering"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(RouteFilter, self).__init__(id=id, location=location, tags=tags, **kwargs) <NEW_LINE> self.etag = None <NEW_LINE> self.rules = rules <NEW_LINE> self.peerings = peerings <NEW_LINE> self.provisioning_state = None | Route Filter Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: Gets a unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param rules: Collection of RouteFilterRules contained within a route filter.
:type rules: list[~azure.mgmt.network.v2019_02_01.models.RouteFilterRule]
:param peerings: A collection of references to express route circuit peerings.
:type peerings: list[~azure.mgmt.network.v2019_02_01.models.ExpressRouteCircuitPeering]
:ivar provisioning_state: The provisioning state of the resource. Possible values are:
'Updating', 'Deleting', 'Succeeded' and 'Failed'.
:vartype provisioning_state: str | 62598fcb7b180e01f3e49221 |
class CovidModel(BaseModel): <NEW_LINE> <INDENT> country: str = Field(..., alias="Country,Other") <NEW_LINE> confirmed: int = Field(0, alias="TotalCases") <NEW_LINE> new_cases: int = Field(0, alias="NewCases") <NEW_LINE> deaths: int = Field(0, alias="TotalDeaths") <NEW_LINE> recovered: int = Field(0, alias="TotalRecovered") <NEW_LINE> active: int = Field(0, alias="ActiveCases") <NEW_LINE> critical: int = Field(0, alias="Serious,Critical") <NEW_LINE> new_deaths: int = Field(0, alias="NewDeaths") <NEW_LINE> total_tests: int = Field(0, alias="TotalTests") <NEW_LINE> total_tests_per_million: Decimal = Field(Decimal(0), alias="Tests/1M pop") <NEW_LINE> total_cases_per_million: Decimal = Field( Decimal(0), alias="TotCases/1M pop" ) <NEW_LINE> total_deaths_per_million: Decimal = Field( Decimal(0), alias="Deaths/1M pop" ) <NEW_LINE> population: Decimal = Field(Decimal(0), alias = "Population") | Dataclass acts as a Model for Covid data
| 62598fcb9f28863672818a4e |
class Command(RunserverMixin, StaticfilesRunserverCommand): <NEW_LINE> <INDENT> pass | Subclass the RunserverCommand from Staticfiles to set up our gulp
environment. | 62598fcb0fa83653e46f528a |
class ProgressWithEvents(AnimatedProgressBar): <NEW_LINE> <INDENT> def __init__(self, start=0, end=10, width=12, fill=unichr(0x25C9).encode("utf-8"), blank=unichr(0x25CC).encode("utf-8"), marker=unichr(0x25CE).encode("utf-8"), format='[%(fill)s%(marker)s%(blank)s] %(progress)s%%', incremental=True, stdout=sys.stdout): <NEW_LINE> <INDENT> super(ProgressWithEvents, self).__init__(start,end,width,fill,blank,marker,format,incremental,stdout) <NEW_LINE> self.events = {} <NEW_LINE> <DEDENT> def add_event(self,event): <NEW_LINE> <INDENT> if event in self.events: <NEW_LINE> <INDENT> self.events[event] += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.events[event] = 1 <NEW_LINE> <DEDENT> <DEDENT> def show_progress(self): <NEW_LINE> <INDENT> isatty = hasattr(self.stdout, 'isatty') and self.stdout.isatty() <NEW_LINE> if isatty: <NEW_LINE> <INDENT> self.stdout.write('\r') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.stdout.write('\n') <NEW_LINE> <DEDENT> self.stdout.write(str(self)) <NEW_LINE> if len(self.events) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.stdout.write('\n') <NEW_LINE> for key in self.events.keys(): <NEW_LINE> <INDENT> self.stdout.write(str(key) + ' = ' + str(self.events[key]) + ' ') <NEW_LINE> <DEDENT> if isatty: <NEW_LINE> <INDENT> self.stdout.write('\033[1A') <NEW_LINE> <DEDENT> self.stdout.flush() | Extends AnimatedProgressBar to allow you to track a set of events that
cause the progress to move. For instance, in a deletion progress bar, you
can track files that were nuked and files that the user doesn't have access to | 62598fcb63b5f9789fe8551b |
class AlphaBetaPlayer(IsolationPlayer): <NEW_LINE> <INDENT> def get_move(self, game, time_left): <NEW_LINE> <INDENT> self.time_left = time_left <NEW_LINE> legal_moves = game.get_legal_moves(self) <NEW_LINE> if len(legal_moves) : <NEW_LINE> <INDENT> best_move = legal_moves[random.randint(0,len(legal_moves)-1)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> best_move = (-1, -1) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> depth = 1 <NEW_LINE> while True: <NEW_LINE> <INDENT> val,current_move = self.alphabeta(game, depth) <NEW_LINE> if current_move == (-1, -1): <NEW_LINE> <INDENT> return best_move <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> best_move = current_move <NEW_LINE> <DEDENT> depth += 1 <NEW_LINE> <DEDENT> <DEDENT> except SearchTimeout: <NEW_LINE> <INDENT> return best_move <NEW_LINE> <DEDENT> return best_move <NEW_LINE> <DEDENT> def alphabeta(self, game, depth, alpha=float("-inf"), beta=float("inf"),Max=True): <NEW_LINE> <INDENT> if self.time_left() < self.TIMER_THRESHOLD: <NEW_LINE> <INDENT> raise SearchTimeout() <NEW_LINE> <DEDENT> legal_moves = game.get_legal_moves(self) <NEW_LINE> best_move = (-1,-1) <NEW_LINE> if (depth == 0 )or (not len(legal_moves)) : <NEW_LINE> <INDENT> return self.score(game,self),best_move <NEW_LINE> <DEDENT> val = float("-inf") if Max else float("inf") <NEW_LINE> for move in legal_moves: <NEW_LINE> <INDENT> n_val,_ = self.alphabeta(game.forecast_move(move),depth-1,alpha,beta,not Max) <NEW_LINE> if Max: <NEW_LINE> <INDENT> if val < n_val: <NEW_LINE> <INDENT> val = n_val <NEW_LINE> best_move = move <NEW_LINE> <DEDENT> if val >= beta: <NEW_LINE> <INDENT> return val,best_move <NEW_LINE> <DEDENT> alpha = max(val,alpha) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if val > n_val: <NEW_LINE> <INDENT> val = n_val <NEW_LINE> best_move = move <NEW_LINE> <DEDENT> if val <= alpha: <NEW_LINE> <INDENT> return val,best_move <NEW_LINE> <DEDENT> beta = min(val,beta) <NEW_LINE> <DEDENT> <DEDENT> return val,best_move | Game-playing agent that chooses a move using iterative deepening minimax
search with alpha-beta pruning. You must finish and test this player to
make sure it returns a good move before the search time limit expires. | 62598fcb283ffb24f3cf3c2a |
class VideoDirectPageSet(VideoPageSet): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(VideoDirectPageSet, self).__init__('direct') <NEW_LINE> <DEDENT> def _AddUserStoryForURL(self, url): <NEW_LINE> <INDENT> self.AddUserStory(VideoPage(url, self, False)) | Chrome proxy video tests: direct fetch. | 62598fcbadb09d7d5dc0a91f |
class DecoderCat(nn.Module): <NEW_LINE> <INDENT> def __init__(self, input_size, hidden_size, n_cat, n_layers, c_z=None): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.input_size = input_size <NEW_LINE> self.hidden_size = hidden_size <NEW_LINE> self.n_cat = n_cat <NEW_LINE> self.n_layers = n_layers <NEW_LINE> self.c_z = c_z <NEW_LINE> if self.c_z is None: <NEW_LINE> <INDENT> self.c_z = input_size <NEW_LINE> <DEDENT> self.init_block() <NEW_LINE> <DEDENT> def init_block(self): <NEW_LINE> <INDENT> self.var_layers = nn.ModuleList() <NEW_LINE> if self.c_z < self.input_size: <NEW_LINE> <INDENT> self.input_size = self.c_z <NEW_LINE> <DEDENT> for _ in range(self.n_layers): <NEW_LINE> <INDENT> self.var_layers.append(nn.Linear(self.input_size, self.hidden_size)) <NEW_LINE> self.var_layers.append(nn.LeakyReLU()) <NEW_LINE> self.input_size = self.hidden_size <NEW_LINE> <DEDENT> self.output = nn.Linear(self.input_size, self.n_cat) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> x = x[:,:self.c_z] <NEW_LINE> for i in range(len(self.var_layers)): <NEW_LINE> <INDENT> x = self.var_layers[i](x) <NEW_LINE> <DEDENT> out = self.output(x) <NEW_LINE> x = Categorical(logits=out) <NEW_LINE> return x | Class implementing a decoder with a Categorical distribution for, categorical
biomarkers (APOE) | 62598fcb4a966d76dd5ef27c |
class Meta: <NEW_LINE> <INDENT> model = User <NEW_LINE> fields = ["username", "password"] | 유저 명과 패스워드 fields 만 제공. | 62598fcb7cff6e4e811b5dcb |
class Adagrad(Optimizer): <NEW_LINE> <INDENT> def __init__(self, learning_rate=0.01, **kwargs): <NEW_LINE> <INDENT> self.initial_decay = kwargs.pop('decay', 0.0) <NEW_LINE> self.epsilon = kwargs.pop('epsilon', K.epsilon()) <NEW_LINE> learning_rate = kwargs.pop('lr', learning_rate) <NEW_LINE> super(Adagrad, self).__init__(**kwargs) <NEW_LINE> with K.name_scope(self.__class__.__name__): <NEW_LINE> <INDENT> self.learning_rate = K.variable(learning_rate, name='learning_rate') <NEW_LINE> self.decay = K.variable(self.initial_decay, name='decay') <NEW_LINE> self.iterations = K.variable(0, dtype='int64', name='iterations') <NEW_LINE> <DEDENT> <DEDENT> @interfaces.legacy_get_updates_support <NEW_LINE> @K.symbolic <NEW_LINE> def get_updates(self, loss, params): <NEW_LINE> <INDENT> grads = self.get_gradients(loss, params) <NEW_LINE> shapes = [K.int_shape(p) for p in params] <NEW_LINE> accumulators = [K.zeros(shape, name='accumulator_' + str(i)) for (i, shape) in enumerate(shapes)] <NEW_LINE> self.weights = [self.iterations] + accumulators <NEW_LINE> self.updates = [K.update_add(self.iterations, 1)] <NEW_LINE> lr = self.learning_rate <NEW_LINE> if self.initial_decay > 0: <NEW_LINE> <INDENT> lr = lr * (1. / (1. + self.decay * K.cast(self.iterations, K.dtype(self.decay)))) <NEW_LINE> <DEDENT> for p, g, a in zip(params, grads, accumulators): <NEW_LINE> <INDENT> new_a = a + K.square(g) <NEW_LINE> self.updates.append(K.update(a, new_a)) <NEW_LINE> new_p = p - lr * g / (K.sqrt(new_a) + self.epsilon) <NEW_LINE> if getattr(p, 'constraint', None) is not None: <NEW_LINE> <INDENT> new_p = p.constraint(new_p) <NEW_LINE> <DEDENT> self.updates.append(K.update(p, new_p)) <NEW_LINE> <DEDENT> return self.updates <NEW_LINE> <DEDENT> def set_weights(self, weights): <NEW_LINE> <INDENT> params = self.weights <NEW_LINE> if len(params) == len(weights) + 1: <NEW_LINE> <INDENT> weights = [np.array(0)] + weights <NEW_LINE> <DEDENT> super(Adagrad, self).set_weights(weights) <NEW_LINE> <DEDENT> def get_config(self): <NEW_LINE> <INDENT> config = {'learning_rate': float(K.get_value(self.learning_rate)), 'decay': float(K.get_value(self.decay)), 'epsilon': self.epsilon} <NEW_LINE> base_config = super(Adagrad, self).get_config() <NEW_LINE> return dict(list(base_config.items()) + list(config.items())) | Adagrad optimizer.
Adagrad is an optimizer with parameter-specific learning rates,
which are adapted relative to how frequently a parameter gets
updated during training. The more updates a parameter receives,
the smaller the learning rate.
It is recommended to leave the parameters of this optimizer
at their default values.
# Arguments
learning_rate: float >= 0. Initial learning rate.
# References
- [Adaptive Subgradient Methods for Online Learning and Stochastic
Optimization](http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf) | 62598fcb099cdd3c636755b4 |
class Field: <NEW_LINE> <INDENT> def __init__(self,max_animals,max_crops): <NEW_LINE> <INDENT> self._crops = [] <NEW_LINE> self._animals = [] <NEW_LINE> self._max_animals = max_animals <NEW_LINE> self._max_crops = max_crops <NEW_LINE> <DEDENT> def plant_crop(self, crop): <NEW_LINE> <INDENT> if len(self._crops) < self._max_crops: <NEW_LINE> <INDENT> self._crops.append(crop) <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def add_animal(self, animal): <NEW_LINE> <INDENT> if len(self._animals) < self._max_animals: <NEW_LINE> <INDENT> self._animals.append(animal) <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def harvest_crop(self,position): <NEW_LINE> <INDENT> return self,self._crops.pop(position) <NEW_LINE> <DEDENT> def remove_animal(self,position): <NEW_LINE> <INDENT> return self,self._animals.pop(position) <NEW_LINE> <DEDENT> def report_contents(self): <NEW_LINE> <INDENT> crop_report = [] <NEW_LINE> animal_report = [] <NEW_LINE> for crop in self._crops: <NEW_LINE> <INDENT> crop_report.append(crop.report()) <NEW_LINE> <DEDENT> for animal in self._animals: <NEW_LINE> <INDENT> animal_report.append(animal.report()) <NEW_LINE> <DEDENT> return{"crops":crop_report, "animals":animal_report} <NEW_LINE> <DEDENT> def report_needs(self): <NEW_LINE> <INDENT> food = 0 <NEW_LINE> light = 0 <NEW_LINE> water = 0 <NEW_LINE> for crop in self._crops: <NEW_LINE> <INDENT> needs = crop.needs() <NEW_LINE> if needs["light need"] > light: <NEW_LINE> <INDENT> light = needs["light need"] <NEW_LINE> <DEDENT> if needs["water need"] > water: <NEW_LINE> <INDENT> water = needs["water need"] <NEW_LINE> <DEDENT> <DEDENT> for animal in self._animals: <NEW_LINE> <INDENT> needs = animal.needs() <NEW_LINE> food += needs["food need"] <NEW_LINE> if needs["water need"] > water: <NEW_LINE> <INDENT> water = needs["water need"] <NEW_LINE> <DEDENT> <DEDENT> return {"food":food,"light":light,"water":water} <NEW_LINE> <DEDENT> def grow(self,light, food, water): <NEW_LINE> <INDENT> if len(self._crops) > 0: <NEW_LINE> <INDENT> for crop in self._crops: <NEW_LINE> <INDENT> crop.grow(light,water) <NEW_LINE> <DEDENT> <DEDENT> if len(self._animals) > 0: <NEW_LINE> <INDENT> food_required = 0 <NEW_LINE> for animal in self._animals: <NEW_LINE> <INDENT> needs = animal.needs() <NEW_LINE> food_required += needs["food need"] <NEW_LINE> <DEDENT> if food > food_required: <NEW_LINE> <INDENT> additional_food = food - food_required <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> additional_food = 0 <NEW_LINE> <DEDENT> for animal in self._animals: <NEW_LINE> <INDENT> needs = animal.needs() <NEW_LINE> feed = 0 <NEW_LINE> if food >= needs["food need"]: <NEW_LINE> <INDENT> food -= needs["food need"] <NEW_LINE> feed = needs["food need"] <NEW_LINE> if additional_food > 0: <NEW_LINE> <INDENT> additional_food -= 1 <NEW_LINE> feed += 1 <NEW_LINE> <DEDENT> <DEDENT> animal.grow(feed,water) | Simulate a field that can contain animals and crops | 62598fcb9f28863672818a4f |
class APIException(Exception): <NEW_LINE> <INDENT> def __init__(self, code: int, message: str, reason: str, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self.code = code <NEW_LINE> self.message = message <NEW_LINE> self.reason = reason <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '{}: {} ({})'.format(self.code, self.message, self.reason) | Custom Exception that is raised from the Requests when an
API call goes wrong, meaning the API did not
return a status code of 200.
Attributes
----------
code : int
The code of the Error that was returned
message : str
The error message as returned by the API
reason : str
The reason as specified by the API
Examples
--------
.. code-block:: python
try:
flight_info = send_sync(my_request_body, use_containers=False)
except pyflight.APIException as err:
print('Error trying to execute a request:')
print(err)
else:
...
The Exception will be formatted as:
`'<status-code>: <error-message> (reason)'`, for example
``400: Bad Request (keyInvalid)`` | 62598fcb4c3428357761a664 |
class ReflexAgent(Agent): <NEW_LINE> <INDENT> def getAction(self, gameState): <NEW_LINE> <INDENT> legalMoves = gameState.getLegalActions() <NEW_LINE> scores = [self.evaluationFunction(gameState, action) for action in legalMoves] <NEW_LINE> bestScore = max(scores) <NEW_LINE> bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] <NEW_LINE> chosenIndex = random.choice(bestIndices) <NEW_LINE> "Add more of your code here if you want to" <NEW_LINE> return legalMoves[chosenIndex] <NEW_LINE> <DEDENT> def evaluationFunction(self, currentGameState, action): <NEW_LINE> <INDENT> successorGameState = currentGameState.generatePacmanSuccessor(action) <NEW_LINE> newPos = successorGameState.getPacmanPosition() <NEW_LINE> newFood = successorGameState.getFood() <NEW_LINE> newGhostStates = successorGameState.getGhostStates() <NEW_LINE> newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] <NEW_LINE> "*** YOUR CODE HERE ***" <NEW_LINE> if successorGameState.isWin(): <NEW_LINE> <INDENT> return float("inf") - 20 <NEW_LINE> <DEDENT> ghostposition = currentGameState.getGhostPosition(1) <NEW_LINE> distfromghost = util.manhattanDistance(ghostposition, newPos) <NEW_LINE> score = max(distfromghost, 3) + successorGameState.getScore() <NEW_LINE> foodlist = newFood.asList() <NEW_LINE> closestfood = 100 <NEW_LINE> for foodpos in foodlist: <NEW_LINE> <INDENT> thisdist = util.manhattanDistance(foodpos, newPos) <NEW_LINE> if (thisdist < closestfood): <NEW_LINE> <INDENT> closestfood = thisdist <NEW_LINE> <DEDENT> <DEDENT> if (currentGameState.getNumFood() > successorGameState.getNumFood()): <NEW_LINE> <INDENT> score += 100 <NEW_LINE> <DEDENT> if action == Directions.STOP: <NEW_LINE> <INDENT> score -= 3 <NEW_LINE> <DEDENT> score -= 3 * closestfood <NEW_LINE> capsuleplaces = currentGameState.getCapsules() <NEW_LINE> if successorGameState.getPacmanPosition() in capsuleplaces: <NEW_LINE> <INDENT> score += 120 <NEW_LINE> <DEDENT> return score | A reflex agent chooses an action at each choice point by examining
its alternatives via a state evaluation function.
The code below is provided as a guide. You are welcome to change
it in any way you see fit, so long as you don't touch our method
headers. | 62598fcb4a966d76dd5ef27e |
class Population: <NEW_LINE> <INDENT> def __init__(self, problem, population_size=POPULATION_SIZE): <NEW_LINE> <INDENT> self._problem = problem <NEW_LINE> self._solutions = [Solution(problem) for _ in range(population_size)] <NEW_LINE> self._population_size = population_size <NEW_LINE> <DEDENT> def _select_one_parent(self, tournament_size=TOURNAMENT_SIZE): <NEW_LINE> <INDENT> tournament = random.sample(self._solutions, tournament_size) <NEW_LINE> return min(tournament, key=lambda x: x.fitness) <NEW_LINE> <DEDENT> def _crossover(self): <NEW_LINE> <INDENT> parents = [] <NEW_LINE> parents = [self._select_one_parent() for _ in range(2)] <NEW_LINE> start = random.randint(0, self._problem.size - 2) <NEW_LINE> end = random.randint(start, self._problem.size) <NEW_LINE> co_path = [-1] * self._problem.size <NEW_LINE> co_path[start:end] = parents[0].path[start:end] <NEW_LINE> unused_cities = [city for city in parents[1].path if city not in co_path] <NEW_LINE> co_path[:start] = unused_cities[:start] <NEW_LINE> co_path[end:] = unused_cities[start:] <NEW_LINE> return Solution(self._problem, path=co_path) <NEW_LINE> <DEDENT> def crossover_all(self): <NEW_LINE> <INDENT> self._solutions = [self._crossover() for _ in range(self._population_size)] <NEW_LINE> <DEDENT> def mutate_all(self): <NEW_LINE> <INDENT> self._solutions = [solution.mutate() for solution in self._solutions] <NEW_LINE> <DEDENT> def get_fittest(self): <NEW_LINE> <INDENT> return min(self._solutions, key=lambda x: x.fitness) | Class defining the population of solution. One population contains
one generation. | 62598fcb97e22403b383b2ad |
class TrafficLightParams: <NEW_LINE> <INDENT> def __init__(self, baseline=False): <NEW_LINE> <INDENT> self.__tls_properties = dict() <NEW_LINE> self.baseline = baseline <NEW_LINE> <DEDENT> def add(self, node_id, tls_type="static", programID=10, offset=None, phases=None, maxGap=None, detectorGap=None, showDetectors=None, file=None, freq=None): <NEW_LINE> <INDENT> self.__tls_properties[node_id] = {"id": node_id, "type": tls_type} <NEW_LINE> if programID: <NEW_LINE> <INDENT> self.__tls_properties[node_id]["programID"] = programID <NEW_LINE> <DEDENT> if offset: <NEW_LINE> <INDENT> self.__tls_properties[node_id]["offset"] = offset <NEW_LINE> <DEDENT> if phases: <NEW_LINE> <INDENT> self.__tls_properties[node_id]["phases"] = phases <NEW_LINE> <DEDENT> if tls_type == "actuated": <NEW_LINE> <INDENT> self.__tls_properties[node_id]["max-gap"] = maxGap if maxGap else MAX_GAP <NEW_LINE> self.__tls_properties[node_id]["detector-gap"] = detectorGap if detectorGap else DETECTOR_GAP <NEW_LINE> self.__tls_properties[node_id]["show-detectors"] = showDetectors if showDetectors else SHOW_DETECTORS <NEW_LINE> if file: <NEW_LINE> <INDENT> self.__tls_properties[node_id]["file"] = file <NEW_LINE> <DEDENT> if freq: <NEW_LINE> <INDENT> self.__tls_properties[node_id]["freq"] = freq <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_properties(self): <NEW_LINE> <INDENT> return self.__tls_properties <NEW_LINE> <DEDENT> def actuated_default(self): <NEW_LINE> <INDENT> tl_type = "actuated" <NEW_LINE> program_id = 1 <NEW_LINE> max_gap = 3.0 <NEW_LINE> detector_gap = 0.8 <NEW_LINE> show_detectors = True <NEW_LINE> phases = [{ "duration": "31", "minDur": "8", "maxDur": "45", "state": "GrGr" }, { "duration": "6", "minDur": "3", "maxDur": "6", "state": "yryr" }, { "duration": "31", "minDur": "8", "maxDur": "45", "state": "rGrG" }, { "duration": "6", "minDur": "3", "maxDur": "6", "state": "ryry" }] <NEW_LINE> return { "tl_type": str(tl_type), "program_id": str(program_id), "max_gap": str(max_gap), "detector_gap": str(detector_gap), "show_detectors": show_detectors, "phases": phases } | Base traffic light.
This class is used to place traffic lights in the network and describe
the state of these traffic lights. In addition, this class supports
modifying the states of certain lights via TraCI. | 62598fcb60cbc95b063646e5 |
class _DecodeStep(pt.nn.Module): <NEW_LINE> <INDENT> def __init__(self, embedding_target: encoder.Embedding, decoder: decoder.Decoder, output_layer: layers.OutputLayer, factor_output_layers: pt.nn.ModuleList): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.embedding_target = embedding_target <NEW_LINE> self.decoder = decoder <NEW_LINE> self.output_layer = pt.jit.script(output_layer) <NEW_LINE> self.factor_output_layers = factor_output_layers <NEW_LINE> self.has_target_factors = bool(factor_output_layers) <NEW_LINE> <DEDENT> def forward(self, step_input, states: List[pt.Tensor], vocab_slice_ids: Optional[pt.Tensor] = None) -> List[pt.Tensor]: <NEW_LINE> <INDENT> target_embed = self.embedding_target(step_input.unsqueeze(1)) <NEW_LINE> decoder_out, new_states = self.decoder(target_embed, states) <NEW_LINE> decoder_out = decoder_out.squeeze(1) <NEW_LINE> step_output = self.output_layer(decoder_out, vocab_slice_ids) <NEW_LINE> outputs = [step_output] <NEW_LINE> if self.has_target_factors: <NEW_LINE> <INDENT> outputs += [fol(decoder_out) for fol in self.factor_output_layers] <NEW_LINE> <DEDENT> outputs += new_states <NEW_LINE> return outputs | Auxiliary module that wraps computation for a single decode step for a SockeyeModel.
End-to-end traceable. Return values are put into a flat list to avoid return type constraints
for traced modules. | 62598fcbf9cc0f698b1c54a7 |
class HubIsExistedSerializer(serializers.Serializer): <NEW_LINE> <INDENT> hub = serializers.ListField( required=True, min_length=1, child=serializers.PrimaryKeyRelatedField( queryset=Hub.objects.filter_by(), error_messages={ 'does_not_exist': _("hub [{pk_value}] does not exist.") } ) ) | 验证列表中的集控是否存在 | 62598fcbec188e330fdf8c3e |
class LXDInstallationError(LXDError): <NEW_LINE> <INDENT> def __init__( self, reason: str, *, details: Optional[str] = None, ) -> None: <NEW_LINE> <INDENT> brief = f"Failed to install LXD: {reason}." <NEW_LINE> resolution = "Please visit https://linuxcontainers.org/lxd/getting-started-cli/ for instructions on installing LXD for your operating system." <NEW_LINE> super().__init__(brief=brief, details=details, resolution=resolution) | LXD Installation Error.
:param reason: Reason for install failure.
:param details: Optional details to include. | 62598fcb167d2b6e312b7320 |
@dataclasses.dataclass <NEW_LINE> class LayoutTreeNode: <NEW_LINE> <INDENT> domNodeIndex: int <NEW_LINE> boundingBox: dom.Rect <NEW_LINE> layoutText: Optional[str] = None <NEW_LINE> inlineTextNodes: Optional[list[InlineTextBox]] = None <NEW_LINE> styleIndex: Optional[int] = None <NEW_LINE> paintOrder: Optional[int] = None <NEW_LINE> isStackingContext: Optional[bool] = None <NEW_LINE> @classmethod <NEW_LINE> def from_json(cls, json: dict) -> LayoutTreeNode: <NEW_LINE> <INDENT> return cls( json["domNodeIndex"], dom.Rect.from_json(json["boundingBox"]), json.get("layoutText"), [InlineTextBox.from_json(i) for i in json["inlineTextNodes"]] if "inlineTextNodes" in json else None, json.get("styleIndex"), json.get("paintOrder"), json.get("isStackingContext"), ) <NEW_LINE> <DEDENT> def to_json(self) -> dict: <NEW_LINE> <INDENT> return filter_none( { "domNodeIndex": self.domNodeIndex, "boundingBox": self.boundingBox.to_json(), "layoutText": self.layoutText, "inlineTextNodes": [i.to_json() for i in self.inlineTextNodes] if self.inlineTextNodes else None, "styleIndex": self.styleIndex, "paintOrder": self.paintOrder, "isStackingContext": self.isStackingContext, } ) | Details of an element in the DOM tree with a LayoutObject.
Attributes
----------
domNodeIndex: int
The index of the related DOM node in the `domNodes` array returned by `getSnapshot`.
boundingBox: dom.Rect
The bounding box in document coordinates. Note that scroll offset of the document is ignored.
layoutText: Optional[str]
Contents of the LayoutText, if any.
inlineTextNodes: Optional[list[InlineTextBox]]
The post-layout inline text nodes, if any.
styleIndex: Optional[int]
Index into the `computedStyles` array returned by `getSnapshot`.
paintOrder: Optional[int]
Global paint order index, which is determined by the stacking order of the nodes. Nodes
that are painted together will have the same index. Only provided if includePaintOrder in
getSnapshot was true.
isStackingContext: Optional[bool]
Set to true to indicate the element begins a new stacking context. | 62598fcb63b5f9789fe8551f |
class SNICallbackTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> from letsencrypt.plugins.standalone.authenticator import StandaloneAuthenticator <NEW_LINE> self.authenticator = StandaloneAuthenticator(config=CONFIG, name=None) <NEW_LINE> self.cert = achallenges.DVSNI( challb=acme_util.DVSNI_P, domain="example.com", account=ACCOUNT).gen_cert_and_response(key_pem=CHALL_KEY_PEM)[1] <NEW_LINE> self.authenticator.private_key = CHALL_KEY <NEW_LINE> self.authenticator.sni_names = {"abcdef.acme.invalid": self.cert} <NEW_LINE> self.authenticator.child_pid = 12345 <NEW_LINE> <DEDENT> def test_real_servername(self): <NEW_LINE> <INDENT> connection = mock.MagicMock() <NEW_LINE> connection.get_servername.return_value = "abcdef.acme.invalid" <NEW_LINE> self.authenticator.sni_callback(connection) <NEW_LINE> self.assertEqual(connection.set_context.call_count, 1) <NEW_LINE> called_ctx = connection.set_context.call_args[0][0] <NEW_LINE> self.assertTrue(isinstance(called_ctx, OpenSSL.SSL.Context)) <NEW_LINE> <DEDENT> def test_fake_servername(self): <NEW_LINE> <INDENT> connection = mock.MagicMock() <NEW_LINE> connection.get_servername.return_value = "example.com" <NEW_LINE> self.authenticator.sni_callback(connection) <NEW_LINE> self.assertEqual(connection.set_context.call_count, 1) <NEW_LINE> called_ctx = connection.set_context.call_args[0][0] <NEW_LINE> self.assertTrue(isinstance(called_ctx, OpenSSL.SSL.Context)) | Tests for sni_callback() method. | 62598fcb3617ad0b5ee064f0 |
class UserType(DjangoObjectType): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = get_user_model() | Class UserType to loads user model | 62598fcb3d592f4c4edbb25c |
class DealActionsAPIView(generics.RetrieveUpdateDestroyAPIView): <NEW_LINE> <INDENT> serializer_class = DealSerializer <NEW_LINE> permission_classes = (permissions.IsAuthenticated,) <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> user = self.request.user <NEW_LINE> current_merchant = get_object_or_404(Merchant, userprofile=user.pk) <NEW_LINE> current_advertiser = get_object_or_404(Advertiser, name=current_merchant.name) <NEW_LINE> deal_pk = self.kwargs.get('pk') <NEW_LINE> deal = Deal.objects.filter(advertiser=current_advertiser, pk=deal_pk) <NEW_LINE> return deal | Authenticated merchant can see a deal's details, update or delete it. | 62598fcb5fc7496912d4844e |
class VerKey(BlsEntity): <NEW_LINE> <INDENT> new_handler = 'indy_crypto_bls_ver_key_new' <NEW_LINE> from_bytes_handler = 'indy_crypto_bls_ver_key_from_bytes' <NEW_LINE> as_bytes_handler = 'indy_crypto_bls_ver_key_as_bytes' <NEW_LINE> free_handler = 'indy_crypto_bls_ver_key_free' <NEW_LINE> @classmethod <NEW_LINE> def new(cls, gen: Generator, sign_key: SignKey) -> 'VerKey': <NEW_LINE> <INDENT> logger = logging.getLogger(__name__) <NEW_LINE> logger.debug("VerKey::new: >>>") <NEW_LINE> c_instance = c_void_p() <NEW_LINE> do_call(cls.new_handler, gen.c_instance, sign_key.c_instance, byref(c_instance)) <NEW_LINE> res = cls(c_instance) <NEW_LINE> logger.debug("VerKey::new: <<< res: %r", res) <NEW_LINE> return res | BLS verification key. | 62598fcb0fa83653e46f5290 |
class ToggleButton(Button): <NEW_LINE> <INDENT> __groups = {} <NEW_LINE> group = ObjectProperty(None, allownone=True) <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self._previous_group = None <NEW_LINE> super(ToggleButton, self).__init__(**kwargs) <NEW_LINE> <DEDENT> def on_group(self, *largs): <NEW_LINE> <INDENT> groups = ToggleButton.__groups <NEW_LINE> if self._previous_group: <NEW_LINE> <INDENT> groups[self._previous_group].remove(self) <NEW_LINE> <DEDENT> group = self._previous_group = self.group <NEW_LINE> if not group in groups: <NEW_LINE> <INDENT> groups[group] = [] <NEW_LINE> <DEDENT> groups[group].append(self) <NEW_LINE> <DEDENT> def _release_group(self, current): <NEW_LINE> <INDENT> if self.group is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for widget in self.__groups[self.group]: <NEW_LINE> <INDENT> if widget is current: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> widget.state = 'normal' <NEW_LINE> <DEDENT> <DEDENT> def _do_press(self): <NEW_LINE> <INDENT> self._release_group(self) <NEW_LINE> self.state = 'normal' if self.state == 'down' else 'down' <NEW_LINE> <DEDENT> def _do_release(self): <NEW_LINE> <INDENT> pass | Toggle button class, see module documentation for more information.
| 62598fcb9f28863672818a51 |
@unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms') <NEW_LINE> class BaseCoursewareTests(SharedModuleStoreTestCase): <NEW_LINE> <INDENT> MODULESTORE = TEST_DATA_SPLIT_MODULESTORE <NEW_LINE> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> super().setUpClass() <NEW_LINE> cls.store = modulestore() <NEW_LINE> cls.course = ToyCourseFactory.create( end=datetime(2028, 1, 1, 1, 1, 1), enrollment_start=datetime(2020, 1, 1, 1, 1, 1), enrollment_end=datetime(2028, 1, 1, 1, 1, 1), emit_signals=True, modulestore=cls.store, ) <NEW_LINE> cls.chapter = ItemFactory(parent=cls.course, category='chapter') <NEW_LINE> cls.sequence = ItemFactory(parent=cls.chapter, category='sequential', display_name='sequence') <NEW_LINE> cls.unit = ItemFactory.create(parent=cls.sequence, category='vertical', display_name="Vertical") <NEW_LINE> cls.user = UserFactory( username='student', email=u'user@example.com', password='foo', is_staff=False ) <NEW_LINE> cls.url = '/api/courseware/course/{}'.format(cls.course.id) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def tearDownClass(cls): <NEW_LINE> <INDENT> super().tearDownClass() <NEW_LINE> cls.store.delete_course(cls.course.id, cls.user.id) <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> super().setUp() <NEW_LINE> self.client.login(username=self.user.username, password='foo') | Base class for courseware API tests | 62598fcb50812a4eaa620db9 |
class ValueSequenceMethodMocker(MethodMocker): <NEW_LINE> <INDENT> def __init__(self, retvals): <NEW_LINE> <INDENT> super(ValueSequenceMethodMocker, self).__init__() <NEW_LINE> self._retvals = retvals if retvals is not None else [] <NEW_LINE> <DEDENT> def get_method(self): <NEW_LINE> <INDENT> def mockmethod(mmself, *args, **kwargs): <NEW_LINE> <INDENT> self.record_args(mmself, args, kwargs) <NEW_LINE> return self._retvals[self._call_count - 1] <NEW_LINE> <DEDENT> return mockmethod | Provides mock method returning a sequence of values.
Note: All objects share the sequence of values, i.e., the n-th
call to the method will return the n-th value, independent
of on which object the method is called. | 62598fcbf9cc0f698b1c54a8 |
class NoEncoder(BaseEncoder): <NEW_LINE> <INDENT> def __init__(self, random_state: Optional[Union[np.random.RandomState, int]] = None ): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.random_state = random_state <NEW_LINE> <DEDENT> def fit(self, X: Dict[str, Any], y: Any = None) -> BaseEncoder: <NEW_LINE> <INDENT> self.check_requirements(X, y) <NEW_LINE> return self <NEW_LINE> <DEDENT> def transform(self, X: Dict[str, Any]) -> Dict[str, Any]: <NEW_LINE> <INDENT> X.update({'encoder': self.preprocessor}) <NEW_LINE> return X <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_properties(dataset_properties: Optional[Dict[str, Any]] = None) -> Dict[str, Union[str, bool]]: <NEW_LINE> <INDENT> return { 'shortname': 'NoEncoder', 'name': 'No Encoder', 'handles_sparse': True } | Don't perform encoding on categorical features | 62598fcb63b5f9789fe85521 |
class IntAttribute(Attribute): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def redoc(cls) -> None: <NEW_LINE> <INDENT> super(IntAttribute, cls).redoc() <NEW_LINE> cls.__doc__ += "\n:type: int" <NEW_LINE> <DEDENT> def post_get(self, value: SupportsInt) -> int: <NEW_LINE> <INDENT> return int(value) | Class for attributes with integers values. | 62598fcb283ffb24f3cf3c30 |
class lazy_property: <NEW_LINE> <INDENT> def __init__(self, fget): <NEW_LINE> <INDENT> self.fget = fget <NEW_LINE> self.func_name = fget.__name__ <NEW_LINE> <DEDENT> def __get__(self, obj, cls): <NEW_LINE> <INDENT> if obj is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> value = self.fget(obj) <NEW_LINE> setattr(obj, self.func_name, value) <NEW_LINE> return value | Allows lazy evaluation of properties of non-mutable data.
Useful when these are expensive to compute and are immutable.
The data must not be mutable because the method gets
replaced with the computed value in the original object. | 62598fcbbe7bc26dc9252030 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.