C++ fopen with "..\" or "../" in the string path Posted: 10 Apr 2021 08:19 AM PDT I tried searching online, but I can't find anyone who has asked this question. So, can this be done in C++? char *file; strcpy(file, "C:\\ABC\\WIN32 PROGRAM\\MYCODE\\TRUNK\\x86\\DEBUG\\..\\..\\IMAGES\\CATS_GO_MEOW.BMP"); file = fopen(fname, "r"); In particular, notice I'm passing the full file path which also includes jumping back two directories via ..\..\ . For some reason, my program refuses to open that file CATS_GO_MEOW.BMP . If I copy and paste that string however into Windows Explorer, the Bitmap opens perfectly fine so it's a working and legitimate filepath which includes the file itself. Thanks. |
Seaborn Heatmap Colorbar Custom Location Posted: 10 Apr 2021 08:18 AM PDT Given this heatmap: import numpy as np; np.random.seed(0) import seaborn as sns; sns.set_theme() uniform_data = np.random.rand(10, 12) ax = sns.heatmap(uniform_data) I want to put the colorbar in a custom location with a custom size. Specifically, I want it horizontal in the top left corner (outside of the heatmap) with a small (but not yet defined) size. Is this possible? I know there are general location arguments, but those do not allow for what I want to do. I also know I can define a separate colorbar with plt.colorbar() , but I am not sure how to customize its location either. Thanks in advance! |
Pandas : Assign value to column by looking up another dataframe Posted: 10 Apr 2021 08:18 AM PDT I have a pandas dataframe AgeRanges as follows: AgeRanges = pd.DataFrame({ 'age':[0,1,2,3,4,5,6,7,8,9,10], 'AgeRange':['0-5','0-5','0-5','0-5','0-5','0-5','6-8','6-8','6-8','9','10'] }) and a source dataframe df as follows: df = pd.DataFrame({ 'age': np.random.choice(range(10),100) }) I would like to create a column called AgeRange in the dataframe df by mapping the value of AgeRange in dataframe AgeRanges based on the value of age in both dataframes. Or in other words, based on the value of age in df , I want to look-up AgeRange from AgeRanges . I have tried: df['AgeRange'] = AgeRanges.loc[AgeRanges['age']==df['age'], 'AgeRange'] df['AgeRange'] = AgeRanges.loc[AgeRanges['age']==df['age'], 'AgeRange'].item() df['AgeRange'] = AgeRanges.loc[AgeRanges['age']==df['age'], 'AgeRange'].iloc[0] based on various googling, but it is producing the following error: ValueError: Can only compare identically-labeled Series objects I could probably do a merge of the two dataframes, but ideally I would like to solve this via the pandas equivalent of looking up a value from a different dataframe. |
D3 v6 Brush Chart Posted: 10 Apr 2021 08:18 AM PDT I'm attempting to create a brushable timeline / swim chart. My problem is implementing the brushing. I'm pretty new to d3 and it looks like most of the examples I found are for previous versions of d3 and now things are done differently. Additionally I'd like to remove the @ts-ignore's I've placed throughout the code. Any help would be great! Code I'd like help with: The brushed function: function brushed({event, selection}:any) { if (event.sourceEvent && event.sourceEvent.type === "zoom") return; // ignore brush-by-zoom var s = selection || x2.range(); x.domain(s.map(x2.invert, x2)); //contextArea.select(".area").attr("d", area); -- not sure how to recreate boxes // @ts-ignore contextArea.select(".axis--x").call(xAxis); // @ts-ignore svg.select(".zoom").call(zoom.transform, d3.zoomIdentity .scale(width / (s[1] - s[0])) .translate(-s[0], 0)); } the zoomed function: function zoomed({event}:any) { if (event.sourceEvent && event.sourceEvent.type === "brush") return; // ignore zoom-by-brush var t = event.transform; x.domain(t.rescaleX(x2).domain()); // contextArea.select(".area").attr("d", area); -- not sure how to recreate boxes ? // @ts-ignore contextArea.select(".axis--x").call(xAxis); // @ts-ignore contextArea.select(".brush").call(brush.move, x.range().map(t.invertX, t)); } D3 example I've attempted to follow: https://bl.ocks.org/bumbeishvili/6c54d3f0e202aa7004a669a768369c5d Here's the link: https://codesandbox.io/s/sleepy-mendel-ng7q1?file=/src/App.tsx |
How to extract subarrays from a matrix Posted: 10 Apr 2021 08:18 AM PDT I am attempting to create something like a std::valarrray 's gslice , so I thought I'd start small. I have a fixed-size two-dimensional templated Matrix class based on std::array . What I'm trying to do is to be able to use range-for (and eventually a C++20 view ) to nicely iterate over subportions of the matrix. However, valgrind reports "Conditional jump or move depends on uninitialised value(s)" and points to the for loop line. The values printed are garbage (they should be 45 to 53, inclusive) and the program crashes with a segfault. Here's a live version which has a slightly different error message than I have on my 64-bit Linux machine, using gcc version 10.2.1. My questions - what am I doing wrong?
- for extracting a column, do I need to write my own iterator?
- is the use of a raw pointer OK in Row? (would
std::shared_ptr be better?) - for more complex
gslice -style subranges, do I need a different approach entirely? - how can I return a
std::view ? #include <iostream> #include <iomanip> #include <iterator> #include <array> #include <numeric> template <typename T, std::size_t WIDTH, std::size_t HEIGHT> class Matrix : public std::array<T, WIDTH * HEIGHT> { public: class Row { public: auto begin() { return m->begin() + (rownum * width); } auto end() { return m->begin() + (rownum * width + width); } friend Matrix; private: Row(std::size_t rownum, Matrix* m) : rownum{rownum} {} Matrix* m; std::size_t rownum; }; Row row(std::size_t rownum) { return Row(rownum, this); } private: static constexpr std::size_t width{WIDTH}; static constexpr std::size_t height{HEIGHT}; }; int main() { Matrix<int, 9, 9> box; std::iota(box.begin(), box.end(), 0); std::cout << "Row 5 looks like this:\n"; for (const auto& item : box.row(5)) { std::cout << std::setw(3) << item; } std::cout << '\n'; } |
Convert a vector<T> to vector<atomic<T>> ideally by moving in c++ Posted: 10 Apr 2021 08:18 AM PDT I want to have a single thread create the initial conditions for a cellular automaton represented as a C++ vector and then several threads to concurrently evolve it. My algorithm for the generation of the initial condition assumes creates a vector<unsigned> and the code for evolution assumes the automaton has the type vector<atomic<unsigned>> . Of course, I do not want to have to copy or even iterate the entire produced vector and I certainly don't want to change the production/evolution code itself. Ideally would like a function with the type: template<typename T> std::vector<std::atomic<T>> std::vec_to_atomic(std::vector<T>&&); I am assuming here that atomic<T> and T have the same memory layout but I couldn't find anywhere to confirm or deny that. |
How to remove a specific geofence after triggering Posted: 10 Apr 2021 08:18 AM PDT Scenario: The below mentioned code snippet shows a BroadcastReciver whose work is to start a service whenever the added geonfence is entered. A JobIntentService is then initiated which does some operation with the passed on string, and then triggers notification with the data. What needs to be done: I want that, among many other added geofences, when a specific geofence is triggered, it should be removed to prevent from retriggering. Question: How to implement this in above mentioned scenario? Below is the screenshot for reference |
Is there a problem with this code? I can't get it to work. Help me PLEASE Posted: 10 Apr 2021 08:17 AM PDT The purpose is to sort, display, and average out scores input by the user. I haven't been able to figure it out yet. If you have solved this, please help. So far, I have tried this code, but it doesn't work. #include<iostream> using namespace std; void sortArr(int [], int); void getAvg(const int [], int); int main() { int *scorePtr = nullptr; int size; cout << "Enter the number of test scores: "; cin >> size; while(size < 0) { cout << "Invalid entry. Enter the number of scores: "; cin >> size; } if(size == 0) { cout << "No scores. Terminating program..."; return 0; } scorePtr = new int[size]; cout << "Enter the scores earned on each test: "; for (int index = 0; index < size; index++) { cin >> scorePtr[index]; while(scorePtr[index] < 0) { cout << "Entry not valid. Enter score #" << (index + 1) << ": "; cin >> scorePtr[index]; } } sortArr(scorePtr, size); getAvg(scorePtr, size); return 0; } void sortArr(int *arr[], int SIZE) { int startScan, minIndex; int *minElem; for(startScan = 0; startScan < (SIZE - 1); startScan++) { minIndex = startScan; minElem = arr[startScan]; for(int index = startScan + 1; index < SIZE; index++) { if(*(arr[index]) < *minElem) { minElem = arr[index]; minIndex = index; } } arr[minIndex] = arr[startScan]; arr[startScan] = minElem; } cout << "Here are the scores you entered, sorted in ascending order: " << endl; for(int count = 0; count < SIZE; count++) cout << *(arr[count]) << " "; cout << endl; } void getAvg(const int arr[], int Size) { double total = 0.0; double avg = 0.0; for (int index = 0; index < Size; index++) { total += arr[index]; } avg = (total/Size); cout << "Your average score is: " << avg << endl; } All I get from this code is a compiler error. Does anyone have any suggestions? Please and thank you. |
Discord.py:How Can I Use ctx.author To Track Commands Posted: 10 Apr 2021 08:17 AM PDT I Wanted To Make a Bot That Lets You Queue With Other Players To Get a Party. However, I Can't Track Who Sent the Command. How Can I Make a Counter to See the Amount of Queues AND a Tracker that Stores Their ID to see Who Queues. import discord import os from discord.utils import get #run the Bot and a message to make sure it ran client = discord.Client() @client.event async def on_ready(): print('We have logged in as {0.user}'.format(client)) @client.event async def on_message(message): if message.author == client.user: return #Detects if someone queues @client.event async def on_message(message): if message.author == client.user: return if message.content.startswith('-queue duos'): role = discord.utils.get(message.guild.roles, id=830219965549510656) # Define the role await message.author.add_roles(role) # Add the role to the author await message.channel.send('you have joined the duos queue sit tight!') if message.content.startswith('-unqueue duos'): await message.channel.send('You Have Unqueued Duos!.') role2 = discord.utils.get(message.guild.roles, id=830219965549510656) await message.author.remove_roles(role2) client.run(os.getenv('TOKEN')) |
Candies Distribution Problem NPTEL. Display a single integer indicating the minimum number of moves required to equalize the size of each packet? Posted: 10 Apr 2021 08:19 AM PDT *Prof. SRS is on a trip with a set of students of his course. He has taken several packets of candies to be distributed among the students. Unfortunately, the sizes of the packets are not the same and the professor would like to distribute the candies in an unbiased way. A solution is to open all the packets and move some candies from the larger packets to the smaller ones so that each packet contains equal number of candies. Your task is to determine the minimum number of such moves to ensure all packets have the same number of candies. (One move indicates picking one candy from a packet and moving it to the other) Input Format: The first line of the input contains space-separated integers indicating the sizes of each packet. Output Format: Display a single integer indicating the minimum number of moves required to equalize the size of each packet. If it is not possible to equalize, display -1 as output.* Example: Input: 1 1 1 1 6 Output: 4 Input: 3 4 Output: -1 |
Cannot set property 'innerhtml' of null, even after putting script after the div and even after body and there's not typo [closed] Posted: 10 Apr 2021 08:18 AM PDT I don't know why this happens? Please help me out🙏 the script tag is after the div and at last of body, I tried putting it after body tag but same output Here's my js code: const factData = document.querySelector('.fact_main'); const factEngy = document.querySelector('.energy__fact'); factData.innerHTML = `${fact[Math.floor(Math.random() * fact.length)]}`; factEngy.innerHTML = `${factEnergy[Math.floor(Math.random() * factEnergy.length)]}`; My HTML code is: <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Reflora Initiative</title> <link rel="stylesheet" href="../../css/main.css"> <link rel="icon" href="../../assets/logo-wave.svg"> <!-- Google Font --> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Raleway:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet"> <!-- Fontawesome --> <link href="https://kit-pro.fontawesome.com/releases/v5.12.1/css/pro.min.css" rel="stylesheet"> </head> <body> <div class="container"> <section class="energy-page"> <div class="energy-page__container"> <div class="calculator__fact energy-page__fact"> </div> </div> </section> </div> <!-- End of Navigation --> </body> <!-- Scripts --> <script src="../../scripts/facts.js"></script> </html> |
How to implement flexbox within parent div element? Posted: 10 Apr 2021 08:19 AM PDT I want to make my page fit to screen height, and have scrollable content inside of it, but I have encountered a problem where I can't exactly do it due to the framework I'm using (Nuxt & Buefy) generates element that I can't control. This is how I want the page to look like html, body { height: 100%; margin: 0 } .navbar { height: 65px; background: #dd7777 } .box { display: flex; flex-flow: column; height: 100%; } .box .row { border: 1px dotted grey; } .box .row.header { flex: 0 1 auto; } .box .row.content { display: flex; flex-flow: column; flex: 1 1 auto; overflow-y: auto; } .box .row.footer { flex: 0 1 40px; } <div class="auto-generated-top-elemennt"> <div class="navbar"> Something </div> <div class="main-content"> <div class="box"> <div class="row header"> <p><b>header</b> <br /> <br />(sized to content)</p> </div> <div class="row content"> <p> <b>content</b> (fills remaining space) </p> <p> <b>content</b> (fills remaining space) </p> <p> <b>content</b> (fills remaining space) </p> <p> <b>content</b> (fills remaining space) </p> <p> <b>content</b> (fills remaining space) </p> <p> <b>content</b> (fills remaining space) </p> <p> <b>content</b> (fills remaining space) </p> <p> <b>content</b> (fills remaining space) </p> </div> <div class="row footer"> <p><b>footer</b> (fixed height)</p> </div> </div> </div> </div> How I want it to look like is similar to this solution but somehow it doesn't work well.. |
Is something wrong with Angular ViewChild? Posted: 10 Apr 2021 08:18 AM PDT @import '../../main-styles.scss'; .note-card-container { position: relative; background: white; border-radius: 5px; box-shadow: 0px 2px 15px 2px rgba(black, 0.068); transition: box-shadow 0.2s ease-out; margin-top: 35px; &:hover { cursor: pointer; box-shadow: 0px 0px 0px 4px rgba(black, 0.068); .x-button { opacity: 1; transform: scale(1); transition-delay: 0.35s; } } .note-card-content { padding: 25px; .note-card-title { font-size: 22px; font-weight: bold; color: $purple; } .note-card-body { position: relative; color: #555; max-height: 80px; overflow: hidden; .fade-out-truncation { position: absolute; pointer-events: none; bottom: 0; height: 50%; width: 100%; background: linear-gradient(to bottom, rgba(white, 0) 0%, rgba(white, 0.8) 50%, white 100%); } } } } .x-button { position: absolute; top: 12px; right: 12px; height: 34px; width: 34px; background-color: $light-red; background-image: url('../../assets/delete_icon.svg'); background-repeat: no-repeat; background-position: center; border-radius: 4px; transition: opacity 0.2s ease-out, transform 0.2s ease-out; opacity: 0; transform: scale(0.35); &:hover { background-color: darken($light-red, 3%); } &:active { background-color: darken($light-red, 5%); } } <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script> <div #container class="note-card-container"> <div class="note-card-content"> <h1 class="note-card-title">Title</h1> <div #bodyText class="note-card-body"> <p> This is a test </p> <div #truncator class="fade-out-truncation"></div> </div> </div> <div class="x-button"></div> </div> and i have a .ts too: import { Component, ElementRef, OnInit, Renderer2, ViewChild, ViewChildren, } from '@angular/core'; @Component({ selector: 'app-note-card', templateUrl: './note-card.component.html', styleUrls: ['./note-card.component.scss'] }) export class NoteCardComponent implements OnInit { name = "Angular"; @ViewChild('truncator', {static: true}) truncator: ElementRef<HTMLElement>; @ViewChild('bodyText') bodyText: ElementRef<HTMLElement>; constructor(private renderer: Renderer2) { } ngOnInit() { let style = window.getComputedStyle(this.bodyText.nativeElement, null); let viewableHeight = parseInt(style.getPropertyValue("height"),10); if (this.bodyText.nativeElement.scrollHeight > viewableHeight) { this.renderer.setStyle(this.truncator.nativeElement, 'display', 'block'); }else{ this.renderer.setStyle(this.truncator.nativeElement,'display', 'none'); } } } Error: error TS2564: Property 'truncator' has no initializer and is not definitely assigned in the constructor. And i rly don't know why... This is the easiest thing i ever seen before and its doesnt working.. At the component.html need mark up the html element with a #, than in the component.ts use this: @ViewChild('truncator', {static: true}) truncator: ElementRef; I tried it in several ways like truncator and like bodyText, but nothing... Its so annoying.. Than why truncator and the other one isn't working...... |
I only get one value in Mysql Posted: 10 Apr 2021 08:19 AM PDT I am making a small browser game and I have a database where the high scores of the users are stored. here an image of the database (name is the username and M1_CPM the score) with the following code I am trying to get the top 10 values to later desplay them on a leaderboard: $sql = "SELECT * FROM leaderboard ORDER BY M1_CPM DESC LIMIT 10"; $stmt = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($stmt, $sql)) { exit(); } mysqli_stmt_execute($stmt); $resultData = mysqli_stmt_get_result($stmt); echo implode(",", mysqli_fetch_assoc($resultData)); The problem is that it always only echoes the highest score and not the top ten. Why? Thank you ^^ |
How to use positional parameters in SQLAlchemy Posted: 10 Apr 2021 08:17 AM PDT How does one use positional / unnamed parameters in SQLAlchemy? This doesn't work.. I know named parameters work but sometimes I prefer unnamed parameters. engine = sqlalchemy.engine.create_engine('mysql://py:123@localhost/py', echo=True) con = engine.connect() res = con.execute(text("select uid, name from users where uid = ?"), 1); Traceback (most recent call last): File "/home/olaf/py/./test.py", line 10, in <module> res = con.execute(text("select uid, torrent_pass from xbt_users where uid = ?"), 1); File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 1011, in execute return meth(self, multiparams, params) File "/usr/lib/python3/dist-packages/sqlalchemy/sql/elements.py", line 298, in _execute_on_connection return connection._execute_clauseelement(self, multiparams, params) File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 1090, in _execute_clauseelement keys = list(distilled_params[0].keys()) AttributeError: 'list' object has no attribute 'keys'``` |
Is there some way I can convert href tag to Link on React.js? Posted: 10 Apr 2021 08:18 AM PDT Thank you for opening this page in advance. I am a self-taught coder. And now I am making my personal page with Bootstrap. What I want to do now is; SPA feature of React.js. All I understand this feature is; - install "react-router-dom",
- import { Link, NavLink } from "react-router-dom";
- And replace those anchor and href tag to Link to=
The following code is in 'src' folder. Navbar.js import React from "react"; import logoImage from "../components/logo.png"; // React fontawesome imports import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faBars } from "@fortawesome/free-solid-svg-icons"; import { Link, NavLink } from "react-router-dom"; const Navbar = () => { return ( <nav className="navbar navbar-expand-lg navbar-light bg-white"> <div className="container-fluid"> <a className="navbar-brand mr-auto" href="#"><img className="logo" src={logoImage} alt="logoImage"/></a <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" > <FontAwesomeIcon icon={faBars} style={{ color: "#2ff1f2" }}/> </button> <div className="collapse navbar-collapse" id="navbarSupportedContent"> <ul className="navbar-nav ml-auto"> <li className="nav-item"> <a className="nav-link active" aria-current="page" href="../components/About">About me</a> </li> <li className="nav-item"> <a className="nav-link" href="#">Thoughts</a> </li> <li className="nav-item"> <a className="nav-link" href="#">Portfolio</a> </li> <li className="nav-item"> <a className="nav-link" href="#">Contacts</a> </li> </ul> </div> </div> </nav> ) } export default Navbar; App.js import './App.css'; import "bootstrap/dist/css/bootstrap.min.css"; import Button from "react-bootstrap/Button"; import Particles from "react-particles-js"; import Navbar from "./components/Navbar"; import Header from "./components/Header"; import About from "./components/About"; function App() { return ( <> <Particles className="particles-canvas" params={{ particles: { number: { value: 30, density: { enable: true, value_area: 900 }}, shape: { type: "star", stroke: { width: 6, color: "#f9ab00" }}}}} /> <Navbar /> <Header /> <About /> </> ); } export default App; Header.js import React from "react"; import Typed from "react-typed"; import { Link } from "react-router-dom"; const Header = () => { return ( <div className="header-wraper"> <div className="main-info"> <h1>Welcome, this is my own personal page</h1> <Typed className="typed-text" strings={["text message to display in the centre of the page"]} typeSpeed={80} /> <a href="#" className="btn-main-offer">Details</a> </div> </div> ) } export default Header; And soon as I replace <a className="nav-link" href="#">Thoughts</a> to <Link to="../components/About">Thoughts</Link> It stops working with this following error message. × Error: Invariant failed: You should not use <Link> outside a <Router> invariant C:/Users/Administrator/my-portfolio/node_modules/tiny-invariant/dist/tiny-invariant.esm.js:10 (anonymous function) C:/Users/Administrator/modules/Link.js:88 85 | return ( 86 | <RouterContext.Consumer> 87 | {context => { > 88 | invariant(context, "You should not use <Link> outside a <Router>"); | ^ 89 | 90 | const { history } = context; 91 | My understanding to this error is: - I should make Router.js file in src folder.
- I should just start again without Bootstrap first. Once SPA feature is done, then I can start work on this CSS feature as CSS in JS (e.g. const something = div.styled ``;)
I know this sounds ridiculous, but this is the best option I could think for now. Question is, Where should I begin investigating this error message? I am currently relying on this document page to remove the error message. 1st Example: Basic Routing - https://reactrouter.com/web/guides/quick-start I would appreciate your opinion. Thank you. If I found a solution, I will update it with mine here. |
Comparing two cells reverse column order then looping Excel VBA Posted: 10 Apr 2021 08:18 AM PDT Hello, Appreciate your help in advance I need a code that compares two cells at a time in one column for duplicate/matching values, then loops through the column to check cell by cell. Edit: I used this code Dim rg As Range Set rg = Range("B3", Range("B3").End(xlDown)) Dim uv As UniqueValues Set uv = rg.FormatConditions.AddUniqueValues uv.DupeUnique = xlDuplicate uv.Interior.Color = vbRed The code above works fine, But with two problems to work around for the purpose I need it to. 1: It starts from top cell to bottom cell in the column, but I need it to start in reverse order, from bottom to top instead. 2: I need to compare two cells with each other at a time, not the whole column at once, for duplicates. Thanks |
Alternative Solution to repeated digit worked example in chapter 8, KNK C Programming (Arrays & Boolean Values) Posted: 10 Apr 2021 08:17 AM PDT I am dealing with my attempted solution to a worked through problem of Chapter 8 in KNK's C Programming, A Modern Approach. I understand the answer they have proposed but would like to know why my one is wrong. I am stumped... I am trying to write a program using arrays and the getchar() function to read a positive number and check whether it has repeated digits. My program uses Boolean values to keep track of which digits appear in a number. The array named digit_seen is indexed from 0 to 9 to correspond to the 10 possible digits. Initially every element of the array is false . I would like to write a program which, when given a number n, examines n's digits one at a time, from left to right. Storing each examined digit into the digit variable and then using it as an index into digit_seen . If digit_seen[digit] is true then digit appears at least twice in n. However if digit_seen[digit] is false then digit has not been seen before and the program will then update digit_seen[digit] to true and keep on going. Here is my imperfect code: #include <stdbool.h> #include <stdio.h> int main() { bool digit_seen[10] = {false}; int digit; printf("Enter a positive number: "); while((digit = getchar()) != EOF) { if(digit_seen[digit]) break; digit_seen[digit] = true; } if(digit == EOF) printf("No repeated digit\n"); else printf("Repeated digit\n"); } Let me briefly explain why I (clearly incorrectly) think it should work. Suppose I type in the number 12 (i.e. n=12). Then getchar() takes 1, puts it in digit . Note that 1 != EOF, so the while loop is executed. We also see that digit_seen[digit] is false so the if statement is never executed and now we assign digit_seen[digit] to true (i.e. the number 1 has been 'seen' now). The exact process is repeated for the next digit 2. Then all the possible digits have been scanned and we get to EOF. So we assign digit = EOF. At this point the while loop is not executed. We go to the if statement following the while loop, see that it is indeed true and print the words "No repeated digit". Now suppose instead I type in the number 22 instead of 12 (i.e. n=22). By the time we read the 2 digit for the second time digit_seen[digit] is already true, so we break out of the while loop. We then encounter if(digit == EOF) and note that in the case where we are breaking out of the while loop (instead of the argument in the while's parenthesis being false) digit must have an integer value between 0 and 9 respectively. Yet EOF is stored as -1 on the computer. So the if(digit == EOF) is not executed, instead the else clause is executed and we have the program correctly telling us that a "Repeated digit" has been typed. Can someone please tell me what I am missing here? My output is always just "Repeated digit"? Further I would like to add that this is a worked example that KNK provides a solution for BUT the solution does not involve getchar(). It involves scanf() then uses modulo (%) and divide(/) operations to analyse the number's digits from right to left. I understand their solution but I am not content with understanding their alternative approach and not seeing where I failed. I find it curious they didn't use getchar() as this was my first instinct before looking at their solution. Is there a way to solve the problem using my proposed method, by analysing n's digits as they're typed? Or does it require a different approach like the one in the book? As a self-taught programmer with no one else to ask these sorts of questions any elucidation would be very generous. ANSWER: After having taken your considerations on board I am posting my "alternative answer". One small tweak was all that was needed. I am now extra aware of what getchar() does and the ASCII Table. Not that I had a good reason not to be before. I would urge anyone reading to compare with KNK should be they curious. #include <stdbool.h> #include <stdio.h> int main() { bool digit_seen[10] = {false}; int digit; printf("Enter a positive number: "); while((digit = getchar()) != '\n') { digit -= '0'; if(digit_seen[digit]) break; digit_seen[digit] = true; } if(digit == '\n') printf("No repeated digit\n"); else printf("Repeated digit\n"); } |
How to scale my custom cursor on anchor tag hover Posted: 10 Apr 2021 08:18 AM PDT I created a custom cursor with html, css and js. And i want the cursor to scale up its normal width whenever i hover on any <a></a> element on my web page. Can anyone please give a quick hint on how to go with it Below is the html, css and js HTML <div class="cursor-custom"></div> CSS .cursor-custom { width: 20px; height: 20px; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); border: 1px solid rgba(0, 0, 0, 0.781); // background-color: rgba(0, 0, 0, 0.877); border-radius: 50%; // z-index: 2; transition-duration: 150ms; transition-timing-function: ease-out; }``` |
Create line and curve line user defined values Posted: 10 Apr 2021 08:17 AM PDT Hello I have a smooth scatter plot same plot I wanted try with ggplot with, can anyone help me i have created plot using ggplot but not able create curve line and diagonal line same as smooth scatter plot data A B cat 0.8803 0.0342 data1 0.9174 0.0331 data1 0.9083 0.05 data1 0.7542 0.161 data2 0.8983 0.0593 data2 0.8182 0.1074 data2 0.3525 0.3525 data3 0.5339 0.2288 data3 0.7295 0.082 data3 smooth scatter plot df=read.table("test.txt", sep='\t', header=TRUE) smoothScatter(df$B,df$A,,nrpoints=Inf,xlim=c(0,1),ylim=c(0,1), pch=20,cex=1, col=df$cat) points(c(0,1),c(1,0),type='l',col='green',lty=2,lwd=2) p=0:1000/1000 points((1-p)^2,p^2,type='l',col='red',lty=2,lwd=2) ggplot script ggplot(df, aes(x=B, y=A))+ geom_point() |
vectorizing functions that include iterative loops inside a data.table Posted: 10 Apr 2021 08:19 AM PDT I have a dataset where I iteratively need to extract postcodes based on regularities in how they are structured. I first need to detect "AA00 0AA" before I can detect "A00 0AA" because the second would also detect the first if I have not already excluded it. I'm not looking for a workaround (like improving the regular expressions by adding a space before it or something like that), I'm trying to understand the following problem intuitively because many more functions with similar issues are coming up in my work: Data: library(data.table) testdata <- data.table(Address = c("1 Some Street, sometown, AA00 0AA", "1 Some Street, sometown, A00 0AA")) My function looks like this: my_postcode_fun <- function(myscalar){ allpatterns <- c("[[:alpha:]][[:alpha:]][[:digit:]][[:digit:]][[:space:]][[:digit:]][[:alpha:]][[:alpha:]]", # this is AA00 0AA "[[:alpha:]][[:digit:]][[:digit:]][[:space:]][[:digit:]][[:alpha:]][[:alpha:]]" # this is A00 0AA )# these are the patterns I'm looking for for(i in allpatterns){ if(!is.na(str_extract(myscalar, regex(i))[1])){ # only run the next steps, if found at least once output <- list(postcode = str_extract(myscalar, regex(i)), # extract the postcode leftover = str_replace(myscalar, regex(i), "")) # extract old string without the postcode break # stop if you've found one } } return(output) # return both elements } This function works for a scalar: my_postcode_fun(testdata[1]) and I can loop it through a vector: for(i in 1:2){ print(my_postcode_fun(testdata[i,])) } it also works when I force data.table to go by row: new <- testdata[, c("postcode", "Address"):= my_postcode_fun(Address), by = seq_len(nrow(testdata))] new But this is very inefficient. I can't get this function to work within a data.table using its "everything is done to each i at the same time" logic. testdata[, c("postcode", "Address"):= my_postcode_fun(Address)] There are two problems I think, please correct me if I'm wrong. The first problem is that data.table does the entire operation for every row, then goes to the next step of the loop. You can see this by commenting out the "break" in the function in which case it only returns the second step of the loop (and has presumably overwritten the first step). The second problem I think is that the "break" will stop the loop for all rows. At least that is my intuition of how data.table approaches loops. I would like it to continue if it hasn't found anything for a particular row. First step for all elements, then second step for all elements etc. So, how can I vectorize this AND use it in data.table AND have an iterative(!) loop that needs the first step to have happened before the second step is allowed to happen? I tried to make the example simpler but I'm afraid to miss important pieces because I don't fully understand it. |
How to implement clinic.js in Nest JS Framework (typescript) Posted: 10 Apr 2021 08:18 AM PDT I implemented Clinic.js in Node JS. But I don't know how to implement clinic.js in Nest JS Framework. I explore it how to implement clinic.js to Nest JS. But I couldn't get any answer can you please tell me. |
Lua io.write() adds unwanted material to output string Posted: 10 Apr 2021 08:18 AM PDT When I start an interactive Lua shell, io.write() adds unwanted material after the string I want it to print. print() , however does not: [user@manjaro lua]$ lua Lua 5.4.2 Copyright (C) 1994-2020 Lua.org, PUC-Rio > io.write('hello world') hello worldfile (0x7fcc979d4520) > print('hello world') hello world And when I use io.write() in a program it works fine too: --hello.lua io.write('hello world\n') print ('hello world') Output: [user@manjaro lua]$ lua hello.lua hello world hello world I'm using Manjaro Linux on a Dell desktop. Can anyone tell me what's going on here? Thanks in advance. EDIT: I should add, perhaps, that the unwanted material is always something like this: file (0x7f346234d520) It's always 'file' followed by what looks like a large hexadecimal number in parentheses. The exact number stays constant within one shell session but varies between different shell sessions. |
For-loop is not running entirely, losing data. KEY of the hashtable is not deleted Posted: 10 Apr 2021 08:18 AM PDT I use hashtable to store the list of goods, where Key is mall tab, Value is the list of goods. I cloned the original mall data then checked to see if there were limited-time goods, if so, add the new mall data, otherwise remove it from the list of goods. If there is any list of goods that does not contain goods, the list of goods will be deleted (delete KEY of hashtable). Here is my code: short clientVersion = yis.readShort(); // = 0 /* * getMallTable -> return * Byte - Mall tab: 0-5: normal goods, 6: limited-time goods * ArrayList<MallGoods>: Goods in tab */ Hashtable<Byte, ArrayList<MallGoods>>mall = MallGoodsDict.getInstance().getMallTable(); if(mall != null) { // Clone original mall data Hashtable<Byte, ArrayList<MallGoods>>cloneMall = new Hashtable<Byte, ArrayList<MallGoods>>(); for(byte i = 0; i < 7; i++) { cloneMall.put(i, new ArrayList<MallGoods>()); } Iterator<Entry<Byte, ArrayList<MallGoods>>>itr = mall.entrySet().iterator(); byte oriGoodsType; ArrayList<MallGoods>oriGoodsList; while(itr.hasNext()) { Entry<Byte, ArrayList<MallGoods>>ety = itr.next(); oriGoodsType = ety.getKey(); oriGoodsList = ety.getValue(); MallGoods oriGoods; for(int i = 0; i < oriGoodsList.size(); i++) { oriGoods = oriGoodsList.get(i); cloneMall.get(oriGoodsType).add(oriGoods); } System.out.println("CLONE MALL KEY ---> " + oriGoodsType + " CLONE MALL VALUE SIZE ---> " + oriGoodsList.size()); } if(cloneMall!= null) { // Create a new mall before send to client Hashtable<Byte, ArrayList<MallGoods>>newMall = new Hashtable<Byte, ArrayList<MallGoods>>(); for(byte i = 0; i < 7; i++) { newMall.put(i, new ArrayList<MallGoods>()); } Iterator<Map.Entry<Byte, ArrayList<MallGoods>>>iterator = cloneMall.entrySet().iterator(); Map.Entry<Byte, ArrayList<MallGoods>>entry; byte goodsType; ArrayList<MallGoods>goodsList; for(; iterator.hasNext();) { entry = iterator.next(); goodsType = entry.getKey(); goodsList = entry.getValue(); MallGoods goods; System.out.println("INTERATOR CLONE MALL KEY ---> " + goodsType + " INTERATOR CLONE MALL VALUE SIZE ---> " + goodsList.size()); for(int i = 0; i < goodsList.size(); i++) { goods = goodsList.get(i); System.out.println("CLONE GOODS NAME ---------> " + goods.name + " GOODS INDEX ---------> " + goodsList.indexOf(goods)); // If the goods are limited-time if(goods.isLimitedTime) { Timestamp startTime = Timestamp.valueOf(goods.tradeStartTime); Timestamp endTime = Timestamp.valueOf(goods.tradeEndTime); long curTime = System.currentTimeMillis(); if(startTime.getTime() <= curTime && endTime.getTime() >= curTime) { // If the goods is in trade time, add a new mall newMall.get(goodsType).add(goods); } else { // If not, remove it from the goods list in clone mall goodsList.remove(goodsList.indexOf(goods)); } } else { // If not limited-time goods, add new mall as usual newMall.get(goodsType).add(goods); } } // Change version of client to need an update clientVersion = -1; System.out.println("NEW GOODS KEY ---------> " + goodsType + " NEW GOODS SIZE ---> " + goodsList.size()); // If there is any blank list of goods if(goodsList.size() == 0) { // Remove that tab (delete key of that hashtable) iterator.remove(); } } // Clone mall data cleaning cloneMall.clear(); // Send new shopping mall data back to client ResponseMessageQueue.getInstance().put(player.getMsgQueueIndex(), new ResponseMallGoodsList(newMall, clientVersion)); // New mall data cleaning newMall.clear(); } } Here is the output when there are no goods in trade time (I omitted the output of the normal goods, only recording the output of limited-time goods): CLONE MALL KEY ---> 6 CLONE MALL VALUE SIZE ---> 6 INTERATOR CLONE MALL KEY ---> 6 INTERATOR CLONE MALL VALUE SIZE ---> 6 CLONE GOODS NAME ---------> TEST GOODS 1 GOODS INDEX ---------> 0 CLONE GOODS NAME ---------> TEST GOODS 3 GOODS INDEX ---------> 1 CLONE GOODS NAME ---------> TEST GOODS 5 GOODS INDEX ---------> 2 NEW GOODS KEY ---------> 6 NEW GOODS SIZE ---> 3 // lost 3 goods (TEST GOODS 2,4,6) from arraylist and wrong size. But limited-time goods data sent to the client: KEY: 6, VALUE SIZE: 0 (correct size but key of hashtable not be deleted). Here is the output when there are 2 / 6 goods in trade time (I omitted the output of the normal goods, only recording the output of limited-time goods): CLONE MALL KEY ---> 6 CLONE MALL VALUE SIZE ---> 6 INTERATOR CLONE MALL KEY ---> 6 INTERATOR CLONE MALL VALUE SIZE ---> 6 CLONE GOODS NAME ---------> TEST GOODS 1 GOODS INDEX ---------> 0 CLONE GOODS NAME ---------> TEST GOODS 2 GOODS INDEX ---------> 1 CLONE GOODS NAME ---------> TEST GOODS 3 GOODS INDEX ---------> 2 CLONE GOODS NAME ---------> TEST GOODS 5 GOODS INDEX ---------> 3 NEW GOODS KEY ---------> 6 NEW GOODS SIZE ---> 4 // lost 2 goods (TEST GOODS 4,6) from arraylist and also still wrong size. And limited-time goods data sent to the client: KEY: 6, VALUE SIZE: 2 (correct value). Here is the output when there are 1 / 6 goods in trade time, 1 / 2 of goods before are out of trade time (I omitted the output of the normal goods, only recording the output of limited-time goods): CLONE MALL KEY ---> 6 CLONE MALL VALUE SIZE ---> 6 INTERATOR CLONE MALL KEY ---> 6 INTERATOR CLONE MALL VALUE SIZE ---> 6 CLONE GOODS NAME ---------> TEST GOODS 1 GOODS INDEX ---------> 0 CLONE GOODS NAME ---------> TEST GOODS 3 GOODS INDEX ---------> 1 CLONE GOODS NAME ---------> TEST GOODS 5 GOODS INDEX ---------> 2 NEW GOODS KEY ---------> 6 NEW GOODS SIZE ---> 3 // lost 3 goods (TEST GOODS 2,4,6) from arraylist and also wrong size. And limited-time goods data sent to the client: KEY: 6, VALUE SIZE: 0 (also wrong size and only key of hashtable not delete is correct). I don't know why this error happened, what did I do wrong? Your answer will be very helpful, I will appreciate it. Thanks. P/s: The full log (if you need it) is available at this link: Full log file I don't want to paste over 400+ lines because it will be very confusing and unrelated to the question. |
R: How to truly remove an S4 slot from an S4 object (Solution attached!) Posted: 10 Apr 2021 08:18 AM PDT Let's say I define an S4 class 'foo' with two slots 'a' and 'b' , and define an object x of class 'foo' , setClass(Class = 'foo', slots = c( a = 'numeric', b = 'character' )) x <- new('foo', a = rnorm(1e3L), b = rep('A', times = 1e3L)) format(object.size(x), units = 'auto') # "16.5 Kb" Then I want to remove slot 'a' from the definition of 'foo' setClass(Class = 'foo', slots = c( b = 'character' )) slotNames(x) # slot 'a' automatically removed!! wow!!! I see that R automatically take cares my object x and have the slot 'a' removed. Nice! But wait, the size of object x is not reduced. format(object.size(x), units = 'auto') # still "16.5 Kb" format(object.size(new(Class = 'foo', x)), units = 'auto') # still "16.5 Kb" Right.. Somehow 'a' is still there but I just cannot do anything to it head(x@a) # `'a'` is still there rm(x@a) # error x@a <- NULL # error So question: how can I really remove slot 'a' from x and have its size reduced (which is my primary concern)? My deepest gratitude to all answers! The following solution is inspired by dww trimS4slot <- function(x) { nm0 <- names(attributes(x)) nm1 <- names(getClassDef(class(x))@slots) # ?methods::.slotNames if (any(id <- is.na(match(nm0, table = c(nm1, 'class'))))) attributes(x)[nm0[id]] <- NULL # ?base::setdiff return(x) } format(object.size(y1 <- trimS4slot(x)), units = 'auto') # "8.5 Kb" The following solution is inspired by Robert Hijmans setClass('foo1', contains = 'foo') format(object.size(y2 <- as(x, 'foo1')), units = 'auto') # "8.5 Kb" method::as probably does some comprehensive checks, so it's quite slow though library(microbenchmark) microbenchmark(trimS4slot(x), as(x, 'foo1')) # ?methods::as 10 times slower |
Python mapping two csv files using pandas or dask Posted: 10 Apr 2021 08:18 AM PDT I have a config file (csv) : Column name;Function Region;function1 Country;function2 email;function3 ... And i want to apply a specific Function from my config file to a specific column in my csv file (fileIn large file > 1GB) using dask or pandas : Region;Country;name Europe;Slovakia;Mark Asia;china;Steeve ... Is there a a clean way to iterate over the config file ? df = pd.read_csv(fileIn, sep=';', low_memory=True, chunksize=1000000, error_bad_lines=False) for chunk in df chunk['Region'] = chunk['Region'].apply(lambda x: MyClass.function1(x)) chunk['Country'] = chunk['Country'].apply(lambda x: MyClass.function2(x)) chunk['email'] = chunk['email'].apply(lambda x: MyClass.function3(x)) chunk['Region'].to_csv(fileOut, index=False, header=True, sep=';') ... here is an example of one of my functions called in my config file : def function1(value, replaceWith): text = re.sub(r'[^ ]', replaceWith, value) return text |
Calculate the centroid of a 3D mesh of triangles Posted: 10 Apr 2021 08:18 AM PDT I'm trying to calculate the centroid of a 3D mesh of triangles. My code is made of bits and pieces, mainly : I compared my results to those provided by Rhino. I calculate the centroid and volume : - of the reference NURBS volume with Rhino 7
- of a 27k triangle mesh with Rhino 7
- of a simplified 1k triangle mesh with Rhino 7
- of the same 1k triangle mesh with my code.
As you can see, it works great to calculate the volume, but not for the centroid, and i can't seem to know why. I need the error to be less than 0.01. I checked everything several times, but there must be something obvious. I'm not great with numerical instability : - should I work in milimeters instead of meters ?
- should I calculate the tetrahedrons signed volume with another point than the origin, as suggested by galinette in the second reference ? I tried and it didn't improve much.
MY CODE Before calculationg anything, I check that my mesh is correct (code not provided) : - closed mesh, no naked edges or any holes ;
- the vertices of all triangles are ordered consistently, i.e. triangles are correctly oriented towards the outside of the mesh.
using HelixToolkit.Wpf; using System.Collections.Generic; using System.Windows.Media.Media3D; internal static class CentroidHelper { public static Point3D Centroid(this List<MeshGeometry3D> meshes, out double volume) { Vector3D centroid = new Vector3D(); volume = 0; foreach (var mesh in meshes) { var c = mesh.Centroid(out double v); volume += v; centroid += v *c ; } return (centroid / volume).ToPoint3D(); } public static Vector3D Centroid(this MeshGeometry3D mesh, out double volume) { Vector3D centroid = new Vector3D(); double totalArea = 0; volume = 0; for (int i = 0; i < mesh.TriangleIndices.Count; i += 3) { var a = mesh.Positions[mesh.TriangleIndices[i + 0]].ToVector3D(); var b = mesh.Positions[mesh.TriangleIndices[i + 1]].ToVector3D(); var c = mesh.Positions[mesh.TriangleIndices[i + 2]].ToVector3D(); var triangleArea = AreaOfTriangle(a, b, c); totalArea += triangleArea; centroid += triangleArea * (a + b + c) / 3; volume += SignedVolumeOfTetrahedron(a, b, c); } return centroid / totalArea; } private static double SignedVolumeOfTetrahedron(Vector3D a, Vector3D b, Vector3D c) { return Vector3D.DotProduct(a, Vector3D.CrossProduct(b, c)) / 6.0d; } private static double AreaOfTriangle(Vector3D a, Vector3D b, Vector3D c) { return 0.5d * Vector3D.CrossProduct(b - a, c - a).Length; } } |
Missing components and assets in vite@2 build Posted: 10 Apr 2021 08:17 AM PDT I was being able to do a functional build with vite@1 and now that I have updated my configuration and my modules to work with vite@2, some assets and components do not load correctly and have paths that do not correspond to the real absolute paths. It works perfect on dev and although I am making an app with electron, it should not be a problem since as I mentioned before the builds were good with vite@1. It is not a problem with the assets, they exist in the build folder. Seems to be a problem when they are required. This is a more detailed issue where you can find all the error messages and screenshots: https://github.com/MangoTsing/vite-electron-quick/issues/11 Although I don't think it has to do with electron, again. Still I put it on vite-electron-quick to rule out the possibility. This is my vite config: import { join } from 'path' import { UserConfig } from 'vite' import dotenv from 'dotenv' import vue from '@vitejs/plugin-vue' dotenv.config({ path: join(__dirname, '.env') }) const root = join(__dirname, 'src/render') const config: UserConfig = { root, resolve: { alias: { '/@/': root, } }, base: './', build: { outDir: join('../../dist/render'), emptyOutDir: true, assetsInlineLimit: 0 }, server: { port: +process.env.PORT, }, plugins: [ vue() ], optimizeDeps: { exclude: [ 'electron-is-dev', 'electron-store', ] }, } export default config Reproduction https://github.com/denyncrawford/mismor-guillotine System Info vite latest: - Operating System: Windows 10 2004
- Node version: 15.2.0
- Package manager (npm) and version: 7.0.8
|
GeoLocation from gpsd Posted: 10 Apr 2021 08:17 AM PDT The gpsd program lets linux users cleanly organize their GPS peripheral data, such that a command line program like cgps or a graphical one like xgps can read the data, and write to a socket, like /var/run/gpsd.sock . There's a nice tutorial on the net for rigging a raspberry pi to use this data. This is all well and good, but how can I integrate this data in firefox or chromium, as the geolocation API? Is there a specific build process I might need? For instance, setting a ./configure flag or something? Is there a way to integrate this data in a prebuilt version of either browser? |
How to generate a random string of a fixed length in Go? Posted: 10 Apr 2021 08:17 AM PDT I want a random string of characters only (uppercase or lowercase), no numbers, in Go. What is the fastest and simplest way to do this? |
No comments:
Post a Comment