code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def test_authenticate_user_returns_endpoint_list(self): <NEW_LINE> <INDENT> result = self.successResultOf(self.st.authenticate_tenant('1111111')) <NEW_LINE> self.assertEqual(result, ('auth-token', fake_service_catalog))
authenticate_tenant returns the impersonation token and the endpoint list.
625941c28da39b475bd64f14
def remove_browser_layer(name): <NEW_LINE> <INDENT> existing = component.queryUtility(ILocalBrowserLayerType, name=name) <NEW_LINE> if existing is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> site_manager = component.getSiteManager() <NEW_LINE> site_manager.unregisterUtility(component=existing, provided=ILocalBrowserLayerType, name=name) <NEW_LINE> site_manager._p_changed = True
this will remove browser layer even if the addon has been removed from the system. Created and used to remove collective.groupdashboard symptom: can't apply portlets import step -> 2013-01-23 12:15:51 ERROR Zope.SiteErrorLog 1358939751.450.337074106184 ... Traceback (innermost last): Module ZPublisher.Publish, line 135, in publish Module Zope2.App.startup, line 291, in commit Module transaction._manager, line 93, in commit Module transaction._transaction, line 322, in commit Module transaction._transaction, line 416, in _commitResources Module ZODB.Connection, line 558, in commit Module ZODB.Connection, line 606, in _commit Module ZODB.Connection, line 640, in _store_objects Module ZODB.serialize, line 422, in serialize Module ZODB.serialize, line 431, in _dump PicklingError: Can't pickle <class 'collective.groupdashboard.interfaces.IGroupDashboardLayer'>: import of module collective.groupdashboard.interfaces failed
625941c2d58c6744b4257c03
def dist(self): <NEW_LINE> <INDENT> return list(map(lambda x: x / float(100), self.distance))
Returns the distance from the previous point in meters.
625941c23c8af77a43ae3741
def __new__(cls, subset, superset): <NEW_LINE> <INDENT> if len(subset) > len(superset): <NEW_LINE> <INDENT> raise ValueError('Invalid arguments have been provided. The superset must be larger than the subset.') <NEW_LINE> <DEDENT> for elem in subset: <NEW_LINE> <INDENT> if elem not in superset: <NEW_LINE> <INDENT> raise ValueError('The superset provided is invalid as it does not contain the element %i' % elem) <NEW_LINE> <DEDENT> <DEDENT> obj = Basic.__new__(cls) <NEW_LINE> obj._subset = subset <NEW_LINE> obj._superset = superset <NEW_LINE> return obj
Default constructor. It takes the subset and its superset as its parameters. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset(['c','d'], ['a','b','c','d']) >>> a.subset ['c', 'd'] >>> a.superset ['a', 'b', 'c', 'd'] >>> a.size 2
625941c2596a897236089a66
def setRange(self, x1, y1, x2, y2): <NEW_LINE> <INDENT> self.x1 = float(x1) <NEW_LINE> self.y1 = float(y1) <NEW_LINE> self.x2 = float(x2) <NEW_LINE> self.y2 = float(y2) <NEW_LINE> self.w = self.x2 - self.x1 <NEW_LINE> self.h = self.y2 - self.y1 <NEW_LINE> self.xmult = self.sw / self.w <NEW_LINE> self.ymult = self.sh / self.h <NEW_LINE> self.dx = 0 <NEW_LINE> self.dy = 0 <NEW_LINE> if self.keepAspect: <NEW_LINE> <INDENT> sr = float(self.sw) / float(self.sh) <NEW_LINE> vr = self.w / self.h <NEW_LINE> if sr < vr: <NEW_LINE> <INDENT> self.ymult *= sr / vr <NEW_LINE> self.dy = round((self.sh - self.h * self.ymult) / 2.0) <NEW_LINE> <DEDENT> elif sr > vr: <NEW_LINE> <INDENT> self.xmult *= vr / sr <NEW_LINE> self.dx = round((self.sw - self.w * self.xmult) / 2.0) <NEW_LINE> <DEDENT> <DEDENT> self.dx += (0.0 - x1) * self.xmult - (0 - self.sx1) <NEW_LINE> self.dy += (0.0 - y1) * self.ymult - (0 - self.sy1)
Set the virtual coordinate range.
625941c207f4c71912b11424
def setTimestampData(inv, alltimestamps): <NEW_LINE> <INDENT> totalcons = []; totalgen = []; totalID = [] <NEW_LINE> for i in range(len(alltimestamps)): <NEW_LINE> <INDENT> timestamp = alltimestamps[i] <NEW_LINE> cons = []; gen = []; ID = [] <NEW_LINE> for j in range(len(inv)): <NEW_LINE> <INDENT> for k in range(len(inv[j].apartments)): <NEW_LINE> <INDENT> index = md.binarySearchII(inv[j].apartments[k].timestamp, timestamp) <NEW_LINE> if index > -1: <NEW_LINE> <INDENT> cons.append(inv[j].apartments[k].consumption[index]) <NEW_LINE> gen.append(inv[j].apartments[k].generation[index]) <NEW_LINE> ID.append(inv[j].apartments[k].ID) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> totalcons.append(md.np.array(cons)) <NEW_LINE> totalgen.append(md.np.array(gen)) <NEW_LINE> totalID.append(ID) <NEW_LINE> <DEDENT> return totalcons, totalgen, totalID
Function to set the consumption and generation associated with each timestamp, for all the apartments. If an apartment has a value for a given timestamp, it will be added in an array representing that timestamp.
625941c21f037a2d8b9461a1
def __deserialize(self, data, klass): <NEW_LINE> <INDENT> if data is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if type(klass) == str: <NEW_LINE> <INDENT> if klass.startswith('list['): <NEW_LINE> <INDENT> sub_kls = re.match('list\[(.*)\]', klass).group(1) <NEW_LINE> return [self.__deserialize(sub_data, sub_kls) for sub_data in data] <NEW_LINE> <DEDENT> if klass.startswith('dict('): <NEW_LINE> <INDENT> sub_kls = re.match('dict\(([^,]*), (.*)\)', klass).group(2) <NEW_LINE> return {k: self.__deserialize(v, sub_kls) for k, v in six.iteritems(data)} <NEW_LINE> <DEDENT> if klass in self.NATIVE_TYPES_MAPPING: <NEW_LINE> <INDENT> klass = self.NATIVE_TYPES_MAPPING[klass] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> klass = getattr(ncloud_loadbalancer.model, klass) <NEW_LINE> <DEDENT> <DEDENT> if klass in self.PRIMITIVE_TYPES: <NEW_LINE> <INDENT> return self.__deserialize_primitive(data, klass) <NEW_LINE> <DEDENT> elif klass == object: <NEW_LINE> <INDENT> return self.__deserialize_object(data) <NEW_LINE> <DEDENT> elif klass == datetime.date: <NEW_LINE> <INDENT> return self.__deserialize_date(data) <NEW_LINE> <DEDENT> elif klass == datetime.datetime: <NEW_LINE> <INDENT> return self.__deserialize_datatime(data) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.__deserialize_model(data, klass)
Deserializes dict, list, str into an object. :param data: dict, list or str. :param klass: class literal, or string of class name. :return: object.
625941c2c4546d3d9de729d5
def reboot(self, names): <NEW_LINE> <INDENT> ret = [] <NEW_LINE> pmap = self.map_providers_parallel() <NEW_LINE> acts = {} <NEW_LINE> for prov, nodes in six.iteritems(pmap): <NEW_LINE> <INDENT> acts[prov] = [] <NEW_LINE> for node in nodes: <NEW_LINE> <INDENT> if node in names: <NEW_LINE> <INDENT> acts[prov].append(node) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for prov, names_ in six.iteritems(acts): <NEW_LINE> <INDENT> fun = '{0}.reboot'.format(prov) <NEW_LINE> for name in names_: <NEW_LINE> <INDENT> ret.append({ name: self.clouds[fun](name) }) <NEW_LINE> <DEDENT> <DEDENT> return ret
Reboot the named VMs
625941c2283ffb24f3c558a6
def test_mod_admin_can_admin(self): <NEW_LINE> <INDENT> self.dbauth.user_create('charlie', 'foo', False) <NEW_LINE> self.dbauth.user_set_admin('charlie', True) <NEW_LINE> flask.request = FakeAuthRequest('charlie', 'foo') <NEW_LINE> local.auth = self.dbauth.User.query.filter_by(label='charlie').one() <NEW_LINE> self.dbauth.user_delete('charlie')
Verify that a newly promoted admin can actually do admin stuff.
625941c2e5267d203edcdc42
def _place_ships_based_on_stat_model(self): <NEW_LINE> <INDENT> self.reverse_probs() <NEW_LINE> for val in sorted(self._d.keys()): <NEW_LINE> <INDENT> for root in self._d[val]: <NEW_LINE> <INDENT> for ship in filter(lambda s: s not in self._placements, Ship.SHORT_NAMES): <NEW_LINE> <INDENT> if self.try_place_max_prob(root, ship): <NEW_LINE> <INDENT> if len(self._placements) == 5: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> break
Place ships based on the stat model alone. The problem with this method is it is non-stochastic - i.e. will generate the same placements over and over again.
625941c296565a6dacc8f66f
def single_worker_inference(infer_model, ckpt, inference_input_file, inference_output_file, hparams): <NEW_LINE> <INDENT> output_infer = inference_output_file <NEW_LINE> infer_data = load_data(inference_input_file, hparams) <NEW_LINE> print ("Batch size type:", type(hparams.infer_batch_size)) <NEW_LINE> with tf.Session( graph=infer_model.graph, config=utils.get_config_proto()) as sess: <NEW_LINE> <INDENT> loaded_infer_model = model_helper.load_model( infer_model.model, ckpt, sess, "infer", infer_model.insert_op) <NEW_LINE> sess.run( infer_model.iterator.initializer, feed_dict={ infer_model.src_placeholder: infer_data, infer_model.batch_size_placeholder: hparams.infer_batch_size }) <NEW_LINE> utils.print_out("# Start decoding ff3") <NEW_LINE> if hparams.inference_indices: <NEW_LINE> <INDENT> _decode_inference_indices( loaded_infer_model, sess, output_infer=output_infer, output_infer_summary_prefix=output_infer, inference_indices=hparams.inference_indices, tgt_eos=hparams.eos, subword_option=hparams.subword_option) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> nmt_utils.decode_and_evaluate( "infer", loaded_infer_model, sess, output_infer, ref_file=None, metrics=hparams.metrics, subword_option=hparams.subword_option, beam_width=hparams.beam_width, tgt_eos=hparams.eos, num_translations_per_input=hparams.num_translations_per_input) <NEW_LINE> <DEDENT> OUTPUT_FOLDER = '7.19' <NEW_LINE> utils.print_out("Ouput Folder : " + OUTPUT_FOLDER) <NEW_LINE> utils.print_out("# Saving Decoder model (Normal,ckpt) By Revo") <NEW_LINE> loaded_infer_model.saver.save(sess, OUTPUT_FOLDER+"/current.ckpt") <NEW_LINE> graph_io.write_graph(sess.graph_def, OUTPUT_FOLDER, "current.graphdef") <NEW_LINE> tf.train.export_meta_graph(filename=OUTPUT_FOLDER + '/current.meta') <NEW_LINE> writer = tf.summary.FileWriter(OUTPUT_FOLDER, sess.graph) <NEW_LINE> writer.close() <NEW_LINE> OUTPUT_FROZEN_FILE = 'nmt.pb' <NEW_LINE> OUTPUT_NODES = ['reverse_table_Lookup'] <NEW_LINE> utils.print_out("# Saving Decoder model (Frozen) By Revo") <NEW_LINE> utils.print_out("# Removed Training nodes and outputing graph_def") <NEW_LINE> inference_graph = tf.graph_util.remove_training_nodes(sess.graph.as_graph_def()) <NEW_LINE> graph_io.write_graph(inference_graph, OUTPUT_FOLDER, "infer_model.graphdef") <NEW_LINE> freeze_graph.freeze_graph("7.19/current.graphdef", "", False, "7.19/current.ckpt", "reverse_table_Lookup", "", "", OUTPUT_FOLDER + "/" + OUTPUT_FROZEN_FILE, True, "") <NEW_LINE> frozen_graph = tf.graph_util.convert_variables_to_constants(sess, sess.graph_def, OUTPUT_NODES) <NEW_LINE> utils.print_out("# Start converting into TOCO file.") <NEW_LINE> converter = tf.contrib.lite.TocoConverter.from_frozen_graph(OUTPUT_FOLDER + "/" + OUTPUT_FROZEN_FILE, ['src_place'], OUTPUT_NODES) <NEW_LINE> tflite_model = converter.convert() <NEW_LINE> open(OUTPUT_FOLDER + "/converted_model.tflite", "wb").write(tflite_model)
Inference with a single worker.
625941c2b57a9660fec33825
def __init__(self, n_layer=12, growth_rate=12, n_class=10, dropout_ratio=0.2, in_ch=16, block=3): <NEW_LINE> <INDENT> in_chs = [in_ch + n_layer * growth_rate * i for i in moves.range(block + 1)] <NEW_LINE> super(DenseNet, self).__init__() <NEW_LINE> self.add_link( 'conv1', L.Convolution2D(3, in_ch, 3, 1, 1, wscale=np.sqrt(2))) <NEW_LINE> for i in moves.range(block): <NEW_LINE> <INDENT> self.add_link('dense%d' % (i + 2), DenseBlock(in_chs[i], growth_rate, n_layer)) <NEW_LINE> if not i == block - 1: <NEW_LINE> <INDENT> self.add_link('trans%d' % (i + 2), Transition(in_chs[i + 1])) <NEW_LINE> <DEDENT> <DEDENT> self.add_link( 'bn%d' % (block + 1), L.BatchNormalization(in_chs[block])) <NEW_LINE> self.add_link('fc%d' % (block + 2), L.Linear(in_chs[block], n_class)) <NEW_LINE> self.train = True <NEW_LINE> self.dropout_ratio = dropout_ratio <NEW_LINE> self.block = block
DenseNet definition. Args: n_layer: Number of convolution layers in one dense block. If n_layer=12, the network is made out of 40 (12*3+4) layers. If n_layer=32, the network is made out of 100 (32*3+4) layers. growth_rate: Number of output feature maps of each convolution layer in dense blocks, which is difined as k in the paper. n_class: Output class. dropout_ratio: Dropout ratio. in_ch: Number of output feature maps of first convolution layer. block: Number of dense block.
625941c28da39b475bd64f15
def candidate_generation(f_y, f_y_size, symbol_size, ngram2mid, mid2index, question): <NEW_LINE> <INDENT> candidates = list() <NEW_LINE> ngram_list = ngram_generation(question) <NEW_LINE> ngram_list = ngram_clean(ngram_list, ngram2mid.keys()) <NEW_LINE> ngram_indexes = ngram_vectorisation(ngram2mid, mid2index, ngram_list) <NEW_LINE> if len(ngram_indexes) > 0: <NEW_LINE> <INDENT> ngram_tuples = [(1, 0, index) for index in ngram_indexes] <NEW_LINE> f_data, f_row, f_col = zip(*ngram_tuples) <NEW_LINE> ngram_vector = sparse.csr_matrix((f_data, (f_row, f_col)), shape=(1, symbol_size)) <NEW_LINE> ngram_vector = ngram_vector.toarray() <NEW_LINE> candidates.append(f_y.dot(ngram_vector.transpose())) <NEW_LINE> candidates = candidates[0] <NEW_LINE> return [index for index in range(len(candidates)) if candidates[index][0] > 0.0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return []
Note: generate candidates with ngrams Args: f_y: knowlege base matrice f_y_size: ngram2mid: map ngram to id mid2index: map id to index question: in natural language Returns: list of candidates
625941c297e22403b379cf3c
def upload_dsl_resources(dsl_resources, temp_dir, fabric_env, retries, wait_interval, timeout): <NEW_LINE> <INDENT> logger = get_logger() <NEW_LINE> remote_plugins_folder = '/opt/manager/resources/' <NEW_LINE> @retry(wait_fixed=wait_interval * 1000, stop_func=partial(_stop_retries, retries, wait_interval), retry_on_exception=lambda e: isinstance(e, RecoverableError)) <NEW_LINE> def upload_dsl_resource(local_path, remote_path): <NEW_LINE> <INDENT> remote_dir = os.path.dirname(remote_path) <NEW_LINE> logger.info('Uploading resources from {0} to {1}' .format(local_path, remote_dir)) <NEW_LINE> fabric.run('sudo mkdir -p {0}'.format(remote_dir)) <NEW_LINE> fabric.put(local_path, remote_path, use_sudo=True) <NEW_LINE> <DEDENT> for dsl_resource in dsl_resources: <NEW_LINE> <INDENT> source_plugin_yaml_path = dsl_resource.get('source_path') <NEW_LINE> destination_plugin_yaml_path = dsl_resource.get('destination_path') <NEW_LINE> if not source_plugin_yaml_path or not destination_plugin_yaml_path: <NEW_LINE> <INDENT> missing_fields = [] <NEW_LINE> if source_plugin_yaml_path is None: <NEW_LINE> <INDENT> missing_fields.append('source_path') <NEW_LINE> <DEDENT> if destination_plugin_yaml_path is None: <NEW_LINE> <INDENT> missing_fields.append('destination_path') <NEW_LINE> <DEDENT> raise CloudifyBootstrapError( 'The following fields are missing: {0}.'.format( ','.join(missing_fields))) <NEW_LINE> <DEDENT> if destination_plugin_yaml_path.startswith('/'): <NEW_LINE> <INDENT> destination_plugin_yaml_path = destination_plugin_yaml_path[1:] <NEW_LINE> <DEDENT> local_plugin_yaml_path = _get_resource_into_dir(temp_dir, source_plugin_yaml_path, retries, wait_interval, timeout) <NEW_LINE> fab_env = copy.deepcopy(fabric_env) <NEW_LINE> fab_env['abort_exception'] = RecoverableError <NEW_LINE> with fabric.settings(**fab_env): <NEW_LINE> <INDENT> remote_plugin_yaml_file_path = "{0}{1}".format(remote_plugins_folder, destination_plugin_yaml_path) <NEW_LINE> upload_dsl_resource(local_path=local_plugin_yaml_path, remote_path=remote_plugin_yaml_file_path)
Uploads dsl resources to the manager. :param dsl_resources: all of the dsl_resources. :param temp_dir: the dir to push the resources to. :param fabric_env: fabric env in order to upload the dsl_resources. :param retries: number of retries per resource download. :param wait_interval: interval between download retries. :param timeout: timeout for uploading a dsl resource. :return:
625941c28e05c05ec3eea316
def __init__(self, enabled, password): <NEW_LINE> <INDENT> ReqElement.__init__(self, 'LocalAdmin') <NEW_LINE> self.setAttribute('enabled', enabled) <NEW_LINE> self.setAttribute('password', password)
Create a LocalAdmin element. :param password: The local admin password. :param enabled: Switches local admin on or off. Switching off local admin on a standalone server is rejected.
625941c263f4b57ef00010c1
def update(self, instance, validated_data): <NEW_LINE> <INDENT> password = validated_data.pop("password", None) <NEW_LINE> user = super().update(instance, validated_data) <NEW_LINE> if password: <NEW_LINE> <INDENT> user.set_password(password) <NEW_LINE> user.save() <NEW_LINE> <DEDENT> return user
Update a user, setting the PWD correctly and return it
625941c20c0af96317bb818b
def __generate(self, kwargs): <NEW_LINE> <INDENT> result = [] <NEW_LINE> size = kwargs["count"] <NEW_LINE> prefix = kwargs["prefix"] <NEW_LINE> suffix = kwargs["suffix"] <NEW_LINE> protocol = kwargs["protocol"] <NEW_LINE> tld = kwargs["tld"] <NEW_LINE> workers = kwargs["workers"] <NEW_LINE> dry_run = kwargs["dry_run"] <NEW_LINE> Log.info("Generating {} {} url(s)".format(size, tld)) <NEW_LINE> Log.info("Protocol: {}".format(protocol.upper())) <NEW_LINE> Log.info("Prefix: {}".format(prefix if prefix else None)) <NEW_LINE> Log.info("Suffix: {}".format(suffix if suffix else None)) <NEW_LINE> Log.info("TLD: {}".format(tld)) <NEW_LINE> Log.info("Workers: {}".format(workers)) <NEW_LINE> urls = [] <NEW_LINE> index = 1 <NEW_LINE> pool = ThreadPoolExecutor(max_workers=workers) <NEW_LINE> while index <= size: <NEW_LINE> <INDENT> url = self.onion.generate(prefix, suffix, protocol, tld) <NEW_LINE> urls.append(url) <NEW_LINE> index += 1 <NEW_LINE> <DEDENT> Log.info("Generated {} {} url(s)".format(len(urls), tld)) <NEW_LINE> if dry_run: <NEW_LINE> <INDENT> Log.warn("Dry run enabled, skipping url validation") <NEW_LINE> return "\n".join(urls) <NEW_LINE> <DEDENT> Log.info("Running HTTP status check in all urls") <NEW_LINE> Log.info("Be patient, this may take a looooong time...") <NEW_LINE> for url in urls: <NEW_LINE> <INDENT> pool.submit(self.__url_check, url=url, urls=result) <NEW_LINE> <DEDENT> pool.shutdown(wait=True) <NEW_LINE> Log.info("Found {} of {} urls".format(len(result), len(urls))) <NEW_LINE> return "\n".join(result)
Handles the operations -g, --generate and --dry-run Parameters ---------- kwargs: dict The dictionary parameter containing the attributes: * count - The number of urls to generate * prefix - The url prefix * suffix - The url suffix * protocol - The protocol * tld - The top level domain * workers - The number of url validation workers * dry_run - The dry run mode Returns ------- result: str The list of urls
625941c282261d6c526ab440
def convert_line_to_html(self, empty): <NEW_LINE> <INDENT> line = [] <NEW_LINE> do_highlight = self.curr_row in self.hl_lines <NEW_LINE> while self.end <= self.size: <NEW_LINE> <INDENT> scope_name = self.view.scope_name(self.pt) <NEW_LINE> while self.view.scope_name(self.end) == scope_name and self.end < self.size: <NEW_LINE> <INDENT> self.end += 1 <NEW_LINE> <DEDENT> if NEW_SCHEMES: <NEW_LINE> <INDENT> color_match = self.view.style_for_scope(scope_name) <NEW_LINE> color = color_match.get('foreground', self.fground) <NEW_LINE> bgcolor = color_match.get('background') <NEW_LINE> style = [] <NEW_LINE> if color_match['bold']: <NEW_LINE> <INDENT> style.append('bold') <NEW_LINE> <DEDENT> if color_match['italic']: <NEW_LINE> <INDENT> style.append('italic') <NEW_LINE> <DEDENT> if do_highlight: <NEW_LINE> <INDENT> sfg = color_match.get('selection_forground', self.defaults.get('selection_forground')) <NEW_LINE> if sfg: <NEW_LINE> <INDENT> color = sfg <NEW_LINE> <DEDENT> bgcolor = color_match.get('selection', '#0000FF') <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> color_match = self.csm.guess_color(scope_name, selected=do_highlight, explicit_background=True) <NEW_LINE> color = color_match.fg_simulated <NEW_LINE> bgcolor = color_match.bg_simulated <NEW_LINE> style = color_match.style.split(' ') <NEW_LINE> <DEDENT> region = sublime.Region(self.pt, self.end) <NEW_LINE> tidied_text = self.html_encode(self.view.substr(region)) <NEW_LINE> self.format_text(line, tidied_text, color, bgcolor, style, empty) <NEW_LINE> self.pt = self.end <NEW_LINE> self.end = self.pt + 1 <NEW_LINE> <DEDENT> return ''.join(line)
Convert the line to its HTML representation.
625941c266673b3332b92034
def json_dumps(data, **kwargs): <NEW_LINE> <INDENT> return json.dumps(data, cls=NumpyAwareJSONEncoder, allow_nan=False)
Uses json.dumps to serialize data into JSON. In addition to the standard json.dumps function, we're also using the NumpyAwareJSONEncoder to handle numpy arrays and the `ignore_nan` parameter by default to handle np.nan values.
625941c28e71fb1e9831d74d
def fail(error_message): <NEW_LINE> <INDENT> print(error_message) <NEW_LINE> exit(1)
Print error message and exit(1) :param error_message: message to print
625941c2dd821e528d63b14e
@iterate_jit(nopython=True) <NEW_LINE> def ExpandIncome(e00200, pencon_p, pencon_s, e00300, e00400, e00600, e00700, e00800, e00900, e01100, e01200, e01400, e01500, e02000, e02100, p22250, p23250, e03500, cmbtp, ptax_was, benefit_value_total, ubi, expanded_income): <NEW_LINE> <INDENT> expanded_income = ( e00200 + pencon_p + pencon_s + e00300 + e00400 + e00600 + e00700 + e00800 - e03500 + e00900 + e01100 + e01200 + e01400 + e01500 + e02000 + e02100 + p22250 + p23250 + cmbtp + 0.5 * ptax_was + benefit_value_total + ubi ) <NEW_LINE> return expanded_income
Calculates expanded_income from component income types.
625941c294891a1f4081ba4c
def get_final_application_state(self): <NEW_LINE> <INDENT> return self.to_application_state(self.final_state())
Get final application state.
625941c23cc13d1c6d3c731e
def letterbox_image(image, size): <NEW_LINE> <INDENT> image_w, image_h = image.size <NEW_LINE> w, h = size <NEW_LINE> new_w = int(image_w * min(w*1.0/image_w, h*1.0/image_h)) <NEW_LINE> new_h = int(image_h * min(w*1.0/image_w, h*1.0/image_h)) <NEW_LINE> resized_image = image.resize((new_w,new_h), Image.BICUBIC) <NEW_LINE> boxed_image = Image.new('RGB', size, (128,128,128)) <NEW_LINE> boxed_image.paste(resized_image, ((w-new_w)//2,(h-new_h)//2)) <NEW_LINE> return boxed_image
resize image with unchanged aspect ratio using padding Reference: https://github.com/qqwweee/keras-yolo3/blob/master/yolo3/utils.py
625941c20c0af96317bb818c
def custom_course_context(self): <NEW_LINE> <INDENT> return LTICourseContext.objects.get( enable=True, uuid=self.lti_params['custom_course_context'])
Returns the custom LTICourseContext id as provided by LTI throws: KeyError or ValueError or LTICourseContext.DoesNotExist :return: context -- the LTICourseContext instance or None
625941c22c8b7c6e89b35765
def get_calendar(self, start: str = None, end: str = None) -> Calendars: <NEW_LINE> <INDENT> params = {} <NEW_LINE> if start is not None: <NEW_LINE> <INDENT> params['start'] = start <NEW_LINE> <DEDENT> if end is not None: <NEW_LINE> <INDENT> params['end'] = end <NEW_LINE> <DEDENT> resp = self.get('/calendar', data=params) <NEW_LINE> return [Calendar(o) for o in resp]
:param start: isoformat date string eg '2006-01-02T15:04:05Z' or '2006-01-02' :param end: isoformat date string
625941c2a8370b7717052844
def harvey(self, hsig, htau, hexp): <NEW_LINE> <INDENT> return hsig / (1.0 + (self.f/htau)**hexp)
Extended Harvey profile to deal with super nyquist cases
625941c2f548e778e58cd520
def newPage(self): <NEW_LINE> <INDENT> doc = self.tabs.currentWidget() <NEW_LINE> if doc is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> doc.newPage()
Append an empty page to the current document.
625941c2851cf427c661a4b5
def get_trend_resolution(self, resolution=None): <NEW_LINE> <INDENT> if not resolution: <NEW_LINE> <INDENT> resolution = Error.Resolution.FIVE_MINUTE <NEW_LINE> <DEDENT> return self._client.get( "projects/{}/errors/{}/trend?resolution={}".format( self.project.id, self.id, resolution ) )
get trend buckets for this error based on time resolution
625941c24d74a7450ccd4167
def get_dynamic_property_mor(session, mor_ref, attribute): <NEW_LINE> <INDENT> return session._call_method(vim_util, "get_dynamic_property", mor_ref, mor_ref._type, attribute)
Get the value of an attribute for a given managed object.
625941c2656771135c3eb810
def testPdfBadParser(self): <NEW_LINE> <INDENT> self.assertRaises(multivio.parser.ParserError.InvalidDocument, PdfParser, mets_file_name, "file://%s" % mets_file_name, mets_file_name)
Check PdfParser instance with a bad file.
625941c299fddb7c1c9de335
def setup_logger(log_filename): <NEW_LINE> <INDENT> format_str = '%(asctime)s@%(name)s %(levelname)s # %(message)s' <NEW_LINE> basicConfig(filename=log_filename, level=DEBUG, format=format_str) <NEW_LINE> stream_handler = StreamHandler() <NEW_LINE> stream_handler.setFormatter(Formatter(format_str)) <NEW_LINE> getLogger().addHandler(stream_handler)
setup a logger that logs lol :arg log_filename : path to logfile
625941c2167d2b6e31218b3a
def create(self): <NEW_LINE> <INDENT> begin_id = 10000 <NEW_LINE> auto_increment_file = "%s/increment_id" % os.path.dirname(Account.db_path) <NEW_LINE> if os.path.exists(auto_increment_file): <NEW_LINE> <INDENT> line = Account.db.load_pickle_data(auto_increment_file) <NEW_LINE> auto_increment_id = int(line) + 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> id_list = [] <NEW_LINE> files_list = os.listdir(Account.db_path) <NEW_LINE> for f in files_list: <NEW_LINE> <INDENT> exist_flag = re.match(r'^(\d{5,})', f) <NEW_LINE> if exist_flag: <NEW_LINE> <INDENT> id_list.append(f) <NEW_LINE> <DEDENT> <DEDENT> if id_list: <NEW_LINE> <INDENT> id_list.sort() <NEW_LINE> max_id = int(id_list[-1]) <NEW_LINE> auto_increment_id = max_id + 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> auto_increment_id = begin_id <NEW_LINE> <DEDENT> <DEDENT> self.account_id = auto_increment_id <NEW_LINE> check_flag = self.check_user_name(auto_increment_id) <NEW_LINE> if not check_flag: <NEW_LINE> <INDENT> user_file = "%s/%s" % (Account.db_path, auto_increment_id) <NEW_LINE> Account.db.dump_pickle_data(auto_increment_file, auto_increment_id) <NEW_LINE> Account.db.dump_pickle_data(user_file, self) <NEW_LINE> return self <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("User name [\033[31;1m%s\033[0m] has been registered!" % self.user_name) <NEW_LINE> return False
创建新账号 :return: 账户实例
625941c2cc40096d615958f5
def run_from_cli(self, should_update, xml_path, tag, directory, destination, filename, extension): <NEW_LINE> <INDENT> self.git = Git(path=self.cwd, cpu_count=self.cpu_count) <NEW_LINE> if should_update: <NEW_LINE> <INDENT> self.git.update_all_repos() <NEW_LINE> if xml_path: <NEW_LINE> <INDENT> self.git.start_with_xml(xml_path) <NEW_LINE> <DEDENT> elif tag and filename and extension: <NEW_LINE> <INDENT> self.git.extract_file_from_all_repos(tag=tag, filename=filename, extension=extension, destination=destination) <NEW_LINE> <DEDENT> elif tag and directory : <NEW_LINE> <INDENT> self.git.extract_directory_from_all_repos(tag=tag, directory=directory, destination=destination) <NEW_LINE> <DEDENT> elif not should_update: <NEW_LINE> <INDENT> self.display_help()
This method handles run from CLI
625941c291af0d3eaac9b9ba
def parse_filters(filter_str): <NEW_LINE> <INDENT> filters_p = __FFI__.new('bxilog_filters_p[1]') <NEW_LINE> err = __BXIBASE_CAPI__.bxilog_filters_parse(filter_str, filters_p) <NEW_LINE> bxierr.BXICError.raise_if_ko(err) <NEW_LINE> return Filters(filters_p[0])
Parse the given string and return the corresponding set of filters as a bxilog_filter_p @param[in] filters_str a string representing filters as defined in ::bxilog_filters_parse() @return an instance of the Filters class
625941c2a79ad161976cc0e9
def customize_compiler_for_nvcc(self): <NEW_LINE> <INDENT> self.src_extensions.append('.cu') <NEW_LINE> default_compiler_so = self.compiler_so <NEW_LINE> super = self._compile <NEW_LINE> def _compile(obj, src, ext, cc_args, extra_postargs, pp_opts): <NEW_LINE> <INDENT> self.set_executable('compiler_so', CUDA['nvcc']) <NEW_LINE> postargs = extra_postargs['nvcc'] <NEW_LINE> super(obj, src, ext, cc_args, postargs, pp_opts) <NEW_LINE> self.compiler_so = default_compiler_so <NEW_LINE> <DEDENT> self._compile = _compile
inject deep into distutils to customize how the dispatch to gcc/nvcc works. If you subclass UnixCCompiler, it's not trivial to get your subclass injected in, and still have the right customizations (i.e. distutils.sysconfig.customize_compiler) run on it. So instead of going the OO route, I have this. Note, it's kindof like a wierd functional subclassing going on.
625941c2aad79263cf3909e2
def on_epoch_end(self, epoch: int, logs: Dict[str, float] = None) -> None: <NEW_LINE> <INDENT> if logs is None: <NEW_LINE> <INDENT> logs = {} <NEW_LINE> <DEDENT> current = logs.get(self.monitor) <NEW_LINE> if current is None: <NEW_LINE> <INDENT> warnings.warn("Early stopping requires %s available!" % self.monitor, RuntimeWarning) <NEW_LINE> <DEDENT> if current < self.value: <NEW_LINE> <INDENT> if self.verbose > 0: <NEW_LINE> <INDENT> print("Epoch %05d: early stopping THR" % epoch) <NEW_LINE> <DEDENT> self.model.stop_training = True
Method that stops training and produces log messages on early stopping epoch: Epoch number logs: Dictionary that holds the monitor being tracked and its value
625941c292d797404e30412d
def create_model(self, data): <NEW_LINE> <INDENT> model = Exchange() <NEW_LINE> model.set_id(data[0]) <NEW_LINE> model.set_name(data[1]) <NEW_LINE> model.set_public(data[2]) <NEW_LINE> model.set_private(data[3]) <NEW_LINE> model.set_user_id(data[4]) <NEW_LINE> model.set_uid(data[5]) <NEW_LINE> model.set_pw(data[6]) <NEW_LINE> return model
Create an Exchange model from database data (id, exchangename, public, private, user_id) :param data: :return Bot:
625941c2e5267d203edcdc43
def find_ini_config_file(warnings=None): <NEW_LINE> <INDENT> if warnings is None: <NEW_LINE> <INDENT> warnings = set() <NEW_LINE> <DEDENT> SENTINEL = object <NEW_LINE> potential_paths = [] <NEW_LINE> path_from_env = os.getenv("ANSIBLE_CONFIG", SENTINEL) <NEW_LINE> if path_from_env is not SENTINEL: <NEW_LINE> <INDENT> path_from_env = unfrackpath(path_from_env, follow=False) <NEW_LINE> if os.path.isdir(to_bytes(path_from_env)): <NEW_LINE> <INDENT> path_from_env = os.path.join(path_from_env, "ansible.cfg") <NEW_LINE> <DEDENT> potential_paths.append(path_from_env) <NEW_LINE> <DEDENT> warn_cmd_public = False <NEW_LINE> try: <NEW_LINE> <INDENT> cwd = os.getcwd() <NEW_LINE> perms = os.stat(cwd) <NEW_LINE> cwd_cfg = os.path.join(cwd, "ansible.cfg") <NEW_LINE> if perms.st_mode & stat.S_IWOTH: <NEW_LINE> <INDENT> if os.path.exists(cwd_cfg): <NEW_LINE> <INDENT> warn_cmd_public = True <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> potential_paths.append(cwd_cfg) <NEW_LINE> <DEDENT> <DEDENT> except OSError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> potential_paths.append(unfrackpath("~/.ansible.cfg", follow=False)) <NEW_LINE> potential_paths.append("/etc/ansible/ansible.cfg") <NEW_LINE> for path in potential_paths: <NEW_LINE> <INDENT> if os.path.exists(to_bytes(path)): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> path = None <NEW_LINE> <DEDENT> if path_from_env != path and warn_cmd_public: <NEW_LINE> <INDENT> warnings.add(u"Ansible is being run in a world writable directory (%s)," u" ignoring it as an ansible.cfg source." u" For more information see" u" https://docs.ansible.com/ansible/devel/reference_appendices/config.html#cfg-in-world-writable-dir" % to_text(cwd)) <NEW_LINE> <DEDENT> return path
Load INI Config File order(first found is used): ENV, CWD, HOME, /etc/ansible
625941c226238365f5f0ee0f
def sorting_theory(): <NEW_LINE> <INDENT> pass
3.1 sorting_theory
625941c22c8b7c6e89b35766
def compara_assinatura(assinatura_calculada, assinatura_infectada): <NEW_LINE> <INDENT> resultado_diferenca = [] <NEW_LINE> for i in range (0, len(assinatura_calculada), 1): <NEW_LINE> <INDENT> resultado_diferenca.append(abs(assinatura_infectada[i] - assinatura_calculada[i])) <NEW_LINE> <DEDENT> soma_diferenca = 0 <NEW_LINE> for resultado in resultado_diferenca: <NEW_LINE> <INDENT> soma_diferenca += resultado <NEW_LINE> <DEDENT> grau_similaridade = soma_diferenca / 6 <NEW_LINE> return grau_similaridade
Essa funcao recebe duas assinaturas de texto e deve devolver o grau de similaridade nas assinaturas.
625941c2097d151d1a222dff
def clean_dataframe(df, time_col): <NEW_LINE> <INDENT> df = df.dropna(subset=['Time', 'Outcome', 'Price']) <NEW_LINE> df['Price'] = strip_values(df['Price'], ['$', ' million', ',']) <NEW_LINE> df['Liftoff Thrust'] = strip_values(df['Liftoff Thrust'], [' kN', ',']) <NEW_LINE> df['Rocket Height'] = strip_values(df['Rocket Height'], [' m']) <NEW_LINE> df[time_col] = pd.to_datetime(df[time_col], infer_datetime_format=True, utc=True) <NEW_LINE> return df
Takes a dataframe and cleans it according to a slightly hardcoded system where units are removed from Price, Liftoff Thrust, and Rocket Height columns, None values are dropped, and a designated time column is converted to official datetime format. Args: dataframe: the input dataframe to clean time_col: the time column of the dataframe Returns: a cleaned dataframe
625941c2d10714528d5ffc85
def scatter_update_tensor(x, indices, updates): <NEW_LINE> <INDENT> x_shape = tf.shape(x) <NEW_LINE> patch = tf.scatter_nd(indices, updates, x_shape) <NEW_LINE> mask = tf.greater(tf.scatter_nd(indices, tf.ones_like(updates), x_shape), 0) <NEW_LINE> return tf.where(mask, patch, x)
Utility function similar to `tf.scatter_update`, but performing on Tensor indices is nd. Avoid error occured when using tf.scatter_update.
625941c244b2445a3393203b
@cpython_api([PyObject], lltype.Void) <NEW_LINE> def _PyObject_GC_TRACK(space, op): <NEW_LINE> <INDENT> raise NotImplementedError
A macro version of PyObject_GC_Track(). It should not be used for extension modules.
625941c263d6d428bbe44493
def subcloud_get(context, subcloud_id): <NEW_LINE> <INDENT> return IMPL.subcloud_get(context, subcloud_id)
Retrieve a subcloud or raise if it does not exist.
625941c2e76e3b2f99f3a7b2
def json(self, **kwargs): <NEW_LINE> <INDENT> return json.dumps(self.dict(), default=_json_date, **kwargs)
Returns a JSON representation of the current query. Kwargs are passed to ``json.dumps``.
625941c2293b9510aa2c323c
def _es_args(self, resource, refresh=None, source_projections=None): <NEW_LINE> <INDENT> args = {"index": self._resource_index(resource)} <NEW_LINE> if source_projections: <NEW_LINE> <INDENT> args["_source"] = ",".join( [source_projections, RESOURCE_FIELD, config.ETAG] ) <NEW_LINE> <DEDENT> if refresh: <NEW_LINE> <INDENT> args["refresh"] = refresh <NEW_LINE> <DEDENT> return args
Get index and doctype args.
625941c2fb3f5b602dac3635
def inference_trivial(net, input_layer): <NEW_LINE> <INDENT> net.use_batch_norm = False <NEW_LINE> x = net.input_layer(input_layer) <NEW_LINE> x = net.flatten(x) <NEW_LINE> x = net.fully_connected(x, 1) <NEW_LINE> return x
A trivial model for benchmarking input pipeline performance
625941c267a9b606de4a7e5f
def build_work_titles(work: Work, titles: Dict[str, Tuple[str, str]]) -> List[WorkTitle]: <NEW_LINE> <INDENT> if not titles: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> language_map = { 'english': anilist_langs.english_ext_lang, 'romaji': anilist_langs.romaji_ext_lang, 'japanese': anilist_langs.japanese_ext_lang, 'unknown': anilist_langs.unknown_ext_lang, } <NEW_LINE> worktitles = [] <NEW_LINE> for title, (language, title_type) in titles.items(): <NEW_LINE> <INDENT> ext_language = language_map.get(language, language_map['unknown']) <NEW_LINE> worktitles.append(WorkTitle( work=work, title=title, ext_language=ext_language, language=ext_language.lang if ext_language else None, type=title_type )) <NEW_LINE> <DEDENT> existing_titles = set(WorkTitle.objects.filter(title__in=titles).values_list('title', flat=True)) <NEW_LINE> missing_titles = [worktitle for worktitle in worktitles if worktitle.title not in existing_titles] <NEW_LINE> WorkTitle.objects.bulk_create(missing_titles) <NEW_LINE> return missing_titles
Insert WorkTitle objects for a given Work when required into Mangaki's database. :param work: a work :param titles: a list of alternative titles :type work: Work :type titles: Dict[str, Tuple[str, str]] :return: a list of WorkTitle objects that were inserted in Mangaki's database :rtype: List[WorkTitle]
625941c20a366e3fb873e7bc
def get_cfn_value(self): <NEW_LINE> <INDENT> return str(self.value if self.value is not None else self.definition.get("default", "NONE"))
Convert parameter value into CFN value. Used when the parameter must go into a comma separated CFN parameter.
625941c207f4c71912b11425
def site_config_dirs(appname): <NEW_LINE> <INDENT> if WINDOWS: <NEW_LINE> <INDENT> path = os.path.normpath(_get_win_folder("CSIDL_COMMON_APPDATA")) <NEW_LINE> pathlist = [os.path.join(path, appname)] <NEW_LINE> <DEDENT> elif sys.platform == 'darwin': <NEW_LINE> <INDENT> pathlist = [os.path.join('/Library/Application Support', appname)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> xdg_config_dirs = os.getenv('XDG_CONFIG_DIRS', '/etc/xdg') <NEW_LINE> if xdg_config_dirs: <NEW_LINE> <INDENT> pathlist = [ os.sep.join([expanduser(x), appname]) for x in xdg_config_dirs.split(os.pathsep) ] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pathlist = [] <NEW_LINE> <DEDENT> pathlist.append('/etc') <NEW_LINE> <DEDENT> return pathlist
Return a list of potential user-shared config dirs for this application. "appname" is the name of application. Typical user config directories are: Mac OS X: /Library/Application Support/<AppName>/ Unix: /etc or $XDG_CONFIG_DIRS[i]/<AppName>/ for each value in $XDG_CONFIG_DIRS Win XP: C:\Documents and Settings\All Users\Application ... ...Data\<AppName> Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) Win 7: Hidden, but writeable on Win 7: C:\ProgramData\<AppName>
625941c230bbd722463cbd68
def minutesPastMidnighttoPytime(t): <NEW_LINE> <INDENT> hour, min = t // 60, t % 60 <NEW_LINE> return datetime.time(hour, min)
converts an integer representing elapsed minutes past midnight to a python datetime.time object >>> minutesPastMidnighttoPytime(100) datetime.time(1, 40)
625941c21f5feb6acb0c4af7
def insert(self, word: str) -> None: <NEW_LINE> <INDENT> node = self.root <NEW_LINE> for char in word: <NEW_LINE> <INDENT> if char not in node.children: <NEW_LINE> <INDENT> node.children[char] = TreeNode() <NEW_LINE> <DEDENT> node = node.children[char] <NEW_LINE> <DEDENT> node.is_end = True
Inserts a word into the trie.
625941c2a934411ee3751637
def get_youtube_id(video_id, lang_code=None): <NEW_LINE> <INDENT> if not lang_code: <NEW_LINE> <INDENT> lang_code = settings.LANGUAGE_CODE <NEW_LINE> <DEDENT> if not lang_code or lang_code == "en": <NEW_LINE> <INDENT> return video_id <NEW_LINE> <DEDENT> return get_dubbed_video_map(lcode_to_ietf(lang_code)).get(video_id)
Given a video ID, return the youtube ID for the given language. If lang_code is None, return the base / default youtube_id for the given video_id. If youtube_id for the given lang_code is not found, function returns None. Accepts lang_code in ietf format
625941c23eb6a72ae02ec47c
def release_oldest_shortened_url(self): <NEW_LINE> <INDENT> shortened_url = ShortenedURL.objects.order_by( 'created_at' ).first() <NEW_LINE> if shortened_url: <NEW_LINE> <INDENT> Word.objects.filter( word=shortened_url.shortened_url ).update(used=False) <NEW_LINE> shortened_url.delete()
Release the oldest shortened url.
625941c215fb5d323cde0ab1
def store_data(self, data, encoding='utf-8'): <NEW_LINE> <INDENT> path = random_filename(self.work_path) <NEW_LINE> try: <NEW_LINE> <INDENT> with open(path, 'wb') as fh: <NEW_LINE> <INDENT> if isinstance(data, six.text_type): <NEW_LINE> <INDENT> data = data.encode(encoding) <NEW_LINE> <DEDENT> if data is not None: <NEW_LINE> <INDENT> fh.write(data) <NEW_LINE> <DEDENT> <DEDENT> return self.store_file(path) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.unlink(path) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> pass
Put the given content into a file, possibly encoding it as UTF-8 in the process.
625941c2cdde0d52a9e52fd6
def _AskForProject(self, add_controller, path=None): <NEW_LINE> <INDENT> add_controller.SetPath(path) <NEW_LINE> add_controller.SetPort(self._table.UniquePort()) <NEW_LINE> if add_controller.ShowModal() == wx.ID_OK: <NEW_LINE> <INDENT> return add_controller.Project() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None
Ask the user for a project using the specified controller. Args: add_controller: A class to use as the Add Project Controller for our dialog. path: A file sytem path to pre-poplate the controller's path with. Returns: A launcher.Project, or None.
625941c24a966d76dd550fb2
def _print_change(self, rstfile, oldline, newline): <NEW_LINE> <INDENT> print ("%s: '%s' --> '%s'"%(self._get_relative_path(rstfile), oldline.rstrip(), newline.rstrip()))
Prints the change to the standard output
625941c250485f2cf553cd3d
def jaccard_distance(boxA, boxB): <NEW_LINE> <INDENT> xA = max(boxA[0], boxB[0]) <NEW_LINE> yA = max(boxA[1], boxB[1]) <NEW_LINE> xB = min(boxA[2], boxB[2]) <NEW_LINE> yB = min(boxA[3], boxB[3]) <NEW_LINE> interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1) <NEW_LINE> boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1) <NEW_LINE> boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1) <NEW_LINE> iou = interArea / float(boxAArea + boxBArea - interArea) <NEW_LINE> return iou * (iou > 0.5)
Calculate the Intersection over Union (IoU) of two bounding boxes. :param bb1: list [x1, x2, y1, y2] The (x1, y1) position is at the top left corner, the (x2, y2) position is at the bottom right corner :param bb2: list [x1, x2, y1, y2] The (x1, y1) position is at the top left corner, the (x2, y2) position is at the bottom right corner :return: float in [0, 1]
625941c2f548e778e58cd521
def containing_profile(self): <NEW_LINE> <INDENT> raise NotImplementedError( 'operation containing_profile(...) not yet implemented')
The query containingProfile returns the closest profile directly or indirectly containing this stereotype. result = (self.namespace.oclAsType(Package).containingProfile()) <p>From package UML::Packages.</p>
625941c2099cdd3c635f0c00
def _set_grouper(self, obj, sort=False): <NEW_LINE> <INDENT> if self.key is not None and self.level is not None: <NEW_LINE> <INDENT> raise ValueError( "The Grouper cannot specify both a key and a level!") <NEW_LINE> <DEDENT> if self._grouper is None: <NEW_LINE> <INDENT> self._grouper = self.grouper <NEW_LINE> <DEDENT> if self.key is not None: <NEW_LINE> <INDENT> key = self.key <NEW_LINE> if (getattr(self.grouper, 'name', None) == key and isinstance(obj, ABCSeries)): <NEW_LINE> <INDENT> ax = self._grouper.take(obj.index) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if key not in obj._info_axis: <NEW_LINE> <INDENT> raise KeyError( "The grouper name {0} is not found".format(key)) <NEW_LINE> <DEDENT> ax = Index(obj[key], name=key) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> ax = obj._get_axis(self.axis) <NEW_LINE> if self.level is not None: <NEW_LINE> <INDENT> level = self.level <NEW_LINE> if isinstance(ax, MultiIndex): <NEW_LINE> <INDENT> level = ax._get_level_number(level) <NEW_LINE> ax = Index(ax._get_level_values(level), name=ax.names[level]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if level not in (0, ax.name): <NEW_LINE> <INDENT> raise ValueError( "The level {0} is not valid".format(level)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> if (self.sort or sort) and not ax.is_monotonic: <NEW_LINE> <INDENT> indexer = self.indexer = ax.argsort(kind='mergesort') <NEW_LINE> ax = ax.take(indexer) <NEW_LINE> obj = obj._take(indexer, axis=self.axis, is_copy=False) <NEW_LINE> <DEDENT> self.obj = obj <NEW_LINE> self.grouper = ax <NEW_LINE> return self.grouper
given an object and the specifications, setup the internal grouper for this particular specification Parameters ---------- obj : the subject object sort : bool, default False whether the resulting grouper should be sorted
625941c29c8ee82313fbb718
def combine_gen_sources(source_a, source_b, mask): <NEW_LINE> <INDENT> animation = zip(source_a(), source_b(), mask()) <NEW_LINE> first_time = cv2.getTickCount() <NEW_LINE> for frame_a, frame_b, frame_mask in animation: <NEW_LINE> <INDENT> frame = primitives.mask_together(frame_a, frame_b, frame_mask) <NEW_LINE> last_time = cv2.getTickCount() <NEW_LINE> execution_time = (last_time - first_time) / cv2.getTickFrequency() <NEW_LINE> write_on_frame(frame, str(execution_time)) <NEW_LINE> cv2.imshow('frame', frame) <NEW_LINE> if cv2.waitKey(1) & 0xFF == ord('q'): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> first_time = cv2.getTickCount() <NEW_LINE> <DEDENT> cv2.destroyAllWindows()
given two source generators and a mask generator, combine the two sources using the mask
625941c215baa723493c3f18
def test_topo_c01b(self): <NEW_LINE> <INDENT> batch_size = 100 <NEW_LINE> c01b_test = TFD(which_set='test', axes=('c', 0, 1, 'b')) <NEW_LINE> c01b_X = c01b_test.X[0:batch_size, :] <NEW_LINE> c01b = c01b_test.get_topological_view(c01b_X) <NEW_LINE> assert c01b.shape == (1, 48, 48, batch_size) <NEW_LINE> b01c = c01b.transpose(3, 1, 2, 0) <NEW_LINE> b01c_X = self.test.X[0:batch_size, :] <NEW_LINE> assert c01b_X.shape == b01c_X.shape <NEW_LINE> assert np.all(c01b_X == b01c_X) <NEW_LINE> b01c_direct = self.test.get_topological_view(b01c_X) <NEW_LINE> assert b01c_direct.shape == b01c.shape <NEW_LINE> assert np.all(b01c_direct == b01c)
Tests that a topological batch with axes ('c',0,1,'b') can be dimshuffled back to match the standard ('b',0,1,'c') format.
625941c2a8ecb033257d3072
def symH(self, parity=0): <NEW_LINE> <INDENT> f = self.x <NEW_LINE> U = self.y <NEW_LINE> N = len(f) <NEW_LINE> ys = U.shape <NEW_LINE> ze_x = np.array([0]) <NEW_LINE> ze_y = np.zeros((ys[0],1)) <NEW_LINE> if parity == 0: <NEW_LINE> <INDENT> Up = np.concatenate((ze_y, U, np.flipud(np.conjugate(U[:, 0:-1]))), 1) <NEW_LINE> fp = np.concatenate((ze_x, f, f[0:-1] + f[-1])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> Up = np.concatenate((ze_y, U, np.flipud(np.conjugate(U))), 1) <NEW_LINE> fp = np.concatenate((ze_x, f, f + f[-1])) <NEW_LINE> <DEDENT> V = FHsignal(fp, Up) <NEW_LINE> return V
enforce Hermitian symetry Parameters ---------- parity : integer 0 even 1 odd Returns ------- V : FHsignal
625941c2e1aae11d1e749c5a
def terms_stats_facet(self, key_field, value_field, facet_fieldname=None): <NEW_LINE> <INDENT> clone = self._clone() <NEW_LINE> clone.query.add_terms_stats_facet(key_field, value_field, facet_fieldname) <NEW_LINE> return clone
Adds term stats faceting to a query
625941c28a43f66fc4b5400b
def get_x_y(self, sentence_maxlen, dataset_name='all'): <NEW_LINE> <INDENT> raise NotImplementedError
Implement with own data source. :param sentence_maxlen: maximum number of characters per sample :param dataset_name: 'all', 'train', 'dev' or 'test' :return: Tuple (x, y) x: Array of shape (batch_size, sentence_maxlen). Entries in dimension 1 are alphabet indices, index 0 is the padding symbol y: Array of shape (batch_size, sentence_maxlen, self.num_labels). Entries in dimension 2 are label indices, index 0 is the null label
625941c207d97122c417882c
def _choose_one_theorem_at_random(thms): <NEW_LINE> <INDENT> size_of_thms = tf.size(thms) <NEW_LINE> def get_an_element(): <NEW_LINE> <INDENT> random_index = tf.random_uniform([], minval=0, maxval=size_of_thms, dtype=tf.int32) <NEW_LINE> return thms[random_index] <NEW_LINE> <DEDENT> return tf.cond(size_of_thms > 0, get_an_element, lambda: '')
Adds tf ops to pick one theorem at random from a list of theorems.
625941c2c432627299f04be9
def replace_filter(text: str, pattern: dict) -> str: <NEW_LINE> <INDENT> for pat, rep in pattern.items(): <NEW_LINE> <INDENT> text = text.replace(pat, rep) <NEW_LINE> <DEDENT> return text
replace_filter filtering text by pattern key to value slower than trans_filter just use text_filter
625941c2be383301e01b542e
def save_collection(self): <NEW_LINE> <INDENT> if self.chosen_collection: <NEW_LINE> <INDENT> if self.chosen_collection.save_id_for_new(): <NEW_LINE> <INDENT> self.collections.append(self.chosen_collection) <NEW_LINE> <DEDENT> self.save_json() <NEW_LINE> self.sort()
Save a unique id number if the object is a newly instantiated :class:`Collection` object. Then append this :class:`Collection` to :attr:`CollectionHolder.collections` :obj:`list`, update `json` data file by calling :meth:`CollectionHolder.save_json()` and at last uptade the order of :class:`Collection` instances in :attr:`CollectionHolder.collections` :obj:`list` by calling :meth:`CollectionHolder.sort()`.
625941c2f7d966606f6a9fa7
def test_categories_list_delete(self): <NEW_LINE> <INDENT> delete_permission = Permission.objects.get(codename='delete_category') <NEW_LINE> self.user.user_permissions.add(delete_permission) <NEW_LINE> self.user.refresh_from_db() <NEW_LINE> self.browser.get(self.live_server_url + reverse('account:login')) <NEW_LINE> self.browser.find_element_by_name('username').send_keys(self.username) <NEW_LINE> self.browser.find_element_by_name('password').send_keys(self.password) <NEW_LINE> self.browser.find_element_by_id('login').click() <NEW_LINE> self.browser.get(self.live_server_url + reverse( 'stock:categories_list'))
Test categories list page with delete category permission
625941c2de87d2750b85fd35
def human_move(board, human): <NEW_LINE> <INDENT> legal = legal_moves(board) <NEW_LINE> move = None <NEW_LINE> while move not in legal: <NEW_LINE> <INDENT> move = ask_number('Твой ход. Выбери одно из полей (0 - 8): ', 0, NUM_SQUARES) <NEW_LINE> if move not in legal: <NEW_LINE> <INDENT> print('\nСмешной человек! Это поле уже занято. Выбери другое.\n') <NEW_LINE> <DEDENT> <DEDENT> print('Ладно...') <NEW_LINE> return move
Получает ход человека.
625941c2656771135c3eb811
def get_all_object(self): <NEW_LINE> <INDENT> return self.bucket.objects.all()
**中文文档** 返回Bucket中的所有对象。对于大型Bucket, 请慎用此方法!
625941c2fff4ab517eb2f3df
def getfixturemarker(obj: object) -> Optional["FixtureFunctionMarker"]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fixturemarker = getattr( obj, "_pytestfixturefunction", None ) <NEW_LINE> <DEDENT> except TEST_OUTCOME: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return fixturemarker
return fixturemarker or None if it doesn't exist or raised exceptions.
625941c2a8370b7717052845
def BLsurfacestat(filename='BL_surface_stat.dat',Uref=1.0,Tref=1.0,**kwargs): <NEW_LINE> <INDENT> if not os.path.exists(filename): <NEW_LINE> <INDENT> print('Error: '+filename+' does not exist') <NEW_LINE> return 1 <NEW_LINE> <DEDENT> if 'grid' in kwargs: <NEW_LINE> <INDENT> grid = kwargs['grid'] <NEW_LINE> Nx2 = grid.Nx2 <NEW_LINE> Ny = grid.Ny <NEW_LINE> <DEDENT> elif all([i in kwargs for i in ['Nx2','Ny']]): <NEW_LINE> <INDENT> grid = None <NEW_LINE> Nx2 = kwargs['Nx2'] <NEW_LINE> Ny = kwargs['Ny'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('Error: Cannot determine the dimensions of BLsurfacestat') <NEW_LINE> return 1 <NEW_LINE> <DEDENT> stat = {} <NEW_LINE> Nl = 3 <NEW_LINE> with open(filename,'rb') as binfile: <NEW_LINE> <INDENT> stat['nsamp'] = np.fromfile(binfile, dtype=np.int32, count=1) <NEW_LINE> dummy = np.fromfile(binfile, dtype=np.float64, count=Nx2*Ny*Nl) <NEW_LINE> <DEDENT> shape = (Nx2,Ny,Nl) <NEW_LINE> dummy = dummy.reshape(shape, order='F') <NEW_LINE> stat['tw1'] = fieldsp.rfield(dummy[:,:,0]*Uref**2,grid) <NEW_LINE> stat['tw2'] = fieldsp.rfield(dummy[:,:,1]*Uref**2,grid) <NEW_LINE> stat['qw'] = fieldsp.rfield(dummy[:,:,2]*Uref*Tref,grid) <NEW_LINE> return stat
Load BL_surface_stat file
625941c2f8510a7c17cf96a0
def print_anova(mydata, x, y): <NEW_LINE> <INDENT> anova_reA= anova_lm(ols('{}~C({})'.format(y, x), data=mydata[[y, x]]).fit()) <NEW_LINE> print("x is {}, y is {} ---".format(x, y)) <NEW_LINE> print(anova_reA) <NEW_LINE> print('\t')
为连续型变量,x为目标变量
625941c26e29344779a625b9
def get_labels(self): <NEW_LINE> <INDENT> return " ".join([it[1] for it in self.get_value() if it]).strip()
Get the fluorescence labels (2nd column)
625941c2566aa707497f4511
def get_parser(self, **kwargs): <NEW_LINE> <INDENT> parser = ConfigArgParser( ignore_unknown_config_file_keys=True, args_for_setting_config_path=['-c', '--config'], default_config_files=list( self.config_file_names(**kwargs) ), formatter_class=argparse.ArgumentDefaultsHelpFormatter, description=self.get_description(**kwargs), epilog=self.get_epilog(**kwargs), prefix_chars='-+', conflict_handler='resolve', ) <NEW_LINE> return parser
:param kwargs: :return:
625941c2236d856c2ad4477c
def __init__(self, c_list_sql_up, c_bool_verbose): <NEW_LINE> <INDENT> self.string_sql_db = r'Finance' <NEW_LINE> self.string_sql_server = r'localhost\SQLEXPRESS' <NEW_LINE> self.sql_conn = SqlMethods( [c_list_sql_up[0], self.string_sql_server, c_list_sql_up[1], self.string_sql_db]) <NEW_LINE> self.string_sym_sp500 = '^SPX' <NEW_LINE> self.dt_sp500_start = datetime(1970, 1, 1) <NEW_LINE> self.dt_sp500_stop = datetime.now() <NEW_LINE> self.dict_sp500_tables = { 'data':{ 'table_name':'sp500.data', 'col_dtype':['date', 'float', 'varchar(10)', 'varchar(500)', 'float', 'float', 'float', 'float', 'float', 'float', 'float'], 'col_names':['date_date', 'float_close', 'string_in_market', 'string_trigger', 'float_50_sma', 'float_200_sma', 'float_delta_50_200', 'float_delta_hl', 'float_delta_div_hl', 'float_velocity', 'float_accel']}, 'analysis':{ 'table_name':'sp500.analysis', 'col_dtype':['date', 'date', 'date', 'float', 'int', 'int', 'int', 'int', 'varchar(10)', 'float', 'float', 'float', 'float', 'float', 'varchar(50)'], 'col_names':['date_analysis', 'date_start', 'date_stop', 'dollar_start', 'int_days_range', 'int_days_in_market', 'int_days_good', 'int_days_bad', 'string_in_market', 'float_ann_fee', 'dollar_gm_with_fee', 'dollar_man_fee', 'dollar_buy_hold', 'dollar_gm_no_fee', 'string_symbol']}} <NEW_LINE> self.tup_sql_db_setup = (False, 'not checked') <NEW_LINE> self.bool_initial_load = False <NEW_LINE> self.bool_verbose = c_bool_verbose <NEW_LINE> self.list_errors = list() <NEW_LINE> self.string_path_base = os.path.join('c:' + os.path.sep, 'Code', 'Prod', 'Sp500')
base class construtor Requirements: package SqlMethods package pandas Inputs: c_list_sql_up Type: list Desc: user and password for sql database c_list_sql_up[0] -> type: string; user name c_list_sql_up[1] -> type: string; password c_bool_verbose Type: boolean Desc: flag if verbose output desired Important Info: 1. format for list to connec to sql db [r'<user name>', r'<sql server name>', r'<user password>', r'<database name>'] Attributes: sql_conn Type: SqlMethods object Desc: connection to local sql express database on external drive dict_sp500_tables Type: dictionary Desc: the tables in the database segemented by category level 00 -> 'data' or 'analysis' level 01 -> 'table_name' -> string; format 'schema name. table name' 'col_dtype' -> list; sql column data types to create table 'col_names' -> list; column names
625941c260cbc95b062c64e8
def _simulation_writeout(filename, organisms, headerData): <NEW_LINE> <INDENT> outputfile = open(filename, "w") <NEW_LINE> for header in headerData: <NEW_LINE> <INDENT> outputfile.write(header + "\n") <NEW_LINE> <DEDENT> for organism in organisms: <NEW_LINE> <INDENT> genome = ["|".join(organisms[organism]['genome'][i]) for i in range(organisms[organism]['polyploid'])] <NEW_LINE> stdout = "O>%s|%s|%s|%s>%s" % (str(organisms[organism]['organism']), str(organisms[organism]['generation']), str(organisms[organism]['parentA']), str(organisms[organism]['parentB']), str(";".join(genome))) <NEW_LINE> outputfile.write(stdout + "\n") <NEW_LINE> <DEDENT> outputfile.close()
! Private function called by simulate_<simulation type>() functions to write out the corresponding population files for each generation. @param filename String: Relative or absolute path of the new population file. @param organisms Dictionary: Dictionary of organisms from simulate_<simulation type>() functions to be written out. @param headerData List: Header data of population file (consisting of gene list and allelic frequencies) from simulate_<simulation type>() functions, to enable write out of simulated populations.
625941c2cad5886f8bd26f7f
def allow_icmp(zone, icmp): <NEW_LINE> <INDENT> if icmp not in get_icmp_types(): <NEW_LINE> <INDENT> log.error('Invalid ICMP type') <NEW_LINE> return False <NEW_LINE> <DEDENT> if icmp not in list_icmp_block(zone): <NEW_LINE> <INDENT> log.info('ICMP Type is already permitted') <NEW_LINE> return 'success' <NEW_LINE> <DEDENT> return __firewall_cmd('--zone={0} --remove-icmp-block={1}'.format(zone, icmp))
Allow a specific ICMP type on a zone .. versionadded:: Beryllium CLI Example: .. code-block:: salt '*' firewalld.allow_icmp zone echo-reply
625941c2fff4ab517eb2f3e0
def c_lift(self, V): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> circs = self.circs[:-1] <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> V = np.asarray(V) <NEW_LINE> V_norm = np.linalg.norm(V) <NEW_LINE> circs = self.solve_circs(V) <NEW_LINE> <DEDENT> return np.sum(V_norm*circs)*2
Calculate the lift
625941c27d847024c06be25f
def schedule_task(self, task, args = None, vars = None, function_name = None, start_time = None, next_run_time = None, stop_time = None, repeats = None, retry_failed = None, period = None, timeout = None, enabled = None, group_name = None, ignore_duplicate = False, sync_output = 0, user_id = True ): <NEW_LINE> <INDENT> if args is None: <NEW_LINE> <INDENT> args = [] <NEW_LINE> <DEDENT> if vars is None: <NEW_LINE> <INDENT> vars = {} <NEW_LINE> <DEDENT> if not ignore_duplicate and self._duplicate_task_exists(task, args, vars): <NEW_LINE> <INDENT> current.log.warning("Duplicate Task, Not Inserted", value=task) <NEW_LINE> return False <NEW_LINE> <DEDENT> kwargs = {} <NEW_LINE> if function_name is None: <NEW_LINE> <INDENT> function_name = task <NEW_LINE> <DEDENT> if start_time: <NEW_LINE> <INDENT> kwargs["start_time"] = start_time <NEW_LINE> <DEDENT> if next_run_time: <NEW_LINE> <INDENT> kwargs["next_run_time"] = next_run_time <NEW_LINE> <DEDENT> elif start_time: <NEW_LINE> <INDENT> kwargs["next_run_time"] = start_time <NEW_LINE> <DEDENT> if stop_time: <NEW_LINE> <INDENT> kwargs["stop_time"] = stop_time <NEW_LINE> <DEDENT> elif start_time: <NEW_LINE> <INDENT> if not isinstance(start_time, datetime.datetime): <NEW_LINE> <INDENT> start_time = datetime.datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S") <NEW_LINE> <DEDENT> stop_time = start_time + datetime.timedelta(days=1) <NEW_LINE> <DEDENT> if repeats is not None: <NEW_LINE> <INDENT> kwargs["repeats"] = repeats <NEW_LINE> <DEDENT> if retry_failed is not None: <NEW_LINE> <INDENT> kwargs["retry_failed"] = retry_failed <NEW_LINE> <DEDENT> if period: <NEW_LINE> <INDENT> kwargs["period"] = period <NEW_LINE> <DEDENT> if timeout: <NEW_LINE> <INDENT> kwargs["timeout"] = timeout <NEW_LINE> <DEDENT> if enabled != None: <NEW_LINE> <INDENT> kwargs["enabled"] = enabled <NEW_LINE> <DEDENT> if group_name: <NEW_LINE> <INDENT> kwargs["group_name"] = group_name <NEW_LINE> <DEDENT> if sync_output != 0: <NEW_LINE> <INDENT> kwargs["sync_output"] = sync_output <NEW_LINE> <DEDENT> if user_id: <NEW_LINE> <INDENT> auth = current.auth <NEW_LINE> if auth.is_logged_in(): <NEW_LINE> <INDENT> vars["user_id"] = auth.user.id <NEW_LINE> <DEDENT> <DEDENT> task_id = current.db.scheduler_task.insert(application_name = "%s/default" % current.request.application, task_name = task, function_name = function_name, args = json.dumps(args), vars = json.dumps(vars), **kwargs) <NEW_LINE> return task_id
Schedule a task in web2py Scheduler @param task: name of the function/task to be scheduled @param args: args to be passed to the scheduled task @param vars: vars to be passed to the scheduled task @param function_name: function name (if different from task name) @param start_time: start_time for the scheduled task @param next_run_time: next_run_time for the the scheduled task @param stop_time: stop_time for the the scheduled task @param repeats: number of times the task to be repeated (0=unlimited) @param retry_failed: number of times the task to be retried (-1=unlimited) @param period: time period between two consecutive runs (seconds) @param timeout: set timeout for a running task @param enabled: enabled flag for the scheduled task @param group_name: group_name for the scheduled task @param ignore_duplicate: disable or enable duplicate checking @param sync_output: sync output every n seconds (0 = disable sync) @param user_id: Add the user_id to task vars if logged in
625941c2711fe17d82542314
def unnormalise_density(c, rho): <NEW_LINE> <INDENT> return c * rho
Reverses any desnity normalisation As a general rule this should be done using the units read in from the file, with unit conversion done afterwards
625941c2596a897236089a68
def run(self): <NEW_LINE> <INDENT> if self.opts['doc']: <NEW_LINE> <INDENT> self._print_docs() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._verify_fun() <NEW_LINE> return self.functions[self.opts['fun']](*self.opts['arg'])
Execute the runner sequence
625941c232920d7e50b28173
def admin_routes(app): <NEW_LINE> <INDENT> admin = Blueprint('admin_notifications', __name__) <NEW_LINE> admin.route("/notifications", methods=['GET'])( admin.route("/notifications/<int:page>", methods=['GET'])( admin.route("/notifications/<int:page>/<int(min=1, max=100):limit>", methods=['GET'])( require_appkey( auth_basic.login_required( permission_super_admin.require(http_exception=403)( check_password_expiration( get_notifications))))))) <NEW_LINE> app.register_blueprint(admin)
Register admin notifications routes with the application. :param app: Flask application :type app: Flask
625941c2a05bb46b383ec7c8
def set_pins(self): <NEW_LINE> <INDENT> for pin in self.data + [self.read]: <NEW_LINE> <INDENT> self.rduino.pin_mode(pin, OUTPUT)
Initialises the Pins on the ruggeduino for sound output
625941c28c3a87329515835d
def get_version(self): <NEW_LINE> <INDENT> return _lib.X509_REQ_get_version(self._req)
Get the version subfield (RFC 2459, section 4.1.2.1) of the certificate request. :return: an integer giving the value of the version subfield
625941c27b25080760e393ff
def run_app(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> (new_in, new_out) = self.get_frame_range_from_shotgun() <NEW_LINE> (current_in, current_out) = self.get_current_frame_range() <NEW_LINE> if new_in is None or new_out is None: <NEW_LINE> <INDENT> message = "Shotgun has not yet been populated with \n" <NEW_LINE> message += "in and out frame data for this Shot." <NEW_LINE> QtGui.QMessageBox.information(None, "No data in Shotgun!", message) <NEW_LINE> return <NEW_LINE> <DEDENT> self.set_frame_range(new_in, new_out) <NEW_LINE> message = "Your scene has been updated with the \n" <NEW_LINE> message += "latest frame ranges from shotgun.\n\n" <NEW_LINE> message += "Previous start frame: %s\n" % current_in <NEW_LINE> message += "New start frame: %s\n\n" % new_in <NEW_LINE> message += "Previous end frame: %s\n" % current_out <NEW_LINE> message += "New end frame: %s\n\n" % new_out <NEW_LINE> QtGui.QMessageBox.information(None, "Frame range updated!", message) <NEW_LINE> <DEDENT> except tank.TankError: <NEW_LINE> <INDENT> message = "There was a problem updating your scene frame range.\n" <NEW_LINE> QtGui.QMessageBox.warning(None, "Frame range not updated!", message) <NEW_LINE> error_message = traceback.format_exc() <NEW_LINE> self.logger.error(error_message)
Callback from when the menu is clicked. The default callback will first query the frame range from shotgun and validate the data. If there is missing Shotgun data it will popup a QMessageBox dialog alerting the user. Assuming all data exists in shotgun, it will set the frame range with the newly queried data and popup a QMessageBox with results.
625941c267a9b606de4a7e60
def delete_group_user(group_id: Union[int, str], login: str): <NEW_LINE> <INDENT> uri = f'/groups/{group_id}/users/{login}' <NEW_LINE> method = 'DELETE' <NEW_LINE> return Request.send(method, uri)
从 Group 中删除 User Args: group_id: Group 的 {login} 或 {id} login: User 的 {login}, 不确定 {id} 是否可行 Returns: 删除的 User 的成员信息
625941c2091ae35668666f07
def designs_id_exists_get_with_http_info(self, id, **kwargs): <NEW_LINE> <INDENT> all_params = ['id'] <NEW_LINE> all_params.append('callback') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> params = locals() <NEW_LINE> for key, val in iteritems(params['kwargs']): <NEW_LINE> <INDENT> if key not in all_params: <NEW_LINE> <INDENT> raise TypeError( "Got an unexpected keyword argument '%s'" " to method designs_id_exists_get" % key ) <NEW_LINE> <DEDENT> params[key] = val <NEW_LINE> <DEDENT> del params['kwargs'] <NEW_LINE> if ('id' not in params) or (params['id'] is None): <NEW_LINE> <INDENT> raise ValueError("Missing the required parameter `id` when calling `designs_id_exists_get`") <NEW_LINE> <DEDENT> collection_formats = {} <NEW_LINE> resource_path = '/Designs/{id}/exists'.replace('{format}', 'json') <NEW_LINE> path_params = {} <NEW_LINE> if 'id' in params: <NEW_LINE> <INDENT> path_params['id'] = params['id'] <NEW_LINE> <DEDENT> query_params = {} <NEW_LINE> header_params = {} <NEW_LINE> form_params = [] <NEW_LINE> local_var_files = {} <NEW_LINE> body_params = None <NEW_LINE> header_params['Accept'] = self.api_client. select_header_accept(['application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript']) <NEW_LINE> if not header_params['Accept']: <NEW_LINE> <INDENT> del header_params['Accept'] <NEW_LINE> <DEDENT> header_params['Content-Type'] = self.api_client. select_header_content_type(['application/json', 'application/x-www-form-urlencoded', 'application/xml', 'text/xml']) <NEW_LINE> auth_settings = ['access_token'] <NEW_LINE> return self.api_client.call_api(resource_path, 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='InlineResponse2002', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), collection_formats=collection_formats)
Check whether a model instance exists in the data source. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.designs_id_exists_get_with_http_info(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str id: Model id (required) :return: InlineResponse2002 If the method is called asynchronously, returns the request thread.
625941c263b5f9789fde708a
def get_song_data(self, artist_name: str, track_title: str) -> dict: <NEW_LINE> <INDENT> self.total_count += 1 <NEW_LINE> result = self.MM.matcher_track_get(q_artist=artist_name, q_track=track_title) <NEW_LINE> result = result["message"] <NEW_LINE> if result["header"]["status_code"] != 200 or result["body"]["track"]["has_lyrics"] != 1: <NEW_LINE> <INDENT> self.track_not_found += 1 <NEW_LINE> self.error_codes.append(result["header"]["status_code"]) <NEW_LINE> return {} <NEW_LINE> <DEDENT> result = result["body"]["track"] <NEW_LINE> return { "Album_Name": result["album_name"], "Release_Date": result["first_release_date"].split("T")[0], "Genres": { "Names": [x["music_genre"]["music_genre_name"] for x in result["primary_genres"]["music_genre_list"]], "Source": "MusixMatch" } }
Gets song data from musixmatch api. Using the free API means access to only 30% of the lyrics body, so that's a no go. We can still use the API to augment our datasets with the album name, release date, and genres. :param artist_name: name of track artist (str) :param track_title: name of track title (str) :return: dict of form { "Album_Name": str, "Release_date": "yyyy-MM-dd, "Genres": list of strs }
625941c257b8e32f5248343f
def getStatus(self): <NEW_LINE> <INDENT> return _CsoundAC.Event_getStatus(self)
getStatus(Event self) -> double
625941c26aa9bd52df036d48
def convolve(f, weights, mode='reflect', cval=0.0, out=None, output=None): <NEW_LINE> <INDENT> if f.dtype != weights.dtype: <NEW_LINE> <INDENT> weights = weights.astype(f.dtype) <NEW_LINE> <DEDENT> if f.ndim != weights.ndim: <NEW_LINE> <INDENT> raise ValueError('mahotas.convolve: `f` and `weights` must have the same dimensions') <NEW_LINE> <DEDENT> output = _get_output(f, out, 'convolve', output=output) <NEW_LINE> _check_mode(mode, cval, 'convolve') <NEW_LINE> return _convolve.convolve(f, weights, output, mode2int[mode])
convolved = convolve(f, weights, mode='reflect', cval=0.0, out={new array}) Convolution of `f` and `weights` Convolution is performed in `doubles` to avoid over/underflow, but the result is then cast to `f.dtype`. Parameters ---------- f : ndarray input. Any dimension is supported weights : ndarray weight filter. If not of the same dtype as `f`, it is cast mode : {'reflect' [default], 'nearest', 'wrap', 'mirror', 'constant', 'ignore'} How to handle borders cval : double, optional If `mode` is constant, which constant to use (default: 0.0) out : ndarray, optional Output array. Must have same shape and dtype as `f` as well as be C-contiguous. Returns ------- convolved : ndarray of same dtype as `f`
625941c2009cb60464c63358
def get_input_train(self, m): <NEW_LINE> <INDENT> pairs = self.train_generator(m) <NEW_LINE> pref, self.training_indices = utils.reshape_pref(self.draw_preference(pairs)) <NEW_LINE> data = self.X.iloc[self.training_indices, [i for i in range(self.d-1)] + [-1]] <NEW_LINE> return [np.array(data), pref]
Construct training data to use for modelling :param m: int, number of preferences :return: list, - data: np.array, n instances with their attributes - pref: list of tuples, training preferences
625941c2cc40096d615958f6
def click_benchmarks_button(self): <NEW_LINE> <INDENT> self.click_element(self.benchmarks_button_locator, True)
Implementing click benchmarks button functionality :return:
625941c2627d3e7fe0d68df4
def setRobotPosition(self, position): <NEW_LINE> <INDENT> assert isinstance(position, Position) <NEW_LINE> self.robot_position = position
Set the position of the robot to POSITION. :param position: a Position object.
625941c282261d6c526ab442
def share_group_snapshot_update(context, share_group_snapshot_id, values): <NEW_LINE> <INDENT> return IMPL.share_group_snapshot_update( context, share_group_snapshot_id, values)
Set the given properties on a share group snapshot and update it. Raises NotFound if share group snapshot does not exist.
625941c2cb5e8a47e48b7a52
def p_factor(t): <NEW_LINE> <INDENT> t[0] = t[1]
factor : VARIABLE | NUMBER | BOOLEAN | STRING | tuple | list
625941c263f4b57ef00010c3
def singleNumber_3(self, nums): <NEW_LINE> <INDENT> if len(nums) == 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> sum = nums[0] <NEW_LINE> for num in nums[1:]: <NEW_LINE> <INDENT> sum ^= num <NEW_LINE> <DEDENT> bit_1 = -1 <NEW_LINE> while sum: <NEW_LINE> <INDENT> bit = sum & 1 <NEW_LINE> bit_1 += 1 <NEW_LINE> if bit == 1: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> sum >>= 1 <NEW_LINE> <DEDENT> nums_1 = [] <NEW_LINE> nums_2 = [] <NEW_LINE> for num in nums: <NEW_LINE> <INDENT> if (num >> bit_1) & 1 == 1: <NEW_LINE> <INDENT> nums_1.append(num) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> nums_2.append(num) <NEW_LINE> <DEDENT> <DEDENT> a = nums_1[0] <NEW_LINE> b = nums_2[0] <NEW_LINE> for num in nums_1[1:]: <NEW_LINE> <INDENT> a ^= num <NEW_LINE> <DEDENT> for num in nums_2[1:]: <NEW_LINE> <INDENT> b ^= num <NEW_LINE> <DEDENT> return [a,b]
:type nums: List[int] :rtype: List[int] 分组,将两个出现一次的数分到不同组
625941c2d164cc6175782cf3
def test_notify_new_review_request_with_diff(self): <NEW_LINE> <INDENT> review_request = self.create_review_request( create_repository=True, submitter=self.user, summary='Test Review Request', description='My description.', publish=False) <NEW_LINE> self.create_diffset(review_request) <NEW_LINE> self._create_config() <NEW_LINE> self.integration.enable_integration() <NEW_LINE> self.spy_on(urlopen, call_original=False) <NEW_LINE> self.spy_on(self.integration.notify) <NEW_LINE> review_request.publish(self.user) <NEW_LINE> self.assertEqual(len(self.integration.notify.calls), 1) <NEW_LINE> self.assertEqual(len(urlopen.spy.calls), 1) <NEW_LINE> self.assertEqual( json.loads(urlopen.spy.calls[0].args[0].data), { 'body': '', 'msgtype': 'm.text', 'formatted_body': '<strong>#1: New review request from Test User: ' 'http://example.com/r/1/</strong><p>#1: ' 'Test Review Request</p><strong><font ' 'color="#efcc96">Description</font></strong><p>My' ' description.</p><strong><font ' 'color="#efcc96">Diff</font></strong><p>http:' '//example.com/r/1/diff/1/ | Revision ' '1</p><strong><font color="#efcc96">Repository' '</font></strong><p>Test ' 'Repo</p><strong><font color="#efcc96">Branch' '</font></strong><p>my-branch</p>', 'format': 'org.matrix.custom.html' })
Testing MatrixIntegration notifies on new review request with diff
625941c2b57a9660fec33828
def update_last_sync_event(self): <NEW_LINE> <INDENT> self.database.update_last_sync_event(self.partner['id'])
Updates last sync event for partner.
625941c2cc0a2c11143dce36