id
stringlengths
30
32
content
stringlengths
139
2.8k
codereview_new_python_data_10124
def _apply(self, group): pairs_inner = distances.capped_distance(sel.positions, sys.positions, self.inRadius, box=box, return_distances=False) - inner = np.array(pairs_inner).T[1] - outer = np.array...
codereview_new_python_data_10125
def wrapper(*args, **kwargs): def check_atomgroup_not_empty(groupmethod): """Decorator triggering a ``ValueError`` if the underlying group is empty. - Avoids obscure computational errors on group methods. Raises ------ Does this work on all groups? If so we should change the name and test. Othe...
codereview_new_python_data_10126
def _load_offsets(self): "{self.filename}. Using slow offset calculation.") self._read_offsets(store=True) return - raise e with fasteners.InterProcessLock(lock_name) as filelock: if not isfile(fname): ```suggestion ...
codereview_new_python_data_10127
def return_data(self, data_selector: Union[str, List[str], None] = None) \ -> Dict[str, np.ndarray]: """ Returns the auxiliary data contained in the :class:`EDRReader`. Returns either all data or data specified as `data_selector` in form - of a str or a list of any of :attribute:`...
codereview_new_python_data_10128
def plot_mean_profile(self, bins=100, range=None, binned, bins = self.bin_radii(frames=frames, bins=bins, range=range) mean = np.array(list(map(np.mean, binned))) - midpoints = 0.5 * bins[1:] + 0.5 * bins[:-1] fig, ax = plt.subplots() if n_std: ```suggestion mid...
codereview_new_python_data_10318
from Bio import BiopythonParserWarning from Bio.Seq import Seq -from Bio.SeqFeature import ( - SimpleLocation, - Location, - Reference, - SeqFeature, - LocationParserError, -) # other Bio.GenBank stuff from .utils import FeatureValueCleaner Minor: Style wise although not formalised we've avoid ...
codereview_new_python_data_10319
def is_android_cuttlefish(plt=None): def is_android_emulator(plt=None): """Return True if we are on android emulator platform.""" - return 'ANDROID_EMULATOR' in (plt or get_platform_group()) def is_android_kernel(plt=None): I think there's a footgun in here: ``` >>> 'x' in ('y' or 'x') False >>> ('y' ...
codereview_new_python_data_10320
r'.*assertion failed at\s.*\sin\s*.*: (.*)') ASSERT_REGEX_GLIBC = re.compile( r'.*:\s*assertion [`\'"]?(.*?)[`\'"]? failed\.?$', re.IGNORECASE) -ASSERT_DISENGAGED_VALUE = re.compile( - r'.*\S.*\/.*:\d+:\s*assertion .* failed:\s*' - r'(optional operator.* called on a diseng...
codereview_new_python_data_10321
def check_error_and_log(error_regex, log_message_format): # Randomly set to ignore long running inputs. if engine_common.decide_with_probability( self.strategies.IGNORE_TIMEOUTS_PROB): - self.set_arg(fuzz_args, constants.IGNORE_TIMEOUTS_ENV_VAR, None) # Randomly set new vs. old...
codereview_new_python_data_10322
def test_pysecsan_command_os_system(self): data = self._read_test_data('pysecsan_command_os_system.txt') expected_type = 'PySecSan' expected_address = '' - expected_state = '' expected_stacktrace = data expected_security_flag = True self._validate_get_crash_data(data, expected_type, ex...
codereview_new_python_data_10323
def test_pysecsan_command_os_system(self): data = self._read_test_data('pysecsan_command_os_system.txt') expected_type = 'PySecSan' expected_address = '' - expected_state = '' expected_stacktrace = data expected_security_flag = True self._validate_get_crash_data(data, expected_type, ex...
codereview_new_python_data_10324
class FuzzResult(object): """Represents a result of a fuzzing session: a list of crashes found and the stats generated.""" - def __init__(self, logs, command, crashes, stats, time_executed, - process_timed_out=None): self.logs = logs self.command = command self.crashes = crashes ...
codereview_new_python_data_10325
def _group_testcases_based_on_variants(testcase_map): project_counter.items(), key=lambda x: x[1], reverse=True)[:10] log_string = "" for tid, count in top_matched_testcase: - log_string += "%s: %d, " % (tid, count) logs.log('VARIANT ANALYSIS (Project Report): project=%s, ' ...
codereview_new_python_data_10326
def _get_runner(): def _get_reproducer_path(log, reproducers_dir): """Gets the reproducer path, if any.""" crash_match = _CRASH_REGEX.search(log) - if not crash_match or not crash_match.group(1): return None tmp_crash_path = Path(crash_match.group(1)) prm_crash_path = Path(reproducers_dir) / tmp_cra...
codereview_new_python_data_10327
from local.butler import common -def execute(_): """Install all required dependencies for running tests, the appengine, and the bot.""" common.install_dependencies() appengine.symlink_dirs() I think you've said that `del X` is the preferred style these days. from local.butler import common ...
codereview_new_python_data_10328
def store_fuzzer_run_results(testcase_file_paths, fuzzer, fuzzer_command, fuzzer_return_code_string = 'Fuzzer timed out.' truncated_fuzzer_output = truncate_fuzzer_output(fuzzer_output, data_types.ENTITY_SIZE_LIMIT) - console_output = '%s: %s\n%s\n%s' % (bot...
codereview_new_python_data_10329
def test_ignore_linux_gate(self): expected_state, expected_stacktrace, expected_security_flag) - def test_capture_shell_bug(self): - """Test capturing shell bugs detected by extra sanitizers""" - data = self._read_test_data('shell_bug.txt')...
codereview_new_python_data_10330
def on_event_request_status(self, wallet, key, status): @event_listener def on_event_invoice_status(self, wallet, key, status): if wallet == self.wallet: - self._logger.debug('invoice status update for key %s' % key) - # FIXME event doesn't pass the new status, so we need to re...
codereview_new_python_data_10334
def generate_evaluation_code(self, code): code.putln('}') else: if item.value.type.is_array: - code.putln("memcpy(%s.%s, %s, sizeof %s);" % ( self.result(), item.key.value, ...
codereview_new_python_data_10336
class TemplateCode(object): """ _placeholder_count = 0 - def __init__(self, writer = None, placeholders = None, extra_stats=None): self.writer = PyxCodeWriter() if writer is None else writer self.placeholders = {} if placeholders is None else placeholders self.extra_stats = []...
codereview_new_python_data_10337
class SoftCComplexType(CComplexType): def __init__(self): super(SoftCComplexType, self).__init__(c_double_type) - def declaration_code(self, entity_code, - for_display = 0, dll_linkage = None, pyrex = 0): base_result = super(SoftCComplexType, self).declaration_code( ...
codereview_new_python_data_10338
def analyse_declarations(self, env): is_frozen = False dataclass_directives = env.directives["dataclasses.dataclass"] if dataclass_directives: - frozen_directive = dataclass_directives[1].get('frozen', None) is_frozen = frozen_d...
codereview_new_python_data_10339
def analyse_declarations(self, env): is_frozen = False dataclass_directives = env.directives["dataclasses.dataclass"] if dataclass_directives: - frozen_directive = dataclass_directives[1].get('frozen', None) is_frozen = frozen_d...
codereview_new_python_data_10340
def create_args_parser(): epilog="""Environment variables: CYTHON_FORCE_REGEN: if set to 1, forces cythonize to regenerate the output files regardless of modification times and changes. - Environment variables accepted by setuptools are supported to configure the C compiler and build: http...
codereview_new_python_data_10342
def compile_multiple(sources, options): a CompilationResultSet. Performs timestamp checking and/or recursion if these are specified in the options. """ - if len(sources) > 1 and options.module_name: raise RuntimeError('Full module name can only be set ' 'for singl...
codereview_new_python_data_10343
def generate_result_code(self, code): flags.append('CO_VARARGS') if self.def_node.starstar_arg: flags.append('CO_VARKEYWORDS') - if self.def_node.is_generator and self.def_node.is_coroutine: flags.append('CO_COROUTINE') - if self.def_node.is_asyncgen: -...
codereview_new_python_data_10345
def from_py_call_code(self, source_code, result_code, error_pos, code, return code.error_goto_if_neg(call_code, error_pos) def error_condition(self, result_code): - # It isn't possible to use CArrays return type so the error_condition - # is irrelevant. Returning a Falsey value does avoid...
codereview_new_python_data_10346
def test_invalid_ellipsis(self): try: ast.parse(textwrap.dedent(code)) except SyntaxError as exc: - assert "invalid syntax" in str(exc), str(exc) else: assert False, "Invalid Python code '%s' failed to raise an exception" % code ...
codereview_new_python_data_10347
class ControlFlow(object): entries set tracked entries loops list stack for loop descriptors exceptions list stack for exception descriptors - in_try_block int track if we're in a try...except or try...finally blcok """ def __init__(self): ```suggestion ...
codereview_new_python_data_10348
def assure_gil(code_path, code=code): assure_gil('error') if code.funcstate.error_without_exception: - code.put("if (PyErr_Occurred()) ") code.put_add_traceback(self.entry.qualified_name) else: warning(self.entry.pos,...
codereview_new_python_data_10349
def optimise_numeric_binop(operator, node, ret_type, arg0, arg1): if not numval.has_constant_result(): return None - is_float = isinstance(numval, ExprNodes.FloatNode) num_type = PyrexTypes.c_double_type if is_float else PyrexTypes.c_long_type if is_float: if operator not in ('Add...
codereview_new_python_data_10363
def set_environment(key, default): #set_environment('NCCL_SOCKET_IFNAME', 'hsi') set_environment('MIOPEN_DEBUG_DISABLE_FIND_DB', '1') set_environment('MIOPEN_DISABLE_CACHE', '1') - set_environment('NCCL_DEBUG', 'INFO') - set_environment('NCCL_DEBUG_SUBSYS', 'INIT') set...
codereview_new_python_data_10382
def run_step( if step.transformation: LOGGER.debug(f"transforming output with `{step.transformation}`") env = os.environ.copy() - env["INTEGRATION_DB_DIRECTORY"] = db_dir try: out = subprocess.run( ...
codereview_new_python_data_10395
def is_new_contributor(self, locale): """Return True if the user hasn't made contributions to the locale yet.""" return ( not self.translation_set.filter(locale=locale) - .exclude(entity__resource__project__slug="tutorial") .exists() ) I would generalize this to `entity__reso...
codereview_new_python_data_10396
def _get_site_url_netloc(): def _default_from_email(): return os.environ.get( - "DEFAULT_FROM_EMAIL", f"Pontoon <noreplay@{_get_site_url_netloc()}>" ) ```suggestion "DEFAULT_FROM_EMAIL", f"Pontoon <noreply@{_get_site_url_netloc()}>" ``` def _get_site_url_netloc(): def _default_f...
codereview_new_python_data_10397
class UserProfile(models.Model): # Visibility class Visibility(models.TextChoices): - ALL = "All users", "All users" TRANSLATORS = "Translators", "Users with translator rights" class VisibilityLoggedIn(models.TextChoices): At least to me, "All users" does not clearly communicate tha...
codereview_new_python_data_10432
# https://packaging.python.org/en/latest/discussions/install-requires-vs-requirements/#install-requires # It is not considered best practice to use install_requires to pin dependencies to specific versions. install_requires=[ - "aioquic>=0.9.20", "asgiref>=3.2.10,<3.6", "Brotli>...
codereview_new_python_data_10514
def _stamp_headers(self, visitor_headers=None, **headers): else: headers["stamped_headers"] = stamped_headers for stamp in headers.keys(): - if stamp != "stamped_headers" and stamp not in headers["stamped_headers"]: headers["stamped_headers...
codereview_new_python_data_10515
def _freeze_group_tasks(self, _id=None, group_id=None, chord=None, # Create two new generators from the original generator of the group tasks (cloning the tasks). tasks1, tasks2 = itertools.tee(self._unroll_tasks(self.tasks)) - # Use the first generator to freeze the group tasks ...
codereview_new_python_data_10516
def prepare_steps(self, args, kwargs, tasks, chain(group(signature1, signature2), signature3) --> Upgrades to chord([signature1, signature2], signature3) The responsibility of this method is to assure that the chain is - correctly unpacked, and that the correct callbacks are set up along the...
codereview_new_python_data_10517
def stamp(self, visitor=None, **headers): """ headers = headers.copy() if visitor is not None: - headers.update(visitor.on_signature(self, **headers)) else: headers["stamped_headers"] = [header for header in headers.keys() if header not in self.options] ...
codereview_new_python_data_10518
def on_stop(self) -> None: def on_apply( self, target: TargetFunction, - args: tuple | None = None, kwargs: dict[str, Any] | None = None, callback: Callable[..., Any] | None = None, accept_callback: Callable[..., Any] | None = None, ```suggestion args:...
codereview_new_python_data_10519
def __init__(self, url=None, open=open, unlink=os.unlink, sep=os.sep, def __reduce__(self, args=(), kwargs=None): kwargs = {} if not kwargs else kwargs - return super().__reduce__(args, dict(kwargs, url=self.url)) def _find_path(self, url): if not url: ```suggestion ret...
codereview_new_python_data_10521
def chordal_cycle_graph(p, create_using=None): def paley_graph(p, create_using=None): - """Returns the Paley $\\frac{(p-1)}{2}-$regular graph on $p$ nodes. The returned graph is a graph on $ \\mathbb{Z}/p\\mathbb{Z}$ with edges between $x$ and $y$ if and only if $x-y$ is a nonzero square in $\\math...
codereview_new_python_data_10522
"""Functions for computing and measuring community structure. -.. warning:: The functions in this class are not imported into the top-level -:mod:`networkx` namespace. - -They can be imported using the :mod:`networkx.algorithms.community` module, -then accessing the functions as attributes of ``community``. For ex...
codereview_new_python_data_10523
def test_claw(self): pytest.raises(nx.NetworkXError, nx.inverse_line_graph, G) def test_edgeless_graph(self): - # This graph has 2 nodes and 0 edges G = nx.Graph() - G_nodes = [0, 1] - G.add_nodes_from(G_nodes) pytest.raises(nx.NetworkXError, nx.inverse_line_graph...
codereview_new_python_data_10524
def test_claw(self): pytest.raises(nx.NetworkXError, nx.inverse_line_graph, G) def test_edgeless_graph(self): - # This graph has 2 nodes and 0 edges G = nx.Graph() - G_nodes = [0, 1] - G.add_nodes_from(G_nodes) pytest.raises(nx.NetworkXError, nx.inverse_line_graph...
codereview_new_python_data_10525
def test_edge_cases_directed_edge_swap(): graph = nx.path_graph(4, create_using=nx.DiGraph) with pytest.raises(nx.NetworkXAlgorithmError): nx.directed_edge_swap(graph, nswap=4, max_tries=10, seed=1) - graph = nx.DiGraph() - edges = [(0, 0), (0, 1), (1, 0), (2, 3), (3, 2)] - graph.add_edges_...
codereview_new_python_data_10526
def laplacian_spectrum(G, weight="weight"): Examples -------- - The multiplicity of O as an eigenvalue of the laplacian matrix is equal to the number of connected components of G. >>> import numpy as np ```suggestion The multiplicity of 0 as an eigenvalue of the laplacian matrix is equ...
codereview_new_python_data_10527
def laplacian_matrix(G, nodelist=None, weight="weight"): to a block diagonal matrix where each block is the respective Laplacian matrix for each component. - >>> G = nx.graph_atlas(26) #This graph from the Graph Atlas has 2 connected components. - >>> print(nx.laplacian_matrix(G).todense()) - [[ 1...
codereview_new_python_data_10528
def lattice_reference(G, niter=5, D=None, connectivity=True, seed=None): if len(G) < 4: raise nx.NetworkXError("Graph has less than four nodes.") if len(G.edges) < 2: - raise nx.NetworkXError("Graph has less than two edges") # Instead of choosing uniformly at random from a generated edge...
codereview_new_python_data_10529
def test_omega(): for o in omegas: assert -1 <= o <= 1 - -def test_graph_no_edges(): G = nx.Graph() G.add_nodes_from([0, 1, 2, 3]) - pytest.raises(nx.NetworkXError, nx.random_reference, G) - pytest.raises(nx.NetworkXError, nx.lattice_reference, G) ```suggestion ``` The tests wi...
codereview_new_python_data_10530
def test_degree_seq_c4(): assert degrees == sorted(d for n, d in G.degree()) -def test_no_edges(): G = nx.DiGraph() G.add_nodes_from([0, 1, 2]) - pytest.raises(nx.NetworkXError, nx.directed_edge_swap, G) - G = nx.Graph() - G.add_nodes_from([0, 1, 2, 3]) - pytest.raises(nx.NetworkXError, ...
codereview_new_python_data_10531
G = nx.path_graph(20) # An example graph center_node = 5 # Or any other node to be in the center edge_nodes = set(G) - {center_node} -pos = nx.circular_layout( - G.subgraph(edge_nodes) -) # Ensures the nodes around the circle are evenly distributed pos[center_node] = np.array([0, 0]) # Or off-center - whate...
codereview_new_python_data_10532
def test_multigraph_weighted_default_weight(self): G = nx.MultiDiGraph([(1, 2), (2, 3)]) # Unweighted edges G.add_weighted_edges_from([(1, 3, 1), (1, 3, 5), (1, 3, 2)]) - # Default value for default weight is 0 assert nx.dag_longest_path(G) == [1, 3] assert nx.dag_...
codereview_new_python_data_10533
def compute_v_structures(G): Returns ------- vstructs : iterator of tuples - The v structures within the graph. Each set has a 3-tuple with the parent, collider, and other parent. Notes ```suggestion The v structures within the graph. Each v structure is a 3-tuple with t...
codereview_new_python_data_10534
def test_hardest_prob(self): def test_strategy_saturation_largest_first(self): def color_remaining_nodes(G, colored_vertices): color_assignments = [] - aux_colored_vertices = { - key: value for key, value in colored_vertices.items() - } scrat...
codereview_new_python_data_10535
def assign_labels(G1, G2, mapped_nodes=None): return G1, G2 -def get_labes(G1, G2): return nx.get_node_attributes(G1, "label"), nx.get_node_attributes(G2, "label") ```suggestion def get_labels(G1, G2): ``` def assign_labels(G1, G2, mapped_nodes=None): return G1, G2 +def get_labels(G1, G...
codereview_new_python_data_10536
def _cut_PT(u, v, graph_params, state_params): ): return True - if len(T1.intersection(G1_nbh)) != len(T2.intersection(G2_nbh)) or len( - T1_out.intersection(G1_nbh) - ) != len(T2_out.intersection(G2_nbh)): return True return False ```sugges...
codereview_new_python_data_10537
def test_updating(self): m, m_rev, T1, T1_tilde, T2, T2_tilde = sparams # Add node to the mapping - m.update({4: self.mapped[4]}) - m_rev.update({self.mapped[4]: 4}) _update_Tinout(4, self.mapped[4], gparams, sparams) assert T1 == {3, 5, 9} Just a nit, but it'd be...
codereview_new_python_data_10573
# Script to run automated C++ tests. # -# Types of automated tests. # 1. Requires credentials, permissions, and AWS resources. # 2. Requires credentials and permissions. # 3. Does not require credentials (mocked if necessary). ```suggestion # Types of automated tests: ``` # Script to run automated C++ t...
codereview_new_python_data_10575
def hello_stepfunctions(stepfunctions_client): """ Use the AWS SDK for Python (Boto3) to create an AWS Step Functions client and list - the state machines in your account. This list may be empty if you have not created any state machines. This example uses the default settings specified in your...
codereview_new_python_data_10629
async def get_operation_link(self, request: web.Request): 'description': 'UUID of the link object to retrieve results of.' }]) @aiohttp_apispec.querystring_schema(BaseGetOneQuerySchema) - @aiohttp_apispec.response_schema(LinkResultSchema(partial=True), ...
codereview_new_python_data_10630
def __getitem__(self, key): # loc['level_one_key', 'column_name']. It's possible for both to be valid # when we have a multiindex on axis=0, and it seems pandas uses # interpretation 1 if that's possible. Do the same. try: - return self._helper_for__ge...
codereview_new_python_data_10631
def get_positions_from_labels(self, row_loc, col_loc): if axis_loc.stop is None or not is_number(axis_loc.stop): slice_stop = axis_loc.stop else: - slice_stop = axis_loc.stop - ( - 0 if axis_loc.step is...
codereview_new_python_data_10632
def concat( for obj in list_of_objs if ( isinstance(obj, (Series, pandas.Series)) - or ( - isinstance(obj, (DataFrame, Series)) - and obj._query_compiler.lazy_execution - ) or sum(obj.shape) ...
codereview_new_python_data_10633
def concat( for obj in list_of_objs if ( isinstance(obj, (Series, pandas.Series)) - or ( - isinstance(obj, (DataFrame, Series)) - and obj._query_compiler.lazy_execution - ) or sum(obj.shape) ...
codereview_new_python_data_10634
def isin(self, values, ignore_indices=False, **kwargs): # noqa: PR02 Boolean mask for self of whether an element at the corresponding position is contained in `values`. """ - # We drop `shape_hint` argument that may be passed from the API layer. - # BaseQC doesn't need...
codereview_new_python_data_10635
def stack(self, level, dropna): # These operations are operations that apply a function to every partition. def isin(self, values, ignore_indices=False, shape_hint=None): if isinstance(values, type(self)): - # HACK: if we won't cast to pandas then the execution engine will try to - ...
codereview_new_python_data_10636
def func(df) -> np.ndarray: ser = ser.astype("category", copy=False) return ser.cat.codes.to_frame(name=MODIN_UNNAMED_SERIES_LABEL) - res = self._modin_frame.apply_full_axis( - axis=0, - func=func, - new_index=self._modin_frame._index_cache, - ...
codereview_new_python_data_10637
def map(self, arg, na_action=None): # noqa: PR01, RT01, D200 """ if isinstance(arg, type(self)): # HACK: if we won't cast to pandas then the execution engine will try to - # # propagate the distributed Series to workers and most likely would have # some performan...
codereview_new_python_data_10638
def map(self, arg, na_action=None): # noqa: PR01, RT01, D200 Map values of Series according to input correspondence. """ if isinstance(arg, type(self)): - # HACK: if we won't cast to pandas then the execution engine will try to # propagate the distributed Series to w...
codereview_new_python_data_10639
def _set_item(df, row_loc): new_columns=self._modin_frame._columns_cache, keep_partitioning=False, ) - return self.__constructor__(new_modin_frame, shape_hint="column") # END __setitem__ methods ```suggestion return self.__constructor__(new_modin_frame) ```...
codereview_new_python_data_10640
def broadcast_axis_partitions( num_splits = NPartitions.get() preprocessed_map_func = cls.preprocess_func(apply_func) left_partitions = cls.axis_partition(left, axis) - if right is None: - right_partitions = None - else: - right_partitions = cls.axis_p...
codereview_new_python_data_10641
def materialize(cls, obj_id): @classmethod def put(cls, data, **kwargs): """ - Put a data into the object store. Parameters ---------- data : object Data to be put. Returns ------- unidist.ObjectRef A referenc...
codereview_new_python_data_10642
def materialize(cls, obj_id): @classmethod def put(cls, data, **kwargs): """ - Put a data into the object store. Parameters ---------- data : object Data to be put. Returns ------- unidist.ObjectRef A referenc...
codereview_new_python_data_10643
def wait(self): wait([self._data]) # If unidist has not been initialized yet by Modin, - # unidist itself handles initialization when calling `UnidistWrapper.put`. _iloc = execution_wrapper.put(PandasDataframePartition._iloc) def mask(self, row_labels, col_labels): ```suggestion # ...
codereview_new_python_data_10644
# If unidist has not been initialized yet by Modin, -# unidist itself handles initialization when calling `UnidistWrapper.put`. _DEPLOY_AXIS_FUNC = UnidistWrapper.put(PandasDataframeAxisPartition.deploy_axis_func) _DRAIN = UnidistWrapper.put(PandasDataframeAxisPartition.drain) ```suggestion # unidist itself...
codereview_new_python_data_10645
def wait(self): wait([self._data]) # If unidist has not been initialized yet by Modin, - # it will be initialized when calling `UnidistWrapper.put`. _iloc = execution_wrapper.put(PandasDataframePartition._iloc) def mask(self, row_labels, col_labels): ```suggestion # unidist itself ...
codereview_new_python_data_10646
def mean(x1, axis=None, dtype=None, out=None, keepdims=None, *, where=True): # Maximum and minimum are ufunc's in NumPy, which means that our array's __array_ufunc__ -# implementation will automatically handle this, so we can just use NumPy's maximum/minimum -# since that will route to our array's ufunc. def max...
codereview_new_python_data_10647
def isscalar(e): less_equal = _dispatch_logic("less_equal") equal = _dispatch_logic("equal") not_equal = _dispatch_logic("not_equal") -array_equal = _dispatch_logic("array_equal") We don't define `array_equal` anywhere. Should this be `equal`? def isscalar(e): less_equal = _dispatch_logic("less_equal") equal =...
codereview_new_python_data_10648
def func(df) -> np.ndarray: # if the dfs have categorical columns # so we intentionaly restore the right dtype. # TODO: revert the change when https://github.com/pandas-dev/pandas/issues/51362 is fixed. - ser = df.astype("category", copy=False).iloc[:, 0] ...
codereview_new_python_data_10649
def func(df) -> np.ndarray: # if the dfs have categorical columns # so we intentionaly restore the right dtype. # TODO: revert the change when https://github.com/pandas-dev/pandas/issues/51362 is fixed. - ser = df.astype("category", copy=False).iloc[:, 0] ...
codereview_new_python_data_10650
def _compute_duplicated(df): ) return result - if len(self._modin_frame.column_widths) > 1: # if the number of columns (or column partitions) we are checking for duplicates is larger than 1, # we must first hash them to generate a single value that can b...
codereview_new_python_data_10651
def __init__( self._dtypes = dtypes self._validate_axes_lengths() - if all(obj is not None for obj in (index, columns, row_lengths, column_widths)): - # this hint allows to filter empty partitions out without triggering metadata computation - # in order to avoid useless...
codereview_new_python_data_10652
def __init__( self._dtypes = dtypes self._validate_axes_lengths() - if all(obj is not None for obj in (index, columns, row_lengths, column_widths)): - # this hint allows to filter empty partitions out without triggering metadata computation - # in order to avoid useless...
codereview_new_python_data_10653
def _reset(df, *axis_lengths, partition_idx): self._modin_frame.apply_full_axis( axis=1, func=_reset, - other=None, enumerate_partitions=True, new_columns=new_columns, sync_label...
codereview_new_python_data_10654
def func(df, **kw): return pandas.DataFrame() result = qc._modin_frame.apply_full_axis( - 1, func, other=None, new_index=[], new_columns=[], enumerate_partitions=True ) result.to_pandas() ```suggestion 1, func, new_index=[], new_columns=[], enumerate...
codereview_new_python_data_10655
def func(df, **kw): return pandas.DataFrame() result = qc._modin_frame.apply_full_axis( - 1, func, other=None, new_index=[], new_columns=[], enumerate_partitions=True ) result.to_pandas() ```suggestion 1, func, new_index=[], new_columns=[], enumerate...
codereview_new_python_data_10656
def test_indexing_duplicate_axis(data): "series_of_integers", ], ) -def test_set_index(data, key_func): - eval_general(*create_test_dfs(data), lambda df: df.set_index(key_func(df))) @pytest.mark.parametrize("index", ["a", ["a", ("b", "")]]) If we are not testing `drop==False` parameter, then le...
codereview_new_python_data_10657
def files(self): try: files = self.dataset.files except AttributeError: - # compatibility with 4.0.1 <= pyarrow < 8.0.0 files = self.dataset._dataset.files self._files = self._get_files(files) return self._files tested th...
codereview_new_python_data_10658
def merge_partitioning(left, right, axis=1): ------- int """ - # Avoiding circular imports from pandas query compiler - from modin.core.storage_formats.pandas.utils import compute_chunksize - lshape = left._row_lengths_cache if axis == 0 else left._column_widths_cache rshape = right._row...
codereview_new_python_data_10659
def getitem_column_array(self, key, numeric=False): new_modin_frame = self._modin_frame.take_2d_labels_or_positional( col_labels=key ) - return self.__constructor__(new_modin_frame, shape_hint) def getitem_row_array(self, key): return self.__constructor...
codereview_new_python_data_10660
def reindex(self, axis, labels, **kwargs): def reset_index(self, **kwargs): if self._modin_frame._index_cache is None: - def _reset(df, *columns_idx, partition_idx): _kw = dict(kwargs) if len(columns_idx) > 1 and partition_idx == 0: old_...
codereview_new_python_data_10661
def broadcast_apply_full_axis( the provided hints in order to save time on syncing them. pass_cols_to_partitions : bool, default: False Whether pass columns into applied `func` or not. - Note that `func` must be able to obtain `*columns` arg. Returns --...
codereview_new_python_data_10662
def broadcast_axis_partitions( Note that `apply_func` must be able to accept `partition_idx` kwarg. lengths : list of ints, default: None The list of lengths to shuffle the object. - apply_func_args : bool, optional - Whether pass extra args to `func` or not. - ...
codereview_new_python_data_10663
def broadcast_apply_full_axis( kw = {} if dtypes == "copy": kw["dtypes"] = self._dtypes - elif dtypes is not None and new_columns is not None: columns = new_columns if new_columns is not None else self.columns kw["dtypes"] = pandas.Series( ...
codereview_new_python_data_10664
def broadcast_apply_full_axis( kw = {} if dtypes == "copy": kw["dtypes"] = self._dtypes - elif dtypes is not None and new_columns is not None: columns = new_columns if new_columns is not None else self.columns kw["dtypes"] = pandas.Series( ...
codereview_new_python_data_10665
def broadcast_apply_full_axis( kw = {} if dtypes == "copy": kw["dtypes"] = self._dtypes - elif dtypes is not None and new_columns is not None: columns = new_columns if new_columns is not None else self.columns kw["dtypes"] = pandas.Series( ...
codereview_new_python_data_10666
def broadcast_apply_full_axis( Setting it to True disables shuffling data from one partition to another. synchronize : boolean, default: True Synchronize external indexes (`new_index`, `new_columns`) with internal indexes. Returns ------- always better to add an ...