code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class ASettingsWindow(QFrame): <NEW_LINE> <INDENT> def __init__(self, internalModel, console, outputConsole, parent=None): <NEW_LINE> <INDENT> super(ASettingsWindow, self).__init__(parent) <NEW_LINE> self._internalModel = internalModel <NEW_LINE> self._console = console <NEW_LINE> self._compSettingsFrame = AComputationSettingsFrame(internalModel, console, outputConsole) <NEW_LINE> self._runFrame = ARunFrame(internalModel, console, outputConsole) <NEW_LINE> self._configureLayout(QHBoxLayout()) <NEW_LINE> <DEDENT> def _configureLayout(self, layout): <NEW_LINE> <INDENT> self.setFrameStyle(QFrame.Panel) <NEW_LINE> self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) <NEW_LINE> splitter = QSplitter() <NEW_LINE> splitter.addWidget(self._compSettingsFrame) <NEW_LINE> splitter.addWidget(self._runFrame) <NEW_LINE> splitter.setCollapsible(0, False) <NEW_LINE> splitter.setCollapsible(1, False) <NEW_LINE> splitter.setStretchFactor(0, 1) <NEW_LINE> splitter.setStretchFactor(1, 3) <NEW_LINE> layout.addWidget(splitter) <NEW_LINE> self.setLayout(layout)
Main container for the output settings and run.
6259903e1d351010ab8f4d74
class IgpProvider: <NEW_LINE> <INDENT> def __init__(self, problem): <NEW_LINE> <INDENT> self._problem = problem <NEW_LINE> self._sp_data = {} <NEW_LINE> self._bgp_next_hop_data = {} <NEW_LINE> self._border_routers = [r.assigned_node for r in problem.bgp_config.border_routers] <NEW_LINE> self._components = [-1]*self._problem.nof_nodes <NEW_LINE> self._static_route_data = {} <NEW_LINE> for sr in problem.static_routes: <NEW_LINE> <INDENT> if sr.dst not in self._static_route_data: <NEW_LINE> <INDENT> self._static_route_data[sr.dst] = {} <NEW_LINE> <DEDENT> self._static_route_data[sr.dst][sr.u] = sr.v <NEW_LINE> <DEDENT> <DEDENT> def recompute(self): <NEW_LINE> <INDENT> self._bgp_next_hop_data.clear() <NEW_LINE> for br in self._border_routers: <NEW_LINE> <INDENT> self._sp_data[br] = nx.single_source_dijkstra(self._problem.G, br, weight='weight') <NEW_LINE> <DEDENT> connected_comp = nx.strongly_connected_components(self._problem.G) <NEW_LINE> id = 0 <NEW_LINE> for comp in connected_comp: <NEW_LINE> <INDENT> for r in comp: <NEW_LINE> <INDENT> self._components[r] = id <NEW_LINE> <DEDENT> id += 1 <NEW_LINE> <DEDENT> pass <NEW_LINE> <DEDENT> def update_bgp_next_hops(self, destination: str, next_hop_data): <NEW_LINE> <INDENT> self._bgp_next_hop_data[destination] = next_hop_data <NEW_LINE> <DEDENT> def get_igp_cost(self, u: int, v: int) -> int: <NEW_LINE> <INDENT> return self._sp_data[v][0][u] <NEW_LINE> <DEDENT> def is_reachable(self, u: int, v: int) -> bool: <NEW_LINE> <INDENT> return self._components[u] == self._components[v] <NEW_LINE> <DEDENT> def get_a_shortest_path(self, u: int, v: int) -> list: <NEW_LINE> <INDENT> return self._sp_data[v][1][u] <NEW_LINE> <DEDENT> def get_bgp_next_hop(self, u: int, dst: str): <NEW_LINE> <INDENT> return self._bgp_next_hop_data[dst][u] <NEW_LINE> <DEDENT> def get_static_route_at(self, u: int, dst: str): <NEW_LINE> <INDENT> if dst in self._static_route_data and u in self._static_route_data[dst]: <NEW_LINE> <INDENT> return self._static_route_data[dst][u] <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def get_next_routers_shortest_paths(self, u: int, v: int): <NEW_LINE> <INDENT> l = [] <NEW_LINE> for neigh in self._problem.G.neighbors(u): <NEW_LINE> <INDENT> w = self._problem.get_weight_for_edge(u, neigh) <NEW_LINE> if self._sp_data[v][0][neigh] + w == self._sp_data[v][0][u]: <NEW_LINE> <INDENT> l.append(neigh) <NEW_LINE> <DEDENT> <DEDENT> return l
Provider for IGP costs.
6259903e3c8af77a43b68867
class LinkedReference(Reference): <NEW_LINE> <INDENT> def _deserialize(self, value, attr, data): <NEW_LINE> <INDENT> if isinstance(value, dict): <NEW_LINE> <INDENT> value = value.get('id') <NEW_LINE> if not value: <NEW_LINE> <INDENT> raise ValidationError("Champ 'id' manquant") <NEW_LINE> <DEDENT> <DEDENT> return super()._deserialize(value, attr, data) <NEW_LINE> <DEDENT> def _serialize(self, value, attr, obj): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> return missing <NEW_LINE> <DEDENT> dump = {'id': str(getattr(value, 'pk', value.id))} <NEW_LINE> if hasattr(value, 'get_links'): <NEW_LINE> <INDENT> links = value.get_links() <NEW_LINE> if links: <NEW_LINE> <INDENT> dump['_links'] = links <NEW_LINE> <DEDENT> <DEDENT> return dump
Marshmallow custom field to map with :class Mongoengine.Reference:
6259903e24f1403a926861f8
class Adapter(object): <NEW_LINE> <INDENT> msg_type_map: Dict[str, str] = {} <NEW_LINE> def update_header(self, msg: Dict[str, Any]) -> Dict[str, Any]: <NEW_LINE> <INDENT> return msg <NEW_LINE> <DEDENT> def update_metadata(self, msg: Dict[str, Any]) -> Dict[str, Any]: <NEW_LINE> <INDENT> return msg <NEW_LINE> <DEDENT> def update_msg_type(self, msg: Dict[str, Any]) -> Dict[str, Any]: <NEW_LINE> <INDENT> header = msg["header"] <NEW_LINE> msg_type = header["msg_type"] <NEW_LINE> if msg_type in self.msg_type_map: <NEW_LINE> <INDENT> msg["msg_type"] = header["msg_type"] = self.msg_type_map[msg_type] <NEW_LINE> <DEDENT> return msg <NEW_LINE> <DEDENT> def handle_reply_status_error(self, msg: Dict[str, Any]) -> Dict[str, Any]: <NEW_LINE> <INDENT> return msg <NEW_LINE> <DEDENT> def __call__(self, msg: Dict[str, Any]): <NEW_LINE> <INDENT> msg = self.update_header(msg) <NEW_LINE> msg = self.update_metadata(msg) <NEW_LINE> msg = self.update_msg_type(msg) <NEW_LINE> header = msg["header"] <NEW_LINE> handler = getattr(self, header["msg_type"], None) <NEW_LINE> if handler is None: <NEW_LINE> <INDENT> return msg <NEW_LINE> <DEDENT> if msg["content"].get("status", None) in {"error", "aborted"}: <NEW_LINE> <INDENT> return self.handle_reply_status_error(msg) <NEW_LINE> <DEDENT> return handler(msg)
Base class for adapting messages Override message_type(msg) methods to create adapters.
6259903e287bf620b6272e43
class TestGithubGetReleasesByRepo: <NEW_LINE> <INDENT> def test_get_releases_by_repo(self): <NEW_LINE> <INDENT> releases_wanted = [ ('debtool_0.2.5_all.deb', 62), ('debtool_0.2.4_all.deb', 5), ('debtool_0.2.1_all.deb', 0), ('debtool_0.2.2_all.deb', 0), ('debtool_0.2.3_all.deb', 2) ] <NEW_LINE> with requests_mock.Mocker() as mock: <NEW_LINE> <INDENT> mock.get('https://api.github.com/repos/brbsix/debtool/releases', text=read('debtool_releases')) <NEW_LINE> releases = list( gdc.Github().get_releases_by_repo('brbsix', 'debtool') ) <NEW_LINE> <DEDENT> assert releases == releases_wanted <NEW_LINE> <DEDENT> def test_get_releases_by_repo_for_repo_without_releases(self): <NEW_LINE> <INDENT> with requests_mock.Mocker() as mock: <NEW_LINE> <INDENT> mock.get('https://api.github.com/repos/brbsix/craigslist/releases', text='[]') <NEW_LINE> releases = list( gdc.Github().get_releases_by_repo('brbsix', 'craigslist') ) <NEW_LINE> <DEDENT> assert releases == []
Test Github class get_releases_by_repo method.
6259903e21a7993f00c671c5
class Encoder(nn.Module): <NEW_LINE> <INDENT> def __init__( self, n_src_vocab, n_max_seq, n_layers=3, n_head=3, d_k=64, d_v=64, d_word_vec=128, d_model=128, d_inner_hid=128, dropout=0.8): <NEW_LINE> <INDENT> super(Encoder, self).__init__() <NEW_LINE> n_position = n_max_seq + 1 <NEW_LINE> self.n_max_seq = n_max_seq <NEW_LINE> self.d_model = d_model <NEW_LINE> self.position_enc = nn.Embedding(n_position, d_word_vec, padding_idx=Constants_PAD) <NEW_LINE> self.position_enc.weight.data = position_encoding_init(n_position, d_word_vec) <NEW_LINE> self.src_word_emb = nn.Embedding(n_src_vocab, d_word_vec, padding_idx=Constants_PAD) <NEW_LINE> self.layer_stack = nn.ModuleList([ EncoderLayer(d_model, d_inner_hid, n_head, d_k, d_v, dropout=dropout) for _ in range(n_layers)]) <NEW_LINE> self.output=nn.Linear(800*128,19) <NEW_LINE> <DEDENT> def forward(self,src_seq,src_pos,return_attns=False): <NEW_LINE> <INDENT> enc_input = self.src_word_emb(src_seq) <NEW_LINE> enc_input += self.position_enc(src_pos) <NEW_LINE> if return_attns: <NEW_LINE> <INDENT> enc_slf_attns = [] <NEW_LINE> <DEDENT> enc_output = enc_input <NEW_LINE> enc_slf_attn_mask = get_attn_padding_mask(src_seq, src_seq) <NEW_LINE> for enc_layer in self.layer_stack: <NEW_LINE> <INDENT> enc_output, enc_slf_attn = enc_layer( enc_output, slf_attn_mask=enc_slf_attn_mask) <NEW_LINE> if return_attns: <NEW_LINE> <INDENT> enc_slf_attns += [enc_slf_attn] <NEW_LINE> <DEDENT> <DEDENT> enc_output=self.output(enc_output.view(-1,800*128)) <NEW_LINE> enc_output=F.log_softmax(enc_output, dim=1) <NEW_LINE> if return_attns: <NEW_LINE> <INDENT> return enc_output, enc_slf_attns <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return enc_output
A encoder model with self attention mechanism.
6259903ed4950a0f3b11176c
class Track: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.root = None <NEW_LINE> <DEDENT> def track(self, value): <NEW_LINE> <INDENT> if self.root: <NEW_LINE> <INDENT> self.insert_bst(value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.root = Node(value) <NEW_LINE> <DEDENT> <DEDENT> def insert_bst(self, value): <NEW_LINE> <INDENT> node = self.root <NEW_LINE> while True: <NEW_LINE> <INDENT> if value < node.value: <NEW_LINE> <INDENT> node.left_len += 1 <NEW_LINE> if node.left: <NEW_LINE> <INDENT> node = node.left <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> node.left = Node(value) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> node.right_len += 1 <NEW_LINE> if node.right: <NEW_LINE> <INDENT> node = node.right <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> node.right = Node(value) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def get_rank(self, value): <NEW_LINE> <INDENT> node = self.root <NEW_LINE> rank = 0 <NEW_LINE> while node.value != value: <NEW_LINE> <INDENT> if value >= node.value: <NEW_LINE> <INDENT> rank = rank + node.left_len <NEW_LINE> rank = rank + 1 <NEW_LINE> node = node.right <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> node = node.left <NEW_LINE> <DEDENT> <DEDENT> return rank + node.left_len
Class to keep a track of each incoming number.
6259903ed6c5a102081e337d
class Topping(): <NEW_LINE> <INDENT> def __init__(self, name, price=1.00): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.price = price <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "{} ${:,.2f}".format(self.name, self.price)
What goes on a pizza
6259903e8c3a8732951f77af
class InformeCuotaSostenimientoPeriodo(Report): <NEW_LINE> <INDENT> __name__ = 'cooperar-informes.informe_cuotasostenimientoperiodo' <NEW_LINE> @classmethod <NEW_LINE> def resumir_datos_clientes(cls, facturadomes, facturadoanio): <NEW_LINE> <INDENT> Asociadas = Pool().get('party.party') <NEW_LINE> asociadas = Asociadas.search([('asociada', '=', True)]) <NEW_LINE> CuotasAsociada = Pool().get('asociadas.cuota') <NEW_LINE> Tuplas_Asociadas = [] <NEW_LINE> total_mes = 0 <NEW_LINE> tipo_factura = '' <NEW_LINE> for asociada in asociadas: <NEW_LINE> <INDENT> if asociada.iva_condition == 'responsable_inscripto': <NEW_LINE> <INDENT> tipo_factura = 'A' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tipo_factura = 'B' <NEW_LINE> <DEDENT> cuota_paga = CuotasAsociada.search([('asociada', '=', asociada), ('mes', '=', facturadomes), ('anio', '=', facturadoanio), ('pagada', '=', True)]) <NEW_LINE> if cuota_paga: <NEW_LINE> <INDENT> total_mes += cuota_paga[0].monto <NEW_LINE> Tuplas_Asociadas.append((asociada.name, str(asociada.monto_actual_cuota), tipo_factura, str(cuota_paga[0].monto))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> Tuplas_Asociadas.append((asociada.name, str(asociada.monto_actual_cuota), tipo_factura, '0')) <NEW_LINE> <DEDENT> <DEDENT> return Tuplas_Asociadas <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_total_mes(cls, facturadomes, facturadoanio): <NEW_LINE> <INDENT> Asociadas = Pool().get('party.party') <NEW_LINE> asociadas = Asociadas.search([('asociada', '=', True)]) <NEW_LINE> CuotasAsociada = Pool().get('asociadas.cuota') <NEW_LINE> total_mes = 0 <NEW_LINE> for asociada in asociadas: <NEW_LINE> <INDENT> cuota_paga = CuotasAsociada.search([('asociada', '=', asociada), ('mes', '=', facturadomes), ('anio', '=', facturadoanio), ('pagada', '=', True)]) <NEW_LINE> if cuota_paga: <NEW_LINE> <INDENT> total_mes += cuota_paga[0].monto <NEW_LINE> <DEDENT> <DEDENT> return total_mes <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def parse (cls, report, objects, data, localcontext): <NEW_LINE> <INDENT> tuplas = [] <NEW_LINE> tuplas = cls.resumir_datos_clientes(data['facturadomes'],data['facturadoanio']) <NEW_LINE> total_mes = cls.get_total_mes(data['facturadomes'],data['facturadoanio']) <NEW_LINE> data['total_mes'] = str(total_mes) <NEW_LINE> return super(InformeCuotaSostenimientoPeriodo,cls).parse(report,tuplas,data,localcontext)
Reportes de Cuotas Sostenimiento por Periodo
6259903e596a897236128eda
class sector_DDD_employment_within_DDD_minutes_travel_time_hbw_am_transit_walk(abstract_access_within_threshold_variable): <NEW_LINE> <INDENT> def __init__(self, sector, threshold): <NEW_LINE> <INDENT> self.threshold = threshold <NEW_LINE> self.travel_data_attribute = "travel_data.am_total_transit_time_walk" <NEW_LINE> self.zone_attribute_to_access = "urbansim.zone.number_of_jobs_of_sector_" + str(sector) <NEW_LINE> abstract_access_within_threshold_variable.__init__(self)
total number of sector DDD jobs for zones within DDD minutes travel time
6259903e8a43f66fc4bf33e8
class EmptyData(Error): <NEW_LINE> <INDENT> pass
is raised within certain protocols to signify a request was successful but yielded no data.
6259903e26238365f5faddb0
class JobPlacement(_messages.Message): <NEW_LINE> <INDENT> clusterName = _messages.StringField(1) <NEW_LINE> clusterUuid = _messages.StringField(2)
Cloud Dataproc job configuration. Fields: clusterName: [Required] The name of the cluster where the job will be submitted. clusterUuid: [Output-only] A cluster UUID generated by the Dataproc service when the job is submitted.
6259903e8e05c05ec3f6f787
class UELCCaseQuizModuleFactory(object): <NEW_LINE> <INDENT> def __init__(self, hname, base_url): <NEW_LINE> <INDENT> hierarchy = HierarchyFactory(name=hname, base_url=base_url) <NEW_LINE> root = hierarchy.get_root() <NEW_LINE> root.add_child_section_from_dict( {'label': "One", 'slug': "one", 'children': [{'label': "Three", 'slug': "introduction"}]}) <NEW_LINE> root.add_child_section_from_dict({'label': "Two", 'slug': "two"}) <NEW_LINE> r = FakeReq() <NEW_LINE> r.POST = {'description': 'description', 'rhetorical': 'rhetorical', 'allow_redo': True, 'show_submit_state': False} <NEW_LINE> casequiz = CaseQuiz.create(r) <NEW_LINE> blocks = [{'label': 'Welcome to your new Forest Site', 'css_extra': '', 'block_type': 'Test Block', 'body': 'You should now use the edit link to add content'}] <NEW_LINE> root.add_child_section_from_dict({'label': 'Four', 'slug': 'four', 'pageblocks': blocks}) <NEW_LINE> root.add_child_section_from_dict(casequiz.as_dict()) <NEW_LINE> self.root = root
Stealing module factory from pagetree factories to adapt for casequiz tests
6259903e73bcbd0ca4bcb4e3
class tempfile(object): <NEW_LINE> <INDENT> def __init__(self, unique_id, suffix='', prefix='', dir=None, text=False): <NEW_LINE> <INDENT> suffix = unique_id + suffix <NEW_LINE> prefix = prefix + _TEMPLATE <NEW_LINE> self.fd, self.name = module_tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir, text=text) <NEW_LINE> self.fo = os.fdopen(self.fd) <NEW_LINE> <DEDENT> def clean(self): <NEW_LINE> <INDENT> if self.fo: <NEW_LINE> <INDENT> self.fo.close() <NEW_LINE> <DEDENT> if self.name and os.path.exists(self.name): <NEW_LINE> <INDENT> os.remove(self.name) <NEW_LINE> <DEDENT> self.fd = self.fo = self.name = None <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.name is not None: <NEW_LINE> <INDENT> logging.debug('Clean was not called for ' + self.name) <NEW_LINE> self.clean() <NEW_LINE> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> msg = 'An exception occurred while calling the destructor' <NEW_LINE> logging.exception(msg) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> pass
A wrapper for tempfile.mkstemp @param unique_id: required, a unique string to help identify what part of code created the tempfile. @var name: The name of the temporary file. @var fd: the file descriptor of the temporary file that was created. @return a tempfile object example usage: t = autotemp.tempfile(unique_id='fig') t.name # name of file t.fd # file descriptor t.fo # file object t.clean() # clean up after yourself
6259903e10dbd63aa1c71e30
class ProtocolScoreEnum(Enum): <NEW_LINE> <INDENT> SSLv20 = 0 <NEW_LINE> SSLv30 = 80 <NEW_LINE> TLSv10 = 90 <NEW_LINE> TLSv11 = 95 <NEW_LINE> TLSv12 = 100
1) Protocol support: SSL 2.0: 0 **V** SSL 3.0: 80 **V** TLS 1.0: 90 **V** TLS 1.1: 95 **V** TLS 1.2: 100 **V** Total score: best protocol score + worst protocol score, divided by 2.
6259903e8e71fb1e983bcd26
class FigureManagerWx(FigureManagerBase): <NEW_LINE> <INDENT> def __init__(self, canvas, num, frame): <NEW_LINE> <INDENT> DEBUG_MSG("__init__()", 1, self) <NEW_LINE> FigureManagerBase.__init__(self, canvas, num) <NEW_LINE> self.frame = frame <NEW_LINE> self.window = frame <NEW_LINE> self.tb = frame.GetToolBar() <NEW_LINE> self.toolbar = self.tb <NEW_LINE> def notify_axes_change(fig): <NEW_LINE> <INDENT> if self.tb is not None: <NEW_LINE> <INDENT> self.tb.update() <NEW_LINE> <DEDENT> <DEDENT> self.canvas.figure.add_axobserver(notify_axes_change) <NEW_LINE> <DEDENT> def show(self): <NEW_LINE> <INDENT> self.frame.Show() <NEW_LINE> <DEDENT> def destroy(self, *args): <NEW_LINE> <INDENT> DEBUG_MSG("destroy()", 1, self) <NEW_LINE> self.frame.Destroy() <NEW_LINE> wxapp = wx.GetApp() <NEW_LINE> if wxapp: <NEW_LINE> <INDENT> wxapp.Yield() <NEW_LINE> <DEDENT> <DEDENT> def get_window_title(self): <NEW_LINE> <INDENT> return self.window.GetTitle() <NEW_LINE> <DEDENT> def set_window_title(self, title): <NEW_LINE> <INDENT> self.window.SetTitle(title) <NEW_LINE> <DEDENT> def resize(self, width, height): <NEW_LINE> <INDENT> self.canvas.SetInitialSize(wx.Size(width, height)) <NEW_LINE> self.window.GetSizer().Fit(self.window)
This class contains the FigureCanvas and GUI frame It is instantiated by GcfWx whenever a new figure is created. GcfWx is responsible for managing multiple instances of FigureManagerWx. public attrs canvas - a FigureCanvasWx(wx.Panel) instance window - a wxFrame instance - wxpython.org/Phoenix/docs/html/Frame.html
6259903e45492302aabfd733
class FeedbackListView(AdminUserRequiredMixin, generic.ListView): <NEW_LINE> <INDENT> model = Feedback <NEW_LINE> template_name = 'myadmin/feedback_list.html' <NEW_LINE> context_object_name = 'feedback_list' <NEW_LINE> paginate_by = 10 <NEW_LINE> q = '' <NEW_LINE> def get_context_data(self, *, object_list=None, **kwargs): <NEW_LINE> <INDENT> context = super(FeedbackListView, self).get_context_data(**kwargs) <NEW_LINE> paginator = context.get('paginator') <NEW_LINE> page = context.get('page_obj') <NEW_LINE> page_list = get_page_list(paginator, page) <NEW_LINE> context['page_list'] = page_list <NEW_LINE> context['q'] = self.q <NEW_LINE> return context <NEW_LINE> <DEDENT> def get_queryset(self): <NEW_LINE> <INDENT> self.q = self.request.GET.get("q", "") <NEW_LINE> return Feedback.objects.filter(content__contains=self.q).order_by('-timestamp')
反馈信息
6259903e287bf620b6272e45
class RectangleGenerator: <NEW_LINE> <INDENT> def __init__(self, min_rect_rel_square=0.3, max_rect_rel_square=1): <NEW_LINE> <INDENT> self.min_rect_rel_square = min_rect_rel_square <NEW_LINE> self.max_rect_rel_square = max_rect_rel_square <NEW_LINE> <DEDENT> def gen_coordinates(self, width, height): <NEW_LINE> <INDENT> x1, x2 = np.random.randint(0, width, 2) <NEW_LINE> y1, y2 = np.random.randint(0, height, 2) <NEW_LINE> x1, x2 = min(x1, x2), max(x1, x2) <NEW_LINE> y1, y2 = min(y1, y2), max(y1, y2) <NEW_LINE> return int(x1), int(y1), int(x2), int(y2) <NEW_LINE> <DEDENT> def __call__(self, batch): <NEW_LINE> <INDENT> batch_size, num_channels, width, height = batch.shape <NEW_LINE> mask = torch.zeros_like(batch) <NEW_LINE> for i in range(batch_size): <NEW_LINE> <INDENT> x1, y1, x2, y2 = self.gen_coordinates(width, height) <NEW_LINE> sqr = width * height <NEW_LINE> while not (self.min_rect_rel_square * sqr <= (x2 - x1 + 1) * (y2 - y1 + 1) <= self.max_rect_rel_square * sqr): <NEW_LINE> <INDENT> x1, y1, x2, y2 = self.gen_coordinates(width, height) <NEW_LINE> <DEDENT> mask[i, :, x1: x2 + 1, y1: y2 + 1] = 1 <NEW_LINE> <DEDENT> return mask
Generates for each object a mask where unobserved region is a rectangle which square divided by the image square is in interval [min_rect_rel_square, max_rect_rel_square].
6259903eb830903b9686eda6
class Coderack(object): <NEW_LINE> <INDENT> def __init__(self, max_capacity=10): <NEW_LINE> <INDENT> self._max_capacity = max_capacity <NEW_LINE> self._urgency_sum = 0 <NEW_LINE> self._codelet_count = 0 <NEW_LINE> self._codelets = set() <NEW_LINE> self._forced_next_codelet = None <NEW_LINE> <DEDENT> def CodeletCount(self): <NEW_LINE> <INDENT> return self._codelet_count <NEW_LINE> <DEDENT> def IsEmpty(self): <NEW_LINE> <INDENT> return self._codelet_count == 0 <NEW_LINE> <DEDENT> def GetCodelet(self): <NEW_LINE> <INDENT> if self._forced_next_codelet: <NEW_LINE> <INDENT> codelet = self._forced_next_codelet <NEW_LINE> self._RemoveCodelet(codelet) <NEW_LINE> self._forced_next_codelet = None <NEW_LINE> return codelet <NEW_LINE> <DEDENT> if self._codelet_count == 0: <NEW_LINE> <INDENT> raise CoderackEmptyException() <NEW_LINE> <DEDENT> random_urgency = random.uniform(0, self._urgency_sum) <NEW_LINE> for codelet in self._codelets: <NEW_LINE> <INDENT> if codelet.urgency >= random_urgency: <NEW_LINE> <INDENT> self._RemoveCodelet(codelet) <NEW_LINE> return codelet <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> random_urgency -= codelet.urgency <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def AddCodelet(self, codelet, *, msg="", parents=[]): <NEW_LINE> <INDENT> kLogger.debug('Codelet added: %s', str(codelet.family)) <NEW_LINE> if self._codelet_count == self._max_capacity: <NEW_LINE> <INDENT> self._ExpungeSomeCodelet() <NEW_LINE> <DEDENT> self._codelets.add(codelet) <NEW_LINE> self._codelet_count += 1 <NEW_LINE> self._urgency_sum += codelet.urgency <NEW_LINE> History.AddArtefact(codelet, ObjectType.CODELET, "Codelet %s %s" % (codelet.family.__name__, msg), parents) <NEW_LINE> <DEDENT> def ForceNextCodelet(self, codelet, *, forcer=None): <NEW_LINE> <INDENT> if codelet not in self._codelets: <NEW_LINE> <INDENT> raise FargError( 'Cannot mark a non-existant codelet as the next to retrieve.') <NEW_LINE> <DEDENT> self._forced_next_codelet = codelet <NEW_LINE> if forcer: <NEW_LINE> <INDENT> History.AddEvent(EventType.CODELET_FORCED, "Codelet forced to be next", [[codelet, ""], [forcer, "forcer"]]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> History.AddEvent(EventType.CODELET_FORCED, "Codelet forced to be next", [[codelet, ""]]) <NEW_LINE> <DEDENT> <DEDENT> def _RemoveCodelet(self, codelet): <NEW_LINE> <INDENT> self._codelets.remove(codelet) <NEW_LINE> self._codelet_count -= 1 <NEW_LINE> self._urgency_sum -= codelet.urgency <NEW_LINE> <DEDENT> def _ExpungeSomeCodelet(self): <NEW_LINE> <INDENT> codelet = random.choice(list(self._codelets)) <NEW_LINE> kLogger.info('Coderack over capacity: expunged codelet of family %s.' % codelet.family.__name__) <NEW_LINE> self._RemoveCodelet(codelet) <NEW_LINE> History.AddEvent(EventType.CODELET_FORCED, "Codelet expunged", [[codelet, ""]])
Implements the coderack --- the collection of codelets waiting to run. .. todo:: Choose the codelet to expunge based on a better criteria than uniformly randomly.
6259903e76d4e153a661dba0
class AbstractRefreshToken(models.Model): <NEW_LINE> <INDENT> id = models.BigAutoField(primary_key=True) <NEW_LINE> user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="%(app_label)s_%(class)s" ) <NEW_LINE> token = models.CharField(max_length=255) <NEW_LINE> application = models.ForeignKey( oauth2_settings.APPLICATION_MODEL, on_delete=models.CASCADE) <NEW_LINE> access_token = models.OneToOneField( oauth2_settings.ACCESS_TOKEN_MODEL, on_delete=models.SET_NULL, blank=True, null=True, related_name="refresh_token" ) <NEW_LINE> created = models.DateTimeField(auto_now_add=True) <NEW_LINE> updated = models.DateTimeField(auto_now=True) <NEW_LINE> revoked = models.DateTimeField(null=True) <NEW_LINE> def revoke(self): <NEW_LINE> <INDENT> access_token_model = get_access_token_model() <NEW_LINE> refresh_token_model = get_refresh_token_model() <NEW_LINE> with transaction.atomic(): <NEW_LINE> <INDENT> self = refresh_token_model.objects.filter( pk=self.pk, revoked__isnull=True ).select_for_update().first() <NEW_LINE> if not self: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> access_token_model.objects.get(id=self.access_token_id).revoke() <NEW_LINE> <DEDENT> except access_token_model.DoesNotExist: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.access_token = None <NEW_LINE> self.revoked = timezone.now() <NEW_LINE> self.save() <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.token <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> unique_together = ("token", "revoked",)
A RefreshToken instance represents a token that can be swapped for a new access token when it expires. Fields: * :attr:`user` The Django user representing resources' owner * :attr:`token` Token value * :attr:`application` Application instance * :attr:`access_token` AccessToken instance this refresh token is bounded to * :attr:`revoked` Timestamp of when this refresh token was revoked
6259903e4e696a045264e74e
class NoCorrespondingHandlingFunctionError(ValueError): <NEW_LINE> <INDENT> def __init__(self, event_type: Type[MessageEventObject]): <NEW_LINE> <INDENT> super().__init__(f"No corresponding message handling function of type {type(event_type)}")
Raised if no corresponding handling function for the message type.
6259903e23849d37ff852313
class TraceServerSpanObserver(TraceSpanObserver): <NEW_LINE> <INDENT> def __init__(self, service_name: str, hostname: str, span: Span, recorder: "Recorder"): <NEW_LINE> <INDENT> self.service_name = service_name <NEW_LINE> self.span = span <NEW_LINE> self.recorder = recorder <NEW_LINE> super().__init__(service_name, hostname, span, recorder) <NEW_LINE> <DEDENT> def on_start(self) -> None: <NEW_LINE> <INDENT> self.start = current_epoch_microseconds() <NEW_LINE> <DEDENT> def on_finish(self, exc_info: Optional[_ExcInfo]) -> None: <NEW_LINE> <INDENT> if exc_info and exc_info[0] is not None and issubclass(ServerTimeout, exc_info[0]): <NEW_LINE> <INDENT> self.on_set_tag("timed_out", True) <NEW_LINE> <DEDENT> super().on_finish(exc_info) <NEW_LINE> <DEDENT> def on_child_span_created(self, span: Span) -> None: <NEW_LINE> <INDENT> trace_observer: TraceSpanObserver <NEW_LINE> if isinstance(span, LocalSpan): <NEW_LINE> <INDENT> trace_observer = TraceLocalSpanObserver( self.service_name, typing.cast(str, span.component_name), self.hostname, span, self.recorder, ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> trace_observer = TraceSpanObserver( self.service_name, self.hostname, span, self.recorder ) <NEW_LINE> <DEDENT> span.register(trace_observer) <NEW_LINE> <DEDENT> def _serialize(self) -> Dict[str, Any]: <NEW_LINE> <INDENT> annotations: List[Dict[str, Any]] = [] <NEW_LINE> annotations.append( self._create_time_annotation( ANNOTATIONS["SERVER_RECEIVE"], typing.cast(int, self.start) ) ) <NEW_LINE> annotations.append( self._create_time_annotation(ANNOTATIONS["SERVER_SEND"], typing.cast(int, self.end)) ) <NEW_LINE> return self._to_span_obj(annotations, self.binary_annotations)
Span recording observer for incoming request spans. This observer implements the server-side span portion of a Zipkin request trace
6259903e1f5feb6acb163e4d
class Integration(Base): <NEW_LINE> <INDENT> def run(self): <NEW_LINE> <INDENT> message.print_welcome() <NEW_LINE> int_name = self.options['<name>'] <NEW_LINE> int_options = self.options['<option>'] <NEW_LINE> int_options = util.option_to_dict(int_options) <NEW_LINE> message.print_bold(int_name + " Integration with Options:") <NEW_LINE> for key, value in int_options.items(): <NEW_LINE> <INDENT> print(key, ": ", value) <NEW_LINE> <DEDENT> integration_class = None <NEW_LINE> try: <NEW_LINE> <INDENT> integration_class = getattr(importlib.import_module( "wavefront_cli.integrations"), int_name) <NEW_LINE> instance = integration_class(int_name, int_options) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> message.print_warn("Error: Unrecognized Integration: " + int_name) <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> if self.options['install']: <NEW_LINE> <INDENT> print("Action: install") <NEW_LINE> if not instance.install(): <NEW_LINE> <INDENT> instance.print_failure() <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> instance.print_success() <NEW_LINE> <DEDENT> <DEDENT> elif self.options['remove']: <NEW_LINE> <INDENT> print("Action: remove") <NEW_LINE> if not instance.remove(): <NEW_LINE> <INDENT> instance.print_failure() <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> instance.print_success() <NEW_LINE> <DEDENT> <DEDENT> system.restart_service("telegraf") <NEW_LINE> sys.exit(0)
Manage Integrations.
6259903eb57a9660fecd2cd5
class EmailOperator(BaseOperator): <NEW_LINE> <INDENT> template_fields = ('subject', 'html_content') <NEW_LINE> template_ext = ('.html',) <NEW_LINE> ui_color = '#e6faf9' <NEW_LINE> @apply_defaults <NEW_LINE> def __init__( self, to, subject, html_content, files=None, *args, **kwargs): <NEW_LINE> <INDENT> super(EmailOperator, self).__init__(*args, **kwargs) <NEW_LINE> self.to = to <NEW_LINE> self.subject = subject <NEW_LINE> self.html_content = html_content <NEW_LINE> self.files = files or [] <NEW_LINE> <DEDENT> def execute(self, context): <NEW_LINE> <INDENT> send_email(self.to, self.subject, self.html_content, files=self.files)
Sends an email. :param to: list of emails to send the email to :type to: list or string (comma or semicolon delimited) :param subject: subject line for the email (templated) :type subject: string :param html_content: content of the email (templated), html markup is allowed :type html_content: string :param files: file names to attach in email :type files: list
6259903e8a349b6b436874a0
class LinkCheckThread(threading.Thread): <NEW_LINE> <INDENT> def __init__(self, page, url, history, HTTPignore, day): <NEW_LINE> <INDENT> threading.Thread.__init__(self) <NEW_LINE> self.page = page <NEW_LINE> self.url = url <NEW_LINE> self.history = history <NEW_LINE> self.setName((u'%s - %s' % (page.title(), url)).encode('utf-8', 'replace')) <NEW_LINE> self.HTTPignore = HTTPignore <NEW_LINE> self.day = day <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> linkChecker = LinkChecker(self.url, HTTPignore=self.HTTPignore) <NEW_LINE> try: <NEW_LINE> <INDENT> ok, message = linkChecker.check() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pywikibot.output('Exception while processing URL %s in page %s' % (self.url, self.page.title())) <NEW_LINE> raise <NEW_LINE> <DEDENT> if ok: <NEW_LINE> <INDENT> if self.history.setLinkAlive(self.url): <NEW_LINE> <INDENT> pywikibot.output('*Link to %s in [[%s]] is back alive.' % (self.url, self.page.title())) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> pywikibot.output('*[[%s]] links to %s - %s.' % (self.page.title(), self.url, message)) <NEW_LINE> self.history.setLinkDead(self.url, message, self.page, self.day)
A thread responsible for checking one URL. After checking the page, it will die.
6259903e30dc7b76659a0a8c
@HOOKS.register_module() <NEW_LINE> class EMAHook(Hook): <NEW_LINE> <INDENT> def __init__(self, momentum=0.0002, interval=1, warm_up=100, resume_from=None): <NEW_LINE> <INDENT> assert isinstance(interval, int) and interval > 0 <NEW_LINE> self.warm_up = warm_up <NEW_LINE> self.interval = interval <NEW_LINE> assert momentum > 0 and momentum < 1 <NEW_LINE> self.momentum = momentum**interval <NEW_LINE> self.checkpoint = resume_from <NEW_LINE> <DEDENT> def before_run(self, runner): <NEW_LINE> <INDENT> model = runner.model <NEW_LINE> if is_module_wrapper(model): <NEW_LINE> <INDENT> model = model.module <NEW_LINE> <DEDENT> self.param_ema_buffer = {} <NEW_LINE> self.model_parameters = dict(model.named_parameters(recurse=True)) <NEW_LINE> for name, value in self.model_parameters.items(): <NEW_LINE> <INDENT> buffer_name = f"ema_{name.replace('.', '_')}" <NEW_LINE> self.param_ema_buffer[name] = buffer_name <NEW_LINE> model.register_buffer(buffer_name, value.data.clone()) <NEW_LINE> <DEDENT> self.model_buffers = dict(model.named_buffers(recurse=True)) <NEW_LINE> if self.checkpoint is not None: <NEW_LINE> <INDENT> runner.resume(self.checkpoint) <NEW_LINE> <DEDENT> <DEDENT> def after_train_iter(self, runner): <NEW_LINE> <INDENT> curr_step = runner.iter <NEW_LINE> momentum = min(self.momentum, (1 + curr_step) / (self.warm_up + curr_step)) <NEW_LINE> if curr_step % self.interval != 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for name, parameter in self.model_parameters.items(): <NEW_LINE> <INDENT> buffer_name = self.param_ema_buffer[name] <NEW_LINE> buffer_parameter = self.model_buffers[buffer_name] <NEW_LINE> buffer_parameter.mul_(1 - momentum).add_(momentum, parameter.data) <NEW_LINE> <DEDENT> <DEDENT> def after_train_epoch(self, runner): <NEW_LINE> <INDENT> self._swap_ema_parameters() <NEW_LINE> <DEDENT> def before_train_epoch(self, runner): <NEW_LINE> <INDENT> self._swap_ema_parameters() <NEW_LINE> <DEDENT> def _swap_ema_parameters(self): <NEW_LINE> <INDENT> for name, value in self.model_parameters.items(): <NEW_LINE> <INDENT> temp = value.data.clone() <NEW_LINE> ema_buffer = self.model_buffers[self.param_ema_buffer[name]] <NEW_LINE> value.data.copy_(ema_buffer.data) <NEW_LINE> ema_buffer.data.copy_(temp)
Exponential Moving Average Hook. Use Exponential Moving Average on all parameters of model in training process. All parameters have a ema backup, which update by the formula as below. EMAHook takes priority over EvalHook and CheckpointSaverHook. .. math:: \text{Xema_{t+1}} = (1 - \text{momentum}) \times \text{Xema_{t}} + \text{momentum} \times X_t Args: momentum (float): The momentum used for updating ema parameter. Defaults to 0.0002. interval (int): Update ema parameter every interval iteration. Defaults to 1. warm_up (int): During first warm_up steps, we may use smaller momentum to update ema parameters more slowly. Defaults to 100. resume_from (str): The checkpoint path. Defaults to None.
6259903ed10714528d69efb9
class JType(XMLString): <NEW_LINE> <INDENT> types = {"int", "char", "boolean"} <NEW_LINE> def __init__(self, tokens: list[Token]) -> None: <NEW_LINE> <INDENT> token = tokens.pop() <NEW_LINE> if token.name == "keyword": <NEW_LINE> <INDENT> assert token.value in self.types <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert token.name == "identifier" <NEW_LINE> <DEDENT> self.singe_content = token <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return str(self.singe_content)
'int' | 'char' | 'boolean' | className
6259903e94891a1f408ba024
class DeviceEndpoint(RestEndpoint): <NEW_LINE> <INDENT> ENDPOINT_PATH = "/api/devices/{device_id}" <NEW_LINE> async def get(self, device_id) -> web.Response: <NEW_LINE> <INDENT> device = self.ledfx.devices.get(device_id) <NEW_LINE> if device is None: <NEW_LINE> <INDENT> response = { 'not found': 404 } <NEW_LINE> return web.Response(text=json.dumps(response), status=404) <NEW_LINE> <DEDENT> response = device.config <NEW_LINE> return web.Response(text=json.dumps(response), status=200) <NEW_LINE> <DEDENT> async def put(self, device_id, request) -> web.Response: <NEW_LINE> <INDENT> device = self.ledfx.devices.get(device_id) <NEW_LINE> if device is None: <NEW_LINE> <INDENT> response = { 'not found': 404 } <NEW_LINE> return web.Response(text=json.dumps(response), status=404) <NEW_LINE> <DEDENT> data = await request.json() <NEW_LINE> device_config = data.get('config') <NEW_LINE> if device_config is None: <NEW_LINE> <INDENT> response = { 'status' : 'failed', 'reason': 'Required attribute "config" was not provided' } <NEW_LINE> return web.Response(text=json.dumps(response), status=500) <NEW_LINE> <DEDENT> _LOGGER.info(("Updating device {} with config {}").format( device_id, device_config)) <NEW_LINE> self.ledfx.devices.destroy(device_id) <NEW_LINE> device = self.ledfx.devices.create( config = device_config, id = device_id, name = device_config.get('type')) <NEW_LINE> self.ledfx.config['devices'][device_id] = device_config <NEW_LINE> save_config( config = self.ledfx.config, config_dir = self.ledfx.config_dir) <NEW_LINE> response = { 'status' : 'success' } <NEW_LINE> return web.Response(text=json.dumps(response), status=500) <NEW_LINE> <DEDENT> async def delete(self, device_id) -> web.Response: <NEW_LINE> <INDENT> device = self.ledfx.devices.get(device_id) <NEW_LINE> if device is None: <NEW_LINE> <INDENT> response = { 'not found': 404 } <NEW_LINE> return web.Response(text=json.dumps(response), status=404) <NEW_LINE> <DEDENT> self.ledfx.devices.destroy(device_id) <NEW_LINE> del self.ledfx.config['devices'][device_id] <NEW_LINE> save_config( config = self.ledfx.config, config_dir = self.ledfx.config_dir) <NEW_LINE> response = { 'status' : 'success' } <NEW_LINE> return web.Response(text=json.dumps(response), status=200)
REST end-point for querying and managing devices
6259903ed99f1b3c44d068f7
class IndexConfigError(Exception): <NEW_LINE> <INDENT> pass
Raise an error when create an :class:`Index` object from config dictionary.
6259903e66673b3332c31653
class TextureSprite(Sprite): <NEW_LINE> <INDENT> def __init__(self, texture): <NEW_LINE> <INDENT> super(TextureSprite, self).__init__() <NEW_LINE> self.texture = texture <NEW_LINE> flags = Uint32() <NEW_LINE> access = c_int() <NEW_LINE> w = c_int() <NEW_LINE> h = c_int() <NEW_LINE> ret = render.SDL_QueryTexture(texture, byref(flags), byref(access), byref(w), byref(h)) <NEW_LINE> if ret == -1: <NEW_LINE> <INDENT> raise SDLError() <NEW_LINE> <DEDENT> self._size = w.value, h.value <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> if self.texture is not None: <NEW_LINE> <INDENT> render.SDL_DestroyTexture(self.texture) <NEW_LINE> <DEDENT> self.texture = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def size(self): <NEW_LINE> <INDENT> return self._size <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> flags = Uint32() <NEW_LINE> access = c_int() <NEW_LINE> w = c_int() <NEW_LINE> h = c_int() <NEW_LINE> ret = render.SDL_QueryTexture(self.texture, byref(flags), byref(access), byref(w), byref(h)) <NEW_LINE> if ret == -1: <NEW_LINE> <INDENT> raise SDLError() <NEW_LINE> <DEDENT> return "TextureSprite(format=%d, access=%d, size=%s)" % (flags.value, access.value, (w.value, h.value))
A simple, visible, texture-based 2D object, using a renderer.
6259903ea79ad1619776b2da
class ACLMetaclass(type): <NEW_LINE> <INDENT> def __new__(cls, name, bases, attrs): <NEW_LINE> <INDENT> new_class = super(ACLMetaclass, cls).__new__(cls, name, bases, attrs) <NEW_LINE> if new_class.model is None: <NEW_LINE> <INDENT> return new_class <NEW_LINE> <DEDENT> new_class.perms = {} <NEW_LINE> if not isinstance(new_class.model, (Model, ModelBase)): <NEW_LINE> <INDENT> raise NotAModel(new_class.model) <NEW_LINE> <DEDENT> elif isinstance(new_class.model, Model) and not new_class.model.pk: <NEW_LINE> <INDENT> raise UnsavedModelInstance(new_class.model) <NEW_LINE> <DEDENT> content_type = ContentType.objects.get_for_model(new_class.model) <NEW_LINE> current_perms = content_type.model_class().get_acl_permissions() <NEW_LINE> register_acl_for_model(new_class.model, current_perms) <NEW_LINE> perms = ACLVerbPermission.objects.filter(content_type=content_type) <NEW_LINE> for perm in perms: <NEW_LINE> <INDENT> if current_perms.has_key(perm.codename) is False: <NEW_LINE> <INDENT> ACLPermission.objects.filter(permission=perm).delete() <NEW_LINE> perm.delete() <NEW_LINE> continue <NEW_LINE> <DEDENT> new_class.perms[perm.codename] = perm <NEW_LINE> func = cls.create_check(new_class, perm.codename) <NEW_LINE> object_name = new_class.model._meta.object_name <NEW_LINE> func_name = "%s_%s" % (perm.codename, object_name.lower()) <NEW_LINE> func.short_description = _("Can %(check)s this %(object_name)s") % { 'object_name': new_class.model._meta.object_name.lower(), 'check': perm.codename} <NEW_LINE> func.k = perm.codename <NEW_LINE> setattr(new_class, func_name, func) <NEW_LINE> <DEDENT> return new_class <NEW_LINE> <DEDENT> def create_check(self, check_name, *args, **kwargs): <NEW_LINE> <INDENT> def check(self, *args, **kwargs): <NEW_LINE> <INDENT> granted = self.can(check_name, *args, **kwargs) <NEW_LINE> return granted <NEW_LINE> <DEDENT> return check
Used to generate the default set of permission
6259903ebe383301e0254a73
class Test_objects(unittest.TestCase): <NEW_LINE> <INDENT> def test_object(self): <NEW_LINE> <INDENT> lines = compile_from_file('obj') <NEW_LINE> find_ops = ['bind_refs', 'invoke'] <NEW_LINE> self.assertTrue(check_op_sequence(lines, find_ops)) <NEW_LINE> <DEDENT> def test_builder_pattern(self): <NEW_LINE> <INDENT> lines = compile_from_file('obj_builder') <NEW_LINE> find_ops = ['bind_refs', 'invoke', 'invoke', 'invoke', 'emit'] <NEW_LINE> self.assertTrue(check_op_sequence(lines, find_ops))
'Objects' testing
6259903ed6c5a102081e3381
class MinimaxAgent(MultiAgentSearchAgent): <NEW_LINE> <INDENT> def getAction(self, gameState): <NEW_LINE> <INDENT> bestValue = float('-Inf') <NEW_LINE> bestAction = None <NEW_LINE> for action in gameState.getLegalActions(0): <NEW_LINE> <INDENT> tempValue = self.minValue(gameState.generateSuccessor(0, action), 1, 1) <NEW_LINE> if bestValue < tempValue: <NEW_LINE> <INDENT> bestValue = tempValue <NEW_LINE> bestAction = action <NEW_LINE> <DEDENT> <DEDENT> return bestAction <NEW_LINE> <DEDENT> def value(self, gameState, agentIndex, currentDepth): <NEW_LINE> <INDENT> if gameState.isWin() or gameState.isLose(): <NEW_LINE> <INDENT> return self.evaluationFunction(gameState) <NEW_LINE> <DEDENT> elif agentIndex == gameState.getNumAgents() - 1: <NEW_LINE> <INDENT> return self.maxValue(gameState, 0, currentDepth) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.minValue(gameState, agentIndex + 1, currentDepth) <NEW_LINE> <DEDENT> <DEDENT> def maxValue(self, gameState, agentIndex, currentDepth): <NEW_LINE> <INDENT> currentDepth += 1 <NEW_LINE> if currentDepth > self.depth: <NEW_LINE> <INDENT> return self.evaluationFunction(gameState) <NEW_LINE> <DEDENT> bestValue = float('-Inf') <NEW_LINE> for action in gameState.getLegalActions(agentIndex): <NEW_LINE> <INDENT> bestValue = max(bestValue, self.value(gameState.generateSuccessor(agentIndex, action), agentIndex, currentDepth)) <NEW_LINE> <DEDENT> return bestValue <NEW_LINE> <DEDENT> def minValue(self, gameState, agentIndex, currentDepth): <NEW_LINE> <INDENT> bestValue = float('Inf') <NEW_LINE> if len(gameState.getLegalActions(agentIndex)) == 0: <NEW_LINE> <INDENT> return self.evaluationFunction(gameState) <NEW_LINE> <DEDENT> for action in gameState.getLegalActions(agentIndex): <NEW_LINE> <INDENT> bestValue = min(bestValue, self.value(gameState.generateSuccessor(agentIndex, action), agentIndex, currentDepth)) <NEW_LINE> <DEDENT> return bestValue
Your minimax agent (question 2)
6259903e23849d37ff852315
class CPUIdle(CPUError): <NEW_LINE> <INDENT> def __init__(self, msg): <NEW_LINE> <INDENT> super(CPUError, self).__init__(msg)
Executed custom-idle instruction and quit-on-idle is enabled.
6259903e1f5feb6acb163e4f
class ModifyIPStrategyRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.ServiceId = None <NEW_LINE> self.StrategyId = None <NEW_LINE> self.StrategyData = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.ServiceId = params.get("ServiceId") <NEW_LINE> self.StrategyId = params.get("StrategyId") <NEW_LINE> self.StrategyData = params.get("StrategyData")
ModifyIPStrategy request structure.
6259903e6e29344779b018ae
class TestSampleGrid(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.filename = os.path.join(TEST_DIR, 'test_data', 'landmask.nc') <NEW_LINE> self.lslon, self.lslat, self.lsgrid = grid.grdRead(self.filename) <NEW_LINE> ncobj = nctools.ncLoadFile(self.filename) <NEW_LINE> self.nclon = nctools.ncGetDims(ncobj, 'lon') <NEW_LINE> self.nclat = nctools.ncGetDims(ncobj, 'lat') <NEW_LINE> self.ncgrid = nctools.ncGetData(ncobj, 'landmask') <NEW_LINE> ncobj.close() <NEW_LINE> self.sample = grid.SampleGrid(self.filename) <NEW_LINE> self.xlon = [100., 130., 180., 250., 300.] <NEW_LINE> self.ylat = [-80., -20., 40.] <NEW_LINE> self.ls = [3., 0., 3., 3., 3., 0., 3., 0., 0., 3., 0., 3., 3., 3., 0.] <NEW_LINE> <DEDENT> def test_gridNctools(self): <NEW_LINE> <INDENT> assert_almost_equal(self.lslon, self.nclon) <NEW_LINE> assert_almost_equal(self.lslat, self.nclat) <NEW_LINE> assert_almost_equal(self.lsgrid, self.ncgrid) <NEW_LINE> <DEDENT> def test_sampleGridArray(self): <NEW_LINE> <INDENT> assert_almost_equal(self.sample.lon, self.nclon) <NEW_LINE> assert_almost_equal(self.sample.lat, self.nclat) <NEW_LINE> assert_almost_equal(self.sample.grid, np.flipud(self.ncgrid)) <NEW_LINE> <DEDENT> def test_sampleGridPoints(self): <NEW_LINE> <INDENT> i = 0 <NEW_LINE> for x in self.xlon: <NEW_LINE> <INDENT> for y in self.ylat: <NEW_LINE> <INDENT> assert_almost_equal(self.sample.sampleGrid(x, y), self.ls[i]) <NEW_LINE> i += 1
Test that the range of methods to load gridded data produce expected results. Uses the 0.083 degree land-sea mask dataset as a test dataset.
6259903eb57a9660fecd2cd7
class CreateInputs(BaseOp): <NEW_LINE> <INDENT> def execute(self, input_data): <NEW_LINE> <INDENT> return [np.array(input_data[0]), np.array(input_data[1])]
op that creates inputs for the pipeline
6259903ed53ae8145f9196b8
class RoleIntrospection(object): <NEW_LINE> <INDENT> title = 'Role' <NEW_LINE> manage.introspection('ptah:role') <NEW_LINE> actions = view.template('ptah.manage:templates/directive-role.pt') <NEW_LINE> def __init__(self, request): <NEW_LINE> <INDENT> self.request = request <NEW_LINE> <DEDENT> def renderActions(self, *actions): <NEW_LINE> <INDENT> return self.actions( roles = ptah.get_roles(), actions = actions, request = self.request)
Role registrations
6259903e50485f2cf55dc1e0
class AbstractParser(object): <NEW_LINE> <INDENT> def __init__(self, name, description, *args): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> self._description = description <NEW_LINE> self._args = [] <NEW_LINE> self._kwargs = {} <NEW_LINE> for arg in args: <NEW_LINE> <INDENT> if isinstance(arg, KW): <NEW_LINE> <INDENT> self._kwargs.update(arg.kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._args.append(arg) <NEW_LINE> <DEDENT> <DEDENT> self._kwargs['description'] = description <NEW_LINE> self.epilog = self._kwargs.pop('epilog', '') <NEW_LINE> self._init() <NEW_LINE> <DEDENT> def _init(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __call__(self, parser, **kwargs): <NEW_LINE> <INDENT> return self._build(parser, self._updated_kwargs(kwargs)) <NEW_LINE> <DEDENT> def _updated_kwargs(self, kwargs): <NEW_LINE> <INDENT> return dict(list(self._kwargs.items()) + list(kwargs.items())) <NEW_LINE> <DEDENT> def _build(self, **kwargs): <NEW_LINE> <INDENT> raise NotImplemented() <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def description(self): <NEW_LINE> <INDENT> return self._description <NEW_LINE> <DEDENT> @property <NEW_LINE> def args(self): <NEW_LINE> <INDENT> return iter(self._args)
ABC for Parser objects. Parser objects can hold Arg and SubParsers. Do not update any instance local state outside of init.
6259903e1d351010ab8f4d79
class GraphQLResolveInfo(NamedTuple): <NEW_LINE> <INDENT> field_name: str <NEW_LINE> field_nodes: List[FieldNode] <NEW_LINE> return_type: "GraphQLOutputType" <NEW_LINE> parent_type: "GraphQLObjectType" <NEW_LINE> path: Path <NEW_LINE> schema: "GraphQLSchema" <NEW_LINE> fragments: Dict[str, FragmentDefinitionNode] <NEW_LINE> root_value: Any <NEW_LINE> operation: OperationDefinitionNode <NEW_LINE> variable_values: Dict[str, Any] <NEW_LINE> context: Any <NEW_LINE> is_awaitable: Callable[[Any], bool]
Collection of information passed to the resolvers. This is always passed as the first argument to the resolvers. Note that contrary to the JavaScript implementation, the context (commonly used to represent an authenticated user, or request-specific caches) is included here and not passed as an additional argument.
6259903ed10714528d69efba
class NameSchema(MappingSchema): <NEW_LINE> <INDENT> name = Name()
Name sheet data structure. `name`: a human readable resource Identifier
6259903e26068e7796d4dba3
class _Service: <NEW_LINE> <INDENT> def start_service(self): <NEW_LINE> <INDENT> settle() <NEW_LINE> if list(processes("stratisd")) != []: <NEW_LINE> <INDENT> raise RuntimeError("A stratisd process is already running") <NEW_LINE> <DEDENT> service = subprocess.Popen( [_STRATISD], universal_newlines=True, ) <NEW_LINE> dbus_interface_present = False <NEW_LINE> limit = time.time() + 120.0 <NEW_LINE> while ( time.time() <= limit and not dbus_interface_present and service.poll() is None ): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> get_object(TOP_OBJECT) <NEW_LINE> dbus_interface_present = True <NEW_LINE> <DEDENT> except dbus.exceptions.DBusException: <NEW_LINE> <INDENT> time.sleep(0.5) <NEW_LINE> <DEDENT> <DEDENT> time.sleep(1) <NEW_LINE> if service.poll() is not None: <NEW_LINE> <INDENT> raise RuntimeError( "Daemon unexpectedly exited with exit code %s" % service.returncode, ) <NEW_LINE> <DEDENT> if not dbus_interface_present: <NEW_LINE> <INDENT> raise RuntimeError("No D-Bus interface for stratisd found") <NEW_LINE> <DEDENT> self._service = service <NEW_LINE> return self <NEW_LINE> <DEDENT> def stop_service(self): <NEW_LINE> <INDENT> self._service.send_signal(signal.SIGINT) <NEW_LINE> self._service.wait() <NEW_LINE> if list(processes("stratisd")) != []: <NEW_LINE> <INDENT> raise RuntimeError("Failed to stop stratisd service")
Start and stop stratisd.
6259903ecad5886f8bdc59ab
class TestContentViewUpdate: <NEW_LINE> <INDENT> @pytest.mark.parametrize( 'key, value', {'description': gen_utf8(), 'name': gen_utf8()}.items(), ids=idgen ) <NEW_LINE> @tier1 <NEW_LINE> def test_positive_update_attributes(self, module_cv, key, value): <NEW_LINE> <INDENT> setattr(module_cv, key, value) <NEW_LINE> content_view = module_cv.update({key}) <NEW_LINE> assert getattr(content_view, key) == value <NEW_LINE> <DEDENT> @pytest.mark.parametrize('new_name', valid_data_list(), ids=idgen) <NEW_LINE> @tier1 <NEW_LINE> def test_positive_update_name(self, module_cv, new_name): <NEW_LINE> <INDENT> module_cv.name = new_name <NEW_LINE> module_cv.update(['name']) <NEW_LINE> updated = entities.ContentView(id=module_cv.id).read() <NEW_LINE> assert new_name == updated.name <NEW_LINE> <DEDENT> @pytest.mark.parametrize('new_name', invalid_names_list(), ids=idgen) <NEW_LINE> @tier1 <NEW_LINE> def test_negative_update_name(self, module_cv, new_name): <NEW_LINE> <INDENT> with pytest.raises(HTTPError): <NEW_LINE> <INDENT> module_cv.name = new_name <NEW_LINE> module_cv.update(['name']) <NEW_LINE> <DEDENT> cv = module_cv.read() <NEW_LINE> assert cv.name != new_name <NEW_LINE> <DEDENT> @pytest.mark.skip_if_open("BZ:1147100") <NEW_LINE> @tier1 <NEW_LINE> def test_negative_update_label(self, module_cv): <NEW_LINE> <INDENT> with pytest.raises(HTTPError): <NEW_LINE> <INDENT> module_cv.label = gen_utf8(30) <NEW_LINE> module_cv.update(['label'])
Tests for updating content views.
6259903e507cdc57c63a5ff9
class Bullet(Sprite): <NEW_LINE> <INDENT> def __init__(self, ai_settings, screen, ship): <NEW_LINE> <INDENT> super(Bullet, self).__init__() <NEW_LINE> self.screen = screen <NEW_LINE> self.rect = pygame.Rect( 0, 0, ai_settings.bullet_width, ai_settings.bullet_height) <NEW_LINE> self.rect.centerx = ship.rect.centerx <NEW_LINE> self.rect.top = ship.rect.top <NEW_LINE> self.y = float(self.rect.y) <NEW_LINE> self.color = ai_settings.bullet_color <NEW_LINE> self.speed_factor = ai_settings.bullet_speed_factor <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.y -= self.speed_factor <NEW_LINE> self.rect.y = self.y <NEW_LINE> <DEDENT> def draw_bullet(self): <NEW_LINE> <INDENT> pygame.draw.rect(self.screen, self.color, self.rect)
子弹管理
6259903e21a7993f00c671cb
class _Receiver(object): <NEW_LINE> <INDENT> __metaclass__ = abc.ABCMeta <NEW_LINE> @abc.abstractmethod <NEW_LINE> def abort_if_abortive(self, packet): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def receive(self, packet): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def reception_failure(self): <NEW_LINE> <INDENT> raise NotImplementedError()
Common specification of different packet-handling behavior.
6259903e76d4e153a661dba2
class BaseMotorBoard(metaclass=abc.ABCMeta): <NEW_LINE> <INDENT> @abc.abstractmethod <NEW_LINE> def channels(self) -> Sequence[BaseMotorChannel]: <NEW_LINE> <INDENT> raise NotImplementedError
Abstract motor board implementation.
6259903e8da39b475be0444c
class Reporter(object): <NEW_LINE> <INDENT> def __init__(self, task=None, stage=None, operation=None): <NEW_LINE> <INDENT> self.task = task <NEW_LINE> self.stage = stage <NEW_LINE> self.operation = operation <NEW_LINE> <DEDENT> def start(self, **data): <NEW_LINE> <INDENT> self.handle(status=Status.START, **data) <NEW_LINE> <DEDENT> def end(self, **data): <NEW_LINE> <INDENT> self.handle(status=Status.SUCCESS, **data) <NEW_LINE> <DEDENT> def error(self, exception, **data): <NEW_LINE> <INDENT> self.handle(status=Status.ERROR, exception=exception, **data) <NEW_LINE> <DEDENT> def handle(self, status, operation=None, exception=None, task=None, **payload): <NEW_LINE> <INDENT> if not WORKER_REPORTING: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> task = task or self.task <NEW_LINE> if task is not None: <NEW_LINE> <INDENT> payload["task"] = task.serialize() <NEW_LINE> stage = task.stage <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> stage = self.stage <NEW_LINE> <DEDENT> dataset = stage.job.dataset.name <NEW_LINE> job_id = stage.job.id <NEW_LINE> operation = operation or stage.stage <NEW_LINE> now = datetime.utcnow() <NEW_LINE> payload.update( { "dataset": dataset, "operation": operation, "job": job_id, "status": status, "updated_at": now, "%s_at" % status: now, "has_error": False, } ) <NEW_LINE> if exception is not None: <NEW_LINE> <INDENT> payload.update( { "status": Status.ERROR, "has_error": True, "error_name": exception.__class__.__name__, "error_msg": stringify(exception), } ) <NEW_LINE> <DEDENT> job = Job(stage.conn, dataset, job_id) <NEW_LINE> stage = job.get_stage(OP_REPORT) <NEW_LINE> stage.queue(payload)
A reporter will create processing status updates.
6259903e0a366e3fb87ddc43
class ProtocolVersion(NamedTuple): <NEW_LINE> <INDENT> major: int <NEW_LINE> minor: int <NEW_LINE> patch: int <NEW_LINE> def to_string(self): <NEW_LINE> <INDENT> return f"v{self.major}.{self.minor}.{self.patch}"
Server protocol version struct
6259903e15baa723494631ef
class Team(object): <NEW_LINE> <INDENT> def __init__(self, name, wins, seed): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.wins = int(wins) <NEW_LINE> self.seed = int(seed) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def get_odds(self): <NEW_LINE> <INDENT> seed_weight = 0.6 <NEW_LINE> win_weight = 0.4 <NEW_LINE> seed_factor = (17 - self.seed) * seed_weight <NEW_LINE> win_factor = self.wins * win_weight <NEW_LINE> return seed_factor + win_factor
Represents a team in the tournament. A team will have a name, wins, and a seed. The wins should be represented as the number of wins less the number of losses. eg. A record of 22-12 is 10 wins.
6259903e379a373c97d9a287
class SettingsDict(dict): <NEW_LINE> <INDENT> separator = "." <NEW_LINE> def copy(self): <NEW_LINE> <INDENT> new_items = self.__class__() <NEW_LINE> for k, v in self.iteritems(): <NEW_LINE> <INDENT> new_items[k] = v <NEW_LINE> <DEDENT> return new_items <NEW_LINE> <DEDENT> def getsection(self, section): <NEW_LINE> <INDENT> section_items = self.__class__() <NEW_LINE> if not section: <NEW_LINE> <INDENT> for key, value in self.iteritems(): <NEW_LINE> <INDENT> if self.separator not in key: <NEW_LINE> <INDENT> section_items[key] = value <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> prefix = section + self.separator <NEW_LINE> for key, value in self.iteritems(): <NEW_LINE> <INDENT> if key.startswith(prefix): <NEW_LINE> <INDENT> section_items[key[len(prefix):]] = value <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return section_items <NEW_LINE> <DEDENT> def setdefaults(self, *args, **kwds): <NEW_LINE> <INDENT> for arg in args: <NEW_LINE> <INDENT> if hasattr(arg, "keys"): <NEW_LINE> <INDENT> for k in arg: <NEW_LINE> <INDENT> self.setdefault(k, arg[k]) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for k, v in arg: <NEW_LINE> <INDENT> self.setdefault(k, v) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for k, v in kwds.iteritems(): <NEW_LINE> <INDENT> self.setdefault(k, v)
A dict subclass with some extra helpers for dealing with app settings. This class extends the standard dictionary interface with some extra helper methods that are handy when dealing with application settings. It expects the keys to be dotted setting names, where each component indicates one section in the settings hierarchy. You get the following extras: * setdefaults: copy any unset settings from another dict * getsection: return a dict of settings for just one subsection
6259903e004d5f362081f913
class BasicTokenizer(object): <NEW_LINE> <INDENT> def __init__(self, do_lower_case=True): <NEW_LINE> <INDENT> self.do_lower_case = do_lower_case <NEW_LINE> <DEDENT> def tokenize(self, text): <NEW_LINE> <INDENT> text = _convert_to_unicode_or_throw(text) <NEW_LINE> text = self._clean_text(text) <NEW_LINE> orig_tokens = whitespace_tokenize(text) <NEW_LINE> split_tokens = [] <NEW_LINE> for token in orig_tokens: <NEW_LINE> <INDENT> if self.do_lower_case: <NEW_LINE> <INDENT> token = token.lower() <NEW_LINE> token = self._run_strip_accents(token) <NEW_LINE> <DEDENT> split_tokens.extend(self._run_split_on_punc(token)) <NEW_LINE> <DEDENT> output_tokens = whitespace_tokenize(" ".join(split_tokens)) <NEW_LINE> return output_tokens <NEW_LINE> <DEDENT> def _run_strip_accents(self, text): <NEW_LINE> <INDENT> text = unicodedata.normalize("NFD", text) <NEW_LINE> output = [] <NEW_LINE> for char in text: <NEW_LINE> <INDENT> cat = unicodedata.category(char) <NEW_LINE> if cat == "Mn": <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> output.append(char) <NEW_LINE> <DEDENT> return "".join(output) <NEW_LINE> <DEDENT> def _run_split_on_punc(self, text): <NEW_LINE> <INDENT> chars = list(text) <NEW_LINE> i = 0 <NEW_LINE> start_new_word = True <NEW_LINE> output = [] <NEW_LINE> while i < len(chars): <NEW_LINE> <INDENT> char = chars[i] <NEW_LINE> if _is_punctuation(char): <NEW_LINE> <INDENT> output.append([char]) <NEW_LINE> start_new_word = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if start_new_word: <NEW_LINE> <INDENT> output.append([]) <NEW_LINE> <DEDENT> start_new_word = False <NEW_LINE> output[-1].append(char) <NEW_LINE> <DEDENT> i += 1 <NEW_LINE> <DEDENT> return ["".join(x) for x in output] <NEW_LINE> <DEDENT> def _clean_text(self, text): <NEW_LINE> <INDENT> output = [] <NEW_LINE> for char in text: <NEW_LINE> <INDENT> cp = ord(char) <NEW_LINE> if cp == 0 or cp == 0xfffd or _is_control(char): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if _is_whitespace(char): <NEW_LINE> <INDENT> output.append(" ") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> output.append(char) <NEW_LINE> <DEDENT> <DEDENT> return "".join(output)
Runs basic tokenization (punctuation splitting, lower casing, etc.).
6259903e097d151d1a2c22c4
class Config: <NEW_LINE> <INDENT> env_file_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) <NEW_LINE> env_file = env_file_path + '/' + '.env' <NEW_LINE> load_dotenv(dotenv_path=env_file) <NEW_LINE> INFLUX_DB = os.getenv('INFLUXDB_DB') <NEW_LINE> INFLUX_USER = os.getenv('INFLUXDB_ADMIN_USER') <NEW_LINE> INFLUX_PASSWORD = os.getenv('INFLUXDB_ADMIN_PASSWORD') <NEW_LINE> INFLUX_PORT = os.getenv('INFLUX_PORT') <NEW_LINE> INFLUX_HOST = os.getenv('INFLUX_HOST') <NEW_LINE> BROKER_PORT = os.getenv('BROKER_PORT') <NEW_LINE> BROKER_TOPIC = os.getenv('BROKER_TOPIC') <NEW_LINE> BROKER_QOS = os.getenv('BROKER_QOS') <NEW_LINE> BROKER_KEEP_ALIVE = os.getenv('BROKER_KEEP_ALIVE') <NEW_LINE> BROKER_USERNAME = os.getenv('BROKER_USERNAME') <NEW_LINE> BROKER_PASSWORD = os.getenv('BROKER_PASSWORD') <NEW_LINE> BROKER_URL = os.getenv('BROKER_URL')
Loading of configurations from dot env file
6259903e8a349b6b436874a4
class CollectorHandler: <NEW_LINE> <INDENT> def __init__(self, entries_handler, collector_registry): <NEW_LINE> <INDENT> self.entries_handler = entries_handler <NEW_LINE> self.collector_registry = collector_registry <NEW_LINE> <DEDENT> def collect(self): <NEW_LINE> <INDENT> yield from self.collector_registry.bandwidthCollector.collect() <NEW_LINE> for router_entry in self.entries_handler.router_entries: <NEW_LINE> <INDENT> if not router_entry.api_connection.is_connected(): <NEW_LINE> <INDENT> router_entry.api_connection.connect() <NEW_LINE> continue <NEW_LINE> <DEDENT> for collector_ID, collect_func in self.collector_registry.registered_collectors.items(): <NEW_LINE> <INDENT> start = default_timer() <NEW_LINE> yield from collect_func(router_entry) <NEW_LINE> router_entry.time_spent[collector_ID] += default_timer() - start
MKTXP Collectors Handler
6259903e07d97122c4217efd
class Net(nn.Module): <NEW_LINE> <INDENT> def __init__(self, hidden_size): <NEW_LINE> <INDENT> super(Net, self).__init__() <NEW_LINE> self.conv1 = nn.Conv2d(1, 32, 3, 1) <NEW_LINE> self.conv2 = nn.Conv2d(32, 64, 3, 1) <NEW_LINE> self.dropout1 = nn.Dropout2d(0.25) <NEW_LINE> self.dropout2 = nn.Dropout2d(0.5) <NEW_LINE> self.fc1 = nn.Linear(9216, hidden_size) <NEW_LINE> self.fc2 = nn.Linear(hidden_size, 10) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> x = self.conv1(x) <NEW_LINE> x = F.relu(x) <NEW_LINE> x = self.conv2(x) <NEW_LINE> x = F.relu(x) <NEW_LINE> x = F.max_pool2d(x, 2) <NEW_LINE> x = self.dropout1(x) <NEW_LINE> x = torch.flatten(x, 1) <NEW_LINE> x = self.fc1(x) <NEW_LINE> x = F.relu(x) <NEW_LINE> x = self.dropout2(x) <NEW_LINE> x = self.fc2(x) <NEW_LINE> output = F.log_softmax(x, dim=1) <NEW_LINE> return output
Define an NN model.
6259903e96565a6dacd2d8ba
class Font: <NEW_LINE> <INDENT> _DATABASE = None <NEW_LINE> def __init__(self, color='black', paper='white', bold=False, italic=False): <NEW_LINE> <INDENT> self.color = color <NEW_LINE> self.paper = paper <NEW_LINE> self.bold = bold <NEW_LINE> self.italic = italic <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_database(cls): <NEW_LINE> <INDENT> if cls._DATABASE is None: <NEW_LINE> <INDENT> cls._DATABASE = QFontDatabase() <NEW_LINE> for variant in FONT_VARIANTS: <NEW_LINE> <INDENT> filename = FONT_FILENAME_PATTERN.format(variant=variant) <NEW_LINE> font_data = load_font_data(filename) <NEW_LINE> cls._DATABASE.addApplicationFontFromData(font_data) <NEW_LINE> <DEDENT> <DEDENT> return cls._DATABASE <NEW_LINE> <DEDENT> def load(self, size=DEFAULT_FONT_SIZE): <NEW_LINE> <INDENT> return Font.get_database().font(FONT_NAME, self.stylename, size) <NEW_LINE> <DEDENT> @property <NEW_LINE> def stylename(self): <NEW_LINE> <INDENT> if self.bold: <NEW_LINE> <INDENT> if self.italic: <NEW_LINE> <INDENT> return "Semibold Italic" <NEW_LINE> <DEDENT> return "Semibold" <NEW_LINE> <DEDENT> if self.italic: <NEW_LINE> <INDENT> return "Italic" <NEW_LINE> <DEDENT> return "Regular"
Utility class that makes it easy to set font related values within the editor.
6259903ebe383301e0254a77
class TC2(UnixCommands): <NEW_LINE> <INDENT> logger = logging.getLogger(__name__) <NEW_LINE> @staticmethod <NEW_LINE> def run_tc(): <NEW_LINE> <INDENT> TC2.logger.info(cons.INFO_RENAME + cons.INFO_CONDITION_RW) <NEW_LINE> step_1 = UnixCommands.ssh_to_server(var.SERVER_NAME, var.SERVER_IP, cons.REMOTE_TOUCH + var.HOST_PATH_TO_SHARE + cons.TEST_FILE_NAME) <NEW_LINE> Inspection.check_ssh_to_server(step_1, TC2, 1) <NEW_LINE> step_2 = UnixCommands.change_directory(var.LOCAL_PATH_TO_SHARE) <NEW_LINE> Inspection.check_change_dir(step_2, TC2, 2) <NEW_LINE> Inspection.check_work_dir(TC2) <NEW_LINE> step_3 = UnixCommands.rename_file(cons.TEST_FILE_NAME, cons.TEST_FILE_2_NAME) <NEW_LINE> Inspection.check_rename(step_3, TC2, 3) <NEW_LINE> Inspection.check_list_of_files(TC2)
From client side rename a file from a share directory. Condition rw
6259903ed53ae8145f9196bb
class GetBlockAPISerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> transactions = TransactionAPISerializer(many=True, source='get_block') <NEW_LINE> previous_hash = SubGetBlockAPISerializer(many=False) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = models.BlockStructureDB <NEW_LINE> fields = '__all__'
Serialize blocks
6259903ed6c5a102081e3385
class BigBracket(BigSymbol): <NEW_LINE> <INDENT> def __init__(self, size, bracket, alignment='l'): <NEW_LINE> <INDENT> self.size = size <NEW_LINE> self.original = bracket <NEW_LINE> self.alignment = alignment <NEW_LINE> self.pieces = None <NEW_LINE> if bracket in FormulaConfig.bigbrackets: <NEW_LINE> <INDENT> self.pieces = FormulaConfig.bigbrackets[bracket] <NEW_LINE> <DEDENT> <DEDENT> def getpiece(self, index): <NEW_LINE> <INDENT> function = getattr(self, 'getpiece' + str(len(self.pieces))) <NEW_LINE> return function(index) <NEW_LINE> <DEDENT> def getpiece1(self, index): <NEW_LINE> <INDENT> return self.pieces[0] <NEW_LINE> <DEDENT> def getpiece3(self, index): <NEW_LINE> <INDENT> if index == 0: <NEW_LINE> <INDENT> return self.pieces[0] <NEW_LINE> <DEDENT> if index == self.size - 1: <NEW_LINE> <INDENT> return self.pieces[-1] <NEW_LINE> <DEDENT> return self.pieces[1] <NEW_LINE> <DEDENT> def getpiece4(self, index): <NEW_LINE> <INDENT> if index == 0: <NEW_LINE> <INDENT> return self.pieces[0] <NEW_LINE> <DEDENT> if index == self.size - 1: <NEW_LINE> <INDENT> return self.pieces[3] <NEW_LINE> <DEDENT> if index == (self.size - 1)/2: <NEW_LINE> <INDENT> return self.pieces[2] <NEW_LINE> <DEDENT> return self.pieces[1] <NEW_LINE> <DEDENT> def getcell(self, index): <NEW_LINE> <INDENT> piece = self.getpiece(index) <NEW_LINE> span = 'span class="bracket align-' + self.alignment + '"' <NEW_LINE> return TaggedBit().constant(piece, span) <NEW_LINE> <DEDENT> def getcontents(self): <NEW_LINE> <INDENT> if self.size == 1 or not self.pieces: <NEW_LINE> <INDENT> return self.getsinglebracket() <NEW_LINE> <DEDENT> rows = [] <NEW_LINE> for index in range(self.size): <NEW_LINE> <INDENT> cell = self.getcell(index) <NEW_LINE> rows.append(TaggedBit().complete([cell], 'span class="arrayrow"')) <NEW_LINE> <DEDENT> return [TaggedBit().complete(rows, 'span class="array"')] <NEW_LINE> <DEDENT> def getsinglebracket(self): <NEW_LINE> <INDENT> if self.original == '.': <NEW_LINE> <INDENT> return [TaggedBit().constant('', 'span class="emptydot"')] <NEW_LINE> <DEDENT> return [TaggedBit().constant(self.original, 'span class="symbol"')]
A big bracket generator.
6259903edc8b845886d54816
class JWKRSATest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> from letsencrypt.acme.jose.jwk import JWKRSA <NEW_LINE> self.jwk256 = JWKRSA(key=RSA256_KEY.publickey()) <NEW_LINE> self.jwk256_private = JWKRSA(key=RSA256_KEY) <NEW_LINE> self.jwk256json = { 'kty': 'RSA', 'e': 'AQAB', 'n': 'rHVztFHtH92ucFJD_N_HW9AsdRsUuHUBBBDlHwNlRd3fp5' '80rv2-6QWE30cWgdmJS86ObRz6lUTor4R0T-3C5Q', } <NEW_LINE> self.jwk512 = JWKRSA(key=RSA512_KEY.publickey()) <NEW_LINE> self.jwk512json = { 'kty': 'RSA', 'e': 'AQAB', 'n': '9LYRcVE3Nr-qleecEcX8JwVDnjeG1X7ucsCasuuZM0e09c' 'mYuUzxIkMjO_9x4AVcvXXRXPEV-LzWWkfkTlzRMw', } <NEW_LINE> <DEDENT> def test_equals(self): <NEW_LINE> <INDENT> self.assertEqual(self.jwk256, self.jwk256) <NEW_LINE> self.assertEqual(self.jwk512, self.jwk512) <NEW_LINE> <DEDENT> def test_not_equals(self): <NEW_LINE> <INDENT> self.assertNotEqual(self.jwk256, self.jwk512) <NEW_LINE> self.assertNotEqual(self.jwk512, self.jwk256) <NEW_LINE> <DEDENT> def test_load(self): <NEW_LINE> <INDENT> from letsencrypt.acme.jose.jwk import JWKRSA <NEW_LINE> self.assertEqual(JWKRSA(key=RSA256_KEY), JWKRSA.load( pkg_resources.resource_string( 'letsencrypt.client.tests', os.path.join('testdata', 'rsa256_key.pem')))) <NEW_LINE> <DEDENT> def test_public(self): <NEW_LINE> <INDENT> self.assertEqual(self.jwk256, self.jwk256_private.public()) <NEW_LINE> <DEDENT> def test_to_json(self): <NEW_LINE> <INDENT> self.assertEqual(self.jwk256.to_json(), self.jwk256json) <NEW_LINE> self.assertEqual(self.jwk512.to_json(), self.jwk512json) <NEW_LINE> <DEDENT> def test_from_json(self): <NEW_LINE> <INDENT> from letsencrypt.acme.jose.jwk import JWK <NEW_LINE> self.assertEqual(self.jwk256, JWK.from_json(self.jwk256json)) <NEW_LINE> <DEDENT> def test_from_json_non_schema_errors(self): <NEW_LINE> <INDENT> from letsencrypt.acme.jose.jwk import JWK <NEW_LINE> self.assertRaises(errors.DeserializationError, JWK.from_json, {'kty': 'RSA', 'e': 'AQAB', 'n': ''}) <NEW_LINE> self.assertRaises(errors.DeserializationError, JWK.from_json, {'kty': 'RSA', 'e': 'AQAB', 'n': '1'})
Tests for letsencrypt.acme.jose.jwk.JWKRSA.
6259903e30c21e258be99a6d
class MockHost(object): <NEW_LINE> <INDENT> def __init__(self, data): <NEW_LINE> <INDENT> self.reader = self._read(data) <NEW_LINE> <DEDENT> def write(self, *args, **kwds): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def read(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.reader.next() <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> <DEDENT> def _read(self, data): <NEW_LINE> <INDENT> while data: <NEW_LINE> <INDENT> (length,) = struct.unpack("<H", data[2:4]) <NEW_LINE> if length: pkt = data[0:length + 4] <NEW_LINE> else: pkt = "" <NEW_LINE> data = data[length + 4:] <NEW_LINE> yield pkt
A mock device which can be used when instantiating a Device. Rather than accessing hardware, commands are replayed though given string (which can be read from file. This class is dumb, so caller has to ensure pkts in the import string or file are properly ordered.
6259903e0a366e3fb87ddc45
class BlockStyle(with_metaclass(ABCMeta, Base)): <NEW_LINE> <INDENT> def __init__(self, background_color=None, separator=None, separator_color=None, **kwargs): <NEW_LINE> <INDENT> super(BlockStyle, self).__init__(**kwargs) <NEW_LINE> self.background_color = background_color <NEW_LINE> self.separator = separator <NEW_LINE> self.separator_color = separator_color
BlockStyle. https://developers.line.me/en/docs/messaging-api/reference/#objects-for-the-block-style
6259903e8a43f66fc4bf33f0
class DeleteAll(FlaskForm): <NEW_LINE> <INDENT> confirmdelete = SubmitField("Confirm delete all data")
Form to confirm deletion of all user collections and the Tenancy collection. TO DO: Be more graceful by only removing tenancies for the current user. Attributes ---------- confirmdelete: SubmitField Confirm deletion of database.
6259903ed99f1b3c44d068fc
class StatusBar(QStatusBar): <NEW_LINE> <INDENT> def __init__(self, parent=None): <NEW_LINE> <INDENT> super().__init__(parent=parent) <NEW_LINE> self._is_cmd_mode = False <NEW_LINE> self.setSizeGripEnabled(False) <NEW_LINE> self._console = QLineEdit() <NEW_LINE> self._console.setVisible(False) <NEW_LINE> self._status_label = QLabel() <NEW_LINE> self.addPermanentWidget(self._console, True) <NEW_LINE> self.addPermanentWidget(self._status_label) <NEW_LINE> self._updateStatusBar() <NEW_LINE> <DEDENT> @property <NEW_LINE> def status_label(self): <NEW_LINE> <INDENT> return self._status_label <NEW_LINE> <DEDENT> @property <NEW_LINE> def console_bar(self): <NEW_LINE> <INDENT> return self._console <NEW_LINE> <DEDENT> def showMessage(self, text, timeout=0): <NEW_LINE> <INDENT> if not self._is_cmd_mode: <NEW_LINE> <INDENT> super().showMessage(text, timeout) <NEW_LINE> <DEDENT> <DEDENT> def showConsole(self, text): <NEW_LINE> <INDENT> if self._is_cmd_mode: <NEW_LINE> <INDENT> super().showMessage(text) <NEW_LINE> <DEDENT> <DEDENT> def showStatus(self, text): <NEW_LINE> <INDENT> self._status_label.setText(text) <NEW_LINE> <DEDENT> def isCmdMode(self): <NEW_LINE> <INDENT> return self._is_cmd_mode <NEW_LINE> <DEDENT> def setCmdMode(self, bool_): <NEW_LINE> <INDENT> if self._is_cmd_mode != bool_: <NEW_LINE> <INDENT> self._is_cmd_mode = bool_ <NEW_LINE> self._updateStatusBar() <NEW_LINE> <DEDENT> <DEDENT> def _updateStatusBar(self): <NEW_LINE> <INDENT> if self._is_cmd_mode: <NEW_LINE> <INDENT> self._console.setVisible(True) <NEW_LINE> self._console.setFocus() <NEW_LINE> self._status_label.setText("[ Command Mode ]") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._console.setVisible(False) <NEW_LINE> self._status_label.setText("[ Normal Mode ]")
状态栏
6259903e29b78933be26a9f3
class Key: <NEW_LINE> <INDENT> def __init__(self, pk_init=new_pk()): <NEW_LINE> <INDENT> self.pk = pk_init <NEW_LINE> self.wif = numtowif(int(self.pk,16)) <NEW_LINE> self.address = new_addy(self.pk)
This will hold the following information: Private Key in both String and Int form WIF String
6259903e07f4c71912bb0692
class FacebookMiddleware(FBMiddleware): <NEW_LINE> <INDENT> def process_request(self, request): <NEW_LINE> <INDENT> fb_user = self.get_fb_user(request) <NEW_LINE> request.facebook = DjangoFacebook(fb_user) if fb_user else None <NEW_LINE> return None
We don't need auth_login action at every request That's why we re-implement middleware
6259903e10dbd63aa1c71e38
class DeleteAccountResource(AccountViewMixin, DeleteAPIResource): <NEW_LINE> <INDENT> decorators = [is_authenticated()]
API View for deleting an account
6259903e21bff66bcd723ecb
class Configurable(metaclass=ConfigurableMeta): <NEW_LINE> <INDENT> def __new__(cls, *args, _final=False, **kwargs): <NEW_LINE> <INDENT> options = tuple(cls.__options__) <NEW_LINE> missing = set() <NEW_LINE> for name, option in options: <NEW_LINE> <INDENT> if option.required and not option.name in kwargs: <NEW_LINE> <INDENT> missing.add(name) <NEW_LINE> <DEDENT> <DEDENT> position = 0 <NEW_LINE> for name, option in options: <NEW_LINE> <INDENT> if not option.positional: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if not isoption(getattr(cls, name)): <NEW_LINE> <INDENT> missing.remove(name) <NEW_LINE> continue <NEW_LINE> <DEDENT> if len(args) <= position: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> position += 1 <NEW_LINE> if name in missing: <NEW_LINE> <INDENT> missing.remove(name) <NEW_LINE> <DEDENT> <DEDENT> extraneous = set(kwargs.keys()) - (set(next(zip(*options))) if len(options) else set()) <NEW_LINE> if len(extraneous): <NEW_LINE> <INDENT> raise TypeError( '{}() got {} unexpected option{}: {}.'.format( cls.__name__, len(extraneous), 's' if len(extraneous) > 1 else '', ', '.join(map(repr, sorted(extraneous))) ) ) <NEW_LINE> <DEDENT> if len(missing): <NEW_LINE> <INDENT> if _final: <NEW_LINE> <INDENT> raise TypeError( '{}() missing {} required option{}: {}.'.format( cls.__name__, len(missing), 's' if len(missing) > 1 else '', ', '.join(map(repr, sorted(missing))) ) ) <NEW_LINE> <DEDENT> return PartiallyConfigured(cls, *args, **kwargs) <NEW_LINE> <DEDENT> return super(Configurable, cls).__new__(cls) <NEW_LINE> <DEDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self._options_values = {**kwargs} <NEW_LINE> for name, value in kwargs.items(): <NEW_LINE> <INDENT> setattr(self, name, value) <NEW_LINE> <DEDENT> position = 0 <NEW_LINE> for name, option in self.__options__: <NEW_LINE> <INDENT> if not option.positional: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> maybe_value = getattr(type(self), name) <NEW_LINE> if not isoption(maybe_value): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if len(args) <= position: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if name in self._options_values: <NEW_LINE> <INDENT> raise ValueError('Already got a value for option {}'.format(name)) <NEW_LINE> <DEDENT> setattr(self, name, args[position]) <NEW_LINE> position += 1 <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> raise AbstractError(self.__call__) <NEW_LINE> <DEDENT> @property <NEW_LINE> def __options__(self): <NEW_LINE> <INDENT> return type(self).__options__ <NEW_LINE> <DEDENT> @property <NEW_LINE> def __processors__(self): <NEW_LINE> <INDENT> return type(self).__processors__
Generic class for configurable objects. Configurable objects have a dictionary of "options" descriptors that defines the configuration schema of the type.
6259903e16aa5153ce40174e
class IFC(AbivarAble): <NEW_LINE> <INDENT> def __init__(self, ddb_filename, ngqpt, q1shfts=(0.,0.,0.), ifcflag=1, brav=1): <NEW_LINE> <INDENT> self.ddb_filename = os.path.abspath(ddb_filename) <NEW_LINE> if not os.path.exists(self.ddb_filename): <NEW_LINE> <INDENT> raise ValueError("%s: no such file" % self.ddb_filename) <NEW_LINE> <DEDENT> self.ifcflag = ifcflag <NEW_LINE> self.brav = brav <NEW_LINE> self.ngqpt = ngqpt <NEW_LINE> self.q1shft = np.reshape(q1shft, (-1,3)) <NEW_LINE> self.nqshft = len(self.q1shft) <NEW_LINE> <DEDENT> def to_abivars(self): <NEW_LINE> <INDENT> d = dict( ifcflag=self.ifcflag, brav=self.brav, ngqpt="%d %d %d" % tuple(q for q in self.ngqpt), nqshft=self.nqshft, ) <NEW_LINE> lines = [] <NEW_LINE> for shift in self.q1shfts: <NEW_LINE> <INDENT> lines.append("%f %f %f" % tuple(c for c in shift)) <NEW_LINE> <DEDENT> d["q1shfts"] = "\n".join(lines) <NEW_LINE> return d <NEW_LINE> <DEDENT> def fourier_interpol(self, qpath=None, qmesh=None, symdynmat=1, asr=1, chneut=1, dipdip=1, executable=None, verbose=0): <NEW_LINE> <INDENT> d = { "symdynmat": symdynmat, "asr" : asr, "chneut" : chneut, "dipdip" : dipdip, } <NEW_LINE> if qpath is not None: <NEW_LINE> <INDENT> qpath = np.reshape(qpath, (-1,3)) <NEW_LINE> d.update({ "nqpath": len(qpath), "qpath" : "\n".join("%f %f %f" % tuple(q) for q in qpath), }) <NEW_LINE> <DEDENT> d.update(self.to_abivars()) <NEW_LINE> from .wrappers import Anaddb <NEW_LINE> anaddb = Anaddb(executable=executable, verbose=verbose)
This object defines the set of variables used for the Fourier interpolation of the interatomic force constants.
6259903ebe383301e0254a79
class OneHotNp(Transform): <NEW_LINE> <INDENT> def __init__(self, out_dim, dtype=np.float): <NEW_LINE> <INDENT> self.out_dim = out_dim <NEW_LINE> self.dtype = dtype <NEW_LINE> <DEDENT> def transform(self, tensor): <NEW_LINE> <INDENT> if not isinstance(tensor, np.ndarray): <NEW_LINE> <INDENT> tensor = np.array(tensor) <NEW_LINE> <DEDENT> res = np.eye(self.out_dim)[tensor.reshape(-1)] <NEW_LINE> targets = res.reshape([*(tensor.shape[:-1]), self.out_dim]) <NEW_LINE> return targets.astype(self.dtype) <NEW_LINE> <DEDENT> def infer_output_info(self, vshape_in, dtype_in): <NEW_LINE> <INDENT> return (self.out_dim,), self.dtype
Make transform with numpy.
6259903ea79ad1619776b2e0
class QueryBuilder: <NEW_LINE> <INDENT> def __init__(self, measurement="", period="time >= '2019-01-01'", limit=25): <NEW_LINE> <INDENT> self._limit = limit <NEW_LINE> self._measurement = measurement <NEW_LINE> self._period = period <NEW_LINE> <DEDENT> def _select_clause(self): <NEW_LINE> <INDENT> return "select * from {0}".format(self._measurement) <NEW_LINE> <DEDENT> def _where_clause(self): <NEW_LINE> <INDENT> return " where {0}".format(self._period) <NEW_LINE> <DEDENT> def _limit_clause(self): <NEW_LINE> <INDENT> return " limit {0}".format(self._limit) <NEW_LINE> <DEDENT> def generate_query(self): <NEW_LINE> <INDENT> return self._select_clause() + self._where_clause( ) + self._limit_clause()
Builds query statement for the query function
6259903ee64d504609df9d02
class BorrowedBooksView(PermissionRequiredMixin, generic.ListView): <NEW_LINE> <INDENT> model = BookInstance <NEW_LINE> template_name = 'catalog/bookinstance_list_all_borrowed.html' <NEW_LINE> paginate_by = 10 <NEW_LINE> permission_required = 'catalog.can_mark_returned' <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> return BookInstance.objects.filter(status__exact='o').order_by('due_back')
Generic class-based view listing books on loan to all users. For stuff only.
6259903e8c3a8732951f77b9
class Question(Item): <NEW_LINE> <INDENT> test = models.ForeignKey(Test, related_name='questions', verbose_name='测试' ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = '问题' <NEW_LINE> verbose_name_plural = '问题' <NEW_LINE> app_label = 'itest' <NEW_LINE> ordering = ['test', 'num', ]
问题
6259903e4e696a045264e752
class ActivitiesLocationSegment(utilities.DbObject): <NEW_LINE> <INDENT> start_lat = Column(Float) <NEW_LINE> start_long = Column(Float) <NEW_LINE> stop_lat = Column(Float) <NEW_LINE> stop_long = Column(Float) <NEW_LINE> @hybrid_property <NEW_LINE> def start_loc(self): <NEW_LINE> <INDENT> return utilities.Location(self.start_lat, self.start_long) <NEW_LINE> <DEDENT> @start_loc.setter <NEW_LINE> def start_loc(self, start_location): <NEW_LINE> <INDENT> self.start_lat = start_location.lat_deg <NEW_LINE> self.start_long = start_location.long_deg <NEW_LINE> <DEDENT> @hybrid_property <NEW_LINE> def stop_loc(self): <NEW_LINE> <INDENT> return utilities.Location(self.stop_lat, self.stop_long) <NEW_LINE> <DEDENT> @stop_loc.setter <NEW_LINE> def stop_loc(self, stop_location): <NEW_LINE> <INDENT> self.stop_lat = stop_location.lat_deg <NEW_LINE> self.stop_long = stop_location.long_deg
Object representing a databse object for storing location segnment from an activity.
6259903ea4f1c619b294f7b8
class BlobTags(Model): <NEW_LINE> <INDENT> _validation = { 'blob_tag_set': {'required': True}, } <NEW_LINE> _attribute_map = { 'blob_tag_set': {'key': 'BlobTagSet', 'type': '[BlobTag]', 'xml': {'name': 'TagSet', 'itemsName': 'TagSet', 'wrapped': True}}, } <NEW_LINE> _xml_map = { 'name': 'Tags' } <NEW_LINE> def __init__(self, *, blob_tag_set, **kwargs) -> None: <NEW_LINE> <INDENT> super(BlobTags, self).__init__(**kwargs) <NEW_LINE> self.blob_tag_set = blob_tag_set
Blob tags. All required parameters must be populated in order to send to Azure. :param blob_tag_set: Required. :type blob_tag_set: list[~azure.storage.blob.models.BlobTag]
6259903e23849d37ff85231b
class removeBreakpoint(ChromeCommand): <NEW_LINE> <INDENT> def __init__(self, breakpointId: "BreakpointId"): <NEW_LINE> <INDENT> self.breakpointId = breakpointId
Removes JavaScript breakpoint.
6259903f1f5feb6acb163e55
class PydubException(Exception): <NEW_LINE> <INDENT> pass
Base class for any Pydub exception
6259903f0a366e3fb87ddc47
class ParametrizedLocator(ParametrizedString): <NEW_LINE> <INDENT> def __get__(self, o, t=None): <NEW_LINE> <INDENT> result = super().__get__(o, t) <NEW_LINE> if isinstance(result, ParametrizedString): <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Locator(result)
:py:class:`ParametrizedString` modified to return instances of :py:class:`smartloc.Locator`
6259903f15baa723494631f3
class UpdateInvoiceItemResultSet(ResultSet): <NEW_LINE> <INDENT> def getJSONFromString(self, str): <NEW_LINE> <INDENT> return json.loads(str) <NEW_LINE> <DEDENT> def get_Response(self): <NEW_LINE> <INDENT> return self._output.get('Response', None)
A ResultSet with methods tailored to the values returned by the UpdateInvoiceItem Choreo. The ResultSet object is used to retrieve the results of a Choreo execution.
6259903f8a43f66fc4bf33f2
class schedule(object): <NEW_LINE> <INDENT> relative = False <NEW_LINE> def __init__(self, run_every=None, relative=False, nowfun=None, app=None): <NEW_LINE> <INDENT> self.run_every = maybe_timedelta(run_every) <NEW_LINE> self.relative = relative <NEW_LINE> self.nowfun = nowfun <NEW_LINE> self._app = app <NEW_LINE> <DEDENT> def now(self): <NEW_LINE> <INDENT> return (self.nowfun or self.app.now)() <NEW_LINE> <DEDENT> def remaining_estimate(self, last_run_at): <NEW_LINE> <INDENT> return remaining( self.maybe_make_aware(last_run_at), self.run_every, self.maybe_make_aware(self.now()), self.relative, ) <NEW_LINE> <DEDENT> def is_due(self, last_run_at): <NEW_LINE> <INDENT> last_run_at = self.maybe_make_aware(last_run_at) <NEW_LINE> rem_delta = self.remaining_estimate(last_run_at) <NEW_LINE> remaining_s = max(rem_delta.total_seconds(), 0) <NEW_LINE> if remaining_s == 0: <NEW_LINE> <INDENT> return schedstate(is_due=True, next=self.seconds) <NEW_LINE> <DEDENT> return schedstate(is_due=False, next=remaining_s) <NEW_LINE> <DEDENT> def maybe_make_aware(self, dt): <NEW_LINE> <INDENT> return maybe_make_aware(dt, self.tz) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<freq: {0.human_seconds}>'.format(self) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if isinstance(other, schedule): <NEW_LINE> <INDENT> return self.run_every == other.run_every <NEW_LINE> <DEDENT> return self.run_every == other <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self.__eq__(other) <NEW_LINE> <DEDENT> def __reduce__(self): <NEW_LINE> <INDENT> return self.__class__, (self.run_every, self.relative, self.nowfun) <NEW_LINE> <DEDENT> @property <NEW_LINE> def seconds(self): <NEW_LINE> <INDENT> return max(self.run_every.total_seconds(), 0) <NEW_LINE> <DEDENT> @property <NEW_LINE> def human_seconds(self): <NEW_LINE> <INDENT> return humanize_seconds(self.seconds) <NEW_LINE> <DEDENT> @property <NEW_LINE> def app(self): <NEW_LINE> <INDENT> return self._app or current_app._get_current_object() <NEW_LINE> <DEDENT> @app.setter <NEW_LINE> def app(self, app): <NEW_LINE> <INDENT> self._app = app <NEW_LINE> <DEDENT> @cached_property <NEW_LINE> def tz(self): <NEW_LINE> <INDENT> return self.app.timezone <NEW_LINE> <DEDENT> @cached_property <NEW_LINE> def utc_enabled(self): <NEW_LINE> <INDENT> return self.app.conf.enable_utc <NEW_LINE> <DEDENT> def to_local(self, dt): <NEW_LINE> <INDENT> if not self.utc_enabled: <NEW_LINE> <INDENT> return timezone.to_local_fallback(dt) <NEW_LINE> <DEDENT> return dt
Schedule for periodic task. :param run_every: Interval in seconds (or a :class:`~datetime.timedelta`). :keyword relative: If set to True the run time will be rounded to the resolution of the interval. :keyword nowfun: Function returning the current date and time (class:`~datetime.datetime`). :keyword app: Celery app instance.
6259903f6fece00bbacccc12
class SparklingJavaTransformer(JavaTransformer): <NEW_LINE> <INDENT> def __init__(self, jt=None): <NEW_LINE> <INDENT> super(SparklingJavaTransformer, self).__init__() <NEW_LINE> if not jt: <NEW_LINE> <INDENT> self._java_obj = self._new_java_obj(self.transformer_name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._java_obj = jt
Base class for Java transformers exposed in Python.
6259903f50485f2cf55dc1e6
class InvalidProvider(ExecutionError): <NEW_LINE> <INDENT> returncode = 139
A provider is not valid. This is detected before any changes have been applied.
6259903f07f4c71912bb0694
class TagsListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'next_link': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': '[TagDetails]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, value: Optional[List["TagDetails"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(TagsListResult, self).__init__(**kwargs) <NEW_LINE> self.value = value <NEW_LINE> self.next_link = None
List of subscription tags. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: An array of tags. :vartype value: list[~azure.mgmt.resource.resources.v2018_05_01.models.TagDetails] :ivar next_link: The URL to use for getting the next set of results. :vartype next_link: str
6259903f30dc7b76659a0a94
class UserViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = User.objects.all().order_by('-date_joined') <NEW_LINE> serializer_class = UserSerializer
api endpoint that allows user to be viewed or edited
6259903f45492302aabfd73c
@dataclass <NEW_LINE> class TrainerControl: <NEW_LINE> <INDENT> should_training_stop: bool = False <NEW_LINE> should_epoch_stop: bool = False <NEW_LINE> should_save: bool = False <NEW_LINE> should_evaluate: bool = False <NEW_LINE> should_log: bool = False <NEW_LINE> def _new_training(self): <NEW_LINE> <INDENT> self.should_training_stop = False <NEW_LINE> <DEDENT> def _new_epoch(self): <NEW_LINE> <INDENT> self.should_epoch_stop = False <NEW_LINE> <DEDENT> def _new_step(self): <NEW_LINE> <INDENT> self.should_save = False <NEW_LINE> self.should_evaluate = False <NEW_LINE> self.should_log = False
A class that handles the :class:`~transformers.Trainer` control flow. This class is used by the :class:`~transformers.TrainerCallback` to activate some switches in the training loop. Args: should_training_stop (:obj:`bool`, `optional`, defaults to :obj:`False`): Whether or not the training should be interrupted. If :obj:`True`, this variable will not be set back to :obj:`False`. The training will just stop. should_epoch_stop (:obj:`bool`, `optional`, defaults to :obj:`False`): Whether or not the current epoch should be interrupted. If :obj:`True`, this variable will be set back to :obj:`False` at the beginning of the next epoch. should_save (:obj:`bool`, `optional`, defaults to :obj:`False`): Whether or not the model should be saved at this step. If :obj:`True`, this variable will be set back to :obj:`False` at the beginning of the next step. should_evaluate (:obj:`bool`, `optional`, defaults to :obj:`False`): Whether or not the model should be evaluated at this step. If :obj:`True`, this variable will be set back to :obj:`False` at the beginning of the next step. should_log (:obj:`bool`, `optional`, defaults to :obj:`False`): Whether or not the logs should be reported at this step. If :obj:`True`, this variable will be set back to :obj:`False` at the beginning of the next step.
6259903f23e79379d538d762
class Action: <NEW_LINE> <INDENT> def __init__(self, address, operator_, value): <NEW_LINE> <INDENT> self.address = address <NEW_LINE> self.operator = ACTION_OPERATORS[operator_] <NEW_LINE> self.value = int(value) <NEW_LINE> <DEDENT> def evaluate(self, memory): <NEW_LINE> <INDENT> memory.set( self.address, self.operator(memory.get(self.address), self.value) )
An instruction action. Performs an inc/dec on a memory address by a certain value.
6259903f21a7993f00c671d1
class CreateLikeTrack(graphene.Mutation): <NEW_LINE> <INDENT> user = graphene.Field(UserType) <NEW_LINE> track = graphene.Field(TrackType) <NEW_LINE> class Arguments: <NEW_LINE> <INDENT> track_id = graphene.Int() <NEW_LINE> <DEDENT> @login_required <NEW_LINE> def mutate(self, info, **kwagrs): <NEW_LINE> <INDENT> user = info.context.user <NEW_LINE> track_id = kwagrs.get("track_id") <NEW_LINE> track = Track.objects.get(id=track_id) <NEW_LINE> Like.objects.create( user=user, track=track ) <NEW_LINE> return CreateLikeTrack(user=user, track=track)
This CreateLikeTrack allows you to add a track to the user preference.
6259903f07f4c71912bb0695
class TestPullActionList(unittest.TestCase): <NEW_LINE> <INDENT> @mock.patch('builtins.open', mock.mock_open(read_data="sn2:action1\nsn1:action1")) <NEW_LINE> def test_get_actions_basic(self): <NEW_LINE> <INDENT> action_list = get_actions.pull_action_list() <NEW_LINE> self.assertEqual(action_list, ['sn2:action1', 'sn1:action1']) <NEW_LINE> <DEDENT> @mock.patch('builtins.open', mock.mock_open(read_data="sn2:action1\nsn1:action1")) <NEW_LINE> def test_get_actions_sorted(self): <NEW_LINE> <INDENT> action_list = get_actions.pull_action_list(sort=True) <NEW_LINE> self.assertEqual(action_list, ['sn1:action1', 'sn2:action1']) <NEW_LINE> <DEDENT> @mock.patch('builtins.open', mock.mock_open()) <NEW_LINE> def test_get_actions_custom_file(self): <NEW_LINE> <INDENT> open_file_name = 'blabla.txt' <NEW_LINE> get_actions.pull_action_list(file=open_file_name) <NEW_LINE> open.assert_called_with(open_file_name, 'r')
GIVEN a file with actions already exists
6259903fd53ae8145f9196bf
class TargetParameter(DeclarativeBase): <NEW_LINE> <INDENT> __tablename__ = 'rep_target_parameter' <NEW_LINE> tableName = __tablename__ <NEW_LINE> id = Column(Integer, autoincrement=True, primary_key=True) <NEW_LINE> replaceParamFileID = Column(Integer, ForeignKey('rep_replace_param_files.id')) <NEW_LINE> targetVariable = Column(String) <NEW_LINE> varFormat = Column(String) <NEW_LINE> replaceParamFile = relationship('ReplaceParamFile', back_populates='targetParameters') <NEW_LINE> def __init__(self, targetVariable, varFormat): <NEW_LINE> <INDENT> self.targetVariable = targetVariable <NEW_LINE> self.varFormat = varFormat <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<TargetParameter: TargetVariable=%s, VarFormat=%s>' % (self.targetVariable, self.varFormat)
Object containing data for a single target value as defined in the Replacement Parameters File.
6259903fe64d504609df9d03
class PortfolioSim(object): <NEW_LINE> <INDENT> def __init__(self, asset_names=[], steps=128, trading_cost=0.0025, time_cost=0.0): <NEW_LINE> <INDENT> self.cost = trading_cost <NEW_LINE> self.time_cost = time_cost <NEW_LINE> self.steps = steps <NEW_LINE> self.asset_names = asset_names <NEW_LINE> self.reset() <NEW_LINE> <DEDENT> def _step(self, w1, y1): <NEW_LINE> <INDENT> w0 = self.w0 <NEW_LINE> p0 = self.p0 <NEW_LINE> dw1 = (y1 * w0) / (np.dot(y1, w0) + eps) <NEW_LINE> c1 = self.cost * ( np.abs(dw1[1:] - w1[1:])).sum() <NEW_LINE> p1 = p0 * (1 - c1) * np.dot(y1, w0) <NEW_LINE> p1 = p1 * (1 - self.time_cost) <NEW_LINE> p1 = np.clip(p1, 0, np.inf) <NEW_LINE> rho1 = p1 / p0 - 1 <NEW_LINE> r1 = np.log((p1 + eps) / (p0 + eps)) <NEW_LINE> reward = r1 / self.steps <NEW_LINE> self.w0 = w1 <NEW_LINE> self.p0 = p1 <NEW_LINE> done = bool(p1 == 0) <NEW_LINE> info = { "reward": reward, "log_return": r1, "portfolio_value": p1, "market_return": y1.mean(), "rate_of_return": rho1, "weights_mean": w1.mean(), "weights_std": w1.std(), "cost": c1, } <NEW_LINE> for i, name in enumerate(['USD'] + self.asset_names): <NEW_LINE> <INDENT> info['weight_' + name] = w1[i] <NEW_LINE> info['price_' + name] = y1[i] <NEW_LINE> <DEDENT> self.infos.append(info) <NEW_LINE> return reward, info, done <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.infos = [] <NEW_LINE> self.w0 = np.array([1.0] + [0.0] * len(self.asset_names)) <NEW_LINE> self.p0 = 1.0
Portfolio management sim. Params: - cost e.g. 0.0025 is max in Poliniex Based of [Jiang 2017](https://arxiv.org/abs/1706.10059)
6259903fd164cc61758221da
class SomeGraph: <NEW_LINE> <INDENT> def __init__( self, some_float: float) -> None: <NEW_LINE> <INDENT> self.some_float = some_float
defines some object graph.
6259903f8a349b6b436874aa
class TopicShow(ListView): <NEW_LINE> <INDENT> model = Topic <NEW_LINE> template_name = 'posts/topic.html' <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> self.object = get_object_or_404(self.model, id=self.kwargs['topic']) <NEW_LINE> self.comments = Comment.objects.filter(topic=self.object) <NEW_LINE> <DEDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super(TopicShow, self).get_context_data(**kwargs) <NEW_LINE> context['object'] = self.object <NEW_LINE> context['comments'] = CommentSorter.sort(self.comments) <NEW_LINE> form_initial = {'topic':self.kwargs['topic']} <NEW_LINE> context['form'] = CommentForm(initial=form_initial) <NEW_LINE> return context
Shows a specific topic, and its comments.
6259903f07d97122c4217f03
class Glib(VProject): <NEW_LINE> <INDENT> NAME = 'glib' <NEW_LINE> GROUP = 'c_projects' <NEW_LINE> DOMAIN = ProjectDomains.DATA_STRUCTURES <NEW_LINE> SOURCE = [ PaperConfigSpecificGit( project_name="glib", remote="https://github.com/GNOME/glib.git", local="glib", refspec="origin/HEAD", limit=None, shallow=False ) ] <NEW_LINE> CONTAINER = get_base_image( ImageBase.DEBIAN_10 ).run('apt', 'install', '-y', 'meson', 'ninja-build') <NEW_LINE> @staticmethod <NEW_LINE> def binaries_for_revision( revision: ShortCommitHash ) -> tp.List[ProjectBinaryWrapper]: <NEW_LINE> <INDENT> binary_map = RevisionBinaryMap(get_local_project_git_path(Glib.NAME)) <NEW_LINE> binary_map.specify_binary( 'build/glib/libglib-2.0.so', BinaryType.SHARED_LIBRARY ) <NEW_LINE> return binary_map[revision] <NEW_LINE> <DEDENT> def run_tests(self) -> None: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def compile(self) -> None: <NEW_LINE> <INDENT> glib_source = local.path(self.source_of_primary) <NEW_LINE> cc_compiler = bb.compiler.cc(self) <NEW_LINE> with local.cwd(glib_source): <NEW_LINE> <INDENT> with local.env(CC=str(cc_compiler)): <NEW_LINE> <INDENT> bb.watch(meson)("build") <NEW_LINE> <DEDENT> bb.watch(ninja)("-j", get_number_of_jobs(bb_cfg()), "-C", "build") <NEW_LINE> verify_binaries(self) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def get_cve_product_info(cls) -> tp.List[tp.Tuple[str, str]]: <NEW_LINE> <INDENT> return [("Gnome", "Glib")]
GLib is the low-level core library that forms the basis for projects such as GTK and GNOME. It provides data structure handling for C, portability wrappers, and interfaces for such runtime functionality as an event loop, threads, dynamic loading, and an object system. (fetched by Git)
6259903f1d351010ab8f4d82
class FooEnum(Enum): <NEW_LINE> <INDENT> GOOD_ENUM_NAME = 1 <NEW_LINE> bad_enum_name = 2
A test case for enum names.
6259903f10dbd63aa1c71e3b
class Limitation: <NEW_LINE> <INDENT> def __init__(self, code, data): <NEW_LINE> <INDENT> self._code = code <NEW_LINE> self._data = data <NEW_LINE> <DEDENT> @property <NEW_LINE> def code(self): <NEW_LINE> <INDENT> return self._code <NEW_LINE> <DEDENT> @code.setter <NEW_LINE> def code(self, new_code): <NEW_LINE> <INDENT> self._code = new_code <NEW_LINE> <DEDENT> @property <NEW_LINE> def data(self): <NEW_LINE> <INDENT> return self._data <NEW_LINE> <DEDENT> @data.setter <NEW_LINE> def data(self, new_data): <NEW_LINE> <INDENT> self._data = new_data <NEW_LINE> <DEDENT> def satisfied(self, path_to_exclude, path_destination): <NEW_LINE> <INDENT> limitation_type = get_limitation_type(self) <NEW_LINE> if limitation_type.check_function(self, path_to_exclude, path_destination): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def to_string(self, entry_input=None): <NEW_LINE> <INDENT> limitation_type = get_limitation_type(self) <NEW_LINE> if entry_input is not None and limitation_type.data_is_path and os.path.exists(os.path.realpath(self._data)): <NEW_LINE> <INDENT> display_limitation = util.shorten_path(os.path.realpath(self._data), entry_input) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> display_limitation = self._data <NEW_LINE> <DEDENT> return "{} \"{}\" {}".format(limitation_type.prefix_string, display_limitation, limitation_type.suffix_string) <NEW_LINE> <DEDENT> def equals(self, other_limitation): <NEW_LINE> <INDENT> if not isinstance(other_limitation, Limitation): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self._code == other_limitation._code and self._data == other_limitation._data: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
A class representing a limitation that is held within an exclusion. Each limitation only has a unique identifier called a code, and some data that is interpreted differently based on the code.
6259903f94891a1f408ba029
class GameSession(object): <NEW_LINE> <INDENT> def __init__(self, ip_address, player_controller_id): <NEW_LINE> <INDENT> self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) <NEW_LINE> self.sock.setblocking(False) <NEW_LINE> self.ip_address = socket.gethostbyname(ip_address) <NEW_LINE> self.player_controller_id = player_controller_id <NEW_LINE> self.sequence = 0 <NEW_LINE> <DEDENT> def pack_and_send(self, device_type, ue_key_code, ue_char_code, event_type): <NEW_LINE> <INDENT> data_keyboard = (settings.VERSION, device_type, self.sequence, self.player_controller_id, ue_key_code, ue_char_code, event_type) <NEW_LINE> data_mouse = (settings.VERSION, device_type, self.sequence, self.player_controller_id, ue_key_code, ue_char_code) <NEW_LINE> if (device_type == settings.DEVICE_KEYBOARD): <NEW_LINE> <INDENT> message = struct.pack(settings.PACKET_FORMAT_KEY, *data_keyboard) <NEW_LINE> <DEDENT> elif (device_type == settings.DEVICE_MOUSE): <NEW_LINE> <INDENT> message = struct.pack(settings.PACKET_FORMAT_MOUSE, *data_mouse) <NEW_LINE> <DEDENT> self.sock.sendto(message, (self.ip_address, settings.UDP_PORT)) <NEW_LINE> self.sequence += 1 <NEW_LINE> <DEDENT> def send_quit_command(self): <NEW_LINE> <INDENT> json_data = { "command" : "quit", "controller" : self.player_controller_id } <NEW_LINE> quit_command = json.dumps(json_data) <NEW_LINE> try: <NEW_LINE> <INDENT> tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> tcp_socket.connect((self.ip_address, settings.TCP_STREAMING_PORT)) <NEW_LINE> tcp_socket.sendall(quit_command.encode("utf-8")) <NEW_LINE> <DEDENT> except socket.error as error: <NEW_LINE> <INDENT> logging.warning(os.strerror(error.errno)); <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> tcp_socket.close()
Keyboard: 8bit Version (Currently use 0) 8bit Protocol Type : (Keyboard (1), Mouse (2), Gamepad, etc.) 32bit Sequence (counter for event) 8bit ControllerID (start from 0) 16bit UEKeyCode (A, B, , Z, 0, ... ,9, punctuation, etc.) 16bit UECharCode (F1, ..., F12, Ctrl, Alt, Numpad, etc.) 8bit Event (Key Down (2), Key Up (3)) Mouse: 8bit Version (Currently use 0) 8bit Protocol Type : (Keyboard (1), Mouse (2), Gamepad, etc.) 32bit Sequence (counter for event) 8bit ControllerID (start from 0) 16bit x-axis movement 16bit y-axis movement
6259903fcad5886f8bdc59af
class SolverObjectException(SolversException, metaclass=ABCMeta): <NEW_LINE> <INDENT> pass
Base for exceptions raised by a ``Solver`` object.
6259903fd53ae8145f9196c1
class BuyShareForm(FlaskForm): <NEW_LINE> <INDENT> buysharecode = StringField('Company Code', validators=[ DataRequired('Company Code is required')]) <NEW_LINE> buyquantity = IntegerField('Quantity to Purchase', validators=[ DataRequired('Quantity is required')]) <NEW_LINE> buysubmit = SubmitField('Purchase', validators=[DataRequired()]) <NEW_LINE> def validate(self): <NEW_LINE> <INDENT> validation = super(BuyShareForm, self).validate() <NEW_LINE> if(validation is False): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if(self.buyquantity is not None and self.buyquantity.data < 0): <NEW_LINE> <INDENT> self.buyquantity.errors.append("Quantity cannot be nagative") <NEW_LINE> validation = False <NEW_LINE> <DEDENT> return validation
Form for buying shares
6259903fa79ad1619776b2e4
class AbstractAnimatedIcon(qt.QObject): <NEW_LINE> <INDENT> def __init__(self, parent=None): <NEW_LINE> <INDENT> qt.QObject.__init__(self, parent) <NEW_LINE> self.__targets = silxweakref.WeakList() <NEW_LINE> self.__currentIcon = None <NEW_LINE> <DEDENT> iconChanged = qt.Signal(qt.QIcon) <NEW_LINE> def register(self, obj): <NEW_LINE> <INDENT> if obj not in self.__targets: <NEW_LINE> <INDENT> self.__targets.append(obj) <NEW_LINE> <DEDENT> self._updateState() <NEW_LINE> <DEDENT> def unregister(self, obj): <NEW_LINE> <INDENT> if obj in self.__targets: <NEW_LINE> <INDENT> self.__targets.remove(obj) <NEW_LINE> <DEDENT> self._updateState() <NEW_LINE> <DEDENT> def hasRegistredObjects(self): <NEW_LINE> <INDENT> return len(self.__targets) <NEW_LINE> <DEDENT> def isRegistered(self, obj): <NEW_LINE> <INDENT> return obj in self.__targets <NEW_LINE> <DEDENT> def currentIcon(self): <NEW_LINE> <INDENT> return self.__currentIcon <NEW_LINE> <DEDENT> def _updateState(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _setCurrentIcon(self, icon): <NEW_LINE> <INDENT> self.__currentIcon = icon <NEW_LINE> self.iconChanged.emit(self.__currentIcon)
Store an animated icon. It provides an event containing the new icon everytime it is updated.
6259903f0fa83653e46f613f
class BatchTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> import rf.batch <NEW_LINE> rf.batch.tqdm = lambda: None <NEW_LINE> <DEDENT> @unittest.skipIf(sys.platform.startswith("win"), "fails on Windows") <NEW_LINE> def test_entry_point(self): <NEW_LINE> <INDENT> ep_script = load_entry_point('rf', 'console_scripts', 'rf') <NEW_LINE> try: <NEW_LINE> <INDENT> with quiet(): <NEW_LINE> <INDENT> ep_script(['-h']) <NEW_LINE> <DEDENT> <DEDENT> except SystemExit: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> @unittest.skipIf(sys.platform.startswith("win"), "fails on Windows") <NEW_LINE> def test_batch_command_interface_Q(self): <NEW_LINE> <INDENT> test_format(self, 'Q') <NEW_LINE> <DEDENT> @unittest.skipIf(sys.platform.startswith("win"), "fails on Windows") <NEW_LINE> def test_batch_command_interface_SAC(self): <NEW_LINE> <INDENT> test_format(self, 'SAC') <NEW_LINE> <DEDENT> @unittest.skipIf(obspyh5 is None, 'obspyh5 not installed') <NEW_LINE> @unittest.skipIf(sys.platform.startswith("win"), "fails on Windows") <NEW_LINE> def test_batch_command_interface_H5(self): <NEW_LINE> <INDENT> test_format(self, 'H5') <NEW_LINE> <DEDENT> def test_plugin_option(self): <NEW_LINE> <INDENT> f = init_data('plugin', plugin='rf.tests.test_batch : gw_test') <NEW_LINE> self.assertEqual(f(nework=4, station=2), 42)
For now batch tests are not run on windows. See https://travis-ci.org/trichter/rf/jobs/589375488 for failures. The batch module has a low priority.
6259903fb830903b9686edac
class OrderByBasketRetrieveView(generics.RetrieveAPIView): <NEW_LINE> <INDENT> permission_classes = (IsAuthenticated,) <NEW_LINE> serializer_class = OrderSerializer <NEW_LINE> lookup_field = 'number' <NEW_LINE> queryset = Order.objects.all() <NEW_LINE> def dispatch(self, request, *args, **kwargs): <NEW_LINE> <INDENT> msg = 'The basket-order API view is deprecated. Use the order API (e.g. /api/v2/orders/<order-number>/).' <NEW_LINE> warnings.warn(msg, DeprecationWarning) <NEW_LINE> partner = request.site.siteconfiguration.partner <NEW_LINE> kwargs['number'] = OrderNumberGenerator().order_number_from_basket_id(partner, kwargs['basket_id']) <NEW_LINE> return super(OrderByBasketRetrieveView, self).dispatch(request, *args, **kwargs) <NEW_LINE> <DEDENT> def filter_queryset(self, queryset): <NEW_LINE> <INDENT> queryset = super(OrderByBasketRetrieveView, self).filter_queryset(queryset) <NEW_LINE> user = self.request.user <NEW_LINE> if not user.is_staff: <NEW_LINE> <INDENT> queryset = queryset.filter(user=user) <NEW_LINE> <DEDENT> return queryset
Allow the viewing of Orders by Basket.
6259903f07d97122c4217f04