code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class RGBImagesFromList(BasePreprocessor): <NEW_LINE> <INDENT> interpolation_func = { 'as_is': lambda num_frames_param, num_frames: np.linspace(0, num_frames, num_frames, endpoint=False).astype(int), 'interpolate': lambda num_frames_param, num_frames: np.linspace(0, num_frames, num_frames_param, endpoint=False).astype(int), 'loop': loop_video_size_casting, 'back_and_forth': back_and_fourth_video_size_casting, 'random_beginning': make_random_beginning_video_size_casting(step=2), } <NEW_LINE> layouts_signatures = {'CTHW': (3, 0, 1, 2), 'TCHW': (0, 3, 1, 2)} <NEW_LINE> trial_data = [os.path.join(TRIAL_DATA_DIR, 'trial_img.jpg')] <NEW_LINE> def __init__(self, num_frames, mode='interpolate', seq_transformer=None, layout='CTHW', norm_mean=(0, 0, 0), norm_std=(1, 1, 1), *args, **kwargs): <NEW_LINE> <INDENT> self._num_frames = num_frames <NEW_LINE> self._interpolation = mode <NEW_LINE> self._layout = layout <NEW_LINE> self._norm_mean = np.array(norm_mean, dtype=float) <NEW_LINE> self._norm_std = np.array(norm_std, dtype=float) <NEW_LINE> super(RGBImagesFromList, self).__init__(*args, **kwargs) <NEW_LINE> self._transform = seq_transformer or (lambda x: x) <NEW_LINE> self._shape = self._shape <NEW_LINE> self._name = self._name or 'default' <NEW_LINE> <DEDENT> def get_image_array(self, data): <NEW_LINE> <INDENT> img_arr = [] <NEW_LINE> for im_file in data: <NEW_LINE> <INDENT> img = cv2.cvtColor(cv2.imread(im_file), cv2.COLOR_BGR2RGB) <NEW_LINE> img_arr.append(img) <NEW_LINE> <DEDENT> return img_arr <NEW_LINE> <DEDENT> def process(self, **kwargs): <NEW_LINE> <INDENT> processed = {} <NEW_LINE> for key, data in kwargs.items(): <NEW_LINE> <INDENT> inp_img_arr = self.get_image_array(data) <NEW_LINE> out_img_arr = self._transform(inp_img_arr) <NEW_LINE> time_slice = self.interpolation_func[self._interpolation](self._num_frames, len(out_img_arr)) <NEW_LINE> img_arr = np.array(out_img_arr)[time_slice, :] <NEW_LINE> img_arr = (img_arr - self._norm_mean) / self._norm_std <NEW_LINE> img_arr = img_arr.transpose(*self.layouts_signatures[self._layout]) <NEW_LINE> processed[key] = img_arr <NEW_LINE> <DEDENT> return processed
Provides a transformed RGB images in CTHW, TCHW layout from list of files
62598fc44f88993c371f0668
class QueryBuilder: <NEW_LINE> <INDENT> operators = { "$gt": ">", "$gte": ">=", "$lt": "<", "$lte": "<=", "$eq": "=", } <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.params = [] <NEW_LINE> self.current_column = None <NEW_LINE> <DEDENT> def group(self, value, action): <NEW_LINE> <INDENT> query = self.build(value) <NEW_LINE> return f" {action} ".join(query) <NEW_LINE> <DEDENT> def op(self, op, v): <NEW_LINE> <INDENT> assert self.current_column is not None <NEW_LINE> self.params.append(v) <NEW_LINE> op = QueryBuilder.operators[op] <NEW_LINE> return f'"{self.current_column}" {op} %s' <NEW_LINE> <DEDENT> def build(self, where): <NEW_LINE> <INDENT> query = [] <NEW_LINE> for k, v in where.items(): <NEW_LINE> <INDENT> if k == "$and": <NEW_LINE> <INDENT> query.append(self.group(v, "AND")) <NEW_LINE> <DEDENT> elif k == "$or": <NEW_LINE> <INDENT> query.append(self.group(v, "OR")) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if k in QueryBuilder.operators: <NEW_LINE> <INDENT> query.append(self.op(k, v)) <NEW_LINE> <DEDENT> elif isinstance(v, dict): <NEW_LINE> <INDENT> assert ( self.current_column is None ), f"Fields in '{self.current_column}' can't be nested." <NEW_LINE> old_current_column = self.current_column <NEW_LINE> self.current_column = k <NEW_LINE> query.append(self.group(v, "AND")) <NEW_LINE> self.current_column = old_current_column <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> query.append(f"{k}=%s") <NEW_LINE> self.params.append(v) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return query <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def build_query(where): <NEW_LINE> <INDENT> if where is None or len(where) == 0: <NEW_LINE> <INDENT> return {"query": "", "params": []} <NEW_LINE> <DEDENT> builder = QueryBuilder() <NEW_LINE> query = builder.group(where, "AND") <NEW_LINE> return {"query": query, "params": builder.params}
Builds a simple select query string
62598fc4aad79263cf42ea90
class VAE(Transform): <NEW_LINE> <INDENT> def __init__(self, encoder, decoder): <NEW_LINE> <INDENT> super(VAE, self).__init__() <NEW_LINE> self.encoder = encoder <NEW_LINE> self.decoder = decoder <NEW_LINE> <DEDENT> def call(self, inputs): <NEW_LINE> <INDENT> mu, logstd = self.encoder(inputs) <NEW_LINE> posterior = Normal(mu, logstd) <NEW_LINE> z = posterior.sample() <NEW_LINE> sample = self.decoder(z) <NEW_LINE> ldj = Normal(inputs).log_prob(sample) - posterior.log_prob(z) <NEW_LINE> return z, ldj <NEW_LINE> <DEDENT> def forward(self, inputs): <NEW_LINE> <INDENT> mu, logstd = self.encoder(inputs) <NEW_LINE> return Normal(mu, logstd).sample() <NEW_LINE> <DEDENT> def inverse(self, latent): <NEW_LINE> <INDENT> return self.decoder(latent)
Variational Autoencoder.
62598fc4a8370b77170f0697
class CursesAsciiPlot(object): <NEW_LINE> <INDENT> def __init__(self, curses_win, **kwargs): <NEW_LINE> <INDENT> self.win = curses_win <NEW_LINE> size = list(self.win.getmaxyx()[::-1]) <NEW_LINE> size[1] -= 1 <NEW_LINE> self.ascii_plotter = AsciiPlot(size=size, **kwargs) <NEW_LINE> <DEDENT> def plot(self, *args, **kwargs): <NEW_LINE> <INDENT> data = self.ascii_plotter.plot(*args, **kwargs) <NEW_LINE> self.win.clear() <NEW_LINE> for line_num, line in enumerate(data.split('\n')): <NEW_LINE> <INDENT> self.win.addstr(line_num, 0, line) <NEW_LINE> <DEDENT> self.win.refresh()
A Curses Ascii Plot
62598fc44428ac0f6e6587e1
class Inotify: <NEW_LINE> <INDENT> def __init__(self, flags): <NEW_LINE> <INDENT> inotify_fd = inotify_init(flags) <NEW_LINE> self._inotify_fd = inotify_fd <NEW_LINE> self._paths = {} <NEW_LINE> <DEDENT> def fileno(self): <NEW_LINE> <INDENT> return self._inotify_fd <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> os.close(self._inotify_fd) <NEW_LINE> <DEDENT> def add_watch(self, path, event_mask=IN_ALL_EVENTS): <NEW_LINE> <INDENT> path = os.path.normpath(path) <NEW_LINE> watch_id = inotify_add_watch( self._inotify_fd, path, event_mask | IN_MASK_ADD ) <NEW_LINE> self._paths[watch_id] = path <NEW_LINE> return watch_id <NEW_LINE> <DEDENT> def remove_watch(self, watch_id): <NEW_LINE> <INDENT> inotify_rm_watch(self._inotify_fd, watch_id) <NEW_LINE> <DEDENT> def read_events(self, event_buffer_size=DEFAULT_EVENT_BUFFER_SIZE): <NEW_LINE> <INDENT> if not self._paths: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> event_buffer = os.read(self._inotify_fd, event_buffer_size) <NEW_LINE> event_list = [] <NEW_LINE> for wd, mask, cookie, name in _parse_buffer(event_buffer): <NEW_LINE> <INDENT> name = name.decode() <NEW_LINE> wd_path = self._paths[wd] <NEW_LINE> src_path = os.path.normpath(os.path.join(wd_path, name)) <NEW_LINE> inotify_event = InotifyEvent(wd, mask, cookie, src_path) <NEW_LINE> _LOGGER.debug('Received event %r', inotify_event) <NEW_LINE> if inotify_event.mask & IN_IGNORED: <NEW_LINE> <INDENT> del self._paths[wd] <NEW_LINE> <DEDENT> event_list.append(inotify_event) <NEW_LINE> <DEDENT> return event_list
Inotify system interface.
62598fc4283ffb24f3cf3b41
class GetEventListTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.base_url = "http://127.0.0.1:8000/api/get_event_list/" <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> print(self.result) <NEW_LINE> <DEDENT> def test_get_event_list_eid_error(self): <NEW_LINE> <INDENT> r = requests.get(self.base_url, params={'eid': 901}) <NEW_LINE> self.result = r.json() <NEW_LINE> self.assertEqual(self.result['status'], 10022) <NEW_LINE> self.assertEqual(self.result['message'], 'query result is empty') <NEW_LINE> <DEDENT> def test_get_event_list_eid_success(self): <NEW_LINE> <INDENT> r = requests.get(self.base_url, params={'eid': 1}) <NEW_LINE> self.result = r.json() <NEW_LINE> self.assertEqual(self.result['status'], 200) <NEW_LINE> self.assertEqual(self.result['message'], 'success') <NEW_LINE> self.assertEqual(self.result['data']['name'], u'红米Pro发布会') <NEW_LINE> self.assertEqual(self.result['data']['address'], u'北京会展中心') <NEW_LINE> <DEDENT> def test_get_event_list_nam_result_null(self): <NEW_LINE> <INDENT> r = requests.get(self.base_url, params={'name': 'abc'}) <NEW_LINE> self.result = r.json() <NEW_LINE> self.assertEqual(self.result['status'], 10022) <NEW_LINE> self.assertEqual(self.result['message'], 'query result is empty') <NEW_LINE> <DEDENT> def test_get_event_list_name_find(self): <NEW_LINE> <INDENT> r = requests.get(self.base_url, params={'name': '发布会'}) <NEW_LINE> self.result = r.json() <NEW_LINE> self.assertEqual(self.result['status'], 200) <NEW_LINE> self.assertEqual(self.result['message'], 'success') <NEW_LINE> self.assertEqual(self.result['data'][0]['name'], u'红米Pro发布会') <NEW_LINE> self.assertEqual(self.result['data'][0]['address'], u'北京会展中心')
获得发布会信息
62598fc49f288636728189da
class SetDiscussionGroup(TLObject): <NEW_LINE> <INDENT> __slots__ = ["broadcast", "group"] <NEW_LINE> ID = 0x40582bb2 <NEW_LINE> QUALNAME = "functions.channels.SetDiscussionGroup" <NEW_LINE> def __init__(self, *, broadcast, group): <NEW_LINE> <INDENT> self.broadcast = broadcast <NEW_LINE> self.group = group <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(b: BytesIO, *args) -> "SetDiscussionGroup": <NEW_LINE> <INDENT> broadcast = TLObject.read(b) <NEW_LINE> group = TLObject.read(b) <NEW_LINE> return SetDiscussionGroup(broadcast=broadcast, group=group) <NEW_LINE> <DEDENT> def write(self) -> bytes: <NEW_LINE> <INDENT> b = BytesIO() <NEW_LINE> b.write(Int(self.ID, False)) <NEW_LINE> b.write(self.broadcast.write()) <NEW_LINE> b.write(self.group.write()) <NEW_LINE> return b.getvalue()
Attributes: LAYER: ``112`` Attributes: ID: ``0x40582bb2`` Parameters: broadcast: Either :obj:`InputChannelEmpty <pyrogram.api.types.InputChannelEmpty>`, :obj:`InputChannel <pyrogram.api.types.InputChannel>` or :obj:`InputChannelFromMessage <pyrogram.api.types.InputChannelFromMessage>` group: Either :obj:`InputChannelEmpty <pyrogram.api.types.InputChannelEmpty>`, :obj:`InputChannel <pyrogram.api.types.InputChannel>` or :obj:`InputChannelFromMessage <pyrogram.api.types.InputChannelFromMessage>` Returns: ``bool``
62598fc47c178a314d78d75c
class Human: <NEW_LINE> <INDENT> species = "Mammal" <NEW_LINE> def __init__(self, name, age): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.age = age <NEW_LINE> self.__weight = 90 <NEW_LINE> <DEDENT> def does(self, action): <NEW_LINE> <INDENT> return "{} does {}".format(self.name, action) <NEW_LINE> <DEDENT> def set_weight(self, new_weight): <NEW_LINE> <INDENT> self.__weight = new_weight
This is a class for humans
62598fc499fddb7c1ca62f4b
class ODM_GCPoint(object): <NEW_LINE> <INDENT> def __init__(self, x, y, z): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = y <NEW_LINE> self.z = z
docstring for ODMPoint
62598fc45166f23b2e24369e
class CognitiveServicesAccountCreateParameters(Model): <NEW_LINE> <INDENT> _validation = { 'sku': {'required': True}, 'kind': {'required': True}, 'location': {'required': True}, 'properties': {'required': True}, } <NEW_LINE> _attribute_map = { 'sku': {'key': 'sku', 'type': 'Sku'}, 'kind': {'key': 'kind', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'properties': {'key': 'properties', 'type': 'object'}, } <NEW_LINE> def __init__(self, sku, kind, location, properties, tags=None): <NEW_LINE> <INDENT> self.sku = sku <NEW_LINE> self.kind = kind <NEW_LINE> self.location = location <NEW_LINE> self.tags = tags <NEW_LINE> self.properties = properties
The parameters to provide for the account. :param sku: Required. Gets or sets the SKU of the resource. :type sku: :class:`Sku <azure.mgmt.cognitiveservices.models.Sku>` :param kind: Required. Gets or sets the Kind of the resource. Possible values include: 'Academic', 'Bing.Autosuggest', 'Bing.Search', 'Bing.Speech', 'Bing.SpellCheck', 'ComputerVision', 'ContentModerator', 'CustomSpeech', 'Emotion', 'Face', 'LUIS', 'Recommendations', 'SpeakerRecognition', 'Speech', 'SpeechTranslation', 'TextAnalytics', 'TextTranslation', 'WebLM' :type kind: str or :class:`Kind <azure.mgmt.cognitiveservices.models.Kind>` :param location: Required. Gets or sets the location of the resource. This will be one of the supported and registered Azure Geo Regions (e.g. West US, East US, Southeast Asia, etc.). The geo region of a resource cannot be changed once it is created, but if an identical geo region is specified on update the request will succeed. :type location: str :param tags: Gets or sets a list of key value pairs that describe the resource. These tags can be used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key no greater than 128 characters and value no greater than 256 characters. :type tags: dict :param properties: Must exist in the request. Must be an empty object. Must not be null. :type properties: object
62598fc44a966d76dd5ef192
class MenuBar(WidgetComponent): <NEW_LINE> <INDENT> menus = Property(depends_on='children') <NEW_LINE> @cached_property <NEW_LINE> def _get_menus(self): <NEW_LINE> <INDENT> isinst = isinstance <NEW_LINE> menus = (child for child in self.children if isinst(child, Menu)) <NEW_LINE> return tuple(menus)
A widget used as a menu bar in a MainWindow.
62598fc4283ffb24f3cf3b42
class OptionsAccountBook(object): <NEW_LINE> <INDENT> openapi_types = {'time': 'float', 'change': 'str', 'balance': 'str', 'type': 'str', 'text': 'str'} <NEW_LINE> attribute_map = {'time': 'time', 'change': 'change', 'balance': 'balance', 'type': 'type', 'text': 'text'} <NEW_LINE> def __init__( self, time=None, change=None, balance=None, type=None, text=None, local_vars_configuration=None ): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._time = None <NEW_LINE> self._change = None <NEW_LINE> self._balance = None <NEW_LINE> self._type = None <NEW_LINE> self._text = None <NEW_LINE> self.discriminator = None <NEW_LINE> if time is not None: <NEW_LINE> <INDENT> self.time = time <NEW_LINE> <DEDENT> if change is not None: <NEW_LINE> <INDENT> self.change = change <NEW_LINE> <DEDENT> if balance is not None: <NEW_LINE> <INDENT> self.balance = balance <NEW_LINE> <DEDENT> if type is not None: <NEW_LINE> <INDENT> self.type = type <NEW_LINE> <DEDENT> if text is not None: <NEW_LINE> <INDENT> self.text = text <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def time(self): <NEW_LINE> <INDENT> return self._time <NEW_LINE> <DEDENT> @time.setter <NEW_LINE> def time(self, time): <NEW_LINE> <INDENT> self._time = time <NEW_LINE> <DEDENT> @property <NEW_LINE> def change(self): <NEW_LINE> <INDENT> return self._change <NEW_LINE> <DEDENT> @change.setter <NEW_LINE> def change(self, change): <NEW_LINE> <INDENT> self._change = change <NEW_LINE> <DEDENT> @property <NEW_LINE> def balance(self): <NEW_LINE> <INDENT> return self._balance <NEW_LINE> <DEDENT> @balance.setter <NEW_LINE> def balance(self, balance): <NEW_LINE> <INDENT> self._balance = balance <NEW_LINE> <DEDENT> @property <NEW_LINE> def type(self): <NEW_LINE> <INDENT> return self._type <NEW_LINE> <DEDENT> @type.setter <NEW_LINE> def type(self, type): <NEW_LINE> <INDENT> self._type = type <NEW_LINE> <DEDENT> @property <NEW_LINE> def text(self): <NEW_LINE> <INDENT> return self._text <NEW_LINE> <DEDENT> @text.setter <NEW_LINE> def text(self, text): <NEW_LINE> <INDENT> self._text = text <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.openapi_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value)) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict( map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items(), ) ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, OptionsAccountBook): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, OptionsAccountBook): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict()
NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually.
62598fc4f548e778e596b85d
class CreateTodo(graphene.Mutation): <NEW_LINE> <INDENT> todo = graphene.Field(TodoType) <NEW_LINE> class Arguments: <NEW_LINE> <INDENT> title = graphene.String(required=True) <NEW_LINE> description = graphene.String(required=True) <NEW_LINE> priority = graphene.String(default_value="low") <NEW_LINE> <DEDENT> def mutate(self, info, **kwargs): <NEW_LINE> <INDENT> user = info.context.user <NEW_LINE> if user.is_anonymous: <NEW_LINE> <INDENT> raise GraphQLError("You must be logged in to create new todo item") <NEW_LINE> <DEDENT> todo = ToDo( title=kwargs.get("title"), description=kwargs.get("description"), priority=kwargs.get("priority").upper(), created_by=user, ) <NEW_LINE> todo.save() <NEW_LINE> return CreateTodo(todo=todo)
A class to create a new todo item. Methods ------- mutate(info, **kwargs): creates a new todo
62598fc4099cdd3c63675541
class StudyNotCreated(Exception): <NEW_LINE> <INDENT> pass
Exception type thrown when an attempt to create a submission with an invalid study id is made.
62598fc40fa83653e46f51a5
@register('direct') <NEW_LINE> class Direct(Driver): <NEW_LINE> <INDENT> def run(self, *command): <NEW_LINE> <INDENT> for key, value in self.environment().items(): <NEW_LINE> <INDENT> os.environ[key] = value <NEW_LINE> <DEDENT> return self._run([self.target] + list(command)) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def valid_target(target): <NEW_LINE> <INDENT> return find_executable(target)
Execute the application directly.
62598fc471ff763f4b5e7a3c
class FakeModule(object): <NEW_LINE> <INDENT> def __init__(self, parser): <NEW_LINE> <INDENT> self.parser = parser <NEW_LINE> self.pre_parse_string = None <NEW_LINE> self.string = None <NEW_LINE> self.config = None <NEW_LINE> <DEDENT> def pre_parse(self, string): <NEW_LINE> <INDENT> self.pre_parse_string = string <NEW_LINE> if string == "test message": <NEW_LINE> <INDENT> return "habitat" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("No callsign found.") <NEW_LINE> <DEDENT> <DEDENT> def parse(self, string, config): <NEW_LINE> <INDENT> self.string = string <NEW_LINE> self.config = config <NEW_LINE> if string == "test message": <NEW_LINE> <INDENT> return {"data": True} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Invalid message string given.")
An empty mock parser module
62598fc4167d2b6e312b7236
class Question(models.Model): <NEW_LINE> <INDENT> title = models.CharField(max_length=500) <NEW_LINE> content = models.TextField() <NEW_LINE> code = models.CharField(max_length=8, null=True, blank=True) <NEW_LINE> user = models.ForeignKey(User, on_delete=models.CASCADE) <NEW_LINE> categories = models.ManyToManyField('Category') <NEW_LINE> tags = models.ManyToManyField('Tag') <NEW_LINE> date_created = models.DateTimeField(auto_now_add=True) <NEW_LINE> date_updated = models.DateTimeField(auto_now=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.title
Question model
62598fc463b5f9789fe85432
@unittest.skip("Enable this and fill in credentials if you want it to run") <NEW_LINE> class TestBasic(unittest.TestCase): <NEW_LINE> <INDENT> def test_create_process_with_logonw(self): <NEW_LINE> <INDENT> _advapi32.CreateProcessWithLogonW( username=None, domain=None, password=None, command_line='%s -c "import sys; print(sys.executable)"' % sys.executable )
Do just enough to exercise the module: ensure that it imports and that basically functionality functions
62598fc4ad47b63b2c5a7b17
class Arc(XYObjectMixin, LineAndFillMixin, DrawObject): <NEW_LINE> <INDENT> def __init__(self, StartXY, EndXY, CenterXY, LineColor = "Black", LineStyle = "Solid", LineWidth = 1, FillColor = None, FillStyle = "Solid", InForeground = False): <NEW_LINE> <INDENT> DrawObject.__init__(self, InForeground) <NEW_LINE> radius = N.sqrt( (StartXY[0]-CenterXY[0])**2 + (StartXY[1]-CenterXY[1])**2 ) <NEW_LINE> minX = CenterXY[0]-radius <NEW_LINE> minY = CenterXY[1]-radius <NEW_LINE> maxX = CenterXY[0]+radius <NEW_LINE> maxY = CenterXY[1]+radius <NEW_LINE> XY = [minX,minY] <NEW_LINE> WH = [maxX-minX,maxY-minY] <NEW_LINE> self.XY = N.asarray( XY, N.float).reshape((2,)) <NEW_LINE> self.WH = N.asarray( WH, N.float).reshape((2,)) <NEW_LINE> self.StartXY = N.asarray(StartXY, N.float).reshape((2,)) <NEW_LINE> self.CenterXY = N.asarray(CenterXY, N.float).reshape((2,)) <NEW_LINE> self.EndXY = N.asarray(EndXY, N.float).reshape((2,)) <NEW_LINE> self.CalcBoundingBox() <NEW_LINE> self.LineColor = LineColor <NEW_LINE> self.LineStyle = LineStyle <NEW_LINE> self.LineWidth = LineWidth <NEW_LINE> self.FillColor = FillColor <NEW_LINE> self.FillStyle = FillStyle <NEW_LINE> self.HitLineWidth = max(LineWidth,self.MinHitLineWidth) <NEW_LINE> self.SetPen(LineColor, LineStyle, LineWidth) <NEW_LINE> self.SetBrush(FillColor, FillStyle) <NEW_LINE> <DEDENT> def Move(self, Delta): <NEW_LINE> <INDENT> Delta = N.asarray(Delta, N.float) <NEW_LINE> self.XY += Delta <NEW_LINE> self.StartXY += Delta <NEW_LINE> self.CenterXY += Delta <NEW_LINE> self.EndXY += Delta <NEW_LINE> self.BoundingBox += Delta <NEW_LINE> if self._Canvas: <NEW_LINE> <INDENT> self._Canvas.BoundingBoxDirty = True <NEW_LINE> <DEDENT> <DEDENT> def _Draw(self, dc , WorldToPixel, ScaleWorldToPixel, HTdc=None): <NEW_LINE> <INDENT> self.SetUpDraw(dc , WorldToPixel, ScaleWorldToPixel, HTdc) <NEW_LINE> StartXY = WorldToPixel(self.StartXY) <NEW_LINE> EndXY = WorldToPixel(self.EndXY) <NEW_LINE> CenterXY = WorldToPixel(self.CenterXY) <NEW_LINE> dc.DrawArc(StartXY, EndXY, CenterXY) <NEW_LINE> if HTdc and self.HitAble: <NEW_LINE> <INDENT> HTdc.DrawArc(StartXY, EndXY, CenterXY) <NEW_LINE> <DEDENT> <DEDENT> def CalcBoundingBox(self): <NEW_LINE> <INDENT> self.BoundingBox = BBox.asBBox( N.array((self.XY, (self.XY + self.WH) ), N.float) ) <NEW_LINE> if self._Canvas: <NEW_LINE> <INDENT> self._Canvas.BoundingBoxDirty = True
Draws an arc of a circle, centered on point ``CenterXY``, from the first point ``StartXY`` to the second ``EndXY``. The arc is drawn in an anticlockwise direction from the start point to the end point.
62598fc460cbc95b063645fd
class IserviceUser(User): <NEW_LINE> <INDENT> name = models.CharField(max_length=100) <NEW_LINE> picture = models.CharField(null=True, max_length=150) <NEW_LINE> favorites_services = models.ManyToManyField('Service') <NEW_LINE> def add_favorite_service(self, service): <NEW_LINE> <INDENT> self.favorites_services.add(service) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def create_user(**kwargs): <NEW_LINE> <INDENT> user = IserviceUser() <NEW_LINE> if 'name' in kwargs: <NEW_LINE> <INDENT> user.name = kwargs['name'] <NEW_LINE> <DEDENT> if 'email' in kwargs: <NEW_LINE> <INDENT> user.email = kwargs['email'] <NEW_LINE> user.username = user.email <NEW_LINE> <DEDENT> if 'picture' in kwargs: <NEW_LINE> <INDENT> user.picture = kwargs['picture'] <NEW_LINE> <DEDENT> if 'password' in kwargs: <NEW_LINE> <INDENT> user.set_password(kwargs['password']) <NEW_LINE> <DEDENT> user.save() <NEW_LINE> if 'phone' in kwargs: <NEW_LINE> <INDENT> for phone_number in kwargs['phone']: <NEW_LINE> <INDENT> phone = PhoneNumber(phone=str(phone_number), user=user, service=None) <NEW_LINE> phone.save() <NEW_LINE> <DEDENT> <DEDENT> return user
This class represents a system user.
62598fc4f9cc0f698b1c5431
class TestCitationRetrieval(TestCase): <NEW_LINE> <INDENT> def create_app(self): <NEW_LINE> <INDENT> app_ = app.create_app() <NEW_LINE> return app_ <NEW_LINE> <DEDENT> @mock.patch('metrics_service.models.execute_SQL_query', return_value=testdata) <NEW_LINE> def test_get_citations(self, mock_execute_SQL_query): <NEW_LINE> <INDENT> from metrics_service.models import get_citations, get_citations_single <NEW_LINE> data = get_citations(testset) <NEW_LINE> self.assertEqual(isinstance(data, list), True) <NEW_LINE> self.assertTrue( False not in [x.__class__.__name__ == 'MetricsModel' for x in data]) <NEW_LINE> data = get_citations(testset, no_zero=False) <NEW_LINE> self.assertEqual(isinstance(data, list), True) <NEW_LINE> data = get_citations_single('a') <NEW_LINE> self.assertEqual(isinstance(data, list), True)
Check if the citation retrieval function returns expected results
62598fc4aad79263cf42ea95
class MESH_OT_flip_custom_normals(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "mesh.flip_custom_normals" <NEW_LINE> bl_label = "Flip Custom Normals" <NEW_LINE> bl_options = {'UNDO'} <NEW_LINE> @classmethod <NEW_LINE> def poll(cls, context): <NEW_LINE> <INDENT> return context.object and context.object.type == 'MESH' and context.object.mode == 'OBJECT' <NEW_LINE> <DEDENT> def execute(self, context): <NEW_LINE> <INDENT> me = context.object.data <NEW_LINE> if me.has_custom_normals: <NEW_LINE> <INDENT> me.calc_normals_split() <NEW_LINE> clnors = [0.0] * 3 * len(me.loops) <NEW_LINE> me.loops.foreach_get("normal", clnors) <NEW_LINE> <DEDENT> bpy.ops.object.mode_set(mode='EDIT') <NEW_LINE> bpy.ops.mesh.select_all(action='SELECT') <NEW_LINE> bpy.ops.mesh.flip_normals() <NEW_LINE> bpy.ops.object.mode_set(mode='OBJECT') <NEW_LINE> me = context.object.data <NEW_LINE> if me.has_custom_normals: <NEW_LINE> <INDENT> clnors[:] = list(zip(*[(-n for n in clnors)] * 3)) <NEW_LINE> for p in me.polygons: <NEW_LINE> <INDENT> ls = p.loop_start + 1 <NEW_LINE> le = ls + p.loop_total - 1 <NEW_LINE> clnors[ls:le] = reversed(clnors[ls:le]) <NEW_LINE> <DEDENT> me.normals_split_custom_set(clnors) <NEW_LINE> <DEDENT> context.scene.update() <NEW_LINE> return {'FINISHED'}
Flip active mesh's normals, including custom ones (only in Object mode)
62598fc4956e5f7376df57de
class Area(AttrsMixin, XHTMLElement): <NEW_LINE> <INDENT> XMLNAME = (XHTML_NAMESPACE, 'area') <NEW_LINE> XMLATTR_shape = ('shape', Shape.from_str_lower, Shape.to_str) <NEW_LINE> XMLATTR_coords = ('coords', Coords.from_str, to_text) <NEW_LINE> XMLATTR_href = ('href', uri.URI.from_octets, to_text) <NEW_LINE> XMLATTR_target = 'target' <NEW_LINE> XMLATTR_nohref = ('nohref', NoHRef.from_str_lower, NoHRef.to_str) <NEW_LINE> XMLATTR_alt = 'alt' <NEW_LINE> XMLATTR_tabindex = ('tabindex', xsi.integer_from_str, xsi.integer_to_str) <NEW_LINE> XMLATTR_accesskey = 'accesskey' <NEW_LINE> XMLCONTENT = xml.ElementType.Empty <NEW_LINE> def __init__(self, parent): <NEW_LINE> <INDENT> super(Area, self).__init__(parent) <NEW_LINE> self.shape = Shape.rect <NEW_LINE> self.alt = ""
Client-side image map area :: <!ELEMENT AREA - O EMPTY -- client-side image map area --> <!ATTLIST AREA %attrs; -- %coreattrs, %i18n, %events -- shape %Shape; rect -- controls interpretation of coords -- coords %Coords; #IMPLIED -- comma-separated list of lengths -- href %URI; #IMPLIED -- URI for linked resource -- target %FrameTarget; #IMPLIED -- render in this frame -- nohref (nohref) #IMPLIED -- this region has no action -- alt %Text; #REQUIRED -- short description -- tabindex NUMBER #IMPLIED -- position in tabbing order -- accesskey %Character; #IMPLIED -- accessibility key character -- onfocus %Script; #IMPLIED -- the element got the focus -- onblur %Script; #IMPLIED -- the element lost the focus -- > The event attributes are not mapped however the target attribute is, even though it relates on to frames and the loose DTD.
62598fc4bf627c535bcb1767
class Tempering(FKSMCsampler): <NEW_LINE> <INDENT> def __init__(self, model, mh_options=None, exponents=None): <NEW_LINE> <INDENT> FKSMCsampler.__init__(self, model, mh_options=mh_options) <NEW_LINE> self.exponents = exponents <NEW_LINE> self.deltas = np.diff(exponents) <NEW_LINE> <DEDENT> @property <NEW_LINE> def T(self): <NEW_LINE> <INDENT> return self.deltas.shape[0] <NEW_LINE> <DEDENT> def logG(self, t, xp, x): <NEW_LINE> <INDENT> delta = self.deltas[t] <NEW_LINE> return self.logG_tempering(x, delta) <NEW_LINE> <DEDENT> def logG_tempering(self, x, delta): <NEW_LINE> <INDENT> dl = delta * x.llik <NEW_LINE> x.lpost += dl <NEW_LINE> self.update_path_sampling_est(x, delta) <NEW_LINE> return dl <NEW_LINE> <DEDENT> def update_path_sampling_est(self, x, delta): <NEW_LINE> <INDENT> grid_size = 10 <NEW_LINE> binwidth = delta / (grid_size - 1) <NEW_LINE> new_ps_est = x.path_sampling[-1] <NEW_LINE> for i, e in enumerate(np.linspace(0., delta, grid_size)): <NEW_LINE> <INDENT> mult = 0.5 if i==0 or i==grid_size-1 else 1. <NEW_LINE> new_ps_est += (mult * binwidth * np.average(x.llik, weights=rs.exp_and_normalise(e * x.llik))) <NEW_LINE> <DEDENT> x.path_sampling.append(new_ps_est) <NEW_LINE> <DEDENT> def compute_post(self, x, epn): <NEW_LINE> <INDENT> x.lprior = self.model.prior.logpdf(x.theta) <NEW_LINE> x.llik = self.model.loglik(x.theta) <NEW_LINE> if epn > 0.: <NEW_LINE> <INDENT> x.lpost = x.lprior + epn * x.llik <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x.lpost = x.lprior.copy() <NEW_LINE> <DEDENT> <DEDENT> def M0(self, N): <NEW_LINE> <INDENT> x0 = TemperingParticles(theta=self.model.prior.rvs(size=N)) <NEW_LINE> self.compute_post(x0, 0.) <NEW_LINE> return x0 <NEW_LINE> <DEDENT> def M(self, t, Xp): <NEW_LINE> <INDENT> epn = self.exponents[t] <NEW_LINE> compute_target = lambda x: self.compute_post(x, epn) <NEW_LINE> return Xp.Metropolis(compute_target, self.mh_options)
FeynmanKac class for tempering SMC. Parameters ---------- exponents: list-like Tempering exponents (must starts with 0., and ends with 1.) See base class for other parameters.
62598fc450812a4eaa620d45
class SequenceIntField(fields.AbstractIntField): <NEW_LINE> <INDENT> def __init__(self, sequence, **kwargs): <NEW_LINE> <INDENT> if not isinstance(sequence, SQLSequence): <NEW_LINE> <INDENT> raise TypeError('Sequence provided must be an instance of ' 'pyxact.sequences.SQLSequence') <NEW_LINE> <DEDENT> self.sequence = sequence <NEW_LINE> super().__init__(py_type=int, sql_type=None, nullable=True, **kwargs) <NEW_LINE> <DEDENT> def update(self, instance, context, cursor): <NEW_LINE> <INDENT> value = self.sequence.nextval(cursor) <NEW_LINE> setattr(instance, self.slot_name, value) <NEW_LINE> return value
Represents an integer field in an SQLTransaction that has a link to a SQLSequence. It can be retrieved and set as a normal SQLField, but when get_new_context is called on the SQLTransaction, it will be updated from the next value of the sequence and the name:value pair will be returned as part of the context dictionary. Within SQLRecord subclasses, an ContextIntField can be used to represent this value. This field type has no direct use inside an SQLRecord.
62598fc492d797404e388cc2
class Bluetooth(Sensor): <NEW_LINE> <INDENT> bluetooth_state = models.BooleanField(default=False) <NEW_LINE> bluetooth_is_discovering = models.BooleanField(default=False) <NEW_LINE> bluetooth_scan_mode = models.BooleanField(default=False) <NEW_LINE> bluetooth_local_address = models.BooleanField(default=False) <NEW_LINE> bluetooth_local_name = models.BooleanField(default=False) <NEW_LINE> def show_name(self): <NEW_LINE> <INDENT> return "Bluetooth"
Model for Bluetooth
62598fc4a219f33f346c6ac8
class Service: <NEW_LINE> <INDENT> priority = None <NEW_LINE> types_list = [] <NEW_LINE> attributes_map = {} <NEW_LINE> def __init__(self, priority = "none"): <NEW_LINE> <INDENT> self.priority = priority <NEW_LINE> self.types_list = [] <NEW_LINE> self.attributes_map = {} <NEW_LINE> <DEDENT> def get_attribute(self, attribute_name): <NEW_LINE> <INDENT> return self.attributes_map.get(attribute_name, None) <NEW_LINE> <DEDENT> def set_attribute(self, attribute_name, attribute_value): <NEW_LINE> <INDENT> self.attributes_map[attribute_name] = attribute_value
The service class, describing a yadis service.
62598fc45fcc89381b2662ad
class SessionType(messages.Enum): <NEW_LINE> <INDENT> NOT_SPECIFIED = 1 <NEW_LINE> LECTURE = 2 <NEW_LINE> KEYNODE = 3 <NEW_LINE> WORKSHOP = 4
SessionType -- session type enumeration value
62598fc44f88993c371f066b
class ProductLogsConfigDyn(LEDMTree): <NEW_LINE> <INDENT> def __init__(self, data): <NEW_LINE> <INDENT> super().__init__(data) <NEW_LINE> <DEDENT> @property <NEW_LINE> def event_logs(self): <NEW_LINE> <INDENT> event_codes = [] <NEW_LINE> event_code_nodes = self.data.findAll("EventCode") <NEW_LINE> for event_code_node in event_code_nodes: <NEW_LINE> <INDENT> event_codes.append(event_code_node.text) <NEW_LINE> <DEDENT> return event_codes
ProductConfigDyn tree /DevMgmt/ProductLogsConfigDyn.xml
62598fc4a05bb46b3848ab2d
@group('smoke') <NEW_LINE> class Echo(base_tests.SimpleProtocol): <NEW_LINE> <INDENT> def runTest(self): <NEW_LINE> <INDENT> request = ofp.message.echo_request() <NEW_LINE> response, pkt = self.controller.transact(request) <NEW_LINE> self.assertTrue(response is not None, "Did not get echo reply") <NEW_LINE> self.assertEqual(response.type, ofp.OFPT_ECHO_REPLY, 'response is not echo_reply') <NEW_LINE> self.assertEqual(request.xid, response.xid, 'response xid != request xid') <NEW_LINE> self.assertEqual(len(response.data), 0, 'response data non-empty')
Test echo response with no data
62598fc471ff763f4b5e7a3e
class DictWrapper(dict): <NEW_LINE> <INDENT> def __init__(self, data, func, prefix): <NEW_LINE> <INDENT> super(DictWrapper, self).__init__(data) <NEW_LINE> self.func = func <NEW_LINE> self.prefix = prefix <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> if key.startswith(self.prefix): <NEW_LINE> <INDENT> use_func = True <NEW_LINE> key = key[len(self.prefix):] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> use_func = False <NEW_LINE> <DEDENT> value = super(DictWrapper, self).__getitem__(key) <NEW_LINE> if use_func: <NEW_LINE> <INDENT> return self.func(value) <NEW_LINE> <DEDENT> return value
Wraps accesses to a dictionary so that certain values (those starting with the specified prefix) are passed through a function before being returned. The prefix is removed before looking up the real value. Used by the SQL construction code to ensure that values are correctly quoted before being used.
62598fc44c3428357761a57e
class BasePluginsParser(BaseParser): <NEW_LINE> <INDENT> NAME = 'base_plugin_parser' <NEW_LINE> DESCRIPTION = u'' <NEW_LINE> _plugin_classes = None <NEW_LINE> @classmethod <NEW_LINE> def DeregisterPlugin(cls, plugin_class): <NEW_LINE> <INDENT> plugin_name = plugin_class.NAME.lower() <NEW_LINE> if plugin_name not in cls._plugin_classes: <NEW_LINE> <INDENT> raise KeyError( u'Plugin class not set for name: {0:s}.'.format( plugin_class.NAME)) <NEW_LINE> <DEDENT> del cls._plugin_classes[plugin_name] <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def GetPluginNames(cls, parser_filter_string=None): <NEW_LINE> <INDENT> plugin_names = [] <NEW_LINE> for plugin_name, _ in cls.GetPlugins( parser_filter_string=parser_filter_string): <NEW_LINE> <INDENT> plugin_names.append(plugin_name) <NEW_LINE> <DEDENT> return plugin_names <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def GetPluginObjects(cls, parser_filter_string=None): <NEW_LINE> <INDENT> plugin_objects = [] <NEW_LINE> for _, plugin_class in cls.GetPlugins( parser_filter_string=parser_filter_string): <NEW_LINE> <INDENT> plugin_object = plugin_class() <NEW_LINE> plugin_objects.append(plugin_object) <NEW_LINE> <DEDENT> return plugin_objects <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def GetPlugins(cls, parser_filter_string=None): <NEW_LINE> <INDENT> if parser_filter_string: <NEW_LINE> <INDENT> includes, excludes = manager.ParsersManager.GetFilterListsFromString( parser_filter_string) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> includes = None <NEW_LINE> excludes = None <NEW_LINE> <DEDENT> for plugin_name, plugin_class in cls._plugin_classes.iteritems(): <NEW_LINE> <INDENT> if excludes and plugin_name in excludes: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if includes and plugin_name not in includes: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> yield plugin_name, plugin_class <NEW_LINE> <DEDENT> <DEDENT> @abc.abstractmethod <NEW_LINE> def Parse(self, parser_context, file_entry, parser_chain=None): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def RegisterPlugin(cls, plugin_class): <NEW_LINE> <INDENT> plugin_name = plugin_class.NAME.lower() <NEW_LINE> if plugin_name in cls._plugin_classes: <NEW_LINE> <INDENT> raise KeyError(( u'Plugin class already set for name: {0:s}.').format( plugin_class.NAME)) <NEW_LINE> <DEDENT> cls._plugin_classes[plugin_name] = plugin_class <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def RegisterPlugins(cls, plugin_classes): <NEW_LINE> <INDENT> for plugin_class in plugin_classes: <NEW_LINE> <INDENT> cls.RegisterPlugin(plugin_class) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def SupportsPlugins(cls): <NEW_LINE> <INDENT> return True
Class that implements the parser with plugins object interface.
62598fc4283ffb24f3cf3b46
class TextMagicClient(_TextMagicClientBase): <NEW_LINE> <INDENT> api_url = 'https://www.textmagic.com/app/api' <NEW_LINE> def __init__(self, username, password): <NEW_LINE> <INDENT> super(TextMagicClient, self).__init__(username, password) <NEW_LINE> <DEDENT> def _submit_request(self, params_dict): <NEW_LINE> <INDENT> params_dict['username'] = self.username <NEW_LINE> params_dict['password'] = self.password <NEW_LINE> params = urllib.urlencode(params_dict) <NEW_LINE> self._log_message("Parameters: %s" % params) <NEW_LINE> request = urllib2.Request(self.api_url, params) <NEW_LINE> response = urllib2.urlopen(request) <NEW_LINE> assert response.info()['Content-Type'] == 'application/json; charset=utf-8', 'Invalid server response - Wrong HTTP Content-Type header!' <NEW_LINE> return response.read()
An instance of this class is used to perform API commands. An instance of this class has to be created to make TextMagic SMS API calls. Once the instance is created, you can invoke the TextMagic API functionality by calling: - send - account - message_status - receive - delete_reply - check_number And you can interpret callback notifications by calling: - callbackMessage
62598fc47cff6e4e811b5ce7
class DatasetCompressionLevel(str, Enum): <NEW_LINE> <INDENT> optimal = "Optimal" <NEW_LINE> fastest = "Fastest"
All available compression levels.
62598fc476e4537e8c3ef867
class Case(object): <NEW_LINE> <INDENT> def __init__(self, N): <NEW_LINE> <INDENT> self.batch = Batch(N) <NEW_LINE> <DEDENT> def assess_likes(self, likes): <NEW_LINE> <INDENT> successes = 0 <NEW_LINE> for i in range(0, len(likes) - 1, 2): <NEW_LINE> <INDENT> X = likes[i] <NEW_LINE> Y = Case.recode_col(likes[i + 1]) <NEW_LINE> successes += self.batch.set_col(X, Y) <NEW_LINE> <DEDENT> return(successes > 0) <NEW_LINE> <DEDENT> def print_final_batch(self): <NEW_LINE> <INDENT> final_batch = list(map(lambda x: x - 1 if (x > 0) else 0, self.batch.get_batch())) <NEW_LINE> print(" ".join(map(str, final_batch))) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def recode_col(c): <NEW_LINE> <INDENT> return(c + 1)
Assesses customers within a case.
62598fc4ec188e330fdf8b56
class Note(object): <NEW_LINE> <INDENT> def __init__(self, path, line, column, message): <NEW_LINE> <INDENT> self.path = path <NEW_LINE> self.line = line <NEW_LINE> self.column = column <NEW_LINE> self.message = message <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.path == other.path and self.line == other.line and self.column == other.column and self.message == other.message <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'path=%s, line=%d, column=%s, message=%s' % (self.path, self.line, self.column, self.message)
Represents a note and also this is the base class of Message.
62598fc44527f215b58ea192
class DummyOAuthProvider(auth.OAuthProvider): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> super(DummyOAuthProvider, self).__init__(name) <NEW_LINE> self.access_token = None <NEW_LINE> <DEDENT> def getTitle(self): <NEW_LINE> <INDENT> return self.name.capitalize() + " account" <NEW_LINE> <DEDENT> def getAccountIdDescription(self): <NEW_LINE> <INDENT> return self.name.capitalize() + " username" <NEW_LINE> <DEDENT> def getAccountURL(self, name): <NEW_LINE> <INDENT> return "https://example.com/user/%s" % name <NEW_LINE> <DEDENT> def getAuthorizeURL(self, state): <NEW_LINE> <INDENT> query = urllib.urlencode({ "state": state }) <NEW_LINE> return "https://example.com/authorize?%s" % query <NEW_LINE> <DEDENT> def getAccessToken(self, code): <NEW_LINE> <INDENT> if code == "incorrect": <NEW_LINE> <INDENT> raise auth.Failure("Incorrect code") <NEW_LINE> <DEDENT> self.access_token = hashlib.sha1(code).hexdigest() <NEW_LINE> return self.access_token <NEW_LINE> <DEDENT> def getUserData(self, access_token): <NEW_LINE> <INDENT> if access_token != self.access_token: <NEW_LINE> <INDENT> raise auth.Failure("Invalid access token") <NEW_LINE> <DEDENT> return { "account": "account-" + self.name, "username": self.name, "email": self.name + "@example.org", "fullname": self.name.capitalize() + " von Testing" }
Dummy OAuth authentication provider used by automatic tests
62598fc4d8ef3951e32c7fbd
class Project: <NEW_LINE> <INDENT> @lazy <NEW_LINE> def settings(self): <NEW_LINE> <INDENT> mod = importlib.import_module(NINA_CONF_MODULE) <NEW_LINE> conf = NinaConf(self, **extra_config(self)) <NEW_LINE> mod.__dict__.update(conf.get_settings()) <NEW_LINE> return mod <NEW_LINE> <DEDENT> @property <NEW_LINE> def urls(self): <NEW_LINE> <INDENT> urls = [] <NEW_LINE> for app, path_ in self.apps: <NEW_LINE> <INDENT> if path_ is None: <NEW_LINE> <INDENT> urls.extend(app.urls) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> urls.append(path(path_, include(apps.url))) <NEW_LINE> <DEDENT> <DEDENT> return urls <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> self.apps = [] <NEW_LINE> set_last_project(self) <NEW_LINE> <DEDENT> def init_project(self): <NEW_LINE> <INDENT> os.environ['DJANGO_SETTINGS_MODULE'] = NINA_CONF_MODULE <NEW_LINE> sys.modules[NINA_CONF_MODULE] = self.settings <NEW_LINE> self.init_urls_module() <NEW_LINE> <DEDENT> def init_urls_module(self): <NEW_LINE> <INDENT> mod = importlib.import_module(NINA_URLS) <NEW_LINE> mod.urlpatterns[:] = self.urls <NEW_LINE> return mod <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.run_command('runserver') <NEW_LINE> <DEDENT> def run_command(self, command, *args, **kwargs): <NEW_LINE> <INDENT> self.init_project() <NEW_LINE> argv = ['nina cmd', command, *map(str, args), *to_argv(**kwargs)] <NEW_LINE> utility = ManagementUtility(argv) <NEW_LINE> utility.execute() <NEW_LINE> <DEDENT> def mount(self, app, path=None): <NEW_LINE> <INDENT> self.apps.append(MountedApp(app, path))
Instances represent Django projects.
62598fc4ff9c53063f51a910
class CourseUpdate(models.Model): <NEW_LINE> <INDENT> course = models.ForeignKey(Course) <NEW_LINE> title = models.CharField(max_length=255, default="No Title Provided") <NEW_LINE> content = models.TextField(max_length=2000, default="*No Content Provided*") <NEW_LINE> date_post = models.DateTimeField(editable=True) <NEW_LINE> date_edit = models.DateTimeField(editable=True) <NEW_LINE> creator = models.ForeignKey(User) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = "Course Update" <NEW_LINE> verbose_name_plural = verbose_name + "s" <NEW_LINE> ordering = ("-date_post", "-date_edit", "title") <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '{0} - {1}'.format(self.creator.username, self.title) <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if self.date_post is None: <NEW_LINE> <INDENT> self.date_post = datetime.datetime.now() <NEW_LINE> self.date_edit = self.date_post <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.date_edit = datetime.datetime.now() <NEW_LINE> <DEDENT> super(CourseUpdate, self).save(*args, **kwargs)
CourseUpdate objects are announcement postings for a course Attributes: course: ForeignKey to course title: Title of post content: Content of post date_post: Date published, can be future date (only shows past dates) date_edit: Date last edited creator: ForeignKey to user who wrote post
62598fc4099cdd3c63675543
class InvalidInput(FuxiException): <NEW_LINE> <INDENT> pass
Request data is invalidate
62598fc49f288636728189dd
class BrowserCodingItem(BrowserItem): <NEW_LINE> <INDENT> def __init__(self, parent, text): <NEW_LINE> <INDENT> BrowserItem.__init__(self, parent, text) <NEW_LINE> self.type_ = BrowserItemCoding <NEW_LINE> self.icon = UI.PixmapCache.getIcon("textencoding.png") <NEW_LINE> <DEDENT> def lessThan(self, other, column, order): <NEW_LINE> <INDENT> if issubclass(other.__class__, BrowserClassItem) or issubclass(other.__class__, BrowserClassAttributesItem): <NEW_LINE> <INDENT> return order == Qt.AscendingOrder <NEW_LINE> <DEDENT> return BrowserItem.lessThan(self, other, column, order)
Class implementing the data structure for browser coding items.
62598fc4a05bb46b3848ab2f
class ColorLoggerMixin(object): <NEW_LINE> <INDENT> CODE_COLOR_MAPPING = { '1': ('yellow',), '2': ('green',), '3': ('cyan',), '4': ('magenta',), '5': ('red',), } <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self._supports_color = supports_color() <NEW_LINE> super(ColorLoggerMixin, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def colorize_msg(self, code, msg): <NEW_LINE> <INDENT> if self._supports_color: <NEW_LINE> <INDENT> return colored( msg, *self.CODE_COLOR_MAPPING.setdefault(code[0], ()) ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return msg <NEW_LINE> <DEDENT> <DEDENT> def colorize_atoms(self, atoms): <NEW_LINE> <INDENT> return atoms
Mixin class that does common initialization and color handling.
62598fc47c178a314d78d762
class SnapshotDomain(): <NEW_LINE> <INDENT> def __init__(self, template, basename, i): <NEW_LINE> <INDENT> self.template = template <NEW_LINE> self.basename = basename <NEW_LINE> self.i = i <NEW_LINE> self.xml = None <NEW_LINE> self.agentname = "" <NEW_LINE> self.agentsnapshotid = 0 <NEW_LINE> <DEDENT> def getName(self): <NEW_LINE> <INDENT> if self.xml == None: <NEW_LINE> <INDENT> self.getXML() <NEW_LINE> <DEDENT> xmlet = ElementTree.fromstring(self.xml) <NEW_LINE> name = xmlet.find('.//name') <NEW_LINE> return name.text <NEW_LINE> <DEDENT> def _getSourceDev(self): <NEW_LINE> <INDENT> agents = getAgents() <NEW_LINE> for agent in agents: <NEW_LINE> <INDENT> response = agent.ping() <NEW_LINE> if not response: <NEW_LINE> <INDENT> agents.remove(agent) <NEW_LINE> <DEDENT> if response == "nolibvirt": <NEW_LINE> <INDENT> agents.remove(agent) <NEW_LINE> <DEDENT> <DEDENT> agent = agents[0] <NEW_LINE> address = None <NEW_LINE> for pool in agent.getPools(): <NEW_LINE> <INDENT> if pool.getType() == 'dynamic-snapshot': <NEW_LINE> <INDENT> splitted = pool.getName().split(':') <NEW_LINE> if len(splitted) == 2: <NEW_LINE> <INDENT> splitted = splitted[1].split("snapshots_") <NEW_LINE> if len(splitted) == 2: <NEW_LINE> <INDENT> if splitted[1] == self.basename: <NEW_LINE> <INDENT> address = pool.getIscsiAddress() <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> if address == None: <NEW_LINE> <INDENT> raise Exception("Nie znaleziono woluminu bazowego") <NEW_LINE> <DEDENT> address = address + '-lun-' + str(self.i) <NEW_LINE> return address <NEW_LINE> <DEDENT> def getXML(self): <NEW_LINE> <INDENT> if not os.path.exists('../etc/templates/' + self.template): <NEW_LINE> <INDENT> if os.path.exists('../etc/templates/' + self.template + '.xml'): <NEW_LINE> <INDENT> self.template += '.xml' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(Colors.setred(" * ") + u"Nie ma takiego szablonu") <NEW_LINE> sys.exit(0) <NEW_LINE> <DEDENT> <DEDENT> f = open('../etc/templates/' + self.template) <NEW_LINE> xmldef = f.read() <NEW_LINE> xmldef = str(xmldef) <NEW_LINE> xmldef = xmldef.replace('$LUN', str(self.i)) <NEW_LINE> xmldef = xmldef.replace('$HEXLUN', str(hex(int(self.i)))[2:]) <NEW_LINE> xmldef = xmldef.replace('$BASELV', self.basename) <NEW_LINE> xmldef = xmldef.replace('$SOURCEDEV', self._getSourceDev()) <NEW_LINE> xmldef = xmldef.replace('$AGENTSEQUENCE', str(self.agentsnapshotid)) <NEW_LINE> xmldef = xmldef.replace('$HEXAGENTSEQUENCE', str(hex(int(self.agentsnapshotid)))[2:]) <NEW_LINE> self.xml = xmldef <NEW_LINE> return xmldef
Tworzenie definicji domeny
62598fc44a966d76dd5ef198
class Mem(IntervalModule): <NEW_LINE> <INDENT> format = "{avail_mem} MiB" <NEW_LINE> divisor = 1024**2 <NEW_LINE> color = "#00FF00" <NEW_LINE> warn_color = "#FFFF00" <NEW_LINE> alert_color = "#FF0000" <NEW_LINE> warn_percentage = 50 <NEW_LINE> alert_percentage = 80 <NEW_LINE> round_size = 1 <NEW_LINE> settings = ( ("format", "format string used for output."), ("divisor", "divide all byte values by this value, default is 1024**2 (megabytes)" ), ("warn_percentage", "minimal percentage for warn state"), ("alert_percentage", "minimal percentage for alert state"), ("color", "standard color"), ("warn_color", "defines the color used when warn percentage is exceeded"), ("alert_color", "defines the color used when alert percentage is exceeded"), ("round_size", "defines number of digits in round"), ) <NEW_LINE> def run(self): <NEW_LINE> <INDENT> memory_usage = virtual_memory() <NEW_LINE> used = memory_usage.used - memory_usage.cached - memory_usage.buffers <NEW_LINE> if memory_usage.percent >= self.alert_percentage: <NEW_LINE> <INDENT> color = self.alert_color <NEW_LINE> <DEDENT> elif memory_usage.percent >= self.warn_percentage: <NEW_LINE> <INDENT> color = self.warn_color <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> color = self.color <NEW_LINE> <DEDENT> cdict = { "used_mem": used / self.divisor, "avail_mem": memory_usage.available / self.divisor, "total_mem": memory_usage.total / self.divisor, "percent_used_mem": memory_usage.percent, } <NEW_LINE> round_dict(cdict, self.round_size) <NEW_LINE> self.data = cdict <NEW_LINE> self.output = { "full_text": self.format.format(**cdict), "color": color }
Shows memory load .. rubric:: Available formatters * {avail_mem} * {percent_used_mem} * {used_mem} * {total_mem} Requires psutil (from PyPI)
62598fc4283ffb24f3cf3b48
class LinuxDistro: <NEW_LINE> <INDENT> def __init__(self, name, version, release, arch): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.version = version <NEW_LINE> self.release = release <NEW_LINE> self.arch = arch <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<LinuxDistro: name=%s, version=%s, release=%s, arch=%s>' % ( self.name, self.version, self.release, self.arch)
Simple collection of information for a Linux Distribution
62598fc47cff6e4e811b5ce9
class StaticHandler(webapp2.RequestHandler): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> orgs = [org for org in models.Organization.all()] <NEW_LINE> random.shuffle(orgs) <NEW_LINE> webapputils.render_page(self, self.request.path, {'orgs': orgs})
Handles GET requests for static pages.
62598fc4aad79263cf42ea99
class ChooseOneStepOf(FeatureUnion): <NEW_LINE> <INDENT> def __init__(self, steps, hyperparams=None): <NEW_LINE> <INDENT> FeatureUnion.__init__(self, steps, joiner=SelectNonEmptyDataInputs()) <NEW_LINE> self._make_all_steps_optional() <NEW_LINE> if hyperparams is None: <NEW_LINE> <INDENT> self.set_hyperparams(HyperparameterSamples({ CHOICE_HYPERPARAM: list(self.keys())[0] })) <NEW_LINE> <DEDENT> <DEDENT> def set_hyperparams(self, hyperparams: Union[HyperparameterSamples, dict]): <NEW_LINE> <INDENT> super().set_hyperparams(hyperparams) <NEW_LINE> step_names = list(self.keys()) <NEW_LINE> chosen_step_name = self.hyperparams[CHOICE_HYPERPARAM] <NEW_LINE> if chosen_step_name not in step_names: <NEW_LINE> <INDENT> raise ValueError('Invalid Chosen Step in {0}'.format(self.name)) <NEW_LINE> <DEDENT> for step_name in step_names: <NEW_LINE> <INDENT> if step_name == chosen_step_name: <NEW_LINE> <INDENT> self[chosen_step_name].set_hyperparams({ OPTIONAL_ENABLED_HYPERPARAM: True }) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self[step_name].set_hyperparams({ OPTIONAL_ENABLED_HYPERPARAM: False }) <NEW_LINE> <DEDENT> <DEDENT> return self <NEW_LINE> <DEDENT> def _make_all_steps_optional(self): <NEW_LINE> <INDENT> step_names = list(self.keys()) <NEW_LINE> for step_name in step_names[:-1]: <NEW_LINE> <INDENT> self[step_name] = Optional(self[step_name]) <NEW_LINE> <DEDENT> self._refresh_steps()
A pipeline to allow choosing one step using an hyperparameter. Example usage : .. code-block:: python p = Pipeline([ ChooseOneStepOf([ ('a', Identity()), ('b', Identity()) ]) ]) p.set_hyperparams({ 'ChooseOneOrManyStepsOf__choice': 'a', }) # or p.set_hyperparams({ 'ChooseOneStepOf': { 'a': { 'enabled': True }, 'b': { 'enabled': False } } }) .. seealso:: :class:`Pipeline` :class:`Optional`
62598fc44527f215b58ea194
class TestDestinyDefinitionsDestinyLocationReleaseDefinition(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testDestinyDefinitionsDestinyLocationReleaseDefinition(self): <NEW_LINE> <INDENT> pass
DestinyDefinitionsDestinyLocationReleaseDefinition unit test stubs
62598fc492d797404e388cc4
class AbuseProcessor(DataProcessor): <NEW_LINE> <INDENT> def get_example_from_tensor_dict(self, tensor_dict): <NEW_LINE> <INDENT> return InputExample( tensor_dict["idx"].numpy(), tensor_dict["comment_text"].numpy().decode("utf-8"), None, str(tensor_dict["label"].numpy()), ) <NEW_LINE> <DEDENT> def get_train_examples(self, data_dir): <NEW_LINE> <INDENT> df = pd.read_csv(os.path.join(data_dir, "cleaned_train.csv")) <NEW_LINE> df = df.drop(['threat','insult','toxic','id'], axis=1) <NEW_LINE> return (self._create_examples(df, 'train')) <NEW_LINE> <DEDENT> def get_dev_examples(self, data_dir): <NEW_LINE> <INDENT> df = pd.read_csv(os.path.join(data_dir, "cleaned_val.csv")) <NEW_LINE> df = df.drop(['threat','insult','toxic','id'], axis=1) <NEW_LINE> return (self._create_examples(df, 'dev')) <NEW_LINE> <DEDENT> def get_labels(self): <NEW_LINE> <INDENT> return [0, 1] <NEW_LINE> <DEDENT> def _create_examples(self, lines, set_type): <NEW_LINE> <INDENT> examples = [] <NEW_LINE> for i in range(len(lines)): <NEW_LINE> <INDENT> if type(lines.iloc[i]['comment_text']) != str: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> guid = "%s-%s" % (set_type, i) <NEW_LINE> text_a = lines.iloc[i]['comment_text'] <NEW_LINE> label = lines.iloc[i]['IsAbuse'] <NEW_LINE> examples.append(InputExample(guid = guid, text_a = text_a, text_b = None, label = label)) <NEW_LINE> <DEDENT> return examples
Processor for the OnlineAbuse data set.
62598fc4adb09d7d5dc0a840
class TestFeaturedCollectionCoverItem(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testFeaturedCollectionCoverItem(self): <NEW_LINE> <INDENT> pass
FeaturedCollectionCoverItem unit test stubs
62598fc4a219f33f346c6acc
class log2(Function): <NEW_LINE> <INDENT> nargs = 1 <NEW_LINE> def fdiff(self, argindex=1): <NEW_LINE> <INDENT> if argindex == 1: <NEW_LINE> <INDENT> return S.One/(log(_Two)*self.args[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ArgumentIndexError(self, argindex) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def eval(cls, arg): <NEW_LINE> <INDENT> if arg.is_number: <NEW_LINE> <INDENT> result = log.eval(arg, base=_Two) <NEW_LINE> if result.is_Atom: <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> <DEDENT> elif arg.is_Pow and arg.base == _Two: <NEW_LINE> <INDENT> return arg.exp <NEW_LINE> <DEDENT> <DEDENT> def _eval_evalf(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.rewrite(log).evalf(*args, **kwargs) <NEW_LINE> <DEDENT> def _eval_expand_func(self, **hints): <NEW_LINE> <INDENT> return _log2(*self.args) <NEW_LINE> <DEDENT> def _eval_rewrite_as_log(self, arg, **kwargs): <NEW_LINE> <INDENT> return _log2(arg) <NEW_LINE> <DEDENT> _eval_rewrite_as_tractable = _eval_rewrite_as_log
Represents the logarithm function with base two. Explanation =========== The benefit of using ``log2(x)`` over ``log(x)/log(2)`` is that the latter is not as efficient under finite precision arithmetic. Examples ======== >>> from sympy.abc import x >>> from sympy.codegen.cfunctions import log2 >>> log2(4).evalf() == 2 True >>> log2(x).diff(x) 1/(x*log(2)) See Also ======== exp2 log10
62598fc4283ffb24f3cf3b49
class ShoppingList(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def OrderGroceries(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): <NEW_LINE> <INDENT> return grpc.experimental.unary_unary(request, target, '/shopping.ShoppingList/OrderGroceries', simple__example__pb2.MessageRequest.SerializeToString, simple__example__pb2.MessageReply.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
Service Definition
62598fc4f548e778e596b863
class NamesTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def test_first_last_name(self): <NEW_LINE> <INDENT> formmated_name = get_fomatted_name("jack","jones"); <NEW_LINE> self.assertEqual(formmated_name, 'Jack Jones')
测试name_function_py
62598fc4099cdd3c63675544
class CollectionFilesExportPlugin(plugin.ExportPlugin): <NEW_LINE> <INDENT> name = "collection_files" <NEW_LINE> description = "Downloads files referenced from the RDFValueCollection." <NEW_LINE> def ConfigureArgParser(self, parser): <NEW_LINE> <INDENT> parser.add_argument("--path", required=True, help="Path to the RDFValueCollection. Files referenced " "in this collection will be downloaded.") <NEW_LINE> parser.add_argument("--output", required=True, help="Directory downloaded files will be written to.") <NEW_LINE> parser.add_argument("--dump_client_info", action="store_true", default=False, help="Detect client paths and dump a yaml version of " "the client object to the root path. This is useful " "for seeing the hostname/users of the " "machine the client id refers to.") <NEW_LINE> parser.add_argument("--overwrite", action="store_true", default=False, help="Overwrite files if they exist.") <NEW_LINE> parser.add_argument("--threads", type=int, default=8, help="Maximum number of threads to use.") <NEW_LINE> <DEDENT> def Run(self, args): <NEW_LINE> <INDENT> export_utils.DownloadCollection(args.path, args.output, overwrite=args.overwrite, dump_client_info=args.dump_client_info, max_threads=args.threads)
ExportPlugin that downloads files and directories.
62598fc47c178a314d78d764
class TransparentDataEncryptionState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): <NEW_LINE> <INDENT> ENABLED = "Enabled" <NEW_LINE> DISABLED = "Disabled"
Specifies the state of the transparent data encryption.
62598fc4ad47b63b2c5a7b1d
class LinkedImageSystemChildPlugin(li.LinkedImageChildPlugin): <NEW_LINE> <INDENT> def __init__(self, lic): <NEW_LINE> <INDENT> li.LinkedImageChildPlugin.__init__(self, lic) <NEW_LINE> self.__linked = lic.child_pimage.linked <NEW_LINE> <DEDENT> def munge_props(self, props): <NEW_LINE> <INDENT> pass
See parent class for docstring.
62598fc43617ad0b5ee0640c
class SpecBasedBiblioEntry(BiblioEntry): <NEW_LINE> <INDENT> def __init__(self, spec, preferredURL=None): <NEW_LINE> <INDENT> super(SpecBasedBiblioEntry, self).__init__() <NEW_LINE> if preferredURL is None: <NEW_LINE> <INDENT> preferredURL = constants.refStatus.snapshot <NEW_LINE> <DEDENT> self.spec = spec <NEW_LINE> self.linkText = spec['vshortname'] <NEW_LINE> self._valid = True <NEW_LINE> preferredURL = constants.refStatus[preferredURL] <NEW_LINE> if preferredURL == constants.refStatus.snapshot: <NEW_LINE> <INDENT> self.url = spec['snapshot_url'] or spec['current_url'] <NEW_LINE> <DEDENT> elif preferredURL == constants.refStatus.current: <NEW_LINE> <INDENT> self.url = spec['current_url'] or spec['snapshot_url'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> if not self.url: <NEW_LINE> <INDENT> self._valid = False <NEW_LINE> <DEDENT> assert self.url <NEW_LINE> <DEDENT> def valid(self): <NEW_LINE> <INDENT> return self._valid <NEW_LINE> <DEDENT> def toHTML(self): <NEW_LINE> <INDENT> return [ self.spec['description'], " URL: ", E.a({"href":self.url}, self.url) ]
Generates a "fake" biblio entry from a spec reference, for when we don't have "real" bibliography data for a reference.
62598fc47cff6e4e811b5ceb
class ChildFlow(flow.GRRFlow): <NEW_LINE> <INDENT> @flow.StateHandler(next_state="ReceiveHello") <NEW_LINE> def Start(self): <NEW_LINE> <INDENT> self.CallClient("ReturnHello", next_state="ReceiveHello") <NEW_LINE> <DEDENT> @flow.StateHandler() <NEW_LINE> def ReceiveHello(self, responses): <NEW_LINE> <INDENT> for response in responses: <NEW_LINE> <INDENT> self.SendReply(rdfvalue.RDFString("Child received")) <NEW_LINE> self.SendReply(response)
This flow will be called by our parent.
62598fc4bf627c535bcb176d
class Message(object): <NEW_LINE> <INDENT> def __init__(self,subject,to,cc=None,bcc=None,text=None,html=None, attachments=None, sender=None, reply_to=None): <NEW_LINE> <INDENT> if not html and not attachments: <NEW_LINE> <INDENT> self.root = MIMEText(text,'plain',self._charset(text)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.root = MIMEMultipart() <NEW_LINE> if html: <NEW_LINE> <INDENT> alt = MIMEMultipart('alternative') <NEW_LINE> alt.attach(MIMEText(text,'plain',self._charset(text))) <NEW_LINE> alt.attach(MIMEText(html,'html',self._charset(html))) <NEW_LINE> self.root.attach(alt) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> txt = MIMEText(text,'plain',self._charset(text)) <NEW_LINE> self.root.attach(txt) <NEW_LINE> <DEDENT> for a in attachments or []: <NEW_LINE> <INDENT> self.root.attach(self._attachment(a)) <NEW_LINE> <DEDENT> <DEDENT> self.root['To'] = to <NEW_LINE> if cc: self.root['Cc'] = cc <NEW_LINE> if bcc: self.root['Bcc'] = bcc <NEW_LINE> if sender: <NEW_LINE> <INDENT> self.root['From'] = sender <NEW_LINE> if not reply_to: <NEW_LINE> <INDENT> self.root['Reply-To'] = sender <NEW_LINE> <DEDENT> <DEDENT> if reply_to: <NEW_LINE> <INDENT> self.root['Reply-To'] = reply_to <NEW_LINE> <DEDENT> self.root['Subject'] = subject <NEW_LINE> <DEDENT> def _charset(self,s): <NEW_LINE> <INDENT> return 'utf-8' if isinstance(s,unicode_type) else 'us-ascii' <NEW_LINE> <DEDENT> def _attachment(self,a): <NEW_LINE> <INDENT> if isinstance(a,MIMEBase): <NEW_LINE> <INDENT> return a <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> main,sub = (guess_type(a)[0] or 'application/octet-stream').split('/',1) <NEW_LINE> attachment = MIMEBase(main,sub) <NEW_LINE> with open(a,'rb') as f: <NEW_LINE> <INDENT> attachment.set_payload(f.read()) <NEW_LINE> <DEDENT> if sys.version_info[0] == 2: <NEW_LINE> <INDENT> attachment.add_header('Content-Disposition','attachment', filename=unicode(os.path.basename(a),sys.getfilesystemencoding())) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> attachment.add_header('Content-Disposition','attachment', filename=os.path.basename(a)) <NEW_LINE> <DEDENT> encode_base64(attachment) <NEW_LINE> return attachment <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self,key): <NEW_LINE> <INDENT> return self.root.__getitem__(key) <NEW_LINE> <DEDENT> def __setitem__(self,key,value): <NEW_LINE> <INDENT> self.root.__setitem__(key,value) <NEW_LINE> <DEDENT> def __delitem__(self,key): <NEW_LINE> <INDENT> return self.root.__delitem__(key) <NEW_LINE> <DEDENT> def __getattr__(self,attr): <NEW_LINE> <INDENT> if attr != 'root': <NEW_LINE> <INDENT> return getattr(self.root,attr)
Wrapper around email.Message class simplifying creation of simple email message objects. Allows most basic email messages types (including text, html & attachments) to be created simply from constructor. More complex messages should be created using the email.mime classes directly Class wraps the email.Message class and delegates item/attr lookups to the wrapped class (allows the object to be treated as a MIMEBase instance even though it doesnt inherit from this) Basic usage: >>> msg = Message('Test Message',to='xyz@xyz.com',text="Hello",html="<b>Hello</b>",attachments=['img.jpg'])
62598fc4283ffb24f3cf3b4b
class Var: <NEW_LINE> <INDENT> def __init__(self, x, y, color, radius): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = y <NEW_LINE> self.color = color <NEW_LINE> self.radius = radius
Keeping constant(same)/ variables for each class in superclass(here)
62598fc4ff9c53063f51a914
class RSparsematrixstats(RPackage): <NEW_LINE> <INDENT> homepage = "https://bioconductor.org/packages/sparseMatrixStats/" <NEW_LINE> git = "https://git.bioconductor.org/packages/sparseMatrixStats" <NEW_LINE> version('1.2.1', commit='9726f3d5e0f03b50c332d85d5e4c339c18b0494c') <NEW_LINE> depends_on('r-matrixgenerics', type=('build', 'run')) <NEW_LINE> depends_on('r-rcpp', type=('build', 'run')) <NEW_LINE> depends_on('r-matrix', type=('build', 'run')) <NEW_LINE> depends_on('r-matrixstats', type=('build', 'run'))
Summary Statistics for Rows and Columns of Sparse Matrices High performance functions for row and column operations on sparse matrices. For example: col / rowMeans2, col / rowMedians, col / rowVars etc. Currently, the optimizations are limited to data in the column sparse format. This package is inspired by the matrixStats package by Henrik Bengtsson.
62598fc47c178a314d78d766
class GETMethodProcessor(MethodProcessor): <NEW_LINE> <INDENT> not_accept_headers = ['Transfer-Encoding'] <NEW_LINE> @staticmethod <NEW_LINE> def make_response(response, provider): <NEW_LINE> <INDENT> headers = [(name, val) for name, val in response.headers.items() if name not in GETMethodProcessor.not_accept_headers] <NEW_LINE> return response.code, response.body, headers <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def make_request(request, provider): <NEW_LINE> <INDENT> from tornado.httputil import url_concat <NEW_LINE> from urllib.parse import parse_qs <NEW_LINE> request_url = '%s://%s%s' % (provider.protocol, provider.host, request.path) <NEW_LINE> get_params = dict((k, v if len(v) > 1 else v[0]) for k, v in parse_qs(request.query).items()) <NEW_LINE> get_params.update(provider.params['keyParams']) <NEW_LINE> request_url = url_concat(request_url, get_params) <NEW_LINE> request_headers = request.headers <NEW_LINE> request_headers['Host'] = provider.host <NEW_LINE> return request_url, request_headers
Класс для обработки GET запросов и ответов к внешнему API
62598fc466673b3332c3069c
class SearchSignal(Base): <NEW_LINE> <INDENT> name = Column(String(40)) <NEW_LINE> value = Column(Integer) <NEW_LINE> contact_id = Column(ForeignKey('contact.id', ondelete='CASCADE'), nullable=False)
Represents a signal used for contacts search result ranking. Examples of signals might include number of emails sent to or received from this contact, or time since last interaction with the contact.
62598fc43346ee7daa3377ac
class IntegerVar(ScriptVariable): <NEW_LINE> <INDENT> form_field = forms.IntegerField <NEW_LINE> def __init__(self, min_value=None, max_value=None, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> if min_value: <NEW_LINE> <INDENT> self.field_attrs['min_value'] = min_value <NEW_LINE> <DEDENT> if max_value: <NEW_LINE> <INDENT> self.field_attrs['max_value'] = max_value
Integer representation. Can enforce minimum/maximum values.
62598fc4167d2b6e312b723e
class DatabaseRouter: <NEW_LINE> <INDENT> def db_for_read(self, model: Model, **hints: Any) -> str: <NEW_LINE> <INDENT> assert model._meta.app_label in APP_LABEL_TO_DATABASE <NEW_LINE> return APP_LABEL_TO_DATABASE[model._meta.app_label] <NEW_LINE> <DEDENT> def db_for_write(self, model: Model, **hints: Any) -> str: <NEW_LINE> <INDENT> assert model._meta.app_label in APP_LABEL_TO_DATABASE <NEW_LINE> return APP_LABEL_TO_DATABASE[model._meta.app_label] <NEW_LINE> <DEDENT> def allow_relation(self, obj1: Model, obj2: Model, **hints: Any) -> bool: <NEW_LINE> <INDENT> assert obj1._meta.app_label in APP_LABEL_TO_DATABASE <NEW_LINE> assert obj2._meta.app_label in APP_LABEL_TO_DATABASE <NEW_LINE> return obj1._meta.app_label == obj2._meta.app_label <NEW_LINE> <DEDENT> def allow_migrate(self, db: str, app_label: str, model_name: str = None, **hints: Any) -> bool: <NEW_LINE> <INDENT> assert app_label in APP_LABEL_TO_DATABASE <NEW_LINE> return db == APP_LABEL_TO_DATABASE[app_label]
A router to control all database operations on models in Concent.
62598fc4851cf427c66b857d
@content( 'proposal', icon='icon novaideo-icon icon-proposal', ) <NEW_LINE> @implementer(IProposal) <NEW_LINE> class Proposal(Commentable, VersionableEntity, SearchableEntity, DuplicableEntity, CorrelableEntity, PresentableEntity): <NEW_LINE> <INDENT> icon = 'icon novaideo-icon icon-proposal' <NEW_LINE> result_template = 'novaideo:views/templates/proposal_result.pt' <NEW_LINE> template = 'novaideo:views/templates/proposal_list_element.pt' <NEW_LINE> name = renamer() <NEW_LINE> author = SharedUniqueProperty('author') <NEW_LINE> working_group = SharedUniqueProperty('working_group', 'proposal') <NEW_LINE> tokens_opposition = CompositeMultipleProperty('tokens_opposition') <NEW_LINE> tokens_support = CompositeMultipleProperty('tokens_support') <NEW_LINE> amendments = CompositeMultipleProperty('amendments', 'proposal') <NEW_LINE> corrections = CompositeMultipleProperty('corrections', 'proposal') <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(Proposal, self).__init__(**kwargs) <NEW_LINE> self.set_data(kwargs) <NEW_LINE> self._support_history = PersistentList() <NEW_LINE> self._amendments_counter = 1 <NEW_LINE> <DEDENT> @property <NEW_LINE> def related_ideas(self): <NEW_LINE> <INDENT> lists_targets = [(c.targets, c) for c in self.source_correlations if ((c.type==CorrelationType.solid) and ('related_ideas' in c.tags))] <NEW_LINE> return MultiDict([(target, c) for targets, c in lists_targets for target in targets]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def tokens(self): <NEW_LINE> <INDENT> result = list(self.tokens_opposition) <NEW_LINE> result.extend(list(self.tokens_support)) <NEW_LINE> return result <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_published(self): <NEW_LINE> <INDENT> return 'draft' not in self.state
Proposal class
62598fc45fdd1c0f98e5e25b
class NaiveTimeField(_IsoFormatMixin, Field): <NEW_LINE> <INDENT> default_error_messages = { "invalid": "Not a valid time string.", } <NEW_LINE> data_type_name = "Naive ISO-8601 Time" <NEW_LINE> def __init__(self, ignore_timezone=False, **options): <NEW_LINE> <INDENT> super(NaiveTimeField, self).__init__(**options) <NEW_LINE> self.ignore_timezone = ignore_timezone <NEW_LINE> <DEDENT> def to_python(self, value): <NEW_LINE> <INDENT> if value in self.empty_values: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if isinstance(value, datetime.time): <NEW_LINE> <INDENT> if value.tzinfo and self.ignore_timezone: <NEW_LINE> <INDENT> return value.replace(tzinfo=None) <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> default_timezone = datetimeutil.IgnoreTimezone if self.ignore_timezone else None <NEW_LINE> try: <NEW_LINE> <INDENT> return datetimeutil.parse_iso_time_string(value, default_timezone) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> msg = self.error_messages["invalid"] <NEW_LINE> raise exceptions.ValidationError(msg) <NEW_LINE> <DEDENT> def prepare(self, value): <NEW_LINE> <INDENT> if (value is not None) and self.ignore_timezone and (value.tzinfo is not None): <NEW_LINE> <INDENT> value = value.replace(tzinfo=None) <NEW_LINE> <DEDENT> return value
Field that handles time values encoded as a string. The format of the string is that defined by ISO-8601. The naive time field differs from :py:`~TimeField` in the handling of the timezone, a timezone will not be applied if one is not specified. Use the ``ignore_timezone`` flag to have any timezone information ignored when decoding the time field.
62598fc44527f215b58ea198
class StaticQueueInfo(queue_info.QueueInfoBase): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.queues = { 'default': StaticTaskQueue(name='default', priority=75, default_priority=75), 'large': StaticTaskQueue(name='large', priority=75, default_priority=75), 'highp': StaticTaskQueue(name='highp', priority=100, default_priority=100), 'lowp': StaticTaskQueue(name='lowp', priority=1, default_priority=1), 'digest': StaticTaskQueue(name='digest', priority=70, default_priority=70)} <NEW_LINE> <DEDENT> def get_queues(self): <NEW_LINE> <INDENT> return list(self.queues.values()) <NEW_LINE> <DEDENT> def is_empty(self): <NEW_LINE> <INDENT> for (queue_name, queue) in six.iteritems(self.queues): <NEW_LINE> <INDENT> if not self.is_queue_empty(queue): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> def get_highest_priority_queue_that_needs_work(self): <NEW_LINE> <INDENT> non_empty_queues = [] <NEW_LINE> for (queue_name, queue) in six.iteritems(self.queues): <NEW_LINE> <INDENT> if not self.is_queue_empty(queue): <NEW_LINE> <INDENT> non_empty_queues.append(self.queues[queue_name]) <NEW_LINE> <DEDENT> <DEDENT> if len(non_empty_queues) == 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> non_empty_queues.sort(key=lambda x: x.priority, reverse=True) <NEW_LINE> return non_empty_queues[0] <NEW_LINE> <DEDENT> def is_queue_empty(self, queue): <NEW_LINE> <INDENT> the_queue = self.queues[queue.name] <NEW_LINE> if not the_queue.tasks.empty(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def does_queue_need_work(self, queue): <NEW_LINE> <INDENT> return not self.is_queue_empty(queue)
Hardcoded queue information.
62598fc4adb09d7d5dc0a844
class DummyMonitor(BaseMonitor): <NEW_LINE> <INDENT> running = Bool() <NEW_LINE> monitored_entries = set_default(['default_path']) <NEW_LINE> received_news = List() <NEW_LINE> def start(self): <NEW_LINE> <INDENT> self.running = True <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.running = False <NEW_LINE> <DEDENT> def refresh_monitored_entries(self, entries=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def handle_database_entries_change(self, news): <NEW_LINE> <INDENT> if news[0] == 'added': <NEW_LINE> <INDENT> self.monitored_entries = self.monitored_entries + [news[1]] <NEW_LINE> <DEDENT> <DEDENT> def handle_database_nodes_change(self, news): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def process_news(self, news): <NEW_LINE> <INDENT> self.received_news.append(news)
Dummy monitor used for testing.
62598fc492d797404e388cc6
class LocalStatusUpdater(threading.Thread): <NEW_LINE> <INDENT> def __init__(self, update_hook): <NEW_LINE> <INDENT> super(LocalStatusUpdater, self).__init__() <NEW_LINE> self.should_quit = False <NEW_LINE> self.should_update_now = False <NEW_LINE> self.update_hook = update_hook <NEW_LINE> self.local_suites = [] <NEW_LINE> self.queue = multiprocessing.Queue() <NEW_LINE> self.stop_event = multiprocessing.Event() <NEW_LINE> self.update_event = multiprocessing.Event() <NEW_LINE> self.getter = LocalStatusGetter(self.queue, self.update_event, self.stop_event) <NEW_LINE> self.start() <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.getter.start() <NEW_LINE> while not self.should_quit: <NEW_LINE> <INDENT> self.update() <NEW_LINE> time.sleep(0.5) <NEW_LINE> <DEDENT> self.stop_event.set() <NEW_LINE> <DEDENT> def update_now(self): <NEW_LINE> <INDENT> self.update_event.set() <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> local_suites = self.queue.get_nowait() <NEW_LINE> <DEDENT> except Queue.Empty: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.local_suites = local_suites <NEW_LINE> gobject.idle_add(self.update_hook, local_suites) <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.stop_event.set() <NEW_LINE> self.should_quit = True
Update the local suites status in the background.
62598fc4ff9c53063f51a916
class RadosRequest(UserRequest): <NEW_LINE> <INDENT> def __init__(self, headline, fsid, cluster_name, commands): <NEW_LINE> <INDENT> self._commands = commands <NEW_LINE> super(RadosRequest, self).__init__(headline, fsid, cluster_name) <NEW_LINE> <DEDENT> def _submit(self, commands=None): <NEW_LINE> <INDENT> if commands is None: <NEW_LINE> <INDENT> commands = self._commands <NEW_LINE> <DEDENT> self.log.debug("%s._submit: %s/%s/%s" % (self.__class__.__name__, self._minion_id, self._cluster_name, commands)) <NEW_LINE> client = LocalClient(config.get('cthulhu', 'salt_config_path')) <NEW_LINE> pub_data = client.run_job(self._minion_id, 'ceph.rados_commands', [self.fsid, self._cluster_name, commands]) <NEW_LINE> if not pub_data: <NEW_LINE> <INDENT> raise PublishError("Failed to publish job") <NEW_LINE> <DEDENT> self.log.info("Request %s started job %s" % (self.id, pub_data['jid'])) <NEW_LINE> self.alive_at = now() <NEW_LINE> self.jid = pub_data['jid'] <NEW_LINE> return self.jid
A user request whose remote operations consist of librados mon commands
62598fc4dc8b845886d53884
class Solution: <NEW_LINE> <INDENT> def threeSumClosest(self, numbers, target): <NEW_LINE> <INDENT> n = len(numbers) <NEW_LINE> if n < 3: return 0 <NEW_LINE> numbers.sort() <NEW_LINE> result = numbers[0] + numbers[1] + numbers[2] <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> j = i + 1 <NEW_LINE> k = n - 1 <NEW_LINE> while j < k: <NEW_LINE> <INDENT> sum = numbers[i] + numbers[j] + numbers[k] <NEW_LINE> if abs(sum - target) < abs(result - target): <NEW_LINE> <INDENT> result = sum <NEW_LINE> <DEDENT> if sum == target: <NEW_LINE> <INDENT> return sum <NEW_LINE> <DEDENT> elif sum < target: <NEW_LINE> <INDENT> j += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> k -= 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return result
@param numbers: Give an array numbers of n integer @param target : An integer @return : return the sum of the three integers, the sum closest target.
62598fc48a349b6b43686508
class Leaf(object): <NEW_LINE> <INDENT> position = None <NEW_LINE> direction = None <NEW_LINE> right = None <NEW_LINE> def __init__(self, pos, direction, right): <NEW_LINE> <INDENT> self.position = pos <NEW_LINE> self.direction = direction <NEW_LINE> self.right = right <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_shape(cls, leaf_type, g_scale, scale, scale_x): <NEW_LINE> <INDENT> u_v = [] <NEW_LINE> if leaf_type < 0: <NEW_LINE> <INDENT> if leaf_type < -3: <NEW_LINE> <INDENT> leaf_type = -1 <NEW_LINE> <DEDENT> shape = leaf_geom.blossom(abs(leaf_type + 1)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if leaf_type < 1 or leaf_type > 10: <NEW_LINE> <INDENT> leaf_type = 8 <NEW_LINE> <DEDENT> shape = leaf_geom.leaves(leaf_type - 1) <NEW_LINE> <DEDENT> verts = shape[0] <NEW_LINE> faces = shape[1] <NEW_LINE> if len(shape) == 3: <NEW_LINE> <INDENT> u_v = shape[2] <NEW_LINE> <DEDENT> for vert in verts: <NEW_LINE> <INDENT> vert *= scale * g_scale <NEW_LINE> vert.x *= scale_x <NEW_LINE> <DEDENT> return verts, faces, u_v <NEW_LINE> <DEDENT> def get_mesh(self, bend, base_shape, index): <NEW_LINE> <INDENT> trf = self.direction.to_track_quat('Z', 'Y') <NEW_LINE> right_t = self.right.rotated(trf.inverted()) <NEW_LINE> spin_ang = pi - right_t.angle(Vector([1, 0, 0])) <NEW_LINE> if bend > 0: <NEW_LINE> <INDENT> bend_trf_1, bend_trf_2 = self.calc_bend_trf(bend) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> bend_trf_1 = bend_trf_2 = None <NEW_LINE> <DEDENT> vertices = [] <NEW_LINE> for vertex in base_shape[0]: <NEW_LINE> <INDENT> vertex = vertex.copy() <NEW_LINE> vertex.rotate(Quaternion(Vector([0, 0, 1]), spin_ang)) <NEW_LINE> vertex.rotate(trf) <NEW_LINE> if bend > 0: <NEW_LINE> <INDENT> vertex.rotate(bend_trf_1) <NEW_LINE> vertex.rotate(bend_trf_2) <NEW_LINE> <DEDENT> vertex += self.position <NEW_LINE> vertices.append(vertex) <NEW_LINE> <DEDENT> index *= len(vertices) <NEW_LINE> faces = deepcopy(base_shape[1]) <NEW_LINE> for face in faces: <NEW_LINE> <INDENT> for ind, elem in enumerate(face): <NEW_LINE> <INDENT> face[ind] = elem + index <NEW_LINE> <DEDENT> <DEDENT> return vertices, faces <NEW_LINE> <DEDENT> def calc_bend_trf(self, bend): <NEW_LINE> <INDENT> normal = self.direction.cross(self.right) <NEW_LINE> theta_pos = atan2(self.position.y, self.position.x) <NEW_LINE> theta_bend = theta_pos - atan2(normal.y, normal.x) <NEW_LINE> bend_trf_1 = Quaternion(Vector([0, 0, 1]), theta_bend * bend) <NEW_LINE> self.direction.rotate(bend_trf_1) <NEW_LINE> self.right.rotate(bend_trf_1) <NEW_LINE> normal = self.direction.cross(self.right) <NEW_LINE> phi_bend = normal.declination() <NEW_LINE> if phi_bend > pi / 2: <NEW_LINE> <INDENT> phi_bend = phi_bend - pi <NEW_LINE> <DEDENT> bend_trf_2 = Quaternion(self.right, phi_bend * bend) <NEW_LINE> return bend_trf_1, bend_trf_2
Class to store data for each leaf in the system
62598fc44a966d76dd5ef19e
class BrillouinZone(object): <NEW_LINE> <INDENT> def __init__(self, reciprocal_lattice, tolerance=0.01): <NEW_LINE> <INDENT> self._reciprocal_lattice = np.array(reciprocal_lattice) <NEW_LINE> self._tolerance = min( np.sum(reciprocal_lattice ** 2, axis=0)) * tolerance <NEW_LINE> self._reduced_bases = get_reduced_bases(reciprocal_lattice.T) <NEW_LINE> self._tmat = np.dot(np.linalg.inv(self._reciprocal_lattice), self._reduced_bases.T) <NEW_LINE> self._tmat_inv = np.linalg.inv(self._tmat) <NEW_LINE> self.shortest_qpoints = None <NEW_LINE> <DEDENT> def run(self, qpoints): <NEW_LINE> <INDENT> reduced_qpoints = np.dot(qpoints, self._tmat_inv.T) <NEW_LINE> reduced_qpoints -= np.rint(reduced_qpoints) <NEW_LINE> self.shortest_qpoints = [] <NEW_LINE> for q in reduced_qpoints: <NEW_LINE> <INDENT> distances = (np.dot(q + search_space, self._reduced_bases) ** 2).sum(axis=1) <NEW_LINE> min_dist = min(distances) <NEW_LINE> shortest_indices = np.where( distances < min_dist + self._tolerance)[0] <NEW_LINE> self.shortest_qpoints.append( np.dot(search_space[shortest_indices] + q, self._tmat.T))
Move qpoints to first Brillouin zone by lattice translation. Attributes ---------- shortest_qpoints : list Each element of the list contains a set of q-points that are in first Brillouin zone (BZ). When inside BZ, there is only one q-point for each element, but on the surface, multiple q-points that are distinguished by non-zero lattice translation are stored.
62598fc45fc7496912d483df
class City(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=32) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name
Primary city where Superhero lives/works.
62598fc4adb09d7d5dc0a846
class Fork: <NEW_LINE> <INDENT> def __init__(self, timeout=0, verbose=False): <NEW_LINE> <INDENT> self.timeout = timeout <NEW_LINE> self.verbose = verbose <NEW_LINE> <DEDENT> def __call__(self, f): <NEW_LINE> <INDENT> P = Parallel(p_iter='fork', ncpus=1, timeout=self.timeout, verbose=self.verbose) <NEW_LINE> g = P(f) <NEW_LINE> def h(*args, **kwds): <NEW_LINE> <INDENT> return list(g([(args, kwds)]))[0][1] <NEW_LINE> <DEDENT> return h
A ``fork`` decorator class.
62598fc45fdd1c0f98e5e25e
class MutabilityRule: <NEW_LINE> <INDENT> def __init__( self, field_rule, values=(), exclude_fields=(), exclude_on_create=True, exclude_on_update=False, exclude_on_delete=False, error_message="", ): <NEW_LINE> <INDENT> self.field_rule = field_rule <NEW_LINE> self.values = values <NEW_LINE> self.exclude_fields = exclude_fields <NEW_LINE> self.exclude_on_create = exclude_on_create <NEW_LINE> self.exclude_on_update = exclude_on_update <NEW_LINE> self.exclude_on_delete = exclude_on_delete <NEW_LINE> self.error_message = error_message <NEW_LINE> <DEDENT> def is_mutable(self, model_instance, field_parts=None): <NEW_LINE> <INDENT> field_parts = field_parts or self.field_rule.split('__') <NEW_LINE> opts = model_instance._meta <NEW_LINE> for field_name in field_parts: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> rel = opts.get_field(field_name) <NEW_LINE> <DEDENT> except FieldDoesNotExist: <NEW_LINE> <INDENT> logger.warning(_(f"Field does not exist - {field_name}")) <NEW_LINE> return True <NEW_LINE> <DEDENT> if isinstance(rel, (RelatedField, ForeignObjectRel)): <NEW_LINE> <INDENT> rel_parts = field_parts[field_parts.index(field_name) + 1 :] <NEW_LINE> if isinstance(rel, ForeignObjectRel): <NEW_LINE> <INDENT> field_name = rel.get_accessor_name() <NEW_LINE> <DEDENT> field_val = getattr(model_instance, field_name) <NEW_LINE> return self._is_mutable_relation(rel, field_val, rel_parts) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> field_val = model_instance.saved_value(field_name) <NEW_LINE> return field_val in self.values <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _is_mutable_relation(self, relation, value, rel_parts): <NEW_LINE> <INDENT> if not rel_parts: <NEW_LINE> <INDENT> return value in self.values <NEW_LINE> <DEDENT> if not value: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if relation.many_to_many or relation.one_to_many: <NEW_LINE> <INDENT> for related_object in value.all(): <NEW_LINE> <INDENT> if not self.is_mutable(related_object, field_parts=rel_parts): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.is_mutable(value, field_parts=rel_parts)
This class serves to define the rule when an model is mutable. To define mutability rule it is mandatory to define "field_rule" of the model from which depend model mutability. To define relation field use '__' as separator in "field_rule" Once, "field_rule" is defined, model becomes immutable if the rule is not fulfilled (you can not update it or delete it). Parameters ---------- field_rule <String>: field mutability effects. values <set>: set of values to establish when the model will be mutable. exclude_fields <set>: set of fields names to exclude for this rule. exclude_on_create <Bool>: To exclude this rule on create set <True>, otherwise <False>. Default True exclude_on_update <Bool>: To exclude this rule on update set <True>, otherwise <False>. Default False exclude_on_delete <Bool>: To exclude this rule on delete set <True>, otherwise <False>. Default False error_message <String>: Message passed on raise. Examples: - Only invoice note can be changed if invoice is not in draft state. MutabilityRule('state', values=('draft',), exclude_fields=('note',)) - Entry can not be deleted (but can be updated) if related invoice is validated MutabilityRule('invoice__state', values=('draft',), exclude_on_update=True) - Invoice line cannot be updated or deleted nor new line can be added if invoice is not in draft or budget state MutabilityRule('invoice__state', values=('draft', 'budget'), exclude_on_create=False)
62598fc471ff763f4b5e7a48
class JoinUs(BrowserView): <NEW_LINE> <INDENT> index = ViewPageTemplateFile("template/join_us.pt") <NEW_LINE> def __call__(self): <NEW_LINE> <INDENT> return self.index()
Join Us
62598fc4377c676e912f6eda
class LocalSite(models.Model): <NEW_LINE> <INDENT> name = models.SlugField(_('name'), max_length=32, blank=False, unique=True) <NEW_LINE> users = models.ManyToManyField(User, blank=True, related_name='local_site') <NEW_LINE> admins = models.ManyToManyField(User, blank=True, related_name='local_site_admins') <NEW_LINE> def is_accessible_by(self, user): <NEW_LINE> <INDENT> return (user.is_authenticated() and self.users.filter(pk=user.pk).exists()) <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.name
A division within a Review Board installation. This allows the creation of independent, isolated divisions within a given server. Users can be designated as members of a LocalSite, and optionally as admins (which allows them to manipulate the repositories, groups and users in the site). Pretty much every other model in this module can all be assigned to a single LocalSite, at which point only members will be able to see or manipulate these objects. Access control is performed at every level, and consistency is enforced through a liberal sprinkling of assertions and unit tests.
62598fc43d592f4c4edbb17d
class EnsembleTransmissionParameters(object): <NEW_LINE> <INDENT> def __init__(self, decoders, transform): <NEW_LINE> <INDENT> self.untransformed_decoders = np.array(decoders) <NEW_LINE> self.transform = np.array(transform) <NEW_LINE> self.decoders = np.dot(transform, decoders.T) <NEW_LINE> self.untransformed_decoders.flags['WRITEABLE'] = False <NEW_LINE> self.transform.flags['WRITEABLE'] = False <NEW_LINE> self.decoders.flags['WRITEABLE'] = False <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if type(self) is not type(other): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.decoders.shape != other.decoders.shape: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if np.any(self.decoders != other.decoders): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True
Transmission parameters for a connection originating at an Ensemble. Attributes ---------- decoders : array Decoders to use for the connection.
62598fc43317a56b869be6b6
class TestPriceModificationValueChangeDecreaseAllOf(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def make_instance(self, include_optional): <NEW_LINE> <INDENT> if include_optional : <NEW_LINE> <INDENT> return PriceModificationValueChangeDecreaseAllOf( type = 'DECREASE_PRICE', value = null ) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return PriceModificationValueChangeDecreaseAllOf( ) <NEW_LINE> <DEDENT> <DEDENT> def testPriceModificationValueChangeDecreaseAllOf(self): <NEW_LINE> <INDENT> inst_req_only = self.make_instance(include_optional=False) <NEW_LINE> inst_req_and_optional = self.make_instance(include_optional=True)
PriceModificationValueChangeDecreaseAllOf unit test stubs
62598fc47047854f4633f69f
class RelationshipProcessComponent(StructuredRel): <NEW_LINE> <INDENT> weight = FloatProperty()
A class to represent the relationship between a Process and a Component. Attributes ---------- weight : float is the weight of the relationship
62598fc4851cf427c66b8581
class User(AbstractBaseUser, PermissionsMixin): <NEW_LINE> <INDENT> GENDER_CHOICE = ( ('M', '男'), ('F', '女'), ) <NEW_LINE> username = models.CharField(_('用户名'), unique=True, db_index=True, max_length=100, null=True) <NEW_LINE> password = models.CharField(_('密码'), max_length=128) <NEW_LINE> email = models.EmailField(_('邮箱'), unique=True) <NEW_LINE> telephone = models.CharField(_('用户手机号码'), max_length=11, null=True) <NEW_LINE> gender = models.CharField(_('性别'), max_length=1, choices=GENDER_CHOICE, null=True) <NEW_LINE> birthday = models.DateField(_('出生日期'), auto_now=False, null=True) <NEW_LINE> avatar = models.ImageField(upload_to='./user/avatar/%Y/%m/%d', null=True) <NEW_LINE> presentation = models.CharField(_('一句话介绍自己'), max_length=100, null=True) <NEW_LINE> is_staff = models.BooleanField(_('是否在Admin中可用'), default=False) <NEW_LINE> is_active = models.BooleanField(_('是否可用'), default=True) <NEW_LINE> USERNAME_FIELD = 'email' <NEW_LINE> REQUIRED_FIELDS = ("username", "password",) <NEW_LINE> objects = GGSUserManager() <NEW_LINE> def get_full_name(self): <NEW_LINE> <INDENT> return self.username <NEW_LINE> <DEDENT> def get_short_name(self): <NEW_LINE> <INDENT> return self.username <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.email <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> db_table = 'ggsuser'
自定义用户,需要在settings.py中指定这个User类为AUTH_USER_MODEL
62598fc45fdd1c0f98e5e25f
@attr.s <NEW_LINE> class Criterion(object): <NEW_LINE> <INDENT> name = attr.ib() <NEW_LINE> predicate = attr.ib() <NEW_LINE> def evaluate(self, attributes): <NEW_LINE> <INDENT> return (self.name in attributes and self.predicate(attributes[self.name]))
A criterion evaluates a predicate (callable object returning boolean) against an attribute with the given name.
62598fc450812a4eaa620d4b
class AssignMentorRoleForOrgTest(test_utils.DjangoTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.init() <NEW_LINE> self.program = program_utils.seedProgram() <NEW_LINE> self.org = org_utils.seedOrganization(self.program.key()) <NEW_LINE> self.profile = profile_utils.seedNDBProfile(self.program.key()) <NEW_LINE> <DEDENT> def testForUserWithNoRole(self): <NEW_LINE> <INDENT> profile_logic.assignMentorRoleForOrg(self.profile, self.org.key) <NEW_LINE> self.assertTrue(self.profile.is_mentor) <NEW_LINE> self.assertListEqual(self.profile.mentor_for, [self.org.key]) <NEW_LINE> self.assertFalse(self.profile.is_admin) <NEW_LINE> self.assertListEqual(self.profile.admin_for, []) <NEW_LINE> <DEDENT> def testForUserWithOrgAdminRole(self): <NEW_LINE> <INDENT> self.profile.mentor_for = [self.org.key] <NEW_LINE> self.profile.admin_for = [self.org.key] <NEW_LINE> self.profile.put() <NEW_LINE> profile_logic.assignMentorRoleForOrg(self.profile, self.org.key) <NEW_LINE> self.assertTrue(self.profile.is_mentor) <NEW_LINE> self.assertListEqual(self.profile.mentor_for, [self.org.key]) <NEW_LINE> self.assertFalse(self.profile.is_admin) <NEW_LINE> self.assertListEqual(self.profile.admin_for, []) <NEW_LINE> <DEDENT> def testForOrgAdminForAnotherOrg(self): <NEW_LINE> <INDENT> other_org = org_utils.seedOrganization(self.program.key()) <NEW_LINE> self.profile.mentor_for = [other_org.key] <NEW_LINE> self.profile.admin_for = [other_org.key] <NEW_LINE> self.profile.put() <NEW_LINE> profile_logic.assignMentorRoleForOrg(self.profile, self.org.key) <NEW_LINE> self.assertTrue(self.profile.is_mentor) <NEW_LINE> self.assertIn(self.org.key, self.profile.mentor_for) <NEW_LINE> self.assertIn(other_org.key, self.profile.mentor_for) <NEW_LINE> self.assertTrue(self.profile.is_admin) <NEW_LINE> self.assertListEqual(self.profile.admin_for, [other_org.key]) <NEW_LINE> <DEDENT> def testOrgMemberWelcomeEmailSent(self): <NEW_LINE> <INDENT> program_messages = program_utils.seedProgramMessages( program_key=self.program.key()) <NEW_LINE> site = program_utils.seedSite() <NEW_LINE> profile_logic.assignMentorRoleForOrg( self.profile, self.org.key, send_org_member_welcome_email=True, program=self.program, program_messages=program_messages, site=site) <NEW_LINE> self.assertIn( ndb_profile_model.MessageType.ORG_MEMBER_WELCOME_MSG, self.profile.sent_messages) <NEW_LINE> self.assertEmailSent(to=self.profile.contact.email)
Unit tests for assignMentorRoleForOrg function.
62598fc492d797404e388cc8
class GEventRegister(EventRegister): <NEW_LINE> <INDENT> def __init__(self, events=None): <NEW_LINE> <INDENT> if events is not None: <NEW_LINE> <INDENT> self.__events__ = events <NEW_LINE> <DEDENT> EventRegister.__init__(self) <NEW_LINE> <DEDENT> def __getattr__(self, event): <NEW_LINE> <INDENT> if event == '__events__': <NEW_LINE> <INDENT> raise AttributeError(event) <NEW_LINE> <DEDENT> return EventRegister.__getattr__(self, event.replace("_", "-"))
Event register for the :class:`GSignals` class. Automatically converts signal names with underscores('foo_bar') to names with hyphens ('foo-bar'). Same API as :class:`EventRegister`.
62598fc4f548e778e596b86b
@dataclass <NEW_LINE> class SynonymPredicateChange(NodeSynonymChange): <NEW_LINE> <INDENT> _inherited_slots: ClassVar[List[str]] = [] <NEW_LINE> class_class_uri: ClassVar[URIRef] = KGCL.SynonymPredicateChange <NEW_LINE> class_class_curie: ClassVar[str] = "kgcl:SynonymPredicateChange" <NEW_LINE> class_name: ClassVar[str] = "synonym predicate change" <NEW_LINE> class_model_uri: ClassVar[URIRef] = KGCL.SynonymPredicateChange <NEW_LINE> id: Union[str, SynonymPredicateChangeId] = None <NEW_LINE> old_value: Optional[str] = None <NEW_LINE> new_value: Optional[str] = None <NEW_LINE> has_textual_diff: Optional[Union[dict, "TextualDiff"]] = None <NEW_LINE> def __post_init__(self, *_: List[str], **kwargs: Dict[str, Any]): <NEW_LINE> <INDENT> if self._is_empty(self.id): <NEW_LINE> <INDENT> self.MissingRequiredField("id") <NEW_LINE> <DEDENT> if not isinstance(self.id, SynonymPredicateChangeId): <NEW_LINE> <INDENT> self.id = SynonymPredicateChangeId(self.id) <NEW_LINE> <DEDENT> if self.old_value is not None and not isinstance(self.old_value, str): <NEW_LINE> <INDENT> self.old_value = str(self.old_value) <NEW_LINE> <DEDENT> if self.new_value is not None and not isinstance(self.new_value, str): <NEW_LINE> <INDENT> self.new_value = str(self.new_value) <NEW_LINE> <DEDENT> if self.has_textual_diff is not None and not isinstance(self.has_textual_diff, TextualDiff): <NEW_LINE> <INDENT> self.has_textual_diff = TextualDiff() <NEW_LINE> <DEDENT> super().__post_init__(**kwargs)
A node synonym change where the predicate of a synonym is changed. Background: synonyms can be represented by a variety of predicates. For example, many OBO ontologies make use of predicates such as oio:hasExactSynonym, oio:hasRelatedSynonym, etc
62598fc4099cdd3c63675548
class ConnectionException(XBeeException): <NEW_LINE> <INDENT> pass
This exception will be thrown when any problem related to the connection with the XBee device occurs. All functionality of this class is the inherited of `Exception <https://docs.python.org/2/library/exceptions.html?highlight=exceptions.exception#exceptions.Exception>`_.
62598fc45166f23b2e2436ae
class NativeLibraryWrapper: <NEW_LINE> <INDENT> def __init__(self, base_folder, library_name, path_to_library=""): <NEW_LINE> <INDENT> if path_to_library == "": <NEW_LINE> <INDENT> os_ending = { "nt": "dll", "posix": "so" } <NEW_LINE> for os_name in os_ending: <NEW_LINE> <INDENT> if os.name == os_name: <NEW_LINE> <INDENT> for root, dirs, files in os.walk(base_folder): <NEW_LINE> <INDENT> for f in files: <NEW_LINE> <INDENT> if in_debug_mode(): <NEW_LINE> <INDENT> if library_name.lower() + "." + os_ending[os_name] in f.lower() and "Debug" in root: <NEW_LINE> <INDENT> path_to_library = os.path.join(root, f) <NEW_LINE> print("Found path " + path_to_library) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if library_name.lower() + "." + os_ending[os_name] in f.lower() and "Debug" not in root: <NEW_LINE> <INDENT> path_to_library = os.path.join(root, f) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> if path_to_library == "": <NEW_LINE> <INDENT> raise IOError("Did not find library.") <NEW_LINE> <DEDENT> self.library = ctypes.cdll.LoadLibrary(path_to_library) <NEW_LINE> self.functions = dict() <NEW_LINE> <DEDENT> def __getattr__(self, function): <NEW_LINE> <INDENT> if function in self.functions: <NEW_LINE> <INDENT> return self.functions[function] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.functions[function] = _FunctionWrapper(function, self.library) <NEW_LINE> return self.functions[function]
Wrapper for a dynamic library with automatic conversion of numpy arrays.
62598fc466673b3332c306a2
class Packable(object): <NEW_LINE> <INDENT> def pack(self): <NEW_LINE> <INDENT> raise NotImplementedError('Must implement in subclass')
Base for all types that provide a .pack() method.
62598fc4f9cc0f698b1c5438
class Guess: <NEW_LINE> <INDENT> def __init__(self, symbol, number): <NEW_LINE> <INDENT> self.symbol=symbol <NEW_LINE> self.number=number <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Guess('{0}',{1})".format(self.symbol, self.number) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return (isinstance(other, Guess)) and self.symbol==other.symbol and self.number == other.number
Fields: symbol: Str number: Nat requires: See Assignment Specifications
62598fc45fc7496912d483e1
class StatusEnum(Enum): <NEW_LINE> <INDENT> DELETED = "deleted"
The status of the deletion request.
62598fc4283ffb24f3cf3b52
class B(Segment): <NEW_LINE> <INDENT> def __init__(self, dist: int): <NEW_LINE> <INDENT> super().__init__(dist)
A segment of the B road.
62598fc47047854f4633f6a1
class QueryNextResponse(FrozenClass): <NEW_LINE> <INDENT> ua_types = { 'TypeId': 'NodeId', 'ResponseHeader': 'ResponseHeader', 'Parameters': 'QueryNextResult', } <NEW_LINE> def __init__(self, binary=None): <NEW_LINE> <INDENT> if binary is not None: <NEW_LINE> <INDENT> self._binary_init(binary) <NEW_LINE> self._freeze = True <NEW_LINE> return <NEW_LINE> <DEDENT> self.TypeId = FourByteNodeId(ObjectIds.QueryNextResponse_Encoding_DefaultBinary) <NEW_LINE> self.ResponseHeader = ResponseHeader() <NEW_LINE> self.Parameters = QueryNextResult() <NEW_LINE> self._freeze = True <NEW_LINE> <DEDENT> def to_binary(self): <NEW_LINE> <INDENT> packet = [] <NEW_LINE> packet.append(self.TypeId.to_binary()) <NEW_LINE> packet.append(self.ResponseHeader.to_binary()) <NEW_LINE> packet.append(self.Parameters.to_binary()) <NEW_LINE> return b''.join(packet) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_binary(data): <NEW_LINE> <INDENT> return QueryNextResponse(data) <NEW_LINE> <DEDENT> def _binary_init(self, data): <NEW_LINE> <INDENT> self.TypeId = NodeId.from_binary(data) <NEW_LINE> self.ResponseHeader = ResponseHeader.from_binary(data) <NEW_LINE> self.Parameters = QueryNextResult.from_binary(data) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'QueryNextResponse(' + 'TypeId:' + str(self.TypeId) + ', ' + 'ResponseHeader:' + str(self.ResponseHeader) + ', ' + 'Parameters:' + str(self.Parameters) + ')' <NEW_LINE> <DEDENT> __repr__ = __str__
:ivar TypeId: :vartype TypeId: NodeId :ivar ResponseHeader: :vartype ResponseHeader: ResponseHeader :ivar Parameters: :vartype Parameters: QueryNextResult
62598fc47cff6e4e811b5cf3
class PolynomialBase(FittableModel): <NEW_LINE> <INDENT> _param_names = () <NEW_LINE> linear = True <NEW_LINE> col_fit_deriv = False <NEW_LINE> @lazyproperty <NEW_LINE> def param_names(self): <NEW_LINE> <INDENT> return self._param_names <NEW_LINE> <DEDENT> def __getattr__(self, attr): <NEW_LINE> <INDENT> if self._param_names and attr in self._param_names: <NEW_LINE> <INDENT> return Parameter(attr, default=0.0, model=self) <NEW_LINE> <DEDENT> raise AttributeError(attr) <NEW_LINE> <DEDENT> def __setattr__(self, attr, value): <NEW_LINE> <INDENT> if attr[0] != '_' and self._param_names and attr in self._param_names: <NEW_LINE> <INDENT> param = Parameter(attr, default=0.0, model=self) <NEW_LINE> param.__set__(self, value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> super(PolynomialBase, self).__setattr__(attr, value) <NEW_LINE> <DEDENT> <DEDENT> def _validate_params(self, **params): <NEW_LINE> <INDENT> valid_params = set(self._param_names) <NEW_LINE> provided_params = set(params) <NEW_LINE> intersection = valid_params.intersection(provided_params) <NEW_LINE> if len(intersection) != len(provided_params): <NEW_LINE> <INDENT> diff = list(provided_params.difference(valid_params)) <NEW_LINE> raise TypeError('Unrecognized input parameters: %s' % diff)
Base class for all polynomial-like models with an arbitrary number of parameters in the form of coefficients. In this case Parameter instances are returned through the class's ``__getattr__`` rather than through class descriptors.
62598fc4956e5f7376df57e5
class WebClusterPicture: <NEW_LINE> <INDENT> def __init__(self, label, data=None): <NEW_LINE> <INDENT> self.label = label <NEW_LINE> if data is None: <NEW_LINE> <INDENT> self._data = self._get_dbdata() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._data = data <NEW_LINE> <DEDENT> <DEDENT> def _get_dbdata(self): <NEW_LINE> <INDENT> return db.cluster_pictures.lookup(self.label) <NEW_LINE> <DEDENT> def is_null(self): <NEW_LINE> <INDENT> return self._data is None <NEW_LINE> <DEDENT> def get_label(self): <NEW_LINE> <INDENT> return self._data['label'] <NEW_LINE> <DEDENT> def image(self): <NEW_LINE> <INDENT> return self._data['image'] <NEW_LINE> <DEDENT> def thumbnail(self): <NEW_LINE> <INDENT> return self._data['thumbnail'] <NEW_LINE> <DEDENT> def depth(self): <NEW_LINE> <INDENT> return self._data['depth'] <NEW_LINE> <DEDENT> def size(self): <NEW_LINE> <INDENT> return self._data['size'] <NEW_LINE> <DEDENT> def potential_toric_rank(self): <NEW_LINE> <INDENT> return self._data['potential_toric_rank'] <NEW_LINE> <DEDENT> def potential_good_reduction(self): <NEW_LINE> <INDENT> return self._data['potential_good_reduction'] <NEW_LINE> <DEDENT> def potential_good_jacobian_reduction(self): <NEW_LINE> <INDENT> return self._data['potential_good_jacobian_reduction'] <NEW_LINE> <DEDENT> def knowl(self): <NEW_LINE> <INDENT> return cp_display_knowl(self.get_label())
Class for retrieving cluster picture information from the database
62598fc4cc40096d6161a33f
class UniquePerson(object): <NEW_LINE> <INDENT> def __call__(self, form, field): <NEW_LINE> <INDENT> if form.lead.data.number == form.follow.data.number: <NEW_LINE> <INDENT> raise ValidationError(field.gettext(f"{form.lead.data} cannot dance with himself or herself."))
Checks if there are no double dancers in the competition.
62598fc4091ae35668704ef6
class StyleStore(object) : <NEW_LINE> <INDENT> __styles = {} <NEW_LINE> @classmethod <NEW_LINE> def styles ( kls ) : <NEW_LINE> <INDENT> return kls.__styles
Store for all created/cofigures styles
62598fc45fdd1c0f98e5e262
class EndPoint(object): <NEW_LINE> <INDENT> def __init__(self, api, path, suffix=''): <NEW_LINE> <INDENT> self.api = api <NEW_LINE> self.path = path <NEW_LINE> self.suffix = suffix <NEW_LINE> <DEDENT> def __getitem__(self, item): <NEW_LINE> <INDENT> return EndPoint(self.api, '/'.join([self.path, str(item)]), self.suffix) <NEW_LINE> <DEDENT> def __getattr__(self, attr): <NEW_LINE> <INDENT> if attr in HTTP_VERBS: <NEW_LINE> <INDENT> return partial(self._http, attr) <NEW_LINE> <DEDENT> return self[attr] <NEW_LINE> <DEDENT> def __call__(self, **kwargs): <NEW_LINE> <INDENT> return self.GET(**kwargs) <NEW_LINE> <DEDENT> def build_url(self, verb='GET', **kwargs): <NEW_LINE> <INDENT> path = self.path <NEW_LINE> if self.api.ensure_slash and verb == 'POST' and not path.endswith('/'): <NEW_LINE> <INDENT> path = path + '/' <NEW_LINE> <DEDENT> extra = '' <NEW_LINE> if kwargs: <NEW_LINE> <INDENT> querystring = urlencode(kwargs) <NEW_LINE> extra = '?' + querystring <NEW_LINE> <DEDENT> return "{0}{1}{2}".format(path, self.suffix, extra) <NEW_LINE> <DEDENT> def _http(self, verb, data=None, **kwargs): <NEW_LINE> <INDENT> url = self.build_url(verb, **kwargs) <NEW_LINE> response = self.api._http(verb, url, data=data) <NEW_LINE> if response.content: <NEW_LINE> <INDENT> return dotify(response.json()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None
A potential end point of an API, where we can get JSON data from. An instance of `EndPoint` is a callable that upon invocation performs a GET request. Any kwargs passed in to the call will be used to build a query string.
62598fc4fff4ab517ebcdab5
class ConnectionsException(ProsperBotException): <NEW_LINE> <INDENT> pass
class for prosper_bots.connections
62598fc44f88993c371f0672