eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: Requesting contract details for NQ futures... Error 200, reqId 9: No security definition has been found for the request, contract: Future(symbol='NQ', exchange='GLOBEX', currency='USD') No contract details found for NQ. Please verify your parameters in TWS/IB Gateway. #!/usr/bin/env python3 from ib_insync import IB, Future from datetime import datetime import sys def parse_expiry(expiry): """ Parse the expiry string from the contract details. IB typically provides expiry as YYYYMM or YYYYMMDD. For comparison, we convert to a datetime object. """ if len(expiry) == 6: # Assume format is YYYYMM; we'll use the 1st of the month for comparison. try: return datetime.strptime(expiry, "%Y%m") except Exception as e: print(f"Error parsing expiry {expiry}: {e}") return None elif len(expiry) == 8: try: return datetime.strptime(expiry, "%Y%m%d") except Exception as e: print(f"Error parsing expiry {expiry}: {e}") return None else: return None def main(): # Connect to IBKR Gateway on localhost using port 4002. ib = IB() print("Connecting to IBKR Gateway...") ib.connect('-----------', 4002, clientId=1) # Create a generic NQ futures contract. contract = Future() contract.symbol = "NQ" contract.secType = "FUT" contract.exchange = "GLOBEX" contract.currency = "USD" # Do not specify lastTradeDateOrContractMonth so that IB returns all available contracts. print("Requesting contract details for NQ futures...") details = ib.reqContractDetails(contract) if not details: print("No contract details found for NQ. Please verify your parameters in TWS/IB Gateway.") ib.disconnect() sys.exit(1) It would be great if you could help me with this. tried different exchanges, tried loading different contract symbols, built a test connection.py ,connects to IBKR Gateway 

Answer: GLOBEX is an old exchange code that is no longer valid. It should be CME. You can look up exchange codes on IBKR's website: https://www.interactivebrokers.com/en/trading/products-exchanges.php Or you can look it up on QuantRocket's website with fewer clicks: https://www.quantrocket.com/data/?modal=ibkrexchangesmodal
Question: So, I tried to simulate this gate on Colab using matplotlib. The histogram is showing at the end, but not the circuit. I have tried out all fixes suggested by ChatGPT such as force inline and circuit_drawer, but it did not work. Please help me with the solution. qc_h = QuantumCircuit(1, 1, name = "qc") qc_h.h(0) qc_h.measure(0, 0) qc_h.draw('mpl') simulator_h = Aer.get_backend('qasm_simulator') transpiled_circuit_h = transpile(qc_h, simulator_h) job_h = simulator_h.run(transpiled_circuit_h, shots = 1024) result_h = job_h.result() counts_h = result_h.get_counts(qc_h) plot_histogram(counts_h) 

Answer: We have to define the matplotlib axes (e.g. two matplotlib subplots) and input the axis as a kwargument for draw and plot_histogram. from qiskit import QuantumCircuit from qiskit_aer import Aer from qiskit.compiler import transpile from qiskit.visualization import plot_histogram from matplotlib import pyplot as plt fig = plt.figure(figsize=(10, 10)) ax = plt.subplot(1, 2, 1) qc_h = QuantumCircuit(1, 1, name='qc') qc_h.h(0) qc_h.measure(0, 0) qc_h.draw('mpl', ax=ax) ax = plt.subplot(1, 2, 2) simulator_h = Aer.get_backend('qasm_simulator') transpiled_circuit_h = transpile(qc_h, simulator_h) job_h = simulator_h.run(transpiled_circuit_h, shots=1024) result_h = job_h.result() counts_h = result_h.get_counts(qc_h) plot_histogram(counts_h, ax=ax) plt.show()  Outputs:  Google Colab pips: !pip install qiskit !pip install pylatexenc !pip install qiskit_aer
Question: ast.Assign.targets is a list a, b = c, d  Yields following AST: Assign( targets=[ Tuple( elts=[ Name(id='a', ctx=Store()), Name(id='b', ctx=Store())], ctx=Store())], value=Tuple( elts=[ Name(id='c', ctx=Load()), Name(id='d', ctx=Load())], ctx=Load()))  Under what conditions target would be a list with multiple elements instead of single Tuple ?

