code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class Client(object): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.http_client = http.HTTPClient(*args, **kwargs) <NEW_LINE> self.chassis = chassis.ChassisManager(self.http_client) <NEW_LINE> self.node = node.NodeManager(self.http_client) <NEW_LINE> self.port = port.PortManager(self.http_client) <NEW_LINE> self.driver = driver.DriverManager(self.http_client)
Client for the Ironic v1 API. :param string endpoint: A user-supplied endpoint URL for the ironic service. :param function token: Provides token for authentication. :param integer timeout: Allows customization of the timeout for client http requests. (optional)
62598faecc0a2c111447b009
class WrapAbsZeroScaled0p9LinearFewShotFetchEnv(WrapAbsScaled0p9LinearBasicFewShotFetchEnv): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> return super().reset(task_params={'goal_color_center': np.zeros(3)}, obs_task_params=np.zeros(3))
This is a debug env, do not use!
62598fae44b2445a339b696c
class FireWallRule: <NEW_LINE> <INDENT> def __init__(self, items): <NEW_LINE> <INDENT> self.__dict__.update(items) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def create(cls, api_client, ipaddressid=None, protocol=None, cidrlist=None, startport=None, endport=None, projectid=None, vpcid=None, data=None, ipaddress=None): <NEW_LINE> <INDENT> cmd = {} <NEW_LINE> if ipaddressid: <NEW_LINE> <INDENT> cmd['ipaddressid'] = ipaddressid <NEW_LINE> <DEDENT> elif ipaddress: <NEW_LINE> <INDENT> cmd['ipaddressid'] = ipaddress.ipaddress.id <NEW_LINE> <DEDENT> if protocol: <NEW_LINE> <INDENT> cmd['protocol'] = protocol <NEW_LINE> <DEDENT> elif 'protocol' in data: <NEW_LINE> <INDENT> cmd['protocol'] = data['protocol'] <NEW_LINE> <DEDENT> if cidrlist: <NEW_LINE> <INDENT> cmd['cidrlist'] = cidrlist <NEW_LINE> <DEDENT> elif 'cidrlist' in data: <NEW_LINE> <INDENT> cmd['cidrlist'] = data['cidrlist'] <NEW_LINE> <DEDENT> if startport: <NEW_LINE> <INDENT> cmd['startport'] = startport <NEW_LINE> <DEDENT> elif 'startport' in data: <NEW_LINE> <INDENT> cmd['startport'] = data['startport'] <NEW_LINE> <DEDENT> if endport: <NEW_LINE> <INDENT> cmd['endport'] = endport <NEW_LINE> <DEDENT> elif 'endport' in data: <NEW_LINE> <INDENT> cmd['endport'] = data['endport'] <NEW_LINE> <DEDENT> if projectid: <NEW_LINE> <INDENT> cmd['projectid'] = projectid <NEW_LINE> <DEDENT> if vpcid: <NEW_LINE> <INDENT> cmd['vpcid'] = vpcid <NEW_LINE> <DEDENT> return FireWallRule(api_client.createFirewallRule(**cmd)) <NEW_LINE> <DEDENT> def delete(self, api_client): <NEW_LINE> <INDENT> cmd = {'id': self.id} <NEW_LINE> api_client.deleteFirewallRule(**cmd) <NEW_LINE> return <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def list(cls, api_client, **kwargs): <NEW_LINE> <INDENT> cmd = {} <NEW_LINE> cmd.update(kwargs) <NEW_LINE> if 'account' in kwargs.keys() and 'domainid' in kwargs.keys(): <NEW_LINE> <INDENT> cmd['listall'] = True <NEW_LINE> <DEDENT> return api_client.listFirewallRules(**cmd)
Manage Firewall rule
62598fae23849d37ff8510ab
class HomeView(BaseView): <NEW_LINE> <INDENT> def index(self, request, template='home/index2.html'): <NEW_LINE> <INDENT> return render(request, template)
主页试图类
62598fae21bff66bcd722c5f
class PrivateTagsAPITests(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.user = get_user_model().objects.create_user( 'test@test.com', 'password123' ) <NEW_LINE> self.client = APIClient() <NEW_LINE> self.client.force_authenticate(self.user) <NEW_LINE> <DEDENT> def test_retrieve_tags(self): <NEW_LINE> <INDENT> Tag.objects.create(user=self.user, name='Vegan') <NEW_LINE> Tag.objects.create(user=self.user, name='Desert') <NEW_LINE> res = self.client.get(TAGS_URL) <NEW_LINE> tags = Tag.objects.all().order_by('-name') <NEW_LINE> serializer = TagSerializer(tags, many=True) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK) <NEW_LINE> self.assertEqual(res.data, serializer.data) <NEW_LINE> <DEDENT> def test_tags_limited_to_user(self): <NEW_LINE> <INDENT> self.user2 = get_user_model().objects.create_user( 'test@test2.com', 'testPass' ) <NEW_LINE> Tag.objects.create(user=self.user2, name='Fruity') <NEW_LINE> tag = Tag.objects.create(user=self.user, name="Comfort Food") <NEW_LINE> res = self.client.get(TAGS_URL) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK) <NEW_LINE> self.assertEqual(len(res.data), 1) <NEW_LINE> self.assertEqual(res.data[0]['name'], tag.name) <NEW_LINE> <DEDENT> def test_create_tag_successful(self): <NEW_LINE> <INDENT> payload = {'name': 'TestTag'} <NEW_LINE> self.client.post(TAGS_URL, payload) <NEW_LINE> tag = Tag.objects.filter(user=self.user, name=payload['name']).exists() <NEW_LINE> self.assertTrue(tag) <NEW_LINE> <DEDENT> def test_tag_must_be_valid(self): <NEW_LINE> <INDENT> payload = {'name': ''} <NEW_LINE> res = self.client.post(TAGS_URL, payload) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> def test_retrieve_tags_assigned_to_recipes(self): <NEW_LINE> <INDENT> tag1 = Tag.objects.create(user=self.user, name="Breakfast") <NEW_LINE> tag2 = Tag.objects.create(user=self.user, name="Lunch") <NEW_LINE> recipe = Recipe.objects.create( user=self.user, title="Eggs", price=5.00, time_minutes=12 ) <NEW_LINE> recipe.tags.add(tag1) <NEW_LINE> res = self.client.get(TAGS_URL, {'assigned_only': 1}) <NEW_LINE> serializer1 = TagSerializer(tag1) <NEW_LINE> serializer2 = TagSerializer(tag2) <NEW_LINE> self.assertIn(serializer1.data, res.data) <NEW_LINE> self.assertNotIn(serializer2.data, res.data)
Test the authorized user API
62598faebe8e80087fbbf05c
class GetData: <NEW_LINE> <INDENT> def __init__(self, nic): <NEW_LINE> <INDENT> self.nic = nic <NEW_LINE> <DEDENT> def netBytes(self): <NEW_LINE> <INDENT> with open('/proc/net/dev') as fh: <NEW_LINE> <INDENT> net_data = fh.read().split() <NEW_LINE> <DEDENT> interface_index = net_data.index(self.nic + ':') <NEW_LINE> received_bytes = int(net_data[interface_index + 1]) <NEW_LINE> transmitted_bytes = int(net_data[interface_index + 9]) <NEW_LINE> return received_bytes, transmitted_bytes
Get system status.
62598faecb5e8a47e493c175
class Boundaries(np.ndarray): <NEW_LINE> <INDENT> def __new__(cls, minimums, maximums, type=np.int): <NEW_LINE> <INDENT> len_minimums = len(minimums) <NEW_LINE> if len_minimums != len(maximums): <NEW_LINE> <INDENT> raise ValueError('Length of minimums and maximums are unequal') <NEW_LINE> <DEDENT> err_indexes = [] <NEW_LINE> for i in range(len_minimums): <NEW_LINE> <INDENT> if maximums[i] < minimums[i]: <NEW_LINE> <INDENT> err_indexes.append(i) <NEW_LINE> <DEDENT> <DEDENT> if err_indexes: <NEW_LINE> <INDENT> raise ValueError('Maximum bounding values are inferior to the ' 'minimum bounding value at the following indexes ' ': {}'.format(err_indexes)) <NEW_LINE> <DEDENT> epsilon = np.finfo(np.float).resolution <NEW_LINE> bounds = np.array([minimums, maximums, (maximums-minimums) + epsilon], type) <NEW_LINE> obj = np.asarray(bounds).view(cls) <NEW_LINE> return obj <NEW_LINE> <DEDENT> def max_val(self, index): <NEW_LINE> <INDENT> return self.__getitem__((1, index)) <NEW_LINE> <DEDENT> def max_vals(self): <NEW_LINE> <INDENT> return self.__getitem__(1) <NEW_LINE> <DEDENT> def min_val(self, index): <NEW_LINE> <INDENT> return self.__getitem__((0, index)) <NEW_LINE> <DEDENT> def min_vals(self): <NEW_LINE> <INDENT> return self.__getitem__(0) <NEW_LINE> <DEDENT> def normalize(self, array): <NEW_LINE> <INDENT> return array / self.__getitem__(2)
Represent the limit of the space for the attribute of a solution. A boundaries records the minimum and maximum values that a solution can take for each of its attribute. These values may be of any numeric type (int or float). Boundaries can also be used to normalize a solution vector, so that distance computation is accurate. Boundaries have always the same shape, it is a matrix of 3 lines and n columns (n being the number of attribute of the solutions). - The 1st line records the minimum values for the attributes (included). - The 2nd line records the maximum values for the attributes (included). - The 3td line records the difference between the maximum and the minimum values. This is the space size of each attribute used for the normalization of solution vectors. Of course, for a specific attribute the minimum value must always be lower or equal to the maximum value. Args: minimums (list): of minimum values. maximums (list): of maximum values. type (type): type of the values, default is np.int. Returns: np.array: of shape (3, n), n being the size of the minimums/maximums vectors.
62598fae627d3e7fe0e06ea6
class MinihubLocation(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.swagger_types = { 'minihub_type': 'str', 'channel': 'int', 'controller_slot': 'int', 'tray': 'int' } <NEW_LINE> self.attribute_map = { 'minihub_type': 'minihubType', 'channel': 'channel', 'controller_slot': 'controllerSlot', 'tray': 'tray' } <NEW_LINE> self._minihub_type = None <NEW_LINE> self._channel = None <NEW_LINE> self._controller_slot = None <NEW_LINE> self._tray = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def minihub_type(self): <NEW_LINE> <INDENT> return self._minihub_type <NEW_LINE> <DEDENT> @minihub_type.setter <NEW_LINE> def minihub_type(self, minihub_type): <NEW_LINE> <INDENT> allowed_values = ["hostside", "driveside", "__UNDEFINED"] <NEW_LINE> if minihub_type not in allowed_values: <NEW_LINE> <INDENT> raise ValueError( "Invalid value for `minihub_type`, must be one of {0}" .format(allowed_values) ) <NEW_LINE> <DEDENT> self._minihub_type = minihub_type <NEW_LINE> <DEDENT> @property <NEW_LINE> def channel(self): <NEW_LINE> <INDENT> return self._channel <NEW_LINE> <DEDENT> @channel.setter <NEW_LINE> def channel(self, channel): <NEW_LINE> <INDENT> self._channel = channel <NEW_LINE> <DEDENT> @property <NEW_LINE> def controller_slot(self): <NEW_LINE> <INDENT> return self._controller_slot <NEW_LINE> <DEDENT> @controller_slot.setter <NEW_LINE> def controller_slot(self, controller_slot): <NEW_LINE> <INDENT> self._controller_slot = controller_slot <NEW_LINE> <DEDENT> @property <NEW_LINE> def tray(self): <NEW_LINE> <INDENT> return self._tray <NEW_LINE> <DEDENT> @tray.setter <NEW_LINE> def tray(self, tray): <NEW_LINE> <INDENT> self._tray = tray <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if self is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if self is None or other is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62598faea17c0f6771d5c22e
class RigidConstraint(Constraint): <NEW_LINE> <INDENT> def __init__(self, rejectProbability): <NEW_LINE> <INDENT> super(RigidConstraint, self).__init__() <NEW_LINE> self.set_reject_probability(rejectProbability) <NEW_LINE> FRAME_DATA = [d for d in self.FRAME_DATA] <NEW_LINE> FRAME_DATA.extend(['_RigidConstraint__rejectProbability'] ) <NEW_LINE> object.__setattr__(self, 'FRAME_DATA', tuple(FRAME_DATA) ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def rejectProbability(self): <NEW_LINE> <INDENT> return self.__rejectProbability <NEW_LINE> <DEDENT> def set_reject_probability(self, rejectProbability): <NEW_LINE> <INDENT> assert is_number(rejectProbability), LOGGER.error("rejectProbability must be a number") <NEW_LINE> rejectProbability = FLOAT_TYPE(rejectProbability) <NEW_LINE> assert rejectProbability>=0 and rejectProbability<=1, LOGGER.error("rejectProbability must be between 0 and 1") <NEW_LINE> self.__rejectProbability = rejectProbability <NEW_LINE> self._dump_to_repository({'_RigidConstraint__rejectProbability': self.__rejectProbability}) <NEW_LINE> <DEDENT> def should_step_get_rejected(self, standardError): <NEW_LINE> <INDENT> if self.standardError is None: <NEW_LINE> <INDENT> raise Exception(LOGGER.error("must compute data first")) <NEW_LINE> <DEDENT> if standardError<=self.standardError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return randfloat() < self.__rejectProbability <NEW_LINE> <DEDENT> def should_step_get_accepted(self, standardError): <NEW_LINE> <INDENT> return not self.should_step_get_reject(standardError)
A rigid constraint is a constraint that doesn't count into the total standard error of the stochastic Engine. But it's internal standard error must monotonously decrease or remain the same from one engine step to another. If standard error of an rigid constraint increases the step will be rejected even before engine's new standardError get computed. :Parameters: #. rejectProbability (Number): Rejecting probability of all steps where standard error increases. It must be between 0 and 1 where 1 means rejecting all steps where standardError increases and 0 means accepting all steps regardless whether standard error increases or not.
62598fae01c39578d7f12d77
class CBORDecodeError(Exception): <NEW_LINE> <INDENT> pass
Raised when an error occurs deserializing a CBOR datastream.
62598fae56ac1b37e63021e4
class Exit(Basic): <NEW_LINE> <INDENT> pass
Basic class for exists.
62598fae3539df3088ecc2ab
class PageObject(SafeSelenium): <NEW_LINE> <INDENT> __metaclass__ = ABCMeta <NEW_LINE> def __init__(self, ui, browser): <NEW_LINE> <INDENT> super(PageObject, self).__init__(browser) <NEW_LINE> self._ui = ui <NEW_LINE> <DEDENT> @property <NEW_LINE> def ui(self): <NEW_LINE> <INDENT> return self._ui <NEW_LINE> <DEDENT> @abstractproperty <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def is_browser_on_page(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def url(self, **kwargs): <NEW_LINE> <INDENT> raise NotImplemented <NEW_LINE> <DEDENT> def warning(self, msg): <NEW_LINE> <INDENT> log = logging.getLogger(self.__class__.__name__) <NEW_LINE> log.warning(msg)
Encapsulates user interactions with a specific part of a web application. Usually, you will rely on `WebAppInterface` to instantiate the page object and won't need to call this method directly. The most important thing is this: Page objects encapsulate Selenium. If you find yourself writing CSS selectors in tests, manipulating forms, or otherwise interacting directly with the web UI, stop! Instead, put these in a `PageObject` subclass :)
62598faeadb09d7d5dc0a583
class TestPhotoEditsURL(TestBaseClass): <NEW_LINE> <INDENT> def test_authenticated_get(self): <NEW_LINE> <INDENT> url = reverse('edit-list') <NEW_LINE> self.login_user() <NEW_LINE> response = self.client.get(url) <NEW_LINE> self.assertEqual(200, response.status_code) <NEW_LINE> self.assertEqual('OK', response.status_text) <NEW_LINE> <DEDENT> def test_unauthenticated_get(self): <NEW_LINE> <INDENT> url = reverse('edit-list') <NEW_LINE> response = self.client.get(url) <NEW_LINE> self.assertEqual(403, response.status_code) <NEW_LINE> self.assertEqual('Forbidden', response.status_text) <NEW_LINE> self.assertTrue( 'credentials were not provided.' in response.data.get('detail')) <NEW_LINE> <DEDENT> def test_access_permissions(self): <NEW_LINE> <INDENT> self.login_user() <NEW_LINE> data = { 'path': self.uploadable_image(), 'filter_effects': 'BLUR' } <NEW_LINE> photo_url = reverse('photo-list') <NEW_LINE> response = self.client.post(photo_url, data=data) <NEW_LINE> response = self.client.get(photo_url) <NEW_LINE> photo_id = response.data[0].get('photo_id') <NEW_LINE> photo_url += str(photo_id) + '/' <NEW_LINE> data = { 'filter_effects': self.get_random_filter() } <NEW_LINE> json_data = json.dumps(data) <NEW_LINE> response = self.client.put( photo_url, data=json_data, content_type='application/json') <NEW_LINE> url = reverse('edit-list') <NEW_LINE> response = self.client.get(url) <NEW_LINE> edit_id = response.data[0].get('photo_edit_id') <NEW_LINE> url += str(edit_id) + '/' <NEW_LINE> response = self.client.get(url) <NEW_LINE> self.assertEqual(edit_id, response.data.get('photo_edit_id')) <NEW_LINE> self.logout_user() <NEW_LINE> login_url = reverse('rest_framework:login') <NEW_LINE> data = { 'username': self.fake.user_name(), 'password': self.fake.password() } <NEW_LINE> user2 = User.objects.create_user( username=data.get('username'), password=data.get('password') ) <NEW_LINE> self.client.post(login_url, data=data) <NEW_LINE> response = self.client.get(url) <NEW_LINE> self.assertTrue( 'You do not have permission' in response.data.get('detail')) <NEW_LINE> self.assertEqual(403, response.status_code) <NEW_LINE> self.assertEqual('Forbidden', response.status_text)
Test the '/api/edit/' Django route.
62598fae66673b3332c303c5
class LrsStyle(LrsObject, LrsAttributes, LrsContainer): <NEW_LINE> <INDENT> def __init__(self, elementName, defaults=None, alsoAllow=None, **overrides): <NEW_LINE> <INDENT> if defaults is None: <NEW_LINE> <INDENT> defaults = {} <NEW_LINE> <DEDENT> LrsObject.__init__(self) <NEW_LINE> LrsAttributes.__init__(self, defaults, alsoAllow=alsoAllow, **overrides) <NEW_LINE> LrsContainer.__init__(self, []) <NEW_LINE> self.elementName = elementName <NEW_LINE> self.objectsAppended = False <NEW_LINE> <DEDENT> def update(self, settings): <NEW_LINE> <INDENT> for name, value in settings.items(): <NEW_LINE> <INDENT> if name not in self.__class__.validSettings: <NEW_LINE> <INDENT> raise LrsError("%s not a valid setting for %s" % (name, self.__class__.__name__)) <NEW_LINE> <DEDENT> self.attrs[name] = value <NEW_LINE> <DEDENT> <DEDENT> def getLabel(self): <NEW_LINE> <INDENT> return unicode_type(self.objId) <NEW_LINE> <DEDENT> def toElement(self, se): <NEW_LINE> <INDENT> element = Element(self.elementName, stylelabel=self.getLabel(), objid=unicode_type(self.objId)) <NEW_LINE> element.attrib.update(self.attrs) <NEW_LINE> return element <NEW_LINE> <DEDENT> def toLrf(self, lrfWriter): <NEW_LINE> <INDENT> obj = LrfObject(self.elementName, self.objId) <NEW_LINE> obj.appendTagDict(self.attrs, self.__class__.__name__) <NEW_LINE> lrfWriter.append(obj) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if hasattr(other, 'attrs'): <NEW_LINE> <INDENT> return self.__class__ == other.__class__ and self.attrs == other.attrs <NEW_LINE> <DEDENT> return False
A mixin class for styles.
62598faea8370b77170f03d5
class JobRelationshipProperties(Model): <NEW_LINE> <INDENT> _validation = { 'pipeline_name': {'max_length': 260}, 'recurrence_id': {'required': True}, 'recurrence_name': {'max_length': 260}, } <NEW_LINE> _attribute_map = { 'pipeline_id': {'key': 'pipelineId', 'type': 'str'}, 'pipeline_name': {'key': 'pipelineName', 'type': 'str'}, 'pipeline_uri': {'key': 'pipelineUri', 'type': 'str'}, 'run_id': {'key': 'runId', 'type': 'str'}, 'recurrence_id': {'key': 'recurrenceId', 'type': 'str'}, 'recurrence_name': {'key': 'recurrenceName', 'type': 'str'}, } <NEW_LINE> def __init__(self, recurrence_id, pipeline_id=None, pipeline_name=None, pipeline_uri=None, run_id=None, recurrence_name=None): <NEW_LINE> <INDENT> super(JobRelationshipProperties, self).__init__() <NEW_LINE> self.pipeline_id = pipeline_id <NEW_LINE> self.pipeline_name = pipeline_name <NEW_LINE> self.pipeline_uri = pipeline_uri <NEW_LINE> self.run_id = run_id <NEW_LINE> self.recurrence_id = recurrence_id <NEW_LINE> self.recurrence_name = recurrence_name
Job relationship information properties including pipeline information, correlation information, etc. :param pipeline_id: the job relationship pipeline identifier (a GUID). :type pipeline_id: str :param pipeline_name: the friendly name of the job relationship pipeline, which does not need to be unique. :type pipeline_name: str :param pipeline_uri: the pipeline uri, unique, links to the originating service for this pipeline. :type pipeline_uri: str :param run_id: the run identifier (a GUID), unique identifier of the iteration of this pipeline. :type run_id: str :param recurrence_id: the recurrence identifier (a GUID), unique per activity/script, regardless of iterations. This is something to link different occurrences of the same job together. :type recurrence_id: str :param recurrence_name: the recurrence name, user friendly name for the correlation between jobs. :type recurrence_name: str
62598faee76e3b2f99fd8a30
class Comment(models.Model): <NEW_LINE> <INDENT> post = models.ForeignKey(Blog, on_delete=models.CASCADE) <NEW_LINE> author = models.ForeignKey(User, on_delete=models.CASCADE) <NEW_LINE> content = models.CharField(max_length=200) <NEW_LINE> date = models.DateTimeField(default=timezone.now()) <NEW_LINE> like = models.IntegerField(default=0) <NEW_LINE> id_code = models.CharField(max_length=6, default='') <NEW_LINE> def set_text(self, new_text: str): <NEW_LINE> <INDENT> self.content = new_text <NEW_LINE> <DEDENT> @property <NEW_LINE> def sub_comment(self): <NEW_LINE> <INDENT> return SubComment.objects.filter(comment_id_code=self.id_code) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.content
Comment for all blog in DEK-COM site.
62598fae5fdd1c0f98e5df85
class HSDescContentEvent(Event): <NEW_LINE> <INDENT> _VERSION_ADDED = stem.version.Requirement.EVENT_HS_DESC_CONTENT <NEW_LINE> _POSITIONAL_ARGS = ('address', 'descriptor_id', 'directory') <NEW_LINE> def _parse(self): <NEW_LINE> <INDENT> if self.address == 'UNKNOWN': <NEW_LINE> <INDENT> self.address = None <NEW_LINE> <DEDENT> self.directory_fingerprint = None <NEW_LINE> self.directory_nickname = None <NEW_LINE> try: <NEW_LINE> <INDENT> self.directory_fingerprint, self.directory_nickname = stem.control._parse_circ_entry(self.directory) <NEW_LINE> <DEDENT> except stem.ProtocolError: <NEW_LINE> <INDENT> raise stem.ProtocolError("HS_DESC_CONTENT's directory doesn't match a ServerSpec: %s" % self) <NEW_LINE> <DEDENT> desc_content = str_tools._to_bytes('\n'.join(str(self).splitlines()[1:-1])) <NEW_LINE> self.descriptor = None <NEW_LINE> if desc_content: <NEW_LINE> <INDENT> self.descriptor = list(stem.descriptor.hidden_service._parse_file(io.BytesIO(desc_content)))[0]
Provides the content of hidden service descriptors we fetch. The HS_DESC_CONTENT event was introduced in tor version 0.2.7.1-alpha. .. versionadded:: 1.4.0 :var str address: hidden service address :var str descriptor_id: descriptor identifier :var str directory: hidden service directory servicing the request :var str directory_fingerprint: hidden service directory's finterprint :var str directory_nickname: hidden service directory's nickname if it was provided :var stem.descriptor.hidden_service.HiddenServiceDescriptorV2 descriptor: descriptor that was retrieved
62598fae2ae34c7f260ab0db
class SimpleModelFactory(ModelFactory): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(SimpleModelFactory, self).__init__() <NEW_LINE> self.state_factory = State <NEW_LINE> self.route_factory = Route <NEW_LINE> <DEDENT> def create_model(self, parameter_set): <NEW_LINE> <INDENT> self.parameter_set = parameter_set <NEW_LINE> state_enumerator = self.state_enumerator_factory() <NEW_LINE> route_mapper = self.route_mapper_factory() <NEW_LINE> new_model = SimpleModel(state_enumerator, route_mapper, self.parameter_set) <NEW_LINE> return new_model <NEW_LINE> <DEDENT> def state_enumerator_factory(self): <NEW_LINE> <INDENT> def enumerate_states(): <NEW_LINE> <INDENT> sc_factory = StateCollectionFactory() <NEW_LINE> A = self.state_factory('A', 'green') <NEW_LINE> A.set_initial_state_flag() <NEW_LINE> B = self.state_factory('B', 'orange') <NEW_LINE> initial_state_id = 'A' <NEW_LINE> final_state_id = 'B' <NEW_LINE> sc_factory.add_state(A) <NEW_LINE> sc_factory.add_state(B) <NEW_LINE> state_collection = sc_factory.make_state_collection() <NEW_LINE> return state_collection, initial_state_id, final_state_id <NEW_LINE> <DEDENT> return enumerate_states <NEW_LINE> <DEDENT> def log_k1_factory(self): <NEW_LINE> <INDENT> log_k1 = self.parameter_set.get_parameter('log_k1') <NEW_LINE> def log_k1_fcn(t): <NEW_LINE> <INDENT> return log_k1 <NEW_LINE> <DEDENT> return log_k1_fcn <NEW_LINE> <DEDENT> def log_k2_factory(self): <NEW_LINE> <INDENT> log_k2 = self.parameter_set.get_parameter('log_k2') <NEW_LINE> def log_k2_fcn(t): <NEW_LINE> <INDENT> return log_k2 <NEW_LINE> <DEDENT> return log_k2_fcn <NEW_LINE> <DEDENT> def route_mapper_factory(self): <NEW_LINE> <INDENT> def map_routes(state_collection): <NEW_LINE> <INDENT> rc_factory = RouteCollectionFactory() <NEW_LINE> log_k1_fcn = self.log_k1_factory() <NEW_LINE> log_k2_fcn = self.log_k2_factory() <NEW_LINE> A_to_B = self.route_factory('A_to_B', 'A', 'B', 'A_to_B', 1) <NEW_LINE> B_to_A = self.route_factory('B_to_A', 'B', 'A', 'B_to_A', 1) <NEW_LINE> route_list = [] <NEW_LINE> rc_factory.add_route(A_to_B) <NEW_LINE> rc_factory.add_route(B_to_A) <NEW_LINE> route_collection = rc_factory.make_route_collection() <NEW_LINE> return route_collection <NEW_LINE> <DEDENT> return map_routes
This factory class creates a simple two-state aggregated kinetic model.
62598fae30bbd72246469975
class CmdDecrire(Commande): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Commande.__init__(self, "décrire", "describe") <NEW_LINE> self.groupe = "joueur" <NEW_LINE> self.aide_courte = "Ouvre un éditeur pour se décrire." <NEW_LINE> self.aide_longue = "Cette commande permet de manipuler votre description. " "Elle ouvre un éditeur dans lequel vous pouvez modifier " "cette description. La description doit d'abord être validée " "par un administrateur avant d'être visible à tous." <NEW_LINE> <DEDENT> def interpreter(self, personnage, dic_masques): <NEW_LINE> <INDENT> editeur = type(self).importeur.interpreteur.construire_editeur( "descedit", personnage, personnage) <NEW_LINE> personnage.contextes.ajouter(editeur) <NEW_LINE> editeur.actualiser()
Commande 'decrire'.
62598faef548e778e596b59d
@registry.register_audio_modality <NEW_LINE> class SpeechRecognitionModality(modality.Modality): <NEW_LINE> <INDENT> def bottom(self, x): <NEW_LINE> <INDENT> inputs = x <NEW_LINE> p = self._model_hparams <NEW_LINE> num_mel_bins = p.audio_num_mel_bins <NEW_LINE> num_channels = 3 if p.audio_add_delta_deltas else 1 <NEW_LINE> with tf.variable_scope(self.name): <NEW_LINE> <INDENT> if p.audio_preproc_in_bottom: <NEW_LINE> <INDENT> with tf.variable_scope("fbanks"): <NEW_LINE> <INDENT> waveforms = tf.squeeze(inputs, [2, 3]) <NEW_LINE> mel_fbanks = compute_mel_filterbank_features( waveforms, sample_rate=p.audio_sample_rate, dither=p.audio_dither, preemphasis=p.audio_preemphasis, frame_length=p.audio_frame_length, frame_step=p.audio_frame_step, lower_edge_hertz=p.audio_lower_edge_hertz, upper_edge_hertz=p.audio_upper_edge_hertz, num_mel_bins=p.audio_num_mel_bins, apply_mask=True) <NEW_LINE> if p.audio_add_delta_deltas: <NEW_LINE> <INDENT> mel_fbanks = add_delta_deltas(mel_fbanks) <NEW_LINE> <DEDENT> x = tf.reshape(mel_fbanks, common_layers.shape_list(mel_fbanks)[:2] + [num_mel_bins, num_channels]) <NEW_LINE> nonpadding_mask = 1. - common_attention.embedding_to_padding(x) <NEW_LINE> num_of_nonpadding_elements = tf.reduce_sum( nonpadding_mask) * num_mel_bins * num_channels <NEW_LINE> mean = tf.reduce_sum( x, axis=[1], keepdims=True) / num_of_nonpadding_elements <NEW_LINE> variance = (num_of_nonpadding_elements * mean**2. - 2. * mean * tf.reduce_sum(x, axis=[1], keepdims=True) + tf.reduce_sum(x**2, axis=[1], keepdims=True) ) / num_of_nonpadding_elements <NEW_LINE> x = (x - mean) / variance * tf.expand_dims(nonpadding_mask, -1) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> x = inputs <NEW_LINE> <DEDENT> x.set_shape([None, None, num_mel_bins, num_channels]) <NEW_LINE> x = tf.pad(x, [[0, 0], [0, 8], [0, 0], [0, 0]]) <NEW_LINE> for _ in range(2): <NEW_LINE> <INDENT> x = tf.layers.conv2d( x, 128, (3, 3), (2, 2), use_bias=False) <NEW_LINE> x = common_layers.layer_norm(x) <NEW_LINE> x = tf.nn.relu(x) <NEW_LINE> <DEDENT> xshape = common_layers.shape_list(x) <NEW_LINE> x = tf.pad(x, [[0, 0], [0, 2], [0, 0], [0, 0]]) <NEW_LINE> x = tf.layers.conv2d(x, p.hidden_size, (3, xshape[2]), use_bias=False) <NEW_LINE> assert common_layers.shape_list(x)[2] == 1 <NEW_LINE> x = common_layers.layer_norm(x) <NEW_LINE> x = tf.nn.relu(x) <NEW_LINE> <DEDENT> return x
Common ASR filterbank processing.
62598fae44b2445a339b696d
class OSCall( object, ): <NEW_LINE> <INDENT> def __init__(self, command_list, ): <NEW_LINE> <INDENT> self.command_list = [] <NEW_LINE> self.add_command( command_list ) <NEW_LINE> <DEDENT> def add_command( self, more_command_list ): <NEW_LINE> <INDENT> if more_command_list is None: <NEW_LINE> <INDENT> self.command_list = more_command_list <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if type( more_command_list ) == str: <NEW_LINE> <INDENT> more_command_list = [ more_command_list ] <NEW_LINE> <DEDENT> self.command_list = more_command_list + self.command_list <NEW_LINE> <DEDENT> self.ix_command = -1 <NEW_LINE> self.working_command = None <NEW_LINE> print( f"command list now{self.command_list}") <NEW_LINE> <DEDENT> def get_next_command( self, ): <NEW_LINE> <INDENT> self.ix_command += 1 <NEW_LINE> if self.ix_command >= len( self.command_list ): <NEW_LINE> <INDENT> ret = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ret = self.command_list[ self.ix_command ] <NEW_LINE> <DEDENT> return ret <NEW_LINE> <DEDENT> def os_call( self, cmd_arg, ): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> a_command = self.working_command <NEW_LINE> if a_command is None: <NEW_LINE> <INDENT> a_command = self.get_next_command( ) <NEW_LINE> <DEDENT> if a_command is None: <NEW_LINE> <INDENT> raise RuntimeError( msg ) <NEW_LINE> break <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if cmd_arg is None: <NEW_LINE> <INDENT> proc = Popen( [ a_command, ] ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> proc = Popen( [ a_command, cmd_arg ] ) <NEW_LINE> <DEDENT> self.working_command = a_command <NEW_LINE> break <NEW_LINE> <DEDENT> except Exception as excpt: <NEW_LINE> <INDENT> pass
try to call os based on attempts with different utilities in different operating systems idea is that a os utility will be used to open a file ( or url, or other argument )
62598fae4a966d76dd5eeed0
class Fleet(object): <NEW_LINE> <INDENT> def __init__(self, frigates=0, destroyers=0, cruisers=0, battleships=0, dreadnoughts=0, superdreadnoughts=0): <NEW_LINE> <INDENT> global ships <NEW_LINE> self.ships = [] <NEW_LINE> self.ships.append((ships['Frigate'], frigates)) <NEW_LINE> self.ships.append((ships['Destroyer'], destroyers)) <NEW_LINE> self.ships.append((ships['Cruiser'], cruisers)) <NEW_LINE> self.ships.append((ships['Battleship'], battleships)) <NEW_LINE> self.ships.append((ships['Dreadnought'], dreadnoughts)) <NEW_LINE> self.ships.append((ships['SuperDreadnought'], superdreadnoughts)) <NEW_LINE> <DEDENT> def number_of_ships(self): <NEW_LINE> <INDENT> return sum([s[1] for s in self.ships]) <NEW_LINE> <DEDENT> def fleet_destroyed(self): <NEW_LINE> <INDENT> return 0 == self.number_of_ships() <NEW_LINE> <DEDENT> def get_ship_by_index(self, i): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> for idx, (ship, n) in enumerate(self.ships): <NEW_LINE> <INDENT> count += n <NEW_LINE> if i < count and count > 0: <NEW_LINE> <INDENT> return idx <NEW_LINE> <DEDENT> <DEDENT> raise Exception("Could not find ship by index " + str(i)) <NEW_LINE> <DEDENT> def get_random_ship(self): <NEW_LINE> <INDENT> total_ships = self.number_of_ships() <NEW_LINE> which_lost = randint(0, total_ships - 1) <NEW_LINE> idx = self.get_ship_by_index(which_lost) <NEW_LINE> return idx <NEW_LINE> <DEDENT> def destroy_ship(self, idx): <NEW_LINE> <INDENT> self.ships[idx] = (self.ships[idx][0], self.ships[idx][1] - 1) <NEW_LINE> if self.ships[idx][1] < 0: <NEW_LINE> <INDENT> raise Exception("destroy_ship destroyed a non-existent ship") <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.ships)
Represents a fleet of ships
62598faecc0a2c111447b00b
class TestHaversine(TestCase): <NEW_LINE> <INDENT> def assertCloseEnough(self, distance_actual, distance_received, threshold=0.003048): <NEW_LINE> <INDENT> self.assertLessEqual( abs(distance_actual - distance_received), threshold) <NEW_LINE> <DEDENT> def evaluate_inputs(self, input_output_list): <NEW_LINE> <INDENT> for (lon1, lat1, lon2, lat2, distance_actual) in input_output_list: <NEW_LINE> <INDENT> distance_received = distance.haversine(lon1, lat1, lon2, lat2) <NEW_LINE> self.assertCloseEnough(distance_actual, distance_received) <NEW_LINE> <DEDENT> <DEDENT> def test_zero_distance(self): <NEW_LINE> <INDENT> self.evaluate_inputs([ (0, 0, 0, 0, 0), (1, 1, 1, 1, 0), (-1, -1, -1, -1, 0), (1, -1, 1, -1, 0), (-1, 1, -1, 1, 0), (76, 42, 76, 42, 0), (-76, 42, -76, 42, 0), ]) <NEW_LINE> <DEDENT> def test_hemisphere_distances(self): <NEW_LINE> <INDENT> self.evaluate_inputs([ (-73, 40, -74, 41, 139.6886345468666), (73, 40, 74, 41, 139.6886345468667), (73, -40, 74, -41, 139.6886345468667), (-73, -40, -74, -41, 139.68863454686704), ]) <NEW_LINE> <DEDENT> def test_competition_distances(self): <NEW_LINE> <INDENT> self.evaluate_inputs([ (-76.428709, 38.145306, -76.426375, 38.146146, 0.22446), (-76.428537, 38.145399, -76.427818, 38.144686, 0.10045), (-76.434261, 38.142471, -76.418876, 38.147838, 1.46914), ])
Tests the haversine code correctness.
62598faea8370b77170f03d6
class LaCrosseSensor(Entity): <NEW_LINE> <INDENT> _temperature = None <NEW_LINE> _humidity = None <NEW_LINE> _low_battery = None <NEW_LINE> _new_battery = None <NEW_LINE> def __init__(self, hass, lacrosse, device_id, name, expire_after, config): <NEW_LINE> <INDENT> self.hass = hass <NEW_LINE> self.entity_id = async_generate_entity_id( ENTITY_ID_FORMAT, device_id, hass=hass ) <NEW_LINE> self._config = config <NEW_LINE> self._name = name <NEW_LINE> self._value = None <NEW_LINE> self._expire_after = expire_after <NEW_LINE> self._expiration_trigger = None <NEW_LINE> lacrosse.register_callback( int(self._config["id"]), self._callback_lacrosse, None ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def device_state_attributes(self): <NEW_LINE> <INDENT> attributes = { "low_battery": self._low_battery, "new_battery": self._new_battery, } <NEW_LINE> return attributes <NEW_LINE> <DEDENT> def _callback_lacrosse(self, lacrosse_sensor, user_data): <NEW_LINE> <INDENT> if self._expire_after is not None and self._expire_after > 0: <NEW_LINE> <INDENT> if self._expiration_trigger: <NEW_LINE> <INDENT> self._expiration_trigger() <NEW_LINE> self._expiration_trigger = None <NEW_LINE> <DEDENT> expiration_at = dt_util.utcnow() + timedelta(seconds=self._expire_after) <NEW_LINE> self._expiration_trigger = async_track_point_in_utc_time( self.hass, self.value_is_expired, expiration_at ) <NEW_LINE> <DEDENT> self._temperature = lacrosse_sensor.temperature <NEW_LINE> self._humidity = lacrosse_sensor.humidity <NEW_LINE> self._low_battery = lacrosse_sensor.low_battery <NEW_LINE> self._new_battery = lacrosse_sensor.new_battery <NEW_LINE> <DEDENT> @callback <NEW_LINE> def value_is_expired(self, *_): <NEW_LINE> <INDENT> self._expiration_trigger = None <NEW_LINE> self._value = None <NEW_LINE> self.async_schedule_update_ha_state()
Implementation of a Lacrosse sensor.
62598faed268445f26639b80
class ShiftLogFormatterMathtext(LogFormatter): <NEW_LINE> <INDENT> def __init__(self, base, sign, zero): <NEW_LINE> <INDENT> LogFormatter.__init__ (self, base) <NEW_LINE> self.sign = sign <NEW_LINE> self.zero = zero <NEW_LINE> <DEDENT> def get_offset (self): <NEW_LINE> <INDENT> usetex = rcParams['text.usetex'] <NEW_LINE> if self.zero < 0: <NEW_LINE> <INDENT> sign_string = '-' <NEW_LINE> <DEDENT> elif self.zero > 0: <NEW_LINE> <INDENT> sign_string = '+' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> if usetex: <NEW_LINE> <INDENT> return (r'$%s%.2e$' % (sign_string, abs (self.zero))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ('$\mathdefault{%s%.2e}$' % (sign_string, abs (self.zero))) <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, x, pos=None): <NEW_LINE> <INDENT> b = self._base <NEW_LINE> usetex = rcParams['text.usetex'] <NEW_LINE> if x == self.zero: <NEW_LINE> <INDENT> if usetex: <NEW_LINE> <INDENT> return '$0$' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '$\mathdefault{0}$' <NEW_LINE> <DEDENT> <DEDENT> fx = math.log(abs(x - self.zero)) / math.log(b) <NEW_LINE> is_decade = abs (round (fx) - fx) < 1.0e10 <NEW_LINE> sign_string = '-' if x < 0 else '' <NEW_LINE> sign_string = '-' if self.sign < 0 else '' <NEW_LINE> if b % 1 == 0.0: <NEW_LINE> <INDENT> base = '%d' % b <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> base = '%s' % b <NEW_LINE> <DEDENT> if not is_decade and self.labelOnlyBase: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> elif not is_decade: <NEW_LINE> <INDENT> if usetex: <NEW_LINE> <INDENT> return (r'$%s%s^{%.2f}$') % (sign_string, base, fx) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ('$\mathdefault{%s%s^{%.2f}}$') % (sign_string, base, fx) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if usetex: <NEW_LINE> <INDENT> return (r'$%s%s^{%d}$') % (sign_string, base, nearest_long(fx)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (r'$\mathdefault{%s%s^{%d}}$') % (sign_string, base, nearest_long(fx))
Format values for log axis; using ``exponent = log_base(value)``
62598fae009cb60464d0151a
@base.vectorize <NEW_LINE> class subs(base.SubBase): <NEW_LINE> <INDENT> __slots__ = [] <NEW_LINE> code = base.opcodes['SUBS'] <NEW_LINE> arg_format = ['sw', 's', 's']
Secret subtraction s_i=s_j-s_k. This instruction is vectorizable
62598faee5267d203ee6b903
class HapBlePduResponseHeader(HapBlePduHeader): <NEW_LINE> <INDENT> def __init__(self, status_code: int, transaction_id: int, continuation: bool=False, response: bool=True) -> None: <NEW_LINE> <INDENT> super(HapBlePduResponseHeader, self).__init__( response=response, continuation=continuation) <NEW_LINE> self.transaction_id = transaction_id <NEW_LINE> self.status_code = status_code <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_data(cls, data: bytes) -> 'HapBlePduResponseHeader': <NEW_LINE> <INDENT> control_field, tid, status_code = unpack('<BBB', data[:3]) <NEW_LINE> control_field = bin(control_field)[2:].zfill(8)[::-1] <NEW_LINE> continuation = control_field[7] == '1' <NEW_LINE> response = control_field[1] == '1' <NEW_LINE> if control_field[0] + control_field[2:7] != '000000': <NEW_LINE> <INDENT> raise ValueError("Invalid control field for response header {}". format(control_field)) <NEW_LINE> <DEDENT> return HapBlePduResponseHeader( continuation=continuation, response=response, transaction_id=tid, status_code=status_code) <NEW_LINE> <DEDENT> @property <NEW_LINE> def data(self) -> bytes: <NEW_LINE> <INDENT> return pack('<BBB', self.control_field, self.transaction_id, self.status_code) <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return super( HapBlePduResponseHeader, self).__str__() + " status_code: {}, transaction_id: {}".format( constants.HapBleStatusCodes()(self.status_code), self.transaction_id)
HAP-BLE PDU Response Header. Parameters ---------- continuation indicates the fragmentation status of the HAP-BLE PDU. False indicates a first fragment or no fragmentation. response indicates whether the PDU is a response (versus a request) transaction_id Transaction Identifier status_code HAP Status code for the request.
62598faeac7a0e7691f72503
class FeaturedSpeakersForm(messages.Message): <NEW_LINE> <INDENT> speaker = messages.StringField(1, required=True) <NEW_LINE> sessionNames = messages.StringField(2, repeated=True)
FeaturedSpeakersForm::= speaker sessions
62598fae6e29344779b00656
class Computer(abstract.ResourceDefinition): <NEW_LINE> <INDENT> name = "Computer" <NEW_LINE> @classmethod <NEW_LINE> def loadAllVersions(cls, registry): <NEW_LINE> <INDENT> registry.add_version(cls, ComputerVersion0, ComputerVersion0.versions) <NEW_LINE> registry.add_version(cls, ComputerVersion1, ComputerVersion1.versions)
The ComputerResource.
62598fae4f6381625f1994bc
class DouyinProxyValidator(BaseProxyValidator): <NEW_LINE> <INDENT> items = [] <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super().__init__(timeout=5) <NEW_LINE> self.pipeline = DouyinPostgreSQLPipeline() <NEW_LINE> self.pipeline.open_spider(None) <NEW_LINE> <DEDENT> def validate(self, proxy): <NEW_LINE> <INDENT> ip, port, http_type = proxy['ip'], proxy['port'], proxy['http_type'] <NEW_LINE> proxy_url = f'{http_type}://{ip}:{port}' <NEW_LINE> http_type = http_type.lower() <NEW_LINE> anonymous = douyin_spider.ANONYMOUS <NEW_LINE> url = douyin.generate_feed_url(http_type=http_type, anonymous=anonymous) <NEW_LINE> proxies = { http_type: proxy_url } <NEW_LINE> result = False <NEW_LINE> response = None <NEW_LINE> try: <NEW_LINE> <INDENT> headers = douyin.generate_headers(anonymous) <NEW_LINE> cookies = douyin.generate_cookies(anonymous) <NEW_LINE> response = requests.get(url, headers=headers, cookies=cookies, proxies=proxies, timeout=self.timeout, verify=False) <NEW_LINE> if response.status_code == 200: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = self.validate_response(proxy, response.json()) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> except (ConnectTimeout, ConnectionError, ReadTimeout) as e: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> if response: <NEW_LINE> <INDENT> response.close() <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def validate_response(self, proxy, result) -> bool: <NEW_LINE> <INDENT> status_code = result['status_code'] <NEW_LINE> if status_code == 0: <NEW_LINE> <INDENT> aweme_list = result['aweme_list'] <NEW_LINE> proxy['available'] = 1 <NEW_LINE> log.info(f'{proxy}-代理有效,爬到 {len(aweme_list)} items') <NEW_LINE> for aweme in aweme_list: <NEW_LINE> <INDENT> item = DouyinItem(aweme) <NEW_LINE> self.items.append(item) <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> elif status_code == 2154: <NEW_LINE> <INDENT> proxy['available'] = 2 <NEW_LINE> proxy['banned_time'] = time.time() <NEW_LINE> log.info(f"{proxy}-代理有效,但已被禁{result['status_code']}") <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(f"{proxy}-代理无效,返回状态码{result['status_code']}") <NEW_LINE> return False <NEW_LINE> <DEDENT> <DEDENT> def save_items(self): <NEW_LINE> <INDENT> log.info(f'共爬取到 {len(self.items)} items,保存中') <NEW_LINE> for item in self.items: <NEW_LINE> <INDENT> self.pipeline.process_item(item, None) <NEW_LINE> <DEDENT> self.items.clear() <NEW_LINE> self.pipeline.close_spider(None)
抖音代理校验
62598fae5fc7496912d4827e
class LjbUpdater(Updater): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Updater.__init__(self) <NEW_LINE> self.folder_url = cbv_const.LJB_FOLDER_URL <NEW_LINE> self.files_pattern = cbv_const.LJB_FILES_PATTERN <NEW_LINE> self.version_pattern = cbv_const.LJB_VERSION_PATTERN <NEW_LINE> self.local_ref_db_dir = cbv_const.USER_LJB_REF_DB_DIR <NEW_LINE> <DEDENT> def download_new_file(self): <NEW_LINE> <INDENT> if not Updater.download_new_file(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.new_file.endswith('.zip'): <NEW_LINE> <INDENT> self.raw_db_files = unzip(self.downloaded_file, self.local_ref_db_dir) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.raw_db_files = self.downloaded_file <NEW_LINE> <DEDENT> return self.raw_db_files
to check if local LJB DB is up-to-date
62598fae66673b3332c303c7
class JSONEncodedDict(TypeDecorator): <NEW_LINE> <INDENT> impl = VARCHAR <NEW_LINE> def process_bind_param(self, value, dialect): <NEW_LINE> <INDENT> if value is not None: <NEW_LINE> <INDENT> value = json.dumps(value) <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def process_result_value(self, value, dialect): <NEW_LINE> <INDENT> if value is not None: <NEW_LINE> <INDENT> value = json.loads(value) <NEW_LINE> <DEDENT> return value
Represents an immutable structure as a json-encoded string. Usage:: JSONEncodedDict(255)
62598fae4e4d562566372421
class TestDegenerateEntries(ScreenshotTest): <NEW_LINE> <INDENT> def sgvs(self): <NEW_LINE> <INDENT> s = default_entries('DoubleDown') <NEW_LINE> for i in range(6, 12): <NEW_LINE> <INDENT> del s[i]['sgv'] <NEW_LINE> <DEDENT> s[0]['trend'] = s[0]['direction'] = None <NEW_LINE> return s
Test that "bad" SGV entries don't cause the watchface to crash.
62598fae99cbb53fe6830ed3
class GoodsSKUIndex(indexes.SearchIndex, indexes.Indexable): <NEW_LINE> <INDENT> text = indexes.CharField(document=True, use_template=True) <NEW_LINE> def get_model(self): <NEW_LINE> <INDENT> return GoodsSKU <NEW_LINE> <DEDENT> def index_queryset(self, using=None): <NEW_LINE> <INDENT> return self.get_model().objects.filter(isDelete=False)
建立索引时被使用的类
62598fae7cff6e4e811b5a28
class ThrowerAnt(Ant): <NEW_LINE> <INDENT> name = 'Thrower' <NEW_LINE> implemented = True <NEW_LINE> damage = 1 <NEW_LINE> food_cost = 3 <NEW_LINE> min_range = 0 <NEW_LINE> max_range = float('inf') <NEW_LINE> def nearest_bee(self, beehive): <NEW_LINE> <INDENT> location = self.place <NEW_LINE> attcak = 0 <NEW_LINE> while location != beehive: <NEW_LINE> <INDENT> if location.bees and attcak >= self.min_range and attcak <= self.max_range: <NEW_LINE> <INDENT> return random_or_none(location.bees) <NEW_LINE> <DEDENT> location = location.entrance <NEW_LINE> attcak += 1 <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def throw_at(self, target): <NEW_LINE> <INDENT> if target is not None: <NEW_LINE> <INDENT> target.reduce_armor(self.damage) <NEW_LINE> <DEDENT> <DEDENT> def action(self, gamestate): <NEW_LINE> <INDENT> self.throw_at(self.nearest_bee(gamestate.beehive))
ThrowerAnt throws a leaf each turn at the nearest Bee in its range.
62598fae8e7ae83300ee909d
class DeviceUtils: <NEW_LINE> <INDENT> FREQ = 62 <NEW_LINE> local_buffer = asyncio.Queue() <NEW_LINE> def get_device_data(self): <NEW_LINE> <INDENT> return next(DataGen.get_message()) <NEW_LINE> <DEDENT> async def push_data_to_buffer(self): <NEW_LINE> <INDENT> freq = self.FREQ <NEW_LINE> while True: <NEW_LINE> <INDENT> await self.local_buffer.put(self.get_device_data()) <NEW_LINE> await asyncio.sleep(1 / freq) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def reformat_message(message): <NEW_LINE> <INDENT> return json.dumps(message)
Collection of utils to access messages from device
62598fae9c8ee8231304016f
class App(base.BaseApp): <NEW_LINE> <INDENT> def set_current(self): <NEW_LINE> <INDENT> _tls.current_app = self <NEW_LINE> <DEDENT> def on_init(self): <NEW_LINE> <INDENT> if self.set_as_current: <NEW_LINE> <INDENT> self.set_current() <NEW_LINE> <DEDENT> <DEDENT> def create_task_cls(self): <NEW_LINE> <INDENT> from celery.task.base import create_task_cls <NEW_LINE> return create_task_cls(app=self) <NEW_LINE> <DEDENT> def Worker(self, **kwargs): <NEW_LINE> <INDENT> from celery.apps.worker import Worker <NEW_LINE> return Worker(app=self, **kwargs) <NEW_LINE> <DEDENT> def Beat(self, **kwargs): <NEW_LINE> <INDENT> from celery.apps.beat import Beat <NEW_LINE> return Beat(app=self, **kwargs) <NEW_LINE> <DEDENT> def TaskSet(self, *args, **kwargs): <NEW_LINE> <INDENT> from celery.task.sets import TaskSet <NEW_LINE> kwargs["app"] = self <NEW_LINE> return TaskSet(*args, **kwargs) <NEW_LINE> <DEDENT> def worker_main(self, argv=None): <NEW_LINE> <INDENT> from celery.bin.celeryd import WorkerCommand <NEW_LINE> return WorkerCommand(app=self).execute_from_commandline(argv) <NEW_LINE> <DEDENT> def task(self, *args, **options): <NEW_LINE> <INDENT> def inner_create_task_cls(**options): <NEW_LINE> <INDENT> def _create_task_cls(fun): <NEW_LINE> <INDENT> base = options.pop("base", None) or self.create_task_cls() <NEW_LINE> @wraps(fun, assigned=("__module__", "__name__")) <NEW_LINE> def run(self, *args, **kwargs): <NEW_LINE> <INDENT> return fun(*args, **kwargs) <NEW_LINE> <DEDENT> run.argspec = getargspec(fun) <NEW_LINE> cls_dict = dict(options, run=run, __module__=fun.__module__, __doc__=fun.__doc__) <NEW_LINE> T = type(fun.__name__, (base, ), cls_dict)() <NEW_LINE> return registry.tasks[T.name] <NEW_LINE> <DEDENT> return _create_task_cls <NEW_LINE> <DEDENT> if len(args) == 1 and callable(args[0]): <NEW_LINE> <INDENT> return inner_create_task_cls()(*args) <NEW_LINE> <DEDENT> return inner_create_task_cls(**options) <NEW_LINE> <DEDENT> def __reduce__(self): <NEW_LINE> <INDENT> return (_unpickle_app, (self.__class__, self.main, self.conf.changes, self.loader_cls, self.backend_cls))
Celery Application. :keyword loader: The loader class, or the name of the loader class to use. Default is :class:`celery.loaders.app.AppLoader`. :keyword backend: The result store backend class, or the name of the backend class to use. Default is the value of the :setting:`CELERY_RESULT_BACKEND` setting.
62598fae4428ac0f6e658520
class UserTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> APP = create_app(config_name="testing") <NEW_LINE> APP.testing = True <NEW_LINE> self.app = APP.test_client() <NEW_LINE> create_tables() <NEW_LINE> super_user() <NEW_LINE> self.test_user = test_user <NEW_LINE> payload = { "user_name": self.test_user['user_name'], "exp": datetime.datetime.utcnow() + datetime.timedelta(minutes=60) } <NEW_LINE> token = jwt.encode( payload=payload, key=secret, algorithm='HS256') <NEW_LINE> self.headers = {'Content-Type': 'application/json', 'token': token } <NEW_LINE> self.data = user <NEW_LINE> self.data5 = data5 <NEW_LINE> self.data6 = data6 <NEW_LINE> <DEDENT> def test_user_signup(self): <NEW_LINE> <INDENT> response = self.app.post( "/api/v2/auth/signup", headers={'Content-Type': 'application/json'}, data=json.dumps(self.data)) <NEW_LINE> print(response) <NEW_LINE> json.loads(response.data) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> <DEDENT> def test_user_signin(self): <NEW_LINE> <INDENT> self.app.post("/api/v2/auth/signup", headers={'Content-Type': 'application/json'}, data=json.dumps(self.data)) <NEW_LINE> response = self.app.post( "/api/v2/auth/signin", headers={'Content-Type': 'application/json'}, data=json.dumps(self.data5)) <NEW_LINE> json.loads(response.data) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> <DEDENT> def test_user_signin_wrong_password(self): <NEW_LINE> <INDENT> self.app.post("/api/v2/auth/signup", headers={'Content-Type': 'application/json'}, data=json.dumps(self.data)) <NEW_LINE> response = self.app.post("/api/v2/auth/signin", headers=self.headers, data=json.dumps(self.data6)) <NEW_LINE> result = json.loads(response.data) <NEW_LINE> print(result) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertEqual(result['message'], 'password or email is incorrect please check your details') <NEW_LINE> <DEDENT> def test_duplicate_user_name(self): <NEW_LINE> <INDENT> self.app.post("/api/v2/auth/signup", headers={'Content-Type': 'application/json'}, data=json.dumps(self.data)) <NEW_LINE> response = self.app.post( "/api/v2/auth/signup", headers={'Content-Type': 'application/json'}, data=json.dumps(self.data)) <NEW_LINE> result = json.loads(response.data) <NEW_LINE> self.assertEqual(result['status'], 400) <NEW_LINE> self.assertEqual(result['error'], "username already taken please try another one") <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> destroy_tables()
Class for Users testcase
62598fae30bbd72246469976
class UserProfileSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> user = UserSerializer() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = UserProfile <NEW_LINE> fields = '__all__' <NEW_LINE> read_only_fields = ('suspended_until', 'last_suspension') <NEW_LINE> <DEDENT> def validate_user(self, value): <NEW_LINE> <INDENT> instance = UserSerializer(data=value, partial=True) <NEW_LINE> if not instance.is_valid(): <NEW_LINE> <INDENT> raise serializers.ValidationError(instance.errors) <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def validate_dob(self, value): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> def create(self, validated_data): <NEW_LINE> <INDENT> user_data = validated_data.pop('user') <NEW_LINE> user = DjangoUser.objects.create_user(**user_data) <NEW_LINE> return UserProfile.objects.create(user=user, **validated_data) <NEW_LINE> <DEDENT> def update(self, instance, validated_data): <NEW_LINE> <INDENT> user_data = validated_data.pop('user') <NEW_LINE> UserProfile.objects.filter(pk=instance.id).update(**validated_data) <NEW_LINE> DjangoUser.objects.filter(pk=instance.user.id).update(**user_data) <NEW_LINE> return instance
Serializer class used to validate a custom User object that has a `OneToOne` relatioship with the default Django user. Creates and updates a `UserProfile` and Django `User` object
62598fae5fcc89381b26614a
class EpochSaver(CallbackAny2Vec): <NEW_LINE> <INDENT> def __init__(self, path_prefix): <NEW_LINE> <INDENT> self.path_prefix = path_prefix <NEW_LINE> self.epoch = 0 <NEW_LINE> os.makedirs(self.path_prefix, exist_ok=True) <NEW_LINE> <DEDENT> def on_epoch_end(self, model): <NEW_LINE> <INDENT> savepath = get_tmpfile( '{}_epoch{}.model'.format(self.path_prefix, self.epoch) ) <NEW_LINE> model.save(savepath) <NEW_LINE> print( "Epoch saved: {}".format(self.epoch + 1), "Starting next epoch" ) <NEW_LINE> self.epoch += 1
Callback to save model after each epoch.
62598fae16aa5153ce4004fe
class Rectangle: <NEW_LINE> <INDENT> def __init__(self, width=0, height=0): <NEW_LINE> <INDENT> self.height = height <NEW_LINE> self.width = width <NEW_LINE> <DEDENT> @property <NEW_LINE> def width(self): <NEW_LINE> <INDENT> return self.__width <NEW_LINE> <DEDENT> @width.setter <NEW_LINE> def width(self, value): <NEW_LINE> <INDENT> if type(value) is not int: <NEW_LINE> <INDENT> raise TypeError("width must be an integer") <NEW_LINE> <DEDENT> if value < 0: <NEW_LINE> <INDENT> raise ValueError("width must be >= 0") <NEW_LINE> <DEDENT> self.__width = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def height(self): <NEW_LINE> <INDENT> return self.__height <NEW_LINE> <DEDENT> @height.setter <NEW_LINE> def height(self, value): <NEW_LINE> <INDENT> if type(value) is not int: <NEW_LINE> <INDENT> raise TypeError("height must be an integer") <NEW_LINE> <DEDENT> if value < 0: <NEW_LINE> <INDENT> raise ValueError("height must be >= 0") <NEW_LINE> <DEDENT> self.__height = value <NEW_LINE> <DEDENT> def area(self): <NEW_LINE> <INDENT> return self.__width * self.__height <NEW_LINE> <DEDENT> def perimeter(self): <NEW_LINE> <INDENT> if self.__width is 0 or self.__height is 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return (self.__width + self.__height) * 2 <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> rec = '' <NEW_LINE> if self.__height > 0 and self.__width > 0: <NEW_LINE> <INDENT> for i in range(self.__height): <NEW_LINE> <INDENT> rec = rec + ('#' * self.__width) + '\n' <NEW_LINE> <DEDENT> <DEDENT> return rec[:-1] <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> sw, sh = str(self.__width), str(self.__height) <NEW_LINE> return "Rectangle(" + sw + ", " + sh + ")" <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> print("Bye rectangle...") <NEW_LINE> del self
Represents a Rectangle
62598faea05bb46b3848a867
class StatsContainer(command.ShowOne): <NEW_LINE> <INDENT> log = logging.getLogger(__name__ + ".StatsContainer") <NEW_LINE> def get_parser(self, prog_name): <NEW_LINE> <INDENT> parser = super(StatsContainer, self).get_parser(prog_name) <NEW_LINE> parser.add_argument( 'container', metavar='<container>', help='ID or name of the (container)s to display stats.') <NEW_LINE> return parser <NEW_LINE> <DEDENT> def take_action(self, parsed_args): <NEW_LINE> <INDENT> client = _get_client(self, parsed_args) <NEW_LINE> container = parsed_args.container <NEW_LINE> stats_info = client.containers.stats(container) <NEW_LINE> return stats_info.keys(), stats_info.values()
Display stats of the container.
62598faedd821e528d6d8f31
class PickleSerialiser(Serialiser): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def serialise(data): <NEW_LINE> <INDENT> serialised = pickle.dumps(data) <NEW_LINE> return serialised <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def deserialise(serialised, dataContainer): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data = pickle.loads(serialised) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise Serialiser.DeserialiseError( "Failed to restore python object. Could not deserialise target data") <NEW_LINE> <DEDENT> return data
PickleSerialiser, Pickle implementation of Serialiser
62598fae44b2445a339b696e
class Node(object): <NEW_LINE> <INDENT> def __iter__(self): <NEW_LINE> <INDENT> for n in self.getChildNodes(): <NEW_LINE> <INDENT> yield n <NEW_LINE> <DEDENT> <DEDENT> def getChildren(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def getChildNodes(self): <NEW_LINE> <INDENT> return () <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> pass
Abstract base class for ast nodes.
62598fae38b623060ffa9096
class Engine(object): <NEW_LINE> <INDENT> def __init__(self, left, right): <NEW_LINE> <INDENT> leftState = StateDriver([]) <NEW_LINE> rightState = StateDriver([]) <NEW_LINE> self.left = StateController(left, leftState, rightState) <NEW_LINE> self.right = StateController(right, rightState, leftState) <NEW_LINE> <DEDENT> def debug(self, title): <NEW_LINE> <INDENT> print('\n') <NEW_LINE> print(title) <NEW_LINE> print("left: %s"% self.left.driver.messages) <NEW_LINE> print("state left: %s"% self.left.state.messages) <NEW_LINE> print("rght: %s"% self.right.driver.messages) <NEW_LINE> print("state rght: %s"% self.right.state.messages) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> leftMessages = self.left.getChanges() <NEW_LINE> rightMessages = self.right.getChanges() <NEW_LINE> print("## Changes:") <NEW_LINE> print("- from left: %s"% leftMessages) <NEW_LINE> print("- from rght: %s"% rightMessages) <NEW_LINE> self.left.update(rightMessages) <NEW_LINE> self.right.update(leftMessages) <NEW_LINE> print("\n## Update done.")
The engine.
62598fae4f6381625f1994bd
class PluginMetaFilter(FilterSet): <NEW_LINE> <INDENT> min_creation_date = django_filters.IsoDateTimeFilter(field_name='creation_date', lookup_expr='gte') <NEW_LINE> max_creation_date = django_filters.IsoDateTimeFilter(field_name='creation_date', lookup_expr='lte') <NEW_LINE> name = django_filters.CharFilter(field_name='name', lookup_expr='icontains') <NEW_LINE> name_exact = django_filters.CharFilter(field_name='name', lookup_expr='exact') <NEW_LINE> title = django_filters.CharFilter(field_name='title', lookup_expr='icontains') <NEW_LINE> category = django_filters.CharFilter(field_name='category', lookup_expr='icontains') <NEW_LINE> type = django_filters.CharFilter(field_name='type', lookup_expr='exact') <NEW_LINE> authors = django_filters.CharFilter(field_name='authors', lookup_expr='icontains') <NEW_LINE> name_title_category = django_filters.CharFilter(method='search_name_title_category') <NEW_LINE> name_authors_category = django_filters.CharFilter( method='search_name_authors_category') <NEW_LINE> def search_name_title_category(self, queryset, name, value): <NEW_LINE> <INDENT> lookup = models.Q(name__icontains=value) <NEW_LINE> lookup = lookup | models.Q(title__icontains=value) <NEW_LINE> lookup = lookup | models.Q(category__icontains=value) <NEW_LINE> return queryset.filter(lookup) <NEW_LINE> <DEDENT> def search_name_authors_category(self, queryset, name, value): <NEW_LINE> <INDENT> lookup = models.Q(name__icontains=value) <NEW_LINE> lookup = lookup | models.Q(authors__icontains=value) <NEW_LINE> lookup = lookup | models.Q(category__icontains=value) <NEW_LINE> return queryset.filter(lookup) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> model = PluginMeta <NEW_LINE> fields = ['id', 'name', 'name_exact', 'title', 'category', 'type', 'authors', 'min_creation_date', 'max_creation_date', 'name_title_category', 'name_authors_category']
Filter class for the PluginMeta model.
62598fae0c0af96317c5637f
class BaseAuth(RequestsAuth): <NEW_LINE> <INDENT> site = None <NEW_LINE> def __init__(self, username, password=None, login_url=None): <NEW_LINE> <INDENT> self.username = username <NEW_LINE> self.password = password <NEW_LINE> self.login_url = login_url <NEW_LINE> self.cookie = None <NEW_LINE> self.digest = None <NEW_LINE> <DEDENT> def __call__(self, request): <NEW_LINE> <INDENT> if self.cookie and self.digest: <NEW_LINE> <INDENT> request.headers.update({'Cookie': self.cookie, 'X-RequestDigest': self.digest}) <NEW_LINE> <DEDENT> return request <NEW_LINE> <DEDENT> def login(self, site): <NEW_LINE> <INDENT> raise NotImplementedError('Auth classes must implement login') <NEW_LINE> <DEDENT> def refresh(self): <NEW_LINE> <INDENT> raise NotImplementedError('Auth classes must implement refresh') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def supports(realm): <NEW_LINE> <INDENT> raise NotImplementedError('Auth classes must implement supports') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_login(realm): <NEW_LINE> <INDENT> raise NotImplementedError('Auth classes must implement get_login')
A base interface that all SharePy auth classes should inherit from
62598fae63d6d428bbee27a8
class TemplateLookup(pyramid_mako.PkgResourceTemplateLookup): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> if not 'cache_args' in kwargs: <NEW_LINE> <INDENT> cache_args = {} <NEW_LINE> prefix = 'mako.cache_args.' <NEW_LINE> for key in settings.keys(): <NEW_LINE> <INDENT> if key.startswith(prefix): <NEW_LINE> <INDENT> name = key.split(prefix)[1].strip() <NEW_LINE> value = settings[key] <NEW_LINE> try: <NEW_LINE> <INDENT> value = value.strip() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> cache_args[name] = value <NEW_LINE> <DEDENT> <DEDENT> coerce_cache_params(cache_args) <NEW_LINE> cache_args['timeout'] = cache_args.get('expire') <NEW_LINE> type_arg = cache_args.get('type') <NEW_LINE> if type_arg and type_arg.startswith('dogpile.cache'): <NEW_LINE> <INDENT> cache_args = coerge_dogpile_args(cache_args) <NEW_LINE> register_plugin("dogpile.cache", "pyramid_weblayer.patch", "UnicodeKeyCapableMakoPlugin") <NEW_LINE> kwargs['cache_impl'] = 'dogpile.cache' <NEW_LINE> <DEDENT> kwargs['cache_args'] = cache_args <NEW_LINE> <DEDENT> super(TemplateLookup, self).__init__(*args, **kwargs)
Sets ``cache_args`` if not passed into the lookup constructor.
62598fae76e4537e8c3ef5aa
class myLog: <NEW_LINE> <INDENT> log = None <NEW_LINE> mutex = threading.Lock() <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def getLog(): <NEW_LINE> <INDENT> if myLog.log == None: <NEW_LINE> <INDENT> myLog.mutex.acquire() <NEW_LINE> myLog.log = Log() <NEW_LINE> myLog.mutex.release() <NEW_LINE> <DEDENT> return myLog.log
This class is used to get log
62598fae44b2445a339b696f
class UserStorage(object): <NEW_LINE> <INDENT> def get_users(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def add_user(self, name, token, roles=''): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def remove_user(self, name, token): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def update_user(self, name, key, value): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def add_role(self, name, token, role=''): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def remove_role(self, name, token, role=''): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def has_role(self, name, token, role=''): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def has_access(self, user, jobname): <NEW_LINE> <INDENT> pass
Manage user information storage.
62598fae56b00c62f0fb28b3
class GOLEvolutionModel: <NEW_LINE> <INDENT> def evolve(self, cellState, neighbourCount): <NEW_LINE> <INDENT> if cellState == CellularGrid.ALIVE and neighbourCount < 2: <NEW_LINE> <INDENT> return CellularGrid.DEAD <NEW_LINE> <DEDENT> elif cellState == CellularGrid.ALIVE and (neighbourCount == 2 or neighbourCount == 3): <NEW_LINE> <INDENT> return CellularGrid.ALIVE <NEW_LINE> <DEDENT> elif cellState == CellularGrid.ALIVE and neighbourCount > 3: <NEW_LINE> <INDENT> return CellularGrid.DEAD <NEW_LINE> <DEDENT> elif cellState == CellularGrid.DEAD and neighbourCount == 3: <NEW_LINE> <INDENT> return CellularGrid.ALIVE <NEW_LINE> <DEDENT> return cellState
Describes the evolution rules of the cellular grid.
62598fae1f5feb6acb162c1c
class BytesWarning(Warning): <NEW_LINE> <INDENT> pass
BytesWarning.
62598faed268445f26639b82
class AddUnlockAction(UpgradeStep): <NEW_LINE> <INDENT> def __call__(self): <NEW_LINE> <INDENT> self.install_upgrade_profile()
Add unlock action.
62598fae30dc7b766599f84a
class NeutronClient(OpenStackBaseClient): <NEW_LINE> <INDENT> VERSION = '2.3.4' <NEW_LINE> Exceptions = neutron_exceptions <NEW_LINE> class Router(OpenStackResourceList): <NEW_LINE> <INDENT> def create(self, body): <NEW_LINE> <INDENT> return super(NeutronClient.Router, self).create(body['name'], body) <NEW_LINE> <DEDENT> <DEDENT> class Network(OpenStackResourceList): <NEW_LINE> <INDENT> def create(self, name, tenant_id): <NEW_LINE> <INDENT> networks = self.client._get_resources('Network') <NEW_LINE> network = networks.list()[0] <NEW_LINE> networks._update(network, name=name, tenant_id=tenant_id) <NEW_LINE> return network <NEW_LINE> <DEDENT> <DEDENT> class Subnet(OpenStackResourceList): <NEW_LINE> <INDENT> def create(self, **kwargs): <NEW_LINE> <INDENT> kwargs.update({ 'gateway_ip': '0.0.0.0', 'host_routes': [], }) <NEW_LINE> return super(NeutronClient.Subnet, self).create(kwargs['name'], kwargs) <NEW_LINE> <DEDENT> <DEDENT> def __init__(self, auth_url, username, password, tenant_id=None, **kwargs): <NEW_LINE> <INDENT> self.client = KeystoneClient( session=KeystoneClient.Session(auth=v2.Password(auth_url, username, password))) <NEW_LINE> <DEDENT> def show_network(self, network_id): <NEW_LINE> <INDENT> networks = self._get_resources('Network') <NEW_LINE> return {'network': networks.get(network_id).to_dict()} <NEW_LINE> <DEDENT> def create_network(self, body=None): <NEW_LINE> <INDENT> networks = self._get_resources('Network') <NEW_LINE> response = [] <NEW_LINE> for args in body.get('networks'): <NEW_LINE> <INDENT> response.append(networks.create(args['name'], args['tenant_id']).to_dict()) <NEW_LINE> <DEDENT> return {'networks': response} <NEW_LINE> <DEDENT> def create_subnet(self, body=None): <NEW_LINE> <INDENT> networks = self._get_resources('Network') <NEW_LINE> subnets = self._get_resources('Subnet') <NEW_LINE> response = [] <NEW_LINE> for args in body.get('subnets'): <NEW_LINE> <INDENT> subnet = subnets.create(**args) <NEW_LINE> network = networks.get(args['network_id']) <NEW_LINE> network.subnets.append(subnet.id) <NEW_LINE> response.append(subnet.to_dict()) <NEW_LINE> <DEDENT> return {'subnets': response} <NEW_LINE> <DEDENT> def list_routers(self): <NEW_LINE> <INDENT> routers = self._get_resources('Router') <NEW_LINE> return {'routers': [r.to_dict() for r in routers.list()]} <NEW_LINE> <DEDENT> def create_router(self, body=None): <NEW_LINE> <INDENT> routers = self._get_resources('Router') <NEW_LINE> return {'router': routers.create(body['router']).to_dict()} <NEW_LINE> <DEDENT> def add_interface_router(self, router, body=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def list_floatingips(self, retrieve_all=True, **kwargs): <NEW_LINE> <INDENT> return {'floatingips': []}
Dummy OpenStack networking service
62598faedd821e528d6d8f33
class Sector(models.Model): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> app_label = 'admin' <NEW_LINE> index_together = [["name"]] <NEW_LINE> <DEDENT> name = models.CharField( max_length=9, default=None, unique=True, db_index=True, ) <NEW_LINE> create_date = models.DateTimeField(auto_now_add=True) <NEW_LINE> write_date = models.DateTimeField(auto_now=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> @property <NEW_LINE> def sub_sectors(self): <NEW_LINE> <INDENT> return SubSector.objetcs.filter(sector=self)
Sector/Industry model
62598faebd1bec0571e150c2
class LoanBooksByUserListView(LoginRequiredMixin,generic.ListView): <NEW_LINE> <INDENT> model = BookInstance <NEW_LINE> template_name = 'catalog/bookinstance_list_borrowed_user.html' <NEW_LINE> paginate_by = 10 <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> return BookInstance.objects.filter(borrower=self.request.user).filter(status__exact='o').order_by('due_back')
Generic class-based view listing books on loan to current user.
62598faee1aae11d1e7ce822
class Menu(Item): <NEW_LINE> <INDENT> @types(title=Unicode, items=ListOf(Item), meta=Meta) <NEW_LINE> def __init__(self, title, items, meta=Meta()): <NEW_LINE> <INDENT> Item.__init__(self, ('title', title), ('items', items), ('meta', meta)) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> @types(Item, data=dict, meta=Meta) <NEW_LINE> def parse(data, meta, loader, encoding='utf-8', depth=0): <NEW_LINE> <INDENT> from easy_menu.entity import KEYWORD_META, Item <NEW_LINE> if KEYWORD_META in data: <NEW_LINE> <INDENT> meta = meta.updated(data[KEYWORD_META], encoding) <NEW_LINE> del data[KEYWORD_META] <NEW_LINE> <DEDENT> assert len(data) == 1, 'Menu should have only one item, not %s.' % len(data) <NEW_LINE> title, content = get_single_item(data) <NEW_LINE> assert isinstance(title, six.string_types), 'Menu title must be string, not %s.' % type(title).__name__ <NEW_LINE> assert isinstance(content, list), 'Menu content must be list, not %s.' % type(content).__name__ <NEW_LINE> title = to_unicode(title, encoding) <NEW_LINE> items = [Item.parse(item, meta, loader, encoding, depth + 1) for item in content] <NEW_LINE> return Menu(title, items, meta) <NEW_LINE> <DEDENT> @types(Unicode) <NEW_LINE> def formatted(self): <NEW_LINE> <INDENT> return '\n'.join( ['# %s:' % self.title] + [' %s' % line for x in self.items for line in x.formatted().splitlines()])
Menu is built from an one-element dict having title string as key and item list element as value
62598faea05bb46b3848a869
class Admin: <NEW_LINE> <INDENT> def __init__(self, bot): <NEW_LINE> <INDENT> self.bot = bot <NEW_LINE> self.voice_states = {} <NEW_LINE> <DEDENT> @commands.command(hidden=True) <NEW_LINE> async def quitbot(self, Password : str): <NEW_LINE> <INDENT> Configured = False <NEW_LINE> try: <NEW_LINE> <INDENT> File = open("PasswordAdmin.pwd","r") <NEW_LINE> Configured = True <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> await self.bot.say("Mot de passe non configuré. Je vais devoir utiliser le mot de passe par defaut, bravo l'adiministrateur...") <NEW_LINE> <DEDENT> if Configured: <NEW_LINE> <INDENT> PasswordAdmin = File.read() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> PasswordAdmin = "1234" <NEW_LINE> <DEDENT> if Password == PasswordAdmin: <NEW_LINE> <INDENT> await self.bot.say("I'll be back...") <NEW_LINE> sys.exit() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> await self.bot.say("H4H4H4H4H4H4H Mauvais mot de passe :thumbsdown: https://www.youtube.com/watch?v=lVIFzVy3tEo")
Bot adminstration commands. Works in multiple servers at once.
62598fae57b8e32f5250811a
class ElementHasAttribute(object): <NEW_LINE> <INDENT> def __init__(self, locator, attribute_name, attribute_value): <NEW_LINE> <INDENT> self.locator = locator <NEW_LINE> self.attribute_name = attribute_name <NEW_LINE> self.attribute_value = attribute_value <NEW_LINE> <DEDENT> def __call__(self, driver): <NEW_LINE> <INDENT> element = driver.find_element(*self.locator) <NEW_LINE> if self.attribute_value in element.get_attribute(self.attribute_name): <NEW_LINE> <INDENT> return element <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
An expectation for checking that an element has a particular attribute. returns the WebElement once it has the particular attribute
62598fae85dfad0860cbfa72
class FakeHash(object): <NEW_LINE> <INDENT> def __init__(self, h): <NEW_LINE> <INDENT> self.h = h <NEW_LINE> <DEDENT> def digest(self): <NEW_LINE> <INDENT> return struct.pack('<Q', self.h)
Implmenets the hexdigest required by HyperLogLog.
62598faed7e4931a7ef3c093
class LedControl(LedControlBase): <NEW_LINE> <INDENT> def _port_name_to_index(self, port_name): <NEW_LINE> <INDENT> if not port_name.startswith(self.SONIC_PORT_NAME_PREFIX): <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> port_idx = int(port_name[len(self.SONIC_PORT_NAME_PREFIX):]) <NEW_LINE> return port_idx <NEW_LINE> <DEDENT> def _port_state_to_mode(self, port_idx, state): <NEW_LINE> <INDENT> if state == "up": <NEW_LINE> <INDENT> return self.LED_MODE_UP[0] if (port_idx < 25) else self.LED_MODE_UP[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.LED_MODE_DOWN[0] if (port_idx < 25) else self.LED_MODE_DOWN[1] <NEW_LINE> <DEDENT> <DEDENT> def _port_led_mode_update(self, port_idx, ledMode): <NEW_LINE> <INDENT> with open(self.f_led.format("port{}".format(port_idx)), 'w') as led_file: <NEW_LINE> <INDENT> led_file.write(str(ledMode)) <NEW_LINE> <DEDENT> <DEDENT> def _initSystemLed(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(self.f_led.format("system"), 'w') as led_file: <NEW_LINE> <INDENT> led_file.write("1") <NEW_LINE> <DEDENT> DBG_PRINT("init system led to normal") <NEW_LINE> with open(self.f_led.format("idn"), 'w') as led_file: <NEW_LINE> <INDENT> led_file.write("1") <NEW_LINE> <DEDENT> DBG_PRINT("init idn led to off") <NEW_LINE> <DEDENT> except IOError as e: <NEW_LINE> <INDENT> DBG_PRINT(str(e)) <NEW_LINE> <DEDENT> <DEDENT> def _initPanelLed(self): <NEW_LINE> <INDENT> with open(self.f_led.format("port1"), 'r') as led_file: <NEW_LINE> <INDENT> shouldInit = (int(led_file.read()) == 0) <NEW_LINE> <DEDENT> if shouldInit == True: <NEW_LINE> <INDENT> for idx in range(1, 27): <NEW_LINE> <INDENT> defmode = self._port_state_to_mode(idx, "down") <NEW_LINE> with open(self.f_led.format("port{}".format(idx)), 'w') as led_file: <NEW_LINE> <INDENT> led_file.write(str(defmode)) <NEW_LINE> DBG_PRINT("init port{} led to mode={}".format(idx, defmode)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def _initDefaultConfig(self): <NEW_LINE> <INDENT> DBG_PRINT("start init led") <NEW_LINE> self._initSystemLed() <NEW_LINE> self._initPanelLed() <NEW_LINE> DBG_PRINT("init led done") <NEW_LINE> <DEDENT> def port_link_state_change(self, portname, state): <NEW_LINE> <INDENT> port_idx = self._port_name_to_index(portname) <NEW_LINE> ledMode = self._port_state_to_mode(port_idx, state) <NEW_LINE> with open(self.f_led.format("port{}".format(port_idx)), 'r') as led_file: <NEW_LINE> <INDENT> saveMode = int(led_file.read()) <NEW_LINE> <DEDENT> if ledMode == saveMode: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._port_led_mode_update(port_idx, ledMode) <NEW_LINE> DBG_PRINT("update {} led mode from {} to {}".format(portname, saveMode, ledMode)) <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> self.SONIC_PORT_NAME_PREFIX = "Ethernet" <NEW_LINE> self.LED_MODE_UP = [11, 11] <NEW_LINE> self.LED_MODE_DOWN = [7, 7] <NEW_LINE> self.f_led = "/sys/class/leds/{}/brightness" <NEW_LINE> self._initDefaultConfig()
Platform specific LED control class
62598fae4527f215b58e9ed4
class PageOfVulnerabilityCheck(object): <NEW_LINE> <INDENT> swagger_types = { 'links': 'list[Link]', 'page': 'PageInfo', 'resources': 'list[VulnerabilityCheck]' } <NEW_LINE> attribute_map = { 'links': 'links', 'page': 'page', 'resources': 'resources' } <NEW_LINE> def __init__(self, links=None, page=None, resources=None): <NEW_LINE> <INDENT> self._links = None <NEW_LINE> self._page = None <NEW_LINE> self._resources = None <NEW_LINE> self.discriminator = None <NEW_LINE> if links is not None: <NEW_LINE> <INDENT> self.links = links <NEW_LINE> <DEDENT> if page is not None: <NEW_LINE> <INDENT> self.page = page <NEW_LINE> <DEDENT> if resources is not None: <NEW_LINE> <INDENT> self.resources = resources <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def links(self): <NEW_LINE> <INDENT> return self._links <NEW_LINE> <DEDENT> @links.setter <NEW_LINE> def links(self, links): <NEW_LINE> <INDENT> self._links = links <NEW_LINE> <DEDENT> @property <NEW_LINE> def page(self): <NEW_LINE> <INDENT> return self._page <NEW_LINE> <DEDENT> @page.setter <NEW_LINE> def page(self, page): <NEW_LINE> <INDENT> self._page = page <NEW_LINE> <DEDENT> @property <NEW_LINE> def resources(self): <NEW_LINE> <INDENT> return self._resources <NEW_LINE> <DEDENT> @resources.setter <NEW_LINE> def resources(self, resources): <NEW_LINE> <INDENT> self._resources = resources <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(PageOfVulnerabilityCheck, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, PageOfVulnerabilityCheck): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62598fae8e7ae83300ee909f
class Platform: <NEW_LINE> <INDENT> LINUX = 'linux' <NEW_LINE> WINDOWS = 'windows' <NEW_LINE> DARWIN = 'darwin' <NEW_LINE> ANDROID = 'android' <NEW_LINE> IOS = 'ios'
Enumeration of supported platforms
62598fae7b180e01f3e4904f
class FunctionExecutionError(DockerBuildException): <NEW_LINE> <INDENT> def __init__(self, message, function_name, cause): <NEW_LINE> <INDENT> super(FunctionExecutionError, self).__init__(message) <NEW_LINE> self._function_name = function_name <NEW_LINE> self._cause = cause <NEW_LINE> <DEDENT> @property <NEW_LINE> def function_name(self): <NEW_LINE> <INDENT> return self._function_name <NEW_LINE> <DEDENT> @property <NEW_LINE> def cause(self): <NEW_LINE> <INDENT> return self._cause
Raised if an error is encountered when a build in function is executed
62598fae23849d37ff8510b1
class User(db.Model): <NEW_LINE> <INDENT> __bind_key__ = 'libraries' <NEW_LINE> __tablename__ = 'user' <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> absolute_uid = db.Column(db.Integer, unique=True) <NEW_LINE> permissions = db.relationship('Permissions', backref='user') <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return '<User {0}, {1}>' .format(self.id, self.absolute_uid)
User table Foreign-key absolute_uid is the primary key of the user in the user database microservice.
62598fae7047854f4633f3d8
class Category(models.Model): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = 'Catégorie' <NEW_LINE> verbose_name_plural = 'Catégories' <NEW_LINE> ordering = ['position', 'title'] <NEW_LINE> <DEDENT> title = models.CharField('Titre', max_length=80) <NEW_LINE> position = models.IntegerField('Position', default=0) <NEW_LINE> slug = models.SlugField(max_length=80, unique=True, help_text='Ces slugs vont provoquer des conflits ' "d'URL et sont donc interdits : notifications " 'resolution_alerte sujet sujets message messages') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.title <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('cat-forums-list', kwargs={'slug': self.slug}) <NEW_LINE> <DEDENT> def get_forums(self, user, with_count=False): <NEW_LINE> <INDENT> forums_pub = Forum.objects.get_public_forums_of_category(self, with_count=with_count) <NEW_LINE> if user is not None and user.is_authenticated(): <NEW_LINE> <INDENT> forums_private = Forum.objects.get_private_forums_of_category(self, user) <NEW_LINE> return list(forums_pub | forums_private) <NEW_LINE> <DEDENT> return forums_pub
A Category is a simple container for Forums. There is no kind of logic in a Category. It simply here for Forum presentation in a predefined order.
62598faecb5e8a47e493c178
class bcolors: <NEW_LINE> <INDENT> HEADER = '\033[95m' <NEW_LINE> OKBLUE = '\033[94m' <NEW_LINE> OKGREEN = '\033[92m' <NEW_LINE> WARNING = '\033[93m' <NEW_LINE> FAIL = '\033[91m' <NEW_LINE> ENDC = '\033[0m' <NEW_LINE> BOLD = '\033[1m' <NEW_LINE> UNDERLINE = '\033[4m'
ANSI color codes
62598fae4f6381625f1994be
class History(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(History, self).__init__() <NEW_LINE> <DEDENT> def writeMessageToRoom(self, message_id, message, room, name, email, picture, timestamp, **kwargs): <NEW_LINE> <INDENT> msg = { 'message_id': message_id, 'message': message, 'room': room, 'name': name, 'email': email, 'picture': picture, 'timestamp': timestamp } <NEW_LINE> if kwargs.has_key('html'): <NEW_LINE> <INDENT> msg['html'] = kwargs.get('html') <NEW_LINE> <DEDENT> res = es.index(index='messages', doc_type=msg['room'], id=msg['message_id'], body=msg); <NEW_LINE> <DEDENT> def getRoomMessages(self, room, date=None, count=50): <NEW_LINE> <INDENT> query = { 'sort': { 'timestamp': 'desc' }, 'size': count } <NEW_LINE> if date: <NEW_LINE> <INDENT> query['query'] = { 'range': { 'timestamp': { 'gte': '2000', 'lte': date.strftime('%y-%m-%d %H:%M:%S'), 'format': 'yyyy||yyyy-MM-dd HH:mm:ss' } } } <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> query['query'] = { 'match_all': {} } <NEW_LINE> <DEDENT> res = es.search(index='messages', doc_type=room, body=query) <NEW_LINE> return self.extractMessages(res) <NEW_LINE> <DEDENT> def searchRoomMessages(self, room, term, count=50): <NEW_LINE> <INDENT> query = { 'sort': { 'timestamp': 'desc' }, 'size': count } <NEW_LINE> query['query'] = { 'simple_query_string': { 'query': term, 'fields': ['message'] } } <NEW_LINE> res = es.search(index='messages', doc_type=room, body=query) <NEW_LINE> return self.extractMessages(res) <NEW_LINE> <DEDENT> def extractMessages(self, els): <NEW_LINE> <INDENT> res = [] <NEW_LINE> for doc in els['hits']['hits']: <NEW_LINE> <INDENT> res.append(doc.get('_source')) <NEW_LINE> <DEDENT> return res
docstring for History.
62598fae26068e7796d4c954
class HostName(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'site_names': {'key': 'siteNames', 'type': '[str]'}, 'azure_resource_name': {'key': 'azureResourceName', 'type': 'str'}, 'azure_resource_type': {'key': 'azureResourceType', 'type': 'str'}, 'custom_host_name_dns_record_type': {'key': 'customHostNameDnsRecordType', 'type': 'str'}, 'host_name_type': {'key': 'hostNameType', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, name: Optional[str] = None, site_names: Optional[List[str]] = None, azure_resource_name: Optional[str] = None, azure_resource_type: Optional[Union[str, "AzureResourceType"]] = None, custom_host_name_dns_record_type: Optional[Union[str, "CustomHostNameDnsRecordType"]] = None, host_name_type: Optional[Union[str, "HostNameType"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(HostName, self).__init__(**kwargs) <NEW_LINE> self.name = name <NEW_LINE> self.site_names = site_names <NEW_LINE> self.azure_resource_name = azure_resource_name <NEW_LINE> self.azure_resource_type = azure_resource_type <NEW_LINE> self.custom_host_name_dns_record_type = custom_host_name_dns_record_type <NEW_LINE> self.host_name_type = host_name_type
Details of a hostname derived from a domain. :ivar name: Name of the hostname. :vartype name: str :ivar site_names: List of apps the hostname is assigned to. This list will have more than one app only if the hostname is pointing to a Traffic Manager. :vartype site_names: list[str] :ivar azure_resource_name: Name of the Azure resource the hostname is assigned to. If it is assigned to a Traffic Manager then it will be the Traffic Manager name otherwise it will be the app name. :vartype azure_resource_name: str :ivar azure_resource_type: Type of the Azure resource the hostname is assigned to. Possible values include: "Website", "TrafficManager". :vartype azure_resource_type: str or ~azure.mgmt.web.v2020_12_01.models.AzureResourceType :ivar custom_host_name_dns_record_type: Type of the DNS record. Possible values include: "CName", "A". :vartype custom_host_name_dns_record_type: str or ~azure.mgmt.web.v2020_12_01.models.CustomHostNameDnsRecordType :ivar host_name_type: Type of the hostname. Possible values include: "Verified", "Managed". :vartype host_name_type: str or ~azure.mgmt.web.v2020_12_01.models.HostNameType
62598faea17c0f6771d5c234
class RespVoiceprintRegisterResponse(object): <NEW_LINE> <INDENT> openapi_types = { 'has_error': 'bool', 'error_id': 'str', 'error_desc': 'str', 'data': 'object' } <NEW_LINE> attribute_map = { 'has_error': 'hasError', 'error_id': 'errorId', 'error_desc': 'errorDesc', 'data': 'data' } <NEW_LINE> def __init__(self, has_error=None, error_id=None, error_desc=None, data=None): <NEW_LINE> <INDENT> self._has_error = None <NEW_LINE> self._error_id = None <NEW_LINE> self._error_desc = None <NEW_LINE> self._data = None <NEW_LINE> self.discriminator = None <NEW_LINE> if has_error is not None: <NEW_LINE> <INDENT> self.has_error = has_error <NEW_LINE> <DEDENT> if error_id is not None: <NEW_LINE> <INDENT> self.error_id = error_id <NEW_LINE> <DEDENT> if error_desc is not None: <NEW_LINE> <INDENT> self.error_desc = error_desc <NEW_LINE> <DEDENT> if data is not None: <NEW_LINE> <INDENT> self.data = data <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def has_error(self): <NEW_LINE> <INDENT> return self._has_error <NEW_LINE> <DEDENT> @has_error.setter <NEW_LINE> def has_error(self, has_error): <NEW_LINE> <INDENT> self._has_error = has_error <NEW_LINE> <DEDENT> @property <NEW_LINE> def error_id(self): <NEW_LINE> <INDENT> return self._error_id <NEW_LINE> <DEDENT> @error_id.setter <NEW_LINE> def error_id(self, error_id): <NEW_LINE> <INDENT> self._error_id = error_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def error_desc(self): <NEW_LINE> <INDENT> return self._error_desc <NEW_LINE> <DEDENT> @error_desc.setter <NEW_LINE> def error_desc(self, error_desc): <NEW_LINE> <INDENT> self._error_desc = error_desc <NEW_LINE> <DEDENT> @property <NEW_LINE> def data(self): <NEW_LINE> <INDENT> return self._data <NEW_LINE> <DEDENT> @data.setter <NEW_LINE> def data(self, data): <NEW_LINE> <INDENT> self._data = data <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, RespVoiceprintRegisterResponse): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually.
62598fae9c8ee82313040171
class DjangoEXPAException(Exception): <NEW_LINE> <INDENT> def __init__(self, error_message): <NEW_LINE> <INDENT> self.error_message = error_message
This error is raised whenever the EXPA API is not working as expected.
62598fae44b2445a339b6970
@skipIf(NO_MOCK, NO_MOCK_REASON) <NEW_LINE> class RpmTestCase(TestCase, LoaderModuleMockMixin): <NEW_LINE> <INDENT> def setup_loader_modules(self): <NEW_LINE> <INDENT> return {rpm: {'rpm': MagicMock(return_value=MagicMock)}} <NEW_LINE> <DEDENT> def test_list_pkgs(self): <NEW_LINE> <INDENT> mock = MagicMock(return_value='') <NEW_LINE> with patch.dict(rpm.__salt__, {'cmd.run': mock}): <NEW_LINE> <INDENT> self.assertDictEqual(rpm.list_pkgs(), {}) <NEW_LINE> <DEDENT> <DEDENT> def test_verify(self): <NEW_LINE> <INDENT> mock = MagicMock(return_value={'stdout': '', 'stderr': '', 'retcode': 0, 'pid': 12345}) <NEW_LINE> with patch.dict(rpm.__salt__, {'cmd.run_all': mock}): <NEW_LINE> <INDENT> self.assertDictEqual(rpm.verify('httpd'), {}) <NEW_LINE> <DEDENT> <DEDENT> def test_file_list(self): <NEW_LINE> <INDENT> mock = MagicMock(return_value='') <NEW_LINE> with patch.dict(rpm.__salt__, {'cmd.run': mock}): <NEW_LINE> <INDENT> self.assertDictEqual(rpm.file_list('httpd'), {'errors': [], 'files': []}) <NEW_LINE> <DEDENT> <DEDENT> def test_file_dict(self): <NEW_LINE> <INDENT> mock = MagicMock(return_value='') <NEW_LINE> with patch.dict(rpm.__salt__, {'cmd.run': mock}): <NEW_LINE> <INDENT> self.assertDictEqual(rpm.file_dict('httpd'), {'errors': [], 'packages': {}}) <NEW_LINE> <DEDENT> <DEDENT> def test_owner(self): <NEW_LINE> <INDENT> self.assertEqual(rpm.owner(), '') <NEW_LINE> ret = 'file /usr/bin/salt-jenkins-build is not owned by any package' <NEW_LINE> mock = MagicMock(return_value=ret) <NEW_LINE> with patch.dict(rpm.__salt__, {'cmd.run_stdout': mock}): <NEW_LINE> <INDENT> self.assertEqual(rpm.owner('/usr/bin/salt-jenkins-build'), '') <NEW_LINE> <DEDENT> ret = {'/usr/bin/vim': 'vim-enhanced-7.4.160-1.e17.x86_64', '/usr/bin/python': 'python-2.7.5-16.e17.x86_64'} <NEW_LINE> mock = MagicMock(side_effect=['python-2.7.5-16.e17.x86_64', 'vim-enhanced-7.4.160-1.e17.x86_64']) <NEW_LINE> with patch.dict(rpm.__salt__, {'cmd.run_stdout': mock}): <NEW_LINE> <INDENT> self.assertDictEqual(rpm.owner('/usr/bin/python', '/usr/bin/vim'), ret) <NEW_LINE> <DEDENT> <DEDENT> def test_checksum(self): <NEW_LINE> <INDENT> ret = { "file1.rpm": True, "file2.rpm": False, "file3.rpm": False, } <NEW_LINE> mock = MagicMock(side_effect=[True, 0, True, 1, False, 0]) <NEW_LINE> with patch.dict(rpm.__salt__, {'file.file_exists': mock, 'cmd.retcode': mock}): <NEW_LINE> <INDENT> self.assertDictEqual(rpm.checksum("file1.rpm", "file2.rpm", "file3.rpm"), ret) <NEW_LINE> <DEDENT> <DEDENT> def test_version_cmp_rpm(self): <NEW_LINE> <INDENT> with patch('salt.modules.rpm.rpm.labelCompare', MagicMock(return_value=0)), patch('salt.modules.rpm.HAS_RPM', True): <NEW_LINE> <INDENT> self.assertEqual(0, rpm.version_cmp('1', '2')) <NEW_LINE> <DEDENT> <DEDENT> def test_version_cmp_fallback(self): <NEW_LINE> <INDENT> with patch('salt.modules.rpm.rpm.labelCompare', MagicMock(return_value=0)), patch('salt.modules.rpm.HAS_RPM', False): <NEW_LINE> <INDENT> self.assertEqual(-1, rpm.version_cmp('1', '2'))
Test cases for salt.modules.rpm
62598fae56ac1b37e63021eb
class ThreadedCommentAdmin(CommentsAdmin): <NEW_LINE> <INDENT> list_display = ("avatar_link", "intro", "submit_date", "is_public", "is_removed", "admin_link") <NEW_LINE> list_display_links = ("intro", "submit_date") <NEW_LINE> fieldsets = ( (_("User"), {"fields": ("user_name", "user_email", "user_url")}), (None, {"fields": ("comment", ("is_public", "is_removed"))}), ) <NEW_LINE> def get_actions(self, request): <NEW_LINE> <INDENT> actions = super(CommentsAdmin, self).get_actions(request) <NEW_LINE> actions.pop("delete_selected") <NEW_LINE> actions.pop("flag_comments") <NEW_LINE> return actions
Admin class for comments.
62598fae7cff6e4e811b5a2c
class SamplerDynestyParameterForm(DynamicForm): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> kwargs['name'] = 'data-parameter' <NEW_LINE> kwargs['fields_properties'] = DYNESTY_FIELDS_PROPERTIES <NEW_LINE> self.job = kwargs.pop('job', None) <NEW_LINE> super(SamplerDynestyParameterForm, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> sampler = Sampler.objects.get(job=self.job) <NEW_LINE> for name, value in self.cleaned_data.items(): <NEW_LINE> <INDENT> SamplerParameter.objects.update_or_create( sampler=sampler, name=name, defaults={ 'value': value, } ) <NEW_LINE> <DEDENT> <DEDENT> def update_from_database(self, job): <NEW_LINE> <INDENT> if not job: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sampler = Sampler.objects.get(job=job) <NEW_LINE> if sampler.sampler_choice != DYNESTY: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> except Sampler.DoesNotExist: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> for name in DYNESTY_FIELDS_PROPERTIES.keys(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> value = SamplerParameter.objects.get(sampler=sampler, name=name).value <NEW_LINE> self.fields[name].initial = value <NEW_LINE> <DEDENT> except SamplerParameter.DoesNotExist: <NEW_LINE> <INDENT> pass
Sampler Dynesty Parameter Form extending Dynamic Form
62598fae30dc7b766599f84d
class RingSBendWaveguideCoupler(RingSymmWaveguideCoupler): <NEW_LINE> <INDENT> sbend_straight = NonNegativeNumberProperty(default = TECH.WG.SHORT_STRAIGHT) <NEW_LINE> def define_shape(self): <NEW_LINE> <INDENT> bs1a, bs2a = self.get_bend_size(self.coupler_angles[0]) <NEW_LINE> bs1b, bs2b = self.get_bend_size(self.coupler_angles[1]) <NEW_LINE> s1 = Shape([(-0.5*self.length-bs2a, 0.0)]) <NEW_LINE> s1.add_polar(bs1a + bs2a + self.sbend_straight, 180.0 + self.coupler_angles[0]) <NEW_LINE> s1.add_polar(bs1a, 180.0) <NEW_LINE> s2 = Shape([(0.5*self.length+bs1b, 0.0)]) <NEW_LINE> s2.add_polar(bs1b + bs2b + self.sbend_straight, - self.coupler_angles[1]) <NEW_LINE> s2.add_polar(bs2b, 0.0) <NEW_LINE> s1.reverse() <NEW_LINE> cs = s1 + s2 <NEW_LINE> return cs
coupler that couples with an SBend along or away from the ring
62598fae2ae34c7f260ab0e1
class LatLong: <NEW_LINE> <INDENT> def generate(self, json_result) -> None: <NEW_LINE> <INDENT> lat_longs = mapquest_interaction.lat_long(json_result) <NEW_LINE> latitude = '' <NEW_LINE> longitude = '' <NEW_LINE> for dictionary in lat_longs: <NEW_LINE> <INDENT> if dictionary['lat'] >= 0: <NEW_LINE> <INDENT> latitude = str(round(dictionary['lat'], 2)) + 'N ' <NEW_LINE> <DEDENT> elif dictionary['lat'] < 0: <NEW_LINE> <INDENT> latitude = str(round(abs(dictionary['lat']), 2)) + 'S ' <NEW_LINE> <DEDENT> if dictionary['lng'] >= 0: <NEW_LINE> <INDENT> longitude = str(round(dictionary['lng'], 2)) + 'E' <NEW_LINE> <DEDENT> elif dictionary['lng'] < 0: <NEW_LINE> <INDENT> longitude = str(round(abs(dictionary['lng']), 2)) + 'W' <NEW_LINE> <DEDENT> print(latitude + longitude) <NEW_LINE> <DEDENT> print()
Class that prints the latitude and longitude of each location
62598faeaad79263cf42e7d3
class ValueIterationAgent(ValueEstimationAgent): <NEW_LINE> <INDENT> def __init__(self, mdp, discount = 0.9, iterations = 100): <NEW_LINE> <INDENT> self.mdp = mdp <NEW_LINE> self.discount = discount <NEW_LINE> self.iterations = iterations <NEW_LINE> self.values = util.Counter() <NEW_LINE> self.qValues = util.Counter() <NEW_LINE> "*** YOUR CODE HERE ***" <NEW_LINE> all_states = self.mdp.getStates() <NEW_LINE> for i in range(0, self.iterations): <NEW_LINE> <INDENT> state_values = util.Counter() <NEW_LINE> for state in all_states: <NEW_LINE> <INDENT> actions = self.mdp.getPossibleActions(state) <NEW_LINE> max_qValue = float('-Inf') <NEW_LINE> if self.mdp.isTerminal(state) or not actions: <NEW_LINE> <INDENT> state_values[state] = 0 <NEW_LINE> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for action in actions: <NEW_LINE> <INDENT> transitions = self.mdp.getTransitionStatesAndProbs(state, action) <NEW_LINE> qValue = 0 <NEW_LINE> for t in transitions: <NEW_LINE> <INDENT> qValue += t[1] * (self.mdp.getReward(state, action, t[0]) + self.discount * self.values[t[0]]) <NEW_LINE> <DEDENT> self.qValues[(state, action)] = qValue <NEW_LINE> max_qValue = max(max_qValue, qValue) <NEW_LINE> <DEDENT> state_values[state] = max_qValue <NEW_LINE> <DEDENT> <DEDENT> self.values = state_values <NEW_LINE> <DEDENT> <DEDENT> def getValue(self, state): <NEW_LINE> <INDENT> return self.values[state] <NEW_LINE> <DEDENT> def getQValue(self, state, action): <NEW_LINE> <INDENT> return self.qValues[(state, action)] <NEW_LINE> <DEDENT> def getPolicy(self, state): <NEW_LINE> <INDENT> possible_actions = self.mdp.getPossibleActions(state) <NEW_LINE> if self.mdp.isTerminal(state) or not possible_actions: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> best_action = None <NEW_LINE> maxValue = float('-Inf') <NEW_LINE> for action in possible_actions: <NEW_LINE> <INDENT> if self.qValues[(state, action)] > maxValue: <NEW_LINE> <INDENT> maxValue = self.qValues[(state, action)] <NEW_LINE> best_action = action <NEW_LINE> <DEDENT> <DEDENT> return best_action <NEW_LINE> <DEDENT> def getAction(self, state): <NEW_LINE> <INDENT> return self.getPolicy(state)
* Please read learningAgents.py before reading this.* A ValueIterationAgent takes a Markov decision process (see mdp.py) on initialization and runs value iteration for a given number of iterations using the supplied discount factor.
62598fae8da39b475be031e4
class ExpectimaxAgent(MultiAgentSearchAgent): <NEW_LINE> <INDENT> def getAction(self, gameState): <NEW_LINE> <INDENT> def expValue(gameState, i ,depth): <NEW_LINE> <INDENT> if gameState.isLose() or gameState.isWin(): <NEW_LINE> <INDENT> return self.evaluationFunction(gameState) <NEW_LINE> <DEDENT> actions = gameState.getLegalActions(i) <NEW_LINE> prob = 1./float(len(actions)) <NEW_LINE> value = 0.0 <NEW_LINE> if i == gameState.getNumAgents() - 1: <NEW_LINE> <INDENT> for action in actions: <NEW_LINE> <INDENT> nextState = gameState.generateSuccessor(i,action) <NEW_LINE> value += maxValue(nextState, depth - 1) * prob <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for action in actions: <NEW_LINE> <INDENT> nextState = gameState.generateSuccessor(i,action) <NEW_LINE> value += expValue(nextState, i + 1, depth) * prob <NEW_LINE> <DEDENT> <DEDENT> return value <NEW_LINE> <DEDENT> def maxValue( gameState,depth): <NEW_LINE> <INDENT> if gameState.isLose() or gameState.isWin() or depth == 0: <NEW_LINE> <INDENT> return self.evaluationFunction(gameState) <NEW_LINE> <DEDENT> actions = gameState.getLegalActions(0) <NEW_LINE> value = -float('inf') <NEW_LINE> for action in actions: <NEW_LINE> <INDENT> nextState = gameState.generateSuccessor(0,action) <NEW_LINE> value = max(expValue(nextState, 1, depth),value) <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> actionsOfMax = gameState.getLegalActions() <NEW_LINE> bestAction = "" <NEW_LINE> value = -float('inf') <NEW_LINE> for action in actionsOfMax: <NEW_LINE> <INDENT> nextState = gameState.generateSuccessor(0,action) <NEW_LINE> evaluation = expValue(nextState,1,self.depth) <NEW_LINE> if evaluation > value: <NEW_LINE> <INDENT> value = evaluation <NEW_LINE> bestAction = action <NEW_LINE> <DEDENT> <DEDENT> return bestAction
Your expectimax agent (question 4)
62598fae66656f66f7d5a3ef
class SourceFree1DMaxwellOperator(MaxwellOperator): <NEW_LINE> <INDENT> _default_dimensions = 1 <NEW_LINE> def get_eh_subset(self): <NEW_LINE> <INDENT> return ( (False,True,False) + (False,False,True) )
A 1D TE Maxwell operator. Field order is [Ey Hz].
62598fae66673b3332c303cc
class IJsonMime(IMime): <NEW_LINE> <INDENT> pass
Interface for JSON mime type.
62598fae009cb60464d01520
class Summary: <NEW_LINE> <INDENT> def __init__(self, proc_results): <NEW_LINE> <INDENT> self.proc_results = proc_results <NEW_LINE> <DEDENT> def _gen_files(self): <NEW_LINE> <INDENT> files = [] <NEW_LINE> for entry in self.proc_results: <NEW_LINE> <INDENT> for call in entry["calls"]: <NEW_LINE> <INDENT> if call["category"] == "filesystem": <NEW_LINE> <INDENT> for argument in call["arguments"]: <NEW_LINE> <INDENT> if argument["name"] == "FileName": <NEW_LINE> <INDENT> if argument["value"] not in files: <NEW_LINE> <INDENT> files.append(argument["value"]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return files <NEW_LINE> <DEDENT> def _gen_keys(self): <NEW_LINE> <INDENT> keys = [] <NEW_LINE> def _check_registry(handles, registry, subkey, handle): <NEW_LINE> <INDENT> for known_handle in handles: <NEW_LINE> <INDENT> if handle != 0 and handle == known_handle["handle"]: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> name = "" <NEW_LINE> if registry == 0x80000000: <NEW_LINE> <INDENT> name = "HKEY_CLASSES_ROOT\\" <NEW_LINE> <DEDENT> elif registry == 0x80000001: <NEW_LINE> <INDENT> name = "HKEY_CURRENT_USER\\" <NEW_LINE> <DEDENT> elif registry == 0x80000002: <NEW_LINE> <INDENT> name = "HKEY_LOCAL_MACHINE\\" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for known_handle in handles: <NEW_LINE> <INDENT> if registry == known_handle["handle"]: <NEW_LINE> <INDENT> name = known_handle["name"] + "\\" <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> handles.append({"handle" : handle, "name" : name + subkey}) <NEW_LINE> <DEDENT> for process in self.proc_results: <NEW_LINE> <INDENT> handles = [] <NEW_LINE> for call in process["calls"]: <NEW_LINE> <INDENT> if call["api"].startswith("RegOpenKeyEx"): <NEW_LINE> <INDENT> registry = 0 <NEW_LINE> subkey = "" <NEW_LINE> handle = 0 <NEW_LINE> for argument in call["arguments"]: <NEW_LINE> <INDENT> if argument["name"] == "Registry": <NEW_LINE> <INDENT> registry = int(argument["value"], 16) <NEW_LINE> <DEDENT> elif argument["name"] == "SubKey": <NEW_LINE> <INDENT> subkey = argument["value"] <NEW_LINE> <DEDENT> elif argument["name"] == "Handle": <NEW_LINE> <INDENT> handle = int(argument["value"], 16) <NEW_LINE> <DEDENT> <DEDENT> _check_registry(handles, registry, subkey, handle) <NEW_LINE> <DEDENT> <DEDENT> for handle in handles: <NEW_LINE> <INDENT> if handle["name"] not in keys: <NEW_LINE> <INDENT> keys.append(handle["name"]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return keys <NEW_LINE> <DEDENT> def _gen_mutexes(self): <NEW_LINE> <INDENT> mutexes = [] <NEW_LINE> for entry in self.proc_results: <NEW_LINE> <INDENT> for call in entry["calls"]: <NEW_LINE> <INDENT> if call["category"] == "synchronization": <NEW_LINE> <INDENT> for argument in call["arguments"]: <NEW_LINE> <INDENT> if argument["name"] == "MutexName": <NEW_LINE> <INDENT> if argument["value"] not in mutexes: <NEW_LINE> <INDENT> mutexes.append(argument["value"]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return mutexes <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> summary = {} <NEW_LINE> summary["files"] = self._gen_files() <NEW_LINE> summary["keys"] = self._gen_keys() <NEW_LINE> summary["mutexes"] = self._gen_mutexes() <NEW_LINE> return summary
Generates summary information.
62598fae67a9b606de545fcd
class TweetAnalyzer(): <NEW_LINE> <INDENT> def clean_tweet(self, tweet): <NEW_LINE> <INDENT> return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", tweet).split()) <NEW_LINE> <DEDENT> def analyze_sentiment(self, tweet): <NEW_LINE> <INDENT> analysis = TextBlob(self.clean_tweet(tweet)) <NEW_LINE> if analysis.sentiment.polarity > 0: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> elif analysis.sentiment.polarity == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> <DEDENT> def tweets_to_data_frame(self, tweets): <NEW_LINE> <INDENT> df = pd.DataFrame(data=[tweet.text for tweet in tweets], columns=['tweets']) <NEW_LINE> df['id'] = np.array([tweet.id for tweet in tweets]) <NEW_LINE> df['len'] = np.array([len(tweet.text) for tweet in tweets]) <NEW_LINE> df['date'] = np.array([tweet.created_at for tweet in tweets]) <NEW_LINE> df['source'] = np.array([tweet.source for tweet in tweets]) <NEW_LINE> df['likes'] = np.array([tweet.favorite_count for tweet in tweets]) <NEW_LINE> df['retweets'] = np.array([tweet.retweet_count for tweet in tweets]) <NEW_LINE> return df
Functionality for analyzing and categorizing content from tweets.
62598faefff4ab517ebcd7e5
class IncompatiblePeer(SSHException): <NEW_LINE> <INDENT> pass
A disagreement arose regarding an algorithm required for key exchange. .. versionadded:: 2.9
62598faea219f33f346c6816
class FontSizeSpec(DataSpec): <NEW_LINE> <INDENT> def __init__(self, default, help=None): <NEW_LINE> <INDENT> super(FontSizeSpec, self).__init__(List(String), default=default, help=help) <NEW_LINE> <DEDENT> def prepare_value(self, cls, name, value): <NEW_LINE> <INDENT> if isinstance(value, string_types): <NEW_LINE> <INDENT> warn('Setting a fixed font size value as a string %r is deprecated, ' 'set with value(%r) or [%r] instead' % (value, value, value), DeprecationWarning, stacklevel=2) <NEW_LINE> if len(value) > 0 and value[0].isdigit(): <NEW_LINE> <INDENT> value = dict(value=value) <NEW_LINE> <DEDENT> <DEDENT> return super(FontSizeSpec, self).prepare_value(cls, name, value)
A DataSpec property that can be set to a font size fixed value, or a data source column name referring to column of font size data.
62598faee5267d203ee6b90a
@attr.s <NEW_LINE> class Session: <NEW_LINE> <INDENT> configuration: Configuration = attr.ib() <NEW_LINE> def __attrs_post_init__(self) -> None: <NEW_LINE> <INDENT> self.interval_wave_object = simpleaudio.WaveObject.from_wave_file( self.configuration.interval_sound_path.as_posix(), ) <NEW_LINE> self.start_stop_wave_object = simpleaudio.WaveObject.from_wave_file( self.configuration.start_stop_sound_path.as_posix(), ) <NEW_LINE> <DEDENT> async def meditate(self) -> None: <NEW_LINE> <INDENT> print( f"{datetime.datetime.utcnow()}: Start a " f"{self.configuration.session_duration} " f"seconds meditation.", ) <NEW_LINE> self.start_stop_wave_object.play() <NEW_LINE> with trio.move_on_after(self.configuration.session_duration): <NEW_LINE> <INDENT> for i in itertools.count(1): <NEW_LINE> <INDENT> print( f"{datetime.datetime.utcnow()}: Interval {i} starts. " f"({self.configuration.interval_duration} seconds)", ) <NEW_LINE> await trio.sleep(self.configuration.interval_duration) <NEW_LINE> self.interval_wave_object.play() <NEW_LINE> <DEDENT> <DEDENT> print(f"{datetime.datetime.utcnow()}: End meditation.") <NEW_LINE> self.start_stop_wave_object.play() <NEW_LINE> await trio.sleep(5) <NEW_LINE> self.start_stop_wave_object.play() <NEW_LINE> await trio.sleep(5) <NEW_LINE> self.start_stop_wave_object.play().wait_done() <NEW_LINE> print(f"{datetime.datetime.utcnow()}: End meditation.")
Meditation session.
62598fae60cbc95b0636434f
class FilteringOption(Option): <NEW_LINE> <INDENT> def take_action(self, action, dest, opt, value, values, parser): <NEW_LINE> <INDENT> if action in FilteringOption.ACTIONS: <NEW_LINE> <INDENT> Option.take_action(self, action, dest, opt, value, values, parser) <NEW_LINE> <DEDENT> if value is None: <NEW_LINE> <INDENT> value = [] <NEW_LINE> <DEDENT> elif not self.nargs or self.nargs <= 1: <NEW_LINE> <INDENT> value = [value] <NEW_LINE> <DEDENT> parser.AddParsedArg(self, opt, [str(v) for v in value])
Subclass that supports Option filtering for FilteringOptionParser
62598faecb5e8a47e493c179
class NativeProcess(_NativeProcess): <NEW_LINE> <INDENT> pass
This class represents a process in the native environment on which it is imported. It aims to allow applications to access a :py:class:`.Process` object suitable for its environment with out checking the operating system.
62598fae4f6381625f1994bf
class AttributeOption(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'attributeoption' <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> option = db.Column(db.String(64)) <NEW_LINE> group_id = db.Column(db.Integer, db.ForeignKey('attributeoptiongroup.id'), nullable=False) <NEW_LINE> item_attropt_values = db.relationship('ItemAtributeValue', backref='option', lazy='dynamic') <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return self.option
Значения выбора: Например "Страна" - Россия, США... Например "Размер" Small/Medium/Large
62598faecc0a2c111447b012
class User_revision( object ): <NEW_LINE> <INDENT> def __init__( self, revision, user_id = None, username = None ): <NEW_LINE> <INDENT> self.__revision = revision <NEW_LINE> self.__user_id = user_id <NEW_LINE> self.__username = username <NEW_LINE> <DEDENT> def to_dict( self ): <NEW_LINE> <INDENT> return dict( revision = self.__revision, user_id = self.__user_id, username = self.__username, ) <NEW_LINE> <DEDENT> revision = property( lambda self: self.__revision ) <NEW_LINE> user_id = property( lambda self: self.__user_id ) <NEW_LINE> username = property( lambda self: self.__username )
A revision timestamp along with information on the user that made that revision.
62598fae01c39578d7f12d7f
@base.calculators.add('scenario_risk') <NEW_LINE> class ScenarioRiskCalculator(base.RiskCalculator): <NEW_LINE> <INDENT> core_func = scenario_risk <NEW_LINE> losses_by_key = datastore.persistent_attribute('losses_by_key') <NEW_LINE> gmf_by_trt_gsim = datastore.persistent_attribute('gmf_by_trt_gsim') <NEW_LINE> pre_calculator = 'scenario' <NEW_LINE> is_stochastic = True <NEW_LINE> def pre_execute(self): <NEW_LINE> <INDENT> if 'gmfs' in self.oqparam.inputs: <NEW_LINE> <INDENT> self.pre_calculator = None <NEW_LINE> <DEDENT> base.RiskCalculator.pre_execute(self) <NEW_LINE> logging.info('Building the epsilons') <NEW_LINE> eps_dict = self.make_eps_dict( self.oqparam.number_of_ground_motion_fields) <NEW_LINE> self.riskinputs = self.build_riskinputs(base.get_gmfs(self), eps_dict) <NEW_LINE> <DEDENT> def post_execute(self, result): <NEW_LINE> <INDENT> self.losses_by_key = result
Run a scenario risk calculation
62598faea17c0f6771d5c236
class SpiderError(IOError): <NEW_LINE> <INDENT> def __init__(self, reason): <NEW_LINE> <INDENT> self.args = reason <NEW_LINE> self.reason = reason <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '#SpiderError%s#' % self.reason
错误信息
62598fae76e4537e8c3ef5ae
class UserInput(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.body = None <NEW_LINE> self.clickPosition = None <NEW_LINE> self.gameRef = None <NEW_LINE> self.leftMouse = False <NEW_LINE> self.middleMouse = False <NEW_LINE> self.rightMouse = False <NEW_LINE> <DEDENT> def createDynamicBody(self, position): <NEW_LINE> <INDENT> self.body = DynamicBody(position=position) <NEW_LINE> <DEDENT> def updateDynamicPosition(self, position): <NEW_LINE> <INDENT> self.body.position = position <NEW_LINE> <DEDENT> def releaseBody(self, position): <NEW_LINE> <INDENT> power = Vec2D.magnitude(self.clickPosition-position) <NEW_LINE> powerLvl = max(1, min(100, power))*0.005 <NEW_LINE> direction = Vec2D.normalize(self.clickPosition-position) <NEW_LINE> self.body.velocity = Vec2D.scale(direction, powerLvl) <NEW_LINE> self.body.position = self.gameRef.screenToWorld(self.body.position) <NEW_LINE> self.gameRef.addDynamicBody(self.body) <NEW_LINE> self.body = None <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> x, y = pg.mouse.get_pos() <NEW_LINE> mousePos = (Vec2D(x, y)) <NEW_LINE> left, middle, right = pg.mouse.get_pressed() <NEW_LINE> if left and not self.leftMouse: <NEW_LINE> <INDENT> self.clickPosition = mousePos <NEW_LINE> self.createDynamicBody(mousePos) <NEW_LINE> <DEDENT> elif not left and self.leftMouse: <NEW_LINE> <INDENT> self.releaseBody(mousePos) <NEW_LINE> <DEDENT> if self.body and self.leftMouse: <NEW_LINE> <INDENT> self.updateDynamicPosition(mousePos) <NEW_LINE> <DEDENT> self.leftMouse, self.middleMouse, self.rightMouse = (left, middle, right)
A class to handle mouse input that creates dynamic bodies
62598fae460517430c43205e
class Element(object): <NEW_LINE> <INDENT> self_closing_tags = ('meta', 'img', 'link', 'script', 'br', 'hr') <NEW_LINE> ELEMENT = '%' <NEW_LINE> ID = '#' <NEW_LINE> CLASS = '.' <NEW_LINE> def __init__(self, haml): <NEW_LINE> <INDENT> self.haml = haml <NEW_LINE> self.tag = None <NEW_LINE> self.id = None <NEW_LINE> self.classes = None <NEW_LINE> self.attributes = '' <NEW_LINE> self.self_close = False <NEW_LINE> self.django_variable = False <NEW_LINE> self.inline_content = '' <NEW_LINE> self._parse_haml() <NEW_LINE> <DEDENT> def _parse_haml(self): <NEW_LINE> <INDENT> haml_regex = r"(?P<tag>%\w+)?(?P<id>#\w*)?(?P<class>\.[\w\.]*)*(?P<attributes>\{.*\})?(?P<selfclose>/)?(?P<django>=)?(?P<inline>[^\w\.#\{].*)?" <NEW_LINE> split_tags = re.search(haml_regex, self.haml).groupdict('') <NEW_LINE> self.attributes_dict = self._parse_attribute_dictionary(split_tags.get('attributes')) <NEW_LINE> self.tag = split_tags.get('tag').strip(self.ELEMENT) or 'div' <NEW_LINE> self.id = self._parse_id(split_tags.get('id')) <NEW_LINE> self.classes = ('%s %s' % (split_tags.get('class').lstrip(self.CLASS).replace('.', ' '), self.attributes_dict.get('class', ''))).strip() <NEW_LINE> self.self_close = split_tags.get('selfclose') or self.tag in self.self_closing_tags <NEW_LINE> self.django_variable = split_tags.get('django') != '' <NEW_LINE> self.inline_content = split_tags.get('inline').strip() <NEW_LINE> <DEDENT> def _parse_id(self, id_haml): <NEW_LINE> <INDENT> id_text = id_haml.strip(self.ID) <NEW_LINE> if 'id' in self.attributes_dict: <NEW_LINE> <INDENT> id_text += self._parse_id_dict(self.attributes_dict['id']) <NEW_LINE> <DEDENT> id_text = id_text.lstrip('_') <NEW_LINE> return id_text <NEW_LINE> <DEDENT> def _parse_id_dict(self, id_dict): <NEW_LINE> <INDENT> text = '' <NEW_LINE> id_dict = self.attributes_dict.get('id') <NEW_LINE> if isinstance(id_dict, str): <NEW_LINE> <INDENT> text = '_'+id_dict <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> text = '' <NEW_LINE> for one_id in id_dict: <NEW_LINE> <INDENT> text += '_'+one_id <NEW_LINE> <DEDENT> <DEDENT> return text <NEW_LINE> <DEDENT> def _parse_attribute_dictionary(self, attribute_dict_string): <NEW_LINE> <INDENT> attributes_dict = {} <NEW_LINE> if (attribute_dict_string): <NEW_LINE> <INDENT> attributes_dict = eval(attribute_dict_string) <NEW_LINE> for k, v in attributes_dict.items(): <NEW_LINE> <INDENT> if k != 'id' and k != 'class': <NEW_LINE> <INDENT> self.attributes += "%s='%s' " % (k, v) <NEW_LINE> <DEDENT> <DEDENT> self.attributes = self.attributes.strip() <NEW_LINE> <DEDENT> return attributes_dict
contains the pieces of an element and can populate itself from haml element text
62598fae56b00c62f0fb28b7
class Meta: <NEW_LINE> <INDENT> model = SelectTemplateHit <NEW_LINE> fields = ('uuid', 'task_uuid', 'date_created', 'query_range', 'query_range_sequence', 'ff_id', 'ff_name', 'is_resolved_hit', 'ff_cath_domain_count', 'ff_uniq_ec_count', 'ff_uniq_go_count', 'ff_seq_count', 'ff_dops_score', 'evalue', 'bitscore', ) <NEW_LINE> read_only_fields = fields
Meta class to map serializer's fields with the model fields.
62598faef548e778e596b5a6
class SelectFrame(BaseSelectFrame): <NEW_LINE> <INDENT> menu_start_line = 2 <NEW_LINE> def initialize(self, options, text, spos , height=None, background=''): <NEW_LINE> <INDENT> self._options = options <NEW_LINE> self._text = text <NEW_LINE> self._sx, self._sy = spos <NEW_LINE> self._height = height <NEW_LINE> self._background = background <NEW_LINE> super(SelectFrame, self).initialize() <NEW_LINE> <DEDENT> def load_all(self): <NEW_LINE> <INDENT> l = len(self._options) <NEW_LINE> pos = [ (self._sx+i, self._sy) for i in range(l) ] <NEW_LINE> keys = dict( (str(i+1),i) for i in range(l) ) <NEW_LINE> return (self._options, pos, keys, self._text), self._height, self._background <NEW_LINE> <DEDENT> def finish(self): <NEW_LINE> <INDENT> raise NotImplementedError
options = ( value1, value2, ...) text = (text1, text2, ...) spos = (startx, starty)
62598faeeab8aa0e5d30bd8f
class TestUnknownResourceHookUpdate(TestFunctional): <NEW_LINE> <INDENT> def test_epilogue_update(self): <NEW_LINE> <INDENT> self.server.manager(MGR_CMD_SET, SERVER, {'job_history_enable': 'True'}) <NEW_LINE> hook_body = "import pbs\n" <NEW_LINE> hook_body += "e = pbs.event()\n" <NEW_LINE> hook_body += "hstr=\'" + "unkown_resource" + "\'\n" <NEW_LINE> hook_body += "e.job.resources_used[\"foo_str\"] = 'unknown resource'\n" <NEW_LINE> hook_body += "e.job.resources_used[\"foo_i\"] = 5\n" <NEW_LINE> a = {'event': 'execjob_epilogue', 'enabled': 'True'} <NEW_LINE> self.server.create_import_hook("ep", a, hook_body) <NEW_LINE> J = Job() <NEW_LINE> J.set_sleep_time(1) <NEW_LINE> jid = self.server.submit(J) <NEW_LINE> self.server.expect(JOB, {'job_state': 'F'}, id=jid, extend='x') <NEW_LINE> self.server.isUp() <NEW_LINE> log_match = 'unable to update attribute resources_used.foo_str ' <NEW_LINE> log_match += 'in job_obit' <NEW_LINE> self.server.log_match("%s;.*%s.*" % (jid, log_match), regexp=True)
Test that a resource that is not known to the server and is updated in an execjob_epilogue hook doesn't crash the server.
62598fae009cb60464d01522
class DnsSrvRecord(A10BaseClass): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.ERROR_MSG = "" <NEW_LINE> self.required = [ "srv_name","port"] <NEW_LINE> self.b_key = "dns-srv-record" <NEW_LINE> self.a10_url="/axapi/v3/gslb/zone/{name}/service/{service_port}+{service_name}/dns-srv-record/{srv_name}+{port}" <NEW_LINE> self.DeviceProxy = "" <NEW_LINE> self.srv_name = "" <NEW_LINE> self.uuid = "" <NEW_LINE> self.weight = "" <NEW_LINE> self.priority = "" <NEW_LINE> self.ttl = "" <NEW_LINE> self.port = "" <NEW_LINE> for keys, value in kwargs.items(): <NEW_LINE> <INDENT> setattr(self,keys, value)
Class Description:: Specify DNS SRV Record. Class dns-srv-record supports CRUD Operations and inherits from `common/A10BaseClass`. This class is the `"PARENT"` class for this module.` :param srv_name: {"description": "Specify Domain Name", "format": "string", "minLength": 1, "optional": false, "maxLength": 127, "type": "string"} :param uuid: {"description": "uuid of the object", "format": "string", "minLength": 1, "modify-not-allowed": 1, "optional": true, "maxLength": 64, "type": "string"} :param weight: {"description": "Specify Weight, default is 10", "format": "number", "default": 10, "optional": true, "maximum": 100, "minimum": 1, "type": "number"} :param priority: {"description": "Specify Priority", "format": "number", "type": "number", "maximum": 65535, "minimum": 0, "optional": true} :param ttl: {"description": "Specify TTL", "format": "number", "type": "number", "maximum": 2147483647, "minimum": 0, "optional": true} :param port: {"description": "Specify Port (Port Number)", "format": "number", "type": "number", "maximum": 65534, "minimum": 0, "optional": false} :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py` URL for this object:: `https://<Hostname|Ip address>//axapi/v3/gslb/zone/{name}/service/{service_port}+{service_name}/dns-srv-record/{srv_name}+{port}`.
62598fae7d847024c075c3c5
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.ALPHA) <NEW_LINE> class SetDefaultBeta(base.DescribeCommand): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def Args(parser): <NEW_LINE> <INDENT> _AddSetDefaultArgs(parser) <NEW_LINE> <DEDENT> def Run(self, args): <NEW_LINE> <INDENT> return versions_util.SetDefault(versions_api.VersionsClient('v1beta1'), args.version, model=args.model)
Sets an existing Cloud ML Engine version as the default for its model.
62598fae796e427e5384e796
class ReleaseViewSet(AppResourceViewSet): <NEW_LINE> <INDENT> model = models.Release <NEW_LINE> serializer_class = serializers.ReleaseSerializer <NEW_LINE> def get_object(self, **kwargs): <NEW_LINE> <INDENT> return self.get_queryset(**kwargs).get(version=self.kwargs['version']) <NEW_LINE> <DEDENT> def rollback(self, request, **kwargs): <NEW_LINE> <INDENT> app = self.get_app() <NEW_LINE> try: <NEW_LINE> <INDENT> release = app.release_set.latest() <NEW_LINE> version_to_rollback_to = release.version - 1 <NEW_LINE> if request.data.get('version'): <NEW_LINE> <INDENT> version_to_rollback_to = int(request.data['version']) <NEW_LINE> <DEDENT> new_release = release.rollback(request.user, version_to_rollback_to) <NEW_LINE> response = {'version': new_release.version} <NEW_LINE> return Response(response, status=status.HTTP_201_CREATED) <NEW_LINE> <DEDENT> except EnvironmentError as e: <NEW_LINE> <INDENT> return Response({'detail': str(e)}, status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> except RuntimeError: <NEW_LINE> <INDENT> new_release.delete() <NEW_LINE> raise
A viewset for interacting with Release objects.
62598faeb7558d589546362c
class MetaSerializer(type): <NEW_LINE> <INDENT> _fields_storage_key = '_fields' <NEW_LINE> @classmethod <NEW_LINE> def __prepare__(mcs, name, bases, **kwargs): <NEW_LINE> <INDENT> return OrderedDict() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _get_fields(mcs, bases, namespace): <NEW_LINE> <INDENT> fields = [ (name, namespace.pop(name)) for name, attribute in list(namespace.items()) if isinstance(attribute, BaseField) ] <NEW_LINE> for base in reversed(bases): <NEW_LINE> <INDENT> if hasattr(base, mcs._fields_storage_key): <NEW_LINE> <INDENT> fields = list( getattr(base, mcs._fields_storage_key).items() ) + fields <NEW_LINE> <DEDENT> <DEDENT> return OrderedDict(fields) <NEW_LINE> <DEDENT> def __new__(mcs, name, bases, namespace): <NEW_LINE> <INDENT> namespace[mcs._fields_storage_key] = mcs._get_fields(bases, namespace) <NEW_LINE> return super().__new__( mcs, name, bases, dict(namespace) )
Metaclass for handling serialization with field objects.
62598fae8a43f66fc4bf217c