code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class PlayMediaCommand(Command): <NEW_LINE> <INDENT> deserialized_types = { 'object_type': 'str', 'delay': 'int', 'description': 'str', 'when': 'bool', 'audio_track': 'ask_sdk_model.interfaces.alexa.presentation.apl.audio_track.AudioTrack', 'component_id': 'str', 'source': 'list[ask_sdk_model.interfaces.alexa.presentation.apl.video_source.VideoSource]' } <NEW_LINE> attribute_map = { 'object_type': 'type', 'delay': 'delay', 'description': 'description', 'when': 'when', 'audio_track': 'audioTrack', 'component_id': 'componentId', 'source': 'source' } <NEW_LINE> supports_multiple_types = False <NEW_LINE> def __init__(self, delay=None, description=None, when=None, audio_track=None, component_id=None, source=None): <NEW_LINE> <INDENT> self.__discriminator_value = "PlayMedia" <NEW_LINE> self.object_type = self.__discriminator_value <NEW_LINE> super(PlayMediaCommand, self).__init__(object_type=self.__discriminator_value, delay=delay, description=description, when=when) <NEW_LINE> self.audio_track = audio_track <NEW_LINE> self.component_id = component_id <NEW_LINE> self.source = source <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.deserialized_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x.value if isinstance(x, Enum) else x, value )) <NEW_LINE> <DEDENT> elif isinstance(value, Enum): <NEW_LINE> <INDENT> result[attr] = value.value <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else (item[0], item[1].value) if isinstance(item[1], Enum) else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, PlayMediaCommand): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
Plays media on a media player (currently only a Video player; audio may be added in the future). The media may be on the background audio track or may be sequenced with speak directives). :param delay: The delay in milliseconds before this command starts executing; must be non-negative. Defaults to 0. :type delay: (optional) int :param description: A user-provided description of this command. :type description: (optional) str :param when: If false, the execution of the command is skipped. Defaults to true. :type when: (optional) bool :param audio_track: The command to issue on the media player :type audio_track: (optional) ask_sdk_model.interfaces.alexa.presentation.apl.audio_track.AudioTrack :param component_id: The name of the media playing component :type component_id: (optional) str :param source: The media source :type source: (optional) list[ask_sdk_model.interfaces.alexa.presentation.apl.video_source.VideoSource]
625990149b70327d1c57fa8f
class SearchAndOrganizeUsers(object): <NEW_LINE> <INDENT> def __init__(self, client_id, client_secret, domain): <NEW_LINE> <INDENT> self.client_id = client_id <NEW_LINE> self.client_secret = client_secret <NEW_LINE> self.domain = domain <NEW_LINE> <DEDENT> def AuthorizeClient(self): <NEW_LINE> <INDENT> self.token = gdata.gauth.OAuth2Token( client_id=self.client_id, client_secret=self.client_secret, scope=SCOPES, user_agent=USER_AGENT) <NEW_LINE> uri = self.token.generate_authorize_url() <NEW_LINE> print('Please visit this URL to authorize the application:') <NEW_LINE> print(uri) <NEW_LINE> code = input('What is the verification code? ').strip() <NEW_LINE> self.token.get_access_token(code) <NEW_LINE> self.user_client = AppsClient(domain=self.domain, auth_token=self.token) <NEW_LINE> self.org_client = OrganizationUnitProvisioningClient( domain=self.domain, auth_token=self.token) <NEW_LINE> <DEDENT> def OrganizeUsers(self, customer_id, org_unit_path, pattern): <NEW_LINE> <INDENT> users = self.user_client.RetrieveAllUsers() <NEW_LINE> matched_users = [] <NEW_LINE> for user in users.entry: <NEW_LINE> <INDENT> if (pattern.search(user.login.user_name) or pattern.search(user.name.given_name) or pattern.search(user.name.family_name)): <NEW_LINE> <INDENT> user_email = '%s@%s' % (user.login.user_name, self.domain) <NEW_LINE> matched_users.append(user_email) <NEW_LINE> <DEDENT> <DEDENT> for i in range(0, len(matched_users), BATCH_SIZE): <NEW_LINE> <INDENT> batch_to_move = matched_users[i: i + BATCH_SIZE] <NEW_LINE> self.org_client.MoveUserToOrgUnit(customer_id, org_unit_path, batch_to_move) <NEW_LINE> <DEDENT> print(('Number of users moved = %d' % len(matched_users))) <NEW_LINE> <DEDENT> def Run(self, org_unit_path, regex): <NEW_LINE> <INDENT> self.AuthorizeClient() <NEW_LINE> customer_id_entry = self.org_client.RetrieveCustomerId() <NEW_LINE> customer_id = customer_id_entry.customer_id <NEW_LINE> pattern = re.compile(regex) <NEW_LINE> print(('Moving Users with the pattern %s' % regex)) <NEW_LINE> self.OrganizeUsers(customer_id, org_unit_path, pattern)
Search users with a pattern and move them to organization.
625990146fece00bbaccc6c5
class thin_film: <NEW_LINE> <INDENT> def __init__ (self, n1, n2, n3, thickness_nm): <NEW_LINE> <INDENT> pass <NEW_LINE> self.n1 = n1 <NEW_LINE> self.n2 = n2 <NEW_LINE> self.n3 = n3 <NEW_LINE> self.thickness_nm = thickness_nm <NEW_LINE> self.too_thick = False <NEW_LINE> def field_reflection_coefficient (n1, n2): <NEW_LINE> <INDENT> return ( (n1 - n2) / (n1 + n2) ) <NEW_LINE> <DEDENT> self.R12 = field_reflection_coefficient (n1, n2) <NEW_LINE> self.R23 = field_reflection_coefficient (n2, n3) <NEW_LINE> self.R12sqd_plus_R23sqd = self.R12*self.R12 + self.R23*self.R23 <NEW_LINE> self.R12_times_R23_times_2 = 2.0 * self.R12 * self.R23 <NEW_LINE> self.phase_factor = -2.0 * self.thickness_nm * 2.0 * math.pi * n2 <NEW_LINE> sample_interval_nm = 1.0 <NEW_LINE> wavelength_0_nm = 380.0 <NEW_LINE> max_thickness_nm = 0.25 * math.pow (wavelength_0_nm, 2) / (n2 * sample_interval_nm) <NEW_LINE> if self.thickness_nm > max_thickness_nm: <NEW_LINE> <INDENT> self.too_thick = True <NEW_LINE> <DEDENT> <DEDENT> def get_interference_reflection_coefficient (self, wl_nm): <NEW_LINE> <INDENT> if self.too_thick: <NEW_LINE> <INDENT> return self.R12sqd_plus_R23sqd <NEW_LINE> <DEDENT> phase = cmath.exp (complex (0, 1.0) * (self.phase_factor / wl_nm)) <NEW_LINE> num = self.R12 + self.R23 * phase <NEW_LINE> den = 1.0 + self.R12 * self.R23 * phase <NEW_LINE> Re = num / den <NEW_LINE> R = Re.real*Re.real + Re.imag*Re.imag <NEW_LINE> return R <NEW_LINE> <DEDENT> def reflection_spectrum (self): <NEW_LINE> <INDENT> spectrum = ciexyz.empty_spectrum() <NEW_LINE> (num_rows, num_cols) = spectrum.shape <NEW_LINE> for i in xrange (0, num_rows): <NEW_LINE> <INDENT> wl_nm = spectrum [i][0] <NEW_LINE> spectrum [i][1] = self.get_interference_reflection_coefficient (wl_nm) <NEW_LINE> <DEDENT> return spectrum <NEW_LINE> <DEDENT> def illuminated_spectrum (self, illuminant): <NEW_LINE> <INDENT> spectrum = self.reflection_spectrum() <NEW_LINE> (num_wl, num_col) = spectrum.shape <NEW_LINE> for i in xrange (0, num_wl): <NEW_LINE> <INDENT> spectrum [i][1] *= illuminant [i][1] <NEW_LINE> <DEDENT> return spectrum <NEW_LINE> <DEDENT> def illuminated_color (self, illuminant): <NEW_LINE> <INDENT> spectrum = self.illuminated_spectrum (illuminant) <NEW_LINE> xyz = ciexyz.xyz_from_spectrum (spectrum) <NEW_LINE> return xyz
A thin film of dielectric material.
625990158c3a8732951f7273
class PinDeleteTest(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> create_test_users(self) <NEW_LINE> create_test_resources(self) <NEW_LINE> create_test_boards(self) <NEW_LINE> create_test_pins(self) <NEW_LINE> self.client = Client() <NEW_LINE> <DEDENT> def test_urls(self): <NEW_LINE> <INDENT> urls = [ { 'url': '/pin/1/delete/', 'status': 302, 'template': 'user/user_login.html', }, { 'url': '/pin/372/delete/', 'status': 302, 'template': 'user/user_login.html', }, { 'url': '/pin/delete/', 'status': 404, 'template': '404.html', }, ] <NEW_LINE> test_urls(self, urls) <NEW_LINE> <DEDENT> def test_logged_in_urls(self): <NEW_LINE> <INDENT> login(self, self.user) <NEW_LINE> urls = [ { 'url': '/pin/1/delete/', 'status': 200, 'template': 'pin/pin_delete.html', }, { 'url': '/pin/372/delete/', 'status': 404, 'template': '404.html', }, { 'url': '/pin/2/delete/', 'status': 404, 'template': '404.html', }, { 'url': '/pin/delete/', 'status': 404, 'template': '404.html', }, ] <NEW_LINE> test_urls(self, urls) <NEW_LINE> <DEDENT> def test_pin_delete(self): <NEW_LINE> <INDENT> login(self, self.user) <NEW_LINE> response = self.client.get('/pin/1/delete/') <NEW_LINE> self.assertEqual(response.context['pin'], self.pin) <NEW_LINE> response = self.client.post('/pin/1/delete/', follow=True) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertEqual(response.templates[0].name, 'pin/pin_board_list.html') <NEW_LINE> n_pins = Pin.objects.all().count() <NEW_LINE> self.assertEqual(n_pins, 1) <NEW_LINE> pins = Pin.objects.all() <NEW_LINE> self.assertEqual(pins[0].pk, 2) <NEW_LINE> resource = Resource.objects.get(pk=1) <NEW_LINE> self.assertEqual(resource.n_pins, 0) <NEW_LINE> user = User.objects.get(pk=1) <NEW_LINE> self.assertEqual(user.n_pins, 0) <NEW_LINE> self.assertEqual(user.n_public_pins, 0) <NEW_LINE> board = Board.objects.get(pk=1) <NEW_LINE> self.assertEqual(board.n_pins, 0) <NEW_LINE> <DEDENT> def test_pin_delete_with_wrong_user(self): <NEW_LINE> <INDENT> login(self, self.user) <NEW_LINE> response = self.client.post('/pin/2/delete/') <NEW_LINE> self.assertEqual(response.status_code, 404) <NEW_LINE> n_pins = Pin.objects.all().count() <NEW_LINE> self.assertEqual(n_pins, 2) <NEW_LINE> <DEDENT> def test_pin_delete_with_unexisting_pin(self): <NEW_LINE> <INDENT> login(self, self.user) <NEW_LINE> response = self.client.post('/pin/673/delete/') <NEW_LINE> self.assertEqual(response.status_code, 404)
Pin deletion test class.
62599015be8e80087fbbfd83
class ApiItem(ApiModel): <NEW_LINE> <INDENT> API_LIST_API_NAME = None <NEW_LINE> API_LIST_CLS = None <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> for attr in self.api_attrs(): <NEW_LINE> <INDENT> setattr(self, attr, kwargs.pop(attr, None)) <NEW_LINE> <DEDENT> for attr, value in kwargs.items(): <NEW_LINE> <INDENT> setattr(self, attr, value) <NEW_LINE> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> api_attrs = self.api_attrs() <NEW_LINE> set_attrs = [k for k in api_attrs if getattr(self, k, None) is not None] <NEW_LINE> return len(set_attrs) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> show_attrs = self.api_attrs_str() <NEW_LINE> attrs = [] <NEW_LINE> for attr in show_attrs: <NEW_LINE> <INDENT> value = getattr(self, attr, None) <NEW_LINE> tmpl = self.T_ATTR_STR if attr in self.API_COMPLEX else self.T_ATTR_REPR <NEW_LINE> attrs.append(tmpl.format(attr=attr, value=value)) <NEW_LINE> <DEDENT> attrs = self.T_ATTR_JOIN.join(attrs) <NEW_LINE> return self.T_CLS_STR.format(obj=self, attrs=attrs) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> show_attrs = self.api_attrs_repr() <NEW_LINE> attrs = [] <NEW_LINE> for attr in show_attrs: <NEW_LINE> <INDENT> value = getattr(self, attr, None) <NEW_LINE> tmpl = self.T_ATTR_REPR <NEW_LINE> attrs.append(tmpl.format(attr=attr, value=value)) <NEW_LINE> <DEDENT> attrs = self.T_ATTR_JOIN.join(attrs) <NEW_LINE> return self.T_CLS_REPR.format(obj=self, attrs=attrs) <NEW_LINE> <DEDENT> def __setattr__(self, attr, value): <NEW_LINE> <INDENT> value = self.api_coerce_value(attr=attr, value=value) <NEW_LINE> super(ApiItem, self).__setattr__(attr, value) <NEW_LINE> <DEDENT> def serialize( self, empty=False, list_attrs=False, exclude_attrs=None, only_attrs=None, wrap_name=True, wrap_item_attr=True, ): <NEW_LINE> <INDENT> exclude_attrs = self.api_coerce_list(value=exclude_attrs) <NEW_LINE> only_attrs = self.api_coerce_list(value=only_attrs) <NEW_LINE> ret = {} <NEW_LINE> sargs = { "empty": empty, "exclude_attrs": exclude_attrs, "only_attrs": only_attrs, "list_attrs": list_attrs, "wrap_name": False, "wrap_item_attr": wrap_item_attr, } <NEW_LINE> for attr in self.api_attrs(): <NEW_LINE> <INDENT> if attr in exclude_attrs or (only_attrs and attr not in only_attrs): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> value = getattr(self, attr, None) <NEW_LINE> is_model = isinstance(value, ApiModel) <NEW_LINE> value = value.serialize(**sargs) if is_model else value <NEW_LINE> include = (value is None and empty) or value is not None <NEW_LINE> ret.update({attr: value} if include else {}) <NEW_LINE> <DEDENT> if wrap_name: <NEW_LINE> <INDENT> ret = {self.API_NAME: ret} <NEW_LINE> <DEDENT> return ret
Model for a complex item in the API.
62599015d164cc6175821c90
class Animal(ABC): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def eat(self): <NEW_LINE> <INDENT> return NotImplementedError('the eat() should be overridden.') <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def run(self): <NEW_LINE> <INDENT> return NotImplementedError('the run() should be overridden.') <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def fly(self): <NEW_LINE> <INDENT> return NotImplementedError('the fly() should be overridden.') <NEW_LINE> <DEDENT> def move(self): <NEW_LINE> <INDENT> pass
ABC class: Animal
62599015d18da76e235b77d7
@pytest.helpers.register <NEW_LINE> class StubbedGCloudContext: <NEW_LINE> <INDENT> def __init__(self, tmp_path): <NEW_LINE> <INDENT> self._saved_db_path = None <NEW_LINE> self._saved_path = None <NEW_LINE> self.tmp_path = tmp_path <NEW_LINE> self._db_path = tmp_path.joinpath("db") <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self._saved_db_path = os.getenv("GCLOUD_DB_PATH", "") <NEW_LINE> os.environ["GCLOUD_DB_PATH"] = str(self._db_path) <NEW_LINE> self._saved_path = os.getenv('PATH', "") <NEW_LINE> here_path = os.path.dirname(__file__) <NEW_LINE> new_path = f"{here_path}:{self._saved_path}" if self._saved_path else here_path <NEW_LINE> os.environ['PATH'] = new_path <NEW_LINE> logger.trace(f"SGCC[{id(self)}].__enter__") <NEW_LINE> return self <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_value, traceback): <NEW_LINE> <INDENT> os.environ['PATH'] = self._saved_path <NEW_LINE> os.environ['GCLOUD_DB_PATH'] = self._saved_db_path <NEW_LINE> logger.trace(f"SGCC[{id(self)}].__exit__") <NEW_LINE> <DEDENT> def _db_json_path(self, tablename): <NEW_LINE> <INDENT> return f"{self._db_path}.{tablename}.json" <NEW_LINE> <DEDENT> def stub_path(self, basename): <NEW_LINE> <INDENT> return os.path.dirname(os.path.abspath(__file__)) + f"/stubfiles/{basename}.json" <NEW_LINE> <DEDENT> def config_path(self, basename): <NEW_LINE> <INDENT> return os.path.dirname(os.path.abspath(__file__)) + f"/configfiles/{basename}" <NEW_LINE> <DEDENT> def db(self, tablename): <NEW_LINE> <INDENT> assert tablename in DB_NAMES <NEW_LINE> return JsonDict(__path__=self._db_json_path(tablename)) <NEW_LINE> <DEDENT> def seed_db(self, tablename, seed_basename): <NEW_LINE> <INDENT> seed_fullname = self.stub_path(seed_basename) <NEW_LINE> if not os.path.exists(seed_fullname): <NEW_LINE> <INDENT> raise RuntimeError(f"No file found for {seed_basename} at {seed_fullname}") <NEW_LINE> <DEDENT> shutil.copy(seed_fullname, self._db_json_path(tablename)) <NEW_LINE> <DEDENT> def seed_configfile(self, basename, seed_basename): <NEW_LINE> <INDENT> seed_fullname = self.config_path(seed_basename) <NEW_LINE> if not os.path.exists(seed_fullname): <NEW_LINE> <INDENT> raise RuntimeError(f"No file found for {seed_basename} at {seed_fullname}") <NEW_LINE> <DEDENT> stubfile_path = self.tmp_path.joinpath(basename) <NEW_LINE> shutil.copy(seed_fullname, stubfile_path) <NEW_LINE> return stubfile_path <NEW_LINE> <DEDENT> def tmpfile(self, filename, mode="wt"): <NEW_LINE> <INDENT> return open(str(self.tmp_path.joinpath(filename)), mode=mode)
Context-manager used to setup the various stub files for our stubbed gcloud implementation. Its main goal is conciseness of use above of all else - notably, above clarity or expressiveness. Prefer the stubbed_gcloud_ctx fixture to using this as is.
625990150a366e3fb87dd708
class NormalExponentialADF(AbstractADF) : <NEW_LINE> <INDENT> def __init__(self, gammas, bounds=(1.0e-10, np.inf)) : <NEW_LINE> <INDENT> self.n_dims = len(gammas) <NEW_LINE> self.parameters = gammas <NEW_LINE> self.bounds = { "lower" : [bounds[0] for i in range(self.n_dims)], "upper" : [bounds[1] for i in range(self.n_dims)] } <NEW_LINE> <DEDENT> @property <NEW_LINE> def parameters(self) : <NEW_LINE> <INDENT> return self._gammas <NEW_LINE> <DEDENT> @parameters.setter <NEW_LINE> def parameters(self, gammas) : <NEW_LINE> <INDENT> if not isinstance(gammas, np.ndarray) or gammas.shape != (self.n_dims,) : <NEW_LINE> <INDENT> raise Exception("bad input gammas") <NEW_LINE> <DEDENT> self._gammas = gammas <NEW_LINE> <DEDENT> def randomize(self, rng=np.random.default_rng(None)) : <NEW_LINE> <INDENT> gammas = rng.random(self.n_dims) * 10 <NEW_LINE> self.parameters = gammas <NEW_LINE> <DEDENT> def _f_reach(self, grs, freqs) : <NEW_LINE> <INDENT> return np.power(self._gammas*grs, freqs) / np.power(1 + self._gammas*grs, freqs + 1) <NEW_LINE> <DEDENT> def _fplus_reach(self, grs, freqs) : <NEW_LINE> <INDENT> return np.power((self._gammas*grs) / (1+ self._gammas*grs), freqs) <NEW_LINE> <DEDENT> def _evaluate(self, xs) : <NEW_LINE> <INDENT> gammas = np.reshape(self._gammas, [1, self.n_dims]) <NEW_LINE> return np.prod(np.exp(-xs/gammas)/gammas, axis=1) <NEW_LINE> <DEDENT> def marginal(self, dims) : <NEW_LINE> <INDENT> return type(self)(self.parameters[dims]) <NEW_LINE> <DEDENT> def partial_evaluate(self, dims, values) : <NEW_LINE> <INDENT> eval_gammas = np.reshape(self._gammas[dims], [1, len(dims)]) <NEW_LINE> np.prod(np.exp(-values/eval_gammas)/eval_gammas) <NEW_LINE> dims_to_marginal = [d for d in list(range(self.n_dims)) if d not in dims] <NEW_LINE> <DEDENT> def cdf(self, value) : <NEW_LINE> <INDENT> if self.n_dims > 1 : <NEW_LINE> <INDENT> raise Exception("cdf method is only defined for a single dimension.") <NEW_LINE> <DEDENT> return 1 - np.exp(-value/self._gammas)
The class for normalized simple exponential ADF.
62599015bf627c535bcb21c5
class AuthenticateError(IOError): <NEW_LINE> <INDENT> pass
An Login error occurred.
625990155166f23b2e2440e8
class NetworkAccess(BBFetchException): <NEW_LINE> <INDENT> def __init__(self, url, cmd): <NEW_LINE> <INDENT> msg = "Network access disabled through BB_NO_NETWORK (or set indirectly due to use of BB_FETCH_PREMIRRORONLY) but access requested with command %s (for url %s)" % (cmd, url) <NEW_LINE> self.url = url <NEW_LINE> self.cmd = cmd <NEW_LINE> BBFetchException.__init__(self, msg) <NEW_LINE> self.args = (url, cmd)
Exception raised when network access is disabled but it is required.
62599015a8ecb03325871f36
class GitHubStatus(GitHubCore): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(GitHubStatus, self).__init__({}) <NEW_LINE> self._github_url = 'https://status.github.com/' <NEW_LINE> <DEDENT> def _recipe(self, *args): <NEW_LINE> <INDENT> url = self._build_url(*args) <NEW_LINE> resp = self._get(url) <NEW_LINE> return resp.json if self._boolean(resp, 200, 404) else {} <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def api(self): <NEW_LINE> <INDENT> return self._recipe('api.json') <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def status(self): <NEW_LINE> <INDENT> return self._recipe('api', 'status.json') <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def last_message(self): <NEW_LINE> <INDENT> return self._recipe('api', 'last-message.json') <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def messages(self): <NEW_LINE> <INDENT> return self._recipe('api', 'messages.json')
A sleek interface to the GitHub System Status API. This will only ever return the JSON objects returned by the API.
62599015a8ecb03325871f38
class RightServiceStub(object): <NEW_LINE> <INDENT> def __init__(self, channel): <NEW_LINE> <INDENT> self.List = channel.unary_unary( '/wgtwo.auth.v0.RightService/List', request_serializer=wgtwo_dot_auth_dot_v0_dot_rights__pb2.ListRightsRequest.SerializeToString, response_deserializer=wgtwo_dot_auth_dot_v0_dot_rights__pb2.ListRightsResponse.FromString, ) <NEW_LINE> self.CheckExpansion = channel.unary_unary( '/wgtwo.auth.v0.RightService/CheckExpansion', request_serializer=wgtwo_dot_auth_dot_v0_dot_rights__pb2.CheckExpansionRequest.SerializeToString, response_deserializer=wgtwo_dot_auth_dot_v0_dot_rights__pb2.CheckExpansionResponse.FromString, )
Missing associated documentation comment in .proto file.
62599015462c4b4f79dbc723
class ImproperRequest (MyExceptions): <NEW_LINE> <INDENT> pass
improper post data
6259901521a7993f00c66c97
class Common(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def handle_error(msg): <NEW_LINE> <INDENT> Logger.log(APP_LOG_DIR, 'ERROR', __name__, msg) <NEW_LINE> with open(SYS_CORE_DIR + 'sys_templates/sys_error.html', 'r') as f: <NEW_LINE> <INDENT> template_content = f.read() <NEW_LINE> <DEDENT> template_vars = {'msg': msg} <NEW_LINE> response_headers = [('Content-Type', 'text/html; charset=utf-8')] <NEW_LINE> response_content = Template(template_content).substitute(template_vars) <NEW_LINE> return {'headers': response_headers, 'content': response_content}
Common shared functions
62599015a8ecb03325871f3c
class figure4Topo(Topo): <NEW_LINE> <INDENT> def __init__(self, sw_path, json_path, thrift_port, pcap_dump, sender_count, senders_sub_name,switch_name,receiver_name, **opts): <NEW_LINE> <INDENT> Topo.__init__(self, **opts) <NEW_LINE> switch = self.addSwitch(switch_name, sw_path=sw_path, json_path=json_path, thrift_port=thrift_port, pcap_dump=pcap_dump) <NEW_LINE> receiver = self.addHost(receiver_name, mac='00:04:00:00:00:01') <NEW_LINE> self.addLink(receiver, switch) <NEW_LINE> senders=[] <NEW_LINE> for h in range(sender_count): <NEW_LINE> <INDENT> senders.append(self.addHost(senders_sub_name+'%d' % (h+1) , mac='00:04:00:00:00:%02x' %(h+2))) <NEW_LINE> <DEDENT> for h in range(sender_count): <NEW_LINE> <INDENT> self.addLink(senders[h],switch)
figure4Toto with 10 host on the left connected to a simpe_switch(p4)
62599015462c4b4f79dbc725
@utils.use_signature(core.TopLevelFacetSpec) <NEW_LINE> class FacetChart(TopLevelMixin, core.TopLevelFacetSpec): <NEW_LINE> <INDENT> def __init__(self, spec, facet=Undefined, **kwargs): <NEW_LINE> <INDENT> _check_if_valid_subspec(spec, 'FacetChart') <NEW_LINE> super(FacetChart, self).__init__(spec=spec, facet=facet, **kwargs) <NEW_LINE> <DEDENT> def interactive(self, name=None, bind_x=True, bind_y=True): <NEW_LINE> <INDENT> copy = self.copy() <NEW_LINE> copy.spec = copy.spec.interactive(name=name, bind_x=bind_x, bind_y=bind_y) <NEW_LINE> return copy
A Chart with layers within a single panel
62599015796e427e5384f4a1
class savedcmd(object): <NEW_LINE> <INDENT> def __init__(self, path, cmdline): <NEW_LINE> <INDENT> docpath = util.escapestr(path) <NEW_LINE> self.__doc__ = self.__doc__ % {"path": util.uirepr(docpath)} <NEW_LINE> self._cmdline = cmdline <NEW_LINE> <DEDENT> def __call__(self, ui, repo, *pats, **opts): <NEW_LINE> <INDENT> options = " ".join(map(util.shellquote, opts["option"])) <NEW_LINE> if options: <NEW_LINE> <INDENT> options = " " + options <NEW_LINE> <DEDENT> return dodiff(ui, repo, self._cmdline + options, pats, opts)
use external program to diff repository (or selected files) Show differences between revisions for the specified files, using the following program:: %(path)s When two revision arguments are given, then changes are shown between those revisions. If only one revision is specified then that revision is compared to the working directory, and, when no revisions are specified, the working directory files are compared to its parent.
6259901556b00c62f0fb35df
class User(Base): <NEW_LINE> <INDENT> __tablename__ = "%s%s" % (TablePrefix, 'User') <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> name = Column(String(127), nullable=False) <NEW_LINE> email = Column(String(127), nullable=False) <NEW_LINE> picture = Column(String) <NEW_LINE> categories = relationship( 'Category', backref='user', order_by='Category.label') <NEW_LINE> items = relationship('Item', backref='user', order_by='Item.label')
Table of users and user information
62599015a8ecb03325871f42
class DropObjectFunction(GraphFunction): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__( function_name='drop', possible_arg_nums=[2], arg_split_words=[], arg_find_type=[ {}, {'type': 'carrying', 'from': 0}, {'type': 'all+here', 'from': 0}, ], arg_constraints=[[], is_held_item(1), []], func_constraints=[{'type': 'fits_in', 'in_args': [1, 2], 'args': []}], callback_triggers=[ {'action': 'moved_to', 'args': [1, 2]}, {'action': 'agent_dropped', 'args': [0, 1]}, ], ) <NEW_LINE> self.formats = { 'dropped': '{0} dropped {1}. ', 'failed': '{0} couldn\'t drop that. ', } <NEW_LINE> <DEDENT> def func(self, graph, args): <NEW_LINE> <INDENT> agent_id, object_id, room_id = args[0], args[1], args[2] <NEW_LINE> graph.move_object(object_id, room_id) <NEW_LINE> put_action = { 'caller': self.get_name(), 'name': 'dropped', 'room_id': room_id, 'actors': [agent_id, object_id], } <NEW_LINE> graph.broadcast_to_room(put_action) <NEW_LINE> return True <NEW_LINE> <DEDENT> def get_find_fail_text(self, arg_idx): <NEW_LINE> <INDENT> return 'You don\'t have that. ' <NEW_LINE> <DEDENT> def parse_descs_to_args(self, graph, args): <NEW_LINE> <INDENT> args.append(graph.node_to_desc_raw(graph.location(args[0]))) <NEW_LINE> return super().parse_descs_to_args(graph, args) <NEW_LINE> <DEDENT> def get_reverse(self, graph, args): <NEW_LINE> <INDENT> return 'get', args
[Actor, object actor is carrying]
62599015bf627c535bcb21d3
class Test (unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.dbg = False <NEW_LINE> self.env = {} <NEW_LINE> self.env["CONFIG_FILE"] = "config.json" <NEW_LINE> self.config = utils.read_config(self.env) <NEW_LINE> <DEDENT> def test_get_par_flags(self): <NEW_LINE> <INDENT> config = self.config <NEW_LINE> flags = par_utils.get_par_flags(config) <NEW_LINE> <DEDENT> def test_create_par_dir(self): <NEW_LINE> <INDENT> config = self.config <NEW_LINE> par_dir = par_utils.create_par_dir(config) <NEW_LINE> par_dir = par_utils.get_par_dir(config) <NEW_LINE> <DEDENT> def test_get_output_par_file(self): <NEW_LINE> <INDENT> config = self.config <NEW_LINE> par_fn = par_utils.get_par_filename(config, absolute = True) <NEW_LINE> <DEDENT> def test_get_build_flags_string(self): <NEW_LINE> <INDENT> config = self.config <NEW_LINE> flag_string = par_utils.get_build_flags_string(config) <NEW_LINE> <DEDENT> def test_smartguide(self): <NEW_LINE> <INDENT> config = self.config <NEW_LINE> if par_utils.smartguide_available(config): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass
Unit test for the verilog pre-processor module
625990156fece00bbaccc6d9
class Menu(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=100) <NEW_LINE> description = models.CharField(max_length=1024) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_menu(cls, id=None): <NEW_LINE> <INDENT> cls_obj = cls.objects <NEW_LINE> if id: <NEW_LINE> <INDENT> cls_obj = cls_obj.get(id=id) <NEW_LINE> <DEDENT> return cls_obj.values('id', 'name') <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> ordering = ['pk']
Model to store Menu - Breakfast/Dinner/Drinks
625990150a366e3fb87dd718
class TestModuletemplate(unittest.TestCase): <NEW_LINE> <INDENT> default_options = { '_debug': False, '__logging': True, '__outputfilter': None, '_useragent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0', '_dnsserver': '', '_fetchtimeout': 5, '_internettlds': 'https://publicsuffix.org/list/effective_tld_names.dat', '_internettlds_cache': 72, '_genericusers': "abuse,admin,billing,compliance,devnull,dns,ftp,hostmaster,inoc,ispfeedback,ispsupport,list-request,list,maildaemon,marketing,noc,no-reply,noreply,null,peering,peering-notify,peering-request,phish,phishing,postmaster,privacy,registrar,registry,root,routing-registry,rr,sales,security,spam,support,sysadmin,tech,undisclosed-recipients,unsubscribe,usenet,uucp,webmaster,www", '__version__': '3.3-DEV', '__database': 'spiderfoot.test.db', '__modules__': None, '_socks1type': '', '_socks2addr': '', '_socks3port': '', '_socks4user': '', '_socks5pwd': '', '_torctlport': 9051, '__logstdout': False } <NEW_LINE> def test_opts(self): <NEW_LINE> <INDENT> module = sfp_template() <NEW_LINE> self.assertEqual(len(module.opts), len(module.optdescs)) <NEW_LINE> <DEDENT> def test_setup(self): <NEW_LINE> <INDENT> sf = SpiderFoot(self.default_options) <NEW_LINE> module = sfp_template() <NEW_LINE> module.setup(sf, dict()) <NEW_LINE> <DEDENT> def test_watchedEvents_should_return_list(self): <NEW_LINE> <INDENT> module = sfp_template() <NEW_LINE> self.assertIsInstance(module.watchedEvents(), list) <NEW_LINE> <DEDENT> def test_producedEvents_should_return_list(self): <NEW_LINE> <INDENT> module = sfp_template() <NEW_LINE> self.assertIsInstance(module.producedEvents(), list)
Test modules.sfp_template
62599015796e427e5384f4a5
class Text(Field): <NEW_LINE> <INDENT> pass
This field class matches the SQLite field type "TEXT"
625990155166f23b2e2440f6
class Config(object): <NEW_LINE> <INDENT> def __init__(self, name, mapping): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.mapping = mapping <NEW_LINE> self.result = None <NEW_LINE> self.start_time = None <NEW_LINE> self.end_time = None <NEW_LINE> self.naarad_id = None <NEW_LINE> self.message = ""
Structure used to stores information about a configuration during runtime
62599015507cdc57c63a5ac6
class PrimitiveProcedure(Procedure): <NEW_LINE> <INDENT> def __init__(self, fn, use_env=False, name='primitive'): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.fn = fn <NEW_LINE> self.use_env = use_env <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '#[{0}]'.format(self.name) <NEW_LINE> <DEDENT> def apply(self, args, env): <NEW_LINE> <INDENT> if not scheme_listp(args): <NEW_LINE> <INDENT> raise SchemeError('arguments are not in a list: {0}'.format(args)) <NEW_LINE> <DEDENT> python_args = [] <NEW_LINE> while args is not nil: <NEW_LINE> <INDENT> python_args.append(args.first) <NEW_LINE> args = args.second <NEW_LINE> <DEDENT> "*** YOUR CODE HERE ***" <NEW_LINE> if self.use_env: <NEW_LINE> <INDENT> python_args.append(env) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return self.fn(*python_args) <NEW_LINE> <DEDENT> except TypeError as x: <NEW_LINE> <INDENT> raise SchemeError()
A Scheme procedure defined as a Python function.
62599015a8ecb03325871f44
class CharmCinder(CharmBase): <NEW_LINE> <INDENT> charm_name = 'cinder' <NEW_LINE> charm_rev = 12 <NEW_LINE> display_name = 'Cinder' <NEW_LINE> menuable = True <NEW_LINE> related = [('cinder:image-service', 'glance:image-service'), ('cinder:storage-backend', 'cinder-ceph:storage-backend'), ('rabbitmq-server:amqp', 'cinder:amqp'), ('cinder:identity-service', 'keystone:identity-service'), ('nova-cloud-controller:cinder-volume-service', 'cinder:cinder-volume-service'), ('cinder:shared-db', 'mysql:shared-db')] <NEW_LINE> allowed_assignment_types = [AssignmentType.BareMetal, AssignmentType.KVM] <NEW_LINE> def set_relations(self): <NEW_LINE> <INDENT> if not self.wait_for_agent([self.charm_name, 'glance', 'keystone', 'rabbitmq-server', 'nova-cloud-controller']): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> super().set_relations()
Cinder directives
62599015507cdc57c63a5ac8
class FlickrAccount(AbstractServiceAccount): <NEW_LINE> <INDENT> persona = models.ForeignKey(OnlinePersona, related_name="flickr_accounts") <NEW_LINE> userid = models.CharField(blank=True, max_length=20, editable=False) <NEW_LINE> api_key = models.CharField(blank=False, max_length=32) <NEW_LINE> api_secret = models.CharField(blank=True, max_length=20) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = "Flickr Account" <NEW_LINE> verbose_name_plural = "Flickr Accounts" <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.username or self.userid <NEW_LINE> <DEDENT> service = u'flickr'
Describes all of the authentication credentials required for accesing photos from a specific Flickr user.
6259901521a7993f00c66ca3
class _BottleneckResidualInner(tf.keras.Model): <NEW_LINE> <INDENT> def __init__(self, filters, strides, input_shape, batch_norm_first=True, data_format="channels_first", fused=True, dtype=tf.float32): <NEW_LINE> <INDENT> super(_BottleneckResidualInner, self).__init__() <NEW_LINE> axis = 1 if data_format == "channels_first" else 3 <NEW_LINE> if batch_norm_first: <NEW_LINE> <INDENT> self.batch_norm_0 = tf.keras.layers.BatchNormalization( axis=axis, input_shape=input_shape, fused=fused, dtype=dtype) <NEW_LINE> <DEDENT> self.conv2d_1 = tf.keras.layers.Conv2D( filters=filters // 4, kernel_size=1, strides=strides, input_shape=input_shape, data_format=data_format, use_bias=False, padding="SAME", dtype=dtype) <NEW_LINE> self.batch_norm_1 = tf.keras.layers.BatchNormalization( axis=axis, fused=fused, dtype=dtype) <NEW_LINE> self.conv2d_2 = tf.keras.layers.Conv2D( filters=filters // 4, kernel_size=3, strides=(1, 1), data_format=data_format, use_bias=False, padding="SAME", dtype=dtype) <NEW_LINE> self.batch_norm_2 = tf.keras.layers.BatchNormalization( axis=axis, fused=fused, dtype=dtype) <NEW_LINE> self.conv2d_3 = tf.keras.layers.Conv2D( filters=filters, kernel_size=1, strides=(1, 1), data_format=data_format, use_bias=False, padding="SAME", dtype=dtype) <NEW_LINE> self.batch_norm_first = batch_norm_first <NEW_LINE> <DEDENT> def call(self, x, training=True): <NEW_LINE> <INDENT> net = x <NEW_LINE> if self.batch_norm_first: <NEW_LINE> <INDENT> net = self.batch_norm_0(net, training=training) <NEW_LINE> net = tf.nn.relu(net) <NEW_LINE> <DEDENT> net = self.conv2d_1(net) <NEW_LINE> net = self.batch_norm_1(net, training=training) <NEW_LINE> net = tf.nn.relu(net) <NEW_LINE> net = self.conv2d_2(net) <NEW_LINE> net = self.batch_norm_2(net, training=training) <NEW_LINE> net = tf.nn.relu(net) <NEW_LINE> net = self.conv2d_3(net) <NEW_LINE> return net
Single bottleneck residual inner function contained in _Resdual. Corresponds to the `F`/`G` functions in the paper. Suitable for training on ImageNet dataset.
6259901556b00c62f0fb35e7
class FlickConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): <NEW_LINE> <INDENT> VERSION = 1 <NEW_LINE> CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL <NEW_LINE> async def _validate_input(self, user_input): <NEW_LINE> <INDENT> auth = SimpleFlickAuth( username=user_input[CONF_USERNAME], password=user_input[CONF_PASSWORD], websession=aiohttp_client.async_get_clientsession(self.hass), client_id=user_input.get(CONF_CLIENT_ID, DEFAULT_CLIENT_ID), client_secret=user_input.get(CONF_CLIENT_SECRET, DEFAULT_CLIENT_SECRET), ) <NEW_LINE> try: <NEW_LINE> <INDENT> with async_timeout.timeout(60): <NEW_LINE> <INDENT> token = await auth.async_get_access_token() <NEW_LINE> <DEDENT> <DEDENT> except asyncio.TimeoutError: <NEW_LINE> <INDENT> raise CannotConnect() <NEW_LINE> <DEDENT> except AuthException: <NEW_LINE> <INDENT> raise InvalidAuth() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return token is not None <NEW_LINE> <DEDENT> <DEDENT> async def async_step_user(self, user_input=None): <NEW_LINE> <INDENT> errors = {} <NEW_LINE> if user_input is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> await self._validate_input(user_input) <NEW_LINE> <DEDENT> except CannotConnect: <NEW_LINE> <INDENT> errors["base"] = "cannot_connect" <NEW_LINE> <DEDENT> except InvalidAuth: <NEW_LINE> <INDENT> errors["base"] = "invalid_auth" <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> _LOGGER.exception("Unexpected exception") <NEW_LINE> errors["base"] = "unknown" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> await self.async_set_unique_id( f"flick_electric_{user_input[CONF_USERNAME]}" ) <NEW_LINE> self._abort_if_unique_id_configured() <NEW_LINE> return self.async_create_entry( title=f"Flick Electric: {user_input[CONF_USERNAME]}", data=user_input, ) <NEW_LINE> <DEDENT> <DEDENT> return self.async_show_form( step_id="user", data_schema=DATA_SCHEMA, errors=errors )
Flick config flow.
62599015d18da76e235b77e3
class FullSegmentBinding(Binding, ReferencedToObjects): <NEW_LINE> <INDENT> _n_objects = 1 <NEW_LINE> @contract(margin='number, >0', segment='$Segment') <NEW_LINE> def __init__(self, margin, segment): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._margin = margin <NEW_LINE> if not isinstance(segment, Segment): <NEW_LINE> <INDENT> raise TypeError( f'Given object has type {type(segment)}, not Segment' ) <NEW_LINE> <DEDENT> self._segment = segment <NEW_LINE> <DEDENT> @contract(x='number', y='number', returns='float|None') <NEW_LINE> def check(self, x, y): <NEW_LINE> <INDENT> x1, y1, x2, y2 = self._segment.get_base_representation() <NEW_LINE> distance = self._get_min_distance(x1, y1, x2, y2, x, y) <NEW_LINE> if distance > self._margin: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return distance <NEW_LINE> <DEDENT> <DEDENT> @contract(x='number', y='number', returns='tuple(number, number)') <NEW_LINE> def bind(self, x, y): <NEW_LINE> <INDENT> x1, y1, x2, y2 = self._segment.get_base_representation() <NEW_LINE> return self._get_nearest_point(x1, y1, x2, y2, x, y) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _get_min_distance(cls, x1, y1, x2, y2, x, y): <NEW_LINE> <INDENT> nearest_x, nearest_y = cls._get_nearest_point(x1, y1, x2, y2, x, y) <NEW_LINE> _dx = nearest_x - x <NEW_LINE> _dy = nearest_y - y <NEW_LINE> square_dist = _dx ** 2 + _dy ** 2 <NEW_LINE> return np.sqrt(square_dist) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _get_nearest_point(cls, x1, y1, x2, y2, x, y): <NEW_LINE> <INDENT> dx = x2 - x1 <NEW_LINE> dy = y2 - y1 <NEW_LINE> dr2 = dx ** 2 + dy ** 2 <NEW_LINE> lerp = ((x - x1) * dx + (y - y1) * dy) / dr2 <NEW_LINE> if lerp < 0: <NEW_LINE> <INDENT> lerp = 0 <NEW_LINE> <DEDENT> elif lerp > 1: <NEW_LINE> <INDENT> lerp = 1 <NEW_LINE> <DEDENT> nearest_x = lerp * dx + x1 <NEW_LINE> nearest_y = lerp * dy + y1 <NEW_LINE> return nearest_x, nearest_y
Binding to all segment (not to point). Parameters ---------- margin: int or float Margin of zone to bind (distance from segment to binding zone border). segment: Segment Segment for binding.
62599015925a0f43d25e8d6e
class TestMaxSizeCalc(base.MaxSizeTestCase): <NEW_LINE> <INDENT> def afterSetUp(self): <NEW_LINE> <INDENT> self.registry = queryUtility(IRegistry) <NEW_LINE> self.settings = self.registry.forInterface(ILimitFileSizePanel, check=False) <NEW_LINE> <DEDENT> def test_size_from_registry(self): <NEW_LINE> <INDENT> validator = MaxSizeValidator('checkFileMaxSize', maxsize=50.0) <NEW_LINE> self.assertEqual(float(30), get_maxsize(validator, self.settings, **{'maxsize': 15.0 , 'field': base.get_file_field(), 'instance': base.PFObject() } ) ) <NEW_LINE> self.assertEqual(float(10), get_maxsize(validator, self.settings, **{'maxsize': 15.0 , 'field': base.get_image_field(), 'instance': base.PFObject() } ) ) <NEW_LINE> <DEDENT> def test_size_from_validator_instance(self): <NEW_LINE> <INDENT> validator = MaxSizeValidator('checkFileMaxSize', maxsize=50.0) <NEW_LINE> or_file_size = self.settings.file_size <NEW_LINE> self.settings.file_size = 0 <NEW_LINE> self.assertEqual(float(50), get_maxsize(validator, self.settings, **{'field': base.get_file_field()} )) <NEW_LINE> self.settings.file_size = or_file_size <NEW_LINE> <DEDENT> def test_size_in_kwargs(self): <NEW_LINE> <INDENT> validator = MaxSizeValidator('checkFileMaxSize') <NEW_LINE> or_file_size = self.settings.file_size <NEW_LINE> self.settings.file_size = 0 <NEW_LINE> self.assertEqual(float(15), get_maxsize(validator, self.settings, **{'maxsize': 15.0 , 'field': base.get_file_field(), 'instance': base.PFObject()} ) ) <NEW_LINE> self.settings.file_size = or_file_size <NEW_LINE> <DEDENT> def test_size_in_instance(self): <NEW_LINE> <INDENT> validator = MaxSizeValidator('checkFileMaxSize') <NEW_LINE> or_file_size = self.settings.file_size <NEW_LINE> self.settings.file_size = 0 <NEW_LINE> self.assertEqual(float(20), get_maxsize(validator, self.settings, **{'field': base.get_file_field(), 'instance': base.PFObject()} ) ) <NEW_LINE> self.settings.file_size = or_file_size <NEW_LINE> <DEDENT> def test_size_in_field(self): <NEW_LINE> <INDENT> validator = MaxSizeValidator('checkFileMaxSize') <NEW_LINE> or_image_size = self.settings.image_size <NEW_LINE> self.settings.image_size = 0 <NEW_LINE> self.assertEqual(float(10), get_maxsize(validator, self.settings, **{'field': base.get_image_field()} ) ) <NEW_LINE> self.settings.image_size = or_image_size
This test cover the file/image size validation monkeypatch. File/Image at validates using zconf.ATFile.max_file_size, so we check only this case
6259901556b00c62f0fb35eb
class TestAndorCam2(unittest.TestCase, VirtualTestAndorCam): <NEW_LINE> <INDENT> camera_type = andorcam2.AndorCam2 <NEW_LINE> camera_args = (0,) <NEW_LINE> def test_binning(self): <NEW_LINE> <INDENT> camera = self.camera_type(*self.camera_args) <NEW_LINE> self.size = camera.getSensorResolution() <NEW_LINE> exposure = 0.1 <NEW_LINE> start = time.time() <NEW_LINE> im, metadata = camera.acquire((self.size[0]/2, self.size[1]/2), exposure, 2) <NEW_LINE> duration = time.time() - start <NEW_LINE> self.assertEqual(im.shape, (self.size[0]/2, self.size[1]/2)) <NEW_LINE> self.assertGreaterEqual(duration, exposure, "Error execution took %f s, less than exposure time %d." % (duration, exposure)) <NEW_LINE> self.assertIn("Exposure time", metadata)
Test directly the AndorCam2 class.
625990156fece00bbaccc6e3
class TCA6408(object): <NEW_LINE> <INDENT> pins = ( 'PWR-GOOD-3.6V', 'PWR-GOOD-1.1V', 'PWR-GOOD-2.0V', 'PWR-GOOD-5.4V', 'PWR-GOOD-5.5V', ) <NEW_LINE> def __init__(self, i2c_dev): <NEW_LINE> <INDENT> assert i2c_dev is not None <NEW_LINE> self._gpios = SysFSGPIO({'device/name': 'tca6408'}, 0x3F, 0x00, 0x00, i2c_dev) <NEW_LINE> <DEDENT> def set(self, name, value=None): <NEW_LINE> <INDENT> assert name in self.pins <NEW_LINE> self._gpios.set(self.pins.index(name), value=value) <NEW_LINE> <DEDENT> def reset(self, name): <NEW_LINE> <INDENT> self.set(name, value=0) <NEW_LINE> <DEDENT> def get(self, name): <NEW_LINE> <INDENT> assert name in self.pins <NEW_LINE> return self._gpios.get(self.pins.index(name))
Abstraction layer for the port/gpio expander
62599015507cdc57c63a5ad0
class QGyroscope(QSensor): <NEW_LINE> <INDENT> def childEvent(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def connectNotify(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def customEvent(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def disconnectNotify(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def isSignalConnected(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def reading(self): <NEW_LINE> <INDENT> return QGyroscopeReading <NEW_LINE> <DEDENT> def receivers(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def sender(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def senderSignalIndex(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def timerEvent(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self, parent=None): <NEW_LINE> <INDENT> pass
QGyroscope(parent: QObject = None)
62599015d164cc6175821cae
class PublishDrop3Test(BaseTest): <NEW_LINE> <INDENT> fixtureDB = True <NEW_LINE> fixturePool = True <NEW_LINE> fixtureCmds = [ "aptly snapshot create snap1 from mirror gnuplot-maverick", "aptly publish snapshot -keyring=${files}/aptly.pub -secret-keyring=${files}/aptly.sec -distribution=sq1 snap1", "aptly publish snapshot -keyring=${files}/aptly.pub -secret-keyring=${files}/aptly.sec -distribution=sq2 snap1", ] <NEW_LINE> runCmd = "aptly publish drop sq1" <NEW_LINE> gold_processor = BaseTest.expand_environ <NEW_LINE> def check(self): <NEW_LINE> <INDENT> super(PublishDrop3Test, self).check() <NEW_LINE> self.check_not_exists('public/dists/sq1') <NEW_LINE> self.check_exists('public/dists/sq2') <NEW_LINE> self.check_exists('public/pool/main/')
publish drop: drop one distribution
625990165166f23b2e244102
class PublishedManager(models.Manager): <NEW_LINE> <INDENT> use_for_related_fields = True <NEW_LINE> def active(self): <NEW_LINE> <INDENT> return self.filter(status='published')
Custom manager for showing published stuff.
62599016925a0f43d25e8d72
class GeolocationError(Exception): <NEW_LINE> <INDENT> pass
Exception raised when a postal code / city doesn't exist or is misformed
6259901656b00c62f0fb35ef
class TestXmlNs0FindIssuesRequest(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 testXmlNs0FindIssuesRequest(self): <NEW_LINE> <INDENT> pass
XmlNs0FindIssuesRequest unit test stubs
62599016bf627c535bcb21e1
class LogWriter(ReportWriter): <NEW_LINE> <INDENT> type_name = 'log' <NEW_LINE> def __init__(self, logger_name: str = 'wrktoolbox'): <NEW_LINE> <INDENT> self.logger = logging.getLogger(logger_name) <NEW_LINE> <DEDENT> def write(self, report: SuiteReport): <NEW_LINE> <INDENT> self.logger.info(str(report.suite)) <NEW_LINE> <DEDENT> def write_output(self, report: SuiteReport, output: BenchmarkOutput): <NEW_LINE> <INDENT> self.logger.info(str(output))
A writer that outputs to a logger.
6259901621a7993f00c66cad
class CodeSystemFilter(backboneelement.BackboneElement): <NEW_LINE> <INDENT> resource_name = "CodeSystemFilter" <NEW_LINE> def __init__(self, jsondict=None, strict=True): <NEW_LINE> <INDENT> self.code = None <NEW_LINE> self.description = None <NEW_LINE> self.operator = None <NEW_LINE> self.value = None <NEW_LINE> super(CodeSystemFilter, self).__init__(jsondict=jsondict, strict=strict) <NEW_LINE> <DEDENT> def elementProperties(self): <NEW_LINE> <INDENT> js = super(CodeSystemFilter, self).elementProperties() <NEW_LINE> js.extend([ ("code", "code", str, False, None, True), ("description", "description", str, False, None, False), ("operator", "operator", str, True, None, True), ("value", "value", str, False, None, True), ]) <NEW_LINE> return js
Filter that can be used in a value set. A filter that can be used in a value set compose statement when selecting concepts using a filter.
625990166fece00bbaccc6e9
class _TrueMatcher(AbstractMatcher): <NEW_LINE> <INDENT> def match(self, message: Message) -> bool: <NEW_LINE> <INDENT> return True
Always true
625990169b70327d1c57fab5
class S3MavenIndex(AmazonS3): <NEW_LINE> <INDENT> _INDEX_DIRNAME = 'central-index' <NEW_LINE> _INDEX_ARCHIVE = _INDEX_DIRNAME + '.zip' <NEW_LINE> _LAST_OFFSET_OBJECT_KEY = 'last_offset.json' <NEW_LINE> _DEFAULT_LAST_OFFSET = 0 <NEW_LINE> def store_index(self, target_dir): <NEW_LINE> <INDENT> with TemporaryDirectory() as temp_dir: <NEW_LINE> <INDENT> central_index_dir = os.path.join(target_dir, self._INDEX_DIRNAME) <NEW_LINE> archive_path = os.path.join(temp_dir, self._INDEX_ARCHIVE) <NEW_LINE> try: <NEW_LINE> <INDENT> Archive.zip_file(central_index_dir, archive_path, junk_paths=True) <NEW_LINE> <DEDENT> except TaskError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.store_file(archive_path, self._INDEX_ARCHIVE) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def retrieve_index_if_exists(self, target_dir): <NEW_LINE> <INDENT> if self.object_exists(self._INDEX_ARCHIVE): <NEW_LINE> <INDENT> with TemporaryDirectory() as temp_dir: <NEW_LINE> <INDENT> archive_path = os.path.join(temp_dir, self._INDEX_ARCHIVE) <NEW_LINE> central_index_dir = os.path.join(target_dir, self._INDEX_DIRNAME) <NEW_LINE> self.retrieve_file(self._INDEX_ARCHIVE, archive_path) <NEW_LINE> Archive.extract_zip(archive_path, central_index_dir, mkdest=True) <NEW_LINE> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def get_last_offset(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> content = self.retrieve_dict(self._LAST_OFFSET_OBJECT_KEY) <NEW_LINE> <DEDENT> except botocore.exceptions.ClientError as exc: <NEW_LINE> <INDENT> if exc.response['Error']['Code'] == 'NoSuchKey': <NEW_LINE> <INDENT> return self._DEFAULT_LAST_OFFSET <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> <DEDENT> return content.get('last_offset', self._DEFAULT_LAST_OFFSET) <NEW_LINE> <DEDENT> def set_last_offset(self, offset): <NEW_LINE> <INDENT> content = { 'last_offset': offset } <NEW_LINE> self.store_dict(content, self._LAST_OFFSET_OBJECT_KEY)
S3 storage for maven index.
62599016bf627c535bcb21e7
class TestCallTimeout(TestService): <NEW_LINE> <INDENT> __test__ = False <NEW_LINE> class PeriodicLogScrape: <NEW_LINE> <INDENT> def __init__(self, service): <NEW_LINE> <INDENT> self.service = service <NEW_LINE> <DEDENT> def on_timer_task(self, event): <NEW_LINE> <INDENT> log = self.service.qm.get_log() <NEW_LINE> for e in log: <NEW_LINE> <INDENT> if (e[0] == 'ROUTER_CORE' and e[1] == 'error' and e[2] == 'client test request done ' 'error=Timed out'): <NEW_LINE> <INDENT> self.service.error = "TIMED OUT!" <NEW_LINE> if self.service._conn: <NEW_LINE> <INDENT> self.service._conn.close() <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> <DEDENT> event.reactor.schedule(1, TestCallTimeout.PeriodicLogScrape(self.service)) <NEW_LINE> <DEDENT> <DEDENT> def __init__(self, address, qm): <NEW_LINE> <INDENT> super(TestCallTimeout, self).__init__(address, credit=1) <NEW_LINE> self.qm = qm <NEW_LINE> <DEDENT> def on_message(self, event): <NEW_LINE> <INDENT> event.reactor.schedule(1, self.PeriodicLogScrape(self))
test that the timeout is handled properly
625990165e10d32532ce3fa3
class UserProfile(AbstractBaseUser, PermissionsMixin): <NEW_LINE> <INDENT> email = models.EmailField(max_length=255, unique=True) <NEW_LINE> name = models.CharField(max_length=255) <NEW_LINE> is_active = models.BooleanField(default=True) <NEW_LINE> is_staff = models.BooleanField(default=False) <NEW_LINE> related_name = 'customuser' <NEW_LINE> objects = UserProfileManager() <NEW_LINE> USERNAME_FIELD = 'email' <NEW_LINE> REQUIRED_FIELDS = ['name'] <NEW_LINE> def get_full_name(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def get_short_name(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.email
Database model for users in the system
625990165166f23b2e24410a
class RateDisabledError(Exception): <NEW_LINE> <INDENT> pass
Rate disabled error
62599016be8e80087fbbfdab
class MetaMonitor(type): <NEW_LINE> <INDENT> @property <NEW_LINE> def etl_id(cls): <NEW_LINE> <INDENT> if cls._trace_key is None: <NEW_LINE> <INDENT> cls._trace_key = trace_key() <NEW_LINE> <DEDENT> return cls._trace_key <NEW_LINE> <DEDENT> @property <NEW_LINE> def environment(cls): <NEW_LINE> <INDENT> if cls._environment is None: <NEW_LINE> <INDENT> raise ValueError("value of 'environment' is None") <NEW_LINE> <DEDENT> return cls._environment <NEW_LINE> <DEDENT> @environment.setter <NEW_LINE> def environment(cls, value): <NEW_LINE> <INDENT> cls._environment = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def cluster_info(cls): <NEW_LINE> <INDENT> if cls._cluster_info is None: <NEW_LINE> <INDENT> job_flow = "/mnt/var/lib/info/job-flow.json" <NEW_LINE> if os.path.exists(job_flow): <NEW_LINE> <INDENT> with open(job_flow) as f: <NEW_LINE> <INDENT> data = json.load(f) <NEW_LINE> <DEDENT> cluster_info = {"cluster_id": data["jobFlowId"], "instance_id": data["masterInstanceId"]} <NEW_LINE> parent_dir, current_dir = os.path.split(os.getcwd()) <NEW_LINE> if parent_dir == "/mnt/var/lib/hadoop/steps": <NEW_LINE> <INDENT> cluster_info["step_id"] = current_dir <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> cluster_info = {} <NEW_LINE> <DEDENT> cls._cluster_info = cluster_info <NEW_LINE> <DEDENT> return cls._cluster_info
Metaclass to implement read-only attributes of our ETL's Monitor. If you need to find out the current trace key, call Monitor.etl_id. If you want to know the "environment" (selected by using --prefix or the user's login), then use Monitor.environment. If you want to know the runtime environment (EMR, instance, step), use Monitor.cluster_info. Behind the scenes, some properties actually do a lazy evaluation.
62599016507cdc57c63a5ada
class SynnefoFilterProcessor(Processor): <NEW_LINE> <INDENT> def is_active(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def filter_extra(self, data): <NEW_LINE> <INDENT> if not self.is_active(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> request = data.get('request', None) <NEW_LINE> if request is not None: <NEW_LINE> <INDENT> data['request'] = cleanse_request(request, HIDDEN_COOKIES, HIDDEN_ALL) <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> def filter_http(self, data): <NEW_LINE> <INDENT> if not self.is_active(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if data['method'] != 'GET': <NEW_LINE> <INDENT> if data['data']: <NEW_LINE> <INDENT> content_type = data['headers'].get('Content-Type', None) <NEW_LINE> if content_type is None: <NEW_LINE> <INDENT> reason = "No content type found" <NEW_LINE> data['data'] = cleanse_str(data['data'], HIDDEN_ALL, case=False, reason=reason) <NEW_LINE> <DEDENT> elif content_type.lower() == 'application/json': <NEW_LINE> <INDENT> data['data'] = cleanse_jsonstr(data['data'], HIDDEN_ALL, case=False) <NEW_LINE> <DEDENT> elif content_type.lower() == 'application/x-www-form-urlencoded': <NEW_LINE> <INDENT> data['data'] = cleanse_formstr(data['data'], HIDDEN_ALL, case=False) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> reason = "Unknown content type: '%s'" % content_type <NEW_LINE> data['data'] = cleanse_str(data['data'], HIDDEN_ALL, case=False, reason=reason) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> data['cookies'] = cleanse(data['cookies'], HIDDEN_COOKIES, case=False) <NEW_LINE> data['headers'] = cleanse(data['headers'], HIDDEN_HEADERS, case=False) <NEW_LINE> <DEDENT> def filter_stacktrace(self, stacktrace): <NEW_LINE> <INDENT> if not self.is_active(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for frame in stacktrace.get('frames', []): <NEW_LINE> <INDENT> if 'vars' not in frame: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> frame['vars'] = cleanse(frame['vars'], HIDDEN_STACKVARS, case=False)
Filter out Synnefo sensitive values
62599016be8e80087fbbfdad
class PBKDF2PasswordHasher(BasePasswordHasher): <NEW_LINE> <INDENT> algorithm = "pbkdf2_sha256" <NEW_LINE> iterations = 15000 <NEW_LINE> digest = hashlib.sha256 <NEW_LINE> def encode(self, password, salt, iterations=None): <NEW_LINE> <INDENT> assert password is not None <NEW_LINE> assert salt and '$' not in salt <NEW_LINE> if not iterations: <NEW_LINE> <INDENT> iterations = self.iterations <NEW_LINE> <DEDENT> hash = pbkdf2(password, salt, iterations, digest=self.digest) <NEW_LINE> hash = base64.b64encode(hash).decode('ascii').strip() <NEW_LINE> return "%s$%d$%s$%s" % (self.algorithm, iterations, salt, hash) <NEW_LINE> <DEDENT> def verify(self, password, encoded): <NEW_LINE> <INDENT> algorithm, iterations, salt, hash = encoded.split('$', 3) <NEW_LINE> assert algorithm == self.algorithm <NEW_LINE> encoded_2 = self.encode(password, salt, int(iterations)) <NEW_LINE> return constant_time_compare(encoded, encoded_2) <NEW_LINE> <DEDENT> def safe_summary(self, encoded): <NEW_LINE> <INDENT> algorithm, iterations, salt, hash = encoded.split('$', 3) <NEW_LINE> assert algorithm == self.algorithm <NEW_LINE> return OrderedDict([ (_('algorithm'), algorithm), (_('iterations'), iterations), (_('salt'), mask_hash(salt)), (_('hash'), mask_hash(hash)), ]) <NEW_LINE> <DEDENT> def must_update(self, encoded): <NEW_LINE> <INDENT> algorithm, iterations, salt, hash = encoded.split('$', 3) <NEW_LINE> return int(iterations) != self.iterations
Secure password hashing using the PBKDF2 algorithm (recommended) Configured to use PBKDF2 + HMAC + SHA256 with 15000 iterations. The result is a 64 byte binary string. Iterations may be changed safely but you must rename the algorithm if you change SHA256.
6259901656b00c62f0fb35f9
class AbsoluteSpec(Specification): <NEW_LINE> <INDENT> def __init__(self, amount): <NEW_LINE> <INDENT> self.amount = amount
AbsoluteSpec class.
62599016a8ecb03325871f5a
class UserManager(BaseUserManager): <NEW_LINE> <INDENT> def create_user(self, email, user_name=None, password=None): <NEW_LINE> <INDENT> if not email: <NEW_LINE> <INDENT> raise ValueError('Users must have an email address') <NEW_LINE> <DEDENT> user = self.model( email=self.normalize_email(email), user_name=user_name) <NEW_LINE> user.set_password(password) <NEW_LINE> user.save(using=self._db) <NEW_LINE> return user <NEW_LINE> <DEDENT> def create_superuser(self, email, password, user_name): <NEW_LINE> <INDENT> user = self.create_user( email=email, password=password, user_name=user_name) <NEW_LINE> user.is_superuser = True <NEW_LINE> user.is_staff = True <NEW_LINE> user.save(using=self._db) <NEW_LINE> return user <NEW_LINE> <DEDENT> def _check_unique_email(self, email): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.get_queryset().get(email=email) <NEW_LINE> raise ValueError("This email is already registered") <NEW_LINE> <DEDENT> except self.model.DoesNotExist: <NEW_LINE> <INDENT> return True
manager for creating user and super user.
62599016d164cc6175821cba
class ClassControllerServicer(object): <NEW_LINE> <INDENT> def List(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') <NEW_LINE> <DEDENT> def GetCommonClasses(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') <NEW_LINE> <DEDENT> def IsExist(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!')
Missing associated documentation comment in .proto file.
625990166fece00bbaccc6f1
class Reco_face(object): <NEW_LINE> <INDENT> def __init__(self, source="Images/cap_default.jpg"): <NEW_LINE> <INDENT> self.source = source <NEW_LINE> <DEDENT> def find_face(self): <NEW_LINE> <INDENT> image = face_recognition.load_image_file(self.source) <NEW_LINE> face_locations = face_recognition.face_locations(image) <NEW_LINE> face_number = len(face_locations) <NEW_LINE> print(face_number) <NEW_LINE> for face_num, face_location in enumerate(face_locations): <NEW_LINE> <INDENT> top, right, bottom, left = face_location <NEW_LINE> face_image = image[top:bottom, left:right] <NEW_LINE> pil_image = Image.fromarray(face_image) <NEW_LINE> pil_image.save(self.source + "_face-{:02d}.jpg".format(face_num)) <NEW_LINE> <DEDENT> <DEDENT> def find_facial_features(self): <NEW_LINE> <INDENT> image = face_recognition.load_image_file(self.source) <NEW_LINE> face_landmarks_list = face_recognition.face_landmarks(image) <NEW_LINE> face_number = len(face_landmarks_list) <NEW_LINE> for face_num, face_landmarks in enumerate(face_landmarks_list): <NEW_LINE> <INDENT> facial_features = ['chin', 'left_eyebrow', 'right_eyebrow', 'nose_bridge', 'nose_tip', 'left_eye', 'right_eye', 'top_lip', 'bottom_lip'] <NEW_LINE> pil_image = Image.fromarray(image) <NEW_LINE> d = ImageDraw.Draw(pil_image) <NEW_LINE> for facial_feature in facial_features: <NEW_LINE> <INDENT> d.line(face_landmarks[facial_feature], width=5) <NEW_LINE> <DEDENT> pil_image.save(self.source + "_face_feature-{:02d}.jpg".format(face_num))
Reconnaissance faciale.
62599016d18da76e235b77ec
class ConnectDB(object): <NEW_LINE> <INDENT> def __init__(self, path, name): <NEW_LINE> <INDENT> self.path = path <NEW_LINE> self.name = name <NEW_LINE> self.connection = None <NEW_LINE> self.cursor = None <NEW_LINE> <DEDENT> def connect(self): <NEW_LINE> <INDENT> self.connection = dataBase.sqlite3.connect(self.path + self.name) <NEW_LINE> self.connection.row_factory = dataBase.sqlite3.Row <NEW_LINE> self.cursor = self.connection.cursor() <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.connection.commit() <NEW_LINE> self.connection.close()
Class connect db est une classe abstraite qui permet de se connecter a une base de donnée sqlite3
625990160a366e3fb87dd732
class Greatsword(Weapon): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__( name="Greatsword", multiplier=2, damage_die=6, )
Class handling the Greatsword weapon type. The greatsword deals 2d6 damage.
625990160a366e3fb87dd734
class InvalidProtoError(Exception): <NEW_LINE> <INDENT> def __init__(self, msg): <NEW_LINE> <INDENT> self.msg = msg <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "InvalidProtoError error: %s" % self.msg
Exception class raised in the event of an invalid protocol passed through a protocol message. This error is from supplying a protocol function call with an invalid protocol argument to specify an action the caller is to take.
625990165e10d32532ce3fa8
class UserManager(BaseUserManager): <NEW_LINE> <INDENT> def create_user(self, nick: str, password: str=None, **kwargs): <NEW_LINE> <INDENT> user = self.model(nick=nick, **kwargs) <NEW_LINE> user.set_password(password) <NEW_LINE> user.save() <NEW_LINE> return user <NEW_LINE> <DEDENT> def create_superuser(self, nick: str, password: str, **kwargs): <NEW_LINE> <INDENT> user = self.create_user(nick=nick, password=password, **kwargs) <NEW_LINE> user.is_staff = True <NEW_LINE> user.is_superuser = True <NEW_LINE> user.save(update_fields=['is_staff', 'is_superuser']) <NEW_LINE> return user
The user manager class
625990160a366e3fb87dd736
class puError(Exception): <NEW_LINE> <INDENT> def __init__( self, dW, sender, engLogMessage, czeStatusBarMessage=None, czeMessageBarMessage=None, duration=20): <NEW_LINE> <INDENT> super(Exception, self).__init__(dW) <NEW_LINE> dW.display_error_messages( sender, engLogMessage, czeStatusBarMessage, czeMessageBarMessage, duration)
A custom exception.
62599016d164cc6175821cc0
class TenantServiceVolume(BaseModel): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> db_table = 'tenant_service_volume' <NEW_LINE> <DEDENT> SHARE = 'share-file' <NEW_LINE> LOCAL = 'local' <NEW_LINE> TMPFS = 'memoryfs' <NEW_LINE> service_id = models.CharField(max_length=32, help_text=u"组件id") <NEW_LINE> category = models.CharField(max_length=50, blank=True, help_text=u"组件类型") <NEW_LINE> host_path = models.CharField(max_length=400, help_text=u"物理机的路径,绝对路径") <NEW_LINE> volume_type = models.CharField(max_length=64, blank=True) <NEW_LINE> volume_path = models.CharField(max_length=400, help_text=u"容器内路径,application为相对;其他为绝对") <NEW_LINE> volume_name = models.CharField(max_length=100, blank=True) <NEW_LINE> volume_capacity = models.IntegerField(default=0, help_text=u"存储大小,单位(Mi)") <NEW_LINE> volume_provider_name = models.CharField(max_length=100, null=True, blank=True, help_text=u"存储驱动名字") <NEW_LINE> access_mode = models.CharField(max_length=100, null=True, blank=True, help_text=u"读写模式:RWO、ROX、RWX") <NEW_LINE> share_policy = models.CharField(max_length=100, null=True, default='', blank=True, help_text=u"共享模式") <NEW_LINE> backup_policy = models.CharField(max_length=100, null=True, default='', blank=True, help_text=u"备份策略") <NEW_LINE> reclaim_policy = models.CharField(max_length=100, null=True, default='', blank=True, help_text=u"回收策略") <NEW_LINE> allow_expansion = models.BooleanField(max_length=100, null=True, default=0, blank=True, help_text=u"只是支持控制扩展,0:不支持;1:支持")
数据持久化表格
625990165166f23b2e244114
class LargeRock(Asteroid): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__("images/meteorGrey_big1.png") <NEW_LINE> self.center.x = random.randint(1, 50) <NEW_LINE> self.center.y = random.randint(1, 150) <NEW_LINE> self.direction = random.randint(1, 50) <NEW_LINE> self.speed = BIG_ROCK_SPEED <NEW_LINE> self.radius = BIG_ROCK_RADIUS <NEW_LINE> self.velocity.dx = math.cos(math.radians(self.direction)) * self.speed <NEW_LINE> self.velocity.dy = math.sin(math.radians(self.direction)) * self.speed <NEW_LINE> <DEDENT> def advance(self): <NEW_LINE> <INDENT> super().advance() <NEW_LINE> self.angle += BIG_ROCK_SPIN <NEW_LINE> <DEDENT> def break_apart(self, asteroids): <NEW_LINE> <INDENT> med = MediumRock() <NEW_LINE> med.center.x = self.center.x <NEW_LINE> med.center.y = self.center.y <NEW_LINE> med.velocity.dy = self.velocity.dy + 2 <NEW_LINE> med2 = MediumRock() <NEW_LINE> med2.center.x = self.center.x <NEW_LINE> med2.center.y = self.center.y <NEW_LINE> med2.velocity.dy = self.velocity.dy - 2 <NEW_LINE> small = SmallRock() <NEW_LINE> small.center.x = self.center.x <NEW_LINE> small.center.y = self.center.y <NEW_LINE> small.velocity.dy = self.velocity.dy + 5 <NEW_LINE> asteroids.append(med) <NEW_LINE> asteroids.append(med2) <NEW_LINE> asteroids.append(small) <NEW_LINE> self.alive = False
Represents a large asteroid
62599016507cdc57c63a5ae4
class Combine(): <NEW_LINE> <INDENT> def __init__(self, operations, combine_op=torch.sum): <NEW_LINE> <INDENT> self.operations = operations <NEW_LINE> self.combine_op = combine_op <NEW_LINE> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> if len(self.operations) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> results = [op(*args, **kwargs) for op in self.operations] <NEW_LINE> return self.combine_op(torch.stack(results, dim=0)) <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, item): <NEW_LINE> <INDENT> return self.operations[item]
Applies different operations to an input and combines its output. Arguments: operations (list): List of operations combine_op (function): Function used to combine the results of all the operations.
62599016bf627c535bcb21f3
class SPEFile(BaseFileWriter): <NEW_LINE> <INDENT> def __init__(self, **kwds): <NEW_LINE> <INDENT> super().__init__(**kwds) <NEW_LINE> self.fp = open(self.filename, "wb") <NEW_LINE> header = chr(0) * 4100 <NEW_LINE> self.fp.write(header) <NEW_LINE> self.fp.seek(34) <NEW_LINE> self.fp.write(struct.pack("h", -1)) <NEW_LINE> self.fp.seek(42) <NEW_LINE> self.fp.write(struct.pack("h", self.feed_info.getParameter(x_pixels))) <NEW_LINE> self.fp.seek(108) <NEW_LINE> self.fp.write(struct.pack("h", 3)) <NEW_LINE> self.fp.seek(664) <NEW_LINE> self.fp.write(struct.pack("h", -1)) <NEW_LINE> self.fp.seek(656) <NEW_LINE> self.fp.write(struct.pack("h", self.feed_info.getParameter("y_pixels"))) <NEW_LINE> self.fp.seek(4100) <NEW_LINE> <DEDENT> def closeWriter(self): <NEW_LINE> <INDENT> super().closeWriter() <NEW_LINE> self.fp.seek(1446) <NEW_LINE> self.fp.write(struct.pack("i", self.number_frames)) <NEW_LINE> <DEDENT> def saveFrame(self, frame): <NEW_LINE> <INDENT> super().saveFrame() <NEW_LINE> np_data = frame.getData() <NEW_LINE> np_data.tofile(self.file_ptrs[index])
SPE file writing class. FIXME: This has not been tested, could be broken..
625990169b70327d1c57fac4
class EmptyFeature(Feature): <NEW_LINE> <INDENT> icon = '.' <NEW_LINE> blocks_light = False <NEW_LINE> blocks_movement = False <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super().__init__(self.blocks_light, self.blocks_movement, self.icon) <NEW_LINE> <DEDENT> def inspect(self): <NEW_LINE> <INDENT> return "empty floorspace"
An empty feature that omits both light and movement.
625990166fece00bbaccc6f9
class BaseModel(Model): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> database = db
Base model class for Habito.
625990169b70327d1c57fac6
class TestSite(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(TestSite, self).setUp() <NEW_LINE> self.username = "test_user" <NEW_LINE> self.url = reverse("create_account") <NEW_LINE> self.params = { "username": self.username, "email": "test@example.org", "password": "testpass", "name": "Test User", "honor_code": "true", "terms_of_service": "true", } <NEW_LINE> self.extended_params = dict(list(self.params.items()) + list({ "address1": "foo", "city": "foo", "state": "foo", "country": "foo", "company": "foo", "title": "foo" }.items())) <NEW_LINE> <DEDENT> @mock.patch("openedx.core.djangoapps.site_configuration.helpers.get_value", fake_site_name) <NEW_LINE> def test_user_signup_source(self): <NEW_LINE> <INDENT> response = self.client.post(self.url, self.params) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertGreater(len(UserSignupSource.objects.filter(site='openedx.localhost')), 0) <NEW_LINE> <DEDENT> def test_user_signup_from_non_configured_site(self): <NEW_LINE> <INDENT> response = self.client.post(self.url, self.params) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertEqual(len(UserSignupSource.objects.filter(site='openedx.localhost')), 0) <NEW_LINE> <DEDENT> @mock.patch("openedx.core.djangoapps.site_configuration.helpers.get_value", fake_get_value) <NEW_LINE> def test_user_signup_missing_enhanced_profile(self): <NEW_LINE> <INDENT> response = self.client.post(self.url, self.params) <NEW_LINE> self.assertEqual(response.status_code, 400) <NEW_LINE> <DEDENT> @mock.patch("openedx.core.djangoapps.site_configuration.helpers.get_value", fake_get_value) <NEW_LINE> def test_user_signup_including_enhanced_profile(self): <NEW_LINE> <INDENT> response = self.client.post(self.url, self.extended_params) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> user = User.objects.get(username=self.username) <NEW_LINE> meta = json.loads(user.profile.meta) <NEW_LINE> self.assertEqual(meta['address1'], 'foo') <NEW_LINE> self.assertEqual(meta['state'], 'foo') <NEW_LINE> self.assertEqual(meta['company'], 'foo') <NEW_LINE> self.assertEqual(meta['title'], 'foo')
Test for Account Creation from white labeled Sites
62599016925a0f43d25e8d86
class Renew(Service): <NEW_LINE> <INDENT> def reply(self): <NEW_LINE> <INDENT> plugin = None <NEW_LINE> acl_users = getToolByName(self, "acl_users") <NEW_LINE> plugins = acl_users._getOb('plugins') <NEW_LINE> authenticators = plugins.listPlugins(IAuthenticationPlugin) <NEW_LINE> for id_, authenticator in authenticators: <NEW_LINE> <INDENT> if authenticator.meta_type == "JWT Authentication Plugin": <NEW_LINE> <INDENT> plugin = authenticator <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if plugin is None: <NEW_LINE> <INDENT> self.request.response.setStatus(501) <NEW_LINE> return dict(error=dict( type='Renew failed', message='JWT authentication plugin not installed.')) <NEW_LINE> <DEDENT> if 'IDisableCSRFProtection' in dir(plone.protect.interfaces): <NEW_LINE> <INDENT> alsoProvides(self.request, plone.protect.interfaces.IDisableCSRFProtection) <NEW_LINE> <DEDENT> mtool = getToolByName(self.context, 'portal_membership') <NEW_LINE> user = mtool.getAuthenticatedMember() <NEW_LINE> payload = {} <NEW_LINE> payload['fullname'] = user.getProperty('fullname') <NEW_LINE> new_token = plugin.create_token(user.getId(), data=payload) <NEW_LINE> if plugin.store_tokens and self.request._auth: <NEW_LINE> <INDENT> old_token = self.request._auth[7:] <NEW_LINE> plugin.delete_token(old_token) <NEW_LINE> <DEDENT> return { 'token': new_token }
Renew authentication token
62599016507cdc57c63a5aea
class App(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.next_window = 'main_menu' <NEW_LINE> self.config = parse_settings.Settings_Parser() <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> program_finished = False <NEW_LINE> while not program_finished: <NEW_LINE> <INDENT> if self.next_window == 'main_menu': <NEW_LINE> <INDENT> self.run_main_menu() <NEW_LINE> <DEDENT> if self.next_window == 'login': <NEW_LINE> <INDENT> self.run_login() <NEW_LINE> <DEDENT> if self.next_window == 'backup': <NEW_LINE> <INDENT> self.run_backup() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> program_finished = True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def run_main_menu(self): <NEW_LINE> <INDENT> tMainMenu = Tk() <NEW_LINE> tMainMenu.title("Homecloud Menu") <NEW_LINE> tMainMenu.geometry("250x190") <NEW_LINE> tMainMenu.resizable(0,0) <NEW_LINE> m_menu = screens.Main_Menu(tMainMenu) <NEW_LINE> m_menu.mainloop() <NEW_LINE> self.check_next_window(m_menu) <NEW_LINE> <DEDENT> def run_login(self): <NEW_LINE> <INDENT> tLogin = Tk() <NEW_LINE> tLogin.title("Login to Homecloud") <NEW_LINE> tLogin.geometry("250x160") <NEW_LINE> tLogin.resizable(0,0) <NEW_LINE> s_login = screens.Login(tLogin, self.config) <NEW_LINE> s_login.mainloop() <NEW_LINE> self.check_next_window(s_login) <NEW_LINE> self.ftp_connection = s_login.get_ftp_connection() <NEW_LINE> <DEDENT> def run_backup(self): <NEW_LINE> <INDENT> tBackup = Tk() <NEW_LINE> tBackup.title("Backup") <NEW_LINE> tBackup.geometry("700x100") <NEW_LINE> s_backup = screens.Backup(tBackup, self.ftp_connection, self.config) <NEW_LINE> s_backup.mainloop() <NEW_LINE> self.check_next_window(s_backup) <NEW_LINE> <DEDENT> def check_next_window(self, frame): <NEW_LINE> <INDENT> self.next_window=frame.get_next_window()
Manages controls the program
62599016bf627c535bcb21f9
class Licence(models.Model): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = 'Licence' <NEW_LINE> verbose_name_plural = 'Licences' <NEW_LINE> <DEDENT> code = models.CharField('Code', max_length=20) <NEW_LINE> title = models.CharField('Titre', max_length=80) <NEW_LINE> description = models.TextField('Description') <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.title
Publication licence.
6259901621a7993f00c66cc5
class FileCacher(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.reset() <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.out = [] <NEW_LINE> <DEDENT> def write(self, line): <NEW_LINE> <INDENT> self.out.append(line) <NEW_LINE> <DEDENT> def flush(self): <NEW_LINE> <INDENT> if '\n' in self.out: <NEW_LINE> <INDENT> self.out.remove('\n') <NEW_LINE> <DEDENT> output = '\n'.join(self.out) <NEW_LINE> self.reset() <NEW_LINE> return output
Class for caching the stdout text.
625990166fece00bbaccc6ff
class DescribeClusterKubeconfigResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Kubeconfig = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Kubeconfig = params.get("Kubeconfig") <NEW_LINE> self.RequestId = params.get("RequestId")
DescribeClusterKubeconfig response structure.
62599016796e427e5384f4cb
class Example: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.swaggerTypes = { 'id': 'int', 'exampleId': 'int', 'title': 'str', 'text': 'str', 'score': 'ScoredWord', 'sentence': 'Sentence', 'word': 'str', 'provider': 'ContentProvider', 'year': 'int', 'rating': 'float', 'documentId': 'int', 'url': 'str' } <NEW_LINE> self.id = None <NEW_LINE> self.exampleId = None <NEW_LINE> self.title = None <NEW_LINE> self.text = None <NEW_LINE> self.score = None <NEW_LINE> self.sentence = None <NEW_LINE> self.word = None <NEW_LINE> self.provider = None <NEW_LINE> self.year = None <NEW_LINE> self.rating = None <NEW_LINE> self.documentId = None <NEW_LINE> self.url = None
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
6259901656b00c62f0fb3608
class Spindle(Package): <NEW_LINE> <INDENT> homepage = "https://computation-rnd.llnl.gov/spindle" <NEW_LINE> url = "https://github.com/hpc/Spindle/archive/v0.8.1.tar.gz" <NEW_LINE> list_url = "https://github.com/hpc/Spindle/releases" <NEW_LINE> version('0.8.1', 'f11793a6b9d8df2cd231fccb2857d912') <NEW_LINE> depends_on("launchmon") <NEW_LINE> def install(self, spec, prefix): <NEW_LINE> <INDENT> configure("--prefix=" + prefix) <NEW_LINE> make() <NEW_LINE> make("install")
Spindle improves the library-loading performance of dynamically linked HPC applications. Without Spindle large MPI jobs can overload on a shared file system when loading dynamically linked libraries, causing site-wide performance problems.
625990168c3a8732951f72b0
class ModStatusOutputNative(ModInput): <NEW_LINE> <INDENT> def __init__(self, physical_source_addr: LcnAddr, output_id: int, value: int): <NEW_LINE> <INDENT> super().__init__(physical_source_addr) <NEW_LINE> self.output_id = output_id <NEW_LINE> self.value = value <NEW_LINE> <DEDENT> def get_output_id(self) -> int: <NEW_LINE> <INDENT> return self.output_id <NEW_LINE> <DEDENT> def get_value(self) -> int: <NEW_LINE> <INDENT> return self.value <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def try_parse(data: str) -> Optional[List[Input]]: <NEW_LINE> <INDENT> matcher = PckParser.PATTERN_STATUS_OUTPUT_NATIVE.match(data) <NEW_LINE> if matcher: <NEW_LINE> <INDENT> addr = LcnAddr(int(matcher.group("seg_id")), int(matcher.group("mod_id"))) <NEW_LINE> return [ ModStatusOutputNative( addr, int(matcher.group("output_id")) - 1, int(matcher.group("value")), ) ] <NEW_LINE> <DEDENT> return None
Status of an output-port in native units received from an LCN module.
6259901621a7993f00c66ccb
class Position(Vector3): <NEW_LINE> <INDENT> __slots__ = ()
Represents the position of an object in the world. A position consists of its x, y and z values in millimeters. Args: x (float): X position in millimeters y (float): Y position in millimeters z (float): Z position in millimeters
625990166fece00bbaccc705
class DeleteLaunchConfigurationRequest(object): <NEW_LINE> <INDENT> swagger_types = { 'region_code': 'str', 'launch_configuration_no': 'str' } <NEW_LINE> attribute_map = { 'region_code': 'regionCode', 'launch_configuration_no': 'launchConfigurationNo' } <NEW_LINE> def __init__(self, region_code=None, launch_configuration_no=None): <NEW_LINE> <INDENT> self._region_code = None <NEW_LINE> self._launch_configuration_no = None <NEW_LINE> self.discriminator = None <NEW_LINE> if region_code is not None: <NEW_LINE> <INDENT> self.region_code = region_code <NEW_LINE> <DEDENT> self.launch_configuration_no = launch_configuration_no <NEW_LINE> <DEDENT> @property <NEW_LINE> def region_code(self): <NEW_LINE> <INDENT> return self._region_code <NEW_LINE> <DEDENT> @region_code.setter <NEW_LINE> def region_code(self, region_code): <NEW_LINE> <INDENT> self._region_code = region_code <NEW_LINE> <DEDENT> @property <NEW_LINE> def launch_configuration_no(self): <NEW_LINE> <INDENT> return self._launch_configuration_no <NEW_LINE> <DEDENT> @launch_configuration_no.setter <NEW_LINE> def launch_configuration_no(self, launch_configuration_no): <NEW_LINE> <INDENT> if launch_configuration_no is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `launch_configuration_no`, must not be `None`") <NEW_LINE> <DEDENT> self._launch_configuration_no = launch_configuration_no <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, DeleteLaunchConfigurationRequest): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62599016507cdc57c63a5af2
class MainWindow(QtWidgets.QMainWindow): <NEW_LINE> <INDENT> def __init__(self, ps, parent: QtWidgets.QWidget=None): <NEW_LINE> <INDENT> super().__init__(parent) <NEW_LINE> self.setWindowTitle("Univerzitet Singidunum") <NEW_LINE> self.resize(1400, 700) <NEW_LINE> self.setWindowIcon(QtGui.QIcon("resources/icons/abacus.png")) <NEW_LINE> self.plugin_service = ps <NEW_LINE> self.action_dict = { "open": QtWidgets.QAction(QtGui.QIcon("resources/icons/folder-open-document.png"), "&Open document"), "plugin_settings": QtWidgets.QAction(QtGui.QIcon("resources/icons/puzzle.png"), "&Plugin settings") } <NEW_LINE> self.menu_bar = QtWidgets.QMenuBar(self) <NEW_LINE> self.tool_bar = QtWidgets.QToolBar("Toolbar", self) <NEW_LINE> self.file_menu = QtWidgets.QMenu("&File", self.menu_bar) <NEW_LINE> self.view_menu = QtWidgets.QMenu("&View", self.menu_bar) <NEW_LINE> self.tools_menu = QtWidgets.QMenu("&Tools", self.menu_bar) <NEW_LINE> self.help_menu = QtWidgets.QMenu("&Help", self.menu_bar) <NEW_LINE> self.central_widget = QtWidgets.QTextEdit(self) <NEW_LINE> self._bind_actions() <NEW_LINE> self._populate_menu_bar() <NEW_LINE> self._populate_tool_bar() <NEW_LINE> self.setCentralWidget(self.central_widget) <NEW_LINE> self.addToolBar(self.tool_bar) <NEW_LINE> self.setMenuBar(self.menu_bar) <NEW_LINE> <DEDENT> def _populate_menu_bar(self): <NEW_LINE> <INDENT> self.file_menu.addAction(self.action_dict["open"]) <NEW_LINE> self.view_menu.addAction(self.tool_bar.toggleViewAction()) <NEW_LINE> self.tools_menu.addAction(self.action_dict["plugin_settings"]) <NEW_LINE> self.menu_bar.addMenu(self.file_menu) <NEW_LINE> self.menu_bar.addMenu(self.view_menu) <NEW_LINE> self.menu_bar.addMenu(self.tools_menu) <NEW_LINE> self.menu_bar.addMenu(self.help_menu) <NEW_LINE> <DEDENT> def _populate_tool_bar(self): <NEW_LINE> <INDENT> self.tool_bar.addAction(self.action_dict["open"]) <NEW_LINE> <DEDENT> def _bind_actions(self): <NEW_LINE> <INDENT> self.action_dict["open"].triggered.connect(self.on_open) <NEW_LINE> self.action_dict["plugin_settings"].triggered.connect(self.on_open_plugin_settings_dialog) <NEW_LINE> <DEDENT> def on_open(self): <NEW_LINE> <INDENT> file_name = QtWidgets.QFileDialog.getOpenFileName(self, "Open python file", ".", "Python Files (*.py)") <NEW_LINE> with open(file_name[0], "r") as fp: <NEW_LINE> <INDENT> text_from_file = fp.read() <NEW_LINE> self.central_widget.setText(text_from_file) <NEW_LINE> <DEDENT> <DEDENT> def on_open_plugin_settings_dialog(self): <NEW_LINE> <INDENT> dialog = PluginDialog("Plugin settings", self, self.plugin_service) <NEW_LINE> dialog.exec_() <NEW_LINE> <DEDENT> def set_central_widget(self, symbolic_name: str): <NEW_LINE> <INDENT> plugin = self.plugin_service.get_by_symbolic_name(symbolic_name) <NEW_LINE> widgets = plugin.get_widget() <NEW_LINE> self.setCentralWidget(widgets[0]) <NEW_LINE> if widgets[1] is not None: <NEW_LINE> <INDENT> self.tool_bar.addSeparator() <NEW_LINE> self.tool_bar.addActions(widgets[1].actions()) <NEW_LINE> <DEDENT> self.menu_bar.addMenu(widgets[2]) if widgets[2] is not None else None
Klasa koja predstavlja glavni prozor aplikacije.
62599016d164cc6175821cce
@implementer(interfaces.IAction) <NEW_LINE> class Action(Component): <NEW_LINE> <INDENT> prefix = 'action' <NEW_LINE> mode = 'input' <NEW_LINE> description = None <NEW_LINE> accesskey = None <NEW_LINE> postOnly = markers.DEFAULT <NEW_LINE> html5Validation = True <NEW_LINE> htmlAttributes = {} <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.htmlAttributes = self.htmlAttributes.copy() <NEW_LINE> if 'htmlAttributes' in kwargs: <NEW_LINE> <INDENT> self.htmlAttributes.update(kwargs.pop('htmlAttributes')) <NEW_LINE> <DEDENT> super(Action, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def available(self, form): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def validate(self, form): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def __call__(self, submission): <NEW_LINE> <INDENT> raise NotImplementedError
A form action.
625990168c3a8732951f72b2
class SpeciesDefinition(object): <NEW_LINE> <INDENT> def __init__(self, lhs, rhs): <NEW_LINE> <INDENT> self.lhs = lhs <NEW_LINE> self.rhs = rhs <NEW_LINE> <DEDENT> behaviours = pyparsing.delimitedList(Behaviour.grammar, delim="+") <NEW_LINE> grammar = identifier + "=" + pyparsing.Group(behaviours) + ";" <NEW_LINE> list_grammar = pyparsing.Group(pyparsing.OneOrMore(grammar)) <NEW_LINE> @classmethod <NEW_LINE> def from_tokens(cls, tokens): <NEW_LINE> <INDENT> species_name = tokens[0] <NEW_LINE> behaviours = tokens[2] <NEW_LINE> for behaviour in behaviours: <NEW_LINE> <INDENT> if behaviour.species is None: <NEW_LINE> <INDENT> behaviour.species = species_name <NEW_LINE> <DEDENT> <DEDENT> return cls(species_name, behaviours)
Class that represents a ProPPA species definition. We store the name and the right hand side of the definition which is a list of behaviours the species is involved in.
62599016be8e80087fbbfdc2
class HeatEquationDescriptor(BVPDescriptor): <NEW_LINE> <INDENT> def __init__(self, diffusivity=1, boundary_conditions=BOUNDARY_CONDITION_HOMOGENEOUS_NEUMANN, source_function=lambda t, x: 0): <NEW_LINE> <INDENT> super().__init__(boundary_conditions, source_function) <NEW_LINE> self.diffusivity = diffusivity <NEW_LINE> <DEDENT> def update_function(self, t, dt, x, y, y_previous, laplacian): <NEW_LINE> <INDENT> return y + self.diffusivity*dt*numpy.dot(laplacian, y) + dt*self.source_function(t, x)
A BVPDescriptor for the heat Equation, dy/dt = a d^2y/dx^2 + source_function. Defaults to homogeneous Neumann boundary conditions (zero derivative at the edges. Physically this corresponds to perfect insulators at both ends), a diffusivity of 1 and no source function. This implementation is currently extremely unstable, and requires a small diffusivity in order to not explode. Attributes: diffusivity (float): The parameter a in the heat equation. A large diffusivity means that heat spreads quickly.
625990178c3a8732951f72b4
class MnemonicReader(nn.Module): <NEW_LINE> <INDENT> def __init__(self, args): <NEW_LINE> <INDENT> super(MnemonicReader, self).__init__() <NEW_LINE> self.args = args <NEW_LINE> self.w_embedding = nn.Embedding(args.w_vocab_size, args.w_embedding_dim, padding_idx=0) <NEW_LINE> self.c_embedding = nn.Embedding(args.c_vocab_size, args.c_embedding_dim, padding_idx=0) <NEW_LINE> self.char_rnn = None <NEW_LINE> self.encoder = None <NEW_LINE> self.ptr = None <NEW_LINE> <DEDENT> def forward(self, p_word, p_char, p_feat, p_mask, q_word, q_char, q_feat, q_mask): <NEW_LINE> <INDENT> p_word_emb = self.w_embedding(p_word) <NEW_LINE> p_char_emb = self.c_embedding(p_char) <NEW_LINE> q_word_emb = self.w_embedding(q_word) <NEW_LINE> q_char_emb = self.c_embedding(q_char) <NEW_LINE> p_char_enc = self.char_rnn(p_char_emb, p_mask) <NEW_LINE> q_char_enc = self.char_rnn(q_char_emb, q_mask) <NEW_LINE> p_input = [p_word_emb, p_char_enc] <NEW_LINE> q_input = [q_word_emb, q_char_enc] <NEW_LINE> p_encoded = self.encoder(torch.cat(p_input, 2), p_mask) <NEW_LINE> q_encoded = self.encoder(torch.cat(q_input, 2), q_mask)
TODO: Documentation
62599017d18da76e235b77f7
class Solution(object): <NEW_LINE> <INDENT> def longestPalindrome(self, s): <NEW_LINE> <INDENT> l = len(s) <NEW_LINE> isPalindrome = [[False]*l for _ in range(l)] <NEW_LINE> maxl = 0 <NEW_LINE> res = "" <NEW_LINE> for length in range(l): <NEW_LINE> <INDENT> for i in range(l): <NEW_LINE> <INDENT> j = i + length <NEW_LINE> if j >= l: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if length == 0: <NEW_LINE> <INDENT> isPalindrome[i][j] = True <NEW_LINE> <DEDENT> elif length == 1: <NEW_LINE> <INDENT> isPalindrome[i][j] = s[i] == s[j] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> isPalindrome[i][j] = s[i] == s[j] and isPalindrome[i + 1][j - 1] <NEW_LINE> <DEDENT> if isPalindrome[i][j] and length >= maxl: <NEW_LINE> <INDENT> maxl = length <NEW_LINE> res = s[i:j+1] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return res
dynamic programming: isPalindrome[i][j] = isPalindrome[i+1][j-1] && s[i] == s[j] time: O(n**2) space: O(n**2)
62599017796e427e5384f4d3
class RechargeSettingsView(mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.RetrieveModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): <NEW_LINE> <INDENT> queryset = RechargeSettings.objects.all() <NEW_LINE> serializer_class = serializers.RechargeSettingsSerializer <NEW_LINE> permission_classes = (PermsRequired('main.vip_info'), ) <NEW_LINE> def perform_create(self, serializer): <NEW_LINE> <INDENT> if self.request.user and hasattr(self.request.user, 'staffprofile'): <NEW_LINE> <INDENT> serializer.save(operator_name=self.request.user.staffprofile) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> serializer.save() <NEW_LINE> <DEDENT> <DEDENT> def perform_update(self, serializer): <NEW_LINE> <INDENT> if self.request.user and hasattr(self.request.user, 'staffprofile'): <NEW_LINE> <INDENT> serializer.save(operator_name=self.request.user.staffprofile) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> serializer.save()
create: 创建充值配置 update: 更新充值配置 retrieve: 充值配置详情 list: 所有充值配置
62599017a8ecb03325871f72
class Minimax(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(Minimax, self).__init__() <NEW_LINE> <DEDENT> def minimaxDecision(self, state): <NEW_LINE> <INDENT> v = self.maxValue(state) <NEW_LINE> return [action for action, successorState in self.successors(state) if self.utility(action) == v] <NEW_LINE> <DEDENT> def infinity(self): <NEW_LINE> <INDENT> return sys.maxint <NEW_LINE> <DEDENT> def negativeInfinity(self): <NEW_LINE> <INDENT> return -sys.maxint - 1 <NEW_LINE> <DEDENT> def maxValue(self, state): <NEW_LINE> <INDENT> if self.isTerminal(state): return self.utility(state) <NEW_LINE> v = self.negativeInfinity() <NEW_LINE> for successorAction,successorState in self.successors(state): <NEW_LINE> <INDENT> v = max(v, self.minValue(successorState)) <NEW_LINE> <DEDENT> return v <NEW_LINE> <DEDENT> def minValue(self, state): <NEW_LINE> <INDENT> if self.isTerminal(state): return self.utility(state) <NEW_LINE> v = self.infinity() <NEW_LINE> for successorAction, successorState in self.successors(state): <NEW_LINE> <INDENT> v = min(v, self.maxValue(successorState)) <NEW_LINE> <DEDENT> return v <NEW_LINE> <DEDENT> def isTerminal(self, state): <NEW_LINE> <INDENT> return true <NEW_LINE> <DEDENT> def successors(self, state): <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> def utility(self, state): <NEW_LINE> <INDENT> pass
docstring for TronMiniMax
625990175166f23b2e244127
class FirstHeaderLineIsContinuationDefect(MessageDefect): <NEW_LINE> <INDENT> pass
A message had a continuation line as its first header line.
625990179b70327d1c57fad8
class Register(UserMixin, TemplateView): <NEW_LINE> <INDENT> template_name = INVITER_FORM_TEMPLATE <NEW_LINE> form = import_attribute(FORM) <NEW_LINE> @property <NEW_LINE> def redirect_url(self): <NEW_LINE> <INDENT> return getattr(settings, 'INVITER_REDIRECT', 'inviter2:done') <NEW_LINE> <DEDENT> def get(self, request, user): <NEW_LINE> <INDENT> context = { 'invitee': user, 'form': self.form(**{INVITER_FORM_USER_KWARG: user}) } <NEW_LINE> return self.render_to_response(context) <NEW_LINE> <DEDENT> def post(self, request, user): <NEW_LINE> <INDENT> form = self.form(**{ INVITER_FORM_USER_KWARG: user, 'data': request.POST }) <NEW_LINE> if form.is_valid(): <NEW_LINE> <INDENT> form.save() <NEW_LINE> if INVITER_AUTOMATIC_LOGIN: <NEW_LINE> <INDENT> username_field = getattr(user, 'USERNAME_FIELD', 'username') <NEW_LINE> user = authenticate( username=getattr(user, username_field), password=form.cleaned_data['password1']) <NEW_LINE> if user is not None: <NEW_LINE> <INDENT> if user.is_active: <NEW_LINE> <INDENT> login(request, user) <NEW_LINE> return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> return HttpResponseRedirect(reverse(self.redirect_url)) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return HttpResponseRedirect(self.redirect_url) <NEW_LINE> <DEDENT> <DEDENT> return self.render_to_response({'invitee': user, 'form': form})
A registration view for invited users. The user model already exists - this view just takes care of setting a password and username, and maybe update the email address. Anywho - one can customize the form that is used.
62599017d18da76e235b77f9
class BlueNoise(ColoredNoise): <NEW_LINE> <INDENT> def __init__(self, t=1, rng=None): <NEW_LINE> <INDENT> super().__init__(beta=-1, t=t, rng=rng)
Blue noise. .. image:: _static/blue_noise.png :scale: 50% Colored noise, or power law noise with spectral density exponent :math:`\beta = -1`. :param float t: the right hand endpoint of the time interval :math:`[0,t]` for the process :param numpy.random.Generator rng: a custom random number generator
6259901721a7993f00c66cd3
class PointerBehaviour(RaycastBehaviour): <NEW_LINE> <INDENT> def __init__(self, canvas: "EditCanvas"): <NEW_LINE> <INDENT> super().__init__(canvas) <NEW_LINE> self._pointer_moved = True <NEW_LINE> self._pointer_distance = 10 <NEW_LINE> self._pointer = RenderSelection( self.canvas.context_identifier, self.canvas.renderer.opengl_resource_pack, ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def pointer_base(self) -> BlockCoordinatesNDArray: <NEW_LINE> <INDENT> return self._pointer.point1 <NEW_LINE> <DEDENT> def bind_events(self): <NEW_LINE> <INDENT> super().bind_events() <NEW_LINE> self.canvas.Bind(EVT_PRE_DRAW, self._pre_draw) <NEW_LINE> self.canvas.Bind(EVT_CAMERA_MOVED, self._invalidate_pointer) <NEW_LINE> self.canvas.Bind(wx.EVT_MOTION, self._invalidate_pointer) <NEW_LINE> self.canvas.Bind(EVT_INPUT_PRESS, self._on_input_press) <NEW_LINE> <DEDENT> def _on_input_press(self, evt: InputPressEvent): <NEW_LINE> <INDENT> if evt.action_id == ACT_INCR_SELECT_DISTANCE: <NEW_LINE> <INDENT> self._pointer_distance += 1 <NEW_LINE> self._pointer_moved = True <NEW_LINE> <DEDENT> elif evt.action_id == ACT_DECR_SELECT_DISTANCE: <NEW_LINE> <INDENT> self._pointer_distance -= 1 <NEW_LINE> self._pointer_moved = True <NEW_LINE> <DEDENT> evt.Skip() <NEW_LINE> <DEDENT> def _invalidate_pointer(self, evt): <NEW_LINE> <INDENT> self._pointer_moved = True <NEW_LINE> evt.Skip() <NEW_LINE> <DEDENT> def _pre_draw(self, evt): <NEW_LINE> <INDENT> if self._pointer_moved: <NEW_LINE> <INDENT> self._update_pointer() <NEW_LINE> self._pointer_moved = False <NEW_LINE> <DEDENT> evt.Skip() <NEW_LINE> <DEDENT> def _post_change_event(self): <NEW_LINE> <INDENT> wx.PostEvent( self.canvas, PointChangeEvent(tuple(self._pointer.point1.tolist())) ) <NEW_LINE> <DEDENT> def _update_pointer(self): <NEW_LINE> <INDENT> if self.canvas.camera.projection_mode == Projection.TOP_DOWN: <NEW_LINE> <INDENT> location = self.closest_block_2d()[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.canvas.camera.rotating: <NEW_LINE> <INDENT> location = self.distance_block_3d(self._pointer_distance) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> location = self.closest_block_3d()[0] <NEW_LINE> <DEDENT> <DEDENT> self._pointer.point1, self._pointer.point2 = location, location + 1 <NEW_LINE> self._post_change_event() <NEW_LINE> <DEDENT> def draw(self): <NEW_LINE> <INDENT> self._pointer.draw(self.canvas.camera.transformation_matrix)
Adds the behaviour of the selection pointer.
62599017925a0f43d25e8d98
class Jacobian(object): <NEW_LINE> <INDENT> def __init__(self, solver, delta=1e-6): <NEW_LINE> <INDENT> self.jacobian = np.zeros((solver.size(), solver.size()), dtype=float) <NEW_LINE> self.solver = solver <NEW_LINE> self.delta = delta <NEW_LINE> <DEDENT> @property <NEW_LINE> def dxdt(self): <NEW_LINE> <INDENT> return self.solver.get_dxdt(self.t) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self.solver.size() <NEW_LINE> <DEDENT> @property <NEW_LINE> def t(self): <NEW_LINE> <INDENT> return self.solver.t <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> dxdt = self.dxdt <NEW_LINE> jac = self.jacobian <NEW_LINE> for i in range(len(self)): <NEW_LINE> <INDENT> self.solver.set_state(i, self.solver.get_state(i) + self.delta) <NEW_LINE> jac[i] = (self.solver.get_dxdt(self.t) - dxdt) / self.delta <NEW_LINE> self.solver.set_state(i, self.solver.get_state(i) - self.delta) <NEW_LINE> <DEDENT> return jac
Approximates the jacobian for a cmf solver J[i,j] = (dxdt(S_i,t)[j]-dxdt(S,t)[j])/delta S is the state vector S_i equals S, except for S_i[i]=S[i]+delta delta is the finite difference to approximate the Jacobian. delta should be a small number, but big enough to avoid floating point errors. 1e-6 to 1e-9 should be nice values Usage to show the jacobian: # Allocate memory for the jacobian jac = Jacobian(solver,delta) # Calculate the Jacobian J = jac() # Show the Jacobian imshow(jac(),interpolation='nearest')
625990175166f23b2e244129
class Created(Response): <NEW_LINE> <INDENT> status = 201
201 Created Must be used to indicate successful resource creation. A REST API responds with the 201 status code whenever a collection creates, or a store adds, a new resource at the client's request. There may also be times when a new resource is created as a result of some controller action, in which case 201 would also be an appropriate response.
625990178c3a8732951f72ba
class XMLSerializer: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.generator = None <NEW_LINE> <DEDENT> def serialize(self, data): <NEW_LINE> <INDENT> if not isinstance(data, dict): <NEW_LINE> <INDENT> raise SerializationException("Can't serialize data, must be a dictionary.") <NEW_LINE> <DEDENT> stream = StringIO() <NEW_LINE> self.generator = XMLGenerator(stream, "utf-8") <NEW_LINE> self.generator.startDocument() <NEW_LINE> self.generator.startElement("request", {}) <NEW_LINE> self._parse(data) <NEW_LINE> self.generator.endElement("request") <NEW_LINE> self.generator.endDocument() <NEW_LINE> return stream.getvalue() <NEW_LINE> <DEDENT> def _parse(self, data, previous_element_tag=None): <NEW_LINE> <INDENT> if isinstance(data, dict): <NEW_LINE> <INDENT> for key in data: <NEW_LINE> <INDENT> value = data[key] <NEW_LINE> self._parse(value, key) <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(data, (list, tuple)): <NEW_LINE> <INDENT> for item in data: <NEW_LINE> <INDENT> self.generator.startElement(previous_element_tag, {}) <NEW_LINE> self._parse(item, previous_element_tag) <NEW_LINE> self.generator.endElement(previous_element_tag) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.generator.startElement(previous_element_tag, {}) <NEW_LINE> self.generator.characters("%s" % data) <NEW_LINE> self.generator.endElement(previous_element_tag)
Serializes data to XML
625990170a366e3fb87dd74e
class SetupError(Error): <NEW_LINE> <INDENT> pass
Jurt not properly installed not the system
62599017be8e80087fbbfdcc
@transformations.coordinate_alias('fk5') <NEW_LINE> class FK5Coordinates(SphericalCoordinatesBase): <NEW_LINE> <INDENT> __doc__ = __doc__.format(params=SphericalCoordinatesBase._init_docstring_param_templ.format(lonnm='ra', latnm='dec')) <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(FK5Coordinates, self).__init__() <NEW_LINE> self._equinox = kwargs.pop('equinox', _EQUINOX_J2000) <NEW_LINE> self._obstime = kwargs.pop('obstime', None) <NEW_LINE> if not isinstance(self._equinox, Time): <NEW_LINE> <INDENT> raise TypeError('specified equinox is not a Time object') <NEW_LINE> <DEDENT> if self._obstime is not None and not isinstance(self._obstime, Time): <NEW_LINE> <INDENT> raise TypeError('specified obstime is not None or a Time object') <NEW_LINE> <DEDENT> if len(args) == 1 and len(kwargs) == 0 and isinstance(args[0], SphericalCoordinatesBase): <NEW_LINE> <INDENT> newcoord = args[0].transform_to(self.__class__) <NEW_LINE> self.ra = newcoord.ra <NEW_LINE> self.dec = newcoord.dec <NEW_LINE> self._distance = newcoord._distance <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> super(FK5Coordinates, self)._initialize_latlon('ra', 'dec', args, kwargs) <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if self.distance is not None: <NEW_LINE> <INDENT> diststr = ', Distance={0:.2g} {1!s}'.format(self.distance._value, self.distance._unit) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> diststr = '' <NEW_LINE> <DEDENT> msg = "<{0} RA={1:.5f} deg, Dec={2:.5f} deg{3}>" <NEW_LINE> return msg.format(self.__class__.__name__, self.ra.degree, self.dec.degree, diststr) <NEW_LINE> <DEDENT> @property <NEW_LINE> def lonangle(self): <NEW_LINE> <INDENT> return self.ra <NEW_LINE> <DEDENT> @property <NEW_LINE> def latangle(self): <NEW_LINE> <INDENT> return self.dec <NEW_LINE> <DEDENT> @property <NEW_LINE> def equinox(self): <NEW_LINE> <INDENT> return self._equinox <NEW_LINE> <DEDENT> @property <NEW_LINE> def obstime(self): <NEW_LINE> <INDENT> if self._obstime is None: <NEW_LINE> <INDENT> return self.equinox <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._obstime <NEW_LINE> <DEDENT> <DEDENT> def precess_to(self, newequinox): <NEW_LINE> <INDENT> from .earth_orientation import precession_matrix_Capitaine <NEW_LINE> pmat = precession_matrix_Capitaine(self._equinox, newequinox) <NEW_LINE> v = [self.x, self.y, self.z] <NEW_LINE> x, y, z = np.dot(pmat.A, v) <NEW_LINE> if self.distance is not None: <NEW_LINE> <INDENT> return self.__class__(x=x, y=y, z=z, unit=self.distance._unit, equinox=newequinox) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.__class__(x=x, y=y, z=z, equinox=newequinox)
A coordinate in the FK5 system. Parameters ---------- {params} equinox : `~astropy.time.Time`, optional The equinox for these coordinates. Defaults to J2000. obstime : `~astropy.time.Time` or None The time of observation for this coordinate. If None, it will be taken to be the same as the `equinox`. Alternatively, a single argument that is any kind of spherical coordinate can be provided, and will be converted to `FK5Coordinates` and used as this coordinate.
625990175e10d32532ce3fb6
class Card: <NEW_LINE> <INDENT> def __init__(self, number, suit, location=None): <NEW_LINE> <INDENT> assert Card.__is_valid(number), "Invalid number of card" <NEW_LINE> self._number = number <NEW_LINE> self._suit = suit <NEW_LINE> self._color = suit.get_color_name() <NEW_LINE> self._location = location <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self._number == 1: <NEW_LINE> <INDENT> temp = "A:" + str(self._suit) <NEW_LINE> <DEDENT> elif self._number == 11: <NEW_LINE> <INDENT> temp = "J:" + str(self._suit) <NEW_LINE> <DEDENT> elif self._number == 12: <NEW_LINE> <INDENT> temp = "Q:" + str(self._suit) <NEW_LINE> <DEDENT> elif self._number == 13: <NEW_LINE> <INDENT> temp = "K:" + str(self._suit) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> temp = str(self._number) + ":" + str(self._suit) <NEW_LINE> <DEDENT> color_code = self._suit.get_color_value()[1].value <NEW_LINE> return color_code + temp + color_code <NEW_LINE> <DEDENT> def get_color(self): <NEW_LINE> <INDENT> return self._color <NEW_LINE> <DEDENT> def get_cardsuit(self): <NEW_LINE> <INDENT> return self._suit <NEW_LINE> <DEDENT> def get_number(self): <NEW_LINE> <INDENT> return self._number <NEW_LINE> <DEDENT> def set_location(self, location): <NEW_LINE> <INDENT> self._location = location <NEW_LINE> <DEDENT> def __is_valid(number): <NEW_LINE> <INDENT> if number < 1 or number > 13 : <NEW_LINE> <INDENT> print("You cannot create a card number more than 13") <NEW_LINE> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True
This is the Card Class Color will have two types : red and black, red will be using a 0 value and black will using 1 as a constant. The Color will be using Enum Type of color inside cardcolor. Inside a card, a number will be assigned for each card from 1 (Ace) to 13 (King). shape will have four types : diamonds, hearts, spades, and clubs using Enum of Card. There will be only 52-card types, ignoring the jokers.
625990170a366e3fb87dd754
class AttachmentColumn(tables.WrappingColumn): <NEW_LINE> <INDENT> instance_detail_url = "horizon:project:instances:detail" <NEW_LINE> def get_raw_data(self, volume): <NEW_LINE> <INDENT> request = self.table.request <NEW_LINE> link = _('%(dev)s on %(instance)s') <NEW_LINE> attachments = [] <NEW_LINE> for attachment in [att for att in volume.attachments if att]: <NEW_LINE> <INDENT> instance = get_attachment_name(request, attachment, self.instance_detail_url) <NEW_LINE> vals = {"instance": instance, "dev": html.escape(attachment.get("device", ""))} <NEW_LINE> attachments.append(link % vals) <NEW_LINE> <DEDENT> return safestring.mark_safe(", ".join(attachments))
Customized column class. So it that does complex processing on the attachments for a volume instance.
625990175e10d32532ce3fb7
class TestLoyaltyStatistics(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def make_instance(self, include_optional): <NEW_LINE> <INDENT> if include_optional : <NEW_LINE> <INDENT> return LoyaltyStatistics( total_active_points = 1.337, total_pending_points = 1.337, total_spent_points = 1.337, total_expired_points = 1.337 ) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return LoyaltyStatistics( total_active_points = 1.337, total_pending_points = 1.337, total_spent_points = 1.337, total_expired_points = 1.337, ) <NEW_LINE> <DEDENT> <DEDENT> def testLoyaltyStatistics(self): <NEW_LINE> <INDENT> inst_req_only = self.make_instance(include_optional=False) <NEW_LINE> inst_req_and_optional = self.make_instance(include_optional=True)
LoyaltyStatistics unit test stubs
62599017507cdc57c63a5b01
class TestInRangeQuirks(TestInRange): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.purge() <NEW_LINE> self.quirks = True
Test in range selectors with quirks.
625990178c3a8732951f72c2
class overlayStaves(PluginFunction): <NEW_LINE> <INDENT> category = "Stable Paths Toolkit" <NEW_LINE> return_type = ImageType([RGB]) <NEW_LINE> self_type = ImageType([RGB]) <NEW_LINE> args = Args([ImageType(ONEBIT, 'Primary Image')])
Overlays the found staves from one image onto another image
625990179b70327d1c57fae2
class Code(object): <NEW_LINE> <INDENT> def __init__(self, rawcode): <NEW_LINE> <INDENT> if not hasattr(rawcode, "co_filename"): <NEW_LINE> <INDENT> rawcode = py.code.getrawcode(rawcode) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.filename = rawcode.co_filename <NEW_LINE> self.firstlineno = rawcode.co_firstlineno - 1 <NEW_LINE> self.name = rawcode.co_name <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise TypeError("not a code object: %r" %(rawcode,)) <NEW_LINE> <DEDENT> self.raw = rawcode <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.raw == other.raw <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other <NEW_LINE> <DEDENT> @property <NEW_LINE> def path(self): <NEW_LINE> <INDENT> p = py.path.local(self.raw.co_filename) <NEW_LINE> if not p.check(): <NEW_LINE> <INDENT> p = self.raw.co_filename <NEW_LINE> <DEDENT> return p <NEW_LINE> <DEDENT> @property <NEW_LINE> def fullsource(self): <NEW_LINE> <INDENT> from py._code import source <NEW_LINE> full, _ = source.findsource(self.raw) <NEW_LINE> return full <NEW_LINE> <DEDENT> def source(self): <NEW_LINE> <INDENT> return py.code.Source(self.raw) <NEW_LINE> <DEDENT> def getargs(self, var=False): <NEW_LINE> <INDENT> raw = self.raw <NEW_LINE> argcount = raw.co_argcount <NEW_LINE> if var: <NEW_LINE> <INDENT> argcount += raw.co_flags & CO_VARARGS <NEW_LINE> argcount += raw.co_flags & CO_VARKEYWORDS <NEW_LINE> <DEDENT> return raw.co_varnames[:argcount]
wrapper around Python code objects
625990176fece00bbaccc718
class _Client(_http_client.JsonHttpClient): <NEW_LINE> <INDENT> def __init__(self, credential, base_url, timeout, params=None): <NEW_LINE> <INDENT> super().__init__( credential=credential, base_url=base_url, timeout=timeout, headers={'User-Agent': _USER_AGENT}) <NEW_LINE> self.credential = credential <NEW_LINE> self.params = params if params else {} <NEW_LINE> <DEDENT> def request(self, method, url, **kwargs): <NEW_LINE> <INDENT> query = '&'.join('{0}={1}'.format(key, self.params[key]) for key in self.params) <NEW_LINE> extra_params = kwargs.get('params') <NEW_LINE> if extra_params: <NEW_LINE> <INDENT> if query: <NEW_LINE> <INDENT> query = extra_params + '&' + query <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> query = extra_params <NEW_LINE> <DEDENT> <DEDENT> kwargs['params'] = query <NEW_LINE> try: <NEW_LINE> <INDENT> return super(_Client, self).request(method, url, **kwargs) <NEW_LINE> <DEDENT> except requests.exceptions.RequestException as error: <NEW_LINE> <INDENT> raise _Client.handle_rtdb_error(error) <NEW_LINE> <DEDENT> <DEDENT> def create_listener_session(self): <NEW_LINE> <INDENT> return _sseclient.KeepAuthSession(self.credential) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def handle_rtdb_error(cls, error): <NEW_LINE> <INDENT> if error.response is None: <NEW_LINE> <INDENT> return _utils.handle_requests_error(error) <NEW_LINE> <DEDENT> message = cls._extract_error_message(error.response) <NEW_LINE> return _utils.handle_requests_error(error, message=message) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _extract_error_message(cls, response): <NEW_LINE> <INDENT> message = None <NEW_LINE> try: <NEW_LINE> <INDENT> data = response.json() <NEW_LINE> if isinstance(data, dict): <NEW_LINE> <INDENT> message = data.get('error') <NEW_LINE> <DEDENT> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> if not message: <NEW_LINE> <INDENT> message = 'Unexpected response from database: {0}'.format(response.content.decode()) <NEW_LINE> <DEDENT> return message
HTTP client used to make REST calls. _Client maintains an HTTP session, and handles authenticating HTTP requests along with marshalling and unmarshalling of JSON data.
6259901756b00c62f0fb3621
class _DictValues(object): <NEW_LINE> <INDENT> def __init__(self, dct): <NEW_LINE> <INDENT> self._dict = dct <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> return self._dict[key]['value'] <NEW_LINE> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> self._dict[key]['value'] = value <NEW_LINE> <DEDENT> def __contains__(self, key): <NEW_LINE> <INDENT> return key in self._dict <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._dict) <NEW_LINE> <DEDENT> def items(self): <NEW_LINE> <INDENT> return [(key, self._dict[key]['value']) for key in self._dict] <NEW_LINE> <DEDENT> def iteritems(self): <NEW_LINE> <INDENT> for key, val in self._dict.iteritems(): <NEW_LINE> <INDENT> yield key, val['value']
A dict-like wrapper for a dict of metadata, where getitem returns 'value' from metadata.
625990175166f23b2e244135
class Din(db.Model): <NEW_LINE> <INDENT> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> d_id = db.Column(db.Integer) <NEW_LINE> index = db.Column(db.Integer) <NEW_LINE> type = db.Column(db.Integer) <NEW_LINE> confirm_time = db.Column(db.Integer) <NEW_LINE> hr24 = db.Column(db.Integer) <NEW_LINE> start_value = db.Column(db.Integer) <NEW_LINE> interval = db.Column(db.Integer) <NEW_LINE> total = db.Column(db.Integer) <NEW_LINE> name = db.Column(db.String(20))
数字量输入 Digit IN
625990170a366e3fb87dd758