id stringlengths 24 28 | content stringlengths 121 2.08k |
|---|---|
codereview_python_data_0 | self.redirect("/static/visualiser/index.html")
def head(self):
self.set_status(204)
self.finish()
Is the name "head" a convention for health checking? Regardless it caught me by surprise, maybe add some docs to this function on why it exist? It should also say what 204.
self.r... |
codereview_python_data_1 | backward_time.append(t2 - t1)
print("Epoch {:05d} | Train Forward Time(s) {:.4f} | Backward Time(s) {:.4f}".
format(epoch, forward_time[-1], backward_time[-1]))
- cross_entropy(logits[val_idx], labels[val_idx])
val_acc = torch.sum(logits[val_idx].argmax(dim=1) == labels[... |
codereview_python_data_4 | execute = pyqtSignal(str)
- STYLESHEET = """
- ConsoleLineEdit {
- font: {{ conf.fonts.debug_console }};
- }
- """
-
def __init__(self, _namespace, parent):
"""Constructor.
Couldn't you move the stylesheet to `ConsoleWidget` with a `ConsoleLineEdit, ConsoleTextEdit` se... |
codereview_python_data_20 | 'this API client')
def iter_kubernetes_nodes(self, project_id, zone, cluster):
- """Iterate k8s nodes in an organization from GCP API.
Args:
project_id (str): id of the project to query.
zone (str): The zone the cluster is in.
please u... |
codereview_python_data_21 | eps=1e-3,
reduction='mean',
avg_factor=None):
- """Calculate dice loss, the coefficient in the denominator is the first
- power instead of the second power.
Args:
pred (torch.Tensor): The prediction, has a shape (n, *)
use_second_power=... |
codereview_python_data_25 | The :class:`~MDAnalysis.core.groups.AtomGroup` or
:class:`~MDAnalysis.core.universe.Universe` to write.
"""
- warnings.warn("Using the last letter of the segid for the chainID "
- "is now deprecated and will be changed in 2.0. "
- "In 2... |
codereview_python_data_30 | :return:
"""
- self._compact_times()
-
if self[self.SAMPLE_COUNT]:
self[self.AVG_CONN_TIME] = self.sum_cn / self[self.SAMPLE_COUNT]
self[self.AVG_LATENCY] = self.sum_lt / self[self.SAMPLE_COUNT]
We don't need to compact times for each KPIset. We only need to ... |
codereview_python_data_42 | if not self._r.headers.get('Host'):
return self._r.url
# If they did set it, retrieve it and reconstruct the expected domain
- host = self._r.headers['Host']
parsed = urlparse(self._r.url)
-
- # If parsed url is str type, ensure that host is also str type
- i... |
codereview_python_data_59 | """
cls = super(Register, metacls).__new__(metacls, classname, bases, classdict)
- if getattr(cls, "task_namespace", None) is None:
cls.task_namespace = metacls._default_namespace
metacls._reg.append(cls)
instead of a `getattr` call here, can you just set `task_namespace ... |
codereview_python_data_60 | self.assertEqual(record["AC"], "CVCL_2260")
self.assertEqual(
record["SY"],
- "Clone 1-5c-4; Clone 1-5c-4 WKD of "
- "Chang Conjunctiva; "
- "Wong-Kilbourne derivative of "
- "Chang conjunctiva; ChWK",
)
... |
codereview_python_data_62 | # package.
"""Simple protein analysis.
-Example:
>>> from Bio.SeqUtils.ProtParam import ProteinAnalysis
>>> X = ProteinAnalysis("MAEGEITTFTALTEKFNLPPGNYKKPKLLYCSNGGHFLRILPDGTVDGT"
... "RDRSDQHIQLQLSAESVGEVYIKSTETGQYLAMDTSGLLYGSQTPSEEC"
Does this render correctly? Do we need something like: ```... |
codereview_python_data_63 | """
result = reply.result
if result[TXN_TYPE] in (SCHEMA, ISSUER_KEY):
- result = deepcopy(result)
result[DATA] = jsonSerz.serialize(result[DATA], toBytes=False)
txnWithMerkleInfo = self.storeTxnInLedger(result)
Why this line is necessary?
"""
... |
codereview_python_data_68 | return tasks_host.do_corpus_pruning(context, last_execution_failed,
revision)
- build_setup_result = build_manager.setup_build(revision=revision)
- build_directory = environment.get_value('BUILD_DIR')
- if not build_setup_result or not build_directory:
raise CorpusP... |
codereview_python_data_69 | amount = self.parent.format_amount(utxo.value_sats(), whitespaces=True)
labels = [name_short, address, label, amount, '%d'%height]
utxo_item = [QStandardItem(x) for x in labels]
- # Storing the full outpoint as the data payload of this item
- utxo_item[0].setData(name)
... |
codereview_python_data_71 | code.putln(
"};")
- def generate_dict_getter(self, scope, code):
- #if scope.name == 'QApplication':
- # import ipdb;ipdb.set_trace()
func_name = scope.mangle_internal("__dict__getter")
dict_attr = scope.lookup_here("__dict__")
dict_name = dict_attr.c... |
codereview_python_data_82 | content_type='text/html')
LOGGER.debug('Inventory summary sent successfully by email.')
except util_errors.EmailSendError:
- LOGGER.warn('Unable to send Violations email')
@staticmethod
def transform_to_template(data):
Keep this at exception ... |
codereview_python_data_84 | raise NotImplementedError
-def _is_spmv_supported_node_feat(g, field):
- """Return whether the node feature shape supports SPMV optimization."""
- return True
-
def _is_spmv_supported_edge_feat(g, field):
"""Return whether the edge feature shape supports SPMV optimization.
Since it's always return... |
codereview_python_data_86 | '25',
'--dict',
os.path.join(DATA_DIR, 'test_fuzzer.dict'),
- '-f',
os.path.join(TEMP_DIR, 'corpus'),
- '-W',
TEMP_DIR,
'--run_time',
'10',
need to add check to make sure that crash.input_input exists on disk.
'25',
'--dict... |
codereview_python_data_87 | from allauth.account import views as account_views
from allauth.socialaccount import views as socialaccount_views, providers
-if settings.AUTHENTICATION_METHOD == 'django' or settings.HEROKU_DEMO:
urlpatterns = [
url(r'^standalone-login/$', login, name='standalone_login'),
url(r'^standalone-log... |
codereview_python_data_90 | emitters.commit()
except dnf.exceptions.ExitOnLock as exc:
logger.info(ucd(exc))
- return 0
except dnf.exceptions.Error as exc:
logger.error(_('Error: %s'), ucd(exc))
return 1
I suppose that 1 would be better here. Please take into account also YUM behavior.
... |
codereview_python_data_91 | dist.broadcast(module.running_mean, 0)
def after_train_epoch(self, runner):
- if self.broadcast_bn_buffer:
- self._broadcast_bn_buffer(runner)
-
if not self.by_epoch or not self.evaluation_flag(runner):
return
from mmdet.apis import multi_gpu_te... |
codereview_python_data_92 | icon_changed = pyqtSignal(QIcon)
#: Signal emitted when a page's title changed (new title as str)
title_changed = pyqtSignal(str)
- #: Signal emitted when a page's currently active search match changed (match as current/total)
- search_match_changed = pyqtSignal(int, int)
#: Signal emitted whe... |
codereview_python_data_96 | try:
self.base.conf._configure_from_options(opts)
self._read_conf_file(opts.releasever)
- self.base.conf.read_dropin()
self.base.conf._adjust_conf_options()
except (dnf.exceptions.ConfigError, ValueError) as e:
logger.critical(_('Config er... |
codereview_python_data_99 | """
self.log("serverdisconnect", "debug", [repr(self.server_conn.address)])
address = self.server_conn.address
- source_address = self.server_conn.source_address()[0]
self.server_conn.finish()
self.server_conn.close()
self.channel.tell("serverdisconnect", sel... |
codereview_python_data_113 | # log encounter
self.emit_event(
'pokemon_appeared',
- formatted='A wild {} appeared! (CP: {}) (IV: {}) (A/D/S {}) (NCP: {})'.format(pokemon.name, pokemon.cp, pokemon.iv, pokemon.iv_display, round(pokemon.cp_percent, 2),),
data={
'pokemon': pokemo... |
codereview_python_data_115 | def crontab(self, *args, **kwargs):
return crontab(*args, **dict(kwargs, app=self.app))
- def next_occurrence(self, crontab, now):
crontab.nowfun = lambda: now
return now + crontab.remaining_estimate(now)
make sure this won't regress
def crontab(self, *args, **kwargs):
... |
codereview_python_data_117 | # data that needs to be added to them.
# We postpone processing of this in order to do type inference/generalization.
# See self.attr_type
- for (xml_obj, data) in self.attributes.iteritems():
for (k, v, scope, default) in data:
xml_obj.append(self.add_dat... |
codereview_python_data_121 | if ann.get('ignore', False):
continue
x1, y1, w, h = ann['bbox']
- x2 = x1 + w
- y2 = y1 + h
- if ((x1 < 0 or x1 >= img_info['width'] or y1 < 0
- or y1 >= img_info['height'])
- and (x2 < 0 or x2 >= img_info['w... |
codereview_python_data_126 | -def hey(incoming_words):
pass
Maybe just `words` or even `phrase` is a better choice?
+def hey(phrase):
pass |
codereview_python_data_127 | # Fork mode is disabled on ephemeral bots due to a bug on the platform.
is_ephemeral = environment.is_ephemeral()
if (not is_fuchsia and not is_android and not is_ephemeral and
not use_dataflow_tracing and
strategy_pool.do_strategy(strategy.FORK_STRATEGY)):
So, you don't want fork mode to be use... |
codereview_python_data_131 | import os
import os.path
-
-from itertools import chain, dropwhile, takewhile
import sip
from PyQt5.QtCore import QUrl, QObject, QPoint, QTimer
Please import modules (`import itertools`) and then use `itertools.chain`, etc.
import os
import os.path
+import itertools
import sip
from PyQt5.QtCore import QUrl, Q... |
codereview_python_data_132 | Chem = pytest.importorskip("rdkit.Chem")
mol = Chem.Mol()
u = mda.Universe(mol, format="RDKIT")
class TestUniverseFromSmiles(object):
def setup_class(self):
I suppose you could also check that the universe is empty--has `0` atoms for example.
Chem = pytest.importorskip("rdkit... |
codereview_python_data_134 | if not pat.match(value):
raise InvalidHeader("Invalid return character or leading space in header: %s" % name)
except TypeError:
- raise InvalidHeader("Header %s value %s must be of type str or bytes, "
- "not %s" % (name, value, type(value)))
def urldefraga... |
codereview_python_data_139 | class RekognitionStubber(ExampleStubber):
"""
- A class that implements a variety of stub functions that are used by the
- Amazon Rekognition unit tests.
- The stubbed functions all expect certain parameters to be passed to them as
- part of the tests, and will raise errors when the actual parameters ... |
codereview_python_data_143 | objreg.register('message-bridge', message_bridge, scope='window',
window=self.win_id)
- if config.val.window.hide_decoration:
- window_flags = Qt.CustomizeWindowHint | Qt.NoDropShadowWindowHint
- self.setWindowFlags(Qt.Window | window_flags)
self.s... |
codereview_python_data_146 | return dict(name=self.name, module=self.module, params=self.params, description=self.description,
stopping_conditions=[fact.display for fact in self.stopping_conditions])
- def __init__(self, id, name, module, params, stopping_conditions=None, description=None):
super().__init_... |
codereview_python_data_147 | return data
def readline(self):
- """Read single line for the BGZF module."""
i = self._buffer.find(self._newline, self._within_block_offset)
# Three cases to consider,
if i == -1:
This isn't for the module, its for the class. How about just: ```python """Read a ... |
codereview_python_data_148 | print("\nSetting up cluster\n")
redis_address = cluster.setup_cluster(config)
print("\nLaunching notebook\n")
- print("*" * 68)
- print(("To connect to the cluster, run the following commands in the "
- "notebook:\n"
- "\t\timport ray\n"
- "\t\tray.init(redis_address=\... |
codereview_python_data_152 | wrap_fp16_model)
-class Depr_Fp16OptimizerHook(Fp16OptimizerHook):
"""A wrapper class for the FP16 optimizer hook. This class wraps
:class:`Fp16OptimizerHook` in `mmcv.runner` and shows a warning that the
:class:`Fp16OptimizerHook` from `mmdet.core` will be deprecated.
Just use... |
codereview_python_data_155 | for a in agents:
executors = await self.dao.get('core_executor', criteria=dict(agent_id=a['id']))
a['executors'] = [dict(executor=e['executor'], preferred=e['preferred']) for e in executors]
- a['sleep'] = self.jitter('{}/{}'.format(a['sleep_min'], a['sleep_max']))
... |
codereview_python_data_159 | display_name (str): display name.
Returns:
- firefox__cache_config: namedtuple containing the block size and first
record offset.
Raises:
`firefox__cache_config` => `firefox_cache_config` (remove the double underscore)
display_name (str): display name.
Returns:
+ fire... |
codereview_python_data_162 | # ANY KIND, either express or implied. See the License for the specific language
# governing permissions and limitations under the License.
-"""Base Modin Dataframe class optimized for PyArrow on Ray execution."""
again, nothing about "experimental" in here
# ANY KIND, either express or implied. See the License fo... |
codereview_python_data_164 | stream_params = stream_parameters(streams)
inds, dims = zip(*[(ind, kdim) for ind, kdim in enumerate(kdims)
if kdim not in stream_params])
- get = itemgetter(*inds)
keys = (get(k) for k in keys)
return dims, ([wrap_tuple(k) for k in keys] if len(inds) == 1 else list(keys))... |
codereview_python_data_170 | x.add_row([item.name, state, item.provider])
print(x)
- print
self.molecule._print_valid_platforms()
- print
self.molecule._print_valid_providers()
Just to be consistent, can we use the print function `print()` instead of the keyword. Same goes for line 437.
... |
codereview_python_data_171 | original_parsed = urlparse(resp.request.url)
redirect_parsed = urlparse(url)
- if original_parsed.hostname != redirect_parsed.hostname:
- try:
- del headers['Authorization']
- except KeyError:
- pass
# ... |
codereview_python_data_172 | "method_%s_%s" % (type_name, attr_name), kwargs)
if method_handler is None:
# in this case we don't need the real directives on the call to get_slot_table
- if (attr_name in TypeSlots.get_slot_table({}).method_name_to_slot
or attr_name in ['__new__', '_... |
codereview_python_data_179 | elif self._config.batch_mode == 'family':
return family
elif self._config.batch_mode == 'unbatched_params':
- param_str = ', '.join(f'{k}={v}' for k, v in six.iteritems(unbatched_args))
- return f'{family}({param_str})'
else:
raise ValueError('U... |
codereview_python_data_183 | in_channels=256,
fc_out_channels=1024,
roi_feat_size=7,
- num_classes=81,
target_means=[0., 0., 0., 0.],
target_stds=[0.1, 0.1, 0.2, 0.2],
reg_class_agnostic=False,
The num of classes you used still is 81.
in_channels=256,
fc_out_channels=... |
codereview_python_data_184 | async def test_edgeql_insert_unless_conflict_20a(self):
# currently we reject ELSE in these cases
with self.assertRaisesRegex(
- edgedb.errors.QueryError,
"UNLESS CONFLICT can not use ELSE when constraint is from a "
"parent type",
):
It's a little u... |
codereview_python_data_194 | def test_that_backprop_runs():
- """Run optimization to ensure that gradients can be computed."""
batch_size = 1
image_height = 9
image_width = 12
Probably need to re-word this doc string now that we're directly checking backprop gradients instead of running an optimization
def test_that_backprop_... |
codereview_python_data_196 | >>> obj.unwrap(expires)
1
>>> obj.unwrap(expires + Timedelta('1 minute'))
Traceback (most recent call last):
...
Expired: 2014-01-01 00:00:00+00:00
We still need this line, this is what is causing the tests to fail in py3
>>> obj.unwrap(expires)
1
>>> obj.unwrap(expire... |
codereview_python_data_203 | from __future__ import with_statement, unicode_literals
from os import environ # a mapping (like a dict)
-from sys import exit as sys_exit
from fabric.api import sudo, env, hosts
from fabric.api import task, parallel
you can just do: ``` python import sys ``` and then in the code: ``` python sys.exit('...') ``` i... |
codereview_python_data_206 | def _setup_pipe_pool_dependency(self):
if self._py_pool_started:
- # Pipeline backend doesn't really do anything with the pool, sole point of this call
- # is to ensure lifetime of the pool exceeds the lifetime of the pipeline's backend
- # so that shared memory managed by... |
codereview_python_data_211 | g_data = json.load(open(graph_file))
self._labels = np.load(label_file)
self._feats = np.load(feat_file)
- self._graph = DGLGraph(nx.DiGraph(json_graph.node_link_graph(g_data)))
graph_id = np.load(graph_id_file)
# lo, hi means the range of graph ids for different port... |
codereview_python_data_213 | status = map_objects.get('status', None)
cells = map_objects['map_cells']
- # insert detail info about gym to fort
for cell in cells:
if 'forts' in cell:
for fort in cell['forts']:
It's unfortunate that you have so many changes in ... |
codereview_python_data_218 | if self.focus is None:
self.set_focus(0)
elif self.follow_focus:
- self.set_focus(self.flow_count())
return f
def set_limit(self, limit):
Shouldn't we do the same we do in `add_flow` here? (Maybe we can even factor that out in its own `update_focus` method)
... |
codereview_python_data_221 | ("float64", np.float64))
def test_gelu(self, dtype):
x = np.random.rand(2, 3, 4).astype(dtype)
- self.assertAllCloseAccordingToType(gelu.gelu(x), _ref_gelu(x))
- self.assertAllCloseAccordingToType(
- gelu.gelu(x, False), _ref_gelu(x, False))
... |
codereview_python_data_229 | def setUp(self):
AgentTestCase.setUp(self)
- prefix = "ExtensionTelemetryUnitTest"
- logger.DEFAULT_LOGGER = Logger(prefix=prefix)
clear_singleton_instances(ProtocolUtil)
# Create the log directory if not exists
this should be reverted to the original value on cleanup
... |
codereview_python_data_232 | if not params.has_objects(schema):
return None
diff_param = -1
overloads = []
sn = self.get_shortname(schema)
You can only check against the first overload and then break the top loop.
if not params.has_objects(schema):
return None
+ new_pa... |
codereview_python_data_233 | INSTALL_DIR_ES = '%s/elasticsearch' % INSTALL_DIR_INFRA
TMP_ARCHIVE_ES = '/tmp/localstack.es.zip'
-ERROR_PROBABILITY = 0.05
-
# set up logger
LOGGER = logging.getLogger(__name__)
Couldn't we be using `ERROR_PROBABILITY` in constants.py (or config.py) instead of `KINESIS_RETURN_ERRORS`? `ERROR_PROBABILITY == 1` wou... |
codereview_python_data_239 | self.CheckTimestamp(event.timestamp, '2015-11-22 17:53:29.305000')
- expected_message = ('Setup Plug and Play Device Install')
- expected_short_message = ('Setup Plug and Play Device Install')
self._TestGetMessageStrings(
event_data, expected_message, expected_short_message)
remove bounding pa... |
codereview_python_data_244 | return self.get_urls(), self.label, self.namespace
-class OscarConfig(AutoLoadURLsConfigMixin, OscarConfigMixin, AppConfig):
"""
Base Oscar app configuration.
It is better to apply `AutoLoadURLsConfigMixin` to only the app config classes that use it (`oscar.apps.catalogue.apps.CatalogueReviewsOnlyCo... |
codereview_python_data_245 | assert_eq(s1, s2, atol=0.01)
assert_eq(p1_proba, p2_proba, atol=0.8)
else:
assert_eq(p1, p2)
assert_eq(p1_proba, p2_proba, atol=0.03)
- assert_eq(y, p1)
- assert_eq(y, p2)
assert_eq(p1_local, p2)
- assert_eq(y, p1_local)
# pref_leaf values shou... |
codereview_python_data_246 | cols = ['Column_' + str(i) for i in range(X.shape[1])]
imptcs = []
for col in cols:
- try:
- imptcs.append(impcts_dict[col])
- except KeyError:
- imptcs.append(0.)
return np.array(imptcs)
X, ... |
codereview_python_data_250 | vrange = vrange or (
0 if len(v) == 0 else (int(F.asnumpy(F.max(v.tousertensor(), dim=0))) + 1))
- if len(u) > 0:
- assert urange > int(F.asnumpy(F.max(u.tousertensor(), dim=0))), \
- "The urange from card should be larger than max u node_id"
- if len(v) > 0:
- assert vrange... |
codereview_python_data_251 | parent_group = group_name(parent)
- if parent_group not in self.membership_cache:
- self.membership_cache[parent_group] = set()
- if member not in self.membership_cache[parent_group]:
- self.membership_cache[parent_group].add(member)
- self.membership.append(
... |
codereview_python_data_254 | sampling_probability: TensorLike,
embedding_fn: Union[TensorLike, Callable] = None,
time_major: bool = False,
- seed: Optional[TensorLike] = None,
scheduling_seed: Optional[TensorLike] = None,
):
"""Initializer.
```suggestion seed: Optional[int] = None, ``` Mayb... |
codereview_python_data_262 | class BigqueryDaoTest(ForsetiTestCase):
"""Tests for the BigqueryDao."""
- #FAKE_PROJECT_NUMBERS = ['11111']
-
@mock.patch.object(_db_connector.DbConnector, '__init__', autospec=True)
def setUp(self, mock_db_connector):
mock_db_connector.return_value = None
nit: Remove if it's not needed.
class BigqueryDao... |
codereview_python_data_271 | root.debug("Already set up logging")
-# setup_test_logging()
logging.info("Bootstrapped test")
This is needed for us to work in IDE UTs
root.debug("Already set up logging")
+setup_test_logging()
logging.info("Bootstrapped test") |
codereview_python_data_273 | -# -*- coding: utf-8 -*-
-"""
-Created on Wed Jan 16 14:20:24 2019
-
-"""
-
"`Learner` support for computer vision"
from ..torch_core import *
from ..basic_train import *
I think this may automatically be added by your text editor, please remove lines 1 to 6 (it should begin with "`Learner` support for computer vis... |
codereview_python_data_276 | '"algorithm":"GOOGLE_SYMMETRIC_ENCRYPTION",'
'"protectionLevel":"SOFTWARE"}}')
-NON_ROTATED_CRYPTO_KEY_STATE_DATA = ('{"createTime":"2019-01-22T23:30:18.939244464Z",'
'"name":"projects/red2k18-224817/locations/global/keyRings/'
'red_key_ring/crypto... |
codereview_python_data_277 | latest_listen = db_conn.fetch_listens(
user_name,
limit=1,
- to_ts=int(time.time()),
)
latest_listen_ts = latest_listen[0].ts_since_epoch if len(latest_listen) > 0 else 0
I think it'd make sense to only calculate time.time() once (it's also used if max_ts and min_ts aren't set)
... |
codereview_python_data_289 | Also cleans up the temp file if close is not invoked
"""
- def __init__(self, path, mode):
- super(AtomicLocalFile, self).__init__(path, mode)
-
def move_to_final_destination(self):
os.rename(self.tmp_path, self.path)
What happens if you remove this? Can't you still initialize this at... |
codereview_python_data_293 | from isbn_verifier import verify
-# Tests adapted from `problem-specifications//canonical-data.json` @ v2.0.0
class IsbnVerifierTests(unittest.TestCase):
Apologies for the delay in reviewing, but since this was written the canonical data has been updated. Can you please update the tests to v2.2.0?
from isbn_verifi... |
codereview_python_data_294 | for dst_type in <list>dest_sig:
found_matches = []
found_candidates = []
- # Make two seperate lists: One for for signature sub-trees with at least one definite match, and another for signature sub-trees with only ambiguous matches (where `de... |
codereview_python_data_297 | """Anchor-based head (RPN, RetinaNet, SSD, etc.).
Args:
- num_classes (int): Number of categories not including the background
category.
in_channels (int): Number of channels in the input feature map.
feat_channels (int): Number of hidden channels. Used in child classes.
... |
codereview_python_data_314 | "-Wno-switch-enum",
"-Wno-weak-template-vtables",
"-Wno-weak-vtables",
- "-Wno-implicit-int-float-conversion"
)
else:
ext.compiler.add_compiler_flag(
This option is not recognized by `Apple clang version 11.0.0 (clang-... |
codereview_python_data_317 | Returns:
list[Tensor]: Refined bboxes of each image in a mini-batch.
"""
bboxes_list = []
for i in range(len(img_metas)):
inds = torch.nonzero(rois[:, 0] == i).squeeze()
Why delete these two statements?
Returns:
list[Tensor]: Refined ... |
codereview_python_data_324 | logs.log_error('Unable to determine build parameters.')
return
- build_params_check_path = os.path.join(symbols_directory,
- '.cached_build_params')
- # Check if we already have the symbols locally.
- cached_build_params = utils.read_data_from_file(
- build_para... |
codereview_python_data_326 | super().__init__(database_manager, txn_type, CONFIG_LEDGER_ID)
self.write_req_validator = write_req_validator
self.constraint_serializer = ConstraintsSerializer(domain_state_serializer)
- self.config = getConfig()
- self._update_state_by_versions = self._get_update_state_by_vers... |
codereview_python_data_330 | agent_details = {
"agent_name": AGENT_NAME,
- "goal_state_version": str(GOAL_STATE_AGENT_VERSION),
"python_version": "Python: {0}.{1}.{2}".format(PY_VERSION_MAJOR, PY_VERSION_MINOR, PY_VERSION_MICRO),
"crp_supported_features": [name for name, _ in get_agent_sup... |
codereview_python_data_331 | nose_command_line += [self.script]
self._start_subprocess(nose_command_line)
- if self.__is_verbose() and is_linux():
self._tailer = FileTailer(self.stdout_file)
def check(self):
It should work cross-platform, not linux-only
nose_command_line += [self.script]
... |
codereview_python_data_335 | ::
ANSIBLE_ROLES_PATH:
- $ephemeral_directory/roles/:$project_directory/../:$HOME/.ansible/roles:/usr/share/ansible/roles:/etc/ansible/roles
ANSIBLE_LIBRARY:
- $ephemeral_directory/modules/:$project_directory/library/:$HOME/.ansible/plugins/modules:/usr/share/ansible/plugins/mod... |
codereview_python_data_347 | logs.log_error('CSP violation: {}'.format(self.request.get('csp-report')))
@handler.get(handler.JSON)
def get(self):
"""Handle a GET request."""
self.log_csp_violation()
@handler.post(handler.JSON, handler.JSON)
def post(self):
"""Handle a POST request."""
self.log_csp_violation()
... |
codereview_python_data_349 | # Testing xtc striding: Check for resolution of Issue #188
with tmpdir.as_cwd():
- with pytest.raises(FinishTimeException):
MDAnalysis.analysis.helanal.helanal_trajectory(
u, selection="name CA", finish=5
)
with tmpdir.as_cwd():
- with pytest.raise... |
codereview_python_data_353 | """
self.special_operation_modifiers[name] = func
""" PRIVATE """
async def _build_operation_object(self, data):
interesting idea. I like this. I'm wondering if this can be combined with the add_special_payload function on the file_svc. they do the same functionality, just different applica... |
codereview_python_data_362 | if replacement_is_path:
path = Path(replacement)
try:
- replacement = path.expanduser().resolve(strict=True)
except FileNotFoundError as e:
raise ValueError(f"Invalid file path: {replacement} ({e})")
This doesn't fly - we say `replacement` is a str, so we can't j... |
codereview_python_data_383 | def __len__(self):
if self.fold != -1:
- if self.cross_valid:
- print("WIP")
- else:
- return self.fold_start_idx[self.fold + 1] - self.fold_start_idx[self.fold]
return len(self.graph_lists)
def _download(self):
Will we implement this?
... |
codereview_python_data_384 | tab.openurl(url)
if background is None:
background = config.get('tabs', 'background-tabs')
- if not background:
- self.setCurrentWidget(tab)
- elif background:
self.tab_index_changed.emit(self.currentIndex(), self.count())
tab.show()
... |
codereview_python_data_387 | avg(t.average_exec_per_sec) as avg_exec_per_sec,
avg(t.fuzzing_time_percent) as fuzzing_time_percent,
sum(t.new_units_added) as new_tests_added,
-sum(t.new_cov_features) as new_cov_features,
avg(t.crash_count*100) as regular_crash_percent,
avg(t.oom_count*100) as oom_percent,
avg(t.leak_count*100) as leak_percent... |
codereview_python_data_397 | buckets = ab.pop('buckets', [tactic])
ab.pop('access', None)
plugin_path = pathlib.PurePath(filename).parts
- plugin = plugin_path[1] if 'plugins' in plugin_path else None
if tactic and tactic not in filename:
self.l... |
codereview_python_data_401 | def commit(self):
"""Commit the stored inventory."""
- if InventoryIndex.inventory_index_warnings:
status = IndexState.PARTIAL_SUCCESS
else:
status = IndexState.SUCCESS
Why are you referencing the class instead of the existing object?
def commit(self):
... |
codereview_python_data_408 | import torch
from mmcv.ops import batched_nms
-from mmdet.core import bbox2result
from mmdet.models.roi_heads.standard_roi_head import StandardRoIHead
from ..builder import HEADS
If `aug_test` is not supported yet, we should raise an exception.
import torch
from mmcv.ops import batched_nms
+from mmdet.core impo... |
codereview_python_data_412 | """
if isinstance(module, (nn.modules.batchnorm._BatchNorm, nn.GroupNorm)):
module.float()
- if (isinstance(module, nn.GroupNorm) or torch.__version__ < '1.3'
- or torch.__version__ == 'parrots'):
module.forward = patch_forward_method(module.forward, torch.half,
... |
codereview_python_data_413 | np.ndarray: The image with bboxes drawn on it.
"""
if kwargs is not None:
- if 'score_thr' in kwargs:
- kwargs.pop('score_thr')
- if 'text_color' in kwargs:
- kwargs.pop('text_color')
- if 'bbox_color' in kwargs:
- ... |
codereview_python_data_417 | TIME_TO_CONSIDER_STATS_AS_OLD = 12 # hours
-def new_user_stats():
return datetime.now(timezone.utc) - db_stats.get_timestamp_for_last_user_stats_update() > timedelta(hours=TIME_TO_CONSIDER_STATS_AS_OLD)
this function name doesn't exactly make it clear what is going on. Stats for a new user? Or new stats about us... |
codereview_python_data_421 | with call signature ``func(r, r0, **kwargs)`` (the "Contacts API").
pbc : bool (optional)
Uses periodic boundary conditions to calculate distances if set to ``True``; the
- default is ``False``.
kwargs : dict, optional
dictionary of additional kwargs ... |
codereview_python_data_427 | #
# kirchhoffs_circuit_laws.py - using NetworkX for Kirchhoff's circuit laws
#
-# Copyright 2015 NetworkX developers.
#
# This file is part of NetworkX.
#
Should kirchoffs_circuit_laws.py go with the examples?
#
# kirchhoffs_circuit_laws.py - using NetworkX for Kirchhoff's circuit laws
#
+# Copyright 2015 Ju... |
codereview_python_data_446 | out.append(('pac+https://example.com/proxy.pac', 'Proxy autoconfiguration file URL'))
return out
- def __repr__(self):
- return utils.get_repr(self, none_ok=self.none_ok,
- valid_values=self.valid_values)
-
class SearchEngineUrl(BaseType):
`valid_values` is fix... |
codereview_python_data_451 | @pytest.mark.usefixtures("maybe_run_functions_eagerly")
@pytest.mark.parametrize("dtype", [np.float16, np.float32, np.float64])
-def test_random(dtype):
inp = np.asanyarray(
[[[1.0, 1.0, 1.0, 1.0]], [[2.0, 2.0, 2.0, 2.0]], [[3.0, 3.0, 3.0, 3.0]]]
).astype(dtype)
NIT: this is not a test case about ... |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 10