running plm regressions with duplicate couples (id-time) Posted: 21 Jul 2021 07:50 AM PDT Hi' I'm trying to run a regression with fixed effects for date (Ti) and state (Si). I have more than one couple for each state-date variation. I wanted to use plm package because I want to later use sandwich package to calculate driscoll-kraay errors. any idea how to bypass the unique couple requirement or how to calculate the driscoll-kraay errors on a felm object? Thanks code: lm5 = plm(B_personal ~ logP1_4 + logTI13p + Border1 + bhavior_f_risk + bhavior_f_case + Border2 + bhavior_m_risk + bhavior_m_case| Si + Ti,df) out: "duplicate couples (id-time) in resulting pdata.frame to find out which, use, e.g., table(index(your_pdataframe), useNA = "ifany")Error in pdim.default(index[[1L]], index[[2L]]) : |
don't know how much time it will take to execute the code Posted: 21 Jul 2021 07:50 AM PDT This is the code that I have typed, to reverse the input number using a function 're' // I tried to run this code, and provided an input of six digits but after that no output is shown and it seems like it has got frozen. I had tried other codes to execute after exiting the previous code running and they worked fine I don't know the problem is with the code, I searched for every syntax error, logic error but found none. #include<iostream> using namespace std; int re(int n){ int rev = 0; while(n>0){ int rem = n % 10; rev = rev * 10 + rem; int n = n / 10; } return rev; } int main(){ int num1,num2; cin>>num1>>num2; cout<<re(num1)<<endl<<re(num2)<<endl; return 0; } |
How to deal with PHPUnit error "Schema for PHPUnit 9.5 is not available"? Posted: 21 Jul 2021 07:50 AM PDT I try to run the tests on newly installed Lumen Framework and get this error "Schema for PHPUnit 9.5 is not available". My composer.json for the project: { "name": "api/service", "description": "API Service.", "keywords": ["framework", "laravel", "lumen"], "license": "MIT", "type": "project", "require": { "php": "^7.4|^8.0", "flipbox/lumen-generator": "^8.2", "intervention/image": "^2.6", "laravel/lumen-framework": "^8.0" }, "require-dev": { "fakerphp/faker": "^1.9.1", "league/flysystem": "^1.0", "mockery/mockery": "^1.3.1", "phpunit/phpunit": "^9.3" }, "autoload": { "psr-4": { "App\\": "app/", "Database\\Factories\\": "database/factories/", "Database\\Seeders\\": "database/seeders/" } }, "autoload-dev": { "classmap": [ "tests/" ] }, "config": { "preferred-install": "dist", "sort-packages": true, "optimize-autoloader": true }, "minimum-stability": "dev", "prefer-stable": true, "scripts": { "post-root-package-install": [ "@php -r \"file_exists('.env') || copy('.env.example', '.env');\"" ] } } Installed versions of the libraries in the project are: php 7.4 laravel/lumen-framework 8.2.4 phpunit 9.5.6 In phpunit.xml I have: <?xml version="1.0" encoding="UTF-8"?> <phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd" bootstrap="vendor/autoload.php" colors="true" > <testsuites> <testsuite name="Application Test Suite"> <directory suffix="Test.php">./tests</directory> </testsuite> </testsuites> <php> <env name="APP_ENV" value="testing"/> <env name="CACHE_DRIVER" value="array"/> <env name="QUEUE_CONNECTION" value="sync"/> <env name="DB_CONNECTION" value="sqlite"/> </php> </phpunit> As I understood that the problem is in determination of the path of phpunit.xsd file in SchemaFinder.php class. There is the function path() with return value: return __DIR__ . '/../../phpunit/'; After investigation the structure of 'phpunit' library in 'vendor' folder I realized that it should be two folders upper: return __DIR__ . '/../../../../phpunit/'; After making this change, I didn't receive the error "Schema for PHPUnit 9.5 is not available" any more. Is this right decision or not? Is there another way to resolve this issue? Maybe not to make changes in vendor/phpunit folder. Thank you! |
Bash run two commands both dependent on the first Posted: 21 Jul 2021 07:50 AM PDT I'm sure this has been asked but my search has been fruitless. I want to run 3 bash commands in order with both the second and third only running if the first succeeded. Example: ## Setup mkdir so_test_tmp && cd so_test_tmp echo "This is something" > something cd .. ## Example commands cd so_test_tmp ??? cat nothing ??? cd .. # 0. cd so_test_tmp ??? cat something ??? cd .. # 1. cd does_not_exist ??? cat nothing ??? cd .. # 2. These three commands should always end in PWD. In 0. the first cd is run, then the last. In 1. all three commands successfully run. In 2. the first command fails so the second and third are not run. |
Android Studio showing unresolved reference in shared test directory, but executing tasks works as expected Posted: 21 Jul 2021 07:50 AM PDT I have a multi-module app in which test source files are shared between modules. For each module that accesses the shared files, we add the following to our build.gradle sourceSets { String testDir = '../shared/src/test/java' test { java.srcDir testDir } } and add the shared module as a dependency using implementation project(path: ':shared') When running tests using gradle everything works correctly, but when viewing the source files Android Studio is incorrectly showing Unresolved Reference errors. Oddly, one of our modules named "feature" doesn't exhibit this behaviour. All the other modules do though, despite them having identical build.gradle files. While investigating the issue I have noticed that when in the Project view the test directory in the shared module is labelled [feature] as if it belongs to the feature module. Furthermore, I have found the following in the Event Log: Duplicate content roots detected: Path [/project/shared/src/test/java] of module [project.feature was removed from modules [project.app, project.network project.wrapper] It's as if Android Studio is deliberately ignoring the sources. I have tried all combinations of resetting cache, deleting .idea and .gradle directories, cleaning etc. I have tried deleting and recreating the modules, and I can't find anything that's causing the issue. All team members are having the same issue. I can also see that the following appears in the .idea/modules/feature/project.feature.iml file, but not in any of the .iml files for the other modules. <content url="file://$MODULE_DIR$/../../../shared/src/test/java"> <sourceFolder url="file://$MODULE_DIR$/../../../shared/src/test/java" isTestSource="true" /> </content> |
Authenticate user with node express.js passport.js local mongoose Posted: 21 Jul 2021 07:50 AM PDT I'm trying to build a local login-system with passport.js. Registration is working already but the user-authentication isn't. Somehow i can't get the user right after getUserByUsername(), which should look it up in my mongodb. But if i console.log it directly as the result of my findOne() it shows up. This is my passport-config.js file const LocalStrategy = require('passport-local').Strategy const bcrypt = require("bcrypt") function initialize(passport, getUserByUsername, getUserById){ const authenticateUser = async (username, password, done) => { const user = getUserByUsername(username) console.log(user) if (user == null) return done(null, false, {message:"no user with that username"}); try { if (await bcrypt.compare(password, user.password)) { return done(null, user) } else { return done(null, false, { message: 'Password incorrect' }) } } catch (e) { return done(e) } } passport.use(new LocalStrategy({ usernameField: 'username' }, authenticateUser)) passport.serializeUser((user, done) => done(null, user.id)) passport.deserializeUser((id, done) => {return done(null, getUserById(id))}) } module.exports = initialize in my server.js file i'm initializing as follows const initializePassport = require("./passport-config") initializePassport(passport, username => { usersModel.findOne({ username: username }, async (err, result) => { if (err) return null if (!result) return null console.log(result) return result }) }, id => { usersModel.findOne({ id: id }, async (err, result) => { if (err) return null if (!result) return null return result }) }, ) |
what are the differences between the Fiber.lanes and Fiber.childLanes in React concurrent mode? Posted: 21 Jul 2021 07:49 AM PDT i know when the Update is created. it will be merged into the Fiber.ChildLanes, and then bubble up to the FiberRoot. but what the Fiber.lanes means? |
Wordpress, render a custom page via plugin Posted: 21 Jul 2021 07:49 AM PDT I want to move a custom page page-mypage.php from current theme into a plugin. I did the plugin and added on the same level as main_plugin.php but the page is not shown when tried to reach (obvious was deleted from current theme). The page have nothing special (can be abstracted with a trivial echo 'test-page' ) but wanted just to be placed into the plugin an not in current theme (link to page is just enough to be done from wp-admin in regular way) My question is how to add the page into plugin ? (there is any predefined structure) |
Pick type by array of string Posted: 21 Jul 2021 07:49 AM PDT I have type type User = { firstName: string, lastName: string, age: string } I need a function fun<User>(['firstName', 'lastName']) I need return type User with picked firstName and lastName . Is it possible to do with typeScript? |
Itext7 and SelectPdf nuget Package Posted: 21 Jul 2021 07:49 AM PDT The packages were successfully installed from nuget when I use the package in my .cs file. I got the following error enter image description here and in the console, I see an internal server error 500 |
Object is not iterable (cannot read property Symbol(Symbol.iterator)) -- React pdf Posted: 21 Jul 2021 07:49 AM PDT I'm using React Pdf renderer library to generate to pdf but problem is that when I use context api rather than prop passing it shows React error" Object is not iterable (cannot read property Symbol(Symbol.iterator))" import React from "react"; import HomePage from "./components/Home/HomePage"; import GeneratorPage from "./components/generator/GeneratorPage"; import { BrowserRouter as Router, Switch, Route, } from "react-router-dom"; import ProviderComp from "./components/Store/Provide"; import { PDFViewer } from "@react-pdf/renderer"; import PdfIndex from "./components/PdfComp/PdfIndex"; function App() { return ( <ProviderComp> <Router> <Switch> <Route path="/" exact> <HomePage /> </Route> <Route path="/generator"> <GeneratorPage /> </Route> <Route path="/preview"> <PDFViewer className="w-full h-full"> <PdfIndex/> </PDFViewer> </Route> </Switch> </Router> </ProviderComp> ); } export default App; |
ajax doesn't work in my intelliJ(unresolved function or method ajax()) Posted: 21 Jul 2021 07:49 AM PDT I get index.html source code from elsewhere but 'unresolved function or method ajax()' appears in my intelliJ. So I downloaded jQuery with npm then added the directory but it still doesn't work. But the the other project it is ok. ajax works. What should I do? |
How to do about it using list? [closed] Posted: 21 Jul 2021 07:50 AM PDT Write a Python code to create a list numbers using these number = 65, 75, 85, 95, 105 and check_number that prompt the user to enter a number to check that number is available or not in list. number = [65,75,85,95,105] check_number = int(input("Enter any number here")) for numbers in number: if check_number == number: print("The number",check_number,"is in the list") break else: print("The number",check_number,"is not in the list") break |
Authenticating to Google.Cloud.Storage.V1 using OAUTH with C#, but getting Error creating credential from JSON. Unrecognized credential type Posted: 21 Jul 2021 07:50 AM PDT I am trying to simply authenticate to the Google Cloud Storage API using OAuth2.0 and C# with a JSON file from Google. here is my OAuth JSON file: { "web": { "client_id": "ClientIdHere", "project_id": "ProjectName", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_secret": "ClientSecretHere", "redirect_uris": [ "https://localhost:44349//RedirectPage.aspx" ] }} Here is the code that I am using protected void DoTheThingsAgain() { try { string bucketName = "Daves-Bucket"; string sharedkeyFilePath = "C:\\inetpub\\wwwroot\\GoogleAPITest\\GoogleAPITest\\App_Data\\JSONFile.json"; GoogleCredential credential = null; using (var jsonStream = new FileStream(sharedkeyFilePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { credential = GoogleCredential.FromStream(jsonStream); } } catch (Exception ex) { throw ex; } } Everything works fine until it hits this line: **credential = GoogleCredential.FromStream(jsonStream);** then it gives me the error: Error creating credential from JSON. Unrecognized credential type . How do I specify the credential type for OAuth? I have seen other solutions for this but not while using OAuth, only with ServiceAccounts. That you in advance for any help you all can provide! |
How to change text color of td in Vue conditionally Posted: 21 Jul 2021 07:49 AM PDT I am consuming data from a json file like this: {"USD": {"7d": 32053.72, "30d": 33194.68, "24h": 31370.42}, "AUD": {"7d": 43134.11, "30d": 44219.00, "24h": 42701.11}, "RUB": {"7d": 2451451.45, "30d": 2465896.74, "24h": 2398589.80}, "JPY": {"7d": 3537735.55, "30d": 3664620.47, "24h": 3472632.46}, "BRL": {"7d": 167555.18, "30d": 169473.27, "24h": 163054.93}, "ILS": {"7d": 108658.72, "30d": 111663.67, "24h": 106988.58}, "GBP": {"7d": 23257.66, "30d": 23838.55, "24h": 22923.17}, "PLN": {"7d": 124869.61, "30d": 127872.57, "24h": 122668.16}, "CAD": {"7d": 40425.62, "30d": 41444.76, "24h": 39827.13}, "EUR": {"7d": 27187.74, "30d": 27955.81, "24h": 26659.79}} And I am displaying it in a table. I calculate percentage change for 7 and 30 days and whether that percentage change is negative or positive. If the change is negative I want to color the text red, if it's positive I want to color it green, this is how I check if a change is positive or negative: // Checking whether the change is positive or negative if(item['7d'] > item['30d']) { this.isPositive = true } else if (item['7d'] < item['30d']) { this.isNegative = true } So far my logic using a ternary operator does not work and I don't get my td's text colored red or green. Why and how can I achieve this? Here is my entire code: <template> <div> <v-data-table :headers="headers" :items="bitcoinInfo" :hide-default-footer="true" class="primary" > <template #item.thirtyDaysDiff="{ item }"> <td :class="isPositive ? 'positive' : 'negative' ? isNegative : 'negative'">{{ calculateThirtyDayDifference(item) }}%</td> </template> <template #item.sevenDaysDifference="{ item }"> <td :class="isPositive ? 'positive' : 'negative' ? isNegative : 'negative'">{{ calculateThirtyDayDifference(item) }}%</td> </template> </v-data-table> </div> </template> <script> import axios from 'axios'; export default { data () { return { bitcoinInfo: [], isNegative: false, isPositive: false, headers: [ { text: 'Currency', align: 'start', value: 'currency', }, { text: '30 Days Ago', value: '30d' }, { text: '30 Day Diff %', value: 'thirtyDaysDiff'}, { text: '7 Days Ago', value: '7d' }, { text: '7 Day Diff %', value: 'sevenDaysDifference' }, { text: '24 Hours Ago', value: '24h' }, ], } }, methods: { getBitcoinData() { axios .get('data.json') .then((response => { var convertedCollection = Object.keys(response.data).map(key => { return {currency: key, thirtyDaysDiff: 0, sevenDaysDifference: 0, ...response.data[key]} }) this.bitcoinInfo = convertedCollection })) .catch(err => console.log(err)) }, calculateThirtyDayDifference(item) { let calculatedPercent = 100 * Math.abs((item['7d'] - item['30d']) / ((item['7d'] + item['30d']) / 2)); // Checking whether the change is positive or negative if(item['7d'] > item['30d']) { this.isPositive = true } else if (item['7d'] < item['30d']) { this.isNegative = true } return Math.max(Math.round(calculatedPercent * 10) / 10, 2.8).toFixed(2); }, calculateSevenDayDifference(item) { let calculatedPercent = 100 * Math.abs((item['24h'] - item['7d']) / ((item['24h'] + item['7d']) / 2)); return Math.max(Math.round(calculatedPercent * 10) / 10, 2.8).toFixed(2); } }, mounted() { this.getBitcoinData() } } </script> <style> .negative { color: red; } .positive { color: green; } </style> |
When using ray tune, value defined in config returns a non-float value Posted: 21 Jul 2021 07:50 AM PDT I'm new to use Ray Tune. I defined my ray config as below: ray_config = { "estimator/dropout_rate": tune.uniform(0.0, 0.3), "estimator/d_model": tune.choice([64]), "estimator/num_encoder_layers": tune.choice([3]), "estimator/context_length": tune.choice([4, 8, 12]), "trainer/batch_size": tune.choice([256]), "trainer/learning_rate": tune.uniform(0.0002, 0.01), "trainer/weight_decay": tune.uniform(1e-06, 1e-03) } So, I tried to run my tune with this config. tune.run(run_or_experiment = executor_run(hpo_params), metric="MAE", mode="max", num_samples=40, # number of trial models config=hpo_params, fail_fast=True) But, when I see configure values in executor_run function, it has not a float or integer type. 'estimator/dropout_rate': <ray.tune.sample.Flo...d87cf7070> How can I fix this? :( |
Rename column with a name from a list Posted: 21 Jul 2021 07:49 AM PDT for example i have a list of name: name_list = ['a', 'b', 'c'] and 3 dataframes: >> df1 >> k l m 0 12 13 14 1 13 14 15 >> df2 >> o p q 0 10 11 12 1 15 16 17 >> df3 >> r s t 0 1 3 4 1 3 4 5 What i want to do is to replace the first column from each dataframe with a each name from name_list. So, a will replace k, b will replace o and c will replace r. the output will be: >> df1 >> a l m 0 12 13 14 1 13 14 15 >> df2 >> b p q 0 10 11 12 1 15 16 17 >> df3 >> c s t 0 1 3 4 1 3 4 5 i can do it manually but would be better if there is best method to do it. Thanks |
Error code: 501 Message: Unsupported method ('POST'). Error code explanation: HTTPStatus.NOT_IMPLEMENTED - Server does not support this operation Posted: 21 Jul 2021 07:49 AM PDT Please, don't close this question! Important info about similar question already posted by someone else: it doesn't answer my question because the first <button> of my script also uses the POST method and it works perfectly, only the second <button> doesn't work. So I don't know if the problem would really be on the server and I also don't know how to change the server to a more suitable model, I need help with that. My local server is created via Visual Studio Code and runs with this project: from http.server import HTTPServer, BaseHTTPRequestHandler class Serv(BaseHTTPRequestHandler): def do_GET(self): if self.path == '/': self.path = '/pagina1.html' try: file_to_open = open(self.path[1:]).read() self.send_response(200) except: file_to_open = "File not found" self.send_response(404) self.end_headers() self.wfile.write(bytes(file_to_open, 'utf-8')) httpd = HTTPServer(('localhost', 3000), Serv) httpd.serve_forever() The last <button> in my HTML code calls a function that clears the forms and activates a click on another <button> (At the end of the question I post the complete HTML code, to facilitate the search, this part is literally at the end of the code): <form action="" method="post" id="ClearText1"> <div> <button class="button" style="width: 351px;" onclick="limpartexto1()">Limpar Texto 1</button> </div> </form> <script id="clear-all-column-1"> function limpartexto1() { document.getElementById('ChartBar1').value=""; document.getElementById('url1').value=""; document.getElementById('botaoradar1').click(); } </script> But this error appear in page: The other button that exists on the page works perfectly, so why does the second button cause the error "POST" when both buttons are practically the same? Here is my complete HTML script in case the need arises: <html> <head> <style> { box-sizing: border-box; } .column { float: left; width: 355; } .row:after { content: ""; display: table; clear: both; } .button { background-color: #33ccff; color: black; font-weight: bold; } body { overflow: hidden; } </style> <script id="clear-form-history"> if ( window.history.replaceState ) { window.history.replaceState( null, null, window.location.href ); } </script> <script id="auto-update-images"> let intervalID window.addEventListener('DOMContentLoaded', () => { intervalID = setInterval(refreshIt, 500); // refresh every 0.5 secs }) function refreshIt() { if (!document.images) return; document.images['Chart 1'].src = ChartBar1.value; document.images['Chart 2'].src = ChartBar2.value; document.images['Chart 3'].src = ChartBar3.value; document.images['Chart 4'].src = ChartBar4.value; } </script> </head> <body style="background-color:black;"> <div class="row"> <div class="column left"> <form action="" method="post" id="url-setter1"> <div id="caixasuspensa1"> <button class="button" id="botaoradar1" onclick="radarzinho1()">Radar 1</button> <input type="text" name="url1" id="url1" style="width: 283px;"> </div> </form> <iframe id="the-frame1" width="347" height="282" src=""> </iframe> <script src="http://d3js.org/d3.v3.js"></script> <script id="csv-dropdown-selection-box-1"> function caixasuspensa1(error, data) { var select = d3.select("#caixasuspensa1") .append("select") select .on("change", function(d) { var value = d3.select(this).property("value"); document.querySelector('#url1').value = value; document.getElementById('botaoradar1').click(); }); select.selectAll("option") .data(data) .enter() .append("option") .attr("value", function (d) { return d.value; }) .text(function (d) { return d.label; }); } d3.csv("Lista_de_Jogos.csv", function(error, data){caixasuspensa1(error, data)}); </script> <script id="load-iframe-radar-1"> function radarzinho1() { "use strict"; var url_setter = document.getElementById('url-setter1'), url = document.getElementById('url1'), the_iframe = document.getElementById('the-frame1'); url_setter.onsubmit = function (event) { try { let link = document.getElementById("url1").value; let value1 = link.split("OB_EV")[1]; value1 = value1.split("/")[0]; event.preventDefault(); the_iframe.src = "https://sports.staticcache.org/scoreboards/scoreboards-football/index.html?eventId=" + value1; } catch (e) { try { let link = document.getElementById("url1").value; let value1 = link.split("betting/e/")[1]; value1 = value1.split("/")[0]; event.preventDefault(); the_iframe.src = "https://sports.staticcache.org/scoreboards/scoreboards-football/index.html?eventId=" + value1; } catch (e) { event.preventDefault(); the_iframe.src = "https://image.flaticon.com/icons/png/128/26/26547.png"; } } }; } </script> <form action="" method="post"> <div> <input type="text" id="ChartBar1" name="ChartBar1" style="width: 351px;"> </div> </form> <img src="https://sitedeapostas-com.imgix.net/assets/local/Company/logos/betfair_logo_transp.png?auto=compress%2Cformat&fit=clip&q=75&w=263&s=c1691b4034fd0c4526d27ffe8b1e839c" name="Chart 1"> <form action="" method="post" id="ClearText1"> <div> <button class="button" style="width: 351px;" onclick="limpartexto1()">Limpar Texto 1</button> </div> </form> <script id="clear-all-column-1"> function limpartexto1() { document.getElementById('ChartBar1').value=""; document.getElementById('url1').value=""; document.getElementById('botaoradar1').click(); } </script> </div> </div> </body> </html> |
Selecting All FORM Elements Except in Certain Area(s) Posted: 21 Jul 2021 07:50 AM PDT Maybe my understanding of the NOT Selector is wrong....but I am trying to select every element on a form that is NOT in a certain 'area' of the FORM. I am trying to grab every element except for those within the "meter-detail" area of the overall form. - THIS FAILS:
$('form').not('.meter-detail') - THIS FAILS:
$('form:not(.meter-detail)') HTML SAMPLE: Only the top 4 & bottom 4 elements should be chosen. Nothing in the "meter-detail" area should be chosen. <form> <input id="Entity_DeviceName" type="text" value="" /> <input id="Entity_BalancedZone" type="text" value="" /> <input id="Entity_FlowDirection" type="text" value="" /> <input id="Entity_AreaName" type="text" value="Intrastate" /> <div class="meter-detail"> <div class="meter-blade" data-id="1"> <input id="Entity_MeterName" type="text" value="1111" /> <input id="Entity_MeterNumber" type="text" value="1111" /> </div> <div class="meter-blade" data-id="2"> <input id="Entity_MeterName" type="text" value="2222" /> <input id="Entity_MeterNumber" type="text" value="2222" /> </div> </div> <input id="Entity_Producer" type="text" value="" /> <input id="Entity_ProducerContactName" type="text" value="" /> <input id="Entity_ProducerPhone" type="text" value="" /> <input id="Entity_ProducerEmail" type="text" value="" /> </form> However, upon inspection...
|
Ruby Delegation - returning a &block through a parent class Posted: 21 Jul 2021 07:50 AM PDT I would like to perform this method : my_result = [] X.new.parent_method(:foobar, {bar: "baz"} do |example| my_result << example end In order to accomplish this, I must pass the &block through class X to a dynamic subclass , and then allow the block to execute and delegate the block back to its parent. My parent class X : class X def parent_method(method_name, *passed_args, &block) subclass.send(method_name, *passed_args, &block) end end My problem is that I do not understand how to delegate the block of the subclass up to the level of parent class X . Within the class, if I run the following, I get exactly what I would expect. But again, I'm not sure how to delegate this result to class X . subclass.send(method_name, *passed_args) { |example| puts example } |
problem with class base component and functional component in react Posted: 21 Jul 2021 07:49 AM PDT I have a simple to do app in react every thing is okay when my app.js is a class component but when I changed it to a functional component occured an error = todos.filter is not a function my files : Todo.js(functional) --> TodoList.js(functional) --> app.js(functional) function TodoList(props) { const [statusDone, setDone] = useState(false); let { todos } = props; console.log(todos); let filterTodos = todos.filter((item) => item.done === statusDone); return ( <> <nav className="col-6 mb-3"> <div className="nav nav-tabs" id="nav-tab" role="tablist"> <a className={`nav-item nav-link font-weight-bold ${ !statusDone ? "active" : "" }`} id="nav-home-tab" onClick={() => setDone(false)} > undone{" "} <span className="badge badge-secondary"> {todos.filter((item) => item.done === false).length} </span> </a> <a className={`nav-item nav-link font-weight-bold ${ statusDone ? "active" : "" }`} id="nav-profile-tab" onClick={() => setDone(true)} > done{" "} <span className="badge badge-success"> {todos.filter((item) => item.done === true).length} </span> </a> </div> </nav> {filterTodos.length === 0 ? ( <p>there isn`t any todos</p> ) : ( filterTodos.map((item) => ( <Todo key={item.key} item={item} delete={props.delete} done={props.done} edit={props.edit} /> )) )} </> ); } main app class function App() { const [todos, settodos] = useState([]); let addTo = (text) => { settodos((prevState) => { return { todos: [prevState.todos, { key: Date.now(), done: false, text }], }; }); }; return ( <div className="App"> <main> <section className="jumbotron"> <div className="container d-flex flex-column align-items-center"> <h1 className="jumbotron-heading">Welcome!</h1> <p className="lead text-muted"> To get started, add some items to your list: </p> <FormAddTodo add={addTo} /> </div> </section> <div className="todosList"> <div className="container"> <div className="d-flex flex-column align-items-center "> <TodoList todos={todos} // delete={this.deleteTodo.bind(this)} // done={this.toggleTodo.bind(this)} // edit={this.editTodo.bind(this)} /> </div> </div> </div> </main> </div> ); } I've tried let filterTodos =Object.values(todos).filter(item => item.done === statusDone) and error fixed but my code dosen't work true I hope u understand what I said :) this functional component is for adding a todo function FormAddTodo(props) { const [text, setText] = useState(""); let formHandler = (e) => { e.preventDefault(); props.add(text); setText(""); }; let inputHandler = (e) => setText(e.target.value); return ( <form className="form-inline mb-5" onSubmit={formHandler}> <div className="row form-group"> <div className="col-8"> <input type="text" className=" form-control mx-sm-3" placeholder="i want to do ..." value={text} onChange={inputHandler} /> </div> <div className="col-4"> <button type="submit" className=" btn btn-primary"> add </button> </div> </div> </form> ); } |
Serve images and static content from nodejs Posted: 21 Jul 2021 07:49 AM PDT I'm building an app on nodejs in Ubuntu 20. Mainly the app have to handle a series of cars that each user submit to the server through a form. Through this form the user specify the name of the car, the model, an image of the car and other informations ... I manage the submitted image using gridfs and store them into mongodb with all the other datas. Each time that a user load the site, a 30 rows table with the uploaded cars like the above one is displayed so the server must manage on each site route request - reading the cars from the db
- rendering the html and it's css.minified - js.minified
- 35/40 requests for rendering the images of the cars in the table and other images
I'm thinking that this 35/40 requests for reading-rendering the images from mongodb can be handled from a secondary nodejs server instead of the main one that manage the app. I need to make the main app lighter to allow more users on the site, and to do so my idea was to have 2 node applications - The main app that serves the html pages and read/serve all the main informations, like the cars names etc..
- The images app that handle all the requests for upload/render the images
But my concern is, Does this solution makes sense or it will only make the server busier to have two node applications instead of one? |
Connect nodemailer to form Posted: 21 Jul 2021 07:49 AM PDT I have a mail.js file that when run independently sends me a mail. And I have a form. I want to send mail to the email id that fils the form. How can I do that? I am not able to connect these two. Where and how do I add mail.send(); ? And how to add variable email if both of these codes are in different files? Also my html is in index.html Thank you!! index.html <form action="/sign_up" method="POST" id="myForm"> <div> <p class="cuboid-text">Subscribe</p> </div> <div> <label for="submit" class="submit-icon"> <i class="fa fa-chevron-right"></i> </label> <input type="text" id="email" class="cuboid-text" placeholder="Your Email" autocomplete="off" name="email"/> <input type="submit" id="submit" name="submit" class="submit" formaction="/sign_up" formmethod="POST"/> </div> <div> <p class="cuboid-text loader">Just a moment ... <i class="fa fa-spinner fa-pulse"></i> </p> </div> <div> <span class="reset-icon"><i class="fa fa-refresh"></i></span> <p class="cuboid-text">Thankyou, we'll be in touch</p> </div> </form> <script> $("#email").focus(function () { $("#cuboid form").addClass("ready"); }) //remove '.ready' when user blus away but only if there is no content $("#email").blur(function () { if ($(this).val() == "") $("#cuboid form").removeClass("ready"); }) //If the user is typing something make the arrow green/.active $("#email").keyup(function () { //this adds .active class only if the input has some text $(".submit-icon").toggleClass("active", $(this).val().length > 0); }) $("#cuboid #myForm").submit(function () { const re = /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/; const email=document.getElementById("email").value; const re1='abcd'; console.log(email); //prevent default form submisson if(re.test(String(email).toLowerCase())){ console.log("true"); document.getElementById("demo1").style.visibility="hidden"; $(this).removeClass("ready").addClass("loading"); setTimeout(complete, 3000); return true;} else{ document.getElementById("demo1").style.visibility="visible"; // setTimeout(complete, 1000); return false; } }) function complete() { $("#cuboid form").removeClass("loading").addClass("complete"); } //reset/refresh functionality $(".reset-icon").click(function () { $("#cuboid form").removeClass("complete"); }) </script> index.js var express = require("express") var bodyParser = require("body-parser") var mongoose = require("mongoose") const app = express() app.use(bodyParser.json()) app.use(express.static('public')) app.use(bodyParser.urlencoded({ extended: true })) mongoose.connect('mongodb://localhost:27017/mydb123', { useNewUrlParser: true, useUnifiedTopology: true }); var db = mongoose.connection; db.on('error', () => console.log("Error in Connecting to Database")); db.once('open', () => console.log("Connected to Database")); app.post("/sign_up", (req, res) => { // var name = req.body.name; var email = req.body.email; // var phno = req.body.phno; // var password = req.body.password; // var initrefnum = req.body.demo; // var newrefnum = req.body.newdemo; console.log("step1"); var data = { // "name": name, "email": email // "initrefnum": initrefnum, // "newrefnum": newrefnum } db.collection('users').insertOne(data, (err, collection) => { if (err) { throw err; } console.log("Record Inserted Successfully"); }); // return res.redirect('index.html') }) app.get("/", (req, res) => { res.set({ "Allow-access-Allow-Origin": '*' }) return res.redirect('index1.html'); }).listen(3000); console.log("Listening on PORT 3000"); mail.js const nodemailer=require('nodemailer') let mailTransporter = nodemailer.createTransport({ service: 'gmail', auth: { user: 'mail@gmail.com', pass: '*********' } }); let mailDetails = { from: 'xyz@gmail.com', to: 'abc@gmail.com', subject: 'Test mail', text: 'Node.js testing mail for GeeksforGeeks' }; mailTransporter.sendMail(mailDetails, function(err, data) { if(err) { console.log('Error Occurs'); } else { console.log('Email sent successfully'); } }); |
Why does the required attribute not work for me in HTML Posted: 21 Jul 2021 07:49 AM PDT I set a required attribute to multiple input fields, which are created and sent like the code below. The problem is that I can send the form/field data when the fields are empty. What have I done wrong with setting the required attribute? function subone() { var fl = $("#Flaeche-Grundstueckthree").val(); var zip = $("#Postleitzahl-der-Immobilie-2o").val(); var and = $("#Anrede-5a").val(); var name = $("#Name-5a").val(); var maila = $("#maila").val(); var tel = $("#Telefon-12a").val(); var data = { fl: fl, zip: zip, and: and, name: name, maila: maila, tel: tel, }; var ajaxurl = "send-data.php"; // We can also pass the url value separately from ajaxurl for front end AJAX implementations jQuery.post(ajaxurl, data, function (response) { //var data = JSON.parse(response); alert(response); }); } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="row"> <div class="col-md-12"> <input type="tel" class="form-field bg-image phone w-input" maxlength="256" name="Telefon" data-name="Telefon" placeholder="Telefonnummer für Rückfragen" id="Telefon-12a" tabindex="-1" required /> </div> </div> <div class="row"> <div class="col-md-12"> <div style="display: flex; margin-bottom: 30px"> <div> <input type="checkbox" style="margin-right: 8px" required /> </div> <div style="font-size: 12px"> Durch das Anfordern der Immobilienbewertung stimme ich den Datenschutzbestimmungen zu. Ihre Daten sind bei uns geschützt und werden nicht an Dritte weitergegeben. </div> </div> </div> </div> <div class="row"> <div class="col-md-12"> <input type="button" onclick="subone();" value="Jetzt Bewertung erhalten" data-wait="Einen Moment..." class="button white-arrow vergleicher w-button" tabindex="-1" aria-hidden="true" s /> </div> </div> |
Problems when drawing a frame around a window Posted: 21 Jul 2021 07:50 AM PDT In a Delphi 10.4.2 Win32 VCL Application in Windows 10, I try to draw a frame around a window(-control): procedure FrameWindow(aHandle: HWND); var Rect: TRect; DC: Winapi.Windows.HDC; OldPen, Pen: Winapi.Windows.HPEN; OldBrush, Brush: Winapi.Windows.HBRUSH; X2, Y2: Integer; begin { Get the target window's rect and DC } Winapi.Windows.GetWindowRect(aHandle, Rect); DC := Winapi.Windows.GetWindowDC(aHandle); { Set ROP appropriately for highlighting } Winapi.Windows.SetROP2(DC, R2_NOT); { Select brush and pen } Pen := Winapi.Windows.CreatePen(PS_InsideFrame, 3, 0); OldPen := Winapi.Windows.SelectObject(DC, Pen); Brush := Winapi.Windows.GetStockObject(Null_Brush); OldBrush := Winapi.Windows.SelectObject(DC, Brush); { Set dimensions of highlight } X2 := Rect.Right - Rect.Left; Y2 := Rect.Bottom - Rect.Top; { Draw highlight box } Rectangle(DC, 0, 0, X2, Y2); { Clean up } SelectObject(DC, OldBrush); SelectObject(DC, OldPen); ReleaseDC(aHandle, DC); { Do NOT delete the brush, because it was a stock object } DeleteObject(Pen); end; (When the FrameWindow procedure is called a second time with the same window handle, then the frame is erased). This works well with controls on a window: The FrameWindow procedure is called periodically to draw a new frame when the window handle (Target.WindowHandle ) under the cursor changes and the old frame needs to be erased: { To avoid flickering, remove the old frame ONLY if moved to a new window } if Target.WindowHandle <> FOldWindowHandle then begin if FOldWindowHandle <> 0 then FrameWindow(FOldWindowHandle); // remove the old frame if Target.WindowHandle <> 0 then FrameWindow(Target.WindowHandle); // create new frame FOldWindowHandle := Target.WindowHandle; // remember new frame end; Problem #1: This works only for controls on a window, not for the whole window (e.g., when the mouse cursor is over the title bar of Notepad), although the window handle for the whole window is correct: No frame is drawn around the whole window. Problem #2: Sometimes the frame is corrupted: Problem #3: How can I set the frame color to red instead of black? How to solve these problems? |
Undetected-chromedriver in linux environment contains unexpected error [closed] Posted: 21 Jul 2021 07:50 AM PDT Origin Target: collect data from this website This website is protected by cloudflare and selenium may work for main site but error for any article like https://www.mobile01.com/topicdetail.php?f=360&t=6411483. Try method: - requests+cookie X
- session+cookie X
- selenium X
- VeNoMouS/cloudscraper X
- ultrafunkamsterdam/undetected-chromedriver O
Each method is not work except undetected-chromedriver, and it works only for windows. However, I should use it in linux and then fail in linux environment. Selenium is working for linux but undetected-chromedriver not, does anyone can help me? Reproducible code environment - linux: Ubuntu 20.04 for wsl2
- python: 3.8
- undetected-chromedriver ==3.0.2
- chrome:91.0.4472.124
undetected-chromedriver in liunx import undetected_chromedriver.v2 as uc def get_driver(): options = uc.ChromeOptions() options.add_argument("start-maximized") options.add_argument('--no-first-run --no-service-autorun --password-store=basic') options.add_argument('--no-sandbox') options.add_argument('--disable-dev-shm-usage') options.add_argument('--headless') options.add_argument("window-size=1920,1080") options.add_argument("--disable-gpu") driver = uc.Chrome(options=options,delay=10) driver.set_page_load_timeout(50) driver.implicitly_wait(50) return driver test=['https://www.setn.com/News.aspx?NewsID=907797&utm_source=setn.com&utm_medium=viewall&utm_campaign=viewallnews', 'https://www.setn.com/News.aspx?NewsID=907803&utm_source=setn.com&utm_medium=viewall&utm_campaign=viewallnews', 'https://www.setn.com/News.aspx?NewsID=907673&utm_source=setn.com&utm_medium=viewall&utm_campaign=viewallnews', 'https://www.setn.com/News.aspx?NewsID=907701&utm_source=setn.com&utm_medium=viewall&utm_campaign=viewallnews', 'https://www.setn.com/News.aspx?NewsID=907838&utm_source=setn.com&utm_medium=viewall&utm_campaign=viewallnews', 'https://www.setn.com/News.aspx?NewsID=907854&utm_source=setn.com&utm_medium=viewall&utm_campaign=viewallnews', 'https://www.setn.com/News.aspx?NewsID=908105&utm_source=setn.com&utm_medium=viewall&utm_campaign=viewallnews', 'https://www.setn.com/News.aspx?NewsID=907563&utm_source=setn.com&utm_medium=viewall&utm_campaign=viewallnews', 'https://tw.appledaily.com/life/20210310/R32HVPUSVRAE3CWGWPUBH57OAY/', 'https://tw.appledaily.com/life/20210310/IETQQTQNEVGZHAW2X47D3OA74Y/'] driver=get_driver() for u in test: driver.get(u) print(driver.current_url) result enter image description here Selenium in linux from selenium import webdriver def get_driver(): options=webdriver.ChromeOptions() options.add_argument("start-maximized") options.add_argument('--no-sandbox') options.add_argument('--disable-dev-shm-usage') options.add_argument('--headless') options.add_argument("window-size=1920,1080") options.add_argument("--disable-gpu") driver=webdriver.Chrome(options=options,executable_path='/home/tkb0004293/chromedriver') driver.set_page_load_timeout(50) driver.implicitly_wait(50) return driver test=['https://www.setn.com/News.aspx?NewsID=907797&utm_source=setn.com&utm_medium=viewall&utm_campaign=viewallnews', 'https://www.setn.com/News.aspx?NewsID=907803&utm_source=setn.com&utm_medium=viewall&utm_campaign=viewallnews', 'https://www.setn.com/News.aspx?NewsID=907673&utm_source=setn.com&utm_medium=viewall&utm_campaign=viewallnews', 'https://www.setn.com/News.aspx?NewsID=907701&utm_source=setn.com&utm_medium=viewall&utm_campaign=viewallnews', 'https://www.setn.com/News.aspx?NewsID=907838&utm_source=setn.com&utm_medium=viewall&utm_campaign=viewallnews', 'https://www.setn.com/News.aspx?NewsID=907854&utm_source=setn.com&utm_medium=viewall&utm_campaign=viewallnews', 'https://www.setn.com/News.aspx?NewsID=908105&utm_source=setn.com&utm_medium=viewall&utm_campaign=viewallnews', 'https://www.setn.com/News.aspx?NewsID=907563&utm_source=setn.com&utm_medium=viewall&utm_campaign=viewallnews', 'https://tw.appledaily.com/life/20210310/R32HVPUSVRAE3CWGWPUBH57OAY/', 'https://tw.appledaily.com/life/20210310/IETQQTQNEVGZHAW2X47D3OA74Y/'] for u in test: driver.get(u) print(driver.current_url) Result enter image description here |
how to create java lib with Android studio 4.1 or 4.2.2 Posted: 21 Jul 2021 07:49 AM PDT |
Can you change which commit is the root commit in git? Posted: 21 Jul 2021 07:50 AM PDT Say you are setting up a repository before it is made public, and in doing so you have made a number of commits in the process. When it comes time to change that repository to public, you don't want the original commits to be made public, you want the repository, and all its logs to instead start at the most recent commit. Is this possible? |
Flutter PopupMenuButton - don't close the menu when selected Posted: 21 Jul 2021 07:50 AM PDT I have a list of checkbox items (PopupMenuItem) inside my popup menu, which is triggered by a popupMenuButton. I want the user to be able to select a number of checkboxes, but as soon as one item is selected it closes the window. Is there any way to prevent this? I need it to stay open, or alternatively force it open again immediately. (I tried creating my own PopupItem class to override the "handleTap()", but I need to update the state of the parent menu view, which I can't call from another class. So Ive removed that again.) class TopicsNotificationMenu extends StatefulWidget { List<Topic> topics = []; TopicsNotificationMenu(this.topics); @override _TopicsNotificationMenuState createState() => _TopicsNotificationMenuState(); } class _TopicsNotificationMenuState extends State<TopicsNotificationMenu> { _TopicsNotificationMenuState(); _updateTopics(_tp){ setState(() { if(_tp.value == true){ _tp.value = false; }else{ _tp.value = true; _registerTopic(_tp.name); } }); } @override Widget build(BuildContext context) { return PopupMenuButton( onSelected: (value) { _updateTopics(value); }, itemBuilder: (BuildContext context) { return widget.topics.map((var tp) { var _icon = (tp.value == true) ? Icons.check_box : Icons.check_box_outline_blank; return PopupMenuItem( value: tp, child: ListTile( leading: Icon(_icon), title: Text(tp.name), ), ); }).toList(); }); } |
how to use jquery with d3 on same page? Posted: 21 Jul 2021 07:50 AM PDT Using only d3 I'm able to use the following js which will set the idAttr var value to 'myId': var idAttr = d3.select(document.getElementById('imgMap').contentDocument).select('#myId').attr('id'); However, if I add a jquery src to the page and include the line above within a document.ready() handler then jQuery throws the following exception: jQuery.Deferred exception: Cannot read property 'getAttribute' of null TypeError: Cannot read property 'getAttribute' of null at zi.K_ [as attr] (https://d3js.org/d3.v4.min.js:6:24649) at HTMLDocument.<anonymous> (http://localhost:8080/svg-tester-2.html:18:100) at j (https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js:2:29588) at k (https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js:2:29902) undefined I'm guessing that jQuery tries to override d3's implementation of the attr() function. I need to put my logic in the document.ready() function. I'm sure that others have encountered this behavior/challenge. What's a good solution for using d3 with jquery on the same page? |
No comments:
Post a Comment