code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class projection: <NEW_LINE> <INDENT> def __init__(self, a_projection='epsg:2192'): <NEW_LINE> <INDENT> if not isinstance(a_projection, str): <NEW_LINE> <INDENT> raise ValueError("The projection parameter should be a string") <NEW_LINE> <DEDENT> self.projection = pyproj.Proj(init=a_projection) <NEW_LINE> <DEDENT> def lat_long_to_x_y(self, lat, lon): <NEW_LINE> <INDENT> return self.projection(lon, lat) <NEW_LINE> <DEDENT> def x_y_to_long_lat(self, x, y): <NEW_LINE> <INDENT> return self.projection(x, y, inverse=True) | Check if an object is float, int or long.
Args:
object to test
Returns:
True if is is as float, int or long, False otherwise | 6259905345492302aabfd9d7 |
class Flujo(models.Model): <NEW_LINE> <INDENT> nombre = models.CharField(max_length=30) <NEW_LINE> proyecto = models.ForeignKey(Proyecto) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.nombre <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> default_permissions = () <NEW_LINE> verbose_name = 'flujo' <NEW_LINE> verbose_name_plural = 'flujos' | Los flujos que forman parte de un proyecto. | 62599053379a373c97d9a523 |
class UnroutedNotificationDAO(dao.ESDAO): <NEW_LINE> <INDENT> __type__ = 'unrouted' <NEW_LINE> @classmethod <NEW_LINE> def example(cls): <NEW_LINE> <INDENT> from service.tests import fixtures <NEW_LINE> return cls(fixtures.NotificationFactory.unrouted_notification()) | DAO for UnroutedNotifications | 625990533c8af77a43b689bf |
class DefaultNBitQuantizeScheme(quantize_scheme.QuantizeScheme): <NEW_LINE> <INDENT> def __init__(self, disable_per_axis=False, num_bits_weight=8, num_bits_activation=8): <NEW_LINE> <INDENT> self._disable_per_axis = disable_per_axis <NEW_LINE> self._num_bits_weight = num_bits_weight <NEW_LINE> self._num_bits_activation = num_bits_activation <NEW_LINE> <DEDENT> def get_layout_transformer(self): <NEW_LINE> <INDENT> return default_n_bit_quantize_layout_transform.DefaultNBitQuantizeLayoutTransform( num_bits_weight=self._num_bits_weight, num_bits_activation=self._num_bits_activation) <NEW_LINE> <DEDENT> def get_quantize_registry(self): <NEW_LINE> <INDENT> return ( default_n_bit_quantize_registry.DefaultNBitQuantizeRegistry( disable_per_axis=self._disable_per_axis, num_bits_weight=self._num_bits_weight, num_bits_activation=self._num_bits_activation)) | Default N-Bit Scheme supported by TFLite. | 62599053dd821e528d6da3de |
class Options(usage.Options): <NEW_LINE> <INDENT> optParameters = [ ["admin", "a", "tcp:9001", "strports description of the admin API port."], ["port", "p", "tcp:9000", "strports description of the port for API connections."], ["config", "c", "config.json", "path to JSON configuration file."] ] <NEW_LINE> optFlags = [ ["mock", "m", "whether to use a mock back end instead of cassandra"] ] <NEW_LINE> def postOptions(self): <NEW_LINE> <INDENT> self.update({ 'regionOverrides': {}, 'cloudServersOpenStack': 'cloudServersOpenStack', 'cloudLoadBalancers': 'cloudLoadBalancers' }) <NEW_LINE> self.update(jsonfig.from_path(self['config'])) <NEW_LINE> if self.get('environment') == 'staging': <NEW_LINE> <INDENT> self['cloudServersOpenStack'] = 'cloudServersPreprod' <NEW_LINE> self['regionOverrides']['cloudLoadBalancers'] = 'STAGING' | Options for the otter-api node.
TODO: Force some common parameters in a base class.
TODO: Tracing support.
TODO: Debugging.
TODO: Environments.
TODO: Admin HTTP interface.
TODO: Specify store | 62599053a219f33f346c7d03 |
class GtkBaseBox(Gtk.Box): <NEW_LINE> <INDENT> def __init__(self, child, params, name, prev_page, next_page): <NEW_LINE> <INDENT> self.backwards_button = params['backwards_button'] <NEW_LINE> self.callback_queue = params['callback_queue'] <NEW_LINE> self.disable_tryit = params['disable_tryit'] <NEW_LINE> self.forward_button = params['forward_button'] <NEW_LINE> self.header = params['header'] <NEW_LINE> self.main_progressbar = params['main_progressbar'] <NEW_LINE> self.settings = params['settings'] <NEW_LINE> self.testing = params['testing'] <NEW_LINE> self.ui_dir = params['ui_dir'] <NEW_LINE> self.process_list = params['process_list'] <NEW_LINE> self.prev_page = prev_page <NEW_LINE> self.next_page = next_page <NEW_LINE> Gtk.Box.__init__(self) <NEW_LINE> self.set_name(name) <NEW_LINE> self.name = name <NEW_LINE> logging.debug("Loading '%s' screen", name) <NEW_LINE> self.ui = Gtk.Builder() <NEW_LINE> self.ui_file = os.path.join(self.ui_dir, "{}.ui".format(name)) <NEW_LINE> self.ui.add_from_file(self.ui_file) <NEW_LINE> self.ui.connect_signals(child) <NEW_LINE> child.add(self.ui.get_object(name)) <NEW_LINE> <DEDENT> def get_prev_page(self): <NEW_LINE> <INDENT> return self.prev_page <NEW_LINE> <DEDENT> def get_next_page(self): <NEW_LINE> <INDENT> return self.next_page <NEW_LINE> <DEDENT> def translate_ui(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def prepare(self, direction): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def store_values(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_name(self): <NEW_LINE> <INDENT> return self.name | Base class for our screens | 62599053a79ad1619776b53d |
class Send(Page): <NEW_LINE> <INDENT> form_model = 'group' <NEW_LINE> form_fields = ['sent_amount'] <NEW_LINE> def is_displayed(self): <NEW_LINE> <INDENT> return self.player.id_in_group == 1 | This page is only for P1
P1 sends amount (all, some, or none) to P2
This amount is tripled by experimenter,
i.e if sent amount by P1 is 5, amount received by P2 is 15 | 6259905326068e7796d4de47 |
class Camera(Camera): <NEW_LINE> <INDENT> camera = None <NEW_LINE> recording = False <NEW_LINE> record_splitter_port = 2 <NEW_LINE> recordings_folder = RecordingsFolder(get_env_recordings_path()) <NEW_LINE> @staticmethod <NEW_LINE> def frames(): <NEW_LINE> <INDENT> if not Camera.camera or Camera.camera.closed: <NEW_LINE> <INDENT> Camera.camera = picamera.PiCamera() <NEW_LINE> <DEDENT> Camera.camera.resolution = 1200, 900 <NEW_LINE> Camera.camera.framerate = 30 <NEW_LINE> time.sleep(2) <NEW_LINE> stream = io.BytesIO() <NEW_LINE> for _ in Camera.camera.capture_continuous(stream, 'jpeg', use_video_port=True): <NEW_LINE> <INDENT> Camera.camera.annotate_text = get_datetime_now_log_string() <NEW_LINE> stream.seek(0) <NEW_LINE> yield stream.read() <NEW_LINE> stream.seek(0) <NEW_LINE> stream.truncate() <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def record(): <NEW_LINE> <INDENT> record_thread = threading.Thread(target=Camera.record_thread) <NEW_LINE> record_thread.daemon = True <NEW_LINE> record_thread.start() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def record_thread(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> chunk = 60 * 5 <NEW_LINE> step = 0.5 <NEW_LINE> logging.info("Recording is on") <NEW_LINE> for _ in Camera.camera.record_sequence( (Camera.recordings_folder.get_next_chunk_path() for _ in range(10000000)), splitter_port=Camera.record_splitter_port): <NEW_LINE> <INDENT> Camera.recording = True <NEW_LINE> for i in range(int(chunk / step)): <NEW_LINE> <INDENT> if not Camera.recording: <NEW_LINE> <INDENT> Camera.stop_recording() <NEW_LINE> return <NEW_LINE> <DEDENT> Camera.camera.wait_recording(step, splitter_port=Camera.record_splitter_port) <NEW_LINE> <DEDENT> <DEDENT> Camera.stop_recording() <NEW_LINE> <DEDENT> except picamera.PiCameraAlreadyRecording as e: <NEW_LINE> <INDENT> logging.info(e) <NEW_LINE> <DEDENT> except AttributeError as e: <NEW_LINE> <INDENT> logging.info(e) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def stop_recording(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> Camera.camera.stop_recording(splitter_port=Camera.record_splitter_port) <NEW_LINE> <DEDENT> except picamera.PiCameraNotRecording as e: <NEW_LINE> <INDENT> logging.info(e) <NEW_LINE> <DEDENT> except AttributeError as e: <NEW_LINE> <INDENT> logging.info(e) <NEW_LINE> <DEDENT> Camera.recording = False <NEW_LINE> Camera.recordings_folder.needs_new_recording = True <NEW_LINE> logging.info("Recording is off") <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def is_recording(): <NEW_LINE> <INDENT> return Camera.recording | Raspberry Pi camera driver. | 62599053fff4ab517ebced21 |
class PendingServiceChainInsertions(object): <NEW_LINE> <INDENT> def __init__(self, context, node_stacks, chain_instance_id, provider_ptg_id, consumer_ptg_id, classifier_id): <NEW_LINE> <INDENT> self.context = context <NEW_LINE> self.node_stacks = node_stacks <NEW_LINE> self.chain_instance_id = chain_instance_id <NEW_LINE> self.provider_ptg_id = provider_ptg_id <NEW_LINE> self.consumer_ptg_id = consumer_ptg_id <NEW_LINE> self.classifier_id = classifier_id | Encapsulates a ServiceChain Insertion Operation | 6259905323e79379d538d9fb |
class HTKFeat_write(object): <NEW_LINE> <INDENT> def __init__(self, filename=None, veclen=13, sampPeriod=100000, paramKind = (MFCC | _O)): <NEW_LINE> <INDENT> self.veclen = veclen <NEW_LINE> self.sampPeriod = sampPeriod <NEW_LINE> self.sampSize = veclen * 4 <NEW_LINE> self.paramKind = paramKind <NEW_LINE> self.dtype = 'f' <NEW_LINE> self.filesize = 0 <NEW_LINE> self.swap = (unpack('=i', pack('>i', 42))[0] != 42) <NEW_LINE> if (filename != None): <NEW_LINE> <INDENT> self.openhtk(filename) <NEW_LINE> <DEDENT> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> self.close() <NEW_LINE> <DEDENT> def openhtk(self, filename): <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> self.fh = open(filename, "wb") <NEW_LINE> self.writeheader() <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.writeheader() <NEW_LINE> <DEDENT> def writeheader(self): <NEW_LINE> <INDENT> self.fh.seek(0,0) <NEW_LINE> self.fh.write(pack(">IIHH", self.filesize, self.sampPeriod, self.sampSize, self.paramKind)) <NEW_LINE> <DEDENT> def writevec(self, vec): <NEW_LINE> <INDENT> if len(vec) != self.veclen: <NEW_LINE> <INDENT> raise Exception("Vector length must be %d" % self.veclen) <NEW_LINE> <DEDENT> if self.swap: <NEW_LINE> <INDENT> numpy.array(vec, self.dtype).byteswap().tofile(self.fh) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> numpy.array(vec, self.dtype).tofile(self.fh) <NEW_LINE> <DEDENT> self.filesize = self.filesize + self.veclen <NEW_LINE> <DEDENT> def writeall(self, arr): <NEW_LINE> <INDENT> for row in arr: <NEW_LINE> <INDENT> self.writevec(row) | Write Sphinx-II format feature files | 62599053baa26c4b54d507a3 |
class FileFormatError(Exception): <NEW_LINE> <INDENT> pass | Error raised when a problem is encountered parsing a file | 625990534e696a045264e8a2 |
class Identify(OAIItem): <NEW_LINE> <INDENT> def __init__(self, identify_response): <NEW_LINE> <INDENT> super(Identify, self).__init__(identify_response.xml, strip_ns=True) <NEW_LINE> self.xml = self.xml.find('.//' + self._oai_namespace + 'Identify') <NEW_LINE> self._identify_dict = xml_to_dict(self.xml, strip_ns=True) <NEW_LINE> for k, v in self._identify_dict.items(): <NEW_LINE> <INDENT> setattr(self, k.replace('-', '_'), v[0]) <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Identify>' <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self._identify_dict.iteritems() | Represents an Identify container.
This object differs from the other entities in that is has to be created
from a :class:`sickle.app.OAIResponse` instead of an XML element.
:param identify_response: The response for an Identify request.
:type identify_response: :class:`sickle.app.OAIResponse` | 625990537cff6e4e811b6f40 |
class TimestampedTemporaryUploadedFile(TemporaryUploadedFile): <NEW_LINE> <INDENT> def __init__(self, name, content_type, size, charset, content_type_extra=None): <NEW_LINE> <INDENT> timestamp_suffix = str(int(time.time())) + '.' <NEW_LINE> suffix = '.tmp.' + content_type_to_ext(content_type) <NEW_LINE> if settings.FILE_UPLOAD_TEMP_DIR: <NEW_LINE> <INDENT> file = tempfile.NamedTemporaryFile(prefix=timestamp_suffix, suffix=suffix, dir=settings.FILE_UPLOAD_TEMP_DIR, delete=False) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> file = tempfile.NamedTemporaryFile(prefix=timestamp_suffix, suffix=suffix, delete=False) <NEW_LINE> <DEDENT> super(TemporaryUploadedFile, self).__init__(file, name, content_type, size, charset, content_type_extra) <NEW_LINE> <DEDENT> def temporary_file_path(self): <NEW_LINE> <INDENT> return self.file.name <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.file.close() <NEW_LINE> <DEDENT> except OSError as e: <NEW_LINE> <INDENT> if e.errno != errno.ENOENT: <NEW_LINE> <INDENT> raise | A file uploaded to a temporary location (i.e. stream-to-disk) and
suffixed with creation timestamp in order to allow old temp files
correct removing. | 6259905323849d37ff8525c3 |
class HTTPBadGateway(ClientException): <NEW_LINE> <INDENT> http_status = 502 <NEW_LINE> message = "Bad Gateway" | HTTP 502 - The server was acting as a gateway or proxy and received an invalid response from the upstream server. | 62599053e64d504609df9e50 |
class Account(object): <NEW_LINE> <INDENT> def __init__(self, credentials, *, protocol=None, main_resource=ME_RESOURCE, **kwargs): <NEW_LINE> <INDENT> protocol = protocol or MSGraphProtocol <NEW_LINE> self.protocol = protocol(default_resource=main_resource, **kwargs) if isinstance(protocol, type) else protocol <NEW_LINE> if not isinstance(self.protocol, Protocol): <NEW_LINE> <INDENT> raise ValueError("'protocol' must be a subclass of Protocol") <NEW_LINE> <DEDENT> self.con = Connection(credentials, **kwargs) <NEW_LINE> self.main_resource = main_resource <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if self.con.auth: <NEW_LINE> <INDENT> return 'Account Client Id: {}'.format(self.con.auth[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'Unidentified Account' <NEW_LINE> <DEDENT> <DEDENT> def authenticate(self, *, scopes, **kwargs): <NEW_LINE> <INDENT> kwargs.setdefault('token_file_name', self.con.token_path.name) <NEW_LINE> return oauth_authentication_flow(*self.con.auth, scopes=scopes, protocol=self.protocol, **kwargs) <NEW_LINE> <DEDENT> @property <NEW_LINE> def connection(self): <NEW_LINE> <INDENT> return self.con <NEW_LINE> <DEDENT> def new_message(self, resource=None): <NEW_LINE> <INDENT> return Message(parent=self, main_resource=resource, is_draft=True) <NEW_LINE> <DEDENT> def mailbox(self, resource=None): <NEW_LINE> <INDENT> return MailBox(parent=self, main_resource=resource, name='MailBox') <NEW_LINE> <DEDENT> def address_book(self, *, resource=None, address_book='personal'): <NEW_LINE> <INDENT> if address_book == 'personal': <NEW_LINE> <INDENT> return AddressBook(parent=self, main_resource=resource, name='Personal Address Book') <NEW_LINE> <DEDENT> elif address_book == 'gal': <NEW_LINE> <INDENT> return GlobalAddressList(parent=self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise RuntimeError('Addres_book must be either "personal" (resource address book) or "gal" (Global Address List)') <NEW_LINE> <DEDENT> <DEDENT> def schedule(self, *, resource=None): <NEW_LINE> <INDENT> return Schedule(parent=self, main_resource=resource) <NEW_LINE> <DEDENT> def storage(self, *, resource=None): <NEW_LINE> <INDENT> if not isinstance(self.protocol, MSGraphProtocol): <NEW_LINE> <INDENT> raise RuntimeError('Drive options only works on Microsoft Graph API') <NEW_LINE> <DEDENT> return Storage(parent=self, main_resource=resource) | Class helper to integrate all components into a single object | 62599053004d5f362081fa6c |
class TestLLABColourAppearanceModel(ColourAppearanceModelTest): <NEW_LINE> <INDENT> FIXTURE_BASENAME = 'llab.csv' <NEW_LINE> OUTPUT_ATTRIBUTES = {'L_L': 'J', 'Ch_L': 'C', 'h_L': 'h', 's_L': 's', 'C_L': 'M', 'A_L': 'a', 'B_L': 'b'} <NEW_LINE> def output_specification_from_data(self, data): <NEW_LINE> <INDENT> XYZ = np.array([data['X'], data['Y'], data['Z']]) <NEW_LINE> XYZ_0 = np.array([data['X_0'], data['Y_0'], data['Z_0']]) <NEW_LINE> specification = XYZ_to_LLAB(XYZ, XYZ_0, data['Y_b'], data['L'], LLAB_InductionFactors(1, data['F_S'], data['F_L'], data['F_C'])) <NEW_LINE> return specification | Defines :mod:`colour.appearance.llab` module unit tests methods for
*LLAB(l:c)* colour appearance model. | 6259905315baa72349463492 |
class BufferDataBus(RLESymbols): <NEW_LINE> <INDENT> def __init__(self, width_data, width_size, width_runlength): <NEW_LINE> <INDENT> super(BufferDataBus, self).__init__( width_data, width_size, width_runlength) <NEW_LINE> self.buffer_sel = Signal(bool(0)) <NEW_LINE> self.read_enable = Signal(bool(0)) <NEW_LINE> self.fifo_empty = Signal(bool(0)) | Connections related to output data buffer
Amplitude : amplitude of the number
size : size required to store amplitude
runlength : number of zeros
dovalid : asserts if ouput data is valid
buffer_sel : select the buffer in double buffer
read_enable : read data from the output fifo
fifo_empty : asserts if any of the two fifos are empty | 6259905310dbd63aa1c720e2 |
class Element(object): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self._kwargs = kwargs <NEW_LINE> <DEDENT> def __dir__(self): <NEW_LINE> <INDENT> return list(self._kwargs.keys()) + ["get"] <NEW_LINE> <DEDENT> def get(self, key, default): <NEW_LINE> <INDENT> if key in self: <NEW_LINE> <INDENT> return self[key] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return default <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> sig = ", ".join([f"{k}={self._kwargs[k]}" for k in sorted(self._kwargs)]) <NEW_LINE> return f"Element({sig})" <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> return self._kwargs[key] <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for key in self._kwargs: <NEW_LINE> <INDENT> yield key <NEW_LINE> <DEDENT> <DEDENT> def __getattr__(self, key): <NEW_LINE> <INDENT> if key not in self._kwargs: <NEW_LINE> <INDENT> raise AttributeError(str(key)) <NEW_LINE> <DEDENT> return self._kwargs[key] <NEW_LINE> <DEDENT> def __setattr__(self, name, key): <NEW_LINE> <INDENT> if name != "_kwargs": <NEW_LINE> <INDENT> raise AttributeError("Element attributes are frozen") <NEW_LINE> <DEDENT> return super().__setattr__(name, key) <NEW_LINE> <DEDENT> def __contains__(self, key): <NEW_LINE> <INDENT> return key in self._kwargs | Representation of a single element.
Implemented as a frozen dictionary with attribute access. | 62599053462c4b4f79dbcf05 |
class WideTree(Tree): <NEW_LINE> <INDENT> def getASCIITrunk(self): <NEW_LINE> <INDENT> result = "" <NEW_LINE> for i in range(self._trunkHeight): <NEW_LINE> <INDENT> result += " || \n" <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def getASCIILeaves(self): <NEW_LINE> <INDENT> result = "" <NEW_LINE> if self._leaves % TREE_LEAVES_PER_ROW > 0: <NEW_LINE> <INDENT> result += "#" * (2*(self._leaves % TREE_LEAVES_PER_ROW)) <NEW_LINE> result += "\n" <NEW_LINE> <DEDENT> for i in range(self._leaves // TREE_LEAVES_PER_ROW): <NEW_LINE> <INDENT> result += "#" * (2*(TREE_LEAVES_PER_ROW)) <NEW_LINE> result += "\n" <NEW_LINE> <DEDENT> return result | represent a wide tree: grows twice as wide as a normal tree, e.g.
#####
######
######
||
|| | 62599053a8ecb03325872717 |
class DottedLine(Line): <NEW_LINE> <INDENT> code = 129 <NEW_LINE> stroke_len: int <NEW_LINE> space_len: int <NEW_LINE> def parse(self): <NEW_LINE> <INDENT> super().parse() <NEW_LINE> self.stroke_len = struct.unpack('<I', self.raw_data[8:12])[0] <NEW_LINE> self.space_len = struct.unpack('<I', self.raw_data[12:16])[0] | Пунктирная линия. | 6259905382261d6c5273094a |
class Info(BaseCommand): <NEW_LINE> <INDENT> name = 'info' | Returns general info about the Broker. | 625990530a50d4780f70683f |
class BaseModelError(BaseError): <NEW_LINE> <INDENT> pass | Base exception class for base model errors. | 6259905307d97122c42181ab |
class LocationHDFS(AWSObject): <NEW_LINE> <INDENT> resource_type = "AWS::DataSync::LocationHDFS" <NEW_LINE> props: PropsDictType = { "AgentArns": ([str], True), "AuthenticationType": (str, True), "BlockSize": (integer, False), "KerberosKeytab": (str, False), "KerberosKrb5Conf": (str, False), "KerberosPrincipal": (str, False), "KmsKeyProviderUri": (str, False), "NameNodes": ([NameNode], True), "QopConfiguration": (QopConfiguration, False), "ReplicationFactor": (integer, False), "SimpleUser": (str, False), "Subdirectory": (str, False), "Tags": (Tags, False), } | `LocationHDFS <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datasync-locationhdfs.html>`__ | 62599053e76e3b2f99fd9eff |
class WAVMdata: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def get_metadata(header): <NEW_LINE> <INDENT> mdata = dict() <NEW_LINE> mdata["riff"] = header[:4] <NEW_LINE> mdata["size"] = to_int(header[4:8]) + 8 <NEW_LINE> mdata["wave"] = header[8:12] <NEW_LINE> mdata["fmt"] = header[12:16] <NEW_LINE> mdata["16"] = to_int(header[16:20]) <NEW_LINE> mdata["type"] = to_int(header[20:22]) <NEW_LINE> mdata["nch"] = to_int(header[22:24]) <NEW_LINE> mdata["fs"] = to_int(header[24:28]) <NEW_LINE> mdata["bps"] = to_int(header[34:36]) <NEW_LINE> mdata["init"] = header[36:40] <NEW_LINE> mdata["datalen"] = to_int(header[40:44]) <NEW_LINE> print(mdata) <NEW_LINE> if to_int(header[28:32]) != mdata["fs"] * mdata["bps"] * mdata["nch"] / 8 or to_int(header[32:34]) != mdata["bps"] * mdata["nch"] / 8 or mdata["datalen"] != mdata["size"] - 44: <NEW_LINE> <INDENT> print("Houston, tenemos un problema") <NEW_LINE> <DEDENT> return mdata <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def write_mdata(mdata, file): <NEW_LINE> <INDENT> file.write(mdata["riff"]) <NEW_LINE> file.write((mdata["size"] - 8).to_bytes(4, byteorder='little')) <NEW_LINE> file.write(mdata["wave"]) <NEW_LINE> file.write(mdata["fmt"]) <NEW_LINE> file.write(mdata["16"].to_bytes(4, byteorder='little')) <NEW_LINE> file.write(mdata["type"].to_bytes(2, byteorder='little')) <NEW_LINE> file.write(mdata["nch"].to_bytes(2, byteorder='little')) <NEW_LINE> file.write(mdata["fs"].to_bytes(4, byteorder='little')) <NEW_LINE> file.write(int(mdata["fs"] * mdata["bps"] * mdata["nch"] / 8).to_bytes( 4, byteorder='little' )) <NEW_LINE> file.write(int(mdata["bps"] * mdata["nch"] / 8).to_bytes( 2, byteorder='little' )) <NEW_LINE> file.write(mdata["bps"].to_bytes(2, byteorder='little')) <NEW_LINE> file.write(mdata["init"]) <NEW_LINE> file.write((mdata["datalen"]).to_bytes(4, byteorder='little')) | Clase con métodos estáticos útiles
para trabajar con metadata de un .wav | 6259905376e4537e8c3f0a8c |
class TextField(Field): <NEW_LINE> <INDENT> def __init__(self, fts=False, stemmer=True, metaphone=False, stopwords_file=None, min_word_length=None, *args, **kwargs): <NEW_LINE> <INDENT> super(TextField, self).__init__(*args, **kwargs) <NEW_LINE> self._fts = fts <NEW_LINE> self._stemmer = stemmer <NEW_LINE> self._metaphone = metaphone <NEW_LINE> self._stopwords_file = stopwords_file <NEW_LINE> self._min_word_length = min_word_length <NEW_LINE> self._index = self._index or self._fts <NEW_LINE> <DEDENT> def db_value(self, value): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> elif isinstance(value, unicode): <NEW_LINE> <INDENT> return value.encode('utf-8') <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def python_value(self, value): <NEW_LINE> <INDENT> if value: <NEW_LINE> <INDENT> return value.decode('utf-8') <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def get_indexes(self): <NEW_LINE> <INDENT> indexes = super(TextField, self).get_indexes() <NEW_LINE> if self._fts: <NEW_LINE> <INDENT> indexes.append(FullTextIndex( self, self._stemmer, self._metaphone, self._stopwords_file, self._min_word_length)) <NEW_LINE> <DEDENT> return indexes | Store unicode strings, encoded as UTF-8. :py:class:`TextField`
also supports full-text search through the optional ``fts``
parameter.
.. note:: If full-text search is enabled for the field, then
the ``index`` argument is implied.
:param bool fts: Enable simple full-text search.
:param bool stemmer: Use porter stemmer to process words.
:param bool metaphone: Use the double metaphone algorithm to
process words.
:param str stopwords_file: File containing stopwords, one per
line. If not specified, the default stopwords will be used.
:param int min_word_length: Minimum length (inclusive) of word
to be included in search index. | 62599053a219f33f346c7d05 |
class ReportManager: <NEW_LINE> <INDENT> def __init__(self, locale): <NEW_LINE> <INDENT> self.locale = locale <NEW_LINE> <DEDENT> def get_report_urls(self, report_page, only_new=True): <NEW_LINE> <INDENT> report_urls = [] <NEW_LINE> reports_raw_list = self._get_reports_from_page(report_page, only_new) <NEW_LINE> for raw_report in reports_raw_list: <NEW_LINE> <INDENT> report_url = self._get_single_report_url(raw_report) <NEW_LINE> report_urls.append(report_url) <NEW_LINE> <DEDENT> return report_urls <NEW_LINE> <DEDENT> def build_report(self, report_page): <NEW_LINE> <INDENT> report = AttackReport(report_page, locale=self.locale) <NEW_LINE> return report <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _get_reports_from_page(reports_page, only_new): <NEW_LINE> <INDENT> single_report_ptrn = re.compile(r'<input name="id_[\W\w]+?</tr>') <NEW_LINE> reports_list = re.findall(single_report_ptrn, reports_page) <NEW_LINE> if only_new: <NEW_LINE> <INDENT> reports_list = [x for x in reports_list if '(new)' in x] <NEW_LINE> <DEDENT> return reports_list <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _get_single_report_url(report): <NEW_LINE> <INDENT> href_ptrn = re.compile(r'<a href="([\W\w]+?)">') <NEW_LINE> url = re.search(href_ptrn, report) <NEW_LINE> url = url.group(1) <NEW_LINE> url = url.replace('&', '&') <NEW_LINE> return url | Helps to create AttackReport objects with the next
methods:
get_report_urls:
takes HTML (string) of report page and
returns list of URLs for each report on this page
build_report:
takes HTML (string) of single report and
returns new AttackReport object. | 62599053a79ad1619776b53e |
class surface_unusual_rows(): <NEW_LINE> <INDENT> def __init__(self,df,dates=[],numerics=[],categoricals=[]): <NEW_LINE> <INDENT> self.df = df <NEW_LINE> self.scores = pd.DataFrame(index=df.index) <NEW_LINE> for col in dates: <NEW_LINE> <INDENT> self.scores[col] = self.date_score(col) <NEW_LINE> <DEDENT> for col in numerics: <NEW_LINE> <INDENT> self.scores[col] = self.numeric_score(col) <NEW_LINE> <DEDENT> for col in categoricals: <NEW_LINE> <INDENT> self.scores[col] = self.categorical_score(col) <NEW_LINE> <DEDENT> <DEDENT> def categorical_score(self,col): <NEW_LINE> <INDENT> dist = pd.value_counts(self.df[col].values,normalize=True) <NEW_LINE> if dist.empty: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> seen = set() <NEW_LINE> dist2 = [x for x in dist.values if not (x in seen or seen.add(x))] <NEW_LINE> dist3 = [dist2[0] / x if x != 0 else 0 for x in dist2] <NEW_LINE> dist4 = [x - 1 for x in dist3] <NEW_LINE> dist5 = [x / dist4[-1] if dist4[-1] != 0 else 0 for x in dist4] <NEW_LINE> dist6 = pd.DataFrame(dist2,dist5).reset_index() <NEW_LINE> mapser = pd.merge(pd.DataFrame(dist).reset_index(),dist6,on=0) <NEW_LINE> mapdict = mapser[['index_x','index_y']].set_index('index_x').to_dict()['index_y'] <NEW_LINE> return self.df[col].map(mapdict) <NEW_LINE> <DEDENT> def cont_score(self,theseries,col): <NEW_LINE> <INDENT> percen = theseries.rank(pct=True) <NEW_LINE> return percen.map(lambda x: 2 * abs(0.5 - x)) <NEW_LINE> <DEDENT> def numeric_score(self,col): <NEW_LINE> <INDENT> return self.cont_score(self.df[col],col) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __dtseconds(x): <NEW_LINE> <INDENT> if not x: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> elif isinstance(x,str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> x = parse(x) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> elif not isinstance(x,dt): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return (x - dt.fromtimestamp(0)).total_seconds() <NEW_LINE> <DEDENT> def date_score(self,col): <NEW_LINE> <INDENT> seconds = self.df[col].map(self.__dtseconds) <NEW_LINE> return self.cont_score(seconds,col) <NEW_LINE> <DEDENT> def show(self,n=5): <NEW_LINE> <INDENT> sort_index = self.scores.sum(axis=1).sort_values(ascending=False).index <NEW_LINE> to_display = self.df.loc[sort_index] <NEW_LINE> context_specific_display(to_display.head(n)) | Give each row a score that sums up how 'unusual' its values are, where
a value is considered unusual for a column of continuous variables when
it has a high percentile, and is considered unusual for a column of
categorical variables when it is rare. | 6259905355399d3f05627a20 |
class AssignmentViewSet(UpdateSerializerMixin, viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = Assignment.objects.all() <NEW_LINE> serializer_class = AssignmentSerializer <NEW_LINE> update_serializer_class = AssignmentUpdateSerializer <NEW_LINE> def get_permissions(self): <NEW_LINE> <INDENT> if self.request.method == 'PUT': <NEW_LINE> <INDENT> self.permission_classes = [AssignmentUpdatePermission, ] <NEW_LINE> <DEDENT> return super(AssignmentViewSet, self).get_permissions() <NEW_LINE> <DEDENT> def list(self, request, roster_pk=None): <NEW_LINE> <INDENT> queryset = self.queryset.filter(roster_id=roster_pk) <NEW_LINE> serializer = self.serializer_class(queryset, many=True) <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> def retrieve(self, request, pk=None, roster_pk=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> assignment = self.queryset.get(pk=pk, roster_id=roster_pk) <NEW_LINE> serializer = self.serializer_class(assignment, many=False) <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> except Assignment.DoesNotExist: <NEW_LINE> <INDENT> raise Http404 <NEW_LINE> <DEDENT> <DEDENT> def create(self, request, pk=None, roster_pk=None): <NEW_LINE> <INDENT> request.data["roster"] = roster_pk <NEW_LINE> return super(AssignmentViewSet, self).create(request) <NEW_LINE> <DEDENT> def update(self, request, pk=None, roster_pk=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.queryset.get(pk=pk, roster_id=roster_pk) <NEW_LINE> <DEDENT> except Assignment.DoesNotExist: <NEW_LINE> <INDENT> raise Http404 <NEW_LINE> <DEDENT> request.data["roster"] = roster_pk <NEW_LINE> return super(AssignmentViewSet, self).update(request) | retrieve:
Returns the requested roster/assignment.
list:
Returns all assignments in this roster.
create:
Create a new assignment in this roster.
update:
Update an assignment in this roster.
delete:
Delete an assignment in this roster. | 62599053be383301e0254d0d |
class UploadRawDataFileForm(SourceInForm): <NEW_LINE> <INDENT> error_css_class = 'error' <NEW_LINE> required_css_class = 'required' <NEW_LINE> filedata = forms.FileField() <NEW_LINE> title = forms.CharField(required=True) <NEW_LINE> tool_name = forms.CharField(required=True) <NEW_LINE> tool_version = forms.CharField(required=False) <NEW_LINE> tool_details = forms.CharField(required=False) <NEW_LINE> data_type = forms.ChoiceField(required=True, widget=forms.Select(attrs={'class': 'no_clear'})) <NEW_LINE> description = forms.CharField(widget=forms.Textarea(attrs={'cols':'80', 'rows':'2'}), required=False) <NEW_LINE> related_id = forms.CharField(widget=forms.HiddenInput(), required=False, label=form_consts.Common.RELATED_ID) <NEW_LINE> related_type = forms.CharField(widget=forms.HiddenInput(), required=False, label=form_consts.Common.RELATED_TYPE) <NEW_LINE> relationship_type = forms.ChoiceField(required=False, label=form_consts.Common.RELATIONSHIP_TYPE, widget=forms.Select(attrs={'id':'relationship_type'})) <NEW_LINE> def __init__(self, username, *args, **kwargs): <NEW_LINE> <INDENT> super(UploadRawDataFileForm, self).__init__(username, *args, **kwargs) <NEW_LINE> self.fields['data_type'].choices = [(c.name, c.name ) for c in get_item_names(RawDataType, True)] <NEW_LINE> self.fields['relationship_type'].choices = relationship_choices <NEW_LINE> self.fields['relationship_type'].initial = RelationshipTypes.RELATED_TO <NEW_LINE> add_bucketlist_to_form(self) <NEW_LINE> add_ticket_to_form(self) | Django form for uploading raw data as a file. | 625990538e7ae83300eea599 |
class _RightBarPage(object): <NEW_LINE> <INDENT> RIGHT_BAR_ENTRIES_PER_PAGES = 8 <NEW_LINE> def __init__(self, client, index): <NEW_LINE> <INDENT> self.client = client <NEW_LINE> self.index = index <NEW_LINE> <DEDENT> @property <NEW_LINE> def soup(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._soup <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> params = { "language": "en", "selectedTab": "PRESENTATION", "startIndex": self.index * _RightBarPage.RIGHT_BAR_ENTRIES_PER_PAGES, } <NEW_LINE> url = client.get_url("/rightbar.action") <NEW_LINE> with contextlib.closing(self.client.opener.open(url, urllib.urlencode(params))) as response: <NEW_LINE> <INDENT> if response.getcode() != 200: <NEW_LINE> <INDENT> raise Exception("Fetching rightbar index %s failed" % self.index) <NEW_LINE> <DEDENT> content = response.read().decode('utf-8') <NEW_LINE> self._soup = bs4.BeautifulSoup(content) <NEW_LINE> <DEDENT> return self._soup <NEW_LINE> <DEDENT> <DEDENT> def summaries(self): <NEW_LINE> <INDENT> def create_summary(div): <NEW_LINE> <INDENT> def get_id(div): <NEW_LINE> <INDENT> return get_path(div).rsplit('/', 1)[1] <NEW_LINE> <DEDENT> def get_path(div): <NEW_LINE> <INDENT> return div.find('a')['href'].rsplit(';', 2)[0] <NEW_LINE> <DEDENT> def get_url(div): <NEW_LINE> <INDENT> return client.get_url(get_path(div)) <NEW_LINE> <DEDENT> def get_desc(div): <NEW_LINE> <INDENT> return div.find('p', class_='image').find_next_sibling('p').get_text(strip=True) <NEW_LINE> <DEDENT> def get_auth(div): <NEW_LINE> <INDENT> return div.find('a', class_='editorlink').get_text(strip=True) <NEW_LINE> <DEDENT> def get_date(div): <NEW_LINE> <INDENT> str = div.find('a', class_='editorlink').parent.next_sibling.strip(" \t\n\r,") <NEW_LINE> return datetime.datetime.strptime(str, "%b %d, %Y") <NEW_LINE> <DEDENT> def get_title(div): <NEW_LINE> <INDENT> return div.find('h1').get_text().strip() <NEW_LINE> <DEDENT> return { 'id' : get_id(div), 'url' : get_url(div), 'desc' : get_desc(div), 'auth' : get_auth(div), 'date' : get_date(div), 'title': get_title(div), } <NEW_LINE> <DEDENT> entries = self.soup.findAll('div', {'class': 'entry'}) <NEW_LINE> return [create_summary(div) for div in entries] | A page returned by /rightbar.action
This page lists all available presentations with pagination. | 62599053baa26c4b54d507a5 |
class UserSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = get_user_model() <NEW_LINE> fields = ('email', 'password', 'name') <NEW_LINE> extra_kwargs = {'password': {'write_only': True, 'min_length': 5}} <NEW_LINE> <DEDENT> def create(self, validated_data): <NEW_LINE> <INDENT> return get_user_model().objects.create_user(**validated_data) <NEW_LINE> <DEDENT> def update(self, instance, validated_data): <NEW_LINE> <INDENT> password = validated_data.pop('password', None) <NEW_LINE> user = super().update(instance, validated_data) <NEW_LINE> if password: <NEW_LINE> <INDENT> user.set_password(password) <NEW_LINE> user.save() <NEW_LINE> <DEDENT> return user | Serializers for the users object | 625990536e29344779b01b4b |
class SqlCompiledQuery(object): <NEW_LINE> <INDENT> def __init__(self, maintable, relationDict=None,maintable_as=None): <NEW_LINE> <INDENT> self.maintable = maintable <NEW_LINE> self.relationDict = relationDict or {} <NEW_LINE> self.aliasDict = {} <NEW_LINE> self.resultmap = Bag() <NEW_LINE> self.distinct = '' <NEW_LINE> self.columns = '' <NEW_LINE> self.joins = [] <NEW_LINE> self.where = None <NEW_LINE> self.group_by = None <NEW_LINE> self.having = None <NEW_LINE> self.order_by = None <NEW_LINE> self.limit = None <NEW_LINE> self.offset = None <NEW_LINE> self.for_update = None <NEW_LINE> self.explodingColumns = [] <NEW_LINE> self.aggregateDict = {} <NEW_LINE> self.pyColumns = [] <NEW_LINE> self.maintable_as = maintable_as <NEW_LINE> <DEDENT> def get_sqltext(self, db): <NEW_LINE> <INDENT> kwargs = {} <NEW_LINE> for k in ( 'maintable', 'distinct', 'columns', 'joins', 'where', 'group_by', 'having', 'order_by', 'limit', 'offset', 'for_update'): <NEW_LINE> <INDENT> kwargs[k] = getattr(self, k) <NEW_LINE> <DEDENT> return db.adapter.compileSql(maintable_as=self.maintable_as,**kwargs) | SqlCompiledQuery is a private class used by the :class:`SqlQueryCompiler` class.
It is used to store all parameters needed to compile a query string. | 62599053dc8b845886d54ac7 |
class Servo(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.pwm = Adafruit_PCA9685.PCA9685() <NEW_LINE> self.max = 600 <NEW_LINE> self.min = 150 <NEW_LINE> self.pulse_length = 1000000 <NEW_LINE> self.pulse_length //= 60 <NEW_LINE> logger.debug('{0}us per period'.format(self.pulse_length)) <NEW_LINE> self.pulse_length //= 4096 <NEW_LINE> logger.debug('{0}us per bit'.format(self.pulse_length)) <NEW_LINE> self.pwm.set_pwm_freq(60) <NEW_LINE> <DEDENT> def _servo_degrees_to_us(self, angle): <NEW_LINE> <INDENT> self._check_range(angle, -90, 90) <NEW_LINE> angle += 90 <NEW_LINE> servo_range = self.max - self.min <NEW_LINE> us = (servo_range / 180.0) * angle <NEW_LINE> return self.min + int(us) <NEW_LINE> <DEDENT> def _check_range(self, value, value_min, value_max): <NEW_LINE> <INDENT> if value < value_min or value > value_max: <NEW_LINE> <INDENT> raise ValueError("Value {value} should be between {min} and {max}".format( value=value, min=value_min, max=value_max)) <NEW_LINE> <DEDENT> <DEDENT> def set_servo_pulse(self, channel, pulse): <NEW_LINE> <INDENT> pulse = self.validate_pulse(channel, pulse) <NEW_LINE> self.pwm.set_pwm(channel, 0, pulse) <NEW_LINE> <DEDENT> def validate_pulse(self, channel, pulse): <NEW_LINE> <INDENT> return max(self.min, min(self.max, pulse)) <NEW_LINE> <DEDENT> def pan(self, angle): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.set_servo_pulse(0, self._servo_degrees_to_us(angle)) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> logger.debug("[SERVO] error in input values") <NEW_LINE> <DEDENT> <DEDENT> def tilt(self, angle): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.set_servo_pulse(1, self._servo_degrees_to_us(angle)) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> logger.debug("[SERVO] error in input values") <NEW_LINE> <DEDENT> <DEDENT> def moveServo(self, HStep=None, VStep=None): <NEW_LINE> <INDENT> if HStep is not None: <NEW_LINE> <INDENT> self.set_servo_pulse(0, self._servo_degrees_to_us(HStep)) <NEW_LINE> <DEDENT> elif VStep is not None: <NEW_LINE> <INDENT> self.set_servo_pulse(1, self._servo_degrees_to_us(VStep)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.debug("[SERVO] error in input values") | class to move the servo up/down and left/right | 6259905399cbb53fe68323ed |
class Mul(Layer): <NEW_LINE> <INDENT> def forward(self, x, is_training=False): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = np.prod(x, axis=0) <NEW_LINE> return self.y <NEW_LINE> <DEDENT> def backward(self, dJdy): <NEW_LINE> <INDENT> return dJdy * (self.y / self.x) | Multiplication Layer: [a,b,c] => a*b*c
backward: dJdy * [bc, ac, ab] | 625990533617ad0b5ee07649 |
class Hub(EnvironmentObject): <NEW_LINE> <INDENT> def __init__(self, id=1, location=(0, 0), radius=20): <NEW_LINE> <INDENT> super().__init__(id, location, radius) <NEW_LINE> self.dropable = True <NEW_LINE> self.carryable = False <NEW_LINE> self.passable = True <NEW_LINE> self.deathable = False <NEW_LINE> self.moveable = False <NEW_LINE> self.dropped_objects = list() | Hub object. | 6259905307d97122c42181ac |
class TypTraits: <NEW_LINE> <INDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__class__.__name__ <NEW_LINE> <DEDENT> def to_literal(self, value): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> def from_json(self, value): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> def to_json(self, value): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> def from_literal(self, value): <NEW_LINE> <INDENT> return value | Encapsulated differences between types | 62599053435de62698e9d305 |
class ChangeSpeed(object): <NEW_LINE> <INDENT> def __init__(self, term, speed): <NEW_LINE> <INDENT> self.term = term <NEW_LINE> self.speed = speed <NEW_LINE> <DEDENT> def __getstate__(self): <NEW_LINE> <INDENT> return [('frames', self.term.expr), ('type', self.speed.type), ('value', self.speed.value.expr)] <NEW_LINE> <DEDENT> def __setstate__(self, state): <NEW_LINE> <INDENT> state = dict(state) <NEW_LINE> self.__init__(INumberDef(state["frames"]), Speed(state["type"], NumberDef(state["value"]))) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def FromXML(cls, doc, element): <NEW_LINE> <INDENT> for subelem in element.getchildren(): <NEW_LINE> <INDENT> tag = realtag(subelem) <NEW_LINE> if tag == "speed": <NEW_LINE> <INDENT> speed = Speed.FromXML(doc, subelem) <NEW_LINE> <DEDENT> elif tag == "term": <NEW_LINE> <INDENT> term = INumberDef(subelem.text) <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> return cls(term, speed) <NEW_LINE> <DEDENT> except UnboundLocalError as exc: <NEW_LINE> <INDENT> raise ParseError(str(exc)) <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, owner, action, params, rank, created): <NEW_LINE> <INDENT> frames = self.term(params, rank) <NEW_LINE> speed, type = self.speed(params, rank) <NEW_LINE> action.speed_frames = frames <NEW_LINE> if frames <= 0: <NEW_LINE> <INDENT> if type == "absolute": <NEW_LINE> <INDENT> owner.speed = speed <NEW_LINE> <DEDENT> elif type == "relative": <NEW_LINE> <INDENT> owner.speed += speed <NEW_LINE> <DEDENT> <DEDENT> elif type == "sequence": <NEW_LINE> <INDENT> action.speed = speed <NEW_LINE> <DEDENT> elif type == "relative": <NEW_LINE> <INDENT> action.speed = speed / frames <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> action.speed = (speed - owner.speed) / frames <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "%s(term=%r, speed=%r)" % ( type(self).__name__, self.term, self.speed) | Speed change over time. | 625990533cc13d1c6d466c40 |
class L3NatDBSepTestCase(L3BaseForSepTests, L3NatTestCaseBase, L3NatDBTestCaseMixin): <NEW_LINE> <INDENT> def test_port_deletion_prevention_handles_missing_port(self): <NEW_LINE> <INDENT> pl = manager.NeutronManager.get_service_plugins().get( service_constants.L3_ROUTER_NAT) <NEW_LINE> self.assertIsNone( pl.prevent_l3_port_deletion(context.get_admin_context(), 'fakeid') ) | Unit tests for a separate L3 routing service plugin. | 6259905345492302aabfd9da |
class SnapshotReport(CallbackBase): <NEW_LINE> <INDENT> xref = None <NEW_LINE> def start(self, doc): <NEW_LINE> <INDENT> if doc.get("plan_name", "nope") == "snapshot": <NEW_LINE> <INDENT> self.xref = {} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.xref = None <NEW_LINE> <DEDENT> <DEDENT> def descriptor(self, doc): <NEW_LINE> <INDENT> if self.xref is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if doc["name"] == "primary": <NEW_LINE> <INDENT> for k, v in doc["configuration"].items(): <NEW_LINE> <INDENT> ts = v["timestamps"][k] <NEW_LINE> dt = ( datetime.datetime.fromtimestamp(ts) .isoformat(sep=" ") ) <NEW_LINE> pvname = v["data_keys"][k]["source"] <NEW_LINE> value = v["data"][k] <NEW_LINE> self.xref[pvname] = dict(value=value, timestamp=dt) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def stop(self, doc): <NEW_LINE> <INDENT> if self.xref is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> t = pyRestTable.Table() <NEW_LINE> t.addLabel("timestamp") <NEW_LINE> t.addLabel("source") <NEW_LINE> t.addLabel("name") <NEW_LINE> t.addLabel("value") <NEW_LINE> for k, v in sorted(self.xref.items()): <NEW_LINE> <INDENT> p = k.find(":") <NEW_LINE> t.addRow((v["timestamp"], k[:p], k[p + 1:], v["value"])) <NEW_LINE> <DEDENT> print(t) <NEW_LINE> for k, v in sorted(doc.items()): <NEW_LINE> <INDENT> print(f"{k}: {v}") <NEW_LINE> <DEDENT> <DEDENT> def print_report(self, header): <NEW_LINE> <INDENT> print() <NEW_LINE> print("=" * 40) <NEW_LINE> print("snapshot:", header.start["iso8601"]) <NEW_LINE> print("=" * 40) <NEW_LINE> print() <NEW_LINE> for k, v in sorted(header.start.items()): <NEW_LINE> <INDENT> print(f"{k}: {v}") <NEW_LINE> <DEDENT> print() <NEW_LINE> for key, doc in header.documents(): <NEW_LINE> <INDENT> self(key, doc) <NEW_LINE> <DEDENT> print() | Show the data from a ``apstools.plans.snapshot()``.
Find most recent snapshot between certain dates::
headers = db(plan_name="snapshot", since="2018-12-15", until="2018-12-21")
h = list(headers)[0] # pick the first one, it's the most recent
apstools.callbacks.SnapshotReport().print_report(h)
Use as callback to a snapshot plan::
RE(
apstools.plans.snapshot(ophyd_objects_list),
apstools.callbacks.SnapshotReport()
) | 625990534e4d562566373909 |
class _ASTNodeWithStatus(_ast_base.ASTNodeBase): <NEW_LINE> <INDENT> def clear_status(self): <NEW_LINE> <INDENT> self.set_status(None) <NEW_LINE> <DEDENT> def set_status(self, status_id): <NEW_LINE> <INDENT> self.set_property("status_id", status_id) <NEW_LINE> <DEDENT> def get_status(self): <NEW_LINE> <INDENT> return self.get_property("status_id", None) <NEW_LINE> <DEDENT> def is_undefined_status(self): <NEW_LINE> <INDENT> return self.get_status() is None <NEW_LINE> <DEDENT> def is_gas_status(self): <NEW_LINE> <INDENT> return self.get_status() == STATUS_GAS <NEW_LINE> <DEDENT> def is_liquid_status(self): <NEW_LINE> <INDENT> return self.get_status() == STATUS_LIQUID <NEW_LINE> <DEDENT> def is_solid_status(self): <NEW_LINE> <INDENT> return self.get_status() == STATUS_SOLID <NEW_LINE> <DEDENT> def is_aqueous_status(self): <NEW_LINE> <INDENT> return self.get_status() == STATUS_AQUEOUS | Protocols for nodes which have to save status. | 625990538da39b475be046ee |
class VEOProject(object): <NEW_LINE> <INDENT> def __init__(self, name=None, annotations=None, synapse_client=None, config_tree=None, **kwargs): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.syn = synapse_client <NEW_LINE> self._get_project_entity() <NEW_LINE> self.syn_id = self.project['id'] <NEW_LINE> self._parent_id = self.project['parentId'] <NEW_LINE> self.conf = self._process_config_tree(config_tree) <NEW_LINE> self.annotations = self._process_annotations(annotations) <NEW_LINE> self.remote = Munch(entity_dicts=None, dag=None) <NEW_LINE> self.dag = None <NEW_LINE> self._build_remote_entity_dag() <NEW_LINE> <DEDENT> def _initialize_project_info(self, ): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _process_config_tree(self, config_tree): <NEW_LINE> <INDENT> if config_tree is None: <NEW_LINE> <INDENT> return Munch() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if isinstance(config_tree, Munch): <NEW_LINE> <INDENT> return config_tree <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return munchify(config_tree) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _process_annotations(self, annotations): <NEW_LINE> <INDENT> if annotations is None: <NEW_LINE> <INDENT> return Munch() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if isinstance(annotations, Munch): <NEW_LINE> <INDENT> return annotations <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return munchify(annotations) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _get_remote_entity_dicts(self): <NEW_LINE> <INDENT> pid = self.project['id'][3:] <NEW_LINE> q = 'SELECT * FROM entity WHERE projectId=="{pid}"'.format(pid=pid) <NEW_LINE> self.remote.entity_dicts = self.syn.query(q)['results'] <NEW_LINE> <DEDENT> def _build_remote_entity_dag(self): <NEW_LINE> <INDENT> self._get_remote_entity_dicts() <NEW_LINE> dag = nx.DiGraph() <NEW_LINE> dag.node = munchify(dag.node) <NEW_LINE> nodes = {ent['entity.id']: SynNode(entity_dict=ent, synapse_session=self.syn) for ent in self.remote.entity_dicts} <NEW_LINE> for node in nodes.values(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> dag.add_node(n=node.id, attr_dict=node) <NEW_LINE> dag.add_edge(u=nodes[node['parentId']].id, v=node.id) <NEW_LINE> <DEDENT> except KeyError as exc: <NEW_LINE> <INDENT> if exc.args[0] == self._parent_id: <NEW_LINE> <INDENT> parent = SynNode(entity_dict={'entity.id': self._parent_id}, is_root=True) <NEW_LINE> dag.add_node(n=node.id, attr_dict=node) <NEW_LINE> dag.add_node(n=parent.id, attr_dict=parent) <NEW_LINE> dag.add_edge(u=parent.id, v=node.id) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if nx.dag.is_directed_acyclic_graph(dag): <NEW_LINE> <INDENT> self.dag = dag <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise e.ValidationError('networkx.dag.is_directed_acyclic_graph() returned `False` suggesting a cyclic relationship between entities.') <NEW_LINE> <DEDENT> <DEDENT> def _get_project_entity(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.project = self.syn.get(syn.Project(name=self.name)) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> self.project = self.syn.store(syn.Project(name=self.name)) | Manage a collection of Synapse Entities common to a single project. | 62599053d53ae8145f919964 |
class ElectricCar(Car): <NEW_LINE> <INDENT> def __init__(self, make, model, year, battery_size=75): <NEW_LINE> <INDENT> super().__init__(make, model, year) <NEW_LINE> self.battery = Battery(battery_size) <NEW_LINE> <DEDENT> def description(self): <NEW_LINE> <INDENT> msg = f"Car info: make: {self.make} " <NEW_LINE> msg = msg + f"model: {self.model} " <NEW_LINE> msg += f"year: {self.year} " <NEW_LINE> msg += f"battery capacity {self.battery.get_battery_size()}-kWh." <NEW_LINE> print(msg) | Model to represent the electric cars | 6259905391af0d3eaad3b32b |
class BrowseTreeField(BrowseField): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self._model = kwargs.pop('model') <NEW_LINE> if 'queryset' not in kwargs: <NEW_LINE> <INDENT> kwargs['queryset'] = self._model.objects.all() <NEW_LINE> try: <NEW_LINE> <INDENT> if self._model and get_listing_option(self._model, 'sortable'): <NEW_LINE> <INDENT> kwargs['queryset'] = kwargs['queryset'].order_by('seq') <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> kwargs['name'] = self._model._meta.verbose_name_plural <NEW_LINE> super(BrowseTreeField, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def label_from_instance(self, obj): <NEW_LINE> <INDENT> return mark_safe((' ' * 2 * obj.level) + obj.title) <NEW_LINE> <DEDENT> def _get_choices(self): <NEW_LINE> <INDENT> if not isinstance(self._queryset, MaterializedQuerySet): <NEW_LINE> <INDENT> self._queryset = copy.deepcopy(self._queryset) <NEW_LINE> <DEDENT> return TreeModelChoiceIterator(self, self._queryset) <NEW_LINE> <DEDENT> choices = property(_get_choices, forms.ChoiceField._set_choices) | browse select field for browsing tree content. | 625990533c8af77a43b689c1 |
class ImportSshPublicKeyResponse(_messages.Message): <NEW_LINE> <INDENT> loginProfile = _messages.MessageField('LoginProfile', 1) | A response message for importing an SSH public key.
Fields:
loginProfile: The login profile information for the user. | 6259905326068e7796d4de4b |
class NoneAdapter(object): <NEW_LINE> <INDENT> def __init__(self, obj): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def getquoted(self, _null=b"NULL"): <NEW_LINE> <INDENT> return _null | Adapt None to NULL.
This adapter is not used normally as a fast path in mogrify uses NULL,
but it makes easier to adapt composite types. | 62599053fff4ab517ebced26 |
class AccountManagerConfig(AppConfig): <NEW_LINE> <INDENT> name = 'account_manager' <NEW_LINE> verbose_name = 'Gestionnaire de comptes utilisateurs' <NEW_LINE> def ready(self): <NEW_LINE> <INDENT> register_observation_links(self) | Account manager app: App's config | 6259905363d6d428bbee3cd6 |
class BookCreateView(CreateView): <NEW_LINE> <INDENT> model = Book <NEW_LINE> fields = '__all__' | Create a new book. | 62599053baa26c4b54d507a6 |
class TestEnvironSetTemp(unittest.TestCase): <NEW_LINE> <INDENT> def test_environ_set(self): <NEW_LINE> <INDENT> os.environ['QUTEBROWSER_ENVIRON_TEST'] = 'oldval' <NEW_LINE> with helpers.environ_set_temp({'QUTEBROWSER_ENVIRON_TEST': 'newval'}): <NEW_LINE> <INDENT> self.assertEqual(os.environ['QUTEBROWSER_ENVIRON_TEST'], 'newval') <NEW_LINE> <DEDENT> self.assertEqual(os.environ['QUTEBROWSER_ENVIRON_TEST'], 'oldval') <NEW_LINE> <DEDENT> def test_environ_unset(self): <NEW_LINE> <INDENT> with helpers.environ_set_temp({'QUTEBROWSER_ENVIRON_TEST': 'newval'}): <NEW_LINE> <INDENT> self.assertEqual(os.environ['QUTEBROWSER_ENVIRON_TEST'], 'newval') <NEW_LINE> <DEDENT> self.assertNotIn('QUTEBROWSER_ENVIRON_TEST', os.environ) <NEW_LINE> <DEDENT> def test_environ_multiple(self): <NEW_LINE> <INDENT> os.environ['QUTEBROWSER_ENVIRON_TEST_1'] = 'oldval_1' <NEW_LINE> os.environ['QUTEBROWSER_ENVIRON_TEST_3'] = 'oldval_3' <NEW_LINE> env = { 'QUTEBROWSER_ENVIRON_TEST_1': 'newval_1', 'QUTEBROWSER_ENVIRON_TEST_2': 'newval_2', 'QUTEBROWSER_ENVIRON_TEST_3': None, } <NEW_LINE> with helpers.environ_set_temp(env): <NEW_LINE> <INDENT> self.assertEqual(os.environ['QUTEBROWSER_ENVIRON_TEST_1'], 'newval_1') <NEW_LINE> self.assertEqual(os.environ['QUTEBROWSER_ENVIRON_TEST_2'], 'newval_2') <NEW_LINE> self.assertNotIn('QUTEBROWSER_ENVIRON_TEST_3', os.environ) <NEW_LINE> <DEDENT> self.assertEqual(os.environ['QUTEBROWSER_ENVIRON_TEST_1'], 'oldval_1') <NEW_LINE> self.assertNotIn('QUTEBROWSER_ENVIRON_TEST_2', os.environ) <NEW_LINE> self.assertEqual(os.environ['QUTEBROWSER_ENVIRON_TEST_3'], 'oldval_3') <NEW_LINE> <DEDENT> def test_environ_none_set(self): <NEW_LINE> <INDENT> os.environ['QUTEBROWSER_ENVIRON_TEST'] = 'oldval' <NEW_LINE> with helpers.environ_set_temp({'QUTEBROWSER_ENVIRON_TEST': None}): <NEW_LINE> <INDENT> self.assertNotIn('QUTEBROWSER_ENVIRON_TEST', os.environ) <NEW_LINE> <DEDENT> self.assertEqual(os.environ['QUTEBROWSER_ENVIRON_TEST'], 'oldval') <NEW_LINE> <DEDENT> def test_environ_none_unset(self): <NEW_LINE> <INDENT> with helpers.environ_set_temp({'QUTEBROWSER_ENVIRON_TEST': None}): <NEW_LINE> <INDENT> self.assertNotIn('QUTEBROWSER_ENVIRON_TEST', os.environ) <NEW_LINE> <DEDENT> self.assertNotIn('QUTEBROWSER_ENVIRON_TEST', os.environ) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> if 'QUTEBROWSER_ENVIRON_TEST' in os.environ: <NEW_LINE> <INDENT> del os.environ['QUTEBROWSER_ENVIRON_TEST'] | Test the environ_set_temp helper. | 625990533eb6a72ae038bb63 |
class PluginWarningOnPyTracer(CoverageTest): <NEW_LINE> <INDENT> def test_exception_if_plugins_on_pytracer(self): <NEW_LINE> <INDENT> if env.C_TRACER: <NEW_LINE> <INDENT> self.skipTest("This test is only about PyTracer.") <NEW_LINE> <DEDENT> self.make_file("simple.py", """a = 1""") <NEW_LINE> cov = coverage.Coverage() <NEW_LINE> cov.set_option("run:plugins", ["tests.plugin1"]) <NEW_LINE> expected_warnings = [ r"Plugin file tracers \(tests.plugin1.Plugin\) aren't supported with PyTracer", ] <NEW_LINE> with self.assert_warnings(cov, expected_warnings): <NEW_LINE> <INDENT> self.start_import_stop(cov, "simple") | Test that we get a controlled exception with plugins on PyTracer. | 625990537cff6e4e811b6f44 |
@dataclass <NEW_LINE> class EntityMention(EntityMention): <NEW_LINE> <INDENT> id: Optional[str] <NEW_LINE> is_filler: Optional[bool] <NEW_LINE> def __init__(self, pack: DataPack, begin: int, end: int): <NEW_LINE> <INDENT> super().__init__(pack, begin, end) <NEW_LINE> self.id: Optional[str] = None <NEW_LINE> self.is_filler: Optional[bool] = None | Attributes:
id (Optional[str]):
is_filler (Optional[bool]): | 62599053507cdc57c63a62a9 |
class prelu: <NEW_LINE> <INDENT> def __init__(self, slope=0.1): <NEW_LINE> <INDENT> self.slope = Tensor(slope) <NEW_LINE> <DEDENT> def __call__(self, x): <NEW_LINE> <INDENT> return leaky_relu(x, self.slope) <NEW_LINE> <DEDENT> @property <NEW_LINE> def parameters(self): <NEW_LINE> <INDENT> return (self.slope,) | A parametric rectified linear unit.
This class maintains the learned slope parameter of a PReLU unit, which is a leaky ReLU with
learned slope in the negative region. | 625990537d847024c075d8df |
class IssuerElementTree(Issuer): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def toXML(cls, issuer): <NEW_LINE> <INDENT> if not isinstance(issuer, Issuer): <NEW_LINE> <INDENT> raise TypeError("Expecting %r class got %r" % (Issuer, type(issuer))) <NEW_LINE> <DEDENT> attrib = {} <NEW_LINE> if issuer.format is not None: <NEW_LINE> <INDENT> attrib[cls.FORMAT_ATTRIB_NAME] = issuer.format <NEW_LINE> <DEDENT> tag = str(QName.fromGeneric(cls.DEFAULT_ELEMENT_NAME)) <NEW_LINE> elem = makeEtreeElement(tag, issuer.qname.prefix, issuer.qname.namespaceURI, **attrib) <NEW_LINE> elem.text = issuer.value <NEW_LINE> return elem <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def fromXML(cls, elem): <NEW_LINE> <INDENT> if not ElementTree.iselement(elem): <NEW_LINE> <INDENT> raise TypeError("Expecting %r input type for parsing; got %r" % (ElementTree.Element, elem)) <NEW_LINE> <DEDENT> if QName.getLocalPart(elem.tag) != cls.DEFAULT_ELEMENT_LOCAL_NAME: <NEW_LINE> <INDENT> raise XMLTypeParseError('No "%s" element found' % cls.DEFAULT_ELEMENT_LOCAL_NAME) <NEW_LINE> <DEDENT> issuerFormat = elem.attrib.get(cls.FORMAT_ATTRIB_NAME) <NEW_LINE> issuer = Issuer() <NEW_LINE> if issuerFormat is not None: <NEW_LINE> <INDENT> issuer.format = issuerFormat <NEW_LINE> <DEDENT> if elem.text is None: <NEW_LINE> <INDENT> raise XMLTypeParseError('No SAML issuer value set') <NEW_LINE> <DEDENT> issuer.value = elem.text.strip() <NEW_LINE> return issuer | Represent a SAML Issuer element in XML using ElementTree | 6259905315baa72349463496 |
class UnknownOSVersionException(BaseException): <NEW_LINE> <INDENT> pass | UnknownOSVersion Exception | 625990533cc13d1c6d466c42 |
class StepsManager(object): <NEW_LINE> <INDENT> def __init__(self, wizard): <NEW_LINE> <INDENT> self._wizard = wizard <NEW_LINE> <DEDENT> def __dir__(self): <NEW_LINE> <INDENT> return self.all <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self.count <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<%s for %s (steps: %s)>' % (self.__class__.__name__, self._wizard, self.all) <NEW_LINE> <DEDENT> def __getitem__(self, step_name): <NEW_LINE> <INDENT> step = self._wizard.storage[step_name] <NEW_LINE> if not step.forms: <NEW_LINE> <INDENT> step.forms = self._wizard.forms[step_name] <NEW_LINE> <DEDENT> return step <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for name in self._wizard.get_forms().keys(): <NEW_LINE> <INDENT> yield self[name] <NEW_LINE> <DEDENT> <DEDENT> def from_slug(self, slug): <NEW_LINE> <INDENT> for step in self: <NEW_LINE> <INDENT> if step.slug == slug: <NEW_LINE> <INDENT> return step <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def all(self): <NEW_LINE> <INDENT> return list(self) <NEW_LINE> <DEDENT> @property <NEW_LINE> def count(self): <NEW_LINE> <INDENT> return len(self._wizard.get_forms()) <NEW_LINE> <DEDENT> @property <NEW_LINE> def current(self): <NEW_LINE> <INDENT> if self._wizard.storage.current_step: <NEW_LINE> <INDENT> return self[self._wizard.storage.current_step.name] <NEW_LINE> <DEDENT> return self.first <NEW_LINE> <DEDENT> @current.setter <NEW_LINE> def current(self, step): <NEW_LINE> <INDENT> self._wizard.storage.current_step = step <NEW_LINE> <DEDENT> @property <NEW_LINE> def first(self): <NEW_LINE> <INDENT> return self[self._wizard.get_forms().keyOrder[0]] <NEW_LINE> <DEDENT> @property <NEW_LINE> def last(self): <NEW_LINE> <INDENT> return self[self._wizard.get_forms().keyOrder[-1]] <NEW_LINE> <DEDENT> @property <NEW_LINE> def next(self): <NEW_LINE> <INDENT> key = self.index + 1 <NEW_LINE> forms = self._wizard.get_forms() <NEW_LINE> if len(forms.keyOrder) > key: <NEW_LINE> <INDENT> return self[forms.keyOrder[key]] <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> @property <NEW_LINE> def previous(self): <NEW_LINE> <INDENT> key = self.index - 1 <NEW_LINE> if key >= 0: <NEW_LINE> <INDENT> return self[self._wizard.get_forms().keyOrder[key]] <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> @property <NEW_LINE> def index(self): <NEW_LINE> <INDENT> return self._wizard.get_forms().keyOrder.index(self.current.name) <NEW_LINE> <DEDENT> index0 = index <NEW_LINE> @property <NEW_LINE> def index1(self): <NEW_LINE> <INDENT> return self.index0 + 1 | A helper class that makes accessing steps easier. | 62599053a17c0f6771d5d623 |
class AutoFlush(Wrapper): <NEW_LINE> <INDENT> def __init__(self, wrapped, delay): <NEW_LINE> <INDENT> super(AutoFlush, self).__init__(wrapped) <NEW_LINE> if not hasattr(self, 'lock'): <NEW_LINE> <INDENT> self.lock = threading.Lock() <NEW_LINE> <DEDENT> self.__last_flushed_at = time.time() <NEW_LINE> self.delay = delay <NEW_LINE> <DEDENT> @property <NEW_LINE> def autoflush(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def write(self, out, *args, **kwargs): <NEW_LINE> <INDENT> self._wrapped.write(out, *args, **kwargs) <NEW_LINE> should_flush = False <NEW_LINE> self.lock.acquire() <NEW_LINE> try: <NEW_LINE> <INDENT> if self.delay and (time.time() - self.__last_flushed_at) > self.delay: <NEW_LINE> <INDENT> should_flush = True <NEW_LINE> self.__last_flushed_at = time.time() <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> self.lock.release() <NEW_LINE> <DEDENT> if should_flush: <NEW_LINE> <INDENT> self.flush() | Creates a file object clone to automatically flush after N seconds. | 6259905338b623060ffaa2d1 |
class TestMomJobDir(TestFunctional): <NEW_LINE> <INDENT> def change_server_name(self, servername): <NEW_LINE> <INDENT> self.server.stop() <NEW_LINE> self.assertFalse(self.server.isUp(), 'Failed to stop PBS') <NEW_LINE> conf = self.du.parse_pbs_config(self.server.hostname) <NEW_LINE> self.du.set_pbs_config( self.server.hostname, confs={'PBS_SERVER_HOST_NAME': conf['PBS_SERVER'], 'PBS_SERVER': servername}) <NEW_LINE> self.server.start() <NEW_LINE> self.assertTrue(self.server.isUp(), 'Failed to start PBS') <NEW_LINE> return <NEW_LINE> <DEDENT> def test_existing_directory_longid(self): <NEW_LINE> <INDENT> self.change_server_name('superlongservername') <NEW_LINE> j = Job(TEST_USER, attrs={ATTR_h: None}) <NEW_LINE> j.set_sleep_time(3) <NEW_LINE> jid = self.server.submit(j) <NEW_LINE> path = self.mom.get_formed_path(self.mom.pbs_conf['PBS_HOME'], 'mom_priv', 'jobs', jid + '.TK') <NEW_LINE> self.logger.info('Creating directory %s', path) <NEW_LINE> self.du.mkdir(hostname=self.mom.hostname, path=path, sudo=True) <NEW_LINE> self.server.rlsjob(jid, USER_HOLD) <NEW_LINE> self.server.expect(JOB, 'queue', id=jid, op=UNSET, max_attempts=20, interval=1, offset=1) <NEW_LINE> ret = self.du.isdir(hostname=self.mom.hostname, path=path, sudo=True) <NEW_LINE> self.assertFalse(ret, 'Directory %s still exists.' % path) <NEW_LINE> <DEDENT> def test_existing_directory_shortid(self): <NEW_LINE> <INDENT> self.change_server_name('svr') <NEW_LINE> j = Job(TEST_USER, attrs={ATTR_h: None}) <NEW_LINE> j.set_sleep_time(3) <NEW_LINE> jid = self.server.submit(j) <NEW_LINE> path = self.mom.get_formed_path(self.mom.pbs_conf['PBS_HOME'], 'mom_priv', 'jobs', jid + '.TK') <NEW_LINE> self.logger.info('Creating directory %s', path) <NEW_LINE> self.du.mkdir(hostname=self.mom.hostname, path=path, sudo=True) <NEW_LINE> self.server.rlsjob(jid, USER_HOLD) <NEW_LINE> self.server.expect(JOB, 'queue', id=jid, op=UNSET, max_attempts=20, interval=1, offset=1) <NEW_LINE> ret = self.du.isdir(hostname=self.mom.hostname, path=path, sudo=True) <NEW_LINE> self.assertFalse(ret, 'Directory %s still exists.' % path) | This test suite tests the mom's ability to create job directories. | 6259905330dc7b76659a0d01 |
class Solution: <NEW_LINE> <INDENT> def findSpecialInteger(self, arr: List[int]) -> int: <NEW_LINE> <INDENT> target = len(arr) // 4 <NEW_LINE> current = arr[0] <NEW_LINE> if len(arr) == 1: return current <NEW_LINE> i = 1 <NEW_LINE> while i < len(arr): <NEW_LINE> <INDENT> if arr[i + target] == current: <NEW_LINE> <INDENT> return current <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> while arr[i] == current: <NEW_LINE> <INDENT> i += 1 <NEW_LINE> <DEDENT> current = arr[i] | Time: 60% (90ms) | 6259905307d97122c42181af |
class FloScriptLexer(RegexLexer): <NEW_LINE> <INDENT> name = 'FloScript' <NEW_LINE> aliases = ['floscript', 'flo'] <NEW_LINE> filenames = ['*.flo'] <NEW_LINE> def innerstring_rules(ttype): <NEW_LINE> <INDENT> return [ (r'%(\(\w+\))?[-#0 +]*([0-9]+|[*])?(\.([0-9]+|[*]))?' '[hlL]?[E-GXc-giorsux%]', String.Interpol), (r'[^\\\'"%\n]+', ttype), (r'[\'"\\]', ttype), (r'%', ttype), ] <NEW_LINE> <DEDENT> tokens = { 'root': [ (r'\s+', Whitespace), (r'[]{}:(),;[]', Punctuation), (r'(\\)(\n)', bygroups(Text, Whitespace)), (r'\\', Text), (r'(to|by|with|from|per|for|cum|qua|via|as|at|in|of|on|re|is|if|be|into|' r'and|not)\b', Operator.Word), (r'!=|==|<<|>>|[-~+/*%=<>&^|.]', Operator), (r'(load|init|server|logger|log|loggee|first|over|under|next|done|timeout|' r'repeat|native|benter|enter|recur|exit|precur|renter|rexit|print|put|inc|' r'copy|set|aux|rear|raze|go|let|do|bid|ready|start|stop|run|abort|use|flo|' r'give|take)\b', Name.Builtin), (r'(frame|framer|house)\b', Keyword), ('"', String, 'string'), include('name'), include('numbers'), (r'#.+$', Comment.Single), ], 'string': [ ('[^"]+', String), ('"', String, '#pop'), ], 'numbers': [ (r'(\d+\.\d*|\d*\.\d+)([eE][+-]?[0-9]+)?j?', Number.Float), (r'\d+[eE][+-]?[0-9]+j?', Number.Float), (r'0[0-7]+j?', Number.Oct), (r'0[bB][01]+', Number.Bin), (r'0[xX][a-fA-F0-9]+', Number.Hex), (r'\d+L', Number.Integer.Long), (r'\d+j?', Number.Integer) ], 'name': [ (r'@[\w.]+', Name.Decorator), (r'[a-zA-Z_]\w*', Name), ], } | For `FloScript <https://github.com/ioflo/ioflo>`_ configuration language source code.
.. versionadded:: 2.4 | 62599053b5575c28eb71374e |
class testAuthent (unittest.TestCase) : <NEW_LINE> <INDENT> pass | def testGetUser(self):
user = User()
user.email = '[email protected]'
user.put()
user2 = User.get_by_email('[email protected]')
#self.assert_(user == user2) # fails - why?
self.assert_(user.email == user2.email) | 6259905345492302aabfd9dd |
class ColdCaller: <NEW_LINE> <INDENT> def __init__(self, roster): <NEW_LINE> <INDENT> roster_file = open(roster, 'r') <NEW_LINE> self.roster = roster_file.read().splitlines() <NEW_LINE> self.students = len(self.roster) <NEW_LINE> <DEDENT> '''Call on a student from roster randomly''' <NEW_LINE> def call(self): <NEW_LINE> <INDENT> randIndex = random.randint(0, self.students - 1) <NEW_LINE> return self.roster[randIndex] | ColdCaller class
takes roster - string of filename with list of students, names separated by linebreaks | 62599053b830903b9686ef00 |
class Team(dataobjects.ValueObject): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.players = [] <NEW_LINE> <DEDENT> def equalsVariables(self): <NEW_LINE> <INDENT> return ['name'] <NEW_LINE> <DEDENT> def addPlayer(self, player): <NEW_LINE> <INDENT> self.players.append(player) <NEW_LINE> <DEDENT> def numberOfPlayers(self): <NEW_LINE> <INDENT> return len(self.players) | from gameengine import game
game.Team(...) | 62599053be8e80087fbc0586 |
@python_2_unicode_compatible <NEW_LINE> class AbstractAttachment(models.Model): <NEW_LINE> <INDENT> post = models.ForeignKey('forum_conversation.Post', verbose_name=_('Post'), related_name='attachments') <NEW_LINE> file = models.FileField(verbose_name=_('File'), upload_to=machina_settings.ATTACHMENT_FILE_UPLOAD_TO) <NEW_LINE> comment = models.CharField(max_length=255, verbose_name=_('Comment'), blank=True, null=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> app_label = 'forum_attachments' <NEW_LINE> verbose_name = _('Attachment') <NEW_LINE> verbose_name_plural = _('Attachments') <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '{}'.format(self.post.subject) <NEW_LINE> <DEDENT> @property <NEW_LINE> def filename(self): <NEW_LINE> <INDENT> return os.path.basename(self.file.name) <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> from django.core.urlresolvers import reverse <NEW_LINE> return reverse('forum_conversation:attachment', kwargs={'pk': str(self.id)}) | Represents a post attachment. An attachment is always linked to a post. | 6259905326068e7796d4de4d |
class MetaDataManager(models.Manager): <NEW_LINE> <INDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.get_query_set().get(name=key).value <NEW_LINE> <DEDENT> except MetaData.DoesNotExist: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> metadata = self.instance.metadata.get(name=key) <NEW_LINE> metadata.value = value <NEW_LINE> metadata.save() <NEW_LINE> <DEDENT> except MetaData.DoesNotExist: <NEW_LINE> <INDENT> metadata = self.instance.metadata.create(name=key, value=value) <NEW_LINE> <DEDENT> <DEDENT> def __contains__(self, key): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if not self[key] is None: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> except IndexError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self.iteritems() <NEW_LINE> <DEDENT> def iterkeys(self): <NEW_LINE> <INDENT> for metadata in self.get_query_set().order_by('name'): <NEW_LINE> <INDENT> yield metadata.name <NEW_LINE> <DEDENT> <DEDENT> def keys(self): <NEW_LINE> <INDENT> return list(self.iterkeys()) <NEW_LINE> <DEDENT> def itervalues(self): <NEW_LINE> <INDENT> for metadata in self.get_query_set().order_by('name'): <NEW_LINE> <INDENT> yield metadata.value <NEW_LINE> <DEDENT> <DEDENT> def values(self): <NEW_LINE> <INDENT> return list(self.itervalues()) <NEW_LINE> <DEDENT> def iteritems(self): <NEW_LINE> <INDENT> for metadata in self.get_query_set().order_by('name'): <NEW_LINE> <INDENT> yield metadata.name, metadata.value <NEW_LINE> <DEDENT> <DEDENT> def items(self): <NEW_LINE> <INDENT> return list(self.iteritems()) | This manager allow to with MetaData.objects as a Dict (useful for
templates). | 6259905329b78933be26ab47 |
class DeviceError(MeFrame): <NEW_LINE> <INDENT> _SOURCE = "!" <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(DeviceError, self).__init__() <NEW_LINE> self._ERRORS = [] <NEW_LINE> for error in ERRORS: <NEW_LINE> <INDENT> self._ERRORS.append(Error(error)) <NEW_LINE> <DEDENT> <DEDENT> def _get_by_code(self, code): <NEW_LINE> <INDENT> for error in self._ERRORS: <NEW_LINE> <INDENT> if error.code == code: <NEW_LINE> <INDENT> return error <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def compose(self, part=False): <NEW_LINE> <INDENT> frame = self._SOURCE + "{:02X}".format(self.ADDRESS) + "{:04X}".format(self.SEQUENCE) <NEW_LINE> frame += self.PAYLOAD[0] <NEW_LINE> frame += "{:02x}".format(self.PAYLOAD[1]) <NEW_LINE> if part: <NEW_LINE> <INDENT> return frame.encode() <NEW_LINE> <DEDENT> if self.CRC is None: <NEW_LINE> <INDENT> self.crc() <NEW_LINE> <DEDENT> frame += "{:04X}".format(self.CRC) <NEW_LINE> frame += self._EOL <NEW_LINE> return frame.encode() <NEW_LINE> <DEDENT> def decompose(self, frame_bytes): <NEW_LINE> <INDENT> frame_bytes = self._SOURCE.encode() + frame_bytes <NEW_LINE> self._decompose_header(frame_bytes) <NEW_LINE> frame = frame_bytes.decode() <NEW_LINE> self.PAYLOAD.append(frame[7]) <NEW_LINE> self.PAYLOAD.append(int(frame[8:10], 16)) <NEW_LINE> self.crc(int(frame[-4:], 16)) <NEW_LINE> <DEDENT> def error(self): <NEW_LINE> <INDENT> error_code = self.PAYLOAD[1] <NEW_LINE> return self._get_by_code(error_code).as_list() | Queries failing return a device error, implemented as repsonse by this class. | 625990533eb6a72ae038bb65 |
class TMQStream(NMEAStream): <NEW_LINE> <INDENT> def _get_type(self, sentence): <NEW_LINE> <INDENT> sentence = sentence.split(',') <NEW_LINE> sen_type = sentence[0].lstrip('$') <NEW_LINE> if not sen_type[:-1] == 'PTMQ': <NEW_LINE> <INDENT> raise TypeError('Not a TMQ sentence') <NEW_LINE> <DEDENT> sen_type = sen_type[-3:] <NEW_LINE> sen_mod = __import__('pynmea.nmea', fromlist=[sen_type]) <NEW_LINE> sen_obj = getattr(sen_mod, sen_type, None) <NEW_LINE> return sen_obj <NEW_LINE> <DEDENT> def _split(self, data, separator=None): <NEW_LINE> <INDENT> sentences = re.split('\$(?=PTMQ)', data) <NEW_LINE> cleaned_sentences = [] <NEW_LINE> for item in sentences: <NEW_LINE> <INDENT> if item: <NEW_LINE> <INDENT> tag = item.split(',')[0][-1] <NEW_LINE> if tag == 'A' and len(item) >= 22: <NEW_LINE> <INDENT> cleaned_item = item[:22].rstrip() <NEW_LINE> <DEDENT> elif tag == 'H' and len(item) >= 15: <NEW_LINE> <INDENT> cleaned_item = item[:15].rstrip() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> cleaned_item = '$'+cleaned_item <NEW_LINE> cleaned_sentences.append(cleaned_item) <NEW_LINE> <DEDENT> <DEDENT> return cleaned_sentences <NEW_LINE> <DEDENT> def _read(self, data=None, size=1024): <NEW_LINE> <INDENT> if not data and not self.stream and not self.head: <NEW_LINE> <INDENT> raise NoDataGivenError('No data was provided') <NEW_LINE> <DEDENT> if not data and self.stream: <NEW_LINE> <INDENT> read_data = self.stream.read(size) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> read_data = data <NEW_LINE> <DEDENT> data = self.head + read_data <NEW_LINE> raw_sentences = self._split(data) <NEW_LINE> if not read_data: <NEW_LINE> <INDENT> self.head = '' <NEW_LINE> return raw_sentences <NEW_LINE> <DEDENT> elif not raw_sentences: <NEW_LINE> <INDENT> self.head = data <NEW_LINE> return raw_sentences <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return raw_sentences | This class is used to process "NMEA" data sent by TMQ devices.
This privilege is bestowed upon TMQ, since they are a bunch of fuktards who can't
get right as simple a task as implementing a simple serial protocol. Even.
There are some major problems with TMQ data, which is sent in binary format. Such as stated
below.
The specification of NMEA protocol encoding: http://catb.org/gpsd/NMEA.html#_nmea_encoding_conventions
TMQ devices commit some major crimes such as:
# Start delimiter as data
'$PTMQA,$Ma$M *18
'
compass angle: 137
# Newline as data
'$PTMQA,
'
compass angle: 258
# End delimiter (*) as data
'$PTMQA,*M\*M *25
'
compass angle: 138
The strategy used to solve this mess is following:
1. Treat statement name ('PTMQA') as delimiter.
2. Treat statements as fixed length strings.
3. Assume that TMQ statements always provide
at the end of statement
| 625990534a966d76dd5f03f5 |
class FlowConversionMode(Enum, IComparable, IFormattable, IConvertible): <NEW_LINE> <INDENT> def __eq__(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __format__(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __ge__(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __gt__(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __le__(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __lt__(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __ne__(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __reduce_ex__(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __str__(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> Invalid = None <NEW_LINE> Tanks = None <NEW_LINE> value__ = None <NEW_LINE> Valves = None | Enumerated type listing possible flow conversion modes for piping calculations.
enum FlowConversionMode, values: Invalid (-1), Tanks (1), Valves (0) | 6259905394891a1f408ba179 |
class MultiScrapper: <NEW_LINE> <INDENT> sourceURLs = [] <NEW_LINE> goodOnes = [] <NEW_LINE> badOnes = [] <NEW_LINE> counter = 0 <NEW_LINE> def scrap_data(self, startingPoint=0, sleepInt=300, logFile="scrap.log"): <NEW_LINE> <INDENT> import time <NEW_LINE> import sys <NEW_LINE> import traceback <NEW_LINE> from nourisher.nourish import Nourisher <NEW_LINE> self.counter = startingPoint + 1 <NEW_LINE> for url in self.sourceURLs: <NEW_LINE> <INDENT> now = time.time() <NEW_LINE> try: <NEW_LINE> <INDENT> log.debug("\nProcessing {0}/{1}: {2}".format(self.counter, len(self.sourceURLs), url)) <NEW_LINE> nour = Nourisher(url) <NEW_LINE> nour.collect_all() <NEW_LINE> nour.retrieve_data() <NEW_LINE> nour.clean_data() <NEW_LINE> nour.update_object_db("cleaned", nour.dataCleaned) <NEW_LINE> self.goodOnes.append(url) <NEW_LINE> <DEDENT> except KeyboardInterrupt as ex: <NEW_LINE> <INDENT> log.debug("So far were processed {0} ({1}) URLs. ".format(self.counter, url)) <NEW_LINE> raise ex <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> sysEr = sys.exc_info() <NEW_LINE> tracb = traceback.format_exc() <NEW_LINE> log.debug(sysEr + tracb) <NEW_LINE> self.badOnes.append((url, tracb)) <NEW_LINE> with open(logFile, "a", encoding="utf-8") as logf: <NEW_LINE> <INDENT> logf.writeline(url) <NEW_LINE> logf.writeline("\n".join(tracb)) <NEW_LINE> <DEDENT> <DEDENT> log.debug("It tooks: {0} seconds. \n---------------\n".format(time.time() - now)) <NEW_LINE> time.sleep(sleepInt) <NEW_LINE> self.counter += 1 <NEW_LINE> <DEDENT> <DEDENT> def fetch_urls(self, filePath): <NEW_LINE> <INDENT> with open(filePath, "r", encoding="utf-8") as ifile: <NEW_LINE> <INDENT> lurls = ifile.readlines() <NEW_LINE> urls = [line.split("\n")[0] for line in lurls] <NEW_LINE> <DEDENT> self.sourceURLs += urls <NEW_LINE> log.debug(self.sourceURLs) | This is for collecting data for multiple source URLs
Attributes
----------
sourceURLs : list of strings
list of URLs which we want to scrap
goodOnes : list of strings
urls which were processed correctly
badOnes : list of strings
urls which were processed correctly
counter : int
number of processed URLs so far | 625990536e29344779b01b4f |
class TopicReadTracker(models.Model): <NEW_LINE> <INDENT> user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=False, null=False) <NEW_LINE> topic = models.ForeignKey(Topic, blank=True, null=True) <NEW_LINE> time_stamp = models.DateTimeField(auto_now=True) <NEW_LINE> objects = TopicReadTrackerManager() <NEW_LINE> class Meta(object): <NEW_LINE> <INDENT> verbose_name = _('Topic read tracker') <NEW_LINE> verbose_name_plural = _('Topic read trackers') <NEW_LINE> unique_together = ('user', 'topic') | Save per user topic read tracking | 62599053507cdc57c63a62ab |
class RetinaNetModule(nn.Module): <NEW_LINE> <INDENT> def __init__(self, cfg): <NEW_LINE> <INDENT> super(RetinaNetModule, self).__init__() <NEW_LINE> self.cfg = cfg.clone() <NEW_LINE> anchor_generator = make_anchor_generator_retinanet(cfg) <NEW_LINE> head = RetinaNetHead(cfg) <NEW_LINE> box_coder = BoxCoder(weights=(10., 10., 5., 5.)) <NEW_LINE> box_selector_test = make_retinanet_postprocessor(cfg, box_coder, is_train=False) <NEW_LINE> loss_evaluator = make_retinanet_loss_evaluator(cfg, box_coder) <NEW_LINE> self.anchor_generator = anchor_generator <NEW_LINE> self.head = head <NEW_LINE> self.box_selector_test = box_selector_test <NEW_LINE> self.loss_evaluator = loss_evaluator <NEW_LINE> self.anchors = None <NEW_LINE> <DEDENT> def forward(self, images, features, targets=None): <NEW_LINE> <INDENT> box_cls, box_regression = self.head(features) <NEW_LINE> if self.anchors is None and not isinstance(targets, dict): <NEW_LINE> <INDENT> anchors = self.anchor_generator(images, features) <NEW_LINE> <DEDENT> elif self.anchors is None and isinstance(targets, dict): <NEW_LINE> <INDENT> anchors = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> anchors = self.anchors <NEW_LINE> <DEDENT> if self.training: <NEW_LINE> <INDENT> return self._forward_train(anchors, box_cls, box_regression, targets) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._forward_test(anchors, box_cls, box_regression) <NEW_LINE> <DEDENT> <DEDENT> def generate_anchors(self, mini_batch_size, crop_size): <NEW_LINE> <INDENT> grid_sizes = [(math.ceil(crop_size / r), math.ceil(crop_size / r)) for r in (8, 16, 32, 64, 128)] <NEW_LINE> self.anchors = self.anchor_generator.get_anchors(mini_batch_size, crop_size, grid_sizes) <NEW_LINE> <DEDENT> def _forward_train(self, anchors, box_cls, box_regression, targets): <NEW_LINE> <INDENT> loss_box_cls, loss_box_reg = self.loss_evaluator( anchors, box_cls, box_regression, targets ) <NEW_LINE> losses = { "loss_retina_cls": loss_box_cls, "loss_retina_reg": loss_box_reg, } <NEW_LINE> return anchors, losses <NEW_LINE> <DEDENT> def _forward_test(self, anchors, box_cls, box_regression): <NEW_LINE> <INDENT> boxes = self.box_selector_test(anchors, box_cls, box_regression) <NEW_LINE> return boxes, {} | Module for RetinaNet computation. Takes feature maps from the backbone and RPN
proposals and losses. | 625990537d847024c075d8e1 |
class int16(vs_bases.v_int): <NEW_LINE> <INDENT> def __init__(self, valu=0, endian='little'): <NEW_LINE> <INDENT> vs_bases.v_int.__init__(self, valu=valu, size=2, endian=endian, signed=True) | Signed 16 bit integer type | 62599053d7e4931a7ef3d584 |
class UnreadableFileError(Exception): <NEW_LINE> <INDENT> def __init__(self, path): <NEW_LINE> <INDENT> Exception.__init__(self, path) | Mutagen is not able to extract information from the file.
| 625990533cc13d1c6d466c44 |
class Identity(object): <NEW_LINE> <INDENT> def __init__(self, enrollment_id, user): <NEW_LINE> <INDENT> if not isinstance(user, Enrollment): <NEW_LINE> <INDENT> raise ValueError('"user" is not a valid Enrollment object') <NEW_LINE> <DEDENT> self._enrollment_id = enrollment_id <NEW_LINE> self._EnrollmentCert = user.cert <NEW_LINE> self._PrivateKey = user.private_key.private_bytes(encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption()) <NEW_LINE> <DEDENT> def CreateIdentity(self, Wallet): <NEW_LINE> <INDENT> sub_directory = Wallet._path + '/' + self._enrollment_id + '/' <NEW_LINE> os.makedirs(sub_directory, exist_ok=True) <NEW_LINE> f = open(sub_directory+'private_sk', 'wb') <NEW_LINE> f.write(self._PrivateKey) <NEW_LINE> f.close() <NEW_LINE> f = open(sub_directory+'enrollmentCert.pem', 'wb') <NEW_LINE> f.write(self._EnrollmentCert) <NEW_LINE> f.close() | Class represents a tuple containing
1) enrollment_id
2) Enrollment Certificate of user
3) Private Key of user | 62599053462c4b4f79dbcf0b |
class TestSuite(unittest.TestCase): <NEW_LINE> <INDENT> def test_ArrayStack(self): <NEW_LINE> <INDENT> stack = ArrayStack() <NEW_LINE> stack.push(1) <NEW_LINE> stack.push(2) <NEW_LINE> stack.push(3) <NEW_LINE> it = stack.__iter__() <NEW_LINE> self.assertEqual(3, next(it)) <NEW_LINE> self.assertEqual(2, next(it)) <NEW_LINE> self.assertEqual(1, next(it)) <NEW_LINE> try: <NEW_LINE> <INDENT> next(it) <NEW_LINE> self.assertTrue(False) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.assertTrue(True) <NEW_LINE> <DEDENT> self.assertEqual(3, stack.__len__()) <NEW_LINE> self.assertFalse(stack.isEmpty()) <NEW_LINE> self.assertEqual(3, stack.peek()) <NEW_LINE> self.assertEqual(3, stack.pop()) <NEW_LINE> self.assertEqual(2, stack.pop()) <NEW_LINE> self.assertEqual(1, stack.pop()) <NEW_LINE> self.assertTrue(stack.isEmpty()) <NEW_LINE> <DEDENT> def test_LinkedListStack(self): <NEW_LINE> <INDENT> stack = LinkedListStack() <NEW_LINE> stack.push(1) <NEW_LINE> stack.push(2) <NEW_LINE> stack.push(3) <NEW_LINE> it = stack.__iter__() <NEW_LINE> self.assertEqual(3, next(it)) <NEW_LINE> self.assertEqual(2, next(it)) <NEW_LINE> self.assertEqual(1, next(it)) <NEW_LINE> try: <NEW_LINE> <INDENT> next(it) <NEW_LINE> self.assertTrue(False) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.assertTrue(True) <NEW_LINE> <DEDENT> self.assertEqual(3, stack.__len__()) <NEW_LINE> self.assertFalse(stack.isEmpty()) <NEW_LINE> self.assertEqual(3, stack.peek()) <NEW_LINE> self.assertEqual(3, stack.pop()) <NEW_LINE> self.assertEqual(2, stack.pop()) <NEW_LINE> self.assertEqual(1, stack.pop()) <NEW_LINE> self.assertTrue(stack.isEmpty()) | Test suite for the stack data structures (above) | 62599053d99f1b3c44d06ba6 |
class ResourcedTestCase(unittest.TestCase): <NEW_LINE> <INDENT> resources = [] <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> super(ResourcedTestCase, self).setUp() <NEW_LINE> self.setUpResources() <NEW_LINE> <DEDENT> def setUpResources(self): <NEW_LINE> <INDENT> setUpResources(self, self.resources, _get_result()) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.tearDownResources() <NEW_LINE> super(ResourcedTestCase, self).tearDown() <NEW_LINE> <DEDENT> def tearDownResources(self): <NEW_LINE> <INDENT> tearDownResources(self, self.resources, _get_result()) | A TestCase parent or utility that enables cross-test resource usage.
ResourcedTestCase is a thin wrapper around the
testresources.setUpResources and testresources.tearDownResources helper
functions. It should be trivially reimplemented where a different base
class is neded, or you can use multiple inheritance and call into
ResourcedTestCase.setUpResources and ResourcedTestCase.tearDownResources
from your setUp and tearDown (or whatever cleanup idiom is used).
:ivar resources: A list of (name, resource) pairs, where 'resource' is a
subclass of `TestResourceManager` and 'name' is the name of the
attribute that the resource should be stored on. | 625990532ae34c7f260ac5ed |
class MyRobot(wpilib.SampleRobot): <NEW_LINE> <INDENT> def robotInit(self): <NEW_LINE> <INDENT> self.lstick = wpilib.Joystick(0) <NEW_LINE> self.rstick = wpilib.Joystick(1) <NEW_LINE> self.lr_motor = wpilib.Jaguar(1) <NEW_LINE> self.rr_motor = wpilib.Jaguar(2) <NEW_LINE> self.lf_motor = wpilib.Jaguar(3) <NEW_LINE> self.rf_motor = wpilib.Jaguar(4) <NEW_LINE> self.robot_drive = wpilib.RobotDrive(self.lf_motor, self.lr_motor, self.rf_motor, self.rr_motor) <NEW_LINE> self.gyro = wpilib.AnalogGyro(1) <NEW_LINE> <DEDENT> def disabled(self): <NEW_LINE> <INDENT> while self.isDisabled(): <NEW_LINE> <INDENT> wpilib.Timer.delay(0.01) <NEW_LINE> <DEDENT> <DEDENT> def autonomous(self): <NEW_LINE> <INDENT> timer = wpilib.Timer() <NEW_LINE> timer.start() <NEW_LINE> while self.isAutonomous() and self.isEnabled(): <NEW_LINE> <INDENT> if timer.get() < 2.0: <NEW_LINE> <INDENT> self.robot_drive.arcadeDrive(-1.0, -.3) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.robot_drive.arcadeDrive(0, 0) <NEW_LINE> <DEDENT> wpilib.Timer.delay(0.01) <NEW_LINE> <DEDENT> <DEDENT> def operatorControl(self): <NEW_LINE> <INDENT> while self.isOperatorControl() and self.isEnabled(): <NEW_LINE> <INDENT> self.robot_drive.tankDrive(self.lstick, self.rstick) <NEW_LINE> wpilib.Timer.delay(0.04) | Main robot class | 6259905391af0d3eaad3b32f |
class RegistrationManager(models.Manager): <NEW_LINE> <INDENT> def activate_user(self, activation_key): <NEW_LINE> <INDENT> from registration.signals import user_activated <NEW_LINE> if SHA1_RE.search(activation_key): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> profile = self.get(activation_key=activation_key) <NEW_LINE> <DEDENT> except self.model.DoesNotExist: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not profile.activation_key_expired(): <NEW_LINE> <INDENT> user = profile.user <NEW_LINE> user.is_active = True <NEW_LINE> user.save() <NEW_LINE> profile.activation_key = self.model.ACTIVATED <NEW_LINE> profile.save() <NEW_LINE> user_activated.send(sender=self.model, user=user) <NEW_LINE> return user <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def create_inactive_user(self, username, password, email, send_email=True): <NEW_LINE> <INDENT> from registration.signals import user_registered <NEW_LINE> new_user = User.objects.create_user(username, email, password) <NEW_LINE> new_user.is_active = False <NEW_LINE> new_user.save() <NEW_LINE> registration_profile = self.create_profile(new_user) <NEW_LINE> if send_email: <NEW_LINE> <INDENT> from django.core.mail import send_mail <NEW_LINE> subject = render_to_string('registration/activation_email_subject.txt', { 'site': settings.SITE_NAME }) <NEW_LINE> subject = ''.join(subject.splitlines()) <NEW_LINE> message = render_to_string('registration/activation_email.txt', { 'activation_key': registration_profile.activation_key, 'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS, 'url': settings.SITE_URL, 'site': settings.SITE_NAME }) <NEW_LINE> send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [new_user.email]) <NEW_LINE> <DEDENT> user_registered.send(sender=self.model, user=new_user) <NEW_LINE> return new_user <NEW_LINE> <DEDENT> create_inactive_user = transaction.commit_on_success(create_inactive_user) <NEW_LINE> def create_profile(self, user): <NEW_LINE> <INDENT> salt = sha_constructor(str(random.random())).hexdigest()[:5] <NEW_LINE> activation_key = sha_constructor(salt+user.username).hexdigest() <NEW_LINE> return self.create(user=user, activation_key=activation_key) <NEW_LINE> <DEDENT> def delete_expired_users(self): <NEW_LINE> <INDENT> for profile in self.all(): <NEW_LINE> <INDENT> if profile.activation_key_expired(): <NEW_LINE> <INDENT> user = profile.user <NEW_LINE> if not user.is_active: <NEW_LINE> <INDENT> user.delete() | Custom manager for the ``RegistrationProfile`` model.
The methods defined here provide shortcuts for account creation
and activation (including generation and emailing of activation
keys), and for cleaning out expired inactive accounts. | 625990530a50d4780f706842 |
class EGGAnimJoint(Group): <NEW_LINE> <INDENT> def make_hierarchy_from_list(self, obj_list): <NEW_LINE> <INDENT> for obj in obj_list: <NEW_LINE> <INDENT> if ((obj.parent == self.object) or ((self.object == None) and (str(obj.parent) not in map(str, obj_list)) and (str(obj) not in [str(ch.object) for ch in self.children]))): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> gr = self.__class__(obj) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print_exc() <NEW_LINE> return ['ERR_MK_OBJ', ] <NEW_LINE> <DEDENT> self.children.append(gr) <NEW_LINE> gr.make_hierarchy_from_list(obj_list) <NEW_LINE> <DEDENT> <DEDENT> return [] <NEW_LINE> <DEDENT> def get_full_egg_str(self, anim_info, framerate, level=0): <NEW_LINE> <INDENT> egg_str = '' <NEW_LINE> if self.object: <NEW_LINE> <INDENT> egg_str += '%s<Table> %s {\n' % (' ' * level, eggSafeName(self.object.yabee_name)) <NEW_LINE> bone_data = anim_info['<skeleton>'][self.object.yabee_name] <NEW_LINE> egg_str += '%s <Xfm$Anim> xform {\n' % (' ' * level) <NEW_LINE> egg_str += '%s <Scalar> order { sprht }\n' % (' ' * level) <NEW_LINE> egg_str += '%s <Scalar> fps { %i }\n' % (' ' * level, framerate) <NEW_LINE> egg_str += '%s <Scalar> contents { ijkprhxyz }\n' % (' ' * level) <NEW_LINE> egg_str += '%s <V> {\n' % (' ' * level) <NEW_LINE> for i in range(len(bone_data['r'])): <NEW_LINE> <INDENT> egg_str += '%s %s %s %s %s %s %s %s %s %s\n' % ( ' ' * level, STRF(bone_data['i'][i]), STRF(bone_data['j'][i]), STRF(bone_data['k'][i]), STRF(bone_data['p'][i]), STRF(bone_data['r'][i]), STRF(bone_data['h'][i]), STRF(bone_data['x'][i]), STRF(bone_data['y'][i]), STRF(bone_data['z'][i])) <NEW_LINE> <DEDENT> egg_str += '%s }\n' % (' ' * level) <NEW_LINE> egg_str += '%s }\n' % (' ' * level) <NEW_LINE> for ch in self.children: <NEW_LINE> <INDENT> egg_str += ch.get_full_egg_str(anim_info, framerate, level + 1) <NEW_LINE> <DEDENT> egg_str += '%s}\n' % (' ' * level) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for ch in self.children: <NEW_LINE> <INDENT> egg_str += ch.get_full_egg_str(anim_info, framerate, level + 1) <NEW_LINE> <DEDENT> <DEDENT> return egg_str | Representation of the <Joint> animation data. Has the same
hierarchy as the character's skeleton. | 625990530fa83653e46f63eb |
class SpeedRPM(SpeedValue): <NEW_LINE> <INDENT> def __init__(self, rotations_per_minute, desc=None): <NEW_LINE> <INDENT> self.rotations_per_minute = rotations_per_minute <NEW_LINE> self.desc = desc <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "{} ".format(self.desc) if self.desc else "" + str(self.rotations_per_minute) + " rot/min" <NEW_LINE> <DEDENT> def __mul__(self, other): <NEW_LINE> <INDENT> assert isinstance(other, (float, int)), "{} can only be multiplied by an int or float".format(self) <NEW_LINE> return SpeedRPM(self.rotations_per_minute * other) <NEW_LINE> <DEDENT> def to_native_units(self, motor): <NEW_LINE> <INDENT> if abs(self.rotations_per_minute) > motor.max_rpm: <NEW_LINE> <INDENT> raise SpeedInvalid("invalid rotations-per-minute: {} max RPM is {}, {} was requested".format( motor, motor.max_rpm, self.rotations_per_minute)) <NEW_LINE> <DEDENT> return self.rotations_per_minute / motor.max_rpm * motor.max_speed | Speed in rotations-per-minute. | 625990538e71fb1e983bcfd0 |
class MainMenu(Screen): <NEW_LINE> <INDENT> pass | The main menu widget. | 6259905307f4c71912bb0941 |
class Dynamic(object): <NEW_LINE> <INDENT> ForwardPriority = 1 <NEW_LINE> ReversedPriority = -1 <NEW_LINE> def __init__(self, priority): <NEW_LINE> <INDENT> self._priority = Dynamic.ForwardPriority <NEW_LINE> if priority == Dynamic.ReversedPriority: <NEW_LINE> <INDENT> self._priority = Dynamic.ReversedPriority <NEW_LINE> <DEDENT> <DEDENT> def priority(self): <NEW_LINE> <INDENT> return self._priority | Dynamic class keeps information that is necessary for applying dynamic
algorithms and ranking. One of the attributes is _priority that is
priority order and indicates whether first element in a sequence has
more priority (forward) or less priority (reversed) comparing to the
last element in naturally sorted sequence, e.g. 1 -> 2 -> 5.
Example:
1 -> 2 -> 3 -> 5 -> 7 -- ForwardPriority as 1 < 7
1 <- 2 <- 3 <- 5 <- 7 -- ReversedPriority as 1 > 7 | 62599053be8e80087fbc0588 |
class NumDiff(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.h = 1.0e-6 <NEW_LINE> self.points = (2.0 * self.h, self.h, -self.h, -2.0 * self.h) <NEW_LINE> self.coeffs = numpy.array((-1.0, 8.0, -8.0, 1.0), dtype=DTYPE) <NEW_LINE> self.divizor = 12.0 * self.h <NEW_LINE> self.errs = numpy.zeros_like(self.points, dtype=DTYPE) <NEW_LINE> <DEDENT> @property <NEW_LINE> def derivative(self): <NEW_LINE> <INDENT> return (self.errs * self.coeffs).sum() / self.divizor <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def sse(y, t): <NEW_LINE> <INDENT> return numpy.square(y - t).sum() * 0.5 <NEW_LINE> <DEDENT> def check_diff(self, x, y, target, dx, forward, f_err=None): <NEW_LINE> <INDENT> if f_err is None: <NEW_LINE> <INDENT> f_err = NumDiff.sse <NEW_LINE> <DEDENT> assert len(x.shape) == len(dx.shape) <NEW_LINE> assert y.shape == target.shape <NEW_LINE> max_diff = 0.0 <NEW_LINE> for i, vle in numpy.ndenumerate(x): <NEW_LINE> <INDENT> for j, d in enumerate(self.points): <NEW_LINE> <INDENT> x[i] = vle + d <NEW_LINE> forward() <NEW_LINE> self.errs[j] = f_err(y, target) <NEW_LINE> <DEDENT> x[i] = vle <NEW_LINE> if abs(dx[i]) > 1.0e-10: <NEW_LINE> <INDENT> max_diff = max(max_diff, abs(1.0 - self.derivative / dx[i])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logging.debug("err_x close to zero for index %d", i) <NEW_LINE> <DEDENT> <DEDENT> logging.debug( "max_diff is %.6f %s", max_diff, "FAIL, should be less than 0.5" if max_diff >= 0.5 else "OK") | Numeric differentiation helper.
WARNING: it is invalid for single precision float data type. | 62599053379a373c97d9a52b |
class FileDB: <NEW_LINE> <INDENT> def __init__(self, filename): <NEW_LINE> <INDENT> from ZODB import FileStorage, DB <NEW_LINE> self.storage = FileStorage.FileStorage(filename) <NEW_LINE> db = DB(self.storage) <NEW_LINE> connection = db.open() <NEW_LINE> self.root = connection.root() <NEW_LINE> <DEDENT> def commit(self): <NEW_LINE> <INDENT> import transaction <NEW_LINE> transaction.commit() <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.commit() <NEW_LINE> self.storage.close() <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> return self.root[key] <NEW_LINE> <DEDENT> def __setitem__(self, key, val): <NEW_LINE> <INDENT> self.root[key] = val <NEW_LINE> <DEDENT> def __getattr__(self, attr): <NEW_LINE> <INDENT> return getattr(self.root, attr) | automate zodb connect and close protocols | 62599053ac7a0e7691f739e8 |
class NavListProcess(mfgames_writing.ncx.ReportNcxFileProcess): <NEW_LINE> <INDENT> def get_help(self): <NEW_LINE> <INDENT> return "Lists the nav entries of a NCX." <NEW_LINE> <DEDENT> def report_tsv(self): <NEW_LINE> <INDENT> index = 1 <NEW_LINE> for nav in self.ncx.navpoints: <NEW_LINE> <INDENT> fields = [format(index), nav[0], nav[1], nav[2]] <NEW_LINE> print('\t'.join(fields)) <NEW_LINE> index += 1 | Scans the NCX file and lists the nav entries. | 6259905316aa5153ce4019ec |
class AudioHarmonicity(object): <NEW_LINE> <INDENT> def __init__(self, sampling_freq, frame_length, overlap): <NEW_LINE> <INDENT> self._aff = fundamental_frequency.FundamentalFrequency(sampling_freq, frame_length, overlap) <NEW_LINE> self._window = window.Hamming(frame_length) <NEW_LINE> self._dft_length = 2048 <NEW_LINE> <DEDENT> def Process(self, frame): <NEW_LINE> <INDENT> arg_min = self._aff.Process(frame) - self._aff.min_lag <NEW_LINE> actual_index = min(numpy.floor(arg_min), len(self._aff.xcorr) - 2) <NEW_LINE> left = self._aff.xcorr[actual_index] <NEW_LINE> right = self._aff.xcorr[actual_index + 1] <NEW_LINE> ah = fundamental_frequency.LinearInterpolation(left, right, arg_min - actual_index) <NEW_LINE> signal_spectrum = PowerSpectrum(frame, self._window.window_data, self._dft_length) <NEW_LINE> power_spectrum = PowerSpectrum(self._aff.combed_signal, self._window.window_data, self._dft_length) <NEW_LINE> ulh = self._GetUpperFrequency(self._GetUpperLimit(signal_spectrum, power_spectrum)) <NEW_LINE> return (numpy.abs(ah), ulh) <NEW_LINE> <DEDENT> def _GetUpperLimit(self, signal_spectrum, power_spectrum): <NEW_LINE> <INDENT> for lolimit in range(len(signal_spectrum) - 1, 0, -1): <NEW_LINE> <INDENT> SignalPower = 0.0 <NEW_LINE> CombedSignalPower = 0.0 <NEW_LINE> for i in range(len(signal_spectrum) - 1, lolimit, -1): <NEW_LINE> <INDENT> SignalPower += signal_spectrum[i] <NEW_LINE> CombedSignalPower += power_spectrum[i] <NEW_LINE> <DEDENT> if SignalPower > 0.0: <NEW_LINE> <INDENT> if CombedSignalPower / SignalPower < 0.5: <NEW_LINE> <INDENT> return lolimit <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return 0.0 <NEW_LINE> <DEDENT> def _GetUpperFrequency(self, bin): <NEW_LINE> <INDENT> octaves = [31.25, 62.5, 125, 250, 500, 1000, 2000, 4000, 8000, 16000] <NEW_LINE> freq = bin * (self._aff.sampling_freq / self._dft_length) <NEW_LINE> if freq < octaves[0]: <NEW_LINE> <INDENT> return octaves[0] <NEW_LINE> <DEDENT> elif freq > octaves[9]: <NEW_LINE> <INDENT> return octaves[9] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> i = 1 <NEW_LINE> while freq > octaves[i]: <NEW_LINE> <INDENT> i += 1 <NEW_LINE> <DEDENT> if freq < (octaves[i] + octaves[i-1]) / 2: <NEW_LINE> <INDENT> return octaves[i-1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return octaves[i] | Harmonicity algorithm test implementation | 62599053fff4ab517ebced2a |
class SiteThemeDbIO(BaseDbIO): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.model_name = SiteTheme | Database I/O operations are handled using this class | 625990532ae34c7f260ac5ee |
class Button(Clickeable, Dibujable): <NEW_LINE> <INDENT> def __init__(self, posicion_x, posicion_y, nombre_archivo, ancho=None, alto=None, dibujado=False): <NEW_LINE> <INDENT> super().__init__(posicion_x, posicion_y, nombre_archivo) <NEW_LINE> <DEDENT> def _al_clickear(self): <NEW_LINE> <INDENT> if len(self.sprite.images) > 1: <NEW_LINE> <INDENT> self.cambiar_imagen(ESTADOS_BOTONES.PRESIONADO) <NEW_LINE> <DEDENT> <DEDENT> def _al_dibujar(self): <NEW_LINE> <INDENT> self._set_parametros() <NEW_LINE> if self.inactivo: <NEW_LINE> <INDENT> self.cambiar_imagen(ESTADOS_BOTONES.INACTIVO) <NEW_LINE> <DEDENT> <DEDENT> def _al_liberar_click(self): <NEW_LINE> <INDENT> self.cambiar_imagen(ESTADOS_BOTONES.ACTIVO) <NEW_LINE> <DEDENT> def _set_parametros(self): <NEW_LINE> <INDENT> self.rect = self.sprite.rect <NEW_LINE> self.xFinal = self.rect[RECT.POS_X] + self.rect[RECT.ANCHO] <NEW_LINE> self.yFinal = self.rect[RECT.POS_Y] + self.rect[RECT.ALTO] <NEW_LINE> <DEDENT> def _al_mover(self): <NEW_LINE> <INDENT> self._set_parametros() <NEW_LINE> <DEDENT> def _al_desactivar(self): <NEW_LINE> <INDENT> self.cambiar_imagen(ESTADOS_BOTONES.INACTIVO) <NEW_LINE> <DEDENT> def _al_activar(self): <NEW_LINE> <INDENT> self.cambiar_imagen(ESTADOS_BOTONES.ACTIVO) | Clase para generar los botones necesarios dentro de la interfaz gráfica | 6259905316aa5153ce4019ed |
class TimeElapsedColumn(rich.progress.ProgressColumn): <NEW_LINE> <INDENT> def render(self, task: "Task") -> Text: <NEW_LINE> <INDENT> elapsed = task.finished_time if task.finished else task.elapsed <NEW_LINE> if elapsed is None: <NEW_LINE> <INDENT> return Text("-:--:--", style="progress.elapsed") <NEW_LINE> <DEDENT> from datetime import timedelta <NEW_LINE> delta = timedelta(seconds=(elapsed)) <NEW_LINE> time = str(delta)[:-4] <NEW_LINE> if time.startswith('0:00:'): <NEW_LINE> <INDENT> time = time[5:] <NEW_LINE> <DEDENT> time = time + 's' <NEW_LINE> passes = task.fields.get('passes') <NEW_LINE> if passes is not None: <NEW_LINE> <INDENT> time += f'[{passes}]' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> time += ' ' <NEW_LINE> <DEDENT> return Text(time, style="progress.elapsed") | Renders time elapsed. | 62599053baa26c4b54d507ab |
class MEA(object): <NEW_LINE> <INDENT> def __init__(self, channels=None, positions=None, adjacency=None, probe=None, ): <NEW_LINE> <INDENT> self._probe = probe <NEW_LINE> self._channels = channels <NEW_LINE> self._check_positions(positions) <NEW_LINE> self._positions = positions <NEW_LINE> if adjacency is None and probe is not None: <NEW_LINE> <INDENT> adjacency = _probe_adjacency_list(probe) <NEW_LINE> self.channels_per_group = _channels_per_group(probe) <NEW_LINE> <DEDENT> self._adjacency = adjacency <NEW_LINE> if probe: <NEW_LINE> <INDENT> cg = sorted(self._probe['channel_groups'].keys())[0] <NEW_LINE> self.change_channel_group(cg) <NEW_LINE> <DEDENT> <DEDENT> def _check_positions(self, positions): <NEW_LINE> <INDENT> if positions is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> positions = _as_array(positions) <NEW_LINE> if positions.shape[0] != self.n_channels: <NEW_LINE> <INDENT> raise ValueError("'positions' " "(shape {0:s})".format(str(positions.shape)) + " and 'n_channels' " "({0:d})".format(self.n_channels) + " do not match.") <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def positions(self): <NEW_LINE> <INDENT> return self._positions <NEW_LINE> <DEDENT> @property <NEW_LINE> def channels(self): <NEW_LINE> <INDENT> return self._channels <NEW_LINE> <DEDENT> @property <NEW_LINE> def n_channels(self): <NEW_LINE> <INDENT> return len(self._channels) if self._channels is not None else 0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def adjacency(self): <NEW_LINE> <INDENT> return self._adjacency <NEW_LINE> <DEDENT> def change_channel_group(self, group): <NEW_LINE> <INDENT> assert self._probe is not None <NEW_LINE> self._channels = _probe_channels(self._probe, group) <NEW_LINE> self._positions = _probe_positions(self._probe, group) | A Multi-Electrode Array.
There are two modes:
* No probe specified: one single channel group, positions and adjacency
list specified directly.
* Probe specified: one can change the current channel_group. | 6259905394891a1f408ba17a |
class Like(Choreography): <NEW_LINE> <INDENT> def __init__(self, temboo_session): <NEW_LINE> <INDENT> Choreography.__init__(self, temboo_session, '/Library/Foursquare/Checkins/Like') <NEW_LINE> <DEDENT> def new_input_set(self): <NEW_LINE> <INDENT> return LikeInputSet() <NEW_LINE> <DEDENT> def _make_result_set(self, result, path): <NEW_LINE> <INDENT> return LikeResultSet(result, path) <NEW_LINE> <DEDENT> def _make_execution(self, session, exec_id, path): <NEW_LINE> <INDENT> return LikeChoreographyExecution(session, exec_id, path) | Create a new instance of the Like Choreography. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied. | 625990537d847024c075d8e3 |
class GetSmsCampaigns(object): <NEW_LINE> <INDENT> swagger_types = { 'campaigns': 'list[object]', 'count': 'int' } <NEW_LINE> attribute_map = { 'campaigns': 'campaigns', 'count': 'count' } <NEW_LINE> def __init__(self, campaigns=None, count=None): <NEW_LINE> <INDENT> self._campaigns = None <NEW_LINE> self._count = None <NEW_LINE> self.discriminator = None <NEW_LINE> if campaigns is not None: <NEW_LINE> <INDENT> self.campaigns = campaigns <NEW_LINE> <DEDENT> if count is not None: <NEW_LINE> <INDENT> self.count = count <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def campaigns(self): <NEW_LINE> <INDENT> return self._campaigns <NEW_LINE> <DEDENT> @campaigns.setter <NEW_LINE> def campaigns(self, campaigns): <NEW_LINE> <INDENT> self._campaigns = campaigns <NEW_LINE> <DEDENT> @property <NEW_LINE> def count(self): <NEW_LINE> <INDENT> return self._count <NEW_LINE> <DEDENT> @count.setter <NEW_LINE> def count(self, count): <NEW_LINE> <INDENT> self._count = count <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(GetSmsCampaigns, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = 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, GetSmsCampaigns): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 625990533cc13d1c6d466c46 |
class ExtraFieldSerializerOptions(serializers.ModelSerializerOptions): <NEW_LINE> <INDENT> def __init__(self, meta): <NEW_LINE> <INDENT> super(ExtraFieldSerializerOptions, self).__init__(meta) <NEW_LINE> self.non_native_fields = getattr(meta, 'non_native_fields', ()) | Meta class options for ExtraFieldSerializerOptions | 62599053a17c0f6771d5d625 |
class JST(datetime.tzinfo): <NEW_LINE> <INDENT> def utcoffset(self,dt): <NEW_LINE> <INDENT> return datetime.timedelta(hours=9) <NEW_LINE> <DEDENT> def dst(self,dt): <NEW_LINE> <INDENT> return datetime.timedelta(0) <NEW_LINE> <DEDENT> def tzname(self,dt): <NEW_LINE> <INDENT> return "JST" | UTCを日本標準時にするクラス
| 6259905330dc7b76659a0d03 |
@method_decorator(csrf_exempt, name="dispatch") <NEW_LINE> class QueryView(View): <NEW_LINE> <INDENT> def get_model(self, model_name: str) -> BaseModel: <NEW_LINE> <INDENT> app_lable__model_name = model_name_map.get(model_name) <NEW_LINE> if not app_lable__model_name: <NEW_LINE> <INDENT> raise APIError(10008) <NEW_LINE> <DEDENT> model = apps.get_model(app_lable__model_name) <NEW_LINE> return model <NEW_LINE> <DEDENT> def get(self, r, *args, **kwargs): <NEW_LINE> <INDENT> model_name = kwargs.get('model_name') <NEW_LINE> model = self.get_model(model_name) <NEW_LINE> _id = kwargs.get('id') <NEW_LINE> if _id: <NEW_LINE> <INDENT> data = model.objects.active().get_or_api_404(id=_id).to_dict() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> query = parse_query_string(r.GET, model_name) <NEW_LINE> data = model.objects .active(query.search, **query.filters) .defer(*query.defer) .order_by(*query.order_by) .pagination(**query.pagination) <NEW_LINE> <DEDENT> return APIResponse(data) <NEW_LINE> <DEDENT> @method_decorator(token_required, name="dispatch") <NEW_LINE> def post(self, r, *args, **kwargs): <NEW_LINE> <INDENT> model_name = kwargs.get('model_name') <NEW_LINE> model = self.get_model(model_name) <NEW_LINE> data = json.loads(r.body) <NEW_LINE> _id = kwargs.get('id') <NEW_LINE> if _id: <NEW_LINE> <INDENT> obj = model.objects.get_or_api_404(id=_id).update_fields(**data) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> obj = model.create(**data, auth=r.user) <NEW_LINE> <DEDENT> return APIResponse(obj.to_dict()) <NEW_LINE> <DEDENT> @method_decorator(token_required, name="dispatch") <NEW_LINE> def delete(self, r, *args, **kwargs): <NEW_LINE> <INDENT> model_name = kwargs.get('model_name') <NEW_LINE> model = self.get_model(model_name) <NEW_LINE> _id = kwargs.get('id') <NEW_LINE> if _id: <NEW_LINE> <INDENT> obj = model.objects.active().get_or_api_404(id=_id).delete() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise APIError(10009) <NEW_LINE> <DEDENT> return APIResponse() | 通用Restful API接口 | 6259905363b5f9789fe8667a |
class Terminal(ABC): <NEW_LINE> <INDENT> def __init__(self, size: Size = None): <NEW_LINE> <INDENT> self.bg_color = color.BLACK <NEW_LINE> self.fg_color = color.WHITE <NEW_LINE> size = (80, 24) if size is None else size <NEW_LINE> self.size = Rect(0, 0, *size) <NEW_LINE> <DEDENT> def color(self, fg: Color, bg: Color): <NEW_LINE> <INDENT> self.fg_color, self.bg_color = fg, bg <NEW_LINE> return self <NEW_LINE> <DEDENT> def read(self): <NEW_LINE> <INDENT> return self.get_key() <NEW_LINE> <DEDENT> def write(self, text: Union[Text, CharCode, List[CharCode]], at: Point, fg_color: Color = None, bg_color: Color = None): <NEW_LINE> <INDENT> if isinstance(text, CharCode): <NEW_LINE> <INDENT> text = [text] <NEW_LINE> <DEDENT> if (at not in self.size or at[0] + len(text) - 1 >= self.size.top_right.x): <NEW_LINE> <INDENT> raise ValueError('writing out of bound') <NEW_LINE> <DEDENT> fg_color = self.fg_color if fg_color is None else fg_color <NEW_LINE> bg_color = self.bg_color if bg_color is None else bg_color <NEW_LINE> for pos, char in enumerate(text): <NEW_LINE> <INDENT> self.draw_glyph( Glyph(char, fg_color, bg_color), Point(at[0] + pos, at[1])) <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def fill(self, bg: Color, window: Rect): <NEW_LINE> <INDENT> if window not in self.size: <NEW_LINE> <INDENT> raise ValueError('window out of bounds') <NEW_LINE> <DEDENT> _glyph = Glyph(CharCode.SPACE, None, bg) <NEW_LINE> for _y in range(window[1], window[3]): <NEW_LINE> <INDENT> for _x in range(window[0], window[2]): <NEW_LINE> <INDENT> self.draw_glyph(_glyph, Point(_x, _y)) <NEW_LINE> <DEDENT> <DEDENT> return self <NEW_LINE> <DEDENT> def clear(self, window: Rect = None): <NEW_LINE> <INDENT> window = self.size if window is None else window <NEW_LINE> if window not in self.size: <NEW_LINE> <INDENT> raise ValueError('window out of bounds') <NEW_LINE> <DEDENT> self.fill(self.bg_color, window) <NEW_LINE> return self <NEW_LINE> <DEDENT> def view(self, window: Rect): <NEW_LINE> <INDENT> return Subterminal(self, window) <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def get_key(self) -> Key: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def draw_glyph(self, glyph_: Glyph, at: Point): <NEW_LINE> <INDENT> pass | Terminal base class, represent a virtual terminal window.
Only requires the implementation of the `draw_glyph` method.
properties:
size -- the rectangle that defines the size of the terminal,
mainly its width and height.
terminal instances always have x and y set to 0
and defaults to a size of 80x24.
fg_color -- default foreground color.
bg_color -- default background color. | 62599053b830903b9686ef02 |
class User: <NEW_LINE> <INDENT> def __init__(self, username: str, password: str, role: str, realname: str = None): <NEW_LINE> <INDENT> self.username = username <NEW_LINE> self.password = password <NEW_LINE> self.roles = [role] <NEW_LINE> self.realname = realname <NEW_LINE> self.id = username <NEW_LINE> self.classes = [] <NEW_LINE> self.question_banks = [] <NEW_LINE> <DEDENT> def is_role(self, role: str) -> bool: <NEW_LINE> <INDENT> return role in self.roles | Defines the properties of a User within the system. | 62599053e5267d203ee6cdf8 |
class Cube(object): <NEW_LINE> <INDENT> def __init__(self, v_min: list, edge_length: float): <NEW_LINE> <INDENT> self.v_min = v_min <NEW_LINE> self.edge_length = edge_length <NEW_LINE> self.centre = [j + 0.5 * edge_length for j in v_min] <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Cube from {0} with edge length {1}".format(self.v_min, self.edge_length) | Bounding box | 62599053cb5e8a47e493cc0c |
class AgentPayDealsRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.OwnerUin = None <NEW_LINE> self.AgentPay = None <NEW_LINE> self.DealNames = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.OwnerUin = params.get("OwnerUin") <NEW_LINE> self.AgentPay = params.get("AgentPay") <NEW_LINE> self.DealNames = params.get("DealNames") | AgentPayDeals请求参数结构体
| 625990533539df3088ecd7b0 |
class MmapedValue(object): <NEW_LINE> <INDENT> _multiprocess = True <NEW_LINE> def __init__(self, typ, metric_name, name, labelnames, labelvalues, multiprocess_mode='', **kwargs): <NEW_LINE> <INDENT> self._params = typ, metric_name, name, labelnames, labelvalues, multiprocess_mode <NEW_LINE> with lock: <NEW_LINE> <INDENT> self.__check_for_pid_change() <NEW_LINE> self.__reset() <NEW_LINE> values.append(self) <NEW_LINE> <DEDENT> <DEDENT> def __reset(self): <NEW_LINE> <INDENT> typ, metric_name, name, labelnames, labelvalues, multiprocess_mode = self._params <NEW_LINE> if typ == 'gauge': <NEW_LINE> <INDENT> file_prefix = typ + '_' + multiprocess_mode <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> file_prefix = typ <NEW_LINE> <DEDENT> if file_prefix not in files: <NEW_LINE> <INDENT> filename = os.path.join( os.environ['prometheus_multiproc_dir'], '{0}_{1}.db'.format(file_prefix, pid['value'])) <NEW_LINE> files[file_prefix] = MmapedDict(filename) <NEW_LINE> <DEDENT> self._file = files[file_prefix] <NEW_LINE> self._key = mmap_key(metric_name, name, labelnames, labelvalues) <NEW_LINE> self._value = self._file.read_value(self._key) <NEW_LINE> <DEDENT> def __check_for_pid_change(self): <NEW_LINE> <INDENT> actual_pid = _pidFunc() <NEW_LINE> if pid['value'] != actual_pid: <NEW_LINE> <INDENT> pid['value'] = actual_pid <NEW_LINE> for f in files.values(): <NEW_LINE> <INDENT> f.close() <NEW_LINE> <DEDENT> files.clear() <NEW_LINE> for value in values: <NEW_LINE> <INDENT> value.__reset() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def inc(self, amount): <NEW_LINE> <INDENT> with lock: <NEW_LINE> <INDENT> self.__check_for_pid_change() <NEW_LINE> self._value += amount <NEW_LINE> self._file.write_value(self._key, self._value) <NEW_LINE> <DEDENT> <DEDENT> def set(self, value): <NEW_LINE> <INDENT> with lock: <NEW_LINE> <INDENT> self.__check_for_pid_change() <NEW_LINE> self._value = value <NEW_LINE> self._file.write_value(self._key, self._value) <NEW_LINE> <DEDENT> <DEDENT> def get(self): <NEW_LINE> <INDENT> with lock: <NEW_LINE> <INDENT> self.__check_for_pid_change() <NEW_LINE> return self._value | A float protected by a mutex backed by a per-process mmaped file. | 62599053a17c0f6771d5d626 |
class GetHeaders: <NEW_LINE> <INDENT> def get_header_value(self, name: str) -> Optional[str]: <NEW_LINE> <INDENT> for header in self.raw_entry["headers"]: <NEW_LINE> <INDENT> if header["name"].lower() == name.lower(): <NEW_LINE> <INDENT> return header["value"] <NEW_LINE> <DEDENT> <DEDENT> return None | Mixin to get a header | 62599053462c4b4f79dbcf0f |
class Category(namedtuple('Category', [ 'ID', 'dbname', 'items' ])): <NEW_LINE> <INDENT> def name(self): <NEW_LINE> <INDENT> return self.dbname.upper() | Item Category
Items are organized into categories (Food, Drugs, Metals, etc).
Category object describes a category's ID, name and list of items.
Attributes:
ID
The database ID
dbname
The name as present in the database.
items
List of Item objects within this category.
Member Functions:
name()
Returns the display name for this Category. | 6259905345492302aabfd9e2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.