question_id int64 59.5M 79.7M | creation_date stringdate 2020-01-01 00:00:00 2025-07-15 00:00:00 | link stringlengths 60 163 | question stringlengths 53 28.9k | accepted_answer stringlengths 26 29.3k | question_vote int64 1 410 | answer_vote int64 -9 482 |
|---|---|---|---|---|---|---|
78,203,312 | 2024-3-21 | https://stackoverflow.com/questions/78203312/polars-map-batches-udf-with-multi-processing | I want to apply a numba UDF, which generates the same length vectors for each groups in df: import numba df = pl.DataFrame( { "group": ["A", "A", "A", "B", "B"], "index": [1, 3, 5, 1, 4], } ) @numba.jit(nopython=True) def UDF(array: np.ndarray, threshold: int) -> np.ndarray: result = np.zeros(array.shape[0]) accumulato... | Here is example how you can do this with numba + using numba's parallelization features: from numba import njit, prange @njit(parallel=True) def UDF_nb_parallel(array, n, threshold): result = np.zeros_like(array, dtype="uint8") for i in prange(array.size // n): accumulator = 0 for j in range(i * n, (i + 1) * n): value ... | 4 | 2 |
78,209,144 | 2024-3-22 | https://stackoverflow.com/questions/78209144/list-comprehension-to-remove-element-from-python-list-if-it-is-only-digits-even | I have many lists like this synonyms = ["3,2'-DIHYDROXYCHALCONE", '36574-83-1', '36574831', "2',3-Dihydroxychalcone", '(E)-1-(2-hydroxyphenyl)-3-(3-hydroxyphenyl)prop-2-en-1-one', MLS002693861] from which I need to remove all elements that are comprised of only digits. I can't figure out how to remove element [1] beca... | Try: synonyms = [ "3,2'-DIHYDROXYCHALCONE", "36574-83-1", "36574831", "2',3-Dihydroxychalcone", "(E)-1-(2-hydroxyphenyl)-3-(3-hydroxyphenyl)prop-2-en-1-one", "MLS002693861", ] out = [s for s in synonyms if not all(ch in "0123456789-_" for ch in s)] print(out) Prints: [ "3,2'-DIHYDROXYCHALCONE", "2',3-Dihydroxychalcone... | 2 | 3 |
78,203,545 | 2024-3-22 | https://stackoverflow.com/questions/78203545/discretized-function-becomes-complex-while-free-propagating-a-real-function-when | My code involves propagation of a real function using Fourier transform and inverse Fourier transform. Specifically, the function evolves as ∂ψ(z,t)/∂t - v ∂ψ(z,t)/∂z =0 I solve this problem by Fourier transforming the above equation given by ∂ψ(k,t)/∂t + ikv ψ(k,t)=0 which has a solution given by ψ(k,t)=e^(-ikvt)ψ(k,... | Look at k_vals: With Nd=6: [0., 6.28318531, 12.56637061, -18.84955592, -12.56637061, -6.28318531] With Nd=5: [0., 6.28318531, 12.56637061, -12.56637061, -6.28318531] When Nd is even, there's one negative frequency that doesn't have a positive frequency counterpart. As we know, the input to the IFFT must be conjugate ... | 3 | 1 |
78,208,703 | 2024-3-22 | https://stackoverflow.com/questions/78208703/in-a-2d-numpy-array-how-to-select-every-first-and-second-element-of-the-inner-a | For example the array: array = np.array([[1, 1, 4, 2, 1, 8], [1, 1, 8, 2, 1, 16], [1, 1, 40, 2, 1, 80], [1, 2, 40, 2, 1, 80]]) I'd like to essentially remove every third [:, ::2] element of the inner arrays. So the result should be: [[1 1 2 1] [1 1 2 1] [1 1 2 1] [1 2 2 1]] I could do two selections and concatenate e... | You can use boolean indexing: array[:, np.arange(array.shape[1]) % 3 != 2] array([[1, 1, 2, 1], [1, 1, 2, 1], [1, 1, 2, 1], [1, 2, 2, 1]]) | 3 | 3 |
78,208,576 | 2024-3-22 | https://stackoverflow.com/questions/78208576/how-to-filter-a-dataframe-by-row-id-row-number | I am looking to get a subset of rows based on the row_id/row_number for a dataframe similar to pyarrow.Table.take. For eg: given the below dataframe from datetime import datetime df = pl.DataFrame( { "integer": [1, 2, 3, 4, 5], "date": [ datetime(2022, 1, 1), datetime(2022, 1, 2), datetime(2022, 1, 3), datetime(2022, 1... | df[[0,4]] will allow to select the indices 0 and 4. Since take is deprecated, the equivalent to your proposed code would be to use gather: df.select(pl.all().gather([0, 4])) Output: shape: (2, 3) ┌─────────┬─────────────────────┬───────┐ │ integer ┆ date ┆ float │ │ --- ┆ --- ┆ --- │ │ i64 ┆ datetime[μs] ┆ f64 │ ╞════... | 2 | 1 |
78,207,935 | 2024-3-22 | https://stackoverflow.com/questions/78207935/different-output-showing-from-a-source-code-machine-learning-python | I'm currently trying to work on a small image machine learning project. I found this person's Kaggle code and I tried replicating it from scratch. However, not even in the main part, I already faced an error. I'm sure there must be a localization issue on my end on how this ended up but I can't figure what. My code: #I... | Based on your folder structure and the code you have provided, the issue is that you haven't put the trailing slash at the end of your folder paths. In the provided code, you're trying to concatenate the folder name directly with the path. However, if you miss a slash or if the folder variable does not include a traili... | 2 | 2 |
78,202,730 | 2024-3-21 | https://stackoverflow.com/questions/78202730/polars-efficient-way-to-apply-function-to-filter-column-of-strings | I have a column of long strings (like sentences) on which I want to do the following: replace certain characters create a list of the remaining strings if a string is all text see whether it is in a dictionary and if so keep it if a string is all numeric keep it if a string is a mix of numeric/text, find ratio of numb... | The filtering can be implemented using polars' native expression API as follows. I've taken the regular expressions from the naive implementation in the question. word_list = ["cost", "atm"] # to avoid long expressions in ``pl.Expr.list.eval`` num_dec_expr = pl.element().str.count_matches(r'[0-9_\/]').cast(pl.Int32) nu... | 2 | 3 |
78,207,067 | 2024-3-22 | https://stackoverflow.com/questions/78207067/how-to-get-the-sub-columns-from-a-pandas-dataframe-after-a-groupby-and-agg | I'm attempting to perform a groupby and aggregate operation on a Pandas DataFrame. Specifically, I want to compute the mean and count for each class group. However, I'm encountering issues accessing the generated columns. Here's an example of the transformation I'm aiming for: import pandas as pd df = pd.DataFrame({ 'C... | You should slice before agg: grouped = df.groupby(by='Class', as_index=False)['Val'].agg(['mean', 'count']) Output: Class mean count 0 A 30.0 2 1 B 35.0 2 2 C 15.0 1 | 2 | 1 |
78,203,785 | 2024-3-22 | https://stackoverflow.com/questions/78203785/polars-rolling-by-option-not-allowed | I have a data frame of the type: df = pl.LazyFrame({"day": [1,2,4,5,2,3,5,6], 'type': ['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b'], "value": [1, 0, 3, 4, 2, 2, 0, 1]}) day type value i64 str i64 1 "a" 1 2 "a" 0 4 "a" 3 5 "a" 4 2 "b" 2 3 "b" 2 5 "b" 0 6 "b" 1 I am trying to create a rolling sum variable, summing, for each ... | That's because in your code you're trying to use Expr.rolling() which doesn't have by parameter (strangely, it is mentioned in the documentation under check_sorted parameter - is it just not implemented yet?), instead of DataFrame.rolling(). If you'd restructure the code to use the latter then it works fine: ( df.rolli... | 5 | 7 |
78,193,123 | 2024-3-20 | https://stackoverflow.com/questions/78193123/how-to-use-window-function-in-pyspark-dataframe | I have a pyspark dataframe as below: Mail sno mail_date date1 present abc@abc.com 790 2024-01-01 2024-02-06 yes abc@abc.com 790 2023-12-23 2023-01-01 nis@abc.com 101 2022-02-23 nis@abc.com 101 2021-01-20 2022-07-09 yes In the final dataframe, I need one record of sno with all the max date values and corresponding max ... | Even thought @DerekO's answer seems correct. I'd like to take another approach on this. I prefer using the groupBy().agg() approach with max and struct. This approach is more efficient in terms of data reduction specially when working with large datasets. So considering the data that you have provided : df_result = df.... | 2 | 1 |
78,204,054 | 2024-3-22 | https://stackoverflow.com/questions/78204054/what-am-i-understanding-wrong-about-this-simple-asynchio-example | I can't wrap my head around how to use aynchio. Can you please just help me fix this issue. Assume I have some IO task which takes 8 seconds that I put in the coroutine task(). I want to run an infinite loop and perform this take every 5 seconds without blocking my code. import asyncio async def task(): print('starting... | Your issue is you're awaiting the coroutine, which does what it says on the box: It stops anything from proceeding until it completes (to say it doesn't go back to main isn't quite right either. It does, just later than you wanted). Spinning it out to another unawaited task will let it "run in the background" import as... | 2 | 2 |
78,203,237 | 2024-3-21 | https://stackoverflow.com/questions/78203237/how-to-implement-the-observer-pattern-using-async-iterators-in-python | I'm working on implementing the observer pattern in Python using asyncio and async iterators. The goal is to create a “change stream” where tasks can add changes, and other tasks can subscribe to these changes as asynchronous iterators. I'm trying to create an interface similar to broadcast streams in Dart. Here's a si... | From your description and comment, it appears you're really looking for a Publish-Subscribe pattern instead of an Observer pattern. They are similar, but where Observers are typically known by the subject and get updates directly, in Publish-Subscribe, the publisher publishes to a bus (like your Stream) that tracks con... | 2 | 4 |
78,203,142 | 2024-3-21 | https://stackoverflow.com/questions/78203142/how-to-populate-null-values-in-columns-after-outer-join-in-python-pandas | My goal is to join two dataframes from different sources in Python using Pandas and then fill null values in columns with corresponding values in the same column. The dataframes have similar columns, but some text/object columns may have different values due to variations in the data sources. For instance, the "Name" c... | # a list with all column names, minus `(dfx)` columns = ["Date", "Order Id", "Employee Id", "Name", "Region", "Value"] # create a dict with a relation between values in df1 and df2, both ways value_relations = {} for col in columns: relations = ( outer_joined_df[[f"{col} (df1)", f"{col} (df2)"]] .drop_duplicates() .dro... | 2 | 1 |
78,203,219 | 2024-3-21 | https://stackoverflow.com/questions/78203219/dealing-with-non-optimal-solutions-from-gekko | I'm running into some situations where it seems like Gekko is getting stuck in local maximums and was wondering what approaches could be used to get around this or dig deeper into the cause (including default settings below). For example, running the scenario below yields an objective of "-5127.34945104756" m = GEKKO(r... | Gekko solvers are gradient-based Nonlinear Programming (NLP) solvers that find local minima. There are a few strategies to help Gekko find the global optimum. Here is an example that can help with this important topic of local vs. global minima. The following script produces the local (not global) solution of (7,0,0) w... | 2 | 1 |
78,203,276 | 2024-3-21 | https://stackoverflow.com/questions/78203276/pandas-converting-dataframe-column-to-int-following-dataframe-manipulation | Running pandas 1.5.3. Also attempted on pandas 2.2.1. I am loading in data from a CSV that looks like such: 888|0|TEST ACCOUNT 888|1|Sample Ship-to 802001|0|COMPANY 1 802001|1|COMPANY 1 INC 802001|2|COMPANY 1 BALL K802001|3|COMPANY 1 With columns CUSNO, S2, and NAME, in that order. I have a script that loads in the da... | I think simple (after dropping the NaNs): df["CUSNO"] = df["CUSNO"].astype(int) print(df) Prints: CUSNO S2 NAME 0 888 0 TEST ACCOUNT 1 888 1 Sample Ship-to 2 802001 0 COMPANY 1 3 802001 1 COMPANY 1 INC 4 802001 2 COMPANY 1 BALL | 2 | 1 |
78,202,373 | 2024-3-21 | https://stackoverflow.com/questions/78202373/how-to-use-layered-conditional-constraints-in-gekko | I'm trying to implement conditional logic in Gekko using "if3" but am unsure how to successfully layer 2 conditions at different levels of granularity. "x1" is vector of binary values (0/1) that controls when an alternative rhs value should be used on element i to constrain x2 and x3. "x2" is a vector of floats where I... | The .lower and .upper bounds are defined when the model is initialized and do not change to reflect newly optimized values. To implement these, use an inequality expression. Use a switching point of 0.5 instead of 1 to avoid numerical issues with an integer value >1 or >=1. The solver tolerance is 1e-6 by default so a ... | 2 | 1 |
78,200,862 | 2024-3-21 | https://stackoverflow.com/questions/78200862/how-may-i-combine-multiple-adapters-in-python-requests | I need to make multiple calls to a web endpoint that is somewhat unreliable, so I have put together a timeout/retry strategy that I issue to a requests.Session() object as an adapter. However, I also need to mount this same endpoint using a client PKCS12 certificate and a public certificate authority (verify), which I ... | Assuming you want the default timeout behavior from TimeoutAdapter, then since TimeoutAdapter and Pkcs12Adapter both inherit from HTTPAdapter, you can have the former inherit from the latter (single inheritance). For example: # timeout.py from requests import Session from requests_pkcs12 import Pkcs12Adapter DEFAULT_TI... | 2 | 2 |
78,191,777 | 2024-3-20 | https://stackoverflow.com/questions/78191777/how-to-find-min-cost-for-element-selection-from-a-sequence-of-adjacent-pairs | Given an array of integers (with at least two elements), I need to choose at least one element of each adjacent pair of elements in the array in a way that costs me the least. Then, return the cost and elements chosen. For example, [50, 30, 40, 60, 10, 30, 10] We choose 30 for the pair (50, 30), and for the pair (30, ... | Calling cost(i) the cost of the optimal solution when considering the array up to element i included only, there is a simple recurrence formula for this problem: cost(i) = min( arr[i] + cost(i-1), arr[i-1] + cost(i-2), ) For instance, the cost for array [50, 30, 40, 60, 10, 30, 10] is the minimum of 10 + cost for [50,... | 3 | 0 |
78,196,569 | 2024-3-20 | https://stackoverflow.com/questions/78196569/extract-words-from-one-df-column-assign-to-another-column | I have two columns in a dataframe: Pests and FieldComment. If the value of Pests is listed as 'None', then I'd like to search the FieldComment column for specific words and overwrite what's in the Pests column. If none of the words are found in the FieldComment column, the Pests column can remain as 'None'. Example: pe... | Convert the pests list into a set. Create a set with the words from FieldComment. Get the intersection of both sets and fill column Pests where it is null. pests_set = set([p.lower() for p in pests_list]) df.loc[df["Pests"].isna(), "Pests"] = df["FieldComment"].apply( lambda x: ", ".join( set(x.strip(".").lower().spl... | 2 | 3 |
78,199,615 | 2024-3-21 | https://stackoverflow.com/questions/78199615/how-to-filter-groups-max-and-min-rows-using-transform | I am working on a task wherein, I need to filter in rows that contain the group's max and min values and filter out other rows. This is to understand how the values change at each decile. np.random.seed(0) df = pd.DataFrame({'id' : range(1,31), 'score' : np.random.uniform(size = 30)}) df id score 0 1 0.548814 1 2 0.715... | Use DataFrame.transform with 2 masks by Series.eq chained by bitwise OR - |: g = df.groupby('decile')['score'] out = df[df['score'].eq(g.transform('min')) | df['score'].eq(g.transform('max'))] print (out) id score decile 1 2 0.715189 6 2 3 0.602763 5 3 4 0.544883 4 5 6 0.645894 5 6 7 0.437587 2 9 10 0.383442 1 10 11 0.... | 2 | 3 |
78,194,029 | 2024-3-20 | https://stackoverflow.com/questions/78194029/is-it-feasible-to-create-virtual-machines-in-kubevirt-through-python-client | KubeVirt is an extension of Kubernetes, enabling it to manage virtual machines.I have deployed a KubeVirt cluster. I want to use Python Client to operate KubeVirt to manage virtual machines. Is this feasible? I use Kubernetes Python Client.But it does not seem to support the resource type of virtual machine.My cluster ... | You're trying to create resources that use the kubevirt.io/v1 api. This isn't a core Kubernetes API; it's provided by the kubevirt custom resource definition, which means it's not supported by any of the static parts of the Python kubernetes client. But don't worry, that's what the DynamicClient is for! You can find so... | 2 | 1 |
78,192,336 | 2024-3-20 | https://stackoverflow.com/questions/78192336/how-to-find-cycles-among-an-array-of-lines | I have a minimal reproducible example. Input data: coordinates = [(50.0, 50.0, 100.0, 50.0), (70.0, 50.0, 75.0, 40.0, 80.0, 50.0)] This is what these lines form in the drawing: The task is to find a loop, i.e. a closed region, and display their boundaries in the terminal. In this case, the result should be as follows... | IIUC, you want the induced / chordless_cycles. If so, here is a primal approach with networkx: points = MultiPoint(list(batched(chain.from_iterable(coordinates), 2))) lines = [ line for coo in coordinates for pop in pairwise(batched(coo, 2)) for gc in [split(LineString(pop), points)] for line in gc.geoms ] G = gdf_to_n... | 3 | 2 |
78,191,983 | 2024-3-20 | https://stackoverflow.com/questions/78191983/what-does-freq-infer-do-in-pandas-shift-how-does-it-differ-from-freq-d | I didn't see the difference between freq in .shift() df = pd.DataFrame({"Col1": [10, 20, 15, 30, 45], "Col2": [13, 23, 18, 33, 48], "Col3": [17, 27, 22, 37, 52]}, index=pd.date_range("2020-01-01", "2020-01-05")) df.shift(periods=2, freq="infer") Col1 Col2 Col3 2020-01-03 10 13 17 2020-01-04 20 23 27 2020-01-05 15 18 22... | freq='infer' means that the frequency is inferred from the index metadata. freq DateOffset, tseries.offsets, timedelta, or str, optional Offset to use from the tseries module or time rule (e.g. ‘EOM’). If freq is specified then the index values are shifted but the data is not realigned. That is, use freq if you would ... | 2 | 2 |
78,192,256 | 2024-3-20 | https://stackoverflow.com/questions/78192256/decorated-function-call-now-showing-warning-for-incorrect-arguments-in-pycharm | I'm having some problems when static type checking decorated functions. For instance, when I use an incorrect function argument name or type, I don't get any warning or error hints in the IDE, only at runtime. What steps will reproduce the problem? Add a decorator to a function Use a incorrect argument name or type ... | Looks similar to this PyCharm issue. If you are willing to annotate the decorator with ParamSpec you can do ... from typing import ParamSpec from typing import TypeVar from typing import Callable P = ParamSpec("P") T = TypeVar("T") def myDecorator(func: Callable[P, T]) -> Callable[P, T]: def wrapper(*args: P.args, **kw... | 2 | 2 |
78,191,270 | 2024-3-20 | https://stackoverflow.com/questions/78191270/type-conversion-using-type-hinting | Say, I have a function that should do some internal stuff and display the provided text: def display_text(text: str): ... print(text) There's also a class with a convert() method: class String: def __init__(self, string: str): self.string = string def convert(self): return self.string Now, can you type hint text argu... | Can you type hint text argument in display_text with String, but if the provided parameter will be str, call convert and assign the returned value to text without any additional code in a display_text function, just with type hinting No, not just with type hinting, since type annotations are absolutely inert at runti... | 2 | 2 |
78,190,287 | 2024-3-20 | https://stackoverflow.com/questions/78190287/how-to-enforce-specific-elements-in-a-vector-to-be-in-an-optimization-solution-i | I'm trying to generate an optimal combination of p records in a vector of length n while simultaneously ensuring (constraining) that specific elements in the vector are included in the solution set p (based on a binary value for now) I have the equation "simu_total_volume" below that does work for ensuring the solution... | There are multiple ways to constrain particular elements within an array. Here is a complete example that optimizes the elements of X to minimize the total cost. Each element X can be [0,1] and two can be selected with sum(X)==2. from gekko import GEKKO m = GEKKO(remote=False) X = m.Array(m.Var,7,lb=0,ub=1,integer=True... | 2 | 1 |
78,190,336 | 2024-3-20 | https://stackoverflow.com/questions/78190336/what-is-a-fast-an-elegant-way-to-transform-a-column-with-a-bunch-a-duplicated-w | Lets assume we have a pandas data frame df with the column 'A', and the following non-vectorized transformation function: def transform_a_to_b(a): ... return b Then if we wanted to create the column 'B' using the transform on 'A', we could do the following: df['B'] = df['A'].apply(lambda x: transform_a_to_b(a)) What ... | Your approach is good, I would just use map+unique in place of merge+drop_duplicates. df['B'] = df['A'].map({k: transform_a_to_b(k) for k in df['A'].unique()}) A pythonic alternative would be to. cache your function: from functools import cache transform_counts = 0 @cache def transform_a_to_b(a): global transform_coun... | 3 | 3 |
78,190,327 | 2024-3-20 | https://stackoverflow.com/questions/78190327/issue-linking-css-to-html-file | I can't figure out how to link a CSS file to my HTML file. I'm am using Visual Studio Code, Python, and Flask to do this My project directory is like this: - templates - home.html - style.css - app.py home.html <!DOCTYPE html> <html> <head> <link href='https://fonts.googleapis.com/css?family=Raleway:400, 600' rel='sty... | In flask, your style.css file should be inside the 'static' folder. Then in your Html file you should link it like this: <link href="{{ url_for('static', filename='style.css') }}" rel="stylesheet" type="text/css"/> | 4 | 4 |
78,184,296 | 2024-3-19 | https://stackoverflow.com/questions/78184296/pivot-a-dataframe-using-polars-pivot-like-pivot-longer-in-r | Coming from R I am remaking some exercises that helped me a lot. So Trying to recreate this R code: wide_data <- read_csv('https://raw.githubusercontent.com/rafalab/dslabs/master/inst/extdata/life-expectancy-and-fertility-two-countries-example.csv') new_tidy_data <- pivot_longer(wide_data, `1960`:`2015`, names_to = "ye... | In polars you've got pivot which makes things wider and then unpivot to make them longer. Unpivot won't split up the single columns with a delimitator into two columns for you, you've got to do that yourself. That looks like this... ( df .unpivot(index='country', value_name='fertility') .with_columns( pl.col('variable'... | 3 | 3 |
78,170,063 | 2024-3-15 | https://stackoverflow.com/questions/78170063/python-tibber-module-just-return-latest-value-not-a-loop | Ultimately I want to write a value into a database. I found a script to output desired data. However it does return it in a loop - but I only need one single value each time I trigger the script, not a loop. import tibber account = tibber.Account("tokenstring") home = account.homes[0] @home.event("live_measurement") as... | The start_live_feed function starts an infinite loop if called with default arguments. In other words, Python will not run any code after you call this function. The function takes an argument exit_condition. This is a function that is run after every time data is received. If it returns a truthy value, the loop will e... | 2 | 1 |
78,169,916 | 2024-3-15 | https://stackoverflow.com/questions/78169916/after-i-unpivot-a-polars-dataframe-how-can-i-pivot-it-back-to-its-original-form | import polars as pl df = pl.DataFrame({ 'A': range(1,4), 'B': range(1,4), 'C': range(1,4), 'D': range(1,4) }) print(df) shape: (3, 4) ┌─────┬─────┬─────┬─────┐ │ A ┆ B ┆ C ┆ D │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 ┆ i64 │ ╞═════╪═════╪═════╪═════╡ │ 1 ┆ 1 ┆ 1 ┆ 1 │ │ 2 ┆ 2 ┆ 2 ┆ 2 │ │ 3 ┆ 3 ┆ 3 ┆ 3 │ └─────┴──... | It seems I need to add an index in order to pivot df_long back into the original form of df? How would it otherwise decide that the entries in df_long with revenue=1 are all on the same row, and not for recipe=A the revenue is 2, for recipe=B, the revenue is 3, etc? You are inferring that from how you defined df, but... | 2 | 2 |
78,188,399 | 2024-3-19 | https://stackoverflow.com/questions/78188399/is-there-parallelism-inside-ollama | Below Python program is intended to translate large English texts into French. I use a for loop to feed a series of reports into Ollama. from functools import cached_property from ollama import Client class TestOllama: @cached_property def ollama_client(self) -> Client: return Client(host=f"http://127.0.0.1:11434") def... | Flags OLLAMA_NUM_PARALLEL and OLLAMA_MAX_LOADED_MODELS were added in v0.1.33. You can set them when starting the Ollama server: OLLAMA_NUM_PARALLEL=4 OLLAMA_MAX_LOADED_MODELS=4 ollama serve Available server settings OLLAMA_MAX_LOADED_MODELS - The maximum number of models that can be loaded concurrently provided they ... | 3 | 4 |
78,150,913 | 2024-3-13 | https://stackoverflow.com/questions/78150913/typeerror-locator-object-is-not-callable-using-first-in-playwright | I have a button on a webpage which looks like this: <button rpl="" aria-controls="comment-children" aria-expanded="true" aria-label="Toggle Comment Thread" class="text-neutral-content-strong bg-neutral-background overflow-visible w-md h-md button-small px-[var(--rem6)] button-plain icon items-center justify-center butt... | Try .first rather than .first(): page.locator('button[aria-label="Toggle Comment Thread"]').first.click() Runnable example: from playwright.sync_api import sync_playwright # 1.40.0 html = '<button aria-label="Toggle Comment Thread"></button>' with sync_playwright() as p: browser = p.chromium.launch() page = browser.ne... | 3 | 4 |
78,168,618 | 2024-3-15 | https://stackoverflow.com/questions/78168618/python-3-11-with-no-builtin-pip-module-whats-going-on | .venv/bin/python -m pip uninstall mysqlclient /Users/anentropic/dev/project/.venv/bin/python: No module named pip and .venv/bin/python Python 3.11.5 (main, Sep 18 2023, 15:04:25) [Clang 14.0.3 (clang-1403.0.22.14.1)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import pip Traceb... | So... pip isn't actually a "builtin" in recent Python versions What changed is it began to be bundled with Python installs by default, so it's usually available but not necessarily. For whatever reason (perhaps because my venv was created by pdm) mine did not come with it. This can be fixed by: .venv/bin/python -m ensu... | 4 | 2 |
78,190,021 | 2024-3-19 | https://stackoverflow.com/questions/78190021/intersecting-geometrycollection-with-polygon | I am using Shapely to intersect geographical data and Pyshp to write the results to a shapefile. I don't completely understand how "intersection" works. First, I create some points and calculate the Voronoi polygons this way: # (1) from shapely import LineString, MultiPoint, Point, Polygon, MultiPolygon from shapely.ge... | When doing overlays with GeometryCollections the inner boundaries are (intentionally) first unioned away, so this result is to be expected (source). It should be possible to solve the performance issue of the loop by using an rtree index, as shown in the following code sample: import numpy as np import shapely from sha... | 3 | 1 |
78,162,630 | 2024-3-14 | https://stackoverflow.com/questions/78162630/storing-data-in-cells-as-a-function | I'm given a pandas dataframe (or even just a 2 dimensional array). Lets assume I have a variable a and one of the cells of the above dataframe (say the cell in place (0,0)) is a: df = pandas.DataFrame() df.at[0,0] = a How should I write the above code such that if the value of a changed then the cell at place (0,0) wi... | What you ask for is not something you would want to do (as all the comments to your question point out). The reason is that in order to achieve this with "simple" types you would need pointers (the memory address where the actual value is stored) which is an extra piece of risky complexity which vanilla Python usually ... | 3 | 1 |
78,179,759 | 2024-3-18 | https://stackoverflow.com/questions/78179759/read-accdb-database-in-python-app-running-on-docker-container-alpine | I am trying and failing to read a local .accdb file in my Python 3.11 app, which is running in an python:3.11-alpine container. My Dockerfile executes without errors: FROM python:3.11-alpine EXPOSE 5001 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 RUN apk update && apk add --no-cache gcc g++ musl-dev unixodbc-d... | As far as I can tell, mdbtools expects a 2-component connection string, with only a single semicolon. Since you end your connection string with a semicolon, it is looking for a file named /app/input_examples/caesar/MODEL_13-16_R01.ACCDB; and cannot find that file. This can be seen here in the source, it's splitting the... | 3 | 3 |
78,162,041 | 2024-3-14 | https://stackoverflow.com/questions/78162041/dropping-elements-from-lists-in-a-nested-polars-column | How do I get this behaviour: (pl.Series(['abc_remove_def', 'remove_abc_def', 'abc_def_remove']).str.split('_') .map_elements(lambda x: [y for y in x if y != 'remove']).list.join('_') ) Without using the slower map_elements? I have tried using .list.eval and pl.element() but I can't find anything that actually excludes... | list.eval, in combination with filter would work as following: # list_eval (pl .Series(['abc_remove_def', 'remove_abc_def', 'abc_def_remove']).str.split('_') .list.eval(pl.element().filter(pl.element() != 'remove')) ) That said, list.set_difference as suggested by @jqurious is the most straightforward and fastest: # l... | 2 | 2 |
78,180,128 | 2024-3-18 | https://stackoverflow.com/questions/78180128/build-palindrome-from-two-strings | I want to write a python function that does this efficiently: The function will take two strings, 'a' and 'b', and attempt to find the longest palindromic string that can be formed such that it is a concatenation of a non-empty substring of 'a' and a non-empty substring of 'b'. If there are multiple valid answers, it w... | You could take this approach: Build a trie for all substrings in b. A suffix tree would be even better, as it is more efficient. Consider all possible "centers" for potential palindromes in the string a. So these can be between two consecutive characters (when palindrome has an even size) or on a character (when pali... | 2 | 4 |
78,188,105 | 2024-3-19 | https://stackoverflow.com/questions/78188105/python-type-hints-what-should-i-use-for-a-variable-that-can-be-any-iterable | Consider the function: def mysum(x)->int: s = 0 for i in x: s += i return s The argument x can be list[int] or set[int], it can also be d.keys() where d is a dict, it can be range(10), as well as any other iterable, where the item is of type int. What is the correct type-hint for x? My python is 3.10+. | You can use typing.Iterable: from typing import Iterable def mysum(x: Iterable[int]) -> int: s = 0 for i in x: s += i return s Edit: typing.Iterable is an alias for collections.abc.Iterable, so you should use that instead, as suggested in the comments. | 3 | 8 |
78,187,120 | 2024-3-19 | https://stackoverflow.com/questions/78187120/drop-all-the-columns-after-a-particular-column | Suppose, I am reading a csv with hundreds of columns. Now, I know that after a particular column say 'XYZ' all the columns are junk. I want to keep all the columns from the beginning till column 'XYZ' and drop all the columns after column 'XYZ'. In pandas, I may do something like: df.iloc[:, :df.columns.get_loc('XYZ') ... | The slicing with [:] solution works for eager evaluation (DataFrame), but as far as I know it doesn't really work for LazyFrame. If you want to be able to use lazy evaluation, you can just use DataFrame.select(): # prepare the data df = pl.LazyFrame({ 'ABC': [1,2,3], 'DEF': [4,5,6], 'XYZ': [7,8,9], 'garbage1': [10,11,1... | 2 | 1 |
78,187,376 | 2024-3-19 | https://stackoverflow.com/questions/78187376/how-to-make-a-regex-orderless-when-validating-a-list-of-texts | My input is this dataframe (but it could be a simple list) : import pandas as pd df = pd.DataFrame({'description': ['ij edf m-nop ij abc', 'abc ij mnop yz', 'yz yz mnop aa abc', 'i j y y abc xxx mnop y z', 'yz mnop ij kl abc uvwxyz', 'aaabc ijij uuu yz mnop']}) I also have a list of keywords (between 3 and 7 items) th... | A regex can be useful, but generating all permutations is not appropriate. I would use a regex to extract words, then checking that the keywords are a subset of the extracted words with set.issubset: import re keywords = {'abc', 'ij', 'mnop', 'yz'} # this is a SET reg = re.compile(r'\b[a-z]+\b', flags=re.I) df['valid']... | 2 | 3 |
78,186,300 | 2024-3-19 | https://stackoverflow.com/questions/78186300/differrent-behavior-between-numpy-arrays-and-array-scalars | This is a follow-up on this question. When we use a numpy array with a specific type, it preserves its type following numeric operations. For example adding 1 to a uint32 array will wrap up the value to 0 if needed (when the array contained the max uint32 value) and keep the array of type uint32: import numpy a = numpy... | As mentioned in the comments: yes, this documentation is imprecise at best. I think it is referring to the behavior between scalars of the same type: import numpy a = numpy.uint32(4294967295) print(a.dtype) # uint32 a += np.uint32(1) # WILL wrap to 0 with warning print(a) # 0 print(a.dtype) # uint32 The behavior of yo... | 4 | 4 |
78,187,026 | 2024-3-19 | https://stackoverflow.com/questions/78187026/how-to-reverse-the-value-of-column-in-a-dataframe | Given a dataframe with one columm "Name" and two rows. Input: Name ABCD XYZ Output: Name DCBA ZYX I have searched online and the solution is to reverse the row/column order. Kindly suggest how can I reverse the value in a column in A DataFrame | You have to use a loop. Assuming strings, you could use apply: df['Name'] = df['Name'].apply(lambda x: x[::-1]) or a list comprehension: df['Name'] = [x[::-1] for x in df['Name']] Output: Name 0 DCBA 1 ZYX If you don't have only strings, a safer approach would be to check for the type: df['Name'] = df['Name'].apply... | 3 | 2 |
78,186,270 | 2024-3-19 | https://stackoverflow.com/questions/78186270/enums-in-pandas-dataframe-not-possible-to-do-groupby-on-a-enumn-column | I just learned about enums and thought that they would fit something I'm coding. But when I run this code, I get an error. Am I trying to do something I shouldn't be doing or is this a bug? When trying to groupby a column with enums, I get this error: TypeError: '<' not supported between instances of 'CarBrand' and 'Ca... | pd.DataFrame.groupby sorts by default. It works if you use sort=False: sum_per_brand = df.groupby('brand', sort=False).sum('price') Alternatively, you could use a datatype which supports sorting (like CategoricalDtype). | 3 | 4 |
78,182,779 | 2024-3-18 | https://stackoverflow.com/questions/78182779/fastest-way-to-count-the-number-of-occurrences-of-a-list-of-items-from-a-numpy-n | I have a histogram of an image, basically a histogram of an image is a graph that show how many times a pixel that is converted to a 0-255 value occurs in an image. With Y axis number of occurance and X axis the pixel value. And what i need is the total number of pixel value from 75-125 image= cv2.imread('grade_0.jpg'... | You can use simple boolean operators: import cv2 image = cv2.imread('grade_0.jpg') out = ((image>=75)&(image<125)).sum() # 57032 Or, as suggested by @jared: out = np.count_nonzero((image>=75)&(image<125)) Timing of the count: # sum 170 µs ± 2.81 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each) # count_non_... | 2 | 2 |
78,179,350 | 2024-3-18 | https://stackoverflow.com/questions/78179350/how-do-i-generate-ngroups-from-a-comparison-function | Suppose I have a function that compares rows in a dataframe: def comp(lhs: pandas.Series, rhs: pandas.Series) -> bool: if lhs.id == rhs.id: return True if abs(lhs.val1 - rhs.val1) < 1e-8: if abs(lhs.val2 - rhs.val2) < 1e-8: return True return False Now I have a dataframe containing id, val1 and val2 columns and I want... | You want to cluster rows that either belong to the same group, or that are close in distance. For that compute the distance with scipy.spatial.distance.pdist to identify the close points, and create a graph with networkx to identify the connected components: import networkx as nx import pandas as pd from scipy.spatial.... | 2 | 4 |
78,182,894 | 2024-3-18 | https://stackoverflow.com/questions/78182894/get-the-name-of-the-group-inside-pandas-groupby-transform | Here is what I am trying to do. I have the following DataFrame in pandas: import numpy as np import pandas as pd n_cols = 3 n_samples = 4 df = pd.DataFrame(np.arange(n_samples * n_cols).reshape(n_samples, n_cols), columns=list('ABC')) print(df) output: A B C 0 0 1 2 1 3 4 5 2 6 7 8 3 9 10 11 I have a category to whi... | No need for grouby, just reindex df_ref and convert to array: df -= df_ref.reindex(cat).values Or, for a copy: out = df.sub(df_ref.reindex(cat).values) Note that your approach would work with groupby.apply: out = df.groupby(cat, group_keys=False).apply(lambda x: x - df_ref.loc[x.name]) Output: A B C 0 -10.0 -9.0 -8... | 2 | 1 |
78,166,162 | 2024-3-15 | https://stackoverflow.com/questions/78166162/how-to-keep-the-date-in-airflow-execution-date-and-convert-time-to-0000 | I'm using time_marker = {{execution_date.in_timezone('Europe/Amsterdam')}} in my dag.py program. I'm trying to keep the date part in execution date, and set the time to "T00:00:00" So whenever during the execution date it runs, the time_marker will always be for example 20240115T00:00:00 How should I do this? I tried t... | Add a custom macro to the DAG definition Function: def format_execution_date(execution_date): amsterdam_time = execution_date.in_timezone('Europe/Amsterdam') midnight_amsterdam_time = amsterdam_time.start_of('day') return midnight_amsterdam_time.format('YYYYMMDDT00:00:00') Use function: with DAG( ... user_defined_macr... | 4 | 1 |
78,180,325 | 2024-3-18 | https://stackoverflow.com/questions/78180325/can-you-use-a-functions-return-type-as-a-type-elsewhere | I have a callback that takes the result of another function as input. Is there a way to directly reference that function's return type? Currently I have the return type defined as a type alias that I can use in both places but that doesn't seem ideal. Does something like C++'s std::result_of exist in python? Current Co... | No, because call_back only knows/cares about the value, not which function produces the value. call_back takes a value, and it's the caller's responsibility to provide a value of the correct type, whether or not they use a function to produce that value. Focus on the type, not the functions that produce or accept value... | 3 | 5 |
78,178,154 | 2024-3-18 | https://stackoverflow.com/questions/78178154/add-subtotal-column-by-condition | could you please advice how to add Quater column, contains sum of months values part 2024-03-01 00:00:00 2024-04-01 00:00:00 2024-05-01 00:00:00 2024-06-01 00:00:00 2024-07-01 00:00:00 2024-08-01 00:00:00 2024-09-01 00:00:00 part1 6 8 2 3 0 5 5 part2 7 1 3 8 9 4 10 part3 10 7 4 5 6 10 0 part4 6 9 3 0 10 9 ... | You can convert columns to quarter periods by DatetimeIndex.to_period for subtotals, join to original by concat and for correct order add DataFrame.sort_index: df.columns = pd.to_datetime(df.columns) out = (pd.concat([df, df.groupby(df.columns.to_period('Q'), axis=1).sum()], axis=1) .sort_index(axis=1, key=lambda x: pd... | 2 | 3 |
78,177,751 | 2024-3-18 | https://stackoverflow.com/questions/78177751/is-there-any-way-to-have-re-sub-report-out-on-every-replacement-it-makes | TL;DR: How to get re.sub to print out what substitutions it makes, including when using groups? Kind of like having a verbose option, is it possible to have re.sub print out a message every time it makes a replacement? This would be very helpful for testing how multiple lines of re.sub is interacting with large texts. ... | Use matchobj.expand(replacement) which will process the replacement string and make the substitutions: import re def replacer2(text, verbose=False): def repl(matchobj, replacement): result = matchobj.expand(replacement) if verbose: print(f"Replacing {matchobj.group()} with {result}...") return result text = re.sub(r"([... | 2 | 3 |
78,175,724 | 2024-3-17 | https://stackoverflow.com/questions/78175724/chromadb-how-to-check-if-collection-exists | I want to create a script that recreates a chromadb collection - delete previous version and creates a new from scratch. client.delete_collection(name=COLLECTION_NAME) collection = client.create_collection( name=COLLECTION_NAME, embedding_function=embedding_func, metadata={"hnsw:space": "cosine"}, ) However, if the co... | You can use the following function collection = client.get_or_create_collection(name="test") It either gets the collection or creates it | 3 | 3 |
78,176,587 | 2024-3-17 | https://stackoverflow.com/questions/78176587/pythons-file-truncate-unexpectedly-does-not-truncate | I have this very simple Python program: def print_file(filename): with open(filename,'r') as read_file: print(read_file.read()) def create_random_file(filename,count): with open(filename,'w+', encoding='utf-8') as writefile: for row_num in range(count): writefile.write(f'{row_num}: fo bar baz\n') def truncate_file_afte... | From the fopen documentation: Reads and writes may be intermixed on read/write streams in any order. Note that ANSI C requires that a file positioning function intervene between output and input, unless an input operation encounters end-of-file. (If this condition is not met, then a read is allowed to return the resul... | 3 | 3 |
78,176,717 | 2024-3-17 | https://stackoverflow.com/questions/78176717/how-to-bind-functions-returning-references-with-pybind11 | When binding C++ with pybind11, I ran into an issue regarding a couple of class members that return (const or non-const) references; considering the following snippet: struct Data { double value1; double value2; }; class Element { public: Element() = default; Element(Data values) : data(values) { } Element(const Elemen... | C++ deduces the return type of your lambda to be Element not Element& thus making a copy so explicitly define the return type, and make sure you also take items by reference to avoid copying. py::class_< Container > (module, "Container") .def(py::init< >(), "Constructs a new instance") .def("__getitem__", [](Container... | 3 | 3 |
78,176,126 | 2024-3-17 | https://stackoverflow.com/questions/78176126/why-is-fast-lookup-possible-for-dict-items | Suppose we have a dictionary d defined as follows d = {i:i for i in range(1,1000001)} And then we store d.items() in x. So, x is a collection of tuples that contain key-value pairs for each element of d. I made a list with the same tuples, defined as follows : l = [(i, i) for i in range(1,1000001)] Now, I compared th... | Since dict is one of the most important core objects, it's implemented in C, as well as dict_values, dict_keys and dict_items. Here's the CPython implementation of dictitems_contains: static int dictitems_contains(PyObject *self, PyObject *obj) { _PyDictViewObject *dv = (_PyDictViewObject *)self; int result; PyObject *... | 3 | 3 |
78,176,271 | 2024-3-17 | https://stackoverflow.com/questions/78176271/how-does-pandas-concat-work-when-the-input-is-a-dictionary | I am struggling to understand how pd.concat works when the input is a dictionary. Let's say we have the following pandas dataframe - # Import pandas library import pandas as pd # initialize list of lists data = [['tom', 10], ['nick', 15], ['juli', 14]] # Create the pandas DataFrame df = pd.DataFrame(data, columns=['Nam... | It actually makes sense, since you concatenate as columns (axis=1) you need to differentiate the concatenated columns. Here is a more meaningful example: out = pd.concat({'left': df.add_prefix('left_'), 'middle': df.add_prefix('middle_'), 'right': df.add_prefix('right_')}, axis=1) left middle right left_Name left_Age m... | 3 | 5 |
78,174,010 | 2024-3-17 | https://stackoverflow.com/questions/78174010/what-is-the-most-efficient-method-to-get-the-last-modification-time-of-every-fil | I want to programmatically list the name and last modification time of every file in a certain revision. Running git log for every file, as suggested here is very slow. Is there a faster way to accomplish this? Running the script below on a non-trivial repo (SDL) takes 59s on my machine. #!/usr/bin/env python import da... | The basic idea is to postprocess git log --name-status with whatever per-commit info you want and look for the first occurrence of names you're interested in. The all-of-them version: git log --name-status --pretty=%ci | awk -F$'\t' ' NF==1 { stamp=$0; next } !seen[$2]++ { print stamp,$0 } ' | sort -t$'\t' -k2,2 and ... | 2 | 6 |
78,172,031 | 2024-3-16 | https://stackoverflow.com/questions/78172031/how-to-obtain-an-exception-with-a-traceback-attribute-that-contains-the-st | It seems that in Python (3.10) an exception that is raised inside a try contains a traceback that does not extend to the calling location of the try. This is somewhat surprising to me, and more importantly, not what I want. Here's a short program that illustrates the problem: # short_tb.py import traceback def caller()... | A more correct handling is already suggested by @Mark Tolonen, but if it's really necessary for __traceback__ to contain a full stack: Use tb_frame.f_back to access the previous frames. Reconstruct traceback objects using types.TracebackType. Link them with tb_next constructor argument. import traceback import types ... | 3 | 1 |
78,170,750 | 2024-3-16 | https://stackoverflow.com/questions/78170750/python-tensorflow-keras-error-when-load-a-json-model-could-not-locate-class-se | I've built and trained my model weeks ago and saved it on model.json dan model.h5 Today, when I tried to load it using model_from_json, it gives me an error TypeError: Could not locate class 'Sequential'. Make sure custom classes are decorated with `@keras.saving.register_keras_serializable()`. Full object config: {'cl... | After checking the version because of @kartoos comments. Yes, my kaggle's notebook use tensorflow version 2.13.1 meanwhile I'm trying to load the model to 2.16.1 Tensorflow version. I tried to install 2.13.1 but i can't find a way, so I'm build and re-train my model using 2.16.1 version tensorflow, and it works, no mor... | 3 | 4 |
78,170,965 | 2024-3-16 | https://stackoverflow.com/questions/78170965/why-does-renamecolumns-b-b-copy-false-followed-by-inplace-method-no | Here's my example: In [1]: import pandas as pd In [2]: df = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6]}) In [3]: df1 = df.rename(columns={'b': 'b'}, copy=False) In [4]: df1.isetitem(1, [7,8,9]) In [5]: df Out[5]: a b 0 1 4 1 2 5 2 3 6 In [6]: df1 Out[6]: a b 0 1 7 1 2 8 2 3 9 If df1 was derived from df with copy=False, ... | copy=False means that the underlying data (numpy) is shared. If we modify one item of the underlying numpy array, it is reflected since the data is shared: df = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6]}) df1 = df.rename(columns={'b': 'c'}, copy=False) df1.values[0, 1] = 999 print(df) a b 0 1 999 1 2 5 2 3 6 print(df1) ... | 3 | 1 |
78,170,789 | 2024-3-16 | https://stackoverflow.com/questions/78170789/polars-replacing-values-greater-than-the-max-of-another-polars-dataframe-within | I have 2 DataFrames: import polars as pl df1 = pl.DataFrame( { "group": ["A", "A", "A", "B", "B", "B"], "index": [1, 3, 5, 1, 3, 8], } ) df2 = pl.DataFrame( { "group": ["A", "A", "A", "B", "B", "B"], "index": [3, 4, 7, 2, 7, 10], } ) I want to cap the index in df2 using the largest index of each group in df1. The grou... | You can compute the max per group over df1, then clip df2: out = df2.with_columns( pl.col('index').clip( upper_bound=df1.select(pl.col('index').max().over('group'))['index'] ) ) Output: shape: (6, 2) ┌───────┬───────┐ │ group ┆ index │ │ --- ┆ --- │ │ str ┆ i64 │ ╞═══════╪═══════╡ │ A ┆ 3 │ │ A ┆ 4 │ │ A ┆ 5 │ │ B ┆ 2... | 6 | 3 |
78,169,670 | 2024-3-15 | https://stackoverflow.com/questions/78169670/how-python-imports-an-instance-of-a-class | I'm trying to find out how exactly importing works in Python. Let's say I have a foo.py module that contains the following class: class Foo: def __init__(self, *args, **kwargs): ... foo = Foo() Now, I want to import it in other modules. Is it going to use the same instance every time that I import it or will make diff... | Import it in the usual way: from foo import Foo If this is the first time, the foo.py code will execute and the {class, def} statements will generate bytecode for the interpreter. And we make a note of it in sys.modules. Subsequent imports will benefit from a cache hit, so we won’t repeat all that evaluation work. When... | 3 | 2 |
78,166,405 | 2024-3-15 | https://stackoverflow.com/questions/78166405/reproducing-the-phase-spectrum-while-using-np-fft-fft2-and-cv2-dft-why-are-the | Another question was asking about the correct way of getting magnitude and phase spectra while using cv2.dft. My answer was limited to the numpy approach and then I thought that using OpenCV for this would be even nicer. I am currently trying to reproduce the same results but I am seeing significant differences in the ... | Given that imFFTOpenCV is a 3D array because OpenCV doesn’t understand complex numbers, np.fft.fftshift(imFFTOpenCV) will swap the real and complex planes. That is, the shift happens in all 3 dimensions of the array. So when computing the phase and magnitude, you need to take this swap into account: magSpectrumOpenCV, ... | 3 | 4 |
78,157,548 | 2024-3-14 | https://stackoverflow.com/questions/78157548/calculate-exponential-complex-sum-with-fft-instead-of-summation-to-simulate-diff | Context I am trying to understand x-ray diffraction a little better by coding it up in python. For a collection of points with positions R_i, the Debye formula goes where the i in the exponential is for the complex number, all other i's are for indices and for now b_i = b_j = 1, for simplicity., Now I tried explicitly... | This answer provides a solution to make the code more efficient so it fully uses the computing power of your CPU and so to make it significantly faster. More than 90% of the time is spent in np.exp because computing the experiential of complex numbers is very expensive. One solution to speed this up is to use multiple... | 3 | 0 |
78,168,476 | 2024-3-15 | https://stackoverflow.com/questions/78168476/how-to-get-the-index-of-the-first-row-that-meets-the-conditions-of-a-mask | This is my DataFrame: import pandas as pd df = pd.DataFrame( { 'a': [100, 1123, 123, 100, 1, 0, 1], 'b': [1000, 11123, 1123, 0, 55, 0, 1], }, index=range(100, 107) ) And this is the expected output. I want to create column c: a b c 100 100 1000 NaN 101 1123 11123 NaN 102 123 1123 NaN 103 100 0 3.0 104 1 55 NaN 105 0 ... | Code This code can be modified to search for the second and third items as well, not only first. cond1 = df['a'] > df['b'] cond2 = df.groupby(cond1).cumcount().eq(0) df.loc[cond1 & cond2, 'c'] = 'the first row' df: a b c 100 100 1000 NaN 101 1123 11123 NaN 102 123 1123 NaN 103 100 0 the first row 104 1 55 NaN 105 0 0... | 4 | 3 |
78,167,633 | 2024-3-15 | https://stackoverflow.com/questions/78167633/how-to-generate-the-section-id-based-on-certain-condition | I have pandas dataframe with this input: data = { 'sec_id': ['1', '', '1.2', '1.3', '1.3.1', '1.3.2', '2', '2.1', '2.2', '2.3', '', '2.3.2', '2.3.3', '3', '4', '4.1', '4.1.1', '4.2', '4.3', '4.4', '5', '5.1', '5.2', '5.3', '5.3.1', '5.3.2', '5.3.3', '5.3.4', '5.3.5', '5.4', '5.5', '6', '6.1', '6.1.1', '6.2', '6.3', '6... | I don't think you need to do this in Pandas. You can create a class that tracks the current section and bumps it by 1, or appends a subsection, or truncates and increments, based on the paragraph type. Here is an example: class SectionCreator: def __init__(self): self.section = [0] def __call__(self, paragraph_type: st... | 3 | 2 |
78,165,778 | 2024-3-15 | https://stackoverflow.com/questions/78165778/how-to-define-an-index-in-sqlalchemyalembic-on-a-column-from-a-base-table | I am a python novice. My project is using SqlAlchemy, Alembic and MyPy. I have a pair of parent-child classes defined like this (a bunch of detail elided): class RawEmergency(InputBase, RawTables): __tablename__ = "emergency" id: Mapped[UNIQUEIDENTIFIER] = mapped_column( UNIQUEIDENTIFIER(), primary_key=True, autoincrem... | You can use sqlalchemy.orm.declared_attr for this. You can add any number of index you want under __table_args__ from sqlalchemy import create_engine, Index from sqlalchemy.orm import Mapped, mapped_column, DeclarativeBase, declared_attr class InputBase(DeclarativeBase): refresh_date: Mapped[str] refresh_time: Mapped[s... | 2 | 3 |
78,165,559 | 2024-3-15 | https://stackoverflow.com/questions/78165559/how-to-write-a-polars-dataframe-to-duckdb | I am trying to write a Polars DataFrame to a duckdb database. I have the following simple code which I expected to work: import polars as pl import duckdb pldf = pl.DataFrame({'mynum': [1,2,3,4]}) with duckdb.connect(database="scratch.db", read_only=False) as con: pldf.write_database(table_name='test_table', connection... | In-memory database. If you just want to use DuckDB to query a polars dataframe, this can simply be achieved as long as the table exists in the current scope. duckdb.sql("SELECT * FROM df").show() Persistent database If you want to use a persistent database, you could install duckdb-engine and write the database using ... | 5 | 4 |
78,166,924 | 2024-3-15 | https://stackoverflow.com/questions/78166924/how-to-improve-efficiency-in-random-column-selection-and-assignment-in-pandas-da | I'm working on a project where I need to create a new DataFrame based on an existing one, with certain columns randomly selected and assigned in each row with probability proportional to the number in that column. However, my current implementation seems to be inefficient, especially when dealing with large datasets. I... | You could first rework your DataFrame to select the columns of interest, normalize the weights, then create a cumsum. tmp = (df[relevant_col_list] .pipe(lambda x: x.div(x.sum(axis=1), axis=0)) .cumsum(axis=1).to_numpy() ) # cumulated probabilities array([[0.06666667, 0.4 , 1. ], [0.11111111, 0.44444444, 1. ], [0.142857... | 3 | 3 |
78,165,746 | 2024-3-15 | https://stackoverflow.com/questions/78165746/python-import-directory-from-a-file-inside-that-directory | I'm sorry if the title is confusing since English is not my first language. What I have trouble is running a python script that calls import of its own directory. The folder structure is like this: MyProject |--Utils |-- util | |-- __init__.py | |-- run.py |-- __init__.py |-- test.py And the code of test.py is as foll... | The error "ModuleNotFoundError: No module named 'Utils'" occurs because Python doesn't automatically search for modules within subdirectories unless they are treated as packages. from .util import | 2 | 1 |
78,164,251 | 2024-3-15 | https://stackoverflow.com/questions/78164251/dividing-each-column-in-polars-dataframe-by-column-specific-scalar-from-another | Polars noob, given an m x n Polars dataframe df and a 1 x n Polars dataframe of scalars, I want to divide each column in df by the corresponding scalar in the other frame. import numpy as np import polars as pl cols = list('abc') df = pl.DataFrame(np.linspace(1, 9, 9).reshape(3, 3), schema=cols) scalars = pl.DataFrame(... | I think you found out a very unique/interesting and clever solution. Consider also just iterating over columns: df.select(column / scalars[column.name] for column in df.iter_columns()) or df.select(pl.col(k) / scalars[k] for k in df.columns) or df.with_columns(pl.col(k).truediv(scalars[k]) for k in df.columns) | 5 | 4 |
78,163,868 | 2024-3-14 | https://stackoverflow.com/questions/78163868/polars-expressions-failed-to-access-intermediate-column-creation-expressions | I want to encode the non-zero binary events with integer numbers. Following is a demo table: import polars as pl df = pl.DataFrame( { "event": [0, 1, 1, 0], "foo": [1, 2, 3, 4], "boo": [2, 3, 4, 5], } ) The expected output is achieved by: df = df.with_row_index() events = df.select(pl.col(["index", "event"])).filter(p... | While the solution using the walrus operator works. It is probably more idiomatic and cleaner to use a pl.when().then() construct in conjunction with pl.int_range() to create the event_id. ( df .with_columns( pl.when(pl.col("event") == 1) .then(pl.int_range(pl.len())) .over("event") .alias("event_id") ) ) shape: (4, 4... | 3 | 2 |
78,163,954 | 2024-3-14 | https://stackoverflow.com/questions/78163954/how-could-i-get-a-value-out-of-a-pandas-dataframe-with-a-shape-of-1-1-without | I want to get a single value from a pandas DataFrame more efficiently. This is how I do it now: # import pandas import pandas as pd # set up the dataframe df = pd.DataFrame({'col1':['a','a','b'],'col2':[10,20,20],'col3':[100.0,200.0,300.0]}) # STEP 1 - filter down to a single row with loc row_of_interest = df.loc[(df['... | You can do: print(column_and_row_of_interest.squeeze()) OR: print(column_and_row_of_interest.iat[0]) This prints: 200.0 | 2 | 3 |
78,162,874 | 2024-3-14 | https://stackoverflow.com/questions/78162874/losing-type-information-inside-polars-dataframe | Sorry if my question doesn't make a lot of sense. I don't have much experience in python. I have some code that looks like: import polars as pl from typing import NamedTuple class Event(NamedTuple): name: str description: str def event_table(num) -> list[Event]: events = [] for i in range(5): events.append(Event("name"... | You can keep the Event objects by passing return_dtype=pl.Object df.select(pl.col("events").map_elements(event_table)) shape: (5, 1) ┌───────────────────────────────────┐ │ events │ │ --- │ │ list[struct[2]] │ ╞═══════════════════════════════════╡ │ [{"name","description"}, {"name"… │ │ [{"name","description"}, {"name... | 2 | 2 |
78,161,984 | 2024-3-14 | https://stackoverflow.com/questions/78161984/typing-for-rare-case-fallback-none-value | Trying to avoid typing issues I often run into the same problem. E.g. I have a function x that very rarily returns value None, all other times it returns int. def x(i: int) -> Union[int, None]: if i == 0: return return i def test(i: int): a = x(i) # typing issue: *= not supported for types int | None and int a *= 25 ... | This might be a case where an exception is better than a return statement you never expect to be reached. def x(i: int) -> int: if i == 0: raise ValueError("didn't expect i==0") return i def test(i: int): try: a = x(i) except ValueError: pass a *= 25 Code that is confident it has sufficiently validated the argument to... | 2 | 6 |
78,161,053 | 2024-3-14 | https://stackoverflow.com/questions/78161053/convert-entire-python-file-from-2-space-indent-to-4-space-indent | I regularly work with Python files that are provided to me as templates, which use an indentation of 2. However, I personally prefer working with an indentation width of 4, which is what I've set in my .vimrc. However, because of the indentation-sensitivity of Python, the typical gg=G way to fix indentation to my prefe... | In vim: " Convert 2-spaces indent to tabs :set noexpandtab tabstop=2 :retab! " Convert tabs to 4-spaces indent :set expandtab tabstop=4 :retab | 3 | 4 |
78,159,660 | 2024-3-14 | https://stackoverflow.com/questions/78159660/whats-the-difference-between-np-dividex-y-and-x-y-in-python3 | I recently found a bug in my code that I was able to fix by replacing np.divide(x, y) with x / y. I was under the impression that np.divide(x, y) was equivalent to x / y (it says as much in the numpy documentation). Is this a bug in numpy or is it expected behaviour? As I said my immediate issue is solved so I'm not to... | The parameter where = mask without the parameter out is somewhat dangerous. Without a target for the output, the function builds an np.empty array of the appropriate shape, and then replaces some subset of the empty array with the output data. But np.empty isn't, well, empty. It's just a random memory location that has... | 2 | 6 |
78,159,962 | 2024-3-14 | https://stackoverflow.com/questions/78159962/in-pandas-how-to-reliably-set-the-index-order-of-multilevel-columns-during-or-a | After pivoting around two columns with a separate value column, I want a df with multiindex columns in a specific order, like so (please ignore that multi-2 and multi-3 labels are pointless in the simplified example): multi-1 one two multi-2 multi-2 multi-2 multi-3 SomeText SomeText mIndex bar -1.788089 -0.631030 baz -... | After pivot, the values don't have an index name, you have to assign it: (df.pivot(columns={'multi-1', 'multi-3'}, values=['multi-2']) .rename_axis(columns={None: 'multi-2'}) .reorder_levels(['multi-1', 'multi-2', 'multi-3'], axis=1) ) Output: multi-1 one two multi-2 multi-2 multi-2 multi-3 SomeText SomeText mIndex ba... | 2 | 5 |
78,155,443 | 2024-3-13 | https://stackoverflow.com/questions/78155443/using-a-column-values-within-the-round-function | I have this dataframe: df = pl.from_repr(""" ┌───────────────┬──────────────┬────────────────────────┐ │ exchange_rate ┆ sig_figs_len ┆ reverse_rate_from_euro │ │ --- ┆ --- ┆ --- │ │ f64 ┆ u32 ┆ f64 │ ╞═══════════════╪══════════════╪════════════════════════╡ │ 6.4881 ┆ 5 ┆ 0.154128 │ │ 6.5196 ┆ 5 ┆ 0.153384 │ │ 6.4527 ... | You could probably do something like this: df.with_columns( ( pl.col('reverse_rate_from_euro') * pl.lit(10).pow(pl.col('sig_figs_len')) ).round() * pl.lit(0.1).pow(pl.col('sig_figs_len')) ) ┌───────────────┬──────────────┬────────────────────────┐ │ exchange_rate ┆ sig_figs_len ┆ reverse_rate_from_euro │ │ --- ┆ --- ┆ ... | 2 | 3 |
78,156,640 | 2024-3-13 | https://stackoverflow.com/questions/78156640/why-is-visual-studio-code-saying-my-code-in-unreachable-after-using-the-pandas-c | Koda Ulaşılamıyor -> Code is unreachable Visual Studio code is graying out my code and saying it is unreachable after I used pd.concat(). The IDE seems to run smoothly but it's disturbing and I want my colorful editor back. How do I disable the editor graying out my code without changing the current language? | This is a bug currently existing in pandas-stubs. The matching overload of concat in pandas-stubs currently returns Never. According to this suggestion in Pylance github, you could work around the pandas-stubs issue by commenting out the Never overload in ...\.vscode\extensions\ms-python.vscode-pylance-2024.3.1\dist\bu... | 16 | 17 |
78,156,811 | 2024-3-13 | https://stackoverflow.com/questions/78156811/how-do-i-isort-using-ruff | I often work in very small projects which do not have config file. How do I use ruff in place of isort to sort the imports? I know that the following command is roughly equivalent to black: ruff format . The format command do not sort the imports. How do I do that? | According to the documentation: Currently, the Ruff formatter does not sort imports. In order to both sort imports and format, call the Ruff linter and then the formatter: ruff check --select I --fix . ruff format . | 18 | 36 |
78,156,692 | 2024-3-13 | https://stackoverflow.com/questions/78156692/pandas-move-values-from-one-column-to-an-appropriate-column | My google-fu is failing me. I have a simple dataframe that looks like this: Sample Subject Person Place Thing 1-1 Janet 1-1 Boston 1-1 Hat 1-2 Chris 1-2 Austin 1-2 Scarf I want the values in the subject column to move into their appropriate column so that I end up with something li... | If the groups are sorted and the pattern is always the same (no missing values), then reshape with numpy: cols = ['Person', 'Place', 'Thing'] out = df.loc[::len(cols), ['Sample']].reset_index(drop=True) out[cols] = df['Subject'].to_numpy().reshape(-1, len(cols)) For a more generic approach, only assuming that the cate... | 2 | 1 |
78,155,230 | 2024-3-13 | https://stackoverflow.com/questions/78155230/polars-timestamp-synchronization-lazy-evaluation | I want to synchronize two numpy arrays of timestamps to each other using Polars LazyFrames. Let's assume that I have two numpy arrays of timestamps which are stored using LazyFrames: import polars as pl timestamps = pl.LazyFrame( np.array( [ np.datetime64("1970-01-01T00:00:00.500000000"), np.datetime64("1970-01-01T00:0... | It seems that your join_as_of example works. The only thing is that, as far as I understand, join_as_of is a left join, so you have to additionally filter out non joined values by is_not_null() (or even better, drop_nulls() as @Hericks suggested in the comment): timestamps.sort("values").join_asof( other_timestamps.wit... | 3 | 1 |
78,154,266 | 2024-3-13 | https://stackoverflow.com/questions/78154266/fill-bins-with-no-coverage-with-0 | I need to generate a heatmap with the average coverage of positions within a bin from a determined number of bins, regardless of the number of bases in a transcriptome within each bin. In other words, if I want to have 10 bins, for one transcriptome, it may have 1000 bases to distribute among 10 bins, and another may h... | IIUC you can use .merge to merge the missing categories, then fill any NaNs with values you want: df["data_bin"] = pd.cut(df["pos"], range(0, 12, 2)) df = pd.merge( df, df["data_bin"].cat.categories.to_frame(), left_on="data_bin", right_on=0, how="outer", )[["chr", "data_bin", "cov"]] df["chr"] = df["chr"].ffill().bfil... | 4 | 1 |
78,153,897 | 2024-3-13 | https://stackoverflow.com/questions/78153897/row-count-expression-in-polars | Is there something like row_number, or a row_count expression in Polars? Something like the Polars with_row_index as an expression, but not just as a data frame method. I want to rank a given customer's order number in a day using the over window function, but can't come up with a solution so far. pl.count().over('ID C... | You might be searching for pl.int_range, potentially combined with pl.Expr.over. import polars as pl df = pl.DataFrame({ "group": ["A", "A", "A", "B", "B", "C"], }) df.with_columns(pl.int_range(pl.len()).over("group").alias("index")) shape: (6, 2) ┌───────┬───────┐ │ group ┆ index │ │ --- ┆ --- │ │ str ┆ i64 │ ╞══════... | 3 | 4 |
78,153,672 | 2024-3-13 | https://stackoverflow.com/questions/78153672/decoding-of-a-byte-sequence-into-a-unicode-string | I am attempting to decode a byte sequence into a Unicode string from various types of files, such as .exe, .dll, and .deb files, using the pefile library in Python. However, I sometimes encounter Unicode decoding errors. How can I handle these errors effectively? Here's the relevant code snippet: import pefile def get_... | I've implemented error handling using nested try-except blocks try: pe = pefile.PE(file_path) for section in pe.sections: try: name = section.Name.decode().strip('\x00') except UnicodeDecodeError: name = "Undecodable" section_addresses[name] = section.VirtualAddress except pefile.PEFormatError: print(f"Error: {file_pa... | 4 | 3 |
78,151,027 | 2024-3-13 | https://stackoverflow.com/questions/78151027/polars-customized-function-returns-multiple-columns | _func is designed to return two columns: from polars.type_aliases import IntoExpr, IntoExprColumn import polars as pl def _func(x: IntoExpr): x1 = x+1 x2 = x+2 return pl.struct([x1, x2]) df = pl.DataFrame({"test": np.arange(1, 11)}) df.with_columns( _func(pl.col("test")).alias(["test1", "test2"]) ) I have tried to wra... | I'm assuming that you cannot or don't want to change the function, so we need to work with sequence of expressions returned by this function. Also I want the answer to be able to accommodate for more than 2 columns, so I don't have to specifically alias each column. The problem in your case is at the end you have a seq... | 3 | 2 |
78,135,862 | 2024-3-10 | https://stackoverflow.com/questions/78135862/convert-undelimited-bytes-to-pandas-dataframe | I am sorry if this is a duplicate, but I didn't find a suitable answer for this problem. If have a bytes object in python, like this: b'\n\x00\x00\x00\x01\x00\x00\x00TEST\xa2~\x08A\x83\x11\xe3@\x05\x00\x00\x00\x03\x00\x00\x00TEST\x91\x9b\xd1?\x1c\xaa,@' It contains first a certain number of integer (4bytes) then a str... | This works fine for me: import numpy as np import pandas as pd data = b'\n\x00\x00\x00\x01\x00\x00\x00TEST\xa2~\x08A\x83\x11\xe3@\x05\x00\x00\x00\x03\x00\x00\x00TEST\x91\x9b\xd1?\x1c\xaa,@' dtype = np.dtype([ ('int1', np.int32), ('int2', np.int32), ('string', 'S4'), ('float1', np.float32), ('float2', np.float32), ]) st... | 2 | 2 |
78,122,985 | 2024-3-7 | https://stackoverflow.com/questions/78122985/test-for-object-callability-in-match-case-construct | For context, I have a function that matches keys in a dictionary to perform certain action; to match item keys, the function accepts either a sequence of keys to match, or a function that recognizes those keys. I'm wondering if I can use the match-case pattern for it. I try something like: def process_fields(dataset,fu... | If you want to test if an object is Callable then: from collections.abc import Callable def func(): pass f = func match f: case Callable(): print("Yes it's callable") | 5 | 3 |
78,111,501 | 2024-3-6 | https://stackoverflow.com/questions/78111501/generate-csv-export-downloadable-odoo | i have a problem to generate downloadable export to csv file, does anyone know the problem? this is my transient model class ReportPatientWizard(models.TransientModel): _name = "report.patient.wizard" _description = "Patient Reports" patient_id = fields.Many2one('hospital.patient', string='Patient', readonly=True) gen... | You specified a field in the route and you don't have a field named file. You need to add a binary field and set its content just after the file name Example: # Prepare file name filename = f'patient_report_{fields.Date.today()}.csv' self.file = base64.b64encode(csv_data.encode('utf-8')) You can add self.ensure_one() ... | 2 | 2 |
78,129,981 | 2024-3-8 | https://stackoverflow.com/questions/78129981/logging-error-failed-to-initialize-logging-system-log-messages-may-be-missing | Logging Error: Failed to initialize logging system. Log messages may be missing. If this issue persists, try setting IDEPreferLogStreaming=YES in the active scheme actions environment variables. Has anyone else encountered this message? Where is IDEPreferLogStreaming located? I don't know what any of this means. It's... | To find IDEPreferLogStreaming, you need to go to Product -> Scheme -> Edit Scheme and then add it as a new Environment Variable yourself. IDEPreferLogStreaming=YES For me it didnt solve the issue though --- [Edit: it works for me now as well. Probably I was to quick saying it doesnt. Thanks for your feedback.] | 83 | 122 |
78,144,551 | 2024-3-12 | https://stackoverflow.com/questions/78144551/current-timestamp-in-azure-databricks-notebook-in-est | I need the current timestamp in EST but the current_timestamp() is returning PST. Tried the following code but it's not working and showing 6 hours before EST time: # Import the current_timestamp function from pyspark.sql.functions import from_utc_timestamp # Set the timezone to EST spark.conf.set("spark.sql.session.ti... | To get rid of the -04:00 you can just use .strftime() in your second approach: from datetime import datetime from pytz import timezone est = timezone('US/Eastern') now_est = datetime.now(est).strftime('%Y-%m-%d %H:%M:%S') print(now_est) Output: 2024-04-04 09:42:58 Now, for the first approach instead of setting EST as ... | 3 | 0 |
78,117,544 | 2024-3-6 | https://stackoverflow.com/questions/78117544/celery-worker-creates-control-folder-when-using-filesystem-as-a-broker | I have a project using Celery with Redis backend to manage tasks. For local development I am trying to set up Celery with filesystem as broker instead of Redis. However, when I run Celery worker, it creates me control folder in the root directory with the following contents: /control ├── celery.pidbox.exchange ├── Q1.e... | Setting a control_folder field did the trick for me: CELERY_BROKER_TRANSPORT_OPTIONS = { "data_folder_in": os.path.join(BASE_DIR, ".celery"), "data_folder_out": os.path.join(BASE_DIR, ".celery"), "control_folder": os.path.join(BASE_DIR, ".celery"), } So for you, I suppose, it would be: broker_transport_options = { "da... | 4 | 2 |
78,122,802 | 2024-3-7 | https://stackoverflow.com/questions/78122802/why-is-my-scipy-optimize-minimizemethod-newton-cg-function-stuck-on-a-local | I want to find the local minimum for a function that depends on 2 variables. For that my plan was to use the scipy.optimize.minimize function with the "newton-cg" method because I can calculate the jacobian and hessian analytically. However, when my starting guesses are on a local maximum, the function terminates succe... | The solution is stuck at a local maximum because you are using a gradient-based solver with a guess at a point where the gradient is exactly zero. The guess satisfies the condition for successful termination, so the solver stops. A simple solution is to perturb the guess: min = o.minimize(get_f_df, (1e-6, 1e-6), jac=Tr... | 4 | 3 |
78,128,173 | 2024-3-8 | https://stackoverflow.com/questions/78128173/displaying-geojson-data-sent-by-flask-server-in-folium-map | I am currently working on a teaching tool for aviation and I need to display realtime data in a 1s interval in a GUI on a map. I decided to use PySide6 and folium for this. The realtime data is simple position data consisting of latitude and longitude. To my understanding it is not possible to insert changing values fr... | I could resolve the issue by adding a header, which is needed by the fetch function: with open('random_position.geojson', 'w') as f: json.dump(feature_collection, f) response = make_response(send_file('random_position.geojson', mimetype='application/json')) response.headers.add('Access-Control-Allow-Origin', '*') retur... | 2 | 2 |
78,132,353 | 2024-3-9 | https://stackoverflow.com/questions/78132353/pytest-how-to-remove-created-data-after-each-test-function | I have a FastAPI + SQLAlchemy project and I'm using Pytest for writing unit tests for the APIs. In each test function, I create some data in some tables (user table, post table, comment table, etc) using SQLAlchemy. These created data in each test function will remain in the tables after test function finished and will... | The problem is that there are multiple sessions. One is used by your tests. The other one(s) is/are used by the server. Because you are using client.get, you are sending a request to the server, which will use its own database session. To solve your problem you can just truncate all tables at the end of each test: htt... | 5 | 9 |
78,136,859 | 2024-3-10 | https://stackoverflow.com/questions/78136859/find-the-optimal-clipped-circle | Given a NxN integer lattice, I want to find the clipped circle which maximizes the sum of its interior lattice point values. Each lattice point (i,j) has a value V(i,j) and are stored in the following matrix V: [[ 1, 1, -3, 0, 0, 3, -1, 3, -3, 2], [-2, -1, 0, 1, 0, -2, 0, 0, 1, -3], [ 2, 2, -3, 2, -2, -1, 2, 2, -2, 0]... | Start by creating a cumulative frequency table, or a fenwick tree. You'll have a record for each radius of circle, with value corresponding to explored weights at that distance from the origin. Then, begin a BFS from the origin. For each diagonal "frontier", you'll need to update your table/tree with the radius:weight ... | 11 | 6 |
78,149,556 | 2024-3-12 | https://stackoverflow.com/questions/78149556/unknown-document-type-error-while-using-llamaindex-with-azure-openai | I'm trying to reproduce the code from documentation: https://docs.llamaindex.ai/en/stable/examples/customization/llms/AzureOpenAI.html and receive the following error after index = VectorStoreIndex.from_documents(documents): raise ValueError(f"Unknown document type: {type(document)}") ValueError: Unknown document type:... | The error occurs because of the type of document you are passing for VectorStoreIndex.from_documents(). When you import SimpleDirectoryReader from legacy modules, the type of document is llama_index.legacy.schema.Document. You are passing that to VectorStoreIndex, which is imported from core modules: from llama_index.... | 2 | 1 |
78,150,355 | 2024-3-12 | https://stackoverflow.com/questions/78150355/from-typing-vs-from-collections-abc-for-standard-primitive-type-annotation | I'm looking at the standard library documentation, and I see that from typing import Sequence is just calling collections.abc under the hood. Now originally, there was a deprecation warning/error and migration from the collections package to collections.abc for some abstract classes. See here. However, now that the abs... | However, now that the abstractions have settled in a new location, is it fine to use either? It's better not to do so. The documentation specifically says: class typing.Sequence(Reversible[T_co], Collection[T_co]) Deprecated alias to collections.abc.Sequence. Deprecated since version 3.9: collections.abc.Sequence no... | 4 | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.