Answer: When there are multiple destinations for the assignment of the value. That is: a = b = c = d  AST: Module( body=[ Assign( targets=[ Name(id='a', ctx=Store()), Name(id='b', ctx=Store()), Name(id='c', ctx=Store())], value=Name(id='d', ctx=Load()))], type_ignores=[])
Question: What kind of polars expression (pl.Expr) might be used in a filter context that will match anything including nulls? Use case: Type hinting and helper Functions that should return an polars.Expr.

Answer: The expression representing the literal value True might be used. See pl.lit for more details. Example. import polars as pl df = pl.DataFrame({ "a": [1, 2, None] }) df.filter(pl.lit(True))  shape: (3, 1) ┌──────┐ │ a │ │ --- │ │ i64 │ ╞══════╡ │ 1 │ │ 2 │ │ null │ └──────┘  Note. In general, simply True also works, but its not an instance of pl.Expr.
Question: Im trying to use pandas in a dbt python model (dbt-duckdb), but I keep getting the problem Python model failed: No module named 'pandas'. Here you can find my dbt model configuration: import boto3 import pandas as pd def model(dbt, session): dbt.config( materialized="table", packages = ["pandas==2.2.3"], python_version="3.11" ) key = "my_key" bucket = "my_bucket" client = boto3.client('s3') return None  Also I know duckdb has a way of importing s3 files but I need to manipulate the files before duckdb reads them because they are not correct. Also this is my models yaml config version: 2 models: - name: test config: packages: - "pandas==2.2.3"  Also I have a virtualenvironemnt with pandas installed. Anyone who has experience with it, thanks in advance!

Answer: Found it, make sure that the venv you are using is called dbt-env dbt will automatically take this venv where you have installed pandas or whatever package you needed!
Question: I have a dataframe called "base_dataframe" that looks as following:  F_NAME L_NAME EMAIL 0 Suzy Maripol suzy@mail.com 1 Anna Smith anna@mail.com 2 Flo Mariland flo@mail.com 3 Sarah Linder sarah@mail.com 4 Nala Kross Nala@mail.com 5 Sarosh Fink sarosh@mail.com  I would like to create a new dataframe that only contains the rows matching specific regular expressions that I define:  For column "F_NAME" I only want to copy over the rows that contain "Sar" For column "L_NAME" I only want to copy over the rows that contain "Mari"  The way I tackle this in my code is : sar_df = base_dataframe["F_NAME"].str.extract(r'(?P<sar_content>(^Sar.*))') mari_df = base_dataframe["L_NAME"].str.extract(r'(?P<mar_content>(^Mari.*))')  Then I copy those filtered columns/DFs over to my target dataframe "new_dataframe": new_dataframe["selected_F_NAME"] = sar_df.copy new_dataframe["selected_L_NAME"] = mari_df.copy  And my "new_dataframe" would at the end look like this :  F_NAME L_NAME EMAIL 0 Suzy Maripol suzy@mail.com 2 Flo Mariland flo@mail.com 3 Sarah Linder sarah@mail.com 5 Sarosh Fink sarosh@mail.com  This works for me but it takes an extremely long time to copy over all the data to my "new_dataframe", because my "base_dataframe" has many hundred thousands of rows. I also need to apply multiple different regular-expressions on multiples columns ( the dataframe example I gave is basically simplified, just to explain what I want to do). I am pretty sure there is a more optimised way to do this, but can't figure it out right now. I would appreciate any help with this.

