code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def alias_cset(alias, engine, csets): <NEW_LINE> <INDENT> return csets[alias] | alias a cset to another | 625941bfa17c0f6771cbdf9b |
def getRender(self): <NEW_LINE> <INDENT> return self.render | This method return the html rendered | 625941bf6fb2d068a760efe3 |
def hadamard_matrix_www(url_file, comments=False): <NEW_LINE> <INDENT> n = eval(url_file.split(".")[1]) <NEW_LINE> rws = [] <NEW_LINE> url = "http://neilsloane.com/hadamard/" + url_file <NEW_LINE> f = urlopen(url) <NEW_LINE> s = f.readlines() <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> r = [] <NEW_LINE> for j in range(n): <NEW_LINE> <INDENT> if s[i][j] == "+": <NEW_LINE> <INDENT> r.append(1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> r.append(-1) <NEW_LINE> <DEDENT> <DEDENT> rws.append(r) <NEW_LINE> <DEDENT> f.close() <NEW_LINE> if comments: <NEW_LINE> <INDENT> lastline = s[-1] <NEW_LINE> if lastline[0] == "A": <NEW_LINE> <INDENT> print(lastline) <NEW_LINE> <DEDENT> <DEDENT> return matrix(rws) | Pulls file from Sloane's database and returns the corresponding Hadamard
matrix as a Sage matrix.
You must input a filename of the form "had.n.xxx.txt" as described
on the webpage http://neilsloane.com/hadamard/, where
"xxx" could be empty or a number of some characters.
If comments=True then the "Automorphism..." line of the had.n.xxx.txt
file is printed if it exists. Otherwise nothing is done.
EXAMPLES::
sage: hadamard_matrix_www("had.4.txt") # optional - internet
[ 1 1 1 1]
[ 1 -1 1 -1]
[ 1 1 -1 -1]
[ 1 -1 -1 1]
sage: hadamard_matrix_www("had.16.2.txt",comments=True) # optional - internet
Automorphism group has order = 49152 = 2^14 * 3
[ 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
[ 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1]
[ 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1]
[ 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1]
[ 1 1 1 1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1]
[ 1 -1 1 -1 -1 1 -1 1 1 -1 1 -1 -1 1 -1 1]
[ 1 1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 1 1]
[ 1 -1 -1 1 -1 1 1 -1 1 -1 -1 1 -1 1 1 -1]
[ 1 1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1]
[ 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1 1 1 1 1]
[ 1 1 -1 -1 1 -1 1 -1 -1 -1 1 1 -1 1 -1 1]
[ 1 1 -1 -1 -1 1 -1 1 -1 -1 1 1 1 -1 1 -1]
[ 1 -1 1 -1 1 -1 -1 1 -1 1 -1 1 -1 1 1 -1]
[ 1 -1 1 -1 -1 1 1 -1 -1 1 -1 1 1 -1 -1 1]
[ 1 -1 -1 1 1 1 -1 -1 -1 1 1 -1 -1 -1 1 1]
[ 1 -1 -1 1 -1 -1 1 1 -1 1 1 -1 1 1 -1 -1] | 625941bf71ff763f4b5495d0 |
def _get_dset_array(self, dspath): <NEW_LINE> <INDENT> branch = self._my_ds_from_path(dspath) <NEW_LINE> if isinstance(branch, h5py.Group): <NEW_LINE> <INDENT> return 'group' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (H5Array(branch), dict(branch.attrs)) | returns a pickle-safe array for the branch specified by dspath | 625941bf3617ad0b5ed67e41 |
def cast(*args): <NEW_LINE> <INDENT> return _itkNeighborhoodConnectedImageFilterPython.itkNeighborhoodConnectedImageFilterIUL3IUL3_cast(*args) | cast(itkLightObject obj) -> itkNeighborhoodConnectedImageFilterIUL3IUL3 | 625941bfe8904600ed9f1e72 |
def tr(self, message): <NEW_LINE> <INDENT> return QCoreApplication.translate('VERSAOVegaMonitor', 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 | 625941bf046cf37aa974cc92 |
def match(self, object_id): <NEW_LINE> <INDENT> if self._regexp is None: <NEW_LINE> <INDENT> self._regexp = re.compile(self.regexp) <NEW_LINE> <DEDENT> return self._regexp.match(object_id) | Validate that object ids match the generator. This is used mainly
when an object id is picked arbitrarily (e.g with ``PUT`` requests).
:returns: `True` if the specified object id matches expected format.
:rtype: bool | 625941bf5e10d32532c5ee70 |
def __init__(self, cursor=None, sort_ascending=None, sort_by=None, result_count=None, results=None, *args, **kwargs): <NEW_LINE> <INDENT> self._cursor = None <NEW_LINE> self._sort_ascending = None <NEW_LINE> self._sort_by = None <NEW_LINE> self._result_count = None <NEW_LINE> self._results = None <NEW_LINE> self.discriminator = None <NEW_LINE> if cursor is not None: <NEW_LINE> <INDENT> self.cursor = cursor <NEW_LINE> <DEDENT> if sort_ascending is not None: <NEW_LINE> <INDENT> self.sort_ascending = sort_ascending <NEW_LINE> <DEDENT> if sort_by is not None: <NEW_LINE> <INDENT> self.sort_by = sort_by <NEW_LINE> <DEDENT> if result_count is not None: <NEW_LINE> <INDENT> self.result_count = result_count <NEW_LINE> <DEDENT> if results is not None: <NEW_LINE> <INDENT> self.results = results <NEW_LINE> <DEDENT> ListResult.__init__(self, *args, **kwargs) | IpfixCollectorConfigListResult - a model defined in Swagger | 625941bfa934411ee37515dc |
def url_grep(): <NEW_LINE> <INDENT> for page in urls: <NEW_LINE> <INDENT> responce = requests.get(page) <NEW_LINE> result = re.findall(r"/docs/ps/mr\d{2}\S+pdf", responce.text) <NEW_LINE> for i in result: <NEW_LINE> <INDENT> links.add(''.join(i)) | This function will fill the list "links" with direct links on guides.
| 625941bf56ac1b37e626411c |
def __init__(self, lib=None): <NEW_LINE> <INDENT> self._root = TocCategory() <NEW_LINE> self._root.add_primary_titles("TOC", u"שרש") <NEW_LINE> self._path_hash = {} <NEW_LINE> self._library = lib <NEW_LINE> vss = db.vstate.find({}, {"title": 1, "first_section_ref": 1, "flags": 1}) <NEW_LINE> self._vs_lookup = {vs["title"]: { "first_section_ref": vs.get("first_section_ref"), "heComplete": bool(vs.get("flags", {}).get("heComplete", False)), "enComplete": bool(vs.get("flags", {}).get("enComplete", False)), } for vs in vss} <NEW_LINE> for c in CategorySet(sort=[("depth", 1)]): <NEW_LINE> <INDENT> self._add_category(c) <NEW_LINE> <DEDENT> ls = db.links.find({"is_first_comment": True}, {"first_comment_indexes":1, "first_comment_section_ref":1}) <NEW_LINE> self._first_comment_lookup = {frozenset(l["first_comment_indexes"]): l["first_comment_section_ref"] for l in ls} <NEW_LINE> indx_set = self._library.all_index_records() if self._library else text.IndexSet() <NEW_LINE> for i in indx_set: <NEW_LINE> <INDENT> node = self._make_index_node(i) <NEW_LINE> cat = self.lookup(i.categories) <NEW_LINE> if not cat: <NEW_LINE> <INDENT> logger.warning(u"Failed to find category for {}".format(i.categories)) <NEW_LINE> continue <NEW_LINE> <DEDENT> cat.append(node) <NEW_LINE> vs = self._vs_lookup[i.title] <NEW_LINE> for field in ("enComplete", "heComplete"): <NEW_LINE> <INDENT> for acat in [cat] + list(reversed(cat.ancestors())): <NEW_LINE> <INDENT> flag = False if not vs[field] else getattr(acat, field, True) <NEW_LINE> setattr(acat, field, flag) <NEW_LINE> if acat.get_primary_title() == u"Commentary": <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self._path_hash[tuple(i.categories + [i.title])] = node <NEW_LINE> <DEDENT> self._sort() | :param lib: Library object, in the process of being created | 625941bfadb09d7d5db6c6da |
def _get_xlsx(obj, auto): <NEW_LINE> <INDENT> col_widths: Dict[Any, float] = defaultdict(float) <NEW_LINE> col = 'A' <NEW_LINE> workbook = openpyxl.Workbook() <NEW_LINE> worksheet = workbook.active <NEW_LINE> for row, data in enumerate(_tabulate(obj, auto=auto), start=1): <NEW_LINE> <INDENT> for col_idx, value in enumerate(data, start=1): <NEW_LINE> <INDENT> cell = worksheet.cell(column=col_idx, row=row) <NEW_LINE> alignment = openpyxl.styles.Alignment( vertical='top', horizontal='left', wrap_text=True ) <NEW_LINE> cell.alignment = alignment <NEW_LINE> if row == 1: <NEW_LINE> <INDENT> cell.font = openpyxl.styles.Font(bold=True) <NEW_LINE> <DEDENT> if isinstance(value, (int, float, datetime.datetime)): <NEW_LINE> <INDENT> cell.value = value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cell.value = str(value) <NEW_LINE> <DEDENT> col_widths[col_idx] = max(col_widths[col_idx], _width(str(value))) <NEW_LINE> <DEDENT> <DEDENT> col_letter = openpyxl.utils.get_column_letter(len(col_widths)) <NEW_LINE> worksheet.auto_filter.ref = "A1:%s1" % col_letter <NEW_LINE> for col in col_widths: <NEW_LINE> <INDENT> if col_widths[col] > XLSX_MAX_WIDTH: <NEW_LINE> <INDENT> width = XLSX_MAX_WIDTH <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> width = col_widths[col] + XLSX_FILTER_PADDING <NEW_LINE> <DEDENT> col_letter = openpyxl.utils.get_column_letter(col) <NEW_LINE> worksheet.column_dimensions[col_letter].width = width <NEW_LINE> <DEDENT> worksheet.freeze_panes = worksheet.cell(row=2, column=1) <NEW_LINE> return workbook | Create an XLSX workbook object.
:param obj: Item, list of Items, or Document to export
:param auto: include placeholders for new items on import
:return: new workbook | 625941bfbe383301e01b53d4 |
def supprDirichletConditions(vector): <NEW_LINE> <INDENT> return vector[1:-1] | Requires:
--------
* vector is a np.array 2D of size (n, 1)
Returns:
--------
* newVector is a np.array 2D of size (n-2, 1) | 625941bfbde94217f3682d3c |
def _is_json_response(self, response): <NEW_LINE> <INDENT> ct_options, _ = response.get_headers().iget('X-Content-Type-Options', '') <NEW_LINE> content_type, _ = response.get_headers().iget('Content-Type', '') <NEW_LINE> if 'application/json' in content_type and 'nosniff' in ct_options: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | This is something I've seen in as a false positive during my
assessments and is better explained in this stackoverflow question
https://goo.gl/BgXVJY | 625941bf99fddb7c1c9de2db |
def export2pdf(self, path=None, tex_file_path=None): <NEW_LINE> <INDENT> if not tex_file_path: <NEW_LINE> <INDENT> tex_file_path = self.export2tex(path) <NEW_LINE> <DEDENT> pdf_file_path = '{}.pdf'.format(tex_file_path[:-3]) <NEW_LINE> command = 'pdflatex {}'.format(tex_file_path) <NEW_LINE> subprocess.check_call(command) <NEW_LINE> return pdf_file_path | Exports to pdf and returns the file_path
| 625941bfb7558d58953c4e61 |
def remember_me(context, request, info, *args, **kw): <NEW_LINE> <INDENT> log.debug('remember_me(%s)' % locals()) <NEW_LINE> log.debug('request.params = %r' % request.params) <NEW_LINE> endpoint = request.params['openid.op_endpoint'] <NEW_LINE> if endpoint != request.registry.settings['openid.provider']: <NEW_LINE> <INDENT> log.warn('Invalid OpenID provider: %s' % endpoint) <NEW_LINE> request.session.flash('Invalid OpenID provider. You can only use: %s' % request.registry.settings['openid.provider']) <NEW_LINE> return HTTPFound(location=request.route_url('home')) <NEW_LINE> <DEDENT> username = unicode(info['identity_url'].split('http://')[1].split('.')[0]) <NEW_LINE> log.info('%s successfully logged in' % username) <NEW_LINE> log.debug('groups = %s' % info['groups']) <NEW_LINE> db = request.db <NEW_LINE> user = db.query(User).filter_by(name=username).first() <NEW_LINE> if not user: <NEW_LINE> <INDENT> user = User(name=username) <NEW_LINE> db.add(user) <NEW_LINE> db.flush() <NEW_LINE> <DEDENT> for group_name in info['groups']: <NEW_LINE> <INDENT> group = db.query(Group).filter_by(name=group_name).first() <NEW_LINE> if not group: <NEW_LINE> <INDENT> group = Group(name=group_name) <NEW_LINE> db.add(group) <NEW_LINE> db.flush() <NEW_LINE> <DEDENT> if group not in user.groups: <NEW_LINE> <INDENT> log.info('Adding %s to %s group', user.name, group.name) <NEW_LINE> user.groups.append(group) <NEW_LINE> <DEDENT> <DEDENT> for group in user.groups: <NEW_LINE> <INDENT> if group.name not in info['groups']: <NEW_LINE> <INDENT> log.info('Removing %s from %s group', user.name, group.name) <NEW_LINE> user.groups.remove(group) <NEW_LINE> <DEDENT> <DEDENT> headers = remember(request, username) <NEW_LINE> came_from = request.session['came_from'] <NEW_LINE> del(request.session['came_from']) <NEW_LINE> if not came_from.startswith(request.host_url): <NEW_LINE> <INDENT> came_from = '/' <NEW_LINE> <DEDENT> response = HTTPFound(location=came_from) <NEW_LINE> response.headerlist.extend(headers) <NEW_LINE> return response | Called upon successful login | 625941bfad47b63b2c509ec9 |
def input_fn(filenames, num_epochs=None, shuffle=True, skip_header_lines=0, batch_size=200): <NEW_LINE> <INDENT> global data_p <NEW_LINE> filename_queue = tf.train.string_input_producer( filenames, num_epochs=num_epochs, shuffle=shuffle) <NEW_LINE> reader = tf.TextLineReader(skip_header_lines=skip_header_lines) <NEW_LINE> _, rows = reader.read_up_to(filename_queue, num_records=batch_size) <NEW_LINE> features = parse_csv(rows) <NEW_LINE> if shuffle: <NEW_LINE> <INDENT> features = tf.train.shuffle_batch( features, batch_size, min_after_dequeue=2 * batch_size + 1, capacity=batch_size * 10, num_threads=multiprocessing.cpu_count(), enqueue_many=True, allow_smaller_final_batch=True ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> features = tf.train.batch( features, batch_size, capacity=batch_size * 10, num_threads=multiprocessing.cpu_count(), enqueue_many=True, allow_smaller_final_batch=True ) <NEW_LINE> <DEDENT> return features, features.pop(data_p.LABEL_COLUMN) | Generates an input function for training or evaluation.
This uses the input pipeline based approach using file name queue
to read data so that entire data is not loaded in memory.
Args:
filenames: [str] list of CSV files to read data from.
num_epochs: int how many times through to read the data.
If None will loop through data indefinitely
shuffle: bool, whether or not to randomize the order of data.
Controls randomization of both file order and line order within
files.
skip_header_lines: int set to non-zero in order to skip header lines
in CSV files.
batch_size: int First dimension size of the Tensors returned by
input_fn
Returns:
A function () -> (features, indices) where features is a dictionary of
Tensors, and indices is a single Tensor of label indices. | 625941bf1b99ca400220a9f9 |
def get_buffet_input(self, message, markup): <NEW_LINE> <INDENT> db.set_state(message.chat.id, State.BUFFETS.value) <NEW_LINE> self.bot.send_photo(message.chat.id, open('images/other/miet.jpg', 'rb'), caption="Схема расположения корпусов «МИЭТ»", reply_markup=markup) <NEW_LINE> markup = types.ReplyKeyboardMarkup() <NEW_LINE> item_1 = types.KeyboardButton('1') <NEW_LINE> item_2 = types.KeyboardButton('2') <NEW_LINE> item_3 = types.KeyboardButton('3') <NEW_LINE> item_4 = types.KeyboardButton('4') <NEW_LINE> item_5 = types.KeyboardButton('5') <NEW_LINE> markup.row(item_1, item_2, item_3, item_4, item_5) <NEW_LINE> self.bot.send_message(message.chat.id, func.message_wrapper({ 'headline': 'Поиск столовой или буфета', 'text': 'Выберите номер корпуса, в котором Вы находитесь сейчас или поблизости:'}), reply_markup=markup, parse_mode="HTML") | Возвращаем сообщение с просьбой о вводе корпуса, в котором он сейчас находится | 625941bf1b99ca400220a9fa |
def batch_generator(X, labels, batch_size, steps_per_epoch, scores, rng, dk): <NEW_LINE> <INDENT> number_of_batches = steps_per_epoch <NEW_LINE> rng = np.random.RandomState(rng.randint(MAX_INT, size = 1)) <NEW_LINE> counter = 0 <NEW_LINE> while 1: <NEW_LINE> <INDENT> X1, X2, X3 = tripletBatchGeneration(X, batch_size, rng, scores, dk) <NEW_LINE> counter += 1 <NEW_LINE> yield([np.array(X1), np.array(X2), np.array(X3)], None) <NEW_LINE> if (counter > number_of_batches): <NEW_LINE> <INDENT> counter = 0 | batch generator
| 625941bf379a373c97cfaa8c |
def test_AlphaEqualThreeWithoutMixing(self): <NEW_LINE> <INDENT> W = [1]*4+[4]*3+[16]*3 <NEW_LINE> L = dvl(W) <NEW_LINE> self.assertEqual(sorted(L),[2]*3+[4]*3+[6]*4) | Alpha Equal Three with no Mixing. | 625941bff8510a7c17cf9644 |
def __init__(self, stream): <NEW_LINE> <INDENT> self.stream = stream | Construct a parser with the given stream.
The stream is expected to contain the output of the command:
xinput --list --long | 625941bf3c8af77a43ae36e7 |
def unset_event_handler(self, event_name, handler_id): <NEW_LINE> <INDENT> self.tab.evaljs(u"{element}['on' + {event_name}] = null".format( element=self.element_js, event_name=escape_js(event_name), )) <NEW_LINE> self.event_handlers_storage.remove(handler_id) | Remove on-event type event listeners from the element | 625941bfeab8aa0e5d26daa0 |
def add_hours(minutes_list): <NEW_LINE> <INDENT> hours_progress = [] <NEW_LINE> total = 0 <NEW_LINE> for minutes in minutes_list: <NEW_LINE> <INDENT> total += minutes / 60 <NEW_LINE> hours_progress.append(total) <NEW_LINE> <DEDENT> return hours_progress | Take a list of minutes and convert it into cumulative list of hours | 625941bfc4546d3d9de7297a |
def load_data(): <NEW_LINE> <INDENT> return bson.json_util.loads(open(FILE_LOCATION).read()) | Load Data From JSON File
:return: List representation of local "popularity" data
:rtype: List | 625941bf4f6381625f114986 |
def _get_arg_parser(): <NEW_LINE> <INDENT> desc = "Ramrod Updater v{0}: Updates STIX and CybOX documents." <NEW_LINE> desc = desc.format(ramrod.__version__) <NEW_LINE> parser = argparse.ArgumentParser(description=desc) <NEW_LINE> parser.add_argument( "--infile", default=None, required=True, help="Input STIX/CybOX document filename." ) <NEW_LINE> parser.add_argument( "--outfile", default=None, help="Output XML document filename. Prints to stdout if no filename is " "provided." ) <NEW_LINE> parser.add_argument( "--from", default=None, dest="from_", metavar="VERSION IN", help="The version of the input document. If not supplied, RAMROD will " "try to determine the version of the input document." ) <NEW_LINE> parser.add_argument( "--to", default=None, dest="to_", metavar="VERSION OUT", help="Update document to this version. If no version is supplied, the " "document will be updated to the latest version." ) <NEW_LINE> parser.add_argument( "--disable-vocab-update", action="store_true", default=False, help="Controlled vocabulary strings will not be updated." ) <NEW_LINE> parser.add_argument( "--disable-remove-optionals", action="store_true", default=False, help="Do not remove empty elements and attributes which were required " "in previous language versions but became optional in later " "releases." ) <NEW_LINE> parser.add_argument( "-f", "--force", action="store_true", default=False, help="Removes untranslatable fields, remaps non-unique IDs, and " "attempts to force the update process." ) <NEW_LINE> return parser | Returns an ArgumentParser instance for this script. | 625941bfe76e3b2f99f3a759 |
def build_stockholm_from_clustal_alig(clustal_file, alif_file): <NEW_LINE> <INDENT> ml.debug(fname()) <NEW_LINE> with open(clustal_file, 'r') as cf, open(alif_file, 'r') as af: <NEW_LINE> <INDENT> clust = AlignIO.read(cf, format='clustal') <NEW_LINE> temp = StringIO() <NEW_LINE> AlignIO.write(clust, temp, format='stockholm') <NEW_LINE> temp.seek(0) <NEW_LINE> st_alig = stockholm_read(temp) <NEW_LINE> for i, alif in enumerate(parse_seq_str(af)): <NEW_LINE> <INDENT> alifold_structure = alif.letter_annotations['ss0'] <NEW_LINE> st_alig.column_annotations['SS_cons'] = alifold_structure <NEW_LINE> if i == 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> st_fd, st_file = mkstemp(prefix='rba_', suffix='_15', dir=CONFIG.tmpdir) <NEW_LINE> with os.fdopen(st_fd, 'w') as sf: <NEW_LINE> <INDENT> st_alig.write_stockholm(sf) <NEW_LINE> return st_file | build stockholm alignment
:return: | 625941bf5fdd1c0f98dc017b |
def __init__(self, conf, channel, topic, **kwargs): <NEW_LINE> <INDENT> options = {'durable': conf.rabbit_durable_queues, 'auto_delete': False, 'exclusive': False} <NEW_LINE> options.update(kwargs) <NEW_LINE> exchange_name = rpc_amqp.get_control_exchange(conf) <NEW_LINE> super(TopicPublisher, self).__init__(channel, exchange_name, topic, type='topic', **options) | init a 'topic' publisher.
Kombu options may be passed as keyword args to override defaults | 625941bf5f7d997b871749de |
def mean_NFI(srcid, source = "all", unit="hours"): <NEW_LINE> <INDENT> unitDict = {"seconds":1, "minutes":60, "hours":3600, "days":86400} <NEW_LINE> if(type(source) == str): <NEW_LINE> <INDENT> if(source.lower() == "all"): <NEW_LINE> <INDENT> dt = srcid.sort_index() <NEW_LINE> NFIlst = pd.Series([(dt.index[i+1] - (dt.index[i] + dt['len'][i])).total_seconds()/unitDict[unit] for i in range(len(dt.index)+1) if(i < len(dt.index)-1)]) <NEW_LINE> return NFIlst.mean() <NEW_LINE> <DEDENT> elif(source.lower() == "air"): <NEW_LINE> <INDENT> dt = srcid.loc[(srcid.srcID > 0) & (srcid.srcID < 2.), :] <NEW_LINE> dt.sort_index() <NEW_LINE> NFIlst = pd.Series([(dt.index[i+1] - (dt.index[i] + dt['len'][i])).total_seconds()/unitDict[unit] for i in range(len(dt.index)+1) if(i < len(dt.index)-1)]) <NEW_LINE> return NFIlst.mean() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> dt = srcid.loc[srcid.srcID.isin(source), :] <NEW_LINE> dt.sort_index() <NEW_LINE> NFIlst = pd.Series([(dt.index[i+1] - (dt.index[i] + dt['len'][i])).total_seconds()/unitDict[unit] for i in range(len(dt.index)+1) if(i < len(dt.index)-1)]) <NEW_LINE> return NFIlst.mean() | Returns the average NFI for selected source type.
Parameters
----------
srcid: pandas dataframe representing NPS NSNSD srcid file, formatted by soundDB library.
source: str or list of floats, optional. Which subset of srcid codes to summarize - choose either "all", "air", or specify a list of srcID codes as float. Defaults to "all" if unspecified.
unit: str, a value that indicates the units desired for the output value. Defaults to "hours".
Returns
-------
numpy.float64 | 625941bf5166f23b2e1a50a2 |
def resolve_rrsets(fqdn, rdtypes): <NEW_LINE> <INDENT> assert rdtypes, "rdtypes must not be empty" <NEW_LINE> if not isinstance(fqdn, DNSName): <NEW_LINE> <INDENT> fqdn = DNSName(fqdn) <NEW_LINE> <DEDENT> fqdn = fqdn.make_absolute() <NEW_LINE> rrsets = [] <NEW_LINE> for rdtype in rdtypes: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> answer = resolve(fqdn, rdtype) <NEW_LINE> logger.debug('found %d %s records for %s: %s', len(answer), rdtype, fqdn, ' '.join(str(rr) for rr in answer)) <NEW_LINE> rrsets.append(answer.rrset) <NEW_LINE> <DEDENT> except dns.resolver.NXDOMAIN as ex: <NEW_LINE> <INDENT> logger.debug('%s', ex) <NEW_LINE> break <NEW_LINE> <DEDENT> except dns.resolver.NoAnswer as ex: <NEW_LINE> <INDENT> logger.debug('%s', ex) <NEW_LINE> <DEDENT> except dns.exception.DNSException as ex: <NEW_LINE> <INDENT> logger.error('DNS query for %s %s failed: %s', fqdn, rdtype, ex) <NEW_LINE> raise <NEW_LINE> <DEDENT> <DEDENT> return rrsets | Get Resource Record sets for given FQDN.
CNAME chain is followed during resolution
but CNAMEs are not returned in the resulting rrset.
:returns:
set of dns.rrset.RRset objects, can be empty
if the FQDN does not exist or if none of rrtypes exist | 625941bf66673b3332b91fda |
def evaluer(self, ancien_plateau, nouveau_plateau, joueur): <NEW_LINE> <INDENT> if joueur == 1: <NEW_LINE> <INDENT> result = (nouveau_plateau[13] - ancien_plateau[13])- (nouveau_plateau[6] - ancien_plateau[6]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = (nouveau_plateau[6] - ancien_plateau[6])- (nouveau_plateau[13] - ancien_plateau[13]) <NEW_LINE> <DEDENT> return result | Evaluation des scores entre deux plateau différents
:param ancien_plateau: ancien plateau
:param nouveau_plateau: nouveau plateau
:param joueur: joueur qui vient de jouer
:return result: score | 625941bf91f36d47f21ac439 |
def regimes_before(regime): <NEW_LINE> <INDENT> regimes = [] <NEW_LINE> for key in spectrum_wavelengths: <NEW_LINE> <INDENT> if key[0] == regime or key[1] == regime: break <NEW_LINE> else: regimes.append(key) <NEW_LINE> <DEDENT> return regimes | Thisj function ...
:param regime:
:return: | 625941bf16aa5153ce3623c2 |
def max_subarray_sum_circular(A: List[int]) -> int: <NEW_LINE> <INDENT> max_curr = max_so_far = float("-inf") <NEW_LINE> min_curr = min_so_far = total = 0 <NEW_LINE> for a in A: <NEW_LINE> <INDENT> max_curr = max(max_curr + a, a) <NEW_LINE> max_so_far = max(max_so_far, max_curr) <NEW_LINE> min_curr = min(min_curr + a, a) <NEW_LINE> min_so_far = min(min_so_far, min_curr) <NEW_LINE> total += a <NEW_LINE> <DEDENT> return max(max_so_far, total - min_so_far) if max_so_far > 0 else max_so_far | Time: O(n)
Space: O(1) | 625941bf3317a56b86939ba7 |
def __init__(self, conf): <NEW_LINE> <INDENT> super(QNetwork, self).__init__(conf) <NEW_LINE> with tf.name_scope(self.name): <NEW_LINE> <INDENT> self.target_ph = tf.placeholder('float32', [None], name='target') <NEW_LINE> self.loss = self._build_q_head() <NEW_LINE> self._build_gradient_ops() | Set up remaining layers, loss function, gradient compute and apply
ops, network parameter synchronization ops, and summary ops. | 625941bf56b00c62f0f145a1 |
def get_domain_http_header(self, domain, config=None): <NEW_LINE> <INDENT> return self._send_request( http_methods.GET, '/domain/' + domain + '/config', params={'httpHeader': ''}, config=config) | get http header configuration of a domain
:param domain: the domain name
:type domain: string
:param config: None
:type config: baidubce.BceClientConfiguration
:return:
:rtype: baidubce.bce_response.BceResponse | 625941bfbd1bec0571d90577 |
def imread(self, filename, flags=cv2.IMREAD_COLOR, dtype=np.uint8): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> n = np.fromfile(filename, dtype) <NEW_LINE> img = cv2.imdecode(n, flags) <NEW_LINE> return img <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> return None | OpenCVのimreadが日本語ファイル名が読めない対策 | 625941bf379a373c97cfaa8d |
def sample_user(email='test@rxhe0916.com', password='testpass'): <NEW_LINE> <INDENT> return get_user_model().objects.create_user(email, password) | Create a sample user | 625941bf442bda511e8be365 |
def invitable(self): <NEW_LINE> <INDENT> return self.bloggers().filter( consent_form_received=False ).exclude( user__received_letters__type="consent_form" ) | No invitation letter has been created for them. | 625941bf090684286d50ec2c |
def _y_boxes_to_xbs(boxes, voxel_size, origin) -> "[(x0, x1, y0, y1, z0, z1), ...]": <NEW_LINE> <INDENT> print("BFDS: _y_boxes_to_xbs:", len(boxes)) <NEW_LINE> xbs = list() <NEW_LINE> voxel_size_half = voxel_size / 2. <NEW_LINE> while boxes: <NEW_LINE> <INDENT> ix0, ix1, iy0, iy1, iz0, iz1 = boxes.pop() <NEW_LINE> x0, y0, z0 = ( origin[0] + ix0 * voxel_size - voxel_size_half, origin[1] + iy0 * voxel_size, origin[2] + iz0 * voxel_size - voxel_size_half, ) <NEW_LINE> x1, y1, z1 = ( origin[0] + ix1 * voxel_size + voxel_size_half, origin[1] + iy1 * voxel_size, origin[2] + iz1 * voxel_size + voxel_size_half, ) <NEW_LINE> xbs.append([x0, x1, y0, y1, z0, z1],) <NEW_LINE> <DEDENT> return xbs | Trasform boxes (int coordinates) to xbs (global coordinates). | 625941bf31939e2706e4cdb6 |
def test_019(self): <NEW_LINE> <INDENT> grid = WaldorfGrid(["axy", "xby", "xyc"], 3, 3) <NEW_LINE> result = grid.get_char(0, 0) <NEW_LINE> self.assertEqual("a", result) <NEW_LINE> projection = grid.get_projection(0, 0, 3, Direction.SOUTH_EAST) <NEW_LINE> self.assertEqual("abc", projection) | get_projection south should value given longer valid length | 625941bf50812a4eaa59c26d |
def _index_to_alphabet(index): <NEW_LINE> <INDENT> return chr(ord("A") + index) | Convert the index to the alphabet.
| 625941bf3cc13d1c6d3c72c4 |
def set_dst(self,dst): <NEW_LINE> <INDENT> self.__dst = dst | ! Set destination
@param self this object
@param dst destintion
@return none | 625941bf7b180e01f3dc474b |
def assert_histories_equal(actual_history, expected_history): <NEW_LINE> <INDENT> local_timezone = tz.gettz() <NEW_LINE> assert _detach_timezone_stamp(actual_history) == _detach_timezone_stamp( (expected_history[0].astimezone(local_timezone), expected_history[1]) ) | Assert that two histories are equal, accounting for differing timezones.
Use of any Python standard library timezone-management option, such as:
datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo
instead of a dedicated external library, notably here dateutil.tz, would
result in failures for certain timezones e.g. 'Europe/London' or
'Australia/Melbourne' due to DST effects.
Note that from Python >= 3.9 it is possible to use a built-in module,
zoneinfo (https://docs.python.org/3/library/zoneinfo.html) to achieve
timezone awareness. For earlier versions, an external module must be used. | 625941bf498bea3a759b99f9 |
def test_str(self): <NEW_LINE> <INDENT> for i in range(512): <NEW_LINE> <INDENT> f = flag.Flag(i) <NEW_LINE> self.assertEqual(str(f), str(i)) | Test __str__ | 625941bf44b2445a33931fe0 |
def transform(self,data): <NEW_LINE> <INDENT> data = [i if i in self.vocab.keys() else 'unseen' for i in list(data)] <NEW_LINE> transformed_data = [self.vocab[value] for value in data] <NEW_LINE> return np.array(transformed_data).reshape(-1,1) | This is the transform function of the label encoder. It takes the data to tansform as an argument. For
every value, it looks up in the dictionary to find a match and replace it with its label. If a match
is not found it relaces it with the label for the unseen values. | 625941bfbe7bc26dc91cd54e |
def get_last_block_header(self): <NEW_LINE> <INDENT> return self.raw_jsonrpc_request("get_last_block_header") | Block header information for the most recent block is easily retrieved with this method.
Output:
{
"block_header": {
"block_size": unsigned int; The block size in bytes.
"depth": unsigned int; The number of blocks succeeding this block on the blockchain. A larger number means an older block.
"difficulty" unsigned int; The strength of the Monero network based on mining power.
"hash": str; The hash of this block.
"height": unsigned int; The number of blocks preceding this block on the blockchain.
"major_version": unsigned int; The major version of the monero protocol at this block height.
"minor_version": unsigned int; The minor version of the monero protocol at this block height.
"nonce": unsigned int; a cryptographic random one-time number used in mining a Monero block.
"num_txes": unsigned int; Number of transactions in the block, not counting the coinbase tx.
"orphan_status": bool; Usually false. If true, this block is not part of the longest chain.
"prev_hash": str; The hash of the block immediately preceding this block in the chain.
"reward": unsigned int; The amount of new atomic units generated in this block and rewarded to the miner. Note: 1 XMR = 1e12 atomic units.
"timestamp": unsigned int; The unix time at which the block was recorded into the blockchain.
}
"status": str; General RPC error code. "OK" means everything looks good.
"untrusted": bool; True for bootstrap mode, False for full sync mode
} | 625941bf23849d37ff7b2fda |
def surface_plot(matrix1, matrix2, x_vec, y_vec, **kwargs): <NEW_LINE> <INDENT> (x, y) = np.meshgrid(x_vec, y_vec) <NEW_LINE> fig = plt.figure() <NEW_LINE> ax = fig.add_subplot(111, projection='3d') <NEW_LINE> surf1 = ax.plot_surface(x, y, matrix1, label = 'Approximated Surface', **kwargs) <NEW_LINE> surf2 = ax.plot_surface(x, y, matrix2, label = 'True Surface', **kwargs) <NEW_LINE> return (fig, ax, surf1, surf2) | Function to create 3d plot | 625941bfec188e330fd5a6ed |
def add_card(cards): <NEW_LINE> <INDENT> card_set = prompt.query('Enter card set: ', default='None') <NEW_LINE> card_color = prompt.query('Enter card color: ') <NEW_LINE> card_text = prompt.query('Enter card text: ') <NEW_LINE> card_creator = prompt.query('Enter card creator: ', default='None') <NEW_LINE> cards.create_cards([{'set': card_set, 'color': card_color, 'text': card_text, 'creator': card_creator}]) | Adds card to the database based on user input
Args:
cards (Cards): Cards object to interface with MongoDB
Returns:
None | 625941bfc4546d3d9de7297b |
def swapPairs(self, head): <NEW_LINE> <INDENT> p = dummy = ListNode(0); <NEW_LINE> p.next = head; <NEW_LINE> while p.next != None and p.next.next != None: <NEW_LINE> <INDENT> p.next.next.next, p.next.next, p.next, p = p.next, p.next.next.next, p.next.next, p.next <NEW_LINE> <DEDENT> return dummy.next | :type head: ListNode
:rtype: ListNode | 625941bf15baa723493c3ebd |
def get_current_obs(self): <NEW_LINE> <INDENT> raw_obs = self.get_raw_obs() <NEW_LINE> noisy_obs = self._inject_obs_noise(raw_obs) <NEW_LINE> if self.position_only: <NEW_LINE> <INDENT> return self._filter_position(noisy_obs) <NEW_LINE> <DEDENT> return noisy_obs | This method should not be overwritten. | 625941bf07d97122c41787d0 |
def countAndSay(self, n): <NEW_LINE> <INDENT> result = "1" <NEW_LINE> for _ in range(1, n): <NEW_LINE> <INDENT> result = self.get_result(result) <NEW_LINE> <DEDENT> return result | :type n: int
:rtype: str | 625941bf76e4537e8c3515bb |
def simplify_coord(G): <NEW_LINE> <INDENT> for n in sorted(G.nodes, key=lambda node: node.height): <NEW_LINE> <INDENT> if n.isCoord: <NEW_LINE> <INDENT> newhead = next(iter(sorted(n.coords, key=lambda v: v.name))) <NEW_LINE> maxht = float('-inf') <NEW_LINE> for c in n.coords | n.conjuncts: <NEW_LINE> <INDENT> if c is not newhead: <NEW_LINE> <INDENT> maxht = max(maxht, c.height) <NEW_LINE> newhead.add_child(c) <NEW_LINE> assert c in G.nodes <NEW_LINE> <DEDENT> <DEDENT> for c in n.children: <NEW_LINE> <INDENT> c.parents.remove(n) <NEW_LINE> c.parentedges -= {(p,e) for (p,e) in c.parentedges if p is n} <NEW_LINE> maxht = max(maxht, c.height) <NEW_LINE> newhead.add_child(c) <NEW_LINE> assert c in G.nodes <NEW_LINE> <DEDENT> assert newhead.height==maxht+1,(n,n.height,newhead,newhead.height,maxht,newhead.children) <NEW_LINE> if n.parents: <NEW_LINE> <INDENT> for p in n.parents: <NEW_LINE> <INDENT> p.add_child(newhead) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> assert n in n.frag.roots <NEW_LINE> for v in n.frag.nodes: <NEW_LINE> <INDENT> v.depth = -1 <NEW_LINE> <DEDENT> for v in n.frag.roots: <NEW_LINE> <INDENT> v._setMinDepth(0) <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> assert newhead.depth==n.depth,(n,n.depth,newhead,newhead.depth) <NEW_LINE> <DEDENT> except AssertionError as ex: <NEW_LINE> <INDENT> print(ex, 'There is a legitimate edge case in which this fails: the coordinator is also a member of an FE and so will continue to have greater depth than the coordination node even when it replaces it', file=sys.stderr) <NEW_LINE> <DEDENT> assert newhead in G.nodes <NEW_LINE> n.frag.nodes.remove(n) <NEW_LINE> <DEDENT> <DEDENT> G.nodes -= {n for n in G.nodes if n.isCoord} | Simplify the graph by removing coordination nodes, choosing one of the coordinators as the head. | 625941bfbde94217f3682d3d |
def viewData(self): <NEW_LINE> <INDENT> if self.storage == []: <NEW_LINE> <INDENT> print("NO DATA IN STORAGE\n") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('DISPLAYING STORAGE DATA:') <NEW_LINE> print(self.storage, "\n") | View data in storage. | 625941bfd10714528d5ffc2a |
def test00_fileCopyFileClosed(self): <NEW_LINE> <INDENT> self.h5file.close() <NEW_LINE> h5cfname = tempfile.mktemp(suffix='.h5') <NEW_LINE> try: <NEW_LINE> <INDENT> self.assertRaises(ClosedFileError, self.h5file.copy_file, h5cfname) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> if os.path.exists(h5cfname): <NEW_LINE> <INDENT> os.remove(h5cfname) | Test copying a closed file. | 625941bfde87d2750b85fcda |
def __set__(self, records, value): <NEW_LINE> <INDENT> protected_ids = [] <NEW_LINE> new_ids = [] <NEW_LINE> other_ids = [] <NEW_LINE> for record_id in records._ids: <NEW_LINE> <INDENT> if record_id in records.env._protected.get(self, ()): <NEW_LINE> <INDENT> protected_ids.append(record_id) <NEW_LINE> <DEDENT> elif not record_id: <NEW_LINE> <INDENT> new_ids.append(record_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> other_ids.append(record_id) <NEW_LINE> <DEDENT> <DEDENT> if protected_ids: <NEW_LINE> <INDENT> protected_records = records.browse(protected_ids) <NEW_LINE> self.write(protected_records, value) <NEW_LINE> <DEDENT> if new_ids: <NEW_LINE> <INDENT> new_records = records.browse(new_ids) <NEW_LINE> with records.env.protecting(records.pool.field_computed.get(self, [self]), records): <NEW_LINE> <INDENT> if self.relational: <NEW_LINE> <INDENT> new_records.modified([self.name], before=True) <NEW_LINE> <DEDENT> self.write(new_records, value) <NEW_LINE> new_records.modified([self.name]) <NEW_LINE> <DEDENT> if self.inherited: <NEW_LINE> <INDENT> parents = records[self.related[0]] <NEW_LINE> parents.filtered(lambda r: not r.id)[self.name] = value <NEW_LINE> <DEDENT> <DEDENT> if other_ids: <NEW_LINE> <INDENT> records = records.browse(other_ids) <NEW_LINE> write_value = self.convert_to_write(value, records) <NEW_LINE> records.write({self.name: write_value}) | set the value of field ``self`` on ``records`` | 625941bff7d966606f6a9f4b |
@task <NEW_LINE> def dev(*args): <NEW_LINE> <INDENT> if not args: <NEW_LINE> <INDENT> print('Tips: \n1. `fab dev:hostname1,hostname2,hostname3`' '\n2. `fab dev:all`') <NEW_LINE> return <NEW_LINE> <DEDENT> if args[0] == 'all': <NEW_LINE> <INDENT> env.hosts = ['t-walis-1', 't-walis-2', 't-walis-3', 't-walis-4', 't-walis-test', ] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> env.hosts = args <NEW_LINE> <DEDENT> execute(_walis_deploy) | Deploy dev env.
:param args: host names
:return: | 625941bfe5267d203edcdbe9 |
def filerevancestors(repo, fctxs, followfirst=False): <NEW_LINE> <INDENT> gen = (rev for rev, _cs in filectxancestors(fctxs, followfirst)) <NEW_LINE> return generatorset(gen, iterasc=False, repo=repo) | Like filectx.ancestors(), but can walk from multiple files/revisions,
and includes the given fctxs themselves
Returns a smartset. | 625941bf0fa83653e4656f06 |
def __init__(self, userid, name, desc, contactNumber, alternateNumber, address, landmark, pincode, locationObj, img): <NEW_LINE> <INDENT> self.userid = userid <NEW_LINE> self.name = name <NEW_LINE> self.desc = desc <NEW_LINE> self.contactNumber = contactNumber <NEW_LINE> self.alternateNumber = alternateNumber <NEW_LINE> self.address = address <NEW_LINE> self.landmark = landmark <NEW_LINE> self.pincode = pincode <NEW_LINE> self.location = locationObj <NEW_LINE> self.img = img <NEW_LINE> self.created_date = datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%f') | Return a new Car object. | 625941bf73bcbd0ca4b2bfc0 |
def interassemblage_distance_euclidean(assemblage1freq, assemblage2freq): <NEW_LINE> <INDENT> a1 = np.array(assemblage1freq) <NEW_LINE> a2 = np.array(assemblage2freq) <NEW_LINE> return np.asscalar(np.sqrt(np.dot(a1-a2,a1-a2))) | Efficient calculation of Euclidean distance between two assemblages using Numpy
dot product.
:param assemblage1freq: List of frequencies for assemblage 1
:param assemblage2freq: List of frequencies for assemblage 2
:return: | 625941bf0a366e3fb873e762 |
def do_take_replaces(self): <NEW_LINE> <INDENT> self.take_vi_replaces() | Take keyboard Input Chords to mean replace Chars, till Esc | 625941bf21a7993f00bc7c36 |
def current_price(self, block_identifier: BlockIdentifier) -> TokenAmount: <NEW_LINE> <INDENT> return self.proxy.functions.currentPrice().call(block_identifier=block_identifier) | Gets the currently required deposit amount. | 625941bf3c8af77a43ae36e8 |
def create_table(self): <NEW_LINE> <INDENT> conn = self.create_connection() <NEW_LINE> c = self.create_cursor(conn) <NEW_LINE> try: <NEW_LINE> <INDENT> c.execute('''CREATE TABLE material_properties (material text, band_gap real, color text)''') <NEW_LINE> self.print_or_not(' Table was created successfully.') <NEW_LINE> <DEDENT> except sql.Error as e: <NEW_LINE> <INDENT> print(' An error has occurred while creating the table:', e.args[0]) <NEW_LINE> <DEDENT> return self.close_connection(conn) | Creates table material_properties with three columns.
| 625941bf8da39b475bd64ebb |
def str2bool(self, v): <NEW_LINE> <INDENT> return v.lower() in ("yes", "true", "t", "1") | Converts a string to a bool | 625941bf8c3a873295158301 |
def standardize(s,ty=2): <NEW_LINE> <INDENT> data = s.dropna().copy() <NEW_LINE> if int(ty) == 1: <NEW_LINE> <INDENT> re = (data - data.min()) / (data.max() - data.min()) <NEW_LINE> <DEDENT> elif ty == 2: <NEW_LINE> <INDENT> re = (data - data.mean()) / data.std() <NEW_LINE> <DEDENT> elif ty == 3: <NEW_LINE> <INDENT> re = data / 10 ** np.ceil(np.log10(data.abs().max())) <NEW_LINE> <DEDENT> return re | 标准化函数
s为Series数据
ty为标准化类型:1 MinMax,2 Standard,3 maxabs | 625941bf925a0f43d2549dbf |
def __init__(self, request_data, old_settings=None, custom_base_path=None): <NEW_LINE> <INDENT> self.__request_data = request_data <NEW_LINE> self.__settings = OneLogin_Saml2_Settings(old_settings, custom_base_path) <NEW_LINE> self.__attributes = [] <NEW_LINE> self.__nameid = None <NEW_LINE> self.__session_index = None <NEW_LINE> self.__session_expiration = None <NEW_LINE> self.__authenticated = False <NEW_LINE> self.__errors = [] <NEW_LINE> self.__error_reason = None <NEW_LINE> self.__last_request_id = None | Initializes the SP SAML instance.
:param request_data: Request Data
:type request_data: dict
:param settings: Optional. SAML Toolkit Settings
:type settings: dict|object
:param custom_base_path: Optional. Path where are stored the settings file and the cert folder
:type custom_base_path: string | 625941bffb3f5b602dac35db |
def p_adicionales(p): <NEW_LINE> <INDENT> pass | adicionales : size
| rindex
| sublist
| contains | 625941bfb57a9660fec337cc |
def test_empty(self): <NEW_LINE> <INDENT> builtIns = CompilerBuiltIns([], None) <NEW_LINE> self.assertEqual(len(builtIns.include_paths), 0) <NEW_LINE> self.assertEqual(len(builtIns.defines), 0) <NEW_LINE> self.assertEqual(builtIns.compiler, None) <NEW_LINE> self.assertEqual(builtIns.std, None) <NEW_LINE> self.assertEqual(builtIns.language, None) | Test empty. | 625941bf82261d6c526ab3e6 |
def can_manage_comment_aliases(self): <NEW_LINE> <INDENT> return | Tests if this user can manage ``Id`` aliases for ``Comnents``.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known changing an alias
will result in a ``PermissionDenied``. This is intended as a
hint to an application that may opt not to offer alias
operations to an unauthorized user.
:return: ``false`` if ``Comment`` aliasing is not authorized, ``true`` otherwise
:rtype: ``boolean``
*compliance: mandatory -- This method must be implemented.* | 625941bf8c3a873295158302 |
def calculate_angle(self): <NEW_LINE> <INDENT> face_a, face_b = self.main_faces <NEW_LINE> if face_a.normal.length_squared == 0 or face_b.normal.length_squared == 0: <NEW_LINE> <INDENT> self.angle = -3 <NEW_LINE> return <NEW_LINE> <DEDENT> a_is_clockwise = ((face_a.vertices.index(self.va) - face_a.vertices.index(self.vb)) % len(face_a.vertices) == 1) <NEW_LINE> b_is_clockwise = ((face_b.vertices.index(self.va) - face_b.vertices.index(self.vb)) % len(face_b.vertices) == 1) <NEW_LINE> is_equal_flip = True <NEW_LINE> if face_a.uvface and face_b.uvface: <NEW_LINE> <INDENT> a_is_clockwise ^= face_a.uvface.flipped <NEW_LINE> b_is_clockwise ^= face_b.uvface.flipped <NEW_LINE> is_equal_flip = (face_a.uvface.flipped == face_b.uvface.flipped) <NEW_LINE> <DEDENT> if a_is_clockwise != b_is_clockwise: <NEW_LINE> <INDENT> if (a_is_clockwise == (face_b.normal.cross(face_a.normal).dot(self.vector) > 0)) == is_equal_flip: <NEW_LINE> <INDENT> self.angle = face_a.normal.angle(face_b.normal) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.angle = -face_a.normal.angle(face_b.normal) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.angle = face_a.normal.angle(-face_b.normal) | Calculate the angle between the main faces | 625941bf07f4c71912b113cb |
def set_min_noutput_items(self, *args, **kwargs): <NEW_LINE> <INDENT> return _filter_swig.pfb_arb_resampler_fff_sptr_set_min_noutput_items(self, *args, **kwargs) | set_min_noutput_items(pfb_arb_resampler_fff_sptr self, int m) | 625941bf566aa707497f44b7 |
def set_request_token_user(self, key, userid): <NEW_LINE> <INDENT> token = self.get_request_token(key) <NEW_LINE> if not token: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> token.userid = userid <NEW_LINE> if not token.verifier: <NEW_LINE> <INDENT> token.generate_verifier() <NEW_LINE> <DEDENT> self.DBSession.flush() <NEW_LINE> return token | Register the user id for this token and also generate a verification
code. | 625941bf8e71fb1e9831d6f4 |
def getHint1(secret,guess): <NEW_LINE> <INDENT> s,g=Counter(secret),Counter(guess) <NEW_LINE> bull = sum(i == j for i,j in zip(secret,guess)) <NEW_LINE> cow = sum((s & g).values()) - bull <NEW_LINE> return '%sA%sB' %(bull,cow) | use Counter to count guess and secret and sum their overlap.
use zip to counter bulls | 625941bf76d4e153a657ea7a |
def get_object(self): <NEW_LINE> <INDENT> user = User.objects.get( pk=self.kwargs.get('student_pk', '') ) <NEW_LINE> grade = Grade.objects.get( student=user ) <NEW_LINE> return grade | Get student grade. | 625941bf442bda511e8be366 |
def __init__(self): <NEW_LINE> <INDENT> self.swaggerTypes = { 'EmfPlusDualRenderingMode': 'str', 'RenderingMode': 'str', 'UseEmfEmbeddedToWmf': 'bool' } <NEW_LINE> self.attributeMap = { 'EmfPlusDualRenderingMode': 'EmfPlusDualRenderingMode','RenderingMode': 'RenderingMode','UseEmfEmbeddedToWmf': 'UseEmfEmbeddedToWmf'} <NEW_LINE> self.EmfPlusDualRenderingMode = None <NEW_LINE> self.RenderingMode = None <NEW_LINE> self.UseEmfEmbeddedToWmf = None | Attributes:
swaggerTypes (dict): The key is attribute name and the value is attribute type.
attributeMap (dict): The key is attribute name and the value is json key in definition. | 625941bf99fddb7c1c9de2dc |
def base_exception_handler(*args): <NEW_LINE> <INDENT> header, frames, trcback = format_report(*extract_exception(*args)) <NEW_LINE> LOGGER.error("!> {0}".format(Constants.logging_separators)) <NEW_LINE> map(lambda x: LOGGER.error("!> {0}".format(x)), header) <NEW_LINE> LOGGER.error("!> {0}".format(Constants.logging_separators)) <NEW_LINE> map(lambda x: LOGGER.error("!> {0}".format(x)), frames) <NEW_LINE> LOGGER.error("!> {0}".format(Constants.logging_separators)) <NEW_LINE> sys.stderr.write("\n".join(trcback)) <NEW_LINE> return True | Provides the base exception handler.
:param \*args: Arguments.
:type \*args: \*
:return: Definition success.
:rtype: bool | 625941bf32920d7e50b28118 |
def _load_nav_graphs(self): <NEW_LINE> <INDENT> print('Loading navigation graphs for %d scans' % len(self.scans)) <NEW_LINE> self.graphs = load_nav_graphs(self.scans) <NEW_LINE> self.paths = {} <NEW_LINE> for scan, G in self.graphs.items(): <NEW_LINE> <INDENT> self.paths[scan] = dict(nx.all_pairs_dijkstra_path(G)) <NEW_LINE> <DEDENT> self.distances = {} <NEW_LINE> for scan, G in self.graphs.items(): <NEW_LINE> <INDENT> self.distances[scan] = dict(nx.all_pairs_dijkstra_path_length(G)) | load graph from self.scan,
Store the graph {scan_id: graph} in self.graphs
Store the shortest path {scan_id: {view_id_x: {view_id_y: [path]} } } in self.paths
Store the distances in self.distances. (Structure see above)
Load connectivity graph for each scan, useful for reasoning about shortest paths
:return: None | 625941bfd164cc6175782c98 |
def __init__(self, dmavendors=None): <NEW_LINE> <INDENT> self._dmavendors = None <NEW_LINE> self.discriminator = None <NEW_LINE> if dmavendors is not None: <NEW_LINE> <INDENT> self.dmavendors = dmavendors | NdmpSettingsDmas - a model defined in Swagger | 625941bfb545ff76a8913d60 |
def get_scrobbler(self, client_id, client_version): <NEW_LINE> <INDENT> return Scrobbler(self, client_id, client_version) | Returns a Scrobbler object used for submitting tracks to the server
Quote from http://www.last.fm/api/submissions:
========
Client identifiers are used to provide a centrally managed database of
the client versions, allowing clients to be banned if they are found to
be behaving undesirably. The client ID is associated with a version
number on the server, however these are only incremented if a client is
banned and do not have to reflect the version of the actual client application.
During development, clients which have not been allocated an identifier should
use the identifier tst, with a version number of 1.0. Do not distribute code or
client implementations which use this test identifier. Do not use the identifiers
used by other clients.
=========
To obtain a new client identifier please contact:
* Last.fm: submissions@last.fm
* # TODO: list others
...and provide us with the name of your client and its homepage address. | 625941bf0a50d4780f666dda |
def _format_download_uri(etextno, mirror): <NEW_LINE> <INDENT> uri_root = (mirror or _GUTENBERG_MIRROR).strip().rstrip('/') <NEW_LINE> _check_mirror_exists(uri_root) <NEW_LINE> extensions = ('.txt', '-8.txt', '-0.txt') <NEW_LINE> for extension in extensions: <NEW_LINE> <INDENT> path = _etextno_to_uri_subdirectory(etextno) <NEW_LINE> uri = '{root}/{path}/{etextno}{extension}'.format( root=uri_root, path=path, etextno=etextno, extension=extension) <NEW_LINE> response = requests.head(uri) <NEW_LINE> if response.ok: <NEW_LINE> <INDENT> return uri <NEW_LINE> <DEDENT> <DEDENT> raise Exception('Failed to find {0} on {1}.' .format(etextno, uri_root)) | Returns the download location on the Project Gutenberg servers for a
given text.
Raises:
UnknownDownloadUri: If no download location can be found for the text. | 625941bf23e79379d52ee4b0 |
def averageOfLevels(self, root): <NEW_LINE> <INDENT> q = deque() <NEW_LINE> if root: <NEW_LINE> <INDENT> q.append((root, 0)) <NEW_LINE> <DEDENT> m = defaultdict(list) <NEW_LINE> max_level = 0 <NEW_LINE> while q: <NEW_LINE> <INDENT> node, level = q.popleft() <NEW_LINE> if node: <NEW_LINE> <INDENT> m[level].append(node.val) <NEW_LINE> max_level = max(max_level, level) <NEW_LINE> if node.left: <NEW_LINE> <INDENT> q.append((node.left, level + 1)) <NEW_LINE> <DEDENT> if node.right: <NEW_LINE> <INDENT> q.append((node.right, level + 1)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> answer = [] <NEW_LINE> for i in range(max_level + 1): <NEW_LINE> <INDENT> answer.append(sum(m[i]) / float(len(m[i]))) <NEW_LINE> <DEDENT> return answer | :type root: TreeNode
:rtype: List[float] | 625941bf046cf37aa974cc94 |
def prepare(data): <NEW_LINE> <INDENT> return (data[0].astype(np.float32).reshape([-1, 784]) / 255.0, data[1].astype(np.int32)) | Cast to float, normalize and reshape
from 28x28 2D images to a vector of 784 | 625941bf9c8ee82313fbb6bf |
def _repr_(self): <NEW_LINE> <INDENT> return ('Semimonomial transformation group over %s'%self.base_ring() + ' of degree %s'%self.degree()) | Returns a string describing ``self``.
EXAMPLES::
sage: F.<a> = GF(4)
sage: SemimonomialTransformationGroup(F, 3) # indirect doctest
Semimonomial transformation group over Finite Field in a of size 2^2 of degree 3 | 625941bf66673b3332b91fdb |
def __init__(self, dct): <NEW_LINE> <INDENT> for k in self.__slots__: <NEW_LINE> <INDENT> v = dct.get(k, None) <NEW_LINE> if k in {"train_root", "val_root", "trainval_root"}: <NEW_LINE> <INDENT> v = Path(v) <NEW_LINE> <DEDENT> setattr(self, k, v) | :param dct: | 625941bf460517430c3940d5 |
def sum_hand_points(self): <NEW_LINE> <INDENT> self.hand_points = 0 <NEW_LINE> for card in self.cards_in_hand: <NEW_LINE> <INDENT> self.hand_points += card_to_value(card) | Calculates the sum of point in a hand
| 625941bfbe8e80087fb20b91 |
def __init__(self, integ_br, root_helper, polling_interval): <NEW_LINE> <INDENT> self.int_br = ovs_lib.OVSBridge(integ_br, root_helper) <NEW_LINE> self.polling_interval = polling_interval <NEW_LINE> self.cur_ports = [] <NEW_LINE> self.datapath_id = "0x%s" % self.int_br.get_datapath_id() <NEW_LINE> self.agent_state = { 'binary': 'neutron-nec-agent', 'host': config.CONF.host, 'topic': q_const.L2_AGENT_TOPIC, 'configurations': {}, 'agent_type': q_const.AGENT_TYPE_NEC, 'start_flag': True} <NEW_LINE> self.setup_rpc() | Constructor.
:param integ_br: name of the integration bridge.
:param root_helper: utility to use when running shell cmds.
:param polling_interval: interval (secs) to check the bridge. | 625941bf63f4b57ef0001069 |
def test_api_v1_template_programmer_project_project_id_delete(self): <NEW_LINE> <INDENT> pass | Test case for api_v1_template_programmer_project_project_id_delete
Deletes the project # noqa: E501 | 625941bf711fe17d825422bb |
def get_quota_work_hours(year, month, hours_per_day): <NEW_LINE> <INDENT> return get_number_of_work_days(year, month) * hours_per_day | Return quota hours for given year and month - enter work hours_per_day. | 625941bf7047854f462a1357 |
def test_get_allowed_origins_with_substitute(self): <NEW_LINE> <INDENT> apt_pkg.config.clear("Unattended-Upgrade::Allowed-Origins") <NEW_LINE> apt_pkg.config.set("Unattended-Upgrade::Allowed-Origins::", "${distro_id} ${distro_codename}-security") <NEW_LINE> li = get_allowed_origins() <NEW_LINE> self.assertTrue(("o=MyDistroID,a=nacked-security") in li) | test if substitute for get_allowed_origins works | 625941bfa219f33f346288b7 |
def size(self, taxonomy=None): <NEW_LINE> <INDENT> size = 0 <NEW_LINE> for field in self.fields: <NEW_LINE> <INDENT> size = size + field.size(taxonomy) <NEW_LINE> <DEDENT> return size | Compute the size for the fields in the message. | 625941bfbe383301e01b53d6 |
def filtrarPeliculaPorActor(self): <NEW_LINE> <INDENT> self.ui.peliculaImagenLabel.setPixmap(QtGui.QPixmap("")) <NEW_LINE> self.ui.tramaPLabel.clear() <NEW_LINE> index = self.ui.buscarPActorComboBox.currentIndex() <NEW_LINE> if (index != 0): <NEW_LINE> <INDENT> nombre = self.ui.buscarPActorComboBox.itemText(index) <NEW_LINE> actor = controller.obtenerActor(nombre) <NEW_LINE> peliculas = controller.peliculasDelActor(actor.id_actor) <NEW_LINE> peliculasAFiltrar = "" <NEW_LINE> if peliculas is not None: <NEW_LINE> <INDENT> for i, data in enumerate(peliculas): <NEW_LINE> <INDENT> row = data[0] <NEW_LINE> if i == len(peliculas) - 1: <NEW_LINE> <INDENT> peliculasAFiltrar += row[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> peliculasAFiltrar += row[1] + "|" <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if peliculasAFiltrar is "": <NEW_LINE> <INDENT> peliculasAFiltrar = u"@~@" <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.proxyModelMovie.setFilterKeyColumn(0) <NEW_LINE> peliculasAFiltrar = u'|' <NEW_LINE> <DEDENT> peliculasFiltradas = QtCore.QRegExp( peliculasAFiltrar, QtCore.Qt.CaseInsensitive, QtCore.QRegExp.RegExp) <NEW_LINE> self.proxyModelMovie.setFilterRegExp(peliculasFiltradas) | Filtra las películas por el actor que participo en ellas luego de
seleccionar dicho actor desde el comboBox en el Tab de las Películas. | 625941bfbde94217f3682d3e |
def __sub__(self, dist): <NEW_LINE> <INDENT> if not isinstance(dist, Distance): <NEW_LINE> <INDENT> raise TypeError('Cannot subtract', type(dist), 'from a', type(self), 'object.') <NEW_LINE> <DEDENT> return self + -1 * dist | Subtract a Distance object from another Distance object
and return a new Distance. | 625941bfb7558d58953c4e63 |
def global_settings(request): <NEW_LINE> <INDENT> account_links = [] <NEW_LINE> tools_links = [] <NEW_LINE> footer_links = [] <NEW_LINE> context = {} <NEW_LINE> tools_title = _('Tools') <NEW_LINE> context['user'] = request.user <NEW_LINE> if request.user.is_authenticated(): <NEW_LINE> <INDENT> context['is_reviewer'] = acl.check_reviewer(request) <NEW_LINE> account_links = [ {'text': _('Account Settings'), 'href': '/settings'}, {'text': _('Change Password'), 'href': 'https://login.persona.org/signin'}, {'text': _('Sign out'), 'href': reverse('users.logout')}, ] <NEW_LINE> if '/developers/' not in request.path: <NEW_LINE> <INDENT> tools_links.append({'text': _('Developer Hub'), 'href': reverse('ecosystem.landing')}) <NEW_LINE> if request.user.is_developer: <NEW_LINE> <INDENT> tools_links.append({'text': _('My Submissions'), 'href': reverse('mkt.developers.apps')}) <NEW_LINE> <DEDENT> <DEDENT> if '/reviewers/' not in request.path and context['is_reviewer']: <NEW_LINE> <INDENT> footer_links.append({ 'text': _('Reviewer Tools'), 'href': reverse('reviewers.apps.queue_pending'), }) <NEW_LINE> <DEDENT> if acl.action_allowed(request, 'AccountLookup', '%'): <NEW_LINE> <INDENT> footer_links.append({'text': _('Lookup Tool'), 'href': reverse('lookup.home')}) <NEW_LINE> <DEDENT> if acl.action_allowed(request, 'Admin', '%'): <NEW_LINE> <INDENT> footer_links.append({'text': _('Admin Tools'), 'href': reverse('zadmin.home')}) <NEW_LINE> <DEDENT> tools_links += footer_links <NEW_LINE> logged = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logged = False <NEW_LINE> <DEDENT> DESKTOP = (getattr(request, 'TABLET', None) or not getattr(request, 'MOBILE', None)) <NEW_LINE> context.update(account_links=account_links, settings=settings, amo=amo, mkt=mkt, tools_links=tools_links, tools_title=tools_title, footer_links=footer_links, ADMIN_MESSAGE=get_config('site_notice'), collect_timings_percent=get_collect_timings(), is_admin=acl.action_allowed(request, 'Apps', 'Edit'), DESKTOP=DESKTOP, logged=logged) <NEW_LINE> return context | Store global Marketplace-wide info. used in the header. | 625941bf3eb6a72ae02ec421 |
def newNDChannel(self, project_name, channel_name): <NEW_LINE> <INDENT> ch = NDChannel.fromName(self.pr, channel_name) <NEW_LINE> pass | Create the tables for a channel | 625941bf377c676e912720f4 |
def get_xy_contiguous_bounded_grids(cube): <NEW_LINE> <INDENT> x_coord, y_coord = cube.coord(axis="X"), cube.coord(axis="Y") <NEW_LINE> x = x_coord.contiguous_bounds() <NEW_LINE> y = y_coord.contiguous_bounds() <NEW_LINE> x, y = np.meshgrid(x, y) <NEW_LINE> return (x, y) | Return 2d arrays for x and y bounds.
Returns array of shape (n+1, m+1).
Example::
xs, ys = get_xy_contiguous_bounded_grids(cube) | 625941bff548e778e58cd4c7 |
def mask_secret_parameters(parameters, secret_parameters, result=None): <NEW_LINE> <INDENT> iterator = None <NEW_LINE> is_dict = isinstance(secret_parameters, dict) <NEW_LINE> is_list = isinstance(secret_parameters, list) <NEW_LINE> if is_dict: <NEW_LINE> <INDENT> iterator = six.iteritems(secret_parameters) <NEW_LINE> <DEDENT> elif is_list: <NEW_LINE> <INDENT> iterator = enumerate(secret_parameters) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return MASKED_ATTRIBUTE_VALUE <NEW_LINE> <DEDENT> if result is None: <NEW_LINE> <INDENT> result = copy.deepcopy(parameters) <NEW_LINE> <DEDENT> for secret_param, secret_sub_params in iterator: <NEW_LINE> <INDENT> if is_dict: <NEW_LINE> <INDENT> if secret_param in result: <NEW_LINE> <INDENT> result[secret_param] = mask_secret_parameters(parameters[secret_param], secret_sub_params, result=result[secret_param]) <NEW_LINE> <DEDENT> <DEDENT> elif is_list: <NEW_LINE> <INDENT> for idx, value in enumerate(result): <NEW_LINE> <INDENT> result[idx] = mask_secret_parameters(parameters[idx], secret_sub_params, result=result[idx]) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> result[secret_param] = MASKED_ATTRIBUTE_VALUE <NEW_LINE> <DEDENT> <DEDENT> return result | Introspect the parameters dict and return a new dict with masked secret
parameters.
:param parameters: Parameters to process.
:type parameters: ``dict`` or ``list`` or ``string``
:param secret_parameters: Dict of parameter names which are secret.
The type must be the same type as ``parameters``
(or at least behave in the same way),
so that they can be traversed in the same way as
recurse down into the structure.
:type secret_parameters: ``dict``
:param result: Deep copy of parameters so that parameters is not modified
in place. Default = None, meaning this function will make a
deep copy before starting.
:type result: ``dict`` or ``list`` or ``string`` | 625941bf091ae35668666ead |
def test_number_set_attribute(self): <NEW_LINE> <INDENT> attr = NumberSetAttribute() <NEW_LINE> assert attr is not None <NEW_LINE> attr = NumberSetAttribute(default={1, 2}) <NEW_LINE> assert attr.default == {1, 2} | NumberSetAttribute.default | 625941bf01c39578d7e74d86 |
def create(self, validated_data): <NEW_LINE> <INDENT> return Project.objects.create(**validated_data) | Create and return a new `Project` instance, given the validated data. | 625941bf7cff6e4e811178d0 |
def test_message_already_unreacted(url, user_1, user_2, public_channel_1): <NEW_LINE> <INDENT> requests.post(f"{url}/channel/join", json={ 'token': user_2['token'], 'channel_id': public_channel_1['channel_id'] }) <NEW_LINE> msg_1 = request_message_send(url, user_1['token'], public_channel_1['channel_id'], "Hello").json() <NEW_LINE> msg_2 = request_message_send(url, user_2['token'], public_channel_1['channel_id'], "Hola").json() <NEW_LINE> request_message_react(url, user_2['token'], msg_2['message_id'], THUMBS_UP) <NEW_LINE> ret_unreact_1 = request_message_unreact(url, user_2['token'], msg_1['message_id'], THUMBS_UP) <NEW_LINE> assert ret_unreact_1.status_code == InputError.code <NEW_LINE> ret_unreact_2 = request_message_unreact(url, user_2['token'], msg_2['message_id'], THUMBS_DOWN) <NEW_LINE> assert ret_unreact_2.status_code == InputError.code <NEW_LINE> requests.delete(url + '/clear') | Test for unreacting to a message that is already unreacted to. | 625941bfff9c53063f47c13f |
def playfile(filename,mimetable=mimetable,**options): <NEW_LINE> <INDENT> contenttype,encoding = mimetypes.guess_type(filename) <NEW_LINE> if contenttype == None or encoding is not None: <NEW_LINE> <INDENT> contenttype = '?/?' <NEW_LINE> <DEDENT> maintype,subtype = contenttype.split('/',1) <NEW_LINE> if maintype == 'text' and subtype == 'html': <NEW_LINE> <INDENT> trywebbrowser(filename,**options) <NEW_LINE> <DEDENT> elif maintype in mimetable: <NEW_LINE> <INDENT> playknownfile(filename,mimetable[maintype],**options) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> trywebbrowser(filename,**options) | 播放任意类型媒体文件:使用mimetypes猜测媒体类型并对应到平台特异的播放器表格;
如果是文本/html,或者未知媒体类型,或者没有播放器表格,则派生网页浏览器
:param filename:
:param mimetable:
:param options:
:return: | 625941bf7d847024c06be204 |
def setFast(self): <NEW_LINE> <INDENT> self.max_num_bases = 7 | For some unit tests, calling this will speed the run of the test
by making some model build parameters very high-speed, low accuracy. | 625941bf507cdc57c6306c20 |
def __init__(self): <NEW_LINE> <INDENT> SloaneSequence.__init__(self, offset=0) | The all 1's sequence.
INPUT:
- ``n`` -- non negative integer
OUTPUT:
- ``integer`` -- function value
EXAMPLES::
sage: a = sloane.A000012; a
The all 1's sequence.
sage: a(1)
1
sage: a(2007)
1
sage: a.list(12)
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
AUTHORS:
- Jaap Spies (2007-01-12) | 625941bf85dfad0860c3ada4 |
def update_collection(collection_uuid, title): <NEW_LINE> <INDENT> assert isinstance(collection_uuid, UUID) <NEW_LINE> data = {"title": title} <NEW_LINE> result = api_request('patch', api_url('collections', str(collection_uuid)), json=data) <NEW_LINE> return _collection_from_response(result) | Update a collection's title | 625941bf94891a1f4081b9f3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.