mteb/BrightProStackoverflowRetrieval huggingface dataset:
Python requests module with multithread

Currently, I am developing the astrophotometric software for multiple telescopes. For this, I constructed a mother computer connected with multiple telescopes and these telescopes can be controlled by HTTP protocol. For synchronized operation, I am trying to control these multiple telescopes simultaneously with multithreading.
However, when I retrieve image data (110MB for each, ~1.2GB for total) from multiple telescopes (10 telescopes), the data transfer speed is much slower than I expected. For seamless operation, we have 10G connection with the mother computer, and 1G connection with 10 telescopes. I expected ~9Gbps data transfer speed when 10 telescopes transfer the data simultaneously, but only 1.5Gbps achieved.

For simple test, I extracted the part of the code and check the time consumption.
```
import requests
import time
from astropy.time import Time
def request_imagearray(cam):
    client_trans_id = 1
    client_id = 1
    attribute = 'imagearray'

    url = f"{cam.device.base_url}/{attribute}"
    hdrs = {'accept' : 'application/imagebytes'}
    # Make Host: header safe for IPv6
    if(cam.device.address.startswith('[') and cam.device.address.startswith('[::1]')):
        hdrs['Host'] = f'{cam.device.address.split("%")[0]}]'
    pdata = {
            "ClientTransactionID": f"{client_trans_id}",
            "ClientID": f"{client_id}" 
            }         

    print('START:',Time.now(), cam.device.address)
    start = time.time()
    response = requests.request("GET","%s/%s" % (cam.device.base_url, attribute), params=pdata, headers=hdrs, verify = False)

    print('consumed time:', time.time() - start, cam.device.address)
# %%

unitnumlist = [1,2,3,5,6,7,8,9,10,11]
camlist = []
for unitnum in unitnumlist:
    #camlist.append(mainCamera(unitnum))
    Thread(target = request_imagearray, kwargs = dict(cam = mainCamera(unitnum))).start()
#%% 
```

and the output is
```
START: 2024-04-15 07:49:59.067946 10.0.106.6:11111
START: 2024-04-15 07:49:59.382973 10.0.106.7:11112
START: 2024-04-15 07:49:59.541495 10.0.106.8:11113
START: 2024-04-15 07:49:59.647055 10.0.106.10:11111
START: 2024-04-15 07:49:59.788433 10.0.106.11:11111
START: 2024-04-15 07:49:59.897876 10.0.106.12:11111
START: 2024-04-15 07:50:00.009254 10.0.106.13:11111
START: 2024-04-15 07:50:00.157893 10.0.106.14:11111
START: 2024-04-15 07:50:00.347704 10.0.106.16:11111
START: 2024-04-15 07:50:00.544626 10.0.106.9:11111
consumed time: 5.96204686164856 10.0.106.6:11111
consumed time: 7.304373502731323 10.0.106.7:11112
consumed time: 7.58618688583374 10.0.106.8:11113
consumed time: 7.617574453353882 10.0.106.10:11111
consumed time: 7.678117990493774 10.0.106.11:11111
consumed time: 7.76300311088562 10.0.106.12:11111
consumed time: 7.636215925216675 10.0.106.14:11111
consumed time: 7.785021066665649 10.0.106.13:11111
consumed time: 7.338518857955933 10.0.106.9:11111
consumed time: 11.309057235717773 10.0.106.16:11111
```

The comsumed time is much longer than I expected. I expected ~3sec for all data transferred. It seems that multithreads starts to request "request.get" at the same time, but all the data is not transferred at the same time.
Pydantic - How to subclass a builtin type

I'm trying to make a subclass of timedelta that expects to receive milliseconds instead of seconds, but it's not currently working.

Am I going against the grain? Is there a "right" way to achieve this with Pydantic? Or do I somehow need to tell Pydantic that `MillisecondTimedelta` is just a `timedelta`..

