code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class SSEClient: <NEW_LINE> <INDENT> def __init__(self, url, last_id=None, http_factory=None, **kwargs): <NEW_LINE> <INDENT> self.url = url <NEW_LINE> self.last_id = last_id <NEW_LINE> self._chunk_size = 10000 <NEW_LINE> if http_factory is None: <NEW_LINE> <INDENT> http_factory = HTTPFactory({}, HTTPConfig()) <NEW_LINE> <DEDENT> self._timeout = http_factory.timeout <NEW_LINE> base_headers = http_factory.base_headers <NEW_LINE> self.http = http_factory.create_pool_manager(1, url) <NEW_LINE> self.requests_kwargs = kwargs <NEW_LINE> if 'headers' not in self.requests_kwargs: <NEW_LINE> <INDENT> self.requests_kwargs['headers'] = {} <NEW_LINE> <DEDENT> self.requests_kwargs['headers'].update(base_headers) <NEW_LINE> self.requests_kwargs['headers']['Cache-Control'] = 'no-cache' <NEW_LINE> self.requests_kwargs['headers']['Accept'] = 'text/event-stream' <NEW_LINE> self._connect() <NEW_LINE> <DEDENT> def _connect(self): <NEW_LINE> <INDENT> if self.last_id: <NEW_LINE> <INDENT> self.requests_kwargs['headers']['Last-Event-ID'] = self.last_id <NEW_LINE> <DEDENT> self.resp = self.http.request( 'GET', self.url, timeout=self._timeout, preload_content=False, retries=0, **self.requests_kwargs) <NEW_LINE> self.resp_file = self.resp.stream(amt=self._chunk_size) <NEW_LINE> throw_if_unsuccessful_response(self.resp) <NEW_LINE> <DEDENT> @property <NEW_LINE> def events(self): <NEW_LINE> <INDENT> event_type = "" <NEW_LINE> event_data = None <NEW_LINE> for line in _BufferedLineReader.lines_from(self.resp_file): <NEW_LINE> <INDENT> if line == "": <NEW_LINE> <INDENT> if event_data is not None: <NEW_LINE> <INDENT> yield Event("message" if event_type == "" else event_type, event_data, self.last_id) <NEW_LINE> <DEDENT> event_type = "" <NEW_LINE> event_data = None <NEW_LINE> continue <NEW_LINE> <DEDENT> colon_pos = line.find(':') <NEW_LINE> if colon_pos < 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if colon_pos == 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> name = line[0:colon_pos] <NEW_LINE> if colon_pos < (len(line) - 1) and line[colon_pos + 1] == ' ': <NEW_LINE> <INDENT> colon_pos += 1 <NEW_LINE> <DEDENT> value = line[colon_pos+1:] <NEW_LINE> if name == 'event': <NEW_LINE> <INDENT> event_type = value <NEW_LINE> <DEDENT> elif name == 'data': <NEW_LINE> <INDENT> event_data = value if event_data is None else (event_data + "\n" + value) <NEW_LINE> <DEDENT> elif name == 'id': <NEW_LINE> <INDENT> self.last_id = value <NEW_LINE> <DEDENT> elif name == 'retry': <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, type, value, traceback): <NEW_LINE> <INDENT> self.close() | A simple Server-Sent Events client.
This implementation does not include automatic retrying of a dropped connection; the caller will do that.
If a connection ends, the events iterator will simply end. | 62598f9bd58c6744b42dc1a0 |
class Animal(_BaseModel): <NEW_LINE> <INDENT> SEX_CHOICES = ( ('f', 'Female'), ('m', 'Male'), ('h', 'Hermaphrodite'), ) <NEW_LINE> specie = models.ForeignKey(Specie, **_FKEY) <NEW_LINE> race = models.CharField(blank=True, **_CHAR) <NEW_LINE> sex = models.CharField(max_length=2, choices=SEX_CHOICES, blank=True) <NEW_LINE> photo = models.ImageField( height_field='photo_height', width_field='photo_width', upload_to='animals', blank=True ) <NEW_LINE> photo_height = models.IntegerField(null=True, blank=True, editable=False) <NEW_LINE> photo_width = models.IntegerField(null=True, blank=True, editable=False) <NEW_LINE> owners = models.ManyToManyField(User, blank=True) | Animal class represents the animal itself. | 62598f9b435de62698e9bb93 |
class FeedbackForm(PotatoCaptchaForm): <NEW_LINE> <INDENT> feedback = forms.CharField(required=True, label='', widget=forms.Textarea(attrs={'rows': 4})) <NEW_LINE> platform = forms.CharField(required=False, widget=forms.HiddenInput, label='') <NEW_LINE> chromeless = forms.CharField(required=False, widget=forms.HiddenInput, label='') <NEW_LINE> from_url = forms.CharField(required=False, widget=forms.HiddenInput, label='') | Site feedback form. | 62598f9b8e7ae83300ee8e3d |
class CreateRouter(neutronV20.CreateCommand): <NEW_LINE> <INDENT> resource = 'router' <NEW_LINE> _formatters = {'external_gateway_info': _format_external_gateway_info, } <NEW_LINE> def add_known_arguments(self, parser): <NEW_LINE> <INDENT> parser.add_argument( '--admin-state-down', dest='admin_state', action='store_false', help=_('Set admin state up to false.')) <NEW_LINE> parser.add_argument( '--admin_state_down', dest='admin_state', action='store_false', help=argparse.SUPPRESS) <NEW_LINE> parser.add_argument( 'name', metavar='NAME', help=_('Name of router to create.')) <NEW_LINE> parser.add_argument( '--description', help=_('Description of router.')) <NEW_LINE> utils.add_boolean_argument( parser, '--distributed', dest='distributed', help=_('Create a distributed router.')) <NEW_LINE> utils.add_boolean_argument( parser, '--ha', dest='ha', help=_('Create a highly available router.')) <NEW_LINE> availability_zone.add_az_hint_argument(parser, self.resource) <NEW_LINE> <DEDENT> def args2body(self, parsed_args): <NEW_LINE> <INDENT> body = {'admin_state_up': parsed_args.admin_state} <NEW_LINE> neutronV20.update_dict(parsed_args, body, ['name', 'tenant_id', 'distributed', 'ha', 'description']) <NEW_LINE> availability_zone.args2body_az_hint(parsed_args, body) <NEW_LINE> return {self.resource: body} | Create a router for a given tenant. | 62598f9b0c0af96317c56121 |
class Tab(Component): <NEW_LINE> <INDENT> @_explicitize_args <NEW_LINE> def __init__(self, children=None, id=Component.UNDEFINED, style=Component.UNDEFINED, className=Component.UNDEFINED, label=Component.UNDEFINED, tab_id=Component.UNDEFINED, **kwargs): <NEW_LINE> <INDENT> self._prop_names = ['children', 'id', 'style', 'className', 'label', 'tab_id'] <NEW_LINE> self._type = 'Tab' <NEW_LINE> self._namespace = 'dash_bootstrap_components/_components' <NEW_LINE> self._valid_wildcard_attributes = [] <NEW_LINE> self.available_events = [] <NEW_LINE> self.available_properties = ['children', 'id', 'style', 'className', 'label', 'tab_id'] <NEW_LINE> self.available_wildcard_properties = [] <NEW_LINE> _explicit_args = kwargs.pop('_explicit_args') <NEW_LINE> _locals = locals() <NEW_LINE> _locals.update(kwargs) <NEW_LINE> args = {k: _locals[k] for k in _explicit_args if k != 'children'} <NEW_LINE> for k in []: <NEW_LINE> <INDENT> if k not in args: <NEW_LINE> <INDENT> raise TypeError( 'Required argument `' + k + '` was not specified.') <NEW_LINE> <DEDENT> <DEDENT> super(Tab, self).__init__(children=children, **args) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if(any(getattr(self, c, None) is not None for c in self._prop_names if c is not self._prop_names[0]) or any(getattr(self, c, None) is not None for c in self.__dict__.keys() if any(c.startswith(wc_attr) for wc_attr in self._valid_wildcard_attributes))): <NEW_LINE> <INDENT> props_string = ', '.join([c+'='+repr(getattr(self, c, None)) for c in self._prop_names if getattr(self, c, None) is not None]) <NEW_LINE> wilds_string = ', '.join([c+'='+repr(getattr(self, c, None)) for c in self.__dict__.keys() if any([c.startswith(wc_attr) for wc_attr in self._valid_wildcard_attributes])]) <NEW_LINE> return ('Tab(' + props_string + (', ' + wilds_string if wilds_string != '' else '') + ')') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ( 'Tab(' + repr(getattr(self, self._prop_names[0], None)) + ')') | A Tab component.
Keyword arguments:
- children (a list of or a singular dash component, string or number; optional): The children of this component
- id (string; optional): The ID of this component, used to identify dash components
in callbacks. The ID needs to be unique across all of the
components in an app.
- style (dict; optional): Defines CSS styles which will override styles previously set.
- className (string; optional): Often used with CSS to style elements with common properties.
- label (string; optional): The tab's label
- tab_id (string; optional): Optional identifier for tab used for determining which tab is visible
if not specified, and Tab is being used inside Tabs component, the tabId
will be set to "tab-i" where i is (zero indexed) position of tab in list
tabs pased to Tabs component.
Available events: | 62598f9be64d504609df9287 |
class PADSWriteHelper(PADSHelper): <NEW_LINE> <INDENT> def new(self, item_id): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def delete(self, item_id): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def __init__(self, user_id=settings['user_id_signed_out'], **kwargs): <NEW_LINE> <INDENT> super().__init__(user_id, **kwargs) | Base class for helper classes that store data, whether saving new
items or modifying existing ones | 62598f9bfff4ab517ebcd58c |
class MLens(object): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> raise Exception("Called abstract method get of MLens") <NEW_LINE> <DEDENT> def set(self, _new): <NEW_LINE> <INDENT> raise Exception("Called abstract method set of MLens") | A mutable lens interface.
Implementations should respect the lens laws:
1) You get out what you put in:
lens.set(a)
assert lens.get() == a
2) Putting back what you got changes nothing:
{ a = lens.get(); lens.set(a) } = {}
3) Writing twice is the same as writing once:
{ lens.set(a); lens.set(b) } = { lens.set(b) } | 62598f9b30dc7b766599f5eb |
class CoursewareContextTestCase(ModuleStoreTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(CoursewareContextTestCase, self).setUp(create_user=True) <NEW_LINE> self.course = CourseFactory.create(org="TestX", number="101", display_name="Test Course") <NEW_LINE> self.discussion1 = ItemFactory.create( parent_location=self.course.location, category="discussion", discussion_id="discussion1", discussion_category="Chapter", discussion_target="Discussion 1" ) <NEW_LINE> self.discussion2 = ItemFactory.create( parent_location=self.course.location, category="discussion", discussion_id="discussion2", discussion_category="Chapter / Section / Subsection", discussion_target="Discussion 2" ) <NEW_LINE> <DEDENT> def test_empty(self): <NEW_LINE> <INDENT> utils.add_courseware_context([], self.course, self.user) <NEW_LINE> <DEDENT> def test_missing_commentable_id(self): <NEW_LINE> <INDENT> orig = {"commentable_id": "non-inline"} <NEW_LINE> modified = dict(orig) <NEW_LINE> utils.add_courseware_context([modified], self.course, self.user) <NEW_LINE> self.assertEqual(modified, orig) <NEW_LINE> <DEDENT> def test_basic(self): <NEW_LINE> <INDENT> threads = [ {"commentable_id": self.discussion1.discussion_id}, {"commentable_id": self.discussion2.discussion_id} ] <NEW_LINE> utils.add_courseware_context(threads, self.course, self.user) <NEW_LINE> def assertThreadCorrect(thread, discussion, expected_title): <NEW_LINE> <INDENT> self.assertEqual( set(thread.keys()), set(["commentable_id", "courseware_url", "courseware_title"]) ) <NEW_LINE> self.assertEqual( thread.get("courseware_url"), reverse( "jump_to", kwargs={ "course_id": self.course.id.to_deprecated_string(), "location": discussion.location.to_deprecated_string() } ) ) <NEW_LINE> self.assertEqual(thread.get("courseware_title"), expected_title) <NEW_LINE> <DEDENT> assertThreadCorrect(threads[0], self.discussion1, "Chapter / Discussion 1") <NEW_LINE> assertThreadCorrect(threads[1], self.discussion2, "Subsection / Discussion 2") | Base testcase class for courseware context for the
comment client service integration | 62598f9b2ae34c7f260aae7f |
class StateManager: <NEW_LINE> <INDENT> def __init__(self, cmd_exec): <NEW_LINE> <INDENT> self.__cmd_exec = cmd_exec <NEW_LINE> self.__state = State.NONE <NEW_LINE> self.__state_obj = StateNone(self.__cmd_exec) <NEW_LINE> <DEDENT> def __update_state(self, next_state, ctrl_points): <NEW_LINE> <INDENT> if next_state == self.__state: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> obj = None <NEW_LINE> if next_state == State.TRANSLATING: <NEW_LINE> <INDENT> obj = StateTranslating(self.__cmd_exec, ctrl_points) <NEW_LINE> <DEDENT> elif State.SCALING_1 <= next_state <= State.SCALING_8: <NEW_LINE> <INDENT> obj = StateScaling( self.__cmd_exec, next_state, ctrl_points) <NEW_LINE> <DEDENT> elif next_state == State.ROTATING: <NEW_LINE> <INDENT> obj = StateRotating(self.__cmd_exec, ctrl_points) <NEW_LINE> <DEDENT> elif next_state == State.NONE: <NEW_LINE> <INDENT> obj = StateNone(self.__cmd_exec) <NEW_LINE> <DEDENT> elif (State.UNIFORM_SCALING_1 <= next_state <= State.UNIFORM_SCALING_4): <NEW_LINE> <INDENT> obj = StateUniformScaling( self.__cmd_exec, next_state, ctrl_points) <NEW_LINE> <DEDENT> if obj is not None: <NEW_LINE> <INDENT> self.__state_obj = obj <NEW_LINE> <DEDENT> self.__state = next_state <NEW_LINE> <DEDENT> def update(self, context, ctrl_points, event): <NEW_LINE> <INDENT> mouse_region = mathutils.Vector(( event.mouse_region_x, event.mouse_region_y)) <NEW_LINE> mouse_view = mathutils.Vector((context.region.view2d.region_to_view( mouse_region.x, mouse_region.y))) <NEW_LINE> next_state = self.__state_obj.update( context, event, ctrl_points, mouse_view) <NEW_LINE> self.__update_state(next_state, ctrl_points) <NEW_LINE> return self.__state | Custom class: Manage state about this feature | 62598f9b379a373c97d98db2 |
class Book(models.Model): <NEW_LINE> <INDENT> title = models.CharField(max_length=200) <NEW_LINE> author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) <NEW_LINE> summary = models.TextField(max_length=1000, help_text="Enter a brief description of the book") <NEW_LINE> isbn = models.CharField('ISBN', max_length=13, help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>') <NEW_LINE> genre = models.ManyToManyField(Genre, help_text="Select a genre for this book") <NEW_LINE> def display_genre(self): <NEW_LINE> <INDENT> return ', '.join([genre.name for genre in self.genre.all()[:3]]) <NEW_LINE> <DEDENT> display_genre.short_description = 'Genre' <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return "{0}({1})".format(self.title,self.author.first_name) <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('book-detail', args=[str(self.id)]) | Model representing a book (but not a specific copy of a book). | 62598f9b63d6d428bbee2550 |
class Datum(object): <NEW_LINE> <INDENT> def __init__(self, pos, kind, ln, data): <NEW_LINE> <INDENT> self.pos = pos <NEW_LINE> self.kind = kind <NEW_LINE> self.ln = ln <NEW_LINE> self.data = data <NEW_LINE> self.children = None <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Datum(%r,%r,%r,%r)" % (self.pos, self.kind, self.ln, self.data) <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> return self.pos < other.pos <NEW_LINE> <DEDENT> def __gt__(self, other): <NEW_LINE> <INDENT> return self.pos > other.pos <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.pos == other.pos <NEW_LINE> <DEDENT> def build_maps(self): <NEW_LINE> <INDENT> if not hasattr(self, 'nChildren'): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if self.kind == TP_ARRAY: <NEW_LINE> <INDENT> del self.nChildren <NEW_LINE> for c in self.children: <NEW_LINE> <INDENT> c.build_maps() <NEW_LINE> <DEDENT> <DEDENT> elif self.kind == TP_MAP: <NEW_LINE> <INDENT> del self.nChildren <NEW_LINE> self.map = {} <NEW_LINE> for i in range(0, len(self.children), 2): <NEW_LINE> <INDENT> k = self.children[i].deref() <NEW_LINE> v = self.children[i+1].deref() <NEW_LINE> v.build_maps() <NEW_LINE> if k.kind != TP_UTF8: <NEW_LINE> <INDENT> raise ValueError("Bad dictionary key type %d"% k.kind) <NEW_LINE> <DEDENT> self.map[bytesToStr(k.data)] = v <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def int_val(self): <NEW_LINE> <INDENT> assert self.kind in (TP_UINT16, TP_UINT32, TP_UINT64, TP_UINT128, TP_SINT32) <NEW_LINE> i = to_int(self.data) <NEW_LINE> if self.kind == TP_SINT32: <NEW_LINE> <INDENT> if i & 0x80000000: <NEW_LINE> <INDENT> i = i - 0x100000000 <NEW_LINE> <DEDENT> <DEDENT> return i <NEW_LINE> <DEDENT> def deref(self): <NEW_LINE> <INDENT> n = 0 <NEW_LINE> s = self <NEW_LINE> while s.kind == TP_PTR: <NEW_LINE> <INDENT> s = s.ptr <NEW_LINE> n += 1 <NEW_LINE> assert n < 100 <NEW_LINE> <DEDENT> return s | Holds a single entry from the Data section | 62598f9b462c4b4f79dbb7aa |
class Conditions: <NEW_LINE> <INDENT> def __init__(self, atoms): <NEW_LINE> <INDENT> self.atoms = atoms <NEW_LINE> self.atoms_symbols = atoms.get_chemical_symbols() <NEW_LINE> self.atoms_labels = atoms.get_chemical_symbols() <NEW_LINE> self.atom_types = [] <NEW_LINE> <DEDENT> def min_distance_rule(self, sym1, sym2, ifcloselabel1=None, ifcloselabel2=None, elselabel1=None, max_distance=3.0): <NEW_LINE> <INDENT> if ifcloselabel1 is None: <NEW_LINE> <INDENT> ifcloselabel1 = sym1 <NEW_LINE> <DEDENT> if ifcloselabel2 is None: <NEW_LINE> <INDENT> ifcloselabel2 = sym2 <NEW_LINE> <DEDENT> if elselabel1 is None: <NEW_LINE> <INDENT> elselabel1 = sym1 <NEW_LINE> <DEDENT> self.atom_types.append([sym1, ifcloselabel1, elselabel1]) <NEW_LINE> self.atom_types.append([sym2, ifcloselabel2]) <NEW_LINE> dist_mat = self.atoms.get_all_distances() <NEW_LINE> index_assigned_sym1 = [] <NEW_LINE> index_assigned_sym2 = [] <NEW_LINE> for i in range(len(self.atoms_symbols)): <NEW_LINE> <INDENT> if self.atoms_symbols[i] == sym2: <NEW_LINE> <INDENT> dist_12 = 1000 <NEW_LINE> index_assigned_sym2.append(i) <NEW_LINE> for t in range(len(self.atoms_symbols)): <NEW_LINE> <INDENT> if (self.atoms_symbols[t] == sym1 and dist_mat[i, t] < dist_12 and t not in index_assigned_sym1): <NEW_LINE> <INDENT> dist_12 = dist_mat[i, t] <NEW_LINE> closest_sym1_index = t <NEW_LINE> <DEDENT> <DEDENT> index_assigned_sym1.append(closest_sym1_index) <NEW_LINE> <DEDENT> <DEDENT> for i1, i2 in zip(index_assigned_sym1, index_assigned_sym2): <NEW_LINE> <INDENT> if dist_mat[i1, i2] > max_distance: <NEW_LINE> <INDENT> raise ValueError('Cannot unambiguously apply minimum-distance ' 'rule because pairings are not obvious. ' 'If you wish to ignore this, then increase ' 'max_distance.') <NEW_LINE> <DEDENT> <DEDENT> for s in range(len(self.atoms_symbols)): <NEW_LINE> <INDENT> if s in index_assigned_sym1: <NEW_LINE> <INDENT> self.atoms_labels[s] = ifcloselabel1 <NEW_LINE> <DEDENT> elif s not in index_assigned_sym1 and self.atoms_symbols[s] == sym1: <NEW_LINE> <INDENT> self.atoms_labels[s] = elselabel1 <NEW_LINE> <DEDENT> elif s in index_assigned_sym2: <NEW_LINE> <INDENT> self.atoms_labels[s] = ifcloselabel2 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_atom_types(self): <NEW_LINE> <INDENT> return self.atom_types <NEW_LINE> <DEDENT> def get_atoms_labels(self): <NEW_LINE> <INDENT> labels = np.array(self.atoms_labels) <NEW_LINE> return labels | Atomic labels for the GULP calculator.
This class manages an array similar to
atoms.get_chemical_symbols() via get_atoms_labels() method, but
with atomic labels in stead of atomic symbols. This is useful
when you need to use calculators like GULP or lammps that use
force fields. Some force fields can have different atom type for
the same element. In this class you can create a set_rule()
function that assigns labels according to structural criteria. | 62598f9b0c0af96317c56122 |
class IndyCredDefId(Regexp): <NEW_LINE> <INDENT> EXAMPLE = "WgWxqztrNooG92RXvxSTWv:3:CL:20:tag" <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super().__init__( ( rf"([{B58}]{{21,22}})" f":3" f":CL" rf":(([1-9][0-9]*)|([{B58}]{{21,22}}:2:.+:[0-9.]+))" f"(.+)?$" ), error="Value {input} is not an indy credential definition identifier." ) | Validate value against indy credential definition identifier specification. | 62598f9b4a966d76dd5eec80 |
class AppTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def test_root_text(self): <NEW_LINE> <INDENT> tester = app.test_client(self) <NEW_LINE> response = tester.get('/') <NEW_LINE> self.assertEqual(response.data, b'Hello world!') | AppTestCase
| 62598f9ba17c0f6771d5bfda |
@singleton <NEW_LINE> class Configurator: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._db_host = 'localhost' <NEW_LINE> self._db_port = 33054 <NEW_LINE> self._db_name = 'ffmpeg' <NEW_LINE> self._db_table = 'appcommand' <NEW_LINE> self._db_user = None <NEW_LINE> self._db_password = '' <NEW_LINE> self._db_config = None <NEW_LINE> self._log_level = logging.INFO <NEW_LINE> self._log_dir = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def db_host(self): <NEW_LINE> <INDENT> return self._db_host <NEW_LINE> <DEDENT> @db_host.setter <NEW_LINE> def db_host(self, value): <NEW_LINE> <INDENT> self._db_host = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def db_port(self): <NEW_LINE> <INDENT> return self._db_port <NEW_LINE> <DEDENT> @db_port.setter <NEW_LINE> def db_port(self, value): <NEW_LINE> <INDENT> self._db_port = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def db_name(self): <NEW_LINE> <INDENT> return self._db_name <NEW_LINE> <DEDENT> @db_name.setter <NEW_LINE> def db_name(self, value): <NEW_LINE> <INDENT> self._db_name = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def db_table(self): <NEW_LINE> <INDENT> return self._db_table <NEW_LINE> <DEDENT> @db_table.setter <NEW_LINE> def db_table(self, value): <NEW_LINE> <INDENT> self._db_table = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def db_user(self): <NEW_LINE> <INDENT> return self._db_user <NEW_LINE> <DEDENT> @db_user.setter <NEW_LINE> def db_user(self, value): <NEW_LINE> <INDENT> self._db_user = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def db_password(self): <NEW_LINE> <INDENT> return self._db_password <NEW_LINE> <DEDENT> @db_password.setter <NEW_LINE> def db_password(self, value): <NEW_LINE> <INDENT> self._db_password = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def db_config(self): <NEW_LINE> <INDENT> return self._db_config <NEW_LINE> <DEDENT> @db_config.setter <NEW_LINE> def db_config(self, value): <NEW_LINE> <INDENT> self._db_config = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def log_level(self): <NEW_LINE> <INDENT> return self._log_level <NEW_LINE> <DEDENT> @log_level.setter <NEW_LINE> def log_level(self, value): <NEW_LINE> <INDENT> self._log_level = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def log_dir(self): <NEW_LINE> <INDENT> return self._log_dir <NEW_LINE> <DEDENT> @log_dir.setter <NEW_LINE> def log_dir(self, value): <NEW_LINE> <INDENT> self._log_dir = value | Configuration manager | 62598f9b96565a6dacd2ce48 |
class ManyQubitGateFallbacker(Backend): <NEW_LINE> <INDENT> def _run_inner(self, gates, n_qubits) -> List[Operation]: <NEW_LINE> <INDENT> decomposed = [] <NEW_LINE> for gate in gates: <NEW_LINE> <INDENT> if gate.n_qargs > 2: <NEW_LINE> <INDENT> decomposed += self._run_inner(gate.fallback(n_qubits), n_qubits) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> decomposed.append(gate) <NEW_LINE> <DEDENT> <DEDENT> return decomposed <NEW_LINE> <DEDENT> def run(self, gates, n_qubits, *args, **kwargs) -> Circuit: <NEW_LINE> <INDENT> return Circuit(n_qubits, self._run_inner(gates, n_qubits)) | Decomposite more than 2 qubit gate by fallback system. | 62598f9b097d151d1a2c0dc5 |
@resource('/users/bind/auto', _web=True) <NEW_LINE> class BindAuto(Resource): <NEW_LINE> <INDENT> key = 'auto' <NEW_LINE> def add_args(self): <NEW_LINE> <INDENT> super(BindAuto, self).add_args() <NEW_LINE> self.req.add_argument('device', type=unicode, default='') <NEW_LINE> <DEDENT> @login_required <NEW_LINE> def post(self): <NEW_LINE> <INDENT> args = self.get_args() <NEW_LINE> self.validate(args) <NEW_LINE> if current_user.is_user(): <NEW_LINE> <INDENT> return self.success(current_user, args) <NEW_LINE> <DEDENT> if current_user.user: <NEW_LINE> <INDENT> abort(BINDED) <NEW_LINE> <DEDENT> if um.config.oauth_model == 'force': <NEW_LINE> <INDENT> abort(NEED_BIND) <NEW_LINE> <DEDENT> user = um.models.User.from_oauth(current_user) <NEW_LINE> um.models.UserLog.bind(user.id, args['device'], key=self.key) <NEW_LINE> return self.success(user, args) <NEW_LINE> <DEDENT> def success(self, user, args): <NEW_LINE> <INDENT> return um.funcs.login(user, device=args['device'], key=self.key) <NEW_LINE> <DEDENT> def validate(self, args): <NEW_LINE> <INDENT> pass | 自动绑定 | 62598f9b3c8af77a43b67e0d |
class ShovelTest_Tool(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.label = "Make Shovel Test Grid" <NEW_LINE> self.description = """Makes a shovel test grid.""" <NEW_LINE> self.canRunInBackground = False <NEW_LINE> self.category = "Wildsong" <NEW_LINE> <DEDENT> def getParameterInfo(self): <NEW_LINE> <INDENT> params = [] <NEW_LINE> baseline_fc = arcpy.Parameter(name="baseline", displayName="Baseline Feature Class", datatype="DEFeatureClass", parameterType="Required", direction="Input", ) <NEW_LINE> baseline_fc.filter.list = ["Polyline"] <NEW_LINE> baseline_fc.value = "testspace.gdb/baseline" <NEW_LINE> params.append(baseline_fc) <NEW_LINE> template_fc = arcpy.Parameter(name="template", displayName="Template Feature Class", datatype="DEFeatureClass", parameterType="Required", direction="Input", ) <NEW_LINE> template_fc.filter.list = ["Polygon"] <NEW_LINE> template_fc.value = "testspace.gdb/template" <NEW_LINE> params.append(template_fc) <NEW_LINE> output_workspace = arcpy.Parameter(name="output_workspace", displayName="Output workspace", datatype="DEWorkspace", parameterType="Required", direction="Input", ) <NEW_LINE> output_workspace.value = "testspace.gdb" <NEW_LINE> params.append(output_workspace) <NEW_LINE> output_poly = arcpy.Parameter(name="output_polygon_features", displayName="Output polygon feature class", datatype="GPString", parameterType="Required", direction="Input", ) <NEW_LINE> output_poly.value = "grid_poly" <NEW_LINE> params.append(output_poly) <NEW_LINE> output_point = arcpy.Parameter(name="output_point_features", displayName="Output point feature class", datatype="GPString", parameterType="Required", direction="Input", ) <NEW_LINE> output_point.value = "grid_point" <NEW_LINE> params.append(output_point) <NEW_LINE> width = arcpy.Parameter(name="grid_cell_width", displayName="Width of a grid cell", datatype="GPDouble", parameterType="Required", direction="Input", ) <NEW_LINE> width.value = "50" <NEW_LINE> params.append(width) <NEW_LINE> height = arcpy.Parameter(name="grid_cell_height", displayName="Height of a grid cell", datatype="GPDouble", parameterType="Required", direction="Input", ) <NEW_LINE> height.value = "50" <NEW_LINE> params.append(height) <NEW_LINE> return params <NEW_LINE> <DEDENT> def isLicensed(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def updateParameters(self, parameters): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def updateMessages(self, parameters): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def execute(self, parameters, messages): <NEW_LINE> <INDENT> for param in parameters: <NEW_LINE> <INDENT> messages.AddMessage("Parameter: %s = %s" % (param.name, param.valueAsText) ) <NEW_LINE> <DEDENT> baseline_fc = parameters[0].valueAsText <NEW_LINE> template_fc = parameters[1].valueAsText <NEW_LINE> workspace = parameters[2].valueAsText <NEW_LINE> output_poly = parameters[3].valueAsText <NEW_LINE> output_point = parameters[4].valueAsText <NEW_LINE> width = parameters[5].valueAsText <NEW_LINE> height = parameters[6].valueAsText <NEW_LINE> makegrid(baseline_fc, template_fc, workspace, output_poly, output_point, width, height) <NEW_LINE> return | This class has the methods you need to define
to use your code as an ArcGIS Python Tool. | 62598f9b009cb60464d012c4 |
class HistoryPlugin(object): <NEW_LINE> <INDENT> def __init__(self, exaile): <NEW_LINE> <INDENT> self.exaile = exaile <NEW_LINE> save_on_exit = settings.get_option('plugin/history/save_on_exit', history_preferences.save_on_exit_default) <NEW_LINE> shown = settings.get_option('plugin/history/shown', False) <NEW_LINE> self.history_loc = os.path.join(xdg.get_data_dir(), 'history') <NEW_LINE> self.history_playlist = HistoryPlaylist( player.PLAYER ) <NEW_LINE> if save_on_exit: <NEW_LINE> <INDENT> self.history_playlist.load_from_location( self.history_loc ) <NEW_LINE> <DEDENT> self.history_page = HistoryPlaylistPage( self.history_playlist, player.PLAYER ) <NEW_LINE> self.history_tab = NotebookTab(main.get_playlist_notebook(), self.history_page ) <NEW_LINE> self.menu = menu.check_menu_item( 'history', '', _('Playback history'), lambda *e: self.is_shown(), self.on_playback_history ) <NEW_LINE> providers.register( 'menubar-view-menu', self.menu ) <NEW_LINE> if save_on_exit and shown: <NEW_LINE> <INDENT> self.show_history( True ) <NEW_LINE> <DEDENT> <DEDENT> def teardown_plugin(self, exaile): <NEW_LINE> <INDENT> if settings.get_option('plugin/history/save_on_exit', history_preferences.save_on_exit_default ): <NEW_LINE> <INDENT> self.history_playlist.save_to_location( self.history_loc ) <NEW_LINE> settings.set_option( 'plugin/history/shown', self.is_shown() ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> settings.set_option( 'plugin/history/shown', False ) <NEW_LINE> <DEDENT> self.show_history(False) <NEW_LINE> <DEDENT> def disable_plugin(self, exaile): <NEW_LINE> <INDENT> if self.menu: <NEW_LINE> <INDENT> providers.unregister( 'menubar-view-menu', self.menu ) <NEW_LINE> self.menu = None <NEW_LINE> <DEDENT> self.show_history(False) <NEW_LINE> if os.path.exists( self.history_loc ): <NEW_LINE> <INDENT> dialog = gtk.MessageDialog( None, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO, _('Erase stored history?') ) <NEW_LINE> if dialog.run() == gtk.RESPONSE_YES: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.unlink( self.history_loc ) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> dialog.destroy() <NEW_LINE> <DEDENT> <DEDENT> def is_shown(self): <NEW_LINE> <INDENT> return main.get_playlist_notebook().page_num( self.history_page ) != -1 <NEW_LINE> <DEDENT> def on_playback_history(self, menu, name, parent, context): <NEW_LINE> <INDENT> self.show_history( not self.is_shown() ) <NEW_LINE> <DEDENT> def show_history(self, show): <NEW_LINE> <INDENT> if show == self.is_shown(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if show: <NEW_LINE> <INDENT> pn = main.get_playlist_notebook() <NEW_LINE> pn.add_tab( self.history_tab, self.history_page ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.history_tab.close() | Implements logic for plugin | 62598f9bbe8e80087fbbedff |
class DelugeTransferProtocol(asyncio.Protocol): <NEW_LINE> <INDENT> def __init__(self, message_received_callback): <NEW_LINE> <INDENT> self.transport = None <NEW_LINE> self.message_received = message_received_callback <NEW_LINE> self._buffer = bytes() <NEW_LINE> self._message_length = 0 <NEW_LINE> self.connected = False <NEW_LINE> self.on_disconnect = asyncio.Future() <NEW_LINE> <DEDENT> def connection_made(self, transport): <NEW_LINE> <INDENT> self.transport = transport <NEW_LINE> self.connected = True <NEW_LINE> <DEDENT> def connection_lost(self, exc): <NEW_LINE> <INDENT> self.connected = False <NEW_LINE> if exc: <NEW_LINE> <INDENT> self.on_disconnect.set_exception(exc) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.on_disconnect.done() <NEW_LINE> <DEDENT> <DEDENT> def transfer_message(self, data): <NEW_LINE> <INDENT> compressed = zlib.compress(rencode.dumps(data)) <NEW_LINE> size_data = len(compressed) <NEW_LINE> header = b"D" + struct.pack("!i", size_data) <NEW_LINE> self.transport.write(header) <NEW_LINE> self.transport.write(compressed) <NEW_LINE> <DEDENT> def data_received(self, data): <NEW_LINE> <INDENT> self._buffer += data <NEW_LINE> while len(self._buffer) >= MESSAGE_HEADER_SIZE: <NEW_LINE> <INDENT> if self._message_length == 0: <NEW_LINE> <INDENT> self._handle_new_message() <NEW_LINE> <DEDENT> if len(self._buffer) >= self._message_length: <NEW_LINE> <INDENT> self._handle_complete_message(self._buffer[:self._message_length]) <NEW_LINE> self._buffer = self._buffer[self._message_length:] <NEW_LINE> self._message_length = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _handle_new_message(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> header = self._buffer[:MESSAGE_HEADER_SIZE] <NEW_LINE> if not header.startswith(b"D"): <NEW_LINE> <INDENT> raise Exception("Invalid header format. First byte is %d" % header[0]) <NEW_LINE> <DEDENT> self._message_length = struct.unpack("!i", header[1:MESSAGE_HEADER_SIZE])[0] <NEW_LINE> if self._message_length < 0: <NEW_LINE> <INDENT> raise Exception("Message length is negative: %d" % self._message_length) <NEW_LINE> <DEDENT> self._buffer = self._buffer[MESSAGE_HEADER_SIZE:] <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> log.warn("Error occurred when parsing message header: %s.", ex) <NEW_LINE> log.warn("This version of Deluge cannot communicate with the sender of this data.") <NEW_LINE> self._message_length = 0 <NEW_LINE> self._buffer = b"" <NEW_LINE> raise <NEW_LINE> <DEDENT> <DEDENT> def _handle_complete_message(self, data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> message = rencode.loads(zlib.decompress(data), decode_utf8=True) <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> log.warn("Failed to decompress (%d bytes) and load serialized data with rencode: %s", len(data), ex) <NEW_LINE> return <NEW_LINE> <DEDENT> if type(message) is not tuple: <NEW_LINE> <INDENT> log.error("Received invalid message: type is not tuple") <NEW_LINE> return <NEW_LINE> <DEDENT> self.message_received(message) | Data messages are transferred using very a simple protocol.
Data messages are transferred with a header containing
the length of the data to be transferred (payload). | 62598f9bbaa26c4b54d4f052 |
class WelcomeHandler(Handler): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> user = self.user <NEW_LINE> if not user: <NEW_LINE> <INDENT> self.redirect("/login") <NEW_LINE> return <NEW_LINE> <DEDENT> self.render("welcome.html", username=user.username) | mapping for url ('/welcome') | 62598f9b3617ad0b5ee05ef0 |
class FastDFSStorage(Storage): <NEW_LINE> <INDENT> def _save(self, name, content, max_length=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _open(self, name, mode='rb'): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def url(self, name): <NEW_LINE> <INDENT> return 'http://image.meiduo.site:8888/' + name | 自定义文件存储系统 | 62598f9b0a50d4780f705178 |
class Unqlite(CMakePackage): <NEW_LINE> <INDENT> homepage = "https://unqlite.org/" <NEW_LINE> url = "https://github.com/symisc/unqlite/archive/v1.1.9.tar.gz" <NEW_LINE> git = 'https://github.com/symisc/unqlite.git' <NEW_LINE> version('master', branch='master') <NEW_LINE> version('1.1.9', sha256='33d5b5e7b2ca223942e77d31112d2e20512bc507808414451c8a98a7be5e15c0') <NEW_LINE> patch('0001-Removed-the-STATIC-key-word-to-enable-building-a-sha.patch', when='@1.1.9') <NEW_LINE> def cmake_args(self): <NEW_LINE> <INDENT> args = ["-DBUILD_SHARED_LIBS:BOOL=ON"] <NEW_LINE> return args | UnQLite is a in-process software library which implements a self-contained,
serverless, zero-configuration, transactional NoSQL database engine. | 62598f9b94891a1f408b95c1 |
@base <NEW_LINE> class CrossSectionStructureVT(VariableTree): <NEW_LINE> <INDENT> s = Float() <NEW_LINE> regions = List(desc='List of names of regions in the cross section') <NEW_LINE> webs = List(desc='List of names of regions in the cross section') <NEW_LINE> materials = Dict(desc='Dictionary of MaterialProps vartrees') <NEW_LINE> airfoil = VarTree(AirfoilShape(), desc='Cross sectional shape') <NEW_LINE> DPs = List(desc='Region division points (nregion + 1)') <NEW_LINE> def add_region(self, name): <NEW_LINE> <INDENT> self.add(name, VarTree(Region())) <NEW_LINE> self.regions.append(name) <NEW_LINE> return getattr(self, name) <NEW_LINE> <DEDENT> def add_web(self, name): <NEW_LINE> <INDENT> self.add(name, VarTree(Region())) <NEW_LINE> self.webs.append(name) <NEW_LINE> return getattr(self, name) <NEW_LINE> <DEDENT> def add_material(self, name, material): <NEW_LINE> <INDENT> if name in self.materials.keys(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.materials[name] = material <NEW_LINE> <DEDENT> return self.materials[name] | Container for a cross-sectional definition of the
internal structure of a blade. | 62598f9b4428ac0f6e6582cb |
class synapseModel(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.name = '' <NEW_LINE> self.srcname = '' <NEW_LINE> self.srcN = 0 <NEW_LINE> self.trgname = '' <NEW_LINE> self.trgN = 0 <NEW_LINE> self.N = 0 <NEW_LINE> self.variables = [] <NEW_LINE> self.variabletypes = [] <NEW_LINE> self.shared_variables = [] <NEW_LINE> self.shared_variabletypes = [] <NEW_LINE> self.variablescope = dict() <NEW_LINE> self.external_variables = [] <NEW_LINE> self.parameters = [] <NEW_LINE> self.pvalue = [] <NEW_LINE> self.postSyntoCurrent = [] <NEW_LINE> self.main_code_lines = defaultdict(str) <NEW_LINE> self.support_code_lines = defaultdict(str) <NEW_LINE> self.connectivity = '' <NEW_LINE> self.delay = 0 <NEW_LINE> self.summed_variables= None | Class that contains all relevant information about a synapse model. | 62598f9b627d3e7fe0e06c4b |
class AbstractRealTimeVisualizer(AbstractVisualizer): <NEW_LINE> <INDENT> X_SPACING = 1. <NEW_LINE> Z_SPACING = 1. <NEW_LINE> def __init__(self, simulation, axis): <NEW_LINE> <INDENT> super(AbstractRealTimeVisualizer, self).__init__(axis) <NEW_LINE> assert_is_type(simulation, Simulation) <NEW_LINE> self._sim = simulation <NEW_LINE> self._rewards = self._sim.get_rewards() <NEW_LINE> self._states = self._sim.get_states() <NEW_LINE> self._actions = self._sim.get_actions() <NEW_LINE> self._dt = self._sim.get_plant().get_time_step() <NEW_LINE> self._time_template = "time: {:.2f}s" <NEW_LINE> self._reward_template = "reward: {:+.1f}" <NEW_LINE> self.get_axis().autoscale(enable=False) <NEW_LINE> <DEDENT> def _key(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_n_steps(self): <NEW_LINE> <INDENT> return self._states.shape[1] <NEW_LINE> <DEDENT> def init_draw(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def animate(self, i): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> return am.FuncAnimation( self._figure, self.animate, frames=self.get_n_steps(), interval=self._dt * 1000, blit=False, init_func=self.init_draw() ) <NEW_LINE> <DEDENT> def save_movie(self, name, bitrate=2000, *args, **kwargs): <NEW_LINE> <INDENT> self.run().save( "{:s}{:s}.mp4".format(FIGURE_PATH, name), fps=int(1. / self._dt), bitrate=bitrate, *args, **kwargs ) | The AbstractRealTimeVisualizer is a class for visualizing motion and animating objects. It can create movies from
Simulations and static plots containing frozen moments of an animation. | 62598f9b8da39b475be02f84 |
class RequestController: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.dispatcher = Dispatcher() <NEW_LINE> <DEDENT> def dispatch_request(self, request): <NEW_LINE> <INDENT> if isinstance(request, Request): <NEW_LINE> <INDENT> self.dispatcher.dispatch(request) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("request must be a Request object") | front controller | 62598f9b8da39b475be02f85 |
@implementer(IStep) <NEW_LINE> @attributes(['server_config']) <NEW_LINE> class CreateServer(object): <NEW_LINE> <INDENT> def as_effect(self): <NEW_LINE> <INDENT> eff = Effect(Func(generate_server_name)) <NEW_LINE> def got_name(random_name): <NEW_LINE> <INDENT> server_config = set_server_name(self.server_config, random_name) <NEW_LINE> return service_request( ServiceType.CLOUD_SERVERS, 'POST', 'servers', data=thaw(server_config), success_pred=has_code(202)) <NEW_LINE> <DEDENT> def report_success(result): <NEW_LINE> <INDENT> return StepResult.SUCCESS, [] <NEW_LINE> <DEDENT> def report_failure(result): <NEW_LINE> <INDENT> return StepResult.RETRY, [] <NEW_LINE> <DEDENT> return eff.on(got_name).on(success=report_success, error=report_failure) | A server must be created.
:ivar pmap server_config: Nova launch configuration. | 62598f9bd486a94d0ba2bd75 |
class NodeTypeSyntaxError(Exception): <NEW_LINE> <INDENT> def __init__(self, message, lineno=None, name=None, filename=None): <NEW_LINE> <INDENT> self.message = message <NEW_LINE> self.lineno = lineno <NEW_LINE> self.name = name <NEW_LINE> self.filename = filename <NEW_LINE> self.source = None <NEW_LINE> super(Exception, self).__init__(message) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self.source is not None: <NEW_LINE> <INDENT> location = 'line %d' % self.lineno <NEW_LINE> name = self.filename or self.name <NEW_LINE> if name: <NEW_LINE> <INDENT> location = 'File "%s", %s' % (name, location) <NEW_LINE> <DEDENT> lines = [self.message, ' ' + location] <NEW_LINE> try: <NEW_LINE> <INDENT> line = self.source.splitlines()[self.lineno - 1] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> line = None <NEW_LINE> <DEDENT> if line: <NEW_LINE> <INDENT> lines.append(' ' + line.strip()) <NEW_LINE> <DEDENT> return u'\n'.join(lines) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.message | Raised to tell the user that there is a problem with the node type. | 62598f9b01c39578d7f12b1e |
class ListBox(QtWidgets.QListWidget): <NEW_LINE> <INDENT> LISTBOX_WIDTH = 100 <NEW_LINE> LISTBOX_HEIGHT = 250 <NEW_LINE> def __init__(self, parent=None): <NEW_LINE> <INDENT> super().__init__(parent=parent) <NEW_LINE> self.setMinimumSize(QtCore.QSize(self.LISTBOX_WIDTH, self.LISTBOX_HEIGHT)) <NEW_LINE> self.setSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding) <NEW_LINE> self.setSortingEnabled(True) <NEW_LINE> self.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) <NEW_LINE> <DEDENT> def move_item(self, item, target_list): <NEW_LINE> <INDENT> self.takeItem(self.row(item)) <NEW_LINE> target_list.addItem(item) <NEW_LINE> <DEDENT> def move_selected_items(self, target_list, callback=None): <NEW_LINE> <INDENT> for item in self.selectedItems(): <NEW_LINE> <INDENT> self.move_item(item, target_list) <NEW_LINE> <DEDENT> if callback: <NEW_LINE> <INDENT> callback() <NEW_LINE> <DEDENT> <DEDENT> def move_all_items(self, target_list, callback=None): <NEW_LINE> <INDENT> while self.count(): <NEW_LINE> <INDENT> self.move_item(self.item(0), target_list) <NEW_LINE> <DEDENT> if callback: <NEW_LINE> <INDENT> callback() <NEW_LINE> <DEDENT> <DEDENT> def all_items_data(self, role=QtCore.Qt.UserRole): <NEW_LINE> <INDENT> for index in range(self.count()): <NEW_LINE> <INDENT> yield self.item(index).data(role) | Standard list box for CAA image type selection dialog.
Keyword Arguments:
parent {[type]} -- Parent of the QListWidget object being created (default: {None}) | 62598f9ba17c0f6771d5bfdb |
class AndroidProcess(backends.Process): <NEW_LINE> <INDENT> def __init__(self, device, pid, name): <NEW_LINE> <INDENT> super(AndroidProcess, self).__init__(device, pid, name) <NEW_LINE> self._last_sys_stats = None <NEW_LINE> <DEDENT> def DumpMemoryMaps(self): <NEW_LINE> <INDENT> cmd = '%s %d' % (_MEMDUMP_PATH_ON_DEVICE, self.pid) <NEW_LINE> dump_out = self.device.underlying_device.RunShellCommand(cmd) <NEW_LINE> return memdump_parser.Parse(dump_out) <NEW_LINE> <DEDENT> def DumpNativeHeap(self): <NEW_LINE> <INDENT> dump_file_path = _DUMPHEAP_OUT_FILE_PATH % self.pid <NEW_LINE> cmd = 'am dumpheap -n %d %s' % (self.pid, dump_file_path) <NEW_LINE> self.device.underlying_device.RunShellCommand(cmd) <NEW_LINE> dump_out = self.device.underlying_device.old_interface.GetFileContents( dump_file_path) <NEW_LINE> self.device.underlying_device.RunShellCommand('rm %s' % dump_file_path) <NEW_LINE> return dumpheap_native_parser.Parse(dump_out) <NEW_LINE> <DEDENT> def GetStats(self): <NEW_LINE> <INDENT> cur_sys_stats = self.device.UpdateAndGetSystemStats() <NEW_LINE> old_sys_stats = self._last_sys_stats or cur_sys_stats <NEW_LINE> cur_proc_stats = cur_sys_stats['processes'].get(str(self.pid)) <NEW_LINE> old_proc_stats = old_sys_stats['processes'].get(str(self.pid)) <NEW_LINE> if (not cur_proc_stats or not old_proc_stats): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> run_time = (((cur_sys_stats['time']['ticks'] - cur_proc_stats['start_time']) / cur_sys_stats['time']['rate'])) <NEW_LINE> ticks = max(1, cur_sys_stats['time']['ticks'] - old_sys_stats['time']['ticks']) <NEW_LINE> cpu_usage = (100 * ((cur_proc_stats['user_time'] + cur_proc_stats['sys_time']) - (old_proc_stats['user_time'] + old_proc_stats['sys_time'])) / ticks) / len(cur_sys_stats['cpu']) <NEW_LINE> proc_stats = backends.ProcessStats( threads=cur_proc_stats['n_threads'], run_time=run_time, cpu_usage=cpu_usage, vm_rss=cur_proc_stats['vm_rss'], page_faults=( (cur_proc_stats['maj_faults'] + cur_proc_stats['min_faults']) - (old_proc_stats['maj_faults'] + old_proc_stats['min_faults']))) <NEW_LINE> self._last_sys_stats = cur_sys_stats <NEW_LINE> return proc_stats | Android-specific implementation of the core |Process| interface. | 62598f9bbaa26c4b54d4f053 |
class OverridePurge(argparse.Action): <NEW_LINE> <INDENT> def __call__(self, parser, namespace, values, option_string=None): <NEW_LINE> <INDENT> libspm.PURGE_PATHS = values <NEW_LINE> setattr(namespace, self.dest, values) | Override paths to be purged | 62598f9b3539df3088ecc056 |
class Message(models.Model): <NEW_LINE> <INDENT> uid = models.BigIntegerField(default=simpleflake, unique=True, db_index=True) <NEW_LINE> message = models.TextField() <NEW_LINE> image = models.CharField(choices=IMAGES, max_length=200) <NEW_LINE> created_date = models.DateTimeField(default=now) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return 'Message {} sent on {}'.format(self.uid, self.created_date.isoformat()) <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('message-detail', kwargs={'slug': self.slug}) <NEW_LINE> <DEDENT> def get_image_url(self): <NEW_LINE> <INDENT> return reverse('message-image', kwargs={'slug': self.slug}) <NEW_LINE> <DEDENT> def get_original_image_url(self): <NEW_LINE> <INDENT> return staticfiles_storage.url('img/kittens/{}'.format(self.image)) <NEW_LINE> <DEDENT> def get_download_url(self): <NEW_LINE> <INDENT> return '{}?download=png'.format(self.get_image_url()) <NEW_LINE> <DEDENT> @property <NEW_LINE> def slug(self): <NEW_LINE> <INDENT> return '{0:x}'.format(self.uid) <NEW_LINE> <DEDENT> def get_image(self): <NEW_LINE> <INDENT> image_path = finders.find('img/kittens/{}'.format(self.image)) <NEW_LINE> if image_path: <NEW_LINE> <INDENT> zip_stream = io.BytesIO() <NEW_LINE> zip_data = zipfile.ZipFile(zip_stream, mode='w') <NEW_LINE> zip_data.writestr('{}.asc'.format(self.slug), self.message) <NEW_LINE> zip_data.close() <NEW_LINE> zip_stream.seek(0) <NEW_LINE> return _FileStream([open(image_path, 'rb'), zip_stream]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | Encrypted message for a particular user. | 62598f9b29b78933be269fad |
class PackageDeleteTestCase(BaseTestGenerator): <NEW_LINE> <INDENT> scenarios = [ ('Fetch Package Node URL', dict( url='/browser/package/obj/')) ] <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> schema_info = parent_node_dict["schema"][-1] <NEW_LINE> self.schema_id = schema_info["schema_id"] <NEW_LINE> self.schema_name = schema_info["schema_name"] <NEW_LINE> self.db_name = parent_node_dict["database"][-1]["db_name"] <NEW_LINE> self.pkg_name= "pkg_%s" % str(uuid.uuid4())[1:4] <NEW_LINE> self.proc_name = "proc_%s" % str(uuid.uuid4())[1:4] <NEW_LINE> self.server_id = schema_info["server_id"] <NEW_LINE> self.db_id = schema_info["db_id"] <NEW_LINE> server_con = server_utils.connect_server(self, self.server_id) <NEW_LINE> if server_con: <NEW_LINE> <INDENT> if "type" in server_con["data"]: <NEW_LINE> <INDENT> if server_con["data"]["type"] == "pg": <NEW_LINE> <INDENT> message = "Packages are not supported by PG." <NEW_LINE> self.skipTest(message) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.package_id = package_utils.create_package(self.server, self.db_name, self.schema_name, self.pkg_name, self.proc_name) <NEW_LINE> <DEDENT> def runTest(self): <NEW_LINE> <INDENT> db_con = database_utils.connect_database(self, utils.SERVER_GROUP, self.server_id, self.db_id) <NEW_LINE> if not db_con["info"] == "Database connected.": <NEW_LINE> <INDENT> raise Exception("Could not connect to database.") <NEW_LINE> <DEDENT> schema_response = schema_utils.verify_schemas(self.server, self.db_name, self.schema_name) <NEW_LINE> if not schema_response: <NEW_LINE> <INDENT> raise Exception("Could not find the schema.") <NEW_LINE> <DEDENT> package_response = package_utils.verify_package(self.server, self.db_name, self.schema_name) <NEW_LINE> if not package_response: <NEW_LINE> <INDENT> raise Exception("Could not find the package.") <NEW_LINE> <DEDENT> delete_response = self.tester.delete( self.url + str(utils.SERVER_GROUP) + '/' + str(self.server_id) + '/' + str(self.db_id) + '/' + str(self.schema_id) + '/' + str(self.package_id), follow_redirects=True) <NEW_LINE> self.assertEquals(delete_response.status_code, 200) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> database_utils.disconnect_database(self, self.server_id, self.db_id) | This class will delete new package under test schema. | 62598f9b0a50d4780f705179 |
class WriteBatch(object): <NEW_LINE> <INDENT> def __init__(self, client): <NEW_LINE> <INDENT> self._client = client <NEW_LINE> self._write_pbs = [] <NEW_LINE> self.write_results = None <NEW_LINE> self.commit_time = None <NEW_LINE> <DEDENT> def _add_write_pbs(self, write_pbs): <NEW_LINE> <INDENT> self._write_pbs.extend(write_pbs) <NEW_LINE> <DEDENT> def create(self, reference, document_data): <NEW_LINE> <INDENT> write_pbs = _helpers.pbs_for_create(reference._document_path, document_data) <NEW_LINE> self._add_write_pbs(write_pbs) <NEW_LINE> <DEDENT> def set(self, reference, document_data, merge=False): <NEW_LINE> <INDENT> if merge is not False: <NEW_LINE> <INDENT> write_pbs = _helpers.pbs_for_set_with_merge( reference._document_path, document_data, merge ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> write_pbs = _helpers.pbs_for_set_no_merge( reference._document_path, document_data ) <NEW_LINE> <DEDENT> self._add_write_pbs(write_pbs) <NEW_LINE> <DEDENT> def update(self, reference, field_updates, option=None): <NEW_LINE> <INDENT> if option.__class__.__name__ == "ExistsOption": <NEW_LINE> <INDENT> raise ValueError("you must not pass an explicit write option to " "update.") <NEW_LINE> <DEDENT> write_pbs = _helpers.pbs_for_update( reference._document_path, field_updates, option ) <NEW_LINE> self._add_write_pbs(write_pbs) <NEW_LINE> <DEDENT> def delete(self, reference, option=None): <NEW_LINE> <INDENT> write_pb = _helpers.pb_for_delete(reference._document_path, option) <NEW_LINE> self._add_write_pbs([write_pb]) <NEW_LINE> <DEDENT> def commit(self): <NEW_LINE> <INDENT> commit_response = self._client._firestore_api.commit( self._client._database_string, self._write_pbs, transaction=None, metadata=self._client._rpc_metadata, ) <NEW_LINE> self._write_pbs = [] <NEW_LINE> self.write_results = results = list(commit_response.write_results) <NEW_LINE> self.commit_time = commit_response.commit_time <NEW_LINE> return results <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_value, traceback): <NEW_LINE> <INDENT> if exc_type is None: <NEW_LINE> <INDENT> self.commit() | Accumulate write operations to be sent in a batch.
This has the same set of methods for write operations that
:class:`~.firestore_v1beta1.document.DocumentReference` does,
e.g. :meth:`~.firestore_v1beta1.document.DocumentReference.create`.
Args:
client (~.firestore_v1beta1.client.Client): The client that
created this batch. | 62598f9b07f4c71912baf1eb |
class ConditionStage(backboneelement.BackboneElement): <NEW_LINE> <INDENT> resource_type = Field("ConditionStage", const=True) <NEW_LINE> assessment: typing.List[fhirtypes.ReferenceType] = Field( None, alias="assessment", title="Formal record of assessment", description=( "Reference to a formal record of the evidence on which the staging " "assessment is based." ), element_property=True, enum_reference_types=["ClinicalImpression", "DiagnosticReport", "Observation"], ) <NEW_LINE> summary: fhirtypes.CodeableConceptType = Field( None, alias="summary", title="Simple summary (disease specific)", description=( 'A simple summary of the stage such as "Stage 3". The determination of ' "the stage is disease-specific." ), element_property=True, ) <NEW_LINE> @classmethod <NEW_LINE> def elements_sequence(cls): <NEW_LINE> <INDENT> return ["id", "extension", "modifierExtension", "summary", "assessment"] | Disclaimer: Any field name ends with ``__ext`` doesn't part of
Resource StructureDefinition, instead used to enable Extensibility feature
for FHIR Primitive Data Types.
Stage/grade, usually assessed formally.
Clinical stage or grade of a condition. May include formal severity
assessments. | 62598f9bfff4ab517ebcd58e |
class ShowMenu(InclusionTag): <NEW_LINE> <INDENT> name = 'show_menu' <NEW_LINE> template = 'menu/dummy.html' <NEW_LINE> options = Options( IntegerArgument('from_level', default=0, required=False), IntegerArgument('to_level', default=100, required=False), IntegerArgument('extra_inactive', default=0, required=False), IntegerArgument('extra_active', default=1000, required=False), Argument('template', default='menu/menu.html', required=False), Argument('namespace', default=None, required=False), Argument('root_id', default=None, required=False), Argument('next_page', default=None, required=False), ) <NEW_LINE> def get_context(self, context, from_level, to_level, extra_inactive, extra_active, template, namespace, root_id, next_page): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> request = context['request'] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return {'template': 'menu/empty.html'} <NEW_LINE> <DEDENT> if next_page: <NEW_LINE> <INDENT> children = next_page.children <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> nodes = menu_pool.get_nodes(request, namespace, root_id) <NEW_LINE> if root_id: <NEW_LINE> <INDENT> id_nodes = menu_pool.get_nodes_by_attribute(nodes, "reverse_id", root_id) <NEW_LINE> if id_nodes: <NEW_LINE> <INDENT> node = id_nodes[0] <NEW_LINE> nodes = node.children <NEW_LINE> for n in nodes: <NEW_LINE> <INDENT> n.parent = None <NEW_LINE> <DEDENT> from_level += node.level + 1 <NEW_LINE> to_level += node.level + 1 <NEW_LINE> nodes = flatten(nodes) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> nodes = [] <NEW_LINE> <DEDENT> <DEDENT> children = cut_levels(nodes, from_level, to_level, extra_inactive, extra_active) <NEW_LINE> children = menu_pool.apply_modifiers(children, request, namespace, root_id, post_cut=True) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> context.update({'children':children, 'template':template, 'from_level':from_level, 'to_level':to_level, 'extra_inactive':extra_inactive, 'extra_active':extra_active, 'namespace':namespace}) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> context = {"template":template} <NEW_LINE> <DEDENT> return context | render a nested list of all children of the pages
- from_level: starting level
- to_level: max level
- extra_inactive: how many levels should be rendered of the not active tree?
- extra_active: how deep should the children of the active node be rendered?
- namespace: the namespace of the menu. if empty will use all namespaces
- root_id: the id of the root node
- template: template used to render the menu | 62598f9b379a373c97d98db4 |
class Ontology(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.parse_obo() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Ontology handler." <NEW_LINE> <DEDENT> def parse_obo(self): <NEW_LINE> <INDENT> from pkg_resources import resource_stream <NEW_LINE> obo = parse_obo(resource_stream("alchemy", "data/chebi.obo")) <NEW_LINE> self.ontology = dict() <NEW_LINE> for entry in obo: <NEW_LINE> <INDENT> self.ontology[entry["id"]] = entry <NEW_LINE> <DEDENT> <DEDENT> @uniquify <NEW_LINE> def get_all_parents_classes(self, key): <NEW_LINE> <INDENT> if key not in self.ontology: <NEW_LINE> <INDENT> print("Warning. You're querying non-existant ChEBI ids! %s" % key) <NEW_LINE> return [] <NEW_LINE> <DEDENT> if "is_a" not in self.ontology[key]: <NEW_LINE> <INDENT> return [self.ontology[key]["name"]] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if type(self.ontology[key]["is_a"]) == list: <NEW_LINE> <INDENT> terms = [self.ontology[key]["name"]] <NEW_LINE> for term in self.ontology[key]["is_a"]: <NEW_LINE> <INDENT> terms += self.get_all_parents_classes(term) <NEW_LINE> <DEDENT> return terms <NEW_LINE> <DEDENT> elif type(self.ontology[key]["is_a"]) == str: <NEW_LINE> <INDENT> return [self.ontology[key]["name"]] + self.get_all_parents_classes(self.ontology[key]["is_a"]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @uniquify <NEW_LINE> def get_all_parent_roles(self, key): <NEW_LINE> <INDENT> import re <NEW_LINE> if key not in self.ontology: <NEW_LINE> <INDENT> print("Warning. You're querying non-existant ChEBI ids! %s" % key) <NEW_LINE> return [] <NEW_LINE> <DEDENT> if "relationship" not in self.ontology[key]: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if type(self.ontology[key]["relationship"]) == list: <NEW_LINE> <INDENT> terms = [] <NEW_LINE> for term in self.ontology[key]["relationship"]: <NEW_LINE> <INDENT> if "has_role " in term: <NEW_LINE> <INDENT> terms += self.get_all_parent_roles(re.sub("has_role ", "", term)) <NEW_LINE> <DEDENT> <DEDENT> return terms <NEW_LINE> <DEDENT> elif type(self.ontology[key]["relationship"]) == str: <NEW_LINE> <INDENT> term = self.ontology[key]["relationship"] <NEW_LINE> if "has_role " in term: <NEW_LINE> <INDENT> return self.get_all_parent_roles(re.sub("has_role ", "", term)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def get_all_classes(self): <NEW_LINE> <INDENT> all_terms = list() <NEW_LINE> for term in self.ontology.keys(): <NEW_LINE> <INDENT> all_terms += self.get_all_parents_classes(term) <NEW_LINE> <DEDENT> return all_terms <NEW_LINE> <DEDENT> def get_all_roles(self): <NEW_LINE> <INDENT> all_terms = list() <NEW_LINE> for term in self.ontology.keys(): <NEW_LINE> <INDENT> all_terms += self.get_all_parent_roles(term) <NEW_LINE> <DEDENT> return all_terms | Ontology handler for alchemy. | 62598f9bbe383301e0253598 |
class AuthenticationEntityManagerPlugin(colony.base.system.Plugin): <NEW_LINE> <INDENT> id = "pt.hive.colony.plugins.authentication.entity_manager" <NEW_LINE> name = "Authentication Entity Manager" <NEW_LINE> description = "Authentication Entity Manager Plugin" <NEW_LINE> version = "1.0.0" <NEW_LINE> author = "Hive Solutions Lda. <development@hive.pt>" <NEW_LINE> platforms = [ colony.base.system.CPYTHON_ENVIRONMENT ] <NEW_LINE> capabilities = [ "authentication_handler" ] <NEW_LINE> main_modules = [ "authentication.entity_manager.exceptions", "authentication.entity_manager.system" ] <NEW_LINE> authentication_entity_manager = None <NEW_LINE> def load_plugin(self): <NEW_LINE> <INDENT> colony.base.system.Plugin.load_plugin(self) <NEW_LINE> import authentication.entity_manager.system <NEW_LINE> self.authentication_entity_manager = authentication.entity_manager.system.AuthenticationEntityManager(self) <NEW_LINE> <DEDENT> def get_handler_name(self): <NEW_LINE> <INDENT> return self.authentication_entity_manager.get_handler_name() <NEW_LINE> <DEDENT> def handle_request(self, request): <NEW_LINE> <INDENT> return self.authentication_entity_manager.handle_request(request) | The main class for the Authentication Entity Manager plugin. | 62598f9b2ae34c7f260aae82 |
class WorkerThread(threading.Thread): <NEW_LINE> <INDENT> tombstone = object() <NEW_LINE> def __init__(self, conf, queue): <NEW_LINE> <INDENT> super(WorkerThread, self).__init__() <NEW_LINE> self.queue = queue <NEW_LINE> self.conf = conf <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> task = self.queue.get() <NEW_LINE> if task is self.tombstone: <NEW_LINE> <INDENT> self.queue.put(task) <NEW_LINE> break <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> for attempt in six.moves.range(self.conf.retries + 1): <NEW_LINE> <INDENT> if attempt > 0: <NEW_LINE> <INDENT> LOG.debug("Attempting to run task %s for the %s time", task.name, attempt + 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> LOG.debug("Attempting to run task %s for the first" " time", task.name) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> task.run() <NEW_LINE> if task.success: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> LOG.exception('Unhandled error when running %s', task.name) <NEW_LINE> <DEDENT> task.reset() <NEW_LINE> <DEDENT> if task.success: <NEW_LINE> <INDENT> for next_task in task.followups: <NEW_LINE> <INDENT> LOG.debug('Added next task %s to queue', next_task.name) <NEW_LINE> self.queue.put(next_task) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> self.queue.task_done() | Thread that executes tasks until the queue provides a tombstone. | 62598f9b3eb6a72ae038a3e0 |
class pipeline(object): <NEW_LINE> <INDENT> def __init__(self, *workers): <NEW_LINE> <INDENT> self.pipe = [] <NEW_LINE> self.connect(*workers) <NEW_LINE> <DEDENT> def __call__(self, next=null): <NEW_LINE> <INDENT> for worker in reversed(self.pipe): <NEW_LINE> <INDENT> next = worker(next=next) <NEW_LINE> <DEDENT> return next <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return linesep.join(repr(worker) for worker in self.pipe) or '<empty pipeline>' <NEW_LINE> <DEDENT> def connect(self, *workers): <NEW_LINE> <INDENT> self.pipe.extend(workers) <NEW_LINE> <DEDENT> def plug(self): <NEW_LINE> <INDENT> self.pipe.append(null) <NEW_LINE> <DEDENT> @contextmanager <NEW_LINE> def fork(self, worker, *pipes): <NEW_LINE> <INDENT> if isinstance(pipes[0], int): <NEW_LINE> <INDENT> pipe_count = pipes[0] <NEW_LINE> pipe_names = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pipe_count = len(pipes) <NEW_LINE> pipe_names = pipes <NEW_LINE> <DEDENT> pipes = tuple(pipeline() for i in range(pipe_count)) <NEW_LINE> yield pipes <NEW_LINE> if pipe_names: <NEW_LINE> <INDENT> self.connect(_fork(worker, **dict(zip(pipe_names, pipes)))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.connect(_fork(worker, *pipes)) <NEW_LINE> <DEDENT> <DEDENT> def feed(self, source): <NEW_LINE> <INDENT> p = self() <NEW_LINE> for item in source: <NEW_LINE> <INDENT> p.send(item) <NEW_LINE> <DEDENT> p.close() | Coroutine pipeline is utility class to connect number of coroutines into
single pipeline. The main goal is readability. The following examples
of code are equal:
.. code-block:: pycon
>>> @coroutine
... def collect(target, next=null):
... while True:
... item = yield
... target.append(item)
... next.send(item)
>>> @coroutine
... def increment(next=null):
... while True:
... item = yield
... next.send(item + 1)
>>> # Without pipelines
>>> result = []
>>> p = increment(collect(result))
>>> for i in [1, 2, 3]:
... p.send(i)
>>> p.close()
>>> # With pipelines
>>> result = []
>>> p = pipeline(
... increment,
... collect.params(result),
... )
>>> p.feed([1, 2, 3])
Pipeline also provides a readable representation, which is useful in debug:
.. code-block:: pycon
>>> p
increment
collect.params([2, 3, 4]) | 62598f9bb5575c28eb712b9d |
class BasicJobType(object): <NEW_LINE> <INDENT> def __init__(self, config, proxyfilename, logger, workingdir, crabserver, s3tester): <NEW_LINE> <INDENT> self.logger = logger <NEW_LINE> self.proxyfilename = proxyfilename <NEW_LINE> self.automaticAvail = False <NEW_LINE> self.crabserver = crabserver <NEW_LINE> self.s3tester = s3tester <NEW_LINE> if config: <NEW_LINE> <INDENT> valid, msg = self.validateConfig(config) <NEW_LINE> if valid: <NEW_LINE> <INDENT> self.config = config <NEW_LINE> self.workdir = workingdir <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> msg += "\nThe documentation about the CRAB configuration file can be found in" <NEW_LINE> msg += " https://twiki.cern.ch/twiki/bin/view/CMSPublic/CRAB3ConfigurationFile" <NEW_LINE> raise ConfigurationException(msg) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def run(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def validateConfig(self, config): <NEW_LINE> <INDENT> return True, "Valid configuration" <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def mergeLumis(inputdata): <NEW_LINE> <INDENT> mergedLumis = set() <NEW_LINE> for reports in inputdata.values(): <NEW_LINE> <INDENT> for report in reports: <NEW_LINE> <INDENT> for run, lumis in literal_eval(report['runlumi']).items(): <NEW_LINE> <INDENT> if isinstance(run, bytes): <NEW_LINE> <INDENT> run = run.decode(encoding='UTF-8') <NEW_LINE> <DEDENT> for lumi in lumis: <NEW_LINE> <INDENT> mergedLumis.add((run, int(lumi))) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> mergedLumis = LumiList(lumis=mergedLumis) <NEW_LINE> return mergedLumis.getCompactList() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def intersectLumis(lumisA, lumisB): <NEW_LINE> <INDENT> result = LumiList(compactList=lumisA) & LumiList(compactList=lumisB) <NEW_LINE> return result.getCompactList() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def subtractLumis(lumisA, lumisB): <NEW_LINE> <INDENT> result = LumiList(compactList=lumisA) - LumiList(compactList=lumisB) <NEW_LINE> return result.getCompactList() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def getDuplicateLumis(lumisDict): <NEW_LINE> <INDENT> doubleLumis = set() <NEW_LINE> for run, lumis in lumisDict.items(): <NEW_LINE> <INDENT> seen = set() <NEW_LINE> doubleLumis.update(set((run, lumi) for lumi in lumis if (run, lumi) in seen or seen.add((run, lumi)))) <NEW_LINE> <DEDENT> doubleLumis = LumiList(lumis=doubleLumis) <NEW_LINE> return doubleLumis.getCompactList() | BasicJobType
TODO: thinking on having a job type help here... | 62598f9bb7558d58954633cf |
class COLS: <NEW_LINE> <INDENT> ID = 0 <NEW_LINE> VALUE_1 = 2 <NEW_LINE> VALUE_2 = 3 <NEW_LINE> VALUE_3 = 4 <NEW_LINE> VALUE_4 = 5 <NEW_LINE> VALUE_5 = 6 | WARNING: These constants must match the zero-based column indexes in the spreadsheet.
If they don't, then the wrong data will be harvested and inserted into the database. | 62598f9b6fb2d068a7693d04 |
class ControlPanelAdapter(SchemaAdapterBase): <NEW_LINE> <INDENT> implements(ISettings) <NEW_LINE> def __init__(self, context): <NEW_LINE> <INDENT> super(ControlPanelAdapter, self).__init__(context) <NEW_LINE> self._settings = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def settings(self): <NEW_LINE> <INDENT> if self._settings is None: <NEW_LINE> <INDENT> self._settings = queryUtility( IRegistry).forInterface(ISettings, False) <NEW_LINE> <DEDENT> return self._settings <NEW_LINE> <DEDENT> @property <NEW_LINE> def portalTypes(self): <NEW_LINE> <INDENT> name = u"portalTypes" <NEW_LINE> return getattr(self.settings, name, ISettings[name].default) <NEW_LINE> <DEDENT> @portalTypes.setter <NEW_LINE> def portalTypes(self, value): <NEW_LINE> <INDENT> self.settings.portalTypes = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def autoSync(self): <NEW_LINE> <INDENT> name = u"autoSync" <NEW_LINE> return getattr(self.settings, name, ISettings[name].default) <NEW_LINE> <DEDENT> @autoSync.setter <NEW_LINE> def autoSync(self, value): <NEW_LINE> <INDENT> self.settings.autoSync = value <NEW_LINE> <DEDENT> def disabled(self, obj): <NEW_LINE> <INDENT> ctype = getattr(obj, 'portal_type', '') <NEW_LINE> if ctype not in self.portalTypes: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | Form adapter
| 62598f9b1f5feb6acb1629c3 |
class AlbumManager(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._model = None <NEW_LINE> self._albums = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def model(self): <NEW_LINE> <INDENT> if not self._model: <NEW_LINE> <INDENT> self._model = self._get_model() <NEW_LINE> <DEDENT> return self._model <NEW_LINE> <DEDENT> @property <NEW_LINE> def albums(self): <NEW_LINE> <INDENT> return self.get_album_list() <NEW_LINE> <DEDENT> def _get_model(self): <NEW_LINE> <INDENT> from picview.models import Album <NEW_LINE> return Album <NEW_LINE> <DEDENT> def get(self, slug): <NEW_LINE> <INDENT> album = cache.get('album-%s' % slug) <NEW_LINE> if album: <NEW_LINE> <INDENT> logger.debug('got album from cache: %s', album) <NEW_LINE> return album <NEW_LINE> <DEDENT> for album in self.albums: <NEW_LINE> <INDENT> if album.slug == slug: <NEW_LINE> <INDENT> return album <NEW_LINE> <DEDENT> <DEDENT> raise Exception('Could not find Album with slug %s' % slug) <NEW_LINE> <DEDENT> def all(self): <NEW_LINE> <INDENT> return self.albums <NEW_LINE> <DEDENT> def get_album_list(self): <NEW_LINE> <INDENT> album_list = cache.get('album-list') <NEW_LINE> if album_list: <NEW_LINE> <INDENT> return album_list <NEW_LINE> <DEDENT> pic_dir = settings.PICVIEW_DIR <NEW_LINE> album_names = os.listdir(pic_dir) <NEW_LINE> logger.debug('album names: %s', album_names) <NEW_LINE> album_list = [] <NEW_LINE> for album_name in sorted(album_names, reverse=True): <NEW_LINE> <INDENT> if ( album_name[0] == '.' or not os.path.isdir(os.path.join(pic_dir, album_name)) ): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> album_list.append(self.model(name=album_name)) <NEW_LINE> <DEDENT> cache.set('album-list', album_list, 30) <NEW_LINE> return album_list | A fake manager | 62598f9b55399d3f056262c2 |
class SetData(base.InnerModel): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> manager = SetDataManager | Represents the ``data`` property of a :py:class:`koordinates.client.Client` instance. | 62598f9b442bda511e95c204 |
class Interpolation(BaseEstimator, DataPreprocessorMixin): <NEW_LINE> <INDENT> def __init__(self, interpolation_model_name, data_type): <NEW_LINE> <INDENT> assert interpolation_model_name in ["linear", "quadratic", "cubic", "spline"] <NEW_LINE> assert data_type == "temporal" <NEW_LINE> self.interpolation_model_name = interpolation_model_name <NEW_LINE> self.median_imputation = None <NEW_LINE> <DEDENT> def fit(self, dataset): <NEW_LINE> <INDENT> if dataset.temporal_feature is not None: <NEW_LINE> <INDENT> self.median_imputation = BasicImputation(imputation_model_name="median", data_type="temporal") <NEW_LINE> self.median_imputation.fit(dataset) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def transform(self, dataset): <NEW_LINE> <INDENT> assert self.median_imputation is not None <NEW_LINE> if dataset.temporal_feature is not None: <NEW_LINE> <INDENT> dataset.temporal_feature = interpolation( dataset.temporal_feature, dataset.time, self.interpolation_model_name ) <NEW_LINE> dataset = self.median_imputation.transform(dataset) <NEW_LINE> <DEDENT> return dataset <NEW_LINE> <DEDENT> def fit_transform(self, dataset): <NEW_LINE> <INDENT> self.fit(dataset) <NEW_LINE> return self.transform(dataset) | Temporal data interpolation.
Attributes:
- interpolation_model_name: 'linear', 'quadratic', 'cubic', 'spline'
- data_type: 'temporal' | 62598f9bcc0a2c111447adad |
class ProjectionGraph(pg.GraphicsWindow): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self.setWindowTitle('Average of area') <NEW_LINE> self.setAntialiasing(True) <NEW_LINE> self.npoints = 400 <NEW_LINE> self.data = np.zeros(self.npoints) <NEW_LINE> self.ptr = 0 <NEW_LINE> self.statistics = pg.LabelItem(justify='right') <NEW_LINE> self.addItem(self.statistics) <NEW_LINE> self.statistics.setText('---') <NEW_LINE> self.plot = self.addPlot(row=1, col=0) <NEW_LINE> self.plot.setLabels(bottom=('Time', 's'), left=('Intensity', 'au')) <NEW_LINE> self.plot.showGrid(x=True, y=True) <NEW_LINE> self.sumCurve = self.plot.plot(pen='y') <NEW_LINE> self.startTime = ptime.time() <NEW_LINE> <DEDENT> def updateGraph(self, values): <NEW_LINE> <INDENT> self.data = values <NEW_LINE> self.sumCurve.setData(np.arange(len(self.data)), self.data) | The graph window class | 62598f9b7d43ff24874272d2 |
class BaseModel(object): <NEW_LINE> <INDENT> create_time = db.Column(db.DateTime, default=datetime.now) <NEW_LINE> update_time = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now) | Base Model | 62598f9b99cbb53fe6830c73 |
class PrimMST(object): <NEW_LINE> <INDENT> def __init__(self, G): <NEW_LINE> <INDENT> import heapq <NEW_LINE> self._mst = [] <NEW_LINE> edges = [] <NEW_LINE> heapq.heapify(edges) <NEW_LINE> visited = set() <NEW_LINE> v = 0 <NEW_LINE> while len(self._mst) < G.V-1: <NEW_LINE> <INDENT> for e in G.adj(v): <NEW_LINE> <INDENT> v1 = e.either() <NEW_LINE> v2 = e.other(v1) <NEW_LINE> if v1 not in visited and v2 not in visited: <NEW_LINE> <INDENT> heapq.heappush(edges, e) <NEW_LINE> <DEDENT> <DEDENT> visited.add(v) <NEW_LINE> while len(edges) > 0: <NEW_LINE> <INDENT> e = heapq.heappop(edges) <NEW_LINE> v1 = e.either() <NEW_LINE> v2 = e.other(v1) <NEW_LINE> if v1 not in visited or v2 not in visited: <NEW_LINE> <INDENT> self._mst.append(e) <NEW_LINE> v = v1 if v1 not in visited else v2 <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def edges(self): <NEW_LINE> <INDENT> return self._mst <NEW_LINE> <DEDENT> def weight(self): <NEW_LINE> <INDENT> return sum([e.weight for e in self.edges]) | Implementation of MST with Prim algoritm | 62598f9b3cc13d1c6d46550d |
class IncomingFriendshipsResultSet(ResultSet): <NEW_LINE> <INDENT> def getJSONFromString(self, str): <NEW_LINE> <INDENT> return json.loads(str) <NEW_LINE> <DEDENT> def get_Response(self): <NEW_LINE> <INDENT> return self._output.get('Response', None) | A ResultSet with methods tailored to the values returned by the IncomingFriendships Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution. | 62598f9b009cb60464d012c6 |
class reconcile(BaseUse): <NEW_LINE> <INDENT> def main(self, args, app): <NEW_LINE> <INDENT> params = self.get_params(args) <NEW_LINE> tool = ReconcileHistory(json.load(params.pop('infile'))) <NEW_LINE> return tool.reconciled_history | Reconcile record dependencies from a sequence of pump history
Tasks performed by this pass:
- Modifies temporary basal duration to account for cancelled and overlapping basals
- Duplicates and modifies temporary basal records to account for delivery pauses when suspended
| 62598f9bd53ae8145f91822f |
class EchoTCPRouterClient(threading.Thread): <NEW_LINE> <INDENT> def __init__(self, host): <NEW_LINE> <INDENT> threading.Thread.__init__(self) <NEW_LINE> self.daemon = True <NEW_LINE> self._conn = URTCPRouterConnection(host) <NEW_LINE> self._stop = False <NEW_LINE> self._q_start = None <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> while not self._stop: <NEW_LINE> <INDENT> q, qd = self._conn.get_actual() <NEW_LINE> if self._q_start is None: <NEW_LINE> <INDENT> self._q_start = q <NEW_LINE> <DEDENT> self._conn.set_q_desired(self._q_start) <NEW_LINE> <DEDENT> self._conn.disconnect() <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self._stop = True <NEW_LINE> self.join() | Echo client for the TCP Router. It stores the first received position
and commands this position to thr robot until stopped | 62598f9b63d6d428bbee2553 |
class SimpleVirus(object): <NEW_LINE> <INDENT> def __init__(self, maxBirthProb, clearProb): <NEW_LINE> <INDENT> self.maxBirthProb = maxBirthProb <NEW_LINE> self.clearProb = clearProb <NEW_LINE> <DEDENT> def doesClear(self): <NEW_LINE> <INDENT> if random.random() < self.clearProb: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def reproduce(self, popDensity): <NEW_LINE> <INDENT> reproduceProb = self.maxBirthProb * (1 - popDensity) <NEW_LINE> if random.random() < reproduceProb: <NEW_LINE> <INDENT> return SimpleVirus(self.maxBirthProb, self.clearProb) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NoChildException() | Representation of a simple virus (does not model drug effects/resistance). | 62598f9b435de62698e9bb96 |
class CfgEx(Exception): <NEW_LINE> <INDENT> def __init__(self, value): <NEW_LINE> <INDENT> super(CfgEx, self).__init__("<unavailable message>") <NEW_LINE> self.value = value <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return repr(self.value) | Configuration Exception.
Thrown in case of an invalid configuration. | 62598f9b460517430c431f2b |
class NuocaMPPlugin(IMultiprocessChildPlugin): <NEW_LINE> <INDENT> def __init__(self, parent_pipe, plugin_name, plugin_type): <NEW_LINE> <INDENT> nuoca_log(logging.INFO, "Creating plugin: %s" % plugin_name) <NEW_LINE> self._parent_pipe = parent_pipe <NEW_LINE> self._plugin_name = plugin_name <NEW_LINE> self._type = plugin_type <NEW_LINE> self._enabled = False <NEW_LINE> IMultiprocessChildPlugin.__init__(self, parent_pipe=parent_pipe) <NEW_LINE> <DEDENT> @property <NEW_LINE> def plugin_name(self): <NEW_LINE> <INDENT> return self._plugin_name <NEW_LINE> <DEDENT> @property <NEW_LINE> def type(self): <NEW_LINE> <INDENT> return self._type <NEW_LINE> <DEDENT> @property <NEW_LINE> def enabled(self): <NEW_LINE> <INDENT> return self._enabled <NEW_LINE> <DEDENT> @enabled.setter <NEW_LINE> def enabled(self, value): <NEW_LINE> <INDENT> self._enabled = value <NEW_LINE> <DEDENT> def activate(self): <NEW_LINE> <INDENT> nuoca_log(logging.INFO, "Activate plugin: %s" % self.name) <NEW_LINE> super(NuocaMPPlugin, self).activate() <NEW_LINE> self._enabled = True <NEW_LINE> <DEDENT> def startup(self, config): <NEW_LINE> <INDENT> raise NotImplementedError("Child class must implement startup method") <NEW_LINE> <DEDENT> def shutdown(self): <NEW_LINE> <INDENT> raise NotImplementedError("Child class must implement shutdown method") <NEW_LINE> <DEDENT> def deactivate(self): <NEW_LINE> <INDENT> nuoca_log(logging.INFO, "Deactivate plugin: %s" % self.name) <NEW_LINE> super(NuocaMPPlugin, self).deactivate() <NEW_LINE> self._enabled = False <NEW_LINE> <DEDENT> def has_required_config_items(self, config, required_config_items): <NEW_LINE> <INDENT> if not config: <NEW_LINE> <INDENT> nuoca_log(logging.ERROR, "%s plugin: missing config file." % self._plugin_name) <NEW_LINE> return False <NEW_LINE> <DEDENT> for config_item in required_config_items: <NEW_LINE> <INDENT> if config_item not in config: <NEW_LINE> <INDENT> nuoca_log(logging.ERROR, "%s plugin: '%s' missing from config." % (self._plugin_name, config_item)) <NEW_LINE> return False <NEW_LINE> <DEDENT> <DEDENT> return True | Base class for NuoCA Multi-Process Plugins
NuoCA plugins are based on Python Yapsy: http://yapsy.sourceforge.net/ | 62598f9b0a50d4780f70517a |
class SingleSwitchTopo(Topo): <NEW_LINE> <INDENT> def __init__(self, n=2, lossy=True, **opts): <NEW_LINE> <INDENT> Topo.__init__(self, **opts) <NEW_LINE> switch = self.addSwitch('s1') <NEW_LINE> for h in range(n): <NEW_LINE> <INDENT> host = self.addHost('h%s' % (h + 1), cpu=.5 / n) <NEW_LINE> if lossy: <NEW_LINE> <INDENT> self.addLink(host, switch, bw=10, delay='5ms', loss=10, use_htb=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.addLink(host, switch, bw=10, delay='5ms', loss=0, use_htb=True) | Single switch connected to n hosts. | 62598f9c4428ac0f6e6582cd |
class ShortThrower(ThrowerAnt): <NEW_LINE> <INDENT> min_range = 0 <NEW_LINE> max_range = 3 <NEW_LINE> name = 'Short' <NEW_LINE> food_cost = 3 <NEW_LINE> implemented = True | A ThrowerAnt that only throws leaves at Bees within 3 places. | 62598f9c45492302aabfc27a |
class ContainerInstanceManagementClient(object): <NEW_LINE> <INDENT> def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, base_url: Optional[str] = None, **kwargs: Any ) -> None: <NEW_LINE> <INDENT> if not base_url: <NEW_LINE> <INDENT> base_url = 'https://management.azure.com' <NEW_LINE> <DEDENT> self._config = ContainerInstanceManagementClientConfiguration(credential, subscription_id, **kwargs) <NEW_LINE> self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) <NEW_LINE> client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} <NEW_LINE> self._serialize = Serializer(client_models) <NEW_LINE> self._serialize.client_side_validation = False <NEW_LINE> self._deserialize = Deserializer(client_models) <NEW_LINE> self.container_groups = ContainerGroupsOperations( self._client, self._config, self._serialize, self._deserialize) <NEW_LINE> self.operations = Operations( self._client, self._config, self._serialize, self._deserialize) <NEW_LINE> self.location = LocationOperations( self._client, self._config, self._serialize, self._deserialize) <NEW_LINE> self.containers = ContainersOperations( self._client, self._config, self._serialize, self._deserialize) <NEW_LINE> <DEDENT> async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: <NEW_LINE> <INDENT> path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } <NEW_LINE> http_request.url = self._client.format_url(http_request.url, **path_format_arguments) <NEW_LINE> stream = kwargs.pop("stream", True) <NEW_LINE> pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) <NEW_LINE> return pipeline_response.http_response <NEW_LINE> <DEDENT> async def close(self) -> None: <NEW_LINE> <INDENT> await self._client.close() <NEW_LINE> <DEDENT> async def __aenter__(self) -> "ContainerInstanceManagementClient": <NEW_LINE> <INDENT> await self._client.__aenter__() <NEW_LINE> return self <NEW_LINE> <DEDENT> async def __aexit__(self, *exc_details) -> None: <NEW_LINE> <INDENT> await self._client.__aexit__(*exc_details) | ContainerInstanceManagementClient.
:ivar container_groups: ContainerGroupsOperations operations
:vartype container_groups: azure.mgmt.containerinstance.aio.operations.ContainerGroupsOperations
:ivar operations: Operations operations
:vartype operations: azure.mgmt.containerinstance.aio.operations.Operations
:ivar location: LocationOperations operations
:vartype location: azure.mgmt.containerinstance.aio.operations.LocationOperations
:ivar containers: ContainersOperations operations
:vartype containers: azure.mgmt.containerinstance.aio.operations.ContainersOperations
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.
:type subscription_id: str
:param str base_url: Service URL
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. | 62598f9cd6c5a102081e1ee6 |
class TopicPartChooseCallback(BaseTopicIntent, BaseCallbackIntent): <NEW_LINE> <INDENT> def get_keyboard(self): <NEW_LINE> <INDENT> return [ [InlineKeyboardButton(label, callback_data=value) for value, label in inftybot.topics.constants.TOPIC_PART_CHOIES], ] <NEW_LINE> <DEDENT> def handle(self, *args, **kwargs): <NEW_LINE> <INDENT> keyboard = self.get_keyboard() <NEW_LINE> topic = self.get_topic() <NEW_LINE> if not topic: <NEW_LINE> <INDENT> raise IntentHandleException("Can not resolve topic. Please, report it") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.update.callback_query.message.reply_text( render_topic(topic), parse_mode=ParseMode.MARKDOWN, ) <NEW_LINE> <DEDENT> self.update.callback_query.message.reply_text( _("What topic part do you want to edit?"), reply_markup=InlineKeyboardMarkup(keyboard) ) <NEW_LINE> return inftybot.topics.states.TOPIC_STATE_EDIT_INPUT | Choose topic part for edit | 62598f9c07f4c71912baf1ec |
class FillStyleExtended(ChoiceSwitch): <NEW_LINE> <INDENT> _icons = None <NEW_LINE> def __init__(self, setting, parent): <NEW_LINE> <INDENT> if self._icons is None: <NEW_LINE> <INDENT> self._generateIcons() <NEW_LINE> <DEDENT> ChoiceSwitch.__init__(self, setting, False, utils.extfillstyles, parent, icons=self._icons) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _generateIcons(cls): <NEW_LINE> <INDENT> from . import collections <NEW_LINE> brush = collections.BrushExtended("") <NEW_LINE> brush.color = 'black' <NEW_LINE> brush.patternspacing = '5pt' <NEW_LINE> brush.linewidth = '0.5pt' <NEW_LINE> size = 12 <NEW_LINE> cls._icons = icons = [] <NEW_LINE> path = qt4.QPainterPath() <NEW_LINE> path.addRect(0, 0, size, size) <NEW_LINE> for f in utils.extfillstyles: <NEW_LINE> <INDENT> pix = qt4.QPixmap(size, size) <NEW_LINE> pix.fill() <NEW_LINE> painter = qt4.QPainter(pix) <NEW_LINE> painter.pixperpt = 1. <NEW_LINE> painter.scaling = 1. <NEW_LINE> painter.setRenderHint(qt4.QPainter.Antialiasing) <NEW_LINE> brush.style = f <NEW_LINE> utils.brushExtFillPath(painter, brush, path) <NEW_LINE> painter.end() <NEW_LINE> icons.append( qt4.QIcon(pix) ) | Extended fill style list. | 62598f9c8e71fb1e983bb857 |
class Document(object): <NEW_LINE> <INDENT> def __init__(self,id,filename): <NEW_LINE> <INDENT> self.id = id <NEW_LINE> self.filename = filename <NEW_LINE> self.wordlist = self.get_words() <NEW_LINE> if self.wordlist: <NEW_LINE> <INDENT> self.wordlist = self.preprocess() <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.filename) <NEW_LINE> <DEDENT> def get_words(self): <NEW_LINE> <INDENT> words = [] <NEW_LINE> pubmed_dict = parser.parse_pubmed_xml(self.filename) <NEW_LINE> text = pubmed_dict['full_title'] + ' ' + pubmed_dict['abstract'] <NEW_LINE> pubmed_paras_dict = parser.parse_pubmed_paragraph(self.filename) <NEW_LINE> for paras in pubmed_paras_dict: <NEW_LINE> <INDENT> text = text + paras['text'] <NEW_LINE> <DEDENT> text = text.encode('ascii','replace').decode('ascii').replace('?',' ') <NEW_LINE> return text <NEW_LINE> <DEDENT> def preprocess(self): <NEW_LINE> <INDENT> CUSTOM_FILTERS = [lambda x: x.lower(),preprocessing.strip_tags,preprocessing.strip_punctuation,preprocessing.strip_multiple_whitespaces,preprocessing.strip_numeric,preprocessing.remove_stopwords,preprocessing.strip_short] <NEW_LINE> return preprocessing.preprocess_string(self.wordlist,CUSTOM_FILTERS) | Processes Pubmed OA nxml documents. pubmed_parser is used to parse the nxml files.
self.wordlist holds the individual word tokens. | 62598f9c7b25080760ed7247 |
class CrossRefs: <NEW_LINE> <INDENT> def __init__(self, id_index, crossref_markers): <NEW_LINE> <INDENT> self._index = id_index <NEW_LINE> self.markers = crossref_markers <NEW_LINE> <DEDENT> def _process_tag(self, tag, value): <NEW_LINE> <INDENT> if tag not in self.markers: <NEW_LINE> <INDENT> return tag, value <NEW_LINE> <DEDENT> refs = split_ids(value) <NEW_LINE> refs = [self._index.get(ref, ref) for ref in refs] <NEW_LINE> return tag, ' ; '.join(refs) <NEW_LINE> <DEDENT> def __call__(self, entry): <NEW_LINE> <INDENT> new_entry = copy.copy(entry) <NEW_LINE> new_entry.clear() <NEW_LINE> new_entry.extend(self._process_tag(tag, value) for tag, value in entry) <NEW_LINE> return new_entry | Visitor, which points cross references to new entry IDs. | 62598f9c1b99ca400228f3fe |
class AsrUra(luigi.WrapperTask): <NEW_LINE> <INDENT> def requires(self): <NEW_LINE> <INDENT> file = "asr_ura.json" <NEW_LINE> yield att.AsrTdrTable(file=file, table="db.abonent") <NEW_LINE> yield att.AsrAbonentTable(file=file, table="db.tdr") <NEW_LINE> yield att.AsrDeviceTable(file=file, table="db.device") <NEW_LINE> yield att.AsrAddressTable(file=file, table="db.address") <NEW_LINE> yield att.AsrBillTable(file=file, table="db.bill") <NEW_LINE> yield att.AsrPaymentTable(file=file, table="db.payment") <NEW_LINE> yield att.AsrSaldoTable(file=file, table="db.saldo") | Задание на выгрузку таблиц из АСР Уральска | 62598f9c6e29344779b003fd |
class Territory(models.Model): <NEW_LINE> <INDENT> id = models.CharField( max_length=100, null=False, unique=True, primary_key=True, editable=False, ) <NEW_LINE> name = models.CharField( max_length=50, null=False, ) <NEW_LINE> controlled_by_initial = models.ForeignKey( 'Nation', on_delete=models.CASCADE, null=True, related_name='initially_controlled_territories', ) <NEW_LINE> variant = models.ForeignKey( 'Variant', null=False, on_delete=models.CASCADE, related_name='territories', ) <NEW_LINE> nationality = models.ForeignKey( 'Nation', on_delete=models.CASCADE, null=True, blank=True, related_name='national_territories', ) <NEW_LINE> neighbours = models.ManyToManyField( 'self', symmetrical=True, blank=True, ) <NEW_LINE> shared_coasts = models.ManyToManyField( 'self', symmetrical=True, ) <NEW_LINE> type = models.CharField( max_length=10, choices=TerritoryType.CHOICES, blank=False, null=False, ) <NEW_LINE> supply_center = models.BooleanField(default=False) <NEW_LINE> initial_piece_type = models.CharField( max_length=50, null=True, choices=PieceType.CHOICES, ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> unique_together = ('name', 'variant') <NEW_LINE> verbose_name_plural = 'territories' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def state(self, turn): <NEW_LINE> <INDENT> return self.territory_states.get(turn=turn) <NEW_LINE> <DEDENT> def adjacent_to(self, territory): <NEW_LINE> <INDENT> return territory in self.neighbours.all() <NEW_LINE> <DEDENT> def shares_coast_with(self, territory): <NEW_LINE> <INDENT> return territory in self.shared_coasts.all() <NEW_LINE> <DEDENT> def get_piece(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.pieces.get(must_retreat=False) <NEW_LINE> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def is_coastal(self): <NEW_LINE> <INDENT> return self.type == TerritoryType.COASTAL <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_sea(self): <NEW_LINE> <INDENT> return self.type == TerritoryType.SEA <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_inland(self): <NEW_LINE> <INDENT> return self.type == TerritoryType.INLAND <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_complex(self): <NEW_LINE> <INDENT> return self.named_coasts.all().exists() | Represents an area in the game map that can be occupied. | 62598f9c10dbd63aa1c70958 |
class Operation(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'display': {'key': 'display', 'type': 'OperationDisplay'}, 'origin': {'key': 'origin', 'type': 'str'}, 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, 'service_specification': {'key': 'properties.serviceSpecification', 'type': 'ServiceSpecification'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(Operation, self).__init__(**kwargs) <NEW_LINE> self.name = kwargs.get('name', None) <NEW_LINE> self.display = kwargs.get('display', None) <NEW_LINE> self.origin = kwargs.get('origin', None) <NEW_LINE> self.is_data_action = kwargs.get('is_data_action', None) <NEW_LINE> self.service_specification = kwargs.get('service_specification', None) | Operations.
:param name: Name of the operation.
:type name: str
:param display: Properties displayed for the operation.
:type display: ~azure.mgmt.databoxedge.v2020_09_01.models.OperationDisplay
:param origin: Origin of the operation.
:type origin: str
:param is_data_action: Indicates whether the operation is a data action.
:type is_data_action: bool
:param service_specification: Service specification.
:type service_specification: ~azure.mgmt.databoxedge.v2020_09_01.models.ServiceSpecification | 62598f9c8c0ade5d55dc3560 |
class CultureCreateSchema(Schema): <NEW_LINE> <INDENT> name = fields.String(required=True) | POST /api/v1/cultures.
Format:
{
"name": "culture"
} | 62598f9c851cf427c66b806a |
class NotValidBGPPropagation(Exception): <NEW_LINE> <INDENT> def __init__(self, message): <NEW_LINE> <INDENT> super(NotValidBGPPropagation, self).__init__(message) | Raised when the requirements violates BGP's propagation rules | 62598f9cc432627299fa2d7a |
class Oracle(object): <NEW_LINE> <INDENT> def __init__(self, y): <NEW_LINE> <INDENT> self.y = y <NEW_LINE> <DEDENT> def pred(self, k, n): <NEW_LINE> <INDENT> return self.y[k:k+n].reshape((-1,1)) <NEW_LINE> <DEDENT> def real(self, k): <NEW_LINE> <INDENT> return self.y[k].reshape((-1,1)) | Perfect predictor of signal y
| 62598f9c29b78933be269fae |
class LogoutAPI(MethodView): <NEW_LINE> <INDENT> def post(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> token = request.headers.get('Authorization').split(' ')[-1] <NEW_LINE> blacklisted = Blacklist({'token': token}).blacklist_token() <NEW_LINE> if blacklisted: <NEW_LINE> <INDENT> response_object = { 'message': 'Logged out successfully.', } <NEW_LINE> return make_response(jsonify(response_object)), 200 <NEW_LINE> <DEDENT> response_object = { 'message': 'Invalid token.', } <NEW_LINE> return make_response(jsonify(response_object)), 401 <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> response_object = { 'message': 'Invalid token.', } <NEW_LINE> return make_response(jsonify(response_object)), 401 | Logout Resource | 62598f9c925a0f43d25e7ddf |
class RecordSpecificationElement( object ): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.recordID = 0 <NEW_LINE> self.recordSetSerialNumber = 0 <NEW_LINE> self.recordLength = 0 <NEW_LINE> self.recordCount = 0 <NEW_LINE> self.recordValues = 0 <NEW_LINE> self.pad4 = 0 <NEW_LINE> <DEDENT> def serialize(self, outputStream): <NEW_LINE> <INDENT> outputStream.write_unsigned_int(self.recordID); <NEW_LINE> outputStream.write_unsigned_int(self.recordSetSerialNumber); <NEW_LINE> outputStream.write_unsigned_short(self.recordLength); <NEW_LINE> outputStream.write_unsigned_short(self.recordCount); <NEW_LINE> outputStream.write_unsigned_short(self.recordValues); <NEW_LINE> outputStream.write_unsigned_byte(self.pad4); <NEW_LINE> <DEDENT> def parse(self, inputStream): <NEW_LINE> <INDENT> self.recordID = inputStream.read_unsigned_int(); <NEW_LINE> self.recordSetSerialNumber = inputStream.read_unsigned_int(); <NEW_LINE> self.recordLength = inputStream.read_unsigned_short(); <NEW_LINE> self.recordCount = inputStream.read_unsigned_short(); <NEW_LINE> self.recordValues = inputStream.read_unsigned_short(); <NEW_LINE> self.pad4 = inputStream.read_unsigned_byte(); | Synthetic record, made up from section 6.2.72. This is used to acheive a repeating variable list element. | 62598f9c6fb2d068a7693d05 |
class SandboxedTestCase(EmptyMrjobConfTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(SandboxedTestCase, self).setUp() <NEW_LINE> self.tmp_dir = mkdtemp() <NEW_LINE> self.addCleanup(rmtree, self.tmp_dir) <NEW_LINE> old_environ = os.environ.copy() <NEW_LINE> self.addCleanup(os.environ.update, old_environ) <NEW_LINE> self.addCleanup(os.environ.clear) <NEW_LINE> <DEDENT> def makedirs(self, path): <NEW_LINE> <INDENT> abs_path = os.path.join(self.tmp_dir, path) <NEW_LINE> if not os.path.isdir(abs_path): <NEW_LINE> <INDENT> os.makedirs(abs_path) <NEW_LINE> <DEDENT> return abs_path <NEW_LINE> <DEDENT> def makefile(self, path, contents=b'', executable=False): <NEW_LINE> <INDENT> self.makedirs(os.path.split(path)[0]) <NEW_LINE> abs_path = os.path.join(self.tmp_dir, path) <NEW_LINE> mode = 'wb' if isinstance(contents, bytes) else 'w' <NEW_LINE> with open(abs_path, mode) as f: <NEW_LINE> <INDENT> f.write(contents) <NEW_LINE> <DEDENT> if executable: <NEW_LINE> <INDENT> os.chmod(abs_path, os.stat(abs_path).st_mode | stat.S_IXUSR) <NEW_LINE> <DEDENT> return abs_path <NEW_LINE> <DEDENT> def abs_paths(self, *paths): <NEW_LINE> <INDENT> return [os.path.join(self.tmp_dir, path) for path in paths] <NEW_LINE> <DEDENT> def add_mrjob_to_pythonpath(self): <NEW_LINE> <INDENT> os.environ['PYTHONPATH'] = ( mrjob_pythonpath() + ':' + os.environ.get('PYTHONPATH', '')) | Patch mrjob.conf, create a temp directory, and save the environment for
each test | 62598f9c0c0af96317c56125 |
class TemplatedNaturalLanguageGenerator(NaturalLanguageGenerator): <NEW_LINE> <INDENT> def __init__(self, templates: Dict[Text, List[Dict[Text, Any]]]) -> None: <NEW_LINE> <INDENT> self.templates = templates <NEW_LINE> <DEDENT> def _random_template_for(self, utter_action: Text, output_channel: Text ) -> Optional[Dict[Text, Any]]: <NEW_LINE> <INDENT> import numpy as np <NEW_LINE> if utter_action in self.templates: <NEW_LINE> <INDENT> return np.random.choice(self.templates[utter_action]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> async def generate(self, template_name: Text, tracker: DialogueStateTracker, output_channel: Text, **kwargs: Any ) -> Optional[Dict[Text, Any]]: <NEW_LINE> <INDENT> filled_slots = tracker.current_slot_values() <NEW_LINE> return self.generate_from_slots(template_name, filled_slots, output_channel, **kwargs) <NEW_LINE> <DEDENT> def generate_from_slots(self, template_name: Text, filled_slots: Dict[Text, Any], output_channel: Text, **kwargs: Any ) -> Optional[Dict[Text, Any]]: <NEW_LINE> <INDENT> r = copy.deepcopy(self._random_template_for(template_name, output_channel)) <NEW_LINE> if r is not None: <NEW_LINE> <INDENT> return self._fill_template_text(r, filled_slots, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def _fill_template_text( self, template: Dict[Text, Any], filled_slots: Optional[Dict[Text, Any]] = None, **kwargs: Any ) -> Dict[Text, Any]: <NEW_LINE> <INDENT> template_vars = self._template_variables(filled_slots, kwargs) <NEW_LINE> if template_vars: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> text = re.sub(r'{([^\n]+?)}', r'{0[\1]}', template["text"]) <NEW_LINE> template["text"] = text.format(template_vars) <NEW_LINE> <DEDENT> except KeyError as e: <NEW_LINE> <INDENT> logger.exception( "Failed to fill utterance template '{}'. " "Tried to replace '{}' but could not find " "a value for it. There is no slot with this " "name nor did you pass the value explicitly " "when calling the template. Return template " "without filling the template. " "".format(template, e.args[0])) <NEW_LINE> <DEDENT> <DEDENT> return template <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _template_variables(filled_slots: Dict[Text, Any], kwargs: Dict[Text, Any]) -> Dict[Text, Any]: <NEW_LINE> <INDENT> if filled_slots is None: <NEW_LINE> <INDENT> filled_slots = {} <NEW_LINE> <DEDENT> template_vars = filled_slots.copy() <NEW_LINE> template_vars.update(kwargs) <NEW_LINE> return template_vars | Natural language generator that generates messages based on templates.
The templates can use variables to customize the utterances based on the
state of the dialogue. | 62598f9c507cdc57c63a4b38 |
class VendedorViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = Vendedor.objects.all().order_by('-id') <NEW_LINE> serializer_class = VendedorSerializer | API endpoint that allows users to be viewed or edited. | 62598f9c462c4b4f79dbb7ae |
class ESConfig(object): <NEW_LINE> <INDENT> config = None <NEW_LINE> @staticmethod <NEW_LINE> def get_instance(): <NEW_LINE> <INDENT> if ESConfig.config is None: <NEW_LINE> <INDENT> ESConfig.config = ESConfig("config.ini") <NEW_LINE> <DEDENT> return ESConfig.config <NEW_LINE> <DEDENT> def __init__(self, filename): <NEW_LINE> <INDENT> self.cfg = ConfigParser.ConfigParser() <NEW_LINE> self.file_name = filename <NEW_LINE> if not os.path.exists(filename): <NEW_LINE> <INDENT> self.cfg.add_section("global") <NEW_LINE> self.cfg.set("global","device_file", "") <NEW_LINE> self.sync2file() <NEW_LINE> <DEDENT> self.cfg.readfp(codecs.open(filename,"r",encoding="utf-8")) <NEW_LINE> <DEDENT> def get_device_file(self): <NEW_LINE> <INDENT> return self.cfg.get("global", "device_file") <NEW_LINE> <DEDENT> def set_device_file(self, file_name): <NEW_LINE> <INDENT> self.cfg.set("global", "device_file", file_name) <NEW_LINE> self.sync2file() <NEW_LINE> <DEDENT> def sync2file(self): <NEW_LINE> <INDENT> with codecs.open(self.file_name, "w", encoding="utf-8") as f: <NEW_LINE> <INDENT> self.cfg.write(f) | >>> config = ESConfig.get_instance()
>>> config.set_device_file(u"中文路径")
>>> config.get_device_file()
u'中文路径' | 62598f9cf8510a7c17d7e049 |
class HelperJobList(GenericJobList): <NEW_LINE> <INDENT> model = HelperJob <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.title = HelperJob._meta.verbose_name_plural | List all HelperJobs | 62598f9c63d6d428bbee2554 |
class JumpToFileCommand(sublime_plugin.TextCommand): <NEW_LINE> <INDENT> def run(self, edit): <NEW_LINE> <INDENT> ERROR_MESSAGE = "File '{0}' not found. Maybe path to source files " "in your settings is incorrect or file really absent" <NEW_LINE> SDL_LOG_SOURCE = "/sdl_core/src/" <NEW_LINE> FILE_NAME_WITHOUT_PATH_NAME = "(.+)(/|(] +))(.{0,}\\.(c|cc|h|cpp|hpp)):(\\d{1,})" <NEW_LINE> FULL_PATH_FILE = "(/.*)(/sdl_core/src/.{0,}\\.(c|cc|h|cpp|hpp)):(\\d{1,})" <NEW_LINE> primaryPath_exist = re.search( FULL_PATH_FILE, self.view.substr(self.view.line(self.view.sel()[0]))) <NEW_LINE> path_not_exist = re.search(FILE_NAME_WITHOUT_PATH_NAME, self.view.substr( self.view.line(self.view.sel()[0]))) <NEW_LINE> if primaryPath_exist: <NEW_LINE> <INDENT> path_to_file = primaryPath_exist.group( 1) + primaryPath_exist.group(2) <NEW_LINE> if path.isfile(path_to_file): <NEW_LINE> <INDENT> line = primaryPath_exist.group(4) <NEW_LINE> open_file(self, path_to_file, line, ERROR_MESSAGE.format(path_to_file)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> path_to_file = self.view.settings().get(SettingsTags.SOURCE_PATH) + primaryPath_exist.group(2) <NEW_LINE> line = primaryPath_exist.group(4) <NEW_LINE> open_file( self, path_to_file, line, ERROR_MESSAGE.format(path_to_file)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if self.view.settings().get(SettingsTags.SOURCE_PATH): <NEW_LINE> <INDENT> flagFind = False <NEW_LINE> file_name = path_not_exist.group(4) <NEW_LINE> path_to_file = self.view.settings().get( SettingsTags.SOURCE_PATH) + SDL_LOG_SOURCE <NEW_LINE> for root, dirnames, filenames in walk(path_to_file): <NEW_LINE> <INDENT> for filename in fnmatch.filter(filenames, file_name): <NEW_LINE> <INDENT> if filename: <NEW_LINE> <INDENT> flagFind = True <NEW_LINE> path_to_file = root + '/' + filename <NEW_LINE> line = path_not_exist.group(5) <NEW_LINE> open_file(self, path_to_file, line, ERROR_MESSAGE.format(path_to_file)) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if not flagFind: <NEW_LINE> <INDENT> sublime.error_message( ERROR_MESSAGE.format(file_name)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> file_name = path_not_exist.group(4) <NEW_LINE> sublime.error_message( ERROR_MESSAGE.format(file_name)) | Represents go to file. | 62598f9c55399d3f056262c4 |
class CSSPSrv(object): <NEW_LINE> <INDENT> def __init__(self ,listener,transport,target): <NEW_LINE> <INDENT> self.state=0 <NEW_LINE> self._listener=listener <NEW_LINE> self.transport=transport <NEW_LINE> self.wrapped=0 <NEW_LINE> self._relay=RPCRelayClient(target) <NEW_LINE> self._relay.init_connection() <NEW_LINE> self.recv=self.Recv <NEW_LINE> <DEDENT> def Recv(self,data,secFlags): <NEW_LINE> <INDENT> if len(data.buf)>255: <NEW_LINE> <INDENT> buff2='\x30\x82'+struct.pack('>H',len(data.buf))+data.buf <NEW_LINE> <DEDENT> elif len(data.buf)>=0x80: <NEW_LINE> <INDENT> buff2='\x30\x81'+chr(len(data.buf))+data.buf <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> buff2='\x30'+chr(len(data.buf))+data.buf <NEW_LINE> <DEDENT> tsreq = decodeDERTRequest(buff2) <NEW_LINE> if self.state==States.Final: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> negToken=str(tsreq['negoTokens'][0]['negoToken']) <NEW_LINE> if self.state==States.Krb0 or self.state==States.Krb1: <NEW_LINE> <INDENT> ret=self.HandleKrb(negToken) <NEW_LINE> pubKeyExists=False <NEW_LINE> try: <NEW_LINE> <INDENT> tsreq.getComponentByName('pubKeyAuth') <NEW_LINE> pubKeyExists=True <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> if pubKeyExists and tsreq['pubKeyAuth']!=None and tsreq['pubKeyAuth'].hasValue(): <NEW_LINE> <INDENT> cmd=str(tsreq['pubKeyAuth']) <NEW_LINE> self._relay.sendCmd(cmd) <NEW_LINE> self.state=States.Final <NEW_LINE> return <NEW_LINE> <DEDENT> self.state=States.Krb1 <NEW_LINE> if ret: <NEW_LINE> <INDENT> self.SendResp(ret) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> <DEDENT> def HandleKrb(self,negToken): <NEW_LINE> <INDENT> if self.state==States.Krb0: <NEW_LINE> <INDENT> resp,bind= self._relay.sendNegotiate(str(negToken)) <NEW_LINE> self.bind=(bind) <NEW_LINE> return resp <NEW_LINE> <DEDENT> if self.state==States.Krb1: <NEW_LINE> <INDENT> auth=self._relay.sendAuth(str(negToken),self.bind) <NEW_LINE> return auth <NEW_LINE> <DEDENT> <DEDENT> def SendResp(self,message): <NEW_LINE> <INDENT> t=encodeDERTRequest( negoTypes = [ message, ]) <NEW_LINE> t='\x30'+t[1:] <NEW_LINE> self.transport.write(type.String(t)) | @summary: Handle CSSP connection
Proxy class for authentication | 62598f9c442bda511e95c205 |
class ProcessCreator(ClassCreator): <NEW_LINE> <INDENT> def __init__( self, name, base='Process', template=None, members=None, procedures=None, author='KratosAppGenerator' ): <NEW_LINE> <INDENT> super(ProcessCreator, self).__init__( name, base, template, members, procedures, author ) | TO BE IMPLEMENTED | 62598f9c3d592f4c4edbac72 |
class TestCompareXLSXFiles(ExcelComparisonTest): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.maxDiff = None <NEW_LINE> filename = 'table07.xlsx' <NEW_LINE> test_dir = 'xlsxwriter/test/comparison/' <NEW_LINE> self.got_filename = test_dir + '_test_' + filename <NEW_LINE> self.exp_filename = test_dir + 'xlsx_files/' + filename <NEW_LINE> self.ignore_files = [] <NEW_LINE> self.ignore_elements = {} <NEW_LINE> <DEDENT> def test_create_file(self): <NEW_LINE> <INDENT> workbook = Workbook(self.got_filename) <NEW_LINE> worksheet = workbook.add_worksheet() <NEW_LINE> worksheet.set_column('C:F', 10.288) <NEW_LINE> worksheet.add_table('C3:F13', {'header_row': 0}) <NEW_LINE> worksheet.write('A1', 'Foo') <NEW_LINE> workbook.close() <NEW_LINE> self.assertExcelEqual() | Test file created by XlsxWriter against a file created by Excel. | 62598f9c4f6381625f19938e |
class Function(Field): <NEW_LINE> <INDENT> _CHECK_ATTRIBUTE = False <NEW_LINE> def __init__(self, serialize=None, deserialize=None, func=None, **kwargs): <NEW_LINE> <INDENT> if func: <NEW_LINE> <INDENT> warnings.warn('"func" argument of fields.Function is deprecated. ' 'Use the "serialize" argument instead.', RemovedInMarshmallow3Warning) <NEW_LINE> serialize = func <NEW_LINE> <DEDENT> super(Function, self).__init__(**kwargs) <NEW_LINE> self.serialize_func = self.func = serialize and utils.callable_or_raise(serialize) <NEW_LINE> self.deserialize_func = deserialize and utils.callable_or_raise(deserialize) <NEW_LINE> <DEDENT> def _serialize(self, value, attr, obj): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._call_or_raise(self.serialize_func, obj, attr) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return missing_ <NEW_LINE> <DEDENT> def _deserialize(self, value, attr, data): <NEW_LINE> <INDENT> if self.deserialize_func: <NEW_LINE> <INDENT> return self._call_or_raise(self.deserialize_func, value, attr) <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def _call_or_raise(self, func, value, attr): <NEW_LINE> <INDENT> if len(utils.get_func_args(func)) > 1: <NEW_LINE> <INDENT> if self.parent.context is None: <NEW_LINE> <INDENT> msg = 'No context available for Function field {0!r}'.format(attr) <NEW_LINE> raise ValidationError(msg) <NEW_LINE> <DEDENT> return func(value, self.parent.context) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return func(value) | A field that takes the value returned by a function.
:param callable serialize: A callable from which to retrieve the value.
The function must take a single argument ``obj`` which is the object
to be serialized. It can also optionally take a ``context`` argument,
which is a dictionary of context variables passed to the serializer.
If no callable is provided then the ```load_only``` flag will be set
to True.
:param callable deserialize: A callable from which to retrieve the value.
The function must take a single argument ``value`` which is the value
to be deserialized. It can also optionally take a ``context`` argument,
which is a dictionary of context variables passed to the deserializer.
If no callable is provided then ```value``` will be passed through
unchanged.
:param callable func: This argument is to be deprecated. It exists for
backwards compatiblity. Use serialize instead.
.. versionchanged:: 2.3.0
Deprecated ``func`` parameter in favor of ``serialize``. | 62598f9c45492302aabfc27b |
class Command(BaseCommand): <NEW_LINE> <INDENT> help = 'reparse all useragents. useful after updating python-ox' <NEW_LINE> args = '' <NEW_LINE> def handle(self, **options): <NEW_LINE> <INDENT> ids = [s['session_key'] for s in models.SessionData.objects.all().values('session_key')] <NEW_LINE> for i in ids: <NEW_LINE> <INDENT> s = models.SessionData.objects.get(pk=i) <NEW_LINE> s.parse_useragent() <NEW_LINE> s.save() | reparse all useragents. useful after updating python-ox | 62598f9cf7d966606f747d8b |
class OrganizationWithEndsAtByPlanSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> subscriptions = WithEndsAtByPlanSerializer( source='get_ends_at_by_plan', many=True, read_only=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = get_organization_model() <NEW_LINE> fields = ('slug', 'printable_name', 'created_at', 'email', 'subscriptions', ) <NEW_LINE> read_only_fields = ('slug', 'created_at') | Operational information on an Organization,
bundled with its active subscriptions. | 62598f9ca79ad16197769e07 |
class _EagerContext(threading.local): <NEW_LINE> <INDENT> def __init__(self, config=None): <NEW_LINE> <INDENT> super(_EagerContext, self).__init__() <NEW_LINE> self.device_spec = pydev.DeviceSpec.from_string("") <NEW_LINE> self.device_name = self.device_spec.to_string() <NEW_LINE> self.mode = default_execution_mode <NEW_LINE> self.is_eager = default_execution_mode == EAGER_MODE <NEW_LINE> self.scope_name = "" <NEW_LINE> self.recording_summaries = False <NEW_LINE> self.summary_writer_resource = None <NEW_LINE> self.scalar_cache = {} <NEW_LINE> self.ones_rank_cache = _EagerTensorCache() <NEW_LINE> self.zeros_cache = _EagerTensorCache() <NEW_LINE> self.execution_mode = None <NEW_LINE> base_config = rewriter_config_pb2.RewriterConfig() <NEW_LINE> base_config.function_optimization = rewriter_config_pb2.RewriterConfig.OFF <NEW_LINE> if config is not None and config.HasField( "graph_options") and config.graph_options.HasField("rewrite_options"): <NEW_LINE> <INDENT> base_config.Merge(config.graph_options.rewrite_options) <NEW_LINE> <DEDENT> self.rewriter_config = base_config.SerializeToString() | Thread local eager context. | 62598f9c21bff66bcd722a08 |
class FileLocked(Exception): <NEW_LINE> <INDENT> def __init__(self, filename, lockfilename): <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> self.lockfilename = lockfilename <NEW_LINE> super(FileLocked, self).__init__(filename, lockfilename) | File is already locked. | 62598f9c4e4d5625663721c7 |
@register <NEW_LINE> class MonitorEximQueue(Monitor): <NEW_LINE> <INDENT> monitor_type = "eximqueue" <NEW_LINE> max_length = 10 <NEW_LINE> r = re.compile(r"(?P<count>\d+) matches out of (?P<total>\d+) messages") <NEW_LINE> path = "/usr/local/sbin" <NEW_LINE> def __init__(self, name: str, config_options: dict) -> None: <NEW_LINE> <INDENT> super().__init__(name, config_options) <NEW_LINE> self.max_length = self.get_config_option( "max_length", required_type="int", minimum=1 ) <NEW_LINE> path = self.get_config_option("path", default="/usr/local/sbin") <NEW_LINE> self.path = os.path.join(path, "exiqgrep") <NEW_LINE> <DEDENT> def run_test(self) -> bool: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _output = subprocess.check_output([self.path, "-xc"]) <NEW_LINE> output = _output.decode("utf-8") <NEW_LINE> for line in output.splitlines(): <NEW_LINE> <INDENT> matches = self.r.match(line) <NEW_LINE> if matches: <NEW_LINE> <INDENT> count = int(matches.group("count")) <NEW_LINE> if count > self.max_length: <NEW_LINE> <INDENT> if count == 1: <NEW_LINE> <INDENT> return self.record_fail("%d message queued" % count) <NEW_LINE> <DEDENT> return self.record_fail("%d messages queued" % count) <NEW_LINE> <DEDENT> if count == 1: <NEW_LINE> <INDENT> return self.record_success("%d message queued" % count) <NEW_LINE> <DEDENT> return self.record_success("%d messages queued" % count) <NEW_LINE> <DEDENT> <DEDENT> return self.record_fail("Error getting queue size") <NEW_LINE> <DEDENT> except Exception as error: <NEW_LINE> <INDENT> return self.record_fail("Error running exiqgrep: %s" % error) <NEW_LINE> <DEDENT> <DEDENT> def describe(self) -> str: <NEW_LINE> <INDENT> return "Checking the exim queue length is < %d" % self.max_length <NEW_LINE> <DEDENT> def get_params(self) -> Tuple: <NEW_LINE> <INDENT> return (self.max_length,) | Make sure an exim queue isn't too big. | 62598f9cd6c5a102081e1ee8 |
class DyInfoDlg(QDialog): <NEW_LINE> <INDENT> def __init__(self, title, info, parent=None): <NEW_LINE> <INDENT> super().__init__(parent) <NEW_LINE> self.setWindowTitle(title) <NEW_LINE> self._initUi(info) <NEW_LINE> <DEDENT> def _initUi(self, info): <NEW_LINE> <INDENT> text = info <NEW_LINE> label = QLabel() <NEW_LINE> label.setText(text) <NEW_LINE> label.setMinimumWidth(500) <NEW_LINE> label.setFont(QFont('Courier New', 12)) <NEW_LINE> vbox = QVBoxLayout() <NEW_LINE> vbox.addWidget(label) <NEW_LINE> self.setLayout(vbox) | 显示信息 | 62598f9ca05bb46b3848a623 |
class RamlSecurityScheme(Model): <NEW_LINE> <INDENT> description = String() <NEW_LINE> type = String() <NEW_LINE> describedBy = Reference(RamlSecuritySchemeDescription) <NEW_LINE> settings = Map(String(), Or(String(), List(String()))) | http://raml.org/spec.html#security | 62598f9c6aa9bd52df0d4c71 |
class PyQuery(object): <NEW_LINE> <INDENT> def __init__(self, session, queryListener, log): <NEW_LINE> <INDENT> self.session = session <NEW_LINE> self.listener = queryListener <NEW_LINE> self.log = log <NEW_LINE> <DEDENT> def query(self, queryTopic=None, respondTopic=None): <NEW_LINE> <INDENT> if queryTopic is None or respondTopic is None: <NEW_LINE> <INDENT> self.log.error("queryTopic or respondTopic connot NULL") <NEW_LINE> return <NEW_LINE> <DEDENT> bo = QueryRequestBO_OTW() <NEW_LINE> bo.setQuerytopic(queryTopic) <NEW_LINE> bo.setTempTopic(respondTopic) <NEW_LINE> sender = self.session.sender("amq.topic/QueryTopic") <NEW_LINE> sender.send(Message(content=bo.getProBO().SerializeToString())) <NEW_LINE> receiver = self.session.receiver("amq.topic/" + respondTopic) <NEW_LINE> self.listener.init(receiver) <NEW_LINE> self.listener.onEvent() <NEW_LINE> self.session.acknowledge() | classdocs | 62598f9c097d151d1a2c0dca |
class KMaxPooling(Layer): <NEW_LINE> <INDENT> def __init__(self, k=2, **kwargs): <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> self.input_spec = InputSpec(ndim=3) <NEW_LINE> self.k = k <NEW_LINE> <DEDENT> def compute_output_shape(self, input_shape): <NEW_LINE> <INDENT> return (input_shape[0], (input_shape[2] * self.k)) <NEW_LINE> <DEDENT> def call(self, inputs): <NEW_LINE> <INDENT> shifted_input = tf.transpose(inputs, [0, 2, 1]) <NEW_LINE> top_k = tf.nn.top_k(shifted_input, k=self.k, sorted=True, name=None)[0] <NEW_LINE> return top_k | K-max pooling layer that extracts the k-highest activations from a sequence (2nd dimension).
TensorFlow backend. | 62598f9c67a9b606de545d6e |
class L3AddressContainer(Persistable): <NEW_LINE> <INDENT> __slots__ = ('container',) <NEW_LINE> def __init__ (self, container=None): <NEW_LINE> <INDENT> super(L3AddressContainer, self).__init__() <NEW_LINE> self.container = container if container is not None else [] <NEW_LINE> <DEDENT> def __getitem__ (self, id): <NEW_LINE> <INDENT> for l3 in self.container: <NEW_LINE> <INDENT> if l3.id == id: <NEW_LINE> <INDENT> return l3 <NEW_LINE> <DEDENT> <DEDENT> raise KeyError("L3 address with id: %s is not defined!" % id) <NEW_LINE> <DEDENT> def __iter__ (self): <NEW_LINE> <INDENT> return iter(self.container) <NEW_LINE> <DEDENT> def __len__ (self): <NEW_LINE> <INDENT> return len(self.container) <NEW_LINE> <DEDENT> def __contains__ (self, item): <NEW_LINE> <INDENT> if not isinstance(item, L3Address): <NEW_LINE> <INDENT> raise RuntimeError( "L3AddressContainer's operator \"in\" works only with L3Address " "objects (and not ID-s!)") <NEW_LINE> <DEDENT> return item in self.container <NEW_LINE> <DEDENT> def append (self, item): <NEW_LINE> <INDENT> self.container.append(item) <NEW_LINE> return item <NEW_LINE> <DEDENT> def remove (self, item): <NEW_LINE> <INDENT> return self.container.remove(item) <NEW_LINE> <DEDENT> def clear (self): <NEW_LINE> <INDENT> del self.container[:] <NEW_LINE> <DEDENT> def __str__ (self): <NEW_LINE> <INDENT> return str(self.container) <NEW_LINE> <DEDENT> def __repr__ (self): <NEW_LINE> <INDENT> return str(self) <NEW_LINE> <DEDENT> def add_l3address (self, id, name=None, configure=None, client=None, requested=None, provided=None): <NEW_LINE> <INDENT> self.container.append( L3Address(id, name=name, configure=configure, client=client, requested=requested, provided=provided)) <NEW_LINE> <DEDENT> def persist (self): <NEW_LINE> <INDENT> return [l3.persist() for l3 in self.container] <NEW_LINE> <DEDENT> def load (self, data, *args, **kwargs): <NEW_LINE> <INDENT> for item in data: <NEW_LINE> <INDENT> self.add_l3address(id=item['id'], name=item.get('name'), configure=item.get('configure'), client=item.get('client'), requested=item.get('requested'), provided=item.get('provided')) | Container class for storing L3 address data. | 62598f9c498bea3a75a578c4 |
class ProxychainsTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def test_proxychains(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.environ['http_proxy'] = '' <NEW_LINE> os.environ['https_proxy'] = '' <NEW_LINE> temp = tempfile.NamedTemporaryFile() <NEW_LINE> url = 'https://wtfismyip.com/text' <NEW_LINE> command = '{} wget -O {} -T {} "{}"'.format(PROXYCHAINS, temp.name, 10, url) <NEW_LINE> subprocess.call(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, shell=True) <NEW_LINE> with open(temp.name) as f: <NEW_LINE> <INDENT> self.assertTrue(ipaddress.ip_address(f.read().strip())) <NEW_LINE> <DEDENT> temp.close() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.fail('Error when calling proxychains') | Tests for proxychains. | 62598f9c627d3e7fe0e06c4f |
class IZCTextIndex(Interface): <NEW_LINE> <INDENT> pass | Persistent text index.
| 62598f9c30dc7b766599f5f1 |
class RGBColor (UIColor): <NEW_LINE> <INDENT> r = None <NEW_LINE> g = None <NEW_LINE> b = None <NEW_LINE> def __init__(self, r=None, g=None, b=None, rgb=None, color=None): <NEW_LINE> <INDENT> UIColor.__init__(self) <NEW_LINE> if color is not None: <NEW_LINE> <INDENT> r, g, b = color.get_rgb() <NEW_LINE> <DEDENT> if rgb is not None: <NEW_LINE> <INDENT> r, g, b = rgb <NEW_LINE> <DEDENT> self.r = r <NEW_LINE> self.g = g <NEW_LINE> self.b = b <NEW_LINE> assert self.r is not None <NEW_LINE> assert self.g is not None <NEW_LINE> assert self.b is not None <NEW_LINE> <DEDENT> def get_rgb(self): <NEW_LINE> <INDENT> return self.r, self.g, self.b <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<RGBColor r=%0.4f, g=%0.4f, b=%0.4f>" % (self.r, self.g, self.b) <NEW_LINE> <DEDENT> def interpolate(self, other, steps): <NEW_LINE> <INDENT> assert steps >= 3 <NEW_LINE> other = RGBColor(color=other) <NEW_LINE> for step in xrange(steps): <NEW_LINE> <INDENT> p = float(step) / (steps - 1) <NEW_LINE> r = self.r + (other.r - self.r) * p <NEW_LINE> g = self.g + (other.g - self.g) * p <NEW_LINE> b = self.b + (other.b - self.b) * p <NEW_LINE> yield RGBColor(r=r, g=g, b=b) <NEW_LINE> <DEDENT> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> t1 = self.get_rgb() <NEW_LINE> t2 = other.get_rgb() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return UIColor.__eq__(self, other) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> t1 = [round(c, 3) for c in t1] <NEW_LINE> t2 = [round(c, 3) for c in t2] <NEW_LINE> return t1 == t2 | Additive Red/Green/Blue representation of a color. | 62598f9c379a373c97d98db8 |
class BetaEmployeeLeaveDaysServiceServicer(object): <NEW_LINE> <INDENT> def EligibleForLeave(self, request, context): <NEW_LINE> <INDENT> context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) <NEW_LINE> <DEDENT> def grantLeave(self, request, context): <NEW_LINE> <INDENT> context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) | Service. define the methods that the grpc server can expose to the client.
| 62598f9ca79ad16197769e08 |
class NoOutputOnStdout(GlslCTest): <NEW_LINE> <INDENT> def check_no_output_on_stdout(self, status): <NEW_LINE> <INDENT> if status.stdout: <NEW_LINE> <INDENT> return False, 'Non empty stdout: {out}\n'.format(out=status.stdout) <NEW_LINE> <DEDENT> return True, '' | Mixin class for checking that there is no output on stdout. | 62598f9c442bda511e95c206 |
class SqlConnection: <NEW_LINE> <INDENT> def __init__(self, host, dbname, user, passw, port): <NEW_LINE> <INDENT> self.host = host <NEW_LINE> self.dbname = dbname <NEW_LINE> self.user = user <NEW_LINE> self.passw = passw <NEW_LINE> self.port = port <NEW_LINE> self.con_str = f'postgresql://{self.user}:{self.passw}@{self.host}:{self.port}/{self.dbname}' <NEW_LINE> <DEDENT> def sql_to_dataframe(self, query): <NEW_LINE> <INDENT> con = create_engine(self.con_str) <NEW_LINE> df = pd.read_sql_query(query,con=con) <NEW_LINE> return df | A connection class for a sql database. Define host, name of database, username, password and port. | 62598f9c99cbb53fe6830c76 |
class MonthlySingleDiseaseReportTest(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.input_file_name = "../data/2017.07.csv" <NEW_LINE> self.output_file_name = "../report/2017.07_diagnosis_report.txt" <NEW_LINE> self.data = MonthlySingleDiseaseReport( input_file_name=self.input_file_name, output_file_name=self.output_file_name) <NEW_LINE> <DEDENT> def test_get_head(self): <NEW_LINE> <INDENT> output_file_name = "../report/test_head.txt" <NEW_LINE> with open(output_file_name, "w") as output_object: <NEW_LINE> <INDENT> output_object.write(str(self.data._get_head())) <NEW_LINE> <DEDENT> output_object.close() <NEW_LINE> <DEDENT> def test_get_diagnosis_icd_counts(self): <NEW_LINE> <INDENT> output_file_name = "../report/test_diagnosis_counts.txt" <NEW_LINE> with open(output_file_name, "w") as output_object: <NEW_LINE> <INDENT> output_object.write(str(self.data._get_diagnosis_icd_counts())) <NEW_LINE> <DEDENT> output_object.close() <NEW_LINE> <DEDENT> def test_create_diagnosis(self): <NEW_LINE> <INDENT> with open(self.output_file_name, "w") as output_object: <NEW_LINE> <INDENT> output_object.write(str(self.data.create_diagnosis())) <NEW_LINE> <DEDENT> output_object.close() <NEW_LINE> <DEDENT> def test_create_ward(self): <NEW_LINE> <INDENT> self.data.pre_ward("../data/2017.07_day.csv") <NEW_LINE> self.data.create_ward(31.0, "../report/2017.07_wards.csv") | The test cases to test code in monthly.py. | 62598f9c3d592f4c4edbac74 |
class YoochooseBuys(YoochooseClicksOrBuys): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def from_csv(cls, filename = buys_filename): <NEW_LINE> <INDENT> return cls(pd.read_csv(filename, header = None, names = ['Session ID', 'Timestamp', 'Item ID', 'Price', 'Quantity'], parse_dates = [1])) | Data frame subclass for buy events. | 62598f9c56ac1b37e6301f8f |
class Topic(db.Model): <NEW_LINE> <INDENT> __tablename__ = "topic" <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> user_id = db.Column(db.Integer, db.ForeignKey('user.id')) <NEW_LINE> title = db.Column(db.String(64)) <NEW_LINE> body = db.Column(db.String(512)) <NEW_LINE> time = datetime.utcnow().strftime('%B %d %Y - %H:%M:%S') <NEW_LINE> timestamp = db.Column(db.String(100),default = time) <NEW_LINE> public = True <NEW_LINE> group_id = db.Column(db.Integer, db.ForeignKey('group.id')) <NEW_LINE> subscribers = db.relationship('User', secondary=subscription_identifier, backref='subscriptions', lazy='dynamic') <NEW_LINE> comments = db.relationship('Comment', backref='topic', lazy='dynamic') <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return '<Topic {}>'.format(self.title) | The table for storing the information about each topic | 62598f9c460517430c431f2d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.