code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def sign(self, response): <NEW_LINE> <INDENT> signed_response = deepcopy(response) <NEW_LINE> assoc_handle = response.request.assoc_handle <NEW_LINE> if assoc_handle: <NEW_LINE> <INDENT> assoc = self.getAssociation(assoc_handle, dumb=False, checkExpiration=False) <NEW_LINE> if not assoc or assoc.expiresIn <= 0: <NEW_LINE> <INDENT> signed_response.fields.setArg( OPENID_NS, 'invalidate_handle', assoc_handle) <NEW_LINE> assoc_type = assoc and assoc.assoc_type or 'HMAC-SHA1' <NEW_LINE> if assoc and assoc.expiresIn <= 0: <NEW_LINE> <INDENT> self.invalidate(assoc_handle, dumb=False) <NEW_LINE> <DEDENT> assoc = self.createAssociation(dumb=True, assoc_type=assoc_type) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> assoc = self.createAssociation(dumb=True) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> signed_response.fields = assoc.signMessage(signed_response.fields) <NEW_LINE> <DEDENT> except kvform.KVFormError as err: <NEW_LINE> <INDENT> raise EncodingError(response, explanation=six.text_type(err)) <NEW_LINE> <DEDENT> return signed_response
Sign a response. I take a L{OpenIDResponse}, create a signature for everything in its L{signed<OpenIDResponse.signed>} list, and return a new copy of the response object with that signature included. @param response: A response to sign. @type response: L{OpenIDResponse} @returns: A signed copy of the response. @returntype: L{OpenIDResponse}
625941ba498bea3a759b9953
def prepare_basket(request, product, voucher=None): <NEW_LINE> <INDENT> basket = Basket.get_basket(request.user, request.site) <NEW_LINE> basket.flush() <NEW_LINE> basket.add_product(product, 1) <NEW_LINE> if product.get_product_class().name == ENROLLMENT_CODE_PRODUCT_CLASS_NAME: <NEW_LINE> <INDENT> basket.clear_vouchers() <NEW_LINE> <DEDENT> elif voucher: <NEW_LINE> <INDENT> basket.clear_vouchers() <NEW_LINE> basket.vouchers.add(voucher) <NEW_LINE> Applicator().apply(basket, request.user, request) <NEW_LINE> logger.info('Applied Voucher [%s] to basket [%s].', voucher.code, basket.id) <NEW_LINE> <DEDENT> affiliate_id = request.COOKIES.get(settings.AFFILIATE_COOKIE_KEY) <NEW_LINE> if affiliate_id: <NEW_LINE> <INDENT> Referral.objects.update_or_create( basket=basket, defaults={'affiliate_id': affiliate_id} ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> Referral.objects.filter(basket=basket).delete() <NEW_LINE> <DEDENT> basket_addition = get_class('basket.signals', 'basket_addition') <NEW_LINE> basket_addition.send(sender=basket_addition, product=product, user=request.user, request=request) <NEW_LINE> return basket
Create or get the basket, add the product, apply a voucher, and record referral data. Existing baskets are merged. The specified product will be added to the remaining open basket. If voucher is passed, all existing vouchers added to the basket are removed because we allow only one voucher per basket. Vouchers are not applied if an enrollment code product is in the basket. Arguments: request (Request): The request object made to the view. product (Product): Product to be added to the basket. voucher (Voucher): Voucher to apply to the basket. Returns: basket (Basket): Contains the product to be redeemed and the Voucher applied.
625941ba6fece00bbac2d5de
def GetRequest(self, cfg): <NEW_LINE> <INDENT> for d in self.disks: <NEW_LINE> <INDENT> d[constants.IDISK_TYPE] = self.disk_template <NEW_LINE> <DEDENT> disk_space = gmi.ComputeDiskSize(self.disks) <NEW_LINE> return { "name": self.name, "disk_template": self.disk_template, "group_name": self.group_name, "tags": self.tags, "os": self.os, "vcpus": self.vcpus, "memory": self.memory, "spindle_use": self.spindle_use, "disks": self.disks, "disk_space_total": disk_space, "nics": self.nics, "required_nodes": self.RequiredNodes(), "hypervisor": self.hypervisor, }
Requests a new instance. The checks for the completeness of the opcode must have already been done.
625941ba377c676e9127204c
def __init__(self, index_filename, filenames, proxy_factory, format, key_function, repr, max_open=10): <NEW_LINE> <INDENT> if not _sqlite: <NEW_LINE> <INDENT> from Bio import MissingPythonDependencyError <NEW_LINE> raise MissingPythonDependencyError("Requires sqlite3, which is " "included Python 2.5+") <NEW_LINE> <DEDENT> if filenames is not None: <NEW_LINE> <INDENT> filenames = list(filenames) <NEW_LINE> <DEDENT> self._index_filename = index_filename <NEW_LINE> self._filenames = filenames <NEW_LINE> self._format = format <NEW_LINE> self._key_function = key_function <NEW_LINE> self._proxy_factory = proxy_factory <NEW_LINE> self._repr = repr <NEW_LINE> self._max_open = max_open <NEW_LINE> self._proxies = {} <NEW_LINE> self._relative_path = os.path.abspath(os.path.dirname(index_filename)) <NEW_LINE> if os.path.isfile(index_filename): <NEW_LINE> <INDENT> self._load_index() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._build_index()
Initialize the class.
625941ba187af65679ca4fc0
def handler404(request): <NEW_LINE> <INDENT> messages.add_message( request, messages.ERROR, force_text(_('Page not found') + ": " + request.prefix + request.get_full_path()) ) <NEW_LINE> return HttpResponseRedirect(request.prefix + "/")
Custom error handler which redirects to the main page rather than displaying the 404 page.
625941ba44b2445a33931f42
@fixture(scope='module') <NEW_LINE> def module_org(): <NEW_LINE> <INDENT> default_org_id = ( nailgun.entities.Organization() .search(query={'search': 'name="{}"'.format(DEFAULT_ORG)})[0] .id ) <NEW_LINE> return nailgun.entities.Organization(id=default_org_id).read()
Shares the same organization for all tests in specific test module. Returns 'Default Organization' by default, override this fixture on :rtype: :class:`nailgun.entities.Organization`
625941ba8c0ade5d55d3e862
def write(self, stream): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.stream().write(stream) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> return self.stream().write(stream.read())
Write stream to file.
625941ba30c21e258bdfa33d
def testlog(self, msg): <NEW_LINE> <INDENT> self.testlogger.info(msg)
sends a info-level message to the logger This method is used mostly in the test cases, that a smaller version of it is quite comfortable.
625941ba92d797404e30402b
def string_to_grid(astring): <NEW_LINE> <INDENT> return [list(r) for r in astring.split('/')]
Convert grid represented as a string in PUZZLE_INPUT to list of lists and return it.
625941baaad79263cf3908de
def set_udim(self, udim, size, start=0): <NEW_LINE> <INDENT> udim_name = udim["name"] <NEW_LINE> self.unlimited_dim_sizes[udim_name] = int(size) <NEW_LINE> self.unlimited_dim_index_start[udim_name] = 0 if start is None else start
Set the number of fills along some unlimited dimension, and optionally, if it's indexed by (index_by) some variable, what value the fills should start at.
625941ba91af0d3eaac9b8b7
def quit(self): <NEW_LINE> <INDENT> raise NotImplementedError
Quits the browser, closing its windows (if it has one). After quit the browser, you can't use it anymore.
625941baa17c0f6771cbdef6
def execute_from_command_line(): <NEW_LINE> <INDENT> start_time = time.time() <NEW_LINE> update_cpplint_usage() <NEW_LINE> options, cpplint_filenames = parse_arguments() <NEW_LINE> if options['expanddir'] == 'no': <NEW_LINE> <INDENT> filenames = cpplint_filenames <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> filenames = list() <NEW_LINE> recursive = (options['expanddir'] == 'recursive') <NEW_LINE> expand_directory = utility.expand_directory <NEW_LINE> for filename in cpplint_filenames: <NEW_LINE> <INDENT> if os.path.isfile(filename): <NEW_LINE> <INDENT> filenames.append(filename) <NEW_LINE> <DEDENT> elif os.path.isdir(filename): <NEW_LINE> <INDENT> expanded_filenames = expand_directory( filename, recursive=recursive, excludedirs=options['excludedirs']) <NEW_LINE> filenames.extend(expanded_filenames) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> print(utility.get_ansi_code('FOREGROUND_CYAN') + utility.get_ansi_code('STYLE_BRIGHT') + '\n=== CCLINT ===' + utility.get_ansi_code('FOREGROUND_RESET') + utility.get_ansi_code('STYLE_RESET_ALL')) <NEW_LINE> stream = file_stream.FileStream(sys.stderr, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace') <NEW_LINE> cpplint_state = cpplint._CppLintState() <NEW_LINE> cpplint_state.ResetErrorCounts() <NEW_LINE> for filename in filenames: <NEW_LINE> <INDENT> stream.begin(filename) <NEW_LINE> cpplint.ProcessFile(filename, cpplint_state.verbose_level) <NEW_LINE> stream.end() <NEW_LINE> <DEDENT> print(utility.get_ansi_code('FOREGROUND_GREEN') + utility.get_ansi_code('STYLE_BRIGHT') + '\n** LINT SUCCEEDED **' + utility.get_ansi_code('STYLE_RESET_ALL') + utility.get_ansi_code('FOREGROUND_WHITE') + utility.get_ansi_code('STYLE_DIM') + ' ({0:.3f} seconds)\n\n'.format(time.time() - start_time) + utility.get_ansi_code('FOREGROUND_RESET') + utility.get_ansi_code('STYLE_RESET_ALL')) <NEW_LINE> total_error_counts = stream.total_error_counts <NEW_LINE> if total_error_counts: <NEW_LINE> <INDENT> print(utility.get_ansi_code('FOREGROUND_RED') + 'Total errors found: {0:d}'.format(total_error_counts)) <NEW_LINE> <DEDENT> print(utility.get_ansi_code('FOREGROUND_RESET') + 'Done.\n') <NEW_LINE> sys.exit(total_error_counts > 0)
Executes the cpplint client with added features. This function is the entry point of the cclint client.
625941bab5575c28eb68dea0
def set_info(self, info_type, info_labels): <NEW_LINE> <INDENT> return self._listitem.setInfo(info_type, info_labels)
Sets the listitem's info
625941ba63f4b57ef0000fc4
def main(): <NEW_LINE> <INDENT> polUni = cobra.model.pol.Uni('') <NEW_LINE> fvTenant = cobra.model.fv.Tenant(polUni, 'pod1') <NEW_LINE> tree = PyraTree('polUni', locals()) <NEW_LINE> dict_tree = tree.dtree <NEW_LINE> xml_tree = tree.etree <NEW_LINE> json_tree = tree.jtree <NEW_LINE> print(ElementTree.tostring(xml_tree, encoding='utf-8')) <NEW_LINE> print(json.dumps(json_tree, indent=4, sort_keys=True))
Use locals() to create a PyraTree, then get JSON/XML representations of the PyraTree data and print them.
625941ba38b623060ff0ac91
def is_trained(self): <NEW_LINE> <INDENT> return self._model_fitted
Returns: bool: True if the model already trained, False otherwise.
625941ba4e696a04525c92ef
def sit(self): <NEW_LINE> <INDENT> print(self.name.title() + ' is now sitting')
собака садиться по команде
625941ba15fb5d323cde09ad
def test_channel(self): <NEW_LINE> <INDENT> log.debug("Inband IPMI[OPEN]: Channel tests") <NEW_LINE> c = self.set_up() <NEW_LINE> c.run_command(self.ipmi_method + BMC_CONST.IPMI_CHANNEL_AUTHCAP) <NEW_LINE> c.run_command(self.ipmi_method + BMC_CONST.IPMI_CHANNEL_INFO)
It will check basic channel functionalities: info and authentication capabilities.
625941ba55399d3f05588556
def dstringcmp(a, b): <NEW_LINE> <INDENT> if a == b: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> for i, char in enumerate(a): <NEW_LINE> <INDENT> if char == b[i]: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if char == '~': <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> if b[i] == '~': <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> if char.isalpha() and not b[i].isalpha(): <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> if not char.isalpha() and b[i].isalpha(): <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> if ord(char) > ord(b[i]): <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> if ord(char) < ord(b[i]): <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except IndexError: <NEW_LINE> <INDENT> if char == '~': <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> return 1 <NEW_LINE> <DEDENT> if b[len(a)] == '~': <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> return -1
debian package version string section lexical sort algorithm "The lexical comparison is a comparison of ASCII values modified so that all the letters sort earlier than all the non-letters and so that a tilde sorts before anything, even the end of a part."
625941ba091ae35668666e07
def run(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> job = self._inputQueue.get() <NEW_LINE> key = job.key <NEW_LINE> _log.debug('Popped job request %r from the input queue' % key) <NEW_LINE> try: del self._unassignedKey2Job[key] <NEW_LINE> except KeyError: <NEW_LINE> <INDENT> _log.info('Discarded cancelled job request %r' % key) <NEW_LINE> continue <NEW_LINE> <DEDENT> if self.dismissed: <NEW_LINE> <INDENT> self._inputQueue.put(job) <NEW_LINE> _log.debug('Dismissing worker %r' % self.getName()) <NEW_LINE> break <NEW_LINE> <DEDENT> job.process() <NEW_LINE> self._outputQueue.put(job) <NEW_LINE> _log.debug('Added job request %r to the output queue' % job.key)
Poll the input job queue indefinitely or until told to exit. Once a job request has been popped from the input queue, process it and add it to the output queue if it's not cancelled, otherwise discard it.
625941bae5267d203edcdb43
def close(self): <NEW_LINE> <INDENT> if self._env_thread is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._stop_event.set() <NEW_LINE> self._env_thread.join() <NEW_LINE> self._stop_event = None <NEW_LINE> self._env_thread = None
Cleans up resources used by the program.
625941badc8b845886cb53d7
def _ninja(self, name, indent=4, block='_all'): <NEW_LINE> <INDENT> n = NinjaFileCloth(indent=indent) <NEW_LINE> n.rule(name, self.rules[name]) <NEW_LINE> return n.get_block(block)
An internal method used by :`~rules.RuleCloth.fetch()` to process content from :attr:`~rules.RuleCloth.rules` and return :meth:`~cloth.BuildCloth.get_block()` in Ninja format.
625941ba925a0f43d2549d16
def visualize_data_transform(self): <NEW_LINE> <INDENT> logging.debug("Saving out raw input grid") <NEW_LINE> sys.stdout.flush() <NEW_LINE> with torch.no_grad(): <NEW_LINE> <INDENT> for bidx, batch in enumerate(self.display_loader): <NEW_LINE> <INDENT> if bidx == self.example_idx: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> input, *_ = self.preprocess_data(batch) <NEW_LINE> if input.dim() == 6: <NEW_LINE> <INDENT> input = input[:, 0, ...] <NEW_LINE> <DEDENT> if input.shape[-1] != 2: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> req_shape = (input.shape[1]*2, 1, input.shape[2], input.shape[3]) <NEW_LINE> channels = input[0, :, None, ...].transpose(1, 4).contiguous().view(req_shape) <NEW_LINE> grid = torchvision.utils.make_grid(channels, nrow=2, padding=2, normalize=True) <NEW_LINE> grid_np = grid.mul_(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to('cpu', torch.uint8).numpy() <NEW_LINE> grid_pil = Image.fromarray(grid_np) <NEW_LINE> grid_path = self.exp_dir / "grids" / f"raw_grid.png" <NEW_LINE> if self.args.rank == 0: <NEW_LINE> <INDENT> grid_pil.save(grid_path, format="PNG") <NEW_LINE> <DEDENT> logging.info(f"Saved raw input grid to {grid_path.resolve()}") <NEW_LINE> sys.stdout.flush()
Just save to disk the raw input data for an example instance. The two complex numbers are shown side-by-side, and the channel dimension is stacked vertically in order.
625941ba9c8ee82313fbb618
def test_ignore_first(self): <NEW_LINE> <INDENT> expression = "my_varfirst(my_other_var)some_varfirsta)" <NEW_LINE> expected = {"my_var", "my_other_var", "some_var", "a"} <NEW_LINE> self.assertSetEqual(extract_vars(expression), expected)
The substring "first" should always be ignored.
625941bacad5886f8bd26e85
def _generate_items(self, test_spec): <NEW_LINE> <INDENT> item = YamlItem(test_spec["test_name"], self, test_spec, self.fspath) <NEW_LINE> original_marks = test_spec.get("marks", []) <NEW_LINE> if original_marks: <NEW_LINE> <INDENT> fmt_vars = self._get_test_fmt_vars(test_spec) <NEW_LINE> pytest_marks, formatted_marks = _format_test_marks( original_marks, fmt_vars, test_spec["test_name"] ) <NEW_LINE> parametrize_marks = [ i for i in formatted_marks if isinstance(i, dict) and "parametrize" in i ] <NEW_LINE> if parametrize_marks: <NEW_LINE> <INDENT> for new_item in self.get_parametrized_items( test_spec, parametrize_marks, pytest_marks ): <NEW_LINE> <INDENT> yield new_item <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> item.add_markers(pytest_marks) <NEW_LINE> <DEDENT> yield item
Modify or generate tests based on test spec If there are any 'parametrize' marks, this will generate extra tests based on the values Args: test_spec (dict): Test specification Yields: YamlItem: Tavern YAML test
625941bad6c5a10208143eea
@memoized <NEW_LINE> def c(k): <NEW_LINE> <INDENT> if k == 0: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> res = 0 <NEW_LINE> for m in range(k): <NEW_LINE> <INDENT> res += (c(m) * c(k - 1 - m)) / float((m + 1) * (2*m + 1)) <NEW_LINE> <DEDENT> return res
The MacLaurin coefficient for erf_inv.
625941baa05bb46b383ec6c7
def valid_pw(name, password, h): <NEW_LINE> <INDENT> salt = h.split(',')[0] <NEW_LINE> return h == make_pw_hash(name, password, salt)
Check if password is valid for a username
625941ba6e29344779a624b8
def cgroupSet( self, param, value, resource='cpu' ): <NEW_LINE> <INDENT> cmd = 'cgset -r %s.%s=%s /%s' % ( resource, param, value, self.name ) <NEW_LINE> quietRun( cmd ) <NEW_LINE> nvalue = int( self.cgroupGet( param, resource ) ) <NEW_LINE> if nvalue != value: <NEW_LINE> <INDENT> error( '*** error: cgroupSet: %s set to %s instead of %s\n' % ( param, nvalue, value ) ) <NEW_LINE> <DEDENT> return nvalue
Set a cgroup parameter and return its value
625941bafbf16365ca6f6060
def flush(self): <NEW_LINE> <INDENT> self.timer.stop() <NEW_LINE> s = ''.join(self.buffer) <NEW_LINE> if len(s): <NEW_LINE> <INDENT> self.last_time = time.monotonic() <NEW_LINE> self.output.emit(s) <NEW_LINE> <DEDENT> self.buffer = []
Dump everything out of the buffer and send it to console_log.
625941bab5575c28eb68dea1
def set_at(self, pos): <NEW_LINE> <INDENT> is_graphics, gross_pos, new_block = self.operate(pos, self.block_class.set) <NEW_LINE> current = self.parent.PixelCls(*self.parent.get_raw(gross_pos)) <NEW_LINE> if new_block == HalfChars.FULL_BLOCK: <NEW_LINE> <INDENT> if self.context.color == current.foreground: <NEW_LINE> <INDENT> new_pixel = self.PixelCls(HalfChars.FULL_BLOCK, self.context.color, self.context.background, self.context.effects) <NEW_LINE> <DEDENT> elif current.foreground is DEFAULT_FG: <NEW_LINE> <INDENT> new_block = HalfChars.UPPER_HALF_BLOCK if pos[1] % 2 == 1 else HalfChars.LOWER_HALF_BLOCK <NEW_LINE> new_pixel = self.PixelCls(new_block, current.foreground, self.context.color, self.context.effects) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_block = HalfChars.UPPER_HALF_BLOCK if pos[1] % 2 == 0 else HalfChars.LOWER_HALF_BLOCK <NEW_LINE> new_pixel = self.PixelCls(new_block, self.context.color, current.foreground, self.context.effects) <NEW_LINE> <DEDENT> <DEDENT> elif current.value == HalfChars.EMPTY or not is_graphics: <NEW_LINE> <INDENT> new_pixel = self.PixelCls(new_block, self.context.color, current.background, self.context.effects) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_pixel = current._replace(foreground=self.context.color, effects=self.context.effects) <NEW_LINE> <DEDENT> self.parent[gross_pos] = new_pixel
Sets pixel at given coordinate Args: - pos (2-sequence): pixel coordinate To be used as a callback to ``.draw.set`` - but there are no drawbacks in being called directly.
625941ba21a7993f00bc7b8d
def start_DAW(): <NEW_LINE> <INDENT> DAW_PATH = 'C:\Program Files\PreSonus\Studio One 4\\Studio One.exe' <NEW_LINE> subprocess.Popen([DAW_PATH]) <NEW_LINE> keyboard.send('space', do_press=True, do_release=True)
Documentation
625941ba50812a4eaa59c1c8
def NeutraliseCharges(smiles, reactions=None): <NEW_LINE> <INDENT> global _reactions <NEW_LINE> if reactions is None: <NEW_LINE> <INDENT> if _reactions is None: <NEW_LINE> <INDENT> _reactions = _InitialiseNeutralisationReactions() <NEW_LINE> <DEDENT> reactions = _reactions <NEW_LINE> <DEDENT> mol = Chem.MolFromSmiles(smiles) <NEW_LINE> replaced = False <NEW_LINE> for i, (reactant, product) in enumerate(reactions): <NEW_LINE> <INDENT> while mol.HasSubstructMatch(reactant): <NEW_LINE> <INDENT> replaced = True <NEW_LINE> rms = AllChem.ReplaceSubstructs(mol, reactant, product) <NEW_LINE> mol = rms[0] <NEW_LINE> <DEDENT> <DEDENT> if replaced: <NEW_LINE> <INDENT> return (Chem.MolToSmiles(mol, True), True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (smiles, False)
Contribution from Hans de Winter
625941ba7b180e01f3dc46a7
def test_instance_group_update_no_replace(self): <NEW_LINE> <INDENT> updt_template = json.loads(copy.deepcopy(ig_tmpl_with_updt_policy)) <NEW_LINE> group = updt_template['Resources']['JobServerGroup'] <NEW_LINE> policy = group['UpdatePolicy']['RollingUpdate'] <NEW_LINE> policy['MinInstancesInService'] = '1' <NEW_LINE> policy['MaxBatchSize'] = '3' <NEW_LINE> policy['PauseTime'] = 'PT0S' <NEW_LINE> config = updt_template['Resources']['JobServerConfig'] <NEW_LINE> config['Properties']['InstanceType'] = 'm1.large' <NEW_LINE> self.update_instance_group(ig_tmpl_with_updt_policy, json.dumps(updt_template), num_updates_expected_on_updt=10, num_creates_expected_on_updt=0, num_deletes_expected_on_updt=0, update_replace=False)
Test simple update only and no replace (i.e. updated instance flavor in Launch Configuration) with no conflict in batch size and minimum instances in service.
625941bac432627299f04ae7
def setZeroes(self, matrix: List[List[int]]) -> None: <NEW_LINE> <INDENT> pos = [] <NEW_LINE> for i in range(len(matrix)): <NEW_LINE> <INDENT> for j in range(len(matrix[0])): <NEW_LINE> <INDENT> if matrix[i][j] == 0: <NEW_LINE> <INDENT> pos.append([i, j]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for p in pos: <NEW_LINE> <INDENT> for i in range(len(matrix)): <NEW_LINE> <INDENT> matrix[i][p[1]] = 0 <NEW_LINE> <DEDENT> for j in range(len(matrix[0])): <NEW_LINE> <INDENT> matrix[p[0]][j] = 0
Do not return anything, modify matrix in-place instead.
625941ba460517430c394030
def make_swagger_name(attribute_name): <NEW_LINE> <INDENT> if attribute_name == 'ref': <NEW_LINE> <INDENT> return "$ref" <NEW_LINE> <DEDENT> if attribute_name.startswith("x_"): <NEW_LINE> <INDENT> return "x-" + camelize(attribute_name[2:], uppercase_first_letter=False) <NEW_LINE> <DEDENT> return camelize(attribute_name.rstrip('_'), uppercase_first_letter=False)
Convert a python variable name into a Swagger spec attribute name. In particular, * if name starts with ``x_``, return ``x-{camelCase}`` * if name is ``ref``, return ``$ref`` * else return the name converted to camelCase, with trailing underscores stripped :param str attribute_name: python attribute name :return: swagger name
625941ba167d2b6e31218a39
def posFuturesPossibles(self,plateau,protective): <NEW_LINE> <INDENT> l = [] <NEW_LINE> if self.color == 1: <NEW_LINE> <INDENT> avance = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> avance = -1 <NEW_LINE> <DEDENT> if plateau.inbounds(self.pos[0]+avance,self.pos[1]) : <NEW_LINE> <INDENT> piece = plateau.getPiece(self.pos[0]+avance,self.pos[1]) <NEW_LINE> if piece == None: <NEW_LINE> <INDENT> l += [(self.pos[0]+avance,self.pos[1])] <NEW_LINE> <DEDENT> <DEDENT> if self.firstMove and plateau.inbounds(self.pos[0]+avance+avance,self.pos[1]): <NEW_LINE> <INDENT> piece = plateau.getPiece(self.pos[0]+avance+avance,self.pos[1]) <NEW_LINE> if piece == None: <NEW_LINE> <INDENT> l += [(self.pos[0]+avance+avance,self.pos[1])] <NEW_LINE> <DEDENT> <DEDENT> if plateau.inbounds(self.pos[0]+avance,self.pos[1]+1) : <NEW_LINE> <INDENT> piece = plateau.getPiece(self.pos[0]+avance,self.pos[1]+1) <NEW_LINE> if (piece != None and piece.color != self.color) or protective: <NEW_LINE> <INDENT> l += [(self.pos[0]+avance,self.pos[1]+1)] <NEW_LINE> <DEDENT> <DEDENT> if plateau.inbounds(self.pos[0]+avance,self.pos[1]-1) : <NEW_LINE> <INDENT> piece = plateau.getPiece(self.pos[0]+avance,self.pos[1]-1) <NEW_LINE> if (piece != None and piece.color != self.color) or protective: <NEW_LINE> <INDENT> l += [(self.pos[0]+avance,self.pos[1]-1)] <NEW_LINE> <DEDENT> <DEDENT> return l
Retourne la liste des positions possibles à partir de la position actuelle.
625941ba76e4537e8c35151b
def getAllRZMLTestFiles(): <NEW_LINE> <INDENT> filePaths = list() <NEW_LINE> searchDir = p.abspath('testFiles') <NEW_LINE> if p.isdir(searchDir): <NEW_LINE> <INDENT> fileNames = os.listdir(searchDir) <NEW_LINE> for fileName in fileNames: <NEW_LINE> <INDENT> if fileName.endswith('.rzml'): <NEW_LINE> <INDENT> filePath = p.join(searchDir, fileName) <NEW_LINE> if p.isfile(filePath): <NEW_LINE> <INDENT> filePaths.append(filePath) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> msg = ("Error: Could not find testFiles, " "please run this script from the 'bin' directory.") <NEW_LINE> print(msg) <NEW_LINE> <DEDENT> return filePaths
Get all RZML files for testing.
625941ba5fcc89381b1e1567
def dfs(start, goal, depth=10): <NEW_LINE> <INDENT> fringe=[] <NEW_LINE> fringe.append(create_node(start, None, None, 1, 0)) <NEW_LINE> while(True): <NEW_LINE> <INDENT> current=fringe.pop() <NEW_LINE> if current.state == goal: <NEW_LINE> <INDENT> CNode=current <NEW_LINE> operators=[] <NEW_LINE> while CNode.depth !=1: <NEW_LINE> <INDENT> operators.insert(0,CNode.operator) <NEW_LINE> CNode=CNode.parent <NEW_LINE> <DEDENT> return operators <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if current.depth<depth: <NEW_LINE> <INDENT> fringe.extend(expand_node(current))
Performs a depth first search from the start state to the goal. Depth param is optional.
625941bad18da76e23532375
def combine_losses(self, aux_losses, loss_weights): <NEW_LINE> <INDENT> total_loss = None <NEW_LINE> for key in aux_losses: <NEW_LINE> <INDENT> weight = 1 <NEW_LINE> if key in loss_weights: <NEW_LINE> <INDENT> weight = loss_weights[key] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("Auxiliary weight not defined for " + str(key)) <NEW_LINE> <DEDENT> this_loss = aux_losses[key] * weight <NEW_LINE> if total_loss is None: <NEW_LINE> <INDENT> total_loss = this_loss <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> total_loss += this_loss <NEW_LINE> <DEDENT> <DEDENT> if total_loss is None: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return total_loss
Takes a dictionary of auxiliary losses and a dictionary of associated weights, where weights and losses are identified by the keys of the auxiliary objectives from which they came from. Outputs a single loss value, which is a convex combination of auxiliary losses with the given weights :param aux_losses: :param loss_weights: :return:
625941ba2c8b7c6e89b35666
def get_winning_move(board, player): <NEW_LINE> <INDENT> possible_moves = get_possible_moves(board) <NEW_LINE> if not possible_moves: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> for move in possible_moves: <NEW_LINE> <INDENT> tmp_board = copy.deepcopy(board) <NEW_LINE> tmp_board[move] = player <NEW_LINE> if winner(tmp_board) != False and winner(tmp_board) != TIE: <NEW_LINE> <INDENT> return move <NEW_LINE> <DEDENT> <DEDENT> return None
Retrieves a winning move for player on board, None of such move doesn't exists
625941ba090684286d50eb84
def test_student_view_data(self): <NEW_LINE> <INDENT> student_view_data = self.vr_block.student_view_data() <NEW_LINE> self.assertEqual(student_view_data, self.vr_data)
Test the results of student_view_data
625941ba23e79379d52ee40a
def control_forward_speed(self, speed): <NEW_LINE> <INDENT> if speed < -30 or 30 < speed: <NEW_LINE> <INDENT> raise MecbotRangeError("speed") <NEW_LINE> <DEDENT> self.__write("VCX" + str(round(speed, 3)))
Control forward speed. :param float speed: Forward speed (-30~30)[m/s] :raises MecbotRangeError: An out-of-range value has been entered.
625941baadb09d7d5db6c636
def restart(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.stop() <NEW_LINE> <DEDENT> except NotImplementedError: <NEW_LINE> <INDENT> raise NotImplementedError('"restart" method not available for ' 'service %s' % self.name) <NEW_LINE> <DEDENT> self.start() <NEW_LINE> return self.status()
First, call :py:func:`stop() <piro.service.Service.stop>` on the service, then call :py:func:`start() <piro.service.Service.start>` on the service. Finally return the result of calling :py:func:`status() <piro.service.Service.status>` on the service. The restart action does not have any hooks of its own - add hooks to :py:func:`start() <piro.service.Service.start>` and/or :py:func:`stop() <piro.service.Service.stop>` instead.
625941ba2eb69b55b151c74f
def InsertTestMethodNameHere(self): <NEW_LINE> <INDENT> self.comment('Step1: Insert test step description') <NEW_LINE> self.comment('Step2: Insert test step description') <NEW_LINE> self.comment('Step3: Insert test step description')
Insert brief description of the test case 1. Insert test step description here 2. Insert test step description here 3. Insert test step description here @tcId Insert test case name here
625941ba7b25080760e392fe
def SetShutdownFlag(): <NEW_LINE> <INDENT> global _ShutdownFlag <NEW_LINE> _ShutdownFlag = True
Set flag to indicate that no need to send anything anymore.
625941ba0383005118ecf488
def test_attmissingdisposition3(self, header_checker): <NEW_LINE> <INDENT> header_checker.check_ignored('"foo; filename=bar;baz"; filename=qux')
Disposition type missing, filename "qux". Can it be more broken? (Probably) This is invalid, so UAs should ignore it.
625941ba3617ad0b5ed67da3
@log_with(log) <NEW_LINE> @policy_blueprint.route('/check', methods=['GET']) <NEW_LINE> def check_policy_api(): <NEW_LINE> <INDENT> res = {} <NEW_LINE> param = getLowerParams(request.all_data) <NEW_LINE> user = getParam(param, "user", required) <NEW_LINE> realm = getParam(param, "realm", required) <NEW_LINE> scope = getParam(param, "scope", required) <NEW_LINE> action = getParam(param, "action", required) <NEW_LINE> client = getParam(param, "client", optional) <NEW_LINE> resolver = getParam(param, "resolver", optional) <NEW_LINE> P = PolicyClass() <NEW_LINE> policies = P.get_policies(user=user, realm=realm, resolver=resolver, scope=scope, action=action, client=client, active=True) <NEW_LINE> if len(policies) > 0: <NEW_LINE> <INDENT> res["allowed"] = True <NEW_LINE> res["policy"] = policies <NEW_LINE> policy_names = [] <NEW_LINE> for pol in policies: <NEW_LINE> <INDENT> policy_names.append(pol.get("name")) <NEW_LINE> <DEDENT> g.audit_object.log({'info': "allowed by policy %s" % policy_names}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> res["allowed"] = False <NEW_LINE> res["info"] = "No policies found" <NEW_LINE> <DEDENT> g.audit_object.log({"success": True, 'action_detail': "action = %s, realm = %s, scope = " "%s" % (action, realm, scope) }) <NEW_LINE> return send_result(res)
This function checks, if the given parameters would match a defined policy or not. :queryparam user: the name of the user :queryparam realm: the realm of the user or the realm the administrator want to do administrative tasks on. :queryparam resolver: the resolver of a user :queryparam scope: the scope of the policy :queryparam action: the action that is done - if applicable :queryparam client: the client, from which this request would be issued :querytype client: IP Address :return: a json result with the keys allowed and policy in the value key :rtype: json :status 200: Policy created or modified. :status 401: Authentication failed **Example request**: .. sourcecode:: http GET /policy/check?user=admin&realm=r1&client=172.16.1.1 HTTP/1.1 Host: example.com Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "id": 1, "jsonrpc": "2.0", "result": { "status": true, "value": { "pol_update_del": { "action": "enroll", "active": true, "client": "172.16.0.0/16", "name": "pol_update_del", "realm": "r1", "resolver": "test", "scope": "selfservice", "time": "", "user": "admin" } } }, "version": "privacyIDEA unknown" }
625941ba9f2886367277a734
def __init__(self, ai_game): <NEW_LINE> <INDENT> self.settings = ai_game.settings <NEW_LINE> self.high_score = 0 <NEW_LINE> self.reset_stats() <NEW_LINE> self.game_active = False
Initialize statistics.
625941ba3cc13d1c6d3c7227
@parameterized.expand(all_yfs) <NEW_LINE> def test_all_yaml_files(yf): <NEW_LINE> <INDENT> print("\nTesting {}".format(yf)) <NEW_LINE> folder_name = yf.split("/")[-2] <NEW_LINE> with open(yf) as f: <NEW_LINE> <INDENT> metadata = yaml.load(f, Loader=yaml.FullLoader) <NEW_LINE> <DEDENT> assert metadata['dataset'] == folder_name <NEW_LINE> assert metadata['task'] in ["classification", "regression"]
Check basic information in yaml files.
625941ba50485f2cf553cc3c
def _request(self, function, params, service='shodan', method='get'): <NEW_LINE> <INDENT> params['key'] = self.api_key <NEW_LINE> base_url = { 'shodan': self.base_url, 'exploits': self.base_exploits_url, }.get(service, 'shodan') <NEW_LINE> if self._api_query_time is not None and self.api_rate_limit > 0: <NEW_LINE> <INDENT> while (1.0 / self.api_rate_limit) + self._api_query_time >= time.time(): <NEW_LINE> <INDENT> time.sleep(0.1 / self.api_rate_limit) <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> method = method.lower() <NEW_LINE> if method == 'post': <NEW_LINE> <INDENT> data = self._session.post(base_url + function, params) <NEW_LINE> <DEDENT> elif method == 'put': <NEW_LINE> <INDENT> data = self._session.put(base_url + function, params=params) <NEW_LINE> <DEDENT> elif method == 'delete': <NEW_LINE> <INDENT> data = self._session.delete(base_url + function, params=params) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data = self._session.get(base_url + function, params=params) <NEW_LINE> <DEDENT> self._api_query_time = time.time() <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> raise APIError('Unable to connect to Shodan') <NEW_LINE> <DEDENT> if data.status_code == 401: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> error = data.json()['error'] <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> if data.text.startswith('<'): <NEW_LINE> <INDENT> error = 'Invalid API key' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> error = u'{}'.format(e) <NEW_LINE> <DEDENT> <DEDENT> raise APIError(error) <NEW_LINE> <DEDENT> elif data.status_code == 403: <NEW_LINE> <INDENT> raise APIError('Access denied (403 Forbidden)') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> data = data.json() <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise APIError('Unable to parse JSON response') <NEW_LINE> <DEDENT> if type(data) == dict and 'error' in data: <NEW_LINE> <INDENT> raise APIError(data['error']) <NEW_LINE> <DEDENT> return data
General-purpose function to create web requests to SHODAN. Arguments: function -- name of the function you want to execute params -- dictionary of parameters for the function Returns A dictionary containing the function's results.
625941baa4f1c619b28afee4
def getSystemAppList(self): <NEW_LINE> <INDENT> sysApp = [] <NEW_LINE> result = self.shell_return("pm list packages -s") <NEW_LINE> result_list = result.split("\r\n") <NEW_LINE> for packages in result_list: <NEW_LINE> <INDENT> package = packages.split(":")[-1].strip() <NEW_LINE> if package: <NEW_LINE> <INDENT> sysApp.append(package) <NEW_LINE> <DEDENT> <DEDENT> return sysApp
获取设备中安装的系统应用包名列表
625941ba3eb6a72ae02ec378
def _set_value(self, x): <NEW_LINE> <INDENT> self.__cached_value__ = x
Set the cached value on the class
625941bad53ae8145f87a119
def ShouldSerializeContent(self): <NEW_LINE> <INDENT> pass
ShouldSerializeContent(self: ContentControl) -> bool Indicates whether the System.Windows.Controls.ContentControl.Content property should be persisted. Returns: true if the System.Windows.Controls.ContentControl.Content property should be persisted; otherwise,false.
625941ba8e05c05ec3eea215
@pytest.inlineCallbacks <NEW_LINE> def test_deleteNs(kubeConfig): <NEW_LINE> <INDENT> namespace = 'test-se-com' <NEW_LINE> pCall = patch.object(lib.TxKubernetesClient, 'call') <NEW_LINE> pApiMethod = patch.object(lib.client, 'CoreV1Api', return_value=Mock( delete_namespace='', ), autospec=True, ) <NEW_LINE> with pApiMethod as mApiMethod, pCall as mCall: <NEW_LINE> <INDENT> yield lib.deleteNamespace(namespace) <NEW_LINE> mApiMethod.assert_called_once() <NEW_LINE> mCall.assert_called_once()
Do I delete a namespace kubernetes resource in a namespace?
625941baa17c0f6771cbdef7
def get_collection_idx(self, db_set): <NEW_LINE> <INDENT> if db_set.lower() == 'train' or db_set.lower() == 'training': <NEW_LINE> <INDENT> return np.arange(len(self.train_images), dtype=np.int32) <NEW_LINE> <DEDENT> elif db_set.lower() == 'validation' or db_set.lower() == 'val': <NEW_LINE> <INDENT> raise ValueError('There is no validation set for {}.'.format(self.name)) <NEW_LINE> <DEDENT> elif db_set.lower() == 'testing' or db_set.lower() == 'test': <NEW_LINE> <INDENT> return np.arange(len(self.test_images), dtype=np.int32) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("'db_set' unrecognized." "Expected 'train', 'training', 'validation', 'val', 'testing', 'test'" "Got {}".format(db_set))
Get the set of collection images for retrieval tasks. :param db_set: string containing either 'train', 'training', 'validation', 'val', 'testing' or 'test'. :return: a nd-array of the collection indexes.
625941ba4527f215b584c2fe
def dump_security_group(self): <NEW_LINE> <INDENT> __endpoint = self.__endpoints["NetworkService"]+ '/v2.0/security-groups' <NEW_LINE> __res=self.get(__endpoint) <NEW_LINE> print(json.dumps(__res, indent=2, sort_keys=True))
dump security group
625941ba21a7993f00bc7b8e
def get_index(shape, position): <NEW_LINE> <INDENT> assert position < size(shape) <NEW_LINE> if ndim(shape)==1: <NEW_LINE> <INDENT> return (position,) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> subshape = shape[1:] <NEW_LINE> index = position//size(subshape) <NEW_LINE> return (index, ) + get_index(subshape, position-index*size(subshape))
Return the index in the multidimensional array that is corresponds to the element in the given position in the linear ordered. Parameters ---------- shape : tuple The shape of the input array position : int The position in the linear ordering Returns ------- index : tuple (same number of elements as shape) The index in the multidimensional array specified by the position in linear order Notes ----- You only have to implement this using row major order: https://en.wikipedia.org/wiki/Row-major_order Make sure to check that the position is valid: assert position < size(shape) Exercises --------- >>> shape = (2,) >>> get_index(shape, 1) (1,) >>> shape = (2, 2, 2) >>> get_index(shape, 4) (1, 0, 0) >>> get_index(shape, 2) (0, 1, 0) >>> get_index((4, 5, 2, 1, 3), 17) (0, 2, 1, 0, 2)
625941babde94217f3682c9f
def test_enrollment_cap(self): <NEW_LINE> <INDENT> course = CourseFactory.create( metadata={ "max_student_enrollments_allowed": 1, "display_coursenumber": "buyme", } ) <NEW_LINE> self._set_ecomm(course) <NEW_LINE> self.setup_user() <NEW_LINE> url = reverse('about_course', args=[text_type(course.id)]) <NEW_LINE> resp = self.client.get(url) <NEW_LINE> self.assertEqual(resp.status_code, 200) <NEW_LINE> self.assertIn("Add buyme to Cart <span>($10 USD)</span>", resp.content) <NEW_LINE> CourseEnrollment.enroll(self.user, course.id) <NEW_LINE> email = '[email protected]' <NEW_LINE> password = 'bar' <NEW_LINE> username = 'test_second' <NEW_LINE> self.create_account(username, email, password) <NEW_LINE> self.activate_user(email) <NEW_LINE> self.login(email, password) <NEW_LINE> resp = self.client.get(url) <NEW_LINE> self.assertEqual(resp.status_code, 200) <NEW_LINE> self.assertIn("Course is full", resp.content) <NEW_LINE> self.assertNotIn("Add buyme to Cart ($10)", resp.content)
Make sure that capped enrollments work even with paywalled courses
625941ba5510c4643540f29a
def set_sentence(self, sent): <NEW_LINE> <INDENT> sent_mecab_info = mecab.jap_text_info(sent) <NEW_LINE> self.original_sentence = sent_mecab_info[0] <NEW_LINE> self.sentence_info = sent_mecab_info[1]
Sets the sentence as a string, to check against the rule
625941ba5fdd1c0f98dc00d5
def __init__(self, cfg_directory_path, is_resume, is_reset_elasticsearch, is_reset_json, is_reset_mysql, is_no_confirm, library_mode=False): <NEW_LINE> <INDENT> configure_logging({"LOG_LEVEL": "ERROR"}) <NEW_LINE> self.log = logging.getLogger(__name__) <NEW_LINE> self.shall_resume = is_resume <NEW_LINE> self.no_confirm = is_no_confirm <NEW_LINE> self.library_mode = library_mode <NEW_LINE> os.environ['CColon'] = os.path.abspath(os.path.dirname(__file__)) <NEW_LINE> self.set_stop_handler() <NEW_LINE> self.thread_event = threading.Event() <NEW_LINE> if cfg_directory_path: <NEW_LINE> <INDENT> self.cfg_directory_path = self.get_expanded_path(cfg_directory_path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.cfg_directory_path = self.get_expanded_path(self.config_directory_default_path) <NEW_LINE> <DEDENT> self.init_config_file_path_if_empty() <NEW_LINE> self.cfg_file_path = self.cfg_directory_path + self.config_file_default_name <NEW_LINE> self.cfg = CrawlerConfig.get_instance() <NEW_LINE> self.cfg.setup(self.cfg_file_path) <NEW_LINE> self.mysql = self.cfg.section("MySQL") <NEW_LINE> self.elasticsearch = self.cfg.section("Elasticsearch") <NEW_LINE> if is_reset_mysql: <NEW_LINE> <INDENT> self.reset_mysql() <NEW_LINE> <DEDENT> if is_reset_json: <NEW_LINE> <INDENT> self.reset_files() <NEW_LINE> <DEDENT> if is_reset_elasticsearch: <NEW_LINE> <INDENT> self.reset_elasticsearch() <NEW_LINE> <DEDENT> if is_reset_elasticsearch or is_reset_json or is_reset_mysql: <NEW_LINE> <INDENT> sys.exit(0) <NEW_LINE> <DEDENT> self.json_file_path = self.cfg_directory_path + self.cfg.section('Files')['url_input_file_name'] <NEW_LINE> self.json = JsonConfig.get_instance() <NEW_LINE> self.json.setup(self.json_file_path) <NEW_LINE> self.crawler_list = self.CrawlerList() <NEW_LINE> self.daemon_list = self.DaemonList() <NEW_LINE> self.__single_crawler = self.get_abs_file_path("./single_crawler.py", True, False) <NEW_LINE> self.manage_crawlers()
The constructor of the main class, thus the real entry point to the tool. :param cfg_file_path: :param is_resume: :param is_reset_elasticsearch: :param is_reset_json: :param is_reset_mysql: :param is_no_confirm:
625941ba7cff6e4e81117829
def handleFrame(self, *args): <NEW_LINE> <INDENT> return _osgGA.FirstPersonManipulator_handleFrame(self, *args)
handleFrame(FirstPersonManipulator self, GUIEventAdapter ea, GUIActionAdapter us) -> bool
625941ba4e696a04525c92f0
def new_game(game_id): <NEW_LINE> <INDENT> free_spaces = False <NEW_LINE> if request.form['free'] == "true": <NEW_LINE> <INDENT> free_spaces = True <NEW_LINE> <DEDENT> app.games[game_id] = Game(app.buzzwords, free_spaces) <NEW_LINE> return f'new game: {game_id}'
Create a new game page.
625941ba55399d3f05588557
def test_detail(self): <NEW_LINE> <INDENT> response = self.client.get(reverse(self.urlprefix + "_detail", kwargs={ "slug": self.slug, })) <NEW_LINE> self.assertEqual(response.status_code, 200)
Test object detail view.
625941ba32920d7e50b28070
def test_enable_gps_via_settings_app(self): <NEW_LINE> <INDENT> settings = Settings(self.marionette) <NEW_LINE> settings.launch() <NEW_LINE> settings.disable_gps() <NEW_LINE> self.assertFalse(self.data_layer.get_setting('geolocation.enabled')) <NEW_LINE> settings.enable_gps() <NEW_LINE> self.assertTrue(self.data_layer.get_setting('geolocation.enabled'))
Enable GPS via the Settings app https://moztrap.mozilla.org/manage/case/2885/
625941ba56b00c62f0f144fb
def forward(self, input_data): <NEW_LINE> <INDENT> in_arg = self.converter(input_data) <NEW_LINE> return self.network.forwardTest(in_arg)
return output arguments which are the Outputs() in network configure. input_data: py_paddle input data. call forward.
625941ba7c178a314d6ef2fd
def _NormalizeMessageFiles(self, message_files): <NEW_LINE> <INDENT> normalized_message_files = set() <NEW_LINE> paths_lower = set() <NEW_LINE> for path in message_files: <NEW_LINE> <INDENT> path_lower = path.lower() <NEW_LINE> if path_lower not in paths_lower: <NEW_LINE> <INDENT> paths_lower.add(path_lower) <NEW_LINE> normalized_message_files.add(path) <NEW_LINE> <DEDENT> <DEDENT> return normalized_message_files
Normalizes the message files. Args: message_files (list[str]): paths of the message files. Returns: set[str]: normalized paths of the message files.
625941ba5e10d32532c5edd2
def upload_planned_rps(self): <NEW_LINE> <INDENT> df = self.parse_stpd() <NEW_LINE> if not df.empty: <NEW_LINE> <INDENT> self.rps_metrics['planned_rps_metrics_obj'] = self.data_session.new_true_metric( meta=dict(self.meta, name=self.PLANNED_RPS_METRICS_NAME, source='tank'), raw=True, aggregate=False, parent=None, case=None) <NEW_LINE> self.rps_metrics['planned_rps_metrics_obj'].put(df)
Uploads planned rps as a raw metric
625941ba090684286d50eb85
def _process_route(route): <NEW_LINE> <INDENT> class RouteStatus(enum.IntEnum): <NEW_LINE> <INDENT> Active = 0x0 <NEW_LINE> Discovery_Underway = 0x1 <NEW_LINE> Discovery_Failed = 0x2 <NEW_LINE> Inactive = 0x3 <NEW_LINE> Validation_Underway = 0x4 <NEW_LINE> <DEDENT> res = {} <NEW_LINE> res['destination'] = '0x{:04x}'.format(route.DstNWK) <NEW_LINE> res['next_hop'] = '0x{:04x}'.format(route.NextHop) <NEW_LINE> raw = route.RouteStatus & 0x07 <NEW_LINE> try: <NEW_LINE> <INDENT> cooked = RouteStatus(raw).name <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> cooked = 'reserved_{:02x}'.format(raw) <NEW_LINE> <DEDENT> res['status'] = cooked <NEW_LINE> res['memory_constrained'] = bool((route.RouteStatus >> 3) & 0x01) <NEW_LINE> res['many_to_one'] = bool((route.RouteStatus >> 4) & 0x01) <NEW_LINE> res['route_record_required'] = bool((route.RouteStatus >> 5) & 0x01) <NEW_LINE> return res
Return a dict representing routing entry.
625941badd821e528d63b04e
def check_keyup_events(event, rocket): <NEW_LINE> <INDENT> if event.key == pygame.K_UP: <NEW_LINE> <INDENT> rocket.moving_up = False <NEW_LINE> <DEDENT> if event.key == pygame.K_DOWN: <NEW_LINE> <INDENT> rocket.moving_down = False
Respond to key releases
625941ba21bff66bcd6847f9
def set_console_info(entity, uid, extras): <NEW_LINE> <INDENT> address = entity.links[0].attributes['occi.networkinterface.address'] <NEW_LINE> ssh_console_present = False <NEW_LINE> vnc_console_present = False <NEW_LINE> comp_sch = 'http://schemas.openstack.org/occi/infrastructure/compute#' <NEW_LINE> for link in entity.links: <NEW_LINE> <INDENT> if link.target.kind.term == "ssh_console" and link.target.kind .scheme == comp_sch: <NEW_LINE> <INDENT> ssh_console_present = True <NEW_LINE> <DEDENT> elif link.target.kind.term == "vnc_console" and link.target.kind .scheme == comp_sch: <NEW_LINE> <INDENT> vnc_console_present = True <NEW_LINE> <DEDENT> <DEDENT> registry = extras['registry'] <NEW_LINE> if not ssh_console_present: <NEW_LINE> <INDENT> identifier = str(uuid.uuid4()) <NEW_LINE> ssh_console = core_model.Resource( identifier, occi_future.SSH_CONSOLE, [], links=None, summary='', title='') <NEW_LINE> ssh_console.attributes['occi.core.id'] = identifier <NEW_LINE> ssh_console.attributes['org.openstack.compute.console.ssh'] = 'ssh://' + address + ':22' <NEW_LINE> registry.add_resource(identifier, ssh_console, extras) <NEW_LINE> identifier = str(uuid.uuid4()) <NEW_LINE> ssh_console_link = core_model.Link( identifier, occi_future.CONSOLE_LINK, [], entity, ssh_console) <NEW_LINE> ssh_console_link.attributes['occi.core.id'] = identifier <NEW_LINE> registry.add_resource(identifier, ssh_console_link, extras) <NEW_LINE> entity.links.append(ssh_console_link) <NEW_LINE> <DEDENT> if not vnc_console_present: <NEW_LINE> <INDENT> console = vm.get_vnc(uid, extras['nova_ctx']) <NEW_LINE> if console is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> identifier = str(uuid.uuid4()) <NEW_LINE> vnc_console = core_model.Resource( identifier, occi_future.VNC_CONSOLE, [], links=None, summary='', title='') <NEW_LINE> vnc_console.attributes['occi.core.id'] = identifier <NEW_LINE> vnc_console.attributes['org.openstack.compute.console.vnc'] = console['url'] <NEW_LINE> registry.add_resource(identifier, vnc_console, extras) <NEW_LINE> identifier = str(uuid.uuid4()) <NEW_LINE> vnc_console_link = core_model.Link( identifier, occi_future.CONSOLE_LINK, [], entity, vnc_console) <NEW_LINE> vnc_console_link.attributes['occi.core.id'] = identifier <NEW_LINE> registry.add_resource(identifier, vnc_console_link, extras) <NEW_LINE> entity.links.append(vnc_console_link)
Adds console access information to the resource.
625941ba1b99ca400220a955
def icurvature(segment, kappa): <NEW_LINE> <INDENT> z = segment.poly() <NEW_LINE> x, y = real(z), imag(z) <NEW_LINE> dx, dy = x.deriv(), y.deriv() <NEW_LINE> ddx, ddy = dx.deriv(), dy.deriv() <NEW_LINE> p = kappa**2*(dx**2 + dy**2)**3 - (dx*ddy - ddx*dy)**2 <NEW_LINE> return polyroots01(p)
returns a list of t-values such that 0 <= t<= 1 and seg.curvature(t) = kappa.
625941ba16aa5153ce36231c
def get_grid_mask(lon, lat, lonlim=None, latlim=None): <NEW_LINE> <INDENT> mask = np.ones(lon.shape, bool) <NEW_LINE> if lonlim is not None: <NEW_LINE> <INDENT> lon = np.mod(lon, 360) <NEW_LINE> lonlim = np.mod(lonlim,360) <NEW_LINE> if np.diff(lonlim) > 0: <NEW_LINE> <INDENT> mask &= (lon >= lonlim[0]) & (lon <= lonlim[1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mask &= (lon >= lonlim[0]) | (lon <= lonlim[1]) <NEW_LINE> <DEDENT> <DEDENT> if latlim is not None: <NEW_LINE> <INDENT> mask &= (lat >= latlim[0]) & (lat <= latlim[1]) <NEW_LINE> <DEDENT> if not mask.any(): <NEW_LINE> <INDENT> raise ValueError('All masked.') <NEW_LINE> <DEDENT> return mask
Mask the region confined by `lonlim` and `latlim` Parameters ---------- lon, lat : ndarrays lon, lat grid lonlim, latlim : tup limits for region Returns ------- bool mask
625941ba6fb2d068a760ef3e
def get_file_list(path, extension): <NEW_LINE> <INDENT> return sorted([ "{}/{}".format(dir_path, file_name)[2:] for dir_path, dir_names, file_names in os.walk(path) for file_name in file_names if file_name.endswith(extension) ])
Get a sorted list of full file names (with path) in a given `path` folder having a given `extension`
625941ba99cbb53fe6792a8b
def get_value(self) -> int: <NEW_LINE> <INDENT> return self.positive_examples
Gets the number of positive examples of the EpsilonBandit. Returns: The number of positive examples of the EpsilonBandit.
625941ba15fb5d323cde09ae
def page(self, code): <NEW_LINE> <INDENT> return Page(self, code)
Given a page code, return a new Page object. :param code: page code :type code: str or unicode :return: Page object :rtype: defoe.alto.page.Page
625941ba45492302aab5e164
def content(self, configuration): <NEW_LINE> <INDENT> lines = [ "# Set to the hostname of this machine", "hostname=\"{0}\"".format(configuration["hostname"].split('.', 1)[0]), ] <NEW_LINE> return { self.confd_hostname_path: lines }
Generated content of this configurator as a dictionary. ### Arguments Argumnet | Description -------- | ----------- configuration | Configuration settings to be applied by this configurator (dict) ### Description Provides the contents of /etc/conf.d/hostname.
625941ba498bea3a759b9955
def getMvMat(self, e, actOri): <NEW_LINE> <INDENT> up = Vector(0, 1, 0).multMatrix(actOri.T).normalized() <NEW_LINE> c = Vector(0, 0, 1).multMatrix(actOri.T) <NEW_LINE> a = e.copy() <NEW_LINE> a[1] += self.height <NEW_LINE> ce = a + c <NEW_LINE> a = a - c * self.factor <NEW_LINE> return geo.lookAtMatrix(a[0], a[1], a[2], ce[0], ce[1], ce[2], up[0], up[1], up[2])
Errechnet ModelviewMatrixTransformation @param e: standpunkt helicopter @param actOri: aktuelle Ausrichtung des Helicopters
625941ba566aa707497f441d
@_dispatch.add_dispatch_list <NEW_LINE> @tf_export('n_in_polymorphic_twice') <NEW_LINE> def n_in_polymorphic_twice(a, b, name=None): <NEW_LINE> <INDENT> _ctx = _context._context or _context.context() <NEW_LINE> if _ctx is not None and _ctx._thread_local_data.is_eager: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._thread_local_data.device_name, "NInPolymorphicTwice", name, _ctx._post_execution_callbacks, a, b) <NEW_LINE> return _result <NEW_LINE> <DEDENT> except _core._FallbackException: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return n_in_polymorphic_twice_eager_fallback( a, b, name=name, ctx=_ctx) <NEW_LINE> <DEDENT> except _core._SymbolicException: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> except (TypeError, ValueError): <NEW_LINE> <INDENT> result = _dispatch.dispatch( n_in_polymorphic_twice, a=a, b=b, name=name) <NEW_LINE> if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> raise <NEW_LINE> <DEDENT> <DEDENT> except _core._NotOkStatusException as e: <NEW_LINE> <INDENT> if name is not None: <NEW_LINE> <INDENT> message = e.message + " name: " + name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> message = e.message <NEW_LINE> <DEDENT> _six.raise_from(_core._status_to_exception(e.code, message), None) <NEW_LINE> <DEDENT> <DEDENT> if not isinstance(a, (list, tuple)): <NEW_LINE> <INDENT> raise TypeError( "Expected list for 'a' argument to " "'n_in_polymorphic_twice' Op, not %r." % a) <NEW_LINE> <DEDENT> _attr_N = len(a) <NEW_LINE> if not isinstance(b, (list, tuple)): <NEW_LINE> <INDENT> raise TypeError( "Expected list for 'b' argument to " "'n_in_polymorphic_twice' Op, not %r." % b) <NEW_LINE> <DEDENT> if len(b) != _attr_N: <NEW_LINE> <INDENT> raise ValueError( "List argument 'b' to 'n_in_polymorphic_twice' Op with length %d " "must match length %d of argument 'a'." % (len(b), _attr_N)) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> _, _, _op = _op_def_lib._apply_op_helper( "NInPolymorphicTwice", a=a, b=b, name=name) <NEW_LINE> <DEDENT> except (TypeError, ValueError): <NEW_LINE> <INDENT> result = _dispatch.dispatch( n_in_polymorphic_twice, a=a, b=b, name=name) <NEW_LINE> if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> raise <NEW_LINE> <DEDENT> return _op <NEW_LINE> _result = None <NEW_LINE> return _result
TODO: add doc. Args: a: A list of `Tensor` objects with the same type. b: A list with the same length as `a` of `Tensor` objects with the same type as `a`. name: A name for the operation (optional). Returns: The created Operation.
625941ba377c676e9127204e
def add_filter(self, fil, obj=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.engine.add_filter(fil, obj=obj) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> exception()
Adds a given filter to the MayaVi pipeline. Adds it to the selected object, or to an object passed thought the kwarg `obj`.
625941bad7e4931a7ee9ddc0
def get_annual_occurrence_rates(self): <NEW_LINE> <INDENT> mag, num_bins = self._get_min_mag_and_num_bins() <NEW_LINE> rates = [] <NEW_LINE> for i in xrange(num_bins): <NEW_LINE> <INDENT> rate = self._get_rate(mag) <NEW_LINE> rates.append((mag, rate)) <NEW_LINE> mag += self.bin_width <NEW_LINE> <DEDENT> return rates
Calculate and return the annual occurrence rates histogram. :returns: See :meth:`openquake.hazardlib.mfd.base.BaseMFD.get_annual_occurrence_rates`.
625941ba4c3428357757c1cf
def values(self, instance): <NEW_LINE> <INDENT> assert isinstance(instance, self.model) <NEW_LINE> values = [] <NEW_LINE> for field in self.fields: <NEW_LINE> <INDENT> value = field.value_from_object(instance) <NEW_LINE> if value is None: <NEW_LINE> <INDENT> if field.default != models.fields.NOT_PROVIDED: <NEW_LINE> <INDENT> value = field.get_default() <NEW_LINE> <DEDENT> elif isinstance(field, models.DateTimeField) and (field.auto_now or field.auto_now_add): <NEW_LINE> <INDENT> value = timezone.now() <NEW_LINE> <DEDENT> <DEDENT> value = field.get_prep_value(value) <NEW_LINE> values.append(value) <NEW_LINE> <DEDENT> return values
Get list of column values.
625941ba9f2886367277a735
def save(self, path): <NEW_LINE> <INDENT> dirname = os.path.dirname(path) <NEW_LINE> if not os.path.isdir(dirname): os.makedirs(dirname) <NEW_LINE> torch.save({ 'recovery' : self.recovery, 'dataset' : self.dataset, 'keys' : self.keys, 'identifier': self.identifier, }, path)
Save data from the class Args ---- path : str path to save all containing data
625941ba4428ac0f6e5ba696
def plot(self,area): <NEW_LINE> <INDENT> area.plotsymbol(self.xloc,self.yloc,size=self.size,symbol=self.symbol,args=self.args)
Plot data. area: area to be used for plotting
625941ba55399d3f05588558
def insert_into_customer_devices(user, device, device_name): <NEW_LINE> <INDENT> new_customer_device, created = CustomerDevice.objects.get_or_create(user_id=user, device_id=device) <NEW_LINE> if created: <NEW_LINE> <INDENT> new_customer_device.device_name = device_name <NEW_LINE> new_customer_device.save() <NEW_LINE> return True <NEW_LINE> <DEDENT> return False
Create a new owner for a device (create new record), Return True if new CustomerDevice instance created, else return False :param user: User instance :param device: Device instance :param device_name: string :return: boolean
625941bacb5e8a47e48b7953
def test_was_reported_recently_with_future_vehicle(self): <NEW_LINE> <INDENT> future_report = Vehicle( run_id='201_38_01', vehicle_id='7184', route_id='201', seconds_since_report=-1, latitude=34.07349, longitude=-118.288185, heading=255, predictable=True ) <NEW_LINE> self.assertEqual(future_report.was_reported_recently(), False)
was_reported_recently() should return False for vehicles whose seconds_since_report is negative (non-sensical / in the future)
625941ba627d3e7fe0d68cf3
def _recvAll(sock, num): <NEW_LINE> <INDENT> recvBuff = '' <NEW_LINE> tmpBuff = '' <NEW_LINE> while len(recvBuff) < num: <NEW_LINE> <INDENT> tmpBuff = sock.recv(num) <NEW_LINE> if not tmpBuff: <NEW_LINE> <INDENT> return (recvBuff, 'socket connection broken') <NEW_LINE> <DEDENT> recvBuff += tmpBuff <NEW_LINE> <DEDENT> return (recvBuff, None)
Receive a specified number of bytes from a socket @param sock: socket to receive from @param num: number of bytes to receive @return (data, error) data: data transferred error: None if all data received, error message string otherwise
625941ba283ffb24f3c557b0
def getYMat(self): <NEW_LINE> <INDENT> if self.__sdpRelaxation is None or self.__sdpRelaxation.y_mat is None: <NEW_LINE> <INDENT> self.solve() <NEW_LINE> <DEDENT> return self.__sdpRelaxation.y_mat
Returns the moment matrix that was the result of solving the specified SDP. If necessary the SDP is solved first.
625941ba56ac1b37e626407a
def _set_for_hybrid_DS(self, state): <NEW_LINE> <INDENT> for ds in self.registry.values(): <NEW_LINE> <INDENT> ds._set_for_hybrid_DS(state)
Internal method to set all sub-models flag for being part of a hybrid trajectory computation. Useful to indicate that high level events should not be reset when a Generator is reused between hybrid trajectory segments.
625941ba091ae35668666e09
def on_page_markdown(self, markdown, page, config, site_navigation=None, **kwargs): <NEW_LINE> <INDENT> if not self.variables: <NEW_LINE> <INDENT> return markdown <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> md_template = self.jinja_env.from_string(markdown) <NEW_LINE> return md_template.render(**self.variables)
Provide a hook for defining functions from an external module
625941ba9c8ee82313fbb619
def get_elements(path: str) -> [image_element.ReleasableImageElement]: <NEW_LINE> <INDENT> for img_seq in pySeq.scandir(path=path): <NEW_LINE> <INDENT> yield image_element.ReleasableImageElement(img_seq)
Scan directory for images. Args: path: Directory path to scan. Yields: Element to add to table view model.
625941ba009cb60464c63260
def test_bad_abstract_syntax_raises(self): <NEW_LINE> <INDENT> msg = r"The supplied abstract syntax is not valid" <NEW_LINE> with pytest.raises(ValueError, match=msg): <NEW_LINE> <INDENT> bwm = BasicWorklistManagementServiceClass(None) <NEW_LINE> context = build_context("1.2.3.4") <NEW_LINE> bwm.SCP(None, context)
Test calling the BWM SCP with an unknown UID raises exception.
625941baf8510a7c17cf95a8
def get_actual(year): <NEW_LINE> <INDENT> if year < 1: <NEW_LINE> <INDENT> raise ValueError("Year must be > 1") <NEW_LINE> <DEDENT> DECEMBER = 12 <NEW_LINE> return datetime.date(year, DECEMBER, 26)
Boxing Day is always celebrated on the 26th of December :param year: int :return: datetime object set for the observed date
625941baeab8aa0e5d26da03
def test_baseXencode(self): <NEW_LINE> <INDENT> for (raw, encoded, charset) in BASE_X_ENCODED_TESTS: <NEW_LINE> <INDENT> self.assertEqual(encoded, utils.baseXencode( raw, charset), "Invalid encoded value for base %s" % len(charset))
Test baseXencode
625941bacad5886f8bd26e87
def disconnect(self): <NEW_LINE> <INDENT> if self.cli is not None: <NEW_LINE> <INDENT> self.cli.disconnect()
Close the connection if the client is initialized.
625941ba5f7d997b87174940
def test_bad_fuel_oxidizer_value(self): <NEW_LINE> <INDENT> case = [{ 'kind': 'constant volume', 'pressure': 1.0, 'temperature': 1000, 'end-time': 10.0, 'fuel': {'CH4': 0.0}, 'oxidizer': {'O2': 1.0, 'N2': 3.76}, 'equivalence-ratio': 1.0 }] <NEW_LINE> with pytest.raises(AssertionError): <NEW_LINE> <INDENT> parse_ignition_inputs('gri30.cti', case) <NEW_LINE> <DEDENT> case = [{ 'kind': 'constant volume', 'pressure': 1.0, 'temperature': 1000, 'end-time': 10.0, 'fuel': {'CH4': 1.0}, 'oxidizer': {'O2': 0.0, 'N2': 3.76}, 'equivalence-ratio': 1.0 }] <NEW_LINE> with pytest.raises(AssertionError): <NEW_LINE> <INDENT> parse_ignition_inputs('gri30.cti', case)
Tests correct errors for improper value.
625941ba1f037a2d8b9460a4
def pipeline_stages(self): <NEW_LINE> <INDENT> pipeline = [ self.first_stage, QueryExistingArtifacts(), ArtifactSaver(), QueryExistingContents(), RpmContentSaver(), RemoteArtifactSaver(), UpdateLCEs(), InterrelateContent(), RelatePulp2to3Content(), ResolveContentFutures(), ] <NEW_LINE> return pipeline
Build a list of stages. This defines the "architecture" of the content migration to Pulp 3. Returns: list: List of :class:`~pulpcore.plugin.stages.Stage` instances
625941ba91f36d47f21ac395
@level_check <NEW_LINE> def set_level(level): <NEW_LINE> <INDENT> Logger.CURRENT.set_level(level)
Set logging threshold on current logger.
625941ba3346ee7daa2b2c0f
def check_core_data(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data = self.read_core_metadata() <NEW_LINE> self.check_data_exist(data) <NEW_LINE> started_at = self.check_and_get_attribute(data, "started_at") <NEW_LINE> self.check_timestamp(started_at) <NEW_LINE> finished_at = self.check_and_get_attribute(data, "finished_at") <NEW_LINE> self.check_timestamp(finished_at) <NEW_LINE> actual_ecosystem = self.check_and_get_attribute(data, "ecosystem") <NEW_LINE> self.compare_ecosystems(self, actual_ecosystem) <NEW_LINE> actual_package = self.check_and_get_attribute(data, "package") <NEW_LINE> self.compare_packages(self, actual_package) <NEW_LINE> actual_version = self.check_and_get_attribute(data, "version") <NEW_LINE> self.compare_versions(self, actual_version) <NEW_LINE> attributes_to_check = ["id", "analyses", "audit", "dependents_count", "latest_version", "package_info", "subtasks"] <NEW_LINE> self.check_attributes_presence(data, attributes_to_check) <NEW_LINE> return "OK" <NEW_LINE> <DEDENT> except ClientError: <NEW_LINE> <INDENT> return "N/A" <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> return str(e)
Check the component core data read from the AWS S3 database. Expected format (with an example data): { "analyses": [ "security_issues", "metadata", "keywords_tagging", "digests", "source_licenses", "dependency_snapshot" ], "audit": null, "dependents_count": -1, "ecosystem": "pypi", "finished_at": "2017-10-06T13:41:43.450021", "id": 1, "latest_version": "0.2.4", "package": "clojure_py", "package_info": { "dependents_count": -1, "relative_usage": "not used" }, "release": "pypi:clojure_py:0.2.4", "started_at": "2017-10-06T13:39:30.134801", "subtasks": null, "version": "0.2.4" }
625941ba0383005118ecf489
def get_carrier(self): <NEW_LINE> <INDENT> return self.carrier
Return the carrier of the Contact.
625941ba16aa5153ce36231d
def compute_distances_no_loops(self, X): <NEW_LINE> <INDENT> num_test = X.shape[0] <NEW_LINE> num_train = self.X_train.shape[0] <NEW_LINE> dists = np.zeros((num_test, num_train)) <NEW_LINE> dists = np.sqrt(np.dot((X**2), np.ones((np.transpose(self.X_train)).shape)) + np.dot(np.ones(X.shape), np.transpose(self.X_train ** 2)) - 2 * np.dot(X, np.transpose(self.X_train))) <NEW_LINE> return dists
Compute the distance between each test point in X and each training point in self.X_train using no explicit loops. Input / Output: Same as compute_distances_two_loops
625941babe7bc26dc91cd4aa
def get_as_tuple(self): <NEW_LINE> <INDENT> return self._x, self._y
:return: a tuple in the form (x, y)
625941ba3eb6a72ae02ec379