```
from datetime import timedelta

from pydantic import BaseModel


class MillisecondTimedelta(timedelta):
    @classmethod
    def __get_validators__(cls):
        # timedelta expects seconds
        yield lambda v: v / 1000
        yield cls


class MyModel(BaseModel):
    td: MillisecondTimedelta

data = {
    "td": 7598040,
}

print(MyModel(**data))
```

Results in:
```
Traceback (most recent call last):
  File "main.py", line 14, in <module>
    class MyModel(BaseModel):
  File "pydantic/main.py", line 262, in pydantic.main.ModelMetaclass.__new__
  File "pydantic/fields.py", line 315, in pydantic.fields.ModelField.infer
  File "pydantic/fields.py", line 284, in pydantic.fields.ModelField.__init__
  File "pydantic/fields.py", line 362, in pydantic.fields.ModelField.prepare
  File "pydantic/fields.py", line 541, in pydantic.fields.ModelField.populate_validators
  File "pydantic/class_validators.py", line 255, in pydantic.class_validators.prep_validators
  File "pydantic/class_validators.py", line 238, in pydantic.class_validators.make_generic_validator
  File "/usr/lib/python3.8/inspect.py", line 3105, in signature
    return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
  File "/usr/lib/python3.8/inspect.py", line 2854, in from_callable
    return _signature_from_callable(obj, sigcls=cls,
  File "/usr/lib/python3.8/inspect.py", line 2384, in _signature_from_callable
    raise ValueError(
ValueError: no signature found for builtin type <class '__main__.MillisecondTimedelta'>
```
Loading external javascript file in index.html of React App

I have this React app in which I load my external javascript file inside the tag as below index.html:
```
....
<script type="text/javascript" src="../src/assets/externalJavascript.js"></script>
</head>
```

Inside externalJavascript.js, I have this below:
```
let queryParams = window.location.search.substring(1);

console.log("Query: ", queryParams)

window.loadFunc = function loadFunc() {
            console.log("Script Loaded!");
          };
```

I access this loadFunc() inside my desired component using window.loadFunc()

All this is not working but if I make the js file inline in the index.html, it's working! Like this below:
```
<script>
      (function () {
          let queryParams = window.location.search.substring(1);

          console.log("Query: ", queryParams);

          window.loadFunc = function loadFunc() {
            console.log("Script Loaded!");
          };
      })()
    </script>
```

When my app loads, I get the query in console log and also I can access the loadFunc() only when it is inline script.

Please help me to solve this.

Thank you!
DAX RLS Function using LOOKUPVALUE Parsing but not working

I have a table that I'm trying to implement RLS on using a secondary table with a structure below:

EmployeeTable
```
EmployeeID        EmployeeEmail
1        1234@email.com
2        4567@email.com
```

FilterTable
```
EmployeeID        ManagerHierarchy
1        3&4&5
2        6&7&4&5
```

The ManagerHierarchy column is a string that shows all managers of an employee concatenated together and separated by "&".

The goal of the RLS is to create a filter that allows any manager to view the report and have their data only display employeeIDs wherein their own ID exists within the ManagerHierarchy column and thus only showing their subordinates.

I have the below DAX expression applied on EmployeeTable that I thought would work and parses in the expression builder, but it is giving me errors:
```
[EmplID]=
LOOKUPVALUE(
FilterTable[EmployeeID], FilterTable[ManagerHIERARCHY],

LOOKUPVALUE( //This is to return the viewer's own employeeID to be crossed over into the FilterTable
[EmployeeID], [EmployeeEmail], USERPRINCIPALNAME())
)
```

The Report it gives is as follows:

An error was encoutnered during the evaluation of the row level security defined on EmployeeTable. Function 'LOOKUPVALUE' does not support values of type Text with values of type integer. Consider using the VALUE or FORMAT function to convert one of the values.

I've tried re-shuffling my DAX expression with to convert it as such, but I haven't been able to make it work as intended.
Consume InputIterator with C++ ranges

