code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class CMS(object): <NEW_LINE> <INDENT> __metaclass__ = CmsMetaclass <NEW_LINE> def site_main(self, galaxy=None, system=None): <NEW_LINE> <INDENT> current_planet = self.game.get_current_planet() <NEW_LINE> current_galaxy = self.game.get_galaxy(current_planet.galaxy_id) <NEW_LINE> try: <NEW_LINE> <INDENT> galaxy = int(galaxy) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> system = int(system) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> galaxy = int(self.request.REQUEST['galaxy']) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> system = int(self.request.REQUEST['system']) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> if not galaxy > 0 or galaxy > MAX_GALAXY: <NEW_LINE> <INDENT> galaxy = current_galaxy.galaxy <NEW_LINE> <DEDENT> if not system > 0 or system > MAX_SYSTEM: <NEW_LINE> <INDENT> system = current_galaxy.system <NEW_LINE> <DEDENT> if galaxy > MAX_GALAXY: <NEW_LINE> <INDENT> galaxy = 1 <NEW_LINE> <DEDENT> if system > MAX_SYSTEM: <NEW_LINE> <INDENT> system = 1 <NEW_LINE> <DEDENT> fields = [] <NEW_LINE> dane = Output() <NEW_LINE> dane.galaxy = galaxy <NEW_LINE> dane.system = system <NEW_LINE> for i in range(1, MAX_PLANETA + 1): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fields.append(Galaxy.objects.get(galaxy=galaxy, system=system, field=i)) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> fields.append(None) <NEW_LINE> <DEDENT> <DEDENT> topnav = topnav_site(self.game) <NEW_LINE> jsbody = 'onmousemove="tt_Mousemove(event);"' <NEW_LINE> return { "jsbody": jsbody, "topnav": topnav, "fields": fields, "dane": dane, "models": models, } <NEW_LINE> <DEDENT> site_main.url = "^ugame/galaxy/$" | @DynamicAttrs | 62598fbd63b5f9789fe85352 |
class MetricsManager(object): <NEW_LINE> <INDENT> __metrics_registry = None <NEW_LINE> @staticmethod <NEW_LINE> def singleton(): <NEW_LINE> <INDENT> if MetricsManager.__metrics_registry is None: <NEW_LINE> <INDENT> raise Exception('startup_metrics was not called.') <NEW_LINE> <DEDENT> return MetricsManager.__metrics_registry <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def init_argument_parser(parser, defaults): <NEW_LINE> <INDENT> InMemoryMetricsRegistry.init_argument_parser(parser, defaults) <NEW_LINE> InfluxDbMetricsRegistry.init_argument_parser(parser, defaults) <NEW_LINE> add_parser_argument( parser, 'monitoring_enabled', defaults, False, type=bool, help='Enable monitoring to stackdriver.') <NEW_LINE> add_parser_argument( parser, 'monitoring_flush_frequency', defaults, 15, help='Frequency at which to push metrics in seconds.') <NEW_LINE> add_parser_argument( parser, 'monitoring_system', defaults, 'file', choices=['file', 'influxdb'], help='Where to store metrics.') <NEW_LINE> add_parser_argument( parser, 'monitoring_context_labels', defaults, None, help='A comma-separated list of additional name=value' ' labels to add to each event to associate them together.' ' (e.g. version=release-1.2.x)') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def startup_metrics(options): <NEW_LINE> <INDENT> monitoring_systems = { 'file': InMemoryMetricsRegistry, 'influxdb': InfluxDbMetricsRegistry } <NEW_LINE> klas = monitoring_systems[options.monitoring_system] <NEW_LINE> logging.debug('Initializing monitoring with system="%s"', klas.__name__) <NEW_LINE> MetricsManager.__metrics_registry = klas(options) <NEW_LINE> if options.monitoring_enabled and options.monitoring_flush_frequency > 0: <NEW_LINE> <INDENT> MetricsManager.__metrics_registry.start_pusher_thread() <NEW_LINE> <DEDENT> return MetricsManager.__metrics_registry <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def shutdown_metrics(): <NEW_LINE> <INDENT> registry = MetricsManager.singleton() <NEW_LINE> registry.stop_pusher_thread() <NEW_LINE> registry.flush_updated_metrics() <NEW_LINE> registry.flush_final_metrics() | Acts as factory for specialized BaseMetricsRegistry singleton. | 62598fbd50812a4eaa620cdb |
class Gaus: <NEW_LINE> <INDENT> def __init__(self, x, area: float, mu: float, sigma: float): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.area = area <NEW_LINE> self.mu = mu <NEW_LINE> self.sigma = sigma <NEW_LINE> self.y = self.area/np.sqrt(2*np.pi*self.sigma**2) * np.exp(-(self.x-self.mu)**2/(2*self.sigma**2)) <NEW_LINE> <DEDENT> def equation(self): <NEW_LINE> <INDENT> return 'f(x)=area/sqrt(2 pi sigma^2) exp(-(x-mu)^2/(2 sigma^2))' <NEW_LINE> <DEDENT> def generate(self): <NEW_LINE> <INDENT> self.y = self.area/np.sqrt(2*np.pi*self.sigma**2) * np.exp(-(self.x-self.mu)**2/(2*self.sigma**2)) | Class for generating a Gaussian on the form Gaus.equation() with
norm 1 times area, mean at mu and standard deviation of sigma.
x is a numpy.ndarray of arbitrary size, respective y values for
the generated gaussian can be accessed through Gaus.y. | 62598fbd099cdd3c636754d3 |
class PKCS7Encoder(object): <NEW_LINE> <INDENT> block_size = 32 <NEW_LINE> def encode(self, text): <NEW_LINE> <INDENT> text_length = len(text) <NEW_LINE> amount_to_pad = self.block_size - (text_length % self.block_size) <NEW_LINE> if amount_to_pad == 0: <NEW_LINE> <INDENT> amount_to_pad = self.block_size <NEW_LINE> <DEDENT> pad = bytearray([amount_to_pad]) <NEW_LINE> return text + pad * amount_to_pad <NEW_LINE> <DEDENT> def decode(self, decrypted): <NEW_LINE> <INDENT> pad = ord(decrypted[-1]) <NEW_LINE> if pad < 1 or pad > 32: <NEW_LINE> <INDENT> pad = 0 <NEW_LINE> <DEDENT> return decrypted[:-pad] | 提供基于PKCS7算法的加解密接口 | 62598fbdd268445f26639c75 |
class EnterpriseServerUserAccountsUploadOrder(sgqlc.types.Input): <NEW_LINE> <INDENT> __schema__ = github_schema <NEW_LINE> __field_names__ = ('field', 'direction') <NEW_LINE> field = sgqlc.types.Field(sgqlc.types.non_null(EnterpriseServerUserAccountsUploadOrderField), graphql_name='field') <NEW_LINE> direction = sgqlc.types.Field(sgqlc.types.non_null(OrderDirection), graphql_name='direction') | Ordering options for Enterprise Server user accounts upload
connections. | 62598fbd5fdd1c0f98e5e173 |
class Exit(DefaultExit): <NEW_LINE> <INDENT> def at_traverse(self, traversing_object, target_location): <NEW_LINE> <INDENT> source_location = traversing_object.location <NEW_LINE> if self.tags.get('wild'): <NEW_LINE> <INDENT> coords = self.tags.get('wild', return_tagobj=True).db_data.split() <NEW_LINE> coords = (int(coords[0]), int(coords[1])) <NEW_LINE> if not WildRoomManager().awake(coords): <NEW_LINE> <INDENT> destination = WildRoomManager().wakeup(coords, traversing_object) <NEW_LINE> <DEDENT> if traversing_object.move_to(destination): <NEW_LINE> <INDENT> self.at_after_traverse(traversing_object, source_location) <NEW_LINE> <DEDENT> <DEDENT> elif traversing_object.move_to(target_location): <NEW_LINE> <INDENT> self.at_after_traverse(traversing_object, source_location) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.db.err_traverse: <NEW_LINE> <INDENT> self.caller.msg(self.db.err_traverse) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.at_failed_traverse(traversing_object) | Exits are connectors between rooms. Exits are normal Objects except
they defines the `destination` property. It also does work in the
following methods:
basetype_setup() - sets default exit locks (to change, use `at_object_creation` instead).
at_cmdset_get(**kwargs) - this is called when the cmdset is accessed and should
rebuild the Exit cmdset along with a command matching the name
of the Exit object. Conventionally, a kwarg `force_init`
should force a rebuild of the cmdset, this is triggered
by the `@alias` command when aliases are changed.
at_failed_traverse() - gives a default error message ("You cannot
go there") if exit traversal fails and an
attribute `err_traverse` is not defined.
Relevant hooks to overload (compared to other types of Objects):
at_traverse(traveller, target_loc) - called to do the actual traversal and calling of the other hooks.
If overloading this, consider using super() to use the default
movement implementation (and hook-calling).
at_after_traverse(traveller, source_loc) - called by at_traverse just after traversing.
at_failed_traverse(traveller) - called by at_traverse if traversal failed for some reason. Will
not be called if the attribute `err_traverse` is
defined, in which case that will simply be echoed. | 62598fbdfff4ab517ebcd9c7 |
class RemoteCollectionsEditorTableView(BaseTableView): <NEW_LINE> <INDENT> def __init__(self, parent, data, truncate=True, minmax=False, get_value_func=None, set_value_func=None, new_value_func=None, remove_values_func=None, copy_value_func=None, is_list_func=None, get_len_func=None, is_array_func=None, is_image_func=None, is_dict_func=None, get_array_shape_func=None, get_array_ndim_func=None, oedit_func=None, plot_func=None, imshow_func=None, is_data_frame_func=None, is_series_func=None, show_image_func=None, remote_editing=False): <NEW_LINE> <INDENT> BaseTableView.__init__(self, parent) <NEW_LINE> self.remote_editing_enabled = None <NEW_LINE> self.remove_values = remove_values_func <NEW_LINE> self.copy_value = copy_value_func <NEW_LINE> self.new_value = new_value_func <NEW_LINE> self.is_data_frame = is_data_frame_func <NEW_LINE> self.is_series = is_series_func <NEW_LINE> self.is_list = is_list_func <NEW_LINE> self.get_len = get_len_func <NEW_LINE> self.is_array = is_array_func <NEW_LINE> self.is_image = is_image_func <NEW_LINE> self.is_dict = is_dict_func <NEW_LINE> self.get_array_shape = get_array_shape_func <NEW_LINE> self.get_array_ndim = get_array_ndim_func <NEW_LINE> self.oedit = oedit_func <NEW_LINE> self.plot = plot_func <NEW_LINE> self.imshow = imshow_func <NEW_LINE> self.show_image = show_image_func <NEW_LINE> self.dictfilter = None <NEW_LINE> self.model = None <NEW_LINE> self.delegate = None <NEW_LINE> self.readonly = False <NEW_LINE> self.model = CollectionsModel(self, data, names=True, truncate=truncate, minmax=minmax, remote=True) <NEW_LINE> self.setModel(self.model) <NEW_LINE> self.delegate = RemoteCollectionsDelegate(self, get_value_func, set_value_func) <NEW_LINE> self.setItemDelegate(self.delegate) <NEW_LINE> self.setup_table() <NEW_LINE> self.menu = self.setup_menu(truncate, minmax) <NEW_LINE> <DEDENT> def setup_menu(self, truncate, minmax): <NEW_LINE> <INDENT> menu = BaseTableView.setup_menu(self, truncate, minmax) <NEW_LINE> return menu <NEW_LINE> <DEDENT> def oedit_possible(self, key): <NEW_LINE> <INDENT> if (self.is_list(key) or self.is_dict(key) or self.is_array(key) or self.is_image(key) or self.is_data_frame(key) or self.is_series(key)): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> def edit_item(self): <NEW_LINE> <INDENT> if self.remote_editing_enabled: <NEW_LINE> <INDENT> index = self.currentIndex() <NEW_LINE> if not index.isValid(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> key = self.model.get_key(index) <NEW_LINE> if self.oedit_possible(key): <NEW_LINE> <INDENT> self.oedit(key) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> BaseTableView.edit_item(self) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> BaseTableView.edit_item(self) | DictEditor table view | 62598fbd3617ad0b5ee06329 |
class InvalidAccess(Exception): <NEW_LINE> <INDENT> pass | Quick helper for invalid accesses | 62598fbd99fddb7c1ca62edd |
class ScheduleFunctionWithoutCalendar(ZiplineCalendarError): <NEW_LINE> <INDENT> msg = ( "To use schedule_function, the TradingAlgorithm must be running on an " "ExchangeTradingSchedule, rather than {schedule}." ) | Raised when schedule_function is called but there is not a calendar to be
used in the construction of an event rule. | 62598fbd44b2445a339b6a67 |
class CoreObject(object): <NEW_LINE> <INDENT> def __init__(self, coreRef, *args, **kwargs): <NEW_LINE> <INDENT> self.coreRef = coreRef <NEW_LINE> if hasattr(self, "onInit"): <NEW_LINE> <INDENT> self.onInit(*args, **kwargs) | Core Object
A core object knows a reference to its core. | 62598fbda219f33f346c69e9 |
class udp(packet_base.PacketBase): <NEW_LINE> <INDENT> _PACK_STR = '!HHHH' <NEW_LINE> _MIN_LEN = struct.calcsize(_PACK_STR) <NEW_LINE> _STR_CONVERT_RULE = {'csum': lambda value: '0x%x' % value} <NEW_LINE> def __init__(self, src_port, dst_port, total_length=0, csum=0): <NEW_LINE> <INDENT> super(udp, self).__init__() <NEW_LINE> self.src_port = src_port <NEW_LINE> self.dst_port = dst_port <NEW_LINE> self.total_length = total_length <NEW_LINE> self.csum = csum <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def parser(cls, buf): <NEW_LINE> <INDENT> (src_port, dst_port, total_length, csum) = struct.unpack_from( cls._PACK_STR, buf) <NEW_LINE> msg = cls(src_port, dst_port, total_length, csum) <NEW_LINE> return msg, None, buf[msg._MIN_LEN:total_length] <NEW_LINE> <DEDENT> def serialize(self, payload, prev): <NEW_LINE> <INDENT> if self.total_length == 0: <NEW_LINE> <INDENT> self.total_length = udp._MIN_LEN + len(payload) <NEW_LINE> <DEDENT> h = struct.pack(udp._PACK_STR, self.src_port, self.dst_port, self.total_length, self.csum) <NEW_LINE> if self.csum == 0: <NEW_LINE> <INDENT> self.csum = packet_utils.checksum_ip( prev, self.total_length, h + payload) <NEW_LINE> h = struct.pack(udp._PACK_STR, self.src_port, self.dst_port, self.total_length, self.csum) <NEW_LINE> <DEDENT> return h | UDP (RFC 768) header encoder/decoder class.
An instance has the following attributes at least.
Most of them are same to the on-wire counterparts but in host byte order.
__init__ takes the correspondig args in this order.
============== ====================
Attribute Description
============== ====================
src_port Source Port
dst_port Destination Port
total_length Length (0 means automatically-calculate when encoding)
csum Checksum (0 means automatically-calculate when encoding)
============== ==================== | 62598fbd4f88993c371f05fa |
class ManagedRuleSet(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'rule_set_type': {'required': True}, 'rule_set_version': {'required': True}, } <NEW_LINE> _attribute_map = { 'rule_set_type': {'key': 'ruleSetType', 'type': 'str'}, 'rule_set_version': {'key': 'ruleSetVersion', 'type': 'str'}, 'rule_group_overrides': {'key': 'ruleGroupOverrides', 'type': '[ManagedRuleGroupOverride]'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(ManagedRuleSet, self).__init__(**kwargs) <NEW_LINE> self.rule_set_type = kwargs['rule_set_type'] <NEW_LINE> self.rule_set_version = kwargs['rule_set_version'] <NEW_LINE> self.rule_group_overrides = kwargs.get('rule_group_overrides', None) | Defines a managed rule set.
All required parameters must be populated in order to send to Azure.
:param rule_set_type: Required. Defines the rule set type to use.
:type rule_set_type: str
:param rule_set_version: Required. Defines the version of the rule set to use.
:type rule_set_version: str
:param rule_group_overrides: Defines the rule group overrides to apply to the rule set.
:type rule_group_overrides:
list[~azure.mgmt.network.v2020_08_01.models.ManagedRuleGroupOverride] | 62598fbd442bda511e95c640 |
class EnvironmentAttributesTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.env = EnvironmentStub() <NEW_LINE> self.env.config.set('trac', 'base_url', 'https://trac.edgewall.org/some/path') <NEW_LINE> <DEDENT> def test_is_component_enabled(self): <NEW_LINE> <INDENT> self.assertFalse(EnvironmentStub.required) <NEW_LINE> self.assertIsNone(self.env.is_component_enabled(EnvironmentStub)) <NEW_LINE> <DEDENT> def test_db_exc(self): <NEW_LINE> <INDENT> db_exc = self.env.db_exc <NEW_LINE> self.assertTrue(hasattr(db_exc, 'IntegrityError')) <NEW_LINE> self.assertIs(db_exc, self.env.db_exc) <NEW_LINE> <DEDENT> def test_abs_href(self): <NEW_LINE> <INDENT> abs_href = self.env.abs_href <NEW_LINE> self.assertEqual('https://trac.edgewall.org/some/path', abs_href()) <NEW_LINE> self.assertIs(abs_href, self.env.abs_href) <NEW_LINE> <DEDENT> def test_href(self): <NEW_LINE> <INDENT> href = self.env.href <NEW_LINE> self.assertEqual('/some/path', href()) <NEW_LINE> self.assertIs(href, self.env.href) <NEW_LINE> <DEDENT> def test_log_file_path_is_relative_path(self): <NEW_LINE> <INDENT> log_file_path = self.env.log_file_path <NEW_LINE> self.assertEqual(os.path.join(self.env.path, 'log', 'trac.log'), log_file_path) <NEW_LINE> self.assertIs(log_file_path, self.env.log_file_path) <NEW_LINE> <DEDENT> def test_log_file_path_is_absolute_path(self): <NEW_LINE> <INDENT> log_file = os.path.join(self.env.path, 'trac.log') <NEW_LINE> self.env.config.set('logging', 'log_file', log_file) <NEW_LINE> self.assertEqual(log_file, self.env.log_file_path) <NEW_LINE> <DEDENT> def test_log_level_not_case_sensitive(self): <NEW_LINE> <INDENT> self.env.config.set('logging', 'log_level', 'warning') <NEW_LINE> self.env.config.save() <NEW_LINE> self.assertEqual('warning', self.env.config.get('logging', 'log_level')) <NEW_LINE> self.assertEqual('WARNING', self.env.log_level) <NEW_LINE> <DEDENT> def test_log_type_not_case_sensitive(self): <NEW_LINE> <INDENT> self.env.config.set('logging', 'log_type', 'File') <NEW_LINE> self.env.config.save() <NEW_LINE> self.assertEqual('File', self.env.config.get('logging', 'log_type')) <NEW_LINE> self.assertEqual('file', self.env.log_type) | Tests for attributes which don't require a real environment
on disk, and therefore can be executed against an `EnvironmentStub`
object (faster execution). | 62598fbdbf627c535bcb1688 |
class CallSignature(Definition): <NEW_LINE> <INDENT> def __init__(self, evaluator, executable_name, bracket_start_pos, index, key_name_str): <NEW_LINE> <INDENT> super(CallSignature, self).__init__(evaluator, executable_name) <NEW_LINE> self._index = index <NEW_LINE> self._key_name_str = key_name_str <NEW_LINE> self._bracket_start_pos = bracket_start_pos <NEW_LINE> <DEDENT> @property <NEW_LINE> def index(self): <NEW_LINE> <INDENT> if self._key_name_str is not None: <NEW_LINE> <INDENT> for i, param in enumerate(self.params): <NEW_LINE> <INDENT> if self._key_name_str == param.name: <NEW_LINE> <INDENT> return i <NEW_LINE> <DEDENT> <DEDENT> if self.params and self.params[-1]._name.get_definition().stars == 2: <NEW_LINE> <INDENT> return i <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> if self._index >= len(self.params): <NEW_LINE> <INDENT> for i, param in enumerate(self.params): <NEW_LINE> <INDENT> if param._name.get_definition().stars == 1: <NEW_LINE> <INDENT> return i <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> return self._index <NEW_LINE> <DEDENT> @property <NEW_LINE> def bracket_start(self): <NEW_LINE> <INDENT> return self._bracket_start_pos <NEW_LINE> <DEDENT> @property <NEW_LINE> def call_name(self): <NEW_LINE> <INDENT> warnings.warn("Use name instead.", DeprecationWarning) <NEW_LINE> return unicode(self.name) <NEW_LINE> <DEDENT> @property <NEW_LINE> def module(self): <NEW_LINE> <INDENT> return self._executable.get_parent_until() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<%s: %s index %s>' % (type(self).__name__, self._name, self.index) | `CallSignature` objects is the return value of `Script.function_definition`.
It knows what functions you are currently in. e.g. `isinstance(` would
return the `isinstance` function. without `(` it would return nothing. | 62598fbd7b180e01f3e49141 |
class Gui: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.menu_def = [['Help', 'About...']] <NEW_LINE> self.layout = [ [sg.Menu(self.menu_def)], [sg.Radio('Import HTML', group_id="selectors", default=True, key='import_select', enable_events=True), sg.Radio('Import File', group_id="selectors", key='export_select', enable_events=True)], [sg.Text('Import HTML', size=(16, 1)), sg.InputText(key='import_html'), sg.FileBrowse(key='html_file_path')], [sg.Text('Import File', size=(16, 1)), sg.InputText(key='import_text', disabled=True), sg.FileBrowse(key='text_file_path', disabled=True)], [sg.Text('Key', size=(16, 1)), sg.InputText(password_char='*', disabled=True, key='encrypt_key')], [sg.Submit('Submit', key='SUBMIT'), sg.Cancel('Cancel', key='CANCEL')]] <NEW_LINE> self.window = sg.Window('FCV Packager', self.layout) | Create the GUI | 62598fbd3539df3088ecc490 |
class FieldSelection(object): <NEW_LINE> <INDENT> def base_select(self): <NEW_LINE> <INDENT> return "select * from Field" <NEW_LINE> <DEDENT> def combine_queries(self, *queries, **kwargs): <NEW_LINE> <INDENT> combiners = kwargs.get("combiners", ()) <NEW_LINE> if len(combiners) != len(queries) - 1: <NEW_LINE> <INDENT> raise RuntimeError("Number of combiners must be one less than " "number of queries!") <NEW_LINE> <DEDENT> order_by = kwargs.get("order_by", "fieldId") <NEW_LINE> final_query = [] <NEW_LINE> final_query.append(self.base_select()) <NEW_LINE> final_query.append("where") <NEW_LINE> for combine, query in zip_longest(combiners, queries): <NEW_LINE> <INDENT> final_query.append(query) <NEW_LINE> if combine is not None: <NEW_LINE> <INDENT> final_query.append(combine) <NEW_LINE> <DEDENT> <DEDENT> final_query.append("order by {}".format(order_by)) <NEW_LINE> return self.finish_query(" ".join(final_query)) <NEW_LINE> <DEDENT> def finish_query(self, query): <NEW_LINE> <INDENT> return query + ";" <NEW_LINE> <DEDENT> def galactic_region(self, maxB, minB, endL, exclusion=False): <NEW_LINE> <INDENT> region_select = ">" if exclusion else "<=" <NEW_LINE> band = maxB - minB <NEW_LINE> sql = '(abs(fieldGB) {0} ({1} - ({2} * ' 'abs(fieldGL)) / {3}))'.format(region_select, maxB, band, endL) <NEW_LINE> return sql <NEW_LINE> <DEDENT> def get_all_fields(self): <NEW_LINE> <INDENT> return self.finish_query(self.base_select()) <NEW_LINE> <DEDENT> def select_region(self, region_type, start_value, end_value): <NEW_LINE> <INDENT> column_name = CUT_TYPEMAP[region_type] <NEW_LINE> if end_value > start_value: <NEW_LINE> <INDENT> sql = '{0} between {1} and {2}'.format(column_name, start_value, end_value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sql = '({0} between {1} and 360 or ' '{0} between 0 and {2})'.format(column_name, start_value, end_value) <NEW_LINE> <DEDENT> return sql <NEW_LINE> <DEDENT> def select_user_regions(self, id_list): <NEW_LINE> <INDENT> sql = [] <NEW_LINE> for fid in id_list: <NEW_LINE> <INDENT> sql.append("fieldId={}".format(fid)) <NEW_LINE> sql.append("or") <NEW_LINE> <DEDENT> del sql[-1] <NEW_LINE> return " ".join(sql) | Class for constructing SQL queries on the survey fields database.
This class is for creating SQL queries to perform on the survey fields
database. It does not actually perform the queries. | 62598fbd167d2b6e312b7159 |
class Models(TestCase): <NEW_LINE> <INDENT> def test_validation(self): <NEW_LINE> <INDENT> TemplateFile(title="valid", name="tests/test.tex").full_clean() <NEW_LINE> with self.assertRaises(ValidationError): <NEW_LINE> <INDENT> TemplateFile(title="invalid", name="template/doesnt.exist").full_clean() | TeXTemplateFile contains the relative path to a tex template (e.g. django_tex/test.tex)
and validates if this template can be loaded.abs
Since TeXTemplateFile is an abstract base class, it is used here in a subclassed version 'TemplateFile' | 62598fbd377c676e912f6e63 |
class IndicatorViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> serializer_class = IndicatorSerializer <NEW_LINE> queryset = Indicator.objects.all() <NEW_LINE> filter_backends = [DjangoFilterBackend] <NEW_LINE> filter_class = IndicatorFilter <NEW_LINE> filterset_fields = ['name', 'price__stock', 'price__date'] <NEW_LINE> def get_permissions(self): <NEW_LINE> <INDENT> if self.action == 'list': <NEW_LINE> <INDENT> permission_classes = [IsAuthenticated] <NEW_LINE> <DEDENT> elif self.action == 'retrieve': <NEW_LINE> <INDENT> permission_classes = [IsAuthenticated] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> permission_classes = [IsAdminUser] <NEW_LINE> <DEDENT> return [permission() for permission in permission_classes] | Indicator stored in the db. | 62598fbd796e427e5384e979 |
class Hbonds(Plugin): <NEW_LINE> <INDENT> enabled = True <NEW_LINE> order = 100 <NEW_LINE> create_command_subparser = True <NEW_LINE> def help(self): <NEW_LINE> <INDENT> return "Find and report hydrogen bonds in molecules" <NEW_LINE> <DEDENT> def process_parser(self): <NEW_LINE> <INDENT> p = self.command_subparsers['hbonds'] <NEW_LINE> group = p.add_argument_group('hbond options') <NEW_LINE> group.add_argument('--aliphatic', action='store_true', help="Includes aliphatic hydrogen bonds") <NEW_LINE> group.add_argument('--detailed', action='store_true', help="Report detailed information on hydrogen bonds.") <NEW_LINE> group.add_argument('--sort-type', action='store_true', help='Sort hydrogen bonds by type') <NEW_LINE> p = self.command_subparsers['measure'] <NEW_LINE> group = None <NEW_LINE> for ag in p._action_groups: <NEW_LINE> <INDENT> if ag.title.startswith('measure'): <NEW_LINE> <INDENT> group = ag <NEW_LINE> <DEDENT> <DEDENT> p = group if group is not None else p <NEW_LINE> p.add_argument('--rama', action='store_true', help=("Report the Ramachandran angles. Filters and " "options are ignored.")) <NEW_LINE> <DEDENT> def process(self, molecules, args): <NEW_LINE> <INDENT> for molecule in molecules: <NEW_LINE> <INDENT> self.process_molecule(molecule, args) <NEW_LINE> <DEDENT> <DEDENT> def process_molecule(self, molecule, args): <NEW_LINE> <INDENT> if args.command == 'hbonds': <NEW_LINE> <INDENT> if getattr(args, 'aliphatic', False): <NEW_LINE> <INDENT> settings.donor2_elements += "|C|13C" <NEW_LINE> settings.hbond_distance_cutoff['d1a1']= (1.8, 3.0) <NEW_LINE> <DEDENT> if hasattr(args, 'sort_type'): <NEW_LINE> <INDENT> settings.hbond_table_sort_type = args.sort_type <NEW_LINE> <DEDENT> if hasattr(args, 'detailed'): <NEW_LINE> <INDENT> settings.hbond_table_detailed = args.detailed <NEW_LINE> <DEDENT> hbonds = find_hbond_partners(molecule) <NEW_LINE> table = HBondTable(hbonds) <NEW_LINE> table.title = ('Hydrogen bond listing ' 'for {}'.format(molecule.fullname)) <NEW_LINE> print(table.content()) <NEW_LINE> <DEDENT> if getattr(args, 'rama', False): <NEW_LINE> <INDENT> table = RamaTable(molecule) <NEW_LINE> table.title = ('Ramachandran angles ' 'for {}'.format(molecule.fullname)) <NEW_LINE> print(table.content()) | The core plugin to offer the 'Hbonds' command. | 62598fbd283ffb24f3cf3a66 |
class MissingCookieError(TavernException): <NEW_LINE> <INDENT> pass | Tried to use a cookie in a request that was not present in the session
cookie jar | 62598fbd4f6381625f1995b3 |
class TweetAnalyzer(): <NEW_LINE> <INDENT> def tweets_to_dataframe(self, tweets): <NEW_LINE> <INDENT> df = pd.DataFrame(data = [tweet.full_text for tweet in tweets], columns = ["tweets"]) <NEW_LINE> df['id'] = np.array([tweet.id for tweet in tweets]) <NEW_LINE> df['len'] = np.array([len(tweet.full_text) for tweet in tweets]) <NEW_LINE> df['date'] = np.array([tweet.created_at for tweet in tweets]) <NEW_LINE> df['source'] = np.array([tweet.source for tweet in tweets]) <NEW_LINE> df['likes'] = np.array([tweet.favorite_count for tweet in tweets]) <NEW_LINE> df['retweets'] = np.array([tweet.retweet_count for tweet in tweets]) <NEW_LINE> return df | Functionality for analyzing and categorizing content from tweets | 62598fbd55399d3f056266f9 |
class CapacityReservationProperties(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'last_sku_update': {'readonly': True}, 'min_capacity': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'last_sku_update': {'key': 'lastSkuUpdate', 'type': 'str'}, 'min_capacity': {'key': 'minCapacity', 'type': 'long'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(CapacityReservationProperties, self).__init__(**kwargs) <NEW_LINE> self.last_sku_update = None <NEW_LINE> self.min_capacity = None | The Capacity Reservation properties.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar last_sku_update: The last time Sku was updated.
:vartype last_sku_update: str
:ivar min_capacity: Minimum CapacityReservation value in GB.
:vartype min_capacity: long | 62598fbd56ac1b37e63023d2 |
class PortCache(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._ports = {} <NEW_LINE> self._waiters = {} <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._ports) <NEW_LINE> <DEDENT> def get_port(self, origin): <NEW_LINE> <INDENT> if origin in self._ports: <NEW_LINE> <INDENT> sig = signal.Signal() <NEW_LINE> event.post_event(sig.emit, self._ports[origin]) <NEW_LINE> return sig <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if origin in self._waiters: <NEW_LINE> <INDENT> return self._waiters[origin] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sig = signal.Signal() <NEW_LINE> self._waiters[origin] = sig <NEW_LINE> mk.attr(origin).connect(self._attr) <NEW_LINE> return sig <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self._ports.values() <NEW_LINE> <DEDENT> def _attr(self, origin, attr): <NEW_LINE> <INDENT> from .port import Port <NEW_LINE> sig = self._waiters.pop(origin) <NEW_LINE> if attr is None: <NEW_LINE> <INDENT> port = origin <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> port = Port(origin, attr) <NEW_LINE> <DEDENT> self._ports[origin] = port <NEW_LINE> sig.emit(port) | Caches created ports. | 62598fbd2c8b7c6e89bd39a7 |
class RedFishTemplate(ZenDevice): <NEW_LINE> <INDENT> def __init__(self, record=None, username=None, password=None, url=None, priority=30, productionstate=None, additional_groups='', additional_systems='', location_override=None): <NEW_LINE> <INDENT> super(RedFishTemplate, self).__init__(record, username, password, url, priority, productionstate, additional_groups, additional_systems, location_override) <NEW_LINE> self.config['deviceclass'] = '/Server/Redfish/CIT' <NEW_LINE> <DEDENT> def get_state_object(self): <NEW_LINE> <INDENT> required_attribs = ['exists', 'name', 'url', 'username', 'password', 'priority', 'productionstate', 'groups', 'systems', 'deviceclass', 'location', 'exists', ] <NEW_LINE> missing = set(required_attribs) - set(self.config.keys()) <NEW_LINE> if len(missing) > 0: <NEW_LINE> <INDENT> raise ValueError("Not all required attributes were set before trying to generate " "a state object.") <NEW_LINE> <DEDENT> return ZenConfig( username=self.config['username'], password=self.config['password'], url=self.config['url'], deviceclass=self.config['deviceclass'], priority=self.config['priority'], productionstate=self.config['productionstate'], groups=self.config['groups'], systems=self.config['systems'], location=self.config['location'], name=self.config['name'], exists=self.config['exists'] ) | Set:
exists
name
url
username
password
priority
productionstate
groups
systems
deviceclass
location
Not Set:
get_current_state_object implemented:
True
get_state_object implemented:
True | 62598fbd3346ee7daa33773a |
class SQSClient(BaseAWSClient): <NEW_LINE> <INDENT> def __init__(self, region_name, aws_access_key_id, aws_secret_access_key, endpoint_url=None ): <NEW_LINE> <INDENT> self.__urls = {} <NEW_LINE> settings = dict( service='sqs', region_name=region_name, aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, ) <NEW_LINE> if endpoint_url: <NEW_LINE> <INDENT> settings.update( endpoint_url=endpoint_url ) <NEW_LINE> <DEDENT> super(SQSClient, self).__init__( **settings ) <NEW_LINE> <DEDENT> def create_queue( self, queue_name, retention_time=345600, visibility_timeout=300, delay_seconds=0, dead_letter_queue=None, max_receive_count=None ): <NEW_LINE> <INDENT> response = self.instance.list_queues() <NEW_LINE> for url in response.get('QueueUrls', []): <NEW_LINE> <INDENT> if url.split('/')[-1] == queue_name: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> kwargs = dict( QueueName=queue_name, Attributes=dict( DelaySeconds=str(delay_seconds), MessageRetentionPeriod=str(retention_time), VisibilityTimeout=str(visibility_timeout) )) <NEW_LINE> if dead_letter_queue and max_receive_count: <NEW_LINE> <INDENT> dead_letter_queue_arn = self.instance.get_queue_attributes( QueueUrl=self.get_queue_url(dead_letter_queue), AttributeNames=['QueueArn'] ).get('Attributes', {}).get("QueueArn") <NEW_LINE> kwargs.setdefault('Attributes', {}).update( RedrivePolicy=json.dumps(dict( deadLetterTargetArn=dead_letter_queue_arn, maxReceiveCount=max_receive_count )) ) <NEW_LINE> <DEDENT> self.instance.create_queue(**kwargs) <NEW_LINE> <DEDENT> <DEDENT> def get_queue_url(self, queue_name): <NEW_LINE> <INDENT> if queue_name not in self.__urls or not self.__urls[queue_name]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.__urls[queue_name] = self.instance.get_queue_url( QueueName=queue_name ).get('QueueUrl') <NEW_LINE> <DEDENT> except ClientError: <NEW_LINE> <INDENT> self.__urls[queue_name] = None <NEW_LINE> <DEDENT> if self.__urls[queue_name]: <NEW_LINE> <INDENT> self.__urls[queue_name] = self.__urls[queue_name].replace( "queue.amazonaws.com", "sqs.{}.amazonaws.com".format( self.settings['region_name'] ) ) <NEW_LINE> <DEDENT> <DEDENT> return self.__urls.get(queue_name) | AWS SQS client | 62598fbd3317a56b869be641 |
class SocialAuthTestsCase(unittest.TestCase): <NEW_LINE> <INDENT> SERVER_NAME = None <NEW_LINE> SERVER_PORT = None <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> client_kwargs = {} <NEW_LINE> if self.SERVER_NAME: <NEW_LINE> <INDENT> client_kwargs['SERVER_NAME'] = self.SERVER_NAME <NEW_LINE> <DEDENT> if self.SERVER_PORT: <NEW_LINE> <INDENT> client_kwargs['SERVER_PORT'] = self.SERVER_PORT <NEW_LINE> <DEDENT> self.jar = None <NEW_LINE> self.client = Client(**client_kwargs) <NEW_LINE> super(SocialAuthTestsCase, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def get_content(self, url, data=None, use_cookies=False): <NEW_LINE> <INDENT> data = data and urllib.urlencode(data, doseq=True) or data <NEW_LINE> request = urllib2.Request(url) <NEW_LINE> agent = urllib2.build_opener() <NEW_LINE> if use_cookies: <NEW_LINE> <INDENT> agent.add_handler(urllib2.HTTPCookieProcessor(self.get_jar())) <NEW_LINE> <DEDENT> request.add_header('User-Agent', USER_AGENT) <NEW_LINE> return ''.join(agent.open(request, data=data).readlines()) <NEW_LINE> <DEDENT> def get_redirect(self, url, data=None, use_cookies=False): <NEW_LINE> <INDENT> data = data and urllib.urlencode(data, doseq=True) or data <NEW_LINE> request = urllib2.Request(url) <NEW_LINE> agent = urllib2.build_opener(RedirectHandler()) <NEW_LINE> if use_cookies: <NEW_LINE> <INDENT> agent.add_handler(urllib2.HTTPCookieProcessor(self.get_jar())) <NEW_LINE> <DEDENT> request.add_header('User-Agent', USER_AGENT) <NEW_LINE> return agent.open(request, data=data) <NEW_LINE> <DEDENT> def get_jar(self): <NEW_LINE> <INDENT> if not self.jar: <NEW_LINE> <INDENT> self.jar = cookielib.CookieJar() <NEW_LINE> <DEDENT> return self.jar <NEW_LINE> <DEDENT> def reverse(self, name, backend): <NEW_LINE> <INDENT> return reverse(name, args=(backend,)) <NEW_LINE> <DEDENT> def make_relative(self, value): <NEW_LINE> <INDENT> parsed = urlparse.urlparse(value) <NEW_LINE> return urlparse.urlunparse(('', '', parsed.path, parsed.params, parsed.query, parsed.fragment)) | Base class for social auth tests | 62598fbdcc0a2c111447b1f2 |
class RefreshButton(Button): <NEW_LINE> <INDENT> def __init__(self, master, textwindow): <NEW_LINE> <INDENT> super().__init__(text='Speak again!', command=self.update) <NEW_LINE> self.textwindow = textwindow <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.textwindow.clear() <NEW_LINE> self.textwindow.write('\n\n\n') <NEW_LINE> self.textwindow.write(self.get_fortune()) <NEW_LINE> <DEDENT> def get_fortune(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> process = Popen(['fortune'], stdin=PIPE, stdout=PIPE, stderr=PIPE) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> return '\tInstall "fortune" for Wanda to give your fortune' <NEW_LINE> <DEDENT> out, err = process.communicate(b'') <NEW_LINE> if process.wait() != 0: <NEW_LINE> <INDENT> raise RuntimeError('fortune failed!') <NEW_LINE> <DEDENT> return '\t' + '\n\t'.join(out.decode('utf-8').split('\n')) | Allows refreshing of the fortune | 62598fbd3539df3088ecc492 |
class AverageMultipleIn(Actor): <NEW_LINE> <INDENT> def init(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @condition(action_input=['tem1','tem2','tem3'], action_output=['ip']) <NEW_LINE> def avg(self, temperature1, temperature2, temperature3): <NEW_LINE> <INDENT> if(temperature1[0] != 'ignore' and temperature2[0] !='ignore' and temperature3[0]!='ignore'): <NEW_LINE> <INDENT> self.result = (temperature1[0]+temperature2[0]+temperature3[0])/ 3 <NEW_LINE> self.type = temperature3[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.result = 'ignore' <NEW_LINE> self.type = 'train' <NEW_LINE> <DEDENT> return ActionResult(production=([self.result, self.type],)) <NEW_LINE> <DEDENT> action_priority = (avg,) | Divides input on port 'dividend' with input on port 'divisor'
Inputs :
tem1 :
tem2 :
tem3 :
Output :
ip: | 62598fbd377c676e912f6e64 |
class Meta: <NEW_LINE> <INDENT> ordering = ('created',) | Define meta information for model. | 62598fbd796e427e5384e97b |
class YUV(tuple): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> _fields = ('y', 'u', 'v') <NEW_LINE> def __new__(cls, y, u, v): <NEW_LINE> <INDENT> return tuple.__new__(cls, (y, u, v)) <NEW_LINE> <DEDENT> def _replace(self, **kw): <NEW_LINE> <INDENT> result = tuple.__new__(YUV, map(kw.pop, 'yuv', self)) <NEW_LINE> if kw: <NEW_LINE> <INDENT> raise ValueError( 'Got unexpected field names: {!r}'.format(list(kw))) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return ( self.__class__.__name__ + '(y={self.y:g}, u={self.u:g}, v={self.v:g})'.format(self=self)) <NEW_LINE> <DEDENT> def _asdict(self): <NEW_LINE> <INDENT> return OrderedDict(zip(self._fields, self)) <NEW_LINE> <DEDENT> def __getnewargs__(self): <NEW_LINE> <INDENT> return tuple(self) <NEW_LINE> <DEDENT> @property <NEW_LINE> def y(self): <NEW_LINE> <INDENT> return Luma(self[0]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def luma(self): <NEW_LINE> <INDENT> return Luma(self[0]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def u(self): <NEW_LINE> <INDENT> return self[1] <NEW_LINE> <DEDENT> @property <NEW_LINE> def v(self): <NEW_LINE> <INDENT> return self[2] | Named tuple representing luma and two chroma offsets | 62598fbd71ff763f4b5e7960 |
class Student: <NEW_LINE> <INDENT> def __init__(self, first_name, last_name, age): <NEW_LINE> <INDENT> self.first_name = first_name <NEW_LINE> self.last_name = last_name <NEW_LINE> self.age = age <NEW_LINE> <DEDENT> def to_json(self): <NEW_LINE> <INDENT> return self.__dict__ | class that defines a student | 62598fbd656771135c489854 |
class ReverseProxyResourceConnector: <NEW_LINE> <INDENT> isLeaf = True <NEW_LINE> implements(resource.IResource) <NEW_LINE> def __init__(self, connector, path): <NEW_LINE> <INDENT> self.connector = connector <NEW_LINE> self.path = path <NEW_LINE> <DEDENT> def render(self, request): <NEW_LINE> <INDENT> request.received_headers['host'] = self.connector.name <NEW_LINE> request.content.seek(0, 0) <NEW_LINE> qs = urlparse.urlparse(request.uri)[4] <NEW_LINE> path = self.path+'/'.join(request.postpath) <NEW_LINE> if qs: <NEW_LINE> <INDENT> rest = path + '?' + qs <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rest = path <NEW_LINE> <DEDENT> clientFactory = ProxyClientFactory(request.method, rest, request.clientproto, request.getAllHeaders(), request.content.read(), request) <NEW_LINE> self.connector.connect(clientFactory) <NEW_LINE> return server.NOT_DONE_YET | Resource that renders the results gotten from another server
Put this resource in the tree to cause everything below it to be relayed
to a different server. | 62598fbd099cdd3c636754d5 |
class AppServiceCertificatePatchResource(ProxyOnlyResource): <NEW_LINE> <INDENT> _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'system_data': {'readonly': True}, 'provisioning_state': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'kind': {'key': 'kind', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'system_data': {'key': 'systemData', 'type': 'SystemData'}, 'key_vault_id': {'key': 'properties.keyVaultId', 'type': 'str'}, 'key_vault_secret_name': {'key': 'properties.keyVaultSecretName', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, kind: Optional[str] = None, key_vault_id: Optional[str] = None, key_vault_secret_name: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(AppServiceCertificatePatchResource, self).__init__(kind=kind, **kwargs) <NEW_LINE> self.key_vault_id = key_vault_id <NEW_LINE> self.key_vault_secret_name = key_vault_secret_name <NEW_LINE> self.provisioning_state = None | Key Vault container ARM resource for a certificate that is purchased through Azure.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Resource Id.
:vartype id: str
:ivar name: Resource Name.
:vartype name: str
:ivar kind: Kind of resource.
:vartype kind: str
:ivar type: Resource type.
:vartype type: str
:ivar system_data: The system metadata relating to this resource.
:vartype system_data: ~azure.mgmt.web.v2020_09_01.models.SystemData
:ivar key_vault_id: Key Vault resource Id.
:vartype key_vault_id: str
:ivar key_vault_secret_name: Key Vault secret name.
:vartype key_vault_secret_name: str
:ivar provisioning_state: Status of the Key Vault secret. Possible values include:
"Initialized", "WaitingOnCertificateOrder", "Succeeded", "CertificateOrderFailed",
"OperationNotPermittedOnKeyVault", "AzureServiceUnauthorizedToAccessKeyVault",
"KeyVaultDoesNotExist", "KeyVaultSecretDoesNotExist", "UnknownError", "ExternalPrivateKey",
"Unknown".
:vartype provisioning_state: str or ~azure.mgmt.web.v2020_09_01.models.KeyVaultSecretStatus | 62598fbdfff4ab517ebcd9cb |
class Exhaustion(object): <NEW_LINE> <INDENT> def __init__(self, link, crossing=None): <NEW_LINE> <INDENT> if crossing is None: <NEW_LINE> <INDENT> crossing = random.choice(link.crossings) <NEW_LINE> <DEDENT> crossings = [crossing] <NEW_LINE> gluings = [[]] <NEW_LINE> frontier = set(crossing.crossing_strands()) <NEW_LINE> frontier_lengths = [4] <NEW_LINE> while len(crossings) < len(link.crossings): <NEW_LINE> <INDENT> choices = [(num_overlap(cs.opposite()[0], frontier), cs) for cs in frontier] <NEW_LINE> overlap, cs = max(choices) <NEW_LINE> C = cs.opposite().crossing <NEW_LINE> assert C not in crossings <NEW_LINE> crossings.append(C) <NEW_LINE> C_gluings = [] <NEW_LINE> for cs in C.crossing_strands(): <NEW_LINE> <INDENT> opp = cs.opposite() <NEW_LINE> if opp in frontier: <NEW_LINE> <INDENT> frontier.discard(opp) <NEW_LINE> b = cs.oriented() <NEW_LINE> a = b.opposite() <NEW_LINE> C_gluings.append((a, b)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> frontier.add(cs) <NEW_LINE> <DEDENT> <DEDENT> assert frontier_lengths[-1] + 4 - 2*overlap == len(frontier) <NEW_LINE> frontier_lengths.append(len(frontier)) <NEW_LINE> gluings.append(C_gluings) <NEW_LINE> <DEDENT> self.link = link <NEW_LINE> self.crossings = crossings <NEW_LINE> self.frontier_lengths = frontier_lengths <NEW_LINE> self.gluings = gluings <NEW_LINE> self.width = max(frontier_lengths)//2 <NEW_LINE> <DEDENT> def test_indices(self): <NEW_LINE> <INDENT> indices = StrandIndices(self.link, self.crossings) <NEW_LINE> all_gluings = sum(self.gluings, [])[:-1] <NEW_LINE> for a, b in all_gluings[:-1]: <NEW_LINE> <INDENT> indices.merge(a, b) <NEW_LINE> <DEDENT> <DEDENT> def alexander_polynomial(self): <NEW_LINE> <INDENT> D = DrorDatum(self.link, self.crossings) <NEW_LINE> gluings = self.gluings[:] <NEW_LINE> for C, gluings in zip(self.crossings, gluings)[:-1]: <NEW_LINE> <INDENT> D.add_crossing(C) <NEW_LINE> for a, b in gluings: <NEW_LINE> <INDENT> D.merge(a, b) <NEW_LINE> <DEDENT> <DEDENT> C = self.crossings[-1] <NEW_LINE> D.add_crossing(C) <NEW_LINE> for a, b in self.gluings[-1][:-1]: <NEW_LINE> <INDENT> D.merge(a, b) <NEW_LINE> <DEDENT> alex = D.omega <NEW_LINE> p, q = alex.numerator(), alex.denominator() <NEW_LINE> assert [abs(c) for c in q.coefficients()] == [1] <NEW_LINE> if p.leading_coefficient() < 0: <NEW_LINE> <INDENT> p = -p <NEW_LINE> <DEDENT> t, e = p.parent().gen(), min(p.exponents()) <NEW_LINE> return p//t**e | An exhaustion of a link where crossings are added in one-by-one
so that the resulting tangle is connected at every stage.
Starting at the given crossing, it uses a greedy algorithm to try
to minimize the sizes of the frontiers of the intermediate tangles.
If no initial crossing is specified, one is choosen at random. | 62598fbdcc40096d6161a2cc |
class ObjectAnnotation: <NEW_LINE> <INDENT> def __init__(self, label, xmin, xmax, ymin, ymax): <NEW_LINE> <INDENT> self.label = label <NEW_LINE> self.xmin = xmin <NEW_LINE> self.xmax = xmax <NEW_LINE> self.ymin = ymin <NEW_LINE> self.ymax = ymax | Value object representing the annotation of a single object within an annotated image. | 62598fbdf548e778e596b78d |
class ModelMethodRequest(ModelRequest): <NEW_LINE> <INDENT> def post(self, selector, method): <NEW_LINE> <INDENT> instance = self.model.get_one(selector) <NEW_LINE> method = getattr(instance, method) <NEW_LINE> assert method.restful is not None <NEW_LINE> result = method(**{arg: lmd(self) for arg, lmd in method.restful.iteritems()}) <NEW_LINE> self.write(json.dumps(result)) <NEW_LINE> self.flush() | /<resource>/<resource_id>/<method> | 62598fbdbf627c535bcb168c |
class DebugCustomFilter(logging.Filter): <NEW_LINE> <INDENT> def filter(self, record): <NEW_LINE> <INDENT> from .config import core, report <NEW_LINE> if record.levelname == "DEBUG": <NEW_LINE> <INDENT> return core.debug or int(report.verbosity) >= 1 <NEW_LINE> <DEDENT> if record.levelname == "DEBUG2": <NEW_LINE> <INDENT> return int(report.verbosity) > 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True | A custom filter for debug message | 62598fbd63d6d428bbee2998 |
class CallUnits(unittest.TestCase): <NEW_LINE> <INDENT> def testCase100(self): <NEW_LINE> <INDENT> resX = tdata + '/b/c/c.pod' + os.pathsep + tdata + '/b/c/c.py' + os.pathsep + tdata + '/b/c/c.pl' + os.pathsep + tdata + '/b/c/c.pm' <NEW_LINE> from filesysobjects import V3K <NEW_LINE> if os.path.exists(tdata + '/b/c/c.pyc'): <NEW_LINE> <INDENT> resX += os.pathsep + tdata + '/b/c/c.pyc' <NEW_LINE> <DEDENT> resX = filesysobjects.apppaths.splitapppathx(resX) <NEW_LINE> arg = tdata + '\\b\\"""\\\\[^\\\\]*\\\\"""[c][.][p][^"""\\\\"""]*' <NEW_LINE> arg = filesysobjects.pathtools.stripquotes(arg) <NEW_LINE> res = filesysobjects.pathtools.expandpath(arg) <NEW_LINE> self.assertEqual(sorted(res), sorted(resX)) | Sets the specific data array and required parameters for test case.
| 62598fbd97e22403b383b0ef |
class CommonFlat(Flat): <NEW_LINE> <INDENT> def __init__(self, node, test_directory): <NEW_LINE> <INDENT> self.common_params = {'output_file': ['', 'Missing output file'], 'golden_file': ['', ''], 'stdout_file': ['', '']} <NEW_LINE> self.test_directory = test_directory <NEW_LINE> Flat.__init__(self, node, self.common_params) <NEW_LINE> <DEDENT> def get_output_file(self): <NEW_LINE> <INDENT> return os.path.join(self.test_directory, self.get_parameter('output_file')) <NEW_LINE> <DEDENT> def get_golden_file(self): <NEW_LINE> <INDENT> if self.get_parameter('golden_file'): <NEW_LINE> <INDENT> return os.path.join(self.test_directory, self.get_parameter('golden_file')) <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def get_stdout_file(self): <NEW_LINE> <INDENT> return os.path.join(self.test_directory, self.get_parameter('stdout_file')) | The class inheriting from Flat. Designed to handle common test
parameters. | 62598fbd0fa83653e46f50cc |
class ConsoleAuthAPI(nova.openstack.common.rpc.proxy.RpcProxy): <NEW_LINE> <INDENT> BASE_RPC_API_VERSION = '1.0' <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(ConsoleAuthAPI, self).__init__( topic=CONF.consoleauth_topic, default_version=self.BASE_RPC_API_VERSION) <NEW_LINE> <DEDENT> def authorize_console(self, ctxt, token, console_type, host, port, internal_access_path): <NEW_LINE> <INDENT> return self.call(ctxt, self.make_msg('authorize_console', token=token, console_type=console_type, host=host, port=port, internal_access_path=internal_access_path)) <NEW_LINE> <DEDENT> def check_token(self, ctxt, token): <NEW_LINE> <INDENT> return self.call(ctxt, self.make_msg('check_token', token=token)) <NEW_LINE> <DEDENT> def get_backdoor_port(self, ctxt, host): <NEW_LINE> <INDENT> return self.call(ctxt, self.make_msg('get_backdoor_port'), version='1.1') | Client side of the consoleauth rpc API.
API version history:
1.0 - Initial version.
1.1 - Added get_backdoor_port() | 62598fbd7d847024c075c5a5 |
class ChatTitleEmpty(BadRequest): <NEW_LINE> <INDENT> ID = "CHAT_TITLE_EMPTY" <NEW_LINE> MESSAGE = __doc__ | The chat title is empty | 62598fbda05bb46b3848aa53 |
class RitaLexer(RegexLexer): <NEW_LINE> <INDENT> name = 'Rita' <NEW_LINE> filenames = ['*.rita'] <NEW_LINE> aliases = ['rita'] <NEW_LINE> mimetypes = ['text/rita'] <NEW_LINE> tokens = { 'root': [ (r'\n', Whitespace), (r'\s+', Whitespace), (r'#(.*?)\n', Comment.Single), (r'@(.*?)\n', Operator), (r'"(\w|\d|\s|(\\")|[\'_\-./,\?\!])+?"', Literal), (r'\'(\w|\d|\s|(\\\')|["_\-./,\?\!])+?\'', Literal), (r'([A-Z_]+)', Keyword), (r'([a-z0-9_]+)', Name), (r'((->)|[!?+*|=])', Operator), (r'[\(\),\{\}]', Punctuation) ] } | Lexer for `RITA <https://github.com/zaibacu/rita-dsl>`_
.. versionadded:: 2.11 | 62598fbdad47b63b2c5a7a3e |
class LogEngine(BaseEngine): <NEW_LINE> <INDENT> def __init__(self, main_engine: MainEngine, event_engine: EventEngine): <NEW_LINE> <INDENT> super(LogEngine, self).__init__(main_engine, event_engine, "log") <NEW_LINE> if not SETTINGS["log.active"]: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.level = SETTINGS["log.level"] <NEW_LINE> self.logger = logging.getLogger("VN Trader") <NEW_LINE> self.logger.setLevel(self.level) <NEW_LINE> self.formatter = logging.Formatter( "%(asctime)s %(levelname)s: %(message)s" ) <NEW_LINE> self.add_null_handler() <NEW_LINE> if SETTINGS["log.console"]: <NEW_LINE> <INDENT> self.add_console_handler() <NEW_LINE> <DEDENT> if SETTINGS["log.file"]: <NEW_LINE> <INDENT> self.add_file_handler() <NEW_LINE> <DEDENT> self.register_event() <NEW_LINE> <DEDENT> def add_null_handler(self): <NEW_LINE> <INDENT> null_handler = logging.NullHandler() <NEW_LINE> self.logger.addHandler(null_handler) <NEW_LINE> <DEDENT> def add_console_handler(self): <NEW_LINE> <INDENT> console_handler = logging.StreamHandler() <NEW_LINE> console_handler.setLevel(self.level) <NEW_LINE> console_handler.setFormatter(self.formatter) <NEW_LINE> self.logger.addHandler(console_handler) <NEW_LINE> <DEDENT> def add_file_handler(self): <NEW_LINE> <INDENT> today_date = datetime.now().strftime("%Y%m%d") <NEW_LINE> filename = f"vt_{today_date}.log" <NEW_LINE> log_path = get_folder_path("log") <NEW_LINE> file_path = log_path.joinpath(filename) <NEW_LINE> file_handler = logging.FileHandler( file_path, mode="a", encoding="utf8" ) <NEW_LINE> file_handler.setLevel(self.level) <NEW_LINE> file_handler.setFormatter(self.formatter) <NEW_LINE> self.logger.addHandler(file_handler) <NEW_LINE> <DEDENT> def register_event(self): <NEW_LINE> <INDENT> self.event_engine.register(EVENT_LOG, self.process_log_event) <NEW_LINE> <DEDENT> def process_log_event(self, event: Event): <NEW_LINE> <INDENT> log = event.data <NEW_LINE> self.logger.log(log.level, log.msg) | Processes log event and output with logging module. | 62598fbd3617ad0b5ee0632f |
class DjangoAdminSettingsDirectory(AdminScriptTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.write_settings('settings', is_dir=True) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.remove_settings('settings', is_dir=True) <NEW_LINE> <DEDENT> def test_setup_environ(self): <NEW_LINE> <INDENT> args = ['startapp', 'settings_test'] <NEW_LINE> app_path = os.path.join(test_dir, 'settings_test') <NEW_LINE> out, err = self.run_django_admin(args, 'test_project.settings') <NEW_LINE> self.addCleanup(shutil.rmtree, app_path) <NEW_LINE> self.assertNoOutput(err) <NEW_LINE> self.assertTrue(os.path.exists(app_path)) <NEW_LINE> <DEDENT> def test_setup_environ_custom_template(self): <NEW_LINE> <INDENT> template_path = os.path.join(custom_templates_dir, 'app_template') <NEW_LINE> args = ['startapp', '--template', template_path, 'custom_settings_test'] <NEW_LINE> app_path = os.path.join(test_dir, 'custom_settings_test') <NEW_LINE> out, err = self.run_django_admin(args, 'test_project.settings') <NEW_LINE> self.addCleanup(shutil.rmtree, app_path) <NEW_LINE> self.assertNoOutput(err) <NEW_LINE> self.assertTrue(os.path.exists(app_path)) <NEW_LINE> self.assertTrue(os.path.exists(os.path.join(app_path, 'api.py'))) <NEW_LINE> <DEDENT> def test_builtin_command(self): <NEW_LINE> <INDENT> args = ['check', 'admin_scripts'] <NEW_LINE> out, err = self.run_django_admin(args) <NEW_LINE> self.assertNoOutput(out) <NEW_LINE> self.assertOutput(err, 'settings are not configured') <NEW_LINE> <DEDENT> def test_builtin_with_bad_settings(self): <NEW_LINE> <INDENT> args = ['check', '--settings=bad_settings', 'admin_scripts'] <NEW_LINE> out, err = self.run_django_admin(args) <NEW_LINE> self.assertOutput(err, "No module named '?bad_settings'?", regex=True) <NEW_LINE> <DEDENT> def test_builtin_with_bad_environment(self): <NEW_LINE> <INDENT> args = ['check', 'admin_scripts'] <NEW_LINE> out, err = self.run_django_admin(args, 'bad_settings') <NEW_LINE> self.assertNoOutput(out) <NEW_LINE> self.assertOutput(err, "No module named '?bad_settings'?", regex=True) <NEW_LINE> <DEDENT> def test_custom_command(self): <NEW_LINE> <INDENT> args = ['noargs_command'] <NEW_LINE> out, err = self.run_django_admin(args) <NEW_LINE> self.assertNoOutput(out) <NEW_LINE> self.assertOutput(err, "settings are not configured") <NEW_LINE> <DEDENT> def test_builtin_with_settings(self): <NEW_LINE> <INDENT> args = ['check', '--settings=test_project.settings', 'admin_scripts'] <NEW_LINE> out, err = self.run_django_admin(args) <NEW_LINE> self.assertNoOutput(err) <NEW_LINE> self.assertOutput(out, SYSTEM_CHECK_MSG) <NEW_LINE> <DEDENT> def test_builtin_with_environment(self): <NEW_LINE> <INDENT> args = ['check', 'admin_scripts'] <NEW_LINE> out, err = self.run_django_admin(args, 'test_project.settings') <NEW_LINE> self.assertNoOutput(err) <NEW_LINE> self.assertOutput(out, SYSTEM_CHECK_MSG) | A series of tests for django-admin.py when the settings file is in a
directory. (see #9751). | 62598fbd5166f23b2e2435c7 |
class Poisson: <NEW_LINE> <INDENT> def __init__(self, data=None, lambtha=1.): <NEW_LINE> <INDENT> if not data: <NEW_LINE> <INDENT> if lambtha <= 0: <NEW_LINE> <INDENT> raise ValueError('lambtha must be a positive value') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.lambtha = lambtha/1.0 <NEW_LINE> <DEDENT> <DEDENT> if data: <NEW_LINE> <INDENT> if type(data) is not list: <NEW_LINE> <INDENT> raise TypeError('data must be a list') <NEW_LINE> <DEDENT> if len(data) < 2: <NEW_LINE> <INDENT> raise ValueError('data must contain multiple values') <NEW_LINE> <DEDENT> self.lambtha = (sum(data) / len(data)) / 1.0 | A class | 62598fbd7cff6e4e811b5c0c |
class Robot(object): <NEW_LINE> <INDENT> mov_d = {0: (0, 1), 1: (1, 0), 2: (0, -1), 3: (-1, 0)} <NEW_LINE> def __init__(self, x, y, dir): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = y <NEW_LINE> self.dir = dir <NEW_LINE> <DEDENT> def mov(self): <NEW_LINE> <INDENT> self.x += Robot.mov_d[self.dir][0] <NEW_LINE> self.y += Robot.mov_d[self.dir][1] <NEW_LINE> <DEDENT> def turn_right(self, k): <NEW_LINE> <INDENT> self.dir = (self.dir + k) % 4 <NEW_LINE> <DEDENT> def turn_left(self, k): <NEW_LINE> <INDENT> self.dir = (self.dir - k) % 4 <NEW_LINE> <DEDENT> def clean(self): <NEW_LINE> <INDENT> print("clean ({}, {})".format(self.x, self.y)) <NEW_LINE> <DEDENT> def mov_dir(self, d): <NEW_LINE> <INDENT> if d == 0: <NEW_LINE> <INDENT> self.mov() <NEW_LINE> <DEDENT> elif d == -1: <NEW_LINE> <INDENT> self.turn_left(1) <NEW_LINE> self.mov() <NEW_LINE> <DEDENT> elif d == 1: <NEW_LINE> <INDENT> self.turn_right(1) <NEW_LINE> self.mov() <NEW_LINE> <DEDENT> <DEDENT> def back(self): <NEW_LINE> <INDENT> self.turn_left(2) <NEW_LINE> self.mov() <NEW_LINE> self.turn_left(2) <NEW_LINE> <DEDENT> def back_from(self, d): <NEW_LINE> <INDENT> if d == 0: <NEW_LINE> <INDENT> self.back() <NEW_LINE> <DEDENT> elif d == -1: <NEW_LINE> <INDENT> self.back() <NEW_LINE> self.turn_right(1) <NEW_LINE> <DEDENT> elif d == 1: <NEW_LINE> <INDENT> self.back() <NEW_LINE> self.turn_left(1) | 题目隐藏了Robot的一种重要参数 abs direction, 即为当前robot朝那个方向:
我们定位为 0 x轴向右, j+1
1 y轴向下, i+1
2 x轴向左, j-1
3 y轴向上, i-1 | 62598fbd167d2b6e312b715f |
class IRATUpdateView(LoginRequiredMixin, PermissionMixin, UpdateView): <NEW_LINE> <INDENT> model = TBLSession <NEW_LINE> template_name = 'irat/irat.html' <NEW_LINE> form_class = IRATForm <NEW_LINE> permissions_required = ['crud_tests'] <NEW_LINE> def get_discipline(self): <NEW_LINE> <INDENT> discipline = Discipline.objects.get( slug=self.kwargs.get('slug', '') ) <NEW_LINE> return discipline <NEW_LINE> <DEDENT> def form_valid(self, form): <NEW_LINE> <INDENT> messages.success(self.request, _('iRAT updated successfully.')) <NEW_LINE> return super(IRATUpdateView, self).form_valid(form) <NEW_LINE> <DEDENT> def get_success_url(self): <NEW_LINE> <INDENT> success_url = reverse_lazy( 'irat:list', kwargs={ 'slug': self.kwargs.get('slug', ''), 'pk': self.kwargs.get('pk', '') } ) <NEW_LINE> return success_url | Update the iRAT duration and weight | 62598fbd5fcc89381b266241 |
class ProjectVariationDelete(UserPassesTestMixin, DeleteView): <NEW_LINE> <INDENT> model = Variation <NEW_LINE> template_name = 'dashboard/project_variation_confirm_delete.html' <NEW_LINE> success_message = 'Variation deleted successfully.' <NEW_LINE> def test_func(self, *args, **kwargs): <NEW_LINE> <INDENT> variation = get_object_or_404(Variation, pk=self.kwargs['pk']) <NEW_LINE> return self.request.user.is_active and self.request.user.is_staff and variation.project.contractor == self.request.user.profile.contractor <NEW_LINE> <DEDENT> def get_success_url(self, *args, **kwargs): <NEW_LINE> <INDENT> return reverse('dashboard:project-detail', kwargs={'pk': str(self.kwargs['project_pk'])}) <NEW_LINE> <DEDENT> def delete(self, *args, **kwargs): <NEW_LINE> <INDENT> messages.success(self.request, self.success_message) <NEW_LINE> return super(ProjectVariationDelete, self).delete(*args, **kwargs) <NEW_LINE> <DEDENT> def get_context_data(self, *args, **kwargs): <NEW_LINE> <INDENT> context = super(ProjectVariationDelete, self).get_context_data(*args, **kwargs) <NEW_LINE> context['page_name'] = 'projects' <NEW_LINE> return context | Delete a particular a variation record from the current project | 62598fbd76e4537e8c3ef78f |
class NotWordExpression: <NEW_LINE> <INDENT> def __init__(self, exp): <NEW_LINE> <INDENT> self.exp = exp <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'NotWordExpression({})'.format(self.exp) <NEW_LINE> <DEDENT> def eval(self): <NEW_LINE> <INDENT> all_par = set(Paragraph.objects.all()) <NEW_LINE> exp_par = self.exp.eval() <NEW_LINE> return all_par - exp_par | Represents NOT expression | 62598fbd7047854f4633f5bd |
class Adapter(Target): <NEW_LINE> <INDENT> def __init__(self: Adapter, target_object: Adaptee) -> None: <NEW_LINE> <INDENT> self._target_object = target_object <NEW_LINE> <DEDENT> def method_1(self: Adapter) -> None: <NEW_LINE> <INDENT> self._target_object.method_adaptee_1() <NEW_LINE> <DEDENT> def method_2(self: Adapter) -> None: <NEW_LINE> <INDENT> self._target_object.method_adaptee_1() <NEW_LINE> self._target_object.method_adaptee_2() | Объект, заменяющий целевой объект. | 62598fbd71ff763f4b5e7964 |
class PasswordChanger(object): <NEW_LINE> <INDENT> def __init__(self, osclients_o=None): <NEW_LINE> <INDENT> if not osclients_o: <NEW_LINE> <INDENT> osclients_o = osclients.OpenStackClients() <NEW_LINE> <DEDENT> if 'KEYSTONE_ADMIN_ENDPOINT' in os.environ: <NEW_LINE> <INDENT> osclients_o.override_endpoint( 'identity', osclients_o.region, 'admin', os.environ['KEYSTONE_ADMIN_ENDPOINT']) <NEW_LINE> <DEDENT> self.keystone = osclients_o.get_keystoneclient() <NEW_LINE> self.users_by_id = dict() <NEW_LINE> for user in self.keystone.users.list(): <NEW_LINE> <INDENT> self.users_by_id[user.id] = user <NEW_LINE> <DEDENT> <DEDENT> def change_password(self, userobj, newpassword): <NEW_LINE> <INDENT> userid = userobj.id <NEW_LINE> (resp, user) = self.keystone.users.client.get('/users/' + userid) <NEW_LINE> if not resp.ok: <NEW_LINE> <INDENT> raise Exception(str(resp.status_code) + ' ' + resp.reason) <NEW_LINE> <DEDENT> user['user']['password'] = newpassword <NEW_LINE> (resp, user) = self.keystone.users.client.patch('/users/' + userid, body=user) <NEW_LINE> if not resp.ok: <NEW_LINE> <INDENT> raise Exception(str(resp.status_code) + ' ' + resp.reason) <NEW_LINE> <DEDENT> <DEDENT> def reset_password(self, userobj): <NEW_LINE> <INDENT> rand = open('/dev/urandom') <NEW_LINE> password = base64.b64encode(rand.read(16), '.!')[:21] <NEW_LINE> self.change_password(userobj, password) <NEW_LINE> return password <NEW_LINE> <DEDENT> def get_user_byid(self, userid): <NEW_LINE> <INDENT> return self.users_by_id[userid] <NEW_LINE> <DEDENT> def get_user_byname(self, username): <NEW_LINE> <INDENT> return self.keystone.users.find(name=username) <NEW_LINE> <DEDENT> def get_list_users_with_cred(self, list_user_ids): <NEW_LINE> <INDENT> list_creds = list() <NEW_LINE> for user_id in list_user_ids: <NEW_LINE> <INDENT> userobj = self.get_user_byid(user_id) <NEW_LINE> password = self.reset_password(userobj) <NEW_LINE> cred = (userobj.name, password, userobj.default_project_id) <NEW_LINE> list_creds.append(cred) <NEW_LINE> <DEDENT> return list_creds | Class to change/reset the password of any user | 62598fbdf548e778e596b790 |
class NumpyBaseEstimator: <NEW_LINE> <INDENT> def _fit_validation(self, X, y): <NEW_LINE> <INDENT> assert isinstance(X, Iterable) and isinstance(y, Iterable) <NEW_LINE> assert len(X) == len(y) <NEW_LINE> X = X if isinstance(X, np.ndarray) else np.array(X) <NEW_LINE> y = y if isinstance(y, np.ndarray) else np.array(y) <NEW_LINE> if X.ndim != 2: <NEW_LINE> <INDENT> raise ValueError(f"X dim must be 2, got {X.ndim} dim of X! ") <NEW_LINE> <DEDENT> return X, y <NEW_LINE> <DEDENT> def _predict_validation(self, X_test): <NEW_LINE> <INDENT> assert isinstance(X_test, Iterable) <NEW_LINE> X_test = X_test if isinstance(X_test, np.ndarray) else np.array(X_test) <NEW_LINE> error_text = f"Mismatched shape for X_test! Get {X_test.shape}, only" f" ({self._X_train.shape[1]}, ) or (_, {self._X_train.shape[1]}) " f"X_test can be." <NEW_LINE> if X_test.ndim == 1: <NEW_LINE> <INDENT> if X_test.shape[0] != self._X_train.shape[1]: <NEW_LINE> <INDENT> raise ValueError(error_text) <NEW_LINE> <DEDENT> <DEDENT> elif X_test.ndim == 2: <NEW_LINE> <INDENT> if X_test.shape[1] != self._X_train.shape[1]: <NEW_LINE> <INDENT> raise ValueError(error_text) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError(f"X_test with the {X_test.ndim} dim! Only 1 or 2 dim X_test can be.") <NEW_LINE> <DEDENT> return X_test <NEW_LINE> <DEDENT> def _score_validation(self, X_test, y_test): <NEW_LINE> <INDENT> X_test = self._predict_validation(X_test) <NEW_LINE> is_valid = True <NEW_LINE> if isinstance(y_test, Iterable): <NEW_LINE> <INDENT> if X_test.shape[0] != len(y_test): <NEW_LINE> <INDENT> is_valid = False <NEW_LINE> <DEDENT> elif X_test.ndim == 1: <NEW_LINE> <INDENT> is_valid = False <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> assert isinstance(y_test, int) or isinstance(y_test, float) <NEW_LINE> if X_test.ndim != 1: <NEW_LINE> <INDENT> is_valid = False <NEW_LINE> <DEDENT> <DEDENT> y_test = np.array(y_test) <NEW_LINE> if not is_valid: <NEW_LINE> <INDENT> raise ValueError(f"Mismatched shape for y_test! X_test with {X_test.shape} shape, but " f"y_test's shape is {y_test.shape}") <NEW_LINE> <DEDENT> return X_test, y_test | Numpy estimator base class for all numpy estimator. | 62598fbdadb09d7d5dc0a766 |
class BBCodeCheck(TargetCheck): <NEW_LINE> <INDENT> check_id = 'bbcode' <NEW_LINE> name = _('Mismatched BBcode') <NEW_LINE> description = _('BBcode in translation does not match source') <NEW_LINE> severity = 'warning' <NEW_LINE> def check_single(self, source, target, unit, cache_slot): <NEW_LINE> <INDENT> src_match = self.get_cache(unit, cache_slot) <NEW_LINE> if src_match is None: <NEW_LINE> <INDENT> src_match = BBCODE_MATCH.findall(source) <NEW_LINE> self.set_cache(unit, src_match, cache_slot) <NEW_LINE> <DEDENT> if len(src_match) == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> tgt_match = BBCODE_MATCH.findall(target) <NEW_LINE> if len(src_match) != len(tgt_match): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> src_tags = set([x[0] for x in src_match]) <NEW_LINE> tgt_tags = set([x[0] for x in tgt_match]) <NEW_LINE> return src_tags != tgt_tags | Check for matching bbcode tags. | 62598fbd7d43ff24874274f9 |
class LabelDomainUtilsMixin(models.Model): <NEW_LINE> <INDENT> @property <NEW_LINE> def pretty_name(self): <NEW_LINE> <INDENT> return self.fqdn <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> <DEDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(LabelDomainUtilsMixin, self).__init__(*args, **kwargs) <NEW_LINE> if self.pk is None and self.fqdn: <NEW_LINE> <INDENT> self.label_domain_from_fqdn() <NEW_LINE> <DEDENT> <DEDENT> def label_domain_from_fqdn(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.domain = Domain.objects.get(name=self.fqdn) <NEW_LINE> self.label = '' <NEW_LINE> <DEDENT> except Domain.DoesNotExist: <NEW_LINE> <INDENT> parts = self.fqdn.split('.', 1) <NEW_LINE> if len(parts) == 2: <NEW_LINE> <INDENT> self.label = parts[0] <NEW_LINE> self.domain = Domain.objects.get(name=parts[1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.label = '' <NEW_LINE> self.domain = Domain.objects.get(name=parts[0]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def clean(self, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.domain <NEW_LINE> <DEDENT> except Domain.DoesNotExist: <NEW_LINE> <INDENT> raise ValidationError('') <NEW_LINE> <DEDENT> self.set_fqdn() <NEW_LINE> super(LabelDomainUtilsMixin, self).clean(*args, **kwargs) <NEW_LINE> <DEDENT> def set_fqdn(self): <NEW_LINE> <INDENT> if self.label: <NEW_LINE> <INDENT> self.fqdn = self.label + '.' + self.domain.name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.fqdn = self.domain.name | This class provides common functionality that many DNS record
classes share.
If you plan on using the ``unique_together`` constraint on a Model
that inherits from ``LabelDomainUtilsMixin`` or ``LabelDomainMixin``, you
must include ``domain`` and ``label`` explicitly if you need them to.
All common records have an ``fqdn`` field. This field is updated
every time the object is saved::
fqdn = name + domain.name
or if name == ''
fqdn = domain.name
This field makes searching for records much easier. Instead of
looking at ``obj.label`` together with ``obj.domain.name``, you can
just search the ``obj.fqdn`` field.
"the total number of octets that represent a name (i.e., the sum of
all label octets and label lengths) is limited to 255" - RFC 4471 | 62598fbd099cdd3c636754d7 |
class ShellExampleTests(PyFlinkTestCase): <NEW_LINE> <INDENT> def test_batch_case(self): <NEW_LINE> <INDENT> from pyflink.shell import b_env, bt_env, FileSystem, OldCsv, DataTypes, Schema <NEW_LINE> import tempfile <NEW_LINE> import os <NEW_LINE> import shutil <NEW_LINE> sink_path = tempfile.gettempdir() + '/batch.csv' <NEW_LINE> if os.path.exists(sink_path): <NEW_LINE> <INDENT> if os.path.isfile(sink_path): <NEW_LINE> <INDENT> os.remove(sink_path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> shutil.rmtree(sink_path) <NEW_LINE> <DEDENT> <DEDENT> b_env.set_parallelism(1) <NEW_LINE> t = bt_env.from_elements([(1, 'hi', 'hello'), (2, 'hi', 'hello')], ['a', 'b', 'c']) <NEW_LINE> bt_env.connect(FileSystem().path(sink_path)) .with_format(OldCsv() .field_delimiter(',') .field("a", DataTypes.BIGINT()) .field("b", DataTypes.STRING()) .field("c", DataTypes.STRING())) .with_schema(Schema() .field("a", DataTypes.BIGINT()) .field("b", DataTypes.STRING()) .field("c", DataTypes.STRING())) .create_temporary_table("batch_sink") <NEW_LINE> t.select("a + 1, b, c").insert_into("batch_sink") <NEW_LINE> bt_env.execute("batch_job") <NEW_LINE> with open(sink_path, 'r') as f: <NEW_LINE> <INDENT> lines = f.read() <NEW_LINE> self.assertEqual(lines, '2,hi,hello\n' + '3,hi,hello\n') <NEW_LINE> <DEDENT> <DEDENT> def test_stream_case(self): <NEW_LINE> <INDENT> from pyflink.shell import s_env, st_env, FileSystem, OldCsv, DataTypes, Schema <NEW_LINE> import tempfile <NEW_LINE> import os <NEW_LINE> import shutil <NEW_LINE> sink_path = tempfile.gettempdir() + '/streaming.csv' <NEW_LINE> if os.path.exists(sink_path): <NEW_LINE> <INDENT> if os.path.isfile(sink_path): <NEW_LINE> <INDENT> os.remove(sink_path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> shutil.rmtree(sink_path) <NEW_LINE> <DEDENT> <DEDENT> s_env.set_parallelism(1) <NEW_LINE> t = st_env.from_elements([(1, 'hi', 'hello'), (2, 'hi', 'hello')], ['a', 'b', 'c']) <NEW_LINE> st_env.connect(FileSystem().path(sink_path)) .with_format(OldCsv() .field_delimiter(',') .field("a", DataTypes.BIGINT()) .field("b", DataTypes.STRING()) .field("c", DataTypes.STRING())) .with_schema(Schema() .field("a", DataTypes.BIGINT()) .field("b", DataTypes.STRING()) .field("c", DataTypes.STRING())) .create_temporary_table("stream_sink") <NEW_LINE> t.select("a + 1, b, c").insert_into("stream_sink") <NEW_LINE> st_env.execute("stream_job") <NEW_LINE> with open(sink_path, 'r') as f: <NEW_LINE> <INDENT> lines = f.read() <NEW_LINE> self.assertEqual(lines, '2,hi,hello\n' + '3,hi,hello\n') | If these tests failed, please fix these examples code and copy them to shell.py | 62598fbd97e22403b383b0f2 |
class Keywordtopic20(AbstructFeature): <NEW_LINE> <INDENT> DIMNUM = 20 <NEW_LINE> key = f"Keywordtopic{DIMNUM}" <NEW_LINE> def create_features(self): <NEW_LINE> <INDENT> topic_texts_pairs = defaultdict(list) <NEW_LINE> for k in TOPIC_KEYWORDS.keys(): <NEW_LINE> <INDENT> topic_texts_pairs[k] = train[train.topic_keyword == k].mecab_text.to_list() <NEW_LINE> topic_texts_pairs[k] += test[test.topic_keyword == k].mecab_text.to_list() <NEW_LINE> <DEDENT> cv = CountVectorizer(min_df=0.04, stop_words=STOPWORDS) <NEW_LINE> lda = LDA(self.DIMNUM, random_state=RANDOM_STATE) <NEW_LINE> corpus = [" ".join(v) for k, v in topic_texts_pairs.items()] <NEW_LINE> cv.fit(corpus) <NEW_LINE> cvec = cv.transform(corpus) <NEW_LINE> lda.fit(cvec) <NEW_LINE> lda_vec = lda.transform(cvec) <NEW_LINE> str_lda_vec_list = [] <NEW_LINE> for l in lda_vec.tolist(): <NEW_LINE> <INDENT> str_lda_vec_list.append([str(val) for val in l]) <NEW_LINE> <DEDENT> for i, k in enumerate(TOPIC_KEYWORDS.keys()): <NEW_LINE> <INDENT> train.loc[train.topic_keyword == k, self.key] = " ".join( str_lda_vec_list[i] ) <NEW_LINE> test.loc[test.topic_keyword == k, self.key] = " ".join(str_lda_vec_list[i]) <NEW_LINE> <DEDENT> self._train[self.key] = train[self.key] <NEW_LINE> self._test[self.key] = test[self.key] | keyword単位でツイート集合を作ってトピックモデリングからベクトルを取得
Args:
AbstructFeature ([type]): [description] | 62598fbda8370b77170f05ca |
class ShowBootvarSchema(MetaParser): <NEW_LINE> <INDENT> pass | Schema for show bootvar | 62598fbdd268445f26639c79 |
class Pluginmanager: <NEW_LINE> <INDENT> def __init__(self, quickload=False): <NEW_LINE> <INDENT> self.p_mgr = None <NEW_LINE> self.plugins = None <NEW_LINE> self.plugins_loaded = False <NEW_LINE> if quickload: <NEW_LINE> <INDENT> self.load_plugins() <NEW_LINE> <DEDENT> <DEDENT> def load_plugins(self): <NEW_LINE> <INDENT> if not self.plugins_loaded: <NEW_LINE> <INDENT> logger.info("Loading plugins ...") <NEW_LINE> with PikeManager([os.path.dirname(os.path.realpath(__file__)) + '/plugins']) as self.p_mgr: <NEW_LINE> <INDENT> classes = self.p_mgr.get_all_inherited_classes(Pluginbase) <NEW_LINE> <DEDENT> logger.debug(" >> %d class(es) inherited from Pluginbase detected: %s", len(classes), str(classes)) <NEW_LINE> self.plugins = [] <NEW_LINE> for pl_class in classes: <NEW_LINE> <INDENT> if hasattr(pl_class, 'MHPLUGIN') and hasattr(pl_class, 'NAME') and pl_class.MHPLUGIN: <NEW_LINE> <INDENT> if pl_class.NAME is not None and pl_class.VERSION is not None and pl_class.AUTHOR is not None: <NEW_LINE> <INDENT> self.plugins.append(pl_class()) <NEW_LINE> logger.info(" - Loaded: " + pl_class.NAME + " - version: " + str(pl_class.VERSION) + " by " + pl_class.AUTHOR) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> plugin_str = str(pl_class) <NEW_LINE> logger.warning(" >> Some mandatory attributes of plugin class %s are undefined. Please correct this and reload the application.", plugin_str) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> logger.info("%d plugin(s) found.", len(self.plugins)) <NEW_LINE> self.plugins_loaded = True <NEW_LINE> <DEDENT> <DEDENT> def begin(self): <NEW_LINE> <INDENT> for plugin in self.plugins: <NEW_LINE> <INDENT> plugin.begin() <NEW_LINE> <DEDENT> <DEDENT> def data(self, data): <NEW_LINE> <INDENT> for plugin in self.plugins: <NEW_LINE> <INDENT> plugin.data(data) <NEW_LINE> <DEDENT> <DEDENT> def end(self): <NEW_LINE> <INDENT> for plugin in self.plugins: <NEW_LINE> <INDENT> plugin.end() | A very simple plugin manager. | 62598fbdcc40096d6161a2ce |
class PullRequestMergeStatus(github.GithubObject.BasicGithubObject): <NEW_LINE> <INDENT> @property <NEW_LINE> def merged(self): <NEW_LINE> <INDENT> return self._NoneIfNotSet(self._merged) <NEW_LINE> <DEDENT> @property <NEW_LINE> def message(self): <NEW_LINE> <INDENT> return self._NoneIfNotSet(self._message) <NEW_LINE> <DEDENT> @property <NEW_LINE> def sha(self): <NEW_LINE> <INDENT> return self._NoneIfNotSet(self._sha) <NEW_LINE> <DEDENT> def _initAttributes(self): <NEW_LINE> <INDENT> self._merged = github.GithubObject.NotSet <NEW_LINE> self._message = github.GithubObject.NotSet <NEW_LINE> self._sha = github.GithubObject.NotSet <NEW_LINE> <DEDENT> def _useAttributes(self, attributes): <NEW_LINE> <INDENT> if "merged" in attributes: <NEW_LINE> <INDENT> assert attributes["merged"] is None or isinstance(attributes["merged"], bool), attributes["merged"] <NEW_LINE> self._merged = attributes["merged"] <NEW_LINE> <DEDENT> if "message" in attributes: <NEW_LINE> <INDENT> assert attributes["message"] is None or isinstance(attributes["message"], (str, unicode)), attributes["message"] <NEW_LINE> self._message = attributes["message"] <NEW_LINE> <DEDENT> if "sha" in attributes: <NEW_LINE> <INDENT> assert attributes["sha"] is None or isinstance(attributes["sha"], (str, unicode)), attributes["sha"] <NEW_LINE> self._sha = attributes["sha"] | This class represents PullRequestMergeStatuss as returned for example by http://developer.github.com/v3/todo | 62598fbd8a349b6b43686428 |
class SubredditInfoBar(CachedTemplate): <NEW_LINE> <INDENT> def __init__(self, site = None): <NEW_LINE> <INDENT> site = site or c.site <NEW_LINE> self.sr = list(wrap_links(site))[0] <NEW_LINE> target = "_top" if c.cname else None <NEW_LINE> self.description_usertext = UserText(self.sr, self.sr.description, target=target) <NEW_LINE> self.subscribers = self.sr._ups <NEW_LINE> self.path = request.path <NEW_LINE> self.accounts_active, self.accounts_active_fuzzed = self.sr.get_accounts_active() <NEW_LINE> if c.user_is_loggedin and c.user.pref_show_flair: <NEW_LINE> <INDENT> self.flair_prefs = FlairPrefs() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.flair_prefs = None <NEW_LINE> <DEDENT> self.sr_style_toggle = False <NEW_LINE> self.use_subreddit_style = True <NEW_LINE> if (c.user_is_loggedin and (self.sr.stylesheet_url or self.sr.header) and feature.is_enabled('stylesheets_everywhere')): <NEW_LINE> <INDENT> self.sr_style_toggle = True <NEW_LINE> self.use_subreddit_style = c.user.use_subreddit_style(c.site) <NEW_LINE> <DEDENT> CachedTemplate.__init__(self) <NEW_LINE> <DEDENT> @property <NEW_LINE> def creator_text(self): <NEW_LINE> <INDENT> if self.sr.author: <NEW_LINE> <INDENT> if self.sr.is_moderator(self.sr.author) or self.sr.author._deleted: <NEW_LINE> <INDENT> return WrappedUser(self.sr.author).render() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.sr.author.name <NEW_LINE> <DEDENT> <DEDENT> return None | When not on Default, renders a sidebox which gives info about
the current reddit, including links to the moderator and
contributor pages, as well as links to the banning page if the
current user is a moderator. | 62598fbd091ae35668704e0f |
class Enclosure(models.Model): <NEW_LINE> <INDENT> href = models.CharField(max_length=1000) <NEW_LINE> file_type = models.CharField(max_length=1000) <NEW_LINE> length = models.TextField() <NEW_LINE> entry = models.ForeignKey( Entry, on_delete=models.CASCADE, related_name="enclosures" ) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.href | A media file.
TODO can this just be removed? | 62598fbd851cf427c66b84a1 |
class Pinnwand(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> file = open("pinnwand.dmp", 'rb') <NEW_LINE> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> print("Datei konnte nicht gefunde werden. Erstelle Datei...") <NEW_LINE> <DEDENT> try : <NEW_LINE> <INDENT> self.__notizen = pickle.load(file) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.__notizen = [] <NEW_LINE> <DEDENT> file.close() <NEW_LINE> <DEDENT> def __ermittlePrioritaet(self, notiz): <NEW_LINE> <INDENT> notiz = str(notiz) <NEW_LINE> return notiz.count('!') + notiz.upper().count('WICHTIG') + notiz.upper().count('EILIG') + notiz.upper().count('DRINGEND') <NEW_LINE> <DEDENT> def hefteAn(self): <NEW_LINE> <INDENT> f = open("pinnwand.dmp", 'wb') <NEW_LINE> eingabe = "-" <NEW_LINE> while eingabe != "": <NEW_LINE> <INDENT> eingabe = input("Notiz: ") <NEW_LINE> self.__notizen.append((self.__ermittlePrioritaet(input), input)) <NEW_LINE> <DEDENT> self.__notizen.sort() <NEW_LINE> self.__notizen.reverse() <NEW_LINE> pickle.dump(self.__notizen, f) <NEW_LINE> f.close() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> message = "Notizen\n" <NEW_LINE> for msg in self.__notizen: <NEW_LINE> <INDENT> message += "{notiz} (Priorität: {prio})\n".format(notiz=msg[1], prio=msg[0]) <NEW_LINE> <DEDENT> return message <NEW_LINE> <DEDENT> def entferne(self): <NEW_LINE> <INDENT> f = open("pinnwand.dmp", 'wb') <NEW_LINE> notiz = self.__notizen[0][0] <NEW_LINE> del self.__notizen[0] <NEW_LINE> pickle.dump[self.__notizen, f] <NEW_LINE> f.close() <NEW_LINE> return notiz + '\n' | Dies ist eine Klasse um Notizen zu verwalten | 62598fbda05bb46b3848aa57 |
class Pattern(object): <NEW_LINE> <INDENT> def __init__(self, ptn, flags=0): <NEW_LINE> <INDENT> if isinstance(ptn, (str, bytes)): <NEW_LINE> <INDENT> self._re = re.compile(ptn, flags=flags) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._re = ptn <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def pattern(self): <NEW_LINE> <INDENT> return self._re.pattern <NEW_LINE> <DEDENT> def _get_segments(self, segname=None): <NEW_LINE> <INDENT> if segname: <NEW_LINE> <INDENT> seg_starts = [ida_segment.get_segm_by_name(segname).start_ea] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> seg_starts = idautils.Segments() <NEW_LINE> <DEDENT> for ea in seg_starts: <NEW_LINE> <INDENT> yield ea, segments.get_bytes(ea) <NEW_LINE> <DEDENT> <DEDENT> def search(self, segname=None): <NEW_LINE> <INDENT> for seg_start, seg_bytes in self._get_segments(segname): <NEW_LINE> <INDENT> match = self._re.search(seg_bytes) <NEW_LINE> if match: <NEW_LINE> <INDENT> return Match(match, seg_start) <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def finditer(self, segname=None): <NEW_LINE> <INDENT> for seg_start, seg_bytes in self._get_segments(segname): <NEW_LINE> <INDENT> for match in self._re.finditer(seg_bytes): <NEW_LINE> <INDENT> yield Match(match, seg_start) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def findall(self, segname=None): <NEW_LINE> <INDENT> matches = [] <NEW_LINE> for _, seg_bytes in self._get_segments(segname): <NEW_LINE> <INDENT> matches.extend(self._re.findall(seg_bytes)) <NEW_LINE> <DEDENT> return matches | Wraps the SRE_Pattern object returned by re. | 62598fbd97e22403b383b0f4 |
class CliResult: <NEW_LINE> <INDENT> def __init__(self, completed_process): <NEW_LINE> <INDENT> self.completed_process = completed_process <NEW_LINE> self.returncode = completed_process.returncode <NEW_LINE> self.stdout = self.completed_process.stdout.decode('utf-8') <NEW_LINE> self.stderr = self.completed_process.stderr.decode('utf-8') | Wraps CompletedProcess, decodes output to strings | 62598fbd5fdd1c0f98e5e17d |
class FileContentSerializer(SingleArtifactContentUploadSerializer, ContentChecksumSerializer): <NEW_LINE> <INDENT> def deferred_validate(self, data): <NEW_LINE> <INDENT> data = super().deferred_validate(data) <NEW_LINE> data["digest"] = data["artifact"].sha256 <NEW_LINE> content = FileContent.objects.filter( digest=data["digest"], relative_path=data["relative_path"] ) <NEW_LINE> if content.exists(): <NEW_LINE> <INDENT> content.get().touch() <NEW_LINE> raise serializers.ValidationError( _( "There is already a file content with relative path '{path}' and digest " "'{digest}'." ).format(path=data["relative_path"], digest=data["digest"]) ) <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> fields = ( SingleArtifactContentUploadSerializer.Meta.fields + ContentChecksumSerializer.Meta.fields ) <NEW_LINE> model = FileContent | Serializer for File Content. | 62598fbdd486a94d0ba2c1bb |
class LeNet5(nn.Module): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(LeNet5, self).__init__() <NEW_LINE> self.model = None <NEW_LINE> self.c1 = C1() <NEW_LINE> self.c2_1 = C2() <NEW_LINE> self.c2_2 = C2() <NEW_LINE> self.c3 = C3() <NEW_LINE> self.f4 = F4() <NEW_LINE> self.f5 = F5() <NEW_LINE> <DEDENT> def forward(self, img): <NEW_LINE> <INDENT> output = self.c1(img) <NEW_LINE> x = self.c2_1(output) <NEW_LINE> output = self.c2_2(output) <NEW_LINE> output += x <NEW_LINE> output = self.c3(output) <NEW_LINE> output = output.view(img.size(0), -1) <NEW_LINE> output = self.f4(output) <NEW_LINE> output = self.f5(output) <NEW_LINE> return output <NEW_LINE> <DEDENT> def distribute(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def compute_params_count(self, pruning_type='structured', threshold=0): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def compute_flops_count(self, threshold=0): <NEW_LINE> <INDENT> return 0 | Input - 1x32x32
Output - 10 | 62598fbd56ac1b37e63023da |
class ProvisionListView(ListView): <NEW_LINE> <INDENT> model = Provision <NEW_LINE> template_name = 'provision_list.html' <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> self.queryset = self.model.objects.filter(returned=False, approved=True) <NEW_LINE> return super(ProvisionListView, self).get_queryset() | View for list of provisions to mark returned from | 62598fbdad47b63b2c5a7a42 |
class DDPGAlgorithm(Algorithm): <NEW_LINE> <INDENT> def __init__(self, obs_dim, vel_obs_dim, act_dim, GAMMA, TAU, gpu_id, ensemble_num=1): <NEW_LINE> <INDENT> self.obs_dim = obs_dim <NEW_LINE> self.vel_obs_dim = vel_obs_dim <NEW_LINE> self.act_dim = act_dim <NEW_LINE> self.GAMMA, self.TAU = GAMMA, TAU <NEW_LINE> self.gpu_id = gpu_id <NEW_LINE> self.ensemble_num = ensemble_num <NEW_LINE> self.models = [] <NEW_LINE> self.target_models = [] <NEW_LINE> for i in range(ensemble_num): <NEW_LINE> <INDENT> model = MLPModel(obs_dim, vel_obs_dim, act_dim, model_id=i) <NEW_LINE> target_model = deepcopy(model) <NEW_LINE> self.models.append(model) <NEW_LINE> self.target_models.append(target_model) <NEW_LINE> print('model_id: {}'.format(i)) <NEW_LINE> print('model: {}'.format(model.parameter_names)) <NEW_LINE> print('target_model: {}'.format(target_model.parameter_names)) <NEW_LINE> <DEDENT> <DEDENT> def _ensemble_predict(self, obs): <NEW_LINE> <INDENT> raise NotImplemented <NEW_LINE> <DEDENT> def actor_predict(self, obs, model_id=None): <NEW_LINE> <INDENT> if model_id is not None: <NEW_LINE> <INDENT> return self.models[model_id].policy(obs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._ensemble_predict(obs) <NEW_LINE> <DEDENT> <DEDENT> def learn(self, obs, action, reward, next_obs, terminal, actor_lr, critic_lr, model_id): <NEW_LINE> <INDENT> self._actor_learn(obs, actor_lr, model_id) <NEW_LINE> critic_loss = self._critic_learn(obs, action, reward, next_obs, terminal, critic_lr, model_id) <NEW_LINE> return critic_loss <NEW_LINE> <DEDENT> def _actor_learn(self, obs, actor_lr, model_id): <NEW_LINE> <INDENT> action = self.models[model_id].policy(obs) <NEW_LINE> Q = self.models[model_id].value(obs, action) <NEW_LINE> loss = layers.reduce_mean(-1.0 * Q) <NEW_LINE> optimizer = fluid.optimizer.AdamOptimizer(actor_lr) <NEW_LINE> optimizer.minimize(loss, parameter_list=self.models[model_id].policy_parameters()) <NEW_LINE> <DEDENT> def _critic_learn(self, obs, action, reward, next_obs, terminal, critic_lr, model_id): <NEW_LINE> <INDENT> next_action = self.target_models[model_id].policy(next_obs) <NEW_LINE> next_Q = self.target_models[model_id].value(next_obs, next_action) <NEW_LINE> terminal = layers.cast(terminal, dtype='float32') <NEW_LINE> target_Q = reward + (1.0 - terminal) * self.GAMMA * next_Q <NEW_LINE> target_Q.stop_gradient = True <NEW_LINE> Q = self.models[model_id].value(obs, action) <NEW_LINE> loss = layers.square_error_cost(Q, target_Q) <NEW_LINE> loss = layers.reduce_mean(loss) <NEW_LINE> optimizer = fluid.optimizer.AdamOptimizer(critic_lr) <NEW_LINE> optimizer.minimize(loss) <NEW_LINE> return loss <NEW_LINE> <DEDENT> def sync_target(self, model_id, first_sync=False, share_vars_parallel_executor=None): <NEW_LINE> <INDENT> if first_sync: <NEW_LINE> <INDENT> decay = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> decay = 1 - self.TAU | Multi head version DDPG algorithm
| 62598fbdcc40096d6161a2cf |
class TestApiUserFactory(AbstractUserFactory): <NEW_LINE> <INDENT> username = TEST_API_USER <NEW_LINE> is_active = True | Factory for creating basic user `test_api_user`. | 62598fbd57b8e32f52508213 |
class TestXmlNs0JdbcDriver(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 testXmlNs0JdbcDriver(self): <NEW_LINE> <INDENT> pass | XmlNs0JdbcDriver unit test stubs | 62598fbd21bff66bcd722e56 |
class VirtualNetworkListUsageResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'value': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': '[VirtualNetworkUsage]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, next_link: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(VirtualNetworkListUsageResult, self).__init__(**kwargs) <NEW_LINE> self.value = None <NEW_LINE> self.next_link = next_link | Response for the virtual networks GetUsage API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar value: VirtualNetwork usage stats.
:vartype value: list[~azure.mgmt.network.v2019_12_01.models.VirtualNetworkUsage]
:param next_link: The URL to get the next set of results.
:type next_link: str | 62598fbdf548e778e596b793 |
class ObjectClass(): <NEW_LINE> <INDENT> def __init__(self, object_name, on, is_heavier_than): <NEW_LINE> <INDENT> self.object_name = object_name <NEW_LINE> self.setState(on, is_heavier_than) <NEW_LINE> <DEDENT> def setState(self, on, is_heavier_than): <NEW_LINE> <INDENT> self.on = on <NEW_LINE> self.is_heavier_than = is_heavier_than | Object Class that holds a name and a state | 62598fbd4a966d76dd5ef0c0 |
class RagMarwa(ConcreteScale): <NEW_LINE> <INDENT> def __init__(self, tonic=None): <NEW_LINE> <INDENT> super(RagMarwa, self).__init__(tonic=tonic) <NEW_LINE> self._abstract = AbstractRagMarwa() <NEW_LINE> self.type = 'Rag Marwa' | A concrete pseudo-raga scale.
>>> sc = scale.RagMarwa('c2')
this gets a pitch beyond the terminus b/c of descending form max
>>> [str(p) for p in sc.pitches]
['C2', 'D-2', 'E2', 'F#2', 'A2', 'B2', 'A2', 'C3', 'D-3'] | 62598fbda219f33f346c69f3 |
class FalsePositive4657: <NEW_LINE> <INDENT> __attr_a = None <NEW_LINE> __attr_b = 'b' <NEW_LINE> @classmethod <NEW_LINE> def load_attrs(cls): <NEW_LINE> <INDENT> cls.__attr_a = 'a' <NEW_LINE> <DEDENT> @property <NEW_LINE> def attr_a(self): <NEW_LINE> <INDENT> return self.__attr_a <NEW_LINE> <DEDENT> @property <NEW_LINE> def attr_b(self): <NEW_LINE> <INDENT> return self.__attr_b <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> self.__attr_c = "this is an unused private instance attribute" <NEW_LINE> <DEDENT> @property <NEW_LINE> def attr_c(self): <NEW_LINE> <INDENT> return cls.__attr_c | False positivie tests for 4657 | 62598fbd66673b3332c305bf |
class ApproximateQAgent(PacmanQAgent): <NEW_LINE> <INDENT> def __init__(self, extractor='IdentityExtractor', **args): <NEW_LINE> <INDENT> self.featExtractor = util.lookup(extractor, globals())() <NEW_LINE> PacmanQAgent.__init__(self, **args) <NEW_LINE> "*** YOUR CODE HERE ***" <NEW_LINE> self.weights = util.Counter() <NEW_LINE> <DEDENT> def getQValue(self, state, action): <NEW_LINE> <INDENT> features = self.featExtractor.getFeatures(state, action) <NEW_LINE> return features * self.weights <NEW_LINE> <DEDENT> def update(self, state, action, nextState, reward): <NEW_LINE> <INDENT> features = self.featExtractor.getFeatures(state, action) <NEW_LINE> for feature in features: <NEW_LINE> <INDENT> self.weights[feature] += self.alpha * (reward + self.discount * self.getValue(nextState) - self.getQValue(state, action)) * features[feature] <NEW_LINE> <DEDENT> <DEDENT> def final(self, state): <NEW_LINE> <INDENT> PacmanQAgent.final(self, state) <NEW_LINE> if self.episodesSoFar == self.numTraining: <NEW_LINE> <INDENT> pass | ApproximateQLearningAgent
You should only have to overwrite getQValue
and update. All other QLearningAgent functions
should work as is. | 62598fbd97e22403b383b0f5 |
class DesiredCapabilities(object): <NEW_LINE> <INDENT> FIREFOX = { "browserName": "firefox", "marionette": True, "acceptInsecureCerts": True, } <NEW_LINE> INTERNETEXPLORER = { "browserName": "internet explorer", "version": "", "platform": "WINDOWS", } <NEW_LINE> EDGE = { "browserName": "MicrosoftEdge", "version": "", "platform": "WINDOWS" } <NEW_LINE> CHROME = { "browserName": "chrome", "version": "", "platform": "ANY", } <NEW_LINE> OPERA = { "browserName": "opera", "version": "", "platform": "ANY", } <NEW_LINE> SAFARI = { "browserName": "safari", "version": "", "platform": "MAC", } <NEW_LINE> HTMLUNIT = { "browserName": "htmlunit", "version": "", "platform": "ANY", } <NEW_LINE> HTMLUNITWITHJS = { "browserName": "htmlunit", "version": "firefox", "platform": "ANY", "javascriptEnabled": True, } <NEW_LINE> IPHONE = { "browserName": "iPhone", "version": "", "platform": "MAC", } <NEW_LINE> IPAD = { "browserName": "iPad", "version": "", "platform": "MAC", } <NEW_LINE> ANDROID = { "browserName": "android", "version": "", "platform": "ANDROID", } <NEW_LINE> PHANTOMJS = { "browserName": "phantomjs", "version": "", "platform": "ANY", "javascriptEnabled": True, } | Set of default supported desired capabilities.
Use this as a starting point for creating a desired capabilities object for
requesting remote webdrivers for connecting to selenium server or selenium grid.
Usage Example::
from selenium import webdriver
selenium_grid_url = "http://198.0.0.1:4444/wd/hub"
# Create a desired capabilities object as a starting point.
capabilities = DesiredCapabilities.FIREFOX.copy()
capabilities['platform'] = "WINDOWS"
capabilities['version'] = "10"
# Instantiate an instance of Remote WebDriver with the desired capabilities.
driver = webdriver.Remote(desired_capabilities=capabilities,
command_executor=selenium_grid_url)
Note: Always use '.copy()' on the DesiredCapabilities object to avoid the side
effects of altering the Global class instance. | 62598fbd50812a4eaa620ce1 |
class SmsResource(BaseResource): <NEW_LINE> <INDENT> routes = ['/sale/<sale_id>/send_coupon_sms'] <NEW_LINE> method_decorators = [login_required, store_provider] <NEW_LINE> def _send_sms(self, to, message): <NEW_LINE> <INDENT> config = get_config() <NEW_LINE> sid = config.get('Twilio', 'sid') <NEW_LINE> secret = config.get('Twilio', 'secret') <NEW_LINE> from_phone_number = config.get('Twilio', 'from') <NEW_LINE> sms_data = {"From": from_phone_number, "To": to, "Body": message} <NEW_LINE> r = requests.post('https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json' % sid, data=sms_data, auth=(sid, secret)) <NEW_LINE> return r.text <NEW_LINE> <DEDENT> def post(self, store, sale_id): <NEW_LINE> <INDENT> GetCouponSmsTextEvent = signal('GetCouponSmsTextEvent') <NEW_LINE> assert len(GetCouponSmsTextEvent.receivers) == 1 <NEW_LINE> sale = store.get(Sale, sale_id) <NEW_LINE> message = GetCouponSmsTextEvent.send(sale)[0][1] <NEW_LINE> to = '+55' + self.get_json()['phone_number'] <NEW_LINE> return self._send_sms(to, message) | SMS RESTful resource. | 62598fbd60cbc95b0636452b |
class BotCollectState(BotState): <NEW_LINE> <INDENT> def __init__(self, bot): <NEW_LINE> <INDENT> BotState.__init__(self, bot) <NEW_LINE> self.prev_target = None <NEW_LINE> self.target = None <NEW_LINE> self.path = [] <NEW_LINE> self.pwrup_table = [] <NEW_LINE> self.snake = bot.snake <NEW_LINE> self.game = bot.game <NEW_LINE> self.t_alive = 0 <NEW_LINE> <DEDENT> def update(self, delta_time): <NEW_LINE> <INDENT> self.prev_target = self.target <NEW_LINE> self.pwrup_table = [] <NEW_LINE> for pwrup in self.game.pwrup_manager.get_powerups(): <NEW_LINE> <INDENT> dis = m_distance(self.snake.body[0], pwrup.pos) <NEW_LINE> score = self.bot.pwrup_score[pwrup.pid] <NEW_LINE> self.pwrup_table.append((dis, score, pwrup)) <NEW_LINE> <DEDENT> if not self.target: <NEW_LINE> <INDENT> self.aquire_target() <NEW_LINE> <DEDENT> if self.target.pos not in [elem[2].pos for elem in self.pwrup_table]: <NEW_LINE> <INDENT> self.aquire_target() <NEW_LINE> <DEDENT> if self.prev_target != self.target: <NEW_LINE> <INDENT> self.path = self.bot.pathfinder.find_path(self.snake[0], self.target.pos) <NEW_LINE> assert self.path <NEW_LINE> self.path.insert(0, self.target.pos) <NEW_LINE> heading = sub_vecs(self.path[-1], self.snake[0]) <NEW_LINE> self.bot.snake.set_heading(heading) <NEW_LINE> <DEDENT> if self.path[-1] == self.snake[0] and len(self.path) >= 1: <NEW_LINE> <INDENT> if m_distance(self.path[-1], self.path[-2]) > 1: <NEW_LINE> <INDENT> portal = get_next_to_portal(self.snake[0], self.game.tilemap) <NEW_LINE> if portal: <NEW_LINE> <INDENT> heading = sub_vecs(portal, self.snake[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> heading = sub_vecs(self.snake[0], self.path[-2]) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> heading = sub_vecs(self.path[-2], self.snake[0]) <NEW_LINE> <DEDENT> self.path.pop() <NEW_LINE> self.bot.snake.set_heading(heading) <NEW_LINE> <DEDENT> <DEDENT> def enter(self, old_state): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def leave(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def aquire_target(self): <NEW_LINE> <INDENT> selection = nsmallest(4, self.pwrup_table) <NEW_LINE> self.target = copy(self.game.randomizer.choice(selection)[2]) | State class implementing the 'Collect State' in which the AI is attempting
to collect powerups. | 62598fbd2c8b7c6e89bd39ae |
class RunTests(Command): <NEW_LINE> <INDENT> description = 'run tests' <NEW_LINE> user_options = [] <NEW_LINE> def initialize_options(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def finalize_options(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> errno = call(['py.test', '--cov=watches', '--cov-report=term-missing']) <NEW_LINE> raise SystemExit(errno) | Run all tests. | 62598fbd5fdd1c0f98e5e17f |
class BadRequest(Exception): <NEW_LINE> <INDENT> def __init__(self, msg: str = None) -> None: <NEW_LINE> <INDENT> msg = msg if msg else "" <NEW_LINE> super(BadRequest, self).__init__(msg) | BadRequest raises if the job was not found / does not exist. | 62598fbd9f28863672818972 |
class MP4StorageStyle(StorageStyle): <NEW_LINE> <INDENT> formats = ['MP4'] <NEW_LINE> def serialize(self, value): <NEW_LINE> <INDENT> value = super(MP4StorageStyle, self).serialize(value) <NEW_LINE> return value | A general storage style for MPEG-4 tags.
| 62598fbd3d592f4c4edbb0ac |
@register_node <NEW_LINE> class LoweredFunc(NodeBase): <NEW_LINE> <INDENT> MixedFunc = 0 <NEW_LINE> HostFunc = 1 <NEW_LINE> DeviceFunc = 2 | Represent a LoweredFunc in TVM. | 62598fbdcc40096d6161a2d0 |
class ISCSIError(RESTError): <NEW_LINE> <INDENT> message = 'Error starting iSCSI target' <NEW_LINE> def __init__(self, error_msg, exit_code, stdout, stderr): <NEW_LINE> <INDENT> details = ('Error starting iSCSI target: {0}. Failed with exit code ' '{1}. stdout: {2}. stderr: {3}') <NEW_LINE> details = details.format(error_msg, exit_code, stdout, stderr) <NEW_LINE> super(ISCSIError, self).__init__(details) | Error raised when an image cannot be written to a device. | 62598fbd99fddb7c1ca62ee3 |
class PropertyName(Base, OrmUtil): <NEW_LINE> <INDENT> __tablename__ = 'property_name' <NEW_LINE> id = Column(INTEGER, primary_key=True, nullable=False, autoincrement=True) <NEW_LINE> property_name = Column(CHAR(240), nullable=False) <NEW_LINE> category_id = Column(INTEGER, ForeignKey('property_category.id'), nullable=False) <NEW_LINE> property_category = relationship("PropertyCategory", back_populates="property_names") <NEW_LINE> property_values = relationship("PropertyValue") | new named properties - property names | 62598fbecc0a2c111447b1fc |
class Supplier(models.Model): <NEW_LINE> <INDENT> SUPPLY_STATUS_CHOICES = ( (0, '停用'), (1, '启用') ) <NEW_LINE> SUPPLY_TYPE_CHOICES = ( (0, '内部单位'), (1, '外部单位') ) <NEW_LINE> id = models.AutoField(primary_key=True) <NEW_LINE> supply_identify = models.CharField(max_length=7, unique=True, verbose_name='供应商编码') <NEW_LINE> supply_name = models.CharField(max_length=20, verbose_name='供应商名称') <NEW_LINE> supply_type = models.IntegerField(choices=SUPPLY_TYPE_CHOICES, default=0, verbose_name="供应商类型") <NEW_LINE> supply_remarks = models.TextField(max_length=400, verbose_name='供应商备注', null=True) <NEW_LINE> supply_status = models.IntegerField(choices=SUPPLY_STATUS_CHOICES, default=0, verbose_name='供应商状态') <NEW_LINE> supply_creator = models.CharField(max_length=20, verbose_name='供应商创建者名字') <NEW_LINE> supply_creator_identify = models.CharField(max_length=20, verbose_name='供应商创建者工号') <NEW_LINE> supply_created_at = models.DateTimeField(auto_now_add=True, verbose_name='供应商创建时间') <NEW_LINE> supply_modified_at = models.DateTimeField(auto_now_add=True, verbose_name='供应商修改时间') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = 'db_supplier' <NEW_LINE> verbose_name = "供应商" <NEW_LINE> verbose_name_plural = verbose_name <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.supply_name | 供应商 | 62598fbe442bda511e95c64c |
@python_2_unicode_compatible <NEW_LINE> class BallotItem(models.Model, ReverseLookupStringMixin): <NEW_LINE> <INDENT> CONTEST_TYPES = ( ('R', 'Referendum'), ('O', 'Office'), ) <NEW_LINE> contest_type = models.CharField( max_length=1, choices=CONTEST_TYPES, help_text='Office if the contest is for a person, referendum if ' 'the contest is for an issue.') <NEW_LINE> ballot = models.ForeignKey(Ballot, related_name='ballot_items') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return (ReverseLookupStringMixin.__str__(self)) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> ordering = ('ballot__date', 'ballot__locality__short_name', 'ballot__locality__name') | A single referendum or candidate office which appears on a voter's Ballot. | 62598fbe66673b3332c305c1 |
class Table (object): <NEW_LINE> <INDENT> def __init__(self, sep = ' '): <NEW_LINE> <INDENT> self.__cols = list() <NEW_LINE> self.__width = list() <NEW_LINE> self.__sep = sep <NEW_LINE> <DEDENT> def addRow(self, *row): <NEW_LINE> <INDENT> row = [ str(item) for item in row ] <NEW_LINE> len_row = [ len(item) for item in row ] <NEW_LINE> width = self.__width <NEW_LINE> len_old = len(width) <NEW_LINE> len_new = len(row) <NEW_LINE> missing = len_new - len_old <NEW_LINE> if missing > 0: <NEW_LINE> <INDENT> width.extend( len_row[ -missing : ] ) <NEW_LINE> <DEDENT> elif missing < 0: <NEW_LINE> <INDENT> len_row.extend( [0] * (-missing) ) <NEW_LINE> <DEDENT> self.__width = [ max( width[i], len_row[i] ) for i in range(len(len_row)) ] <NEW_LINE> self.__cols.append(row) <NEW_LINE> <DEDENT> def justify(self, column, direction): <NEW_LINE> <INDENT> if direction == -1: <NEW_LINE> <INDENT> self.__width[column] = abs(self.__width[column]) <NEW_LINE> <DEDENT> elif direction == 1: <NEW_LINE> <INDENT> self.__width[column] = - abs(self.__width[column]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Bad direction value.") <NEW_LINE> <DEDENT> <DEDENT> def getWidth(self): <NEW_LINE> <INDENT> width = 0 <NEW_LINE> if self.__width: <NEW_LINE> <INDENT> width = sum( abs(x) for x in self.__width ) <NEW_LINE> width = width + len(self.__width) * len(self.__sep) + 1 <NEW_LINE> <DEDENT> return width <NEW_LINE> <DEDENT> def getOutput(self): <NEW_LINE> <INDENT> return '%s\n' % '\n'.join( self.yieldOutput() ) <NEW_LINE> <DEDENT> def yieldOutput(self): <NEW_LINE> <INDENT> width = self.__width <NEW_LINE> if width: <NEW_LINE> <INDENT> num_cols = len(width) <NEW_LINE> fmt = ['%%%ds' % -w for w in width] <NEW_LINE> if width[-1] > 0: <NEW_LINE> <INDENT> fmt[-1] = '%s' <NEW_LINE> <DEDENT> fmt = self.__sep.join(fmt) <NEW_LINE> for row in self.__cols: <NEW_LINE> <INDENT> row.extend( [''] * (num_cols - len(row)) ) <NEW_LINE> yield fmt % tuple(row) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def show(self): <NEW_LINE> <INDENT> print(self.getOutput()) | Text based table. The number of columns and the width of each column
is automatically calculated. | 62598fbebf627c535bcb1694 |
class django_language(object): <NEW_LINE> <INDENT> def __enter__(self): <NEW_LINE> <INDENT> if django_translation is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> current_lang = django_translation.get_language() <NEW_LINE> if current_lang != 'en': <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> activate(current_lang, path=os.path.join( os.path.dirname(__file__), 'locale')) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> if current_lang != 'en-us': <NEW_LINE> <INDENT> LOGGER.warning(u'could not switch `humanize` i18n to %s, ' u'its translations will appear in english.', current_lang) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def __exit__(self, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> deactivate() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass | a context manager for easy language switching in Django. Usage::
with django_language():
humanize.whatever(…)
And that's all. It runs activate with the current django language
in the current thread. | 62598fbe5fcc89381b266244 |
class Condition(object): <NEW_LINE> <INDENT> def __init__(self, length=0): <NEW_LINE> <INDENT> self._condition = np.zeros(length) <NEW_LINE> <DEDENT> def add(self, arg, unit=1.0): <NEW_LINE> <INDENT> self._condition = np.hstack((self._condition, arg / unit)) <NEW_LINE> <DEDENT> def equal(self, arg1, arg2, unit=1.0): <NEW_LINE> <INDENT> arg = arg1 - arg2 <NEW_LINE> self.add(arg, unit) <NEW_LINE> <DEDENT> def lower_bound(self, arg1, arg2, unit=1.0): <NEW_LINE> <INDENT> arg = arg1 - arg2 <NEW_LINE> self.add(arg, unit) <NEW_LINE> <DEDENT> def upper_bound(self, arg1, arg2, unit=1.0): <NEW_LINE> <INDENT> arg = arg2 - arg1 <NEW_LINE> self.add(arg, unit) <NEW_LINE> <DEDENT> def change_value(self, index, value): <NEW_LINE> <INDENT> self._condition[index] = value <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> return self._condition | OpenGoddard.optimize Condition class
thin wrappper of numpy zeros and hstack
Examples:
for examples in equality function.
Initial condtion : x[0] = 0.0
Termination Condition : x[-1] = 100
>>> result = Condition()
>>> result.equal(x[0], 0.0)
>>> result.equal(x[-1], 100)
>>> return result()
for examples in inequality function
Inequation condtion : 0.0 <= x <= 100
>>> result = Condition()
>>> result.lower_bound(x, 0.0)
>>> result.upper_bound(x, 100)
>>> return result() | 62598fbeec188e330fdf8a81 |
class Rankstr(CMakePackage): <NEW_LINE> <INDENT> homepage = "https://github.com/ecp-veloc/rankstr" <NEW_LINE> url = "https://github.com/ecp-veloc/rankstr/archive/v0.0.3.tar.gz" <NEW_LINE> git = "https://github.com/ecp-veloc/rankstr.git" <NEW_LINE> tags = ['ecp'] <NEW_LINE> version('main', branch='main') <NEW_LINE> version('0.0.3', sha256='d32052fbecd44299e13e69bf2dd7e5737c346404ccd784b8c2100ceed99d8cd3') <NEW_LINE> version('0.0.2', sha256='c16d53aa9bb79934cbe2dcd8612e2db7d59de80be500c104e39e8623d4eacd8e') <NEW_LINE> depends_on('mpi') <NEW_LINE> def cmake_args(self): <NEW_LINE> <INDENT> args = [] <NEW_LINE> args.append("-DMPI_C_COMPILER=%s" % self.spec['mpi'].mpicc) <NEW_LINE> if self.spec.satisfies('platform=cray'): <NEW_LINE> <INDENT> args.append("-DRANKSTR_LINK_STATIC=ON") <NEW_LINE> <DEDENT> return args | Assign one-to-one mapping of MPI ranks to strings | 62598fbe26068e7796d4cb4b |
class TimeBasedStopCondition(StopCondition): <NEW_LINE> <INDENT> def __init__(self, max_time): <NEW_LINE> <INDENT> self.max_time = max_time <NEW_LINE> <DEDENT> def should_stop(self, abs_seconds, rel_seconds, sensor_graph): <NEW_LINE> <INDENT> return rel_seconds >= self.max_time <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def FromString(cls, desc): <NEW_LINE> <INDENT> parse_exp = Literal(u'run_time').suppress() + time_interval(u'interval') <NEW_LINE> try: <NEW_LINE> <INDENT> data = parse_exp.parseString(desc) <NEW_LINE> return TimeBasedStopCondition(data[u'interval'][0]) <NEW_LINE> <DEDENT> except ParseException: <NEW_LINE> <INDENT> raise ArgumentError(u"Could not parse time based stop condition") | Stop the simulation after a fixed period of time.
This time is relative to the call to `run` so the simulation
may be continued over multiple run calls, each of which lasts
for max_time seconds.
Args:
max_time (int): The maximum number of seconds to run the
simulation for. | 62598fbef548e778e596b796 |
class ResampledFieldGridWarperLayer(GridWarperLayer): <NEW_LINE> <INDENT> def __init__(self, source_shape, output_shape, coeff_shape, field_transform=None, resampler=None, name='resampling_interpolated_spline_grid_warper'): <NEW_LINE> <INDENT> if resampler==None: <NEW_LINE> <INDENT> self._resampler=ResamplerLayer(interpolation='LINEAR',boundary='REPLICATE') <NEW_LINE> self._interpolation = 'LINEAR' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._resampler=resampler <NEW_LINE> self._interpolation = self._resampler.interpolation <NEW_LINE> <DEDENT> self._field_transform = field_transform <NEW_LINE> super(ResampledFieldGridWarperLayer, self).__init__(source_shape=source_shape, output_shape=output_shape, coeff_shape=coeff_shape, name=name) <NEW_LINE> <DEDENT> def _create_features(self): <NEW_LINE> <INDENT> embedded_output_shape = list(self._output_shape)+[1]*(len(self._source_shape) - len(self._output_shape)) <NEW_LINE> embedded_coeff_shape = list(self._coeff_shape)+[1]*(len(self._source_shape) - len(self._output_shape)) <NEW_LINE> if self._field_transform==None and self._interpolation == 'BSPLINE': <NEW_LINE> <INDENT> range_func= lambda f,x: tf.linspace(1.,f-2.,x) <NEW_LINE> <DEDENT> elif self._field_transform==None and self._interpolation != 'BSPLINE': <NEW_LINE> <INDENT> range_func= lambda f,x: tf.linspace(0.,f-1.,x) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> range_func= lambda f,x: np.arange(x,dtype=np.float32) <NEW_LINE> embedded_output_shape+=[1] <NEW_LINE> embedded_coeff_shape+=[1] <NEW_LINE> <DEDENT> ranges = [range_func(f,x) for f,x in zip(embedded_coeff_shape,embedded_output_shape)] <NEW_LINE> coords= tf.stack([tf.reshape(x,[1,-1]) for x in tf.meshgrid(*ranges, indexing='ij')],2) <NEW_LINE> return coords <NEW_LINE> <DEDENT> def layer_op(self, field): <NEW_LINE> <INDENT> input_shape = tf.shape(field) <NEW_LINE> input_dtype = field.dtype.as_numpy_dtype <NEW_LINE> batch_size = int(field.get_shape()[0]) <NEW_LINE> if self._field_transform==None: <NEW_LINE> <INDENT> coords=self._psi <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> coords = tf.matmul(self._psi,self._field_transform[:,:,1:3]) <NEW_LINE> <DEDENT> coords = tf.reshape(tf.tile(coords,[batch_size,1,1]),[-1]+list(self._output_shape)+[len(self._source_shape)]) <NEW_LINE> resampled_coords = self._resampler(field, coords) <NEW_LINE> return resampled_coords | The resampled field grid warper defines a grid based on
sampling coordinate values from a spatially varying displacement
field (passed as a tensor input) along an affine grid pattern
in the field.
This enables grids representing small patches of a larger transform,
as well as the composition of multiple transforms before sampling. | 62598fbe3346ee7daa337740 |
class CommentForm(forms.ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Comments <NEW_LINE> fields = ('text', ) <NEW_LINE> widgets = { 'text': SummernoteWidget(), } | Форма добавления комментария к требованию
| 62598fbe5fdd1c0f98e5e182 |
class MailboxTileSource(pager.DataSource): <NEW_LINE> <INDENT> __gtype_name__ = 'PisakEmailMailboxTileSource' <NEW_LINE> __gproperties__ = { 'mailbox': ( str, '', '', '', GObject.PARAM_READWRITE) } <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._mailbox = None <NEW_LINE> now = datetime.datetime.now() <NEW_LINE> maxdelta = datetime.timedelta(10**4) <NEW_LINE> self._data_sorting_key = lambda msg: ((now - msg["Date"]) if msg else maxdelta) <NEW_LINE> <DEDENT> @property <NEW_LINE> def mailbox(self): <NEW_LINE> <INDENT> return self._mailbox <NEW_LINE> <DEDENT> @mailbox.setter <NEW_LINE> def mailbox(self, value): <NEW_LINE> <INDENT> self._mailbox = value <NEW_LINE> <DEDENT> def _produce_item(self, message_obj): <NEW_LINE> <INDENT> message = message_obj.content <NEW_LINE> tile = MailboxTile(self.mailbox) <NEW_LINE> self._prepare_item(tile) <NEW_LINE> tile.connect('clicked', self.item_handler, message_obj) <NEW_LINE> for label, value in ( ('from', message['From'][0] or message['From'][1]) if self._mailbox == 'inbox' else ('to', message['To'][0] or message['To'][1]), ('subject', message['Subject']), ('date', message['Date'].strftime(DATE_FORMAT)) ): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> getattr(tile, label).set_text(value) <NEW_LINE> <DEDENT> except AttributeError as e: <NEW_LINE> <INDENT> _LOG.warning(e) <NEW_LINE> <DEDENT> <DEDENT> return tile <NEW_LINE> <DEDENT> def _query_portion_of_data(self, ids): <NEW_LINE> <INDENT> imap_client = pisak.app.box["imap_client"] <NEW_LINE> return imap_client.get_many_previews_from_inbox(ids) if self._mailbox == 'inbox' else imap_client.get_many_previews_from_sent_box(ids) <NEW_LINE> <DEDENT> def _query_ids(self): <NEW_LINE> <INDENT> imap_client = pisak.app.box["imap_client"] <NEW_LINE> return imap_client.get_inbox_ids() if self._mailbox == 'inbox' else imap_client.get_sent_box_ids() | Data source that provides tiles representing messages in various
email mailboxes. | 62598fbee1aae11d1e7ce91d |
class XRay(NCNRLoader): <NEW_LINE> <INDENT> instrument = "X-ray" <NEW_LINE> radiation = "xray" <NEW_LINE> wavelength = 1.5416 <NEW_LINE> dLoL = 1e-3/wavelength <NEW_LINE> d_s1 = 275.5 <NEW_LINE> d_s2 = 192.5 <NEW_LINE> d_s3 = 175.0 <NEW_LINE> d_detector = None | Instrument definition for NCNR X-ray reflectometer.
Normal dT is in the range 2e-5 to 3e-4.
Slits are fixed throughout the experiment in one of a
few preconfigured openings. Please update this file with
the standard configurations when you find them.
You can choose to ignore the geometric calculation entirely
by setting the slit opening to 0 and using sample_broadening
to define the entire divergence::
xray = ncnrdata.XRay(slits_at_To=0)
data = xray.load("exp123.dat", sample_broadening=1e-4) | 62598fbe44b2445a339b6a6e |
class NamespacedCommand(BaseCommand): <NEW_LINE> <INDENT> @property <NEW_LINE> def commands(self): <NEW_LINE> <INDENT> if not hasattr(self, "_commands"): <NEW_LINE> <INDENT> self._commands = {} <NEW_LINE> for _ in reversed(self.__class__.mro()): <NEW_LINE> <INDENT> self._commands.update( { name: cmd_cls for name, cmd_cls in vars(self.__class__).items() if inspect.isclass(cmd_cls) and hasattr(cmd_cls, "mro") and BaseCommand in cmd_cls.mro() } ) <NEW_LINE> <DEDENT> <DEDENT> return self._commands <NEW_LINE> <DEDENT> def run_command_from_argv(self, command, argv): <NEW_LINE> <INDENT> command.style = self.style <NEW_LINE> cmd_args = argv[:] <NEW_LINE> cmd_args[0] = " ".join([cmd_args[0], cmd_args.pop(1)]) <NEW_LINE> command.run_from_argv(cmd_args) <NEW_LINE> <DEDENT> def run_from_argv(self, argv): <NEW_LINE> <INDENT> self._called_from_command_line = True <NEW_LINE> if len(argv) > 2 and not argv[2].startswith("-") and argv[2] in self.commands: <NEW_LINE> <INDENT> command = self.commands.get(argv[2])(stdout=self.stdout, stderr=self.stderr) <NEW_LINE> self.run_command_from_argv(command, argv) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.print_help(argv[0], argv[1]) <NEW_LINE> <DEDENT> <DEDENT> def create_parser(self, prog_name, subcommand): <NEW_LINE> <INDENT> args = sa.util.get_cls_kwargs(CommandParser) <NEW_LINE> kwargs = { "cmd": None, "prog": "{} {}".format(os.path.basename(prog_name), subcommand), "description": self.help or None, } <NEW_LINE> parser = CommandParser(**{k: v for k, v in kwargs.items() if k in args}) <NEW_LINE> for name, command_cls in self.commands.items(): <NEW_LINE> <INDENT> parser.add_argument(name, help=command_cls.help) <NEW_LINE> <DEDENT> return parser <NEW_LINE> <DEDENT> def print_help(self, prog_name, subcommand): <NEW_LINE> <INDENT> parser = self.create_parser(prog_name, subcommand) <NEW_LINE> parser.print_help(self.stdout) | Namespaced django command implementation. | 62598fbe57b8e32f52508215 |
class UpdateOwnStatus(permissions.BasePermission): <NEW_LINE> <INDENT> def has_object_permission(self, request, view, obj): <NEW_LINE> <INDENT> if request.method in permissions.SAFE_METHODS: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return obj.user_profile.id == request.user.id | Allow users to edit their own status | 62598fbe091ae35668704e15 |
class Meta: <NEW_LINE> <INDENT> db_table = 'vacancies' | Model's metaclass. | 62598fbe1f5feb6acb162e10 |
class LinkEncode(object): <NEW_LINE> <INDENT> def __init__(self, length=DEFAULT_LENGTH): <NEW_LINE> <INDENT> self.params = [] <NEW_LINE> self.encode_mapping = string.ascii_letters + string.digits <NEW_LINE> self.length = length <NEW_LINE> self.base = len(self.encode_mapping) <NEW_LINE> <DEDENT> def add(self, param): <NEW_LINE> <INDENT> self.params.append(str(param)) <NEW_LINE> <DEDENT> def base_encode(self, num): <NEW_LINE> <INDENT> digits = [] <NEW_LINE> while num > 0: <NEW_LINE> <INDENT> digits.append(self.encode_mapping[num % self.base]) <NEW_LINE> num /= self.base <NEW_LINE> <DEDENT> return ''.join(digits[::-1]) <NEW_LINE> <DEDENT> def hexdigest(self): <NEW_LINE> <INDENT> if not self.params: <NEW_LINE> <INDENT> raise AttributeError('Need Params') <NEW_LINE> <DEDENT> digest = int(hashlib.md5(''.join(self.params)).hexdigest(), 16) <NEW_LINE> return self.base_encode(digest)[:self.length] <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def generate_new_link(): <NEW_LINE> <INDENT> encode = LinkEncode() <NEW_LINE> encode.add(request.remote_addr) <NEW_LINE> encode.add(time.time()) <NEW_LINE> return encode.hexdigest() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def check_shortlink(shortlink, length=DEFAULT_LENGTH): <NEW_LINE> <INDENT> if shortlink and len(shortlink) == length: <NEW_LINE> <INDENT> if shortlink_pattern.match(shortlink): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False | >>> encode = LinkEncode()
>>> encode.add('127.0.0.1')
>>> encode.add(time.time())
>>> encode.hexdigest() | 62598fbe7b180e01f3e49148 |
class RunConfig: <NEW_LINE> <INDENT> cases_path = os.path.join(PRO_PATH, "test_dir") <NEW_LINE> uat_url = "uat-api.3ona.co" <NEW_LINE> prd_url="api.crypto.com" <NEW_LINE> rerun = "1" <NEW_LINE> max_fail = "5" <NEW_LINE> NEW_REPORT = None <NEW_LINE> DATA_LOCATION=os.path.join(PRO_PATH, "data", "cyprto_test_data.xls") <NEW_LINE> WS_URL="wss://uat-stream.3ona.co/v2/market/" | 运行测试配置 | 62598fbe66673b3332c305c3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.