code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class TritonBrowser(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._tree4url = make_tree4url() <NEW_LINE> <DEDENT> @property <NEW_LINE> def _url_of_schedule(self): <NEW_LINE> <INDENT> tree, _url = self._tree4url(TRITONLINK_HOME_URL) <NEW_LINE> return schedule_of_classes_hrefs(tree)[0] <NEW_LINE> <DEDENT> @property <NEW_LINE> def terms(self): <NEW_LINE> <INDENT> tree, _url = self._tree4url(self._url_of_schedule) <NEW_LINE> return options2Terms(term_options(tree)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def subjects(self): <NEW_LINE> <INDENT> tree, _url = self._tree4url(self._url_of_schedule) <NEW_LINE> for option in subject_options(tree): <NEW_LINE> <INDENT> name = option.text.split("-")[1].strip() <NEW_LINE> code = option.get(VALUE).decode('utf8') <NEW_LINE> if code not in config.SUBJECT_CODE_BLACKLIST: <NEW_LINE> <INDENT> yield Subject(name, code) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _run_class_search(self, term_code, subject_code): <NEW_LINE> <INDENT> sched_tree, sched_url = self._tree4url(self._url_of_schedule) <NEW_LINE> url, query = prepare_class_search_query(term_code, subject_code, sched_tree, sched_url) <NEW_LINE> result_tree, _url = self._tree4url(url, query, hack_around_broken_html=True) <NEW_LINE> return result_tree <NEW_LINE> <DEDENT> def classes_for(self, term_code, subject_code): <NEW_LINE> <INDENT> LOGGER.info("Getting courses in subject %s for term %s", repr(subject_code), repr(term_code)) <NEW_LINE> results_tree = self._run_class_search(term_code, subject_code) <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> course_instances, url = course_instances_from(results_tree, subject_code) <NEW_LINE> <DEDENT> except TransientError: <NEW_LINE> <INDENT> LOGGER.info("Waiting before retrying after transient error") <NEW_LINE> _sleep(config.RETRY_DELAY) <NEW_LINE> continue <NEW_LINE> <DEDENT> for course_instance in course_instances: <NEW_LINE> <INDENT> yield course_instance <NEW_LINE> <DEDENT> if url is None: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> results_tree, _url = self._tree4url(url, hack_around_broken_html=True) <NEW_LINE> <DEDENT> <DEDENT> def all_classes_during(self, term_code): <NEW_LINE> <INDENT> for subject in self.subjects: <NEW_LINE> <INDENT> for course_inst in self.classes_for(term_code, subject.code): <NEW_LINE> <INDENT> yield course_inst | Used to programmatically browse TritonLink's Schedule of Classes. | 62599051d486a94d0ba2d477 |
class UpnpStatusBinarySensor(UpnpEntity, BinarySensorEntity): <NEW_LINE> <INDENT> _attr_device_class = DEVICE_CLASS_CONNECTIVITY <NEW_LINE> def __init__( self, coordinator: UpnpDataUpdateCoordinator, entity_description: UpnpBinarySensorEntityDescription, ) -> None: <NEW_LINE> <INDENT> super().__init__(coordinator=coordinator, entity_description=entity_description) <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_on(self) -> bool: <NEW_LINE> <INDENT> return self.coordinator.data[self.entity_description.key] == "Connected" | Class for UPnP/IGD binary sensors. | 625990513cc13d1c6d466bec |
class MultiHeadedAttention(nn.Module): <NEW_LINE> <INDENT> def __init__(self, num_heads, d_model, dropout=0.1): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> assert d_model % num_heads == 0 <NEW_LINE> self.d_k = d_model // num_heads <NEW_LINE> self.num_heads = num_heads <NEW_LINE> self.linear_layers = nn.ModuleList([nn.Linear(d_model, d_model) for _ in range(3)]) <NEW_LINE> self.output_linear = nn.Linear(d_model, d_model) <NEW_LINE> self.attention = Attention() <NEW_LINE> self.dropout = nn.Dropout(p=dropout) <NEW_LINE> <DEDENT> def forward(self, query, key, value, mask=None): <NEW_LINE> <INDENT> batch_size = query.size(0) <NEW_LINE> query, key, value = [l(x).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2) for l, x in zip(self.linear_layers, (query, key, value))] <NEW_LINE> x, attn = self.attention(query, key, value, mask=mask, dropout=self.dropout) <NEW_LINE> x = x.transpose(1, 2).contiguous().view(batch_size, -1, self.num_heads * self.d_k) <NEW_LINE> return self.output_linear(x), attn | Take in model size and number of heads. | 62599051ac7a0e7691f7398f |
class ProductionConfig(Config): <NEW_LINE> <INDENT> SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL') or 'sqlite:///' + os.path.join(basedir,'data.sqlite') | 生产环境 | 6259905155399d3f056279cd |
class Module(containers.DeclarativeContainer): <NEW_LINE> <INDENT> config = configparser.ConfigParser() <NEW_LINE> config.read('config.ini') <NEW_LINE> configuration = providers.Object(config) <NEW_LINE> rofex_client = providers.Singleton(RofexClient, config=config) <NEW_LINE> rofex_facade = providers.Singleton(RofexFacade, config=config, client=rofex_client()) <NEW_LINE> portfolio = providers.Singleton(Portfolio, account_id=config["PORTFOLIO"]["AccountId"], initial_amount=float(config["PORTFOLIO"]["InitialAmount"])) | IoC container of engine providers. | 62599051dc8b845886d54a71 |
class res_partner(osv.osv): <NEW_LINE> <INDENT> _inherit = 'res.partner' <NEW_LINE> _columns = { 'name_prefix':fields.many2one('config.preffix', 'Prefix'), 'lastname':fields.char('Lastname', size=128), 'firstname':fields.char('Firstname', size=128), 'middlename':fields.char('Middle Name', size=128), 'name_sufix':fields.many2one('config.suffix', 'Sufix'), 'photo':fields.binary('Photo'), 'birthdate': fields.date('Birth Date'), 'birthplace':fields.many2one('config.city', 'Birth Place'), 'age': fields.function(_compute_age, method=True, type='integer', string='Age', store=True), 'gender':fields.selection([ ('M','Male'), ('F','Female'), ],'Gender'), 'height':fields.char('Height', size=64), 'weight':fields.char('Weight', size=64), 'marital_status_id':fields.many2one('hr.employee.marital.status', 'Marital Status'), 'mothers_maiden_name':fields.char('Mothers Maiden Name', size=128), 'religion_id':fields.many2one('config.religion', 'Religion', required=False), 'tribe_id':fields.many2one('config.tribe', 'Tribe'), 'spouse_id':fields.many2one('res.partner', 'Spouse', required=False), 'educational_attainment':fields.many2one('config.education', 'Educational Attainment'), } <NEW_LINE> _rec_name = "complete_name" <NEW_LINE> _defaults = { 'citizenship_id' : 171, } | OpenERP Model : Res Partner Information | 6259905124f1403a92686327 |
class SettingsNotConfigured(Exception): <NEW_LINE> <INDENT> def __init__(self, missing_setting: str = 'Unknown', comment: str = 'None'): <NEW_LINE> <INDENT> self.missing = missing_setting <NEW_LINE> self.comment = comment <NEW_LINE> super().__init__() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self.missing != 'Unknown': <NEW_LINE> <INDENT> return_string = f"The settings file is missing the setting for {self.missing}" <NEW_LINE> if self.comment != 'None': <NEW_LINE> <INDENT> return ', '.join([return_string, self.comment]) <NEW_LINE> <DEDENT> return return_string <NEW_LINE> <DEDENT> return "The settings file is missing a setting for an unspecified section" | Is raised when the settings file is missing information | 62599051498bea3a75a58fd4 |
class APIRequestFailureException(Exception): <NEW_LINE> <INDENT> pass | Indicates that a request to external API has failed
Arguments:
Exception {[type]} -- Exception class | 6259905107d97122c4218158 |
class UserCreateView(CreateView): <NEW_LINE> <INDENT> model = User <NEW_LINE> form_class = UserCreationForm <NEW_LINE> template_name = 'signup.html' <NEW_LINE> def form_valid(self, form): <NEW_LINE> <INDENT> form.save() <NEW_LINE> user = authenticate(username=form.cleaned_data.get('username'), password=form.cleaned_data.get('password1')) <NEW_LINE> if user is not None: <NEW_LINE> <INDENT> login(self.request, user) <NEW_LINE> <DEDENT> return HttpResponseRedirect('/') | A view that creates a new user, logs them in, and redirects them to the
root URL. | 6259905130dc7b76659a0cd6 |
class LiamsGame(Game): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> super(LiamsGame, self).__init__() <NEW_LINE> self._name = name <NEW_LINE> self._gameobjects = [] <NEW_LINE> self._font = pygame.font.Font(None, 24) <NEW_LINE> self.pause_surface = pygame.Surface( (self._screen.get_size()[0] / 3, self._screen.get_size()[1] / 3)) <NEW_LINE> self.pause_surface.fill(GREEN) <NEW_LINE> self.pause_rect = self.pause_surface.get_rect() <NEW_LINE> <DEDENT> def addtobatch(self, gameobject): <NEW_LINE> <INDENT> self._gameobjects.append(gameobject) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> if not super(LiamsGame, self)._update(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for event in self._events: <NEW_LINE> <INDENT> if event.type == pygame.KEYDOWN: <NEW_LINE> <INDENT> keystate = pygame.key.get_pressed() <NEW_LINE> if keystate[pygame.constants.K_e]: <NEW_LINE> <INDENT> self.gamestate = "pause" <NEW_LINE> <DEDENT> if keystate[pygame.constants.K_r]: <NEW_LINE> <INDENT> self.gamestate = "quit" <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for gameobject in self._gameobjects: <NEW_LINE> <INDENT> gameobject.update(self._clock.get_time()) <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def draw(self): <NEW_LINE> <INDENT> self._screen.blit(self._background, (0, 0)) <NEW_LINE> for gameobject in self._gameobjects: <NEW_LINE> <INDENT> gameobject.draw(self._screen) <NEW_LINE> <DEDENT> if self.gamestate == "pause": <NEW_LINE> <INDENT> self.pause_surface.blit(self._font.render( "PAUSED", True, WHITE), self.pause_rect.move(SCREEN_WIDTH / 3, SCREEN_HEIGHT / 3)) <NEW_LINE> self._screen.blit(self._background, (0, 0)) <NEW_LINE> self._screen.blit(self.pause_surface, (0, 0)) <NEW_LINE> <DEDENT> pygame.display.flip() <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> if super(LiamsGame, self)._startup(): <NEW_LINE> <INDENT> while self.update(): <NEW_LINE> <INDENT> self.draw() <NEW_LINE> <DEDENT> <DEDENT> super(LiamsGame, self)._shutdown() | need documentation | 62599051d6c5a102081e35cc |
class Character: <NEW_LINE> <INDENT> def __init__(self, name, age, height, weight): <NEW_LINE> <INDENT> self.race = "Generic Character" <NEW_LINE> self.intelligence = random.randrange(8, 18) <NEW_LINE> self.strength = random.randrange(8, 18) <NEW_LINE> self.dexterity = random.randrange(8, 18) <NEW_LINE> self.wisdom = random.randrange(8, 18) <NEW_LINE> self.charisma = random.randrange(8, 18) <NEW_LINE> self.name = name <NEW_LINE> self.age = age <NEW_LINE> self.height = height <NEW_LINE> self.weight = weight <NEW_LINE> <DEDENT> def get_intelligence(self): <NEW_LINE> <INDENT> return(self.intelligence) <NEW_LINE> <DEDENT> def get_strength(self): <NEW_LINE> <INDENT> return(self.strength) <NEW_LINE> <DEDENT> def get_dexterity(self): <NEW_LINE> <INDENT> return(self.dexterity) <NEW_LINE> <DEDENT> def get_wisdom(self): <NEW_LINE> <INDENT> return(self.wisdom) <NEW_LINE> <DEDENT> def get_charisma(self): <NEW_LINE> <INDENT> return(self.charisma) <NEW_LINE> <DEDENT> def set_intelligence(self, intelligence): <NEW_LINE> <INDENT> self.intelligence = intelligence <NEW_LINE> <DEDENT> def set_strength(self, strength): <NEW_LINE> <INDENT> self.strength = strength <NEW_LINE> <DEDENT> def set_dexterity(self, dexterity): <NEW_LINE> <INDENT> self.dexterity = dexterity <NEW_LINE> <DEDENT> def set_wisdom(self, wisdom): <NEW_LINE> <INDENT> self.wisdom = wisdom <NEW_LINE> <DEDENT> def set_charisma(self, charisma): <NEW_LINE> <INDENT> self.charisma = charisma <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> answer = "Name: " + self.name + "\n" <NEW_LINE> answer += "Race: " + self.race + "\n" <NEW_LINE> answer += "Age: " + str(self.age) + "\n" <NEW_LINE> answer += "Height: " + str(self.height) + " inches\n" <NEW_LINE> answer += "Weight: " + str(self.weight) + " lbs\n" <NEW_LINE> answer += "Intelligence: " + str(self.intelligence) + "\n" <NEW_LINE> answer += "Strength: " + str(self.strength) + "\n" <NEW_LINE> answer += "Dexterity: " + str(self.dexterity) + "\n" <NEW_LINE> answer += "Wisdom: " + str(self.wisdom) + "\n" <NEW_LINE> answer += "Charisma: " + str(self.charisma) + "\n" <NEW_LINE> return answer | Common base class for any type of character | 625990518e7ae83300eea546 |
class Middleware(Application): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def factory(cls, global_config, **local_config): <NEW_LINE> <INDENT> def _factory(app): <NEW_LINE> <INDENT> return cls(app, **local_config) <NEW_LINE> <DEDENT> return _factory <NEW_LINE> <DEDENT> def __init__(self, application): <NEW_LINE> <INDENT> self.application = application <NEW_LINE> <DEDENT> def process_request(self, req): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def process_response(self, response): <NEW_LINE> <INDENT> return response <NEW_LINE> <DEDENT> @webob.dec.wsgify(RequestClass=Request) <NEW_LINE> def __call__(self, req): <NEW_LINE> <INDENT> response = self.process_request(req) <NEW_LINE> if response: <NEW_LINE> <INDENT> return response <NEW_LINE> <DEDENT> response = req.get_response(self.application) <NEW_LINE> return self.process_response(response) | Base WSGI middleware.
These classes require an application to be
initialized that will be called next. By default the middleware will
simply call its wrapped app, or you can override __call__ to customize its
behavior. | 625990513eb6a72ae038bb0f |
class KattisClient: <NEW_LINE> <INDENT> HEADERS = {'User-Agent': 'kattis-cli-submit'} <NEW_LINE> @staticmethod <NEW_LINE> def create_from_config(kattis_config): <NEW_LINE> <INDENT> if kattis_config is None: <NEW_LINE> <INDENT> raise KattisClientException( "No config provided. Make sure you are not passing None values") <NEW_LINE> <DEDENT> if kattis_config.password is None and kattis_config.token is None: <NEW_LINE> <INDENT> raise KattisConfigException( "Your .kattisrc seems to be corrupted. Please download a new one.") <NEW_LINE> <DEDENT> login_args = {'user': kattis_config.username, 'script': 'true'} <NEW_LINE> if kattis_config.password: <NEW_LINE> <INDENT> login_args['password'] = kattis_config.password <NEW_LINE> <DEDENT> if kattis_config.token: <NEW_LINE> <INDENT> login_args['token'] = kattis_config.token <NEW_LINE> <DEDENT> res = requests.post(kattis_config.loginurl, data=login_args, headers=KattisClient.HEADERS) <NEW_LINE> if not res.status_code == 200: <NEW_LINE> <INDENT> raise KattisClientException( "Could not log in to Kattis. Status code: " + str(res.status_code)) <NEW_LINE> <DEDENT> return KattisClient(kattis_config, res.cookies) <NEW_LINE> <DEDENT> def __init__(self, kattis_config, auth_cookies): <NEW_LINE> <INDENT> self.config = kattis_config <NEW_LINE> self.auth_cookies = auth_cookies <NEW_LINE> <DEDENT> def submit_solution(self, kattis_submission): <NEW_LINE> <INDENT> data = {'submit': 'true', 'submit_ctr': 2, 'language': kattis_submission.language, 'mainclass': kattis_submission.mainclass, 'problem': kattis_submission.problem, 'tag': '', 'script': 'true'} <NEW_LINE> sub_files = [] <NEW_LINE> for f in kattis_submission.files: <NEW_LINE> <INDENT> with open(f) as sub_file: <NEW_LINE> <INDENT> sub_files.append(('sub_file[]', (os.path.basename(f), sub_file.read(), 'application/octet-stream'))) <NEW_LINE> <DEDENT> <DEDENT> response = requests.post( self.config.submissionurl, data=data, files=sub_files, cookies=self.auth_cookies, headers=KattisClient.HEADERS) <NEW_LINE> if not response.status_code == 200: <NEW_LINE> <INDENT> raise KattisClientException( "Could not submit to Kattis. Status code: " + str(res.status_code)) <NEW_LINE> <DEDENT> return KattisSubmissionResult.create_from_response(response, self.config) | A client for executing Kattis requests | 625990514e4d5625663738c3 |
class SteamWishlistDataUpdateCoordinator(DataUpdateCoordinator): <NEW_LINE> <INDENT> def __init__(self, hass: core.HomeAssistant, url: str): <NEW_LINE> <INDENT> self.url = url <NEW_LINE> self.steam_id = self.url.split("/")[-3] <NEW_LINE> self.http_session = async_get_clientsession(hass) <NEW_LINE> super().__init__( hass, _LOGGER, name=DOMAIN, update_method=self._async_fetch_data, update_interval=SCAN_INTERVAL, ) <NEW_LINE> <DEDENT> async def _async_fetch_data(self) -> Dict[str, Dict[str, Any]]: <NEW_LINE> <INDENT> data: Dict[str, Dict[str, Any]] = {} <NEW_LINE> for page in range(10): <NEW_LINE> <INDENT> url = f"{self.url}?p={page}" <NEW_LINE> async with self.http_session.get(url) as resp: <NEW_LINE> <INDENT> result = await resp.json() <NEW_LINE> if not isinstance(result, dict): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> data.update(result) <NEW_LINE> if len(result) <= 50: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return data <NEW_LINE> <DEDENT> @property <NEW_LINE> def device_info(self) -> DeviceInfo: <NEW_LINE> <INDENT> unique_id = self.config_entry.unique_id <NEW_LINE> return DeviceInfo( identifiers={(DOMAIN, unique_id)}, manufacturer="Valve Corp", name="Steam", configuration_url=DEVICE_CONFIGURATION_URL.format(self.steam_id), ) | Data update coordinator for all steam_wishlist entities.
This class handles updating for all entities created by this component.
Since all data required to update all sensors and binary_sensors comes
from a single api endpoint, this will handle fetching that data. This way
each entity doesn't need to fetch the exact same data every time an update
is scheduled. | 6259905191af0d3eaad3b2d9 |
class AcceptAll(Test): <NEW_LINE> <INDENT> def why_not(self, _: Globals, subject: Data) -> str: <NEW_LINE> <INDENT> return '' | Every value passes this test | 6259905130c21e258be99cba |
class OrgView(View): <NEW_LINE> <INDENT> def get(self,request): <NEW_LINE> <INDENT> return render(request,"org-list.html") | 课程机构 | 6259905107d97122c4218159 |
class PySparseSGD(mx.optimizer.Optimizer): <NEW_LINE> <INDENT> def __init__(self, learning_rate=0.01, momentum=0.0, **kwargs): <NEW_LINE> <INDENT> super(PySparseSGD, self).__init__(learning_rate=learning_rate, **kwargs) <NEW_LINE> self.momentum = momentum <NEW_LINE> <DEDENT> def create_state(self, index, weight): <NEW_LINE> <INDENT> if self.momentum == 0.0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return mx.nd.zeros(weight.shape, weight.context, dtype=weight.dtype) <NEW_LINE> <DEDENT> <DEDENT> def update(self, index, weight, grad, state): <NEW_LINE> <INDENT> lr = self._get_lr(index) <NEW_LINE> wd = self._get_wd(index) <NEW_LINE> self._update_count(index) <NEW_LINE> num_rows = weight.shape[0] <NEW_LINE> if self.momentum == 0.0: <NEW_LINE> <INDENT> for row in range(num_rows): <NEW_LINE> <INDENT> grad_row = grad[row].asnumpy() <NEW_LINE> all_zeros = mx.test_utils.almost_equal(grad_row, np.zeros_like(grad_row)) <NEW_LINE> if all_zeros: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if self.clip_gradient is not None: <NEW_LINE> <INDENT> weight[row] = ((1 - lr*wd)*weight[row] - lr*mx.nd.clip(grad[row]*self.rescale_grad, -self.clip_gradient, self.clip_gradient)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> weight[row] = (1 - lr*wd)*weight[row] - lr*self.rescale_grad*grad[row] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> mom = state <NEW_LINE> for row in range(num_rows): <NEW_LINE> <INDENT> grad_row = grad[row].asnumpy() <NEW_LINE> all_zeros = mx.test_utils.almost_equal(grad_row, np.zeros_like(grad_row)) <NEW_LINE> if all_zeros: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if self.clip_gradient is not None: <NEW_LINE> <INDENT> mom[row] = (self.momentum*mom[row] - lr*wd*weight[row] - lr*mx.nd.clip(grad[row]*self.rescale_grad, -self.clip_gradient, self.clip_gradient)) <NEW_LINE> weight[row] += mom[row] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mom[row] = self.momentum*mom[row] - lr*wd*weight[row] - lr*self.rescale_grad*grad[row] <NEW_LINE> weight[row] += mom[row] | python reference implemenation of sgd | 62599051b57a9660fecd2f31 |
class Rectangle(BaseGeometry): <NEW_LINE> <INDENT> def __init__(self, width, height): <NEW_LINE> <INDENT> self.__width = width <NEW_LINE> self.__height = height <NEW_LINE> self.integer_validator('width', width) <NEW_LINE> self.integer_validator('height', height) | rectangle class | 625990513c8af77a43b68998 |
class PublishArchiveIndex(PublishArchivePage, ArchiveIndexView): <NEW_LINE> <INDENT> def get_page_title(self): <NEW_LINE> <INDENT> return "%s, Archive - %s" % (self.picker.name, self.picker.commune.name) <NEW_LINE> <DEDENT> def get_template_names(self): <NEW_LINE> <INDENT> tpl_list = ( "{0:>s}/newsengine/archive/{1:>s}/{2:>s}/{3:>s}/index.html".format(self.commune.theme.keyname, self.realm.keyname, self.commune.keyname, self.picker.keyname), "{0:>s}/newsengine/archive/{1:>s}/{2:>s}/index.html".format(self.commune.theme.keyname, self.realm.keyname, self.commune.keyname), "{0:>s}/newsengine/archive/{1:>s}/index.html".format(self.commune.theme.keyname, self.realm.keyname), "{0:>s}/newsengine/archive/index.html".format(self.commune.theme.keyname), ) <NEW_LINE> return tpl_list | Archive index view for :model:`newsengine.Publish`, populated by a :model:`conduit.DynamicPicker` | 625990518e71fb1e983bcf7a |
class ClusterUpgradeDescriptionObject(Model): <NEW_LINE> <INDENT> _attribute_map = { 'config_version': {'key': 'ConfigVersion', 'type': 'str'}, 'code_version': {'key': 'CodeVersion', 'type': 'str'}, 'upgrade_kind': {'key': 'UpgradeKind', 'type': 'str'}, 'rolling_upgrade_mode': {'key': 'RollingUpgradeMode', 'type': 'str'}, 'upgrade_replica_set_check_timeout_in_seconds': {'key': 'UpgradeReplicaSetCheckTimeoutInSeconds', 'type': 'long'}, 'force_restart': {'key': 'ForceRestart', 'type': 'bool'}, 'enable_delta_health_evaluation': {'key': 'EnableDeltaHealthEvaluation', 'type': 'bool'}, 'monitoring_policy': {'key': 'MonitoringPolicy', 'type': 'MonitoringPolicyDescription'}, 'cluster_health_policy': {'key': 'ClusterHealthPolicy', 'type': 'ClusterHealthPolicy'}, 'cluster_upgrade_health_policy': {'key': 'ClusterUpgradeHealthPolicy', 'type': 'ClusterUpgradeHealthPolicyObject'}, 'application_health_policy_map': {'key': 'ApplicationHealthPolicyMap', 'type': '[ApplicationHealthPolicyMapItem]'}, } <NEW_LINE> def __init__(self, config_version=None, code_version=None, upgrade_kind="Rolling", rolling_upgrade_mode="UnmonitoredAuto", upgrade_replica_set_check_timeout_in_seconds=None, force_restart=None, enable_delta_health_evaluation=None, monitoring_policy=None, cluster_health_policy=None, cluster_upgrade_health_policy=None, application_health_policy_map=None): <NEW_LINE> <INDENT> self.config_version = config_version <NEW_LINE> self.code_version = code_version <NEW_LINE> self.upgrade_kind = upgrade_kind <NEW_LINE> self.rolling_upgrade_mode = rolling_upgrade_mode <NEW_LINE> self.upgrade_replica_set_check_timeout_in_seconds = upgrade_replica_set_check_timeout_in_seconds <NEW_LINE> self.force_restart = force_restart <NEW_LINE> self.enable_delta_health_evaluation = enable_delta_health_evaluation <NEW_LINE> self.monitoring_policy = monitoring_policy <NEW_LINE> self.cluster_health_policy = cluster_health_policy <NEW_LINE> self.cluster_upgrade_health_policy = cluster_upgrade_health_policy <NEW_LINE> self.application_health_policy_map = application_health_policy_map | Represents a ServiceFabric cluster upgrade.
:param config_version:
:type config_version: str
:param code_version:
:type code_version: str
:param upgrade_kind: Possible values include: 'Invalid', 'Rolling'.
Default value: "Rolling" .
:type upgrade_kind: str or :class:`enum <azure.servicefabric.models.enum>`
:param rolling_upgrade_mode: Possible values include: 'Invalid',
'UnmonitoredAuto', 'UnmonitoredManual', 'Monitored'. Default value:
"UnmonitoredAuto" .
:type rolling_upgrade_mode: str or :class:`enum
<azure.servicefabric.models.enum>`
:param upgrade_replica_set_check_timeout_in_seconds:
:type upgrade_replica_set_check_timeout_in_seconds: long
:param force_restart:
:type force_restart: bool
:param enable_delta_health_evaluation:
:type enable_delta_health_evaluation: bool
:param monitoring_policy:
:type monitoring_policy: :class:`MonitoringPolicyDescription
<azure.servicefabric.models.MonitoringPolicyDescription>`
:param cluster_health_policy:
:type cluster_health_policy: :class:`ClusterHealthPolicy
<azure.servicefabric.models.ClusterHealthPolicy>`
:param cluster_upgrade_health_policy:
:type cluster_upgrade_health_policy:
:class:`ClusterUpgradeHealthPolicyObject
<azure.servicefabric.models.ClusterUpgradeHealthPolicyObject>`
:param application_health_policy_map:
:type application_health_policy_map: list of
:class:`ApplicationHealthPolicyMapItem
<azure.servicefabric.models.ApplicationHealthPolicyMapItem>` | 625990513cc13d1c6d466bee |
class Operation(models.Model): <NEW_LINE> <INDENT> operation_name = models.CharField(max_length=128) <NEW_LINE> operation_description = models.TextField(max_length=256, null=True, blank=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.operation_name | Catalogo de operaciones
Registro de las diferentes acciones que pueden hacer sobre un objeto
(view, create, delete, update, otros) | 62599051097d151d1a2c2526 |
class _DiskImage(object): <NEW_LINE> <INDENT> tmp_prefix = 'openstack-disk-mount-tmp' <NEW_LINE> def __init__(self, image, partition=None, mount_dir=None): <NEW_LINE> <INDENT> self.partition = partition <NEW_LINE> self.mount_dir = mount_dir <NEW_LINE> self.image = image <NEW_LINE> self._mkdir = False <NEW_LINE> self._mounter = None <NEW_LINE> self._errors = [] <NEW_LINE> if mount_dir: <NEW_LINE> <INDENT> device = self._device_for_path(mount_dir) <NEW_LINE> if device: <NEW_LINE> <INDENT> self._reset(device) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def _device_for_path(path): <NEW_LINE> <INDENT> device = None <NEW_LINE> path = os.path.realpath(path) <NEW_LINE> with open("/proc/mounts", 'r') as ifp: <NEW_LINE> <INDENT> for line in ifp: <NEW_LINE> <INDENT> fields = line.split() <NEW_LINE> if fields[1] == path: <NEW_LINE> <INDENT> device = fields[0] <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return device <NEW_LINE> <DEDENT> def _reset(self, device): <NEW_LINE> <INDENT> self._mounter = mount.Mount.instance_for_device(self.image, self.mount_dir, self.partition, device) <NEW_LINE> mount_name = os.path.basename(self.mount_dir or '') <NEW_LINE> self._mkdir = mount_name.startswith(self.tmp_prefix) <NEW_LINE> <DEDENT> @property <NEW_LINE> def errors(self): <NEW_LINE> <INDENT> return '\n--\n'.join([''] + self._errors) <NEW_LINE> <DEDENT> def mount(self): <NEW_LINE> <INDENT> if self._mounter: <NEW_LINE> <INDENT> raise exception.NovaException(_('image already mounted')) <NEW_LINE> <DEDENT> if not self.mount_dir: <NEW_LINE> <INDENT> self.mount_dir = tempfile.mkdtemp(prefix=self.tmp_prefix) <NEW_LINE> self._mkdir = True <NEW_LINE> <DEDENT> mounter = mount.Mount.instance_for_format(self.image, self.mount_dir, self.partition) <NEW_LINE> if mounter.do_mount(): <NEW_LINE> <INDENT> self._mounter = mounter <NEW_LINE> return self._mounter.device <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> LOG.debug(mounter.error) <NEW_LINE> self._errors.append(mounter.error) <NEW_LINE> return None <NEW_LINE> <DEDENT> <DEDENT> def umount(self): <NEW_LINE> <INDENT> if self._mounter: <NEW_LINE> <INDENT> self._mounter.do_umount() <NEW_LINE> self._mounter = None <NEW_LINE> <DEDENT> <DEDENT> def teardown(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self._mounter: <NEW_LINE> <INDENT> self._mounter.do_teardown() <NEW_LINE> self._mounter = None <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> if self._mkdir: <NEW_LINE> <INDENT> os.rmdir(self.mount_dir) | Provide operations on a disk image file. | 6259905173bcbd0ca4bcb73f |
class AttributeAPIView(APIView): <NEW_LINE> <INDENT> model = None <NEW_LINE> serializer = None <NEW_LINE> def get(self, request, pk, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> instance = self.model.objects.get(id=pk) <NEW_LINE> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> return Response(status=status.HTTP_404_NOT_FOUND) <NEW_LINE> <DEDENT> serializer = self.serializer(instance) <NEW_LINE> return Response( serializer.data, status=status.HTTP_200_OK ) | Базовый класс vie для отображения атрибута по id, обновления и удаления записии
Для работы необходимо определить не абстрактный класс атрибута и его сериализатор | 62599051d99f1b3c44d06b50 |
class TestPubSubPubSubSubcommands(object): <NEW_LINE> <INDENT> @skip_if_redis_py_version_lt('2.10.6') <NEW_LINE> def test_pubsub_channels(self, r): <NEW_LINE> <INDENT> r.pubsub(ignore_subscribe_messages=True).subscribe('foo', 'bar', 'baz', 'quux') <NEW_LINE> channels = sorted(r.pubsub_channels()) <NEW_LINE> assert channels == [b('bar'), b('baz'), b('foo'), b('quux')] <NEW_LINE> <DEDENT> @skip_if_redis_py_version_lt('2.10.6') <NEW_LINE> def test_pubsub_numsub(self, r): <NEW_LINE> <INDENT> r.pubsub(ignore_subscribe_messages=True).subscribe('foo', 'bar', 'baz') <NEW_LINE> r.pubsub(ignore_subscribe_messages=True).subscribe('bar', 'baz') <NEW_LINE> r.pubsub(ignore_subscribe_messages=True).subscribe('baz') <NEW_LINE> channels = [(b('bar'), 2), (b('baz'), 3), (b('foo'), 1)] <NEW_LINE> assert channels == sorted(r.pubsub_numsub('foo', 'bar', 'baz')) <NEW_LINE> <DEDENT> @skip_if_redis_py_version_lt('2.10.6') <NEW_LINE> def test_pubsub_numpat(self, r): <NEW_LINE> <INDENT> r.pubsub(ignore_subscribe_messages=True).psubscribe('*oo', '*ar', 'b*z') <NEW_LINE> assert r.pubsub_numpat() == 3 | Test Pub/Sub subcommands of PUBSUB
@see https://redis.io/commands/pubsub | 62599051a219f33f346c7cb6 |
class ComprehensiveTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.pf = NavTrajectoryOpt() <NEW_LINE> self.dt = 0.005 <NEW_LINE> self.ins = SimpleINSComputer() <NEW_LINE> self.ins.dt = self.dt <NEW_LINE> init_state = self.pf.init_state() <NEW_LINE> self.ins.set_state(init_state) <NEW_LINE> self.time = np.arange(0., 1000., self.dt) | Test each method in SimpleINSComputer. | 62599051009cb60464d029ef |
class ModerationTranslationTaskEditCreateView(UpdateAPIView): <NEW_LINE> <INDENT> permission_classes = [IsAdminUser] <NEW_LINE> lookup_field = "id" <NEW_LINE> queryset = TranslationTask.objects.all() <NEW_LINE> serializer_class = TranslationTaskWithDataSerializer <NEW_LINE> def update(self, request, id=None, *args, **kwargs): <NEW_LINE> <INDENT> translation_task = get_object_or_404(TranslationTask, pk=id) <NEW_LINE> serializer = self.get_serializer(translation_task) <NEW_LINE> if translation_task.status == "closed": <NEW_LINE> <INDENT> return Response(None, status=status.HTTP_404_NOT_FOUND) <NEW_LINE> <DEDENT> return edit_create_task(request, id, translation_task, serializer) | Update TranslationTask view for Moderator | 62599051596a897236129009 |
class IMAPConnection: <NEW_LINE> <INDENT> def __init__(self, host, port, enc): <NEW_LINE> <INDENT> self.conn = imaplib.IMAP4_SSL(host, port) <NEW_LINE> self.enc = enc <NEW_LINE> self.mailbox = "INBOX" <NEW_LINE> self.uid_cache = {} <NEW_LINE> <DEDENT> def login(self, user, passwd): <NEW_LINE> <INDENT> self.conn.login(user, passwd) <NEW_LINE> <DEDENT> def logout(self): <NEW_LINE> <INDENT> self.conn.logout() <NEW_LINE> <DEDENT> def select(self, mailbox): <NEW_LINE> <INDENT> results = self.conn.select(mailbox) <NEW_LINE> if results[0] != "OK": <NEW_LINE> <INDENT> raise Exception() <NEW_LINE> <DEDENT> self.mailbox = mailbox <NEW_LINE> <DEDENT> def get_message(self, uid): <NEW_LINE> <INDENT> if not uid: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> params = self.conn.uid("FETCH", uid, "(BODY[1])") <NEW_LINE> if not params[1]: <NEW_LINE> <INDENT> for subject, s_uid in self.uid_cache.items(): <NEW_LINE> <INDENT> if s_uid == uid: <NEW_LINE> <INDENT> self.uid_cache.pop(subject) <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> data = params[1][0][1] <NEW_LINE> dec_data = self.enc.decrypt_message(data) <NEW_LINE> return dec_data <NEW_LINE> <DEDENT> def put_message(self, subject, data): <NEW_LINE> <INDENT> if subject in self.uid_cache: <NEW_LINE> <INDENT> self.uid_cache.pop(subject) <NEW_LINE> <DEDENT> enc_data = self.enc.encrypt_message(data) <NEW_LINE> msg = email.mime.text.MIMEText(enc_data) <NEW_LINE> msg['Subject'] = subject <NEW_LINE> results = self.conn.append(self.mailbox, "(\\Seen \\Draft)", time.time(), msg.as_string()) <NEW_LINE> info = results[1][0] <NEW_LINE> match = re.search("APPENDUID [0-9]+ ([0-9]+)", info, re.I) <NEW_LINE> if match: <NEW_LINE> <INDENT> new_uid = match.group(1) <NEW_LINE> self.uid_cache[subject] = new_uid <NEW_LINE> <DEDENT> <DEDENT> def delete_message(self, uid): <NEW_LINE> <INDENT> self.conn.uid("STORE", uid, "+FLAGS", "\\Deleted") <NEW_LINE> for subject, s_uid in self.uid_cache.items(): <NEW_LINE> <INDENT> if s_uid == uid: <NEW_LINE> <INDENT> self.uid_cache.pop(subject) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def search_by_subject(self, subject): <NEW_LINE> <INDENT> results = self.conn.uid("SEARCH", "SUBJECT", "\"%s\"" % subject) <NEW_LINE> if not results[1]: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> uids = results[1][0].split(" ") <NEW_LINE> if len(uids) == 1 and uids[0] == '': <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return uids <NEW_LINE> <DEDENT> def get_uid_by_subject(self, subject): <NEW_LINE> <INDENT> if subject in self.uid_cache: <NEW_LINE> <INDENT> return self.uid_cache[subject] <NEW_LINE> <DEDENT> results = self.search_by_subject(subject) <NEW_LINE> if not results: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> self.uid_cache[subject] = results[-1] <NEW_LINE> return results[-1] | Class that manages a connection to an IMAP server
| 6259905123e79379d538d9ac |
class Reason(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): <NEW_LINE> <INDENT> ACCOUNT_NAME_INVALID = "AccountNameInvalid" <NEW_LINE> ALREADY_EXISTS = "AlreadyExists" | The reason that a vault name could not be used. The Reason element is only returned if
NameAvailable is false. | 6259905176d4e153a661dcd3 |
class ToolTipEventFilter(QtCore.QObject): <NEW_LINE> <INDENT> codes = None <NEW_LINE> code_text = None <NEW_LINE> annotations = None <NEW_LINE> def set_codes_and_annotations(self, code_text, codes, annotations): <NEW_LINE> <INDENT> self.code_text = code_text <NEW_LINE> self.codes = codes <NEW_LINE> self.annotations = annotations <NEW_LINE> for item in self.code_text: <NEW_LINE> <INDENT> for c in self.codes: <NEW_LINE> <INDENT> if item['cid'] == c['cid']: <NEW_LINE> <INDENT> item['name'] = c['name'] <NEW_LINE> item['color'] = c['color'] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def eventFilter(self, receiver, event): <NEW_LINE> <INDENT> if event.type() == QtCore.QEvent.ToolTip: <NEW_LINE> <INDENT> help_event = QHelpEvent(event) <NEW_LINE> cursor = receiver.cursorForPosition(help_event.pos()) <NEW_LINE> pos = cursor.position() <NEW_LINE> receiver.setToolTip("") <NEW_LINE> txt = "" <NEW_LINE> multiple_msg = '<p style="color:#f89407">' + _("Press O to cycle overlapping codes") + "</p>" <NEW_LINE> multiple = 0 <NEW_LINE> if self.code_text is None: <NEW_LINE> <INDENT> return super(ToolTipEventFilter, self).eventFilter(receiver, event) <NEW_LINE> <DEDENT> for item in self.code_text: <NEW_LINE> <INDENT> if item['pos0'] <= pos and item['pos1'] >= pos: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> txt += '<p style="background-color:' + item['color'] <NEW_LINE> txt += '; color:' + TextColor(item['color']).recommendation + '">' + item['name'] <NEW_LINE> if item['avid'] is not None: <NEW_LINE> <INDENT> txt += " [" + msecs_to_hours_mins_secs(item['av_pos0']) <NEW_LINE> txt += " - " + msecs_to_hours_mins_secs(item['av_pos1']) + "]" <NEW_LINE> <DEDENT> if item['memo'] is not None and item['memo'] != "": <NEW_LINE> <INDENT> txt += "<br /><em>" + _("Memo: ") + item['memo'] + "</em>" <NEW_LINE> <DEDENT> if item['important'] == 1: <NEW_LINE> <INDENT> txt += "<br /><em>IMPORTANT</em>" <NEW_LINE> <DEDENT> txt += "</p>" <NEW_LINE> multiple += 1 <NEW_LINE> <DEDENT> except KeyError as e_: <NEW_LINE> <INDENT> msg_ = "Codes ToolTipEventFilter " + str(e_) + ". Possible key error: " <NEW_LINE> msg_ += str(item) + "\n" + str(self.code_text) <NEW_LINE> logger.error(msg_) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if multiple > 1: <NEW_LINE> <INDENT> txt = multiple_msg + txt <NEW_LINE> <DEDENT> for item in self.annotations: <NEW_LINE> <INDENT> if item['pos0'] <= pos and item['pos1'] >= pos: <NEW_LINE> <INDENT> txt += "<p>" + _("ANNOTATED") + "</p>" <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if txt != "": <NEW_LINE> <INDENT> receiver.setToolTip(txt) <NEW_LINE> <DEDENT> <DEDENT> return super(ToolTipEventFilter, self).eventFilter(receiver, event) | Used to add a dynamic tooltip for the textEdit.
The tool top text is changed according to its position in the text.
If over a coded section the codename is displayed in the tooltip.
Need to add av time segments to the code_text where relevant. | 625990512ae34c7f260ac59a |
class Restaurant(): <NEW_LINE> <INDENT> def __init__(self, restaurant_name, cuisine_type): <NEW_LINE> <INDENT> self.restaurant_name = restaurant_name <NEW_LINE> self.cuisine_type = cuisine_type <NEW_LINE> self.number_served = 0 <NEW_LINE> <DEDENT> def describe_restaurant(self): <NEW_LINE> <INDENT> print(self.restaurant_name.title() + " serves delicious " + self.cuisine_type + "!") <NEW_LINE> <DEDENT> def open_restaurant(self): <NEW_LINE> <INDENT> print(self.restaurant_name.title() + " is open for business!") <NEW_LINE> <DEDENT> def set_number_served(self): <NEW_LINE> <INDENT> print(self.restaurant_name.title() + " has served " + str(self.number_served) + " plus customers!") <NEW_LINE> <DEDENT> def increment_number_served(self, customers): <NEW_LINE> <INDENT> self.number_served += customers | class to define attributes for restaurant instances and indicate if they're open or not | 62599051462c4b4f79dbceb6 |
class Sentiment2Vec(X2Vec): <NEW_LINE> <INDENT> POSITIVE_SENTIMENT = "POSITIVE" <NEW_LINE> NEUTRAL_SENTIMENT = "NEUTRAL" <NEW_LINE> NEGATIVE_SENTIMENT = "NEGATIVE" <NEW_LINE> NEUTRAL_MARGIN = 0.15 <NEW_LINE> @staticmethod <NEW_LINE> def _get_sentence_tokens(sentence): <NEW_LINE> <INDENT> sentiment = Sentiment2Vec.NEUTRAL_SENTIMENT <NEW_LINE> polarity = TextBlob(sentence).sentiment.polarity <NEW_LINE> if polarity >= Sentiment2Vec.NEUTRAL_MARGIN: <NEW_LINE> <INDENT> sentiment = Sentiment2Vec.POSITIVE_SENTIMENT <NEW_LINE> <DEDENT> elif polarity <= -Sentiment2Vec.NEUTRAL_MARGIN: <NEW_LINE> <INDENT> sentiment = Sentiment2Vec.NEGATIVE_SENTIMENT <NEW_LINE> <DEDENT> return [(word, sentiment) for word in sentence.split()] <NEW_LINE> <DEDENT> def tokenize_corpus(self, corpus, tokenize=True): <NEW_LINE> <INDENT> corpus = [' '.join(sentence) for sentence in corpus] <NEW_LINE> if not tokenize: <NEW_LINE> <INDENT> return corpus <NEW_LINE> <DEDENT> print('Starting to tag corpus') <NEW_LINE> corpus_tags = [Sentiment2Vec._get_sentence_tokens(sentence) for sentence in corpus] <NEW_LINE> for sentence in corpus_tags: <NEW_LINE> <INDENT> for tag in sentence: <NEW_LINE> <INDENT> if tag[1] is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> cur_set = self.token_dict.get(tag[0], set()) <NEW_LINE> cur_set.add(tag[1]) <NEW_LINE> self.token_dict[tag[0]] = cur_set <NEW_LINE> <DEDENT> <DEDENT> tagged_corpus = [[word[0] + "_" + word[1] for word in sentence if word[1] is not None] for sentence in corpus_tags] <NEW_LINE> return tagged_corpus | A word embedding model that generates different embeddings for identical words based on their meaning. | 6259905199cbb53fe683239b |
class EncryptedMessage(object): <NEW_LINE> <INDENT> implements(smtp.IMessage) <NEW_LINE> log = Logger() <NEW_LINE> def __init__(self, user, outgoing_mail): <NEW_LINE> <INDENT> leap_assert_type(user, smtp.User) <NEW_LINE> self._user = user <NEW_LINE> self._lines = [] <NEW_LINE> self._outgoing = outgoing_mail <NEW_LINE> <DEDENT> def lineReceived(self, line): <NEW_LINE> <INDENT> self._lines.append(line) <NEW_LINE> <DEDENT> def eomReceived(self): <NEW_LINE> <INDENT> self.log.debug('Message data complete.') <NEW_LINE> self._lines.append('') <NEW_LINE> raw_mail = '\r\n'.join(self._lines) <NEW_LINE> return self._outgoing.send_message(raw_mail, self._user) <NEW_LINE> <DEDENT> def connectionLost(self): <NEW_LINE> <INDENT> self.log.error('Connection lost unexpectedly!') <NEW_LINE> emit_async(catalog.SMTP_CONNECTION_LOST, self._userid, self._user.dest.addrstr) <NEW_LINE> self._lines = [] | Receive plaintext from client, encrypt it and send message to a
recipient. | 6259905171ff763f4b5e8c5e |
class BaseModelAdmin(ModelAdmin): <NEW_LINE> <INDENT> form = AdminModelForm | Base class for ModelAdmins used across the site. | 6259905145492302aabfd98a |
class Forward(RelativeCompose): <NEW_LINE> <INDENT> SYNOPSIS = ('f', 'forward', 'message/forward', '[att] <messages>') <NEW_LINE> ORDER = ('Composing', 4) <NEW_LINE> HTTP_QUERY_VARS = { 'mid': 'metadata-ID', } <NEW_LINE> HTTP_POST_VARS = {} <NEW_LINE> def command(self): <NEW_LINE> <INDENT> session, config, idx = self.session, self.session.config, self._idx() <NEW_LINE> if self.args and self.args[0].lower().startswith('att'): <NEW_LINE> <INDENT> with_atts = self.args.pop(0) or True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> with_atts = False <NEW_LINE> <DEDENT> refs = [Email(idx, i) for i in self._choose_messages(self.args)] <NEW_LINE> if refs: <NEW_LINE> <INDENT> trees = [m.evaluate_pgp(m.get_message_tree(), decrypt=True) for m in refs] <NEW_LINE> ref_subjs = [t['headers_lc']['subject'] for t in trees] <NEW_LINE> msg_bodies = [] <NEW_LINE> msg_atts = [] <NEW_LINE> for t in trees: <NEW_LINE> <INDENT> text = '-------- Original Message --------\n' <NEW_LINE> for h in ('Date', 'Subject', 'From', 'To'): <NEW_LINE> <INDENT> v = t['headers_lc'].get(h.lower(), None) <NEW_LINE> if v: <NEW_LINE> <INDENT> text += '%s: %s\n' % (h, v) <NEW_LINE> <DEDENT> <DEDENT> text += '\n' <NEW_LINE> text += ''.join([p['data'] for p in t['text_parts'] if p['type'] in self._TEXT_PARTTYPES]) <NEW_LINE> msg_bodies.append(text) <NEW_LINE> if with_atts: <NEW_LINE> <INDENT> for att in t['attachments']: <NEW_LINE> <INDENT> if att['mimetype'] not in self._ATT_MIMETYPES: <NEW_LINE> <INDENT> msg_atts.append(att['part']) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> local_id, lmbox = config.open_local_mailbox(session) <NEW_LINE> email = Email.Create(idx, local_id, lmbox, msg_text='\n\n'.join(msg_bodies), msg_subject=('Fwd: %s' % ref_subjs[-1])) <NEW_LINE> if msg_atts: <NEW_LINE> <INDENT> msg = email.get_msg() <NEW_LINE> for att in msg_atts: <NEW_LINE> <INDENT> msg.attach(att) <NEW_LINE> <DEDENT> email.update_from_msg(msg) <NEW_LINE> <DEDENT> self._tag_blank([email]) <NEW_LINE> return self._edit_messages([email]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._error('No message found') | Create forwarding drafts of one or more messages | 62599051d53ae8145f919913 |
class ResourceTemplates(object): <NEW_LINE> <INDENT> template_packages = [__name__] <NEW_LINE> @classmethod <NEW_LINE> def templates(cls): <NEW_LINE> <INDENT> templates = [] <NEW_LINE> dirname = cls.get_template_dir() <NEW_LINE> if dirname is not None: <NEW_LINE> <INDENT> for pkg in cls.template_packages: <NEW_LINE> <INDENT> if not resource_isdir(pkg, dirname): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for template_file in resource_listdir(pkg, dirname): <NEW_LINE> <INDENT> if not template_file.endswith('.yaml'): <NEW_LINE> <INDENT> log.warning("Skipping unknown template file %s", template_file) <NEW_LINE> continue <NEW_LINE> <DEDENT> template_content = resource_string(pkg, os.path.join(dirname, template_file)) <NEW_LINE> template = yaml.safe_load(template_content) <NEW_LINE> template['template_id'] = template_file <NEW_LINE> templates.append(template) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return templates <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_template_dir(cls): <NEW_LINE> <INDENT> if getattr(cls, 'template_dir_name', None): <NEW_LINE> <INDENT> dirname = os.path.join('templates', cls.template_dir_name) <NEW_LINE> if not resource_isdir(__name__, dirname): <NEW_LINE> <INDENT> log.warning(u"No resource directory {dir} found when loading {cls_name} templates".format( dir=dirname, cls_name=cls.__name__, )) <NEW_LINE> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return dirname <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def get_template(cls, template_id): <NEW_LINE> <INDENT> dirname = cls.get_template_dir() <NEW_LINE> if dirname is not None: <NEW_LINE> <INDENT> path = os.path.join(dirname, template_id) <NEW_LINE> for pkg in cls.template_packages: <NEW_LINE> <INDENT> if resource_exists(pkg, path): <NEW_LINE> <INDENT> template_content = resource_string(pkg, path) <NEW_LINE> template = yaml.safe_load(template_content) <NEW_LINE> template['template_id'] = template_id <NEW_LINE> return template | Gets the templates associated w/ a containing cls. The cls must have a 'template_dir_name' attribute.
It finds the templates as directly in this directory under 'templates'. | 62599051b57a9660fecd2f33 |
class SphinxBaseFileInput(FileInput): <NEW_LINE> <INDENT> def __init__(self, app, env, *args, **kwds): <NEW_LINE> <INDENT> self.app = app <NEW_LINE> self.env = env <NEW_LINE> warnings.warn('%s is deprecated.' % self.__class__.__name__, RemovedInSphinx30Warning, stacklevel=2) <NEW_LINE> kwds['error_handler'] = 'sphinx' <NEW_LINE> super().__init__(*args, **kwds) <NEW_LINE> <DEDENT> def warn_and_replace(self, error): <NEW_LINE> <INDENT> return UnicodeDecodeErrorHandler(self.env.docname)(error) | A base class of SphinxFileInput.
It supports to replace unknown Unicode characters to '?'. | 62599051e76e3b2f99fd9eb3 |
class TestTextInstance(DeepQaTestCase): <NEW_LINE> <INDENT> def tearDown(self): <NEW_LINE> <INDENT> super(TestTextInstance, self).tearDown() <NEW_LINE> TextInstance.tokenizer = tokenizers['words'](Params({})) <NEW_LINE> <DEDENT> def test_words_tokenizes_the_sentence_correctly(self): <NEW_LINE> <INDENT> t = TextClassificationInstance("This is a sentence.", None) <NEW_LINE> assert t.words() == {'words': ['this', 'is', 'a', 'sentence', '.']} <NEW_LINE> TextInstance.tokenizer = tokenizers['characters'](Params({})) <NEW_LINE> assert t.words() == {'characters': ['T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 's', 'e', 'n', 't', 'e', 'n', 'c', 'e', '.']} <NEW_LINE> TextInstance.tokenizer = tokenizers['words and characters'](Params({})) <NEW_LINE> assert t.words() == {'words': ['this', 'is', 'a', 'sentence', '.'], 'characters': ['t', 'h', 'i', 's', 'i', 's', 'a', 's', 'e', 'n', 't', 'e', 'n', 'c', 'e', '.']} <NEW_LINE> <DEDENT> def test_to_indexed_instance_converts_correctly(self): <NEW_LINE> <INDENT> data_indexer = DataIndexer() <NEW_LINE> a_word_index = data_indexer.add_word_to_index("a", namespace='words') <NEW_LINE> sentence_index = data_indexer.add_word_to_index("sentence", namespace='words') <NEW_LINE> capital_a_index = data_indexer.add_word_to_index("A", namespace='characters') <NEW_LINE> space_index = data_indexer.add_word_to_index(" ", namespace='characters') <NEW_LINE> a_index = data_indexer.add_word_to_index("a", namespace='characters') <NEW_LINE> s_index = data_indexer.add_word_to_index("s", namespace='characters') <NEW_LINE> e_index = data_indexer.add_word_to_index("e", namespace='characters') <NEW_LINE> n_index = data_indexer.add_word_to_index("n", namespace='characters') <NEW_LINE> t_index = data_indexer.add_word_to_index("t", namespace='characters') <NEW_LINE> c_index = data_indexer.add_word_to_index("c", namespace='characters') <NEW_LINE> instance = TextClassificationInstance("A sentence", None).to_indexed_instance(data_indexer) <NEW_LINE> assert instance.word_indices == [a_word_index, sentence_index] <NEW_LINE> TextInstance.tokenizer = tokenizers['characters'](Params({})) <NEW_LINE> instance = TextClassificationInstance("A sentence", None).to_indexed_instance(data_indexer) <NEW_LINE> assert instance.word_indices == [capital_a_index, space_index, s_index, e_index, n_index, t_index, e_index, n_index, c_index, e_index] <NEW_LINE> TextInstance.tokenizer = tokenizers['words and characters'](Params({})) <NEW_LINE> instance = TextClassificationInstance("A sentence", None).to_indexed_instance(data_indexer) <NEW_LINE> assert instance.word_indices == [[a_word_index, a_index], [sentence_index, s_index, e_index, n_index, t_index, e_index, n_index, c_index, e_index]] | The point of this test class is to test the TextEncoder used by the TextInstance, to be sure
that we get what we expect when using character encoders, or word-and-character encoders. | 625990513539df3088ecd758 |
class TennisSingleEliminationTournamentView(): <NEW_LINE> <INDENT> def print_SET_header(self): <NEW_LINE> <INDENT> print("*** Tennis Single Elimination Tournament Example ***") <NEW_LINE> <DEDENT> def print_players(self, players): <NEW_LINE> <INDENT> print("* Players *") <NEW_LINE> for player in players: <NEW_LINE> <INDENT> assert isinstance(player, tm.TennisPlayer) <NEW_LINE> TennisPlayerView.print_player(player) <NEW_LINE> <DEDENT> <DEDENT> def print_round_header(self, info): <NEW_LINE> <INDENT> print("* {0} *".format(info)) <NEW_LINE> <DEDENT> def print_round_results(self, matches): <NEW_LINE> <INDENT> print("* Round results *") <NEW_LINE> for match in matches: <NEW_LINE> <INDENT> TennisMatchView.print_match(match) | View from MVC for TournamentTest in TennisTournament example. | 62599051dc8b845886d54a75 |
class Item(db.Model, CRUDMixin, MarshmallowMixin): <NEW_LINE> <INDENT> __schema__ = ItemSchema <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> unique = db.Column(db.String(255), unique=True, default=id_generator) <NEW_LINE> name = db.Column(db.String(255)) <NEW_LINE> description = db.Column(db.String(8**7)) <NEW_LINE> owners = db.relationship('Person', secondary="items_owners", lazy='dynamic', backref="items") <NEW_LINE> excerpts = db.relationship('Excerpt', secondary="items_excerpts", lazy='dynamic') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return(self.name) | Description.
:param int id: the database object identifier
:param str unique: alpha-numeric code for shorthand identifier
:param str name: what the item is called
:param int :
:param int :
:param int : | 6259905155399d3f056279d1 |
class MesosNetworkManager(object): <NEW_LINE> <INDENT> _mesos_network_manager = None <NEW_LINE> def __init__(self, args=None, mesos_api_connected=False, queue=None): <NEW_LINE> <INDENT> self.args = args <NEW_LINE> if queue: <NEW_LINE> <INDENT> self.queue = queue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.queue = Queue() <NEW_LINE> <DEDENT> self.logger = logger.MesosManagerLogger(args) <NEW_LINE> self.vnc = vnc_mesos.VncMesos(args=self.args, logger=self.logger, queue=self.queue) <NEW_LINE> self.mserver = mserver.MesosServer(args=self.args, logger=self.logger, queue=self.queue) <NEW_LINE> <DEDENT> def start_tasks(self): <NEW_LINE> <INDENT> self.logger.info("Starting all tasks.") <NEW_LINE> gevent.joinall([ gevent.spawn(self.vnc.vnc_process), gevent.spawn(self.mserver.start_server), ]) <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> for cls in DBBaseMM.get_obj_type_map().values(): <NEW_LINE> <INDENT> cls.reset() <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def get_instance(cls): <NEW_LINE> <INDENT> return MesosNetworkManager._mesos_network_manager <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def destroy_instance(cls): <NEW_LINE> <INDENT> inst = cls.get_instance() <NEW_LINE> if inst is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> inst.vnc = None <NEW_LINE> inst.q = None <NEW_LINE> MesosNetworkManager._mesos_network_manager = None | Starts all background process | 62599051baa26c4b54d50762 |
class PriorityQueue(Queue): <NEW_LINE> <INDENT> def __init__(self, order=min, f=lambda x: x): <NEW_LINE> <INDENT> update(self, A=[], order=order, f=f) <NEW_LINE> <DEDENT> def append(self, item): <NEW_LINE> <INDENT> bisect.insort(self.A, (self.f(item), item)) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.A) <NEW_LINE> <DEDENT> def pop(self): <NEW_LINE> <INDENT> if self.order == min: <NEW_LINE> <INDENT> return self.A.pop(0)[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.A.pop()[1] <NEW_LINE> <DEDENT> <DEDENT> def __contains__(self, item): <NEW_LINE> <INDENT> return some(lambda x: x[1] == item, self.A) <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> for _, item in self.A: <NEW_LINE> <INDENT> if item == key: <NEW_LINE> <INDENT> return item <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __delitem__(self, key): <NEW_LINE> <INDENT> for i, (value, item) in enumerate(self.A): <NEW_LINE> <INDENT> if item == key: <NEW_LINE> <INDENT> self.A.pop(i) <NEW_LINE> return | A queue in which the minimum (or maximum) element (as determined by f and
order) is returned first. If order is min, the item with minimum f(x) is
returned first; if order is max, then it is the item with maximum f(x).
Also supports dict-like lookup. | 62599051f7d966606f749311 |
class MultiLineLabel(pg.sprite.Sprite): <NEW_LINE> <INDENT> def __init__(self, path, size, text, color, rect_attr, bg=None, char_limit=42, align="left", vert_space=0): <NEW_LINE> <INDENT> attr = {"center": (0, 0)} <NEW_LINE> lines = wrap_text(text, char_limit) <NEW_LINE> labels = [Label(path, size, line, color, attr, bg) for line in lines] <NEW_LINE> width = max([label.rect.width for label in labels]) <NEW_LINE> spacer = vert_space*(len(lines)-1) <NEW_LINE> height = sum([label.rect.height for label in labels])+spacer <NEW_LINE> self.image = pg.Surface((width, height)).convert() <NEW_LINE> self.image.set_colorkey(pg.Color("black")) <NEW_LINE> self.image.fill(pg.Color("black")) <NEW_LINE> self.rect = self.image.get_rect(**rect_attr) <NEW_LINE> aligns = {"left" : {"left": 0}, "center": {"centerx": self.rect.width//2}, "right" : {"right": self.rect.width}} <NEW_LINE> y = 0 <NEW_LINE> for label in labels: <NEW_LINE> <INDENT> label.rect = label.image.get_rect(**aligns[align]) <NEW_LINE> label.rect.top = y <NEW_LINE> label.draw(self.image) <NEW_LINE> y += label.rect.height+vert_space <NEW_LINE> <DEDENT> <DEDENT> def draw(self, surface): <NEW_LINE> <INDENT> surface.blit(self.image, self.rect) | Create a single surface with multiple lines of text rendered on it. | 62599051009cb60464d029f1 |
class AttachmentTile(PersistentTile): <NEW_LINE> <INDENT> def __call__(self): <NEW_LINE> <INDENT> self.update() <NEW_LINE> return self.index() <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def file_size(self, file_): <NEW_LINE> <INDENT> if INamed.providedBy(file_): <NEW_LINE> <INDENT> return file_.getSize() / 1024 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> <DEDENT> def get_icon_for(self, file_): <NEW_LINE> <INDENT> mtr = getToolByName(self.context, "mimetypes_registry", None) <NEW_LINE> if mtr is None: <NEW_LINE> <INDENT> return self.context.getIcon() <NEW_LINE> <DEDENT> lookup = mtr.lookup(file_.contentType) <NEW_LINE> if lookup: <NEW_LINE> <INDENT> mti = lookup[0] <NEW_LINE> try: <NEW_LINE> <INDENT> self.context.restrictedTraverse(mti.icon_path) <NEW_LINE> return mti.icon_path <NEW_LINE> <DEDENT> except (NotFound, KeyError, AttributeError): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return self.context.getIcon() <NEW_LINE> <DEDENT> def lookupMime(self, name): <NEW_LINE> <INDENT> mtr = getToolByName(self.context, "mimetypes_registry", None) <NEW_LINE> if mtr is None: <NEW_LINE> <INDENT> return name <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> mimetypes = mtr.lookup(name) <NEW_LINE> <DEDENT> except MimeTypeException: <NEW_LINE> <INDENT> mimetypes = () <NEW_LINE> <DEDENT> if len(mimetypes): <NEW_LINE> <INDENT> return mimetypes[0].name() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return name | Attachment tile.
This is a persistent tile which stores a file and optionally link
text. When rendered, the tile will output an <a /> tag like::
<a href="http://.../@@plone.app.standardtiles.attachment/tile-id/
@@download/filename.ext">Link text</a>
If the link text is not provided, the filename itself will be used.
The tile is a public traversal view, so it will stream the file data
if the correct filename (matching the uploaded filename), is given in
the traversal subpath (filename.ext in the example above). Note that the
``id`` of the tile is still required for the tile to be able to
access its persistent data. | 6259905176d4e153a661dcd4 |
class ExperienceProviding(server.Thing): <NEW_LINE> <INDENT> def delete_operation(self, op): <NEW_LINE> <INDENT> aggressor = self.get_prop_string("__aggressor") <NEW_LINE> xp_provided = self.get_prop_float("xp_provided") <NEW_LINE> if aggressor and xp_provided: <NEW_LINE> <INDENT> return server.OPERATION_IGNORED, Operation("set", Entity(aggressor, {"xp!append": xp_provided}), to=aggressor, from_=aggressor), Operation("imaginary", Entity(description="You gain {} xp.".format(xp_provided)), to=aggressor, from_=aggressor) <NEW_LINE> <DEDENT> return server.OPERATION_IGNORED <NEW_LINE> <DEDENT> def hit_operation(self, op): <NEW_LINE> <INDENT> arg = op[0] <NEW_LINE> if arg: <NEW_LINE> <INDENT> actor_id = arg.id <NEW_LINE> if actor_id: <NEW_LINE> <INDENT> return server.OPERATION_IGNORED, Operation("set", Entity(self.id, {"__aggressor": actor_id}), to=self.id) <NEW_LINE> <DEDENT> <DEDENT> return server.OPERATION_IGNORED | Attached to entities that will gift "xp" to their attackers when killed. | 62599051d53ae8145f919915 |
class EntryMixin: <NEW_LINE> <INDENT> def getIdAndTitle(self, value): <NEW_LINE> <INDENT> portal_directories = getToolByName(self, 'portal_directories') <NEW_LINE> dir = getattr(portal_directories, self.directory) <NEW_LINE> if not value: <NEW_LINE> <INDENT> id = None <NEW_LINE> title = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.entry_type == 'id': <NEW_LINE> <INDENT> id = value <NEW_LINE> try: <NEW_LINE> <INDENT> title = dir.getEntry(id, default=None)[dir.title_field] <NEW_LINE> <DEDENT> except (IndexError, ValueError, KeyError, TypeError, AttributeError): <NEW_LINE> <INDENT> title = None <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> entry = dir.getEntryByDN(value) <NEW_LINE> <DEDENT> except (IndexError, ValueError, KeyError): <NEW_LINE> <INDENT> id = None <NEW_LINE> title = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> id = entry[dir.id_field] <NEW_LINE> title = entry[dir.title_field] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return (id, title) <NEW_LINE> <DEDENT> def getTagForValue(self, value): <NEW_LINE> <INDENT> id, title = self.getIdAndTitle(value) <NEW_LINE> if id is None or title is None: <NEW_LINE> <INDENT> return renderHtmlTag('span', contents=escape('? (%s)' % value)) <NEW_LINE> <DEDENT> portal_url = getToolByName(self, 'portal_url')() <NEW_LINE> if self.directory_view: <NEW_LINE> <INDENT> directory = self.directory_view <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> directory = self.directory <NEW_LINE> <DEDENT> href = '%s/%s?%s' % (portal_url, self.skin_name, urlencode({'dirname': directory, 'id': id,})) <NEW_LINE> return renderHtmlTag('a', href=href, contents=escape(title)) | Mixin class that knows how to access id and title from
and entry, even if it's LDAP keyed by dn. | 62599051287bf620b62730a2 |
class CharactersLimitExceeded(TranslatorError): <NEW_LINE> <INDENT> def __init__(self, cause, message='Characters Limit Exceeded'): <NEW_LINE> <INDENT> self.cause = cause <NEW_LINE> self.message = message <NEW_LINE> super().__init__(self.cause, self.message) | Exception raised when the char limit has been exceeded. | 6259905163d6d428bbee3c85 |
class ESRowIterator(object): <NEW_LINE> <INDENT> def __init__(self, resultset, field_names): <NEW_LINE> <INDENT> self.resultset = resultset <NEW_LINE> self.field_names = field_names <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> record = self.resultset.__getitem__(index) <NEW_LINE> array = [] <NEW_LINE> for field in self.field_names: <NEW_LINE> <INDENT> value = record <NEW_LINE> for key in field.split('.'): <NEW_LINE> <INDENT> if key in value: <NEW_LINE> <INDENT> value = value[key] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> array.append(value) <NEW_LINE> <DEDENT> return tuple(array) | Wrapper for ElasticSearch ResultSet to be able to return rows() as tuples and records() as
dictionaries | 62599051b830903b9686eed7 |
class ProjectAdmins(APIView): <NEW_LINE> <INDENT> @handle_exceptions_for_ajax <NEW_LINE> def post(self, request, project_id): <NEW_LINE> <INDENT> project = Project.objects.as_admin(request.user, project_id) <NEW_LINE> if project.islocked: <NEW_LINE> <INDENT> return Response( {'error': 'The project is locked. New administrators cannot ' + 'be added.'}, status=status.HTTP_400_BAD_REQUEST ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user = User.objects.get(pk=request.data.get('user_id')) <NEW_LINE> <DEDENT> except User.DoesNotExist: <NEW_LINE> <INDENT> return Response( {'error': 'The user you are trying to add to the group ' + 'of administrators does not exist.'}, status=status.HTTP_404_NOT_FOUND ) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> Admins.objects.create(project=project, user=user) <NEW_LINE> <DEDENT> except IntegrityError: <NEW_LINE> <INDENT> return Response( {'error': 'The user is already an administrator of this ' + 'project.'}, status=status.HTTP_400_BAD_REQUEST ) <NEW_LINE> <DEDENT> refreshed_admins = Project.objects.get(pk=project_id).admins.all() <NEW_LINE> serializer = UserSerializer(refreshed_admins, many=True) <NEW_LINE> return Response( {'users': serializer.data}, status=status.HTTP_201_CREATED ) | API endpoints for all project administrators.
/ajax/projects/:project_id/admins | 625990518e71fb1e983bcf7e |
class CircularWindow(SlidingWindow): <NEW_LINE> <INDENT> def _customize(self): <NEW_LINE> <INDENT> self._indices_nan.extend(self._remove_corners(self.window_size)) <NEW_LINE> super()._customize() <NEW_LINE> <DEDENT> def _remove_corners(self, ny): <NEW_LINE> <INDENT> return [(0, 0), (0, ny - 1), (ny - 1, 0), (ny - 1, ny - 1)] | Modify the functionality of the SlidingWindow iterator extending the
customization to include a circular window, that is adding corners
element of window to be set as nan.
Examples
--------
Using iter and next (not usual)
>>> import numpy as np
>>> from sliding_window import CircularWindow
>>> grid = np.arange(25).reshape((5, 5))
>>> grid
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
>>> sliding = CircularWindow(grid, window_size=3)
>>> i = iter(sliding)
>>> next(i)
(array([[nan, 1., nan],
[ 5., 6., 7.],
[nan, 11., nan]], dtype=float32), (1, 1))
>>> next(i)
(array([[nan, 2., nan],
[ 6., 7., 8.],
[nan, 12., nan]], dtype=float32), (1, 2))
>>> next(i)
(array([[nan, 3., nan],
[ 7., 8., 9.],
[nan, 13., nan]], dtype=float32), (1, 3))
>>> next(i)
(array([[nan, 6., nan],
[10., 11., 12.],
[nan, 16., nan]], dtype=float32), (2, 1))
Example using "for, in"
>>> grid_2 = np.arange(12).reshape((3, 4))
>>> grid_2
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> sliding_2 = CircularWindow(grid_2, window_size=3)
>>> for window in sliding_2:
... print(window)
(array([[nan, 1., nan],
[ 4., 5., 6.],
[nan, 9., nan]], dtype=float32), (1, 1))
(array([[nan, 2., nan],
[ 5., 6., 7.],
[nan, 10., nan]], dtype=float32), (1, 2)) | 62599051435de62698e9d2b7 |
class Downder: <NEW_LINE> <INDENT> def __init__(self, heads=None, retries=3, proxies=None, delay=3, timeout=30): <NEW_LINE> <INDENT> self.throttle = Throttle(delay) <NEW_LINE> self.retries = retries <NEW_LINE> self.heads = heads <NEW_LINE> self.proxies = proxies <NEW_LINE> self.delay = delay <NEW_LINE> self.timeout = timeout <NEW_LINE> <DEDENT> def download(self, url, is_json=False): <NEW_LINE> <INDENT> print('下载的页面:', url) <NEW_LINE> try: <NEW_LINE> <INDENT> self.throttle.wait(url) <NEW_LINE> response = requests.get( url, headers=self.heads, proxies=self.proxies, timeout=self.timeout) <NEW_LINE> if response.status_code == 200: <NEW_LINE> <INDENT> if is_json: <NEW_LINE> <INDENT> return response.json() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return response.content <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> except RequestException as e: <NEW_LINE> <INDENT> print(e.response) <NEW_LINE> html = '' <NEW_LINE> if hasattr(e.response, 'status_code'): <NEW_LINE> <INDENT> code = e.response.status_code <NEW_LINE> print('error code', code) <NEW_LINE> if self.retries > 0 and 500 <= code < 600: <NEW_LINE> <INDENT> html = self.download(url) <NEW_LINE> self.retries -= 1 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> code = None <NEW_LINE> <DEDENT> <DEDENT> return html <NEW_LINE> <DEDENT> def write_csv(self, filename, all_list): <NEW_LINE> <INDENT> with open(filename, 'w', newline='') as f: <NEW_LINE> <INDENT> writer = csv.writer(f) <NEW_LINE> fields = ('商品详情', '商品id', '商品价格', '好评率', '评价数') <NEW_LINE> writer.writerow(fields) <NEW_LINE> for row in all_list: <NEW_LINE> <INDENT> writer.writerow(row) | 下载类 | 6259905173bcbd0ca4bcb743 |
class SW_evap_from_surfacewater(flux_connection): <NEW_LINE> <INDENT> thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> _cmf_core.SW_evap_from_surfacewater_swiginit(self, _cmf_core.new_SW_evap_from_surfacewater(*args, **kwargs)) <NEW_LINE> <DEDENT> __swig_destroy__ = _cmf_core.delete_SW_evap_from_surfacewater | Connection for Shuttleworth-Wallace canopy interception evaporation.
C++ includes: ShuttleworthWallace.h | 62599051d99f1b3c44d06b54 |
class TestNewUpstreamVersion(Base): <NEW_LINE> <INDENT> expected_title = "anitya.project.version.update" <NEW_LINE> expected_subti = ('A new version of "2ping" has been detected: "2.1.1" ' 'in advance of "2.1.0", packaged as "2ping"') <NEW_LINE> expected_link = "https://release-monitoring.org/project/2/" <NEW_LINE> expected_icon = "https://apps.fedoraproject.org/packages/" + "images/icons/package_128x128.png" <NEW_LINE> expected_packages = set([ '2ping', ]) <NEW_LINE> expected_usernames = set(['anitya']) <NEW_LINE> expected_objects = set([ 'projects/2ping', ]) <NEW_LINE> msg = { "username": "fedmsg", "i": 1, "timestamp": 1412234961, "msg_id": "2014-f4dfc3e4-8909-45d7-b929-1862efb373cf", "crypto": "x509", "topic": "org.release-monitoring.prod.anitya.project.version.update", "msg": { "project": { "regex": None, "name": "2ping", "created_on": 1412174944.0, "version": "2.1.1", "version_url": "http://www.finnie.org/software/2ping/", "updated_on": 1412179539.0, "homepage": "http://www.finnie.org/software/2ping/", "id": 2, "backend": "custom" }, "message": { "versions": [ "2.1.1" ], "old_version": "2.1.0", "upstream_version": "2.1.1", "project": { "regex": None, "name": "2ping", "created_on": 1412174944.0, "version": "2.1.1", "version_url": "http://www.finnie.org/software/2ping/", "updated_on": 1412179539.0, "homepage": "http://www.finnie.org/software/2ping/", "id": 2, "backend": "custom" }, "agent": "anitya", "packages": [ { "package_name": "2ping", "distro": "Fedora" } ] }, "distro": None } } | The purpose of anitya is to monitor upstream projects and to
try and detect when they release new tarballs.
*These* messages are the ones that get published when a tarball is found
that is newer than the one last seen in the `anitya
<https://release-monitoring.org>`_ database. | 62599051498bea3a75a58fda |
class GoalID(metaclass=Metaclass): <NEW_LINE> <INDENT> __slots__ = [ '_stamp', '_id', ] <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> assert all(['_' + key in self.__slots__ for key in kwargs.keys()]), 'Invalid arguments passed to constructor: %r' % kwargs.keys() <NEW_LINE> from builtin_interfaces.msg import Time <NEW_LINE> self.stamp = kwargs.get('stamp', Time()) <NEW_LINE> self.id = kwargs.get('id', str()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> typename = self.__class__.__module__.split('.') <NEW_LINE> typename.pop() <NEW_LINE> typename.append(self.__class__.__name__) <NEW_LINE> args = [s[1:] + '=' + repr(getattr(self, s, None)) for s in self.__slots__] <NEW_LINE> return '%s(%s)' % ('.'.join(typename), ', '.join(args)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def stamp(self): <NEW_LINE> <INDENT> return self._stamp <NEW_LINE> <DEDENT> @stamp.setter <NEW_LINE> def stamp(self, value): <NEW_LINE> <INDENT> from builtin_interfaces.msg import Time <NEW_LINE> assert isinstance(value, Time), "The 'stamp' field must be a sub message of type 'Time'" <NEW_LINE> self._stamp = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def id(self): <NEW_LINE> <INDENT> return self._id <NEW_LINE> <DEDENT> @id.setter <NEW_LINE> def id(self, value): <NEW_LINE> <INDENT> assert isinstance(value, str), "The 'id' field must of type 'str'" <NEW_LINE> self._id = value | Message class 'GoalID'. | 6259905116aa5153ce4019a7 |
class UserProfile(AuditModel): <NEW_LINE> <INDENT> user = models.OneToOneField(User, on_delete=models.CASCADE) <NEW_LINE> phone_number = models.CharField(max_length=20, null=True, default=None) | Store additional information on users | 62599051b57a9660fecd2f36 |
class AutoBlogAction(SimpleItem): <NEW_LINE> <INDENT> implements(IAutoBlogAction, IRuleElementData) <NEW_LINE> enable_blogging = False <NEW_LINE> exclude_from_nav = False <NEW_LINE> enable_comments = False <NEW_LINE> element = 'collective.blogging.actions.AutoBlog' <NEW_LINE> @property <NEW_LINE> def summary(self): <NEW_LINE> <INDENT> return _(u"Enable auto-blogging") | The implementation of the action defined before | 62599051009cb60464d029f3 |
@implementer(IProtocolNegotiationFactory) <NEW_LINE> class ClientNegotiationFactory(ClientFactory): <NEW_LINE> <INDENT> def __init__(self, acceptableProtocols): <NEW_LINE> <INDENT> self._acceptableProtocols = acceptableProtocols <NEW_LINE> <DEDENT> def acceptableProtocols(self): <NEW_LINE> <INDENT> return self._acceptableProtocols | A L{ClientFactory} that has a set of acceptable protocols for NPN/ALPN
negotiation. | 625990518da39b475be046a0 |
class TestCaseBackendArchive(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.test_path = tempfile.mkdtemp(prefix='perceval_') <NEW_LINE> archive_path = os.path.join(self.test_path, 'myarchive') <NEW_LINE> self.archive = Archive.create(archive_path) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> shutil.rmtree(self.test_path) <NEW_LINE> <DEDENT> def _test_fetch_from_archive(self, **kwargs): <NEW_LINE> <INDENT> items = [items for items in self.backend.fetch(**kwargs)] <NEW_LINE> items_archived = [item for item in self.backend.fetch_from_archive()] <NEW_LINE> self.assertEqual(len(items), len(items_archived)) <NEW_LINE> for i in range(len(items)): <NEW_LINE> <INDENT> item = items[i] <NEW_LINE> archived_item = items_archived[i] <NEW_LINE> del item['timestamp'] <NEW_LINE> del archived_item['timestamp'] <NEW_LINE> self.assertEqual(item, archived_item) | Unit tests for Backend using the archive | 6259905129b78933be26ab1f |
class PayInvoiceAsk(ModelView): <NEW_LINE> <INDENT> __name__ = 'account.invoice.pay.ask' <NEW_LINE> type = fields.Selection([ ('writeoff', 'Write-Off'), ('partial', 'Partial Payment'), ], 'Type', required=True) <NEW_LINE> journal_writeoff = fields.Many2One('account.journal', 'Write-Off Journal', states={ 'invisible': Eval('type') != 'writeoff', 'required': Eval('type') == 'writeoff', }, depends=['type']) <NEW_LINE> account_writeoff = fields.Many2One('account.account', 'Write-Off Account', domain=[ ('kind', '!=', 'view'), ('company', '=', Eval('context', {}).get('company', 0)), ], states={ 'invisible': Eval('type') != 'writeoff', 'required': Eval('type') == 'writeoff', }, depends=['type']) <NEW_LINE> amount = fields.Numeric('Payment Amount', digits=(16, Eval('currency_digits', 2)), readonly=True, depends=['currency_digits']) <NEW_LINE> currency = fields.Many2One('currency.currency', 'Payment Currency', readonly=True) <NEW_LINE> currency_digits = fields.Integer('Payment Currency Digits', readonly=True) <NEW_LINE> amount_writeoff = fields.Numeric('Write-Off Amount', digits=(16, Eval('currency_digits_writeoff', 2)), readonly=True, depends=['currency_digits_writeoff', 'type'], states={ 'invisible': Eval('type') != 'writeoff', }) <NEW_LINE> currency_writeoff = fields.Many2One('currency.currency', 'Write-Off Currency', readonly=True, states={ 'invisible': Eval('type') != 'writeoff', }, depends=['type']) <NEW_LINE> currency_digits_writeoff = fields.Integer('Write-Off Currency Digits', required=True, readonly=True) <NEW_LINE> lines_to_pay = fields.Many2Many('account.move.line', None, None, 'Lines to Pay', readonly=True) <NEW_LINE> lines = fields.Many2Many('account.move.line', None, None, 'Lines', domain=[ ('id', 'in', Eval('lines_to_pay')), ('reconciliation', '=', None), ], states={ 'invisible': Eval('type') != 'writeoff', }, on_change=['lines', 'amount', 'currency', 'currency_writeoff', 'invoice'], depends=['lines_to_pay', 'type']) <NEW_LINE> payment_lines = fields.Many2Many('account.move.line', None, None, 'Payment Lines', readonly=True, states={ 'invisible': Eval('type') != 'writeoff', }, depends=['type']) <NEW_LINE> company = fields.Many2One('company.company', 'Company', readonly=True) <NEW_LINE> invoice = fields.Many2One('account.invoice', 'Invoice', readonly=True) <NEW_LINE> @staticmethod <NEW_LINE> def default_type(): <NEW_LINE> <INDENT> return 'partial' <NEW_LINE> <DEDENT> def on_change_lines(self): <NEW_LINE> <INDENT> Currency = Pool().get('currency.currency') <NEW_LINE> res = {} <NEW_LINE> with Transaction().set_context(date=self.invoice.currency_date): <NEW_LINE> <INDENT> amount = Currency.compute(self.currency, self.amount, self.currency_writeoff) <NEW_LINE> <DEDENT> res['amount_writeoff'] = Decimal('0.0') <NEW_LINE> for line in self.lines: <NEW_LINE> <INDENT> res['amount_writeoff'] += line.debit - line.credit <NEW_LINE> <DEDENT> if self.invoice.type in ('in_invoice', 'out_credit_note'): <NEW_LINE> <INDENT> res['amount_writeoff'] = - res['amount_writeoff'] - amount <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> res['amount_writeoff'] = res['amount_writeoff'] - amount <NEW_LINE> <DEDENT> return res | Pay Invoice | 625990513617ad0b5ee075fb |
class AccessResource(object): <NEW_LINE> <INDENT> __slots__ = ['idx', 'usr', 'token', '_remaining', 'reset_time', 'last_used', 'used_cnt', 'fail_cnt'] <NEW_LINE> def __init__(self, usr=None, token=None, remaining=None, reset_time=None, idx=0, *args, **kwargs): <NEW_LINE> <INDENT> self.idx = idx <NEW_LINE> self.usr = usr <NEW_LINE> self.token = token <NEW_LINE> self._remaining = remaining <NEW_LINE> self.reset_time = reset_time <NEW_LINE> self.last_used = idx <NEW_LINE> self.used_cnt = 0 <NEW_LINE> self.fail_cnt = 0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def remaining(self): <NEW_LINE> <INDENT> if self._remaining is None or self.reset_time is None: <NEW_LINE> <INDENT> return self._remaining <NEW_LINE> <DEDENT> if self.reset_time + 300 < time.time(): <NEW_LINE> <INDENT> self._remaining = None <NEW_LINE> <DEDENT> return self._remaining <NEW_LINE> <DEDENT> @remaining.setter <NEW_LINE> def remaining(self, val): <NEW_LINE> <INDENT> self._remaining = val <NEW_LINE> <DEDENT> def __cmp__(self, other): <NEW_LINE> <INDENT> me_rem = self.remaining <NEW_LINE> he_rem = other.remaining <NEW_LINE> if me_rem is None and he_rem is None: <NEW_LINE> <INDENT> return self.last_used - other.last_used <NEW_LINE> <DEDENT> elif me_rem is None: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> elif he_rem is None: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return he_rem - me_rem <NEW_LINE> <DEDENT> <DEDENT> def to_json(self): <NEW_LINE> <INDENT> js = collections.OrderedDict() <NEW_LINE> js['usr'] = self.usr <NEW_LINE> js['remaining'] = self.remaining <NEW_LINE> js['reset_time'] = self.reset_time <NEW_LINE> js['last_used'] = self.last_used <NEW_LINE> js['used_cnt'] = self.used_cnt <NEW_LINE> js['fail_cnt'] = self.fail_cnt <NEW_LINE> return js | Represents one access token | 62599051435de62698e9d2b8 |
class TestExperiment(GOLExperiment): <NEW_LINE> <INDENT> size = (100, 100, ) <NEW_LINE> seed = BigBang( pos=(32, 20), size=(10, 10), vals={ "state": RandInt(0, 1), } ) | Regular experiment for tests. | 625990511f037a2d8b9e52c8 |
class SpcComment(Comment): <NEW_LINE> <INDENT> rest_comment = models.TextField(_('rest_comment'), max_length=COMMENT_MAX_LENGTH, null = True) | Custom model for comments
`rest_comment` stores compiled ReST comments | 62599051cad5886f8bdc5adb |
class ImageDetectionServicer(object): <NEW_LINE> <INDENT> def ListAvailableDetectors(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 DetectImage(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 DetectMultipleImages(self, request_iterator, 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. | 6259905123849d37ff852578 |
class Module(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.required_mips = 0 <NEW_LINE> self.required_ram = 0 <NEW_LINE> self.required_storage = 0 <NEW_LINE> self.m_id = 0 <NEW_LINE> <DEDENT> def set_required_mips(self, required_mips): <NEW_LINE> <INDENT> self.required_mips = required_mips <NEW_LINE> <DEDENT> def get_required_mips(self): <NEW_LINE> <INDENT> return self.required_mips <NEW_LINE> <DEDENT> def set_required_ram(self, required_ram): <NEW_LINE> <INDENT> self.required_ram = required_ram <NEW_LINE> <DEDENT> def get_required_ram(self): <NEW_LINE> <INDENT> return self.required_ram <NEW_LINE> <DEDENT> def set_required_storage(self, required_storage): <NEW_LINE> <INDENT> self.required_storage = required_storage <NEW_LINE> <DEDENT> def get_required_storage(self): <NEW_LINE> <INDENT> return self.required_storage <NEW_LINE> <DEDENT> def set_m_id(self, m_id): <NEW_LINE> <INDENT> self.m_id = m_id <NEW_LINE> <DEDENT> def get_m_id(self): <NEW_LINE> <INDENT> return self.m_id | Each Application has modules in it.
This class describes, creates the modules and loads the data into them | 6259905107d97122c421815f |
class AppointmentSerializer(serializers.HyperlinkedModelSerializer): <NEW_LINE> <INDENT> url = serializers.HyperlinkedIdentityField(view_name='api:appointment-detail') <NEW_LINE> stylist = serializers.HyperlinkedRelatedField(view_name='api:stylist-detail', many=False, read_only=False, queryset=User.objects.filter(is_stylist='YES')) <NEW_LINE> customer = serializers.HyperlinkedIdentityField(view_name='api:customer-detail', many=False, read_only=True) <NEW_LINE> item_in_bill = ItemInBillSerializer(many=True, read_only=False) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Appointment <NEW_LINE> fields = ( 'url', 'title', 'location', 'start_date_time', 'end_date_time', 'stylist', 'customer', 'status', 'item_in_bill', ) <NEW_LINE> extra_kwargs = { 'status': {'read_only': True}, 'end_date_time': {'read_only': True}, 'title': {'read_only': True} } <NEW_LINE> <DEDENT> def create(self, validated_data): <NEW_LINE> <INDENT> item_in_bill = validated_data.pop('item_in_bill') <NEW_LINE> if len(item_in_bill) != 1: <NEW_LINE> <INDENT> return Response(status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> item_in_bill = item_in_bill.pop() <NEW_LINE> appointment = Appointment(**validated_data) <NEW_LINE> item_portfolio = item_in_bill.get('item_portfolio') <NEW_LINE> item_menu = item_in_bill.get('item_menu') <NEW_LINE> if item_portfolio: <NEW_LINE> <INDENT> haircut = PortfolioHaircut.objects.get(pk=int(item_portfolio.get('pk'))) <NEW_LINE> appointment.end_date_time = appointment.start_date_time + haircut.duration <NEW_LINE> appointment.title = haircut.name <NEW_LINE> appointment.save() <NEW_LINE> ItemInBill.objects.create(appointment=appointment, item_portfolio=haircut) <NEW_LINE> <DEDENT> elif item_menu: <NEW_LINE> <INDENT> menu = StylistMenu.objects.get(pk=int(item_menu.get('pk'))) <NEW_LINE> appointment.end_date_time = appointment.start_date_time + menu.duration <NEW_LINE> appointment.title = menu.name <NEW_LINE> appointment.save() <NEW_LINE> ItemInBill.objects.create(appointment=appointment, item_menu=menu) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Response(status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> return appointment | AppointmentSerializer (serializer for Appointment Model)
- **fields**::
:url: Url for a specific object
:location: Text field for the location
:date: Date Field
:stylist: SlugRelatedField (ensures that you can only select a stylist from the given options)
:customer: UserSerialzer(many=False, read_only=True) | 6259905191af0d3eaad3b2de |
class JSONHandler(tornado.web.RequestHandler): <NEW_LINE> <INDENT> def set_default_headers(self): <NEW_LINE> <INDENT> self.set_header('Content-Type', 'application/json') <NEW_LINE> <DEDENT> def write_json(self, data): <NEW_LINE> <INDENT> self.write(json.dumps(data, sort_keys=True, indent=4)) | Base Request Handler.
Every other handler should inherit this handler.
Assures the process of returning JSON to the clients. | 625990514428ac0f6e6599ee |
class Person: <NEW_LINE> <INDENT> def __init__(self, name, country='unknown', colour='undefined', age=0): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.country = country <NEW_LINE> self.colour = colour <NEW_LINE> self.age = age <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f"{self.name}, {self.country}, {self.colour}, {self.age}" <NEW_LINE> <DEDENT> def print(self): <NEW_LINE> <INDENT> print(f"Name: {self.name} Home Country: {self.country} Skin colour: {self.colour} Age: {self.age}") | describes different people | 625990516e29344779b01aff |
class MatchPartner(models.AbstractModel): <NEW_LINE> <INDENT> _inherit = "res.partner.match" <NEW_LINE> def match_after_match(self, partner, new_partner, infos, opt): <NEW_LINE> <INDENT> if partner.contact_type == "attached": <NEW_LINE> <INDENT> if partner.type == "email_alias": <NEW_LINE> <INDENT> partner = partner.contact_id <NEW_LINE> del infos["email"] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> partner.write({"active": True, "contact_id": False}) <NEW_LINE> <DEDENT> <DEDENT> return super().match_after_match(partner, new_partner, infos, opt) <NEW_LINE> <DEDENT> @job <NEW_LINE> @api.model <NEW_LINE> def match_update(self, partner, infos, options=None): <NEW_LINE> <INDENT> if "email" in infos: <NEW_LINE> <INDENT> all_emails = partner.other_contact_ids.mapped("email") <NEW_LINE> all_emails.append(partner.email) <NEW_LINE> if infos["email"] not in all_emails: <NEW_LINE> <INDENT> vals = { "contact_type": "attached", "type": "email_alias", "email": infos["email"], "contact_id": partner.id, } <NEW_LINE> self.env["res.partner"].sudo().create(vals) <NEW_LINE> del infos["email"] <NEW_LINE> <DEDENT> <DEDENT> return super().match_update(partner, infos, options) | Extend the matching so that all create partner must be checked by a human. | 6259905145492302aabfd98f |
class DreamhostProviderTests(TestCase, IntegrationTestsV2): <NEW_LINE> <INDENT> provider_name = "dreamhost" <NEW_LINE> domain = "lexicon-example.com" <NEW_LINE> def _filter_query_parameters(self): <NEW_LINE> <INDENT> return ["key"] <NEW_LINE> <DEDENT> @pytest.mark.skip(reason="can not set ttl when creating/updating records") <NEW_LINE> def test_provider_when_calling_list_records_after_setting_ttl(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def test_identifier(self): <NEW_LINE> <INDENT> dreamhost_record = { "type": "A", "record": "www.example.com", "value": "1.2.3.4", } <NEW_LINE> identifier = Provider._identifier(dreamhost_record) <NEW_LINE> dreamhost_record_from_id = Provider._id_to_dreamhost_record(identifier) <NEW_LINE> assert dreamhost_record_from_id == dreamhost_record <NEW_LINE> <DEDENT> def test_id_to_record(self): <NEW_LINE> <INDENT> dreamhost_record = { "type": "A", "record": "www.example.com", "value": "1.2.3.4", } <NEW_LINE> identifier = Provider._identifier(dreamhost_record) <NEW_LINE> record = Provider._id_to_record(identifier) <NEW_LINE> dreamhost_record_from_id = Provider._record_to_dreamhost_record(record) <NEW_LINE> assert dreamhost_record_from_id == dreamhost_record <NEW_LINE> <DEDENT> def test_id_to_dreamhost_record(self): <NEW_LINE> <INDENT> dreamhost_record = { "type": "A", "record": "www.example.com", "value": "1.2.3.4", } <NEW_LINE> identifier = Provider._identifier(dreamhost_record) <NEW_LINE> dreamhost_record_from_id = Provider._id_to_dreamhost_record(identifier) <NEW_LINE> assert dreamhost_record_from_id == dreamhost_record | TestCase for Dreamhost | 62599051ac7a0e7691f73997 |
class FunOpt(Structure): <NEW_LINE> <INDENT> _fields_ = [ ('algorithm', c_int), ('timeout', c_size_t), ('max_object_size', c_size_t), ('flag_exact_wanted', c_bool), ('flag_best_wanted', c_bool) ] | typedef struct ap_funopt_t {
int algorithm;
/* Algorithm selection:
- 0 is default algorithm;
- MAX_INT is most accurate available;
- MIN_INT is most efficient available;
- otherwise, no accuracy or speed meaning
*/
size_t timeout; /* unit !? */
/* Above the given computation time, the function may abort with the
exception flag flag_time_out on.
*/
size_t max_object_size; /* in abstract object size unit. */
/* If during the computation, the size of some object reach this limit, the
function may abort with the exception flag flag_out_of_space on.
*/
bool flag_exact_wanted;
/* return information about exactitude if possible
*/
bool flag_best_wanted;
/* return information about best correct approximation if possible
*/
} ap_funopt_t; | 625990510fa83653e46f639a |
class AntGroup: <NEW_LINE> <INDENT> def __init__(self, n): <NEW_LINE> <INDENT> self.n = n <NEW_LINE> self.ants = [] <NEW_LINE> self.timeElapsed = 0. <NEW_LINE> self.createAnts() <NEW_LINE> <DEDENT> def createAnts(self): <NEW_LINE> <INDENT> ngon = Ngon(self.n) <NEW_LINE> for vertex in ngon.getVerticies(): <NEW_LINE> <INDENT> self.ants.append(Ant(vertex, sim.SPEED)) <NEW_LINE> <DEDENT> for ant,nextAnt in zip(self.ants[:-1], self.ants[1:]): <NEW_LINE> <INDENT> ant.setNextAnt(nextAnt) <NEW_LINE> <DEDENT> self.ants[-1].setNextAnt(self.ants[0]) <NEW_LINE> <DEDENT> def getAnts(self): <NEW_LINE> <INDENT> return self.ants <NEW_LINE> <DEDENT> def getPositions(self): <NEW_LINE> <INDENT> positions = [[],[]] <NEW_LINE> for ant in self.ants: <NEW_LINE> <INDENT> x,y = ant.getPosition() <NEW_LINE> positions[0].append(x) <NEW_LINE> positions[1].append(y) <NEW_LINE> <DEDENT> return positions <NEW_LINE> <DEDENT> def getDistanceBetweenAnts(self): <NEW_LINE> <INDENT> x1,y1 = self.ants[0].getPosition(); <NEW_LINE> x2,y2 = self.ants[1].getPosition(); <NEW_LINE> return sqrt((x1-x2)**2 + (y1-y2)**2) <NEW_LINE> <DEDENT> def step(self, dt): <NEW_LINE> <INDENT> for ant in self.ants: <NEW_LINE> <INDENT> ant.setNextPosition(dt) <NEW_LINE> <DEDENT> for ant in self.ants: <NEW_LINE> <INDENT> ant.step() <NEW_LINE> <DEDENT> self.timeElapsed += dt <NEW_LINE> <DEDENT> def getNumberOfAnts(self): <NEW_LINE> <INDENT> return self.n | Represents a group of ants arranged on the verticies of an n
sided polygon.
SPEED: float/int
Speed that the ants should move with.
n: int
Number of ants
ants: list-type
List of ants in this group.
timeElapsed: float
The amount of time that has passed since the beginning of
the simulation. | 6259905124f1403a9268632b |
class TimeToFailure(BaseClass): <NEW_LINE> <INDENT> def __init__(self, pinger=None, target=None, timeout=300, threshold=5, *args, **kwargs): <NEW_LINE> <INDENT> super(TimeToFailure, self).__init__(*args, **kwargs) <NEW_LINE> self._pinger = pinger <NEW_LINE> self.target = target <NEW_LINE> self.target = target <NEW_LINE> self.timeout = timeout <NEW_LINE> self.threshold = threshold <NEW_LINE> return <NEW_LINE> <DEDENT> @property <NEW_LINE> def pinger(self): <NEW_LINE> <INDENT> if self._pinger is None: <NEW_LINE> <INDENT> self._pinger = ping.ADBPing() <NEW_LINE> <DEDENT> return self._pinger <NEW_LINE> <DEDENT> def run(self, parameters): <NEW_LINE> <INDENT> if parameters.target is None: <NEW_LINE> <INDENT> target = self.target <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> target = parameters.target <NEW_LINE> <DEDENT> if parameters.timeout is None: <NEW_LINE> <INDENT> timeout = self.timeout <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> timeout = parameters.timeout <NEW_LINE> <DEDENT> if parameters.threshold is None: <NEW_LINE> <INDENT> threshold = self.threshold <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> threshold = parameters.threshold <NEW_LINE> <DEDENT> start = now() <NEW_LINE> time_limit = start + timeout <NEW_LINE> failures = 0 <NEW_LINE> first = None <NEW_LINE> while failures < threshold and now() < time_limit: <NEW_LINE> <INDENT> if self.pinger.run(target): <NEW_LINE> <INDENT> failures = 0 <NEW_LINE> first = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> failures += 1 <NEW_LINE> if failures == 1: <NEW_LINE> <INDENT> first = now() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if failures == threshold and first is not None: <NEW_LINE> <INDENT> return first - start <NEW_LINE> <DEDENT> return | A TimeToFailure pings a target until the pings fail. | 6259905107d97122c4218160 |
class OfferVariation(models.Model, TimestampMixin): <NEW_LINE> <INDENT> offer = models.ForeignKey(Offer, on_delete=models.CASCADE, related_name="variations") <NEW_LINE> _price = models.DecimalField(null=True, max_digits=10, decimal_places=3) <NEW_LINE> _is_active = models.BooleanField(default=True) <NEW_LINE> @property <NEW_LINE> def is_active(self): <NEW_LINE> <INDENT> if not self.price: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self._is_active <NEW_LINE> <DEDENT> @is_active.setter <NEW_LINE> def is_active(self, value): <NEW_LINE> <INDENT> self._is_active = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def price(self): <NEW_LINE> <INDENT> extra_cost = sum(self.extras.values_list("additional_price", flat=True)) <NEW_LINE> if extra_cost: <NEW_LINE> <INDENT> return self._price + extra_cost <NEW_LINE> <DEDENT> return self._price <NEW_LINE> <DEDENT> @price.setter <NEW_LINE> def price(self, value): <NEW_LINE> <INDENT> self._price = value | TODO:
This is a specific combination of menuitem-variations for a given offer (eg. small burger, big chips) | 62599051b7558d5895464985 |
class BlobGoal(Goal): <NEW_LINE> <INDENT> def score(self, board: Block) -> int: <NEW_LINE> <INDENT> score = [] <NEW_LINE> flatten_board = _flatten(board) <NEW_LINE> board_size = len(flatten_board) <NEW_LINE> visit = [[-1] * board_size for _ in range(board_size)] <NEW_LINE> for i in range(board_size): <NEW_LINE> <INDENT> for w in range(board_size): <NEW_LINE> <INDENT> if visit[i][w] == -1: <NEW_LINE> <INDENT> score.append (self._undiscovered_blob_size ((i, w), flatten_board, visit)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return max(score) <NEW_LINE> <DEDENT> def _undiscovered_blob_size(self, pos: Tuple[int, int], board: List[List[Tuple[int, int, int]]], visited: List[List[int]]) -> int: <NEW_LINE> <INDENT> if len(board) > pos[0] >= 0 and len(board) > pos[1] >= 0 and visited[pos[0]][pos[1]] == -1: <NEW_LINE> <INDENT> if board[pos[0]][pos[1]] == self.colour: <NEW_LINE> <INDENT> visited[pos[0]][pos[1]] = 1 <NEW_LINE> size = 1 <NEW_LINE> for i in range(-1, 2): <NEW_LINE> <INDENT> size += self._undiscovered_blob_size ((i + pos[0], pos[1]), board, visited) <NEW_LINE> <DEDENT> for w in range(-1, 2): <NEW_LINE> <INDENT> size += self._undiscovered_blob_size ((pos[0], w + pos[1]), board, visited) <NEW_LINE> <DEDENT> return size <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> visited[pos[0]][pos[1]] = 0 <NEW_LINE> <DEDENT> <DEDENT> return 0 <NEW_LINE> <DEDENT> def description(self) -> str: <NEW_LINE> <INDENT> return 'Player gains a point for each ' + colour_name(self.colour) + ' connected together' | Stores the goal for players. Blob goal accounts for the max score for
player's colours connected top/left/right/bottom together. Player gains
a point for each block connected together. | 62599051d6c5a102081e35d4 |
class _SolverDlg(object): <NEW_LINE> <INDENT> WRITE_COMMENTS_PARAM = "writeCommentsToInputFile" <NEW_LINE> def __init__(self, default, param_path, use_default, custom_path): <NEW_LINE> <INDENT> self.default = default <NEW_LINE> self.param_path = param_path <NEW_LINE> self.use_default = use_default <NEW_LINE> self.custom_path = custom_path <NEW_LINE> self.param_group = FreeCAD.ParamGet(self.param_path) <NEW_LINE> <DEDENT> def get_binary(self): <NEW_LINE> <INDENT> binary = self.default <NEW_LINE> FreeCAD.Console.PrintLog("Solver binary path: {} \n".format(binary)) <NEW_LINE> if self.param_group.GetBool(self.use_default, True) is False: <NEW_LINE> <INDENT> binary = self.param_group.GetString(self.custom_path) <NEW_LINE> <DEDENT> FreeCAD.Console.PrintLog("Solver binary path: {} \n".format(binary)) <NEW_LINE> from distutils.spawn import find_executable as find_bin <NEW_LINE> return find_bin(binary) <NEW_LINE> <DEDENT> def get_write_comments(self): <NEW_LINE> <INDENT> return self.param_group.GetBool(self.WRITE_COMMENTS_PARAM, True) | Internal query logic for solver specific settings.
Each instance queries settings for one specific solver (e.g. Elmer) common
among all solvers. To clarify: There are a few settings that are useful
for every solver (e.g. where to find the solver binary) but the value and
the FreeCAD parameter path is different for each one. A instance of this
class contains all the solver specific paths needed. The settings can be
queried via the methods which use those path members to query the value for
the specific solver.
:ivar default:
Default binary name as a string preferably without a prefix path to
make it more generic (e.g. "ccx"). This only works if the binary can be
found via the PATH environment variable on linux or similar mechanisms
on other operating systems. Used if nothing else is specified by the
user.
:ivar param_path:
Parent param path (FreeCADs settings/parameter system) that contains
all settings for the specific solver.
:ivar use_default:
Param path identifying the "use_default" setting. Only specifie the
last part as the *param_path* is prepended to this value.
:ivar custom_path:
Param path identifying the "custom_path" setting. Only specifie the
last part as the *param_path* is prepended to this value. | 62599051cad5886f8bdc5adc |
class ABCLedgerInput(ABCInput): <NEW_LINE> <INDENT> raw_columns = [ "volume", "balance", "fee", "refid", "type", "product" ] <NEW_LINE> resampled_columns = [ "balance" ] <NEW_LINE> @property <NEW_LINE> @abstractmethod <NEW_LINE> def asset(self) -> Union[CryptoEnum, QuoteEnum]: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> ABCInput.__init__(self) <NEW_LINE> self.verbose = True <NEW_LINE> <DEDENT> def _resample(self, raw_data): <NEW_LINE> <INDENT> resampled_data = resampleSerie(raw_data["balance"]).last() <NEW_LINE> return pd.DataFrame( resampled_data, columns=self.__class__.resampled_columns ) <NEW_LINE> <DEDENT> def fillMissing(self, resampled_data): <NEW_LINE> <INDENT> resampled_data["balance"].ffill(inplace=True) <NEW_LINE> resampled_data["balance"].fillna(0, inplace=True) <NEW_LINE> return resampled_data <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def buy(self, ledger, volume_spent, price, timestamp=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def sell(self, ledger, volume_spent, price, timestamp=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def deposit(self, ledger, volume, timestamp=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def withdraw(self, ledger, volume, timestamp=None): <NEW_LINE> <INDENT> pass | Base class for any ledger | 62599051462c4b4f79dbcebb |
class getSettings_result(object): <NEW_LINE> <INDENT> def __init__(self, success=None, e=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> self.e = e <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.success = Settings() <NEW_LINE> self.success.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.e = TalkException() <NEW_LINE> self.e.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('getSettings_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.STRUCT, 0) <NEW_LINE> self.success.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.e is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('e', TType.STRUCT, 1) <NEW_LINE> self.e.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- success
- e | 625990513eb6a72ae038bb17 |
class MapzenReverse(MapzenQuery): <NEW_LINE> <INDENT> provider = 'mapzen' <NEW_LINE> method = 'reverse' <NEW_LINE> _URL = 'https://search.mapzen.com/v1/reverse' <NEW_LINE> _RESULT_CLASS = MapzenReverseResult <NEW_LINE> def _build_params(self, location, provider_key, **kwargs): <NEW_LINE> <INDENT> location = Location(location) <NEW_LINE> return { 'point.lat': location.lat, 'point.lon': location.lng, 'size': kwargs.get('size', 1), 'layers': kwargs.get('layers'), 'source': kwargs.get('sources'), 'boundary.country': kwargs.get('country'), 'api_key': provider_key } | Mapzen REST API
=======================
API Reference
-------------
https://mapzen.com/documentation/search/reverse/ | 625990512ae34c7f260ac59e |
class URL(db.Model): <NEW_LINE> <INDENT> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> full = db.Column(db.String(CHROME_MAX_URL_LENGTH), unique=True, nullable=False, index=True) <NEW_LINE> short = db.Column(db.String(MAX_HASH_LENGTH), nullable=True) | A model to represent the only entity of our app - the URL.
It has a primary key, full version of the url (unique since we don't want repetitions) and fully searchable
because we search in records using that field. And a short user friendly identifier generated directly from the
primary key. | 625990511f037a2d8b9e52c9 |
class IntervalClass(AbjadObject): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> @abc.abstractmethod <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __abs__(self): <NEW_LINE> <INDENT> return type(self)(abs(self._number)) <NEW_LINE> <DEDENT> def __float__(self): <NEW_LINE> <INDENT> return float(self._number) <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(repr(self)) <NEW_LINE> <DEDENT> def __int__(self): <NEW_LINE> <INDENT> return self._number <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self._format_string <NEW_LINE> <DEDENT> @property <NEW_LINE> def _format_string(self): <NEW_LINE> <INDENT> return str(self.number) <NEW_LINE> <DEDENT> @property <NEW_LINE> def _storage_format_specification(self): <NEW_LINE> <INDENT> from abjad.tools import systemtools <NEW_LINE> return systemtools.StorageFormatSpecification( self, is_indented=False, positional_argument_values=( self.number, ), ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def number(self): <NEW_LINE> <INDENT> return self._number | Interval-class base class.
| 6259905145492302aabfd990 |
class Collection(model.Model): <NEW_LINE> <INDENT> name = model.StringProperty('n', required=True) <NEW_LINE> urlname = model.ComputedProperty(lambda self: urlname(self.name)) <NEW_LINE> owner = model.UserProperty('o', required=True) <NEW_LINE> admins = model.UserProperty('a', repeated=True) <NEW_LINE> created = model.DateTimeProperty('c', auto_now_add=True) <NEW_LINE> updated = model.DateTimeProperty('u', auto_now=True) <NEW_LINE> json = model.TextProperty('j', required=True) <NEW_LINE> @classmethod <NEW_LINE> def create(cls, name, publisher_key): <NEW_LINE> <INDENT> return Collection( parent=publisher_key, id=urlname(name), name=name, owner=users.get_current_user(), json=simplejson.dumps(dict( name=name, admin=users.get_current_user().nickname(), url='http://%s.%s.appspot.com/publishers/%s/%s' % (appver, appid, publisher_key.id(), urlname(name))))) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_by_urlname(cls, urlname, publisher_key): <NEW_LINE> <INDENT> return model.Key('Collection', urlname, parent=publisher_key).get() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def all_by_publisher(cls, publisher_key): <NEW_LINE> <INDENT> return Collection.query(ancestor=publisher_key).fetch() | Model for a collection of records. | 625990516e29344779b01b01 |
@inherit_doc <NEW_LINE> class JavaPredictionModel(PredictionModel[T], JavaModel, _PredictorParams): <NEW_LINE> <INDENT> @property <NEW_LINE> @since("2.1.0") <NEW_LINE> def numFeatures(self) -> int: <NEW_LINE> <INDENT> return self._call_java("numFeatures") <NEW_LINE> <DEDENT> @since("3.0.0") <NEW_LINE> def predict(self, value: T) -> float: <NEW_LINE> <INDENT> return self._call_java("predict", value) | (Private) Java Model for prediction tasks (regression and classification). | 62599051498bea3a75a58fde |
class Print3DTools(bpy.types.Panel): <NEW_LINE> <INDENT> bl_label = "3D Print Tools" <NEW_LINE> bl_idname = "3D Print Tools" <NEW_LINE> bl_space_type = 'VIEW_3D' <NEW_LINE> bl_region_type = 'TOOLS' <NEW_LINE> bl_category = "Extended Tools" <NEW_LINE> def draw(self, context): <NEW_LINE> <INDENT> layout = self.layout <NEW_LINE> col = layout.column() <NEW_LINE> col.label(text="UV Tools") <NEW_LINE> col.operator("object.shape_from_uv", text="Create UV Shape", icon='SHAPEKEY_DATA') <NEW_LINE> col.operator("object.autosplit_geometry", text="Autosplit Geometry", icon='UV_ISLANDSEL') <NEW_LINE> col.prop(bpy.context.scene, "use_active_uv_for_shape", text="Use Active Map", icon='GROUP_UVS') <NEW_LINE> col.prop(bpy.context.scene, "uv_shape_adjust_scale", text="Rescale Islands", icon='BORDERMOVE') | Creates a new tab with physics UI | 625990510c0af96317c577be |
class Room: <NEW_LINE> <INDENT> def __init__(self, name, room_setting=None): <NEW_LINE> <INDENT> if not room_setting: <NEW_LINE> <INDENT> room_setting = { 'moderate': { 'room': name.lower(), 'anything': False, 'spam': False, 'banword': False, 'caps': False, 'stretching': False, 'groupchats': False, 'urls': False }, 'broadcastrank': ' ', 'allow games': False, 'tourwhitelist': []} <NEW_LINE> <DEDENT> self.users = {} <NEW_LINE> self.rank = ' ' <NEW_LINE> self.name = name.lower() <NEW_LINE> self.room_setting = room_setting <NEW_LINE> self.loaded = False <NEW_LINE> self.is_pm = self.name == 'pm' <NEW_LINE> self.broadcastrank = self.room_setting['broadcastrank'] <NEW_LINE> <DEDENT> def add_user(self, user): <NEW_LINE> <INDENT> if user.id not in self.users: <NEW_LINE> <INDENT> self.users[user.id] = user <NEW_LINE> <DEDENT> <DEDENT> def remove_user(self, user): <NEW_LINE> <INDENT> if user in self.users: <NEW_LINE> <INDENT> del self.users[user] <NEW_LINE> <DEDENT> <DEDENT> def renamed_user(self, userid, user): <NEW_LINE> <INDENT> self.remove_user(userid) <NEW_LINE> self.add_user(user) | Contains all important information of a pokemon showdown room.
Attributes:
name: string, name of this room.
room_setting: dict, dictionary containing a lot of the room settings in this room
defined below:
room_setting = {
'moderate': {
'room': str,
'anything': bool,
'spam': bool,
'banword': bool,
'caps': bool,
'stretching': bool,
'groupchats': bool,
'urls': bool
},
'broadcastrank': ' ',
'allowgames': False,
'tourwhitelist': []
}
users: map, maps user ids to users.
rank: string, the rank of this bot in this room.
loaded: bool, determines if all the information for this room has been loaded yet.
broadcastrank: string, rank required in this room for users to use commands. | 62599051fff4ab517ebcecda |
class metaStatic(Singleton): <NEW_LINE> <INDENT> def __new__(mcl, classname, bases, classdict): <NEW_LINE> <INDENT> def __init__(self, *p, **k): <NEW_LINE> <INDENT> cls = self.__class__ <NEW_LINE> if p: <NEW_LINE> <INDENT> if not self: <NEW_LINE> <INDENT> return super(newcls, self).__init__(*p, **k) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError("'" + classname + "' object does not support redefinition") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> newdict = {'__init__': __init__} <NEW_LINE> def __getattribute__(self, name): <NEW_LINE> <INDENT> if name in newcls._hide: <NEW_LINE> <INDENT> raise AttributeError("'" + classname + "' object has no attribute '" + name + "'") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return super(newcls, self).__getattribute__(name) <NEW_LINE> <DEDENT> <DEDENT> newdict['__getattribute__'] = __getattribute__ <NEW_LINE> _hide = ('clear', 'update', 'pop', 'popitem', '__setitem__', '__delitem__', 'append', 'extend') <NEW_LINE> newdict['_hide'] = _hide <NEW_LINE> def __setitem__(self, key, value): <NEW_LINE> <INDENT> raise TypeError("'%s' object does not support item assignation" % (self.__class__)) <NEW_LINE> <DEDENT> newdict['__setitem__'] = __setitem__ <NEW_LINE> def __delitem__(self, key): <NEW_LINE> <INDENT> raise TypeError("'%s' object does not support item deletion" % (self.__class__)) <NEW_LINE> <DEDENT> newdict['__delitem__'] = __delitem__ <NEW_LINE> for k in classdict: <NEW_LINE> <INDENT> if k in newdict: <NEW_LINE> <INDENT> warnings.warn("Attribute %r is predefined in class %r of type %r and can't be overriden" % (k, classname, mcl.__name__)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> newdict[k] = classdict[k] <NEW_LINE> <DEDENT> <DEDENT> newcls = super(metaStatic, mcl).__new__(mcl, classname, bases, newdict) <NEW_LINE> return newcls | A static (immutable) Singleton metaclass to quickly build classes
holding predefined immutable dicts
>>> class FrozenDictSingleton(with_metaclass(metaStatic, dict)) :
... pass
...
>>> FrozenDictSingleton({'A':1})
{'A': 1}
>>> a = FrozenDictSingleton()
>>> a
{'A': 1}
>>> b = FrozenDictSingleton()
>>> a, b
({'A': 1}, {'A': 1})
>>> a is b
True
>>> b = FrozenDictSingleton({'B':2})
Traceback (most recent call last):
...
TypeError: 'FrozenDictSingleton' object does not support redefinition
>>> a['A']
1
>>> a['A'] = 2 #doctest: +ELLIPSIS
Traceback (most recent call last):
...
TypeError: '<class '...FrozenDictSingleton'>' object does not support item assignation
>>> a.clear()
Traceback (most recent call last):
...
AttributeError: 'FrozenDictSingleton' object has no attribute 'clear'
>>> a, b, FrozenDictSingleton()
({'A': 1}, {'A': 1}, {'A': 1})
>>> a is b and a is FrozenDictSingleton()
True
>>> class StaticTest(FrozenDictSingleton):
... pass
...
>>> StaticTest({'A': 1})
{'A': 1}
>>> a = StaticTest()
>>> a
{'A': 1}
>>> b = StaticTest()
>>> a, b
({'A': 1}, {'A': 1})
>>> class StaticTest2( StaticTest ):
... pass
...
>>> StaticTest2({'B': 2})
{'B': 2}
>>> a = StaticTest2()
>>> a
{'B': 2}
>>> b = StaticTest2()
>>> a, b
({'B': 2}, {'B': 2}) | 62599051d99f1b3c44d06b58 |
class PuzzleButton(Button): <NEW_LINE> <INDENT> def __init__(self, master, v, r, c ): <NEW_LINE> <INDENT> self.board_width, self.board_height= ( int(master['width']), int(master['height']) ) <NEW_LINE> self.dx = self.board_width/4 <NEW_LINE> self.dy = self.board_height/4 <NEW_LINE> Button.__init__(self, master, text='%2d'%(v) ) <NEW_LINE> self.place(x=int(self.dx*r), y=int(self.dy*c), width=int(self.dx), height=int(self.dy) ) <NEW_LINE> self.row = r <NEW_LINE> self.column=c <NEW_LINE> self.value=v <NEW_LINE> <DEDENT> def move(self, r, c): <NEW_LINE> <INDENT> self.place(x=int(self.dx*r), y=int(self.dy*c), width=int(self.dx), height=int(self.dy)) <NEW_LINE> self.row=r <NEW_LINE> self.column=c | A button with additional info | 6259905107d97122c4218162 |
class EmailBackend(ModelBackend): <NEW_LINE> <INDENT> def authenticate(self, request: HttpRequest, email: str=None, password: str=None, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user = User.objects.get(email=email) <NEW_LINE> <DEDENT> except (User.MultipleObjectsReturned, User.DoesNotExist): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if user.check_password(password): <NEW_LINE> <INDENT> return user | Authenticate against email addresses. | 62599051a219f33f346c7cbe |
class Hypothesis(object): <NEW_LINE> <INDENT> def __init__(self, tokens, log_prob, state): <NEW_LINE> <INDENT> self.tokens = tokens <NEW_LINE> self.log_prob = log_prob <NEW_LINE> self.state = state <NEW_LINE> <DEDENT> def Extend(self, token, log_prob, new_state): <NEW_LINE> <INDENT> return Hypothesis(self.tokens + [token], self.log_prob + log_prob, new_state) <NEW_LINE> <DEDENT> @property <NEW_LINE> def latest_token(self): <NEW_LINE> <INDENT> return self.tokens[-1] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return ('Hypothesis(log prob = %.4f, tokens = %s)' % (self.log_prob, self.tokens)) | Defines a hypothesis during beam search. | 6259905130dc7b76659a0cdb |
class MATS1DElasticWithFlaw( MATS1DElastic ): <NEW_LINE> <INDENT> flaw_position = Float( 0.15 ) <NEW_LINE> flaw_radius = Float( 0.05 ) <NEW_LINE> reduction_factor = Float( 0.9 ) <NEW_LINE> stiffness = 'secant' <NEW_LINE> def get_E( self, sctx = None ): <NEW_LINE> <INDENT> if sctx: <NEW_LINE> <INDENT> X = sctx.fets_eval.get_X_pnt( sctx ) <NEW_LINE> if fabs( X[0] - self.flaw_position ) < self.flaw_radius: <NEW_LINE> <INDENT> return self.E * self.reduction_factor <NEW_LINE> <DEDENT> <DEDENT> return self.E <NEW_LINE> <DEDENT> def get_corr_pred( self, sctx, eps_app_eng, d_eps, tn, tn1, *args, **kw ): <NEW_LINE> <INDENT> E = self.get_E( sctx ) <NEW_LINE> D_el = array( [[E]] ) <NEW_LINE> sigma = array( [E * eps_app_eng[0] ] ) <NEW_LINE> return sigma, D_el | Specialized damage model.
The damage model is driven by a single damage variable omega_0
at the point x = 0. The material points are damage according
to the nonlocal distribution function alpha implemnted
in the get_alpha procedure.
The implementation reuses the standard MATS1DDamage but replaces
the state variables at each material point by the single shared
variable omega_0. | 62599051507cdc57c63a625d |
class WarningTestMixin(object): <NEW_LINE> <INDENT> @contextmanager <NEW_LINE> def assertWarns(self, warning_class): <NEW_LINE> <INDENT> with warnings.catch_warnings(record=True) as warns: <NEW_LINE> <INDENT> warnings.simplefilter("always") <NEW_LINE> yield <NEW_LINE> self.assertGreaterEqual(len(warns), 1) <NEW_LINE> self.assertTrue(any(issubclass(warning.category, warning_class) for warning in warns)) | Add the ability to assert on warnings raised by a chunk of code. | 625990512ae34c7f260ac5a0 |
class ControlModel(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'control_de_materias' <NEW_LINE> id_control = db.Column(db.Integer, primary_key=True, autoincrement=True) <NEW_LINE> id_cohorte = db.Column(db.Integer, db.ForeignKey('cohorte.id_cohorte')) <NEW_LINE> id_materia = db.Column(db.Integer, db.ForeignKey('materia.id_materia')) <NEW_LINE> id_profesor = db.Column(db.Integer, db.ForeignKey('persona.cedula')) <NEW_LINE> fecha_inicio = db.Column(db.String) <NEW_LINE> fecha_fin = db.Column(db.String) <NEW_LINE> captura = db.Column(db.Boolean) <NEW_LINE> def __init__(self, data): <NEW_LINE> <INDENT> self.id_cohorte = data.get('id_cohorte') <NEW_LINE> self.id_materia = data.get('id_materia') <NEW_LINE> self.id_profesor = data.get('id_profesor') <NEW_LINE> self.fecha_inicio = data.get('fecha_inicio') <NEW_LINE> self.fecha_fin = data.get('fecha_fin') <NEW_LINE> self.captura = data.get('captura') <NEW_LINE> <DEDENT> def __repr(self): <NEW_LINE> <INDENT> return '<id_control {}>'.format(self.id_control) <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> coh = self.id_cohorte <NEW_LINE> mat = self.id_materia <NEW_LINE> s = ControlModel.query.filter_by(id_cohorte=coh,id_materia=mat).count() <NEW_LINE> if s > 0: <NEW_LINE> <INDENT> return "esta materia ya esta registrada para este cohorte" <NEW_LINE> <DEDENT> db.session.add(self) <NEW_LINE> db.session.commit() <NEW_LINE> return "control registrado" <NEW_LINE> <DEDENT> def get_control(self): <NEW_LINE> <INDENT> s = ControlModel.query.all() <NEW_LINE> return s <NEW_LINE> <DEDENT> def get_full_control(self) -> object: <NEW_LINE> <INDENT> s = db.session.query(self, cohortemodel.CohorteModel, usermodel.UserModel, materiamodel.MateriaModel).join(cohortemodel.CohorteModel, usermodel.UserModel, materiamodel.MateriaModel).all() <NEW_LINE> return s <NEW_LINE> <DEDENT> def get_control_by_profesor_id(self,id): <NEW_LINE> <INDENT> s = db.session.query(self,dbmateria).filter_by(id_profesor=id).filter_by(captura=True).join(dbmateria).all() <NEW_LINE> return s <NEW_LINE> <DEDENT> def habilitar_captura(self, id): <NEW_LINE> <INDENT> if db.session.query(self).filter_by(id_control=id).first().captura == True: <NEW_LINE> <INDENT> db.session.query(self).filter_by(id_control=id).update({"captura":False}, synchronize_session=False) <NEW_LINE> db.session.commit() <NEW_LINE> return "Inhabilitada captura de nota para la materia" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> db.session.query(self).filter_by(id_control=id).update({"captura":True}, synchronize_session=False) <NEW_LINE> db.session.commit() <NEW_LINE> return "Habilitada captura de nota para la materia" | Control Model | 62599051287bf620b62730a8 |
class Solution: <NEW_LINE> <INDENT> def isPalindrome(self, s:str): <NEW_LINE> <INDENT> if s == "": <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> s = s.lower() <NEW_LINE> z = "" <NEW_LINE> for i in s: <NEW_LINE> <INDENT> if ord("a") <= ord(i) <= ord("z"): <NEW_LINE> <INDENT> z += i <NEW_LINE> <DEDENT> <DEDENT> return z == z[::-1] | @param s: A string
@return: Whether the string is a valid palindrome | 6259905173bcbd0ca4bcb749 |
class HeapSort: <NEW_LINE> <INDENT> def sort(self, nums): <NEW_LINE> <INDENT> if not nums: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._heapify(nums) <NEW_LINE> tail = len(nums) - 1 <NEW_LINE> while tail: <NEW_LINE> <INDENT> swap(nums, 0, tail) <NEW_LINE> self._sink(nums, 0, tail - 1) <NEW_LINE> tail -= 1 <NEW_LINE> <DEDENT> <DEDENT> def _heapify(self, nums): <NEW_LINE> <INDENT> n = len(nums) <NEW_LINE> i = n // 2 - 1 <NEW_LINE> while i > 0: <NEW_LINE> <INDENT> self._sink(nums, i, n - 1) <NEW_LINE> i -= 1 <NEW_LINE> <DEDENT> <DEDENT> def _sink(self, nums, idx, bound): <NEW_LINE> <INDENT> l_idx = (idx + 1) * 2 - 1 <NEW_LINE> r_idx = (idx + 1) * 2 <NEW_LINE> if r_idx <= bound: <NEW_LINE> <INDENT> if nums[l_idx] <= nums[r_idx] and nums[idx] < nums[r_idx]: <NEW_LINE> <INDENT> swap(nums, idx, r_idx) <NEW_LINE> self._sink(nums, r_idx, bound) <NEW_LINE> <DEDENT> elif nums[r_idx] <= nums[l_idx] and nums[idx] < nums[l_idx]: <NEW_LINE> <INDENT> swap(nums, idx, l_idx) <NEW_LINE> self._sink(nums, l_idx, bound) <NEW_LINE> <DEDENT> <DEDENT> elif l_idx <= bound: <NEW_LINE> <INDENT> if nums[idx] < nums[l_idx]: <NEW_LINE> <INDENT> swap(nums, idx, l_idx) | O(N*logN), in-place, unstable sorting algorithm | 62599051ac7a0e7691f7399b |
class ModelPeople(Base): <NEW_LINE> <INDENT> __tablename__ = 'people' <NEW_LINE> id = Column('id', Integer, primary_key=True) <NEW_LINE> name = Column('name', String) <NEW_LINE> height = Column('height', String) <NEW_LINE> mass = Column('mass', String) <NEW_LINE> hair_color = Column('hair_color', String) <NEW_LINE> skin_color = Column('skin_color', String) <NEW_LINE> eye_color = Column('eye_color', String) <NEW_LINE> birth_year = Column('birth_year', String) <NEW_LINE> gender = Column('gender', String) <NEW_LINE> planet_id = Column('planet_id', Integer, ForeignKey('planet.id')) <NEW_LINE> created = Column('created', String) <NEW_LINE> edited = Column('edited', String) <NEW_LINE> url = Column('url', String) | People model. | 62599051498bea3a75a58fe0 |
class _FilterHints(object): <NEW_LINE> <INDENT> def __init__(self, namefield): <NEW_LINE> <INDENT> self._namefield = namefield <NEW_LINE> self._allnames = False <NEW_LINE> self._names = None <NEW_LINE> self._datakinds = set() <NEW_LINE> <DEDENT> def RequestedNames(self): <NEW_LINE> <INDENT> if self._allnames or self._names is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return utils.UniqueSequence(self._names) <NEW_LINE> <DEDENT> def ReferencedData(self): <NEW_LINE> <INDENT> return frozenset(self._datakinds) <NEW_LINE> <DEDENT> def _NeedAllNames(self): <NEW_LINE> <INDENT> self._allnames = True <NEW_LINE> self._names = None <NEW_LINE> <DEDENT> def NoteLogicOp(self, op): <NEW_LINE> <INDENT> if op != qlang.OP_OR: <NEW_LINE> <INDENT> self._NeedAllNames() <NEW_LINE> <DEDENT> <DEDENT> def NoteUnaryOp(self, op, datakind): <NEW_LINE> <INDENT> if datakind is not None: <NEW_LINE> <INDENT> self._datakinds.add(datakind) <NEW_LINE> <DEDENT> self._NeedAllNames() <NEW_LINE> <DEDENT> def NoteBinaryOp(self, op, datakind, name, value): <NEW_LINE> <INDENT> if datakind is not None: <NEW_LINE> <INDENT> self._datakinds.add(datakind) <NEW_LINE> <DEDENT> if self._allnames: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> EQ_OPS = [qlang.OP_EQUAL, qlang.OP_EQUAL_LEGACY] <NEW_LINE> if op in EQ_OPS and name == self._namefield: <NEW_LINE> <INDENT> if self._names is None: <NEW_LINE> <INDENT> self._names = [] <NEW_LINE> <DEDENT> self._names.append(value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._NeedAllNames() | Class for filter analytics.
When filters are used, the user of the L{Query} class usually doesn't know
exactly which items will be necessary for building the result. It therefore
has to prepare and compute the input data for potentially returning
everything.
There are two ways to optimize this. The first, and simpler, is to assign
each field a group of data, so that the caller can determine which
computations are necessary depending on the data groups requested. The list
of referenced groups must also be computed for fields referenced in the
filter.
The second is restricting the items based on a primary key. The primary key
is usually a unique name (e.g. a node name). This class extracts all
referenced names from a filter. If it encounters any filter condition which
disallows such a list to be determined (e.g. a non-equality filter), all
names will be requested.
The end-effect is that any operation other than L{qlang.OP_OR} and
L{qlang.OP_EQUAL} will make the query more expensive. | 625990510c0af96317c577bf |
class power_off_device(relay_step): <NEW_LINE> <INDENT> def __init__(self, serial, except_charging=False, timeout=120, device_info="", **kwargs): <NEW_LINE> <INDENT> relay_step.__init__(self, **kwargs) <NEW_LINE> self.serial = serial <NEW_LINE> self.timeout = timeout <NEW_LINE> self.except_charging = except_charging <NEW_LINE> self.device_info = device_info <NEW_LINE> <DEDENT> def do(self): <NEW_LINE> <INDENT> if self.device_info != "broxtonp": <NEW_LINE> <INDENT> self.relay.power_on() <NEW_LINE> <DEDENT> self.relay.power_off() <NEW_LINE> <DEDENT> def check_condition(self): <NEW_LINE> <INDENT> wait_time = 0 <NEW_LINE> while local_utils.is_device_connected(self.serial, self.except_charging) and wait_time < self.timeout: <NEW_LINE> <INDENT> time.sleep(2) <NEW_LINE> wait_time += 2 <NEW_LINE> <DEDENT> return not local_utils.is_device_connected(self.serial, self.except_charging) | description:
Shuts down the device.
usage:
relay_steps.power_off_device(serial=serial,
relay_type = relay_type,
relay_port = relay_port,
power_port = power_port)()
tags:
shutdown, relay | 6259905121a7993f00c67428 |
class Generator(nn.Module): <NEW_LINE> <INDENT> def __init__(self, num_classes, dims, shape): <NEW_LINE> <INDENT> super(Generator, self).__init__() <NEW_LINE> self._shape = shape <NEW_LINE> self.labels_emb = nn.Embedding(num_classes, num_classes) <NEW_LINE> self.model = nn.Sequential( *self._block(dims + num_classes, 128, normalize=False), *self._block(128, 256), *self._block(256, 512), *self._block(512, 1024), nn.Linear(1024, int(np.prod(self._shape))), nn.Tanh() ) <NEW_LINE> <DEDENT> def _block(self, in_features, out_features, normalize=True): <NEW_LINE> <INDENT> layers = [nn.Linear(in_features, out_features)] <NEW_LINE> if normalize: <NEW_LINE> <INDENT> layers.append(nn.BatchNorm1d(out_features, 0.8)) <NEW_LINE> <DEDENT> layers.append(nn.LeakyReLU(0.2, inplace=True)) <NEW_LINE> return layers <NEW_LINE> <DEDENT> def forward(self, noise, labels): <NEW_LINE> <INDENT> gen_input = torch.cat((self.labels_emb(labels), noise), -1) <NEW_LINE> img = self.model(gen_input) <NEW_LINE> img = img.view(img.size(0), *self._shape) <NEW_LINE> return img | Definition of the generator class
| 6259905115baa7234946344c |
class Image(Model): <NEW_LINE> <INDENT> def insert_bare(self, cursor): <NEW_LINE> <INDENT> cursor.execute("INSERT INTO images (document_id, url, alt)" "VALUES (%(document_id)s, %(url)s, %(alt)s)", self.serialize()) | Represents an image from a document, as it is stored in the database. | 62599051d6c5a102081e35d7 |
class DBEventSink(EventSink): <NEW_LINE> <INDENT> def __init__(self, dest, db_stats=False, namespace=STAMPEDE_NS, props=None, db_type=None, **kw): <NEW_LINE> <INDENT> self._namespace=namespace <NEW_LINE> if namespace == STAMPEDE_NS: <NEW_LINE> <INDENT> self._db = stampede_loader.Analyzer(dest, perf=db_stats, batch="yes", props=props, db_type=db_type) <NEW_LINE> <DEDENT> elif namespace == DASHBOARD_NS: <NEW_LINE> <INDENT> self._db = stampede_dashboard_loader.Analyzer(dest, perf=db_stats, batch="yes", props=props, db_type=db_type) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Unknown namespace specified '%s'" % (namespace)) <NEW_LINE> <DEDENT> super(DBEventSink, self).__init__() <NEW_LINE> <DEDENT> def send(self, event, kw): <NEW_LINE> <INDENT> if self._isdbg: <NEW_LINE> <INDENT> self._log.debug("send.start event=%s" % (event)) <NEW_LINE> <DEDENT> d = {'event' : self._namespace + event} <NEW_LINE> for k, v in kw.iteritems(): <NEW_LINE> <INDENT> d[k.replace('__','.')] = v <NEW_LINE> <DEDENT> self._db.notify(d) <NEW_LINE> if self._isdbg: <NEW_LINE> <INDENT> self._log.debug("send.end event=%s" % (event)) <NEW_LINE> <DEDENT> <DEDENT> def close(self): <NEW_LINE> <INDENT> self._log.debug("close.start") <NEW_LINE> self._db.finish() <NEW_LINE> self._log.debug("close.end") | Write wflow event logs to database via loader | 62599051009cb60464d029f9 |
class Benchmark(object): <NEW_LINE> <INDENT> __metaclass__ = ABCMeta <NEW_LINE> def __init__(self, index, last=False, word_size=4): <NEW_LINE> <INDENT> self.index = index <NEW_LINE> self.last = last <NEW_LINE> self.word_size = word_size <NEW_LINE> self.directory = '' <NEW_LINE> self.max_addr = -1 <NEW_LINE> <DEDENT> def read(self, addr): <NEW_LINE> <INDENT> addr *= self.word_size <NEW_LINE> return AccessType.READ, addr, self.word_size <NEW_LINE> <DEDENT> def write(self, addr): <NEW_LINE> <INDENT> addr *= self.word_size <NEW_LINE> return AccessType.WRITE, addr, self.word_size <NEW_LINE> <DEDENT> def idle(self, cycles): <NEW_LINE> <INDENT> return AccessType.IDLE, cycles, 0 <NEW_LINE> <DEDENT> def produce(self, port): <NEW_LINE> <INDENT> if port >= 0: <NEW_LINE> <INDENT> return AccessType.PRODUCE, port, 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return AccessType.IDLE, 0, 0 <NEW_LINE> <DEDENT> <DEDENT> def consume(self, port): <NEW_LINE> <INDENT> if port >= 0: <NEW_LINE> <INDENT> return AccessType.CONSUME, port, 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return AccessType.IDLE, 0, 0 <NEW_LINE> <DEDENT> <DEDENT> def reset(self, directory): <NEW_LINE> <INDENT> self.directory = directory <NEW_LINE> <DEDENT> def collect_stats(self, directory, dist): <NEW_LINE> <INDENT> self.reset(directory) <NEW_LINE> for t, addr, size in self.run(False): <NEW_LINE> <INDENT> if t == AccessType.READ or t == AccessType.WRITE: <NEW_LINE> <INDENT> dist.insert_range(addr, size) <NEW_LINE> self.max_addr = max(self.max_addr, addr + size) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_size(self, directory): <NEW_LINE> <INDENT> if self.max_addr < 0: <NEW_LINE> <INDENT> self.reset(directory) <NEW_LINE> for t, addr, size in self.run(False): <NEW_LINE> <INDENT> if t == AccessType.READ or t == AccessType.WRITE: <NEW_LINE> <INDENT> self.max_addr = max(self.max_addr, addr + size) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return max(self.max_addr, 0) <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def run(self, repeat): <NEW_LINE> <INDENT> assert(False) | Base clase for benchmarks.
A benchmark is a kernel used to generate an address trace. | 62599051b57a9660fecd2f3a |
class Surface(DaeObject): <NEW_LINE> <INDENT> def __init__(self, id, img, format=None, xmlnode=None): <NEW_LINE> <INDENT> self.id = id <NEW_LINE> self.image = img <NEW_LINE> self.format = format if format is not None else "A8R8G8B8" <NEW_LINE> if xmlnode != None: <NEW_LINE> <INDENT> self.xmlnode = xmlnode <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.xmlnode = E.newparam( E.surface( E.init_from(self.image.id), E.format(self.format) , type="2D") , sid=self.id) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def load( collada, localscope, node ): <NEW_LINE> <INDENT> surfacenode = node.find( tag('surface') ) <NEW_LINE> if surfacenode is None: raise DaeIncompleteError('No surface found in newparam') <NEW_LINE> if surfacenode.get('type') != '2D': raise DaeMalformedError('Hard to imagine a non-2D surface, isn\'t it?') <NEW_LINE> initnode = surfacenode.find( tag('init_from') ) <NEW_LINE> if initnode is None: raise DaeIncompleteError('No init image found in surface') <NEW_LINE> formatnode = surfacenode.find( tag('format') ) <NEW_LINE> if formatnode is None: format = None <NEW_LINE> else: format = formatnode.text <NEW_LINE> imgid = initnode.text <NEW_LINE> id = node.get('sid') <NEW_LINE> if imgid in localscope: <NEW_LINE> <INDENT> img = localscope[imgid] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> img = collada.images.get(imgid) <NEW_LINE> <DEDENT> if img is None: raise DaeBrokenRefError("Missing image '%s' in surface '%s'" % (imgid, id)) <NEW_LINE> return Surface(id, img, format, xmlnode=node) <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> surfacenode = self.xmlnode.find( tag('surface') ) <NEW_LINE> initnode = surfacenode.find( tag('init_from') ) <NEW_LINE> if self.format: <NEW_LINE> <INDENT> formatnode = surfacenode.find( tag('format') ) <NEW_LINE> if formatnode is None: <NEW_LINE> <INDENT> surfacenode.append(E.format(self.format)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> formatnode.text = self.format <NEW_LINE> <DEDENT> <DEDENT> initnode.text = self.image.id <NEW_LINE> self.xmlnode.set('sid', self.id) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '<Surface id=%s>' % (self.id,) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str(self) | Class containing data coming from a <surface> tag.
Collada materials use this to access to the <image> tag.
The only extra information we store right now is the
image format. In theory, this enables many more features
according to the collada spec, but no one seems to actually
use them in the wild, so for now, it's unimplemented. | 62599051b5575c28eb713729 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.