Background in ::before hides the content Posted: 19 Sep 2021 08:30 AM PDT Consider: <div class="auth-form-frame"> Some very long text </div> If I give a background color to .auth-form-frame::before , the text becomes invisible: @mixin pseudo-element-background { content: ""; background-size: cover; background-position: top; /* When resizing the window, the top of image stays attached to top */ position: absolute; top: 0px; right: 0px; bottom: 0px; left: 0px; } .auth-form-frame { position: relative; border-radius: 1rem; overflow: hidden; box-shadow: 0 2rem 4rem rgba(black, 0.4); width: 50rem; height: 25rem; color: #000; font-size: 10rem; &:before { @include pseudo-element-background; background-color: green; } > * { z-index: 100; } } The full example appears in jsbin. Why does this happen? How can I make the content visible despite the background color of the pseudo-element of <div> ? |
How to use one class attribute of a class as a type inside another class in pydantic? Posted: 19 Sep 2021 08:30 AM PDT from pydantic import BaseModel from typing import Optional class A(BaseModel): a: int b: Optional[str] c: bool = False class B(BaseModel): a: str b: Optional[str] c: #I want to add the attribute "c" from class A as a type here How do I use attribute "c" from class A as a type inside class B? |
How to get an email from a filled form using PHP script? Posted: 19 Sep 2021 08:30 AM PDT I'm trying to create a php script to send a filled form from a website to a specific email. I tried several ways but I don't get the email on my webmail. I also don't get any errors so I am not sure where the problem is. The files are in the same directory and the webmail seems to work well. I would be grateful for your input. This is email.php file: <?php $error = ""; $successMessage = ""; if ($_POST) { if (!$_POST["name"]) { $error .= "A name is required.<br>"; } if (!$_POST["email"]) { $error .= "An email address is required.<br>"; } if (!$_POST["choice"]) { $error .= "Select a trial session.<br>"; } if (!$_POST["date"]) { $error .= "Select a date.<br>"; } if ($_POST['email'] && filter_var($_POST["email"], FILTER_VALIDATE_EMAIL) === false) { $error .= "The email address is invalid.<br>"; } if ($error != "") { $error = '<div class="alert alert-danger" role="alert"><p>There were error(s) in your form:</p>' . $error . '</div>'; } else { $emailTo = "my@addressemail.com"; $subject = "trial session"; $name = $_POST['name']; $choice = $_POST['choice']; $date = $_POST['date']; $headers = "From: ".$_POST['email']; if (mail($emailTo, $subject, $name, $choice, $date, $headers)) { $successMessage = '<div class="alert alert-success" role="alert">Your message was sent, we\'ll get back to you ASAP!</div>'; } else { $error = '<div class="alert alert-danger" role="alert"><p><strong>Your message couldn\'t be sent - please try again later</div>'; } } } ?> <div class="container"> <h1>Get in touch!</h1> <div id="error"><? echo $error.$successMessage; ?></div> <form method="post" action="email.php"> <fieldset class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" id="name" name="name" > </fieldset> <fieldset class="form-group"> <label for="email">Email address</label> <input type="email" class="form-control" id="email" name="email" placeholder="Enter email"> <small class="text-muted">We'll never share your email with anyone else.</small> </fieldset> <div class="mb-3"> <div class="control-label" id="choice" name="choice">Which trial session you would like to book?</div> <select class="form-select" required aria-label="select example" id="choice" name="choice"> <option value="">I'm interested in...</option> <option value="1">option1</option> <option value="2">option2</option> </select> </div> <div class="form-group"> <!-- Date input --> <label class="control-label" for="date">Date</label> <input class="form-control" id="date" name="date" placeholder="MM/DD/YYY" type="text"/> </div> <button type="submit" id="submit" class="btn btn-primary">Submit</button> </form> </div> |
Flutter with Firebase Messaging. iOS device doesn't receive data only messages Posted: 19 Sep 2021 08:30 AM PDT I'm sending data-only message from Cloud functions I tried this solution: https://github.com/FirebaseExtended/flutterfire/issues/3395#issuecomment-683973108 Here are the option sendings from Cloud Functions: { android: { priority: "high", }, apns: { payload: { aps: { contentAvailable: true, }, }, headers: { "apns-push-type": "background", "apns-priority": "5", "apns-topic": "io.flutter.plugins.firebase.messaging", // bundle identifier }, }, } And here the code which handle messages. (I want to create a notification from the client not from the server) const AndroidNotificationChannel channel = AndroidNotificationChannel( 'high_importance_channel', 'High Importance Notifications', 'This channel is used for important notifications.', importance: Importance.max, ); class BackgroundHandler { static const IOSNotificationDetails iosNotificationDetails = IOSNotificationDetails(subtitle: 'notification'); static final AndroidNotificationDetails androidNotificationDetails = AndroidNotificationDetails(channel.id, channel.name, channel.description); } FirebaseMessaging.onMessage.listen((RemoteMessage message) { print('It works'); print(message); FlutterLocalNotificationsPlugin().show(0, 'notification', 'new notification', NotificationDetails(android: BackgroundHandler.androidNotificationDetails, iOS: BackgroundHandler.iosNotificationDetails)); NotificationManager.handleNotificationData(message.data); }); On Android it works perfectly and it works even with notification, but nothing happens with data only messages. |
how to make height of "main_body" div equal to it's parent div responsivly Posted: 19 Sep 2021 08:30 AM PDT if there is no long text in "main_body" div,height of "main_body" div is equal to it's parent.but if i put long text,the height of "main_body" div is not the same height as it's parent. html <body> <div class="main_body"> <div class="i_m_nothing"> </div> Hello, everyone! This is the LONGEST TEXT EVER! I was inspired by the various other "longest texts ever" on the internet, and I wanted to make my own. So here it is! This is going to be a WORLD RECORD! This is actually my third attempt at doing this. The first time, I didn't save it. The second time, the Neocities editor crashed. Now I'm writing this in Notepad, then copying it into the Neocities editor instead of typing it directly in the Neocities editor to avoid crashing. It sucks that my past two attempts are gone now. Those actually got pretty long. Not the longest, but still pretty long. I hope this one won't get lost somehow. Anyways, let's talk about WAFFLES! I like waffles. Waffles are cool. Waffles is a funny word. There's a Teen Titans Go episode called "Waffles" where the word "Waffles" is said a hundred-something times. It's pretty annoying. There's also a Teen Titans Go episode about Pig Latin. Don't know what Pig Latin is? It's a language where you take all the consonants before the first vowel, move them to the end, and add '-ay' to the end. If the word begins with a vowel, you just add '-way' to the end. For example, "Waffles" becomes "Afflesway". I've been speaking Pig Latin fluently since the fourth grade, so it surprised me when I saw the episode for the first time. I speak Pig Latin with my sister sometimes. It's pretty fun. I like speaking it in public so that everyone around us gets confused. That's never actually happened before, but if it ever does, 'twill be pretty funny. By the way, "'twill" is a word I invented recently, and it's a contraction of "it will". I really hope it gains popularity in the near future, because "'twill" is WAY more fun than saying "it'll". "It'll" is too boring. Nobody likes boring. This is nowhere near being the longest text ever, but eventually it will be! I might still be writing this a decade later, who knows? But right now, it's not very long. But I'll just keep writing until it is the longest! Have you ever heard the song "Dau Dau" by Awesome Scampis? It's an amazing song. Look it up on YouTube! I play that song all the time around my sister! It drives her crazy, and I love it. Another way I like driving my sister crazy is by speaking my own made up language to her. She hates the languages I make! The only language that we both speak besides English is Pig Latin. I think you already knew that. Whatever. I think I'm gonna go for now. Bye! Hi, I'm back </div> </body> CSS .html,body { height: 100%; background-color:blue; margin: 0; } .main_body { height: 100%; background: yellow; } .i_m_nothing{ height:50%; width:50%; background-color:red; } |
Make a find prime number function in javascript Posted: 19 Sep 2021 08:29 AM PDT Make a find prime number function in javascript. I want to let it display the values to textarea whenever it finds a prime number. However, it will only show the result when the function is fully executed. Here is my code: let start = performance.now() let textarea = document.querySelector('textarea') let time = document.getElementById('time') let texts = document.getElementById('texts') let amount = document.getElementById('amount') let status = document.getElementById('status') let logs = []; let number = 0 let prime = []; function check(){ status.textContent = 'processing' amount.textContent = 'processing' time.textContent = 'processing' textarea.textContent =logs setTimeout(function(){reallycheckprimenumber()},0) } function reallycheckprimenumber(){ number = 0; let start = performance.now() let value = texts.value if(value ==''){ value = texts.placeholder; } for (var i = 0;i<value;i++){ time.textContent = '' amount.textContent = '' var nums = 2; for (let x = 0;x<=i/2;x++){ if(nums>3){ break; } if(i!==0 && i!==1 && i !== x){ if(i%x === 0){ nums++; } } } if(nums === 3){ prime.push(i) textarea.textContent += prime number +=1 } if(i === value-1){ status.textContent = 'done' let end = performance.now() time.textContent = (end-start).toFixed(5) +'ms' amount.textContent = number } } } check() <h1>Get Prime number application:</h1> <h2>Prime Number: <span></span></h2> <h3 >Processing Time: <span id = 'time'>0 ms</span></h3> <h3>Number: <span id = 'amount'>0</span></h3> <h3>Status: <span id = 'status'>Processing</span></h3> <label for = 'texts'>Enter the range you want to get number from</label> <input type = 'text' id = 'texts' placeholder = '100'> <input type = 'button' id = 'button' value = 'set' onclick = 'check()'> <textarea readonly></textarea> I have tried several ways to make the application displays prime number while it is finding other prime number. However, I failed. I found that only console will work. I really have no idea on how to solve this problem. Anyone have an idea and know how to solve it? Thanks so much for any helps and supports |
Algorithm wont pass test sets Posted: 19 Sep 2021 08:29 AM PDT Very new to coding competition format and could use some assistance if possible. I have ran several different testing on my solution and it gives the right answer for my test input, however when I submit my answer, I get the Samples correct, however I just get a "WA" for test set 1 and test set 2 is skipped. I am unsure of what other types of test cases I can test in my debugging to find the problem. I'm sure the code can be crazy optimized, I'm just looking for some constructive criticism to better understand where I can improve. Kick start problem info link https://codingcompetitions.withgoogle.com/kickstart/round/0000000000435bae/0000000000887c32 Here is my current solution: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Solution { static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader( new InputStreamReader(System.in)); } String next(){ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next());} long nextLong(){ return Long.parseLong(next());} double nextDouble(){ return Double.parseDouble(next());} String nextLine(){ String str = ""; try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader s = new FastReader(); int testCases, numberOfHouses; String houseLineup = ""; StringBuilder finalResult= new StringBuilder(); testCases = s.nextInt(); for(int i = 1;i<=testCases;i++){ numberOfHouses = s.nextInt(); houseLineup = s.nextLine(); finalResult.append( calcResult(numberOfHouses, houseLineup, i, testCases)); } System.out.print(finalResult); } private static String calcResult(int numberOfHouses, String houseLineup, int testCase, int totalTestCases) { String addToResult = "Case #"+testCase+": "; int total=0; int tempTotal = 0; int count = 0; int placeHolder = 0; boolean foundANumberOne = false; for(int i = 0;i<numberOfHouses;i++){ if((houseLineup.charAt(i))=='1'){ foundANumberOne = true; total+=tempTotal; tempTotal=0; count = 0; placeHolder = i; } else{ if(!foundANumberOne){ count++; tempTotal+=count; } else{ String temp = houseLineup.substring(i); int temp1 = temp.indexOf('1'); if(temp1==-1){ total+=((temp.length()*(temp.length()+1))/2); break; } else{ int highOne, lowOne, currentPlace; lowOne = placeHolder; String subHouseLineup = houseLineup.substring(i); highOne = subHouseLineup.indexOf('1'); highOne+=(houseLineup.length()-subHouseLineup.length()); currentPlace = i; if((currentPlace-lowOne)>(highOne-currentPlace)){ total+=tempTotal; tempTotal=0; count=1; tempTotal++; } else{ count++; tempTotal+=count; } } } } } if(totalTestCases==testCase) addToResult+= total; else addToResult+= total +"\n"; return addToResult; } } Here is my Sample test data cases that I have tried so far that are correct. 6 3 111 6 100100 5 10001 10 1010101010 5 00001 5 10000 Along with the sample test output for the corresponding test sets I have debugged. Case #1: 0 Case #2: 5 Case #3: 4 Case #4: 5 Case #5: 10 Case #6: 10 |
Deploying docker image as IBM Cloud Action with credentials Posted: 19 Sep 2021 08:29 AM PDT I have a small NodeJS app I want to deploy to IBM Cloud as an "action". What I've been doing until now is just zipping the project files and creating/updating actions using the IBM Cloud CLI like this: ibmcloud fn action create project-name C:\Users\myuser\Desktop\node-js-projects\some-project\test-folder.zip --kind nodejs:12 This was working great, however I'm now testing a new project which has a much larger modules folder, and as such IBMCloud won't accept it. I've turned my attention to using Docker as the below article explains. https://medium.com/weekly-webtips/adding-extra-npm-modules-to-ibm-cloud-functions-with-docker-fabacd5d52f1 Everything makes sense, however I have no idea what to do with the credentials that the app uses. Since IBM Cloud seems to require you to run "docker push" I'm assuming it's not safe to include a .env file in the docker image? I know in IBM Cloud I can pass "parameters" to an action but not sure if that helps here. Can those params be accessed from a piece of code deployed this way? Would really appreciate some help on this one. Hoping there's a straightforward standard way of doing it that I've just missed. I'm brand new to docker so still learning. |
Manage Virtualbox VMs from inside a guest VM Posted: 19 Sep 2021 08:29 AM PDT My application comes with a sort of plugin architecture, where each plugin needs to run inside its own VM. There are multiple reasons for that, but to give an example: Each plugin can choose the OS it will be running on. The main application comes with a control interface where plugins can be added, removed, loaded, stopped. That means that it should be possible to spin up new VMs dynamically. The main application runs in a guest VM itself (again, for various reasons. Ressource management being the most important here). What I would like to do is spin up new VMs (and stop running VMs when requested to do so) on the host (because of the dynamic nature of the plugins it would be impossible to properly provision the main application VM). Virtualbox is used as the virtualization software here. The host operating system is Linux. I wonder if VBox exposes some sort of a network API where I could interact with the manager? |
Mumbai Network Tokens are not being listed as "created by `you`" in testnet.opensea.io Posted: 19 Sep 2021 08:29 AM PDT Here is an example tokens description part of a contract in Mumbai network. And below you see the description part of that exact same contract in Rinkeby network. Due to this issue I can not delete the collection that I created. I event sent a support ticket to opensea.io about the problem, they simply said that "they are fixing bugs." which literally doesn't help me at all. |
Laravel extension update problem (VS Code) (solved) Posted: 19 Sep 2021 08:29 AM PDT This is not a question I'm putting this here so it might help someone who has problem like i do. this happens to me for 1 hours ago and i think its my VS Code broken. and the last part i do the windows 10 re-install I'm working with VS Code on windows, with laravel extension pack for my weapon. About 1 hour ago, 1 of my extension auto update and broke some function like ctrl click on my .php after re-install windows and completly fresh install vs code, the problem still exists, so i make my deep research, and found that this extension auto update 1 hour ago. solve this by downgrading to previous version, hopefully they fix it latter. i know this is not a question, just want to help bunch of coders mate if we have same situation. i will delete this question after next update of the extension. |
Blazor WASM: Unhandled exception Object of type T has a property matching the name, but it does not have [ParameterAttribute] applied Posted: 19 Sep 2021 08:29 AM PDT I'm a bit stumped here because I do have the parameter attribute applied. I seem to be simply following the documentation in a one to one fashion. Error message Unhandled exception rendering component: Object of type 'Onero.Client.Features.CourseManager.CourseModelRegister' has a property matching the name 'HighSchoolRegistrationModelId', but it does not have [ParameterAttribute] applied. Component hierarchy //parent <CascadingValue Value="HighSchoolRegistrationModelId"> <CourseModelAddForm></CourseModelAddForm> </CascadingValue> @code { public long HighSchoolRegistrationModelId; protected override async Task OnInitializedAsync() { await base.OnInitializedAsync(); HighSchoolRegistrationModelId = await CourseService.GetHighSchool(); } } //middle component @if (add) { <CourseModelRegister HighSchoolRegistrationModelId="@HighSchoolRegistrationModelId"> </CourseModelRegister> } @code { [CascadingParameter] protected long HighSchoolRegistrationModelId { get; set; } private bool add = false; protected override async Task OnParametersSetAsync() { await base.OnParametersSetAsync(); } private void ShowAddForm() { add = true; } } //Grandchild where error occurs @code { [CascadingParameter] protected long HighSchoolRegistrationModelId { get; set; } // rest of code omitted } Am I missing something? Perhaps this has to do with lifecycle management? I tried using OnInitialized as well as OnParametersSet. |
How to allocate pointers inside nested structs in C++ Posted: 19 Sep 2021 08:30 AM PDT Okay, let's try this again. I have to allocate a pointer which is a member of a nested struct: it works inside a function, but it doesn't seem to be allocated when I exit the function where I allocate it. Since people have been asking for minimal reproducible examples, here you go, this should do it: #include <iostream> #include <fstream> #include <string> #include <iomanip> using namespace std; typedef struct HEADER { int16_t VERSION; int16_t BITS_PER_CHAR; char TABL[4]; int32_t TABL_BLOCKSIZE; }HEADER; typedef struct TKEY_CRC { int32_t ENTRYOFFSET; int32_t CRC32VAL; }TKEY_CRC; typedef struct TDAT { char TDAT_VAL[5] = { 0 }; int32_t TDAT_BLOCKSIZE; }TDAT; typedef struct TKEY { char TKEY_VAL[5] = { 0 }; int32_t TKEY_BLOCKSIZE; TKEY_CRC* PREHEADER; TDAT ENTRY_TDAT; }TKEY; typedef struct TABLE_ENTRY { char SUBTABLE_NAME[9] = { 0 }; int32_t TKEY_OFFSET = 0; TKEY ENTRY_TKEY; }TABLE_ENTRY; void minimal_reproducible_example(HEADER*& h, TABLE_ENTRY*& t) { h = new HEADER; t = new TABLE_ENTRY[200]; for (int i = 0; i < 200; i++) t[i].ENTRY_TKEY.PREHEADER = new TKEY_CRC[40]; // THIS IS WHERE I HAVE THE PROBLEM, IT DOESN'T GET ALLOCATED OUTSIDE OF minimal_reproducible_example return; } int main() { HEADER* head; TABLE_ENTRY* table; minimal_reproducible_example(head, table); // HERE table.ENTRY_TKEY.PREHEADER[i], where i is between 0 and 200, isn't allocated. } How can I fix this so that the PREHEADER member of the ENTRY_TKEY member of the TABLE_ENTRY t gets allocated properly inside the function? P.S.: if you need something added to the example because it isn't enough for you, ask what you need, don't downvote the question. It doesn't help nobody. |
Unhandled Rejection (TypeError): getNotes is not a function in react? Posted: 19 Sep 2021 08:30 AM PDT i'm learning react so i created a simple application to manage notes with a title and a description. I create a getNotes function in Note.js file and i passed the getNotes function to NoteForm and NoteList component. getNotes is working fine in NoteForm component but it is not working in NoteList component. getNotes() function is used to update the list of Notes. please tell me why getNotes() function is not working in NoteList Note.js function Notes() { const [notes, setNotes] = useState([]); const getNotes = async () => { const notesRes = await axios.get("http://localhost:5000/notes/"); setNotes(notesRes.data); console.log(notes); } useEffect(() => { getNotes(); }, []); return ( <div> <NoteForm getNotes={getNotes} /> <NoteList notes={notes} getNotes = {getNotes}/> </div> ); } export default Notes; Noteform.js function NoteForm({ getNotes }) { const [Title, setTitle] = useState(""); const [description, setDesc] = useState(""); async function saveNote(e) { e.preventDefault(); try { const noteData = { title: Title, desc: description, }; await axios.post("http://localhost:5000/notes/", noteData); getNotes(); setTitle(''); setDesc(''); } catch (err) { console.error(err); } } return (...); } export default NoteForm; NoteList.js function NoteList({notes}, {getNotes}) { //------------Delete----------- async function delNote (id) { await axios.delete(`http://localhost:5000/notes/${id}`); getNotes(); } //------------Update----------- const [open, setOpen] = React.useState(false); const [UpdateTitle, setUpdateTitle] = useState(""); const [UpdateDescription, setUpdateDescription] = useState(""); const handleClickOpen = (title, desc) => { setUpdateTitle(title); setUpdateDescription(desc); setOpen(true); }; async function updateNote(id, updatetitle, updatedesc ) { const res = await axios.put("http://localhost:5000/notes/", {id, updatetitle, updatedesc}); handleClose(); getNotes(); } const handleClose = () => { setOpen(false); }; // --------------------------- function renderNotes() { return notes.map((note, i) => { return <div style={{ display:"inline-block",borderStyle: "ridge", padding:"20px", borderEndStartRadius: "50px", borderBlockEndColor:"yellowgreen", borderStartEndRadius:"50px", margin:"10px" }} key={i}> <b>Title: </b> {note.title} <br/> <b>Description: </b> {note.desc} <br/> <button onClick = {()=> delNote(note._id) } >Delete</button> <div> <Button variant="contained" style = {{ marginTop: "10px" , padding: "0.5px"}} onClick={()=>handleClickOpen(note.title, note.desc)}> Edit </Button> <Dialog open={open} onClose={handleClose}> <DialogTitle>Update Your Note</DialogTitle> <DialogContent> {/* <DialogContentText> To subscribe to this website, please enter your email address here. We will send updates occasionally. </DialogContentText> */} <TextField autoFocus margin="dense" id="name" onChange={(e) => { setUpdateTitle(e.target.value); }} value = {UpdateTitle} label="Title" fullWidth variant="standard" /> <TextField autoFocus margin="dense" id="name" onChange={(e) => { setUpdateDescription(e.target.value); }} value = {UpdateDescription} label="Description" type="email" fullWidth variant="standard" /> </DialogContent> <DialogActions> <Button onClick={handleClose}>Cancel</Button> <Button onClick={()=> updateNote(note._id, UpdateTitle, UpdateDescription )}>Update</Button> </DialogActions> </Dialog> </div> </div>; }).reverse(); } return ( <div> <div > {renderNotes()} </div> </div> ); } export default NoteList; |
PostgreSQL idempotent Policy row level se Posted: 19 Sep 2021 08:30 AM PDT In SQL you can perform a CREATE TABLE IF NOT EXISTS table_name (... table definition); which allows you to run the same SQL multiple times without it erroring. With policies you use: CREATE policy "Users can read their own profile" on user_profiles for insert with check ( auth.uid() = user_id ); However running this command more than once will result in an error like: policy "Users can read their own profile" for table "user_profiles" already exists From the docs, conditional policy creation does not seem to be an option. Is there any way around this? Note there is a previous question which claims that there is already a idempotent policy creation. I would argue this is not the case. Running drop policy if exists "Users can read their own profile" on user_profiles; followed by the create seems error prone unless it's possible to perform this inside a transaction which I don't know if that's possible. i.e. if your script partially ran it would leave your application without a policy applied after it previously had been applied. |
python upload large files - Error: Message 413 Request Entity Too Large - ignores 100-continue Posted: 19 Sep 2021 08:30 AM PDT I've written this code to upload files to 3rd. party ResApi server. The code works as expected for small files, but as soon as I try to upload files larger than 100MB then fails. Here is my code and error below: import sys, os from requests import Request, Session from requests.adapters import HTTPAdapter from requests.packages.urllib3.poolmanager import PoolManager from requests_toolbelt.multipart.encoder import MultipartEncoder import ssl from subprocess import * class SSLAdapter(HTTPAdapter): '''An HTTPS Transport Adapter that uses an arbitrary SSL version.''' def __init__(self, ssl_version=None, **kwargs): self.ssl_version = ssl_version super(SSLAdapter, self).__init__(**kwargs) def init_poolmanager(self, connections, maxsize, block=False): self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block, ssl_version=self.ssl_version) class FileBoxRequest: def __init__(self): self.ca_file='trustedca.pem' self.cert_file='TECHUSER.cer' self.key_file='TECHUSER.key' def sendFile(self, my1GBFile): self.base_url = 'https://myserver.com/fileBoxServer/api/ssl/files/upload'; s = Session() #s.headers.update({'Expect': '100-continue'}) s.mount('https://', SSLAdapter(ssl.PROTOCOL_TLSv1_2)) multipart_data = MultipartEncoder(fields={ 'file': ('my1GBFile.txt', open(my1GBFile, 'rb'), 'text/plain') } ) #req = Request('POST', self.base_url, data=multipart_data,headers={'Content-Type': multipart_data.content_type,'Accept': 'application/json','Expect': '100-continue'}) req = Request('POST', self.base_url, data=multipart_data,headers={'Content-Type': multipart_data.content_type,'Accept': 'application/json'}) prepped = req.prepare() print('Sending filebox...') r = s.send(prepped, verify=self.ca_file, cert=(self.cert_file, self.key_file), timeout=54000 #90 minutes ) if r.ok: cookies = dict(r.cookies) print("cookies: ", cookies) else: print("Error: HTTP %i - %s, Message %s" % (r.status_code, r.reason, r.text)) Message: HTTP 413 - Request Entity Too Large. The requested resource /fileBoxServer/api/ssl/files/upload does not allow request data with POST requests, or the amount of data provided in the request exceeds the capacity limit. Checking with the engineering team of the RES API suggested to add header={'Expect': '100-continue'} to the request. But as soon as I add this header I get this error: File "../scripts\FileBoxRequest.py", line 79, in sendFile r = s.send(prepped, File "C:\ProgramData\Miniconda3\envs\jup385\lib\site-packages\requests\sessions.py", line 655, in send r = adapter.send(request, **kwargs) File "C:\ProgramData\Miniconda3\envs\jup385\lib\site-packages\requests\adapters.py", line 498, in send raise ConnectionError(err, request=request) ConnectionError: ('Connection aborted.', ConnectionAbortedError(10053, 'An established connection was aborted by the software in your host machine', None, 10053, None)) Adding the header to the session is seems to be ignored: s.headers.update({'Expect': '100-continue'}) **This is python version:** Python version 3.8.5 (default, Sep 3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)] Version info. sys.version_info(major=3, minor=8, micro=5, releaselevel='final', serial=0) I am sure, the problem is in my code of python client side, because I replicated this code perl and in DotNet C#, added the header 'Expect': '100-continue' , in both scripts I upload files larger than 1GB successfully. #Perl: ... my $file_path = "OneGbFile.txt"; my $url = 'https://myserver.com/fileBoxServer/api/ssl/files/upload'; my $res = $ua->post($url, Content_Type => 'multipart/form-data', Accept => 'application/json', Expect => '100-continue' Content => [ file => [$file_path], ], ); //DotNet ... using (var handler = new HttpClientHandler()) { X509Certificate2 certificate = new X509Certificate2(certPath); handler.ClientCertificates.Clear(); handler.ClientCertificates.Add(certificate); handler.SslProtocols = SslProtocols.Tls12; handler.ClientCertificateOptions = ClientCertificateOption.Manual; using (var client = new HttpClient(handler)) { client.Timeout = TimeSpan.FromMinutes(60); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("Expect", "100-continue"); using (var formData = new MultipartFormDataContent()) { formData.Add(new StreamContent(fileInfo.OpenRead()), "file", fileInfo.Name); //string result = client.PostAsync("fileBoxServer/api/ssl/files/upload", formData).Result.Content.ReadAsStringAsync().Result; string result = client.PostAsync(base_url, formData).Result.Content.ReadAsStringAsync().Result; LogWriter(string.Format("Result: {0}", result)); } } } An option could be so send the data by chunks, but apparently the ResApi service I am calling does not support this option. Any help or suggestion is very welcome. |
Java Class Diagrams Posted: 19 Sep 2021 08:28 AM PDT I have a Interface in my project like, public interface TraOp{ } Now in class A I use this interface as argument in constructor like, class A implements B{ private long var1; A(TraOp obj){} } Can someone let me know how this will be presented in class diagram. |
mypy: found module but no type hints or library stubs (not 3rd party lib) Posted: 19 Sep 2021 08:29 AM PDT I've got a project, type hints in modules. ├── src │ ├── damastes │ │ ├── __init__.py │ │ ├── main.py │ ├── __init__.py │ ├── procrustes │ │ ├── __init__.py │ │ └── run.py └── tests ├── __init__.py └── test_procrustes.py src/procrustes/__init__.py : from .run import * src/damastes/main.py : from src.procrustes import run is OK, from mypy's point of view. More proper import from procrustes import run # type: ignore requires ignore. The same with tests/test_procrustes.py : it's either from procrustes import * # type: ignore or from src.procrustes import * Why mypy can't see type hints without qualified import? If the module is found, what prevents mypy from analyzing it? error: Skipping analyzing 'procrustes': found module but no type hints or library stubs I tried adding py.typed to the procrustes directory. No difference. |
Upgrading @angular/fire from 6.x to 7.x Posted: 19 Sep 2021 08:30 AM PDT I'm trying to upgrade my app dependencies and my code from @angular/fire 6.x to 7.1.0-rc4 (because I need a feature that is not present in 7.0.x) so I edited my package.json and specified: "@angular/fire": "~7.1.0-rc.4", "firebase": "^9.0.0", then I changed my imports from: import { AngularFirestore } from '@angular/fire'; to import { AngularFirestore } from '@angular/fire/compat'; My app is a Ionic5/Angular12 app, so I assume it uses Ivy by default. Looking here, it seems to me I've done everything that was needed to upgrade. However I get the following compilation error: Module '"@angular/fire/compat"' has no exported member 'AngularFirestore'.ts(2305) import AngularFirestore What am I missing? |
Python sum pairs from text file Posted: 19 Sep 2021 08:30 AM PDT I am given a sorted array of positive integers and a number X and I need to print out all pairs of numbers whose sum is equal to X. Print out only unique pairs and the pairs should be in ascending order. However the program needs to read lines of text from standard input where each line contains a comma separated list of sorted numbers, followed by a semicolon, followed by the integer X. e.g. test input:1,2,3,4,6;5 output: 1,4;2,3 I have tried list1 = [] for line in sys.stdin: for n in line: list1.append(n) strlist = [ x for x in list1 if x.isdigit() ] numlist = list(map(int, strlist)) sum = numlist[-1] res = [] while numlist: num = numlist.pop() diff = sum - num if diff in numlist: res.append((diff, num)) res.reverse() print(res, end="") But i get Test Input: 1,2,3,4,6;5 Expected Output: 1,4;2,3 My Output: [(2, 3), (1, 4)] |
Interval scheduling Posted: 19 Sep 2021 08:29 AM PDT Suppose we need always two nurses in a hospital during the period [1, t]. We have n nurses (n1, n2, …, n). The nurses give the hospital their availability time Ex: Nurse k gives {start_k, end_k}. We have also an integer number I. Question Is their two groups of nurses G1, G2 so that |G1| <= I |G2| <= I and for each moment during [1, t] there are at least two nurses one from group1 and one from group2 available. Note: we can let the nurse leave or enter whenever we think it gives a better result (considering their availability time). Sample IO Input: nurses_availability: [ {1, 5}, {1, 6}, {5, 6}, {8, 10}, {6, 10}, {6, 8}, {7, 10} ] I = 3 t = 10 Solution: G1 = [ {1, 5}, {6, 10} ] G2 = [ {1, 6}, {6, 8}, {7, 10}] |
How to extract data within a tag attribute, dynamic page? Posted: 19 Sep 2021 08:29 AM PDT <app-local-insights-poi id="facilities" @section-loaded="updateNavigation" :latitude="52.5725587366925" :longitude="4.79693685890163" icon-base-url="https://assets.loco.net/abc/123" area-type="coord-123" class="border-light-2 border-solid border-0 border-b py-6 bg-white mt-6 md:mt-0"></app-local-insights-poi> How can I use Scrapy to extract the long and lat data? |
Terraform - Adding exceptions to ignore_changes Posted: 19 Sep 2021 08:29 AM PDT I currently have a module which contains a block with many configurable properties resource "example_resource" "instance1" { block1 { property1 = var.variable1 # Should generate a diff if changed property2 = var.variable2 # Ignore property3 = var.variable3 # Ignore .... .... propertyN = var.variableN # Ignore } lifecycle { ignore_changes = [ block1[0].property2, block1[0].property3, ... ,block1[0].propertyN ] } } Once the resource has been generated many of the properties within block1 are likely to change due to interaction with the user. I want to ignore such changes when running a terraform plan apart from a few exceptions which should generate a difference if changed in the future. (For example in the above resource if property1 is changed it should generate a diff but not for the others) Ignoring such changes can be done using the ignore_changes within lifecycle block. But it seems like to do the above. Adding the entire block1 argument to this will cause all changes within to be ignored, or we have to add all ignored properties within the block one by one to the ignore_changes block as I have mentioned in the example. Manually doing as such makes things a bit harder to maintain, as you will have to keep adding/removing new properties as a new property is added/removed to the block. So is it possible to configure the ignore_changes block to ignore all changes and specifically add the required exceptions? P.S. I do not believe this question is specific to a certain resource, But the resource I am trying to implement this concept to is the Azure App Service Resource, specifically to the site_config block within it. |
Spaces in a CSV file are discarded by CSV Serde in Redshift spectrum tables Posted: 19 Sep 2021 08:29 AM PDT My CSV file looks like "col1","col2","col3" "1","ab","2 " "2","xy"," " I have created an external table on top of it with all fields as varchar and the properties as below: ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde' STORED AS textfile LOCATION 's3://bucketname/foldername' TABLE PROPERTIES ('skip.header.line.count'='1','serialization.null.format'='') However, this reads my file as below. i.e. without spaces in the 3rd column in 1st row and null in the 3rd column of the 2nd row. 1->ab->2 2->xy->null Even if i remove the serilization property, i am not getting the desired two blank spaces in the 2nd row. Is this a limitation in the sense that CSV Serde discards the blankspaces or is there a workaround to achieve this? Thanks to Bill, I have tried few Regex to parse this: WITH SERDEPROPERTIES ('input.regex'='\"(.*)\",\"(.*)\",\"(.*)\"') or WITH SERDEPROPERTIES ('input.regex'='"(.*)","(.*)","(.*)"') With the above the fields are getting trimmed by 1 digit at the end. So, I moved the double quote inside the brackets as below and even tried using the escape char ('input.regex'='(".*"),(".*"),(".*")') or ('input.regex'='(\".*\"),(\".*\"),(\".*\")') "1" "ab" "2 " "2" "xy" " " Now everything is coming as it, the blank spaces, lagging spaces but now the double quotes are also coming as part of data. Funny thing is, if i keep the escape char in only the first column, then that field is enclosed in " even in o/p but the other fields comes clean. ('input.regex'='(\".*\"),(".*"),(".*")') "1" ab 2 "2" xy blankspace |
Using key value pair assignments for a dictionary as an iterator in a for loop Posted: 19 Sep 2021 08:29 AM PDT I just recently came across this cool hack in Python. This: d = {} for i, d[i] in enumerate('abc'): pass >>> d {0: 'a', 1: 'b', 2: 'c'} >>> This assigns key value pairs to a empty dictionary from the iterator. I would like to know how Cython backend parses this, my expectation is that it's being parsed with unpacking assignment. But it would be nice to know the actual Cython implementation of this, and also if doing this is recommended or not? I know I just can simply do: d = {} for i, v in enumerate('abc'): d[i] = v But the cool hack above can do this with shorter code, but I am not sure if it is considered good practice in Python. I never seen anybody use this... |
How to integrate google map in automotive apps in android? Posted: 19 Sep 2021 08:29 AM PDT I integrated google map into our android application. If I run the app in the Nexus 5X emulator it loading fine; no issue is observed. When I run the same app in the android automotive emulator..once the application is launched and showing as a google play services are updating but at the same time map not loading. Can anyone tell me what is the issue? Is it possible to integrate google maps into the automotive platform? below is my code public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; private ActivityMapsBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityMapsBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; // Add a marker in Sydney and move the camera LatLng sydney = new LatLng(-34, 151); mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney")); mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); } } |
Using IPython with the prompt-toolkit module - add toolbar at the bottom of IPython's terminal Posted: 19 Sep 2021 08:29 AM PDT prompt_toolkit is great to implementing own CLI. It contains a really nice feature from my perspective, a toolbar which displays at the bottom of the console and may be refreshed on regular time interval. In my application I need to embed Python console and user can execute function from imported modules but is also able to write Python syntax and execute it. That's really nice and that's something I miss in prompt_toolkit. Is it possible to combine those two? I mean to have a toolbar at the bottom of the IPython's console? |
Pandas: Select rows whose dictionary contains a specific value Posted: 19 Sep 2021 08:29 AM PDT I have a dataframe, in which one column contain a dictionaries for every row. I want to select rows whose dictionary contains a specific value. Doesn't matter which key contains it. The dictionaries have many levels (they contain a lot of lists, with a lot of dictionaries, again with a lot of lists and so on). The data could look similar to this, but with the dictionaries being more complex: df = pd.DataFrame({"A": [1,2,3], "B": [{"a":1}, {"b":**specific_value**}, {"c":3}]}) A B 0 1 {'a': 1} 1 2 {'b': 2} 2 3 {'c': 3} I tried: df.B.apply(lambda x : 'specific_value' in x.values()) To which I get "false" even the rows that I know contain the 'specific_value'. I am unsure if it is because of the layers. |
Make video autoplay using React Posted: 19 Sep 2021 08:30 AM PDT I am trying to make my video autoplay using react. adding autoplay=1 as a parameter doesn't work. Any suggestions?` Here is my code. <div className="video mt-5" style={{ position: "relative", paddingBottom: "56.25%" /* 16:9 */, paddingTop: 25, height: 0 }} > <iframe style={{ position: "absolute", top: 0, left: 0, width: "100%", height: "100%" }} src={'https://www.youtube.com/embed/hEnr6Ewpu_U?'} frameBorder="0" /> </div> |
how i can add telegram.ext class in visual studio Posted: 19 Sep 2021 08:29 AM PDT I want create a bot but I cant import class of telegram.ext I guess I did not install the necessary stuff I install python Environments anaconda 5.3.0 , python 3.7 64-bit and 32-bit , python 3.6 64-bit But I did not answer my code I will easily do this in pycharm but in vs :( |
No comments:
Post a Comment