With an input iterator, I can consume different sub-ranges out of it, e.g.
```
void test(std::input_iterator auto it) {
  while (*it < 1) ++it; // drop_while
  int n = *it++; // take(1)
  int sum = 0; while (n-- > 0) sum += (1 + *it++); // fold_left(take(n) | transform)
  int prd = 1; while (int x = *it++ / 2) prd *= x; // fold_left(transform | take_while)
  std::cout << sum << ' ' << prd << '\n';
}

int main() {
    test(std::begin({0, 0, 0, 3, 400, 30, 2, 4, 6, 0}));
}
```

Is there a way to do the same with `std::ranges`/`std::views`?
Storing Binary String in DynamoDb

I am trying to store a binary string in DynamoDB using Java. However, the builder is converting the bytes somehow. My original string is a zipped string. If I pass:

H4sIAAAAAAAAA7LJKMnNsePlsslITUyxsynJLMlJtTMxMFXwyy9RcMzJyS9PTbHRhwjb6IMVARUn5adUKiSlJ+fn5BfZKpVnZJakKoHEk1PzSlKL7GwyDDHNAIrZ6EMVgOwDKoPy8tIz8yr0DfUMDfVMkZXog6wBM6COBAAAAP//AwBuTqCXrQAAAA==

The value in the database is converted to: SDRzSUFBQUFBQUFBQTdMSktNbk5zZVBsc3NsSVRVeXhzeW5KTE1sSnRUTXhNRlh3eXk5UmNNekp5UzlQVGJIUmh3amI2SU1WQVJVbjVhZFVLaVNsSitmbjVCZlpLcFZuWkpha0tvSEVrMVB6U2xLTDdHd3lEREhOQUlyWjZFTVZnT3dES29QeTh0SXo4eXIwRGZVTURmVk1rWlhvZzZ3Qk02Q09CQUFBQVAvL0F3QnVUcUNYclFBQUFBPT0=
```
Object responseMap = mMap.get("Response");
LinkedHashMap<String, String> responseMapped = (LinkedHashMap<String, String>)responseMap;

String status = statusMapped.get("N");
String response = responseMapped.get("B");

SdkBytes bytes = SdkBytes.fromUtf8String(response);

historyValueMap.put("Status", AttributeValue.builder().n(status).build());
historyValueMap.put("Response", AttributeValue.builder().b(bytes).build());

historyMap.put(historyKey, AttributeValue.builder().m(historyValueMap).build());
```

I also tried to convert the byte array to a base64 but that didn't work either.
```
String status = statusMapped.get("N");
byte[] response = responseMapped.get("B").getBytes();

byte[] base64Response = Base64.getEncoder().encode(response);
SdkBytes responseAsSdk = SdkBytes.fromByteArray(base64Response);

historyValueMap.put("Status", AttributeValue.builder().n(status).build());
historyValueMap.put("Response", AttributeValue.builder().b(responseAsSdk).build());
```
How can I pass a variable from CSV file to Oracle SQL query fetch in Python?

I have the following piece of code where I read a csv file and connect to the database. then I want to pass two columns from CSV file as variable to my query and eventually convert the result to a pd database.

I have tried different ways of binding and converted columns to list but I was unsuccessful. with this piece of code I get the following Error:
```
DatabaseError: DPY-4010: a bind variable replacement value  
for placeholder ":HOUR" was not provided
```

or I get below error when I add this part to execute():
```
res = connection.cursor().execute("SELECT HOUR,UNITSCHEDULEID,VERSIONID,MINRUNTIME FROM 
 int_Stg.UnitScheduleOfferHourly WHERE  Hour in :1 AND UnitScheduleId in :2", hour, unitid)
```
```
TypeError: Cursor.execute() takes from 2 to 3 positional arguments but 4 were given
```

