why does the time limit exceed even though my function terminates? Posted: 31 May 2021 07:56 AM PDT Q: "Given an array of integers nums and an integer k, return the total number of continuous subarrays whose sum equals to k." I have written the following function (a brute force solution that will check whether every sub array sums to the total k): def subarraySum(nums,k): counter = 0 pointer = 0 temp_holder = 0 while pointer < len(nums): for i in range(pointer,len(nums)): temp_holder+= nums[i] if temp_holder == k: counter += 1 temp_holder = 0 pointer += 1 return counter When I run it against some larger input sets, I get a 'Time Limit Exceeded' error. Any idea where the code may be going wrong? When I run the above function manually in my head, I think there could be instances where solutions are missed. Here is the question for reference: https://leetcode.com/problems/subarray-sum-equals-k/ |
firebase.database() is not a function? Posted: 31 May 2021 07:56 AM PDT HIHI, I try to import firebase into my project. At first step, I import the code as below: import firebase from '@firebase/app'; require('firebase/auth'); require('firebase/storage'); require("firebase/firestore"); require('firebase/functions'); require('firebase/database'); system console.log the info as this picture I can't find the database function. and then I try the code as below: import firebase from 'firebase/app'; import 'firebase/database'; import 'firebase/storage'; Beside database, I can't find other things Could anyone tell me what happen? Thanks first. |
How to get list of filenames with different prefix with current date and store as list in pyspark Posted: 31 May 2021 07:56 AM PDT Need to get multiple filenames to list from a folder for current date in blob storage. /mnt/myspace/inbound/FMD/FOA/pricelist/05_2021-05-28.json /mnt/myspace/inbound/FMD/FOA/pricelist/1000_2021-05-28.json /mnt/myspace/inbound/FMD/FOA/pricelist/A1_2021-05-28.json /mnt/myspace/inbound/FMD/FOA/pricelist/B3_2021-05-28.json /mnt/myspace/inbound/FMD/FOA/pricelist/C3_2021-05-28.json date changes dynamically for everyday with current date. so date should be passed as an argument not working with below option date = datetime.today().strftime('%Y-%m-%d') df = spark.read.json("/mnt/myspace/inbound/FMD/FOA/pricelist/"+"(.*)"+date+".json") kindly help |
Generating random/synthetic queries(around 10000 queries) at once based on Database Posted: 31 May 2021 07:55 AM PDT I have an IMDB database for which I need to generate synthetic queries(around 5000 queries) at once, for training my model, Is there any way to do that? |
How to resolve runtime error caused for stl_iterator due to reference binding to null pointer of type int? Posted: 31 May 2021 07:55 AM PDT I have been trying to solve this problem on Leetcode about deep copying a Linked list with an additional random pointer to each node. for the same, I have thought of doing this in a two step process i.e. first create a deep copy of the linked list just with the next nodes and then later construct the random pointer assignment. To construct the random pointer assignment, I am - creating a vector with value from random pointer of each node
- Then writing a constructRandom function which takes the head and the above obtained vector as input and iterates through the linked list to find the node with value equal to the first value of the vector and then removing the first value from the vector.
- recursively calling the same function until all the nodes are done
I know this is very inefficient way as it appears to me of complexity O(n!). But while implementing this I came across certain error, which I want to figure out before I think of another efficient solution. The error is Line 789: Char 16: runtime error: reference binding to null pointer of type 'int' (stl_iterator.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_iterator.h:820:16 Here is my complete code of the class LinkedList, class Solution { public: Node* constructDeepCopy(Node* head){ if(!head){ return head; } Node* newNode = new Node(head->val); newNode->next = constructDeepCopy(head->next); return newNode; } Node* constructRandom(Node* head, vector<int> values){ Node* curr = head, *temp=head; if(head == NULL){ return NULL; } while (temp){ if(values.front() == temp->val){ curr->random = temp; values.erase(values.begin()); break; } else if(values.front() == 10001){ curr->random = NULL; values.erase(values.begin()); break; } else{ temp = temp->next; } } if(values.size()>0){ curr->next->random = constructRandom(curr->next, values); } return curr; } Node* copyRandomList(Node* head) { vector<int> value{}; Node* newNode = constructDeepCopy(head); Node* curr = head->random; while(curr){ if(curr == NULL){ value.push_back(10001); } else{ value.push_back(curr->val); } curr = curr->random; } newNode = constructRandom(newNode, value); return newNode; } }; can anyone please help me point out the error. I believe this error must be similar to that of out of bounds exception that arises with arrays but I can not find out where I am going out of bounds here. Thank you. |
Solve math equations in Python Posted: 31 May 2021 07:55 AM PDT My equation is like this, when I run wrong results, I don't know if my code has any errors. Hope everybody help please My code: k = int(input('input a number: ')) math = pow(abs(k)-math.sqrt(pow(k,2)+1),1/3) print(math) Here is a picture of my program to solve: https://i.stack.imgur.com/BfDnS.jpg This is the printout I got: https://i.stack.imgur.com/WFlE7.jpg |
Add a counter to a VBA function Posted: 31 May 2021 07:55 AM PDT I am currently working on a sheet where I would like to know how many times does a cell change in value. I have the following code: Function Bidcalcul(Bid As Variant, Intervmin As Variant, Intervmax As Variant, Ticksize As Variant, Percentage As Variant) As Variant Dim rowcompteur As Integer Dim valeurinitial As Variant valeurinitial = ActiveCell.Value rowcompteur = ActiveCell.Row If IsError(Bid) Then Bidcalcul = WorksheetFunction.Floor(Bid * Percentage, Ticksize) End If If Intervmin <= (Bid - valeurinitial) And (Bid - valeurinitial) <= Intervmax Then Bidcalcul = valeurinitial Else Bidcalcul = WorksheetFunction.Floor(Bid * Percentage, Ticksize) **Call Compteur(rowcompteur, 23)** End If End Function Private Sub Compteur(rowcompteur As Integer, column As Integer) Cells(rowcompteur, column).Value = Cells(rowcompteur, column).Value + 1 End Sub But when calling the function Compteur it doesn't seems to work. Do you have any idea on how I could do it? (I've already tried with a simple formula on excel but since I retrieve my values from Bloomberg it doesn't work) Thanks! |
Corrupted/overwritten excel file with write_xlsx Posted: 31 May 2021 07:55 AM PDT I am using this code in R to change the name of the fourth column of an excel file (thanks to this: Change column name with file name of corresponding excel file), however the problem is that at the end the file is overwritten and it generates a corrupted excel file (Excel file format and extension don't match). How it is possible to create a new excel file a the end (not overwritten) or do you have any other solution to not create a corrupted file? filenames <- list.files(pattern = '\.xlsx', full.names = TRUE) lapply(filenames, function(x) { #Read the data data <- readxl::read_excel(x) #Change the 4th column with filename names(data)[4] <- tools::file_path_sans_ext(basename(x)) #Write the data back writexl::write_xlsx(data, x) }) |
Simple async example from zeromq with python Posted: 31 May 2021 07:55 AM PDT I would like to write a simple Pub/Sub in Python that runs async. My idea is that a publisher sends a msg and the subscribers are listening to it asynchron while normal synchron python code is still executed. Here is my code for the subscriber: import asyncio import zmq from zmq.asyncio import Context ctx = Context.instance() async def recv(): s = ctx.socket(zmq.SUB) s.connect('tcp://127.0.0.1:5001') s.subscribe(b'') await asyncio.sleep(1) #while True: msg = await s.recv_multipart() print('received', msg) s.close() print("Test1") asyncio.run(recv()) print("Test2") and here my code for the publisher: import zmq import time import zmq.asyncio import asyncio ctx = zmq.asyncio.Context() host = "127.0.0.1" port = "5001" # Creates a socket instance async def publish(): socket = ctx.socket(zmq.PUB) # Binds the socket to a predefined port on localhost socket.bind("tcp://{}:{}".format(host, port)) await asyncio.sleep(1) # Sends a string message await socket.send_string("test") asyncio.run(publish()) I would expect that the lines of my subscriber are executed like this: Test1 Test2 test <= Msg comming back from publisher since I use async other python code should be executed first but what happens is it gets executed like this: Test1 test Test2 which means it is normally synchron executed. Can someone please explain me what I did wrong? Many thanks |
PHP Secure Image Upload Control? Posted: 31 May 2021 07:55 AM PDT First of all, I would like to apologize for asking this question again, although many people have already asked this question and it has been answered. But I'm so confused. Although I came across https://www.w3schools.com/php/php_file_upload.asp and I trusted w3schools, I succumbed to my curiosity and researched. https://www.php.net/manual/en/function.getimagesize.php here "the getimagesize() function should not be used to test whether the specified file is a valid file, but a purpose-built solution such as the Fileinfo plugin." When I saw that it was written, I continued my research. I came across those who recommended "exif_imagetype". But when I searched again How to bypass the exif_imagetype function to upload php code? I was thoroughly confused when I saw this question. I saw this here the most reliable way to check upload file is an image Then i write that code: function isset_file($name) { return (!isset($_FILES[$name]) || $_FILES[$name]['error'] == UPLOAD_ERR_NO_FILE); } if (isset_file('image')) { echo "There is no image."; return; } $whitelist_type = array('image/jpeg', 'image/png', 'image/jpg'); $fileinfo = finfo_open(FILEINFO_MIME_TYPE); $filetype = finfo_file($fileinfo, $_FILES['image']['tmp_name']); finfo_close($fileinfo); if (!in_array($filetype, $whitelist_type)) { echo "That file is not png,jpg and jpeg type."; return; } $target_dir = "uploads/"; $image_extension = explode(".", basename($_FILES["image"]["name"])); if (count($image_extension) > 1) { $image_extension = "." . end($image_extension); } else { $image_extension = ""; } $target_file = $target_dir . $_POST['ad'] . $image_extension; if (file_exists($target_file)) { echo "That image is already exists."; return; } if ($_FILES["image"]["size"] > 500000) { echo "Image size is too big."; return; } if (!move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) { echo "There is some error when trying to upload image."; return; } But in that link https://www.php.net/manual/en/function.finfo-file.php i saw that comment: "Tempting as it may seem to use finfo_file() to validate uploaded image files (Check whether a supposed imagefile really contains an image), the results cannot be trusted. It's not that hard to wrap harmful executable code in a file identified as a GIF for instance. A better & safer option is to check the result of: if (!$img = @imagecreatefromgif($uploadedfilename)) { trigger_error('Not a GIF image!',E_USER_WARNING); // do necessary stuff } what should i do? i just want to be 100% safe for upload vulnerabilty by only allowing png,jpg and jpeg types |
How can I create a panda Serie from two series, selecting the first matching element in the second file from a common column? Posted: 31 May 2021 07:54 AM PDT Bonjour ! I'm developing a easy driving simulator with psychopy. I set (traffic) lights around the window, and they are lighting on and off. The light and the colour are randomly generated. Then, I would like to : - dataframe LIGHTS_list :record each light switching on and off ✅
- dataframe KEYS_list : record each key pressed ✅
- dataframe LIGHT_trial : match the first key pressed during the light on ❌
- dataframe LIGHT_trial : if no key pressed, write "nothing" ❌
- dataframe LIGHT_trial : check if the first key pressed is the one expected ✅❌ (the function works but isn't correctly implemented, because of the two previous steps)
if you need to see the variables declarations: # --------- TABLE LIGHT components EVENT_list= pd.DataFrame (columns = ["frame","trigger","lightON","lightCOLOUR","keypressed","result"]) #initializing the list for the FRAMES when a new action is recorded LIGHTS_list = pd.DataFrame(columns = ["LIGHT name","LIGHT colour","lightON", "LIGHT time off", "action required"]) KEYS_list = pd.DataFrame(columns =["lightON","KEY name", "KEY pressed time", "KEY duration"]) #------------------- ATTENTION, j'ai ajouté lightON pour merger les tableaux en light_trial light_trial = pd.DataFrame(columns = ["LIGHT name","LIGHT colour","LIGHT time on", "LIGHT time off", "action required","KEY name", "KEY pressed time", "KEY duration"]) #------------------------ATTENTION, action result removed after KEYNAME for test merging EXAMPLE LIGHTS_list : LIGHT name - LIGHT colour - lightON - LIGHT time off - action required lightBB - green - 0.0233359 - 0.9297223 - nothing lightRG - green - 1.9957957 - 2.8119444 - nothing lightLF - orange - 3.8795967 - 4.7616028 - nothing lightRG - red - 5.87728 - 6.6938645 - space KEYS_list : lightON - KEY name - KEY pressed time - KEY duration 0.0233359 - a - 1.005227 - 0.1171798 1.9957957 - z - 2.5968278 - 0.1431718 3.8795967 - e - 4.1282927 - 0.1876447 3.8795967 - e - 4.827796 - 0.1544934 5.87728 - r - 6.4868242 - 0.1813495 5.87728 - escape - 7.1298663 - 0.1340118 WISH : LIGHT_trial : LIGHT name - LIGHT colour - lightON - LIGHT time off - action required - KEY name - action result - KEY pressed time - KEY duration lightBB - green - 0.0233359 - 0.9297223 - nothing - a - WRONG - 1.005227 - 0.1171798 lightRG - green - 1.9957957 - 2.8119444 - nothing - z - WRONG - 2.5968278 - 0.1431718 lightLF - orange - 3.8795967 - 4.7616028 - nothing - e - WRONG - 4.1282927 - 0.1876447 lightRG - red - 5.87728 - 6.6938645 - space - r - WRONG - 6.4868242 - 0.1813495 then, here is the code I've written so far and I'm totally lost# ''' ######### FILE 7 : LIGHTS-KEYS TRIAL ########### # data to be written row-wise in csv file ''' for each key pressed (KEY_list) take the time it was pressed and check if it is between LIGHT ON && LIGHT OFF of each light in LIGHT_list if OKAY, take the first KEY and create the TRIAL entry ''' #""" i = 0 j = 0 thislight=pd.DataFrame(columns=['lightname','lightcolour','timeON','timeOFF','actionrequired']) print('type', type(thislight)) print("empty this light",thislight) keysoflight = pd.DataFrame(columns=['lightON','keyname', 'keytime', 'keydur']) while i < len(LIGHTS_list): for index, LIGHTrow in LIGHTS_list.iterrows() : lightname = LIGHTS_list["LIGHT name"].iloc[i] lightcolour = LIGHTS_list["LIGHT colour"].iloc[i] timeON = LIGHTS_list['lightON'].iloc[i] timeOFF = LIGHTS_list['LIGHT time off'].iloc[i] actionrequired = LIGHTS_list["action required"].iloc[i] keyname = '' keypressedtime = 0.0 keyduration = 0.0 actionresult='none' thislight = pd.Series([lightname, lightcolour, timeON, timeOFF, actionrequired],index=thislight.columns) print("add light in this light") print(thislight) while j < len(KEYS_list): for index, KEYrow in KEYS_list.iterrows(): lightTimeOn = KEYrow["lightON"] keyname = KEYrow["KEY name"] keypressedtime = KEYS_list["KEY pressed time"].iloc[index] keyduration = KEYrow["KEY duration"] if lightTimeOn == timeON: print ("light ",i, "start :",timeON, "lightTimeOn",lightTimeOn, "key:",keyname,"pressed:", keypressedtime, "stop:",timeOFF) keygroupitem= pd.Series([lightTimeOn, keyname, keypressedtime, keyduration], index=keysoflight.columns) keysoflight = keysoflight.append(keygroupitem, ignore_index=True) actionresult = result_light_keyboard(lightcolour,keyname) """ if keypressedtime <= timeOFF and keypressedtime >= timeON: print ("light ",i, "start :",timeON, "key:",keyname,"pressed:", keypressedtime, "stop:",timeOFF) keygroupitem= pd.Series([keyname, keypressedtime, keyduration], index=keysoflight.columns) keysoflight = keysoflight.append(keygroupitem, ignore_index=True) actionresult = result_light_keyboard(lightcolour,keyname) """ print(keysoflight) #keysoflight = keysoflight.iloc[0] #keysoflight= KEYS_list[KEYS_list['KEY pressed time'].between(timeON, timeOFF)] #keysoflight = keysoflight.iloc[0] #print(keysoflight) j=j+1 #lighttrial_entry = pd.Series([lightname,lightcolour,timeON,timeOFF,actionrequired,keyname,actionresult,keypressedtime,keyduration],index=light_trial.columns) lighttrial_entry = pd.Series([lightname,lightcolour,timeON,timeOFF,actionrequired,keyname,keypressedtime,keyduration],index=light_trial.columns) light_trial = light_trial.append(lighttrial_entry, ignore_index=True) #keysoflight = pd.DataFrame(columns=["keyname", "keytime", "keydur"]) i = i+1 j = 0 #lON = LIGHT_list["lightCOLOUR"].iloc[-1] #for key in KEY_list : # each LIGHT, retreive all the [KEYS] pressed during ON && OFF #show the first one """ LIGHTS_list["LIGHT name","LIGHT colour","LIGHT time on", "LIGHT time off", "action required"]) KEYS_list = ["KEY name", "KEY pressed time", "KEY duration"]) light_trial =["LIGHT name","LIGHT colour","LIGHT time on", "LIGHT time off", "action required","KEY name","action result", "KEY pressed time", "KEY duration" """ #light_trial = light_trial.drop(light_trial[(light_trial['KEY pressed time'] > light_trial['LIGHT time off']) & (light_trial['KEY pressed time'] < light_trial['LIGHT time on']) ].index) #""" #light_trial = LIGHTS_list.merge(KEYS_list, on='lightON') #------------------- NE MET PAS LES LUMIERES QUI N'ONT PAS EU DE TOUCHE #light_trial = pd.concat([LIGHTS_list, KEYS_list], axis=1, join='inner') light_trial.to_csv('lights-trial.csv',index=False,header=True) ''' printing output type <class 'pandas.core.frame.DataFrame'> empty this light Empty DataFrame Index: [] add light in this light lightname lightBB lightcolour green timeON 0.0233359 timeOFF 0.929722 actionrequired nothing dtype: object light 0 start : 0.023335899924859405 lightTimeOn 0.023335899924859405 key: a pressed: 1.0052269999869168 stop: 0.9297222999157384 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 light 0 start : 0.023335899924859405 lightTimeOn 0.023335899924859405 key: a pressed: 1.0052269999869168 stop: 0.9297222999157384 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 light 0 start : 0.023335899924859405 lightTimeOn 0.023335899924859405 key: a pressed: 1.0052269999869168 stop: 0.9297222999157384 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 2 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 2 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 2 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 2 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 2 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 2 0.023336 a 1.005227 0.11718 light 0 start : 0.023335899924859405 lightTimeOn 0.023335899924859405 key: a pressed: 1.0052269999869168 stop: 0.9297222999157384 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 2 0.023336 a 1.005227 0.11718 3 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 2 0.023336 a 1.005227 0.11718 3 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 2 0.023336 a 1.005227 0.11718 3 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 2 0.023336 a 1.005227 0.11718 3 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 2 0.023336 a 1.005227 0.11718 3 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 2 0.023336 a 1.005227 0.11718 3 0.023336 a 1.005227 0.11718 light 0 start : 0.023335899924859405 lightTimeOn 0.023335899924859405 key: a pressed: 1.0052269999869168 stop: 0.9297222999157384 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 2 0.023336 a 1.005227 0.11718 3 0.023336 a 1.005227 0.11718 4 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 2 0.023336 a 1.005227 0.11718 3 0.023336 a 1.005227 0.11718 4 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 2 0.023336 a 1.005227 0.11718 3 0.023336 a 1.005227 0.11718 4 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 2 0.023336 a 1.005227 0.11718 3 0.023336 a 1.005227 0.11718 4 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 2 0.023336 a 1.005227 0.11718 3 0.023336 a 1.005227 0.11718 4 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 2 0.023336 a 1.005227 0.11718 3 0.023336 a 1.005227 0.11718 4 0.023336 a 1.005227 0.11718 light 0 start : 0.023335899924859405 lightTimeOn 0.023335899924859405 key: a pressed: 1.0052269999869168 stop: 0.9297222999157384 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 2 0.023336 a 1.005227 0.11718 3 0.023336 a 1.005227 0.11718 4 0.023336 a 1.005227 0.11718 5 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 2 0.023336 a 1.005227 0.11718 3 0.023336 a 1.005227 0.11718 4 0.023336 a 1.005227 0.11718 5 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 2 0.023336 a 1.005227 0.11718 3 0.023336 a 1.005227 0.11718 4 0.023336 a 1.005227 0.11718 5 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 2 0.023336 a 1.005227 0.11718 3 0.023336 a 1.005227 0.11718 4 0.023336 a 1.005227 0.11718 5 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 2 0.023336 a 1.005227 0.11718 3 0.023336 a 1.005227 0.11718 4 0.023336 a 1.005227 0.11718 5 0.023336 a 1.005227 0.11718 lightON keyname keytime keydur 0 0.023336 a 1.005227 0.11718 1 0.023336 a 1.005227 0.11718 2 0.023336 a 1.005227 0.11718 3 0.023336 a 1.005227 0.11718 4 0.023336 a 1.005227 0.11718 5 0.023336 a 1.005227 0.11718 Traceback (most recent call last): File "C:\Users\melis\Google Drive (ethical.sun.laoshi@gmail.com)\Aïna\Project-MT\full (ugly).py", line 699, in <module> thislight = pd.Series([lightname, lightcolour, timeON, timeOFF, actionrequired],index=thislight.columns) File "C:\Program Files\PsychoPy3\lib\site-packages\pandas\core\generic.py", line 4372, in __getattr__ return object.__getattribute__(self, name) AttributeError: 'Series' object has no attribute 'columns' ##### Experiment ended. ##### |
Dependent dropdowns in React Redux Posted: 31 May 2021 07:54 AM PDT I have two dropdowns and one of them is dependent to other one. So basically, I have a watchMake dropdown and according to the value of this, I am getting modelMake list. So here how I dispatch my data for dropdown: const [inputs, setInputs] = useState({ watchMake: "", watchModel: "", }); const handleChange = (inputName) => (e) => { e.preventDefault(); setInputs({ ...inputs, [inputName]: e.target.value, }); }; useEffect(() => { dispatch(makeWatches()); dispatch(modelWatches(inputs.watchMake)); }, [dispatch, inputs]); And here are my dropdowns: <Form.Group controlId="watchMake"> <Form.Label className="form-subtitle" htmlFor="watchMake"> Watch Make </Form.Label> {makeLoading ? ( <LoadingBox></LoadingBox> ) : makeError ? ( <MessageBox variant="danger">{makeError}</MessageBox> ) : ( <Form.Control as="select" id="watchMake" defaultValue={inputs.watchMake} onChange={handleChange("watchMake")} required > {watchMakes.map((makes, index) => ( <option key={index}>{makes}</option> ))} </Form.Control> )} </Form.Group> <Form.Group controlId="watchModel"> <Form.Label className="form-subtitle" htmlFor="watchModel"> Watch Model </Form.Label> {modelLoading ? ( <LoadingBox></LoadingBox> ) : modelError ? ( <MessageBox variant="danger">{modelError}</MessageBox> ) : ( <Form.Control as="select" onChange={handleChange("watchModel")} required > {watchModels.map((models, index) => ( <option key={index}>{models}</option> ))} </Form.Control> )} </Form.Group> So a few days ago, I asked the same question because even though I can the watch make dropdown, there was nothing coming through the watch model dropdown. So in use effect, I added these dependencies: [dispatch, inputs] which was empty before and it started to work. So I am selecting watch make and models are coming right but the thing is I cannot change model. If you can help me about this I would be really glad. Thanks... |
get an unknown amount of numbers from the user and get the average of these numbers with using dynamically allocated memory to store the values Posted: 31 May 2021 07:55 AM PDT I need to write a code that gets an unknown amount of numbers from the user and get the average of these numbers with using dynamically allocated memory to store the values, but I could write it in C++ and it must be C.How can I convert it in C language? #include <bits/stdc++.h> using namespace std; int main() { int n; cout<<"Get the number of inputs"<<endl; cin>>n; // input total number of elements int* a = new int[n]; //creating a dynamic array for(int i=0;i<n;i++){ cin>>a[i]; } double* average=new double; for(int i=0;i<n;i++){ *average+=a[i]; //storing sum } *average=*average/n*1.0; // calculating average cout<<"average of all numbers is "<<*average<<endl; return 0; } This is all i can do,but it still doesn`t compile.there are two error at line 17 and 19.(I have to use dynamically allocated memory) #include <stdio.h> #include <math.h> int main() { int n,i; printf("Get the number of inputs:\n"); scanf("%d",&n); // input total number of elements int* a[n]; //creating a dynamic array for(i=0;i<n;i++) { scanf("%d",&a[i]); } double* average=malloc(double*); for(i=0;i<n;i++){ *average+=a[i]; //storing sum } *average=*average/n*1.0; // calculating average printf("average of all numbers is:%lf",average); return 0; } |
c++ opencv 2.4.9 imread then imwrite,color changed Posted: 31 May 2021 07:55 AM PDT #include<iostream> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> using namespace std; using namespace cv; int main() { Mat srcImage = imread(img_path, CV_LOAD_IMAGE_UNCHANGED); imwrite("./test.png", srcImage); return 0; } i read a image,then save to file.but the image color is changed.this is why?? this is my result image |
Exchanging list values in Python [closed] Posted: 31 May 2021 07:55 AM PDT I initially have two different lists: list1 = [0, 1, 2, 3, 4, 5, 6] list2 = [0, 3, 2, 5, 5, 5, 6] After some operations performed by the algorithm in question, list2 is modified as follows: list2_changed = [0, 3, 1, 5, 9, 5, 6] Now, I need to pass these changes to list1 like this: list1_changed = [0, 1, 1, 3, 9, 5, 6] Could someone help me do this in Python? |
How to use a while loop for multiple condition [closed] Posted: 31 May 2021 07:54 AM PDT A user wants you to write a program that prints all numbers from 1 to the inputted number that are either a multiplier of 3 or end with 3. Test Case Sample input 14 Sample output 3 6 9 12 13 import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner read = new Scanner(System.in); int number = read.nextInt(); while (1 < number) { System.out.println(number); ((number%10 == 3) || (number%3 == 0)); } } } |
How do I check if a ref cursor points to empty result set in postgres Posted: 31 May 2021 07:55 AM PDT How do i check if a ref cursor is pointing to an empty result set in postgres. I have set the ref cursor variable to null, but when i run a function that returns a ref cursor , it runs forever when result set is empty. Is this a postgres bug? Below is the code function_1 returns a ref cursor begin; select * from function_1(11::bigint) as result; fetch all from "test"; end; |
Cannot create deep level menu Posted: 31 May 2021 07:55 AM PDT I'm trying to create a deep level menu, so I have defined in my database this table structure: id | parent | menu_order 15 0 0 22 15 0 26 15 0 30 15 0 47 22 0 49 22 0 51 22 0 68 26 0 69 26 0 What am I tryng to achieve is generate the code that allow me to correctly set the menu_order column, in the example above the final result should be: id | parent | menu_order 15 0 0 22 15 1 26 15 5 30 15 8 47 22 2 49 22 3 51 22 4 68 26 6 69 26 7 The result is pretty simple to understand, essentially 22 have as parent 15 , so menu_order is 1 . The same concept is applied to the nested level of 22 , which are (47,49,51 ). Actually my code looks like this: <?php $posts = [ ['id' => 15, 'parent' => 0, 'menu_order' => 0], ['id' => 22, 'parent' => 15, 'menu_order' => 0], ['id' => 26, 'parent' => 15, 'menu_order' => 0], ['id' => 30, 'parent' => 15, 'menu_order' => 0], ['id' => 47, 'parent' => 22, 'menu_order' => 0], ['id' => 49, 'parent' => 22, 'menu_order' => 0], ['id' => 51, 'parent' => 22, 'menu_order' => 0], ['id' => 68, 'parent' => 26, 'menu_order' => 0], ['id' => 69, 'parent' => 26, 'menu_order' => 0], ]; $currOrder = -1; foreach ($posts as $key => $p) { $currOrder++; $test[] = [ 'id' => $p['id'], 'parent' => $p['parent'], 'menu_order' => $currOrder ]; hasChild($p['id'], $currOrder, $test); } function hasChild($postId, &$currOrder, $test) { // get childs post $childs = $this->where('parent', $postId) ->get() ->getResult(); foreach ($childs as $c) { $currOrder++; $test[] = [ 'id' => $c['id'], 'parent' => $c['parent'], 'menu_order' => $currOrder ]; // check nested levels if ($c->parent != 0) { hasChild($c['id'], $currOrder, $test); } } } the problem's that I get duplicated posts for the nested level and the menu_order is comopletely messed up. I guess I'm overcomplicating the logic, could someone help me to achieve this? Thanks |
mkdir within a loop Posted: 31 May 2021 07:55 AM PDT I am trying to create multiple directories on Python, one for each of the elements of the list loadcase_id_full defined simply by : [1, 2, 3, 4, 5]. I tried the following: import os import yaml from pathlib import Path this_dir = Path(__file__).parent top_dir = this_dir.parent base_dir = top_dir / 'tmp' with open(path_to_acc_matrix) as f: var = yaml.safe_load(f) # Extracting the data in lists of a size equal to the number of load cases (usually 5) loadcase_id_full = var['acceleration_matrix'][4] path_to_new_dirs = top_dir / 'templates' / 'tests' / 'data' path_iter = 1 path_iter = str(path_iter) pathname = 'QS-' + path_iter directory = path_to_new_dirs / pathname for index in loadcase_id_full : if not os.path.exists(directory): os.makedirs(directory) path_iter = index path_iter = str(path_iter) pathname = 'QS-' + path_iter directory = base_dir / pathname print(directory) This only creates the first directory (so from the "directory" variable defined outside of the loop...) The print function shows me that the paths I want are correct: /users/develop/tmp/QS-1 /users/develop/tmp/QS-2 /users/develop/tmp/QS-3 /users/develop/tmp/QS-4 /users/develop/tmp/QS-5 But it just doesn't create them. If I put the os.mkdirs at the end of the loop, it doesn't create any directories. Does anyone knows how to solve this? Thanks in advance for your help! :) |
Map an Array without using the last element of the Array Posted: 31 May 2021 07:55 AM PDT Is it possible to map an Array without using the last element of the Array and without creating a new Array to map. {array.map((arr, index) => { ... } )} So if the array was: { 'apple', 'bread', 'banana'} Only apple and bread would be mapped. Use case for this question is more because I was just wondering if it is possible. I know that there are solutions with slice and creating new Array that would be shorter but I just thought that it might be possible to solve this without mutating or creating new Array's |
Regex exclude whitespaces from a group to select only a number Posted: 31 May 2021 07:55 AM PDT I need to take only a number (a float number) from a text, but I can't remove the whitespaces... ** Update I have a problem with this method, I only need to consider numbers and ',' between '- EUR' and 'Fee' as rule. |
How to check if an item is displayed or even there in selenium? Posted: 31 May 2021 07:55 AM PDT I have a website that has anywhere from 3 to 4 images on it. If it tries to acquire the 4th image and it's not there the program blows up. I want to check if the fourth is there, and if it is I want to acquire it, if not I want to go on with the program. I want to do it without using try and except. I've tried .isDisplayed could not get it to work. This is the driver statement that acquires the image. Image3 = driver.find_element_by_xpath('//*[@id="goods_thumb_content"]/ul/li[3]').get_attribute("data-bigimg"); I'm using Selenium and here is the code: #This is the code when all four images are present. and when it's not the last <li> <l/> is not present. <ul> <li class="thumb_item active logsss_event_cl" data-isself="1" data- bigimg="https://gloimg.rglcdn.com/rosegal/pdm-product-pic/Clothing/2021/03/09/source- img/20210309165545_60473811b6a7c.jpg" data-zoomimg="https://gloimg.rglcdn.com/rosegal/pdm- product-pic/Clothing/2021/03/09/source-img/20210309165545_60473811b6a7c.jpg" data-logsss-const- value="{'x': 'change_pic'}" style="height: 131.6px;"> <img src="https://gloimg.rglcdn.com/rosegal/pdm-product-pic/Clothing/2021/03/09/grid- img/1618874299184494137.jpg?im_scale=w75_1x" alt="Plus Size Paisley Print Empire Waist Asymmetric Tank Top - "> </li> <li class="thumb_item logsss_event_cl" data-isself="1" data- bigimg="https://gloimg.rglcdn.com/rosegal/pdm-product-pic/Clothing/2021/03/09/source- img/20210309165545_60473811c9ce8.jpg" data-zoomimg="https://gloimg.rglcdn.com/rosegal/pdm- product-pic/Clothing/2021/03/09/source-img/20210309165545_60473811c9ce8.jpg" data-logsss-const- value="{'x': 'change_pic'}" style="height: 131.6px;"> <img src="https://gloimg.rglcdn.com/rosegal/pdm-product-pic/Clothing/2021/03/09thumb- img/1615251725078779977.jpg?im_scale=w75_1x" alt="Plus Size Paisley Print Empire Waist Asymmetric Tank Top - "> </li> <li class="thumb_item logsss_event_cl" data-isself="1" data- bigimg="https://gloimg.rglcdn.com/rosegal/pdm-product-pic/Clothing/2021/03/09/source- img/20210309165545_60473811df353.jpg" data-zoomimg="https://gloimg.rglcdn.com/rosegal/pdm- product-pic/Clothing/2021/03/09/source-img/20210309165545_60473811df353.jpg" data-logsss-const- value="{'x': 'change_pic'}" style="height: 131.6px;"> <img src="https://gloimg.rglcdn.com/rosegal/pdm-product-pic/Clothing/2021/03/09thumb- img/1615251725121900529.jpg?im_scale=w75_1x" alt="Plus Size Paisley Print Empire Waist Asymmetric Tank Top - "> </li> #The <li> below is not present when the fourth image is not there. <li class="thumb_item logsss_event_cl" data-isself="1" data- bigimg="https://gloimg.rglcdn.com/rosegal/pdm-product-pic/Clothing/2021/03/09/source- img/20210309165545_60473811f1542.jpg" data-zoomimg="https://gloimg.rglcdn.com/rosegal/pdm- product-pic/Clothing/2021/03/09/source-img/20210309165545_60473811f1542.jpg" data-logsss-const- value="{'x': 'change_pic'}" style="height: 131.6px;"> <img src="https://gloimg.rglcdn.com/rosegal/pdm-product-pic/Clothing/2021/03/09thumb- img/1615251725802705831.jpg?im_scale=w75_1x" alt="Plus Size Paisley Print Empire Waist Asymmetric Tank Top - "> </li> </ul> |
Raspi4 WIFI-Access-Point Full-Tunnel directly into Wireguard Posted: 31 May 2021 07:56 AM PDT I run a working Wireguard server with 2 Wireguard Gateways for Site-to-Site VPN and a couple of Mobile Devices with a Full Tunnel that are used occasionally. One of my Site Gateways is a RaspberryPi4 that I want to provide a WIFI-Access-Point that directly tunnels to the Wireguard Server. This RaspberryPi has working access to all connected subnets via the main Server, so Wireguard is setup properly. I want to use my Raspi4 to roam the world and provide me a WIFI-Access-Point while any device that connects to it is directly routed into Wireguard and emerges to the web only from there. I used the standard gateway setup provided and my WIFI device can access the web but doesn't tunnel through Wireguard (yet). I can't really find where I can configure where the access point is bound to, dnsmasq, apdconf or a simply iptables rule? Example IPs Server: 10.0.7.1, local network 192.168.0.1/24 Raspi4: 10.0.7.5, local network 192.168.6.5/24, WIFI 192.168.7.5/24 So far I haven't succeeded, ideas? |
I don't get a database file when running my SQLAlchemy code Posted: 31 May 2021 07:56 AM PDT I am trying to make a database in my flask project. When running this code I don't get any errors. But i'm supposed to get a .db file in my directory. Which I don't. Any ideas? :) from flask import Flask from flask_sqlalchemy import SQLAlchemy from os import path db = SQLAlchemy() DB_NAME = "database.db" def create_app(): app = Flask(__name__) app.config['SECRET_KEY'] = 'key123' app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}' db.init_app(app) return app def create_database(app): if not path.exists('website/' + DB_NAME): db.create_all(app=app) |
I am getting "PackageManagement\Install-Package : Access to the cloud file is denied" errors while installing Az module in power shell Posted: 31 May 2021 07:55 AM PDT I am trying to install Az module on windows power shell by "Install-Module -Name Az -Scope CurrentUser -Force -Allowclobber command". But i am getting below error. PS C:\WINDOWS\system32> Install-Module -Name Az -Scope CurrentUser -Force -Allowclobber PackageManagement\Install-Package : Access to the cloud file is denied At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\2.2.5\PSModule.psm1:9711 char:34 + ... talledPackages = PackageManagement\Install-Package @PSBoundParameters + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (Microsoft.Power....InstallPackage:InstallPackage) [Install-Package], Exception + FullyQualifiedErrorId : System.ComponentModel.Win32Exception,Microsoft.PowerShell.Commands.RemoveItemCommand,Microsoft.PowerShell.PackageManagement.Cmdlets.Instal lPackage I searched and found some issue is with onedrive sync activated in my system. Can you please help me on this to install Az module in powershell. |
The exception java.lang.NoSuchMethodError thrown when invoking Azure storage related java API Posted: 31 May 2021 07:56 AM PDT Leave thread here for others who might run into same issues. I'm trying to reading blob from Azure container by code below: public static void main(String[] args) { String connectStr = "it's a workable connection string..."; // Create a BlobServiceClient object which will be used to create a container client BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().connectionString(connectStr).buildClient(); String containerName = "eugenecontainer"; BlobContainerClient blobContainerClient = blobServiceClient.getBlobContainerClient(containerName); for (BlobItem blobItem: blobContainerClient.listBlobs()){ System.out.println(blobItem.getName()); } } However, when it executes blobContainerClient.listBlobs() , exception as following throws: Exception in thread "main" java.lang.NoSuchMethodError: io.netty.bootstrap.Bootstrap.config()Lio/netty/bootstrap/BootstrapConfig; I'm using maven as the build tool. What happens here? |
Color from hex string in jetpack compose Posted: 31 May 2021 07:55 AM PDT How to parse hex string e.g. #9CCC65 in Color class in jetpack compose. P.S: option seem to be missing in jetpack compose package Current Workaround: Exported parseColor() method from standard Color class. @ColorInt fun parseColor(@Size(min = 1) colorString: String): Int { if (colorString[0] == '#') { // Use a long to avoid rollovers on #ffXXXXXX var color = colorString.substring(1).toLong(16) if (colorString.length == 7) { // Set the alpha value color = color or -0x1000000 } else require(colorString.length == 9) { "Unknown color" } return color.toInt() } throw IllegalArgumentException("Unknown color") } |
Is there a difference in Async execution vs non-async execution in WebAPI ASP.NET Core controllers? Posted: 31 May 2021 07:55 AM PDT Is there a difference between calling a method of service with async/await: [HttpPost] public async Task<SmthResponce> AddSmth([FromBody] SmthRequest smthRequest) { return await smthsService.AddSmthAsync(smthRequest); } and without: [HttpPost] public Task<SmthResponce> AddSmth([FromBody] SmthRequest smthRequest) { return smthsService.AddSmthAsync(smthRequest); } |
Is is_constexpr possible in C++11? Posted: 31 May 2021 07:55 AM PDT Is it possible to produce a compile-time boolean value based on whether or not a C++11 expression is a constant expression (i.e. constexpr ) in C++11? A few questions on SO relate to this, but I don't see a straight answer anywhere. |
How to detect idle time in JavaScript elegantly Posted: 31 May 2021 07:57 AM PDT Is it possible to detect "idle" time in JavaScript? My primary use case probably would be to pre-fetch or preload content. Idle time: Period of user inactivity or without any CPU usage |
No comments:
Post a Comment