Answer: Since you goal seems to be filtering, couldn't you replace your extract logic by a simple boolean indexing?: # identify rows with F_NAME starting with "Sar" m1 = base_dataframe['F_NAME'].str.startswith('Sar') # identify rows with L_NAME starting with "Mari" m2 = base_dataframe['L_NAME'].str.startswith('Mari') # keep rows with either match out = base_dataframe[m1|m2]  Or, if you have multiple conditions: conditions = [base_dataframe['F_NAME'].str.startswith('Sar'), base_dataframe['L_NAME'].str.startswith('Mari'), # ... other conditions, ] out = base_dataframe[np.logical_xor.reduce(conditions)]  Output:  F_NAME L_NAME EMAIL 0 Suzy Maripol suzy@mail.com 2 Flo Mariland flo@mail.com 3 Sarah Linder sarah@mail.com 5 Sarosh Fink sarosh@mail.com
Question: How do I do the following dot product in 3 dimensions with numpy?  I tried: x = np.array([[[-1, 2, -4]], [[-1, 2, -4]]]) W = np.array([[[2, -4, 3], [-3, -4, 3]], [[2, -4, 3], [-3, -4, 3]]]) y = np.dot(W, x.transpose())  but received this error message:  y = np.dot(W, x) ValueError: shapes (2,2,3) and (2,1,3) not aligned: 3 (dim 2) != 1 (dim 1)  It's 2 dimensions equivalent is: x = np.array([-1, 2, -4]) W = np.array([[2, -4, 3], [-3, -4, 3]]) y = np.dot(W,x) print(f'{y=}')  which will return: y=array([-22, -17])  Also, y = np.dot(W,x.transpose()) will return the same answer.

Answer: The issue comes from the 3D transposition which does not transpose the axes you want by default. You need to specify the right axes during this call: W @ x.transpose(0, 2, 1) # Output: # array([[[-22], # [-17]], # # [[-22], # [-17]]])
Question: This very simple script gives error KeyError: "None of [Index(['A', 1], dtype='object')] are in the [index]": import pandas as pd import matplotlib.pyplot as plt L1 = ['A','A','A','A','B','B','B','B'] L2 = [1,1,2,2,1,1,2,2] V = [9.8,9.9,10,10.1,19.8,19.9,20,20.1] df = pd.DataFrame({'L1':L1,'L2':L2,'V':V}) print(df) df.groupby(['L1','L2']).boxplot(column='V') plt.show()  So my dataframe is:  L1 L2 V 0 A 1 9.8 1 A 1 9.9 2 A 2 10.0 3 A 2 10.1 4 B 1 19.8 5 B 1 19.9 6 B 2 20.0 7 B 2 20.1  and I would expect a plot with four boxplot showing the values V, the labels of boxplots should be A/1, A/2, B/1, B/2. I had a look at How To Solve KeyError: u"None of [Index([..], dtype='object')] are in the [columns]" but I was not able to fix my error, AI tools are not helping me either. What am I not understanding?

Answer: You can use boxplot for the grouping as well df.boxplot(column='V', by=['L1', 'L2'])
Question: In How to modify list entries during for loop?, the general recommendation is that it can be unsafe so don't do it unless you know it's safe. In comments under the first answer @martineau says:  It [the loop variable] doesn't make a copies. It just assigns the loop variable name to successive elements or value of the thing being iterated-upon.  That is the behavior I expect and want, but I'm not getting it. I want to remove trailing Nones from each value in the list. My loop variable is modified correctly but the list elements remain unchanged. How can I get the loop variable fv to be a pointer to the rows of list foo, not a copy of the row? Extra credit: my code is sucky non-pythonic, so a solution using comprehensions or slices instead of for loops would be preferred. foo = [ ['a', 'b', None, None], ['c', None, 'e', None], ['f', None, None, None] ] desired = [ ['a', 'b'], ['c', None, 'e'], ['f'] ] for fv in foo: for v in range(len(fv) -1, 0, -1): if fv[v] == None: fv = fv[:v] print(f' {v:2} {fv}') else: break print(foo)  The output is:  3 ['a', 'b', None] 2 ['a', 'b'] 3 ['c', None, 'e'] 3 ['f', None, None] 2 ['f', None] 1 ['f'] [['a', 'b', None, None], ['c', None, 'e', None], ['f', None, None, None]] 