the following is the code I execute:
```
import pandas as pd
import numpy as np

df = pd.read_csv(r"csv.csv") 

df=df.dropna()

unitid=df['UNITSCHEDULEID'].unique()
hour=df['GMT_DATETIME'].unique()

import os, oracledb, csv, pyodbc
TNS_Admin = os.environ.get('TNS_Admin', r'\\corp.xxx\oracle')
oracledb.defaults.config_dir = TNS_Admin
pw = input(f'Enter password: ')
connection = oracledb.connect(user='xxxxx', password= pw, dsn="World")

res = connection.cursor().execute("SELECT HOUR,UNITSCHEDULEID,VERSIONID,MINRUNTIME FROM 
 int_Stg.UnitScheduleOfferHourly WHERE  Hour in :Hour AND UnitScheduleId in :unitid").fetchall()
print(res)

connection.close()
```
How to save a xml structure using python tree.write(file_name)?

I wanted to add Element with Subelements to my xml file using Python. But after changing file the Element and Subelement looks like a line, not like a xml-tree.

I do this:
```
tree = ET.parse('existing_file.xml')
root = tree.getroot()
new_object = ET.SubElement(root, 'object')
name = ET.SubElement(new_object, 'name')
name.text = 'car'
color = ET.SubElement(new_object, 'color')
color.text = 'Red'
new_tree = ET.ElementTree(root)
new_tree.write('new_file.xml')
```

But after this I've got file without structure like this:
```
<object><name>car</name><color>red</color></object>
```

But i need this:
```
<object>
     <name>car</name>
     <color>red</color>
</object>
```

what do I do wrong?
How can I build a firestore query for Android with whereGreaterthan() filters for two different fields?

I need to filter the list of my documents which I am fetching from `firestore` in my android `app`. this is the query.
```
  query = FirebaseFirestore.getInstance()
            .collection("students")
            .whereLessThan("mAge",25)
            .whereGreaterThan("mAge",20)
            .whereGreaterThan("mGrades",20);
```

but, I get an error in the log:
```
java.lang.RuntimeException: Unable to start activity ComponentInfo{dsardy.in.acchebacche/dsardy.in.acchebacche.MainActivity}: java.lang.IllegalArgumentException: All where filters other than whereEqualTo() must be on the same field. But you have filters on 'mAge' and 'mGrades'
```

Can this be achieved? a filter with two or more fields greater than some values is an important and general query, `firestore` must have something to tackle this.
How to make MudSelect show text of selected option instead of value?

```
<MudSelect MultiSelection="true" @bind-SelectedValues="ViewModel.Model.GlobalSalaryAccessUserIds">
                @foreach (var salaryAccessUser in ViewModel.GlobalSalaryAccessUsers)
                {
                    <MudSelectItem Value="@salaryAccessUser.Id">@GenerateSalaryAccessUserDisplayString(salaryAccessUser)</MudSelectItem>
                }
            </MudSelect>
```

Now instead of string which generates in `GenerateSalaryAccessUserDisplayString` it shows a value of the option, which is id, when I've selected a few of them . How can I change it to show the generated string?
How to record audio and video corss platform with electron

So i was making a electron project that records your screen and your desktop or selected app's audio with desktopCapture. I got the screen record, and at one point even got the mic to work, but at no point, no matter what i tried, i couldn't record desktop audio nor any app's audio. After some research i found that you cannot record any desktop nor app's audio with chromium on linux.

So what could be the solution or some other ways to try to record desktop audio. Maybe there is some way to record desktop audio with a different library and then combine the video with audio somehow.

Any suggestions would be appreciated.

Code for the screen recorder itself:
```
videoSelectBtn.onclick = getVideoSources;

async function getVideoSources() {
  const inputSources = await desktopCapturer.getSources({
    types: ["window", "screen", "audio"],
  });

  inputSources.forEach((source) => {
    if (source.name === "Screen 1") {
      selectSource(source);
    } else {
      console.log(source);
    }
  });
}

async function selectSource(source) {
  videoSelectBtn.innerText = source.name;

  const constraints = {
    audio: {
      mandatory: {
        chromeMediaSource: "desktop",
      },
    },
    video: {
      mandatory: {
        chromeMediaSource: "desktop",
      },
    },
  };

  const stream = await navigator.mediaDevices.getUserMedia(constraints);
```
My api request in my asyncThunk function in slice file doesn't work when I put a dispatch method before that

