code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class SaltRaetSetupMatcher(ioflo.base.deeding.Deed): <NEW_LINE> <INDENT> Ioinits = {'opts': salt.utils.stringutils.to_str('.salt.opts'), 'modules': salt.utils.stringutils.to_str('.salt.loader.modules'), 'matcher': salt.utils.stringutils.to_str('.salt.matcher')} <NEW_LINE> def action(self): <NEW_LINE> <INDENT> self.matcher.value = salt.minion.Matcher( self.opts.value, self.modules.value) | Make the matcher object | 6259902fd4950a0f3b111679 |
class ScalePreprocessing(Preprocessing): <NEW_LINE> <INDENT> def __init__(self, scale: float): <NEW_LINE> <INDENT> self.scale = scale <NEW_LINE> <DEDENT> def normalize(self, data): <NEW_LINE> <INDENT> return data * self.scale <NEW_LINE> <DEDENT> def denormalize(self, data): <NEW_LINE> <INDENT> return data / self.scale | Data preprocessing that scales (multiplies) the data by the given value. | 6259902f6e29344779b016c7 |
class WebCacheThread(threading.Thread): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.execute_queue = queue.Queue() <NEW_LINE> self.exception_queue = collections.defaultdict(functools.partial(queue.Queue, maxsize=1)) <NEW_LINE> self.result_queue = collections.defaultdict(functools.partial(queue.Queue, maxsize=1)) <NEW_LINE> super().__init__(name=__class__.__name__, daemon=True) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> thread_id, args, kwargs = self.execute_queue.get_nowait() <NEW_LINE> try: <NEW_LINE> <INDENT> cache_obj = WebCache(*args, **kwargs) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.exception_queue[thread_id].put_nowait(e) <NEW_LINE> loop = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> loop = True <NEW_LINE> <DEDENT> self.execute_queue.task_done() <NEW_LINE> while loop: <NEW_LINE> <INDENT> thread_id, method, args, kwargs = self.execute_queue.get() <NEW_LINE> try: <NEW_LINE> <INDENT> result = method(cache_obj, *args, **kwargs) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.exception_queue[thread_id].put_nowait(e) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.result_queue[thread_id].put_nowait(result) <NEW_LINE> <DEDENT> self.execute_queue.task_done() | Thread executing all sqlite3 calls for the ThreadedWebCache class. | 6259902f8e05c05ec3f6f697 |
class LoginHandler: <NEW_LINE> <INDENT> def __init__(self, header:dict, credentials:dict, targetUrl:str, filterTag:str, httpHandler:httplib2.Http, httpRequestType:str, debugPrint:bool): <NEW_LINE> <INDENT> self.header=header <NEW_LINE> self.credentials=credentials <NEW_LINE> self.targetUrl=targetUrl <NEW_LINE> self.filterTag=filterTag.strip() <NEW_LINE> self.requestType=httpRequestType <NEW_LINE> self.httpHandler=httpHandler <NEW_LINE> self.debugPrint=debugPrint <NEW_LINE> if(self.debugPrint): <NEW_LINE> <INDENT> print("Print args here") <NEW_LINE> <DEDENT> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.prepareRequest() <NEW_LINE> self.performRequest() <NEW_LINE> self.postProcessRequest() <NEW_LINE> <DEDENT> def getStatus(self): <NEW_LINE> <INDENT> return self.status <NEW_LINE> <DEDENT> def getCookie(self): <NEW_LINE> <INDENT> return self.cookie <NEW_LINE> <DEDENT> def isLoginSuccessfull(self): <NEW_LINE> <INDENT> return not (self.httpContent==None) <NEW_LINE> <DEDENT> def prepareRequest(self): <NEW_LINE> <INDENT> if(self.debugPrint): <NEW_LINE> <INDENT> print("Preprocess Request") <NEW_LINE> <DEDENT> self.body=self.credentials <NEW_LINE> return <NEW_LINE> <DEDENT> def performRequest(self): <NEW_LINE> <INDENT> http=self.httpHandler; <NEW_LINE> url = self.targetUrl <NEW_LINE> requestType=self.requestType <NEW_LINE> header=self.header <NEW_LINE> body=self.body <NEW_LINE> if(self.debugPrint): <NEW_LINE> <INDENT> print("HTTP Request to "+url) <NEW_LINE> <DEDENT> response, content = http.request(url, requestType, headers=header, body=urllib.parse.urlencode(body)) <NEW_LINE> if(self.debugPrint): <NEW_LINE> <INDENT> print("finished request: "+str(response.status)) <NEW_LINE> <DEDENT> self.httpResponse=response <NEW_LINE> self.httpContent=content <NEW_LINE> <DEDENT> def postProcessRequest(self): <NEW_LINE> <INDENT> if(self.debugPrint): <NEW_LINE> <INDENT> print("Postprocess Request") <NEW_LINE> print(self.httpResponse) <NEW_LINE> <DEDENT> content=self.httpContent.decode(encoding='utf-8') <NEW_LINE> response=self.httpResponse <NEW_LINE> if(response.status>=200 and response.status<=400): <NEW_LINE> <INDENT> self.status=response.status <NEW_LINE> <DEDENT> soup=BeautifulSoup(content, "html.parser") <NEW_LINE> warningInChallengeWrapper=soup.findAll('div', attrs={"class":"alert-danger"}) <NEW_LINE> if len(warningInChallengeWrapper)>0: <NEW_LINE> <INDENT> warning=warningInChallengeWrapper[0].contents <NEW_LINE> if "Login failed invalid" in str(warning): <NEW_LINE> <INDENT> self.httpContent=None <NEW_LINE> print(warning) <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> cookie=response['set-cookie'] <NEW_LINE> cookie=str(cookie).split(sep=';')[0] <NEW_LINE> if self.debugPrint: <NEW_LINE> <INDENT> print("request seems successfully") <NEW_LINE> print("cookie:"+cookie) <NEW_LINE> <DEDENT> self.header['Cookie']=cookie <NEW_LINE> self.cookie=cookie <NEW_LINE> self.httpContent=content <NEW_LINE> return | classdocs
This class does not do any I/O operations
It does not create a html file output. This can be done somewhere else
It's focus is on request handling
it's also designed to handle multiple request to the same target.
This can be defined in the "run" method. | 6259902f5e10d32532ce413f |
class EB_Gurobi(Tarball): <NEW_LINE> <INDENT> def install_step(self): <NEW_LINE> <INDENT> if self.cfg['license_file'] is None or not os.path.exists(self.cfg['license_file']): <NEW_LINE> <INDENT> raise EasyBuildError("No existing license file specified: %s", self.cfg['license_file']) <NEW_LINE> <DEDENT> super(EB_Gurobi, self).install_step() <NEW_LINE> copy_file(self.cfg['license_file'], os.path.join(self.installdir, 'gurobi.lic')) <NEW_LINE> <DEDENT> def sanity_check_step(self): <NEW_LINE> <INDENT> custom_paths = { 'files': ['bin/%s' % f for f in ['grbprobe', 'grbtune', 'gurobi_cl', 'gurobi.sh']], 'dirs': [], } <NEW_LINE> super(EB_Gurobi, self).sanity_check_step(custom_paths=custom_paths) <NEW_LINE> <DEDENT> def make_module_extra(self): <NEW_LINE> <INDENT> txt = super(EB_Gurobi, self).make_module_extra() <NEW_LINE> txt += self.module_generator.set_environment('GUROBI_HOME', self.installdir) <NEW_LINE> txt += self.module_generator.set_environment('GRB_LICENSE_FILE', os.path.join(self.installdir, 'gurobi.lic')) <NEW_LINE> return txt | Support for installing linux64 version of Gurobi. | 6259902f8c3a8732951f75d0 |
class AudioObjectEditForm(forms.Form): <NEW_LINE> <INDENT> collection = CollectionSuggestionField(required=True) <NEW_LINE> error_css_class = 'has-error' <NEW_LINE> required_css_class = 'required' <NEW_LINE> def __init__(self, data=None, instance=None, initial={}, **kwargs): <NEW_LINE> <INDENT> if instance is None: <NEW_LINE> <INDENT> mods_instance = None <NEW_LINE> st_instance = None <NEW_LINE> dt_instance = None <NEW_LINE> rights_instance = None <NEW_LINE> comment_instance = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mods_instance = instance.mods.content <NEW_LINE> st_instance = instance.sourcetech.content <NEW_LINE> dt_instance = instance.digitaltech.content <NEW_LINE> rights_instance = instance.rights.content <NEW_LINE> self.object_instance = instance <NEW_LINE> orig_initial = initial <NEW_LINE> initial = {} <NEW_LINE> if self.object_instance.collection: <NEW_LINE> <INDENT> initial['collection'] = str(self.object_instance.collection.uri) <NEW_LINE> <DEDENT> if self.object_instance.ark: <NEW_LINE> <INDENT> initial['identifier'] = self.object_instance.ark <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> initial['identifier'] = self.object_instance.pid + ' (PID)' <NEW_LINE> <DEDENT> initial.update(orig_initial) <NEW_LINE> <DEDENT> common_opts = {'data': data, 'initial': initial} <NEW_LINE> self.mods = ModsEditForm(instance=mods_instance, prefix='mods', **common_opts) <NEW_LINE> self.sourcetech = SourceTechForm(instance=st_instance, prefix='st', **common_opts) <NEW_LINE> self.digitaltech = DigitalTechForm(instance=dt_instance, prefix='dt', **common_opts) <NEW_LINE> self.rights = RightsForm(instance=rights_instance, prefix='rights', **common_opts) <NEW_LINE> self.comments = CommentForm( prefix='comments',**common_opts) <NEW_LINE> for form in ( self.mods, self.sourcetech, self.digitaltech, self.rights, self.comments ): <NEW_LINE> <INDENT> form.error_css_class = self.error_css_class <NEW_LINE> form.required_css_class = self.error_css_class <NEW_LINE> <DEDENT> super(AudioObjectEditForm, self).__init__(data=data, initial=initial) <NEW_LINE> <DEDENT> def is_valid(self): <NEW_LINE> <INDENT> return all(form.is_valid() for form in [ super(AudioObjectEditForm, self), self.mods, self.sourcetech, self.digitaltech, self.rights, self.comments, ]) <NEW_LINE> <DEDENT> def update_instance(self): <NEW_LINE> <INDENT> self.object_instance.mods.content = self.mods.update_instance() <NEW_LINE> if self.object_instance.mods.content.record_info: <NEW_LINE> <INDENT> self.object_instance.mods.content.record_info.change_date = str(datetime.now().isoformat()) <NEW_LINE> <DEDENT> self.object_instance.sourcetech.content = self.sourcetech.update_instance() <NEW_LINE> self.object_instance.digitaltech.content = self.digitaltech.update_instance() <NEW_LINE> self.object_instance.rights.content = self.rights.update_instance() <NEW_LINE> if hasattr(self, 'cleaned_data'): <NEW_LINE> <INDENT> if hasattr(self, 'object_instance'): <NEW_LINE> <INDENT> self.object_instance.collection = self.object_instance.get_object(self.cleaned_data['collection']) <NEW_LINE> <DEDENT> <DEDENT> return self.object_instance | :class:`~django.forms.Form` for metadata on an
:class:`~keep.audio.models.AudioObject`.
Takes an :class:`~keep.audio.models.AudioObject`. This stands in contrast
to a regular :class:`~eulxml.forms.XmlObjectForm`, which would
take an :class:`~eulxml.xmlmap.XmlObject`. This form edits a whole
:class:`~keep.audio.models.AudioObject` by editing multiple XML
datastreams (whose content are instances of :class:`~eulxml.xmlmap.XmlObject`),
with individual :class:`~eulxml.forms.XmlObjectForm` form instances
for each XML datastream. | 6259902f287bf620b6272c60 |
class Formats: <NEW_LINE> <INDENT> ISO_8601_DATETIME = '%Y-%m-%dT%H:%M:%S%z' <NEW_LINE> ISO_8601_DATE = '%Y-%m-%d' | Abstract data type containing commonly used datetime format strings | 6259902f66673b3332c31469 |
class BatchDeleteEntitiesRequest(proto.Message): <NEW_LINE> <INDENT> parent = proto.Field(proto.STRING, number=1,) <NEW_LINE> entity_values = proto.RepeatedField(proto.STRING, number=2,) <NEW_LINE> language_code = proto.Field(proto.STRING, number=3,) | The request message for
[EntityTypes.BatchDeleteEntities][google.cloud.dialogflow.v2beta1.EntityTypes.BatchDeleteEntities].
Attributes:
parent (str):
Required. The name of the entity type to delete entries for.
Supported formats:
- ``projects/<Project ID>/agent/entityTypes/<Entity Type ID>``
- ``projects/<Project ID>/locations/<Location ID>/agent/entityTypes/<Entity Type ID>``
entity_values (Sequence[str]):
Required. The reference ``values`` of the entities to
delete. Note that these are not fully-qualified names, i.e.
they don't start with ``projects/<Project ID>``.
language_code (str):
Optional. The language used to access language-specific
data. If not specified, the agent's default language is
used. For more information, see `Multilingual intent and
entity
data <https://cloud.google.com/dialogflow/docs/agents-multilingual#intent-entity>`__. | 6259902f9b70327d1c57fdfd |
class Subprocess: <NEW_LINE> <INDENT> def is_running(self): <NEW_LINE> <INDENT> return ( self.is_external() or hasattr(self, 'process') and self.process.returncode is None ) <NEW_LINE> <DEDENT> def is_external(self): <NEW_LINE> <INDENT> return getattr(self, 'external', False) <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> if self.is_running() and not self.is_external(): <NEW_LINE> <INDENT> super(Subprocess, self).stop() <NEW_LINE> self.process.terminate() <NEW_LINE> self.process.wait() <NEW_LINE> del self.process <NEW_LINE> <DEDENT> <DEDENT> @properties.NonDataProperty <NEW_LINE> def log_root(self): <NEW_LINE> <INDENT> var_log = os.path.join(sys.prefix, 'var', 'log').replace('/usr/var', '/var') <NEW_LINE> if not os.path.isdir(var_log): <NEW_LINE> <INDENT> os.makedirs(var_log) <NEW_LINE> <DEDENT> return var_log <NEW_LINE> <DEDENT> def get_log(self): <NEW_LINE> <INDENT> log_name = self.__class__.__name__ <NEW_LINE> log_filename = os.path.join(self.log_root, log_name) <NEW_LINE> log_file = open(log_filename, 'a') <NEW_LINE> self.log_reader = open(log_filename, 'r') <NEW_LINE> self.log_reader.seek(log_file.tell()) <NEW_LINE> return log_file <NEW_LINE> <DEDENT> def _get_more_data(self, file, timeout): <NEW_LINE> <INDENT> timeout = datetime.timedelta(seconds=timeout) <NEW_LINE> timer = Stopwatch() <NEW_LINE> while timer.split() < timeout: <NEW_LINE> <INDENT> data = file.read() <NEW_LINE> if data: <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> <DEDENT> raise RuntimeError("Timeout") <NEW_LINE> <DEDENT> def wait_for_pattern(self, pattern, timeout=5): <NEW_LINE> <INDENT> data = '' <NEW_LINE> pattern = re.compile(pattern) <NEW_LINE> while True: <NEW_LINE> <INDENT> self.assert_running() <NEW_LINE> data += self._get_more_data(self.log_reader, timeout) <NEW_LINE> res = pattern.search(data) <NEW_LINE> if res: <NEW_LINE> <INDENT> self.__dict__.update(res.groupdict()) <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def assert_running(self): <NEW_LINE> <INDENT> process_running = self.process.returncode is None <NEW_LINE> if not process_running: <NEW_LINE> <INDENT> raise RuntimeError("Process terminated") <NEW_LINE> <DEDENT> <DEDENT> class PortFree(Guard): <NEW_LINE> <INDENT> def __init__(self, port=None): <NEW_LINE> <INDENT> if port is not None: <NEW_LINE> <INDENT> warnings.warn( "Passing port to PortFree is deprecated", DeprecationWarning ) <NEW_LINE> <DEDENT> <DEDENT> def allowed(self, service, *args, **kwargs): <NEW_LINE> <INDENT> port_free = service.port_free(service.port) <NEW_LINE> if not port_free: <NEW_LINE> <INDENT> log.warning("%s already running on port %s", service, service.port) <NEW_LINE> service.external = True <NEW_LINE> <DEDENT> return port_free | Mix-in to handle common subprocess handling | 6259902f4e696a045264e65e |
class NumberRange(ISTNode): <NEW_LINE> <INDENT> __type__ = 'Range' <NEW_LINE> __name_field__ = '' <NEW_LINE> __value_field__ = '' <NEW_LINE> def __init__(self, always_visible=True): <NEW_LINE> <INDENT> super(NumberRange, self).__init__() <NEW_LINE> self.min = self.max = '' <NEW_LINE> self.always_visible = always_visible <NEW_LINE> <DEDENT> replacements = { '2147483647': 'INT32 MAX', '4294967295': 'UINT32 MAX', '-2147483647': 'INT32 MIN', '1.79769e+308': '+inf', '-1.79769e+308': '-inf', '': 'unknown range' } <NEW_LINE> def parse(self, o=[]): <NEW_LINE> <INDENT> self.min = o[0] if len(o) > 0 else '' <NEW_LINE> self.max = o[1] if len(o) > 1 else '' <NEW_LINE> return self <NEW_LINE> <DEDENT> def is_pointless(self): <NEW_LINE> <INDENT> return self._format() in ('[0, ]', '[, ]', '(-inf, +inf)') <NEW_LINE> <DEDENT> def _format(self): <NEW_LINE> <INDENT> min_value = self.replacements.get(str(self.min), str(self.min)) <NEW_LINE> max_value = self.replacements.get(str(self.max), str(self.max)) <NEW_LINE> l_brace = '(' if min_value.find('inf') != -1 else '[' <NEW_LINE> r_brace = ')' if max_value.find('inf') != -1 else ']' <NEW_LINE> return '{l_brace}{min_value}, {max_value}{r_brace}'.format( l_brace=l_brace, r_brace=r_brace, min_value=min_value, max_value=max_value) <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> return NumberRange(self.always_visible) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self._format() if self.always_visible or not self.is_pointless() else '' | Class representing simple number range | 6259902f1d351010ab8f4b91 |
class rand_int32_t(rand_int_t): <NEW_LINE> <INDENT> def __init__(self, i=0): <NEW_LINE> <INDENT> super().__init__(32, i) | Creates a random signed 32-bit attribute | 6259902f30c21e258be99885 |
class WidgetConnector(QObject): <NEW_LINE> <INDENT> dataChanged = pyqtSignal(bool) <NEW_LINE> def __init__(self, form, adaptor, prefix=""): <NEW_LINE> <INDENT> QObject.__init__(self) <NEW_LINE> self._adaptor = None <NEW_LINE> self._form = form <NEW_LINE> self._widget_prefix = prefix <NEW_LINE> self._object = None <NEW_LINE> self._mapping = [] <NEW_LINE> self.setAdaptor(adaptor) <NEW_LINE> <DEDENT> def load(self, object): <NEW_LINE> <INDENT> self._connectObject(object) <NEW_LINE> self.dataChanged.emit(False) <NEW_LINE> <DEDENT> def save(self, overwrite=False): <NEW_LINE> <INDENT> if self._object: <NEW_LINE> <INDENT> for link in self._mapping: <NEW_LINE> <INDENT> link.save(self._object, overwrite) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def connectedObject(self): <NEW_LINE> <INDENT> return self._object <NEW_LINE> <DEDENT> def isDirty(self): <NEW_LINE> <INDENT> if self._object: <NEW_LINE> <INDENT> for link in self._mapping: <NEW_LINE> <INDENT> if link.isDirty(): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def onDataChanged(self): <NEW_LINE> <INDENT> if self._object != None: <NEW_LINE> <INDENT> self.dataChanged.emit(self.isDirty()) <NEW_LINE> <DEDENT> <DEDENT> def setAdaptor(self, adaptor): <NEW_LINE> <INDENT> if adaptor == self._adaptor: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._adaptor = adaptor <NEW_LINE> self._object = None <NEW_LINE> self._mapping = [] <NEW_LINE> for widget in self._form.findChildren(QWidget): <NEW_LINE> <INDENT> attribute = widget.property("dataAttribute") <NEW_LINE> if not attribute and self._widget_prefix: <NEW_LINE> <INDENT> name = str(widget.objectName()) <NEW_LINE> if not name.startswith(self._widget_prefix): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> attribute = name[len(self._widget_prefix) :] <NEW_LINE> <DEDENT> if not attribute: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self._adaptor.getAttrDef(str(attribute)) <NEW_LINE> linker = Linkage(adaptor, attribute, widget) <NEW_LINE> self._mapping.append(linker) <NEW_LINE> linker.dataChanged.connect(self.onDataChanged) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _connectObject(self, object): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._object = None <NEW_LINE> for link in self._mapping: <NEW_LINE> <INDENT> link.load(object) <NEW_LINE> <DEDENT> self._object = object <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.object = None <NEW_LINE> raise | Mixin class for a widget to provide automatic connection with an
ORM base class from SqlAlchemy.
Interrogates the object to determine the field names, then attempts
to link each field with a child widget of the form with the same
name.
The LoadEntity function and SaveEntity functions provide the main
connection between the entity and the object. The IsDirty function
determines whether an entity has changed. | 6259902f8e05c05ec3f6f698 |
class WriteTenantNestedSerializer(object): <NEW_LINE> <INDENT> def __init__(self, name=None, slug=None): <NEW_LINE> <INDENT> self.swagger_types = { 'name': 'str', 'slug': 'str' } <NEW_LINE> self.attribute_map = { 'name': 'name', 'slug': 'slug' } <NEW_LINE> self._name = name <NEW_LINE> self._slug = slug <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> <DEDENT> @property <NEW_LINE> def slug(self): <NEW_LINE> <INDENT> return self._slug <NEW_LINE> <DEDENT> @slug.setter <NEW_LINE> def slug(self, slug): <NEW_LINE> <INDENT> self._slug = slug <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 6259902f30c21e258be99886 |
class EditScheduleStepTestCase(WgerEditTestCase): <NEW_LINE> <INDENT> object_class = ScheduleStep <NEW_LINE> url = 'manager:step:edit' <NEW_LINE> pk = 2 <NEW_LINE> data = {'workout': 1, 'duration': 8} | Tests editing a schedule | 6259902fc432627299fa406f |
class ThreadGenerateGarbage(ThreadBase): <NEW_LINE> <INDENT> def gen_key(self): <NEW_LINE> <INDENT> chars = string.ascii_lowercase + string.digits <NEW_LINE> return ''.join(random.choice(chars) for x in range(8)) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> while self.run: <NEW_LINE> <INDENT> time.sleep(1) <NEW_LINE> self.queue.put((self.gen_key(), random.randint(0, 1000), 'c')) | stat, value, type
c = counter, t = timer, g = gauge
(stat, x, type) | 6259902f8c3a8732951f75d2 |
class RecordingSampler(Sampler): <NEW_LINE> <INDENT> def __init__(self, metadata, random_state=None): <NEW_LINE> <INDENT> self.metadata = metadata <NEW_LINE> self.info = self._init_info(metadata) <NEW_LINE> self.rng = check_random_state(random_state) <NEW_LINE> <DEDENT> def _init_info(self, metadata, required_keys=None): <NEW_LINE> <INDENT> keys = [k for k in ['subject', 'session', 'run'] if k in self.metadata.columns] <NEW_LINE> if not keys: <NEW_LINE> <INDENT> raise ValueError( 'metadata must contain at least one of the following columns: ' 'subject, session or run.') <NEW_LINE> <DEDENT> if required_keys is not None: <NEW_LINE> <INDENT> missing_keys = [ k for k in required_keys if k not in self.metadata.columns] <NEW_LINE> if len(missing_keys) > 0: <NEW_LINE> <INDENT> raise ValueError( f'Columns {missing_keys} were not found in metadata.') <NEW_LINE> <DEDENT> keys += required_keys <NEW_LINE> <DEDENT> metadata = metadata.reset_index().rename( columns={'index': 'window_index'}) <NEW_LINE> info = metadata.reset_index().groupby(keys)[ ['index', 'i_start_in_trial']].agg(['unique']) <NEW_LINE> info.columns = info.columns.get_level_values(0) <NEW_LINE> return info <NEW_LINE> <DEDENT> def sample_recording(self): <NEW_LINE> <INDENT> return self.rng.choice(self.n_recordings) <NEW_LINE> <DEDENT> def sample_window(self, rec_ind=None): <NEW_LINE> <INDENT> if rec_ind is None: <NEW_LINE> <INDENT> rec_ind = self.sample_recording() <NEW_LINE> <DEDENT> win_ind = self.rng.choice(self.info.iloc[rec_ind]['index']) <NEW_LINE> return win_ind, rec_ind <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @property <NEW_LINE> def n_recordings(self): <NEW_LINE> <INDENT> return self.info.shape[0] | Base sampler simplifying sampling from recordings.
Parameters
----------
metadata : pd.DataFrame
DataFrame with at least one of {subject, session, run} columns for each
window in the BaseConcatDataset to sample examples from. Normally
obtained with `BaseConcatDataset.get_metadata()`. For instance,
`metadata.head()` might look like this:
i_window_in_trial i_start_in_trial i_stop_in_trial target subject session run
0 0 0 500 -1 4 session_T run_0
1 1 500 1000 -1 4 session_T run_0
2 2 1000 1500 -1 4 session_T run_0
3 3 1500 2000 -1 4 session_T run_0
4 4 2000 2500 -1 4 session_T run_0
random_state : np.RandomState | int | None
Random state.
Attributes
----------
info : pd.DataFrame
Series with MultiIndex index which contains the subject, session, run
and window indices information in an easily accessible structure for
quick sampling of windows.
n_recordings : int
Number of recordings available. | 6259902f3eb6a72ae038b6e1 |
class LakeShore336Device(Device): <NEW_LINE> <INDENT> loop1 = FormattedComponent( LakeShore336_LoopControl, "{self.prefix}", loop_number=1 ) <NEW_LINE> loop2 = FormattedComponent( LakeShore336_LoopControl, "{self.prefix}", loop_number=2 ) <NEW_LINE> loop3 = FormattedComponent( LakeShore336_LoopRO, "{self.prefix}", loop_number=3 ) <NEW_LINE> loop4 = FormattedComponent( LakeShore336_LoopRO, "{self.prefix}", loop_number=4 ) <NEW_LINE> scanning_rate = Component(EpicsSignal, "read.SCAN", kind="omitted") <NEW_LINE> process_record = Component(EpicsSignal, "read.PROC", kind="omitted") <NEW_LINE> read_all = Component(EpicsSignal, "readAll.PROC", kind="omitted") <NEW_LINE> serial = Component(AsynRecord, "serial", kind="omitted") | LakeShore 336 temperature controller.
- loop 1: temperature positioner AND heater, PID, & ramp controls
- loop 2: temperature positioner AND heater, PID, & ramp controls
- loop 3: temperature positioner
- loop 4: temperature positioner | 6259902f66673b3332c3146b |
class RemediationLevel(BaseEnum): <NEW_LINE> <INDENT> OFFICIAL_FIX = D("0.87") <NEW_LINE> TEMPORARY_FIX = D("0.90") <NEW_LINE> WORKAROUND = D("0.95") <NEW_LINE> UNAVAILABLE = D("1") <NEW_LINE> NOT_DEFINED = NotDefined(D("1")) <NEW_LINE> _vectors = { "of": "OFFICIAL_FIX", "tf": "TEMPORARY_FIX" } | Vector: RL | 6259902f1d351010ab8f4b92 |
class StructureDefinitionDifferential(backboneelement.BackboneElement): <NEW_LINE> <INDENT> resource_type = "StructureDefinitionDifferential" <NEW_LINE> def __init__(self, jsondict=None, strict=True): <NEW_LINE> <INDENT> self.element = None <NEW_LINE> super(StructureDefinitionDifferential, self).__init__(jsondict=jsondict, strict=strict) <NEW_LINE> <DEDENT> def elementProperties(self): <NEW_LINE> <INDENT> js = super(StructureDefinitionDifferential, self).elementProperties() <NEW_LINE> js.extend([ ("element", "element", elementdefinition.ElementDefinition, True, None, True), ]) <NEW_LINE> return js | Differential view of the structure.
A differential view is expressed relative to the base StructureDefinition -
a statement of differences that it applies. | 6259902f50485f2cf55dbff8 |
class MSVSProject: <NEW_LINE> <INDENT> def __init__(self, path, name = None, dependencies = None, guid = None, spec = None, build_file = None, config_platform_overrides = None, fixpath_prefix = None): <NEW_LINE> <INDENT> self.path = path <NEW_LINE> self.guid = guid <NEW_LINE> self.spec = spec <NEW_LINE> self.build_file = build_file <NEW_LINE> self.name = name or os.path.splitext(os.path.basename(path))[0] <NEW_LINE> self.dependencies = list(dependencies or []) <NEW_LINE> self.entry_type_guid = ENTRY_TYPE_GUIDS['project'] <NEW_LINE> if config_platform_overrides: <NEW_LINE> <INDENT> self.config_platform_overrides = config_platform_overrides <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.config_platform_overrides = {} <NEW_LINE> <DEDENT> self.fixpath_prefix = fixpath_prefix <NEW_LINE> <DEDENT> def set_dependencies(self, dependencies): <NEW_LINE> <INDENT> self.dependencies = list(dependencies or []) <NEW_LINE> <DEDENT> def get_guid(self): <NEW_LINE> <INDENT> if self.guid is None: <NEW_LINE> <INDENT> self.guid = MakeGuid(self.name) <NEW_LINE> <DEDENT> return self.guid | Visual Studio project. | 6259902fbe8e80087fbc00f7 |
class ModelEmbeddings(nn.Module): <NEW_LINE> <INDENT> def __init__(self, embed_size, vocab): <NEW_LINE> <INDENT> super(ModelEmbeddings, self).__init__() <NEW_LINE> self.embed_size = embed_size <NEW_LINE> self.source = None <NEW_LINE> self.target = None <NEW_LINE> src_pad_token_idx = vocab.src['<pad>'] <NEW_LINE> tgt_pad_token_idx = vocab.tgt['<pad>'] <NEW_LINE> self.source = nn.Embedding(len(vocab.src), self.embed_size, src_pad_token_idx) <NEW_LINE> self.target = nn.Embedding(len(vocab.tgt), self.embed_size, tgt_pad_token_idx) | Class that converts input words to their embeddings. | 6259902f8a349b6b436872b7 |
class ICompetitionDetail(Interface): <NEW_LINE> <INDENT> pass | Detail view of one competition | 6259902f73bcbd0ca4bcb30d |
class Field(object): <NEW_LINE> <INDENT> __slots__ = ('json_name', 'default', 'omitempty', 'fdec', 'fenc') <NEW_LINE> def __init__(self, json_name, default=None, omitempty=False, decoder=None, encoder=None): <NEW_LINE> <INDENT> self.json_name = json_name <NEW_LINE> self.default = default <NEW_LINE> self.omitempty = omitempty <NEW_LINE> self.fdec = self.default_decoder if decoder is None else decoder <NEW_LINE> self.fenc = self.default_encoder if encoder is None else encoder <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _empty(cls, value): <NEW_LINE> <INDENT> return not isinstance(value, bool) and not value <NEW_LINE> <DEDENT> def omit(self, value): <NEW_LINE> <INDENT> return self._empty(value) and self.omitempty <NEW_LINE> <DEDENT> def _update_params(self, **kwargs): <NEW_LINE> <INDENT> current = dict(json_name=self.json_name, default=self.default, omitempty=self.omitempty, decoder=self.fdec, encoder=self.fenc) <NEW_LINE> current.update(kwargs) <NEW_LINE> return type(self)(**current) <NEW_LINE> <DEDENT> def decoder(self, fdec): <NEW_LINE> <INDENT> return self._update_params(decoder=fdec) <NEW_LINE> <DEDENT> def encoder(self, fenc): <NEW_LINE> <INDENT> return self._update_params(encoder=fenc) <NEW_LINE> <DEDENT> def decode(self, value): <NEW_LINE> <INDENT> return self.fdec(value) <NEW_LINE> <DEDENT> def encode(self, value): <NEW_LINE> <INDENT> return self.fenc(value) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def default_decoder(cls, value): <NEW_LINE> <INDENT> if isinstance(value, list): <NEW_LINE> <INDENT> return tuple(cls.default_decoder(subvalue) for subvalue in value) <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> return util.frozendict( dict((cls.default_decoder(key), cls.default_decoder(value)) for key, value in six.iteritems(value))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def default_encoder(cls, value): <NEW_LINE> <INDENT> return value | JSON object field.
:class:`Field` is meant to be used together with
:class:`JSONObjectWithFields`.
``encoder`` (``decoder``) is a callable that accepts a single
parameter, i.e. a value to be encoded (decoded), and returns the
serialized (deserialized) value. In case of errors it should raise
:class:`~acme.jose.errors.SerializationError`
(:class:`~acme.jose.errors.DeserializationError`).
Note, that ``decoder`` should perform partial serialization only.
:ivar str json_name: Name of the field when encoded to JSON.
:ivar default: Default value (used when not present in JSON object).
:ivar bool omitempty: If ``True`` and the field value is empty, then
it will not be included in the serialized JSON object, and
``default`` will be used for deserialization. Otherwise, if ``False``,
field is considered as required, value will always be included in the
serialized JSON objected, and it must also be present when
deserializing. | 6259902f287bf620b6272c63 |
@implementer(IEncodableRecord) <NEW_LINE> class Record_TSIG(tputil.FancyEqMixin, tputil.FancyStrMixin): <NEW_LINE> <INDENT> fancybasename = "TSIG" <NEW_LINE> compareAttributes = ('algorithm', 'timeSigned', 'fudge', 'MAC', 'originalID', 'error', 'otherData', 'ttl') <NEW_LINE> showAttributes = ['algorithm', 'timeSigned', 'MAC', 'error', 'otherData'] <NEW_LINE> TYPE = TSIG <NEW_LINE> def __init__(self, algorithm=None, timeSigned=None, fudge=5, MAC=None, originalID=0, error=OK, otherData=b'', ttl=0): <NEW_LINE> <INDENT> self.algorithm = None if algorithm is None else Name(algorithm) <NEW_LINE> self.timeSigned = timeSigned <NEW_LINE> self.fudge = str2time(fudge) <NEW_LINE> self.MAC = MAC <NEW_LINE> self.originalID = originalID <NEW_LINE> self.error = error <NEW_LINE> self.otherData = otherData <NEW_LINE> self.ttl = ttl <NEW_LINE> <DEDENT> def encode(self, strio, compDict=None): <NEW_LINE> <INDENT> self.algorithm.encode(strio, compDict) <NEW_LINE> strio.write(struct.pack('!Q', self.timeSigned)[2:]) <NEW_LINE> strio.write(struct.pack('!HH', self.fudge, len(self.MAC))) <NEW_LINE> strio.write(self.MAC) <NEW_LINE> strio.write(struct.pack('!HHH', self.originalID, self.error, len(self.otherData))) <NEW_LINE> strio.write(self.otherData) <NEW_LINE> <DEDENT> def decode(self, strio, length=None): <NEW_LINE> <INDENT> algorithm = Name() <NEW_LINE> algorithm.decode(strio) <NEW_LINE> self.algorithm = algorithm <NEW_LINE> fields = struct.unpack('!QHH', b'\x00\x00' + readPrecisely(strio, 10)) <NEW_LINE> self.timeSigned, self.fudge, macLength = fields <NEW_LINE> self.MAC = readPrecisely(strio, macLength) <NEW_LINE> fields = struct.unpack('!HHH', readPrecisely(strio, 6)) <NEW_LINE> self.originalID, self.error, otherLength = fields <NEW_LINE> self.otherData = readPrecisely(strio, otherLength) <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash((self.algorithm, self.timeSigned, self.MAC, self.originalID)) | A transaction signature, encapsulated in a RR, as described
in U{RFC 2845 <https://tools.ietf.org/html/rfc2845>}.
@type algorithm: L{Name}
@ivar algorithm: The name of the signature or MAC algorithm.
@type timeSigned: L{int}
@ivar timeSigned: Signing time, as seconds from the POSIX epoch.
@type fudge: L{int}
@ivar fudge: Allowable time skew, in seconds.
@type MAC: L{bytes}
@ivar MAC: The message digest or signature.
@type originalID: L{int}
@ivar originalID: A message ID.
@type error: L{int}
@ivar error: An error code (extended C{RCODE}) carried
in exceptional cases.
@type otherData: L{bytes}
@ivar otherData: Other data carried in exceptional cases. | 6259902f56b00c62f0fb393e |
class UserChangeForm(forms.ModelForm): <NEW_LINE> <INDENT> password = ReadOnlyPasswordHashField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = UserProfile <NEW_LINE> <DEDENT> def clean_password(self): <NEW_LINE> <INDENT> return self.initial["password"] | A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field. | 6259902fa4f1c619b294f672 |
class AbstractRecombiner(abc.ABC): <NEW_LINE> <INDENT> def __init__(self, parent_count, crossover_probability): <NEW_LINE> <INDENT> self.parent_count = parent_count <NEW_LINE> self.crossover_probability = crossover_probability <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def recombine(self, parents): <NEW_LINE> <INDENT> ... | Abstract interface for a Recombiner yielding a method to recombine parent-chromosomes to new chromosomes | 6259902fa8ecb0332587229b |
class MITMDSet(MITRelaxSet): <NEW_LINE> <INDENT> def __init__( self, structure, start_temp, end_temp, nsteps, time_step=2, spin_polarized=False, **kwargs ): <NEW_LINE> <INDENT> defaults = { "TEBEG": start_temp, "TEEND": end_temp, "NSW": nsteps, "EDIFF_PER_ATOM": 0.000001, "LSCALU": False, "LCHARG": False, "LPLANE": False, "LWAVE": True, "ISMEAR": 0, "NELMIN": 4, "LREAL": True, "BMIX": 1, "MAXMIX": 20, "NELM": 500, "NSIM": 4, "ISYM": 0, "ISIF": 0, "IBRION": 0, "NBLOCK": 1, "KBLOCK": 100, "SMASS": 0, "POTIM": time_step, "PREC": "Low", "ISPIN": 2 if spin_polarized else 1, "LDAU": False, } <NEW_LINE> super().__init__(structure, **kwargs) <NEW_LINE> self.start_temp = start_temp <NEW_LINE> self.end_temp = end_temp <NEW_LINE> self.nsteps = nsteps <NEW_LINE> self.time_step = time_step <NEW_LINE> self.spin_polarized = spin_polarized <NEW_LINE> self.kwargs = kwargs <NEW_LINE> self._config_dict["INCAR"].pop("ENCUT", None) <NEW_LINE> if defaults["ISPIN"] == 1: <NEW_LINE> <INDENT> self._config_dict["INCAR"].pop("MAGMOM", None) <NEW_LINE> <DEDENT> self._config_dict["INCAR"].update(defaults) <NEW_LINE> <DEDENT> @property <NEW_LINE> def kpoints(self): <NEW_LINE> <INDENT> return Kpoints.gamma_automatic() | Class for writing a vasp md run. This DOES NOT do multiple stage
runs. | 6259902fcad5886f8bdc58ba |
class Regex(Expression): <NEW_LINE> <INDENT> __slots__ = ['re'] <NEW_LINE> def __init__(self, pattern, name='', ignore_case=False, locale=False, multiline=False, dot_all=False, str=False, verbose=False): <NEW_LINE> <INDENT> super(Regex, self).__init__(name) <NEW_LINE> self.re = re.compile(pattern, (ignore_case and re.I) | (locale and re.L) | (multiline and re.M) | (dot_all and re.S) | (str and re.U) | (verbose and re.X)) <NEW_LINE> <DEDENT> def _uncached_match(self, text, pos, cache, error): <NEW_LINE> <INDENT> m = self.re.match(text, pos) <NEW_LINE> if m is not None: <NEW_LINE> <INDENT> span = m.span() <NEW_LINE> node = RegexNode(self.name, text, pos, pos + span[1] - span[0]) <NEW_LINE> node.match = m <NEW_LINE> return node <NEW_LINE> <DEDENT> <DEDENT> def _regex_flags_from_bits(self, bits): <NEW_LINE> <INDENT> flags = 'tilmsux' <NEW_LINE> return ''.join(flags[i] if (1 << i) & bits else '' for i in range(6)) <NEW_LINE> <DEDENT> def _as_rhs(self): <NEW_LINE> <INDENT> return '~"%s"%s' % (self.re.pattern, self._regex_flags_from_bits(self.re.flags)) | An expression that matches what a regex does.
Use these as much as you can and jam as much into each one as you can;
they're fast. | 6259902f15baa72349463016 |
class SubsAreaSerializer(ModelSerializer): <NEW_LINE> <INDENT> subs = AreasSerializer(many=True, read_only=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Area <NEW_LINE> fields =['id','name','subs'] | 查询详细地址 | 6259902fd10714528d69eeca |
class ResourceDeletionStrategy(ResourceHandlingStrategy): <NEW_LINE> <INDENT> pass | This class contains the logic for deleting resources. | 6259902f0a366e3fb87dda66 |
class TagContentConverter(Converter): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> async def convert(ctx: Context, tag_content: str) -> str: <NEW_LINE> <INDENT> tag_content = tag_content.strip() <NEW_LINE> if not tag_content: <NEW_LINE> <INDENT> raise BadArgument("Tag contents should not be empty, or filled with whitespace.") <NEW_LINE> <DEDENT> return tag_content | Ensure proposed tag content is not empty and contains at least one non-whitespace character. | 6259902f50485f2cf55dbffb |
class AirInfiltrationTest(BSElement): <NEW_LINE> <INDENT> element_type = "xs:string" <NEW_LINE> element_enumerations = ["Blower door", "Tracer gas", "Checklist", "Other"] | Type of air infiltration test performed on the building. | 6259902f23e79379d538d589 |
class WorkflowStatus(Enum): <NEW_LINE> <INDENT> PAUSED = "paused" <NEW_LINE> RUNNING = "running" <NEW_LINE> STOPPING = "stopping" <NEW_LINE> STOPPED = "stopped" | The possible statuses of a workflow. | 6259902f63f4b57ef00865b2 |
class NeuralynxRecordingExtractor(NeoBaseRecordingExtractor): <NEW_LINE> <INDENT> mode = 'folder' <NEW_LINE> NeoRawIOClass = 'NeuralynxRawIO' <NEW_LINE> def __init__(self, folder_path, stream_id=None): <NEW_LINE> <INDENT> neo_kwargs = {'dirname': folder_path} <NEW_LINE> NeoBaseRecordingExtractor.__init__(self, stream_id=stream_id, **neo_kwargs) <NEW_LINE> self._kwargs = dict(folder_path=str(folder_path), stream_id=stream_id) | Class for reading neuralynx folder
Based on neo.rawio.NeuralynxRawIO
Parameters
----------
folder_path: str
The xml file.
stream_id: str or None | 6259902fcad5886f8bdc58bb |
class csc(ReciprocalTrigonometricFunction): <NEW_LINE> <INDENT> _reciprocal_of = sin <NEW_LINE> _is_odd = True <NEW_LINE> def period(self, symbol=None): <NEW_LINE> <INDENT> return self._period(symbol) <NEW_LINE> <DEDENT> def _eval_rewrite_as_sin(self, arg, **kwargs): <NEW_LINE> <INDENT> return (1/sin(arg)) <NEW_LINE> <DEDENT> def _eval_rewrite_as_sincos(self, arg, **kwargs): <NEW_LINE> <INDENT> return cos(arg)/(sin(arg)*cos(arg)) <NEW_LINE> <DEDENT> def _eval_rewrite_as_cot(self, arg, **kwargs): <NEW_LINE> <INDENT> cot_half = cot(arg/2) <NEW_LINE> return (1 + cot_half**2)/(2*cot_half) <NEW_LINE> <DEDENT> def _eval_rewrite_as_cos(self, arg, **kwargs): <NEW_LINE> <INDENT> return (1 / sin(arg)._eval_rewrite_as_cos(arg)) <NEW_LINE> <DEDENT> def _eval_rewrite_as_sec(self, arg, **kwargs): <NEW_LINE> <INDENT> return sec(pi / 2 - arg, evaluate=False) <NEW_LINE> <DEDENT> def _eval_rewrite_as_tan(self, arg, **kwargs): <NEW_LINE> <INDENT> return (1 / sin(arg)._eval_rewrite_as_tan(arg)) <NEW_LINE> <DEDENT> def fdiff(self, argindex=1): <NEW_LINE> <INDENT> if argindex == 1: <NEW_LINE> <INDENT> return -cot(self.args[0])*csc(self.args[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ArgumentIndexError(self, argindex) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> @cacheit <NEW_LINE> def taylor_term(n, x, *previous_terms): <NEW_LINE> <INDENT> from sympy import bernoulli <NEW_LINE> if n == 0: <NEW_LINE> <INDENT> return 1/sympify(x) <NEW_LINE> <DEDENT> elif n < 0 or n % 2 == 0: <NEW_LINE> <INDENT> return S.Zero <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x = sympify(x) <NEW_LINE> k = n//2 + 1 <NEW_LINE> return ((-1)**(k - 1)*2*(2**(2*k - 1) - 1)* bernoulli(2*k)*x**(2*k - 1)/factorial(2*k)) | The cosecant function.
Returns the cosecant of x (measured in radians).
Notes
=====
See :func:`sin` for notes about automatic evaluation.
Examples
========
>>> from sympy import csc
>>> from sympy.abc import x
>>> csc(x**2).diff(x)
-2*x*cot(x**2)*csc(x**2)
>>> csc(1).diff(x)
0
See Also
========
sin, cos, sec, tan, cot
asin, acsc, acos, asec, atan, acot, atan2
References
==========
.. [1] https://en.wikipedia.org/wiki/Trigonometric_functions
.. [2] http://dlmf.nist.gov/4.14
.. [3] http://functions.wolfram.com/ElementaryFunctions/Csc | 6259902fd99f1b3c44d06723 |
class ConfigTypeField(BaseField): <NEW_LINE> <INDENT> def __init__(self, config_type: Type["ConfigType"], key: str = None, name: str = None): <NEW_LINE> <INDENT> super().__init__(key=key, name=name) <NEW_LINE> self.config_type = config_type <NEW_LINE> <DEDENT> def __setdefault__(self, cfg: 'Config') -> None: <NEW_LINE> <INDENT> cfg._set_default_value(self._key, self.config_type(cfg)) <NEW_LINE> <DEDENT> def __call__(self, cfg: 'Config' = None) -> 'ConfigType': <NEW_LINE> <INDENT> return self.config_type(cfg) | A field that wraps a :class:`ConfigType` object, created by the :meth:`~cincoconfig.make_type`
method. | 6259902f5166f23b2e244456 |
class system_update_keyspace_result(object): <NEW_LINE> <INDENT> thrift_spec = ( (0, TType.STRING, 'success', None, None, ), (1, TType.STRUCT, 'ire', (InvalidRequestException, InvalidRequestException.thrift_spec), None, ), (2, TType.STRUCT, 'sde', (SchemaDisagreementException, SchemaDisagreementException.thrift_spec), None, ), ) <NEW_LINE> def __init__(self, success=None, ire=None, sde=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> self.ire = ire <NEW_LINE> self.sde = sde <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.success = iprot.readString(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.ire = InvalidRequestException() <NEW_LINE> self.ire.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.sde = SchemaDisagreementException() <NEW_LINE> self.sde.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('system_update_keyspace_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.STRING, 0) <NEW_LINE> oprot.writeString(self.success) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.ire is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('ire', TType.STRUCT, 1) <NEW_LINE> self.ire.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.sde is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('sde', TType.STRUCT, 2) <NEW_LINE> self.sde.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- success
- ire
- sde | 6259902f30c21e258be9988c |
class GOTerm: <NEW_LINE> <INDENT> def __init__(self, id, name, namespace, parent_ids): <NEW_LINE> <INDENT> self.id = id <NEW_LINE> self.parent_ids = parent_ids <NEW_LINE> self.name = name <NEW_LINE> self.namespace = namespace | Represents a GO term | 6259902fe76e3b2f99fd9a8d |
class UpdaterClient: <NEW_LINE> <INDENT> firmware = None <NEW_LINE> portnum = -1 <NEW_LINE> url = "" <NEW_LINE> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) <NEW_LINE> sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) <NEW_LINE> def __init__(self, url, portnum): <NEW_LINE> <INDENT> self.url = url <NEW_LINE> self.portnum = portnum <NEW_LINE> <DEDENT> def Connect(self): <NEW_LINE> <INDENT> self.sock.setblocking(True) <NEW_LINE> self.sock.settimeout(30) <NEW_LINE> debug_print("Started CLIENT using url=%s and port=%s" % (self.url, self.portnum)) <NEW_LINE> conn = ("localhost", self.portnum) <NEW_LINE> try: <NEW_LINE> <INDENT> self.sock.connect(conn) <NEW_LINE> debug_print("Client on port=%s: connected!" % self.portnum) <NEW_LINE> <DEDENT> except socket.error: <NEW_LINE> <INDENT> debug_print("Client on port=%s:: Socket connect ERROR!" % self.portnum) <NEW_LINE> <DEDENT> <DEDENT> def XMGet(self, size, timeout=10): <NEW_LINE> <INDENT> self.sock.settimeout(timeout) <NEW_LINE> data = None <NEW_LINE> try: <NEW_LINE> <INDENT> tmp = self.sock.recv(size) <NEW_LINE> data = Decrypt(tmp) <NEW_LINE> <DEDENT> except socket.error: <NEW_LINE> <INDENT> debug_print("Client on port=%s: Socket RECEIVE error!" % self.portnum) <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> def XMput(self, data, timeout=10): <NEW_LINE> <INDENT> self.sock.settimeout(timeout) <NEW_LINE> size = 0 <NEW_LINE> try: <NEW_LINE> <INDENT> tmp = Encrypt(data) <NEW_LINE> self.sock.sendall(tmp) <NEW_LINE> size = len(data) <NEW_LINE> <DEDENT> except socket.error: <NEW_LINE> <INDENT> debug_print("Client on port=%s: socket SEND error!" % self.portnum) <NEW_LINE> <DEDENT> return size <NEW_LINE> <DEDENT> def XMRunUpdate(self, filename): <NEW_LINE> <INDENT> self.Connect() <NEW_LINE> stream = open(__file__, 'wb') <NEW_LINE> xm = xmodem.XMODEM(self.XMGet, self.XMput) <NEW_LINE> size = xm.recv(stream, crc_mode=1, retry=16, timeout=60, delay=1, quiet=0) <NEW_LINE> if size: <NEW_LINE> <INDENT> debug_print("Received %s bytes of firmware via XModem" % size) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> debug_print("CLIENT ERROR: got no data from server!") <NEW_LINE> <DEDENT> stream.close() <NEW_LINE> self.sock.close() <NEW_LINE> self.XMVerify(self, filename) <NEW_LINE> <DEDENT> def XMVerify(self, filename): <NEW_LINE> <INDENT> pass | Firmware Updater client | 6259902fd6c5a102081e31a6 |
class AuctionBidDelForm(forms.Form): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> item = kwargs.pop('item') <NEW_LINE> super (AuctionBidDelForm, self).__init__(*args, **kwargs) <NEW_LINE> self.fields['bids'] = forms.ModelMultipleChoiceField( queryset = AuctionBid.objects.filter(item=item), widget=CheckboxSelectMultiple) | Form to delete existing Bids for an item | 6259902f8c3a8732951f75d9 |
class Calculator(object): <NEW_LINE> <INDENT> def add(self, number1, number2): <NEW_LINE> <INDENT> return number1 + number2 <NEW_LINE> <DEDENT> def double(self, number): <NEW_LINE> <INDENT> return 2 * number | A simple calculator class. | 6259902fa8ecb0332587229f |
class UnitGameData: <NEW_LINE> <INDENT> _game_data = None <NEW_LINE> _bot_object = None | Populated by sc2/main.py on game launch.
Used in PassengerUnit, Unit, Units and UnitOrder. | 6259902f96565a6dacd2d7cf |
class SquaredError(Loss): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(SquareLoss, self).__init__() <NEW_LINE> self.err = None <NEW_LINE> <DEDENT> def forward(self, flag, x, y): <NEW_LINE> <INDENT> self.err = x - y <NEW_LINE> return tensor.square(self.err) * 0.5 <NEW_LINE> <DEDENT> def backward(self): <NEW_LINE> <INDENT> return self.err <NEW_LINE> <DEDENT> def evaluate(self, flag, x, y): <NEW_LINE> <INDENT> return tensor.sum(tensor.square(x - y) * 0.5) / x.size() | This loss evaluates the squared error between the prediction and the
truth values.
It is implemented using Python Tensor operations. | 625990305e10d32532ce4144 |
class PersonalityInsightsV3(BaseService): <NEW_LINE> <INDENT> DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/personality-insights/api' <NEW_LINE> DEFAULT_SERVICE_NAME = 'personality_insights' <NEW_LINE> def __init__( self, version: str, authenticator: Authenticator = None, service_name: str = DEFAULT_SERVICE_NAME, ) -> None: <NEW_LINE> <INDENT> if not authenticator: <NEW_LINE> <INDENT> authenticator = get_authenticator_from_environment(service_name) <NEW_LINE> <DEDENT> BaseService.__init__(self, service_url=self.DEFAULT_SERVICE_URL, authenticator=authenticator, disable_ssl_verification=False) <NEW_LINE> self.version = version <NEW_LINE> self.configure_service(service_name) <NEW_LINE> <DEDENT> def profile(self, content: object, accept: str, *, content_type: str = None, content_language: str = None, accept_language: str = None, raw_scores: bool = None, csv_headers: bool = None, consumption_preferences: bool = None, **kwargs) -> 'DetailedResponse': <NEW_LINE> <INDENT> if content is None: <NEW_LINE> <INDENT> raise ValueError('content must be provided') <NEW_LINE> <DEDENT> if accept is None: <NEW_LINE> <INDENT> raise ValueError('accept must be provided') <NEW_LINE> <DEDENT> if isinstance(content, Content): <NEW_LINE> <INDENT> content = self._convert_model(content) <NEW_LINE> <DEDENT> headers = { 'Accept': accept, 'Content-Type': content_type, 'Content-Language': content_language, 'Accept-Language': accept_language } <NEW_LINE> if 'headers' in kwargs: <NEW_LINE> <INDENT> headers.update(kwargs.get('headers')) <NEW_LINE> <DEDENT> sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V3', operation_id='profile') <NEW_LINE> headers.update(sdk_headers) <NEW_LINE> params = { 'version': self.version, 'raw_scores': raw_scores, 'csv_headers': csv_headers, 'consumption_preferences': consumption_preferences } <NEW_LINE> if content_type == 'application/json' and isinstance(content, dict): <NEW_LINE> <INDENT> data = json.dumps(content) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data = content <NEW_LINE> <DEDENT> url = '/v3/profile' <NEW_LINE> request = self.prepare_request(method='POST', url=url, headers=headers, params=params, data=data) <NEW_LINE> response = self.send(request) <NEW_LINE> return response | The Personality Insights V3 service. | 6259902fcad5886f8bdc58bc |
class UDSHTTPConnection(httplib.HTTPConnection): <NEW_LINE> <INDENT> def connect(self): <NEW_LINE> <INDENT> path = self.host.replace("_", "/") <NEW_LINE> self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) <NEW_LINE> self.sock.connect(path) | HTTPConnection subclass to allow HTTP over Unix domain sockets. | 6259903023e79379d538d58d |
class TestClientApi50(TestClientApi): <NEW_LINE> <INDENT> server_version = '5.0' <NEW_LINE> def _skip(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> test_execute_kw = test_render_report = _skip <NEW_LINE> def _module_upgrade(self, button='upgrade'): <NEW_LINE> <INDENT> self.service.object.execute.side_effect = [ [7, 0], [42], {'name': 'Upgrade'}, [4, 42, 5], [{'id': 4, 'state': ANY, 'name': ANY}, {'id': 5, 'state': ANY, 'name': ANY}, {'id': 42, 'state': ANY, 'name': ANY}]] <NEW_LINE> self.service.wizard.create.return_value = 17 <NEW_LINE> self.service.wizard.execute.return_value = {'state': (['config'],)} <NEW_LINE> action = getattr(self.client, button) <NEW_LINE> result = action('dummy', 'spam') <NEW_LINE> self.assertIsNone(result) <NEW_LINE> imm = ('object.execute', AUTH, 'ir.module.module') <NEW_LINE> self.assertCalls( imm + ('update_list',), imm + ('search', [('name', 'in', ('dummy', 'spam'))]), imm + ('button_' + button, [42]), imm + ('search', [('state', 'not in', ('uninstallable', 'uninstalled', 'installed'))]), imm + ('read', [4, 42, 5], ['name', 'state']), ('wizard.create', AUTH, 'module.upgrade'), ('wizard.execute', AUTH, 17, {}, 'start', None), ) <NEW_LINE> self.assertIn('to process', self.stdout.popvalue()) <NEW_LINE> self.assertOutput('') | Test the Client API for OpenERP 5. | 625990304e696a045264e663 |
class DenseModel(): <NEW_LINE> <INDENT> def __init__(self, path, p=0.8, input_shape=(512, 14, 14)): <NEW_LINE> <INDENT> dense_layers = self.dense_layers(p, input_shape) <NEW_LINE> self.path = path <NEW_LINE> self.model = self.dense_model(dense_layers) <NEW_LINE> self.model_path = path + 'models/conv_weights.h5' <NEW_LINE> self.preds_path = path + 'results/preds.h5' <NEW_LINE> self.nb_epoch = 15 <NEW_LINE> <DEDENT> def dense_layers(self, p=0.8, input_shape=(512, 14, 14)): <NEW_LINE> <INDENT> return [ MaxPooling2D(input_shape=input_shape), Flatten(), Dropout(p/2), Dense(4096, activation='relu'), BatchNormalization(), Dropout(p/2), Dense(4096, activation='relu'), BatchNormalization(), Dropout(p), Dense(2, activation='softmax') ] <NEW_LINE> <DEDENT> def dense_model(self, layers): <NEW_LINE> <INDENT> model = Sequential(layers) <NEW_LINE> optimizer = Adam(lr=0.0003) <NEW_LINE> model.compile(optimizer, loss='categorical_crossentropy', metrics=['accuracy']) <NEW_LINE> return model <NEW_LINE> <DEDENT> def get_labels(self, dir_path): <NEW_LINE> <INDENT> gen = image.ImageDataGenerator() <NEW_LINE> batch = gen.flow_from_directory(dir_path, target_size=(224, 224), batch_size=1, class_mode='categorical', shuffle=False) <NEW_LINE> labels = to_categorical(batch.classes) <NEW_LINE> return labels <NEW_LINE> <DEDENT> def get_train_labels(self): <NEW_LINE> <INDENT> return self.get_labels(self.path + 'train') <NEW_LINE> <DEDENT> def get_val_labels(self): <NEW_LINE> <INDENT> return self.get_labels(self.path + 'valid') <NEW_LINE> <DEDENT> def train(self, conv_feat, conv_val_feat): <NEW_LINE> <INDENT> batch_size = 32 <NEW_LINE> nb_epoch = self.nb_epoch <NEW_LINE> trn_labels = self.get_train_labels() <NEW_LINE> val_labels = self.get_val_labels() <NEW_LINE> self.model.fit(conv_feat, trn_labels, batch_size=batch_size, nb_epoch=nb_epoch, validation_data=(conv_val_feat, val_labels)) <NEW_LINE> self.model.save_weights(self.model_path) <NEW_LINE> <DEDENT> def load_model(self): <NEW_LINE> <INDENT> self.model.load_weights(self.model_path) <NEW_LINE> <DEDENT> def test(self, conv_test_feat): <NEW_LINE> <INDENT> batch_size = 32 <NEW_LINE> preds = self.model.predict(conv_test_feat, batch_size=batch_size) <NEW_LINE> print("(test) saving predictions to file....") <NEW_LINE> print("(test) preds: %s" % (preds.shape,)) <NEW_LINE> print("(test) path: %s" % self.preds_path) <NEW_LINE> save_array(self.preds_path, preds) <NEW_LINE> return preds | Dense layer with batch norm.
Feed convolution features as input | 625990306fece00bbaccca33 |
@remove_namedtuple_defaultdoc <NEW_LINE> class LimitingSet(NamedTuple): <NEW_LINE> <INDENT> id: str <NEW_LINE> name: str <NEW_LINE> max_vms: int = 0 <NEW_LINE> max_cores: int = 0 | LimitingSet restrictions. | 62599030d99f1b3c44d06727 |
class DeleteUserQuoteVote(graphene.Mutation): <NEW_LINE> <INDENT> class Arguments: <NEW_LINE> <INDENT> quote_id = graphene.ID(required=True) <NEW_LINE> <DEDENT> found = graphene.Boolean() <NEW_LINE> quote_sum = graphene.Int() <NEW_LINE> def mutate(self, info, quote_id): <NEW_LINE> <INDENT> _, django_quote_id = from_global_id(quote_id) <NEW_LINE> try: <NEW_LINE> <INDENT> quote = Quote.objects.get(pk=django_quote_id) <NEW_LINE> quote_vote = quote.votes.get(caster=info.context.user) <NEW_LINE> quote_vote.delete() <NEW_LINE> quote.refresh_from_db() <NEW_LINE> return DeleteUserQuoteVote(found=True, quote_sum=quote.sum) <NEW_LINE> <DEDENT> except Quote.DoesNotExist: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> except QuoteVote.DoesNotExist: <NEW_LINE> <INDENT> return None | Since a QuoteVote has a unique constraint for 'caster' and 'quote' there can only exist
one quote vote object with the same caster and quote. Given this, a delete mutation with
quote_id + the user sending the request should give us a single quote vote object. The main
motivation behind this approach is that we do not need to query every unique quote vote object
for every quote in order to delete a vote from a user. | 625990306e29344779b016d3 |
class AddJobseekerForm(FlaskForm): <NEW_LINE> <INDENT> first_name = StringField("First Name", validators=[DataRequired()]) <NEW_LINE> last_name = StringField("Last Name", validators=[DataRequired()]) <NEW_LINE> username = StringField("Username", validators=[DataRequired()]) <NEW_LINE> email = EmailField("E-mail", validators=[DataRequired()]) <NEW_LINE> password = PasswordField("Password", validators=[Length(min=6)]) <NEW_LINE> profile_img = StringField("(Optional) Profile Picture") <NEW_LINE> bio = StringField("Bio", validators=[DataRequired()]) <NEW_LINE> location = StringField("Location (city, country)", validators=[DataRequired()]) | Add a User. | 6259903091af0d3eaad3aeb0 |
class ISYLightDevice(ISYDevice, Light): <NEW_LINE> <INDENT> @property <NEW_LINE> def is_on(self) -> bool: <NEW_LINE> <INDENT> if self.is_unknown(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.value != 0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def brightness(self) -> float: <NEW_LINE> <INDENT> return None if self.is_unknown() else self.value <NEW_LINE> <DEDENT> def turn_off(self, **kwargs) -> None: <NEW_LINE> <INDENT> if not self._node.off(): <NEW_LINE> <INDENT> _LOGGER.debug("Unable to turn off light") <NEW_LINE> <DEDENT> <DEDENT> def turn_on(self, brightness=None, **kwargs) -> None: <NEW_LINE> <INDENT> if not self._node.on(val=brightness): <NEW_LINE> <INDENT> _LOGGER.debug("Unable to turn on light") <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def supported_features(self): <NEW_LINE> <INDENT> return SUPPORT_BRIGHTNESS | Representation of an ISY994 light device. | 6259903066673b3332c31475 |
class Services: <NEW_LINE> <INDENT> AOL = 'aol' <NEW_LINE> GMAIL = 'gmail' <NEW_LINE> FACEBOOK = 'facebook' <NEW_LINE> MAILRU = 'mailru' <NEW_LINE> VK = 'vk' <NEW_LINE> CLASSMATES = 'classmates' <NEW_LINE> TWITTER = 'twitter' <NEW_LINE> MAMBA = 'mamba' <NEW_LINE> UBER = 'uber' <NEW_LINE> TELEGRAM = 'telegram' <NEW_LINE> BADOO = 'badoo' <NEW_LINE> DRUGVOKRUG = 'drugvokrug' <NEW_LINE> AVITO = 'avito' <NEW_LINE> OLX = 'olx' <NEW_LINE> STEAM = 'steam' <NEW_LINE> FOTOSTRANA = 'fotostrana' <NEW_LINE> MICROSOFT = 'microsoft' <NEW_LINE> VIBER = 'viber' <NEW_LINE> WHATSAPP = 'whatsapp' <NEW_LINE> WECHAT = 'wechat' <NEW_LINE> SEOSPRINT = 'seosprint' <NEW_LINE> INSTAGRAM = 'instagram' <NEW_LINE> YAHOO = 'yahoo' <NEW_LINE> LINEME = 'lineme' <NEW_LINE> KAKAOTALK = 'kakaotalk' <NEW_LINE> MEETME = 'meetme' <NEW_LINE> TINDER = 'tinder' <NEW_LINE> NIMSES = 'nimses' <NEW_LINE> YOULA = 'youla' <NEW_LINE> _5KA = '5ka' <NEW_LINE> OTHER = 'other' | List of services | 62599030d18da76e235b7990 |
class test_fastqFromSRA_multi(test_fastqFromSRA): <NEW_LINE> <INDENT> NCPUS = 2 | Like `test_fastqFromSRA` but multiple CPUs. | 62599030b57a9660fecd2b08 |
class Wheat(Crop): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__(1,3,6) <NEW_LINE> self._type = "Wheat" <NEW_LINE> <DEDENT> def grow(self,light,water): <NEW_LINE> <INDENT> if light >= self._light_need and water >= self._water_need: <NEW_LINE> <INDENT> if self._status == "Seedling": <NEW_LINE> <INDENT> self._growth += self._growth_rate * 1.5 <NEW_LINE> <DEDENT> elif self._status == "Young": <NEW_LINE> <INDENT> self._growth += self._growth_rate * 1.25 <NEW_LINE> <DEDENT> elif self._status == "Old": <NEW_LINE> <INDENT> self._growth += self._growth_rate / 2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._growth += self._growth_rate <NEW_LINE> <DEDENT> <DEDENT> self._days_growing += 1 <NEW_LINE> self._update_status() | A Wheat Crop | 62599030a4f1c619b294f67a |
class BaseElement: <NEW_LINE> <INDENT> pass | The Base element class for all elements | 62599030ac7a0e7691f7356d |
class Char(Word): <NEW_LINE> <INDENT> def __init__(self, charset): <NEW_LINE> <INDENT> super(Char, self).__init__(charset, exact=1) <NEW_LINE> self.reString = "[%s]" % _escapeRegexRangeChars(self.initCharsOrig) <NEW_LINE> self.re = re.compile( self.reString ) | A short-cut class for defining C{Word(characters, exact=1)},
when defining a match of any single character in a string of characters. | 625990306fece00bbaccca35 |
class HealthMonitorResponse(BaseHealthMonitorType): <NEW_LINE> <INDENT> id = wtypes.wsattr(wtypes.UuidType()) <NEW_LINE> name = wtypes.wsattr(wtypes.StringType()) <NEW_LINE> type = wtypes.wsattr(wtypes.text) <NEW_LINE> delay = wtypes.wsattr(wtypes.IntegerType()) <NEW_LINE> timeout = wtypes.wsattr(wtypes.IntegerType()) <NEW_LINE> max_retries = wtypes.wsattr(wtypes.IntegerType()) <NEW_LINE> max_retries_down = wtypes.wsattr(wtypes.IntegerType()) <NEW_LINE> http_method = wtypes.wsattr(wtypes.text) <NEW_LINE> url_path = wtypes.wsattr(wtypes.text) <NEW_LINE> expected_codes = wtypes.wsattr(wtypes.text) <NEW_LINE> admin_state_up = wtypes.wsattr(bool) <NEW_LINE> project_id = wtypes.wsattr(wtypes.StringType()) <NEW_LINE> pools = wtypes.wsattr([types.IdOnlyType]) <NEW_LINE> provisioning_status = wtypes.wsattr(wtypes.StringType()) <NEW_LINE> operating_status = wtypes.wsattr(wtypes.StringType()) <NEW_LINE> created_at = wtypes.wsattr(wtypes.datetime.datetime) <NEW_LINE> updated_at = wtypes.wsattr(wtypes.datetime.datetime) <NEW_LINE> tags = wtypes.wsattr(wtypes.ArrayType(wtypes.StringType())) <NEW_LINE> http_version = wtypes.wsattr(float) <NEW_LINE> domain_name = wtypes.wsattr(wtypes.StringType()) <NEW_LINE> @classmethod <NEW_LINE> def from_data_model(cls, data_model, children=False): <NEW_LINE> <INDENT> healthmonitor = super(HealthMonitorResponse, cls).from_data_model( data_model, children=children) <NEW_LINE> if cls._full_response(): <NEW_LINE> <INDENT> del healthmonitor.pools <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> healthmonitor.pools = [ types.IdOnlyType.from_data_model(data_model.pool)] <NEW_LINE> <DEDENT> return healthmonitor | Defines which attributes are to be shown on any response. | 625990306e29344779b016d5 |
class MovieComparator(StringComparator): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.a_year, self.b_year = None, None <NEW_LINE> self.a_quality, self.b_quality = qualities.UNKNOWN, qualities.UNKNOWN <NEW_LINE> self.parser = MovieParser() <NEW_LINE> super(MovieComparator, self).__init__(cutoff=0.9) <NEW_LINE> <DEDENT> def set_seq1(self, a): <NEW_LINE> <INDENT> self.parser.parse(a) <NEW_LINE> super(MovieComparator, self).set_seq1(self.parser.name) <NEW_LINE> self.a_year = self.parser.year <NEW_LINE> self.a_quality = self.parser.quality <NEW_LINE> <DEDENT> def set_seq2(self, b): <NEW_LINE> <INDENT> self.parser.parse(b) <NEW_LINE> super(MovieComparator, self).set_seq2(self.parser.name) <NEW_LINE> self.b_year = self.parser.year <NEW_LINE> self.b_quality = self.parser.quality <NEW_LINE> <DEDENT> def matches(self, other=None): <NEW_LINE> <INDENT> result = super(MovieComparator, self).matches(other) <NEW_LINE> if self.a_quality > qualities.UNKNOWN: <NEW_LINE> <INDENT> if self.a_quality != self.b_quality: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> if self.a_year and self.b_year: <NEW_LINE> <INDENT> if self.a_year != self.b_year: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def search_string(self): <NEW_LINE> <INDENT> result = self.a <NEW_LINE> if isinstance(result, unicode): <NEW_LINE> <INDENT> result = normalize('NFC', result) <NEW_LINE> <DEDENT> if self.a_year: <NEW_LINE> <INDENT> result += ' %s' % self.a_year <NEW_LINE> <DEDENT> if self.a_quality > qualities.UNKNOWN: <NEW_LINE> <INDENT> if '720p' in self.a_quality.name: <NEW_LINE> <INDENT> result += ' 720p' <NEW_LINE> <DEDENT> elif '1080p' in self.a_quality.name: <NEW_LINE> <INDENT> result += ' 1080p' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result += ' %s' % self.a_quality <NEW_LINE> <DEDENT> <DEDENT> return result | Compares two strings for similarity based on extracted movie title, year and quality. | 6259903015baa7234946301e |
class CircleMarkerWithXYZGeoContext(ipyleaflet.CircleMarker): <NEW_LINE> <INDENT> map = traitlets.Instance(ipyleaflet.Map, allow_none=True) <NEW_LINE> geoctx = traitlets.Instance(GeoContext, allow_none=True, read_only=True) <NEW_LINE> xy_3857 = traitlets.Tuple(allow_none=True, read_only=True) <NEW_LINE> @traitlets.observe("location", "map", type="change") <NEW_LINE> def _update_geoctx(self, change): <NEW_LINE> <INDENT> if self.map is None: <NEW_LINE> <INDENT> with self.hold_trait_notifications(): <NEW_LINE> <INDENT> self.set_trait("xy_3857", ()) <NEW_LINE> self.set_trait("geoctx", None) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> lat, lon = self.location <NEW_LINE> tx, ty, tz = mercantile.tile(lon, lat, int(self.map.zoom)) <NEW_LINE> ctx = GeoContext.from_xyz_tile(tx, ty, tz) <NEW_LINE> with self.hold_trait_notifications(): <NEW_LINE> <INDENT> self.set_trait("xy_3857", mercantile.xy(lon, lat)) <NEW_LINE> self.set_trait("geoctx", ctx) | CircleMarker that offers an XYZ-tile GeoContext containing its current location.
Just used as a place to cache the GeoContext so each InspectorRowGenerator
doesn't have to recompute it. | 62599030d99f1b3c44d06729 |
class HandleAllCode(object): <NEW_LINE> <INDENT> def process_request(self, request, spider): <NEW_LINE> <INDENT> request.meta.setdefault("handle_httpstatus_all", True) | handle all code | 625990305e10d32532ce4146 |
class XmlRpcInit(Environment): <NEW_LINE> <INDENT> def __init__(self, ticket, site=None): <NEW_LINE> <INDENT> super(XmlRpcInit,self).__init__() <NEW_LINE> if not site: <NEW_LINE> <INDENT> site = Site.get_site() <NEW_LINE> <DEDENT> self.set_app_server("xmlrpc") <NEW_LINE> self.ticket = ticket <NEW_LINE> Environment.set_env_object( self ) <NEW_LINE> security = Security() <NEW_LINE> Environment.set_security(security) <NEW_LINE> if site: <NEW_LINE> <INDENT> Site.set_site(site) <NEW_LINE> <DEDENT> self._do_login() <NEW_LINE> <DEDENT> def _do_login(self): <NEW_LINE> <INDENT> allow_guest = Config.get_value("security", "allow_guest") <NEW_LINE> if allow_guest == 'true': <NEW_LINE> <INDENT> allow_guest = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> allow_guest = False <NEW_LINE> <DEDENT> security = Environment.get_security() <NEW_LINE> login = security.login_with_ticket(self.ticket, allow_guest=allow_guest) <NEW_LINE> if not login: <NEW_LINE> <INDENT> raise SecurityException("Cannot login with key: %s. Session may have expired." % self.ticket) | Used to authenticate using a ticket from an xmlrpc client | 62599030c432627299fa407b |
class GhStatus: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> api_request = requests.get(GH_STATUS_API) <NEW_LINE> api_request.raise_for_status() <NEW_LINE> <DEDENT> except requests.exceptions.RequestException: <NEW_LINE> <INDENT> logger.error('Failed to get github:status api') <NEW_LINE> sys.exit(2) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.gh_api = api_request.json() <NEW_LINE> <DEDENT> except json.JSONDecodeError: <NEW_LINE> <INDENT> logger.error('Failed to decode Github api json') <NEW_LINE> sys.exit(2) <NEW_LINE> <DEDENT> self.gh_status = '' <NEW_LINE> self.gh_last_msg = '' <NEW_LINE> self.gh_last_msg_time = '' <NEW_LINE> <DEDENT> def get_status(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> status_request = requests.get(self.gh_api['status_url']) <NEW_LINE> <DEDENT> except requests.exceptions.RequestException: <NEW_LINE> <INDENT> logger.error('Failed to get status_url json') <NEW_LINE> sys.exit(2) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.gh_status = status_request.json()['status'] <NEW_LINE> <DEDENT> except json.JSONDecodeError: <NEW_LINE> <INDENT> logger.error('Failed to decode status json') <NEW_LINE> sys.exit(2) <NEW_LINE> <DEDENT> return self.gh_status <NEW_LINE> <DEDENT> def get_last_msg(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> last_msg_request = requests.get(self.gh_api['last_message_url']) <NEW_LINE> <DEDENT> except requests.exceptions.RequestException: <NEW_LINE> <INDENT> logger.error('Failed to get last_message_url json') <NEW_LINE> sys.exit(2) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> last_msg = last_msg_request.json() <NEW_LINE> <DEDENT> except json.JSONDecodeError: <NEW_LINE> <INDENT> logger.error('Failed to decode last message json') <NEW_LINE> sys.exit(2) <NEW_LINE> <DEDENT> self.gh_status = last_msg['status'] <NEW_LINE> self.gh_last_msg = last_msg['body'] <NEW_LINE> self.gh_last_msg_time = last_msg['created_on'] <NEW_LINE> return (self.gh_status, self.gh_last_msg_time, self.gh_last_msg) | Methods for getting current GitHub status. | 62599030d53ae8145f9194e9 |
class HasSettings(Protocol): <NEW_LINE> <INDENT> settings: typing.Dict[str, typing.Any] | Something that quacks like a tornado.web.Application. | 62599030d18da76e235b7991 |
class Providesb(Recipe): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(Providesb, self).__init__() <NEW_LINE> self.homepage = 'dummy' <NEW_LINE> self.repos = { 'stable': Dummy() } <NEW_LINE> <DEDENT> def build(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def verify(self): <NEW_LINE> <INDENT> pass | Dummy recipe does nothing special but have dependency. | 6259903066673b3332c31477 |
class Style(object): <NEW_LINE> <INDENT> __slots__ = ("fg", "bg", "attrs") <NEW_LINE> COLORNAMES = { "black": COLOR_BLACK, "red": COLOR_RED, "green": COLOR_GREEN, "yellow": COLOR_YELLOW, "blue": COLOR_BLUE, "magenta": COLOR_MAGENTA, "cyan": COLOR_CYAN, "white": COLOR_WHITE, } <NEW_LINE> ATTRNAMES = { "blink": A_BLINK, "bold": A_BOLD, "dim": A_DIM, "reverse": A_REVERSE, "standout": A_STANDOUT, "underline": A_UNDERLINE, } <NEW_LINE> def __init__(self, fg, bg, attrs=0): <NEW_LINE> <INDENT> self.fg = fg <NEW_LINE> self.bg = bg <NEW_LINE> self.attrs = attrs <NEW_LINE> <DEDENT> def __call__(self, *args): <NEW_LINE> <INDENT> text = Text() <NEW_LINE> for arg in args: <NEW_LINE> <INDENT> if isinstance(arg, Text): <NEW_LINE> <INDENT> text.extend(arg) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> text.append((self, arg)) <NEW_LINE> <DEDENT> <DEDENT> return text <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.fg == other.fg and self.bg == other.bg and self.attrs == other.attrs <NEW_LINE> <DEDENT> def __neq__(self, other): <NEW_LINE> <INDENT> return self.fg != other.fg or self.bg != other.bg or self.attrs != other.attrs <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> color2name = ("black", "red", "green", "yellow", "blue", "magenta", "cyan", "white") <NEW_LINE> attrs2name = ("blink", "bold", "dim", "reverse", "standout", "underline") <NEW_LINE> return "<%s fg=%s bg=%s attrs=%s>" % ( self.__class__.__name__, color2name[self.fg], color2name[self.bg], "|".join([attrs2name[b] for b in xrange(6) if self.attrs&(1<<b)]) or 0) <NEW_LINE> <DEDENT> def fromstr(cls, value): <NEW_LINE> <INDENT> fg = COLOR_WHITE <NEW_LINE> bg = COLOR_BLACK <NEW_LINE> attrs = 0 <NEW_LINE> parts = value.split(":") <NEW_LINE> if len(parts) > 0: <NEW_LINE> <INDENT> fg = cls.COLORNAMES[parts[0].lower()] <NEW_LINE> if len(parts) > 1: <NEW_LINE> <INDENT> bg = cls.COLORNAMES[parts[1].lower()] <NEW_LINE> if len(parts) > 2: <NEW_LINE> <INDENT> for strattr in parts[2].split("|"): <NEW_LINE> <INDENT> attrs |= cls.ATTRNAMES[strattr.lower()] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return cls(fg, bg, attrs) <NEW_LINE> <DEDENT> fromstr = classmethod(fromstr) <NEW_LINE> def fromenv(cls, name, default): <NEW_LINE> <INDENT> return cls.fromstr(os.environ.get(name, default)) <NEW_LINE> <DEDENT> fromenv = classmethod(fromenv) | Store foreground color, background color and attribute (bold, underlined
etc.). | 6259903026238365f5fadbd9 |
class Flavor_disabled(extensions.ExtensionDescriptor): <NEW_LINE> <INDENT> name = "FlavorDisabled" <NEW_LINE> alias = "OS-FLV-DISABLED" <NEW_LINE> namespace = ("http://docs.openstack.org/compute/ext/" "flavor_disabled/api/v1.1") <NEW_LINE> updated = "2012-08-29T00:00:00+00:00" <NEW_LINE> def get_controller_extensions(self): <NEW_LINE> <INDENT> controller = FlavorDisabledController() <NEW_LINE> extension = extensions.ControllerExtension(self, 'flavors', controller) <NEW_LINE> return [extension] | Support to show the disabled status of a flavor | 62599030be8e80087fbc0103 |
class BookViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = Books.objects.all().order_by('id') <NEW_LINE> serializer_class = BookSerializer <NEW_LINE> permission_classes = [permissions.IsAuthenticatedOrReadOnly] <NEW_LINE> def get_paginated_response(self, data): <NEW_LINE> <INDENT> return Response(data) | API endpoint that allows books to be viewed or edited. | 62599030d4950a0f3b111681 |
class ATTEventHook(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def att_response_hook(self, received_packet, our_response_packet): <NEW_LINE> <INDENT> send_packet = True <NEW_LINE> log.debug("ATT response hook triggered. Received packet: %s Send packet: %s packet: %s" % (received_packet, send_packet, our_response_packet)) <NEW_LINE> return (send_packet, our_response_packet) <NEW_LINE> <DEDENT> def att_prepare_queued_write_hook(self, gatt_handle, offset, data): <NEW_LINE> <INDENT> write_value_to_queue = True <NEW_LINE> log.debug("ATT queued write hook triggered. Write value to attribute pepared write queue" "for attribute: %s on offset: %d with value: %s" % (hex(gatt_handle), offset, data)) <NEW_LINE> return (write_value_to_queue, gatt_handle, offset, data) <NEW_LINE> <DEDENT> def att_execute_queued_write_hook(self, flags): <NEW_LINE> <INDENT> execute = True <NEW_LINE> log.debug("ATT execute write hook triggered. Action: %d" % flags) <NEW_LINE> return (execute, flags) <NEW_LINE> <DEDENT> def att_write_hook(self, gatt_handle, data): <NEW_LINE> <INDENT> write_value_to_attribute = True <NEW_LINE> log.debug("ATT write hook triggered. Write value to attribute: %s value: %s" % (hex(gatt_handle), data)) <NEW_LINE> return (write_value_to_attribute, gatt_handle, data) | ATTEventHook is used by blesuite.pybt.att to allow the user to hook ATT operations triggered by a peer
ATT request. These hooks allow the user to view and/or modify outgoing ATT responses, incoming write requests,
and incoming long write requests (prepared write and execute write). | 62599030d6c5a102081e31ac |
class AnnualSurveyFolderView(OrgnizationsView): <NEW_LINE> <INDENT> grok.context(IAnnualSurveyFolder) <NEW_LINE> grok.template('annual_survey_folder') <NEW_LINE> grok.name('members_view') <NEW_LINE> grok.require('zope2.View') <NEW_LINE> def getLastYear(self): <NEW_LINE> <INDENT> id = (datetime.datetime.today() + datetime.timedelta(-365)).strftime("%Y") <NEW_LINE> return id <NEW_LINE> <DEDENT> def getOrganizationFolder(self): <NEW_LINE> <INDENT> braindata = self.catalog()({'object_provides':IOrgnizationFolder.__identifier__}) <NEW_LINE> if len(braindata) == 0:return None <NEW_LINE> return braindata[0].getObject() <NEW_LINE> <DEDENT> @memoize <NEW_LINE> def allitems(self): <NEW_LINE> <INDENT> folder = self.getOrganizationFolder() <NEW_LINE> mview = getMultiAdapter((folder, self.request),name=u"orgnizations_survey_fullview") <NEW_LINE> return mview.allitems() <NEW_LINE> <DEDENT> def getMemberList(self,start=0,size=10): <NEW_LINE> <INDENT> folder = self.getOrganizationFolder() <NEW_LINE> mview = getMultiAdapter((folder, self.request),name=u"orgnizations_survey_fullview") <NEW_LINE> return mview.getMemberList(start=start,size=size) | 信息公开,年检公告 | 62599030a8ecb033258722a5 |
class HacsRepositoryInfo(HacsBaseException): <NEW_LINE> <INDENT> pass | Raise this when repository info is missing/wrong. | 62599030d10714528d69eecf |
class WebSocketServer(tornado.websocket.WebSocketHandler): <NEW_LINE> <INDENT> def _get_ack(self, message_obj): <NEW_LINE> <INDENT> message = {"event": "ack", "data": message_obj['data']} <NEW_LINE> return json.dumps(message) <NEW_LINE> <DEDENT> def check_origin(self, origin): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def initialize(self, ws_handler_instance): <NEW_LINE> <INDENT> self.ws_handler_instance = ws_handler_instance <NEW_LINE> <DEDENT> def on_close(self,): <NEW_LINE> <INDENT> log.debug('Connection closed.') <NEW_LINE> <DEDENT> def on_message(self, message): <NEW_LINE> <INDENT> log.debug("Message received: {}".format(message)) <NEW_LINE> try: <NEW_LINE> <INDENT> message_obj = json.loads(message) <NEW_LINE> <DEDENT> except ValueError as e: <NEW_LINE> <INDENT> log.warning("Invalid Websocket request received: {}".format(e)) <NEW_LINE> return <NEW_LINE> <DEDENT> self.ws_handler_instance.handle_socket_data(message_obj) <NEW_LINE> self.write_message(self._get_ack(message_obj)) <NEW_LINE> <DEDENT> def open(self): <NEW_LINE> <INDENT> log.debug('New connection opened.') | Tornado WebSocket server listening for Websocket messages. This class
consists of a reference to WebSocketHandler that gets called for each new
message. | 62599030d53ae8145f9194eb |
class choice(HyperoptProxy): <NEW_LINE> <INDENT> def __init__(self, options: list): <NEW_LINE> <INDENT> super().__init__(hyperopt_func=hyperopt.hp.choice, options=options) | :func:`hyperopt.hp.choice` proxy. | 62599030d18da76e235b7992 |
class TestSaltStackIntegration(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testSaltStackIntegration(self): <NEW_LINE> <INDENT> pass | SaltStackIntegration unit test stubs | 6259903066673b3332c31479 |
class InternalObject(object): <NEW_LINE> <INDENT> is_binx_internal = True <NEW_LINE> registered_colls = set() <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.__dict__.update(kwargs) | a namespace class for instance checking for an internally used model object
It is otherwise a normal python object. _Internals are used as medium for
serialization and deserialization and their declarations bound with Collections and enforced by Serializers.
It can be inherited from or used as a Mixin. | 62599030b57a9660fecd2b0c |
class ProductNameField(PillarNameField): <NEW_LINE> <INDENT> @property <NEW_LINE> def _content_iface(self): <NEW_LINE> <INDENT> from lp.registry.interfaces.product import IProduct <NEW_LINE> return IProduct | Field used by IProduct.name. | 6259903056b00c62f0fb394a |
class Rcpod485(device.OpenedRcpod): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> device.OpenedRcpod.__init__(self, *args, **kwargs) <NEW_LINE> self.led1 = self.rc2 <NEW_LINE> self.led2 = self.rc1 <NEW_LINE> self.led1.output().assert_() <NEW_LINE> self.led2.output().assert_() <NEW_LINE> self.txe = self.rd4 <NEW_LINE> self.serialSetTxEnable(self.txe) | Implements the special features of the rcpod-485 board.
This board includes two LEDs and an RS-485 transceiver. | 625990306e29344779b016d9 |
class Screen(object): <NEW_LINE> <INDENT> @property <NEW_LINE> def width(self): <NEW_LINE> <INDENT> return self._width <NEW_LINE> <DEDENT> @width.setter <NEW_LINE> def width(self, value): <NEW_LINE> <INDENT> self._width = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def height(self): <NEW_LINE> <INDENT> return self._height <NEW_LINE> <DEDENT> @height.setter <NEW_LINE> def height(self, value): <NEW_LINE> <INDENT> self._height = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def resolution(self): <NEW_LINE> <INDENT> return self._width * self._height | docstring for Screen. | 62599030796e427e5384f806 |
class BlockReference(object): <NEW_LINE> <INDENT> def __init__(self, name, context, stack, depth): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self._context = context <NEW_LINE> self._stack = stack <NEW_LINE> self._depth = depth <NEW_LINE> <DEDENT> @property <NEW_LINE> def super(self): <NEW_LINE> <INDENT> if self._depth + 1 >= len(self._stack): <NEW_LINE> <INDENT> return self._context.environment. undefined('there is no parent block called %r.' % self.name, name='super') <NEW_LINE> <DEDENT> return BlockReference(self.name, self._context, self._stack, self._depth + 1) <NEW_LINE> <DEDENT> @internalcode <NEW_LINE> def __call__(self): <NEW_LINE> <INDENT> rv = concat(self._stack[self._depth](self._context)) <NEW_LINE> if self._context.eval_ctx.autoescape: <NEW_LINE> <INDENT> rv = Markup(rv) <NEW_LINE> <DEDENT> return rv | One block on a template reference. | 62599030d53ae8145f9194ed |
class ErrorHandler(BaseCGIHandler): <NEW_LINE> <INDENT> os_environ = dict(list(os.environ.items())) <NEW_LINE> def __init__(self,**kw): <NEW_LINE> <INDENT> setup_testing_defaults(kw) <NEW_LINE> BaseCGIHandler.__init__( self, StringIO(''), StringIO(), StringIO(), kw, multithread=True, multiprocess=True ) | Simple handler subclass for testing BaseHandler | 6259903021bff66bcd723cef |
@attr.s(auto_attribs=True, frozen=True, slots=True) <NEW_LINE> class TraceRequestEndParams: <NEW_LINE> <INDENT> method: str <NEW_LINE> url: URL <NEW_LINE> headers: "CIMultiDict[str]" <NEW_LINE> response: ClientResponse | Parameters sent by the `on_request_end` signal | 625990301d351010ab8f4ba3 |
class AdbSmartSocketClient(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def connect(self, port=5037): <NEW_LINE> <INDENT> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> sock.connect(('127.0.0.1', port)) <NEW_LINE> self.sock = sock <NEW_LINE> <DEDENT> def select_service(self, service): <NEW_LINE> <INDENT> message = '%04x%s' % (len(service), service) <NEW_LINE> self.sock.send(message.encode('ascii')) <NEW_LINE> status = self._read_exactly(4) <NEW_LINE> if status == b'OKAY': <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif status == b'FAIL': <NEW_LINE> <INDENT> reason_len = int(self._read_exactly(4), 16) <NEW_LINE> reason = self._read_exactly(reason_len).decode('ascii') <NEW_LINE> raise SelectServiceError(reason) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception('Unrecognized status=%s' % (status)) <NEW_LINE> <DEDENT> <DEDENT> def _read_exactly(self, num_bytes): <NEW_LINE> <INDENT> buf = b'' <NEW_LINE> while len(buf) < num_bytes: <NEW_LINE> <INDENT> new_buf = self.sock.recv(num_bytes) <NEW_LINE> buf += new_buf <NEW_LINE> <DEDENT> return buf | Implements the smartsockets system defined by:
https://android.googlesource.com/platform/system/core/+/master/adb/protocol.txt | 62599030711fe17d825e14e0 |
class DeleteMiembro(MiembroMixin, DeleteView): <NEW_LINE> <INDENT> template_name = 'miembros/delete_confirm.html' <NEW_LINE> @method_decorator(login_required) <NEW_LINE> def dispatch(self, *args, **kwargs): <NEW_LINE> <INDENT> return super(DeleteMiembro, self).dispatch(*args, **kwargs) <NEW_LINE> <DEDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super(DeleteMiembro, self).get_context_data(**kwargs) <NEW_LINE> miembro = Miembro.objects.get(pk=self.kwargs['pk']) <NEW_LINE> context['miembro'] = Miembro <NEW_LINE> context['proyecto'] = Proyecto.objects.get(pk=miembro.proyecto.pk) <NEW_LINE> return context <NEW_LINE> <DEDENT> def delete(self, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return super(DeleteMiembro, self).delete( self, *args, **kwargs ) <NEW_LINE> <DEDENT> except ProtectedError as e: <NEW_LINE> <INDENT> kwargs = super(DeleteMiembro, self).get_context_data(**kwargs) <NEW_LINE> miembro = Miembro.objects.get(pk=self.kwargs['pk']) <NEW_LINE> url = reverse('miembros_listar', kwargs={'pk':miembro.proyecto.pk}) <NEW_LINE> return HttpResponseRedirect(url) <NEW_LINE> <DEDENT> <DEDENT> def get_success_url(self, **kwargs): <NEW_LINE> <INDENT> kwargs = super(DeleteMiembro, self).get_context_data(**kwargs) <NEW_LINE> miembro = Miembro.objects.get(pk=self.kwargs['pk']) <NEW_LINE> return reverse('miembros_listar',args=[miembro.proyecto.pk]) | *Vista Basada en Clase para eliminar clientes*:
+ *template_name*: nombre del template a ser rendirizado
+ *success_url: url a ser redireccionada en caso de exito* | 62599030ec188e330fdf991e |
class FlowProperty(db.Property): <NEW_LINE> <INDENT> data_type = Flow <NEW_LINE> def get_value_for_datastore(self, model_instance): <NEW_LINE> <INDENT> flow = super(FlowProperty, self).get_value_for_datastore(model_instance) <NEW_LINE> return db.Blob(pickle.dumps(flow)) <NEW_LINE> <DEDENT> def make_value_from_datastore(self, value): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return pickle.loads(value) <NEW_LINE> <DEDENT> def validate(self, value): <NEW_LINE> <INDENT> if value is not None and not isinstance(value, Flow): <NEW_LINE> <INDENT> raise BadValueError('Property %s must be convertible ' 'to a FlowThreeLegged instance (%s)' % (self.name, value)) <NEW_LINE> <DEDENT> return super(FlowProperty, self).validate(value) <NEW_LINE> <DEDENT> def empty(self, value): <NEW_LINE> <INDENT> return not value | App Engine datastore Property for Flow.
Utility property that allows easy storage and retreival of an
oauth2client.Flow | 62599030a8ecb033258722a9 |
class SparseCoefMixin: <NEW_LINE> <INDENT> def densify(self): <NEW_LINE> <INDENT> msg = "Estimator, %(name)s, must be fitted before densifying." <NEW_LINE> check_is_fitted(self, msg=msg) <NEW_LINE> if sp.issparse(self.coef_): <NEW_LINE> <INDENT> self.coef_ = self.coef_.toarray() <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def sparsify(self): <NEW_LINE> <INDENT> msg = "Estimator, %(name)s, must be fitted before sparsifying." <NEW_LINE> check_is_fitted(self, msg=msg) <NEW_LINE> self.coef_ = sp.csr_matrix(self.coef_) <NEW_LINE> return self | Mixin for converting coef_ to and from CSR format.
L1-regularizing estimators should inherit this. | 625990308e05c05ec3f6f6a1 |
class ShaderProgram(): <NEW_LINE> <INDENT> def __init__(self, context, modules): <NEW_LINE> <INDENT> self.stages = [] <NEW_LINE> for stage, spirv in modules.items(): <NEW_LINE> <INDENT> if not isinstance(spirv, bytes): <NEW_LINE> <INDENT> raise TypeError("shader must be a bytes object") <NEW_LINE> <DEDENT> module = ShaderModule(context, spirv) <NEW_LINE> self.stages.append(PipelineShaderStage(module, stage)) | ShaderProgram
A `ShaderProgram` embed all `ShaderModule` of a `Pipeline`. | 62599030d164cc6175821ffe |
class QueriesMixinFactory(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def extend(cls, client, querybuilders): <NEW_LINE> <INDENT> class QueriesMixin(object): <NEW_LINE> <INDENT> builders = {} <NEW_LINE> def _getqueries(self): <NEW_LINE> <INDENT> if not hasattr(self, '_queries'): <NEW_LINE> <INDENT> self._queries = Queries(self, self.builders) <NEW_LINE> <DEDENT> return self._queries <NEW_LINE> <DEDENT> queries = property(fget=_getqueries) <NEW_LINE> <DEDENT> class Queries(object): <NEW_LINE> <INDENT> def __init__(self, client, builders): <NEW_LINE> <INDENT> self.client = client <NEW_LINE> self.builders = builders <NEW_LINE> <DEDENT> def __getattr__(self, attribute): <NEW_LINE> <INDENT> if attribute not in self.builders: <NEW_LINE> <INDENT> raise AttributeError(attribute) <NEW_LINE> <DEDENT> return QueryTask(self.client, self.builders[attribute]) <NEW_LINE> <DEDENT> <DEDENT> class QueryTask(object): <NEW_LINE> <INDENT> def __init__(self, client, builder): <NEW_LINE> <INDENT> self.builder = builder <NEW_LINE> self.client = client <NEW_LINE> <DEDENT> def build(self, **kwargs): <NEW_LINE> <INDENT> self.query = self.builder.build(**kwargs) <NEW_LINE> return self <NEW_LINE> <DEDENT> def execute(self, database): <NEW_LINE> <INDENT> if self.query is None: <NEW_LINE> <INDENT> raise UnbuiltQueryError('{0} query task does not have a built query.'.format(self.builder.__name__)) <NEW_LINE> <DEDENT> response = self.client.execute(database, self.query) <NEW_LINE> results = [t for t in response.primary_results if t.table_name == "PrimaryResult"] <NEW_LINE> result = results[0].to_dataframe() if results is not None and len(results) == 1 else None <NEW_LINE> result = self.builder.postprocess(result) <NEW_LINE> return SimpleNamespace(raw=response, result=result) <NEW_LINE> <DEDENT> <DEDENT> QueriesMixin.builders = { qb.name : qb for qb in querybuilders } if querybuilders is not None else {} <NEW_LINE> return MixinFactory.extend(client, QueriesMixin) | Creates a QueriesMixin from a list of queries. | 6259903030c21e258be99898 |
class TestV1ObjectFieldSelector(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testV1ObjectFieldSelector(self): <NEW_LINE> <INDENT> model = k8sv1.models.v1_object_field_selector.V1ObjectFieldSelector() | V1ObjectFieldSelector unit test stubs | 62599030287bf620b6272c73 |
class GetContactsWithQueryResultSet(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) <NEW_LINE> <DEDENT> def get_AccessToken(self): <NEW_LINE> <INDENT> return self._output.get('AccessToken', None) <NEW_LINE> <DEDENT> def get_ContactID(self): <NEW_LINE> <INDENT> return self._output.get('ContactID', None) <NEW_LINE> <DEDENT> def get_Link(self): <NEW_LINE> <INDENT> return self._output.get('Link', None) | A ResultSet with methods tailored to the values returned by the GetContactsWithQuery Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution. | 625990308c3a8732951f75e4 |
class Change(BaseHandler): <NEW_LINE> <INDENT> _validator_fields = [ Field('shopname', T_STR), Field('location', T_STR), Field('address', T_STR), Field('telephone', T_STR), Field('longitude', T_FLOAT), Field('latitude', T_FLOAT), Field('logo_url', T_STR), Field('head_img', T_STR), Field('city', T_STR), Field('province', T_STR), Field('provinceid', T_STR), ] <NEW_LINE> def update_ext(self, data): <NEW_LINE> <INDENT> user_ext = UserExt(uid = int(self.user.userid)) <NEW_LINE> user_ext.head_img = data.get('head_img') <NEW_LINE> user_ext.logo_url = data.get('logo_url') <NEW_LINE> user_ext.contact = data.get('telephone', '') <NEW_LINE> apcli('bindUserExt', user_ext) <NEW_LINE> <DEDENT> def update_apollo(self, data): <NEW_LINE> <INDENT> val = {} <NEW_LINE> for k in ('telephone', 'shopname', 'longitude', 'latitude'): <NEW_LINE> <INDENT> if data[k]: <NEW_LINE> <INDENT> val[k] = data[k] <NEW_LINE> <DEDENT> <DEDENT> if data['address'] or data['location']: <NEW_LINE> <INDENT> addr = ((data['location'] or '') + (data['address'] or '')) <NEW_LINE> if not addr.startswith(self._user.city or ''): <NEW_LINE> <INDENT> addr = (self._user.city or '') + addr <NEW_LINE> <DEDENT> val['businessaddr'] = val['address'] = addr <NEW_LINE> <DEDENT> if not val:return <NEW_LINE> apcli_ex('updateUser', int(self.user.userid), User(**val)) <NEW_LINE> <DEDENT> _base_err = '修改用户信息失败' <NEW_LINE> @check(['login', 'validator']) <NEW_LINE> def POST(self): <NEW_LINE> <INDENT> data = self.validator.data <NEW_LINE> values = {k:v for k, v in data.iteritems() if v is not None} <NEW_LINE> if not values: <NEW_LINE> <INDENT> return self.write(success({})) <NEW_LINE> <DEDENT> userid = int(self.user.userid) <NEW_LINE> user = apcli_ex('findUserBriefById', userid) <NEW_LINE> if not user: <NEW_LINE> <INDENT> user = UserBrief(city='', uid=userid, province='') <NEW_LINE> <DEDENT> self._user = user <NEW_LINE> if (getattr(config, 'CHANGE_SAME_PROVINCE', True) and user.province and data['province'] and user.province != data['province']): <NEW_LINE> <INDENT> raise ParamError('不能修改所在省') <NEW_LINE> <DEDENT> self.update_ext(data) <NEW_LINE> self.update_apollo(data) <NEW_LINE> return self.write(success({})) | 修改用户信息 | 62599030be8e80087fbc0109 |
class HKVError(Exception): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def for_name(cls, name): <NEW_LINE> <INDENT> desc = ERRORS[name] <NEW_LINE> return cls(desc[0], name, desc[1]) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def for_code(cls, code): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> name, description = ERROR_CODES[code] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> name, description = '???', 'Unknown error?!' <NEW_LINE> <DEDENT> return cls(code, name, description) <NEW_LINE> <DEDENT> def __init__(self, code, name, message): <NEW_LINE> <INDENT> super(HKVError, self).__init__('code %s (%s): %s' % (code, name, message)) <NEW_LINE> self.code = code <NEW_LINE> self.name = name | HKVError(code, name, message) -> new instance
General exception for this module.
code is a numeric error code; name is a symbolic name for the error;
message is a human-readable description of the error; the three are
combined into the final exception message by the constructor. Users are
encouraged to use the factory functions provided on the class instead of
calling the constructor directly.
The "code" and "name" constructor parameters are stored in same-named
instance attributes. | 625990304e696a045264e668 |
class ISolgemaFullcalendarEvents(Interface): <NEW_LINE> <INDENT> pass | Solgema Fullcalendar update view interface | 6259903030c21e258be99899 |
class Person: <NEW_LINE> <INDENT> def __init__(self, fname, lname, birthyr): <NEW_LINE> <INDENT> self.fname = fname <NEW_LINE> self.lname = lname <NEW_LINE> self.birthyr = birthyr <NEW_LINE> <DEDENT> def greetings(self): <NEW_LINE> <INDENT> greet = "Hello and Welcom, " + self.fname + "." <NEW_LINE> return greet <NEW_LINE> <DEDENT> def age(self): <NEW_LINE> <INDENT> today = datetime.date.today() <NEW_LINE> age = today.year - int(self.birthyr) <NEW_LINE> return age | A model of a person | 62599030ac7a0e7691f73575 |
class ISettlement(Interface): <NEW_LINE> <INDENT> pass | Settlement Type
| 6259903096565a6dacd2d7d5 |
class ArchiveHeader(NetAppObject): <NEW_LINE> <INDENT> _data = None <NEW_LINE> @property <NEW_LINE> def data(self): <NEW_LINE> <INDENT> return self._data <NEW_LINE> <DEDENT> @data.setter <NEW_LINE> def data(self, val): <NEW_LINE> <INDENT> if val != None: <NEW_LINE> <INDENT> self.validate('data', val) <NEW_LINE> <DEDENT> self._data = val <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_api_name(): <NEW_LINE> <INDENT> return "archive-header" <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_desired_attrs(): <NEW_LINE> <INDENT> return [ 'data', ] <NEW_LINE> <DEDENT> def describe_properties(self): <NEW_LINE> <INDENT> return { 'data': { 'class': basestring, 'is_list': False, 'required': 'required' }, } | Header that describes information about instances of sampled data.
If the requested timestamp is greater/newer than available in the archives,
we will return the most recent header. | 62599030d18da76e235b7995 |
class ManageUserView(generics.RetrieveUpdateAPIView): <NEW_LINE> <INDENT> serializer_class = UserSerializer <NEW_LINE> authentication_classes = (authentication.TokenAuthentication,) <NEW_LINE> permission_classes = (permissions.IsAuthenticated,) <NEW_LINE> def get_object(self): <NEW_LINE> <INDENT> return self.request.user | Manage the authenticated user. | 625990301d351010ab8f4ba7 |
class PhotoGalleryView(ListView): <NEW_LINE> <INDENT> model = ImagerProfile <NEW_LINE> template_name = 'imager_images/photo_gallery.html' <NEW_LINE> context_object_name = 'data' <NEW_LINE> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super(PhotoGalleryView, self).get_context_data(**kwargs) <NEW_LINE> photos = self.request.user.profile.photo.all() <NEW_LINE> albums = self.request.user.profile.album.all() <NEW_LINE> num_photos = len(photos) <NEW_LINE> num_albums = len(albums) <NEW_LINE> context['data'] = { 'num_photos': num_photos, 'num_albums': num_albums, 'photos': photos, 'albums': albums, } <NEW_LINE> return context | All photos view. | 625990306fece00bbaccca3e |
class ServerUpdateParameters(Model): <NEW_LINE> <INDENT> _attribute_map = { 'sku': {'key': 'sku', 'type': 'Sku'}, 'storage_profile': {'key': 'properties.storageProfile', 'type': 'StorageProfile'}, 'administrator_login_password': {'key': 'properties.administratorLoginPassword', 'type': 'str'}, 'version': {'key': 'properties.version', 'type': 'str'}, 'ssl_enforcement': {'key': 'properties.sslEnforcement', 'type': 'SslEnforcementEnum'}, 'tags': {'key': 'tags', 'type': '{str}'}, } <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(ServerUpdateParameters, self).__init__(**kwargs) <NEW_LINE> self.sku = kwargs.get('sku', None) <NEW_LINE> self.storage_profile = kwargs.get('storage_profile', None) <NEW_LINE> self.administrator_login_password = kwargs.get('administrator_login_password', None) <NEW_LINE> self.version = kwargs.get('version', None) <NEW_LINE> self.ssl_enforcement = kwargs.get('ssl_enforcement', None) <NEW_LINE> self.tags = kwargs.get('tags', None) | Parameters allowd to update for a server.
:param sku: The SKU (pricing tier) of the server.
:type sku: ~azure.mgmt.rdbms.mariadb.models.Sku
:param storage_profile: Storage profile of a server.
:type storage_profile: ~azure.mgmt.rdbms.mariadb.models.StorageProfile
:param administrator_login_password: The password of the administrator
login.
:type administrator_login_password: str
:param version: The version of a server. Possible values include: '5.6',
'5.7'
:type version: str or ~azure.mgmt.rdbms.mariadb.models.ServerVersion
:param ssl_enforcement: Enable ssl enforcement or not when connect to
server. Possible values include: 'Enabled', 'Disabled'
:type ssl_enforcement: str or
~azure.mgmt.rdbms.mariadb.models.SslEnforcementEnum
:param tags: Application-specific metadata in the form of key-value pairs.
:type tags: dict[str, str] | 625990308a43f66fc4bf3215 |
class JWTCookieAuthentication(authentication.BaseAuthentication): <NEW_LINE> <INDENT> User = get_user_model() <NEW_LINE> def authenticate(self, request): <NEW_LINE> <INDENT> if not self.validate_csrf_header(request): <NEW_LINE> <INDENT> raise AuthenticationFailed("Custom header against CSRF attacks is not set") <NEW_LINE> <DEDENT> raw_token = request.COOKIES.get(api_settings.ACCESS_TOKEN_COOKIE_NAME) <NEW_LINE> if raw_token is None: <NEW_LINE> <INDENT> raise AuthenticationFailed("Authorization cookie not set") <NEW_LINE> <DEDENT> validated_token = self.get_validated_token(raw_token) <NEW_LINE> return self.get_user(validated_token), None <NEW_LINE> <DEDENT> def authenticate_header(self, request): <NEW_LINE> <INDENT> return "Custom authentication method" <NEW_LINE> <DEDENT> def validate_csrf_header(self, request): <NEW_LINE> <INDENT> if not settings.is_prod_mode(): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> header = request.META.get('HTTP_X_REQUESTED_WITH') <NEW_LINE> return header == 'XMLHttpRequest' <NEW_LINE> <DEDENT> def get_validated_token(self, raw_token): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return Token(raw_token) <NEW_LINE> <DEDENT> except TokenError as e: <NEW_LINE> <INDENT> raise AuthenticationFailed(str(e)) <NEW_LINE> <DEDENT> <DEDENT> def get_user(self, validated_token): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user_id = validated_token[api_settings.USER_ID_CLAIM] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise AuthenticationFailed('Token contained no recognizable user identification') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> user = self.User.objects.get(**{api_settings.USER_ID_FIELD: user_id}) <NEW_LINE> <DEDENT> except self.User.DoesNotExist: <NEW_LINE> <INDENT> raise AuthenticationFailed('User not found', code='user_not_found') <NEW_LINE> <DEDENT> if not user.is_active: <NEW_LINE> <INDENT> raise AuthenticationFailed('User is inactive', code='user_inactive') <NEW_LINE> <DEDENT> return user | A Django rest authentication class that will:
- Check that requests contains the anti-CSRF custom header
- Validate the JWT token received
- Returns the user | 6259903063f4b57ef00865ba |
class DomesticMelonOrder(AbstractMelonOrder): <NEW_LINE> <INDENT> def __init__(self, species, qty): <NEW_LINE> <INDENT> super(DomesticMelonOrder, self).__init__(species, qty, "domestic", 0.08) | A melon order within the USA. | 62599030d99f1b3c44d06733 |
class linkObj: <NEW_LINE> <INDENT> def __init__(self, link, name): <NEW_LINE> <INDENT> self.url = link <NEW_LINE> self.name = name | A container for relative links and their paired names | 6259903096565a6dacd2d7d6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.