code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class listenerThread(baseThread): <NEW_LINE> <INDENT> def __init__(self, quiet=False): <NEW_LINE> <INDENT> super().__init__(name='listener', quiet=quiet) <NEW_LINE> self.own_ip = None <NEW_LINE> self.sort = False <NEW_LINE> self.packet_info = dict() <NEW_LINE> <DEDENT> @property <NEW_LINE> def counted_hosts(self): <NEW_LINE> <INDENT> return len(self.packet_info) <NEW_LINE> <DEDENT> def _initSocket(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003)) <NEW_LINE> self.is_privileged = True <NEW_LINE> return sock <NEW_LINE> <DEDENT> except PermissionError: <NEW_LINE> <INDENT> log.error('no permissions for raw socket. listener stopped') <NEW_LINE> self.stop(True) <NEW_LINE> exit(-1) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> log.error('could not create socket for listener. listener stopped') <NEW_LINE> log.debug(e) <NEW_LINE> self.stop(True) <NEW_LINE> exit(-1) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self.dropPrivileges() <NEW_LINE> <DEDENT> <DEDENT> def run(self): <NEW_LINE> <INDENT> with self._initSocket() as listener: <NEW_LINE> <INDENT> if not self.stopped(): <NEW_LINE> <INDENT> log.info('Listening for incoming packets...') <NEW_LINE> <DEDENT> self.listener_ready.set() <NEW_LINE> while not self.stopped(): <NEW_LINE> <INDENT> raw_packet = listener.recv(65565) <NEW_LINE> eth_header = Ether(raw_packet[:14]) <NEW_LINE> eth_len = eth_header.length <NEW_LINE> if eth_header.type_id == 0x0800: <NEW_LINE> <INDENT> ip_header = IP(raw_packet[eth_len:eth_len+20]) <NEW_LINE> if ip_header.protocol_num == 0x01: <NEW_LINE> <INDENT> offset = ip_header.ip_ihl*4 <NEW_LINE> icmp_buffer = raw_packet[eth_len+offset:eth_len+offset+sizeof(ICMP)] <NEW_LINE> icmp_header = ICMP(icmp_buffer) <NEW_LINE> if icmp_header.type == 0x03: <NEW_LINE> <INDENT> if not self.own_ip: <NEW_LINE> <INDENT> self.own_ip = ip_header.dst_addr <NEW_LINE> <DEDENT> if self.own_ip == ip_header.src_addr: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> eth_src = int.from_bytes(eth_header.src, byteorder='big', signed=False) <NEW_LINE> packet_id = (ip_header.src << 48) + eth_src <NEW_LINE> if not packet_id in self.packet_info.keys(): <NEW_LINE> <INDENT> ip_str = ip_header.src_addr <NEW_LINE> mac_str = eth_header.src_addr <NEW_LINE> if self.sort: <NEW_LINE> <INDENT> log.debug('[*] Host up: {:<16} {}'.format(ip_str, mac_str)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log.info('[*] Host up: {:<16} {}'.format(ip_str, mac_str)) <NEW_LINE> <DEDENT> self.packet_info[packet_id] = (ip_str, mac_str)
Waits for packets to arrive and decodes them to check for 'ICMP: Port Unreachable'
62598f9e67a9b606de545dad
class EntryApi(ModelViewSet): <NEW_LINE> <INDENT> queryset = Entry.objects.all() <NEW_LINE> serializer_class = EntrySerializer <NEW_LINE> authentication_classes = (BearerTokenAuthentication,) <NEW_LINE> permission_classes = ( IsAuthenticated, )
Convert data to JSON format and vice versa
62598f9e8e71fb1e983bb89a
class Top: <NEW_LINE> <INDENT> def __init__(self, regwidth: int, blocks: Dict[str, IpBlock], instances: Dict[str, str], if_addrs: Dict[Tuple[str, Optional[str]], int], windows: List[Window], attrs: Dict[str, str]): <NEW_LINE> <INDENT> self.regwidth = regwidth <NEW_LINE> self.blocks = blocks <NEW_LINE> self.instances = instances <NEW_LINE> self.if_addrs = if_addrs <NEW_LINE> self.attrs = attrs <NEW_LINE> self.window_block = RegBlock(regwidth, ReggenParams()) <NEW_LINE> merged = [] <NEW_LINE> for full_if_name, addr in if_addrs.items(): <NEW_LINE> <INDENT> merged.append((addr, full_if_name)) <NEW_LINE> inst_name, if_name = full_if_name <NEW_LINE> assert inst_name in instances <NEW_LINE> block_name = instances[inst_name] <NEW_LINE> assert block_name in blocks <NEW_LINE> block = blocks[block_name] <NEW_LINE> assert block.bus_interfaces.has_interface(False, if_name) <NEW_LINE> <DEDENT> for window in sorted(windows, key=lambda w: w.offset): <NEW_LINE> <INDENT> merged.append((window.offset, window)) <NEW_LINE> self.window_block.add_window(window) <NEW_LINE> <DEDENT> self.block_instances = {} <NEW_LINE> offset = 0 <NEW_LINE> for base_addr, item in sorted(merged, key=lambda pr: pr[0]): <NEW_LINE> <INDENT> assert offset <= base_addr, item <NEW_LINE> if isinstance(item, Window): <NEW_LINE> <INDENT> addrsep = (regwidth + 7) // 8 <NEW_LINE> offset = item.next_offset(addrsep) <NEW_LINE> continue <NEW_LINE> <DEDENT> inst_name, if_name = item <NEW_LINE> block_name = instances[inst_name] <NEW_LINE> block = blocks[block_name] <NEW_LINE> lst = self.block_instances.setdefault(block_name, []) <NEW_LINE> if inst_name not in lst: <NEW_LINE> <INDENT> lst.append(inst_name) <NEW_LINE> <DEDENT> assert if_name in block.reg_blocks <NEW_LINE> reg_block = block.reg_blocks[if_name] <NEW_LINE> offset = base_addr + reg_block.offset
An object representing the entire chip, as seen by reggen. This contains instances of some blocks (possibly multiple instances of each block), starting at well-defined base addresses. It may also contain some windows. These are memories that don't have their own comportable IP (so aren't defined in a block), but still take up address space.
62598f9e7047854f4633f1c7
class Table: <NEW_LINE> <INDENT> PATH = os.path.dirname(os.path.realpath(__file__)) <NEW_LINE> TOP_FILE = PATH + '/table_top.obj' <NEW_LINE> LEGS_FILE = PATH + '/table_legs.obj' <NEW_LINE> TOP_TAG = 'Table_top' <NEW_LINE> LEGS_TAG = 'Table_legs' <NEW_LINE> def __init__(self, magoz, light_source, color): <NEW_LINE> <INDENT> self.__table_top = Shapes(magoz, light_source, self.TOP_FILE, color, self.TOP_TAG) <NEW_LINE> self.__table_legs = Shapes(magoz, light_source, self.LEGS_FILE, color, self.LEGS_TAG) <NEW_LINE> self.__shape_list = [self.__table_top, self.__table_legs] <NEW_LINE> <DEDENT> def build_shape(self, x, y, z): <NEW_LINE> <INDENT> self.__table_legs.build_shape(x, y, z) <NEW_LINE> self.__table_top.build_shape(x, y, z) <NEW_LINE> <DEDENT> def mull_points(self, mat): <NEW_LINE> <INDENT> self.__table_top.mull_points(mat) <NEW_LINE> self.__table_legs.mull_points(mat) <NEW_LINE> <DEDENT> def real_to_guf(self): <NEW_LINE> <INDENT> self.__table_legs.real_to_guf() <NEW_LINE> self.__table_top.real_to_guf() <NEW_LINE> <DEDENT> def get_middle(self): <NEW_LINE> <INDENT> a1, b1, c1 = self.__table_top.get_middle().get_points() <NEW_LINE> a2, b2, c2 = self.__table_legs.get_middle().get_points() <NEW_LINE> x = (a1 + a2) / 2 <NEW_LINE> y = (b1 + b2) / 2 <NEW_LINE> z = (c1 + c2) / 2 <NEW_LINE> return Point3D(x, y, z) <NEW_LINE> <DEDENT> def get_big_z(self): <NEW_LINE> <INDENT> return max(self.__table_legs.get_big_z(), self.__table_top.get_big_z()) <NEW_LINE> <DEDENT> def draw(self, canvas): <NEW_LINE> <INDENT> self.__shape_list.sort(key=lambda value: value.get_middle().z, reverse=True) <NEW_LINE> for shape in self.__shape_list: <NEW_LINE> <INDENT> shape.draw(canvas)
A class for displaying a 3D table.
62598f9e07f4c71912baf22f
class TwitterApi(object): <NEW_LINE> <INDENT> def __init__(self, config): <NEW_LINE> <INDENT> self._config = config <NEW_LINE> self._auth = tw.OAuthHandler( self._config['credentials']['consumer_key'], self._config['credentials']['consumer_secret']) <NEW_LINE> self._auth.set_access_token( self._config['credentials']['access_token'], self._config['credentials']['access_token_secret']) <NEW_LINE> self._api = tw.API(self._auth) <NEW_LINE> <DEDENT> @property <NEW_LINE> def auth(self): <NEW_LINE> <INDENT> return self._auth <NEW_LINE> <DEDENT> @property <NEW_LINE> def api(self): <NEW_LINE> <INDENT> return self._api <NEW_LINE> <DEDENT> def reauth(self, config=None): <NEW_LINE> <INDENT> if config is not None: <NEW_LINE> <INDENT> self._config = config <NEW_LINE> <DEDENT> self._auth = tw.OAuthHandler( self._config['credentials']['consumer_key'], self._config['credentials']['consumer_secret']) <NEW_LINE> self._auth.set_access_token( self._config['credentials']['access_token'], self._config['credentials']['access_token_secret']) <NEW_LINE> return self._api
Twitter auth info
62598f9e38b623060ffa8e76
class DoublePressContext(Subject): <NEW_LINE> <INDENT> __subject_events__ = (u'break_double_press', ) <NEW_LINE> @contextmanager <NEW_LINE> def breaking_double_press(self): <NEW_LINE> <INDENT> self._broke_double_press = False <NEW_LINE> yield <NEW_LINE> if not self._broke_double_press: <NEW_LINE> <INDENT> self.break_double_press() <NEW_LINE> <DEDENT> <DEDENT> def break_double_press(self): <NEW_LINE> <INDENT> self.notify_break_double_press() <NEW_LINE> self._broke_double_press = True
Determines the context of double press. Every double press element in the same scope can not be interleaved -- i.e. let buttons B1 and B2, the sequence press(B1), press(B2), press(B1) does not trigger a double press event regardless of how fast it happens.
62598f9e8a43f66fc4bf1f60
@attr.s(auto_attribs=True) <NEW_LINE> class AuthFunctionalUnit: <NEW_LINE> <INDENT> authentication: bool = attr.ib(default=False) <NEW_LINE> @classmethod <NEW_LINE> def from_bytes(cls, _bytes): <NEW_LINE> <INDENT> if len(_bytes) != 2: <NEW_LINE> <INDENT> raise ValueError( f"Authentication Functional Unit data should by 2 " f"bytes. Got: {_bytes}" ) <NEW_LINE> <DEDENT> last_byte = bool(_bytes[-1]) <NEW_LINE> return cls(authentication=last_byte) <NEW_LINE> <DEDENT> def to_bytes(self): <NEW_LINE> <INDENT> if self.authentication: <NEW_LINE> <INDENT> return b"\x07\x80" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None
Consists of 2 bytes. First byte encodes the number of unused bytes in the second byte. So really you just need to set the last bit to 0 to use authentication. In the green book they use the 0x07 as first byte and 0x80 as last byte. We will use this to not make it hard to look up. It is a bit weirdly defined in the Green Book. I interpret is as if the data exists it is the functional unit 0 (authentication). In examples in the Green Book they set 0x070x80 as exists.
62598f9e44b2445a339b685f
class BaseController(object): <NEW_LINE> <INDENT> def __init__(self, state, model): <NEW_LINE> <INDENT> self.state = state <NEW_LINE> self.control = self.state.control <NEW_LINE> self.model = model <NEW_LINE> self.init() <NEW_LINE> <DEDENT> def init(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _update(self): <NEW_LINE> <INDENT> for ev in pg.event.get(): <NEW_LINE> <INDENT> if self._handle_event(ev): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _handle_event(self, event): <NEW_LINE> <INDENT> if self.is_quit_event(event): <NEW_LINE> <INDENT> raise SystemExit <NEW_LINE> <DEDENT> return self.handle_event(event) <NEW_LINE> <DEDENT> def handle_event(self, event): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def register(self, name, *args, **kwargs): <NEW_LINE> <INDENT> return bool(self.model.register(name, *args, **kwargs)) <NEW_LINE> <DEDENT> def is_quit_event(self, event): <NEW_LINE> <INDENT> altf4_event = ( event.type == pg.KEYDOWN and event.key == pg.K_F4 and event.mod == pg.KMOD_LALT ) <NEW_LINE> pgquit_event = event.type == pg.QUIT <NEW_LINE> return altf4_event or pgquit_event
Base controller class for the MVC pattern implementation. Shouldn't be instanciated manually but subclassed then registered in a State class. A subclass of BaseController may override the following method: - **init**: called at initialization (default: do nothing) - **is_quit_event**: define what a quit event is (default: pygame.QUIT and Alt+f4) - **handle_event**: process a given event (default: do nothing) An instance has the following attributes: - **self.state**: the state that uses the controller - **self.control**: the game that uses the controller - **self.model**: the model associated with the controller
62598f9e07f4c71912baf230
class SlbDeletePort(Aliyunsdk): <NEW_LINE> <INDENT> def __init__(self,slbIp,listenPort,resultFormat=resultFormat): <NEW_LINE> <INDENT> Aliyunsdk.__init__(self) <NEW_LINE> self.listenPort = int(listenPort) <NEW_LINE> self.resultFormat = resultFormat <NEW_LINE> self.slbIp = slbIp <NEW_LINE> self.slballip = GetSlbIpAll() <NEW_LINE> self.slballip.run() <NEW_LINE> if not self.slbIp in self.slballip.iplist: <NEW_LINE> <INDENT> print('SLB IP: %s not exists' % self.slbIp) <NEW_LINE> os._exit(17) <NEW_LINE> <DEDENT> self.slbinfo = GetSlbInfo(slbIp) <NEW_LINE> self.slbinfo.run() <NEW_LINE> if self.listenPort not in self.slbinfo.listenerPorts: <NEW_LINE> <INDENT> raise SkipPort(self.listenPort) <NEW_LINE> <DEDENT> self.request = DeleteLoadBalancerListenerRequest() <NEW_LINE> self.request.set_accept_format(self.resultFormat) <NEW_LINE> self.request.set_LoadBalancerId(self.slbinfo.slbid) <NEW_LINE> self.request.set_ListenerPort(self.listenPort) <NEW_LINE> <DEDENT> def handling(self): <NEW_LINE> <INDENT> if u'RequestId' in self.result.keys(): <NEW_LINE> <INDENT> print('Port %s deleted' % self.listenPort) <NEW_LINE> <DEDENT> Aliyunsdk.handling(self)
把要删除的SLB IP和端口作为参数,生成该类的实例 一个实例只删除一个端口,多个端口需要多个实例
62598f9e442bda511e95c240
class User(BaseModel): <NEW_LINE> <INDENT> user_name = models.CharField(max_length=20) <NEW_LINE> user_pass = models.CharField(max_length=100) <NEW_LINE> user_mail = models.CharField(max_length=50) <NEW_LINE> user_addr = models.CharField(max_length=50) <NEW_LINE> user_tele = models.CharField(max_length=11) <NEW_LINE> user_code = models.CharField(max_length=10) <NEW_LINE> user_recv = models.CharField(max_length=20, default='') <NEW_LINE> objects = UserManager()
用户信息模型类
62598f9ea17c0f6771d5c020
class ModuleAwareNodeTransformer(ast.NodeTransformer): <NEW_LINE> <INDENT> def __init__(self, namespaces: Dict[str, Tuple[ast.AST, List[Union[ast.Import, ast.ImportFrom]]]]): <NEW_LINE> <INDENT> super(ModuleAwareNodeTransformer, self).__init__() <NEW_LINE> self.namespaces = namespaces <NEW_LINE> self.module_namespace: Optional[str] = None <NEW_LINE> self.module_imports: Optional[List[Union[ast.Import, ast.ImportFrom]]] = None <NEW_LINE> <DEDENT> @contextmanager <NEW_LINE> def rewriter(self, module_namespace: str, module_imports: List[Union[ast.Import, ast.ImportFrom]]): <NEW_LINE> <INDENT> self.module_namespace = module_namespace <NEW_LINE> self.module_imports = module_imports <NEW_LINE> try: <NEW_LINE> <INDENT> yield self <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self.module_namespace = None <NEW_LINE> self.module_imports = None
Base class for NodeTransformers which need module/global context.
62598f9e6e29344779b00441
class SimpleBoard(AbstractBoard, SEBinaryWorkload): <NEW_LINE> <INDENT> def __init__( self, clk_freq: str, processor: AbstractProcessor, memory: AbstractMemorySystem, cache_hierarchy: AbstractCacheHierarchy, ) -> None: <NEW_LINE> <INDENT> super().__init__( clk_freq=clk_freq, processor=processor, memory=memory, cache_hierarchy=cache_hierarchy, ) <NEW_LINE> <DEDENT> @overrides(AbstractBoard) <NEW_LINE> def _setup_board(self) -> None: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @overrides(AbstractBoard) <NEW_LINE> def has_io_bus(self) -> bool: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> @overrides(AbstractBoard) <NEW_LINE> def get_io_bus(self) -> IOXBar: <NEW_LINE> <INDENT> raise NotImplementedError( "SimpleBoard does not have an IO Bus. " "Use `has_io_bus()` to check this." ) <NEW_LINE> <DEDENT> @overrides(AbstractBoard) <NEW_LINE> def has_dma_ports(self) -> bool: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> @overrides(AbstractBoard) <NEW_LINE> def get_dma_ports(self) -> List[Port]: <NEW_LINE> <INDENT> raise NotImplementedError( "SimpleBoard does not have DMA Ports. " "Use `has_dma_ports()` to check this." ) <NEW_LINE> <DEDENT> @overrides(AbstractBoard) <NEW_LINE> def has_coherent_io(self) -> bool: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> @overrides(AbstractBoard) <NEW_LINE> def get_mem_side_coherent_io_port(self) -> Port: <NEW_LINE> <INDENT> raise NotImplementedError( "SimpleBoard does not have any I/O ports. Use has_coherent_io to " "check this." ) <NEW_LINE> <DEDENT> @overrides(AbstractBoard) <NEW_LINE> def _setup_memory_ranges(self) -> None: <NEW_LINE> <INDENT> memory = self.get_memory() <NEW_LINE> self.mem_ranges = [AddrRange(memory.get_size())] <NEW_LINE> memory.set_memory_range(self.mem_ranges)
This is an incredibly simple system. It contains no I/O, and will work only with a classic cache hierarchy setup. **Limitations** * Only supports SE mode You can run a binary executable via the `set_se_binary_workload` function.
62598f9e56b00c62f0fb2696
class IndirectArrayRegion(AbstractBufferRegion): <NEW_LINE> <INDENT> def __init__(self, region, size, component_count, component_stride): <NEW_LINE> <INDENT> self.region = region <NEW_LINE> self.size = size <NEW_LINE> self.count = component_count <NEW_LINE> self.stride = component_stride <NEW_LINE> self.array = self <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'IndirectArrayRegion(size=%d, count=%d, stride=%d)' % ( self.size, self.count, self.stride) <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> count = self.count <NEW_LINE> if not isinstance(index, slice): <NEW_LINE> <INDENT> elem = index // count <NEW_LINE> j = index % count <NEW_LINE> return self.region.array[elem * self.stride + j] <NEW_LINE> <DEDENT> start = index.start or 0 <NEW_LINE> stop = index.stop <NEW_LINE> step = index.step or 1 <NEW_LINE> if start < 0: <NEW_LINE> <INDENT> start = self.size + start <NEW_LINE> <DEDENT> if stop is None: <NEW_LINE> <INDENT> stop = self.size <NEW_LINE> <DEDENT> elif stop < 0: <NEW_LINE> <INDENT> stop = self.size + stop <NEW_LINE> <DEDENT> assert step == 1 or step % count == 0, 'Step must be multiple of component count' <NEW_LINE> data_start = (start // count) * self.stride + start % count <NEW_LINE> data_stop = (stop // count) * self.stride + stop % count <NEW_LINE> data_step = step * self.stride <NEW_LINE> value_step = step * count <NEW_LINE> data = self.region.array[:] <NEW_LINE> value = [0] * ((stop - start) // step) <NEW_LINE> stride = self.stride <NEW_LINE> for i in range(count): <NEW_LINE> <INDENT> value[i::value_step] = data[data_start + i:data_stop + i:data_step] <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def __setitem__(self, index, value): <NEW_LINE> <INDENT> count = self.count <NEW_LINE> if not isinstance(index, slice): <NEW_LINE> <INDENT> elem = index // count <NEW_LINE> j = index % count <NEW_LINE> self.region.array[elem * self.stride + j] = value <NEW_LINE> return <NEW_LINE> <DEDENT> start = index.start or 0 <NEW_LINE> stop = index.stop <NEW_LINE> step = index.step or 1 <NEW_LINE> if start < 0: <NEW_LINE> <INDENT> start = self.size + start <NEW_LINE> <DEDENT> if stop is None: <NEW_LINE> <INDENT> stop = self.size <NEW_LINE> <DEDENT> elif stop < 0: <NEW_LINE> <INDENT> stop = self.size + stop <NEW_LINE> <DEDENT> assert step == 1 or step % count == 0, 'Step must be multiple of component count' <NEW_LINE> data_start = (start // count) * self.stride + start % count <NEW_LINE> data_stop = (stop // count) * self.stride + stop % count <NEW_LINE> data = self.region.array[:] <NEW_LINE> if step == 1: <NEW_LINE> <INDENT> data_step = self.stride <NEW_LINE> value_step = count <NEW_LINE> for i in range(count): <NEW_LINE> <INDENT> data[data_start + i:data_stop + i:data_step] = value[i::value_step] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> data_step = (step // count) * self.stride <NEW_LINE> data[data_start:data_stop:data_step] = value <NEW_LINE> <DEDENT> self.region.array[:] = data <NEW_LINE> <DEDENT> def invalidate(self): <NEW_LINE> <INDENT> self.region.invalidate()
A mapped region in which data elements are not necessarily contiguous. This region class is used to wrap buffer regions in which the data must be accessed with some stride. For example, in an interleaved buffer this region can be used to access a single interleaved component as if the data was contiguous.
62598f9ed7e4931a7ef3be7e
class FlatteningPathLoader(TemplatePathLoader): <NEW_LINE> <INDENT> def __init__(self, *a, **kw): <NEW_LINE> <INDENT> self.keep_ext = kw.pop('keep_ext', True) <NEW_LINE> super(FlatteningPathLoader, self).__init__(*a, **kw) <NEW_LINE> <DEDENT> def load(self, *a, **kw): <NEW_LINE> <INDENT> tmpl = super(FlatteningPathLoader, self).load(*a, **kw) <NEW_LINE> name = os.path.basename(tmpl.name) <NEW_LINE> if not self.keep_ext: <NEW_LINE> <INDENT> name, ext = os.path.splitext(name) <NEW_LINE> <DEDENT> tmpl.name = name <NEW_LINE> return tmpl
I've seen this mode of using dust templates in a couple places, but really it's lazy and too ambiguous. It increases the chances of silent conflicts and makes it hard to tell which templates refer to which just by looking at the template code.
62598f9e10dbd63aa1c7099b
class ReturnContainer(): <NEW_LINE> <INDENT> def __init__(self, val=None): <NEW_LINE> <INDENT> self.val = val <NEW_LINE> <DEDENT> def seqEval(self): <NEW_LINE> <INDENT> raise ReturnCalled(self.val.staticEval())
Stuctural container of return statement in hdl
62598f9e236d856c2adc932c
class PacketCaptureParameters(Model): <NEW_LINE> <INDENT> _validation = { 'target': {'required': True}, 'storage_location': {'required': True}, } <NEW_LINE> _attribute_map = { 'target': {'key': 'target', 'type': 'str'}, 'bytes_to_capture_per_packet': {'key': 'bytesToCapturePerPacket', 'type': 'int'}, 'total_bytes_per_session': {'key': 'totalBytesPerSession', 'type': 'int'}, 'time_limit_in_seconds': {'key': 'timeLimitInSeconds', 'type': 'int'}, 'storage_location': {'key': 'storageLocation', 'type': 'PacketCaptureStorageLocation'}, 'filters': {'key': 'filters', 'type': '[PacketCaptureFilter]'}, } <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(PacketCaptureParameters, self).__init__(**kwargs) <NEW_LINE> self.target = kwargs.get('target', None) <NEW_LINE> self.bytes_to_capture_per_packet = kwargs.get('bytes_to_capture_per_packet', 0) <NEW_LINE> self.total_bytes_per_session = kwargs.get('total_bytes_per_session', 1073741824) <NEW_LINE> self.time_limit_in_seconds = kwargs.get('time_limit_in_seconds', 18000) <NEW_LINE> self.storage_location = kwargs.get('storage_location', None) <NEW_LINE> self.filters = kwargs.get('filters', None)
Parameters that define the create packet capture operation. All required parameters must be populated in order to send to Azure. :param target: Required. The ID of the targeted resource, only VM is currently supported. :type target: str :param bytes_to_capture_per_packet: Number of bytes captured per packet, the remaining bytes are truncated. Default value: 0 . :type bytes_to_capture_per_packet: int :param total_bytes_per_session: Maximum size of the capture output. Default value: 1073741824 . :type total_bytes_per_session: int :param time_limit_in_seconds: Maximum duration of the capture session in seconds. Default value: 18000 . :type time_limit_in_seconds: int :param storage_location: Required. :type storage_location: ~azure.mgmt.network.v2016_09_01.models.PacketCaptureStorageLocation :param filters: :type filters: list[~azure.mgmt.network.v2016_09_01.models.PacketCaptureFilter]
62598f9e85dfad0860cbf967
class AlbumForm(ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Album <NEW_LINE> fields = ['title', 'description', 'photos', 'cover', 'published'] <NEW_LINE> <DEDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> username = kwargs.pop('username') <NEW_LINE> super(AlbumForm, self).__init__(*args, **kwargs) <NEW_LINE> self.fields['photos'].queryset = Photo.objects.filter(user__username=username) <NEW_LINE> self.fields['cover'].queryset = Photo.objects.filter(user__username=username)
Form for an Album.
62598f9e66656f66f7d5a1d7
class TestCows(unittest.TestCase): <NEW_LINE> <INDENT> def __check_zero_free(self, array): <NEW_LINE> <INDENT> for i in range(0, len(array), 2): <NEW_LINE> <INDENT> elem = array[i:i + 2] <NEW_LINE> self.assertNotEqual(bytearray([0, 0]), elem) <NEW_LINE> <DEDENT> <DEDENT> def __create_buffer(self, length): <NEW_LINE> <INDENT> array = bytearray(length) <NEW_LINE> array[0] = 1 <NEW_LINE> for i in range(1, length): <NEW_LINE> <INDENT> array[i] = 3 * array[i - 1] % 19 <NEW_LINE> <DEDENT> return array <NEW_LINE> <DEDENT> def test_cows(self): <NEW_LINE> <INDENT> array = self.__create_buffer(1024) <NEW_LINE> original = array[:] <NEW_LINE> cows.cows_stuff(array) <NEW_LINE> self.__check_zero_free(array) <NEW_LINE> cows.cows_unstuff(array) <NEW_LINE> self.assertSequenceEqual(original[2:], array[2:]) <NEW_LINE> <DEDENT> def test_cows_padded(self): <NEW_LINE> <INDENT> array = self.__create_buffer(1023) <NEW_LINE> original = array[:] <NEW_LINE> cows.cows_stuff(array) <NEW_LINE> self.__check_zero_free(array) <NEW_LINE> cows.cows_unstuff(array) <NEW_LINE> self.assertSequenceEqual(original[2:], array[2:]) <NEW_LINE> <DEDENT> def test_cows_all_zeros(self): <NEW_LINE> <INDENT> array = bytearray([0, 0] * 512) <NEW_LINE> original = array[:] <NEW_LINE> cows.cows_stuff(array) <NEW_LINE> self.__check_zero_free(array) <NEW_LINE> expected = bytearray([0, 1] * 512) <NEW_LINE> self.assertSequenceEqual(expected, array) <NEW_LINE> cows.cows_unstuff(array) <NEW_LINE> self.assertSequenceEqual(original[2:], array[2:]) <NEW_LINE> <DEDENT> def test_cows_padded_all_zeros(self): <NEW_LINE> <INDENT> array = bytearray([0] * 1023) <NEW_LINE> original = array[:] <NEW_LINE> cows.cows_stuff(array) <NEW_LINE> self.__check_zero_free(array) <NEW_LINE> expected = bytearray([0, 1] * 510) + bytearray([0, 2, 0]) <NEW_LINE> self.assertSequenceEqual(expected, array) <NEW_LINE> cows.cows_unstuff(array) <NEW_LINE> self.assertSequenceEqual(original[2:], array[2:]) <NEW_LINE> <DEDENT> def test_cows_no_zeros(self): <NEW_LINE> <INDENT> array = bytearray([1, 1] * 512) <NEW_LINE> original = array[:] <NEW_LINE> cows.cows_stuff(array) <NEW_LINE> self.__check_zero_free(array) <NEW_LINE> expected = bytearray([2, 0]) + original[2:] <NEW_LINE> self.assertSequenceEqual(expected, array) <NEW_LINE> cows.cows_unstuff(array) <NEW_LINE> self.assertSequenceEqual(original[2:], array[2:]) <NEW_LINE> <DEDENT> def test_cows_padded_no_zeros(self): <NEW_LINE> <INDENT> array = bytearray([1] * 1023) <NEW_LINE> original = array[:] <NEW_LINE> cows.cows_stuff(array) <NEW_LINE> self.__check_zero_free(array) <NEW_LINE> expected = bytearray([2, 0]) + original[2:] <NEW_LINE> self.assertSequenceEqual(expected, array) <NEW_LINE> cows.cows_unstuff(array) <NEW_LINE> self.assertSequenceEqual(original[2:], array[2:])
Tests for the COWS functions.
62598f9e7d847024c075c1b6
@python_2_unicode_compatible <NEW_LINE> class Relationship(models.Model): <NEW_LINE> <INDENT> university_session = models.ForeignKey('mentorships.UniversitySession') <NEW_LINE> mentor = models.ForeignKey( 'mentorships.UserRole', related_name='mentor') <NEW_LINE> mentee = models.ForeignKey( 'mentorships.UserRole', related_name='mentee') <NEW_LINE> method = models.ForeignKey('universities.Method') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> unique_together = ('university_session', 'mentee') <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "{mentor} => {mentee}".format(mentor=self.mentor, mentee=self.mentee) <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if not self.id: <NEW_LINE> <INDENT> new_object = True <NEW_LINE> <DEDENT> super(Relationship, self).save(*args, **kwargs) <NEW_LINE> if new_object: <NEW_LINE> <INDENT> self.mentor.relationship = self <NEW_LINE> self.mentor.is_active = True <NEW_LINE> self.mentor.save() <NEW_LINE> self.mentee.relationship = self <NEW_LINE> self.mentee.is_active = True <NEW_LINE> self.mentee.save()
Allow `User` to have a variety of `Role`s per `UniversitySession`. All `Role` relationships will be recreated each `UniversitySession`.
62598f9e627d3e7fe0e06c90
class InvokerSignature: <NEW_LINE> <INDENT> def __init__(self, invoker_signature, sbus_arguments, sbus_annotations): <NEW_LINE> <INDENT> self.invokerSignature = invoker_signature <NEW_LINE> self.arguments = sbus_arguments <NEW_LINE> self.annotations = sbus_annotations
Contains information about Invoker signature and SBus arguments and annotations. Do not confuse with SBus.Signature.
62598f9ebd1bec0571e14fb6
class MacAddress: <NEW_LINE> <INDENT> def __init__(self, address): <NEW_LINE> <INDENT> self.address = address <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_string(cls, address_string): <NEW_LINE> <INDENT> if not _MAC_REGEX.match(address_string): <NEW_LINE> <INDENT> raise ValueError("'%s' does not appear to be a MAC address" % address_string) <NEW_LINE> <DEDENT> address = bytes(int(x, 16) for x in address_string.split(':')) <NEW_LINE> return cls(address) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> address_string = ":".join("%02x" % x for x in self.address) <NEW_LINE> return address_string <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.address == other.address <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(self.address) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "%s.from_string(\"%s\")" % (self.__class__.__name__, self.__str__())
Class for comparing mac addresses
62598f9ed268445f26639a76
class RungeKutta: <NEW_LINE> <INDENT> def __init__(self, function): <NEW_LINE> <INDENT> self.func = function <NEW_LINE> self.order = 4 <NEW_LINE> <DEDENT> def __call__(self, r, t, h): <NEW_LINE> <INDENT> k1 = h*self.func(r, t) <NEW_LINE> k2 = h*self.func(r + 0.5*k1, t + 0.5*h) <NEW_LINE> k3 = h*self.func(r + 0.5*k2, t + 0.5*h) <NEW_LINE> k4 = h*self.func(r + k3, t + h) <NEW_LINE> return (k1 + 2*k2 + 2*k3 + k4)/6
This class declares the Runge-Kutta object which can be used to solve systems of ODEs using the fourth order Runge-Kutta method. Symbols and parameters: 'function' is a user-defined function. 'r' is a scalar or vector passed to the Runge-Kutta method. 't' is the time 'h' is the time step
62598f9ed7e4931a7ef3be7f
class RAFT_IMAGE( ctypes.Structure ): <NEW_LINE> <INDENT> _fields_ = [ ( "data", RAFT_MATRIX ), ( "tl_x", ctypes.c_double ), ( "tl_y", ctypes.c_double ), ( "br_x", ctypes.c_double ),( "br_y", ctypes.c_double ) ]
A raft_image from raft:
62598f9e796e427e5384e579
class FileDel(generics.DestroyAPIView): <NEW_LINE> <INDENT> authentication_classes = (SessionAuthentication, BasicAuthentication, TokenAuthentication) <NEW_LINE> permission_classes = (IsAuthenticated, IsOwner) <NEW_LINE> model = UploadedFile <NEW_LINE> serializer_class = UploadedFileSerializer
Delete files by current user
62598f9efbf16365ca793e9f
class GazeboWorldEntryWidget(GenericUserEntryWidget): <NEW_LINE> <INDENT> def __init__(self, browser_button=True, placeholder_text=None, enabled=True, parent=None): <NEW_LINE> <INDENT> super(GazeboWorldEntryWidget, self).__init__("Gazebo world file", False, browser_button, placeholder_text, enabled, parent) <NEW_LINE> <DEDENT> def check_input_validity(self): <NEW_LINE> <INDENT> is_valid = self.check_file_validity(".world") <NEW_LINE> current_input = self.entry_edit_line.text() <NEW_LINE> self.update_valid_input(current_input, is_valid and current_input != "")
Widget specific to the input of a Gazebo's world file
62598f9e004d5f362081eef0
class Algorithm(object): <NEW_LINE> <INDENT> def initialize(self): <NEW_LINE> <INDENT> print('The Algorithm class is deprecated.') <NEW_LINE> self.iter_ = 0 <NEW_LINE> self.current_solution = None <NEW_LINE> <DEDENT> def callback(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def iterate(self, n=1): <NEW_LINE> <INDENT> for i in range(n): <NEW_LINE> <INDENT> self.iter_ += 1 <NEW_LINE> self.callback(self) <NEW_LINE> <DEDENT> return self.current_solution <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.initialize() <NEW_LINE> self.iterate() <NEW_LINE> self.cont() <NEW_LINE> self.at_exit() <NEW_LINE> return self.current_solution <NEW_LINE> <DEDENT> def cont(self): <NEW_LINE> <INDENT> while not self.stop_condition(self): <NEW_LINE> <INDENT> self.iterate() <NEW_LINE> <DEDENT> return self.current_solution <NEW_LINE> <DEDENT> def at_exit(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> print("Deprecation warning: use 'run' method instead.") <NEW_LINE> self.run()
Abstract class to define iterative algorithms. Attributes ---------- niterations : int Current iteration number. Methods ------- initialize : Set variables to initial state. run : performs the optimization until stop_condition is reached or Ctrl-C is pressed. next : perform one iteration and return current solution. callback : user-defined function to print status or save variables. cont : continue the optimization skipping initialiaztion.
62598f9e1f037a2d8b9e3ecd
class User(db.Model): <NEW_LINE> <INDENT> __tablename__ = "user" <NEW_LINE> id = db.Column(db.Integer, primary_key=True, autoincrement=True) <NEW_LINE> email = db.Column(db.String(255), unique=True, nullable=False) <NEW_LINE> registered_on = db.Column(db.DateTime, nullable=False) <NEW_LINE> admin = db.Column(db.Boolean, nullable=False, default=False) <NEW_LINE> public_id = db.Column(db.String(100), unique=True) <NEW_LINE> username = db.Column(db.String(50), unique=True) <NEW_LINE> password_hash = db.Column(db.String(100)) <NEW_LINE> @property <NEW_LINE> def password(self): <NEW_LINE> <INDENT> raise AttributeError('password: write-only field') <NEW_LINE> <DEDENT> @password.setter <NEW_LINE> def password(self, password): <NEW_LINE> <INDENT> self.password_hash = flask_bcrypt.generate_password_hash(password).decode('utf-8') <NEW_LINE> <DEDENT> def check_password(self, password): <NEW_LINE> <INDENT> return flask_bcrypt.check_password_hash(self.password_hash, password) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def encode_auth_token(user_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> payload = { 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=1, seconds=5), 'iat': datetime.datetime.utcnow(), 'sub': user_id } <NEW_LINE> return jwt.encode( payload, key, algorithm='HS256' ) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> return e <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def decode_auth_token(auth_token): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> payload = jwt.decode(auth_token, key) <NEW_LINE> is_blacklisted_token = BlacklistToken.check_blacklist(auth_token) <NEW_LINE> if is_blacklisted_token: <NEW_LINE> <INDENT> return 'Token blacklisted. Please log in again.' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return payload['sub'] <NEW_LINE> <DEDENT> <DEDENT> except jwt.ExpiredSignatureError: <NEW_LINE> <INDENT> return 'Signature expired. Please log in again.' <NEW_LINE> <DEDENT> except jwt.InvalidTokenError: <NEW_LINE> <INDENT> return 'Invalid token. Please log in again.' <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<User '{}'>".format(self.username)
User Model for storing user related details
62598f9e851cf427c66b80ae
class HTTPSTestCase(unittest.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> cls.server = HTTPServer(("localhost", 0), Handler) <NEW_LINE> ssl.wrap_socket = sslwrap(ssl.wrap_socket) <NEW_LINE> cls.server.socket = ssl.wrap_socket(cls.server.socket, certfile='./tests/server.pem', server_side=True) <NEW_LINE> cls.server_thread = threading.Thread(target=cls.server.serve_forever) <NEW_LINE> cls.server_thread.start() <NEW_LINE> time.sleep(1) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def tearDownClass(cls): <NEW_LINE> <INDENT> cls.server.shutdown() <NEW_LINE> cls.server.socket.close() <NEW_LINE> cls.server_thread.join()
Test case class that starts up a https server and exposes it via the `server` attribute. The testing server is only created in the setUpClass method so that multiple tests can use the same server instance. The server is started in a separate thread and once the tests are completed the server is shutdown and cleaned up.
62598f9e097d151d1a2c0e0e
class ActivityDiagramHandler(xml.sax.ContentHandler): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.CurrentData = "" <NEW_LINE> <DEDENT> def startElement(self, tag, attributes): <NEW_LINE> <INDENT> self.CurrentData = tag <NEW_LINE> if tag == "mxCell": <NEW_LINE> <INDENT> id = attributes.get("id") <NEW_LINE> parent = attributes.get("parent") <NEW_LINE> style = attributes.get("style") <NEW_LINE> if attributes.get("vertex") == "1": <NEW_LINE> <INDENT> value = attributes.get("value") <NEW_LINE> vertex = Vertex(id, value, parent, style) <NEW_LINE> activityDiagram.add_vertex(vertex) <NEW_LINE> if style == "ellipse;whiteSpace=wrap;html=1;aspect=fixed;": <NEW_LINE> <INDENT> activityDiagram.start_node = vertex <NEW_LINE> <DEDENT> <DEDENT> elif attributes.get("edge") == "1": <NEW_LINE> <INDENT> source = attributes.get("source") <NEW_LINE> target = attributes.get("target") <NEW_LINE> edge = Edge(id, parent, style, source, target) <NEW_LINE> activityDiagram.add_edge(edge) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def endElement(self, tag): <NEW_LINE> <INDENT> self.CurrentData = ""
CurentData is the type of tag the parser getting ActivityDiagram is the activity diagram being parsed
62598f9e56ac1b37e6301fd1
class ModifyPersonSampleRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.PersonId = None <NEW_LINE> self.Name = None <NEW_LINE> self.Description = None <NEW_LINE> self.Usages = None <NEW_LINE> self.FaceOperationInfo = None <NEW_LINE> self.TagOperationInfo = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.PersonId = params.get("PersonId") <NEW_LINE> self.Name = params.get("Name") <NEW_LINE> self.Description = params.get("Description") <NEW_LINE> self.Usages = params.get("Usages") <NEW_LINE> if params.get("FaceOperationInfo") is not None: <NEW_LINE> <INDENT> self.FaceOperationInfo = AiSampleFaceOperation() <NEW_LINE> self.FaceOperationInfo._deserialize(params.get("FaceOperationInfo")) <NEW_LINE> <DEDENT> if params.get("TagOperationInfo") is not None: <NEW_LINE> <INDENT> self.TagOperationInfo = AiSampleTagOperation() <NEW_LINE> self.TagOperationInfo._deserialize(params.get("TagOperationInfo"))
ModifyPersonSample请求参数结构体
62598f9e38b623060ffa8e78
class BoundConstraint(Constraint[D.T_memory, D.T_event, D.T_state]): <NEW_LINE> <INDENT> def __init__(self, evaluate_function: Callable[[D.T_memory, D.T_event, Optional[D.T_state]], float], inequality: str, bound: float, depends_on_next_state: bool = True) -> None: <NEW_LINE> <INDENT> self._evaluate_function = evaluate_function <NEW_LINE> self._inequality = inequality <NEW_LINE> self._bound = bound <NEW_LINE> self._depends_on_next_state = depends_on_next_state <NEW_LINE> assert inequality in ['<', '<=', '>', '>='] <NEW_LINE> inequality_functions = {'<': (lambda val, bnd: val < bnd), '<=': (lambda val, bnd: val <= bnd), '>': (lambda val, bnd: val > bnd), '>=': (lambda val, bnd: val >= bnd)} <NEW_LINE> self._check_function = inequality_functions[inequality] <NEW_LINE> <DEDENT> def check(self, memory: D.T_memory, action: D.T_event, next_state: Optional[D.T_state] = None) -> bool: <NEW_LINE> <INDENT> return self._check_function(self.evaluate(memory, action, next_state), self._bound) <NEW_LINE> <DEDENT> def _is_constraint_dependent_on_next_state_(self) -> bool: <NEW_LINE> <INDENT> return self._depends_on_next_state <NEW_LINE> <DEDENT> def evaluate(self, memory: D.T_memory, action: D.T_event, next_state: Optional[D.T_state] = None) -> float: <NEW_LINE> <INDENT> return self._evaluate_function(memory, action, next_state) <NEW_LINE> <DEDENT> def get_inequality(self) -> str: <NEW_LINE> <INDENT> return self._inequality <NEW_LINE> <DEDENT> def get_bound(self) -> float: <NEW_LINE> <INDENT> return self._bound <NEW_LINE> <DEDENT> def _cast(self, src_sub: List[Tree], dst_sub: List[Tree]): <NEW_LINE> <INDENT> def cast_evaluate_function(memory, action, next_state): <NEW_LINE> <INDENT> cast_memory = cast(memory, dst_sub[0], src_sub[0]) <NEW_LINE> cast_action = cast(action, dst_sub[1], src_sub[1]) <NEW_LINE> cast_next_state = cast(next_state, dst_sub[2], src_sub[2]) <NEW_LINE> return self._evaluate_function(cast_memory, cast_action, cast_next_state) <NEW_LINE> <DEDENT> return BoundConstraint(cast_evaluate_function, self._inequality, self._bound, self._depends_on_next_state)
A constraint characterized by an evaluation function, an inequality and a bound. # Example A BoundConstraint with inequality '>=' is checked if (and only if) its #BoundConstraint.evaluate() function returns a float greater than or equal to its bound.
62598f9e01c39578d7f12b64
class ManipulationUpdate(PermissionRequiredMixin, UpdateView): <NEW_LINE> <INDENT> model = Manipulation <NEW_LINE> template_name = 'manipulation_form.html' <NEW_LINE> template_object_name = 'process' <NEW_LINE> permission_required = "hypotheses.update_manipulation"
This view is for editing a Manipulation.
62598f9e7b25080760ed728d
class GenerateHamiltonInputUCT(GenerateHamiltonInputEPP): <NEW_LINE> <INDENT> _use_load_config = False <NEW_LINE> csv_column_headers = ['Input Plate', 'Input Well', 'Sample Name', 'Adapter Well'] <NEW_LINE> output_file_name = 'KAPA_MAKE_LIBRARIES.csv' <NEW_LINE> _max_nb_input_containers = 1 <NEW_LINE> _max_nb_output_containers = 1 <NEW_LINE> def _generate_csv_dict(self): <NEW_LINE> <INDENT> csv_dict = {} <NEW_LINE> for art in self.artifacts: <NEW_LINE> <INDENT> if art.type == 'Analyte': <NEW_LINE> <INDENT> output = self.process.outputs_per_input(art.id, Analyte=True) <NEW_LINE> if len(output) > 1: <NEW_LINE> <INDENT> raise InvalidStepError('Multiple outputs found for an input %s. ' 'This step is not compatible with replicates.' % art.name) <NEW_LINE> <DEDENT> row, column = art.location[1].split(":") <NEW_LINE> input_location = row + column <NEW_LINE> adapter_well = output[0].reagent_labels[0][3]+output[0].reagent_labels[0][2] <NEW_LINE> csv_line = [art.container.name, input_location, art.name, adapter_well] <NEW_LINE> csv_dict[art.location[1]] = csv_line <NEW_LINE> <DEDENT> <DEDENT> return csv_dict
"Generate a CSV containing the necessary information for the KAPA make libraries method
62598f9ebaa26c4b54d4f094
class ODMcomplexTypeDefinitionCity(object): <NEW_LINE> <INDENT> openapi_types = { 'value': 'str' } <NEW_LINE> attribute_map = { 'value': 'value' } <NEW_LINE> def __init__(self, value=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._value = None <NEW_LINE> self.discriminator = None <NEW_LINE> if value is not None: <NEW_LINE> <INDENT> self.value = value <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> return self._value <NEW_LINE> <DEDENT> @value.setter <NEW_LINE> def value(self, value): <NEW_LINE> <INDENT> self._value = value <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.openapi_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ODMcomplexTypeDefinitionCity): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ODMcomplexTypeDefinitionCity): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict()
NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually.
62598f9e4527f215b58e9ccb
class ZdSEmailValidator(EmailValidator): <NEW_LINE> <INDENT> message = _("Utilisez une adresse de courriel valide.") <NEW_LINE> def __call__(self, value, check_username_available=True): <NEW_LINE> <INDENT> value = force_text(value) <NEW_LINE> if not value or "@" not in value: <NEW_LINE> <INDENT> raise ValidationError(self.message, code=self.code) <NEW_LINE> <DEDENT> user_part, domain_part = value.rsplit("@", 1) <NEW_LINE> if not self.user_regex.match(user_part) or contains_utf8mb4(user_part): <NEW_LINE> <INDENT> raise ValidationError(self.message, code=self.code) <NEW_LINE> <DEDENT> blacklist = BannedEmailProvider.objects.values_list("provider", flat=True) <NEW_LINE> for provider in blacklist: <NEW_LINE> <INDENT> if "@{}".format(provider) in value.lower(): <NEW_LINE> <INDENT> raise ValidationError(_("Ce fournisseur ne peut pas être utilisé."), code=self.code) <NEW_LINE> <DEDENT> <DEDENT> user_count = User.objects.filter(email=value).count() <NEW_LINE> if check_username_available and user_count > 0: <NEW_LINE> <INDENT> raise ValidationError(_("Cette adresse courriel est déjà utilisée"), code=self.code) <NEW_LINE> <DEDENT> elif not check_username_available and user_count == 0: <NEW_LINE> <INDENT> raise ValidationError(_("Cette adresse courriel n'existe pas"), code=self.code) <NEW_LINE> <DEDENT> if domain_part and not self.validate_domain_part(domain_part): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> domain_part = domain_part.encode("idna").decode("ascii") <NEW_LINE> if self.validate_domain_part(domain_part): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> except UnicodeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> raise ValidationError(self.message, code=self.code)
Based on https://docs.djangoproject.com/en/1.8/_modules/django/core/validators/#EmailValidator Changed : - check if provider is not if blacklisted - check if email is not used by another user - remove whitelist check - add custom errors and translate them into French
62598f9e01c39578d7f12b65
class ServerException(Exception): <NEW_LINE> <INDENT> pass
服务器内部错误
62598f9eac7a0e7691f722f2
class TCPKeepAliveAdapter(SocketOptionsAdapter): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> socket_options = kwargs.pop('socket_options', SocketOptionsAdapter.default_options) <NEW_LINE> idle = kwargs.pop('idle', 60) <NEW_LINE> interval = kwargs.pop('interval', 20) <NEW_LINE> count = kwargs.pop('count', 5) <NEW_LINE> socket_options = socket_options + [ (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) ] <NEW_LINE> if getattr(socket, 'TCP_KEEPINTVL', None) is not None: <NEW_LINE> <INDENT> socket_options += [(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, interval)] <NEW_LINE> <DEDENT> elif sys.platform == 'darwin': <NEW_LINE> <INDENT> TCP_KEEPALIVE = getattr(socket, 'TCP_KEEPALIVE', 0x10) <NEW_LINE> socket_options += [(socket.IPPROTO_TCP, TCP_KEEPALIVE, interval)] <NEW_LINE> <DEDENT> if getattr(socket, 'TCP_KEEPCNT', None) is not None: <NEW_LINE> <INDENT> socket_options += [(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, count)] <NEW_LINE> <DEDENT> if getattr(socket, 'TCP_KEEPIDLE', None) is not None: <NEW_LINE> <INDENT> socket_options += [(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, idle)] <NEW_LINE> <DEDENT> super(TCPKeepAliveAdapter, self).__init__( socket_options=socket_options, **kwargs )
An adapter for requests that turns on TCP Keep-Alive by default. The adapter sets 4 socket options: - ``SOL_SOCKET`` ``SO_KEEPALIVE`` - This turns on TCP Keep-Alive - ``IPPROTO_TCP`` ``TCP_KEEPINTVL`` 20 - Sets the keep alive interval - ``IPPROTO_TCP`` ``TCP_KEEPCNT`` 5 - Sets the number of keep alive probes - ``IPPROTO_TCP`` ``TCP_KEEPIDLE`` 60 - Sets the keep alive time if the socket library has the ``TCP_KEEPIDLE`` constant The latter three can be overridden by keyword arguments (respectively): - ``idle`` - ``interval`` - ``count`` You can use this adapter like so:: >>> from requests_toolbelt.adapters import socket_options >>> tcp = socket_options.TCPKeepAliveAdapter(idle=120, interval=10) >>> s = requests.Session() >>> s.mount('http://', tcp)
62598f9e63d6d428bbee2599
class VersionInfo (object): <NEW_LINE> <INDENT> def __init__ (self, msg): <NEW_LINE> <INDENT> data = msg.data <NEW_LINE> verinfo = struct.unpack ('< 4B 2H I', data[:12]) <NEW_LINE> desc = data[12:].strip ('\x00') <NEW_LINE> (self.v_cpu, self.p_cpu, self.node_y, self.node_x, self.size, self.ver_num, self.time) = verinfo <NEW_LINE> self.desc = desc <NEW_LINE> self.ver_num /= 100.0
SC&MP/SARK version information as returned by the SVER command.
62598f9e56b00c62f0fb2698
class HelloApiView(APIView): <NEW_LINE> <INDENT> serializer_class = serializers.HelloSerializer <NEW_LINE> def get(self, request, format=None): <NEW_LINE> <INDENT> an_apiview = [ 'Uses HTTP methods as functions (get, post, patch, put, delete)', 'It is similar to a traditional Django View', 'Gives you the most control over your logic', 'Is mapped manually to URLs' ] <NEW_LINE> return Response({'message': 'Hello!', 'an_apiview': an_apiview}) <NEW_LINE> <DEDENT> def post(self, request): <NEW_LINE> <INDENT> serializer = serializers.HelloSerializer(data=request.data) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> name = serializer.data.get('name') <NEW_LINE> message = 'Hello {0}'.format(name) <NEW_LINE> return Response({'message': message}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST ) <NEW_LINE> <DEDENT> <DEDENT> def put(self, request, pk=None): <NEW_LINE> <INDENT> return Response({'method': 'put'}) <NEW_LINE> <DEDENT> def patch(self, request, pk=None): <NEW_LINE> <INDENT> return Response({'method': 'patch'}) <NEW_LINE> <DEDENT> def delete(self, request, pk=None): <NEW_LINE> <INDENT> return Response({'method': 'delete'})
Test API View.
62598f9e236d856c2adc932d
class SQSEnvelope(MessageBodyParser, MediaTypeAndContentParser): <NEW_LINE> <INDENT> def __init__(self, graph): <NEW_LINE> <INDENT> self.should_validate_md5 = graph.config.sqs_envelope.validate_md5 <NEW_LINE> <DEDENT> def parse_raw_message(self, consumer, raw_message): <NEW_LINE> <INDENT> message_id = self.parse_message_id(raw_message) <NEW_LINE> receipt_handle = self.parse_receipt_handle(raw_message) <NEW_LINE> attributes = raw_message.get("Attributes", {}) <NEW_LINE> approximate_receive_count = int(attributes.get("ApproximateReceiveCount", 1)) <NEW_LINE> body = self.parse_body(raw_message) <NEW_LINE> if self.should_validate_md5: <NEW_LINE> <INDENT> self.validate_md5(raw_message, body) <NEW_LINE> <DEDENT> message = self.parse_message(body) <NEW_LINE> media_type, content = self.parse_media_type_and_content(message) <NEW_LINE> return SQSMessage( consumer=consumer, content=content, media_type=media_type, message_id=message_id, receipt_handle=receipt_handle, approximate_receive_count=approximate_receive_count, ) <NEW_LINE> <DEDENT> def parse_message_id(self, raw_message): <NEW_LINE> <INDENT> return raw_message["MessageId"] <NEW_LINE> <DEDENT> def parse_receipt_handle(self, raw_message): <NEW_LINE> <INDENT> return raw_message["ReceiptHandle"] <NEW_LINE> <DEDENT> def parse_body(self, raw_message): <NEW_LINE> <INDENT> return raw_message["Body"] <NEW_LINE> <DEDENT> def validate_md5(self, raw_message, body): <NEW_LINE> <INDENT> expected_md5_of_body = raw_message["MD5OfBody"] <NEW_LINE> actual_md5_of_body = md5(body).hexdigest() <NEW_LINE> if expected_md5_of_body != actual_md5_of_body: <NEW_LINE> <INDENT> raise ValidationError("MD5 validation failed. Expected: {} Actual: {}".format( expected_md5_of_body, actual_md5_of_body, ))
Enveloping base class.
62598f9eb7558d5895463416
class StadsdeelViewSet(rest.DatapuntViewSet): <NEW_LINE> <INDENT> metadata_class = ExpansionMetadata <NEW_LINE> queryset = models.Stadsdeel.objects.all().order_by('id') <NEW_LINE> queryset_detail = models.Stadsdeel.objects.select_related( 'gemeente', ) <NEW_LINE> serializer_detail_class = serializers.StadsdeelDetail <NEW_LINE> serializer_class = serializers.Stadsdeel <NEW_LINE> filterset_fields = ('code',) <NEW_LINE> def get_object(self): <NEW_LINE> <INDENT> pk = self.kwargs['pk'] <NEW_LINE> if pk and len(pk) == 1: <NEW_LINE> <INDENT> obj = get_object_or_404(models.Stadsdeel, code=pk) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> obj = get_object_or_404(models.Stadsdeel, pk=pk) <NEW_LINE> <DEDENT> return obj
Stadsdeel Door de Amsterdamse gemeenteraad vastgestelde begrenzing van een stadsdeel, ressorterend onder een stadsdeelbestuur. [Stelselpedia] (https://www.amsterdam.nl/stelselpedia/gebieden-index/catalogus/stadsdeel/)
62598f9eeab8aa0e5d30bb6d
class Infinitum: <NEW_LINE> <INDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return other is Infinitum or isinstance(other, Infinitum) <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return other is not Infinitum and not isinstance(other, Infinitum)
An OSC "Infinitum" argument, typically referred to as an "Impulse" There is no value for the argument as its presence in an OSC message provides the only semantic meaning.
62598f9ef7d966606f747dcf
class MainHandler(webapp2.RequestHandler): <NEW_LINE> <INDENT> def write_form(self, error_username="",error_password="", error_validation="", error_email="", username="", email=""): <NEW_LINE> <INDENT> self.response.out.write(form % {"error_username": error_username, "error_password": error_password, "error_validation": error_validation, "error_email": error_email, "username": username, "email": email}) <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> self.write_form() <NEW_LINE> <DEDENT> def post(self): <NEW_LINE> <INDENT> have_error=False <NEW_LINE> user_name = self.request.get('username') <NEW_LINE> user_password = self.request.get('password') <NEW_LINE> user_verification = self.request.get('verify') <NEW_LINE> user_email = self.request.get('email') <NEW_LINE> error_username="" <NEW_LINE> error_password="" <NEW_LINE> error_validation="" <NEW_LINE> error_mail="" <NEW_LINE> if not valid_username(user_name): <NEW_LINE> <INDENT> error_username ="That is not a valid username" <NEW_LINE> have_error=True <NEW_LINE> <DEDENT> if not valid_password(user_password): <NEW_LINE> <INDENT> error_password = "That is not a valid password" <NEW_LINE> have_error=True <NEW_LINE> <DEDENT> elif user_password != user_verification: <NEW_LINE> <INDENT> error_validation = "The passwords do not match" <NEW_LINE> have_error=True <NEW_LINE> <DEDENT> if not valid_email(user_email): <NEW_LINE> <INDENT> error_email = "That is not a valid email." <NEW_LINE> have_error=True <NEW_LINE> <DEDENT> if have_error: <NEW_LINE> <INDENT> self.write_form(error_username, error_password, error_validation,error_mail, user_name, user_email) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> username = self.request.get('username') <NEW_LINE> self.redirect('/welcome?username=%s' % username)
Handles requests coming in to '/' (the root of our site) e.g. www.user-input.com/
62598f9e435de62698e9bbdc
class SVPAlreadyRedeemedException(SalesforceVoucherProxyException): <NEW_LINE> <INDENT> pass
The voucher has already been redeemed.
62598f9e627d3e7fe0e06c92
class _SimpleLayoutBase(Layout): <NEW_LINE> <INDENT> def __init__(self, **config): <NEW_LINE> <INDENT> Layout.__init__(self, **config) <NEW_LINE> self.clients = _ClientList() <NEW_LINE> <DEDENT> def clone(self, group): <NEW_LINE> <INDENT> c = Layout.clone(self, group) <NEW_LINE> c.clients = _ClientList() <NEW_LINE> return c <NEW_LINE> <DEDENT> def focus(self, client): <NEW_LINE> <INDENT> self.clients.current_client = client <NEW_LINE> self.group.layout_all() <NEW_LINE> <DEDENT> def focus_first(self): <NEW_LINE> <INDENT> return self.clients.focus_first() <NEW_LINE> <DEDENT> def focus_last(self): <NEW_LINE> <INDENT> return self.clients.focus_last() <NEW_LINE> <DEDENT> def focus_next(self, window): <NEW_LINE> <INDENT> return self.clients.focus_next(window) <NEW_LINE> <DEDENT> def focus_previous(self, window): <NEW_LINE> <INDENT> return self.clients.focus_previous(window) <NEW_LINE> <DEDENT> def previous(self): <NEW_LINE> <INDENT> if self.clients.current_client is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> client = self.focus_previous(self.clients.current_client) or self.focus_last() <NEW_LINE> self.group.focus(client, True) <NEW_LINE> <DEDENT> def next(self): <NEW_LINE> <INDENT> if self.clients.current_client is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> client = self.focus_next(self.clients.current_client) or self.focus_first() <NEW_LINE> self.group.focus(client, True) <NEW_LINE> <DEDENT> def add(self, client, offset_to_current=0): <NEW_LINE> <INDENT> return self.clients.add(client, offset_to_current) <NEW_LINE> <DEDENT> def remove(self, client): <NEW_LINE> <INDENT> return self.clients.remove(client) <NEW_LINE> <DEDENT> def info(self): <NEW_LINE> <INDENT> d = Layout.info(self) <NEW_LINE> d.update(self.clients.info()) <NEW_LINE> return d
Basic layout class for simple layouts, which need to maintain a single list of clients. This class offers full fledged list of clients and focus cycling. Basic Layouts like Max and Matrix are based on this class
62598f9ea8370b77170f01cb
@attrs(frozen=True) <NEW_LINE> class WattSample: <NEW_LINE> <INDENT> watts = attrib(type=float, converter=float) <NEW_LINE> moment = attrib(converter=datetime_coercion) <NEW_LINE> def settlement_period(self, period_class): <NEW_LINE> <INDENT> return period_class(moment=self.moment) <NEW_LINE> <DEDENT> @property <NEW_LINE> def killowatts(self): <NEW_LINE> <INDENT> return self.watts / 1000 <NEW_LINE> <DEDENT> @property <NEW_LINE> def megawatts(self): <NEW_LINE> <INDENT> return self.killowatts / 1000
A sample of the power being drawn. A measurement, in watts, of electrical power being drawn at a specific moment in time.
62598f9ed268445f26639a77
class MatchFilterError(Exception): <NEW_LINE> <INDENT> def __init__(self, value): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.value <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'MatchFilterError: ' + self.value
Default error for match-filter errors.
62598f9ea8ecb03325870ff5
class TestThermalSpeedLite: <NEW_LINE> <INDENT> def test_is_jitted(self): <NEW_LINE> <INDENT> assert is_jitted(thermal_speed_lite) <NEW_LINE> <DEDENT> @pytest.mark.parametrize( "inputs", [ dict(T=5 * u.eV, particle=Particle("p"), method="most_probable", ndim=3), dict(T=3000 * u.K, particle=Particle("e"), method="nrl", ndim=2), dict( T=5000 * u.K, particle=Particle("He+"), method="mean_magnitude", ndim=1 ), dict(T=1 * u.eV, particle=Particle("Ar+"), method="rms", ndim=3), ], ) <NEW_LINE> def test_normal_vs_lite_values(self, inputs): <NEW_LINE> <INDENT> T_unitless = inputs["T"].to(u.K, equivalencies=u.temperature_energy()).value <NEW_LINE> m_unitless = inputs["particle"].mass.value <NEW_LINE> coeff = thermal_speed_coefficients(method=inputs["method"], ndim=inputs["ndim"]) <NEW_LINE> lite = thermal_speed_lite(T=T_unitless, mass=m_unitless, coeff=coeff) <NEW_LINE> pylite = thermal_speed_lite.py_func(T=T_unitless, mass=m_unitless, coeff=coeff) <NEW_LINE> assert pylite == lite <NEW_LINE> normal = thermal_speed(**inputs) <NEW_LINE> assert np.isclose(normal.value, lite)
Test class for `thermal_speed_lite`.
62598f9e2ae34c7f260aaec9
class UENASSigProc(UESigProc): <NEW_LINE> <INDENT> TRACE = True <NEW_LINE> Dom = 'EMM' <NEW_LINE> Type = (2, 0) <NEW_LINE> Filter = None <NEW_LINE> Timer = None <NEW_LINE> Kwargs = {} <NEW_LINE> def __init__(self, ued, **kwargs): <NEW_LINE> <INDENT> self.UE = ued <NEW_LINE> self.MME = self.UE.MME <NEW_LINE> self.Name = self.__class__.__name__ <NEW_LINE> self._pdu = [] <NEW_LINE> self.Kwargs = cpdict(self.__class__.Kwargs) <NEW_LINE> for kw in kwargs: <NEW_LINE> <INDENT> if kw in self.Kwargs: <NEW_LINE> <INDENT> self.Kwargs[kw] = kwargs[kw] <NEW_LINE> <DEDENT> <DEDENT> self._state_prev = getattr(self.UE, self.Dom)['state'] <NEW_LINE> if self.Dom == 'ESM': <NEW_LINE> <INDENT> self._s1_struct = None <NEW_LINE> <DEDENT> self._log('DBG', 'instantiating procedure') <NEW_LINE> <DEDENT> def _log(self, logtype='DBG', msg=''): <NEW_LINE> <INDENT> self.UE._log(logtype, '[{0}: {1}] {2}'.format(self.Type, self.Name, msg)) <NEW_LINE> <DEDENT> def _trace(self, direction='UL', pdu=None): <NEW_LINE> <INDENT> if self.TRACE: <NEW_LINE> <INDENT> self._pdu.append( (time(), direction, pdu) ) <NEW_LINE> <DEDENT> self.UE._log('TRACE_NAS_{0}'.format(direction), pdu.show()) <NEW_LINE> if direction == 'DL': <NEW_LINE> <INDENT> self.UE._proc_out = self <NEW_LINE> <DEDENT> <DEDENT> def process(self, naspdu=None): <NEW_LINE> <INDENT> self._log('ERR', '[process] unsupported') <NEW_LINE> <DEDENT> def postprocess(self, proc=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def output(self): <NEW_LINE> <INDENT> self._log('ERR', '[output] unsupported') <NEW_LINE> return None <NEW_LINE> <DEDENT> def init_timer(self): <NEW_LINE> <INDENT> if self.Timer is not None: <NEW_LINE> <INDENT> self.TimerValue = getattr(self.UE, self.Timer, 10) <NEW_LINE> self.TimerStart = time() <NEW_LINE> self.TimerStop = self.TimerStart + self.TimerValue <NEW_LINE> <DEDENT> <DEDENT> def timeout(self): <NEW_LINE> <INDENT> self._log('WNG', 'timeout') <NEW_LINE> <DEDENT> def _end(self, state=None): <NEW_LINE> <INDENT> if self.UE.Proc[self.Dom] and self == self.UE.Proc[self.Dom][-1]: <NEW_LINE> <INDENT> self.UE.Proc[self.Dom].pop() <NEW_LINE> <DEDENT> if state: <NEW_LINE> <INDENT> getattr(self.UE, self.Dom)['state'] = state <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> getattr(self.UE, self.Dom)['state'] = self._state_prev
UE related NAS signalling procedure instance attributes: - Name: procedure name - Dom: procedure domain ('EMM' / 'ESM') - Type: (protocol discriminator, type) of the initiating message - Filter: list of (protocol discriminator, type) expected in response - Timer: name of the timer to be run when a response is expected - Kwargs: procedure configuration parameters, used during initialization - UE: reference to the UEd instance to which the procedure applies - MME: reference to the MMEd instance handling the UEd / ENBd instances - _nas_resp: NAS PDU to be responded by output() init args: - UEd instance - potential kwargs that must match the keys in the local .Kwargs attribute process(pdu=None): - process the NAS PDU received by the MME server from the eNB output(): - return the NAS PDU to be sent to the eNB within an S1AP structure, or None
62598f9e1f037a2d8b9e3ecf
class PGSE11Error(PyNanacoError): <NEW_LINE> <INDENT> pass
ご希望のチャージ金額は、チャージ可能限度額を超えています。
62598f9e3539df3088ecc09d
class RoleManager(base.ModelManager): <NEW_LINE> <INDENT> model_class = model.Role <NEW_LINE> foreign_key_name = 'role' <NEW_LINE> user_assoc = model.UserRoleAssociation <NEW_LINE> group_assoc = model.GroupRoleAssociation <NEW_LINE> def get(self, trans: ProvidesUserContext, decoded_role_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> role = (self.session().query(self.model_class) .filter(self.model_class.id == decoded_role_id).one()) <NEW_LINE> <DEDENT> except sqlalchemy_exceptions.MultipleResultsFound: <NEW_LINE> <INDENT> raise galaxy.exceptions.InconsistentDatabase('Multiple roles found with the same id.') <NEW_LINE> <DEDENT> except sqlalchemy_exceptions.NoResultFound: <NEW_LINE> <INDENT> raise galaxy.exceptions.RequestParameterInvalidException('No accessible role found with the id provided.') <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise galaxy.exceptions.InternalServerError(f"Error loading from the database.{unicodify(e)}") <NEW_LINE> <DEDENT> if not (trans.user_is_admin or trans.app.security_agent.ok_to_display(trans.user, role)): <NEW_LINE> <INDENT> raise galaxy.exceptions.RequestParameterInvalidException('No accessible role found with the id provided.') <NEW_LINE> <DEDENT> return role <NEW_LINE> <DEDENT> def list_displayable_roles(self, trans: ProvidesUserContext): <NEW_LINE> <INDENT> roles = [] <NEW_LINE> for role in trans.sa_session.query(Role).filter(Role.deleted == false()): <NEW_LINE> <INDENT> if trans.user_is_admin or trans.app.security_agent.ok_to_display(trans.user, role): <NEW_LINE> <INDENT> roles.append(role) <NEW_LINE> <DEDENT> <DEDENT> return roles <NEW_LINE> <DEDENT> def create_role(self, trans: ProvidesUserContext, role_definition_model) -> model.Role: <NEW_LINE> <INDENT> name = role_definition_model.name <NEW_LINE> description = role_definition_model.description <NEW_LINE> user_ids = role_definition_model.user_ids or [] <NEW_LINE> group_ids = role_definition_model.group_ids or [] <NEW_LINE> if trans.sa_session.query(Role).filter(Role.name == name).first(): <NEW_LINE> <INDENT> raise RequestParameterInvalidException(f"A role with that name already exists [{name}]") <NEW_LINE> <DEDENT> role_type = Role.types.ADMIN <NEW_LINE> role = Role(name=name, description=description, type=role_type) <NEW_LINE> trans.sa_session.add(role) <NEW_LINE> users = [trans.sa_session.query(model.User).get(trans.security.decode_id(i)) for i in user_ids] <NEW_LINE> groups = [trans.sa_session.query(model.Group).get(trans.security.decode_id(i)) for i in group_ids] <NEW_LINE> for user in users: <NEW_LINE> <INDENT> trans.app.security_agent.associate_user_role(user, role) <NEW_LINE> <DEDENT> for group in groups: <NEW_LINE> <INDENT> trans.app.security_agent.associate_group_role(group, role) <NEW_LINE> <DEDENT> trans.sa_session.flush() <NEW_LINE> return role
Business logic for roles.
62598f9ef7d966606f747dd0
class NnlsL2nz(NnlsL2): <NEW_LINE> <INDENT> def __call__(self, A, Y, rng=np.random, E=None): <NEW_LINE> <INDENT> sigma = (self.reg * A.max()) * np.sqrt((A > 0).mean(axis=0)) <NEW_LINE> sigma[sigma == 0] = 1 <NEW_LINE> return self._solve(A, Y, rng, E, sigma=sigma)
Non-negative least-squares with L2 regularization on nonzero components. Similar to `.LstsqL2nz`, except the output values are non-negative. If solving for non-negative **weights**, it is important that the intercepts of the post-population are also non-negative, since agents with negative intercepts will never be silent, affecting output accuracy.
62598f9e7d43ff24874272f6
class strlist(object): <NEW_LINE> <INDENT> _list = None <NEW_LINE> _str = None <NEW_LINE> def __init__(self, data=""): <NEW_LINE> <INDENT> if type(data) == str: <NEW_LINE> <INDENT> self._str = data <NEW_LINE> self._list = map(ord, self._str) <NEW_LINE> <DEDENT> elif type(data) in (list, tuple): <NEW_LINE> <INDENT> self._list = list(data) <NEW_LINE> self._str = ''.join(map(chr, self._list)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError('Expected str or [int]; got %(type)s' % { 'type': type(data), }) <NEW_LINE> <DEDENT> <DEDENT> def list(self): <NEW_LINE> <INDENT> return self._list <NEW_LINE> <DEDENT> def str(self): <NEW_LINE> <INDENT> return self._str <NEW_LINE> <DEDENT> def __cmp__(self, other): <NEW_LINE> <INDENT> if self._str == other: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return 1 <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return self._str.__hash__() <NEW_LINE> <DEDENT> def __nonzero__(self) : <NEW_LINE> <INDENT> if self._str: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> return 0 <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self._str
Evaluates and encodes a string for use as part of a DHCP packet.
62598f9e99cbb53fe6830cbb
class DateWidget(Widget): <NEW_LINE> <INDENT> def clean(self, value): <NEW_LINE> <INDENT> if not value: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return dateparse.parse_datetime(value) <NEW_LINE> <DEDENT> def render(self, value): <NEW_LINE> <INDENT> if not value: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return value.isoformat() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return dateparse.parse_datetime(value).isoformat()
Widget for converting date fields. Takes optional ``format`` parameter.
62598f9e851cf427c66b80b0
class LicenseDialog(QDialog): <NEW_LINE> <INDENT> def __init__(self, parent=None): <NEW_LINE> <INDENT> QDialog.__init__(self, parent) <NEW_LINE> self._ui = Ui_LicenseDialog() <NEW_LINE> self._ui.setupUi(self)
Dialog for displaying the license.
62598f9e38b623060ffa8e7a
class VF6_Ofast_autopar_gcc(VF): <NEW_LINE> <INDENT> def __init__(self, model, dx, dt=None, align=None): <NEW_LINE> <INDENT> super(VF6_Ofast_autopar_gcc, self).__init__(model, dx, dt, align) <NEW_LINE> self.fstep = libvf6_Ofast_autopar_gcc.vf6.step
VF6 with auto parallelization.
62598f9e45492302aabfc2c0
class FixedArrayStack(Stack): <NEW_LINE> <INDENT> def __init__(self, capacity=None): <NEW_LINE> <INDENT> self.capacity = capacity if capacity is not None else DEFAULT_CAPACITY <NEW_LINE> self.size = 0 <NEW_LINE> self.items = [] <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> i = 0 <NEW_LINE> while i < len(self.items): <NEW_LINE> <INDENT> yield self.items[i] <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self,index): <NEW_LINE> <INDENT> return self.items[index] <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.items) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'Stack[{}] = {}'.format(self.capacity, self.items) <NEW_LINE> <DEDENT> def push(self, x): <NEW_LINE> <INDENT> if self.size != self.capacity: <NEW_LINE> <INDENT> self.items.append(x) <NEW_LINE> self.size += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise StackException("This stack of size {} is full!".format(self.capacity)) <NEW_LINE> <DEDENT> <DEDENT> def pop(self): <NEW_LINE> <INDENT> if self.items: <NEW_LINE> <INDENT> elem, self.items = self.items[-1], self.items[:-1] <NEW_LINE> self.size -= 1 <NEW_LINE> return elem <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise StackException('Tried to pop() from an empty stack!') <NEW_LINE> <DEDENT> <DEDENT> def is_empty(self): <NEW_LINE> <INDENT> return not self.items <NEW_LINE> <DEDENT> def make_empty(self): <NEW_LINE> <INDENT> self.items = [] <NEW_LINE> self.size = 0
A list-based LIFO stack that raises a StackException on overflow/underflow.
62598f9e3539df3088ecc09e
class NeutronException(Exception): <NEW_LINE> <INDENT> message = _("An unknown exception occurred.") <NEW_LINE> def __init__(self, message=None, **kwargs): <NEW_LINE> <INDENT> if message: <NEW_LINE> <INDENT> self.message = message <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self._error_string = self.message % _safe_decode_dict(kwargs) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> self._error_string = self.message <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self._error_string
Base Neutron Exception. To correctly use this class, inherit from it and define a 'message' property. That message will get printf'd with the keyword arguments provided to the constructor.
62598f9e07f4c71912baf233
class MasterOfNature(Feature): <NEW_LINE> <INDENT> name = "Master of Nature" <NEW_LINE> source = "Cleric (Nature Domain)"
At 17th level, you gain the ability to command animals and plant creatures. While creatures are charmed by your Charm Animals and Plants feature, you can take a bonus action on your turn to verbally command what each of those creatures will do on its next turn.
62598f9e55399d3f0562630a
class LinkedQueue: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._queue = DoublyLinkedList() <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._queue) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self._queue) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '< %s object at %s >' % (self.__class__, hex(id(self))) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self._queue) <NEW_LINE> <DEDENT> def is_empty(self): <NEW_LINE> <INDENT> return self._queue.is_empty() <NEW_LINE> <DEDENT> def enqueue(self, e): <NEW_LINE> <INDENT> return self._queue.push_back(e) <NEW_LINE> <DEDENT> def dequeue(self): <NEW_LINE> <INDENT> if self.is_empty(): <NEW_LINE> <INDENT> raise EmptyQueueError <NEW_LINE> <DEDENT> return self._queue.pop_front() <NEW_LINE> <DEDENT> def first(self): <NEW_LINE> <INDENT> if self.is_empty(): <NEW_LINE> <INDENT> raise EmptyQueueError <NEW_LINE> <DEDENT> return self._queue.first()
FIFO Queue implementation using a doubly linked list for storage.
62598f9ee5267d203ee6b6f6
class ExhibitionModelFormTests(UserSetUp, TestCase): <NEW_LINE> <INDENT> def test_login(self): <NEW_LINE> <INDENT> form_data = { 'title': 'New exhibition', 'description': 'description goes here', 'released_at': timezone.now(), } <NEW_LINE> form = ExhibitionForm(data=form_data) <NEW_LINE> self.assertTrue(form.is_valid()) <NEW_LINE> self.assertRaises(IntegrityError, form.save) <NEW_LINE> <DEDENT> def test_validation(self): <NEW_LINE> <INDENT> form_data = { 'title': 'New exhibition', 'description': 'description goes here', 'released_at': timezone.now(), } <NEW_LINE> form = ExhibitionForm(data=form_data) <NEW_LINE> self.assertTrue(form.is_valid()) <NEW_LINE> self.assertEqual(form.instance.title, form_data['title']) <NEW_LINE> self.assertEqual(form.instance.description, form_data['description']) <NEW_LINE> form.instance.author_id = self.user.id <NEW_LINE> form.save() <NEW_LINE> self.assertEqual( Exhibition.objects.get(id=form.instance.id).title, 'New exhibition' ) <NEW_LINE> <DEDENT> def test_valid_release_date(self): <NEW_LINE> <INDENT> released_at = datetime(2010, 1, 1, 1, 1, 0, 0, timezone.get_default_timezone()) <NEW_LINE> form_data = { 'title': 'New exhibition', 'description': 'description goes here', 'released_at': released_at, } <NEW_LINE> form = ExhibitionForm(data=form_data) <NEW_LINE> self.assertTrue(form.is_valid()) <NEW_LINE> self.assertEqual(form.instance.title, form_data['title']) <NEW_LINE> self.assertEqual(form.instance.description, form_data['description']) <NEW_LINE> self.assertEqual(form.instance.released_at, form_data['released_at']) <NEW_LINE> form.instance.author_id = self.user.id <NEW_LINE> form.save() <NEW_LINE> self.assertEqual( Exhibition.objects.get(id=form.instance.id).released_at, released_at ) <NEW_LINE> <DEDENT> def test_invalid_release_date(self): <NEW_LINE> <INDENT> released_at = 4 <NEW_LINE> form_data = { 'title': 'New exhibition', 'description': 'description goes here', 'released_at': released_at, } <NEW_LINE> form = ExhibitionForm(data=form_data) <NEW_LINE> self.assertFalse(form.is_valid()) <NEW_LINE> self.assertEqual(form.instance.title, form_data['title']) <NEW_LINE> self.assertEqual(form.instance.description, form_data['description']) <NEW_LINE> form.instance.author_id = self.user.id <NEW_LINE> self.assertRaises(ValueError, form.save) <NEW_LINE> <DEDENT> def test_invalidation(self): <NEW_LINE> <INDENT> form_data = { 'title': 'New exhibition', } <NEW_LINE> form = ExhibitionForm(data=form_data) <NEW_LINE> self.assertFalse(form.is_valid()) <NEW_LINE> self.assertEqual(form.instance.title, form_data['title']) <NEW_LINE> self.assertRaises(ValueError, form.save)
model.ExhibitionForm tests.
62598f9e1b99ca400228f422
@register <NEW_LINE> class Uniform(Initializer): <NEW_LINE> <INDENT> def __init__(self, scale=0.07): <NEW_LINE> <INDENT> super(Uniform, self).__init__(scale=scale) <NEW_LINE> self.scale = scale <NEW_LINE> <DEDENT> def _init_weight(self, _, arr): <NEW_LINE> <INDENT> random.uniform(-self.scale, self.scale, out=arr)
Initializes weights with random values uniformly sampled from a given range. Parameters ---------- scale : float, optional The bound on the range of the generated random values. Values are generated from the range [-`scale`, `scale`]. Default scale is 0.07. Example ------- >>> # Given 'module', an instance of 'mxnet.module.Module', initialize weights >>> # to random values uniformly sampled between -0.1 and 0.1. ... >>> init = mx.init.Uniform(0.1) >>> module.init_params(init) >>> for dictionary in module.get_params(): ... for key in dictionary: ... print(key) ... print(dictionary[key].asnumpy()) ... fullyconnected0_weight [[ 0.01360891 -0.02144304 0.08511933]]
62598f9e57b8e32f52508010
class Pubkey(db.Model): <NEW_LINE> <INDENT> __tablename__ = "pubkeys" <NEW_LINE> id = db.Column(db.Integer(), primary_key=True) <NEW_LINE> string = db.Column(db.String()) <NEW_LINE> friends = db.relationship("Friend", backref="pubkey") <NEW_LINE> peers = db.relationship("Peer", backref="pubkey") <NEW_LINE> created = db.Column(db.DateTime(), default=db.func.now()) <NEW_LINE> def jsonify(self, peers=False, friends=False): <NEW_LINE> <INDENT> response = {} <NEW_LINE> response['string'] = self.string <NEW_LINE> response['created'] = time.mktime(self.created.timetuple()) <NEW_LINE> if peers: <NEW_LINE> <INDENT> response['peers'] = [_.jsonify() for _ in self.peers] <NEW_LINE> <DEDENT> if friends: <NEW_LINE> <INDENT> response['friends'] = [_.jsonify() for _ in self.friends] <NEW_LINE> <DEDENT> return response
We track public keys instead of specific remote nodes so people can move their private keys from device to device or network to network like with the cellular internet system and still be generally contactable as part of our friends list.
62598f9e0c0af96317c5616b
class LoginForm(Form): <NEW_LINE> <INDENT> name = StringField('Name', validators=[Required()]) <NEW_LINE> room = HiddenField() <NEW_LINE> submit = SubmitField('Enter Chatroom')
Accepts a nickname and a room.
62598f9eac7a0e7691f722f4
class ArgumentError(Exception): <NEW_LINE> <INDENT> pass
A problem with the supplied arguments to a class or function
62598f9eadb09d7d5dc0a373
class Database: <NEW_LINE> <INDENT> def __init__(self, db_name): <NEW_LINE> <INDENT> self.db = sqlite3.connect(f'{base_dir}/{db_name}') <NEW_LINE> <DEDENT> def add_table(self, table_name, **columns): <NEW_LINE> <INDENT> self.cols = "" <NEW_LINE> for col_name, col_type in columns.items(): <NEW_LINE> <INDENT> self.cols += col_name+" "+col_type+"," <NEW_LINE> <DEDENT> self.cols = self.cols[0:len(self.cols)-1] <NEW_LINE> self.db.execute("CREATE TABLE IF NOT EXISTS {}({})".format( table_name, self.cols)) <NEW_LINE> <DEDENT> def drop_table(self, table_name): <NEW_LINE> <INDENT> self.db.execute("DROP TABLE IF EXISTS {}".format( table_name)) <NEW_LINE> <DEDENT> def insert(self, table_name, *data): <NEW_LINE> <INDENT> self.data = "" <NEW_LINE> for value in data: <NEW_LINE> <INDENT> if value == "null": <NEW_LINE> <INDENT> self.data += ''+value.strip('"')+''+',' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.data += '"'+value.replace('"', '')+'"'+',' <NEW_LINE> <DEDENT> <DEDENT> self.data = self.data[0:len(self.data)-1] <NEW_LINE> self.db.execute("INSERT INTO {} values({})".format( table_name, self.data)) <NEW_LINE> self.db.commit() <NEW_LINE> <DEDENT> def remove(self, table_name, where="1"): <NEW_LINE> <INDENT> self.where = where <NEW_LINE> self.db.execute("DELETE FROM {} WHERE {}".format( table_name, self.where)) <NEW_LINE> self.db.commit() <NEW_LINE> <DEDENT> def drop(self, table_name): <NEW_LINE> <INDENT> self.db.execute("DROP TABLE IF EXISTS {}".format( table_name)) <NEW_LINE> self.db.commit() <NEW_LINE> <DEDENT> def get_items(self, table_name, where=1): <NEW_LINE> <INDENT> if(table_name != 1): <NEW_LINE> <INDENT> self.where = where <NEW_LINE> self.items = self.db.execute( "SELECT * FROM {} WHERE {}".format(table_name, self.where)) <NEW_LINE> self.db.commit() <NEW_LINE> return list(self.items) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> <DEDENT> def get_tables(self): <NEW_LINE> <INDENT> self.tables = self.db.execute("SELECT name FROM sqlite_master") <NEW_LINE> return list(self.tables) <NEW_LINE> <DEDENT> def query(self, query_string): <NEW_LINE> <INDENT> self.results = self.db.execute(query_string) <NEW_LINE> self.db.commit() <NEW_LINE> return self.results <NEW_LINE> <DEDENT> def close_connection(self): <NEW_LINE> <INDENT> self.db.close()
Class used to interact with sqlite database
62598f9eeab8aa0e5d30bb6f
class Directory(FSItem): <NEW_LINE> <INDENT> def __init__(self, path): <NEW_LINE> <INDENT> super().__init__(path) <NEW_LINE> if super().isfile(): <NEW_LINE> <INDENT> raise FileSystemError("file with name {0} already exists". format(self.path)) <NEW_LINE> <DEDENT> <DEDENT> def create(self): <NEW_LINE> <INDENT> if os.path.exists(self.path): <NEW_LINE> <INDENT> raise FileSystemError("Directory with name {0} already exists". format(self.path)) <NEW_LINE> <DEDENT> os.makedirs(self.path) <NEW_LINE> <DEDENT> def items(self): <NEW_LINE> <INDENT> yield self.files() <NEW_LINE> yield self.subdirectories() <NEW_LINE> <DEDENT> def files(self): <NEW_LINE> <INDENT> if not super().isdirectory(): <NEW_LINE> <INDENT> raise FileSystemError("directory with name {0} does not exists". format(self.path)) <NEW_LINE> <DEDENT> for path in os.listdir(self.path): <NEW_LINE> <INDENT> if os.path.isfile(os.path.join(self.path, path)): <NEW_LINE> <INDENT> yield File(os.path.join(self.path, path)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def subdirectories(self): <NEW_LINE> <INDENT> if not super().isdirectory(): <NEW_LINE> <INDENT> raise FileSystemError("directory with name {0} does not exists". format(self.path)) <NEW_LINE> <DEDENT> if os.path.exists ( self .path): <NEW_LINE> <INDENT> for name in os.listdir ( self .path): <NEW_LINE> <INDENT> if os.path.isdir (os.path.join ( self .path, name)): <NEW_LINE> <INDENT> yield Directory (os.path.join ( self .path, name)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def filesrecursive(self): <NEW_LINE> <INDENT> if not super().isdirectory(): <NEW_LINE> <INDENT> raise FileSystemError("directory with name {0} does not exists". format(self.path)) <NEW_LINE> <DEDENT> for root, dir, files in os.walk(self.path): <NEW_LINE> <INDENT> for file in files: <NEW_LINE> <INDENT> yield File(file) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def getsubdirectory(self, name): <NEW_LINE> <INDENT> if not os.path.isdir(os.path.join(self.path, name)): <NEW_LINE> <INDENT> raise FileSystemError("{0} is not a subdirectory". format(os.path.join(self.path, name))) <NEW_LINE> <DEDENT> return Directory(os.path.join(self.path, name))
Class for working with directories
62598f9e435de62698e9bbdd
class H0_mixed: <NEW_LINE> <INDENT> def __init__(self, Lp, Rp): <NEW_LINE> <INDENT> self.Lp = Lp <NEW_LINE> self.Rp = Rp <NEW_LINE> <DEDENT> def matvec(self, x): <NEW_LINE> <INDENT> x = x.split_legs(['(vL.vR)']) <NEW_LINE> x = npc.tensordot(self.Lp, x, axes=('vR', 'vL')) <NEW_LINE> x = npc.tensordot(x, self.Rp, axes=(['vR', 'wR'], ['vL', 'wL'])) <NEW_LINE> x = x.transpose(['vR*', 'vL*']) <NEW_LINE> x = x.iset_leg_labels(['vL', 'vR']) <NEW_LINE> x = x.combine_legs(['vL', 'vR']) <NEW_LINE> return (x)
Class defining the zero site Hamiltonian for Lanczos. Parameters ---------- Lp : :class:`tenpy.linalg.np_conserved.Array` left part of the environment Rp : :class:`tenpy.linalg.np_conserved.Array` right part of the environment Attributes ---------- Lp : :class:`tenpy.linalg.np_conserved.Array` left part of the environment Rp : :class:`tenpy.linalg.np_conserved.Array` right part of the environment
62598f9ef7d966606f747dd1
class BrHtmlImprover (HtmlImprover): <NEW_LINE> <INDENT> def _appendLineBreaks (self, text): <NEW_LINE> <INDENT> result = text <NEW_LINE> result = result.replace ("\n", "<br>") <NEW_LINE> opentags = r"[uod]l|hr|h\d|tr|td" <NEW_LINE> closetags = r"li|d[td]|t[rdh]|caption|thead|tfoot|tbody|colgroup|col|h\d" <NEW_LINE> remove_br_before = r"<br\s*/?>[\s\n]*(?=<(?:" + opentags + r")[ >])" <NEW_LINE> result = re.sub(remove_br_before, "", result, flags=re.I) <NEW_LINE> remove_br_after = r"(<(?:" + opentags + r")[ >]|</(?:" + closetags + r")>)[\s\n]*<br\s*/?>" <NEW_LINE> result = re.sub(remove_br_after, r"\1", result, flags=re.I) <NEW_LINE> append_eol_before = r"\n*(<li>|<h\d>|</?[uo]l>|<hr\s*/?>|<p>|</?table.*?>|</?tr.*?>|<td.*?>)" <NEW_LINE> result = re.sub(append_eol_before, "\n\\1", result, flags=re.I) <NEW_LINE> append_eol_after = r"(<hr\s*/?>|<br\s*/?>|</\s*h\d>|</\s*p>|</\s*ul>)\n*" <NEW_LINE> result = re.sub(append_eol_after, "\\1\n", result, flags=re.I) <NEW_LINE> return result
Class replace \n to <br>
62598f9ebe8e80087fbbee48
class Item(object): <NEW_LINE> <INDENT> sprite = "*" <NEW_LINE> def __init__(self, x, y): <NEW_LINE> <INDENT> self.pos_x = x <NEW_LINE> self.pos_y = y <NEW_LINE> <DEDENT> def tick(self): <NEW_LINE> <INDENT> raise NotImplementedError("tick not implemented") <NEW_LINE> <DEDENT> def get_sprite(self): <NEW_LINE> <INDENT> return self.sprite <NEW_LINE> <DEDENT> def get_position(self): <NEW_LINE> <INDENT> return self.pos_x, self.pos_y <NEW_LINE> <DEDENT> def event_discard(self): <NEW_LINE> <INDENT> raise NotImplementedError("event_discard not implemented") <NEW_LINE> <DEDENT> def is_hit(self, target): <NEW_LINE> <INDENT> raise NotImplementedError("is_hit not implemented") <NEW_LINE> <DEDENT> def can_hit(self): <NEW_LINE> <INDENT> raise NotImplementedError("can_hit not implemented") <NEW_LINE> <DEDENT> def move_up(self): <NEW_LINE> <INDENT> self.pos_y -= 1 <NEW_LINE> <DEDENT> def move_down(self): <NEW_LINE> <INDENT> self.pos_y += 1 <NEW_LINE> <DEDENT> def move_right(self): <NEW_LINE> <INDENT> self.pos_x += 1 <NEW_LINE> <DEDENT> def move_left(self): <NEW_LINE> <INDENT> self.pos_x -= 1
Base class for all elements in game
62598f9ebd1bec0571e14fb8
class ProductFactory(Factory): <NEW_LINE> <INDENT> name = Sequence(lambda n: 'Product {0}'.format(n)) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = models.Product
Product Factory
62598f9e009cb60464d0130e
@Registers.model <NEW_LINE> class DqnCnnPong(DqnCnn): <NEW_LINE> <INDENT> def create_model(self, model_info): <NEW_LINE> <INDENT> state = Input(shape=self.state_dim, dtype="int8") <NEW_LINE> state1 = Lambda(lambda x: K.cast(x, dtype='float32') / 255.)(state) <NEW_LINE> convlayer = Conv2D(32, (8, 8), strides=(4, 4), activation='relu', padding='valid')(state1) <NEW_LINE> convlayer = Conv2D(64, (4, 4), strides=(2, 2), activation='relu', padding='valid')(convlayer) <NEW_LINE> convlayer = Conv2D(64, (3, 3), strides=(1, 1), activation='relu', padding='valid')(convlayer) <NEW_LINE> flattenlayer = Flatten()(convlayer) <NEW_LINE> denselayer = Dense(256, activation='relu')(flattenlayer) <NEW_LINE> value = Dense(self.action_dim, activation='linear')(denselayer) <NEW_LINE> if self.dueling: <NEW_LINE> <INDENT> adv = Dense(1, activation='linear')(denselayer) <NEW_LINE> mean = Lambda(layer_normalize)(value) <NEW_LINE> value = Lambda(layer_add)([adv, mean]) <NEW_LINE> <DEDENT> model = Model(inputs=state, outputs=value) <NEW_LINE> adam = Adam(lr=self.learning_rate, clipnorm=10.) <NEW_LINE> model.compile(loss='mse', optimizer=adam) <NEW_LINE> if model_info.get("summary"): <NEW_LINE> <INDENT> model.summary() <NEW_LINE> <DEDENT> self.infer_state = tf.placeholder(tf.int8, name="infer_input", shape=(None, ) + tuple(self.state_dim)) <NEW_LINE> self.infer_v = model(self.infer_state) <NEW_LINE> self.actor_var = TFVariables([self.infer_v], self.sess) <NEW_LINE> self.sess.run(tf.initialize_all_variables()) <NEW_LINE> return model
Docstring for DqnPong.
62598f9e090684286d5935cf
class TestDump(DumpFaster): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> self.test_data_init() <NEW_LINE> <DEDENT> def test_free_space(self, file_path, free_limit): <NEW_LINE> <INDENT> _stat = statvfs(file_path) <NEW_LINE> _gb_free = _stat[0] * _stat[2] / 1024 ** 3 <NEW_LINE> return True if _gb_free > free_limit else False <NEW_LINE> <DEDENT> def test_build_archive(self, regex=False): <NEW_LINE> <INDENT> self.batch_files(queue=True, regex=regex) <NEW_LINE> self.files.gen_final_catalog(self.files.catalog_name, self.files.archive_list, self.paperdb.file_md5_dict) <NEW_LINE> <DEDENT> def test_data_init(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_dump_faster(self): <NEW_LINE> <INDENT> self.batch_size_mb = 15000 <NEW_LINE> self.tape_size = 1536000 <NEW_LINE> self.fast_batch()
move all the testing methods here to cleanup the production dump class
62598f9e24f1403a926857a7
class RunApiGuestUpgrade(RunApi): <NEW_LINE> <INDENT> def __init__(self, step_name: str = None): <NEW_LINE> <INDENT> super().__init__("guestUpgrade", step_name) <NEW_LINE> <DEDENT> def request(self): <NEW_LINE> <INDENT> return ( super() .request() .with_json( { "email": "$email", "password": "$password", "code": "$verify_code", } ) )
Implement api 'guestUpgrade'. Key-value pairs (required): - email: $email (str) - password: $password (str) - code: $verify_code (str) Key-value pairs (optional): - countryCode (str) - acceptMarketingEmail (int) - registerAppVersion (str)
62598f9e4e4d56256637220e
class NestAuth(AuthBase): <NEW_LINE> <INDENT> def __init__(self, token): <NEW_LINE> <INDENT> self.token = token <NEW_LINE> <DEDENT> def __call__(self, r): <NEW_LINE> <INDENT> r.headers={} <NEW_LINE> r.headers['Content-Type'] = 'application/json' <NEW_LINE> r.headers['Authorization'] = 'Bearer {}'.format(self.token) <NEW_LINE> return r
Attaches HTTP Pizza Authentication to the given Request object.
62598f9e442bda511e95c245
class ProcessNameParser(LineOnlyReceiver): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.result = '' <NEW_LINE> <DEDENT> def lineReceived(self, line): <NEW_LINE> <INDENT> if line: <NEW_LINE> <INDENT> self.result = line.strip()
Handler for the output lines returned from the cpu time command. After parsing, the ``result`` attribute will contain a dictionary mapping process names to elapsed CPU time. Process names may be truncated. A special process will be added indicating the wallclock time.
62598f9ed268445f26639a78
class BaseNetwork(nn.Module): <NEW_LINE> <INDENT> def __init__(self, cfg): <NEW_LINE> <INDENT> super(BaseNetwork, self).__init__() <NEW_LINE> self.cfg = cfg <NEW_LINE> '''load network blocks''' <NEW_LINE> for phase_name, net_spec in cfg.config['model'].items(): <NEW_LINE> <INDENT> method_name = net_spec['method'] <NEW_LINE> optim_spec = self.load_optim_spec(cfg.config, net_spec) <NEW_LINE> subnet = MODULES.get(method_name)(cfg.config, optim_spec) <NEW_LINE> self.add_module(phase_name, subnet) <NEW_LINE> '''load corresponding loss functions''' <NEW_LINE> setattr(self, phase_name + '_loss', LOSSES.get(self.cfg.config['model'][phase_name]['loss'], 'Null')( self.cfg.config['model'][phase_name].get('weight', 1))) <NEW_LINE> <DEDENT> '''freeze submodules or not''' <NEW_LINE> self.freeze_modules(cfg) <NEW_LINE> <DEDENT> def freeze_modules(self, cfg): <NEW_LINE> <INDENT> if cfg.config['mode'] == 'train': <NEW_LINE> <INDENT> freeze_layers = cfg.config['train']['freeze'] <NEW_LINE> for layer in freeze_layers: <NEW_LINE> <INDENT> if not hasattr(self, layer): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for param in getattr(self, layer).parameters(): <NEW_LINE> <INDENT> param.requires_grad = False <NEW_LINE> <DEDENT> cfg.log_string('The module: %s is fixed.' % (layer)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def set_mode(self): <NEW_LINE> <INDENT> freeze_layers = self.cfg.config['train']['freeze'] <NEW_LINE> for name, child in self.named_children(): <NEW_LINE> <INDENT> if name in freeze_layers: <NEW_LINE> <INDENT> child.train(False) <NEW_LINE> <DEDENT> <DEDENT> if self.cfg.config[self.cfg.config['mode']]['batch_size'] == 1: <NEW_LINE> <INDENT> for m in self.modules(): <NEW_LINE> <INDENT> if m._get_name().find('BatchNorm') != -1: <NEW_LINE> <INDENT> m.eval() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def load_weight(self, pretrained_model): <NEW_LINE> <INDENT> model_dict = self.state_dict() <NEW_LINE> pretrained_dict = {k: v for k, v in pretrained_model.items() if k in model_dict} <NEW_LINE> self.cfg.log_string( str(set([key.split('.')[0] for key in model_dict if key not in pretrained_dict])) + ' subnet missed.') <NEW_LINE> model_dict.update(pretrained_dict) <NEW_LINE> self.load_state_dict(model_dict) <NEW_LINE> <DEDENT> def load_optim_spec(self, config, net_spec): <NEW_LINE> <INDENT> if config['mode'] == 'train': <NEW_LINE> <INDENT> if 'optimizer' in net_spec.keys(): <NEW_LINE> <INDENT> optim_spec = net_spec['optimizer'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> optim_spec = config['optimizer'] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> optim_spec = None <NEW_LINE> <DEDENT> return optim_spec <NEW_LINE> <DEDENT> def forward(self, *args, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def loss(self, *args, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError
Base Network Module for other networks
62598f9edd821e528d6d8d1f
class WacomStylus(Structure): <NEW_LINE> <INDENT> _fields_ = [ ("id", c_int), ("name", c_char_p), ("num_buttons", c_int), ("has_eraser", c_bool), ("is_eraser", c_bool), ("has_lens", c_bool), ("has_wheel", c_bool), ("type", c_int), ("axes", c_int) ]
struct _WacomStylus { int id; char *name; int num_buttons; gboolean has_eraser; gboolean is_eraser; gboolean has_lens; gboolean has_wheel; WacomStylusType type; WacomAxisTypeFlags axes; };
62598f9e2c8b7c6e89bd35bb
class Settings(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.screen_width = 1200 <NEW_LINE> self.screen_height = 800 <NEW_LINE> self.bg_color = (230, 230, 230) <NEW_LINE> self.rocket_speed_factor = 1.5
A class to store all settings for Rocket Game.
62598f9e92d797404e388a5b
class RoleWidget(QtWidgets.QComboBox): <NEW_LINE> <INDENT> def __init__(self,name,exptConfigUi,parent=None): <NEW_LINE> <INDENT> super(RoleWidget, self).__init__() <NEW_LINE> self.name = name <NEW_LINE> self.exptConfigUi = exptConfigUi <NEW_LINE> self.onUpdate() <NEW_LINE> self.exptConfigUi.updateRoles.connect(self.onUpdate) <NEW_LINE> <DEDENT> @QtCore.pyqtSlot() <NEW_LINE> def onUpdate(self): <NEW_LINE> <INDENT> currentText=self.currentText() <NEW_LINE> self.clear() <NEW_LINE> self.addItem('') <NEW_LINE> hardwareList = self.exptConfigUi.roleDict.get(self.name) <NEW_LINE> if hardwareList: <NEW_LINE> <INDENT> self.addItems(hardwareList) <NEW_LINE> <DEDENT> self.setCurrentIndex( self.findText(currentText, QtCore.Qt.MatchExactly) ) <NEW_LINE> <DEDENT> def setToText(self, text): <NEW_LINE> <INDENT> index=self.findText(text, QtCore.Qt.MatchExactly) <NEW_LINE> self.setCurrentIndex(index)
Combo box for selecting what hardware to use for a specific software role
62598f9ed486a94d0ba2bdbf
class ARJoinMappingStruct(Structure): <NEW_LINE> <INDENT> _fields_ = [ ('schemaIndex', c_uint), ('realId', ARInternalId) ]
Join field mapping (ar.h line 5453).
62598f9e63d6d428bbee259c
class DesignNameMetric (Metric): <NEW_LINE> <INDENT> title = "Design Name" <NEW_LINE> align = 'left' <NEW_LINE> width = 25 <NEW_LINE> def load_cell(self, design, verbose=False): <NEW_LINE> <INDENT> name = design['path'][design.rep] <NEW_LINE> design.name = name <NEW_LINE> <DEDENT> def face_value(self, design): <NEW_LINE> <INDENT> return design.name
Make a column that just lists the name of each design.
62598f9e656771135c48946d
class Dialog(QObject): <NEW_LINE> <INDENT> show_dialog = pyqtSignal() <NEW_LINE> TOGGLE_DEPS = {} <NEW_LINE> TOGGLE_DEPS_INVERTED = [] <NEW_LINE> VOLATILE_WIDGETS = {} <NEW_LINE> WIDGET_NAMES = {} <NEW_LINE> GRAY = QBrush(Qt.gray) <NEW_LINE> def __init__(self, dialog): <NEW_LINE> <INDENT> QObject.__init__(self) <NEW_LINE> self.window = QDialog() <NEW_LINE> self.ui = dialog() <NEW_LINE> self.ui.setupUi(self.window) <NEW_LINE> self.window.setWindowFlags(Qt.WindowCloseButtonHint) <NEW_LINE> self.window.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) <NEW_LINE> self.window.setWindowIcon(ICON) <NEW_LINE> if 'button_box' in dir(self.ui): <NEW_LINE> <INDENT> self.ui.button_box.accepted.connect(self.ok) <NEW_LINE> self.ui.button_box.rejected.connect(self.cancel) <NEW_LINE> <DEDENT> self.signalmapper_toggles = QSignalMapper() <NEW_LINE> self.window.setWindowModality(Qt.ApplicationModal) <NEW_LINE> <DEDENT> def initialize(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def show(self, tab=0): <NEW_LINE> <INDENT> self.show_dialog.emit() <NEW_LINE> self.window.adjustSize() <NEW_LINE> self.window.show() <NEW_LINE> <DEDENT> def toggle_visibility(self, checkbox, widgets=[]): <NEW_LINE> <INDENT> if checkbox in self.TOGGLE_DEPS_INVERTED: <NEW_LINE> <INDENT> if checkbox.isChecked(): <NEW_LINE> <INDENT> for widget in widgets: <NEW_LINE> <INDENT> widget.hide() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for widget in widgets: <NEW_LINE> <INDENT> widget.show() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if checkbox.isChecked(): <NEW_LINE> <INDENT> for widget in widgets: <NEW_LINE> <INDENT> widget.show() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for widget in widgets: <NEW_LINE> <INDENT> widget.hide() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> @pyqtSlot(str) <NEW_LINE> def toggle(self, checkbox): <NEW_LINE> <INDENT> self.toggle_visibility(self.ui.__dict__[checkbox], self.TOGGLE_DEPS[self.ui.__dict__[checkbox]]) <NEW_LINE> self.window.adjustSize() <NEW_LINE> <DEDENT> def toggle_toggles(self): <NEW_LINE> <INDENT> for checkbox, widgets in self.TOGGLE_DEPS.items(): <NEW_LINE> <INDENT> self.toggle_visibility(checkbox, widgets) <NEW_LINE> self.signalmapper_toggles.setMapping(checkbox, checkbox.objectName()) <NEW_LINE> checkbox.toggled.connect(self.signalmapper_toggles.map) <NEW_LINE> checkbox.toggled.connect(self.window.adjustSize) <NEW_LINE> <DEDENT> self.signalmapper_toggles.mapped[str].connect(self.toggle) <NEW_LINE> <DEDENT> def fill_list(self, listwidget, config): <NEW_LINE> <INDENT> for configitem in sorted(config, key=str.lower): <NEW_LINE> <INDENT> listitem = QListWidgetItem(configitem) <NEW_LINE> if config[configitem].enabled is False: <NEW_LINE> <INDENT> listitem.setForeground(self.GRAY) <NEW_LINE> <DEDENT> listwidget.addItem(listitem) <NEW_LINE> <DEDENT> <DEDENT> @pyqtSlot() <NEW_LINE> def ok(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @pyqtSlot() <NEW_LINE> def cancel(self): <NEW_LINE> <INDENT> self.window.close()
one single dialog
62598f9e851cf427c66b80b2
class Capability(BaseEnum): <NEW_LINE> <INDENT> GET = ProtocolEvent.GET <NEW_LINE> SET = ProtocolEvent.SET <NEW_LINE> START_AUTOSAMPLE = ProtocolEvent.START_AUTOSAMPLE <NEW_LINE> STOP_AUTOSAMPLE = ProtocolEvent.STOP_AUTOSAMPLE <NEW_LINE> ACQUIRE_STATUS = ProtocolEvent.ACQUIRE_STATUS <NEW_LINE> START_LEVELING = ProtocolEvent.START_LEVELING <NEW_LINE> STOP_LEVELING = ProtocolEvent.STOP_LEVELING <NEW_LINE> START_HEATER = ProtocolEvent.START_HEATER <NEW_LINE> STOP_HEATER = ProtocolEvent.STOP_HEATER
Protocol events that should be exposed to users (subset of above).
62598f9e7047854f4633f1cd
class Personaje(object): <NEW_LINE> <INDENT> def __init__(self, nombre, clase, nivel, alineamiento, raza, sexo, edad, altura, peso, pelo, ojos, diox, manobuena, jugador, fue, des, con, intl, sab, car, asp, hon): <NEW_LINE> <INDENT> self.nombre = nombre <NEW_LINE> self.clase = clase <NEW_LINE> self.nivel = nivel <NEW_LINE> self.alineamiento = alineamiento <NEW_LINE> self.raza = raza <NEW_LINE> self.sexo = sexo <NEW_LINE> self.edad = edad <NEW_LINE> self.altura = altura <NEW_LINE> self.peso = peso <NEW_LINE> self.pelo = pelo <NEW_LINE> self.ojos = ojos <NEW_LINE> self.diox = diox <NEW_LINE> self.manobuena = manobuena <NEW_LINE> self.jugador = jugador <NEW_LINE> self.fue = fue <NEW_LINE> self.des = des <NEW_LINE> self.con = con <NEW_LINE> self.intl = intl <NEW_LINE> self.sab = sab <NEW_LINE> self.car = car <NEW_LINE> self.asp = asp <NEW_LINE> self.hon = hon
Este script crea la clase Personaje, que tendrá los atributos y características básicas comunes a todos los personajes.
62598f9e21a7993f00c65d6d
class DlopenFailedException(CouchbaseException): <NEW_LINE> <INDENT> pass
Failed to open shared object
62598f9e38b623060ffa8e7c
class ModuleTests(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> notify2.init("notify2 test suite") <NEW_LINE> <DEDENT> def test_init_uninit(self): <NEW_LINE> <INDENT> assert notify2.is_initted() <NEW_LINE> self.assertEqual(notify2.get_app_name(), "notify2 test suite") <NEW_LINE> notify2.uninit() <NEW_LINE> assert not notify2.is_initted() <NEW_LINE> <DEDENT> def test_get_server_info(self): <NEW_LINE> <INDENT> r = notify2.get_server_info() <NEW_LINE> assert isinstance(r, dict), type(r) <NEW_LINE> <DEDENT> def test_get_server_caps(self): <NEW_LINE> <INDENT> r = notify2.get_server_caps() <NEW_LINE> assert isinstance(r, list), type(r)
Test module level functions.
62598f9e596a897236127a65
class itkVTKImageToImageFilterIUL2(itkVTKImageImportPython.itkVTKImageImportIUL2): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __New_orig__(): <NEW_LINE> <INDENT> return _itkVTKImageToImageFilterPython.itkVTKImageToImageFilterIUL2___New_orig__() <NEW_LINE> <DEDENT> __New_orig__ = staticmethod(__New_orig__) <NEW_LINE> def SetInput(self, *args): <NEW_LINE> <INDENT> return _itkVTKImageToImageFilterPython.itkVTKImageToImageFilterIUL2_SetInput(self, *args) <NEW_LINE> <DEDENT> def GetExporter(self): <NEW_LINE> <INDENT> return _itkVTKImageToImageFilterPython.itkVTKImageToImageFilterIUL2_GetExporter(self) <NEW_LINE> <DEDENT> def GetImporter(self): <NEW_LINE> <INDENT> return _itkVTKImageToImageFilterPython.itkVTKImageToImageFilterIUL2_GetImporter(self) <NEW_LINE> <DEDENT> __swig_destroy__ = _itkVTKImageToImageFilterPython.delete_itkVTKImageToImageFilterIUL2 <NEW_LINE> def cast(*args): <NEW_LINE> <INDENT> return _itkVTKImageToImageFilterPython.itkVTKImageToImageFilterIUL2_cast(*args) <NEW_LINE> <DEDENT> cast = staticmethod(cast) <NEW_LINE> def GetPointer(self): <NEW_LINE> <INDENT> return _itkVTKImageToImageFilterPython.itkVTKImageToImageFilterIUL2_GetPointer(self) <NEW_LINE> <DEDENT> def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkVTKImageToImageFilterIUL2.__New_orig__() <NEW_LINE> import itkTemplate <NEW_LINE> itkTemplate.New(obj, *args, **kargs) <NEW_LINE> return obj <NEW_LINE> <DEDENT> New = staticmethod(New)
Proxy of C++ itkVTKImageToImageFilterIUL2 class
62598f9e91f36d47f2230d95
class Tabular(): <NEW_LINE> <INDENT> def __init__(self, h, A): <NEW_LINE> <INDENT> self.h = np.asarray(h) <NEW_LINE> self.A = np.asarray(A) <NEW_LINE> self.V = scipy.integrate.cumtrapz(h, A, initial=0.) <NEW_LINE> self.hmax = self.h.max() <NEW_LINE> self.hmin = self.h.min() <NEW_LINE> self.Amax = self.A.max() <NEW_LINE> self.A_interpolator = scipy.interpolate.interp1d(self.h, self.A) <NEW_LINE> self.V_interpolator = scipy.interpolate.interp1d(self.h, self.V) <NEW_LINE> <DEDENT> def A_sj(self, h): <NEW_LINE> <INDENT> hmax = self.hmax <NEW_LINE> hmin = self.hmin <NEW_LINE> _h = np.copy(h) <NEW_LINE> _h[_h < hmin] = hmin <NEW_LINE> _h[_h > hmax] = hmax <NEW_LINE> A = self.A_interpolator(_h) <NEW_LINE> return A <NEW_LINE> <DEDENT> def V_sj(self, h): <NEW_LINE> <INDENT> hmax = self.hmax <NEW_LINE> hmin = self.hmin <NEW_LINE> Amax = self.Amax <NEW_LINE> _h = np.copy(h) <NEW_LINE> _h[_h < hmin] = hmin <NEW_LINE> _h[_h > hmax] = hmax <NEW_LINE> r = np.maximum(h - _h, 0) <NEW_LINE> V = self.V_interpolator(_h) + (r * Amax) <NEW_LINE> return V
Class for computing tabular area/volume-depth relations at superjunctions. Inputs: ------- h : np.ndarray Depth points on depth-area profile (meters) A : np.ndarray Surface areas associated with each depth (square meters)
62598f9e63b5f9789fe84f60
class UnitTests(unittest.TestCase): <NEW_LINE> <INDENT> def test_insert(self): <NEW_LINE> <INDENT> database = MagicMock() <NEW_LINE> target, name, location, epiweek, value = 'ov_noro_broad', 'wiki', 'vi', 201820, 3.14 <NEW_LINE> SensorsTable(database=database).insert(target, name, location, epiweek, value) <NEW_LINE> self.assertEqual(database.execute.call_count, 1) <NEW_LINE> args, kwargs = database.execute.call_args <NEW_LINE> sql, args = args <NEW_LINE> self.assertEqual(sql, SensorsTable.SQL_INSERT) <NEW_LINE> <DEDENT> def test_get_most_recent_epiweek(self): <NEW_LINE> <INDENT> database = MagicMock() <NEW_LINE> target, name, location, epiweek = 'ov_noro_broad', 'ght', 'dc', 201820 <NEW_LINE> database.execute.return_value = [(epiweek,)] <NEW_LINE> table = SensorsTable(database=database) <NEW_LINE> returned_epiweek = table.get_most_recent_epiweek(target, name, location) <NEW_LINE> self.assertEqual(database.execute.call_count, 1) <NEW_LINE> args, kwargs = database.execute.call_args <NEW_LINE> sql, args = args <NEW_LINE> self.assertEqual(sql, SensorsTable.SQL_SELECT) <NEW_LINE> self.assertEqual(args, (target, name, location)) <NEW_LINE> self.assertEqual(returned_epiweek, epiweek) <NEW_LINE> <DEDENT> def test_get_connection_info(self): <NEW_LINE> <INDENT> username, password, database = SensorsTable()._get_connection_info() <NEW_LINE> self.assertIsInstance(username, str) <NEW_LINE> self.assertIsInstance(password, str) <NEW_LINE> self.assertIsInstance(database, str)
Basic unit tests.
62598f9e91af0d3eaad39bf5
class AbstractVote(models.Model): <NEW_LINE> <INDENT> review = models.ForeignKey('reviews.ProductReview', related_name='votes') <NEW_LINE> user = models.ForeignKey(AUTH_USER_MODEL, related_name='review_votes') <NEW_LINE> UP, DOWN = 1, -1 <NEW_LINE> VOTE_CHOICES = ( (UP, _("Up")), (DOWN, _("Down")) ) <NEW_LINE> delta = models.SmallIntegerField(_('Delta'), choices=VOTE_CHOICES) <NEW_LINE> date_created = models.DateTimeField(auto_now_add=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> ordering = ['-date_created'] <NEW_LINE> unique_together = (('user', 'review'),) <NEW_LINE> verbose_name = _('Vote') <NEW_LINE> verbose_name_plural = _('Votes') <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return u"%s vote for %s" % (self.delta, self.review) <NEW_LINE> <DEDENT> def clean(self): <NEW_LINE> <INDENT> if not self.review.is_anonymous and self.review.user == self.user: <NEW_LINE> <INDENT> raise ValidationError(_( "You cannot vote on your own reviews")) <NEW_LINE> <DEDENT> if not self.user.id: <NEW_LINE> <INDENT> raise ValidationError(_( "Only signed-in users can vote on reviews")) <NEW_LINE> <DEDENT> previous_votes = self.review.votes.filter(user=self.user) <NEW_LINE> if len(previous_votes) > 0: <NEW_LINE> <INDENT> raise ValidationError(_( "You can only vote once on a review")) <NEW_LINE> <DEDENT> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> super(AbstractVote, self).save(*args, **kwargs) <NEW_LINE> self.review.update_totals()
Records user ratings as yes/no vote. * Only signed-in users can vote. * Each user can vote only once.
62598f9ebe8e80087fbbee4a
class Locator(QObject): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> QObject.__init__(self) <NEW_LINE> self._thread = LocateThread() <NEW_LINE> self.connect(self._thread, SIGNAL("finished()"), self._load_results) <NEW_LINE> self.connect(self._thread, SIGNAL("finished()"), self._cleanup) <NEW_LINE> self.connect(self._thread, SIGNAL("terminated()"), self._cleanup) <NEW_LINE> <DEDENT> def _cleanup(self): <NEW_LINE> <INDENT> self._thread.wait() <NEW_LINE> <DEDENT> def navigate_to(self, function, filePath, isVariable): <NEW_LINE> <INDENT> self._thread.find(function, filePath, isVariable) <NEW_LINE> <DEDENT> def _load_results(self): <NEW_LINE> <INDENT> if len(self._thread.results) == 1: <NEW_LINE> <INDENT> main_container.MainContainer().open_file( filename=self._thread.results[0][1], cursorPosition=self._thread.results[0][2], positionIsLineNumber=True) <NEW_LINE> <DEDENT> elif len(self._thread.results) == 0: <NEW_LINE> <INDENT> QMessageBox.information(main_container.MainContainer(), self.tr("Definition Not Found"), self.tr("This Definition does not " "belong to this Project.")) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> misc_container.MiscContainer().show_results(self._thread.results) <NEW_LINE> <DEDENT> <DEDENT> def get_classes_from_project(self, projectPath): <NEW_LINE> <INDENT> global mapping_locations <NEW_LINE> filesFromProject = [filePath for filePath in mapping_locations if filePath.startswith( projectPath)] <NEW_LINE> classes = [item for key in filesFromProject for item in mapping_locations[key] if item[0] == FILTERS['classes']] <NEW_LINE> return classes
This class is used Go To Definition feature.
62598f9e435de62698e9bbe0
class JSONEncoder(_json.JSONEncoder): <NEW_LINE> <INDENT> def default(self, o): <NEW_LINE> <INDENT> if isinstance(o, datetime): <NEW_LINE> <INDENT> return http_date(o) <NEW_LINE> <DEDENT> if isinstance(o, uuid.UUID): <NEW_LINE> <INDENT> return str(o) <NEW_LINE> <DEDENT> if isinstance(o, decimal.Decimal): <NEW_LINE> <INDENT> return float(o) <NEW_LINE> <DEDENT> if hasattr(o, '__html__'): <NEW_LINE> <INDENT> return text_type(o.__html__()) <NEW_LINE> <DEDENT> return _json.JSONEncoder.default(self, o)
The default Flask JSON encoder. This one extends the default simplejson encoder by also supporting ``datetime`` objects, ``UUID`` as well as ``Markup`` objects which are serialized as RFC 822 datetime strings (same as the HTTP date format). In order to support more data types override the :meth:`default` method.
62598f9e45492302aabfc2c3
class AccountAcc(TypedDict): <NEW_LINE> <INDENT> acc: str <NEW_LINE> pAcc: str <NEW_LINE> uAcc: str <NEW_LINE> name: str <NEW_LINE> level: int <NEW_LINE> subAccs: List[str] <NEW_LINE> status: int
Python representation of a tuple or struct. Solidity compiler output does not include the names of structs that appear in method definitions. A tuple found in an ABI may have been written in Solidity as a literal, anonymous tuple, or it may have been written as a named `struct`:code:, but there is no way to tell from the compiler output. This class represents a tuple that appeared in a method definition. Its name is derived from a hash of that tuple's field names, and every method whose ABI refers to a tuple with that same list of field names will have a generated wrapper method that refers to this class. Any members of type `bytes`:code: should be encoded as UTF-8, which can be accomplished via `str.encode("utf_8")`:code:
62598f9e9b70327d1c57eb8a
class ArrConvertor(object): <NEW_LINE> <INDENT> def __init__(self, size=0, inner_conv=None): <NEW_LINE> <INDENT> self.size = size <NEW_LINE> self.inner_conv = inner_conv <NEW_LINE> <DEDENT> def set_size(self, size): <NEW_LINE> <INDENT> self.size = size <NEW_LINE> <DEDENT> def get_size(self): <NEW_LINE> <INDENT> return self.size <NEW_LINE> <DEDENT> def set_inner_convertor(self, inner_conv): <NEW_LINE> <INDENT> self.inner_conv = inner_conv <NEW_LINE> <DEDENT> def get_inner_convertor(self): <NEW_LINE> <INDENT> return self.inner_conv <NEW_LINE> <DEDENT> def get_byte_count(self): <NEW_LINE> <INDENT> if self.inner_conv is None: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.size * self.inner_conv.get_byte_count() <NEW_LINE> <DEDENT> <DEDENT> def from_bytes(self, b): <NEW_LINE> <INDENT> data = list() <NEW_LINE> for i in range(0, self.size): <NEW_LINE> <INDENT> data.append(self.inner_conv.from_bytes(b[self.inner_conv.get_byte_count()*i:self.inner_conv.get_byte_count()*(i+1)])) <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> def to_bytes(self, data): <NEW_LINE> <INDENT> b = bytes() <NEW_LINE> for item in data: <NEW_LINE> <INDENT> b += self.inner_conv.to_bytes(item) <NEW_LINE> <DEDENT> return b
classdocs
62598f9e66656f66f7d5a1dd
class TaskParamButton(QPushButton): <NEW_LINE> <INDENT> tp = None <NEW_LINE> def __init__(self, taskName='', parent=None): <NEW_LINE> <INDENT> super(TaskParamButton, self).__init__(parent) <NEW_LINE> name = ctaTaskPool.taskPool.getTask(taskName).setting.get('symbolList','None') <NEW_LINE> self.setText(str(name)) <NEW_LINE> self.setStyleSheet(STYLESHEET_STOP) <NEW_LINE> self.taskName = taskName <NEW_LINE> self.clicked.connect(self.buttonClicked) <NEW_LINE> <DEDENT> def buttonClicked(self): <NEW_LINE> <INDENT> filterList = ['name','className','mPrice','backtesting'] <NEW_LINE> kvList = ctaTaskPool.taskPool.getTask(self.taskName).setting.items() <NEW_LINE> param = dict([it for it in kvList if it[0] not in filterList]) <NEW_LINE> self.__class__.tp = TaskParamWidget(param) <NEW_LINE> self.__class__.tp.show()
查看参数按钮
62598f9e3eb6a72ae038a42d
class HubMixin(HubAccessMixin): <NEW_LINE> <INDENT> hub_model = Hub <NEW_LINE> hub_context_name = 'hub' <NEW_LINE> def get_hub_model(self): <NEW_LINE> <INDENT> return self.hub_model <NEW_LINE> <DEDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> kwargs.update({self.hub_context_name: self.get_hub()}) <NEW_LINE> return super(HubMixin, self).get_context_data(**kwargs) <NEW_LINE> <DEDENT> def get_object(self): <NEW_LINE> <INDENT> if hasattr(self, 'hub'): <NEW_LINE> <INDENT> return self.hub <NEW_LINE> <DEDENT> hub_slug = self.kwargs.get('hub_slug', None) <NEW_LINE> self.hub = get_object_or_404(self.get_hub_model(), slug=hub_slug) <NEW_LINE> return self.hub <NEW_LINE> <DEDENT> get_hub = get_object
Mixin used like a SingleObjectMixin to fetch an hub
62598f9e4e4d562566372210
class PylintQualityReporter(BaseQualityReporter): <NEW_LINE> <INDENT> COMMAND = 'pylint' <NEW_LINE> MODERN_OPTIONS = ['--msg-template="{path}:{line}: [{msg_id}({symbol}), {obj}] {msg}"'] <NEW_LINE> LEGACY_OPTIONS = ['-f', 'parseable', '--reports=no', '--include-ids=y'] <NEW_LINE> OPTIONS = MODERN_OPTIONS <NEW_LINE> EXTENSIONS = ['py'] <NEW_LINE> DUPE_CODE_VIOLATION = 'R0801' <NEW_LINE> VIOLATION_REGEX = re.compile(r'^([^:]+):(\d+): \[(\w+),? ?([^\]]*)] (.*)$') <NEW_LINE> MULTI_LINE_VIOLATION_REGEX = re.compile(r'==(\w|.+):(.*)') <NEW_LINE> DUPE_CODE_MESSAGE_REGEX = re.compile(r'Similar lines in (\d+) files') <NEW_LINE> def _run_command(self, src_path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return super(PylintQualityReporter, self)._run_command(src_path) <NEW_LINE> <DEDENT> except QualityReporterError as report_error: <NEW_LINE> <INDENT> if "no such option: --msg-template" in six.text_type(report_error): <NEW_LINE> <INDENT> self.OPTIONS = self.LEGACY_OPTIONS <NEW_LINE> return super(PylintQualityReporter, self)._run_command(src_path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _process_dupe_code_violation(self, lines, current_line, message): <NEW_LINE> <INDENT> src_paths = [] <NEW_LINE> message_match = self.DUPE_CODE_MESSAGE_REGEX.match(message) <NEW_LINE> if message_match: <NEW_LINE> <INDENT> for _ in range(int(message_match.group(1))): <NEW_LINE> <INDENT> current_line += 1 <NEW_LINE> match = self.MULTI_LINE_VIOLATION_REGEX.match( lines[current_line] ) <NEW_LINE> src_path, l_number = match.groups() <NEW_LINE> src_paths.append(('%s.py' % src_path, l_number)) <NEW_LINE> <DEDENT> <DEDENT> return src_paths <NEW_LINE> <DEDENT> def _parse_output(self, output, src_path=None): <NEW_LINE> <INDENT> violations_dict = defaultdict(list) <NEW_LINE> output_lines = output.split('\n') <NEW_LINE> for output_line_number, line in enumerate(output_lines): <NEW_LINE> <INDENT> match = self.VIOLATION_REGEX.match(line) <NEW_LINE> if match is not None: <NEW_LINE> <INDENT> (pylint_src_path, line_number, pylint_code, function_name, message) = match.groups() <NEW_LINE> if pylint_code == self.DUPE_CODE_VIOLATION: <NEW_LINE> <INDENT> files_involved = self._process_dupe_code_violation( output_lines, output_line_number, message ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> files_involved = [(pylint_src_path, line_number)] <NEW_LINE> <DEDENT> for violation in files_involved: <NEW_LINE> <INDENT> pylint_src_path, line_number = violation <NEW_LINE> if src_path is None or src_path == pylint_src_path: <NEW_LINE> <INDENT> if function_name: <NEW_LINE> <INDENT> error_str = u"{0}: {1}: {2}".format(pylint_code, function_name, message) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> error_str = u"{0}: {1}".format(pylint_code, message) <NEW_LINE> <DEDENT> violation = Violation(int(line_number), error_str) <NEW_LINE> violations_dict[pylint_src_path].append(violation) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return violations_dict
Report Pylint violations.
62598f9e097d151d1a2c0e14
class RPCError(Exception): <NEW_LINE> <INDENT> pass
Base class for all excetions thrown by :py:mod:`tinyrpc`.
62598f9e44b2445a339b6863
class VoiceActivityDetector(DataConsumer, DataProducer): <NEW_LINE> <INDENT> def __init__(self, silence_threshold=0.005, context_width=5, onset_threshold=5, ending_threshold=20): <NEW_LINE> <INDENT> super(VoiceActivityDetector, self).__init__() <NEW_LINE> self.silence_threshold=silence_threshold <NEW_LINE> self.context_width = context_width <NEW_LINE> self.onset_threshold = onset_threshold <NEW_LINE> self.ending_threshold = ending_threshold <NEW_LINE> self._silence_q = collections.deque(maxlen=context_width) <NEW_LINE> self._speech_q = collections.deque() <NEW_LINE> self.SILENCE = SilenceState(self, self._silence_q, self._speech_q) <NEW_LINE> self.ONSETTING = OnsettingState(self, self._silence_q, self._speech_q) <NEW_LINE> self.SPEAKING = SpeakingState(self, self._silence_q, self._speech_q) <NEW_LINE> self.ENDING = EndingState(self, self._silence_q, self._speech_q) <NEW_LINE> self._state = self.SILENCE <NEW_LINE> <DEDENT> def handle_frame(self, frame): <NEW_LINE> <INDENT> if frame['silence'] == True: <NEW_LINE> <INDENT> self._state.handle_silence_frame(frame) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._state.handle_speech_frame(frame) <NEW_LINE> <DEDENT> <DEDENT> def change_state(self, state): <NEW_LINE> <INDENT> self._state.exit() <NEW_LINE> self._state = state <NEW_LINE> self._state.enter() <NEW_LINE> <DEDENT> def evaluate(self, frame): <NEW_LINE> <INDENT> frame['silence'] = True if frame['rms'] < self.silence_threshold else False <NEW_LINE> frame['voiced'] = True if frame['zcr'] < 0.1 else False <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> frame = self.pop() <NEW_LINE> self.evaluate(frame) <NEW_LINE> self.handle_frame(frame)
A simple voice activity detection processor. Discards silence audio frames and enriches non-silent audio frames with voice activity information.
62598f9e45492302aabfc2c4