Answer: The line fv = fv[:v] will create a new variable named fv instead of mutating fv. You should mutate the existing list. One solution could be using while to strip unwanted values until none left. The .pop() method will mutate row instead of returning a new list: for row in foo: while row and row[-1] is None: row.pop() assert foo == desired
Question: My understanding is that DataFrames do not support MultiIndexing, which generally does not pose much problems, but translating some pythonic habits to Julia poses difficulties. I wonder how one could load and subselect features by columns, as in the example below. import numpy as np import pandas as pd #generating sample data nsmpls = 10 smpls = [f'smpl{j}' for j in range(nsmpls)] nfeats = 5 feats = [f'feat{j}' for j in range(nfeats)] data = np.random.rand(nfeats, nsmpls) countries = ['France'] * 2 + ['UK'] * 3 + ['US'] * 5 df = pd.DataFrame(data, index=feats, columns=pd.MultiIndex.from_tuples(zip(countries, smpls))) df.to_csv('./data.tsv', sep='\t') #--------------------------------------------------------------------- #loading dataset df = pd.read_csv('./data.tsv', sep='\t', index_col=0, header=[0,1]) #extracting subset dg = df.xs('France', level=0, axis=1) print(dg.shape) #iterating for country, group in df.groupby(level=0, axis=1): print('#samples: {}'.format(group.shape[1])) 

Answer: Something like this ? using DataFrames, CSV # Used your sample data df = DataFrame(CSV.File("data.tsv")) # Filter the columns by country name france_cols = findall(x -> occursin("France", x), names(df)) # Subset the df dg = select(df, france_cols) # Optional : use "sampleX" as col names instead of the country name rename!(dg, collect(dg[1, :])) dg = dg[2:end, :] display(dg) println(size(dg))  By default, DataFrames adds numbers to similar column names like this : France, France_1 etc so I selected all the columns containing "France".
Question: I am trying to learn GIMP 2.10.38 with python and I don't know either that well, so I tried adding a simple python script but it doesn't show up in GIMP at all. Here is the script I added: #!/usr/bin/env python from gimpfu import * def simple_plugin(image, drawable): gimp.message("Hello from a simple plugin!") register( "python-fu-simple-plugin", "Simple Plugin Test", "A simple test plugin", "Your Name", "Your Name", "2024", "<Image>/Filters/Simple Test", # Or any menu location "RGB*", [], simple_plugin, ) main()  The script is in the correct folder - confirmed that in preferences - folders - plug-ins Searching online I came across the --verbose argument and that led me to this error: Querying plug-in: 'C:\Users\Prafulla\AppData\Roaming\GIMP\2.10\plug-ins\simplepy.py' gimp-2.10: LibGimpBase-WARNING: gimp-2.10: gimp_wire_read(): error  I know it is a general error related to communication within GIMP but couldn't find enough information online. I have tried a reinstall already, but not tried deleting all folders manually yet. Any idea how I should proceed?

