Mediarecorder is not starting when i set output file a parcelfiledescriptor for video recording Posted: 05 Feb 2022 05:05 AM PST try { descriptors = ParcelFileDescriptor.createPipe(); } catch (IOException e) { e.printStackTrace(); } parcelRead = new ParcelFileDescriptor(descriptors[0]); parcelWrite = new ParcelFileDescriptor(descriptors[1]); inputStream = new ParcelFileDescriptor.AutoCloseInputStream(parcelRead); mediaRecorder = new MediaRecorder(); // Step 1: Unlock and set camera to MediaRecorder mCamera.unlock(); mediaRecorder.setCamera(mCamera); // Step 2: Set sources mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER); // Step 3: Set a CamcorderProfile (requires API Level 8 or higher) mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_720P)); // The bandwidth actually consumed is often above what was requested // Step 4: Set output file mediaRecorder.setOutputFile(parcelWrite.getFileDescriptor()); // Step 5: Set the preview output mediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface()); mediaRecorder.prepare(); mediaRecorder.start(); E/MediaRecorder: start failed: -2147483648 0xb400007c921b82c0 W/System.err: java.lang.RuntimeException: start failed. W/System.err: at android.media.MediaRecorder.start(Native Method) at com.googleDev21ex.videorecorder.VideoRecordActivity2$2$1$1.run(VideoRecordActivity2.java:150) at android.os.Handler.handleCallback(Handler.java:938) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:239) at android.app.ActivityThread.main(ActivityThread.java:8212) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:626) |
npm: Could not determine Node.js install directory Posted: 05 Feb 2022 05:04 AM PST cannot use npm any command, but the node -v is worked error message: TypeError: Class extends value undefined is not a constructor or null at Object.<anonymous> (E:\nodejs\node_modules\npm\node_modules\socks-proxy-agent\dist\agent.js:114:44) at Module._compile (node:internal/modules/cjs/loader:1101:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) at Module.load (node:internal/modules/cjs/loader:981:32) at Function.Module._load (node:internal/modules/cjs/loader:822:12) at Module.require (node:internal/modules/cjs/loader:1005:19) at require (node:internal/modules/cjs/helpers:102:18) at Object.<anonymous> (E:\nodejs\node_modules\npm\node_modules\socks-proxy-agent\dist\index.js:5:33) at Module._compile (node:internal/modules/cjs/loader:1101:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) at Module.load (node:internal/modules/cjs/loader:981:32) at Function.Module._load (node:internal/modules/cjs/loader:822:12) at Module.require (node:internal/modules/cjs/loader:1005:19) at require (node:internal/modules/cjs/helpers:102:18) at Object.<anonymous> (E:\nodejs\node_modules\npm\node_modules\make-fetch-happen\lib\agent.js:161:25) at Module._compile (node:internal/modules/cjs/loader:1101:14) Could not determine Node.js install directory os: windows 11 node: v16.13.2 I also reinstall the node and restart the system, but still did not work |
using postman data is sent to POST method and saved but in some strange string Posted: 05 Feb 2022 05:04 AM PST I am begineer in node js and have to make college project in very little time due to this sem being a crunch sem. so I tried to make a comment system for my blog using node js college project. So far, articles can be created,updated,deleted and read. POST comment works when using Postman and also redirects to proper page. The post method saves comment and it is also visible on concerned page, However the string that I type in Postman as comment gets changes to some random String which is shown in the included picture. I need a solution to fix this problem and as a begineer any help, pointers are apreciated. My schema for comments and article //comment.Schema const mongoose= require('mongoose') var commentSchema = new mongoose.Schema( { text:{ type: String, required:true }, date:{ type:Date, default: Date.now }, article:{ type: mongoose.Schema.Types.ObjectId, ref: 'Article' } } ) module.exports=mongoose.model('Comment',commentSchema) //Article schema const mongoose = require('mongoose') //Define Database schema const articleSchema=new mongoose.Schema({ title:{ type:String, required: true }, description:{ type:String, required:true }, markdown:{ type:String, required:true }, createdAt:{ type: Date, default: Date.now }, slug:{ type:String, required:true, unique:true }, comments:[{ type: String, type:mongoose.Schema.Types.ObjectId, ref:'Comment' }], }) //export Article model module.exports=mongoose.model('Article',articleSchema) //POST request to save a comment router.post('/edit/:id/comments', async (req,res)=>{ const id = req.params.id; const comment = new Comment({ text: req.body.comment, Article: id }) await comment.save(); const ArticleRelated= await Article.findById(id); ArticleRelated.comments.push(comment); await ArticleRelated.save(function(err) { if(err) {console.log(err)} res.redirect('/') }) //ejs file to show Article and comments <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> <title>Blog project</title> </head> <body> <div class="container"> <h1 class="mb-4"><%= article.title %></h1> <div class="text-muted mb-2"> <%= article.createdAt.toLocaleDateString() %> </div> <a href="/" class="btn btn-secondary">All Articles</a> <a href="/articles/edit/<%= article.id %>" class="btn btn-info">edit</a> <div> <%- article.sanitizedHtml %> </div> <h2>Comments</h2> <div> <a href="/articles/edit/<%= article.id %>/comments" class="btn btn-info">Add Comment</a> <div> <%= article.comments %> </div> </div> </div> </body> </html> |
Problem with pulling images stored as url in firebase database Posted: 05 Feb 2022 05:04 AM PST So I have a some data stored as json in firebase,the data is users and courses,then there is separate data for every user and every course.I have no problems with retrieving all the data except the image for the course.Image is stored as an url to imgur(https://i.imgur.com/jZAuXdx.jpg).On my front page of the website the images of the courses aren't showing up,but when I click on any course to see more details about it,then the image is there. This is the div on the main page that shows all courses. <h2 class="sectionName">All our courses</h2> <hr class="section"> <div class="row" id="app"> <div class="col-lg-4" v-for="course in courses"> <div class="card"> <div class="embed-responsive"> <img alt="Card image cap" class="card-img-top" v-bind:src="course.image" /> </div> <div class="card-block"> <a :href="'course.html?title=' + course.title + '&author=' + course.author + '&numberOfLessons=' + course.numberOfLessons+ '&price=' + course.price+ '&dateOfChange=' + course.dateOfChange+ '&id=' + course.id+ '&category=' + course.category+ '&language=' + course.language+ '&numberOfUsers=' + course.numberOfUsers+ '&rating=' + course.rating+ '&description=' + course.description+ '&hasCertificate=' + course.hasCertificate+ '&img=' + course.img"><h2 class="title">{{course.title}}</h2></a> <p class="author">{{course.author}}</p> <hr class="delim"> <h3 class="cena">{{course.cena}}</h3> <p class="card-text"><button type="button" onclick="zeljaKlik()" class="btn btn1 levo">Lista Želja</button> </a> <button type="button" onclick="korpaKlik()" class="btn btn1 desno">Korpa</button> </p> </div> </div> </div> </div> </div> This is the coursesIndex.js code function getParamValue(name){ var location = decodeURI(window.location.toString()); var index = location.indexOf("?")+1; var subs = location.substring(index,location.length); var splitted = subs.split("&"); for(i=0; i < splitted.length; i++){ var s = splitted[i].split("="); var pName = s[0]; var pValue = s[1]; if(pName == name){ return pValue; } } } var courseA = getParamValue('author'); var authorSpan = document.getElementById('auhtorSpan'); authorSpan.innerText = courseA var courseBrK = getParamValue('numberOfUsers'); var numberOfUsersSpan = document.getElementById('numberOfUsersSpan'); numberOfUsersSpan.innerText = courseBrK; var courseB = getParamValue('numberOfLessons'); var numberOfLessonsSpan = document.getElementById('numberOfLessonsSpan'); numberOfLessonsSpan.innerText = courseB; var courseC= getParamValue('price'); var cSpan = document.getElementById('priceSpan'); cSpan.innerText = courseC; var courseD = getParamValue('dateOfChange'); var dateOfChangeSpan = document.getElementById('dateOfChangeSpan'); dateOfChangeSpan.innerText = courseD; var courseI = getParamValue('id'); var idSpan = document.getElementById('idSpan'); idSpan.innerText = courseI; var courseJ = getParamValue('language'); var jSpan = document.getElementById('languageSpan'); jSpan.innerText = courseJ; var courseK = getParamValue('category'); var categorySpan = document.getElementById('categorySpan'); categorySpan.innerText = courseK; var courseN = getParamValue('title'); var titleSpan = document.getElementById('titleSpan'); titleSpan.innerText = courseN; var courseOP = getParamValue('description'); var opSpan = document.getElementById('descriptionSpan'); opSpan.innerText = courseOP; var courseOC = getParamValue('rating'); var ocSpan = document.getElementById('ratingSpan'); ocSpan.innerText = courseOC; var courseSer = getParamValue('hasCertificate'); var serSpan = document.getElementById('hasCertificateSpan'); serSpan.innerText = courseSer; var courseImage = getParamValue('image'); var imageSpan = document.getElementById('imageSpan'); imageSpan.src = courseImage; And this is courses.js file var app = new Vue({ el: '#app', data:{ courses: [] }, mounted: function(){ axios.get('https://web-dizajn-69619-default-rtdb.firebaseio.com/courses.json') .then(response => { this.courses= response.data; // handle success }) .catch(error => { console.log(error); }) } }) |
Build on-premise kubernetes cluster Posted: 05 Feb 2022 05:03 AM PST I am going to build an on-premise Kubernetes cluster I have no idea from which point can I start? I am going to build it in my garage :D, and I will use it to deploy Java applications, Databases (Postgres), Redis, Kafka,... - Number of Nodes required?
- specs for each Node (masters, workers)?
- connectivity between nodes (public/private)network?
- expose cluster over the internet?
- Do I need a Load balancer?
- Do I need WAF?
- how to secure my Cluster?
- what is the topology should I follow?
- how to achieve HA and Fault tolerance?
- do I need certificates?
- how to connect to my cluster?
- nodes will be virtualized?
- hardware bare-metal required for this purpose?
Thanks |
CSV error, unable to record data in the file Posted: 05 Feb 2022 05:06 AM PST with open('student_record.csv','w') as sr: write = csv.writer(sr) data = [['Name', 'Password', 'Designation'], ['Pti', '12345', 'Creator'], ['Shannya', '890', 'Manager']] sr.writerows(data) with open('student_record.csv','r') as read: reading = csv.reader(read) for x in reading: print(x) following shows error, AttributeError: '_io.TextIOWrapper' object has no attribute 'writerows' |
Logical AND (&&) and OR (||) operators confusion Posted: 05 Feb 2022 05:06 AM PST I'm still getting confused with the logical operator. My case is that I'm using React.js component such as below: const Component = () => { const [data, setData] = useState({ date: "", value: "", }) const [disabled, setDisabled] = useState(true); useEffect(() => { if (data.date !== "" && data.value !== "") { setDisabled(false); } else if (data.date === "" || data.value === "") { setDisabled(true); } }, [data.date, data.value]); return <Button disabled={disabled} /> } So my case here is that I have a state consisting of date and value where I receive an input from a user. If the input for one of the state (date or value ) is empty, I want the button to be disabled. From my understanding, the logical operator should be correct. What happens right now is that the Button will be enabled once both input has been filled. However, if I emptied one of the field, it doesn't get disabled. Only when I empty both input field then Button would get disabled. What am I doing wrong here? Thank you so much in advance |
Run function every x seconds - dearpygui Posted: 05 Feb 2022 05:04 AM PST I have a window application in which I am trying to refresh a table every x seconds after running my function. However I could not find any suitable method to rerun the function within the event loop of the app. This is my code and the function I'm trying to rerun is FLAS(I'm returning a list of objects). flights = FLAS() with dpg.window(width=785, height=600, no_collapse=True, no_move=True, no_title_bar=True, no_resize=True): with dpg.table(header_row=True, policy=dpg.mvTable_SizingFixedFit, row_background=True, reorderable=True, resizable=False, no_host_extendX=False, hideable=True, borders_innerV=True, delay_search=True, borders_outerV=True, borders_innerH=True, borders_outerH=True): dpg.add_table_column(label="Callsign", width_fixed=True) dpg.add_table_column(label="FIX", width_fixed=True) dpg.add_table_column(label="Exit FIR", width_fixed=True) dpg.add_table_column(label="Next FIR", width_fixed=True) dpg.add_table_column(label="Entry FL", width_fixed=True) dpg.add_table_column(label="Exit FL", width_fixed=True) print(len(flights)) if len(flights) == 0: flights.append(Flight("No flights in range", 000000, "XXX", 0, "XXXX", "XXXX",0,0,0,0)) for flight in flights: with dpg.table_row(): dpg.add_text(flight.callsign) dpg.add_text(flight.fix) dpg.add_text(flight.cFIR) dpg.add_text(flight.xFIR) dpg.add_text(flight.efl) dpg.add_text(flight.xfl) dpg.show_viewport() dpg.start_dearpygui() dpg.destroy_context() |
Redefinition error when defining friend function inside class Posted: 05 Feb 2022 05:03 AM PST I am learning friend declarations in C++ using the books listed here. So after reading, to test my understanding of the concept, i wrote the following program whose output i am unable to understand: template<typename T> struct Name { friend void anotherFeed(int x)//anotherFeed is implicitly inline and its definition is generate only when we use this nonmember function so why are we getting error at instiantiation? { } }; int main() { Name<int> s; Name<double> p;//error here. My question is that this is instiantiation of the class template Name<double> and not a call to anotherFeed so why do we get error here? } The above program give the following error: error: redefinition of 'void anotherFeed(int)' This is my current understanding: - The non-member function
anotherFeed(int) is implicitly inline. - Even if
anotherFeed(int) is inline , we cannot define the same function(doesn't matter inline or not) in the same translation unit. - The definition of
anotherFeed(int) is generated only when we use/call this function just like for a nontemplate member function of a class template. My question is that: Assuming that my understanding(the above 3 points) are correct, since i have not called/used anotherFeed so its definition should not be generated and we should not get the redefinition error at the time of creating an instance of the class template. Only when we call anotherFeed using those instances, we should get the redefinition error. So why do we get error at the time of creating class template's instance. Is there anything wrong in any of the above 3 points. |
Run mini-httpd serveron linux Posted: 05 Feb 2022 05:05 AM PST i just installed mini-httpd on linux mint. but can'n connect to localhost / 127.0.0.1 on browser server is working ● mini-httpd.service - LSB: mini-httpd start script Loaded: loaded (/etc/init.d/mini-httpd; generated) Active: active (exited) since Sat 2022-02-05 14:33:10 EET; 6min ago Docs: man:systemd-sysv-generator(8) Process: 6236 ExecStart=/etc/init.d/mini-httpd start (code=exited, status=0/SUCCESS) and this is the config file # Example config for mini_httpd. # Author: Marvin Stark <marv@der-marv.de> # Author-Update: 2015 Jose dos Santos Junior <j.s.junior@live.com> # Description Update: Changed the default document root (data_dir)/var/www/html # Last-Update: 2015-09-05 # Uncomment this line for turning on ssl support. #ssl # On which host mini_httpd should bind? host=localhost # On which port mini_httpd should listen? port=80 # Which user mini_httpd should use? user=nobody # Run in chroot mode? #chroot # yes nochroot # no # Working directory of mini_httpd. #dir=<work_dir> # We are the web files stored? # Please change this to your needs. data_dir=/var/www/html # CGI path cgipat=cgi-bin/* # Which certificate to use? #certfile=<certfile> # Which logfile to use? logfile=/var/log/mini_httpd.log # Which pidfile to use? pidfile=/var/run/mini_httpd.pid # Which charset to use? charset=iso-8859-1 |
How to send File to an external API like Postman Posted: 05 Feb 2022 05:04 AM PST There is an external API that I send Post request as form-data in Postman. There are 2 parameters in my request Body. First is Name and the second is Image (can be different file format like txt etc.) So, now I need to do the same thing (to send request) from C# code, not via Postman. What is the equivalent of this Postman method (FormFile) in C#? Note: I'm trying to create a model with properties string: Name and IFileFormat: Image |
BigTable schema design Posted: 05 Feb 2022 05:04 AM PST Playing around with BigTable trying to understand how to properly design a schema for a IoT use-case. We have sensors, identified by uuids that submit data. Thinking of a effecient design, one approach would be to have "Week-First-Date" as the row key, some static name "sensor-data" as the family name and sensorId as column. This way data is grouped on weekly basis, partitions should not grow above 100MB and hotspotting will be prevented. Looking at the image above, "week-first-day1" would contain all the data for sensorId-A, B etc. Is there anything wrong with this general schema? |
How do I test a range in KDB? Posted: 05 Feb 2022 05:06 AM PST Let's say I have a range 3 < x < 5 . What's the cleanest way to get 1 if x > 5 , -1 if x < 3 and 0 if it's in the range 3 <x <5 ? I'm trying to mix together & and | (trying to adapt the answer from here: In KDB/Q, how do I clip numbers to be in the range -1, 1?). I'm not sure if it's possible this way though. |
how to get highest value in django model for each objects Posted: 05 Feb 2022 05:06 AM PST admin want to add diffrent challenges. each challenge have lot of users . each users maybe have lot of likes . i want to show the winner of each challenge. for that i need to get which candidate get highest like . how can i get it . is there any way like .count .? how can i use that ? in which model . for example :- challenges 1 first_contest 2 second_contest candidates id name contest 1 jhon first_contest 2 sara second_contest 3 abi first_contest candidates likes id user_id candidate_id 1 1 1 2 2 2 3 1 1 in this case cadidate 1 = jhon get 2 likes so in first contest jhon wins . also in second contest sara get 1 like . so i need show the winner in first contest . how is that ? models.py class Challenge(models.Model): title = models.CharField(max_length=50) class Candidates(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) image = models.FileField( upload_to="challenge_candidates/",) def likes_count(self): return self.likes.all().count() class CandidateLikes(models.Model): like = models.CharField(max_length=10) user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='candidate_likes') contest_candidates = models.ForeignKey(Candidates, on_delete=models.CASCADE, related_name='likes') sorry for my poor english . thank you . |
Oracle renaming auto generated list paritions Posted: 05 Feb 2022 05:06 AM PST I have several environments where automatic list partitioning is implemented. Some product managers don't like the system GENERATED partition name, which is being GENERATED and want to reference the partition by a more meaningful name. In an effort to address those concerns I'm trying to create a procedure, which will rename the partition based on the high_value. In the example below I am partitioning by state so the names I want to generate are P_OHIO, P_IOWA.. In the procedure below I am getting the following error: ORA-14048: a partition maintenance operation may not be combined with other operations ORA-06512: Can someone please advise me on why I am getting this error and how to rectify it. Thanks in advance for your help and expertise. CREATE TABLE T21 ( seq_num NUMBER GENERATED BY DEFAULT AS IDENTITY (START WITH 1) NOT NULL, num NUMBER(*,0), state VARCHAR2(20) ) SEGMENT CREATION DEFERRED PARTITION BY LIST (state) AUTOMATIC (PARTITION P_CALIFORNIA VALUES ('CALIFORNIA') ); insert into t21 (num, state) select level * round(dbms_random.value(1,50)), case round(dbms_random.value(1,50)) when 1 then 'Alabama' when 2 then 'Alaska' when 3 then 'Arizona' when 4 then 'Arkansas' when 5 then 'California' when 6 then 'Colorado' when 7 then 'Connecticut' when 8 then 'Delaware' when 9 then 'Florida' when 10 then 'Georgia' when 11 then 'Hawaii' when 12 then 'Idaho' when 13 then 'Illinois' when 14 then 'Indiana' when 15 then 'Iowa' when 16 then 'Kansas' when 17 then 'Kentucky' when 18 then 'Louisiana' when 19 then 'Maine' when 20 then 'Maryland' when 21 then 'Massachusetts' when 22 then 'Michigan' when 23 then 'Minnesota' when 24 then 'Mississippi' when 25 then 'Missouri' when 26 then 'Montana' when 27 then 'Nebraska' when 28 then 'Nevada' when 29 then 'New Hampshire' when 30 then 'New Jersey' when 31 then 'New Mexico' when 32 then 'New York' when 33 then 'North Carolina' when 34 then 'North Dakota' when 35 then 'Ohio' when 36 then 'Oklahoma' when 37 then 'Oregon' when 38 then 'Pennsylvania' when 39 then 'Rhode Island' when 40 then 'South Carolina' when 41 then 'South Dakota' when 42 then 'Tennessee' when 43 then 'Texas' when 44 then 'Utah' when 45 then 'Vermont' when 46 then 'Virginia' when 47 then 'Washington' when 48 then 'West Virginia' when 49 then 'Wisconsin' when 50 then 'Wyoming' end from dual connect by level <= 100; SELECT TABLE_NAME, PARTITION_NAME, HIGH_VALUE FROM USER_TAB_PARTITIONS WHERE TABLE_NAME ='T21'; CREATE OR REPLACE PROCEDURE RenameListPartitions IS CURSOR PartTables IS SELECT TABLE_NAME FROM USER_PART_TABLES WHERE PARTITIONING_TYPE = 'LIST' ORDER BY TABLE_NAME; CURSOR TabParts(aTableName VARCHAR2) IS SELECT PARTITION_NAME, HIGH_VALUE FROM USER_TAB_PARTITIONS WHERE regexp_like(partition_name,'^SYS_P[[:digit:]]{1,10}') AND TABLE_NAME = aTableName AND table_name not like 'BIN$%' ORDER BY PARTITION_POSITION; newPartName VARCHAR2(30); BEGIN FOR aTab IN PartTables LOOP FOR aPart IN TabParts(aTab.TABLE_NAME) LOOP execute immediate 'select ' || aPart.HIGH_VALUE || ' from dual' into newPartName; IF newPartName <> aPart.PARTITION_NAME THEN EXECUTE IMMEDIATE 'ALTER TABLE '||aTab.TABLE_NAME||' RENAME PARTITION '||aPart.PARTITION_NAME||' TO '||newPartName; END IF; END LOOP; END LOOP; END RenameListPartitions; / EXEC RenameListPartitions; |
highlight if the same combination of data appears in another row Posted: 05 Feb 2022 05:05 AM PST Hi does anyone know how to use excel vba to highlight if the same combination of data appears in another row (within the same item, an empty row is used to split the items)? Sub InsBl() Dim LR As Long, i As Long LR = Range("A" & Rows.Count).End(xlUp).Row For i = LR To 2 Step -1 If Range("A" & i).Value <> Range("A" & i - 1).Value Then Rows(i).Insert Next i End Sub |
Switch from Main dispatcher to IO dispatcher from non lifecycle class Posted: 05 Feb 2022 05:04 AM PST I m using coroutines in my android app, and i have this function that need to communicate with UI and Main thread. private suspend fun init() : RequestProcessor<LocalData, ApiResult, ApiError> { @Suppress("LeakingThis") _localData = listener.databaseCall() withContext(Dispatchers.IO) { if (_localData == null) { checkIfShouldFetch(null, null) } else { withContext(Dispatchers.Main) { mediatorLiveData.addSource(_localData!!) { newLocalData -> mediatorLiveData.removeSource(_localData!!) // I want to call this from the IO thread. checkIfShouldFetch(newLocalData, _localData) } } } } return this } My question is, how to come back to the root context (IO) from the nested context (Main)? when i call again withContext(Dispatchers.IO) this error is displayed : Suspension functions can be called only within coroutine body I need to call the function checkIfShouldFetch(newLocalData, _localData) from the IO context and i didn't find how to do it. |
how can I output return only odd friends name from this array in JavaScript Posted: 05 Feb 2022 05:04 AM PST I want to output as a string from this code. I just checked its length but I could not output as a string again like-('joy', 'james';). I don't know where is my problem with the output string. please help to solve this problem. thank you. function oddFriend(name) { let oddFr = []; for (let i = 0; i < name.length; i++) { let frName = name[i].length; console.log(frName); if (frName % 2 != 0) { oddFr.push(frName); } } return oddFr; } console.log(oddFriend(["jon", "james", "robert", "george", "Leo", "joy"])); |
Comparing data in two CSVs and creating a third CSV for matching data Posted: 05 Feb 2022 05:05 AM PST Let's say I have file1.csv: OU Mailfile CORP:Jenny Smith: mail/246802.nsf "CORP:John Smith:,John Smith:" mail/123456.nsf STORE:Mary Poppins: mail/789012.nsf STORE:Tony Stark: mail/345678.nsf STORE:Carmen Sandiego: mail/901234.nsf NEWS:Peter Parker: mail/567890.nsf NEWS:Clark Kent: mail/654321.nsf STORES:store123 mail/369121.nsf Then file2.csv: OU CORP STORE NEWS For every line in file2.csv that has 'CORP', 'STORE', or 'NEWS', I want to search through file1.csv and create a file, such as STOREall.csv, CORPall.csv, and NEWSall.csv. So a file like STOREall.csv should have: OU Mailfile STORE:Mary Poppins: mail/789012.nsf STORE:Tony Stark: mail/345678.nsf STORE:Carmen Sandiego: mail/901234.nsf STORES:store123 mail/369121.nsf CORPall.csv: OU Mailfile CORP:Jenny Smith: mail/246802.nsf CORP:John Smith:,John Smith: mail/123456.nsf Then NEWSall.csv OU Mailfile NEWS:Peter Parker: mail/567890.nsf NEWS:Clark Kent: mail/654321.nsf If I can also have it with just OU column and not Mailfile column, that would also be good. But I think I can just do a usecols=['OU'] for that. |
cmake4eclipse - why are the CMAKE providers deprecated Posted: 05 Feb 2022 05:05 AM PST I am trying to index large CMake projects which depend on one another and the only documentation I found on how to do that, is this from 2018. The last post there says to enable inside C/C++ General > Preprocesor include paths the 2 providers "CMAKE_COMPILE_COMMANDS_JSON Parser" and "CMAKE_COMPILE_COMMANDS_JSON Compiler Built-Ins", however in recent versions of cmake4eclipse these are deprecated. I could not find a changelog explaining why or the workarounds. How to solve the problem of missing includes? Edit: I would also like to know - is it possible to resolve the includes without building from Eclipse (but merely by running the configure step perhaps). It's less useful to build from Eclipse but the Indexer functionality critically depends on having the correct includes. |
Read the value from a cell in a csv file in R from lapply Posted: 05 Feb 2022 05:05 AM PST In this code, is there a way to ask for the integer value of a specific cell in the csv file, ie row 1, col 2? I know the syntax is [, (2)] but not sure where to input that in this set of code? wd = setwd("/Users/TK/Downloads/DataCSV") Groups <- list.dirs(path = wd, full.names = TRUE, recursive = FALSE) print(Groups) Subj <- list.dirs(path = Groups, full.names = TRUE, recursive = FALSE) print(Subj) for(i in Subj) { setwd(i) section_area <- list.files(path = i, pattern = "section_area", full.names = FALSE, recursive = TRUE) print(section_area) read_area <- lapply(section_area, read.csv) print(read_area) } |
Integer validation using java.util.Scanner Posted: 05 Feb 2022 05:05 AM PST I am trying to validate that the user only enters an integer. Is there another way to do this that will make the validation more simplified? Scanner in = new Scanner(System.in); System.out.print("Enter the amount of subjects that you need to get an average of: "); int amount_of_subjects; while (!in.hasNextInt()) { // warning statement System.out.println("Please Enter integer!"); in.nextLine(); } amount_of_subjects = Integer.parseInt(in.nextLine()); |
How to mimic `Get-AzureADUser` in C# Posted: 05 Feb 2022 05:05 AM PST I am working on an Azure AD B2C application and the B2C policy stores the MFA secret-key in the extension_mfaTotpSecretKey property of the user. This works and when I run Get-AzureADUser -ObjectId '<object-id>' | ConvertTo-Json , then it shows: { "ExtensionProperty": { "odata.metadata": "https://graph.windows.net/<tenant-id>/$metadata#directoryObjects/@Element", "odata.type": "Microsoft.DirectoryServices.User", "createdDateTime": "2/4/2022 2:13:22 PM", "employeeId": null, "onPremisesDistinguishedName": null, "userIdentities": "[]", "extension_7eb927869ae04818b3aa16db92645c09_mfaTotpSecretKey": "32YZJFPXXOMHT237M64IVW63645GXQLV" }, "DeletionTimestamp": null, ... } During the migration process from the old directory to the new Azure B2C directory, I also want to transfer the existing TOTP key so users don't need to reregister their TOTP key. I have spent all day to get this to work, but no luck and I really don't know what's left. I have created an app registration in the tenant with Directory.ReadWrite.All rights, but when I read the user, then the extension is empty: var creds = new ClientSecretCredential("<tenant-id>", "<client-id>", "<client-secret>", new TokenCredentialOptions { AuthorityHost = AzureAuthorityHosts.AzurePublicCloud }); var graphClient = new GraphServiceClient(creds, new[] { "https://graph.microsoft.com/.default" }); var user = await graphClient.Users["<object-id>"].Request().Select(u => new {u.Id, u.Extensions}).Expand(u => new { u.Extensions}).GetAsync(); If I can't read the value, then I probably can't write it. I tried using OpenTypeExtension, but I am under the impression that this is a completely different property. I can't find any documentation that tells me how I can run Get-AzureADUser using Graph API v2 in C#. |
Converting code using wmi to code using ffmpy Posted: 05 Feb 2022 05:04 AM PST I have the following code that prints out the names of the connected USB cameras: import wmi c = wmi.WMI() wql = "Select * From Win32_USBControllerDevice" for item in c.query(wql): a = item.Dependent.PNPClass b = item.Dependent.Name.upper() if (a.upper() == 'MEDIA' or a.upper() == 'CAMERA') and 'AUDIO' not in b: print(item.Dependent.Name) The problem with this code is that it only works in Windows. I want to alter this code so that it works on all operating systems. I know that I have to use something other than wmi, since wmi only works in Windows. So, I was thinking about using an ffmpeg wrapper called ffmpy. So maybe I could convert the code to use ffmpy? I got the code above from the following SO post: Associate USB Video Capture Device Friendly Name with OpenCV Port Number in Python. Any help would be much appreciated! Thanks! |
Align self doesn't work on an anchor tag when its parent is flex [duplicate] Posted: 05 Feb 2022 05:05 AM PST I can't get the align-self: center property to work on an a tag .container { margin-bottom: 1rem; background-color: red; } .container-link { display: flex; align-self: center; padding-left: 2rem; height: 50px; } <div class="container"> <a class="container-link" href="google.com">link</a> </div> <div class="container"> <a class="container-link" href="#">link</a> </div> Howcome those links aren't aligned in the center now...? I tried adding flex to the container too but no go .container { margin-bottom: 1rem; background-color: red; display: flex; } .container-link { display: flex; align-self: center; padding-left: 2rem; height: 50px; } <div class="container"> <a class="container-link" href="google.com">link</a> </div> <div class="container"> <a class="container-link" href="#">link</a> </div> Why does this not work either? align-self: flex-end not working in flexbox You're applying flex properties to a child of a block element. Such properties will be ignored because you're in a block formatting context. Switch from display: block to display: flex to establish a flex formatting context. My parent is flex can't get align-self to work in a flexbox container Again, same rebuttal, I am flexing and my container is flex? Why does align self center not work? Note on duplicate The duplicate is not flex. |
React Native android crash ReactNativeReanimated Posted: 05 Feb 2022 05:05 AM PST Hello i have some crash problem when running application in react native 0.63.4 here my crash error E/ReactNativeJNI: logMarker CREATE_REACT_CONTEXT_END E/unknown:ReactNative: ReactInstanceManager.createReactContext: mJSIModulePackage not null E/AndroidRuntime: FATAL EXCEPTION: create_react_context Process: com.apps, PID: 20635 java.lang.AssertionError: Could not find module with name ReanimatedModule at com.facebook.infer.annotation.Assertions.assertNotNull(Assertions.java:35) at com.facebook.react.bridge.NativeModuleRegistry.getModule(NativeModuleRegistry.java:148) at com.facebook.react.bridge.CatalystInstanceImpl.getNativeModule(CatalystInstanceImpl.java:596) at com.facebook.react.bridge.CatalystInstanceImpl.getNativeModule(CatalystInstanceImpl.java:566) at com.facebook.react.bridge.ReactContext.getNativeModule(ReactContext.java:165) at com.swmansion.reanimated.ReanimatedJSIModulePackage.getJSIModules(ReanimatedJSIModulePackage.java:17) at com.facebook.react.ReactInstanceManager.createReactContext(ReactInstanceManager.java:1256) at com.facebook.react.ReactInstanceManager.access$1100(ReactInstanceManager.java:131) at com.facebook.react.ReactInstanceManager$5.run(ReactInstanceManager.java:1016) at java.lang.Thread.run(Thread.java:764) here my package.json { "name": "Apps", "version": "0.0.1", "private": true, "scripts": { "android": "react-native run-android", "ios": "react-native run-ios", "start": "react-native start", "test": "jest", "lint": "eslint ." }, "dependencies": { "axios": "^0.19.0", "core-js": "^3.3.5", "lodash": "4.17.15", "moment": "2.24.0", "phoenix": "^1.4.10", "phoenix-channels": "^1.0.0", "querystring": "^0.2.0", "react": "16.13.1", "react-native": "0.63.4", "react-native-countdown-component": "2.5.2", "react-native-datepicker": "1.7.2", "react-native-device-info": "^8.0.1", "react-native-elements": "^1.2.7", "react-native-fbsdk": "^3.0.0", "react-native-gesture-handler": "^1.10.2", "react-native-google-places-autocomplete": "1.3.9", "react-native-google-signin": "1.2.3", "react-native-htmlview": "0.15.0", "react-native-image-picker": "0.28.0", "react-native-image-zoom-viewer": "2.2.26", "react-native-insider": "^4.1.1", "react-native-maps": "0.24.2", "react-native-number-stepper": "0.0.2", "react-native-onesignal": "^3.6.0", "react-native-reanimated": "^2.0.0-rc.3", "react-native-router-flux": "^4.2.0", "react-native-screens": "^2.18.1", "react-native-share": "^1.2.1", "react-native-star-rating": "1.1.0", "react-native-url-preview": "^1.1.4", "react-native-vector-icons": "6.6.0", "react-native-version-check": "^3.3.1", "react-native-view-more-text": "2.1.0", "react-native-webview": "^10.3.2", "recyclerlistview": "^2.0.12" }, "devDependencies": { "@babel/core": "^7.13.1", "@babel/runtime": "^7.13.6", "@react-native-community/eslint-config": "^2.0.0", "babel-jest": "^26.6.3", "eslint": "^7.20.0", "jest": "^26.6.3", "metro-react-native-babel-preset": "^0.65.1", "react-test-renderer": "16.13.1" }, "jest": { "preset": "react-native" } } here my MainApplication.java package com.apps; import android.app.Application; import com.facebook.react.ReactApplication; import com.learnium.RNDeviceInfo.RNDeviceInfo; import com.geektime.rnonesignalandroid.ReactNativeOneSignalPackage; import cl.json.RNSharePackage; import com.imagepicker.ImagePickerPackage; import com.oblador.vectoricons.VectorIconsPackage; import co.apptailor.googlesignin.RNGoogleSigninPackage; import com.facebook.reactnative.androidsdk.FBSDKPackage; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import com.facebook.soloader.SoLoader; import com.facebook.CallbackManager; import com.facebook.FacebookSdk; import com.facebook.react.bridge.JSIModulePackage; import com.swmansion.reanimated.ReanimatedJSIModulePackage; import com.airbnb.android.react.maps.MapsPackage; import io.xogus.reactnative.versioncheck.RNVersionCheckPackage; import java.util.Arrays; import java.util.List; public class MainApplication extends Application implements ReactApplication { private static CallbackManager mCallbackManager = CallbackManager.Factory.create(); protected static CallbackManager getCallbackManager() { return mCallbackManager; } private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage(), new RNDeviceInfo(), new ReactNativeOneSignalPackage(), new RNSharePackage(), new ImagePickerPackage(), new VectorIconsPackage(), new RNGoogleSigninPackage(), new RNVersionCheckPackage(), new FBSDKPackage(), new MapsPackage() ); } @Override protected String getJSMainModuleName() { return "index"; } @Override protected JSIModulePackage getJSIModulePackage() { return new ReanimatedJSIModulePackage(); } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); FacebookSdk.sdkInitialize(getApplicationContext()); SoLoader.init(this, /* native exopackage */ false); } } here my MainActivity.java package com.apps; import com.facebook.react.ReactActivity; import com.facebook.react.ReactActivityDelegate; import com.facebook.react.ReactRootView; import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView; import android.content.Intent; import android.os.Bundle; public class MainActivity extends ReactActivity { /** * Returns the name of the main component registered from JavaScript. * This is used to schedule rendering of the component. */ @Override protected String getMainComponentName() { return "Apps"; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(null); } @Override protected ReactActivityDelegate createReactActivityDelegate() { return new ReactActivityDelegate(this, getMainComponentName()) { @Override protected ReactRootView createRootView() { return new RNGestureHandlerEnabledRootView(MainActivity.this); } }; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); MainApplication.getCallbackManager().onActivityResult(requestCode, resultCode, data); } @Override public void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); } } i already enable my hermes & follow the instructions in the doc react-native-reanimated but still crash & get error like that, i already stuck 1 weeks to solve this problem but still not works. Please help me :) |
No MaterialLocalizations found - MyApp widgets require MaterialLocalizations to be provided by a Localizations widget ancestor Posted: 05 Feb 2022 05:04 AM PST I was just trying to create an app with button which shows an alert message when the button is pressed. But it gives me this error(Mentioned below). I wrote this code by taking reference of this video. I am running the application on a live android phone using adb connect Please help..! Code import 'package:flutter/material.dart'; void main(){ runApp(MyApp()); } class MyApp extends StatelessWidget{ @override Widget build(BuildContext context) { return MaterialApp( title: "Test", home: Scaffold( appBar: AppBar(title: Text("Test")), body: Container( child: Center( child: RaisedButton( color: Colors.redAccent, textColor: Colors.white, onPressed: (){testAlert(context);}, child: Text("PressMe"), ), ), ), ), ); } void testAlert(BuildContext context){ var alert = AlertDialog( title: Text("Test"), content: Text("Done..!"), ); showDialog( context: context, builder: (BuildContext context){ return alert; } ); } } This is the code that i wrote. I also tried inserting the contents of testAlert() function directly into onPressed but doesn't work. Error Performing hot reload... Syncing files to device ZUK Z2131... Reloaded 0 of 419 libraries in 1,929ms. I/flutter (18652): ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════ I/flutter (18652): The following assertion was thrown while handling a gesture: I/flutter (18652): No MaterialLocalizations found. I/flutter (18652): MyApp widgets require MaterialLocalizations to be provided by a Localizations widget ancestor. I/flutter (18652): Localizations are used to generate many different messages, labels,and abbreviations which are used I/flutter (18652): by the material library. I/flutter (18652): To introduce a MaterialLocalizations, either use a MaterialApp at the root of your application to I/flutter (18652): include them automatically, or add a Localization widget with a MaterialLocalizations delegate. I/flutter (18652): The specific widget that could not find a MaterialLocalizations ancestor was: I/flutter (18652): MyApp I/flutter (18652): The ancestors of this widget were: I/flutter (18652): [root] I/flutter (18652): I/flutter (18652): When the exception was thrown, this was the stack: I/flutter (18652): #0 debugCheckHasMaterialLocalizations.<anonymous closure> (package:flutter/src/material/debug.dart:124:7) I/flutter (18652): #1 debugCheckHasMaterialLocalizations (package:flutter/src/material/debug.dart:127:4) I/flutter (18652): #2 showDialog (package:flutter/src/material/dialog.dart:635:10) I/flutter (18652): #3 MyApp.testAlert (package:flutter_app/main.dart:33:5) I/flutter (18652): #4 MyApp.build.<anonymous closure> (package:flutter_app/main.dart:19:29) I/flutter (18652): #5 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:507:14) I/flutter (18652): #6 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:562:30) I/flutter (18652): #7 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:102:24) I/flutter (18652): #8 TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:242:9) I/flutter (18652): #9 TapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:175:7) I/flutter (18652): #10 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:315:9) I/flutter (18652): #11 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:73:12) I/flutter (18652): #12 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:11) I/flutter (18652): #13 _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:180:19) I/flutter (18652): #14 _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:158:22) I/flutter (18652): #15 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:138:7) I/flutter (18652): #16 _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:101:7) I/flutter (18652): #17 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:85:7) I/flutter (18652): #18 _invoke1 (dart:ui/hooks.dart:168:13) I/flutter (18652): #19 _dispatchPointerDataPacket (dart:ui/hooks.dart:122:5) I/flutter (18652): I/flutter (18652): Handler: onTap I/flutter (18652): Recognizer: I/flutter (18652): TapGestureRecognizer#d5d82(debugOwner: GestureDetector, state: possible, won arena, finalPosition: I/flutter (18652): Offset(220.2, 406.1), sent tap down) I/flutter (18652): ════════════════════════════════════════════════════════════════════════════════════════════════════ W/ActivityThread(18652): handleWindowVisibility: no activity for token android.os.BinderProxy@59b4e8d I/ViewRootImpl(18652): CPU Rendering VSync enable = true |
Modelling generic variables in a Latent class model with gmnl() Posted: 05 Feb 2022 05:06 AM PST I have the problem in fomulating a model, where at least one variable is to be estimated independently from the classes, so one and the same coefficient for all classes. How could one do this? I am working with the R package gmnl. install.packages("gmnl") library(gmnl) library(mlogit) #browseURL("https://cran.r-project.org/web/packages/poLCA/index.html") ## Examples using the Fishing data set from the AER package data("Electricity", package = "mlogit") Electr <- mlogit.data(Electricity, id.var = "id", choice = "choice", varying = 3:26, shape = "wide", sep = "") Elec.lc <- gmnl(choice ~ pf + cl + loc + wk + tod + seas| 0 | 0 | 0 | 1, data = Electr, subset = 1:3000, model = 'lc', panel = TRUE, Q = 2) summary(Elec.lc) How would you model one of the variables pf, cl, loc, wk, tod, or seas independently from the class? Thank you! |
Restart python-script from within itself Posted: 05 Feb 2022 05:04 AM PST I have a python-based GTK application that loads several modules. It is run from the (linux) terminal like so: ./myscript.py --some-flag setting From within the program the user can download (using Git) newer versions. If such exists/are downloaded, a button appear that I wish would restart the program with newly compiled contents (including dependencies/imports). Preferably it would also restart it using the contents of sys.argv to keep all the flags as they were. So what I fail to find/need is a nice restart procedure that kills the current instance of the program and starts a new using the same arguments. Preferably the solution should work for Windows and Mac as well but it is not essential. |
How can I convert Markdown documents to HTML en masse? Posted: 05 Feb 2022 05:06 AM PST I'm writing some documentation in Markdown, and creating a separate file for each section of the doc. I would like to be able to convert all the files to HTML in one go, but I can't find anyone else who has tried the same thing. I'm on a Mac, so I would think a simple bash script should be able to handle it, but I've never done anything in bash and haven't had any luck. It seems like it should be simple to write something so I could just run: markdown-batch ./*.markdown Any ideas? |
No comments:
Post a Comment