code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def get_story_titles_in_topic(topic): <NEW_LINE> <INDENT> canonical_story_references = topic.canonical_story_references <NEW_LINE> story_ids = [story.story_id for story in canonical_story_references] <NEW_LINE> stories = story_fetchers.get_stories_by_ids(story_ids) <NEW_LINE> story_titles = [story.title for story in stories if story is not None] <NEW_LINE> return story_titles | Returns titles of the stories present in the topic.
Args:
topic: Topic. The topic domain objects.
Returns:
list(str). The list of story titles in the topic. | 625941c0d53ae8145f87a1dd |
@add_arg_scope <NEW_LINE> def conv2d(name, x, output_channels, filter_size=None, stride=None, logscale_factor=3.0, init=True, apply_actnorm=True, conv_init="default"): <NEW_LINE> <INDENT> if init == "zeros" and apply_actnorm: <NEW_LINE> <INDENT> raise ValueError("apply_actnorm is unstable when init is set to zeros.") <NEW_LINE> <DEDENT> if filter_size is None: <NEW_LINE> <INDENT> filter_size = [3, 3] <NEW_LINE> <DEDENT> if stride is None: <NEW_LINE> <INDENT> stride = [1, 1] <NEW_LINE> <DEDENT> x = add_edge_bias(x, filter_size=filter_size) <NEW_LINE> _, _, _, in_channels = common_layers.shape_list(x) <NEW_LINE> filter_shape = filter_size + [in_channels, output_channels] <NEW_LINE> stride_shape = [1, 1] + stride <NEW_LINE> with tf.variable_scope(name, reuse=tf.AUTO_REUSE): <NEW_LINE> <INDENT> if conv_init == "default": <NEW_LINE> <INDENT> initializer = default_initializer() <NEW_LINE> <DEDENT> elif conv_init == "zeros": <NEW_LINE> <INDENT> initializer = tf.zeros_initializer() <NEW_LINE> <DEDENT> w = tf.get_variable("W", filter_shape, tf.float32, initializer=initializer) <NEW_LINE> x = tf.nn.conv2d(x, w, stride_shape, padding="VALID", data_format="NHWC") <NEW_LINE> if apply_actnorm: <NEW_LINE> <INDENT> x, _ = actnorm("actnorm", x, logscale_factor=logscale_factor, init=init, trainable=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x += tf.get_variable("b", [1, 1, 1, output_channels], initializer=tf.zeros_initializer()) <NEW_LINE> logs = tf.get_variable("logs", [1, output_channels], initializer=tf.zeros_initializer()) <NEW_LINE> x *= tf.exp(logs * logscale_factor) <NEW_LINE> <DEDENT> return x | conv2d layer with edge bias padding and optional actnorm.
Args:
name: variable scope.
x: 4-D Tensor of shape (NHWC)
output_channels: Number of output channels.
filter_size:
stride:
logscale_factor: see actnorm for parameter meaning.
init: Whether to apply data-dependent initialization Valid only if
apply_actnorm is set to True.
apply_actnorm: if apply_actnorm the activations of the first minibatch
have zero mean and unit variance. Else, there is no scaling
applied.
conv_init: default or zeros. default is a normal distribution with 0.05 std.
Returns:
x: actnorm(conv2d(x))
Raises:
ValueError: if init is set to "zeros" and apply_actnorm is set to True. | 625941c0dd821e528d63b114 |
def __init__(self, parameters): <NEW_LINE> <INDENT> if 'AZURE_ACCOUNT_NAME' not in parameters: <NEW_LINE> <INDENT> raise BadConfigurationException("AZURE_ACCOUNT_NAME needs to be " + "specified") <NEW_LINE> <DEDENT> if 'AZURE_ACCOUNT_KEY' not in parameters: <NEW_LINE> <INDENT> raise BadConfigurationException("AZURE_ACCOUNT_KEY needs to be specified") <NEW_LINE> <DEDENT> self.azure_account_name = parameters['AZURE_ACCOUNT_NAME'] <NEW_LINE> self.azure_account_key = parameters['AZURE_ACCOUNT_KEY'] <NEW_LINE> self.connection = self.create_azure_connection() | Creates a new AzureStorage object, with the account name and account key
and that the user has specified.
Args:
parameters: A dict that contains the credentials necessary to authenticate
with the Blob Storage.
Raises:
BadConfigurationException: If the account name or account key are not
specified. | 625941c015fb5d323cde0a76 |
def task_reader(self): <NEW_LINE> <INDENT> msg_dict = self.msg_temp() <NEW_LINE> code = msg_dict.get('code') <NEW_LINE> task_name = msg_dict.get('task_name') <NEW_LINE> make_file(task_name) <NEW_LINE> make_main_script(task_name, code) <NEW_LINE> pass | 拿到msg | 625941c01f037a2d8b946168 |
def getConfig(s=None, default=None): <NEW_LINE> <INDENT> readIfRequired() <NEW_LINE> if s is None: <NEW_LINE> <INDENT> return configs <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return configs.get(s, default) | Get the dictionnary of configs. If a name is given, return the
object with this name if it exists.
reads if required. | 625941c0956e5f7376d70dd8 |
def grayCodeBacktracking(self, n): <NEW_LINE> <INDENT> res = [] <NEW_LINE> num = [0] <NEW_LINE> def backtrack(res, n, num): <NEW_LINE> <INDENT> if n == 0: <NEW_LINE> <INDENT> res.append(num[0]) <NEW_LINE> return <NEW_LINE> <DEDENT> backtrack(res, n-1, num) <NEW_LINE> num[0] = num[0] ^ (1 << (n-1)) <NEW_LINE> backtrack(res, n-1, num) <NEW_LINE> <DEDENT> backtrack(res, n, num) <NEW_LINE> return res | :type n: int
:rtype: List[int] | 625941c0fff4ab517eb2f3a4 |
def scoreMotifs(motifs): <NEW_LINE> <INDENT> z = zip(*motifs) <NEW_LINE> totalscore = 0 <NEW_LINE> for string in z: <NEW_LINE> <INDENT> score = len(string)-max([string.count('A'),string.count('C'), string.count('G'), string.count('T')]) <NEW_LINE> totalscore += score <NEW_LINE> <DEDENT> return totalscore | This function computes the score of list of motifs | 625941c0167d2b6e31218aff |
def query_price(self, country_code, start, end, as_series=False): <NEW_LINE> <INDENT> domain = DOMAIN_MAPPINGS[country_code] <NEW_LINE> params = { 'documentType': 'A44', 'in_Domain': domain, 'out_Domain': domain } <NEW_LINE> response = self.base_request(params=params, start=start, end=end) <NEW_LINE> if response is None: <NEW_LINE> <INDENT> self.logger.info('HTTP request returned nothing') <NEW_LINE> return None <NEW_LINE> <DEDENT> if not as_series: <NEW_LINE> <INDENT> self.logger.info('HTTP request processed - XML') <NEW_LINE> return response.text <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> from . import parsers <NEW_LINE> series = parsers.parse_prices(response.text) <NEW_LINE> series = series.tz_convert(TIMEZONE_MAPPINGS[country_code]) <NEW_LINE> self.logger.info('HTTP request processed - pandas') <NEW_LINE> return series | Parameters
----------
country_code : str
start : pd.Timestamp
end : pd.Timestamp
as_series : bool
Default False
If True: Return the response as a Pandas Series
If False: Return the response as raw XML
Returns
-------
str | pd.Series | 625941c05fdd1c0f98dc019c |
def download_command_as_json(request, command_id): <NEW_LINE> <INDENT> if request.method == 'GET': <NEW_LINE> <INDENT> comm = CommandEntry.objects.filter(id=command_id).first() <NEW_LINE> json_response = {} <NEW_LINE> if comm: <NEW_LINE> <INDENT> json_response = comm.as_object() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> json_response['msg'] = 'Command with id {0} not found'.format(command_id) <NEW_LINE> <DEDENT> response = HttpResponse( json.dumps(json_response, indent=4, separators=(',', ': ')), content_type='application/json') <NEW_LINE> response['Content-Disposition'] = 'attachment; filename=Command-{0}.json'.format(command_id) <NEW_LINE> return response <NEW_LINE> <DEDENT> return res.get_only_get_allowed({}) | Retrieves a command by id and generates a file to be downloaded | 625941c023849d37ff7b2ffa |
def get_available_audio_languages(): <NEW_LINE> <INDENT> call_args = { 'paths': [['spokenAudioLanguages', {'from': 0, 'to': 25}, ['id', 'name']]] } <NEW_LINE> response = common.make_call('path_request', call_args) <NEW_LINE> lang_list = {} <NEW_LINE> for lang_dict in itervalues(response.get('spokenAudioLanguages', {})): <NEW_LINE> <INDENT> lang_list[lang_dict['id']] = lang_dict['name'] <NEW_LINE> <DEDENT> return lang_list | Get the list of available audio languages of videos | 625941c024f1403a92600ad2 |
@login_required <NEW_LINE> def order_details(request, order_id, template_name="registration/order_details.html"): <NEW_LINE> <INDENT> page_title = 'Order Details for Order #' + order_id <NEW_LINE> return render_to_response(template_name, locals(), context_instance=RequestContext(request)) | displays the details of a past customer order; order details can only be loaded by the same
user to whom the order instance belongs. | 625941c0498bea3a759b9a19 |
@connection <NEW_LINE> def send_release(): <NEW_LINE> <INDENT> return "<RELEASE>" | sending a release-signal so that the tvpaintplugin stops listening
So tvpaint can continue.. | 625941c056b00c62f0f145c2 |
def get_result_string(self, join = '\n'): <NEW_LINE> <INDENT> return join.join(self.last_result) | get_result_string(self) -> string
Gets the last result in a single string. | 625941c0a79ad161976cc0af |
@content_type('application/json; charset=utf-8') <NEW_LINE> def pretty_json(content, **kwargs): <NEW_LINE> <INDENT> return json(content, indent=4, separators=(',', ': '), **kwargs) | JSON (Javascript Serialized Object Notion) pretty printed and indented | 625941c010dbd63aa1bd2b0e |
def emit(self, record): <NEW_LINE> <INDENT> msg = self.format(record) <NEW_LINE> if not msg.startswith('\n') or msg.endswith('\n'): <NEW_LINE> <INDENT> msg += '\n' <NEW_LINE> <DEDENT> if (self.client is None) or (self.transport is None): <NEW_LINE> <INDENT> raise ScribeTransportError('No transport defined') <NEW_LINE> <DEDENT> if hasattr(record, 'processName'): <NEW_LINE> <INDENT> pn = record.processName <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pn = 'Unknown' <NEW_LINE> <DEDENT> category = self.category % { 'module' : record.module, 'levelname': record.levelname, 'loggername' : record.name, 'processName' : pn, 'hostname' : socket.gethostname(), } <NEW_LINE> log_entry = scribe.LogEntry(category=category, message=msg) <NEW_LINE> try: <NEW_LINE> <INDENT> self.transport.open() <NEW_LINE> for le in self.get_entries(log_entry): <NEW_LINE> <INDENT> result = self.client.Log(messages=[le[1]]) <NEW_LINE> if result != scribe.ResultCode.OK: <NEW_LINE> <INDENT> raise ScribeLogError(result) <NEW_LINE> <DEDENT> self.pop_entry(le[0]) <NEW_LINE> <DEDENT> self.transport.close() <NEW_LINE> <DEDENT> except TTransportException: <NEW_LINE> <INDENT> if self.file_buffer is not None: <NEW_LINE> <INDENT> self.add_entry(log_entry) <NEW_LINE> <DEDENT> self._do_error(record) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self._do_error(record) | Emit a record.
If a formatter is specified, it is used to format the record.
The record is then logged to Scribe with a trailing newline. | 625941c015baa723493c3edd |
def OnItemDrag(self,*args): <NEW_LINE> <INDENT> pass | OnItemDrag(self: TreeView,e: ItemDragEventArgs)
Raises the System.Windows.Forms.TreeView.ItemDrag event.
e: An System.Windows.Forms.ItemDragEventArgs that contains the event data. | 625941c0851cf427c661a47b |
def test_full_binary_tree(self): <NEW_LINE> <INDENT> self.root = BinaryNode(18) <NEW_LINE> self.root.left = BinaryNode(15) <NEW_LINE> self.root.right = BinaryNode(20) <NEW_LINE> self.root.left.left = BinaryNode(40) <NEW_LINE> self.root.left.right = BinaryNode(50) <NEW_LINE> self.root.right.left = BinaryNode(16) <NEW_LINE> self.root.right.right = BinaryNode(25) <NEW_LINE> self.assertEqual(post_order_traversal(self.root), [40, 50, 15, 16, 25, 20, 18]) | Full (Perfect) Binary Tree
Each node has exactly 0 or 2 children and all leaf nodes are on
the same level.
18
/ / / 15 20
/ \ / 40 50 16 25 | 625941c0b57a9660fec337eb |
def failure_message(context): <NEW_LINE> <INDENT> pg = context.scene.pdt_pg <NEW_LINE> pg.error = f"{PDT_ERR_SEL_1_E_1_F}" <NEW_LINE> context.window_manager.popup_menu(oops, title="Error", icon="ERROR") | Warn to the user to select 1 edge and 1 face.
Args:
context: Blender bpy.context instance.
Returns:
Nothing. | 625941c0bde94217f3682d5d |
def unpack_float(self, offset): <NEW_LINE> <INDENT> o = self._offset + offset <NEW_LINE> try: <NEW_LINE> <INDENT> return struct.unpack_from("<f", self._buf, o)[0] <NEW_LINE> <DEDENT> except struct.error: <NEW_LINE> <INDENT> raise OverrunBufferException(o, len(self._buf)) | Returns a single-precision float (4 bytes) from
the relative offset. IEEE 754 format.
Arguments:
- `offset`: The relative offset from the start of the block.
Throws:
- `OverrunBufferException` | 625941c0435de62698dfdbb6 |
def test_wiki_samples(self): <NEW_LINE> <INDENT> grid = DataGrid(fields=[ ('ID', 'userId'), ('Name', 'displayName'), ('E-mail', 'emailAddress')]) <NEW_LINE> users = [User(1, 'john', 'john@foo.net'), User(2, 'fred', 'fred@foo.net')] <NEW_LINE> output = grid.render(users) <NEW_LINE> assert '<td>2</td><td>Fred</td><td>fred@foo.net</td>' in output <NEW_LINE> grid = DataGrid(fields=[ ('Name', lambda row: row[1]), ('Country', lambda row: row[2]), ('Age', lambda row: row[0])]) <NEW_LINE> data = [(33, "Anton Bykov", "Bulgaria"), (23, "Joe Doe", "Great Britain"), (44, "Pablo Martelli", "Brazil")] <NEW_LINE> output = grid.render(data) <NEW_LINE> assert '<td>Joe Doe</td><td>Great Britain</td><td>23</td>' in output | Test that sample code on DataGridWidget wiki page actually works. | 625941c045492302aab5e22b |
def which(prog): <NEW_LINE> <INDENT> return common.lookup_prog([prog], os.getenv("PATH").split(":")); | Look for a program in the system PATH. | 625941c06aa9bd52df036d0c |
def paintEvent(self, event): <NEW_LINE> <INDENT> logger.debug('开始画图') <NEW_LINE> x = self.start[0] <NEW_LINE> y = self.start[1] <NEW_LINE> w = self.end[0] - x <NEW_LINE> h = self.end[1] - y <NEW_LINE> pp = QPainter(self) <NEW_LINE> pp.drawRect(x, y, w, h) | 给出截图的辅助线
:param event:
:return: | 625941c04c3428357757c294 |
def remove(self, item, priority=None): <NEW_LINE> <INDENT> if priority is None: <NEW_LINE> <INDENT> priority = self.priority(item) <NEW_LINE> <DEDENT> self.values[priority].remove(item) <NEW_LINE> if not self.values[priority]: <NEW_LINE> <INDENT> del self.values[priority] | Remove the given item from the queue.
If given a priority, will only remove from that priority. | 625941c0f9cc0f698b140567 |
def _create(tensorsSize, floatsSize, intsSize): <NEW_LINE> <INDENT> return lib.cnn_create_extraData(tensorsSize, floatsSize, intsSize) | ExtraData의 포인터를 반환합니다. | 625941c0091ae35668666ecc |
def gooding(k, r, v, tofs, numiter=150, rtol=1e-8): <NEW_LINE> <INDENT> k = k.to_value(u.m**3 / u.s**2) <NEW_LINE> r0 = r.to_value(u.m) <NEW_LINE> v0 = v.to_value(u.m / u.s) <NEW_LINE> tofs = tofs.to_value(u.s) <NEW_LINE> results = np.array( [gooding_fast(k, r0, v0, tof, numiter=numiter, rtol=rtol) for tof in tofs] ) <NEW_LINE> return results[:, 0] << u.m, results[:, 1] << u.m / u.s | Propagate the orbit using the Gooding method.
The Gooding method solves the Elliptic Kepler Equation with a cubic convergence,
and accuracy better than 10e-12 rad is normally achieved. It is not valid for
eccentricities equal or greater than 1.0.
Parameters
----------
k : ~astropy.units.Quantity
Standard gravitational parameter of the attractor.
r : ~astropy.units.Quantity
Position vector.
v : ~astropy.units.Quantity
Velocity vector.
tofs : ~astropy.units.Quantity
Array of times to propagate.
numiter : int
Maximum number of iterations for convergence.
rtol : float
This method does not require of tolerance since it is non iterative.
Returns
-------
rr : ~astropy.units.Quantity
Propagated position vectors.
vv : ~astropy.units.Quantity
Notes
-----
This method was developed by Gooding and Odell in their paper *The
hyperbolic Kepler equation (and the elliptic equation revisited)* with
DOI: https://doi.org/10.1007/BF01235540 | 625941c091af0d3eaac9b980 |
def test_register_success(self): <NEW_LINE> <INDENT> self.fill_submit_form_with_values(self.register_form, self.user_form_user) <NEW_LINE> user = USER_MODEL.objects.get() <NEW_LINE> for field in self.user_without_password_fields(): <NEW_LINE> <INDENT> field_value = getattr(user, field) <NEW_LINE> self.assertEqual(field_value, self.user_for_tests[field]) <NEW_LINE> <DEDENT> self.assertTrue(user.check_password(self.user_for_tests['password1'])) | Registration is successful and all provided fields are stored. | 625941c030dc7b76659018d3 |
def zigzagencode(value): <NEW_LINE> <INDENT> if value >= 0: <NEW_LINE> <INDENT> return value << 1 <NEW_LINE> <DEDENT> return (value << 1) ^ (~0) | zigzag transform: encodes signed integers so that they can be
effectively used with varint encoding. see wire_format.h for
more details. | 625941c071ff763f4b5495f1 |
def get_crd(self, axis, shaped=False, center="none"): <NEW_LINE> <INDENT> return self.get_crds([axis], shaped=shaped, center=center)[0] | if axis is not specified, return all coords,
shaped makes axis capitalized and returns ogrid like crds
shaped is only used if axis == None
sfx can be none, node, cell, face, edge
raises KeyError if axis not found | 625941c032920d7e50b28138 |
def maj_dico_compte(dico, mot, ligne): <NEW_LINE> <INDENT> if mot.lower() not in dico: <NEW_LINE> <INDENT> dico[mot.lower()] = [ligne] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dico[mot.lower()].append(ligne) | Ajoute la ligne à la clé mot dans le dico.
:param dico: Dictionnaire à modifier.
:param mot: Clé à incrémenter. | 625941c00fa83653e4656f26 |
def showKeywords(self, lst_of_pairs, tfidf_list, rel_freq_lst, lst_pnn): <NEW_LINE> <INDENT> keywords = [] <NEW_LINE> lst_pnn = list(lst_pnn) <NEW_LINE> lst_pnn_lowered = [name.lower() for name in lst_pnn] <NEW_LINE> freq_lst = [] <NEW_LINE> for w in tfidf_list: <NEW_LINE> <INDENT> for rel_f in rel_freq_lst: <NEW_LINE> <INDENT> if w[0] == rel_f[0]: <NEW_LINE> <INDENT> freq_lst.append((w[0], rel_f[1], w[1])) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for term in freq_lst: <NEW_LINE> <INDENT> kw = [] <NEW_LINE> for pair in set(lst_of_pairs): <NEW_LINE> <INDENT> if term[0] == pair[0]: <NEW_LINE> <INDENT> if pair[1] in lst_pnn_lowered: <NEW_LINE> <INDENT> for n in range(len(lst_pnn_lowered)): <NEW_LINE> <INDENT> if pair[1] == lst_pnn_lowered[n]: <NEW_LINE> <INDENT> kw.append(lst_pnn[n]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> kw.append(pair[1]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> keywords.append((kw, term[1], term[2])) <NEW_LINE> <DEDENT> return keywords | Функция сопоставляет стеммы ключевых слов непосредственно со словами,
чтобы вывести их в резултат.
На вход принимает список пар (стемма, слово), список весов, список
относительных частот (для web) и список имен собственных.
Список имен собственных нужен для правильного вывода слов
с заглавной буквы и аббревиатур. Возвращает список кортежей
ключевых слов и их весов. | 625941c02c8b7c6e89b3572c |
def process_options(arglist=None): <NEW_LINE> <INDENT> global options, args <NEW_LINE> parser = OptionParser(version=__version__, usage="%prog [options] input ...") <NEW_LINE> parser.add_option('-v', '--verbose', default=0, action='count', help="print status messages, or debug with -vv") <NEW_LINE> parser.add_option('-q', '--quiet', default=0, action='count', help="report only file names, or nothing with -qq") <NEW_LINE> parser.add_option('-r', '--repeat', action='store_true', help="show all occurrences of the same error") <NEW_LINE> parser.add_option('--exclude', metavar='patterns', default=DEFAULT_EXCLUDE, help="exclude files or directories which match these " "comma separated patterns (default: %s)" % DEFAULT_EXCLUDE) <NEW_LINE> parser.add_option('--filename', metavar='patterns', default='*.py', help="when parsing directories, only check filenames " "matching these comma separated patterns (default: " "*.py)") <NEW_LINE> parser.add_option('--select', metavar='errors', default='', help="select errors and warnings (e.g. E,W6)") <NEW_LINE> parser.add_option('--ignore', metavar='errors', default='', help="skip errors and warnings (e.g. E4,W)") <NEW_LINE> parser.add_option('--show-source', action='store_true', help="show source code for each error") <NEW_LINE> parser.add_option('--show-pep8', action='store_true', help="show text of PEP 8 for each error") <NEW_LINE> parser.add_option('--statistics', action='store_true', help="count errors and warnings") <NEW_LINE> parser.add_option('--count', action='store_true', help="print total number of errors and warnings " "to standard error and set exit code to 1 if " "total is not null") <NEW_LINE> parser.add_option('--benchmark', action='store_true', help="measure processing speed") <NEW_LINE> parser.add_option('--testsuite', metavar='dir', help="run regression tests from dir") <NEW_LINE> parser.add_option('--doctest', action='store_true', help="run doctest on myself") <NEW_LINE> options, args = parser.parse_args(arglist) <NEW_LINE> if options.testsuite: <NEW_LINE> <INDENT> args.append(options.testsuite) <NEW_LINE> <DEDENT> if len(args) == 0 and not options.doctest: <NEW_LINE> <INDENT> parser.error('input not specified') <NEW_LINE> <DEDENT> options.prog = os.path.basename(sys.argv[0]) <NEW_LINE> options.exclude = options.exclude.split(',') <NEW_LINE> for index in range(len(options.exclude)): <NEW_LINE> <INDENT> options.exclude[index] = options.exclude[index].rstrip('/') <NEW_LINE> <DEDENT> if options.filename: <NEW_LINE> <INDENT> options.filename = options.filename.split(',') <NEW_LINE> <DEDENT> if options.select: <NEW_LINE> <INDENT> options.select = options.select.split(',') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> options.select = [] <NEW_LINE> <DEDENT> if options.ignore: <NEW_LINE> <INDENT> options.ignore = options.ignore.split(',') <NEW_LINE> <DEDENT> elif options.select: <NEW_LINE> <INDENT> options.ignore = [''] <NEW_LINE> <DEDENT> elif options.testsuite or options.doctest: <NEW_LINE> <INDENT> options.ignore = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> options.ignore = DEFAULT_IGNORE.split(',') <NEW_LINE> <DEDENT> options.physical_checks = find_checks('physical_line') <NEW_LINE> options.logical_checks = find_checks('logical_line') <NEW_LINE> options.counters = {} <NEW_LINE> options.messages = {} <NEW_LINE> return options, args | Process options passed either via arglist or via command line args. | 625941c09c8ee82313fbb6df |
def symb(self, s): <NEW_LINE> <INDENT> right = '' <NEW_LINE> d = { '(': ')', '{': '}', '[': ']', } <NEW_LINE> for x in s: <NEW_LINE> <INDENT> if x in d: <NEW_LINE> <INDENT> right = d[x] + right <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if x == right[:1]: <NEW_LINE> <INDENT> right = right[1:] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return False if right else True | :type s: str
:rtype: bool | 625941c03eb6a72ae02ec441 |
def xor_cycle(data: bytes, key: bytes) -> bytes: <NEW_LINE> <INDENT> return bytes([x^y for x, y in zip(data, cycle(key))]) | Cyclically xor key over data. | 625941c073bcbd0ca4b2bfe0 |
def check(self): <NEW_LINE> <INDENT> self.check_was_run = True <NEW_LINE> if not "Architecture" in self.sections: <NEW_LINE> <INDENT> print("eDeb Package Error: No Architecture field in the package") <NEW_LINE> return "Package was created poorly. No Architecture field in the package" <NEW_LINE> <DEDENT> arch = self.sections["Architecture"] <NEW_LINE> if arch != "all" and arch != apt_pkg.config.find("APT::Architecture"): <NEW_LINE> <INDENT> if arch in apt_pkg.get_architectures(): <NEW_LINE> <INDENT> self.multiarch = arch <NEW_LINE> self.pkgname = "%s:%s" % (self.pkgname, self.multiarch) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("eDeb Package Error: Wrong architecture, %s" %arch) <NEW_LINE> return "Package is not eligible for installation because of wrong architecture: <b>%s</b>" %arch <NEW_LINE> <DEDENT> <DEDENT> if self.cache._depcache.broken_count > 0: <NEW_LINE> <INDENT> print("eDeb Package Error: Failed to satisfy dependencies. Broken cache. Now clearing..") <NEW_LINE> self.cache.clear() <NEW_LINE> print("eDeb Notification: Cache cleared.") <NEW_LINE> return "Broken dependencies from previous installation (broken cache). Cache has been cleared.<ps><ps>If the issue persists, please select Fix to attempt to complete the broken installation." <NEW_LINE> <DEDENT> return True | Check if the package is installable. | 625941c030c21e258bdfa406 |
def _compute_results_per_page(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> results_per_page = int(request.args.get('results_per_page')) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> results_per_page = self.results_per_page <NEW_LINE> <DEDENT> if results_per_page <= 0: <NEW_LINE> <INDENT> results_per_page = self.results_per_page <NEW_LINE> <DEDENT> return min(results_per_page, self.max_results_per_page) | Helper function which returns the number of results per page based
on the request argument ``results_per_page`` and the server
configuration parameters :attr:`results_per_page` and
:attr:`max_results_per_page`. | 625941c06fb2d068a760f005 |
def xmlrpc_protocol(self, server, params, function=None, key_word=None): <NEW_LINE> <INDENT> def core_cohort_create_cohorts(params): <NEW_LINE> <INDENT> return proxy.core_cohort_create_cohorts(params) <NEW_LINE> <DEDENT> def core_course_get_courses(params): <NEW_LINE> <INDENT> return proxy.core_course_get_courses() <NEW_LINE> <DEDENT> def core_course_create_courses(params): <NEW_LINE> <INDENT> return proxy.core_course_create_courses(params) <NEW_LINE> <DEDENT> def core_user_get_users(params): <NEW_LINE> <INDENT> return proxy.core_user_get_users(params) <NEW_LINE> <DEDENT> def core_user_create_users(params): <NEW_LINE> <INDENT> return proxy.core_user_create_users(params) <NEW_LINE> <DEDENT> def core_user_update_users(params): <NEW_LINE> <INDENT> return proxy.core_user_update_users(params) <NEW_LINE> <DEDENT> def core_user_delete_users(params): <NEW_LINE> <INDENT> return proxy.core_user_delete_users(params) <NEW_LINE> <DEDENT> def enrol_manual_enrol_users(params): <NEW_LINE> <INDENT> return proxy.enrol_manual_enrol_users(params) <NEW_LINE> <DEDENT> def core_course_duplicate_course(params): <NEW_LINE> <INDENT> return proxy.core_course_duplicate_course(params) <NEW_LINE> <DEDENT> def core_enrol_get_enrolled_users(params): <NEW_LINE> <INDENT> return proxy.core_enrol_get_enrolled_users(params) <NEW_LINE> <DEDENT> def core_course_update_courses(params): <NEW_LINE> <INDENT> return proxy.core_course_update_courses(params) <NEW_LINE> <DEDENT> def not_implemented_yet(params): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> proxy = self.conn_xmlrpc(server) <NEW_LINE> select_method = { "core_course_get_courses": core_course_get_courses, "core_course_create_courses": core_course_create_courses, "core_course_duplicate_course": core_course_duplicate_course, "core_user_get_users": core_user_get_users, "core_user_create_users": core_user_create_users, "core_user_update_users": core_user_update_users, "core_user_delete_users": core_user_delete_users, "enrol_manual_enrol_users": enrol_manual_enrol_users, "core_enrol_get_enrolled_users": core_enrol_get_enrolled_users, "core_course_update_courses": core_course_update_courses, "core_cohort_create_cohorts": core_cohort_create_cohorts, "not_implemented_yet": not_implemented_yet, } <NEW_LINE> if function is None or function not in select_method: <NEW_LINE> <INDENT> function = "not_implemented_yet" <NEW_LINE> <DEDENT> return select_method[function](params) | Select the correct function to call | 625941c099cbb53fe6792b51 |
def checkInclusion(self, s1, s2): <NEW_LINE> <INDENT> s1_dic, s2_dic = {}, {} <NEW_LINE> if len(s1) > len(s2): return False <NEW_LINE> for c in s1: <NEW_LINE> <INDENT> s1_dic[c] = s1_dic.get(c, 0) + 1 <NEW_LINE> <DEDENT> for i in range(len(s1)): <NEW_LINE> <INDENT> s2_dic[s2[i]] = s2_dic.get(s2[i], 0) + 1 <NEW_LINE> <DEDENT> if s1_dic == s2_dic: return True <NEW_LINE> for i in range(len(s1), len(s2)): <NEW_LINE> <INDENT> s2_dic[s2[i]] = s2_dic.get(s2[i], 0) + 1 <NEW_LINE> s2_dic[s2[i-len(s1)]] -= 1 <NEW_LINE> if s2_dic[s2[i-len(s1)]] == 0: <NEW_LINE> <INDENT> del s2_dic[s2[i-len(s1)]] <NEW_LINE> <DEDENT> if s1_dic == s2_dic: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False | :type s1: str
:type s2: str
:rtype: bool | 625941c03617ad0b5ed67e63 |
def visit_family( self, results: Any, level: int, w: Node, ix: int, prod: Production ) -> None: <NEW_LINE> <INDENT> return | At a family of children | 625941c06aa9bd52df036d0d |
def notification(message, height, pause): <NEW_LINE> <INDENT> pass | Displays a string message
:param str message: Message to display
:param int height: Height of dialog box if applicable
:param bool pause: Whether or not the application should pause for
confirmation (if available) | 625941c0e76e3b2f99f3a77a |
def due_mapper(attribute): <NEW_LINE> <INDENT> def _fn(v): <NEW_LINE> <INDENT> today = date.today() <NEW_LINE> due = v['due'] <NEW_LINE> days = [(dateformat.format(d, 'l'), d) for d in [ (today + timedelta(days=d)) for d in range(2, 7)]] <NEW_LINE> days.append((_('Today'), today)) <NEW_LINE> days.append((_('Tomorrow'), today + timedelta(days=1))) <NEW_LINE> days = dict((k.lower(), v) for k, v in days) <NEW_LINE> if due.lower() in days: <NEW_LINE> <INDENT> return {attribute: days[due.lower()]} <NEW_LINE> <DEDENT> day = [today.year, today.month, today.day] <NEW_LINE> try: <NEW_LINE> <INDENT> for i, n in enumerate(due.split('.')): <NEW_LINE> <INDENT> day[2-i] = int(n, 10) <NEW_LINE> <DEDENT> <DEDENT> except (IndexError, TypeError, ValueError): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return {attribute: date(*day)} <NEW_LINE> <DEDENT> except (TypeError, ValueError): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return {} <NEW_LINE> <DEDENT> return _fn | Understands ``Today``, ``Tomorrow``, the following five localized
week day names or (partial) dates such as ``20.12.`` and ``01.03.2012``. | 625941c023e79379d52ee4d0 |
def vigsquare(printable=False): <NEW_LINE> <INDENT> alpha = string.ascii_uppercase <NEW_LINE> rotater = collections.deque(alpha) <NEW_LINE> vigsquare_list = [] <NEW_LINE> for i in range(26): <NEW_LINE> <INDENT> vigsquare_list.append(''.join(rotater)) <NEW_LINE> rotater.rotate(-1) <NEW_LINE> <DEDENT> if printable: <NEW_LINE> <INDENT> return '\n'.join(vigsquare_list) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ''.join(vigsquare_list) | Returns a string like a vigenere square,
printable joins each row with a newline so it's literally square
printable=False (defaul) joins without newlines for easier
searching by row and column index | 625941c03d592f4c4ed1cfdd |
def crop_to(image_to_crop, reference_image): <NEW_LINE> <INDENT> reference_size = reference_image.size <NEW_LINE> current_size = image_to_crop.size <NEW_LINE> dx = current_size[0] - reference_size[0] <NEW_LINE> dy = current_size[1] - reference_size[1] <NEW_LINE> left = dx / 2 <NEW_LINE> upper = dy / 2 <NEW_LINE> right = dx / 2 + reference_size[0] <NEW_LINE> lower = dy / 2 + reference_size[1] <NEW_LINE> return image_to_crop.crop(box=(left, upper, right, lower)) | Crops image to the size of a reference image. This function assumes that the relevant image is located in the center
and you want to crop away equal sizes on both the left and right as well on both the top and bottom.
:param image_to_crop
:param reference_image
:return: image cropped to the size of the reference image | 625941c0a934411ee37515fe |
def test_read_code_position_handles_malformed_input(self): <NEW_LINE> <INDENT> def assert_is_parsed(code_position_string): <NEW_LINE> <INDENT> code_position = parser._read_code_position([code_position_string], 0) <NEW_LINE> self.assertEqual(len(code_position), 4) <NEW_LINE> self.assertTrue(isinstance(code_position[3], int)) <NEW_LINE> <DEDENT> parser = Log4jParser() <NEW_LINE> assert_is_parsed('?(C.java:23)') <NEW_LINE> assert_is_parsed('.m(C.java:23)') <NEW_LINE> assert_is_parsed('C.(C.java:23)') <NEW_LINE> assert_is_parsed('.(C.java:23)') <NEW_LINE> assert_is_parsed('(C.java:23)') <NEW_LINE> assert_is_parsed('C.m(?)') <NEW_LINE> assert_is_parsed('C.m(:23)') <NEW_LINE> assert_is_parsed('C.m(C.java:)') <NEW_LINE> assert_is_parsed('C.m(:)') <NEW_LINE> assert_is_parsed('C.m()') <NEW_LINE> assert_is_parsed('C.m(C.java:NaN)') <NEW_LINE> assert_is_parsed('C.m(C.java:3rr0r)') <NEW_LINE> assert_is_parsed('?.?:?') <NEW_LINE> assert_is_parsed('(C.java:23)') <NEW_LINE> assert_is_parsed('C.m(') <NEW_LINE> assert_is_parsed('(') <NEW_LINE> assert_is_parsed('') <NEW_LINE> assert_is_parsed('C.m(C.java:23:42)') <NEW_LINE> assert_is_parsed('C.m(C.java:23)(D.java:42)') <NEW_LINE> assert_is_parsed('C.m(C.ja(D.java:42)va:23)') <NEW_LINE> assert_is_parsed('C.m(C.java:23') <NEW_LINE> assert_is_parsed('C.m(C.java:23:') | Malformed code positions are handled. | 625941c0d4950a0f3b08c2bb |
@dsym.command(name='import-system-symbols', short_help='Import system debug symbols.') <NEW_LINE> @click.argument('bundles', type=click.Path(), nargs=-1) <NEW_LINE> @click.option('--threads', default=8, help='The number of threads to use') <NEW_LINE> @click.option('--trim-symbols', is_flag=True, help='If enabled symbols are trimmed before storing. ' 'This reduces the database size but means that symbols are ' 'already trimmed on the way to the database.') <NEW_LINE> @click.option('--no-demangle', is_flag=True, help='If this is set to true symbols are never demangled. ' 'By default symbols are demangled if they are trimmed or ' 'demangled symbols are shorter than mangled ones. Enabling ' 'this option speeds up importing slightly.') <NEW_LINE> @configuration <NEW_LINE> def import_system_symbols(bundles, threads, trim_symbols, no_demangle): <NEW_LINE> <INDENT> import zipfile <NEW_LINE> from sentry.utils.db import is_mysql <NEW_LINE> if threads != 1 and is_mysql(): <NEW_LINE> <INDENT> warnings.warn(Warning('disabled threading for mysql')) <NEW_LINE> threads = 1 <NEW_LINE> <DEDENT> for path in bundles: <NEW_LINE> <INDENT> with zipfile.ZipFile(path) as f: <NEW_LINE> <INDENT> sdk_info = json.load(f.open('sdk_info')) <NEW_LINE> label = ('%s.%s.%s (%s)' % ( sdk_info['version_major'], sdk_info['version_minor'], sdk_info['version_patchlevel'], sdk_info['version_build'], )).ljust(18) <NEW_LINE> with click.progressbar(f.namelist(), label=label) as bar: <NEW_LINE> <INDENT> process_archive(bar, f, sdk_info, threads, trim_symbols=trim_symbols, demangle=not no_demangle) | Imports system symbols from preprocessed zip files into Sentry.
It takes a list of zip files as arguments that contain preprocessed
system symbol information. These zip files contain JSON dumps. The
actual zipped up dsym files cannot be used here, they need to be
preprocessed. | 625941c0187af65679ca5088 |
def resize(self, size): <NEW_LINE> <INDENT> dimension = (2 * self.border + self.width) <NEW_LINE> factor = size / dimension <NEW_LINE> self._img.attrib['transform'] = 'scale(%f)' % factor | resize the code by applying a scale transform | 625941c0cdde0d52a9e52f9b |
def _fetchRequirement(self, requirement: str) -> Union[int, float, bool, None]: <NEW_LINE> <INDENT> if requirement in self._requirementOverrides: <NEW_LINE> <INDENT> value = self._requirementOverrides[requirement] <NEW_LINE> if value is None: <NEW_LINE> <INDENT> raise AttributeError( f"Encountered explicit None for '{requirement}' requirement of {self}" ) <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> elif self._config is not None: <NEW_LINE> <INDENT> value = getattr(self._config, 'default' + requirement.capitalize()) <NEW_LINE> if value is None: <NEW_LINE> <INDENT> raise AttributeError( f"Encountered None for default '{requirement}' requirement " f"in config: {self._config}" ) <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise AttributeError( f"Default value for '{requirement}' requirement of {self} cannot be determined" ) | Get the value of the specified requirement ('blah').
Done by looking it up in our requirement storage and querying 'defaultBlah'
on the config if it isn't set. If the config would be queried but isn't
associated, raises AttributeError.
:param requirement: The name of the resource | 625941c0a17c0f6771cbdfbd |
def calculateMainRecord(self, record: QtSql.QSqlRecord, fieldName: str): <NEW_LINE> <INDENT> lst = [r for r in self._widgetsInformation if r.fieldIndex == -1] <NEW_LINE> s = ('存在计算列,但没有实现calculateSubViewCell函数。' '该函数给定当前行数据及列名,应该返回计算列的值') <NEW_LINE> if lst: <NEW_LINE> <INDENT> raise UserWarning(s) <NEW_LINE> <DEDENT> return | 用于计算主表的计算字段 | 625941c0796e427e537b052e |
def verifyBond1(self, records): <NEW_LINE> <INDENT> self.assertEqual(len(records), 1) <NEW_LINE> record = records[0] <NEW_LINE> self.assertTrue(not 'portfolio' in record) <NEW_LINE> self.assertEqual('DBANFB12014 Dragon Days Ltd 6.0%', record['description']) <NEW_LINE> self.assertEqual('HKD', record['currency']) <NEW_LINE> self.assertEqual(1000000000, record['quantity']) <NEW_LINE> self.assertAlmostEqual(6, record['coupon']) <NEW_LINE> self.assertEqual('2018-3-21', record['interest start day']) <NEW_LINE> self.assertEqual('2022-3-21', record['maturity']) <NEW_LINE> self.assertAlmostEqual(103.730688, record['average cost']) <NEW_LINE> self.assertAlmostEqual(101.599947, record['amortized cost']) <NEW_LINE> self.assertEqual(1037306880, record['total cost']) <NEW_LINE> self.assertAlmostEqual(6739726.03, record['accrued interest'], 2) <NEW_LINE> self.assertAlmostEqual(1022739195.71, record['total amortized cost'], 2) | DBANFB12014 Dragon Days Ltd 6.0%, the bond exists in both
portfolio 12229 and 12734. | 625941c0e1aae11d1e749c20 |
def p_tfpdef(self, p): <NEW_LINE> <INDENT> p1 = p[1] <NEW_LINE> kwargs = {'arg': p1.value, 'annotation': p[2]} <NEW_LINE> if PYTHON_VERSION_INFO >= (3, 5, 1): <NEW_LINE> <INDENT> kwargs.update({ 'lineno': p1.lineno, 'col_offset': p1.lexpos, }) <NEW_LINE> <DEDENT> p[0] = ast.arg(**kwargs) | tfpdef : name_tok colon_test_opt | 625941c015baa723493c3ede |
def load(self, obj, parent=None, public=True): <NEW_LINE> <INDENT> if isinstance(obj, str): <NEW_LINE> <INDENT> obj = Node.factory(obj).target <NEW_LINE> <DEDENT> objpackage = getattr(obj, '__package__', None) <NEW_LINE> for name in dir(obj): <NEW_LINE> <INDENT> if name == '__call__': <NEW_LINE> <INDENT> target = obj <NEW_LINE> name = type(obj).__name__ <NEW_LINE> <DEDENT> elif name.startswith('__' if not public else '_'): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> target = getattr(obj, name) <NEW_LINE> <DEDENT> targetpackage = getattr(target, '__package__', None) <NEW_LINE> if targetpackage and objpackage: <NEW_LINE> <INDENT> if not targetpackage.startswith(objpackage): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> if target == parent: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if callable(target): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> inspect.signature(target) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.add(target, name=name) <NEW_LINE> <DEDENT> continue <NEW_LINE> <DEDENT> node = Node(name, target) <NEW_LINE> if node.callables: <NEW_LINE> <INDENT> self.group(name).load(target, parent=obj) <NEW_LINE> <DEDENT> <DEDENT> return self | Load a Python object callables into sub-commands. | 625941c0cad5886f8bd26f44 |
def contains(self, item): <NEW_LINE> <INDENT> return self._search(item) is not None | Return True if this binary search tree contains the given item.
TODO: Best case running time: ??? under what conditions?
TODO: Worst case running time: ??? under what conditions? | 625941c0d6c5a10208143fb3 |
def test_create_valid_account(self): <NEW_LINE> <INDENT> self.session.execute_cmd("NEW") <NEW_LINE> self.session.execute_cmd("mark") <NEW_LINE> prompt = self.menutree.nodetext <NEW_LINE> self.assertEqual(self.default_node, "create_password") | Try to create an account. | 625941c0ad47b63b2c509eeb |
def promptForInputCategorical(message, options): <NEW_LINE> <INDENT> response = '' <NEW_LINE> options_list = ', '.join(options) <NEW_LINE> while response not in options: <NEW_LINE> <INDENT> response = input('{} ({}): '.format(message, options_list)) <NEW_LINE> <DEDENT> return response | Prompts for user input with limited number of options
:param message: Message displayed to the user
:param options: limited number of options.
Prompt will repeat until user input matches one of the provided options.
:return: user response | 625941c05f7d997b87174a00 |
def run(self,): <NEW_LINE> <INDENT> if not self.image_width or not self.image_height: <NEW_LINE> <INDENT> self.set_size() <NEW_LINE> <DEDENT> directory = os.path.abspath(self.image_path) <NEW_LINE> for file in os.listdir(directory): <NEW_LINE> <INDENT> filename = os.fsdecode(file) <NEW_LINE> if filename.endswith(".png"): <NEW_LINE> <INDENT> rgb_image = get_jpg_from_png_image(os.path.join( self.image_path, filename)) <NEW_LINE> new_file_name = os.path.splitext(filename)[0] + '.jpg' <NEW_LINE> decor_name = self.decor_data[ self.decor_data.file == filename]['decor'].values <NEW_LINE> decor_type = self.decor_data[ self.decor_data.file == filename]['type'].values <NEW_LINE> if decor_name: <NEW_LINE> <INDENT> new_file_path = os.path.join(self.path_to_jpg, decor_type[0], decor_name[0]) <NEW_LINE> if not os.path.exists(new_file_path): <NEW_LINE> <INDENT> os.makedirs(new_file_path) <NEW_LINE> <DEDENT> rgb_image.save(os.path.join(new_file_path, new_file_name)) | Create structures of folders and subfolders, convert image ans save this image. | 625941c08e7ae83300e4af37 |
def categorical_crossentropy(output, target, from_logits=False): <NEW_LINE> <INDENT> if not from_logits: <NEW_LINE> <INDENT> output /= tf.reduce_sum( output, axis=len(output.get_shape()) - 1, keep_dims=True) <NEW_LINE> epsilon = _to_tensor(_EPSILON, output.dtype.base_dtype) <NEW_LINE> output = tf.clip_by_value(output, epsilon, 1. - epsilon) <NEW_LINE> return -tf.reduce_sum( target * tf.log(output), axis=len(output.get_shape()) - 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return tf.nn.softmax_cross_entropy_with_logits( labels=target, logits=output) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> return tf.nn.softmax_cross_entropy_with_logits( logits=output, labels=target) | Categorical crossentropy between an output tensor
and a target tensor, where the target is a tensor of the same
shape as the output.
# TODO(rbharath): Should probably swap this over to tf mode. | 625941c0046cf37aa974ccb4 |
def create_recordset(self, zone, **attrs): <NEW_LINE> <INDENT> zone = self._get_resource(_zone.Zone, zone) <NEW_LINE> attrs.update({'zone_id': zone.id}) <NEW_LINE> return self._create(_rs.Recordset, prepend_key=False, **attrs) | Create a new recordset in the zone
:param zone: The value can be the ID of a zone
or a :class:`~otcextensions.sdk.dns.v2.zone.Zone` instance.
:param dict attrs: Keyword arguments which will be used to create
a :class:`~otcextensions.sdk.dns.v2.recordset.Recordset`,
comprised of the properties on the Recordset class.
:returns: The results of zone creation
:rtype: :class:`~otcextensions.sdk.dns.v2.recordset.Recordset` | 625941c01b99ca400220aa1c |
def set_data(self, items, checked_items): <NEW_LINE> <INDENT> self._icons = [self._make_icon(i + 1) for i in range(len(items))] <NEW_LINE> for item in items: <NEW_LINE> <INDENT> qitem = QStandardItem(item) <NEW_LINE> qitem.setFlags(~Qt.ItemIsEditable) <NEW_LINE> qitem.setData(qApp.palette().window(), Qt.BackgroundRole) <NEW_LINE> self._deselect_item(qitem) <NEW_LINE> self._items[item] = qitem <NEW_LINE> self.model.appendRow(qitem) <NEW_LINE> <DEDENT> self._selected = [item for item in checked_items if item in items] <NEW_LINE> for rank, item in enumerate(self._selected): <NEW_LINE> <INDENT> qitem = self._items[item] <NEW_LINE> self._select_item(qitem, rank) | Sets data and updates geometry.
Args:
items (Sequence(str)): All items.
checked_items (Sequence(str)): Initially checked items. | 625941c03539df3088e2e2b6 |
def parse_genotypes(variant, individuals, individual_positions): <NEW_LINE> <INDENT> genotypes = [] <NEW_LINE> for ind in individuals: <NEW_LINE> <INDENT> pos = individual_positions[ind["individual_id"]] <NEW_LINE> genotypes.append(parse_genotype(variant, ind, pos)) <NEW_LINE> <DEDENT> return genotypes | Parse the genotype calls for a variant
Args:
variant(cyvcf2.Variant)
individuals: List[dict]
individual_positions(dict)
Returns:
genotypes(list(dict)): A list of genotypes | 625941c04a966d76dd550f78 |
@listify <NEW_LINE> def prefix(iterable, prefix): <NEW_LINE> <INDENT> for item in iterable: <NEW_LINE> <INDENT> yield prefix + item | Prefix each item from the iterable with a prefix | 625941c0ff9c53063f47c15f |
def free(ds): <NEW_LINE> <INDENT> if isinstance(ds, TypeVar): <NEW_LINE> <INDENT> return [ds] <NEW_LINE> <DEDENT> elif isinstance(ds, Mono) and not isinstance(ds, Unit): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for x in ds.parameters: <NEW_LINE> <INDENT> result.extend(free(x)) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [] | Return the free variables (TypeVar) of a blaze type (Mono). | 625941c06fb2d068a760f006 |
def getPdg(name): <NEW_LINE> <INDENT> for (pdg, pname) in rOdd.items(): <NEW_LINE> <INDENT> if name == pname: <NEW_LINE> <INDENT> return abs(pdg) <NEW_LINE> <DEDENT> <DEDENT> for (pdg, pname) in rEven.items(): <NEW_LINE> <INDENT> if name == pname: <NEW_LINE> <INDENT> return abs(pdg) <NEW_LINE> <DEDENT> <DEDENT> return None | Convert a name to the pdg number according to the dictionaries rOdd and
rEven.
:type name: string
:returns: particle pdg; None, if name could not be resolved | 625941c0ac7a0e7691ed403b |
def __init__(self, username, password, pin, language="en"): <NEW_LINE> <INDENT> self._username = username <NEW_LINE> self._password = password <NEW_LINE> self._pin = pin <NEW_LINE> self._language = language <NEW_LINE> self._access_token = None <NEW_LINE> self._session_id = None <NEW_LINE> self._site_id = None <NEW_LINE> self._site_name = None <NEW_LINE> self._site_uuid = None <NEW_LINE> self._session = None <NEW_LINE> self._created_session = False | Initialize the object. | 625941c010dbd63aa1bd2b0f |
def minimax(state, depth, alpha, beta, MAXI, MINI): <NEW_LINE> <INDENT> if end_state(state) or depth == 0: <NEW_LINE> <INDENT> return [static_value(state, MAXI, MINI), ""] <NEW_LINE> <DEDENT> next_moves = get_all_next_moves(state, MAXI, MINI) <NEW_LINE> move = [] <NEW_LINE> if state[9] == MAXI: <NEW_LINE> <INDENT> for s in next_moves: <NEW_LINE> <INDENT> score = minimax(s, depth - 1, alpha, beta, MAXI, MINI)[0] <NEW_LINE> if score > alpha: <NEW_LINE> <INDENT> move = copy.deepcopy(s) <NEW_LINE> alpha = score <NEW_LINE> <DEDENT> if alpha >= beta: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> return [alpha, move] <NEW_LINE> <DEDENT> elif state[9] == MINI: <NEW_LINE> <INDENT> for s in next_moves: <NEW_LINE> <INDENT> score = minimax(s, depth - 1, alpha, beta, MAXI, MINI)[0] <NEW_LINE> if score < beta: <NEW_LINE> <INDENT> move = copy.deepcopy(s) <NEW_LINE> beta = score <NEW_LINE> <DEDENT> if alpha >= beta: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> return [beta, move] | Parameters
----------
state : list
A list of length 10, representing a particular state of the game.
depth : int
The depth of the search tree.
alpha : int
Alpha value.
beta : TYPE
Beta value.
MAXI : str
The Maximizer player.
MINI : str
The Minimizer player.
Returns
-------
list
Implements the minimax algorithm with alpha-beta pruning and
returns a list whose first index is the alpha/beta value of the game state
and the second index is another list representing the next state recommended
by the algorithm. | 625941c0d8ef3951e32434a8 |
def main(period, doc_type, borough, block, lot, *_): <NEW_LINE> <INDENT> if borough in BOROUGHS: <NEW_LINE> <INDENT> borough = BOROUGHS[borough] <NEW_LINE> <DEDENT> block = str(block).zfill(5) <NEW_LINE> lot = str(lot).zfill(4) <NEW_LINE> bbl = ''.join([borough, block, lot]) <NEW_LINE> bbldir = os.path.join('data', borough, block, lot) <NEW_LINE> try: <NEW_LINE> <INDENT> os.makedirs(bbldir) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> docname = PERIODS[(period, doc_type)] <NEW_LINE> filenames = os.listdir(bbldir) <NEW_LINE> nostatement_fname = 'nostatement.' + period + '.txt' <NEW_LINE> if (docname in filenames) or (docname.replace('.pdf', '.txt') in filenames): <NEW_LINE> <INDENT> LOGGER.info(u'Already downloaded "%s" for BBL %s, skipping', docname, bbl) <NEW_LINE> return <NEW_LINE> <DEDENT> elif docname + '.pdf' in filenames: <NEW_LINE> <INDENT> subprocess.check_call('mv "{bbldir}/{docname}.pdf" "{bbldir}/{docname}"'.format( bbldir=bbldir, docname=docname), shell=True) <NEW_LINE> LOGGER.info(u'Already downloaded "%s" for BBL %s, skipping (fixed path)', docname, bbl) <NEW_LINE> return <NEW_LINE> <DEDENT> elif nostatement_fname in filenames: <NEW_LINE> <INDENT> LOGGER.info(u'There is no "%s" for BBL %s, skipping', docname, bbl) <NEW_LINE> return <NEW_LINE> <DEDENT> url = 'https://nycprop.nyc.gov/nycproperty/StatementSearch?' + 'bbl={bbl}&stmtDate={period}&stmtType={doc_type}'.format( period=period, bbl=bbl, doc_type=doc_type) <NEW_LINE> filename = os.path.join(bbldir, docname) <NEW_LINE> LOGGER.info('Saving %s for %s', filename, bbl) <NEW_LINE> return subprocess.check_call( 'wget --no-check-certificate --max-redirect=0 -O "{filename}" "{url}" ' ' || (rm "{filename}" && touch "{nofilemarker}")'.format( filename=filename, url=url, nofilemarker=os.path.join(bbldir, nostatement_fname) ), shell=True) | Download a single tax bill | 625941c0a4f1c619b28affa9 |
def unmatched_existing_values(self, new_values, existing_values): <NEW_LINE> <INDENT> new_value_pks = map(lambda value: self.resolve_pk(value), new_values) <NEW_LINE> return filter(lambda value: self.resolve_key(value.pk) not in new_value_pks, existing_values) | Find existing values that do not match the new_values according to the result of resolve_pk. For obj._set operations, these unmatched values will need to be removed
:param new_values: values meant to replace the existing_values.
:param existing_values: The existing values of the attribute collections
:return: The unmatched existing values that will need to be removed | 625941c0a219f33f346288d7 |
def test_get_nonexistent_bucketlist(self): <NEW_LINE> <INDENT> url = '/bucketlists/10' <NEW_LINE> get_response = self.client.get(url, headers=self.headers) <NEW_LINE> self.assertEqual(get_response.status_code, 202) <NEW_LINE> self.assertIn("Bucketlist not found", get_response.data.decode()) | test get a non existant bucketlist | 625941c099fddb7c1c9de2fd |
def generate_cartesian_path(path, frame_id, time, commander, start_state=None, n_points=50, max_speed=np.pi/4): <NEW_LINE> <INDENT> pose_eef_approach = commander.get_fk(frame_id, start_state) <NEW_LINE> waypoints = [] <NEW_LINE> for num in range(n_points): <NEW_LINE> <INDENT> p = deepcopy(pose_eef_approach) <NEW_LINE> p.pose.position.x += float(path[0]*num)/n_points <NEW_LINE> p.pose.position.y += float(path[1]*num)/n_points <NEW_LINE> p.pose.position.z += float(path[2]*num)/n_points <NEW_LINE> waypoints.append(p) <NEW_LINE> <DEDENT> path = commander.get_ik(waypoints, start_state if start_state else commander.get_current_state()) <NEW_LINE> if path[0] is None: <NEW_LINE> <INDENT> return None, -1 <NEW_LINE> <DEDENT> trajectory = RobotTrajectory() <NEW_LINE> trajectory.joint_trajectory.joint_names = path[0].joint_state.name <NEW_LINE> old_joint_state = None <NEW_LINE> old_time_sec = float('inf') <NEW_LINE> jump_occurs = False <NEW_LINE> for num, state in enumerate(path): <NEW_LINE> <INDENT> time_sec = float(num*time)/len(path) <NEW_LINE> if state: <NEW_LINE> <INDENT> if old_time_sec < time_sec: <NEW_LINE> <INDENT> distance = (np.abs(old_joint_state-state.joint_state.position)%(np.pi))/(time_sec-old_time_sec) <NEW_LINE> jump_occurs = np.any(distance>max_speed) <NEW_LINE> <DEDENT> if not jump_occurs: <NEW_LINE> <INDENT> jtp = JointTrajectoryPoint() <NEW_LINE> jtp.positions = state.joint_state.position <NEW_LINE> jtp.time_from_start = rospy.Duration(time_sec) <NEW_LINE> trajectory.joint_trajectory.points.append(jtp) <NEW_LINE> old_joint_state = np.array(state.joint_state.position) <NEW_LINE> old_time_sec = time_sec <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> successrate = float(len(trajectory.joint_trajectory.points))/n_points <NEW_LINE> return trajectory, successrate | Generate a cartesian path of the end effector of "descent" meters where path = [x, y, z] wrt frame_id
move_group.compute_cartesian_path does not allow to start from anything else but the current state, use this instead
:param start_state: The start state to compute the trajectory from
:param path: [x, y, z] The vector to follow in straight line
:param n_points: The number of way points (high number will be longer to compute)
:param time: time of the overall motion
:param commander: Commander providing FK, IK and current state
:param max_speed: Maximum speed in rad/sec for each joint
:return: [rt, success_rate] a RobotTrajectory from the current pose and applying the given cartesian path to the
end effector and the success rate of the motion (-1 in case of total failure) | 625941c08a349b6b435e80de |
def merge(L1: list, L2: list) -> list: <NEW_LINE> <INDENT> newL = [] <NEW_LINE> i1 = 0 <NEW_LINE> i2 = 0 <NEW_LINE> while i1 != len(L1) and i2 != len(L2): <NEW_LINE> <INDENT> if L1[i1] <= L2[i2]: <NEW_LINE> <INDENT> newL.append(L1[i1]) <NEW_LINE> i1 += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> newL.append(L2[i2]) <NEW_LINE> i2 += 1 <NEW_LINE> <DEDENT> <DEDENT> newL.extend(L1[i1:]) <NEW_LINE> newL.extend(L2[i2:]) <NEW_LINE> return newL | Merge sorted lists L1 and L2 into a new list and return that new list.
>>> merge([1, 3, 4, 6], [1, 2, 5, 7])
[1, 1, 2, 3, 4, 5, 6, 7] | 625941c045492302aab5e22c |
def insert_after(self, other): <NEW_LINE> <INDENT> self.parent_collection.insert( self.parent_collection.index(other) + 1, self ) | Insert at index after `other`.
Args:
other: An instance of the same model to place `self` after. | 625941c0be7bc26dc91cd56f |
def main(opt): <NEW_LINE> <INDENT> clr = pickle.load(opt.model) <NEW_LINE> clr_info = pickle.load(opt.model) <NEW_LINE> D = np.loadtxt(opt.infile) <NEW_LINE> y = np.array(D[:, -1]) <NEW_LINE> if opt.ns: <NEW_LINE> <INDENT> X = D[:, :-(1 + N_NS)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> X = D[:, :-1] <NEW_LINE> <DEDENT> S = np.atleast_2d(D[:, -(1 + N_NS):-1]) <NEW_LINE> start_time = datetime.datetime.now() <NEW_LINE> start_utime = os.times()[0] <NEW_LINE> opt.start_time = start_time.isoformat() <NEW_LINE> logger.info("start time = " + start_time.isoformat()) <NEW_LINE> p = clr.predict_proba(X) <NEW_LINE> n = 0 <NEW_LINE> m = 0 <NEW_LINE> for i in xrange(p.shape[0]): <NEW_LINE> <INDENT> c = np.argmax(p[i, :]) <NEW_LINE> opt.outfile.write("%d %d " % (y[i], c)) <NEW_LINE> opt.outfile.write(" ".join(S[i, :].astype(str)) + " ") <NEW_LINE> opt.outfile.write(str(p[i, 0]) + " " + str(p[i, 1]) + "\n") <NEW_LINE> n += 1 <NEW_LINE> m += 1 if c == y[i] else 0 <NEW_LINE> <DEDENT> end_time = datetime.datetime.now() <NEW_LINE> end_utime = os.times()[0] <NEW_LINE> logger.info("end time = " + end_time.isoformat()) <NEW_LINE> opt.end_time = end_time.isoformat() <NEW_LINE> logger.info("elapsed_time = " + str((end_time - start_time))) <NEW_LINE> opt.elapsed_time = str((end_time - start_time)) <NEW_LINE> logger.info("elapsed_utime = " + str((end_utime - start_utime))) <NEW_LINE> opt.elapsed_utime = str((end_utime - start_utime)) <NEW_LINE> opt.nos_samples = n <NEW_LINE> logger.info('nos_samples = ' + str(opt.nos_samples)) <NEW_LINE> opt.nos_correct_samples = m <NEW_LINE> logger.info('nos_correct_samples = ' + str(opt.nos_correct_samples)) <NEW_LINE> opt.accuracy = m / float(n) <NEW_LINE> logger.info('accuracy = ' + str(opt.accuracy)) <NEW_LINE> opt.negative_mean_prob = np.mean(p[:, 0]) <NEW_LINE> logger.info('negative_mean_prob = ' + str(opt.negative_mean_prob)) <NEW_LINE> opt.positive_mean_prob = np.mean(p[:, 1]) <NEW_LINE> logger.info('positive_mean_prob = ' + str(opt.positive_mean_prob)) <NEW_LINE> if opt.info: <NEW_LINE> <INDENT> for key in clr_info.keys(): <NEW_LINE> <INDENT> opt.outfile.write("#classifier_%s=%s\n" % (key, str(clr_info[key]))) <NEW_LINE> <DEDENT> for key, key_val in vars(opt).iteritems(): <NEW_LINE> <INDENT> opt.outfile.write("#%s=%s\n" % (key, str(key_val))) <NEW_LINE> <DEDENT> <DEDENT> if opt.infile != sys.stdin: <NEW_LINE> <INDENT> opt.infile.close() <NEW_LINE> <DEDENT> if opt.outfile != sys.stdout: <NEW_LINE> <INDENT> opt.outfile.close() <NEW_LINE> <DEDENT> if opt.model != sys.stdout: <NEW_LINE> <INDENT> opt.model.close() <NEW_LINE> <DEDENT> sys.exit(0) | Main routine that exits with status code 0
| 625941c055399d3f0558861e |
def is_state_valid(self, state): <NEW_LINE> <INDENT> is_valid = True <NEW_LINE> split = state.split(",") <NEW_LINE> is_valid = is_valid and len(split) == 3 <NEW_LINE> is_valid = is_valid and bool(re.findall("continue|loss|win", split[0])) <NEW_LINE> is_valid = is_valid and bool(re.match("[0-9 ]+", split[1])) <NEW_LINE> is_valid = is_valid and bool(re.match("^[0-8HMBX/ ]+$", split[2])) <NEW_LINE> return is_valid | Checks if state string is valid.
:return: True if valid else False | 625941c0aad79263cf3909a9 |
def skip_on_devices(*disabled_devices): <NEW_LINE> <INDENT> def skip(test_method): <NEW_LINE> <INDENT> @functools.wraps(test_method) <NEW_LINE> def test_method_wrapper(self, *args, **kwargs): <NEW_LINE> <INDENT> device = FLAGS.jax_test_dut or xla_bridge.get_backend().platform <NEW_LINE> if device in disabled_devices: <NEW_LINE> <INDENT> test_name = getattr(test_method, '__name__', '[unknown test]') <NEW_LINE> raise SkipTest('{} not supported on {}.' .format(test_name, device.upper())) <NEW_LINE> <DEDENT> return test_method(self, *args, **kwargs) <NEW_LINE> <DEDENT> return test_method_wrapper <NEW_LINE> <DEDENT> return skip | A decorator for test methods to skip the test on certain devices. | 625941c082261d6c526ab407 |
def allowTypes(self, *types): <NEW_LINE> <INDENT> for typ in types: <NEW_LINE> <INDENT> if not isinstance(typ, str): <NEW_LINE> <INDENT> typ = qual(typ) <NEW_LINE> <DEDENT> self.allowedTypes[typ] = 1 | SecurityOptions.allowTypes(typeString): Allow a particular type, by its
name. | 625941c0cad5886f8bd26f45 |
def common_req(self, execute, send_body=True): <NEW_LINE> <INDENT> self._SERVER = {'CLIENT_ADDR_HOST': self.client_address[0], 'CLIENT_ADDR_PORT': self.client_address[1]} <NEW_LINE> self._to_log = True <NEW_LINE> self._cmd = None <NEW_LINE> self._payload = None <NEW_LINE> self._path = None <NEW_LINE> self._payload_params = None <NEW_LINE> self._query_params = {} <NEW_LINE> self._fragment = None <NEW_LINE> (cmd, res, req) = (None, None, None) <NEW_LINE> try: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> path = self._pathify() <NEW_LINE> cmd = path[1:] <NEW_LINE> res = execute(cmd) <NEW_LINE> <DEDENT> except HttpReqError as e: <NEW_LINE> <INDENT> e.report(self) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.send_exception(500) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> raise <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not isinstance(res, HttpResponse): <NEW_LINE> <INDENT> req = self.build_response() <NEW_LINE> if send_body: <NEW_LINE> <INDENT> req.add_data(res) <NEW_LINE> <DEDENT> req.set_send_body(send_body) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> req = res <NEW_LINE> <DEDENT> self.end_response(req) <NEW_LINE> <DEDENT> <DEDENT> except socket.error as e: <NEW_LINE> <INDENT> if e.errno in (errno.ECONNRESET, errno.EPIPE): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> LOG.exception("exception - cmd=%r - method=%r", cmd, self.command) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> LOG.exception("exception - cmd=%r - method=%r", cmd, self.command) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> del req, res | Common code for GET and POST requests | 625941c00383005118ecf54f |
def get_nom(self, nombre): <NEW_LINE> <INDENT> if nombre <= 0: <NEW_LINE> <INDENT> raise ValueError("le nombre {} est négatif ou nul".format(nombre)) <NEW_LINE> <DEDENT> if nombre == 1: <NEW_LINE> <INDENT> return self.nom_singulier <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> nombre = get_nom_nombre(nombre) <NEW_LINE> return nombre + " " + self.nom_pluriel | Retourne le nom singulier ou pluriel. | 625941c05166f23b2e1a50c4 |
def iter_tree(jottapath, JFS): <NEW_LINE> <INDENT> filedirlist = JFS.getObject('%s?mode=list' % jottapath) <NEW_LINE> logging.debug("got tree: %s", filedirlist) <NEW_LINE> if not isinstance(filedirlist, JFSFileDirList): <NEW_LINE> <INDENT> yield ( '', tuple(), tuple() ) <NEW_LINE> <DEDENT> for folder in filedirlist.tree(): <NEW_LINE> <INDENT> logging.debug(folder) <NEW_LINE> yield folder, tuple(folder.folders()), tuple(folder.files()) | Get a tree of of files and folders. use as an iterator, you get something like os.walk | 625941c076e4537e8c3515dc |
def convert_celsius_to_fahrenheit(deg_celsius): <NEW_LINE> <INDENT> return (9/5) * deg_celsius + 32 | Convert degress celsius to fahrenheit
Returns float value - temp in fahrenheit
Keyword arguments:
def_celcius -- temp in degrees celsius | 625941c07d43ff24873a2c0a |
def __init__(self, topname, trajname=None, frame_start=0): <NEW_LINE> <INDENT> FrameReader.__init__(self, topname, trajname, frame_start) <NEW_LINE> try: <NEW_LINE> <INDENT> import mdtraj <NEW_LINE> <DEDENT> except ImportError as e: <NEW_LINE> <INDENT> if "scipy" in repr(e): <NEW_LINE> <INDENT> e.msg = "The MDTraj FrameReader also requires Scipy" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> e.msg = "The MDTraj FrameReader requires the module MDTraj (and probably Scipy)" <NEW_LINE> <DEDENT> raise <NEW_LINE> <DEDENT> logger.warning("WARNING: Using MDTraj which renames solvent molecules") <NEW_LINE> try: <NEW_LINE> <INDENT> if trajname is None: <NEW_LINE> <INDENT> self._traj = mdtraj.load(topname) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._traj = mdtraj.load(trajname, top=topname) <NEW_LINE> <DEDENT> <DEDENT> except OSError as e: <NEW_LINE> <INDENT> if not os.path.isfile(topname): <NEW_LINE> <INDENT> raise FileNotFoundError(topname) from e <NEW_LINE> <DEDENT> if trajname is not None and not os.path.isfile(trajname): <NEW_LINE> <INDENT> raise FileNotFoundError(trajname) from e <NEW_LINE> <DEDENT> if "no loader for filename" in repr(e): <NEW_LINE> <INDENT> raise UnsupportedFormatException from e <NEW_LINE> <DEDENT> e.args = ("Error opening file '{0}' or '{1}'".format(topname, trajname),) <NEW_LINE> raise <NEW_LINE> <DEDENT> self.num_atoms = self._traj.n_atoms <NEW_LINE> self.num_frames = self._traj.n_frames | Open input XTC file from which to read coordinates using mdtraj library.
:param topname: GROMACS GRO file from which to read topology
:param trajname: GROMACS XTC file to read subsequent frames | 625941c0596a897236089a2e |
def renormalize_binary_logits(a, b): <NEW_LINE> <INDENT> norm = elementwise_logsumexp(a, b) <NEW_LINE> return a - norm, b - norm | Normalize so exp(a) + exp(b) == 1 | 625941c0cb5e8a47e48b7a18 |
def __init__(self, profile: Optional[object] = None, branch: Optional[str] = 'master'): <NEW_LINE> <INDENT> super().__init__(profile, branch) <NEW_LINE> self.utils = Utils() | Initialize Class properties. | 625941c0460517430c3940f6 |
def getInputDim(self): <NEW_LINE> <INDENT> r <NEW_LINE> return sum(self.attribSize) | Size of the latent vector given by self.buildRandomCriterionTensor | 625941c0a8ecb033257d3039 |
def test_log_fail(self): <NEW_LINE> <INDENT> self.logger.open_test_case(self.some_test_case_id) <NEW_LINE> self.logger.log_fail(self.some_log_fail_msg) <NEW_LINE> self.virtual_file.seek(0) <NEW_LINE> self.assertRegexpMatches(self.virtual_file.readline(), LOGGER_PREAMBLE + re.escape("open test case,,,Test case "+self.some_test_case_id+"\r\n")) <NEW_LINE> self.assertRegexpMatches(self.virtual_file.readline(), LOGGER_PREAMBLE + re.escape("fail,,,"+self.some_log_fail_msg+"\r\n")) | Given: FuzzLoggerCsv with a virtual file handle.
When: Calling open_test_case with some test_case_id.
and: Calling log_fail with some description.
Then: open_test_case logs as expected.
and: log_fail logs as expected. | 625941c0d4950a0f3b08c2bc |
@linter.register <NEW_LINE> @with_matched_tokens(start=match_regex("^using$"), end=match_regex("^=$"), length=3) <NEW_LINE> def alias_names(source, *, match): <NEW_LINE> <INDENT> alias_token = match[1] <NEW_LINE> alias = alias_token.value <NEW_LINE> if alias == "is_transparent": <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not alias[0].isupper(): <NEW_LINE> <INDENT> yield Error(message="Alias '{}' should be capitalized".format(alias), tokens=[alias_token]) <NEW_LINE> <DEDENT> if not alias.endswith("_t"): <NEW_LINE> <INDENT> yield Error(message="Alias '{}' should end with '_t'".format(alias), tokens=[alias_token]) | Flag type aliases that don't adhere to the naming conventions. | 625941c015fb5d323cde0a78 |
def can_nodes_fuse(v1, v2, glycan1, glycan2): <NEW_LINE> <INDENT> if v1 * v2 < 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> elif v1 == -1 and v2 == -1: <NEW_LINE> <INDENT> root_sugar1, root_bond1 = get_root_bond(glycan1) <NEW_LINE> root_sugar2, root_bond2 = get_root_bond(glycan2) <NEW_LINE> same_root_bond = root_bond1 == root_bond2 <NEW_LINE> same_root_sugar = glycan1.names[root_sugar1] == glycan2.names[root_sugar2] <NEW_LINE> return same_root_bond and same_root_sugar <NEW_LINE> <DEDENT> bond_to_node1 = {}; bond_to_node2 = {} <NEW_LINE> for v in glycan1.bonds[v1]: <NEW_LINE> <INDENT> bond_to_node1[glycan1.bonds[v1][v]] = v <NEW_LINE> <DEDENT> for v in glycan2.bonds[v2]: <NEW_LINE> <INDENT> bond_to_node2[glycan2.bonds[v2][v]] = v <NEW_LINE> <DEDENT> for bond1 in bond_to_node1: <NEW_LINE> <INDENT> for bond2 in bond_to_node2: <NEW_LINE> <INDENT> same_carbon = bond1[1] == bond2[1] <NEW_LINE> if same_carbon: <NEW_LINE> <INDENT> v1_adj = bond_to_node1[bond1] <NEW_LINE> v2_adj = bond_to_node2[bond2] <NEW_LINE> v1_adj_name = glycan1.names[v1_adj] if v1_adj >= 0 else 'root' <NEW_LINE> v2_adj_name = glycan2.names[v2_adj] if v2_adj >= 0 else 'root' <NEW_LINE> if v1_adj_name != v2_adj_name: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return True | Checks immediate neighbors of v1 in glycan1 and v2 in glycan2
to verify they can fuse. O(1) run time, since maximum degree
is limited by sugar carbon count. | 625941c0d7e4931a7ee9de88 |
def new_model(self): <NEW_LINE> <INDENT> BASE_PATH = reduce(lambda l, r: l + os.path.sep + r, os.path.dirname(os.path.realpath(__file__)).split(os.path.sep)[:-1]) <NEW_LINE> dataPath = os.path.join(BASE_PATH, "data") | Just calls load_model without a filename
to create a new model. | 625941c0d486a94d0b98e0b0 |
def __init__( self, cursor: SnowflakeCursor, rows: list[bytes], stream_buffer_size: int = 1024 * 1024 * 10, ): <NEW_LINE> <INDENT> self.cursor = cursor <NEW_LINE> self.rows = rows <NEW_LINE> self._stream_buffer_size = stream_buffer_size <NEW_LINE> self.stage_path = f"@{self._STAGE_NAME}/{uuid.uuid4().hex}" | Construct an agent that uploads binding parameters as CSV files to a temporary stage.
Args:
cursor: The cursor object.
rows: Rows of binding parameters in CSV format.
stream_buffer_size: Size of each file, default to 10MB. | 625941c0293b9510aa2c3203 |
def adapt_datetime(ts): <NEW_LINE> <INDENT> return time.mktime(ts.timetuple()) | Internet says I need dis | 625941c0d6c5a10208143fb4 |
def cleanup(self): <NEW_LINE> <INDENT> if self._temp_dir: <NEW_LINE> <INDENT> self.logger.debug("Deleting temporary directory '%s'" % self._temp_dir) <NEW_LINE> shutil.rmtree(path=self._temp_dir, ignore_errors=True) <NEW_LINE> self._temp_dir = None | Cleanup any resources used by this command. | 625941c0167d2b6e31218b01 |
def __repr__(self): <NEW_LINE> <INDENT> out = "<%s(" % (self.__class__.__name__) <NEW_LINE> fields = [] <NEW_LINE> fields.append("filename=%r" % (self.filename)) <NEW_LINE> fields.append("auto_remove=%r" % (self.auto_remove)) <NEW_LINE> fields.append("appname=%r" % (self.appname)) <NEW_LINE> fields.append("verbose=%r" % (self.verbose)) <NEW_LINE> fields.append("base_dir=%r" % (self.base_dir)) <NEW_LINE> fields.append("use_stderr=%r" % (self.use_stderr)) <NEW_LINE> fields.append("initialized=%r" % (self.initialized)) <NEW_LINE> fields.append("simulate=%r" % (self.simulate)) <NEW_LINE> fields.append("timeout=%r" % (self.timeout)) <NEW_LINE> out += ", ".join(fields) + ")>" <NEW_LINE> return out | Typecasting into a string for reproduction. | 625941c05fcc89381b1e1628 |
def browse(self, destination_name, cnt=100, jms_correlation_id=None, jms_type=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> msg = 'destination_name:{0}, count:{1}, jms_correlation_id:{2}, jms_type:{3}'.format( destination_name, cnt, jms_correlation_id, jms_type) <NEW_LINE> self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_jms_browsing', msg), self._mh.fromhere()) <NEW_LINE> if (not self._is_connected): <NEW_LINE> <INDENT> self._mh.demsg('htk_on_warning', self._mh._trn.msg( 'htk_jms_not_connected'), self._mh.fromhere()) <NEW_LINE> return None <NEW_LINE> <DEDENT> ev = event.Event('jms_before_browse', destination_name, cnt) <NEW_LINE> if (self._mh.fire_event(ev) > 0): <NEW_LINE> <INDENT> destination_name = ev.argv(0) <NEW_LINE> cnt = ev.argv(1) <NEW_LINE> jms_correlation_id = ev.argv(2) <NEW_LINE> jms_type = ev.argv(3) <NEW_LINE> <DEDENT> if (ev.will_run_default()): <NEW_LINE> <INDENT> receiver = self._client.create_receiver( 'queue://{0}'.format(destination_name), options=Copy()) <NEW_LINE> msgs = [] <NEW_LINE> i = 0 <NEW_LINE> while (i < cnt): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> msg = receiver.receive(timeout=1) <NEW_LINE> receiver.accept() <NEW_LINE> correlation_id = None <NEW_LINE> type = None <NEW_LINE> for key, value in msg.properties.items(): <NEW_LINE> <INDENT> if (key == 'properties.correlation-id'): <NEW_LINE> <INDENT> correlation_id = value <NEW_LINE> <DEDENT> elif (key == 'message-annotations.x-opt-jms-type'): <NEW_LINE> <INDENT> type = value <NEW_LINE> <DEDENT> <DEDENT> if ((jms_correlation_id == None or jms_correlation_id == correlation_id) and (jms_type == None or jms_type == type)): <NEW_LINE> <INDENT> msgs.append(msg) <NEW_LINE> i = i + 1 <NEW_LINE> <DEDENT> <DEDENT> except Timeout: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> receiver.close() <NEW_LINE> messages = [] <NEW_LINE> for msg in msgs: <NEW_LINE> <INDENT> message = {} <NEW_LINE> message['message'] = msg.body <NEW_LINE> for key, value in msg.properties.items(): <NEW_LINE> <INDENT> if (key in mapping.values()): <NEW_LINE> <INDENT> message[ list(mapping.keys())[list(mapping.values()).index(key)]] = value <NEW_LINE> <DEDENT> <DEDENT> messages.append(message) <NEW_LINE> <DEDENT> <DEDENT> self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_jms_msg_received', len(messages)), self._mh.fromhere()) <NEW_LINE> ev = event.Event('jms_after_browse') <NEW_LINE> self._mh.fire_event(ev) <NEW_LINE> return messages <NEW_LINE> <DEDENT> except ProtonException as ex: <NEW_LINE> <INDENT> self._mh.demsg('htk_on_error', ex, self._mh.fromhere()) <NEW_LINE> return None | Method browses queue
Args:
destination_name (str): queue name
cnt (int): count of messages
jms_correlation_id (str): requested JMSCorrelationID
jms_type (str): requested JMSType
Returns:
list: messages as dictionary {'message', JMS headers}
Raises:
event: jms_before_browse
event: jms_after_browse | 625941c056ac1b37e626413f |
def get_player_ids(self) -> List[str]: <NEW_LINE> <INDENT> return [x.player_id for x in self.player_list] | Collect user ids from a list of players | 625941c05fdd1c0f98dc019e |
def test_new_user_email_normalized(self): <NEW_LINE> <INDENT> email = 'test@SNACKYS.COM' <NEW_LINE> user = get_user_model().objects.create_user(email, 'test123') <NEW_LINE> self.assertEqual(user.email, email.lower()) | Test the email for a new user is normalized | 625941c030c21e258bdfa407 |
def forward(self, context, h, x): <NEW_LINE> <INDENT> x = self.embeds(x) <NEW_LINE> context = context.squeeze() <NEW_LINE> prob = self.p_gen(torch.cat((context, h[-1], x), dim=1)) <NEW_LINE> return F.sigmoid(prob) | :param context: (batch, hidden_size) attention vector
:param h: (n_layer, batch, hidden_size) decoder state
:param x: (batch, embedding_size) decoder input
:return: generation probability | 625941c04527f215b584c3c5 |
def get_available_letters(letters_guessed): <NEW_LINE> <INDENT> choices_left = list("abcdefghijklmnopqrstuvwxyz") <NEW_LINE> for letter in letters_guessed: <NEW_LINE> <INDENT> if letter in choices_left: <NEW_LINE> <INDENT> choices_left.remove(letter) <NEW_LINE> <DEDENT> <DEDENT> return choices_left | lettersGuessed: list of letters that have been guessed so far
returns: string, comprised of letters that represents what letters have not
yet been guessed. | 625941c023849d37ff7b2ffc |
def delete_by_id(model, value): <NEW_LINE> <INDENT> session = get_session() <NEW_LINE> session.delete(session.query(model).filter_by(ID=value).first()) <NEW_LINE> session.commit() <NEW_LINE> session.close() <NEW_LINE> pass | 根据条件删除记录
:param model:
:param value:
:return: | 625941c01f5feb6acb0c4abf |
def update(self, x=None, update_model=False): <NEW_LINE> <INDENT> if update_model: <NEW_LINE> <INDENT> self.model.update() <NEW_LINE> <DEDENT> if self.is_stack_of_tasks(): <NEW_LINE> <INDENT> for hard_task in self.tasks: <NEW_LINE> <INDENT> for soft_task in hard_task: <NEW_LINE> <INDENT> soft_task.update(x=x, update_model=False) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if self._enabled: <NEW_LINE> <INDENT> self._update(x=x) <NEW_LINE> <DEDENT> <DEDENT> for constraint in self.constraints: <NEW_LINE> <INDENT> constraint.update() | Compute the A matrix and b vector that will be used by the task solver.
Args:
x (np.array[float], None): variables that are being optimized.
update_model (bool): if True, it will update the model before updating each task. | 625941c060cbc95b062c64ae |
def goal_pose_cb(self, msg_curr_pose, msg_goal_pose: PoseStamped): <NEW_LINE> <INDENT> with self.lock: <NEW_LINE> <INDENT> if self.graph is None: <NEW_LINE> <INDENT> self.get_logger().warn( 'Got goal pose, but the map was not received yet!') <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> self.lock.acquire() <NEW_LINE> if USE_ODOM: <NEW_LINE> <INDENT> robot_pose = Pose2D( x=msg_curr_pose.pose.pose.position.x, y=msg_curr_pose.pose.pose.position.y, theta=utils.quaternionToYaw( msg_curr_pose.pose.pose.orientation)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> robot_pose = Pose2D( x=msg_curr_pose.pose.position.x, y=msg_curr_pose.pose.position.y, theta=utils.quaternionToYaw(msg_curr_pose.pose.orientation)) <NEW_LINE> <DEDENT> start_position_px = utils.meter2cell(Point2D(x=robot_pose.x, y=robot_pose.y), self.map_origin, self.map_resolution) <NEW_LINE> start_pt = MapPoint(start_position_px.x, start_position_px.y) <NEW_LINE> goal_position_px = utils.meter2cell( Point2D(x=msg_goal_pose.pose.position.x, y=msg_goal_pose.pose.position.y), self.map_origin, self.map_resolution) <NEW_LINE> goal_pt = MapPoint(goal_position_px.x, goal_position_px.y) <NEW_LINE> path = self.doSearch(start_pt, goal_pt, SearchMethods.A_STAR) <NEW_LINE> if path is not None: <NEW_LINE> <INDENT> if DEBUG: <NEW_LINE> <INDENT> self.get_logger().debug('Showing final searched map') <NEW_LINE> self.graph.showGraph(self.dbg_img_pub, self.get_clock().now().to_msg(), 'map') <NEW_LINE> time.sleep(2.0) <NEW_LINE> self.get_logger().debug('Showing final path') <NEW_LINE> self.graph.showPath(path, self.get_logger(), self.dbg_img_pub, self.get_clock().now().to_msg(), 'map') <NEW_LINE> <DEDENT> path_to_publish = Path() <NEW_LINE> path_to_publish.header.stamp = self.get_clock().now().to_msg() <NEW_LINE> path_to_publish.header.frame_id = 'map' <NEW_LINE> for node in path: <NEW_LINE> <INDENT> curr_target = utils.cell2meter(Point2D(node.x, node.y), self.map_origin, self.map_resolution) <NEW_LINE> pose = PoseStamped() <NEW_LINE> pose.header.stamp = path_to_publish.header.stamp <NEW_LINE> pose.header.frame_id = path_to_publish.header.frame_id <NEW_LINE> pose.pose.position.x = curr_target.x <NEW_LINE> pose.pose.position.y = curr_target.y <NEW_LINE> pose.pose.position.z = 0.0 <NEW_LINE> pose.pose.orientation = Quaternion(x=0., y=0., z=0., w=1.0) <NEW_LINE> path_to_publish.poses.append(pose) <NEW_LINE> <DEDENT> self.path_pub.publish(path_to_publish) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.get_logger().warn( 'There is no solution for the specified problem!') <NEW_LINE> <DEDENT> self.graph = Graph(self.occgrid, debug_mode=DEBUG) <NEW_LINE> self.lock.release() | Given a the robot current and target/goal poses, compute the path from
the starting pose to the goal pose. We are only considering positions. | 625941c021a7993f00bc7c58 |
def __init__(self, error=None, metadata=None, orders=None, success=None, warning=None): <NEW_LINE> <INDENT> self._error = None <NEW_LINE> self._metadata = None <NEW_LINE> self._orders = None <NEW_LINE> self._success = None <NEW_LINE> self._warning = None <NEW_LINE> self.discriminator = None <NEW_LINE> if error is not None: <NEW_LINE> <INDENT> self.error = error <NEW_LINE> <DEDENT> if metadata is not None: <NEW_LINE> <INDENT> self.metadata = metadata <NEW_LINE> <DEDENT> if orders is not None: <NEW_LINE> <INDENT> self.orders = orders <NEW_LINE> <DEDENT> if success is not None: <NEW_LINE> <INDENT> self.success = success <NEW_LINE> <DEDENT> if warning is not None: <NEW_LINE> <INDENT> self.warning = warning | EmailOrdersResponse - a model defined in Swagger | 625941c0d268445f265b4dda |
def can_support_nonorthogonal_axes(self) -> bool: <NEW_LINE> <INDENT> return self._nonorthogonal_axes_supported | Return boolean indicating if the current slice selection can support nonorthogonal viewing.
Both display axes must be spatial for this to be supported. | 625941c08c3a873295158323 |
def add_tempo(self, track, time, tempo): <NEW_LINE> <INDENT> self.tracks[track].addTempo(time, tempo) | Add a tempo event.
Use:
MyMIDI.addTempo(track, time, tempo)
Arguments:
track: The track to which the event is added. [Integer, 0-127].
time: The time at which the event is added, in beats. [Float].
tempo: The tempo, in Beats per Minute. [Integer] | 625941c0d486a94d0b98e0b1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.