By wonseok on Jun 04, 2021 04:02 am I am a developer who uses php, css, and html. Android, ios, all through react-native. I'm trying to make it work. Q. Files worked with css Is there a way to recall it as a react-native? I'm only allowed to see the screen on the webview. react-native - using the ability to leverage expo-cli I can't do it. Read in browser »  By alti21 on Jun 04, 2021 04:02 am Hi I am creating an app where a user can search for a book and put it on a shelf depending on which shelf the user clicks on. Currently the user can type a query and many results can get displayed. The user can open a dropdown on a book and click on a shelf (in the dropdown) to select a shelf for that book. I want to call a method that will update the shelf of a book. It works only if the shelfType is hardcoded however (shelfTypes are 'wantToRead', 'read', 'currentlyReading'). What I want to happen is that the user clicks on a shelf and that shelf is set as the local state variable shelfType in SearchPage. Then once the shelfType changes, the method to update the shelf of a book will run (it makes an API call to a backend). But for some strange reason I can only update the shelf if I hardcode the shelf type into the update method, not when I use the value of the state shelfType. What am I doing wrong? I hope this question makes sense. SearchPage.js import React, { useEffect, useState } from 'react'; import { BsArrowLeftShort } from 'react-icons/bs'; import SearchBar from '../components/SearchBar'; import { search, update, getAll } from '../api/BooksAPI'; import Book from '../components/Book'; const SearchPage = () => { const [query, setQuery] = useState(''); const [data, setData] = useState(); const handleChange = (e) => { setQuery(e.target.value); }; useEffect(() => { const bookSearch = setTimeout(() => { if (query.length > 0) { search(query).then((res) => { if (res.length > 0) { setData(res); } else setData(); }); } else { setData(); // make sure data is not undefined } }, 1000); return () => clearTimeout(bookSearch); }, [query]); const [shelfType, setShelfType] = useState('None'); const [currentBook, setCurrentBook] = useState({}); const doSomethingWithBookAndShelf = (book, shelf) => { setShelfType(shelf); setCurrentBook(book); }; useEffect(() => { //following line doesn't update like this, but I want it to work like this update(currentBook, shelfType).then((res) => console.log(res)); // update works if I run update(currentBook, 'wantToRead').then((res) => console.log(res)); getAll().then((res) => console.log(res)); }, [shelfType]); return ( <div> <SearchBar type="text" searchValue={query} placeholder="Search for a book" icon={<BsArrowLeftShort />} handleChange={handleChange} /> <div className="book-list"> {data !== ? data.map((book) => ( <Book book={book} key={book.id} doSomethingWithBookAndShelf={doSomethingWithBookAndShelf} /> )) : 'ok'} </div> </div> ); }; export default SearchPage; Book.js import React from 'react'; import PropTypes from 'prop-types'; import ButtonDropDown from './ButtonDropDown'; const Book = ({ book, doSomethingWithBookAndShelf }) => { return ( <div className="book"> <img src={book.imageLinks.thumbnail} alt={book.title} className="book-thumbnail" /> <ButtonDropDown choices={['Currently Reading', 'Want to Read', 'Read', 'None']} onSelectChoice={(choice) => { // book came from the component props doSomethingWithBookAndShelf(book, choice); }} /> <div className="book-title">{book.title}</div> <div className="book-authors">{book.authors}</div> </div> ); }; Book.propTypes = { doSomethingWithBookAndShelf: PropTypes.func.isRequired, book: PropTypes.shape({ imageLinks: PropTypes.shape({ thumbnail: PropTypes.string.isRequired, }), title: PropTypes.string.isRequired, authors: PropTypes.arrayOf(PropTypes.string), }).isRequired, }; export default Book; ButtonDropDown.js import React, { useState } from 'react'; import PropTypes from 'prop-types'; import { BsFillCaretDownFill } from 'react-icons/bs'; const ButtonDropDown = ({ choices, label, onSelectChoice }) => { const [active, setActive] = useState(false); const toggleClass = () => { setActive(!active); }; return ( <div className="dropdown"> <button type="button" className="dropbtn" onFocus={toggleClass} onBlur={toggleClass} > <BsFillCaretDownFill /> </button> <div id="myDropdown" className={`dropdown-content ${active ? `show` : `hide`}`} > <div className="dropdown-label">{label}</div> {choices.map((choice, index) => ( <button // eslint-disable-next-line react/no-array-index-key key={index} className="dropdown-choice" onClick={() => { // we create an specific callback for each item onSelectChoice(choice); }} type="button" value={choice} > {choice} </button> ))} </div> </div> ); }; ButtonDropDown.propTypes = { choices: PropTypes.arrayOf(PropTypes.string).isRequired, label: PropTypes.string, onSelectChoice: PropTypes.func.isRequired, }; ButtonDropDown.defaultProps = { label: 'Move to...', }; export default ButtonDropDown;
Read in browser »  By Mustafa Shaheen on Jun 04, 2021 04:02 am I have a tableview inside a tableview cell. I am unable scroll that table. I have also attached the screenshot of the table Here is my code: - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; if (self) { // Initialization code self.frame = CGRectMake(0, 0, 300, 50); self.subMenuTableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain]; self.subMenuTableView.tag = 100; self.subMenuTableView.delegate = self; self.subMenuTableView.dataSource = self; self.subMenuTableView.separatorStyle = UITableViewCellSeparatorStyleNone; self.subMenuTableView.bounces = NO; self.subMenuTableView.scrollEnabled = YES; self.subMenuTableView.alwaysBounceVertical = NO; [self addSubview:self.subMenuTableView]; // add it cell } return self; } - (void)layoutSubviews { [super layoutSubviews]; //UITableView *subMenuTableView =(UITableView *) [self viewWithTag:100]; self.subMenuTableView.frame = CGRectMake(0.2, 0.3, self.bounds.size.width-5, self.bounds.size.height-5);//set the frames for tableview }
Read in browser »  By Muhammad Azrai Bin Sidratul Mu on Jun 04, 2021 04:02 am So I'm trying to play around with WebGazer but I'm already stuck at loading the js file. The webgazer.js file consists of 140k line of codes, but when I load my page the js file only loads until line 94k. I don't want to use NPM cause it's causing me a lot of hassle to install & run the NPM. How do I fix this problem? Thanks in advance Read in browser »  By user1668604 on Jun 04, 2021 04:02 am I would like to use QT's cross platform UI/UX toolkit for trying out some computer graphics ideas. For rendering 3d content I need to have nearly full control over graphics APIs (Metal, Direct3d and Vulkan) and QT's cross platform 3d graphics APIs are not of interest. So only QT's basic UI and input handling functionality is needed on top of rendered image. Any advise on how to achieve this in qt please? Read in browser »  By tayu on Jun 04, 2021 04:02 am How can you multiply two numbers that have confidence intervals and get the result with the new confidence interval? My situation is like below. There are two tests for a disease, test A and test B. This is the confusion matrix of the test A . data.frame(disease=c(30,70),no_disease=c(10,90),row.names =c("A","not A")) <table> <tr ><th></th> <th align="center">Disease</th> <th align="center">No disease</th></tr> <tr><td align="center"> A </td> <td align="center">30</td> <td align="center">10</td></tr> <tr><td align="center">not A</td> <td align="center">70</td> <td align="center">90</td></tr> </table> Positive likelihood value can be calculated using code below. library(epiR) datA <- as.table(matrix(c(30,70,10,90), nrow = 2)) colnames(datA) <- c("Dis+","Dis-") rownames(datA) <- c("Test+","Test-") rvalA <- epi.tests(datA, conf.level = 0.95) print(rvalA) Positive likelihood ratio 3.00 (1.55, 5.80) Test B confusion matrix. data.frame(disease=c(60,40),no_disease=c(40,60),row.names =c("B","not B")) <table> <tr ><th></th> <th align="center">Disease</th> <th align="center">No disease</th></tr> <tr><td align="center"> B </td> <td align="center">60</td> <td align="center">40</td></tr> <tr><td align="center">not B</td> <td align="center">40</td> <td align="center">60</td></tr> </table> Positive likelihood value for test B. datB <- as.table(matrix(c(60,40,40,60), nrow = 2)) colnames(datB) <- c("Dis+","Dis-") rownames(datB) <- c("Test+","Test-") rvalB <- epi.tests(datB, conf.level = 0.95) print(rvalB) Positive likelihood ratio 1.50 (1.12, 2.00) Suppose, there is a patient with A test positive, and then B test positive. I would like to multiply these positive likelihood ratio, like 3 x 1.5, to get the odds. But I don't have any idea how to get the confidence intervals after this multiplication. Could you teach me how to do that, if possible, with code? Thank you in advance! Read in browser »  By Kierran Purden on Jun 04, 2021 04:02 am I've been experimenting with C again after a while of not coding, and I have come across something I don't understand regarding bit shifting. #include <stdio.h> #include <stdint.h> #include <inttypes.h> void main() { uint64_t x = 0; uint64_t testBin = 0b11110000; x = 1 << testBin; printf("testBin is %"PRIu64"\nx is %"PRIu64"\n", testBin, x); //uint64_t y = 240%32; //printf("%"PRIu64 "\n",y); } In the above code, x returns 65536, indicating that after bit shifting 240 places the 1 is now sat in position 17 of a 32-bit register, whereas I'd expect it to be at position 49 of a 64-bit register. I tried the same with unsigned long long types, that did the same thing. I've tried compiling both with and without the m64 argument, both the same. I'm not a programmer by trade so I may have missed something fundamental, please bear with me. Thanks in advance Read in browser »  By BENABAD kheira on Jun 04, 2021 04:02 am Bonjour, je cherche quelqu'un qui maitrise la programmation en VBA Read in browser »  By Saikat Hazra on Jun 04, 2021 04:02 am This is the 2D array $arr1 = array("0"=> array("priority"=>3),"1"=> array("priority"=>3),"2"=> array("priority"=>2),"3"=> array("priority"=>1),"4"=> array("priority"=>1),"5"=> array("priority"=>-1),"6"=> array("priority"=>2),"7"=> array("priority"=>2),"8"=> array("priority"=>1),"9"=> array("priority"=>3),"10"=> array("priority"=>1),"11"=> array("priority"=>-1),"12"=> array("priority"=>-1),"13"=> array("priority"=>2),"14"=> array("priority"=>3)); This is the 1D array $arr2=["77","79","81","73","2","1"]; i want to merge these two array like this $arr3 = array("0"=> array("priority"=>3,"user"=>77),"1"=> array("priority"=>3,"user"=>79),"2"=> array("priority"=>2,"user"=>81),"3"=> array("priority"=>1,"user"=>73),"4"=> array("priority"=>1,"user"=>2),"5"=> array("priority"=>-1,"user"=>1),"6"=> array("priority"=>2,"user"=>77),"7"=> array("priority"=>2,"user"=>79),"8"=> array("priority"=>1,"user"=>81),"9"=> array("priority"=>3,"user"=>73),"10"=> array("priority"=>1,"user"=>2),"11"=> array("priority"=>-1,"user"=>1),"12"=> array("priority"=>-1,"user"=>77),"13"=> array("priority"=>2,"user"=>79),"14"=> array("priority"=>3,"user"=>81));
Read in browser »  By Cappylol on Jun 04, 2021 04:02 am I'm trying to receive data in JH from Impyla, everything works fine except tables in one DB are returning data in b'' format. Code: from impala.dbapi import connect conn = connect(host=host, port=21050, user={userName}, use_ssl=True, auth_mechanism='GSSAPI', kerberos_service_name='impala', database=db) cursor = conn.cursor() cursor.execute(sql) data = cursor.fetchall() example output: b'', b'UK', b'X', b'Hlavn\xc3\xad 51', It is happening only on 1 DB, other DBs and tables that I have tested are ok in utf-8 (tested on 4 DBs). + Not every column is in b''. Packages: impyla 0.17.0 pypi_0 pypi bitarray 2.1.0 pypi_0 pypi six 1.14.0 py_1 conda-forge thrift 0.11.0 pypi_0 pypi thrift-cpp 0.13.0 h62aa4f2_2 conda-forge thrift-sasl 0.4.3 pypi_0 pypi thriftpy 0.3.9 py37h516909a_1001 conda-forge thriftpy2 0.4.14 py37h5e8e339_0 conda-forge krb5 1.17.2 h926e7f8_0 conda-forge However, if I run same query not from JH, but directly from server the output is in correct encoding - no bytes. Packages on server: impyla 0.16.3 py37hc8dfbb8_0 conda-forge bitarray 2.0.1 py37h5e8e339_0 conda-forge thrift 0.13.0 py37hcd2ae1e_2 conda-forge thrift_sasl 0.4.2 py37h8f50634_0 conda-forge thriftpy 0.3.9 py37h516909a_1001 conda-forge thriftpy2 0.4.14 py37h5e8e339_0 conda-forge six 1.15.0 pyh9f0ad1d_0 conda-forge krb5 1.19.1 hcc1bbae_0 conda-forge Any clues? :) Thank you. Read in browser »  By Marco Faustinelli on Jun 04, 2021 04:01 am I want to have several div's in column, centered on the page axis and stretched in width as much as the div width allows it. I am using the <Grid> component (both container and item): In the previous image all Grid items have xs={12}, while "page body" has xs={10}. I would expect that the following container would do the job: <Grid container direction='column' justify='center' alignItems='stretch'> .... </Grid> However, if I want the effect shown in the previous image, I have to give the container a property direction='row'. If I give direction='column', all grid items are aligned on the left side of the screen: This seems wrong to me. I have also checked on the FlexyBoxes site, and it requires 'flex-direction:column': What am I missing here? Why do I get a column ordering only if I specify direction='row'? Read in browser »  By marcus on Jun 04, 2021 04:01 am The content of HTML body is defined in a.html file instead of index.html. Then this content is loaded to index.html via jquery load() function. How can I get the ".test-img" class element in a.js file? This is the index.html file: <html> <head> ... </head> <body> <div id="myContent"></div> <script src="js/jquery.min.js"></script> <script> $(function(){ $("#myContent").load("a.html"); }); </script> <script src="js/main.js"></script> </body> </html> This is the a.html file: <div class="container"> <div class="box"> <div class="title">test</div> <img class="test-img" src="test.jpg" > </div> </div> This is the main.js file: document.write('<script type="text/javascript" src="js/a.js"></script>');
Read in browser »  By Christos Fotos on Jun 04, 2021 04:01 am I am trying to create a 3D cave exploration mini game for Android tablets. Throughout the cave, there will be items that when the player touches them, they will get Destroyed On Collision at which point a window will pop up with a multiple choice quiz mini game. When the player object picks up the first item and the quiz pops up, it forces me to complete the whole quiz whereas I want the questions to be one or two per item. Below are my three scripts that control the Quiz. QnA.cs [System.Serializable] public class QnA { public string Question; public string Answers; public int CorrectAnswers; } QuizManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class QuizManager : MonoBehaviour { public List<QnA> QnA; public GameObject options; public int CurrentQuestion; public GameObject QuizPanel; public GameObject GoPanel; //Game Over Panel public Text QuestionTxt; public Text ScoreText; int totalQuestions = 0; public int score; private void Start() { totalQuestions = QnA.Count; //Sets the total number of questions to the count of inserted questions. GoPanel.SetActive(false); //Deactivates the Game Over Panel GenerateQuestions(); } //What to do if the questions are over. void GameOver() { QuizPanel.SetActive(false); GoPanel.SetActive(true); ScoreText.text = score + "/" + totalQuestions; } //Method attached to the button in the GameOverPanel to close the popup. public void CloseWindow() { GoPanel.SetActive(false); } //What to do if the answer is correct. public void correct() { score += 1; QnA.RemoveAt(CurrentQuestion); GenerateQuestions(); } //What to do if the answer is wrong. public void wrong() { QnA.RemoveAt(CurrentQuestion); GenerateQuestions(); } //Set the answer to the current question. void SetAnswers() { for (int i = 0; i < options.Length; i++) { options[i].GetComponent<AnswerScript>().isCorrect = false; options[i].transform.GetChild(0).GetComponent<Text>().text = QnA[CurrentQuestion].Answers[i]; if (QnA[CurrentQuestion].CorrectAnswers == i+1) { options[i].GetComponent<AnswerScript>().isCorrect = true; } } } void GenerateQuestions() { if (QnA.Count > 0) { CurrentQuestion = Random.Range(0, QnA.Count); QuestionTxt.text = QnA[CurrentQuestion].Question; SetAnswers(); }else { Debug.Log("Out of Questions"); GameOver(); } } } AnswerScript.cs is the script that I have assigned the the multiple choice buttons in order to display if the answer is correct or wrong. using System.Collections; using System.Collections.Generic; using UnityEngine; public class AnswerScript : MonoBehaviour { public bool isCorrect = false; public QuizManager quizManager; public void Answer() { if (isCorrect) { Debug.Log("Correct!"); quizManager.correct(); }else { Debug.Log("Wrong"); quizManager.wrong(); } } } I know that there is something that I have to add or change in the QuizManager to achieve what I want to do, but I have no idea. Read in browser »  By The man in the pink suit on Jun 04, 2021 03:57 am I have a date picker like this: <Form.Group controlId="dropOffDate"> <Form.Label className="form-subtitle">Drop Off Date</Form.Label> <Form.Control type="date" onChange={handleChange("dropOffDate")} name="dropOffDate" defaultValue={inputs.dropOffDate} ></Form.Control> </Form.Group> So basically, it returns the format like this: YYYY-MM-DD But I need to parse it to format "DD/MM/YYYY" and I am using this function: function convertDateFormat(date) { return String(date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear()) } So also I am calling this function when I dispatch my data dispatch(Order(convertDateFormat(inputs.pickUpDate), "20/04/2021")); but I am getting this error: TypeError: date.getDate is not a function Do you have any idea that I can do it in react? Read in browser »  By ThatRandomDeveloper on Jun 04, 2021 03:50 am I am using the requests library to download a file from a URL. This is my code for tag in soup.find_all('a'): if '.zip' in str(tag): file_name = str(tag).strip().split('>')[-2].split('<')[0] link = link_name+tag.get('href') r = requests.get(link, stream=True) with open(os.path.join(download_path, file_name), 'wb') as fd: for chunk in r.iter_content(chunk_size=1024): if chunk: fd.write(chunk) And then I unzip the file using this code unzip_path = os.path.join(download_path, file_name.split('.')[0]) with zipfile.ZipFile(os.path.join(download_path, file_name), 'r') as zip_ref: zip_ref.extractall(unzip_path) This code looks if there is a zip file in the provided page and then downloads the zipped file in a directory. Then it will unzip the file using the zipFile library. The problem with this code is that sometimes the download is not complete. So for example if the zipped file is 312KB long only parts of it is downloaded. And then I get a BadZipFile error. But sometimes the entire file is downloaded correctly. I tried the same without streaming and even that results in the same problem. How do I check if all the chunks are downloaded properly. Read in browser »  By sht47 on Jun 04, 2021 03:50 am To clarify the what I want to do, I modified the question. def main(): for i in range(10): sub1(i) sub2(i) def sub1(i): if i == 5: continue else: print(f'hello world from sub1') def sub2(i): print(f'hello world from sub2') if __name__ == '__main__': main() I would like to skip sub2 when i is 5. When I run this script, I got error of SyntaxError: 'continue' not properly in loop. Is it possible to call continue statement from child function? Is there any alternative way to do this ? I want to use this syntax because of readability. Read in browser »  By Dead3ye on Jun 04, 2021 03:34 am File "C:\Users\RAJDEEP\Desktop\FINAL\preprocessed.py", line 10 source_dir=r'C:\Users\RAJDEEP\Desktop\FINAL\original_images\' +class_name ^ SyntaxError: EOL while scanning string literal Read in browser »  By Jimmy Hou on Jun 04, 2021 03:30 am df = pd.read_csv('https://raw.githubusercontent.com/justmarkham/DAT8/master/data/u.user', sep ='|') df.head() df.groupby(["occupation", "gender"])["occupation"].count() The output gives me the count of each F and M, but how do I calculate the ratio? Read in browser »  By alex Serg on Jun 04, 2021 03:28 am I place two buttons horizontally on the screen. The screen size is 1920 x 1080, I run it on the emulator. each one has layuot_width = 140dp the left one has a 40dp left binding, the right one doesn't the right one has the right 40dp binding, the left one doesn't and yet, each upper binding to the upper element, as I understand it, they must withstand the size of 140dp and the margins from the right and from the left to 40dp, and in the center already as it turns out. Instead, I get this picture I don't understand why they are stretched to the full screen? xml code <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".EditGeneralTableActivity"> <EditText android:id="@+id/edTextCurName" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:layout_marginTop="8dp" android:layout_marginEnd="8dp" android:ems="10" android:inputType="textPersonName" android:text="Name" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Spinner android:id="@+id/spinEditTable" android:layout_width="match_parent" android:layout_height="40dp" android:layout_marginStart="8dp" android:layout_marginTop="8dp" android:layout_marginEnd="8dp" app:layout_constraintEnd_toEndOf="@+id/edTextCurName" app:layout_constraintStart_toStartOf="@+id/edTextCurName" app:layout_constraintTop_toBottomOf="@+id/edTextCurName" /> <Button android:id="@+id/btnSaveEditTable" android:layout_width="140dp" android:layout_height="wrap_content" android:layout_marginStart="40dp" android:layout_marginTop="16dp" android:onClick="onClickSave" android:text="@string/button_save" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/spinEditTable" /> <Button android:id="@+id/btnDeleteEditTable" android:layout_width="140dp" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:layout_marginEnd="40dp" android:text="@string/button_delete" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/spinEditTable" /> </androidx.constraintlayout.widget.ConstraintLayout>
Read in browser »  By nastari on Jun 04, 2021 02:40 am I have a question about how EVM and Solidity work. In this example on the official Solidity website, there are two contracts ( Caller, C ). What happens and I didn't know is that I can host the "Caller" contract and still interact with the "C" contract even though it's not instantiated in the blockchain. Just so I understand, does "Caller" host under the hood the "C" contract with you? Because I'm imagining that if I wanted to create a contract that offered several services I would do it just like that, it's much better than passing instance of related contracts in the blockchain. Or is there something I don't understand? The source code is in ( Getter Functions - https://docs.soliditylang.org/en/v0.8.4/contracts.html ) contract C { uint public data = 42; } contract Caller { C c = new C(); function f() public view returns (uint) { return c.data(); } }
Read in browser »  By Fabic on Jun 04, 2021 02:00 am I have a grid with a lots of childs. The HTML is simple as this: <div class="parent"> <div class="child"></div> <div class="child"></div> ... </div> The .parent has width: 100% and max-width: 1024px. The .childs should - be equally wide (even if the last row contains fewer elements)
- be as small as possible
- be at least as wide as their
min-width - fill all the space (in width) of their parent
- wrap if there is not enough space
I don't know the number of childs. Do you have a solution? (I'm fine with solutions for Chrome, Safari and Firefox) UPDATE The parent should never scroll horizontally. UPDATE 2 Example: .parent has a width of 1020px and there are 11 childs with a min-width of 100px. All elements should be 102px wide; 10 elements in the first row and the 11th element in the second row. Read in browser »  By Jack Daniel on Jun 03, 2021 06:27 pm I am making a real-time android chat application with text and image messages using Firestore, Firebase storage & java. The Firestore database structure is: chats/chat_id/messages/message_id/{description of the message}. The structure of firebase storage is: chats/chat_id/messages/message_id/{image message} I have added a snapshot listener to chats/chat_id/messages, so whenever there is a new text or image message I am able to display it. The following code is executed when send button is clicked (i.e an image or text message is sent): public void sendMessage(View view) { try { //to hide keyboard once send button is pressed InputMethodManager inputmanager = (InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE); if (inputmanager != null) { inputmanager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0); } } catch (Exception var2) { } scrollview.post(new Runnable() { @Override public void run() { scrollview.fullScroll(ScrollView.FOCUS_DOWN); } }); if(messageText.getText().toString().length()!=0) { Map<String, Object> newMessageSent = new HashMap<>(); newMessageSent.put("type", "text"); newMessageSent.put("from",currentUser.getUid().toString()); newMessageSent.put("text",messageText.getText().toString()); messageText.setText(""); messageSentTimeStamp = new Timestamp(new Date()); newMessageSent.put("timestamp",messageSentTimeStamp); db.collection("chats").document(chat_id).collection("messages").document(currentUser.getUid()+messageSentTimeStamp) .set(newMessageSent) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { } }); } if(image_selected==1) { chatLinearLayout.removeView(ImageMessageToSend); image_selected=0; Map<String, Object> newMessageSent = new HashMap<>(); newMessageSent.put("type", "image"); newMessageSent.put("from",currentUser.getUid().toString()); messageSentTimeStamp = new Timestamp(new Date()); newMessageSent.put("timestamp",messageSentTimeStamp); StorageReference ref = storageReference.child("chats").child(chat_id).child("messages").child(currentUser.getUid()+messageSentTimeStamp); // adding listeners on upload // or failure of image ref.putFile(selectedImage).addOnSuccessListener( new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess( UploadTask.TaskSnapshot taskSnapshot) { db.collection("chats").document(chat_id).collection("messages").document(currentUser.getUid()+messageSentTimeStamp) .set(newMessageSent) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { } }); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { } }) .addOnProgressListener( new OnProgressListener<UploadTask.TaskSnapshot>() { // Progress Listener for loading // percentage on the dialog box @Override public void onProgress( UploadTask.TaskSnapshot taskSnapshot) { } }); } } The onCreate method which has the snapshot listener @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chat); scrollview = findViewById(R.id.chatScrollView); scrollview.post(new Runnable() { @Override public void run() { scrollview.fullScroll(ScrollView.FOCUS_DOWN); } }); messageText =findViewById(R.id.messageText); chatLinearLayout=findViewById(R.id.chatLinearLayout); frbAuth = FirebaseAuth.getInstance(); currentUser = frbAuth.getCurrentUser(); db = FirebaseFirestore.getInstance(); storage = FirebaseStorage.getInstance(); storageReference = storage.getReference(); Intent fromUserList = getIntent(); user_id = fromUserList.getStringExtra("user_id"); chat_user = fromUserList.getStringExtra("chat_user"); setTitle(chat_user); user_id_compare = currentUser.getUid().toString().compareTo(user_id); //comparing id of current user with id of user with whom chat is happening if(user_id_compare<0) { chat_id = currentUser.getUid().toString()+user_id; } else { chat_id = user_id+currentUser.getUid().toString(); } db.collection("chats").document(chat_id).collection("messages").orderBy("timestamp") .addSnapshotListener(new EventListener<QuerySnapshot>() { @Override public void onEvent(@Nullable QuerySnapshot snapshots, @Nullable FirebaseFirestoreException e) { if (e != null) { return; } for (DocumentChange dc : snapshots.getDocumentChanges()) { switch (dc.getType()) { case ADDED: from=(String) dc.getDocument().get("from"); messageType= (String) dc.getDocument().get("type"); timeStamp = (Timestamp) dc.getDocument().get("timestamp"); if(from.equals(currentUser.getUid())) { if(messageType.equals("text")) { sentMessageText = (String) dc.getDocument().get("text"); TextView sentTextMessage = new TextView(getApplicationContext()); LinearLayout.LayoutParams sentTextMessageLayoutParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); sentTextMessageLayoutParams.gravity = Gravity.RIGHT; sentTextMessage.setText(sentMessageText); sentTextMessage.setTextSize(20); sentTextMessage.setTextColor(getResources().getColor(R.color.black)); chatLinearLayout.addView(sentTextMessage, sentTextMessageLayoutParams); } if(messageType.equals("image")) { StorageReference ref = storageReference.child("chats").child(chat_id).child("messages").child(currentUser.getUid()+timeStamp); //Toast.makeText(ChatActivity.this,currentUser.getUid()+timeStamp,Toast.LENGTH_LONG).show(); ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() { @Override public void onSuccess(Uri uri) { ImageView sentImageMessage = new ImageView(getApplicationContext()); LinearLayout.LayoutParams sentImageMessageLayoutParams = new LinearLayout.LayoutParams( 400 , 400 ) ; sentImageMessageLayoutParams.gravity = Gravity.RIGHT; Glide.with(getApplicationContext()).load(uri.toString()).into(sentImageMessage); chatLinearLayout.addView(sentImageMessage,sentImageMessageLayoutParams); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { } }); } } else { if(messageType.equals("text")) { receivedMessageText = (String) dc.getDocument().get("text"); TextView receivedTextMessage= new TextView(getApplicationContext()); LinearLayout.LayoutParams receivedTextMessageLayoutParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams. WRAP_CONTENT , LinearLayout.LayoutParams. WRAP_CONTENT ) ; receivedTextMessageLayoutParams.gravity = Gravity.LEFT; receivedTextMessage.setText(receivedMessageText); receivedTextMessage.setTextSize(20); receivedTextMessage.setTextColor(getResources().getColor(R.color.black)); chatLinearLayout.addView(receivedTextMessage,receivedTextMessageLayoutParams); } if(messageType.equals("image")) { StorageReference ref = storageReference.child("chats").child(chat_id).child("messages").child(user_id+timeStamp); ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() { @Override public void onSuccess(Uri uri) { ImageView receivedImageMessage = new ImageView(getApplicationContext()); LinearLayout.LayoutParams receivedImageMessageImageLayoutParams = new LinearLayout.LayoutParams( 400 , 400 ) ; receivedImageMessageImageLayoutParams.gravity = Gravity.LEFT; Glide.with(getApplicationContext()).load(uri.toString()).into(receivedImageMessage); chatLinearLayout.addView(receivedImageMessage,receivedImageMessageImageLayoutParams ); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { } }); } } break; case MODIFIED: break; case REMOVED: break; } } } }); } When the chat activity is opened, the previous text and image messages of the chat are displayed with the help of the snapshot listener but the problem is that all the text messages are displayed first followed by all the image messages. I know that this is because the images are being downloaded from firebase storage and the download is asynchronous, so before the download of an image is completed the next text message is displayed. So the problem is that all text messages are displayed first followed by all the image messages, hence, the actual order of messages is not maintained. Kindly help me with this. Read in browser »  By Gibson on Jun 03, 2021 05:10 pm my time select is being pre-filled with the current hour: <%= form.time_select :afterstart, class: "form-control" %> How can I have a blank placeholder (default to null) so it doesn't get stored in ddbb unless the user fills it in? Couldn't find any usable method in the API docs. Thanks! Read in browser »  By Rainning on Jun 03, 2021 11:01 am I have a custom component RedirectButton, which is implemented with <button> with additional routing function provided by react-router-dom V5. The following code won't trigger the handleSubmit, why? return <div className="import-workspace box"> <div style={{display: "flex", flexDirection: "column"}}> <form ref={formRef} onSubmit={handleSubmit}> <h1>Import Your Space</h1> <InputText ref={spaceIdRef} label="space-id" init={spaceId} onChange={value => setSpaceId(value)}/> <InputText ref={mapIdRef} label="map-id" init={mapId} onChange={value => setMapId(value)}/> <InputText ref={roomsRef} area label="rooms" init={rooms} onChange={value => setRooms(value)}/> <RedirectButton text="Start Discrimination" style={{background: "lightgreen"}} to="/workspace-generator" formRef={formRef}/> </form> </div> </div> and if I changed the <RedirectButton> to simply <button>test</button> then the handleSubmit will be called, why? import {Link, useLocation} from "react-router-dom"; const RedirectButton = ({text, to, style, onClick}) => { const { pathname } = useLocation() const { display, justifyContent, ...rest } = style return <Link to={to? to: pathname} onClick={onClick} style={{ textDecoration: "none", display, justifyContent }}> <button style={{ ...rest }}> {text} </button> </Link> } export default RedirectButton
Read in browser »  By rishab ajain445 on Jun 03, 2021 08:51 am I want to achieve this without having to push it individually in the accounts with cross account policy enabled. Is there a way to just mention the image uri path in my lambda function of other accounts so that it picks up my docker image from the origin account. My image already resides in one of the account, lets call it ACC A. Now i want to use the same repo in ACC B, without having to push that image again in ACC B. Read in browser »  Recent Articles:
|
No comments:
Post a Comment