I have this asyncThunk action and everything was fine until I put a `dispatch` call before sending request. As a result every code after this `dispatch` call doesn't work anymore. 'first' goes in log but 'second' no. I don't know why this dispatch blocks next codes in my asyncThunk function.

My slice file:
```
export const postLoginData = createAsyncThunk(
  'login/postLoginData',
  async (allData) => {
    const { dispatch, params } = allData;

    let loginResponse = '';

    console.log('first')
    dispatch(setStatus({type: 'loading', payload: 'wait'}))
    console.log('second')

    await postRequest('/o/token/coach', params)
      .then(response => {
        loginResponse = response.data
        const data = response.data;
        if (data.access_token) {
          dispatch(loginSuccess(data))
          localStorage.setItem('Authentication', JSON.stringify(data));
        }
      })
      .catch(err => {
        if (err.response.status === 400) {
          loginResponse = { error: '400 Error' }
        }
      })
    dispatch(setStatus({ type: 'loading', payload: false }))
    console.log(loginResponse)
    return loginResponse
  }
)
```
Gorm preload doesn't follow the Join conditions

So I'm trying to make a complex queries with a lot of joins and nested structs. I need to load the structs but Preload is not following related Joins with their conditions and its keep doing its own queries.

How can I make this work?

My joins are pretty complicated and I don't want to do the same join twice.
```
type Assetinfo struct {
    Uid           string
    MapPolicyApps []MapPolicyApps `gorm:"foreignKey:app_id;references:uid;AssociationForeignKey:pol_id"`
}
type MapPolicyApps struct {
    Id           int
    PolID        string       `gorm:"column_name:pol_id;foreignKey:Uid"`
    PolicyPolicy PolicyPolicy `gorm:"foreignKey:Uid;references:PolID;AssociationForeignKey:uid"`
    AppType      string    // This can be application or category
    AppId        string    `gorm:"column_name:app_id;foreignKey:Uid"`  // this can be app id or application id (bad naming i know)
    Asset        Assetinfo `gorm:"foreignKey:AppId;references:Uid"`
    CreatedAt    string
}

type PolicyPolicy struct {
    Uid               string `gorm:"primaryKey"`
    IsEnabled         bool
    MapPolicyProfiles []MapPolicyProfiles `gorm:"foreignKey:PolID;references:Uid"`
}

var assets []*Assetinfo 

err := Db.Table("application_application apps").
    Select("Distinct apps.*, apps.avatar as icon, profile_asset.address as ip, apps.is_health_check as is_need_request").
    Joins("LEFT JOIN map_policy_identities ON map_policy_identities.assign_type = 'user' AND map_policy_identities.assign_id = ?", userid).
    Joins("LEFT JOIN policy_policy ON map_policy_identities.pol_id = policy_policy.uid AND policy_policy.is_enabled = true").
    Joins("LEFT JOIN map_policy_apps ON map_policy_identities.pol_id = map_policy_apps.pol_id").
    Joins("LEFT JOIN map_category_apps ON map_category_apps.category_id = map_policy_apps.app_id").
    Joins("LEFT JOIN map_app_assets ON apps.uid = map_app_assets.app_id").
    Joins("LEFT JOIN profile_asset ON profile_asset.uid = map_app_assets.asset_id").
    Where("map_policy_apps.app_id = apps.uid OR apps.uid = map_category_apps.app_id").
    Where("apps.is_enabled = true AND apps.is_visibled = true").
    Preload("MapPolicyApps.PolicyPolicy.MapPolicyProfiles.ProfileAddr").
    Preload("MapPolicyApps.PolicyPolicy.MapPolicyProfiles.ProfileTimerange").
    Preload("MapPolicyApps.PolicyPolicy.MapPolicyProfiles.ProfilePosturecheck").
    Find(&assets).Error
```

And Gorm can't load the structs without Preload, So if it's possible to load all nested structs with joins and without Preload, I would appreciate to know how.
Copy and delete files from SFTP folder

