code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class Modem(object): <NEW_LINE> <INDENT> __LOCK_PWR = "PWR" <NEW_LINE> __LOCK_TIMEOUT = 60.0 <NEW_LINE> @classmethod <NEW_LINE> def __lock_name(cls, func): <NEW_LINE> <INDENT> return "%s-%s" % (cls.__name__, func) <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> self.__module = GE910() <NEW_LINE> self.__io = IO() <NEW_LINE> <DEDENT> def switch_on(self): <NEW_LINE> <INDENT> self.start_tx() <NEW_LINE> self.__io.power = IO.LOW <NEW_LINE> self.__io.output_enable = IO.HIGH <NEW_LINE> time.sleep(4) <NEW_LINE> self.__io.on_off = IO.LOW <NEW_LINE> time.sleep(6) <NEW_LINE> self.__io.on_off = IO.HIGH <NEW_LINE> time.sleep(1) <NEW_LINE> <DEDENT> def switch_off(self): <NEW_LINE> <INDENT> end_time = time.time() + 5 <NEW_LINE> while True: <NEW_LINE> <INDENT> if not self.__io.pwmon: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if time.time() > end_time: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> time.sleep(1) <NEW_LINE> <DEDENT> self.__io.output_enable = IO.LOW <NEW_LINE> self.__io.power = IO.HIGH <NEW_LINE> self.__module.end_tx() <NEW_LINE> self.end_tx() <NEW_LINE> <DEDENT> def setup_serial(self): <NEW_LINE> <INDENT> self.__module.setup_serial() <NEW_LINE> <DEDENT> def execute(self, command): <NEW_LINE> <INDENT> return self.__module.execute(command) <NEW_LINE> <DEDENT> def start_tx(self): <NEW_LINE> <INDENT> Lock.acquire(self.__lock_name(Modem.__LOCK_PWR), Modem.__LOCK_TIMEOUT) <NEW_LINE> <DEDENT> def end_tx(self): <NEW_LINE> <INDENT> Lock.release(self.__lock_name(Modem.__LOCK_PWR)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def power(self): <NEW_LINE> <INDENT> return 1 if self.__io.power == IO.LOW else 0 <NEW_LINE> <DEDENT> def __str__(self, *args, **kwargs): <NEW_LINE> <INDENT> return "Modem:{module:%s, io:%s}" % (self.__module, self.__io) | Modem with Telit GE910 and NXP PCA8574 remote 8-bit I/O expander | 62598fa83d592f4c4edbae01 |
class RunStop(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.init_successful = True <NEW_LINE> try: <NEW_LINE> <INDENT> rospy.wait_for_service('pr2_etherCAT/halt_motors', 5) <NEW_LINE> self.halt_motors_client=rospy.ServiceProxy('pr2_etherCAT/halt_motors',Empty) <NEW_LINE> rospy.loginfo("Found halt motors service") <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> rospy.logerr("Cannot find halt motors service") <NEW_LINE> self.init_successful = False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> rospy.wait_for_service('pr2_etherCAT/reset_motors',5) <NEW_LINE> self.reset_motors_client=rospy.ServiceProxy('pr2_etherCAT/reset_motors',Empty) <NEW_LINE> rospy.loginfo("Found reset motors service") <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> rospy.logerr("Cannot find halt motors service") <NEW_LINE> self.init_successful = False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> rospy.wait_for_service('power_board/control2',5) <NEW_LINE> self.power_board_client=rospy.ServiceProxy('power_board/control2',PowerBoardCommand2) <NEW_LINE> rospy.loginfo("Found power_board/control2 service") <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> rospy.logerr("Cannot find power_board/control2 service") <NEW_LINE> self.init_successful = False <NEW_LINE> <DEDENT> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.halt_motors_client(EmptyRequest()) <NEW_LINE> success = [False, False, False] <NEW_LINE> for circuit in CIRCUITS: <NEW_LINE> <INDENT> success[circuit] = self.standby_power(circuit) <NEW_LINE> <DEDENT> if success[0] and success[1] and success[2]: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def start(self): <NEW_LINE> <INDENT> success = [False, False, False] <NEW_LINE> for circuit in CIRCUITS: <NEW_LINE> <INDENT> success[circuit] = self.reset_power(circuit) <NEW_LINE> <DEDENT> if success[0] and success[1] and success[2]: <NEW_LINE> <INDENT> rospy.sleep(2.0) <NEW_LINE> self.reset_motors_client(EmptyRequest()) <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def standby_power(self, circuit): <NEW_LINE> <INDENT> stdby_cmd = PowerBoardCommand2Request() <NEW_LINE> stdby_cmd.circuit = circuit <NEW_LINE> stdby_cmd.command = "stop" <NEW_LINE> return self.power_board_client(stdby_cmd) <NEW_LINE> <DEDENT> def reset_power(self,circuit): <NEW_LINE> <INDENT> reset_cmd = PowerBoardCommand2Request() <NEW_LINE> reset_cmd.circuit = circuit <NEW_LINE> reset_cmd.command = "start" <NEW_LINE> return self.power_board_client(reset_cmd) | Provide utility functions for starting/stopping PR2. | 62598fa8435de62698e9bd29 |
class CanvasGridStyle(HasTraits): <NEW_LINE> <INDENT> x_interval = Int(16) <NEW_LINE> y_interval = Int(16) <NEW_LINE> antialias = Bool(False) <NEW_LINE> line_dash = List([3,2]) <NEW_LINE> line_color = RGBAColor((.73, .83, .86)) <NEW_LINE> line_width = Int(1) <NEW_LINE> visible = Bool(True) | Grid line style settings.
Note: I've made the default y_interval 1 pixel larger to deal with
the aspect ration of the screen pixels. This is almost surely
screen dependent, and we should probably deal with this in a
more intelligent way. | 62598fa876e4537e8c3ef4e1 |
class CompilerProxy(Proxy, SQLCompiler): <NEW_LINE> <INDENT> def as_sql(self, *args, **kwargs): <NEW_LINE> <INDENT> sql, params = self._target.as_sql(*args, **kwargs) <NEW_LINE> if not sql: <NEW_LINE> <INDENT> return sql, params <NEW_LINE> <DEDENT> qn = self.quote_name_unless_alias <NEW_LINE> qn2 = self.connection.ops.quote_name <NEW_LINE> alias = self.query.tables[0] if VERSION < (2, 0) else self.query.base_table <NEW_LINE> from_clause = self.query.alias_map[alias] <NEW_LINE> alias = from_clause.table_alias <NEW_LINE> clause_sql, _ = self.compile(from_clause) <NEW_LINE> clause = ' '.join(['FROM', clause_sql]) <NEW_LINE> index = sql.index(clause) + len(clause) <NEW_LINE> extra_table, extra_params = self.union(self.query.pm_get_extra()) <NEW_LINE> opts = self.query.get_meta() <NEW_LINE> qn2_pk_col = qn2(opts.pk.column) <NEW_LINE> new_sql = [ sql[:index], ' {0} ({1}) {2} ON ({3}.{4} = {2}.{5})'.format( INNER, extra_table, self.query.pm_alias_prefix, qn(alias), qn2_pk_col, qn2_pk_col), ] <NEW_LINE> if index < len(sql): <NEW_LINE> <INDENT> new_sql.append(sql[index:]) <NEW_LINE> <DEDENT> new_sql = ''.join(new_sql) <NEW_LINE> heading_param_count = sql[:index].count('%s') <NEW_LINE> return new_sql, params[:heading_param_count] + extra_params + params[heading_param_count:] <NEW_LINE> <DEDENT> def union(self, querysets): <NEW_LINE> <INDENT> if VERSION < (1, 11, 12) or (2, 0) <= VERSION < (2, 0, 4): <NEW_LINE> <INDENT> result_sql, result_params = [], [] <NEW_LINE> for qs in querysets: <NEW_LINE> <INDENT> sql, params = qs.query.sql_with_params() <NEW_LINE> result_sql.append(sql) <NEW_LINE> result_params.extend(params) <NEW_LINE> <DEDENT> return ' UNION '.join(result_sql), tuple(result_params) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> qs = querysets[0].union(*querysets[1:]) <NEW_LINE> return qs.query.sql_with_params() | A proxy to a compiler. | 62598fa82ae34c7f260ab015 |
class Layer(object): <NEW_LINE> <INDENT> property_definitions = None <NEW_LINE> properties = None <NEW_LINE> @classmethod <NEW_LINE> def create_properties(cls, layer_model, property_class): <NEW_LINE> <INDENT> properties = collections.OrderedDict() <NEW_LINE> for k, v in cls.property_definitions.iteritems(): <NEW_LINE> <INDENT> if k in properties: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if 'options' in v: <NEW_LINE> <INDENT> def create_options_getter(x): <NEW_LINE> <INDENT> return lambda: x['options'] <NEW_LINE> <DEDENT> options_getter = create_options_getter(v) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> options_getter = lambda: None <NEW_LINE> <DEDENT> editor = type_to_editor[v['type']](options_getter) <NEW_LINE> editor.value_range = v.get('range', None) <NEW_LINE> is_bindable = v.get('scale_bindable', False) <NEW_LINE> parameters = { 'property': k, 'label': v['label'], 'icon': v['icon'], 'editor': editor, 'data': layer_model.data, 'scale_bindable': is_bindable } <NEW_LINE> if k in layer_model.data: <NEW_LINE> <INDENT> if (is_bindable and isinstance(layer_model.data[k], collections.Mapping) and 'binding' in layer_model.data[k]): <NEW_LINE> <INDENT> if layer_model.data[k]['binding'] is not None: <NEW_LINE> <INDENT> parameters['scale_binding'] = scales.ScaleBinding( layer_model.data[k]['binding']['data'], layer_model.data[k]['binding']['scale']) <NEW_LINE> <DEDENT> <DEDENT> elif (not is_bindable and isinstance(layer_model.data[k], collections.Mapping) and 'binding' in layer_model.data[k]): <NEW_LINE> <INDENT> layer_model.data[k] = layer_model.data[k]['value'] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if is_bindable: <NEW_LINE> <INDENT> layer_model.data[k] = { 'value': v['default'], 'binding': None } <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> layer_model.data[k] = v['default'] <NEW_LINE> <DEDENT> <DEDENT> properties[k] = property_class(parameters, parent=layer_model) <NEW_LINE> if k == 'name': <NEW_LINE> <INDENT> properties[k].editor.tags.add( editor_type.EditorTags.force_update_after_edit) <NEW_LINE> <DEDENT> <DEDENT> return properties | A layer contains a dictionary with definitions of all available properties.
If a property is missing in one layer it must be added to the data
structure containing its default value. | 62598fa80c0af96317c562b6 |
class BayesianTargetEncodingTransformer(TargetEncodingTransformer): <NEW_LINE> <INDENT> def __init__(self, target, n_splits, cvfold, len_train, l=100, param_dict=None): <NEW_LINE> <INDENT> super().__init__(target, n_splits, cvfold, len_train, param_dict) <NEW_LINE> self.l = l <NEW_LINE> self.agg = ['bayesian_encoding'] <NEW_LINE> <DEDENT> def _encode(self, dataframe, merge_dataframe, key, var, agg, new_features): <NEW_LINE> <INDENT> avg = dataframe[self.var].mean() <NEW_LINE> g = dataframe[key + var].groupby(key)[self.var].agg(['sum', 'count']).reset_index() <NEW_LINE> g.columns = key + ['sum', 'count'] <NEW_LINE> g[new_features[0]] = ((g['sum'] + (self.l * avg).values) / (g['count'] + self.l)) <NEW_LINE> g = change_dtype(g, columns=new_features) <NEW_LINE> merge_dataframe = merge_dataframe.merge(g[key + new_features], on=key, how='left') <NEW_LINE> return merge_dataframe <NEW_LINE> <DEDENT> def _get_feature_names(self, key, var, agg): <NEW_LINE> <INDENT> return ['_'.join([a, str(self.l), v, 'groupby'] + key) for v in var for a in agg] | Example
-------
param_dict = [
{
'key': ['ip','hour'],
}
] | 62598fa8925a0f43d25e7f72 |
class EntropyJudger: <NEW_LINE> <INDENT> def __init__(self, document, least_cnt_threshold=5, solid_rate_threshold=0.018, entropy_threshold=1.92): <NEW_LINE> <INDENT> self._least_cnt_threshold = least_cnt_threshold <NEW_LINE> self._solid_rate_threshold = solid_rate_threshold <NEW_LINE> self._entropy_threshold = entropy_threshold <NEW_LINE> self._indexer = CnTextIndexer(document) <NEW_LINE> <DEDENT> def judge(self, candidate): <NEW_LINE> <INDENT> solid_rate = self._get_solid_rate(candidate) <NEW_LINE> entropy = self._get_entropy(candidate) <NEW_LINE> if solid_rate < self._solid_rate_threshold or entropy < self._entropy_threshold: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def _get_solid_rate(self, candidate): <NEW_LINE> <INDENT> if len(candidate) < 2: <NEW_LINE> <INDENT> return 1.0 <NEW_LINE> <DEDENT> cnt = self._indexer.count(candidate) <NEW_LINE> if cnt < self._least_cnt_threshold: <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDENT> rate = 1.0 <NEW_LINE> for c in candidate: <NEW_LINE> <INDENT> rate *= cnt / self._indexer.char_cnt_map[c] <NEW_LINE> <DEDENT> return math.pow(rate, 1/float(len(candidate))) * math.sqrt(len(candidate)) <NEW_LINE> <DEDENT> def _get_entropy(self, candidate): <NEW_LINE> <INDENT> left_char_dic = WordCountDict() <NEW_LINE> right_char_dic = WordCountDict() <NEW_LINE> candidate_pos_generator = self._indexer.find(candidate) <NEW_LINE> for pos in candidate_pos_generator: <NEW_LINE> <INDENT> c = self._indexer[pos-1] <NEW_LINE> left_char_dic.add(c) <NEW_LINE> c = self._indexer[pos+len(candidate)] <NEW_LINE> right_char_dic.add(c) <NEW_LINE> <DEDENT> previous_total_char_cnt = left_char_dic.count() <NEW_LINE> next_total_char_cnt = right_char_dic.count() <NEW_LINE> previous_entropy = 0.0 <NEW_LINE> next_entropy = 0.0 <NEW_LINE> for char, count in left_char_dic.items(): <NEW_LINE> <INDENT> prob = count / previous_total_char_cnt <NEW_LINE> previous_entropy -= prob * math.log(prob) <NEW_LINE> <DEDENT> for char, count in right_char_dic.items(): <NEW_LINE> <INDENT> prob = count / next_total_char_cnt <NEW_LINE> next_entropy -= prob * math.log(prob) <NEW_LINE> <DEDENT> return min(previous_entropy, next_entropy) | Use entropy and solid rate to judge whether a candidate is a chinese word or not. | 62598fa867a9b606de545eff |
class OuputUnits(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.unitsScaleLoads=1.0 <NEW_LINE> self.unitsLoads='units:[m,kN]' <NEW_LINE> self.vectorScaleLoads=1.0 <NEW_LINE> self.vectorScalePointLoads=1.0 <NEW_LINE> self.unitsScaleDispl=1.0 <NEW_LINE> self.unitsDispl='[m]' <NEW_LINE> self.scaleDispBeamIntForc=(1.0,1.0,1.0) <NEW_LINE> self.scaleDispReactions=(1.0,1.0) <NEW_LINE> self.scaleDispEigenvectors=(1.0,1.0) <NEW_LINE> self.unitsScaleForc=1.0 <NEW_LINE> self.unitsForc='[kN/m]' <NEW_LINE> self.unitsScaleMom=1.0 <NEW_LINE> self.unitsMom='[kN.m/m]' | Unit for the generation of graphic files report files.
:ivar unitsScaleLoads: factor to apply to loads if we want to change
the units (defaults to 1).
:ivar unitsLoads: text to especify the units in which loads are
represented (defaults to 'units:[m,kN]')
:ivar vectorScaleLoads: factor to apply to the vectors length in the
representation of element loads (defaults to 1).
:ivar vectorScalePointLoads: factor to apply to the vectors length in the
representation of nodal loads (defaults to 1).
:ivar unitsScaleDispl: factor to apply to displacements if we want to change
the units (defaults to 1).
:ivar unitsDispl: text to especify the units in which displacements are
represented (defaults to '[m]'
:ivar scaleDispBeamIntForc: tuple (escN,escQ,escM) correponding to the scales
to apply to displays of, respectively, axial forces (N),
shear forces (Q) or bending moments (M) in beam elements
(defaults to (1.0,1.0,1.0))
:ivar scaleDispReactions: tuple (escN,escM) correponding to the scales
to apply to displays of, respectively, forces (F)
or moments (M) in nodal reactions
(defaults to (1.0,1.0))
:ivar scaleDispEigenvectors: tuple (escN,escM) correponding to the scales
to apply to displays of eigenvectors
(defaults to (1.0,1.0))
:ivar unitsScaleForc: factor to apply to internal forces if we want to change
the units (defaults to 1).
:ivar unitsForc: text to especify the units in which forces are
represented (defaults to '[kN/m]')
:ivar unitsScaleMom: factor to apply to internal moments if we want to change
the units (defaults to 1).
:ivar unitsMom: text to especify the units in which bending moments are
represented (defaults to '[kN.m/m]') | 62598fa8f548e778e596b4d8 |
class BGPProfile(Element): <NEW_LINE> <INDENT> typeof = 'bgp_profile' <NEW_LINE> @classmethod <NEW_LINE> def create(cls, name, port=179, external_distance=20, internal_distance=200, local_distance=200, subnet_distance=None): <NEW_LINE> <INDENT> json = {'name': name, 'external': external_distance, 'internal': internal_distance, 'local': local_distance, 'port': port} <NEW_LINE> if subnet_distance: <NEW_LINE> <INDENT> d = [{'distance': distance, 'subnet': subnet.href} for subnet, distance in subnet_distance] <NEW_LINE> json.update(distance_entry=d) <NEW_LINE> <DEDENT> return ElementCreator(cls, json) <NEW_LINE> <DEDENT> @property <NEW_LINE> def port(self): <NEW_LINE> <INDENT> return self.data.get('port') <NEW_LINE> <DEDENT> @property <NEW_LINE> def external_distance(self): <NEW_LINE> <INDENT> return self.data.get('external') <NEW_LINE> <DEDENT> @property <NEW_LINE> def internal_distance(self): <NEW_LINE> <INDENT> return self.data.get('internal') <NEW_LINE> <DEDENT> @property <NEW_LINE> def local_distance(self): <NEW_LINE> <INDENT> return self.data.get('local') <NEW_LINE> <DEDENT> @property <NEW_LINE> def subnet_distance(self): <NEW_LINE> <INDENT> return [(Element.from_href(entry.get('subnet')), entry.get('distance')) for entry in self.data.get('distance_entry')] | A BGP Profile specifies settings specific to an engine level BGP
configuration. A profile specifies engine specific settings such
as distance, redistribution, and aggregation and port.
These settings are always in effect:
* BGP version 4/4+
* No autosummary
* No synchronization
* Graceful restart
Example of creating a custom BGP Profile with default administrative
distances and custom subnet distances::
Network.create(name='inside', ipv4_network='1.1.1.0/24')
BGPProfile.create(
name='bar',
internal_distance=100,
external_distance=200,
local_distance=50,
subnet_distance=[(Network('inside'), 100)]) | 62598fa83539df3088ecc1e8 |
class ZeroEstimator(BaseEstimator): <NEW_LINE> <INDENT> def fit(self, X, y, sample_weight=None): <NEW_LINE> <INDENT> if np.issubdtype(y.dtype, int): <NEW_LINE> <INDENT> self.n_classes = np.unique(y).shape[0] <NEW_LINE> if self.n_classes == 2: <NEW_LINE> <INDENT> self.n_classes = 1 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.n_classes = 1 <NEW_LINE> <DEDENT> <DEDENT> def predict(self, X): <NEW_LINE> <INDENT> check_is_fitted(self, 'n_classes') <NEW_LINE> y = np.empty((X.shape[0], self.n_classes), dtype=np.float64) <NEW_LINE> y.fill(0.0) <NEW_LINE> return y | An estimator that simply predicts zero. | 62598fa8dd821e528d6d8e69 |
@dataclass(frozen=True) <NEW_LINE> class BackendUpdateEnvironments: <NEW_LINE> <INDENT> available_environments: Dict[str, List[str]] | Update the information about the environments on the client, from the informations retrieved from the agents | 62598fa863d6d428bbee26e5 |
class SavedObject(SONManipulator): <NEW_LINE> <INDENT> def will_copy(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def _transform_value(self, value): <NEW_LINE> <INDENT> if isinstance(value, list): <NEW_LINE> <INDENT> return map(self._transform_value, value) <NEW_LINE> <DEDENT> if isinstance(value, dict): <NEW_LINE> <INDENT> if value.get('_class'): <NEW_LINE> <INDENT> cls = resolve_class(value['_class']) <NEW_LINE> return cls(self._transform_dict(value)) <NEW_LINE> <DEDENT> return self._transform_dict(value) <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def _transform_dict(self, object): <NEW_LINE> <INDENT> for (key, value) in object.items(): <NEW_LINE> <INDENT> object[key] = self._transform_value(value) <NEW_LINE> <DEDENT> return object <NEW_LINE> <DEDENT> def transform_outgoing(self, son, collection): <NEW_LINE> <INDENT> return self._transform_value(son) | Сonverts saved documents into class instance, the class name with path of
class module keep in document :_class: parameter e.g.::
{'name': 'John', 'age': 18, '_class': 'my_project.account.User'} -
will convert into class User
Embedded documents will convert, if they have :_class: parameter
TODO: this only works for documents that are in the same database. To fix
this we'll need to add a DatabaseInjector that adds `_db` and then make
use of the optional `database` support for DBRefs. | 62598fa82c8b7c6e89bd36f9 |
class HelperViewTest(unittest.TestCase): <NEW_LINE> <INDENT> layer = INTEGRATION_TESTING <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> self.portal = self.layer['portal'] <NEW_LINE> self.request = self.portal.REQUEST <NEW_LINE> pp = api.portal.get_tool('portal_properties') <NEW_LINE> self.barra_helper = api.content.get_view( name='barra_helper', context=self.portal, request=self.request, ) <NEW_LINE> self.sheet = getattr(pp, 'brasil_gov', None) <NEW_LINE> self.barra_viewlet_js = BarraViewletJs( self.portal, self.request, None, None) <NEW_LINE> ltool = self.portal.portal_languages <NEW_LINE> defaultLanguage = BARRA_JS_DEFAULT_LANGUAGE <NEW_LINE> supportedLanguages = [BARRA_JS_DEFAULT_LANGUAGE, 'en', 'es', 'fr'] <NEW_LINE> ltool.manage_setLanguageSettings(defaultLanguage, supportedLanguages, setUseCombinedLanguageCodes=False) <NEW_LINE> self.ltool = ltool <NEW_LINE> self.ltool.setLanguageBindings() <NEW_LINE> <DEDENT> def test_helper_view_registration(self): <NEW_LINE> <INDENT> view = self.barra_helper.__of__(self.portal) <NEW_LINE> self.assertTrue(view) <NEW_LINE> <DEDENT> def test_helper_view_local(self): <NEW_LINE> <INDENT> self.assertFalse(self.barra_helper.local()) <NEW_LINE> self.sheet.local = True <NEW_LINE> self.assertTrue(self.barra_helper.local()) <NEW_LINE> <DEDENT> def test_helper_false_mostra_barra_remota(self): <NEW_LINE> <INDENT> self.barra_viewlet_js.update() <NEW_LINE> self.assertNotIn(BARRA_LOCAL_HTML, self.barra_viewlet_js.render()) <NEW_LINE> self.assertIn(BARRA_EXTERNA_HTML, self.barra_viewlet_js.render()) <NEW_LINE> <DEDENT> def test_helper_true_mostra_barra_local(self): <NEW_LINE> <INDENT> self.sheet.local = True <NEW_LINE> self.barra_viewlet_js.update() <NEW_LINE> self.assertIn(BARRA_LOCAL_HTML, self.barra_viewlet_js.render()) <NEW_LINE> self.assertNotIn(BARRA_EXTERNA_HTML, self.barra_viewlet_js.render()) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_version(code): <NEW_LINE> <INDENT> return code[code.find('@version'):code.find(' @source')] <NEW_LINE> <DEDENT> def test_js_external_mesma_versao_static(self): <NEW_LINE> <INDENT> from filecmp import cmp <NEW_LINE> import requests <NEW_LINE> barra_js_tmp_location = '/tmp/{0}'.format(BARRA_JS_FILE) <NEW_LINE> headers = { 'Accept-Language': BARRA_JS_DEFAULT_LANGUAGE, 'Cache-Control': 'no-cache', } <NEW_LINE> r = requests.get(BARRA_JS_URL, headers=headers) <NEW_LINE> code = r.text.encode('utf-8') <NEW_LINE> with open(barra_js_tmp_location, 'wb') as output: <NEW_LINE> <INDENT> output.write(code) <NEW_LINE> <DEDENT> iguais = cmp(barra_js_tmp_location, BARRA_JS_STATIC_FILE_LOCATION) <NEW_LINE> msg = ( 'O código da barra foi atualizado ({0}); ' 'rode o buildout para atualizar a cópia local' ) <NEW_LINE> self.assertTrue(iguais, msg.format(self.get_version(code))) | Caso de teste da Browser View BarraHelper | 62598fa86aa9bd52df0d4dfd |
class TestRunner: <NEW_LINE> <INDENT> def __init__(self, executable: str, args: Sequence[str], tests: Iterable[Test]): <NEW_LINE> <INDENT> self._executable: str = executable <NEW_LINE> self._args: Sequence[str] = args <NEW_LINE> self._tests: List[Test] = list(tests) <NEW_LINE> <DEDENT> async def run_tests(self) -> None: <NEW_LINE> <INDENT> for idx, test in enumerate(self._tests, 1): <NEW_LINE> <INDENT> total = str(len(self._tests)) <NEW_LINE> test_counter = f'Test {idx:{len(total)}}/{total}' <NEW_LINE> _LOG.info('%s: [ RUN] %s', test_counter, test.name) <NEW_LINE> command = [self._executable, test.file_path, *self._args] <NEW_LINE> if self._executable.endswith('.py'): <NEW_LINE> <INDENT> command.insert(0, sys.executable) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> process = await pw_cli.process.run_async(*command) <NEW_LINE> if process.returncode == 0: <NEW_LINE> <INDENT> test.status = TestResult.SUCCESS <NEW_LINE> test_result = 'PASS' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> test.status = TestResult.FAILURE <NEW_LINE> test_result = 'FAIL' <NEW_LINE> _LOG.log(pw_cli.log.LOGLEVEL_STDOUT, '[%s]\n%s', pw_cli.color.colors().bold_white(process.pid), process.output.decode(errors='ignore').rstrip()) <NEW_LINE> _LOG.info('%s: [%s] %s', test_counter, test_result, test.name) <NEW_LINE> <DEDENT> <DEDENT> except subprocess.CalledProcessError as err: <NEW_LINE> <INDENT> _LOG.error(err) <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def all_passed(self) -> bool: <NEW_LINE> <INDENT> return all(test.status is TestResult.SUCCESS for test in self._tests) | Runs unit tests by calling out to a runner script. | 62598fa81f5feb6acb162b55 |
class InputParameterVerificationError(Exception): <NEW_LINE> <INDENT> pass | Самописный Exception. | 62598fa88c0ade5d55dc362b |
class AclOption(models.Model): <NEW_LINE> <INDENT> id = models.PositiveIntegerField(primary_key=True, db_column="auth_option_id", help_text="primary key" ) <NEW_LINE> auth_option = models.CharField(max_length=50, unique=True, help_text="the name of the permission, e.g. 'f_post'" ) <NEW_LINE> is_global = models.PositiveSmallIntegerField( default=0, help_text="this permission can be granted globally (once for all forums)" ) <NEW_LINE> is_local = models.PositiveSmallIntegerField( default=0, help_text="this permission can be granted locally (individual setting for each forum)" ) <NEW_LINE> founder_only = models.PositiveSmallIntegerField( default=0, help_text="only founders can have this permission" ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = u"%sacl_options" % settings.PHPBB_TABLE_PREFIX | List of possible permissions | 62598fa81b99ca400228f4ca |
class ValidateScreenerRule(Rule): <NEW_LINE> <INDENT> consequence = RemoveMatch <NEW_LINE> priority = 64 <NEW_LINE> def when(self, matches, context): <NEW_LINE> <INDENT> ret = [] <NEW_LINE> for screener in matches.named('other', lambda match: 'other.validate.screener' in match.tags): <NEW_LINE> <INDENT> format_match = matches.previous(screener, lambda match: match.name == 'format', 0) <NEW_LINE> if not format_match or matches.input_string[format_match.end:screener.start].strip(seps): <NEW_LINE> <INDENT> ret.append(screener) <NEW_LINE> <DEDENT> <DEDENT> return ret | Validate tag other.validate.screener | 62598fa8e5267d203ee6b840 |
class Attention(tf.layers.Layer): <NEW_LINE> <INDENT> def __init__(self, hidden_size, num_heads, attention_dropout, train): <NEW_LINE> <INDENT> if hidden_size % num_heads != 0: <NEW_LINE> <INDENT> raise ValueError("Hidden size must be evenly divisible by the number of " "heads.") <NEW_LINE> <DEDENT> super(Attention, self).__init__() <NEW_LINE> self.hidden_size = hidden_size <NEW_LINE> self.num_heads = num_heads <NEW_LINE> self.attention_dropout = attention_dropout <NEW_LINE> self.train = train <NEW_LINE> self.q_dense_layer = tf.layers.Dense(hidden_size, use_bias=False, name="q") <NEW_LINE> self.k_dense_layer = tf.layers.Dense(hidden_size, use_bias=False, name="k") <NEW_LINE> self.v_dense_layer = tf.layers.Dense(hidden_size, use_bias=False, name="v") <NEW_LINE> self.output_dense_layer = tf.layers.Dense(hidden_size, use_bias=False, name="output_transform") <NEW_LINE> <DEDENT> def split_heads(self, x): <NEW_LINE> <INDENT> with tf.name_scope("split_heads", values=[]): <NEW_LINE> <INDENT> batch_size = tf.shape(x)[0] <NEW_LINE> length = tf.shape(x)[1] <NEW_LINE> depth = (self.hidden_size // self.num_heads) <NEW_LINE> x = tf.reshape(x, [batch_size, length, self.num_heads, depth]) <NEW_LINE> return tf.transpose(x, [0, 2, 1, 3]) <NEW_LINE> <DEDENT> <DEDENT> def combine_heads(self, x): <NEW_LINE> <INDENT> with tf.name_scope("combine_heads", values=[]): <NEW_LINE> <INDENT> batch_size = tf.shape(x)[0] <NEW_LINE> length = tf.shape(x)[2] <NEW_LINE> x = tf.transpose(x, [0, 2, 1, 3]) <NEW_LINE> return tf.reshape(x, [batch_size, length, self.hidden_size]) <NEW_LINE> <DEDENT> <DEDENT> def call(self, x, y, bias, cache=None): <NEW_LINE> <INDENT> q = self.q_dense_layer(x) <NEW_LINE> k = self.k_dense_layer(y) <NEW_LINE> v = self.v_dense_layer(y) <NEW_LINE> if cache is not None: <NEW_LINE> <INDENT> k = tf.concat([cache["k"], k], axis=1) <NEW_LINE> v = tf.concat([cache["v"], v], axis=1) <NEW_LINE> cache["k"] = k <NEW_LINE> cache["v"] = v <NEW_LINE> <DEDENT> q = self.split_heads(q) <NEW_LINE> k = self.split_heads(k) <NEW_LINE> v = self.split_heads(v) <NEW_LINE> depth = (self.hidden_size // self.num_heads) <NEW_LINE> q *= depth ** -0.5 <NEW_LINE> logits = tf.matmul(q, k, transpose_b=True) <NEW_LINE> logits += bias <NEW_LINE> weights = tf.nn.softmax(logits, name="attention_weights") <NEW_LINE> if self.train: <NEW_LINE> <INDENT> weights = tf.nn.dropout(weights, 1.0 - self.attention_dropout) <NEW_LINE> <DEDENT> attention_output = tf.matmul(weights, v) <NEW_LINE> attention_output = self.combine_heads(attention_output) <NEW_LINE> attention_output = self.output_dense_layer(attention_output) <NEW_LINE> return attention_output | Multi-headed attention layer. | 62598fa8090684286d593676 |
class BeamSearchDecoderOutput( collections.namedtuple( "BeamSearchDecoderOutput", ("scores", "predicted_ids", "parent_ids") ) ): <NEW_LINE> <INDENT> pass | Outputs of a `BeamSearchDecoder` step.
Contains:
- `scores`: The scores for this step, which are the log probabilities
over the output vocabulary, possibly penalized by length and attention
coverage.
A `float32` `Tensor` of shape `[batch_size, beam_width, vocab_size]`.
- `predicted_ids`: The token IDs predicted for this step.
A `int32` `Tensor` of shape `[batch_size, beam_width]`.
- `parent_ids`: The indices of the parent beam of each beam.
A `int32` `Tensor` of shape `[batch_size, beam_width]`. | 62598fa8a219f33f346c674c |
class TestFlickrRipper(TestCase): <NEW_LINE> <INDENT> net = True <NEW_LINE> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> if os.environ.get('PYWIKIBOT2_TEST_GUI', '0') != '1': <NEW_LINE> <INDENT> raise unittest.SkipTest('FlickrRipper tests are disabled on Travis-CI') <NEW_LINE> <DEDENT> super(TestFlickrRipper, cls).setUpClass() <NEW_LINE> <DEDENT> def testTkdialog(self): <NEW_LINE> <INDENT> box = flickrripper.Tkdialog('foo', 'tests/data/MP_sounds.png', 'MP_sounds.png') <NEW_LINE> box.run() | Test Tkdialog. | 62598fa8ac7a0e7691f72440 |
class ApiRDFValueReflectionRenderer(api_call_renderers.ApiCallRenderer): <NEW_LINE> <INDENT> args_type = ApiRDFValueReflectionRendererArgs <NEW_LINE> def RenderRDFStruct(self, cls): <NEW_LINE> <INDENT> fields = [] <NEW_LINE> for field_desc in cls.type_infos: <NEW_LINE> <INDENT> repeated = isinstance(field_desc, type_info.ProtoList) <NEW_LINE> if hasattr(field_desc, "delegate"): <NEW_LINE> <INDENT> field_desc = field_desc.delegate <NEW_LINE> <DEDENT> field = { "name": field_desc.name, "index": field_desc.field_number, "repeated": repeated, "dynamic": isinstance(field_desc, type_info.ProtoDynamicEmbedded) } <NEW_LINE> field_type = field_desc.type <NEW_LINE> if field_type is not None: <NEW_LINE> <INDENT> field["type"] = field_type.__name__ <NEW_LINE> <DEDENT> if field_type == rdfvalue.EnumNamedValue: <NEW_LINE> <INDENT> allowed_values = [] <NEW_LINE> for enum_label in sorted(field_desc.enum): <NEW_LINE> <INDENT> enum_value = field_desc.enum[enum_label] <NEW_LINE> allowed_values.append(dict(name=enum_label, value=int(enum_value), doc=enum_value.description)) <NEW_LINE> <DEDENT> field["allowed_values"] = allowed_values <NEW_LINE> <DEDENT> if field_desc.default is not None: <NEW_LINE> <INDENT> if field_type: <NEW_LINE> <INDENT> field_default = field_type(field_desc.default) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> field_default = field_desc.default <NEW_LINE> <DEDENT> field["default"] = api_value_renderers.RenderValue( field_default, with_types=True) <NEW_LINE> <DEDENT> if field_desc.description: <NEW_LINE> <INDENT> field["doc"] = field_desc.description <NEW_LINE> <DEDENT> if field_desc.friendly_name: <NEW_LINE> <INDENT> field["friendly_name"] = field_desc.friendly_name <NEW_LINE> <DEDENT> if field_desc.labels: <NEW_LINE> <INDENT> field["labels"] = [rdfvalue.SemanticDescriptor.Labels.reverse_enum[x] for x in field_desc.labels] <NEW_LINE> <DEDENT> fields.append(field) <NEW_LINE> <DEDENT> return dict(name=cls.__name__, doc=cls.__doc__ or "", fields=fields, kind="struct") <NEW_LINE> <DEDENT> def RenderPrimitiveRDFValue(self, cls): <NEW_LINE> <INDENT> return dict(name=cls.__name__, doc=cls.__doc__ or "", kind="primitive") <NEW_LINE> <DEDENT> def RenderType(self, cls): <NEW_LINE> <INDENT> if aff4.issubclass(cls, rdfvalue.RDFStruct): <NEW_LINE> <INDENT> return self.RenderRDFStruct(cls) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.RenderPrimitiveRDFValue(cls) <NEW_LINE> <DEDENT> <DEDENT> def Render(self, args, token=None): <NEW_LINE> <INDENT> _ = token <NEW_LINE> if self.args_type: <NEW_LINE> <INDENT> rdfvalue_class = rdfvalue.RDFValue.classes[args.type] <NEW_LINE> return self.RenderType(rdfvalue_class) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> results = {} <NEW_LINE> for cls in rdfvalue.RDFValue.classes.values(): <NEW_LINE> <INDENT> if aff4.issubclass(cls, rdfvalue.RDFValue): <NEW_LINE> <INDENT> results[cls.__name__] = self.RenderType(cls) <NEW_LINE> <DEDENT> <DEDENT> return results | Renders descriptor of a given RDFValue type. | 62598fa8d58c6744b42dc270 |
class RouteDependency(object): <NEW_LINE> <INDENT> def __init__(self, model_class, primary_key_elements): <NEW_LINE> <INDENT> self.model_class = model_class <NEW_LINE> self.primary_key_elements = primary_key_elements <NEW_LINE> <DEDENT> def __call__(self, context, request): <NEW_LINE> <INDENT> return (self.model_class, dict((pk, request.matchdict[element]) for element, pk in self.primary_key_elements.iteritems()) ) | Model dependency based on matched route segments.
Use to specify the relationships between the matched route segment elements
and the column names of the model primary keys.
For example, for a view where the route pattern `r'/users/{user_id}'`,
and the `user_id` element is related to the `id` column of the `User`
model, the dependency can be written as:
::
@view_config(
decorator=cache_factory(depends_on=[
RouteDependency(User, {'user_id': 'id'}),
])
def user_view(context, request):
pass
When a request in received, the model instance identity will be generated
by matched route segment elements (the matchdict items). For a request for
`/users/sue`, it would generate:
::
dependency(request) --> {'id': 'sue'} | 62598fa8a8370b77170f0310 |
class AutoCompleteSelectWidget(forms.widgets.TextInput): <NEW_LINE> <INDENT> add_link = None <NEW_LINE> def __init__(self, channel, help_text = u'', show_help_text = True, plugin_options = {}, *args, **kwargs): <NEW_LINE> <INDENT> self.plugin_options = plugin_options <NEW_LINE> super(forms.widgets.TextInput, self).__init__(*args, **kwargs) <NEW_LINE> self.channel = channel <NEW_LINE> self.help_text = help_text <NEW_LINE> self.show_help_text = show_help_text <NEW_LINE> <DEDENT> def render(self, name, value, attrs=None): <NEW_LINE> <INDENT> value = value or '' <NEW_LINE> final_attrs = self.build_attrs(attrs) <NEW_LINE> self.html_id = final_attrs.pop('id', name) <NEW_LINE> current_repr = '' <NEW_LINE> initial = None <NEW_LINE> lookup = get_lookup(self.channel) <NEW_LINE> if value: <NEW_LINE> <INDENT> objs = lookup.get_objects([value]) <NEW_LINE> try: <NEW_LINE> <INDENT> obj = objs[0] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> raise Exception("%s cannot find object:%s" % (lookup, value)) <NEW_LINE> <DEDENT> current_repr = lookup.format_item_display(obj) <NEW_LINE> initial = [current_repr,obj.pk] <NEW_LINE> <DEDENT> if self.show_help_text: <NEW_LINE> <INDENT> help_text = self.help_text <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> help_text = u'' <NEW_LINE> <DEDENT> context = { 'name': name, 'html_id': self.html_id, 'current_id': value, 'current_repr': current_repr, 'help_text': help_text, 'extra_attrs': mark_safe(flatatt(final_attrs)), 'func_slug': self.html_id.replace("-",""), 'add_link': self.add_link, } <NEW_LINE> context.update(plugin_options(lookup,self.channel,self.plugin_options,initial)) <NEW_LINE> context.update(bootstrap()) <NEW_LINE> return mark_safe(render_to_string(('autocompleteselect_%s.html' % self.channel, 'autocompleteselect.html'),context)) <NEW_LINE> <DEDENT> def value_from_datadict(self, data, files, name): <NEW_LINE> <INDENT> got = data.get(name, None) <NEW_LINE> if got: <NEW_LINE> <INDENT> return got <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def id_for_label(self, id_): <NEW_LINE> <INDENT> return '%s_text' % id_ | widget to select a model and return it as text | 62598fa8d486a94d0ba2bf03 |
class get_last_period_usage(Command): <NEW_LINE> <INDENT> ARGS = [ Hex('MeterMacId'), ] | Send the GET_LAST_PERIOD_USAGE command to get the previous period
accumulation data from the RAVEn(TM). | 62598fa830dc7b766599f783 |
class CleanData(Attack): <NEW_LINE> <INDENT> name = 'clean' <NEW_LINE> def __call__(self, model_fn, images_batch_nhwc, y_np): <NEW_LINE> <INDENT> del y_np, model_fn <NEW_LINE> return images_batch_nhwc | Also known as the "null attack". Just returns the unaltered clean image | 62598fa88e7ae83300ee8fd8 |
class TestEnvironmentCatalog(_messages.Message): <NEW_LINE> <INDENT> androidDeviceCatalog = _messages.MessageField('AndroidDeviceCatalog', 1) <NEW_LINE> iosDeviceCatalog = _messages.MessageField('IosDeviceCatalog', 2) <NEW_LINE> networkConfigurationCatalog = _messages.MessageField('NetworkConfigurationCatalog', 3) | A description of a test environment.
Fields:
androidDeviceCatalog: Android devices suitable for running Android
Instrumentation Tests.
iosDeviceCatalog: Supported iOS devices
networkConfigurationCatalog: Supported network configurations | 62598fa867a9b606de545f01 |
class ROSTopicCondition(Condition): <NEW_LINE> <INDENT> def __init__(self, state_name, topic, topic_class, field=None, msgeval=None): <NEW_LINE> <INDENT> Condition.__init__(self, state_name) <NEW_LINE> self._topic = topic <NEW_LINE> self._field = field <NEW_LINE> self._subscriber = rospy.Subscriber(topic, topic_class, self._callback) <NEW_LINE> if msgeval is None: <NEW_LINE> <INDENT> assert field is not None <NEW_LINE> msgeval = rostopic.msgevalgen(field) <NEW_LINE> <DEDENT> self._msgeval = msgeval <NEW_LINE> self._value = None <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<%s topic=%s field=%s>' % (self.__class__.__name__, self._topic, self._field) <NEW_LINE> <DEDENT> def _callback(self, msg): <NEW_LINE> <INDENT> self._value = self._msgeval(msg) <NEW_LINE> <DEDENT> def get_value(self): <NEW_LINE> <INDENT> return self._value | Mirrors a ROS message field of a topic as its value.
Note that this Condition's value remains None until a message is received. | 62598fa84e4d56256637235b |
class PolyLines(ShapeObject): <NEW_LINE> <INDENT> def __init__(self, points, **attr): <NEW_LINE> <INDENT> self.points = points <NEW_LINE> ShapeObject.__init__(self, attr) <NEW_LINE> <DEDENT> def show(self, window): <NEW_LINE> <INDENT> self.object = visual.curve(pos = map(tuple, self.points), color = window.foreground) | Multiple connected lines | 62598fa8d268445f26639b1e |
class WorkoutLogForm(ModelForm): <NEW_LINE> <INDENT> repetition_unit = ModelChoiceField(queryset=RepetitionUnit.objects.all(), label=_('Unit'), required=False) <NEW_LINE> weight_unit = ModelChoiceField(queryset=WeightUnit.objects.all(), label=_('Unit'), required=False) <NEW_LINE> exercise = ModelChoiceField(queryset=Exercise.objects.all(), label=_('Exercise'), required=False) <NEW_LINE> reps = IntegerField(label=_('Repetitions'), required=False) <NEW_LINE> weight = DecimalField(label=_('Weight'), initial=0, required=False) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = WorkoutLog <NEW_LINE> exclude = ('workout', ) | Helper form for a WorkoutLog.
These fields are re-defined here only to make them optional | 62598fa8656771135c4895b7 |
class FilterWheelDeviceWrapper(DeviceWrapper): <NEW_LINE> <INDENT> def __init__(self, name="arcticfilterwheel", port=0 ): <NEW_LINE> <INDENT> controllerWrapper = ArcticFWActorWrapper( name="arcticFWActorWrapper", ) <NEW_LINE> DeviceWrapper.__init__(self, name=name, stateCallback=None, controllerWrapper=controllerWrapper) <NEW_LINE> <DEDENT> def _makeDevice(self): <NEW_LINE> <INDENT> port = self.port <NEW_LINE> if port is None: <NEW_LINE> <INDENT> raise RuntimeError("Controller port is unknown") <NEW_LINE> <DEDENT> self.debugMsg("_makeDevice, port=%s" % (port,)) <NEW_LINE> self.device = FilterWheelDevice( host="localhost", port=port, ) | !A wrapper for an FilterWheelDevice talking to a fake filter wheel controller
| 62598fa8bd1bec0571e1505e |
class NVB_OT_amt_event_new(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = 'kb.amt_event_new' <NEW_LINE> bl_label = 'Create new animation event' <NEW_LINE> bl_options = {'UNDO'} <NEW_LINE> @classmethod <NEW_LINE> def poll(self, context): <NEW_LINE> <INDENT> return context.object and context.object.type == 'ARMATURE' <NEW_LINE> <DEDENT> def execute(self, context): <NEW_LINE> <INDENT> amt = context.object <NEW_LINE> if not amt: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> event_list = amt.nvb.amt_event_list <NEW_LINE> nvb_utils.amt_event_list_init(amt) <NEW_LINE> name_list = [ev.name for ev in event_list] <NEW_LINE> name_idx = 0 <NEW_LINE> new_name = 'event.{:0>3d}'.format(name_idx) <NEW_LINE> while new_name in name_list: <NEW_LINE> <INDENT> name_idx += 1 <NEW_LINE> new_name = 'event.{:0>3d}'.format(name_idx) <NEW_LINE> <DEDENT> nvb_utils.amt_event_list_item_create(amt, new_name) <NEW_LINE> if amt.animation_data and amt.animation_data.action: <NEW_LINE> <INDENT> nvb_utils.init_amt_event_action(amt, amt.animation_data.action) <NEW_LINE> <DEDENT> return {'FINISHED'} | Add a new event to the event list | 62598fa8a17c0f6771d5c16b |
class TestAdditionalServiceDefinitionRequest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def make_instance(self, include_optional): <NEW_LINE> <INDENT> if include_optional : <NEW_LINE> <INDENT> return AdditionalServiceDefinitionRequest( id = '0' ) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return AdditionalServiceDefinitionRequest( id = '0', ) <NEW_LINE> <DEDENT> <DEDENT> def testAdditionalServiceDefinitionRequest(self): <NEW_LINE> <INDENT> inst_req_only = self.make_instance(include_optional=False) <NEW_LINE> inst_req_and_optional = self.make_instance(include_optional=True) | AdditionalServiceDefinitionRequest unit test stubs | 62598fa82c8b7c6e89bd36fb |
class InvalidFetcherClassName(InvalidFetcherError): <NEW_LINE> <INDENT> pass | Indicates the given fetcher class name cannot be imported. | 62598fa87d847024c075c2fa |
class EllipticCurve: <NEW_LINE> <INDENT> def __init__(self, p, a, b, g, n): <NEW_LINE> <INDENT> self.p = p <NEW_LINE> self.a = a <NEW_LINE> self.b = b <NEW_LINE> self.g = g <NEW_LINE> self.n = n <NEW_LINE> assert pow(2, p - 1, p) == 1 <NEW_LINE> assert (4 * a * a * a + 27 * b * b) % p != 0 <NEW_LINE> assert self.lying_on_curve(g) <NEW_LINE> assert self.multiply(n, g) is None <NEW_LINE> <DEDENT> def lying_on_curve(self, point): <NEW_LINE> <INDENT> if point is None: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> x, y = point <NEW_LINE> return (y * y - x * x * x - self.a * x - self.b) % self.p == 0 <NEW_LINE> <DEDENT> def multiply(self, n, point): <NEW_LINE> <INDENT> if n % self.n == 0 or point is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if n < 0: <NEW_LINE> <INDENT> return self.negative_point(self.multiply(-n, point)) <NEW_LINE> <DEDENT> result = None <NEW_LINE> addend = point <NEW_LINE> while n: <NEW_LINE> <INDENT> if n & 1: <NEW_LINE> <INDENT> result = self.add(result, addend) <NEW_LINE> <DEDENT> addend = self.double_point(addend) <NEW_LINE> n >>= 1 <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def negative_point(self, point): <NEW_LINE> <INDENT> if point is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> x, y = point <NEW_LINE> result = x, -y % self.p <NEW_LINE> assert self.lying_on_curve(result) <NEW_LINE> return result <NEW_LINE> <DEDENT> def add(self, point1, point2): <NEW_LINE> <INDENT> assert self.lying_on_curve(point1) <NEW_LINE> assert self.lying_on_curve(point2) <NEW_LINE> if point1 is None: <NEW_LINE> <INDENT> return point2 <NEW_LINE> <DEDENT> if point2 is None: <NEW_LINE> <INDENT> return point1 <NEW_LINE> <DEDENT> x1, y1 = point1 <NEW_LINE> x2, y2 = point2 <NEW_LINE> if x1 == x2 and y1 != y2: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if x1 == x2: <NEW_LINE> <INDENT> s = (3 * x1 * x1 + self.a) * inverse_mod(2 * y1, self.p) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s = (y1 - y2) * inverse_mod(x1 - x2, self.p) <NEW_LINE> <DEDENT> x3 = s * s - x1 - x2 <NEW_LINE> y3 = s * (x3 - x1) + y1 <NEW_LINE> result = (x3 % self.p, -y3 % self.p) <NEW_LINE> assert self.lying_on_curve(result) <NEW_LINE> return result <NEW_LINE> <DEDENT> def double_point(self, point): <NEW_LINE> <INDENT> return self.add(point, point) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> a = abs(self.a) <NEW_LINE> b = abs(self.b) <NEW_LINE> a_sign = '-' if self.a < 0 else '+' <NEW_LINE> b_sign = '-' if self.b < 0 else '+' <NEW_LINE> return 'y^2 = (x^3 {} {}x {} {}) mod {}'.format(a_sign, a, b_sign, b, self.p) | An elliptic curve over a prime field.
The field is specified by the parameter 'p'.
The curve coefficients are 'a' and 'b'.
The base point of the cyclic subgroup is 'g'.
The order of the subgroup is 'n'. | 62598fa891af0d3eaad39d45 |
class proxytype_(object): <NEW_LINE> <INDENT> def __init__(self,ob): <NEW_LINE> <INDENT> self.ob_ = ob <NEW_LINE> <DEDENT> def __getattr__(self,attr): <NEW_LINE> <INDENT> return self.__dict__.get(attr,self.__dict__['ob_'].__getattr__(attr)) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__dict__['ob_'].__repr__() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.__dict__['ob_'].__str__() | each tuple member is encapsulated within a proxytype_,
having all the attribute requests (except for few) proxied through | 62598fa8167d2b6e312b6ea7 |
class BaseEntity(object): <NEW_LINE> <INDENT> def __init__(self, node): <NEW_LINE> <INDENT> self.node = node <NEW_LINE> <DEDENT> @property <NEW_LINE> def version_number(self): <NEW_LINE> <INDENT> return self.node.version_number <NEW_LINE> <DEDENT> @property <NEW_LINE> def config(self): <NEW_LINE> <INDENT> return self.node.running_config <NEW_LINE> <DEDENT> @property <NEW_LINE> def error(self): <NEW_LINE> <INDENT> return self.node.connection.error <NEW_LINE> <DEDENT> def get_block(self, parent, config='running_config'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> parent = r'^%s$' % parent <NEW_LINE> return self.node.section(parent, config=config) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def configure(self, commands): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.node.config(commands) <NEW_LINE> return True <NEW_LINE> <DEDENT> except (CommandError): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def command_builder(self, string, value=None, default=None, disable=None): <NEW_LINE> <INDENT> if default: <NEW_LINE> <INDENT> return 'default %s' % string <NEW_LINE> <DEDENT> elif disable: <NEW_LINE> <INDENT> return 'no %s' % string <NEW_LINE> <DEDENT> elif value is True: <NEW_LINE> <INDENT> return string <NEW_LINE> <DEDENT> elif value: <NEW_LINE> <INDENT> return '%s %s' % (string, value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'no %s' % string <NEW_LINE> <DEDENT> <DEDENT> def configure_interface(self, name, commands): <NEW_LINE> <INDENT> commands = make_iterable(commands) <NEW_LINE> commands.insert(0, 'interface %s' % name) <NEW_LINE> return self.configure(commands) | Base class for all resources to derive from
This BaseEntity class should not be directly instatiated. It is
designed to be implemented by all resource classes to provide common
methods.
Attributes:
node (Node): The node instance this resource will perform operations
against for configuration
config (Config): Returns an instance of Config with the nodes
current running configuration
error (CommandError): Holds the latest CommandError exception
instance if raised
Args:
node (Node): An instance of Node | 62598fa863b5f9789fe8509b |
class JSON(object): <NEW_LINE> <INDENT> def __init__(self, value): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.value == json.loads(other) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.value != json.loads(other) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return True | Helper object that is equal to any JSON string representing a specific value. | 62598fa867a9b606de545f02 |
class svn_error_t: <NEW_LINE> <INDENT> __swig_setmethods__ = {} <NEW_LINE> __setattr__ = lambda self, name, value: _swig_setattr(self, svn_error_t, name, value) <NEW_LINE> __swig_getmethods__ = {} <NEW_LINE> __getattr__ = lambda self, name: _swig_getattr(self, svn_error_t, name) <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> __swig_setmethods__["apr_err"] = _core.svn_error_t_apr_err_set <NEW_LINE> __swig_getmethods__["apr_err"] = _core.svn_error_t_apr_err_get <NEW_LINE> __swig_getmethods__["message"] = _core.svn_error_t_message_get <NEW_LINE> __swig_setmethods__["child"] = _core.svn_error_t_child_set <NEW_LINE> __swig_getmethods__["child"] = _core.svn_error_t_child_get <NEW_LINE> __swig_setmethods__["pool"] = _core.svn_error_t_pool_set <NEW_LINE> __swig_getmethods__["pool"] = _core.svn_error_t_pool_get <NEW_LINE> __swig_getmethods__["file"] = _core.svn_error_t_file_get <NEW_LINE> __swig_setmethods__["line"] = _core.svn_error_t_line_set <NEW_LINE> __swig_getmethods__["line"] = _core.svn_error_t_line_get <NEW_LINE> def set_parent_pool(self, parent_pool=None): <NEW_LINE> <INDENT> import libsvn.core, weakref <NEW_LINE> self.__dict__["_parent_pool"] = parent_pool or libsvn.core.application_pool; <NEW_LINE> if self.__dict__["_parent_pool"]: <NEW_LINE> <INDENT> self.__dict__["_is_valid"] = weakref.ref( self.__dict__["_parent_pool"]._is_valid) <NEW_LINE> <DEDENT> <DEDENT> def assert_valid(self): <NEW_LINE> <INDENT> if "_is_valid" in self.__dict__: <NEW_LINE> <INDENT> assert self.__dict__["_is_valid"](), "Variable has already been deleted" <NEW_LINE> <DEDENT> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> self.assert_valid() <NEW_LINE> value = _swig_getattr(self, self.__class__, name) <NEW_LINE> members = self.__dict__.get("_members") <NEW_LINE> if members is not None: <NEW_LINE> <INDENT> _copy_metadata_deep(value, members.get(name)) <NEW_LINE> <DEDENT> _assert_valid_deep(value) <NEW_LINE> return value <NEW_LINE> <DEDENT> def __setattr__(self, name, value): <NEW_LINE> <INDENT> self.assert_valid() <NEW_LINE> self.__dict__.setdefault("_members",{})[name] = value <NEW_LINE> return _swig_setattr(self, self.__class__, name, value) <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> this = _core.new_svn_error_t() <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this <NEW_LINE> <DEDENT> __swig_destroy__ = _core.delete_svn_error_t <NEW_LINE> __del__ = lambda self : None; | Proxy of C svn_error_t struct | 62598fa856b00c62f0fb27ea |
class AccountDeleteViewTest(LoginTestMixin, TestCase): <NEW_LINE> <INDENT> user_permissions = ( APP_NAME + '.view_account', APP_NAME + '.delete_account', ) <NEW_LINE> def test_get(self): <NEW_LINE> <INDENT> account = Account.objects.create( user_id='test_user', expires=now(), token='12345', site_id=0, ) <NEW_LINE> self.login() <NEW_LINE> response = self.client.get( reverse(APP_NAME + '_account_delete', kwargs={'pk': account.pk}) ) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> <DEDENT> def test_post(self): <NEW_LINE> <INDENT> account = Account.objects.create( user_id='test_user', expires=now(), token='12345', site_id=0, ) <NEW_LINE> self.assertTrue(account.active) <NEW_LINE> self.login() <NEW_LINE> response = self.client.post( reverse(APP_NAME + '_account_delete', kwargs={'pk': account.pk}), follow=True, ) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> with self.assertRaises(Account.DoesNotExist): <NEW_LINE> <INDENT> account.refresh_from_db() | Tests for the ``AccountDeleteView`` view | 62598fa80c0af96317c562b9 |
class SMSIntegration(BaseIntegration): <NEW_LINE> <INDENT> def test_connection(self, data): <NEW_LINE> <INDENT> errors = {} <NEW_LINE> fields = ["from_phone", "to_phone", "twilio_account_sid", "twilio_auth_token"] <NEW_LINE> for field in fields: <NEW_LINE> <INDENT> if not data.get(field): <NEW_LINE> <INDENT> errors[field] = [TEST_CONNECTION_REQUIRED] <NEW_LINE> <DEDENT> <DEDENT> if len(errors) > 0: <NEW_LINE> <INDENT> return False, errors <NEW_LINE> <DEDENT> from_phone = data.get("from_phone") <NEW_LINE> to_phone = data.get("to_phone") <NEW_LINE> twilio_account_sid = data.get("twilio_account_sid") <NEW_LINE> twilio_auth_token = data.get("twilio_auth_token") <NEW_LINE> extra = data.get("extra") <NEW_LINE> try: <NEW_LINE> <INDENT> client = twilio.rest.Client(twilio_account_sid, twilio_auth_token) <NEW_LINE> body = "Test Alert! Hello World!" <NEW_LINE> if extra: <NEW_LINE> <INDENT> body = "{} {}".format(body, extra) <NEW_LINE> <DEDENT> client.messages.create(to=to_phone, from_=from_phone, body=body) <NEW_LINE> return True, {} <NEW_LINE> <DEDENT> except Exception as exc: <NEW_LINE> <INDENT> response = {"non_field_errors": [str(exc)]} <NEW_LINE> return False, response <NEW_LINE> <DEDENT> <DEDENT> def send_event(self, alert_fields): <NEW_LINE> <INDENT> from_phone = self.integration_data.get("from_phone") <NEW_LINE> to_phone = self.integration_data.get("to_phone") <NEW_LINE> twilio_account_sid = self.integration_data.get("twilio_account_sid") <NEW_LINE> twilio_auth_token = self.integration_data.get("twilio_auth_token") <NEW_LINE> extra = self.integration_data.get("extra") <NEW_LINE> try: <NEW_LINE> <INDENT> body = "{} alert".format(alert_fields.get("event_type")) <NEW_LINE> if extra: <NEW_LINE> <INDENT> body = '{} {}'.format(body, extra) <NEW_LINE> <DEDENT> if alert_fields.get("originating_ip"): <NEW_LINE> <INDENT> body = "{} from {}".format(body, alert_fields.get("originating_ip")) <NEW_LINE> <DEDENT> if alert_fields.get("cmd"): <NEW_LINE> <INDENT> body = "{} cmd: {}".format(body, alert_fields.get("cmd")) <NEW_LINE> <DEDENT> if len(body) > MAX_SMS_LEN: <NEW_LINE> <INDENT> body = body[:MAX_SMS_LEN] <NEW_LINE> <DEDENT> body = body.encode('ascii', 'replace') <NEW_LINE> client = twilio.rest.Client(twilio_account_sid, twilio_auth_token) <NEW_LINE> client.messages.create(to=to_phone, from_=from_phone, body=body) <NEW_LINE> return {}, None <NEW_LINE> <DEDENT> except Exception as exc: <NEW_LINE> <INDENT> raise IntegrationSendEventError(exc) <NEW_LINE> <DEDENT> <DEDENT> def format_output_data(self, output_data): <NEW_LINE> <INDENT> return output_data | An integration to send SMS messages to a defined phone number on Honeycomb alerts. | 62598fa8cc0a2c111447af47 |
class WBSDefinition(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.swaggerTypes = { 'CodePrefix': 'str', 'GenerateWBSCode': 'bool', 'VerifyUniqueness': 'bool', 'CodeMaskCollection': 'list[WBSCodeMask]' } <NEW_LINE> self.attributeMap = { 'CodePrefix': 'CodePrefix','GenerateWBSCode': 'GenerateWBSCode','VerifyUniqueness': 'VerifyUniqueness','CodeMaskCollection': 'CodeMaskCollection'} <NEW_LINE> self.CodePrefix = None <NEW_LINE> self.GenerateWBSCode = None <NEW_LINE> self.VerifyUniqueness = None <NEW_LINE> self.CodeMaskCollection = None | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62598fa85166f23b2e24330f |
class MovieGenreView(APIView): <NEW_LINE> <INDENT> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> moviegenre = MovieGenre.objects.select_related().get(slug=kwargs['moviegenre_slug']) <NEW_LINE> serializer = MovieGenreSerializer(moviegenre) <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> except MovieGenre.DoesNotExist: <NEW_LINE> <INDENT> return Response(status=status.HTTP_404_NOT_FOUND) | Movie genre api-view | 62598fa8d486a94d0ba2bf05 |
class TimeoutError(RuntimeError): <NEW_LINE> <INDENT> pass | Timeout error of command execution. | 62598fa844b2445a339b690b |
class IndexPage(PageObject): <NEW_LINE> <INDENT> url = 'http://localhost:{}/index.html'.format(PORT) <NEW_LINE> def is_browser_on_page(self): <NEW_LINE> <INDENT> return self.browser.title == 'PyTube.org' <NEW_LINE> <DEDENT> def search(self, phrase): <NEW_LINE> <INDENT> selector = 'input.gsc-input' <NEW_LINE> self.wait_for_element_visibility(selector, 'Search input available') <NEW_LINE> self.q(css=selector).fill(phrase + Keys.ENTER) <NEW_LINE> self.wait_for_element_visibility('.gsc-results', 'Search results shown') | Testing representation of the main page of the site | 62598fa876e4537e8c3ef4e5 |
class TinyMCEWidget(forms.Textarea): <NEW_LINE> <INDENT> class Media: <NEW_LINE> <INDENT> extend = False <NEW_LINE> js = ('//tinymce.cachefly.net/4.0/tinymce.min.js',) <NEW_LINE> <DEDENT> def __init__(self, attrs=None): <NEW_LINE> <INDENT> final_attrs = { 'class': 'tinymce', 'style': 'display: inline-block;' } <NEW_LINE> if attrs is not None: <NEW_LINE> <INDENT> final_attrs.update(attrs) <NEW_LINE> <DEDENT> super(TinyMCEWidget, self).__init__(attrs=final_attrs) <NEW_LINE> <DEDENT> def render(self, name, value, attrs=None): <NEW_LINE> <INDENT> output = super(TinyMCEWidget, self).render(name, value, attrs) <NEW_LINE> return mark_safe(output + "\n<script>tinymce.init({selector: '#%s', menubar:false, statusbar: true, plugins: 'code fullscreen', toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | code fullscreen' });</script>" % attrs['id']) | TinyMCE HTML editor widget | 62598fa8e5267d203ee6b843 |
class PublicUserApiTests(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.client = APIClient() <NEW_LINE> <DEDENT> def test_create_valid_user_success(self): <NEW_LINE> <INDENT> payload = { 'email': 'test@q.com', 'password': 'testpass', 'name': 'Test name' } <NEW_LINE> res = self.client.post(CREATE_USER_URL, payload) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_201_CREATED) <NEW_LINE> user = get_user_model().objects.get(**res.data) <NEW_LINE> self.assertTrue(user.check_password(payload['password'])) <NEW_LINE> self.assertNotIn('password', res.data) <NEW_LINE> <DEDENT> def test_user_exists(self): <NEW_LINE> <INDENT> payload = {'email': 'test@q.com', 'password': 'testpass'} <NEW_LINE> create_user(**payload) <NEW_LINE> res = self.client.post(CREATE_USER_URL, payload) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> def test_password_too_short(self): <NEW_LINE> <INDENT> payload = {'email': 'test@q.com', 'name': 'Test', 'password': 'pw'} <NEW_LINE> res = self.client.post(CREATE_USER_URL, payload) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> user_exists = get_user_model().objects.filter( email=payload['email'] ).exists() <NEW_LINE> self.assertFalse(user_exists) <NEW_LINE> <DEDENT> def test_create_token_for_user(self): <NEW_LINE> <INDENT> payload = {'email': 'test@test.com', 'password': 'testpass'} <NEW_LINE> create_user(**payload) <NEW_LINE> res = self.client.post(TOKEN_URL, payload) <NEW_LINE> self.assertIn('token', res.data) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK) <NEW_LINE> <DEDENT> def test_create_token_invalid_credentials(self): <NEW_LINE> <INDENT> create_user(email='test@test.com', password='testpass') <NEW_LINE> payload = {'email': 'test@test.com', 'password': 'wrong'} <NEW_LINE> res = self.client.post(TOKEN_URL, payload) <NEW_LINE> self.assertNotIn('token', res.data) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> def test_create_token_no_user(self): <NEW_LINE> <INDENT> payload = {'email': 'test@test.com', 'password': 'testpass'} <NEW_LINE> res = self.client.post(TOKEN_URL, payload) <NEW_LINE> self.assertNotIn('token', res.data) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> def test_create_token_missing_field(self): <NEW_LINE> <INDENT> res = self.client.post(TOKEN_URL, {'email': 'one', 'password': ''}) <NEW_LINE> self.assertNotIn('token', res.data) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) | Test the users API (public) | 62598fa8bd1bec0571e1505f |
class RedisConfigForm(BaseForm): <NEW_LINE> <INDENT> name = fields.StringField(validators=[validators.DataRequired(message='请填写容器名称')]) <NEW_LINE> def validate_name(self, field): <NEW_LINE> <INDENT> name = field.data <NEW_LINE> resource = self.resource.data <NEW_LINE> if not resource.get_container(name=name): <NEW_LINE> <INDENT> raise validators.ValidationError(f'[{name}]容器不存在') | redis config的form校验类 | 62598fa88a43f66fc4bf20b4 |
class AndSpec(Specification): <NEW_LINE> <INDENT> def __init__(self, *specs: Specification) -> None: <NEW_LINE> <INDENT> self.specs = specs <NEW_LINE> <DEDENT> def is_satisfied(self, item: Product) -> bool: <NEW_LINE> <INDENT> return all(spec.is_satisfied(item) for spec in self.specs) | Combinator specification - combines multiple specifications into one. | 62598fa84e4d56256637235d |
class NSOperationSyntheticProvider(NSObject.NSObjectSyntheticProvider): <NEW_LINE> <INDENT> def __init__(self, value_obj, internal_dict): <NEW_LINE> <INDENT> super(NSOperationSyntheticProvider, self).__init__(value_obj, internal_dict) <NEW_LINE> self.type_name = "NSOperation" <NEW_LINE> self.register_child_value("private", ivar_name="_private", provider_class=NSOperationInternal.NSOperationInternalSyntheticProvider, summary_function=self.get_private_summary) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_private_summary(provider): <NEW_LINE> <INDENT> return provider.summary() <NEW_LINE> <DEDENT> def summaries_parts(self): <NEW_LINE> <INDENT> return self.private_provider.summaries_parts() | Class representing NSOperation. | 62598fa8435de62698e9bd2e |
class ContentHandlerException(TableauPyException): <NEW_LINE> <INDENT> _message_template = 'An error occurred with ContentHandler' | raised when an exception is thrown by a ContentHandlers | 62598fa87d43ff248742739e |
class NoNetworkError(GeneWikiError): <NEW_LINE> <INDENT> def __init__(self,message = None): <NEW_LINE> <INDENT> super(GeneWikiError,self).__init__(message) | Exception for GeneWiki errors specifically related to network. | 62598fa892d797404e388b01 |
class end_process_keyword(parser.keyword): <NEW_LINE> <INDENT> def __init__(self, sString): <NEW_LINE> <INDENT> parser.keyword.__init__(self, sString) | unique_id = process_statement : end_process_keyword | 62598fa856b00c62f0fb27ec |
class ContainerH5TableDataset(ContainerResolverMixin, AbstractH5TableDataset): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def get_inverse_class(cls): <NEW_LINE> <INDENT> return BuilderH5TableDataset | A reference-resolving dataset for resolving references inside tables
(i.e. compound dtypes) that returns resolved references as Containers | 62598fa8cb5e8a47e493c114 |
class TypeValue(object): <NEW_LINE> <INDENT> pass | A Stub-Object to parse the received data
| 62598fa832920d7e50bc5f8e |
class Rectangle: <NEW_LINE> <INDENT> number_of_instances = 0 <NEW_LINE> print_symbol = "#" <NEW_LINE> def __init__(self, width=0, height=0): <NEW_LINE> <INDENT> self.width = width <NEW_LINE> self.height = height <NEW_LINE> type(self).number_of_instances += 1 <NEW_LINE> <DEDENT> @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> if not isinstance(value, int): <NEW_LINE> <INDENT> raise TypeError("width must be an integer") <NEW_LINE> <DEDENT> if value < 0: <NEW_LINE> <INDENT> raise ValueError("width must be >= 0") <NEW_LINE> <DEDENT> 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> if not isinstance(value, int): <NEW_LINE> <INDENT> raise TypeError("height must be an integer") <NEW_LINE> <DEDENT> if value < 0: <NEW_LINE> <INDENT> raise ValueError("height must be >= 0") <NEW_LINE> <DEDENT> self.__height = value <NEW_LINE> <DEDENT> def area(self): <NEW_LINE> <INDENT> return self.width * self.height <NEW_LINE> <DEDENT> def perimeter(self): <NEW_LINE> <INDENT> if self.width is 0 or self.height is 0: <NEW_LINE> <INDENT> perimeter = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> perimeter = (self.width * 2) + (self.height * 2) <NEW_LINE> <DEDENT> return perimeter <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> string = "" <NEW_LINE> if self.width != 0 and self.height != 0: <NEW_LINE> <INDENT> for i in range(self.height - 1): <NEW_LINE> <INDENT> for j in range(self.width): <NEW_LINE> <INDENT> string += str(self.print_symbol) <NEW_LINE> <DEDENT> string += "\n" <NEW_LINE> <DEDENT> for j in range(self.width): <NEW_LINE> <INDENT> string += str(self.print_symbol) <NEW_LINE> <DEDENT> <DEDENT> return string <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Rectangle(" + str(self.width) + ", " + str(self.height) + ")" <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> print("Bye rectangle...") <NEW_LINE> type(self).number_of_instances -= 1 <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def bigger_or_equal(rect_1, rect_2): <NEW_LINE> <INDENT> if not isinstance(rect_1, Rectangle): <NEW_LINE> <INDENT> raise TypeError("rect_1 must be an instance of Rectangle") <NEW_LINE> <DEDENT> if not isinstance(rect_2, Rectangle): <NEW_LINE> <INDENT> raise TypeError("rect_2 must be an instance of Rectangle") <NEW_LINE> <DEDENT> if rect_1.area() >= rect_2.area(): <NEW_LINE> <INDENT> return rect_1 <NEW_LINE> <DEDENT> return rect_2 <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def square(cls, size=0): <NEW_LINE> <INDENT> return cls(size, size) | Represent an empty rectangle.
Attributes:
number_of _instances (int): number of rectangles created.
print_symbol (any): symbol used as rectangle represetnation. | 62598fa823849d37ff850fed |
class ROSBagException(Exception): <NEW_LINE> <INDENT> def __init__(self, value=None): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> self.args = (value,) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.value | Base class for exceptions in rosbag. | 62598fa83539df3088ecc1ed |
class TestBasicPolicyNegative(BasePolicyTest): <NEW_LINE> <INDENT> _interface = 'json' <NEW_LINE> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> super(TestBasicPolicyNegative, cls).setUpClass() <NEW_LINE> <DEDENT> def runTest(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @test.attr(type=['sanity','ci_sanity', 'vcenter']) <NEW_LINE> @preposttest_wrapper <NEW_LINE> def test_remove_policy_with_ref(self): <NEW_LINE> <INDENT> vn1_name = 'vn4' <NEW_LINE> vn1_subnets = ['10.1.1.0/24'] <NEW_LINE> policy_name = 'policy1' <NEW_LINE> rules = [ { 'direction': '<>', 'simple_action': 'pass', 'protocol': 'icmp', 'source_network': vn1_name, 'dest_network': vn1_name, }, ] <NEW_LINE> policy_fixture = self.useFixture( PolicyFixture( policy_name=policy_name, rules_list=rules, inputs=self.inputs, connections=self.connections)) <NEW_LINE> vn1_fixture = self.useFixture( VNFixture( project_name=self.inputs.project_name, connections=self.connections, vn_name=vn1_name, inputs=self.inputs, subnets=vn1_subnets, policy_objs=[ policy_fixture.policy_obj])) <NEW_LINE> assert vn1_fixture.verify_on_setup() <NEW_LINE> ret = policy_fixture.verify_on_setup() <NEW_LINE> if ret['result'] == False: <NEW_LINE> <INDENT> self.logger.error( "Policy %s verification failed after setup" % policy_name) <NEW_LINE> assert ret['result'], ret['msg'] <NEW_LINE> <DEDENT> self.logger.info( "Done with setup and verification, moving onto test ..") <NEW_LINE> policy_removal = True <NEW_LINE> pol_id = None <NEW_LINE> if self.quantum_h: <NEW_LINE> <INDENT> policy_removal = self.quantum_h.delete_policy(policy_fixture.get_id()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.vnc_lib.network_policy_delete(id=policy_fixture.get_id()) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> policy_removal = False <NEW_LINE> <DEDENT> <DEDENT> self.assertFalse( policy_removal, 'Policy removal succeed as not expected since policy is referenced with VN') <NEW_LINE> return True | Negative tests | 62598fa856ac1b37e6302125 |
class EditorCalltipsQScintillaPage(ConfigurationPageBase, Ui_EditorCalltipsQScintillaPage): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(EditorCalltipsQScintillaPage, self).__init__() <NEW_LINE> self.setupUi(self) <NEW_LINE> self.setObjectName("EditorCalltipsQScintillaPage") <NEW_LINE> ctContext = Preferences.getEditor("CallTipsStyle") <NEW_LINE> if ctContext == QsciScintilla.CallTipsNoContext: <NEW_LINE> <INDENT> self.ctNoContextButton.setChecked(True) <NEW_LINE> <DEDENT> elif ctContext == QsciScintilla.CallTipsNoAutoCompletionContext: <NEW_LINE> <INDENT> self.ctNoAutoCompletionButton.setChecked(True) <NEW_LINE> <DEDENT> elif ctContext == QsciScintilla.CallTipsContext: <NEW_LINE> <INDENT> self.ctContextButton.setChecked(True) <NEW_LINE> <DEDENT> <DEDENT> def save(self): <NEW_LINE> <INDENT> if self.ctNoContextButton.isChecked(): <NEW_LINE> <INDENT> Preferences.setEditor( "CallTipsStyle", QsciScintilla.CallTipsNoContext) <NEW_LINE> <DEDENT> elif self.ctNoAutoCompletionButton.isChecked(): <NEW_LINE> <INDENT> Preferences.setEditor( "CallTipsStyle", QsciScintilla.CallTipsNoAutoCompletionContext) <NEW_LINE> <DEDENT> elif self.ctContextButton.isChecked(): <NEW_LINE> <INDENT> Preferences.setEditor( "CallTipsStyle", QsciScintilla.CallTipsContext) | Class implementing the QScintilla Calltips configuration page. | 62598fa8462c4b4f79dbb946 |
class LeaveOneOut(object): <NEW_LINE> <INDENT> def __init__(self, n, indices=True): <NEW_LINE> <INDENT> self.n = n <NEW_LINE> self.indices = indices <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> n = self.n <NEW_LINE> for i in xrange(n): <NEW_LINE> <INDENT> test_index = np.zeros(n, dtype=np.bool) <NEW_LINE> test_index[i] = True <NEW_LINE> train_index = np.logical_not(test_index) <NEW_LINE> if self.indices: <NEW_LINE> <INDENT> ind = np.arange(n) <NEW_LINE> train_index = ind[train_index] <NEW_LINE> test_index = ind[test_index] <NEW_LINE> <DEDENT> yield train_index, test_index <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '%s.%s(n=%i)' % ( self.__class__.__module__, self.__class__.__name__, self.n, ) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self.n | Leave-One-Out cross validation iterator.
Provides train/test indices to split data in train test sets. Each
sample is used once as a test set (singleton) while the remaining
samples form the training set.
Due to the high number of test sets (which is the same as the
number of samples) this cross validation method can be very costly.
For large datasets one should favor KFold, StratifiedKFold or
ShuffleSplit.
Parameters
----------
n: int
Total number of elements
indices: boolean, optional (default True)
Return train/test split as arrays of indices, rather than a boolean
mask array. Integer indices are required when dealing with sparse
matrices, since those cannot be indexed by boolean masks.
Examples
--------
>>> from sklearn import cross_validation
>>> X = np.array([[1, 2], [3, 4]])
>>> y = np.array([1, 2])
>>> loo = cross_validation.LeaveOneOut(2)
>>> len(loo)
2
>>> print(loo)
sklearn.cross_validation.LeaveOneOut(n=2)
>>> for train_index, test_index in loo:
... print("TRAIN:", train_index, "TEST:", test_index)
... X_train, X_test = X[train_index], X[test_index]
... y_train, y_test = y[train_index], y[test_index]
... print(X_train, X_test, y_train, y_test)
TRAIN: [1] TEST: [0]
[[3 4]] [[1 2]] [2] [1]
TRAIN: [0] TEST: [1]
[[1 2]] [[3 4]] [1] [2]
See also
========
LeaveOneLabelOut for splitting the data according to explicit,
domain-specific stratification of the dataset. | 62598fa85166f23b2e243311 |
class InstanceNotFound(VmOrInstanceNotFound): <NEW_LINE> <INDENT> pass | Raised if a specific instance cannot be found. | 62598fa8097d151d1a2c0f62 |
class MediaUpload(object): <NEW_LINE> <INDENT> def chunksize(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def mimetype(self): <NEW_LINE> <INDENT> return 'application/octet-stream' <NEW_LINE> <DEDENT> def size(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def resumable(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def getbytes(self, begin, end): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def has_stream(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def stream(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @util.positional(1) <NEW_LINE> def _to_json(self, strip=None): <NEW_LINE> <INDENT> t = type(self) <NEW_LINE> d = copy.copy(self.__dict__) <NEW_LINE> if strip is not None: <NEW_LINE> <INDENT> for member in strip: <NEW_LINE> <INDENT> del d[member] <NEW_LINE> <DEDENT> <DEDENT> d['_class'] = t.__name__ <NEW_LINE> d['_module'] = t.__module__ <NEW_LINE> return json.dumps(d) <NEW_LINE> <DEDENT> def to_json(self): <NEW_LINE> <INDENT> return self._to_json() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def new_from_json(cls, s): <NEW_LINE> <INDENT> data = json.loads(s) <NEW_LINE> module = data['_module'] <NEW_LINE> m = __import__(module, fromlist=module.split('.')[:-1]) <NEW_LINE> kls = getattr(m, data['_class']) <NEW_LINE> from_json = getattr(kls, 'from_json') <NEW_LINE> return from_json(s) | Describes a media object to upload.
Base class that defines the interface of MediaUpload subclasses.
Note that subclasses of MediaUpload may allow you to control the chunksize
when uploading a media object. It is important to keep the size of the chunk
as large as possible to keep the upload efficient. Other factors may influence
the size of the chunk you use, particularly if you are working in an
environment where individual HTTP requests may have a hardcoded time limit,
such as under certain classes of requests under Google App Engine.
Streams are io.Base compatible objects that support seek(). Some MediaUpload
subclasses support using streams directly to upload data. Support for
streaming may be indicated by a MediaUpload sub-class and if appropriate for a
platform that stream will be used for uploading the media object. The support
for streaming is indicated by has_stream() returning True. The stream() method
should return an io.Base object that supports seek(). On platforms where the
underlying httplib module supports streaming, for example Python 2.6 and
later, the stream will be passed into the http library which will result in
less memory being used and possibly faster uploads.
If you need to upload media that can't be uploaded using any of the existing
MediaUpload sub-class then you can sub-class MediaUpload for your particular
needs. | 62598fa88e7ae83300ee8fdb |
class BlancClass(object): <NEW_LINE> <INDENT> pass | blanc container class to have a collection of attributes.
For rapid shell- or prototyping. In the process of improving the code
this class might/can/will at some point be replaced with a more
tailored class.
Usage:
>>> from cma.utilities.utils import BlancClass
>>> p = BlancClass()
>>> p.value1 = 0
>>> p.value2 = 1 | 62598fa8baa26c4b54d4f1ea |
class Converter(object): <NEW_LINE> <INDENT> extract_map = {'.ape': ApeType, '.flac': FlacType, '.m4a': M4aType, '.mp3': Mp3Type, '.ogg': OggType, '.wav': WavType, '.wv': WvType} <NEW_LINE> def __init__(self, split=False, files=tuple()): <NEW_LINE> <INDENT> self.files = files <NEW_LINE> self._file_objs = [] <NEW_LINE> self.split = split <NEW_LINE> <DEDENT> def run(self, encoder): <NEW_LINE> <INDENT> self._prepare_files(encoder) <NEW_LINE> self._encode() <NEW_LINE> <DEDENT> def _prepare_files(self, encoder): <NEW_LINE> <INDENT> for filename in self.files: <NEW_LINE> <INDENT> base, ext = os.path.splitext(filename) <NEW_LINE> if self.split: <NEW_LINE> <INDENT> self._split_file(filename, base, ext, encoder) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> klass = Converter.extract_map.get(ext.lower()) <NEW_LINE> if not klass: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> obj = klass(filename, encoder) <NEW_LINE> self._file_objs.append(obj) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _split_file(self, filename, base, ext, encoder): <NEW_LINE> <INDENT> wav = base + ".wav" <NEW_LINE> cuefile = None <NEW_LINE> for tmp in (base + ".cue", base + ".wav.cue", base + ".flac.cue", base + ".wv.cue", base + ".ape.cue"): <NEW_LINE> <INDENT> if os.path.exists(tmp): <NEW_LINE> <INDENT> cuefile = tmp <NEW_LINE> print("*** cuefile: %s" % cuefile) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if cuefile is None: <NEW_LINE> <INDENT> print("*** No cuefile found for `%s'" % filename) <NEW_LINE> return <NEW_LINE> <DEDENT> cue = CueObjectParser(cuefile) <NEW_LINE> klass = Converter.extract_map.get(ext.lower()) <NEW_LINE> if not klass: <NEW_LINE> <INDENT> print("*** Cannot find right converter for `%s'" % ext) <NEW_LINE> return <NEW_LINE> <DEDENT> fobj = klass(filename, encoder) <NEW_LINE> fobj.extract_wav() <NEW_LINE> pipe = sp.Popen(["cuebreakpoints", cuefile], stdout=sp.PIPE) <NEW_LINE> sp.check_call(["shnsplit", "-a", base + "_", "-o", "wav", wav], stdin=pipe.stdout, stdout=sp.PIPE) <NEW_LINE> filepath = os.path.dirname(filename) <NEW_LINE> for index, filename in enumerate(match_file(filepath)): <NEW_LINE> <INDENT> obj = WavType(filename, encoder) <NEW_LINE> obj.tmp_wav_remove = True <NEW_LINE> obj.album = cue.album <NEW_LINE> obj.album_artist = cue.album_artist <NEW_LINE> obj.album = cue.album <NEW_LINE> obj.title, obj.performer = cue.get_track_data(index) <NEW_LINE> self._file_objs.append(obj) <NEW_LINE> <DEDENT> fobj.cleanup() <NEW_LINE> <DEDENT> def _encode(self): <NEW_LINE> <INDENT> pool = mp.Pool() <NEW_LINE> pool.map_async(encode, tuple(self._file_objs)).get(999) | Main class for converting files | 62598fa84e4d56256637235e |
class ServiceBox(gtk.ScrolledWindow): <NEW_LINE> <INDENT> def __init__(self, callback_func): <NEW_LINE> <INDENT> gtk.ScrolledWindow.__init__(self) <NEW_LINE> self._func = callback_func <NEW_LINE> self.vbox = gtk.VBox(spacing=5) <NEW_LINE> self.services = {} <NEW_LINE> self._set_style() <NEW_LINE> self._create_ui() <NEW_LINE> <DEDENT> def _set_style(self): <NEW_LINE> <INDENT> self.set_shadow_type(gtk.SHADOW_IN) <NEW_LINE> self.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC) <NEW_LINE> <DEDENT> def _create_ui(self): <NEW_LINE> <INDENT> self.add_with_viewport(self.vbox) <NEW_LINE> self.vbox.show() <NEW_LINE> <DEDENT> def add_item(self, name, stype='', desc='', state=''): <NEW_LINE> <INDENT> item = ServiceItem(name, stype, desc, state) <NEW_LINE> item.listen_signals(self._func) <NEW_LINE> self.vbox.pack_start(item, expand=False) <NEW_LINE> self.services[name] = {'widget':item} <NEW_LINE> self.set_item(name, (stype, desc, state)) <NEW_LINE> <DEDENT> def set_item(self, name, info): <NEW_LINE> <INDENT> self.services[name]['values'] = info <NEW_LINE> self.services[name]['widget'].update(info) | holds ServiceItems | 62598fa87cff6e4e811b5963 |
class ProtocolError(Exception): <NEW_LINE> <INDENT> pass | A protocol error | 62598fa8e76e3b2f99fd896f |
class LinearRegression(object): <NEW_LINE> <INDENT> def __init__(self, train_labels, test_labels, item_based_ratings, collaborative_ratings, training_data_mask): <NEW_LINE> <INDENT> self.item_based_ratings = item_based_ratings <NEW_LINE> self.collaborative_ratings = collaborative_ratings <NEW_LINE> self.item_based_ratings_shape = item_based_ratings.shape <NEW_LINE> self.collaborative_ratings_shape = collaborative_ratings.shape <NEW_LINE> item_based_ratings = self.flatten_matrix(item_based_ratings)[training_data_mask.flatten()] <NEW_LINE> collaborative_ratings = self.flatten_matrix(collaborative_ratings)[training_data_mask.flatten()] <NEW_LINE> self.train_data = numpy.vstack(( item_based_ratings, collaborative_ratings ) ).T <NEW_LINE> self.flat_train_labels = self.flatten_matrix(train_labels)[training_data_mask.flatten()] <NEW_LINE> self.flat_test_labels = self.flatten_matrix(test_labels) <NEW_LINE> self.regression_coef1 = 0 <NEW_LINE> self.regression_coef2 = 0 <NEW_LINE> <DEDENT> def flatten_matrix(self, matrix): <NEW_LINE> <INDENT> return matrix.flatten() <NEW_LINE> <DEDENT> def unflatten(self, matrix, shape): <NEW_LINE> <INDENT> return matrix.reshape(shape) <NEW_LINE> <DEDENT> def train(self): <NEW_LINE> <INDENT> regr_model = linear_model.LinearRegression() <NEW_LINE> regr_model.fit(self.train_data, self.flat_train_labels) <NEW_LINE> weighted_item_based_ratings = regr_model.coef_[0] * self.item_based_ratings <NEW_LINE> weighted_collaborative_ratings = regr_model.coef_[1] * self.collaborative_ratings <NEW_LINE> self.regression_coef1 = regr_model.coef_[0] <NEW_LINE> self.regression_coef2 = regr_model.coef_[1] <NEW_LINE> print("CBF coef: {}".format(regr_model.coef_[0])) <NEW_LINE> print("CF coef: {}".format(regr_model.coef_[1])) <NEW_LINE> print("Intercept: {}".format(regr_model.intercept_)) <NEW_LINE> return weighted_collaborative_ratings + weighted_item_based_ratings +regr_model.intercept_ | Linear regression to combine the results of two matrices. | 62598fa8f9cc0f698b1c5265 |
class RawStream(RawInputStream, RawOutputStream): <NEW_LINE> <INDENT> def __init__(self, samplerate=None, blocksize=None, device=None, channels=None, dtype=None, latency=None, extra_settings=None, callback=None, finished_callback=None, clip_off=None, dither_off=None, never_drop_input=None, prime_output_buffers_using_stream_callback=None): <NEW_LINE> <INDENT> _StreamBase.__init__(self, kind='duplex', wrap_callback='buffer', **_remove_self(locals())) | Raw stream for playback and recording. See __init__(). | 62598fa844b2445a339b690c |
class LoadBalancerStatus(object): <NEW_LINE> <INDENT> def __init__(self, load_balancer_id, load_balancer_name, status): <NEW_LINE> <INDENT> self.load_balancer_id = load_balancer_id <NEW_LINE> self.status = status <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return ( '<LoadBalancerStatus %s is %s at %s>' % ( self.load_balancer_id, self.status, id(self)) ) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return (self.__class__ == other.__class__ and self.__dict__ == other.__dict__) | Simple status of SLB
Args:
load_balancer_id (str): LoadBalancerId unique identifier of the SLB.
load_balancer_name (str): name of the SLB.
status (str): SLB status. | 62598fa8f7d966606f747f1e |
class FeiraLivreRetrieveTest(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.feira_um = FeiraLivre.objects.create(nome_feira='Feira test1') <NEW_LINE> self.feira_dois = FeiraLivre.objects.create(nome_feira='Feira test2') <NEW_LINE> self.feira_tres = FeiraLivre.objects.create(nome_feira='Feira test3') <NEW_LINE> self.feira_quatro = FeiraLivre.objects.create(nome_feira='Feira test4') <NEW_LINE> <DEDENT> def test_get_valid_single_puppy(self): <NEW_LINE> <INDENT> response = client.get(reverse( 'feira_delete_update_retrieve', kwargs={'pk': self.feira_um.pk})) <NEW_LINE> feira = FeiraLivre.objects.get(pk=self.feira_um.pk) <NEW_LINE> serializer = FeiraLivreSerializer(feira) <NEW_LINE> self.assertEqual(response.data, serializer.data) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_200_OK) <NEW_LINE> <DEDENT> def test_get_invalid_single_puppy(self): <NEW_LINE> <INDENT> response = client.get( reverse('feira_delete_update_retrieve', kwargs={'pk': 30})) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) | Módulo de teste para o GET de uma só FeiraLivre | 62598fa8d7e4931a7ef3bfd5 |
class IVolunteerteamLocator (IArticleLocator): <NEW_LINE> <INDENT> pass | Volunteerteam table add row donor | 62598fa855399d3f0562645e |
class LoadData(ImpalaDDL): <NEW_LINE> <INDENT> def __init__( self, table_name, path, database=None, partition=None, partition_schema=None, overwrite=False, ): <NEW_LINE> <INDENT> self.table_name = table_name <NEW_LINE> self.database = database <NEW_LINE> self.path = path <NEW_LINE> self.partition = partition <NEW_LINE> self.partition_schema = partition_schema <NEW_LINE> self.overwrite = overwrite <NEW_LINE> <DEDENT> def compile(self): <NEW_LINE> <INDENT> overwrite = 'OVERWRITE ' if self.overwrite else '' <NEW_LINE> if self.partition is not None: <NEW_LINE> <INDENT> partition = '\n' + _format_partition( self.partition, self.partition_schema ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> partition = '' <NEW_LINE> <DEDENT> scoped_name = self._get_scoped_name(self.table_name, self.database) <NEW_LINE> return "LOAD DATA INPATH '{}' {}INTO TABLE {}{}".format( self.path, overwrite, scoped_name, partition ) | Generate DDL for LOAD DATA command. Cannot be cancelled | 62598fa84f6381625f19945b |
class PathTool: <NEW_LINE> <INDENT> def _getProxy(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def cmdline_path(self, path): <NEW_LINE> <INDENT> raise NotImplemented() <NEW_LINE> <DEDENT> def absolutePath(self, path): <NEW_LINE> <INDENT> return self._getProxy().abspath(path) <NEW_LINE> <DEDENT> def join(self, *paths): <NEW_LINE> <INDENT> return self._getProxy().join(*paths) <NEW_LINE> <DEDENT> def baseName(self, path): <NEW_LINE> <INDENT> return self._getProxy().basename(path) <NEW_LINE> <DEDENT> def dirName(self, path): <NEW_LINE> <INDENT> return self._getProxy().dirname(path) <NEW_LINE> <DEDENT> def isAbsolute(self, path): <NEW_LINE> <INDENT> return self._getProxy().isabs(path) <NEW_LINE> <DEDENT> def normalizePath(self, path): <NEW_LINE> <INDENT> return self._getProxy().normpath(path) <NEW_LINE> <DEDENT> def split(self, path): <NEW_LINE> <INDENT> return self._getProxy().split(path) <NEW_LINE> <DEDENT> def splitDrive(self, path): <NEW_LINE> <INDENT> return self._getProxy().splitdrive(path) <NEW_LINE> <DEDENT> def splitExt(self, path): <NEW_LINE> <INDENT> return self._getProxy().splitext(path) | Abstract path class that defines an interface
| 62598fa8167d2b6e312b6eab |
class ValueConverter(object): <NEW_LINE> <INDENT> klasses = set() <NEW_LINE> def __new__(cls, klass): <NEW_LINE> <INDENT> if cls is ValueConverter: <NEW_LINE> <INDENT> converter = cls.get_converter(klass) <NEW_LINE> if converter: <NEW_LINE> <INDENT> return converter <NEW_LINE> <DEDENT> <DEDENT> return super(ValueConverter, cls).__new__(cls) <NEW_LINE> <DEDENT> def __init__(self, klass): <NEW_LINE> <INDENT> if isinstance(klass, System.Type): <NEW_LINE> <INDENT> self.clr_type = klass <NEW_LINE> self.klass = utils.get_class_from_name(klass.ToString()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.klass = klass <NEW_LINE> self.clr_type = GetClrType(self.klass) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def get_converter(cls, klass): <NEW_LINE> <INDENT> if not isinstance(klass, System.Type): <NEW_LINE> <INDENT> klass = GetClrType(klass) <NEW_LINE> <DEDENT> if klass.IsArray or GetClrType(System.Collections.ICollection).IsAssignableFrom(klass): <NEW_LINE> <INDENT> return WrappedListConverter(utils.get_class_from_name(klass.ToString())) <NEW_LINE> <DEDENT> if klass.Equals(System.Object): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> for converter in cls.__subclasses__(): <NEW_LINE> <INDENT> for klass_ in converter.klasses: <NEW_LINE> <INDENT> if klass.Equals(klass_) or klass.IsSubclassOf(klass_): <NEW_LINE> <INDENT> return converter(klass_) <NEW_LINE> <DEDENT> <DEDENT> subclass_converter = converter.get_converter(klass) <NEW_LINE> if subclass_converter: <NEW_LINE> <INDENT> return subclass_converter <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def to_python(cls, value): <NEW_LINE> <INDENT> if isinstance(value, System.Object): <NEW_LINE> <INDENT> converter = cls.get_converter(value.GetType()) <NEW_LINE> if converter is None or isinstance(converter, WrappedListConverter): <NEW_LINE> <INDENT> return utils.get_wrapper_class(value.GetType())(instance=value) <NEW_LINE> <DEDENT> return converter.to_python(value) <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def to_csharp(self, value, force=False): <NEW_LINE> <INDENT> return getattr(value, 'instance', value) | Handle conversions between C# values and Python values for a particular C# class.
Attributes:
klasses (set): The C# class we're converting from. Not a RuntimeType, but an actual class. | 62598fa891af0d3eaad39d49 |
class ProcessorGroup(_object): <NEW_LINE> <INDENT> __swig_setmethods__ = {} <NEW_LINE> __setattr__ = lambda self, name, value: _swig_setattr(self, ProcessorGroup, name, value) <NEW_LINE> __swig_getmethods__ = {} <NEW_LINE> __getattr__ = lambda self, name: _swig_getattr(self, ProcessorGroup, name) <NEW_LINE> def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined - class is abstract") <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> __swig_destroy__ = _ParaMEDMEM.delete_ProcessorGroup <NEW_LINE> __del__ = lambda self : None; <NEW_LINE> def deepCpy(self): <NEW_LINE> <INDENT> return _ParaMEDMEM.ProcessorGroup_deepCpy(self) <NEW_LINE> <DEDENT> def fuse(self, *args): <NEW_LINE> <INDENT> return _ParaMEDMEM.ProcessorGroup_fuse(self, *args) <NEW_LINE> <DEDENT> def intersect(self, *args): <NEW_LINE> <INDENT> return _ParaMEDMEM.ProcessorGroup_intersect(self, *args) <NEW_LINE> <DEDENT> def contains(self, *args): <NEW_LINE> <INDENT> return _ParaMEDMEM.ProcessorGroup_contains(self, *args) <NEW_LINE> <DEDENT> def containsMyRank(self): <NEW_LINE> <INDENT> return _ParaMEDMEM.ProcessorGroup_containsMyRank(self) <NEW_LINE> <DEDENT> def size(self): <NEW_LINE> <INDENT> return _ParaMEDMEM.ProcessorGroup_size(self) <NEW_LINE> <DEDENT> def getCommInterface(self): <NEW_LINE> <INDENT> return _ParaMEDMEM.ProcessorGroup_getCommInterface(self) <NEW_LINE> <DEDENT> def myRank(self): <NEW_LINE> <INDENT> return _ParaMEDMEM.ProcessorGroup_myRank(self) <NEW_LINE> <DEDENT> def translateRank(self, *args): <NEW_LINE> <INDENT> return _ParaMEDMEM.ProcessorGroup_translateRank(self, *args) <NEW_LINE> <DEDENT> def createComplementProcGroup(self): <NEW_LINE> <INDENT> return _ParaMEDMEM.ProcessorGroup_createComplementProcGroup(self) <NEW_LINE> <DEDENT> def createProcGroup(self): <NEW_LINE> <INDENT> return _ParaMEDMEM.ProcessorGroup_createProcGroup(self) <NEW_LINE> <DEDENT> def getProcIDs(self): <NEW_LINE> <INDENT> return _ParaMEDMEM.ProcessorGroup_getProcIDs(self) | 1 | 62598fa826068e7796d4c894 |
class Command(BaseCommand): <NEW_LINE> <INDENT> option_list = BaseCommand.option_list + ( make_option('--json', action='store_true', dest='json', default=False, help='Output the result encoded as a JSON object'), ) <NEW_LINE> help = ( "Get some statistics about the Package Tracking System\n" "- Total number of source packages with at least one subscription\n" "- Total number of subscriptions\n" "- Total number of unique emails\n" ) <NEW_LINE> def handle(self, *args, **kwargs): <NEW_LINE> <INDENT> from collections import OrderedDict <NEW_LINE> stats = OrderedDict(( ('package_number', SourcePackageName.objects.all_with_subscribers().count()), ('subscription_number', Subscription.objects.count()), ('date', timezone.now().strftime('%Y-%m-%d')), ('unique_emails_number', EmailUser.objects.count()), )) <NEW_LINE> if kwargs['json']: <NEW_LINE> <INDENT> self.stdout.write(json.dumps(stats)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.stdout.write('Src pkg\tSubscr.\tDate\t\tNb email') <NEW_LINE> self.stdout.write('\t'.join(map(str, stats.values()))) | A Django management command which outputs some statistics about the PTS. | 62598fa863d6d428bbee26ec |
class Node: <NEW_LINE> <INDENT> def __init__(self, data, next=None): <NEW_LINE> <INDENT> self.data = data <NEW_LINE> self.next = next <NEW_LINE> <DEDENT> def get_next(self): <NEW_LINE> <INDENT> return self.next <NEW_LINE> <DEDENT> def get_data(self): <NEW_LINE> <INDENT> return self.data <NEW_LINE> <DEDENT> def set_next(self,next): <NEW_LINE> <INDENT> self.next = next | This class represents the Node of the List.
The Node contains the data and points to next element (Node). | 62598fa830bbd72246469915 |
class ListDetailViewSet(ViewSet): <NEW_LINE> <INDENT> queryset = todo_models.List.objects.all() <NEW_LINE> def detail(self, *args, **kwargs): <NEW_LINE> <INDENT> list_obj = get_object_or_404(self.queryset, pk=kwargs['list_id']) <NEW_LINE> serializer = todo_serializers.ListSerializer(list_obj) <NEW_LINE> return Response(serializer.data, status=200) | Viewing details for List
| 62598fa801c39578d7f12cba |
class RestoreDatabaseMetadata(_messages.Message): <NEW_LINE> <INDENT> class SourceTypeValueValuesEnum(_messages.Enum): <NEW_LINE> <INDENT> TYPE_UNSPECIFIED = 0 <NEW_LINE> BACKUP = 1 <NEW_LINE> <DEDENT> backupInfo = _messages.MessageField('BackupInfo', 1) <NEW_LINE> cancelTime = _messages.StringField(2) <NEW_LINE> name = _messages.StringField(3) <NEW_LINE> optimizeDatabaseOperationName = _messages.StringField(4) <NEW_LINE> progress = _messages.MessageField('OperationProgress', 5) <NEW_LINE> sourceType = _messages.EnumField('SourceTypeValueValuesEnum', 6) | A RestoreDatabaseMetadata object.
Enums:
SourceTypeValueValuesEnum: The type of the restore source.
Fields:
backupInfo: Information about the backup used to restore the database.
cancelTime: The time at which this operation was cancelled. If set, this
operation is in the process of undoing itself (which is guaranteed to
succeed) and cannot be cancelled again.
name: Name of the database being created and restored to.
optimizeDatabaseOperationName: If exists, the name of the long-running
operation that will be used to track the post-restore optimization
process to optimize the performance of the restored database, and remove
the dependency on the restore source. The name is of the form `projects/
<project>/instances/<instance>/databases/<database>/operations/<operatio
n> where the <database> is the name of database being created and
restored to. The metadata type of the long-running operation is
OptimizeRestoreDatabaseMetadata. This long-running operation will be
automatically created by the system after the RestoreDatabase long-
running operation completes successfully. This operation will not be
created if the restore was not successful.
progress: The progress of the RestoreDatabase operation.
sourceType: The type of the restore source. | 62598fa81f037a2d8b9e4027 |
class TimedPOMDPMaze(POMDPMaze): <NEW_LINE> <INDENT> def __init__(self, maze_game, **kwargs): <NEW_LINE> <INDENT> super().__init__(maze_game, **kwargs) <NEW_LINE> self.delay = kwargs.get("delay") if kwargs.get("delay") else 5 <NEW_LINE> self.ticks = 0 <NEW_LINE> <DEDENT> def on_start(self): <NEW_LINE> <INDENT> self.ticks = 0 <NEW_LINE> <DEDENT> def on_terminal(self): <NEW_LINE> <INDENT> super().on_terminal() <NEW_LINE> <DEDENT> def on_update(self): <NEW_LINE> <INDENT> self.ticks += 1 <NEW_LINE> if self.ticks == self.delay: <NEW_LINE> <INDENT> super().on_start() <NEW_LINE> <DEDENT> if self.ticks >= self.delay: <NEW_LINE> <INDENT> super().on_update() | The TimedPOMDPMaze. Adds FOW after a delay (ticks)
:param maze_game: MazeGame instance
:param kwargs: dict of custom arguments | 62598fa83617ad0b5ee0608f |
class PlayerProgram(ctypes.Structure): <NEW_LINE> <INDENT> pass | Add a slave to the current media player.
ote if the player is playing, the slave will be added directly. this call
will also update the slave list of the attached libvlc_media_t.
ersion libvlc 3.0.0 and later.
See libvlc_media_slaves_add
\param p_mi the media player
\param i_type subtitle or audio
\param psz_uri uri of the slave (should contain a valid scheme).
\param b_select true if this slave should be selected when it's loaded
eturn 0 on success, -1 on error.
| 62598fa8379a373c97d98f4d |
class __Node: <NEW_LINE> <INDENT> def __init__(self, e, prevNode, nextNode): <NEW_LINE> <INDENT> self.__element = e <NEW_LINE> self.__nextNode = nextNode <NEW_LINE> self.__prevNode = prevNode <NEW_LINE> <DEDENT> def nextNode(self, node): <NEW_LINE> <INDENT> if node is None: <NEW_LINE> <INDENT> return self.__nextNode <NEW_LINE> <DEDENT> self.__nextNode = node <NEW_LINE> <DEDENT> def prevNode(self, node): <NEW_LINE> <INDENT> if node is None: <NEW_LINE> <INDENT> return self.__prevNode <NEW_LINE> <DEDENT> self.__prevNode = node <NEW_LINE> <DEDENT> def element(self, e): <NEW_LINE> <INDENT> if e is None: <NEW_LINE> <INDENT> return self.__element <NEW_LINE> <DEDENT> self.__element = e <NEW_LINE> <DEDENT> def dispose(self): <NEW_LINE> <INDENT> self.__element = self.__prevNode = self.__nextNode = None | Class represent a node in the LL | 62598fa8e76e3b2f99fd8971 |
class Compound(models.Model): <NEW_LINE> <INDENT> front = models.CharField(max_length=50, unique=True) <NEW_LINE> reading = models.CharField(max_length=500, null=True, blank=True) <NEW_LINE> gloss = models.CharField(max_length=5000, null=True, blank=True) <NEW_LINE> pos = models.CharField(max_length=500, null=True, blank=True) <NEW_LINE> examples = models.ManyToManyField( 'Example', related_name='compounds', null=True, blank=True ) <NEW_LINE> antonyms = models.ManyToManyField('self', null=True, blank=True) <NEW_LINE> similar = models.ManyToManyField('self', null=True, blank=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.front <NEW_LINE> <DEDENT> def as_json(self): <NEW_LINE> <INDENT> return dict( front=self.front, reading=self.reading, gloss=self.gloss, examples=[example.as_json() for example in self.examples.all()], antonyms=[antonym.as_json() for antonym in self.antonyms.all()], similar=[similar.as_json() for similar in self.similar.all()] ) <NEW_LINE> <DEDENT> def is_processed(self): <NEW_LINE> <INDENT> processed = False <NEW_LINE> for kanji in self.kanji.all(): <NEW_LINE> <INDENT> processed = kanji.processed <NEW_LINE> <DEDENT> return processed | Kanji compound, usually word or expression, may include kana | 62598fa88da39b475be0311f |
class NoEnvLoad(Package): <NEW_LINE> <INDENT> def __init__(self, package: Package): <NEW_LINE> <INDENT> self.package = package <NEW_LINE> <DEDENT> def install_env(self, ctx: Namespace): <NEW_LINE> <INDENT> ctx.log.debug('cancel installation of %s in env' % self.ident()) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.package == other <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(self.package) <NEW_LINE> <DEDENT> def ident(self) -> str: <NEW_LINE> <INDENT> return self.package.ident() <NEW_LINE> <DEDENT> def is_fetched(self, ctx: Namespace) -> bool: <NEW_LINE> <INDENT> return self.package.is_fetched(ctx) <NEW_LINE> <DEDENT> def is_built(self, ctx: Namespace) -> bool: <NEW_LINE> <INDENT> return self.package.is_built(ctx) <NEW_LINE> <DEDENT> def is_installed(self, ctx: Namespace) -> bool: <NEW_LINE> <INDENT> return self.package.is_installed(ctx) <NEW_LINE> <DEDENT> def fetch(self, ctx: Namespace): <NEW_LINE> <INDENT> return self.package.fetch(ctx) <NEW_LINE> <DEDENT> def build(self, ctx: Namespace): <NEW_LINE> <INDENT> return self.package.build(ctx) <NEW_LINE> <DEDENT> def install(self, ctx: Namespace): <NEW_LINE> <INDENT> return self.package.install(ctx) <NEW_LINE> <DEDENT> def __getattr__(self, key: str): <NEW_LINE> <INDENT> return getattr(self.package, key) | Wrapper class for packages that avoids them being loaded into PATH and
LD_LIBRARY_PATH by the default :func:`Package.install_env` method.
This is useful for packages that are used by referening direct paths,
instead of counting on their presence when calling :func:`util.run`. | 62598fa8925a0f43d25e7f7a |
class Ai(base.BaseAi): <NEW_LINE> <INDENT> def move(self, bots, events): <NEW_LINE> <INDENT> response = [] <NEW_LINE> for bot in bots: <NEW_LINE> <INDENT> if not bot.alive: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> move_pos = random.choice(list(self.get_valid_moves(bot))) <NEW_LINE> response.append(actions.Move(bot_id=bot.bot_id, x=move_pos.x, y=move_pos.y)) <NEW_LINE> <DEDENT> return response | Dummy bot that moves randomly around the board. | 62598fa8851cf427c66b8204 |
class CustomQCompleter(QCompleter): <NEW_LINE> <INDENT> def __init__(self, parent=None,model=None,proxy=None,columns=None,*args): <NEW_LINE> <INDENT> self.columnind=0 <NEW_LINE> super(CustomQCompleter, self).__init__(parent,*args) <NEW_LINE> self.setCaseSensitivity(QtCore.Qt.CaseInsensitive) <NEW_LINE> self.parent=parent <NEW_LINE> if proxy!=None: <NEW_LINE> <INDENT> self.setModel(proxy) <NEW_LINE> <DEDENT> elif model!=None: <NEW_LINE> <INDENT> proxy = nameLookupModel(columns) <NEW_LINE> proxy.setSourceModel(model) <NEW_LINE> self.setModel(proxy) <NEW_LINE> <DEDENT> self.setCompletionRole(JoinRole) <NEW_LINE> self.setFilterMode(QtCore.Qt.MatchContains) <NEW_LINE> self.popup().setItemDelegate(JoinDelegate(self)) <NEW_LINE> <DEDENT> def setModel(self, model): <NEW_LINE> <INDENT> self.source_model = model <NEW_LINE> self.filterProxyModel=model <NEW_LINE> super(CustomQCompleter, self).setModel(self.source_model) <NEW_LINE> <DEDENT> def pathFromIndex(self,index,role=QtCore.Qt.DisplayRole): <NEW_LINE> <INDENT> model=self.source_model <NEW_LINE> return model.data(model.index(index.row(),0),role=JoinRole) | adapted from: http://stackoverflow.com/a/7767999/2156909 | 62598fa8f7d966606f747f20 |
class QuantumRegisters: <NEW_LINE> <INDENT> def __init__(self, env): <NEW_LINE> <INDENT> self.env = env <NEW_LINE> self.registerDict = {} <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> value = self.registerDict.get(index) <NEW_LINE> if value is not None: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> value = QuantumRegisterStorage(index, self.env) <NEW_LINE> self.registerDict[index] = value <NEW_LINE> return value | The quantum register dict | 62598fa8d7e4931a7ef3bfd7 |
class LoggedInUser(Singleton): <NEW_LINE> <INDENT> __metaclass__ = Singleton <NEW_LINE> request = None <NEW_LINE> user = None <NEW_LINE> address = None <NEW_LINE> def set_data(self, request): <NEW_LINE> <INDENT> self.request = id(request) <NEW_LINE> if request.user.is_authenticated: <NEW_LINE> <INDENT> self.user = request.user <NEW_LINE> self.address = request.META.get('REMOTE_ADDR') <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def current_user(self): <NEW_LINE> <INDENT> return self.user <NEW_LINE> <DEDENT> @property <NEW_LINE> def have_user(self): <NEW_LINE> <INDENT> return not self.user is None | Синглтон для хранения пользователя,
от имени которого выполняется запрос | 62598fa8eab8aa0e5d30bcc6 |
class StepMethodNeedsMoreThanOneArgument(HitchStoryException): <NEW_LINE> <INDENT> pass | Method in story engine takes more than one argument. | 62598fa83539df3088ecc1f0 |
class JsonPlugin(monasca_setup.detection.ArgsPlugin): <NEW_LINE> <INDENT> def __init__(self, template_dir, overwrite=True, args=None): <NEW_LINE> <INDENT> super(JsonPlugin, self).__init__( template_dir, overwrite, args) <NEW_LINE> <DEDENT> def _detect(self): <NEW_LINE> <INDENT> self.available = False <NEW_LINE> if os.path.isdir(VAR_CACHE_DIR): <NEW_LINE> <INDENT> self.available = True <NEW_LINE> <DEDENT> <DEDENT> def build_config(self): <NEW_LINE> <INDENT> config = agent_config.Plugins() <NEW_LINE> config['json_plugin'] = {'init_config': None, 'instances': [{'name': VAR_CACHE_DIR, 'metrics_dir': VAR_CACHE_DIR}]} <NEW_LINE> return config <NEW_LINE> <DEDENT> def dependencies_installed(self): <NEW_LINE> <INDENT> return True | Detect if /var/cache/monasca_json_plugin exists
This builds a config for the json_plugin. This detects if
/var/cache/monasca_json_plugin exists and if so,
builds a configuration for it.
Users are free to add their own configs. | 62598fa84e4d562566372361 |
class Document(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.bundles = [] <NEW_LINE> self._highest_bundle_id = 0 <NEW_LINE> self.meta = {} <NEW_LINE> self.json = {} <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self.bundles) <NEW_LINE> <DEDENT> def create_bundle(self): <NEW_LINE> <INDENT> self._highest_bundle_id += 1 <NEW_LINE> bundle = Bundle(document=self, bundle_id=str(self._highest_bundle_id)) <NEW_LINE> self.bundles.append(bundle) <NEW_LINE> bundle.number = len(self.bundles) <NEW_LINE> return bundle <NEW_LINE> <DEDENT> def load_conllu(self, filename=None): <NEW_LINE> <INDENT> reader = ConlluReader(files=filename) <NEW_LINE> reader.apply_on_document(self) <NEW_LINE> <DEDENT> def store_conllu(self, filename): <NEW_LINE> <INDENT> writer = ConlluWriter(files=filename) <NEW_LINE> writer.apply_on_document(self) <NEW_LINE> <DEDENT> def from_conllu_string(self, string): <NEW_LINE> <INDENT> reader = ConlluReader(filehandle=io.StringIO(string)) <NEW_LINE> reader.apply_on_document(self) <NEW_LINE> <DEDENT> def to_conllu_string(self): <NEW_LINE> <INDENT> fh = io.StringIO() <NEW_LINE> writer = ConlluWriter(filehandle=fh) <NEW_LINE> writer.apply_on_document(self) <NEW_LINE> return fh.getvalue() | Document is a container for Universal Dependency trees. | 62598fa866656f66f7d5a32c |
class IHTMLTextAreaWidget(IHTMLFormElement): <NEW_LINE> <INDENT> rows = zope.schema.Int( title=u'Rows', description=(u'This attribute specifies the number of visible text ' u'lines.'), required=False) <NEW_LINE> cols = zope.schema.Int( title=u'columns', description=(u'This attribute specifies the visible width in average ' u'character widths.'), required=False) <NEW_LINE> readonly = zope.schema.Choice( title=u'Read-Only', description=(u'When set for a form control, this boolean attribute ' u'prohibits changes to the control.'), values=(None, 'readonly'), required=False) <NEW_LINE> accesskey = zope.schema.TextLine( title=u'Access Key', description=(u'This attribute assigns an access key to an element.'), min_length=1, max_length=1, required=False) <NEW_LINE> onselect = zope.schema.TextLine( title=u'On Select', description=(u'The ``onselect`` event occurs when a user selects ' u'some text in a text field.'), required=False) | A widget using the HTML TEXTAREA element. | 62598fa82c8b7c6e89bd3702 |
class CountryDevices(Metric): <NEW_LINE> <INDENT> def __init__(self, name, series, buckets, status, private): <NEW_LINE> <INDENT> super().__init__(name, series, buckets, status) <NEW_LINE> self.private = private <NEW_LINE> self.users_by_country = self._calculate_metrics_countries() <NEW_LINE> self.country_data = self._build_country_info() <NEW_LINE> <DEDENT> def get_number_territories(self): <NEW_LINE> <INDENT> territories_total = 0 <NEW_LINE> for data in self.country_data.values(): <NEW_LINE> <INDENT> if data['number_of_users'] > 0: <NEW_LINE> <INDENT> territories_total += 1 <NEW_LINE> <DEDENT> <DEDENT> return territories_total <NEW_LINE> <DEDENT> def _calculate_metrics_countries(self): <NEW_LINE> <INDENT> users_by_country = {} <NEW_LINE> max_users = 0.0 <NEW_LINE> for country_counts in self.series: <NEW_LINE> <INDENT> country_code = country_counts['name'] <NEW_LINE> users_by_country[country_code] = {} <NEW_LINE> counts = [] <NEW_LINE> for daily_count in country_counts['values']: <NEW_LINE> <INDENT> if daily_count is not None: <NEW_LINE> <INDENT> counts.append(daily_count) <NEW_LINE> <DEDENT> <DEDENT> number_of_users = 0 <NEW_LINE> percentage_of_users = 0 <NEW_LINE> if len(counts) > 0: <NEW_LINE> <INDENT> percentage_of_users = sum(counts) / len(counts) <NEW_LINE> number_of_users = sum(counts) <NEW_LINE> <DEDENT> users_by_country[country_code]['number_of_users'] = ( number_of_users) <NEW_LINE> users_by_country[country_code]['percentage_of_users'] = ( percentage_of_users) <NEW_LINE> if max_users < percentage_of_users: <NEW_LINE> <INDENT> max_users = percentage_of_users <NEW_LINE> <DEDENT> <DEDENT> metrics_countries = _calculate_colors(users_by_country, max_users) <NEW_LINE> return metrics_countries <NEW_LINE> <DEDENT> def _build_country_info(self): <NEW_LINE> <INDENT> if not self.users_by_country: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> country_data = {} <NEW_LINE> for country in pycountry.countries: <NEW_LINE> <INDENT> country_info = self.users_by_country.get(country.alpha_2) <NEW_LINE> number_of_users = 0 <NEW_LINE> percentage_of_users = 0 <NEW_LINE> color_rgb = [247, 247, 247] <NEW_LINE> if country_info is not None: <NEW_LINE> <INDENT> if self.private: <NEW_LINE> <INDENT> number_of_users = country_info['number_of_users'] or 0 <NEW_LINE> <DEDENT> percentage_of_users = country_info['percentage_of_users'] or 0 <NEW_LINE> color_rgb = country_info['color_rgb'] or [247, 247, 247] <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> country_name = country.common_name <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> country_name = country.name <NEW_LINE> <DEDENT> country_data[country.numeric] = { 'name': country_name, 'code': country.alpha_2, 'percentage_of_users': percentage_of_users, 'color_rgb': color_rgb } <NEW_LINE> if self.private: <NEW_LINE> <INDENT> country_data[country.numeric]['number_of_users'] = ( number_of_users) <NEW_LINE> <DEDENT> <DEDENT> return country_data | Metrics for the devices in countries.
:var name: The name of the metric
:var series: The series dictionary from the metric
:var buckets: The buckets dictionary from the metric
:var status: The status of the metric
:var private: Boolean, True to add private information
displayed for publisher, False if not
:var users_by_country: Dictionary with additional metrics per country
:var country_data: The metrics on every country | 62598fa8435de62698e9bd32 |
class XMLRPCDispatcher(SimpleXMLRPCServer.SimpleXMLRPCDispatcher): <NEW_LINE> <INDENT> def __init__(self, allow_none, encoding): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> SimpleXMLRPCServer.SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> SimpleXMLRPCServer.SimpleXMLRPCDispatcher.__init__(self) <NEW_LINE> <DEDENT> self.logger = logging.getLogger(self.__class__.__name__) <NEW_LINE> self.allow_none = allow_none <NEW_LINE> self.encoding = encoding <NEW_LINE> <DEDENT> def _marshaled_dispatch(self, address, data): <NEW_LINE> <INDENT> params, method = xmlrpclib.loads(data) <NEW_LINE> if not self.instance.check_acls(address, method): <NEW_LINE> <INDENT> raise XMLRPCACLCheckException <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if '.' not in method: <NEW_LINE> <INDENT> params = (address, ) + params <NEW_LINE> <DEDENT> response = self.instance._dispatch(method, params, self.funcs) <NEW_LINE> if type(response) not in [bool, str, list, dict, set, type(None)]: <NEW_LINE> <INDENT> response = (response.decode('utf-8'), ) <NEW_LINE> <DEDENT> elif type(response) == set: <NEW_LINE> <INDENT> response = (list(response), ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> response = (response, ) <NEW_LINE> <DEDENT> raw_response = xmlrpclib.dumps(response, methodresponse=True, allow_none=self.allow_none, encoding=self.encoding) <NEW_LINE> <DEDENT> except xmlrpclib.Fault: <NEW_LINE> <INDENT> fault = sys.exc_info()[1] <NEW_LINE> raw_response = xmlrpclib.dumps(fault, methodresponse=True, allow_none=self.allow_none, encoding=self.encoding) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> err = sys.exc_info() <NEW_LINE> self.logger.error("Unexpected handler error", exc_info=1) <NEW_LINE> raw_response = xmlrpclib.dumps( xmlrpclib.Fault(1, "%s:%s" % (err[0].__name__, err[1])), methodresponse=True, allow_none=self.allow_none, encoding=self.encoding) <NEW_LINE> <DEDENT> return raw_response | An XML-RPC dispatcher. | 62598fa867a9b606de545f08 |
@admin.register(UserSettings) <NEW_LINE> class UserSettingsAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> list_display = ('user',) | UserSettingsAdmin. | 62598fa85fcc89381b2660eb |
class TestHg(AdapterTestHelper): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(TestHg, self).setUp(Hg) <NEW_LINE> <DEDENT> def test_status(self): <NEW_LINE> <INDENT> self.adapter.status() <NEW_LINE> self.assert_executed_command("hg status") <NEW_LINE> <DEDENT> def test_update(self): <NEW_LINE> <INDENT> self.adapter.update() <NEW_LINE> self.assert_executed_command("hg pull -u") <NEW_LINE> <DEDENT> def test_clone(self): <NEW_LINE> <INDENT> self.adapter.clone("ssh://hg@project.org/foo/bar") <NEW_LINE> self.assert_executed_command("hg clone %s %s" % ( "ssh://hg@project.org/foo/bar", os.path.join(self.sandbox.path, "repository") ), with_path=False) | Hg adapter test suite. | 62598fa84428ac0f6e65845f |
class SamiInstrumentDriver(SingleConnectionInstrumentDriver): <NEW_LINE> <INDENT> pass | SamiInstrumentDriver baseclass
Subclasses SingleConnectionInstrumentDriver with connection state
machine.
Needs to be subclassed in the specific driver module. | 62598fa810dbd63aa1c70aef |
class People(Amity): <NEW_LINE> <INDENT> _table = "people" <NEW_LINE> validators = {"firstname":r"([a-zA-Z]+)", "lastname": r"([a-zA-Z]+)", "file":r"([a-zA-Z]+)" } <NEW_LINE> def __init__(self,oid=0): <NEW_LINE> <INDENT> super(People,self).__init__(oid,People._table) <NEW_LINE> <DEDENT> def typeIs(self,type): <NEW_LINE> <INDENT> if self.data['type'] == type: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | docstring for Room | 62598fa8dd821e528d6d8e72 |
@app.route("/signup") <NEW_LINE> @as_view(name="signup") <NEW_LINE> class SignUpView(MethodView): <NEW_LINE> <INDENT> def prepare(self): <NEW_LINE> <INDENT> self.form = SignUpForm() <NEW_LINE> self.user = User() <NEW_LINE> self.service = SignUpService(self.user) <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> return render_template("signup.html", **vars(self)) <NEW_LINE> <DEDENT> def post(self): <NEW_LINE> <INDENT> if not self.form.validate(): <NEW_LINE> <INDENT> return render_template("signup.html", **vars(self)) <NEW_LINE> <DEDENT> self.form.populate_obj(self.user) <NEW_LINE> self.service.signup() <NEW_LINE> self.service.send_confirm_mail() <NEW_LINE> return redirect(url_for("account.person", id=self.user.id)) | The view to sign up. | 62598fa84527f215b58e9e1f |
class ScheduleFieldDisplayType(Enum,IComparable,IFormattable,IConvertible): <NEW_LINE> <INDENT> def __eq__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __format__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __ge__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __gt__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __le__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __lt__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __ne__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __reduce_ex__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __str__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> Max=None <NEW_LINE> Min=None <NEW_LINE> MinMax=None <NEW_LINE> Standard=None <NEW_LINE> Totals=None <NEW_LINE> value__=None | Display type of schedule field.
enum ScheduleFieldDisplayType,values: Max (3),Min (4),MinMax (2),Standard (0),Totals (1) | 62598fa857b8e32f525080b9 |
class TestOFPEchoReply(unittest.TestCase): <NEW_LINE> <INDENT> version = ofproto.OFP_VERSION <NEW_LINE> msg_type = ofproto.OFPT_ECHO_REPLY <NEW_LINE> msg_len = ofproto.OFP_HEADER_SIZE <NEW_LINE> xid = 2495926989 <NEW_LINE> def test_init(self): <NEW_LINE> <INDENT> c = OFPEchoReply(_Datapath) <NEW_LINE> eq_(c.data, None) <NEW_LINE> <DEDENT> def _test_parser(self, data): <NEW_LINE> <INDENT> fmt = ofproto.OFP_HEADER_PACK_STR <NEW_LINE> buf = pack(fmt, self.version, self.msg_type, self.msg_len, self.xid) <NEW_LINE> if data is not None: <NEW_LINE> <INDENT> buf += data <NEW_LINE> <DEDENT> res = OFPEchoReply.parser(object, self.version, self.msg_type, self.msg_len, self.xid, buf) <NEW_LINE> eq_(res.version, self.version) <NEW_LINE> eq_(res.msg_type, self.msg_type) <NEW_LINE> eq_(res.msg_len, self.msg_len) <NEW_LINE> eq_(res.xid, self.xid) <NEW_LINE> if data is not None: <NEW_LINE> <INDENT> eq_(res.data, data) <NEW_LINE> <DEDENT> <DEDENT> def test_parser_mid(self): <NEW_LINE> <INDENT> data = b'Reply Message.' <NEW_LINE> self._test_parser(data) <NEW_LINE> <DEDENT> def test_parser_max(self): <NEW_LINE> <INDENT> data = b'Reply Message.'.ljust(65527) <NEW_LINE> self._test_parser(data) <NEW_LINE> <DEDENT> def test_parser_min(self): <NEW_LINE> <INDENT> data = None <NEW_LINE> self._test_parser(data) <NEW_LINE> <DEDENT> def _test_serialize(self, data): <NEW_LINE> <INDENT> fmt = ofproto.OFP_HEADER_PACK_STR <NEW_LINE> buf = pack(fmt, self.version, self.msg_type, self.msg_len, self.xid) + data <NEW_LINE> c = OFPEchoReply(_Datapath) <NEW_LINE> c.data = data <NEW_LINE> c.serialize() <NEW_LINE> eq_(ofproto.OFP_VERSION, c.version) <NEW_LINE> eq_(ofproto.OFPT_ECHO_REPLY, c.msg_type) <NEW_LINE> eq_(0, c.xid) <NEW_LINE> fmt = '!' + ofproto.OFP_HEADER_PACK_STR.replace('!', '') + str(len(c.data)) + 's' <NEW_LINE> res = struct.unpack(fmt, six.binary_type(c.buf)) <NEW_LINE> eq_(res[0], ofproto.OFP_VERSION) <NEW_LINE> eq_(res[1], ofproto.OFPT_ECHO_REPLY) <NEW_LINE> eq_(res[2], len(buf)) <NEW_LINE> eq_(res[3], 0) <NEW_LINE> eq_(res[4], data) <NEW_LINE> <DEDENT> def test_serialize_mid(self): <NEW_LINE> <INDENT> data = b'Reply Message.' <NEW_LINE> self._test_serialize(data) <NEW_LINE> <DEDENT> def test_serialize_max(self): <NEW_LINE> <INDENT> data = b'Reply Message.'.ljust(65527) <NEW_LINE> self._test_serialize(data) <NEW_LINE> <DEDENT> @raises(AssertionError) <NEW_LINE> def test_serialize_check_data(self): <NEW_LINE> <INDENT> c = OFPEchoReply(_Datapath) <NEW_LINE> c.serialize() | Test case for ofproto_v1_2_parser.OFPEchoReply
| 62598fa8fff4ab517ebcd722 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.