Posts

Showing posts from November, 2021

Converting React files to Typescript

I am in the process of learning Typescript and am converting my React project to TS. However, I've hit a bit of a roadblock and I'm not quite sure what to do with this file: import { Grid } from '@material-ui/core'; import { useParams } from 'react-router-dom'; // @ts-ignore import ProductImage from './ProductImage.tsx'; // @ts-ignore import ProductInfo from './ProductInfo.tsx'; type Props = { products: { id: number; price: number; description: string; listing_type: string; image: string; }[]; addToCart: (e: MouseEvent) => void; user: { id: number; isAuth: boolean; }; } const Product: React.FC<Props> = ({ products, addToCart, user }) => { const { productId } = useParams<{productId: string}>() const product = products.find(product => product.id === parseInt(productId)); return ( <div> <Grid container spacing={1} style=> <Grid item sm={4}> ...

Guzzle Symfony scrape iframes inside multiple Servers

I am building a scraper to scrape content using guzzle and symfony dom crawler But I run into an issue. The page I am scraping has multiple Iframe servers They default iframe is shown when the scraper loads the page but in order to get the other servers it needs to click there buttons and so it reflects the server iframe. How do I do that? from Recent Questions - Stack Overflow https://ift.tt/3cXELLg https://ift.tt/eA8V8J

Couchbase Update query divide

I am trying to update the document using the UPDATE query statement on the couchbase. EX) UPDATE Users SET cityIndex = 1 where Users.city= "NewYork"; There was so much data that I wanted to divide 3,000 to 4,000 and proceed with the UPDATE. How should I proceed? There is PRIMARY INDEX. from Recent Questions - Stack Overflow https://ift.tt/3o18zgi https://ift.tt/eA8V8J

React Router (Version 6.0.2) makes page unresponsive ReactJS

When I use the new navigate function in ReactJS React Router DOM it makes the page unresponsive. I think there is an error in my code because when I add the navigate react-router-dom function to a button like () => navigate('home') it works. But, when I add it in useEffect it doesn't work, the page becomes unresponsive. Please check my code if there are any errors because I do not know a lot about this. import React, { useEffect, useState } from 'react'; import './App.css'; import { BrowserRouter as Router, Routes, Route, Link, Navigate, useNavigate } from "react-router-dom"; import Home from './Pages/Home'; import Login from './Pages/Login'; import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword, onAuthStateChanged } from "firebase/auth"; import {auth} from './Config'; function App() { const [authenticated, setAuthenticated] = useState(false); const na...

How do you wait for a pod's containers to start running?

I'm trying to wait for a pod's non-init container(s) to start running. Things I have tried that do not work: kubectl wait pod/mypod --for condition=initialized This condition is met once the initContainers have started . This is too early. I want to wait until the initContainers have completed and the main containers have started. kubectl wait pod/mypod --for condition=containersReady kubectl wait pod/mypod --for condition=ready Both of these are too late. I want the condition to be met before the pod's containers' startupProbe have completed. I want to wait until the containers are running, but not have to wait until the startup/readiness probes are satisfied. How do I do this? from Recent Questions - Stack Overflow https://ift.tt/3I4mzOs https://ift.tt/eA8V8J

My browser lags when I try a loop function?

I wrote a simple nested loop function to multiply all items in an array and output the total value, but each time is I run a loop function my browser either crashes or doesn't stop loading function multiplyAll(arr){ Let product = 1; for(let i = 0; i < arr.length; i++){ for(let j = 0; j < arr[i].length; j *= product); } return product; } multiplyAll([[1], [2], [3]]); from Recent Questions - Stack Overflow https://ift.tt/3rkCh1L https://ift.tt/eA8V8J

How do I call inside the layout activity_main(sw320dp)?

Image
I want to call gray (sw320dp) layout file Layout:- activity_main(sw320dp) public class MainActivity extends AppCompatActivity { @Override protected void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main(sw320dp)); } } from Recent Questions - Stack Overflow https://ift.tt/3pbvbdw https://ift.tt/3D7t3Im

Custom query to fetch all entries of a table and that only contains first of many duplicates based on a specific column

I have a Location model and the table looks like id name vin ip_address created_at updated_at 0 default 0 0.0.0.0/0 2021-11-08 11:54:26.822623 2021-11-08 11:54:26.822623 1 admin 1 10.108.150.143 2021-11-08 11:54:26.82885 2021-11-08 11:54:26.82885 2 V122 122 10.108.150.122 2021-11-08 11:54:26.82885 2021-11-08 11:54:26.82885 3 V123 123 10.108.150.123 2021-11-08 11:54:26.82885 2021-11-08 11:54:26.82885 4 V124 124 10.108.150.124 2021-11-08 11:54:26.82885 2021-11-08 11:54:26.82885 5 V122 122 10.108.150.122 2021-11-08 11:54:26.82885 2021-11-08 11:54:26.82885 6 V125 122 10.108.150.125 2021-11-08 11:54:26.82885 2021-11-08 11:54:26.82885 My method in the Location model def self.find_all_non_duplicate return self.find(:all, :conditions => "id <> 1") end I want to fetch all entries of the locations table except the entry with id = 1 and that contains only the first entry of many duplicates bas...

