code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class ValidatedGraphSet(GraphSet): <NEW_LINE> <INDENT> @validator("resources") <NEW_LINE> def dedupe_and_validate_resources(cls, resources: Tuple[Resource, ...]) -> Tuple[Resource, ...]: <NEW_LINE> <INDENT> deduped_resources = dedupe_resources(resources) <NEW_LINE> validate_resources(deduped_resources) <NEW_LINE> return deduped_resources <NEW_LINE> <DEDENT> def to_rdf(self) -> Graph: <NEW_LINE> <INDENT> namespace = Namespace(f"{self.name}:") <NEW_LINE> node_cache = NodeCache() <NEW_LINE> graph = Graph() <NEW_LINE> metadata_node = BNode() <NEW_LINE> graph.add((metadata_node, RDF.type, getattr(namespace, "metadata"))) <NEW_LINE> graph.add((metadata_node, getattr(namespace, "name"), Literal(self.name))) <NEW_LINE> graph.add((metadata_node, getattr(namespace, "version"), Literal(self.version))) <NEW_LINE> graph.add((metadata_node, getattr(namespace, "start_time"), Literal(self.start_time))) <NEW_LINE> graph.add((metadata_node, getattr(namespace, "end_time"), Literal(self.end_time))) <NEW_LINE> for error in self.errors: <NEW_LINE> <INDENT> graph.add((metadata_node, getattr(namespace, "error"), Literal(error))) <NEW_LINE> <DEDENT> for resource in self.resources: <NEW_LINE> <INDENT> resource.to_rdf(namespace=namespace, graph=graph, node_cache=node_cache) <NEW_LINE> <DEDENT> return graph <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_graph_set(cls, graph_set: GraphSet) -> "ValidatedGraphSet": <NEW_LINE> <INDENT> return cls( name=graph_set.name, version=graph_set.version, start_time=graph_set.start_time, end_time=graph_set.end_time, resources=graph_set.resources, errors=graph_set.errors, ) <NEW_LINE> <DEDENT> def to_neptune_lpg(self, scan_id: str) -> Dict: <NEW_LINE> <INDENT> vertices = [] <NEW_LINE> edges = [] <NEW_LINE> vertex = { "~id": scan_id, "~label": "metadata", "name": self.name, "version": self.version, "start_time": self.start_time, "end_time": self.end_time, } <NEW_LINE> vertices.append(vertex) <NEW_LINE> for error in self.errors: <NEW_LINE> <INDENT> vertex = {"~id": str(uuid.uuid1()), "~label": "error", "error": error} <NEW_LINE> vertices.append(vertex) <NEW_LINE> edges.append( { "~id": str(uuid.uuid1()), "~label": "generated", "~from": f"{self.name}:{self.version}", "~to": vertex["~id"], } ) <NEW_LINE> vertices.append(vertex) <NEW_LINE> <DEDENT> for resource in self.resources: <NEW_LINE> <INDENT> resource.to_lpg(vertices, edges) <NEW_LINE> <DEDENT> for v in vertices: <NEW_LINE> <INDENT> v["scan_id"] = scan_id <NEW_LINE> edges.append( { "~id": uuid.uuid1(), "~label": "identified_resource", "~from": scan_id, "~to": v["~id"], } ) <NEW_LINE> <DEDENT> return {"vertices": vertices, "edges": edges}
A GraphSet which has been validated - duplicate resources have been merged and required resource links have been verified
62598fc14a966d76dd5ef125
class Package(j.baseclasses.threebot_package): <NEW_LINE> <INDENT> def _init(self, **kwargs): <NEW_LINE> <INDENT> self.branch = kwargs["package"].branch or "master" <NEW_LINE> self.euroflow_io = "https://github.com/euroflow-io/www_euroflow_io.git" <NEW_LINE> <DEDENT> def prepare(self): <NEW_LINE> <INDENT> server = self.openresty <NEW_LINE> server.install(reset=True) <NEW_LINE> server.configure() <NEW_LINE> website = server.websites.get("euroflow_io") <NEW_LINE> website.ssl = False <NEW_LINE> website.port = 80 <NEW_LINE> locations = website.locations.get("euroflow_io") <NEW_LINE> static_location = locations.locations_static.new() <NEW_LINE> static_location.name = "static" <NEW_LINE> static_location.path_url = "/" <NEW_LINE> path = j.clients.git.getContentPathFromURLorPath(self.euroflow_io, branch=self.branch, pull=True) <NEW_LINE> static_location.path_location = path <NEW_LINE> static_location.use_jumpscale_weblibs = True <NEW_LINE> website.path = path <NEW_LINE> locations.configure() <NEW_LINE> website.configure() <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> self.prepare() <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def uninstall(self): <NEW_LINE> <INDENT> pass
to start need to run kosmos -p "j.tools.threebot_packages.get('euroflow_io',giturl='https://github.com/euroflow-io/www_euroflow_io.git',branch='master')" kosmos -p "j.servers.threebot.default.start(web=True, ssl=False)"
62598fc1ec188e330fdf8ae4
class GenericMolFile(data.Text): <NEW_LINE> <INDENT> MetadataElement(name="number_of_molecules", default=0, desc="Number of molecules", readonly=True, visible=True, optional=True, no_value=0) <NEW_LINE> def set_peek(self, dataset, is_multi_byte=False): <NEW_LINE> <INDENT> if not dataset.dataset.purged: <NEW_LINE> <INDENT> dataset.peek = get_file_peek(dataset.file_name, is_multi_byte=is_multi_byte) <NEW_LINE> if (dataset.metadata.number_of_molecules == 1): <NEW_LINE> <INDENT> dataset.blurb = "1 molecule" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dataset.blurb = "%s molecules" % dataset.metadata.number_of_molecules <NEW_LINE> <DEDENT> dataset.peek = data.get_file_peek(dataset.file_name, is_multi_byte=is_multi_byte) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dataset.peek = 'file does not exist' <NEW_LINE> dataset.blurb = 'file purged from disk' <NEW_LINE> <DEDENT> <DEDENT> def get_mime(self): <NEW_LINE> <INDENT> return 'text/plain'
Abstract class for most of the molecule files.
62598fc1091ae35668704e77
class MultipleChoiceItem(ChoiceItem): <NEW_LINE> <INDENT> def __init__(self, label, choices, default=(), help='', check=True): <NEW_LINE> <INDENT> ChoiceItem.__init__(self, label, choices, default, help, check=check) <NEW_LINE> self.set_prop("display", shape = (1, -1)) <NEW_LINE> <DEDENT> def horizontal(self, row_nb=1): <NEW_LINE> <INDENT> self.set_prop("display", shape = (row_nb, -1)) <NEW_LINE> return self <NEW_LINE> <DEDENT> def vertical(self, col_nb=1): <NEW_LINE> <INDENT> self.set_prop("display", shape = (-1, col_nb)) <NEW_LINE> return self <NEW_LINE> <DEDENT> def serialize(self, instance, writer): <NEW_LINE> <INDENT> value = self.get_value(instance) <NEW_LINE> seq = [] <NEW_LINE> _choices = self.get_prop_value("data", instance, "choices") <NEW_LINE> for key, _label, _img in _choices: <NEW_LINE> <INDENT> seq.append( key in value ) <NEW_LINE> <DEDENT> writer.write_sequence( seq ) <NEW_LINE> <DEDENT> def deserialize(self, instance, reader): <NEW_LINE> <INDENT> flags = reader.read_sequence() <NEW_LINE> _choices = self.get_prop_value("data", instance, "choices") <NEW_LINE> value = [] <NEW_LINE> for idx, flag in enumerate(flags): <NEW_LINE> <INDENT> if flag: <NEW_LINE> <INDENT> value.append( _choices[idx][0] ) <NEW_LINE> <DEDENT> <DEDENT> self.__set__(instance, value)
Construct a data item for a list of choices -- multiple choices can be selected * label [string]: name * choices [list or tuple]: string list or (key, label) list * default [-]: default label or default key (optional) * help [string]: text shown in tooltip (optional) * check [bool]: if False, value is not checked (optional, default=True)
62598fc1aad79263cf42ea26
@register_resource <NEW_LINE> class v1_RouteStatus(Resource): <NEW_LINE> <INDENT> __kind__ = 'v1.RouteStatus' <NEW_LINE> __fields__ = { 'ingress': 'ingress', } <NEW_LINE> __types__ = { 'ingress': 'v1.RouteIngress', } <NEW_LINE> __required__ = set([ 'ingress', ]) <NEW_LINE> ingress = None <NEW_LINE> def __init__(self, *, ingress, **_kwargs_): <NEW_LINE> <INDENT> self.ingress = ingress <NEW_LINE> super().__init__(**_kwargs_)
RouteStatus provides relevant info about the status of a route, including which routers acknowledge it.
62598fc1851cf427c66b8507
class Solution: <NEW_LINE> <INDENT> def mergeKLists(self, lists): <NEW_LINE> <INDENT> return self.merge_range_lists(lists, 0, len(lists) - 1) <NEW_LINE> <DEDENT> def merge_range_lists(self, lists, start, end): <NEW_LINE> <INDENT> if start == end: <NEW_LINE> <INDENT> return lists[start] <NEW_LINE> <DEDENT> mid = (start + end) // 2 <NEW_LINE> left = self.merge_range_lists(lists, start, mid) <NEW_LINE> right = self.merge_range_lists(lists, mid + 1, end) <NEW_LINE> return self.merge_two_lists(left, right) <NEW_LINE> <DEDENT> def merge_two_lists(self, a, b): <NEW_LINE> <INDENT> dummyNode = cur = ListNode(-1) <NEW_LINE> while a and b: <NEW_LINE> <INDENT> if a.val < b.val: <NEW_LINE> <INDENT> cur.next = a <NEW_LINE> a = a.next <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cur.next = b <NEW_LINE> b = b.next <NEW_LINE> <DEDENT> cur = cur.next <NEW_LINE> <DEDENT> while a: <NEW_LINE> <INDENT> cur.next = a <NEW_LINE> cur = cur.next <NEW_LINE> a = a.next <NEW_LINE> <DEDENT> while b: <NEW_LINE> <INDENT> cur.next = b <NEW_LINE> cur = cur.next <NEW_LINE> b = b.next <NEW_LINE> <DEDENT> return dummyNode.next
@param lists: a list of ListNode @return: The head of one sorted list.
62598fc13d592f4c4edbb10f
class SiteAssets(AdminMixin, AdminSite): <NEW_LINE> <INDENT> pass
A Django AdminSite with the AdminMixin to allow registering custom dashboard view.
62598fc197e22403b383b15b
class MultitenantOrgFilter(admin.RelatedFieldListFilter): <NEW_LINE> <INDENT> multitenant_lookup = 'pk__in' <NEW_LINE> def field_choices(self, field, request, model_admin): <NEW_LINE> <INDENT> if request.user.is_superuser: <NEW_LINE> <INDENT> return super().field_choices(field, request, model_admin) <NEW_LINE> <DEDENT> organizations = request.user.organizations_pk <NEW_LINE> return field.get_choices( include_blank=False, limit_choices_to={self.multitenant_lookup: organizations}, )
Admin filter that shows only organizations the current user is associated with in its available choices
62598fc14c3428357761a50d
class Meta: <NEW_LINE> <INDENT> model = CompanyInformation <NEW_LINE> fields = ('name', 'scale', 'industry', 'style', 'address', 'contact', 'introduction', 'description', 'established')
定义规则字段.
62598fc1ff9c53063f51a8a0
class GaussianProcessRegressorModel(object): <NEW_LINE> <INDENT> def __init__(self, units=TimeUnits.seconds, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> from sklearn import gaussian_process <NEW_LINE> from pandas import DataFrame <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> print('GaussianProcessRegressorModel requires scikit-learn and pandas') <NEW_LINE> raise <NEW_LINE> <DEDENT> if 'kernel' not in kwargs: <NEW_LINE> <INDENT> from sklearn.gaussian_process.kernels import Matern, WhiteKernel, ConstantKernel <NEW_LINE> kwargs['kernel'] = ConstantKernel() + Matern(length_scale=1, nu=3 / 2) + WhiteKernel(noise_level=1) <NEW_LINE> <DEDENT> self.model = gaussian_process.GaussianProcessRegressor(**kwargs) <NEW_LINE> self.units = units <NEW_LINE> self.is_trained = False <NEW_LINE> self.ordering = None <NEW_LINE> self.__dataframe_class = DataFrame <NEW_LINE> <DEDENT> def train(self, input_data, durations, ordering=None): <NEW_LINE> <INDENT> if isinstance(input_data, self.__dataframe_class): <NEW_LINE> <INDENT> self.ordering = [ key for key, value in OrderedDict(input_data.dtypes).items() if value in ('float64', 'int64')] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if ordering is None: <NEW_LINE> <INDENT> raise ValueError('Ordering must be provided for non-pandas dataframe inputs') <NEW_LINE> <DEDENT> self.ordering = ordering <NEW_LINE> <DEDENT> self.model.fit(input_data, durations) <NEW_LINE> self.is_trained = True <NEW_LINE> <DEDENT> def predict(self, input_data): <NEW_LINE> <INDENT> if not self.is_trained: <NEW_LINE> <INDENT> raise ValueError('Cannot predict with untrained model') <NEW_LINE> <DEDENT> ordered_input_data = [[input_data[field] for field in self.ordering]] <NEW_LINE> predicted = self.model.predict(ordered_input_data, return_std=True) <NEW_LINE> return DurationPdf(GaussianPdf(predicted[0][0], predicted[1][0]**2), units=self.units)
Learns the duration of a task from data using scikit-learn's GaussianProcessRegressor Attributes: model (GaussianProcessRegressor): The underlying model used to predict the data units (TimeUnits, optional): The time units the resulting durations should be in. Defaults to TimeUnits.seconds is_trained (bool): A boolean value indicating if the model has been trained. ordering (list[str]): The ordering of the input data used to construct input data Args: units (TimeUnits, optional): The time units the resulting durations should be in. Defaults to TimeUnits.seconds Keyword Args: kernel: The kernel to use in the regressor model. Defaults to ConstantKernel() + Matern(length_scale=1, nu=3 / 2) + WhiteKernel(noise_level=1)
62598fc1be7bc26dc9251f85
class Cat(UnixCommand): <NEW_LINE> <INDENT> args = ('shell_glob',) <NEW_LINE> local_op = staticmethod(cat_local_op)
Cat files.
62598fc1099cdd3c6367550b
class MarketingVersion(NamedTuple): <NEW_LINE> <INDENT> major: int <NEW_LINE> minor: int <NEW_LINE> patch: int <NEW_LINE> @classmethod <NEW_LINE> def fromTuple(cls, value: Tuple[str]) -> 'MarketingVersion': <NEW_LINE> <INDENT> return cls(int(value[0]), int(value[1]), int(value[2])) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def fromString(cls, value: str) -> 'MarketingVersion': <NEW_LINE> <INDENT> return MarketingVersion.fromTuple(value.split('.')) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f"{self.major}.{self.minor}.{self.patch}" <NEW_LINE> <DEDENT> def asInt(self): <NEW_LINE> <INDENT> return self.major * 65536 + self.minor * 256 + self.patch <NEW_LINE> <DEDENT> def bumpMajor(self) -> 'MarketingVersion': <NEW_LINE> <INDENT> return MarketingVersion(self.major + 1, 0, 0) <NEW_LINE> <DEDENT> def bumpMinor(self) -> 'MarketingVersion': <NEW_LINE> <INDENT> return MarketingVersion(self.major, self.minor + 1, 0) <NEW_LINE> <DEDENT> def bumpPatch(self) -> 'MarketingVersion': <NEW_LINE> <INDENT> return MarketingVersion(self.major, self.minor, self.patch + 1)
Holds the current immutable marketing version. Provides methods to create new values.
62598fc126068e7796d4cbae
class Container(pgu.gui.Container): <NEW_LINE> <INDENT> def __init__(self, **params): <NEW_LINE> <INDENT> super(Container, self).__init__(**params) <NEW_LINE> self.time = pygame.time.get_ticks() <NEW_LINE> pygame.joystick.init() <NEW_LINE> joy = pygame.joystick.Joystick(1) <NEW_LINE> joy.init()
Specialised container widget that knows how to handle joypad
62598fc1bf627c535bcb16f9
class ProgressBar(): <NEW_LINE> <INDENT> _ROUND_DECIMAL_PLACES = 1 <NEW_LINE> def __init__(self, total, status, bar_length): <NEW_LINE> <INDENT> self._status = status <NEW_LINE> self._total = total <NEW_LINE> self._bar_length = bar_length <NEW_LINE> <DEDENT> def update(self, current_length, total=None): <NEW_LINE> <INDENT> total_length = self._total if total is None else total <NEW_LINE> filled_length = int(round(self._bar_length * (current_length / float(total_length)))) <NEW_LINE> percent = round(100.0 * (current_length / float(total_length)), ProgressBar._ROUND_DECIMAL_PLACES) <NEW_LINE> bar = '=' * filled_length + '-' * (self._bar_length - filled_length) <NEW_LINE> sys.stdout.write('[{0}] {1}{2} ...{3}\r'.format(bar, percent, '%', self._status)) <NEW_LINE> sys.stdout.flush() <NEW_LINE> <DEDENT> def clean(self): <NEW_LINE> <INDENT> sys.stdout.write(u'\u001b[1000D') <NEW_LINE> sys.stdout.flush()
Animated progress bar to track progress of processing.
62598fc176e4537e8c3ef7f9
class DownsampleAlongH(snt.AbstractModule): <NEW_LINE> <INDENT> def __init__(self, factor, ptype = 'AVG', padding = 'SAME', verbose = False, name = "downsample_along_h"): <NEW_LINE> <INDENT> super(DownsampleAlongH, self).__init__(name = name) <NEW_LINE> self._factor = factor <NEW_LINE> self._ptype = ptype <NEW_LINE> self._padding = padding <NEW_LINE> if verbose: <NEW_LINE> <INDENT> print('Downsample type: {}, factor: {}, padding: {}'.format(ptype, factor, padding)) <NEW_LINE> <DEDENT> <DEDENT> def _build(self, inputs): <NEW_LINE> <INDENT> return tf.nn.pool(inputs, [self._factor, 1], self._ptype, self._padding, strides = [self._factor, 1])
Downsampling by taking every n by n entries along H (rows)
62598fc1956e5f7376df57a8
class AreaWeightedRegridder(object): <NEW_LINE> <INDENT> def __init__(self, src_grid_cube, target_grid_cube, mdtol=1): <NEW_LINE> <INDENT> self._src_grid = snapshot_grid(src_grid_cube) <NEW_LINE> self._target_grid = snapshot_grid(target_grid_cube) <NEW_LINE> if not (0 <= mdtol <= 1): <NEW_LINE> <INDENT> msg = 'Value for mdtol must be in range 0 - 1, got {}.' <NEW_LINE> raise ValueError(msg.format(mdtol)) <NEW_LINE> <DEDENT> self._mdtol = mdtol <NEW_LINE> self._target_grid_cube_cache = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def _target_grid_cube(self): <NEW_LINE> <INDENT> if self._target_grid_cube_cache is None: <NEW_LINE> <INDENT> x, y = self._target_grid <NEW_LINE> data = np.empty((y.points.size, x.points.size)) <NEW_LINE> cube = iris.cube.Cube(data) <NEW_LINE> cube.add_dim_coord(y, 0) <NEW_LINE> cube.add_dim_coord(x, 1) <NEW_LINE> self._target_grid_cube_cache = cube <NEW_LINE> <DEDENT> return self._target_grid_cube_cache <NEW_LINE> <DEDENT> def __call__(self, cube): <NEW_LINE> <INDENT> if get_xy_dim_coords(cube) != self._src_grid: <NEW_LINE> <INDENT> raise ValueError('The given cube is not defined on the same ' 'source grid as this regridder.') <NEW_LINE> <DEDENT> return eregrid.regrid_area_weighted_rectilinear_src_and_grid( cube, self._target_grid_cube, mdtol=self._mdtol)
This class provides support for performing area-weighted regridding.
62598fc14527f215b58ea122
class RelatedUserQuerySet(models.QuerySet): <NEW_LINE> <INDENT> def api(self, user=None): <NEW_LINE> <INDENT> if not user.is_authenticated: <NEW_LINE> <INDENT> return self.none() <NEW_LINE> <DEDENT> return self.filter(users=user)
For models with relations through :py:class:`User`.
62598fc19f288636728189a5
class CreateUserView(CreateAPIView): <NEW_LINE> <INDENT> serializer_class = serializers.UserSerializer <NEW_LINE> permission_classes = (AllowAny,)
Endpoint for creating new Users
62598fc197e22403b383b15c
class Ball: <NEW_LINE> <INDENT> def __init__(self, color=0): <NEW_LINE> <INDENT> self.color = color <NEW_LINE> self.selected = False <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.color == other.color <NEW_LINE> <DEDENT> def set_color(self, color): <NEW_LINE> <INDENT> self.color = color <NEW_LINE> <DEDENT> def set_random_color(self, number_of_colors): <NEW_LINE> <INDENT> self.color = randint(1, number_of_colors)
Class implementing a ball object
62598fc197e22403b383b15d
class RepeatUntil(Subconstruct): <NEW_LINE> <INDENT> __slots__ = ["predicate"] <NEW_LINE> def __init__(self, predicate, subcon): <NEW_LINE> <INDENT> super(RepeatUntil, self).__init__(subcon) <NEW_LINE> self.predicate = predicate <NEW_LINE> <DEDENT> def _parse(self, stream, context, path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> obj = ListContainer() <NEW_LINE> while True: <NEW_LINE> <INDENT> subobj = self.subcon._parse(stream, context, path) <NEW_LINE> obj.append(subobj) <NEW_LINE> if self.predicate(subobj, context): <NEW_LINE> <INDENT> return obj <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except ExplicitError: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> except ConstructError: <NEW_LINE> <INDENT> raise RangeError("missing terminator when parsing") <NEW_LINE> <DEDENT> <DEDENT> def _build(self, obj, stream, context, path): <NEW_LINE> <INDENT> for subobj in obj: <NEW_LINE> <INDENT> self.subcon._build(subobj, stream, context, path) <NEW_LINE> if self.predicate(subobj, context): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise RangeError("missing terminator when building") <NEW_LINE> <DEDENT> <DEDENT> def _sizeof(self, context, path): <NEW_LINE> <INDENT> raise SizeofError("cannot calculate size")
An array that repeats until the predicate indicates it to stop. Note that the last element (which caused the repeat to exit) is included in the return value. :param predicate: a predicate function that takes (obj, context) and returns True to break, or False to continue :param subcon: the subcon used to parse and build each element Example:: >>> RepeatUntil(lambda x,ctx: x>7, Byte).build(range(20)) b'\x00\x01\x02\x03\x04\x05\x06\x07\x08' >>> RepeatUntil(lambda x,ctx: x>7, Byte).parse(b"\x01\xff\x02") [1, 255]
62598fc14c3428357761a50f
class SpecialOp(Basic): <NEW_LINE> <INDENT> def __new__(cls, op, arg1, arg2): <NEW_LINE> <INDENT> return Basic.__new__(cls, op, arg1, arg2)
Represents the results of operations with NonBasic and NonExpr
62598fc155399d3f0562676a
class Plugin(HasherPlugin): <NEW_LINE> <INDENT> def __init__(self, context): <NEW_LINE> <INDENT> super().__init__('KECCAK 224', "Thomas Engel", ["_pysha3"], context) <NEW_LINE> <DEDENT> def run(self, text): <NEW_LINE> <INDENT> import _pysha3 <NEW_LINE> return _pysha3.keccak_224(text.encode('utf-8', errors='surrogateescape')).hexdigest()
Hashes a string using KECCAK 224. Example: Input: abcdefghijklmnopqrstuvwxyz ^°!"§$%&/()=?´`<>| ,.-;:_#+'*~ 0123456789 Output: dbf87ddd2f01eb7f172b18d94baf83ace62cb71c6ec2b5c82bdf2bab
62598fc150812a4eaa620d13
class CardProvider(ProviderBase): <NEW_LINE> <INDENT> def get_by_id(self, card_id): <NEW_LINE> <INDENT> json_obj = self.get_json('/cards/'+card_id, query_params = {'badges': False}) <NEW_LINE> return Card.from_json(json_obj) <NEW_LINE> <DEDENT> def get_cards(self, list_id): <NEW_LINE> <INDENT> json_obj = self.get_json('/lists/'+list_id+'/cards') <NEW_LINE> return Card.from_json_list(json_obj)
Provider class used to manage the Trello API operations
62598fc17d847024c075c610
class ISharedStockData(ISharedData): <NEW_LINE> <INDENT> pass
Interface for accessing shared stock data.
62598fc14428ac0f6e658778
class GridDataManager(): <NEW_LINE> <INDENT> def __init__(self, filename): <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> <DEDENT> def writeGridData(self, gridData): <NEW_LINE> <INDENT> with open(self.filename, 'w', newline = '') as file: <NEW_LINE> <INDENT> writer = csv.writer(file, delimiter = '\t') <NEW_LINE> csvFileHeader = [''] + [i for i in range(0, len(gridData[0]))] <NEW_LINE> writer.writerow(csvFileHeader) <NEW_LINE> for li in range(0, len(gridData)): <NEW_LINE> <INDENT> line = [li] + gridData[li] <NEW_LINE> writer.writerow(line) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def readGridData(self, requiredDimX, requiredDimY): <NEW_LINE> <INDENT> twoDIntMatrix = [] <NEW_LINE> fileNotFoundName = None <NEW_LINE> try: <NEW_LINE> <INDENT> with open(self.filename, 'r') as file: <NEW_LINE> <INDENT> reader = csv.reader(file, delimiter='\t') <NEW_LINE> header = next(reader) <NEW_LINE> dataDimX = len(header) - 1 <NEW_LINE> fillerDimX = 0 <NEW_LINE> if dataDimX < requiredDimX: <NEW_LINE> <INDENT> fillerDimX = requiredDimX - dataDimX <NEW_LINE> <DEDENT> dataDimY = 0 <NEW_LINE> for row in reader: <NEW_LINE> <INDENT> dataDimY += 1 <NEW_LINE> intLst = [int(s) for s in row] <NEW_LINE> cellDataRow = intLst[1:] <NEW_LINE> if fillerDimX > 0: <NEW_LINE> <INDENT> fillerList = [0 for _ in range(fillerDimX)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fillerList = [] <NEW_LINE> <DEDENT> twoDIntMatrix.append(cellDataRow + fillerList) <NEW_LINE> <DEDENT> if dataDimY < requiredDimY: <NEW_LINE> <INDENT> fillerDimY = requiredDimY - dataDimY <NEW_LINE> <DEDENT> for _ in range(fillerDimY): <NEW_LINE> <INDENT> twoDIntMatrix.append([0 for _ in range(requiredDimY)]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except FileNotFoundError as e: <NEW_LINE> <INDENT> fileNotFoundName = e.filename <NEW_LINE> return None, fileNotFoundName <NEW_LINE> <DEDENT> return twoDIntMatrix, fileNotFoundName
This class reads/writes the internal grid data from/to a csv file.
62598fc17047854f4633f628
@needs_auth() <NEW_LINE> class ItemStatesView(APIView): <NEW_LINE> <INDENT> path = "/item/{id}/states" <NEW_LINE> async def get(self) -> JSONResponse: <NEW_LINE> <INDENT> identifier = self.data["id"] <NEW_LINE> item = self.core.item_manager.items.get(identifier) <NEW_LINE> if not item: <NEW_LINE> <INDENT> return self.error( ERROR_ITEM_NOT_FOUND, f"No item found with identifier {identifier}", 404) <NEW_LINE> <DEDENT> return self.json({ "item": item.identifier, "type": item.type, "states": await item.states.dump(), }) <NEW_LINE> <DEDENT> async def post(self) -> JSONResponse: <NEW_LINE> <INDENT> identifier = self.data["id"] <NEW_LINE> item = self.core.item_manager.items.get(identifier) <NEW_LINE> if not item: <NEW_LINE> <INDENT> return self.error( ERROR_ITEM_NOT_FOUND, f"No item found with identifier {identifier}", 404) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> content = (await self.request.content.read()).decode() <NEW_LINE> commit = STATE_COMMIT_SCHEMA( json.loads(content) if content else {}) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> return JSONResponse(error=e) <NEW_LINE> <DEDENT> if not commit.keys() & item.states.states.keys() == commit.keys(): <NEW_LINE> <INDENT> return self.error( ERROR_INVALID_ITEM_STATES, f"The given states {set(commit.keys())} do not comply with " f"accepted states {set(item.states.states.keys())}") <NEW_LINE> <DEDENT> if not item.status == ItemStatus.ONLINE: <NEW_LINE> <INDENT> return JSONResponse( error=ItemNotOnlineError( f"The item {item.identifier} is not online")) <NEW_LINE> <DEDENT> return JSONResponse(dict(ChainMap( *[await item.states.set(state, value) for state, value in commit.items()])))
Item states view
62598fc1a8370b77170f0636
@public <NEW_LINE> class Accept(HelloReturn): <NEW_LINE> <INDENT> __slots__ = ( 'realm', 'authid', 'authrole', 'authmethod', 'authprovider', 'authextra', ) <NEW_LINE> def __init__(self, realm=None, authid=None, authrole=None, authmethod=None, authprovider=None, authextra=None): <NEW_LINE> <INDENT> assert(realm is None or type(realm) == six.text_type) <NEW_LINE> assert(authid is None or type(authid) == six.text_type) <NEW_LINE> assert(authrole is None or type(authrole) == six.text_type) <NEW_LINE> assert(authmethod is None or type(authmethod) == six.text_type) <NEW_LINE> assert(authprovider is None or type(authprovider) == six.text_type) <NEW_LINE> assert(authextra is None or type(authextra) == dict) <NEW_LINE> self.realm = realm <NEW_LINE> self.authid = authid <NEW_LINE> self.authrole = authrole <NEW_LINE> self.authmethod = authmethod <NEW_LINE> self.authprovider = authprovider <NEW_LINE> self.authextra = authextra <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return u"Accept(realm=<{}>, authid=<{}>, authrole=<{}>, authmethod={}, authprovider={}, authextra={})".format(self.realm, self.authid, self.authrole, self.authmethod, self.authprovider, self.authextra)
Information to accept a ``HELLO``.
62598fc1796e427e5384e9ea
class ReduceApply(TensorExpression): <NEW_LINE> <INDENT> def __init__(self, reduce: ReduceFnType, args: Sequence[TensorExpression]): <NEW_LINE> <INDENT> self.reduce = reduce <NEW_LINE> self.lhs = None <NEW_LINE> self.args = tuple(args) <NEW_LINE> <DEDENT> def to_scalar_expression(self) -> ScalarExpression: <NEW_LINE> <INDENT> if self.lhs is None: <NEW_LINE> <INDENT> raise ValueError(f"Cannot scalarize a ReduceApply that has not been " f"bound to its lhs: {self}") <NEW_LINE> <DEDENT> full_args = [self.lhs.to_scalar_expression() ] + [arg.to_scalar_expression() for arg in self.args] <NEW_LINE> return ScalarApplyFn(self.reduce.operator.prim_name, *full_args).expr() <NEW_LINE> <DEDENT> def visit_affine_exprs(self, callback): <NEW_LINE> <INDENT> for ind in self.reduce.reduce_dims: <NEW_LINE> <INDENT> ind.visit_affine_exprs(callback) <NEW_LINE> <DEDENT> for arg in self.args: <NEW_LINE> <INDENT> arg.visit_affine_exprs(callback) <NEW_LINE> <DEDENT> <DEDENT> def collect_uses(self, uses: Set["TensorUse"]): <NEW_LINE> <INDENT> for arg in self.args: <NEW_LINE> <INDENT> arg.collect_uses(uses) <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return f"{repr(self.reduce)}({', '.join(repr(a) for a in self.args)})"
Application of a reduction. This captures the lhs separately (initial value) separately from the rhs.
62598fc1bf627c535bcb16fb
class Vocab(object): <NEW_LINE> <INDENT> def __init__(self, vocab_file, max_size): <NEW_LINE> <INDENT> self._word_to_id = {} <NEW_LINE> self._id_to_word = {} <NEW_LINE> self._count = 0 <NEW_LINE> with open(vocab_file, 'r') as vocab_f: <NEW_LINE> <INDENT> for line in vocab_f: <NEW_LINE> <INDENT> pieces = line.split() <NEW_LINE> if len(pieces) != 2: <NEW_LINE> <INDENT> sys.stderr.write('Bad line: %s\n' % line) <NEW_LINE> continue <NEW_LINE> <DEDENT> if pieces[0] in self._word_to_id: <NEW_LINE> <INDENT> raise ValueError('Duplicated word: %s.' % pieces[0]) <NEW_LINE> <DEDENT> self._word_to_id[pieces[0]] = self._count <NEW_LINE> self._id_to_word[self._count] = pieces[0] <NEW_LINE> self._count += 1 <NEW_LINE> if self._count > max_size: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def CheckVocab(self, word): <NEW_LINE> <INDENT> if word not in self._word_to_id: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self._word_to_id[word] <NEW_LINE> <DEDENT> def WordToId(self, word): <NEW_LINE> <INDENT> if word not in self._word_to_id: <NEW_LINE> <INDENT> return self._word_to_id[UNKNOWN_TOKEN] <NEW_LINE> <DEDENT> return self._word_to_id[word] <NEW_LINE> <DEDENT> def IdToWord(self, word_id): <NEW_LINE> <INDENT> if word_id not in self._id_to_word: <NEW_LINE> <INDENT> raise ValueError('id not found in vocab: %d.' % word_id) <NEW_LINE> <DEDENT> return self._id_to_word[word_id] <NEW_LINE> <DEDENT> def NumIds(self): <NEW_LINE> <INDENT> return self._count
Vocabulary class for mapping words and ids.
62598fc1d486a94d0ba2c226
class EASUpdateMixin(object): <NEW_LINE> <INDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> super(EASUpdateMixin, self).save(*args, **kwargs) <NEW_LINE> expired = False <NEW_LINE> if hasattr(self, 'end_date'): <NEW_LINE> <INDENT> if self.end_date: <NEW_LINE> <INDENT> if isinstance(self.end_date, date): <NEW_LINE> <INDENT> expired = self.end_date < date.today() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> expired = self.end_date < datetime.now() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> expired = False <NEW_LINE> <DEDENT> <DEDENT> if not self.active or expired: <NEW_LINE> <INDENT> for related_object in self._meta.get_all_related_objects(): <NEW_LINE> <INDENT> accessor_name = related_object.get_accessor_name() <NEW_LINE> if not hasattr(self, accessor_name): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> related_queryset = eval('self.%s' % accessor_name) <NEW_LINE> field_name = related_object.field.name <NEW_LINE> for item in related_queryset.all(): <NEW_LINE> <INDENT> setattr(item, field_name, None) <NEW_LINE> item.save()
If it's expired or inactive, unset this object from any foriegn key fields
62598fc13346ee7daa337773
class Meter(Base): <NEW_LINE> <INDENT> __tablename__ = 'meter' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> counter_name = Column(String(255)) <NEW_LINE> sources = relationship("Source", secondary=lambda: sourceassoc) <NEW_LINE> user_id = Column(String(255), ForeignKey('user.id')) <NEW_LINE> project_id = Column(String(255), ForeignKey('project.id')) <NEW_LINE> resource_id = Column(String(255), ForeignKey('resource.id')) <NEW_LINE> resource_metadata = Column(JSONEncodedDict) <NEW_LINE> counter_type = Column(String(255)) <NEW_LINE> counter_volume = Column(Integer) <NEW_LINE> timestamp = Column(DateTime, default=timeutils.utcnow) <NEW_LINE> message_signature = Column(String) <NEW_LINE> message_id = Column(String)
Metering data
62598fc13d592f4c4edbb113
class _SavePoint(object): <NEW_LINE> <INDENT> def __init__(self, db_conn): <NEW_LINE> <INDENT> self.db_conn = db_conn <NEW_LINE> self.ident = str(time.time()).replace('.', 'sp') <NEW_LINE> db_conn._query('SAVEPOINT %s' % self.ident) <NEW_LINE> <DEDENT> def rollback(self): <NEW_LINE> <INDENT> self.db_conn._query('ROLLBACK TO %s' % self.ident)
Simple savepoint object
62598fc192d797404e388c8d
class Slime(Skull): <NEW_LINE> <INDENT> def __init__(self,x,y): <NEW_LINE> <INDENT> self.n = 0 <NEW_LINE> self.pos = (x, y) <NEW_LINE> self.symbol = "K" <NEW_LINE> self.setpos(x, y) <NEW_LINE> self.worth = 100 <NEW_LINE> mobs.append(self) <NEW_LINE> <DEDENT> def AutoMove(self): <NEW_LINE> <INDENT> if self.n == 1: <NEW_LINE> <INDENT> self.n = 0 <NEW_LINE> self.symbol = "B" <NEW_LINE> dis = [1000]*4 <NEW_LINE> try: <NEW_LINE> <INDENT> if Board[self.pos[0]-2][self.pos[1]-1] == "0" or Board[self.pos[0]-2][self.pos[1]-1] == "P": <NEW_LINE> <INDENT> dis[0] = (self.pos[0] - P.pos[0] - 1)**2 + (self.pos[1] - P.pos[1])**2 <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if Board[self.pos[0]-1][self.pos[1]-2] == "0" or Board[self.pos[0]-1][self.pos[1]-2] == "P": <NEW_LINE> <INDENT> dis[1] = (self.pos[0] - P.pos[0])**2 + (self.pos[1] - P.pos[1] - 1)**2 <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if Board[self.pos[0]-1][self.pos[1]] == "0" or Board[self.pos[0]-1][self.pos[1]] == "P": <NEW_LINE> <INDENT> dis[2] = (self.pos[0] - P.pos[0])**2 + (self.pos[1] - P.pos[1] + 1)**2 <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if Board[self.pos[0]][self.pos[1]-1] == "0" or Board[self.pos[0]][self.pos[1]-1] == "P": <NEW_LINE> <INDENT> dis[3] = (self.pos[0] - P.pos[0] + 1)**2 + (self.pos[1] - P.pos[1])**2 <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> Board[self.pos[0]-1][self.pos[1]-1] = self.symbol <NEW_LINE> if min(dis) == dis[0]: <NEW_LINE> <INDENT> self.Move("up") <NEW_LINE> <DEDENT> elif min(dis) == dis[1]: <NEW_LINE> <INDENT> self.Move("left") <NEW_LINE> <DEDENT> elif min(dis) == dis[2]: <NEW_LINE> <INDENT> self.Move("right") <NEW_LINE> <DEDENT> elif min(dis) == dis[3]: <NEW_LINE> <INDENT> self.Move("down") <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.n = 1 <NEW_LINE> self.symbol = 'K' <NEW_LINE> Board[self.pos[0]-1][self.pos[1]-1] = self.symbol
主角每動兩次之後,這隻怪物才會動一次 worth 100 points
62598fc1091ae35668704e7d
class Water(Place): <NEW_LINE> <INDENT> def add_insect(self, insect): <NEW_LINE> <INDENT> "*** REPLACE THIS LINE ***" <NEW_LINE> Place.add_insect(self, insect) <NEW_LINE> if insect.watersafe == False: <NEW_LINE> <INDENT> Insect.reduce_armor(insect, insect.armor)
Water is a place that can only hold 'watersafe' insects.
62598fc1283ffb24f3cf3adb
class InsurancePlanPlan(backboneelement.BackboneElement): <NEW_LINE> <INDENT> resource_type = "InsurancePlanPlan" <NEW_LINE> def __init__(self, jsondict=None, strict=True): <NEW_LINE> <INDENT> self.coverageArea = None <NEW_LINE> self.generalCost = None <NEW_LINE> self.identifier = None <NEW_LINE> self.network = None <NEW_LINE> self.specificCost = None <NEW_LINE> self.type = None <NEW_LINE> super(InsurancePlanPlan, self).__init__(jsondict=jsondict, strict=strict) <NEW_LINE> <DEDENT> def elementProperties(self): <NEW_LINE> <INDENT> js = super(InsurancePlanPlan, self).elementProperties() <NEW_LINE> js.extend([ ("coverageArea", "coverageArea", fhirreference.FHIRReference, True, None, False), ("generalCost", "generalCost", InsurancePlanPlanGeneralCost, True, None, False), ("identifier", "identifier", identifier.Identifier, True, None, False), ("network", "network", fhirreference.FHIRReference, True, None, False), ("specificCost", "specificCost", InsurancePlanPlanSpecificCost, True, None, False), ("type", "type", codeableconcept.CodeableConcept, False, None, False), ]) <NEW_LINE> return js
Plan details. Details about an insurance plan.
62598fc126068e7796d4cbb2
class QLearningAgent(ReinforcementAgent): <NEW_LINE> <INDENT> def __init__(self, **args): <NEW_LINE> <INDENT> ReinforcementAgent.__init__(self, **args) <NEW_LINE> "*** YOUR CODE HERE ***" <NEW_LINE> self.qvalues = util.Counter() <NEW_LINE> <DEDENT> def getQValue(self, state, action): <NEW_LINE> <INDENT> return self.qvalues[(state, action)] <NEW_LINE> <DEDENT> def computeValueFromQValues(self, state): <NEW_LINE> <INDENT> qvalues = [] <NEW_LINE> for action in self.getLegalActions(state): <NEW_LINE> <INDENT> qvalues.append(self.getQValue(state, action)) <NEW_LINE> <DEDENT> if len(qvalues) != 0: <NEW_LINE> <INDENT> return max(qvalues) <NEW_LINE> <DEDENT> return 0.0 <NEW_LINE> <DEDENT> def computeActionFromQValues(self, state): <NEW_LINE> <INDENT> qvalues = [] <NEW_LINE> for action in self.getLegalActions(state): <NEW_LINE> <INDENT> qvalues.append((action, self.getQValue(state, action))) <NEW_LINE> <DEDENT> if len(qvalues) != 0: <NEW_LINE> <INDENT> return max(qvalues, key = lambda item: item[1])[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def getAction(self, state): <NEW_LINE> <INDENT> legalActions = self.getLegalActions(state) <NEW_LINE> action = None <NEW_LINE> if util.flipCoin(self.epsilon): <NEW_LINE> <INDENT> if len(legalActions) != 0: <NEW_LINE> <INDENT> return random.choice(legalActions) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return self.computeActionFromQValues(state) <NEW_LINE> <DEDENT> <DEDENT> def update(self, state, action, nextState, reward): <NEW_LINE> <INDENT> value = self.computeValueFromQValues(nextState) <NEW_LINE> sample = reward + self.discount * value <NEW_LINE> qvalue = self.getQValue(state, action) <NEW_LINE> temp = (1 - self.alpha) * qvalue + self.alpha * sample <NEW_LINE> self.qvalues[(state, action)] = temp <NEW_LINE> <DEDENT> def getPolicy(self, state): <NEW_LINE> <INDENT> return self.computeActionFromQValues(state) <NEW_LINE> <DEDENT> def getValue(self, state): <NEW_LINE> <INDENT> return self.computeValueFromQValues(state)
Q-Learning Agent Functions you should fill in: - computeValueFromQValues - computeActionFromQValues - getQValue - getAction - update Instance variables you have access to - self.epsilon (exploration prob) - self.alpha (learning rate) - self.discount (discount rate) Functions you should use - self.getLegalActions(state) which returns legal actions for a state
62598fc17cff6e4e811b5c7b
class GameState: <NEW_LINE> <INDENT> def __init__(self, n_human_players=1, n_ai_players=1, n_cards=10): <NEW_LINE> <INDENT> self.n_cards = n_cards <NEW_LINE> with open("cards-against-humanity/answers.pickle", 'rb') as ans: <NEW_LINE> <INDENT> self.answer_cards = pickle.load(ans) <NEW_LINE> shuffle(self.answer_cards) <NEW_LINE> <DEDENT> self.used_answers = 0 <NEW_LINE> with open("cards-against-humanity/questions.pickle", 'rb') as qs: <NEW_LINE> <INDENT> self.question_cards = pickle.load(qs) <NEW_LINE> shuffle(self.question_cards) <NEW_LINE> <DEDENT> self.used_questions = 0 <NEW_LINE> self.human_players = [] <NEW_LINE> for _ in range(n_human_players): <NEW_LINE> <INDENT> self.human_players.append(HumanPlayer(Player(self, n_cards))) <NEW_LINE> <DEDENT> self.ai_players = [] <NEW_LINE> for _ in range(n_ai_players): <NEW_LINE> <INDENT> self.ai_players.append(AIPlayer(Player(self, n_cards))) <NEW_LINE> <DEDENT> <DEDENT> def pop_ans(self, n_cards): <NEW_LINE> <INDENT> cards = self.answer_cards[self.used_answers : self.used_answers + n_cards] <NEW_LINE> self.used_answers += n_cards <NEW_LINE> return cards <NEW_LINE> <DEDENT> def pop_q(self): <NEW_LINE> <INDENT> card = self.question_cards[self.used_questions] <NEW_LINE> self.used_questions += 1 <NEW_LINE> while card.count("_") != 1: <NEW_LINE> <INDENT> card = self.question_cards[self.used_questions] <NEW_LINE> self.used_questions += 1 <NEW_LINE> <DEDENT> self.current_question = card <NEW_LINE> return self.current_question <NEW_LINE> <DEDENT> def set_question(self, q): <NEW_LINE> <INDENT> self.current_question = q <NEW_LINE> <DEDENT> def choose_ai_answer(self): <NEW_LINE> <INDENT> score_list=[] <NEW_LINE> for i in self.ai_players[0].player.card_strings: <NEW_LINE> <INDENT> phrase = self.current_question.replace("_", i) <NEW_LINE> temp = amazon_sentiment_score(phrase) <NEW_LINE> temp_sum = temp['Positive']+temp['Negative'] <NEW_LINE> current_score=(temp['Positive']-temp['Negative'])/temp_sum <NEW_LINE> score_list.append((current_score+1)/2) <NEW_LINE> <DEDENT> results = freq_expectation(np.array(score_list), self.ai_players[0].trace) <NEW_LINE> print(results) <NEW_LINE> my_answer= self.ai_players[0].player.card_strings[np.argmax(results)] <NEW_LINE> return self.current_question.replace("_", my_answer )
Store the gamestate.
62598fc176e4537e8c3ef7fd
class Species(SrcClass): <NEW_LINE> <INDENT> def __init__(self, args=cf.config_args()): <NEW_LINE> <INDENT> name = 'species' <NEW_LINE> url_base = 'ftp.ncbi.nih.gov' <NEW_LINE> aliases = {"species_map": "mapping file for species"} <NEW_LINE> super(Species, self).__init__(name, url_base, aliases, args) <NEW_LINE> self.remote_file = 'names.dmp' <NEW_LINE> <DEDENT> def get_remote_file_size(self, alias): <NEW_LINE> <INDENT> ftp = ftplib.FTP(self.url_base) <NEW_LINE> ftp.login() <NEW_LINE> ftp.cwd('/pub/taxonomy/') <NEW_LINE> ftp.voidcmd('TYPE I') <NEW_LINE> file_size = ftp.size('taxdmp.zip') <NEW_LINE> ftp.quit() <NEW_LINE> return file_size <NEW_LINE> <DEDENT> def get_remote_file_modified(self, alias): <NEW_LINE> <INDENT> ftp = ftplib.FTP(self.url_base) <NEW_LINE> ftp.login() <NEW_LINE> ftp.cwd('/pub/taxonomy/') <NEW_LINE> time_str = ftp.sendcmd('MDTM taxdmp.zip') <NEW_LINE> time_str = time_str[4:] <NEW_LINE> ftp.quit() <NEW_LINE> time_format = "%Y%m%d%H%M%S" <NEW_LINE> return time.mktime(time.strptime(time_str, time_format)) <NEW_LINE> <DEDENT> def get_remote_url(self, alias): <NEW_LINE> <INDENT> url = self.url_base + '/pub/taxonomy/taxdmp.zip' <NEW_LINE> return 'ftp://' + url <NEW_LINE> <DEDENT> def create_mapping_dict(self, filename, key_col=3, value_col=4): <NEW_LINE> <INDENT> species = dict() <NEW_LINE> species2taxid = dict() <NEW_LINE> with open(filename, encoding='utf-8') as infile: <NEW_LINE> <INDENT> reader = csv.reader((line.replace('\t|', '') for line in infile), delimiter='\t', quoting=csv.QUOTE_NONE) <NEW_LINE> for full_line in reader: <NEW_LINE> <INDENT> line = full_line[3:] <NEW_LINE> if line[3] == 'scientific name': <NEW_LINE> <INDENT> taxid = line[0] <NEW_LINE> sci_name = line[1] <NEW_LINE> uniq_name = line[2] <NEW_LINE> if uniq_name == '': <NEW_LINE> <INDENT> uniq_name = sci_name <NEW_LINE> <DEDENT> if ' ' in sci_name: <NEW_LINE> <INDENT> abbr_name = sci_name[0] + sci_name[sci_name.find(' ') + 1:][:3] <NEW_LINE> <DEDENT> else: abbr_name = sci_name[:4] <NEW_LINE> species[taxid] = dict() <NEW_LINE> species[taxid]['scientific_name'] = sci_name <NEW_LINE> species[taxid]['unique_name'] = uniq_name <NEW_LINE> species[taxid]['abbreviated_name'] = abbr_name <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> with open('species.json', 'w') as outfile: <NEW_LINE> <INDENT> json.dump(species, outfile, indent=4, sort_keys=True) <NEW_LINE> <DEDENT> for key in species: <NEW_LINE> <INDENT> s_name = species[key]['unique_name'] <NEW_LINE> species2taxid[s_name] = key <NEW_LINE> <DEDENT> return species2taxid
Extends SrcClass to provide species specific check functions. This Species class provides source-specific functions that check the species version information and determine if it differs from the current version in the Knowledge Network (KN). Attributes: see utilities.SrcClass
62598fc1aad79263cf42ea2c
class FaceLandmarksDataset(Dataset): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.csv_file = '../ext_face/cropped_global_300w.csv' <NEW_LINE> self.globalDF = pd.read_csv(self.csv_file) <NEW_LINE> self.g_images = self.globalDF['imgPath'] <NEW_LINE> self.save_dir = '/media/drive/ibug/300W_cropped/frcnn/' <NEW_LINE> self.save_dir_adv = '/media/drive/ibug/300W_cropped/frcnn_adv/' <NEW_LINE> self.save_dir_comb = '/media/drive/ibug/300W_cropped/frcnn_comb/' <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.g_images) <NEW_LINE> <DEDENT> def __getitem__(self, idx): <NEW_LINE> <INDENT> img = read_image(self.g_images[idx]) <NEW_LINE> _, H, W = img.shape <NEW_LINE> scale = H / H <NEW_LINE> try: <NEW_LINE> <INDENT> img = preprocess(img) <NEW_LINE> img, params = util.random_flip( img, x_random=True, return_param=True) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print("Exception") <NEW_LINE> <DEDENT> img = torch.from_numpy(img)[None] <NEW_LINE> return img,self.g_images[idx],scale
Face Landmarks dataset.
62598fc1d8ef3951e32c7f89
class SerialDictSlot(SerialSlot): <NEW_LINE> <INDENT> def __init__(self, slot, inslot=None, name=None, subname=None, default=None, depends=None, selfdepends=True, transform=None): <NEW_LINE> <INDENT> super(SerialDictSlot, self).__init__( slot, inslot, name, subname, default, depends, selfdepends ) <NEW_LINE> if transform is None: <NEW_LINE> <INDENT> transform = lambda x: x <NEW_LINE> <DEDENT> self.transform = transform <NEW_LINE> <DEDENT> def _saveValue(self, group, name, value): <NEW_LINE> <INDENT> sg = group.create_group(name) <NEW_LINE> for key, v in value.iteritems(): <NEW_LINE> <INDENT> if isinstance(v, dict): <NEW_LINE> <INDENT> self._saveValue(sg, key, v) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sg.create_dataset(str(key), data=v) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _getValueHelper(self, subgroup): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for key in subgroup.keys(): <NEW_LINE> <INDENT> if isinstance(subgroup[key], h5py.Group): <NEW_LINE> <INDENT> value = self._getValueHelper(subgroup[key]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> value = subgroup[key][()] <NEW_LINE> <DEDENT> result[self.transform(key)] = value <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def _getValue(self, subgroup, slot): <NEW_LINE> <INDENT> result = self._getValueHelper(subgroup) <NEW_LINE> try: <NEW_LINE> <INDENT> slot.setValue(result) <NEW_LINE> <DEDENT> except AssertionError as e: <NEW_LINE> <INDENT> warnings.warn('setValue() failed. message: {}'.format(e.message))
For saving a dictionary.
62598fc13d592f4c4edbb114
class DownloadTeacherDataView(grok.View): <NEW_LINE> <INDENT> grok.context(Interface) <NEW_LINE> grok.name('download-teacher-data') <NEW_LINE> grok.require('cmf.ManagePortal') <NEW_LINE> def __call__(self): <NEW_LINE> <INDENT> view = self.context.restrictedTraverse('@@upload-to-server') <NEW_LINE> zip_data = view.zip_csv() <NEW_LINE> now = DateTime() <NEW_LINE> nice_filename = '%s_%s' % ('tarmii_logs_',now.strftime('%Y%m%d')) <NEW_LINE> self.request.response.setHeader("Content-Disposition", "attachment; filename=%s.zip" % nice_filename) <NEW_LINE> self.request.response.setHeader("Content-Type", 'application/octet-stream') <NEW_LINE> self.request.response.setHeader("Content-Length", len(zip_data)) <NEW_LINE> self.request.response.setHeader('Last-Modified', DateTime.rfc822(DateTime())) <NEW_LINE> self.request.response.setHeader("Cache-Control", "no-store") <NEW_LINE> self.request.response.setHeader("Pragma", "no-cache") <NEW_LINE> self.request.response.write(zip_data) <NEW_LINE> <DEDENT> def render(self): <NEW_LINE> <INDENT> return ''
Return the teacher data from uploadtoserver view as a http response.
62598fc197e22403b383b160
class FlickrObject(object): <NEW_LINE> <INDENT> __converters__ = [] <NEW_LINE> __display__ = [] <NEW_LINE> def __init__(self,**params): <NEW_LINE> <INDENT> params["loaded"] = False <NEW_LINE> self._set_properties(**params) <NEW_LINE> <DEDENT> def _set_properties(self,**params): <NEW_LINE> <INDENT> for c in self.__class__.__converters__ : <NEW_LINE> <INDENT> c(params) <NEW_LINE> <DEDENT> self.__dict__.update(params) <NEW_LINE> <DEDENT> def __getattr__(self,name): <NEW_LINE> <INDENT> if not self.loaded : <NEW_LINE> <INDENT> self.load() <NEW_LINE> <DEDENT> if self.loaded : raise AttributeError("'%s' object has no attribute '%s'"%(self.__class__.__name__,name)) <NEW_LINE> <DEDENT> def __setattr__(self,name,values): <NEW_LINE> <INDENT> raise FlickrError("Readonly attribute") <NEW_LINE> <DEDENT> def get(self,key,*args,**kwargs): <NEW_LINE> <INDENT> return self.__dict__.get(key,*args,**kwargs) <NEW_LINE> <DEDENT> def __getitem__(self,key): <NEW_LINE> <INDENT> return self.__dict__[key] <NEW_LINE> <DEDENT> def __setitem__(self,key,value): <NEW_LINE> <INDENT> raise FlickrError("Read-only attribute") <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> vals = [] <NEW_LINE> for k in self.__class__.__display__ : <NEW_LINE> <INDENT> val_found = False <NEW_LINE> try : <NEW_LINE> <INDENT> value = self.__dict__[k] <NEW_LINE> val_found = True <NEW_LINE> <DEDENT> except KeyError : <NEW_LINE> <INDENT> self.load() <NEW_LINE> try : <NEW_LINE> <INDENT> value = self.__dict__[k] <NEW_LINE> val_found = True <NEW_LINE> <DEDENT> except KeyError : pass <NEW_LINE> <DEDENT> if not val_found : continue <NEW_LINE> if isinstance(value,unicode): <NEW_LINE> <INDENT> value = value.encode("utf8") <NEW_LINE> <DEDENT> if isinstance(value,str): <NEW_LINE> <INDENT> value = "'%s'"%value <NEW_LINE> <DEDENT> else : value = str(value) <NEW_LINE> if len(value) > 20: value = value[:20]+"..." <NEW_LINE> vals.append("%s = %s"%(k,value)) <NEW_LINE> <DEDENT> return "%s(%s)"%(self.__class__.__name__,", ".join(vals)) <NEW_LINE> <DEDENT> def __repr__(self): return str(self) <NEW_LINE> def getInfo(self): <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> def load(self): <NEW_LINE> <INDENT> props = self.getInfo() <NEW_LINE> self.__dict__["loaded"] = True <NEW_LINE> self._set_properties(**props)
Base Object for Flickr API Objects
62598fc163b5f9789fe853c9
class TestDDPG: <NEW_LINE> <INDENT> @pytest.mark.large <NEW_LINE> def test_ddpg_double_pendulum(self): <NEW_LINE> <INDENT> deterministic.set_seed(0) <NEW_LINE> runner = LocalRunner(snapshot_config) <NEW_LINE> env = MetaRLEnv(gym.make('InvertedDoublePendulum-v2')) <NEW_LINE> action_noise = OUStrategy(env.spec, sigma=0.2) <NEW_LINE> policy = DeterministicMLPPolicy(env_spec=env.spec, hidden_sizes=[64, 64], hidden_nonlinearity=F.relu, output_nonlinearity=torch.tanh) <NEW_LINE> qf = ContinuousMLPQFunction(env_spec=env.spec, hidden_sizes=[64, 64], hidden_nonlinearity=F.relu) <NEW_LINE> replay_buffer = SimpleReplayBuffer(env_spec=env.spec, size_in_transitions=int(1e6), time_horizon=100) <NEW_LINE> algo = DDPG(env_spec=env.spec, policy=policy, qf=qf, replay_buffer=replay_buffer, steps_per_epoch=20, n_train_steps=50, min_buffer_size=int(1e4), exploration_strategy=action_noise, target_update_tau=1e-2, discount=0.9) <NEW_LINE> runner.setup(algo, env) <NEW_LINE> last_avg_ret = runner.train(n_epochs=10, batch_size=100) <NEW_LINE> assert last_avg_ret > 45 <NEW_LINE> env.close() <NEW_LINE> <DEDENT> @pytest.mark.large <NEW_LINE> def test_ddpg_pendulum(self): <NEW_LINE> <INDENT> deterministic.set_seed(0) <NEW_LINE> runner = LocalRunner(snapshot_config) <NEW_LINE> env = MetaRLEnv(normalize(gym.make('InvertedPendulum-v2'))) <NEW_LINE> action_noise = OUStrategy(env.spec, sigma=0.2) <NEW_LINE> policy = DeterministicMLPPolicy(env_spec=env.spec, hidden_sizes=[64, 64], hidden_nonlinearity=F.relu, output_nonlinearity=torch.tanh) <NEW_LINE> qf = ContinuousMLPQFunction(env_spec=env.spec, hidden_sizes=[64, 64], hidden_nonlinearity=F.relu) <NEW_LINE> replay_buffer = SimpleReplayBuffer(env_spec=env.spec, size_in_transitions=int(1e6), time_horizon=100) <NEW_LINE> algo = DDPG(env_spec=env.spec, policy=policy, qf=qf, replay_buffer=replay_buffer, steps_per_epoch=20, n_train_steps=50, min_buffer_size=int(1e4), exploration_strategy=action_noise, target_update_tau=1e-2, discount=0.9) <NEW_LINE> runner.setup(algo, env) <NEW_LINE> last_avg_ret = runner.train(n_epochs=10, batch_size=100) <NEW_LINE> assert last_avg_ret > 10 <NEW_LINE> env.close()
Test class for DDPG.
62598fc123849d37ff85130b
class NetworkInterfaceLoadBalancerListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'next_link': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': '[LoadBalancer]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(NetworkInterfaceLoadBalancerListResult, self).__init__(**kwargs) <NEW_LINE> self.value = kwargs.get('value', None) <NEW_LINE> self.next_link = None
Response for list ip configurations API service call. Variables are only populated by the server, and will be ignored when sending a request. :param value: A list of load balancers. :type value: list[~azure.mgmt.network.v2019_07_01.models.LoadBalancer] :ivar next_link: The URL to get the next set of results. :vartype next_link: str
62598fc1167d2b6e312b71ce
class PPMI(Counter): <NEW_LINE> <INDENT> def __init__(self, sentences, winSize=5, minCount=5): <NEW_LINE> <INDENT> super().__init__(self, sentences, winSize, minCount) <NEW_LINE> self.cooccurence = [[]] <NEW_LINE> self.unigram_counts = [] <NEW_LINE> <DEDENT> def build_vocabulary(self): <NEW_LINE> <INDENT> super().build_vocabulary() <NEW_LINE> self.cooccurence = np.zeros((self.size, self.size)) <NEW_LINE> self.ppmi = np.zeros((self.size, self.size)) <NEW_LINE> <DEDENT> def compute_cooccurence(self): <NEW_LINE> <INDENT> logging.info("Filling cooccurence matrix") <NEW_LINE> for s in self.sentences: <NEW_LINE> <INDENT> for index, word in enumerate(s): <NEW_LINE> <INDENT> word_id = len(self.id2word) <NEW_LINE> if word in self.word2id.keys(): <NEW_LINE> <INDENT> word_id = self.word2id[word] <NEW_LINE> for context in s[max(0, index - self.context_size):min(len(s), index + self.context_size + 1)]: <NEW_LINE> <INDENT> context_id = len(self.id2word) <NEW_LINE> if context in self.word2id.keys(): <NEW_LINE> <INDENT> context_id = self.word2id[context] <NEW_LINE> if context != word: <NEW_LINE> <INDENT> self.cooccurence[word_id, context_id] += 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> logging.info("Cooccurence matrix computed") <NEW_LINE> <DEDENT> def compute_ppmi(self): <NEW_LINE> <INDENT> logging.info("PPMI computation") <NEW_LINE> total = np.sum(self.cooccurence) <NEW_LINE> pi_ = np.apply_along_axis(np.sum, 1, self.cooccurence) <NEW_LINE> p_j = np.apply_along_axis(np.sum, 0, self.cooccurence) <NEW_LINE> for i in range(len(pi_)): <NEW_LINE> <INDENT> for j in range(len(p_j)): <NEW_LINE> <INDENT> temp = self.cooccurence[i, j] <NEW_LINE> if temp != 0: <NEW_LINE> <INDENT> self.ppmi[i, j] = max(0, np.log2(total * temp / (pi_[i] * p_j[j]))) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> logging.info("PPMI done")
Positive pointwise mutual information Extends the Counter class with some additional function to compute a ppmi matrix that could be used to initialize embedddings. Deprecated ?
62598fc171ff763f4b5e79d4
class StatisticsBaseEntity(ToyotaBaseEntity, SensorEntity): <NEW_LINE> <INDENT> _attr_icon = ICON_HISTORY <NEW_LINE> @property <NEW_LINE> def native_unit_of_measurement(self): <NEW_LINE> <INDENT> return self.vehicle.odometer.unit <NEW_LINE> <DEDENT> def get_statistics_attributes(self, statistics): <NEW_LINE> <INDENT> def get_timedelta(time): <NEW_LINE> <INDENT> return str(timedelta(seconds=time)) <NEW_LINE> <DEDENT> attr = { "Highway_distance": round(statistics.get(HIGHWAY_DISTANCE, 0), 1), "Highway_percentage": round( statistics.get(HIGHWAY_DISTANCE_PERCENTAGE, 0), 1 ), "Number_of_trips": statistics.get(TRIPS, 0), "Number_of_night_trips": statistics.get(NIGHT_TRIPS, 0), "Total_driving_time": get_timedelta(statistics.get(TOTAL_DURATION, 0)), "Average_speed": round(statistics.get(AVERAGE_SPEED, 0), 1), "Max_speed": round(statistics.get(MAX_SPEED, 0), 1), "Hard_acceleration_count": statistics.get(HARD_ACCELERATION, 0), "Hard_braking_count": statistics.get(HARD_BRAKING, 0), } <NEW_LINE> if FUEL_CONSUMED in statistics: <NEW_LINE> <INDENT> attr.update( { "Average_fuel_consumed": round(statistics.get(FUEL_CONSUMED, 0), 2), } ) <NEW_LINE> <DEDENT> if COACHING_ADVICE in statistics: <NEW_LINE> <INDENT> attr.update( { "Coaching_advice_most_occurrence": statistics.get( COACHING_ADVICE, 0 ), } ) <NEW_LINE> <DEDENT> if DRIVER_SCORE in statistics: <NEW_LINE> <INDENT> attr.update( { "Average_driver_score": round(statistics.get(DRIVER_SCORE, 0), 1), "Average_driver_score_accelerations": round( statistics.get(DRIVER_SCORE_ACCELERATIONS, 0), 1 ), "Average_driver_score_braking": round( statistics.get(DRIVER_SCORE_BRAKING, 0), 1 ), } ) <NEW_LINE> <DEDENT> if self.vehicle.details[HYBRID]: <NEW_LINE> <INDENT> attr.update( { "EV_distance": round(statistics.get(EV_DISTANCE, 0), 1), "EV_driving_time": get_timedelta(statistics.get(EV_DURATION, 0)), "EV_distance_percentage": round( statistics.get(EV_DISTANCE_PERCENTAGE, 0), 1 ), "EV_duration_percentage": round( statistics.get(EV_DURATION_PERCENTAGE, 0), 1 ), } ) <NEW_LINE> <DEDENT> return attr
Builds on Toyota base entity
62598fc14a966d76dd5ef12d
class CRideModel(models.Model): <NEW_LINE> <INDENT> created = models.DateTimeField( 'created at', auto_now_add=True, help_text='Date time on which the object was created.' ) <NEW_LINE> modified = models.DateTimeField( 'modified at', auto_now=True, help_text='Date time on which the object was last modified.' ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> get_latest_by = 'created' <NEW_LINE> ordering = ['-created', '-modified']
Comparte Ride base model. CRideModel acts as an abstract base class from which every other model in the project will inherit. This class provides every table with the following attributes: + created (DateTime): Store the datetime the object was created. + modified (DateTime): Store the last datetime the object was modified.
62598fc166673b3332c3062b
class GaussianMixtureModel(Configurable[GaussianMixtureModelConfig], nn.Module): <NEW_LINE> <INDENT> component_probs: torch.Tensor <NEW_LINE> means: torch.Tensor <NEW_LINE> precisions_cholesky: torch.Tensor <NEW_LINE> def __init__(self, config: GaussianMixtureModelConfig): <NEW_LINE> <INDENT> super().__init__(config) <NEW_LINE> self.covariance_type = config.covariance_type <NEW_LINE> self.register_buffer("component_probs", torch.empty(config.num_components)) <NEW_LINE> self.register_buffer("means", torch.empty(config.num_components, config.num_features)) <NEW_LINE> shape = covariance_shape( config.num_components, config.num_features, config.covariance_type ) <NEW_LINE> self.register_buffer("precisions_cholesky", torch.empty(shape)) <NEW_LINE> self.reset_parameters() <NEW_LINE> <DEDENT> @jit.unused <NEW_LINE> def reset_parameters(self) -> None: <NEW_LINE> <INDENT> nn.init.uniform_(self.component_probs) <NEW_LINE> self.component_probs.div_(self.component_probs.sum()) <NEW_LINE> nn.init.normal_(self.means) <NEW_LINE> nn.init.uniform_(self.precisions_cholesky) <NEW_LINE> if self.covariance_type == "full": <NEW_LINE> <INDENT> self.precisions_cholesky.copy_( self.precisions_cholesky.bmm(self.precisions_cholesky.transpose(-1, -2)) ) <NEW_LINE> <DEDENT> elif self.covariance_type == "tied": <NEW_LINE> <INDENT> self.precisions_cholesky.copy_( self.precisions_cholesky.mm(self.precisions_cholesky.t()) ) <NEW_LINE> <DEDENT> <DEDENT> def forward(self, data: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: <NEW_LINE> <INDENT> log_probabilities = jit_log_normal( data, self.means, self.precisions_cholesky, self.covariance_type ) <NEW_LINE> log_responsibilities = log_probabilities + self.component_probs.log() <NEW_LINE> log_prob = log_responsibilities.logsumexp(1, keepdim=True) <NEW_LINE> return log_responsibilities - log_prob, log_prob.squeeze(1) <NEW_LINE> <DEDENT> def sample(self, num_datapoints: int) -> torch.Tensor: <NEW_LINE> <INDENT> component_counts = np.random.multinomial(num_datapoints, self.component_probs.numpy()) <NEW_LINE> result = [] <NEW_LINE> for i, count in enumerate(component_counts): <NEW_LINE> <INDENT> sample = jit_sample_normal( count.item(), self.means[i], self._get_component_precision(i), self.covariance_type, ) <NEW_LINE> result.append(sample) <NEW_LINE> <DEDENT> return torch.cat(result, dim=0) <NEW_LINE> <DEDENT> def _get_component_precision(self, component: int) -> torch.Tensor: <NEW_LINE> <INDENT> if self.covariance_type == "tied": <NEW_LINE> <INDENT> return self.precisions_cholesky <NEW_LINE> <DEDENT> return self.precisions_cholesky[component]
PyTorch module for a Gaussian mixture model. Covariances are represented via their Cholesky decomposition for computational efficiency. The model does not have trainable parameters.
62598fc15166f23b2e243638
class AiReviewProhibitedAsrTaskInput(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Definition = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Definition = params.get("Definition")
内容审核 Asr 文字鉴违禁任务输入参数类型
62598fc1aad79263cf42ea2e
class _FrozenSetMeta(GenericMeta): <NEW_LINE> <INDENT> def __subclasscheck__(self, cls): <NEW_LINE> <INDENT> if issubclass(cls, Set): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return super().__subclasscheck__(cls)
This metaclass ensures set is not a subclass of FrozenSet. Without this metaclass, set would be considered a subclass of FrozenSet, because FrozenSet.__extra__ is collections.abc.Set, and set is a subclass of that.
62598fc14c3428357761a515
class ReadNamespacedJob(Task): <NEW_LINE> <INDENT> def __init__( self, job_name: str = None, namespace: str = "default", kube_kwargs: dict = None, kubernetes_api_key_secret: str = "KUBERNETES_API_KEY", **kwargs: Any ): <NEW_LINE> <INDENT> self.job_name = job_name <NEW_LINE> self.namespace = namespace <NEW_LINE> self.kube_kwargs = kube_kwargs or {} <NEW_LINE> self.kubernetes_api_key_secret = kubernetes_api_key_secret <NEW_LINE> super().__init__(**kwargs) <NEW_LINE> <DEDENT> @defaults_from_attrs( "job_name", "namespace", "kube_kwargs", "kubernetes_api_key_secret" ) <NEW_LINE> def run( self, job_name: str = None, namespace: str = "default", kube_kwargs: dict = None, kubernetes_api_key_secret: str = "KUBERNETES_API_KEY", ) -> None: <NEW_LINE> <INDENT> if not job_name: <NEW_LINE> <INDENT> raise ValueError("The name of a Kubernetes job must be provided.") <NEW_LINE> <DEDENT> kubernetes_api_key = Secret(kubernetes_api_key_secret).get() <NEW_LINE> if kubernetes_api_key: <NEW_LINE> <INDENT> configuration = client.Configuration() <NEW_LINE> configuration.api_key["authorization"] = kubernetes_api_key <NEW_LINE> api_client = client.BatchV1Api(client.ApiClient(configuration)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> config.load_incluster_config() <NEW_LINE> <DEDENT> except config.config_exception.ConfigException: <NEW_LINE> <INDENT> config.load_kube_config() <NEW_LINE> <DEDENT> api_client = client.BatchV1Api() <NEW_LINE> <DEDENT> kube_kwargs = {**self.kube_kwargs, **(kube_kwargs or {})} <NEW_LINE> return api_client.read_namespaced_job( name=job_name, namespace=namespace, **kube_kwargs )
Task for reading a namespaced job on Kubernetes. Note that all initialization arguments can optionally be provided or overwritten at runtime. This task will attempt to connect to a Kubernetes cluster in three steps with the first successful connection attempt becoming the mode of communication with a cluster. 1. Attempt to use a Prefect Secret that contains a Kubernetes API Key 2. Attempt in-cluster connection (will only work when running on a Pod in a cluster) 3. Attempt out-of-cluster connection using the default location for a kube config file The argument `kube_kwargs` will perform an in-place update when the task is run. This means that it is possible to provide `kube_kwargs = {"info": "here"}` at instantiation and then provide `kube_kwargs = {"more": "info"}` at run time which will make `kube_kwargs = {"info": "here", "more": "info"}`. *Note*: Keys present in both instantiation and runtime will be replaced with the runtime value. Args: - job_name (str, optional): The name of a job to read - namespace (str, optional): The Kubernetes namespace to read this job from, defaults to the `default` namespace - kube_kwargs (dict, optional): Optional extra keyword arguments to pass to the Kubernetes API (e.g. `{"pretty": "...", "exact": "..."}`) - kubernetes_api_key_secret (str, optional): the name of the Prefect Secret which stored your Kubernetes API Key; this Secret must be a string and in BearerToken format - **kwargs (dict, optional): additional keyword arguments to pass to the Task constructor
62598fc1e1aae11d1e7ce952
class Boost(Pickup): <NEW_LINE> <INDENT> def __init__(self, x, y): <NEW_LINE> <INDENT> Pickup.__init__(self, x, y) <NEW_LINE> self.image = pygame.image.load('Boost.png') <NEW_LINE> <DEDENT> def func(self,player): <NEW_LINE> <INDENT> effect_func(player,'speed',600)
Makes the player faster for a short duration
62598fc166656f66f7d5a64c
class Callable(TraitType): <NEW_LINE> <INDENT> info_text = 'a callable' <NEW_LINE> def validate(self, obj, value): <NEW_LINE> <INDENT> if six.callable(value): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.error(obj, value)
A trait which is callable. Notes ----- Classes are callable, as are instances with a __call__() method.
62598fc1442bda511e95c6ba
class PluginExtensionRegistry(ProviderExtensionRegistry): <NEW_LINE> <INDENT> plugin_manager = Instance(IPluginManager) <NEW_LINE> def _plugin_manager_changed(self, trait_name, old, new): <NEW_LINE> <INDENT> if old is not None: <NEW_LINE> <INDENT> for plugin in old: <NEW_LINE> <INDENT> self.remove_provider(plugin) <NEW_LINE> <DEDENT> <DEDENT> if new is not None: <NEW_LINE> <INDENT> for plugin in new: <NEW_LINE> <INDENT> self.add_provider(plugin) <NEW_LINE> <DEDENT> <DEDENT> return <NEW_LINE> <DEDENT> @on_trait_change('plugin_manager:plugin_added') <NEW_LINE> def _on_plugin_added(self, obj, trait_name, old, event): <NEW_LINE> <INDENT> self.add_provider(event.plugin) <NEW_LINE> return <NEW_LINE> <DEDENT> @on_trait_change('plugin_manager:plugin_removed') <NEW_LINE> def _on_plugin_removed(self, obj, trait_name, old, event): <NEW_LINE> <INDENT> self.remove_provider(event.plugin) <NEW_LINE> return
An extension registry that uses plugins as extension providers. The application's plugins are used as the registries providers so adding or removing a plugin affects the extension points and extensions etc.
62598fc1f548e778e596b7fa
class DCVersionI(DCBase) : <NEW_LINE> <INDENT> def __init__(self, vnum, tsprod=None, arr=None, cmt=None) : <NEW_LINE> <INDENT> DCBase.__init__(self, cmt) <NEW_LINE> self._name = self.__class__.__name__ <NEW_LINE> <DEDENT> def set_vnum(self, vnum) : print_warning(self, sys._getframe()) <NEW_LINE> def set_tsprod(self, tsprod) : print_warning(self, sys._getframe()) <NEW_LINE> def add_data(self, nda) : print_warning(self, sys._getframe()) <NEW_LINE> def vnum(self) : print_warning(self, sys._getframe()); return None <NEW_LINE> def str_vnum(self) : print_warning(self, sys._getframe()); return None <NEW_LINE> def tsprod(self) : print_warning(self, sys._getframe()); return None <NEW_LINE> def data(self) : print_warning(self, sys._getframe()); return None <NEW_LINE> def save(self, group) : print_warning(self, sys._getframe()) <NEW_LINE> def load(self, group) : print_warning(self, sys._getframe()) <NEW_LINE> def print_obj(self) : print_warning(self, sys._getframe())
Abstract interface class for the Detector Calibration (DC) project o = DCVersionI(vnum, tsprod=None, arr=None) o.set_vnum(vnum) # sets (int) version o.set_tsprod(tsprod) # sets (double) time stamp of the version production o.add_data(nda) # sets (np.array) calibration array vnum = o.vnum() # returns (int) version number s_vnum = o.str_vnum() # returns (str) version number tsvers = o.tsprod() # returns (double) time stamp of the version production nda = o.data() # returns (np.array) calibration array o.save(group) # saves object content under h5py.group in the hdf5 file. o.load(group) # loads object content from the h5py.group of hdf5 file.
62598fc1adb09d7d5dc0a7d8
class TestDeleteGeneratorWithValidID(unittest.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> cls.client = craft_ai.Client(settings.CRAFT_CFG) <NEW_LINE> cls.generator_id = generate_entity_id("test_delete_generator") <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def tearDownClass(cls): <NEW_LINE> <INDENT> cls.client.delete_generator(cls.generator_id) <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.client.create_generator( valid_data.VALID_GENERATOR_CONFIGURATION, self.generator_id ) <NEW_LINE> <DEDENT> except craft_ai.errors.CraftAiBadRequestError as e: <NEW_LINE> <INDENT> if "one already exists" not in e.message: <NEW_LINE> <INDENT> raise e <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def test_delete_generator_with_valid_id(self): <NEW_LINE> <INDENT> resp = self.client.delete_generator(self.generator_id) <NEW_LINE> self.assertIsInstance(resp, dict) <NEW_LINE> self.assertTrue("id" in resp.keys())
Checks that the client succeeds when deleting a generator with OK input
62598fc18a349b6b43686499
class DiskMetricTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_return_total_used_avail_percent(self): <NEW_LINE> <INDENT> stdout_string = ('Filesystem 1K-blocks Used Available Use% ' 'mounted on\n/dev/dm-1 57542652 18358676 ' '36237928 34% /') <NEW_LINE> self.FAKE_RESULT = fake.FakeResult(stdout=stdout_string) <NEW_LINE> fake_shell = fake.MockShellCommand(fake_result=self.FAKE_RESULT) <NEW_LINE> self.metric_obj = disk_metric.DiskMetric(shell=fake_shell) <NEW_LINE> expected_result = { disk_metric.DiskMetric.TOTAL: 57542652, disk_metric.DiskMetric.USED: 18358676, disk_metric.DiskMetric.AVAIL: 36237928, disk_metric.DiskMetric.PERCENT_USED: 34 } <NEW_LINE> self.assertEqual(expected_result, self.metric_obj.gather_metric())
Class for testing DiskMetric.
62598fc1bf627c535bcb1701
class DummyTqdmFile: <NEW_LINE> <INDENT> file = None <NEW_LINE> def __init__(self, file): <NEW_LINE> <INDENT> self.file = file <NEW_LINE> <DEDENT> def write(self, x): <NEW_LINE> <INDENT> if len(x.rstrip()) > 0: <NEW_LINE> <INDENT> tqdm.write(x, file=self.file) <NEW_LINE> <DEDENT> <DEDENT> def flush(self): <NEW_LINE> <INDENT> return getattr(self.file, "flush", lambda: None)() <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> return getattr(self.file, "close", lambda: None)() <NEW_LINE> <DEDENT> def isatty(self): <NEW_LINE> <INDENT> return getattr(self.file, "isatty", lambda: False)()
Dummy file-like that will write to tqdm.
62598fc1a05bb46b3848aac7
class ForbiddenError(Exception): <NEW_LINE> <INDENT> pass
Raised when the bot can't do something.
62598fc176e4537e8c3ef801
class LogicalExpression(pymbolic.primitives.Expression): <NEW_LINE> <INDENT> def __inv__(self): <NEW_LINE> <INDENT> return LogicalNot(self) <NEW_LINE> <DEDENT> __invert__ = __inv__ <NEW_LINE> def __and__(self, other): <NEW_LINE> <INDENT> return LogicalAnd((self, other)) <NEW_LINE> <DEDENT> def __or__(self, other): <NEW_LINE> <INDENT> return LogicalOr((self, other)) <NEW_LINE> <DEDENT> def __rshift__(self, other): <NEW_LINE> <INDENT> return IfThen(self, other) <NEW_LINE> <DEDENT> def tabulate(self): <NEW_LINE> <INDENT> def contextualize(props, vals): <NEW_LINE> <INDENT> return dict(zip([p.name for p in props], vals)) <NEW_LINE> <DEDENT> def filter_exprs(split_expr): <NEW_LINE> <INDENT> return [*reversed([*filter(lambda it: not isinstance(it, Proposition), split_expr)])] <NEW_LINE> <DEDENT> def filter_props(split_expr): <NEW_LINE> <INDENT> return sorted([*set(filter(lambda it: isinstance(it, Proposition), split_expr))]) <NEW_LINE> <DEDENT> split_expr = LogicalSplitter()(self) <NEW_LINE> exprs = filter_exprs(split_expr) <NEW_LINE> props = filter_props(split_expr) <NEW_LINE> comb = combination(len(props)) <NEW_LINE> evaluator = LogicalEvaluator() <NEW_LINE> truths = [] <NEW_LINE> for vals in comb: <NEW_LINE> <INDENT> evaluator.context = contextualize(props, vals) <NEW_LINE> truths.append((vals.tolist() + [evaluator(e) for e in exprs])) <NEW_LINE> <DEDENT> columns = [*props, *exprs] <NEW_LINE> table = pd.DataFrame(truths, columns=columns) <NEW_LINE> return table <NEW_LINE> <DEDENT> def is_equivalent(self, other): <NEW_LINE> <INDENT> return np.array_equal(self.tabulate().values[:, -1], other.tabulate().values[:, -1])
Overrides logical methods of `pymbolic.primitives.Expression` for `matstep` logic operators.
62598fc17cff6e4e811b5c7f
class Loader(abc.ABC): <NEW_LINE> <INDENT> def __init__(self, batch_size): <NEW_LINE> <INDENT> self._batch_size = batch_size <NEW_LINE> <DEDENT> @property <NEW_LINE> def batch_size(self): <NEW_LINE> <INDENT> return self._batch_size <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def __call__(self): <NEW_LINE> <INDENT> raise NotImplementedError()
Base class for creating batches of TUs.
62598fc14527f215b58ea12a
class MeetupEventsScraper: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.groups = ['API-Craft-Boston', 'Boston-Algorithmic-Trading', 'Big-Data-Analytics-Discovery-Visualization', 'Boston-Data-Mining', 'bostonhadoop', 'boston-java'] <NEW_LINE> <DEDENT> def scrape_these_groups(self, key): <NEW_LINE> <INDENT> meetup_dict = {} <NEW_LINE> for group in self.groups: <NEW_LINE> <INDENT> meetup_dict[group] = 'https://api.meetup.com/2/events?' + 'key=' + key + '&group_urlname=' + group + '&page=20' <NEW_LINE> <DEDENT> return meetup_dict <NEW_LINE> <DEDENT> def parse_events_json(self, key): <NEW_LINE> <INDENT> group_events = {} <NEW_LINE> for group in self.scrape_these_groups(key): <NEW_LINE> <INDENT> r = requests.get(self.scrape_these_groups(key)[group]) <NEW_LINE> event_list = [] <NEW_LINE> for event in r.json()['results']: <NEW_LINE> <INDENT> event_list.append( (event['name'], event['time'], event['venue'], event['description'], event['waitlist_count']) ) <NEW_LINE> <DEDENT> group_events[group] = event_list <NEW_LINE> <DEDENT> return group_events
Gather event data from a given list of Meetup groups Attributes: groups: list of groups that we want to know about their events
62598fc1d486a94d0ba2c22c
class Solution: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.longest_path = 0 <NEW_LINE> <DEDENT> def longestConsecutive(self, root): <NEW_LINE> <INDENT> self.helper(root) <NEW_LINE> return self.longest_path <NEW_LINE> <DEDENT> def helper(self, root): <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> left_path = self.helper(root.left) <NEW_LINE> right_path = self.helper(root.right) <NEW_LINE> subtree_path = 1 <NEW_LINE> if root.left and root.val + 1 == root.left.val: <NEW_LINE> <INDENT> subtree_path = max(subtree_path, left_path + 1) <NEW_LINE> <DEDENT> if root.right and root.val + 1 == root.right.val: <NEW_LINE> <INDENT> subtree_path = max(subtree_path, right_path + 1) <NEW_LINE> <DEDENT> self.longest_path = max(self.longest_path, subtree_path) <NEW_LINE> return subtree_path <NEW_LINE> <DEDENT> def longestConsecutive_2(self, root): <NEW_LINE> <INDENT> return self.helper_2(root, None, 0) <NEW_LINE> <DEDENT> def helper_2(self, node, parent, length_without_root): <NEW_LINE> <INDENT> if not node: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> length = length_without_root + 1 if parent and parent.val + 1 == node.val else 1 <NEW_LINE> left_length = self.helper_2(node.left, node, length) <NEW_LINE> right_length = self.helper_2(node.right, node,length) <NEW_LINE> return max(length, left_length, right_length)
@param: root: the root of binary tree @return: the length of the longest consecutive sequence path
62598fc150812a4eaa620d17
class DescriptionDefinition(Element): <NEW_LINE> <INDENT> def __init__(self, *content): <NEW_LINE> <INDENT> super().__init__("dd") <NEW_LINE> self.extend(content)
An HTML definition element (<dd>) for description lists.
62598fc1f9cc0f698b1c53fe
@attr.s(frozen=True, auto_attribs=True) <NEW_LINE> class NewDocEvent(BaseEvent): <NEW_LINE> <INDENT> kind: EventKind = EventKind.new_document
Event
62598fc15fc7496912d483a9
class Node(): <NEW_LINE> <INDENT> def __init__(self, name, value=None, given=False): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.value = value <NEW_LINE> self.given = bool(given) <NEW_LINE> self.dependencies_attached = [] <NEW_LINE> self.data_type = None <NEW_LINE> <DEDENT> def set_given(self, is_given): <NEW_LINE> <INDENT> self.given = bool(is_given) <NEW_LINE> return True <NEW_LINE> <DEDENT> def is_given(self): <NEW_LINE> <INDENT> return self.given <NEW_LINE> <DEDENT> def set_value(self, value): <NEW_LINE> <INDENT> if not (isinstance(value, numpy.ndarray) or numpy.isscalar(value)): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> value = numpy.asarray(value) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise UnexpectedParameterType("'value' is expected to be an instance of numpy.ndarray") <NEW_LINE> <DEDENT> <DEDENT> self.value = value <NEW_LINE> return True <NEW_LINE> <DEDENT> def set_name(self, name): <NEW_LINE> <INDENT> self.name = str(name) <NEW_LINE> return True <NEW_LINE> <DEDENT> def get_value(self): <NEW_LINE> <INDENT> return self.value <NEW_LINE> <DEDENT> def get_name(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def get_dependencies_attached(self): <NEW_LINE> <INDENT> return self.dependencies_attached <NEW_LINE> <DEDENT> def set_data_type(self, data_type): <NEW_LINE> <INDENT> set_data_type(self, data_type) <NEW_LINE> return True <NEW_LINE> <DEDENT> def zeros(self): <NEW_LINE> <INDENT> return numpy.zeros(self.value.shape) <NEW_LINE> <DEDENT> def zeros_hessian(self): <NEW_LINE> <INDENT> return numpy.zeros((self.value.size, self.value.size)) <NEW_LINE> <DEDENT> def has_log_conditional_probability_gradient(self): <NEW_LINE> <INDENT> for dependence in self.get_dependencies_attached(): <NEW_LINE> <INDENT> if not dependence.self.has_log_conditional_probability_gradient_node(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> def has_log_conditional_probability_hessian(self): <NEW_LINE> <INDENT> for dependence in self.get_dependencies_attached(): <NEW_LINE> <INDENT> if not dependence.self.has_log_conditional_probability_hessian_node(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> def has_log_conditional_probability_diagonal_hessian(self): <NEW_LINE> <INDENT> for dependence in self.get_dependencies_attached(): <NEW_LINE> <INDENT> if not dependence.self.has_log_conditional_probability_diagonal_hessian_node(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> def has_log_conditional_probability(self): <NEW_LINE> <INDENT> for dependence in self.get_dependencies_attached(): <NEW_LINE> <INDENT> if not dependence.self.has_log_conditional_probability_node(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> def can_sample_conditional_probability(self): <NEW_LINE> <INDENT> for dependence in self.get_dependencies_attached(): <NEW_LINE> <INDENT> if not dependence.can_sample_conditional_probability_node(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True
Node of a graphical model. A node represents a variable or set of variables. The node is characterized by name, value, and by the given flag. The flag is True if the variable is considered a given quantity, False if it considered unknown (uncertain).
62598fc1d8ef3951e32c7f8c
class IHDUSessionLoginMixin(BaseSessionLoginMixin): <NEW_LINE> <INDENT> def __init__(self, username, password): <NEW_LINE> <INDENT> super(IHDUSessionLoginMixin, self).__init__(username, password) <NEW_LINE> self.home_url = HOME_URLS['ihdu'] <NEW_LINE> <DEDENT> def login(self, headers=IHDU_HEADERS): <NEW_LINE> <INDENT> super(IHDUSessionLoginMixin, self).login(headers) <NEW_LINE> <DEDENT> def _do_login(self): <NEW_LINE> <INDENT> payload = self._get_payload(CAS_LOGIN_URLS['ihdu']) <NEW_LINE> try: <NEW_LINE> <INDENT> rsp = self.post(CAS_LOGIN_URLS['ihdu'], data=payload, headers=CAS_LOGIN_HEADERS, allow_redirects=False) <NEW_LINE> next_url = rsp.headers['location'] <NEW_LINE> rsp = self.get(next_url, allow_redirects=False) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def _check_sess_vaild(self): <NEW_LINE> <INDENT> cookies_keys = list(self.cookies.get_dict().keys()) <NEW_LINE> if 'tp_up' in cookies_keys: <NEW_LINE> <INDENT> rsp = self.get(self.home_url, allow_redirects=False) <NEW_LINE> if rsp.status_code != 200 or 'Object moved' in rsp.text: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> soup = BeautifulSoup(rsp.text, 'lxml') <NEW_LINE> try: <NEW_LINE> <INDENT> self.realname = soup.find('div', id='user-con').find('span', class_='tit').get_text().strip() <NEW_LINE> return True <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return False
混合 ihdu(https://i.hdu.edu.cn/tp_up/view?m=up) 的登录功能.
62598fc1fff4ab517ebcda44
class UserBooks(Resource): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.reqparse = reqparse.RequestParser() <NEW_LINE> self.reqparse.add_argument('title', type = str, required = True, help = "Title not provided") <NEW_LINE> self.reqparse.add_argument('author', type = str, required = True, help = "Author not provided") <NEW_LINE> self.reqparse.add_argument('isbn', type = str, required = True, help = "ISBN not provided") <NEW_LINE> self.reqparse.add_argument('pub_date', type = str, required = True, help = "Publication date not provided") <NEW_LINE> super(UserBooks, self).__init__() <NEW_LINE> <DEDENT> def get(self, id): <NEW_LINE> <INDENT> user = UserModel.query.get_or_404(id) <NEW_LINE> return { 'books': list(map(lambda x: BookModel.serialize(x), user.books)) } <NEW_LINE> <DEDENT> @auth.login_required <NEW_LINE> def post(self, id): <NEW_LINE> <INDENT> data = self.reqparse.parse_args() <NEW_LINE> user = UserModel.query.get_or_404(id) <NEW_LINE> try: <NEW_LINE> <INDENT> pub_date = datetime.strptime(data['pub_date'], '%Y-%m-%d') <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return {"message": "Publication date (pub_date) must be in YYYY-mm-dd format" }, 400 <NEW_LINE> <DEDENT> if UserModel.query.filter_by(id=id, email=g.user.email).first() is None: <NEW_LINE> <INDENT> return { "message": "Users are only allowed to add books to their own wishlist" }, 401 <NEW_LINE> <DEDENT> book = BookModel.query.filter_by(isbn=data['isbn']).first() <NEW_LINE> if book is None: <NEW_LINE> <INDENT> book = BookModel(isbn = data['isbn'], title = data['title'], author = data['author'], pub_date = pub_date) <NEW_LINE> book.add_to_db() <NEW_LINE> <DEDENT> elif not(book.title == data['title'] and book.author == data['author'] and str(book.pub_date) == data['pub_date']): <NEW_LINE> <INDENT> print(book.pub_date) <NEW_LINE> print(data['pub_date']) <NEW_LINE> return { "message": "Different book with this ISBN already exists" }, 409 <NEW_LINE> <DEDENT> elif book in user.books: <NEW_LINE> <INDENT> return { "message": "Book with this ISBN already in user's wishlist" }, 409 <NEW_LINE> <DEDENT> user.books.append(book) <NEW_LINE> commit() <NEW_LINE> return { 'book': BookModel.serialize(book) }, 201
Resource: books Endpoint: /api/users/<id>/books Methods: GET, POST
62598fc12c8b7c6e89bd3a1f
class IPrincipalField(interface.Interface): <NEW_LINE> <INDENT> pass
principal id field
62598fc160cbc95b0636459a
class InterruptableThread(threading.Thread): <NEW_LINE> <INDENT> def __init__(self, cursor, query): <NEW_LINE> <INDENT> LOGGER.debug('InterruptableThread.__init__ start') <NEW_LINE> threading.Thread.__init__(self) <NEW_LINE> self.cursor = cursor <NEW_LINE> self.query = query <NEW_LINE> self.result = NONE_RESPONSE <NEW_LINE> self.daemon = True <NEW_LINE> LOGGER.debug('InterruptableThread.__init__ end') <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> LOGGER.debug('InterruptableThread.run start') <NEW_LINE> self.cursor.execute(self.query) <NEW_LINE> if SQL == 'mysqldb': <NEW_LINE> <INDENT> self.result = self.cursor.fetchall() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.result = self.cursor.fetchall() <NEW_LINE> <DEDENT> except ODBC_PROGRAMMING_ERROR: <NEW_LINE> <INDENT> self.result = None <NEW_LINE> <DEDENT> <DEDENT> LOGGER.debug('InterruptableThread.run end. Executed query: {}' ''.format(self.query))
Class to run a MySQL query with a time out
62598fc14c3428357761a519
class Entry_u_boot_spl_bss_pad(Entry_blob): <NEW_LINE> <INDENT> def __init__(self, section, etype, node): <NEW_LINE> <INDENT> Entry_blob.__init__(self, section, etype, node) <NEW_LINE> <DEDENT> def ObtainContents(self): <NEW_LINE> <INDENT> fname = tools.GetInputFilename('spl/u-boot-spl') <NEW_LINE> bss_size = elf.GetSymbolAddress(fname, '__bss_size') <NEW_LINE> if not bss_size: <NEW_LINE> <INDENT> self.Raise('Expected __bss_size symbol in spl/u-boot-spl') <NEW_LINE> <DEDENT> self.SetContents(chr(0) * bss_size) <NEW_LINE> return True
U-Boot SPL binary padded with a BSS region Properties / Entry arguments: None This is similar to u_boot_spl except that padding is added after the SPL binary to cover the BSS (Block Started by Symbol) region. This region holds the various used by SPL. It is set to 0 by SPL when it starts up. If you want to append data to the SPL image (such as a device tree file), you must pad out the BSS region to avoid the data overlapping with U-Boot variables. This entry is useful in that case. It automatically pads out the entry size to cover both the code, data and BSS. The ELF file 'spl/u-boot-spl' must also be available for this to work, since binman uses that to look up the BSS address.
62598fc14a966d76dd5ef133
class IdentityDetail(APIView): <NEW_LINE> <INDENT> permission_classes = (ApiAuthRequired,) <NEW_LINE> def get(self, request, identity_uuid): <NEW_LINE> <INDENT> identity = get_identity(request.user, identity_uuid) <NEW_LINE> if not identity: <NEW_LINE> <INDENT> return failure_response( status.HTTP_404_NOT_FOUND, "The requested Identity ID %s was not found on an active provider" % identity_uuid) <NEW_LINE> <DEDENT> serialized_data = IdentityDetailSerializer(identity).data <NEW_LINE> return Response(serialized_data)
The identity contains every credential necessary for atmosphere to connect 'The Provider' with a specific user. These credentials can vary from provider to provider.
62598fc1adb09d7d5dc0a7dc
class SwiftAPI(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> session = _get_swift_session() <NEW_LINE> self.connection = swift_client.Connection(session=session) <NEW_LINE> <DEDENT> def create_object(self, container, obj, filename, object_headers=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.connection.put_container(container) <NEW_LINE> <DEDENT> except swift_exceptions.ClientException as e: <NEW_LINE> <INDENT> operation = _("put container") <NEW_LINE> raise exception.SwiftOperationError(operation=operation, error=e) <NEW_LINE> <DEDENT> with open(filename, "r") as fileobj: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> obj_uuid = self.connection.put_object(container, obj, fileobj, headers=object_headers) <NEW_LINE> <DEDENT> except swift_exceptions.ClientException as e: <NEW_LINE> <INDENT> operation = _("put object") <NEW_LINE> raise exception.SwiftOperationError(operation=operation, error=e) <NEW_LINE> <DEDENT> <DEDENT> return obj_uuid <NEW_LINE> <DEDENT> def get_temp_url(self, container, obj, timeout): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> account_info = self.connection.head_account() <NEW_LINE> <DEDENT> except swift_exceptions.ClientException as e: <NEW_LINE> <INDENT> operation = _("head account") <NEW_LINE> raise exception.SwiftOperationError(operation=operation, error=e) <NEW_LINE> <DEDENT> parse_result = parse.urlparse(self.connection.url) <NEW_LINE> swift_object_path = '/'.join((parse_result.path, container, obj)) <NEW_LINE> temp_url_key = account_info['x-account-meta-temp-url-key'] <NEW_LINE> url_path = swift_utils.generate_temp_url(swift_object_path, timeout, temp_url_key, 'GET') <NEW_LINE> return parse.urlunparse((parse_result.scheme, parse_result.netloc, url_path, None, None, None)) <NEW_LINE> <DEDENT> def delete_object(self, container, obj): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.connection.delete_object(container, obj) <NEW_LINE> <DEDENT> except swift_exceptions.ClientException as e: <NEW_LINE> <INDENT> operation = _("delete object") <NEW_LINE> if e.http_status == http_client.NOT_FOUND: <NEW_LINE> <INDENT> raise exception.SwiftObjectNotFoundError(obj=obj, container=container, operation=operation) <NEW_LINE> <DEDENT> raise exception.SwiftOperationError(operation=operation, error=e) <NEW_LINE> <DEDENT> <DEDENT> def head_object(self, container, obj): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.connection.head_object(container, obj) <NEW_LINE> <DEDENT> except swift_exceptions.ClientException as e: <NEW_LINE> <INDENT> operation = _("head object") <NEW_LINE> raise exception.SwiftOperationError(operation=operation, error=e) <NEW_LINE> <DEDENT> <DEDENT> def update_object_meta(self, container, obj, object_headers): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.connection.post_object(container, obj, object_headers) <NEW_LINE> <DEDENT> except swift_exceptions.ClientException as e: <NEW_LINE> <INDENT> operation = _("post object") <NEW_LINE> raise exception.SwiftOperationError(operation=operation, error=e)
API for communicating with Swift.
62598fc14f88993c371f0639
class UserStore(models.Model): <NEW_LINE> <INDENT> store = models.ForeignKey(Store) <NEW_LINE> user = models.ForeignKey(User) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return str(self.store) + ' | ' + str(self.user)
Class that show the relationship beetween user and stores and citires
62598fc156ac1b37e6302446
class NatlinkSpeaker(SpeakerBase): <NEW_LINE> <INDENT> _name = "natlink" <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self._register() <NEW_LINE> <DEDENT> def speak(self, text): <NEW_LINE> <INDENT> mic_state = natlink.getMicState() <NEW_LINE> natlink.execScript('TTSPlayString "%s"' % text) <NEW_LINE> if mic_state != natlink.getMicState(): <NEW_LINE> <INDENT> natlink.setMicState(mic_state)
This speaker class uses the text-to-speech functionality embedded into Dragon NaturallySpeaking (DNS). It is available only on Microsoft Windows and requires (DNS) and Natlink to be installed on the system.
62598fc197e22403b383b168
class Critic(nn.Module): <NEW_LINE> <INDENT> def __init__(self, state_size, action_size, seed, fc1_units=100, fc2_units=100): <NEW_LINE> <INDENT> super(Critic, self).__init__() <NEW_LINE> self.seed = torch.manual_seed(seed) <NEW_LINE> self.bn0 = nn.BatchNorm1d(state_size) <NEW_LINE> self.fcs1 = nn.Linear(state_size, fc1_units) <NEW_LINE> self.fc2 = nn.Linear(fc1_units+action_size, fc2_units) <NEW_LINE> self.fc3 = nn.Linear(fc2_units, 1) <NEW_LINE> self.reset_parameters() <NEW_LINE> <DEDENT> def reset_parameters(self): <NEW_LINE> <INDENT> self.fcs1.weight.data.uniform_(*hidden_init(self.fcs1)) <NEW_LINE> self.fc2.weight.data.uniform_(*hidden_init(self.fc2)) <NEW_LINE> self.fc3.weight.data.uniform_(-3e-3, 3e-3) <NEW_LINE> <DEDENT> def forward(self, state, action): <NEW_LINE> <INDENT> xs = F.relu(self.fcs1(self.bn0(state))) <NEW_LINE> x = torch.cat((xs, action), dim=1) <NEW_LINE> x = F.relu(self.fc2(x)) <NEW_LINE> return self.fc3(x)
Critic (Value) Model.
62598fc13346ee7daa337778
class CGGetterCall(CGPerSignatureCall): <NEW_LINE> <INDENT> def __init__(self, argsPre, returnType, nativeMethodName, descriptor, attr): <NEW_LINE> <INDENT> CGPerSignatureCall.__init__(self, returnType, argsPre, [], nativeMethodName, attr.isStatic(), descriptor, attr, getter=True)
A class to generate a native object getter call for a particular IDL getter.
62598fc160cbc95b0636459c
class LogisticLoss(BaseLoss): <NEW_LINE> <INDENT> def transform(self, preds): <NEW_LINE> <INDENT> return np.clip(1.0/(1.0 + np.exp(-preds)), 0.00001, 0.99999) <NEW_LINE> <DEDENT> def grad(self, preds, labels): <NEW_LINE> <INDENT> preds = self.transform(preds) <NEW_LINE> return (1-labels)/(1-preds) - labels/preds <NEW_LINE> <DEDENT> def hess(self, preds, labels): <NEW_LINE> <INDENT> preds = self.transform(preds) <NEW_LINE> return labels/np.square(preds) + (1-labels)/np.square(1-preds)
label is {0, 1} grad = (1-y)/(1-pred) - y/pred hess = y/pred**2 + (1-y)/(1-pred)**2
62598fc166656f66f7d5a652
class BaseRenewableCertTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> from letsencrypt import storage <NEW_LINE> self.tempdir = tempfile.mkdtemp() <NEW_LINE> self.cli_config = configuration.RenewerConfiguration( namespace=mock.MagicMock( config_dir=self.tempdir, work_dir=self.tempdir, logs_dir=self.tempdir, ) ) <NEW_LINE> os.makedirs(os.path.join(self.tempdir, "live", "example.org")) <NEW_LINE> os.makedirs(os.path.join(self.tempdir, "archive", "example.org")) <NEW_LINE> os.makedirs(os.path.join(self.tempdir, "renewal")) <NEW_LINE> config = configobj.ConfigObj() <NEW_LINE> for kind in ALL_FOUR: <NEW_LINE> <INDENT> config[kind] = os.path.join(self.tempdir, "live", "example.org", kind + ".pem") <NEW_LINE> <DEDENT> config.filename = os.path.join(self.tempdir, "renewal", "example.org.conf") <NEW_LINE> config.write() <NEW_LINE> self.config = config <NEW_LINE> self.defaults = configobj.ConfigObj() <NEW_LINE> self.test_rc = storage.RenewableCert(config.filename, self.cli_config) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> shutil.rmtree(self.tempdir) <NEW_LINE> <DEDENT> def _write_out_ex_kinds(self): <NEW_LINE> <INDENT> for kind in ALL_FOUR: <NEW_LINE> <INDENT> where = getattr(self.test_rc, kind) <NEW_LINE> os.symlink(os.path.join("..", "..", "archive", "example.org", "{0}12.pem".format(kind)), where) <NEW_LINE> with open(where, "w") as f: <NEW_LINE> <INDENT> f.write(kind) <NEW_LINE> <DEDENT> os.unlink(where) <NEW_LINE> os.symlink(os.path.join("..", "..", "archive", "example.org", "{0}11.pem".format(kind)), where) <NEW_LINE> with open(where, "w") as f: <NEW_LINE> <INDENT> f.write(kind)
Base class for setting up Renewable Cert tests. .. note:: It may be required to write out self.config for your test. Check :class:`.cli_test.DuplicateCertTest` for an example.
62598fc15fc7496912d483ab
class PluralTest(unittest.TestCase): <NEW_LINE> <INDENT> def testPlural(self): <NEW_LINE> <INDENT> self.assertEqual('cards', utility.plural(7, 'card')) <NEW_LINE> <DEDENT> def testPluralNoS(self): <NEW_LINE> <INDENT> self.assertEqual('dice', utility.plural(5, 'die', 'dice')) <NEW_LINE> <DEDENT> def testSingular(self): <NEW_LINE> <INDENT> self.assertEqual('card', utility.plural(1, 'card')) <NEW_LINE> <DEDENT> def testSingularNoS(self): <NEW_LINE> <INDENT> self.assertEqual('die', utility.plural(1, 'die', 'dice')) <NEW_LINE> <DEDENT> def testZero(self): <NEW_LINE> <INDENT> self.assertEqual('cards', utility.plural(0, 'card')) <NEW_LINE> <DEDENT> def testZeroNoS(self): <NEW_LINE> <INDENT> self.assertEqual('dice', utility.plural(0, 'die', 'dice'))
Tests of getting the singular/plural form. (unittest.TestCase)
62598fc15fdd1c0f98e5e1f3
class Variables(IgorObject): <NEW_LINE> <INDENT> def __init__(self, data, order): <NEW_LINE> <INDENT> version, = struct.unpack(order+"h",data[:2]) <NEW_LINE> if version == 1: <NEW_LINE> <INDENT> pos = 8 <NEW_LINE> nSysVar, nUserVar, nUserStr = struct.unpack(order+"hhh",data[2:pos]) <NEW_LINE> nDepVar, nDepStr = 0, 0 <NEW_LINE> <DEDENT> elif version == 2: <NEW_LINE> <INDENT> pos = 12 <NEW_LINE> nSysVar, nUservar, nUserStr, nDepVar, nDepStr = struct.unpack(order+"hhh",data[2:pos]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Unknown variable record version "+str(version)) <NEW_LINE> <DEDENT> self.sysvar, pos = _parse_sys_numeric(nSysVar, order, data, pos) <NEW_LINE> self.uservar, pos = _parse_user_numeric(nUserVar, order, data, pos) <NEW_LINE> if version == 1: <NEW_LINE> <INDENT> self.userstr, pos = _parse_user_string1(nUserStr, order, data, pos) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.userstr, pos = _parse_user_string2(nUserStr, order, data, pos) <NEW_LINE> <DEDENT> self.depvar, pos = _parse_dep_numeric(nDepVar, order, data, pos) <NEW_LINE> self.depstr, pos = _parse_dep_string(nDepStr, order, data, pos) <NEW_LINE> <DEDENT> def format(self, indent=0): <NEW_LINE> <INDENT> return " "*indent+"<Variables: system %d, user %d, dependent %s>" %(len(self.sysvar), len(self.uservar)+len(self.userstr), len(self.depvar)+len(self.depstr))
Contains system numeric variables (e.g., K0) and user numeric and string variables.
62598fc1442bda511e95c6c0
class PymapError(Exception): <NEW_LINE> <INDENT> pass
The base exception for all custom errors in :mod:`pymap`.
62598fc14527f215b58ea130
class HistSaverIfMatch(object): <NEW_LINE> <INDENT> def __init__(self, regex, extension = ".pdf", outpath="./"): <NEW_LINE> <INDENT> self.rgx = re.compile(regex) <NEW_LINE> self.ext = extension <NEW_LINE> self.path = outpath <NEW_LINE> self.can = TCanvas("saveCanvas", "saveCanvas", 1000, 1000) <NEW_LINE> <DEDENT> def __call__(self, obj): <NEW_LINE> <INDENT> if obj.InheritsFrom("TH1") and self.rgx.search(obj.GetName()): <NEW_LINE> <INDENT> self.can.Clear() <NEW_LINE> self.can.cd() <NEW_LINE> self.can.SetLogz(logColAxis) <NEW_LINE> obj.SetStats(False) <NEW_LINE> if obj.InheritsFrom("TH2"): <NEW_LINE> <INDENT> drawTH2DColMap(obj, self.can) <NEW_LINE> if draw2DRelErrMap: <NEW_LINE> <INDENT> drawTH2DErrColMap(obj, self.can) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> obj.Draw("E1LP") <NEW_LINE> <DEDENT> self.can.SaveAs("".join([self.path, obj.GetName(), self.ext]))
Functor for saving all (toplevel) histograms in a TFile.
62598fc1fff4ab517ebcda48
class lexicalConceptualResourceTextInfoType_model(SchemaModel): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = "Lexical conceptual resource text" <NEW_LINE> <DEDENT> __schema_name__ = 'lexicalConceptualResourceTextInfoType' <NEW_LINE> __schema_fields__ = ( ( u'mediaType', u'mediaType', REQUIRED ), ( u'lingualityInfo', u'lingualityInfo', REQUIRED ), ( u'languageInfo', u'languageinfotype_model_set', REQUIRED ), ( u'modalityInfo', u'modalityinfotype_model_set', RECOMMENDED ), ( u'sizeInfo', u'sizeinfotype_model_set', REQUIRED ), ( u'textFormatInfo', u'textformatinfotype_model_set', RECOMMENDED ), ( u'characterEncodingInfo', u'characterencodinginfotype_model_set', OPTIONAL ), ( u'domainInfo', u'domaininfotype_model_set', OPTIONAL ), ( u'timeCoverageInfo', u'timecoverageinfotype_model_set', OPTIONAL ), ( u'geographicCoverageInfo', u'geographiccoverageinfotype_model_set', OPTIONAL ), ) <NEW_LINE> __schema_classes__ = { u'characterEncodingInfo': "characterEncodingInfoType_model", u'domainInfo': "domainInfoType_model", u'geographicCoverageInfo': "geographicCoverageInfoType_model", u'languageInfo': "languageInfoType_model", u'lingualityInfo': "lingualityInfoType_model", u'modalityInfo': "modalityInfoType_model", u'sizeInfo': "sizeInfoType_model", u'textFormatInfo': "textFormatInfoType_model", u'timeCoverageInfo': "timeCoverageInfoType_model", } <NEW_LINE> mediaType = models.CharField( verbose_name='Media', help_text='Specifies the media type of the resource and basically ' 'corresponds to the physical medium of the content representation.' ' Each media type is described through a distinctive set of featur' 'es. A resource may consist of parts attributed to different types' ' of media. A tool/service may take as input/output more than one ' 'different media types.', default="text", editable=False, max_length=10, ) <NEW_LINE> lingualityInfo = models.OneToOneField("lingualityInfoType_model", verbose_name='Linguality', help_text='Groups information on the number of languages of the re' 'source part and of the way they are combined to each other', ) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> _unicode = u'<{} id="{}">'.format(self.__schema_name__, self.id) <NEW_LINE> return _unicode
Groups information on the textual part of the lexical/conceptual resource
62598fc13346ee7daa337779
class ParametersNode(object): <NEW_LINE> <INDENT> def __init__(self, kind='', name='', description='', value='', type_='', tags='', restrictions='', supported_formats=''): <NEW_LINE> <INDENT> self.kind = kind <NEW_LINE> self.name = name <NEW_LINE> self.description = description <NEW_LINE> self.value = value <NEW_LINE> self.type_ = type_ <NEW_LINE> self.tags = tags <NEW_LINE> self.supported_formats = supported_formats <NEW_LINE> self.restrictions = restrictions <NEW_LINE> self.path = None <NEW_LINE> self.parent = None <NEW_LINE> self.children = {} <NEW_LINE> self.cli_element = None <NEW_LINE> <DEDENT> def computePath(self, is_root=True, path=[]): <NEW_LINE> <INDENT> self.path = list(path) <NEW_LINE> if not is_root: <NEW_LINE> <INDENT> self.path.append(self.name) <NEW_LINE> <DEDENT> if not self.children: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for name, child in self.children.items(): <NEW_LINE> <INDENT> child.computePath(False, self.path) <NEW_LINE> <DEDENT> <DEDENT> def applyFunc(self, f): <NEW_LINE> <INDENT> f(self) <NEW_LINE> for c in self.children.values(): <NEW_LINE> <INDENT> c.applyFunc(f) <NEW_LINE> <DEDENT> <DEDENT> def find(self, path): <NEW_LINE> <INDENT> if not path: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> if not self.children.get(path[0]): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.children[path[0]].find(path[1:]) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> t = (self.name, self.description, self.value, self.type_, self.tags, self.supported_formats, self.children, self.path) <NEW_LINE> return 'ParametersNode(%s, %s, %s, %s, %s, %s, %s, path=%s)' % tuple(map(repr, t)) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str(self)
Represents a <NODE> tag inside the <PARAMETERS> tags. :ivar name: name attribute of the node :ivar description: text for description attribute of the node :ivar value: value attribute of the node :ivar type_: type attribute of the node :ivar tags: tags attribute of the node :ivar supported_formats: supported_format attribute of the node :ivar restrictions: restrictions attribute of the node :ivar path: the path to the node :ivar path: list of strings :ivar parent: link to the parent of the node :ivar children: children of the node :type children: dict with name to node mapping :ivar cli_element: CLIElement that this parameter is mapped to.
62598fc155399d3f05626778
class DeepImageFeaturizer(JavaTransformer, JavaMLReadable, JavaMLWritable): <NEW_LINE> <INDENT> inputCol = Param( Params._dummy(), "inputCol", "input column name.", typeConverter=TypeConverters.toString) <NEW_LINE> outputCol = Param( Params._dummy(), "outputCol", "output column name.", typeConverter=TypeConverters.toString) <NEW_LINE> modelName = Param( Params._dummy(), "modelName", "A deep learning model name", typeConverter=SparkDLTypeConverters.buildSupportedItemConverter( SUPPORTED_MODELS)) <NEW_LINE> scaleHint = Param( Params._dummy(), "scaleHint", "Hint which algorhitm to use for image " "resizing", typeConverter=_LazyScaleHintConverter()) <NEW_LINE> @keyword_only <NEW_LINE> def __init__(self, inputCol=None, outputCol=None, modelName=None, scaleHint="SCALE_AREA_AVERAGING"): <NEW_LINE> <INDENT> super(DeepImageFeaturizer, self).__init__() <NEW_LINE> self._java_obj = self._new_java_obj("com.databricks.sparkdl.DeepImageFeaturizer", self.uid) <NEW_LINE> self._setDefault(scaleHint="SCALE_AREA_AVERAGING") <NEW_LINE> kwargs = self._input_kwargs <NEW_LINE> self.setParams(**kwargs) <NEW_LINE> <DEDENT> @keyword_only <NEW_LINE> def setParams(self, inputCol=None, outputCol=None, modelName=None, scaleHint="SCALE_AREA_AVERAGING"): <NEW_LINE> <INDENT> kwargs = self._input_kwargs <NEW_LINE> self._set(**kwargs) <NEW_LINE> self._transfer_params_to_java() <NEW_LINE> return self <NEW_LINE> <DEDENT> def setInputCol(self, value): <NEW_LINE> <INDENT> return self._set(inputCol=value) <NEW_LINE> <DEDENT> def getInputCol(self): <NEW_LINE> <INDENT> return self.getOrDefault(self.inputCol) <NEW_LINE> <DEDENT> def setOutputCol(self, value): <NEW_LINE> <INDENT> return self._set(outputCol=value) <NEW_LINE> <DEDENT> def getOutputCol(self): <NEW_LINE> <INDENT> return self.getOrDefault(self.outputCol) <NEW_LINE> <DEDENT> def setModelName(self, value): <NEW_LINE> <INDENT> return self._set(modelName=value) <NEW_LINE> <DEDENT> def getModelName(self): <NEW_LINE> <INDENT> return self.getOrDefault(self.modelName) <NEW_LINE> <DEDENT> def setScaleHint(self, value): <NEW_LINE> <INDENT> return self._set(scaleHint=value) <NEW_LINE> <DEDENT> def getScaleHint(self): <NEW_LINE> <INDENT> return self.getOrDefault(self.scaleHint) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def read(cls): <NEW_LINE> <INDENT> return _DeepImageFeaturizerReader(cls) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _from_java(cls, java_stage): <NEW_LINE> <INDENT> res = DeepImageFeaturizer() <NEW_LINE> res._java_obj = java_stage <NEW_LINE> res._resetUid(java_stage.uid()) <NEW_LINE> res._transfer_params_from_java() <NEW_LINE> return res
Applies the model specified by its popular name, with its prediction layer(s) chopped off, to the image column in DataFrame. The output is a MLlib Vector so that DeepImageFeaturizer can be used in a MLlib Pipeline. The input image column should be ImageSchema.
62598fc1e1aae11d1e7ce956
class VauxooToolsServers(VauxooTools): <NEW_LINE> <INDENT> def __init__(self, app_name='Vauxoo Tools', usage_message='Generated by VauxooTools', options=None, log=False, vx_instance=VxConfigServers): <NEW_LINE> <INDENT> super(VauxooToolsServers, self).__init__(app_name=app_name, usage_message=usage_message, options=options, log=log, vx_instance=vx_instance) <NEW_LINE> <DEDENT> def get_shostname(self): <NEW_LINE> <INDENT> return self.params.get('sh') <NEW_LINE> <DEDENT> def get_sport(self): <NEW_LINE> <INDENT> return self.params.get('spo') <NEW_LINE> <DEDENT> def get_sdb(self): <NEW_LINE> <INDENT> return self.params.get('sd') <NEW_LINE> <DEDENT> def get_suser(self): <NEW_LINE> <INDENT> return self.params.get('su') <NEW_LINE> <DEDENT> def get_spwd(self): <NEW_LINE> <INDENT> return self.params.get('sp') <NEW_LINE> <DEDENT> def get_records(self): <NEW_LINE> <INDENT> return self.params.get('il')
Vauxoo tools is the base class to manage the common features necesary to work with this library.
62598fc1167d2b6e312b71d8
class AssignmentsView(APIView): <NEW_LINE> <INDENT> def post(self, request, classroom_pk): <NEW_LINE> <INDENT> verify_user_type(request, 'instructor') <NEW_LINE> request.data['classroom'] = classroom_pk <NEW_LINE> request.data['due_date'] = self.date_decode(request.data['due_date']) <NEW_LINE> serializer = post_serialize(request, AssignmentSerializer) <NEW_LINE> assignment = serializer.save() <NEW_LINE> response = Response(serializer.data, status=status.HTTP_201_CREATED) <NEW_LINE> response['Location'] = location(request, f'/instructor/classrooms/{classroom_pk}/assignments/{assignment.id}') <NEW_LINE> return response <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get(request, classroom_pk): <NEW_LINE> <INDENT> verify_user_type(request, 'instructor') <NEW_LINE> instructor = Instructor.objects.get(user=request.user) <NEW_LINE> classroom = Classroom.objects.get(instructor=instructor, id=classroom_pk) <NEW_LINE> assignments = Assignment.objects.filter(classroom=classroom) <NEW_LINE> serializer = AssignmentSerializer(assignments, many=True) <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def date_decode(due_date): <NEW_LINE> <INDENT> year, month, day, hour, minute = ( due_date['year'], due_date['month'], due_date['day'], due_date['hour'], due_date['minute']) <NEW_LINE> return datetime(year, month, day, hour, minute, second=59, tzinfo=pytz.UTC)
Add an assignment or view a list of all assignments in this classroom.
62598fc1956e5f7376df57af
class Tox21(MoleculeCSVDataset): <NEW_LINE> <INDENT> @deprecated('Import Tox21 from dgllife.data instead.', 'class') <NEW_LINE> def __init__(self, smiles_to_graph=smiles_to_bigraph, node_featurizer=None, edge_featurizer=None, load=True): <NEW_LINE> <INDENT> if 'pandas' not in sys.modules: <NEW_LINE> <INDENT> dgl_warning("Please install pandas") <NEW_LINE> <DEDENT> self._url = 'dataset/tox21.csv.gz' <NEW_LINE> data_path = get_download_dir() + '/tox21.csv.gz' <NEW_LINE> download(_get_dgl_url(self._url), path=data_path) <NEW_LINE> df = pd.read_csv(data_path) <NEW_LINE> self.id = df['mol_id'] <NEW_LINE> df = df.drop(columns=['mol_id']) <NEW_LINE> super(Tox21, self).__init__(df, smiles_to_graph, node_featurizer, edge_featurizer, "smiles", "tox21_dglgraph.bin", load=load) <NEW_LINE> self._weight_balancing() <NEW_LINE> <DEDENT> def _weight_balancing(self): <NEW_LINE> <INDENT> num_pos = F.sum(self.labels, dim=0) <NEW_LINE> num_indices = F.sum(self.mask, dim=0) <NEW_LINE> self._task_pos_weights = (num_indices - num_pos) / num_pos <NEW_LINE> <DEDENT> @property <NEW_LINE> def task_pos_weights(self): <NEW_LINE> <INDENT> return self._task_pos_weights
Tox21 dataset. The Toxicology in the 21st Century (https://tripod.nih.gov/tox21/challenge/) initiative created a public database measuring toxicity of compounds, which has been used in the 2014 Tox21 Data Challenge. The dataset contains qualitative toxicity measurements for 8014 compounds on 12 different targets, including nuclear receptors and stress response pathways. Each target results in a binary label. A common issue for multi-task prediction is that some datapoints are not labeled for all tasks. This is also the case for Tox21. In data pre-processing, we set non-existing labels to be 0 so that they can be placed in tensors and used for masking in loss computation. See examples below for more details. All molecules are converted into DGLGraphs. After the first-time construction, the DGLGraphs will be saved for reloading so that we do not need to reconstruct them everytime. Parameters ---------- smiles_to_graph: callable, str -> DGLGraph A function turning smiles into a DGLGraph. Default to :func:`dgl.data.chem.smiles_to_bigraph`. node_featurizer : callable, rdkit.Chem.rdchem.Mol -> dict Featurization for nodes like atoms in a molecule, which can be used to update ndata for a DGLGraph. Default to None. edge_featurizer : callable, rdkit.Chem.rdchem.Mol -> dict Featurization for edges like bonds in a molecule, which can be used to update edata for a DGLGraph. Default to None. load : bool Whether to load the previously pre-processed dataset or pre-process from scratch. ``load`` should be False when we want to try different graph construction and featurization methods and need to preprocess from scratch. Default to True.
62598fc1ff9c53063f51a8b0
class NoiseLevelType(Serializable): <NEW_LINE> <INDENT> _fields = ('PNCRSD', 'BNCRSD') <NEW_LINE> _required = _fields <NEW_LINE> _numeric_format = {fld: FLOAT_FORMAT for fld in _fields} <NEW_LINE> PNCRSD = FloatDescriptor( 'PNCRSD', _required, strict=DEFAULT_STRICT, docstring='Noise power level in fast time signal vector for f_IC(v,t) = f_0(v_CH_REF).') <NEW_LINE> BNCRSD = FloatDescriptor( 'BNCRSD', _required, strict=DEFAULT_STRICT, docstring='Noise Equivalent BW for the noise signal. Bandwidth BN_CRSD is expressed relative' ' to the fast time sample rate for the channel (fs).') <NEW_LINE> def __init__(self, PNCRSD=None, BNCRSD=None, **kwargs): <NEW_LINE> <INDENT> if '_xml_ns' in kwargs: <NEW_LINE> <INDENT> self._xml_ns = kwargs['_xml_ns'] <NEW_LINE> <DEDENT> if '_xml_ns_key' in kwargs: <NEW_LINE> <INDENT> self._xml_ns_key = kwargs['_xml_ns_key'] <NEW_LINE> <DEDENT> self.PNCRSD = PNCRSD <NEW_LINE> self.BNCRSD = BNCRSD <NEW_LINE> super(NoiseLevelType, self).__init__(**kwargs)
The thermal noise level information.
62598fc18a349b6b436864a0
class AppServiceCertificateOrderPaged(Paged): <NEW_LINE> <INDENT> _attribute_map = { 'next_link': {'key': 'nextLink', 'type': 'str'}, 'current_page': {'key': 'value', 'type': '[AppServiceCertificateOrder]'} } <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(AppServiceCertificateOrderPaged, self).__init__(*args, **kwargs)
A paging container for iterating over a list of :class:`AppServiceCertificateOrder <azure.mgmt.web.models.AppServiceCertificateOrder>` object
62598fc14f88993c371f063b
class NextContent: <NEW_LINE> <INDENT> __slots__ = ('_requestCnt', '_response', '_processing', '_data', '_stream', '_nextCnt') <NEW_LINE> def __init__(self, requestCnt, response, processing, data, stream): <NEW_LINE> <INDENT> assert isinstance(requestCnt, RequestContentMultiPart), 'Invalid request content %s' % requestCnt <NEW_LINE> assert isinstance(response, ResponseMultiPart), 'Invalid response %s' % response <NEW_LINE> assert isinstance(processing, Processing), 'Invalid processing %s' % processing <NEW_LINE> assert isinstance(data, DataMultiPart), 'Invalid data %s' % data <NEW_LINE> assert isinstance(stream, StreamMultiPart), 'Invalid stream %s' % stream <NEW_LINE> self._requestCnt = requestCnt <NEW_LINE> self._response = response <NEW_LINE> self._processing = processing <NEW_LINE> self._data = data <NEW_LINE> self._stream = stream <NEW_LINE> self._nextCnt = None <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> if self._nextCnt is not None: return self._nextCnt <NEW_LINE> stream, processing = self._stream, self._processing <NEW_LINE> assert isinstance(stream, StreamMultiPart), 'Invalid stream %s' % stream <NEW_LINE> assert isinstance(processing, Processing), 'Invalid processing %s' % processing <NEW_LINE> if not stream._flag & (FLAG_CONTENT_END | FLAG_MARK_END): <NEW_LINE> <INDENT> if not stream._flag & FLAG_MARK_START: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> stream._readToMark(self._data.packageSize) <NEW_LINE> if stream._flag & FLAG_MARK_START: break <NEW_LINE> if stream._flag & FLAG_END: return <NEW_LINE> <DEDENT> <DEDENT> req = processing.ctx.request() <NEW_LINE> self._nextCnt = reqCnt = self._requestCnt.__class__() <NEW_LINE> assert isinstance(req, RequestPopulate), 'Invalid request %s' % req <NEW_LINE> assert isinstance(reqCnt, RequestContentMultiPart), 'Invalid request content %s' % reqCnt <NEW_LINE> req.headers = stream._pullHeaders() <NEW_LINE> if stream._flag & FLAG_CLOSED: stream._flag ^= FLAG_CLOSED <NEW_LINE> reqCnt.source = stream <NEW_LINE> reqCnt.fetchNextContent = NextContent(reqCnt, self._response, self._processing, self._data, stream) <NEW_LINE> reqCnt.previousContent = self._requestCnt <NEW_LINE> chain = Chain(self._processing).process(request=req, requestCnt=reqCnt, response=self._response) <NEW_LINE> return chain.doAll().arg.requestCnt
Callable used for processing the next request content.
62598fc1a219f33f346c6a6a
class AcceptPackageTest(RouterBaseTest): <NEW_LINE> <INDENT> def test_accept_package(self): <NEW_LINE> <INDENT> payment, collateral = 50000000, 100000000 <NEW_LINE> deadline = int(time.time()) <NEW_LINE> package = self.create_package(payment, collateral, deadline, '12.970686,77.595590') <NEW_LINE> for member in (package['courier'], package['recipient']): <NEW_LINE> <INDENT> LOGGER.info('accepting package: %s for user %s', package['escrow'][0], member[1]) <NEW_LINE> self.call( 'accept_package', 200, 'member could not accept package', member[1], escrow_pubkey=package['escrow'][0], location='12.970686,77.595590') <NEW_LINE> events = routes.db.get_package_events(package['escrow'][0]) <NEW_LINE> expected_event_type = 'couriered' if member == package['courier'] else 'received' <NEW_LINE> self.assertEqual( events[-1]['event_type'], expected_event_type, "'{}' event expected, but '{}' got instead".format(expected_event_type, events[-1]['event_type']))
Test for accept_package endpoint.
62598fc17cff6e4e811b5c87
class Reponse(models.Model): <NEW_LINE> <INDENT> question = models.ForeignKey(Question) <NEW_LINE> contenu = models.CharField(max_length=512, help_text="Le texte de la réponse à la question") <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name="réponse" <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return str(self.question.id) + ' -> ' + self.contenu
La réponse d'un élève à une question
62598fc14c3428357761a51f
@attrs(**ATTRSCONFIG) <NEW_LINE> class LogGroup(Resource): <NEW_LINE> <INDENT> RESOURCE_TYPE = "AWS::Logs::LogGroup" <NEW_LINE> Properties: LogGroupProperties = attrib( factory=LogGroupProperties, converter=create_object_converter(LogGroupProperties), )
A Log Group for Logs. See Also: `AWS Cloud Formation documentation for LogGroup <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-loggroup.html>`_
62598fc163b5f9789fe853d5
class TemplatesWriter(XMLStreamWriterBase): <NEW_LINE> <INDENT> def __init__(self, device, templatesViewer): <NEW_LINE> <INDENT> XMLStreamWriterBase.__init__(self, device) <NEW_LINE> self.templatesViewer = templatesViewer <NEW_LINE> <DEDENT> def writeXML(self): <NEW_LINE> <INDENT> XMLStreamWriterBase.writeXML(self) <NEW_LINE> self.writeDTD('<!DOCTYPE Templates SYSTEM "Templates-{0}.dtd">'.format( templatesFileFormatVersion)) <NEW_LINE> self.writeComment(" eric6 templates file ") <NEW_LINE> self.writeComment( " Saved: {0} ".format(time.strftime('%Y-%m-%d, %H:%M:%S'))) <NEW_LINE> self.writeStartElement("Templates") <NEW_LINE> self.writeAttribute("version", templatesFileFormatVersion) <NEW_LINE> groups = self.templatesViewer.getAllGroups() <NEW_LINE> for group in groups: <NEW_LINE> <INDENT> self.writeStartElement("TemplateGroup") <NEW_LINE> self.writeAttribute("name", group.getName()) <NEW_LINE> self.writeAttribute("language", group.getLanguage()) <NEW_LINE> templates = group.getAllEntries() <NEW_LINE> for template in templates: <NEW_LINE> <INDENT> self.writeStartElement("Template") <NEW_LINE> self.writeAttribute("name", template.getName()) <NEW_LINE> self.writeTextElement( "TemplateDescription", template.getDescription()) <NEW_LINE> self.writeTextElement( "TemplateText", template.getTemplateText()) <NEW_LINE> self.writeEndElement() <NEW_LINE> <DEDENT> self.writeEndElement() <NEW_LINE> <DEDENT> self.writeEndElement() <NEW_LINE> self.writeEndDocument()
Class implementing the writer class for writing an XML templates file.
62598fc192d797404e388c94
class AttendanceForm(FlaskForm): <NEW_LINE> <INDENT> building = StringField('Prédio onde a unidade se localiza:', validators=[ DataRequired('Digite o nome do prédio.') ]) <NEW_LINE> floor = StringField('Digite o andar onde a unidade se localiza:', validators=[ DataRequired('Digite o andar.') ]) <NEW_LINE> room = StringField('Sala onde a unidade se localiza:', validators=[ DataRequired('Digite o nome da sala.') ]) <NEW_LINE> email = EmailField('Email da unidade:', validators=[ DataRequired('Digite o email.') ]) <NEW_LINE> opening = StringField('Horário de funcionamento:', validators=[ DataRequired('Digite o horário de funcionamento.') ]) <NEW_LINE> type1 = StringField('Tipo do telefone:', validators=[ DataRequired('Digite o tipo do telefone.') ]) <NEW_LINE> phone1 = StringField('Telefone:', validators=[ DataRequired('Digite o telefone para contato.') ]) <NEW_LINE> type2 = StringField('Tipo do telefone:') <NEW_LINE> phone2 = StringField('Telefone:') <NEW_LINE> type3 = StringField('Tipo do telefone:') <NEW_LINE> phone3 = StringField('Telefone:') <NEW_LINE> attendance_id = StringField(validators=[ DataRequired() ]) <NEW_LINE> create = SubmitField('Editar')
Form for adding attendance information to database
62598fc1a8370b77170f0645
class TestTopNReclaimQuery(ImpalaTestSuite): <NEW_LINE> <INDENT> QUERY = "select * from tpch.lineitem order by l_orderkey desc limit 10;" <NEW_LINE> MEM_LIMIT = "50m" <NEW_LINE> @classmethod <NEW_LINE> def get_workload(self): <NEW_LINE> <INDENT> return 'tpch' <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def add_test_dimensions(cls): <NEW_LINE> <INDENT> super(TestTopNReclaimQuery, cls).add_test_dimensions() <NEW_LINE> cls.ImpalaTestMatrix.add_dimension( create_uncompressed_text_dimension(cls.get_workload())) <NEW_LINE> <DEDENT> def test_top_n_reclaim(self, vector): <NEW_LINE> <INDENT> exec_options = vector.get_value('exec_option') <NEW_LINE> exec_options['mem_limit'] = self.MEM_LIMIT <NEW_LINE> result = self.execute_query(self.QUERY, exec_options) <NEW_LINE> runtime_profile = str(result.runtime_profile) <NEW_LINE> num_of_times_tuple_pool_reclaimed = re.findall( 'TuplePoolReclamations: ([0-9]*)', runtime_profile) <NEW_LINE> assert len(num_of_times_tuple_pool_reclaimed) > 0 <NEW_LINE> for n in num_of_times_tuple_pool_reclaimed: <NEW_LINE> <INDENT> assert int(n) > 0
Test class to validate that TopN periodically reclaims tuple pool memory and runs with a lower memory footprint.
62598fc1956e5f7376df57b0
class F(CTLS.F, PathFormula): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return 'F {}'.format(self._subformula[0])
A class representing CTL F-formulas.
62598fc15fc7496912d483ad
class ClientsAPI(Resource): <NEW_LINE> <INDENT> @jwt_required() <NEW_LINE> @roles_required(ROLE_EMPLOYEE) <NEW_LINE> def get(self): <NEW_LINE> <INDENT> clients = get_all_clients() <NEW_LINE> client_schema = BaseClientJsonSchema(many=True) <NEW_LINE> return client_schema.dump(clients).data
An API to get or create clients.
62598fc1be7bc26dc9251f8e