Answer: Your problem isn't the "wire-read" error (which has been showing in my Gimp console for years without being related to any trouble). In the same terminal output, you should also see this: Traceback (most recent call last): File "/path/to/your/file.py", line 17, in <module> simple_plugin, TypeError: register() takes at least 11 arguments (10 given)  The missing argument is the (usually empty) list of return values register( "python-fu-simple-plugin", "Simple Plugin Test", "A simple test plugin", "Your Name", "Your Name", "2024", "<Image>/Filters/Simple Test", # Or any menu location "RGB*", [], # <- your existing list of input values [], # <- your missing list of returned values simple_plugin, )  This said this is a deprecated registration usage, in more modern times you would use: #!/usr/bin/env python from gimpfu import * def simple_plugin(image, drawable): gimp.message("Simple plugin, working on %s in %s" % (drawable.name,image.name)) register( "simple-plugin", # "python-fu" added by default anyway... "Simple Plugin Test", "A simple test plugin", "Your Name", "Your Name", "2025", "Simple Test", # Just the menu item "RGB*,GRAY*", # GRAY necessary if you want the plugin to also work on mask/Channels. [ (PF_IMAGE, 'image', 'Input image', None), # Explicit input image (if necessary) (PF_DRAWABLE,'drawable','Input drawable',None), # Explicit input drawable (if necessary) ], [], simple_plugin, menu="<Image>/Filters" # Menu location of menu item above ) main()  Where the two main differences are that:  You explicitly declare the input image and drawable. If they are in that order as the first two arguments, Gimp will use the current image/drawable and not ask for them in a dialog. This syntax allows you to write scripts that don't even need an existing image, or that don't need any input drawable The menu where the item appears is defined separately. You can put the menu in any <dialog> that is coherent with the second argument: <Image>, but also <Layers>, <Vectors>, <Brushes>, <Palettes>...
Question: Just trying to rewrite this c# code to python. Server send public key(modulus, exponent), need to encrypt it with pkcs1 padding. using (TcpClient client = new TcpClient()) { await client.ConnectAsync(ip, port); using (NetworkStream stream = client.GetStream()) { await App.SendCmdToServer(stream, "auth", this.Ver.ToString().Split('.', StringSplitOptions.None)); byte[] modulus = new byte[256]; int num2 = await stream.ReadAsync(modulus, 0, modulus.Length); byte[] exponent = new byte[3]; int num3 = await stream.ReadAsync(exponent, 0, exponent.Length); this.ServerRsa = RSA.Create(); this.ServerRsa.ImportParameters(new RSAParameters() { Modulus = modulus, Exponent = exponent }); using (MemoryStream data = new MemoryStream()) { using (BinaryWriter writer = new BinaryWriter((Stream) data)) { writer.Write(string1); writer.Write(string2); await App.SendDataToServer(stream, this.ServerRsa.Encrypt(data.ToArray(), RSAEncryptionPadding.Pkcs1)); } } } }  Everything works fine, except encrypted result by python. I've tried with rsa and pycryptodome, no luck at all, server returns reject. Tried something like this (rsa) server_rsa = rsa.newkeys(2048)[0] server_rsa.n = int.from_bytes(modulus, byteorder='big') server_rsa.e = int.from_bytes(exponent, byteorder='big') data = (string1 + string2).encode() encrypted_data = rsa.encrypt(data, server_rsa)  or this (pycryptodome) pubkey = construct((int.from_bytes(modulus, 'big'), int.from_bytes(exponent, 'big'))) cipher = PKCS1_v1_5.new(pubkey) encrypted_data = cipher.encrypt(data)  Is there some special python RSA implementation, that just not working with C#, or vice versa?

Answer: The PyCryptodome is a good choice for cryptographic tasks in Python. The problem is with the data formatting, you are concatenating the strings directly in Python and the BinaryWriter in C# write the lengths of the strings as prefixes.This code show how you can do that: import struct data = b"" data += struct.pack(">I", len(string1.encode('utf-8'))) # add length as big-endian unsigned int data += string1.encode('utf-8') data += struct.pack(">I", len(string2.encode('utf-8'))) data += string2.encode('utf-8')    In the code above I encoded the length of the strings as big-endian unsigned int but as was commented by @Topaco the BinaryWriter encodes the length prefix with LEB128. So to replicate BinaryWriter you can do this: import leb128 data = bytearray() data += leb128.u.encode(len(string1.encode())) data += string1.encode() data += leb128.u.encode(len(string2.encode())) data += string2.encode()  I used the leb128 package that can be installed with pip install leb128. But you can create a function to do that encoding def encode_leb128(number): if number == 0: return bytearray([0]) result = bytearray() while number > 0: byte = number & 0x7f number >>= 7 if number > 0: byte |= 0x80 result.append(byte) return result
Question: I am working on Odoo 18 and need to modify the Enquiry Screen to display additional counts near the progress bar. The current progress bar already shows the Expected Revenue, but I want to add more details for better visibility. Requirements CHECK THIS IMAGES 👇 Current view  Expected View  For the "NEW" Stage: The display format should be: 525K - 12 (10) 525K → Expected Revenue (already displayed) 12 → Total Enquiries for the Year (10) → Count of enquiries currently in this stage For all other stages: The display format should be: 525K - 6 6 → Count of enquiries currently in this stage My Questions  Where should I modify the code to achieve this? Should it be done in a custom module, or can it be handled via the XML views? How can I fetch and display these counts dynamically for each stage in Odoo 18? If it needs changes in OWL JS, how should I approach updating the progress bar component?  What I Have Tried I checked the model (crm.lead or similar) but didn’t find an existing field that directly provides the total count of enquiries per year. I explored the OWL JS components but am unsure how to modify the display logic near the progress bar.

