code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class DistributedReadWriteLock(readWriteLock.ReadWriteLock): <NEW_LINE> <INDENT> def __init__(self, distributed_lock): <NEW_LINE> <INDENT> readWriteLock.ReadWriteLock.__init__(self) <NEW_LINE> self.distributed_lock = distributed_lock <NEW_LINE> self.global_lock = threading.Lock() <NEW_LINE> <DEDENT> def write_acquire(self): <NEW_LINE> <INDENT> self.global_lock.acquire() <NEW_LINE> self.distributed_lock.acquire() <NEW_LINE> self.write_acquire_local() <NEW_LINE> <DEDENT> def write_release(self): <NEW_LINE> <INDENT> self.global_lock.release() <NEW_LINE> self.distributed_lock.release() <NEW_LINE> self.write_release_local() <NEW_LINE> <DEDENT> def write_acquire_local(self): <NEW_LINE> <INDENT> readWriteLock.ReadWriteLock.write_acquire(self) <NEW_LINE> <DEDENT> def write_release_local(self): <NEW_LINE> <INDENT> readWriteLock.ReadWriteLock.write_release(self)
Distributed version of ReadWriteLock.
625990517d847024c075d894
class ProductListView(generics.ListAPIView): <NEW_LINE> <INDENT> renderer_classes = (CMSPageRenderer, JSONRenderer, BrowsableAPIRenderer) <NEW_LINE> product_model = ProductModel <NEW_LINE> serializer_class = app_settings.PRODUCT_SUMMARY_SERIALIZER <NEW_LINE> limit_choices_to = models.Q() <NEW_LINE> filter_class = None <NEW_LINE> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> response = self.list(request, *args, **kwargs) <NEW_LINE> add_never_cache_headers(response) <NEW_LINE> return response <NEW_LINE> <DEDENT> def get_queryset(self): <NEW_LINE> <INDENT> qs = self.product_model.objects.filter(self.limit_choices_to) <NEW_LINE> if hasattr(self.product_model, 'translations'): <NEW_LINE> <INDENT> language = get_language_from_request(self.request) <NEW_LINE> qs = qs.prefetch_related('translations').filter(translations__language_code=language) <NEW_LINE> <DEDENT> qs = qs.select_related('polymorphic_ctype') <NEW_LINE> return qs <NEW_LINE> <DEDENT> def get_template_names(self): <NEW_LINE> <INDENT> return [self.request.current_page.get_template()]
This view is used to list all products which shall be visible below a certain URL. Usage: Add it to the urlpatterns responsible for rendering the catalog's views. The file containing this patterns can be referenced by the CMS apphook used by the CMS pages responsible for rendering the catalog's list view. ``` urlpatterns = [ url(r'^$', ProductListView.as_view()), url(r'^(?P<slug>[\w-]+)/?$', ProductRetrieveView.as_view()), # see below ... ] ``` You may add these attributes to the ``as_view()`` method: :param renderer_classes: A list or tuple of REST renderer classes. :param product_model: The product model onto which the filter set is applied. :param serializer_class: The serializer class used to process the queryset returned by the catalog's product list view. :param limit_choices_to: Limit the queryset of product models to these choices. :param filter_class: A filter set which must be inherit from :class:`django_filters.FilterSet`.
62599051d99f1b3c44d06b5a
class InputRequest(metaclass=ABCMeta): <NEW_LINE> <INDENT> def __init__(self, source, requester_source=None): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._source = source <NEW_LINE> self._requester_source = requester_source <NEW_LINE> self.thread = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def source(self): <NEW_LINE> <INDENT> return self._source <NEW_LINE> <DEDENT> @property <NEW_LINE> def requester_source(self): <NEW_LINE> <INDENT> return self._requester_source <NEW_LINE> <DEDENT> def emit_input_ready_signal(self, input_data): <NEW_LINE> <INDENT> handler_source = self.source <NEW_LINE> signal_source = self._get_request_source() <NEW_LINE> new_signal = InputReadySignal(source=signal_source, input_handler_source=handler_source, data=input_data, success=True) <NEW_LINE> App.get_event_loop().enqueue_signal(new_signal) <NEW_LINE> <DEDENT> def emit_failed_input_ready_signal(self): <NEW_LINE> <INDENT> handler_source = self.source <NEW_LINE> signal_source = self._get_request_source() <NEW_LINE> new_signal = InputReadySignal(source=signal_source, input_handler_source=handler_source, data="", success=False) <NEW_LINE> App.get_event_loop().enqueue_signal(new_signal) <NEW_LINE> <DEDENT> def _get_request_source(self): <NEW_LINE> <INDENT> return self.requester_source or self.source <NEW_LINE> <DEDENT> def initialize_thread(self): <NEW_LINE> <INDENT> self.thread = threading.Thread(name=INPUT_THREAD_NAME, target=self.run) <NEW_LINE> self.thread.daemon = True <NEW_LINE> <DEDENT> def start_thread(self): <NEW_LINE> <INDENT> self.thread.start() <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> data = self.get_input() <NEW_LINE> App.get_event_loop().enqueue_signal(InputReceivedSignal(self, data)) <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def text_prompt(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def get_input(self): <NEW_LINE> <INDENT> return ""
Base input request class. This should be overloaded for every InputHandler class. Purpose of this class is to print prompt and get input from user. The `run_input` method is the entry point for this class. Output from this method must be a user input. The `text_prompt` method is used to get textual representation of a prompt. This will be used on concurrent input to replace existing prompt to get new input. WARNING: The `run_input` method will run in a separate thread!
6259905129b78933be26ab22
class Oden(Linter): <NEW_LINE> <INDENT> syntax = ('oden') <NEW_LINE> cmd = ('oden', 'lint') <NEW_LINE> version_args = '--version' <NEW_LINE> version_re = r'(?P<version>\d+\.\d+\.\d+)' <NEW_LINE> version_requirement = '>= 0.3.0' <NEW_LINE> regex = r'[^:]*:(?P<line>\d+):(?P<col>\d+):\s*(?P<error>error:)?\s+(?P<message>.*)' <NEW_LINE> tempfile_suffix = 'oden' <NEW_LINE> error_stream = util.STREAM_BOTH
Provides an interface to oden.
62599051462c4b4f79dbcebf
class FRAM: <NEW_LINE> <INDENT> def __init__(self, max_size, write_protect=False, wp_pin=None): <NEW_LINE> <INDENT> self._max_size = max_size <NEW_LINE> self._wp = write_protect <NEW_LINE> self._wraparound = False <NEW_LINE> if not wp_pin is None: <NEW_LINE> <INDENT> self._wp_pin = wp_pin <NEW_LINE> self._wp_pin.switch_to_output() <NEW_LINE> self._wp_pin.value = self._wp <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._wp_pin = wp_pin <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def write_wraparound(self): <NEW_LINE> <INDENT> return self._wraparound <NEW_LINE> <DEDENT> @write_wraparound.setter <NEW_LINE> def write_wraparound(self, value): <NEW_LINE> <INDENT> if not value in (True, False): <NEW_LINE> <INDENT> raise ValueError("Write wraparound must be 'True' or 'False'.") <NEW_LINE> <DEDENT> self._wraparound = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def write_protected(self): <NEW_LINE> <INDENT> return self._wp if self._wp_pin is None else self._wp_pin.value <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self._max_size <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> if isinstance(key, int): <NEW_LINE> <INDENT> if key > self._max_size: <NEW_LINE> <INDENT> raise ValueError("Register '{0}' greater than maximum FRAM size." " ({1})".format(key, self._max_size)) <NEW_LINE> <DEDENT> buffer = bytearray(1) <NEW_LINE> read_buffer = self._read_register(key, buffer) <NEW_LINE> <DEDENT> elif isinstance(key, slice): <NEW_LINE> <INDENT> if key.step is not None: <NEW_LINE> <INDENT> raise ValueError("Slice stepping is not currently available.") <NEW_LINE> <DEDENT> registers = list(range(key.start if key.start is not None else 0, key.stop if key.stop is not None else self._max_size)) <NEW_LINE> if (registers[0] + len(registers)) > self._max_size: <NEW_LINE> <INDENT> raise ValueError("Register + Length greater than maximum FRAM size." " ({0})".format(self._max_size)) <NEW_LINE> <DEDENT> buffer = bytearray(len(registers)) <NEW_LINE> read_buffer = self._read_register(registers[0], buffer) <NEW_LINE> <DEDENT> return read_buffer <NEW_LINE> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> if self.write_protected: <NEW_LINE> <INDENT> raise RuntimeError("FRAM currently write protected.") <NEW_LINE> <DEDENT> if isinstance(key, int): <NEW_LINE> <INDENT> if not isinstance(value, (int, bytearray, list, tuple)): <NEW_LINE> <INDENT> raise ValueError("Data must be a single integer, or a bytearray," " list, or tuple.") <NEW_LINE> <DEDENT> if key > self._max_size: <NEW_LINE> <INDENT> raise ValueError("Requested register '{0}' greater than maximum" " FRAM size. ({1})".format(key, self._max_size)) <NEW_LINE> <DEDENT> self._write(key, value, self._wraparound) <NEW_LINE> <DEDENT> elif isinstance(key, slice): <NEW_LINE> <INDENT> raise ValueError("Slicing not available during write operations.") <NEW_LINE> <DEDENT> <DEDENT> def _read_register(self, register, read_buffer): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def _write(self, start_register, data, wraparound): <NEW_LINE> <INDENT> raise NotImplementedError
Driver base for the FRAM Breakout.
6259905123849d37ff85257e
class Color(object): <NEW_LINE> <INDENT> def __init__(self, *args): <NEW_LINE> <INDENT> self.__alpha = colorAttribute(255) <NEW_LINE> self.__red = colorAttribute(255) <NEW_LINE> self.__green = colorAttribute(255) <NEW_LINE> self.__blue = colorAttribute(255) <NEW_LINE> self.__setup(*args) <NEW_LINE> logging.debug('Color created') <NEW_LINE> <DEDENT> def __setup(self, *args): <NEW_LINE> <INDENT> if len(args) == 1: <NEW_LINE> <INDENT> if type(args[0]) is str: <NEW_LINE> <INDENT> if len(args[0]) != 8: <NEW_LINE> <INDENT> raise ValueError('Color value must be 8 bytes in length, aabbggrr. See help(Color).') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.color = args[0] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> elif len(args) == 4: <NEW_LINE> <INDENT> self.alpha = args[0] <NEW_LINE> self.blue = args[1] <NEW_LINE> self.green = args[2] <NEW_LINE> self.red = args[3] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise RuntimeError('Invalid number of arguments for Color. See help(Color) for usage.') <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def color(selfself): <NEW_LINE> <INDENT> return self.__str__() <NEW_LINE> <DEDENT> @color.setter <NEW_LINE> def color(self, value): <NEW_LINE> <INDENT> self.__alpha = colorAttribute(value[:2]) <NEW_LINE> self.__blue = colorAttribute(value[2:4]) <NEW_LINE> self.__green = colorAttribute(value[4:6]) <NEW_LINE> self.__red = colorAttribute(value[6:8]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def alpha(self): <NEW_LINE> <INDENT> return self.__alpha <NEW_LINE> <DEDENT> @alpha.setter <NEW_LINE> def alpha(self, value): <NEW_LINE> <INDENT> self.__alpha = colorAttribute(value) <NEW_LINE> <DEDENT> @property <NEW_LINE> def red(self): <NEW_LINE> <INDENT> return self.__red <NEW_LINE> <DEDENT> @red.setter <NEW_LINE> def red(self, value): <NEW_LINE> <INDENT> self.__red = colorAttribute(value) <NEW_LINE> <DEDENT> @property <NEW_LINE> def green(self): <NEW_LINE> <INDENT> return self.__green <NEW_LINE> <DEDENT> @green.setter <NEW_LINE> def green(self, value): <NEW_LINE> <INDENT> self.__green = colorAttribute(value) <NEW_LINE> <DEDENT> @property <NEW_LINE> def blue(self): <NEW_LINE> <INDENT> return self.__blue <NEW_LINE> <DEDENT> @blue.setter <NEW_LINE> def blue(self, value): <NEW_LINE> <INDENT> self.__blue = colorAttribute(value) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.__alpha) + str(self.__blue) + str(self.__green) + str(self.__red)
Represents a color as a complete attribute with alpha, red, green and blue. Color attribute can be expressed as an 8 byte value in the format of aabbggrr: aa = Alpha bb = Blue gg = Green rr = Red Syntax: x = Color('FF0000FF') # gives RED x = Color(255, 0, 0, 255') # gives RED x = Color('FF', '00', '00', 'FF') # gives RED Color can also be expressed as four integer or hex values, in the order of a, b, g, r: All attributes can be modified using decimal values or hex strings. x.red = 255 x.green = 'A0' x.alpha = '80' Errors: RuntimeError : Incorrect number of arguments ValueError : Incorrect length of string color argument
6259905191af0d3eaad3b2e4
@attr.s(auto_attribs=True, init=False) <NEW_LINE> class CredentialsGoogle(model.Model): <NEW_LINE> <INDENT> can: Optional[MutableMapping[str, bool]] = None <NEW_LINE> created_at: Optional[str] = None <NEW_LINE> domain: Optional[str] = None <NEW_LINE> email: Optional[str] = None <NEW_LINE> google_user_id: Optional[str] = None <NEW_LINE> is_disabled: Optional[bool] = None <NEW_LINE> logged_in_at: Optional[str] = None <NEW_LINE> type: Optional[str] = None <NEW_LINE> url: Optional[str] = None <NEW_LINE> def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, created_at: Optional[str] = None, domain: Optional[str] = None, email: Optional[str] = None, google_user_id: Optional[str] = None, is_disabled: Optional[bool] = None, logged_in_at: Optional[str] = None, type: Optional[str] = None, url: Optional[str] = None ): <NEW_LINE> <INDENT> self.can = can <NEW_LINE> self.created_at = created_at <NEW_LINE> self.domain = domain <NEW_LINE> self.email = email <NEW_LINE> self.google_user_id = google_user_id <NEW_LINE> self.is_disabled = is_disabled <NEW_LINE> self.logged_in_at = logged_in_at <NEW_LINE> self.type = type <NEW_LINE> self.url = url
Attributes: can: Operations the current user is able to perform on this object created_at: Timestamp for the creation of this credential domain: Google domain email: EMail address google_user_id: Google's Unique ID for this user is_disabled: Has this credential been disabled? logged_in_at: Timestamp for most recent login using credential type: Short name for the type of this kind of credential url: Link to get this item
62599051e5267d203ee6cdaa
class ToolPaletteManager ( ActionManager ): <NEW_LINE> <INDENT> image_size = Tuple( ( 16, 16 ) ) <NEW_LINE> show_tool_names = Bool( True ) <NEW_LINE> _image_cache = Instance( ImageCache ) <NEW_LINE> def __init__ ( self, *args, **facets ): <NEW_LINE> <INDENT> super( ToolPaletteManager, self ).__init__( *args, **facets ) <NEW_LINE> self._image_cache = ImageCache( self.image_size[0], self.image_size[1] ) <NEW_LINE> <DEDENT> def create_tool_palette ( self, parent, controller = None ): <NEW_LINE> <INDENT> tool_palette = ToolPalette( parent ) <NEW_LINE> self._add_tools( tool_palette, self.groups ) <NEW_LINE> self._set_initial_tool_state( tool_palette, self.groups ) <NEW_LINE> return tool_palette <NEW_LINE> <DEDENT> def _add_tools ( self, tool_palette, groups ): <NEW_LINE> <INDENT> previous_non_empty_group = None <NEW_LINE> for group in self.groups: <NEW_LINE> <INDENT> if len( group.items ) > 0: <NEW_LINE> <INDENT> for item in group.items: <NEW_LINE> <INDENT> control_id = item.add_to_palette( tool_palette, self._image_cache, self.show_tool_names ) <NEW_LINE> item.control_id = control_id <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> tool_palette.realize() <NEW_LINE> <DEDENT> def _set_initial_tool_state ( self, tool_palette, groups ): <NEW_LINE> <INDENT> for group in groups: <NEW_LINE> <INDENT> checked = False <NEW_LINE> for item in group.items: <NEW_LINE> <INDENT> if item.action.style == 'radio': <NEW_LINE> <INDENT> tool_palette.toggle_tool( item.control_id, item.action.checked ) <NEW_LINE> checked = checked or item.action.checked <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if not checked and len( group.items ) > 0: <NEW_LINE> <INDENT> group.items[ 0 ].action.checked = True
A tool bar manager realizes itself in a tool palette bar control.
6259905182261d6c52730927
class Friend(models.Model): <NEW_LINE> <INDENT> to_user = models.ForeignKey(AUTH_USER_MODEL, related_name='friends') <NEW_LINE> from_user = models.ForeignKey(AUTH_USER_MODEL, related_name='_unused_friend_relation') <NEW_LINE> created = models.DateTimeField(default=datetime.datetime.now()) <NEW_LINE> notify = models.IntegerField(blank= True, null = True) <NEW_LINE> objects = FriendshipManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = _('Friend') <NEW_LINE> verbose_name_plural = _('Friends') <NEW_LINE> unique_together = ('from_user', 'to_user') <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return "User #%d is friends with #%d" % (self.to_user_id, self.from_user_id) <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if self.to_user == self.from_user: <NEW_LINE> <INDENT> raise ValidationError("Users cannot be friends with themselves.") <NEW_LINE> <DEDENT> super(Friend, self).save(*args, **kwargs)
Model to represent Friendships
6259905163b5f9789fe8662e
class PathOverflow(Exception): <NEW_LINE> <INDENT> pass
Raised when trying to add or move a node to a position where no more nodes can be added (see :attr:`~treebeard.MP_Node.path` and :attr:`~treebeard.MP_Node.alphabet` for more info)
62599051cb5e8a47e493cbe6
class MusicaMP3(object): <NEW_LINE> <INDENT> def __init__(self, nome='', autor='', ano=0, estrelas=0): <NEW_LINE> <INDENT> self.nome = nome <NEW_LINE> self.autor = autor <NEW_LINE> self.ano = ano <NEW_LINE> self.estrelas = estrelas
Música MP3
6259905130c21e258be99cc6
class LinkOutBamStepPart(BaseStepPart): <NEW_LINE> <INDENT> name = "link_out_bam" <NEW_LINE> def __init__(self, parent): <NEW_LINE> <INDENT> super().__init__(parent) <NEW_LINE> self.base_path_in = ( "work/{wildcards.mapper}.{wildcards.library_name}/out/" "{wildcards.mapper}.{wildcards.library_name}{{postproc}}{{ext}}" ) <NEW_LINE> self.base_pattern_out = ( "output/{{mapper}}.{{library_name}}/out/{{mapper}}.{{library_name}}{ext}" ) <NEW_LINE> self.base_path_out = self.base_pattern_out.replace(",[^.]", "") <NEW_LINE> self.extensions = EXT_VALUES <NEW_LINE> <DEDENT> def get_input_files(self, action): <NEW_LINE> <INDENT> def input_function(wildcards): <NEW_LINE> <INDENT> return expand( self.base_path_in.format(wildcards=wildcards), postproc=[self._get_postproc_token()], ext=self.extensions, ) <NEW_LINE> <DEDENT> assert action == "run", "Unsupported action" <NEW_LINE> return input_function <NEW_LINE> <DEDENT> def get_output_files(self, action): <NEW_LINE> <INDENT> assert action == "run", "Unsupported action" <NEW_LINE> return expand(self.base_pattern_out, ext=self.extensions) <NEW_LINE> <DEDENT> def get_shell_cmd(self, action, wildcards): <NEW_LINE> <INDENT> assert action == "run", "Unsupported action" <NEW_LINE> ins = expand( self.base_path_in.format(wildcards=wildcards), postproc=[self._get_postproc_token()], ext=self.extensions, ) <NEW_LINE> outs = [s.format(**wildcards) for s in expand(self.base_path_out, ext=self.extensions)] <NEW_LINE> assert len(ins) == len(outs) <NEW_LINE> return "\n".join( ( "test -L {out} || ln -sr {in_} {out}".format(in_=in_, out=out) for in_, out in zip(ins, outs) ) ) <NEW_LINE> <DEDENT> def _get_postproc_token(self): <NEW_LINE> <INDENT> if self.config["postprocessing"] == "gatk_post_bam": <NEW_LINE> <INDENT> do_realignment = self.config["gatk_post_bam"]["do_realignment"] <NEW_LINE> do_recalibration = self.config["gatk_post_bam"]["do_recalibration"] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> do_realignment, do_recalibration = False, False <NEW_LINE> <DEDENT> realigned_infix = self.config["gatk_post_bam"]["realigned_infix"] <NEW_LINE> recalibrated_infix = self.config["gatk_post_bam"]["recalibrated_infix"] <NEW_LINE> return { (False, False): "", (False, True): "." + recalibrated_infix, (True, False): "." + realigned_infix, (True, True): "." + realigned_infix + "." + recalibrated_infix, }[(do_realignment, do_recalibration)]
Link out the read mapping results Depending on the configuration, the files are linked out after postprocessing
625990513c8af77a43b6899e
class TestSalesEndpoints(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.app = create_app(config_name="testing") <NEW_LINE> self.client = self.app.test_client <NEW_LINE> self.product_item = {"name": "Table", "description": "The product description here", "quantity": 12, "category": "Furniture", "unit price": 2000} <NEW_LINE> self.sale_record = {"sale_attendant": "Kay Jay", "product_name": "Table", "quantity": 2 } <NEW_LINE> self.login_user = {"email": "[email protected]", "password": "asdfg", } <NEW_LINE> <DEDENT> def login(self): <NEW_LINE> <INDENT> response = self.client().post(LOGIN_URL, data=json.dumps(self.login_user), content_type='application/json') <NEW_LINE> access_token = json.loads(response.data.decode())["access_token"] <NEW_LINE> return access_token <NEW_LINE> <DEDENT> def test_post_single_sale_record(self): <NEW_LINE> <INDENT> post_product = self.client().post(PROD_BASE_URL, data=json.dumps(self.product_item), headers=dict(Authorization="Bearer "+self.login()), content_type='application/json') <NEW_LINE> response = self.client().post(BASE_URL, data=json.dumps(self.sale_record), headers=dict(Authorization="Bearer "+self.login()), content_type="application/json") <NEW_LINE> self.assertEqual(response.status_code, 201) <NEW_LINE> <DEDENT> def test_get_single_sale_record(self): <NEW_LINE> <INDENT> post_product = self.client().post(PROD_BASE_URL, data=json.dumps(self.product_item), headers=dict(Authorization="Bearer "+self.login()), content_type='application/json') <NEW_LINE> response = self.client().post(BASE_URL, data=json.dumps(self.sale_record), headers=dict(Authorization="Bearer "+self.login()), content_type="application/json") <NEW_LINE> data = json.loads(response.get_data()) <NEW_LINE> print(data) <NEW_LINE> single_sale_record = self.client().get(SINGLE_SALE_URL.format(data['sale record']['sale_id']), headers=dict(Authorization="Bearer "+self.login()), content_type="application/json") <NEW_LINE> self.assertEqual(single_sale_record.status_code, 200) <NEW_LINE> <DEDENT> def test_get_all_sale_records_method(self): <NEW_LINE> <INDENT> get_all_sale_records = self.client().get(BASE_URL, headers=dict(Authorization="Bearer "+self.login()), content_type="application/json") <NEW_LINE> self.assertEqual(get_all_sale_records.status_code, 200) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> SaleRecordModel.product_list = []
class to test the sales endpoints
62599051e76e3b2f99fd9eba
class Profile(models.Model): <NEW_LINE> <INDENT> user = models.OneToOneField(User, verbose_name=_("User"), on_delete=models.CASCADE) <NEW_LINE> picture = models.ImageField(_("Picture"), upload_to=upload_location, default="avatar.jpeg", height_field=None, width_field=None, max_length=None, blank=True, null=True ) <NEW_LINE> location = models.CharField(_("Location"), max_length=100, null=True, blank=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = 'Profile' <NEW_LINE> verbose_name_plural = 'Profiles' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.user.username <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse("profiles:profile", kwargs={"username": self.user.username}) <NEW_LINE> <DEDENT> def like_link(self): <NEW_LINE> <INDENT> return reverse("likes:like_user", kwargs={"id": self.user.id})
Model definition for Profile.
62599051b830903b9686eedb
class Node(object): <NEW_LINE> <INDENT> def __init__(self, value=None, depth=None): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> self.depth = depth
Base node to be inherited.
625990514e4d5625663738cb
class Rent(): <NEW_LINE> <INDENT> def __init__(self, idc, idf): <NEW_LINE> <INDENT> self.__idc = idc <NEW_LINE> self.__idf = idf <NEW_LINE> self.__isRented = True <NEW_LINE> <DEDENT> def getIDC(self): <NEW_LINE> <INDENT> return self.__idc <NEW_LINE> <DEDENT> def getIDF(self): <NEW_LINE> <INDENT> return self.__idf <NEW_LINE> <DEDENT> def getIsRented(self): <NEW_LINE> <INDENT> return self.__isRented <NEW_LINE> <DEDENT> def setIDC(self, idc): <NEW_LINE> <INDENT> self.__idc = idc <NEW_LINE> <DEDENT> def setIDF(self, idf): <NEW_LINE> <INDENT> self.__idf = idf <NEW_LINE> <DEDENT> def setIsRented(self): <NEW_LINE> <INDENT> self.__isRented = True <NEW_LINE> <DEDENT> def setIsNotRented(self): <NEW_LINE> <INDENT> self.__isRented = False
Store a rent A rent consists of a client id and a film id The film with the ID is rented to the client with the ID
62599051d486a94d0ba2d485
class upgrade_result(object): <NEW_LINE> <INDENT> def __init__(self, success=None, err=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> self.err = err <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.success = iprot.readBinary() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.err = InvalidPackageId() <NEW_LINE> self.err.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('upgrade_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.STRING, 0) <NEW_LINE> oprot.writeBinary(self.success) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.err is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('err', TType.STRUCT, 1) <NEW_LINE> self.err.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - success - err
62599051379a373c97d9a4e7
class GameStats: <NEW_LINE> <INDENT> def __init__(self, sets): <NEW_LINE> <INDENT> self.sets = sets <NEW_LINE> self.reset_stats() <NEW_LINE> self.game_active = True <NEW_LINE> <DEDENT> def reset_stats(self): <NEW_LINE> <INDENT> self.bird_left = self.sets.bird_limit
跟踪游戏统计信息
6259905116aa5153ce4019af
class TrackerEvent(object): <NEW_LINE> <INDENT> def __init__(self, frame, frames_per_second, supply=None, clock_position=None): <NEW_LINE> <INDENT> self.frame = frame <NEW_LINE> self.supply = supply <NEW_LINE> self.clock_position = clock_position <NEW_LINE> self.frames_per_second = frames_per_second <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> if self.supply: <NEW_LINE> <INDENT> return '{} {} Event'.format(self.supply, self.frame) <NEW_LINE> <DEDENT> return '{} Event'.format(self.frame)
not necesarily a trackerevent, but event was too generic
625990518e7ae83300eea554
class TestItem(): <NEW_LINE> <INDENT> def __init__(self, test_function): <NEW_LINE> <INDENT> self._test_data = self.parse_data(test_function) <NEW_LINE> self.done = False <NEW_LINE> <DEDENT> def finish(self, test_report): <NEW_LINE> <INDENT> self._test_data["duration"] = test_report.duration <NEW_LINE> self._test_data["outcome"] = test_report.outcome <NEW_LINE> self.done = True <NEW_LINE> <DEDENT> def set_return(self, data): <NEW_LINE> <INDENT> if isinstance(data, tuple): <NEW_LINE> <INDENT> self._test_data["result"] = str(data[0]) <NEW_LINE> self._test_data["criteria"] = str(data[1]) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def parse_data(test): <NEW_LINE> <INDENT> data = inspect.getdoc(test.function) <NEW_LINE> crt_item = Report.default_item <NEW_LINE> found_data = { key: Report.doc_items[key].value for key in Report.doc_items} <NEW_LINE> found_data["name"] = test.nodeid <NEW_LINE> if not data: <NEW_LINE> <INDENT> raise ValueError( f"{found_data['name']}: Test requires docstring." ) <NEW_LINE> <DEDENT> docstring_items = {} <NEW_LINE> for item in re.split(Report.visible_items, data.strip()): <NEW_LINE> <INDENT> if item[1:-1] in Report.doc_items: <NEW_LINE> <INDENT> crt_item = item[1:-1] <NEW_LINE> continue <NEW_LINE> <DEDENT> item_value = item.strip() <NEW_LINE> crt_doc_item = Report.doc_items[crt_item] <NEW_LINE> if not crt_doc_item.from_docstring: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if crt_doc_item.one_of and item_value not in crt_doc_item.one_of: <NEW_LINE> <INDENT> raise ValueError( f"{crt_item} must be one of " f"{crt_doc_item.one_of}, not {item_value}") <NEW_LINE> <DEDENT> if crt_item in docstring_items.keys(): <NEW_LINE> <INDENT> raise ValueError(f"Item {crt_item} specified twice.") <NEW_LINE> <DEDENT> docstring_items[crt_item] = item_value <NEW_LINE> <DEDENT> for name, item in Report.doc_items.items(): <NEW_LINE> <INDENT> if not item.from_docstring or not item.required: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if name not in docstring_items: <NEW_LINE> <INDENT> raise ValueError( f"{found_data['name']}: Test {name} is required." ) <NEW_LINE> <DEDENT> if docstring_items[name] == "": <NEW_LINE> <INDENT> raise ValueError( f"{found_data['name']}: Test {name} is empty." ) <NEW_LINE> <DEDENT> <DEDENT> return {**found_data, **docstring_items} <NEW_LINE> <DEDENT> def to_json(self): <NEW_LINE> <INDENT> return self._test_data
Holds data about one test item.
625990517b25080760ed873e
class ObjectsToLayer(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "blayers.objects_to_layer" <NEW_LINE> bl_label = "Objects To Layer" <NEW_LINE> layer_index = bpy.props.IntProperty() <NEW_LINE> @classmethod <NEW_LINE> def poll(self,context) : <NEW_LINE> <INDENT> layers_from,BLayers,BLayersSettings,layers,objects,selected = source_layers() <NEW_LINE> return True if selected and len(BLayers) else False <NEW_LINE> <DEDENT> def draw(self,context) : <NEW_LINE> <INDENT> scene = context.scene <NEW_LINE> layout = self.layout <NEW_LINE> layers_from,BLayers,BLayersSettings,layers,objects,selected = source_layers() <NEW_LINE> col = layout.column(align=True) <NEW_LINE> for l in [l for l in BLayers if l.type == 'LAYER'] : <NEW_LINE> <INDENT> col.prop(l,'move',toggle = True,text = l.name) <NEW_LINE> <DEDENT> <DEDENT> def execute(self, context): <NEW_LINE> <INDENT> scene = context.scene <NEW_LINE> layers_from,BLayers,BLayersSettings,layers,objects,selected = source_layers() <NEW_LINE> if not self.dst_layers : <NEW_LINE> <INDENT> self.dst_layers = [l.index for l in BLayers if l.move] <NEW_LINE> <DEDENT> print(selected) <NEW_LINE> for ob in selected : <NEW_LINE> <INDENT> for i in self.dst_layers : <NEW_LINE> <INDENT> ob.layers[i]=True <NEW_LINE> <DEDENT> if not self.shift : <NEW_LINE> <INDENT> for i in self.src_layers : <NEW_LINE> <INDENT> if i not in self.dst_layers : <NEW_LINE> <INDENT> ob.layers[i]=False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return {'FINISHED'} <NEW_LINE> <DEDENT> def invoke(self, context, event): <NEW_LINE> <INDENT> scene = context.scene <NEW_LINE> layers_from,BLayers,BLayersSettings,layers,objects,selected = source_layers() <NEW_LINE> index = BLayersSettings.active_index <NEW_LINE> self.shift = event.shift <NEW_LINE> self.src_layers = [] <NEW_LINE> for ob in selected : <NEW_LINE> <INDENT> for i,l in enumerate(ob.layers) : <NEW_LINE> <INDENT> if l and i not in self.src_layers : <NEW_LINE> <INDENT> self.src_layers.append(i) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if index in range(len(BLayers)): <NEW_LINE> <INDENT> BLayers[index].move = True <NEW_LINE> for l in BLayers : <NEW_LINE> <INDENT> if l.index in self.src_layers : <NEW_LINE> <INDENT> l.move = True <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> l.move = False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if event.type == 'M' : <NEW_LINE> <INDENT> self.dst_layers = [] <NEW_LINE> wm = context.window_manager <NEW_LINE> return wm.invoke_props_dialog(self,width=175) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> self.dst_layers = [self.layer_index] <NEW_LINE> return self.execute(context)
Move objects to layers
6259905107d97122c4218166
class SearchForm(forms.Form): <NEW_LINE> <INDENT> search_item = forms.CharField(label="Search", max_length=256)
Define the search form
6259905124f1403a9268632e
class DijkstraTowardsVisitor(DijkstraVisitor): <NEW_LINE> <INDENT> def __init__(self, t :int): <NEW_LINE> <INDENT> self.t = t <NEW_LINE> <DEDENT> def examine_vertex(self, u :int, g :DirectedGraph): <NEW_LINE> <INDENT> if u == self.t: <NEW_LINE> <INDENT> raise DijkstraStopException(self.t)
`DijkstraTowardsVisitor` can be passed to `dijkstra_shortest_paths` to abort computation once the cost of the shortest path to `t` is known. Important notes: - stopping when discovering t does not guarantee that we have find the shortest path. - stopping when discovering a vertex u farther than t from s always occur after finishing vertex t. As a sequel, we must wait that t is examined to guarantee that a a shortest path to t has been explored.
625990518e71fb1e983bcf87
class Flaggable(models.Model): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> <DEDENT> flags = generic.GenericRelation('Flag') <NEW_LINE> def flag(self, user, reason=''): <NEW_LINE> <INDENT> if not user.is_authenticated(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> flag_model = get_model('flag') <NEW_LINE> flag = None <NEW_LINE> if not self.is_flagged_by(user): <NEW_LINE> <INDENT> flag = flag_model(content_object=self, user=user, reason=reason) <NEW_LINE> flag.save() <NEW_LINE> <DEDENT> return flag <NEW_LINE> <DEDENT> def is_flagged_by(self, user): <NEW_LINE> <INDENT> if not user.is_authenticated(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> flags = self.flags.filter(user=user) <NEW_LINE> return (not (flags.count() == 0))
Interface for any model that can be flagged as objectionable or inappropriate by a user of the system. Generally used for user created content.
62599051004d5f362081fa4a
class SignalEvent(Event): <NEW_LINE> <INDENT> def __init__(self, inst, datetime, signal_type): <NEW_LINE> <INDENT> self.type = 'SIGNAL' <NEW_LINE> self.inst = inst <NEW_LINE> self.datetime = datetime <NEW_LINE> self.signal_type = signal_type
Handles the event of sending a Signal from a Strategy object. This is received by a Portfolio object and acted upon.
6259905171ff763f4b5e8c6b
class Experiment051(object): <NEW_LINE> <INDENT> def __init__(p): <NEW_LINE> <INDENT> p.name = 'e051' <NEW_LINE> p.num_images = None <NEW_LINE> p.train_pct = 80 <NEW_LINE> p.valid_pct = 15 <NEW_LINE> p.test_pct = 5 <NEW_LINE> p.num_submission_images = None <NEW_LINE> p.batch_size = 237 <NEW_LINE> p.epochs = 10000 <NEW_LINE> p.final_epochs = 40 <NEW_LINE> p.image_shape = (64, 64) <NEW_LINE> p.rng_seed = 13579 <NEW_LINE> p.learning_rule = nn.Momentum <NEW_LINE> p.learning_rate = .4 <NEW_LINE> p.min_learning_rate = 0.0003 <NEW_LINE> p.patience = 10 <NEW_LINE> p.improvement_threshold = 0.995 <NEW_LINE> p.momentum = 0.5 <NEW_LINE> p.max_momentum = 0.90 <NEW_LINE> p.activation = nn.PReLULayer <NEW_LINE> p.l1_reg = 0.000 <NEW_LINE> p.l2_reg = 0.000 <NEW_LINE> p.dropout_conv = 0.3 <NEW_LINE> p.dropout_hidd = 0.5 <NEW_LINE> p.resizer = pp.StretchResizer <NEW_LINE> p.preprocessor = pp.Rotator360 <NEW_LINE> <DEDENT> def build_net(p, n): <NEW_LINE> <INDENT> n.add_convolution(32, (5, 5), (2, 2)) <NEW_LINE> n.add_dropout(p.dropout_conv) <NEW_LINE> n.add_convolution(64, (5, 5), (2, 2)) <NEW_LINE> n.add_dropout(p.dropout_conv) <NEW_LINE> n.add_convolution(128, (5, 5), (2, 2)) <NEW_LINE> n.merge_data_channel('shapes') <NEW_LINE> n.add_dropout(p.dropout_conv) <NEW_LINE> n.add_hidden(1024) <NEW_LINE> n.merge_data_channel('shapes') <NEW_LINE> n.add_dropout(p.dropout_hidd) <NEW_LINE> n.add_hidden(1024) <NEW_LINE> n.merge_data_channel('shapes') <NEW_LINE> n.add_dropout(p.dropout_hidd) <NEW_LINE> n.add_logistic()
comments: same as e037 except: (1) batch normalization (2) prelu (recommended not to use with l1/l2 reg but last experiment did) (3) higher learning rate (4) shape input comes before dropout (5) lower patience (given that rotations are regularizing even when training is not improving this might be a bad idea) (6) bigger batch sizes results: Seems to have done very poorly. I think the annealing rate may have been too aggressive. And this version of batch normalization had bug on change of learning rate that might have prevented it improved validation scores for a while after learning rate change. Not sure I can draw any conclusions from this experiment except to note that it's another example of prelu not doing particularly well, but being very well regularized. 091 | 27.7%, 0.902754 | 30.8%, 0.967690 * | 28.4%, 0.925873 | momentum=0.752, frustration=9,
625990514e696a045264e881
class LRRMessage(BaseMessage): <NEW_LINE> <INDENT> event_data_type = None <NEW_LINE> event_data = None <NEW_LINE> partition = -1 <NEW_LINE> event_type = None <NEW_LINE> version = 0 <NEW_LINE> report_code = 0xFF <NEW_LINE> event_prefix = '' <NEW_LINE> event_source = LRR_EVENT_TYPE.UNKNOWN <NEW_LINE> event_status = 0 <NEW_LINE> event_code = 0 <NEW_LINE> event_description = '' <NEW_LINE> def __init__(self, data=None, skip_report_override=False): <NEW_LINE> <INDENT> BaseMessage.__init__(self, data) <NEW_LINE> self.skip_report_override = skip_report_override <NEW_LINE> if data is not None: <NEW_LINE> <INDENT> self._parse_message(data) <NEW_LINE> <DEDENT> <DEDENT> def _parse_message(self, data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _, values = data.split(':') <NEW_LINE> values = values.split(',') <NEW_LINE> if len(values) <= 3: <NEW_LINE> <INDENT> self.event_data, self.partition, self.event_type = values <NEW_LINE> self.version = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.event_data, self.partition, self.event_type, self.report_code = values <NEW_LINE> self.version = 2 <NEW_LINE> event_type_data = self.event_type.split('_') <NEW_LINE> self.event_prefix = event_type_data[0] <NEW_LINE> self.event_source = get_event_source(self.event_prefix) <NEW_LINE> self.event_status = int(event_type_data[1][0]) <NEW_LINE> self.event_code = int(event_type_data[1][1:], 16) <NEW_LINE> if not self.skip_report_override and self.report_code not in ['00', 'ff']: <NEW_LINE> <INDENT> self.event_code = int(event_type_data[1][1] + self.report_code, 16) <NEW_LINE> <DEDENT> self.event_description = get_event_description(self.event_source, self.event_code) <NEW_LINE> self.event_data_type = get_event_data_type(self.event_source, self.event_code) <NEW_LINE> <DEDENT> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise InvalidMessageError('Received invalid message: {0}'.format(data)) <NEW_LINE> <DEDENT> <DEDENT> def dict(self, **kwargs): <NEW_LINE> <INDENT> return dict( time = self.timestamp, event_data = self.event_data, event_data_type = self.event_data_type, event_type = self.event_type, partition = self.partition, report_code = self.report_code, event_prefix = self.event_prefix, event_source = self.event_source, event_status = self.event_status, event_code = hex(self.event_code), event_description = self.event_description, **kwargs )
Represent a message from a Long Range Radio or emulated Long Range Radio.
625990514428ac0f6e6599f6
class Package(object): <NEW_LINE> <INDENT> name = '' <NEW_LINE> max_length = 0 <NEW_LINE> max_breadth = 0 <NEW_LINE> max_height = 0 <NEW_LINE> max_weight = 0 <NEW_LINE> cost = 0 <NEW_LINE> def __init__(self, name, length, breadth, height, weight, cost): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.max_length = length <NEW_LINE> self.max_breadth = breadth <NEW_LINE> self.max_height = height <NEW_LINE> self.max_weight = weight <NEW_LINE> self.cost = cost
Represents the requirements of a shipping package
62599051b830903b9686eedc
class RAWreader(object): <NEW_LINE> <INDENT> def __init__(self, path, extension): <NEW_LINE> <INDENT> self.path = path <NEW_LINE> self.extension = extension <NEW_LINE> self.list_files = [f for f in listdir(path) if isfile(join(path, f))] <NEW_LINE> <DEDENT> def check_width(self, image): <NEW_LINE> <INDENT> ini_len = len(image[0]) <NEW_LINE> for row in image: <NEW_LINE> <INDENT> if len(row) != ini_len: <NEW_LINE> <INDENT> print(len(row)) <NEW_LINE> print(ini_len) <NEW_LINE> return False <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> def check_path_str(self, path): <NEW_LINE> <INDENT> if path[-1] != "/": <NEW_LINE> <INDENT> path = path + "/" <NEW_LINE> <DEDENT> return path <NEW_LINE> <DEDENT> def get_array_of_images(self): <NEW_LINE> <INDENT> arr_images = [] <NEW_LINE> for item_name in self.list_files: <NEW_LINE> <INDENT> if item_name.endswith(self.extension): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> with open(self.check_path_str( self.path) + item_name, 'r', errors='ignore') as f: <NEW_LINE> <INDENT> file = f.read() <NEW_LINE> file = file.split("\n") <NEW_LINE> arr = [] <NEW_LINE> for line in file: <NEW_LINE> <INDENT> if len(line) > 0: <NEW_LINE> <INDENT> x = line.strip(" ").strip("\n").split(" ") <NEW_LINE> x = [int(i) for i in x] <NEW_LINE> arr.append(x) <NEW_LINE> <DEDENT> <DEDENT> if arr[-1] == ['']: <NEW_LINE> <INDENT> arr = arr[:-1] <NEW_LINE> <DEDENT> if self.check_width(arr): <NEW_LINE> <INDENT> m_arr = np.array(arr) <NEW_LINE> arr_images.append(m_arr) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Pixels lost in conversion') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> output = np.stack(arr_images) <NEW_LINE> return output
Read raw files from dataset. Example ------- >>> array_converted = RAWreader( >>> "databases/caltech/Faces_easy",".raw.rescale") >>> imgs = array_converted.get_array_of_images()
62599051a79ad1619776b51d
class TypeAxis(SimpleAxis): <NEW_LINE> <INDENT> def get_keys(self, obj): <NEW_LINE> <INDENT> return type(obj).mro()
An axis which matches the class and super classes of an object in method resolution order.
62599051d486a94d0ba2d487
class NoLocationError(Error): <NEW_LINE> <INDENT> def __init__(self, message=None, address=None): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.__message = message <NEW_LINE> self.__address = address <NEW_LINE> <DEDENT> @property <NEW_LINE> def message(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.__message <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def address(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.__address <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return None
Returned when requesting market update without a postcode
625990510fa83653e46f63a2
class QListPrinter: <NEW_LINE> <INDENT> class Iter: <NEW_LINE> <INDENT> def __init__(self, array, begin, end, typ): <NEW_LINE> <INDENT> self.array = array <NEW_LINE> self.end = end <NEW_LINE> self.begin = begin <NEW_LINE> self.offset = 0 <NEW_LINE> if typ.name == 'QStringList': <NEW_LINE> <INDENT> self.el_type = gdb.lookup_type('QString') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.el_type = typ.template_argument(0) <NEW_LINE> <DEDENT> if ((self.el_type.sizeof > gdb.lookup_type('void').pointer().sizeof) or typeinfo.type_is_known_static(self.el_type)): <NEW_LINE> <INDENT> self.is_pointer = True <NEW_LINE> <DEDENT> elif (typeinfo.type_is_known_movable(self.el_type) or typeinfo.type_is_known_primitive(self.el_type)): <NEW_LINE> <INDENT> self.is_pointer = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Could not determine whether QList stores " + self.el_type.name + " directly or as a pointer: to fix " + "this, add it to one of the variables in the "+ "qt5printers.typeinfo module") <NEW_LINE> <DEDENT> self.node_type = gdb.lookup_type(typ.name + '::Node').pointer() <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __next__(self): <NEW_LINE> <INDENT> if self.begin + self.offset >= self.end: <NEW_LINE> <INDENT> raise StopIteration <NEW_LINE> <DEDENT> node = self.array[self.begin + self.offset].reinterpret_cast(self.node_type) <NEW_LINE> if self.is_pointer: <NEW_LINE> <INDENT> p = node['v'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p = node <NEW_LINE> <DEDENT> self.offset += 1 <NEW_LINE> value = p.address.cast(self.el_type.pointer()).dereference() <NEW_LINE> return (str(self.offset), value) <NEW_LINE> <DEDENT> def next(self): <NEW_LINE> <INDENT> return self.__next__() <NEW_LINE> <DEDENT> <DEDENT> def __init__(self, val): <NEW_LINE> <INDENT> self.val = val <NEW_LINE> <DEDENT> def children(self): <NEW_LINE> <INDENT> d = self.val['d'] <NEW_LINE> begin = int(d['begin']) <NEW_LINE> end = int(d['end']) <NEW_LINE> if begin == end: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> return self.Iter(d['array'], begin, end, self.val.type.strip_typedefs()) <NEW_LINE> <DEDENT> def to_string(self): <NEW_LINE> <INDENT> if self.val['d']['begin'] == self.val['d']['end']: <NEW_LINE> <INDENT> return '<empty>' <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def display_hint(self): <NEW_LINE> <INDENT> return 'array'
Print a Qt5 QList
6259905194891a1f408ba156
class HostPortCreateRequest(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.swagger_types = { 'type': 'str', 'port': 'str', 'label': 'str', 'iscsi_chap_secret': 'str' } <NEW_LINE> self.attribute_map = { 'type': 'type', 'port': 'port', 'label': 'label', 'iscsi_chap_secret': 'iscsiChapSecret' } <NEW_LINE> self._type = None <NEW_LINE> self._port = None <NEW_LINE> self._label = None <NEW_LINE> self._iscsi_chap_secret = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def type(self): <NEW_LINE> <INDENT> return self._type <NEW_LINE> <DEDENT> @type.setter <NEW_LINE> def type(self, type): <NEW_LINE> <INDENT> allowed_values = ["notImplemented", "scsi", "fc", "sata", "sas", "iscsi", "ib", "fcoe", "nvmeof", "__UNDEFINED"] <NEW_LINE> if type not in allowed_values: <NEW_LINE> <INDENT> raise ValueError( "Invalid value for `type`, must be one of {0}" .format(allowed_values) ) <NEW_LINE> <DEDENT> self._type = type <NEW_LINE> <DEDENT> @property <NEW_LINE> def port(self): <NEW_LINE> <INDENT> return self._port <NEW_LINE> <DEDENT> @port.setter <NEW_LINE> def port(self, port): <NEW_LINE> <INDENT> self._port = port <NEW_LINE> <DEDENT> @property <NEW_LINE> def label(self): <NEW_LINE> <INDENT> return self._label <NEW_LINE> <DEDENT> @label.setter <NEW_LINE> def label(self, label): <NEW_LINE> <INDENT> self._label = label <NEW_LINE> <DEDENT> @property <NEW_LINE> def iscsi_chap_secret(self): <NEW_LINE> <INDENT> return self._iscsi_chap_secret <NEW_LINE> <DEDENT> @iscsi_chap_secret.setter <NEW_LINE> def iscsi_chap_secret(self, iscsi_chap_secret): <NEW_LINE> <INDENT> self._iscsi_chap_secret = iscsi_chap_secret <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if self is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if self is None or other is None: <NEW_LINE> <INDENT> return None <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.
62599051fff4ab517ebcece1
class SpawnDeleteFilesJob(CommandMessage): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(SpawnDeleteFilesJob, self).__init__('spawn_delete_files_job') <NEW_LINE> self.job_id = None <NEW_LINE> self.trigger_id = None <NEW_LINE> self.source_file_id = None <NEW_LINE> self.purge = False <NEW_LINE> <DEDENT> def to_json(self): <NEW_LINE> <INDENT> return {'job_id': self.job_id, 'trigger_id': self.trigger_id, 'source_file_id': self.source_file_id, 'purge': str(self.purge) } <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_json(json_dict): <NEW_LINE> <INDENT> message = SpawnDeleteFilesJob() <NEW_LINE> message.job_id = json_dict['job_id'] <NEW_LINE> message.trigger_id = json_dict['trigger_id'] <NEW_LINE> message.source_file_id = json_dict['source_file_id'] <NEW_LINE> message.purge = bool(json_dict['purge']) <NEW_LINE> return message <NEW_LINE> <DEDENT> def execute(self): <NEW_LINE> <INDENT> results = PurgeResults.objects.get(trigger_event=self.trigger_id) <NEW_LINE> if results.force_stop_purge: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> files_to_delete = ScaleFile.objects.filter_files(job_ids=[self.job_id]) <NEW_LINE> if files_to_delete: <NEW_LINE> <INDENT> files = [] <NEW_LINE> workspaces = [] <NEW_LINE> for f in files_to_delete: <NEW_LINE> <INDENT> files.append({'id': f.id, 'file_path': f.file_path, 'workspace': f.workspace.name}) <NEW_LINE> if f.workspace.name not in [k for wrkspc in workspaces for k in wrkspc.keys()]: <NEW_LINE> <INDENT> workspaces.append({f.workspace.name: f.workspace.json_config}) <NEW_LINE> <DEDENT> <DEDENT> inputs = Data() <NEW_LINE> inputs.add_value(JsonValue('job_id', str(self.job_id))) <NEW_LINE> inputs.add_value(JsonValue('trigger_id', str(self.trigger_id))) <NEW_LINE> inputs.add_value(JsonValue('source_file_id', str(self.source_file_id))) <NEW_LINE> inputs.add_value(JsonValue('purge', str(self.purge))) <NEW_LINE> inputs.add_value(JsonValue('files', json.dumps(files))) <NEW_LINE> inputs.add_value(JsonValue('workspaces', json.dumps(workspaces))) <NEW_LINE> msg = create_jobs_message(job_type_name="scale-delete-files", job_type_version="1.0.0", event_id=self.trigger_id, job_type_rev_num=1, input_data=inputs) <NEW_LINE> self.new_messages.append(msg) <NEW_LINE> <DEDENT> return True
Command message that spawns a delete files system job
625990518e7ae83300eea556
class AddressForm(forms.ModelForm): <NEW_LINE> <INDENT> u <NEW_LINE> zip_code = BRZipCodeField( label=_(u'Zip Code'), help_text=_(u'Enter a zip code in the format XXXXX-XXX.'), max_length=9, required=True ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Address <NEW_LINE> exclude = ['created', 'modified']
Class of model form Adress
6259905123e79379d538d9ba
@args_kwargs <NEW_LINE> @Stream.register_api() <NEW_LINE> class combine_latest(Stream): <NEW_LINE> <INDENT> _graphviz_orientation = 270 <NEW_LINE> _graphviz_shape = "triangle" <NEW_LINE> def __init__(self, *upstreams, **kwargs): <NEW_LINE> <INDENT> emit_on = kwargs.pop("emit_on", None) <NEW_LINE> first = kwargs.pop("first", None) <NEW_LINE> self.last = [None for _ in upstreams] <NEW_LINE> self.missing = set(upstreams) <NEW_LINE> if emit_on is not None: <NEW_LINE> <INDENT> if not isinstance(emit_on, Iterable): <NEW_LINE> <INDENT> emit_on = (emit_on,) <NEW_LINE> <DEDENT> emit_on = tuple( upstreams[x] if isinstance(x, int) else x for x in emit_on ) <NEW_LINE> self.emit_on = emit_on <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.emit_on = upstreams <NEW_LINE> <DEDENT> Stream.__init__(self, upstreams=upstreams, **kwargs) <NEW_LINE> self._graphviz_edge_types = { u: {"style": "solid"} for u in self.upstreams } <NEW_LINE> self._graphviz_edge_types.update( {u: {"style": "dashed"} for u in self.emit_on} ) <NEW_LINE> if first: <NEW_LINE> <INDENT> move_to_first(self, first) <NEW_LINE> <DEDENT> <DEDENT> def update(self, x, who=None): <NEW_LINE> <INDENT> if self.missing and who in self.missing: <NEW_LINE> <INDENT> self.missing.remove(who) <NEW_LINE> <DEDENT> self.last[self.upstreams.index(who)] = x <NEW_LINE> if not self.missing and who in self.emit_on: <NEW_LINE> <INDENT> tup = tuple(self.last) <NEW_LINE> return self._emit(tup)
Combine multiple streams together to a stream of tuples This will emit a new tuple of all of the most recent elements seen from any stream. Parameters ---------- emit_on : stream or list of streams or None only emit upon update of the streams listed. If None, emit on update from any stream See Also -------- zip
6259905199cbb53fe68323a9
class CryptoInvalidKeyException(Exception): <NEW_LINE> <INDENT> pass
Exception raised when an invalid key is supplied for encryption or decryption
625990513eb6a72ae038bb1f
class DynamicFilter(eventfilter.EventObjectFilter): <NEW_LINE> <INDENT> @property <NEW_LINE> def fields(self): <NEW_LINE> <INDENT> return self._fields <NEW_LINE> <DEDENT> @property <NEW_LINE> def limit(self): <NEW_LINE> <INDENT> return self._limit <NEW_LINE> <DEDENT> @property <NEW_LINE> def separator(self): <NEW_LINE> <INDENT> return self._separator <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> super(DynamicFilter, self).__init__() <NEW_LINE> self._fields = [] <NEW_LINE> self._limit = 0 <NEW_LINE> self._separator = u',' <NEW_LINE> <DEDENT> def CompileFilter(self, filter_string): <NEW_LINE> <INDENT> lex = SelectiveLexer(filter_string) <NEW_LINE> _ = lex.NextToken() <NEW_LINE> if lex.error: <NEW_LINE> <INDENT> raise errors.WrongPlugin('Malformed filter string.') <NEW_LINE> <DEDENT> _ = lex.NextToken() <NEW_LINE> if lex.error: <NEW_LINE> <INDENT> raise errors.WrongPlugin('No fields defined.') <NEW_LINE> <DEDENT> if lex.state is not 'END': <NEW_LINE> <INDENT> while lex.state is not 'END': <NEW_LINE> <INDENT> _ = lex.NextToken() <NEW_LINE> if lex.error: <NEW_LINE> <INDENT> raise errors.WrongPlugin('No filter defined for DynamicFilter.') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if lex.state != 'END': <NEW_LINE> <INDENT> raise errors.WrongPlugin( 'Malformed DynamicFilter, end state not reached.') <NEW_LINE> <DEDENT> self._fields = lex.fields <NEW_LINE> self._limit = lex.limit <NEW_LINE> self._separator = unicode(lex.separator) <NEW_LINE> if lex.lex_filter: <NEW_LINE> <INDENT> super(DynamicFilter, self).CompileFilter(lex.lex_filter) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.matcher = None
A twist to the EventObjectFilter allowing output fields to be selected. This filter is essentially the same as the EventObjectFilter except it wraps it in a selection of which fields should be included by an output module that has support for selective fields. That is to say the filter: SELECT field_a, field_b WHERE attribute contains 'text' Will use the EventObjectFilter "attribute contains 'text'" and at the same time indicate to the appropriate output module that the user wants only the fields field_a and field_b to be used in the output.
6259905145492302aabfd998
class FunctionNotFoundError(SoftboxenError): <NEW_LINE> <INDENT> message = 'Invalid function: %(error)s'
Raise when base function not initialized
62599051d53ae8145f919921
class KaaNode(object): <NEW_LINE> <INDENT> def __init__(self, host, port): <NEW_LINE> <INDENT> self.host = str(host) <NEW_LINE> self.port = str(port) <NEW_LINE> <DEDENT> def download_sdk(self, profile_id, language, kaauser, ofile): <NEW_LINE> <INDENT> url = 'http://{}:{}/kaaAdmin/rest/api/sdk?sdkProfileId={}' '&targetPlatform={}'.format(self.host, self.port, str(profile_id), language) <NEW_LINE> req = requests.post(url, auth=(kaauser.name, kaauser.password)) <NEW_LINE> if req.status_code != requests.codes.ok: <NEW_LINE> <INDENT> raise KaaNodeError('Unable to download SDK.' 'Return code: {}'.format(req.status_code)) <NEW_LINE> <DEDENT> with open(ofile, 'w') as output_file: <NEW_LINE> <INDENT> output_file.write(req.content) <NEW_LINE> <DEDENT> <DEDENT> def get_applications(self, kaauser): <NEW_LINE> <INDENT> url = 'http://{}:{}/kaaAdmin/rest/api/applications'.format(self.host, self.port) <NEW_LINE> req = requests.get(url, auth=(kaauser.name, kaauser.password)) <NEW_LINE> if req.status_code != requests.codes.ok: <NEW_LINE> <INDENT> raise KaaNodeError('Unable to get list of applications. ' 'Return code: {}'.format(req.status_code)) <NEW_LINE> <DEDENT> return req.json() <NEW_LINE> <DEDENT> def get_sdk_profiles(self, appname, kaauser): <NEW_LINE> <INDENT> apps = self.get_applications(kaauser) <NEW_LINE> token = None <NEW_LINE> for app in apps: <NEW_LINE> <INDENT> if app['name'] == appname: <NEW_LINE> <INDENT> token = app['applicationToken'] <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if not token: <NEW_LINE> <INDENT> raise KaaNodeError('Application: "{}" was not found'.format(appname)) <NEW_LINE> <DEDENT> url = 'http://{}:{}/kaaAdmin/rest/api/sdkProfiles/{}'.format(self.host, self.port, str(token)) <NEW_LINE> req = requests.get(url, auth=(kaauser.name, kaauser.password)) <NEW_LINE> if req.status_code != requests.codes.ok: <NEW_LINE> <INDENT> raise KaaNodeError('Unable to get SDK profiles. ' 'Return code: {}'.format(req.status_code)) <NEW_LINE> <DEDENT> return req.json() <NEW_LINE> <DEDENT> def wait_for_server(self, timeout): <NEW_LINE> <INDENT> start = time.time() <NEW_LINE> while time.time() - start < timeout: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> url = 'http://{}:{}/kaaAdmin/rest/api'.format(self.host, self.port) <NEW_LINE> requests.get(url) <NEW_LINE> return <NEW_LINE> <DEDENT> except requests.ConnectionError as ex: <NEW_LINE> <INDENT> time.sleep(1) <NEW_LINE> <DEDENT> <DEDENT> raise KaaNodeError("Timeout error")
Allows to communicate with Kaa node via REST API
6259905107f4c71912bb08f9
class TestCompareXLSXFiles(ExcelComparisonTest): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.set_filename('simple01.xlsx') <NEW_LINE> <DEDENT> def test_create_file(self): <NEW_LINE> <INDENT> workbook = Workbook(self.got_filename) <NEW_LINE> worksheet = workbook.add_worksheet() <NEW_LINE> worksheet.write_string(0, 0, 'Hello') <NEW_LINE> worksheet.write_number(1, 0, 123) <NEW_LINE> workbook.close() <NEW_LINE> self.assertExcelEqual() <NEW_LINE> <DEDENT> def test_create_file_A1(self): <NEW_LINE> <INDENT> workbook = Workbook(self.got_filename) <NEW_LINE> worksheet = workbook.add_worksheet() <NEW_LINE> worksheet.write_string('A1', 'Hello') <NEW_LINE> worksheet.write_number('A2', 123) <NEW_LINE> workbook.close() <NEW_LINE> self.assertExcelEqual() <NEW_LINE> <DEDENT> def test_create_file_write(self): <NEW_LINE> <INDENT> workbook = Workbook(self.got_filename) <NEW_LINE> worksheet = workbook.add_worksheet() <NEW_LINE> worksheet.write(0, 0, 'Hello') <NEW_LINE> worksheet.write(1, 0, 123) <NEW_LINE> workbook.close() <NEW_LINE> self.assertExcelEqual() <NEW_LINE> <DEDENT> def test_create_file_with_statement(self): <NEW_LINE> <INDENT> with Workbook(self.got_filename) as workbook: <NEW_LINE> <INDENT> worksheet = workbook.add_worksheet() <NEW_LINE> worksheet.write(0, 0, 'Hello') <NEW_LINE> worksheet.write(1, 0, 123) <NEW_LINE> <DEDENT> self.assertExcelEqual() <NEW_LINE> <DEDENT> def test_create_file_write_A1(self): <NEW_LINE> <INDENT> workbook = Workbook(self.got_filename) <NEW_LINE> worksheet = workbook.add_worksheet() <NEW_LINE> worksheet.write('A1', 'Hello') <NEW_LINE> worksheet.write('A2', 123) <NEW_LINE> workbook.close() <NEW_LINE> self.assertExcelEqual() <NEW_LINE> <DEDENT> def test_create_file_kwargs(self): <NEW_LINE> <INDENT> workbook = Workbook(self.got_filename) <NEW_LINE> worksheet = workbook.add_worksheet() <NEW_LINE> worksheet.write_string(row=0, col=0, string='Hello') <NEW_LINE> worksheet.write_number(row=1, col=0, number=123) <NEW_LINE> workbook.close() <NEW_LINE> self.assertExcelEqual() <NEW_LINE> <DEDENT> def test_create_file_write_date_default(self): <NEW_LINE> <INDENT> workbook = Workbook(self.got_filename) <NEW_LINE> worksheet = workbook.add_worksheet() <NEW_LINE> worksheet.write('A1', 'Hello') <NEW_LINE> worksheet.write('A2', date(1900, 5, 2)) <NEW_LINE> workbook.close() <NEW_LINE> self.assertExcelEqual() <NEW_LINE> <DEDENT> def test_create_file_in_memory(self): <NEW_LINE> <INDENT> workbook = Workbook(self.got_filename, {'in_memory': True}) <NEW_LINE> worksheet = workbook.add_worksheet() <NEW_LINE> worksheet.write_string(0, 0, 'Hello') <NEW_LINE> worksheet.write_number(1, 0, 123) <NEW_LINE> workbook.close() <NEW_LINE> self.assertExcelEqual()
Test file created by XlsxWriter against a file created by Excel.
62599051e64d504609df9e30
class NullPrior(Prior): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def loglikelihood(self, net): <NEW_LINE> <INDENT> return 0.0
A null prior which returns 0.0 for the loglikelihood. The name for this object is a bit confusing because the UniformPrior is often considered the null prior in that it doesn't favor any edge more than another. It still favors smaller networks and takes time to calculate the loglikelihood. This class provides an implementation that simply returns 0.0 for the loglikelihood. It's a null prior in the sense that the resulting scores are the same as if you hadn't used a prior at all.
62599051097d151d1a2c2536
class _NoMessage(object): <NEW_LINE> <INDENT> def __init__(self, message_type): <NEW_LINE> <INDENT> self.message_type = message_type <NEW_LINE> <DEDENT> def message_hook(self, *args, **kwargs): <NEW_LINE> <INDENT> warn( f'Message type "{self.message_type}" not supported for ' f'game "{GAME_NAME}".' )
Class used to hook non-supported message types.
62599051a8ecb033258726d7
class InvalidActionException(Exception): <NEW_LINE> <INDENT> pass
Raised when an action is impossible to execute
625990510fa83653e46f63a4
class IpynbCasper(Template): <NEW_LINE> <INDENT> aliases = ['ipynbcasper']
ipynb casper
62599051498bea3a75a58fe6
class TestPlanioIntegration(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testPlanioIntegration(self): <NEW_LINE> <INDENT> pass
PlanioIntegration unit test stubs
625990510c0af96317c577c2
class Investment(Base): <NEW_LINE> <INDENT> __tablename__ = 'interinvest' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> dt = Column(DateTime, default=datetime.utcnow) <NEW_LINE> freq = Column(String(1), default='Q') <NEW_LINE> assets = Column(Float) <NEW_LINE> net_inv_pos = Column(Float) <NEW_LINE> direct_inv = Column(Float) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return f'<InterInvest(dt={self.dt}, freq={self.freq}, assets={self.assets},' f' net_inv_pos={self.net_inv_pos}, direct_inv={self.direct_inv})>'
https://bank.gov.ua/NBUStatService/v1/statdirectory/interinvestpos?date=200301&s181=Total&json
6259905130dc7b76659a0cdf
class TestGenPartitionsPair(TestGenPartitionsBase): <NEW_LINE> <INDENT> attrib="quick" <NEW_LINE> def setup(self): <NEW_LINE> <INDENT> self.par = Par(N=4, m_q=1) <NEW_LINE> self.model = SinglePair(self.par) <NEW_LINE> <DEDENT> def test_one(self): <NEW_LINE> <INDENT> assert self._generate_partitions_1() == [(-4, fsPairs(h=[-2], p=[-4])), (-4, fsPairs(h=[-1], p=[-4])), (-4, fsPairs(h=[0], p=[-4])), (-4, fsPairs(h=[1], p=[-4])), (-3, fsPairs(h=[-2], p=[-3])), (-3, fsPairs(h=[-1], p=[-3])), (-3, fsPairs(h=[0], p=[-3])), (-3, fsPairs(h=[1], p=[-3])), (-3, fsPairs(h=[2], p=[-3]))] <NEW_LINE> <DEDENT> def test_two(self): <NEW_LINE> <INDENT> res = self._generate_partitions(2, 0, 3) <NEW_LINE> assert res == [(3, fsPairs(h=[-2, 2], p=[3, -3])), (3, fsPairs(h=[-1, 1], p=[3, -3])), (3, fsPairs(h=[-1, 2], p=[3, -3])), (3, fsPairs(h=[0, 1], p=[3, -3])), (3, fsPairs(h=[0, 2], p=[3, -3])), (3, fsPairs(h=[1, 2], p=[3, -3])), (-4, fsPairs(h=[-2, -1], p=[-4, -3])), (-4, fsPairs(h=[-2, 0], p=[-4, -3])), (-4, fsPairs(h=[-2, 1], p=[-4, 3])), (-4, fsPairs(h=[-2, 2], p=[-4, 3])), (-4, fsPairs(h=[-1, 0], p=[-4, 3])), (-4, fsPairs(h=[-1, 1], p=[-4, 3])), (-4, fsPairs(h=[-1, 2], p=[-4, 3])), (-4, fsPairs(h=[0, 1], p=[-4, 3])), (-4, fsPairs(h=[0, 2], p=[-4, 3])), (-4, fsPairs(h=[1, 2], p=[-4, 3]))] <NEW_LINE> <DEDENT> def test_two_restart(self): <NEW_LINE> <INDENT> r1 = self._generate_partitions(2, 0, 3) <NEW_LINE> r2 = self._generate_partitions(2, 3, 5) <NEW_LINE> assert r1+r2 == self._generate_partitions(2, 0, 5)
Test generate_partitions: SinglePair model.
6259905171ff763f4b5e8c6f
class CartItem(models.Model): <NEW_LINE> <INDENT> pass <NEW_LINE> m = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) <NEW_LINE> user_id = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) <NEW_LINE> quantity = models.IntegerField(default=1) <NEW_LINE> order_id = models.ForeignKey('TestCart', on_delete=models.SET_NULL, null=True) <NEW_LINE> def getPrice(self): <NEW_LINE> <INDENT> return self.m.price <NEW_LINE> <DEDENT> def getLineTotal(self): <NEW_LINE> <INDENT> return self.m.price * self.quantity <NEW_LINE> <DEDENT> def increaseQuantity(self): <NEW_LINE> <INDENT> self.quantity += 1 <NEW_LINE> self.save() <NEW_LINE> <DEDENT> def decreaseQuantity(self): <NEW_LINE> <INDENT> self.quantity -=1 <NEW_LINE> if self.quantity < 1: <NEW_LINE> <INDENT> self.quantity = 1 <NEW_LINE> <DEDENT> self.save() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f'{self.m} x [{self.quantity}] For: {self.order_id}'
eeew
62599051462c4b4f79dbcec5
class ExpectedImprovementInterface(with_metaclass(ABCMeta, object)): <NEW_LINE> <INDENT> @abstractproperty <NEW_LINE> def dim(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractproperty <NEW_LINE> def num_to_sample(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractproperty <NEW_LINE> def num_being_sampled(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def compute_expected_improvement(self, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def compute_grad_expected_improvement(self, **kwargs): <NEW_LINE> <INDENT> pass
Interface for Expected Improvement computation: EI and its gradient at specified point(s) sampled from a GaussianProcess. A class to encapsulate the computation of expected improvement and its spatial gradient using points sampled from an associated GaussianProcess. The general EI computation requires monte-carlo integration; it can support q,p-EI optimization. It is designed to work with any GaussianProcess. See file docs for a description of what EI is and an overview of how it can be computed. Implementers are responsible for dealing with PRNG state for any randomness needed in EI computation. Implementers are also responsible for storing ``points_to_sample`` and ``points_being_sampled``: :param points_to_sample: points at which to evaluate EI and/or its gradient to check their value in future experiments (i.e., "q" in q,p-EI) :type points_to_sample: array of float64 with shape (num_to_sample, dim) :param points_being_sampled: points being sampled in concurrent experiments (i.e., "p" in q,p-EI) :type points_being_sampled: array of float64 with shape (num_being_sampled, dim)
6259905145492302aabfd99a
class BaseTestCase(TestCase): <NEW_LINE> <INDENT> def create_app(self): <NEW_LINE> <INDENT> app.config.from_object('config.TestConfig') <NEW_LINE> return app <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> create_db() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> db.session.remove() <NEW_LINE> db.drop_all()
A base test case.
6259905107d97122c421816b
class Result(ffn.GroupStats): <NEW_LINE> <INDENT> def __init__(self, *backtests): <NEW_LINE> <INDENT> tmp = [pd.DataFrame({x.name: x.strategy.prices}) for x in backtests] <NEW_LINE> super(Result, self).__init__(*tmp) <NEW_LINE> self.backtest_list = backtests <NEW_LINE> self.backtests = {x.name: x for x in backtests} <NEW_LINE> if len(backtests) == 1: <NEW_LINE> <INDENT> self.strategy = self.backtest_list[0].strategy <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.strategy = {x.name: x.strategy for x in backtests} <NEW_LINE> <DEDENT> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> new_backtests = [test for test in self.backtest_list] <NEW_LINE> new_backtests += [test for test in other.backtest_list] <NEW_LINE> return Result(*new_backtests) <NEW_LINE> <DEDENT> def __sub__(self, other): <NEW_LINE> <INDENT> new_backtests = [test for test in self.backtest_list] <NEW_LINE> new_backtests = list(set(new_backtests) - set([test for test in other.backtest_list])) <NEW_LINE> return Result(*new_backtests) <NEW_LINE> <DEDENT> def sub(self, other_name): <NEW_LINE> <INDENT> others = parse_arg(other_name) <NEW_LINE> new_backtests = [test for test in self.backtest_list if test.name not in others] <NEW_LINE> return Result(*new_backtests) <NEW_LINE> <DEDENT> def subtract(self, other_name): <NEW_LINE> <INDENT> return self.sub(other_name) <NEW_LINE> <DEDENT> def display_monthly_returns(self, backtest=0): <NEW_LINE> <INDENT> key = self._get_backtest(backtest) <NEW_LINE> self[key].display_monthly_returns() <NEW_LINE> <DEDENT> def plot_weights(self, backtest=0, filter=None, figsize=(15, 5), **kwds): <NEW_LINE> <INDENT> key = self._get_backtest(backtest) <NEW_LINE> if filter is not None: <NEW_LINE> <INDENT> data = self.backtests[key].weights[filter] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data = self.backtests[key].weights <NEW_LINE> <DEDENT> data.plot(figsize=figsize, **kwds) <NEW_LINE> <DEDENT> def plot_security_weights(self, backtest=0, filter=None, figsize=(15, 5), **kwds): <NEW_LINE> <INDENT> key = self._get_backtest(backtest) <NEW_LINE> if filter is not None: <NEW_LINE> <INDENT> data = self.backtests[key].security_weights[filter] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data = self.backtests[key].security_weights <NEW_LINE> <DEDENT> data.plot(figsize=figsize, **kwds) <NEW_LINE> plt.show() <NEW_LINE> <DEDENT> def plot_histogram(self, backtest=0, **kwds): <NEW_LINE> <INDENT> key = self._get_backtest(backtest) <NEW_LINE> self[key].plot_histogram(**kwds) <NEW_LINE> <DEDENT> def _get_backtest(self, backtest): <NEW_LINE> <INDENT> if type(backtest) == int: <NEW_LINE> <INDENT> return self.backtest_list[backtest].name <NEW_LINE> <DEDENT> return backtest <NEW_LINE> <DEDENT> def save(self, path=DEFAULT_PATH): <NEW_LINE> <INDENT> import pickle <NEW_LINE> name = log_name(path, ';'.join(list(self.keys()))) <NEW_LINE> f = open(path+'\\'+name, 'wb') <NEW_LINE> pickle.dump(self, f) <NEW_LINE> f.close() <NEW_LINE> return True
Based on ffn's GroupStats with a few extra helper methods. Args: * backtests (list): List of backtests Attributes: * backtest_list (list): List of bactests in the same order as provided * backtests (dict): Dict of backtests by name
62599051e5267d203ee6cdb0
class HTTPServerWithEvents(http_server.HTTPServer): <NEW_LINE> <INDENT> def __init__(self, addr, handler, worker_id): <NEW_LINE> <INDENT> http_server.HTTPServer.__init__(self, addr, handler, False) <NEW_LINE> self.worker_id = worker_id <NEW_LINE> self.events = [] <NEW_LINE> <DEDENT> def append(self, event): <NEW_LINE> <INDENT> self.events.append(event)
HTTP server used by the handler to store events
625990512ae34c7f260ac5a8
class IsOwnerOrReadOnly(permissions.BasePermission): <NEW_LINE> <INDENT> def has_object_permission(self, request, view, obj): <NEW_LINE> <INDENT> if request.method in permissions.SAFE_METHODS: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return obj.author == request.user
Determine if object belongs to owner, otherwise allow safe methods
62599051b830903b9686eede
class Wrapper(BaseWrapper): <NEW_LINE> <INDENT> def wrap(self, entry: PluginEntry): <NEW_LINE> <INDENT> return Environment(entry.plugin, self._get_registry(entry))
Wraps a plugin into environment
625990518e71fb1e983bcf8c
class Preferences(UsersModel, db.Model): <NEW_LINE> <INDENT> __tablename__ = 'preferences' <NEW_LINE> id = db.Column(db.Integer, primary_key=True,autoincrement=True) <NEW_LINE> preferences = db.Column(db.Text, default='') <NEW_LINE> description = db.Column(db.Text, default='') <NEW_LINE> user = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> managed = True
User preferences, such as columns selection
6259905145492302aabfd99b
class RecipeSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> ingredients = serializers.PrimaryKeyRelatedField( many=True, queryset=Ingredient.objects.all() ) <NEW_LINE> tags = serializers.PrimaryKeyRelatedField( many=True, queryset=Tag.objects.all() ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Recipe <NEW_LINE> fields = ( 'id', 'title', 'image', 'ingredients', 'tags', 'time_minutes', 'price', 'link' ) <NEW_LINE> read_only_fields = ('id',)
Serializer for recipe objects
62599051dc8b845886d54a85
class ISIdNumberField(RegexField): <NEW_LINE> <INDENT> default_error_messages = { 'invalid': ugettext('Enter a valid Icelandic identification number. The format is XXXXXX-XXXX.'), 'checksum': ugettext(u'The Icelandic identification number is not valid.'), } <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> kwargs['min_length'],kwargs['max_length'] = 10,11 <NEW_LINE> super(ISIdNumberField, self).__init__(r'^\d{6}(-| )?\d{4}$', *args, **kwargs) <NEW_LINE> <DEDENT> def clean(self, value): <NEW_LINE> <INDENT> value = super(ISIdNumberField, self).clean(value) <NEW_LINE> if value in EMPTY_VALUES: <NEW_LINE> <INDENT> return u'' <NEW_LINE> <DEDENT> value = self._canonify(value) <NEW_LINE> if self._validate(value): <NEW_LINE> <INDENT> return self._format(value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValidationError(self.error_messages['checksum']) <NEW_LINE> <DEDENT> <DEDENT> def _canonify(self, value): <NEW_LINE> <INDENT> return value.replace('-', '').replace(' ', '') <NEW_LINE> <DEDENT> def _validate(self, value): <NEW_LINE> <INDENT> check = [3, 2, 7, 6, 5, 4, 3, 2, 1, 0] <NEW_LINE> return sum([int(value[i]) * check[i] for i in range(10)]) % 11 == 0 <NEW_LINE> <DEDENT> def _format(self, value): <NEW_LINE> <INDENT> return smart_unicode(value[:6]+'-'+value[6:])
Icelandic identification number (kennitala). This is a number every citizen of Iceland has.
625990513539df3088ecd768
class CategoryViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = Category.objects.all() <NEW_LINE> serializer_class = CategorySerializer
API endpoint that allows donations to be viewed and edited.
62599051d486a94d0ba2d48b
class LimitsController(Controller): <NEW_LINE> <INDENT> _serialization_metadata = { "application/xml": { "attributes": { "limit": ["verb", "URI", "regex", "value", "unit", "resetTime", "remaining", "name"], }, "plurals": { "rate": "limit", }, }, } <NEW_LINE> def index(self, req): <NEW_LINE> <INDENT> abs_limits = {} <NEW_LINE> rate_limits = req.environ.get("nova.limits", []) <NEW_LINE> return { "limits": { "rate": rate_limits, "absolute": abs_limits, }, }
Controller for accessing limits in the OpenStack API.
6259905115baa72349463454
class SmartClassParameters(ForemanObjects): <NEW_LINE> <INDENT> objName = 'smart_class_parameters' <NEW_LINE> payloadObj = 'smart_class_parameter' <NEW_LINE> itemType = ItemSmartClassParameter <NEW_LINE> index = 'id'
SmartClassParameters class
62599051009cb60464d02a01
class CorpusDocument (dict): <NEW_LINE> <INDENT> def __init__(self, id = None): <NEW_LINE> <INDENT> self._docid = id <NEW_LINE> <DEDENT> def get_id(self): <NEW_LINE> <INDENT> return self._docid <NEW_LINE> <DEDENT> def _set_id(self, id): <NEW_LINE> <INDENT> self._docid = deepcopy(id)
Class for documents apearing in the corpus.
625990517cff6e4e811b6f04
class WaveletPacket2D(Node2D): <NEW_LINE> <INDENT> def __init__(self, data, wavelet, mode='sp1', maxlevel=None): <NEW_LINE> <INDENT> super(WaveletPacket2D, self).__init__(None, data, "") <NEW_LINE> if not isinstance(wavelet, Wavelet): <NEW_LINE> <INDENT> wavelet = Wavelet(wavelet) <NEW_LINE> <DEDENT> self.wavelet = wavelet <NEW_LINE> self.mode = mode <NEW_LINE> if data is not None: <NEW_LINE> <INDENT> data = numerix.as_float_array(data) <NEW_LINE> assert len(data.shape) == 2 <NEW_LINE> self.data_size = data.shape <NEW_LINE> if maxlevel is None: <NEW_LINE> <INDENT> maxlevel = dwt_max_level(min(self.data_size), self.wavelet) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.data_size = None <NEW_LINE> <DEDENT> self._maxlevel = maxlevel <NEW_LINE> <DEDENT> def reconstruct(self, update=True): <NEW_LINE> <INDENT> if self.has_any_subnode: <NEW_LINE> <INDENT> data = super(WaveletPacket2D, self).reconstruct(update) <NEW_LINE> if self.data_size is not None and (data.shape != self.data_size): <NEW_LINE> <INDENT> data = data[:self.data_size[0], :self.data_size[1]] <NEW_LINE> <DEDENT> if update: <NEW_LINE> <INDENT> self.data = data <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> return self.data <NEW_LINE> <DEDENT> def get_level(self, level, order="natural", decompose=True): <NEW_LINE> <INDENT> assert order in ["natural", "freq"] <NEW_LINE> if level > self.maxlevel: <NEW_LINE> <INDENT> raise ValueError("The level cannot be greater than the maximum" " decomposition level value (%d)" % self.maxlevel) <NEW_LINE> <DEDENT> result = [] <NEW_LINE> def collect(node): <NEW_LINE> <INDENT> if node.level == level: <NEW_LINE> <INDENT> result.append(node) <NEW_LINE> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> self.walk(collect, decompose=decompose) <NEW_LINE> if order == "freq": <NEW_LINE> <INDENT> nodes = {} <NEW_LINE> for (row_path, col_path), node in [(self.expand_2d_path(node.path), node) for node in result]: <NEW_LINE> <INDENT> nodes.setdefault(row_path, {})[col_path] = node <NEW_LINE> <DEDENT> graycode_order = get_graycode_order(level, x='l', y='h') <NEW_LINE> nodes = [nodes[path] for path in graycode_order if path in nodes] <NEW_LINE> result = [] <NEW_LINE> for row in nodes: <NEW_LINE> <INDENT> result.append( [row[path] for path in graycode_order if path in row] ) <NEW_LINE> <DEDENT> <DEDENT> return result
Data structure representing 2D Wavelet Packet decomposition of signal. data - original data (signal) wavelet - wavelet used in DWT decomposition and reconstruction mode - signal extension mode - see MODES maxlevel - maximum level of decomposition (will be computed if not specified)
62599051d6c5a102081e35df
class AccessFromEmpty(Exception): <NEW_LINE> <INDENT> pass
Error attempting to access an element from an empty container.
6259905124f1403a92686331
class SplitTimeDeltaWidget(NamedMultiWidget): <NEW_LINE> <INDENT> def __init__(self, attrs=None): <NEW_LINE> <INDENT> widgets = OrderedDict() <NEW_LINE> widgets['unit'] = forms.widgets.Select( attrs={'style': 'width: 8em;'}, choices=TIME_DELTA_UNIT_CHOICES ) <NEW_LINE> widgets['amount'] = forms.widgets.NumberInput( attrs={ 'maxlength': 4, 'style': 'width: 8em;', 'placeholder': _('Amount') } ) <NEW_LINE> super(SplitTimeDeltaWidget, self).__init__(widgets=widgets, attrs=attrs) <NEW_LINE> <DEDENT> def decompress(self, value): <NEW_LINE> <INDENT> return { 'unit': None, 'amount': None } <NEW_LINE> <DEDENT> def value_from_datadict(self, querydict, files, name): <NEW_LINE> <INDENT> unit = querydict.get('{}_unit'.format(name)) <NEW_LINE> amount = querydict.get('{}_amount'.format(name)) <NEW_LINE> if not unit or not amount: <NEW_LINE> <INDENT> return now() <NEW_LINE> <DEDENT> amount = int(amount) <NEW_LINE> timedelta = datetime.timedelta(**{unit: amount}) <NEW_LINE> return now() + timedelta
A Widget that splits a timedelta input into two field: one for unit of time and another for the amount of units.
6259905130dc7b76659a0ce0
class PassageIndex(models.Model): <NEW_LINE> <INDENT> start_verse = VerseField() <NEW_LINE> end_verse = VerseField() <NEW_LINE> task = models.ForeignKey(Task, blank=True, null=True) <NEW_LINE> book = models.ForeignKey(Book, blank=True, null=True) <NEW_LINE> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, PassageIndex): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.start_verse == other.start_verse and self.end_verse == other.end_verse <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def extract_from_string(value): <NEW_LINE> <INDENT> passages = [] <NEW_LINE> references = scriptures.extract(value) <NEW_LINE> for (book, from_chapter, from_verse, to_chapter, to_verse) in references: <NEW_LINE> <INDENT> start_verse = '{book} {chapter}:{verse}'.format( book=book, chapter=from_chapter, verse=from_verse ) <NEW_LINE> end_verse = '{book} {chapter}:{verse}'.format( book=book, chapter=to_chapter, verse=to_verse ) <NEW_LINE> passages.append(PassageIndex(start_verse=start_verse, end_verse=end_verse)) <NEW_LINE> <DEDENT> return passages
Describes a passage index. This is used to index passages associated with different things for searching.
6259905107f4c71912bb08fc
class Selection(Accumulator): <NEW_LINE> <INDENT> def __init__(self, child): <NEW_LINE> <INDENT> self._skipped = 0 <NEW_LINE> self._child = child <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def create(cls, child): <NEW_LINE> <INDENT> return cls(child=child) <NEW_LINE> <DEDENT> def update(self, datum): <NEW_LINE> <INDENT> if common.is_selected(datum): <NEW_LINE> <INDENT> self._child.update(datum) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._skipped += 1 <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def state(self): <NEW_LINE> <INDENT> child_state = self._child.state <NEW_LINE> return dict(skipped=self._skipped, **(child_state if isinstance(child_state, dict) else dict(value=child_state)))
Select data based on the "select" tag in each datum.
62599051fff4ab517ebcece5
class CreateCounterexample(object): <NEW_LINE> <INDENT> def __init__(self, text): <NEW_LINE> <INDENT> self.text = text <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _from_dict(cls, _dict): <NEW_LINE> <INDENT> args = {} <NEW_LINE> if 'text' in _dict: <NEW_LINE> <INDENT> args['text'] = _dict.get('text') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError( 'Required property \'text\' not present in CreateCounterexample JSON' ) <NEW_LINE> <DEDENT> return cls(**args) <NEW_LINE> <DEDENT> def _to_dict(self): <NEW_LINE> <INDENT> _dict = {} <NEW_LINE> if hasattr(self, 'text') and self.text is not None: <NEW_LINE> <INDENT> _dict['text'] = self.text <NEW_LINE> <DEDENT> return _dict <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return json.dumps(self._to_dict(), indent=2) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, self.__class__): <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
CreateCounterexample. :attr str text: The text of a user input marked as irrelevant input. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters - It cannot consist of only whitespace characters - It must be no longer than 1024 characters.
6259905107d97122c421816d
class TwitterClient(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> consumer_key = 'XXXXXXXXXXXXXXXXXXXXXXXX' <NEW_LINE> consumer_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX' <NEW_LINE> access_token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX' <NEW_LINE> access_token_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXX' <NEW_LINE> try: <NEW_LINE> <INDENT> self.auth = OAuthHandler(consumer_key, consumer_secret) <NEW_LINE> self.auth.set_access_token(access_token, access_token_secret) <NEW_LINE> self.api = tweepy.API(self.auth) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print("Error: Authentication Failed") <NEW_LINE> <DEDENT> <DEDENT> def clean_tweet(self, tweet): <NEW_LINE> <INDENT> return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t]) |(\w+:\/\/\S+)", " ", tweet).split()) <NEW_LINE> <DEDENT> def get_tweet_sentiment(self, tweet): <NEW_LINE> <INDENT> analysis = TextBlob(self.clean_tweet(tweet)) <NEW_LINE> if analysis.sentiment.polarity > 0: <NEW_LINE> <INDENT> return 'positive' <NEW_LINE> <DEDENT> elif analysis.sentiment.polarity == 0: <NEW_LINE> <INDENT> return 'neutral' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'negative' <NEW_LINE> <DEDENT> <DEDENT> def get_tweets(self, query, count = 10): <NEW_LINE> <INDENT> tweets = [] <NEW_LINE> try: <NEW_LINE> <INDENT> fetched_tweets = self.api.search(q = query, count = count) <NEW_LINE> for tweet in fetched_tweets: <NEW_LINE> <INDENT> parsed_tweet = {} <NEW_LINE> parsed_tweet['text'] = tweet.text <NEW_LINE> parsed_tweet['sentiment'] = self.get_tweet_sentiment(tweet.text) <NEW_LINE> if tweet.retweet_count > 0: <NEW_LINE> <INDENT> if parsed_tweet not in tweets: <NEW_LINE> <INDENT> tweets.append(parsed_tweet) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> tweets.append(parsed_tweet) <NEW_LINE> <DEDENT> <DEDENT> return tweets <NEW_LINE> <DEDENT> except tweepy.TweepError as e: <NEW_LINE> <INDENT> print("Error : " + str(e))
Generic Twitter Class for sentiment analysis.
62599051d53ae8145f919925
class ProfileServicer(object): <NEW_LINE> <INDENT> def Insert(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') <NEW_LINE> <DEDENT> def Update(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') <NEW_LINE> <DEDENT> def Remove(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!')
Missing associated documentation comment in .proto file.
6259905110dbd63aa1c720a7
class SaMsgQueueGroupNotificationBufferT(Structure): <NEW_LINE> <INDENT> _fields_ = [('numberOfItems', SaUint32T), ('notification', POINTER(SaMsgQueueGroupNotificationT)), ('queueGroupPolicy', SaMsgQueueGroupPolicyT)]
Contain array of queue group notifications.
625990511f037a2d8b9e52cf
class EmptyTestResultFactory(ITestResultFactory): <NEW_LINE> <INDENT> def __init__(self, result_factory_func=None): <NEW_LINE> <INDENT> self._result_factory_func = result_factory_func <NEW_LINE> <DEDENT> def create(self, testcase): <NEW_LINE> <INDENT> if self._result_factory_func is None: <NEW_LINE> <INDENT> return testresult.EmptyResult() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._result_factory_func(testcase) <NEW_LINE> <DEDENT> <DEDENT> def dumps(self): <NEW_LINE> <INDENT> return self._result_factory_func <NEW_LINE> <DEDENT> def loads(self, buf): <NEW_LINE> <INDENT> self._result_factory_func = buf
测试结果工厂
62599051e5267d203ee6cdb2
class BertSquadLogitsLayer(tf.keras.layers.Layer): <NEW_LINE> <INDENT> def __init__(self, initializer=None, float_type=tf.float32, **kwargs): <NEW_LINE> <INDENT> super(BertSquadLogitsLayer, self).__init__(**kwargs) <NEW_LINE> self.initializer = initializer <NEW_LINE> self.float_type = float_type <NEW_LINE> <DEDENT> def build(self, unused_input_shapes): <NEW_LINE> <INDENT> self.final_dense = tf.keras.layers.Dense( units=2, kernel_initializer=self.initializer, name='final_dense') <NEW_LINE> super(BertSquadLogitsLayer, self).build(unused_input_shapes) <NEW_LINE> <DEDENT> def call(self, inputs): <NEW_LINE> <INDENT> sequence_output = inputs <NEW_LINE> input_shape = sequence_output.shape.as_list() <NEW_LINE> sequence_length = input_shape[1] <NEW_LINE> num_hidden_units = input_shape[2] <NEW_LINE> final_hidden_input = tf.keras.backend.reshape(sequence_output, [-1, num_hidden_units]) <NEW_LINE> logits = self.final_dense(final_hidden_input) <NEW_LINE> logits = tf.keras.backend.reshape(logits, [-1, sequence_length, 2]) <NEW_LINE> logits = tf.transpose(logits, [2, 0, 1]) <NEW_LINE> unstacked_logits = tf.unstack(logits, axis=0) <NEW_LINE> if self.float_type == tf.float16: <NEW_LINE> <INDENT> unstacked_logits = tf.cast(unstacked_logits, tf.float32) <NEW_LINE> <DEDENT> return unstacked_logits[0], unstacked_logits[1]
Returns a layer that computes custom logits for BERT squad model.
62599051dd821e528d6da3a3
class ScreenRecord(AbstractTimestampTrashBinModel): <NEW_LINE> <INDENT> case = models.ForeignKey(Case, related_name='screens', on_delete=models.CASCADE) <NEW_LINE> name = models.CharField("screen name", max_length=40) <NEW_LINE> start_time = models.DateTimeField(default=now) <NEW_LINE> end_time = models.DateTimeField(null=True, blank=True) <NEW_LINE> button = models.CharField( help_text="Button the operator pressed to finish the screen", choices=BUTTON_CHOICES, max_length=10, blank=True, ) <NEW_LINE> input = models.CharField( help_text="Input field from screen", blank=True, default='', max_length=80, ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = _("screen record") <NEW_LINE> verbose_name_plural = _("screen records") <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def end(self, case, button=None, input=None): <NEW_LINE> <INDENT> self.button = button or '' <NEW_LINE> self.input = input or '' <NEW_LINE> self.end_time = now() <NEW_LINE> self.save() <NEW_LINE> case.current_screen = None <NEW_LINE> case.save()
A record of each screen that was visited during the call, and the operator's input.
62599051dc8b845886d54a87
class GetConfig(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.conf=configparser.ConfigParser() <NEW_LINE> self.conf.read('./Config.ini', encoding='UTF-8') <NEW_LINE> <DEDENT> @LazyProperty <NEW_LINE> def crawl_isdownload(self): <NEW_LINE> <INDENT> return self.conf.get('crawl','isDownloadFile') <NEW_LINE> <DEDENT> @LazyProperty <NEW_LINE> def crawl_iscrackcode(self): <NEW_LINE> <INDENT> return self.conf.get('crawl', 'isCrackCode') <NEW_LINE> <DEDENT> @LazyProperty <NEW_LINE> def crawl_headers(self): <NEW_LINE> <INDENT> headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36', 'Host': 'kns.cnki.net', 'Connection': 'keep-alive', 'Cache-Control': 'max-age=0', } <NEW_LINE> return headers <NEW_LINE> <DEDENT> @LazyProperty <NEW_LINE> def crawl_isdetail(self): <NEW_LINE> <INDENT> return self.conf.get('crawl', 'isDetailPage') <NEW_LINE> <DEDENT> @LazyProperty <NEW_LINE> def crawl_stepWaitTime(self): <NEW_LINE> <INDENT> return int(self.conf.get('crawl', 'stepWaitTime')) <NEW_LINE> <DEDENT> @LazyProperty <NEW_LINE> def crawl_isDownLoadLink(self): <NEW_LINE> <INDENT> return int(self.conf.get('crawl', 'isDownLoadLink'))
to get config from config.ini
62599051cb5e8a47e493cbea
class CmdDumpSimap(gdb.Command): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(CmdDumpSimap, self).__init__("ovs_dump_simap", gdb.COMMAND_DATA) <NEW_LINE> <DEDENT> def invoke(self, arg, from_tty): <NEW_LINE> <INDENT> arg_list = gdb.string_to_argv(arg) <NEW_LINE> if len(arg_list) != 1: <NEW_LINE> <INDENT> print("ERROR: Missing argument!\n") <NEW_LINE> print(self.__doc__) <NEW_LINE> return <NEW_LINE> <DEDENT> simap = gdb.parse_and_eval(arg_list[0]).cast( gdb.lookup_type('struct simap').pointer()) <NEW_LINE> values = dict() <NEW_LINE> max_name_len = 0 <NEW_LINE> for name, value in ForEachSIMAP(simap.dereference()): <NEW_LINE> <INDENT> values[name.string()] = long(value) <NEW_LINE> if len(name.string()) > max_name_len: <NEW_LINE> <INDENT> max_name_len = len(name.string()) <NEW_LINE> <DEDENT> <DEDENT> for name in sorted(values.iterkeys()): <NEW_LINE> <INDENT> print("{}: {} / 0x{:x}".format(name.ljust(max_name_len), values[name], values[name]))
Dump all key, value entries of a simap Usage: ovs_dump_simap <struct simap *>
62599051baa26c4b54d50773
class Client(object): <NEW_LINE> <INDENT> def __init__(self, key, trk_host=KISSmetrics.TRACKING_HOSTNAME, trk_scheme=KISSmetrics.TRACKING_SCHEME): <NEW_LINE> <INDENT> self.key = key <NEW_LINE> if trk_scheme not in ('http', 'https'): <NEW_LINE> <INDENT> raise ValueError('trk_scheme must be one of (http, https)') <NEW_LINE> <DEDENT> self.http = PoolManager() <NEW_LINE> self.trk_host = trk_host <NEW_LINE> self.trk_scheme = trk_scheme <NEW_LINE> <DEDENT> def record(self, person, event, properties=None, timestamp=None, path=KISSmetrics.RECORD_PATH): <NEW_LINE> <INDENT> this_request = request.record(self.key, person, event, timestamp=timestamp, properties=properties, scheme=self.trk_scheme, host=self.trk_host, path=path) <NEW_LINE> return self._request(this_request) <NEW_LINE> <DEDENT> def set(self, person, properties=None, timestamp=None, path=KISSmetrics.SET_PATH): <NEW_LINE> <INDENT> this_request = request.set(self.key, person, timestamp=timestamp, properties=properties, scheme=self.trk_scheme, host=self.trk_host, path=path) <NEW_LINE> return self._request(this_request) <NEW_LINE> <DEDENT> def alias(self, person, identity, path=KISSmetrics.ALIAS_PATH): <NEW_LINE> <INDENT> this_request = request.alias(self.key, person, identity, scheme=self.trk_scheme, host=self.trk_host, path=path) <NEW_LINE> return self._request(this_request) <NEW_LINE> <DEDENT> def _request(self, uri, method='GET'): <NEW_LINE> <INDENT> return self.http.request(method, uri)
Interface to KISSmetrics tracking service
6259905107d97122c421816e
class IndexSet(object): <NEW_LINE> <INDENT> def __init__(self, impl): <NEW_LINE> <INDENT> self._impl = impl <NEW_LINE> <DEDENT> def entity_index(self, entity): <NEW_LINE> <INDENT> return self._impl.entity_index(entity._impl) <NEW_LINE> <DEDENT> def sub_entity_index(self, element, i, codim): <NEW_LINE> <INDENT> if element.codimension != 0: <NEW_LINE> <INDENT> return ValueError("`Element` must be an entity of codimension0.") <NEW_LINE> <DEDENT> return self._impl.sub_entity_index(element._impl, i, codim)
Query the index set of a grid view.
62599051b5575c28eb71372e
class WhoisBr(WhoisEntry): <NEW_LINE> <INDENT> regex = { 'domain': 'domain:\s*(.+)\n', 'owner': 'owner:\s*([\S ]+)', 'ownerid': 'ownerid:\s*(.+)', 'country': 'country:\s*(.+)', 'owner_c': 'owner-c:\s*(.+)', 'admin_c': 'admin-c:\s*(.+)', 'tech_c': 'tech-c:\s*(.+)', 'billing_c': 'billing-c:\s*(.+)', 'nserver': 'nserver:\s*(.+)', 'nsstat': 'nsstat:\s*(.+)', 'nslastaa': 'nslastaa:\s*(.+)', 'saci': 'saci:\s*(.+)', 'created': 'created:\s*(.+)', 'expires': 'expires:\s*(.+)', 'changed': 'changed:\s*(.+)', 'status': 'status:\s*(.+)', 'nic_hdl_br': 'nic-hdl-br:\s*(.+)', 'person': 'person:\s*([\S ]+)', 'email': 'e-mail:\s*(.+)', } <NEW_LINE> def __init__(self, domain, text): <NEW_LINE> <INDENT> if 'Not found:' in text: <NEW_LINE> <INDENT> raise PywhoisError(text) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> WhoisEntry.__init__(self, domain, text, self.regex)
Whois parser for .br domains
625990518e71fb1e983bcf8f
class OneOf(Validator): <NEW_LINE> <INDENT> def __init__(self, iterable): <NEW_LINE> <INDENT> self.iterable = iterable <NEW_LINE> self.values_text = ', '.join(str(each) for each in self.iterable) <NEW_LINE> <DEDENT> def _repr_args(self): <NEW_LINE> <INDENT> return 'iterable={0!r}'.format(self.iterable) <NEW_LINE> <DEDENT> def _format_error(self, value): <NEW_LINE> <INDENT> return "Invalid input {input}, While Expected {values}'".format( input=value, values=self.values_text, ) <NEW_LINE> <DEDENT> def __call__(self, value): <NEW_LINE> <INDENT> if value not in self.iterable: <NEW_LINE> <INDENT> raise ValidationOneOfError(self._format_error(value)) <NEW_LINE> <DEDENT> return value
Validator which if ``value`` is a member of ``iterable``. :param iterable iterable: A sequence of invalid values.
62599051287bf620b62730b4
class SentiSynsetTools(object): <NEW_LINE> <INDENT> def load_senti_synsets_for_word(self, word): <NEW_LINE> <INDENT> return list(swn.senti_synsets('slow')) <NEW_LINE> <DEDENT> def get_scores_from_senti_synset(self, string_name_of_synset, return_format=tuple): <NEW_LINE> <INDENT> breakdown = swn.senti_synset(string_name_of_synset) <NEW_LINE> if return_format is tuple: <NEW_LINE> <INDENT> return (breakdown.pos_score(), breakdown.neg_score(), breakdown.obj_score()) <NEW_LINE> <DEDENT> elif return_format is dict: <NEW_LINE> <INDENT> return { 'posScore': breakdown.pos_score(), 'negScore': breakdown.neg_score(), 'objScore': breakdown.obj_score() }
Tools for loading and working with SentiWordNet stuff
62599051d53ae8145f919926
class ConstrainedLayer(nn.Module): <NEW_LINE> <INDENT> def __init__(self, module, equalized=True, lr_mul=1.0, init_bias_to_zero=True): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.module = module <NEW_LINE> self.equalized = equalized <NEW_LINE> if init_bias_to_zero and self.module.bias is not None: <NEW_LINE> <INDENT> self.module.bias.data.fill_(0) <NEW_LINE> <DEDENT> if self.equalized: <NEW_LINE> <INDENT> self.module.weight.data.normal_(0, 1) <NEW_LINE> self.module.weight.data /= lr_mul <NEW_LINE> self.scale = getLayerNormalizationFactor(self.module) * lr_mul <NEW_LINE> <DEDENT> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> x = self.module(x) <NEW_LINE> if self.equalized: <NEW_LINE> <INDENT> x *= self.scale <NEW_LINE> <DEDENT> return x <NEW_LINE> <DEDENT> @property <NEW_LINE> def bias(self): <NEW_LINE> <INDENT> return self.module.bias <NEW_LINE> <DEDENT> @property <NEW_LINE> def out_channels(self): <NEW_LINE> <INDENT> return self.module.out_channels <NEW_LINE> <DEDENT> @property <NEW_LINE> def in_channels(self): <NEW_LINE> <INDENT> return self.module.in_channels <NEW_LINE> <DEDENT> @property <NEW_LINE> def out_features(self): <NEW_LINE> <INDENT> return self.module.out_features <NEW_LINE> <DEDENT> @property <NEW_LINE> def in_features(self): <NEW_LINE> <INDENT> return self.module.in_features <NEW_LINE> <DEDENT> @property <NEW_LINE> def kernel_size(self): <NEW_LINE> <INDENT> return self.module.kernel_size <NEW_LINE> <DEDENT> @property <NEW_LINE> def weight(self): <NEW_LINE> <INDENT> return self.module.weight
A handy refactor that allows the user to: - initialize one layer's bias to zero - apply He's initialization at runtime
6259905191af0d3eaad3b2ee
class JVM(Subsystem): <NEW_LINE> <INDENT> options_scope = 'jvm' <NEW_LINE> @classmethod <NEW_LINE> def register_options(cls, register): <NEW_LINE> <INDENT> super(JVM, cls).register_options(register) <NEW_LINE> register('--options', action='append', metavar='<option>...', help='Run with these extra JVM options.') <NEW_LINE> register('--program-args', action='append', metavar='<arg>...', help='Run with these extra program args.') <NEW_LINE> register('--debug', action='store_true', help='Run the JVM with remote debugging.') <NEW_LINE> register('--debug-port', advanced=True, type=int, default=5005, help='The JVM will listen for a debugger on this port.') <NEW_LINE> register('--debug-args', advanced=True, type=list_option, default=[ '-Xdebug', '-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address={debug_port}' ], help='The JVM remote-debugging arguments. {debug_port} will be replaced with ' 'the value of the --debug-port option.') <NEW_LINE> <DEDENT> def get_jvm_options(self): <NEW_LINE> <INDENT> ret = [] <NEW_LINE> for opt in self.get_options().options: <NEW_LINE> <INDENT> ret.extend(safe_shlex_split(opt)) <NEW_LINE> <DEDENT> if (self.get_options().debug or self.get_options().is_flagged('debug_port') or self.get_options().is_flagged('debug_args')): <NEW_LINE> <INDENT> debug_port = self.get_options().debug_port <NEW_LINE> ret.extend(arg.format(debug_port=debug_port) for arg in self.get_options().debug_args) <NEW_LINE> <DEDENT> return ret <NEW_LINE> <DEDENT> def get_program_args(self): <NEW_LINE> <INDENT> ret = [] <NEW_LINE> for arg in self.get_options().program_args: <NEW_LINE> <INDENT> ret.extend(safe_shlex_split(arg)) <NEW_LINE> <DEDENT> return ret
A JVM invocation.
625990512ae34c7f260ac5ab
class ConfigureDialog(QtGui.QDialog): <NEW_LINE> <INDENT> def __init__(self, parent=None): <NEW_LINE> <INDENT> QtGui.QDialog.__init__(self, parent) <NEW_LINE> self._ui = Ui_ConfigureDialog() <NEW_LINE> self._ui.setupUi(self) <NEW_LINE> self._previousIdentifier = '' <NEW_LINE> self.identifierOccursCount = None <NEW_LINE> self._makeConnections() <NEW_LINE> <DEDENT> def _makeConnections(self): <NEW_LINE> <INDENT> self._ui.lineEdit0.textChanged.connect(self.validate) <NEW_LINE> <DEDENT> def accept(self): <NEW_LINE> <INDENT> result = QtGui.QMessageBox.Yes <NEW_LINE> if not self.validate(): <NEW_LINE> <INDENT> result = QtGui.QMessageBox.warning(self, 'Invalid Configuration', 'This configuration is invalid. Unpredictable behaviour may result if you choose \'Yes\', are you sure you want to save this configuration?)', QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No) <NEW_LINE> <DEDENT> if result == QtGui.QMessageBox.Yes: <NEW_LINE> <INDENT> QtGui.QDialog.accept(self) <NEW_LINE> <DEDENT> <DEDENT> def validate(self): <NEW_LINE> <INDENT> value = self.identifierOccursCount(self._ui.lineEdit0.text()) <NEW_LINE> valid = (value == 0) or (value == 1 and self._previousIdentifier == self._ui.lineEdit0.text()) <NEW_LINE> if valid: <NEW_LINE> <INDENT> self._ui.lineEdit0.setStyleSheet(DEFAULT_STYLE_SHEET) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._ui.lineEdit0.setStyleSheet(INVALID_STYLE_SHEET) <NEW_LINE> <DEDENT> return valid <NEW_LINE> <DEDENT> def getConfig(self): <NEW_LINE> <INDENT> self._previousIdentifier = self._ui.lineEdit0.text() <NEW_LINE> config = {} <NEW_LINE> config['identifier'] = self._ui.lineEdit0.text() <NEW_LINE> config['file_chooser_count'] = self._ui.spinBoxFileChoosers.value() <NEW_LINE> config['directory_chooser_count'] = self._ui.spinBoxDirectoryChoosers.value() <NEW_LINE> return config <NEW_LINE> <DEDENT> def setConfig(self, config): <NEW_LINE> <INDENT> self._previousIdentifier = config['identifier'] <NEW_LINE> self._ui.lineEdit0.setText(config['identifier']) <NEW_LINE> self._ui.spinBoxDirectoryChoosers.setValue(config['directory_chooser_count']) <NEW_LINE> self._ui.spinBoxFileChoosers.setValue(config['file_chooser_count'])
Configure dialog to present the user with the options to configure this step.
62599051a219f33f346c7ccb
class Target(ConfigSerializable): <NEW_LINE> <INDENT> type = None <NEW_LINE> value = None
Target Config.
62599051dc8b845886d54a89
class c_double(ctypes.c_double, _ConvertMixin, _CompareMixin, _NumberMixin, _StringMixin): <NEW_LINE> <INDENT> pass
Ctypes wrapper with additional functionality
62599051a8ecb033258726dd
class FieldMeta( namedtuple( "FieldMeta", ( "id", "module", "sign", "type", "label", "is_sys", "see_permission", "edit_permission", "is_required", "is_lock", "is_show_edit", "sort_id", ), ) ): <NEW_LINE> <INDENT> fields = ( "#id", "module", "sign", "type", "field_str", "is_sys", "see_permission", "edit_permission", "is_required", "lock", "edit_is_show", "sort_id", ) <NEW_LINE> def __new__(cls, *args, **kwargs): <NEW_LINE> <INDENT> raw = super(FieldMeta, cls).__new__(cls, *args, **kwargs) <NEW_LINE> new_kwargs = raw._asdict() <NEW_LINE> _format_yn_str_in_dict(new_kwargs) <NEW_LINE> return super(FieldMeta, cls).__new__(cls, **new_kwargs)
Field information.
625990518e71fb1e983bcf90
class Visitor(object): <NEW_LINE> <INDENT> log = None <NEW_LINE> def default(self, node, *args): <NEW_LINE> <INDENT> for child in node.getChildNodes(): <NEW_LINE> <INDENT> self.visit(child, *args)
This class implements a Visitor pattern. It has to be used with compiler.walk usage: result = compiler.walk(ast, Visitor()).result
6259905176d4e153a661dcde
class BranchGenerator: <NEW_LINE> <INDENT> def __init__(self, instr, op, python_op=None): <NEW_LINE> <INDENT> self.instr = instr <NEW_LINE> self.op = op <NEW_LINE> self.python_op = python_op <NEW_LINE> <DEDENT> def generate(self, code, srcs, true_label, negate): <NEW_LINE> <INDENT> if all(isinstance(src, Constant) for src in srcs) and self.python_op: <NEW_LINE> <INDENT> values = [src.value for src in srcs] <NEW_LINE> result = (self.python_op)(*values) <NEW_LINE> if result != negate: <NEW_LINE> <INDENT> code.append('jmp.%s;', true_label) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> instr = self.instr <NEW_LINE> negate_instr = branchInstrs[negateOp[self.op]] <NEW_LINE> if len(srcs) == 1: <NEW_LINE> <INDENT> code.append('%s.%s.%s;', negate_instr if negate else instr, srcs[0], true_label) <NEW_LINE> return <NEW_LINE> <DEDENT> elif len(srcs) != 2: <NEW_LINE> <INDENT> raise CompInternalError(self.instr) <NEW_LINE> <DEDENT> arglist = instructions[self.instr] <NEW_LINE> combo, swap_needed = arglist.find_combo(srcs + [true_label], (0, 1)) <NEW_LINE> if not combo: <NEW_LINE> <INDENT> raise CompInternalError('No %s in %s %s', srcs, self.instr, arglist) <NEW_LINE> <DEDENT> regs = list(srcs) <NEW_LINE> if negate: <NEW_LINE> <INDENT> instr = negate_instr <NEW_LINE> <DEDENT> if swap_needed: <NEW_LINE> <INDENT> regs[0], regs[1] = regs[1], regs[0] <NEW_LINE> instr = branchInstrs[argSwitchOp[branchInstrOps[instr]]] <NEW_LINE> <DEDENT> code.append('%s.%s.%s.%s;', instr, regs[0], regs[1], true_label) <NEW_LINE> <DEDENT> def evaluate(self, srcs): <NEW_LINE> <INDENT> return (self.python_op)(*srcs)
Generator for all branch ops.
62599051435de62698e9d2ca
class User(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'users' <NEW_LINE> id = db.Column(db.Integer, primary_key = True ) <NEW_LINE> username = db.Column(db.String(64), unique = True, index=True ) <NEW_LINE> role_id = db.Column(db.Integer, db.ForeignKey( 'roles.id' ) ) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return '<User %r>' % self.username
database table class User
62599051462c4b4f79dbcecb
class py34FileType(object): <NEW_LINE> <INDENT> def __init__(self, mode='r', bufsize=-1, encoding=None, errors=None): <NEW_LINE> <INDENT> self._mode = mode <NEW_LINE> self._bufsize = bufsize <NEW_LINE> self._encoding = encoding <NEW_LINE> self._errors = errors <NEW_LINE> <DEDENT> def __call__(self, string): <NEW_LINE> <INDENT> if string == '-': <NEW_LINE> <INDENT> if 'r' in self._mode: <NEW_LINE> <INDENT> return _sys.stdin <NEW_LINE> <DEDENT> elif 'w' in self._mode: <NEW_LINE> <INDENT> return _sys.stdout <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> msg = _('argument "-" with mode %r') % self._mode <NEW_LINE> raise ValueError(msg) <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> return open(string, self._mode, self._bufsize, self._encoding, self._errors) <NEW_LINE> <DEDENT> except OSError as e: <NEW_LINE> <INDENT> message = _("can't open '%s': %s") <NEW_LINE> raise ArgumentTypeError(message % (string, e)) <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> args = self._mode, self._bufsize <NEW_LINE> kwargs = [('encoding', self._encoding), ('errors', self._errors)] <NEW_LINE> args_str = ', '.join([repr(arg) for arg in args if arg != -1] + ['%s=%r' % (kw, arg) for kw, arg in kwargs if arg is not None]) <NEW_LINE> return '%s(%s)' % (type(self).__name__, args_str)
Factory for creating file object types Instances of FileType are typically passed as type= arguments to the ArgumentParser add_argument() method. Keyword Arguments: - mode -- A string indicating how the file is to be opened. Accepts the same values as the builtin open() function. - bufsize -- The file's desired buffer size. Accepts the same values as the builtin open() function. - encoding -- The file's encoding. Accepts the same values as the builtin open() function. - errors -- A string indicating how encoding and decoding errors are to be handled. Accepts the same value as the builtin open() function.
6259905123e79379d538d9c2
class DiffBotRequest(models.Model): <NEW_LINE> <INDENT> type = models.CharField(max_length=100) <NEW_LINE> created = models.DateTimeField(auto_now_add=True) <NEW_LINE> attempted = models.DateTimeField(blank=True, null=True) <NEW_LINE> completed = models.DateTimeField(blank=True, null=True) <NEW_LINE> parameters = ListField(default=['']) <NEW_LINE> response = models.TextField(blank=True, null=True)
A job for the DiffBot!
6259905163b5f9789fe8663a
class FileChooserListView(FileChooserController): <NEW_LINE> <INDENT> _ENTRY_TEMPLATE = 'FileListEntry'
Implementation of :class:`FileChooserController` using a list view.
62599051dd821e528d6da3a7
class RestoredTrainer(TensorFlowTrainer): <NEW_LINE> <INDENT> def __init__(self, loss, global_step, trainer): <NEW_LINE> <INDENT> self.global_step = global_step <NEW_LINE> self.loss = loss <NEW_LINE> self.trainer = trainer
Trainer class that takes already existing graph.
6259905163d6d428bbee3c99
class TestTestValidateQuery(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testTestValidateQuery(self): <NEW_LINE> <INDENT> pass
TestValidateQuery unit test stubs
62599051dc8b845886d54a8b
class ModifySnapshotByTimeOffsetTemplateRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Definition = None <NEW_LINE> self.Name = None <NEW_LINE> self.Width = None <NEW_LINE> self.Height = None <NEW_LINE> self.ResolutionAdaptive = None <NEW_LINE> self.Format = None <NEW_LINE> self.Comment = None <NEW_LINE> self.SubAppId = None <NEW_LINE> self.FillType = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Definition = params.get("Definition") <NEW_LINE> self.Name = params.get("Name") <NEW_LINE> self.Width = params.get("Width") <NEW_LINE> self.Height = params.get("Height") <NEW_LINE> self.ResolutionAdaptive = params.get("ResolutionAdaptive") <NEW_LINE> self.Format = params.get("Format") <NEW_LINE> self.Comment = params.get("Comment") <NEW_LINE> self.SubAppId = params.get("SubAppId") <NEW_LINE> self.FillType = params.get("FillType")
ModifySnapshotByTimeOffsetTemplate请求参数结构体
625990513539df3088ecd76e
class ComputePixelToDistortedPixelTestCase(BaseTestCase): <NEW_LINE> <INDENT> def testNoDistortion(self): <NEW_LINE> <INDENT> focalPlaneToFieldAngle = self.makeAffineTransform(scale=self.radPerMm) <NEW_LINE> pixelToDistortedPixel = computePixelToDistortedPixel( pixelToFocalPlane=self.pixelToFocalPlane, focalPlaneToFieldAngle=focalPlaneToFieldAngle, ) <NEW_LINE> bboxD = lsst.geom.Box2D(self.bbox) <NEW_LINE> pixelPoints = bboxD.getCorners() <NEW_LINE> pixelPoints.append(bboxD.getCenter()) <NEW_LINE> assert_allclose(pixelToDistortedPixel.applyForward(pixelPoints), pixelPoints) <NEW_LINE> assert_allclose(pixelToDistortedPixel.applyInverse(pixelPoints), pixelPoints) <NEW_LINE> <DEDENT> def testDistortion(self): <NEW_LINE> <INDENT> focalPlaneToFieldAngle = afwGeom.makeRadialTransform([0.0, self.radPerMm, 0.0, self.radPerMm]) <NEW_LINE> pixelToDistortedPixel = computePixelToDistortedPixel( pixelToFocalPlane=self.pixelToFocalPlane, focalPlaneToFieldAngle=focalPlaneToFieldAngle, ) <NEW_LINE> tanWcsTransform = afwGeom.TransformPoint2ToSpherePoint(self.tanWcs.getFrameDict()) <NEW_LINE> pixelToDistortedSky = pixelToDistortedPixel.then(tanWcsTransform) <NEW_LINE> wcs = makeDistortedTanWcs( tanWcs=self.tanWcs, pixelToFocalPlane=self.pixelToFocalPlane, focalPlaneToFieldAngle=focalPlaneToFieldAngle, ) <NEW_LINE> bboxD = lsst.geom.Box2D(self.bbox) <NEW_LINE> pixelPoints = bboxD.getCorners() <NEW_LINE> pixelPoints.append(bboxD.getCenter()) <NEW_LINE> skyPoints1 = pixelToDistortedSky.applyForward(pixelPoints) <NEW_LINE> skyPoints2 = wcs.pixelToSky(pixelPoints) <NEW_LINE> self.assertSpherePointListsAlmostEqual(skyPoints1, skyPoints2) <NEW_LINE> pixelPoints1 = pixelToDistortedSky.applyInverse(skyPoints1) <NEW_LINE> pixelPoints2 = wcs.skyToPixel(skyPoints1) <NEW_LINE> assert_allclose(pixelPoints1, pixelPoints2)
Test lsst.afw.geom.computePixelToDistortedPixel
625990518da39b475be046b3
class Vocabulary(Tokenizer): <NEW_LINE> <INDENT> def __init__(self, text): <NEW_LINE> <INDENT> print('Start init Vocabulary.__init__()') <NEW_LINE> super().__init__(text) <NEW_LINE> self.vocab = set(self.tokens) <NEW_LINE> print('End init Vocabulary.__init__()')
Find unique words in text
62599051b7558d589546498e
@attr.s <NEW_LINE> class ThrottleDecorator: <NEW_LINE> <INDENT> throttle: _throttle.Throttle = attr.ib() <NEW_LINE> def _check(self, key: str) -> result.RateLimitResult: <NEW_LINE> <INDENT> result = self.throttle.check(key=key, quantity=1) <NEW_LINE> if result.limited: <NEW_LINE> <INDENT> raise ThrottleExceeded("Rate-limit exceeded", result=result) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def __call__(self, func: typing.Callable) -> typing.Callable: <NEW_LINE> <INDENT> key = func.__name__ <NEW_LINE> if inspect.iscoroutinefunction(func): <NEW_LINE> <INDENT> @functools.wraps(func) <NEW_LINE> async def wrapper(*args, **kwargs) -> typing.Callable: <NEW_LINE> <INDENT> self._check(key=key) <NEW_LINE> return await func(*args, **kwargs) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> @functools.wraps(func) <NEW_LINE> def wrapper(*args, **kwargs) -> typing.Callable: <NEW_LINE> <INDENT> self._check(key=key) <NEW_LINE> return func(*args, **kwargs) <NEW_LINE> <DEDENT> <DEDENT> return wrapper <NEW_LINE> <DEDENT> def sleep_and_retry(self, func: typing.Callable) -> typing.Callable: <NEW_LINE> <INDENT> throttled_func = self(func) <NEW_LINE> if inspect.iscoroutinefunction(func): <NEW_LINE> <INDENT> @functools.wraps(func) <NEW_LINE> async def wrapper(*args, **kwargs) -> typing.Callable: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return await throttled_func(*args, **kwargs) <NEW_LINE> <DEDENT> except ThrottleExceeded as e: <NEW_LINE> <INDENT> await asyncio.sleep( e.result.retry_after.total_seconds() ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> @functools.wraps(func) <NEW_LINE> def wrapper(*args, **kwargs) -> typing.Callable: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return throttled_func(*args, **kwargs) <NEW_LINE> <DEDENT> except ThrottleExceeded as e: <NEW_LINE> <INDENT> time.sleep(e.result.retry_after.total_seconds()) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return wrapper
The class that acts as a decorator used to throttle function calls. This class requires an intantiated throttle with which to limit function invocations. .. attribute:: throttle The :class:`~rush.throttle.Throttle` which should be used to limit decorated functions.
6259905130dc7b76659a0ce3
class RebaseHelperError(Exception): <NEW_LINE> <INDENT> pass
Class representing Error raised inside rebase-helper after intentionally catching some expected and well known exception/error.
6259905124f1403a92686334