code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def shuffle(self) -> "Route": <NEW_LINE> <INDENT> points = list(range(len(self))) <NEW_LINE> random.shuffle(points) <NEW_LINE> new_route = self.__class__() <NEW_LINE> for p in points: <NEW_LINE> <INDENT> new_route.add(self[p]) <NEW_LINE> <DEDENT> return new_route | Shuffle a route.
This is done by creating a list of the indexes and shuffling that. rather
than manipulating Point's. when the order has been determined, a new Route
is created.
Returns:
Route - A shuffled route | 625941be7c178a314d6ef36c |
def _find_remove_targets(name=None, version=None, pkgs=None, **kwargs): <NEW_LINE> <INDENT> cur_pkgs = __salt__['pkg.list_pkgs'](versions_as_list=True, **kwargs) <NEW_LINE> if pkgs: <NEW_LINE> <INDENT> to_remove = _repack_pkgs(pkgs) <NEW_LINE> if not to_remove: <NEW_LINE> <INDENT> return {'name': name, 'changes': {}, 'result': False, 'comment': 'Invalidly formatted pkgs parameter. See ' 'minion log.'} <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> _normalize_name = __salt__.get('pkg.normalize_name', lambda pkgname: pkgname) <NEW_LINE> to_remove = {_normalize_name(name): version} <NEW_LINE> cver = cur_pkgs.get(name, []) <NEW_LINE> <DEDENT> version_spec = False <NEW_LINE> targets = [] <NEW_LINE> problems = [] <NEW_LINE> for pkgname, pkgver in six.iteritems(to_remove): <NEW_LINE> <INDENT> cver = cur_pkgs.get(pkgname, []) <NEW_LINE> if not cver: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> elif __salt__['pkg_resource.version_clean'](pkgver) is None: <NEW_LINE> <INDENT> targets.append(pkgname) <NEW_LINE> continue <NEW_LINE> <DEDENT> version_spec = True <NEW_LINE> match = re.match('^([<>])?(=)?([^<>=]+)$', pkgver) <NEW_LINE> if not match: <NEW_LINE> <INDENT> msg = 'Invalid version specification {0!r} for package ' '{1!r}.'.format(pkgver, pkgname) <NEW_LINE> problems.append(msg) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> gt_lt, eq, verstr = match.groups() <NEW_LINE> comparison = gt_lt or '' <NEW_LINE> comparison += eq or '' <NEW_LINE> if comparison in ['=', '']: <NEW_LINE> <INDENT> comparison = '==' <NEW_LINE> <DEDENT> if not _fulfills_version_spec(cver, comparison, verstr): <NEW_LINE> <INDENT> log.debug( 'Current version ({0}) did not match ({1}) specified ' '({2}), skipping remove {3}' .format(cver, comparison, verstr, pkgname) ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> targets.append(pkgname) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if problems: <NEW_LINE> <INDENT> return {'name': name, 'changes': {}, 'result': False, 'comment': ' '.join(problems)} <NEW_LINE> <DEDENT> if not targets: <NEW_LINE> <INDENT> msg = ( 'All specified packages{0} are already absent.' .format(' (matching specified versions)' if version_spec else '') ) <NEW_LINE> return {'name': name, 'changes': {}, 'result': True, 'comment': msg} <NEW_LINE> <DEDENT> return targets | Inspect the arguments to pkg.removed and discover what packages need to
be removed. Return a dict of packages to remove. | 625941be67a9b606de4a7dcd |
def _populate_user_quota_usage(user): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user.space_usage = seafile_api.get_user_self_usage(user.email) <NEW_LINE> user.space_quota = seafile_api.get_user_quota(user.email) <NEW_LINE> <DEDENT> except SearpcError as e: <NEW_LINE> <INDENT> logger.error(e) <NEW_LINE> user.space_usage = -1 <NEW_LINE> user.space_quota = -1 | Populate space/share quota to user.
Arguments:
- `user`: | 625941be50812a4eaa59c235 |
def getCard(self): <NEW_LINE> <INDENT> self.random_number = np.random.choice(self.number_list, 1, p=self.p_number)[0] <NEW_LINE> self.random_direction = np.random.choice(self.directions, 1)[0] <NEW_LINE> self.card = Card(self.side, self.random_direction, self.random_number) | Pick random number and direction, assign them to a variable and create a Card instance with those
variables as arguments. | 625941bef7d966606f6a9f12 |
def matrix_divided(matrix, div): <NEW_LINE> <INDENT> if div == 0: <NEW_LINE> <INDENT> raise ZeroDivisionError('division by zero') <NEW_LINE> <DEDENT> if type(div) is not int and type(div) is not float: <NEW_LINE> <INDENT> raise TypeError('div must be a number') <NEW_LINE> <DEDENT> new_matrix = [] <NEW_LINE> for i in range(len(matrix)): <NEW_LINE> <INDENT> if type(matrix) is not list: <NEW_LINE> <INDENT> raise TypeError('matrix must be a matrix' ' (list of lists) of integers/floats') <NEW_LINE> <DEDENT> for j in matrix[i]: <NEW_LINE> <INDENT> if type(j) is not int and type(j) is not float: <NEW_LINE> <INDENT> raise TypeError('matrix must be a matrix' ' (list of lists) of integers/floats') <NEW_LINE> <DEDENT> <DEDENT> if len(matrix[i]) != len(matrix[0]): <NEW_LINE> <INDENT> raise TypeError('Each row of the matrix must have the same size') <NEW_LINE> <DEDENT> new_matrix += [list(map(lambda x: round(x / div, 2), matrix[i]))] <NEW_LINE> <DEDENT> return (new_matrix) | Function divides all elements of a matrix(list of lists)
by second parameter passed (div)
Parameters:
matrix -- a list of lists to be divided
div -- number to divide matrix by
Return: new matrix containing the quotients of aforementioned division | 625941be21bff66bcd684866 |
def sign_ssh_data(self, data, algorithm=None): <NEW_LINE> <INDENT> return bytes() | Sign a blob of data with this private key, and return a `.Message`
representing an SSH signature message.
:param str data:
the data to sign.
:param str algorithm:
the signature algorithm to use, if different from the key's
internal name. Default: ``None``.
:return: an SSH signature `message <.Message>`.
.. versionchanged:: 2.9
Added the ``algorithm`` kwarg. | 625941be29b78933be1e55c2 |
def test_module_promotion_preserves_contents(self): <NEW_LINE> <INDENT> create_dummy_file('foo.py', 'print "Hello, world"') <NEW_LINE> sha1 = file_sha('foo.py') <NEW_LINE> self.assertFileTree(['foo.py']) <NEW_LINE> Module('foo').promote() <NEW_LINE> self.assertFileTree(['foo/__init__.py']) <NEW_LINE> sha2 = file_sha('foo/__init__.py') <NEW_LINE> assert sha1 == sha2 | Promotion preserves file content. | 625941bee8904600ed9f1e3b |
@main.route('/home/comment/<int:post_id>',methods = ['GET','POST']) <NEW_LINE> @login_required <NEW_LINE> def comment(post_id): <NEW_LINE> <INDENT> form = CommentForm() <NEW_LINE> post = Post.query.get_or_404(post_id) <NEW_LINE> if form.validate_on_submit(): <NEW_LINE> <INDENT> comment = form.comment.data <NEW_LINE> comment = Comment(comment = comment,user_id = current_user._get_current_object().id,post_id=post.id) <NEW_LINE> db.session.add(comment) <NEW_LINE> db.session.commit() <NEW_LINE> flash('Your comment has been posted!') <NEW_LINE> return redirect(url_for('.comment',post_id=post_id)) <NEW_LINE> <DEDENT> all_comments = Comment.query.order_by(Comment.date_posted.desc()).all() <NEW_LINE> return render_template("comments.html",form=form, comment = all_comments,post = post) | View root page function that returns the comments and its data | 625941be45492302aab5e1d2 |
def save_file(shares): <NEW_LINE> <INDENT> nome_file=input('\n\tNome del file da utilizzare per salvare i dati (senza estensione) : ') <NEW_LINE> xls_file=path+nome_file+'.xls' <NEW_LINE> csv_file=path+nome_file+'.csv' <NEW_LINE> txt_file=path+nome_file+'.txt' <NEW_LINE> print ('\n\tSalvo il DataFrame "Shares" delle azioni nel file Shares') <NEW_LINE> print ('\tI files vengono salvati nel folder: ', path) <NEW_LINE> if len(shares)<65536: <NEW_LINE> <INDENT> shares.to_excel(xls_file) <NEW_LINE> print('\tI dati sono stati salvati in formato xls nel file ', xls_file) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('\n\tIl file contiene ', len(shares), ' righe, è troppo grande per Excel. Verrà salvato solo come testo.') <NEW_LINE> <DEDENT> shares.to_csv(csv_file, sep=',', na_rep='', ) <NEW_LINE> print('\tI dati sono stati salvati in formato csv nel file ', csv_file) <NEW_LINE> with open(txt_file, "w") as my_output_file: <NEW_LINE> <INDENT> with open(csv_file, "r") as my_input_file: <NEW_LINE> <INDENT> [ my_output_file.write(" ".join(row)+'\n') for row in csv.reader(my_input_file)] <NEW_LINE> <DEDENT> <DEDENT> my_output_file.close() <NEW_LINE> print('\tI dati sono stati salvati in formato txt nel file ', txt_file) | Salva il DataFrame delle azioni nei formati Excel File, CSV, TXT.
Il DataFrame Shares dei titoli viene salvato come file XLS nella directory di lavoro definita nella variabile path | 625941be4a966d76dd550f1e |
def display_peek( self, dataset ): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return dataset.peek <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return "HMMER3 database (multiple files)" | Create HTML content, used for displaying peek. | 625941be1f5feb6acb0c4a65 |
def initialize_connection_fc(self, volume, connector): <NEW_LINE> <INDENT> initiators = [fczm_utils.get_formatted_wwn(wwpn) for wwpn in connector['wwpns']] <NEW_LINE> eseries_vol = self._get_volume(volume['name_id']) <NEW_LINE> mapping = self.map_volume_to_host(volume, eseries_vol, initiators) <NEW_LINE> lun_id = mapping['lun'] <NEW_LINE> initiator_info = self._build_initiator_target_map_fc(connector) <NEW_LINE> target_wwpns, initiator_target_map, num_paths = initiator_info <NEW_LINE> if target_wwpns: <NEW_LINE> <INDENT> msg = ("Successfully fetched target details for LUN %(id)s " "and initiator(s) %(initiators)s.") <NEW_LINE> msg_fmt = {'id': volume['id'], 'initiators': initiators} <NEW_LINE> LOG.debug(msg, msg_fmt) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> msg = _('Failed to get LUN target details for the LUN %s.') <NEW_LINE> raise exception.VolumeBackendAPIException(data=msg % volume['id']) <NEW_LINE> <DEDENT> target_info = {'driver_volume_type': 'fibre_channel', 'data': {'target_discovered': True, 'target_lun': int(lun_id), 'target_wwn': target_wwpns, 'access_mode': 'rw', 'initiator_target_map': initiator_target_map}} <NEW_LINE> return target_info | Initializes the connection and returns connection info.
Assigns the specified volume to a compute node/host so that it can be
used from that host.
The driver returns a driver_volume_type of 'fibre_channel'.
The target_wwn can be a single entry or a list of wwns that
correspond to the list of remote wwn(s) that will export the volume.
Example return values:
{
'driver_volume_type': 'fibre_channel'
'data': {
'target_discovered': True,
'target_lun': 1,
'target_wwn': '500a098280feeba5',
'access_mode': 'rw',
'initiator_target_map': {
'21000024ff406cc3': ['500a098280feeba5'],
'21000024ff406cc2': ['500a098280feeba5']
}
}
}
or
{
'driver_volume_type': 'fibre_channel'
'data': {
'target_discovered': True,
'target_lun': 1,
'target_wwn': ['500a098280feeba5', '500a098290feeba5',
'500a098190feeba5', '500a098180feeba5'],
'access_mode': 'rw',
'initiator_target_map': {
'21000024ff406cc3': ['500a098280feeba5',
'500a098290feeba5'],
'21000024ff406cc2': ['500a098190feeba5',
'500a098180feeba5']
}
}
} | 625941becad5886f8bd26eeb |
def do_render(self, gpsmap): <NEW_LINE> <INDENT> dummy_map = gpsmap | render the layer | 625941bea05bb46b383ec735 |
def get_updated_definition( func: Callable, traces: Iterable[CallTrace], max_typed_dict_size: int, rewriter: Optional[TypeRewriter] = None, existing_annotation_strategy: ExistingAnnotationStrategy = ExistingAnnotationStrategy.REPLICATE, ) -> FunctionDefinition: <NEW_LINE> <INDENT> if rewriter is None: <NEW_LINE> <INDENT> rewriter = NoOpRewriter() <NEW_LINE> <DEDENT> arg_types, return_type, yield_type = shrink_traced_types(traces, max_typed_dict_size) <NEW_LINE> arg_types = {name: rewriter.rewrite(typ) for name, typ in arg_types.items()} <NEW_LINE> if return_type is not None: <NEW_LINE> <INDENT> return_type = rewriter.rewrite(return_type) <NEW_LINE> <DEDENT> if yield_type is not None: <NEW_LINE> <INDENT> yield_type = rewriter.rewrite(yield_type) <NEW_LINE> <DEDENT> return FunctionDefinition.from_callable_and_traced_types(func, arg_types, return_type, yield_type, existing_annotation_strategy) | Update the definition for func using the types collected in traces. | 625941be9f2886367277a7a1 |
def on_stop(self, func): <NEW_LINE> <INDENT> self._on_stop_funcs.append(func) | Register a cleanup function to be executed when the server stops | 625941be63d6d428bbe44401 |
def _get_clone_spec(self, datastore, disk_move_type, snapshot, backing, disk_type, host=None, resource_pool=None, extra_config=None, disks_to_clone=None): <NEW_LINE> <INDENT> if disk_type is not None: <NEW_LINE> <INDENT> disk_device = self._get_disk_device(backing) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> disk_device = None <NEW_LINE> <DEDENT> relocate_spec = self._get_relocate_spec(datastore, resource_pool, host, disk_move_type, disk_type, disk_device) <NEW_LINE> cf = self._session.vim.client.factory <NEW_LINE> clone_spec = cf.create('ns0:VirtualMachineCloneSpec') <NEW_LINE> clone_spec.location = relocate_spec <NEW_LINE> clone_spec.powerOn = False <NEW_LINE> clone_spec.template = False <NEW_LINE> clone_spec.snapshot = snapshot <NEW_LINE> config_spec = cf.create('ns0:VirtualMachineConfigSpec') <NEW_LINE> config_spec.managedBy = self._create_managed_by_info() <NEW_LINE> clone_spec.config = config_spec <NEW_LINE> if extra_config: <NEW_LINE> <INDENT> if BACKING_UUID_KEY in extra_config: <NEW_LINE> <INDENT> config_spec.instanceUuid = extra_config.pop(BACKING_UUID_KEY) <NEW_LINE> <DEDENT> config_spec.extraConfig = self._get_extra_config_option_values( extra_config) <NEW_LINE> <DEDENT> if disks_to_clone: <NEW_LINE> <INDENT> config_spec.deviceChange = ( self._create_device_change_for_disk_removal( backing, disks_to_clone)) <NEW_LINE> <DEDENT> LOG.debug("Spec for cloning the backing: %s.", clone_spec) <NEW_LINE> return clone_spec | Get the clone spec.
:param datastore: Reference to datastore
:param disk_move_type: Disk move type
:param snapshot: Reference to snapshot
:param backing: Source backing VM
:param disk_type: Disk type of clone
:param host: Target host
:param resource_pool: Target resource pool
:param extra_config: Key-value pairs to be written to backing's
extra-config
:param disks_to_clone: UUIDs of disks to clone
:return: Clone spec | 625941bea219f33f3462887e |
def set_create_time(self, *args, **kwargs): <NEW_LINE> <INDENT> if kwargs.get("start", None) and kwargs.get("end", None): <NEW_LINE> <INDENT> if kwargs.get("range", None): <NEW_LINE> <INDENT> raise ApiError("cannot specify range= in addition to start= and end=") <NEW_LINE> <DEDENT> stime = kwargs["start"] <NEW_LINE> if not isinstance(stime, str): <NEW_LINE> <INDENT> stime = stime.isoformat() <NEW_LINE> <DEDENT> etime = kwargs["end"] <NEW_LINE> if not isinstance(etime, str): <NEW_LINE> <INDENT> etime = etime.isoformat() <NEW_LINE> <DEDENT> self._time_filter = {"start": stime, "end": etime} <NEW_LINE> <DEDENT> elif kwargs.get("range", None): <NEW_LINE> <INDENT> if kwargs.get("start", None) or kwargs.get("end", None): <NEW_LINE> <INDENT> raise ApiError("cannot specify start= or end= in addition to range=") <NEW_LINE> <DEDENT> self._time_filter = {"range": kwargs["range"]} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ApiError("must specify either start= and end= or range=") <NEW_LINE> <DEDENT> return self | Restricts the alerts that this query is performed on to the specified
creation time (either specified as a start and end point or as a
range).
:return: This instance | 625941be1d351010ab855a2e |
def submissions(): <NEW_LINE> <INDENT> custom = False <NEW_LINE> atable = db.auth_user <NEW_LINE> cftable = db.custom_friend <NEW_LINE> handle = None <NEW_LINE> duplicates = [] <NEW_LINE> row = None <NEW_LINE> if len(request.args) < 1: <NEW_LINE> <INDENT> if auth.is_logged_in(): <NEW_LINE> <INDENT> user_id = session.user_id <NEW_LINE> handle = session.handle <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> redirect(URL("default", "index")) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> handle = request.args[0] <NEW_LINE> row = utilities.get_user_records([handle], "stopstalk_handle", "stopstalk_handle", True) <NEW_LINE> if row is None: <NEW_LINE> <INDENT> query = (cftable.stopstalk_handle == handle) <NEW_LINE> row = db(query).select().first() <NEW_LINE> if row: <NEW_LINE> <INDENT> custom = True <NEW_LINE> user_id = row.id <NEW_LINE> if row.duplicate_cu: <NEW_LINE> <INDENT> duplicates = [(row.id, row.duplicate_cu)] <NEW_LINE> user_id = row.duplicate_cu.id <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise HTTP(404) <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> user_id = row.id <NEW_LINE> <DEDENT> <DEDENT> if request.vars.page: <NEW_LINE> <INDENT> page = request.vars.page <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> page = "1" <NEW_LINE> <DEDENT> if int(page) > current.USER_PAGINATION_LIMIT and not auth.is_logged_in(): <NEW_LINE> <INDENT> session.flash = T("Please enter a valid page") <NEW_LINE> redirect(URL("default", "index")) <NEW_LINE> return <NEW_LINE> <DEDENT> stable = db.submission <NEW_LINE> query = (stable.user_id == user_id) <NEW_LINE> if custom: <NEW_LINE> <INDENT> query = (stable.custom_user_id == user_id) <NEW_LINE> <DEDENT> PER_PAGE = current.PER_PAGE <NEW_LINE> if request.extension == "json": <NEW_LINE> <INDENT> total_submissions = db(query).count() <NEW_LINE> if not auth.is_logged_in() and total_submissions > current.USER_PAGINATION_LIMIT * PER_PAGE: <NEW_LINE> <INDENT> total_submissions = current.USER_PAGINATION_LIMIT * PER_PAGE <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> page_count = total_submissions / PER_PAGE <NEW_LINE> if total_submissions % PER_PAGE: <NEW_LINE> <INDENT> page_count += 1 <NEW_LINE> <DEDENT> return dict(page_count=page_count) <NEW_LINE> <DEDENT> offset = PER_PAGE * (int(page) - 1) <NEW_LINE> all_submissions = db(query).select(orderby=~stable.time_stamp, limitby=(offset, offset + PER_PAGE)) <NEW_LINE> table = utilities.render_table(all_submissions, duplicates, session.user_id) <NEW_LINE> if handle == session.handle: <NEW_LINE> <INDENT> user = "Self" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> user = row["first_name"] <NEW_LINE> <DEDENT> return dict(handle=handle, user=user, table=table, total_rows=len(all_submissions)) | Retrieve submissions of a specific user | 625941be82261d6c526ab3ad |
@pytest.mark.parametrize( "text, expected", [ ( "Let's have URL http://janlipovsky.cz and a second URL https://example.com/@eon01/asdsd-dummy it's over.", [ ("http://janlipovsky.cz", (15, 36)), ("https://example.com/@eon01/asdsd-dummy", (54, 92)), ], ), ( "Some text www.company.com", [ ("www.company.com", (10, 25)), ], ), ], ) <NEW_LINE> def test_find_urls_with_indices(urlextract, text, expected): <NEW_LINE> <INDENT> assert urlextract.find_urls(text, get_indices=True) == expected | Testing find_urls returning only unique URLs
:param fixture urlextract: fixture holding URLExtract object
:param str text: text in which we should find links
:param list(str) expected: list of URLs that has to be found in text | 625941be0383005118ecf4f6 |
def _valueToPos(self, value): <NEW_LINE> <INDENT> if self.vertical: <NEW_LINE> <INDENT> return scale(value, (self.min(), self.max()), (0, self.height() - self._splitter.handleWidth() * 2)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return scale(value, (self.min(), self.max()), (0, self.width() - self._splitter.handleWidth() * 2)) | converts slider value to local pixel x coord | 625941beff9c53063f47c106 |
def update_metric(self, eval_metric, labels): <NEW_LINE> <INDENT> raise NotImplementedError() | Evaluates and accumulates evaluation metric on outputs of the last forward
computation.
Parameters
----------
eval_metric : EvalMetric
Evaluation metric to use.
labels : list of NDArray
Typically `data_batch.label`.
Examples
--------
An example of updating evaluation metric::
>>> mod.forward(data_batch)
>>> mod.update_metric(metric, data_batch.label) | 625941be046cf37aa974cc5b |
def fit_transform(self, raw_documents, y=None): <NEW_LINE> <INDENT> if not self.fit_vocabulary: <NEW_LINE> <INDENT> return self.transform(raw_documents) <NEW_LINE> <DEDENT> term_counts_per_doc = [] <NEW_LINE> term_counts = Counter() <NEW_LINE> document_counts = Counter() <NEW_LINE> max_df = self.max_df <NEW_LINE> max_features = self.max_features <NEW_LINE> for doc in raw_documents: <NEW_LINE> <INDENT> term_count_current = Counter(self.analyzer.analyze(doc)) <NEW_LINE> term_counts.update(term_count_current) <NEW_LINE> if max_df < 1.0: <NEW_LINE> <INDENT> document_counts.update(term_count_current.iterkeys()) <NEW_LINE> <DEDENT> term_counts_per_doc.append(term_count_current) <NEW_LINE> <DEDENT> n_doc = len(term_counts_per_doc) <NEW_LINE> if max_df < 1.0: <NEW_LINE> <INDENT> max_document_count = max_df * n_doc <NEW_LINE> stop_words = set(t for t, dc in document_counts.iteritems() if dc > max_document_count) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> stop_words = set() <NEW_LINE> <DEDENT> if max_features is None: <NEW_LINE> <INDENT> terms = set(term_counts) - stop_words <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> terms = set() <NEW_LINE> for t, tc in term_counts.most_common(): <NEW_LINE> <INDENT> if t not in stop_words: <NEW_LINE> <INDENT> terms.add(t) <NEW_LINE> <DEDENT> if len(terms) >= max_features: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.vocabulary = dict(((t, i) for i, t in enumerate(terms))) <NEW_LINE> return self._term_count_dicts_to_matrix(term_counts_per_doc) | Learn the vocabulary dictionary and return the count vectors
This is more efficient than calling fit followed by transform.
Parameters
----------
raw_documents: iterable
an iterable which yields either str, unicode or file objects
Returns
-------
vectors: array, [n_samples, n_features] | 625941be099cdd3c635f0b6e |
def create_fake_import(module_name): <NEW_LINE> <INDENT> def fake_import(name, *args, **kwargs): <NEW_LINE> <INDENT> if name == module_name: <NEW_LINE> <INDENT> raise ImportError('mocked import Error for module %s' % name) <NEW_LINE> <DEDENT> return real_import(name, *args, **kwargs) <NEW_LINE> <DEDENT> return fake_import | Create a fake import function.
It raises ImportErorr for a given module name. | 625941be2ae34c7f2600d043 |
def tr(self, message): <NEW_LINE> <INDENT> return QCoreApplication.translate('AttributeTransfer', message) | Get the translation for a string using Qt translation API.
We implement this ourselves since we do not inherit QObject.
:param message: String for translation.
:type message: str, QString
:returns: Translated version of message.
:rtype: QString | 625941be009cb60464c632c5 |
def convertToIntArr(self): <NEW_LINE> <INDENT> return _MEDCoupling.DataArrayDouble_convertToIntArr(self) | convertToIntArr(self) -> DataArrayInt
1 | 625941be57b8e32f524833ab |
def draw_line(event): <NEW_LINE> <INDENT> end_point = find_closest_midpoint(event) <NEW_LINE> print ("end") <NEW_LINE> if end_point == start_point_list[0]: <NEW_LINE> <INDENT> raise ValueError("Start point and end point are equal.") <NEW_LINE> <DEDENT> end_point_list[0] = end_point <NEW_LINE> edges.append( tuple((start_point_list[0], end_point_list[0])) ) <NEW_LINE> node_painter.begin(img) <NEW_LINE> node_painter.setPen(line_drawer) <NEW_LINE> node_painter.drawLine(start_point_list[0], end_point) <NEW_LINE> node_painter.end() <NEW_LINE> calculate_edge_length(end_point_list) | uses the starting point and the second point - which is indicated by
another click - to draw a line between those points | 625941be596a8972360899d5 |
def object_hook(self, obj): <NEW_LINE> <INDENT> if "__type__" in obj: <NEW_LINE> <INDENT> if obj["__type__"] == "complex": <NEW_LINE> <INDENT> val = obj["__value__"] <NEW_LINE> return val[0] + 1j * val[1] <NEW_LINE> <DEDENT> if obj["__type__"] == "array": <NEW_LINE> <INDENT> return np.array(obj["__value__"]) <NEW_LINE> <DEDENT> <DEDENT> return obj | Object hook. | 625941be99cbb53fe6792af9 |
def printpos(s, start, end, fill = 0): <NEW_LINE> <INDENT> fs = 10 <NEW_LINE> return "%s %s%s %s" % (s[start - fs:start], s[start:end], '-' * fill, s[end:end + fs]) | For debugging purposes. | 625941bed4950a0f3b08c262 |
def exists(url): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> resp = requests.get(url.geturl()) <NEW_LINE> <DEDENT> except InvalidSchema as e: <NEW_LINE> <INDENT> raise URLError(e) <NEW_LINE> <DEDENT> return resp.status_code < 400 | Check the existence of a resource.
Args:
url: (urlparse.SplitResult) Resource locator
Returns:
(Bool): True if resource is accessible | 625941be3eb6a72ae02ec3e7 |
def zone_sm_reconfig_schedule(db_session, zone_sm, zone_sm_event=None, randomize=False, master_reconfig=False, **kwargs): <NEW_LINE> <INDENT> master_sm = get_master_sm(db_session) <NEW_LINE> coalesce_time = timedelta(seconds=3*float(settings['sleep_time'])) <NEW_LINE> delay_secs = 6*float(settings['sleep_time']) <NEW_LINE> if randomize: <NEW_LINE> <INDENT> delay_secs += 60*float(settings['master_hold_timeout']) * random() <NEW_LINE> <DEDENT> delay_time = timedelta(seconds=delay_secs) <NEW_LINE> sg_id = zone_sm.sg.id_ <NEW_LINE> if master_reconfig: <NEW_LINE> <INDENT> if (master_sm.state != MSTATE_HOLD or (master_sm.state == MSTATE_HOLD and master_sm.hold_sg == HOLD_SG_NONE)): <NEW_LINE> <INDENT> create_event(MasterSMMasterReconfig, db_session=db_session, sm_id=master_sm.id_, master_id=master_sm.id_) <NEW_LINE> <DEDENT> <DEDENT> elif (master_sm.state != MSTATE_HOLD or (master_sm.state == MSTATE_HOLD and (master_sm.hold_sg != sg_id and master_sm.hold_sg != HOLD_SG_ALL))): <NEW_LINE> <INDENT> create_event(MasterSMPartialReconfig, db_session=db_session, sm_id=master_sm.id_, master_id=master_sm.id_, sg_id=sg_id, sg_name=zone_sm.sg.name) <NEW_LINE> <DEDENT> if not zone_sm_event: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if master_sm.state == MSTATE_READY: <NEW_LINE> <INDENT> create_event(zone_sm_event, db_session=db_session, sm_id=zone_sm.id_, zone_id=zone_sm.id_, name=zone_sm.name, delay=delay_time, coalesce_period=coalesce_time, **kwargs) <NEW_LINE> return <NEW_LINE> <DEDENT> elif master_sm.state == MSTATE_HOLD: <NEW_LINE> <INDENT> schedule_time = master_sm.hold_stop + delay_time <NEW_LINE> create_event(zone_sm_event, db_session=db_session, time=schedule_time, coalesce_period=coalesce_time, sm_id=zone_sm.id_, zone_id=zone_sm.id_, name=zone_sm.name, **kwargs) <NEW_LINE> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log_critical('MasterSM - unrecognized state, exiting') <NEW_LINE> systemd_exit(os.EX_SOFTWARE, SDEX_GENERIC) <NEW_LINE> <DEDENT> return | Schedule MasterSM zone creation/update events
Zone SM helper function | 625941bed164cc6175782c5f |
def _check_ur(self): <NEW_LINE> <INDENT> return self.turn == self.board[0][2] == self.board[1][1] == self.board[2][0] | Assures all values in upper-right diagonal are winning or not | 625941be92d797404e30409b |
def getPathForOID(self, oid, create=False): <NEW_LINE> <INDENT> if isinstance(oid, int): <NEW_LINE> <INDENT> oid = utils.p64(oid) <NEW_LINE> <DEDENT> path = self.layout.oid_to_path(oid) <NEW_LINE> path = os.path.join(self.base_dir, path) <NEW_LINE> if create and not os.path.exists(path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.makedirs(path) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> assert os.path.exists(path) <NEW_LINE> <DEDENT> <DEDENT> return path | Given an OID, return the path on the filesystem where
the blob data relating to that OID is stored.
If the create flag is given, the path is also created if it didn't
exist already. | 625941bebaa26c4b54cb1034 |
def frequencySort2(self, s: str) -> str: <NEW_LINE> <INDENT> return ''.join(c * f for c, f in Counter(s).most_common()) | Pure python function. | 625941be8e7ae83300e4aede |
def get_report_file(x, amazon_report_id): <NEW_LINE> <INDENT> report = try_or_sleep(x.get_report)(report_id=bytes(str(amazon_report_id), CODING)) <NEW_LINE> text = report.response.text <NEW_LINE> return text_to_df(text, report.response.encoding) | Get report and convert it to DF. | 625941be5f7d997b871749a6 |
def allocate(self, host_type): <NEW_LINE> <INDENT> server_number = 1 <NEW_LINE> if host_type in self.hosts: <NEW_LINE> <INDENT> server_number = self._next_server_number(self.hosts[host_type]) <NEW_LINE> self.hosts[host_type].append(server_number) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.hosts[host_type] = [server_number] <NEW_LINE> <DEDENT> return host_type + str(server_number) | Reserve and return the next available hostname | 625941be3346ee7daa2b2c7b |
def pause(start_time, action_period): <NEW_LINE> <INDENT> tsleep = start_time + action_period - time() <NEW_LINE> if tsleep > 0: <NEW_LINE> <INDENT> sleep(tsleep) | Sleep untill next action period | 625941bed4950a0f3b08c263 |
def load_h5(fname): <NEW_LINE> <INDENT> f = h5py.File(fname) <NEW_LINE> data = dict() <NEW_LINE> for k in f.keys(): <NEW_LINE> <INDENT> data[k] = f[k][:] <NEW_LINE> <DEDENT> return data | load .h5 file and return a dict | 625941bea05bb46b383ec736 |
@register.simple_tag(takes_context=True) <NEW_LINE> def url_replace(context, **kwargs): <NEW_LINE> <INDENT> query = context['request'].GET.dict() <NEW_LINE> query.update(kwargs) <NEW_LINE> return urlencode(query) | will append kwargs to the existing url
ie: assuming the current url is '/home/?foo=bar'
<a href="?{% url_replace page=1 %}">Next</a>
rendered html:
<a href="/home/?foo=bar&page=1">Next</a> | 625941be6fb2d068a760efac |
@tf_export('cos') <NEW_LINE> def cos(x, name=None): <NEW_LINE> <INDENT> _ctx = _context.context() <NEW_LINE> if not _ctx.executing_eagerly(): <NEW_LINE> <INDENT> _, _, _op = _op_def_lib._apply_op_helper( "Cos", x=x, name=name) <NEW_LINE> _result = _op.outputs[:] <NEW_LINE> _inputs_flat = _op.inputs <NEW_LINE> _attrs = ("T", _op.get_attr("T")) <NEW_LINE> _execute.record_gradient( "Cos", _inputs_flat, _attrs, _result, name) <NEW_LINE> _result, = _result <NEW_LINE> return _result <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._handle, _ctx.device_name, "Cos", name, _ctx._post_execution_callbacks, x) <NEW_LINE> return _result <NEW_LINE> <DEDENT> except _core._FallbackException: <NEW_LINE> <INDENT> return cos_eager_fallback( x, name=name) <NEW_LINE> <DEDENT> except _core._NotOkStatusException as e: <NEW_LINE> <INDENT> if name is not None: <NEW_LINE> <INDENT> message = e.message + " name: " + name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> message = e.message <NEW_LINE> <DEDENT> _six.raise_from(_core._status_to_exception(e.code, message), None) | Computes cos of x element-wise.
Args:
x: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`, `complex64`, `complex128`.
name: A name for the operation (optional).
Returns:
A `Tensor`. Has the same type as `x`. | 625941bec4546d3d9de72943 |
def load_jpeg(self): <NEW_LINE> <INDENT> return self.video._video_zip.open(self.video._frame_name[self.index]).read() | Loads and returns the frame as compressed jpeg data. | 625941be167d2b6e31218aa8 |
def CheckForCopyright(filename, lines, error): <NEW_LINE> <INDENT> for line in xrange(1, min(len(lines), 11)): <NEW_LINE> <INDENT> if re.search(r'Copyright', lines[line], re.I): break <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> error(filename, 1, 'legal/copyright', 5, 'No copyright, suggest: "Copyright (c) %d, The Toft Authors.\n' ' All rights reserved."' % datetime.date.today().year) | Logs an error if no Copyright message appears at the top of the file. | 625941beaad79263cf39094f |
def __init__(self, entry, feed=None): <NEW_LINE> <INDENT> self.feed = feed <NEW_LINE> self.post = entry | Entry is expected to be the dictionary object from a FeedSync
After wrangling, it will become a models.Post object. | 625941be0a366e3fb873e729 |
def test_04a_validate_optional_description_missing(self): <NEW_LINE> <INDENT> info, _ = self._load_feed_file() <NEW_LINE> del info['reports'][0]['description'] <NEW_LINE> cr = CbReport(**info['reports'][0]) <NEW_LINE> assert 'description' not in cr.data | Verify that description is optional and not required. | 625941be4e696a04525c935e |
def __init__(self, path): <NEW_LINE> <INDENT> self._properties = {} <NEW_LINE> if not os.path.isfile(path): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for line in open(path): <NEW_LINE> <INDENT> matchobj = re.match(r'(\w+)=(.*)', line.strip()) <NEW_LINE> if matchobj: <NEW_LINE> <INDENT> var = matchobj.group(1) <NEW_LINE> val = matchobj.group(2) <NEW_LINE> if var not in self._properties: <NEW_LINE> <INDENT> self._properties[var] = val <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for key in VERSION_PROPERTIES: <NEW_LINE> <INDENT> if key not in self._properties: <NEW_LINE> <INDENT> logging.warning('Mandatory key "%s" does not exist in %s', key, path) | Parses a version definition file.
Args:
path: A filename which has the version definition.
If the file is not existent, empty properties are prepared instead. | 625941be0c0af96317bb80fa |
def pythonify(filelist: List[str], arguments: List[str] = []) -> None: <NEW_LINE> <INDENT> if not isinstance(filelist, list): <NEW_LINE> <INDENT> raise ValueError("First argument must be a list") <NEW_LINE> <DEDENT> options, args = parse_args(arguments) <NEW_LINE> options.full = True <NEW_LINE> execute(options, filelist) | Convert to python the files included in the list. | 625941be26238365f5f0ed7c |
def extract_email_features(email_task): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> task_input_information = json.loads(email_task.task_input) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> log.error("Could not parse task input as valid json; task input: %s", email_task.task_input) <NEW_LINE> return email_error_information() <NEW_LINE> <DEDENT> email = CourseEmail.objects.get(id=task_input_information['email_id']) <NEW_LINE> email_feature_dict = { 'created': get_default_time_display(email.created), 'sent_to': [target.long_display() for target in email.targets.all()], 'requester': str(email_task.requester), } <NEW_LINE> features = ['subject', 'html_message', 'id'] <NEW_LINE> email_info = {feature: str(getattr(email, feature)) for feature in features} <NEW_LINE> email_feature_dict['email'] = email_info <NEW_LINE> number_sent = _('0 sent') <NEW_LINE> if hasattr(email_task, 'task_output') and email_task.task_output is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> task_output = json.loads(email_task.task_output) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> log.error("Could not parse task output as valid json; task output: %s", email_task.task_output) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if 'succeeded' in task_output and task_output['succeeded'] > 0: <NEW_LINE> <INDENT> num_emails = task_output['succeeded'] <NEW_LINE> number_sent = ungettext( "{num_emails} sent", "{num_emails} sent", num_emails ).format(num_emails=num_emails) <NEW_LINE> <DEDENT> if 'failed' in task_output and task_output['failed'] > 0: <NEW_LINE> <INDENT> num_emails = task_output['failed'] <NEW_LINE> number_sent += ", " <NEW_LINE> number_sent += ungettext( "{num_emails} failed", "{num_emails} failed", num_emails ).format(num_emails=num_emails) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> email_feature_dict['number_sent'] = number_sent <NEW_LINE> return email_feature_dict | From the given task, extract email content information
Expects that the given task has the following attributes:
* task_input (dict containing email_id)
* task_output (optional, dict containing total emails sent)
* requester, the user who executed the task
With this information, gets the corresponding email object from the
bulk emails table, and loads up a dict containing the following:
* created, the time the email was sent displayed in default time display
* sent_to, the group the email was delivered to
* email, dict containing the subject, id, and html_message of an email
* number_sent, int number of emails sent
* requester, the user who sent the emails
If task_input cannot be loaded, then the email cannot be loaded
and None is returned for these fields. | 625941be23849d37ff7b2fa2 |
def GetFannedVRad(): <NEW_LINE> <INDENT> vrad = np.array([ 289.9, 287.2, 271.4, 318.2, 236.6, 258.6]) <NEW_LINE> return vrad | GetFannedVRad:
Returns the radial velocity of the Ophiuchus Stream members identified as
fanned candidates by Sesar et al. (2016).
Args: None
Returns:
vrad (array) | 625941be4d74a7450ccd40d5 |
def clean(self): <NEW_LINE> <INDENT> data = self.data <NEW_LINE> phone = data.get('phone') <NEW_LINE> password = data.get('password') <NEW_LINE> if password not in cache.get(u'pwds_{}'.format(phone), []): <NEW_LINE> <INDENT> raise forms.ValidationError(u'动态密码错误') <NEW_LINE> <DEDENT> return data | Check phone and password | 625941be4e4d5625662d42ed |
def shownChanged(self, boardview, shown): <NEW_LINE> <INDENT> pass | Update the suggestions to match a changed position. | 625941becad5886f8bd26eec |
def maxProfit(self, prices): <NEW_LINE> <INDENT> lowest_price = sys.maxsize <NEW_LINE> largest_return = 0 <NEW_LINE> for i in prices: <NEW_LINE> <INDENT> if i < lowest_price: <NEW_LINE> <INDENT> lowest_price = i <NEW_LINE> <DEDENT> elif (i - lowest_price) > largest_return: <NEW_LINE> <INDENT> largest_return = i - lowest_price <NEW_LINE> <DEDENT> <DEDENT> return largest_return | One pass. O(n)
:type prices: List[int]
:rtype: int | 625941bea8ecb033257d2fe0 |
def do_memstats(self, args): <NEW_LINE> <INDENT> self._exec_command(args, JERRY_DEBUGGER_MEMSTATS) <NEW_LINE> return | Memory statistics | 625941bea8370b77170527b3 |
def read_origin_destination(filename, separator=','): <NEW_LINE> <INDENT> origin_destination_list = [] <NEW_LINE> Log.add('Reading origin/destination statistics from file ...') <NEW_LINE> with open(filename, 'r') as f: <NEW_LINE> <INDENT> line = f.readline() <NEW_LINE> while line: <NEW_LINE> <INDENT> fields = line.rstrip().split(separator) <NEW_LINE> origin_destination_list.append((fields[0].strip(), fields[1].strip(), float(fields[2].strip()))) <NEW_LINE> line = f.readline() <NEW_LINE> <DEDENT> <DEDENT> Log.add('Finished.') <NEW_LINE> return origin_destination_list | Reads origin/destination statistics from a csv file
with the following structure:
origin1,destination1,weight
origin2,destination2,weight
origin3,destination3,weight
Parameters
----------
filename: str
path to the file containing the origin/destination statistics
separator: str
arbitrary separation character (default: ',')
Returns
-------
list | 625941be090684286d50ebf4 |
def tstheng(next, qiang): <NEW_LINE> <INDENT> global a, b, c, d <NEW_LINE> if (a - next % a) < c or (b - next // a) < d: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for k in range(c): <NEW_LINE> <INDENT> if qiang[next + k] != 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for m in range(d): <NEW_LINE> <INDENT> if qiang[next + k + m * a] != 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return True | 检查下一块砖能不能横着铺 | 625941be7d43ff24873a2bb0 |
def _may_send_newlines(self, con): <NEW_LINE> <INDENT> scnt = 0 <NEW_LINE> netok = True <NEW_LINE> try: <NEW_LINE> <INDENT> ppos = self.get_sent_pos(con) <NEW_LINE> it_lines = self.select_lines_to_send(con, ppos) <NEW_LINE> scnt, pos = self.send_new_lines(con, it_lines) <NEW_LINE> if scnt > 0: <NEW_LINE> <INDENT> self.save_sent_pos(pos) <NEW_LINE> <DEDENT> <DEDENT> except pywintypes.error as e: <NEW_LINE> <INDENT> self.lerror("send error", str(e)) <NEW_LINE> netok = False <NEW_LINE> <DEDENT> return scnt, netok | Send new lines if there are ones content with additional conditions.
Note:
Conditions are over last position & no duplicates
Args:
con(DBConnector): DB connection
Returns:
int: Count of sent lines
netok: True if sending causes no network problem. | 625941be046cf37aa974cc5c |
def automaton_copy( s :int, g :Automaton, g_dup :Automaton, pmap_vrelevant :ReadPropertyMap = None, pmap_erelevant :ReadPropertyMap = None, pmap_vertices :ReadWritePropertyMap = None, pmap_edges :ReadWritePropertyMap = None, callback_dup_vertex = None, callback_dup_edge = None ): <NEW_LINE> <INDENT> map_vcolor = defaultdict(int) <NEW_LINE> pmap_vcolor = make_assoc_property_map(map_vcolor) <NEW_LINE> if not pmap_vrelevant: <NEW_LINE> <INDENT> pmap_vrelevant = make_func_property_map(lambda u: True) <NEW_LINE> <DEDENT> if not pmap_erelevant: <NEW_LINE> <INDENT> pmap_erelevant = make_func_property_map(lambda e: True) <NEW_LINE> <DEDENT> if not pmap_vertices: <NEW_LINE> <INDENT> map_vertices = dict() <NEW_LINE> pmap_vertices = make_assoc_property_map(map_vertices) <NEW_LINE> <DEDENT> if not pmap_edges: <NEW_LINE> <INDENT> map_edges = dict() <NEW_LINE> pmap_edges = make_assoc_property_map(map_edges) <NEW_LINE> <DEDENT> vis = DepthFirstSearchCopyVisitor( g_dup, pmap_vrelevant, pmap_erelevant, pmap_vertices, pmap_edges, pmap_vcolor, callback_dup_vertex, callback_dup_edge ) <NEW_LINE> depth_first_search( s, g, pmap_vcolor, vis, if_push = lambda e, g: pmap_erelevant[e] and pmap_vrelevant[target(e, g)] ) | Copy a sub-graph from an Automaton according to an edge-based filtering
starting from a given source node.
Args:
s: The VertexDescriptor of the source node.
g: An Automaton instance.
pmap_vrelevant: A ReadPropertyMap{VertexDescriptor : bool} which indicates
for each vertex whether if it must be duped or not.
Only used if vis == None.
pmap_erelevant: A ReadPropertyMap{EdgeDescriptor : bool} which indicates
for each edge whether if it must be duped or not.
Only used if vis == None.
callback_dup_vertex: Callback(u, g, u_dup, g_dup).
Pass None if irrelevant.
callback_dup_edge: Callback(e, g, e_dup, g_dup).
Pass None if irrelevant.
vis: Pass a custom DepthFirstSearchExtractVisitor or None.
This visitor must overload super()'s methods. | 625941be925a0f43d2549d86 |
def get( self, resource_group_name, network_watcher_name, **kwargs ): <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } <NEW_LINE> error_map.update(kwargs.pop('error_map', {})) <NEW_LINE> api_version = "2020-11-01" <NEW_LINE> accept = "application/json" <NEW_LINE> url = self.get.metadata['url'] <NEW_LINE> path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'networkWatcherName': self._serialize.url("network_watcher_name", network_watcher_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } <NEW_LINE> url = self._client.format_url(url, **path_format_arguments) <NEW_LINE> query_parameters = {} <NEW_LINE> query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') <NEW_LINE> header_parameters = {} <NEW_LINE> header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') <NEW_LINE> request = self._client.get(url, query_parameters, header_parameters) <NEW_LINE> pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) <NEW_LINE> response = pipeline_response.http_response <NEW_LINE> if response.status_code not in [200]: <NEW_LINE> <INDENT> map_error(status_code=response.status_code, response=response, error_map=error_map) <NEW_LINE> error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) <NEW_LINE> raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) <NEW_LINE> <DEDENT> deserialized = self._deserialize('NetworkWatcher', pipeline_response) <NEW_LINE> if cls: <NEW_LINE> <INDENT> return cls(pipeline_response, deserialized, {}) <NEW_LINE> <DEDENT> return deserialized | Gets the specified network watcher by resource group.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param network_watcher_name: The name of the network watcher.
:type network_watcher_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: NetworkWatcher, or the result of cls(response)
:rtype: ~azure.mgmt.network.v2020_11_01.models.NetworkWatcher
:raises: ~azure.core.exceptions.HttpResponseError | 625941be50485f2cf553ccaa |
def get_data(self): <NEW_LINE> <INDENT> self._init() <NEW_LINE> if not self._measured: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def abs_file_dict(d): <NEW_LINE> <INDENT> return dict((abs_file(k), v) for k,v in iitems(d)) <NEW_LINE> <DEDENT> self.data.add_lines(abs_file_dict(self.collector.get_line_data())) <NEW_LINE> self.data.add_arcs(abs_file_dict(self.collector.get_arc_data())) <NEW_LINE> self.data.add_plugins(abs_file_dict(self.collector.get_plugin_data())) <NEW_LINE> self.collector.reset() <NEW_LINE> if self._warn_unimported_source: <NEW_LINE> <INDENT> for pkg in self.source_pkgs: <NEW_LINE> <INDENT> if pkg not in sys.modules: <NEW_LINE> <INDENT> self._warn("Module %s was never imported." % pkg) <NEW_LINE> <DEDENT> elif not ( hasattr(sys.modules[pkg], '__file__') and os.path.exists(sys.modules[pkg].__file__) ): <NEW_LINE> <INDENT> self._warn("Module %s has no Python source." % pkg) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._warn( "Module %s was previously imported, " "but not measured." % pkg ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> summary = self.data.summary() <NEW_LINE> if not summary and self._warn_no_data: <NEW_LINE> <INDENT> self._warn("No data was collected.") <NEW_LINE> <DEDENT> for src in self.source: <NEW_LINE> <INDENT> for py_file in find_python_files(src): <NEW_LINE> <INDENT> py_file = files.canonical_filename(py_file) <NEW_LINE> if self.omit_match and self.omit_match.match(py_file): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> self.data.touch_file(py_file) <NEW_LINE> <DEDENT> <DEDENT> self._measured = False <NEW_LINE> return self.data | Get the collected data and reset the collector.
Also warn about various problems collecting data.
Returns:
:class:`CoverageData`: the collected coverage data. | 625941be71ff763f4b549599 |
def add_bounds_for_categorical(self, bounds_arr): <NEW_LINE> <INDENT> for param in self.hyperparams: <NEW_LINE> <INDENT> if param.param_type == 'categorical': <NEW_LINE> <INDENT> lower = np.zeros(len(param.possible_values)) <NEW_LINE> upper = np.ones(len(param.possible_values)) <NEW_LINE> bounds_arr = np.concatenate([bounds_arr, np.vstack([lower, upper]).T]) <NEW_LINE> <DEDENT> <DEDENT> return bounds_arr | not used | 625941be711fe17d82542283 |
def select_label_sequentially(self, k_labels, label_scores, label_models): <NEW_LINE> <INDENT> n_topics = label_scores.shape[0] <NEW_LINE> chosen_labels = [] <NEW_LINE> for _ in xrange(n_topics): <NEW_LINE> <INDENT> chosen_labels.append(list()) <NEW_LINE> <DEDENT> for i in xrange(n_topics): <NEW_LINE> <INDENT> for j in xrange(k_labels): <NEW_LINE> <INDENT> inds, scores = self.label_mmr_score(i, chosen_labels[i], label_scores, label_models) <NEW_LINE> chosen_labels[i].append(inds[np.argmax(scores)]) <NEW_LINE> <DEDENT> <DEDENT> return chosen_labels | Return:
------------
list<list<int>>: shape n_topics x k_labels | 625941be7047854f462a131e |
def most_similar_to_given(model, average, given): <NEW_LINE> <INDENT> minimum = (float('inf'), None) <NEW_LINE> distances = model.wv.distances(average, given) <NEW_LINE> for i, w in enumerate(distances): <NEW_LINE> <INDENT> if distances[i] < minimum[0]: <NEW_LINE> <INDENT> minimum = (distances[i], given[i]) <NEW_LINE> <DEDENT> <DEDENT> return minimum[1] | Finds the most similar word from the set of words
to the average word
average : a word VECTOR that represents the average of several words
given : a set of words to compare the average word to
Returns the word in given closest to the average word | 625941be50485f2cf553ccab |
def test_decorator(self): <NEW_LINE> <INDENT> class Resource(object): <NEW_LINE> <INDENT> @guard.guard(make_checker(True)) <NEW_LINE> def allowed(self, request): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @guard.guard(make_checker(False)) <NEW_LINE> def denied(self, request): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> request = http.Request.blank('/') <NEW_LINE> Resource().allowed(request) <NEW_LINE> self.assertRaises(http.UnauthorizedError, Resource().denied, request) | Check the decorator is passing or failing in the correct manner. | 625941bebe383301e01b539e |
def select_filters(filters, level): <NEW_LINE> <INDENT> return [f for f in filters if f.max_debug_level is None or cmp_debug_levels(level, f.max_debug_level) <= 0] | Return from the list in ``filters`` those filters which indicate that
they should run for the given debug level. | 625941beb7558d58953c4e2b |
def run_test(self, redant): <NEW_LINE> <INDENT> vol_option = {'cluster.server-quorum-type': 'server'} <NEW_LINE> redant.set_volume_options(self.vol_name, vol_option, self.server_list[0]) <NEW_LINE> brick_list = redant.get_all_bricks(self.vol_name, self.server_list[0]) <NEW_LINE> redant.stop_glusterd(self.server_list[1:]) <NEW_LINE> ret = redant.wait_for_glusterd_to_stop(self.server_list[1:]) <NEW_LINE> if not ret: <NEW_LINE> <INDENT> raise Exception(f"Glusterd did not stop on " f"all the servers: {self.server_list[0]}") <NEW_LINE> <DEDENT> ret = redant.are_bricks_offline(self.vol_name, brick_list[0:1], self.server_list[0]) <NEW_LINE> if not ret: <NEW_LINE> <INDENT> raise Exception("Bricks are online") <NEW_LINE> <DEDENT> redant.restart_glusterd(self.server_list[0]) <NEW_LINE> ret = redant.wait_for_glusterd_to_start(self.server_list[0]) <NEW_LINE> if not ret: <NEW_LINE> <INDENT> raise Exception(f"Glusterd not running on {self.server_list[0]}") <NEW_LINE> <DEDENT> ret = redant.are_bricks_offline(self.vol_name, brick_list[0:1], self.server_list[0]) <NEW_LINE> if not ret: <NEW_LINE> <INDENT> raise Exception("Bricks are online") <NEW_LINE> <DEDENT> redant.start_glusterd(self.server_list) <NEW_LINE> ret = redant.wait_for_glusterd_to_start(self.server_list) <NEW_LINE> if not ret: <NEW_LINE> <INDENT> raise Exception(f"Glusterd not started on all the " f"servers: {self.server_list}") <NEW_LINE> <DEDENT> ret = redant.wait_for_volume_process_to_be_online(self.vol_name, self.server_list[0], self.server_list, timeout=600) <NEW_LINE> if not ret: <NEW_LINE> <INDENT> raise Exception("Not all volume processes are online") | Test Brick status when Quorum is not met after glusterd restart.
1. Create a volume and mount it.
2. Set the quorum type to 'server'.
3. Bring some nodes down such that quorum won't be met.
4. Brick status should be offline in the node which is up.
5. Restart glusterd in this node.
6. The brick status still should be offline as quorum isn't met. | 625941be73bcbd0ca4b2bf89 |
def respondToHead(self, trans): <NEW_LINE> <INDENT> res = trans.response() <NEW_LINE> w = res.write <NEW_LINE> res.write = lambda *args: None <NEW_LINE> self.respondToGet(trans) <NEW_LINE> res.write = w | Respond to a HEAD request.
A correct but inefficient implementation. | 625941be7b180e01f3dc4715 |
def test_make_macro(self): <NEW_LINE> <INDENT> macro, body = self.create_random_instance(return_body=True) <NEW_LINE> self.assertEqual(body, macro.body) | Test creating a macro and checking its parameters. The base class
will already do part of this test but will not check parameters. | 625941be796e427e537b04d6 |
def batch_normalization(x, mean, std, beta, gamma, epsilon=0.0001): <NEW_LINE> <INDENT> return tf.nn.batch_normalization(x, mean, std, beta, gamma, epsilon) | Apply batch normalization on x given mean, std, beta and gamma.
| 625941be4a966d76dd550f1f |
def to_openbabel(self): <NEW_LINE> <INDENT> obmol = cclib.bridge.makeopenbabel( self.atomcoords, self.atomnos, self.charge, self.mult ) <NEW_LINE> obmol.SetTitle(self.name) <NEW_LINE> return obmol | Return a OBMol. | 625941be23e79379d52ee479 |
@utils.supported_filters() <NEW_LINE> @check_user_admin_or_owner() <NEW_LINE> @database.run_in_session() <NEW_LINE> @utils.wrap_to_dict(RESP_FIELDS) <NEW_LINE> def get_user( user_id, exception_when_missing=True, user=None, session=None, **kwargs ): <NEW_LINE> <INDENT> return utils.get_db_object( session, models.User, exception_when_missing, id=user_id ) | get field dict of a user. | 625941be8e71fb1e9831d6bd |
def get_own_set_attribute(self, node, set_name, attr_name): <NEW_LINE> <INDENT> return self._send({'name': 'getOwnSetAttribute', 'args': [node, set_name, attr_name]}) | Get the value of the attribute entry specifically set for the set at the node.
:param node: the owner of the set.
:type node: dict
:param set_name: the name of the set.
:type set_name: str
:param attr_name: the name of the attribute entry.
:type attr_name: str
:returns: Return the value of the attribute. If it is undefined, then there is no such attribute at the set.
:rtype: str or int or float or bool or dict or None
:raises CoreIllegalArgumentError: If some of the parameters don't match the input criteria.
:raises CoreIllegalOperationError: If the context of the operation is not allowed.
:raises CoreInternalError: If some internal error took place inside the core layers. | 625941be9c8ee82313fbb687 |
def test_toggle_call_recording_neutral(self): <NEW_LINE> <INDENT> estimated_response_json = { 'recording_enabled': 'wildcard', } <NEW_LINE> client = get_client() <NEW_LINE> with patch.object(client, 'get_call', return_value=estimated_response_json) as get_mock: <NEW_LINE> <INDENT> client.toggle_call_recording('callId') <NEW_LINE> get_mock.assert_called_with('callId') | toggle_call_recording() should call get_call with the id | 625941bed164cc6175782c60 |
def __init__(self): <NEW_LINE> <INDENT> self.InvokerTDid = None | :param InvokerTDid: 凭证did
:type InvokerTDid: str | 625941bed486a94d0b98e057 |
def show_vcs_output_vcs_nodes_vcs_node_info_manufacturer_name(self, **kwargs): <NEW_LINE> <INDENT> config = ET.Element("config") <NEW_LINE> show_vcs = ET.Element("show_vcs") <NEW_LINE> config = show_vcs <NEW_LINE> if kwargs.pop('delete_show_vcs', False) is True: <NEW_LINE> <INDENT> delete_show_vcs = config.find('.//*show-vcs') <NEW_LINE> delete_show_vcs.set('operation', 'delete') <NEW_LINE> <DEDENT> output = ET.SubElement(show_vcs, "output") <NEW_LINE> if kwargs.pop('delete_output', False) is True: <NEW_LINE> <INDENT> delete_output = config.find('.//*output') <NEW_LINE> delete_output.set('operation', 'delete') <NEW_LINE> <DEDENT> vcs_nodes = ET.SubElement(output, "vcs-nodes") <NEW_LINE> if kwargs.pop('delete_vcs_nodes', False) is True: <NEW_LINE> <INDENT> delete_vcs_nodes = config.find('.//*vcs-nodes') <NEW_LINE> delete_vcs_nodes.set('operation', 'delete') <NEW_LINE> <DEDENT> vcs_node_info = ET.SubElement(vcs_nodes, "vcs-node-info") <NEW_LINE> if kwargs.pop('delete_vcs_node_info', False) is True: <NEW_LINE> <INDENT> delete_vcs_node_info = config.find('.//*vcs-node-info') <NEW_LINE> delete_vcs_node_info.set('operation', 'delete') <NEW_LINE> <DEDENT> manufacturer_name = ET.SubElement(vcs_node_info, "manufacturer-name") <NEW_LINE> if kwargs.pop('delete_manufacturer_name', False) is True: <NEW_LINE> <INDENT> delete_manufacturer_name = config.find('.//*manufacturer-name') <NEW_LINE> delete_manufacturer_name.set('operation', 'delete') <NEW_LINE> <DEDENT> manufacturer_name.text = kwargs.pop('manufacturer_name') <NEW_LINE> callback = kwargs.pop('callback', self._callback) <NEW_LINE> return callback(config) | Auto Generated Code
| 625941be99fddb7c1c9de2a5 |
def rule_text(self): <NEW_LINE> <INDENT> if self.debug: <NEW_LINE> <INDENT> print('rule_text' + lineno()) <NEW_LINE> <DEDENT> return 'S3 bucket does not have the required tags of Name, ResourceOwner, DeployedBy, Project' | Returns rule text
:return: | 625941be498bea3a759b99c2 |
def __init__(self, decorations=None, time=None, value=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._decorations = None <NEW_LINE> self._time = None <NEW_LINE> self._value = None <NEW_LINE> self.discriminator = None <NEW_LINE> if decorations is not None: <NEW_LINE> <INDENT> self.decorations = decorations <NEW_LINE> <DEDENT> self.time = time <NEW_LINE> self.value = value | VehicleStatsAmbientAirTempMilliCWithDecoration - a model defined in OpenAPI | 625941befbf16365ca6f60d1 |
def test_invalid_product(self): <NEW_LINE> <INDENT> self.basket.addProduct("TTT", 2) <NEW_LINE> total = self.basket.getFinalAmount("BOGO50") <NEW_LINE> self.assertRaises(ValueError("Product is not available")) | Test Validation | 625941becdde0d52a9e52f43 |
def test_annotate_default_action_sub_default_group_default_iob_annotation_empty_in_data(self): <NEW_LINE> <INDENT> pattern = 'pos~"NN.?"' <NEW_LINE> annotation = [] <NEW_LINE> data = [ {'raw':'Over', 'pos':'IN'}, {'raw':'a', 'pos':'DT' }, {'raw':'cup', 'pos':'NN' }, {'raw':'of', 'pos':'IN'}, {'raw':'coffee', 'pos':'NN'}, {'raw':',', 'pos':','}, {'raw':'Mr.', 'pos':'NNP'}, {'raw':'Stone', 'pos':'NNP'}, {'raw':'told', 'pos':'VBD'}, {'raw':'his', 'pos':'PRP$'}, {'raw':'story', 'pos':'NN'} ] <NEW_LINE> expected = [ {'raw':'Over', 'pos':'IN'}, {'raw':'a', 'pos':'DT' }, {'raw':'of', 'pos':'IN'}, {'raw':',', 'pos':','}, {'raw':'told', 'pos':'VBD'}, {'raw':'his', 'pos':'PRP$'}] <NEW_LINE> result = pyrata.re.annotate(pattern, annotation, data) <NEW_LINE> self.assertEqual(result, expected) | Test annotate method on step with default args namely sub action, zero group and iob False. The annotation is empty. The pattern is present in the data. | 625941be2c8b7c6e89b356d5 |
def RetrieveOrgUnit(self, customer_id, org_unit_path): <NEW_LINE> <INDENT> uri = UNIT_URL % (customer_id, org_unit_path) <NEW_LINE> return self._GetProperties(uri) | Retrieve a Orgunit based on its path.
Args:
customer_id: The ID of the Google Apps customer.
org_unit_path: The organization's full path name.
Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization)
Returns:
A dict containing the result of the retrieve operation. | 625941be4f6381625f114950 |
def get_call_type_with_literals(self, context, args, kws, literals): <NEW_LINE> <INDENT> return self.get_call_type(context, args, kws) | Simliar to .get_call_type() but with extra argument for literals.
Default implementation ignores literals and forwards to .get_call_type(). | 625941be6fece00bbac2d64f |
def group_install(name=None, groups=None, skip=None, include=None, **kwargs): <NEW_LINE> <INDENT> pkg_groups = [] <NEW_LINE> if groups: <NEW_LINE> <INDENT> pkg_groups = yaml.safe_load(groups) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pkg_groups.append(name) <NEW_LINE> <DEDENT> skip_pkgs = [] <NEW_LINE> if skip: <NEW_LINE> <INDENT> skip_pkgs = yaml.safe_load(skip) <NEW_LINE> <DEDENT> include = [] <NEW_LINE> if include: <NEW_LINE> <INDENT> include = yaml.safe_load(include) <NEW_LINE> <DEDENT> ret = {} <NEW_LINE> pkgs = [] <NEW_LINE> for group in pkg_groups: <NEW_LINE> <INDENT> group_detail = group_info(group) <NEW_LINE> for package in group_detail['mandatory packages'].keys(): <NEW_LINE> <INDENT> pkgs.append(package) <NEW_LINE> <DEDENT> for package in group_detail['default packages'].keys(): <NEW_LINE> <INDENT> if package not in skip_pkgs: <NEW_LINE> <INDENT> pkgs.append(package) <NEW_LINE> <DEDENT> <DEDENT> for package in include: <NEW_LINE> <INDENT> pkgs.append(package) <NEW_LINE> <DEDENT> <DEDENT> install_pkgs = yaml.safe_dump(pkgs) <NEW_LINE> return install(pkgs=install_pkgs, **kwargs) | Install the passed package group(s). This is basically a wrapper around
pkg.install, which performs package group resolution for the user. This
function is currently considered "experimental", and should be expected to
undergo changes before it becomes official.
name
The name of a single package group to install. Note that this option is
ignored if "groups" is passed.
groups
The names of multiple packages which are to be installed.
CLI Example::
salt '*' pkg.groupinstall groups='["Group 1", "Group 2"]'
skip
The name(s), in a list, of any packages that would normally be
installed by the package group ("default" packages), which should not
be installed.
CLI Examples::
salt '*' pkg.groupinstall 'My Group' skip='["foo", "bar"]'
include
The name(s), in a list, of any packages which are included in a group,
which would not normally be installed ("optional" packages). Note that
this will nor enforce group membership; if you include packages which
are not members of the specified groups, they will still be installed.
CLI Examples::
salt '*' pkg.groupinstall 'My Group' include='["foo", "bar"]'
other arguments
Because this is essentially a wrapper around pkg.install, any argument
which can be passed to pkg.install may also be included here, and it
will be passed along wholesale. | 625941be29b78933be1e55c3 |
def __call__(self): <NEW_LINE> <INDENT> self.page1() <NEW_LINE> grinder.sleep(2117) <NEW_LINE> self.page2() <NEW_LINE> grinder.sleep(1867) <NEW_LINE> self.page3() <NEW_LINE> grinder.sleep(4351) <NEW_LINE> self.page4() <NEW_LINE> grinder.sleep(16341) <NEW_LINE> self.page5() <NEW_LINE> grinder.sleep(1309) <NEW_LINE> self.page6() <NEW_LINE> grinder.sleep(669) <NEW_LINE> self.page7() <NEW_LINE> grinder.sleep(1260) <NEW_LINE> self.page8() <NEW_LINE> grinder.sleep(837) <NEW_LINE> self.page9() <NEW_LINE> grinder.sleep(1108) <NEW_LINE> self.page10() <NEW_LINE> grinder.sleep(3146) <NEW_LINE> self.page11() <NEW_LINE> grinder.sleep(2822) <NEW_LINE> self.page12() <NEW_LINE> grinder.sleep(1333) <NEW_LINE> self.page13() <NEW_LINE> grinder.sleep(17417) <NEW_LINE> self.page14() <NEW_LINE> grinder.sleep(6680) <NEW_LINE> self.page15() <NEW_LINE> grinder.sleep(600) <NEW_LINE> self.page16() <NEW_LINE> grinder.sleep(584) <NEW_LINE> self.page17() <NEW_LINE> grinder.sleep(1049) <NEW_LINE> self.page18() <NEW_LINE> grinder.sleep(2901) <NEW_LINE> self.page19() <NEW_LINE> grinder.sleep(1441) <NEW_LINE> self.page20() <NEW_LINE> grinder.sleep(791) <NEW_LINE> self.page21() <NEW_LINE> grinder.sleep(1365) <NEW_LINE> self.page22() <NEW_LINE> grinder.sleep(1067) <NEW_LINE> self.page23() <NEW_LINE> grinder.sleep(1284) <NEW_LINE> self.page24() <NEW_LINE> grinder.sleep(879) <NEW_LINE> self.page25() <NEW_LINE> grinder.sleep(1066) <NEW_LINE> self.page26() <NEW_LINE> grinder.sleep(974) <NEW_LINE> self.page27() | Called for every run performed by the worker thread. | 625941bed6c5a10208143f5b |
def test_new_accessions_2(self): <NEW_LINE> <INDENT> os.chdir('test_new_accessions_2') <NEW_LINE> ref_acc = ['E-GEOD-42314'] <NEW_LINE> test_acc = new_accessions() <NEW_LINE> os.chdir('..') <NEW_LINE> self.assertEqual(ref_acc, test_acc) | Is the list of new accessions correctly generated for two json files? | 625941be091ae35668666e76 |
def _find_items(self, bill_lines): <NEW_LINE> <INDENT> items = [] <NEW_LINE> skip_line = False <NEW_LINE> for line_index in range(len(bill_lines)): <NEW_LINE> <INDENT> if skip_line: <NEW_LINE> <INDENT> logger.debug( 'Skipped line %s ' 'Used to build previous item' % bill_lines[line_index]) <NEW_LINE> skip_line = False <NEW_LINE> continue <NEW_LINE> <DEDENT> lines = bill_lines[line_index: line_index + 2] <NEW_LINE> if self._is_total_line(lines[0]): <NEW_LINE> <INDENT> logger.debug( 'Found total line: "%s"' % lines[0]) <NEW_LINE> break <NEW_LINE> <DEDENT> item, skip_line = self._process_line(*lines) <NEW_LINE> if item: <NEW_LINE> <INDENT> items.append(item) <NEW_LINE> <DEDENT> <DEDENT> if not items: <NEW_LINE> <INDENT> raise ValueError('No items found') <NEW_LINE> <DEDENT> return items | Find items of the bill.
Returns list of items in format:
[
{
'name': 'item-name [string]',
'quantity': 'item-quantity [int]',
'amount': 'item-amount [float]'
}
] | 625941be1b99ca400220a9c3 |
def list_tasks(self, owner=None): <NEW_LINE> <INDENT> if owner is None: <NEW_LINE> <INDENT> all = self._db.task_list.find() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> all = self._db.task_list.find({'owner': owner}) <NEW_LINE> <DEDENT> for task_dict in all: <NEW_LINE> <INDENT> task_dict['id'] = task_dict.pop('_id') <NEW_LINE> <DEDENT> return all | Return list of tasks. | 625941be6e29344779a62527 |
def slh(n,s,maxiter = 0): <NEW_LINE> <INDENT> if maxiter == 0: <NEW_LINE> <INDENT> return SymmetricLatinHypercubeDesign(n,s) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return SymmetricLatinHypercubeDesignDecorrelation(n,s,maxiter) | short name of SymmetricLatinHypercubeDesign | 625941be596a8972360899d6 |
def SIRT_CPU(projections, volume, geometry, iterations=10, relaxation=1,options = {'poisson_weight': False, 'l2_update': True, 'preview':False, 'bounds':None}, psf=None): <NEW_LINE> <INDENT> if not isinstance(projections, numpy.memmap): <NEW_LINE> <INDENT> projections = numpy.ascontiguousarray(projections) <NEW_LINE> <DEDENT> fwd_weights = np.zeros_like(projections) <NEW_LINE> forwardproject(fwd_weights, np.ones_like(volume, dtype=np.float32), geometry, psf=psf) <NEW_LINE> tol = 1e-6 <NEW_LINE> fwd_weights[fwd_weights < tol] = np.Inf <NEW_LINE> fwd_weights = 1 / fwd_weights <NEW_LINE> bwd_weights = np.zeros_like(volume, dtype=np.float32) <NEW_LINE> backproject(np.ones_like(projections, dtype=np.float32), bwd_weights, geometry, psf=psf) <NEW_LINE> bwd_weights[bwd_weights < tol] = np.Inf <NEW_LINE> bwd_weights = relaxation / bwd_weights <NEW_LINE> print('Doing SIRT with CPU/GPU iterations...') <NEW_LINE> misc.progress_bar(0) <NEW_LINE> for ii in range(iterations): <NEW_LINE> <INDENT> vol_update = np.zeros_like(volume) <NEW_LINE> cur_proj = projections.copy() <NEW_LINE> forwardproject(cur_proj, -volume, geometry, operation='+') <NEW_LINE> cur_proj *= fwd_weights <NEW_LINE> backproject(cur_proj, vol_update, geometry,operation='+') <NEW_LINE> volume += bwd_weights*vol_update <NEW_LINE> volume += vol_update <NEW_LINE> misc.progress_bar((ii+1) / iterations) | SIRT on CPU with or without detector PSF | 625941be377c676e912720bc |
def __setitem__(self, xy, item): <NEW_LINE> <INDENT> x, y = xy <NEW_LINE> self.level_map[y][x] = item | x (col) and y (row) position of char to set. (x and y start with 0) | 625941bea934411ee37515a6 |
def addFactionsFromXML(self, factionRoots) -> None: <NEW_LINE> <INDENT> for factionRoot in factionRoots: <NEW_LINE> <INDENT> factionNames = self.__xml.getNamesFromXML(factionRoot) <NEW_LINE> for name in factionNames: <NEW_LINE> <INDENT> newfaction = Faction(name) <NEW_LINE> self.repository.addFaction(newfaction) | Takes a list of Faction GameObject XML roots and adds
them to the repository | 625941be23849d37ff7b2fa3 |
def my_first_name(): <NEW_LINE> <INDENT> return 'Alexandra' | Return your first name as a string.
>>> my_first_name() != 'PUT YOUR FIRST NAME HERE'
True | 625941be656771135c3eb77f |
def bwCmds( self, bw=None, speedup=0, use_hfsc=False, use_tbf=False): <NEW_LINE> <INDENT> cmds, parent = [], ' root ' <NEW_LINE> if bw and ( bw < 0 or bw > 1000 ): <NEW_LINE> <INDENT> error( 'Bandwidth', bw, 'is outside range 0..1000 Mbps\n' ) <NEW_LINE> <DEDENT> elif bw is not None: <NEW_LINE> <INDENT> if ( speedup > 0 and self.node.name[0:1] == 's' ): <NEW_LINE> <INDENT> bw = speedup <NEW_LINE> <DEDENT> if use_hfsc: <NEW_LINE> <INDENT> cmds += [ '%s qdisc add dev %s root handle 1:0 hfsc default 1', '%s class add dev %s parent 1:0 classid 1:1 hfsc sc ' + 'rate %fMbit ul rate %fMbit' % ( bw, bw ) ] <NEW_LINE> <DEDENT> elif use_tbf: <NEW_LINE> <INDENT> latency_us = 10 * 1500 * 8 / bw <NEW_LINE> cmds += ['%s qdisc add dev %s root handle 1: tbf ' + 'rate %fMbit burst 15000 latency %fus' % ( bw, latency_us ) ] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cmds += [ '%s qdisc add dev %s root handle 1:0 htb default 1', '%s class add dev %s parent 1:0 classid 1:1 htb ' + 'rate %fMbit burst 15k' % bw ] <NEW_LINE> <DEDENT> parent = ' parent 1:1 ' <NEW_LINE> <DEDENT> return cmds, parent | Return tc commands to set bandwidth | 625941bef548e778e58cd48f |
def pauseScreen(mode,score,limit,lev,fClick,ybo,p,st,sc,pc): <NEW_LINE> <INDENT> if click==True and pauseMenu.collidepoint(mx,my): <NEW_LINE> <INDENT> restart() <NEW_LINE> return "menu",0,0,1,0,300,0,0,"pending",0 <NEW_LINE> <DEDENT> if click==True and pauseRetry.collidepoint(mx,my): <NEW_LINE> <INDENT> restart() <NEW_LINE> return "levels",0,0,1,1,300,0,0,"pending",0 <NEW_LINE> <DEDENT> return mode,score,limit,lev,fClick,ybo,p,st,sc,pc | This function checks activity in the pause screen, if menu is clicked then
the user goes to the menu, if they click restart they restart | 625941be4f88993c3716bf7e |
def __init__(self): <NEW_LINE> <INDENT> self.cnn_filter_num = 128 <NEW_LINE> self.cnn_first_filter_size = 5 <NEW_LINE> self.cnn_filter_size = 3 <NEW_LINE> self.res_layer_num = 7 <NEW_LINE> self.l2_reg = 1e-4 <NEW_LINE> self.value_fc_size = 256 <NEW_LINE> self.distributed = False <NEW_LINE> self.input_depth = 14 | WARNING: DO NOT CHANGE THESE PARAMETERS | 625941be7c178a314d6ef36d |
def get_max_joltage(inputs: list) -> int: <NEW_LINE> <INDENT> return max([int(i) for i in inputs]) | Retrieves max joltage from list of inputs. | 625941be7c178a314d6ef36e |
def _convertList(self, vector): <NEW_LINE> <INDENT> return ravel(vector).tolist() | Converts the incoming vector to a python list. | 625941bef7d966606f6a9f14 |
def _update_on_node(self, node, try_all=False): <NEW_LINE> <INDENT> if try_all is True and hasattr(node, 'update_all'): <NEW_LINE> <INDENT> node.update_all() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> node.update() | Call update/update_all on currently focused node. If try_all is
True update_all will be called if available but update will be used as
a fallback.
Args:
node: urwid.TreeNode to call function on.
try_all (optional): bool to try calling update_all before update. | 625941be3d592f4c4ed1cf88 |
def accidentesSize(analyzer): <NEW_LINE> <INDENT> return lt.size(analyzer['accidentes']) | Número de accidentes leidos | 625941be45492302aab5e1d3 |
def extract_encoder_weights(network, names, saveas): <NEW_LINE> <INDENT> layers = las.layers.get_all_layers(network) <NEW_LINE> d = {} <NEW_LINE> for i, name in enumerate(names): <NEW_LINE> <INDENT> for l in layers: <NEW_LINE> <INDENT> if l.name == name: <NEW_LINE> <INDENT> weight = l.W.container.data <NEW_LINE> bias = l.b.container.data <NEW_LINE> d[saveas[i][0]] = weight <NEW_LINE> d[saveas[i][1]] = bias <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return d | extract encoder weights of the given model
:param network: trained model
:param names: names of layer weights to extract
:param saveas: names to save to in a list of tuples [(weight name, bias name), ...]
:return: dictionary containing weights and biases of the encoding layers | 625941be21bff66bcd684868 |
def _create_client(self, clt_class, url, public=True): <NEW_LINE> <INDENT> verify_ssl = pyrax.get_setting("verify_ssl") <NEW_LINE> if self.service == "object_store": <NEW_LINE> <INDENT> client = pyrax.connect_to_cloudfiles(region=self.region, public=public, context=self.identity) <NEW_LINE> <DEDENT> elif self.service == "compute": <NEW_LINE> <INDENT> client = pyrax.connect_to_cloudservers(region=self.region, context=self.identity) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> client = clt_class(self.identity, region_name=self.region, management_url=url, verify_ssl=verify_ssl) <NEW_LINE> <DEDENT> return client | Creates a client instance for the service. | 625941beec188e330fd5a6b7 |
def _get_patchset_revs(args, srctree, recipe_path): <NEW_LINE> <INDENT> import bb <NEW_LINE> if args.initial_rev: <NEW_LINE> <INDENT> return args.initial_rev, args.initial_rev <NEW_LINE> <DEDENT> commits = [] <NEW_LINE> initial_rev = None <NEW_LINE> with open(recipe_path, 'r') as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <INDENT> if line.startswith('# initial_rev:'): <NEW_LINE> <INDENT> initial_rev = line.split(':')[-1].strip() <NEW_LINE> <DEDENT> elif line.startswith('# commit:'): <NEW_LINE> <INDENT> commits.append(line.split(':')[-1].strip()) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> update_rev = initial_rev <NEW_LINE> if initial_rev: <NEW_LINE> <INDENT> stdout, _ = bb.process.run('git rev-list --reverse %s..HEAD' % initial_rev, cwd=srctree) <NEW_LINE> newcommits = stdout.split() <NEW_LINE> for i in xrange(min(len(commits), len(newcommits))): <NEW_LINE> <INDENT> if newcommits[i] == commits[i]: <NEW_LINE> <INDENT> update_rev = commits[i] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return initial_rev, update_rev | Get initial and update rev of a recipe. These are the start point of the
whole patchset and start point for the patches to be re-generated/updated. | 625941bee64d504609d74753 |
def create_preset_images(self): <NEW_LINE> <INDENT> for f in self.get_files_from_data(): <NEW_LINE> <INDENT> photoInstances = {} <NEW_LINE> for preset in self.generator.settings["GALLERY_PRESETS"]: <NEW_LINE> <INDENT> preset_dir = "%s%s%s" % (self.absolute_output_path, os.sep, preset["name"]) <NEW_LINE> photoInstances[preset["name"]] = Photo(self, f, preset_dir, preset) <NEW_LINE> <DEDENT> self.photos.append(photoInstances) | Creates the image assets for each preset and returns a PhotoSet object | 625941beb545ff76a8913d29 |
def test_selinux_enforcing(selinux_getenforce): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> assert selinux_getenforce == "Enforcing" <NEW_LINE> <DEDENT> except AssertionError: <NEW_LINE> <INDENT> pytest.fail(msg="SELinux is not in Enforcing mode!") | Verifies whether SELinux is in 'Enforcing' state.
:param selinux_getenforce: Current enforcing status
:type selinux_getenforce: ``str``
:raises: pytest.Failed | 625941bee76e3b2f99f3a729 |
def save(self, file_name): <NEW_LINE> <INDENT> print('Saving model to: {0}'.format(file_name)) <NEW_LINE> if self.layer == 1: <NEW_LINE> <INDENT> with open(file_name, 'wb') as f: <NEW_LINE> <INDENT> pickle.dump(self.W, f) <NEW_LINE> pickle.dump(self.W2, f) <NEW_LINE> pickle.dump(self.W3, f) <NEW_LINE> pickle.dump(self.vbias, f) <NEW_LINE> pickle.dump(self.hbias, f) <NEW_LINE> pickle.dump(self.dW, f) <NEW_LINE> pickle.dump(self.dW_prev, f) <NEW_LINE> <DEDENT> <DEDENT> elif self.layer == 2: <NEW_LINE> <INDENT> with open(file_name, 'wb') as f: <NEW_LINE> <INDENT> pickle.dump(self.W, f) <NEW_LINE> pickle.dump(self.vbias, f) <NEW_LINE> pickle.dump(self.hbias, f) <NEW_LINE> pickle.dump(self.W1, f) <NEW_LINE> pickle.dump(self.vbias1, f) <NEW_LINE> pickle.dump(self.hbias1, f) <NEW_LINE> <DEDENT> <DEDENT> elif self.layer == 3: <NEW_LINE> <INDENT> with open(file_name, 'wb') as f: <NEW_LINE> <INDENT> pickle.dump(self.W, f) <NEW_LINE> pickle.dump(self.vbias, f) <NEW_LINE> pickle.dump(self.hbias, f) <NEW_LINE> pickle.dump(self.W1, f) <NEW_LINE> pickle.dump(self.vbias1, f) <NEW_LINE> pickle.dump(self.hbias1, f) <NEW_LINE> pickle.dump(self.W22, f) <NEW_LINE> pickle.dump(self.vbias2, f) <NEW_LINE> pickle.dump(self.hbias2, f) | Function to save all main parameters | 625941be56b00c62f0f1456b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.