code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class Client: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def pipeline_class(code_model, async_mode: bool) -> str: <NEW_LINE> <INDENT> if code_model.options["azure_arm"]: <NEW_LINE> <INDENT> if async_mode: <NEW_LINE> <INDENT> return "AsyncARMPipelineClient" <NEW_LINE> <DEDENT> return "ARMPipelineClient" <NEW_LINE> <DEDENT> if async_mode: <NEW_LINE> <INDENT> return "AsyncPipelineClient" <NEW_LINE> <DEDENT> return "PipelineClient" <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def imports(code_model, async_mode: bool) -> FileImport: <NEW_LINE> <INDENT> file_import = FileImport() <NEW_LINE> file_import.add_from_import("msrest", "Serializer", ImportType.AZURECORE) <NEW_LINE> file_import.add_from_import("msrest", "Deserializer", ImportType.AZURECORE) <NEW_LINE> file_import.add_from_import("typing", "Any", ImportType.STDLIB, TypingSection.CONDITIONAL) <NEW_LINE> any_optional_gp = any(not gp.required for gp in code_model.global_parameters) <NEW_LINE> if any_optional_gp or code_model.base_url: <NEW_LINE> <INDENT> file_import.add_from_import("typing", "Optional", ImportType.STDLIB, TypingSection.CONDITIONAL) <NEW_LINE> <DEDENT> if code_model.options["azure_arm"]: <NEW_LINE> <INDENT> file_import.add_from_import( "azure.mgmt.core", Client.pipeline_class(code_model, async_mode), ImportType.AZURECORE ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> file_import.add_from_import( "azure.core", Client.pipeline_class(code_model, async_mode), ImportType.AZURECORE ) <NEW_LINE> <DEDENT> if not code_model.sorted_schemas: <NEW_LINE> <INDENT> file_import.add_from_import("typing", "Dict", ImportType.STDLIB, TypingSection.TYPING) <NEW_LINE> <DEDENT> return file_import | A service client.
| 62599038711fe17d825e1561 |
class GatlingWidget(urwid.Pile): <NEW_LINE> <INDENT> def __init__(self, executor): <NEW_LINE> <INDENT> self.executor = executor <NEW_LINE> self.dur = executor.get_load().duration <NEW_LINE> widgets = [] <NEW_LINE> if self.executor.script: <NEW_LINE> <INDENT> self.script_name = urwid.Text("Script: %s" % os.path.basename(self.executor.script)) <NEW_LINE> widgets.append(self.script_name) <NEW_LINE> <DEDENT> if self.dur: <NEW_LINE> <INDENT> self.progress = urwid.ProgressBar('pb-en', 'pb-dis', done=self.dur) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.progress = urwid.Text("Running...") <NEW_LINE> <DEDENT> widgets.append(self.progress) <NEW_LINE> self.elapsed = urwid.Text("Elapsed: N/A") <NEW_LINE> self.eta = urwid.Text("ETA: N/A", align=urwid.RIGHT) <NEW_LINE> widgets.append(urwid.Columns([self.elapsed, self.eta])) <NEW_LINE> super(GatlingWidget, self).__init__(widgets) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> if self.executor.start_time: <NEW_LINE> <INDENT> elapsed = time.time() - self.executor.start_time <NEW_LINE> self.elapsed.set_text("Elapsed: %s" % humanize_time(elapsed)) <NEW_LINE> if self.dur: <NEW_LINE> <INDENT> eta = self.dur - elapsed <NEW_LINE> if eta >= 0: <NEW_LINE> <INDENT> self.eta.set_text("ETA: %s" % humanize_time(eta)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> over = elapsed - self.dur <NEW_LINE> self.eta.set_text("Overtime: %s" % humanize_time(over)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.eta.set_text("") <NEW_LINE> <DEDENT> if isinstance(self.progress, urwid.ProgressBar): <NEW_LINE> <INDENT> self.progress.set_completion(elapsed) <NEW_LINE> <DEDENT> <DEDENT> self._invalidate() | Progress sidebar widget
:type executor: bzt.modules.grinder.GatlingExecutor | 62599038a4f1c619b294f74c |
class TestResponse(requests.Response): <NEW_LINE> <INDENT> def __init__(self, data): <NEW_LINE> <INDENT> self._text = None <NEW_LINE> super(TestResponse, self).__init__() <NEW_LINE> if isinstance(data, dict): <NEW_LINE> <INDENT> self.status_code = data.get('status_code', 200) <NEW_LINE> headers = data.get('headers') <NEW_LINE> if headers: <NEW_LINE> <INDENT> self.headers.update(headers) <NEW_LINE> <DEDENT> self._content = data.get('text') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.status_code = data <NEW_LINE> <DEDENT> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> @property <NEW_LINE> def text(self): <NEW_LINE> <INDENT> return self.content | Utility class to wrap requests.Response.
Class used to wrap requests.Response and provide some convenience to
initialize with a dict. | 62599038d99f1b3c44d06830 |
class PressureReading(AbstractReading): <NEW_LINE> <INDENT> __tablename__ = "pressure_reading" <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> timestamp = Column(DateTime, nullable=False) <NEW_LINE> model = Column(String(250), nullable=False) <NEW_LINE> min_reading = Column(Integer, nullable=False) <NEW_LINE> avg_reading = Column(Integer, nullable=False) <NEW_LINE> max_reading = Column(Integer, nullable=False) <NEW_LINE> status = Column(String(250), nullable=False) <NEW_LINE> def get_timestamp(self, date): <NEW_LINE> <INDENT> reading_display_datetime = datetime.strftime(date, '%Y-%m-%d %H:%M') <NEW_LINE> return reading_display_datetime | Concrete Implementation of a Pressure Reading | 6259903826238365f5fadce0 |
class TestBusinessUnitReference(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testBusinessUnitReference(self): <NEW_LINE> <INDENT> pass | BusinessUnitReference unit test stubs | 62599038b57a9660fecd2c06 |
class Node(object): <NEW_LINE> <INDENT> def __init__(self, is_leaf, parent, *, scope=None, active=None, value=None): <NEW_LINE> <INDENT> self.is_leaf = is_leaf <NEW_LINE> if self.is_leaf: <NEW_LINE> <INDENT> self.value = value <NEW_LINE> self.scope = range(value, value+1) <NEW_LINE> self.active = set() <NEW_LINE> self.active.add(value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.active = active <NEW_LINE> if isinstance(scope, range): <NEW_LINE> <INDENT> self.scope = scope <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.scope = range(*scope) <NEW_LINE> <DEDENT> self.left_child = None <NEW_LINE> self.right_child = None <NEW_LINE> <DEDENT> self.parent = parent <NEW_LINE> <DEDENT> def right_left_most(self, value=True): <NEW_LINE> <INDENT> assert not self.is_leaf <NEW_LINE> if value: <NEW_LINE> <INDENT> return self.right_child.scope.start <NEW_LINE> <DEDENT> curr_node = self.right_child <NEW_LINE> while not curr_node.is_leaf: <NEW_LINE> <INDENT> curr_node = curr_node.left_child <NEW_LINE> <DEDENT> return curr_node | The node of binary tree.
If the node is a leaf, it contains an integer (index) as its value.
If the node is an internal node, it contains a series of contiguous integers. | 6259903876d4e153a661db38 |
class RetrieveUser(APIView): <NEW_LINE> <INDENT> def get(self, request, pk): <NEW_LINE> <INDENT> response = requests.get(USER_BASE_URL+"/"+pk) <NEW_LINE> if response.status_code == 200: <NEW_LINE> <INDENT> return Response(response.json()) <NEW_LINE> <DEDENT> return Response(status=status.HTTP_404_NOT_FOUND) | class to retrieve specified users from JsonPlaceHolder external API
Reference: 'https://jsonplaceholder.typicode.com/users' | 6259903807d97122c4217e28 |
class NutrientDef(models.Model): <NEW_LINE> <INDENT> nutr_id = models.CharField(primary_key=True, max_length=3, db_column='nutr_id') <NEW_LINE> units = models.CharField(max_length=7) <NEW_LINE> tagname = models.CharField(max_length=20, blank=True) <NEW_LINE> nutr_desc = models.CharField(max_length=60, verbose_name="nutrient description") <NEW_LINE> decimal_places = models.CharField(max_length=1) <NEW_LINE> sr_order = models.DecimalField(max_digits=6, decimal_places=0) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.nutr_desc <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> db_table = 'usda_nutrient_def' <NEW_LINE> managed = False <NEW_LINE> verbose_name = 'Nutrient definition' | Definitions of nutrients used in the database.
150 records from the USDA NUTR_DEF table.
See sr27doc page 34 for more info.
(names in parenthesis are USDA names when significantly different)
nutr_id (Nutr_No): Unique 3-digit identifier code for a nutrient.
units: Units of measure (mg, g, μg, and so on).
tagname: International Network of Food Data Systems
(INFOODS) Tagnames.† A unique abbreviation for a
nutrient/food component developed by INFOODS to
aid in the interchange of data.
nutr_desc (NutrDesc): Name of nutrient/food component.
decimal_places (Num_Dec): Number of decimal places to which a nutrient
value is rounded.
sr_order (SR_Order): Used to sort nutrient records in the same order as
various reports produced from SR | 62599038b5575c28eb71358f |
class SVC(ProbabilityClassifier): <NEW_LINE> <INDENT> Estimator = svm.SVC <NEW_LINE> BASE_PARAMS = {'probability': True} | Implements a Support Vector Classifier model. | 625990388a43f66fc4bf3318 |
@attr.s(auto_attribs=True, init=False) <NEW_LINE> class GitStatus(model.Model): <NEW_LINE> <INDENT> action: Optional[str] = None <NEW_LINE> conflict: Optional[bool] = None <NEW_LINE> revertable: Optional[bool] = None <NEW_LINE> text: Optional[str] = None <NEW_LINE> def __init__( self, *, action: Optional[str] = None, conflict: Optional[bool] = None, revertable: Optional[bool] = None, text: Optional[str] = None ): <NEW_LINE> <INDENT> self.action = action <NEW_LINE> self.conflict = conflict <NEW_LINE> self.revertable = revertable <NEW_LINE> self.text = text | Attributes:
action: Git action: add, delete, etc
conflict: When true, changes to the local file conflict with the remote repository
revertable: When true, the file can be reverted to an earlier state
text: Git description of the action | 6259903891af0d3eaad3afbe |
class BufferVar(NodeGeneric): <NEW_LINE> <INDENT> def __init__(self, builder, buffer_var, content_type): <NEW_LINE> <INDENT> self._builder = builder <NEW_LINE> self._buffer_var = buffer_var <NEW_LINE> self._content_type = content_type <NEW_LINE> <DEDENT> def asnode(self): <NEW_LINE> <INDENT> return self._buffer_var <NEW_LINE> <DEDENT> @property <NEW_LINE> def dtype(self): <NEW_LINE> <INDENT> return self._content_type <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> t = TVMType(self._content_type) <NEW_LINE> if t.lanes > 1: <NEW_LINE> <INDENT> index = _make.Ramp(index * t.lanes, 1, t.lanes) <NEW_LINE> <DEDENT> return _make.Load(self._content_type, self._buffer_var, index) <NEW_LINE> <DEDENT> def __setitem__(self, index, value): <NEW_LINE> <INDENT> value = _api.convert(value) <NEW_LINE> if value.dtype != self._content_type: <NEW_LINE> <INDENT> raise ValueError( "data type does not match content type %s vs %s" % ( value.dtype, self._content_type)) <NEW_LINE> <DEDENT> t = TVMType(self._content_type) <NEW_LINE> if t.lanes > 1: <NEW_LINE> <INDENT> index = _make.Ramp(index * t.lanes, 1, t.lanes) <NEW_LINE> <DEDENT> self._builder.emit(_make.Store(self._buffer_var, value, index)) | Buffer variable with content type, makes load store easily.
Do not create it directly, create use IRBuilder.
Examples
--------
In the follow example, x is BufferVar.
:code:`x[0] = ...` directly emit a store to the IRBuilder,
:code:`x[10]` translates to Load.
.. code-block:: python
# The following code generate IR for x[0] = x[
ib = tvm.ir_builder.create()
x = ib.pointer("float32")
x[0] = x[10] + 1
See Also
--------
IRBuilder.pointer
IRBuilder.buffer_ptr
IRBuilder.allocate | 625990386e29344779b017dd |
@deconstructible <NEW_LINE> class UploadToPathAndRename(object): <NEW_LINE> <INDENT> def __init__(self, path): <NEW_LINE> <INDENT> self.sub_path = path <NEW_LINE> <DEDENT> def __call__(self, instance, filename): <NEW_LINE> <INDENT> ext = filename.split('.')[-1] <NEW_LINE> if instance.pk: <NEW_LINE> <INDENT> if isinstance(instance.pk, uuid.UUID): <NEW_LINE> <INDENT> filename = '{}.{}'.format(instance.pk, ext) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError("UploadToPathAndRename should only be called " "for objects with UUID primary keys.") <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> filename = '{}.{}'.format(uuid.uuid4().hex, ext) <NEW_LINE> <DEDENT> return os.path.join(self.sub_path, filename) | Helper class for renaming files to a uuid on upload.
For user-supplied files, file names should be obfuscated by using this
class for the upload_to parameter. This will match the primary key of the
parent object if it exists, or generate a new uuid if it does not. | 62599038287bf620b6272d76 |
class AbstractPostgresIndexEntry(BaseIndexEntry): <NEW_LINE> <INDENT> autocomplete = SearchVectorField() <NEW_LINE> title = SearchVectorField() <NEW_LINE> body = SearchVectorField() <NEW_LINE> class Meta(BaseIndexEntry.Meta): <NEW_LINE> <INDENT> abstract = True <NEW_LINE> indexes = [ GinIndex(fields=["autocomplete"]), GinIndex(fields=["title"]), GinIndex(fields=["body"]), ] | This class is the specific IndexEntry model for PostgreSQL database systems.
It inherits the fields defined in BaseIndexEntry, and adds PostgreSQL-specific
fields (tsvectors), plus indexes for doing full-text search on those fields. | 6259903816aa5153ce401678 |
class CategoriesResultExplanation(): <NEW_LINE> <INDENT> def __init__(self, *, relevant_text: List['CategoriesRelevantText'] = None) -> None: <NEW_LINE> <INDENT> self.relevant_text = relevant_text <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dict(cls, _dict: Dict) -> 'CategoriesResultExplanation': <NEW_LINE> <INDENT> args = {} <NEW_LINE> if 'relevant_text' in _dict: <NEW_LINE> <INDENT> args['relevant_text'] = [ CategoriesRelevantText.from_dict(x) for x in _dict.get('relevant_text') ] <NEW_LINE> <DEDENT> return cls(**args) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _from_dict(cls, _dict): <NEW_LINE> <INDENT> return cls.from_dict(_dict) <NEW_LINE> <DEDENT> def to_dict(self) -> Dict: <NEW_LINE> <INDENT> _dict = {} <NEW_LINE> if hasattr(self, 'relevant_text') and self.relevant_text is not None: <NEW_LINE> <INDENT> _dict['relevant_text'] = [x.to_dict() for x in self.relevant_text] <NEW_LINE> <DEDENT> return _dict <NEW_LINE> <DEDENT> def _to_dict(self): <NEW_LINE> <INDENT> return self.to_dict() <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return json.dumps(self.to_dict(), indent=2) <NEW_LINE> <DEDENT> def __eq__(self, other: 'CategoriesResultExplanation') -> bool: <NEW_LINE> <INDENT> if not isinstance(other, self.__class__): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other: 'CategoriesResultExplanation') -> bool: <NEW_LINE> <INDENT> return not self == other | Information that helps to explain what contributed to the categories result.
:attr List[CategoriesRelevantText] relevant_text: (optional) An array of
relevant text from the source that contributed to the categorization. The sorted
array begins with the phrase that contributed most significantly to the result,
followed by phrases that were less and less impactful. | 62599038d10714528d69ef51 |
class DataReadException(Exception): <NEW_LINE> <INDENT> def __init__(self, message): <NEW_LINE> <INDENT> Exception.__init__(self, message) | An exception that indicates that there was an error reading from the underlying medium
| 62599038ac7a0e7691f73674 |
class WurfdocsError(Exception): <NEW_LINE> <INDENT> pass | Basic exception for errors raised by Wurfdocs | 6259903873bcbd0ca4bcb415 |
class ProjectExplore(generic.ListView): <NEW_LINE> <INDENT> model = Project <NEW_LINE> def project_explore(request): <NEW_LINE> <INDENT> categories = CategoryM.objects.all() <NEW_LINE> ExCategories = [] <NEW_LINE> idbuf = 0 <NEW_LINE> Occupied = [] <NEW_LINE> MaxHorizontal = 6 <NEW_LINE> MaxVertical = 2 <NEW_LINE> MaxDisplay = MaxHorizontal*MaxVertical <NEW_LINE> MaxDiameter = 160 <NEW_LINE> CatLen = len(categories) <NEW_LINE> categories = paginate_queryset(request, categories, MaxDisplay) <NEW_LINE> for category in categories: <NEW_LINE> <INDENT> for i in range(MaxDisplay): <NEW_LINE> <INDENT> radiusbuf = random.uniform(40, 80) <NEW_LINE> leftbuf = random.uniform(0, MaxDiameter*MaxHorizontal) <NEW_LINE> topbuf = random.uniform(100, 100+MaxDiameter*MaxVertical) <NEW_LINE> leftint = math.floor(leftbuf/MaxDiameter) <NEW_LINE> topint = math.floor((topbuf-100)/MaxDiameter) <NEW_LINE> posbuf = { 'left':leftint, 'top':topint, } <NEW_LINE> if posbuf in Occupied: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> Occupied.append(posbuf) <NEW_LINE> leftbuf = leftint*160 + random.uniform(radiusbuf, MaxDiameter-radiusbuf) <NEW_LINE> topbuf = topint*160 + 100 + random.uniform(radiusbuf, MaxDiameter-radiusbuf) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> ExCategories.append({"name":category.name, "left":leftbuf, "top":topbuf, "radius":radiusbuf, "id":idbuf }) <NEW_LINE> idbuf = idbuf + 1 <NEW_LINE> <DEDENT> context = { 'categories':ExCategories, 'search_form':ProjectSearchForm() } <NEW_LINE> return render(request, 'project_explore.html', context) | Explore Projects | 625990380a366e3fb87ddb72 |
class BasicDistance(sim.Allocation): <NEW_LINE> <INDENT> initial_x = sim.Normal("initial x coordinate", loc=0, scale=1) <NEW_LINE> initial_y = sim.Normal("initial y coordinate", loc=0, scale=1) <NEW_LINE> initial_energy = sim.Exponential("Initial energy of individuals", scale=1000) <NEW_LINE> step_x = sim.Continuous("step in x direction", -.1, .1) <NEW_LINE> step_y = sim.Continuous("step in y direction", -.1, .1) | Distance parameters for a random walk model. | 6259903871ff763f4b5e8926 |
class Mission(object): <NEW_LINE> <INDENT> theatre = "Caucasus" <NEW_LINE> descriptionText = "" <NEW_LINE> descriptionBlueTask = "" <NEW_LINE> descriptionRedTask = "" <NEW_LINE> sortie = "" <NEW_LINE> version = 0 <NEW_LINE> currentKey = 0 <NEW_LINE> startTime = 0 <NEW_LINE> usedModules = [] <NEW_LINE> resourceCounter = [] <NEW_LINE> needModules = [] <NEW_LINE> pictureFileNameR = [] <NEW_LINE> pictureFileNameB = [] <NEW_LINE> trig = Trig() <NEW_LINE> result = Result() <NEW_LINE> groundControl = GroundControl() <NEW_LINE> weather = Weather() <NEW_LINE> missionMap = {'centerX' : 0.0, 'centerY' : 0.0, 'zoom' : 0} <NEW_LINE> coalitions = {'red' : [], 'blue' : []} <NEW_LINE> def __init__(self, arg): <NEW_LINE> <INDENT> super(Mission, self).__init__() <NEW_LINE> self.arg = arg | docstring for Mission | 62599038507cdc57c63a5f26 |
class CreateContainer(show.ShowOne): <NEW_LINE> <INDENT> def get_parser(self, prog_name): <NEW_LINE> <INDENT> parser = super(CreateContainer, self).get_parser(prog_name) <NEW_LINE> parser.add_argument('--name', '-n', help='a human-friendly name.') <NEW_LINE> parser.add_argument('--type', default='generic', help='type of container to create (default: ' '%(default)s).') <NEW_LINE> parser.add_argument('--secret', '-s', action='append', help='one secret to store in a container ' '(can be set multiple times). Example: ' '--secret "private_key=' 'https://url.test/v1/secrets/1-2-3-4"') <NEW_LINE> return parser <NEW_LINE> <DEDENT> def take_action(self, args): <NEW_LINE> <INDENT> container_type = self.app.client.containers._container_map.get( args.type) <NEW_LINE> if not container_type: <NEW_LINE> <INDENT> raise ValueError('Invalid container type specified.') <NEW_LINE> <DEDENT> secret_refs = CreateContainer._parse_secrets(args.secret) <NEW_LINE> if container_type is RSAContainer: <NEW_LINE> <INDENT> public_key_ref = secret_refs.get('public_key') <NEW_LINE> private_key_ref = secret_refs.get('private_key') <NEW_LINE> private_key_pass_ref = secret_refs.get('private_key_passphrase') <NEW_LINE> entity = RSAContainer( api=self.app.client.containers._api, name=args.name, public_key_ref=public_key_ref, private_key_ref=private_key_ref, private_key_passphrase_ref=private_key_pass_ref, ) <NEW_LINE> <DEDENT> elif container_type is CertificateContainer: <NEW_LINE> <INDENT> certificate_ref = secret_refs.get('certificate') <NEW_LINE> intermediates_ref = secret_refs.get('intermediates') <NEW_LINE> private_key_ref = secret_refs.get('private_key') <NEW_LINE> private_key_pass_ref = secret_refs.get('private_key_passphrase') <NEW_LINE> entity = CertificateContainer( api=self.app.client.containers._api, name=args.name, certificate_ref=certificate_ref, intermediates_ref=intermediates_ref, private_key_ref=private_key_ref, private_key_passphrase_ref=private_key_pass_ref, ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> entity = container_type(api=self.app.client.containers._api, name=args.name, secret_refs=secret_refs) <NEW_LINE> <DEDENT> entity.store() <NEW_LINE> return entity._get_formatted_entity() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _parse_secrets(secrets): <NEW_LINE> <INDENT> if not secrets: <NEW_LINE> <INDENT> raise ValueError("Must supply at least one secret.") <NEW_LINE> <DEDENT> return dict( (s.split('=')[0], s.split('=')[1]) for s in secrets if s.count('=') is 1 ) | Store a container in Barbican. | 6259903810dbd63aa1c71d61 |
class TemplateViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = models.Template.objects.all() <NEW_LINE> serializer_class = serializers.TemplateSerializer | This viewset automatically provides `list` and `detail` actions. | 6259903830dc7b76659a09bf |
class ObjectType(colander.Mapping): <NEW_LINE> <INDENT> def serialize(self, node, appstruct): <NEW_LINE> <INDENT> appstruct = appstruct.__dict__ <NEW_LINE> return super(ObjectType, self).serialize(node, appstruct) <NEW_LINE> <DEDENT> def deserialize(self, node, cstruct): <NEW_LINE> <INDENT> data = super(ObjectType, self).deserialize(node, cstruct) <NEW_LINE> appstruct = node.instance.__class__() <NEW_LINE> appstruct.__dict__.update(data) <NEW_LINE> return appstruct | A colander type representing a generic python object
(uses colander mapping-based serialization). | 62599038d99f1b3c44d06832 |
class Car: <NEW_LINE> <INDENT> def __init__(self, fuel=0, name=""): <NEW_LINE> <INDENT> self.fuel = fuel <NEW_LINE> self.odometer = 0 <NEW_LINE> self.name = name <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "{}, fuel={}, odometer={}".format(self.name, self.fuel, self.odometer) <NEW_LINE> <DEDENT> def add_fuel(self, amount): <NEW_LINE> <INDENT> self.fuel += amount <NEW_LINE> <DEDENT> def drive(self, distance): <NEW_LINE> <INDENT> if distance > self.fuel: <NEW_LINE> <INDENT> distance = self.fuel <NEW_LINE> self.fuel = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.fuel -= distance <NEW_LINE> <DEDENT> self.odometer += distance <NEW_LINE> return distance | Represent a Car object. | 6259903826238365f5fadce2 |
class DescribeEnvironmentsRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.EnvironmentId = None <NEW_LINE> self.Offset = None <NEW_LINE> self.Limit = None <NEW_LINE> self.ClusterId = None <NEW_LINE> self.Filters = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.EnvironmentId = params.get("EnvironmentId") <NEW_LINE> self.Offset = params.get("Offset") <NEW_LINE> self.Limit = params.get("Limit") <NEW_LINE> self.ClusterId = params.get("ClusterId") <NEW_LINE> if params.get("Filters") is not None: <NEW_LINE> <INDENT> self.Filters = [] <NEW_LINE> for item in params.get("Filters"): <NEW_LINE> <INDENT> obj = Filter() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.Filters.append(obj) <NEW_LINE> <DEDENT> <DEDENT> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set)) | DescribeEnvironments请求参数结构体
| 6259903876d4e153a661db39 |
class Reaction(object): <NEW_LINE> <INDENT> def __init__(self, reactants, products=None, reactant_value=0, product_value=0): <NEW_LINE> <INDENT> if not isinstance(reactants, list) or (products is not None and not isinstance(products, list)): <NEW_LINE> <INDENT> raise TypeError <NEW_LINE> <DEDENT> if len(reactants) == 0: <NEW_LINE> <INDENT> raise ValueError <NEW_LINE> <DEDENT> self.reactants = reactants <NEW_LINE> self.products = products <NEW_LINE> self.reactant_value = reactant_value <NEW_LINE> self.product_value = product_value <NEW_LINE> <DEDENT> def get_reactants(self): <NEW_LINE> <INDENT> return self.reactants <NEW_LINE> <DEDENT> def get_products(self): <NEW_LINE> <INDENT> return self.products <NEW_LINE> <DEDENT> def get_reactant_value(self): <NEW_LINE> <INDENT> return self.reactant_value <NEW_LINE> <DEDENT> def get_product_value(self): <NEW_LINE> <INDENT> return self.product_value <NEW_LINE> <DEDENT> def as_dict(self): <NEW_LINE> <INDENT> return {'reactants': {x.get_id(): x.get_symbol() for x in self.reactants}, 'products': {x.get_id(): x.get_symbol() for x in self.products}, 'reactant_value': self.reactant_value, 'product_value': self.product_value} <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.as_dict()) | Reactions record a transformation from initial reactant Molecules to the resulting product Molecules.
Associated with the transformation is a 'weight', whose meaning is specific to the IChemistry which generated the Reaction. | 62599038b5575c28eb713590 |
class Entry(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.key = None <NEW_LINE> self.value = None <NEW_LINE> self.hash = 0 <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<Entry: key={0} value={1}>".format(self.key, self.value) | A hash table entry.
Attributes:
* key - The key for this entry.
* hash - The has of the key.
* value - The value associated with the key. | 625990388a43f66fc4bf331a |
class Error: <NEW_LINE> <INDENT> def __init__(self, error_code): <NEW_LINE> <INDENT> self.error_code = error_code <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self.error_code == ARDUINO_NOT_FOUND: <NEW_LINE> <INDENT> return 'The Arduino cannot be found. Make sure it is plugged in.' <NEW_LINE> <DEDENT> elif self.error_code == SYNTAX: <NEW_LINE> <INDENT> return 'There was a syntax error in your program.' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'Unknown error.' | Signifies a load error. | 6259903863f4b57ef008663a |
class _FileReader(_UnicodeReader): <NEW_LINE> <INDENT> def __init__(self, process, file, bufsize, datatype, encoding): <NEW_LINE> <INDENT> super().__init__(encoding) <NEW_LINE> self._process = process <NEW_LINE> self._file = file <NEW_LINE> self._bufsize = bufsize <NEW_LINE> self._datatype = datatype <NEW_LINE> self._paused = False <NEW_LINE> <DEDENT> def feed(self): <NEW_LINE> <INDENT> while not self._paused: <NEW_LINE> <INDENT> data = self._file.read(self._bufsize) <NEW_LINE> if data: <NEW_LINE> <INDENT> self._process.feed_data(self.decode(data), self._datatype) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.check_partial() <NEW_LINE> self._process.feed_eof(self._datatype) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def pause_reading(self): <NEW_LINE> <INDENT> self._paused = True <NEW_LINE> <DEDENT> def resume_reading(self): <NEW_LINE> <INDENT> self._paused = False <NEW_LINE> self.feed() <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self._file.close() | Forward data from a file | 62599038d4950a0f3b111706 |
@register.tag('form') <NEW_LINE> class FormNode(Node): <NEW_LINE> <INDENT> def __init__(self, parser, token): <NEW_LINE> <INDENT> bits = token.split_contents() <NEW_LINE> remaining_bits = bits[1:] <NEW_LINE> self.kwargs = token_kwargs(remaining_bits, parser) <NEW_LINE> if remaining_bits: <NEW_LINE> <INDENT> raise TemplateSyntaxError("%r received an invalid token: %r" % (bits[0], remaining_bits[0])) <NEW_LINE> <DEDENT> for key in self.kwargs: <NEW_LINE> <INDENT> if key not in ('form', 'layout', 'template'): <NEW_LINE> <INDENT> raise TemplateSyntaxError("%r received an invalid key: %r" % (bits[0], key)) <NEW_LINE> <DEDENT> self.kwargs[key] = self.kwargs[key] <NEW_LINE> <DEDENT> self.nodelist = parser.parse(('end{}'.format(bits[0]),)) <NEW_LINE> parser.delete_first_token() <NEW_LINE> <DEDENT> def render(self, context): <NEW_LINE> <INDENT> form = self.kwargs.get('form') <NEW_LINE> form = form.resolve(context) if form else context.get('form') <NEW_LINE> if form is None: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> layout = self.kwargs.get('layout') <NEW_LINE> if layout is not None: <NEW_LINE> <INDENT> layout = layout.resolve(context) <NEW_LINE> <DEDENT> if layout is None: <NEW_LINE> <INDENT> if 'view' in context: <NEW_LINE> <INDENT> view = context['view'] <NEW_LINE> if hasattr(view, 'layout'): <NEW_LINE> <INDENT> layout = view.layout <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if layout is None: <NEW_LINE> <INDENT> if hasattr(form, 'layout'): <NEW_LINE> <INDENT> layout = form.layout <NEW_LINE> <DEDENT> <DEDENT> template_name = self.kwargs.get('template', 'material/form.html') <NEW_LINE> template = get_template(template_name) <NEW_LINE> parts = defaultdict(dict) <NEW_LINE> with context.push( form=form, layout=layout, form_template_pack=os.path.dirname(template_name), form_parts=parts): <NEW_LINE> <INDENT> children = (node for node in self.nodelist if isinstance(node, FormPartNode)) <NEW_LINE> _render_parts(context, children) <NEW_LINE> children = (node for node in self.nodelist if isinstance(node, IncludeNode)) <NEW_LINE> for included_list in children: <NEW_LINE> <INDENT> included = included_list.template.resolve(context) <NEW_LINE> children = (node for node in included.nodelist if isinstance(node, FormPartNode)) <NEW_LINE> _render_parts(context, children) <NEW_LINE> <DEDENT> return template.render(context) | Template based form rendering
Example::
{% form template='material/form.html' form=form layout=view.layout %}
{% part form.email prepend %}<span class="input-group-addon" id="basic-addon1">@</span>{% endpart %}
{% endform %} | 625990385e10d32532ce41ca |
class spacetime: <NEW_LINE> <INDENT> def __init__(self, z_positions, masses, reflection_symmetric=False): <NEW_LINE> <INDENT> self.reflection_symmetric = reflection_symmetric <NEW_LINE> self.z_positions = np.array(z_positions) <NEW_LINE> self.masses = np.array(masses) <NEW_LINE> self.N = len(z_positions) | Define an axisymmetric spacetime.
For an axisymmetric, vacuum spacetime with Brill-Lindquist singularities
the only parameters that matter is the locations of the singularities
(i.e. their z-location) and their bare masses.
Parameters
----------
z_positions : list of float
The location of the singularities on the z-axis.
masses : list of float
The bare masses of the singularities.
reflection_symmetry : bool, optional
Is the spacetime symmetric across the x-axis.
See also
--------
trappedsurface : class defining the trapped surfaces on a spacetime.
Examples
--------
>>> schwarzschild = spacetime([0.0], [1.0], True)
This defines standard Schwarzschild spacetime with unit mass.
>>> binary = spacetime([-0.75, 0.75], [1.0, 1.1])
This defines two black holes, with the locations mirrored but different
masses. | 625990388e05c05ec3f6f722 |
class ProductionConfig(Config): <NEW_LINE> <INDENT> DEBUG = False <NEW_LINE> LOG_LEVEL = "INFO" <NEW_LINE> SQLALCHEMY_DATABASE_URI = "mysql://root:[email protected]:3306/company_info?charset=utf8" | 生产模式下的配置 | 6259903807d97122c4217e2b |
class Cache(object): <NEW_LINE> <INDENT> def __init__(self, root_dir, reporthook=None): <NEW_LINE> <INDENT> self.root_dir = root_dir <NEW_LINE> self.reporthook = reporthook <NEW_LINE> if not os.path.isdir(root_dir): <NEW_LINE> <INDENT> os.mkdir(root_dir) <NEW_LINE> <DEDENT> <DEDENT> def fetch_url(self, source_url, filename, force=False): <NEW_LINE> <INDENT> target_file = self.local_path(filename) <NEW_LINE> if not os.path.isfile(target_file) or force: <NEW_LINE> <INDENT> target_dir = os.path.dirname(target_file) <NEW_LINE> if not os.path.exists(target_dir): <NEW_LINE> <INDENT> os.makedirs(target_dir) <NEW_LINE> <DEDENT> (downloaded_filename, headers) = _urlopener.retrieve(source_url, target_file, reporthook=self.reporthook) <NEW_LINE> <DEDENT> return os.path.abspath(target_file) <NEW_LINE> <DEDENT> def has_file(self, filename): <NEW_LINE> <INDENT> return os.path.exists(os.path.join(self.root_dir, filename)) <NEW_LINE> <DEDENT> def local_path(self, filename): <NEW_LINE> <INDENT> return os.path.join(self.root_dir, filename) <NEW_LINE> <DEDENT> def json_dump(self, obj, filename): <NEW_LINE> <INDENT> target_file = os.path.join(self.root_dir, filename) <NEW_LINE> target_dir = os.path.dirname(target_file) <NEW_LINE> if not os.path.exists(target_dir): <NEW_LINE> <INDENT> os.mkdirs(target_dir) <NEW_LINE> <DEDENT> with open(target_file, 'wb') as f: <NEW_LINE> <INDENT> json.dump(obj, f) <NEW_LINE> <DEDENT> <DEDENT> def json_load(self, filename): <NEW_LINE> <INDENT> with open(os.path.join(self.root_dir, filename), 'rb') as f: <NEW_LINE> <INDENT> return json.load(f) <NEW_LINE> <DEDENT> <DEDENT> def erase(self, filename): <NEW_LINE> <INDENT> os.unlink(os.path.join(self.root_dir, filename)) | A simple disk-based URL cache. Note that it is *not* safe for any kind of multithreading or multiprocessing (i.e. you should not use several instances with the same ``root_dir`` in parallel, as no locking of files is done to ensure correct operation). | 6259903871ff763f4b5e8928 |
class IncidentsSensor(RestoreEntity, SensorEntity): <NEW_LINE> <INDENT> def __init__(self, client): <NEW_LINE> <INDENT> self._client = client <NEW_LINE> self._entry_id = self._client.entry_id <NEW_LINE> self._unique_id = f"{self._client.unique_id}_Incidents" <NEW_LINE> self._state = None <NEW_LINE> self._state_attributes = {} <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self) -> str: <NEW_LINE> <INDENT> return "Incidents" <NEW_LINE> <DEDENT> @property <NEW_LINE> def icon(self) -> str: <NEW_LINE> <INDENT> if ( "prio" in self._state_attributes and self._state_attributes["prio"][0] == "a" ): <NEW_LINE> <INDENT> return "mdi:ambulance" <NEW_LINE> <DEDENT> return "mdi:fire-truck" <NEW_LINE> <DEDENT> @property <NEW_LINE> def native_value(self) -> str: <NEW_LINE> <INDENT> return self._state <NEW_LINE> <DEDENT> @property <NEW_LINE> def unique_id(self) -> str: <NEW_LINE> <INDENT> return self._unique_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def should_poll(self) -> bool: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> @property <NEW_LINE> def extra_state_attributes(self) -> object: <NEW_LINE> <INDENT> attr = {} <NEW_LINE> data = self._state_attributes <NEW_LINE> if not data: <NEW_LINE> <INDENT> return attr <NEW_LINE> <DEDENT> for value in ( "id", "trigger", "created_at", "message_to_speech_url", "prio", "type", "responder_mode", "can_respond_until", ): <NEW_LINE> <INDENT> if data.get(value): <NEW_LINE> <INDENT> attr[value] = data[value] <NEW_LINE> <DEDENT> if "address" not in data: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for address_value in ( "latitude", "longitude", "address_type", "formatted_address", ): <NEW_LINE> <INDENT> if address_value in data["address"]: <NEW_LINE> <INDENT> attr[address_value] = data["address"][address_value] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return attr <NEW_LINE> <DEDENT> async def async_added_to_hass(self) -> None: <NEW_LINE> <INDENT> await super().async_added_to_hass() <NEW_LINE> state = await self.async_get_last_state() <NEW_LINE> if state: <NEW_LINE> <INDENT> self._state = state.state <NEW_LINE> self._state_attributes = state.attributes <NEW_LINE> if "id" in self._state_attributes: <NEW_LINE> <INDENT> self._client.incident_id = self._state_attributes["id"] <NEW_LINE> <DEDENT> _LOGGER.debug("Restored entity 'Incidents' to: %s", self._state) <NEW_LINE> <DEDENT> self.async_on_remove( async_dispatcher_connect( self.hass, f"{FIRESERVICEROTA_DOMAIN}_{self._entry_id}_update", self.client_update, ) ) <NEW_LINE> <DEDENT> @callback <NEW_LINE> def client_update(self) -> None: <NEW_LINE> <INDENT> data = self._client.websocket.incident_data <NEW_LINE> if not data or "body" not in data: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._state = data["body"] <NEW_LINE> self._state_attributes = data <NEW_LINE> if "id" in self._state_attributes: <NEW_LINE> <INDENT> self._client.incident_id = self._state_attributes["id"] <NEW_LINE> <DEDENT> self.async_write_ha_state() | Representation of FireServiceRota incidents sensor. | 62599038b830903b9686ed40 |
class BootstrapPortal(BootstrapCommon): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(BootstrapPortal, self).__init__('portal') <NEW_LINE> self.params = PortalParams() <NEW_LINE> <DEDENT> def _bootstrap_complete(self): <NEW_LINE> <INDENT> BOOTSTRAP.FEEDBACK.block([ 'Finished bootstrapping Lense API portal!\n', 'You should restart your Apache service to load the new virtual host', 'configuration. You can connect to the Lense API portal using the', 'administrator credentials generated during the engine bootstrap process', 'at the following URL:\n', 'http://{0}:{1}'.format(self.params.input.response.get('portal_host'), self.params.input.response.get('portal_port')) ], 'COMPLETE') <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.read_input(BOOTSTRAP.ANSWERS.get('portal', {})) <NEW_LINE> self.update_config() <NEW_LINE> self.deploy_apache() <NEW_LINE> self.set_permissions(self.CONFIG.portal.log, owner='www-data:www-data') <NEW_LINE> self.group_add_user('www-data') <NEW_LINE> self._bootstrap_complete() | Class object for handling bootstrap of the Lense API portal. | 62599038711fe17d825e1563 |
class NSNitroNserrSslBundleMaxCert(NSNitroSsl2Errors): <NEW_LINE> <INDENT> pass | Nitro error code 3665
Exceeded maximum Intermediate certificates limit of 9. | 6259903830dc7b76659a09c1 |
class TaperedGrMFD(object): <NEW_LINE> <INDENT> def __init__(self, mo_t, mo_corner, b_gr): <NEW_LINE> <INDENT> self.mo_t = mo_t <NEW_LINE> self.mo_corner = mo_corner <NEW_LINE> self.b_gr = b_gr <NEW_LINE> <DEDENT> def get_ccdf(self, mo): <NEW_LINE> <INDENT> beta = 2./3.*self.b_gr <NEW_LINE> ratio = self.mo_t / mo <NEW_LINE> phi = ratio**beta * np.exp((self.mo_t-mo) / self.mo_corner) <NEW_LINE> return phi | Implements the Tapered G-R (Pareto) MFD as described by Kagan (2002) GJI
page 523.
:parameter mo_t:
:parameter mo_corner:
:parameter b_gr: | 6259903896565a6dacd2d853 |
class MAONPCSkeletonPatcher(_ASkeletonTweak): <NEW_LINE> <INDENT> tweak_name = _(u"Mayu's Animation Overhaul Skeleton Tweaker") <NEW_LINE> tweak_tip = _(u'Changes all (modded and vanilla) NPCs to use the MAO ' u'skeletons. Not compatible with VORB. Note: ONLY use if ' u'you have MAO installed.') <NEW_LINE> tweak_key = u'MAO Skeleton' <NEW_LINE> tweak_log_header = _(u'MAO Skeleton Setter') <NEW_LINE> tweak_order = 11 <NEW_LINE> _sheo_skeleton = u'characters\\_male\\skeletonsesheogorath.nif' <NEW_LINE> _sheo_skeleton_mao = (u"Mayu's Projects[M]\\Animation Overhaul\\Vanilla\\" u'SkeletonSESheogorath.nif') <NEW_LINE> _skeleton_mao = (u"Mayu's Projects[M]\\Animation Overhaul\\Vanilla\\" u'SkeletonBeast.nif') <NEW_LINE> def _get_target_skeleton(self, record): <NEW_LINE> <INDENT> return (self._sheo_skeleton_mao if self._get_skeleton_path(record) in ( self._sheo_skeleton, self._sheo_skeleton_mao) else self._skeleton_mao) | Changes all NPCs to use the right Mayu's Animation Overhaul Skeleton
for use with MAO. | 62599038d99f1b3c44d06834 |
class yellow(ColorGroup): <NEW_LINE> <INDENT> _colors = ('Yellow', 'LightYellow', 'LemonChiffon', 'LightGoldenrodYellow', 'PapayaWhip', 'Moccasin', 'PeachPuff', 'PaleGoldenrod', 'Khaki', 'DarkKhaki', 'Gold') | CSS "Yellow" Color Group as defined by https://www.w3schools.com/colors/colors_groups.asp
{colors} | 625990384e696a045264e6e9 |
class Solution: <NEW_LINE> <INDENT> def subdomainVisits(self, cpdomains): <NEW_LINE> <INDENT> if not cpdomains: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> res = {} <NEW_LINE> for c in cpdomains: <NEW_LINE> <INDENT> l = c.split(" ") <NEW_LINE> count, names = int(l[0]), l[1].split('.') <NEW_LINE> for i in range(len(names)): <NEW_LINE> <INDENT> key = '.'.join(names[i:]) <NEW_LINE> if key not in res: <NEW_LINE> <INDENT> res[key] = count <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> res[key] += count <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> output = [] <NEW_LINE> for key in res: <NEW_LINE> <INDENT> output.append(str(res[key])+' ' +key) <NEW_LINE> <DEDENT> return output | @param cpdomains: a list cpdomains of count-paired domains
@return: a list of count-paired domains | 62599038be383301e02549a6 |
class UserView(View): <NEW_LINE> <INDENT> def __init__(self, request): <NEW_LINE> <INDENT> template = '%(path)s/user.pt' % {'path': View.path['templates']} <NEW_LINE> super(UserView, self).__init__(request = request, template = template, actions = { 'login_user': self.login_user, 'logout_user': self.logout_user, 'activate_user': self.activate_user }) <NEW_LINE> self.title = self.localizer.translate('User', 'fora') <NEW_LINE> self.value['identity'] = request.matchdict['identity'] <NEW_LINE> <DEDENT> def prepare_template(self): <NEW_LINE> <INDENT> user = User.get_user_by_identity(self.value['identity']) <NEW_LINE> if user.is_guest(): <NEW_LINE> <INDENT> self.exception = HTTPNotFound() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.title = self.localizer.translate('User ${user_username}', domain = 'fora', mapping = {'user_username': user.username()}) <NEW_LINE> self.value['user'] = { 'uuid': user.uuid(), 'username': user.username(), 'email_address': user.email_address() } <NEW_LINE> <DEDENT> super(UserView, self).prepare_template() <NEW_LINE> <DEDENT> def login_user(self): <NEW_LINE> <INDENT> value = { 'status': False } <NEW_LINE> user = User.get_user_by_identity(self.json['identity']) <NEW_LINE> if not user.is_guest(): <NEW_LINE> <INDENT> if user.password() == self.json['password']: <NEW_LINE> <INDENT> self.session['user'] = user.uuid() <NEW_LINE> self.session.changed() <NEW_LINE> value['status'] = True <NEW_LINE> <DEDENT> <DEDENT> self.response = render_to_response(renderer_name = 'json', value = value, request = self.request) <NEW_LINE> <DEDENT> def logout_user(self): <NEW_LINE> <INDENT> self.session['user'] = None <NEW_LINE> self.session.invalidate() <NEW_LINE> value = { 'status': True } <NEW_LINE> self.response = render_to_response(renderer_name = 'json', value = value, request = self.request) <NEW_LINE> <DEDENT> def activate_user(self): <NEW_LINE> <INDENT> value = { 'status': True } <NEW_LINE> self.response = render_to_response(renderer_name = 'json', value = value, request = self.request) | This class contains the user view of fora.
| 62599038287bf620b6272d79 |
class ProxyServer(tornado.tcpserver.TCPServer): <NEW_LINE> <INDENT> def __init__(self, target_server,target_port, client_ssl_options=None,server_ssl_options=None, session_factory=maproxy.session.SessionFactory(), *args,**kwargs): <NEW_LINE> <INDENT> assert(session_factory , issubclass(session_factory.__class__,maproxy.session.SessionFactory)) <NEW_LINE> self.session_factory=session_factory <NEW_LINE> self.target_server=target_server <NEW_LINE> self.target_port=target_port <NEW_LINE> self.client_ssl_options=client_ssl_options <NEW_LINE> self.server_ssl_options=server_ssl_options <NEW_LINE> if self.server_ssl_options is True: <NEW_LINE> <INDENT> self.server_ssl_options={} <NEW_LINE> <DEDENT> if self.server_ssl_options is False: <NEW_LINE> <INDENT> self.server_ssl_options=None <NEW_LINE> <DEDENT> if self.client_ssl_options is False: <NEW_LINE> <INDENT> self.client_ssl_options=None <NEW_LINE> <DEDENT> self.SessionsList=[] <NEW_LINE> super(ProxyServer,self).__init__(ssl_options=self.client_ssl_options,*args,**kwargs) <NEW_LINE> <DEDENT> def handle_stream(self, stream, address): <NEW_LINE> <INDENT> assert isinstance(stream,tornado.iostream.IOStream) <NEW_LINE> session=self.session_factory.new() <NEW_LINE> session.new_connection(stream,address,self) <NEW_LINE> self.SessionsList.append(session) <NEW_LINE> <DEDENT> def remove_session(self,session): <NEW_LINE> <INDENT> assert ( isinstance(session, maproxy.session.Session) ) <NEW_LINE> assert ( session.p2s_state==maproxy.session.Session.State.CLOSED ) <NEW_LINE> assert ( session.c2p_state ==maproxy.session.Session.State.CLOSED ) <NEW_LINE> self.SessionsList.remove(session) <NEW_LINE> self.session_factory.delete(session) <NEW_LINE> <DEDENT> def get_connections_count(self): <NEW_LINE> <INDENT> return len(self.SessionsList) | TCP Proxy Server . | 6259903850485f2cf55dc10f |
class DataRequirementSchema: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def get_schema( max_nesting_depth: Optional[int] = 6, nesting_depth: int = 0, nesting_list: List[str] = [], max_recursion_limit: Optional[int] = 2, include_extension: Optional[bool] = False, extension_fields: Optional[List[str]] = [ "valueBoolean", "valueCode", "valueDate", "valueDateTime", "valueDecimal", "valueId", "valueInteger", "valuePositiveInt", "valueString", "valueTime", "valueUnsignedInt", "valueUri", "valueQuantity", ], extension_depth: int = 0, max_extension_depth: Optional[int] = 2, ) -> Union[StructType, DataType]: <NEW_LINE> <INDENT> from spark_fhir_schemas.stu3.complex_types.extension import ExtensionSchema <NEW_LINE> from spark_fhir_schemas.stu3.complex_types.datarequirement_codefilter import ( DataRequirement_CodeFilterSchema, ) <NEW_LINE> from spark_fhir_schemas.stu3.complex_types.datarequirement_datefilter import ( DataRequirement_DateFilterSchema, ) <NEW_LINE> if ( max_recursion_limit and nesting_list.count("DataRequirement") >= max_recursion_limit ) or (max_nesting_depth and nesting_depth >= max_nesting_depth): <NEW_LINE> <INDENT> return StructType([StructField("id", StringType(), True)]) <NEW_LINE> <DEDENT> my_nesting_list: List[str] = nesting_list + ["DataRequirement"] <NEW_LINE> schema = StructType( [ StructField("id", StringType(), True), StructField( "extension", ArrayType( ExtensionSchema.get_schema( max_nesting_depth=max_nesting_depth, nesting_depth=nesting_depth + 1, nesting_list=my_nesting_list, max_recursion_limit=max_recursion_limit, include_extension=include_extension, extension_fields=extension_fields, extension_depth=extension_depth, max_extension_depth=max_extension_depth, ) ), True, ), StructField("type", StringType(), True), StructField("profile", ArrayType(StringType()), True), StructField("mustSupport", ArrayType(StringType()), True), StructField( "codeFilter", ArrayType( DataRequirement_CodeFilterSchema.get_schema( max_nesting_depth=max_nesting_depth, nesting_depth=nesting_depth + 1, nesting_list=my_nesting_list, max_recursion_limit=max_recursion_limit, include_extension=include_extension, extension_fields=extension_fields, extension_depth=extension_depth, max_extension_depth=max_extension_depth, ) ), True, ), StructField( "dateFilter", ArrayType( DataRequirement_DateFilterSchema.get_schema( max_nesting_depth=max_nesting_depth, nesting_depth=nesting_depth + 1, nesting_list=my_nesting_list, max_recursion_limit=max_recursion_limit, include_extension=include_extension, extension_fields=extension_fields, extension_depth=extension_depth, max_extension_depth=max_extension_depth, ) ), True, ), ] ) <NEW_LINE> if not include_extension: <NEW_LINE> <INDENT> schema.fields = [ c if c.name != "extension" else StructField("extension", StringType(), True) for c in schema.fields ] <NEW_LINE> <DEDENT> return schema | Describes a required data item for evaluation in terms of the type of data,
and optional code or date-based filters of the data. | 625990381d351010ab8f4caa |
class Supervisor(BotPlugin): <NEW_LINE> <INDENT> @botcmd(split_args_with=None) <NEW_LINE> def supervisor(self, message, args): <NEW_LINE> <INDENT> output = 'Unable to process!' <NEW_LINE> if len(args) < 1: <NEW_LINE> <INDENT> return 'Not enough arguments. Try !supervisor help' <NEW_LINE> <DEDENT> scmd = args[0] <NEW_LINE> if scmd in ALLOWED_COMMANDS: <NEW_LINE> <INDENT> additional_params = ' '.join(args[1:]) if len(args) > 1 else '' <NEW_LINE> output = run_cmd('sudo supervisorctl {cmd} {params}'.format(cmd=scmd, params=additional_params)) <NEW_LINE> <DEDENT> return output | Bot Plugin to control supervisord | 62599038d4950a0f3b111707 |
class SkipListHandler: <NEW_LINE> <INDENT> def __init__(self, skip_file_content=""): <NEW_LINE> <INDENT> self.__skip = [] <NEW_LINE> if not skip_file_content: <NEW_LINE> <INDENT> skip_file_content = "" <NEW_LINE> <DEDENT> self.__skip_file_lines = [line.strip() for line in skip_file_content.splitlines() if line.strip()] <NEW_LINE> valid_lines = self.__check_line_format(self.__skip_file_lines) <NEW_LINE> self.__gen_regex(valid_lines) <NEW_LINE> <DEDENT> def __gen_regex(self, skip_lines): <NEW_LINE> <INDENT> for skip_line in skip_lines: <NEW_LINE> <INDENT> norm_skip_path = os.path.normpath(skip_line[1:].strip()) <NEW_LINE> rexpr = re.compile( fnmatch.translate(norm_skip_path + '*')) <NEW_LINE> self.__skip.append((skip_line, rexpr)) <NEW_LINE> <DEDENT> <DEDENT> def __check_line_format(self, skip_lines): <NEW_LINE> <INDENT> valid_lines = [] <NEW_LINE> for line in skip_lines: <NEW_LINE> <INDENT> if len(line) < 2 or line[0] not in ['-', '+']: <NEW_LINE> <INDENT> LOG.warning("Skipping malformed skipfile pattern: %s", line) <NEW_LINE> continue <NEW_LINE> <DEDENT> valid_lines.append(line) <NEW_LINE> <DEDENT> return valid_lines <NEW_LINE> <DEDENT> @property <NEW_LINE> def skip_file_lines(self): <NEW_LINE> <INDENT> return self.__skip_file_lines <NEW_LINE> <DEDENT> def overwrite_skip_content(self, skip_lines): <NEW_LINE> <INDENT> self.__skip = [] <NEW_LINE> valid_lines = self.__check_line_format(skip_lines) <NEW_LINE> self.__gen_regex(valid_lines) <NEW_LINE> <DEDENT> def should_skip(self, source): <NEW_LINE> <INDENT> if not self.__skip: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for line, rexpr in self.__skip: <NEW_LINE> <INDENT> if rexpr.match(source): <NEW_LINE> <INDENT> sign = line[0] <NEW_LINE> return sign == '-' <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def __call__(self, source_file_path: str) -> bool: <NEW_LINE> <INDENT> return self.should_skip(source_file_path) | Skiplist file format:
-/skip/all/source/in/directory*
-/do/not/check/this.file
+/dir/check.this.file
-/dir/* | 625990388da39b475be0437f |
class DeleteClusterResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.ClusterId = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.ClusterId = params.get("ClusterId") <NEW_LINE> self.RequestId = params.get("RequestId") | DeleteCluster返回参数结构体
| 625990383eb6a72ae038b7f9 |
class ChgPokeForm(Form): <NEW_LINE> <INDENT> newpoke = IntegerField("New id", validators=[DataRequired()]) <NEW_LINE> changepoke = SubmitField(u'Submit') | Change user's pokemon. | 625990381f5feb6acb163d82 |
class Meta: <NEW_LINE> <INDENT> verbose_name_plural = 'entries' | Хранит дополнительную информацию по управленью модели. | 62599038b830903b9686ed41 |
class Mem(models.Model): <NEW_LINE> <INDENT> server = models.ForeignKey('Asset', on_delete=models.CASCADE) <NEW_LINE> mem_sn = models.CharField('SN号', max_length=128, blank=True, null=True) <NEW_LINE> mem_model = models.CharField('内存型号', max_length=128, blank=True, null=True) <NEW_LINE> mem_manufacturer = models.CharField('内存制造商', max_length=128, blank=True, null=True) <NEW_LINE> mem_slot = models.IntegerField('插槽', blank=True, null=True, default=0) <NEW_LINE> mem_capacity = models.IntegerField('内存容量(单位:MB)', default=2048) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.server.name + ": " + str(self.mem_capacity) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = '内存' <NEW_LINE> verbose_name_plural = "内存" <NEW_LINE> unique_together = ('server', 'mem_slot') | 内存配置 | 625990381d351010ab8f4cab |
class DictTreeLib(object): <NEW_LINE> <INDENT> def __init__(self,tree): <NEW_LINE> <INDENT> self.tree = tree <NEW_LINE> print('Debug DictTreeLib Class',self.tree) <NEW_LINE> <DEDENT> def printOut(self): <NEW_LINE> <INDENT> print('DictTreeLib PrintOut:',self.tree) <NEW_LINE> return self.tree <NEW_LINE> <DEDENT> def getTree(self): <NEW_LINE> <INDENT> return self.tree <NEW_LINE> <DEDENT> def setTree(self,tree): <NEW_LINE> <INDENT> self.tree = tree <NEW_LINE> <DEDENT> def selectTree(self,path): <NEW_LINE> <INDENT> return self.tree.get(path) <NEW_LINE> <DEDENT> def listNode(self): <NEW_LINE> <INDENT> return self.tree.keys() <NEW_LINE> <DEDENT> def listLeafs(self): <NEW_LINE> <INDENT> return self.tree.values() <NEW_LINE> <DEDENT> def addNode(self,sub,value): <NEW_LINE> <INDENT> self.tree[sub]=value <NEW_LINE> <DEDENT> def delNode(self,key): <NEW_LINE> <INDENT> del self.tree[key] <NEW_LINE> <DEDENT> def findNode(self,key): <NEW_LINE> <INDENT> result = [] <NEW_LINE> self._findNode(self.tree,key,result) <NEW_LINE> return result <NEW_LINE> <DEDENT> def _findNode(self,obj,key,result): <NEW_LINE> <INDENT> for k, v in obj.items(): <NEW_LINE> <INDENT> if key in k: <NEW_LINE> <INDENT> result.append(obj[k]) <NEW_LINE> <DEDENT> if isinstance(v,dict): <NEW_LINE> <INDENT> item = self._findkey(v,key,result) <NEW_LINE> if item is not None: <NEW_LINE> <INDENT> result.append(item) | Dictionary Tree Object Library
handles nested dictionary trees | 6259903882261d6c5273078d |
class WlanExpNodesConfiguration(wn_config.NodesConfiguration): <NEW_LINE> <INDENT> def __init__(self, ini_file=None, serial_numbers=None, host_config=None): <NEW_LINE> <INDENT> super(WlanExpNodesConfiguration, self).__init__(ini_file=ini_file, serial_numbers=serial_numbers, host_config=host_config) | Class for WLAN Exp Node Configuration.
This class is a child of the WARPNet Node configuration. | 6259903894891a1f408b9fc0 |
class ChannelException: <NEW_LINE> <INDENT> pass | !
Channel related exceptions. | 6259903863f4b57ef008663c |
class Solution(object): <NEW_LINE> <INDENT> def isPalindrome_change(self, head): <NEW_LINE> <INDENT> pre = None <NEW_LINE> slow = fast = head <NEW_LINE> while fast and fast.next: <NEW_LINE> <INDENT> fast = fast.next.next <NEW_LINE> slow.next, slow, pre = pre, slow.next, slow <NEW_LINE> <DEDENT> if fast: <NEW_LINE> <INDENT> slow = slow.next <NEW_LINE> <DEDENT> while pre and pre.val == slow.val: <NEW_LINE> <INDENT> pre, slow = pre.next, slow.next <NEW_LINE> <DEDENT> return not pre <NEW_LINE> <DEDENT> def isPalindrome_no_change(self, head): <NEW_LINE> <INDENT> pre = None <NEW_LINE> slow = fast = head <NEW_LINE> while fast and fast.next: <NEW_LINE> <INDENT> fast = fast.next.next <NEW_LINE> slow.next, slow, pre = pre, slow.next, slow <NEW_LINE> <DEDENT> pre, left, right = slow, pre, slow if not fast else slow.next <NEW_LINE> res = True <NEW_LINE> while right: <NEW_LINE> <INDENT> res = res and (left.val == right.val) <NEW_LINE> right = right.next <NEW_LINE> left.next, left, pre = pre, left.next, left <NEW_LINE> <DEDENT> return res | :type head: ListNode
:rtype: bool | 62599038baa26c4b54d5043b |
class EntityFilterer(HTMLParser.HTMLParser): <NEW_LINE> <INDENT> _result = [] <NEW_LINE> def getResult(self): <NEW_LINE> <INDENT> return u''.join(self._result) <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> HTMLParser.HTMLParser.reset(self) <NEW_LINE> self._result = [] <NEW_LINE> <DEDENT> def _formatAttrs(self, attrs): <NEW_LINE> <INDENT> if len(attrs) == 0: <NEW_LINE> <INDENT> return u'' <NEW_LINE> <DEDENT> reformatted = [] <NEW_LINE> for name, value in attrs: <NEW_LINE> <INDENT> reformatted.append(u'%s="%s"' % (name, value)) <NEW_LINE> <DEDENT> return u' %s' % u' '.join(reformatted) <NEW_LINE> <DEDENT> def handle_starttag(self, tag, attrs): <NEW_LINE> <INDENT> self._result.append(u'<%s%s>' % (tag, self._formatAttrs(attrs))) <NEW_LINE> <DEDENT> def handle_startendtag(self, tag, attrs): <NEW_LINE> <INDENT> self._result.append(u'<%s%s/>' % (tag, self._formatAttrs(attrs))) <NEW_LINE> <DEDENT> def handle_endtag(self, tag): <NEW_LINE> <INDENT> self._result.append(u'</%s>' % tag) <NEW_LINE> <DEDENT> def handle_data(self, data): <NEW_LINE> <INDENT> self._result.append(data) <NEW_LINE> <DEDENT> def handle_charref(self, name): <NEW_LINE> <INDENT> if name[0] in ('x', 'X'): <NEW_LINE> <INDENT> self._result.append(unichr(int(name[1:], 16))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._result.append(unichr(int(name))) <NEW_LINE> <DEDENT> <DEDENT> def handle_entityref(self, name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._result.append(unichr(htmlentitydefs.name2codepoint[name])) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> self._result.append(u'&%s;' % name) <NEW_LINE> <DEDENT> <DEDENT> def handle_comment(self, data): <NEW_LINE> <INDENT> self.result.append(u'<!--%s-->' % data) <NEW_LINE> <DEDENT> def handle_decl(self, decl): <NEW_LINE> <INDENT> self.result.append(decl) <NEW_LINE> <DEDENT> def handle_pi(self, data): <NEW_LINE> <INDENT> self.result.append(u'<?%s>' % data) | A filter for HTML named and numeric entities that converts them to
their equivalent Unicode characters. | 62599038b57a9660fecd2c0d |
class AnyWrapperMsgGenerator(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> @overloaded <NEW_LINE> def error(cls, ex): <NEW_LINE> <INDENT> return "Error - " + ex <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> @error.register(object, str) <NEW_LINE> def error_0(cls, strval): <NEW_LINE> <INDENT> return strval <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> @error.register(object, int, int, str) <NEW_LINE> def error_1(cls, id, errorCode, errorMsg): <NEW_LINE> <INDENT> err = str(id) <NEW_LINE> err += " | " <NEW_LINE> err += str(errorCode) <NEW_LINE> err += " | " <NEW_LINE> err += errorMsg <NEW_LINE> return err <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def connectionClosed(cls): <NEW_LINE> <INDENT> return "Connection Closed" | generated source for class AnyWrapperMsgGenerator | 6259903896565a6dacd2d855 |
class TransitionError(Exception): <NEW_LINE> <INDENT> pass | Raised when an op attempts an invalid transition on a task. | 62599038287bf620b6272d7d |
class getGroups_result(object): <NEW_LINE> <INDENT> thrift_spec = ( (0, TType.LIST, 'success', (TType.STRUCT, (apache.airavata.model.sharing.ttypes.UserGroup, apache.airavata.model.sharing.ttypes.UserGroup.thrift_spec), False), None, ), ) <NEW_LINE> def __init__(self, success=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.LIST: <NEW_LINE> <INDENT> self.success = [] <NEW_LINE> (_etype17, _size14) = iprot.readListBegin() <NEW_LINE> for _i18 in range(_size14): <NEW_LINE> <INDENT> _elem19 = apache.airavata.model.sharing.ttypes.UserGroup() <NEW_LINE> _elem19.read(iprot) <NEW_LINE> self.success.append(_elem19) <NEW_LINE> <DEDENT> iprot.readListEnd() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write(oprot._fast_encode(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('getGroups_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.LIST, 0) <NEW_LINE> oprot.writeListBegin(TType.STRUCT, len(self.success)) <NEW_LINE> for iter20 in self.success: <NEW_LINE> <INDENT> iter20.write(oprot) <NEW_LINE> <DEDENT> oprot.writeListEnd() <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- success | 62599038dc8b845886d54747 |
class Strong(convenience.AbstractWithOptionalEscapedText): <NEW_LINE> <INDENT> def get_default_html_tag(self): <NEW_LINE> <INDENT> return 'strong' | Renders a ``<strong>``. | 62599038d164cc6175822107 |
class Context (tree.Visitor.Context): <NEW_LINE> <INDENT> def __init__ (self, attributes): <NEW_LINE> <INDENT> super ().__init__ (attributes) <NEW_LINE> self.contextCollectStage = True <NEW_LINE> self.colorMap = None <NEW_LINE> self.contextColorId = 0 | Visitor for assigning rendering colors. | 62599038b5575c28eb713593 |
class Variable: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.name = None <NEW_LINE> self.plotPath = None <NEW_LINE> self.type = None <NEW_LINE> self.namespace = None <NEW_LINE> self.moosePath = None <NEW_LINE> self.xml = None <NEW_LINE> <DEDENT> def __init__(self, name, type): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.type = type | Variable to plot.
| 62599038d10714528d69ef55 |
class _Getch: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.impl = _Getch_windows() <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> self.impl = _Getch_unix() <NEW_LINE> <DEDENT> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> return self.impl() | Gets a single character from standard input. Does not echo to the screen. | 6259903866673b3332c31589 |
class Rapid_i(Platform): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.platformName = "Rapid-i" <NEW_LINE> self.tags = ["trips"] <NEW_LINE> self.isValidMode = {} <NEW_LINE> self.isValidMode["phonefy"] = False <NEW_LINE> self.isValidMode["usufy"] = True <NEW_LINE> self.isValidMode["searchfy"] = False <NEW_LINE> self.url = {} <NEW_LINE> self.url["usufy"] = "http://rapid-i.com/rapidforum/index.php?action=profile;user=" + "<usufy>" <NEW_LINE> self.needsCredentials = {} <NEW_LINE> self.needsCredentials["usufy"] = True <NEW_LINE> self.creds = [] <NEW_LINE> self.validQuery = {} <NEW_LINE> self.validQuery["usufy"] = ".+" <NEW_LINE> self.notFoundText = {} <NEW_LINE> self.notFoundText["usufy"] = ["The user whose profile you are trying to view does not exist."] <NEW_LINE> self.fieldsRegExp = {} <NEW_LINE> self.fieldsRegExp["usufy"] = {} <NEW_LINE> self.foundFields = {} | A <Platform> object for Rapid-i. | 6259903830c21e258be999a2 |
class UserGeneratedAnswer(ORMBase): <NEW_LINE> <INDENT> __tablename__ = 'userGeneratedAnswer' <NEW_LINE> __table_args__ = dict( mysql_engine='InnoDB', mysql_charset='utf8', ) <NEW_LINE> ugAnswerId = sqlalchemy.schema.Column( sqlalchemy.types.Integer(), primary_key=True, autoincrement=True, ) <NEW_LINE> studentId = sqlalchemy.schema.Column( sqlalchemy.types.Integer(), sqlalchemy.schema.ForeignKey('student.studentId'), nullable=False, index=True, ) <NEW_LINE> ugQuestionGuid = sqlalchemy.schema.Column( customtypes.GUID(), sqlalchemy.schema.ForeignKey('userGeneratedQuestions.ugQuestionGuid'), nullable=False, index=True, ) <NEW_LINE> chosenAnswer = sqlalchemy.schema.Column( sqlalchemy.types.Integer(), nullable=True, ) <NEW_LINE> questionRating = sqlalchemy.schema.Column( sqlalchemy.types.Integer(), nullable=True, ) <NEW_LINE> comments = sqlalchemy.schema.Column( sqlalchemy.types.Text(), nullable=False, default='', ) <NEW_LINE> studentGrade = sqlalchemy.schema.Column( sqlalchemy.types.Numeric(precision=5, scale=3, asdecimal=False), nullable=False, default=0, ) | Answers from students evaluating user-generated questions | 62599038796e427e5384f911 |
class EditResult(JsonGetter): <NEW_LINE> <INDENT> def __init__(self, res_dict, feature_id=None): <NEW_LINE> <INDENT> RequestError(res_dict) <NEW_LINE> self.json = munch.munchify(res_dict) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def success_count(l): <NEW_LINE> <INDENT> return len([d for d in l if d.get(SUCCESS_STATUS) in (True, TRUE)]) <NEW_LINE> <DEDENT> def summary(self): <NEW_LINE> <INDENT> if self.json.get(ADD_RESULTS, []): <NEW_LINE> <INDENT> print('Added {} feature(s)'.format(self.success_count(getattr(self, ADD_RESULTS)))) <NEW_LINE> <DEDENT> if self.json.get(UPDATE_RESULTS, []): <NEW_LINE> <INDENT> print('Updated {} feature(s)'.format(self.success_count(getattr(self, UPDATE_RESULTS)))) <NEW_LINE> <DEDENT> if self.json.get(DELETE_RESULTS, []): <NEW_LINE> <INDENT> print('Deleted {} feature(s)'.format(self.success_count(getattr(self, DELETE_RESULTS)))) <NEW_LINE> <DEDENT> if self.json.get(ATTACHMENTS, []): <NEW_LINE> <INDENT> print('Attachment Edits: {}'.format(self.success_count(getattr(self, ATTACHMENTS)))) <NEW_LINE> <DEDENT> if self.json.get(ADD_ATTACHMENT_RESULT): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> k,v = getattr(self, ADD_ATTACHMENT_RESULT).items()[0] <NEW_LINE> print("Added attachment '{}' for feature {}".format(v, k)) <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> print('Added 1 attachment') <NEW_LINE> <DEDENT> <DEDENT> if self.json.get(DELETE_ATTACHMENT_RESULTS): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for res in getattr(self, DELETE_ATTACHMENT_RESULTS, []) or []: <NEW_LINE> <INDENT> if res.get(SUCCESS_STATUS) in (True, TRUE): <NEW_LINE> <INDENT> print("Deleted attachment '{}'".format(res.get(RESULT_OBJECT_ID))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Failed to Delete attachment '{}'".format(res.get(RESULT_OBJECT_ID))) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except IndexError: <NEW_LINE> <INDENT> print('Deleted {} attachment(s)'.format(len(getattr(self, DELETE_ATTACHMENT_RESULT)))) <NEW_LINE> <DEDENT> <DEDENT> if self.json.get(UPDATE_ATTACHMENT_RESULT): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> print("Updated attachment '{}'".format(self.json.get(UPDATE_ATTACHMENT_RESULT, {}).get(RESULT_OBJECT_ID))) <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> print('Updated 1 attachment') | class to handle Edit operation results | 6259903810dbd63aa1c71d69 |
class ListNamedShadowsForThingRequest(rpc.Shape): <NEW_LINE> <INDENT> def __init__(self, *, thing_name: typing.Optional[str] = None, next_token: typing.Optional[str] = None, page_size: typing.Optional[int] = None): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.thing_name = thing_name <NEW_LINE> self.next_token = next_token <NEW_LINE> self.page_size = page_size <NEW_LINE> <DEDENT> def set_thing_name(self, thing_name: str): <NEW_LINE> <INDENT> self.thing_name = thing_name <NEW_LINE> return self <NEW_LINE> <DEDENT> def set_next_token(self, next_token: str): <NEW_LINE> <INDENT> self.next_token = next_token <NEW_LINE> return self <NEW_LINE> <DEDENT> def set_page_size(self, page_size: int): <NEW_LINE> <INDENT> self.page_size = page_size <NEW_LINE> return self <NEW_LINE> <DEDENT> def _to_payload(self): <NEW_LINE> <INDENT> payload = {} <NEW_LINE> if self.thing_name is not None: <NEW_LINE> <INDENT> payload['thingName'] = self.thing_name <NEW_LINE> <DEDENT> if self.next_token is not None: <NEW_LINE> <INDENT> payload['nextToken'] = self.next_token <NEW_LINE> <DEDENT> if self.page_size is not None: <NEW_LINE> <INDENT> payload['pageSize'] = self.page_size <NEW_LINE> <DEDENT> return payload <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _from_payload(cls, payload): <NEW_LINE> <INDENT> new = cls() <NEW_LINE> if 'thingName' in payload: <NEW_LINE> <INDENT> new.thing_name = payload['thingName'] <NEW_LINE> <DEDENT> if 'nextToken' in payload: <NEW_LINE> <INDENT> new.next_token = payload['nextToken'] <NEW_LINE> <DEDENT> if 'pageSize' in payload: <NEW_LINE> <INDENT> new.page_size = int(payload['pageSize']) <NEW_LINE> <DEDENT> return new <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _model_name(cls): <NEW_LINE> <INDENT> return 'aws.greengrass#ListNamedShadowsForThingRequest' <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> attrs = [] <NEW_LINE> for attr, val in self.__dict__.items(): <NEW_LINE> <INDENT> if val is not None: <NEW_LINE> <INDENT> attrs.append('%s=%r' % (attr, val)) <NEW_LINE> <DEDENT> <DEDENT> return '%s(%s)' % (self.__class__.__name__, ', '.join(attrs)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if isinstance(other, self.__class__): <NEW_LINE> <INDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> return False | ListNamedShadowsForThingRequest
All attributes are None by default, and may be set by keyword in the constructor.
Keyword Args:
thing_name:
next_token:
page_size:
Attributes:
thing_name:
next_token:
page_size: | 6259903873bcbd0ca4bcb41e |
class NifOp: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> op = None <NEW_LINE> props = None <NEW_LINE> @staticmethod <NEW_LINE> def init(operator): <NEW_LINE> <INDENT> NifOp.op = operator <NEW_LINE> NifOp.props = operator.properties <NEW_LINE> NifLog.op = operator | A simple reference holder class but enables classes to be decoupled.
This module require initialisation to function. | 62599038d53ae8145f9195fa |
class TrustMiddleware(wsgi.Middleware): <NEW_LINE> <INDENT> def process_request(self, req): <NEW_LINE> <INDENT> trusts = list_trust(req.context, req.context.user_id) <NEW_LINE> LOG.debug('Trust list of user %s is %s' % (req.context.user_id, str(trusts))) <NEW_LINE> req.context.trusts = trusts | This middleware gets trusts information of the requester
and fill it into request context. This information will
be used by senlin engine later to support privilege
management. | 6259903863f4b57ef008663e |
@attr(shard=1) <NEW_LINE> class TestNewInstructorDashboardEmailViewXMLBacked(SharedModuleStoreTestCase): <NEW_LINE> <INDENT> MODULESTORE = TEST_DATA_MIXED_MODULESTORE <NEW_LINE> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> super(TestNewInstructorDashboardEmailViewXMLBacked, cls).setUpClass() <NEW_LINE> cls.course_key = SlashSeparatedCourseKey('edX', 'toy', '2012_Fall') <NEW_LINE> cls.url = reverse('instructor_dashboard', kwargs={'course_id': cls.course_key.to_deprecated_string()}) <NEW_LINE> cls.email_link = '<a href="" data-section="send_email">Email</a>' <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> super(TestNewInstructorDashboardEmailViewXMLBacked, self).setUp() <NEW_LINE> instructor = AdminFactory.create() <NEW_LINE> self.client.login(username=instructor.username, password="test") <NEW_LINE> self.url = reverse('instructor_dashboard', kwargs={'course_id': self.course_key.to_deprecated_string()}) <NEW_LINE> self.email_link = '<a href="" data-section="send_email">Email</a>' <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> super(TestNewInstructorDashboardEmailViewXMLBacked, self).tearDown() <NEW_LINE> BulkEmailFlag.objects.all().delete() <NEW_LINE> <DEDENT> def test_email_flag_true_mongo_false(self): <NEW_LINE> <INDENT> BulkEmailFlag.objects.create(enabled=True, require_course_email_auth=False) <NEW_LINE> response = self.client.get(self.url) <NEW_LINE> self.assertNotIn(self.email_link, response.content) <NEW_LINE> <DEDENT> def test_email_flag_false_mongo_false(self): <NEW_LINE> <INDENT> BulkEmailFlag.objects.create(enabled=False, require_course_email_auth=False) <NEW_LINE> response = self.client.get(self.url) <NEW_LINE> self.assertNotIn(self.email_link, response.content) | Check for email view on the new instructor dashboard | 6259903816aa5153ce401682 |
class EqualEarth(_WarpedRectangularProjection): <NEW_LINE> <INDENT> def __init__(self, central_longitude=0, false_easting=None, false_northing=None, globe=None): <NEW_LINE> <INDENT> if PROJ_VERSION < (5, 2, 0): <NEW_LINE> <INDENT> raise ValueError('The EqualEarth projection requires Proj version ' '5.2.0, but you are using {}.' .format('.'.join(str(v) for v in PROJ_VERSION))) <NEW_LINE> <DEDENT> proj_params = [('proj', 'eqearth'), ('lon_0', central_longitude)] <NEW_LINE> super().__init__(proj_params, central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) <NEW_LINE> self.threshold = 1e5 | An Equal Earth projection.
This projection is pseudocylindrical, and equal area. Parallels are
unequally-spaced straight lines, while meridians are equally-spaced arcs.
It is intended for world maps.
Note
----
To use this projection, you must be using Proj 5.2.0 or newer.
References
----------
Bojan Šavrič, Tom Patterson & Bernhard Jenny (2018) The Equal
Earth map projection, International Journal of Geographical Information
Science, DOI: 10.1080/13658816.2018.1504949 | 6259903807d97122c4217e33 |
class HomePageView(UploadFormMixin, ListView): <NEW_LINE> <INDENT> model = Activity <NEW_LINE> template_name = 'home.html' <NEW_LINE> context_object_name = 'activities' <NEW_LINE> paginate_by = 25 <NEW_LINE> def get_queryset(self) -> QuerySet: <NEW_LINE> <INDENT> return get_activities_for_user(self.request.user) <NEW_LINE> <DEDENT> def get_context_data(self, **kwargs) -> dict: <NEW_LINE> <INDENT> context = super(HomePageView, self).get_context_data(**kwargs) <NEW_LINE> context['leaders'] = get_leaders() <NEW_LINE> context['val_errors'] = ERRORS <NEW_LINE> return context | Handle logged-in user home page | 6259903873bcbd0ca4bcb41f |
class PboInfo: <NEW_LINE> <INDENT> def __init__(self, filename, packing_method=0, original_size=0, reserved=0, timestamp=0, data_size=-1, fp=None): <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> self.packing_method = packing_method <NEW_LINE> self.original_size = original_size <NEW_LINE> self.reserved = reserved <NEW_LINE> self.timestamp = timestamp <NEW_LINE> self.data_size = data_size <NEW_LINE> self.fp = fp <NEW_LINE> self.data_offset = -1 <NEW_LINE> <DEDENT> def get_data_size(self): <NEW_LINE> <INDENT> if self.fp is None: <NEW_LINE> <INDENT> return self.data_size <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return os.fstat(self.fp.fileno()).st_size <NEW_LINE> <DEDENT> <DEDENT> def get_timestamp(self): <NEW_LINE> <INDENT> if self.fp is None: <NEW_LINE> <INDENT> return self.timestamp <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return long(os.path.getmtime(self.fp.name)) <NEW_LINE> <DEDENT> <DEDENT> def check_name_hash(self): <NEW_LINE> <INDENT> return self.get_data_size() > 0 <NEW_LINE> <DEDENT> def check_file_hash(self, version): <NEW_LINE> <INDENT> if version == 2: <NEW_LINE> <INDENT> return (self.get_data_size() > 0 and not self.filename.lower().endswith(( b'.paa', b'.jpg', b'.p3d', b'.tga', b'.rvmat', b'.lip', b'.ogg', b'.wss', b'.png', b'.rtm', b'.pac', b'.fxy', b'.wrp'))) <NEW_LINE> <DEDENT> elif version == 3: <NEW_LINE> <INDENT> return (self.get_data_size() > 0 and self.filename.lower().endswith(( b'.sqf', b'.inc', b'.bikb', b'.ext', b'.fsm', b'.sqm', b'.hpp', b'.cfg', b'.sqs', b'.h'))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Unknown signature version {}".format(version)) <NEW_LINE> <DEDENT> <DEDENT> def dump(self): <NEW_LINE> <INDENT> print(self.filename + "{0} Bytes @ {1:x}".format(self.get_data_size(), self.data_offset)) | PboInfo class | 6259903823e79379d538d697 |
class CausalConv1d(torch.nn.Module): <NEW_LINE> <INDENT> def __init__(self, in_channels, out_channels, kernel_size, dilation=1, bias=True, pad="ConstantPad1d", pad_params={"value": 0.0}): <NEW_LINE> <INDENT> super(CausalConv1d, self).__init__() <NEW_LINE> self.pad = getattr(torch.nn, pad)((kernel_size - 1) * dilation, **pad_params) <NEW_LINE> self.conv = torch.nn.Conv1d(in_channels, out_channels, kernel_size, dilation=dilation, bias=bias) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> return self.conv(self.pad(x))[:, :, :x.size(2)] | CausalConv1d module with customized initialization. | 62599038ec188e330fdf9a2e |
class WorkflowNotFoundException(Exception): <NEW_LINE> <INDENT> def __init__(self) -> None: <NEW_LINE> <INDENT> super(WorkflowNotFoundException, self).__init__("The requested workflow run wasn't found.") | Raised when the requested run ID is not found. | 6259903823e79379d538d698 |
class ProjectLookup: <NEW_LINE> <INDENT> exposed = True <NEW_LINE> @staticmethod <NEW_LINE> def _get_projects_details(project_id=None): <NEW_LINE> <INDENT> lookup_url = u'{0}/projectinfo/by_project_id/{1}'.format( get_config().get('metadata', 'endpoint_url'), project_id ) <NEW_LINE> return requests.get(url=lookup_url).json() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> @tools.json_out() <NEW_LINE> @validate_project() <NEW_LINE> def GET(project_id=None): <NEW_LINE> <INDENT> return ProjectLookup._get_projects_details(project_id) | Retrieves details of a given project. | 6259903830c21e258be999a4 |
@ajax_form_config(name='properties.html', context=IRESTCallerTask, layer=IPyAMSLayer, permission=MANAGE_TASKS_PERMISSION) <NEW_LINE> class RESTTaskEditForm(BaseTaskEditForm): <NEW_LINE> <INDENT> pass | REST task edit form | 62599038b830903b9686ed44 |
class DownscalingLSF(DownscalingBase, LSFTask): <NEW_LINE> <INDENT> pass | downscaling on lsf cluster | 6259903896565a6dacd2d857 |
class SockeyeModel: <NEW_LINE> <INDENT> def __init__(self, config: ModelConfig): <NEW_LINE> <INDENT> self.config = config <NEW_LINE> logger.info("%s", self.config) <NEW_LINE> self.encoder = None <NEW_LINE> self.attention = None <NEW_LINE> self.decoder = None <NEW_LINE> self.rnn_cells = [] <NEW_LINE> self.built = False <NEW_LINE> self.params = None <NEW_LINE> <DEDENT> def save_config(self, folder: str): <NEW_LINE> <INDENT> fname = os.path.join(folder, C.CONFIG_NAME) <NEW_LINE> with open(fname, "w") as out: <NEW_LINE> <INDENT> json.dump(self.config._asdict(), out, indent=2, sort_keys=True) <NEW_LINE> logger.info('Saved config to "%s"', fname) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def load_config(fname: str) -> ModelConfig: <NEW_LINE> <INDENT> with open(fname, "r") as inp: <NEW_LINE> <INDENT> config = ModelConfig(**json.load(inp)) <NEW_LINE> logger.info('ModelConfig loaded from "%s"', fname) <NEW_LINE> return config <NEW_LINE> <DEDENT> <DEDENT> def save_params_to_file(self, fname: str): <NEW_LINE> <INDENT> assert self.built <NEW_LINE> params = self.params.copy() <NEW_LINE> for cell in self.rnn_cells: <NEW_LINE> <INDENT> params = cell.unpack_weights(params) <NEW_LINE> <DEDENT> sockeye.utils.save_params(params, fname) <NEW_LINE> logging.info('Saved params to "%s"', fname) <NEW_LINE> <DEDENT> def load_params_from_file(self, fname: str): <NEW_LINE> <INDENT> assert self.built <NEW_LINE> self.params, _ = sockeye.utils.load_params(fname) <NEW_LINE> for cell in self.rnn_cells: <NEW_LINE> <INDENT> self.params = cell.pack_weights(self.params) <NEW_LINE> <DEDENT> logger.info('Loaded params from "%s"', fname) <NEW_LINE> <DEDENT> def _build_model_components(self, max_seq_len: int, fused_encoder: bool, rnn_forget_bias: float = 0.0): <NEW_LINE> <INDENT> self.encoder = sockeye.encoder.get_encoder(self.config, rnn_forget_bias, fused_encoder) <NEW_LINE> self.attention = sockeye.attention.get_attention(self.config.attention_use_prev_word, self.config.attention_type, self.config.attention_num_hidden, self.config.rnn_num_hidden, max_seq_len, self.config.attention_coverage_type, self.config.attention_coverage_num_hidden, self.config.layer_normalization) <NEW_LINE> self.lexicon = sockeye.lexicon.Lexicon(self.config.vocab_source_size, self.config.vocab_target_size, self.config.learn_lexical_bias) if self.config.lexical_bias else None <NEW_LINE> self.decoder = sockeye.decoder.get_decoder(self.config.num_embed_target, self.config.vocab_target_size, self.config.rnn_num_layers, self.config.rnn_num_hidden, self.attention, self.config.rnn_cell_type, self.config.rnn_residual_connections, rnn_forget_bias, self.config.dropout, self.config.weight_tying, self.lexicon, self.config.context_gating, self.config.layer_normalization, self.config.lm_pretrain_layers) <NEW_LINE> self.rnn_cells = self.encoder.get_rnn_cells() + self.decoder.get_rnn_cells() <NEW_LINE> self.built = True | SockeyeModel shares components needed for both training and inference.
ModelConfig contains parameters and their values that are fixed at training time and must be re-used at inference
time.
:param config: Model configuration. | 6259903830c21e258be999a5 |
class User: <NEW_LINE> <INDENT> def __init__(self,fullname, email, username, password): <NEW_LINE> <INDENT> self.fullname = fullname <NEW_LINE> self.email = email <NEW_LINE> self.username = username <NEW_LINE> self.password = password <NEW_LINE> <DEDENT> user_list = [] <NEW_LINE> def save_user(self): <NEW_LINE> <INDENT> User.user_list.append(self) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def user_exists(cls, username): <NEW_LINE> <INDENT> for user in cls.user_list: <NEW_LINE> <INDENT> if user.username == username: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def find_by_username(cls,username): <NEW_LINE> <INDENT> for user in cls.user_list: <NEW_LINE> <INDENT> if user.username == username: <NEW_LINE> <INDENT> return user <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0 | Class that generates new users login system | 62599038dc8b845886d5474b |
class Profile(models.Model): <NEW_LINE> <INDENT> user = models.OneToOneField(User) <NEW_LINE> rank_choices = ( ('Diagnostic', 'Diagnostic'), ('Research', 'Research'), ('Manager', 'Manager'), ('Quality', 'Quality'), ('Super', 'Super'), ) <NEW_LINE> rank = models.CharField(max_length=100, choices=rank_choices, default='Diagnostic') <NEW_LINE> cfia_access = models.BooleanField(default=False) <NEW_LINE> lab_choices = ( (1, 'St-Johns'), (2, 'Dartmouth'), (3, 'Charlottetown'), (4, 'St-Hyacinthe'), (5, 'Longeuil'), (6, 'Fallowfield'), (7, 'Carling'), (8, 'Greater Toronto Area'), (9, 'Winnipeg'), (10, 'Saskatoon'), (11, 'Calgary'), (12, 'Lethbridge'), (13, 'Burnaby'), (14, 'Sidney'), (15, 'Other') ) <NEW_LINE> lab = models.CharField(max_length=100, choices=lab_choices, blank=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> s = "%s : %s : %s" % (self.user.username, self.rank, self.lab) <NEW_LINE> return s | Extends Django User Profile.
Certain features of the website check this model access priviledges. Any kind of field can be added to further
store information on user. Defaults are created whenever a new user is created | 6259903876d4e153a661db3e |
class GetEmailIdentityRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.EmailIdentity = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.EmailIdentity = params.get("EmailIdentity") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set)) | GetEmailIdentity请求参数结构体
| 62599038a8ecb033258723b6 |
class HalfBeam(Load): <NEW_LINE> <INDENT> def __init__(self, nelx, nely, E, nu): <NEW_LINE> <INDENT> super().__init__(nelx, nely, E, nu) <NEW_LINE> <DEDENT> def force(self): <NEW_LINE> <INDENT> f = super().force() <NEW_LINE> f[1] = -1 <NEW_LINE> return f <NEW_LINE> <DEDENT> def fixdofs(self): <NEW_LINE> <INDENT> n1, n2, n3, n4 = self.nodes(self.nelx-1, self.nely-1) <NEW_LINE> return ([x for x in range(0, self.dim*(self.nely+1), self.dim)] + [self.dim*n3+1]) | This child of the Load class represents the loading conditions of a
half beam. Only half of the beam is considered due to the symetry
about the y-axis.
Illustration
------------
F
|
V
> #-----#-----#-----#-----#-----#-----#
| | | | | | |
> #-----#-----#-----#-----#-----#-----#
| | | | | | |
> #-----#-----#-----#-----#-----#-----#
| | | | | | |
> #-----#-----#-----#-----#-----#-----#
^ | 62599038cad5886f8bdc5948 |
class iPerf3_v6Test(iPerf3Test): <NEW_LINE> <INDENT> opts = "-6" <NEW_LINE> def runTest(self): <NEW_LINE> <INDENT> wan = self.dev.wan <NEW_LINE> self.target_ip = wan.get_interface_ip6addr(wan.iface_dut) <NEW_LINE> super(iPerf3_v6Test, self).runTest() | iPerf3 ipv6 generic performance tests | 6259903826068e7796d4dae0 |
class SponsorFile(models.Model): <NEW_LINE> <INDENT> sponsor = models.ForeignKey('Sponsor', on_delete=models.CASCADE) <NEW_LINE> file = models.FileField(_('Sponsor file'), upload_to=sponsors_upload_to) <NEW_LINE> name = models.CharField(_('Sponsor file name'), max_length=128) <NEW_LINE> description = models.CharField(_('Sponsor file small description'), max_length=128) <NEW_LINE> created = models.DateTimeField('Sponsor file creation date', auto_now_add=True) <NEW_LINE> modified = models.DateTimeField('Sponsor file last modification date', auto_now=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return "{} - {}".format(self.sponsor.name, self.name) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = _("sponsor file") <NEW_LINE> verbose_name_plural = _("sponsor files") <NEW_LINE> ordering = ("sponsor", "name", "created") | Sponsor file class handler. | 625990385e10d32532ce41cf |
class Timer(Animal): <NEW_LINE> <INDENT> def run(self): <NEW_LINE> <INDENT> print("Start...") | docstring for Timer | 62599038e76e3b2f99fd9ba4 |
class TemplateContent(models.Model): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> verbose_name = _('template content') <NEW_LINE> verbose_name_plural = _('template contents') <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def initialize_type(cls, TEMPLATE_LOADERS=DEFAULT_TEMPLATE_LOADERS): <NEW_LINE> <INDENT> cls.template_loaders = [find_template_loader(loader) for loader in TEMPLATE_LOADERS if loader] <NEW_LINE> cls.add_to_class('filename', models.CharField(_('template'), max_length=100, choices=TemplateChoices(cls.template_loaders))) <NEW_LINE> <DEDENT> def render(self, **kwargs): <NEW_LINE> <INDENT> context = kwargs.pop('context', None) <NEW_LINE> name = 'content/template/%s' % self.filename <NEW_LINE> for loader in self.template_loaders: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> template, display_name = loader.load_template(name) <NEW_LINE> <DEDENT> except TemplateDoesNotExist: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if not hasattr(template, 'render'): <NEW_LINE> <INDENT> template = Template(template, name=name) <NEW_LINE> <DEDENT> if context: <NEW_LINE> <INDENT> ctx = context <NEW_LINE> ctx.update(dict(content=self, **kwargs)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ctx = Context(dict(content=self, **kwargs)) <NEW_LINE> <DEDENT> result = template.render(ctx) <NEW_LINE> if context: <NEW_LINE> <INDENT> context.pop() <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> return u'' | This content type scans all template folders for files in the
``content/template/`` folder and lets the website administrator select
any template from a set of provided choices.
The templates aren't restricted in any way. | 6259903823e79379d538d699 |
class TextProcessor(object): <NEW_LINE> <INDENT> tags = re.compile('<[^>]*>') <NEW_LINE> p_endstart_tags = re.compile('</p>\s*<p>') <NEW_LINE> p_startonlyhack_tags = re.compile('<p>') <NEW_LINE> links = re.compile('(https?://\S*)') <NEW_LINE> domain_re = re.compile('https?://([^ /]*)') <NEW_LINE> do_resave_all = False <NEW_LINE> @classmethod <NEW_LINE> def resave_all(klass, model): <NEW_LINE> <INDENT> if DescriptionProcessor.do_resave_all: <NEW_LINE> <INDENT> for b in model.objects.raw().all(): <NEW_LINE> <INDENT> b.save() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def remove_html(klass, signal, sender, instance, **kwargs): <NEW_LINE> <INDENT> d = getattr(instance, instance.textprocessor_fieldname()).strip() <NEW_LINE> d = TextProcessor.p_endstart_tags.sub('%s%s' % (os.linesep, os.linesep), d) <NEW_LINE> d = TextProcessor.p_startonlyhack_tags.sub('%s%s' % (os.linesep, os.linesep), d) <NEW_LINE> d = TextProcessor.tags.sub('', d).strip() <NEW_LINE> setattr(instance, instance.textprocessor_fieldname(), d) <NEW_LINE> return <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def discover_citations(klass, signal, sender, instance, created, **kwargs): <NEW_LINE> <INDENT> d = instance.description <NEW_LINE> for link in DescriptionProcessor.links.findall(d): <NEW_LINE> <INDENT> domain = DescriptionProcessor.domain_re.search(d).group() <NEW_LINE> http_domain = "http://%s"%domain <NEW_LINE> s = Node.get_or_none(label=domain) <NEW_LINE> if not s: <NEW_LINE> <INDENT> s = Node.add(label=domain, url=http_domain).publish() <NEW_LINE> <DEDENT> if not s.types: <NEW_LINE> <INDENT> s.add_type(NodeType.SOURCE()) <NEW_LINE> <DEDENT> a = s.behaviors.filter(url=link) <NEW_LINE> if not a: <NEW_LINE> <INDENT> a = Behavior.add(link, Dimension.SOURCE_EVAL(), url=link, node=s).publish() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> a = a[0] <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> Citation.add(a, instance).publish() <NEW_LINE> <DEDENT> except AlreadyExists: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return | Static class for doing description processing. | 62599038d6c5a102081e32bf |
class LibTool(GNUTarPackage): <NEW_LINE> <INDENT> name = 'libtool' <NEW_LINE> built_path = 'libtool' <NEW_LINE> installed_path = 'bin/libtool' <NEW_LINE> tar_compression = 'gz' | :identifier: libtool-<version>
:param str version: version to download | 62599038b57a9660fecd2c13 |
class USBRaw(object): <NEW_LINE> <INDENT> CONFIGURATION = None <NEW_LINE> INTERFACE = (0, 0) <NEW_LINE> ENDPOINTS = (None, None) <NEW_LINE> timeout = 2000 <NEW_LINE> find_devices = staticmethod(find_devices) <NEW_LINE> def __init__(self, vendor=None, product=None, serial_number=None, device_filters=None, timeout=None, **kwargs): <NEW_LINE> <INDENT> super(USBRaw, self).__init__() <NEW_LINE> self.timeout = timeout <NEW_LINE> device_filters = device_filters or {} <NEW_LINE> devices = list(self.find_devices(vendor, product, serial_number, None, **device_filters)) <NEW_LINE> if not devices: <NEW_LINE> <INDENT> raise ValueError('No device found.') <NEW_LINE> <DEDENT> elif len(devices) > 1: <NEW_LINE> <INDENT> desc = '\n'.join(str(dev) for dev in devices) <NEW_LINE> raise ValueError('{} devices found:\n{}\nPlease narrow the search' ' criteria'.format(len(devices), desc)) <NEW_LINE> <DEDENT> self.usb_dev = devices[0] <NEW_LINE> try: <NEW_LINE> <INDENT> if self.usb_dev.is_kernel_driver_active(0): <NEW_LINE> <INDENT> self.usb_dev.detach_kernel_driver(0) <NEW_LINE> <DEDENT> <DEDENT> except (usb.core.USBError, NotImplementedError) as e: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.usb_dev.set_configuration() <NEW_LINE> <DEDENT> except usb.core.USBError as e: <NEW_LINE> <INDENT> raise Exception('failed to set configuration\n %s' % e) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.usb_dev.set_interface_altsetting() <NEW_LINE> <DEDENT> except usb.core.USBError as e: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.usb_intf = self._find_interface(self.usb_dev, self.INTERFACE) <NEW_LINE> self.usb_recv_ep, self.usb_send_ep = self._find_endpoints(self.usb_intf, self.ENDPOINTS) <NEW_LINE> <DEDENT> def _find_interface(self, dev, setting): <NEW_LINE> <INDENT> return self.usb_dev.get_active_configuration()[self.INTERFACE] <NEW_LINE> <DEDENT> def _find_endpoints(self, interface, setting): <NEW_LINE> <INDENT> recv, send = setting <NEW_LINE> if recv is None: <NEW_LINE> <INDENT> recv = find_endpoint(interface, usb.ENDPOINT_IN, usb.ENDPOINT_TYPE_BULK) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> recv = usb_find_desc(interface, bEndpointAddress=recv) <NEW_LINE> <DEDENT> if send is None: <NEW_LINE> <INDENT> send = find_endpoint(interface, usb.ENDPOINT_OUT, usb.ENDPOINT_TYPE_BULK) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> send = usb_find_desc(interface, bEndpointAddress=send) <NEW_LINE> <DEDENT> return recv, send <NEW_LINE> <DEDENT> def write(self, data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.usb_send_ep.write(data) <NEW_LINE> <DEDENT> except usb.core.USBError as e: <NEW_LINE> <INDENT> raise ValueError(str(e)) <NEW_LINE> <DEDENT> <DEDENT> def read(self, size): <NEW_LINE> <INDENT> if size <= 0: <NEW_LINE> <INDENT> size = 1 <NEW_LINE> <DEDENT> data = array_to_bytes(self.usb_recv_ep.read(size, self.timeout)) <NEW_LINE> return data <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> return usb.util.dispose_resources(self.usb_dev) | Base class for drivers that communicate with instruments
via usb port using pyUSB | 62599038b830903b9686ed45 |
class BaseModel(): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> form = "%Y-%m-%dT%H:%M:%S.%f" <NEW_LINE> if kwargs: <NEW_LINE> <INDENT> for k, v in kwargs.items(): <NEW_LINE> <INDENT> if k == "created_at" or k == "updated_at": <NEW_LINE> <INDENT> self.__dict__[k] = datetime.strptime(v, form) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__dict__[k] = v <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.id = str(uuid.uuid4()) <NEW_LINE> self.created_at = datetime.now() <NEW_LINE> self.updated_at = datetime.now() <NEW_LINE> <DEDENT> models.storage.new(self) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> nameClass = self.__class__.__name__ <NEW_LINE> idValue = self.id <NEW_LINE> allAttribute = self.__dict__ <NEW_LINE> return "[{}] ({}) {}".format(nameClass, idValue, allAttribute) <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> self.updated_at = datetime.now() <NEW_LINE> models.storage.save() <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> dict = {} <NEW_LINE> for i in self.__dict__: <NEW_LINE> <INDENT> if i == "updated_at" or i == "created_at": <NEW_LINE> <INDENT> dict[i] = getattr(self, i).isoformat() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dict[i] = getattr(self, i) <NEW_LINE> <DEDENT> <DEDENT> dict["__class__"] = self.__class__.__name__ <NEW_LINE> return dict | Base Model | 625990381d351010ab8f4cb3 |
class TestYamlFileReader(object): <NEW_LINE> <INDENT> @pytest.fixture <NEW_LINE> def template_yaml(self, tmpdir): <NEW_LINE> <INDENT> test_file = tmpdir.mkdir("TestLoadTemplateTextFile").join("sample.yaml") <NEW_LINE> test_file.write("temp: sample") <NEW_LINE> return test_file <NEW_LINE> <DEDENT> def test_reading_temp_in_text_file_as_string(self, template_yaml): <NEW_LINE> <INDENT> load_text = operation.YamlFileReader(str(template_yaml)).get_read_data() <NEW_LINE> assert {"temp": "sample"} == load_text | test code to YamlFIleReader.
| 62599038c432627299fa4191 |
class BaseNodeData(models.Model): <NEW_LINE> <INDENT> node = models.OneToOneField('flowr.Node') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> abstract = True | Subclasses of this object are used to store information associated with
a :class:`Node` in the :class:`DCCGraph`. | 6259903896565a6dacd2d858 |
class GetLenders(Choreography): <NEW_LINE> <INDENT> def __init__(self, temboo_session): <NEW_LINE> <INDENT> Choreography.__init__(self, temboo_session, '/Library/Kiva/Loans/GetLenders') <NEW_LINE> <DEDENT> def new_input_set(self): <NEW_LINE> <INDENT> return GetLendersInputSet() <NEW_LINE> <DEDENT> def _make_result_set(self, result, path): <NEW_LINE> <INDENT> return GetLendersResultSet(result, path) <NEW_LINE> <DEDENT> def _make_execution(self, session, exec_id, path): <NEW_LINE> <INDENT> return GetLendersChoreographyExecution(session, exec_id, path) | Create a new instance of the GetLenders Choreography. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied. | 62599038b57a9660fecd2c14 |
class DatespanFilter(BaseReportFilter): <NEW_LINE> <INDENT> template = "reports/filters/datespan.html" <NEW_LINE> label = ugettext_lazy("Date Range") <NEW_LINE> slug = "datespan" <NEW_LINE> inclusive = True <NEW_LINE> default_days = 30 <NEW_LINE> @property <NEW_LINE> def datespan(self): <NEW_LINE> <INDENT> datespan = DateSpan.since(self.default_days, format="%Y-%m-%d", timezone=self.timezone, inclusive=self.inclusive) <NEW_LINE> if self.request.datespan.is_valid() and self.slug == 'datespan': <NEW_LINE> <INDENT> datespan.startdate = self.request.datespan.startdate <NEW_LINE> datespan.enddate = self.request.datespan.enddate <NEW_LINE> <DEDENT> return datespan <NEW_LINE> <DEDENT> @property <NEW_LINE> def filter_context(self): <NEW_LINE> <INDENT> return { 'datespan': self.datespan, 'report_labels': self.report_labels, 'separator': _(' to '), 'timezone': self.timezone.zone, } <NEW_LINE> <DEDENT> @property <NEW_LINE> def report_labels(self): <NEW_LINE> <INDENT> return simplejson.dumps({ 'last_7_days': _('Last 7 Days'), 'last_month': _('Last Month'), 'last_30_days': _('Last 30 Days') }) | A filter that returns a startdate and an enddate.
This is the standard datespan filter that gets pulled into request with the decorator
@datespan_in_request | 625990388a43f66fc4bf3326 |
class CentralPane(RecycleView): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(CentralPane, self).__init__(**kwargs) <NEW_LINE> self.data = kwargs.get('data', 'nothing found') | The central pane has two text output sub-panes, both containing some text.
The first is an article title; the second - its respective date.
The central pane should be Recycle View. | 6259903891af0d3eaad3afcc |
class RollParser(commands.Converter): <NEW_LINE> <INDENT> async def convert(self, ctx, argument): <NEW_LINE> <INDENT> matches = re.search(r"(?:(\d*)-)?(\d*)", argument) <NEW_LINE> minshit = matches.group(1) or 1 <NEW_LINE> maxshit = matches.group(2) or 100 <NEW_LINE> return (int(minshit), int(maxshit)) | This makes parsing the roll thing into a function
annotation | 6259903863f4b57ef0086640 |
class BadPDUType (SNMPEngineError): <NEW_LINE> <INDENT> pass | Bad SNMP PDU type
| 625990386e29344779b017eb |
class SecsS07F19(SecsStreamFunction): <NEW_LINE> <INDENT> _stream = 7 <NEW_LINE> _function = 19 <NEW_LINE> _data_format = None <NEW_LINE> _to_host = False <NEW_LINE> _to_equipment = True <NEW_LINE> _has_reply = True <NEW_LINE> _is_reply_required = True <NEW_LINE> _is_multi_block = False | current equipment process program - request.
**Structure**::
>>> import secsgem.secs
>>> secsgem.secs.functions.SecsS07F19
Header only
**Example**::
>>> import secsgem.secs
>>> secsgem.secs.functions.SecsS07F19()
S7F19 W .
:param value: parameters for this function (see example)
:type value: dict | 6259903807d97122c4217e37 |
class Operator(object): <NEW_LINE> <INDENT> def __init__(self, tag=None): <NEW_LINE> <INDENT> self.tag = tag <NEW_LINE> <DEDENT> @property <NEW_LINE> def _tagstr(self): <NEW_LINE> <INDENT> return ' "%s"' % self.tag if self.tag is not None else '' <NEW_LINE> <DEDENT> @property <NEW_LINE> def reads(self): <NEW_LINE> <INDENT> return self._reads <NEW_LINE> <DEDENT> @reads.setter <NEW_LINE> def reads(self, val): <NEW_LINE> <INDENT> self._reads = val <NEW_LINE> <DEDENT> @property <NEW_LINE> def sets(self): <NEW_LINE> <INDENT> return self._sets <NEW_LINE> <DEDENT> @sets.setter <NEW_LINE> def sets(self, val): <NEW_LINE> <INDENT> self._sets = val <NEW_LINE> <DEDENT> @property <NEW_LINE> def incs(self): <NEW_LINE> <INDENT> return self._incs <NEW_LINE> <DEDENT> @incs.setter <NEW_LINE> def incs(self, val): <NEW_LINE> <INDENT> self._incs = val <NEW_LINE> <DEDENT> @property <NEW_LINE> def updates(self): <NEW_LINE> <INDENT> return self._updates <NEW_LINE> <DEDENT> @updates.setter <NEW_LINE> def updates(self, val): <NEW_LINE> <INDENT> self._updates = val <NEW_LINE> <DEDENT> @property <NEW_LINE> def all_signals(self): <NEW_LINE> <INDENT> return self.reads + self.sets + self.incs + self.updates <NEW_LINE> <DEDENT> def init_signals(self, signals): <NEW_LINE> <INDENT> for sig in self.all_signals: <NEW_LINE> <INDENT> if sig.base not in signals: <NEW_LINE> <INDENT> signals.init(sig.base) | Base class for operator instances understood by nengo.Simulator.
The lifetime of a Signal during one simulator timestep:
0. at most one set operator (optional)
1. any number of increments
2. any number of reads
3. at most one update
A signal that is only read can be considered a "constant".
A signal that is both set *and* updated can be a problem:
since reads must come after the set, and the set will destroy
whatever were the contents of the update, it can be the case
that the update is completely hidden and rendered irrelevant.
There are however at least two reasons to use both a set and an update:
- to use a signal as scratch space (updating means destroying it)
- to use sets and updates on partly overlapping views of the same
memory.
N.B.: It is done on purpose that there are no default values for
reads, sets, incs, and updates.
Each operator should explicitly set each of these properties. | 62599038ac7a0e7691f73682 |
class LongRunningCommand(AbstractCommand): <NEW_LINE> <INDENT> done: bool = False <NEW_LINE> def execute(self) -> int: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for _ in track(range(10), description='Processing...'): <NEW_LINE> <INDENT> time.sleep(1) <NEW_LINE> <DEDENT> <DEDENT> except KeyboardInterrupt: <NEW_LINE> <INDENT> log.info('Cancelled') <NEW_LINE> return 1 <NEW_LINE> <DEDENT> self.done = True <NEW_LINE> log.info('Done') <NEW_LINE> return 0 | A long running command class | 62599038baa26c4b54d50442 |
class Ticker(object): <NEW_LINE> <INDENT> url = 'http://www.feixiaohao.com/exchange/bithumb/' <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.ua = UserAgent() <NEW_LINE> <DEDENT> def ticker(self, url, num): <NEW_LINE> <INDENT> html = requests.get(url, headers={'User-Agent': self.ua.random}) <NEW_LINE> response = Selector(text=html.text) <NEW_LINE> header_info = response.xpath('//div[@class="box box1200"]/div/div/div[@class="info"]') <NEW_LINE> vol = response.xpath('//div[@class="box box1200"]/div/div/div[@class="vol"]/div') <NEW_LINE> response = response.xpath('//table[@class="table noBg"]/tbody/tr') <NEW_LINE> for info in response: <NEW_LINE> <INDENT> arb = info.xpath('./td[3]/a/text()').extract_first(None) <NEW_LINE> name_base = info.xpath('./td[2]/a/img/@alt').extract_first() <NEW_LINE> if arb is None: <NEW_LINE> <INDENT> arb = info.xpath('./td[3]/text()').extract_first() <NEW_LINE> <DEDENT> if len(name_base.split('-')) == 1: <NEW_LINE> <INDENT> name_base = 'None-{}'.format(name_base) <NEW_LINE> <DEDENT> result = { 'img_url': info.xpath('./td[2]/a/img/@src').extract_first(), 'name_plat': header_info.xpath('./input/@value').extract_first().lower(), 'url': url, 'name_zh': name_base.split('-')[0], 'name': name_base.split('-')[1].lower(), 'arb': arb.strip(), 'base': arb.split('/')[0].strip(), 'quote': arb.split('/')[1], 'price': info.xpath('./td[4]/text()').extract_first(), 'price_cny': info.xpath('./td[4]/@data-cny').extract_first(), 'price_usd': info.xpath('./td[4]/@data-usd').extract_first(), 'price_btc': info.xpath('./td[4]/@data-btc').extract_first(), 'price_native': info.xpath('./td[4]/@data-native').extract_first(), 'volume': info.xpath('./td[5]/text()').extract_first(), 'volume_cny': info.xpath('./td[5]/@data-cny').extract_first(), 'volume_usd': info.xpath('./td[5]/@data-usd').extract_first(), 'volume_btc': info.xpath('./td[5]/@data-btc').extract_first(), 'volume_native': info.xpath('./td[5]/@data-native').extract_first(), 'percent': info.xpath('./td[6]/text()').extract_first(), 'time': info.xpath('./td[7]/text()').extract_first(), 'time_now': num, 'volume_plat_cny': vol.xpath('./div[1]/text()').extract_first(), 'volume_plat_usd': vol.xpath('./div[2]/span[1]/text()').extract_first(), 'volume_plat_btc': vol.xpath('./div[2]/span[2]/text()').extract_first(), } <NEW_LINE> yield result | 通过url获取详情页币种信息 | 62599038d6c5a102081e32c1 |
class IsPostOnly(permissions.BasePermission): <NEW_LINE> <INDENT> safe_methods = ('POST',) <NEW_LINE> def has_object_permission(self, request, view, obj): <NEW_LINE> <INDENT> return request.method in self.safe_methods | Custom permission to only allow owners of an object to edit it. | 62599038b830903b9686ed46 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.