Answer: To display an additional count near the progress bar in Odoo 18's Enquiry Screen, follow these steps:  Template Inheritance: Extend the existing ColumnProgress template from the crm module using XML. This allows you to inject custom elements into the progress bar's structure.  XPath Positioning: Use an XPath expression to target the <AnimatedNumber> element (which displays the current value) and insert your additional count after it.  Manifest Configuration: Ensure your module's __manifest__.py declares a dependency on crm and loads the XML asset in the backend.    Code Solution: <?xml version="1.0" encoding="UTF-8"?> <templates xml:space="preserve"> <!-- Inherit and extend the CRM progress bar template --> <t t-inherit="crm.ColumnProgress" t-inherit-mode="extension"> <!-- Insert additional count after the AnimatedNumber element --> <xpath expr="//AnimatedNumber" position="after"> <span class="ml-2"> <!-- Replace 'your_field' with the actual field name --> ####### </span> </xpath> </t> </templates>   Manifest File (__manifest__.py): { # ... other manifest keys 'assets': { 'web.assets_backend': [ 'your_module/static/src/xml/your_template.xml', # XML asset path ], }, # ... other manifest keys }
Question: In Python Polars, I am trying to extract the length of the lists inside a struct to re-use it in an expression. For example, I have the code below: import polars as pl df = pl.DataFrame( { "x": [0, 4], "y": [ {"low": [-1, 0, 1], "up": [1, 2, 3]}, {"low": [-2, -1, 0], "up": [0, 1, 2]}, ], } ) df.with_columns( check=pl.concat_list([pl.all_horizontal( [ pl.col("x").ge(pl.col("y").struct["low"].list.get(i)), pl.col("x").le(pl.col("y").struct["up"].list.get(i)), ] ) for i in range(3)]).list.max() ) shape: (2, 3) ┌─────┬─────────────────────────┬───────┐ │ x ┆ y ┆ check │ │ --- ┆ --- ┆ --- │ │ i64 ┆ struct[2] ┆ bool │ ╞═════╪═════════════════════════╪═══════╡ │ 0 ┆ {[-1, 0, 1],[1, 2, 3]} ┆ true │ │ 4 ┆ {[-2, -1, 0],[0, 1, 2]} ┆ false │ └─────┴─────────────────────────┴───────┘  and I would like to infer the length of the lists in advance (i.e. not having to hardcode the 3), as it can change depending on the call. The challenge I am facing, is that I need to include everything in the same expression context. I have tried as below, but it is not working as I cannot extract the value returned by one of the expressions: df.with_columns( check=pl.concat_list([pl.all_horizontal( [ pl.col("x").ge(pl.col("y").struct["low"].list.get(i)), pl.col("x").le(pl.col("y").struct["up"].list.get(i)), ] ) for i in range(pl.col("y").struct["low"].list.len())]).list.max() ) 

Answer: Unfortunately, I don't see a way to use an expression for the list length here. Also, direct comparisons of list columns are not yet natively supported. Still, some on-the-fly exploding and imploding of the list columns could be used to achieve the desired result without relying on knowing the list lengths upfront. ( df .with_columns( ge_low=(pl.col("x") >= pl.col("y").struct["low"].explode()).implode().over(pl.int_range(pl.len())), le_up=(pl.col("x") <= pl.col("y").struct["up"].explode()).implode().over(pl.int_range(pl.len())), ) .with_columns( check=(pl.col("ge_low").explode() & pl.col("le_up").explode()).implode().over(pl.int_range(pl.len())) ) )  shape: (2, 5) ┌─────┬─────────────────────────┬─────────────────────┬───────────────────────┬───────────────────────┐ │ x ┆ y ┆ ge_low ┆ le_up ┆ check │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ struct[2] ┆ list[bool] ┆ list[bool] ┆ list[bool] │ ╞═════╪═════════════════════════╪═════════════════════╪═══════════════════════╪═══════════════════════╡ │ 0 ┆ {[-1, 0, 1],[1, 2, 3]} ┆ [true, true, false] ┆ [true, true, true] ┆ [true, true, false] │ │ 4 ┆ {[-2, -1, 0],[0, 1, 2]} ┆ [true, true, true] ┆ [false, false, false] ┆ [false, false, false] │ └─────┴─────────────────────────┴─────────────────────┴───────────────────────┴───────────────────────┘