content
stringlengths
1
1.04M
input_ids
listlengths
1
774k
ratio_char_token
float64
0.38
22.9
token_count
int64
1
774k
import operator from enum import Enum from functools import reduce from typing import * import numpy as np from .stage import StageType from .utils import ALL, NOT_SET __all__ = [ 'BatchAggregationMode', 'BatchAggregator', 'BatchAggregatorDict', ] class BatchAggregator(object): """ Class to aggregate batch arrays. >>> agg = BatchAggregator(BatchAggregationMode.CONCAT) >>> agg BatchAggregator(mode=CONCAT, axis=0) >>> agg.add(np.array([1, 2, 3, 4])) >>> agg.add(np.array([5, 6])) >>> agg.get() array([1, 2, 3, 4, 5, 6]) >>> agg = BatchAggregator(BatchAggregationMode.AVERAGE) >>> agg BatchAggregator(mode=AVERAGE, axis=None) >>> agg.add(np.array([1, 2, 3, 4])) >>> agg.add(np.array([5, 6])) >>> agg.get() 3.5 >>> agg = BatchAggregator(BatchAggregationMode.SUM) >>> agg BatchAggregator(mode=SUM, axis=None) >>> agg.add(np.array([1, 2, 3, 4])) >>> agg.add(np.array([5, 6])) >>> agg.get() 21 """ mode: BatchAggregationMode axis: Union[int, Tuple[int, ...]] def __init__(self, mode: Union[str, BatchAggregationMode], axis: Optional[Union[int, Tuple[int, ...], List[int]]] = NOT_SET): """ Construct a new :class:`BatchAggregator`. Args: mode: Aggregation mode. axis: The axis to aggregate. Defaults to `0` for `CONCAT` mode, while :obj:`None` for `SUM` and `AVERAGE` mode. """ mode = BatchAggregationMode(mode) if axis is NOT_SET: axis = 0 if mode == BatchAggregationMode.CONCAT else None if mode == BatchAggregationMode.CONCAT: if not isinstance(axis, int): raise TypeError('`axis` must be a int when `mode` is CONCAT.') if axis is not None: if hasattr(axis, '__iter__'): axis = tuple(int(v) for v in axis) if len(axis) == 1: axis = axis[0] else: axis = int(axis) self.mode = mode self.axis = axis self._buf = None self._weight_sum = 0. def get(self) -> Optional[np.ndarray]: """ Get the aggregation result. Returns: The result, or :obj:`None` if no value has been collected. """ if self._buf is not None: if self.mode == BatchAggregationMode.CONCAT: return np.concatenate(self._buf, axis=self.axis) else: return self._buf def add(self, values: np.ndarray, weight: Optional[float] = 1.): """ Add a batch array to the aggregator. Args: values: The batch array. weight: The batch weight, used only in `AVERAGE` mode. """ # CONCAT: append the values to the buf if self.mode == BatchAggregationMode.CONCAT: if self._buf is None: self._buf = [] self._buf.append(values) # SUM elif self.mode == BatchAggregationMode.SUM: batch_sum = np.sum(values, axis=self.axis) if self._buf is None: self._buf = batch_sum else: self._buf += batch_sum # AVERAGE: maintain the `total_weight` state and update the buf else: # infer the batch size and weight batch_shape = np.shape(values) if self.axis is None: batch_size = float(reduce(operator.mul, np.shape(values), 1.)) elif isinstance(self.axis, tuple): batch_size = 1. for a in self.axis: batch_size *= batch_shape[a] else: batch_size = batch_shape[self.axis] batch_weight = weight * batch_size # do update the weight self._weight_sum += batch_weight r1 = weight / self._weight_sum batch_sum = np.sum(values, axis=self.axis) if self._buf is None: self._buf = r1 * batch_sum else: r2 = batch_weight / self._weight_sum self._buf += r1 * batch_sum - r2 * self._buf class BatchAggregatorDict(Mapping[str, BatchAggregator]): """ Maintain a dict of :class:`BatchAggregator` instances, maybe with a default factory to construct :class:`BatchAggregator` instance for new keys. >>> agg_dict = BatchAggregatorDict.new() >>> agg_dict['acc'].add(np.array([0.75, 0.875])) >>> agg_dict['loss'].add(np.array([0.125, 0.2])) >>> len(agg_dict) 2 >>> list(agg_dict) ['acc', 'loss'] >>> agg_dict['acc'].get() 0.8125 >>> agg_dict['loss'].get() 0.1625 """ @staticmethod def new(metrics: Union[Sequence[str], type(ALL)] = ALL, outputs: Union[Sequence[str], type(ALL)] = (), aggregators: Optional[Mapping[str, BatchAggregator]] = None, excludes: Sequence[str] = (), stage_type: Optional[StageType] = None) -> 'BatchAggregatorDict': """ Construct a new :class:`BatchAggregatorDict` according to the field settings `metrics`, `outputs` and `aggregators`. Args: metrics: The names of the batch arrays, which should be aggregated by ``BatchAggregator('AVERAGE', axis=None)``. :obj:`ALL` indicates that an array is by default a metric if it is neither specified in `outputs` nor in `aggregator`. outputs: The names of the batch arrays, which should be aggregated by ``BatchAggregator('CONCAT', axis=0)``. :obj:`ALL` indicates that an array is by default an output if it is neither specified in `outputs` nor in `aggregator`. aggregators: The dict of names and their corresponding aggregators. excludes: The names to exclude. If a name is excluded, no aggregator will be designated to this name, i.e., ``get(name)`` returns None, and ``__getitem__(name)`` raises `KeyError`. stage_type: If specified, will add stage metric prefix to the keys of `metrics`, `outputs` and `aggregators`. Returns: The aggregator dict. Notes: :obj:`ALL` could be specified to at most one of `metrics` and `outputs`. The argument `aggregators` has higher priority than `outputs`, and so does `outputs` have higher priority than `metrics`. That is to say, if a name is specified in both `aggregators` and `outputs`, then the aggregator specified in `aggregators` will be chosen; this is also true if a name is specified in both `outputs` and `metrics`. """ # the aggregator factories average_aggregator_factory = lambda: \ BatchAggregator(mode=BatchAggregationMode.AVERAGE, axis=None) concat_aggregator_factory = lambda: \ BatchAggregator(mode=BatchAggregationMode.CONCAT, axis=0) # determine the default factory if metrics == ALL and outputs == ALL: raise ValueError('Only one of `metrics` and `outputs` can be ' '`ALL`.') elif metrics == ALL: default_factory = average_aggregator_factory elif outputs == ALL: default_factory = concat_aggregator_factory else: default_factory = None # build the aggregator instances agg_dict = {} if metrics != ALL and metrics: for key in metrics: if stage_type is not None: key = stage_type.add_metric_prefix(key) agg_dict[key] = average_aggregator_factory() if outputs != ALL and outputs: for key in outputs: if stage_type is not None: key = stage_type.add_metric_prefix(key) agg_dict[key] = concat_aggregator_factory() if aggregators: for key, agg in aggregators.items(): if stage_type is not None: key = stage_type.add_metric_prefix(key) agg_dict[key] = agg # build the excludes names if excludes and stage_type is not None: excludes = [stage_type.add_metric_prefix(n) for n in excludes] # now construct the `BatchAggregatorDict` instance return BatchAggregatorDict( agg_dict, excludes=excludes, default_factory=default_factory) def __init__(self, aggregators: Mapping[str, BatchAggregator], excludes: Sequence[str] = (), default_factory: Optional[ Callable[[], BatchAggregator]] = None): """ Construct a new :class:`BatchAggregatorDict`. Args: aggregators: The mapping from names to aggregators. excludes: The names to exclude from this dict. If a name is excluded, no aggregator will be designated to this name, i.e., ``get(name)`` returns None, and ``__getitem__(name)`` raises :class:`KeyError`. default_factory: The default factory, which is used to create new :class:`BatchAggregator` instances if the aggregator to a requested name does not exist. If not specified, accessing non-existing name will raise an error. """ self._aggregators = {} self._excludes = set(excludes or ()) self._default_factory = default_factory for key in aggregators: if key not in self._excludes: agg = aggregators[key] if not isinstance(agg, BatchAggregator): raise TypeError(f'Item {key!r} is not an instance of ' f'{BatchAggregator.__qualname__}: ' f'{agg!r}') self._aggregators[key] = agg
[ 11748, 10088, 198, 6738, 33829, 1330, 2039, 388, 198, 6738, 1257, 310, 10141, 1330, 4646, 198, 6738, 19720, 1330, 1635, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 764, 14247, 1330, 15371, 6030, 198, 6738, 764, 26791, 1330, ...
2.101618
4,822
# Ex. 001 print("Olá, Mundo!")
[ 2, 1475, 13, 3571, 16, 198, 198, 4798, 7203, 30098, 6557, 11, 33324, 78, 2474, 8, 198 ]
1.882353
17
from django.contrib import admin from symposion_project.proposals.models import TalkProposal, TutorialProposal, LightningProposal admin.site.register(TalkProposal) admin.site.register(TutorialProposal) admin.site.register(LightningProposal)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 198, 6738, 5659, 1930, 295, 62, 16302, 13, 1676, 1930, 874, 13, 27530, 1330, 12167, 24331, 40725, 11, 36361, 24331, 40725, 11, 12469, 24331, 40725, 628, 198, 28482, 13, 15654, 13, 302...
3.43662
71
from django import forms
[ 6738, 42625, 14208, 1330, 5107, 628, 198 ]
3.857143
7
#!/usr/bin/env python from api.messaging.sms.sms_message_request import SMSMessageRequest __author__ = "Likhit Jain and Yashita P Jain" __copyright__ = "Copyright 2019, Kaleyra" __license__ = "MIT" __version__ = "1.0" __email__ = "support@kaleyra.com" __status__ = "Production" # User will be able to check account usage for a given period. # from_date, to_date are mandatory parameters. # Format of the date has to be specified. smsMessageRequest = SMSMessageRequest(from_date='', to_date='', format='') smsMessageResponse = smsMessageRequest.credit_usage() print(smsMessageResponse.to_json()) print(smsMessageResponse.get_status()) print(smsMessageResponse.get_total_credits()) print(smsMessageResponse.get_total_sms()) print(smsMessageResponse.get_start_date()) print(smsMessageResponse.get_end_date())
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 40391, 13, 37348, 3039, 13, 82, 907, 13, 82, 907, 62, 20500, 62, 25927, 1330, 29287, 12837, 18453, 198, 198, 834, 9800, 834, 796, 366, 43, 13848, 270, 449, 391, 290, 575, ...
3.022305
269
import ast import json import os import re import subprocess import time from multiprocessing.pool import ThreadPool from Postgres_connection.connection import get_postgres_connection from bigdata_logs.logger import getLoggingInstance log = getLoggingInstance() hadoop_bin=os.getenv("hadoop_bin_dir") get_yarn_cmd = "%syarn node -all -list" % hadoop_bin get_node_info = "%syarn node -status " % hadoop_bin get_yarn_master_cmd = "%syarn rmadmin -getAllServiceState" % hadoop_bin get_nm_address_cmd = "%shdfs getconf -confKey yarn.nodemanager.address" % hadoop_bin get_host_ip = "getent hosts " get_status_cmd = "lsof -t -i:" cluster_id = 0 rpyc_port = 0 updated_at = ""
[ 11748, 6468, 198, 11748, 33918, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 850, 14681, 198, 11748, 640, 198, 6738, 18540, 305, 919, 278, 13, 7742, 1330, 14122, 27201, 198, 198, 6738, 2947, 34239, 62, 38659, 13, 38659, 1330, 651, 62...
2.779592
245
from rest_framework.parsers import DataAndFiles, MultiPartParser class MultiPartParser(MultiPartParser): """ Parser for multipart form data, which may include file data. Lifted from https://github.com/tomchristie/django-rest-framework/pull/4026/ to work around request.data being empty when multipart/form-data is posted. See https://github.com/tomchristie/django-rest-framework/issues/3951 """ def parse(self, stream, media_type=None, parser_context=None): """ Parses the incoming bytestream as a multipart encoded form, and returns a DataAndFiles object. `.data` will be a `QueryDict` containing all the form parameters. `.files` will be a `QueryDict` containing all the form files. For POSTs, accept Django request parsing. See issue #3951. """ parser_context = parser_context or {} request = parser_context['request'] _request = request._request if _request.method == 'POST': return DataAndFiles(_request.POST, _request.FILES) return super().parse( stream, media_type=media_type, parser_context=parser_context )
[ 6738, 1334, 62, 30604, 13, 79, 945, 364, 1330, 6060, 1870, 25876, 11, 15237, 7841, 46677, 628, 198, 4871, 15237, 7841, 46677, 7, 29800, 7841, 46677, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 23042, 263, 329, 18540, 433, 129...
2.74186
430
import dill as pickle from typing import Optional, Union from sklearn.base import ClassifierMixin, RegressorMixin from sklearn.metrics import log_loss, accuracy_score, mean_squared_error, r2_score from rule_surrogate import Config from rule_surrogate.utils.io_utils import get_path, obj2pkl, assert_file_exists from rule_surrogate.core.metrics import auc_score FILE_EXTENSION = '.mdl' CLASSIFICATION = 'classification' REGRESSION = 'regression' class SKModelWrapper(ModelBase): """A wrapper that wraps models in Sklearn""" @property @property # def score(self, y_true, y_pred): # raise NotImplementedError("This is the SKModelWrapper base class!")
[ 11748, 288, 359, 355, 2298, 293, 198, 6738, 19720, 1330, 32233, 11, 4479, 198, 198, 6738, 1341, 35720, 13, 8692, 1330, 5016, 7483, 35608, 259, 11, 3310, 44292, 35608, 259, 198, 6738, 1341, 35720, 13, 4164, 10466, 1330, 2604, 62, 22462, ...
2.995633
229
""" KeyGenerator uses the RSA keys to encrypt the email """ import os import re import rsa import pickle from base64 import b64encode, b64decode
[ 37811, 198, 9218, 8645, 1352, 3544, 262, 42319, 8251, 284, 34117, 262, 3053, 198, 37811, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 374, 11400, 198, 11748, 2298, 293, 198, 6738, 2779, 2414, 1330, 275, 2414, 268, 8189, 11, 275, 2414...
3.318182
44
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from datetime import datetime from cinderclient.tests.unit.fixture_data import base # FIXME(jamielennox): use timeutils from oslo FORMAT = '%Y-%m-%d %H:%M:%S' REQUEST_ID = 'req-test-request-id'
[ 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 921, 743, 7330, 198, 2, 257, 4866, 286, 262, 13789, 379, 198, 2,...
3.361991
221
#!/usr/bin/env python from __future__ import print_function from future.standard_library import install_aliases install_aliases() from urllib.parse import urlparse, urlencode from urllib.request import urlopen, Request from urllib.error import HTTPError from os.path import splitext from re import findall from random import randint import json import os import requests from flask import Flask from flask import request from flask import make_response # Flask app should start in global layout app = Flask(__name__) if __name__ == '__main__': port = int(os.getenv('PORT', 5000)) print("Starting app on port %d" % port) app.run(debug=False, port=port, host='0.0.0.0')
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 2003, 13, 20307, 62, 32016, 1330, 2721, 62, 7344, 1386, 198, 17350, 62, 7344, 1386, 3419, 198, 198, 6738, 2956, 297, 571,...
3.202765
217
import random from engine import Scalar class Module: ''' base class''' def zero_grad(self): '''Zero out all the gradients to clear out accumulated gradients from previous loss. (before backprop)''' class Neuron(Module): ''' A single node of computation ''' def __init__(self, n_in, non_linear=True): ''' Randomly initialize weights using `random.uniform` ''' self.weights = [Scalar(random.uniform(-1, 1)) for _ in n_in] self.bias = Scalar(0) self.non_linear = non_linear def parameters(self): ''' Get all parameters ''' return self.weights + [self.bias] class Layer(Module): ''' Class representing single layer in a Neural Network ''' class MLP(Module): ''' A simple feed forward Mutli Layer Perceptron class ''' def __call__(self, x): ''' This is the forward propagation with input x ''' for layer in self.layers: x = layer(x) return x
[ 11748, 4738, 198, 6738, 3113, 1330, 34529, 283, 628, 198, 4871, 19937, 25, 198, 220, 220, 220, 705, 7061, 2779, 1398, 7061, 6, 198, 220, 220, 220, 825, 6632, 62, 9744, 7, 944, 2599, 198, 220, 220, 220, 220, 220, 220, 220, 705, 706...
2.627027
370
import sys sys.path.append("../") import random import training.next_util_functions as func random_state = 42 random.seed(random_state) # assert ['not'] == func.extract_queries_from_explanations(text) # text = "Finally we also handle `backticks as quotes`" # assert ["backticks as quotes"] == func.extract_queries_from_explanations(text) # text = "No quotes here though, so should be empty" # assert [] == func.extract_queries_from_explanations(text)
[ 11748, 25064, 198, 17597, 13, 6978, 13, 33295, 7203, 40720, 4943, 198, 11748, 4738, 198, 11748, 3047, 13, 19545, 62, 22602, 62, 12543, 2733, 355, 25439, 198, 198, 25120, 62, 5219, 796, 5433, 198, 25120, 13, 28826, 7, 25120, 62, 5219, ...
2.8
170
import time import pytest from mrq.job import Job from mrq.queue import Queue @pytest.mark.parametrize(["queues", "enqueue_on"], [ [["main/", "second/"], ["main/", "main/sub", "main/sub/nested", "second/x"]], [["prefix/main/"], ["prefix/main/", "prefix/main/sub", "prefix/main/sub/nested"]], ]) @pytest.mark.parametrize(["queue", "enqueue_on"], [ ["main/", ["/main", "main_", "/", "main", "other"]], ["prefix/main/", ["prefix", "prefix/other", "prefix/main"]], ]) @pytest.mark.parametrize(["delimiter"], ["/", ".", "-"]) def test_refresh_interval(worker): """ Tests that a refresh interval of 0 disables the subqueue detection """ worker.start(queues="test/", flags="--subqueues_refresh_interval=0") time.sleep(2) job_id1 = worker.send_task( "tests.tasks.general.GetTime", {"a": 41}, queue="test/subqueue", block=False) time.sleep(5) job1 = Job(job_id1).fetch().data assert job1["status"] == "queued" worker.stop()
[ 11748, 640, 198, 11748, 12972, 9288, 198, 6738, 285, 81, 80, 13, 21858, 1330, 15768, 198, 6738, 285, 81, 80, 13, 36560, 1330, 4670, 518, 628, 198, 31, 9078, 9288, 13, 4102, 13, 17143, 316, 380, 2736, 7, 14692, 4188, 947, 1600, 366, ...
2.468983
403
import sys num_words = 0 count = {} for word in sys.stdin: num_words += 1 count[word] = count.get(word, 0) + 1 for word in count: print('{} {}', word, count[word]) with open('logfile.csv', 'a') as logger: logger.write('word_count.py,num_words,{}\n'.format(num_words)) logger.write('word_count.py,num_distinct,{}\n'.format(len(count)))
[ 11748, 25064, 198, 198, 22510, 62, 10879, 796, 657, 198, 9127, 796, 23884, 198, 1640, 1573, 287, 25064, 13, 19282, 259, 25, 198, 220, 220, 220, 997, 62, 10879, 15853, 352, 198, 220, 220, 220, 954, 58, 4775, 60, 796, 954, 13, 1136, ...
2.455172
145
from pendulum import Identifier num_links = 1 sample_rate = 100.0 init_type = 'random' sensor_noise = True duration = 10.0 for i in range(20): identifier = Identifier(num_links, duration, sample_rate, init_type, sensor_noise, False, False) identifier.identify()
[ 6738, 44017, 14452, 1330, 11440, 7483, 198, 198, 22510, 62, 28751, 796, 352, 198, 39873, 62, 4873, 796, 1802, 13, 15, 198, 15003, 62, 4906, 796, 705, 25120, 6, 198, 82, 22854, 62, 3919, 786, 796, 6407, 198, 32257, 796, 838, 13, 15, ...
2.459016
122
import numpy as np import os import pickle from models.ResNet_cifar import ResNet from utils.load_cifar import load_train if __name__ == '__main__': nnum_classes = 10 batch_size = 128 epochs = 100 train_x, train_y = load_train(nnum_classes) net = ResNet(True) train_set_len = train_x.shape[0] r_idx = np.arange(train_x.shape[0]) total_batch = int(train_set_len / batch_size) for epoch in range(epochs): # print(train_x[0]) r_idx = np.arange(train_x.shape[0]) np.random.shuffle(r_idx) train_x = train_x[r_idx] train_y = train_y[r_idx] for i in range(total_batch + 1): if ((i + 1) * batch_size) > train_set_len: break batch_x = train_x[i * batch_size: (i + 1) * batch_size] batch_y = train_y[i * batch_size: (i + 1) * batch_size] if i % 100 == 0: global_step, train_loss, train_acc = net.train(batch_x, batch_y, True) print('%d step\ttrain loss : %.3f\ttrain accuracy : %.3f' % (global_step, train_loss, train_acc)) # val_loss, val_acc = net.validate(test_x[:200], test_y[:200]) # print('%d step\ttrain loss : %.3f\ttrain accuracy : %.3f\tval loss : %.3f\tval accuracy : %.3f' % ( # global_step, train_loss, train_acc, val_loss, val_acc)) else: _, loss, ac = net.train(batch_x, batch_y, False)
[ 11748, 299, 32152, 355, 45941, 201, 198, 11748, 28686, 201, 198, 11748, 2298, 293, 201, 198, 6738, 4981, 13, 4965, 7934, 62, 66, 361, 283, 1330, 1874, 7934, 201, 198, 6738, 3384, 4487, 13, 2220, 62, 66, 361, 283, 1330, 3440, 62, 274...
1.91199
784
# # Copyright (c) 2020, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import cudf import cupy as cp import pandas as pd import rmm class GroupByMomentsCal(object): """ This is the class that GroupByMoments uses to calculate the basic statistics of the data that is grouped by a categorical feature. Parameters ----------- col : str column name col_count : str column name to get group counts cont_col : list of str pre-calculated unique values. stats : list of str or set of str, default ['count'] count of groups = ['count'] sum of cont_col = ['sum'] mean of cont_col = ['mean'] var of cont_col = ['var'] std of cont_col = ['std'] limit_frac : float, default 0.1 fraction of memory to use during unique id calculation. gpu_mem_util_limit : float, default 0.8 GPU memory utilization limit during frequency based calculation. If limit is exceeded, unique ids are moved to host memory. gpu_mem_trans_use : float, default 0.8 GPU memory utilization limit during transformation. How much GPU memory will be used during transformation is calculated using this parameter. order_column_name : str, default "order-nvtabular" a column name to be used to preserve the order of input data. cudf's merge function doesn't preserve the order of the data and this column name is used to create a column with integer values in ascending order. ddof : int, default "1" Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. """ def merge(self, gdf): """ Merges gdf with the calculated group stats. Parameters ----------- gdf : cudf DataFrame Returns ----------- stats_joined: cudf DataFrame """ order = cudf.Series(cp.arange(gdf.shape[0])) gdf[self.order_column_name] = order col_names = [] if self.cont_col is not None: for i in range(len(self.cont_col)): col_prefix = f"{self.col}_{self.cont_col[i]}_" col_names.extend(col_prefix + stat for stat in self.stats_names if stat != "count") if "count" in self.stats_names: col_names.append(self.col + "_count") avail_gpu_mem = rmm.get_info().free sub_stats_size = int(avail_gpu_mem * self.gpu_mem_trans_use / (self.stats.shape[1] * 8)) if sub_stats_size == 0: sub_stats_size = 1 stats_joined = None i = 0 while i < self.stats.shape[0]: sub_stats = cudf.from_pandas(self.stats.iloc[i : i + sub_stats_size]) joined = gdf[[self.col, self.order_column_name]].merge( sub_stats, on=[self.col], how="left" ) joined = joined.sort_values(self.order_column_name) joined.reset_index(drop=True, inplace=True) if stats_joined is None: stats_joined = joined[col_names].copy() else: stats_joined = stats_joined.add(joined[col_names], fill_value=0) i = i + sub_stats_size joined = cudf.Series([]) gdf.drop(columns=[self.order_column_name], inplace=True) return stats_joined[col_names] def fit(self, gdf): """ Calculates the requested group stats of gdf and stores results in the host memory. Parameters ----------- gdf : cudf DataFrame """ if self.cont_col is None: groups = gdf[[self.col] + [self.col_count]].groupby([self.col]) else: groups = gdf[[self.col] + self.cont_col + [self.col_count]].groupby([self.col]) if self.cont_col is not None: if self._el_in_stats_names({"sum", "mean", "std", "var"}): sums_part = groups.sum() self.sums_host.append(sums_part.to_pandas()) if self._el_in_stats_names({"std", "var"}): var_part = groups.std(ddof=self.ddof) ** 2 self.vars_host.append(var_part.to_pandas()) if self._el_in_stats_names({"count", "mean", "std", "var"}): counts_part = groups.count() self.counts_host.append(counts_part.to_pandas()) def fit_finalize(self): """ Finalizes the stats calculation. """ self.stats = pd.DataFrame() if "count" in self.stats_names and not (self._el_in_stats_names({"mean", "std", "var"})): counts_dev = cudf.DataFrame([]) for i in range(len(self.counts_host)): counts_part = cudf.from_pandas(self.counts_host.pop()) if counts_dev.shape[0] == 0: counts_dev = counts_part else: counts_dev = counts_dev.add(counts_part, fill_value=0) self.counts = counts_dev.to_pandas() new_col = self.col + "_count" self.stats[new_col] = self.counts[self.col_count] if self.cont_col is not None: if "sum" in self.stats_names and not (self._el_in_stats_names({"mean", "std", "var"})): sums_dev = cudf.DataFrame([]) for i in range(len(self.sums_host)): sums_part = cudf.from_pandas(self.sums_host.pop()) if sums_dev.shape[0] == 0: sums_dev = sums_part else: sums_dev = sums_dev.add(sums_part, fill_value=0) self.sums = sums_dev.to_pandas() for cont_name in self.cont_col: new_col = self.col + "_" + cont_name + "_sum" self.stats[new_col] = self.sums[cont_name] if self._el_in_stats_names({"mean", "std", "var"}): sums_dev = cudf.DataFrame([]) counts_dev = cudf.DataFrame([]) if self._el_in_stats_names({"std", "var"}): var_dev = cudf.DataFrame([]) for i in range(len(self.sums_host)): sums_part = cudf.from_pandas(self.sums_host.pop()) counts_part = cudf.from_pandas(self.counts_host.pop()) if self._el_in_stats_names({"std", "var"}): var_part = cudf.from_pandas(self.vars_host.pop()) if i == 0: counts_dev = counts_part sums_dev = sums_part if self._el_in_stats_names({"std", "var"}): var_dev = var_part else: if self._el_in_stats_names({"std", "var"}): # n1*v1 var_dev = var_dev.mul(counts_dev) # n2*v2 var_dev = var_dev.add(var_part.mul(counts_part), fill_value=0) # n1*(m1-m12)**2 m12_tmp = sums_dev.add(sums_part, fill_value=0) m12_tmp = m12_tmp.mul(1 / (counts_dev.add(counts_part, fill_value=0))) var_dev = var_dev.add( counts_dev.mul( ((sums_dev.mul(1 / counts_dev)).add(-1 * m12_tmp, fill_value=0)) ** 2 ), fill_value=0, ) var_dev = var_dev.add( counts_part.mul( (sums_part.mul(1 / counts_part).add(-1 * m12_tmp, fill_value=0)) ** 2 ), fill_value=0, ) del m12_tmp counts_dev = counts_dev.add(counts_part, fill_value=0) sums_dev = sums_dev.add(sums_part, fill_value=0) if self._el_in_stats_names({"std", "var"}): var_dev = var_dev.mul(1 / counts_dev) result_map = {} if "count" in self.stats_names: self.counts = counts_dev.to_pandas() result_map["count"] = self.counts if "sum" in self.stats_names: self.sums = sums_dev.to_pandas() result_map["sum"] = self.sums if "mean" in self.stats_names: mean_dev = sums_dev.mul(1 / counts_dev) self.mean = mean_dev.to_pandas() result_map["mean"] = self.mean if "var" in self.stats_names: self.var = var_dev.to_pandas() result_map["var"] = self.var if "std" in self.stats_names: self.std = var_dev.sqrt().to_pandas() result_map["std"] = self.std for cont_name in self.cont_col: for su_op in self.supported_ops: if su_op in self.stats_names: if su_op == "count": new_col = self.col + "_count" self.stats[new_col] = result_map[su_op][cont_name] else: new_col = self.col + "_" + cont_name + "_" + su_op self.stats[new_col] = result_map[su_op][cont_name] self.stats[self.col] = self.stats.index self.stats.reset_index(drop=True, inplace=True) return self.stats.shape[0]
[ 2, 198, 2, 15069, 357, 66, 8, 12131, 11, 15127, 23929, 44680, 6234, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, ...
1.869353
5,534
"""bill-versions-enacted Revision ID: 825d555af49 Revises: 3101ec185bdf Create Date: 2015-12-08 08:35:52.703472 """ # revision identifiers, used by Alembic. revision = '825d555af49' down_revision = '3101ec185bdf' from alembic import op import sqlalchemy as sa
[ 37811, 35546, 12, 47178, 12, 268, 23800, 198, 198, 18009, 1166, 4522, 25, 807, 1495, 67, 31046, 1878, 2920, 198, 18009, 2696, 25, 3261, 486, 721, 21652, 65, 7568, 198, 16447, 7536, 25, 1853, 12, 1065, 12, 2919, 8487, 25, 2327, 25, 4...
2.557692
104
import smtplib from email.mime.text import MIMEText ''' 이거 버리고 django.core.mail 사용하기 from django.core.mail import send_mail send_mail( 'Subject here', 'Here is the message.', 'from@example.com', ['to@example.com'], fail_silently=False, ) [ settings.py 설정값들 ] EMAIL_BACKEND EMAIL_FILE_PATH EMAIL_HOST EMAIL_HOST_PASSWORD EMAIL_HOST_USER EMAIL_PORT EMAIL_SSL_CERTFILE EMAIL_SSL_KEYFILE EMAIL_SUBJECT_PREFIX EMAIL_TIMEOUT EMAIL_USE_LOCALTIME '''
[ 11748, 895, 83, 489, 571, 198, 6738, 3053, 13, 76, 524, 13, 5239, 1330, 337, 3955, 2767, 2302, 628, 198, 7061, 6, 198, 35975, 112, 166, 109, 108, 31619, 110, 226, 167, 99, 105, 166, 111, 254, 42625, 14208, 13, 7295, 13, 4529, 2382...
1.987234
235
""" Main configurations of the application, this file needed to be loaded initially. """ import configparser import os from . import ROOT, CONNECTION_STRING, LOG_SUNDAY, MIN_PRODUCTION, PRODUCTION_START_HOUR from .log_me import logMessage if not os.path.exists(ROOT): os.makedirs(ROOT) SLACK_WH = None DISCORD_WH = None GOOGLE_WH = None SLACK_APP_TOKEN = None SLACK_CHANNEL_ID = None DISPLAY_HOUR_COUNT = 0 DATABASE_NAME = "barcode" # default is_api_available = False config = configparser.ConfigParser(interpolation=None) exists = config.read(ROOT + "config.ini") if exists: if config.has_section("SQL SERVER"): try: DATABASE_NAME = config["SQL SERVER"]["DATABASE"] CONNECTION_STRING = ( r"Driver={ODBC Driver 17 for SQL Server};" rf'Server={config["SQL SERVER"]["SERVER"]};' rf"Database={DATABASE_NAME};" rf'uid={config["SQL SERVER"]["UID"]};' rf'pwd={config["SQL SERVER"]["PWD"]};' r"Integrated Security=false;" ) except KeyError as e: CONNECTION_STRING = None logMessage(f'Required key "{e.args[0]}" not found in configurations.') if config.has_section("SLACK APP"): try: SLACK_APP_TOKEN = config["SLACK APP"]["BOT_TOKEN"] SLACK_CHANNEL_ID = config["SLACK APP"]["CHANNEL_ID"] if not SLACK_APP_TOKEN.startswith("xoxb"): SLACK_APP_TOKEN = None else: is_api_available = True except KeyError as e: SLACK_APP_TOKEN = None logMessage(f'Required key "{e.args[0]}" not found in configurations.') if config.has_option("WEBHOOK", "SLACK"): value = config.get("WEBHOOK", "SLACK") if value.startswith("https://hooks.slack.com/services/"): SLACK_WH = value is_api_available = True if config.has_option("WEBHOOK", "DISCORD"): value = config.get("WEBHOOK", "DISCORD") if value.startswith("https://discord"): DISCORD_WH = value is_api_available = True if config.has_option("WEBHOOK", "GOOGLE"): value = config.get("WEBHOOK", "GOOGLE") if value.startswith("https://chat.googleapis.com"): GOOGLE_WH = value is_api_available = True if config.has_option("GENERAL", "SUNDAY_ENABLE"): value = config.get("GENERAL", "SUNDAY_ENABLE") try: if int(value) != 0: LOG_SUNDAY = True except: pass # Default value will consider if config.has_option("GENERAL", "MIN_PRODUCTION_LOGGING"): value = config.get("GENERAL", "MIN_PRODUCTION_LOGGING") try: if int(value) > 0: MIN_PRODUCTION = int(value) except: pass # Default value will consider if config.has_option("GENERAL", "PRODUCTION_START_HOUR"): value = config.get("GENERAL", "PRODUCTION_START_HOUR") try: value = int(value) if value >= 0 and value < 24: PRODUCTION_START_HOUR = value except: pass # Default value will consider if config.has_option("GENERAL", "DISPLAY_HOUR_COUNT"): value = config.get("GENERAL", "DISPLAY_HOUR_COUNT") try: value = int(value) if value == 1: DISPLAY_HOUR_COUNT = value except: pass # Default value will consider if not is_api_available: logMessage("No valid webhook configurations found. Failed to sent report.") else: CONNECTION_STRING = None logMessage("Configuration file missing, Exiting..!") # Then do not run
[ 37811, 198, 13383, 25412, 286, 262, 3586, 11, 428, 2393, 2622, 284, 307, 9639, 7317, 13, 198, 198, 37811, 198, 198, 11748, 4566, 48610, 198, 11748, 28686, 198, 198, 6738, 764, 1330, 15107, 2394, 11, 7102, 45, 24565, 62, 18601, 2751, 1...
2.086908
1,795
# Generated by Django 3.0.7 on 2020-06-21 15:53 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 15, 13, 22, 319, 12131, 12, 3312, 12, 2481, 1315, 25, 4310, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
import numpy as np import pytest from snc.agents.hedgehog.asymptotic_workload_cov.\ compute_asymptotic_cov_bernoulli_service_and_arrivals \ import ComputeAsymptoticCovBernoulliServiceAndArrivals from snc.agents.hedgehog.asymptotic_workload_cov.\ compute_asymptotic_cov_bernoulli_service_poisson_arrivals \ import ComputeAsymptoticCovBernoulliServicePoissonArrivals import snc.agents.hedgehog.workload.workload as workload from snc.environments import examples @pytest.fixture(params=[ComputeAsymptoticCovBernoulliServicePoissonArrivals, ComputeAsymptoticCovBernoulliServiceAndArrivals])
[ 11748, 299, 32152, 355, 45941, 198, 11748, 12972, 9288, 198, 198, 6738, 3013, 66, 13, 49638, 13, 704, 469, 31897, 13, 4107, 76, 457, 6210, 62, 1818, 2220, 62, 66, 709, 13, 59, 198, 220, 220, 220, 24061, 62, 4107, 76, 457, 6210, 62...
2.515873
252
from typing import * with open("i") as f: data = f.read().splitlines() print(simplify_data(data)["z"])
[ 6738, 19720, 1330, 1635, 628, 628, 198, 4480, 1280, 7203, 72, 4943, 355, 277, 25, 198, 220, 220, 220, 1366, 796, 277, 13, 961, 22446, 35312, 6615, 3419, 628, 198, 198, 4798, 7, 14323, 489, 1958, 62, 7890, 7, 7890, 8, 14692, 89, 89...
2.478261
46
from django.urls import path from .views import * app_name = 'home' urlpatterns = [ path('<slug>', index, name='home'), ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 6738, 764, 33571, 1330, 1635, 198, 1324, 62, 3672, 796, 705, 11195, 6, 220, 198, 6371, 33279, 82, 796, 685, 220, 198, 3108, 10786, 27, 6649, 1018, 29, 3256, 6376, 11, 1438, 11639, 1...
2.659574
47
# Copyright FuseSoC contributors # Licensed under the 2-Clause BSD License, see LICENSE for details. # SPDX-License-Identifier: BSD-2-Clause
[ 2, 15069, 376, 1904, 2396, 34, 20420, 198, 2, 49962, 739, 262, 362, 12, 2601, 682, 347, 10305, 13789, 11, 766, 38559, 24290, 329, 3307, 13, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 347, 10305, 12, 17, 12, 2601, 682, 198 ...
3.204545
44
import asyncio import time import trio import pyinstrument trio.run(task)
[ 11748, 30351, 952, 198, 11748, 640, 198, 198, 11748, 19886, 198, 198, 11748, 12972, 259, 43872, 628, 628, 628, 198, 83, 27250, 13, 5143, 7, 35943, 8, 198 ]
2.928571
28
from fnmatch import fnmatch import warnings def prepare_command(command, project): ''' Preprocesses a command by expanding variables like {project}. For example, used in the test_command option, to specify the path to the tests directory. ''' return command.format(python='python', pip='pip', project=project) # Taken from https://stackoverflow.com/a/107717
[ 6738, 24714, 15699, 1330, 24714, 15699, 198, 11748, 14601, 628, 198, 4299, 8335, 62, 21812, 7, 21812, 11, 1628, 2599, 198, 220, 220, 220, 705, 7061, 198, 220, 220, 220, 3771, 14681, 274, 257, 3141, 416, 11581, 9633, 588, 1391, 16302, ...
3.29661
118
# models.py # Michael Huang (mh999), Jeffrey Tsang (jet253) # December 3rd, 2016 """Models module for Breakout This module contains the model classes for the Breakout game. That is anything that you interact with on the screen is model: the paddle, the ball, and any of the bricks. Technically, just because something is a model does not mean there has to be a special class for it. Unless you need something special, both paddle and individual bricks could just be instances of GRectangle. However, we do need something special: collision detection. That is why we have custom classes. You are free to add new models to this module. You may wish to do this when you add new features to your game. If you are unsure about whether to make a new class or not, please ask on Piazza.""" import random # To randomly generate the ball velocity from constants import * from game2d import * # PRIMARY RULE: Models are not allowed to access anything except the module constants.py. # If you need extra information from Play, then it should be a parameter in your method, # and Play should pass it as a argument when it calls the method. class Paddle(GRectangle): """An instance is the game paddle. This class contains a method to detect collision with the ball, as well as move it left and right. You may wish to add more features to this class. The attributes of this class are those inherited from GRectangle. LIST MORE ATTRIBUTES (AND THEIR INVARIANTS) HERE IF NECESSARY """ # GETTERS AND SETTERS (ONLY ADD IF YOU NEED THEM) # INITIALIZER TO CREATE A NEW PADDLE def __init__(self, x, bottom, width, height, color): """Creates a paddle of Parent class Grectangle Initializer: Creates a GRectangle object as the paddle. Paddle is a subclass of GRectangle with the given arguments. Parameter x: The x-coordinate of the paddle Precondition: x is a number (int or float) Parameter bottom: the vertical coordinate of the bottom edge of the paddle Precondition: bottom is a number(int or float) Parameter width: the paddle width Precondition: width is a number(int or float)>=0 Parameter height:the paddle height Precondition: width is a number(int or float)>=0 Parameter color: the paddle color Precondition:color is an RGB object of class colormodel""" GRectangle.__init__(self, x=x, bottom=bottom, width=width, height=height, linecolor=color, fillcolor=color) # METHODS TO MOVE THE PADDLE AND CHECK FOR COLLISIONS def move(self,press): """Moves the paddle left and right in the bounds of the window Sets left attribute to 0 and right attribute to width of game window to create boundaries Parameter: a number added to the x coordinate of the paddle moves in one key press Precondition: press is a number(int or float)""" self.x+=press if self.left<0: self.left=0 if self.right>GAME_WIDTH: self.right=GAME_WIDTH def collides(self,ball): """Returns: True if the ball collides with this brick Parameter ball: The ball to check Precondition: ball is of class Ball""" if ball._vy<0: return self.contains(ball.x-BALL_RADIUS, ball.y-BALL_RADIUS) or\ self.contains(ball.x-BALL_RADIUS, ball.y+BALL_RADIUS)or\ self.contains(ball.x+BALL_RADIUS, ball.y-BALL_RADIUS) or\ self.contains(ball.x+BALL_RADIUS, ball.y+BALL_RADIUS) # ADD MORE METHODS (PROPERLY SPECIFIED) AS NECESSARY class Brick(GRectangle): """An instance is the game paddle. This class contains a method to detect collision with the ball. You may wish to add more features to this class. The attributes of this class are those inherited from GRectangle. LIST MORE ATTRIBUTES (AND THEIR INVARIANTS) HERE IF NECESSARY """ # GETTERS AND SETTERS (ONLY ADD IF YOU NEED THEM) # INITIALIZER TO CREATE A BRICK def __init__(self, left,y, width, height, color): """Initializer: creates a GRectangle object as the brick. Brick is a subclass of GRectangle with the given arguments. Parameter left: The left edge of the paddle Precondition: left is a number (int or float) Parameter y: the vertical coordinate of the paddle Precondition: bottom is a number(int or float) Parameter width: the paddle width Precondition: width is a number(int or float)>=0 Parameter height:the paddle height Precondition: width is a number(int or float)>=0 Parameter color: the paddle color Precondition:color is an RGB object of class colormodel""" GRectangle.__init__(self, left=left, y=y, width=width, height=height, \ linecolor=color, fillcolor=color) # METHOD TO CHECK FOR COLLISION def collides(self,ball): """Returns: True if the ball collides with this brick Parameter ball: The ball to check Precondition: ball is of class Ball""" return self.contains(ball.x-BALL_RADIUS, ball.y-BALL_RADIUS) or\ self.contains(ball.x-BALL_RADIUS, ball.y+BALL_RADIUS) # ADD MORE METHODS (PROPERLY SPECIFIED) AS NECESSARY class Ball(GEllipse): """Instance is a game ball. We extend GEllipse because a ball must have additional attributes for velocity. This class adds this attributes and manages them. INSTANCE ATTRIBUTES: _vx [int or float]: Velocity in x direction _vy [int or float]: Velocity in y direction The class Play will need to look at these attributes, so you will need getters for them. However, it is possible to write this assignment with no setters for the velocities. How? The only time the ball can change velocities is if it hits an obstacle (paddle or brick) or if it hits a wall. Why not just write methods for these instead of using setters? This cuts down on the amount of code in Gameplay. NOTE: The ball does not have to be a GEllipse. It could be an instance of GImage (why?). This change is allowed, but you must modify the class header up above. LIST MORE ATTRIBUTES (AND THEIR INVARIANTS) HERE IF NECESSARY """ # GETTERS AND SETTERS (ONLY ADD IF YOU NEED THEM) def getVX(self): """Returns: velocity in x direction of ball""" return self._vx def getVY(self): """Returns: velocity in y direction of ball""" return self._vy def setVY(self, value): """Sets vy to value Parameter value:value is a number(int or float)""" assert (type(value)==int or type(value)==float) self._vy=value # INITIALIZER TO SET RANDOM VELOCITY def __init__(self, x, y, width, height, color): """Initializer: creates a GRectangle object as the ball. Ball is a subclass of GRectangle with the given arguments for the instance. The initializer also sets the default values for attributes _vx and _vy. Parameter x: The x coordinate of the paddle Precondition: left is a number (int or float) Parameter y: the y coordinate of the paddle Precondition: bottom is a number(int or float) Parameter width: the paddle width Precondition: width is a number(int or float)>=0 Parameter height:the paddle height Precondition: width is a number(int or float)>=0 Parameter color: the paddle color Precondition:color is an RGB object of class colormodel""" GEllipse.__init__(self, x=x, y=y, width=width, height=height,\ fillcolor=color) self._vx = random.uniform(1.0,5.0) self._vx = self._vx * random.choice([-1, 1]) self.setVY(-2.0) # METHODS TO MOVE AND/OR BOUNCE THE BALL def step(self): """Modifies the x and y attributes of the Ball instance to allow it to move at random speeds""" self.x=self.x+self._vx self.y=self.y+self._vy def bounce(self): """Modifies the _vy and _vx class attributes to be negative when the ball object hits any of the four corners of the game window.""" if self.y>=GAME_HEIGHT: self._vy=-self._vy if self.x>=GAME_WIDTH: self._vx=-self._vx if self.x<=0: self._vx=-self._vx if self.y<=0: self._vy=-self._vy # ADD MORE METHODS (PROPERLY SPECIFIED) AS NECESSARY def bottom(self): """Returns: True if the y coordinate of the ball passes through the bottom of the screen; False otherwise Allows the Ball object to pass through the bottom of the game window if the player does not catch the ball with the paddle.""" if self.y<=0: return True else: return False # IF YOU NEED ADDITIONAL MODEL CLASSES, THEY GO HERE
[ 2, 4981, 13, 9078, 198, 2, 3899, 31663, 357, 76, 71, 17032, 828, 19627, 13146, 648, 357, 31173, 28592, 8, 198, 2, 3426, 513, 4372, 11, 1584, 198, 37811, 5841, 1424, 8265, 329, 12243, 448, 198, 198, 1212, 8265, 4909, 262, 2746, 6097,...
2.525176
3,694
from wtforms import Form, TextAreaField, validators
[ 6738, 266, 83, 23914, 1330, 5178, 11, 8255, 30547, 15878, 11, 4938, 2024, 628 ]
3.785714
14
""" super simple tests """ import os import mail_script import requests from jinja2 import Template, Environment, FileSystemLoader jinja_environment = Environment(autoescape=True,loader=FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates'))) test_filing = { 'date': 'today', 'committees': [ { 'committee_name': 'test committee', 'committee_id': '123', 'committee_name': 'Lindsay\'s fictional committee', 'filings': [ { 'candidate_name': '', 'file_number': '123456', 'amendment_indicator': 'N', 'report_type': 'F3', 'report_type_full': 'Sept Quarterly', 'total_receipts': '1000', 'total_disbursements': '5000', 'total_independent_expenditures': '23', 'receipt_date': '08/30/2016', 'coverage_start_date': '07/01/2016', 'coverage_end_date': '08/30/2016', 'url': 'www.example.com', }, { 'candidate_name': 'person', 'file_number': '12346', 'amendment_indicator': 'N', 'report_type': 'F3', 'report_type_full': 'Sept Quarterly', 'total_receipts': '1000', 'total_disbursements': '5000', 'total_independent_expenditures': '23', 'receipt_date': '08/30/2016', 'coverage_start_date': '07/01/2016', 'coverage_end_date': '08/30/2016', 'url': 'www.example.com', }, ] } ] } test_email_render() test_email(test_filing) # data = (r['sub_id'], # primary key # r['committee_id'], # r['committee_name'], # r['candidate_name'] # r['file_number'], # r['amendment_indicator'], # r['report_type'] # r['report_type_full'], # r['total_receipts'], # r['total_disbursements'], # r['total_independent_expenditures'], # r['receipt_date'], # r['coverage_start_date'], # r['coverage_end_date'], # r['pages'], # 'http://docquery.fec.gov/dcdev/posted/{0}.fec'.format(r['file_number'])
[ 37811, 2208, 2829, 5254, 37227, 198, 11748, 28686, 198, 198, 11748, 6920, 62, 12048, 198, 198, 11748, 7007, 198, 6738, 474, 259, 6592, 17, 1330, 37350, 11, 9344, 11, 9220, 11964, 17401, 198, 198, 18594, 6592, 62, 38986, 796, 9344, 7, ...
1.761388
1,383
# Copyright 2018 Canonical Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module containg base class for implementing charm tests.""" import contextlib import logging import unittest import zaza.model import zaza.model as model import zaza.charm_lifecycle.utils as lifecycle_utils import zaza.utilities.openstack as openstack_utils def skipIfNotHA(service_name): """Run decorator to skip tests if application not in HA configuration.""" return _skipIfNotHA_inner_1 class OpenStackBaseTest(unittest.TestCase): """Generic helpers for testing OpenStack API charms.""" @classmethod def setUpClass(cls): """Run setup for test class to create common resourcea.""" cls.keystone_session = openstack_utils.get_overcloud_keystone_session() cls.model_name = model.get_juju_model() cls.test_config = lifecycle_utils.get_charm_config() cls.application_name = cls.test_config['charm_name'] cls.lead_unit = model.get_lead_unit_name( cls.application_name, model_name=cls.model_name) logging.debug('Leader unit is {}'.format(cls.lead_unit)) @contextlib.contextmanager def config_change(self, default_config, alternate_config): """Run change config tests. Change config to `alternate_config`, wait for idle workload status, yield, return config to `default_config` and wait for idle workload status before return from function. Example usage: with self.config_change({'preferred-api-version': '2'}, {'preferred-api-version': '3'}): do_something() :param default_config: Dict of charm settings to set on completion :type default_config: dict :param alternate_config: Dict of charm settings to change to :type alternate_config: dict """ # we need to compare config values to what is already applied before # attempting to set them. otherwise the model will behave differently # than we would expect while waiting for completion of the change _app_config = model.get_application_config(self.application_name) app_config = {} # convert the more elaborate config structure from libjuju to something # we can compare to what the caller supplies to this function for k in alternate_config.keys(): # note that conversion to string for all values is due to # attempting to set any config with other types lead to Traceback app_config[k] = str(_app_config.get(k, {}).get('value', '')) if all(item in app_config.items() for item in alternate_config.items()): logging.debug('alternate_config equals what is already applied ' 'config') yield if default_config == alternate_config: logging.debug('default_config also equals what is already ' 'applied config') return logging.debug('alternate_config already set, and default_config ' 'needs to be applied before return') else: logging.debug('Changing charm setting to {}' .format(alternate_config)) model.set_application_config( self.application_name, alternate_config, model_name=self.model_name) logging.debug( 'Waiting for units to execute config-changed hook') model.wait_for_agent_status(model_name=self.model_name) logging.debug( 'Waiting for units to reach target states') model.wait_for_application_states( model_name=self.model_name, states=self.test_config.get('target_deploy_status', {})) # TODO: Optimize with a block on a specific application until idle. model.block_until_all_units_idle() yield logging.debug('Restoring charm setting to {}'.format(default_config)) model.set_application_config( self.application_name, default_config, model_name=self.model_name) logging.debug( 'Waiting for units to reach target states') model.wait_for_application_states( model_name=self.model_name, states=self.test_config.get('target_deploy_status', {})) # TODO: Optimize with a block on a specific application until idle. model.block_until_all_units_idle() def restart_on_changed(self, config_file, default_config, alternate_config, default_entry, alternate_entry, services): """Run restart on change tests. Test that changing config results in config file being updates and services restarted. Return config to default_config afterwards :param config_file: Config file to check for settings :type config_file: str :param default_config: Dict of charm settings to set on completion :type default_config: dict :param alternate_config: Dict of charm settings to change to :type alternate_config: dict :param default_entry: Config file entries that correspond to default_config :type default_entry: dict :param alternate_entry: Config file entries that correspond to alternate_config :type alternate_entry: dict :param services: Services expected to be restarted when config_file is changed. :type services: list """ # lead_unit is only useed to grab a timestamp, the assumption being # that all the units times are in sync. mtime = model.get_unit_time( self.lead_unit, model_name=self.model_name) logging.debug('Remote unit timestamp {}'.format(mtime)) with self.config_change(default_config, alternate_config): logging.debug( 'Waiting for updates to propagate to {}'.format(config_file)) model.block_until_oslo_config_entries_match( self.application_name, config_file, alternate_entry, model_name=self.model_name) # Config update has occured and hooks are idle. Any services should # have been restarted by now: logging.debug( 'Waiting for services ({}) to be restarted'.format(services)) model.block_until_services_restarted( self.application_name, mtime, services, model_name=self.model_name) logging.debug( 'Waiting for updates to propagate to '.format(config_file)) model.block_until_oslo_config_entries_match( self.application_name, config_file, default_entry, model_name=self.model_name) @contextlib.contextmanager def pause_resume(self, services): """Run Pause and resume tests. Pause and then resume a unit checking that services are in the required state after each action :param services: Services expected to be restarted when config_file is changed. :type services: list """ model.block_until_service_status( self.lead_unit, services, 'running', model_name=self.model_name) model.block_until_unit_wl_status( self.lead_unit, 'active', model_name=self.model_name) model.run_action( self.lead_unit, 'pause', model_name=self.model_name) model.block_until_unit_wl_status( self.lead_unit, 'maintenance', model_name=self.model_name) model.block_until_all_units_idle(model_name=self.model_name) model.block_until_service_status( self.lead_unit, services, 'stopped', model_name=self.model_name) yield model.run_action( self.lead_unit, 'resume', model_name=self.model_name) model.block_until_unit_wl_status( self.lead_unit, 'active', model_name=self.model_name) model.block_until_all_units_idle(model_name=self.model_name) model.block_until_service_status( self.lead_unit, services, 'running', model_name=self.model_name)
[ 2, 15069, 2864, 19507, 605, 12052, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921,...
2.315763
3,984
from tkinter import * from core.helpers.os_helpers import platform_is_windows, platform_is_linux, platform_is_darwin from core.highlight.highlight_circle import HighlightCircle from core.highlight.highlight_rectangle import HighlightRectangle
[ 6738, 256, 74, 3849, 1330, 1635, 198, 198, 6738, 4755, 13, 16794, 364, 13, 418, 62, 16794, 364, 1330, 3859, 62, 271, 62, 28457, 11, 3859, 62, 271, 62, 23289, 11, 3859, 62, 271, 62, 27455, 5404, 198, 6738, 4755, 13, 8929, 2971, 13,...
3.430556
72
from collections import deque
[ 6738, 17268, 1330, 390, 4188, 198 ]
5
6
# Owner(s): ["oncall: gpu_enablement"] import functools from unittest import TestCase import torch_tensorrt.fx.observer as ob from test_observer import execution_verifier, set_observer_callback_rethrow from torch_tensorrt.fx.passes.lower_basic_pass import fuse_permute_linear
[ 2, 23853, 7, 82, 2599, 14631, 261, 13345, 25, 308, 19944, 62, 21633, 434, 8973, 198, 11748, 1257, 310, 10141, 198, 6738, 555, 715, 395, 1330, 6208, 20448, 198, 198, 11748, 28034, 62, 83, 22854, 17034, 13, 21373, 13, 672, 15388, 355, ...
3.088889
90
#!/usr/bin/env python3 """ "Fixes" the output of bcl2fastq to meet our requirements. Files are renamed, grouped by pool, and shifted out of the demultiplexing directory. projects_ready.txt is added listing the projects found projects_pending.txt is deleted if it exists """ # I guess we could go back to keeping the files in /ifs/runqc until they are renamed, # and this might be sensible for backup purposes. In any case I could do this with a # symlink so the code can stay the same. import os, sys, re, time from glob import glob import yaml from collections import namedtuple # Global error collector ERRORS = set() def main(output_dir, prefix=None): """ Usage BCL2FASTQPostprocessor.py <run_dir> [prefix] """ output_dir = os.path.abspath(output_dir) #The prefix is normally the run name ie. the folder name, but driver.sh #will set this explicitly based on RunInfo. if not prefix: prefix = os.path.basename(output_dir) #All renames need to be logged. The log wants to live in the demultiplexing/ #subdirectory. demux_dir = output_dir + "/demultiplexing" with open(os.path.join(demux_dir, 'renames.log'), 'a') as log_fh: log("# %s" % sys.argv[0]) log("# renaming files in %s on %s" % ( demux_dir, time.strftime('%Y-%m-%d %H:%M', time.localtime()) )) project_seen = do_renames(output_dir, prefix, log=log) if ERRORS: log("# There were errors...") for e in ERRORS: print("Error: %s" % e) log("# %s" % e) else: save_projects_ready(output_dir, project_seen) log("# DONE. And projects_ready.txt was saved out.") def save_projects_ready(output_dir, proj_seen): """Save out what we've processed. There might be stuff already in projects_ready.txt and we want to maintain the contents as a sorted set (as per 'sort -u') """ proj_ready_file = os.path.join(output_dir, 'projects_ready.txt') try: with open(proj_ready_file) as pr_fh: for l in pr_fh: proj_seen.add(l.strip()) except FileNotFoundError: # OK, there was no old file pass with open(proj_ready_file, 'w') as pr_fh: for p in sorted(proj_seen): # Only add projects for which there is a directory. This catches the # case where a incorrect project name was in the sample sheet and # the files have been completely flushed on re-do. if os.path.isdir(os.path.join(output_dir,p)): print(p, file=pr_fh) # And delete projects_pending.txt. It probably doesn't exist, which is fine. try: os.unlink(os.path.join(output_dir, 'projects_pending.txt')) except FileNotFoundError: pass def check_project_name(proj_name): """ BCL2FASTQ is already quite fussy about project names. This will just chack that the project name isn't going to clobber any of our folders. """ if "." in proj_name: raise ValueError("Invalid project name {!r} contains a period.".format(proj_name)) if proj_name in "counts demultiplexing md5sums multiqc_reports QC seqdata slurm_output".split(): raise ValueError("Invalid project name {!r} conflicts with reserved names.".format(proj_name)) def do_renames(output_dir, runid, log = lambda m: print(m)): """ The main part of the code that does the renaming (moving). Primary reason for splitting this out from main() is to separate the sys.argv processing and the log file handling in order to simplify unit testing. Returns the list of projects for which files have been renamed. """ proj_seen = set() # Previously we scanned for *.fastq.gz files, but it's more sensible to look for an explicit # list of projects. The projects don't get listed in Stats.json, so go back to sample_summary.yml # directly. This allows us to proceed even when no files were produced (ie. all the barcodes are wrong) try: with open( os.path.join( output_dir, "seqdata/pipeline" , "sample_summary.yml" ) ) as sfh: summary = yaml.safe_load(sfh) for proj in summary['ProjectInfo']: add_project(proj) # Now we can't add any new projects. except FileNotFoundError: log("Failed to read seqdata/pipeline/sample_summary.yml. Proceeding anyway.") # Some funny-business with UMI reads. These come out as read 2 but we actually want to rename them # to _UMI and rename the _3 read as _2. For this reason, gather up the file list first. afile = namedtuple("afile", "samplename lane readnumber project pool_and_library".split()) all_fastq = set() afile_to_filename = dict() # Notwithstanding the list of projects obtained by the summary, look for fastq.gz files in all # locations. # Either we have a list of projects and will find corresponding fastq, or else we have no list and # will make it up as we go along. for fastq_file in glob(os.path.join( output_dir, "demultiplexing/lane*" , "*/*/*.fastq.gz" )): #os.path.split is unhelpful here. Just do it the obvious way. # something like: 10528, 10528EJ0019L01, 10528EJpool03_S19_L005_R1_001.fastq.gz lane_dir, project, pool_and_library, filename = fastq_file.split('/')[-4:] #Note the project as one we've processed. add_project(project) # get information from the filename re_match = re.match( r'(.*)_(S[0-9]+)_L00(\d)_R(\d)_\d+.fastq.gz', filename, re.I) if not re_match: log("# skipping (regex mismatch) %s" % fastq_file) continue samplename = re_match.group(1) # e.g.: We ignore this! lane = re_match.group(3) # e.g.: L00(5) readnumber = re_match.group(4) # e.g.: R(1) # Check lane matches the directory name if not lane_dir == 'lane{}'.format(lane): log("# skipping (lane mismatch) %s" % fastq_file) continue # Add this to the collection thisfile = afile( samplename = samplename, lane = lane, readnumber = readnumber, project = project, pool_and_library = pool_and_library ) all_fastq.add(thisfile) afile_to_filename[thisfile] = fastq_file # Now go again for files not in a subdirectory (if Sample_Name was blank) # (apologies for the copy-paste) for fastq_file in glob(os.path.join( output_dir, "demultiplexing/lane*" , "*/*.fastq.gz" )): #os.path.split is unhelpful here. Just do it the obvious way. # something like: 10528, 10528EJ0019L01, 10528EJpool03_S19_L005_R1_001.fastq.gz lane_dir, project, filename = fastq_file.split('/')[-3:] #Note the project as one we've processed. add_project(project) # get information from the filename # Note this ignores index reads. re_match = re.match( r'(.*)_(S[0-9]+)_L00(\d)_R(\d)_\d+.fastq.gz', filename, re.I) if not re_match: log("# skipping (regex mismatch) %s" % fastq_file) continue pool_and_library = re_match.group(1) # e.g.: 10528EJpool03__10528EJ0019L01 lane = re_match.group(3) # e.g.: L00(5) readnumber = re_match.group(4) # e.g.: R(1) # Check lane matches the directory name if not lane_dir == 'lane{}'.format(lane): log("# skipping (lane mismatch) %s" % fastq_file) continue # Add this to the collection thisfile = afile( samplename = '', lane = lane, readnumber = readnumber, project = project, pool_and_library = pool_and_library ) all_fastq.add(thisfile) afile_to_filename[thisfile] = fastq_file for f in all_fastq: fastq_file = afile_to_filename[f] readnumber = translate_read_number(f, all_fastq) # split out library and pool try: pool, library = f.pool_and_library.split('__') except ValueError: #log("# skipping (no pool__library) %s" % fastq_file) #continue # Decided be a little less strict here. This is also needed for PhiX pool = 'NoPool' library = pool_and_library new_filename = "{runid}_{f.lane}_{library}_{readnumber}.fastq.gz".format(**locals()) new_filename_relative = os.path.join ( f.project, pool, new_filename ) new_filename_absolute = os.path.join ( output_dir, new_filename_relative ) #Make the directory to put it in os.makedirs(os.path.dirname(new_filename_absolute), exist_ok=True) #Paranoia. Rather than checking if the file exists, create it exclusively. #That way, no possible race condition that can cause one file to be renamed over #another file (ignoring remote NFS race conditions). try: log( "mv %s %s" % ('/'.join(fastq_file.split('/')[-4:]), new_filename_relative) ) with open(new_filename_absolute, 'x') as tmp_fd: os.replace(fastq_file, new_filename_absolute) except FileExistsError: log("# FileExistsError renaming %s" % new_filename_relative) raise # Now deal with the undetermined files. undet_fastq = set() for undet_file_absolute in glob(os.path.join( output_dir, "demultiplexing/lane*", "[Uu]ndetermined_*" )): lane_dir, filename = undet_file_absolute.split('/')[-2:] # eg. Undetermined_S0_L004_R1_001.fastq.gz re_match = re.match( r'undetermined_(.*)_L00(\d)_R(\d)_\d+.fastq.gz', filename, re.I) if not re_match: log("# skipping %s" % fastq_file) continue lane = re_match.group(2) readnumber = re_match.group(3) # Check lane matches the directory name if not lane_dir == 'lane{}'.format(lane): log("# skipping (lane mismatch) %s" % fastq_file) continue # Add this to the collection thisfile = afile( samplename = 'undetermined', lane = lane, readnumber = readnumber, project = '', pool_and_library = '' ) undet_fastq.add(thisfile) afile_to_filename[thisfile] = undet_file_absolute # And process the set we just collected for f in undet_fastq: fastq_file = afile_to_filename[f] readnumber = translate_read_number(f, undet_fastq) # eg. 160811_D00261_0355_BC9DA7ANXX_4_unassigned_1.fastq.gz new_filename = "{runid}_{f.lane}_unassigned_{readnumber}.fastq.gz".format(**locals()) new_filename_absolute = os.path.join ( output_dir, new_filename ) #See comment above try: log( "mv %s %s" % ( os.path.join("demultiplexing", filename), new_filename) ) with open(new_filename_absolute, 'x') as tmp_fd: os.rename(fastq_file, new_filename_absolute) except FileExistsError: log("# FileExistsError renaming %s" % new_filename) raise # Cleanup empty project directories (as per Cleanup.py) then warn if any dirs # remain (or, if fact, that's an error). for lane_dir in glob(os.path.join(output_dir, "demultiplexing", "lane*")): for proj in list(proj_seen): for root, dirs, files in os.walk( os.path.join(lane_dir, proj), topdown=False ): try: os.rmdir(root) log("rmdir '%s'" % root) except Exception: # Assume it was non-empty. ERRORS.add("Failed to remove all project directories from demultiplexing area.") log("# could not remove dir '%s'" % root) # And we cannot say the project is ready. # TODO - Should I add it to pending?? proj_seen.discard(proj) # Finally return the projects processed return proj_seen if __name__ == '__main__': print("Running: " + ' '.join(sys.argv)) main(*sys.argv[1:]) if ERRORS: exit(1)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 37811, 366, 22743, 274, 1, 262, 5072, 286, 275, 565, 17, 7217, 80, 284, 1826, 674, 5359, 13, 198, 220, 220, 220, 13283, 389, 25121, 11, 32824, 416, 5933, 11, 290, 14869, 5...
2.25751
5,526
import io import base64 import requests from .base import ViDeployedModel from typing import List
[ 11748, 33245, 198, 11748, 2779, 2414, 198, 11748, 7007, 198, 6738, 764, 8692, 1330, 16049, 49322, 276, 17633, 198, 6738, 19720, 1330, 7343, 628 ]
4.125
24
#!/usr/bin/python import re import os import sys from bs4 import BeautifulSoup if __name__ == '__main__': try: labContent = driveContentScrappers() serializeLabContent(labContent) except Exception, e: print 'Exception! ', e #raise
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 11748, 302, 198, 11748, 28686, 198, 11748, 25064, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 197, 28311, 25,...
2.804598
87
#!/usr/bin/env python3 import sys import re arg_re = re.compile(r'--\S+') if __name__ == '__main__': if len(sys.argv) != 2: sys.exit("Usage: {} tests.sh\n".format(sys.argv[0])) main(sys.argv[1])
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 25064, 198, 11748, 302, 628, 198, 853, 62, 260, 796, 302, 13, 5589, 576, 7, 81, 6, 438, 59, 50, 10, 11537, 628, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, ...
2.04717
106
import numpy as np from optimizer import StochasticOptimizer class Svrg(StochasticOptimizer): """ Stochastic variance-reduced gradient descent with constant stepsize. Reference: https://papers.nips.cc/paper/4937-accelerating-stochastic-gradient-descent-using-predictive-variance-reduction.pdf Arguments: lr (float, optional): an estimate of the inverse smoothness constant """
[ 11748, 299, 32152, 355, 45941, 198, 198, 6738, 6436, 7509, 1330, 520, 5374, 3477, 27871, 320, 7509, 628, 198, 4871, 311, 37020, 70, 7, 1273, 5374, 3477, 27871, 320, 7509, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 520, 5374,...
2.875862
145
# ------------------------------------------------------------------------------------------------ # # MIT License # # # # Copyright (c) 2020, Microsoft Corporation # # # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software # # and associated documentation files (the "Software"), to deal in the Software without # # restriction, including without limitation the rights to use, copy, modify, merge, publish, # # distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the # # Software is furnished to do so, subject to the following conditions: # # # # The above copyright notice and this permission notice shall be included in all copies or # # substantial portions of the Software. # # # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING # # BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # # ------------------------------------------------------------------------------------------------ # import os import tempfile from ..utils import jit from ._misc import dump, dumps, load, loads
[ 2, 16529, 3880, 1303, 198, 2, 17168, 13789, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220,...
2.09802
1,010
import pandas as pd import math import numpy as np from web_scraping.scraping import *
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 10688, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 3992, 62, 1416, 2416, 278, 13, 1416, 2416, 278, 1330, 1635, 198 ]
3
29
""" main.admin ========== """ from django.contrib import admin from .models import InternetConsumption admin.site.register(InternetConsumption)
[ 37811, 198, 12417, 13, 28482, 198, 2559, 855, 198, 37811, 198, 198, 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 198, 6738, 764, 27530, 1330, 4455, 9444, 24098, 628, 198, 28482, 13, 15654, 13, 30238, 7, 28566, 9444, 24098, 8, ...
3.52381
42
#!/usr/bin/python # Copyright (c) 2015 Hewlett-Packard Development Company, L.P. # # This module is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This software is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this software. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: os_user short_description: Manage OpenStack Identity Users extends_documentation_fragment: openstack author: David Shrewsbury version_added: "2.0" description: - Manage OpenStack Identity users. Users can be created, updated or deleted using this module. A user will be updated if I(name) matches an existing user and I(state) is present. The value for I(name) cannot be updated without deleting and re-creating the user. options: name: description: - Username for the user required: true password: description: - Password for the user required: false default: None update_password: required: false default: always choices: ['always', 'on_create'] version_added: "2.3" description: - C(always) will attempt to update password. C(on_create) will only set the password for newly created users. email: description: - Email address for the user required: false default: None default_project: description: - Project name or ID that the user should be associated with by default required: false default: None domain: description: - Domain to create the user in if the cloud supports domains required: false default: None enabled: description: - Is the user enabled required: false default: True state: description: - Should the resource be present or absent. choices: [present, absent] default: present availability_zone: description: - Ignored. Present for backwards compatability required: false requirements: - "python >= 2.6" - "shade" ''' EXAMPLES = ''' # Create a user - os_user: cloud: mycloud state: present name: demouser password: secret email: demo@example.com domain: default default_project: demo # Delete a user - os_user: cloud: mycloud state: absent name: demouser # Create a user but don't update password if user exists - os_user: cloud: mycloud state: present name: demouser password: secret update_password: on_create email: demo@example.com domain: default default_project: demo ''' RETURN = ''' user: description: Dictionary describing the user. returned: On success when I(state) is 'present' type: dictionary contains: default_project_id: description: User default project ID. Only present with Keystone >= v3. type: string sample: "4427115787be45f08f0ec22a03bfc735" domain_id: description: User domain ID. Only present with Keystone >= v3. type: string sample: "default" email: description: User email address type: string sample: "demo@example.com" id: description: User ID type: string sample: "f59382db809c43139982ca4189404650" name: description: User name type: string sample: "demouser" ''' try: import shade HAS_SHADE = True except ImportError: HAS_SHADE = False from ansible.module_utils.basic import * from ansible.module_utils.openstack import * if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 15069, 357, 66, 8, 1853, 30446, 15503, 12, 11869, 446, 7712, 5834, 11, 406, 13, 47, 13, 198, 2, 198, 2, 770, 8265, 318, 1479, 3788, 25, 345, 460, 17678, 4163, 340, 290, 14, 273, 1309...
2.641379
1,595
"""正規表現モジュール re の使い方 オプション:空行/コメントを付与して正規表現を見やすくする (VERBOSE) [説明ページ] https://tech.nkhn37.net/python-re-options/#VERBOSE """ import re text = '私のメールアドレスは、user_01@test.comです。' ptrn = re.compile(r'''([a-z0-9_.+-]+) #local @ #delimiter ([a-z0-9][a-z0-9-]*[a-z0-9]*\.)+[a-z]{2,} #domain''', re.VERBOSE) if result := ptrn.search(text): print(result.group())
[ 37811, 29826, 96, 17358, 237, 26193, 101, 163, 237, 122, 40361, 21091, 24440, 43353, 302, 220, 5641, 45635, 18566, 43095, 198, 20513, 30965, 15661, 1209, 100, 6527, 171, 120, 248, 163, 102, 118, 26193, 234, 171, 120, 237, 24679, 26998, ...
1.39604
303
#!/usr/bin/env python3 """ The mol-mod data importer takes an Excel or Tar file stream, then rearranges and inserts the data into the database. The script is executed inside a running container using the import_excel.py wrapper. """ import hashlib import json import logging import os import re import select import sys import tarfile import tempfile from collections import OrderedDict from datetime import date from io import BytesIO from typing import List, Mapping, Optional import pandas import psycopg2 from psycopg2.extras import DictCursor DEFAULT_MAPPING = os.path.join(os.path.dirname(__file__), 'data-mapping.json') # Define pandas dict of sheets type. This is what's returned from read_excel() PandasDict = Mapping[str, pandas.DataFrame] def as_snake_case(text: str) -> str: """ Converts CamelCase to snake_case. As a special case, this function converts `ID` to `_id` instead of `_i_d`. """ output = "" for i, char in enumerate(text): if char.isupper() and i != 0: # preserve _id if not (char == 'D' and text[i-1] == 'I'): output += "_" output += char.lower() return output def connect_db(pass_file='/run/secrets/postgres_pass'): """ Uses environment variables to set postgres connection settings, and creates a database connection. A simple query to list datasets is then used to verify the connection. """ try: with open(pass_file) as password: password = password.read() except FileNotFoundError: logging.error("Could not read postgres pwd from %s", pass_file) sys.exit(1) try: connection = psycopg2.connect( user=os.getenv('POSTGRES_USER', 'psql'), password=password, database=os.getenv('POSTGRES_DB', 'db'), host=os.getenv('POSTGRES_HOST', 'localhost'), port=os.getenv('POSTGRES_PORT', '5432') ) logging.info("Connected to PostgreSQL database") cursor = connection.cursor(cursor_factory=DictCursor) cursor.execute("SELECT * FROM public.dataset;") logging.debug("Database connection verified") except psycopg2.OperationalError as err: logging.error("Could not connect to postgres database") logging.error(err) sys.exit(1) return connection, cursor def get_base_query(table_mapping: dict): """ Creates an SQL insert query base using the given `table_mapping`. Note that the retured query will not be complete as it will not include any data values. """ field_map = OrderedDict() for field, settings in table_mapping.items(): if field in ['targetTable']: continue field_map[field] = f'"{settings.get("field", as_snake_case(field))}"' fields = ", ".join(list(field_map.values())) return f"INSERT INTO {table_mapping['targetTable']} ({fields})", field_map def format_value(value): """ Formats `value` in a manner suitable for postgres insert queries. """ if isinstance(value, (str, date)): return f"'{value}'" if value is None: return 'NULL' return value def format_values(data: pandas.DataFrame, mapping: dict, start: int = 0, end: Optional[int] = 0) -> str: """ Formats the values in `data` according to the given `mapping` in a way that is suitable for database insert queries. Only values from `start` to `end` will be used. """ values = [] for i in range(start, end): value = [] for field in mapping: value += [format_value(data[field][i])] values += [f'({", ".join(map(str, value))})'] return values def insert_common(data: pandas.DataFrame, mapping: dict, db_cursor: DictCursor, batch_size: int = 1000): """ Inserts `data` into the database based on the given `mapping`. """ base_query, field_mapping = get_base_query(mapping) total = len(data.values) start = 0 end = min(total, batch_size) while start < total: logging.info(" * inserting %s to %s", start, end) values = format_values(data, field_mapping, start, end) query = f"{base_query} VALUES {', '.join(values)};" try: db_cursor.execute(query) except psycopg2.Error as err: logging.error(err) logging.error("No data were imported.") sys.exit(1) start = end end = min(total, end + batch_size) def insert_dataset(data: pandas.DataFrame, mapping: dict, db_cursor: DictCursor) -> int: """ Inserts a single dataset into the database, and returns the database `pid`. """ base_query, field_mapping = get_base_query(mapping['dataset']) if len(data.values) != 1: logging.error("There must be exactly one dataset to insert") sys.exit(1) values = format_values(data, field_mapping, 0, 1) query = f"{base_query} VALUES {', '.join(values)} RETURNING pid;" try: db_cursor.execute(query) except psycopg2.Error as err: logging.error(err) logging.error("No data were imported.") sys.exit(1) return db_cursor.fetchall()[0]['pid'] def insert_events(data: pandas.DataFrame, mapping: dict, db_cursor: DictCursor, batch_size: int = 1000) -> pandas.DataFrame: """ Inserts sampling events, reeturning the given dataframe with updated `pid`'s from the database. """ base_query, field_mapping = get_base_query(mapping['event']) total = len(data.values) start = 0 end = min(total, batch_size) pids = [] while start < total: logging.info(" * inserting %s to %s", start, end) values = format_values(data, field_mapping, start, end) query = f"{base_query} VALUES {', '.join(values)} RETURNING pid;" try: db_cursor.execute(query) pids += [r['pid'] for r in db_cursor.fetchall()] except psycopg2.Error as err: logging.error(err) logging.error("No data were imported.") sys.exit(1) start = end end = min(total, end + batch_size) # assign pids to data for future joins return data.assign(pid=pids) def insert_asvs(data: pandas.DataFrame, mapping: dict, db_cursor: DictCursor, batch_size: int = 1000) -> (pandas.DataFrame, int): """ Inserts asv's into the database, returning the database `pid`'s. Unlike the other categories asv conflicts returns the id of the previously registered entry. """ base_query, field_mapping = get_base_query(mapping['asv']) total = len(data.values) start = 0 end = min(total, batch_size) # get max asv_id before insert (this helps us figure out which asv's were # already in the database). db_cursor.execute("SELECT MAX(pid) FROM asv;") old_max_pid = db_cursor.fetchone()[0] pids = [] while start < total: logging.info(" * inserting %s to %s", start, end) values = format_values(data, field_mapping, start, end) query = f"{base_query} VALUES {', '.join(values)} " + \ "ON CONFLICT (asv_sequence) DO UPDATE SET pid = asv.pid " + \ "RETURNING pid;" try: db_cursor.execute(query) pids += [r['pid'] for r in db_cursor.fetchall()] except psycopg2.Error as err: logging.error(err) logging.error("No data were imported.") sys.exit(1) start = end end = min(total, end + batch_size) # assign pids to data for future joins return data.assign(pid=pids), old_max_pid or 0 def read_data_file(data_file: str, sheets: List[str]): """ Opens and reads the given `sheets` from `data_file`. `data_file` must be a valid excel or tar file. """ # Check input file format is_tar = tarfile.is_tarfile(data_file) if is_tar: tar = tarfile.open(data_file) else: try: pandas.read_excel(data_file) except (ValueError, KeyError): logging.error("Input neither recognized as tar nor as Excel.") sys.exit(1) data = {} # Read one sheet at the time, to catch any missing sheets for sheet in sheets: # Skip occurrences and asvs, as they are taken from asv-table sheet if sheet in ['asv', 'occurrence']: continue try: if is_tar: # Find correct file in tar archive content = None for member in tar: # Ignore parent dir, if any member_name = os.path.basename(member.name) if member_name.split('.')[0] == sheet: csv_file = tar.extractfile(member) content = BytesIO(csv_file.read()) csv_file.close() if not content: raise KeyError try: data[sheet] = pandas.read_csv(content) except Exception: logging.error("Input file '%s' could not be read. " "Please inpect file.", member.name) sys.exit(1) else: data[sheet] = pandas.read_excel(data_file, sheet_name=sheet) except KeyError: logging.error("Input sheet '%s' not found. Aborting.", sheet) sys.exit(1) logging.info("%s file read", "Tar" if is_tar else "Excel") for sheet in data: # Drop empty rows and columns, if any data[sheet] = data[sheet].dropna(how='all') data[sheet] = data[sheet].drop(data[sheet].filter(regex="Unnamed"), axis='columns') # Drop 'domain' column if e.g. ampliseq has included that for sheet in ['asv-table', 'annotation']: data[sheet] = data[sheet].drop(columns=['domain'], errors='ignore') return data def handle_dates(dates: pandas.Series): ''' Removes time digits (e.g. 00:00:00) from (Excel) date / timestamp field, as they mess up validation. Does nothing if field is text / string. ''' try: dates = dates.dt.date # E.g. if field is text except AttributeError: pass return dates def run_import(data_file: str, mapping_file: str, batch_size: int = 1000, validate: bool = True, dry_run: bool = False): """ Inserts the data from data_file into the database using the mapping_file. """ logging.info("Connecting to database") connection, cursor = connect_db() logging.info("Loading mapping file") try: mapping = json.load(open(mapping_file)) except json.decoder.JSONDecodeError as err: filename = os.path.basename(mapping_file) logging.error(f'There is an error in {filename}: {err}') sys.exit(1) logging.info("Loading data file") data = read_data_file(data_file, list(mapping.keys())) # # Derive occurrence and asv 'sheets' from asv-table sheet. # # We do this already here, to include asv and occurrence fields subsequent # validation (which expects 'unpivoted' rows). This means, however, # that asv-table defaults (added in data-mapping.json) will have no effects # on occurrences or asvs. # try: # 'Unpivot' event columns into rows, keeping 'id_columns' as columns id_columns = ['asv_id_alias', 'DNA_sequence', 'associatedSequences', 'kingdom', 'phylum', 'class', 'order', 'family', 'genus', 'specificEpithet', 'infraspecificEpithet', 'otu'] occurrences = data['asv-table'] \ .melt(id_columns, # Store event column header and values as: var_name='event_id_alias', value_name='organism_quantity') except KeyError: logging.error('Input files seem to not have been read properly. ' 'Please, check dimensions (#rows, #cols) below:') for sheet in ['dataset', 'emof', 'mixs', 'asv-table', 'annotation']: logging.error(f'Sheet {sheet} has dimensions {data[sheet].shape}') logging.error('Excel files exported from R have caused this problem ' 'before. Try opening and saving input in Excel, ' 'or importing data as *.tar.gz instead.') sys.exit(1) # Remove rows with organism_quantity 0, # and reset index so that removed rows are no longer referenced # As we do this before validation, we need to catch potential TypeError try: occurrences = occurrences[occurrences.organism_quantity > 0] except TypeError: logging.error('Counts in asv-table include non-numeric values. ' 'No data were imported.') sys.exit(1) else: occurrences.reset_index(inplace=True) # Store as 'sheet' in data object data['occurrence'] = occurrences # Also create asv 'sheet' data['asv'] = occurrences[['asv_id_alias', 'DNA_sequence']] # Make sure we have unique asv rows, # to avoid ON CONFLICT - DO UPDATE errors in insert_asvs data['asv'] = data['asv'].drop_duplicates() data['asv'].reset_index(inplace=True) # Check for field differences between data input and mapping logging.info("Checking fields") if not compare_fields(data, mapping): logging.error('No data were imported.') sys.exit(1) # Deal with Excel timestamps # Requires date fields to exist, so do not move ahead of field check! data['event']['eventDate'] = handle_dates(data['event']['eventDate']) data['annotation']['date_identified'] = \ handle_dates(data['annotation']['date_identified']) if validate: logging.info("Validating input data") if not run_validation(data, mapping): logging.error("No data were imported.") sys.exit(1) if not compare_aliases(data): logging.error("No data were imported.") sys.exit(1) logging.info("Updating defaults") update_defaults(data, mapping) # Replace remaining missing values with None. # These will be transformed by format_value, and inserted into db as [null] for sheet in data.keys(): data[sheet] = data[sheet].where(pandas.notnull(data[sheet]), None) # # Insert DATASET # logging.info("Inserting data") logging.info(" * dataset") dataset = insert_dataset(data['dataset'], mapping, cursor) # # Insert EVENTS # # Get 'event_pid' from dataset and add as new column data['event'] = data['event'].assign(dataset_pid=lambda _: dataset) logging.info(" * event") data['event'] = insert_events(data['event'], mapping, cursor, batch_size) # # Insert MIXS # # Join with 'event' to get 'event_pid' as 'pid' events = data['event'].set_index('event_id_alias') data['mixs'] = data['mixs'].join(events['pid'], on='event_id_alias') logging.info(" * mixs") insert_common(data['mixs'], mapping['mixs'], cursor, batch_size) # # Insert EMOF # # Join with 'event' to get 'event_pid' data['emof'] = data['emof'] \ .join(events['pid'], on='event_id_alias') data['emof'].rename(columns={'pid': 'event_pid'}, inplace=True) logging.info(" * emof") insert_common(data['emof'], mapping['emof'], cursor, batch_size) # # Insert ASV # # Generate 'asv_id' as ASV:<md5-checksum of 'DNA_sequence'> data['asv']['asv_id'] = [f'ASV:{hashlib.md5(s.encode()).hexdigest()}' for s in data['asv']['DNA_sequence']] logging.info(" * asvs") data['asv'], old_max_asv = insert_asvs(data['asv'], mapping, cursor, batch_size) # Drop asv_id column again, as it confuses pandas del data['asv']['asv_id'] # # Insert TAXON_ANNOTATION # # Join with asv to add 'asv_pid' asvs = data['asv'].set_index('asv_id_alias') # Use inner join so that annotation is only added for new asvs data['annotation'] = data['annotation'] \ .join(asvs['pid'], on='asv_id_alias', how='inner') data['annotation'].rename(columns={'pid': 'asv_pid'}, inplace=True) annotation = data['annotation'][data['annotation'].asv_pid > old_max_asv] annotation.reset_index(inplace=True) logging.info(" * annotations") insert_common(annotation, mapping['annotation'], cursor, batch_size) # # Insert OCCURRENCE # # Join with asvs to add 'asv_pid' occurrences = data['occurrence'].join(asvs['pid'], on='asv_id_alias') occurrences.rename(columns={'pid': 'asv_pid'}, inplace=True) # Set contributor´s taxon ranks to empty strings # to allow for concatenation tax_fields = ["kingdom", "phylum", "class", "order", "family", "genus", "specificEpithet", "infraspecificEpithet", "otu"] occurrences[tax_fields] = occurrences[tax_fields].fillna('') # Join with events to add 'event_pid' occurrences = occurrences.join(events, on='event_id_alias') occurrences.rename(columns={'pid': 'event_pid'}, inplace=True) # Concatenate contributor´s taxon rank fields occurrences['previous_identifications'] = \ ["|".join(z) for z in zip(*[occurrences[f] for f in tax_fields])] logging.info(" * occurrences") insert_common(occurrences, mapping['occurrence'], cursor, batch_size) # # Commit or Roll back # if dry_run: logging.info("Dry run, rolling back changes") connection.rollback() else: logging.info("Committing changes") connection.commit() def run_validation(data: PandasDict, mapping: dict): """ Uses `mapping` to run regexp validation of the fields in data. """ valid = True for sheet, fields in mapping.items(): logging.info(" * %s", sheet) for field, settings in fields.items(): previous_mistake = False if 'validation' not in settings: continue try: validator = re.compile(settings['validation']) except re.error as err: logging.error('Seems to be something wrong with a regular ' 'expression used in validation. Please check ' 'data-mapping.json.\nPython says: "%s"', err) sys.exit(1) for value in data[sheet][field]: if not validator.fullmatch(str(value)): valid = False if not previous_mistake: logging.warning(" - malformed value for %s", field) logging.warning(' - validator: "%s"', settings['validation']) previous_mistake = True logging.warning("offending value: %s", value) if valid: logging.info("Validation successful") else: logging.error("Validation failed") return valid def update_defaults(data: PandasDict, mapping: dict): """ Uses the `mapping` dict to set default values in `data`. """ for sheet, fields in mapping.items(): logging.info(" * %s", sheet) for field, settings in fields.items(): if 'default' in settings: default = settings['default'] # If field (listed in mapping) is missing from input form if field not in data[sheet]: # Add default to all rows data[sheet][field] = [default]*len(data[sheet].values) else: # Fill only NaN cells data[sheet][field].fillna(value=default, inplace=True) def compare_sheets(data: PandasDict, sheet1: str, sheet2: str, field1: str, field2: str = None): """ Compares full sets of values for corresponding fields in different sheets, and returns False if these differ. """ if not field2: field2 = field1 set1 = set(data[sheet1][field1]) set2 = set(data[sheet2][field2]) diff = set1.difference(set2) if diff: logging.error('%s value(s) %s in %s sheet not present in %s sheet.', field1, diff, sheet1, sheet2) return False return True def compare_aliases(data: PandasDict): """ Compares sets of key fields between sheets, and returns false if if there is any difference. """ nodiff = True # Check if any events in dependent sheets are missing from event sheet for sheet in ['mixs', 'emof', 'occurrence']: nodiff &= compare_sheets(data, sheet, 'event', 'event_id_alias') # Check if any events lack occurrences nodiff &= compare_sheets(data, 'event', 'occurrence', 'event_id_alias') # Check if any asvs lack annotation nodiff &= compare_sheets(data, 'asv', 'annotation', 'asv_id_alias') return nodiff def compare_fields(data: PandasDict, mapping: dict): """ Combines booleans returned from compare_sets, and returns False if any of these are False (i.e. there is some diff) """ nodiff = True # Check if any mapping fields are missing from data input for sheet in mapping.keys(): set1 = set([k for k in mapping[sheet].keys() if k not in [ # Fields not expected in input 'status', 'targetTable', 'asv_pid', 'dataset_pid', 'pid', 'event_pid', 'asv_id', 'previous_identifications', 'event_pid' ]]) set2 = set(data[sheet].keys()) diff = set1.difference(set2) if diff: logging.error(f'Fields {diff} are missing from sheet {sheet}.') nodiff &= False # Check if any input fields are missing from mapping # Ignore fields that are always expected to be missing, e.g. # Unpivoted event fields from asv-table - which are dataset-specific events = data['occurrence']['event_id_alias'].tolist() # Fields used for deriving db fields, or that are moved to derived sheets expected = ['event_id_alias', 'associatedSequences', 'DNA_sequence', 'asv_sequence', 'asv_id_alias', 'order', 'phylum', 'kingdom', 'class', 'family', 'genus', 'infraspecificEpithet', 'index', 'otu', 'specificEpithet'] for sheet in data.keys(): set1 = set([k for k in data[sheet].keys() if k not in events + expected]) set2 = set(mapping[sheet].keys()) diff = set1.difference(set2) if diff: logging.error(f'Fields {diff} not in mapping.') nodiff &= False return nodiff if __name__ == '__main__': import argparse PARSER = argparse.ArgumentParser(description=__doc__) PARSER.add_argument('--dry-run', action='store_true', help=("Performs all transactions, but then issues a " "rollback to the database so that it remains " "unaffected. This will still increment " "id sequences.")) PARSER.add_argument('--batch_size', type=int, default=100, help=("Sets the max number of rows to be inserted for " "each insert query.")) PARSER.add_argument('--mapping_file', default=DEFAULT_MAPPING, help=("Sets the data mapping file to use for field " "mapping and validation.")) PARSER.add_argument('--no-validation', action="store_true", help="Do NOT validate the data before insertion.") PARSER.add_argument('-v', '--verbose', action="count", default=0, help="Increase logging verbosity (default: warning).") PARSER.add_argument('-q', '--quiet', action="count", default=3, help="Decrease logging verbosity (default: warning).") ARGS = PARSER.parse_args() # Set log level based on ./scripts/import_excel argument # E.g: --v means log level = 10(3-2) = 10 logging.basicConfig(level=(10*(ARGS.quiet - ARGS.verbose))) # Check if there is streaming data available from stdin # (used in case importer is not executed via import_excel.py) if not select.select([sys.stdin], [], [], 0.0)[0]: logging.error("An excel input stream is required") PARSER.print_help() sys.exit(1) # Write stdin to a temporary file with tempfile.NamedTemporaryFile('rb+') as temp: temp.write(sys.stdin.buffer.raw.read()) run_import(temp.name, ARGS.mapping_file, ARGS.batch_size, # --no_validation -> not True = False not ARGS.no_validation, ARGS.dry_run)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 37811, 198, 464, 18605, 12, 4666, 1366, 848, 4337, 2753, 281, 24134, 393, 14110, 2393, 4269, 11, 788, 37825, 6231, 198, 392, 42220, 262, 1366, 656, 262, 6831, 13, 383, 4226, 318, ...
2.329487
10,747
from django.views.generic import ListView, DetailView, CreateView, \ DeleteView, UpdateView, \ ArchiveIndexView, DateDetailView, \ DayArchiveView, MonthArchiveView, \ TodayArchiveView, WeekArchiveView, \ YearArchiveView from school.models import School_crc
[ 6738, 42625, 14208, 13, 33571, 13, 41357, 1330, 7343, 7680, 11, 42585, 7680, 11, 13610, 7680, 11, 3467, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 2...
1.789474
247
import urllib3 import subprocess import requests import time import os import sys import sqlite3 import platform #top try: input = raw_input except NameError: pass global favtv global favmve global tvgenres global moviegenres favtv = [] favmve = [] tvgenres = [] moviegenres = [] MYDB = homedir + "myplex.db" http = urllib3.PoolManager() sql = sqlite3.connect(MYDB) cur = sql.cursor() FIXME = homedir + "fixme.txt" PROBLEMS = homedir + "problems.txt" with open (PROBLEMS, "w") as file: file.write('') file.close() ostype = platform.system() cur.execute('CREATE TABLE IF NOT EXISTS settings(item TEXT, setting TEXT)') sql.commit() command = 'SELECT setting FROM settings WHERE item LIKE \'TVPART\'' cur.execute(command) if not cur.fetchone(): print ("Looks like you have never run the update DB script. I need some information to proceed.\n Enter the link to your metadata.\n Example: http://192.168.1.134:32400/library/metadata/\n") TVPART = str(input('Link:')) cur.execute('INSERT INTO settings VALUES(?, ?)', ("TVPART",TVPART.strip())) sql.commit() print (TVPART + " has been added to the settings table. Moving on.") else: cur.execute(command) test2 = cur.fetchone()[0] TVPART = test2 command = 'SELECT setting FROM settings WHERE item LIKE \'TVGET\'' cur.execute(command) if not cur.fetchone(): print ("Enter the link to your TV show tree.\nExample: http://192.168.1.134:32400/library/sections/1/all/ \n") TVGET = str(input('Link:')) cur.execute('INSERT INTO settings VALUES(?, ?)', ("TVGET",TVGET.strip())) sql.commit() print (TVGET + " has been added to the settings table. Moving on.") else: cur.execute(command) test1 = cur.fetchone()[0] TVGET = test1 command = 'SELECT setting FROM settings WHERE item LIKE \'MOVIEGET\'' cur.execute(command) if not cur.fetchone(): print ("Enter the link to your Movie tree.\nExample: http://192.168.1.134:32400/library/sections/2/all/ \n") MOVIEGET = str(input('Link:')) cur.execute('INSERT INTO settings VALUES(?, ?)', ("MOVIEGET",MOVIEGET.strip())) sql.commit() print (MOVIEGET + " has been added to the settings table. Moving on.") else: cur.execute(command) test = cur.fetchone()[0] MOVIEGET = test print ("Database update starting...\n") cur.execute('CREATE TABLE IF NOT EXISTS shows(TShow TEXT, Episode TEXT, Season INT, Enum INT, Tnum INT, Summary TEXT, Link TEXT)') sql.commit() cur.execute('CREATE TABLE IF NOT EXISTS Movies(Movie TEXT, Summary TEXT, Rating TEXT, Tagline TEXT, Genre TEXT, Director TEXT, Actors TEXT)') sql.commit() cur.execute('CREATE TABLE IF NOT EXISTS TVshowlist(TShow TEXT, Summary TEXT, Genre TEXT, Rating TEXT, Duration INT, Totalnum INT)') sql.commit() #mark try: if "Windows" not in ostype: option = str(sys.argv[1]) else: print ("Notice: For Windows, the update db script may default to 'all' when there is an argument failure.\n") option = "all" if ("updatetv" in option): getgenrestv() startupactiontv() gettvshows() getshows() restoregenrestv() elif ("updatemovies" in option): getgenresmovie() startupactionmovie() getmovies() restoregenremovies() elif ("all" in option): getgenrestv() getgenresmovie() startupactiontv() startupactionmovie() gettvshows() getshows() getmovies() restoregenrestv() restoregenremovies() elif ("getcommercials" in option): getcommercials() print ("Commercial Get Finished.") elif ("getprerolls" in option): getprerolls() print ("Preroll Get Finished.") except TypeError: print ("No option specified. Use 'updatetv' or 'updatemovies' or 'all' to update your db.") print ("Done")
[ 11748, 2956, 297, 571, 18, 198, 11748, 850, 14681, 198, 11748, 7007, 198, 11748, 640, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 44161, 578, 18, 198, 11748, 3859, 198, 2, 4852, 198, 198, 28311, 25, 198, 197, 15414, 796, 8246, 6...
2.803891
1,285
from django.shortcuts import render, redirect, reverse from django.views import View from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.humanize.templatetags.humanize import naturaltime from django.http import JsonResponse, HttpResponse from chat.models import Message from datetime import datetime, timedelta import time # References # https://simpleisbetterthancomplex.com/tutorial/2016/07/27/how-to-return-json-encoded-response.html
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 11, 18941, 11, 9575, 198, 6738, 42625, 14208, 13, 33571, 1330, 3582, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 19816, 1040, 1330, 23093, 37374, 35608, 259, 198, 6738, 42625, ...
3.477612
134
""" sentry.web.frontend.accounts ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import itertools from django.contrib import messages from django.contrib.auth import login as login_user, authenticate from django.core.context_processors import csrf from django.db import transaction from django.http import HttpResponseRedirect from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_protect from django.utils import timezone from sudo.decorators import sudo_required from sentry.models import ( LostPasswordHash, Project, UserOption ) from sentry.plugins import plugins from sentry.web.decorators import login_required from sentry.web.forms.accounts import ( AccountSettingsForm, NotificationSettingsForm, AppearanceSettingsForm, RecoverPasswordForm, ChangePasswordRecoverForm, ProjectEmailOptionsForm) from sentry.web.helpers import render_to_response from sentry.utils.auth import get_auth_providers, get_login_redirect from sentry.utils.safe import safe_execute @login_required @csrf_protect @never_cache @login_required @sudo_required @transaction.atomic @csrf_protect @never_cache @login_required @sudo_required @transaction.atomic @csrf_protect @never_cache @login_required @sudo_required @transaction.atomic @csrf_protect @never_cache @login_required
[ 37811, 198, 82, 13000, 13, 12384, 13, 8534, 437, 13, 23317, 82, 198, 27156, 15116, 8728, 198, 198, 25, 22163, 4766, 25, 357, 66, 8, 2321, 416, 262, 11352, 563, 4816, 11, 766, 37195, 20673, 329, 517, 3307, 13, 198, 25, 43085, 25, 3...
3.327314
443
# -*- Mode: Python; tab-width: 2; indent-tabs-mode:nil; -*- # vim: set ts=2 et sw=2 tw=80: # # Copyright (c) 2013 MathJax Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # FONTFAMILY_PREFIX = "Asana MathJax" FONTNAME_PREFIX = "AsanaMathJax" MATHFONT = "Asana-Math.otf" MAINFONTS = None FONTSPLITTING_EXTRA = { "Variants": [ ("zero.onum", 0xE200), # old style numbers ("one.onum", 0xE201), ("two.onum", 0xE202), ("three.onum", 0xE203), ("four.onum", 0xE204), ("five.onum", 0xE205), ("six.onum", 0xE206), ("seven.onum", 0xE207), ("eight.onum", 0xE208), ("nine.onum", 0xE209), ("u1D49C.salt", 0xE20A), # script salt (used as caligraphic) ("uni212C.salt", 0xE20B), ("u1D49E.salt", 0xE20C), ("u1D49F.salt", 0xE20D), ("uni2130.salt", 0xE20E), ("uni2131.salt", 0xE20F), ("u1D4A2.salt", 0xE210), ("uni210B.salt", 0xE211), ("uni2110.salt", 0xE212), ("u1D4A5.salt", 0xE213), ("u1D4A6.salt", 0xE214), ("uni2112.salt", 0xE215), ("uni2133.salt", 0xE216), ("u1D4A9.salt", 0xE217), ("u1D4AA.salt", 0xE218), ("u1D4AB.salt", 0xE219), ("u1D4AC.salt", 0xE21A), ("uni211B.salt", 0xE21B), ("u1D4AE.salt", 0xE21C), ("u1D4AF.salt", 0xE21D), ("u1D4B0.salt", 0xE21E), ("u1D4B1.salt", 0xE21F), ("u1D4B2.salt", 0xE220), ("u1D4B3.salt", 0xE221), ("u1D4B4.salt", 0xE222), ("u1D4B5.salt", 0xE223), ("u1D4D0.salt", 0xE224), # bold script salt (used as bold caligraphic) ("u1D4D1.salt", 0xE225), ("u1D4D2.salt", 0xE226), ("u1D4D3.salt", 0xE227), ("u1D4D4.salt", 0xE228), ("u1D4D5.salt", 0xE229), ("u1D4D6.salt", 0xE22A), ("u1D4D7.salt", 0xE22B), ("u1D4D8.salt", 0xE22C), ("u1D4D9.salt", 0xE22D), ("u1D4DA.salt", 0xE22E), ("u1D4DB.salt", 0xE22F), ("u1D4DC.salt", 0xE230), ("u1D4DD.salt", 0xE231), ("u1D4DE.salt", 0xE232), ("u1D4DF.salt", 0xE233), ("u1D4E0.salt", 0xE234), ("u1D4E1.salt", 0xE235), ("u1D4E2.salt", 0xE236), ("u1D4E3.salt", 0xE237), ("u1D4E4.salt", 0xE238), ("u1D4E5.salt", 0xE239), ("u1D4E6.salt", 0xE23A), ("u1D4E7.salt", 0xE23B), ("u1D4E8.salt", 0xE23C), ("u1D4E9.salt", 0xE23D) ] } FONTSPLITTING_REMOVE = None FONTDATA = { "FileVersion": "2.3", "Year": "2013", "TeX_factor": None, # Leave None for automatic computation "baselineskip": 1.2, "lineH": .8, "lineD": .2, "hasStyleChar": True } RULECHAR = 0x0305 REMAP = { 0x00AF: 0x0304, # MACRON 0x02B9: 0x2032, # prime 0x03D2: 0x03A5, # Upsilon with hook 0x20F0: 0x002A, # (combining star above) 0x25AA: 0x25A0, # blacksquare 0x25B4: 0x25B2, # blacktriangle 0x25B5: 0x25B3, # blacktriangledown 0x25B8: 0x25B6, # blacktriangleright 0x25BE: 0x25BC, # blacktriangledown 0x25BF: 0x25BD, # triangledown 0x25C2: 0x25C0, # blactriangleleft 0x25C3: 0x25C1, # triangleleft 0x2758: 0x2223, # light vertical bar 0x3008: 0x27E8, # langle 0x3009: 0x27E9, # rangle 0xFE37: 0x23DE, 0xFE38: 0x23DF, # over and under braces } REMAPACCENT = { "\u2192": "\u20D7", # vector arrow "\u2032": "\u0301", # acute accent "\u007E": "\u0303", # tilde "\u2035": "\u0300", # grave accent "\u005E": "\u0302", # hat "\u0060": "\u0300", "\u00B4": "\u0301" } REMAPACCENTUNDER = { } VARIANT = None VARIANTFONTS = [] TEXCALIGRAPHIC = "offsetA: 0xE20A, noLowerCase: 1" TEXCALIGRAPHICFONTS = ["VARIANTS"] TEXOLDSTYLE = "offsetN: 0xE200" TEXOLDSTYLEFONTS = ["VARIANTS"] TEXCALIGRAPHICBOLD = "offsetA: 0xE224, noLowerCase: 1" TEXCALIGRAPHICBOLDFONTS = ["VARIANTS"] TEXOLDSTYLEBOLD = None TEXOLDSTYLEBOLDFONTS = [] SANSSERIFGREEK = None SANSSERIFITALICNUMBER = None SANSSERIFITALICGREEK = None SANSSERIFBOLDITALICNUMBER = None SMALLOPFONTS = None DELIMITERS = { 0x002D: {"alias": 0x0305, "dir": "H"}, # hyphen-minus 0x002F: {"alias": 0x2044, "dir": "H"}, # slash 0x003D: # equal sign { "dir": "H", "HW": [0x003D], "stretch": [(0x003D,"rep")] }, 0x005C: # reversed solidus { "dir": "V", "HW": [0x005C] }, 0x002D: {"alias": 0x0305, "dir": "H"}, # minus 0x005E: {"alias": 0x0302, "dir": "H"}, # wide hat 0x005F: {"alias": 0x0332, "dir": "H"}, # low line 0x007E: {"alias": 0x0303, "dir": "H"}, # wide tilde 0x00AF: {"alias": 0x0305, "dir": "H"}, # macron 0x02C6: {"alias": 0x0302, "dir": "H"}, 0x02C9: {"alias": 0x0305, "dir": "H"}, # macron 0x02DC: {"alias": 0x0303, "dir": "H"}, 0x2015: {"alias": 0x0305, "dir": "H"}, # horizontal line 0x2017: {"alias": 0x0305, "dir": "H"}, # horizontal line 0x203E: {"alias": 0x0305, "dir": "H"}, # overline 0x2195: # updown arrow { "dir": "V", "HW": [0x2195], "stretch": [("arrowup","top"),("glyph3798","ext"),("arrowdown","bot")] }, 0x21D5: # updown double arrow { "dir": "V", "HW": [0x2195], "stretch": [("arrowdblup","top"),("glyph3799","ext"),("arrowdbldown","bot")] }, 0x2212: {"alias": 0x0305, "dir": "H"}, # minus 0x2215: {"alias": 0x2044, "dir": "V"}, # division slash 0x2312: {"alias": 0x23DC, "dir": "H"}, # arc 0x2322: {"alias": 0x23DC, "dir": "H"}, # frown 0x2323: {"alias": 0x23DD, "dir": "H"}, # smile 0x2329: {"alias": 0x27E8, "dir": "V"}, # langle 0x232A: {"alias": 0x27E9, "dir": "V"}, # rangle 0x23AA: # \bracevert { "dir": "V", "HW": [0x23AA], "stretch": [(0x23AA,"ext")] }, 0x23AF: # horizontal line { "dir": "H", "HW": [0x23AF], "stretch": [(0x23AF,"rep")] }, 0x23B0: {"alias": 0x27C6, "dir": "V"}, # \lmoustache 0x23B1: {"alias": 0x27C5, "dir": "V"}, # \rmoustache 0x23D0: # vertical line extension { "dir": "V", "HW": [0x7C], "stretch": [(0x7C,"ext")] }, 0x2500: {"alias": 0x0305, "dir": "H"}, 0x2758: {"alias": 0x2223, "dir": "V"}, # vertical separator 0x27EE: {"alias": 0x0028, "dir": "V"}, 0x27EF: {"alias": 0x0029, "dir": "V"}, 0x27F5: {"alias": 0x2190, "dir": "H"}, # long left arrow 0x27F6: {"alias": 0x2192, "dir": "H"}, # long right arrow 0x27F7: {"alias": 0x2194, "dir": "H"}, # long left-right arrow 0x27F8: {"alias": 0x21D0, "dir": "H"}, # long left double arrow 0x27F9: {"alias": 0x21D2, "dir": "H"}, # long right double arrow 0x27FA: {"alias": 0x21D4, "dir": "H"}, # long left-right double arrow 0x27FB: {"alias": 0x21A4, "dir": "H"}, # long left arrow from bar 0x27FC: {"alias": 0x21A6, "dir": "H"}, # long right arrow from bar 0x27FD: {"alias": 0x2906, "dir": "H"}, # long left double arrow from bar 0x27FE: {"alias": 0x2907, "dir": "H"}, # long right double arrow from bar 0x3008: {"alias": 0x27E8, "dir": "V"}, # langle 0x3009: {"alias": 0x27E9, "dir": "V"}, # rangle 0xFE37: {"alias": 0x23DE, "dir": "H"}, # horizontal brace down 0xFE38: {"alias": 0x23DF, "dir": "H"} # horizontal brace up } DELIMITERS_EXTRA = [ 0x0306, 0x0333, 0x033F, 0x2045, 0x2046, 0x20D0, 0x20D1, 0x20D6, 0x20D7, 0x20E1, 0x20E9, 0x20EE, 0x20EF, 0x21A9, 0x21AA, 0x2210, 0x2211, 0x2229, 0x222B, 0x222C, 0x222D, 0x222E, 0x222F, 0x2230, 0x2231, 0x2232, 0x2233, 0x22C0, 0x22C1, 0x22C2, 0x22C3, 0x23B4, 0x23B5, 0x23DC, 0x23DD, 0x23E0, 0x23E1, 0x27E6, 0x27E7, 0x27EA, 0x27EB, 0x29FC, 0x29FD, 0x2A00, 0x2A01, 0x2A02, 0x2A03, 0x2A04, 0x2A05, 0x2A06, 0x2A07, 0x2A08, 0x2A09, 0x2A0C, 0x2A0D, 0x2A0E, 0x2A0F, 0x2A10, 0x2A11, 0x2A12, 0x2A13, 0x2A14, 0x2A15, 0x2A16, 0x2A17, 0x2A18, 0x2A19, 0x2A1A, 0x2A1B, 0x2A1C ]
[ 2, 532, 9, 12, 10363, 25, 11361, 26, 7400, 12, 10394, 25, 362, 26, 33793, 12, 8658, 82, 12, 14171, 25, 45991, 26, 532, 9, 12, 198, 2, 43907, 25, 900, 40379, 28, 17, 2123, 1509, 28, 17, 665, 28, 1795, 25, 198, 2, 198, 2, 1506...
1.777233
4,893
from pyspark import SparkContext, SparkConf from pyspark.sql import SparkSession # set conf conf = ( SparkConf() .set("spark.hadoop.fs.s3a.fast.upload", True) .set("spark.hadoop.fs.s3a.impl", "org.apache.hadoop.fs.s3a.S3AFileSystem") .set('spark.hadoop.fs.s3a.aws.credentials.provider', 'com.amazonaws.auth.EnvironmentVariableCredentialsProvider') .set('spark.jars.packages', 'org.apache.hadoop:hadoop-aws:2.7.3') ) # apply config sc = SparkContext(conf=conf).getOrCreate() if __name__ == "__main__": # init spark session spark = SparkSession\ .builder\ .appName("ENEM Job")\ .getOrCreate() spark.sparkContext.setLogLevel("WARN") uf_idade = ( spark .read .format("parquet") .load("s3a://dl-processing-zone-539445819060/intermediarias/uf_idade") ) uf_sexo = ( spark .read .format("parquet") .load("s3a://dl-processing-zone-539445819060/intermediarias/uf_sexo") ) uf_notas = ( spark .read .format("parquet") .load("s3a://dl-processing-zone-539445819060/intermediarias/uf_notas") ) print("****************") print("* JOIN FINAL *") print("****************") uf_final = ( uf_idade .join(uf_sexo, on="SG_UF_RESIDENCIA", how="inner") .join(uf_notas, on="SG_UF_RESIDENCIA", how="inner") ) ( uf_final .write .mode("overwrite") .format("parquet") .save("s3a://dl-consumer-zone-539445819060/enem_uf") ) print("*********************") print("Escrito com sucesso!") print("*********************") spark.stop()
[ 6738, 279, 893, 20928, 1330, 17732, 21947, 11, 17732, 18546, 198, 6738, 279, 893, 20928, 13, 25410, 1330, 17732, 36044, 198, 198, 2, 900, 1013, 198, 10414, 796, 357, 198, 4561, 668, 18546, 3419, 198, 220, 220, 220, 764, 2617, 7203, 27...
2.08
825
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """Fix the Flores description.""" from yoyo import step __depends__ = {"20210503_01_xxxx-add-flores-task"} fix_desc = """Machine Translation Evaluation East Asian languages: Javanese, Indonesian, Malay, Tagalog, Tamil, English""" steps = [step(f'UPDATE tasks SET `desc`="{fix_desc}" WHERE task_code="flores_small2"')]
[ 2, 15069, 357, 66, 8, 3203, 11, 3457, 13, 290, 663, 29116, 13, 198, 2, 770, 2723, 2438, 318, 11971, 739, 262, 17168, 5964, 1043, 287, 262, 198, 2, 38559, 24290, 2393, 287, 262, 6808, 8619, 286, 428, 2723, 5509, 13, 198, 198, 37811...
3.401361
147
import pytest import sys import numpy as np import mbuild from dropletbuilder.utils.io_tools import get_fn """ Unit Tests for Droplet class. """
[ 11748, 12972, 9288, 198, 11748, 25064, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 285, 11249, 198, 198, 6738, 3102, 37069, 38272, 13, 26791, 13, 952, 62, 31391, 1330, 651, 62, 22184, 628, 198, 198, 37811, 198, 26453, 30307, 329, 21...
3.170213
47
import xml.etree.cElementTree as ET import pprint from collections import defaultdict import re ''' The code below is to find out how many types of tags are there and the number of each tag. ''' if __name__ == "__main__": test()
[ 11748, 35555, 13, 316, 631, 13, 66, 20180, 27660, 355, 12152, 201, 198, 11748, 279, 4798, 201, 198, 6738, 17268, 1330, 4277, 11600, 201, 198, 11748, 302, 201, 198, 201, 198, 7061, 6, 201, 198, 464, 2438, 2174, 318, 284, 1064, 503, 7...
3.012346
81
from validation import vworkspace #import os with vworkspace() as w: #os.environ['PROPER_EFFECTS_DEBUG_LEVEL'] = '8' w.all_functions.display(activate="print_code_proper_effects")
[ 6738, 21201, 1330, 410, 5225, 10223, 198, 2, 11748, 28686, 198, 198, 4480, 410, 5225, 10223, 3419, 355, 266, 25, 198, 220, 220, 220, 1303, 418, 13, 268, 2268, 17816, 4805, 31054, 62, 37267, 2943, 4694, 62, 30531, 62, 2538, 18697, 2052...
2.647887
71
frase = 'Curso em Vídeo Python' print(frase.upper().count('O')) # Antes não tinha nenhum O maiúsculo, mas com a combinação feita, tem! print(len(frase)) print(frase[0]) print(frase.replace('Python', 'Daniel')) print(frase) # Não contou o 'Daniel' da linha anterior! frase = frase.replace('Python', 'Daniel') print(frase) # AGORA FOI, pq eu salvei na linha anterior! print('Curso' in frase) print(frase.find('Curso')) print(frase.find('curso')) print(frase.lower().find('curso')) print(frase.split()) dividido = frase.split() print(dividido) print(dividido[2]) # Mostra a segunda parte do que foi dividido print(dividido[2][3]) # Mostra o caractere 3 da segunda parte
[ 8310, 589, 796, 705, 26628, 568, 795, 569, 8836, 2934, 78, 11361, 6, 201, 198, 4798, 7, 8310, 589, 13, 45828, 22446, 9127, 10786, 46, 6, 4008, 220, 220, 220, 220, 1303, 3738, 274, 299, 28749, 19783, 3099, 299, 16550, 388, 440, 285, ...
2.337793
299
''' * @Author: csy * @Date: 2019-04-28 13:55:42 * @Last Modified by: csy * @Last Modified time: 2019-04-28 13:55:42 ''' users = { 'aeinstein': { 'first': 'albert', 'last': 'einstein', 'location': 'princeton', }, 'mcurie': { 'first': 'marie', 'last': 'curie', 'location': 'paris', } } for username, userinfo in users.items(): print('Username:'+username.title()) print('\tFullname:'+userinfo['first']+'\t'+userinfo['last']) print('\tLocation:'+userinfo['location']) print()
[ 7061, 6, 198, 9, 2488, 13838, 25, 269, 1837, 220, 198, 9, 2488, 10430, 25, 13130, 12, 3023, 12, 2078, 1511, 25, 2816, 25, 3682, 220, 198, 9, 2488, 5956, 40499, 416, 25, 220, 220, 269, 1837, 220, 198, 9, 2488, 5956, 40499, 640, 2...
2.121673
263
__all__ = ['aesECB', 'aesCBC', 'aesCFB', 'aesOFB', 'aesCTR', 'padding', 'xor', 'chunk'] from blocks import aesECB from blocks import aesCBC from blocks import aesCFB from blocks import aesOFB from blocks import aesCTR from blocks import padding from blocks import xor from blocks import chunk
[ 834, 439, 834, 796, 37250, 64, 274, 2943, 33, 3256, 220, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 705, 64, 274, 29208, 3256, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 705, 64, 274, 22495, 33, 3256, 220...
2.054348
184
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model from msrest.exceptions import HttpOperationError class CloudError(Model): """CloudError. """ _attribute_map = { } class Error(Model): """Error. :param status: :type status: int :param message: :type message: str """ _attribute_map = { 'status': {'key': 'status', 'type': 'int'}, 'message': {'key': 'message', 'type': 'str'}, } class ErrorException(HttpOperationError): """Server responsed with exception of type: 'Error'. :param deserialize: A deserializer :param response: Server response to be deserialized. """ class FirstParameterGroup(Model): """Additional parameters for a set of operations, such as: ParameterGrouping_post_multi_param_groups, ParameterGrouping_post_shared_parameter_group_object. :param header_one: :type header_one: str :param query_one: Query parameter with default. Default value: 30 . :type query_one: int """ _attribute_map = { 'header_one': {'key': '', 'type': 'str'}, 'query_one': {'key': '', 'type': 'int'}, } class ParameterGroupingPostMultiParamGroupsSecondParamGroup(Model): """Additional parameters for post_multi_param_groups operation. :param header_two: :type header_two: str :param query_two: Query parameter with default. Default value: 30 . :type query_two: int """ _attribute_map = { 'header_two': {'key': '', 'type': 'str'}, 'query_two': {'key': '', 'type': 'int'}, } class ParameterGroupingPostOptionalParameters(Model): """Additional parameters for post_optional operation. :param custom_header: :type custom_header: str :param query: Query parameter with default. Default value: 30 . :type query: int """ _attribute_map = { 'custom_header': {'key': '', 'type': 'str'}, 'query': {'key': '', 'type': 'int'}, } class ParameterGroupingPostRequiredParameters(Model): """Additional parameters for post_required operation. All required parameters must be populated in order to send to Azure. :param body: Required. :type body: int :param custom_header: :type custom_header: str :param query: Query parameter with default. Default value: 30 . :type query: int :param path: Required. Path parameter :type path: str """ _validation = { 'body': {'required': True}, 'path': {'required': True}, } _attribute_map = { 'body': {'key': '', 'type': 'int'}, 'custom_header': {'key': '', 'type': 'str'}, 'query': {'key': '', 'type': 'int'}, 'path': {'key': '', 'type': 'str'}, }
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 16529, 35937, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 4091, 13789, 13, 14116, 287, 262, 1628, 6808, 329, 198, 2, 5964, 1321...
2.87376
1,109
# coding: utf-8 # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. from .format_entry import FormatEntry from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401 from oci.decorators import init_model_state_from_kwargs @init_model_state_from_kwargs class RandomDigitsFormatEntry(FormatEntry): """ The Random Digits masking format generates random digits of length within a range. The length range is defined by the startLength and endLength attributes. The start length must be less than or equal to the end length. When masking columns with uniqueness constraint, ensure that the length range is sufficient enough to generate unique values. This masking format pads to the appropriate length in a string, but does not pad when used for a number column. It's a complementary type of Random Number, which is not padded. """ def __init__(self, **kwargs): """ Initializes a new RandomDigitsFormatEntry object with values from keyword arguments. The default value of the :py:attr:`~oci.data_safe.models.RandomDigitsFormatEntry.type` attribute of this class is ``RANDOM_DIGITS`` and it should not be changed. The following keyword arguments are supported (corresponding to the getters/setters of this class): :param type: The value to assign to the type property of this RandomDigitsFormatEntry. Allowed values for this property are: "DELETE_ROWS", "DETERMINISTIC_SUBSTITUTION", "DETERMINISTIC_ENCRYPTION", "DETERMINISTIC_ENCRYPTION_DATE", "FIXED_NUMBER", "FIXED_STRING", "LIBRARY_MASKING_FORMAT", "NULL_VALUE", "POST_PROCESSING_FUNCTION", "PRESERVE_ORIGINAL_DATA", "RANDOM_DATE", "RANDOM_DECIMAL_NUMBER", "RANDOM_DIGITS", "RANDOM_LIST", "RANDOM_NUMBER", "RANDOM_STRING", "RANDOM_SUBSTITUTION", "REGULAR_EXPRESSION", "SHUFFLE", "SQL_EXPRESSION", "SUBSTRING", "TRUNCATE_TABLE", "USER_DEFINED_FUNCTION" :type type: str :param description: The value to assign to the description property of this RandomDigitsFormatEntry. :type description: str :param start_length: The value to assign to the start_length property of this RandomDigitsFormatEntry. :type start_length: int :param end_length: The value to assign to the end_length property of this RandomDigitsFormatEntry. :type end_length: int """ self.swagger_types = { 'type': 'str', 'description': 'str', 'start_length': 'int', 'end_length': 'int' } self.attribute_map = { 'type': 'type', 'description': 'description', 'start_length': 'startLength', 'end_length': 'endLength' } self._type = None self._description = None self._start_length = None self._end_length = None self._type = 'RANDOM_DIGITS' @property def start_length(self): """ **[Required]** Gets the start_length of this RandomDigitsFormatEntry. The minimum number of digits the generated values should have. It can be any integer greater than zero, but it must be less than or equal to the end length. :return: The start_length of this RandomDigitsFormatEntry. :rtype: int """ return self._start_length @start_length.setter def start_length(self, start_length): """ Sets the start_length of this RandomDigitsFormatEntry. The minimum number of digits the generated values should have. It can be any integer greater than zero, but it must be less than or equal to the end length. :param start_length: The start_length of this RandomDigitsFormatEntry. :type: int """ self._start_length = start_length @property def end_length(self): """ **[Required]** Gets the end_length of this RandomDigitsFormatEntry. The maximum number of digits the generated values should have. It can be any integer greater than zero, but it must be greater than or equal to the start length. :return: The end_length of this RandomDigitsFormatEntry. :rtype: int """ return self._end_length @end_length.setter def end_length(self, end_length): """ Sets the end_length of this RandomDigitsFormatEntry. The maximum number of digits the generated values should have. It can be any integer greater than zero, but it must be greater than or equal to the start length. :param end_length: The end_length of this RandomDigitsFormatEntry. :type: int """ self._end_length = end_length
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 2, 15069, 357, 66, 8, 1584, 11, 33160, 11, 18650, 290, 14, 273, 663, 29116, 13, 220, 1439, 2489, 10395, 13, 198, 2, 770, 3788, 318, 10668, 12, 36612, 284, 345, 739, 262, 14499, 2448, 33532, 1...
2.660742
1,913
#/usr/bin/env python3 if __name__ == "__main__": print(max(factorize(int(input("Enter a number: ")))))
[ 2, 14, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 3601, 7, 9806, 7, 31412, 1096, 7, 600, 7, 15414, 7203, 17469, 257, 1271, 25, 366, 4008, 22305, 19...
2.454545
44
import pytest from cisa.cisa import get_ics_threats, get_vulnerability_reports from config.config import get_software_list, config_parser, config_parser_section
[ 11748, 12972, 9288, 198, 6738, 269, 9160, 13, 66, 9160, 1330, 651, 62, 873, 62, 19971, 82, 11, 651, 62, 85, 40920, 62, 48922, 198, 6738, 4566, 13, 11250, 1330, 651, 62, 43776, 62, 4868, 11, 4566, 62, 48610, 11, 4566, 62, 48610, 62...
3.458333
48
from django.contrib import admin from .models import Homework, Done @admin.register(Homework) @admin.register(Done) # Register your models here.
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 764, 27530, 1330, 8074, 6433, 11, 24429, 198, 198, 31, 28482, 13, 30238, 7, 28718, 6433, 8, 198, 198, 31, 28482, 13, 30238, 7, 45677, 8, 628, 198, 2, 17296, 534, 4981, 994, ...
3.311111
45
import argparse import os import random import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader from gym_dataset import GymDataset from gym_canvas import CanvasEnv from model import FCN if __name__ == "__main__": main()
[ 11748, 1822, 29572, 198, 11748, 28686, 198, 11748, 4738, 198, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 40085, 355, 6436, 198, 6738, 28034, 13, 26791, 13, 7890, 1330, 6060, 17401, 198, 198, 67...
3.125
88
#encoding utf-8 #__author__ = Jonas Duarte, duarte.jsystem@gmail.com #Python3 __author__ = 'Jonas Duarte'
[ 2, 12685, 7656, 3384, 69, 12, 23, 198, 198, 2, 834, 9800, 834, 796, 40458, 10343, 32074, 11, 7043, 32074, 13, 73, 10057, 31, 14816, 13, 785, 198, 2, 37906, 18, 198, 834, 9800, 834, 796, 705, 18219, 292, 10343, 32074, 6, 628, 628 ]
2.5
44
""" Usage: Create ~/.pypirc with info: [distutils] index-servers = pypi [pypi] repository: https://upload.pypi.org/legacy/ username: ... password: ... (Not needed anymore) Registering the project: python3 setup.py register New release: python3 setup.py sdist upload I had some trouble at some point, and this helped: pip3 install --user twine python3 setup.py sdist twine upload dist/background_zmq_ipython-* See also MANIFEST.in for included files. For debugging this script: python3 setup.py sdist pip3 install --user dist/...*.tar.gz -v (Without -v, all stdout/stderr from here will not be shown.) """ from distutils.core import setup import time from pprint import pprint import os import sys from subprocess import Popen, check_output, PIPE def parse_pkg_info(fn): """ :param str fn: :rtype: dict[str,str] """ res = {} for ln in open(fn).read().splitlines(): if not ln or not ln[:1].strip(): continue key, value = ln.split(": ", 1) res[key] = value return res if os.path.exists("PKG-INFO"): print("Found existing PKG-INFO.") info = parse_pkg_info("PKG-INFO") version = info["Version"] print("Version via PKG-INFO:", version) else: try: version = git_head_version() print("Version via Git:", version) except Exception as exc: print("Exception while getting Git version:", exc) sys.excepthook(*sys.exc_info()) version = time.strftime("1.%Y%m%d.%H%M%S", time.gmtime()) print("Version via current time:", version) if os.environ.get("DEBUG", "") == "1": debug_print_file(".") debug_print_file("PKG-INFO") setup( name='background_zmq_ipython', version=version, packages=['background_zmq_ipython'], package_dir={'background_zmq_ipython': ''}, description='Background ZMQ IPython/Jupyter kernel', author='Albert Zeyer', author_email='albzey@gmail.com', url='https://github.com/albertz/background-zmq-ipython', license='2-clause BSD license', long_description=open('README.rst').read(), install_requires=open('requirements.txt').read().splitlines(), # https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: Education', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Operating System :: Unix', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
[ 198, 37811, 198, 28350, 25, 198, 198, 16447, 39763, 79, 4464, 1980, 351, 7508, 25, 628, 220, 220, 220, 685, 17080, 26791, 60, 198, 220, 220, 220, 6376, 12, 2655, 690, 796, 198, 220, 220, 220, 220, 220, 220, 220, 279, 4464, 72, 628...
2.547684
1,101
import os app_config = dict( development = DevelopmentConfig, testing = TestingConfig, production = ProductionConfig )
[ 11748, 28686, 628, 198, 198, 1324, 62, 11250, 796, 8633, 7, 198, 220, 220, 220, 2478, 796, 7712, 16934, 11, 198, 220, 220, 220, 4856, 796, 23983, 16934, 11, 198, 220, 220, 220, 3227, 796, 19174, 16934, 198, 8 ]
3.410256
39
#!/usr/bin/env python3 """ wautils A set of web-based tools for Wild Apricot Integration o Accepts your Wild Apricot Credentials via Wild Apricot OAuth o Determines if you are have Wild Apricot admin credentials o Give you further access only if you have admin credentials """ usage_mesg = """ usage: wautils [--debug] Start up wautils web server """ from flask import Flask, redirect, url_for, render_template, flash, g, request, send_file from flask_cors import CORS from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager, UserMixin, login_user, logout_user, current_user, login_required from flask_bootstrap import Bootstrap from flask_restful import Resource as FlaskRestResource from flask_restful import reqparse as FlaskRestReqparse from flask_restful import Api as FlaskRestAPI from flask_restful import request as FlaskRestRequest import WaApi import urllib import os,sys,requests from dotenv import load_dotenv from oauth import OAuthSignIn import getopt import json import random import csv pos_ran_chars = 'abcdefghijknpqrstuvwxyz23456789' # for debugging import pprint ex_code_fail = 1 # used with sys.exit() ex_code_success = 0 # get keys and config info from .env load_dotenv() wa_uri_prefix = "https://api.wildapricot.org/v2.1/" wa_uri_prefix_accounts = wa_uri_prefix + "Accounts/" app = Flask(__name__) app.secret_key = os.environ['FLASK_SECRET_KEY'] app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite' app.config['OAUTH_CREDENTIALS'] = { 'wildapricot' : { 'account' : os.environ['WA_ACCOUNT'], 'id' : os.environ['OAUTH_ID'], 'api_key' : os.environ['OAUTH_API_KEY'], 'secret' : os.environ['OAUTH_SECRET'] } } # rest api support restapi = FlaskRestAPI(app) # bootstrap framework support Bootstrap(app) # allow cross-site origin CORS(app) # tell bootstrap NOT to fetch from CDNs app.config['BOOTSTRAP_SERVE_LOCAL'] = True # login manager setup lm = LoginManager(app) lm.login_view = 'utils' # database setup db = SQLAlchemy(app) # for debugging pp = pprint.PrettyPrinter(stream=sys.stderr) @lm.user_loader @app.route('/') @app.route('/signoffs') @login_required @app.route('/events') @login_required @app.route('/dump_events') @login_required """ {'AccessLevel': 'Public', 'CheckedInAttendeesNumber': 0, 'ConfirmedRegistrationsCount': 0, 'EndDate': '2021-04-01T00:00:00-04:00', 'EndTimeSpecified': False, 'EventType': 'Regular', 'HasEnabledRegistrationTypes': True, 'Id': 4053381, 'Location': '', 'Name': 'Adams Test', 'PendingRegistrationsCount': 0, 'RegistrationEnabled': True, 'RegistrationsLimit': None, 'StartDate': '2021-04-01T00:00:00-04:00', 'StartTimeSpecified': False, 'Tags': [], 'Url': 'https://api.wildapricot.org/v2.1/accounts/335649/Events/4053381'} """ """ swipe_file = open('/tmp/events.csv','w') swipe_file_csv = csv.writer(swipe_file) q = BadgeSwipe.query.order_by(desc(BadgeSwipe.timestamp)) for r in q: dat = r.to_dict() ar = [] ar.append(dat['timestamp']) ar.append(dat['user_name']) if '.' in dat['card_id']: # put leading zero back into card id (fac,id) = dat['card_id'].split('.') id = '0' + id if len(id) == 4 else id id = '00' + id if len(id) == 3 else id id = '000' + id if len(id) == 2 else id id = '0000' + id if len(id) == 1 else id dat['card_id'] = fac + id ar.append(dat['card_id']) swipe_file_csv.writerow(ar) swipe_file.close() return send_file('/tmp/swipes.csv',as_attachment=True,attachment_filename='swipes.csv') """ @app.route('/members') @login_required @app.route('/utils') @login_required @app.route('/logout') @app.route('/authorize/<provider>') @app.route('/callback/<provider>') ################################################################################ # REST API STUFF ### class WAGetAnyEndpointREST(FlaskRestResource): """ REST API for our js in the browser to call us on """ restapi.add_resource(WAGetAnyEndpointREST,'/api/v1/wa_get_any_endpoint') def wa_get_any_endpoint_rest(): """ respond passed endpoint up to WA, return response to requestor """ pp.pprint('------wa_get_any_endpoint_rest()--------') rp = FlaskRestReqparse.RequestParser() rp.add_argument('endpoint',type=str) rp.add_argument('$asyncfalse',type=str) args = rp.parse_args() wapi,creds = wapi_init() # browser js doesn't necessarily know our account ID. We add it here ep = args['endpoint'].replace('$accountid', creds['account']) # get this user's info wa_accounts_contact_me = wapi.execute_request( wa_uri_prefix_accounts + creds['account'] + "/contacts/" + str(current_user.id)) if wa_accounts_contact_me.IsAccountAdministrator: # WA account admins get carte blanche to do anything return wa_execute_request_raw(wapi,wa_uri_prefix + ep) else: # non admins get to do only certain things if (urllib.parse.urlparse(ep).path == 'accounts/' + creds['account'] + '/events/'): return wa_execute_request_raw(wapi,wa_uri_prefix + ep) if (urllib.parse.urlparse(ep).path == 'accounts/' + creds['account'] + '/eventregistrations'): return wa_execute_request_raw(wapi,wa_uri_prefix + ep) return {"error":1,"error_message":"permision denied"} ### class WAPutAnyEndpointREST(FlaskRestResource): """ REST API for our js in the browser to call us on """ restapi.add_resource(WAPutAnyEndpointREST,'/api/v1/wa_put_any_endpoint') def wa_put_any_endpoint_rest(): """ send PUT endpoint rq up to WA, return response to requestor """ rp = FlaskRestReqparse.RequestParser() wapi,creds = wapi_init() rq = FlaskRestRequest.json ep = rq['endpoint'] pd = rq['put_data'] ep = ep.replace('$accountid', creds['account']) wa_accounts_contact_me = wapi.execute_request( wa_uri_prefix_accounts + creds['account'] + "/contacts/" + str(current_user.id)) if wa_accounts_contact_me.IsAccountAdministrator: try: response = wapi.execute_request_raw(wa_uri_prefix + ep, data=pd, method="PUT") except urllib.error.HTTPError as e: return {"error":1,"error_message": ep + ':' + str(e) } except WaApi.ApiException as e: return {"error":1,"error_message": ep + ':' + str(e) } decoded = json.loads(response.read().decode()) result = [] if isinstance(decoded, list): for item in decoded: result.append(item) elif isinstance(decoded, dict): result.append(decoded) return result else: return {"error":1,"error_message":"You are not a WA account admin"} ## end rest stuff ################################################################################ # Execution starts here if __name__ == '__main__': # parse cmd line args and perform operations try: # parse cmd line args ops,args = getopt.getopt(sys.argv[1:],"c:",["debug","cmd="]) except getopt.GetoptError as err: sys.stderr.write(str(err) + '\n') sys.stderr.write(usage_mesg) sys.exit(ex_code_fail) for o,a in ops: if (o == '--debug'): db.create_all() app.run(host='0.0.0.0',port=8080,debug=True) if (o == '--cmd' or o == '-c'): cmd = a wapi,creds = wapi_init() response = wapi.execute_request_raw(wa_uri_prefix_accounts + creds['account'] + "/contacts/?$async=false") sys.stderr.write(json.dumps( response.read().decode(), indent=4,sort_keys=True)) """ wapi,creds = wapi_init() response = wapi.execute_request_raw("https://api.wildapricot.org/v2.1/", method="GET") """ sys.exit(ex_code_success) # run production on local port that apache proxy's to sys.stderr.write("Starting web server\n") db.create_all() app.run(port=7000,debug=False) # no options given. print usage and exit sys.stderr.write(usage_mesg) sys.exit(ex_code_fail)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 37811, 198, 198, 86, 2306, 4487, 220, 628, 220, 220, 220, 317, 900, 286, 3992, 12, 3106, 4899, 329, 6183, 2758, 291, 313, 38410, 220, 220, 198, 220, 220, 220, 220, 198, 22...
2.427368
3,442
#!/usr/bin/env python3 import time import unicornhat as uh import requests import signal import buttonshim import subprocess # Import the library import pihole as ph #from blinkt import set_pixel, set_brightness, show, clear uh.set_layout(uh.PHAT) #blinkt.set_clear_on_exit() import subprocess, platform Cr,Cg,Cb = 0,50,0 Gr,Gg,Gb = 0,70,0 Ar,Ag,Ab = 130,60,0 Rr,Rg,Rb = 255,0,0 RrX,RgX,RbX = 130,0,0 ExternalSource = True HoleStatus = "enabled" uh.clear() while True: uh.brightness(1) if pingOk('188.72.89.2'): #PiHole PixelNumber =0 PixelRow =0 uh.set_pixel(PixelNumber,PixelRow,Cr,Cg,Cb) uh.show() if website_up('http://192.168.11.125/admin/'): pihole = ph.PiHole("192.168.11.125") pihole.refresh() if pihole.status == "enabled": uh.set_pixel(PixelNumber,PixelRow, Gr,Gg,Gb) else: uh.set_pixel(PixelNumber,PixelRow, Rr,Rg,Rb) uh.show() if not pihole.status == HoleStatus: HoleStatus = pihole.status exec(open("/usr/local/bin/status_check/DHM_update.py").read()) #exec(open("/usr/local/bin/status_check/inky_update.py").read()) else: uh.set_pixel(PixelNumber,PixelRow, Rr,Rg,Rb) uh.show() #HomeBridge Admin PixelNumber =1 PixelRow =0 uh.set_pixel(PixelNumber,PixelRow,Cr,Cg,Cb) uh.show() if website_up('http://192.168.11.160:8581/login'): uh.set_pixel(PixelNumber,PixelRow, Gr,Gg,Gb) else: uh.set_pixel(PixelNumber,PixelRow, Rr,Rg,Rb) uh.show() #CODEX ADMIN PixelNumber =3 PixelRow =0 uh.set_pixel(PixelNumber,PixelRow,Cr,Cg,Cb) uh.show() if website_up('http://192.168.11.190:3755/cgi-bin/'): uh.set_pixel(PixelNumber,PixelRow, Gr,Gg,Gb) else: uh.set_pixel(PixelNumber,PixelRow, Rr,Rg,Rb) uh.show() #Codex PLEX PixelNumber =4 PixelRow =0 uh.set_pixel(PixelNumber,PixelRow,Cr,Cg,Cb) uh.show() if website_up('http://192.168.11.190:32400/web/'): uh.set_pixel(PixelNumber,PixelRow, Gr,Gg,Gb) else: uh.set_pixel(PixelNumber,PixelRow, Rr,Rg,Rb) uh.show() if ExternalSource == True: #PiHole #PixelNumber =0 #PixelRow =2 #uh.set_pixel(PixelNumber,PixelRow,Cr,Cg,Cb) #uh.show() #if website_up('http://192.168.195.112/admin/'): #pihole = ph.PiHole("192.168.195.112") #pihole.refresh() #if pihole.status == "enabled": #uh.set_pixel(PixelNumber,PixelRow, Gr,Gg,Gb) #else: #uh.set_pixel(PixelNumber,PixelRow, Rr,Rg,Rb) #uh.show() #else: #uh.set_pixel(PixelNumber,PixelRow, Rr,Rg,Rb) #uh.show() #Jane Pi PixelNumber =3 PixelRow =2 uh.set_pixel(PixelNumber,PixelRow,Cr,Cg,Cb) uh.show() if pingOk('192.168.195.112'): uh.set_pixel(PixelNumber,PixelRow, Gr,Gg,Gb) else: uh.set_pixel(PixelNumber,PixelRow, Rr,Rg,Rb) uh.show() #Janie Plus PLEX PixelNumber =4 PixelRow =2 uh.set_pixel(PixelNumber,PixelRow,Cr,Cg,Cb) uh.show() if website_up('http://192.168.195.112:32400/web/'): uh.set_pixel(PixelNumber,PixelRow, Gr,Gg,Gb) else: uh.set_pixel(PixelNumber,PixelRow, Rr,Rg,Rb) uh.show() #Temp #buttonshim.set_pixel(0x94, 0x00, 0xd3) PixelNumber =7 PixelRow =3 uh.set_pixel(PixelNumber,PixelRow,Cr,Cg,Cb) #show() cmd ="cat /sys/class/thermal/thermal_zone0/temp" thermal = subprocess.check_output(cmd, shell=True).decode("utf8") tempC = round(float(thermal) / 1e3,1) # Change backlight if temp changes #print(tempC) if tempC < 40: uh.set_pixel(PixelNumber,PixelRow, 0,0,50) #buttonshim.set_pixel(0,0,200) elif tempC < 50: uh.set_pixel(PixelNumber,PixelRow, 0,50,0) #buttonshim.set_pixel(0,200,0) elif tempC > 60: uh.set_pixel(PixelNumber,PixelRow, 75,0,0) #buttonshim.set_pixel(255,0,0) else: uh.set_pixel(PixelNumber,PixelRow, 50,50,0) #buttonshim.set_pixel(200,200,0) uh.show() #clear() #show() time.sleep(5) else: uh.brightness(1) uh.clear() uh.set_all(0,0,0) uh.show() time.sleep(1) uh.set_all(0,0,255) uh.show() time.sleep(1) uh.clear()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 640, 198, 11748, 44986, 5183, 355, 21480, 198, 11748, 7007, 198, 11748, 6737, 198, 11748, 12163, 38400, 198, 11748, 850, 14681, 198, 198, 2, 17267, 262, 5888, 198, 11748,...
1.711416
2,987
""" Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE OFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This script creates the lambda function handler for the lambda function sending emails to users via SES """ import boto3 import logging as log import random import string import cfnresponse from html import escape log.getLogger().setLevel(log.INFO)
[ 37811, 201, 198, 15269, 6186, 13, 785, 11, 3457, 13, 393, 663, 29116, 13, 1439, 6923, 33876, 13, 201, 198, 4303, 36227, 12, 34156, 12, 33234, 7483, 25, 17168, 12, 15, 201, 198, 201, 198, 5990, 3411, 318, 29376, 7520, 11, 1479, 286, ...
3.464088
362
n1 = int(input('digite um numero: ')) r = n1 % 2 if r == 1: print('O numero {} é IMPAR!'.format(n1)) else: print('O numero {} é PAR'.format(n1))
[ 77, 16, 796, 493, 7, 15414, 10786, 12894, 578, 23781, 997, 3529, 25, 705, 4008, 198, 81, 796, 299, 16, 4064, 362, 198, 361, 374, 6624, 352, 25, 198, 220, 220, 220, 3601, 10786, 46, 997, 3529, 23884, 38251, 30023, 1503, 0, 4458, 18...
2.202899
69
"""A sample test.""" class TestSample: """A sample unit test class.""" def test_setup(self) -> None: """Test setup.""" return None def test_one(self) -> None: """Assert something.""" assert True
[ 37811, 32, 6291, 1332, 526, 15931, 628, 198, 4871, 6208, 36674, 25, 198, 220, 220, 220, 37227, 32, 6291, 4326, 1332, 1398, 526, 15931, 628, 220, 220, 220, 825, 1332, 62, 40406, 7, 944, 8, 4613, 6045, 25, 198, 220, 220, 220, 220, 2...
2.43
100
import os import platform import time
[ 11748, 28686, 198, 11748, 3859, 198, 11748, 640, 628 ]
4.333333
9
""" A few utility bobs and bits. """ import re from pathlib import Path, PurePath from typing import Optional, Tuple, Union import bs4 import requests from .progress import ProgressSettings, progress_for, size_from_headers PathLike = Union[PurePath, str, Tuple[str, ...]] def to_path(pathlike: PathLike) -> Path: """ Convert a given PathLike into a Path. """ if isinstance(pathlike, tuple): return Path(*pathlike) return Path(pathlike) Regex = Union[str, re.Pattern] def to_pattern(regex: Regex) -> re.Pattern: """ Convert a regex to a re.Pattern. """ if isinstance(regex, re.Pattern): return regex return re.compile(regex) def soupify(response: requests.Response) -> bs4.BeautifulSoup: """ Wrap a requests response in a bs4 object. """ return bs4.BeautifulSoup(response.text, "html.parser") def stream_to_path( response: requests.Response, target: Path, progress_name: Optional[str] = None, chunk_size: int = 1024 ** 2 ) -> None: """ Download a requests response content to a file by streaming it. This function avoids excessive memory usage when downloading large files. The chunk_size is in bytes. If progress_name is None, no progress bar will be shown. Otherwise a progress bar will appear, if the download is bigger than an internal threshold. """ with response: length = size_from_headers(response) if progress_name and length and int(length) > 1024 * 1024 * 10: # 10 MiB settings: Optional[ProgressSettings] = ProgressSettings(progress_name, length) else: settings = None with open(target, 'wb') as file_descriptor: with progress_for(settings) as progress: for chunk in response.iter_content(chunk_size=chunk_size): file_descriptor.write(chunk) progress.advance(len(chunk)) def prompt_yes_no(question: str, default: Optional[bool] = None) -> bool: """ Prompts the user a yes/no question and returns their choice. """ if default is True: prompt = "[Y/n]" elif default is False: prompt = "[y/N]" else: prompt = "[y/n]" text = f"{question} {prompt} " wrong_reply = "Please reply with 'yes'/'y' or 'no'/'n'." while True: response = input(text).strip().lower() if response in {"yes", "ye", "y"}: return True if response in {"no", "n"}: return False if response == "" and default is not None: return default print(wrong_reply)
[ 37811, 198, 32, 1178, 10361, 275, 8158, 290, 10340, 13, 198, 37811, 198, 198, 11748, 302, 198, 6738, 3108, 8019, 1330, 10644, 11, 17129, 15235, 198, 6738, 19720, 1330, 32233, 11, 309, 29291, 11, 4479, 198, 198, 11748, 275, 82, 19, 198...
2.544669
1,041
from .tickers import get_tickers
[ 6738, 764, 83, 21630, 1330, 651, 62, 83, 21630, 198 ]
3.3
10
msg = "hello" target = "world" print("{0} {1} !".format(msg, target))
[ 19662, 796, 366, 31373, 1, 198, 16793, 796, 366, 6894, 1, 198, 4798, 7203, 90, 15, 92, 1391, 16, 92, 5145, 1911, 18982, 7, 19662, 11, 2496, 4008 ]
2.464286
28
from __future__ import absolute_import, division, print_function import six import sys import mmtbx.model import iotbx.pdb import boost_adaptbx.boost.python as bp from libtbx.utils import null_out from libtbx import group_args from cctbx.array_family import flex from collections import OrderedDict # from cctbx.maptbx.box import shift_and_box_model ext = bp.import_ext("cctbx_geometry_restraints_ext") # ============================================================================== # ============================================================================== class place_hydrogens(): ''' Add H atoms to a model Parameters ---------- use_neutron_distances : bool use neutron distances instead of X-ray adp_scale : float scale factor for isotropic B of H atoms. B(H-atom) = adp_scale * B(parent non-H atom) keep_existing_H : bool keep existing H atoms in model, only place missing H ''' # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ def run(self): ''' Function that places H atoms ''' model_has_bogus_cs = False # TODO temporary fix until the code is moved to model class # check if box cussion of 5 A is enough to prevent symm contacts cs = self.model.crystal_symmetry() if cs is None: self.model = shift_and_box_model(model = self.model) model_has_bogus_cs = True # Remove existing H if requested self.n_H_initial = self.model.get_hd_selection().count(True) if not self.keep_existing_H: self.model = self.model.select(~self.model.get_hd_selection()) # Add H atoms and place them at center of coordinates pdb_hierarchy = self.add_missing_H_atoms_at_bogus_position() pdb_hierarchy.atoms().reset_serial() #pdb_hierarchy.sort_atoms_in_place() p = mmtbx.model.manager.get_default_pdb_interpretation_params() p.pdb_interpretation.clash_guard.nonbonded_distance_threshold=None p.pdb_interpretation.use_neutron_distances = self.use_neutron_distances p.pdb_interpretation.proceed_with_excessive_length_bonds=True #p.pdb_interpretation.restraints_library.cdl=False # XXX this triggers a bug !=360 ro = self.model.get_restraint_objects() self.model = mmtbx.model.manager( model_input = None, pdb_hierarchy = pdb_hierarchy, build_grm = True, stop_for_unknowns = self.stop_for_unknowns, crystal_symmetry = self.model.crystal_symmetry(), restraint_objects = ro, pdb_interpretation_params = p, log = null_out()) #f = open("intermediate1.pdb","w") #f.write(self.model.model_as_pdb()) # Only keep H that have been parameterized in riding H procedure sel_h = self.model.get_hd_selection() if sel_h.count(True) == 0: return # get rid of isolated H atoms. #For example when heavy atom is missing, H needs not to be placed sel_isolated = self.model.isolated_atoms_selection() self.sel_lone_H = sel_h & sel_isolated self.model = self.model.select(~self.sel_lone_H) # get riding H manager --> parameterize all H atoms sel_h = self.model.get_hd_selection() self.model.setup_riding_h_manager(use_ideal_dihedral = True) sel_h_in_para = flex.bool( [bool(x) for x in self.model.riding_h_manager.h_parameterization]) sel_h_not_in_para = sel_h_in_para.exclusive_or(sel_h) self.site_labels_no_para = [atom.id_str().replace('pdb=','').replace('"','') for atom in self.model.get_hierarchy().atoms().select(sel_h_not_in_para)] # self.model = self.model.select(~sel_h_not_in_para) self.exclude_H_on_disulfides() #self.exclude_h_on_coordinated_S() # f = open("intermediate2.pdb","w") # f.write(model.model_as_pdb()) # Reset occupancies, ADPs and idealize H atom positions self.model.reset_adp_for_hydrogens(scale = self.adp_scale) self.model.reset_occupancy_for_hydrogens_simple() self.model.idealize_h_riding() self.exclude_h_on_coordinated_S() # self.n_H_final = self.model.get_hd_selection().count(True) # ------------------------------------------------------------------------------ def add_missing_H_atoms_at_bogus_position(self): ''' ! this changes hierarchy in place ! Add missing H atoms to a pdb_hierarchy object all H atoms will be at center of coordinates (all of them superposed) Parameters ---------- pdb_hierarchy : cctbx hierarchy object pdb_hierarchy to which missing H atoms will be added ''' pdb_hierarchy = self.model.get_hierarchy() mon_lib_srv = self.model.get_mon_lib_srv() #XXX This breaks for 1jxt, residue 2, TYR get_class = iotbx.pdb.common_residue_names_get_class no_H_placed_resnames = list() for m in pdb_hierarchy.models(): for chain in m.chains(): for rg in chain.residue_groups(): n_atom_groups = len(rg.atom_groups()) for ag in rg.atom_groups(): if n_atom_groups == 3 and ag.altloc == '': continue #print list(ag.atoms().extract_name()) if(get_class(name=ag.resname) == "common_water"): continue actual = [a.name.strip().upper() for a in ag.atoms()] # mlq = mon_lib_query(residue=ag, mon_lib_srv=mon_lib_srv) #if (get_class(name=ag.resname) in ['modified_rna_dna', 'other']): if mlq is None: self.no_H_placed_mlq.append(ag.resname) continue expected_h = list() for k, v in six.iteritems(mlq.atom_dict()): if(v.type_symbol=="H"): expected_h.append(k) missing_h = list(set(expected_h).difference(set(actual))) if 0: print(ag.resname, missing_h) new_xyz = ag.atoms().extract_xyz().mean() hetero = ag.atoms()[0].hetero for mh in missing_h: # TODO: this should be probably in a central place if len(mh) < 4: mh = (' ' + mh).ljust(4) a = (iotbx.pdb.hierarchy.atom() .set_name(new_name=mh) .set_element(new_element="H") .set_xyz(new_xyz=new_xyz) .set_hetero(new_hetero=hetero)) ag.append_atom(a) return pdb_hierarchy # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ def show(self, log): ''' Informative output ''' if log is None: log = sys.stdout # if (not self.keep_existing_H and self.n_H_initial): msg = 'Number of hydrogen atoms trimmed from input model: %s \n' print(msg % self.n_H_initial, file=log) # msg = 'Number of hydrogen atoms added to the input model: %s \n' print(msg % self.n_H_final, file=log) # if self.no_H_placed_mlq: msg = ''' No H atoms were placed on the following residues because no restraints were found:''' print(msg, file=log) for resname in self.no_H_placed_mlq: print(resname, file=log) # if self.site_labels_disulfides: msg = ''' The following cysteine HG atoms were not placed because the sulfur atom is involved in a disulfide bond''' print(msg, file=log) for label in self.site_labels_disulfides: print(label, file=log) # if self.site_labels_no_para: msg = ''' The following H atoms were not placed because they could not be parameterized (not enough restraints information)''' print(msg, file=log) for label in self.site_labels_no_para: print(label) # ------------------------------------------------------------------------------ # ============================================================================== # stub for reduce parameters # TODO can be parameters or phil, depending on how many options are really needed reduce_master_params_str = """ flip_NQH = True .type = bool .help = add H and rotate and flip NQH groups search_time_limit = 600 .type = int .help = max seconds to spend in exhaustive search (default=600) """ def optimize(model): """ Carry out reduce optimization Parameters ---------- model mmtbx model object that contains H atoms H atoms should be at approprite distances Returns ------- model mmtbx model object with optimized H atoms """ # hierarchy object --> has hierarchy of structure pdb_hierarchy = model.get_hierarchy() # geometry restraints manager --> info about ideal bonds, angles; what atoms are bonded, etc. grm = model.get_restraints_manager() print("Reduce optimization happens here") return model
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 198, 11748, 2237, 198, 11748, 25064, 198, 11748, 8085, 83, 65, 87, 13, 19849, 198, 11748, 1312, 313, 65, 87, 13, 79, 9945, 198, 11748, 5750, 62, 42552, 65...
2.557344
3,479
from django.shortcuts import render # Create your views here. from django.shortcuts import render_to_response from django.template import RequestContext from history.models import Teamindex #from history.models import Seasonindex from history.models import Seasondata
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 198, 2, 13610, 534, 5009, 994, 13, 198, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 62, 1462, 62, 26209, 198, 6738, 42625, 14208, 13, 28243, 1330, 19390, 21947, 198, 198,...
4.044776
67
# -*- coding: utf8 -*- # Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from tencentcloud.common.abstract_model import AbstractModel class ActivateSubscribeRequest(AbstractModel): """ActivateSubscribe请求参数结构体 """ def __init__(self): """ :param SubscribeId: 订阅实例ID。 :type SubscribeId: str :param InstanceId: 数据库实例ID :type InstanceId: str :param SubscribeObjectType: 数据订阅类型0-全实例订阅,1数据订阅,2结构订阅,3数据订阅与结构订阅 :type SubscribeObjectType: int :param Objects: 订阅对象 :type Objects: :class:`tencentcloud.dts.v20180330.models.SubscribeObject` :param UniqSubnetId: 数据订阅服务所在子网。默认为数据库实例所在的子网内。 :type UniqSubnetId: str :param Vport: 订阅服务端口;默认为7507 :type Vport: int """ self.SubscribeId = None self.InstanceId = None self.SubscribeObjectType = None self.Objects = None self.UniqSubnetId = None self.Vport = None class ActivateSubscribeResponse(AbstractModel): """ActivateSubscribe返回参数结构体 """ def __init__(self): """ :param AsyncRequestId: 配置数据订阅任务ID。 :type AsyncRequestId: str :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.AsyncRequestId = None self.RequestId = None class CompleteMigrateJobRequest(AbstractModel): """CompleteMigrateJob请求参数结构体 """ def __init__(self): """ :param JobId: 数据迁移任务ID :type JobId: str """ self.JobId = None class CompleteMigrateJobResponse(AbstractModel): """CompleteMigrateJob返回参数结构体 """ def __init__(self): """ :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.RequestId = None class ConsistencyParams(AbstractModel): """抽样检验时的抽样参数 """ def __init__(self): """ :param SelectRowsPerTable: 数据内容检测参数。表中选出用来数据对比的行,占表的总行数的百分比。取值范围是整数[1-100] :type SelectRowsPerTable: int :param TablesSelectAll: 数据内容检测参数。迁移库表中,要进行数据内容检测的表,占所有表的百分比。取值范围是整数[1-100] :type TablesSelectAll: int :param TablesSelectCount: 数据数量检测,检测表行数是否一致。迁移库表中,要进行数据数量检测的表,占所有表的百分比。取值范围是整数[1-100] :type TablesSelectCount: int """ self.SelectRowsPerTable = None self.TablesSelectAll = None self.TablesSelectCount = None class CreateMigrateCheckJobRequest(AbstractModel): """CreateMigrateCheckJob请求参数结构体 """ def __init__(self): """ :param JobId: 数据迁移任务ID :type JobId: str """ self.JobId = None class CreateMigrateCheckJobResponse(AbstractModel): """CreateMigrateCheckJob返回参数结构体 """ def __init__(self): """ :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.RequestId = None class CreateMigrateJobRequest(AbstractModel): """CreateMigrateJob请求参数结构体 """ def __init__(self): """ :param JobName: 数据迁移任务名称 :type JobName: str :param MigrateOption: 迁移任务配置选项 :type MigrateOption: :class:`tencentcloud.dts.v20180330.models.MigrateOption` :param SrcDatabaseType: 源实例数据库类型,目前支持:mysql,redis,mongodb,postgresql,mariadb,percona。不同地域数据库类型的具体支持情况,请参考控制台创建迁移页面。 :type SrcDatabaseType: str :param SrcAccessType: 源实例接入类型,值包括:extranet(外网),cvm(CVM自建实例),dcg(专线接入的实例),vpncloud(云VPN接入的实例),cdb(腾讯云数据库实例),ccn(云联网实例) :type SrcAccessType: str :param SrcInfo: 源实例信息,具体内容跟迁移任务类型相关 :type SrcInfo: :class:`tencentcloud.dts.v20180330.models.SrcInfo` :param DstDatabaseType: 目标实例数据库类型,目前支持:mysql,redis,mongodb,postgresql,mariadb,percona。不同地域数据库类型的具体支持情况,请参考控制台创建迁移页面。 :type DstDatabaseType: str :param DstAccessType: 目标实例接入类型,目前支持:cdb(腾讯云数据库实例) :type DstAccessType: str :param DstInfo: 目标实例信息 :type DstInfo: :class:`tencentcloud.dts.v20180330.models.DstInfo` :param DatabaseInfo: 需要迁移的源数据库表信息,用json格式的字符串描述。当MigrateOption.MigrateObject配置为2(指定库表迁移)时必填。 对于database-table两级结构的数据库: [{Database:db1,Table:[table1,table2]},{Database:db2}] 对于database-schema-table三级结构: [{Database:db1,Schema:s1 Table:[table1,table2]},{Database:db1,Schema:s2 Table:[table1,table2]},{Database:db2,Schema:s1 Table:[table1,table2]},{Database:db3},{Database:db4 Schema:s1}] :type DatabaseInfo: str """ self.JobName = None self.MigrateOption = None self.SrcDatabaseType = None self.SrcAccessType = None self.SrcInfo = None self.DstDatabaseType = None self.DstAccessType = None self.DstInfo = None self.DatabaseInfo = None class CreateMigrateJobResponse(AbstractModel): """CreateMigrateJob返回参数结构体 """ def __init__(self): """ :param JobId: 数据迁移任务ID :type JobId: str :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.JobId = None self.RequestId = None class CreateSubscribeRequest(AbstractModel): """CreateSubscribe请求参数结构体 """ def __init__(self): """ :param Product: 订阅的数据库类型,目前支持的有 mysql :type Product: str :param PayType: 实例付费类型,1小时计费,0包年包月 :type PayType: int :param Duration: 购买时长。PayType为0时必填。单位为月,最大支持120 :type Duration: int :param Count: 购买数量,默认为1,最大为10 :type Count: int :param AutoRenew: 是否自动续费,默认为0,1表示自动续费。小时计费实例设置该标识无效。 :type AutoRenew: int :param Tags: 实例资源标签 :type Tags: list of TagItem """ self.Product = None self.PayType = None self.Duration = None self.Count = None self.AutoRenew = None self.Tags = None class CreateSubscribeResponse(AbstractModel): """CreateSubscribe返回参数结构体 """ def __init__(self): """ :param SubscribeIds: 数据订阅实例的ID数组 注意:此字段可能返回 null,表示取不到有效值。 :type SubscribeIds: list of str :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.SubscribeIds = None self.RequestId = None class CreateSyncCheckJobRequest(AbstractModel): """CreateSyncCheckJob请求参数结构体 """ def __init__(self): """ :param JobId: 灾备同步任务ID :type JobId: str """ self.JobId = None class CreateSyncCheckJobResponse(AbstractModel): """CreateSyncCheckJob返回参数结构体 """ def __init__(self): """ :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.RequestId = None class CreateSyncJobRequest(AbstractModel): """CreateSyncJob请求参数结构体 """ def __init__(self): """ :param JobName: 灾备同步任务名 :type JobName: str :param SyncOption: 灾备同步任务配置选项 :type SyncOption: :class:`tencentcloud.dts.v20180330.models.SyncOption` :param SrcDatabaseType: 源实例数据库类型,目前仅包括:mysql :type SrcDatabaseType: str :param SrcAccessType: 源实例接入类型,目前仅包括:cdb(云上cdb实例) :type SrcAccessType: str :param SrcInfo: 源实例信息 :type SrcInfo: :class:`tencentcloud.dts.v20180330.models.SyncInstanceInfo` :param DstDatabaseType: 目标实例数据库类型,目前仅包括:mysql :type DstDatabaseType: str :param DstAccessType: 目标实例接入类型,目前仅包括:cdb(云上cdb实例) :type DstAccessType: str :param DstInfo: 目标实例信息 :type DstInfo: :class:`tencentcloud.dts.v20180330.models.SyncInstanceInfo` :param DatabaseInfo: 需要同步的源数据库表信息,用json格式的字符串描述。 对于database-table两级结构的数据库: [{Database:db1,Table:[table1,table2]},{Database:db2}] :type DatabaseInfo: str """ self.JobName = None self.SyncOption = None self.SrcDatabaseType = None self.SrcAccessType = None self.SrcInfo = None self.DstDatabaseType = None self.DstAccessType = None self.DstInfo = None self.DatabaseInfo = None class CreateSyncJobResponse(AbstractModel): """CreateSyncJob返回参数结构体 """ def __init__(self): """ :param JobId: 灾备同步任务ID :type JobId: str :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.JobId = None self.RequestId = None class DeleteMigrateJobRequest(AbstractModel): """DeleteMigrateJob请求参数结构体 """ def __init__(self): """ :param JobId: 数据迁移任务ID :type JobId: str """ self.JobId = None class DeleteMigrateJobResponse(AbstractModel): """DeleteMigrateJob返回参数结构体 """ def __init__(self): """ :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.RequestId = None class DeleteSyncJobRequest(AbstractModel): """DeleteSyncJob请求参数结构体 """ def __init__(self): """ :param JobId: 待删除的灾备同步任务ID :type JobId: str """ self.JobId = None class DeleteSyncJobResponse(AbstractModel): """DeleteSyncJob返回参数结构体 """ def __init__(self): """ :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.RequestId = None class DescribeAsyncRequestInfoRequest(AbstractModel): """DescribeAsyncRequestInfo请求参数结构体 """ def __init__(self): """ :param AsyncRequestId: 任务 ID :type AsyncRequestId: str """ self.AsyncRequestId = None class DescribeAsyncRequestInfoResponse(AbstractModel): """DescribeAsyncRequestInfo返回参数结构体 """ def __init__(self): """ :param Info: 任务执行结果信息 :type Info: str :param Status: 任务执行状态,可能的值有:success,failed,running :type Status: str :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.Info = None self.Status = None self.RequestId = None class DescribeMigrateCheckJobRequest(AbstractModel): """DescribeMigrateCheckJob请求参数结构体 """ def __init__(self): """ :param JobId: 数据迁移任务ID :type JobId: str """ self.JobId = None class DescribeMigrateCheckJobResponse(AbstractModel): """DescribeMigrateCheckJob返回参数结构体 """ def __init__(self): """ :param Status: 校验任务状态:unavailable(当前不可用), starting(开始中),running(校验中),finished(校验完成) :type Status: str :param ErrorCode: 任务的错误码 :type ErrorCode: int :param ErrorMessage: 任务的错误信息 :type ErrorMessage: str :param Progress: Check任务总进度,如:"30"表示30% :type Progress: str :param CheckFlag: 校验是否通过,0-未通过,1-校验通过, 3-未校验 :type CheckFlag: int :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.Status = None self.ErrorCode = None self.ErrorMessage = None self.Progress = None self.CheckFlag = None self.RequestId = None class DescribeMigrateJobsRequest(AbstractModel): """DescribeMigrateJobs请求参数结构体 """ def __init__(self): """ :param JobId: 数据迁移任务ID :type JobId: str :param JobName: 数据迁移任务名称 :type JobName: str :param Order: 排序字段,可以取值为JobId、Status、JobName、MigrateType、RunMode、CreateTime :type Order: str :param OrderSeq: 排序方式,升序为ASC,降序为DESC :type OrderSeq: str :param Offset: 偏移量,默认为0 :type Offset: int :param Limit: 返回实例数量,默认20,有效区间[1,100] :type Limit: int """ self.JobId = None self.JobName = None self.Order = None self.OrderSeq = None self.Offset = None self.Limit = None class DescribeMigrateJobsResponse(AbstractModel): """DescribeMigrateJobs返回参数结构体 """ def __init__(self): """ :param TotalCount: 任务数目 :type TotalCount: int :param JobList: 任务详情数组 :type JobList: list of MigrateJobInfo :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.TotalCount = None self.JobList = None self.RequestId = None class DescribeRegionConfRequest(AbstractModel): """DescribeRegionConf请求参数结构体 """ class DescribeRegionConfResponse(AbstractModel): """DescribeRegionConf返回参数结构体 """ def __init__(self): """ :param TotalCount: 可售卖地域的数量 :type TotalCount: int :param Items: 可售卖地域详情 :type Items: list of SubscribeRegionConf :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.TotalCount = None self.Items = None self.RequestId = None class DescribeSubscribeConfRequest(AbstractModel): """DescribeSubscribeConf请求参数结构体 """ def __init__(self): """ :param SubscribeId: 订阅实例ID :type SubscribeId: str """ self.SubscribeId = None class DescribeSubscribeConfResponse(AbstractModel): """DescribeSubscribeConf返回参数结构体 """ def __init__(self): """ :param SubscribeId: 订阅实例ID :type SubscribeId: str :param SubscribeName: 订阅实例名称 :type SubscribeName: str :param ChannelId: 订阅通道 :type ChannelId: str :param Product: 订阅数据库类型 :type Product: str :param InstanceId: 被订阅的实例 :type InstanceId: str :param InstanceStatus: 被订阅的实例的状态,可能的值有running,offline,isolate :type InstanceStatus: str :param SubsStatus: 订阅实例状态,可能的值有unconfigure-未配置,configuring-配置中,configured-已配置 :type SubsStatus: str :param Status: 订阅实例生命周期状态,可能的值有:normal-正常,isolating-隔离中,isolated-已隔离,offlining-下线中 :type Status: str :param CreateTime: 订阅实例创建时间 :type CreateTime: str :param IsolateTime: 订阅实例被隔离时间 :type IsolateTime: str :param ExpireTime: 订阅实例到期时间 :type ExpireTime: str :param OfflineTime: 订阅实例下线时间 :type OfflineTime: str :param ConsumeStartTime: 订阅实例消费时间起点。 :type ConsumeStartTime: str :param PayType: 订阅实例计费类型,1-小时计费,0-包年包月 :type PayType: int :param Vip: 订阅通道Vip :type Vip: str :param Vport: 订阅通道Port :type Vport: int :param UniqVpcId: 订阅通道所在VpcId :type UniqVpcId: str :param UniqSubnetId: 订阅通道所在SubnetId :type UniqSubnetId: str :param SdkConsumedTime: 当前SDK消费时间位点 :type SdkConsumedTime: str :param SdkHost: 订阅SDK IP地址 :type SdkHost: str :param SubscribeObjectType: 订阅对象类型0-全实例订阅,1-DDL数据订阅,2-DML结构订阅,3-DDL数据订阅+DML结构订阅 :type SubscribeObjectType: int :param SubscribeObjects: 订阅对象,当SubscribeObjectType 为0时,此字段为空数组 :type SubscribeObjects: list of SubscribeObject :param ModifyTime: 修改时间 :type ModifyTime: str :param Region: 地域 :type Region: str :param Tags: 订阅实例的标签 注意:此字段可能返回 null,表示取不到有效值。 :type Tags: list of TagItem :param AutoRenewFlag: 自动续费标识,0-不自动续费,1-自动续费 注意:此字段可能返回 null,表示取不到有效值。 :type AutoRenewFlag: int :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.SubscribeId = None self.SubscribeName = None self.ChannelId = None self.Product = None self.InstanceId = None self.InstanceStatus = None self.SubsStatus = None self.Status = None self.CreateTime = None self.IsolateTime = None self.ExpireTime = None self.OfflineTime = None self.ConsumeStartTime = None self.PayType = None self.Vip = None self.Vport = None self.UniqVpcId = None self.UniqSubnetId = None self.SdkConsumedTime = None self.SdkHost = None self.SubscribeObjectType = None self.SubscribeObjects = None self.ModifyTime = None self.Region = None self.Tags = None self.AutoRenewFlag = None self.RequestId = None class DescribeSubscribesRequest(AbstractModel): """DescribeSubscribes请求参数结构体 """ def __init__(self): """ :param SubscribeId: 数据订阅的实例ID :type SubscribeId: str :param SubscribeName: 数据订阅的实例名称 :type SubscribeName: str :param InstanceId: 绑定数据库实例的ID :type InstanceId: str :param ChannelId: 数据订阅实例的通道ID :type ChannelId: str :param PayType: 计费模式筛选,可能的值:0-包年包月,1-按量计费 :type PayType: str :param Product: 订阅的数据库产品,如mysql :type Product: str :param Status: 数据订阅实例的状态,creating - 创建中,normal - 正常运行,isolating - 隔离中,isolated - 已隔离,offlining - 下线中 :type Status: list of str :param SubsStatus: 数据订阅实例的配置状态,unconfigure - 未配置, configuring - 配置中,configured - 已配置 :type SubsStatus: list of str :param Offset: 返回记录的起始偏移量 :type Offset: int :param Limit: 单次返回的记录数量 :type Limit: int :param OrderDirection: 排序方向,可选的值为"DESC"和"ASC",默认为"DESC",按创建时间逆序排序 :type OrderDirection: str :param TagFilters: 标签过滤条件 :type TagFilters: list of TagFilter :param SubscribeVersion: 订阅实例版本;txdts-旧版数据订阅,kafka-kafka版本数据订阅 :type SubscribeVersion: str """ self.SubscribeId = None self.SubscribeName = None self.InstanceId = None self.ChannelId = None self.PayType = None self.Product = None self.Status = None self.SubsStatus = None self.Offset = None self.Limit = None self.OrderDirection = None self.TagFilters = None self.SubscribeVersion = None class DescribeSubscribesResponse(AbstractModel): """DescribeSubscribes返回参数结构体 """ def __init__(self): """ :param TotalCount: 符合查询条件的实例总数 :type TotalCount: int :param Items: 数据订阅实例的信息列表 :type Items: list of SubscribeInfo :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.TotalCount = None self.Items = None self.RequestId = None class DescribeSyncCheckJobRequest(AbstractModel): """DescribeSyncCheckJob请求参数结构体 """ def __init__(self): """ :param JobId: 要查询的灾备同步任务ID :type JobId: str """ self.JobId = None class DescribeSyncCheckJobResponse(AbstractModel): """DescribeSyncCheckJob返回参数结构体 """ def __init__(self): """ :param Status: 任务校验状态: starting(开始中),running(校验中),finished(校验完成) :type Status: str :param ErrorCode: 任务校验结果代码 :type ErrorCode: int :param ErrorMessage: 提示信息 :type ErrorMessage: str :param StepInfo: 任务执行步骤描述 :type StepInfo: list of SyncCheckStepInfo :param CheckFlag: 校验标志:0(尚未校验成功) , 1(校验成功) :type CheckFlag: int :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.Status = None self.ErrorCode = None self.ErrorMessage = None self.StepInfo = None self.CheckFlag = None self.RequestId = None class DescribeSyncJobsRequest(AbstractModel): """DescribeSyncJobs请求参数结构体 """ def __init__(self): """ :param JobId: 灾备同步任务ID :type JobId: str :param JobName: 灾备同步任务名 :type JobName: str :param Order: 排序字段,可以取值为JobId、Status、JobName、CreateTime :type Order: str :param OrderSeq: 排序方式,升序为ASC,降序为DESC :type OrderSeq: str :param Offset: 偏移量,默认为0 :type Offset: int :param Limit: 返回实例数量,默认20,有效区间[1,100] :type Limit: int """ self.JobId = None self.JobName = None self.Order = None self.OrderSeq = None self.Offset = None self.Limit = None class DescribeSyncJobsResponse(AbstractModel): """DescribeSyncJobs返回参数结构体 """ def __init__(self): """ :param TotalCount: 任务数目 :type TotalCount: int :param JobList: 任务详情数组 :type JobList: list of SyncJobInfo :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.TotalCount = None self.JobList = None self.RequestId = None class DstInfo(AbstractModel): """目的实例信息,具体内容跟迁移任务类型相关 """ def __init__(self): """ :param InstanceId: 目标实例ID,如cdb-jd92ijd8 :type InstanceId: str :param Region: 目标实例地域,如ap-guangzhou :type Region: str :param Ip: 目标实例vip。已废弃,无需填写 :type Ip: str :param Port: 目标实例vport。已废弃,无需填写 :type Port: int :param ReadOnly: 目前只对MySQL有效。当为整实例迁移时,1-只读,0-可读写。 :type ReadOnly: int :param User: 目标数据库账号 :type User: str :param Password: 目标数据库密码 :type Password: str """ self.InstanceId = None self.Region = None self.Ip = None self.Port = None self.ReadOnly = None self.User = None self.Password = None class ErrorInfo(AbstractModel): """迁移任务错误信息及提示 """ def __init__(self): """ :param ErrorLog: 具体的报错日志, 包含错误码和错误信息 :type ErrorLog: str :param HelpDoc: 报错对应的帮助文档Ur :type HelpDoc: str """ self.ErrorLog = None self.HelpDoc = None class IsolateSubscribeRequest(AbstractModel): """IsolateSubscribe请求参数结构体 """ def __init__(self): """ :param SubscribeId: 订阅实例ID :type SubscribeId: str """ self.SubscribeId = None class IsolateSubscribeResponse(AbstractModel): """IsolateSubscribe返回参数结构体 """ def __init__(self): """ :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.RequestId = None class MigrateDetailInfo(AbstractModel): """描述详细迁移过程 """ def __init__(self): """ :param StepAll: 总步骤数 :type StepAll: int :param StepNow: 当前步骤 :type StepNow: int :param Progress: 总进度,如:"10" :type Progress: str :param CurrentStepProgress: 当前步骤进度,如:"1" :type CurrentStepProgress: str :param MasterSlaveDistance: 主从差距,MB;在增量同步阶段有效,目前支持产品为:redis和mysql :type MasterSlaveDistance: int :param SecondsBehindMaster: 主从差距,秒;在增量同步阶段有效,目前支持产品为:mysql :type SecondsBehindMaster: int :param StepInfo: 步骤信息 :type StepInfo: list of MigrateStepDetailInfo """ self.StepAll = None self.StepNow = None self.Progress = None self.CurrentStepProgress = None self.MasterSlaveDistance = None self.SecondsBehindMaster = None self.StepInfo = None class MigrateJobInfo(AbstractModel): """迁移任务详情 """ def __init__(self): """ :param JobId: 数据迁移任务ID :type JobId: str :param JobName: 数据迁移任务名称 :type JobName: str :param MigrateOption: 迁移任务配置选项 :type MigrateOption: :class:`tencentcloud.dts.v20180330.models.MigrateOption` :param SrcDatabaseType: 源实例数据库类型:mysql,redis,mongodb,postgresql,mariadb,percona :type SrcDatabaseType: str :param SrcAccessType: 源实例接入类型,值包括:extranet(外网),cvm(cvm自建实例),dcg(专线接入的实例),vpncloud(云vpn接入的实例),cdb(腾讯云数据库实例),ccn(云联网实例) :type SrcAccessType: str :param SrcInfo: 源实例信息,具体内容跟迁移任务类型相关 :type SrcInfo: :class:`tencentcloud.dts.v20180330.models.SrcInfo` :param DstDatabaseType: 目标实例数据库类型:mysql,redis,mongodb,postgresql,mariadb,percona :type DstDatabaseType: str :param DstAccessType: 目标实例接入类型,目前支持:cdb(腾讯云数据库实例) :type DstAccessType: str :param DstInfo: 目标实例信息 :type DstInfo: :class:`tencentcloud.dts.v20180330.models.DstInfo` :param DatabaseInfo: 需要迁移的源数据库表信息,如果需要迁移的是整个实例,该字段为[] :type DatabaseInfo: str :param CreateTime: 任务创建(提交)时间 :type CreateTime: str :param StartTime: 任务开始执行时间 :type StartTime: str :param EndTime: 任务执行结束时间 :type EndTime: str :param Status: 任务状态,取值为:1-创建中(Creating),3-校验中(Checking)4-校验通过(CheckPass),5-校验不通过(CheckNotPass),7-任务运行(Running),8-准备完成(ReadyComplete),9-任务成功(Success),10-任务失败(Failed),11-撤销中(Stopping),12-完成中(Completing) :type Status: int :param Detail: 任务详情 :type Detail: :class:`tencentcloud.dts.v20180330.models.MigrateDetailInfo` :param ErrorInfo: 任务错误信息提示,当任务发生错误时,不为null或者空值 :type ErrorInfo: list of ErrorInfo """ self.JobId = None self.JobName = None self.MigrateOption = None self.SrcDatabaseType = None self.SrcAccessType = None self.SrcInfo = None self.DstDatabaseType = None self.DstAccessType = None self.DstInfo = None self.DatabaseInfo = None self.CreateTime = None self.StartTime = None self.EndTime = None self.Status = None self.Detail = None self.ErrorInfo = None class MigrateOption(AbstractModel): """迁移任务配置选项 """ def __init__(self): """ :param RunMode: 任务运行模式,值包括:1-立即执行,2-定时执行 :type RunMode: int :param ExpectTime: 期望执行时间,当runMode=2时,该字段必填,时间格式:yyyy-mm-dd hh:mm:ss :type ExpectTime: str :param MigrateType: 数据迁移类型,值包括:1-结构迁移,2-全量迁移,3-全量+增量迁移 :type MigrateType: int :param MigrateObject: 迁移对象,1-整个实例,2-指定库表 :type MigrateObject: int :param ConsistencyType: 抽样数据一致性检测参数,1-未配置,2-全量检测,3-抽样检测, 4-仅校验不一致表,5-不检测 :type ConsistencyType: int :param IsOverrideRoot: 是否用源库Root账户覆盖目标库,值包括:0-不覆盖,1-覆盖,选择库表或者结构迁移时应该为0 :type IsOverrideRoot: int :param ExternParams: 不同数据库用到的额外参数.以JSON格式描述. Redis可定义如下的参数: { "ClientOutputBufferHardLimit":512, 从机缓冲区的硬性容量限制(MB) "ClientOutputBufferSoftLimit":512, 从机缓冲区的软性容量限制(MB) "ClientOutputBufferPersistTime":60, 从机缓冲区的软性限制持续时间(秒) "ReplBacklogSize":512, 环形缓冲区容量限制(MB) "ReplTimeout":120, 复制超时时间(秒) } MongoDB可定义如下的参数: { 'SrcAuthDatabase':'admin', 'SrcAuthFlag': "1", 'SrcAuthMechanism':"SCRAM-SHA-1" } MySQL暂不支持额外参数设置。 :type ExternParams: str :param ConsistencyParams: 仅用于“抽样数据一致性检测”,ConsistencyType配置为抽样检测时,必选 :type ConsistencyParams: :class:`tencentcloud.dts.v20180330.models.ConsistencyParams` """ self.RunMode = None self.ExpectTime = None self.MigrateType = None self.MigrateObject = None self.ConsistencyType = None self.IsOverrideRoot = None self.ExternParams = None self.ConsistencyParams = None class MigrateStepDetailInfo(AbstractModel): """迁移中的步骤信息 """ def __init__(self): """ :param StepNo: 步骤序列 :type StepNo: int :param StepName: 步骤展现名称 :type StepName: str :param StepId: 步骤英文标识 :type StepId: str :param Status: 步骤状态:0-默认值,1-成功,2-失败,3-执行中,4-未执行 :type Status: int :param StartTime: 当前步骤开始的时间,格式为"yyyy-mm-dd hh:mm:ss",该字段不存在或者为空是无意义 注意:此字段可能返回 null,表示取不到有效值。 :type StartTime: str """ self.StepNo = None self.StepName = None self.StepId = None self.Status = None self.StartTime = None class ModifyMigrateJobRequest(AbstractModel): """ModifyMigrateJob请求参数结构体 """ def __init__(self): """ :param JobId: 待修改的数据迁移任务ID :type JobId: str :param JobName: 数据迁移任务名称 :type JobName: str :param MigrateOption: 迁移任务配置选项 :type MigrateOption: :class:`tencentcloud.dts.v20180330.models.MigrateOption` :param SrcAccessType: 源实例接入类型,值包括:extranet(外网),cvm(CVM自建实例),dcg(专线接入的实例),vpncloud(云VPN接入的实例),cdb(云上CDB实例) :type SrcAccessType: str :param SrcInfo: 源实例信息,具体内容跟迁移任务类型相关 :type SrcInfo: :class:`tencentcloud.dts.v20180330.models.SrcInfo` :param DstAccessType: 目标实例接入类型,值包括:extranet(外网),cvm(CVM自建实例),dcg(专线接入的实例),vpncloud(云VPN接入的实例),cdb(云上CDB实例). 目前只支持cdb. :type DstAccessType: str :param DstInfo: 目标实例信息, 其中目标实例地域不允许修改. :type DstInfo: :class:`tencentcloud.dts.v20180330.models.DstInfo` :param DatabaseInfo: 当选择'指定库表'迁移的时候, 需要设置待迁移的源数据库表信息,用符合json数组格式的字符串描述, 如下所例。 对于database-table两级结构的数据库: [{"Database":"db1","Table":["table1","table2"]},{"Database":"db2"}] 对于database-schema-table三级结构: [{"Database":"db1","Schema":"s1","Table":["table1","table2"]},{"Database":"db1","Schema":"s2","Table":["table1","table2"]},{"Database":"db2","Schema":"s1","Table":["table1","table2"]},{"Database":"db3"},{"Database":"db4","Schema":"s1"}] 如果是'整个实例'的迁移模式,不需设置该字段 :type DatabaseInfo: str """ self.JobId = None self.JobName = None self.MigrateOption = None self.SrcAccessType = None self.SrcInfo = None self.DstAccessType = None self.DstInfo = None self.DatabaseInfo = None class ModifyMigrateJobResponse(AbstractModel): """ModifyMigrateJob返回参数结构体 """ def __init__(self): """ :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.RequestId = None class ModifySubscribeAutoRenewFlagRequest(AbstractModel): """ModifySubscribeAutoRenewFlag请求参数结构体 """ def __init__(self): """ :param SubscribeId: 订阅实例ID,例如:subs-8uey736k :type SubscribeId: str :param AutoRenewFlag: 自动续费标识。1-自动续费,0-不自动续费 :type AutoRenewFlag: int """ self.SubscribeId = None self.AutoRenewFlag = None class ModifySubscribeAutoRenewFlagResponse(AbstractModel): """ModifySubscribeAutoRenewFlag返回参数结构体 """ def __init__(self): """ :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.RequestId = None class ModifySubscribeConsumeTimeRequest(AbstractModel): """ModifySubscribeConsumeTime请求参数结构体 """ def __init__(self): """ :param SubscribeId: 数据订阅实例的ID :type SubscribeId: str :param ConsumeStartTime: 消费时间起点,也即是指定订阅数据的时间起点,时间格式如:Y-m-d h:m:s,取值范围为过去24小时之内 :type ConsumeStartTime: str """ self.SubscribeId = None self.ConsumeStartTime = None class ModifySubscribeConsumeTimeResponse(AbstractModel): """ModifySubscribeConsumeTime返回参数结构体 """ def __init__(self): """ :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.RequestId = None class ModifySubscribeNameRequest(AbstractModel): """ModifySubscribeName请求参数结构体 """ def __init__(self): """ :param SubscribeId: 数据订阅实例的ID :type SubscribeId: str :param SubscribeName: 数据订阅实例的名称,长度限制为[1,60] :type SubscribeName: str """ self.SubscribeId = None self.SubscribeName = None class ModifySubscribeNameResponse(AbstractModel): """ModifySubscribeName返回参数结构体 """ def __init__(self): """ :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.RequestId = None class ModifySubscribeObjectsRequest(AbstractModel): """ModifySubscribeObjects请求参数结构体 """ def __init__(self): """ :param SubscribeId: 数据订阅实例的ID :type SubscribeId: str :param SubscribeObjectType: 数据订阅的类型,可选的值有:0 - 全实例订阅;1 - 数据订阅;2 - 结构订阅;3 - 数据订阅+结构订阅 :type SubscribeObjectType: int :param Objects: 订阅的数据库表信息 :type Objects: list of SubscribeObject """ self.SubscribeId = None self.SubscribeObjectType = None self.Objects = None class ModifySubscribeObjectsResponse(AbstractModel): """ModifySubscribeObjects返回参数结构体 """ def __init__(self): """ :param AsyncRequestId: 异步任务的ID :type AsyncRequestId: str :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.AsyncRequestId = None self.RequestId = None class ModifySubscribeVipVportRequest(AbstractModel): """ModifySubscribeVipVport请求参数结构体 """ def __init__(self): """ :param SubscribeId: 数据订阅实例的ID :type SubscribeId: str :param DstUniqSubnetId: 指定目的子网,如果传此参数,DstIp必须在目的子网内 :type DstUniqSubnetId: str :param DstIp: 目标IP,与DstPort至少传一个 :type DstIp: str :param DstPort: 目标PORT,支持范围为:[1025-65535] :type DstPort: int """ self.SubscribeId = None self.DstUniqSubnetId = None self.DstIp = None self.DstPort = None class ModifySubscribeVipVportResponse(AbstractModel): """ModifySubscribeVipVport返回参数结构体 """ def __init__(self): """ :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.RequestId = None class ModifySyncJobRequest(AbstractModel): """ModifySyncJob请求参数结构体 """ def __init__(self): """ :param JobId: 待修改的灾备同步任务ID :type JobId: str :param JobName: 灾备同步任务名称 :type JobName: str :param SyncOption: 灾备同步任务配置选项 :type SyncOption: :class:`tencentcloud.dts.v20180330.models.SyncOption` :param DatabaseInfo: 当选择'指定库表'灾备同步的时候, 需要设置待同步的源数据库表信息,用符合json数组格式的字符串描述, 如下所例。 对于database-table两级结构的数据库: [{"Database":"db1","Table":["table1","table2"]},{"Database":"db2"}] :type DatabaseInfo: str """ self.JobId = None self.JobName = None self.SyncOption = None self.DatabaseInfo = None class ModifySyncJobResponse(AbstractModel): """ModifySyncJob返回参数结构体 """ def __init__(self): """ :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.RequestId = None class OfflineIsolatedSubscribeRequest(AbstractModel): """OfflineIsolatedSubscribe请求参数结构体 """ def __init__(self): """ :param SubscribeId: 数据订阅实例的ID :type SubscribeId: str """ self.SubscribeId = None class OfflineIsolatedSubscribeResponse(AbstractModel): """OfflineIsolatedSubscribe返回参数结构体 """ def __init__(self): """ :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.RequestId = None class ResetSubscribeRequest(AbstractModel): """ResetSubscribe请求参数结构体 """ def __init__(self): """ :param SubscribeId: 数据订阅实例的ID :type SubscribeId: str """ self.SubscribeId = None class ResetSubscribeResponse(AbstractModel): """ResetSubscribe返回参数结构体 """ def __init__(self): """ :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.RequestId = None class SrcInfo(AbstractModel): """源实例信息 """ def __init__(self): """ :param AccessKey: 阿里云AccessKey。源库是阿里云RDS5.6适用 :type AccessKey: str :param Ip: 实例的IP地址 :type Ip: str :param Port: 实例的端口 :type Port: int :param User: 实例的用户名 :type User: str :param Password: 实例的密码 :type Password: str :param RdsInstanceId: 阿里云RDS实例ID。源库是阿里云RDS5.6/5.6适用 :type RdsInstanceId: str :param CvmInstanceId: CVM实例短ID,格式如:ins-olgl39y8,与云服务器控制台页面显示的实例ID相同。如果是CVM自建实例,需要传递此字段 :type CvmInstanceId: str :param UniqDcgId: 专线网关ID,格式如:dcg-0rxtqqxb :type UniqDcgId: str :param VpcId: 私有网络ID,格式如:vpc-92jblxto :type VpcId: str :param SubnetId: 私有网络下的子网ID,格式如:subnet-3paxmkdz :type SubnetId: str :param UniqVpnGwId: VPN网关ID,格式如:vpngw-9ghexg7q :type UniqVpnGwId: str :param InstanceId: 数据库实例ID,格式如:cdb-powiqx8q :type InstanceId: str :param Region: 地域英文名,如:ap-guangzhou :type Region: str :param Supplier: 当实例为RDS实例时,填写为aliyun, 其他情况均填写others :type Supplier: str :param CcnId: 云联网ID,如:ccn-afp6kltc 注意:此字段可能返回 null,表示取不到有效值。 :type CcnId: str :param EngineVersion: 数据库版本,当实例为RDS实例时才有效,格式如:5.6或者5.7,默认为5.6 :type EngineVersion: str """ self.AccessKey = None self.Ip = None self.Port = None self.User = None self.Password = None self.RdsInstanceId = None self.CvmInstanceId = None self.UniqDcgId = None self.VpcId = None self.SubnetId = None self.UniqVpnGwId = None self.InstanceId = None self.Region = None self.Supplier = None self.CcnId = None self.EngineVersion = None class StartMigrateJobRequest(AbstractModel): """StartMigrateJob请求参数结构体 """ def __init__(self): """ :param JobId: 数据迁移任务ID :type JobId: str """ self.JobId = None class StartMigrateJobResponse(AbstractModel): """StartMigrateJob返回参数结构体 """ def __init__(self): """ :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.RequestId = None class StartSyncJobRequest(AbstractModel): """StartSyncJob请求参数结构体 """ def __init__(self): """ :param JobId: 灾备同步任务ID :type JobId: str """ self.JobId = None class StartSyncJobResponse(AbstractModel): """StartSyncJob返回参数结构体 """ def __init__(self): """ :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.RequestId = None class StopMigrateJobRequest(AbstractModel): """StopMigrateJob请求参数结构体 """ def __init__(self): """ :param JobId: 数据迁移任务ID :type JobId: str """ self.JobId = None class StopMigrateJobResponse(AbstractModel): """StopMigrateJob返回参数结构体 """ def __init__(self): """ :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.RequestId = None class SubscribeInfo(AbstractModel): """订阅实例信息 """ def __init__(self): """ :param SubscribeId: 数据订阅的实例ID :type SubscribeId: str :param SubscribeName: 数据订阅实例的名称 :type SubscribeName: str :param ChannelId: 数据订阅实例绑定的通道ID :type ChannelId: str :param Product: 数据订阅绑定实例对应的产品名称 :type Product: str :param InstanceId: 数据订阅实例绑定的数据库实例ID :type InstanceId: str :param InstanceStatus: 数据订阅实例绑定的数据库实例状态 :type InstanceStatus: str :param SubsStatus: 数据订阅实例的配置状态,unconfigure - 未配置, configuring - 配置中,configured - 已配置 :type SubsStatus: str :param ModifyTime: 上次修改时间 :type ModifyTime: str :param CreateTime: 创建时间 :type CreateTime: str :param IsolateTime: 隔离时间 :type IsolateTime: str :param ExpireTime: 到期时间 :type ExpireTime: str :param OfflineTime: 下线时间 :type OfflineTime: str :param ConsumeStartTime: 最近一次修改的消费时间起点,如果从未修改则为零值 :type ConsumeStartTime: str :param Region: 数据订阅实例所属地域 :type Region: str :param PayType: 计费方式,0 - 包年包月,1 - 按量计费 :type PayType: int :param Vip: 数据订阅实例的Vip :type Vip: str :param Vport: 数据订阅实例的Vport :type Vport: int :param UniqVpcId: 数据订阅实例Vip所在VPC的唯一ID :type UniqVpcId: str :param UniqSubnetId: 数据订阅实例Vip所在子网的唯一ID :type UniqSubnetId: str :param Status: 数据订阅实例的状态,creating - 创建中,normal - 正常运行,isolating - 隔离中,isolated - 已隔离,offlining - 下线中,offline - 已下线 :type Status: str :param SdkConsumedTime: SDK最后一条确认消息的时间戳,如果SDK一直消费,也可以作为SDK当前消费时间点 :type SdkConsumedTime: str :param Tags: 标签 注意:此字段可能返回 null,表示取不到有效值。 :type Tags: list of TagItem :param AutoRenewFlag: 自动续费标识。0-不自动续费,1-自动续费 注意:此字段可能返回 null,表示取不到有效值。 :type AutoRenewFlag: int :param SubscribeVersion: 订阅实例版本;txdts-旧版数据订阅,kafka-kafka版本数据订阅 注意:此字段可能返回 null,表示取不到有效值。 :type SubscribeVersion: str """ self.SubscribeId = None self.SubscribeName = None self.ChannelId = None self.Product = None self.InstanceId = None self.InstanceStatus = None self.SubsStatus = None self.ModifyTime = None self.CreateTime = None self.IsolateTime = None self.ExpireTime = None self.OfflineTime = None self.ConsumeStartTime = None self.Region = None self.PayType = None self.Vip = None self.Vport = None self.UniqVpcId = None self.UniqSubnetId = None self.Status = None self.SdkConsumedTime = None self.Tags = None self.AutoRenewFlag = None self.SubscribeVersion = None class SubscribeObject(AbstractModel): """数据数据订阅的对象 """ def __init__(self): """ :param ObjectsType: 数据订阅对象的类型,0-数据库,1-数据库内的表 注意:此字段可能返回 null,表示取不到有效值。 :type ObjectsType: int :param DatabaseName: 订阅数据库的名称 注意:此字段可能返回 null,表示取不到有效值。 :type DatabaseName: str :param TableNames: 订阅数据库中表名称数组 注意:此字段可能返回 null,表示取不到有效值。 :type TableNames: list of str """ self.ObjectsType = None self.DatabaseName = None self.TableNames = None class SubscribeRegionConf(AbstractModel): """数据订阅地域售卖信息 """ def __init__(self): """ :param RegionName: 地域名称,如广州 注意:此字段可能返回 null,表示取不到有效值。 :type RegionName: str :param Region: 地区标识,如ap-guangzhou 注意:此字段可能返回 null,表示取不到有效值。 :type Region: str :param Area: 地域名称,如华南地区 注意:此字段可能返回 null,表示取不到有效值。 :type Area: str :param IsDefaultRegion: 是否为默认地域,0 - 不是,1 - 是的 注意:此字段可能返回 null,表示取不到有效值。 :type IsDefaultRegion: int :param Status: 当前地域的售卖情况,1 - 正常, 2-灰度,3 - 停售 注意:此字段可能返回 null,表示取不到有效值。 :type Status: int """ self.RegionName = None self.Region = None self.Area = None self.IsDefaultRegion = None self.Status = None class SwitchDrToMasterRequest(AbstractModel): """SwitchDrToMaster请求参数结构体 """ def __init__(self): """ :param DstInfo: 灾备实例的信息 :type DstInfo: :class:`tencentcloud.dts.v20180330.models.SyncInstanceInfo` :param DatabaseType: 数据库的类型 (如 mysql) :type DatabaseType: str """ self.DstInfo = None self.DatabaseType = None class SwitchDrToMasterResponse(AbstractModel): """SwitchDrToMaster返回参数结构体 """ def __init__(self): """ :param AsyncRequestId: 后台异步任务请求id :type AsyncRequestId: str :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.AsyncRequestId = None self.RequestId = None class SyncCheckStepInfo(AbstractModel): """灾备任务校验步骤 """ def __init__(self): """ :param StepNo: 步骤序列 :type StepNo: int :param StepName: 步骤展现名称 :type StepName: str :param StepCode: 步骤执行结果代码 :type StepCode: int :param StepMessage: 步骤执行结果提示 :type StepMessage: str """ self.StepNo = None self.StepName = None self.StepCode = None self.StepMessage = None class SyncDetailInfo(AbstractModel): """描述详细同步任务过程 """ def __init__(self): """ :param StepAll: 总步骤数 :type StepAll: int :param StepNow: 当前步骤 :type StepNow: int :param Progress: 总进度 :type Progress: str :param CurrentStepProgress: 当前步骤进度 :type CurrentStepProgress: str :param MasterSlaveDistance: 主从差距,MB :type MasterSlaveDistance: int :param SecondsBehindMaster: 主从差距,秒 :type SecondsBehindMaster: int :param StepInfo: 步骤信息 :type StepInfo: list of SyncStepDetailInfo """ self.StepAll = None self.StepNow = None self.Progress = None self.CurrentStepProgress = None self.MasterSlaveDistance = None self.SecondsBehindMaster = None self.StepInfo = None class SyncInstanceInfo(AbstractModel): """灾备同步的实例信息,记录主实例或灾备实例的信息 """ def __init__(self): """ :param Region: 地域英文名,如:ap-guangzhou :type Region: str :param InstanceId: 实例短ID :type InstanceId: str """ self.Region = None self.InstanceId = None class SyncJobInfo(AbstractModel): """灾备同步任务信息 """ def __init__(self): """ :param JobId: 灾备任务id :type JobId: str :param JobName: 灾备任务名 :type JobName: str :param SyncOption: 任务同步 :type SyncOption: :class:`tencentcloud.dts.v20180330.models.SyncOption` :param SrcAccessType: 源接入类型 :type SrcAccessType: str :param SrcDatabaseType: 源数据类型 :type SrcDatabaseType: str :param SrcInfo: 源实例信息 :type SrcInfo: :class:`tencentcloud.dts.v20180330.models.SyncInstanceInfo` :param DstAccessType: 灾备接入类型 :type DstAccessType: str :param DstDatabaseType: 灾备数据类型 :type DstDatabaseType: str :param DstInfo: 灾备实例信息 :type DstInfo: :class:`tencentcloud.dts.v20180330.models.SyncInstanceInfo` :param Detail: 任务信息 :type Detail: :class:`tencentcloud.dts.v20180330.models.SyncDetailInfo` :param Status: 任务状态 :type Status: int :param DatabaseInfo: 迁移库表 :type DatabaseInfo: str :param CreateTime: 创建时间 :type CreateTime: str :param StartTime: 开始时间 :type StartTime: str :param EndTime: 结束时间 :type EndTime: str """ self.JobId = None self.JobName = None self.SyncOption = None self.SrcAccessType = None self.SrcDatabaseType = None self.SrcInfo = None self.DstAccessType = None self.DstDatabaseType = None self.DstInfo = None self.Detail = None self.Status = None self.DatabaseInfo = None self.CreateTime = None self.StartTime = None self.EndTime = None class SyncOption(AbstractModel): """灾备同步任务配置选项 """ def __init__(self): """ :param SyncObject: 同步对象,1-整个实例,2-指定库表 :type SyncObject: int :param RunMode: 同步开始设置,1-立即开始 :type RunMode: int :param SyncType: 同步模式, 3-全量且增量同步 :type SyncType: int :param ConsistencyType: 数据一致性检测, 1-无需配置 :type ConsistencyType: int """ self.SyncObject = None self.RunMode = None self.SyncType = None self.ConsistencyType = None class SyncStepDetailInfo(AbstractModel): """同步任务进度 """ def __init__(self): """ :param StepNo: 步骤编号 :type StepNo: int :param StepName: 步骤名 :type StepName: str :param CanStop: 能否中止 :type CanStop: int :param StepId: 步骤号 :type StepId: int """ self.StepNo = None self.StepName = None self.CanStop = None self.StepId = None class TagFilter(AbstractModel): """标签过滤 """ def __init__(self): """ :param TagKey: 标签键值 :type TagKey: str :param TagValue: 标签值 :type TagValue: list of str """ self.TagKey = None self.TagValue = None class TagItem(AbstractModel): """标签 """ def __init__(self): """ :param TagKey: 标签键值 :type TagKey: str :param TagValue: 标签值 注意:此字段可能返回 null,表示取不到有效值。 :type TagValue: str """ self.TagKey = None self.TagValue = None
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 23, 532, 9, 12, 198, 2, 15069, 357, 66, 8, 2177, 12, 7908, 2320, 43, 317, 1959, 15302, 11, 257, 9368, 1087, 1664, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11...
1.476582
33,778
# https://www.hackerrank.com/challenges/count-triplets-1/problem # This solution works but will time out #!/bin/python3 import math import os import random import re import sys from collections import defaultdict # Complete the countTriplets function below. if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nr = input().rstrip().split() n = int(nr[0]) r = int(nr[1]) arr = list(map(int, input().rstrip().split())) ans = countTriplets(arr, r) fptr.write(str(ans) + '\n') fptr.close()
[ 2, 3740, 1378, 2503, 13, 31153, 8056, 962, 13, 785, 14, 36747, 34120, 14, 9127, 12, 28461, 46916, 12, 16, 14, 45573, 198, 2, 770, 4610, 2499, 475, 481, 640, 503, 198, 198, 2, 48443, 8800, 14, 29412, 18, 198, 198, 11748, 10688, 198...
2.639423
208
default_app_config = "kitsune.wiki.apps.WikiConfig"
[ 12286, 62, 1324, 62, 11250, 796, 366, 74, 896, 1726, 13, 15466, 13, 18211, 13, 32603, 16934, 1, 198 ]
2.736842
19
# Generated by Django 2.2.14 on 2021-01-11 23:18 from django.db import migrations, models import django.utils.timezone
[ 2, 2980, 515, 416, 37770, 362, 13, 17, 13, 1415, 319, 33448, 12, 486, 12, 1157, 2242, 25, 1507, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 26791, 13, 2435, 11340, 628 ]
2.95122
41
#! /usr/bin/env python3 # SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) # # SPDX-License-Identifier: MIT import sys import os import json import yaml import build_board_info workflow_file = '.github/workflows/build.yml' # Get boards in json format boards_info_json = build_board_info.get_board_mapping() # Get all the boards out of the json format info_boards = [board for board in boards_info_json.keys() if not boards_info_json[board].get("alias", False)] # We need to know the path of the workflow file base_path = os.path.dirname(__file__) yml_path = os.path.abspath(os.path.join(base_path, '..', workflow_file)) # Loading board list based on build jobs in the workflow file. ci_boards = [] with open(yml_path, "r") as f: workflow = yaml.safe_load(f) ok = True for job in workflow["jobs"]: if not job.startswith("build"): continue job_boards = workflow["jobs"][job]["strategy"]["matrix"]["board"] if job_boards != sorted(job_boards): print("Boards for job \"{}\" not sorted. Must be:".format(job)) print(" - \"" + "\"\n - \"".join(sorted(job_boards)) + "\"") ok = False ci_boards.extend(job_boards) # All the travis_boards elements must be on info_boards info_boards.sort() ci_boards.sort() missing_boards = set(info_boards) - set(ci_boards) if missing_boards: ok = False print('Boards missing in {}:'.format(workflow_file)) for board in missing_boards: print(board) if not ok: sys.exit(1)
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 2, 30628, 55, 12, 8979, 15269, 8206, 25, 1946, 4527, 37906, 1222, 13588, 37906, 20420, 357, 5450, 1378, 12567, 13, 785, 14, 324, 1878, 4872, 14, 21170, 5013, 29412, 14, 34...
2.663866
595
#! /usr/bin/env python from setuptools import setup, find_packages setup( name = 'pyspatialite', version = '0.2', packages=['pyspatialite'], description = 'DB-API 2.0 interface for SQLite 3.x with Spatialite', author = 'Lokkju Brennr', author_email = 'lokkju@lokkju.com', license = 'zlib/libpng license', platforms = 'ALL', url = 'https://github.com/lokkju/pyspatialite/', # no download_url, since pypi hosts it! #download_url = 'http://code.google.com/p/pyspatialite/downloads/list', package_data={ 'pyspatialite': ['*.dll', '*.pyd'], } )
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 40406, 7, 198, 220, 220, 220, 1438, 796, 705, 79, 893, 8071, 498, 578, 3256, 198, 220, 220, 220, 2196, 796, 705, 15...
2.330739
257
""" Python package which is intended to gather all kinds of MPEG-1 Audio related meta information from file. Such as duration of MPEGAudio file, average bitrate for variable bitrate (VBR) MPEGAudio files, etc. Most of the information about MPEGAudio Headers is from excellent article `MPEGAudio Audio Frame Header By Konrad Windszus, in Code Project <http://www.codeproject.com/KB/audio-video/mpegaudioinfo.aspx#MPEGAudioFrame>`_. If you are solely interested on details of MPEGAudio headers that is a good place to start. Unit tests (:file:`tests/` -directory) are matched against the MPEGAudioInfo.exe provided in that project. Notable feature of mpeg1audio is the fact that it :doc:`tries to parse lazily</laziness>`. It doesn't parse all frames, or ending unless really needed. .. todo:: Free bitrate, this should be simple to implement, though I haven't yet found any free bitrate files which to test against. .. todo:: Table of contents for VBR, this is not high on priority list since we don't need to seek the MPEGAudio really. Usage example ------------- >>> import mpeg1audio >>> try: ... mp3 = mpeg1audio.MPEGAudio(open('data/song.mp3', 'rb')) ... except mpeg1audio.MPEGAudioHeaderException: ... pass ... else: ... print mp3.duration 0:03:12 Why the exception? It may seem unnecessary, but it has a purpose so that there cannot be *empty* MPEGAudio instances, those are more infuriating than the handling of exception. """ import os from mpeg1audio.utils import FileOpener __version__ = "0.5.5" __release__ = "0.5.5 alpha" __copyright__ = "Jari Pennanen, 2010" __description__ = "MPEG-1 Audio package" __author__ = "Jari Pennanen" __license__ = "FreeBSD, see COPYING" # Pylint disable settings: # ------------------------ # ToDos, DocStrings: # pylint: disable-msg=W0511,W0105 # # Unused variable, argument: # pylint: disable-msg=W0612,W0613 # # Re-define built-in: # pylint: disable-msg=W0622 # # Protected member access: # pylint: disable-msg=W0212 # # Too many lines per module: # pylint: disable-msg=C0302 # # Too many instance attributes, Too few public methods: # pylint: disable-msg=R0902,R0903 # # TODO: LOW: I don't like the verboseness of EpyDoc syntax, maybe change to # reStructuredText? from datetime import timedelta from mpeg1audio import headers from mpeg1audio import utils from headers import MPEGAudioHeaderEOFException, MPEGAudioHeaderException import math import struct __all__ = ['MPEGAudioFrameBase', 'MPEGAudioFrameIterator', 'MPEGAudioFrame', 'MPEGAudio', 'MPEGAudioHeaderException', 'MPEGAudioHeaderEOFException', 'PARSE_ALL_CHUNK_SIZE', 'headers', 'utils', 'vbri', 'xing'] PARSE_ALL_CHUNK_SIZE = 153600 """Chunk size of parsing all frames. :type: int""" class MPEGAudioFrameBase(object): """MPEGAudio frame base, should not be instated, only inherited. Variables defined here are constant through out the frames of :class:`MPEGAudio`. """ class MPEGAudioFrame(MPEGAudioFrameBase): """MPEGAudio *Frame* meta data.""" def get_forward_iterator(self, file, chunk_size=None): """Get forward iterator from this position. :param file: File object :type file: file object :param chunk_size: Chunked reading size, ``None`` defaults to :const:`mpeg1audio.utils.DEFAULT_CHUNK_SIZE`. :type chunk_size: int :return: Generator that iterates forward from this frame. :rtype: generator of :class:`MPEGAudioFrame` """ # TODO: LOW: Free bitrate. next_frame_offset = self.offset + self.size chunks = utils.chunked_reader(file, start_position=next_frame_offset, chunk_size=chunk_size) return MPEGAudioFrame.parse_consecutive(next_frame_offset, chunks) # def get_backward_iterator(self, file): # # TODO: LOW: Backward iterator # raise NotImplementedError('Backward iteration not implemented!') @classmethod def find_and_parse(cls, file, max_frames=3, chunk_size=None, #IGNORE:R0913 begin_frame_search= -1, lazily_after=1, max_chunks= -1, max_consecutive_chunks= -1): """Find and parse from file. :param file: File object being searched. :type file: file object :param max_frames: Maximum of frames returned. Defaults to ``3``. ``None`` means give all frames as lazy generator. :type max_frames: int, or None :param chunk_size: Size of chunked reading. Defaults to :const:`utils.DEFAULT_CHUNK_SIZE`, minimum ``4``. :type chunk_size: int :param begin_frame_search: Begin frame search from this position in file. Defaults to ``-1``, meaning continue where file pointer has left. :type begin_frame_search: int :param lazily_after: Check also next header(s), before becoming lazy generator. Defaults to ``1``. :type lazily_after: int :param max_chunks: Maximum amount of chunks the chunked reader can yield. ``-1`` means infinity, and can be looped to end of file. :type max_chunks: int :param max_consecutive_chunks: Maximum of *consecutive* chunks in returned lazy generator. ``-1`` means infinity, and can be looped to end of file. :type max_consecutive_chunks: int """ chunk_size = chunk_size or utils.DEFAULT_CHUNK_SIZE chunk_size = max(chunk_size, 4) chunks = utils.chunked_reader(file, chunk_size=chunk_size, start_position=begin_frame_search, max_chunks=max_chunks) for chunk_offset, chunk in chunks: for found in utils.find_all_overlapping(chunk, chr(255)): consecutive_chunks = \ utils.chunked_reader(file, chunk_size=chunk_size, start_position=chunk_offset + found, max_chunks=max_consecutive_chunks) frames = MPEGAudioFrame.parse_consecutive(chunk_offset + found, consecutive_chunks) try: return utils.genlimit(frames, lazily_after + 1, max_frames) except ValueError: pass return iter([]) @classmethod def parse_consecutive(cls, header_offset, chunks): """Parse consecutive MPEGAudio Frame headers. Parses from given position until header parsing error, or end of chunks. :param header_offset: Header offset *within a file*. :type header_offset: int :param chunks: Generator yielding more chunks when *End of Chunk* is reached. :type chunks: generator, or list :return: Generator yielding MPEGAudio frames. :rtype: generator of :class:`MPEGFrame` :see: :func:`utils.chunked_reader()` """ previous_mpegframe = None previous_mpegframe_offset = None previous_chunk = "" next_mpegframe_offset = header_offset for next_chunk_offset, next_chunk in chunks: # Get 4 bytes from previous chunk previous_chunk_end = previous_chunk[-4:] # Join the 4 bytes, if there were any, to tested chunk chunk = previous_chunk_end + next_chunk chunk_offset = next_chunk_offset - len(previous_chunk_end) # Yield all frames in chunk while True: if (previous_mpegframe is not None) and \ (previous_mpegframe_offset is not None): if previous_mpegframe.size is None: return # TODO: LOW: Free bitrate, you must search for the # second frame. next_mpegframe_offset = previous_mpegframe_offset + \ previous_mpegframe.size next_mpegframe = None next_header_offset = next_mpegframe_offset - chunk_offset # Get header bytes within chunk try: header_bytes = headers.get_bytes(next_header_offset, chunk) except MPEGAudioHeaderEOFException: # We need next chunk, end of this chunk was reached break # Parse and append if parseable try: next_mpegframe = MPEGAudioFrame.parse(header_bytes) except MPEGAudioHeaderException: return else: # Frame was parsed successfully next_mpegframe.offset = next_mpegframe_offset yield next_mpegframe previous_mpegframe_offset = next_mpegframe_offset previous_mpegframe = next_mpegframe previous_chunk = next_chunk return @classmethod def parse(cls, bytes): """Tries to create MPEGAudio Frame from given bytes. :param bytes: MPEGAudio Header bytes. Usually obtained with :func:`headers.get_bytes` :type bytes: int :rtype: :class:`MPEGAudioFrame` :return: MPEGAudio Frame :raise headers.MPEGAudioHeaderException: Raised if MPEGAudio Frame cannot be parsed. """ # TODO: LOW: CRC, verify and parse. # http://www.codeproject.com/KB/audio-video/mpegaudioinfo.aspx#CRC # Header synchronization bits headers.check_sync_bits((bytes >> 21) & 2047) # Header parseable information mpeg_version_bits = (bytes >> 19) & 3 layer_bits = (bytes >> 17) & 3 protection_bit = (bytes >> 16) & 1 bitrate_bits = (bytes >> 12) & 15 samplerate_bits = (bytes >> 10) & 3 padding_bit = (bytes >> 9) & 1 private_bit = (bytes >> 8) & 1 mode_bits = (bytes >> 6) & 3 mode_extension_bits = (bytes >> 4) & 3 copyright_bit = (bytes >> 3) & 1 original_bit = (bytes >> 2) & 1 emphasis_bits = (bytes >> 0) & 3 self = MPEGAudioFrame() self.version = headers.get_mpeg_version(mpeg_version_bits) self.layer = headers.get_layer(layer_bits) self.bitrate = headers.get_bitrate(self.version, self.layer, bitrate_bits) self.sample_rate = headers.get_sample_rate(self.version, samplerate_bits) self.channel_mode = headers.get_channel_mode(mode_bits) self.channel_mode_extension = \ headers.get_channel_mode_ext(self.layer, mode_extension_bits) self.emphasis = headers.get_emphasis(emphasis_bits) self._padding_size = padding_bit self.is_private = private_bit == 1 self.is_copyrighted = copyright_bit == 1 self.is_original = original_bit == 1 self.is_protected = protection_bit == 1 # Non-header parseable information self.samples_per_frame = headers.get_samples_per_frame(self.version, self.layer) self.size = headers.get_frame_size(self.version, self.layer, self.sample_rate, self.bitrate, self._padding_size) return self class MPEGAudioFrameIterator(object): """MPEGAudio Frame iterator, for lazy evaluation.""" def __init__(self, mpeg, begin_frames, end_frames): """ :param mpeg: MPEGAudio Which frames are to be iterated over. :type mpeg: :class:`MPEGAudio` :param begin_frames: First frames of MPEGAudio. :type begin_frames: lambda: [:class:`MPEGAudioFrame`, ...] :param end_frames: End frames of MPEGAudio. :type end_frames: lambda: [:class:`MPEGAudioFrame`, ...] """ self.mpeg = mpeg """MPEGAudio which frames are iterated. :type: :class:`MPEGAudio` """ self._begin_frames = begin_frames """Begin frames. :type: list of :class:`MPEGAudioFrame` """ self._end_frames = end_frames """End frames. :type: list of :class:`MPEGAudioFrame`, or None """ self._has_parsed_all = False """Has parsing all occurred? :type: bool """ self._has_parsed_beginning = not callable(self._begin_frames) """Has parsing beginning occurred? :type: bool """ self._has_parsed_ending = not callable(self._end_frames) """Has parsing end occurred? :type: bool """ def parse_all(self, force=False): """Parse all frames. :see: :func:`MPEGAudio.parse_all` """ # TODO: LOW: How do we deal corrupted MPEGAudio files? # Where some frames are misplaced, etc? if self._has_parsed_all and not force: # TODO: DEBUG! raise NotImplementedError('This should not happen, ever!') # return avg_bitrate = 0 index = -1 for index, frame in enumerate(self): avg_bitrate += frame.bitrate # Close for now self.mpeg.close() frame_count = index + 1 bitrate = avg_bitrate / frame_count # Set MPEGAudio values self.mpeg.frame_count = frame_count self.mpeg.bitrate = bitrate # Set has parsed all self._has_parsed_all = True # def __reversed__(self): # # TODO: LOW: Backward iterator # pass class MPEGAudio(MPEGAudioFrameBase): """ Parses MPEGAudio file meta data. Uses Xing and VBRI headers if neccessary, for better performance with VBR files. VBR files that doesn't have those headers the file must parse all frames. """ _file = FileOpener(mode='rb') """Opens the file when needed""" def __init__(self, file, begin_start_looking=0, ending_start_looking=0, mpeg_test=True): """ .. todo:: If given filename, create file and close it always automatically when not needed. :param file: File handle returned e.g. by open(). Alternatively path to file which to open on request. :type file: file object, or string :param begin_start_looking: Start position of MPEGAudio header search. For example if you know that file has ID3v2, it is adviced to give the size of ID3v2 tag to this field. Value *must be equal or lesser than* (<=) the beginning of MPEGAudio. If the given value exceeds the first header, the given MPEGAudio might be incorrect. :type begin_start_looking: int :param ending_start_looking: End position of MPEGAudio *relative to end of file*. For example if you know that file has ID3v1 footer, give ``128``, the size of ID3v1, this ensures that we can *at least* skip over that. Value *must be equal or lesser than* (<=) end of the last MPEGAudio header. :type ending_start_looking: int :param mpeg_test: Do mpeg test first before continuing with parsing the beginning. This is useful especially if there is even slight possibility that given file is not MPEGAudio, we can rule them out fast. :type mpeg_test: bool :raise headers.MPEGAudioHeaderException: Raised if header cannot be found. """ super(MPEGAudio, self).__init__() self._filepath = None """File path type: String, unicode, or :const:`None` """ self._filehandle = None """File handle when instiated using path to file. type: File object, or :const:`None` """ # If instiated using path to file if isinstance(file, (str, unicode)): self._filepath = file # Open the file try: file = open(file, "rb") except (IOError, os.error): raise MPEGAudioHeaderException( 'File %s cannot be opened' % file) self._filehandle = file # If instiated using file object else: self._file = file """File object. :type: file object """ self.is_vbr = False """Is variable bitrate? type: bool """ self.filesize = utils.get_filesize(file) """Filesize in bytes. :type: int """ self.xing = None """XING Header, if any. :type: :class:`XING`, or None """ self.vbri = None """VBRI Header, if any. :type: :class:`VBRI`, or None """ self.frames = None """All MPEGAudio frames. :type: iterator for :class:`MPEGAudioFrame` """ self._frame_count = None self._frame_size = None self._size = None self._duration = None self._bitrate = None self._begin_start_looking = begin_start_looking self._ending_start_looking = ending_start_looking test_frames = [] if mpeg_test: test_frames = list(self.is_mpeg_test()) # Parse beginning of file, when needed. In reality, this is run every # time init is run. The set_mpeg_details, XING, VBRI uses the first # frames so we cannot make this very lazy. begin_frames = lambda: self.parse_beginning(begin_start_looking) # Parse ending of file, when needed. end_frames = lambda: self.parse_ending(ending_start_looking) # Creates frame iterator between begin and end frames. self.frames = MPEGAudioFrameIterator(self, begin_frames, end_frames) # Set MPEGAudio Details self.set_mpeg_details(self.frames[0], test_frames) # Parse VBR Headers if can be found. self.parse_xing() self.parse_vbri() # Close for now self.close() def _get_size(self, parse_all=False, parse_ending=True): """MPEGAudio Size getter. :rtype: int, or None """ if self._size is not None: return self._size if parse_ending: # 100% accurate size, if parsing ending did indeed return frame from # same MPEGAudio: self.size = self.frames[-1].offset + self.frames[-1].size - \ self.frames[0].offset else: # TODO: NORMAL: Estimation of size Following might be a good enough # for 99% of time, maybe it should be default? A biggest risk is # that files with a *huge* footer will yield totally inaccurate # values, is that risk too big? # # Should we choose a higher accuracy over performance with 99% of # cases? self.size = self.filesize - self._ending_start_looking - \ self.frames[0].offset # TODO: LOW: parse_all in here is redundant, parse_ending gives 100% # accurate. if parse_all: self.frames.parse_all() return self._size def _set_size(self, value): """MPEGAudio Size setter.""" self._size = value def _get_sample_count(self, parse_all=False, parse_ending=True): """Sample count getter. :rtype: int, or None """ frame_count = self._get_frame_count(parse_all=parse_all, parse_ending=parse_ending) if frame_count is not None: return self.frame_count * self.samples_per_frame return None def _get_bitrate(self, parse_all=True): """Bitrate getter. :rtype: int, float, or None """ if self._bitrate is not None: return self._bitrate if self.is_vbr: sample_count = self._get_sample_count(parse_all) mpeg_size = self._get_size() self.bitrate = headers.get_vbr_bitrate(mpeg_size, sample_count, self.sample_rate) return self._bitrate def _set_bitrate(self, value): """Bitrate setter.""" self._bitrate = value def _get_frame_count(self, parse_all=False, parse_ending=True): """Frame count getter. :rtype: int, or None """ if self._frame_count is not None: return self._frame_count if not self.is_vbr: # CBR mpeg_size = self._get_size(parse_all=parse_all, parse_ending=parse_ending) first_frame = self.frames[0] unpadded_frame_size = first_frame.size - first_frame._padding_size # unpadded_frames = float(self.size) / float(unpadded_frame_size) padded_frame_size = unpadded_frame_size + 1 padded_frames = float(mpeg_size) / float(padded_frame_size) # TODO: NORMAL: Estimation of frame_count: # it seems to be either this: self._frame_count = int(math.ceil(padded_frames)) # or this: #self._frame_count = int(unpadded_frames) # now how can we guess which one? # print unpadded_frames, padded_frames # Average it aint: #self._frame_count = int(round((unpadded_frames + padded_frames) / \ # float(2))) else: # VBR self.frames.parse_all() #raise NotImplementedError('Frame count not yet lazy.') return self._frame_count def _set_frame_count(self, value): """Frame count setter.""" self._frame_count = value def _get_frame_size(self, parse_all=True): """Frame size getter. :rtype: int, or None """ if self._frame_size is not None: return self._frame_size if not self.is_vbr: # CBR self.frame_size = self.frames[0].size else: # VBR frame_count = self._get_frame_count() mpeg_size = self._get_size() self.frame_size = headers.get_vbr_frame_size(mpeg_size, frame_count) return self._frame_size def _set_frame_size(self, value): """Frame size setter.""" self._frame_size = value def _get_duration(self, parse_all=True): """Duration getter. :rtype: datetime.timedelta, or None """ if self._duration is not None: return self._duration if not self.is_vbr: # CBR sample_count = self._get_sample_count(parse_all=False, parse_ending=True) if sample_count is not None: self.duration = \ headers.get_duration_from_sample_count(sample_count, self.sample_rate) # mpeg_size = self._get_size() # bitrate = self._get_bitrate(parse_all) # if (bitrate is not None) and (mpeg_size is not None): # self.duration = \ # _get_duration_from_size_bitrate(mpeg_size=self.size, # bitrate=self.bitrate) else: # VBR sample_count = self._get_sample_count(parse_all) if sample_count is not None: self.duration = \ headers.get_duration_from_sample_count(sample_count, self.sample_rate) return self._duration def _set_duration(self, value): """Duration setter.""" self._duration = value size = property(_get_size, _set_size) """MPEGAudio Size in bytes. .. note:: May start parsing of :func:`all frames<MPEGAudio.parse_all>`, or :func:`ending frames<MPEGAudio.parse_ending>`. :type: int """ sample_count = property(_get_sample_count) """Count of samples in MPEGAudio. .. note:: May start parsing of all frames. :type: int """ frame_size = property(_get_frame_size, _set_frame_size) """Frame size in bytes. For VBR files this is *average frame size*. .. note:: May start parsing of all frames. :type: int """ bitrate = property(_get_bitrate, _set_bitrate) """Bitrate of the *file* in kilobits per second, for example 192. For VBR files this is *average bitrate* returned as ``float``. .. note:: May start parsing of all frames. :type: int, or float """ frame_count = property(_get_frame_count, _set_frame_count) """Count of frames in MPEGAudio. .. note:: May start parsing of all frames. :type: int """ duration = property(_get_duration, _set_duration) """Duration. .. note:: May start parsing of all frames. :type: datetime.timedelta """ def parse_xing(self): """Tries to parse and set XING from first mpeg frame. :see: :class:`XING` """ from xing import XING, XINGHeaderException try: self.xing = XING.find_and_parse(self._file, self.frames[0].offset) except XINGHeaderException: pass else: VBRHeader.set_mpeg(self, self.xing) def parse_vbri(self): """Tries to parse and set VBRI from first mpeg frame. :see: :class:`VBRI` """ from vbri import VBRI, VBRIHeaderException try: self.vbri = VBRI.find_and_parse(self._file, self.frames[0].offset) except VBRIHeaderException: pass else: VBRHeader.set_mpeg(self, self.vbri) def is_mpeg_test(self, test_position=None): """Test that the file is MPEGAudio. Validates that from middle of the file we can find three valid consecutive MPEGAudio frames. :raise headers.MPEGAudioHeaderException: Raised if MPEGAudio frames cannot be found. :return: List of test MPEGAudio frames. :rtype: list """ # The absolute theoretical maximum frame size is 2881 bytes: # MPEGAudio 2.5 Layer II, 8000 Hz @ 160 kbps, with a padding slot. # # To get three consecutive headers we need (in bytes): # (Max Frame Size + Header Size) * (Amount of consecutive frames + 1) # # This calculation yields (2881+4)*4 = 11 540, which I decided to round # to (2^14 = 16 384) # TODO: LOW: Some people use random position in the middle, but why? # # If test position is not given explicitely it is assumed to be at the # middle of "start" and "end" of looking. if test_position is None: looking_length = self.filesize - self._ending_start_looking - \ self._begin_start_looking test_position = self._begin_start_looking + \ int(0.5 * looking_length) try: return utils.genmin(MPEGAudioFrame.find_and_parse(file=self._file, max_frames=3, chunk_size=16384, begin_frame_search=test_position, lazily_after=2, max_chunks=1), 3) except ValueError: raise MPEGAudioHeaderException("MPEG Test is not passed, " "file might not be MPEG?") def set_mpeg_details(self, first_mpegframe, mpegframes): """Sets details of *this* MPEGAudio from the given frames. Idea here is that usually one or multiple mpeg frames represents single MPEGAudio file with good probability, only if the file is VBR this fails. :param first_mpegframe: First MPEGAudio frame of the file. :type first_mpegframe: :class:`MPEGAudioFrame` :param mpegframes: List of MPEGAudio frames, order and position does not matter, only thing matters are the fact they are from same MPEGAudio. These are used determine the VBR status of the file. :type mpegframes: [:class:`MPEGAudioFrame`, ...] """ # Copy values of MPEGAudio Frame to MPEGAudio, where applicable. self.is_copyrighted = first_mpegframe.is_copyrighted self.is_original = first_mpegframe.is_original self.is_private = first_mpegframe.is_private self.is_protected = first_mpegframe.is_protected self.offset = first_mpegframe.offset self.channel_mode = first_mpegframe.channel_mode self.channel_mode_extension = first_mpegframe.channel_mode_extension self.emphasis = first_mpegframe.emphasis self.sample_rate = first_mpegframe.sample_rate self.samples_per_frame = first_mpegframe.samples_per_frame self.frame_size = first_mpegframe.size self.bitrate = first_mpegframe.bitrate # If no testing frames was given, resort to getting last three frames. if len(mpegframes) == 0: mpegframes = self.frames[-3:] # If any of the bitrates differ, this is most likely VBR. self.is_vbr = any(mpegframe.bitrate != first_mpegframe.bitrate \ for mpegframe in mpegframes) if self.is_vbr: self.bitrate = None self.frame_size = None self.frame_count = None def parse_all(self, force=False): """Parse all frames. You should not need to call this, the initialization of :class:`MPEGAudio`, or getters does this automatically. By parsing all frames, MPEGAudio is ensured to populate following fields with *accurate values*: - ``frame_count`` - ``bitrate`` Essentially all properties, and variables of MPEGAudio should be as accurate as possible after running this. :param force: Force re-parsing all frames. Defaults to ``False``. :type force: bool """ # Semantically, I think, only frames should have parse_all() only, thus # this MPEGAudio.parse_all() exists purely because user of this API # should not need to guess the "extra" semantics of frames and # MPEGAudio. self.frames.parse_all(force=force) def parse_beginning(self, begin_offset=0, max_frames=6): """Parse beginning of MPEGAudio. :param begin_offset: Beginning offset, from beginning of file. :type begin_offset: int :param max_frames: Maximum of frames to be parsed, and returned forward from first found frame. ``-1`` means *infinity*, and can be looped to end of file. :type max_frames: int :return: List of MPEGAudio frames. :rtype: [:class:`MPEGAudioFrame`, ...] :raise headers.MPEGAudioHeaderException: Raised if no frames was found. This should not happen if :class:`MPEGAudio.is_mpeg_test` has passed. """ try: return utils.genmin(\ MPEGAudioFrame.find_and_parse(file=self._file, max_frames=max_frames, begin_frame_search=begin_offset), 1) except ValueError: raise MPEGAudioHeaderEOFException( "There is not enough frames in this file.") def parse_ending(self, end_offset=0, min_frames=3, rewind_offset=4000): """Parse ending of MPEGAudio. You should not need to call this, the initialization of :class:`MPEGAudio`, or getters does this automatically. .. note:: Performance wisely the max_frames argument would be useless, and is not implemented. As this method must try recursively find_and_parse further and further from the ending until minimum of frames is met. This might take a long time for files that does not have frames. :param end_offset: End offset as relative to *end of file*, if you know the *size of footers*, give that. :type end_offset: int :param min_frames: Minimum amount of frames from the end of file. :type min_frames: int :param rewind_offset: When minimum is not met, rewind the offset this much and retry. Defaults to ``4000``. :type rewind_offset: int :return: List of MPEGAudio frames, amount of items is variable. :rtype: [:class:`MPEGAudioFrame`, ...] :raise headers.MPEGAudioHeaderEOFException: Raised if whole file does not include any frames. This should not happen if :func:`MPEGAudio.is_mpeg_test` has passed. """ # min_frames is always positive: min_frames = max(min_frames, 1) begin_frame_search = self.filesize - end_offset end_frames = [] while True: # Oh noes, not enough frames. if len(end_frames) < min_frames: begin_frame_search -= rewind_offset # Retry from backwards... end_frames = \ list(MPEGAudioFrame.find_and_parse(\ file=self._file, max_frames=None, begin_frame_search=begin_frame_search)) if begin_frame_search < 0 and len(end_frames) < min_frames: raise MPEGAudioHeaderException( 'Not enough frames was found') else: return end_frames class VBRHeader(object): """VBR Header""" @classmethod def set_mpeg(cls, mpeg, vbr): """Set values of VBR header to MPEGAudio. :param mpeg: MPEGAudio to be set. :type mpeg: :class:`MPEGAudio` :param vbr: VBR from where to set. :type vbr: :class:`VBRHeader` """ if vbr.frame_count is not None: mpeg.frame_count = vbr.frame_count if vbr.mpeg_size is not None: mpeg.size = vbr.mpeg_size
[ 37811, 198, 37906, 5301, 543, 318, 5292, 284, 6431, 477, 6982, 286, 41203, 12, 16, 13491, 3519, 198, 28961, 1321, 422, 2393, 13, 8013, 355, 9478, 286, 41203, 21206, 2393, 11, 2811, 1643, 4873, 198, 1640, 7885, 1643, 4873, 357, 53, 114...
2.133281
16,679
all = [ ' hydrogen', ' helium', ' lithium', ' beryllium', ' boron', ' carbon', ' nitrogen', ' oxygen', ' fluorine', ' neon', ' sodium', ' magnesium', ' aluminum', ' silicon', ' phosphorus', ' sulfur', ' chlorine', ' argon', ' potassium', ' calcium', ' scandium', ' titanium', ' vanadium', ' chromium', ' manganese', ' iron', ' cobalt', ' nickel', ' copper', ' zinc', ' gallium', ' germanium', ' arsenic', ' selenium', ' bromine', ' krypton', ' rubidium', ' strontium', ' yttrium', ' zirconium', ' niobium', ' molybdenum', ' technetium', ' ruthenium', ' rhodium', ' palladium', ' silver', ' cadmium', ' indium', ' tin', ' antimony', ' tellurium', ' iodine', ' xenon', ' cesium', ' barium', ' lanthanum', ' cerium', ' praseodymium', ' neodymium', ' promethium', ' samarium', ' europium', ' gadolinium', ' terbium', ' dysprosium', ' holmium', ' erbium', ' thulium', ' ytterbium', ' lutetium', ' hafnium', ' tantalum', ' tungsten', ' rhenium', ' osmium', ' iridium', ' platinum', ' gold', ' mercury', ' thallium', ' lead', ' bismuth', ' polonium', ' astatine', ' radon', ' francium', ' radium', ' actinium', ' thorium', ' protactinium', ' uranium', ' neptunium', ' plutonium', ' americium', ' curium', ' berkelium', ' californium', ' einsteinium', ' fermium', ' mendelevium', ' nobelium', ' lawrencium', ' rutherfordium', ' dubnium', ' seaborgium', ' bohrium', ' hassium', ' meitnerium', ' darmstadtium', ' roentgenium', ' copernicium', ' ununtrium', ' flerovium', ' ununpentium', ' livermorium', ' ununseptium', ' ununoctium', ]
[ 439, 796, 685, 198, 220, 705, 17669, 3256, 198, 220, 705, 43142, 3256, 198, 220, 705, 28444, 3256, 198, 220, 705, 275, 1924, 297, 1505, 3256, 198, 220, 705, 275, 273, 261, 3256, 198, 220, 705, 6588, 3256, 198, 220, 705, 23417, 3256,...
2.273548
775
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="EEG/GSR Wellness Tracker", version="0.0.1", author="Bar Lehmann", author_email="bar.lehmann@gmail.com", description="A package to help explore connections between EEG/GSR with self reported measures of Mood and Focus using the MNE API", long_description= "A package to facilitate easy introductory use of MNE Python and simple statistical analyses of EEG biometrics with self reported mood and focus ratings. Short records of about (10 seconds) can be used as entries, and GSR data can be added if possible/desired. Basic means of analyses of such connections between EEG/GSR with self reported measures of Mood and Focus are provided in the package. This package uses the MNE API", long_description_content_type="text/markdown", url="https://github.com/barlehmann/EEG_GSR_Wellness_Tracker", packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], python_requires='>=3.6', )
[ 198, 11748, 900, 37623, 10141, 628, 198, 4480, 1280, 7203, 15675, 11682, 13, 9132, 1600, 366, 81, 4943, 355, 277, 71, 25, 198, 220, 220, 220, 890, 62, 11213, 796, 277, 71, 13, 961, 3419, 198, 198, 2617, 37623, 10141, 13, 40406, 7, ...
3.197297
370
input = [4, 6, 2, 9, 1] print(selection_sort(input)) # print(input) # [1, 2, 4, 6, 9] 가 되어야 합니다!
[ 15414, 796, 685, 19, 11, 718, 11, 362, 11, 860, 11, 352, 60, 628, 198, 198, 4798, 7, 49283, 62, 30619, 7, 15414, 4008, 198, 2, 3601, 7, 15414, 8, 1303, 685, 16, 11, 362, 11, 604, 11, 718, 11, 860, 60, 220, 166, 108, 222, 316...
1.578125
64
carro = Carro("Chevrolet", "Tracker", "Branco") carro.ligar() carro.desligar() carro.exibirInformacoes()
[ 197, 198, 7718, 305, 796, 1879, 305, 7203, 7376, 85, 33087, 1600, 366, 35694, 1600, 366, 33, 2596, 1073, 4943, 198, 7718, 305, 13, 4604, 283, 3419, 198, 7718, 305, 13, 8906, 4604, 283, 3419, 198, 7718, 305, 13, 1069, 571, 343, 818, ...
2.229167
48
from pathlib import Path import sqlite3 from matplotlib import pyplot as plt from process_meteo_data import setup_db_connection, EXPORTS_FOLDER connection, cursor = setup_db_connection() data = cursor.execute(f'SELECT * FROM temperatures LIMIT 100;').fetchall() _, date, temp = list(zip(*data)) plt.plot(temp) plt.savefig(EXPORTS_FOLDER + '/' + "temp.png") plt.show()
[ 6738, 3108, 8019, 1330, 10644, 198, 11748, 44161, 578, 18, 198, 198, 6738, 2603, 29487, 8019, 1330, 12972, 29487, 355, 458, 83, 198, 198, 6738, 1429, 62, 4164, 68, 78, 62, 7890, 1330, 9058, 62, 9945, 62, 38659, 11, 25703, 33002, 62, ...
2.80597
134
from xpybuild.propertysupport import * from xpybuild.buildcommon import * from xpybuild.pathsets import * from xpybuild.targets.java import * import logging Javac('${OUTPUT_DIR}/test-source-target/', ['./Simple.java'], []).option('javac.source', '7').option('javac.target', '8')
[ 6738, 2124, 9078, 11249, 13, 26745, 11284, 1330, 1635, 198, 6738, 2124, 9078, 11249, 13, 11249, 11321, 1330, 1635, 198, 6738, 2124, 9078, 11249, 13, 6978, 28709, 1330, 1635, 198, 198, 6738, 2124, 9078, 11249, 13, 83, 853, 1039, 13, 1235...
2.81
100
"""Test the gopkg module.""" from ghmonitor.gopkg.translate import get_repo_from_random_urn, translate, GITHUB_REPO_RE def test_get_repo_urn(): """Test the function. Be careful though, it requires an Internet access.""" assert 'kubernetes/metrics' == get_repo_from_random_urn('k8s.io/metrics') assert get_repo_from_random_urn('seznam.cz') is None def test_github_re(): """Test the regular expression.""" assert GITHUB_REPO_RE.match('bitbucket.com/user/repo') is None m = GITHUB_REPO_RE.match('github.com/user/project') assert m.group('user') == 'user' assert m.group('repo') == 'project' m = GITHUB_REPO_RE.match('github.com/user/project/folder') assert m.group('user') == 'user' assert m.group('repo') == 'project' def test_translate(): """Test the translation. Again, needs Internet access.""" assert 'kubernetes/metrics' == translate('k8s.io/metrics') assert 'user/project' == translate('github.com/user/project') assert translate('launchpad.net/project') is None
[ 37811, 14402, 262, 308, 404, 10025, 8265, 526, 15931, 198, 198, 6738, 24997, 41143, 13, 70, 404, 10025, 13, 7645, 17660, 1330, 651, 62, 260, 7501, 62, 6738, 62, 25120, 62, 700, 11, 15772, 11, 402, 10554, 10526, 62, 2200, 16402, 62, ...
2.685714
385
import mailer as m import consoleLogger as cl import fileLogger as fl ''' Created by: Richard Payne Created on: 05/08/17 Desc: Takes string from connection and extracts username, password and IP address of the attempted login. '''
[ 11748, 6920, 263, 355, 285, 201, 198, 11748, 8624, 11187, 1362, 355, 537, 201, 198, 11748, 2393, 11187, 1362, 355, 781, 201, 198, 201, 198, 201, 198, 7061, 6, 201, 198, 41972, 416, 25, 6219, 32788, 201, 198, 41972, 319, 25, 8870, 14...
2.847826
92
from django.urls import path from . import views from .views import ( SearchsProductView ) app_name = 'shop' urlpatterns = [ #path('', views.index, name='index'), path('', views.product_list, name='product_list'), path('shop/', views.product_list, name='product_list'), path('addtocartform/', views.addtocartform, name='addtocartform'), path('search/', SearchsProductView.as_view(), name='query'), path('<slug:category_slug>/', views.product_list, name='product_list_by_category'), path('<int:id>/<slug:slug>/', views.product_detail, name='product_detail'), ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 6738, 764, 1330, 5009, 198, 6738, 764, 33571, 1330, 357, 198, 220, 220, 220, 11140, 82, 15667, 7680, 198, 8, 628, 198, 1324, 62, 3672, 796, 705, 24643, 6, 198, 198, 6371, 33279, 82,...
2.723982
221
from planner import * from othertools import * import matplotlib.pyplot as plt if __name__ == "__main__": main()
[ 6738, 42351, 1330, 1635, 198, 6738, 584, 31391, 1330, 1635, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1388, 3419, 198 ]
2.926829
41
#pylint: disable=C0114 from livechat.customer.rtm.client import CustomerRTM from livechat.customer.web.client import CustomerWeb
[ 2, 79, 2645, 600, 25, 15560, 28, 34, 486, 1415, 198, 6738, 2107, 17006, 13, 23144, 263, 13, 17034, 76, 13, 16366, 1330, 22092, 14181, 44, 198, 6738, 2107, 17006, 13, 23144, 263, 13, 12384, 13, 16366, 1330, 22092, 13908, 198 ]
3.146341
41
import os import shutil from logging import getLogger from pathlib import Path from shutil import copyfile import git import requests from ogr.services.pagure import PagureService logger = getLogger(__name__) work_dir = Path("/tmp/playground") readme_path = Path(__file__).parent / "README.md" service = PagureService( token=os.getenv("PAGURE_TOKEN"), instance_url="https://git.stg.centos.org/" ) if __name__ == "__main__": if not work_dir.is_dir(): logger.warning("Your work_dir is missing.") page = "https://git.stg.centos.org/api/0/projects?namespace=source-git&short=true" i = 0 while True: logger.info(page) r = requests.get(page) for p in r.json()["projects"]: AddMasterBranch(p["name"]).run() page = r.json()["pagination"]["next"] if not page: break i = i + 1
[ 11748, 28686, 198, 11748, 4423, 346, 198, 6738, 18931, 1330, 651, 11187, 1362, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 4423, 346, 1330, 4866, 7753, 198, 198, 11748, 17606, 198, 11748, 7007, 198, 198, 6738, 267, 2164, 13, 30416, 1...
2.368564
369
""" 86. Binary Search Tree Iterator https://www.lintcode.com/problem/binary-search-tree-iterator/description the difference between this method and the standard method is: if one has right subtree, it no longer keep itself in the stack. so when taken out of the stack, it does not need to make extra step to remove itself. the downside of this simplified method is it is not appliable to find kth closest member in a binary tree (maybe?) """ """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None Example of iterate a tree: iterator = BSTIterator(root) while iterator.hasNext(): node = iterator.next() do something for node """ class BSTIterator: """ @param: root: The root of binary tree. """ """ @return: True if there has next node, or false """ """ @return: return next node """
[ 37811, 198, 4521, 13, 45755, 11140, 12200, 40806, 1352, 198, 5450, 1378, 2503, 13, 75, 600, 8189, 13, 785, 14, 45573, 14, 39491, 12, 12947, 12, 21048, 12, 48727, 14, 11213, 198, 198, 1169, 3580, 1022, 428, 2446, 290, 262, 3210, 2446, ...
3.143836
292
"""切り替え用 settings ファイル base.py をベースに上書きする. """ from .base import * DEBUG = False ALLOWED_HOSTS = ['*'] STATIC_URL = '/apis-service-center/app/static/'
[ 37811, 26344, 229, 28255, 162, 249, 123, 2515, 230, 18796, 101, 6460, 14524, 243, 25362, 11482, 9202, 198, 198, 8692, 13, 9078, 17433, 240, 35604, 6312, 8943, 28618, 41468, 162, 249, 116, 33778, 33623, 25748, 13, 198, 37811, 198, 6738, ...
1.888889
81