code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class UserViewSet(viewsets.ReadOnlyModelViewSet): <NEW_LINE> <INDENT> queryset = User.objects.all() <NEW_LINE> serializer_class = UserSerializer | This endpoint presents the users in the system.
As you can see, the collection of snippet instances owned by a user are
serialized using a hyperlinked representation. | 62598fbd5fc7496912d48365 |
class Calculator(Process): <NEW_LINE> <INDENT> def __init__(self,userdata_queue, export_queue): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.userdata_queue = userdata_queue <NEW_LINE> self.export_queue = export_queue <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def calculator_social_security(income): <NEW_LINE> <INDENT> if income < config.fund_low: <NEW_LINE> <INDENT> return config.fund_low * config.social_security_ratio <NEW_LINE> <DEDENT> elif income > config.fund_high: <NEW_LINE> <INDENT> return config.fund_high * config.social_security_ratio <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return income * config.social_security_ratio <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def tax(cls, income): <NEW_LINE> <INDENT> taxable_income = income - cls.calculator_social_security(income) - CUTOFF_POINT <NEW_LINE> for item in INCOME_TAX_QUICK_LOOKUP_TABLE: <NEW_LINE> <INDENT> if taxable_income > item.taxable: <NEW_LINE> <INDENT> return taxable_income * item.taxrate - item.quick <NEW_LINE> <DEDENT> <DEDENT> return 0.00 <NEW_LINE> <DEDENT> def payroll(self, userdata_list): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for employee in userdata_list: <NEW_LINE> <INDENT> employee_id, income = employee <NEW_LINE> income = float(income) <NEW_LINE> social_security = Calculator.calculator_social_security(income) <NEW_LINE> tax = Calculator.tax(income) <NEW_LINE> real_income = income - social_security - tax <NEW_LINE> result.append([employee_id, '{:.2f}'.format(income), '{:.2f}'.format(social_security), '{:.2f}'.format(tax), '{:.2f}'.format(real_income)]) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> userdata_list = self.userdata_queue.get(timeout=1) <NEW_LINE> <DEDENT> except queue.Empty: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> result = self.payroll(userdata_list) <NEW_LINE> self.export_queue.put(result) | 计算结果类 | 62598fbdfff4ab517ebcd9b8 |
class ReflexAgent(Agent): <NEW_LINE> <INDENT> def getAction(self, gameState): <NEW_LINE> <INDENT> legalMoves = gameState.getLegalActions() <NEW_LINE> scores = [self.evaluationFunction(gameState, action) for action in legalMoves] <NEW_LINE> bestScore = max(scores) <NEW_LINE> bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] <NEW_LINE> chosenIndex = random.choice(bestIndices) <NEW_LINE> "Add more of your code here if you want to" <NEW_LINE> return legalMoves[chosenIndex] <NEW_LINE> <DEDENT> def evaluationFunction(self, currentGameState, action): <NEW_LINE> <INDENT> successorGameState = currentGameState.generatePacmanSuccessor(action) <NEW_LINE> newPos = successorGameState.getPacmanPosition() <NEW_LINE> newFood = successorGameState.getFood() <NEW_LINE> newGhostStates = successorGameState.getGhostStates() <NEW_LINE> newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] <NEW_LINE> oldFood = currentGameState.getFood().asList() <NEW_LINE> score = 0 <NEW_LINE> if(action == Directions.STOP): <NEW_LINE> <INDENT> score -= 9999999 <NEW_LINE> <DEDENT> closest = 999999 <NEW_LINE> nextP = None <NEW_LINE> for p in oldFood: <NEW_LINE> <INDENT> dist = manhattanDistance(newPos, p) <NEW_LINE> if (dist < closest): <NEW_LINE> <INDENT> closest = dist <NEW_LINE> nextP = p <NEW_LINE> <DEDENT> <DEDENT> score += 1 if closest == 0 else 1.0/(closest) <NEW_LINE> for g in newGhostStates: <NEW_LINE> <INDENT> p = g.getPosition() <NEW_LINE> s = g.scaredTimer <NEW_LINE> if (manhattanDistance(newPos, p) == 0 and s == 0): <NEW_LINE> <INDENT> score -= 9999999 <NEW_LINE> <DEDENT> <DEDENT> return score | A reflex agent chooses an action at each choice point by examining
its alternatives via a state evaluation function.
The code below is provided as a guide. You are welcome to change
it in any way you see fit, so long as you don't touch our method
headers. | 62598fbd956e5f7376df5768 |
class TestRGBLuminance(unittest.TestCase): <NEW_LINE> <INDENT> def test_RGB_luminance(self): <NEW_LINE> <INDENT> self.assertAlmostEqual( RGB_luminance( np.array([50.0, 50.0, 50.0]), np.array([0.73470, 0.26530, 0.00000, 1.00000, 0.00010, -0.07700]), np.array([0.32168, 0.33767])), 50., places=7) <NEW_LINE> self.assertAlmostEqual( RGB_luminance( np.array([74.6, 16.1, 100.0]), np.array([0.73470, 0.26530, 0.00000, 1.00000, 0.00010, -0.07700]), np.array([0.32168, 0.33767])), 30.1701166701, places=7) <NEW_LINE> self.assertAlmostEqual( RGB_luminance( np.array([40.6, 4.2, 67.4]), np.array([0.73470, 0.26530, 0.00000, 1.00000, 0.00010, -0.07700]), np.array([0.32168, 0.33767])), 12.1616018403, places=7) <NEW_LINE> <DEDENT> def test_n_dimensional_RGB_luminance(self): <NEW_LINE> <INDENT> RGB = np.array([50.0, 50.0, 50.0]), <NEW_LINE> P = np.array([0.73470, 0.26530, 0.00000, 1.00000, 0.00010, -0.07700]), <NEW_LINE> W = np.array([0.32168, 0.33767]) <NEW_LINE> Y = 50 <NEW_LINE> np.testing.assert_almost_equal( RGB_luminance(RGB, P, W), Y) <NEW_LINE> RGB = np.tile(RGB, (6, 1)) <NEW_LINE> Y = np.tile(Y, 6) <NEW_LINE> np.testing.assert_almost_equal( RGB_luminance(RGB, P, W), Y) <NEW_LINE> RGB = np.reshape(RGB, (2, 3, 3)) <NEW_LINE> Y = np.reshape(Y, (2, 3)) <NEW_LINE> np.testing.assert_almost_equal( RGB_luminance(RGB, P, W), Y) <NEW_LINE> <DEDENT> @ignore_numpy_errors <NEW_LINE> def test_nan_RGB_luminance(self): <NEW_LINE> <INDENT> cases = [-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan] <NEW_LINE> cases = set(permutations(cases * 3, r=3)) <NEW_LINE> for case in cases: <NEW_LINE> <INDENT> RGB = np.array(case) <NEW_LINE> P = np.array(np.vstack((case[0:2], case[0:2], case[0:2]))) <NEW_LINE> W = np.array(case[0:2]) <NEW_LINE> try: <NEW_LINE> <INDENT> RGB_luminance(RGB, P, W) <NEW_LINE> <DEDENT> except np.linalg.linalg.LinAlgError: <NEW_LINE> <INDENT> import traceback <NEW_LINE> from colour.utilities import warning <NEW_LINE> warning(traceback.format_exc()) | Defines :func:`colour.models.rgb.derivation.RGB_luminance` definition
unit tests methods. | 62598fbd99fddb7c1ca62ed6 |
class ButtStockModel(models.Model): <NEW_LINE> <INDENT> date = models.DateField('日期', default=timezone.now, blank=False) <NEW_LINE> day_price = models.FloatField('成交单价', blank=False, null=False) <NEW_LINE> amount = models.FloatField('金额', blank=True, null=True) <NEW_LINE> item_id = models.ForeignKey( "RegularInputItemsModel", on_delete=models.CASCADE, verbose_name="投资对象", db_column="item_id", related_name="butt_stock_ids", blank=False, null=False ) <NEW_LINE> is_active = models.BooleanField('是否持有', default=False) <NEW_LINE> copies = models.FloatField('成交份额', blank=False, null=False) <NEW_LINE> end_worth = models.FloatField('完结价值', blank=True, null=True, default=0) <NEW_LINE> yield_rate = models.CharField('收益率', max_length=255) <NEW_LINE> total_earning = models.FloatField('总收益', default=0) <NEW_LINE> note = RichTextField('备注', blank=True, null=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = 'tb_butt_stock' <NEW_LINE> verbose_name = '烟蒂股' <NEW_LINE> verbose_name_plural = verbose_name <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> self.amount = round((self.copies * self.day_price), 2) <NEW_LINE> self.yield_rate = '{:.2%}'.format((self.end_worth - self.amount) / self.amount) <NEW_LINE> self.total_earning = round(self.end_worth - self.amount, 2) <NEW_LINE> return super(ButtStockModel, self).save(args, **kwargs) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f"{formats.date_format(self.date)}-{self.item_id.name}" | 烟蒂股 | 62598fbd3d592f4c4edbb094 |
class SolutionMaxSubarray: <NEW_LINE> <INDENT> def maxSubArray(self, nums): <NEW_LINE> <INDENT> if (len(nums) == 0): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> prevMax = maxSum = nums[0] <NEW_LINE> i = 1 <NEW_LINE> while (i < len(nums)): <NEW_LINE> <INDENT> if (prevMax + nums[i] > 0): <NEW_LINE> <INDENT> prevMax = max(prevMax + nums[i], nums[i]) <NEW_LINE> maxSum = max(maxSum, prevMax) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> prevMax = 0 <NEW_LINE> maxSum = max(maxSum, nums[i]) <NEW_LINE> <DEDENT> i += 1 <NEW_LINE> <DEDENT> return maxSum | @param nums: A list of integers
@return: An integer denote the sum of maximum subarray | 62598fbdf9cc0f698b1c53b9 |
class Solution: <NEW_LINE> <INDENT> def reverse(self, head): <NEW_LINE> <INDENT> prev = None <NEW_LINE> while (head): <NEW_LINE> <INDENT> tmp = head.next <NEW_LINE> head.next = prev <NEW_LINE> prev = head <NEW_LINE> if (tmp): <NEW_LINE> <INDENT> head = tmp <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return head | @param head: The first node of the linked list.
@return: You should return the head of the reversed linked list.
Reverse it in-place. | 62598fbd7b180e01f3e4913a |
class RazerBlackWidowChromaTournamentEdition(_RippleKeyboard): <NEW_LINE> <INDENT> EVENT_FILE_REGEX = re.compile(r'.*BlackWidow_Tournament_Edition_Chroma(-if01)?-event-kbd') <NEW_LINE> USB_VID = 0x1532 <NEW_LINE> USB_PID = 0x0209 <NEW_LINE> HAS_MATRIX = True <NEW_LINE> MATRIX_DIMS = [6, 22] <NEW_LINE> METHODS = ['get_device_type_keyboard', 'set_wave_effect', 'set_static_effect', 'set_spectrum_effect', 'set_reactive_effect', 'set_none_effect', 'set_breath_random_effect', 'set_breath_single_effect', 'set_breath_dual_effect', 'set_custom_effect', 'set_key_row', 'get_game_mode', 'set_game_mode', 'get_macros', 'delete_macro', 'add_macro', 'set_ripple_effect', 'set_ripple_effect_random_colour'] <NEW_LINE> DEVICE_IMAGE = "https://assets.razerzone.com/eeimages/support/products/571/571_blackwidow_tournament_edition_chroma.png" | Class for the Razer BlackWidow Tournament Edition Chroma | 62598fbd63d6d428bbee2986 |
class TestCommunicationCostPage(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def make_instance(self, include_optional): <NEW_LINE> <INDENT> if include_optional : <NEW_LINE> <INDENT> return CommunicationCostPage( pagination = openfec_sdk.models.seek_info.SeekInfo( count = 56, last_indexes = '0', pages = 56, per_page = 56, ), results = [ openfec_sdk.models.communication_cost.CommunicationCost( action_code = '0', action_code_full = '0', candidate_first_name = '0', candidate_id = '0', candidate_last_name = '0', candidate_middle_name = '0', candidate_name = '0', candidate_office = '0', candidate_office_district = '0', candidate_office_full = '0', candidate_office_state = '0', committee_id = '0', committee_name = '0', communication_class = '0', communication_type = '0', communication_type_full = '0', cycle = 56, file_number = 56, form_type_code = '0', image_number = '0', original_sub_id = 56, pdf_url = '0', primary_general_indicator = '0', primary_general_indicator_description = '0', purpose = '0', report_type = '0', report_year = 56, schedule_type = '0', schedule_type_full = '0', state_full = '0', sub_id = 56, support_oppose_indicator = '0', tran_id = '0', transaction_amount = 1.337, transaction_date = datetime.datetime.strptime('1975-12-30', '%Y-%m-%d').date(), transaction_type = '0', ) ] ) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return CommunicationCostPage( ) <NEW_LINE> <DEDENT> <DEDENT> def testCommunicationCostPage(self): <NEW_LINE> <INDENT> inst_req_only = self.make_instance(include_optional=False) <NEW_LINE> inst_req_and_optional = self.make_instance(include_optional=True) | CommunicationCostPage unit test stubs | 62598fbd442bda511e95c632 |
class Test_find_all_valid_locations(unittest.TestCase): <NEW_LINE> <INDENT> pass | Tests the find_all_valid_locations function with the following cases:
TBD | 62598fbd66673b3332c305a7 |
class Warning(Exception): <NEW_LINE> <INDENT> pass | Important warnings like data truncations while inserting.
Exception raised for important warnings like data truncations
while inserting, etc. It must be a subclass of the Python
StandardError (defined in the module exceptions). | 62598fbdf548e778e596b77c |
class Node(object): <NEW_LINE> <INDENT> def __init__(self, parent, key, text, values, icon=None): <NEW_LINE> <INDENT> self.parent = parent <NEW_LINE> self.children = [] <NEW_LINE> self.key = key <NEW_LINE> self.text = text <NEW_LINE> self.values = values <NEW_LINE> self.icon = icon <NEW_LINE> <DEDENT> def _Add(self, node): <NEW_LINE> <INDENT> self.children.append(node) | Contains information about the individual node in the tree | 62598fbd26068e7796d4cb30 |
class ITopicTreeVisitor: <NEW_LINE> <INDENT> def _accept(self, topicObj): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def _startTraversal(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _onTopic(self, topicObj): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _startChildren(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _endChildren(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _doneTraversal(self): <NEW_LINE> <INDENT> pass | Topic tree traverser. Provides the traverse() method
which traverses a topic tree and calls self._onTopic() for
each topic in the tree that satisfies self._accept().
Additionally it calls self._startChildren() whenever it
starts traversing the subtopics of a topic, and
self._endChildren() when it is done with the subtopics.
Finally, it calls self._doneTraversal() when traversal
has been completed.
Derive from ITopicTreeVisitor and override one or more of the
four self._*() methods described above. Give an instance to
an instance of pub.TopicTreeTraverser. | 62598fbd56ac1b37e63023c4 |
class ListImages(ImageCommand, command_base.GoogleComputeListCommand): <NEW_LINE> <INDENT> def ListFunc(self): <NEW_LINE> <INDENT> return self._images_api.list | List the images for a project. | 62598fbdff9c53063f51a824 |
class SimpleRelated(TranslatableModel): <NEW_LINE> <INDENT> normal = models.ForeignKey(Normal, related_name='simplerel', on_delete=models.CASCADE) <NEW_LINE> manynormals = models.ManyToManyField(Normal, blank=True, related_name='manysimplerel') <NEW_LINE> translated_fields = TranslatedFields( translated_field = models.CharField(max_length=255), ) | Model with foreign key to Normal, shared only and regular translatable field | 62598fbd63b5f9789fe85346 |
class PriorityBuffer(Buffer): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.samples = [] <NEW_LINE> self.priority = [] <NEW_LINE> self.total_usage = 0 <NEW_LINE> <DEDENT> def is_empty(self): <NEW_LINE> <INDENT> return len(self.samples) == 0 <NEW_LINE> <DEDENT> def add_sample(self, sample): <NEW_LINE> <INDENT> if isinstance(sample, tuple): <NEW_LINE> <INDENT> self.samples.append(sample) <NEW_LINE> self.priority.append(0) <NEW_LINE> <DEDENT> elif isinstance(sample, list): <NEW_LINE> <INDENT> for i in sample: <NEW_LINE> <INDENT> self.samples.append(i) <NEW_LINE> self.priority.append(0) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_sample(self, n): <NEW_LINE> <INDENT> self.total_usage += n <NEW_LINE> hold = random.choices(range(len(self.priority)), [1 - (self.priority[i]/self.total_usage) for i in range(len(self.priority))], k=n) <NEW_LINE> res = [] <NEW_LINE> for i in hold: <NEW_LINE> <INDENT> self.priority[i] += 1 <NEW_LINE> res.append(self.samples[i]) <NEW_LINE> <DEDENT> return res <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.priority = [0 for _ in range(len(self.samples))] <NEW_LINE> <DEDENT> def clear(self): <NEW_LINE> <INDENT> self.samples = [] <NEW_LINE> self.priority = [] <NEW_LINE> self.total_usage = 0 | Return the sample from the last returned to the most returned | 62598fbd01c39578d7f12f51 |
class PostTag(db.Model): <NEW_LINE> <INDENT> __tablename__ = "posts_tags" <NEW_LINE> post_id = db.Column(db.Integer , db.ForeignKey('posts.id' , ondelete="CASCADE") , primary_key=True) <NEW_LINE> tag_id = db.Column(db.Integer , db.ForeignKey("tags.id" , ondelete="CASCADE") , primary_key=True) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> e = self <NEW_LINE> return f"<PostTag {e.post_id} {e.tag_id}>" | Post Tags. | 62598fbd442bda511e95c634 |
class DrupalBinder(Binder): <NEW_LINE> <INDENT> pass | Generic Binder for Drupal | 62598fbd9c8ee82313040260 |
class Event(object): <NEW_LINE> <INDENT> def __init__(self, name, myid, **kwargs): <NEW_LINE> <INDENT> self.name = name.encode('ascii', 'ignore') <NEW_LINE> self.id = myid <NEW_LINE> self.properties = kwargs <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return ' '.join([self.name, str(self.id)]) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.__repr__() | A top level event. | 62598fbd56ac1b37e63023c5 |
class MergeInfo(): <NEW_LINE> <INDENT> def __init__(self, index1=None, index2=None, seg=None): <NEW_LINE> <INDENT> if index1 > index2: <NEW_LINE> <INDENT> tmp = index1 <NEW_LINE> index1 = index2 <NEW_LINE> index2 = tmp <NEW_LINE> <DEDENT> self._minIndex = index1 <NEW_LINE> self._maxIndex = index2 <NEW_LINE> self._seg = seg <NEW_LINE> <DEDENT> def __cmp__(self, other): <NEW_LINE> <INDENT> if self._maxIndex > other._maxIndex: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> elif self._maxIndex < other._maxIndex: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> minIndex, maxIndex = self.getIndices() <NEW_LINE> seg = self.getSeg() <NEW_LINE> return "(%(minIndex)s, %(maxIndex)s, %(seg)s)" %vars() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> minIndex, maxIndex = self.getIndices() <NEW_LINE> seg = self.getSeg() <NEW_LINE> return "mergeInfo(%(minIndex)r, %(maxIndex)r, %(seg)r)" %vars() <NEW_LINE> <DEDENT> def getIndices(self): <NEW_LINE> <INDENT> return self._minIndex, self._maxIndex <NEW_LINE> <DEDENT> def getSeg(self): <NEW_LINE> <INDENT> return self._seg | Records indices and joining segment for two clusters to be merged. | 62598fbd9f28863672818967 |
class ITrustPolicyLayer(Interface): <NEW_LINE> <INDENT> pass | Marker interface for browserlayer. | 62598fbdadb09d7d5dc0a755 |
class BindingEndpoint(object): <NEW_LINE> <INDENT> def __init__(self,instance,setter,valueChangedSignal,getter=None): <NEW_LINE> <INDENT> self.instanceId = id(instance) <NEW_LINE> self.instance = instance <NEW_LINE> self.getter = getter <NEW_LINE> self.setter = setter <NEW_LINE> self.valueChangedSignal = valueChangedSignal <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def forProperty(instance,propertyName,useGetter=False): <NEW_LINE> <INDENT> assert isinstance(propertyName,str) <NEW_LINE> if propertyName.startswith("get") or propertyName.startswith("set"): <NEW_LINE> <INDENT> getterName = "get" + propertyName[3:] <NEW_LINE> setterName = "set" + propertyName[3:] <NEW_LINE> if len(propertyName[3:]) > 1: <NEW_LINE> <INDENT> signalName = propertyName[3].lower() + propertyName[4:] + "Changed" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> signalName = propertyName.lower() + "Changed" <NEW_LINE> <DEDENT> assert hasattr(instance,getterName) <NEW_LINE> assert hasattr(instance,setterName) <NEW_LINE> assert hasattr(instance,signalName) <NEW_LINE> getter = getattr(instance,getterName) <NEW_LINE> setter = getattr(instance,setterName) <NEW_LINE> signal = getattr(instance,signalName) <NEW_LINE> <DEDENT> elif hasattr(instance, propertyName) and callable(getattr(instance,propertyName)): <NEW_LINE> <INDENT> getterName = propertyName <NEW_LINE> setterName = "set" + propertyName.capitalize() <NEW_LINE> signalName = propertyName + "Changed" <NEW_LINE> assert hasattr(instance,setterName) <NEW_LINE> assert hasattr(instance,signalName) <NEW_LINE> getter = getattr(instance,getterName) <NEW_LINE> setter = getattr(instance,setterName) <NEW_LINE> signal = getattr(instance,signalName) <NEW_LINE> <DEDENT> elif hasattr(instance, propertyName): <NEW_LINE> <INDENT> signalName = propertyName + "Changed" <NEW_LINE> assert hasattr(instance,signalName) <NEW_LINE> getter = lambda: getattr(instance,propertyName) <NEW_LINE> setter = lambda value: setattr(instance,propertyName,value) <NEW_LINE> signal = getattr(instance,signalName) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if len(propertyName) > 1: <NEW_LINE> <INDENT> getterName = "get" + propertyName[0].upper() + propertyName[1:] <NEW_LINE> setterName = "set" + propertyName[0].upper() + propertyName[1:] <NEW_LINE> signalName = propertyName + "Changed" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> getterName = "get" + propertyName.upper() <NEW_LINE> setterName = "set" + propertyName.upper() <NEW_LINE> signalName = propertyName.lower() + "Changed" <NEW_LINE> <DEDENT> assert hasattr(instance,getterName) <NEW_LINE> assert hasattr(instance,setterName) <NEW_LINE> assert hasattr(instance,signalName) <NEW_LINE> getter = getattr(instance,getterName) <NEW_LINE> setter = getattr(instance,setterName) <NEW_LINE> signal = getattr(instance,signalName) <NEW_LINE> <DEDENT> return BindingEndpoint(instance, setter, signal, getter = getter if useGetter else None) | Data object that contains the triplet of: getter, setter and change notification signal,
as well as the object instance and it's memory id to which the binding triplet belongs.
Parameters:
instance -- the object instance to which the getter, setter and changedSignal belong
setter -- the value setter method
valueChangedSignal -- the pyqtSignal that is emitted with the value changes
getter -- the value getter method (default None)
If None, the signal argument(s) are passed to the setter method | 62598fbd7d847024c075c595 |
class Meta: <NEW_LINE> <INDENT> model = Admin | Factory configuration. | 62598fbd55399d3f056266ed |
class Calendar(models.Model): <NEW_LINE> <INDENT> name = models.CharField(verbose_name=_('name'), max_length=200) <NEW_LINE> user = models.ForeignKey(CalendarUser, blank=True, null=True, verbose_name=_("calendar user"), help_text=_("select user"), related_name="calendar user") <NEW_LINE> max_concurrent = models.IntegerField(null=True, blank=True, default=0, help_text=_("Max concurrent is not implemented")) <NEW_LINE> created_date = models.DateTimeField(auto_now_add=True, verbose_name=_('date')) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> permissions = ( ("view_calendar", _('Can see Calendar list')), ) <NEW_LINE> verbose_name = _('calendar') <NEW_LINE> verbose_name_plural = _('calendars') <NEW_LINE> app_label = "appointment" <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> @property <NEW_LINE> def events(self): <NEW_LINE> <INDENT> return self.event_set <NEW_LINE> <DEDENT> def get_recent(self, amount=5, in_datetime=datetime.datetime.now, tzinfo=pytz.utc): <NEW_LINE> <INDENT> return self.events.order_by('-start').filter(start__lt=timezone.now())[:amount] <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('calendar_home', kwargs={'calendar_slug': self.slug}) <NEW_LINE> <DEDENT> def add_event_url(self): <NEW_LINE> <INDENT> return reverse('s_create_event_in_calendar', args=[self.slug]) | This is for grouping events so that batch relations can be made to all
events. An example would be a project calendar.
name: the name of the calendar
events: all the events contained within the calendar.
>>> calendar = Calendar(name = 'Test Calendar')
>>> calendar.save() | 62598fbd92d797404e388c4f |
class Message(BASE, CinderBase): <NEW_LINE> <INDENT> __tablename__ = 'messages' <NEW_LINE> id = Column(String(36), primary_key=True, nullable=False) <NEW_LINE> project_id = Column(String(36), nullable=False) <NEW_LINE> message_level = Column(String(255), nullable=False) <NEW_LINE> request_id = Column(String(255), nullable=True) <NEW_LINE> resource_type = Column(String(255)) <NEW_LINE> resource_uuid = Column(String(36), nullable=True) <NEW_LINE> event_id = Column(String(255), nullable=False) <NEW_LINE> expires_at = Column(DateTime, nullable=True) | Represents a message | 62598fbd44b2445a339b6a62 |
class ImagenetData(Dataset): <NEW_LINE> <INDENT> def __init__(self, data_dir=None): <NEW_LINE> <INDENT> if data_dir is None: <NEW_LINE> <INDENT> raise ValueError('Data directory not specified') <NEW_LINE> <DEDENT> super(ImagenetData, self).__init__('imagenet', 300, 300, data_dir=data_dir) <NEW_LINE> <DEDENT> def num_classes(self): <NEW_LINE> <INDENT> return 1000 <NEW_LINE> <DEDENT> def num_examples_per_epoch(self, subset='train'): <NEW_LINE> <INDENT> if subset == 'train': <NEW_LINE> <INDENT> return 1281167 <NEW_LINE> <DEDENT> elif subset == 'validation': <NEW_LINE> <INDENT> return 50000 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Invalid data subset "%s"' % subset) <NEW_LINE> <DEDENT> <DEDENT> def get_image_preprocessor(self): <NEW_LINE> <INDENT> return preprocessing.RecordInputImagePreprocessor | Configuration for Imagenet dataset. | 62598fbd99fddb7c1ca62ed8 |
class PokemonFormAdapter(Adapter): <NEW_LINE> <INDENT> pokemon_forms = { 201: 'abcdefghijklmnopqrstuvwxyz!?', 386: ['normal', 'attack', 'defense', 'speed'], 412: ['plant', 'sandy', 'trash'], 413: ['plant', 'sandy', 'trash'], 422: ['west', 'east'], 423: ['west', 'east'], 479: ['normal', 'heat', 'wash', 'frost', 'fan', 'cut'], 487: ['altered', 'origin'], 492: ['land', 'sky'], 493: [ 'normal', 'fighting', 'flying', 'poison', 'ground', 'rock', 'bug', 'ghost', 'steel', 'fire', 'water', 'grass', 'thunder', 'psychic', 'ice', 'dragon', 'dark', '???', ], } <NEW_LINE> def _decode(self, obj, context): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> forms = self.pokemon_forms[ context['national_id'] ] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return forms[obj >> 3] <NEW_LINE> <DEDENT> def _encode(self, obj, context): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> forms = self.pokemon_forms[ context['national_id'] ] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return forms.index(obj) << 3 | Converts form ids to form names, and vice versa. | 62598fbd57b8e32f52508209 |
class EmailNotification(models.Model): <NEW_LINE> <INDENT> name = models.CharField(blank=False, max_length=50) <NEW_LINE> subject = models.CharField(blank=False, max_length=77) <NEW_LINE> body = models.TextField(blank=False) <NEW_LINE> sites = models.ManyToManyField(Site) <NEW_LINE> objects = EmailNotificationQuerySet.as_manager() <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def clean(self): <NEW_LINE> <INDENT> self.save() <NEW_LINE> super(EmailNotification, self).clean() <NEW_LINE> validate_email_unique(self) <NEW_LINE> <DEDENT> @property <NEW_LINE> def sitenames(self): <NEW_LINE> <INDENT> return [site.name for site in self.sites.all()] | Record of Email constructed in and sent via the project | 62598fbdcc0a2c111447b1e6 |
class GetNodeSecurity_result: <NEW_LINE> <INDENT> thrift_spec = ( (0, TType.BYTE, 'success', None, None, ), ) <NEW_LINE> def __init__(self, success=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.BYTE: <NEW_LINE> <INDENT> self.success = iprot.readByte(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('GetNodeSecurity_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.BYTE, 0) <NEW_LINE> oprot.writeByte(self.success) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- success | 62598fbd4a966d76dd5ef0ac |
class GameWindow(pyglet.window.Window,object): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(GameWindow, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> pass | docstring for GameWindow | 62598fbd63d6d428bbee298a |
class History: <NEW_LINE> <INDENT> url = BASE_URL + '/history' <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def rates_time_period(self): <NEW_LINE> <INDENT> response = requests.get(self.url + '?start_at=2018-01-01&end_at=2018-09-01') <NEW_LINE> status_code = response.status_code <NEW_LINE> logger.info(f"Code status: {status_code}. Successful operation. " f"URL: {self.url + '?start_at=2018-01-01&end_at=2018-09-01'}") <NEW_LINE> return response <NEW_LINE> <DEDENT> def specific_exchange_rates(self): <NEW_LINE> <INDENT> response = requests.get(self.url + '?start_at=2018-01-01&end_at=2018-09-01&symbols=ILS,JPY') <NEW_LINE> status_code = response.status_code <NEW_LINE> logger.info(f"Code status: {status_code}. Successful operation. " f"URL: {self.url + '?start_at=2018-01-01&end_at=2018-09-01&symbols=ILS,JPY'}") <NEW_LINE> return response <NEW_LINE> <DEDENT> def different_currency(self): <NEW_LINE> <INDENT> response = requests.get(self.url + '?start_at=2018-01-01&end_at=2018-09-01&base=USD') <NEW_LINE> status_code = response.status_code <NEW_LINE> logger.info(f"Code status: {status_code}. Successful operation. " f"URL: {self.url + '?start_at=2018-01-01&end_at=2018-09-01&base=USD'}") <NEW_LINE> return response | Class History | 62598fbd442bda511e95c636 |
class MailChimpSessionSchema(Schema): <NEW_LINE> <INDENT> def __init__(self, session=None, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> if session is None and self.context.get('session', None) is None: <NEW_LINE> <INDENT> session = MailChimpSession() <NEW_LINE> <DEDENT> self.session = session <NEW_LINE> self.context = {'session': session} | Adds MailChimpSession to Schema
When used as a nested object of another Schema it checks if a session already exists
This to prevent initializing unneeded sessions | 62598fbde5267d203ee6bad9 |
class GlobalsPlugin(BasePlugin): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(GlobalsPlugin, self).__init__(GlobalsPlugin.__name__) <NEW_LINE> <DEDENT> @cw_timer(prefix="Plugin-Globals") <NEW_LINE> def on_before_transform_template(self, template_dict): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> global_section = Globals(template_dict) <NEW_LINE> <DEDENT> except InvalidGlobalsSectionException as ex: <NEW_LINE> <INDENT> raise InvalidDocumentException([ex]) <NEW_LINE> <DEDENT> template = SamTemplate(template_dict) <NEW_LINE> for logicalId, resource in template.iterate(): <NEW_LINE> <INDENT> resource.properties = global_section.merge(resource.type, resource.properties) <NEW_LINE> template.set(logicalId, resource) <NEW_LINE> <DEDENT> Globals.del_section(template_dict) <NEW_LINE> Globals.fix_openapi_definitions(template_dict) | Plugin to process Globals section of a SAM template before the template is translated to CloudFormation. | 62598fbd9f28863672818968 |
@tf_export("data.experimental.AutoShardPolicy") <NEW_LINE> class AutoShardPolicy(enum.IntEnum): <NEW_LINE> <INDENT> OFF = -1 <NEW_LINE> AUTO = 0 <NEW_LINE> FILE = 1 <NEW_LINE> DATA = 2 <NEW_LINE> HINT = 3 <NEW_LINE> @classmethod <NEW_LINE> def _to_proto(cls, obj): <NEW_LINE> <INDENT> if obj == cls.OFF: <NEW_LINE> <INDENT> return dataset_options_pb2.AutoShardPolicy.OFF <NEW_LINE> <DEDENT> if obj == cls.FILE: <NEW_LINE> <INDENT> return dataset_options_pb2.AutoShardPolicy.FILE <NEW_LINE> <DEDENT> if obj == cls.DATA: <NEW_LINE> <INDENT> return dataset_options_pb2.AutoShardPolicy.DATA <NEW_LINE> <DEDENT> if obj == cls.AUTO: <NEW_LINE> <INDENT> return dataset_options_pb2.AutoShardPolicy.AUTO <NEW_LINE> <DEDENT> if obj == cls.HINT: <NEW_LINE> <INDENT> return dataset_options_pb2.AutoShardPolicy.HINT <NEW_LINE> <DEDENT> raise ValueError("%s._to_proto() is called with undefined enum %s." % (cls.__name__, obj.name)) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _from_proto(cls, pb): <NEW_LINE> <INDENT> if pb == dataset_options_pb2.AutoShardPolicy.OFF: <NEW_LINE> <INDENT> return cls.OFF <NEW_LINE> <DEDENT> if pb == dataset_options_pb2.AutoShardPolicy.FILE: <NEW_LINE> <INDENT> return cls.FILE <NEW_LINE> <DEDENT> if pb == dataset_options_pb2.AutoShardPolicy.DATA: <NEW_LINE> <INDENT> return cls.DATA <NEW_LINE> <DEDENT> if pb == dataset_options_pb2.AutoShardPolicy.AUTO: <NEW_LINE> <INDENT> return cls.AUTO <NEW_LINE> <DEDENT> if pb == dataset_options_pb2.AutoShardPolicy.HINT: <NEW_LINE> <INDENT> return cls.HINT <NEW_LINE> <DEDENT> raise ValueError("%s._from_proto() is called with undefined enum %s." % (cls.__name__, pb)) | Represents the type of auto-sharding to use.
OFF: No sharding will be performed.
AUTO: Attempts FILE-based sharding, falling back to DATA-based sharding.
FILE: Shards by input files (i.e. each worker will get a set of files to
process). When this option is selected, make sure that there is at least as
many files as workers. If there are fewer input files than workers, a runtime
error will be raised.
DATA: Shards by elements produced by the dataset. Each worker will process the
whole dataset and discard the portion that is not for itself. Note that for
this mode to correctly partitions the dataset elements, the dataset needs to
produce elements in a deterministic order.
HINT: Looks for the presence of `shard(SHARD_HINT, ...)` which is treated as a
placeholder to replace with `shard(num_workers, worker_index)`. | 62598fbdaad79263cf42e9af |
class ImageFormatException(Exception): <NEW_LINE> <INDENT> def __init__(self, fpath): <NEW_LINE> <INDENT> msg = str.format("File {:s} has invalid image type", fpath) <NEW_LINE> self.fpath = fpath <NEW_LINE> super(ImageFormatException, self).__init__(msg) | The exception that is raised when
the format of an image file is invalid | 62598fbd5fdd1c0f98e5e16b |
class Decoder(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._clear_codes() <NEW_LINE> self.remainder = [] <NEW_LINE> <DEDENT> def code_size(self): <NEW_LINE> <INDENT> return len(self._codepoints) <NEW_LINE> <DEDENT> def decode(self, codepoints): <NEW_LINE> <INDENT> codepoints = [ cp for cp in codepoints ] <NEW_LINE> for cp in codepoints: <NEW_LINE> <INDENT> decoded = self._decode_codepoint(cp) <NEW_LINE> for character in decoded: <NEW_LINE> <INDENT> yield character <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _decode_codepoint(self, codepoint): <NEW_LINE> <INDENT> ret = "" <NEW_LINE> if codepoint == CLEAR_CODE: <NEW_LINE> <INDENT> self._clear_codes() <NEW_LINE> <DEDENT> elif codepoint == END_OF_INFO_CODE: <NEW_LINE> <INDENT> raise ValueError("End of information code not supported directly by this Decoder") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if codepoint in self._codepoints: <NEW_LINE> <INDENT> ret = self._codepoints[ codepoint ] <NEW_LINE> if None != self._prefix: <NEW_LINE> <INDENT> self._codepoints[ len(self._codepoints) ] = self._prefix + ret[0] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> ret = self._prefix + self._prefix[0] <NEW_LINE> self._codepoints[ len(self._codepoints) ] = ret <NEW_LINE> <DEDENT> self._prefix = ret <NEW_LINE> <DEDENT> return ret <NEW_LINE> <DEDENT> def _clear_codes(self): <NEW_LINE> <INDENT> self._codepoints = dict( (pt, struct.pack("B", pt)) for pt in range(256) ) <NEW_LINE> self._codepoints[CLEAR_CODE] = CLEAR_CODE <NEW_LINE> self._codepoints[END_OF_INFO_CODE] = END_OF_INFO_CODE <NEW_LINE> self._prefix = None | Uncompresses a stream of lzw code points, as created by
L{Encoder}. Given a list of integer code points, with all
unpacking foolishness complete, turns that list of codepoints into
a list of uncompressed bytes. See L{BitUnpacker} for what this
doesn't do. | 62598fbd55399d3f056266ef |
class UserDetailView(RetrieveAPIView): <NEW_LINE> <INDENT> serializer_class = serializers.UserDetailSerialzier <NEW_LINE> def get_object(self): <NEW_LINE> <INDENT> return self.request.user | 获取用户信息 | 62598fbd63b5f9789fe8534a |
class CommentViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = Comment.objects.all().order_by('id') <NEW_LINE> serializer_class = CommentSerializer | View for /comments API endpoint | 62598fbd3346ee7daa337735 |
class BRAINSCut(SEMLikeCommandLine): <NEW_LINE> <INDENT> input_spec = BRAINSCutInputSpec <NEW_LINE> output_spec = BRAINSCutOutputSpec <NEW_LINE> _cmd = " BRAINSCut " <NEW_LINE> _outputs_filenames = {} | title: BRAINSCut (BRAINS)
category: Segmentation.Specialized
description: Automatic Segmentation using neural networks
version: 1.0
license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt
contributor: Vince Magnotta, Hans Johnson, Greg Harris, Kent Williams, Eunyoung Regina Kim | 62598fbd23849d37ff85128e |
class LimitedInputFilter(object): <NEW_LINE> <INDENT> def __init__(self, application): <NEW_LINE> <INDENT> self.app = application <NEW_LINE> <DEDENT> def __call__(self, environ, start_response): <NEW_LINE> <INDENT> content_length = environ.get('CONTENT_LENGTH', '') <NEW_LINE> if content_length: <NEW_LINE> <INDENT> environ['wsgi.input'] = _LengthLimitedFile( environ['wsgi.input'], int(content_length)) <NEW_LINE> <DEDENT> return self.app(environ, start_response) | WSGI middleware that limits the input length of a request to that
specified in Content-Length. | 62598fbd4428ac0f6e6586fd |
class CitiesTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def test_city_country(self): <NEW_LINE> <INDENT> formatted = city_country('santiago', 'chile') <NEW_LINE> self.assertEqual(formatted, 'Santiago, Chile') <NEW_LINE> <DEDENT> def test_city_country_population(self): <NEW_LINE> <INDENT> formatted = city_country('santiago', 'chile', '5000000') <NEW_LINE> self.assertEqual(formatted, 'Santiago, Chile - population 5000000') | Tests for 'city_functions.py' validity | 62598fbd3617ad0b5ee06321 |
class Bloom_Filter: <NEW_LINE> <INDENT> def __init__(self,mem,count,segments): <NEW_LINE> <INDENT> self.array_size=mem <NEW_LINE> self.length=count <NEW_LINE> """Initiate a numpy array with zeros""" <NEW_LINE> self.array=np.zeros(self.array_size,dtype=int) <NEW_LINE> """calculate the optimal number of hash functions needed""" <NEW_LINE> self.max_hash_num=2*int(math.floor((self.array_size/self.length)*np.log(2))) <NEW_LINE> """Number of segments""" <NEW_LINE> self.segments=segments <NEW_LINE> """A dictionary to keep track of distribution of input data as in how many points in segment 1...""" <NEW_LINE> self.distribution_dict={segment:0 for segment in range(self.segments)} <NEW_LINE> """False positive rate; to be calculated after insertion""" <NEW_LINE> self.fp_rate=0 <NEW_LINE> <DEDENT> """Insertion method""" <NEW_LINE> def insert(self,item,segment_id): <NEW_LINE> <INDENT> hash_num=self.segments-segment_id <NEW_LINE> """Increment by 1 in the distribution dictionary""" <NEW_LINE> self.distribution_dict[segment_id]=self.distribution_dict[segment_id]+1 <NEW_LINE> """hash the item to be inserted to different hash functions with different seed numbers""" <NEW_LINE> for i in range(hash_num): <NEW_LINE> <INDENT> index=mmh3.hash(item,i)%(self.array_size) <NEW_LINE> """set the specific index to 1""" <NEW_LINE> self.array[index]=1 <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> """Search method""" <NEW_LINE> def search(self,item,segment_id): <NEW_LINE> <INDENT> hash_num=self.segments-segment_id <NEW_LINE> found=0 <NEW_LINE> for i in range(hash_num): <NEW_LINE> <INDENT> index=mmh3.hash(item,i)%(self.array_size) <NEW_LINE> """If all the indices is already 1, then found=True""" <NEW_LINE> if self.array[index]==1: <NEW_LINE> <INDENT> found=found+1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> None <NEW_LINE> <DEDENT> <DEDENT> return found==hash_num <NEW_LINE> <DEDENT> """Calculate the false positive rate""" <NEW_LINE> def fp_calculator(self): <NEW_LINE> <INDENT> fp_val=0 <NEW_LINE> """For loop to calculate each segment's false positive rate""" <NEW_LINE> for i in range(self.segments): <NEW_LINE> <INDENT> fp_val=fp_val+((self.distribution_dict[i]/self.array_size)*(1-math.exp((-(self.max_hash_num-i)*self.length)/self.array_size))**(self.max_hash_num-i)) <NEW_LINE> <DEDENT> self.fp_rate=fp_val <NEW_LINE> return fp_val | Inititalization function that takes in the false positive rate
and number of elements to be inserted | 62598fbddc8b845886d53795 |
class ProxyMiddleWare(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.invalid_proxy = set() <NEW_LINE> self.proxy = Proxy.get_proxy() <NEW_LINE> <DEDENT> def process_request(self, request, spider): <NEW_LINE> <INDENT> request.meta['proxy'] = self.proxy['https'] <NEW_LINE> start_num = Proxy.get_status() <NEW_LINE> <DEDENT> def process_response(self, request, response, spider): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if str(response.status).startswith('4') or str(response.status).startswith('5'): <NEW_LINE> <INDENT> print('状态码异常:', response.status) <NEW_LINE> num = Proxy.get_status() <NEW_LINE> if len(self.invalid_proxy) >= num: <NEW_LINE> <INDENT> self.invalid_proxy.clear() <NEW_LINE> <DEDENT> self.invalid_proxy.add(request.meta['proxy']) <NEW_LINE> self.proxy = Proxy.get_proxy() <NEW_LINE> while True: <NEW_LINE> <INDENT> if self.proxy['https'] in self.invalid_proxy: <NEW_LINE> <INDENT> self.proxy = Proxy.get_proxy() <NEW_LINE> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> request.meta['proxy'] = self.proxy['https'] <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> return request <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> request.meta['proxy'] = self.proxy['https'] <NEW_LINE> return request <NEW_LINE> <DEDENT> return response <NEW_LINE> <DEDENT> def process_exception(self, request, exception, spider): <NEW_LINE> <INDENT> if isinstance(exception, TimeoutError): <NEW_LINE> <INDENT> self.invalid_proxy.add(request.meta['proxy']) <NEW_LINE> self.proxy = Proxy.get_proxy() <NEW_LINE> return request <NEW_LINE> <DEDENT> self.invalid_proxy.add(request.meta['proxy']) <NEW_LINE> self.proxy = Proxy.get_proxy() <NEW_LINE> num = Proxy.get_status() <NEW_LINE> if len(self.invalid_proxy) >= num: <NEW_LINE> <INDENT> self.invalid_proxy.clear() <NEW_LINE> <DEDENT> while True: <NEW_LINE> <INDENT> if self.proxy['https'] in self.invalid_proxy: <NEW_LINE> <INDENT> self.proxy = Proxy.get_proxy() <NEW_LINE> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> request.meta['proxy'] = self.proxy['https'] <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> return request | 设置Proxy | 62598fbd5166f23b2e2435b9 |
class FallbackRule(enum.Enum): <NEW_LINE> <INDENT> pass_through = 'pass_through' <NEW_LINE> strict = 'strict' <NEW_LINE> zero = 'zero' | Fallback rules for the ConfigurableOps class. | 62598fbd1f5feb6acb162dfb |
class v6_0(tls.Unicode, TypeMeta): <NEW_LINE> <INDENT> info_text = "KBaseFBA.ETC-6.0" | ElectronTransportChains (ETC) object | 62598fbda8370b77170f05bb |
class ProductStatus(Status): <NEW_LINE> <INDENT> def addInputBinding(self, factory, product): <NEW_LINE> <INDENT> self.addObserver(observer=factory.pyre_status) <NEW_LINE> return super().addInputBinding(factory=factory, product=product) <NEW_LINE> <DEDENT> def removeInputBinding(self, factory, product): <NEW_LINE> <INDENT> self.removeObserver(observer=factory.pyre_status) <NEW_LINE> return super().removeInputBinding(factory=factory, product=product) <NEW_LINE> <DEDENT> def addOutputBinding(self, factory, product): <NEW_LINE> <INDENT> self.flush(observable=factory.pyre_status) <NEW_LINE> return super().addOutputBinding(factory=factory, product=product) | A helper that watches over the traits of products and records value changes | 62598fbdbf627c535bcb1680 |
class ApiRouter(DefaultRouter): <NEW_LINE> <INDENT> routes = [ Route( url=r"^{prefix}/?$", mapping={ 'get': 'list', 'post': 'create' }, name="{basename}-list", initkwargs={'suffix': 'List'} ), Route( url=r"^{prefix}/{lookup}/?$", mapping={ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy' }, name="{basename}-detail", initkwargs={'suffix': 'Instance'} ), Route( url=r"^{prefix}/{lookup}/{methodname}/?$", mapping={ "{httpmethod}": "{methodname}", }, name="{basename}-{methodnamehyphen}", initkwargs={} ), ] | Generate URL patterns for list, detail, and viewset-specific
HTTP routes. | 62598fbd283ffb24f3cf3a5e |
class MultiprocessingDistributor(DistributorBaseClass): <NEW_LINE> <INDENT> def __init__(self, n_workers, disable_progressbar=False, progressbar_title="Feature Extraction", show_warnings=True): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.pool = Pool(processes=n_workers, initializer=initialize_warnings_in_workers, initargs=(show_warnings,)) <NEW_LINE> self.n_workers = n_workers <NEW_LINE> self.disable_progressbar = disable_progressbar <NEW_LINE> self.progressbar_title = progressbar_title <NEW_LINE> <DEDENT> def distribute(self, func, partitioned_chunks, kwargs): <NEW_LINE> <INDENT> return self.pool.imap_unordered(partial(func, **kwargs), partitioned_chunks) <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.pool.close() <NEW_LINE> self.pool.terminate() <NEW_LINE> self.pool.join() | Distributor using a multiprocessing Pool to calculate the jobs in parallel on the local machine. | 62598fbd9c8ee82313040262 |
class PublicProjects(BaseProjects): <NEW_LINE> <INDENT> export_map = ( 'pk', 'name', 'public', 'analyze', 'reset', 'description', 'permalink', 'analysis_status', 'analyzed_at', ) <NEW_LINE> @valid_user(anon_ok=True) <NEW_LINE> def get(self): <NEW_LINE> <INDENT> form = PublicProjectsForm(request.args) <NEW_LINE> if not form.validate(): <NEW_LINE> <INDENT> return {'message' : 'please correct the errors mentioned below', errors: form.errors}, 400 <NEW_LINE> <DEDENT> data = form.data <NEW_LINE> query = {'public': True} <NEW_LINE> if not data['show_failed']: <NEW_LINE> <INDENT> query['analysis_status'] = { '$in': [ 'succeeded', 'in_progress' ] } <NEW_LINE> <DEDENT> query = { '$and': [ query, {'$or': [{'deleted': {'$exists': False}}, {'deleted': False}]}, {'$or': [{'delete': {'$exists': False}}, {'delete': False}]}, ] } <NEW_LINE> if data['query']: <NEW_LINE> <INDENT> search_dict = { '$or': [ {'$and': [{'name': {'$ilike': '%%%s%%' % q}} for q in data['query']]} ] } <NEW_LINE> query = {'$and': [query, search_dict]} <NEW_LINE> <DEDENT> projects = backend.filter(Project, query, raw=True, only=self.export_fields) <NEW_LINE> projects = projects.sort(data['sort'], data['direction'], explicit_nullsfirst=False) <NEW_LINE> offset, limit = data['offset'], data['limit'] <NEW_LINE> serialized_projects = [self.export(project) for project in projects[offset:offset + limit]] <NEW_LINE> res = { 'projects': serialized_projects, 'count': len(projects), 'offset': offset, 'limit': limit, 'query' : data['query'] } <NEW_LINE> return res, 200 | Source: User Backend | 62598fbdec188e330fdf8a6e |
class lognorm_gen(rv_continuous): <NEW_LINE> <INDENT> def _rvs(self, s): <NEW_LINE> <INDENT> return exp(s * self._random_state.standard_normal(self._size)) <NEW_LINE> <DEDENT> def _pdf(self, x, s): <NEW_LINE> <INDENT> return exp(self._logpdf(x, s)) <NEW_LINE> <DEDENT> def _logpdf(self, x, s): <NEW_LINE> <INDENT> return _lognorm_logpdf(x, s) <NEW_LINE> <DEDENT> def _cdf(self, x, s): <NEW_LINE> <INDENT> return _norm_cdf(log(x) / s) <NEW_LINE> <DEDENT> def _ppf(self, q, s): <NEW_LINE> <INDENT> return exp(s * _norm_ppf(q)) <NEW_LINE> <DEDENT> def _stats(self, s): <NEW_LINE> <INDENT> p = exp(s*s) <NEW_LINE> mu = sqrt(p) <NEW_LINE> mu2 = p*(p-1) <NEW_LINE> g1 = sqrt((p-1))*(2+p) <NEW_LINE> g2 = np.polyval([1, 2, 3, 0, -6.0], p) <NEW_LINE> return mu, mu2, g1, g2 <NEW_LINE> <DEDENT> def _entropy(self, s): <NEW_LINE> <INDENT> return 0.5 * (1 + log(2*pi) + 2 * log(s)) | A lognormal continuous random variable.
%(before_notes)s
Notes
-----
The probability density function for `lognorm` is::
lognorm.pdf(x, s) = 1 / (s*x*sqrt(2*pi)) * exp(-1/2*(log(x)/s)**2)
for ``x > 0``, ``s > 0``.
`lognorm` takes ``s`` as a shape parameter.
If ``log(x)`` is normally distributed with mean ``mu`` and variance
``sigma**2``, then ``x`` is log-normally distributed with shape parameter
sigma and scale parameter ``exp(mu)``.
%(example)s | 62598fbd377c676e912f6e5f |
class IKTaskSet: <NEW_LINE> <INDENT> def __init__(self, iktaskset=None): <NEW_LINE> <INDENT> if iktaskset: <NEW_LINE> <INDENT> self.iktaskset = iktaskset <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.iktaskset = osm.IKTaskSet() <NEW_LINE> <DEDENT> <DEDENT> def add_ikmarkertask(self, name, do_apply, weight): <NEW_LINE> <INDENT> ikt = osm.IKMarkerTask() <NEW_LINE> ikt.setName(name) <NEW_LINE> ikt.setApply(do_apply) <NEW_LINE> ikt.setWeight(weight) <NEW_LINE> self.iktaskset.cloneAndAppend(ikt) <NEW_LINE> <DEDENT> def add_ikmarkertask_bilateral(self, name, do_apply, weight): <NEW_LINE> <INDENT> self.add_ikmarkertask('L%s' % name, do_apply, weight) <NEW_LINE> self.add_ikmarkertask('R%s' % name, do_apply, weight) <NEW_LINE> <DEDENT> def add_ikcoordinatetask(self, name, do_apply, manual_value, weight): <NEW_LINE> <INDENT> ikt = osm.IKCoordinateTask() <NEW_LINE> ikt.setName(name) <NEW_LINE> ikt.setApply(do_apply) <NEW_LINE> ikt.setValueType(ikt.ManualValue) <NEW_LINE> ikt.setValue(manual_value) <NEW_LINE> ikt.setWeight(weight) <NEW_LINE> self.iktaskset.cloneAndAppend(ikt) <NEW_LINE> <DEDENT> def add_ikcoordinatetask_bilateral(self, name, do_apply, manual_value, weight): <NEW_LINE> <INDENT> self.add_ikcoordinatetask('%s_l' % name, do_apply, manual_value, weight) <NEW_LINE> self.add_ikcoordinatetask('%s_r' % name, do_apply, manual_value, weight) | Wrapper of org.opensim.modeling.IKTaskSet with convenience methods.
| 62598fbdf548e778e596b782 |
class Cmd(command.BaseCmd): <NEW_LINE> <INDENT> DEFAULT_HANDLERS = (command.BaseCmd.DEFAULT_HANDLERS + (command.cmdlet.raiseOnNonZeroReturnCode, command.cmdlet.raiseWhenOutputIsNone, command.cmdlet.stripOutput, raise_when_no_instances, )) <NEW_LINE> def __init__(self, wmicpath=None, handler=None): <NEW_LINE> <INDENT> wmicpath = wmicpath and str(wmicpath) or 'wmic' <NEW_LINE> command.BaseCmd.__init__(self, wmicpath, handler=handler) <NEW_LINE> <DEDENT> def get_cmdline(self, wmicmd): <NEW_LINE> <INDENT> wmi_clsname = wmicmd.get_wmi_class_name() <NEW_LINE> query_builder = __WmicQueryBuilder(wmi_clsname, self.cmdline) <NEW_LINE> each(query_builder.addQueryElement, wmicmd.fields) <NEW_LINE> query_builder.usePathCommand(1) <NEW_LINE> query_builder.useSplitListOutput(1) <NEW_LINE> query_builder.setNamespace('\\\\%s' % wmicmd.NAMESPACE) <NEW_LINE> return query_builder.buildQuery() <NEW_LINE> <DEDENT> def create_wmic_command(self, wmicmd): <NEW_LINE> <INDENT> handler = comp(wmicmd.handler, partial(parse_items, wmicmd.fields, wmicmd.WMI_CLASS), raise_when_empty, self.handler) <NEW_LINE> return command.Cmd(self.get_cmdline(wmicmd), handler) <NEW_LINE> <DEDENT> def process(self, other): <NEW_LINE> <INDENT> return self.create_wmic_command(other) | Command class for `wmic` executable overriding command.Cmdlet.process
method and extending
command.BaseCmd.DEFAULT_HANDLERS static attribute with additional
handlers specific to wmic command.
Path to wmic binary is used as a cmdline for command.BaseCmd
The class defines additional public methods:
* get_cmdline
* create_wmic_command | 62598fbdadb09d7d5dc0a758 |
class Dataset(object): <NEW_LINE> <INDENT> name = None <NEW_LINE> start_time = None <NEW_LINE> stop_time = None <NEW_LINE> dimensions = None <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.dimensions = [] <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Dataset name=%r dimension=%r>' % (self.name, self.dimensions) | A representation of a DSC dataset
A DSC dataset is one to two dimensional structure where the last
dimension holds an array of values and counters.
It is based on the XML structure of DSC:
<array name="pcap_stats" dimensions="2" start_time="1563520560" stop_time="1563520620">
<dimension number="1" type="ifname"/>
<dimension number="2" type="pcap_stat"/>
<data>
<ifname val="eth0">
<pcap_stat val="filter_received" count="5625"/>
<pcap_stat val="pkts_captured" count="4894"/>
<pcap_stat val="kernel_dropped" count="731"/>
</ifname>
</data>
</array>
Attributes:
- name: The name of the dataset
- start_time: The start time of the dataset in seconds
- stop_time: The stop time of the dataset in seconds
- dimensions: An array with `Dimension`, the first dimension | 62598fbd97e22403b383b0e3 |
class PrivateEndpointConnection(Resource): <NEW_LINE> <INDENT> _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'private_endpoint': {'key': 'properties.privateEndpoint', 'type': 'PrivateEndpoint'}, 'private_link_service_connection_state': {'key': 'properties.privateLinkServiceConnectionState', 'type': 'ConnectionState'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, private_endpoint: Optional["PrivateEndpoint"] = None, private_link_service_connection_state: Optional["ConnectionState"] = None, provisioning_state: Optional[Union[str, "EndPointProvisioningState"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(PrivateEndpointConnection, self).__init__(**kwargs) <NEW_LINE> self.private_endpoint = private_endpoint <NEW_LINE> self.private_link_service_connection_state = private_link_service_connection_state <NEW_LINE> self.provisioning_state = provisioning_state | Properties of the PrivateEndpointConnection.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Resource Id.
:vartype id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param private_endpoint: The Private Endpoint resource for this Connection.
:type private_endpoint: ~azure.mgmt.servicebus.v2018_01_01_preview.models.PrivateEndpoint
:param private_link_service_connection_state: Details about the state of the connection.
:type private_link_service_connection_state:
~azure.mgmt.servicebus.v2018_01_01_preview.models.ConnectionState
:param provisioning_state: Provisioning state of the Private Endpoint Connection. Possible
values include: "Creating", "Updating", "Deleting", "Succeeded", "Canceled", "Failed".
:type provisioning_state: str or
~azure.mgmt.servicebus.v2018_01_01_preview.models.EndPointProvisioningState | 62598fbda8370b77170f05bc |
class ContainerNetworkMode(object): <NEW_LINE> <INDENT> service_name = None <NEW_LINE> def __init__(self, container): <NEW_LINE> <INDENT> self.container = container <NEW_LINE> <DEDENT> @property <NEW_LINE> def id(self): <NEW_LINE> <INDENT> return self.container.id <NEW_LINE> <DEDENT> @property <NEW_LINE> def mode(self): <NEW_LINE> <INDENT> return 'container:' + self.container.id | A network mode that uses a container's network stack. | 62598fbdd486a94d0ba2c1ab |
class ModifiedTransition(Transition): <NEW_LINE> <INDENT> def __init__(self, base_transition): <NEW_LINE> <INDENT> self.base_transition=base_transition <NEW_LINE> self.modifiers=list() <NEW_LINE> self.key=self.base_transition.key <NEW_LINE> self.flows=base_transition.flows <NEW_LINE> <DEDENT> def enabled(self, globalstate, localstate, te, t0, rng): <NEW_LINE> <INDENT> b_enabled=self.base_transition.enabled() <NEW_LINE> for m in self.modifiers: <NEW_LINE> <INDENT> if not m.enabled(globalstate, localstate, te, t0, rng): <NEW_LINE> <INDENT> b_enabled=False <NEW_LINE> <DEDENT> <DEDENT> modifier=1.0 <NEW_LINE> for m in self.modifiers: <NEW_LINE> <INDENT> modifier*=m.hazard_modifier(globalstate, localstate, t0, rng) <NEW_LINE> <DEDENT> hazard=base_transition.hazard(globalstate, localstate, t0, rng, modifier) <NEW_LINE> return hazard, b_enabled <NEW_LINE> <DEDENT> def fire(self, globalstate, localstate, t0, rng): <NEW_LINE> <INDENT> pass | This is a transition that has been modified by TransitionModifier objects. | 62598fbd3346ee7daa337736 |
class ApplicationListOptions(Model): <NEW_LINE> <INDENT> _attribute_map = { 'max_results': {'key': '', 'type': 'int'}, 'timeout': {'key': '', 'type': 'int'}, 'client_request_id': {'key': '', 'type': 'str'}, 'return_client_request_id': {'key': '', 'type': 'bool'}, 'ocp_date': {'key': '', 'type': 'rfc-1123'}, } <NEW_LINE> def __init__(self, *, max_results: int=1000, timeout: int=30, client_request_id: str=None, return_client_request_id: bool=False, ocp_date=None, **kwargs) -> None: <NEW_LINE> <INDENT> super(ApplicationListOptions, self).__init__(**kwargs) <NEW_LINE> self.max_results = max_results <NEW_LINE> self.timeout = timeout <NEW_LINE> self.client_request_id = client_request_id <NEW_LINE> self.return_client_request_id = return_client_request_id <NEW_LINE> self.ocp_date = ocp_date | Additional parameters for list operation.
:param max_results: The maximum number of items to return in the response.
A maximum of 1000 applications can be returned. Default value: 1000 .
:type max_results: int
:param timeout: The maximum time that the server can spend processing the
request, in seconds. The default is 30 seconds. Default value: 30 .
:type timeout: int
:param client_request_id: The caller-generated request identity, in the
form of a GUID with no decoration such as curly braces, e.g.
9C4D50EE-2D56-4CD3-8152-34347DC9F2B0.
:type client_request_id: str
:param return_client_request_id: Whether the server should return the
client-request-id in the response. Default value: False .
:type return_client_request_id: bool
:param ocp_date: The time the request was issued. Client libraries
typically set this to the current system clock time; set it explicitly if
you are calling the REST API directly.
:type ocp_date: datetime | 62598fbdbe7bc26dc9251f4a |
class BaseRemoteError(Exception): <NEW_LINE> <INDENT> pass | All exceptions from remote method are derived from this class. | 62598fbd956e5f7376df576c |
class DistributionClassXMLLoader(ComponentClassXMLLoader): <NEW_LINE> <INDENT> @read_annotations <NEW_LINE> def load_componentclass(self, element): <NEW_LINE> <INDENT> subblocks = ('Parameter', 'RandomDistribution') <NEW_LINE> children = self._load_blocks(element, blocks=subblocks) <NEW_LINE> distributionblock = expect_single(children["RandomDistribution"]) <NEW_LINE> return DistributionClass(name=element.get('name'), parameters=children["Parameter"], distributionblock=distributionblock) <NEW_LINE> <DEDENT> @read_annotations <NEW_LINE> def load_distributionblock(self, element): <NEW_LINE> <INDENT> subblocks = () <NEW_LINE> children = self._load_blocks(element, blocks=subblocks) <NEW_LINE> return DistributionBlock( standard_library=element.attrib['standardLibrary']) <NEW_LINE> <DEDENT> tag_to_loader = { "ComponentClass": load_componentclass, "RandomDistribution": load_distributionblock } | This class is used by XMLReader interny.
This class loads a NineML XML tree, and stores
the components in ``components``. It o records which file each XML node
was loaded in from, and stores this in ``component_srcs``. | 62598fbd5fdd1c0f98e5e16e |
class SSHConnect (Action): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Action.__init__(self, name=_("Connect")) <NEW_LINE> <DEDENT> def activate(self, leaf): <NEW_LINE> <INDENT> utils.spawn_in_terminal(["ssh", leaf[HOST_ADDRESS_KEY]]) <NEW_LINE> <DEDENT> def get_description(self): <NEW_LINE> <INDENT> return _("Connect to SSH host") <NEW_LINE> <DEDENT> def get_icon_name(self): <NEW_LINE> <INDENT> return "network-server" <NEW_LINE> <DEDENT> def item_types(self): <NEW_LINE> <INDENT> yield HostLeaf <NEW_LINE> <DEDENT> def valid_for_item(self, item): <NEW_LINE> <INDENT> if item.check_key(HOST_SERVICE_NAME_KEY): <NEW_LINE> <INDENT> return item[HOST_SERVICE_NAME_KEY] == 'ssh' <NEW_LINE> <DEDENT> return False | Used to launch a terminal connecting to the specified
SSH host. | 62598fbd5166f23b2e2435bb |
class DynamicsIsLinear(BaseDynamicsVisitor): <NEW_LINE> <INDENT> def is_linear(self, dynamics, outputs=None): <NEW_LINE> <INDENT> self.outputs = (set(dynamics.analog_send_port_names) if outputs is None else outputs) <NEW_LINE> substituted = dynamics.flatten() <NEW_LINE> DynamicsSubstituteAliases(substituted) <NEW_LINE> self.input_and_states = [ sympy.Symbol(i) for i in chain( substituted.state_variable_names, substituted.analog_receive_port_names, substituted.analog_reduce_port_names)] <NEW_LINE> try: <NEW_LINE> <INDENT> self.visit(substituted) <NEW_LINE> <DEDENT> except NineMLStopVisitException: <NEW_LINE> <INDENT> linear = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> linear = True <NEW_LINE> <DEDENT> return linear <NEW_LINE> <DEDENT> def action_dynamics(self, dynamics, **kwargs): <NEW_LINE> <INDENT> if dynamics.num_regimes > 1: <NEW_LINE> <INDENT> raise NineMLStopVisitException() <NEW_LINE> <DEDENT> <DEDENT> def action_oncondition(self, on_condition, **kwargs): <NEW_LINE> <INDENT> if on_condition.num_state_assignments: <NEW_LINE> <INDENT> raise NineMLStopVisitException() <NEW_LINE> <DEDENT> <DEDENT> def action_stateassignment(self, state_assignment, **kwargs): <NEW_LINE> <INDENT> self._check_linear(state_assignment) <NEW_LINE> <DEDENT> def action_timederivative(self, time_derivative, **kwargs): <NEW_LINE> <INDENT> self._check_linear(time_derivative) <NEW_LINE> <DEDENT> def action_alias(self, alias, **kwargs): <NEW_LINE> <INDENT> if alias.name in self.outputs: <NEW_LINE> <INDENT> self._check_linear(alias) <NEW_LINE> <DEDENT> <DEDENT> def _is_linear(self, expr): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return sympy.poly(expr.rhs, *self.input_and_states).is_linear <NEW_LINE> <DEDENT> except PolynomialError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def _check_linear(self, expr): <NEW_LINE> <INDENT> if not self._is_linear(expr): <NEW_LINE> <INDENT> raise NineMLStopVisitException() <NEW_LINE> <DEDENT> <DEDENT> def default_action(self, obj, nineml_cls, **kwargs): <NEW_LINE> <INDENT> pass | Checks to see whether the dynamics class is linear or nonlinear
Parameters
----------
dynamics : Dynamics
The dynamics element to check linearity of
outputs : list(str) | None
List of outputs that are relevant to the check. For example, if there
is an analog send port on a synapse that is not connected to the cell
then any alias that maps the state variable/inputs to the analog send
port is not relevant. | 62598fbddc8b845886d53797 |
class Random(object): <NEW_LINE> <INDENT> def __init__(self, seed=12345, state=None): <NEW_LINE> <INDENT> self.rng = np.random.mtrand.RandomState(seed=seed) <NEW_LINE> self.seed = seed <NEW_LINE> if state is None: <NEW_LINE> <INDENT> self.rng.seed(seed) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.state = state <NEW_LINE> <DEDENT> <DEDENT> def get_state(self): <NEW_LINE> <INDENT> return self.rng.get_state() <NEW_LINE> <DEDENT> def set_state(self, value): <NEW_LINE> <INDENT> return self.rng.set_state(value) <NEW_LINE> <DEDENT> state=property(get_state, set_state) <NEW_LINE> @property <NEW_LINE> def u(self): <NEW_LINE> <INDENT> return self.rng.random_sample() <NEW_LINE> <DEDENT> @property <NEW_LINE> def g(self): <NEW_LINE> <INDENT> return self.rng.standard_normal() <NEW_LINE> <DEDENT> def gamma(self, k, theta=1.0): <NEW_LINE> <INDENT> return self.rng.gamma(k,theta) <NEW_LINE> <DEDENT> def gvec(self, shape): <NEW_LINE> <INDENT> return self.rng.standard_normal(shape) | Class to interface with the standard pseudo-random number generator.
Initializes the standard numpy pseudo-random number generator from a seed
at the beginning of the simulation, and keeps track of the state so that
it can be output to the checkpoint files throughout the simulation.
Attributes:
rng: The random number generator to be used.
seed: The seed number to start the generator.
state: A tuple of five objects giving the current state of the random
number generator. The first is the type of random number generator,
here 'MT19937', the second is an array of 624 integers, the third
is the current position in the array that is being read from, the
fourth gives whether it has a gaussian random number stored, and
the fifth is this stored Gaussian random number, or else the last
Gaussian random number returned. | 62598fbd091ae35668704e01 |
class SubAppIdInfo(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.SubAppId = None <NEW_LINE> self.Name = None <NEW_LINE> self.Description = None <NEW_LINE> self.CreateTime = None <NEW_LINE> self.Status = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.SubAppId = params.get("SubAppId") <NEW_LINE> self.Name = params.get("Name") <NEW_LINE> self.Description = params.get("Description") <NEW_LINE> self.CreateTime = params.get("CreateTime") <NEW_LINE> self.Status = params.get("Status") | 子应用信息。
| 62598fbda8370b77170f05bd |
class PCA9685: <NEW_LINE> <INDENT> def __init__(self, channel, address=0x40, frequency=60, busnum=None): <NEW_LINE> <INDENT> import Adafruit_PCA9685 <NEW_LINE> if busnum is not None: <NEW_LINE> <INDENT> from Adafruit_GPIO import I2C <NEW_LINE> def get_bus(): <NEW_LINE> <INDENT> return busnum <NEW_LINE> <DEDENT> I2C.get_default_bus = get_bus <NEW_LINE> <DEDENT> self.pwm = Adafruit_PCA9685.PCA9685(address=address) <NEW_LINE> self.pwm.set_pwm_freq(frequency) <NEW_LINE> self.channel = channel <NEW_LINE> <DEDENT> def set_pulse(self, pulse): <NEW_LINE> <INDENT> self.pwm.set_pwm(self.channel, 0, pulse) <NEW_LINE> <DEDENT> def run(self, pulse): <NEW_LINE> <INDENT> self.set_pulse(pulse) | PWM motor controler using PCA9685 boards.
This is used for most RC Cars | 62598fbd4c3428357761a498 |
class ProblemRelation(object): <NEW_LINE> <INDENT> __slots__ = ['_name', '_patient_count', '_ratio'] <NEW_LINE> def __init__(self, name, patient_count, ratio): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> self._patient_count = patient_count <NEW_LINE> self._ratio = ratio <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def patient_count(self): <NEW_LINE> <INDENT> return self._patient_count <NEW_LINE> <DEDENT> @property <NEW_LINE> def ratio(self): <NEW_LINE> <INDENT> return self._ratio <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<ProblemRelation '%s' (patients: %d ; ratio: %.6f) @0x%x>" % (self._name, self._patient_count, self._ratio, id(self)) <NEW_LINE> <DEDENT> def _is_eq(self, other): <NEW_LINE> <INDENT> return (self._name == other._name and self._patient_count == other._patient_count and self._ratio == other._ratio) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self._is_eq(other) <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self._is_eq(other) <NEW_LINE> <DEDENT> def _is_lt(self, other): <NEW_LINE> <INDENT> if self.ratio > other.ratio: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif self.ratio < other.ratio: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> elif self.patient_count > other.patient_count: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif self.patient_count < other.patient_count: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> elif self.name < other.name: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> return self._is_lt(other) <NEW_LINE> <DEDENT> def __gt__(self, other): <NEW_LINE> <INDENT> return not self._is_lt(other) | A class to model a problem with a particular count of patients and
ratio of patients. | 62598fbd9c8ee82313040263 |
class InsertUserResponse(object): <NEW_LINE> <INDENT> openapi_types = { 'organisation_id': 'int', 'user_id': 'int', 'validation_errors': 'list[str]' } <NEW_LINE> attribute_map = { 'organisation_id': 'OrganisationId', 'user_id': 'UserId', 'validation_errors': 'ValidationErrors' } <NEW_LINE> def __init__(self, organisation_id=None, user_id=None, validation_errors=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._organisation_id = None <NEW_LINE> self._user_id = None <NEW_LINE> self._validation_errors = None <NEW_LINE> self.discriminator = None <NEW_LINE> if organisation_id is not None: <NEW_LINE> <INDENT> self.organisation_id = organisation_id <NEW_LINE> <DEDENT> if user_id is not None: <NEW_LINE> <INDENT> self.user_id = user_id <NEW_LINE> <DEDENT> if validation_errors is not None: <NEW_LINE> <INDENT> self.validation_errors = validation_errors <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def organisation_id(self): <NEW_LINE> <INDENT> return self._organisation_id <NEW_LINE> <DEDENT> @organisation_id.setter <NEW_LINE> def organisation_id(self, organisation_id): <NEW_LINE> <INDENT> self._organisation_id = organisation_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def user_id(self): <NEW_LINE> <INDENT> return self._user_id <NEW_LINE> <DEDENT> @user_id.setter <NEW_LINE> def user_id(self, user_id): <NEW_LINE> <INDENT> self._user_id = user_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def validation_errors(self): <NEW_LINE> <INDENT> return self._validation_errors <NEW_LINE> <DEDENT> @validation_errors.setter <NEW_LINE> def validation_errors(self, validation_errors): <NEW_LINE> <INDENT> self._validation_errors = validation_errors <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, InsertUserResponse): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, InsertUserResponse): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict() | NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually. | 62598fbd7d43ff24874274f3 |
class Get(base.Command): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def Args(parser): <NEW_LINE> <INDENT> parser.add_argument( 'operation', help='An identifier that uniquely identifies the operation.') <NEW_LINE> <DEDENT> @util.ReraiseHttpException <NEW_LINE> def Run(self, args): <NEW_LINE> <INDENT> sql_client = self.context['sql_client'] <NEW_LINE> resources = self.context['registry'] <NEW_LINE> util.ValidateInstanceName(args.instance) <NEW_LINE> instance_ref = resources.Parse(args.instance, collection='sql.instances') <NEW_LINE> operation_ref = resources.Parse( args.operation, collection='sql.operations', params={'project': instance_ref.project, 'instance': instance_ref.instance}) <NEW_LINE> result = sql_client.operations.Get(operation_ref.Request()) <NEW_LINE> return result <NEW_LINE> <DEDENT> def Display(self, unused_args, result): <NEW_LINE> <INDENT> self.format(result) | Retrieves information about a Cloud SQL instance operation. | 62598fbd97e22403b383b0e6 |
class FamilyVarObj(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> dict = defaultdict(list) <NEW_LINE> self.gene_family_dict = dict <NEW_LINE> self.gene_family_dict['Genes'] = TaxaVarObj() <NEW_LINE> self.gene_family_dict['RxLR'] = TaxaVarObj() <NEW_LINE> self.gene_family_dict['CRN'] = TaxaVarObj() <NEW_LINE> self.gene_family_dict['CAZY'] = TaxaVarObj() <NEW_LINE> self.gene_family_dict['Apoplastic:Cutinase'] = TaxaVarObj() <NEW_LINE> self.gene_family_dict['Apoplastic:Glucanase inhibitor'] = TaxaVarObj() <NEW_LINE> self.gene_family_dict['Apoplastic:NLP'] = TaxaVarObj() <NEW_LINE> self.gene_family_dict['Apoplastic:Phytotoxin'] = TaxaVarObj() <NEW_LINE> self.gene_family_dict['Apoplastic:Protease inhibitor (cathepsin)'] = TaxaVarObj() <NEW_LINE> self.gene_family_dict['Apoplastic:Protease inhibitor (cystatin-like)'] = TaxaVarObj() <NEW_LINE> self.gene_family_dict['Apoplastic:Protease inhibitor (Kazal-type)'] = TaxaVarObj() <NEW_LINE> self.gene_family_dict['MAMP:Elicitin'] = TaxaVarObj() <NEW_LINE> self.gene_family_dict['MAMP:Transglutaminase'] = TaxaVarObj() <NEW_LINE> <DEDENT> def add_family(self, family): <NEW_LINE> <INDENT> self.gene_family_dict[family] = TaxaVarObj() | An object containing TaxaVarObj's for different gene families. | 62598fbd283ffb24f3cf3a60 |
class TimeFormRange(FlaskForm): <NEW_LINE> <INDENT> datetime_1 = DateTimeField(u'Time 1') <NEW_LINE> datetime_2 = DateTimeField(u'Time 2') | Class to manage time range input | 62598fbd099cdd3c636754d1 |
class ShutdownHTTPHandler(http.Request): <NEW_LINE> <INDENT> def process(self): <NEW_LINE> <INDENT> self.loseConnection() | A HTTP handler that just immediately calls loseConnection. | 62598fbdd268445f26639c73 |
class PostManager(models.Manager): <NEW_LINE> <INDENT> def published(self, user=None, platform=None): <NEW_LINE> <INDENT> if user and user.is_staff: <NEW_LINE> <INDENT> min_published_status = base.DRAFT <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> min_published_status = base.PUBLISHED <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> from platforms import settings as platforms_settings <NEW_LINE> if platform and platforms_settings.USE_PLATFORMS: <NEW_LINE> <INDENT> query = self.platform(platform) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ImportError <NEW_LINE> <DEDENT> <DEDENT> except ImportError: <NEW_LINE> <INDENT> query = self.all() <NEW_LINE> <DEDENT> return query.filter( publishing_status__gte=min_published_status ).order_by('-created_at') | Get items that should be visible to the currently logged in user
- if no user is provided, only published items will be returned
- if platforms is provided, filter by platform | 62598fbda8370b77170f05be |
class Pastebin(callbacks.Plugin): <NEW_LINE> <INDENT> threaded = True <NEW_LINE> def pastebin(self, irc, msg, args, optlist, text): <NEW_LINE> <INDENT> api_key = self.registryValue('pastebinAPIkey') <NEW_LINE> if api_key == '': <NEW_LINE> <INDENT> irc.reply('Pastebin API key must be set. See plugins.pastebinAPIkey value.') <NEW_LINE> return <NEW_LINE> <DEDENT> api_url = 'http://pastebin.com/api/api_post.php' <NEW_LINE> visibility = self.registryValue('visibility').lower() <NEW_LINE> expiredate = self.registryValue('expire').lower() <NEW_LINE> pastename = msg.nick + "@" + msg.args[0] + "@" + strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) <NEW_LINE> for (key, value) in optlist: <NEW_LINE> <INDENT> if key == 'visibility': <NEW_LINE> <INDENT> visibility = value <NEW_LINE> <DEDENT> if key == 'pastename': <NEW_LINE> <INDENT> pastename = value <NEW_LINE> <DEDENT> if key == 'expire': <NEW_LINE> <INDENT> expire = value <NEW_LINE> <DEDENT> <DEDENT> visibility_map = {'public': '0', 'unlisted': '1', 'private': '2'} <NEW_LINE> visibility = visibility_map[visibility] <NEW_LINE> expiredate_map = {'never': 'N', '10min': '10M', '1hour': '1H', '1day': '1D', '1month': '1M'} <NEW_LINE> expiredate = expiredate_map[expiredate] <NEW_LINE> values = {'api_paste_code': text, 'api_paste_name': pastename, 'api_paste_format':'text', 'api_paste_private': visibility, 'api_paste_expire_date': expiredate, 'api_option': 'paste', 'api_dev_key': api_key } <NEW_LINE> data = urllib.urlencode(values) <NEW_LINE> req = urllib2.Request(api_url, data) <NEW_LINE> response = urllib2.urlopen(req) <NEW_LINE> the_page = response.read() <NEW_LINE> irc.reply(the_page) <NEW_LINE> <DEDENT> pastebin = wrap(pastebin, [getopts({'visibility': ('literal', ('public', 'unlisted', 'private')), 'pastename': ('something'), 'expire': ('literal', ('never', '10min', '1hour', '1day', '1month')) }), ('text')]) | This plugin contains a command to upload text to pastebin.com. | 62598fbd5fdd1c0f98e5e170 |
class Collection(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(Collection, self).__init__() <NEW_LINE> self._values_ = [] <NEW_LINE> <DEDENT> @property <NEW_LINE> def _values(self): <NEW_LINE> <INDENT> return self._values_ <NEW_LINE> <DEDENT> def __contains__(self, item): <NEW_LINE> <INDENT> return (item in self._values_) <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> return self._values_.__getitem__(key) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self._values_.__iter__() <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._values_) <NEW_LINE> <DEDENT> def index(self, item): <NEW_LINE> <INDENT> return self._values_.index(item) | Base class for collection classes. May also be used for part collections
that don't yet have any custom methods.
Has the following characteristics.:
* Container (implements __contains__)
* Iterable (delegates __iter__ to |list|)
* Sized (implements __len__)
* Sequence (delegates __getitem__ to |list|) | 62598fbd956e5f7376df576d |
class GetTouchMovementNode(ArmLogicTreeNode): <NEW_LINE> <INDENT> bl_idname = 'LNGetTouchMovementNode' <NEW_LINE> bl_label = 'Get Touch Movement' <NEW_LINE> arm_section = 'surface' <NEW_LINE> arm_version = 1 <NEW_LINE> def arm_init(self, context): <NEW_LINE> <INDENT> self.add_input('ArmFloatSocket', 'X Multiplier', default_value=-1.0) <NEW_LINE> self.add_input('ArmFloatSocket', 'Y Multiplier', default_value=-1.0) <NEW_LINE> self.add_output('ArmFloatSocket', 'X') <NEW_LINE> self.add_output('ArmFloatSocket', 'Y') <NEW_LINE> self.add_output('ArmFloatSocket', 'Multiplied X') <NEW_LINE> self.add_output('ArmFloatSocket', 'Multiplied Y') | Returns the movement values of the current touch event. | 62598fbdad47b63b2c5a7a34 |
class NSNitroNserrPbrNoloopback(NSNitroPbrErrors): <NEW_LINE> <INDENT> pass | Nitro error code 913
PBR cannot be configured on the loopback interface | 62598fbde1aae11d1e7ce914 |
class RegisterForm(FlaskForm): <NEW_LINE> <INDENT> first_name = StringField('First Name', validators = [InputRequired()]) <NEW_LINE> last_name = StringField('Last Name') <NEW_LINE> username = StringField('Username', validators = [InputRequired()]) <NEW_LINE> password = PasswordField('Password', validators = [InputRequired()]) <NEW_LINE> email = StringField('Email', validators = [InputRequired()]) | Form to register a new user | 62598fbdf9cc0f698b1c53be |
class Parte(): <NEW_LINE> <INDENT> global log <NEW_LINE> log = Log() <NEW_LINE> def __init__(self, fileName, stopOnNo, np): <NEW_LINE> <INDENT> self.partIn = PartIn() <NEW_LINE> self.fileName = fileName.split('.')[0] <NEW_LINE> self.testFileName = self.fileName+"_test" <NEW_LINE> self.partOut1 = PartOut(fileName) <NEW_LINE> self.partOut2 = PartOut(self.testFileName+".cpp") <NEW_LINE> self.stopOnNo = stopOnNo <NEW_LINE> self.noOutOnSuccess = np <NEW_LINE> <DEDENT> def run(self, i=None): <NEW_LINE> <INDENT> output = '' <NEW_LINE> inputString = self.partIn.input(i) <NEW_LINE> thread1 = Thread(target=self.partOut1.process, args=(inputString, )) <NEW_LINE> thread2 = Thread(target=self.partOut2.process, args=(inputString, )) <NEW_LINE> self.executeThreads(thread1, thread2) <NEW_LINE> out1 = self.partOut1.returnOutput() <NEW_LINE> out2 = self.partOut2.returnOutput() <NEW_LINE> output = 'input:\n'+inputString+'\noutput1:\n'+out1+'\noutput2:\n'+out2+'\n' <NEW_LINE> if out1!=out2: <NEW_LINE> <INDENT> log.warning(output+'Error!') <NEW_LINE> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not self.noOutOnSuccess: <NEW_LINE> <INDENT> log.success(output+'Success!') <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> <DEDENT> def executeThreads(self, *threads): <NEW_LINE> <INDENT> [x.start() for x in threads] <NEW_LINE> [x.join() for x in threads] <NEW_LINE> <DEDENT> def multipleRun(self, n): <NEW_LINE> <INDENT> for i in range(0,n): <NEW_LINE> <INDENT> log.display('.'*6+'run-'+str(i+1)+'.'*6) <NEW_LINE> if not self.run(i) and self.stopOnNo: <NEW_LINE> <INDENT> return | code to use input and output python code to write input, get output, compare them and display | 62598fbdcc0a2c111447b1ec |
class StorageAccountKey(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'key_name': {'readonly': True}, 'value': {'readonly': True}, 'permissions': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'key_name': {'key': 'keyName', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'}, 'permissions': {'key': 'permissions', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(StorageAccountKey, self).__init__(**kwargs) <NEW_LINE> self.key_name = None <NEW_LINE> self.value = None <NEW_LINE> self.permissions = None | An access key for the storage account.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar key_name: Name of the key.
:vartype key_name: str
:ivar value: Base 64-encoded value of the key.
:vartype value: str
:ivar permissions: Permissions for the key -- read-only or full permissions. Possible values
include: "Read", "Full".
:vartype permissions: str or ~azure.mgmt.storage.v2020_08_01_preview.models.KeyPermission | 62598fbd7b180e01f3e4913f |
class EditImportedStatusCmd(_MPxCommand): <NEW_LINE> <INDENT> def __init__(self, node, imported): pass <NEW_LINE> def doIt(self, args): pass <NEW_LINE> def isUndoable(self): pass <NEW_LINE> def redoIt(self): pass <NEW_LINE> def undoIt(self): pass <NEW_LINE> @staticmethod <NEW_LINE> def creator(): pass <NEW_LINE> @staticmethod <NEW_LINE> def execute(node, imported): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> __dict__ = None <NEW_LINE> __weakref__ = None <NEW_LINE> imported = None <NEW_LINE> kCmdName = 'editImportedStatus' <NEW_LINE> node = None | Command to unapply and reapply a change of the imported status.
This command is a private implementation detail of this module and should
not be called otherwise. | 62598fbd7047854f4633f5b4 |
class SettingsBase: <NEW_LINE> <INDENT> id = db.Column( db.Integer, primary_key=True ) <NEW_LINE> module = db.Column( db.String, index=True, nullable=False ) <NEW_LINE> name = db.Column( db.String, index=True, nullable=False ) <NEW_LINE> @strict_classproperty <NEW_LINE> @staticmethod <NEW_LINE> def __auto_table_args(): <NEW_LINE> <INDENT> return (db.CheckConstraint('module = lower(module)', 'lowercase_module'), db.CheckConstraint('name = lower(name)', 'lowercase_name')) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def delete(cls, module, *names, **kwargs): <NEW_LINE> <INDENT> if not names: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> (cls.query .filter(cls.name.in_(names), cls.module == module) .filter_by(**kwargs) .delete(synchronize_session='fetch')) <NEW_LINE> db.session.flush() <NEW_LINE> cls._clear_cache() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def delete_all(cls, module, **kwargs): <NEW_LINE> <INDENT> cls.query.filter_by(module=module, **kwargs).delete() <NEW_LINE> db.session.flush() <NEW_LINE> cls._clear_cache() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _get_cache(cls, kwargs): <NEW_LINE> <INDENT> if not has_request_context(): <NEW_LINE> <INDENT> return defaultdict(dict), False <NEW_LINE> <DEDENT> key = (cls, frozenset(kwargs.items())) <NEW_LINE> try: <NEW_LINE> <INDENT> return g.global_settings_cache[key], True <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> g.global_settings_cache = cache = dict() <NEW_LINE> cache[key] = rv = defaultdict(dict) <NEW_LINE> return rv, False <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return g.global_settings_cache.setdefault(key, defaultdict(dict)), False <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def _clear_cache(): <NEW_LINE> <INDENT> if has_request_context(): <NEW_LINE> <INDENT> g.pop('global_settings_cache', None) | Base class for any kind of setting tables. | 62598fbd97e22403b383b0e7 |
class PauseClusterMessage(AWSProperty): <NEW_LINE> <INDENT> props: PropsDictType = { "ClusterIdentifier": (str, True), } | `PauseClusterMessage <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-redshift-scheduledaction-pauseclustermessage.html>`__ | 62598fbd656771135c48984e |
class BagAclNhEnum(Enum): <NEW_LINE> <INDENT> nexthop_none = 0 <NEW_LINE> nexthop_default = 1 <NEW_LINE> nexthop = 2 <NEW_LINE> @staticmethod <NEW_LINE> def _meta_info(): <NEW_LINE> <INDENT> from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ipv6_acl_oper as meta <NEW_LINE> return meta._meta_table['BagAclNhEnum'] | BagAclNhEnum
Bag acl nh
.. data:: nexthop_none = 0
Next Hop None
.. data:: nexthop_default = 1
Nexthop Default
.. data:: nexthop = 2
Nexthop | 62598fbd283ffb24f3cf3a62 |
class CounterButton: <NEW_LINE> <INDENT> def __init__(self, numbers, topic, ff, max_value=10): <NEW_LINE> <INDENT> self.counter = 0 <NEW_LINE> self.max_value = max_value <NEW_LINE> self.ff = ff <NEW_LINE> self.buttons = Buttons(numbers) <NEW_LINE> self.pub = rospy.Publisher(topic, Int8, queue_size=10) <NEW_LINE> <DEDENT> def update(self, buttons): <NEW_LINE> <INDENT> self.buttons.update(buttons) <NEW_LINE> if self.buttons: <NEW_LINE> <INDENT> rospy.logdebug("{buttons} max={max_value}".format(buttons=self.buttons, max_value=self.max_value)) <NEW_LINE> self.pub.publish(self.counter) <NEW_LINE> self.counter += 1 <NEW_LINE> if self.counter > self.max_value: <NEW_LINE> <INDENT> self.counter = 0 <NEW_LINE> <DEDENT> self.ff.feedback() | Convert a button pressed to counter topic | 62598fbd50812a4eaa620cda |
class SubDivisionInline(admin.StackedInline): <NEW_LINE> <INDENT> model = SubDivision <NEW_LINE> extra = 1 | docstring for SubDivisionInline | 62598fbd9f2886367281896b |
class ColumnFormatter(Formatter): <NEW_LINE> <INDENT> def __init__(self, column_index, FORMAT, custom_converter=None): <NEW_LINE> <INDENT> self.indices = column_index <NEW_LINE> if isinstance(column_index, int): <NEW_LINE> <INDENT> func = lambda r, c, v: c == column_index <NEW_LINE> <DEDENT> elif isinstance(column_index, list): <NEW_LINE> <INDENT> if len(column_index) == 0: <NEW_LINE> <INDENT> raise IndexError("column list is empty. do not waste resurce") <NEW_LINE> <DEDENT> if is_array_type(column_index, int): <NEW_LINE> <INDENT> func = lambda r, c, v: c in column_index <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise IndexError("column list should be a list of integers") <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError("%s is not supported" % type(column_index)) <NEW_LINE> <DEDENT> Formatter.__init__(self, func, FORMAT, custom_converter) | Apply formatting on columns | 62598fbdaad79263cf42e9b5 |
class CheckNameAvailabilityResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'name_available': {'readonly': True}, 'reason': {'readonly': True}, 'message': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'name_available': {'key': 'nameAvailable', 'type': 'bool'}, 'reason': {'key': 'reason', 'type': 'str'}, 'message': {'key': 'message', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(CheckNameAvailabilityResult, self).__init__(**kwargs) <NEW_LINE> self.name_available = None <NEW_LINE> self.reason = None <NEW_LINE> self.message = None | The CheckNameAvailability operation response.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar name_available: Gets a boolean value that indicates whether the name is available for you
to use. If true, the name is available. If false, the name has already been taken or invalid
and cannot be used.
:vartype name_available: bool
:ivar reason: Gets the reason that a Storage Sync Service name could not be used. The Reason
element is only returned if NameAvailable is false. Possible values include: "Invalid",
"AlreadyExists".
:vartype reason: str or ~azure.mgmt.storagesync.models.NameAvailabilityReason
:ivar message: Gets an error message explaining the Reason value in more detail.
:vartype message: str | 62598fbdd268445f26639c74 |
class MaskPoints(FilterBase): <NEW_LINE> <INDENT> __version__ = 0 <NEW_LINE> filter = Instance(tvtk.MaskPoints, args=(), allow_none=False, record=True) <NEW_LINE> input_info = PipelineInfo(datasets=['any'], attribute_types=['any'], attributes=['any']) <NEW_LINE> output_info = PipelineInfo(datasets=['poly_data'], attribute_types=['any'], attributes=['any']) <NEW_LINE> def update_pipeline(self): <NEW_LINE> <INDENT> self.filter.maximum_number_of_points = self._find_number_of_points_in_input() <NEW_LINE> super(MaskPoints, self).update_pipeline() <NEW_LINE> <DEDENT> def _find_number_of_points_in_input(self): <NEW_LINE> <INDENT> inp = self.inputs[0].outputs[0] <NEW_LINE> if hasattr(inp, 'update'): <NEW_LINE> <INDENT> inp.update() <NEW_LINE> <DEDENT> return inp.number_of_points | Selectively passes the input points downstream. This can be
used to subsample the input points. Note that this does not pass
geometry data, this means all grid information is lost. | 62598fbdd486a94d0ba2c1af |
class EDTestSuitePluginUnitGroupSaxsv1_0(EDTestSuite): <NEW_LINE> <INDENT> def process(self): <NEW_LINE> <INDENT> self.addTestCaseFromName("EDTestCasePluginUnitExecSaxsAddv1_0") <NEW_LINE> self.addTestCaseFromName("EDTestCasePluginUnitExecSaxsAnglev1_0") <NEW_LINE> self.addTestCaseFromName("EDTestCasePluginUnitExecSaxsCurvesv1_0") <NEW_LINE> self.addTestCaseFromName("EDTestCasePluginUnitExecSaxsMacv1_0") <NEW_LINE> self.addTestCaseFromName("EDTestCasePluginUnitExecSaxsDelMetadatav1_0") <NEW_LINE> self.addTestCaseFromName("EDTestCasePluginUnitExecSaxsAddMetadatav1_0") | This is the test suite Unit for EDNA Group Saxsv1_0
It will run subsequently all unit tests . | 62598fbd5fc7496912d4836b |
class TrailSectionGeoJSONSerializer(GeoFeatureModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = TrailSection <NEW_LINE> url_field_name = 'guid' <NEW_LINE> fields = [ 'guid', 'name', 'grade', 'image', 'notes', 'geom' ] <NEW_LINE> geo_field = 'geom' | Serializer class for a trail_mapper section model as GeoJSON. | 62598fbd92d797404e388c53 |
class GPS(ABC): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> @abstractmethod <NEW_LINE> def baud_rate(cls): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> @abstractmethod <NEW_LINE> def boot_time(cls): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> @abstractmethod <NEW_LINE> def serial_lock_timeout(cls): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> @abstractmethod <NEW_LINE> def serial_comms_timeout(cls): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self, interface, uart, verbose=False): <NEW_LINE> <INDENT> self.__interface = interface <NEW_LINE> self._serial = HostSerial(uart, self.baud_rate()) <NEW_LINE> self._verbose = verbose <NEW_LINE> <DEDENT> def power_on(self): <NEW_LINE> <INDENT> self.__interface.power_gps(True) <NEW_LINE> time.sleep(self.boot_time()) <NEW_LINE> <DEDENT> def power_off(self): <NEW_LINE> <INDENT> self.__interface.power_gps(False) <NEW_LINE> <DEDENT> def open(self): <NEW_LINE> <INDENT> self._serial.open(self.serial_lock_timeout(), self.serial_comms_timeout()) <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self._serial.close() <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def report(self, message_class): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def report_all(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __str__(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.__class__.__name__ + ":{interface:%s, serial:%s, verbose:%s}" % (self.__interface, self._serial, self._verbose) | classdocs | 62598fbd4428ac0f6e658703 |
class ImageRequestSerializer(GeoFeatureModelSerializer, serializers.HyperlinkedModelSerializer): <NEW_LINE> <INDENT> request_texts = RequestTextSerializer(many=True) <NEW_LINE> submitted_images = SubmittedImageSerializer(many=True) <NEW_LINE> creator = serializers.ReadOnlyField(source='creator.username') <NEW_LINE> url = serializers.HyperlinkedIdentityField(view_name='api_image_requests_detail', format='html') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = ImageRequest <NEW_LINE> geo_field = 'points' <NEW_LINE> fields = ('id', 'created', 'url', 'submitted_images', 'wikidata_id', 'points', 'request_texts', 'creator') <NEW_LINE> <DEDENT> def create(self, data): <NEW_LINE> <INDENT> request_texts = data.pop('request_texts') <NEW_LINE> submitted_images = data.pop('submitted_images') <NEW_LINE> image_request_object = ImageRequest.objects.create(**data) <NEW_LINE> for text in request_texts: <NEW_LINE> <INDENT> RequestText.objects.create(image_request=image_request_object, **text) <NEW_LINE> <DEDENT> return image_request_object | Serializers the image requests. | 62598fbd8a349b6b4368641e |
class Client(BaseClient): <NEW_LINE> <INDENT> def __init__(self, credentials=None, http=None, use_gax=None): <NEW_LINE> <INDENT> super(Client, self).__init__(credentials=credentials, http=http) <NEW_LINE> if use_gax is None: <NEW_LINE> <INDENT> self._use_gax = _USE_GAX <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._use_gax = use_gax <NEW_LINE> <DEDENT> <DEDENT> _connection_class = Connection <NEW_LINE> _speech_api = None <NEW_LINE> def sample(self, content=None, source_uri=None, encoding=None, sample_rate=None): <NEW_LINE> <INDENT> return Sample(content=content, source_uri=source_uri, encoding=encoding, sample_rate=sample_rate, client=self) <NEW_LINE> <DEDENT> @property <NEW_LINE> def speech_api(self): <NEW_LINE> <INDENT> if self._speech_api is None: <NEW_LINE> <INDENT> if self._use_gax: <NEW_LINE> <INDENT> self._speech_api = GAPICSpeechAPI(self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._speech_api = _JSONSpeechAPI(self) <NEW_LINE> <DEDENT> <DEDENT> return self._speech_api | Client to bundle configuration needed for API requests.
:type credentials: :class:`oauth2client.client.OAuth2Credentials` or
:class:`NoneType`
:param credentials: The OAuth2 Credentials to use for the connection
owned by this client. If not passed (and if no ``http``
object is passed), falls back to the default inferred
from the environment.
:type http: :class:`httplib2.Http` or class that defines ``request()``.
:param http: An optional HTTP object to make requests. If not passed, an
``http`` object is created that is bound to the
``credentials`` for the current object.
:type use_gax: bool
:param use_gax: (Optional) Explicitly specifies whether
to use the gRPC transport (via GAX) or HTTP. If unset,
falls back to the ``GOOGLE_CLOUD_DISABLE_GRPC`` environment
variable | 62598fbdf9cc0f698b1c53bf |
class OrderView(FlaskView): <NEW_LINE> <INDENT> @cross_origin(headers=['Content-Type']) <NEW_LINE> def index(self): <NEW_LINE> <INDENT> return jsonify(status='OK', orders=dict([(elem.name, elem.value) for elem in Character.Orders])) | API to return the list of valid orders. | 62598fbd21bff66bcd722e4b |
class Stack(object): <NEW_LINE> <INDENT> def __init__(self, dtype=None): <NEW_LINE> <INDENT> self._dtype = dtype <NEW_LINE> <DEDENT> def __call__(self, data): <NEW_LINE> <INDENT> return _stack_arrs(data, True, self._dtype) | Stack the input data samples to construct the batch.
The N input samples must have the same shape/length and will be stacked to construct a batch.
Parameters
----------
dtype : str or numpy.dtype, default None
The value type of the output. If it is set to None, the input data type is used.
Examples
--------
>>> from gluonnlp.data import bf
>>> # Stack multiple lists
>>> a = [1, 2, 3, 4]
>>> b = [4, 5, 6, 8]
>>> c = [8, 9, 1, 2]
>>> bf.Stack()([a, b, c])
[[1. 2. 3. 4.]
[4. 5. 6. 8.]
[8. 9. 1. 2.]]
<NDArray 3x4 @cpu(0)>
>>> # Stack multiple numpy.ndarrays
>>> import numpy as np
>>> a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
>>> b = np.array([[5, 6, 7, 8], [1, 2, 3, 4]])
>>> bf.Stack()([a, b])
[[[1. 2. 3. 4.]
[5. 6. 7. 8.]]
[[5. 6. 7. 8.]
[1. 2. 3. 4.]]]
<NDArray 2x2x4 @cpu(0)>
>>> # Stack multiple NDArrays
>>> import mxnet as mx
>>> a = mx.nd.array([[1, 2, 3, 4], [5, 6, 7, 8]])
>>> b = mx.nd.array([[5, 6, 7, 8], [1, 2, 3, 4]])
>>> bf.Stack()([a, b])
[[[1. 2. 3. 4.]
[5. 6. 7. 8.]]
[[5. 6. 7. 8.]
[1. 2. 3. 4.]]]
<NDArray 2x2x4 @cpu(0)> | 62598fbd442bda511e95c63e |
class BaseWebPage(IWebPage): <NEW_LINE> <INDENT> def __init__(self, url:str, html:str, headers:Mapping[str, str]): <NEW_LINE> <INDENT> _raise_not_dict(headers, "headers") <NEW_LINE> self.url = url <NEW_LINE> self.html = html <NEW_LINE> self.headers = CaseInsensitiveDict(headers) <NEW_LINE> self.scripts: List[str] = [] <NEW_LINE> self.meta: Mapping[str, str] = {} <NEW_LINE> self._parse_html() <NEW_LINE> <DEDENT> def _parse_html(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def new_from_url(cls, url: str, **kwargs:Any) -> IWebPage: <NEW_LINE> <INDENT> response = requests.get(url, **kwargs) <NEW_LINE> return cls.new_from_response(response) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def new_from_response(cls, response:requests.Response) -> IWebPage: <NEW_LINE> <INDENT> return cls(response.url, html=response.text, headers=response.headers) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> async def new_from_url_async(cls, url: str, verify: bool = True, aiohttp_client_session: aiohttp.ClientSession = None, **kwargs:Any) -> IWebPage: <NEW_LINE> <INDENT> if not aiohttp_client_session: <NEW_LINE> <INDENT> connector = aiohttp.TCPConnector(ssl=verify) <NEW_LINE> aiohttp_client_session = aiohttp.ClientSession(connector=connector) <NEW_LINE> <DEDENT> async with aiohttp_client_session.get(url, **kwargs) as response: <NEW_LINE> <INDENT> return await cls.new_from_response_async(response) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> async def new_from_response_async(cls, response:aiohttp.ClientResponse) -> IWebPage: <NEW_LINE> <INDENT> html = await response.text() <NEW_LINE> return cls(str(response.url), html=html, headers=response.headers) | Implements factory methods for a WebPage.
Subclasses must implement _parse_html() and select(string). | 62598fbd4527f215b58ea0af |
class TempTrackerSetupTestCase(unittest.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> cls.parser = tracker.process_args() <NEW_LINE> cls.database_dir = 'example' <NEW_LINE> cls.path_to_tracker = os.path.join(cls.database_dir, '.tracker.json') <NEW_LINE> cls.path_to_backup_tracker = os.path.join(cls.database_dir, '.tracker.json.bak') <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> shutil.copyfile(self.path_to_tracker, self.path_to_backup_tracker) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> os.rename(self.path_to_backup_tracker, self.path_to_tracker) | Base class to setup environment for tests which modify the tracker | 62598fbde5267d203ee6bae0 |
class Categories(common.ViewletBase): <NEW_LINE> <INDENT> def update(self): <NEW_LINE> <INDENT> super(Categories, self).update() <NEW_LINE> backend = get_backend(self.context) <NEW_LINE> self.categories = backend.get_categories() | Display categories | 62598fbd7047854f4633f5b5 |
class ConfigUpdateProperty(Command): <NEW_LINE> <INDENT> log = logging.getLogger(__name__) <NEW_LINE> def get_parser(self, prog_name): <NEW_LINE> <INDENT> parser = super(ConfigUpdateProperty, self).get_parser(prog_name) <NEW_LINE> parser.add_argument('--tag_json_file', '-f', help='JSON file with tags to update', required=False) <NEW_LINE> parser.add_argument('--tags', '-t', help='JSON tags string', required=False) <NEW_LINE> return parser <NEW_LINE> <DEDENT> def take_action(self, parsed_args): <NEW_LINE> <INDENT> self.log.debug(parsed_args) <NEW_LINE> try: <NEW_LINE> <INDENT> if parsed_args.tag_json_file is None and parsed_args.tags is None: <NEW_LINE> <INDENT> self.app.stdout.write("Provide at least one parameter") <NEW_LINE> return <NEW_LINE> <DEDENT> if parsed_args.tag_json_file is not None and parsed_args.tags is not None: <NEW_LINE> <INDENT> self.app.stdout.write("Provide only one parameter") <NEW_LINE> return <NEW_LINE> <DEDENT> if parsed_args.tag_json_file is not None: <NEW_LINE> <INDENT> with Utility.open_file(parsed_args.tag_json_file) as handle: <NEW_LINE> <INDENT> input_payload = handle.read() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> input_payload = parsed_args.tags <NEW_LINE> <DEDENT> payload = json.loads(input_payload) <NEW_LINE> api_instance = test_sdk_client.ConfigurationApi(Utility.set_headers()) <NEW_LINE> api_response = api_instance.update_property(payload) <NEW_LINE> print(api_response) <NEW_LINE> <DEDENT> except Exception as exception: <NEW_LINE> <INDENT> Utility.print_exception(exception) | Update config property. | 62598fbd796e427e5384e977 |
class NoteEditor(BaseEditor): <NEW_LINE> <INDENT> gladefile = "NoteSlave" <NEW_LINE> proxy_widgets = ('notes', ) <NEW_LINE> size = (500, 200) <NEW_LINE> model_type = object <NEW_LINE> def __init__(self, store, model, attr_name='notes', title=u'', label_text=None, message_text=None, mandatory=False, visual_mode=False, ok_button_label=None, cancel_button_label=None, min_length=0): <NEW_LINE> <INDENT> self.title = title <NEW_LINE> self.label_text = label_text <NEW_LINE> self.message_text = message_text <NEW_LINE> self.mandatory = mandatory <NEW_LINE> self.attr_name = attr_name <NEW_LINE> self.min_length = min_length <NEW_LINE> self.original_notes = getattr(model, attr_name, u'') <NEW_LINE> BaseEditor.__init__(self, store, model, visual_mode=visual_mode) <NEW_LINE> self._setup_widgets() <NEW_LINE> if ok_button_label is not None: <NEW_LINE> <INDENT> self.main_dialog.ok_button.set_label(ok_button_label) <NEW_LINE> <DEDENT> if cancel_button_label is not None: <NEW_LINE> <INDENT> self.main_dialog.cancel_button.set_label(cancel_button_label) <NEW_LINE> <DEDENT> <DEDENT> def _setup_widgets(self): <NEW_LINE> <INDENT> if self.message_text: <NEW_LINE> <INDENT> self.message_label.set_text(self.message_text) <NEW_LINE> self.message_label.set_visible(True) <NEW_LINE> <DEDENT> if self.label_text: <NEW_LINE> <INDENT> self.observations_label.set_text(self.label_text) <NEW_LINE> <DEDENT> self.notes.set_accepts_tab(False) <NEW_LINE> self.notes.set_property('mandatory', self.mandatory) <NEW_LINE> <DEDENT> def setup_proxies(self): <NEW_LINE> <INDENT> self.notes.set_property('model-attribute', self.attr_name) <NEW_LINE> self.add_proxy(self.model, NoteEditor.proxy_widgets) <NEW_LINE> <DEDENT> def create_model(self, store): <NEW_LINE> <INDENT> return Note() <NEW_LINE> <DEDENT> def get_title(self, *args): <NEW_LINE> <INDENT> return self.title <NEW_LINE> <DEDENT> def on_cancel(self): <NEW_LINE> <INDENT> if not isinstance(self.model, Domain): <NEW_LINE> <INDENT> setattr(self.model, self.attr_name, self.original_notes) <NEW_LINE> <DEDENT> <DEDENT> def confirm(self): <NEW_LINE> <INDENT> if len(self.notes.read()) < self.min_length: <NEW_LINE> <INDENT> warning(_("The note must have at least %s characters.") % self.min_length) <NEW_LINE> return <NEW_LINE> <DEDENT> BaseEditor.confirm(self) | Simple editor that offers a label and a textview. | 62598fbdaad79263cf42e9b6 |
class BitmapsExtension(BigEndianStructure): <NEW_LINE> <INDENT> _fields_ = [ ("nb_bitmaps", c_uint32), ("reserved", c_uint32), ("bitmap_directory_size", c_uint64), ("bitmap_directory_offset", c_uint64), ] | from qcow2.h: Qcow2BitmapHeaderExt | 62598fbd97e22403b383b0ea |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.