instruction
stringlengths
71
95.1k
I have an interface under development using an object-based approach. Objects should be statically allocated by the application writer (Dynamic memory allocation is not allowed). I want to obfuscate the object data so the application writer can only access the struct members using the provided methods. So I came to thi...
I am very confuse what is better approach to display child view and subscribe to its event on ReactiveUI WPF, so far I have 2 implementation that somehow works for my case: Implementation 1: public class ChildWindowView { public event EventHandler<Exception> Error; public event EventHandler<bool> Closed; i...
I am learning C and therefore decided to build my own, little shell. Currently I am concerned with input parsing. I want to split a line of text into tokens with delimiters. But it should be possible to escape the delimiter. A simple example would be: Input: "echo Hello World" Output: [echo, Hello, World] with n=3 toke...
I have a piece of python code doing fuzzy matching which works very well and is pretty fast. For reference, it uses the following files: https://raw.githubusercontent.com/datasets/s-and-p-500-companies/master/data/constituents.csv https://raw.githubusercontent.com/nlintz/pyBros/master/sp500/sp500.csv import csv from fu...
I have written some code for calculating a count of common factors. Please help me remove anything unnecessary and shorten it. Please tell me if any function in Python 3 can calculate common factors directly! # a string of 2 numbers # is input e.g. '10 15' a,b=str(input()).split(' ') a,b=int(a),int(b) n=0 if a>=b: ...
Hello I made this calculator in Python, I know it's pretty basic but I want your opinions if I made it well or not, and if you find any mistakes or not. P.S ( I know I could do another better than this one if I looked in internet but I want to evolve that's why I'm here ) #Commands print("Operations that you can use:")...
I'm a beginner programmer and I was hoping someone would be able to review my program. Everything has been tested for user validation, error-checking and conforms to the specification with a few slight additions of my own. I want to know what I've done well, what I haven't done well, improvements I can make e.g. how ca...
I made the looks of asteroids using pygame. I still need to implement collisions but since it is running incredibly slow with 'amount' anything above 10. Please rip my code to shreds and explain why it is bad so that I can improve. :) import pygame import pygame.locals import numpy import random asteroids = [] paused ...
all! I am developing a web "app" with JavaScript and jQuery with the help of a couple of other libraries for ease of use. Its purpose is to collect user ID's and to build a list of "attackable" targets for the game at https://torn.com Details for the API can be found at https://api.torn.com, although I'm pretty sure i...
I made a program (C#, .NET) that calculates time for XML and CSV export and please I have a question for improving my knowledge in programming. Do you think that I can improve the structure of the program? Or what do you think about code refactoring? Way of solve... Is it good? I uploaded the project to github. Thanks ...
Problem HackerRank Range query: You are given an array A of n integers. You have to perform m queries on the array. The queries are of two types: Modify the ith element of the array. Given x, y, print min{Ai + Ai+1 +…+ Aj | x ≤ i ≤ j ≤ y}. Note: A brute force solution may not work; Try using an efficient data stru...
I'm trying to learn Python, so I started with a program to convert length units, mixing imperial and metric. First I wrote a bunch of small simple functions, but then I wanted to solve the issue of having an intuitive way of calling one function with some easy to remember parameter values in order to convert from any u...
I've wrote a simulation of Langton's Ant in Java, and hope you have some suggestions to improve the code. The class Control.java contains just the main: import java.io.IOException; public class Control { static boolean exit = false; public static void main(String[] args) throws InterruptedException, IOException...
When I am developing in Bootstrap, I need to make sure that what is on the screen looks good. Bootstrap have various cutoff points where the flow can change. So to help with the visual debugging, I have created this tool that just shows what the current screen is according to Bootstrap. <cfscript> sizes = [ { ...
This is a function for checking if the checksum provided by card[] is valid. card[] contains six pairs of characters. The first five pairs make up a hexadecimal number, and the last pair contains the checksum. The checksum is valid if it is equal to XOR of the first five pairs. It is working fine, but the code is awful...
Asking for a review of my implementation of a command pattern. In a Editor, words can be entered and the entering of words can be undone. General purpose Interface public interface Command { void execute(); } The concrete write word command // Command public class WriteCommand implements Command { private Edi...
I'm solving a problem with find and replace a substring in a string. I've solved it using Python with a couple of lines, in C++ using std library and now solved it with C by using allocation on the stack. I want to get genuine feedback on the code I wrote and perhaps make it simpler. The constraints: do not use standa...
Here is the Interface I am using in my working app. <?php declare(strict_types=1); namespace midorikocak\nano; use Exception; interface CrudInterface { /** * @param array $data Array data of an Item. * @return array Array data of an Item with id. * @throws Exception if the data does not pass v...
I'm writing toy parsers for toy languages to understand how parsers work. Assuming a language as follows (in sketchy EBNF patois) expression := lparen [datum] [expression [datum]] rparen datum := any string of characters other than ( or ) rparen := ( lparen := ) These are some valid expressions (hello...
I posted a question here ffmpeg batch script for video resizing but I forgot the issue of the rotation and the video files were scaled with wrong dimensions. Below is the improved version of the script #!/bin/bash set -eu status=true fail() { echo "$@" >&2 status=false } # Resize a single file resize() { ...
I am a beginner so please keep it in mind while answering! For player vs CPU is there any more effective way to make CPU better ?? import numpy as np board=['-','-','-', '-','-','-', '-','-','-'] def check_win(): global winner global game_over if board[0]=='X' and board[1]=='X' and board[2...
I've recently completed a vanilla JS challenge . It is a method for calculating and ranking scores. If possible, I would love to make it better. Any suggestions are welcome. Challenge Directions: The input array contains a series of objects that hold user scores. Scores are ranked both individually (within the object) ...
First I have two conditions on the number of list elements,then in one of these conditions I have two others conditons to treat it : My code: List<StringBuilder> result = ReadResult_WS_Import(NameFile); if ((result != null) && (result.Any())) { var is_No_Errors_Found_Exist = result...
I have this class to generate unique ids and random ids from those unique ids. For the unique ids, it's a sequence of numbers between (start number = given number [start_seed]/or random number (0:1000000), and end number = start number + number of desired unique id -1) converted to string and hashed using md5 and conv...
I recently wrote the following Java 1.8 snippet to generate a CLABE control digit based on the following subheading on the CLABE page on Wikipedia and I was curious on how it could be improved. private void generateCLABEControlDigit() { final int[] expectedResults = {0,1,2,3,6,0,0,0,0,3,7,8,9,5,9,1,7}; final St...
I was playing around with ASP.NET Core 3.1 and tried to implement Dependency Injection flavor called Pure DI, i.e. without dependency container (even the built in one) to instantiate Controllers. You can see entire code here, but here's the rundown: I know I have to replace the default IControllerActivator but the main...
I am writing a function inside of a React component to hide/show columns in a table. The table is generated from an imported config object containing objects which model the column data. We render by simply mapping over the table content and rendering cells based on the columns. The method I'm writing exists in the tab...
I have been programming for a while, but I've only made games and less serious stuff. I want to get more serious. I would like some feedback on this class that defines a person. Structure, readability, use of static variables, etc. Please point out everything that can be improved. public class Person { private Str...
This code maps a function over a dataset in parallel in a monitored fashion, and returns the result in the variable out. import pandas as pd import numpy as np from tqdm import tqdm, trange from joblib import Parallel, delayed import multiprocessing import math n_jobs = multiprocessing.cpu_count() df = pd.DataFrame(np...
I am trying to build a generic query handler using the MediatR (v8) library. Let's jump to the code: First of all I have an abstract query class like this: public abstract class Query<TQueryResult> : IRequest<TQueryResult> { public Guid Id { get; } = Guid.NewGuid(); public DateTime Timestamp { get; } prot...
I recently worked on this problem that converts numbers to words. I was wondering if there is a better way to do it than mine, And I will really appreciate any reviews to my version of the solution and on how to make it better /** * Converts a given number into words * @param {integer} , num, the number to be convert...
I have designed a basic interface for a smart mirror I made. I coded it to include the time, date, and several phrases that refresh every 24 hours. The phrases are just some random quotes as examples. I was wondering if there were anyways I could streamline this code or even improve the layout of the interface. import...
I've been building this program for around a week or two on my spare time because I'm slowly starting to figure out how to code better. This program generates a yearly 5/3/1 cycle that is exported to a CSV file so you can easily print it off if you want. Below is my code: /** * */ package main; import java.util.Sc...
This code is used to select K for a K-nearest neighbor graph [KNNG] from a dataset with an unknown number of centroids (which is not the same as K-means clustering). Suppose that you have a dataset of observations stored in a data matrix X[n_samples, n_features] with each row being an observation or feature vector and ...
I have created a Modal, at the bottom of my CV to show various different resources and content creators that I have used to learn how to code, I have nearly finished this project and will be sending it out to companies maybe in the next few months. This modal animates in and out of the page by sliding down and blurring...
Based on this article And this question posted on the power bi forums Objectives: Resolve a hierarchy (parent - child relationship) in Power Query adding levels and their corresponding sorting columns. The final result can be used in a Power Pivot table and use it to generate a dynamic P&L. Key point was to add the sor...
I created this console app that gets some JSON strings from a web request using a Parallel.For loop, class Program { private static readonly object ConsoleLock = new object(); static void Main(string[] args) { //DECLARATION var link = "http://www.mytestrequest.com/id=" int start = ...
I am very new to PHP coding, hence just wanted to know if my coding is prone to any SQL injection attack or any other kind of threat. Below is the code for adding client to the database: <?php $response = array(); include 'db/db_connect.php'; include 'functions.php'; //Get the input request parameters $inputJSON = fil...
I'm currently trying to learn the basics of the Rust programming language, to do this my first piece of code after the classic 'Hello World' was a simple recursive Factorial function. This is the code: use std::io; fn factorial(num: i64) -> i64 { return if num == 1 { 1 }else{ num * factorial(n...
I have just migrated from Python 2 to Python 3. I have written the following script to fetch all records of a table, ir_attachment, from PostgreSQL. After fetching all the records I check following points: If an attachment record has no value for one of related_model, related_model_id or saved_file_name, then I append...
I want my input to be any random numbers in any number of elements. Examples: Input: 1 2 3 4 1 Output: 2 3 4 Input: 4 3 5 2 5 1 3 5 Output: 4 2 1 Input: 5 5 2 6 7 7 9 9 3 3 4 1 Output: 2 6 4 1 from collections import defaultdict n = int(input("")) print("") array = 0 def single_element(array, n): table = def...
My aim is to assign a color to each workday in a week. So if a user enters a day as a str, then I can know which color it should have. Because colors and workdays are fixed, I make them as enum.Enum instance. Is enum.Enum a proper choice for colors and workdays? To link day and color, I choose dictionary for weekday_c...
I made the following wrapper for the mediainfo command line. I did this mainly because mediainfo gives me more information than os.stat, specifically it gives me the Encoded date for .wma files, while the dates in os.stat don't represent the time the files were made, but rather the date the files were compressed (they ...
I'd like feedback on my solution to the outlined (medium level) programming challenge. What might be a more efficient or Pythonic solution? The challenge as outlined by Coderbyte: [Run Length] (https://www.coderbyte.com/solution/Run%20Length?tblang=german) Have the function RunLength(str) take the str parameter being ...
I want to make a camera class with help of the Eigen library. The camera will be used to perform certain calculations or rather the values used to setup the camera will be used later on in multiple matrix calculations. The camera can be defined by the 9D vector and the near/far plane and width/height values alone. Redu...
The code below looks at different range values and then populates specific cells on a worksheet called GeneralInfo in the Worksheet_Activate event.The below code does work as expected, but its time to clean it up a little bit, so I am looking for some ideas. I have tried to split up the code with using smaller procedu...
I'm trying to add error handling and response logging for API calls. The way I have my application (chatbot) set up is that a helper function is called from the main dialog, and that helper function calls the API. I believe this is standard practice. What I'm not sure on is how I should be catching errors in the proces...
i need to improve the performance of ConcurrentDictionary. for that i created 2 classes for check if the more efficiencies than the original. public class FixedConcurrentDictionary<TKey, TValue> { readonly ConcurrentDictionary<TKey, TValue> _dictionary = new ConcurrentDictionary<TKey, TValue>(); public bool IsE...
I am starting my adventure with Python and object oriented programming. I wrote a script for salting and hashing password. My main goal is practice with OOP, not cryptography. I know there is no error handling. Wonder how improve my code it and make more object oriented. It would be nice if someone more experienced c...
I wanted to write my own code for md5 in javascript and learn its inner mechanics. (I know it is not trusted anymore, deprecated, ... but I'm just learning). I didn't want to just copy the code that uses these like 60 repeated lines and over-complicated functions (like here), so I started writing my own implementation:...
Well, I'm working with Selenium to scrape a webpage that has obfuscated class names (example <div class="example-gHJkLM">...)... So I needed to create an extension method to get public static ReadOnlyCollection<IWebElement> Descendants(this IWebElement element, bool hasChildren = false, int index = -1, string postAppen...
I wrote this quick (lots of googling) and dirty (I hope not too dirty) script to download a URL list with a win32 wget port and save them as files with the url as the name to use as a "poor man's url cache" for another program. It works (tested ~200k links), but I wonder if I did progress management right (it was a pow...
I was tasked with writing a python script to check if a passed ID number exists within a file. The file I was give contains roughly 25,000 unique ID numbers. An ID number is a unique 9 digit number. I have a couple specific things for you to comment on if you decide to review this: As it stands, I convert the user_id...
I am looking for a better way to minimize nested if statements in my MessageHandler.handleMessage method. I am looking to adhere to SRP and a function should do one thing and one thing well! Any input would be greatly appreciated. class MessageHandler(): """ MessageHandler - Handles twitch IRC messages and emits e...
I am working on a simple personal project to build a Hoffman Tree. In my constructor, shown below, I am reading in a file, creating HoffmanNodes that represent each char in the file then I got through the file to encode it. I need to create a Scanner to go through the file once to find all the chars and their frequency...
I'm attempting to speed up some python code that is supposed to automatically pick the minimum samples argument in DBSCAN. Currently the execution time grows exponentially as the number of training samples increases: 0.128999948502 seconds for 100 training examples 0.281999826431 seconds for 1000 training examples 11...
I know that multiple functions are already available. However, I thought of writing my own because I wanted to learn the logic (and also because I thought there wasn't enough confusion :P). Please review the function I wrote and suggest me efficient changes. Without further ado, here I go: scan(string,size) char** stri...
What would be the "correct" way of transforming an array of objects into an object that contains an array? Suppose I have this array that contains objects: const paintings = [ { painting: "Mona Lisa" }, { painting: "The Starry Night" }, { painting: "The Last Supper" }, { painting: "Girl with a Pearl Earring" },...
First I fetch an instance from the database. The three functions getSwitches, getSingle and getLinears need the return value instance. When all requests are finished I want to fill the array barFrequencyData with the data. How do I correctly refactor the code? Should I use async/await or promises in this case? barFre...
A few days ago someone asked this question. But they quickly deleted the post offering no solution. Given: a = ['COP' , '\t\t\t', 'Basis', 'Notl', 'dv01', '6m', '9m', '1y', '18m', '2y', '3y', "15.6", 'mm', '4.6', '4y', '5y', '10', 'mm', '4.6', '6y', '7y', '8y', '9y', '10y', '20y', 'TOTAL', '\t\t9.2' ] They n...
categories = [{id: "761601bc-4daf-4db2-a0cf-fe7f443fcb94", name: "Shoes"},{id: "601ebcfe-fcbd-4075-a4b4-a42e356c5747", name: "Hats"},{id: "238933cf-77a5-4443-b290-7d7c836f80ff", name: "Eyewear"}]; voucher = {id:1,categories:["761601bc-4daf-4db2-a0cf-fe7f443fcb94","601ebcfe-fcbd-4075-a4b4-a42e356c5747"]}; filterCatego...
I am currently building cache for my application, and I would like to have my redis cache client work the same way you would dependency inject a DbContext. I am using StackExchange.Redis to manage my redis cache: https://github.com/StackExchange/StackExchange.Redis I have made it work, but I am not very confident in th...
I am learning programming with Python. I am not sure if I can write a try/except block like this. import os import shutil try: shutil.rmtree('c:/guna/newCAT1') print("dir newCAT1 deleted") except: os.mkdir('c:/guna/newCAT1') print("dir newCAT1 created") fileIN=open('c:/guna/newCAT1/secretMSG.txt','...
I'm taking on a project from a previous programmer. My goal is to make it a bit smaller and hopefully better. Originally the code has a bunch of length checks and Booleans as shown below. C# string[] splitStrArray = SNString.Split('-'); string part1 = splitStrArray[0]; string part2 = splitStrArray[1]; string part3 = sp...
I have written a palindrome program. And I was just wondering if it correct? I checked using the words racecar and madam, and it says they are palindromes. I have also tested nonpalindrome words and it worked correctly. Is my implementation correct? If it's not could you correct it for me. It it works correct, is there...
Just looking for advice/thoughts on the overall AccountModal and how its written. looking to achieve better written, more legible, less repetitive code, more concise, cleaner etc... AccountScreen.js: import React from 'react'; import { StyleSheet, ScrollView, View, Dimensions, Image } from 'react-native'; import * as C...
I'm trying to construct a simple database for use by 2 persons only (myself and other guy), right now, we're using excel table with 4 fields "requisition, origin date, request date and authorized date", but I want to take it to the next level :D. So, I'm building this small database app to emulate that, the file will b...
Hi so like in my question, i wrote some part of code for shopify to get recent orders for past 30 day and i wondering if it is really readable, or maybe i schould change something? I mean maybe there is a better way to achive same result. Or maybe i schould use different names? change position for function? $(document...
I've designed a single-file safe integer library in C++. It catches undefined behavior prior to integer overflows or underflows and throws the respective exceptions. I intend this to be portable, to not rely on undefined behavior, and to rely as little on implementation-defined behavior as possible. safe_integer.hpp: /...
Will you review the syntax, structure, and logic of my code. It can be tested using the main. using iTextSharp.text.pdf; using iTextSharp.text; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AddCopyRightPDF { class Prog...
This is a simple poker counter. It lets players decide their actions and makes the currency calculations for them. While adding a bit of console animation. Can I achieve the same results with simpler code?? from string import ascii_lowercase def get_player_names(): ''' Returns a List Of Playrer Names Got ...
With some effort I've managed to build a very simple (maybe too simple haha) navigation bar for a website. Is it possible to make a transition on the dropwdown list from height:0 to some suitable height? I've tried and it seems not to be possible. No javascript for now Any advice or extra tweak I could add? All is gre...
I'm timing out on Codewars' Prime Streaming kata. Below is my code: "use strict"; let _base = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]; let _bufferSize = 1000 class Primes { static get base() { return _base; } static get bufferSize() { return _bufferSize; }...
I'm very new to Haskell and I was trying to implement a DFT which is very imperative into Haskell and I wanted to get a feedback. More specially how can I avoid so many helper functions and I avoid limiting to Double everywhere. Thank you. My DFT algorithm: void dft(double[] inreal , double[] inimag, double[] outreal,...
I'm new here and also into programming, I've made this small paper-scissors-rock project, and I would like to get it reviewed and know, how can I maybe: simplify my code make it perform better using System; using System.Threading; namespace PaperScissorsStoneGame { class Program { static void Main(s...
I'm in the process of implementing a fully generic service to filter out entries (of any type), which are contained in a ICollection. As it is generic, without any constraints, the properties must be accessed through reflection. I'm not fully happy with the performance, even though it respects the minimum response time...
I use a change of groupbox locations depending on the number of weeks in the month. Is there any possibility for me to improve the functionality of this code a little bit, is it slow to load on this part? Thank you all for your help. FormWindowState LastWindowState = FormWindowState.Minimized; private void ...
I am a new python programmer. I have created the code to put API data from pipedrive to Snowflake database. Here are the steps in my code. Delete the csv file if it exists. Make an API call put all the paginated data in a list. Create a csv file from the list. Truncate the table in Snowflake. Remove data from Snowfla...
This method splits up two comma separated items, if they exist, and increments the amount if the are already in the list; otherwise add the item to the list I want to know if this code can be optimized some more. Any suggestions? The method below works 100% fine but I feel like it is not neatly done. private void Seper...
Could the aggregate functions after using grouping functions like groupby() and resample() be looped for cleaner code ____DateTime.____ | Steps | day_segment 2017-10-25 00:00:00| 4 | night 2017-10-25 00:01:00| 7 | night 2017-10-25 00:02:00| 10 | night 2017-10-25 00:03:00| 26 | night . . . 2017-10-25 10:04:00| 80...
Background Apologies for "burying the lead." The questions are in the next section. In my application, the purpose of inheritance is to abstract away complicated logic in the base class template, so that the writer of a derived class template doesn't need to worry about it. This logic, however, will depend on these sim...
This if for a school project that is all about getting the most performance possible out of a relatively weak computer. For this project we have received a weather station report generator that generates 8000 weather measurements per second. These measurements are split into groups of 10 stations resulting in 800 clust...
I have an XML Parser in Java using WoodStox that I wrote. This parser is going to be parsing through extremely large files, could be 5+GB. The goal of the parser is to convert a nest XML file into a CSV. The XML file is going to be formatted in such a way where there will be a 'rowTag' that has the actual information t...
What I have tried to accomplish with the code is to make some sort of partner budget where 2 people can have 2 separate budgets with separate expenses but which are still intertwined with eachother in some instances. The code refers to the range A36:H160 and K36:R76. The first range being Fixed expenses and the 2. ra...
Recently I was receiving Error 2015 when trying to use Application.Evaluate, then I realized it was because my formula was greater than 255 characters. As a workaround, I came up with this UDF: Function AdvancedEvaluate(eformula As String) ThisWorkbook.Worksheets("Scripting Worksheet").Range("A1").Formula = eformu...
Please could we examine the below code for anyway to put all console output in one statements? #include <iostream> using namespace std; int main( ) { //print("") in Python cout<<"Hello " "everybody!"<<endl; cout<<"My name is AK."<<endl; cout<<"Goodbye."<<endl; cout<<""<<endl; //Poem cout<<"Twin...
I'd like feedback on my solution to the outlined programming challenge (medium level). I've tried it fast in any way I know how to, but, what might be a more efficient and/or pythonic solution? [Letter Count II] Have the function LetterCount(str) take the str parameter being passed and return the first word with t...
ERROR: type should be string, got "https://jsfiddle.net/0a7tcv2g/\nI know I could locally store the data, write in es6, and all that, but I wanted to learn to work with APIs, and really understand JS through ES5, before brushing up my ES6+ skills. I haven't finished adding all the small details yet, but thats trivial at this point. Just looking for feedback on my JS, and responsiveness of my site. (I know I used some es6, and could use const in some places instead of let).\nHTML:\n<!DOCTYPE html>\n<html>\n<head>\n<title>Pokedex</title>\n<link rel=\"stylesheet\" type=\"text/css\" \nhref=\"styles.css\">\n</head>\n<body>\n<h1 id=\"main-header\">Pokedex</h1>\n<div id=\"main-container\">\n\n</div>\n<script src=\"index.js\" \ntype=\"text/javascript\"></script>\n</body>\n</html>\n\nCSS:\n*{\nfont-family: Arial, Helvetica, San-serrif;\nmargin:0;\npadding: 0;\n}\n\nh1 {\nbackground: red;\ncolor: white;\nfont-size: 3em;\ntext-align: center;\n\n}\n\n#main-container {\nposition: absolute;\ndisplay: flex;\nflex-wrap: wrap;\nperspective: 625em;\n}\n\n.card-container {\nposition: relative;\ndisplay: flex;\ntransform-style: preserve-3d;\nflex-wrap: wrap;\njustify-content: center;\nalign-content: center;\nflex-basis: 31%;\nheight: 25em;\nwidth:18.75em;\nbox-shadow: 0.07em 0.07em 0.4em 0.13em \nrgb(40, 40, 40, 0.6);\nmargin: 0.4em;\ntransition: 1000ms;\nbackground: #0000ff;\nborder: 0.63em solid gold;\n}\n\n.frontFace, .backFace {\ndisplay: flex;\nflex-wrap: wrap; \nflex-basis: 31%;\nposition: absolute; \nheight: 100%;\nwidth: 100%;\nbackface-visibility: hidden;\ncolor: white;\n/*Temporary*/\ntext-shadow: -0.13em 0 red, 0 0.13em red, \n0.13em 0 red, 0 -0.13em red;\n}\n\n.backFace {\ntransform: rotateY(180deg);\nheight: 100%\nwidth: 100%;\n\n}\n\n.frontFace img, .backFace img {\nposition: absolute;\nmargin-top: 18%;\nmargin-left: 20%;\nbackground: white;\nborder: gold 0.19em solid;\nwidth: 60%;\nheight: auto;\n}\n\n\n\n.name{\nwidth: 100%;\ntext-align: center;\nfont-size: 1.5em;\noverflow:auto;\n}\n\n.frontName {\nfont-size: 1.5em;\ntext-align: center;\nmargin-top: 2%;\nwidth: 100%;\nmax-width: 100%;\n\n}\n\n.type {\nmargin-top: 70%;\nmargin-left: 66%;\n}\n\n.id {\nposition: absolute;\nmargin-left: 4%;\nmargin-top: 4%;\nheight: auto;\n}\n\nJS:\nconst container = document.getElementById('main-container');\n\nfunction getPokemon(callback) {\n const xhr = new XMLHttpRequest();\n const url = 'https://pokeapi.co/api/v2/pokemon/';\n\n xhr.onload = function() {\n if(xhr.status === 200) {\n const pokemon = JSON.parse(xhr.responseText);\n pokemon.results.forEach((poke, index)=>{\n\n let cardContainer = document.createElement('div');\n cardContainer.className = 'card-container';\n container.appendChild(cardContainer);\n let frontFace = document.createElement('div');\n frontFace.className = 'frontFace';\n cardContainer.appendChild(frontFace);\n let sprite = document.createElement('img')\n sprite.src = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${(index + 1).toString()}.png`\n frontFace.appendChild(sprite);\n let backName = document.createElement('h4');\n backName.className = 'name';\n function capitalName(string) {\n backName.innerText = string.charAt(0).toUpperCase() + string.slice(1);\n }\n capitalName(poke.name)\n frontFace.appendChild(backName); \n })\n\n callback();\n }\n }\n xhr.open('GET', url, true);\n xhr.send();\n}\n\nfunction cardBack() {\n const endPoint = this.innerText.charAt(0).toLowerCase() + this.innerText.slice(1);\n const card = this.parentElement;\n const xhr = new XMLHttpRequest();\n\n xhr.onload = function() {\n if(xhr.status === 200) {\n if(card.childNodes.length === 2) {\n card.style.transform = 'rotateY(180deg)';\n }\n else {\n const details = JSON.parse(xhr.responseText); \n let backFace = document.createElement('div');\n backFace.className = 'backFace';\n backFace.addEventListener('click', ()=>{\n card.style.transform = ''\n })\n card.appendChild(backFace);\n let sprite = document.createElement('img')\n sprite.src = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${(details.id).toString()}.png`\n backFace.appendChild(sprite);\n let name = document.createElement('h4');\n name.className = 'frontName';\n name.innerHTML = details.name;\n let type = document.createElement('h4');\n type.className = 'type';\n type.innerHTML = details.types[0].type.name;\n backFace.appendChild(name);\n backFace.appendChild(type);\n let ids = document.createElement('h4');\n ids.className = 'id';\n ids.innerHTML = `#${details.id}`;\n backFace.appendChild(ids);\n card.style.transform = 'rotateY(180deg)';\n }\n }\n }\n xhr.open('GET', 'https://pokeapi.co/api/v2/pokemon/' + endPoint, true);\n xhr.send();\n}\n\ngetPokemon(()=>{\n const cardFront = document.querySelectorAll('.frontFace');\n cardFront.forEach((card)=> {\n card.addEventListener('click', cardBack);\n })\n});\n\n"
This is my first go at Django, so I'm looking first to learn how to make this more idiomatic. Also, is there a better way to set up my tests? To my HTTP status codes make sense? chores/tests.py import datetime import json from django.test import TestCase, Client from django.urls import reverse from rest_framework impo...
Background I was looking for a simple Event Broker or EventBus (whatever else keyword you can come up with) to use in a small(-ish) WinForms application. In Java I was using org.greenrobot.EventBus for a long time, but couldn't find a comparably established and simple solution in C# - everything looks to be enterprise ...
Inspired by Wrapping IndexDB with RxJs. (Edit - Added a Stackblitz example). My use case is a simple, on-disk temporary cache. No errors are propagated, null values are returned instead. All errors are logged. import { Injectable } from '@angular/core'; import { Observable, Observer, ReplaySubject, Subject } from 'rx...
I'm creating a simple registration form for a Linux installation party I'm organizing. Although I'm a decent programmer, I rarely create HTML files. I want to know if this form is safe for my users and if it will work on most devices. Am I following all the good web development practices? Is my code pure HTML5? <!DOCTY...
I have a common style (common.scss) and a text direction (RTL, LTR) option file (option-document-direction-rtl.scss, option-document-direction-ltr.scss). And by switching the reading of these files, the css file with RTL / LTR changed is output by method like gulp.js. _common.scss body { max-width: 1120px; backgrou...
I was tasked to write process that initially seemed like a straight forward thing. "Fetch data from database, create a cache object, and assign this data to it. Use existing class to model this after." That's it in a nutshell. The 'existing' class did not do any caching, just an async call across layers to the database...
I am brand new to writing hooks and I am having a little trouble getting my head wrapped around it. Initially, I wanted to write this with one event listener that passed the event and a separate param to distinguish itself from the other incoming arguments. With hooks, I was confused as to how I should pass a separate...
I'm implementing the following function for signed integer numbers: given endpoints of a closed interval lo and hi, and inputs x (in [lo..hi]) and dx, I'd like to compute the "reflected sum": if x + dx is still in [lo..hi] then that's it; otherwise the underhanging or overhanging portion is "folded back" onto the resu...
I have a dictionary where for each key, a single value is stored. Say import pandas as pd dd = {'Alice': 40, 'Bob': 50, 'Charlie': 35} Now, I want to cast this dictionary to a pd.Dataframe with two columns. The first column contains the keys of the dictionary, the second column the values and give the colu...
My program looks for the area of ​​the figures, depending on the value of the variable а. area -> triangle area -> triangle2 area -> square area -> rhombus I want to get constructive criticism about the structure of the code and what can be redone. The program is written in the Python programming language. while ...
I have time-series data (t) that I want to loop through each t and take the difference of the previous five lags t-1 ... t-5. This code works, but is inefficient. I'm not sure how to increase the performance and efficiency of the code. Sample data import pandas as pd import numpy.random as nr dat = pd.DataFrame({'t...
Wrote some code to install bootstrap (latest) in a newly created rails application. update: fixed a typo yarn add bootstrap jquery popper.js expose-loader yarn install --check-files perl -pi.bak -e "s/extract_css: false/extract_css: true/" config/webpacker.yml s1=$'\n\nimport "bootstrap/dist/js/bootstrap";' echo "$s1" ...