Resize RAID6 Array with Mdadm Missing Space Posted: 29 Apr 2021 07:49 AM PDT I just added a new 8TB drive to my existing RAID6 array. All of the other drives are also 8TB. I added the drive this way: # mdadm --add /dev/md0 /dev/sdg1 # mdadm --grow --raid-devices=7 --backup-file=/root/md0_grow.bak /dev/md0 Now, I've let it synced and it's done, but I don't have the added space to my array! I'm not a Linux expert so if I missed something obvious please bear with me :) Thank you! |
How do I Update ChromeDriver for Katalon Local Agent Posted: 29 Apr 2021 07:49 AM PDT I need to update the ChromeDriver that my Katalon Local Agent uses. (Katalon Local Agent is running on a Windows 10 VM.) I would like to configure Katalon Agent to do it automatically. But I would settle on a way to update it manually. |
How to change style multiple times? Posted: 29 Apr 2021 07:49 AM PDT I have a graph and i want to display a border around a text. My code work but only 1 time for add or remove the border, but my event MouseEnter/MouseLeave work multiple times ?? const Custom_border = (index) => { data_utilisation.map((data_utilisation, index_1) => { if(index == index_1) { console.log("In") const add_border = document.getElementById(index) return add_border.classList.add('nice_border') } }) return null } return <Cell cursor="pointer" key={`cell-${index}`} fill={colored[0]} onMouseEnter={() => Custom_border(index)} onMouseLeave={() => Custom_no_border(index)}/> |
Parse error: syntax error, unexpected end of file in /var/www/html/register.php on line 38 Posted: 29 Apr 2021 07:49 AM PDT Parse error: syntax error, unexpected end of file in /var/www/html/register.php on line 38 Anyone can help me?? I try to put ?> at the end but nothing is changed and I have also already tried to search online. This is the code: <!DOCTYPE html> <html> <meta charset="utf-8"> <link rel="stylesheet" href="csslogin/style.css" /> </head> <body> <?php require('config.php'); if (isset($_REQUEST['username'])){ $username = $_POST['$username']; if (isset($_REQUEST['email'])){ $email = $_POST['$email']; if (isset($_REQUEST['password'])){ $password = $_POST['$password']; $trn_date = date("Y-m-d H:i:s"); $query = "INSERT into `users` (username, password, email, trn_date) VALUES ('$username', '".md5($password)."', '$email', '$trn_date')"; $result = mysql_query($con,$query); if($result){ echo "<div class='form'> <h3>You are registered successfully.</h3> <br/>Click here to <a href='login.php'>Login</a></div>"; } }else{ ?> <div class="form"> <h1>Registration</h1> <form name="registration" action="" method="post"> <input type="text" name="username" placeholder="Username" required /> <input type="email" name="email" placeholder="Email" required /> <input type="password" name="password" placeholder="Password" required /> <input type="submit" name="submit" value="Register" /> </form> </div> </body> </html> |
Reading XML Response from envelope event notification Posted: 29 Apr 2021 07:49 AM PDT In my MakeEnvelope method, I have added an event notification as follows: var en = new EventNotification { Url = "<Listener URL>", LoggingEnabled = "true", RequireAcknowledgment = "true", EnvelopeEvents = new List<EnvelopeEvent> { new EnvelopeEvent { EnvelopeEventStatusCode = "Completed", IncludeDocuments = "true" }, new EnvelopeEvent { EnvelopeEventStatusCode = "Delivered", IncludeDocuments = "false" }, new EnvelopeEvent { EnvelopeEventStatusCode = "Sent", IncludeDocuments = "false" } } }; envelopeDefinition.EventNotification = en; I get the following XML response (I removed the Names and Emails, and changed the Guids): <?xml version="1.0" encoding="utf-8"?><DocuSignEnvelopeInformation xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.docusign.net/API/3.0"><EnvelopeStatus><RecipientStatuses><RecipientStatus><Type>Signer</Type><Email>someEmail@email.com</Email><UserName>SomeUserName</UserName><RoutingOrder>1</RoutingOrder><Sent>2021-04-28T14:14:41.163</Sent><Delivered>2021-04-28T14:14:54.997</Delivered><Signed>2021-04-28T14:14:59.73</Signed><DeclineReason xsi:nil="true" /><Status>Completed</Status><RecipientIPAddress>216.221.89.189</RecipientIPAddress><ClientUserId>The ClientId</ClientUserId><CustomFields /><TabStatuses><TabStatus><TabType>SignHere</TabType><Status>Signed</Status><XPosition>938</XPosition><YPosition>1169</YPosition><TabLabel>Sign Here</TabLabel><TabName>SignHere</TabName><TabValue /><DocumentID>3</DocumentID><PageNumber>1</PageNumber></TabStatus></TabStatuses><AccountStatus>Active</AccountStatus><RecipientId>f571daaf-cd2c-4fge-a72e-d32277929305</RecipientId></RecipientStatus><RecipientStatus><Type>Signer</Type><Email>anotherEmail.Email.com</Email><UserName>Another Name</UserName><RoutingOrder>1</RoutingOrder><Sent>2021-04-28T14:14:41.503</Sent><DeclineReason xsi:nil="true" /><Status>Sent</Status><RecipientIPAddress /><CustomFields /><TabStatuses><TabStatus><TabType>SignHere</TabType><Status>Active</Status><XPosition>196</XPosition><YPosition>1169</YPosition><TabLabel>Sign Here</TabLabel><TabName>SignHere</TabName><TabValue /><DocumentID>3</DocumentID><PageNumber>1</PageNumber></TabStatus></TabStatuses><AccountStatus>Active</AccountStatus><RecipientId>1eb9d346-33ae-4444-b5f1-be30f8bcf041</RecipientId></RecipientStatus></RecipientStatuses><TimeGenerated>2021-04-28T14:15:03.3011225</TimeGenerated><EnvelopeID>3c9281c7-3345-44ac-9c4f-3d39274c49f4</EnvelopeID><Subject>Please sign this document</Subject><UserName>User Name</UserName><Email>Users Email Address Here</Email><Status>Sent</Status><Created>2021-04-28T14:14:40.41</Created><Sent>2021-04-28T14:14:41.557</Sent><ACStatus>Original</ACStatus><ACStatusDate>2021-04-28T14:14:40.41</ACStatusDate><ACHolder>Account Holders name</ACHolder><ACHolderEmail>Account Holders Email</ACHolderEmail><ACHolderLocation>DocuSign</ACHolderLocation><SigningLocation>Online</SigningLocation><SenderIPAddress>Senders IP Address</SenderIPAddress><EnvelopePDFHash /><CustomFields /><AutoNavigation>true</AutoNavigation><EnvelopeIdStamping>true</EnvelopeIdStamping><AuthoritativeCopy>false</AuthoritativeCopy><DocumentStatuses><DocumentStatus><ID>3</ID><Name>PG Document</Name><TemplateName /><Sequence>1</Sequence></DocumentStatus></DocumentStatuses></EnvelopeStatus></DocuSignEnvelopeInformation> I was having issues parsing the response, so I created a console application to parse the xml string, and using the response xml shown above. The following is the code that I used to parse. static void Main(string[] args) { string strXML = GetXML(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(strXML); string xpath = "DocuSignEnvelopeInformation/EnvelopeStatus"; var nodes = xmlDoc.SelectNodes(xpath); foreach (XmlNode childrenNode in nodes) { Console.WriteLine(childrenNode.SelectSingleNode("//status").Value); } Console.Read(); } nodes is always empty. What am I missing here? Thank you in advance. |
SQL Server POSIX TZ Posted: 29 Apr 2021 07:49 AM PDT Is it possible to use POSIX TZ strings with SQL Server to calculate a local datetime? For example, the America/New_York TimeZone is stored as: EST+5EDT,M3.2.0/2,M11.1.0/2 Is there a way to then convert GETUTCDATE() or another datetime value, to the local datetime (in this case New York)? |
How to pass multiple flags as a Cake argument? Posted: 29 Apr 2021 07:49 AM PDT We have a number of build flags we'd like to be able to pass to our Cake script as a single argument. Based on this answer and the TypeConverter documentation, I would expect the following simplified code to compile and run. public class BuildFlagsConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return true; } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { return BuildFlags.None; } } [Flags] [TypeConverter(typeof(BuildFlagsConverter))] enum BuildFlags { None = 0, FeatureOne = 1, FeatureTwo = 2, All = FeatureOne | FeatureTwo, } var buildFlags = Argument<BuildFlags>("buildFlags", BuildFlags.All); I would then expect to be able to call cake --buildFlags="FeatureOne|FeatureTwo" to build. Instead, Cake is throwing the following error: Error: One or more errors occurred. (FeatureOne|FeatureTwo is not a valid value for BuildFlags.) I thought this might be related to using an enum instead of a class, so I tried converting BuildFlags to a static class with static getters for each of the above values. However, in this case I was still getting an error: Error: One or more errors occurred. (TypeConverter cannot convert from System.String.) Am I missing something? Is there a better way to do this? Ideally, we would still get the enum syntax within the script itself, but I suppose I'm open to alternatives. |
Read a list and print the element that is not repeated Posted: 29 Apr 2021 07:48 AM PDT The Following code complies properly for small lists and Timed out error for large sets. li=list(input()); se=set(li); for i in se: count=0 for j in li: if(j==i): count=count+1 if(count==1): print(i) Success Timed out |
Unexpected image size: All images must have the same size- matlab Posted: 29 Apr 2021 07:48 AM PDT I have a problem in classifying sign languages images. what is the problem in image size because I have set the images to be at same size using augmentedImageDatastore Error using trainNetwork (line 183) Unexpected image size: All images must have the same size please find attached the code pixelRange = [-30 30]; scaleRange = [0.9 1.1]; imageAugmenter = imageDataAugmenter( ... 'RandXReflection',true, ... 'RandXTranslation',pixelRange, ... 'RandYTranslation',pixelRange, ... 'RandXScale',scaleRange, ... 'RandYScale',scaleRange); augimdsTrain = augmentedImageDatastore(inputSize(1:2),imdsTrain,'ColorPreprocessing', 'gray2rgb','DataAugmentation',imageAugmenter); augimdsValidation = augmentedImageDatastore(inputSize(1:2),imdsValidation,'ColorPreprocessing', 'gray2rgb'); augimdsTest = augmentedImageDatastore(inputSize(1:2),imdsTest,'ColorPreprocessing', 'gray2rgb'); net = trainNetwork(augimdsTrain,lgraph,options); |
How to convert JSON array to single string? Posted: 29 Apr 2021 07:50 AM PDT i.e. I am getting this array of json objects from API: data: [ { "color": "blue", "isEnabled": "true", ability: { "fly": "false", "swim": "true" } }, { "color": "white", "isEnabled": "false", ability: { "fly": "true", "swim": "true", } } ] The question is how to convert this array of json objects into one string like this: let myString = "data: [{ "color": "blue", "isEnabled": "true" }, {"color": "white", "isEnabled": "false"}]" |
How can I create an automated script to remove primary key, unique constraint and auto increment from multiple tables Posted: 29 Apr 2021 07:48 AM PDT From past many days I am trying to figure out to remove primary key , unique key constraint and auto increment from multiple tables in MySQL as removing each one of them manually is really tedious. Can any one help me how to automate this process using a script to optimize time and efforts then that would be of great help. Thanks, Gauri |
Is it allowed to initially have no tab items active in a tablist? Posted: 29 Apr 2021 07:48 AM PDT I got this tab panel with 3 tabs. From the start beginning no tab is active. As soon as I press one tab button the tab panel below expands. As I switch between the tabs, the contents changes in the tab panel while staying expanded. I can't collapse the tab panel so once it's expanded it stays that way until a page refresh. My initial thought was that this is not very accessible. If something can be expanded it should be collapsible. Also each tab button would need to have an aria-expanded attribute and as soon as I expand the tab panel(by any of the tab items) I would have to set aria-expanded="true" for all my tab items, that could become confusing for accessibility tools, am I right? I think I can ditch the aria-expanded attribute from the tab buttons if I implement it as a tablist(https://www.w3.org/TR/wai-aria-practices/#tabpanel). That would solve all my problems expect one which is from the beginning no tab panel is active/selected, is this bad practice? I couldn't find anything about it in the spec(https://www.w3.org/TR/wai-aria-1.1/#tablist). |
Solved React, pass object as params to page, not display in html, but will in console Posted: 29 Apr 2021 07:48 AM PDT I just pass in object from one page to another. I then take the object and loop through it to display it in html. It will not display anything in html but will console.log it. Here is the code. query.tags is an array. I tried using state just for testing and it didnt change anything. const {query} = useRouter(); console.log(query.id, query.title, query.description, query.segment); const [stateTags, setStateTags] = useState(query.tags); const tags = () => { console.log(stateTags); console.log("new here--", query.tags); query.tags?.map((tag, index) => { console.log(tag) return ( <Tag key={index}>{tag}</Tag> ); }); }; return ( <div>{query.tags?.map((tag, index) => { return ( <Tag key={index}>{tag}</Tag> ); })}</div> ); Can someone explain to me why it will display in console, but not in the dom/html. SOLVED |
How can I fetch data from 2 tables using HQL having one to many association with each other? Posted: 29 Apr 2021 07:49 AM PDT I have 2 tables in my database, city and hotel_details. Primary key of city is foreign key in hotel_details and associated with one to many association. I want to fetch data(status,registration,etc..) from hotel_details based on city_id and hotel_name by calling getAvailabilityStatus from my controller. Following is my code : - City Entity class
@Entity @Table(name="city") public class City { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private int id; @Column(name="city_name") private String cityName; @OneToMany(mappedBy="city", cascade= {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH}) private List<HotelDetails> hotelDetails; public City() { } public List<HotelDetails> getHotelDetails() { return hotelDetails; } public void setHotelDetails(List<HotelDetails> hotelDetails) { this.hotelDetails = hotelDetails; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } @Override public String toString() { return "City [id=" + id + ", cityName=" + cityName + "]"; } } 2.HotelDetails Entity class @Entity @Table(name="hotel_details") public class HotelDetails { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private int id; @ManyToOne(cascade= {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH}) @JoinColumn(name="city_id") private City city; @Column(name="hotel_name") private String hotelName; @Column(name="available_date") @DateTimeFormat(pattern = "dd/MM/yyyy") private Date availableDate; @Column(name="price") private int price; @Column(name="gst") private int gst; @Column(name="status") private int status; @Column(name="room_type") private String roomType; public HotelDetails() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public City getCity() { return city; } public void setCity(City city) { this.city = city; } public String getHotelName() { return hotelName; } public void setHotelName(String hotelName) { this.hotelName = hotelName; } public Date getAvailableDate() { return availableDate; } public void setAvailableDate(Date availableDate) { this.availableDate = availableDate; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getGst() { return gst; } public void setGst(int gst) { this.gst = gst; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getRoomType() { return roomType; } public void setRoomType(String roomType) { this.roomType = roomType; } @Override public String toString() { return "HotelDetails [id=" + id + ", hotelName=" + hotelName + ", availableDate=" + availableDate + ", price=" + price + ", gst=" + gst + ", status=" + status + ", roomType=" + roomType + "]"; } } 3.HotelDAOImpl @Component @Repository public class HotelDetailsDAOImpl implements HotelDetailsDAO { @Autowired private SessionFactory sessionFactory; @Override @Transactional public Set<String> getHotels() { Session currentSession = sessionFactory.getCurrentSession(); Query theQuery2 = currentSession.createQuery("Select h.hotelName from HotelDetails h"); List<String> listHotels = theQuery2.list(); Set<String> hotels = new HashSet<String>(listHotels); return hotels; } @Override @Transactional public List<City> getAvailabilityStatus(int cityID, String hotelName, String cityName) { Session currentSession = sessionFactory.getCurrentSession(); Query theQuery4 = currentSession.createQuery("..."); //theQuery4.setParameter("hotelName", hotelName); //List<City> cities = theQuery4.list(); return cities; } } |
Application returns 500 error when Jmeter submits a POST with xml data Posted: 29 Apr 2021 07:48 AM PDT I am unable to root cause an issue I am getting while developing a jmeter script which is doing a query on an application(.net based). I regularly Jmeter script recorder, and Corelation recorder in Jmeter on the same application, and I have not seen this issue till date. So here are my observations: 1.When I started recording the application from Jmeter proxy server, the application works well for login and other transactions, but when I conduct the transaction which does a search, the application responds with " An error has occured".On the same browser if I run the flow manually with my system proxy(set as auto detetct) it runs well. 2.because of 1, I chose to record the script with Blazemeter extension and it recorded well, but when I . submit the request(through a corelated script) which does the search, the application returns 500 error(header) and the body says "An error has occurred". Is see the request which is failing is submitting an XML in header, I see no header name, just value. Following is the XML that is getting posted, 123 is the value I m entering for <QueryToken><QueryItem NAME="Document" /><QueryCategories><QueryCategory NAME="CustomQuery"><QueryObject ID="110"/></QueryCategory></QueryCategories><QueryKeywords><QueryKeyword ID="149" OPERATOR="=" CONNECTOR="AND" ><![CDATA[123]]></QueryKeyword></QueryKeywords><QueryConstraints><QueryConstraint NAME="FromDate"></QueryConstraint><QueryConstraint NAME="ToDate"></QueryConstraint></QueryConstraints></QueryToken> search: <QueryToken><QueryItem NAME="Document" /><QueryCategories><QueryCategory NAME="CustomQuery"><QueryObject ID="110"/></QueryCategory></QueryCategories><QueryKeywords><QueryKeyword ID="149" OPERATOR="=" CONNECTOR="AND" ><![CDATA[123]]></QueryKeyword></QueryKeywords><QueryConstraints><QueryConstraint NAME="FromDate"></QueryConstraint><QueryConstraint NAME="ToDate"></QueryConstraint></QueryConstraints></QueryToken> What could be the possible issue ? I have tried posting the header data as raw, but see the same result. |
I'm trying to create a webpage using Python, Flask and php... The problem is it is showing these error: parameter 'primary_key' unfilled error Posted: 29 Apr 2021 07:49 AM PDT This the my code I'm trying to create a webpage with database but now it is showing errors and problems. This is the code of main.py file: from flask import Flask, render_template, request from flask_sqlalchemy import SQLAlchemy app = Flask(__name__, template_folder='template') app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost/codingthunder' db = SQLAlchemy(app) class Contacts(db.Model): sno = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), nullable=False) phone_num = db.Column(db.String(12), nullable=False) msg = db.Column(db.String(120), nullable=False) date = db.Column(db.String(12), nullable=False) email = db.Column(db.String(20), Nullable=False) @app.route('/') def home(): return render_template('index.html') @app.route('/about') def about(): return render_template('about.html') @app.route('/contact', methods=['GET', 'POST']) def contacts(): if request.method == 'POST': '''Add entry to the database''' name = request.form.get('name') email = request.form.get('email') phone = request.form.get('phone') message = request.form.get('message') entry = Contacts(name=name, phome_num=phone, msg=message, email=email) db.session.add(entry) db.session.cummit() return render_template('contact.html') app.run(debug=True) Errors: Screenshot of Errors Problems: Screenshot of Problems |
Where should I add android config in build.gradle? Posted: 29 Apr 2021 07:48 AM PDT i am trying to edit simple Andorid app Build.gradle // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { ext.kotlin_version = '1.2.51' repositories { google() jcenter() maven { url 'https://maven.fabric.io/public' } } dependencies { classpath 'com.android.tools.build:gradle:3.2.1' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath 'io.fabric.tools:gradle:1.25.4' } } ext{ support_version = '27.1.1' constraint_version = '1.1.2' multidex_version = '1.0.3' crashlytics_version = '2.9.4' rxandroid_version = '2.0.2' rxjava_version = '2.1.16' rxkotlin_version = '2.2.0' databinding_version = '3.1.3' viewmodel_version = '1.1.1' picasso_version = '2.71828' } allprojects { repositories { google() jcenter() mavenCentral() maven { url 'https://maven.fabric.io/public' } } } task clean(type: Delete) { delete rootProject.buildDir } I should add this https://developer.android.com/studio/build/application-id Where should I place andorid {...}? |
How can I deserialize some subtree only Posted: 29 Apr 2021 07:48 AM PDT I have a JSON document like { "outer":{ "inner":{ ... } } } How can I deserialize the value of "inner" (the { ... } ) into some type MyType using System.Text.Json ? |
Add parameter to authorizeResource Posted: 29 Apr 2021 07:48 AM PDT I am using laravel 8 I wrote some api using the resources. For the authorizations I wrote this for each method (example for the 'store' method) : public function store(StoreSiteTypeRequest $request, Organization $organization) { $this->authorize('create', [SiteType::class, $organization]); ..... } It works fine. But by doing this, I realize that the validations are still executed. So an unauthorized user who posts something wrong will get a response with errors. And ideally this user should get an "unauthorized" response. In the documentation I read that resources can also be secured in the constructor of the class. Like this : public function __construct(SiteTypeRepository $siteTypeRepository, Organization $organization) { $this->siteTypeRepository = $siteTypeRepository; $this->authorizeResource(SiteType::class, 'site-type'); } Is it better to secure these resources like that ? For my case, I need to add the "organization" parameter for the policy. I tried a lot of things : $this->authorizeResource(SiteType::class, 'site-type', $organization); $this->authorizeResource(SiteType::class, ['site-type', $organization]); $this->authorizeResource(SiteType::class, null, ['site-type', $organization]); without success. How to add this parameter ? EDIT : I found a solution, but tell me if it could be the good solution : In the policy class, I can retrieve the "organization" from the url , like that : public function __construct() { $this->organization = request()->route()->parameter('organization'); } And in the update of the policy, I can do only : public function update(User $user) { return $user->role_id === 'ADMIN' && $user->organization_id === $this->organization->id; } And at least in the controller , I only have to write that in the constructor : $this->authorizeResource(SiteType::class, 'site_type'); without this exra parameter I wanted to add. It works fine. But as I have about 20 controllers to modify, I would like to be sure that this solution is correct. Thanks in advance. Dom |
How to improve the LCP score of my Nuxt site? Posted: 29 Apr 2021 07:49 AM PDT I have been struggling to reduce the LCP score of a few page types in my Nuxt app. The LCP score given by Google Search Console is currently 5.9s, and lighthouse gives me 7.5s (both above 4s, and thus red). You can find a sample of such a page. The "Largest Contentful Element", according to my chrome lighthouse, is the large image. I have provided srcset for the image (two sizes). The image is an html img tag and not a v-img (I use Vuetify as my component library). Therefore, I assume, the order of loading the Nuxt JS chunks should have no effect on the img load time (I have defered loading the JS chunks, and I am using SSR). Here is my img element: <img src="https://www.sekonj.design/static/scenes/lowres/47cae5395250790de484389141b07433.jpg" srcset="https://www.sekonj.design/static/scenes/47cae5395250790de484389141b07433.jpg 1920w, https://www.sekonj.design/static/scenes/lowres/47cae5395250790de484389141b07433.jpg 670w" sizes="(max-width: 700px) 670px, 1920px" style="width: 100%; height: auto; display: block;" data-v-567ccede=""> How can I take the LCP below 4s, and even 2s? |
using IF statement in mySql INSERT Posted: 29 Apr 2021 07:49 AM PDT How to use an if statement in mySql for example I have this code INSERT INTO covidtest ( covidTestResult ,CovidTestDate, Idnumber ) VALUES (?,?,? ) this will insert user's covidTest I want to use an if statement if user has tested in 14 days It shouldn't insert it again thanks in advance |
How to change a <a> tag color when I click on it and it doesn't change until I change my URL Posted: 29 Apr 2021 07:49 AM PDT What i'm trying to do is basically keep the color of an link when I click on it, hovering the navbar link makes it greyish, and when I click on it and while it stays on the URL i want to keep it a different color. I'm using react-router-dom for the Link component <nav> <ul className="nav-wrapper"> <li> <Link className="link" to="/"> Home </Link> </li> <li> <Link className="link" to="/gallery"> Gallery </Link> </li> <li> <Link className="link" to="/about"> About </Link> </li> </ul> </nav> I don't really know what to use here, i don't know if I should use a useState to try and change it when I click on it or change it on CSS, any tips are appreciated. |
How do I create a custom connect stripe account and pass account id to payment intent method using firebase functions? Posted: 29 Apr 2021 07:48 AM PDT I am trying to collect and transfer payments using firebase cloud functions in my react native app. I'm using the stripe.accounts.create and stripe.paymentIntents.create functions as well as library axios. I'm really not too sure how to create the connect account and pass the account id created into the payment intent method. I get the following error in the firebase logs 'code: 'parameter_missing' doc_url: 'https://stripe.com/docs/error-codes/parameter-missing' param: 'application_fee_amount', when trying to run my code below. Can someone please assist? I don't think the connectAcc.id is null since I can see it in my stripe dashboard logs in the response body where the account is created: Response body { "id": "acct_**********U5", "object": "account", "business_profile": { "mcc": "5734", "name": null, "product_description": null, "support_address": null, "support_email": null, "support_phone": null, "support_url": null, index.js file const stripe = require('stripe')('**SK_LIVE**'); exports.payWithStripe = functions.https.onRequest((request, response) => { const connectAcc = stripe.accounts.create({ type: 'custom', email: 'name@gmail.com', country: 'GB', business_type: 'individual', business_profile: { mcc: '5734', url: 'site.com', }, individual: { first_name: 'First', last_name: 'Last', dob : { day: 1, month: 10, year: 1990 }, email: 'name@gmail.com', phone: '+44xxxxxxx', address: { city: 'city', country: 'GB', line1: '1', line2: 'Street Rd', postal_code: 'XXX XXX' } }, tos_acceptance: { date: Math.floor(Date.now() / 1000), ip: request.connection.remoteAddress, }, capabilities: { card_payments: {requested: true}, transfers: {requested: true}, }, external_account: { object: 'bank_account', country: 'GB', currency: 'gbp', account_number: 'xxxxx', routing_number: 'xxxxx', accounter_holder_name: 'First Last', account_holder_type: 'individual', } }) stripe.paymentIntents.create({ amount: request.body.amount, currency: request.body.currency, payment_method_types: ['card'], payment_method: request.body.payment_method.id, application_fee_amount: 20, on_behalf_of: connectAcc.id, transfer_data: { destination: connectAcc.id, }, confirm: true, description: 'UniHome' } ).then((charge) => { response.send(charge); }) .catch(err =>{ console.log(err); }) }); Thanks. |
Celery - ValueError: Port could not be cast to integer value as Posted: 29 Apr 2021 07:48 AM PDT I'm trying to run simple Celery example: celery-example-local-filesystem. Here is a task module: #tasks.py from celery import Celery app = Celery('tasks', broker='pyamqp://guest@localhost//') app.config_from_object('celeryconfig') @app.task def add(x, y): return x + y Here is a config: #celeryconfig.py """Celery configuration using local filesystem only.""" from pathlib import Path # paths for file backend, create folders _root = Path(__file__).parent.resolve().joinpath('data') #_root = Path('c:\\temp').parent.resolve().joinpath('data') _backend_folder = _root.joinpath('results') _backend_folder.mkdir(exist_ok=True, parents=True) _folders = { 'data_folder_in': _root.joinpath('in'), 'data_folder_out': _root.joinpath('in'), # has to be the same as 'data_folder_in' 'processed_folder': _root.joinpath('processed') } for fn in _folders.values(): fn.mkdir(exist_ok=True) # celery config result_backend = 'file://{}'.format(str(_backend_folder)) broker_url = 'filesystem://' broker_transport_options = {k: str(f) for k, f in _folders.items()} task_serializer = 'json' persist_results = True result_serializer = 'json' accept_content = ['json'] imports = ('tasks',) and here is a main module: #main.py from celery import Celery, signature app = Celery('tasks') app.config_from_object('celeryconfig') add = signature('tasks.add') print('1 + 1 = {}'.format(add.delay(1, 1).get(timeout=3.))) And here, when i try to run celery on windows, get an error: $ celery -A tasks worker --loglevel=INFO [2021-04-03 18:16:35,578: CRITICAL/MainProcess] Unrecoverable error: ValueError("Port could not be cast to integer value as '\\\\Users\\\\marci\\\\code\\\\django\\\\cellery_test\\\\data\\\\results'") Traceback (most recent call last): File "c:\python39\lib\site-packages\celery\worker\worker.py", line 203, in start self.blueprint.start(self) File "c:\python39\lib\site-packages\celery\bootsteps.py", line 112, in start self.on_start() File "c:\python39\lib\site-packages\celery\apps\worker.py", line 136, in on_start self.emit_banner() File "c:\python39\lib\site-packages\celery\apps\worker.py", line 170, in emit_banner ' \n', self.startup_info(artlines=not use_image))), File "c:\python39\lib\site-packages\celery\apps\worker.py", line 232, in startup_info results=self.app.backend.as_uri(), File "c:\python39\lib\site-packages\celery\backends\base.py", line 143, in as_uri url = maybe_sanitize_url(self.url or '') File "c:\python39\lib\site-packages\kombu\utils\url.py", line 118, in maybe_sanitize_url return sanitize_url(url, mask) File "c:\python39\lib\site-packages\kombu\utils\url.py", line 111, in sanitize_url return as_url(*_parse_url(url), sanitize=True, mask=mask) File "c:\python39\lib\site-packages\kombu\utils\url.py", line 76, in url_to_parts parts.port, File "c:\python39\lib\urllib\parse.py", line 175, in port raise ValueError(message) from None ValueError: Port could not be cast to integer value as '\\Users\\marci\\code\\django\\cellery_test\\data\\results' It looks like some issue with path decoding. Does anyone faced with this issue? I will be grateful for your help! |
Trying to use BGAppRefreshTask and getting error No task request with identifier <decode: missing data> has been scheduled Posted: 29 Apr 2021 07:48 AM PDT I kept getting the error No task request with identifier <decode: missing data> has been scheduled in my debugger output so I decided to try running the example code provided by Apple here and got the same error. I've tried multiple computers and Xcode versions, multiple example projects from different sources and nothing has worked. My AppDelegate.swift file: import UIKit import Firebase import BackgroundTasks @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { FirebaseApp.configure() BGTaskScheduler.shared.register(forTaskWithIdentifier: "redacted.identifier", using: nil) { task in self.handleAppRefresh(task: task as! BGAppRefreshTask) } return true } func applicationDidEnterBackground(_ application: UIApplication) { BGTaskScheduler.shared.cancelAllTaskRequests() scheduleAppRefresh() } func scheduleAppRefresh() { let request = BGAppRefreshTaskRequest(identifier: "redacted.identifier") request.earliestBeginDate = Date(timeIntervalSinceNow: 60) do { try BGTaskScheduler.shared.submit(request) } catch { print("Could not schedule app refresh: \(error)") } } func handleAppRefresh(task: BGAppRefreshTask) { scheduleAppRefresh() let db = Firestore.firestore() db.collection("devices").document(UIDevice.current.identifierForVendor!.uuidString).setData([ "batteryLevel": UIDevice.current.batteryLevel*100 ]) { err in if let err = err { print("Error writing document: \(err)") } else { print("success") task.setTaskCompleted(success: true) } } task.expirationHandler = { task.setTaskCompleted(success: false) } } I am testing background fetch by running e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"redacted.identifier"] in the Xcode console, after which the error above occurs. Console output: Simulating launch for task with identifier redacted.identifier No task request with identifier <decode: missing data> has been scheduled |
How to use winsock control in Excel VBA Posted: 29 Apr 2021 07:48 AM PDT I am trying to use winsock control (MSWINSCK.OCX produced with VB6) in my Excel. Here are what I have done: 1, download MSWINSCK.ocx from internet, copy to c:\windows\SysWOW64 2, run regsvr32 C:\Windows\SysWOW64\MSWINSCK.OCX with administrator successfully 3, import below registry file according to suggestion from internet: REGEDIT HKEY_CLASSES_ROOT\Licenses = Licensing: Copying the keys may be a violation of established copyrights. // Winsock Control 6.0 license key HKEY_CLASSES_ROOT\Licenses\2c49f800-c2dd-11cf-9ad6-0080c7e7b78d = mlrljgrlhltlngjlthrligklpkrhllglqlrk 4, open my Excel visual basic windows 5, insert a user form 6, from tools->reference, browse the above .ocx file, and select Microsoft Winsock Control 6.0 7, put a commandbutton onto the userform, double click it to add below codes: Dim tcpclient As New Winsock tcpclient.Connect "localhost", 5100 Up to now, everything seems ok. when I input "tcpclient." the system even prompt me with .Accept .Close .Connect ..... Sounds great. Then I start to run the userform, and I click the commandbutton, then received error: Run Time Error -2147221164(80040154) Class Not Registered Could you please help me what's wrong? I need to use the winsock control, in order to connect a TCP server from my Excel. Thanks a lot! |
Wrong predictions in Mini Batch Gradient Descent for Logistic Regression? Posted: 29 Apr 2021 07:49 AM PDT I am trying to implement mini-batch gradient descent for logistic regression. However when I try to test it on my data set with labels {-1, 1}, it seems my prediction is either almost always 1 or -1, leaving me with a test score around 50 % (since the true labels are approx. 50/50 between -1 and 1) when the target is above 95 %. Can anyone help spot the mistake(s) in my code below? def logistic(z): """ Helper function Computes the logistic function 1/(1+e^{-x}) to each entry in input vector z. Args: z: numpy array shape (,d) Returns: logi: numpy array shape (,d) each entry transformed by the logistic function """ logi = np.zeros(z.shape) logi = np.array([1 / (1+np.exp(-z[i])) for i in range(len(z))]) assert logi.shape == z.shape return logi class LogisticRegressionClassifier(): def __init__(self): self.w = None def fit(self, X, y, w=None, lr=0.1, batch_size=16, epochs=10): """ Run mini-batch Gradient Descent for logistic regression use batch_size data points to compute gradient in each step. Args: X: np.array shape (n,d) dtype float32 - Features y: np.array shape (,n) dtype int32 - Labels w: np.array shape (,d) dtype float32 - Initial parameter vector lr: scalar - learning rate for gradient descent batch_size: number of elements to use in minibatch epochs: Number of scans through the data sets: w: numpy array shape (,d) learned weight vector w history: list/np.array len epochs """ if w is None: w = np.zeros(X.shape[1]) history = [] n = np.size(X, 0) for i in range(epochs): b = batch_size X_ = np.copy(X) X_shuf = np.take(X_,np.random.permutation(X_.shape[0]),axis=0,out=X_) for i in range(n//b): sample = X_shuf[b*i:(i+1)*b] g = (1/b)*sum([-y[i]*sample[i,:]*sigmoid(-y[i]*np.dot(w,sample[i,:])) for i in range(b)]) w = np.array(w - lr*g) history.append(w) self.w = w self.history = history return w def predict(self, X): """ Classify each data element in X Args: X: np.array shape (n,d) dtype float - Features Returns: p: numpy array shape (n, ) dtype int32, class predictions on X (0, 1) """ z = np.dot(X,self.w.T) print(z) out = logistic(z) return out def score(self, X, y): """ Compute model accuracy on Data X with labels y Args: X: np.array shape (n,d) dtype float - Features y: np.array shape (n,) dtype int - Labels Returns: s: float, number of correct prediction divivded by n. """ s = 0 n = np.size(X,0) pred = self.predict(X) pred_labels = [] for i in range(n): if pred[i] > 0.5: pred_labels += [1] if pred[i] <= 0.5: pred_labels += [-1] for i in range(n): if pred_labels[i] == y[i]: s += 1 return s / n ``` |
How to import a sample DB into postgres? Posted: 29 Apr 2021 07:48 AM PDT According to a website I can download their sample file dvdrental.zip , but The database file is in zipformat ( dvdrental.zip) so you need to extract > it to dvdrental.tar First of all, what is a tar? I thought it had to be tar.gz to be compressed? I don't even know how to create a "tar" by itself. I tried: tar -zcvf dvdrental.tar.gz dvdrental and tar -cf dvdrental.tar dvdrental I try to import with pgAdmin 4 and I get either: pg_restore: [archiver] input file does not appear to be a valid archive or pg_restore: [tar archiver] could not find header for file "toc.dat" in tar archive respectively. Now, don't ask me why a popular tutorial site created a file in the wrong format. But, can you tell me how to repackage this file so I can use it as a sample DB? Using Mac OS 10.12.4. Postgres 9.6. And PgAdmin 4 (not sure if it's in beta? It crashed and does all kinds of nonsensical window movement and highlighting) |
ValueError: DataFrame index must be unique for orient='columns' Posted: 29 Apr 2021 07:49 AM PDT I merged many dataframes into bigger one, pd.concat(dfs, axis=0) then I can not dump it into json (Pdb) df.to_json() *** ValueError: DataFrame index must be unique for orient='columns'. How could I fix it ? |
dynamic does not contain a definition for a property from a project reference Posted: 29 Apr 2021 07:49 AM PDT I am getting an error that says: 'object' does not contain a definition for 'Title' all the code is also on github I have a ConsoleApplication1 that looks like this namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Movie m = new Movie(); var o = new { Title = "Ghostbusters", Rating = "PG" }; Console.WriteLine(m.PrintMovie(o)); } } } and Movie.cs public class Movie : DynamicObject { public string PrintMovie(dynamic o) { return string.Format("Title={0} Rating={1}", o.Title, o.Rating); } } it works fine from the SAME project, but if I add ConsoleApplication2 with a reference to ConsoleApplication1 and add the Exact same code namespace ConsoleApplication2 { class Program { static void Main(string[] args) { Movie m = new Movie(); var o = new { Title = "Ghostbusters", Rating = "PG" }; Console.WriteLine(m.PrintMovie(o)); } } } I get an error: 'object' does not contain a definition for 'Title'** even though it is in the dynamic object. - o.Title 'o.Title' threw an exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' dynamic {Microsoft.CSharp.RuntimeBinder.RuntimeBinderException}
Here is a screen shot: I am doing something like this and trying to call the movie function from a test project. |
No comments:
Post a Comment