I have to pick (remove) the files with file mask `FileName_A_*` and `FileName_B_*` from SFTP location and place them in an sharedrive.

I tried using WinSCP. I have created an `HourlyFile.txt` file with below code and placed it under `C:\Program Files (x86)\WinSCP`. Another batch file `HourlyFile.bat` to execute the script from HourlyFile.txt

HourlyFile.txt:
```
option batch abort
option confirm off
open sftp..........
get -filemask="FileName_A_*" /outbound/test/* \\sharedrive
get -filemask="FileName_B_*" /outbound/test/* \\sharedrive
del /outbound/test/FileName_A_*
del /outbound/test/FileName_B_* 
exit
```

HourlyFile.bat:
```
winscp.com /script=HourlyFile.txt
pause
```

I tried with below options to delete the file but got the error message "Unknown command". Also the above code is copying subfolder from `/outbound/test/` , which it should not.
Commands tried:
```
del /outbound/test/FileName_A_*
-del /outbound/test/FileName_A_*
delete /outbound/test/FileName_A_*
delete /outbound/test/FileName_A_20190604_090002
delete /outbound/test/FileName_A_20190604_090002.csv
```
useState set method not changing my state - react native

I'm working on a part of an application dealing with a deck of cards. For however many cards a player is supposed to have, I am looping through a deck of cards held in a state, randomly picking a card, assigning it to that player and then removing it from the deck. This all works correctly but when the deck is empty (.length === 0), I want to invoke a shuffle() method that will set the deck equal to the discard pile which is also an array held in a useState. The discard pile is also working as expected but for some reason when trying to set the currentDeck to the discard pile, using setCurrentDeck(discardPile), the currentDeck array remains empty. (I've also tried setCurrentDeck([...discardPile])).

I know this mostly likely has to do with how React handles batching hook calls, and that the value of currentDeck is not what I think it is because of the other setCurrentDeck() calls, but I'm still not able to figure out what's going on.

My code (simplified):
```
const [currentDeck, setCurrentDeck] = useState(deck) // 'deck' is a hard coded array of cards
const [discardPile, setDiscardPile] = useState([])
const [faceUpCard, setFaceUpCard] = useState(null)

  useEffect(() => {
    if (currentDeck.length === 0) {
      const temp = discardPile;
      setCurrentDeck([...temp]);
      setDiscardPile([]);
    }
  }, [currentDeck]);

  function deal() {
    if (readyToDeal) {
      for (let i = 0; i < round + 2; i++) {
        for (let j = 0; j < players.length; j++) {
          const rand = Math.floor(Math.random() * currentDeck.length);
          // players are assigned cards
          currentDeck.splice(rand, 1); // card that was assigned is removed from deck
          setCurrentDeck([...currentDeck]);
        }
      }
      const rand = Math.floor(Math.random() * currentDeck.length);
      setFaceUpCard(currentDeck[rand]);
      currentDeck.splice(rand, 1);
      setCurrentDeck([...currentDeck]);
      setReadyToDeal(false);
    }
  }
```

I have also tried setting currentDeck with a shuffle method like this:
```
  function shuffle() {
    const temp = discardPile;
    setCurrentDeck([ ...temp]);
    setDiscardPile([]);
  }

  function deal() {
    if (readyToDeal) {
      for (let i = 0; i < round + 2; i++) {
        for (let j = 0; j < players.length; j++) {
          if (currentDeck.length === 0) {
            shuffle();
          }
          const rand = Math.floor(Math.random() * currentDeck.length);
          // players are assigned cards
          currentDeck.splice(rand, 1); // card that was assigned is removed from deck
          setCurrentDeck([...currentDeck]);
        }
      }
      const rand = Math.floor(Math.random() * currentDeck.length);
      setFaceUpCard(currentDeck[rand]);
      currentDeck.splice(rand, 1);
      setCurrentDeck([...currentDeck]);
      setReadyToDeal(false);
    }
  }
```

but still no luck. Any help or advice would be appreciated. Thank you!