id stringlengths 24 28 | content stringlengths 121 2.08k |
|---|---|
codereview_python_data_8712 | @pytest.fixture()
def plot_data(self, psa):
- # TODO: Which one is needed? Passes with any one!
psa.run(metric='hausdorff')
psa.run(metric='discrete_frechet')
return psa.plot()
`isinstance` is probably more appropriate than `type(...) is ...`.
@pytest.fixture()
de... |
codereview_python_data_8714 | "Focus follows new flows."
)
loader.add_option(
- "filter_active", bool, False,
"Toggle whether the view filter is enabled."
)
Let's call this `view_filter_active` please so that it's symmetric with `intercept` and `intercept_active`.
"Focus... |
codereview_python_data_8721 | if testcase.regression.startswith('0:'):
# If the regression range starts from the start of time,
- # then we assume that the bug impacts extended stable.
- new_impact = data_types.SecurityImpact.EXTENDED_STABLE
elif testcase.is_impact_set_flag:
# Add impact label based on testcase's impact value.... |
codereview_python_data_8723 | mask_lower = x < lower
mask_upper = upper < x
mask = tf.logical_or(mask_lower, mask_upper)
- mask = tf.cast(mask, tf.float32)
return x * mask
I think we have to do ```python x = tf.convert_to_tensor(x) ... mask = tf.cast(mask, x.dtype) ```
mask_lower = x < lower
mask_upper = upper < x... |
codereview_python_data_8735 | def test_defaults_replacement(self, klass, monkeypatch):
configtypes.FontBase.set_defaults(['Terminus'], '23pt')
- expected = '23pt Terminus'
- assert klass().to_py('23pt default_family') == expected
class TestFontFamily:
```suggestion assert klass().to_py('23pt default_family') == '23pt T... |
codereview_python_data_8736 | import MDAnalysis.lib.log
import pytest
from MDAnalysis.lib.log import _set_verbose
-from numpy.testing import assert_, assert_equal, assert_raises
def test_start_stop_logging():
`assert_` and `assert_raises` should not be used.
import MDAnalysis.lib.log
import pytest
from MDAnalysis.lib.log import _set_verbos... |
codereview_python_data_8747 | Only callables that accept one argument (:meth:`~nvidia.dali.types.SampleInfo` objects that
represent the index of the requested sample) can be used as ``source`` when ``parallel`` is
set to True. It can be a function or an object implementing ``__call__`` operator, which
- allows to add some initial ... |
codereview_python_data_8748 | def do_transform(self, x, is_y):
h,w,*_ = x.shape
intpr = cv2.INTER_AREA
- if(is_y < min(h, w)) : intpr = cv2.INTER_LINEAR
if is_y: return scale_min(x, self.sz_y, intpr if self.tfm_y == TfmType.PIXEL else cv2.INTER_NEAREST)
else : return scale_min(x, self.sz, intpr)
I... |
codereview_python_data_8771 | if source == target:
if source not in G:
- raise nx.NodeNotFound(
- f"Source {source} or target {target} not in G".format(source, target)
- )
return 0
weight = _weight_function(G, weight)
length = _dijkstra(G, source, weight, target=target)
This sho... |
codereview_python_data_8777 | def test_atomtype_alignment(self):
result_line = ("ATOM 1 H5T GUA R 1 7.974 6.430 9.561"
- " 1.00 0.00 RNAA H 0\n")
assert_equal(self.writtenstuff[4], result_line)
A test with a negative charge would be nice. But it should go in an other test method... |
codereview_python_data_8787 | await self._save_and_refresh_item(file_path, Adversary, final, allowed)
stored_adv = await self._services.get('data_svc').locate('adversaries', dict(adversary_id=final["id"]))
for a in stored_adv:
- a.has_repeatable_abilities = a.check_repeatable_abilities(self.get_service('data_sv... |
codereview_python_data_8788 | <h1>Error 503 Backend is unhealthy</h1>
<p>Backend is unhealthy</p>
<h3>Guru Mediation:</h3>
- <p>Details: cache-sea4451-SEA 1645523408 3341736689</p>
<hr>
<p>Varnish cache server</p>
</body>
If you did the naming change above, this should also be changed: ``` KEY_AGE_MORE_THAN_MAX_AGE =... |
codereview_python_data_8789 | line = line.split()
atomids[i]= line[0]
names[i] = line[1]
- types[i] = str(line[5])
bonded_atoms = line[6:]
for other_atom in bonded_atoms:
other_atom = int(other_atom) - 1
Str call isn't needed
... |
codereview_python_data_8790 | return {}
with open(metadata_file_path) as handle:
- return handle.read()
def get_all_issue_metadata(fuzz_target_path):
For consistency with the other return value ({}) in this function on line 453, and other get_* functions, this should return the parsed value (i.e. the dictionary). Something like this (w... |
codereview_python_data_8815 | return global_params.iteritems()
-_event_callbacks = {}
class Task(object):
__metaclass__ = Register
I think this should go into the Task class.
return global_params.iteritems()
class Task(object):
__metaclass__ = Register |
codereview_python_data_8818 | ----------
g : DGLGraph
The graph.
- node_feats : torch.Tensor
- The input node feature of shape :math:`(N_{in}, node_in_feats)`
- where :math:`N_{in}` is the number of source nodes.
edge_feats : torch.Tensor
The input edge feature of sha... |
codereview_python_data_8824 | """
h_rel = self.rel_emb(rels)
proj_rel = self.rel_project(rels).reshape(-1, self.nfeats, self.rfeats)
- h_head = torch.einsum('ab,abc->ac', h_head, proj_rel)
- h_tail = torch.einsum('ab,abc->ac', h_tail, proj_rel)
return - torch.norm(h_head + h_rel - h_tail, p=self.p, ... |
codereview_python_data_8829 | # No need to pad.
return
- if last_date is pd.NaT:
# If there is no data, determine how many days to add so that
# desired days are written to the correct slots.
days_to_zerofill = tds[tds.slice_indexer(end=date)]
How about `pd.isnull(last_date)`?... |
codereview_python_data_8830 | plot_opts = Keywords(['plot_opt1', 'plot_opt2']+custom_plot, name)
opt_groups = {'plot': Options(allowed_keywords=plot_opts),
'style': Options(allowed_keywords=style_opts),
- 'output':Options(allowed_keywords=['backend'])}
Store._options[backend][na... |
codereview_python_data_8837 | LQTY_ADDR = string_to_ethereum_address('0x063c26fF1592688B73d8e2A18BA4C23654e2792E')
LQTY_PROXY = string_to_ethereum_address('0x9476832d4687c14b2c1a04E2ee4693162a7340B6')
-ADDR_NOT_IN_LIQUITY = '0xA0446D8804611944F1B527eCD37d7dcbE442caba'
liquity_mocked_historical_prices = {
A_ETH: {
what do you mean by addres... |
codereview_python_data_8839 | mode_manager = objreg.get('mode-manager', scope='window',
window=self._win_id)
- if (result.cmdline[0] != 'repeat-command' and
- result.cmdline[0] != 'prompt-accept'):
last_command[mode_manager.mode] = (
... |
codereview_python_data_8849 | Parameters
----------
nbunch : single node, container, or all nodes (default= all nodes)
- The view will only report edges from these nodes (outgoing if directed).
data : string or bool, optional (default=False)
The edge attribute returned in 3-tuple (u, v, dd... |
codereview_python_data_8851 | from datastore import ndb_utils
from handlers import base_handler
from libs import handler
def admins_from_iam_policy(iam_policy):
maybe add some logs.log to tell which users are getting added as admins. also, look for any places that need more logging for better future debugging.
from datastore import ndb_utils... |
codereview_python_data_8866 | project=project,
network=network,
ip=ips,
- raw_data=json.dumps(instance_network_interface.__dict__,
- indent=2))
# Rule violation.
# resource_type: string
Why not store the original JSON ... |
codereview_python_data_8870 | def head(self):
p = os.path.join(self.request.master.options.cadir, self.filename)
p = os.path.expanduser(p)
- with open(p, "rb") as f:
- content_length = len(f.read())
self.set_header("Content-Type", "application/x-x509-ca-cert")
self.set_header(
Please use: ... |
codereview_python_data_8871 | @task
def send_confile(confile):
put('confiles/' + confile, 'tempfile')
- sudo('mv tempfile ~/.bigchaindb')
print('For this node, bigchaindb show-config says:')
run('bigchaindb show-config')
do we need sudo here? I am afraid that the bigchaindb process may not have the right read/write permissions
... |
codereview_python_data_8880 | where None represents all parsers and plugins.
A parser filter expression is a comma separated value string that
- denotes which parsers should be used. See filters/parser_filter.py
- for details of the expression syntax.
- Note that preset names in this expression will ... |
codereview_python_data_8889 | __version__ = '0.2.0'
-__short_version__ = '0.1'
\ No newline at end of file
\ No newline at end of file
maybe bump this too?
__version__ = '0.2.0'
\ No newline at end of file
+__short_version__ = '0.2'
\ No newline at end of file |
codereview_python_data_8890 | request: Request,
auth_constraint: AuthConstraint,
auth_action: AbstractAuthAction=None):
- is_role_accepted = self.is_role_accepted(request, auth_constraint)
- if is_role_accepted is None:
return False, "sender's DID {} is not found in... |
codereview_python_data_8892 | elif self.typedef_flag:
base_code = self.cname
else:
- base_code = "__PYX_ENUM_DECL %s" % self.cname
base_code = public_decl(base_code, dll_linkage)
return self.base_declaration_code(base_code, entity_code)
Does this really apply to plain ... |
codereview_python_data_8897 | 'qutebrowser/misc/checkpyver.py',
'qutebrowser/misc/guiprocess.py',
'qutebrowser/misc/editor.py',
- 'qutebrowser/misc/cmdhistory.py'
'qutebrowser/mainwindow/statusbar/keystring.py',
'qutebrowser/mainwindow/statusbar/percentage.py',
There's a comma missing here at the end :wink:
'quteb... |
codereview_python_data_8898 | """Check that we're accessing proper config options."""
if FAILED_LOAD:
if not ConfigChecker.printed_warning:
- print("[WARN] Could not find configdata.yml. Please run " +
"pylint from qutebrowser root.", file=sys.stderr)
print("Skipp... |
codereview_python_data_8900 | Args:
url: url to save as a bookmark. If None, use url of current page.
- title: title of the new bookmark."""
if url and not title:
raise cmdexc.CommandError('Title must be provided if url has '
'been provided')
The `"""` sh... |
codereview_python_data_8904 | 'full_name': full_name,
'rule_index': 0,
'rule_name': violation.constraint,
- 'violation_type': 'CV ' + violation.constraint,
'violation_data': json_format.MessageToDict(
violation.metadata, including_default_value_f... |
codereview_python_data_8907 | distributed = False
if len(cfg.gpu_ids) > 1:
warnings.warn(
- 'Only supports single GPU in non-distribute testing time.'
- f'We treat gpu-ids is set to {cfg.gpu_ids}, and will set '
- f'to {cfg.gpu_ids[0:1]}.')
cfg.gpu_ids = cfg.gp... |
codereview_python_data_8909 | # check spans
eff_query_spans = [blocksize_multiplier * s for s in hsp.query_span_all]
- assert hsp.hit_span_all == eff_query_spans
block_sizes = hsp.query_span_all
# set strand and starts
This should probably throw an exception (``Valu... |
codereview_python_data_8913 | self.assertListEqual(generate_metric_list(cpu_percent_values),
collected_metrics[name]["cpu"]["cur_cpu"][0:5])
@patch("azurelinuxagent.common.osutil.default.DefaultOSUtil._get_proc_stat")
def test_cgroup_tracking(self, *args):
num_extensions = 5
why do ... |
codereview_python_data_8914 | # Additional filter on the project field speeds things up because it makes faster
# to execute a SQL subquery generated by Django.
if project and project.slug != "all-projects":
- translations = translations.filter(entity__resource__project=project,)
# Finally, we return a... |
codereview_python_data_8919 | world_size=world_size,
rank=proc_id)
train_mask, val_mask, test_mask, n_classes, g = data
- nfeat = g.ndata.pop('feat').to(device)
- labels = g.ndata.pop('label').to(device)
in_feats = nfeat.shape[1]
train_nid = t... |
codereview_python_data_8931 | if response.status_code == 200 and status_code == '201' and key:
response.status_code = 201
response._content = self.get_201_reponse(key, bucket_name)
- response.headers['Content-Length']=len(response._content)
response.headers['Content-Type... |
codereview_python_data_8935 | SDNV2('CTSN', 0),
SDNV2('LT', 0),
SDNV2('DL', 0),
- MultipleTypeField([
- (SDNV2("FO", 0), lambda x: (
- x.ProcFlags & 0x01)),
- (SDNV2("ADUL", 0), lambda x: (
- ... |
codereview_python_data_8949 | if trans:
msg = self.output.post_transaction_output(trans)
logger.info(msg)
- list_bunch = dnf.cli.output._make_lists(trans, self._goal)
- if [tsi._active for tsi in list_bunch.failed]:
- raise dnf.exceptions.Error(_('Transaction failed'))
def gpgsigcheck... |
codereview_python_data_8951 | world_size=world_size,
rank=proc_id)
- if args.per_etype_fanout:
- sampler = dgl.dataloading.MultiLayerEtypeNeighborSampler(fanouts, etype_field='etype')
- else:
- sampler = dgl.dataloading.MultiLayerNeighborSample... |
codereview_python_data_8954 | except Exception as e:
logger.error("Unexpected error in process_data {}".format(e))
- def _declate_upgrade_failed(self, *,
from_version,
to_version,
reason):
A typo in method name
exce... |
codereview_python_data_8956 | # there was only one exact match
return options[0]
- # there are more than one exact match for this fuzzy symbol
raise MultipleSymbolsFoundForFuzzySymbol(
symbol=symbol,
options=self.retrieve_all(owner.sid for owner in owners),
... |
codereview_python_data_8959 | path = getattr(options, 'yara_rules_path', None)
if path:
try:
- with open(path, 'rb') as rules_file:
yara_rules_string = rules_file.read()
- yara_rules_string = codecs.decode(yara_rules_string, 'utf-8')
except IOError as exception:
raise errors.BadConfigObjec... |
codereview_python_data_8963 | def _process_post_response(self, response, mode):
logger.debug(response)
result = response['result']
if mode == self.mode_commit:
check_tx_code = result.get('check_tx', {}).get('code', 0)
If you omit the second parameter, `get` returns `None` if the lookup is unsuccessful, ... |
codereview_python_data_8966 | d["resp_ctype"] = t.split(";")[0]
else:
d["resp_ctype"] = ""
- return flowcache.get(
- raw_format_flow,
- tuple(sorted(d.items())),
- focus,
- extended,
- truncate_urls,
- )
I think these could just be part of `d` ?
d["resp_ctype... |
codereview_python_data_8968 | with mb_conn.cursor() as curs:
curs.execute("DROP TABLE IF EXISTS mapping.tmp_mbid_mapping")
curs.execute("""CREATE TABLE mapping.tmp_mbid_mapping (
- id SERIAL,
recording_name ... |
codereview_python_data_8970 | self.assertFalse(task_9.has_excessive_failures())
task_9.add_failure()
self.assertTrue(task_9.has_excessive_failures())
-
-
-if __name__ == '__main__':
- unittest.main()
remove this (you should use `tox` for running tests, so this won't be needed)
self.assertFalse(task_9.has_exc... |
codereview_python_data_8978 | Args:
times: How many times to repeat.
command: The command to run, with optional args.
"""
-
if count is not None:
times *= count
No blank line after the docstring.
Args:
times: How many times to repeat.
command: The command to run, with optional args.... |
codereview_python_data_8983 | data = test_pipeline(data)
data = collate([data], samples_per_gpu=1)
# just get the actual data from DataContainer
- data['img_metas'] = [i.data[0] for i in data['img_metas']]
- data['img'] = [i.data[0] for i in data['img']]
if next(model.parameters()).is_cuda:
# scatter to specified ... |
codereview_python_data_8984 | Atlas of all connected graphs with up to 6 nodes.
This example uses Graphviz via PyGraphviz.
-It should show 142 graphs (oeis.org/A001349).
"""
import random
It's probably not relevant to the example, but I was confused by the linked sequence: it looks like the value is 112 for `n=6`. I'm not sure that I'm interpr... |
codereview_python_data_8985 | import numpy as np
-class Median_2d_test(test.TestCase):
def _validateMedian_2d(self, inputs, expected_values, filter_shape = (3, 3)):
Class name in CamelCase to be consistent with others : e.g. Median2DTest
import numpy as np
+class Median2DTest(test.TestCase):
def _validateMedian_2d(self, inputs, expected_v... |
codereview_python_data_8993 | self.applications.add(offer1, result1)
self.applications.add(offer2, result2)
discounts = self.applications.grouped_voucher_discounts
- discounts = [*discounts,]
assert len(discounts) == 1
assert discounts[0]['voucher'] == voucher
assert discounts[0]['discoun... |
codereview_python_data_8994 | The subgraph index.
"""
e_array = e.todgltensor()
- rst = _CAPI_DGLGraphEdgeSubgraph(self._handle, e_array, preserve_nodes)
induced_nodes = utils.toindex(rst(1))
- gidx = GraphIndex(rst(0))
return SubgraphIndex(gidx, self, induced_nodes, e)
@utils.cach... |
codereview_python_data_8999 | raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
def _find_no_duplicates(self, name, domain=None, path=None):
- """__get_item__ and get call _find_no_duplicates -- never used in
- Requests internally. Takes as args name and optional domain and path.
- Returns a coo... |
codereview_python_data_9005 | >>> view = blocks_of(arr, 2, 2)
>>> view[:] = 100
>>> arr
- array([[100, 1, 2, 3],
- [ 4, 100, 6, 7],
- [ 8, 9, 100, 11],
- [ 12, 13, 14, 100]])
Notes
-----
So a block of size 2x2 is equivalent to the diagonal? Or rather 4 blocks of size 1x1 al... |
codereview_python_data_9008 | # Detecing KVM is tricky, so let's use an environment variable, set from the
# docker image, to determine whether to turn it on or not.
- kvm = environment.get_value('FUCHSIA_USE_KVM')
- if kvm:
qemu_args.append('-enable-kvm')
# Get the list of fuzzers for ClusterFuzz to choose from.
nit: no need for t... |
codereview_python_data_9010 | sleep(worker_id + 1)
line_input = queue_of_texts.get()
if line_input is not None:
- letters_in_line = Counter([idx for idx in line_input.lower() if
- idx.isalpha()])
letter_to_frequency.add_counter(letters_in_line)
queue_o... |
codereview_python_data_9013 | results (dict): Result dict from loading pipeline.
Returns:
- dict: Padded results, 'pad_shape', 'pad_fixed_size',
- 'pad_size_divisor' keys are added into result dict.
"""
self._pad_img(results)
The change of keys should be described in the class docst... |
codereview_python_data_9016 | "kaitaistruct>=0.7,<0.9",
"ldap3>=2.5,<2.6",
"passlib>=1.6.5, <1.8",
- "ply>=3.4, <3.12",
"pyasn1>=0.3.1,<0.5",
"pyOpenSSL>=17.5,<18.1",
"pyparsing>=2.1.3, <2.3",
Did you actually test this with ply 3.4? That release is pretty old (2011), so I think we can b... |
codereview_python_data_9017 | accepted_mimetypes: Iterable[str],
) -> List[str]:
"""Override chooseFiles to (optionally) invoke custom file uploader."""
- if config.val.fileselect.handler == "default":
return super().chooseFiles(mode, old_files, accepted_mimetypes)
return shared.choose_file(
... |
codereview_python_data_9020 | import torch
-from nvidia.dali.pipeline import pipeline
import nvidia.dali.types as types
import nvidia.dali.fn as fn
-@pipeline
def create_coco_pipeline(default_boxes, args):
try:
shard_id = torch.distributed.get_rank()
same as in the previous file, do we want to replace our examples to use this?
... |
codereview_python_data_9026 | ('move-to-end-of-line', ['$']),
('move-to-start-of-document', ['gg']),
('move-to-end-of-document', ['G']),
- ('yank selection -p', ['Y']),
('yank selection', ['y'] + RETURN_KEYS),
('scroll left', ['H']),
('scroll down', ['J']),
What's the `-p` supposed to do... |
codereview_python_data_9031 | port = DEFAULT_PORT
hosts.append((ip, port))
else:
- ip = result[0]
- port = int(result[1])
- hosts.append((ip, port))
- #raise RuntimeError("Format error of ip_config.")
server_count_per_machine = ar... |
codereview_python_data_9038 | class BinaryDSVReaderTest(shared_test_lib.BaseTestCase):
"""Tests for the binary delimited separated values reader."""
- def setUp(self):
- """Sets up the needed objects used throughout the test."""
- self._resolver_context = context.Context()
-
@shared_test_lib.skipUnlessHasTestFile(['password.csv'])
... |
codereview_python_data_9041 | environment.reset_current_memory_tool_options()
# Clear exceptions.
- if sys.version_info.major == 2:
- # TODO(ochang): Remove this once migrated to Python 3.
- sys.exc_clear()
# Call python's garbage collector.
utils.python_gc()
i think we use this in 3 places, feel free to create a helper in utils... |
codereview_python_data_9055 | )
self.connected_exchanges[location].append(exchange_obj)
- def get_all_binance_pairs(self, location: Location) -> List[str]:
- pairs = list(query_binance_exchange_pairs(location=location).keys())
- if len(pairs) == 0:
- self.msg_aggregator.add_error('Failed... |
codereview_python_data_9056 | from tensorflow_addons.image.transform_ops import rotate
from tensorflow_addons.image.transform_ops import transform
from tensorflow_addons.image.translate_ops import translate
-from tensorflow_addons.image.augment_ops import blend
@gabrieldemarmiesse Is blend an `augment_ops` or something else? I.e. in Opencv is a... |
codereview_python_data_9069 | return os.path.exists(file_path)
-def file_open(file_path, mode="rb", kwargs=None):
if isinstance(file_path, str):
match = S3_ADDRESS_REGEX.search(file_path)
if match:
```suggestion def file_open(file_path, mode="rb", compression="infer"): ```
return os.path.exists(file_path)
+def fil... |
codereview_python_data_9071 | if not user_email:
return
- spotify_url = current_app.config['SERVER_ROOT_URL'] + '/profile/music-services/details/'
text = render_template('emails/spotify_import_error.txt', error=error, link=spotify_url)
send_mail(
subject='ListenBrainz Spotify Importer Error',
can we use url_for(... |
codereview_python_data_9072 | """
Get a list of output links filtered on some criteria
"""
- outputs = self.fastquery.get_outputs_by_pubkey(owner)
if not include_spent:
outputs = self.fastquery.filter_spent_outputs(outputs)
return outputs
Can we make this so that we don't need to ins... |
codereview_python_data_9073 | [11.5000, -4.5000, 20.5000, 4.5000],
[-4.5000, 11.5000, 4.5000, 20.5000],
[11.5000, 11.5000, 20.5000, 20.5000]])
- >>> self = AnchorGenerator(9, [1.], [1.], ctr_offset=0.5)
- >>> all_anchors = self.grid_anchors((2, 2), device='cpu')
- >>> print(a... |
codereview_python_data_9075 | 'https://{domain}/revisions?job={job_type}&revision={revision}')
FILE_UNREPRODUCIBLE_TESTCASE_TEXT = (
- '***************************************\n'
'Note: This crash might not be reproducible with the provided testcase. '
'That said, for the past %d days, we\'ve been seeing this crash '
'freque... |
codereview_python_data_9077 | LOG = get_logger('system')
-class DBContext:
"""
Simple helper class to setup and sql engine, a database session
and a connection.
Please use new-style class `DBContext(object)`
LOG = get_logger('system')
+class DBContext(object):
"""
Simple helper class to setup and sql engine, a database ... |
codereview_python_data_9080 | class TestGROWriterLarge(TestCase, tempdir.TempDir):
@classmethod
def setUpClass(cls):
cls.tmpdir = tempdir.TempDir()
Why does this need to be changed?
class TestGROWriterLarge(TestCase, tempdir.TempDir):
+ # not normally recommended to use class-level
+ # setup for universe (special case h... |
codereview_python_data_9084 | use_alternate = biased_coin(data, alternate_chance)
data.stop_example()
if use_alternate:
- return base
- else:
return alternate
class many(object):
Surely if `use_alternate` is True, we should return `alternate`, not `base`?
use_alternate = biased_c... |
codereview_python_data_9087 | from dgl.nn.pytorch import RelGraphConv
class RGCN(nn.Module):
- """
- Parameters
- ----------
- in_dim : int
- Input feature size or number of nodes
- """
def __init__(self, in_dim, h_dim, out_dim, num_rels,
regularizer="basis", num_bases=-1, dropout=0.,
... |
codereview_python_data_9088 | ]
)
for rt in resp["RouteTables"]:
- for assoc in rt["Associations"]:
ec2_client.disassociate_route_table(
AssociationId=assoc["RouteTableAssociationId"]
)
nit: Can w... |
codereview_python_data_9092 | def FastaNcbiIterator(source, alphabet=single_letter_alphabet):
for title, sequence in SimpleFastaParser(source):
id, name, xrefs = fasta_title_parser_auto(title)
yield SeqRecord(Seq(sequence, alphabet), id, name, name, dbxrefs=xrefs)
The SeqRecord ``.dbxrefs`` is expected to be a list of strin... |
codereview_python_data_9093 | with shared_test_lib.TempDirectory() as temp_directory:
filter_file = os.path.join(temp_directory, 'filter.txt')
- with open(filter_file, 'w') as file_object:
file_object.write('/a_directory/.+_file\n')
options.file_filter = filter_file
`open(filter_file, 'w')` => `io.open(filter_file,... |
codereview_python_data_9106 | def getAscendent(self, node_type):
"""Return the ancenstor node of the given type, or None.
- Node type can a
- two letter code or longer description. e.g. 'fa' or 'family'.
"""
if node_type in _nodetype_to_code:
node_type = _nodetype_to_code[node_type]
This (... |
codereview_python_data_9109 | def __init__(self, *a, __remote_end__=None, **kw):
if __remote_end__ is None:
- if hasattr(self, "_preprocess_init_args"):
- a, kw = self._preprocess_init_args(*a, **kw)
- if __remote_end__ is None:
__remote_end__ = remote_cls(*a, **kw)... |
codereview_python_data_9115 | """
def __init__(self, config):
- """Args:
- config(ClientConfig): the client config object
"""
super(ExplainClient, self).__init__(config)
self.stub = explain_pb2_grpc.ExplainStub(config['channel'])
It's not clear exactly what is the `prefix` here. So it would be... |
codereview_python_data_9126 | # pylint: enable=bad-builtin
msg = message_mock.getmsg(usertypes.MessageLevel.error)
assert msg.text.startswith(
- "Error building SQL Query: Expression tree is too large")
@pytest.mark.parametrize('max_items, before, after', [
You could just replace `map(str, range(10000)))` with `str(x) fo... |
codereview_python_data_9130 | """
inplace = validate_bool_kwarg(inplace, "inplace")
duplicates = self.duplicated(subset=subset, keep=keep)
- indices, = duplicates.nonzero()
return self.drop(index=self.index[indices], inplace=inplace)
def duplicated(self, subset=None, keep="first"):
It looks like that... |
codereview_python_data_9131 | else:
i += 1
result.extend(x[i:])
- return list(map(tuple, result))
def _intervals(s):
This function is quite cryptic. Could there be a short notice what happens here?
else:
i += 1
result.extend(x[i:])
+ return tuple(map(tuple, result))
def... |
codereview_python_data_9134 | if self.gt_unique_best:
assigned_gt_inds[gt_argmax_overlaps[i]] = i + 1
else:
- assigned_gt_inds[overlaps[:, i] == gt_max_overlaps[i]] \
- = i + 1
if gt_labels is not None:
assigned_labels = assigned_g... |
codereview_python_data_9136 | self.generate_set_slot_code(src, scope, code)
-class DelSlot(InternalMethodSlot):
- # For __del__ if defined
- def __init__(self, slot_name, **kwargs):
- super(DelSlot, self).__init__(slot_name, **kwargs)
-
- def slot_code(self, scope):
- if not scope.lookup_here("__del__"):
- ... |
codereview_python_data_9138 | """Computes the axis wise maximum over chosen elements.
Args:
- data: 2-D float `Tensor` of size `[n, m]`.
- mask: 2-D Boolean `Tensor` of size `[n, m]`.
dim: The dimension over which to compute the maximum.
Returns:
I guess it's better to switch to `with shape`
"""Computes the ax... |
codereview_python_data_9140 | # We need to see if we match the end of the netloc, accounting for a
# 'username[:password]@' at the beginning and a ':port' at the end.
- host_or_ip = netloc.split('@')[-1].split(':')[0]
if is_ipv4_address(host_or_ip):
for proxy_ip in no_proxy:
if is_vali... |
codereview_python_data_9142 | -from . import (maxflow, mincost, edmondskarp, fordfulkerson, preflowpush,
- shortestaugmentingpath, capacityscaling, networksimplex, utils)
__all__ = sum([maxflow.__all__,
mincost.__all__,
Now that there no longer are name conflicts, you can remove this import and move the definition of `__all__`... |
codereview_python_data_9143 | response = authenticate_presign_url_signv4(method, path, headers, data, url, query_params, request_dict)
if response is not None:
- LOGGER.debug('Signature calculation failed with the error.')
return response
def authenticate_presign_url_signv2(method, path, headers, data, url, query_para... |
codereview_python_data_9145 | mode_manager = objreg.get('mode-manager', scope='window',
window=self._win_id)
- if result.cmdline[0] not in ['leave-mode', 'prompt-accept',
'repeat-command']:
last_command[mode_manager.mode] = (
... |
codereview_python_data_9151 | # specified explicitly
async with self._run_and_rollback():
with self.assertRaisesRegex(
- exceptions.UnknownEdgeDBError,
r"subjectexpr is already defined for .+max_int"):
await self.con.execute("""
CREATE CONST... |
codereview_python_data_9152 | else:
cmd = "pw useradd {0} -m".format(username)
if comment is not None:
- cmd += " -c '{0}'".format(comment)
retcode, out = shellutil.run_get_output(cmd)
if retcode != 0:
raise OSUtilError(("Failed to create user account:{0}, "
These changes loo... |
codereview_python_data_9153 | ((lambda x, y: x ** y), "**")]
def test_bool_disallowed():
- error_msg = "[Ii]nput[s]? to arithmetic operator `[\S]*` cannot be [a]?[ ]?boolean[s]?. Consider using bitwise operator[s]?"
for kinds in unary_input_kinds:
for (op, _, op_desc, _, _) in math_function_operations:
... |
codereview_python_data_9156 | class AtomSelection(Selection):
def __init__(self, name, resid, segid):
- Selection.__init__(self)
self.name = name
self.resid = resid
self.segid = segid
Really, we never used that? It's been here since Day 1. Fair to remove it, though.
class AtomSelection(Selection):
def... |
codereview_python_data_9164 | init_swagger_documentation(app_svc.application)
if args.fresh:
- logging.info("Fresh startup: removing server data files")
asyncio.get_event_loop().run_until_complete(data_svc.destroy())
run_tasks(services=app_svc.get_services())
may want to add a note here on where to find previous file... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.