code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def test_rescue(self): <NEW_LINE> <INDENT> called = {'rescued': False, 'unrescued': False} <NEW_LINE> def fake_rescue(self, context, instance_ref, network_info, image_meta): <NEW_LINE> <INDENT> called['rescued'] = True <NEW_LINE> <DEDENT> self.stubs.Set(nova.virt.fake.FakeDriver, 'rescue', fake_rescue) <NEW_LINE> def fake_unrescue(self, instance_ref, network_info): <NEW_LINE> <INDENT> called['unrescued'] = True <NEW_LINE> <DEDENT> self.stubs.Set(nova.virt.fake.FakeDriver, 'unrescue', fake_unrescue) <NEW_LINE> instance = jsonutils.to_primitive(self._create_fake_instance()) <NEW_LINE> instance_uuid = instance['uuid'] <NEW_LINE> self.compute.run_instance(self.context, instance_uuid) <NEW_LINE> self.compute.rescue_instance(self.context, instance=instance) <NEW_LINE> self.assertTrue(called['rescued']) <NEW_LINE> self.compute.unrescue_instance(self.context, instance=instance) <NEW_LINE> self.assertTrue(called['unrescued']) <NEW_LINE> self.compute.rescue_instance(self.context, instance_uuid=instance_uuid) <NEW_LINE> self.assertTrue(called['rescued']) <NEW_LINE> self.compute.unrescue_instance(self.context, instance_uuid=instance_uuid) <NEW_LINE> self.assertTrue(called['unrescued']) <NEW_LINE> self.compute.terminate_instance(self.context, instance=instance)
Ensure instance can be rescued and unrescued
625941b9b57a9660fec336ed
def test_fspl(self): <NEW_LINE> <INDENT> distance = np.array([[1000000]]) <NEW_LINE> lambda_ = np.array([[3e8 / 1e3]]) <NEW_LINE> self.assertTrue(ut.fspl(distance, lambda_))
Test utility.fspl.
625941b9925a0f43d2549ce1
def finalize_score(puzzle, view, unguessed_consonants, current_score): <NEW_LINE> <INDENT> for ch in range(len(puzzle)): <NEW_LINE> <INDENT> if puzzle[ch] in unguessed_consonants: <NEW_LINE> <INDENT> current_score += CONSONANT_BONUS <NEW_LINE> <DEDENT> <DEDENT> return current_score
(str, str, str, int) -> int Return the final score by adding CONSONANT_BONUS to current_score for each letter in view that's also in unguessed_consonants, but is hidden in view. >>> finalize_score('banana', 'ba^a^a', 'npr', 3) 7 >>> finalize_score('santiago', 'santiago', 'rp', 2) 2
625941b91f5feb6acb0c49c2
def get_default_person(self): <NEW_LINE> <INDENT> if not self.db_is_open: <NEW_LINE> <INDENT> LOG.debug("database is closed") <NEW_LINE> <DEDENT> return None
Return the default Person of the database.
625941b931939e2706e4ccdd
def test_api_play_quiz(self): <NEW_LINE> <INDENT> payload=dict(previous_questions=[]) <NEW_LINE> response = self.client.post(url_for('quizzes.play_quiz'), json=payload) <NEW_LINE> json_data = response.json['question'] <NEW_LINE> self.assertIsNotNone(json_data['question']) <NEW_LINE> self.assertIsNotNone(json_data['category']) <NEW_LINE> self.assertIsNotNone(json_data['difficulty']) <NEW_LINE> self.assertIsNotNone(json_data['answer'])
Quiz Turn: paly a quiz turn
625941b92c8b7c6e89b35631
def is_expired(self): <NEW_LINE> <INDENT> return datetime.utcnow() >= self.expires
Check token expiration with timezone awareness
625941b95f7d997b87174909
def __init__(self, *, confidence_level: str = None, text: str = None, provenance_ids: List[str] = None, location: 'Location' = None) -> None: <NEW_LINE> <INDENT> self.confidence_level = confidence_level <NEW_LINE> self.text = text <NEW_LINE> self.provenance_ids = provenance_ids <NEW_LINE> self.location = location
Initialize a ContractTypes object. :param str confidence_level: (optional) The confidence level in the identification of the contract type. :param str text: (optional) The contract type. :param List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`.
625941b9097d151d1a222cc9
def cast(*args): <NEW_LINE> <INDENT> return _itkIntensityWindowingImageFilterPython.itkIntensityWindowingImageFilterIF3IUS3_cast(*args)
cast(itkLightObject obj) -> itkIntensityWindowingImageFilterIF3IUS3
625941b90383005118ecf452
def __repr__(self): <NEW_LINE> <INDENT> return 'Edge(%s, %s)' % (repr(self[0]), repr(self[1]))
Return a string representation of this object that can be evaluated as a Python expression.
625941b923849d37ff7b2eff
def testLoadListsWithoutRepetitions(self): <NEW_LINE> <INDENT> ld = ListDifference("testdirs/01/in02.txt", "testdirs/01/diff02.txt", "testdirs/01/out02.txt") <NEW_LINE> ld.inputList.sort() <NEW_LINE> ld.differenceList.sort() <NEW_LINE> self.assertEqual(ld.inputList, ["goodbye", "hello", "joe", "john", "karl"]) <NEW_LINE> self.assertEqual(ld.differenceList, ["john","mike"])
Open the list files and load the contents of them as lists but without repetitions
625941b95166f23b2e1a4fc6
def dag_to_str(self, morf_dag): <NEW_LINE> <INDENT> conc_dag = '' <NEW_LINE> for item in morf_dag: <NEW_LINE> <INDENT> num1, num2, (forma, lemat, tag, posp, kwal) = item <NEW_LINE> line_string = '\t'.join((str(num1), str(num2), forma, lemat, tag, ','.join(posp), ','.join(kwal), '0.0', '', '', '' + '\n')) <NEW_LINE> conc_dag += line_string <NEW_LINE> <DEDENT> return conc_dag
Convert a DAG in the Morfeusz-compliant format to a DAG in the Concraft-compliant format.
625941b9f548e778e58cd3e9
def get_required_slot_names_by_task(taskname): <NEW_LINE> <INDENT> filename = "task_{}.json".format(taskname) <NEW_LINE> task_config_path = os.path.join(this_file_path, "template", filename) <NEW_LINE> with open(task_config_path) as json_file: <NEW_LINE> <INDENT> data = json.load(json_file) <NEW_LINE> <DEDENT> return data.get("required_slots")
read taskname from config json and then read the slot config file to get the slot names :param taskname: current task/story name :return: the slot names , list[str]
625941b9be383301e01b52fa
def createDistanceMatrix(self, distance_function, child_process_chunksize = 15, number_of_cores = None): <NEW_LINE> <INDENT> if number_of_cores is None: <NEW_LINE> <INDENT> number_of_cores = multiprocessing.cpu_count() <NEW_LINE> <DEDENT> print('Creating distance matrix using ', number_of_cores, 'cores.') <NEW_LINE> genomes_df = self.genomes.copy() <NEW_LINE> no_of_genes, no_of_genomes = genomes_df.shape <NEW_LINE> list_of_genome_names = list(genomes_df.columns) <NEW_LINE> list_of_genomes = [list(genomes_df.loc[:, name]) for name in list_of_genome_names] <NEW_LINE> distance_matrix = [] <NEW_LINE> for genome in tqdm(list_of_genomes): <NEW_LINE> <INDENT> with Pool(processes = number_of_cores) as pool: <NEW_LINE> <INDENT> fut = pool.starmap_async(distance_function, zip([genome] * len(list_of_genomes), list_of_genomes), chunksize = child_process_chunksize) <NEW_LINE> fut.wait() <NEW_LINE> <DEDENT> distance_matrix.append(fut.get()) <NEW_LINE> <DEDENT> distance_matrix = pd.DataFrame(distance_matrix, columns = list_of_genome_names, index = list_of_genome_names) <NEW_LINE> return distance_matrix
Takes a dictionary of KO sets and returns a distance (or similarity) matrix which is basically how many genes do they have in common.
625941b9f7d966606f6a9e75
def test_calls_permissions_for_user(self): <NEW_LINE> <INDENT> check_permissions(self.parent, self.user, False, False) <NEW_LINE> assert self.parent.permissions_for_user.called
Check call to parent page's permissions_for_user method.
625941b93346ee7daa2b2bd7
def index(self): <NEW_LINE> <INDENT> return self.__sent[0].para_index()
Gets the index of the paragraph.
625941b9711fe17d825421e0
def publish(self, subject, message): <NEW_LINE> <INDENT> log.debug('publish(%s, %s)', str(subject), str(message)) <NEW_LINE> for owner in self._subscriptions.keys(): <NEW_LINE> <INDENT> for token in self._subscriptions[owner].keys(): <NEW_LINE> <INDENT> if subject in self._subscriptions[owner][token]: <NEW_LINE> <INDENT> self._subscriptions[owner][token][subject](token, subject, copy.deepcopy(message))
Send messade to all subscribers :param subject: message subject :param message: message data
625941b9ad47b63b2c509df7
def __check_cancel(self): <NEW_LINE> <INDENT> return self.__canceling
Private method. Provides a callback method for internal code to use to determine whether the current action has been canceled.
625941b963f4b57ef0000f90
def ResetDisplayList(self): <NEW_LINE> <INDENT> pass
ResetDisplayList.
625941b97047854f462a127b
def test_bad_git_url(self): <NEW_LINE> <INDENT> course_key = CourseLocator('org', 'course', 'run') <NEW_LINE> with self.assertRaisesRegexp(GitExportError, unicode(GitExportError.URL_BAD)): <NEW_LINE> <INDENT> git_export_utils.export_to_git(course_key, 'Sillyness') <NEW_LINE> <DEDENT> with self.assertRaisesRegexp(GitExportError, unicode(GitExportError.URL_BAD)): <NEW_LINE> <INDENT> git_export_utils.export_to_git(course_key, 'example.com:edx/notreal') <NEW_LINE> <DEDENT> with self.assertRaisesRegexp(GitExportError, unicode(GitExportError.URL_NO_AUTH)): <NEW_LINE> <INDENT> git_export_utils.export_to_git(course_key, 'http://blah')
Test several bad URLs for validation
625941b999cbb53fe6792a55
def computeForce(self, other): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> r = self.position - other.position <NEW_LINE> self.force = self.charge * other.charge / r.norm() ** 3 * r <NEW_LINE> <DEDENT> except (AttributeError, TypeError, ValueError): <NEW_LINE> <INDENT> raise TypeError("Tried to compute the force created by " "a non-Ion object")
Calcule la force électrostatique de Coulomb exercée par un Ion other sur self. Masque la méthode de Particle. Args : other(Ion): Un autre Ion, source de l'interaction. Raises : TypeError si other n'est pas un objet Ion
625941b931939e2706e4ccde
def force_long_type(): <NEW_LINE> <INDENT> Marshaller.dispatch[type(0)] = lambda _, v, w: w( "<value><i8>%d</i8></value>" % v)
Since in python3 theres no long type anymore, we have to force the use of long type at xmlrpc here. :return:
625941b9b7558d58953c4d89
def test_generic_fk(self): <NEW_LINE> <INDENT> class TagSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> tagged_item = serializers.StringRelatedField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Tag <NEW_LINE> fields = ('tag', 'tagged_item') <NEW_LINE> <DEDENT> <DEDENT> serializer = TagSerializer(Tag.objects.all(), many=True) <NEW_LINE> expected = [ { 'tag': 'django', 'tagged_item': 'Bookmark: https://www.djangoproject.com/' }, { 'tag': 'python', 'tagged_item': 'Bookmark: https://www.djangoproject.com/' }, { 'tag': 'reminder', 'tagged_item': 'Note: Remember the milk' } ] <NEW_LINE> self.assertEqual(serializer.data, expected)
Test a relationship that spans a GenericForeignKey field. IE. A forward generic relationship.
625941b94428ac0f6e5ba660
def _raw_fields(self, positions, scatterer, medium_wavevec, medium_index, illum_polarization): <NEW_LINE> <INDENT> index_ratio = scatterer.n / medium_index <NEW_LINE> size_parameter = medium_wavevec * scatterer.r <NEW_LINE> rho, phi, z = positions <NEW_LINE> pol_angle = np.arctan2( illum_polarization.values[1], illum_polarization.values[0]) <NEW_LINE> phi += pol_angle <NEW_LINE> phi %= (2 * np.pi) <NEW_LINE> particle_kz = np.mean(z) <NEW_LINE> if np.ptp(z) > 1e-13 * (1 + np.abs(particle_kz)): <NEW_LINE> <INDENT> msg = ("mielens currently assumes the detector is a fixed " + "z from the particle") <NEW_LINE> raise ValueError(msg) <NEW_LINE> <DEDENT> field_calculator = MieLensCalculator( particle_kz=particle_kz, index_ratio=index_ratio, size_parameter=size_parameter, lens_angle=self.lens_angle, **self.calculator_accuracy_kwargs) <NEW_LINE> fields_pll, fields_prp = field_calculator.calculate_scattered_field( rho, phi) <NEW_LINE> parallel = np.array([np.cos(pol_angle), np.sin(pol_angle)]) <NEW_LINE> perpendicular = np.array([-np.sin(pol_angle), np.cos(pol_angle)]) <NEW_LINE> field_xyz = np.zeros([3, fields_pll.size], dtype='complex') <NEW_LINE> for i in range(2): <NEW_LINE> <INDENT> field_xyz[i, :] += fields_pll * parallel[i] <NEW_LINE> field_xyz[i, :] += fields_prp * perpendicular[i] <NEW_LINE> <DEDENT> incident_field_x, _ = field_calculator.calculate_incident_field() <NEW_LINE> field_xyz *= np.exp(1j * particle_kz) / incident_field_x <NEW_LINE> return field_xyz
Parameters ---------- positions : (3, N) numpy.ndarray The (k * rho, phi, z) coordinates, relative to the sphere, of the points to calculate the fields. Note that the radial coordinate is rescaled by the wavevector. scatterer : ``scatterer.Sphere`` object medium_wavevec : float medium_index : float illum_polarization : 2-element tuple The (x, y) field polarizations.
625941b98a43f66fc4b53ed7
def get_command_line_configuration(configuration_schema, command_line_options): <NEW_LINE> <INDENT> command_line_options = command_line_options[1:] <NEW_LINE> command_line_options = " ".join(command_line_options) <NEW_LINE> command_line_options = command_line_options.replace("=", " ") <NEW_LINE> command_line_options = command_line_options.split(" ") <NEW_LINE> configuration = {} <NEW_LINE> for command_line_option, value in zip(command_line_options[::2], command_line_options[1::2]): <NEW_LINE> <INDENT> if (not command_line_option.startswith("--") and not command_line_option.startswith("-")): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> for target, option in six.iteritems(configuration_schema): <NEW_LINE> <INDENT> if command_line_option in option.command_line_options: <NEW_LINE> <INDENT> configuration[target] = value <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return configuration
Get configuration, based on the given arguments to the program. Notes: * The first argument is omitted, as it's the script path. * Both '--option=value' and '--option value' formats are supported. * Both '--<option>' and '-<option>' formats are supported. Args: configuration_schema (dict): a match between each target option to its sources. command_line_options (iterable): the program arguments, as given by `sys.argv`. Returns: dict: a match between each target option to the given value.
625941b9293b9510aa2c3107
def get_user(user_id): <NEW_LINE> <INDENT> return User.query.get(user_id)
Return a speciic user from the database.
625941b9de87d2750b85fbfc
@api_view(["GET"]) <NEW_LINE> @permission_classes([AllowAny]) <NEW_LINE> def monthly_leaderboard(request): <NEW_LINE> <INDENT> date = datetime.now() <NEW_LINE> month = date.month <NEW_LINE> year = date.year <NEW_LINE> topmonth = ( Trash.objects.values("user__username") .annotate(Sum("weight")) .filter(takeout_date__year=year) .filter(takeout_date__month=month) ).order_by("weight__sum")[:5] <NEW_LINE> return Response(topmonth)
This view returns a list of the top 5 of the rankings for low waste given the month.
625941b916aa5153ce3622e6
def conv2D(x, W): <NEW_LINE> <INDENT> return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding = "SAME")
Initialise a 2D Tensorflow convolutional layer based on input vector x and filter vector W Args: x: Input matrix of the convolutional layer. Tensorflow variable of unknown dimension W: Input filter of the convolutional layer. 4D Tensorflow variable of dimension (filter_height, filter_width, nb_input_channels, nb_output_channels) Returns: : Initialised 2D convolutional layer. 2D Tensorflow convolutional layer with input x, filter W and stride (1,1)
625941b9d8ef3951e32433ab
def test_help_for_command_add(): <NEW_LINE> <INDENT> usage_string = ( 'usage: dispass add [-g] [-n] [-s] <labelspec> [<labelspec2>] [...]\n' ' dispass add [-i] [-g] [-h]' ) <NEW_LINE> cmd = DispassCommand(['add', '-h']) <NEW_LINE> assert cmd_output_startswith(cmd, usage_string) <NEW_LINE> cmd = DispassCommand(['add', '--help']) <NEW_LINE> assert cmd_output_startswith(cmd, usage_string) <NEW_LINE> cmd = DispassCommand(['help', 'add']) <NEW_LINE> assert cmd_output_startswith(cmd, usage_string)
commands: get help for add command via all possible combinations
625941b94e696a04525c92c3
def worker_start(self, worker): <NEW_LINE> <INDENT> worker.servers[self.name] = servers = [] <NEW_LINE> for sock in worker.params.sockets: <NEW_LINE> <INDENT> server = self.create_server(worker, sock.sock) <NEW_LINE> server.bind_event('stop', partial(self._stop_worker, worker)) <NEW_LINE> servers.append(server)
Start the worker by invoking the :meth:`create_server` method.
625941b9851cf427c661a385
def get_sequential_model(input_nodes, first_layer, hidden_layer, output_shape, activation_input, activation_hidden, activation_output): <NEW_LINE> <INDENT> model = Sequential() <NEW_LINE> model.add(Dense(first_layer, activation = activation_input, input_shape = input_nodes)) <NEW_LINE> for layer in hidden_layer: <NEW_LINE> <INDENT> model.add(Dense(layer, activation = activation_hidden)) <NEW_LINE> <DEDENT> model.add(Dense(output_shape, activation = activation_output)) <NEW_LINE> return model
Define a dense sequential neural network with input_nodes number of input nodes, hidden_layer a list of hidden layers, output_shape defines output shape. In addition the types of activation need to be defined.
625941b94e4d5625662d424b
def output(self): <NEW_LINE> <INDENT> self.x_imgs = self.prev_layer.output() <NEW_LINE> return numpy.asarray(map( lambda i: tanh(self.b[i] + reduce( lambda res, j: res + conv2d(self.x_imgs[j], self.theta[i]), self.connections[i], 0 )), xrange(0, len(self.connections)) ))
Generate output of this layer
625941b9cdde0d52a9e52e9d
def acc(self): <NEW_LINE> <INDENT> AccountDialog(self)
Instantiate account information window.
625941b9d58c6744b4257acf
def trap(self, height): <NEW_LINE> <INDENT> stack = [-1] <NEW_LINE> rightmax=0; <NEW_LINE> for i in range(len(height)-1,-1,-1): <NEW_LINE> <INDENT> if rightmax < height[i]: <NEW_LINE> <INDENT> stack.append(i) <NEW_LINE> rightmax = height[i] <NEW_LINE> <DEDENT> <DEDENT> leftmax=0 <NEW_LINE> sum=0 <NEW_LINE> for i in range(0,len(height)): <NEW_LINE> <INDENT> if i == stack[len(stack)-1]:stack.pop() <NEW_LINE> if stack[len(stack)-1] == -1:rightmax=-1; <NEW_LINE> else:rightmax = height[stack[len(stack)-1]] <NEW_LINE> if height[i] < leftmax and height[i] < rightmax: <NEW_LINE> <INDENT> sum+=min(leftmax,rightmax) - height[i] <NEW_LINE> <DEDENT> leftmax = max(leftmax,height[i]) <NEW_LINE> <DEDENT> return sum
:type height: List[int] :rtype: int
625941b97d43ff24873a2b12
def _release(self, event): <NEW_LINE> <INDENT> for zoom_id in self._ids_zoom: <NEW_LINE> <INDENT> self.figure.canvas.mpl_disconnect(zoom_id) <NEW_LINE> <DEDENT> self._ids_zoom = [] <NEW_LINE> if not self._xypress: <NEW_LINE> <INDENT> self._cancel_action() <NEW_LINE> return <NEW_LINE> <DEDENT> last_a = [] <NEW_LINE> for cur_xypress in self._xypress: <NEW_LINE> <INDENT> x, y = event.x, event.y <NEW_LINE> lastx, lasty, a, _ind, view = cur_xypress <NEW_LINE> if abs(x - lastx) < 5 or abs(y - lasty) < 5: <NEW_LINE> <INDENT> self._cancel_action() <NEW_LINE> return <NEW_LINE> <DEDENT> twinx, twiny = False, False <NEW_LINE> if last_a: <NEW_LINE> <INDENT> for la in last_a: <NEW_LINE> <INDENT> if a.get_shared_x_axes().joined(a, la): <NEW_LINE> <INDENT> twinx = True <NEW_LINE> <DEDENT> if a.get_shared_y_axes().joined(a, la): <NEW_LINE> <INDENT> twiny = True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> last_a.append(a) <NEW_LINE> if self._button_pressed == 1: <NEW_LINE> <INDENT> direction = 'in' <NEW_LINE> <DEDENT> elif self._button_pressed == 3: <NEW_LINE> <INDENT> direction = 'out' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> a._set_view_from_bbox((lastx, lasty, x, y), view, direction, self._zoom_mode, twinx, twiny) <NEW_LINE> <DEDENT> self._zoom_mode = None <NEW_LINE> self.toolmanager.get_tool(_views_positions).push_current() <NEW_LINE> self._cancel_action()
the release mouse button callback in zoom to rect mode
625941b992d797404e303ff8
def custom_lookup_rows(self, key, values, fields=[]): <NEW_LINE> <INDENT> db = current.db <NEW_LINE> table = current.s3db.supply_item_category <NEW_LINE> ctable = db.supply_catalog <NEW_LINE> ptable = db.supply_item_category.with_alias("supply_parent_item_category") <NEW_LINE> gtable = db.supply_item_category.with_alias("supply_grandparent_item_category") <NEW_LINE> left = [ctable.on(ctable.id == table.catalog_id), ptable.on(ptable.id == table.parent_item_category_id), gtable.on(gtable.id == ptable.parent_item_category_id), ] <NEW_LINE> qty = len(values) <NEW_LINE> if qty == 1: <NEW_LINE> <INDENT> query = (table.id == values[0]) <NEW_LINE> limitby = (0, 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> query = (table.id.belongs(values)) <NEW_LINE> limitby = (0, qty) <NEW_LINE> <DEDENT> rows = db(query).select(*self.fields, left=left, limitby=limitby) <NEW_LINE> self.queries += 1 <NEW_LINE> return rows
Custom lookup method for item category rows, does a left join with the parent category. Parameters key and fields are not used, but are kept for API compatibility reasons. @param values: the supply_item_category IDs
625941b97b25080760e392c9
def __update_register_features(self, unique_id, feature): <NEW_LINE> <INDENT> if self.__next_feature_index > self.__register_features.shape[0] - len(feature['feature']): <NEW_LINE> <INDENT> self.__register_features = np.concatenate((self.__register_features, np.empty(shape=self.__register_features.shape, dtype=np.float32))) <NEW_LINE> self.__register_info = np.concatenate((self.__register_info, np.empty(shape=self.__register_info.shape, dtype=np.int64)), axis=1) <NEW_LINE> <DEDENT> for f in feature['feature']: <NEW_LINE> <INDENT> self.__register_features[self.__next_feature_index] = f <NEW_LINE> self.__register_info[0][self.__next_feature_index] = unique_id <NEW_LINE> self.__register_info[1][self.__next_feature_index] = int(time.mktime(time.strptime(feature['time_stamp'], "%Y-%m-%d %H:%M:%S"))) <NEW_LINE> self.__next_feature_index += 1
Update register features array
625941b98e71fb1e9831d61c
def _stack_to_string(self, stack): <NEW_LINE> <INDENT> value_str = " |" <NEW_LINE> while not stack.is_empty(): <NEW_LINE> <INDENT> value_str = F"| {stack.top()} {value_str}" <NEW_LINE> stack.pop() <NEW_LINE> <DEDENT> return value_str
Return a string of the stack values seperated by "|".
625941b957b8e32f5248330f
def columns(): <NEW_LINE> <INDENT> con = sqlite3.connect(DB_PATH) <NEW_LINE> cur = con.cursor() <NEW_LINE> cur.execute("SELECT * " "FROM {tbl} " "LIMIT 1".format(tbl=REG_TBL)) <NEW_LINE> names = [description[0] for description in cur.description] <NEW_LINE> cur.close() <NEW_LINE> con.close() <NEW_LINE> return names
list column names :return list: of column names
625941b9cb5e8a47e48b791d
def rhoc_z(self, z): <NEW_LINE> <INDENT> return self.rhoc*(1+z)**3
:param z: :return:
625941b99c8ee82313fbb5e3
def results_to_proto(results): <NEW_LINE> <INDENT> results_proto = Results() <NEW_LINE> for result in results: <NEW_LINE> <INDENT> results_proto.results.append(result_to_proto(result)) <NEW_LINE> <DEDENT> return results_proto
Given a list of result dicts, convert it to a tcav.Results proto. Args: results: a list of dictionaries returned by tcav.run() Returns: TCAV.Results proto
625941b923849d37ff7b2f00
def _is_straight(self): <NEW_LINE> <INDENT> self.hand.sort(key=Card.getRank) <NEW_LINE> _isStraight = True <NEW_LINE> if self.hand[-1].getRank() == 14 and self.hand[0].getRank() == 2: <NEW_LINE> <INDENT> _previousRank = 1 <NEW_LINE> for card in self.hand[:-1]: <NEW_LINE> <INDENT> if not card.getRank() == _previousRank + 1: <NEW_LINE> <INDENT> _isStraight = False <NEW_LINE> break <NEW_LINE> <DEDENT> _previousRank = card.getRank() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> _previousRank = self.hand[0].getRank() <NEW_LINE> for card in self.hand[1:]: <NEW_LINE> <INDENT> if not card.getRank() == _previousRank + 1: <NEW_LINE> <INDENT> _isStraight = False <NEW_LINE> break <NEW_LINE> <DEDENT> _previousRank = card.getRank() <NEW_LINE> <DEDENT> <DEDENT> self.isStraight = _isStraight
Five cards with consecutive ranks
625941b91d351010ab85598c
def test_trust_key(self): <NEW_LINE> <INDENT> ret = {'message': 'Only specify one argument, fingerprint or keyid', 'res': False} <NEW_LINE> ret1 = {'message': 'KeyID 3F0C8 not in GPG keychain', 'res': False} <NEW_LINE> ret2 = {'message': 'Required argument, fingerprint or keyid', 'res': False} <NEW_LINE> ret3 = ('ERROR: Valid trust levels - expired,unknown,' 'not_trusted,marginally,fully,ultimately') <NEW_LINE> ret4 = {'res': False, 'message': 'Fingerprint not found for keyid 3F0C8E90D459D89A'} <NEW_LINE> mock_conf = MagicMock(return_value='') <NEW_LINE> mock_user = MagicMock(return_value={'home': 'salt'}) <NEW_LINE> mock_cmd = MagicMock(return_value={'retcode': 1, 'stderr': 'error'}) <NEW_LINE> with patch.dict(gpg.__salt__, {'config.option': mock_conf, 'user.info': mock_user, 'cmd.run_all': mock_cmd}): <NEW_LINE> <INDENT> self.assertDictEqual(gpg.trust_key(keyid='3F0C8E90D459D89A', fingerprint='53C'), ret) <NEW_LINE> self.assertDictEqual(gpg.trust_key(keyid='3F0C8'), ret1) <NEW_LINE> self.assertDictEqual(gpg.trust_key(), ret2) <NEW_LINE> self.assertEqual(gpg.trust_key(fingerprint='53C9'), ret3) <NEW_LINE> self.assertEqual(gpg.trust_key(fingerprint='53C96', trust_level='not_trusted'), {'res': False, 'message': 'error'}) <NEW_LINE> <DEDENT> with patch.object(gpg, 'get_key', MagicMock(return_value=RET)): <NEW_LINE> <INDENT> self.assertDictEqual(gpg.trust_key(keyid='3F0C8E90D459D89A'), ret4)
Tests if it set the trust level for a key in GPG keychain
625941b938b623060ff0ac5e
def check_brackets(label): <NEW_LINE> <INDENT> stack = [] <NEW_LINE> pushChars, popChars = "<({[", ">)}]" <NEW_LINE> for c in label: <NEW_LINE> <INDENT> if c in pushChars: <NEW_LINE> <INDENT> stack.append(c) <NEW_LINE> <DEDENT> elif c in popChars: <NEW_LINE> <INDENT> if not stack: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> stackTop = stack.pop() <NEW_LINE> balancingBracket = pushChars[popChars.index(c)] <NEW_LINE> if stackTop != balancingBracket: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return not stack
check if all brackets in *label match, return True / False
625941b9d164cc6175782bbc
def __init__(self, instance_of): <NEW_LINE> <INDENT> if not isinstance(instance_of, six.class_types): <NEW_LINE> <INDENT> raise Error('ExternalDependency provider expects to get class, ' + 'got {0} instead'.format(str(instance_of))) <NEW_LINE> <DEDENT> self.instance_of = instance_of <NEW_LINE> self.provide = self.__call__ <NEW_LINE> super(ExternalDependency, self).__init__()
Initializer.
625941b94c3428357757c199
def malloc(self, shape, dtype=None, stream=None, fill=None): <NEW_LINE> <INDENT> stream = stream or self.stream <NEW_LINE> dtype = dtype or self.device._default_dtype <NEW_LINE> return self.device.malloc(shape, dtype, fill, stream)
Allocates device memory. Parameters ---------- shape : tuple The shape of the array to allocate. dtype : np.dtype That data type of the array. fill : scalar or np.ndarray, optional Default value to set allocated array to. stream : c_void_p, optional CUDA stream to associate the returned object with. Returns ------- dev_ptr: c_void_p Pointer to allocated device memory.
625941b9a4f1c619b28afeb0
def get_hangouts_tokens(cookies, driverpath): <NEW_LINE> <INDENT> tmprinter = TMPrinter() <NEW_LINE> chrome_options = get_chrome_options_args(config.headless) <NEW_LINE> options = { 'connection_timeout': None } <NEW_LINE> tmprinter.out("Starting browser...") <NEW_LINE> driver = webdriver.Chrome( executable_path=driverpath, seleniumwire_options=options, options=chrome_options ) <NEW_LINE> driver.header_overrides = config.headers <NEW_LINE> tmprinter.out("Setting cookies...") <NEW_LINE> driver.get("https://hangouts.google.com/robots.txt") <NEW_LINE> for k, v in cookies.items(): <NEW_LINE> <INDENT> driver.add_cookie({'name': k, 'value': v}) <NEW_LINE> <DEDENT> tmprinter.out("Fetching Hangouts homepage...") <NEW_LINE> driver.get("https://hangouts.google.com") <NEW_LINE> tmprinter.out("Waiting for the /v2/people/me/blockedPeople request, it " "can takes a few minutes...") <NEW_LINE> req = driver.wait_for_request('/v2/people/me/blockedPeople', timeout=120) <NEW_LINE> tmprinter.out("Request found !") <NEW_LINE> driver.close() <NEW_LINE> tmprinter.out("") <NEW_LINE> auth_token = req.headers["Authorization"] <NEW_LINE> hangouts_token = req.url.split("key=")[1] <NEW_LINE> return (auth_token, hangouts_token)
gets auth and hangout token
625941b9d268445f265b4ce4
def start(self, args): <NEW_LINE> <INDENT> enable_log() <NEW_LINE> self.results = App._init_results(self.config) <NEW_LINE> if args.poll_seconds: <NEW_LINE> <INDENT> self.config.override_monitor_setting( 'poll_seconds', args.poll_seconds ) <NEW_LINE> <DEDENT> if self.config.log_file: <NEW_LINE> <INDENT> set_log_file(self.config.log_file) <NEW_LINE> log.debug("Opening log file {}".format(self.config.log_file)) <NEW_LINE> <DEDENT> self._start_monitoring() <NEW_LINE> if self.config.http_port: <NEW_LINE> <INDENT> log.info("Starting web frontend on port {}".format( self.config.http_port )) <NEW_LINE> self._start_frontend()
Start up all of the application components
625941b9c432627299f04ab3
def dataCleanup(data): <NEW_LINE> <INDENT> classDistribution = defaultdict(list) <NEW_LINE> for i in range(0, len(data)): <NEW_LINE> <INDENT> className = data[i][14] <NEW_LINE> if className not in classDistribution: <NEW_LINE> <INDENT> classDistribution[className] = [] <NEW_LINE> <DEDENT> classDistribution[className].append(data[i][:-1]) <NEW_LINE> <DEDENT> return classDistribution
The function creates a dictionary with classes as keys and values as the instances belonging to that class. The input is train fold dataset. :param data: train fold :return: classDistribution : dictionary with classes as keys and instances as values.
625941b916aa5153ce3622e7
def __init__(self): <NEW_LINE> <INDENT> self.logger = logging.getLogger("main.database.DbUtils")
Database utilities
625941b915baa723493c3de1
@app.route("/history") <NEW_LINE> @login_required <NEW_LINE> def history(): <NEW_LINE> <INDENT> rows = db.execute("SELECT * FROM lookups WHERE user_id = :user", user=session["user_id"]) <NEW_LINE> lookups = [] <NEW_LINE> for row in rows: <NEW_LINE> <INDENT> lookups.insert(0,list((row['brand'], row['title'], row['vegan_status'], row['barcode'], row['barcode_url'], row['time']))) <NEW_LINE> <DEDENT> return render_template("history.html", lookups=lookups)
Show history of transactions
625941b95fcc89381b1e1533
def scatterplot(self,plotobj): <NEW_LINE> <INDENT> plt.subplots(1) <NEW_LINE> arr=plotobj.histogram.weights.nonzero() <NEW_LINE> y=arr[1] <NEW_LINE> x=arr[0] <NEW_LINE> cc = plotobj.histogram.weights[x,y] <NEW_LINE> plt.scatter(x,y,s=50, c=cc, label=plotobj.histogram.title) <NEW_LINE> plt.legend() <NEW_LINE> plt.show()
A routine for replotting sparse data as a scatter plot. plotobj should be a maps[register_number] not a dd(histogram_number) instance.
625941b92ae34c7f2600cfa1
def is_adjacent_to(self, o): <NEW_LINE> <INDENT> assert type(o) is Location, "incorrect type of arg o: should be Location, is {}".format(type(o)) <NEW_LINE> result = _lib.bc_Location_is_adjacent_to(self._ptr, o._ptr) <NEW_LINE> _check_errors() <NEW_LINE> result = bool(result) <NEW_LINE> return result
Determines whether this location is adjacent to the specified location, including diagonally. Note that squares are not adjacent to themselves, and squares on different planets are not adjacent to each other. Also, nothing is adjacent to something not on a map. :type self: Location :type o: Location :rtype: bool
625941b9de87d2750b85fbfd
def reachableReactions(rxn, sinks): <NEW_LINE> <INDENT> soup = sinks <NEW_LINE> pending = set(rxn) <NEW_LINE> newPending, newSoup = inSoup(rxn, pending, soup) <NEW_LINE> iteration = 0 <NEW_LINE> while (len(newPending - pending) > 0 or len(newSoup - soup) > 0): <NEW_LINE> <INDENT> pending = newPending <NEW_LINE> soup = newSoup <NEW_LINE> newPending, newSoup = inSoup(rxn, pending, soup) <NEW_LINE> iteration += 1 <NEW_LINE> <DEDENT> return newPending, newSoup, iteration
Look for reachable reactions.
625941b999fddb7c1c9de202
def read_bytes(self, expected_length): <NEW_LINE> <INDENT> raise NotImplementedError
Read fixed-length bytes
625941b9d99f1b3c44c67405
def __init__(self, chromosomes): <NEW_LINE> <INDENT> super(InMemoryRefReader, self).__init__() <NEW_LINE> self._chroms = {} <NEW_LINE> contigs = [] <NEW_LINE> for i, (contig_name, start, bases) in enumerate(chromosomes): <NEW_LINE> <INDENT> if start < 0: <NEW_LINE> <INDENT> raise ValueError('start={} must be >= for chromosome={}'.format( start, contig_name)) <NEW_LINE> <DEDENT> if contig_name in self._chroms: <NEW_LINE> <INDENT> raise ValueError('Duplicate chromosome={} detect'.format(contig_name)) <NEW_LINE> <DEDENT> if not bases: <NEW_LINE> <INDENT> raise ValueError( 'Bases must contain at least one base, but got "{}"'.format(bases)) <NEW_LINE> <DEDENT> end = start + len(bases) <NEW_LINE> self._chroms[contig_name] = _InMemoryChromosome(start, end, bases) <NEW_LINE> contigs.append( reference_pb2.ContigInfo( name=contig_name, n_bases=end, pos_in_fasta=i)) <NEW_LINE> <DEDENT> self.header = RefFastaHeader(contigs=contigs)
Initializes an InMemoryRefReader using data from chromosomes. Args: chromosomes: List[tuple]. The chromosomes we are caching in memory as a list of tuples. Each tuple must be exactly three string elements in length, containing (chromosome name, start, bases). Raises: ValueError: If any of the InMemoryChromosome are invalid.
625941b9d99f1b3c44c67406
def b(text: str, func: callable = None, *arg, **kw) -> None: <NEW_LINE> <INDENT> global m <NEW_LINE> m.b(text, func, *arg, **kw)
【控件:按钮】 向当前页面的最后一行的末尾插入按钮。 text: str 按钮上的文本。 func: callable 返回函数。 当按钮按下时,返回函数被触发,且其执行效果类似于 func(*arg, **kw); color: str 设置按钮颜色。颜色名可从 https://www.w3schools.com/colors/colors_names.asp 中任意选择,如 "red"。 disabled: bool 设置按钮禁用与否。若为True,则按钮被禁用,无法点击。 popup: str 设置按钮气泡文本。若设置,则当鼠标移到按钮上方的时候,会弹出写有文本的气泡。 一般用于对按钮功能的解释,或一些与游戏性有关的用途。 用法举例: api.b('TEST_BUTTON', test_func, 1, 'two', color='red', popup='测试文本') 会显示一个文本为TEST_BUTTON的红色按钮, 鼠标移上去会显示一个写有“测试文本”的气泡出现, 按下按钮,会触发test_func函数 相当于执行代码:test_func(1, 'two') 注意:color和popup参数会被自动除去,不会传入要触发的函数中
625941b94527f215b584c2ca
@cache.cache('pgcd', expire=3600) <NEW_LINE> def pgcd(a, b): <NEW_LINE> <INDENT> if a < b: <NEW_LINE> <INDENT> return pgcd(b, a) <NEW_LINE> <DEDENT> if b == 0: <NEW_LINE> <INDENT> return a <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return pgcd(b, (a % b))
the euclidean algorithm
625941b907d97122c41786fa
def _calculate_s_powder_over_atoms_core(self, q_indx=None): <NEW_LINE> <INDENT> atoms_items = {} <NEW_LINE> atoms = range(self._num_atoms) <NEW_LINE> self._prepare_data(k_point=q_indx) <NEW_LINE> if PATHOS_FOUND: <NEW_LINE> <INDENT> p_local = ProcessingPool(nodes=AbinsModules.AbinsParameters.threads) <NEW_LINE> result = p_local.map(self._calculate_s_powder_one_atom, atoms) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = [self._calculate_s_powder_one_atom(atom=atom) for atom in atoms] <NEW_LINE> <DEDENT> for atom in range(self._num_atoms): <NEW_LINE> <INDENT> atoms_items["atom_%s" % atom] = {"s": result[atoms.index(atom)]} <NEW_LINE> self._report_progress(msg="S for atom %s" % atom + " has been calculated.") <NEW_LINE> <DEDENT> return atoms_items
Helper function for _calculate_s_powder_1d. :returns: Python dictionary with S data
625941b9379a373c97cfa9b9
def position_after(self, a, b): <NEW_LINE> <INDENT> return self.position_at_least(a, b) and not self.position_equal(a, b)
Returns true if position 'a' is after 'b'.
625941b9be7bc26dc91cd474
def identity(payload): <NEW_LINE> <INDENT> user_id = payload['identity'] <NEW_LINE> return UserModel.find_by_id(user_id)
Receives the JWT payload.
625941b9eab8aa0e5d26d9cd
def pc_input_buffers_full_avg(self, *args): <NEW_LINE> <INDENT> return _blocks_swig1.vector_sink_i_sptr_pc_input_buffers_full_avg(self, *args)
pc_input_buffers_full_avg(vector_sink_i_sptr self, int which) -> float pc_input_buffers_full_avg(vector_sink_i_sptr self) -> pmt_vector_float
625941b91d351010ab85598d
def sessionattendancelog_save_with_http_info(self, id, **kwargs): <NEW_LINE> <INDENT> local_var_params = locals() <NEW_LINE> all_params = [ 'id', 'unknown_base_type' ] <NEW_LINE> all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) <NEW_LINE> for key, val in six.iteritems(local_var_params['kwargs']): <NEW_LINE> <INDENT> if key not in all_params: <NEW_LINE> <INDENT> raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method sessionattendancelog_save" % key ) <NEW_LINE> <DEDENT> local_var_params[key] = val <NEW_LINE> <DEDENT> del local_var_params['kwargs'] <NEW_LINE> if self.api_client.client_side_validation and ('id' not in local_var_params or local_var_params['id'] is None): <NEW_LINE> <INDENT> raise ApiValueError("Missing the required parameter `id` when calling `sessionattendancelog_save`") <NEW_LINE> <DEDENT> collection_formats = {} <NEW_LINE> path_params = {} <NEW_LINE> if 'id' in local_var_params: <NEW_LINE> <INDENT> path_params['id'] = local_var_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> if 'unknown_base_type' in local_var_params: <NEW_LINE> <INDENT> body_params = local_var_params['unknown_base_type'] <NEW_LINE> <DEDENT> header_params['Content-Type'] = self.api_client.select_header_content_type( ['application/json']) <NEW_LINE> auth_settings = ['bearerAuth'] <NEW_LINE> return self.api_client.call_api( '/sessionattendancelog/{id}', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type=None, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats)
Create or edit a class attendance log # noqa: E501 Allows the user to create or edit a class attendance log. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.sessionattendancelog_save_with_http_info(id, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str id: The id of the att log to save (leave empty to create a new one). (required) :param UNKNOWN_BASE_TYPE unknown_base_type: :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: None If the method is called asynchronously, returns the request thread.
625941b9925a0f43d2549ce3
def ebi_taxid_to_lineage(tax_id): <NEW_LINE> <INDENT> url = 'http://www.ebi.ac.uk/ena/data/taxonomy/v1/taxon/tax-id/{}' <NEW_LINE> if tax_id == 0 or tax_id == 1: <NEW_LINE> <INDENT> return None, None <NEW_LINE> <DEDENT> response = requests.get(url.format(tax_id), timeout=5) <NEW_LINE> result = json.loads(response.text) <NEW_LINE> sciname = result['scientificName'] <NEW_LINE> taxonomy = [x for x in result['lineage'].split('; ') if x] <NEW_LINE> return sciname, taxonomy
Returns scientific name and lineage for a given taxid using EBI's taxonomy API e.g.('Retroviridae', ['Viruses', 'Retro-transcribing viruses'])
625941b921bff66bcd6847c4
def embedding_lookup(input_ids, vocab_size, precision, embedding_size=128, initializer_range=0.02, word_embedding_name="word_embeddings", use_one_hot_embeddings=False): <NEW_LINE> <INDENT> if input_ids.shape.ndims == 2: <NEW_LINE> <INDENT> input_ids = tf.expand_dims(input_ids, axis=[-1]) <NEW_LINE> <DEDENT> embedding_table = tf.compat.v1.get_variable( name=word_embedding_name, shape=[vocab_size, embedding_size], initializer=create_initializer(initializer_range), dtype=precision) <NEW_LINE> flat_input_ids = tf.reshape(input_ids, [-1]) <NEW_LINE> if use_one_hot_embeddings: <NEW_LINE> <INDENT> one_hot_input_ids = tf.one_hot(flat_input_ids, depth=vocab_size, dtype=precision) <NEW_LINE> output = tf.matmul(one_hot_input_ids, embedding_table) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> output = tf.gather(embedding_table, flat_input_ids) <NEW_LINE> <DEDENT> input_shape = get_shape_list(input_ids) <NEW_LINE> output = tf.reshape(output, input_shape[0:-1] + [input_shape[-1] * embedding_size]) <NEW_LINE> return (output, embedding_table)
Looks up words embeddings for id tensor. Args: input_ids: int32 Tensor of shape [batch_size, seq_length] containing word ids. vocab_size: int. Size of the embedding vocabulary. embedding_size: int. Width of the word embeddings. initializer_range: float. Embedding initialization range. word_embedding_name: string. Name of the embedding table. use_one_hot_embeddings: bool. If True, use one-hot method for word embeddings. If False, use `tf.gather()`. Returns: float Tensor of shape [batch_size, seq_length, embedding_size].
625941b976d4e153a657e99f
def checkoutput(*args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> out = su.check_output(*args, **kwargs) <NEW_LINE> out = out.decode('utf-8') <NEW_LINE> <DEDENT> except su.CalledProcessError: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> return out
Just a wrapper to return utf-8 from check_output
625941b9d486a94d0b98dfbc
def preprocess(page): <NEW_LINE> <INDENT> pattern = "([a-zA-Z]+(?:'[a-z]+)?)" <NEW_LINE> tokens_raw = nltk.regexp_tokenize(page, pattern) <NEW_LINE> tokens = [word.lower() for word in tokens_raw] <NEW_LINE> stopwords_list = stopwords.words('english') <NEW_LINE> stopwords_list += list(string.punctuation) <NEW_LINE> stopwords_list += ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] <NEW_LINE> return [word for word in tokens if word not in stopwords_list and len(word) > 3]
Preprocess a document or page Tokenize, remove all stopwords from the document, and lemmatize each word.
625941b9498bea3a759b9920
def get_download_ids(keyword, field, size=10000): <NEW_LINE> <INDENT> n_iter = DOWNLOAD_QUERY_SIZE // size <NEW_LINE> results = get_total_results(keyword) <NEW_LINE> if results is None: <NEW_LINE> <INDENT> logger.error("Error retrieving total results. Max number of attempts reached") <NEW_LINE> return <NEW_LINE> <DEDENT> total = sum(results[category]["doc_count"] for category in INDEX_ALIASES_TO_AWARD_TYPES.keys()) <NEW_LINE> required_iter = (total // size) + 1 <NEW_LINE> n_iter = min(max(1, required_iter), n_iter) <NEW_LINE> for i in range(n_iter): <NEW_LINE> <INDENT> filter_query = QueryWithFilters.generate_transactions_elasticsearch_query( {"keyword_search": [es_minimal_sanitize(keyword)]} ) <NEW_LINE> search = TransactionSearch().filter(filter_query) <NEW_LINE> group_by_agg_key_values = { "field": field, "include": {"partition": i, "num_partitions": n_iter}, "size": size, "shard_size": size, } <NEW_LINE> aggs = A("terms", **group_by_agg_key_values) <NEW_LINE> search.aggs.bucket("results", aggs) <NEW_LINE> response = search.handle_execute() <NEW_LINE> if response is None: <NEW_LINE> <INDENT> raise Exception("Breaking generator, unable to reach cluster") <NEW_LINE> <DEDENT> results = [] <NEW_LINE> for result in response["aggregations"]["results"]["buckets"]: <NEW_LINE> <INDENT> results.append(result["key"]) <NEW_LINE> <DEDENT> yield results
returns a generator that yields list of transaction ids in chunksize SIZE Note: this only works for fields in ES of integer type.
625941b99b70327d1c4e0c43
@APP.route('/') <NEW_LINE> def peyl_page(): <NEW_LINE> <INDENT> return render_template('main.html')
Provides the main.html template
625941b9507cdc57c6306b43
def getExistingUserInfo(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> entry = self._users.next() <NEW_LINE> uid = entry.pw_uid <NEW_LINE> if uid not in self._uids: <NEW_LINE> <INDENT> self._uids.add(uid) <NEW_LINE> return entry
Read and return the next record from C{self._users}, filtering out any records with previously seen uid values (as these cannot be found with C{getpwuid} and only cause trouble).
625941b90383005118ecf454
def __init__(self, **args): <NEW_LINE> <INDENT> ReinforcementAgent.__init__(self, **args) <NEW_LINE> self.q_values = defaultdict(util.Counter)
You can initialize Q-values here...
625941b971ff763f4b5494fe
def legendre_old(nu, mu, x): <NEW_LINE> <INDENT> if mu < 0 or mu > nu: <NEW_LINE> <INDENT> raise ValueError('require 0 <= mu <= nu, but mu=%d and nu=%d' % (nu, mu)) <NEW_LINE> <DEDENT> if mu == 0: <NEW_LINE> <INDENT> p_nu = 1.0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s = 1 <NEW_LINE> if mu & 1: <NEW_LINE> <INDENT> s = -1 <NEW_LINE> <DEDENT> z = sqrt(1 - x ** 2) <NEW_LINE> p_nu = s * odd_factorial(2 * mu - 1) * z ** mu <NEW_LINE> <DEDENT> if mu == nu: <NEW_LINE> <INDENT> return p_nu <NEW_LINE> <DEDENT> p_nu_prev = p_nu <NEW_LINE> p_nu = x * (2 * mu + 1) * p_nu <NEW_LINE> if nu == mu + 1: <NEW_LINE> <INDENT> return p_nu <NEW_LINE> <DEDENT> for n in range(mu + 2, nu + 1): <NEW_LINE> <INDENT> result = (x * (2 * n - 1) * p_nu - (n + mu - 1) * p_nu_prev) / (n - mu) <NEW_LINE> p_nu_prev = p_nu <NEW_LINE> p_nu = result <NEW_LINE> <DEDENT> return result
Compute the associated Legendre polynomial with degree nu and order mu. This function uses the recursion formula in the degree nu. (Abramowitz & Stegun, Section 8.5.)
625941b9f548e778e58cd3eb
def get_problems(self, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.__get_problems_with_http_info(**kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.__get_problems_with_http_info(**kwargs) <NEW_LINE> return data
get_problems # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_problems(async_req=True) >>> result = thread.get() :param async_req: bool :param str locator: :param str fields: :return: ProblemOccurrences If the method is called asynchronously, returns the request thread.
625941b9442bda511e8be295
def extract_name_from_unimarc(self, unimarc): <NEW_LINE> <INDENT> data = dict() <NEW_LINE> sort_name_in_progress = [] <NEW_LINE> for (code, key) in ( ('a', 'family'), ('b', 'given'), ('c', 'extra'), ): <NEW_LINE> <INDENT> value = self._xpath1(unimarc, 'ns2:subfield[@code="%s"]' % code) <NEW_LINE> if value is not None and value.text: <NEW_LINE> <INDENT> value = value.text <NEW_LINE> value = self.remove_commas_from(value) <NEW_LINE> sort_name_in_progress.append(value) <NEW_LINE> data[key] = value <NEW_LINE> <DEDENT> <DEDENT> return (data.get('given', None), data.get('family', None), data.get('extra', None), ", ".join(sort_name_in_progress))
Turn a UNIMARC tag into a 4-tuple: (given name, family name, extra, sort name)
625941b921bff66bcd6847c5
def build(self, data_sources): <NEW_LINE> <INDENT> for data_source in data_sources: <NEW_LINE> <INDENT> with data_source as stream: <NEW_LINE> <INDENT> for source, target in stream: <NEW_LINE> <INDENT> self._add_line(source, is_source=True) <NEW_LINE> self._add_line(target, is_source=False) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if _cosine_similarity(*self._alphabets) > self._similarity_threshold: <NEW_LINE> <INDENT> source_bpe = _BPE.learn_from_terms(self._dictionaries[0] + self._dictionaries[1], symbols=self._symbols, min_frequency=self._min_frequency, separator=self._separator) <NEW_LINE> target_bpe = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> source_bpe = _BPE.learn_from_terms(self._dictionaries[0], symbols=self._symbols, min_frequency=self._min_frequency, separator=self._separator) <NEW_LINE> target_bpe = _BPE.learn_from_terms(self._dictionaries[1], symbols=self._symbols, min_frequency=self._min_frequency, separator=self._separator) <NEW_LINE> <DEDENT> source_terms, target_terms = self._collect_terms( data_sources, source_bpe, target_bpe if target_bpe is not None else source_bpe ) <NEW_LINE> for counter in self._alphabets + self._dictionaries: <NEW_LINE> <INDENT> counter.clear() <NEW_LINE> <DEDENT> source_codes = source_bpe.bpe_codes <NEW_LINE> target_codes = target_bpe.bpe_codes if target_bpe is not None else None <NEW_LINE> return SubwordTextProcessor(source_codes, source_terms, target_codes, target_terms, self._separator)
It builds a new processor from a collection of data sources. A data source object must support __enter__ and __exit__ method to open and close the data stream. The data source object myst also be iterable returning a pair of strings: source and target. :param data_sources: a collection of data source objects :return: and instance of Dictionary
625941b956ac1b37e626404f
def __eq__(self, other: Any) -> bool: <NEW_LINE> <INDENT> return isinstance(other, Bell) and other.index == self.index
Determines if two Bells are equal.
625941b9b5575c28eb68de6d
def _argmin(a, positions, shape, dtype): <NEW_LINE> <INDENT> result = numpy.empty((1,), dtype=dtype) <NEW_LINE> pos_nd = numpy.unravel_index(positions[numpy.argmin(a)], shape) <NEW_LINE> for i, pos_nd_i in enumerate(pos_nd): <NEW_LINE> <INDENT> result["pos"][0, i] = pos_nd_i <NEW_LINE> <DEDENT> return result[0]
Find original array position corresponding to the minimum.
625941b963d6d428bbe4435f
@pytest.mark.tier(2) <NEW_LINE> @pytest.mark.meta(blockers=[1200783, 1207209]) <NEW_LINE> def test_iso_provision_from_template(provider, vm_name, smtp_test, datastore_init, request, setup_provider): <NEW_LINE> <INDENT> iso_template, host, datastore, iso_file, iso_kickstart, iso_root_password, iso_image_type, vlan = map(provider.data['provisioning'].get, ('pxe_template', 'host', 'datastore', 'iso_file', 'iso_kickstart', 'iso_root_password', 'iso_image_type', 'vlan')) <NEW_LINE> request.addfinalizer(lambda: cleanup_vm(vm_name, provider)) <NEW_LINE> provisioning_data = { 'vm_name': vm_name, 'host_name': {'name': [host]}, 'datastore_name': {'name': [datastore]}, 'provision_type': 'ISO', 'iso_file': {'name': [iso_file]}, 'custom_template': {'name': [iso_kickstart]}, 'root_password': iso_root_password, 'vlan': vlan, } <NEW_LINE> do_vm_provisioning(iso_template, provider, vm_name, provisioning_data, request, smtp_test, num_sec=1500)
Tests ISO provisioning Metadata: test_flag: iso, provision suite: infra_provisioning
625941b930c21e258bdfa30d
def eigvals_3x3(X: np.ndarray) -> np.ndarray: <NEW_LINE> <INDENT> x00, x01, x02, x10, x11, x12, x20, x21, x22 = X.ravel() <NEW_LINE> b = x00 + x11 + x22 <NEW_LINE> c = x00 * x11 + x00 * x22 - x01 * x10 - x02 * x20 + x11 * x22 - x12 * x21 <NEW_LINE> d = ( -x00 * x11 * x22 + x00 * x12 * x21 + x01 * x10 * x22 - x01 * x12 * x20 - x02 * x10 * x21 + x02 * x11 * x20 ) <NEW_LINE> p = b ** 2 - 3.0 * c <NEW_LINE> if p == 0.0: <NEW_LINE> <INDENT> return (b / 3.0) * np.ones(3) <NEW_LINE> <DEDENT> q = 2.0 * b ** 3 - 9.0 * b * c - 27.0 * d <NEW_LINE> if q ** 2 > 4.0 * p ** 3: <NEW_LINE> <INDENT> raise ValueError('This symbolic expression works only for real eigenvalues') <NEW_LINE> <DEDENT> delta = trunc_arccos(q / (2.0 * trunc_sqrt(p ** 3))) <NEW_LINE> tmp = 2.0 * trunc_sqrt(p) <NEW_LINE> return np.array( [ (b + tmp * np.cos(delta / 3.0)) / 3.0, (b + tmp * np.cos((delta + 2.0 * np.pi) / 3.0)) / 3.0, (b + tmp * np.cos((delta - 2.0 * np.pi) / 3.0)) / 3.0, ] )
Eigenvalues of 3-dimensional real square matrix Args: X: 3-dimensional square matrix Returns: Eigenvalues of `X` Notes: This symbolic expression doesn't work for complex eigenvalues References: M.J. Kronenbur. A Method for Fast Diagonalization ofa 2x2 or 3x3 Real Symmetric Matrix
625941b9e64d504609d746b0
def test_login_correct_set_to_True(self): <NEW_LINE> <INDENT> tester = app.test_client(self) <NEW_LINE> response = tester.post('/login', data=dict(username="user1"), follow_redirects=True) <NEW_LINE> self.assertEqual(app_info["logged"], True) <NEW_LINE> print("test_login_correct_set_to_True route -- PASS")
Test LOGIN set to True
625941b9d58c6744b4257ad0
def __find_framing_lines(self, orth_lines, frame): <NEW_LINE> <INDENT> min_horz, max_horz = None, None <NEW_LINE> min_vert, max_vert = None, None <NEW_LINE> for rho, theta in orth_lines[0]: <NEW_LINE> <INDENT> if (min_vert is None or abs(rho) < abs(min_vert[0])): <NEW_LINE> <INDENT> min_vert = (rho, theta) <NEW_LINE> <DEDENT> elif (rho == min_vert[0] and abs(theta) > abs(min_vert[1])): <NEW_LINE> <INDENT> min_vert = (rho, theta) <NEW_LINE> <DEDENT> if (max_vert is None or abs(rho) > abs(max_vert[0])): <NEW_LINE> <INDENT> max_vert = (rho, theta) <NEW_LINE> <DEDENT> elif (rho == max_vert[0] and abs(theta) > abs(max_vert[1])): <NEW_LINE> <INDENT> max_vert = (rho, theta) <NEW_LINE> <DEDENT> <DEDENT> for rho, theta in orth_lines[1]: <NEW_LINE> <INDENT> if (min_horz is None or abs(rho) < abs(min_horz[0])): <NEW_LINE> <INDENT> min_horz = (rho, theta) <NEW_LINE> <DEDENT> elif (rho == min_horz[0] and abs(theta) < abs(min_horz[1])): <NEW_LINE> <INDENT> min_horz = (rho, theta) <NEW_LINE> <DEDENT> if (max_horz is None or abs(rho) > abs(max_horz[0])): <NEW_LINE> <INDENT> max_horz = (rho, theta) <NEW_LINE> <DEDENT> elif (rho == max_horz[0] and abs(theta) < abs(max_horz[1])): <NEW_LINE> <INDENT> max_horz = (rho, theta) <NEW_LINE> <DEDENT> <DEDENT> if ( min_horz is None or max_horz is None or min_vert is None or max_vert is None ): <NEW_LINE> <INDENT> raise MTGException('Unable to calculate framing lines') <NEW_LINE> <DEDENT> def dfunc(frame, min_vert, min_horz, drawline): <NEW_LINE> <INDENT> drawline(frame, min_horz[0], min_horz[1], (0, 255, 0)) <NEW_LINE> drawline(frame, max_horz[0], max_horz[1], (0, 255, 0)) <NEW_LINE> drawline(frame, min_vert[0], min_vert[1], (0, 0, 255)) <NEW_LINE> drawline(frame, max_vert[0], max_vert[1], (0, 0, 255)) <NEW_LINE> return frame <NEW_LINE> <DEDENT> self.debugger.addFrame( 'Framing', frame.copy(), dfunc, min_vert, min_horz, self.__draw_line ) <NEW_LINE> return (min_horz, max_horz, min_vert, max_vert)
Find the framing lines, which are the min/max horizontal and vertical lines
625941b9ad47b63b2c509df9
def acls(self): <NEW_LINE> <INDENT> return { 1: [ {'rule': { 'dl_type': IPV4_ETH, 'ip_proto': 1, 'actions': { 'allow': 0, 'output': [ {'tunnel': { 'type': 'vlan', 'tunnel_id': 200, 'dp': self.topo.switches_by_id[0], 'port': self.host_port_maps[1][0][0]}} ] } }} ] }
Return ACL config
625941b997e22403b379ce09
def verify_import_function_called_when_import_button_clicked_test(self): <NEW_LINE> <INDENT> with patch('PyQt5.QtWidgets.QDialog.exec'): <NEW_LINE> <INDENT> self.form.on_import_as_new_button_clicked = MagicMock() <NEW_LINE> self.form.exec() <NEW_LINE> self.form.service_type_combo_box.setCurrentIndex(1) <NEW_LINE> self.form.plan_selection_combo_box.setCurrentIndex(3) <NEW_LINE> QtTest.QTest.mouseClick(self.form.import_as_new_button, QtCore.Qt.LeftButton) <NEW_LINE> <DEDENT> self.form.on_import_as_new_button_clicked.assert_called_with(False)
Test that the "on_import_as_new_button_clicked" function is executed when the "Import New" button is clicked
625941b97047854f462a127d
def retrieve_potential_adtrust_agents(api): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> dl_enabled_masters = api.Command.server_find( ipamindomainlevel=MIN_DOMAIN_LEVEL, all=True)['result'] <NEW_LINE> <DEDENT> except (errors.DatabaseError, errors.NetworkError) as e: <NEW_LINE> <INDENT> logger.error( "Could not retrieve a list of existing IPA masters: %s", e) <NEW_LINE> return None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> adtrust_agents = api.Command.server_find( servrole=u'AD trust agent', all=True)['result'] <NEW_LINE> <DEDENT> except (errors.DatabaseError, errors.NetworkError) as e: <NEW_LINE> <INDENT> logger.error("Could not retrieve a list of adtrust agents: %s", e) <NEW_LINE> return None <NEW_LINE> <DEDENT> dl_enabled_master_cns = {m['cn'][0] for m in dl_enabled_masters} <NEW_LINE> adtrust_agents_cns = {m['cn'][0] for m in adtrust_agents} <NEW_LINE> potential_agents_cns = dl_enabled_master_cns - adtrust_agents_cns <NEW_LINE> potential_agents_cns -= {api.env.host} <NEW_LINE> return sorted(potential_agents_cns)
Retrieve a sorted list of potential AD trust agents :param api: initialized API instance :returns: sorted list of FQDNs of masters which are not AD trust agents
625941b994891a1f4081b918
def format_func(args): <NEW_LINE> <INDENT> if args.all and args.branch is not None: <NEW_LINE> <INDENT> print("Only specify branch or all, but not both!") <NEW_LINE> return False <NEW_LINE> <DEDENT> if not args.branch: <NEW_LINE> <INDENT> if args.all: <NEW_LINE> <INDENT> files = get_files_to_check_working_tree() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> files = get_files_to_check() <NEW_LINE> <DEDENT> _format_files(args.clang_format, files) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _reformat_branch(args.clang_format, *args.branch)
Format files command entry point
625941b9187af65679ca4f8d
def photometry(self): <NEW_LINE> <INDENT> self.SNR = [] <NEW_LINE> self.phot_err = [] <NEW_LINE> self.phot_c = [] <NEW_LINE> self.phot = [] <NEW_LINE> self.lam_eff = [] <NEW_LINE> self.lam_c = [] <NEW_LINE> self.lam_err = [] <NEW_LINE> self.tag = [] <NEW_LINE> self.eazytag = [] <NEW_LINE> self.det = [] <NEW_LINE> for Filter in self.filters: <NEW_LINE> <INDENT> lam = self.filters[Filter]["lam"] <NEW_LINE> trans = self.filters[Filter]["trans"] <NEW_LINE> Fnu = self.iFnu(lam) <NEW_LINE> Flam = self.iFlam(lam) <NEW_LINE> phot_lam = np.trapz(Flam*trans,lam)/np.trapz(trans,lam) <NEW_LINE> lam_pivot = np.sqrt(np.trapz(trans,lam)/np.trapz(trans/lam**2,lam)) <NEW_LINE> phot_c = 1e17*(lam_pivot**2)*phot_lam/c <NEW_LINE> self.phot_c.append(phot_c) <NEW_LINE> sigma_flux = self.filters[Filter]["flux_err"] <NEW_LINE> phot = np.random.normal(loc=phot_c,scale=sigma_flux) <NEW_LINE> if phot<0: <NEW_LINE> <INDENT> phot=0. <NEW_LINE> <DEDENT> SNR = phot/sigma_flux <NEW_LINE> self.SNR.append(SNR) <NEW_LINE> if SNR>3.: <NEW_LINE> <INDENT> self.det.append("det") <NEW_LINE> self.phot_err.append(sigma_flux) <NEW_LINE> self.phot.append(phot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.det.append("up_lim") <NEW_LINE> phot = (3./2.)*sigma_flux <NEW_LINE> phot_err = (3./2.)*sigma_flux <NEW_LINE> self.phot.append(phot) <NEW_LINE> self.phot_err.append(phot_err) <NEW_LINE> <DEDENT> self.lam_eff.append(lam_pivot) <NEW_LINE> self.lam_c.append(self.filters[Filter]["lam_c"]) <NEW_LINE> self.lam_err.append(self.filters[Filter]["delt_lam"]/2.) <NEW_LINE> self.tag.append(Filter) <NEW_LINE> self.eazytag.append(self.filters[Filter]["eazy_tag"])
Photometry of the SED using the filters available, gives the flux in fnu
625941b9046cf37aa974cbba
def commit(self): <NEW_LINE> <INDENT> self.db_connection.commit()
Commit changes from any insert or update statements.
625941b966673b3332b91f07
def validate(self): <NEW_LINE> <INDENT> method_names = sorted([i for i in dir(self) if i.startswith("_validate") and callable(getattr(self, i))]) <NEW_LINE> for method_name in method_names: <NEW_LINE> <INDENT> method = getattr(self, method_name) <NEW_LINE> method()
Validate attributes by running all self._validate_*() methods. :raises TypeError: if an attribute has invalid type :raises ValueError: if an attribute contains invalid value
625941b930dc7b76659017da
def test_use_short_margin(self): <NEW_LINE> <INDENT> coco_ast = self.get_coco_ast("Semantic { " "forbid ruleset{contains_all([ " "property{name=='margin-right'}," "property{name=='margin-left'}," "property{name=='margin-top'}," "property{name=='margin-bottom'}" "])} message '' }") <NEW_LINE> css_tree = helpers.ParseHelper.parse_css_string('a{margin-left:0;margin-top:0;margin-bottom:0;margin-right:0}' 'b{margin-top:0;margin-bottom:0;margin-right:0}') <NEW_LINE> _, violation_log = violations.ViolationsFinder.find(coco_ast, css_tree) <NEW_LINE> assert violation_log.number_of_violations() == 1
Use the shorthand margin property instead
625941b9d10714528d5ffb4f
def cal_single_label_accuracy(logits, labels, name=""): <NEW_LINE> <INDENT> pre = tf.argmax(logits, 1, name="predict_{}".format(name)) <NEW_LINE> real = labels <NEW_LINE> correct_prediction = tf.equal(tf.cast(pre, tf.int32), tf.cast(real, tf.int32)) <NEW_LINE> accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name='single_label_accuracy_{}'.format(name)) <NEW_LINE> return accuracy
:param logits: :param labels: :param name: :return:
625941b9de87d2750b85fbfe
def _decorator(func): <NEW_LINE> <INDENT> def _wrapper(*args, **kwargs): <NEW_LINE> <INDENT> logline = '{0} {1}'.format(args, kwargs) <NEW_LINE> try: <NEW_LINE> <INDENT> log.debug(logline.decode('utf-8', 'replace')) <NEW_LINE> <DEDENT> except Exception as exception: <NEW_LINE> <INDENT> log.info( 'Exception occured while logging signature of calling' 'method in http client') <NEW_LINE> log.exception(exception) <NEW_LINE> <DEDENT> response = None <NEW_LINE> elapsed = None <NEW_LINE> try: <NEW_LINE> <INDENT> start = time() <NEW_LINE> response = func(*args, **kwargs) <NEW_LINE> elapsed = time() - start <NEW_LINE> <DEDENT> except Exception as exception: <NEW_LINE> <INDENT> log.critical('Call to Requests failed due to exception') <NEW_LINE> log.exception(exception) <NEW_LINE> raise exception <NEW_LINE> <DEDENT> request_body = '' <NEW_LINE> if 'body' in dir(response.request): <NEW_LINE> <INDENT> request_body = response.request.body <NEW_LINE> <DEDENT> elif 'data' in dir(response.request): <NEW_LINE> <INDENT> request_body = response.request.data <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log.info( "Unable to log request body, neither a 'data' nor a " "'body' object could be found") <NEW_LINE> <DEDENT> request_params = '' <NEW_LINE> request_url = response.request.url <NEW_LINE> if 'params' in dir(response.request): <NEW_LINE> <INDENT> request_params = response.request.params <NEW_LINE> <DEDENT> elif '?' in request_url: <NEW_LINE> <INDENT> request_url, request_params = request_url.split('?') <NEW_LINE> <DEDENT> logline = ''.join([ '\n{0}\nREQUEST SENT\n{0}\n'.format('-' * 12), 'request method..: {0}\n'.format(response.request.method), 'request url.....: {0}\n'.format(request_url), 'request params..: {0}\n'.format(request_params), 'request headers.: {0}\n'.format(response.request.headers), 'request body....: {0}\n'.format(request_body)]) <NEW_LINE> try: <NEW_LINE> <INDENT> log.log(level, logline.decode('utf-8', 'replace')) <NEW_LINE> <DEDENT> except Exception as exception: <NEW_LINE> <INDENT> log.log(level, '\n{0}\nREQUEST INFO\n{0}\n'.format('-' * 12)) <NEW_LINE> log.exception(exception) <NEW_LINE> <DEDENT> logline = ''.join([ '\n{0}\nRESPONSE RECEIVED\n{0}\n'.format('-' * 17), 'response status..: {0}\n'.format(response), 'response time....: {0}\n'.format(elapsed), 'response headers.: {0}\n'.format(response.headers), 'response body....: {0}\n'.format(response.content), '-' * 79]) <NEW_LINE> try: <NEW_LINE> <INDENT> log.log(level, logline.decode('utf-8', 'replace')) <NEW_LINE> <DEDENT> except Exception as exception: <NEW_LINE> <INDENT> log.log(level, '\n{0}\nRESPONSE INFO\n{0}\n'.format('-' * 13)) <NEW_LINE> log.exception(exception) <NEW_LINE> <DEDENT> return response <NEW_LINE> <DEDENT> return _wrapper
Accepts a function and returns wrapped version of that function.
625941b932920d7e50b2803c
def save_embedding(embedding, filename, embeddings_path): <NEW_LINE> <INDENT> path = os.path.join(embeddings_path, str(filename)) <NEW_LINE> try: <NEW_LINE> <INDENT> np.save(path, embedding) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print(str(e))
Saves the embedding numpy file to the 'embeddings' folder. Args: embedding: numpy array of 128 values after the image is fed to the FaceNet model. filename: filename of the image file. embeddings_path: absolute path of the 'embeddings/' folder.
625941b9cc40096d615957c3
def append(self, content): <NEW_LINE> <INDENT> self.content.append(content)
add another string to the content
625941b9dd821e528d63b01b
def is_done(self): <NEW_LINE> <INDENT> return self.__is_expired() or self.__has_all_results()
Checks all things to see if it is done :return: true if expired, or has all results
625941b96fb2d068a760ef11
def framesync_fpath(self, session_id): <NEW_LINE> <INDENT> framesync_fname = "{subject_id}_{session_id}.framesync".format( subject_id=self.subject_id, session_id=session_id) <NEW_LINE> return join(self.raw_gaze_dpath, framesync_fname)
Returns the file path the framesync file.
625941b9507cdc57c6306b44
def calc_distance(tf_idf_ret): <NEW_LINE> <INDENT> result = defaultdict(dict) <NEW_LINE> for fromCategory, fromTokens in tf_idf_ret.items(): <NEW_LINE> <INDENT> for toCategory, toTokens in tf_idf_ret.items(): <NEW_LINE> <INDENT> if fromCategory == toCategory: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for f in fromTokens.term_scores: <NEW_LINE> <INDENT> if f not in toTokens.term_scores: <NEW_LINE> <INDENT> toTokens.set_score(f, 0) <NEW_LINE> <DEDENT> <DEDENT> for t in toTokens.term_scores: <NEW_LINE> <INDENT> if t not in fromTokens.term_scores: <NEW_LINE> <INDENT> fromTokens.set_score(t, 0) <NEW_LINE> <DEDENT> <DEDENT> v1 = [score for (term, score) in sorted(fromTokens.term_scores.items())] <NEW_LINE> v2 = [score for (term, score) in sorted(toTokens.term_scores.items())] <NEW_LINE> result[fromCategory][toCategory] = nltk.cluster.util.cosine_distance(v1, v2) <NEW_LINE> <DEDENT> <DEDENT> return result
tf_idf のスコアを元に距離を取得します。 ret[str] = float
625941b9d8ef3951e32433ad
def __init__(self, message="Sorry, Conflict prevents operation"): <NEW_LINE> <INDENT> ErrorPage.__init__(self, CONFLICT, "Conflict", message)
Construct an object that will return an HTTP 409 Conflict message.
625941b9be383301e01b52fd
def getAction(self, gameState): <NEW_LINE> <INDENT> def maxValue(gameState, alpha, beta, depth): <NEW_LINE> <INDENT> v = -9999999.9 <NEW_LINE> for action in gameState.getLegalActions(0): <NEW_LINE> <INDENT> successor = gameState.generateSuccessor(0, action) <NEW_LINE> v = max(v, value(successor, alpha, beta, 1, depth)) <NEW_LINE> if v > beta: <NEW_LINE> <INDENT> return v <NEW_LINE> <DEDENT> alpha = max(alpha, v) <NEW_LINE> <DEDENT> return v <NEW_LINE> <DEDENT> def minValue(gameState, alpha, beta, agentIndex, depth): <NEW_LINE> <INDENT> v = 99999999.9 <NEW_LINE> for action in gameState.getLegalActions(agentIndex): <NEW_LINE> <INDENT> successor = gameState.generateSuccessor(agentIndex, action) <NEW_LINE> v = min(v, value(successor, alpha, beta, (agentIndex+1), depth)) <NEW_LINE> if v < alpha: <NEW_LINE> <INDENT> return v <NEW_LINE> <DEDENT> beta = min(beta, v) <NEW_LINE> <DEDENT> return v <NEW_LINE> <DEDENT> def value(state, alpha, beta, agentIndex, depth): <NEW_LINE> <INDENT> if agentIndex == state.getNumAgents(): <NEW_LINE> <INDENT> agentIndex = 0 <NEW_LINE> depth -= 1 <NEW_LINE> <DEDENT> if state.isWin() or state.isLose() or depth == 0: <NEW_LINE> <INDENT> return self.evaluationFunction(state) <NEW_LINE> <DEDENT> elif agentIndex == 0: <NEW_LINE> <INDENT> return maxValue(state, alpha, beta, depth) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return minValue(state, alpha, beta, agentIndex, depth) <NEW_LINE> <DEDENT> <DEDENT> bestAction = 'Stop' <NEW_LINE> maxScore = -10000000.0 <NEW_LINE> alpha = -9999999.9 <NEW_LINE> beta = 9999999.9 <NEW_LINE> for action in gameState.getLegalActions(0): <NEW_LINE> <INDENT> sucessor = gameState.generateSuccessor(0, action) <NEW_LINE> score = value(sucessor, alpha, beta, 1, self.depth) <NEW_LINE> if score > maxScore: <NEW_LINE> <INDENT> maxScore = score <NEW_LINE> bestAction = action <NEW_LINE> <DEDENT> if score > beta: <NEW_LINE> <INDENT> return bestAction <NEW_LINE> <DEDENT> alpha = max(alpha,score) <NEW_LINE> <DEDENT> return bestAction
Returns the minimax action using self.depth and self.evaluationFunction
625941b9b5575c28eb68de6e
def set_sensor_custom_altitude(self, altitude, aot=-1, water=-1, ozone=-1): <NEW_LINE> <INDENT> self.sensor_altitude = -1 * altitude <NEW_LINE> self.aot = aot <NEW_LINE> self.water = water <NEW_LINE> self.ozone = ozone
Set the altitude of the sensor, along with other variables required for the parameterisation of the sensor. Takes optional arguments of `aot`, `water` and `ozone` to specify atmospheric contents underneath the sensor. If these aren't specified then the water and ozone contents will be interpolated from the US-1962 standard atmosphere, and the AOT will be interpolated from a 2km exponential aerosol profile. Arguments: * `altitude` -- The altitude of the sensor, in km. * `aot` -- (Optional, keyword argument) The AOT at 550nm at the sensor * `water` -- (Optional, keyword argument) The water vapour content (in g/cm^2) at the sensor * `ozone` -- (Optional, keyword argument) The ozone content (in cm-atm) at the sensor Example usage:: s.altitudes.set_sensor_custom_altitude(8, 0.35, 1.6, 0.4) # Altitude of 8km, AOT of 0.35, Water content of 1.6g/cm^2 and Ozone of 0.4cm-atm
625941b907f4c71912b112f7
def try_include(self, filepath): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(filepath) as f: <NEW_LINE> <INDENT> self.scope[self.name] = self <NEW_LINE> exec(compile(f.read(), filepath, "exec"), self.scope) <NEW_LINE> <DEDENT> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> pass
Tries to include another file into current scope. Arguments: - filepath (`str`): path to file trying to be included
625941b945492302aab5e130
def balance(self): <NEW_LINE> <INDENT> while self.recNum > self.shpNum: <NEW_LINE> <INDENT> self.null() <NEW_LINE> <DEDENT> while self.recNum < self.shpNum: <NEW_LINE> <INDENT> self.record()
Adds corresponding empty attributes or null geometry records depending on which type of record was created to make sure all three files are in synch.
625941b9711fe17d825421e3