code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class UpdatedException(Exception): <NEW_LINE> <INDENT> def __init__(self, data): <NEW_LINE> <INDENT> Exception.__init__(self) <NEW_LINE> self.data = data | Base exception with additional payload | 62599052d7e4931a7ef3d556 |
class InfiniteSliceSource(_MethodOfImagesSourceBase): <NEW_LINE> <INDENT> def __init__(self, y, sigma, h, brain_conductivity, saline_conductivity, glass_conductivity=0, n=20, x=0, z=0, SourceClass=CartesianGaussianSourceKCSD3D, mask_invalid_space=True): <NEW_LINE> <INDENT> super(InfiniteSliceSource, self).__init__(mask_invalid_space) <NEW_LINE> self.x = x <NEW_LINE> self.y = y <NEW_LINE> self.z = z <NEW_LINE> self.h = h <NEW_LINE> wtg = float(brain_conductivity - glass_conductivity) / (brain_conductivity + glass_conductivity) <NEW_LINE> wts = float(brain_conductivity - saline_conductivity) / (brain_conductivity + saline_conductivity) <NEW_LINE> self.n = n <NEW_LINE> self._source = SourceClass( self.SourceConfig(x, y, z, sigma, brain_conductivity)) <NEW_LINE> weights = [1] <NEW_LINE> sources = [self._source] <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> weights.append(wtg**i * wts**(i+1)) <NEW_LINE> sources.append(SourceClass( self.SourceConfig(x, 2 * (i+1) * h - y, z, sigma, brain_conductivity))) <NEW_LINE> weights.append(wtg**(i+1) * wts**i) <NEW_LINE> sources.append(SourceClass( self.SourceConfig(x, -2 * i * h - y, z, sigma, brain_conductivity))) <NEW_LINE> <DEDENT> for i in range(1, n + 1): <NEW_LINE> <INDENT> weights.append((wtg * wts)**i) <NEW_LINE> weights.append((wtg * wts)**i) <NEW_LINE> sources.append(SourceClass( self.SourceConfig(x, y + 2 * i * h, z, sigma, brain_conductivity))) <NEW_LINE> sources.append(SourceClass( self.SourceConfig(x, y - 2 * i * h, z, sigma, brain_conductivity))) <NEW_LINE> <DEDENT> self._positive = [(w, s) for w, s in zip(weights, sources) if w > 0] <NEW_LINE> self._positive.sort(key=operator.itemgetter(0), reverse=False) <NEW_LINE> self._negative = [(w, s) for w, s in zip(weights, sources) if w < 0] <NEW_LINE> self._negative.sort(key=operator.itemgetter(0), reverse=True) <NEW_LINE> <DEDENT> def is_applicable(self, X, Y, Z): <NEW_LINE> <INDENT> return (Y >= 0) & (Y < self.h) <NEW_LINE> <DEDENT> def _calculate_field(self, name, *args, **kwargs): <NEW_LINE> <INDENT> return (sum(w * getattr(s, name)(*args, **kwargs) for w, s in self._positive) + sum(w * getattr(s, name)(*args, **kwargs) for w, s in self._negative)) | Torbjorn V. Ness (2015) | 62599052d6c5a102081e35f6 |
class GameConfigMessage(ServerMessage): <NEW_LINE> <INDENT> prefix = "C" <NEW_LINE> message_type = "game config" <NEW_LINE> min_part_count = 5 <NEW_LINE> custom_settings = list() <NEW_LINE> def __init__(self, message, socket_manager): <NEW_LINE> <INDENT> super(GameConfigMessage, self).__init__(self.prefix, self.message_type, self.min_part_count, message) <NEW_LINE> self.server_version = self.get_part(1) <NEW_LINE> self.game_title = self.get_part(2) <NEW_LINE> self.map_width = int(self.get_part(3)) <NEW_LINE> self.map_height = int(self.get_part(4)) <NEW_LINE> self.settings_count = int(self.get_part(5)) <NEW_LINE> for _ in range(self.settings_count): <NEW_LINE> <INDENT> self.custom_settings.append(GameSettingMessage(socket_manager.receive_message())) | Messages for custom game settings | 62599052004d5f362081fa58 |
class LocalWorker(multiprocessing.Process, LoggingMixin): <NEW_LINE> <INDENT> def __init__(self, result_queue): <NEW_LINE> <INDENT> super(LocalWorker, self).__init__() <NEW_LINE> self.daemon = True <NEW_LINE> self.result_queue = result_queue <NEW_LINE> self.key = None <NEW_LINE> self.command = None <NEW_LINE> <DEDENT> def execute_work(self, key, command): <NEW_LINE> <INDENT> if key is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.log.info("%s running %s", self.__class__.__name__, command) <NEW_LINE> try: <NEW_LINE> <INDENT> subprocess.check_call(command, close_fds=True) <NEW_LINE> state = State.SUCCESS <NEW_LINE> <DEDENT> except subprocess.CalledProcessError as e: <NEW_LINE> <INDENT> state = State.FAILED <NEW_LINE> self.log.error("Failed to execute task %s.", str(e)) <NEW_LINE> <DEDENT> self.result_queue.put((key, state)) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.execute_work(self.key, self.command) <NEW_LINE> time.sleep(1) | LocalWorker Process implementation to run airflow commands. Executes the given
command and puts the result into a result queue when done, terminating execution. | 62599052cad5886f8bdc5aed |
class Classifier(object): <NEW_LINE> <INDENT> trained = False <NEW_LINE> def train(self, X_train, Y_train): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def evaluate(self, X_test, Y_test): <NEW_LINE> <INDENT> pass | Common interface for all IDS classifiers | 625990528da39b475be046c4 |
class WaitAgentsStarted(BaseCondition): <NEW_LINE> <INDENT> def __init__(self, timeout=1200): <NEW_LINE> <INDENT> super(WaitAgentsStarted, self).__init__(timeout) <NEW_LINE> <DEDENT> def iter_blocking_state(self, status): <NEW_LINE> <INDENT> states = Status.check_agents_started(status) <NEW_LINE> if states is not None: <NEW_LINE> <INDENT> for state, item in states.items(): <NEW_LINE> <INDENT> yield item[0], state <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def do_raise(self, model_name, status): <NEW_LINE> <INDENT> raise AgentsNotStarted(model_name, status) | Wait until all agents are idle or started. | 6259905207d97122c4218182 |
class VisualPerceptionType (pyxb.binding.datatypes.string, pyxb.binding.basis.enumeration_mixin): <NEW_LINE> <INDENT> _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'VisualPerceptionType') <NEW_LINE> _XSDLocation = pyxb.utils.utility.Location('http://ddex.net/xml/20100121/ddex.xsd', 1841, 4) <NEW_LINE> _Documentation = 'A Type of MusicalCreation according to how it is experienced in an AudioVisual Creation.' | A Type of MusicalCreation according to how it is experienced in an AudioVisual Creation. | 625990523617ad0b5ee0761f |
class ItemDetailSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> category = CategoryListSerializer() <NEW_LINE> stock = StockListSerializer() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Item <NEW_LINE> fields = ['id', 'name', 'price', 'category', 'description', 'image_url', 'comments_total', 'average_rate', 'store', 'quantity', 'running_out_level', 'running_out', 'stock'] | Detail Item
Get by id | 6259905207f4c71912bb0912 |
class ProductionConfig(Config): <NEW_LINE> <INDENT> DATABASE_URL = os.getenv('PROD_DATABASE_URL') <NEW_LINE> DEBUG = False <NEW_LINE> TESTING = False | Configurations for Production. | 625990527cff6e4e811b6f1a |
class Organizer(models.Model): <NEW_LINE> <INDENT> image = models.ImageField(blank=True, null=True, upload_to="media/people/%Y/") <NEW_LINE> order = models.IntegerField(default=0) <NEW_LINE> name = models.CharField(max_length=50) <NEW_LINE> role = models.CharField(max_length=20) | Organizers for the about page. | 6259905223e79379d538d9d4 |
class Response(ReqRep): <NEW_LINE> <INDENT> __slots__ = ('response', 'exception', 'reason', 'return_code') <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.response = kwargs.get('response', None) <NEW_LINE> self.exception = kwargs.get('exception', None) <NEW_LINE> self.reason = kwargs.get('reason', None) <NEW_LINE> self.return_code = kwargs.get('return_code', None) | Request response skeleton
response: Server response
exception: Exception occurred during request processing
reason: Reason of the exception
return_code: Like HTTP response code
:exception AttributeError if attribute not listing in __slots__
:exception NotImplementedError for __delattr__ and __delitem__ | 625990520fa83653e46f63bd |
class FakeInteract: <NEW_LINE> <INDENT> def __init__(self, answers): <NEW_LINE> <INDENT> self.answers = answers <NEW_LINE> <DEDENT> def find_answer(self, message, choices=None, default=None): <NEW_LINE> <INDENT> keys = self.answers.keys() <NEW_LINE> for key in keys: <NEW_LINE> <INDENT> if key in message.lower(): <NEW_LINE> <INDENT> if not choices: <NEW_LINE> <INDENT> return self.answers[key] <NEW_LINE> <DEDENT> answer = self.answers[key] <NEW_LINE> if answer in choices: <NEW_LINE> <INDENT> return answer <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mess = "Would answer %s\n" % answer <NEW_LINE> mess += "But choices are: %s\n" % choices <NEW_LINE> raise Exception(mess) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if default is not None: <NEW_LINE> <INDENT> return default <NEW_LINE> <DEDENT> mess = "Could not find answer for\n :: %s\n" % message <NEW_LINE> mess += "Known keys are: %s" % ", ".join(keys) <NEW_LINE> raise Exception(mess) <NEW_LINE> <DEDENT> def ask_choice(self, choices, message): <NEW_LINE> <INDENT> return self.find_answer(message, choices) <NEW_LINE> <DEDENT> def ask_yes_no(self, message, default=False): <NEW_LINE> <INDENT> return self.find_answer(message, default=default) <NEW_LINE> <DEDENT> def ask_path(self, message): <NEW_LINE> <INDENT> return self.find_answer(message) <NEW_LINE> <DEDENT> def ask_string(self, message): <NEW_LINE> <INDENT> return self.find_answer(message) <NEW_LINE> <DEDENT> def ask_program(self, message): <NEW_LINE> <INDENT> return self.find_answer(message) | A class to control qibuild.interact behavior
Answers must be a dict: message -> answer
message must be a part of the message
answer can be a boolean (for ask_yes_no), and string
(for ask_path or ask_string), or a string that must
match one of the choices, for (ask_choice)
Note that if you do not specify an answer for
ask_yes_no, the default will be used.
Any other non specifed answer will raise an exception | 625990524428ac0f6e659a12 |
class TestPFAOWS(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.start = B2BExport() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_start(self): <NEW_LINE> <INDENT> self.start.b2b_export_logic("PF", "PP_A_OW", "b2b", 2) | 测试case,平台采购+成人+单程直飞 | 625990524e696a045264e88f |
class TimestampMixin(object): <NEW_LINE> <INDENT> STATUSPOLICY = [ (StatusPolicy.NEW, _('Record has be created.')), (StatusPolicy.UPT, _('Record has be updated.')), (StatusPolicy.DEL, _('Record has be deleted.')), ] <NEW_LINE> status = db.Column( ChoiceType(STATUSPOLICY, impl=db.String(1)), nullable=False, default=StatusPolicy.NEW ) <NEW_LINE> created = db.Column(db.DateTime, nullable=False, default=datetime.now) <NEW_LINE> updated = db.Column(db.DateTime, nullable=False, default=datetime.now, onupdate=datetime.now) | Timestamp model mix-in with fractional seconds support.
SQLAlchemy-Utils timestamp model does not have support for
fractional seconds. | 6259905263d6d428bbee3cab |
class Fragment(object): <NEW_LINE> <INDENT> i = 0 <NEW_LINE> fragments = {} <NEW_LINE> def lookup(self, *commits): <NEW_LINE> <INDENT> name = self._name_for(*commits) <NEW_LINE> return self.topics.get(name) <NEW_LINE> <DEDENT> def register(self, *commits): <NEW_LINE> <INDENT> new = self._next() <NEW_LINE> self.assign(new, *commits) <NEW_LINE> return new <NEW_LINE> <DEDENT> def assign(self, topic, *commits): <NEW_LINE> <INDENT> name = self._name_for(*commits) <NEW_LINE> self.topics[name] = topic <NEW_LINE> <DEDENT> def _name_for(self, *commits): <NEW_LINE> <INDENT> return ' '.join(sorted(commits)) <NEW_LINE> <DEDENT> def _next(self): <NEW_LINE> <INDENT> self.i += 1 <NEW_LINE> return self.template % self.i | Tracks fragments of the git explosion, i.e. commits which
were exploded off the source branch into smaller topic branches. | 625990523539df3088ecd780 |
class Parameters(): <NEW_LINE> <INDENT> def __init__(self, network, max_length, tot_crit_tracks, stations_list): <NEW_LINE> <INDENT> self.network = network <NEW_LINE> self.max_length = max_length <NEW_LINE> self.tot_crit_tracks = tot_crit_tracks <NEW_LINE> self.stations_list = stations_list | Object saving all parameters for calculation | 6259905291af0d3eaad3b303 |
class _GetActName: <NEW_LINE> <INDENT> _re_actname1 = _re.compile(r'[))][((]') <NEW_LINE> _re_actname2 = _re.compile(r'[((、]') <NEW_LINE> def __call__(self, elems): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data = elems.find('.//h1').text.strip() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise _InvalidPage <NEW_LINE> <DEDENT> named = self._re_actname1.split(data) <NEW_LINE> if len(named) == 1: <NEW_LINE> <INDENT> named = re_inbracket.split(data) <NEW_LINE> <DEDENT> name = self._re_actname2.split(named[0]) <NEW_LINE> yomi = self._re_actname2.split(named[1].rstrip('))')) <NEW_LINE> self.current = name[0] <NEW_LINE> _verbose('name: {}, yomi: {}'.format(name, yomi)) <NEW_LINE> return name, yomi | 名前の取得 | 625990528da39b475be046c6 |
class LoginSchema(Schema): <NEW_LINE> <INDENT> email = fields.Email(load_only=True, required=True) <NEW_LINE> password = fields.String(load_only=True, required=True) | Serialized login schema. | 6259905282261d6c52730937 |
class UsosWebOAuth(BaseOAuth1): <NEW_LINE> <INDENT> name = 'usosweb' <NEW_LINE> EXTRA_DATA = [('id', 'id')] <NEW_LINE> AUTHORIZATION_URL = 'https://usosapps.uw.edu.pl/services/oauth/authorize' <NEW_LINE> REQUEST_TOKEN_URL = 'https://usosapps.uw.edu.pl/services/oauth/request_token' <NEW_LINE> ACCESS_TOKEN_URL = 'https://usosapps.uw.edu.pl/services/oauth/access_token' <NEW_LINE> def process_error(self, data): <NEW_LINE> <INDENT> if 'denied' in data: <NEW_LINE> <INDENT> raise AuthCanceled(self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> super(UsosWebOAuth, self).process_error(data) <NEW_LINE> <DEDENT> <DEDENT> def get_user_details(self, response): <NEW_LINE> <INDENT> fullname, first_name, last_name = self.get_user_names(first_name=response['first_name'], last_name=response['last_name']) <NEW_LINE> return {'username': fullname, 'email': '', 'fullname': fullname, 'first_name': first_name, 'last_name': last_name} <NEW_LINE> <DEDENT> def user_data(self, access_token, *args, **kwargs): <NEW_LINE> <INDENT> return self.get_json( 'https://usosapps.uw.edu.pl/services/users/user', auth=self.oauth_auth(access_token) ) | UsosWeb OAuth authentication backend | 6259905207d97122c4218184 |
class EmailCreateView(LoginRequiredMixin, NextMixin, FormMessageMixin, generic.CreateView): <NEW_LINE> <INDENT> template_name = 'baseform.html' <NEW_LINE> form_class = EmailAddressForm <NEW_LINE> default_next_url = reverse_lazy('kdo-profile-update') <NEW_LINE> form_valid_message = _("Your new email address has been created. " "You should receive an message soon with a link to " "verify the address belongs to you.") <NEW_LINE> def get_form_kwargs(self): <NEW_LINE> <INDENT> kwargs = super(EmailCreateView, self).get_form_kwargs() <NEW_LINE> kwargs['user'] = self.request.user <NEW_LINE> return kwargs <NEW_LINE> <DEDENT> def form_valid(self, form): <NEW_LINE> <INDENT> response = super(EmailCreateView, self).form_valid(form) <NEW_LINE> self.send_email(self.object) <NEW_LINE> return response <NEW_LINE> <DEDENT> def send_email(self, email_address): <NEW_LINE> <INDENT> template = EmailVerificationEmail() <NEW_LINE> message = template.render({'user': self.request.user, 'email': email_address, 'site': get_current_site(self.request)}) <NEW_LINE> return message.send() | Create an EmailAddress for the current user. | 625990523617ad0b5ee07621 |
class Save(models.Model): <NEW_LINE> <INDENT> user = models.ForeignKey(User, related_name="Save_user") <NEW_LINE> game = models.ForeignKey(Game, related_name="Save_game") <NEW_LINE> date = models.DateTimeField(auto_now_add=True) <NEW_LINE> score = models.IntegerField(null=False) <NEW_LINE> game_board = models.CharField(max_length=100, default='') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return "user: " + self.user.username + "___game: " + str(self.game.id) + "___score: " + str(self.score) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> unique_together = (('user', 'game'),) | Save table | 625990528e71fb1e983bcfa5 |
class Message(Interface): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def to_python(cls, data): <NEW_LINE> <INDENT> assert data.get('message') <NEW_LINE> kwargs = { 'message': trim(data['message'], 2048) } <NEW_LINE> if data.get('params'): <NEW_LINE> <INDENT> kwargs['params'] = trim(data['params'], 1024) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> kwargs['params'] = () <NEW_LINE> <DEDENT> return cls(**kwargs) <NEW_LINE> <DEDENT> def get_path(self): <NEW_LINE> <INDENT> return 'sentry.interfaces.Message' <NEW_LINE> <DEDENT> def get_hash(self): <NEW_LINE> <INDENT> return [self.message] | A standard message consisting of a ``message`` arg, and an optional
``params`` arg for formatting.
If your message cannot be parameterized, then the message interface
will serve no benefit.
- ``message`` must be no more than 1000 characters in length.
>>> {
>>> "message": "My raw message with interpreted strings like %s",
>>> "params": ["this"]
>>> } | 6259905230dc7b76659a0cec |
class TestLinalgSolve(unittest2.TestCase): <NEW_LINE> <INDENT> def test_array_array(self): <NEW_LINE> <INDENT> test_op = np.eye(2) <NEW_LINE> test_vec = np.arange(2) <NEW_LINE> np_tst.assert_allclose( atmos_flux_inversion.linalg.solve(test_op, test_vec), la.solve(test_op, test_vec)) <NEW_LINE> <DEDENT> def test_method_array(self): <NEW_LINE> <INDENT> test_op = ( atmos_flux_inversion.correlations.HomogeneousIsotropicCorrelation. from_array([1, .5, .25, .5])) <NEW_LINE> test_vec = np.arange(4) <NEW_LINE> np_tst.assert_allclose( atmos_flux_inversion.linalg.solve( test_op, test_vec), la.solve(test_op.dot(np.eye(4)), test_vec), atol=1e-10) <NEW_LINE> <DEDENT> def test_linop_array(self): <NEW_LINE> <INDENT> test_diag = np.ones(4) <NEW_LINE> test_op = ( LinearOperator( matvec=lambda x: x * test_diag, shape=(4, 4))) <NEW_LINE> test_vec = np.arange(4) <NEW_LINE> np_tst.assert_allclose( atmos_flux_inversion.linalg.solve(test_op, test_vec), test_vec / test_diag) <NEW_LINE> test_mat = np.eye(4) <NEW_LINE> np_tst.assert_allclose( atmos_flux_inversion.linalg.solve(test_op, test_mat), test_mat / test_diag[np.newaxis, :]) <NEW_LINE> <DEDENT> def test_array_linop(self): <NEW_LINE> <INDENT> test_diag = 1 + np.arange(4) <NEW_LINE> test_op = ( atmos_flux_inversion.linalg.DiagonalOperator( test_diag)) <NEW_LINE> test_arry = np.diag(test_diag) <NEW_LINE> result = atmos_flux_inversion.linalg.solve( test_arry, test_op) <NEW_LINE> self.assertIsInstance( result, LinearOperator) <NEW_LINE> np_tst.assert_allclose( result.dot(np.eye(4)), np.eye(4), atol=1e-10) <NEW_LINE> <DEDENT> def test_matop_matop(self): <NEW_LINE> <INDENT> test_op = MatrixLinearOperator( np.eye(4)) <NEW_LINE> test_vec = MatrixLinearOperator( np.arange(4).reshape(4, 1)) <NEW_LINE> np_tst.assert_allclose( atmos_flux_inversion.linalg.solve( test_op, test_vec), la.solve(test_op.A, test_vec.A)) <NEW_LINE> <DEDENT> def test_bad_shape(self): <NEW_LINE> <INDENT> test_op = np.eye(4) <NEW_LINE> test_vec = np.arange(5) <NEW_LINE> self.assertRaises( ValueError, atmos_flux_inversion.linalg.solve, test_op, test_vec) <NEW_LINE> self.assertRaises( la.LinAlgError, atmos_flux_inversion.linalg.solve, test_op[:, :-1], test_vec[:-1]) <NEW_LINE> <DEDENT> def test_solve_method_fails(self): <NEW_LINE> <INDENT> test_op = ( atmos_flux_inversion.correlations.HomogeneousIsotropicCorrelation. from_array([1, .5, .25, .125, .0625], is_cyclic=False)) <NEW_LINE> ident = np.eye(*test_op.shape) <NEW_LINE> test_mat = test_op.dot(ident) <NEW_LINE> for vec in ident: <NEW_LINE> <INDENT> with self.subTest(test_vec=vec): <NEW_LINE> <INDENT> np_tst.assert_allclose( atmos_flux_inversion.linalg.solve(test_op, vec), np_la.solve(test_mat, vec), atol=1e-10) | Test the general solve function. | 62599052379a373c97d9a500 |
class LongThrower(ThrowerAnt): <NEW_LINE> <INDENT> name = 'Long' <NEW_LINE> implemented = True <NEW_LINE> food_cost = 2 <NEW_LINE> armor = 1 <NEW_LINE> min_range = 5 <NEW_LINE> def nearest_bee(self, hive): <NEW_LINE> <INDENT> current_place = self.place <NEW_LINE> for i in range (0, self.min_range): <NEW_LINE> <INDENT> current_place = current_place.entrance <NEW_LINE> <DEDENT> while current_place != hive: <NEW_LINE> <INDENT> if len(current_place.bees) > 0: <NEW_LINE> <INDENT> return random_or_none(current_place.bees) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> current_place = current_place.entrance | A ThrowerAnt that only throws leaves at Bees at least 5 places away. | 6259905207d97122c4218185 |
class TestDataObjectReplicaJSONDecoder(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.data_object, self.data_object_as_json = create_data_object_with_baton_json_representation() <NEW_LINE> self.replica = self.data_object.replicas.get_by_number(1) <NEW_LINE> self.replica_as_json_string = json.dumps(self.data_object_as_json["replicates"][0]) <NEW_LINE> self.replica.created = None <NEW_LINE> self.replica.last_modified = None <NEW_LINE> <DEDENT> def test_decode(self): <NEW_LINE> <INDENT> decoded = DataObjectReplicaJSONDecoder().decode(self.replica_as_json_string) <NEW_LINE> self.assertEqual(decoded, self.replica) <NEW_LINE> <DEDENT> def test_with_json_loads(self): <NEW_LINE> <INDENT> decoded = json.loads(self.replica_as_json_string, cls=DataObjectReplicaJSONDecoder) <NEW_LINE> self.assertEqual(decoded, self.replica) | Tests for `DataObjectReplicaJSONDecoder`. | 625990528e7ae83300eea572 |
class DistributedGoofy(DistributedObject): <NEW_LINE> <INDENT> def __init__(self, cr): <NEW_LINE> <INDENT> DistributedObject.__init__(self, cr) | THIS IS A DUMMY FILE FOR THE DISTRIBUTED CLASS | 62599052be383301e0254cfa |
class Director(models.Model): <NEW_LINE> <INDENT> class DirectorManager(models.Manager): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> last = models.CharField(max_length=20, blank=False, null=False, verbose_name='Last Name') <NEW_LINE> first = models.CharField(max_length=20, blank=False, null=False, verbose_name='First Name') <NEW_LINE> dob = models.DateField(blank=False, null=False, verbose_name='Date of Birth') <NEW_LINE> dod = models.DateField(null=True, default=None, verbose_name='Date of Death') <NEW_LINE> objects = DirectorManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = 'directors' <NEW_LINE> ordering = ['last', 'first'] <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return '[%s] %s, %s (%s)' % (self.id, self.last, self.first, self.dob) <NEW_LINE> <DEDENT> def get_full_name(self): <NEW_LINE> <INDENT> return '%s %s' % (self.first, self.last) <NEW_LINE> <DEDENT> def save(self, force_insert=False, force_update=False, using=None, update_fields=None): <NEW_LINE> <INDENT> if self.dod and (self.dod < self.dob): <NEW_LINE> <INDENT> raise ValidationError('Director dod cannot be less than dob') <NEW_LINE> <DEDENT> super(Director, self).save(force_insert, force_update, using, update_fields) | :param: last - Last name of the director
:param: first - First name of the director
:param: dob - Director's date of birth
:param: dod - Director's date of death. None if still alive | 625990524e696a045264e890 |
class GitProxy(object): <NEW_LINE> <INDENT> def __init__(self, repo): <NEW_LINE> <INDENT> self._repo = repo <NEW_LINE> <DEDENT> def get_config(self, name): <NEW_LINE> <INDENT> return self._repo.git.config('--get', name) <NEW_LINE> <DEDENT> def checkout(self, *args, **kwargs): <NEW_LINE> <INDENT> return self._repo.git.checkout(*args, **kwargs) <NEW_LINE> <DEDENT> def ls_files(self, *args, **kwargs): <NEW_LINE> <INDENT> return self._repo.git.ls_files(*args, **kwargs) <NEW_LINE> <DEDENT> def describe(self, *args, **kwargs): <NEW_LINE> <INDENT> return self._repo.git.describe(*args, **kwargs) <NEW_LINE> <DEDENT> def diff(self, *args, **kwargs): <NEW_LINE> <INDENT> return self._repo.git.diff(*args, **kwargs) <NEW_LINE> <DEDENT> def log(self, *args, **kwargs): <NEW_LINE> <INDENT> return self._repo.git.log(*args, **kwargs) <NEW_LINE> <DEDENT> def status(self, *args, **kwargs): <NEW_LINE> <INDENT> return self._repo.git.status(*args, **kwargs) <NEW_LINE> <DEDENT> def rev_list(self, *args, **kwargs): <NEW_LINE> <INDENT> return self._repo.git.rev_list(*args, **kwargs) | Proxy to underlying git repository
This is used for callers to interact with underlying repository from
outside of PackageRepo. | 6259905263d6d428bbee3cad |
class ReqDescription(ReqTagGeneric): <NEW_LINE> <INDENT> def __init__(self, config): <NEW_LINE> <INDENT> ReqTagGeneric.__init__( self, config, "Description", set([InputModuleTypes.ctstag, InputModuleTypes.reqtag, InputModuleTypes.testcase])) <NEW_LINE> <DEDENT> def rewrite(self, rid, req): <NEW_LINE> <INDENT> self.check_mandatory_tag(rid, req, 2) <NEW_LINE> tag = req[self.get_tag()] <NEW_LINE> if len(tag.get_content()) > 1024: <NEW_LINE> <INDENT> raise RMTException(3, "%s: Description is much too long: " "%d characters" % (rid, len(tag.get_content()))) <NEW_LINE> <DEDENT> if len(tag.get_content()) > 255: <NEW_LINE> <INDENT> print("+++ WARNING %s: Description is too long: %d characters" % (rid, len(tag.get_content()))) <NEW_LINE> print("+++ Please consider split up this requirement") <NEW_LINE> <DEDENT> del req[self.get_tag()] <NEW_LINE> return self.get_tag(), tag | Requirement description attribute | 6259905245492302aabfd9b5 |
class MAVLink_log_entry_message(MAVLink_message): <NEW_LINE> <INDENT> id = MAVLINK_MSG_ID_LOG_ENTRY <NEW_LINE> name = 'LOG_ENTRY' <NEW_LINE> fieldnames = ['id', 'num_logs', 'last_log_num', 'time_utc', 'size'] <NEW_LINE> ordered_fieldnames = ['time_utc', 'size', 'id', 'num_logs', 'last_log_num'] <NEW_LINE> fieldtypes = ['uint16_t', 'uint16_t', 'uint16_t', 'uint32_t', 'uint32_t'] <NEW_LINE> format = '<IIHHH' <NEW_LINE> native_format = bytearray('<IIHHH', 'ascii') <NEW_LINE> orders = [2, 3, 4, 0, 1] <NEW_LINE> lengths = [1, 1, 1, 1, 1] <NEW_LINE> array_lengths = [0, 0, 0, 0, 0] <NEW_LINE> crc_extra = 56 <NEW_LINE> unpacker = struct.Struct('<IIHHH') <NEW_LINE> def __init__(self, id, num_logs, last_log_num, time_utc, size): <NEW_LINE> <INDENT> MAVLink_message.__init__(self, MAVLink_log_entry_message.id, MAVLink_log_entry_message.name) <NEW_LINE> self._fieldnames = MAVLink_log_entry_message.fieldnames <NEW_LINE> self.id = id <NEW_LINE> self.num_logs = num_logs <NEW_LINE> self.last_log_num = last_log_num <NEW_LINE> self.time_utc = time_utc <NEW_LINE> self.size = size <NEW_LINE> <DEDENT> def pack(self, mav, force_mavlink1=False): <NEW_LINE> <INDENT> return MAVLink_message.pack(self, mav, 56, struct.pack('<IIHHH', self.time_utc, self.size, self.id, self.num_logs, self.last_log_num), force_mavlink1=force_mavlink1) | Reply to LOG_REQUEST_LIST | 62599052be8e80087fbc055c |
class MappingTree(DSLdapObject): <NEW_LINE> <INDENT> _must_attributes = ['cn'] <NEW_LINE> def __init__(self, instance, dn=None): <NEW_LINE> <INDENT> super(MappingTree, self).__init__(instance, dn) <NEW_LINE> self._rdn_attribute = 'cn' <NEW_LINE> self._must_attributes = ['cn'] <NEW_LINE> self._create_objectclasses = ['top', 'extensibleObject', 'nsMappingTree'] <NEW_LINE> self._protected = False <NEW_LINE> <DEDENT> def set_parent(self, parent): <NEW_LINE> <INDENT> self.replace('nsslapd-parent-suffix', parent) | Mapping tree DSLdapObject with:
- must attributes = ['cn']
- RDN attribute is 'cn'
:param instance: An instance
:type instance: lib389.DirSrv
:param dn: Entry DN
:type dn: str | 6259905291af0d3eaad3b305 |
class PrefixLoader(BaseLoader): <NEW_LINE> <INDENT> def __init__(self, mapping, delimiter='/'): <NEW_LINE> <INDENT> self.mapping = mapping <NEW_LINE> self.delimiter = delimiter <NEW_LINE> <DEDENT> def get_loader(self, template): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> prefix, name = template.split(self.delimiter, 1) <NEW_LINE> loader = self.mapping[prefix] <NEW_LINE> <DEDENT> except (ValueError, KeyError): <NEW_LINE> <INDENT> raise TemplateNotFound(template) <NEW_LINE> <DEDENT> return loader, name <NEW_LINE> <DEDENT> def get_source(self, environment, template): <NEW_LINE> <INDENT> loader, name = self.get_loader(template) <NEW_LINE> try: <NEW_LINE> <INDENT> return loader.get_source(environment, name) <NEW_LINE> <DEDENT> except TemplateNotFound: <NEW_LINE> <INDENT> raise TemplateNotFound(template) <NEW_LINE> <DEDENT> <DEDENT> @internalcode <NEW_LINE> def load(self, environment, name, globals=None): <NEW_LINE> <INDENT> loader, local_name = self.get_loader(name) <NEW_LINE> try: <NEW_LINE> <INDENT> return loader.load(environment, local_name, globals) <NEW_LINE> <DEDENT> except TemplateNotFound: <NEW_LINE> <INDENT> raise TemplateNotFound(name) <NEW_LINE> <DEDENT> <DEDENT> def list_templates(self): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for prefix, loader in iteritems(self.mapping): <NEW_LINE> <INDENT> for template in loader.list_templates(): <NEW_LINE> <INDENT> result.append(prefix + self.delimiter + template) <NEW_LINE> <DEDENT> <DEDENT> return result | A loader that is passed a dict of loaders where each loader is bound
to a prefix. The prefix is delimited from the template by a slash per
default, which can be changed by setting the `delimiter` argument to
something else::
loader = PrefixLoader({
'app1': PackageLoader('mypackage.app1'),
'app2': PackageLoader('mypackage.app2')
})
By loading ``'app1/index.html.bak'`` the file from the app1 package is loaded,
by loading ``'app2/index.html.bak'`` the file from the second. | 6259905215baa7234946346e |
class RoleTypeSet: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.role_types = {} <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for role_type in self.role_types.values(): <NEW_LINE> <INDENT> yield role_type <NEW_LINE> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.role_types.keys()) <NEW_LINE> <DEDENT> def add(self, role, type): <NEW_LINE> <INDENT> if self.role_types.has_key(role): <NEW_LINE> <INDENT> role_type = self.role_types[role] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> role_type = refpolicy.RoleType() <NEW_LINE> role_type.role = role <NEW_LINE> self.role_types[role] = role_type <NEW_LINE> <DEDENT> role_type.types.add(type) | A non-overlapping set of role type statements.
This clas allows the incremental addition of role type statements and
maintains a non-overlapping list of statements. | 62599052d6c5a102081e35fa |
class File(models.Model): <NEW_LINE> <INDENT> short_name = models.CharField(unique=True, max_length=80) <NEW_LINE> file = models.FileField(upload_to="uploads") <NEW_LINE> description = models.CharField(max_length=255) <NEW_LINE> comments = models.CharField(max_length=255, blank=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.short_name <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = 'x file' | These are files that are significant enough we want to track and describe.
They can be associated with a project. | 6259905276d4e153a661dce9 |
class GeneralAssemblyInvitation(object): <NEW_LINE> <INDENT> def __init__(self, general_assembly, member, sent, token=None): <NEW_LINE> <INDENT> self.general_assembly = general_assembly <NEW_LINE> self.member = member <NEW_LINE> self.sent = sent <NEW_LINE> self.token = token | Invitation of a member to a general assembly
The general assembly invitation describes an invitation for a member to a
general assembly with sent timestamp and token string. | 62599052004d5f362081fa5a |
class SAmsNetId(Structure): <NEW_LINE> <INDENT> _pack_ = 1 <NEW_LINE> _fields_ = [("b", c_ubyte * 6)] | Struct with array of 6 bytes used to describe a net id. | 62599052287bf620b62730cc |
class ButtonCustom(QPushButton): <NEW_LINE> <INDENT> def __init__(self, value='', styles='', param=None, path_icon=None): <NEW_LINE> <INDENT> QPushButton.__init__(self, value) <NEW_LINE> if path_icon: <NEW_LINE> <INDENT> self.setIcon(QIcon(path_icon)) <NEW_LINE> self.setIconSize(QSize(20,20)) <NEW_LINE> <DEDENT> self.setStyleSheet(styles) <NEW_LINE> self.param=param <NEW_LINE> self.action=None <NEW_LINE> self.clicked.connect(self.clickAction) <NEW_LINE> self.setAction() <NEW_LINE> <DEDENT> def clickAction(self): <NEW_LINE> <INDENT> if self.action: <NEW_LINE> <INDENT> function_string = self.action <NEW_LINE> function_string(self.param) if self.param else function_string() <NEW_LINE> <DEDENT> <DEDENT> def setSize(self, sizeI, sizeE): <NEW_LINE> <INDENT> self.setFixedSize(sizeI, sizeE) <NEW_LINE> <DEDENT> def setAction(self, action=None): <NEW_LINE> <INDENT> if action is not None: <NEW_LINE> <INDENT> self.action = action | Clase de botón o icono personalizado. | 625990522ae34c7f260ac5c3 |
class TensorDataLoader: <NEW_LINE> <INDENT> def __init__(self, *tensors, batch_size, shuffle=False, pin_memory=False): <NEW_LINE> <INDENT> assert all(t.shape[0] == tensors[0].shape[0] for t in tensors) <NEW_LINE> self.dataset_len = tensors[0].shape[0] <NEW_LINE> self.pin_memory = pin_memory and T.cuda.is_available() <NEW_LINE> self.tensors = [T.as_tensor(t) for t in tensors] <NEW_LINE> if self.pin_memory: <NEW_LINE> <INDENT> self.tensors = [t.pin_memory() for t in self.tensors] <NEW_LINE> <DEDENT> self.batch_size = batch_size <NEW_LINE> self.shuffle = shuffle <NEW_LINE> n_batches, remainder = divmod(self.dataset_len, self.batch_size) <NEW_LINE> if remainder > 0: <NEW_LINE> <INDENT> n_batches += 1 <NEW_LINE> <DEDENT> self.n_batches = n_batches <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> if self.shuffle: <NEW_LINE> <INDENT> r = T.randperm(self.dataset_len) <NEW_LINE> self.tensors = [t[r] for t in self.tensors] <NEW_LINE> del r <NEW_LINE> <DEDENT> self.i = 0 <NEW_LINE> return self <NEW_LINE> <DEDENT> def __next__(self): <NEW_LINE> <INDENT> if self.i >= self.dataset_len: <NEW_LINE> <INDENT> raise StopIteration <NEW_LINE> <DEDENT> batch = tuple(t[self.i: self.i+self.batch_size] for t in self.tensors) <NEW_LINE> self.i += self.batch_size <NEW_LINE> return batch <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self.n_batches | Warning:
`TensorDataLoader` doesn't support distributed training now. | 625990520a50d4780f70682d |
class ProjectCursorPagination(CursorPagination): <NEW_LINE> <INDENT> def encode_cursor(self, cursor): <NEW_LINE> <INDENT> tokens = {} <NEW_LINE> if cursor.offset != 0: <NEW_LINE> <INDENT> tokens['o'] = str(cursor.offset) <NEW_LINE> <DEDENT> if cursor.reverse: <NEW_LINE> <INDENT> tokens['r'] = '1' <NEW_LINE> <DEDENT> if cursor.position is not None: <NEW_LINE> <INDENT> tokens['p'] = cursor.position <NEW_LINE> <DEDENT> querystring = urlparse.urlencode(tokens, doseq=True) <NEW_LINE> encoded = b64encode(querystring.encode('ascii')).decode('ascii') <NEW_LINE> return encoded | Customized cursor pagination class. | 62599052ac7a0e7691f739be |
class FindDuplicatesTests(unittest.TestCase): <NEW_LINE> <INDENT> def test_specification(self): <NEW_LINE> <INDENT> n = 1000000 <NEW_LINE> duplicate = 3578 <NEW_LINE> input_list = list(range(1, n + 1)) <NEW_LINE> input_list.append(duplicate) <NEW_LINE> shuffle(input_list) <NEW_LINE> expected_return = [] <NEW_LINE> expected_return.append(duplicate) <NEW_LINE> self.assertEqual(find_duplicates(input_list), expected_return) <NEW_LINE> <DEDENT> def test_multiple_duplicates(self): <NEW_LINE> <INDENT> input_list = [5,4,4,3,2,1,2] <NEW_LINE> expected_return = [2, 4] <NEW_LINE> self.assertEqual(find_duplicates(input_list), expected_return) <NEW_LINE> <DEDENT> def test_chars(self): <NEW_LINE> <INDENT> input_list = ['a', 'b', 'c', 'c', 'd'] <NEW_LINE> expected_return = ['c'] <NEW_LINE> self.assertEqual(find_duplicates(input_list), expected_return) <NEW_LINE> <DEDENT> def test_no_duplicates(self): <NEW_LINE> <INDENT> no_duplicate_list = [5,4,3,2,1,0] <NEW_LINE> expected_return = [] <NEW_LINE> self.assertEqual(find_duplicates(no_duplicate_list), expected_return) <NEW_LINE> <DEDENT> def test_empty_input(self): <NEW_LINE> <INDENT> empty_list = [] <NEW_LINE> expected_return = [] <NEW_LINE> self.assertEqual(find_duplicates(empty_list), expected_return) <NEW_LINE> <DEDENT> def test_non_list(self): <NEW_LINE> <INDENT> non_list = 'cow' <NEW_LINE> with self.assertRaises(TypeError): <NEW_LINE> <INDENT> find_duplicates(non_list) | Run tests on find_duplicates().
Useage: $ python find_duplicates_tests.py | 6259905255399d3f056279fc |
class CityAdminMixin(admin.ModelAdmin): <NEW_LINE> <INDENT> list_display = () <NEW_LINE> list_filter = () <NEW_LINE> fields = () <NEW_LINE> exclude = () <NEW_LINE> readonly_for_city = () <NEW_LINE> def get_city(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> city = City.objects.get(user=request.user) <NEW_LINE> <DEDENT> except City.DoesNotExist: <NEW_LINE> <INDENT> city = None <NEW_LINE> <DEDENT> return city <NEW_LINE> <DEDENT> def get_list_display(self, request): <NEW_LINE> <INDENT> if self.get_city(request): <NEW_LINE> <INDENT> return self.list_display <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if ('city,') in self.list_display: <NEW_LINE> <INDENT> return self.list_display <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ('city',) + self.list_display <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_list_filter(self, request): <NEW_LINE> <INDENT> if self.get_city(request): <NEW_LINE> <INDENT> return self.list_filter <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if ('city',) in self.list_filter: <NEW_LINE> <INDENT> return self.list_filter <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ('city',) + self.list_filter <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def add_view(self, request, form_url='', extra_context=None): <NEW_LINE> <INDENT> if self.get_city(request): <NEW_LINE> <INDENT> if ('city',) not in self.exclude: <NEW_LINE> <INDENT> self.exclude += ('city',) <NEW_LINE> <DEDENT> <DEDENT> return super(CityAdminMixin, self). add_view(request, form_url, extra_context) <NEW_LINE> <DEDENT> def change_view(self, request, object_id, form_url='', extra_context=None): <NEW_LINE> <INDENT> if self.get_city(request): <NEW_LINE> <INDENT> if ('city',) not in self.exclude: <NEW_LINE> <INDENT> self.exclude += ('city',) <NEW_LINE> <DEDENT> <DEDENT> return super(CityAdminMixin,self). change_view(request, object_id, form_url, extra_context) <NEW_LINE> <DEDENT> def get_queryset(self, request): <NEW_LINE> <INDENT> queryset = super(CityAdminMixin, self).get_queryset(request) <NEW_LINE> city = self.get_city(request) <NEW_LINE> if city: <NEW_LINE> <INDENT> queryset = queryset.filter(city=city) <NEW_LINE> <DEDENT> return queryset <NEW_LINE> <DEDENT> def save_model(self, request, obj, form, change): <NEW_LINE> <INDENT> city = self.get_city(request) <NEW_LINE> if city: <NEW_LINE> <INDENT> obj.city = city <NEW_LINE> <DEDENT> obj.save() | City auth admin | 625990522ae34c7f260ac5c4 |
class User(AbstractBaseUser, PermissionsMixin): <NEW_LINE> <INDENT> email = models.EmailField(verbose_name=u'email address', max_length=255, unique=True, db_index=True) <NEW_LINE> def _make_username(self): <NEW_LINE> <INDENT> return self.email.split('@')[0] <NEW_LINE> <DEDENT> username = property(_make_username) <NEW_LINE> firstname = models.CharField(verbose_name=u'first name', max_length=30) <NEW_LINE> lastname = models.CharField(verbose_name=u'last name', max_length=30) <NEW_LINE> middlename = models.CharField(verbose_name=u'middle name', max_length=30, blank=True, null=True) <NEW_LINE> nickname = models.CharField(max_length=30, blank=True, null=True) <NEW_LINE> maidenname = models.CharField(verbose_name=u'maiden name', max_length=30, blank=True, null=True) <NEW_LINE> GENDER = ( ('B', 'Brother'), ('S', 'Sister') ) <NEW_LINE> gender = models.CharField(max_length=1, choices=GENDER) <NEW_LINE> date_of_birth = models.DateField(null=True) <NEW_LINE> def _get_age(self): <NEW_LINE> <INDENT> age = date.today() - self.date_of_birth <NEW_LINE> return age.days/365 <NEW_LINE> <DEDENT> age = property(_get_age) <NEW_LINE> phone = models.CharField(max_length=25, null=True, blank=True) <NEW_LINE> USERNAME_FIELD = 'email' <NEW_LINE> REQUIRED_FIELDS = [] <NEW_LINE> is_active = models.BooleanField(default=True) <NEW_LINE> is_admin = models.BooleanField(default=False) <NEW_LINE> is_staff = models.BooleanField(default=False) <NEW_LINE> objects = APUserManager() <NEW_LINE> def get_absolute_url(self): <NEW_LINE> <INDENT> return "/users/%s/" % urlquote(self.username) <NEW_LINE> <DEDENT> def get_full_name(self): <NEW_LINE> <INDENT> fullname = '%s %s' % (self.firstname, self.lastname) <NEW_LINE> return fullname.strip() <NEW_LINE> <DEDENT> def get_short_name(self): <NEW_LINE> <INDENT> return self.firstname <NEW_LINE> <DEDENT> def email_user(self, subject, message, from_email=None): <NEW_LINE> <INDENT> send_mail(subject, message, from_email, [self.email]) <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.email | A basic user account, containing all common user information.
This is a custom-defined User, but inherits from Django's classes
to integrate with Django's other provided User tools/functionality
AbstractBaseUser provides Django's basic authentication backend.
PermissionsMixin provides compatability with Django's built-in permissions system. | 62599052379a373c97d9a503 |
@base.Hidden <NEW_LINE> @base.ReleaseTracks(base.ReleaseTrack.ALPHA) <NEW_LINE> class SetIamPolicy(base.Command): <NEW_LINE> <INDENT> detailed_help = iam_util.GetDetailedHelpForSetIamPolicy('disk image', 'my-image') <NEW_LINE> @staticmethod <NEW_LINE> def Args(parser): <NEW_LINE> <INDENT> SetIamPolicy.disk_image_arg = flags.MakeDiskImageArg(plural=False) <NEW_LINE> SetIamPolicy.disk_image_arg.AddArgument( parser, operation_type='set the IAM policy of') <NEW_LINE> compute_flags.AddPolicyFileFlag(parser) <NEW_LINE> <DEDENT> def Run(self, args): <NEW_LINE> <INDENT> holder = base_classes.ComputeApiHolder(self.ReleaseTrack()) <NEW_LINE> client = holder.client <NEW_LINE> image_ref = SetIamPolicy.disk_image_arg.ResolveAsResource( args, holder.resources, scope_lister=compute_flags.GetDefaultScopeLister(client)) <NEW_LINE> policy = iam_util.ParsePolicyFile(args.policy_file, client.messages.Policy) <NEW_LINE> request = client.messages.ComputeImagesSetIamPolicyRequest( policy=policy, resource=image_ref.image, project=image_ref.project) <NEW_LINE> return client.apitools_client.images.SetIamPolicy(request) | Set the IAM Policy for a Google Compute Engine disk image.
*{command}* replaces the existing IAM policy for a disk image, given an image
and a file encoded in JSON or YAML that contains the IAM policy. If the given
policy file specifies an "etag" value, then the replacement will succeed only
if the policy already in place matches that etag. (An etag obtained via
`get-iam-policy` will prevent the replacement if the policy for the image has
been subsequently updated.) A policy file that does not contain an etag value
will replace any existing policy for the image. | 62599052dc8b845886d54aa1 |
class LogitechMediaServer(object): <NEW_LINE> <INDENT> def __init__(self, hass, host, port, username, password): <NEW_LINE> <INDENT> self.hass = hass <NEW_LINE> self.host = host <NEW_LINE> self.port = port <NEW_LINE> self._username = username <NEW_LINE> self._password = password <NEW_LINE> <DEDENT> @asyncio.coroutine <NEW_LINE> def create_players(self): <NEW_LINE> <INDENT> result = [] <NEW_LINE> data = yield from self.async_query('players', 'status') <NEW_LINE> if data is False: <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> for players in data.get('players_loop', []): <NEW_LINE> <INDENT> player = SqueezeBoxDevice( self, players['playerid'], players['name']) <NEW_LINE> yield from player.async_update() <NEW_LINE> result.append(player) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> @asyncio.coroutine <NEW_LINE> def async_query(self, *command, player=""): <NEW_LINE> <INDENT> auth = None if self._username is None else aiohttp.BasicAuth( self._username, self._password) <NEW_LINE> url = "http://{}:{}/jsonrpc.js".format( self.host, self.port) <NEW_LINE> data = json.dumps({ "id": "1", "method": "slim.request", "params": [player, command] }) <NEW_LINE> _LOGGER.debug("URL: %s Data: %s", url, data) <NEW_LINE> try: <NEW_LINE> <INDENT> websession = async_get_clientsession(self.hass) <NEW_LINE> with async_timeout.timeout(TIMEOUT, loop=self.hass.loop): <NEW_LINE> <INDENT> response = yield from websession.post( url, data=data, auth=auth) <NEW_LINE> if response.status != 200: <NEW_LINE> <INDENT> _LOGGER.error( "Query failed, response code: %s Full message: %s", response.status, response) <NEW_LINE> return False <NEW_LINE> <DEDENT> data = yield from response.json() <NEW_LINE> <DEDENT> <DEDENT> except (asyncio.TimeoutError, aiohttp.ClientError) as error: <NEW_LINE> <INDENT> _LOGGER.error("Failed communicating with LMS: %s", type(error)) <NEW_LINE> return False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return data['result'] <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> _LOGGER.error("Received invalid response: %s", data) <NEW_LINE> return False | Representation of a Logitech media server. | 6259905230c21e258be99ce7 |
class FinalOptimizePhase(Visitor.CythonTransform): <NEW_LINE> <INDENT> def visit_SingleAssignmentNode(self, node): <NEW_LINE> <INDENT> self.visitchildren(node) <NEW_LINE> if node.first: <NEW_LINE> <INDENT> lhs = node.lhs <NEW_LINE> lhs.lhs_of_first_assignment = True <NEW_LINE> if isinstance(lhs, ExprNodes.NameNode) and lhs.entry.type.is_pyobject: <NEW_LINE> <INDENT> lhs.entry.init_to_none = False <NEW_LINE> lhs.entry.init = 0 <NEW_LINE> <DEDENT> <DEDENT> return node <NEW_LINE> <DEDENT> def visit_SimpleCallNode(self, node): <NEW_LINE> <INDENT> self.visitchildren(node) <NEW_LINE> if node.function.type.is_cfunction and isinstance(node.function, ExprNodes.NameNode): <NEW_LINE> <INDENT> if node.function.name == 'isinstance': <NEW_LINE> <INDENT> type_arg = node.args[1] <NEW_LINE> if type_arg.type.is_builtin_type and type_arg.type.name == 'type': <NEW_LINE> <INDENT> from CythonScope import utility_scope <NEW_LINE> node.function.entry = utility_scope.lookup('PyObject_TypeCheck') <NEW_LINE> node.function.type = node.function.entry.type <NEW_LINE> PyTypeObjectPtr = PyrexTypes.CPtrType(utility_scope.lookup('PyTypeObject').type) <NEW_LINE> node.args[1] = ExprNodes.CastNode(node.args[1], PyTypeObjectPtr) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return node <NEW_LINE> <DEDENT> def visit_PyTypeTestNode(self, node): <NEW_LINE> <INDENT> self.visitchildren(node) <NEW_LINE> if not node.notnone: <NEW_LINE> <INDENT> if not node.arg.may_be_none(): <NEW_LINE> <INDENT> node.notnone = True <NEW_LINE> <DEDENT> <DEDENT> return node | This visitor handles several commuting optimizations, and is run
just before the C code generation phase.
The optimizations currently implemented in this class are:
- eliminate None assignment and refcounting for first assignment.
- isinstance -> typecheck for cdef types
- eliminate checks for None and/or types that became redundant after tree changes | 625990524e696a045264e891 |
@UASLocalMetadataSet.add_parser <NEW_LINE> class MissionID(StringElementParser): <NEW_LINE> <INDENT> key = b'\x03' <NEW_LINE> TAG = 3 <NEW_LINE> UDSKey = "06 0E 2B 34 01 01 01 01 01 05 05 00 00 00 00 00" <NEW_LINE> LDSName = "Mission ID" <NEW_LINE> ESDName = "Mission Number" <NEW_LINE> UDSName = "Episode Number" <NEW_LINE> min_length, max_length = 0, 127 | Mission ID is the descriptive mission identifier.
Mission ID value field free text with maximum of 127 characters
describing the event. | 625990523eb6a72ae038bb3d |
class Cylindrical(Projection): <NEW_LINE> <INDENT> _separable = True | Base class for Cylindrical projections.
Cylindrical projections are so-named because the surface of
projection is a cylinder. | 6259905276e4537e8c3f0a69 |
@python_2_unicode_compatible <NEW_LINE> class User(AbstractUser): <NEW_LINE> <INDENT> nickname = models.CharField(null=True, blank=True, max_length=255, verbose_name='昵称') <NEW_LINE> job_title = models.CharField(max_length=50, null=True, blank=True, verbose_name='职称') <NEW_LINE> introduction = models.TextField(blank=True, null=True, verbose_name='简介') <NEW_LINE> picture = models.ImageField(upload_to='profile_pics/', null=True, blank=True, verbose_name='头像') <NEW_LINE> location = models.CharField(max_length=50, null=True, blank=True, verbose_name='城市') <NEW_LINE> personal_url = models.URLField(max_length=555, blank=True, null=True, verbose_name='个人链接') <NEW_LINE> weibo = models.URLField(max_length=255, blank=True, null=True, verbose_name='微博链接') <NEW_LINE> zhihu = models.URLField(max_length=255, blank=True, null=True, verbose_name='知乎链接') <NEW_LINE> github = models.URLField(max_length=255, blank=True, null=True, verbose_name='Github链接') <NEW_LINE> linkedin = models.URLField(max_length=255, blank=True, null=True, verbose_name='LinkedIn链接') <NEW_LINE> created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间') <NEW_LINE> updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = '用户' <NEW_LINE> verbose_name_plural = verbose_name <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.username <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse("users:detail", kwargs={"username": self.username}) <NEW_LINE> <DEDENT> def get_profile_name(self): <NEW_LINE> <INDENT> return self.nickname if self.nickname else self.username | Customized User Model | 62599052a8ecb033258726f5 |
class TestInternals(BaseTest): <NEW_LINE> <INDENT> def _check_get_set_state(self, ptr): <NEW_LINE> <INDENT> state = _helperlib.rnd_get_state(ptr) <NEW_LINE> i, ints = state <NEW_LINE> self.assertIsInstance(i, int) <NEW_LINE> self.assertIsInstance(ints, list) <NEW_LINE> self.assertEqual(len(ints), N) <NEW_LINE> j = (i * 100007) % N <NEW_LINE> ints = [i * 3 for i in range(N)] <NEW_LINE> _helperlib.rnd_set_state(ptr, (j, ints)) <NEW_LINE> self.assertEqual(_helperlib.rnd_get_state(ptr), (j, ints)) <NEW_LINE> <DEDENT> def _check_shuffle(self, ptr): <NEW_LINE> <INDENT> r = random.Random() <NEW_LINE> ints, index = _copy_py_state(r, ptr) <NEW_LINE> for i in range(index, N + 1, 2): <NEW_LINE> <INDENT> r.random() <NEW_LINE> <DEDENT> _helperlib.rnd_shuffle(ptr) <NEW_LINE> mt = r.getstate()[1] <NEW_LINE> ints, index = mt[:-1], mt[-1] <NEW_LINE> self.assertEqual(_helperlib.rnd_get_state(ptr)[1], list(ints)) <NEW_LINE> <DEDENT> def _check_init(self, ptr): <NEW_LINE> <INDENT> r = np.random.RandomState() <NEW_LINE> for i in [0, 1, 125, 2**32 - 5]: <NEW_LINE> <INDENT> r.seed(np.uint32(i)) <NEW_LINE> st = r.get_state() <NEW_LINE> ints = list(st[1]) <NEW_LINE> index = st[2] <NEW_LINE> assert index == N <NEW_LINE> _helperlib.rnd_seed(ptr, i) <NEW_LINE> self.assertEqual(_helperlib.rnd_get_state(ptr), (index, ints)) <NEW_LINE> <DEDENT> <DEDENT> def _check_perturb(self, ptr): <NEW_LINE> <INDENT> states = [] <NEW_LINE> for i in range(10): <NEW_LINE> <INDENT> _helperlib.rnd_seed(ptr, 0) <NEW_LINE> _helperlib.rnd_seed(ptr, os.urandom(512)) <NEW_LINE> states.append(tuple(_helperlib.rnd_get_state(ptr)[1])) <NEW_LINE> <DEDENT> self.assertEqual(len(set(states)), len(states)) <NEW_LINE> <DEDENT> def test_get_set_state(self): <NEW_LINE> <INDENT> self._check_get_set_state(py_state_ptr) <NEW_LINE> <DEDENT> def test_shuffle(self): <NEW_LINE> <INDENT> self._check_shuffle(py_state_ptr) <NEW_LINE> <DEDENT> def test_init(self): <NEW_LINE> <INDENT> self._check_init(py_state_ptr) <NEW_LINE> <DEDENT> def test_perturb(self): <NEW_LINE> <INDENT> self._check_perturb(py_state_ptr) | Test low-level internals of the implementation. | 6259905291af0d3eaad3b307 |
class RawDeprecated(object): <NEW_LINE> <INDENT> def __init__(self, first_token, text): <NEW_LINE> <INDENT> self.first_token = first_token <NEW_LINE> self.text = text <NEW_LINE> <DEDENT> def getType(self): <NEW_LINE> <INDENT> return 'deprecated' <NEW_LINE> <DEDENT> def getFormatted(self, formatter): <NEW_LINE> <INDENT> return formatter.formatCommand('deprecated', self.text.text.strip()) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'RawDeprecated(%s)' % repr(self.text) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.text == other.text | A representation of a @deprecated entry.
@ivar text The @deprecated clauses's text. | 625990527d847024c075d8b9 |
class Tape: <NEW_LINE> <INDENT> def __init__(self, init, endsym): <NEW_LINE> <INDENT> self._cells = list(init) <NEW_LINE> self._endsym = endsym <NEW_LINE> self._current = 0 <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return ''.join(self._cells) <NEW_LINE> <DEDENT> @property <NEW_LINE> def current_cell(self): <NEW_LINE> <INDENT> print("G-----> {0}".format(self._current)) <NEW_LINE> return self._cells[self._current] <NEW_LINE> <DEDENT> @current_cell.setter <NEW_LINE> def current_cell(self, val): <NEW_LINE> <INDENT> print("S-----> {0}".format(self._current)) <NEW_LINE> self._cells[self._current] = val <NEW_LINE> <DEDENT> def shift_left(self): <NEW_LINE> <INDENT> self._current += 1 <NEW_LINE> if self._current >= len(self._cells): <NEW_LINE> <INDENT> self._cells += [self._endsym] <NEW_LINE> <DEDENT> <DEDENT> def shift_right(self): <NEW_LINE> <INDENT> if self._current == 0: <NEW_LINE> <INDENT> self._cells = [self._endsym] + self._cells <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._current -= 1 | Tape is a list of cells that contain symbols of the current machine; | 6259905276d4e153a661dcea |
class UserByCompanyCity(Base): <NEW_LINE> <INDENT> company = columns.Text(primary_key=True) <NEW_LINE> city = columns.Text(primary_key=True) <NEW_LINE> id = columns.Integer(primary_key=True) <NEW_LINE> first_name = columns.Text() <NEW_LINE> last_name = columns.Text() <NEW_LINE> email = columns.Text() <NEW_LINE> def get_data(self): <NEW_LINE> <INDENT> return { 'id': str(self.id), 'first_name': self.first_name, 'last_name' : self.last_name, 'email' : self.email, 'company' : self.company, 'city' : self.city } | Model Person object by company & city in the database | 625990528da39b475be046c9 |
class CercaCampoStudio(models.Model): <NEW_LINE> <INDENT> lavoro = models.ForeignKey(Lavoro, on_delete=models.CASCADE) <NEW_LINE> campo_studio = models.ForeignKey(CampoStudi, on_delete=models.CASCADE, null=True) | Rappresenta la tabella che associa una Offerta di Lavoro con zero o piu Campi di Studio | 62599052462c4b4f79dbcee3 |
class Config(object): <NEW_LINE> <INDENT> SECRET_KEY = os.environ.get('CONDUIT_SECRET', 'secret-key') <NEW_LINE> APP_DIR = os.path.abspath(os.path.dirname(__file__)) <NEW_LINE> PROJECT_ROOT = os.path.abspath(os.path.join(APP_DIR, os.pardir)) <NEW_LINE> BCRYPT_LOG_ROUNDS = 13 <NEW_LINE> DEBUG_TB_INTERCEPT_REDIRECTS = False <NEW_LINE> CACHE_TYPE = 'simple' <NEW_LINE> SQLALCHEMY_TRACK_MODIFICATIONS = False <NEW_LINE> JWT_AUTH_USERNAME_KEY = 'email' <NEW_LINE> JWT_AUTH_HEADER_PREFIX = 'Token' <NEW_LINE> CORS_ORIGIN_WHITELIST = [ 'http://0.0.0.0:4100', 'http://localhost:4100', 'http://0.0.0.0:8000', 'http://localhost:8000', 'http://0.0.0.0:4200', 'http://localhost:4200', 'http://0.0.0.0:4000', 'http://localhost:4000', 'http://0.0.0.0:' + os.environ.get('PORT', '8080'), 'https://0.0.0.0:' + os.environ.get('PORT', '8080'), 'https://tp-devops-final.netlify.app', os.environ.get('FRONT_PROD_URL', ''), ] <NEW_LINE> JWT_HEADER_TYPE = 'Token' | Base configuration. | 625990528da39b475be046ca |
class Teacher_list(APIView): <NEW_LINE> <INDENT> def get(self, request, format=None): <NEW_LINE> <INDENT> users = User.objects.all().filter(is_teacher=True) <NEW_LINE> serializer = CustomUserSerializer(users, many=True) <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> def post(self, request, format=None): <NEW_LINE> <INDENT> serializer = TeacherRegisterSerializer(data=request.data) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> serializer.save() <NEW_LINE> return Response(serializer.data, status=status.HTTP_201_CREATED) <NEW_LINE> <DEDENT> return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) | List all code snippets, or create a new snippet. | 62599052cad5886f8bdc5af0 |
class RequestsHttpClient(HttpClient): <NEW_LINE> <INDENT> def __init__(self, timeout=HttpClient.DEFAULT_TIMEOUT): <NEW_LINE> <INDENT> super(RequestsHttpClient, self).__init__(timeout) <NEW_LINE> <DEDENT> def get(self, url, headers=None, params=None, stream=False, timeout=None): <NEW_LINE> <INDENT> if timeout is None: <NEW_LINE> <INDENT> timeout = self.timeout <NEW_LINE> <DEDENT> response = requests.get( url, headers=headers, params=params, stream=stream, timeout=timeout ) <NEW_LINE> return RequestsHttpResponse(response) <NEW_LINE> <DEDENT> def post(self, url, headers=None, data=None, timeout=None): <NEW_LINE> <INDENT> if timeout is None: <NEW_LINE> <INDENT> timeout = self.timeout <NEW_LINE> <DEDENT> response = requests.post( url, headers=headers, data=data, timeout=timeout ) <NEW_LINE> return RequestsHttpResponse(response) | HttpClient implemented by requests. | 625990524a966d76dd5f03cf |
class TestOverrideSettings(object): <NEW_LINE> <INDENT> setting = '' <NEW_LINE> method = '' <NEW_LINE> value = None <NEW_LINE> def test_override_value(self): <NEW_LINE> <INDENT> value = self.value or 'new value' <NEW_LINE> with self.settings(**{self.setting: value}): <NEW_LINE> <INDENT> self.assertEquals(first=value, second=getattr(self.storage, self.method)()) | Test cases for setting overrides | 6259905245492302aabfd9b8 |
class ExerciseViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = Exercise.objects.all() <NEW_LINE> serializer_class = ExerciseSerializer <NEW_LINE> permission_classes = (IsAuthenticatedOrReadOnly, CreateOnlyPermission) <NEW_LINE> http_method_names = ['get', 'options', 'head'] <NEW_LINE> ordering_fields = '__all__' <NEW_LINE> filter_fields = ('category', 'creation_date', 'description', 'language', 'muscles', 'muscles_secondary', 'status', 'name', 'equipment', 'license', 'license_author') <NEW_LINE> def perform_create(self, serializer): <NEW_LINE> <INDENT> language = load_language() <NEW_LINE> obj = serializer.save(language=language) <NEW_LINE> obj.set_author(self.request) <NEW_LINE> obj.save() | API endpoint for exercise objects | 62599052b57a9660fecd2f5a |
class BaseModel(db.Model): <NEW_LINE> <INDENT> __abstract__ = True <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> @staticmethod <NEW_LINE> def to_camel_case(snake_str): <NEW_LINE> <INDENT> title_str = snake_str.title().replace("_", "") <NEW_LINE> return title_str[0].lower() + title_str[1:] <NEW_LINE> <DEDENT> def serialize(self): <NEW_LINE> <INDENT> return {self.to_camel_case(column.name): getattr(self, column.name) for column in self.__table__.columns} <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> db.session.add(self) <NEW_LINE> db.session.commit() <NEW_LINE> return True <NEW_LINE> <DEDENT> except SQLAlchemyError: <NEW_LINE> <INDENT> db.session.rollback() <NEW_LINE> return False <NEW_LINE> <DEDENT> <DEDENT> def delete(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> db.session.delete(self) <NEW_LINE> db.session.commit() <NEW_LINE> return True <NEW_LINE> <DEDENT> except SQLAlchemyError: <NEW_LINE> <INDENT> db.session.rollback() <NEW_LINE> return False <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def fetch_all(cls): <NEW_LINE> <INDENT> return cls.query.all() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def count(cls): <NEW_LINE> <INDENT> return cls.query.count() | Base models.
- Contains the serialize method to convert objects to a dictionary
- Common field atrributes in the models | 62599052379a373c97d9a504 |
class StreamLabsMonthlyUsage(StreamLabsDailyUsage): <NEW_LINE> <INDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return "{} {}".format(self._location_name, NAME_MONTHLY_USAGE) <NEW_LINE> <DEDENT> @property <NEW_LINE> def state(self): <NEW_LINE> <INDENT> return self._streamlabs_usage_data.get_monthly_usage() | Monitors the monthly water usage. | 625990528e7ae83300eea576 |
class BatchGradientVerificationCallback(VerificationCallbackBase): <NEW_LINE> <INDENT> def __init__( self, input_mapping: Optional[Callable] = None, output_mapping: Optional[Callable] = None, sample_idx: int = 0, **kwargs: Any, ): <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> self._input_mapping = input_mapping <NEW_LINE> self._output_mapping = output_mapping <NEW_LINE> self._sample_idx = sample_idx <NEW_LINE> <DEDENT> def message(self, *args: Any, **kwargs: Any) -> str: <NEW_LINE> <INDENT> message = ( "Your model is mixing data across the batch dimension." " This can lead to wrong gradient updates in the optimizer." " Check the operations that reshape and permute tensor dimensions in your model." ) <NEW_LINE> return message <NEW_LINE> <DEDENT> def on_train_start(self, trainer: Trainer, pl_module: LightningModule) -> None: <NEW_LINE> <INDENT> verification = BatchGradientVerification(pl_module) <NEW_LINE> result = verification.check( input_array=pl_module.example_input_array, input_mapping=self._input_mapping, output_mapping=self._output_mapping, sample_idx=self._sample_idx, ) <NEW_LINE> if not result: <NEW_LINE> <INDENT> self._raise() | The callback version of the :class:`BatchGradientVerification` test.
Verification is performed right before training begins. | 6259905207f4c71912bb0919 |
class Config: <NEW_LINE> <INDENT> __instance = None <NEW_LINE> def __new__(cls, config=None): <NEW_LINE> <INDENT> if config != None: <NEW_LINE> <INDENT> cls.__instance = super(Config, cls).__new__(cls) <NEW_LINE> cls.__instance.style_weights = config.get("style-weights", {}) <NEW_LINE> cls.__instance.variants = config.get("variants", []) <NEW_LINE> paths = config.get("paths", {}) <NEW_LINE> cls.__instance.path_bug_reports_dir = paths.get("bug-reports-directory", "./bug_reports") <NEW_LINE> cls.__instance.path_tmp_files_dir = paths.get("tmp-files-directory", "./tmp_generated_files") <NEW_LINE> <DEDENT> elif cls.__instance == None: <NEW_LINE> <INDENT> raise RuntimeError("Config must be initialized before use") <NEW_LINE> <DEDENT> return cls.__instance <NEW_LINE> <DEDENT> def getStyleProbability(self, style_name): <NEW_LINE> <INDENT> weight = self.style_weights.get(style_name, DEFAULT_STYLE_WEIGHT) <NEW_LINE> weight = _bound(0, 100, weight) <NEW_LINE> return _weightToProbability(weight) <NEW_LINE> <DEDENT> def getStyleValueWeights(self, style_name, value_type="", keyword=None): <NEW_LINE> <INDENT> key_suffix = keyword if keyword != None else "<" + value_type + ">" <NEW_LINE> style_and_type = style_name + ":" + key_suffix <NEW_LINE> weight = self.style_weights.get(style_and_type, DEFAULT_STYLE_VALUE_WEIGHT) <NEW_LINE> return _bound(0, 100000, weight) <NEW_LINE> <DEDENT> def getVariants(self): <NEW_LINE> <INDENT> return self.variants <NEW_LINE> <DEDENT> def getBugReportDirectory(self): <NEW_LINE> <INDENT> return self.path_bug_reports_dir <NEW_LINE> <DEDENT> def getTmpFilesDirectory(self): <NEW_LINE> <INDENT> return self.path_tmp_files_dir | Singleton Class | 6259905223e79379d538d9db |
class DagConRunner(object): <NEW_LINE> <INDENT> def __init__(self, script, mode=None): <NEW_LINE> <INDENT> self.script = script <NEW_LINE> self.mode = mode <NEW_LINE> self.validateSettings() <NEW_LINE> <DEDENT> def validateSettings(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> assert self.script in SCRIPT_CHOICES <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise ValueError("Script is not a recognized DagCon script!") <NEW_LINE> <DEDENT> if self.script == 'gcon.py': <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> assert self.mode in MODE_CHOICES <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise ValueError("Gcon.py runners must specify mode 'r' or 'd'") <NEW_LINE> <DEDENT> <DEDENT> self.executable = which( self.script ) <NEW_LINE> <DEDENT> def runGcon(self, inputFile, outputFile, refFile=None): <NEW_LINE> <INDENT> if outputFile is None: <NEW_LINE> <INDENT> outputFile = self.getOutputFileName( inputFile ) <NEW_LINE> <DEDENT> if self.mode == 'r': <NEW_LINE> <INDENT> assert refFile is not None <NEW_LINE> p = subprocess.Popen( [self.executable, self.mode, inputFile, refFile, '-o', outputFile] ) <NEW_LINE> p.wait() <NEW_LINE> <DEDENT> elif self.mode == 'd': <NEW_LINE> <INDENT> p = subprocess.Popen( [self.executable, self.mode, inputFile, '-o', outputFile] ) <NEW_LINE> p.wait() <NEW_LINE> <DEDENT> return outputFile <NEW_LINE> <DEDENT> def getOutputFile(self, inputFile): <NEW_LINE> <INDENT> path, filename = os.path.split( inputFile ) <NEW_LINE> root, ext = os.path.splitext( filename ) <NEW_LINE> outputFile = root + '_consensus.fa' <NEW_LINE> return os.path.join( path, outputFile ) <NEW_LINE> <DEDENT> def __call__(self, inputFile, refFile=None): <NEW_LINE> <INDENT> outputFile = self.getOutputFile( inputFile ) <NEW_LINE> if os.path.exists( outputFile ): <NEW_LINE> <INDENT> return outputFile <NEW_LINE> <DEDENT> elif self.script == 'gcon.py': <NEW_LINE> <INDENT> return self.runGcon( inputFile, outputFile, refFile ) | A tool for resequencing clusters of rDNA sequences with
the Gcon.py script from PB-DagCon | 625990522ae34c7f260ac5c6 |
class RowPacker(Packer): <NEW_LINE> <INDENT> def pack(self, blocks): <NEW_LINE> <INDENT> self.mapping = {} <NEW_LINE> num_rows, _ = factor(len(blocks)) <NEW_LINE> rows = [[] for _ in range(num_rows)] <NEW_LINE> for block in blocks: <NEW_LINE> <INDENT> min_row = min(rows, key=lambda row: sum(b.width for b in row)) <NEW_LINE> min_row.append(block) <NEW_LINE> <DEDENT> y = 0 <NEW_LINE> for row in rows: <NEW_LINE> <INDENT> x = 0 <NEW_LINE> for block in row: <NEW_LINE> <INDENT> self.mapping[block] = (x, y) <NEW_LINE> x += block.width + self.margin <NEW_LINE> <DEDENT> y += max(block.height for block in row) + self.margin | Packs blocks into rows, greedily trying to minimize the maximum width. | 62599052dc8b845886d54aa3 |
class PreprocessedTestWebIDLFile(SandboxDerived): <NEW_LINE> <INDENT> __slots__ = ( 'basename', ) <NEW_LINE> def __init__(self, sandbox, path): <NEW_LINE> <INDENT> SandboxDerived.__init__(self, sandbox) <NEW_LINE> self.basename = path | Describes an individual test-only .webidl source file that requires
preprocessing. | 625990524e4d5625663738e7 |
class NATRule: <NEW_LINE> <INDENT> def __init__(self, core_client): <NEW_LINE> <INDENT> self.__cc = core_client <NEW_LINE> <DEDENT> def __post(self, endpoint, package="", uid="", params={}): <NEW_LINE> <INDENT> payload = { 'package': package } <NEW_LINE> if uid: <NEW_LINE> <INDENT> payload['uid'] = uid <NEW_LINE> <DEDENT> if params: <NEW_LINE> <INDENT> payload = self.__cc.merge_payloads(payload, params) <NEW_LINE> <DEDENT> return self.__cc.http_post(endpoint, payload=payload) <NEW_LINE> <DEDENT> def add(self, package="", position="", params={}): <NEW_LINE> <INDENT> payload = { 'package': package, 'position': position } <NEW_LINE> if params: <NEW_LINE> <INDENT> payload = self.__cc.merge_payloads(payload, params) <NEW_LINE> <DEDENT> return self.__cc.http_post('add-nat-rule', payload=payload) <NEW_LINE> <DEDENT> def show(self, package="", uid="", params={}): <NEW_LINE> <INDENT> return self.__post('show-nat-rule', package, uid, params) <NEW_LINE> <DEDENT> def set(self, package="", uid="", params={}): <NEW_LINE> <INDENT> return self.__post('set-nat-rule', package, uid, params) <NEW_LINE> <DEDENT> def delete(self, package="", uid="", params={}): <NEW_LINE> <INDENT> return self.__post('delete-nat-rule', package, uid, params) <NEW_LINE> <DEDENT> def show_all(self, package="", params={}): <NEW_LINE> <INDENT> payload = { 'package': package } <NEW_LINE> if params: <NEW_LINE> <INDENT> payload = self.__cc.merge_payloads(payload, params) <NEW_LINE> <DEDENT> return self.__cc.http_post('show-nat-rulebase', payload=payload) | Manage NAT rules. | 625990523539df3088ecd786 |
class NjuUiaAuth: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.session = requests.Session() <NEW_LINE> self.session.headers.update({ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:56.0) Gecko/20100101 Firefox/56.0' }) <NEW_LINE> r = self.session.get(URL_NJU_UIA_AUTH) <NEW_LINE> self.lt = re.search( r'<input type="hidden" name="lt" value="(.*)"/>', r.text).group(1) <NEW_LINE> self.execution = re.search( r'<input type="hidden" name="execution" value="(.*)"/>', r.text).group(1) <NEW_LINE> self._eventId = re.search( r'<input type="hidden" name="_eventId" value="(.*)"/>', r.text).group(1) <NEW_LINE> self.rmShown = re.search( r'<input type="hidden" name="rmShown" value="(.*)"', r.text).group(1) <NEW_LINE> self.pwdDefaultEncryptSalt = re.search( r'<input type="hidden" id="pwdDefaultEncryptSalt" value="(.*)"', r.text).group(1) <NEW_LINE> <DEDENT> def getCaptchaCode(self): <NEW_LINE> <INDENT> url = 'https://authserver.nju.edu.cn/authserver/captcha.html' <NEW_LINE> res = self.session.get(url, stream=True) <NEW_LINE> return BytesIO(res.content) <NEW_LINE> <DEDENT> def parsePassword(self, password): <NEW_LINE> <INDENT> random_iv = ''.join(random.sample((string.ascii_letters + string.digits) * 10, 16)) <NEW_LINE> random_str = ''.join(random.sample((string.ascii_letters + string.digits) * 10, 64)) <NEW_LINE> data = random_str + password <NEW_LINE> key = self.pwdDefaultEncryptSalt.encode("utf-8") <NEW_LINE> iv = random_iv.encode("utf-8") <NEW_LINE> bs = AES.block_size <NEW_LINE> pad = lambda s: s + (bs - len(s) % bs) * chr(bs - len(s) % bs) <NEW_LINE> cipher = AES.new(key, AES.MODE_CBC, iv) <NEW_LINE> data = cipher.encrypt(pad(data).encode("utf-8")) <NEW_LINE> return base64.b64encode(data).decode("utf-8") <NEW_LINE> <DEDENT> def needCaptcha(self, username): <NEW_LINE> <INDENT> url = 'https://authserver.nju.edu.cn/authserver/needCaptcha.html?username={}'.format( username) <NEW_LINE> r = self.session.post(url) <NEW_LINE> if 'true' in r.text: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def login(self, username, password, captchaResponse=""): <NEW_LINE> <INDENT> data = { 'username': username, 'password': self.parsePassword(password), 'lt': self.lt, 'dllt': 'userNamePasswordLogin', 'execution': self.execution, '_eventId': self._eventId, 'rmShown': self.rmShown, 'captchaResponse': captchaResponse, "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit 537.36 (KHTML, like Gecko) Chrome" } <NEW_LINE> r = self.session.post(URL_NJU_UIA_AUTH, data=data, allow_redirects=False) <NEW_LINE> return r.status_code == 302 | DESCRIPTION:
Designed for passing Unified Identity Authentication(UIA) of Nanjing University. | 6259905291af0d3eaad3b309 |
class P9_EliasGammaCoding: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def elias_gamma_list_encode(L): <NEW_LINE> <INDENT> answer = "" <NEW_LINE> for x in L: <NEW_LINE> <INDENT> answer += stringextra.elias_gamma_encode(x) <NEW_LINE> <DEDENT> return answer <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def elias_gamma_list_decode(s): <NEW_LINE> <INDENT> answer = [] <NEW_LINE> i = 0 <NEW_LINE> length_s = len(s) <NEW_LINE> while (i < length_s): <NEW_LINE> <INDENT> decoding, i = stringextra.elias_gamma_decode(s, i, True) <NEW_LINE> answer.append(decoding) <NEW_LINE> <DEDENT> return answer | L is a list of n integers. Write an encode function that returns
a string representing the concatenation of the Elias gamma codes
for L, and a decode function that takes a string s, generated
by the encode function, and returns the array that was passed to
the encode function. | 62599052498bea3a75a59006 |
class InvalidContentType(NeutronException): <NEW_LINE> <INDENT> message = _("Invalid content type %(content_type)s.") | An error due to invalid content type.
:param content_type: The invalid content type. | 62599052d7e4931a7ef3d55e |
class TestCompareXLSXFiles(ExcelComparisonTest): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.maxDiff = None <NEW_LINE> filename = 'default_row03.xlsx' <NEW_LINE> test_dir = 'xlsxwriter/test/comparison/' <NEW_LINE> self.got_filename = test_dir + '_test_' + filename <NEW_LINE> self.exp_filename = test_dir + 'xlsx_files/' + filename <NEW_LINE> self.ignore_files = [] <NEW_LINE> self.ignore_elements = {} <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.set_default_row(24, 1) <NEW_LINE> worksheet.write('A1', 'Foo') <NEW_LINE> worksheet.write('A10', 'Bar') <NEW_LINE> for row in range(1, 8 + 1): <NEW_LINE> <INDENT> worksheet.set_row(row, 24) <NEW_LINE> <DEDENT> workbook.close() <NEW_LINE> self.assertExcelEqual() | Test file created by XlsxWriter against a file created by Excel. | 62599052462c4b4f79dbcee5 |
class DebugConf(object): <NEW_LINE> <INDENT> trace = False <NEW_LINE> memory_summary = True <NEW_LINE> top_k = 3 <NEW_LINE> interval_s = 50 | Make Debug config, user could re-set it. | 6259905207d97122c421818a |
class SensorList(ApiList): <NEW_LINE> <INDENT> API_NAME = "sensors" <NEW_LINE> API_NAME_SRC = "sensor_list" <NEW_LINE> API_SIMPLE = {} <NEW_LINE> API_COMPLEX = {"cache_info": "CacheInfo"} <NEW_LINE> API_CONSTANTS = {} <NEW_LINE> API_STR_ADD = [] <NEW_LINE> API_ITEM_ATTR = "sensor" <NEW_LINE> API_ITEM_CLS = "Sensor" | Automagically generated API array object. | 6259905299cbb53fe68323cb |
class LazyObject(object): <NEW_LINE> <INDENT> _wrapped = None <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self._wrapped = empty <NEW_LINE> <DEDENT> __getattr__ = new_method_proxy(getattr) <NEW_LINE> def __setattr__(self, name, value): <NEW_LINE> <INDENT> if name == "_wrapped": <NEW_LINE> <INDENT> self.__dict__["_wrapped"] = value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self._wrapped is empty: <NEW_LINE> <INDENT> self._setup() <NEW_LINE> <DEDENT> setattr(self._wrapped, name, value) <NEW_LINE> <DEDENT> <DEDENT> def __delattr__(self, name): <NEW_LINE> <INDENT> if name == "_wrapped": <NEW_LINE> <INDENT> raise TypeError("can't delete _wrapped.") <NEW_LINE> <DEDENT> if self._wrapped is empty: <NEW_LINE> <INDENT> self._setup() <NEW_LINE> <DEDENT> delattr(self._wrapped, name) <NEW_LINE> <DEDENT> def _setup(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> __dir__ = new_method_proxy(dir) <NEW_LINE> @new_method_proxy <NEW_LINE> def __getitem__(self, key): <NEW_LINE> <INDENT> return self[key] <NEW_LINE> <DEDENT> @new_method_proxy <NEW_LINE> def __setitem__(self, key, value): <NEW_LINE> <INDENT> self[key] = value <NEW_LINE> <DEDENT> @new_method_proxy <NEW_LINE> def __delitem__(self, key): <NEW_LINE> <INDENT> del self[key] | A wrapper for another class that can be used to delay instantiation of the
wrapped class.
By subclassing, you have the opportunity to intercept and alter the
instantiation. If you don't need to do that, use SimpleLazyObject. | 625990520fa83653e46f63c5 |
class StationError(RuntimeError): <NEW_LINE> <INDENT> pass | Mismatching station name on commandline compared to config or wrong station. | 6259905216aa5153ce4019c8 |
class Describe_PhysPkgReader(object): <NEW_LINE> <INDENT> def it_constructs_ZipPkgReader_when_pkg_is_file_like( self, _ZipPkgReader_, zip_pkg_reader_ ): <NEW_LINE> <INDENT> _ZipPkgReader_.return_value = zip_pkg_reader_ <NEW_LINE> file_like_pkg = BytesIO(b"pkg-bytes") <NEW_LINE> phys_reader = _PhysPkgReader.factory(file_like_pkg) <NEW_LINE> _ZipPkgReader_.assert_called_once_with(file_like_pkg) <NEW_LINE> assert phys_reader is zip_pkg_reader_ <NEW_LINE> <DEDENT> def and_it_constructs_DirPkgReader_when_pkg_is_a_dir(self, request): <NEW_LINE> <INDENT> dir_pkg_reader_ = instance_mock(request, _DirPkgReader) <NEW_LINE> _DirPkgReader_ = class_mock( request, "pptx.opc.serialized._DirPkgReader", return_value=dir_pkg_reader_ ) <NEW_LINE> phys_reader = _PhysPkgReader.factory(dir_pkg_path) <NEW_LINE> _DirPkgReader_.assert_called_once_with(dir_pkg_path) <NEW_LINE> assert phys_reader is dir_pkg_reader_ <NEW_LINE> <DEDENT> def and_it_constructs_ZipPkgReader_when_pkg_is_a_zip_file_path( self, _ZipPkgReader_, zip_pkg_reader_ ): <NEW_LINE> <INDENT> _ZipPkgReader_.return_value = zip_pkg_reader_ <NEW_LINE> pkg_file_path = test_pptx_path <NEW_LINE> phys_reader = _PhysPkgReader.factory(pkg_file_path) <NEW_LINE> _ZipPkgReader_.assert_called_once_with(pkg_file_path) <NEW_LINE> assert phys_reader is zip_pkg_reader_ <NEW_LINE> <DEDENT> def but_it_raises_when_pkg_path_is_not_a_package(self): <NEW_LINE> <INDENT> with pytest.raises(PackageNotFoundError) as e: <NEW_LINE> <INDENT> _PhysPkgReader.factory("foobar") <NEW_LINE> <DEDENT> assert str(e.value) == "Package not found at 'foobar'" <NEW_LINE> <DEDENT> @pytest.fixture <NEW_LINE> def zip_pkg_reader_(self, request): <NEW_LINE> <INDENT> return instance_mock(request, _ZipPkgReader) <NEW_LINE> <DEDENT> @pytest.fixture <NEW_LINE> def _ZipPkgReader_(self, request): <NEW_LINE> <INDENT> return class_mock(request, "pptx.opc.serialized._ZipPkgReader") | Unit-test suite for `pptx.opc.serialized._PhysPkgReader` objects. | 625990524e4d5625663738e9 |
class TagName(object): <NEW_LINE> <INDENT> def __init__(self, name, options, desc, plural=None, role=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.desc = desc <NEW_LINE> self.plural = plural <NEW_LINE> self.user = "u" in options <NEW_LINE> self.internal = "i" in options <NEW_LINE> self.numeric = "n" in options <NEW_LINE> self.machine = "m" in options <NEW_LINE> self.has_sort = "s" in options <NEW_LINE> self.has_roles = "r" in options <NEW_LINE> self.hidden = "h" in options <NEW_LINE> self.role = role <NEW_LINE> assert self.user or self.internal or self.numeric <NEW_LINE> assert not (set(options) - set("uinmshr")) <NEW_LINE> if self.has_roles: <NEW_LINE> <INDENT> assert self.internal <NEW_LINE> <DEDENT> if self.has_sort: <NEW_LINE> <INDENT> assert self.user or self.internal <NEW_LINE> <DEDENT> if self.machine: <NEW_LINE> <INDENT> assert self.user <NEW_LINE> <DEDENT> if self.hidden: <NEW_LINE> <INDENT> assert self.user + self.internal == 1 <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "%s(%r)" % (type(self).__name__, vars(self)) | Text:
desc -- translated description
plural -- translated plural description or None
role -- translated role description (for people tags)
Types:
user -- user editable tag e.g. "foo"
hidden -- if user tag should only be shown in the tag editor (e.g.
tracknumber is hidden, since ~#track/~#tracks are more
useful for displaying)
has_sort -- has a sort user variant e.g. "foosort"
machine -- user tag is not human readable. Something people might
want to hide in the tag editor.
internal -- generated by QL e.g. "~foo"
hidden -- if it is replaced by another tag (for backwards compat)
has_sort -- has a sort user variant e.g. "~foosort"
has_roles -- has a roles variant e.g. "~foo:roles"
numeric -- e.g. "~#foo" | 625990524e696a045264e893 |
class NSGroupInfo(object): <NEW_LINE> <INDENT> swagger_types = { 'nsgroup_policy_path': 'str', 'nsgroup': 'ResourceReference' } <NEW_LINE> attribute_map = { 'nsgroup_policy_path': 'nsgroup_policy_path', 'nsgroup': 'nsgroup' } <NEW_LINE> def __init__(self, nsgroup_policy_path=None, nsgroup=None): <NEW_LINE> <INDENT> self._nsgroup_policy_path = None <NEW_LINE> self._nsgroup = None <NEW_LINE> self.discriminator = None <NEW_LINE> if nsgroup_policy_path is not None: <NEW_LINE> <INDENT> self.nsgroup_policy_path = nsgroup_policy_path <NEW_LINE> <DEDENT> if nsgroup is not None: <NEW_LINE> <INDENT> self.nsgroup = nsgroup <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def nsgroup_policy_path(self): <NEW_LINE> <INDENT> return self._nsgroup_policy_path <NEW_LINE> <DEDENT> @nsgroup_policy_path.setter <NEW_LINE> def nsgroup_policy_path(self, nsgroup_policy_path): <NEW_LINE> <INDENT> self._nsgroup_policy_path = nsgroup_policy_path <NEW_LINE> <DEDENT> @property <NEW_LINE> def nsgroup(self): <NEW_LINE> <INDENT> return self._nsgroup <NEW_LINE> <DEDENT> @nsgroup.setter <NEW_LINE> def nsgroup(self, nsgroup): <NEW_LINE> <INDENT> self._nsgroup = nsgroup <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(NSGroupInfo, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, NSGroupInfo): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62599052a8ecb033258726f9 |
class APIError(Exception): <NEW_LINE> <INDENT> pass | Raised when something went wrong on the server
| 625990527d847024c075d8bd |
class NewGroupDialog(_BaseGroupDialog): <NEW_LINE> <INDENT> new_aov_group_signal = QtCore.Signal(AOVGroup) <NEW_LINE> def __init__(self, parent=None): <NEW_LINE> <INDENT> super().__init__(parent) <NEW_LINE> self.status_widget.add_info(0, "Enter a group name") <NEW_LINE> self.status_widget.add_info(1, "Choose a file") <NEW_LINE> self.status_widget.add_info(2, "Select AOVs for group") <NEW_LINE> self.priority.valueChanged.connect(self.validate_group_name) <NEW_LINE> self.enable_creation(False) <NEW_LINE> self.setWindowTitle("Create AOV Group") <NEW_LINE> <DEDENT> def _additional_group_name_validation(self, group_name): <NEW_LINE> <INDENT> if group_name in manager.AOV_MANAGER.groups: <NEW_LINE> <INDENT> group = manager.AOV_MANAGER.groups[group_name] <NEW_LINE> priority = self.priority.value() <NEW_LINE> if priority > group.priority: <NEW_LINE> <INDENT> msg = f"This definition will have priority for {group_name}" <NEW_LINE> self.status_widget.add_info(0, msg) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> msg = ( f"Group {group_name} already exists with priority {group.priority}" ) <NEW_LINE> self.status_widget.add_warning(0, msg) <NEW_LINE> <DEDENT> <DEDENT> super()._additional_group_name_validation(group_name) <NEW_LINE> <DEDENT> def accept(self): <NEW_LINE> <INDENT> group_name = str(self.group_name.text()) <NEW_LINE> group = AOVGroup(group_name) <NEW_LINE> group.path = os.path.expandvars(self.file_widget.get_path()) <NEW_LINE> self.build_group_from_ui(group) <NEW_LINE> aov_file = manager.AOVFile(group.path) <NEW_LINE> aov_file.add_group(group) <NEW_LINE> aov_file.write_to_file() <NEW_LINE> self.new_aov_group_signal.emit(group) <NEW_LINE> return super().accept() | Dialog for creating a new AOV group. | 62599052498bea3a75a59008 |
class TodoDetail(DetailGenericAPIView): <NEW_LINE> <INDENT> queryset = Todos.objects.all().filter(status=UNDO) <NEW_LINE> serializer_class = Serializer | Retrieve, update or delete a task. | 62599052004d5f362081fa5d |
class L1_Root_pt(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "object.l1_root_pt" <NEW_LINE> bl_label = "L1 Root" <NEW_LINE> bl_options = {'REGISTER', 'UNDO'} <NEW_LINE> @classmethod <NEW_LINE> def poll(cls, context): <NEW_LINE> <INDENT> found = 'L1 Root' in bpy.data.objects <NEW_LINE> if found == False: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if found == True: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def execute(self, context): <NEW_LINE> <INDENT> CriaPontoDef('L1 Root', 'Anatomical Points - Mandible') <NEW_LINE> TestaPontoCollDef() <NEW_LINE> return {'FINISHED'} | Tooltip | 62599052435de62698e9d2e5 |
class Img_Block(QFrame): <NEW_LINE> <INDENT> def __init__(self, Img_list, *args, **kwargs): <NEW_LINE> <INDENT> QFrame.__init__(self, *args, **kwargs) <NEW_LINE> hv = QHBoxLayout(self) <NEW_LINE> self.Imgs = Img_list <NEW_LINE> WB = Img_list[0] <NEW_LINE> BG = Img_list[1] <NEW_LINE> self.WB = LabeledImg(WB, self) <NEW_LINE> self.BG = LabeledImg(BG, self) <NEW_LINE> self.BG.Img.Action_Type = "BKGD" <NEW_LINE> self.BG.Img.Allowed_Indicator_Num = 5 <NEW_LINE> hv.addWidget(self.WB) <NEW_LINE> hv.addWidget(self.BG) <NEW_LINE> self.layout = hv <NEW_LINE> self.Single_Connect() <NEW_LINE> <DEDENT> def Single_Connect(self): <NEW_LINE> <INDENT> self.WB.Syncing.connect(self.BG.LabeledImg_Sync) <NEW_LINE> self.BG.Syncing.connect(self.WB.LabeledImg_Sync) <NEW_LINE> self.WB.Img.Indicator_Add.connect( self.BG.Img.Connection_SRC_Indicator_to_Temp) <NEW_LINE> self.BG.Img.Indicator_Add.connect( self.WB.Img.Connection_SRC_Indicator_to_Temp) <NEW_LINE> <DEDENT> def Sync_from_toobar(self, Tb): <NEW_LINE> <INDENT> print("Syncing from Toolbar") <NEW_LINE> x, y, w, h = Tb.Crop.Input_x.Value(), Tb.Crop.Input_y.Value( ), Tb.Crop.Input_w.Value(), Tb.Crop.Input_h.Value() <NEW_LINE> mw, mh = Tb.Marker.Input_w.Value(), Tb.Marker.Input_h.Value() <NEW_LINE> Angle = Tb.Rotation.Value() <NEW_LINE> Flip_H = Tb.Flip_H.isChecked() <NEW_LINE> Flip_V = Tb.Flip_V.isChecked() <NEW_LINE> Scale_Factor = self.WB.Img.Scale_Factor <NEW_LINE> self.WB.Img.Display_Img(Scale_Factor, Angle, Flip_H, Flip_V) <NEW_LINE> self.BG.Img.Display_Img(Scale_Factor, Angle, Flip_H, Flip_V) <NEW_LINE> for i in self.WB.Img.Indicator: <NEW_LINE> <INDENT> i.Set_Acture_Pos(x, y, w, h) <NEW_LINE> <DEDENT> for i in self.BG.Img.Indicator: <NEW_LINE> <INDENT> i.Set_Acture_Size(mw, mh) <NEW_LINE> <DEDENT> <DEDENT> def Pack_Info(self): <NEW_LINE> <INDENT> info = {} <NEW_LINE> info['filename'] = self.WB.Img.FileName <NEW_LINE> info['rotation'] = self.WB.Img.Angle <NEW_LINE> info['Flip_h'] = self.WB.Img.Flip_H <NEW_LINE> info['Flip_v'] = self.WB.Img.Flip_V <NEW_LINE> info['crop'] = [] <NEW_LINE> info['markers'] = [] <NEW_LINE> crops = [i for i in self.WB.Img.Indicator if i.Active] <NEW_LINE> markers = [i for i in self.BG.Img.Indicator if i.Active] <NEW_LINE> for i in crops: <NEW_LINE> <INDENT> info['crop'].append({'name': i.Name.text(), 'pos': i.Acture_Pos()}) <NEW_LINE> <DEDENT> for i in markers: <NEW_LINE> <INDENT> info['markers'].append({ 'name': i.Name.text(), 'pos': i.Acture_Pos() }) <NEW_LINE> <DEDENT> info['src_img'] = self.WB.Img.Src_Img <NEW_LINE> return info <NEW_LINE> <DEDENT> def mousePressEvent(self, event): <NEW_LINE> <INDENT> print("Img_Box is clicked") | Assign two picture
同步两个图片的设置情况 | 6259905221a7993f00c67450 |
class Comment(Model): <NEW_LINE> <INDENT> def __init__(self, form, user_id=-1): <NEW_LINE> <INDENT> super().__init__(form) <NEW_LINE> self.content = form.get('content', '') <NEW_LINE> self.user_id = form.get('user_id', user_id) <NEW_LINE> self.weibo_id = int(form.get('weibo_id', -1)) <NEW_LINE> <DEDENT> def user(self): <NEW_LINE> <INDENT> u = User.find_by(id=self.user_id) <NEW_LINE> return u <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def add(cls, form, user_id, username, weibo_id): <NEW_LINE> <INDENT> c = Comment(form) <NEW_LINE> c.user_id = user_id <NEW_LINE> c.weibo_id = weibo_id <NEW_LINE> c.username = username <NEW_LINE> c.save() <NEW_LINE> return c <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def update(cls, form): <NEW_LINE> <INDENT> comment_id = int(form['id']) <NEW_LINE> c = Comment.find_by(id=comment_id) <NEW_LINE> c.content = form['content'] <NEW_LINE> c.save() <NEW_LINE> return c | 评论类 | 6259905230dc7b76659a0cf0 |
class AttentionPool(nn.Module): <NEW_LINE> <INDENT> def __init__(self, hidden_size, drop=0.0): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.fc = nn.Sequential(nn.Linear(hidden_size, 1), nn.ReLU()) <NEW_LINE> self.dropout = nn.Dropout(drop) <NEW_LINE> <DEDENT> def forward(self, input_, mask=None): <NEW_LINE> <INDENT> score = self.fc(input_).squeeze(-1) <NEW_LINE> if mask is not None: <NEW_LINE> <INDENT> mask = mask.to(dtype=input_.dtype) * -1e4 <NEW_LINE> score = score + mask <NEW_LINE> <DEDENT> norm_score = self.dropout(F.softmax(score, dim=1)) <NEW_LINE> output = norm_score.unsqueeze(1).matmul(input_).squeeze(1) <NEW_LINE> return output | attention pooling layer | 62599052f7d966606f749329 |
class UserInstruments(object): <NEW_LINE> <INDENT> openapi_types = { } <NEW_LINE> attribute_map = { } <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.discriminator = None <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.openapi_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, UserInstruments): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually. | 6259905271ff763f4b5e8c91 |
class RoundRobinQueue: <NEW_LINE> <INDENT> def __init__(self, qfactory: Callable[[Hashable], BaseQueue], start_domains: Iterable[Hashable] = ()) -> None: <NEW_LINE> <INDENT> self.queues = {} <NEW_LINE> self.qfactory = qfactory <NEW_LINE> for key in start_domains: <NEW_LINE> <INDENT> self.queues[key] = self.qfactory(key) <NEW_LINE> <DEDENT> self.key_queue = deque(start_domains) <NEW_LINE> <DEDENT> def push(self, obj: Any, key: Hashable) -> None: <NEW_LINE> <INDENT> if key not in self.key_queue: <NEW_LINE> <INDENT> self.queues[key] = self.qfactory(key) <NEW_LINE> self.key_queue.appendleft(key) <NEW_LINE> <DEDENT> q = self.queues[key] <NEW_LINE> q.push(obj) <NEW_LINE> <DEDENT> def peek(self) -> Optional[Any]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> key = self.key_queue[-1] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.queues[key].peek() <NEW_LINE> <DEDENT> def pop(self) -> Optional[Any]: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> key = self.key_queue.pop() <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> q = self.queues[key] <NEW_LINE> m = q.pop() <NEW_LINE> if len(q) == 0: <NEW_LINE> <INDENT> del self.queues[key] <NEW_LINE> q.close() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.key_queue.appendleft(key) <NEW_LINE> <DEDENT> if m: <NEW_LINE> <INDENT> return m <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def close(self) -> List[Hashable]: <NEW_LINE> <INDENT> active = [] <NEW_LINE> for k, q in self.queues.items(): <NEW_LINE> <INDENT> if len(q): <NEW_LINE> <INDENT> active.append(k) <NEW_LINE> <DEDENT> q.close() <NEW_LINE> <DEDENT> return active <NEW_LINE> <DEDENT> def __len__(self) -> int: <NEW_LINE> <INDENT> return sum(len(x) for x in self.queues.values()) if self.queues else 0 | A round robin queue implemented using multiple internal queues (typically,
FIFO queues). The internal queue must implement the following methods:
* push(obj)
* pop()
* peek()
* close()
* __len__()
The constructor receives a qfactory argument, which is a callable used to
instantiate a new (internal) queue when a new key is allocated. The
qfactory function is called with the key number as first and only argument.
start_domains is a sequence of domains to initialize the queue with. If the
queue was previously closed leaving some domain buckets non-empty, those
domains should be passed in start_domains.
The queue maintains a fifo queue of keys. The key that went last is popped
first and the next queue for that key is then popped. | 6259905224f1403a92686341 |
class EmailWhitelistItem(models.Model): <NEW_LINE> <INDENT> email_address = models.EmailField() <NEW_LINE> reason = models.TextField(blank=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.email_address | The email whitelist is a list of author email addresses to blindly accept comments from. | 62599052379a373c97d9a509 |
class InterfaceField: <NEW_LINE> <INDENT> def __init__(self, type_pattern=typing.Any, tests=None): <NEW_LINE> <INDENT> err_msg = f"Expected 'type_pattern' to be a type or a typing pattern but got {type(type_pattern)}" <NEW_LINE> assert issubclass(type(type_pattern), type(type)) or issubclass( type(type_pattern), typing._Final), err_msg <NEW_LINE> self.type_pattern = type_pattern <NEW_LINE> self.wrapping_phase = True <NEW_LINE> tests = [] if tests is None else tests <NEW_LINE> self.tests = tests if isinstance(tests, Iterable) else [tests] <NEW_LINE> <DEDENT> def update_value(self, name, value, config_class): <NEW_LINE> <INDENT> check_type(name, value, self.type_pattern) <NEW_LINE> for test in self.tests: <NEW_LINE> <INDENT> self._check_test(test, name, value, config_class) <NEW_LINE> <DEDENT> self.value = value <NEW_LINE> return self if self.wrapping_phase else value <NEW_LINE> <DEDENT> def finish_wrapping_phase(self, name, config_class): <NEW_LINE> <INDENT> inner_key = name.split('.')[-1] <NEW_LINE> err_msg = f"The field '{inner_key}' in '{config_class}' is required to be overridden" <NEW_LINE> assert hasattr(self, 'value'), err_msg <NEW_LINE> self.wrapping_phase = False <NEW_LINE> return self.value <NEW_LINE> <DEDENT> def _check_test(self, test, name, value, config_class): <NEW_LINE> <INDENT> test_file = Path(inspect.getsourcefile(test)).absolute() <NEW_LINE> line_number = inspect.getsourcelines(test)[-1] <NEW_LINE> base_err_msg = ( f"Can't set '{name} = {value}' for config '{config_class}'. Its test defined in '{test_file}' " f"at line {line_number}") <NEW_LINE> try: <NEW_LINE> <INDENT> test_result = test(value) <NEW_LINE> err_msg = f"Test failed. Expected return type to be boolean but was {type(test_result)}" <NEW_LINE> assert test_result in [True, False], err_msg <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> exception_class = type(e) <NEW_LINE> err_msg = f"{base_err_msg} raised the exception: \n{str(e)}" <NEW_LINE> raise exception_class(err_msg) from None <NEW_LINE> <DEDENT> assert test_result, f"{base_err_msg} didn't pass" | Used to define allowed values for a config-attribute | 62599052dd821e528d6da3c2 |
class AdminUserList(Resource): <NEW_LINE> <INDENT> @api.doc(security='apikey') <NEW_LINE> @admin_required <NEW_LINE> def get(self): <NEW_LINE> <INDENT> res = user.get_all_user() <NEW_LINE> return res | Contains GET method for Admin Endpoint | 625990520c0af96317c577d3 |
class BatchPerformanceLoggerBase(Base, Callback): <NEW_LINE> <INDENT> def __init__(self, batch_generator, metrics_name_postfix="unknown", inspect_period = 2000, init_iter = -1, **kwargs): <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> self._batch_generator = batch_generator <NEW_LINE> self._metrics_name_postfix = metrics_name_postfix <NEW_LINE> self._inspect_period = inspect_period <NEW_LINE> self._iter = init_iter <NEW_LINE> <DEDENT> def on_batch_end(self, batch, logs=None): <NEW_LINE> <INDENT> self._iter += 1 <NEW_LINE> generated_batch_data = self._generate_batch() <NEW_LINE> predicted_batch_data = self._predict_model(generated_batch_data) <NEW_LINE> batch_metrics_data = self._calc_performance(generated_batch_data, predicted_batch_data) <NEW_LINE> self._log_metrics(batch_metrics_data, logs) <NEW_LINE> if (self._iter > 0) and (self._inspect_period > 0) and (self._iter % self._inspect_period == 0): <NEW_LINE> <INDENT> self._inspect_data(generated_batch_data, predicted_batch_data, batch_metrics_data) <NEW_LINE> <DEDENT> <DEDENT> def _generate_batch(self): <NEW_LINE> <INDENT> return next(self._batch_generator) <NEW_LINE> <DEDENT> def _predict_model(self, batch_data): <NEW_LINE> <INDENT> self._log.error("Please implement this method") <NEW_LINE> <DEDENT> def _calc_performance(self, generated_batch_data, predicted_batch_data): <NEW_LINE> <INDENT> self._log.error("Please implement this method") <NEW_LINE> <DEDENT> def _inspect_data(self, generated_batch_data, predicted_batch_data, batch_metrics_data): <NEW_LINE> <INDENT> self._log.error("Please implement this method") <NEW_LINE> <DEDENT> def _log_metrics(self, batch_metrics_data, logs): <NEW_LINE> <INDENT> for metric, value in batch_metrics_data.items(): <NEW_LINE> <INDENT> logs[metric] = value | Abstract method to log batch level metrics (e.g. for a validation set)
Please implement:
_predict_model(batch_data)
_calc_performance(batch_data)
# Only if you want to inspect results during training
_inspect_data( generated_batch_data, predicted_batch_data, batch_metrics_data) | 6259905276e4537e8c3f0a6f |
class HeadingText(MHeadingText, Widget): <NEW_LINE> <INDENT> implements(IHeadingText) <NEW_LINE> level = Int(1) <NEW_LINE> text = Unicode('Default') <NEW_LINE> def __init__(self, parent, **traits): <NEW_LINE> <INDENT> super(HeadingText, self).__init__(**traits) <NEW_LINE> self._create_control(parent) <NEW_LINE> <DEDENT> def _create_control(self, parent): <NEW_LINE> <INDENT> self.control = QtGui.QLabel(parent) <NEW_LINE> self._set_text(self.text) <NEW_LINE> self.control.setFrameShape(QtGui.QFrame.StyledPanel) <NEW_LINE> self.control.setFrameShadow(QtGui.QFrame.Raised) <NEW_LINE> self.control.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed) <NEW_LINE> <DEDENT> def _set_text(self, text): <NEW_LINE> <INDENT> text = "<b>" + text + "</b>" <NEW_LINE> self.control.setText(text) <NEW_LINE> <DEDENT> def _text_changed(self, new): <NEW_LINE> <INDENT> if self.control is not None: <NEW_LINE> <INDENT> self._set_text(new) | The toolkit specific implementation of a HeadingText. See the
IHeadingText interface for the API documentation. | 62599052a79ad1619776b52f |
class linkParser(sgmllib.SGMLParser): <NEW_LINE> <INDENT> def parse(self, s): <NEW_LINE> <INDENT> self.feed(s) <NEW_LINE> self.close() <NEW_LINE> <DEDENT> def __init__(self, verbose=0): <NEW_LINE> <INDENT> sgmllib.SGMLParser.__init__(self, verbose) <NEW_LINE> self.hyperlinks = [] <NEW_LINE> <DEDENT> def start_a(self, attributes): <NEW_LINE> <INDENT> for name, value in attributes: <NEW_LINE> <INDENT> if name == "href": <NEW_LINE> <INDENT> self.hyperlinks.append(value) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_hyperlinks(self): <NEW_LINE> <INDENT> return self.hyperlinks | A simple parser class. | 625990528e71fb1e983bcfae |
class Map(): <NEW_LINE> <INDENT> def __init__(self, url, seed, size, timeout=2): <NEW_LINE> <INDENT> self.request = requests.get(url, timeout=timeout) <NEW_LINE> self.request.raise_for_status() <NEW_LINE> self.cdn_url = 'https://assets-rustserversio.netdna-ssl.com' <NEW_LINE> self.seed = seed <NEW_LINE> self.size = size <NEW_LINE> self.features = self.get_features() <NEW_LINE> self.img_hi_res = f"{self.cdn_url}/maps/{self.seed}-{self.size}-Procedural_Map.jpg" <NEW_LINE> self.img_monuments = f"{self.cdn_url}/maps/{self.seed}-{self.size}-Procedural_Map-lowres-monuments.jpg" <NEW_LINE> <DEDENT> def get_features(self): <NEW_LINE> <INDENT> soup = BeautifulSoup(self.request.text, 'html.parser') <NEW_LINE> media_content = soup.find("div", class_="media-content") <NEW_LINE> features = re.findall(r'\S.*, .*', media_content.text)[0].strip().split(', ') <NEW_LINE> return features[:-2] | Map with details
Attributes:
cdn_url (str): Map image host
features (list): List of map monuments
img_hi_res (str): High resolution map image
img_monuments (str): Map image with monuments
request (requests.models.Response): GET <map URL>
seed (int): Map seed
size (int): Map size | 62599052435de62698e9d2e6 |
class AttentionLayer(nn.Module): <NEW_LINE> <INDENT> def __init__(self, use_language=True, use_spatial=True): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._use_language = use_language <NEW_LINE> self._use_spatial = use_spatial <NEW_LINE> self.fc_subject = nn.Sequential(nn.Linear(300, 256), nn.ReLU()) <NEW_LINE> self.fc_object = nn.Sequential(nn.Linear(300, 256), nn.ReLU()) <NEW_LINE> self.fc_lang = nn.Sequential( nn.Linear(512, 256), nn.ReLU(), nn.Linear(256, 128), nn.ReLU()) <NEW_LINE> self.mask_net = nn.Sequential( nn.Conv2d(2, 32, 5, stride=2, padding=2), nn.ReLU(), nn.Conv2d(32, 64, 5, stride=2, padding=2), nn.ReLU(), nn.Conv2d(64, 128, 8), nn.ReLU()) <NEW_LINE> self.fc_delta = nn.Sequential( nn.Linear(38, 256), nn.ReLU(), nn.Linear(256, 128), nn.ReLU(), nn.Linear(128, 128), nn.ReLU()) <NEW_LINE> self.fc_spatial = nn.Sequential( nn.Linear(256, 128), nn.ReLU(), nn.Linear(128, 128), nn.ReLU()) <NEW_LINE> <DEDENT> def forward(self, subj_embs, obj_embs, deltas, masks): <NEW_LINE> <INDENT> lang_attention, spatial_attention = None, None <NEW_LINE> if self._use_language: <NEW_LINE> <INDENT> lang_attention = self.fc_lang(torch.cat(( self.fc_subject(subj_embs), self.fc_object(obj_embs) ), dim=1)) <NEW_LINE> <DEDENT> if self._use_spatial: <NEW_LINE> <INDENT> spatial_attention = self.fc_spatial(torch.cat(( self.mask_net(masks).view(masks.shape[0], -1), self.fc_delta(deltas) ), dim=1)) <NEW_LINE> <DEDENT> if self._use_language or self._use_spatial: <NEW_LINE> <INDENT> attention = 0 <NEW_LINE> if self._use_language: <NEW_LINE> <INDENT> attention = attention + lang_attention <NEW_LINE> <DEDENT> if self._use_spatial: <NEW_LINE> <INDENT> attention = attention + spatial_attention <NEW_LINE> <DEDENT> return attention <NEW_LINE> <DEDENT> return None | Drive attention using language and/or spatial features. | 6259905245492302aabfd9bc |
class TestStreamSlice(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.stream = StringIO.StringIO('0123456789') <NEW_LINE> <DEDENT> def test_read(self): <NEW_LINE> <INDENT> s = _StreamSlice(self.stream, 0, 4) <NEW_LINE> self.assertEqual('', s.read(0)) <NEW_LINE> self.assertEqual('0', s.read(1)) <NEW_LINE> self.assertEqual('123', s.read()) <NEW_LINE> <DEDENT> def test_read_too_much(self): <NEW_LINE> <INDENT> s = _StreamSlice(self.stream, 1, 4) <NEW_LINE> self.assertEqual('1234', s.read(6)) <NEW_LINE> <DEDENT> def test_read_all(self): <NEW_LINE> <INDENT> s = _StreamSlice(self.stream, 2, 1) <NEW_LINE> self.assertEqual('2', s.read(-1)) | Test _StreamSlice. | 6259905276d4e153a661dced |
class Loader(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.__softwares = {} <NEW_LINE> self.__addons = {} <NEW_LINE> <DEDENT> def addSoftwareInfo(self, softwareName, version, options={}): <NEW_LINE> <INDENT> assert isinstance(options, dict), 'options need to be a dictionary' <NEW_LINE> self.__softwares[softwareName] = { 'version': version, 'options': dict(options) } <NEW_LINE> <DEDENT> def addAddonInfo(self, softwareName, addonName, options={}): <NEW_LINE> <INDENT> assert isinstance(options, dict), 'options need to be a dictionary' <NEW_LINE> if softwareName not in self.__addons: <NEW_LINE> <INDENT> self.__addons[softwareName] = {} <NEW_LINE> <DEDENT> self.__addons[softwareName][addonName] = { 'options': dict(options) } <NEW_LINE> <DEDENT> def softwares(self, env={}): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for softwareName in self.__softwares.keys(): <NEW_LINE> <INDENT> softwareVersion = self.__softwareVersion(softwareName, env) <NEW_LINE> softwareOptions = self.__softwares[softwareName]['options'] <NEW_LINE> software = Software( softwareName, softwareVersion ) <NEW_LINE> self.__setVersionedOptions(software, softwareOptions) <NEW_LINE> self.__addAddonsToSoftware(software, env) <NEW_LINE> result.append(software) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def __softwareVersion(self, name, env): <NEW_LINE> <INDENT> version = self.__softwares[name]['version'] <NEW_LINE> uverName = Versioned.toUverName(name) <NEW_LINE> if uverName in env: <NEW_LINE> <INDENT> version = env[uverName] <NEW_LINE> <DEDENT> return version <NEW_LINE> <DEDENT> def __addAddonsToSoftware(self, software, env): <NEW_LINE> <INDENT> assert isinstance(software, Software), "Invalid software type!" <NEW_LINE> softwareName = software.name() <NEW_LINE> if softwareName in self.__addons: <NEW_LINE> <INDENT> for addonName, addonContent in self.__addons[softwareName].items(): <NEW_LINE> <INDENT> if addonName not in self.__softwares: <NEW_LINE> <INDENT> raise AddonNotFoundError( 'Could not find a version for the addon "{0}"'.format( addonName ) ) <NEW_LINE> <DEDENT> addonVersion = self.__softwareVersion(addonName, env) <NEW_LINE> addonOptions = addonContent['options'] <NEW_LINE> addon = Addon( addonName, addonVersion ) <NEW_LINE> self.__setVersionedOptions(addon, addonOptions) <NEW_LINE> software.addAddon(addon) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __setVersionedOptions(self, versioned, options): <NEW_LINE> <INDENT> assert isinstance(versioned, Versioned), "Invalid versioned type" <NEW_LINE> for optionName, optionValue in options.items(): <NEW_LINE> <INDENT> versioned.setOption(optionName, optionValue) | Abstract loader.
Returns a list of software instances based on the addon and software
information (@see softwares) | 6259905282261d6c5273093c |
class ImageViewer(tk.Frame): <NEW_LINE> <INDENT> def __init__(self, master, img_data, passive=False, attached=True, *args, **kwargs): <NEW_LINE> <INDENT> tk.Frame.__init__(self, master, background='black') <NEW_LINE> self.master = master <NEW_LINE> self.attached=attached <NEW_LINE> self.master.config(bg="black") <NEW_LINE> self.vmin = self.vmax = None <NEW_LINE> self.img = img_data <NEW_LINE> self._create_figure() <NEW_LINE> self._add_img() <NEW_LINE> self._setup_canvas() <NEW_LINE> self._zoom_im = None <NEW_LINE> self._add_range_slider() <NEW_LINE> self._update_clim() <NEW_LINE> <DEDENT> def set_data(self,data): <NEW_LINE> <INDENT> self.ax.images[0].set_data(data) <NEW_LINE> <DEDENT> def _update_clim(self): <NEW_LINE> <INDENT> self.vmin, self.vmax = self.range_slider.minval, self.range_slider.maxval <NEW_LINE> self._im.set_clim( vmin=self.vmin, vmax=self.vmax) <NEW_LINE> self.fig.canvas.draw() <NEW_LINE> self.master.after( 500, self._update_clim ) <NEW_LINE> <DEDENT> def _add_range_slider(self): <NEW_LINE> <INDENT> self.range_slider = RangeSlider( self.master, range_slider_len=400, minval=-100, maxval=1000, bd=0, padx=0, pady=0, background='black') <NEW_LINE> self.range_slider.pack(side=tk.TOP, expand=tk.NO) <NEW_LINE> <DEDENT> def _create_figure(self): <NEW_LINE> <INDENT> self.fig = plt.figure(figsize=(6,6)) <NEW_LINE> self.ax = self.fig.add_axes([0, 0, 1, 1]) <NEW_LINE> self.ax.set_facecolor("black") <NEW_LINE> self.fig.patch.set_visible(False) <NEW_LINE> self.ax.axis('off') <NEW_LINE> <DEDENT> def _add_img(self): <NEW_LINE> <INDENT> self._im = self.ax.imshow(self.img, interpolation='nearest', norm=None, vmin=self.vmin, vmax=self.vmax, cmap='gist_gray') <NEW_LINE> self.vmin,self.vmax = self._im.get_clim() <NEW_LINE> <DEDENT> def _setup_canvas(self): <NEW_LINE> <INDENT> if not self.attached: <NEW_LINE> <INDENT> self.image_frame= tk.Toplevel(self.master) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.image_frame = tk.Frame( self.master, bg="black" ) <NEW_LINE> self.image_frame.pack( side=tk.TOP, expand=tk.YES) <NEW_LINE> <DEDENT> self.disp_frame = tk.Frame(self.image_frame, bg="black") <NEW_LINE> self.disp_frame.pack(side=tk.TOP, expand=tk.YES, fill=tk.BOTH) <NEW_LINE> self.canvas = FigureCanvasTkAgg(self.fig, master=self.disp_frame) <NEW_LINE> self.canvas.get_tk_widget().configure(bg='black', highlightbackgroun="black") <NEW_LINE> self.canvas.get_tk_widget().pack(side=tk.TOP, expand=tk.YES, fill=tk.BOTH) <NEW_LINE> self.toolbar = NavigationToolbar2Tk(self.canvas, self.disp_frame) <NEW_LINE> self.toolbar.update() <NEW_LINE> self.canvas._tkcanvas.pack(side=tk.TOP, expand=tk.YES, fill=tk.BOTH) <NEW_LINE> self.canvas.draw() <NEW_LINE> self.zp = ZoomPan() <NEW_LINE> self.figZoom = self.zp.zoom_factory( self.ax, base_scale=1.1) | Main image viewer ; uses range_slider.py to update clim | 62599052b57a9660fecd2f60 |
class PlaceholderType(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.swaggerTypes = { } <NEW_LINE> self.attributeMap = { } | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 6259905271ff763f4b5e8c93 |
class PairList(list): <NEW_LINE> <INDENT> def __init__(self, *args): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> for arg in args: <NEW_LINE> <INDENT> for element in arg: <NEW_LINE> <INDENT> self.append(element) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def append(self, value: Pair): <NEW_LINE> <INDENT> if isinstance(value, dict): <NEW_LINE> <INDENT> value = Pair(**value) <NEW_LINE> <DEDENT> for index, pair in enumerate(self): <NEW_LINE> <INDENT> if pair.base == value.base and pair.quote == value.quote: <NEW_LINE> <INDENT> self[index] = Pair(**{**pair, **value}) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> super().append(Pair(**value)) | Unique pairs inside this list | 62599052ac7a0e7691f739c6 |
class AppController(Borg): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.click_drag_screen = None <NEW_LINE> self.task_list_screen = None <NEW_LINE> self.timer_screen = None <NEW_LINE> self.screen_controller = None <NEW_LINE> self.timer_screen = None <NEW_LINE> self.timer_task_manager = None <NEW_LINE> self.menu_bar = None <NEW_LINE> self.data_container_registry = list() <NEW_LINE> <DEDENT> def register(self, ref): <NEW_LINE> <INDENT> self.data_container_registry.append(ref) <NEW_LINE> <DEDENT> def _flush(self): <NEW_LINE> <INDENT> to_remove = list() <NEW_LINE> for ref in self.data_container_registry: <NEW_LINE> <INDENT> if ref() is None: <NEW_LINE> <INDENT> to_remove.append(ref) <NEW_LINE> <DEDENT> <DEDENT> for item in to_remove: <NEW_LINE> <INDENT> self.data_container_registry.remove(item) <NEW_LINE> <DEDENT> <DEDENT> def clear_app_data(self): <NEW_LINE> <INDENT> self._flush() <NEW_LINE> for widget in self.data_container_registry: <NEW_LINE> <INDENT> widget().clear_data() <NEW_LINE> <DEDENT> <DEDENT> def load_app_data(self): <NEW_LINE> <INDENT> self._flush() <NEW_LINE> for widget in self.data_container_registry: <NEW_LINE> <INDENT> widget().load_data() | Contains references to important controller objects.
Also contains the registry for object saving and loading. | 62599052596a897236129022 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.