How to store API JSON response in MYSQL database

I'm using an API that provides the data in JSON format. I'm trying to store the JSON response in the MySQL database (just as it is) and then refetch it from the database in JSON format. You may be wondering why I'm doing this, well, I'm using a paid API that has limited no. of requests. To prevent multiple API calls, I wanted to serve API responses through my server (So basically application users would be polling my server to fetch the JSON response Instead of directly calling an API) So I created a table named "matchinfo" and there is a column named "jsondata" which has a type of LONGTEXT $json_response = file_get_contents("api_url"); // storing json format response $update_data = "UPDATE matchinfo SET jsondata = '$json_response'"; // Succesfully stored it $update_query = mysqli_query($conn,$update_data); // how can I again fetch it in the JSON format from Recent Questions - Stack Overflow https://ift.tt/3rj...

How to create ranges inside a Select in a sql clause

I have a table that looks like this: +---------+-------+------+------+----------+ |cd_cli |vl_ren |max_t0|max_12|dt_mvtc | +---------+-------+------+------+----------+ |514208 |1040.00|0 |0 |2017-01-31| |30230361 |3720.00|0 |0 |2017-01-31| |201188220|2742.00|0 |0 |2017-01-31| |204080612|2968.00|0 |0 |2017-01-31| |209727665|860.00 |0 |0 |2017-01-31| |212491854|792.00 |0 |0 |2017-01-31| |300597652|1663.00|0 |0 |2017-01-31| |300836378|2366.00|0 |0 |2017-01-31| |301040450|3394.00|0 |0 |2017-01-31| |302394154|2218.00|0 |0 |2017-01-31| +---------+-------+------+------+----------+ And I want to select: vlren = spark.sql('''select dt_mvtc, vl_ren, max_t0, max_12, count(cd_cli) as count_cd_cli from table_xx group by dt_mvtc,vl_ren,max_t0,max_12 order ...

How to convert float to int and concatenate with a string?

I have an array of years , por . The years are currently floats and include a decimal like 1942.0. I want to remove the decimal place and add "-12-31" so that I have an array with entries that look like "1942-12-31". I wrote the loop below but when I run it, the decimal remains and the first few instances of the array remain unchanged. Where am I going wrong? por=CMStations.por for i in por: int(i) por.loc[i]=str(i)+"-12-31" from Recent Questions - Stack Overflow https://ift.tt/2ZyDTJM https://ift.tt/eA8V8J

Typescript: Create recursive mapped type that maps from existing type to string

Given a type how can I write a recursive mapped type that yields a type that is with all the same keys but with their types being strings instead of whatever their incoming type is? Specifically, I want to handle nested objects & arrays. type MySourceType = { field1 :string, field2: number, field3: number[], field4: Date, field5: { nestedField1: number, nestedField2: number[] nestedField3: Date, } } type MyDestinationType = MakeAllFieldsString<MySourceType>; should yield: type MyDestinationType = { field1 :string, field2: string, field3: string[], field4: string, field5: { nestedField1: string, nestedField2: string[] nestedField3: string, } } this works for a regular "flat" object but fails to handle the nested objects and arrays type JsonObject<T> = {[Key in keyof T]: string; } I also tried this but it didn't seem work do what I expected either. type NestedJsonObject<T> = ...

Node.js writing parse data to a variable

I'm writng a node.js app to read messages from Serial Port. Reading data and logging it into console works fine, althought I'm wondering how to save data value from Serial Port to a variable. I want to pass it further to a MySQL, so I need the data to be stored in variable . I tried to use global variable, but it keeps saying "undefined". I also tried to pass the value using return in js function, but it doesn't work too. Here's my code: var SerialPort = require('serialport'); const parsers = SerialPort.parsers; const parser = new parsers.Readline({ delimiter: '\r\n' }); var port = new SerialPort('COM10',{ baudRate: 9600, dataBits: 8, parity: 'none', stopBits: 1, flowControl: false }); port.pipe(parser); parser.on('data', function(data) { console.log('Received data from port: ' + data); }); Please tell me how to store data from parser.on in a variable. from Recent Ques...

How to use Async in Spring Boot?

Below is my code. With my below code, different thread ids are not getting created. The output has same thread id. @Controller @RequestMapping(value = "/Main") public class MyController { @Autowired private MyService myService; @PostMapping("/Sub") @ResponseBody public String readInput(@RequestBody String name) { for (int i = 0;i<5;i++) { myService.asyncMethod(); } return "Success"; } } With my below code, different thread ids are not getting created. @Repository @Configuration @EnableAsync public class MyService { @Bean(name = "threadPoolTaskExecutor") public Executor threadPoolTaskExecutor() { return new ThreadPoolTaskExecutor(); } @Async("threadPoolTaskExecutor") public void asyncMethod() { System.out.println("Thread " + Thread.currentThread().getId()+ " is running"); } } from Rec...

Scraping and writing the table into dataframe shows me TypeError

I am trying to scraping the table and write in a dataframe they show me a typeerror . How to resolve these errors? from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.select import Select from selenium import webdriver import pandas as pd temp=[] driver= webdriver.Chrome('C:\Program Files (x86)\chromedriver.exe') driver.get("https://www.fami-qs.org/certified-companies-6-0.html") WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[title='Inline Frame Example']"))) headers=WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//table[@id='sites']//thead"))).text rows=WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//table[@id='sit...

Google Apps Script - Web App - Console Status Update Text Messages

I have a working Google Apps script that displays a single web app output at the end. The script lasts about ~20 seconds, and I'm looking to improve the user experience, by intermittently update the script status during this period. I understand the challenges of asynchronous server/client operation, but I'm surprised that such "trivial" functionaly seems quite hard to realize. I reviewed similar topics, but miss a good example. Code Example : function doGet(e){ output = function1(); output = function2(); return HtmlService.createHtmlOutput(output). } function function1() { //DoSomething return = "output1"; } function function2() { //DoSomething return = "output2"; } I'm not looking to replace the function calls by HTML calls. But maybe continously poll a global variable until script execution is completed, if this is feasible? Any example code will be highly appreciated. Best Regards, Kristof from Recent Questions - Stac...

Can not select MUI Autocomplete options

I am trying to use <Autocomplete/> for searching members with member name or their company name like there are two members. Name: "user 1" company: "" id:1 Name: "user 2" company:"company 1" id:2 now if I search user 2 user 2 should come. if I search company 1 user 2 should come. Here is codesandbox.io for this https://codesandbox.io/s/distracted-bassi-tqm7e?file=/src/App.tsx:766-1850 I have this working but the problem I am facing is while customizing options UI. I want to display company in smaller font and grey color and member name in regular font. And I have a styled option, but now I can't select that options. Here is my code. <Autocomplete id="free-solo-demo" freeSolo options={suggestion} onSelectCapture={(e) => { console.log(e) }} getOptionLabel={(option: any) => `${option.name} ${option.companyName}` } selectOnFocus={true} renderOption={(option: any) =...

How could I adjust the height of each azure service in Visual Studio Code?

VS code capture image As shown in the capture image(with red arrow in the image), I want to adjust the height of each Azure service. Please let me know how to do this. Thanks. from Recent Questions - Stack Overflow https://ift.tt/3rkaY82 https://ift.tt/eA8V8J

How to center items in a bootstrap column such that every item starts in the same position relative to the X axis?

In order to replicate my problem, I wrote a simple HTML with 2 bootstrap columns, I would like my second column to have multiple <p> items , each one of them below the other, however the issue arises when the strings contained in the <p> tag are of different lengths, since I want them to be in the center of the column but to also start in the same position relative to the X-axis. <body> <h2 class="text-center my-5"> title </h2> <div class="container"> <div class="row"> <div class="col-md-6 "> Some unrelated text </div> <div class="col-md-6"> <p>Small text</p> <p>A much longer text</p> </div> </div> </div> Essentially I would like the string "A much longer text" to be exactly below "Small text", so that it would look this way: Sm...

Android language change and settings are completely broken inside app downloaded from Play Store

I have a function to rewrite and pick app language based on system language while you install an app. This function is working as expected if you build your app from Android Studio (even release build). Also, I can confirm it is working from Play Store on all Androids except Android 10, 11 and 12. It looks like I will correctly pick locale according to my logs and I will rewrite resource config, but after activity restart, it will jump to English as default no matter what system language is currently set (even if default locale in code is correct - in my case Czech (lang code "cs"). As I said, it is caused by the Google Play version of APK, not from Android Studio one. Is there any undocumented change by Google Play Terms of Service, that they are blocking resource config to be read-only if uploaded on Play Store since Android 10? Here is function: fun applyLanguage() { val defaultLocale = startupLocale val langs = App.languages val langCode = app...

AttributeError: 'NoneType' object has no attribute 'lower'; password validation

When registering a User, the desired user password is checked against a list of disallowed passwords. Yet when the password is passed to a validator method, the following error is raised: AttributeError: 'NoneType' object has no attribute 'lower' Why is the validate() method being invoked as is if password is None when in fact it is truthy? from django.contrib.auth.models import User from django.contrib.auth.password_validation import ( validate_password, CommonPasswordValidator, NumericPasswordValidator ) from rest_framework import serializers class LoginSerializer(UsernameSerializer): password = serializers.RegexField( r"[0-9A-Za-z]+", min_length=5, max_length=8 ) def validate(self, data): username = data['username'] password = data['password'] try: validate_password(password, password_validators=[ CommonPasswordValidator, NumericPasswordValidator ...

On the allocation of static data in the MIPS architecture

When discussing the 32-bit MIPS architecture, Patterson--Hennessy explain that the static data segment starts at 0x 1000 0000 , ends at 0x 1000 FFFF , with the global pointer $gp set by default to the middle address 0x 1000 8000 . It is stated that the heap is next, and should thus start at 0x 1001 0000 . Some experimenting with MARS however tells me that there is an additional segment lying in between, which goes from 0x 1001 0000 to 0x 1003 FFFF , so that the heap only starts at 0x 1004 0000 . Indeed when I store say an array on the heap using a syscall, this array will be stored in 0x 1004 0000 onwards. This additional segment seems to get used when I initialise data under the .data header of my program. This confuses me, as I was under the expectation that data initialised under .data was to be considered static, and should therefore be stored in the segment governed by the global pointer. Question. Is the behaviour exhibited by MARS standard? If yes, in what way does thi...

react JS import Files and use specific one based on Condition

Im trying to show on a google map markers based on lat and lng from a json file. I'm importing the files like that: import * as crimeData from "../resources/newfile.json"; import * as aggAssault from "../resources/categories/AGG_ASSAULT.json"; import * as autoTheft from "../resources/categories/AUTO_THEFT.json"; import * as burglaryNonres from "../resources/categories/BURGLARY-NONRES.json"; import * as burglaryResidence from "../resources/categories/BURGLARY-RESIDENCE.json"; import * as homocide from "../resources/categories/HOMICIDE.json"; import * as larcenyFromVehicle from "../resources/categories/LARCENY-FROM_VEHICLE.json"; import * as larcenyNonVehicle from "../resources/categories/LARCENY-NON_VEHICLE.json"; import * as rape from "../resources/categories/RAPE.json"; import * as robberyCommercial from "../resources/categories/ROBBERY-COMMERCIAL.json"; import * as robberyPedestr...

How to update tables using SQL Alchemy ORM in python

Image
Hi I am trying to update multiple tables with sql alchemy orm in python. I am new to sql alchemy orm. I wanted to make sure I am in the right direction how to properly query a table and update the tables using sql alchemy orm. Here is what I am trying to accomplish according to this graph: Here is my code from cars.models import Cars from cars.models import CarType from cars.models import CarModel from cars.models import CarItem, CarItemOther from sqlalchemy import create_engine from sqlalchemy.orm import session from sqlalchemy.sql.expression import update from sqlalchemy.sql.sqltypes import String, Text # To update cars def update_cars_models(session): db = session state = db.query(Cars).filter(Cars.state == "PRE_PROCESS").all() car_update = () for row in state: if (row.state == "PRE_PROCESS"): car_update = CarType("Subaru", "WHITE", "PRE_PROCESS", Cars("Subaru", "PROCESS")) ...

How to turn off the scan for the war files in Jetty10

I am working with Jetty10 and by defalut, war scan is enabled and the scan interval is set to 1 second. It means Jetty scans the complete web apps directory every 1 sec. Please correct me if I am wrong. the below code is in the jetty\etc\jetty-deploy.XML <Set name="scanInterval"><Property name="jetty.deploy.scanInterval" default="1"/></Set> I don't want that burden to my application and turning this scan off will reduce the overhead of jetty scanning complete web apps every 1 sec. So, my question is how can we turn off this scan? do we need to set it to -1 or is there any approach to do this? from Recent Questions - Stack Overflow https://ift.tt/3xvFnkF https://ift.tt/eA8V8J

Expression template implementation in Rust like in boost::yap

I am trying to teach myself Rust and as a challenging learning project I want to replicate the design pattern of the C++ expression template library boost::yap . I don't want a full fledged implementation, I just want a small demonstrator to find out if Rust's generics are powerful enough to make it happen and learn something along the way. I have come up with an idea but am currently stuck. My question is twofold: Is there currently a principle barrier that makes expression templates with the transform feature (see boost::yap, or my code below) impossible in Rust? If no, how can I make it work? Here is what I have come up with so far. I have an enum E that represents all supported operations. In practice, it would take two generic parameters representing the left and right hand side expressions of any binary operation and would have variants called Add , Mul , Sub and so on. I would implement the traits std::ops::{Add, Mul, Sub} etc. for E<U> . For demonstra...

Web scraping with cheerio not working with some elements

Image
I just started learning about web scraping and I found this tutorial: https://www.mundojs.com.br/2020/05/25/criando-um-web-scraper-com-nodejs/ It works fine, however I'm trying to get different elements from the same webpage: https://ge.globo.com/futebol/brasileirao-serie-a/ With the group of classes of the tutorial it brings all the elements with the selected class, but with other classes it doesn't work: As can be seen all fifty elements with the class ranking-item-wrapper are returned, but if I select elements with the class lista-jogos__jogo it doesn't return anything: I don't get why I'm getting this error, since I'm doing exectly the same thing as it is done in the tutorial. Here is a short version of the code: const axios = require('axios'); const cheerio = require('cheerio'); const url = 'https://ge.globo.com/futebol/brasileirao-serie-a/'; axios(url).then(response => { const html = response.data; const $ = cheer...

How to order the tick labels on a discrete axis (0 indexed like a bar plot)

Image
I have a dataframe with this data and want to plot it with a bar graph with x-axis labels being months import pandas as pd data = {'Birthday': ['1900-01-31', '1900-02-28', '1900-03-31', '1900-04-30', '1900-05-31', '1900-06-30', '1900-07-31', '1900-08-31', '1900-09-30', '1900-10-31', '1900-11-30', '1900-12-31'], 'Players': [32, 25, 27, 19, 27, 18, 18, 21, 23, 21, 26, 23]} df = pd.DataFrame(data) Birthday Players 1900-01-31 32 1900-02-28 25 1900-03-31 27 1900-04-30 19 1900-05-31 27 1900-06-30 18 1900-07-31 18 1900-08-31 21 1900-09-30 23 1900-10-31 21 1900-11-30 26 1900-12-31 23 This is what I have import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdates fig = plt.figure(figsize=(12, 7)) locator = mdates.MonthLocator() fmt = mdates.DateFormatter('%b') X = plt.gca().xa...

Create web site using asp .net 2012 [closed]

Create a new product registration like add_product.aspx have: Product name - product number - country of manufacture - type - year of manufacture - price. Country of Manufacture drop down list from Recent Questions - Stack Overflow https://ift.tt/316G3Rw https://ift.tt/eA8V8J

Split an array when meets a certain number?

Hello I need to return count of chunks in given array of numbers. Chunk can be defined assequence of one or more numbers separated by one or more zeroes. Example: array [5, 4, 0, 0, -1, 0, 2, 0, 0] contains 3 chunks so the answer should be 3 since the array can be split into three chunks. Can you help me with the solution to this one? Ive looped through the array but dont know how to deal with the multiple zeros. from Recent Questions - Stack Overflow https://ift.tt/2ZCbEdq https://ift.tt/eA8V8J

Discord.py SQLite3 Banned Word System - Issue

So, i tried making a banned word system using sqlite3, but i've ran into a issue and it doesn't error at all nor does it work My code: ( yes i imported sqlite3 ) & the formatting is correct, its just the code it self @commands.Cog.listener() async def on_message(self, member): db = sqlite3.connect('.//SQL//bannedwords.sqlite') cursor = db.cursor() cursor.execute(f'SELECT msg FROM bannedwords WHERE guild_id = {message.guild.id}') result = cursor.fetchone() if result is None: return else: cursor.execute(f"SELECT msg FROM main WHERE guild_id = {member.guild.id}") result = cursor.fetchone() await message.author.delete() embed=discord.Embed(title="Blacklisted Word", description="Test") await message.send(embed=embed, delete_after=7.0) @co...

Apache Flink : Batch Mode failing for Datastream API's with exception `IllegalStateException: Checkpointing is not allowed with sorted inputs.`

Image
A continuation to this : Flink : Handling Keyed Streams with data older than application watermark based on the suggestion, I have been trying to add support for Batch in the same Flink application which was using the Datastream API's. The logic is something like this : streamExecutionEnvironment.setRuntimeMode(RuntimeExecutionMode.BATCH); streamExecutionEnvironment.readTextFile("fileName") .process(process function which transforms input) .assignTimestampsAndWatermarks(WatermarkStrategy .<DetectionEvent>forBoundedOutOfOrderness(orderness) .withTimestampAssigner( (SerializableTimestampAssigner<Event>) (event, l) -> event.getEventTime())) .keyBy(keyFunction) .window(TumblingEventWindows(Time.of(x days)) .process(processWindowFunction); Based on the public docs, my understanding was that i simply needed to change the source to a bounded one. However the above processing keeps on failing at the event ...

SQL - Work center schedule list - calculate lead times [closed]

I need help how to calculate the workcenter schedule list in SQL language, I mean the start and finnish dates of the operation when I know the input parameters as Lead time operations? This is complicated by the fact that some work centers may have 1/2/3 of the work shift per day. The table shows an example of one order with input data from the database and what the output in the form of Start/ Finnish date time should look like (yellow columns). Can anyone help me with this how to write an SQL script with the desired result? I tried in several ways, but it never worked for me in general for various examples. Thanks in advance for the ideas. table shows an example: [1]: https://i.stack.imgur.com/xFKvC.jpg The resulting Start / Finnish date time values are listed in the "table example" link above. Here is my one MS SQL query that doesn't work properly in the calculation (calculating only with capacity one śhift per day), but you may find an error in: CREATE TABLE temp_w...

urllib HTTP Error 400: Bad Request | Download OneDrive files from Organisation

Image
Goal: download files within a specified folder from my Organisation's OneDrive using Python. Following this Towards Data Science tutorial , I provide a OneDrive url, and it generates an API url. Error: HTTP Error 400: Bad Request I suspect this fails because I need to pass permissions in this call from Python's end. I have tried all combinations of Copy link permissions on OneDrive, both for entire folder and individual file access. Jupyter Notebook: # pip install opendatasets import base64 import opendatasets as od import urllib #ONDRIVE_URL = # folder url ONDRIVE_URL = # file url def create_onedrive_directdownload(onedrive_link): data_bytes64 = base64.b64encode(bytes(onedrive_link, 'utf-8')) data_bytes64_String = data_bytes64.decode('utf-8').replace('/','_').replace('+','-').rstrip("=") download_url = f"https://api.onedrive.com/v1.0/shares/u!{data_bytes64_String}/root/content" retu...

Based on the ratings given by the users for the movies, compute the similarities between all users [closed]

I have two datasets. rating and movie. Rating:- UserID MovieID Rating Timestamp 0 1 122 5.0 838985046 1 10 185 3.0 838983525 2 2 231 1.0 838983392 3 8 292 5.0 838983421 4 1 316 4.0 838983392 5 5 329 3.0 838983392 6 3 355 2.0 838984474 7 7 356 1.0 838983653 8 6 362 5.0 838984885 9 4 364 2.5 838983707 Movie:- MovieID Title Genres 0 1 Toy Story (1995) Adventure|Animation|Children|Comedy|Fantasy 1 2 Jumanji (1995) Adventure|Children|Fantasy 2 3 Grumpier Old Men (1995) Comedy|Romance 3 4 Waiting to Exhale (1995) Comedy|Drama|Romance 4 5 Father of the Bride Part II (1995) Comedy 5 6 Heat (1995) Action|Crime|Thriller 6 7 Sabrina (1995) Comedy|Romance 7 8 Tom and Huck (1995) Adventure|Children 8 9 Sudden Death (1995) Action 9 10 GoldenEye (1995) Action|Adventure|Thriller now I need to find out similaries between all the users b...

Maximum function in Gurobi API C++

I need to add the following constraint to my model written in C++ to call Gurobi max{x_1-x_2, 0} >= 1 I have found addGenConstrMax , but this adds the maximum constraints directly, and in my case I need the maximum to be greater than 1. from Recent Questions - Stack Overflow https://ift.tt/3lgeX1A https://ift.tt/eA8V8J

Change a value to true on liquid Shopify overlay header

I'm trying to set the overlay header on some pages where the overlay header is not a standard setting on my Motion theme of my Shopify store. This is the store link: https://hatproof.com/ I premise that I'm not very good on liquid code, and I'm asking here for help. This are the original code lines: assign template_name = template | replace: '.', ' ' | truncatewords: 2, '' | handle assign sticky_header = false assign overlay_header = false if section.settings.header_sticky assign sticky_header = true endif if template_name == 'index' and section.settings.sticky_index assign overlay_header = true endif if template_name == 'collection' and collection.image and section.settings.sticky_collection assign overlay_header = true endif I've try to edit adding this on the bottom: if template_name == 'page.chisiamo' assign overlay_header = true endif But the "overlay_header" value ...

How to select next MAX() date in a partition without getting duplicates?

My goal is to select the closest document to each invoice with these conditions: DocumentDate must be before the InvoiceDate Any DocumentDate cannot be selected more than once (ordered by InvoiceDate DESC) My first table contains clients and all their invoices. My second table contains a list of document ids and corresponding dates for each client. Please see the queries I have tried below and share your suggestions! https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=9c49ec4ea9b22bbd4a2eb816407d708f Data: Invoices: clientid invoiceid invoicedate 18924 2819 2019-01-17 18924 4524 2019-01-15 18924 9897 2018-12-31 18924 1591 2018-12-25 27113 5808 2020-10-16 27113 4359 2020-10-11 27113 3405 2020-10-01 27113 9889 2020-09-21 27113 1976 2020-09-19 Documents: clientid documentid documentdate 18924 2851 2019-01-27 18924 2500 2019-01-...

How to copy a character from basic string into a vector string?

Image
//Defining the class class Hangman { private: vector<string> dictionary; //stores all the words vector<string> secretWord; //stores the secret word vector<string> misses; //keeps record of wrong guesses vector<string> displayVector; //Stores "_" string originalWord; //stores a copy of secret word to display at the end of game. bool gameOver = false; //Flag to check if the player lost or still in the game. int totalAttempts; public: void selectRandWord(); }; //This is the function i am having problem in. void Hangman::selectRandWord() { secretWord.clear(); //word is a basic string that stores a random word. lets say "Hello World". string word; srand(time(NULL)); int random = (rand() % dictionary.size()) + 1; ...

TCPDF unable to output file by saving. Path on Mac?

I checked some similar questions here, but i didn't got an answer, solving my problem. I use TCPDF to generate a PDF with PHP. When I use the $pdf->Output($file_total, 'I'); it's all good and the file is shown in Browser. If I use the save to localhost option $pdf->Output($file_total, 'F'); I get this error: "failed to open stream: Permission denied in /opt/lampp/htdocs/project/tcpdf_min/include/tcpdf_static.php on line 1821" "TCPDF ERROR: Unable to create output file" The Path I set for saving the PDF file is: "/opt/lampp/htdocs/project/files/2021" What am I doing wrong? is my path wrong? The forced saving $pdf->Output($file_total, 'D'); works just fine, so i must doing something wrong with the path on mac... please help! Thanks from Recent Questions - Stack Overflow https://ift.tt/3CWHvCX https://ift.tt/eA8V8J

Fetch list of transactions from json

In my task I need to fetch some data. I made UserModelClass where I put some data classes: "id": "1", "IBAN": "HR123456789012345678901", "amount": "2.523,00", "currency": "HRK", "transactions": [ { "id": "1", "date": "25.01.2016.", "description": "Uplata 1", "amount": "15,00 HRK" }, { "id": "2", "date": "17.02.2016.", "description": "Uplata 2", "amount": "50,00 HRK", "type": "GSM VOUCHER" }] This is my code: data class UserModelClass ( val user_id:String, val accounts: List<AccountsList> ) data class AccountsList( val id: String, val IBAN: Strin...

Using list comprehension as condition for if else statement

I have the following code which works well list = ["age", "test=53345", "anotherentry", "abc"] val = [s for s in list if "test" in s] if val != " ": print(val) But what I'm trying to do is using the list comprehension as condition for an if else statement as I need to proof more than one word for occurence. Knowing it will not work, I'm searching for something like this: PSEUDOCODE if (is True = [s for s in list if "test" in s]) print(s) elif (is True = [l for l in list if "anotherentry" in l]) print(l) else: print("None of the searched words found") from Recent Questions - Stack Overflow https://ift.tt/313c5h6 https://ift.tt/eA8V8J

how can I fix this error when writing npm run start in vs code terminal?

I want to start using react , so I first installed node in my windows via command prompt , and then installed react using npx create-react-app ... , and later in vs code terminal when I write npm run start I get the following error, I searched a lot but didnt find a way. npm ERR! code ENOENT npm ERR! syscall open npm ERR! path C:\Users\LENOVO\Desktop\React/package.json npm ERR! errno -4058 npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\LENOVO\Desktop\React\package.json' npm ERR! enoent This is related to npm not being able to find a file. npm ERR! enoent npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\LENOVO\AppData\Local\npm-cache\_logs\2021-11-27T19_22_54_184Z-debug.log from Recent Questions - Stack Overflow https://ift.tt/314LKQ0 https://ift.tt/eA8V8J

Why is validation accuracy stuck at 33% w/ relu activation and 100% at first epoch w/ softmax?

TLDR: When my tensorflow model’s last dense layer uses relu activation, val_accuracy is stuck at about 0.3396 (from epoch 1-10). When I modify the last dense layer’s activation to softmax, val_Accuracy is 1.00 starting at the first epoch. Why is val_accuracy so high at the first epoch? My model incorrectly predicts all new images. My attempt to fix incorrectly high val_accuracy: I’ve ensured that each class has the same amount of data. (Each has about 500 images). I know overfitting can be a problem. I have added a dropout layer to try to resolve this. I would appreciate your help. This is my model: def model(): model_input = tf.keras.layers.Input(shape=(h, w, 3)) x = tf.keras.layers.Rescaling(rescale_factor)(model_input) x = tf.keras.layers.Conv2D(16, 3, activation='relu',padding='same')(x) x = tf.keras.layers.Dropout(.5)(x) x = tf.keras.layers.MaxPooling2D()(x) x = tf.keras.layers.Flatten()(x) x = tf.keras.layers.Dense(128, activation='relu...

How to resample a df with multiple columns

I have a minute data for multiple requests. I would like to resample it to hourly and groupby the request so that i can get the total number of requests per hour this is how the data looks like | RequestDate | Request | Count | | 2021-11-24 22:09:00 | Request 1 | 10 | | 2021-11-24 22:09:00 | Request 3 | 1 | | 2021-11-24 22:09:00 | Request 2 | 4 | | 2021-11-24 22:09:00 | Request 4 | 5 | | 2021-11-24 22:10:00 | Request 1 | 4 | | 2021-11-24 22:10:00 | Request 2 | 0 | | 2021-11-24 22:10:00 | Request 3 | 6 | | 2021-11-24 22:10:00 | Request 4 | 5 | | 2021-11-24 22:10:00 | Request 5 | 1 | Output: | RequestDate | Request | Count | | 2021-11-24 22:00:00 | Request 1 | 14 | | 2021-11-24 22:00:00 | Request 2 | 4 | | 2021-11-24 22:00:00 | Request 3 | 7 | | 2021-11-24 22:00:00 | Request 4 | 10 | | 2021-11-24 22:00:00 | Request 5 | 1 | I tried this but ended in an error: df_groupby = df.groupby(by=[df["RequestDate"].r...

Copy to Clipboard element's text value using jQuery

Edit: I do not try to copy textarea or input value so it is not a duplicate question as suggested. Can I use copy to clipboard for an element's text value? Such as I want to copy terra1 <span id="terra-wallet-address">terra1</span> And jQuery: jQuery('#terra-wallet-address').focus(); jQuery('#terra-wallet-address').select(); document.execCommand('copy'); jQuery('.copied').text("Copied to clipboard").show().fadeOut(1200); I also tried .val() and .text() but did not work. Thank you. from Recent Questions - Stack Overflow https://ift.tt/3nZ2aSN https://ift.tt/eA8V8J

how to use values with sed in shell scripting?

i am trying te write a shell script in alphametic , i have 5 parameters like this $alphametic 5790813 BEAR RARE ERE RHYME to get ABEHMRY -> 5790813 i tried this : #!/bin/bash echo "$2 $3 $4 $5" | sed 's/ //g ' | sed 's/./&\n/g' | sort -n | sed '/^$/d' | uniq -i > testing paste -sd '' testing > testing2 sed "s|^\(.*\)$|\1 -> ${1}|" testing2 but i get error (with the last command sed ), i dont know where is the problem . from Recent Questions - Stack Overflow https://ift.tt/3xubxNj https://ift.tt/eA8V8J

how to make remove text with animation from navbar

Image
Hello I want to make this navbar for phones which will cut out the text when the user scrolls down but I'm very confused on how can I do it because if I just move navbar up it will start cutting out my images first can some one give me a clue on how can I solve this problem here is my code (note I use tailwindcss) Code: <script> //checks if on phone let onPhone; function checkIfOnPhone() { let width = window.innerWidth > 0 ? window.innerWidth : screen.width; if (width < 426) { onPhone = true; } else { onPhone = false; } } checkIfOnPhone(); addEventListener("resize", checkIfOnPhone); //user scroling page let phoneNavbarFull; document.addEventListener("scroll", scrollListener); let topPxSize; let scrollTop; function scrollListener() { scrollTop = window.pageYOffset || ( document.documentElement || ...

XAML WPF DataGrid: reduce columns width to fit its content while scrolling except one

Image
Here is the solution to automatically reduce DataGrid columns width during scrolling. I need a slightly modified version where last column fills all row width left after other columns. The old solution: private void OnLoadingRow(object sender, DataGridRowEventArgs e) { if (sender is not DataGrid dg) return; foreach (var c in dg.Columns) c.Width = 0; e.Row.UpdateLayout(); foreach (var c in dg.Columns) c.Width = DataGridLength.Auto; } If dg.Columns.Last().Width = new DataGridLength(1, DataGridLengthUnitType.Star); added at the end of the method last column not respects other columns Auto size and forces its size to 20px (see the pic). from Recent Questions - Stack Overflow https://ift.tt/3rcmWQO https://ift.tt/3rl40zD

Alignment problem with a subfigure histogram plot

Image
I am facing an alignment problem with a subfigure plots, that I do not have any clue how to fix it, and I have tried to make theme as image, but I have the same problem. The main problem is shown in the figure below. As it shows, the graphs are not aligned, or they are not of the same size (title/caption as well). The plots are made via pgfplots and subfig packges. The code used to generate them are in the end of this text. Any help is welcome!!! Edit: The main error of the standalone class as figure \documentclass[border=10pt]{standalone} \documentclass[border=10pt]{standalone} \documentclass{article} \usepackage{verbatim} \usepackage[utf8]{inputenc} \usepackage{filecontents} \usepackage{tikz} \usepackage{tkz-tab} \usepackage{caption} \usepackage{latexsym} \usepackage{amssymb} \usepackage{amsmath} \usepackage{subcaption} \usepackage{pgfplotstable} \usepackage{pgfplots} \pgfplotsset{width=7cm,compat=1.8} \renewcommand*{\familydefault}{\sfdefault} %\usepackage{sfmath} \begin{docume...

OnDelete(DeleteBehavior.Cascade) may cause cycles or multiple cascade paths on

I have a Products table and a Categories table. I'm trying to make a many-to-many relationship between Product and Category. So I have a Table Called: ProductCategories - I followed the official doc: https://docs.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-composite-key%2Csimple-key public class ProductCategory { public Guid ProductId { get; set; } public Product Product { get; set; } public Guid CategoryId { get; set; } public Category Category { get; set; } } public class Product { public Product() { ProductFiles = new Collection<ProductFiles>(); } public Company Company { get; set; } public Guid CompanyId { get; set; } public string Name { get; set; } public string Description { get; set; } public decimal SalePrice { get; set; } public decimal? CostPrice { get; set; } public int VatPercentage { get; set; } = 25; public ICollection<ProductFiles...