text
stringlengths
1
2.12k
source
dict
java, beginner, random break; case 32: System.out.println("Eat a raw egg!"); break; case 33: System.out.println("Put a clamp on your nipples!"); break; case 34: System.out.println("Let everyone watch you whip and nay nay!"); break; case 35: System.out.println("Say something dirty to the person to your left!"); break; case 36: System.out.println("Do 100 squats!"); break; } // Restart ********************************************************** System.out.println(); System.out.println("Would you like to play again? (type y/n and hit enter)"); String y = myObj.nextLine(); System.out.println(); if (y.equals("y")) { Main.main(args); } else { System.out.println("Ok, Bye!"); } System.out.println(); } } ```
{ "domain": "codereview.stackexchange", "id": 43171, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner, random", "url": null }
java, beginner, random Answer: myObj is not a good name for your scanner. You should not hard-code your random bounds, and you should replace your large switch with a random index into an array. Don't recurse on main() after the player asks to play again - instead, just loop. Suggested import java.util.*; import static java.lang.System.out; public class Main { private static final String[] truths = { "What is your favourite thing?", "How are you doing?", "How fluffy are puppies?" }; private static final String[] dares = { "Do something nice", "Be nice", "Take care of yourself" }; private final Scanner in = new Scanner(System.in); private final Random rand = new Random(); public static void main(String[] args) { new Main().run(); } public void run() { do { round(); } while (playAgain()); out.println("Ok, bye!"); } public void round() { out.println("TRUTH OR DARE?"); out.print("Type truth or dare: "); String truthOrDare = in.nextLine().toLowerCase(); String[] source; if (truthOrDare.startsWith("t")) source = truths; else source = dares; int index = rand.nextInt(source.length); out.println(source[index]); } public boolean playAgain() { out.print("Would you like to play again [y|n]? "); String choice = in.nextLine().toLowerCase(); out.println(); return choice.startsWith("y"); } }
{ "domain": "codereview.stackexchange", "id": 43171, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner, random", "url": null }
parsing, haskell, functional-programming, variant-type Title: Haskell: implementing Read for a custom dynamic value type Question: I'm using Haskell to interpret a dynamically-typed language. I have a sum type called Value which can represent some basic objects: data Value = Integer Integer | Float Double | Char Char | List [Value] deriving Show (For now I'm not adding a special case for strings - they'll just be lists of characters.) I have instantiated Read for it, so that I can parse string inputs into Values as though they're normal Haskell values. While for this demo I just derived Show using the default implementation, I had to define Read manually, because I don't want the input to need the data constructors prefixed before every element. (I would have to write input as Integer 43 instead of just 43, for example) I implement readsPrec (which seems a needlessly complex method to have as the minimal typeclass implementation, but it's what Haskell requires...) in terms of Haskell's default implementations for the underlying data types. readsPrec takes a precedence value, which I just pass on to the readsPrec of other types; it returns a list of possible parses as tuples of (value, restOfString). The basic algorithm I use is to attempt to parse the input into each type, and choose the first result from each. Unfortunately there's quite a lot of plumbing required to deal with the list of tuples produced by readsPrec. instance Read Value where readsPrec precedence s = -- `justs` stops the parsing once all of the read attempts are failing justs $ map (foldl orElse Nothing) $ transpose attempts where -- try to parse the input into each of these types, one at a time attempts = [u Integer, u Float, u Char, u List] u constructor = maybes [(constructor val, rest) | (val, rest) <- readsPrec precedence s]
{ "domain": "codereview.stackexchange", "id": 43172, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "parsing, haskell, functional-programming, variant-type", "url": null }
parsing, haskell, functional-programming, variant-type This implementation also uses a couple of utility functions: -- | Create an infinite list of Maybes, where the elements in the input -- | are `Just`s, and everything after that is a `Nothing` maybes xs = map Just xs ++ repeat Nothing -- | Collect the values of all Justs at the start of a list justs (Just x : xs) = x : justs xs justs _ = [] I want to know if my code, especially the plumbing around readsPrec, can be made more idiomatic, perhaps using some more builtin functions. Maybe the whole algorithm can be simplified. I also don't like the fact I'm using a constant-sized list for the attempts. I'd like to be able to just use a tuple, but if I ever wanted to add more data types, I'd have to change things like unzip4 to unzip5, because I can't write it polymorphically over tuple size. (where unzip would be used for tuples, in place of transpose for lists) I'm not really interested in whether the minutiae of my syntax style are "correct". Here is an online demo of my code. Answer: Your algorithm is fine. Your Read instance, however, isn't. There are semi-written laws, namely that for any type A that instanciates both Show and Read the following laws hold: if I read a value and then show it again, I will end up with the same string (except for whitespace changes): srIdentity :: (Read a, Show a) => a -> String -> String srIdentity x s = show (read s `asTypeOf` x) if I show a value and then read it again, I get the same value back: rsIdentity :: (Show a, Read a) => a -> a rsIdentity = read . show the process must be repeatable for both variants srsrIdentity :: (Show a, Read a) => a -> String -> String srsrIdentity x = srIdentity x . srIdentity x rsrsIdentity :: (Show a, Read a) => a -> a rsrsIdentity = rsIdentity . rsIdentity Your Read instance does not hold any of those laws. What you really want is a regular function parseString :: String -> Value
{ "domain": "codereview.stackexchange", "id": 43172, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "parsing, haskell, functional-programming, variant-type", "url": null }
parsing, haskell, functional-programming, variant-type Usually, you would use one of the (many) parsing libraries for this, like attoparsec or parsec. Many of those parsers are also Monad or even MonadPlus (or Alternative), so you end up with something along valueP :: Parser Value valueP = integerP <|> floatP <|> charP <|> many valueP I'd like to be able to just use a tuple, but if I ever wanted to add more data types Adding a new type would then lead to just another alternative: valueP :: Parser Value valueP = integerP <|> floatP <|> charP <|> complexP -- <---- <|> many valueP So have a look at parsers and parsing. And keep in mind: if you derive Show, you should also derive Read. If you feel the need to write the Read instance by hand, don't, instead write a parser.
{ "domain": "codereview.stackexchange", "id": 43172, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "parsing, haskell, functional-programming, variant-type", "url": null }
python, python-3.x, combinatorics Title: Count five-digit octal numbers with alternating even and odd digits, without repeated digits Question: I need to find the number of five-digit octal numbers in which all digits are different and no two odd or even digits are adjacent. My code below gives the correct answer, but I'm not satisfied. Can you help me improve it or how would you solve this task? from itertools import product c = 0 for args in product((0, 1, 2, 3, 4, 5, 6, 7), repeat=5): n1, n2, n3, n4, n5 = args # no zero start if n1 == 0: continue if (n1 + n2) == 0: continue if (n1 + n2 + n3) == 0: continue if (n1 + n2 + n3 + n4) == 0: continue if (n1 + n2 + n3 + n4 + n5) == 0: continue # different digits if (args.count(0) > 1 or args.count(1) > 1 or args.count(2) > 1 or args.count(3) > 1 or args.count(4) > 1 or args.count(5) > 1 or args.count(6) > 1 or args.count(7) > 1): continue # even odd even odd even or odd even odd even odd if ((n1 % 2 == 0 and n2 % 2 != 0 and n3 % 2 == 0 and n4 % 2 != 0 and n5 % 2 == 0) or (n1 % 2 != 0 and n2 % 2 == 0 and n3 % 2 != 0 and n4 % 2 == 0 and n5 % 2 != 0)): c+=1 print(c) # 504 (correct) Answer: As Toby noted, it's not too difficult to calculate the answer. The more you can offload the computer work to insights from your brain, the better your approach will be. But we'll proceed with reviewing your code. As noted, c is not a good variable name. I'll call it validNumbers. I would recommend to always put continue on the next line. Leaving it on the same line can lead to overlooking what you're doing. I don't see how n1+n2==0 could happen if n1!=0. (0,1,2,3,4,5,6,7) is better written as range(8). itertools also has permutations, which guarantees no repeated elements. (Otherwise, I would say that you should have len(args)==len(set(args)).)
{ "domain": "codereview.stackexchange", "id": 43173, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, combinatorics", "url": null }
python, python-3.x, combinatorics Python allows you to chain comparisons. This means that "even odd even odd even" could be n1 % 2 == n3 % 2 == n5 % 2 == 0 and n2 % 2 == n4 % 2 != 0. Even better would be to combine the two tests into one: n1 % 2 == n3 % 2 == n5 % 2 != n2 % 2 == n4 % 2. Instead of the first line assigning everything from args, it would be better to have for n1, n2, n3, n4, n5 in permutations(range(8), r=5): and skip args. But even better would be to have everything in terms of args. This makes the parity checks a bit harder, but not too bad: args[::2] gets the items with even indices (n1, n3, and n5), while args[1::2] gets the odd indices. Then we can use a comprehension and put those items into a set to make sure they're all the same. (This removes needing the previous paragraph.) from itertools import permutations validNumbers = 0 for args in permutations(range(8), r=5): # no zero start if args[0] == 0: continue evens = set(n%2 for n in args[::2]) odds = set(n%2 for n in args[1::2]) if ( len(evens)==len(odds)==1 and evens != odds ): validNumbers+=1 print(validNumbers) # 504 (correct) The big advantage of this approach is that we can now easily adjust the base or the length by simply changing the 8 or 5 in line 4, and the rest of the code remains the same. If 8 or 5 were much bigger, then this could start slowing down. In that case, you could create your number one digit at a time, and only proceed if the number is correct so far. Or grab the evens separately from the odds, with something like: for evens,odds in product(permutations(range(0,8,2),r=3),permutations(range(1,8,2),r=3)):
{ "domain": "codereview.stackexchange", "id": 43173, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, combinatorics", "url": null }
python, performance, strings, regex Title: Extract regular words from string but retain all other elements and record their type Question: This snippet processes every regular (\w+) word in a text and reinserts the processed version: import re import time def process(word: str) -> str: time.sleep(0.05) # Processing takes a while... return word.title() text = """This is just a text! Newlines should work. Multiple ones as well, as well as arbitrary spaces. Super-hyphenated long-lasting and overly-complex words should also work. Arbitrary punctuation; has to work... Because? Why not!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! """ processed_items = [] items = re.split(r"(\w+)", text) for item in items: # Have to check for word *again* in order to skip unnecessary processing, even # though we just matched/found all words. is_word = re.match(r"\w+", item) is not None if is_word: item = process(item) processed_items.append(item) processed_text = "".join(processed_items) print(processed_text) Processing is expensive, so we would like to skip non-word elements, of which there can be many of arbitrary types. In this current version, this requires matching using a word regex twice. There should be a way to only process/split the input once, cutting the regex effort in half. That would require some more structure. A possible solution data structure I had in mind could be a (eventually named) tuple like: items = [ ("Hello", True), ("World", True), ("!", False), ] where the second element indicates whether the element is a word. This would spare us from having to re.match(r"\w+", item) a second time. However, as before, splitting "Hello World!" into the above three elements requires word-splitting in the first place. Answer: Your biggest problem is use of split(). It indiscriminately mixes in matches and non-matches. Instead, just finditer and explicitly define two groups: words and non-words. import re import time from typing import Iterator
{ "domain": "codereview.stackexchange", "id": 43174, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, strings, regex", "url": null }
python, performance, strings, regex def process(word: str) -> str: time.sleep(0.05) # Processing takes a while... return word.title() WORD_PAT = re.compile( r''' (?P<notword>\W*) # named capturing group: non-word characters (?P<word>\w*) # named capturing group: word characters ''', re.VERBOSE, ) def split_and_process(text: str) -> Iterator[str]: for match in WORD_PAT.finditer(text): yield match.group('notword') yield process(match.group('word')) def test() -> None: text = """This is just a text! Newlines should work. Multiple ones as well, as well as arbitrary spaces. Super-hyphenated long-lasting and overly-complex words should also work. Arbitrary punctuation; has to work... Because? Why not!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! """ processed_text = "".join(split_and_process(text)) print(processed_text) if __name__ == '__main__': test()
{ "domain": "codereview.stackexchange", "id": 43174, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, strings, regex", "url": null }
python, numpy, pandas, cython Title: type hinting/documenting/extension of a Cython lib Question: I've updated some of the type hinting/documentation in a lib called pygrib. The source documentation can be found here. The goal is to extend the Cython api with the associated native type hints and maintain an open ended platform for future growth, IE more methods like to_dataframe() pygrib uses Cython to read gridded binary files grib pygrib2.__init__.py from .core import * from .extension import * pygrib2.core.py import os from pygrib2.extension import File class Reader: """reader wrapper with typing support around the pygrib open function""" grib_file: File def __init__(self, file_path: str): def _unzip(path: str) -> str: os.system(f'gzip -d {path}') return path.strip('.gz') if file_path.endswith('.gz'): self.file_path = _unzip(file_path) else: self.file_path = file_path def __enter__(self) -> File: self.grib_file = File(self.file_path) return self.grib_file def __exit__(self, *_) -> None: self.grib_file.close() pygrib2.extension.py from typing import NewType, Type, Union, Any import pandas as pd import pygrib PyGribOpen = NewType('PyGribOpen', Type[pygrib.open]) PyGribMessage = NewType('PyGribMessage', Type[pygrib.gribmessage]) class Message: def __init__(self, message: PyGribMessage): self._message = message def __repr__(self): return str(self._message) def __getattr__(self, key: str) -> Any: """>>> Message.keys()""" return self._message.__getattribute__(key) def __getitem__(self, key: Union[bytes, str]) -> Any: """>>> Message['values']""" return self._message.__getattribute__(key) class File(pygrib.open): def __next__(self): """>>> next(GribFile)""" return Message(super().__next__())
{ "domain": "codereview.stackexchange", "id": 43175, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, numpy, pandas, cython", "url": null }
python, numpy, pandas, cython def __getitem__(self, key: Union[int, slice]): """>>> GribFile[1]""" return Message(super().__getitem__(key)) def to_dataframe(self): return pd.DataFrame.from_records(dict(_full_message(grb)) for grb in self) def _full_message(grb: Message): """ ### usage ``` if __name__ == '__main__': with grib.Reader(GRIB_FILE) as grbs: for grb in grbs: x = tuple(grib._full_message(grb)) print(x) ``` """ for k in grb.keys(): try: yield k, grb[k] except RuntimeError: print(k) pygrib2.extension.pyi from typing import ( Iterator, NewType, TypeVar, Tuple, Union, List, Any ) import numpy as np import pandas as pd import numpy.typing as npt FloatArray = npt.NDArray[np.float_] NData = NewType('NData[float]', FloatArray) NLats = NewType('NLat[float]', FloatArray) NLons = NewType('NLon[float]', FloatArray) class Message: """ ### Grib message object. Each grib message has attributes corresponding to GRIB keys. Parameter names are described by the name, shortName and paramID keys. pygrib also defines some special attributes which are defined below ### Variables - messagenumber - The grib message number in the file. - projparams - A dictionary containing proj4 key/value pairs describing the grid. Set to None for unsupported grid types. - expand_reduced - If True (default), reduced lat/lon and gaussian grids will be expanded to regular grids when data is accessed via values key. If False, data is kept on unstructured reduced grid, and is returned in a 1-d array. - fcstimeunits - A string representing the forecast time units (an empty string if not defined). - analDate - A python datetime instance describing the analysis date and time for the forecast. Only set if forecastTime and julianDay keys exist.
{ "domain": "codereview.stackexchange", "id": 43175, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, numpy, pandas, cython", "url": null }
python, numpy, pandas, cython - validDate - A python datetime instance describing the valid date and time for the forecast. Only set if forecastTime and julianDay keys exist, and fcstimeunits is defined. If forecast time is a range, then validDate corresponds to the end of the range. """ def data( self, lat1: int = ..., lat2: int = ..., lon1: int = ..., lon2: int = ... ) -> Tuple[NData, NLats, NLons]: """ extract data, lats and lons for a subset region defined by the keywords lat1,lat2,lon1,lon2. The default values of lat1,lat2,lon1,lon2 are None, which means the entire grid is returned. If the grid type is unprojected lat/lon and a geographic subset is requested (by using the lat1,lat2,lon1,lon2 keywords), then 2-d arrays are returned, otherwise 1-d arrays are returned. """ def expand_grid(self, arg=True) -> None: """toggle expansion of 1D reduced grid data to a regular (2D) grid (on by default).""" def has_key(self, key: Any) -> bool: """tests whether a grib message object has a specified key.""" def is_missing(self, key: Any) -> bool: """ returns True if key is invalid or value associated with key is equal to grib missing value flag (False otherwise) """ def keys(self) -> List[str]: """return keys associated with a grib message in a list""" def latlons(self) -> Tuple[NLats, NLons]: """ compute lats and lons (in degrees) of grid. Currently handles regular lat/lon, global gaussian, mercator, stereographic, lambert conformal, albers equal-area, space-view, azimuthal equidistant, reduced gaussian, reduced lat/lon, lambert azimuthal equal-area, rotated lat/lon and rotated gaussian grids. Returns lats,lons numpy arrays containing latitudes and longitudes of grid (in degrees). """
{ "domain": "codereview.stackexchange", "id": 43175, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, numpy, pandas, cython", "url": null }
python, numpy, pandas, cython def tostring(self) -> bytes: """ return coded grib message in a binary string. """ def valid_key(self, key: str) -> bool: """ tests whether a grib message object has a specified key, it is not missing and it has a value that can be read """ class File: """extension class for `<class 'pygrib._pygrib.open'>`""" def close(self) -> None: """close GRIB file, deallocate C structures associated with class instance""" def message(self, num: int) -> Message: """retrieve N'th message in iterator. same as seek(N-1) followed by readline().""" def read(self, num: int = None) -> List[Message]: """ read N messages from current position, returning grib messages instances in a list. If N=None, all the messages to the end of the file are read. pygrib.open(f).read() is equivalent to list(pygrib.open(f)), both return a list containing gribmessage instances for all the grib messages in the file f. """ def tell(self) -> Union[int, None]: ... def seek(self, num: int) -> int: ... def __iter__(self) -> Iterator[Message]: ... def __next__(self) -> Message: ... def __getitem__(self, key: Union[int, slice]) -> Message: ... def to_dataframe(self, **kwargs) -> pd.DataFrame: ... Message = TypeVar('Message', bound=Message) File = TypeVar("File", bound=File) main.py import numpy as np import pygrib2 as grib GRIB_FILE = 'data/ecmwf_tigge.grb' if __name__ == '__main__': with grib.Reader(GRIB_FILE) as grib_file: assert isinstance(grib_file, grib.File) message = grib_file[1] assert isinstance(message, grib.Message) assert all(isinstance(d, np.ndarray) for d in message.data())
{ "domain": "codereview.stackexchange", "id": 43175, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, numpy, pandas, cython", "url": null }
python, numpy, pandas, cython Answer: Your Reader method has a grib_file member that is missing from the class until __enter__. This is generally not advisable: some linters will tell you that it needs to be set in __init__. In that case, it would be hinted as an Optional and set to None until __enter__ is called. However, the lighter-weight approach is to scrap your class entirely and make a method looking roughly like @contextmanager def read_grib(file_path: str) -> Iterator[File]: if file_path.endswith('.gz'): os.system(f'gzip -d {file_path}') file_path = file_path.strip('.gz') grib_file = File(self.file_path) try: yield grib_file finally: grib_file.close() But there are other unadvisable bits in there: don't os.system, use subprocess instead; and preferably use .with_suffix on a Path instead of doing your own string manipulation. Even more preferable than subprocess is calling into the built-in gzip support. Message is so permissive as to be almost useless. If you know anything about the actual members on the interior PyGribMessage, you should be exposing that in your typehinting, because right now it's all Any. Many of your functions are missing return typehints, including _full_message. I encourage you to run mypy on your source; when properly configured it will let you know about such things.
{ "domain": "codereview.stackexchange", "id": 43175, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, numpy, pandas, cython", "url": null }
python, python-2.x Title: TapeEquilibrium Codility implementation not achieving 100% Question: Given the following task description from here : A non-empty zero-indexed array A consisting of N integers is given. Array A represents numbers on a tape. Any integer P, such that 0 < P < N, splits this tape into two non-empty parts: A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1]. The difference between the two parts is the value of: |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])| In other words, it is the absolute difference between the sum of the first part and the sum of the second part. For example, consider array A such that: A[0] = 3 A[1] = 1 A[2] = 2 A[3] = 4 A[4] = 3 We can split this tape in four places: P = 1, difference = |3 − 10| = 7 P = 2, difference = |4 − 9| = 5 P = 3, difference = |6 − 7| = 1 P = 4, difference = |10 − 3| = 7 Write a function: def solution(A) that, given a non-empty zero-indexed array A of N integers, returns the minimal difference that can be achieved. For example, given: A[0] = 3 A[1] = 1 A[2] = 2 A[3] = 4 A[4] = 3 the function should return 1, as explained above. Assume that: N is an integer within the range [2..100,000]; each element of array A is an integer within the range [−1,000..1,000]. Complexity: expected worst-case time complexity is O(N); expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). Elements of input arrays can be modified.
{ "domain": "codereview.stackexchange", "id": 43176, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-2.x", "url": null }
python, python-2.x Elements of input arrays can be modified. I decided to implement an algorithm that with 2 counters/pointers (one from leftmost and another one from rightmost of the array input) representing the total sum of values that the pointer(s) have traversed. The process works by first deciding which pointer to move closer to the other in each iteration, which is looking the next element directly next to the location of the current pointer, attempt to temporarily sum the value to the pointer, and then find the absolute difference between the other pointer. The absolute difference is also calculated for the other pointer, and then compared against each other's pointer temporarily accumulated value, to find out which one yields lower absolute difference. The pointer move that yields the lowest absolute difference then performs the actual summation to the pointer, and that particular pointer moves for that iteration. The following is my code : from math import fabs def solution(A): l_ptr = 0 r_ptr = A.__len__() - 1 l_sum = A[l_ptr] r_sum = A[r_ptr] while l_ptr < r_ptr - 1: if fabs(l_sum + A[l_ptr + 1] - r_sum) > fabs(l_sum - (r_sum + A[r_ptr - 1])): r_ptr -= 1 r_sum += A[r_ptr] else: l_ptr += 1 l_sum += A[l_ptr] return (int)(fabs(l_sum - r_sum)) In the test case, I didn't manage to achieve 100% test accuracy, and I'm not sure exactly why, but I think perhaps it has something to do with the pointer not being able to look for the array element that are several steps away at a given iteration and the possibility of having negative value. The followings are the test cases that it fails on according to Codility : ▶ small_random random small, length = 100 ✘WRONG ANSWER got 269 expected 39 ▶ large_ones large sequence, numbers from -1 to 1, length = ~100,000 ✘WRONG ANSWER got 228 expected 0 ▶ large_random random large, length = ~100,000 ✘WRONG ANSWER got 202635 expected 1
{ "domain": "codereview.stackexchange", "id": 43176, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-2.x", "url": null }
python, python-2.x Obviously provided that it's evaluation of a test set, the actual input data for the test are not given, so it's more difficult for me to figure out what part of my algorithm that is incorrect and the causes. Could someone provide an explanation (preferably with a sample input data) what I misunderstood and the cause? Thank you in advance. Answer: Algorithm Your algorithm works for input with only positive integers. But it may not work with some input that contains negative numbers, for example it gives incorrect result for: [-1, 1, 1, -1, -2] Why does it work for all positive numbers? At any point in your loop, you basically have: leftsum: the sum of elements on the left so far leftnext: the next element on the left rightsum: the sum of elements on the right so far rightnext: the next element on the right When you know that all remaining elements in the middle are non-negative, then you can safely decide whether to take the left or the right, by minimizing the difference between leftsum + leftnext and rightsum + rightnext. This is safe, because all the remaining elements are non-negative, therefore the difference can only shrink, or otherwise be minimal. But when there can be negative numbers in the middle, you don't have such knowledge, and it can be impossible to decide which side to advance. Consider this alternative that's simple and intuitively easy to understand, and it's guaranteed to give correct result: Set left to the first element Set right to the total sum - left Initialize mindiff to the absolute difference of left and right Iterate from the 2nd element until the -1th: add to left and subtract from right and update mindiff (A quick tip for writing the loop: for value in A[1:-1]: ...) return mindiff Technique It's strange you did from math import fabs when you don't need floating point math to solve this problem. You can use abs instead of fabs. Instead of A.__len__() it's more natural to use len(A).
{ "domain": "codereview.stackexchange", "id": 43176, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-2.x", "url": null }
javascript, calculator, vue.js Title: Simple Vue calculator Question: I made conditional calculator in Vue js but I need help to make it more efficient. https://jsfiddle.net/wbrx9cyp/1/ example of code: essentialPackage(){ this.essentialToggle = true; this.mediumToggle = false; this.extraToggle = false; if(this.shortToggle && this.essentialToggle){ this.packagePrice = 1.2; }else if(this.longToggle && this.essentialToggle){ this.packagePrice = 39; } }, I made it best I could, but there are too many if statements Can somebody point me in the right direction? Answer: Introduction Based on your JSFiddle, you have code with multiple responsibilities stored in one area. Separate them. I've written some examples below in TypeScript, however the same ideas can be translated to JavaScript easily. If Statements To answer the question about too many if statements, make a calculator component that takes in each parameter and returns the result. I've added an example below. Class Design Term Design Perhaps Term could be a class that ShortTerm and LongTerm extend. I'm not sure exactly what the difference is in pricing between ShortTerm and LongTerm, but they should have a price/rate. Just a price different from each other. class Term { price: number; constructor(price: number) { this.price = price; } } class ShortTerm extends Term { constructor() { super(1.5); } } class LongTerm extends Term { constructor() { super(1.2); } } Package Design We can further specialise our packages. // Forced to use Pack as Package is a keyword. class Pack { price: number; constructor(price: number) { this.price = price; } } class Essential extends Pack { constructor() { super(1); } } class Medium extends Pack { constructor() { super(1.5); } } class Extra extends Pack { constructor() { super(1.9); } }
{ "domain": "codereview.stackexchange", "id": 43177, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, calculator, vue.js", "url": null }
javascript, calculator, vue.js class Extra extends Pack { constructor() { super(1.9); } } Calculator Design Now that we have some parts of our insurance offer neatly organised, we can create a class dedicated to calculation. class Calculator { public calculate(term: number, pack: number) { return term * pack; } } Putting it all together Now we have two insurance variables, and a calculator. Lets put it all together. const shortTerm = new ShortTerm(); const medium = new Medium(); const calculate = new Calculator().calculate; const offer = calculate(shortTerm.price, medium.price) console.log(offer); // Ouput: 2.25 Conclusion Given that we've designed our 3 components (Terms, Packs, Calculator), we're able to delegate all our calculation logic to one simple function. We can further design our Offers as a class, given they might have a client (person who bought the offer), expiry date, each insurance variable, and some methods like editOffer() which changes a variable from shortTerm to LongTerm. Note While a lot of the classes are the same with just a price variable, there may be specific differences between a package, a term, etc. Unfortunately I don't have the specifics to know what the differences are. However you can still apply all these principles to improve your software design and increase your codes efficiency.
{ "domain": "codereview.stackexchange", "id": 43177, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, calculator, vue.js", "url": null }
performance, c Title: Department change management utility Question: I was wondering on how to make the execution time faster. Is there a way to make it faster with this method or do I need to make with another method? If someone have any solution please help me. because I'm really struggling with this and I tried many different things and my lecture said that this code's execution time is still too long. This program is about a person who wants to change departments. But if he wants to change departments, there must be another person from that department that want to move to the other department. For example, #include<stdio.h> #include<stdlib.h> typedef struct Node{ int a; int b; struct Node *next; }Node; typedef struct Result{ int info; struct Result *next; }Result; Node *createNode(int a, int b){ Node *p = (Node*)malloc(sizeof(Node)); p->a = a; p->b = b; p->next = NULL; return p; } Result *createResult(int res){ Result *p = (Result*)malloc(sizeof(Result)); p->info = res; p->next = NULL; return p; } void initialize(Node **F, Result **R){ (*F) = NULL; (*R) = NULL; } int check(Node **F, int a, int b){ if((*F) == NULL){ (*F) = createNode(a, b); return 0; } Node *temp = (*F); Node *before = NULL; while(temp != NULL){ if(temp->b == a && temp->a == b){ if(before == NULL){ (*F) = temp->next; }else{ before->next = temp->next; } free(temp); return 1; }else{ before = temp; temp = temp->next; } } before->next = createNode(a, b); return 0; } void addResult(Result **R, int res){ Result *p = createResult(res); Result *temp = (*R); if(temp == NULL){ (*R) = p; }else{ while(temp->next != NULL){ temp = temp->next; } temp->next = p; } }
{ "domain": "codereview.stackexchange", "id": 43178, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c", "url": null }
performance, c void showResult(Result *R){ Result *temp = R; if(temp == NULL){ return; }else{ while(temp != NULL){ printf("%d\n", temp->info); temp = temp->next; } } } int main(){ int a, b, i, N, count; Node *First; Result *Res; initialize(&First, &Res); while(scanf ("%d", &N) != EOF){ count = 0; First = NULL; for(i=0; i<N; i++){ scanf("%d %d", &a, &b); count += check(&First, a, b); } addResult(&Res, count); } showResult(Res); return 0; } Input and Output example: 7 //The amount of people who wants to change 1 2 //The person who wants to change dept from where to where (1) 35 66 //The person who wants to change dept from where to where 100 500 //The person who wants to change dept from where to where(2) 2 1 //The person who wants to change dept from where to where (1) 2 3 //The person who wants to change dept from where to where(3) 500 100 //The person who wants to change dept from where to where(2) 3 2 //The person who wants to change dept from where to where(3) 3 //The total of how many can change from dept A to dept B 3 //The amount of people who wants to change 100 200 //The person who wants to change dept from where to where 200 400 //The person who wants to change dept from where to where 400 1 //The person who wants to change dept from where to where Answer: You have undefined behaviour here: Node *createNode(int a, int b){ Node *p = (Node*)malloc(sizeof(Node)); p->a = a; p->b = b; p->next = NULL; return p; } When malloc() fails (and it will, according to Murphy!) it returns a null pointer. Dereferencing such a pointer (with ->) is Undefined Behaviour. We need to avoid that: Node *createNode(int a, int b) { Node *p = malloc(sizeof *p); /* N.B. don't cast! */ if (p) { p->a = a; p->b = b; p->next = NULL; } return p; }
{ "domain": "codereview.stackexchange", "id": 43178, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c", "url": null }
performance, c Also, we need to account for the fact that createNode() can return null, when we call it, and possibly further back in the call tree, until we get to inform the user. I don't see any corresponding free() calls for these allocations. Please don't leak memory. No comments on the performance right now - deal with correctness first.
{ "domain": "codereview.stackexchange", "id": 43178, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c", "url": null }
c#, .net, bitwise, apache-kafka Title: Convert a c# decimal to big-endian byte array Question: Following the avro schema documentation for decimals I've created a method to turn a decimal into a byte array. The goals are: Should be represented by a non-scaled integer Should be big-endian I've tested the code I wrote, but I'd like to know if the program still works in any unforeseen corner cases. private static byte[] ToBigEndianByteArray(decimal value, int scale) { var bigInteger = new BigInteger(value * (decimal)Math.Pow(10, scale)); var bytes = bigInteger.ToByteArray(); return BitConverter.IsLittleEndian ? bytes.Reverse().Select(ReverseEndianness).ToArray() : bytes; static byte ReverseEndianness(byte input) { const int bits = 8; return (byte)Enumerable.Range(0, bits - 1) .Aggregate(0, (accumulator, index) => BitAtIndexIsSet(input, index) ? SetBitAtIndex(accumulator, bits - 1 - index) : accumulator); static int SetBitAtIndex(int value, int index) => value | 1 << index; static bool BitAtIndexIsSet(int value, int index) => (value & (1 << index)) != 0; } } Example usage: ToBigEndianByteArray(8.45m, 2) produces 0000001101001101 (845 in decimal). Answer: It does not look correct to me, in two ways:
{ "domain": "codereview.stackexchange", "id": 43179, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, bitwise, apache-kafka", "url": null }
c#, .net, bitwise, apache-kafka Answer: It does not look correct to me, in two ways: Computing Math.Pow(10, scale). This is not exact when scale is negative or large. Since it's fine for moderate positive scales and the amount of inexactness in other cases typically won't be very high, it may be difficult to actually produce a wrong result, but I would not dare to rely on it - especially for a format that is supposed to be exact. Big-endian does not mean reversing the bits in every byte, which I think the ReverseEndianness does, but it's a relatively confusing function, and I don't mean the bitwise part of it but rather everything except that. I would have used something like this adapted for C#. Doesn't really matter in the end, because the specification does not say to reverse the bits to begin with, so you can remove that whole function. Furthermore I think the API is hard to use correctly, because it assumes that you already have a scale, which is not trivial to find. Passing the wrong scale can very easily result in information being lost. Alternatively, you may be able to use the GetBits method on the decimal, extract its internal scale (and use it directly as the scale in avro format, which uses the same kind of scales), and convert the integer part that it has internally to a big-endian (but not bit-reversed) array of bytes. It seems to me that this would severely limit the possibility of both incorrect API usage, and incorrect implementation.
{ "domain": "codereview.stackexchange", "id": 43179, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, bitwise, apache-kafka", "url": null }
php, validation, json Title: PHP Validate JSON objects with a JSON schema Question: I have a basic JSON API written in PHP. I want to validate incoming JSON data. I know there are PHP JSON validators out there, here is a quick one I just rolled up. <?php $json_payload = json_decode('{ "data": { "a_string": "short", "a_number": 7 } }'); validateJSONPayload( '{ "data": { "a_string": "type=string,min_length=7,max_length=10", "a_number": "type=integer,min=8,max=50" } }', $json_payload ); function validateJSONPayload($json_schema, $json_payload){ $json_schema = json_decode($json_schema); function reCursiveCheck($schema_value, $schema_type, $payload_value, $payload_type){ if($schema_type === "object" || $schema_type === "array"){ # KEEP LOOPING foreach ($schema_value as $key => $key_val) { if(!property_exists($payload_value, $key)) echo "validation failed because the data does not match the schema<br />"; reCursiveCheck($key_val, gettype($key_val), $payload_value->{$key}, gettype($payload_value->{$key})); } } else { # VALUE IS A STRING, NUMBER, BOOL, NULL $validation_param_strings = explode(",", $schema_value); # STORE THE PARAMS TO CALL THE VALIDATION FUNCTION $validation_params = array(); foreach($validation_param_strings as $validation_param) { $params = explode("=", $validation_param); $validation_params[$params[0]] = $params[1]; } // print_r($validation_params); validateProperty($payload_value, $payload_type, $validation_params); } }
{ "domain": "codereview.stackexchange", "id": 43180, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, validation, json", "url": null }
php, validation, json function validateProperty($payload_value, $payload_type, $validation_rule){ if($payload_type !== $validation_rule["type"]) { echo "types do not match<br />"; } # STRING VALIDATION if($validation_rule["type"] === "string"){ if(strlen($payload_value) > $validation_rule["max_length"]) echo "string too long<br />"; if(strlen($payload_value) < $validation_rule["min_length"]) echo "string too short<br />"; } # NUMBER VALIDATION if($validation_rule["type"] === "integer"){ if($payload_value > (int)$validation_rule["max"]) echo "number too large<br />"; if($payload_value < (int)$validation_rule["min"]) echo "number too small<br />"; } # NULL VALIDATION if($validation_rule["type"] === "null"){ echo "found a null<br />"; } } foreach($json_schema as $key => $value) { if(!property_exists($json_payload, $key)) echo "validation failed because the data does not match the schema<br />"; reCursiveCheck($value, gettype($value), $json_payload->{$key}, gettype($json_payload->{$key})); } } ?> Answer: Your solution is very "functional programming" in approach, with nested function declarations and such. This in of itself is not "wrong", it is just a little bit unusual in the PHP world. I would consider moving this into an object-oriented paradigm which is more common in PHP. I would think in this case perhaps only a class with static functions might be needed, so you could make calls against the validator like: $result = JsonSchemaValidator::validate($jsonSchema, $jsonPayload); If you find you have one schema that is used multiple times for validation, then perhaps it makes sense to have concrete validator objects like this: $validator = new JsonSchemaValidator($jsonSchema); $result1 = $validator->validate($jsonPayload1); $result2 = $validator->validate($jsonPatload2);
{ "domain": "codereview.stackexchange", "id": 43180, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, validation, json", "url": null }
php, validation, json This would save you the overhead of having to re-validate the schema with each validation request. I am not sure which is more appropriate to your application, but wanted to present both options for putting this logic into a class. Some odd naming conventions are in play: Why name a variable $json_payload when it does not contain JSON at all, but rather an object built from JSON? Perhaps $payload is better here. Why are you mixing camelCase and snake_case in your code? I know PHP is not very consistent here, but that doesn't mean you shouldn't be - at least within the confines of a single library, class, set of functions, etc. Why uppercase first c in reCursiveCheck()? I think your main validateJSONPayload() function name and signature is odd. As noted above, the "payload" is not JSON at all. Why pass one parameter as a JSON string and the other as an actual data structure? This seems to be an incongruous approach. I would probably just pass JSON for both parameters so caller doesn't need to decode one of the parameters beforehand. Why define validation rules in a string like "type=string,min_length=7,max_length=10"? You are introducing complexity in your code to have to perform string manipulation to get at these values when they should be defined as appropriate properties/values on the schema. Why not mirror the already well-established JSON Schema format?
{ "domain": "codereview.stackexchange", "id": 43180, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, validation, json", "url": null }
php, validation, json Do not echo error/validation messages to standard output. A validator like this should do one thing - validate, not deliver end user messaging. Leave that up to functionality further up the call stack that is more well-positioned to understand the context for how end user messaging should be delivered. This code might throw exceptions and/or log errors when it gets put into a bad state (i.e. invalid JSON is passed) but outside of that, it's contract to the caller should be to just deliver validation results and leave it up to the calling code to determine what action to take from there. If you are delivering error messages, you should also remove any HTML markup from it. What if this code is being used in a RESTful service where response is going to be JSON format and not HMTL? Now you have to go strip out the HTML mark-up that has been added. The takeaway here is to separate your display concerns from your business logic. This code is incredibly fragile and strictly "happy path" in nature, as you are doing no validation of the passed dependencies and you just assume that all of the steps in the code will work properly. Most critically, you just assume the passed schema JSON will decode properly. What if it doesn't? Right now, your code will just silently fail, perhaps giving the caller the perception that validation passed, since you currently do not return any validation result to the caller (you just echo out failures). To extend on my earlier class-based example, perhaps you need to do something like: try { $result = JsonSchemaValidator::validate($jsonSchema, $jsonPayload); } catch (InvalidArgumentException $e) { // perhaps we had schema or payload which could not be decoded // and we have the code throw InvalidArgumentExpection // perhaps log the error error_log($e->getMessage()); // then perhaps do something to recover $result = false; }
{ "domain": "codereview.stackexchange", "id": 43180, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, validation, json", "url": null }
php, validation, json or try { $validator = new JsonSchemaValidator($jsonSchema); $result1 = $validator->validate($jsonPayload1); $result2 = $validator->validate($jsonPatload2); } catch (InvalidArgumentException) { // do something } I echo the sentiment mentioned in comments to question above that I am really not quite sure why you would want to roll your own solution to this problem.
{ "domain": "codereview.stackexchange", "id": 43180, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, validation, json", "url": null }
javascript, beginner, event-handling Title: When "How To Ask" is too subtle Question: This is the first JavaScript code I've ever written, alert("hello, world!"); aside. This site is closing quite a lot of questions because people won't read the rulebook or pay attention to the How To Ask panel that's displayed as you're entering your question title - almost 60% of closed questions involve broken code, so I suggested to pop a red in-your-face warning when a user is about to ask a blatantly off-topic question with broken code. Not knowing whether Stack Exchange would go forward with something like that, I suggested we implement one ourselves, for the heck of it. It's still too early for the July community-challenge, so this isn't an entry... well it would be, but I just couldn't wait to try something, so here it goes. I've "stolen" some HTML and CSS from the Ask Question page, adapted it a little bit to fit the Stack Snippet box, and proceeded to implement the JavaScript code to make it work. Go ahead, try it! The script is triggered when you hit ENTER in the title box. NOTE: The code uses String.includes, which may not be available in your browser. See the accepted answer for details. function validateKey(e) { "use strict"; if (e.keyCode == 13) { var field = document.getElementById("title"); if (!validateTitle(field)) { showWarning(); } else { clearWarning(); } } } function validateTitle(titleField) { "use strict"; var title = titleField.value; return !title.includes("bug") && !title.includes("issue") && !title.includes("t work") // catches won't work, isn't working, etc. && !title.includes("s wrong") // catches what's wrong, what is wrong && !title.includes("fix") && !title.includes("why"); } function showWarning() { "use strict"; var msg = getWarningDiv(); document.getElementsByTagName("table")[0].appendChild(msg); }
{ "domain": "codereview.stackexchange", "id": 43181, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, event-handling", "url": null }
javascript, beginner, event-handling function clearWarning() { "use strict"; var popup = document.getElementsByClassName("message-dismissable")[0]; if (popup == undefined) { return; } popup.parentNode.removeChild(popup); } function getWarningDiv() { "use strict"; var popup = document.createElement("div"); popup.className = "message message-error message-dismissable"; popup.setAttribute("style", "max-width: 270px; min-width: 270px; position: absolute; top: 32px; left: 378px; display: block;"); popup.addEventListener("click", function(event) { clearWarning(); }); var tooltip = document.createElement("div"); tooltip.className = "message-inner message-tip message-tip-left-top"; popup.appendChild(tooltip); var tipText = document.createElement("div"); tipText.title = "close this message (or hit Esc)"; tipText.className = "message-close"; tipText.textContent = "×"; tooltip.appendChild(tipText); var msg = document.createElement("div"); msg.className = "message-text"; msg.setAttribute("style", "padding-right: 35px;"); msg.textContent = "Wait! If your code does not work as intended, this question is off-topic!"; popup.appendChild(msg); return popup; } body { font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; font-size: 13px; line-height: 1.3em; color: #222; background: #fff; min-width: 1030px; } .ask-title-table { width: 668px; height: 44px; } table { border-collapse: collapse; border-spacing: 0; border-color: grey; } .ask-title-cell-key { width: 40px; } #title { width: 498px; } .form-item label { display: block; font-weight: bold; padding-bottom: 3px; } input[type=text], input[type=url], input[type=email], input[type=tel], textarea { font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; background: #fff; color: #444; border: 1px solid #ccc; font-size: 14px; padding: 8px 10px; } .message.message-error.message-dismissable { cursor: pointer; }
{ "domain": "codereview.stackexchange", "id": 43181, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, event-handling", "url": null }
javascript, beginner, event-handling .message.message-error.message-dismissable { cursor: pointer; } .message.message-error { z-index: 1; display: none; color: #fff; background-color: #c04848; text-align: left; } .message.message-error .message-text { padding: 15px; } .message.message-error .message-close { padding: 2px 6px 3px 6px; font-family: Arial,sans-serif; font-size: 16px; font-weight: normal; color: #fcb2b1 !important; line-height: 1; float: right; border: 1px solid rgba(255,255,255,0.2); margin-top: 8px; margin-right: 8px; } .message.message-error .message-tip-left-top:before { top: 0; left: -9px; border-top: 9px solid #c04848; border-left: 9px solid transparent; } .message.message-error .message-tip:before { content: ""; position: absolute; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <html> <head> <title>Ask a Question - Code Review Stack Exchange</title> </head> <body> <form> <div id="question-form"> <div class="form-item ask-title"> <table class="ask-title-table"> <tbody> <tr> <td class="ask-title-cell-key"> <label for="title">Title</label> </td> <td class="ask-title-cell-value"> <input id="title" name="title" type="text" maxlength="300" tabindex="100" placeholder="State the task that your code accomplishes. Make your title distinctive." class="ask-title-field" data-min-length="15" data-max-length="150" autocomplete="off" onkeypress="return validateKey(event)"/> </td> </tr> </tbody> </table> </div> <!-- warning should be inserted here --> </div> </form> </body> </html> Again, the CSS and HTML aren't exactly mine - they're merely an excuse for the JavaScript, which I'd like to improve. Also, did I overlook any blatant false positives?
{ "domain": "codereview.stackexchange", "id": 43181, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, event-handling", "url": null }
javascript, beginner, event-handling Answer: String.includes() is part of the experimental ECMAScript 6 language proposal. Therefore, you cannot rely on it being available in browsers. On browsers that do not support String.includes(), your script does nothing — it just leaves an error in the JavaScript console, if one cares to look there. That is one of the dangers of JavaScript programming: the page just breaks completely due to one mistake, even if it works on your own browser. The conservative approach, title.indexOf(…) >= 0, is definitely recommended. Other than that, your code looks pretty good. However, since you have included jQuery in your Stack Snippet, I am puzzled by why you didn't make use of it. Much of this code would be simplified. More jQuery, please!
{ "domain": "codereview.stackexchange", "id": 43181, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, event-handling", "url": null }
python, performance, array, numpy Title: Replace nested for loops when assigning intial conditions in a 4-dimensional array Question: I create a 4-dimensional (x, y, z, t) array of zero values. I then set the initial values at t = Tmax. To do this, I use a nested for loop. I attempted to improve on the code by getting rid of the nested for loops, and replacing it with a single line of code. It works, however, I am not sure if the line f[:, :, :, N] = np.array([[X_] * (J+1)] * (J+1)).T is very optimised? It looks messy. Is there a more elegant way of writing this particular line? I have considered numpy's tile and repeat functions. My best attempt is as follows: import numpy as np I = 50 J = 25 K = 25 N = 50 Xmin = 0 Xmax = 200 Ymin = 0 Ymax = 1 Zmin = 0 Zmax = 1 dx = (Xmax - Xmin) / I dy = (Ymax - Ymin) / J dz = (Zmax - Zmin) / K X_ = np.linspace(Xmin, Xmax, I + 1) #Original approach f = np.zeros((I + 1, J + 1, K + 1, N + 1)) for i in range(0, I + 1): for j in range(0, J + 1): for k in range(0, K +1): f[i, j, k, N] = i * dx print(f[:, :, :, :].sum()) #My attempt at a faster approach f[:, :, :, N] = np.array([[X_] * (J+1)] * (J+1)).T print(f[:, :, :, :].sum()) Thanks. Answer: You mentioned that you've considered np.tile. I think (subjective) it's a bit more readable than line you proposed. Objectively speaking np.tile method was created exactly for cases like your have. Moreover I've found np.tile-based solution at least 2 times faster. I have found two solutions: Generate replicas and put it into zeros-array slice You can generate line of I+1 elements and replicate it using np.tile method. Then you can put in N'th slice of your np.zeros array f = np.zeros((I + 1, J + 1, K + 1, N + 1)) line_i = np.arange(I + 1) * dx f[:, :, :, N] = np.tile(line_i, (K + 1, J + 1, 1)).T
{ "domain": "codereview.stackexchange", "id": 43182, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, array, numpy", "url": null }
python, performance, array, numpy Over-replicate and assign zeros You can generate an entire f array using np.tile method. Then you can assign over-replicated elements to zero. line_i = np.arange(I + 1) * dx f = np.tile(line_i, (N + 1, K + 1, J + 1, 1)).T f[:, :, :, :-1] = 0 P.S. You are using f.sum() to validate results from two different solution. It's not the best practice for your case as sum of elements doesn't depend on the order of elements. You can use: (f_nested == f_oneline).all()
{ "domain": "codereview.stackexchange", "id": 43182, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, array, numpy", "url": null }
algorithm, strings, interview-questions, go Title: Golang solution to CTCI 1.2: Check whether two strings are permutations of each other Question: Just started learning Go recently. Did some questions from Cracking the Coding Interview book. Wrote the solutions in Go. Let me know what you think. https://github.com/samjingwen/ctci Below is question 1.2 from the book: // CheckPermutation Given two strings, write a method to // decide if one is a permutation of the other. func CheckPermutation(s1, s2 string) bool { if len(s1) != len(s2) { return false } s1CharCountMap := getCharCountMap(s1) s2CharCountMap := getCharCountMap(s2) for k, s1Count := range s1CharCountMap { s2Count, exists := s2CharCountMap[k] if s1Count > s2Count { return false } else if !exists { return false } } return true } func getCharCountMap(str string) map[rune]int { charCount := make(map[rune]int) for _, char := range str { _, exists := charCount[char] if exists { charCount[char] += 1 } else { charCount[char] = 1 } } return charCount } Answer: Code should be correct, maintainable, robust, reasonably efficient, and, most important, readable. Sam wrote: func getCharCountMapSam(str string) map[rune]int { charCount := make(map[rune]int) for _, char := range str { _, exists := charCount[char] if exists { charCount[char] += 1 } else { charCount[char] = 1 } } return charCount } Peter wrote: func getCharCountMapPeter(str string) map[rune]int { charCount := make(map[rune]int) for _, char := range str { charCount[char]++ } return charCount } Benchmarks: BenchmarkMapSam-8 463837 2495 ns/op 830 B/op 5 allocs/op BenchmarkMapPeter-8 539000 1937 ns/op 830 B/op 5 allocs/op Whom would you hire?
{ "domain": "codereview.stackexchange", "id": 43183, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, strings, interview-questions, go", "url": null }
algorithm, strings, interview-questions, go Whom would you hire? Sam wrote: func CheckPermutationSam(s1, s2 string) bool { if len(s1) != len(s2) { return false } s1CharCountMap := getCharCountMapSam(s1) s2CharCountMap := getCharCountMapSam(s2) for k, s1Count := range s1CharCountMap { s2Count, exists := s2CharCountMap[k] if s1Count > s2Count { return false } else if !exists { return false } } return true } Peter wrote: func CheckPermutationPeter(s1, s2 string) bool { if len(s1) != len(s2) { return false } s1CharCountMap := getCharCountMapPeter(s1) s2CharCountMap := getCharCountMapPeter(s2) if len(s1CharCountMap) != len(s2CharCountMap) { return false } for s1Char, s1Count := range s1CharCountMap { if s1Count != s2CharCountMap[s1Char] { return false } } return true } Whom would you hire? The Go Programming Language Specification Index expressions if the map is nil or does not contain such an entry, a[x] is the zero value for the element type of M The zero value Each element of such a variable or value is set to the zero value for its for its type: 0 for numeric types IncDec statements The "++" and "--" statements increment or decrement their operands by the untyped constant 1. As with an assignment, the operand must be addressable or a map index expression. IncDecStmt = Expression ( "++" | "--" ) . The following assignment statements are semantically equivalent: IncDec statement Assignment x++ x += 1 x-- x -= 1
{ "domain": "codereview.stackexchange", "id": 43183, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, strings, interview-questions, go", "url": null }
python, validation Title: Multiple condition checking on array-like container in Python Question: I'm writing a function that validates array-like container to have correct type, length or to be hashable. Some of conditions may not be used for validation. def check_container(container, type_=None, length=None, hashable=None): """ Validates container to have correct type and length, or hashable parameter. Arguments: container {iterable} -- instance to be validated Keyword Arguments: type_ {type/tuple of types} -- valid type/type length {int} -- valid length hashable {bool} -- if container should be hashable Returns: bool -- result of verification """ valid = True if type_ is not None: valid = valid and isinstance(container, type_) if length is not None: valid = valid and len(container) == length if hashable is not None: valid = valid and isinstance(container, collections.Hashable) return valid I confused by the style I collect all booleans together: valid = valid and other_condition. It doesn't look "pythonic" for me. Any thoughts on how it can be writed more compact, readable and "pythonic way"? Update Usage of check_container function in code: class one: class BoxToMultiDiscrete: def __init__(self, bounds, n_bins): if not check_container(bounds, tuple): raise TypeError("bounds should be a tuple") if not check_container(n_bins, tuple, len(bounds[0])): raise TypeError("n_bins should be a tuple of the same length as boundaries") low = list(bounds[0]) high = list(bounds[1]) self.bins_list = [] for i in range(len(n_bins)): bins = np.linspace(low[i], high[i], n_bins[i] - 1) self.bins_list.append(bins) def transform(self, input_vector):
{ "domain": "codereview.stackexchange", "id": 43184, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, validation", "url": null }
python, validation def transform(self, input_vector): if not check_container(input_vector, tuple, len(self.bins_list)): raise TypeError("input_vector should be a tuple of the same length as n_bins") output_vector = tuple() for i in range(len(input_vector)): digit = np.digitize(input_vector[i], self.bins_list[i]) output_vector += (int(digit),) return output_vector class two: class MultiDiscreteToDiscrete: def __init__(self, n_bins): if not check_container(n_bins, tuple): raise TypeError("n_bins should be a tuple") self.n_bins = n_bins self.space_size = np.product(n_bins) temp = (1,) + n_bins[:-1] self.cumprod = np.cumprod(temp) def transform(self, input_vector): if not check_container(input_vector, tuple, len(self.n_bins)): raise TypeError("input_vector should be a tuple of the same length as n_bins") return self._convert(input_vector) def _convert(self, input_vector): num = 0 for i, bin in enumerate(input_vector): num += bin * self.cumprod[i] return num P.S. Maybe you can give some feedback about classes too.
{ "domain": "codereview.stackexchange", "id": 43184, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, validation", "url": null }
python, validation P.S. Maybe you can give some feedback about classes too. Answer: By the Single Responsibility Principle, each function should do one thing, and the name of the function should reflect its purpose. Your function does multiple things, which is the underlying reason for the code being awkward. As a result, the code that calls check_container() is also awkward, since it can no longer give one specific reason why the validation failed. It performs zero, one, or two checks for the type of container. In modern Python, types of parameters should be declared using type annotations. You can either do static analysis using mypy, or runtime validation using enforce. I'm not sure why you insist that certain containers be tuples. Is it important that it be immutable? Or hashable? If it's not actually important that they be tuples, consider dropping that requirement in favour of duck typing. With the type checks taken care of by other means, all you have left is a dimension check. So, write a function for that, or maybe you can just write that check inline instead.
{ "domain": "codereview.stackexchange", "id": 43184, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, validation", "url": null }
shell, sh Title: Replace version numbers in multiple files Question: In the script below I need to search in multiple files, and find a string, and replace with another. It's basically version numbers (which need incrementing). Every time I find the old version number, and replace with a new version number. The script is working well, but maybe has a cleaner way to search the old version number, because now I enter all the values manually. It needs to be bulletproof, because if the file string version numbers changed with another third party app or script, the new version numbers must be the next number when running the script (currently, the version number check is done manually). Can you give me any clues to improve the script? oldVersion='1\.1\.10' oldBuildNum='14' oldVersionCode='22' oldCurrentProjectVersion='20' newVersion='1\.1\.11' newBuildNum='15' newVersionCode='23' newCurrentProjectVersion='21' canonical=$(cd -P -- "$(dirname -- "$0")" && printf '%s\n' "$(pwd -P)/") xcodePath="${canonical}ios/Runner.xcodeproj/project.pbxproj" sed -i -e "s/MARKETING_VERSION = ${oldVersion}/MARKETING_VERSION = ${newVersion}/g" "$xcodePath" sed -i -e "s/FLUTTER_BUILD_NAME = ${oldVersion}/FLUTTER_BUILD_NAME = ${newVersion}/g" "$xcodePath" sed -i -e "s/FLUTTER_BUILD_NUMBER = ${oldBuildNum}/FLUTTER_BUILD_NUMBER = ${newBuildNum}/g" "$xcodePath" sed -i -e "s/CURRENT_PROJECT_VERSION = ${oldCurrentProjectVersion}/CURRENT_PROJECT_VERSION = ${newCurrentProjectVersion}/g" "$xcodePath" pubspec="${canonical}pubspec.yaml" # The version string format here is: version: 1.1.10+22 sed -i -e "s/version: ${oldVersion}+${oldVersionCode}/version: ${newVersion}+${newVersionCode}/g" "$pubspec" android="${canonical}android/local.properties" sed -i -e "s/flutter\.versionName=${oldVersion}/flutter\.versionName=${newVersion}/g" $android sed -i -e "s/flutter\.versionCode=${oldVersionCode}/flutter\.versionCode=${newVersionCode}/g" $android
{ "domain": "codereview.stackexchange", "id": 43185, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "shell, sh", "url": null }
shell, sh Answer: A shell program ought to begin with an interpreter specification: #!/bin/sh It looks like oldVersion needs to be a regex, but newVersion is used as literal replacement, so shouldn't contain those backslashes. It's very inefficient to repeatedly run sed in-place, compared to a single sed command for each file: sed -i \ -e "s/\(MARKETING_VERSION\|FLUTTER_BUILD_NAME\) = ${oldVersion}/\1 = ${newVersion}/g" \ -e "s/\(FLUTTER_BUILD_NUMBER = \)${oldBuildNum}/\1${newBuildNum}/g" \ -e "s/\(CURRENT_PROJECT_VERSION = \)${oldCurrentProjectVersion}/CURRENT_PROJECT_\1${newCurrentProjectVersion}/g" \ "$xcodePath" Depending on the input file, we might not need to use /g option (i.e. if the match won't occur multiple times on a given line). If those are whole lines, as in a key=value properties file, perhaps we want to replace everything after =, like this: sed -i \ -e "/^\(MARKETING_VERSION\|FLUTTER_BUILD_NAME\) /s/=.*/= ${newVersion}/" \ -e "/^FLUTTER_BUILD_NUMBER /s/=.*/= ${newBuildNum}/" \ -e "s/^CURRENT_PROJECT_VERSION /s/=.*/= ${newCurrentProjectVersion}/" \ "$xcodePath" Then we don't need to know what the old version was, just the new version we want to create. I've even been known to write a function to create a sed program for such files: #!/bin/bash # (We need Bash, as we use a process substitution below) # Output a sed script that sets each KEY to VALUE change_values() { printf '/^%s *=/s/=.*/= %s/\n' "${@//\//\\/}" } change_xcode_file() { change_values \ MARKETING_VERSION "$newVersion" \ FLUTTER_BUILD_NAME "$newVersion" \ FLUTTER_BUILD_NUMBER "$newBuildNum" \ CURRENT_PROJECT_VERSION "$newCurrentProjectVersion" } sed -i -f <(change_xcode_file) "$xcodePath" That might be overkill for you, but I found that useful in my project, where any developer might need to quickly adjust which things get overwritten in the config.
{ "domain": "codereview.stackexchange", "id": 43185, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "shell, sh", "url": null }
beginner, game, rust, hangman Title: A Rust beginner's Hangman game Question: I have been learning Rust for a few days (This is my third) now, and I've really fallen in love with the language, this is my first real project, Hangman. I was wondering what I could do better / what is currently fine. lib.rs: use rand::Rng; use std::fs; use std::io; #[derive(PartialEq)] // im not even sure what this does but it wants me to add it. #[derive(Debug)] pub enum GuessResult { CORRECT, INCORRECT, TAKEN, INVALID, } pub enum WinState { WIN, LOSE, NIL, } #[derive(Debug)] pub struct Hangman { pub guesses: Vec<char>, pub correct_guesses: Vec<char>, pub incorrect_guesses: Vec<char>, pub incorrect_threshold: i32, // how many we can get wrong. pub word: Word, } // Platform generously supplied on github by Chris Horton // You can find it here: https://gist.github.com/chrishorton/8510732aa9a80a03c829b09f12e20d9c const PLATFORM: [&str; 7] = [ " +---+ | | | | | | ========= ", " +---+ | | O | | | | ========= ", " +---+ | | O | | | | | ========= ", " +---+ | | O | /| | | | ========= ", " +---+ | | O | /|\\ | | | ========= ", " +---+ | | O | /|\\ | / | | ========= ", " +---+ | | O | /|\\ | / \\ | | ========= ", ]; impl Hangman { pub fn new(filename: String) -> Hangman { Hangman { guesses: vec![], correct_guesses: vec![], incorrect_guesses: vec![], incorrect_threshold: 6, word: get_random_word(filename), } } /** Take a guess from the user, either a full string or one character at once. If the user has already entered it, we try again. */ pub fn take_turn(&mut self) -> WinState { let mut input = String::new();
{ "domain": "codereview.stackexchange", "id": 43186, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, game, rust, hangman", "url": null }
beginner, game, rust, hangman io::stdin() .read_line(&mut input) .expect("Something went wrong while reading your line"); input = input.trim().to_string(); if input == "" { // no value entered. return WinState::NIL; } let guessed_char: char = input.chars().collect::<Vec<char>>()[0]; let result = match input.len() { 0 => GuessResult::INVALID, 1 => self.check_char(guessed_char), _ => self.check_str(input), }; self.guesses.push(guessed_char); match result { GuessResult::CORRECT => { // dbg. // println!("Added correct."); self.correct_guesses.push(guessed_char); } GuessResult::INCORRECT => { println!("Incorrect."); self.incorrect_guesses.push(guessed_char); } _ => return WinState::NIL, }; return if self.incorrect_guesses.len() >= self.incorrect_threshold as usize { WinState::LOSE } else if self .word .word // it works. // by removing all the characters that are correct from the words chars, so if the len is 0, we have all the correct ones. .chars() .filter(|x| !self.correct_guesses.contains(x)) .collect::<Vec<_>>() .len() == 0 { WinState::WIN } else { WinState::NIL }; } /* Get what the current game looks like graphically. */ pub fn get_print_state(&self) -> String { let plat = self.get_platform_state(); let mut underscores: String = (0..self.word.length).fold(String::new(), |b, _| b + "_"); let correct_guesses: String = (&self.correct_guesses).into_iter().collect();
{ "domain": "codereview.stackexchange", "id": 43186, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, game, rust, hangman", "url": null }
beginner, game, rust, hangman let correct_guesses: String = (&self.correct_guesses).into_iter().collect(); for c in correct_guesses.chars() { for (i, c2) in self.word.word.chars().enumerate() { if c == c2 { underscores.replace_range(i..i + 1, &String::from(c)); } } } return format!( " {} {} {} ", plat, underscores, (&self.incorrect_guesses).into_iter().collect::<String>() ); } fn get_platform_state(&self) -> String { PLATFORM[self.incorrect_guesses.len()].to_string() } /** To be called whenever a CHARACTER is guessed. */ fn check_char(&self, what: char) -> GuessResult { if self.guesses.contains(&what) { return GuessResult::TAKEN; } else { return if self.word.contains(what) { GuessResult::CORRECT } else { GuessResult::INCORRECT }; } } /** To be called whenever a full string is guessed. */ fn check_str(&self, str: String) -> GuessResult { if str .chars() .all(|x| self.check_char(x) != GuessResult::INCORRECT) // we loop through all the chars and check against them. { GuessResult::CORRECT } else { GuessResult::INCORRECT } } } #[derive(Debug)] pub struct Word { pub word: String, pub length: usize, } impl Word { pub fn new(word: String) -> Word { Word { word: word.to_string(), length: word.len(), } } pub fn contains(&self, letter: char) -> bool { return self.word.contains(letter); } }
{ "domain": "codereview.stackexchange", "id": 43186, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, game, rust, hangman", "url": null }
beginner, game, rust, hangman pub fn get_random_word(filename: String) -> Word { let str = fs::read_to_string(filename).expect("Something went wrong when reading the file."); let strings: Vec<&str> = str.split("\n").collect(); let choice = rand::thread_rng().gen_range(0..strings.len()); Word { word: strings[choice].to_string(), length: strings[choice].len(), } } main.rs: use hangman::Hangman; fn main() { let mut game = Hangman::new("./words.txt".to_string()); dbg!(&game); loop { println!("{}", game.get_print_state()); match &game.take_turn() { hangman::WinState::WIN => { println!("YOU WIN!"); break; } hangman::WinState::LOSE => { println!("{}", game.get_print_state()); println!("You lost :( \nThe word was: {}", game.word.word); break; } _ => (), }; } } words.txt: This is a 500,000 line file of words generated from https://random-word-api.herokuapp.com/all
{ "domain": "codereview.stackexchange", "id": 43186, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, game, rust, hangman", "url": null }
beginner, game, rust, hangman Answer: API considerations The way your API is currently structured it is a bit ... irritating to separate user-interaction from game logic. This comes down to the fact that you handle all user-interaction except the final result within take_turn. This makes for a strange mix of user interaction and logic that would make it horrendously difficult to change the user interaction to a graphical interface. Instead of exposing a take_turn it seems more appropriate for a Hangman instance to expose a guess and an additional is_finished or game_result or something like that which gives the external caller access to what take_turn would return. With that said (and because that'd be a bit of a major overhaul), here's some things that could be changed in the current code without completely changing it. Optional is a thing Currently you have a tri-state enum with that WinState. While this is pretty nice, it's more idiomatic to encode the WinState::NIL as Option::None. Of course that would require adjusting the match expression in main.rs to traverse the Some, but getting familiar with Option should be very useful for future interactions with more complex results. check_str is more forgiving than usual The way check_str is implemented it currently allows guessing partial words. Usually when a full word is submitted as a guess, it is only correct when it's actually the hidden word. Instead of checking whether all chars in the guess are also in the word, you should be able to just check equality with std::string#eq_ignore_ascii_case. And some bullet points:
{ "domain": "codereview.stackexchange", "id": 43186, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, game, rust, hangman", "url": null }
beginner, game, rust, hangman get_random_word could use Word::new instead of duplicating that constructor PartialEq is used to implement != for GuessResult (used in check_str) You could reformulate the check in check_str with any to short-circuit it, when the guess is incorrect. As it is that check is \$O(n^2)\$. I really like the differentiation between INVALID and TAKEN guesses, exposing that and making the user-interaction more responsive to that (while keeping the API considerations in mind) could be a very rewarding extension of this. It's highly non-obvious that incorrect_threshold is related to the PLATFORM's length. You probably want to tie these together to avoid breaking things. I have a suspicion that the way you build underscores could be simplified by iterating over self.word.word and building from that, but I'm not proficient enough to write that off the cuff...
{ "domain": "codereview.stackexchange", "id": 43186, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, game, rust, hangman", "url": null }
javascript, console Title: Inspect console directly on a web page Question: Occasionally, I do some web dev on computers where "inspect" is disabled, which can make debugging JavaScript (a language that is really good at dodging errors) a real pain. I've created a JavaScript file that when you include it via a script tag on an HTML page, it will rewrite the console handlers and add some elements to the bottom of the page: Code: // https://gist.github.com/UnsignedArduino/e23b8329c3a786d1e4e99d8ee941436e // Include this JavaScript file in an HTML file and it will add a DIV element to the bottom of the page which will contain console output and // an textarea to run JavaScript code! // Set false to do nothing const on_page_console = true; if (on_page_console) { (() => { const element_to_append_to = document.body; element_to_append_to.appendChild(document.createElement("br")); element_to_append_to.appendChild(document.createElement("br")); const on_page_console_div = document.createElement("div"); on_page_console_div.style.border = "1px outset black"; on_page_console_div.style.padding = "5px"; const warning_b = document.createElement("b"); warning_b.innerHTML = "On page console:"; on_page_console_div.appendChild(warning_b); element_to_append_to.appendChild(document.createElement("br")); on_page_console_div.appendChild(document.createElement("br")); const console_textarea = document.createElement("textarea"); console_textarea.type = "text"; console_textarea.rows = 10; console_textarea.cols = 40; console_textarea.id = "command_input"; console_textarea.name = "command_input"; console_textarea.readOnly = true; console_textarea.style = "width: 100%; resize: vertical; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box;" on_page_console_div.appendChild(console_textarea); on_page_console_div.appendChild(document.createElement("br"));
{ "domain": "codereview.stackexchange", "id": 43187, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, console", "url": null }
javascript, console on_page_console_div.appendChild(document.createElement("br")); const command_label = document.createElement("label"); command_label.for = "command_input"; command_label.innerHTML = "Run JavaScript code: " + "(Remember that you can only run code in the context " + 'of <a href="/on_page_console.js"><code>/on_page_console.js</code></a> - see ' + '<a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#using_eval_in_content_scripts">here</a>.)'; on_page_console_div.appendChild(command_label); const command_input = document.createElement("textarea"); command_input.type = "text"; command_input.rows = 10; command_input.cols = 40; command_input.id = "command_input"; command_input.name = "command_input"; command_input.style = "width: 100%; resize: vertical; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box;" on_page_console_div.appendChild(command_input); on_page_console_div.appendChild(document.createElement("br")); const command_button = document.createElement("button"); command_button.type = "button"; command_button.innerHTML = "Run"; command_button.onclick = () => { console.log("Result: " + eval(command_input.value)); }; on_page_console_div.appendChild(command_button); element_to_append_to.appendChild(on_page_console_div); const auto_scroll = true; // https://stackoverflow.com/a/50773729/10291933 function produce_text(name, args) { return args.reduce((output, arg) => { return output + (typeof arg === "object" && (JSON || {}).stringify ? JSON.stringify(arg) : arg) + "\n"; }, ""); } function rewire_logging_func(name) { console["old" + name] = console[name]; console[name] = (...arguments) => { console_textarea.innerHTML += produce_text(name, arguments);; console_textarea.scrollTop = console_textarea.scrollHeight; console["old" + name].apply(undefined, arguments); }; }
{ "domain": "codereview.stackexchange", "id": 43187, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, console", "url": null }
javascript, console function rewire_logging() { rewire_logging_func("log"); rewire_logging_func("debug"); rewire_logging_func("warn"); rewire_logging_func("error"); rewire_logging_func("info"); } window.onerror = (error_msg, url, line_number, col_number, error) => { let error_output; if (error.stack == null) { error_output = error_msg + "\n URL: " + url + ":" + line_number + ":" + col_number; } else { error_output = error.stack; } console.error(error_output); return false; }; rewire_logging(); })(); } In case it's needed, here's a Repl. I would appreciate it if I could get help with (my probably weird) code styles, best practices on how to implement such a thing, and performance. (The page will freeze while executing JavaScript) Note that this was designed with the fact that the server could only serve static files, and not inject HTML and such. Answer: Here are my thoughts: tl;dr: Page freezing might be related to sharing an id between elements. Some other changes might fix readability, depending on your preferences. Page freezing: I couldn't reproduce this, but I have a guess as to what was causing it. You are sharing an id between the the two text areas - I think you copy/pasted the code for the output text area to reuse as the input text area. You want to avoid reusing id's. This may be a personal preference, so take it for what it is worth. I have a hard time reading/deciphering html when it is added using create/append. I prefer to write it up as a string and use insertAdjacentHTML at the end. (you can see my approach for this in the code at the end). I renamed/added a few variables to help with readability and reuse.
{ "domain": "codereview.stackexchange", "id": 43187, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, console", "url": null }
javascript, console I changed on_page_console to showCustomConsole. I thought this would make the purpose of the variable/it's use in the if statement a bit more understandable. Now if you look at the if statement, it is obvious what we are checking before we run the encased code. I moved the id's used for the textareas out of the html string and defined them as variables. This made reuse easier, and if you want to change the id to something more meaningful, you only need to do so in 1 spot. Styling - I'm a bit wishy-washy on this one. I typically try to avoid inline-styling, but you don't have a lot of it happening. I noticed you reused the styling for the two textareas, so I saved those as a string and inserted them into the consoleHtml string as an argument. If you were going to really add bunch of bells & whistles to this, I'd suggest using classes in a style script to better handle styling. I noticed in your example, you had 'console.log('here') in the input textarea. All you need to do is write "here" and you'll get "Result: here" in the output textarea. If you want to do some math, just type it in (example, 1+1 in the input area will result in "Result: 2" in the output area.). You can even use variables: let a = 1 let b = 2 a + b Result: 3 Template Literals - I prefer these to strings. I think it is easier to read a string using these, especially when you are mashing strings and variables together. I didn't take apart the functions you built based off of the code from the stack overflow link in the comments. I figured they were mostly self-explanatory. I did however change the console_textarea to console_output, using the id for the element. I thought this was another place where the code was more readable and storing the id in a variable helped avoid any accidental id reuse. I originally worked through this on codepen.
{ "domain": "codereview.stackexchange", "id": 43187, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, console", "url": null }
javascript, console I originally worked through this on codepen. const showCustomConsole = true if(showCustomConsole){ let documentBody = document.body let consoleTitle = `On Page Console:` let consoleId = 'console_out' let consoleLabel = `Run JavaScript code: (Remember that you can only run code in the context of <a href="/on_page_console.js"><code>/on_page_console.js</code></a> - see <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#using_eval_in_content_scripts">here</a>.) ` let scriptId = 'script_in' let textAreaStyle = 'style="width: 100%; resize: vertical; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box;"' function runHandler(){ console.log(`Result: ${eval(document.getElementById(scriptId).value)}`) } // https://stackoverflow.com/a/50773729/10291933
{ "domain": "codereview.stackexchange", "id": 43187, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, console", "url": null }
javascript, console function produce_text(name, args) { return args.reduce((output, arg) => { return output + (typeof arg === "object" && (JSON || {}).stringify ? JSON.stringify(arg) : arg) + "\n"; }, ""); } function rewire_logging_func(name) { let console_output = document.getElementById(consoleId) console["old" + name] = console[name]; console[name] = (...arguments) => { console_output.innerHTML += produce_text(name, arguments);; console_output.scrollTop = console_output.scrollHeight; console["old" + name].apply(undefined, arguments); }; } function rewire_logging() { rewire_logging_func("log"); rewire_logging_func("debug"); rewire_logging_func("warn"); rewire_logging_func("error"); rewire_logging_func("info"); } window.onerror = (error_msg, url, line_number, col_number, error) => { let error_output; if (error.stack == null) { error_output = error_msg + "\n URL: " + url + ":" + line_number + ":" + col_number; } else { error_output = error.stack; } console.error(error_output); return false; }; let consoleHtml = ` <br><br> <div style="border:1px outset black; padding: 5px;"> <b>${consoleTitle}</b> <br> <textarea rows="10" cols="40' type="text" id="${consoleId}" readonly style="${textAreaStyle}"></textarea> <br> <label for="${consoleId}">${consoleLabel}</label> <textarea rows="10" cols="40' type="text" id="${scriptId}" style="${textAreaStyle}"></textarea> <button onclick="runHandler()">Run</button> </div> ` documentBody.insertAdjacentHTML("beforeend", consoleHtml) rewire_logging() } <head> <title>Inspect console directly on a web page</title> </head> <body> <h3>Sample Web Page</h3> <script></script> </body>
{ "domain": "codereview.stackexchange", "id": 43187, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, console", "url": null }
c#, .net, async-await Title: Reading and modify big set of data Question: I have a method that iterate over my table question in database and then will split a column commentaires and finnally put results in table propositions column commentaire so I have a code that read a large set of data DicCom 16400 rows and then lstProp with 7 rows so in total we have 116000 rows to modify. Here is my code : public static void UpdateDatabaseProCom() { Dictionary<int, string[]> DicCom = new Dictionary<int, string[]>(); List<string> listR = new List<string> { "R1", "R2", "R3", "R4", "R5", "R6", "R7" }; var QueryListCom = from e in context.question where e.Id_types == 5 && (e.Commentaires.StartsWith("/R") || e.Commentaires.StartsWith("/ R") || e.Commentaires.StartsWith("R1")) && listR.All(x => e.Commentaires.Contains(x)) select new { e.Id, e.Commentaires }; foreach (var item in QueryListCom.ToDictionary(p => p.Id, p => p.Commentaires)) { DicCom.Add(item.Key, item.Value.Split('/')); } foreach (var qstComSplit in DicCom.AsParallel()) { var qst = context.question.FirstOrDefault(item => item.Id == qstComSplit.Key); var CommSplitted = qstComSplit.Value.Skip(1).ToArray(); var lstProp = qst.proposition.ToArray(); var counter = 0; for (int i = 0; i < lstProp.Count(); i++) { if (CommSplitted.Count() == 7 && lstProp.Count() == 7) { lstProp[i].Commentaires = CommSplitted[counter]; context.SaveChanges(); Console.WriteLine(qstComSplit.Key); counter++; } } } }
{ "domain": "codereview.stackexchange", "id": 43188, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, async-await", "url": null }
c#, .net, async-await My code take munch time to finsih, so I want to optimize it and I want to know how can I do that. I see that my code can be transformed to async await because it performs an expensive computation and have long-running operation so in this case we can talk about CPU-bound yes or no but with the running of my operation I don't need to yield the program to do another work so I have just a one task to do in my code ? When I have this code it is a good idea to think to use Task ? Answer: The most obvious improvement is to call SaveChanges() after the loops. This allows EF Core (I assume) to batch the updates for more performance. CommSplitted and lstProp are arrays (because of ToArray()). Use the array Length property instead of the LINQ extension method Count(). Count() will detect that this is an array and not loop the collection. Instead, it will call the Length property. But still, this involves a little overhead. For other collection types use the Count property (without parameter braces). By inspecting the inner loop more closely, it becomes apparent that the modifications will only be applied when the length of both arrays are equal to 7. Since the length of these arrays does not change during the execution of the loop, do this test before the loop. Or did you mean to do something different like basing the condition on a property of the array elements or just make sure both arrays have the same length with if (CommSplitted.Length == lstProp.Length)? The counter will always be equal to i. Therefore, you can use i as index in CommSplitted. The magic number 7 can be replaced by a constant. This allows you to give it a descriptive name. It also makes it easier and safer to change this number in future as you will have to do it only in a single place. You will be sure not to miss a place. Another magic number is Id_types 5. No idea what 5 stands for. A well named constant would clarify this.
{ "domain": "codereview.stackexchange", "id": 43188, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, async-await", "url": null }
c#, .net, async-await It makes no sense to add the questions to a dictionary that is never looked up by key (this is what a dictionary is for) just to loop over its elements and to add them to another dictionary which is also never looked up by key. If you intend to loop through a collection or to access the items by index, use an array (fixed length) or a List<T> (variable length). If you must store a pair of values, you can use a KeyValuePair<TKey, TValue> or a tuple as element type. Of what type is qst.proposition? I assume it to be a List<Proposition>. Calling .ToArray() has no apparent sense. In the foreach loop you are querying the very question by Id that you queried already in the first loop. This is an unnecessary round-trip to the database. Loop the questions returned form the database directly and do the split later. As @robH pointed out in a comment, do not use AsParallel(). The length of listR is constant. Make it an array. public static void UpdateDatabaseProCom() { const int RequiredLength = 7; string[] listR = new[] { "R1", "R2", "R3", "R4", "R5", "R6", "R7" }; var questions = from q in context.question where q.Id_types == 5 && ( q.Commentaires.StartsWith("/R") || q.Commentaires.StartsWith("/ R") || q.Commentaires.StartsWith("R1") ) && listR.All(x => q.Commentaires.Contains(x)) select q; foreach (var question in questions) { string[] comments = question.Commentaires.Split('/').Skip(1).ToArray(); if (comments.Length == RequiredLength && question.proposition.Count == RequiredLength) { for (int i = 0; i < RequiredLength; i++) { question.proposition[i].Commentaires = comments[i]; Console.WriteLine(question.Id); } } } context.SaveChanges(); }
{ "domain": "codereview.stackexchange", "id": 43188, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, async-await", "url": null }
c#, .net, async-await I am not sure whether proposition is a list or an array. You may have to replace Count by Length in the latter case. Note: EF Core will automatically split the updates done in the database by SaveChanges in reasonable sized batches. See Efficient Updating. In case you need to know the number of changes, SaveChanges returns the number of database updates. int count = context.SaveChanges(); Avoid calling ToList, ToArray or ToDictionary on IQueryable<T> (resulting from querying a database) and on IEnumerable<T> if possible. This avoids unnecessary memory allocations. The items are being retrieved from the source as you are looping the result set without storing it in a collection. In .NET Core and with C# 8.0+ you can replace .Skip(1).ToArray() with a range operator: string[] comments = question.Commentaires.Split('/')[1..]; This operation is I/O (database) bound, not CPU bound. There are no complex calculations. Database operations require disk accesses measured in milliseconds (ms). CPU operations are measured in nanoseconds (ns). There is a factor of one million between ns and ms! Therefore, running parallel tasks will not help. Async/await does not speed up things, it only keeps the UI responsive while the operation is running.
{ "domain": "codereview.stackexchange", "id": 43188, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, async-await", "url": null }
java, object-oriented, interview-questions, game-of-life Title: Conway's Game of Life Object oriented implementation in Java Question: I have designed Conway's Game of Life in Java, the solution follows Object Oriented design and paradigm, please review and let me know the feedback Class Cell Cell has one property alive and behavior to update alive status public class Cell { private boolean alive; public Cell( boolean alive) { this.alive = alive; } public void updateStatus(int aliveNeighboursCount) { if (alive && aliveNeighboursCount > 3) { alive = false; } else if (alive && aliveNeighboursCount < 2) { alive = false; } else if (aliveNeighboursCount == 3 && !alive) { alive = true; } } public boolean isAlive() { return this.alive; } } Class Grid getAliveNeighboursCount method finds the alive neighbor of every cell and returns the count nextCycle creates new cells with their alive status based neighbours count and replaces the current cells of the Grid public class Grid { private Cell[][] cells; public Grid(int size, Randomizer randomizer) { this.cells = randomizer.loadCells(size); } private boolean isOutOfBound(int maxSize, int i, int j) { return (i < 0 || i == maxSize) || (j < 0 || j == maxSize); } int getAliveNeighboursCount(int xPos, int yPos) { int aliveNeighboursCount = 0; for (int i = xPos - 1; i <= xPos + 1; i++) { for (int j = yPos - 1; j <= yPos + 1; j++) { if (isOutOfBound(cells.length, i, j) || (i == xPos && j == yPos)) { continue; } aliveNeighboursCount += cells[i][j].isAlive() ? 1 : 0; } } return aliveNeighboursCount; }
{ "domain": "codereview.stackexchange", "id": 43189, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, object-oriented, interview-questions, game-of-life", "url": null }
java, object-oriented, interview-questions, game-of-life public void nextCycle() { Cell[][] newCells = new Cell[this.cells.length][this.cells[0].length]; for (int i = 0; i < newCells.length; i++) { for (int j = 0; j < newCells[0].length; j++) { Cell cell = new Cell(false); cell.updateStatus(getAliveNeighboursCount(i, j)); newCells[i][j] = cell; } } this.cells = newCells; } @Override public String toString() { StringBuilder gridString = new StringBuilder(); for (int i = 0; i < cells.length; i++) { for (int j = 0; j < cells[0].length; j++) { gridString.append(cells[i][j].isAlive() ? "*\t" : "-\t"); } gridString.append("\n"); } return gridString.toString(); } } Class Randomizer Grid takes Randomizer object to randomize cells based on the biased random number import java.util.Random; public class Randomizer { private final int aliveCellsForEveryTenCell; public Randomizer(int aliveCellsForEveryTenCell) { this.aliveCellsForEveryTenCell = aliveCellsForEveryTenCell; } private boolean getNext() { return new Random().nextInt(10) <= aliveCellsForEveryTenCell; } public Cell[][] loadCells(int size) { Cell[][] cells = new Cell[size][size]; for (int i = 0; i < size; i++) { for (int j = 0; j < cells[0].length; j++) { cells[i][j] = new Cell( getNext()); } } return cells; } } Class Action This class is to execute the Code public class Action { public static void main(String[] args) throws InterruptedException { Randomizer randomizer = new Randomizer(4); Grid grid = new Grid(25, randomizer); System.out.println(grid); for (int i = 0; i < 10; i++) { Thread.sleep(1000); grid.nextCycle(); System.out.println(grid); } } }
{ "domain": "codereview.stackexchange", "id": 43189, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, object-oriented, interview-questions, game-of-life", "url": null }
java, object-oriented, interview-questions, game-of-life Answer: It's hard to judge a design when there is no information about what you want from it. If you wanted classes and methods, well you succeeded, but that's about it. But if you, for example, wanted extensibility and robustness, then it's a whole different thing. You added the "interview-questions" tag. Can you tell us what your interviewer was looking for? Grid For me the Grid class is supposed to encapsulate and protect the array. That is broken in your design as the array is created by Randomizer. There is very little point in trying to verify the bounds of the array in Grid because Grid doesn't even know the size of the array it has. There is no guarantee that Randomizer provides what it is asked to provide because a programmer can subclass Randomizer and return data that is not compatible to what Grid expects. You could add error checking to ensure the array returned by Randomizer has correct dimensions, but that's "treating the symptoms, not the disease." A better approach would be for Grid to initialize the array itself and ask Randomizer to place the live/dead value to the cells created by Grid using setter methods. Randomizer Conway's game of life is about creating seeds that provide interesting generations. You should define the Randomizer as an interface, called something like Seeder, and make Grid accept the interface instead of some concrete implementation. Then you can implement different seeders, like your RandomSeeder. Cell It has no meaning outside the Grid class. It seems to only exist as a container for the game rules, and even the rules have been split between the Grid and the Cell (grid being responsible for counting the neighbors and cell making the decision based on that count). Maybe it exists only for the sake of having a class?
{ "domain": "codereview.stackexchange", "id": 43189, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, object-oriented, interview-questions, game-of-life", "url": null }
c# Title: c# SqlDataReader Question: This logic get data from a database and checks if the inbound ipAddress is within the range or if its equal to one we have stored in the system. In production its using a SqlDataReader but in the working sample I am just using a DataTable. How I could possibly improve the code quality with using the SqlDataReader public static bool CheckIPAddressRange(string accessKey, string ipAddress) { bool canAccess = false; string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; SQLHelper sql = new SQLHelper(conn); SqlParameter[] parms = new SqlParameter[] { new SqlParameter("@AccessKey", SqlDbType.VarChar,36), }; parms[0].Value = accessKey; SqlDataReader dr = sql.ExecuteReaderStoreProcedure("dbo.[Select_IPRange]", parms); while (dr.Read()) { bool IsRange = Convert.ToBoolean(dr["IsRange"]); if (IsRange == true){ canAccess = IsInRange(Convert.ToString(dr["IPAddress"]), Convert.ToString(dr["IPEndAddress"]), ipAddress); } else { string accessIP = Convert.ToString(dr["IPAddress"]); if (ipAddress == accessIP){ canAccess = true; } } if (canAccess == true){ break; } } dr.Close(); return canAccess; } working sample https://dotnetfiddle.net/1nE9h3 Answer: Here are my suggestions SqlParameter You can use the object initializer to set the Value directly like this var spParameters = new SqlParameter[] { new SqlParameter("@AccessKey", SqlDbType.VarChar, 36) { Value = accessKey } }; Convert.ToString vs GetString You can convert your dr to a IDataReader interface You can use there GetBoolean, GetString, etc. They require an index so you have to use GetOrdinal to translate column name to index Your branching logic could be simplified like this
{ "domain": "codereview.stackexchange", "id": 43190, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#", "url": null }
c# Your branching logic could be simplified like this bool ProcessRecord(IDataRecord record, string ipAddress) { bool isRange = record.GetBoolean(record.GetOrdinal("IsRange")); if (isRange) { return IsInRange(record.GetString(record.GetOrdinal("IPAddress")), record.GetString(record.GetOrdinal("IPEndAddress")), ipAddress); } else { return ipAddress == record.GetString(record.GetOrdinal("IPAddress")); } } DataReader With the above helper method your main while loop can be simplified like this SqlDataReader reader = sql.ExecuteReaderStoreProcedure("dbo.[Select_IPRange]", spParameters); while (reader.Read()) { if (canAccess = ProcessRecord((IDataRecord)reader, ipAddress)) break; } reader.Close(); return canAccess;
{ "domain": "codereview.stackexchange", "id": 43190, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#", "url": null }
javascript, game, physics, pong Title: Predict bouncing ball destination in JavaScript Question: In a Pong-style 2D game, a ball (a circle of radius BALLRADIUS) can bounce (with perfect elasticity) on the top or bottom of the screen. When it hits the left or right side of the screen, one of the players scores a point. This function calculates the y-coordinate at which a ball initially at coordinates (x, y) and travelling at velocity (vx, vy) will next hit the left or right side of the screen. const WIDTH = 1000; const HEIGHT = 1000; const BALLRADIUS = 10; function predictBallDestination(x, y, vx, vy) { /* Predict y coordinate at which a ball at (x, y) and travelling at velocity (vx, vy) will next hit the left or right side of the screen. The ball can bounce on the top or bottom of the screen with perfect elasticity. */ if (vy === 0) { // Traveling horizontally return y; } if (vx === 0) { // Traveling vertically throw new Error("Ball.predict: ball can never reach the side because vx is 0"); } // Calculate horizontal distance to the side towards which it is traveling const dx = vx > 0 ? WIDTH - BALLRADIUS - x : x - BALLRADIUS; // Calculate total vertical distance it will travel const dy = Math.abs(vy * dx / vx); // Calculate remaining vertical distance to travel after the first bounce let remainder; if (vy > 0) { // Initially going down if (dy <= HEIGHT - y - BALLRADIUS) { return y + dy; // no bounce } remainder = dy - (HEIGHT - y - BALLRADIUS); } else { // Initially going up if (dy <= y - BALLRADIUS) { return y - dy; // no bounce } remainder = dy - (y - BALLRADIUS); } // Calculate distance it will still have to travel after the last bounce const lastPart = remainder % (HEIGHT - BALLRADIUS * 2);
{ "domain": "codereview.stackexchange", "id": 43191, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, game, physics, pong", "url": null }
javascript, game, physics, pong const bounces = 1 + Math.floor(remainder / (HEIGHT - BALLRADIUS * 2)); const evenBounces = bounces % 2 === 0; console.log("Bounces", bounces); if ((vy > 0 && evenBounces) || (vy < 0 && !evenBounces)) { // If the ball is going down after the last bounce return lastPart + BALLRADIUS; } else { // going up after the last bounce return HEIGHT - BALLRADIUS - lastPart; } } console.log(predictBallDestination(500, 500, 1, 0)); // 500 - travels right and hits the right side at (WIDTH - 10, 500) console.log(predictBallDestination(500, 500, 1, .5)); // 745 - travels down-right without bounce console.log(predictBallDestination(500, 500, 1, 1)); // 990 - hits at the corner console.log(predictBallDestination(500, 500, 1, 2)); // 500 - bounces once at the middle bottom console.log(predictBallDestination(500, 500, 1, 4)); // 500 - bounces twice and still hits in the middle I would appreciate any suggestions to simplify the logic or otherwise improve this function. Is there some way to take care of all the different cases (going up or down, no bounce, odd number of bounces, even number of bounces) with a single formula?
{ "domain": "codereview.stackexchange", "id": 43191, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, game, physics, pong", "url": null }
javascript, game, physics, pong Answer: Single responsibility. Never ignore or cover up bugs. I will point out that the function predictBallDestination has gone way outside its role by throwing an error due to a game state that should never happen. Even if it is possible somehow for the ball to have no horizontal movement, detecting this state should be done at a much higher level. Yes this function is where vx = 0 will matter, but then a divide by zero is the least of your problems. Always attempt to recover the correct state, and reserve throwing errors only when there is absolutely no way to recover the valid state. Ask yourself "What is setting vx == 0?" and fix the problem there! Throwing an error is just ignoring the underlying bug. More constants You code is doing a lot of repeated calculations. Most notable you are subtracting BALLRADIUS many times. Extend your list of constants to avoid the needless math. For example to define a play field with inset const WIDTH = canvas.width; // Whatever sets the size const HEIGHT = canvas.height; const INSET = 50; const BALLRADIUS = 10; const LEFT = INSET + BALLRADIUS; const RIGHT = WIDTH - INSET - BALLRADIUS; const TOP = INSET + BALLRADIUS; const BOTTOM = HEIGHT - INSET - BALLRADIUS; To many conditions You are checking the ball velocity over and over, is ball going left or right, up or down. That can all be done in the math. The only check needed is which edge you want the y position at. If you set the max slope of the ball's travel such that it does not hit the top and bottom edge more than say 2000 times you can simplify the final odd even check. // using constants from above const MAX_BOUNCES = 2000; // number of times ball hits top and bottom function getYPos(x, y, vx, vy) { const h = BOTTOM - TOP; const edge = vx < 0 ? LEFT : RIGHT; const hy = ((y + (edge - x) * vy / vx) - TOP + h * MAX_BOUNCES) % (h * 2); return (hy < h ? hy : h - hy + h) + TOP; }
{ "domain": "codereview.stackexchange", "id": 43191, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, game, physics, pong", "url": null }
javascript, react.js Title: React Custom hooks - useFetch Question: I created custom hooks, which allows to fetch the API using two request methods 'GET' and 'POST'. Use cases: const { data: fetchData, loading: fetchLoading, error: fetchError } = useFetch('/url'); const { data: postData, loading: postLoading, error: postError, post } = useFetch('/url', 'POST'); <DisplayData data={fetchData} /> <Button onClick={()=> post({id:4, name: 'jody'})} /> useFetch.js: const useFetch = (url, method) => { const [data, setData] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(false); if (!url || url.length === 0) { console.error('Missing url'); if (!error) setError(true); return { error }; } const runFetchProcess = async (data) => { const requestMethod = method === 'POST' ? 'POST' : 'GET'; let requestHeader = { headers: { 'Content-Type': 'application/json' }, method: requestMethod }; if (data) { requestHeader.body = JSON.stringify(data); } try { const response = await fetch(url, requestHeader); const responseData = await response?.json(); if (!response.ok) { setLoading(false); setError(true); throw Error('something wrong here mate'); } else { setData(responseData); setLoading(false); } } catch (e) { setError(true); console.error('useFetch.js', e); } finally { setLoading(false); } }; const post = (data) => { if (!data) return; runFetchProcess(data); }; useEffect(() => { if (method) return; runFetchProcess(); }, []); return { data, loading, error, post }; }; export default useFetch; Please have a look my code. Looking forward to have some great feedback.
{ "domain": "codereview.stackexchange", "id": 43192, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, react.js", "url": null }
javascript, react.js Please have a look my code. Looking forward to have some great feedback. Answer: Be sure to use a linter when using hooks. The linter discovered 3 issues: React Hook useEffect has missing dependencies: 'method' and 'runFetchProcess'. Either include them or remove the dependency array. (react-hooks/exhaustive-deps) The 'runFetchProcess' function makes the dependencies of useEffect Hook (at line 43) change on every render. To fix this, wrap the definition of 'runFetchProcess' in its own useCallback() Hook. (react-hooks/exhaustive-deps) React Hook "useEffect" is called conditionally. React Hooks must be called in the exact same order in every component render. Did you accidentally call a React Hook after an early return? (react-hooks/rules-of-hooks) -- Fixed by moving if from line 10ish to line 22ish. I've also removed the return from use effect. The return from use effect should be a callback to cleanup code.
{ "domain": "codereview.stackexchange", "id": 43192, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, react.js", "url": null }
javascript, react.js const useFetch = (url, method) => { const [data, setData] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(false); if (!url || url.length === 0) { console.error('Missing url'); if (!error) setError(true); // return { error }; // moved to line 22ish } const runFetchProcess = useCallback(async (data) => { const requestMethod = method === 'POST' ? 'POST' : 'GET'; let requestHeader = { headers: { 'Content-Type': 'application/json' }, method: requestMethod }; if(error) { return; } if (data) { requestHeader.body = JSON.stringify(data); } try { const response = await fetch(url, requestHeader); const responseData = await response?.json(); if (!response.ok) { setLoading(false); setError(true); throw Error('something wrong here mate'); } else { setData(responseData); setLoading(false); } } catch (e) { setError(true); console.error('useFetch.js', e); } finally { setLoading(false); } }, [error, method, url]); const post = (data) => { if (!data) return; runFetchProcess(data); }; useEffect(() => { if (!method) { runFetchProcess(); } }, [method, runFetchProcess]); return { data, loading, error, post }; }; export default useFetch; Also, be sure you don't update state on an unmounted component. See useSafeSetState Finally, consider simplifying / untwisting your code by creating 2 hooks, useFetch for GET and useSend for POST. Calling useFetch for posting is confusing. Also, the second parameter my be hard to remember and is error prone. Is it POST or post?
{ "domain": "codereview.stackexchange", "id": 43192, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, react.js", "url": null }
java, parsing, file, serialization Title: Processing a binary file with buffer length tags Question: I am trying to process a very large binary file using MappedByteBuffer from java.nio package. This is how the data looks like in the file: [0, 12, 83, 0, 0, 0, 0, 9, -11, -66, -116, -91, 100, 79, 39, 82, 0, 1, 0, 0, 10, 52, 126, -35, 45, -75, 65, 32, 32, 32, 32, 32, 32, 32, 78, 32,0,0, 0, 100, 78, 67, 90, 32, 80, 78, 32, 49, 78, 0, 0, 0, 0, 78.... ....10 GB of more data] We skip the first byte (0), the next byte(12) tells us how many bytes to process next. After processing 12 bytes, we see 39 and then we process next 39 bytes and so on. Here is the code that works but it's not the most efficient code. MappedByteBuffers are expensive to create and there is no way to explicitly release them, we let the GC reclaim them when ever it runs. I am creating 2 mappedbytebuffers, one to read the first byte and then another to read the number of bytes the first buffer told me to. I could read let's say 1024 bytes in the first buffer itself but I am not sure how to handle the case where there is not enough number of bytes left to read at the end of the buffer. I am open to using 3rd party libraries, I am already using bytes-java to process my messages later. I tried using Chronicle-Bytes but couldn't understand how to use it in my use case. public void parse(String filename) throws IOException { try (RandomAccessFile file = new RandomAccessFile(new File(filename), "r")) { FileChannel inChannel = file.getChannel(); //skip the first byte, start at 1 long position = 1; long length = inChannel.size(); //get the number of bytes to read by reading the first byte int bytesToRead = 1; while(position < length) { //first mapped buffer to read the number of bytes to read ahead MappedByteBuffer msgTypeBuffer = inChannel.map(FileChannel.MapMode.READ_ONLY, position, bytesToRead);
{ "domain": "codereview.stackexchange", "id": 43193, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, parsing, file, serialization", "url": null }
java, parsing, file, serialization bytesToRead = (int) (msgTypeBuffer.get()); //we have the number of bytes to read position++; //move cursor to the next position //second bytebuffer - reads bytesToRead MappedByteBuffer msgBuffer = inChannel.map(FileChannel.MapMode.READ_ONLY, position, bytesToRead); byte[] payBytes = new byte[bytesToRead]; msgBuffer.get(payBytes, 0, bytesToRead); Message m = parsers.messageIn(payBytes, stock); if (!m.isEmpty()) { //process the message } //move the cursor after the bytes that have been read position += bytesToRead + 1; } } } Answer: You seem to have taken a very odd starting position here. The data file is in a simple stream format, so I really can't see why you'd bother with RandomAccessFiles and MappedByteBuffers - they add no value. The processing can be boiled down to this (add error handling as needed) : Open a java.io.BufferedInputStream for the file Read first byte (perhaps check it's actually zero) and discard it Read a length byte Allocate an appropriately sized byte array Read into the array (different form of the read() method) Process the array Repeat from step 3 until finished (let GC deal with the arrays you don't need) A sketch of the code would be : public void parse(String filename) throws IOException { try (BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(filename))) { //skip the first byte inStream.read();
{ "domain": "codereview.stackexchange", "id": 43193, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, parsing, file, serialization", "url": null }
java, parsing, file, serialization //skip the first byte inStream.read(); int bytesToRead = 0; while((bytesToRead = inStream.read())!= -1) { byte[] payBytes = new byte[bytesToRead]; // inStream.read(payBytes); // May not read all bytes requested - prefer the loop below int offset = 0; while(bytesToRead > 0) { int bytesRead = inStream.read(payBytes, offset, bytesToRead); offset += bytesRead; bytesToRead -= bytesRead; } Message m = parsers.messageIn(payBytes, stock); if (!m.isEmpty()) { //process the message } } } }
{ "domain": "codereview.stackexchange", "id": 43193, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, parsing, file, serialization", "url": null }
c++, memory-management, io, video Title: C++ intializing and saving mp4 ftyp box struct byte by byte Question: I'm unsure whether the way I'm performing initialization is recommended, and whether there is a simpler way to save out a struct like the one I'm using. The main points of feedback I'm looking for are around the use of memcpys and reinterpret_casts or (char*)& casts and whether they are unavoidable. Additional background for a reader is I needed to convert from my system's little endian format to bigendian which is also required for mp4 by the spec I'm reading. Unfortunately this reverses things like the uint32 made from "ftyp", and so I have written "pytf" instead as a temporary work around. struct Box { uint32_t size; uint32_t boxtype; // this is the fourcc type so it's a 32 because I believe it is actually 4 8chars together }; struct FTBox : Box { uint32_t brand; uint32_t minor; uint32_t compatible_brands[2] = {0,0}; }; void run_functions() { stringstream tt; FTBox r{}; cout << sizeof(r) << endl; string mytype = "pytf"; memcpy(&r.boxtype, mytype.data(), 4); cout << "type is " << r.boxtype << endl; cout << sizeof(r) << endl; r.minor = 0; cout << sizeof(r) << endl; memcpy(&r.brand, (char *)&"14pm", 4); cout << "major brand is " << r.brand << endl; cout << sizeof(r) << endl; vector<uint32_t> brands; brands.reserve(2); memcpy(&brands[0], (char *)&"mosi", 4); memcpy(&brands[1], (char *)&"xxxx", 4); memcpy(&r.compatible_brands, &brands[0], 8); cout << "brand one is " << r.compatible_brands[0] << endl; cout << "brand two is " << r.compatible_brands[1] << endl; cout << sizeof(r) << endl; r.size = sizeof(r); cout << sizeof(r) << endl;
{ "domain": "codereview.stackexchange", "id": 43194, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, memory-management, io, video", "url": null }
c++, memory-management, io, video uint32_t *rptr = reinterpret_cast<uint32_t *>(&r); size_t number = sizeof(r) / sizeof(uint32_t); cout << "number is " << number << endl; for (int i = 0; i < number; i++) { cout << "step " << i << "is " << *(rptr + i) << endl; uint32_t bigend = __bswap_32(*(rptr + i)); // make bigend into bytes char *bytes = reinterpret_cast<char *>(&bigend); // should stil be 4 bytes for (int j = 0; j < sizeof(bigend); j++) { tt << *(bytes + j); } } ofstream f{}; f.open("test.mp4", ios::binary); f.write(tt.str().data(), sizeof(r)); }
{ "domain": "codereview.stackexchange", "id": 43194, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, memory-management, io, video", "url": null }
c++, memory-management, io, video Answer: When I teach C++, the mantra I repeat over and over is: When you get the types right, everything Just Works. What’s going on here is a good example of how code becomes messy and terrible and inefficient when you don’t get the types right. C++ is a strongly-typed language. It’s probably the most strongly-typed language you’re ever going to use. If you’re not going to use the type system, you’re going to be swimming upstream the whole time, fighting the language. All those ugly casts are a symptom of that. Here’s a pretty glaring example: the fact that you have to manually reverse those strings because you’re forcing them into 32-bit integers. If you think about what you’re trying to do, it’s just silly. They’re not numbers; they’re strings. Jamming them into an integer just because they technically “fit” is ridiculous. This just makes no sense: uint32_t s = "ftyp";. The correct kind of type you should be using for this is something like std::array<char, 4>. (You could use std::string, but that’s overkill when you know exactly how large the string will always be, and it’s so tiny.) If you’d done that, writing it out would be as simple as: f.write(boxtype.data(), boxtype.size()). But even a bare array like that isn’t great. As usual, you need to get the type right. Here’s one example of how: class box_type_t { public: constexpr explicit box_type_t(std::string_view sv) : _data{'\0', '\0', '\0', '\0'} { if (sv.size() > 4) throw std::invalid_argument{"string is too long for box type"}; std::ranges::copy(sv.substr(0, 4), _data.begin()); } explicit operator std::string() const { return std::string{_data.data(), _data.size()}; } constexpr explicit operator std::string_view() const noexcept { return std::string_view{_data.data(), _data.size()}; } constexpr auto operator<=>(box_type_t const&) const noexcept = default;
{ "domain": "codereview.stackexchange", "id": 43194, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, memory-management, io, video", "url": null }
c++, memory-management, io, video constexpr auto operator<=>(box_type_t const&) const noexcept = default; friend constexpr auto operator<=>(box_type_t const& lhs, std::string_view rhs) noexcept { return std::string_view{lhs} <=> rhs; } template <typename Char, typename Traits> friend auto operator<<(std::basic_ostream<Char, Traits>& o, box_type_t const& bt) -> std::basic_ostream<Char, Traits>& { // Only need this temporary buffer so it's NUL terminated. // // Alternately, you could make _data a *5* char array, and NUL // terminate it there. Or you could widen each character and put them // in the stream one at a time (but that's problematic). auto buf = std::array<char, 5>{'\0', '\0', '\0', '\0', '\0'}; std::ranges::copy_n(bt._data.data(), bt._data.size(), buf.data()); return o << buf.data(); } private: std::array<char, 4> _data; }; Now usage of this type is simple, clean, elegant, and idiot-proof: // constructing a box type auto bt = box_type_t{"ftyp"}; // checking a box type bt == "ftyp"; //or: auto bt2 = box_type_t{"ftyp"}; bt == bt2; // printing a box type // (note, doesn't reverse the string!) std::cout << bt; // using box types with other libraries auto sv = std::string_view{bt}; // convert to a string view auto s = std::string{bt}; // or convert to a string
{ "domain": "codereview.stackexchange", "id": 43194, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, memory-management, io, video", "url": null }
c++, memory-management, io, video Once again: When you get the types right, everything Just Works. (One thing I haven’t accounted for anywhere is if the system isn’t using UTF-8 or ASCII for char. In that case 'a' may not be 0x61, so "ftyp" may not be translating to the correct sequence of numeric values. What you should do is always use u8"ftyp", and have the box_type_t constructor insist on only accepting std::basic_string_view<char8_t> (even if it holds chars internally). But that’s a complication that adds a lot of noise, so I’ve just ignored it.) Now, your plan is to write to MP4 files, which has its own standards and quirks, so you don’t want to be using the standard functions. Whenever the standard functions do the job, then it’s fine to defer to them, but you want control. So what you should probably do is create a namespace for all your MP4 stuff (that’s something you should do anyway), and create a set of file writing functions: namespace mp4 { namespace _detail { // This tag will be handy to make write functions for classes in the mp4 namespace. struct mp4_write_tag {}; // To write 32-bit ints: auto write(std::ostream&, std::uint_fast32_t) -> std::ostream&; auto write(std::ostream&, std::uint_least32_t) -> std::ostream&; // Note: uint32_t is OPTIONAL, so you can't assume it exists. You need to // check if it's supported. #ifdef UINT32_MAX auto write(std::ostream&, std::uint32_t) -> std::ostream&; #endif // Any other functions you want.... // // For example, if you want to be able to write strings: // auto write(std::ostream&, std::string_view) -> std::ostream&; // // Or, if you want to write random byte data: // template <std::size_t Extent> // auto write(std::ostream&, std::span<std::byte, Extent>) -> std::ostream&; // template <std::size_t Extent> // auto write(std::ostream&, std::span<unsigned char, Extent>) -> std::ostream&;
{ "domain": "codereview.stackexchange", "id": 43194, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, memory-management, io, video", "url": null }
c++, memory-management, io, video // This function transforms non-member calls from // write(o, t); // to: // t.write(mp4::_detail::mp4_write_tag{}, o); // So classes in the mp4 namespace can have non-member write() functions // without conflicting with the write() niebloid. template <typename T> auto write(std::ostream& o, T&& t) -> decltype(std::forward<T>(t).write(mp4_write_tag{}, o)) { return std::forward<T>(t).write(mp4_write_tag{}, o); } // This struct, and the inline variable below, are to make write() a // customization point object, using a niebloid. // // See: // * https://ericniebler.com/2014/10/21/customization-point-design-in-c11-and-beyond/ // * https://brevzin.github.io/c++/2020/12/19/cpo-niebloid/ struct write_func { template <typename T> constexpr auto write(std::ostream& o, T&& t) const -> decltype(write(o, std::forward<T>(t))) requires std::same_as<decltype(write(o, std::forward<T>(t))), std::ostream&> { write(o, std::forward<T>(t)); return o; } }; } // namespace _detail inline constexpr auto write = _detail::write_func{}; } // namespace mp4 Now you can add a write() function to the box_type_t class above like so: // In the mp4 namespace, of course. namespace mp4 { class box_type_t { // ... [everything else as above] ... public: auto write(_detail::mp4_write_tag, std::ostream& o) const -> std::ostream& { // Same implementation as the normal stream inserter, but doesn't // have to be. (For example, the normal stream inserter could handle // conversions to non-UTF8/ASCII char types.) auto buf = std::array<char, 5>{'\0', '\0', '\0', '\0', '\0'}; std::ranges::copy_n(bt._data.data(), bt._data.size(), buf.data()); return o << buf.data(); } }; } // namepsace mp4
{ "domain": "codereview.stackexchange", "id": 43194, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, memory-management, io, video", "url": null }
c++, memory-management, io, video return o << buf.data(); } }; } // namepsace mp4 And now, writing a chunk like the one in your code would be as simple as this: // The raw chunk data: auto size = std::uint_fast32_t{24}; // yes, this is a magic number, and thus bad, but bear with me auto type = mp4::box_type_t{"ftyp"}; auto brand = mp4::brand_t{"mp41"}; // brand_t is similar to box_type_t auto minor = std::uint_fast32_t{0}; auto compatible_brands = std::array{ mp4::brand_t{"isom"}, mp4::brand_t{"xxxx"} }; // Writing the data: mp4::write(f, size); mp4::write(f, type); mp4::write(f, brand); mp4::write(f, minor); for (auto&& b : compatible_brands) mp4::write(f, b); And of course, if you made a proper type for the chunk: // Initializing the chunk (using a proper constructor). // // Only non-default data needs to be provided auto ftbox = ftbox_t{ mp4::box_type_t{"mp41"}, std::array{ mp4::box_type_t{"isom"}, mp4::box_type_t{"xxxx"} }; } // Writing the data: mp4::write(f, ftbox); Safe, clean, elegant, and idiot-proof. That’s the payoff from getting the types right. In fact, let's go a step further, and presume we have an abstract base class box_t, from which ftbox_t is derived: namespace mp4 { class box_t { public: virtual ~box_t() = default; // Assume no extra data in the chunk by default. You decide whether that's // wise, and if not, just make the function pure virtual. virtual auto payload_size() const noexcept -> std::uint_fast32_t { return 0; } virtual auto type() const noexcept -> box_type_t = 0; // This function and _do_write() use the non-virtual interface pattern. // // See: https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-Virtual_Interface auto write(_detail::mp4_write_tag, std::ostream& o) const -> std::ostream& { // The chunk size: mp4::write(o, std::uint_fast32_t(payload_size() + 8)); // The chunk type: mp4::write(o, type());
{ "domain": "codereview.stackexchange", "id": 43194, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, memory-management, io, video", "url": null }
c++, memory-management, io, video // The chunk type: mp4::write(o, type()); // The chunk's data: do_write(o); return o; // Note that there is another, safer, though less efficient way to // do this. // // Simply don't have a payload_size() function, and instead do: // // // Write the chunk data into a buffer. // auto buffer = std::ostringstream{}; // do_write(buffer); // // // Get the size of that data written. // auto const payload_size = buffer.view().size(); // // // Now write the actual chunk size: // mp4::write(o, std::uint_fast32_t(payload_size + 8)); // // // The chunk type: // mp4::write(o, type()); // // // The chunk's data: // o << buffer.rdbuf(); // // return o; // // The extra cost is that additional buffer. But it’s guaranteed to // have the correct size, so... you have to weigh the trade-offs. } private: virtual auto do_write(std::ostream&) const -> std::ostream& = 0; }; class ftbox_t : public box_t { public: // Obviously make some sensible constructors.... auto payload_size() const noexcept -> std::uint_fast32_t override { return std::uint_fast32_t( 4 // size of brand + 4 // size of minor + (_compatible_brands.size() * 4) ); // Note that I've hardcoded the size of each thing. A better solution // might be to have a mp4::write_size() function that returns the // correct written size for whatever. So this function would be: // // return mp4::write_size(_brand) // + mp4::write_size(_minor) // + mp4::write_size(_compatible_brands) // ; }
{ "domain": "codereview.stackexchange", "id": 43194, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, memory-management, io, video", "url": null }
c++, memory-management, io, video auto type() const noexcept -> box_type_t override { return box_type_t{"ftyp"}; } private: auto do_write(std::ostream& o) const -> std::ostream& override { mp4::write(o, _brand); mp4::write(o, _minor); for (auto&& b : _compatible_brands) mp4::write(o, b); } brand_t _brand; minor_t _minor; std::array<brand_t, 2> _compatible_brands; // I just realized I've been assuming there can always only be 2 // compatible brands. If the number of compatible brands can vary, then // instead of using an array, you could use a vector. }; } // namespace mp4 If you make derived classes for all chunk types, then creating and writing an entire MP4 file would be as simple as: auto chunks = std::vector<std::unique_ptr<mp4::box_t>>{}; // Make as many chunks as you like. For example: chunks.push_back(std::make_unique<mp4::ftbox_t>( mp4::brand_t{"mp41"}, std::array{ mp4::brand_t{"isom"}, mp4::brand_t{"xxxx"} } )); // Now write all the chunks: for (auto&& p_chunk : chunks) mp4::write(f, *p_chunk); // Or make a function that writes a whole MP4 in one shot: // mp4::write_file(f, chunks);
{ "domain": "codereview.stackexchange", "id": 43194, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, memory-management, io, video", "url": null }
c++, memory-management, io, video // Or make a function that writes a whole MP4 in one shot: // mp4::write_file(f, chunks); You might be concerned about the efficiency of all the above. That’s usually the concern that drives people to writing all the type-punning shenanigans involving casts to raw memory and such. Well, here’s the punchline that might blow your mind: Your code will be significantly slower than the code I write above. Why? Because all the work you do to create a buffer—that string stream—and then write all the items into that buffer so you ultimately byte-blast it into the final output stream… all of that is just wasted effort. Streams are already buffered. (That includes the C streams, which most people don’t know.) So all the manual work you do to create that buffer, and then blast the buffer contents into the stream… that’s already happening. You’re just creating an unnecessary, extra buffer. Instead of going “data → buffer → stream”, you’re going “data → buffer 1 → buffer 2 → stream”. All you need to do to get maximally efficient output is get the data into the stream as efficiently as possible. After that, the library will handle buffering it, and then blasting it into the file as quickly as possible, probably in multi-kilobyte chunks at a time. The trick, then becomes getting the data into the stream as efficiently as possible and that… that’s a complex topic that could take entire books to really cover. But one trick will you get a long way there: Avoid formatted output functions… especially those that use locales. Basically, write() is your friend… never use operator<< (well, it’s okay for strings, because they're unformatted output… it’s also fine for copying from one stream to another via the stream buffer). For example, consider writing 32-bit integers. What you could do is this: namespace mp4 { namespace _detail {
{ "domain": "codereview.stackexchange", "id": 43194, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, memory-management, io, video", "url": null }
c++, memory-management, io, video namespace _detail { auto write(std::ostream& o, std::uint_fast32_t i) -> std::ostream& { auto const buf = std::array<char, 4>{ static_cast<char>((i >> 24) & 0xFFu), static_cast<char>((i >> 16) & 0xFFu), static_cast<char>((i >> 8) & 0xFFu), static_cast<char>(i & 0xFFu) }; return o.write(buf.data(), buf.size()); } } // namespace _detail } // namepsace mp4
{ "domain": "codereview.stackexchange", "id": 43194, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, memory-management, io, video", "url": null }
c++, memory-management, io, video You can’t get any faster than that. Wait, you may be thinking… creating an array buffer, then manually copying the integer byte-by-byte while doing all those arithmetic operations… surely that can’t be as efficient as a __bswap_32 compiler intrinsic?! Wanna bet? There are two functions in that code, blast() and write(). blast() just reinterpret_casts the number to bytes, and then copies those to the stream. As you might expect, this causes issues with endianness (see the output on the bottom right). It’s as ultimately fast as you can hope for… aside from giving the wrong result, but slipping a __bswap_32 in there would fix that, right? Take a look at the assembly generated for the two functions over on the upper right. blast() is lines 2–8. write() is lines 10–17. Notice that the assembly generated for the two functions is identical… … … except write() does the bswap correctly (on line 11)! That’s GCC on O2. Clang does the same optimization on O1. There’s a moral here, and it is this: When programming in C++, trust the compiler. Don’t try to outsmart it. Don’t try to work around it. It is smarter than you are. If you try to fight it, or do things to outsmart it, it is you who will end up looking silly in the end. In this case, it is smart enough to recognize that what we’re doing with that temporary array is a 32-bit bswap. So… it just does it. And this is perfectly portable code (well, I mean, once you static assert that char is 8 bits), that will work on any system… regardless of endianness—even on bizarre “PDP-endian” systems—and regardless of the size of uint_fast32_t (for the record, it’s actually 64 bits on the system Compiler Explorer is using… if you tried to cast a 64-bit number to raw bytes then do a 32-bit bswap on a big-endian machine… well, you’d get grief).
{ "domain": "codereview.stackexchange", "id": 43194, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, memory-management, io, video", "url": null }
c++, memory-management, io, video The power of C++ is at compile time. It’s in the type system, and it’s in the stupidly-powerful compiler technologies that optimize the bejeezus out of your code. Leverage that power; don’t “work around” it, and don’t fight it. Write what you mean—the reason Stroustrup invented C++ in the first place was explicitly to meaningfully model stuff, and translate those models to efficient machine code. Focus on correctly modelling your problem, and let the compiler sort out transforming what you mean to the most efficient machine code possible. Remember these mantras:
{ "domain": "codereview.stackexchange", "id": 43194, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, memory-management, io, video", "url": null }
c++, memory-management, io, video The power of C++ is at compile time. When you get the types right, everything Just Works. Write what you mean; let the compiler handle translating to efficient machine code. Trust the compiler… but always check if it matters.* And to summarize the review: Make proper types for the elements of your problem. For example, you have a “ftbox”—which is a specific type of “box”—that has a “brand”, a “minor” (whatever that means), and a list of compatible “brands”. That’s a list of classes to make, right there: you need a class ftbox, which is derived from box, that has data members with type brand, minor, and an array/vector of brand. Each of those types has to support being written to files/streams, so you probably need a generic/overloaded write() function. And so on…. In every case, is you write those types well, they will be maximally ergonomic and efficient, and using them and combining them will be effortless. When you get the types right, everything Just Works.
{ "domain": "codereview.stackexchange", "id": 43194, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, memory-management, io, video", "url": null }
c++, memory-management, io, video Don’t write shitty code because you think it’s efficient. For starters, it often isn’t. It happens regularly that I see C++ beginners twist themselves in knots writing almost illegible, low-level, C-like code… that is slower—sometimes by orders of magnitude—than a single line of high-level C++. But even in the “best” case, where that low-level, C-like code is extremely efficient, it is almost always true that high-level C++ code can match its performance. Or, if not, the C++ code is only slower by an amount that doesn’t actually matter in practice. (In this case, an example would be bending over backwards to make reversing the endianness of a number, even though, in the slowest case, that cost will be absolutely dwarfed by the cost of actually writing the bytes to a file. So if your byte-swapping is slow, no-one will ever notice.) Here, for example, there are not only no benefits to all the gymnastics to efficiently write byte sequences to a buffer, then writing that buffer to a stream… because the stream is already buffered. You could avoid the extra costs by doing the simple and obvious thing: just write the byte sequences directly to the stream. Good, clean, well-written, high-level C++ code will be just as fast as even the most well-done juggling of bytes in raw memory… and it will be much easier to read, understand, and maintain.
{ "domain": "codereview.stackexchange", "id": 43194, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, memory-management, io, video", "url": null }
c#, performance, programming-challenge, array Title: Distribute items over array in order to minimize the difference between min and max array values Question: I came across this problem in a programming challenge a few days ago. I came up with the implementation below, however it resulted in a "time limit exceeded" failure for a few of the test cases. The questions were unfortunately not made available after the challenge was over but it went something like this: There are a number of CPUs that each have a number of jobs already assigned to them. The CPUs are represented as an integer array cpus where cpus[i] represents the number of jobs currently assigned to the \$ith\$ CPU. You are given a number of additional jobs to assign to the CPUs. The goal is to assign the new jobs to the CPUs in a way that minimizes the difference between the CPU with the maximum number of jobs assigned and the CPU with the minimum number of jobs assigned. All jobs must be assigned to a CPU. Jobs that have been assigned to a CPU cannot be reassigned to a different CPU. The constraints were all quite large, something like: \$1 <= cpus.Length <= 10^6\$ \$0 <= cpus[i] <= 10^6\$ \$1 <= jobs <= 10^9\$ The only way that I could visualize a solution was to first sort the array, and then fill in the jobs iteratively working from the smallest array elements up. Basically "pouring" the jobs into the lower void of the array and filling it up as if it were being filled with a liquid until all the array values were equal (or all jobs have been distributed). Evidently there is a faster way to do this! int MaxDifference(int[] cpus, int jobs) {
{ "domain": "codereview.stackexchange", "id": 43195, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance, programming-challenge, array", "url": null }
c#, performance, programming-challenge, array // Sort the array in ascending order. Array.Sort(cpus); // Get the initial min/max values. var min = cpus[0]; var max = cpus[cpus.Length - 1]; // Distribute the jobs over the CPUs until all jobs are allocated or all CPUs have an equal number of jobs. var i = 0; while (jobs > 0 && min < max) { // Distribute a job to the current CPU. cpus[i]++; jobs--; // Advance to the next CPU if it has fewer jobs than the current one or start over at the beginning. if (i < cpus.Length - 1 && cpus[i + 1] < cpus[i]) { i++; } else { i = 0; } // Update the new min value. min = cpus[i]; } // Check to see which condition halted our distribution loop. if (jobs > 0) { // Since all CPUs have an equal number of jobs the max difference can only be 0 or 1. return jobs % cpus.Length == 0 ? 0 : 1; } else { // Since all jobs have been allocated just return the difference between the max and the min. return max - min; } }
{ "domain": "codereview.stackexchange", "id": 43195, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance, programming-challenge, array", "url": null }
c#, performance, programming-challenge, array Answer: This is not a proper review, but an extended comment. Your visualization is correct. The time complexity problem stems from the way the jobs are poured. You pour them one at a time. You may do better pouring them in rounds. Let \$c_i\$ be a number of jobs at \$i_{th}\$ cpu after sorting. The goal of the first round is to equalize \$c_0\$ and \$c_1\$. It takes \$c_1 - c_0\$ jobs. The goal of the second round is to equalize \$c_0, c_1, c_2\$ it tales \$2 (c_2 - c1)\$ jobs (\$c_0\$ is already equal to \$c_1\$. In general. the \$k_{th}\$ round, equalizing everything to \$c_k\$, takes \$k (c_k - c_{k-1})\$ jobs. This observation hints a solution: cumulatively compute \$\sum_{k=1} k(c_k - c_{k-1})\$ for as long as it is less than the amount of jobs. The resulting time complexity is linear in the number of CPUs; of course the sorting phase would dominate.
{ "domain": "codereview.stackexchange", "id": 43195, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance, programming-challenge, array", "url": null }
c#, performance Title: Updating items of one List that match another List Question: I'm using VS 2008. I pass a List<T> a using ref, along with another List<T> b. I need to cycle thru List<T> b, which contains around 200,000 items, and for each item in b, it it matches criteria in a, which contains 100,000 or more items, and update it. public static void UpdateList(ref List<ExampleT> a, List<ExampleT> b) { var count = 0; for (int i = 0; i < b.Count; i++) { foreach (var z in a.FindAll(x => x.MatchA == b[i].MatchA && x.MatchB == b[i].MatchB)) { z.ToUpdate = b[i].ToUpdate; count++; } if(count >= 10000) break; } } Now, the only reason I added count was so that once 10000 items in a have been updated, the loop will stop, otherwise it will take a very long time to go thru all of the items. Even by limiting it like this, it still takes around 3 min. For the sake of the example, T in this case is an object similar to the following: public class ExampleT { public string MatchA {get;set;} public string MatchB {get;set;} public double? ToUpdate {get;set;} //in List a this will ALWAYS be null until it gets updated in the foreach } Is there a way I can make this more efficient? Answer: Your code is O(n m), where n is the length of a and m is the length of b. You could make it O(n + m) (assuming only a small number of items from a match each item in b) by using a hash table. One possible way to do this is to use ToLookup(): var aLookup = a.ToLookup(x => new { x.MatchA, x.MatchB }); foreach (var bItem in b) { foreach (var aItem in aLookup[new { bItem.MatchA, bItem.MatchB }]) aItem.ToUpdate = bItem.ToUpdate; } Another way to do basically the same thing would be using join: var pairs = from bItem in b join aItem in a on new { bItem.MatchA, bItem.MatchB } equals new { aItem.MatchA, aItem.MatchB } select new { bItem, aItem };
{ "domain": "codereview.stackexchange", "id": 43196, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance", "url": null }
c#, performance foreach (var pair in pairs) pair.aItem.ToUpdate = pair.bItem.ToUpdate; Also, you should really use better variable names.
{ "domain": "codereview.stackexchange", "id": 43196, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance", "url": null }
javascript, html Title: Price toggle with upsell remover/adder Question: I've created a working price toggler, that also has an upsell remover/adder. While it works well, I'd like to understand how I could do it better, because I'm having to essentially run two compound if/else statements to account for the duration toggle and the upsell toggle. const pricing = document.querySelector('#toggle'); var single = pricing.dataset.scMonthly; var both = pricing.dataset.bothMonthly; var bc = pricing.dataset.bcMonthly; var price = both; function setPackage(){ if (document.getElementById("package").checked == true) { if (document.getElementById("toggle").checked == true) { var price = both; document.getElementById("price").innerHTML = price; } else { var price = both * 10; document.getElementById("price").innerHTML = price; } } else { if (document.getElementById("toggle").checked == true) { var price = single; document.getElementById("price").innerHTML = price; } else { var price = single * 10; document.getElementById("price").innerHTML = price; } } } function setPrice() { var x = document.querySelectorAll('.annual'); var y = document.querySelectorAll('.month'); for (var i = 0; i < x.length; i++) { if (document.getElementById("toggle").checked == true) { x[i].classList.add('hidden'); y[i].classList.remove('hidden'); if (document.getElementById("package").checked == true) { document.getElementById("price").innerHTML = both; } else { document.getElementById("price").innerHTML = single; } document.getElementById("bcValue").innerHTML = bc; } else { x[i].classList.remove('hidden'); y[i].classList.add('hidden');
{ "domain": "codereview.stackexchange", "id": 43197, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, html", "url": null }
javascript, html if (document.getElementById("package").checked == true) { document.getElementById("price").innerHTML = both * 10; } else { document.getElementById("price").innerHTML = single * 10; } document.getElementById("bcValue").innerHTML = bc * 10; } } } <div> <p>Annually</p> <!-- Toggle Button --> <label for="toggle"> <!-- toggle --> <div class="relative"> <!-- hidden input --> <input id="toggle" type="checkbox" class="hidden" onclick="setPrice()" data-sc-monthly="59" data-both-monthly="79" data-bc-monthly="20" /> <!-- line --> <div></div> <!-- dot --> <div class="toggle_dot"></div> </div> </label> <p>Monthly</p> </div> <div> <div> <h3>Main Report</h3> <h4>$<span id="price">790</span></h4> <p><span class="annual">ANNUALLY</span><span class="month hidden">MONTHLY</span></p> <div> <input id="package" type="checkbox" onclick="setPackage()" checked /> <h5>Include our special secondary coverage for just $<span id="bcValue">200</span></h5> </div> <a class="btn btn-success"> JOIN NOW </a> </div> </div> As you can see, each function has to check if the parameters controlled by the other function are set or not, and make adjustments accordingly. My JS-fu is not strong enough yet to figure out how to improve this code overall. Thanks for any help!
{ "domain": "codereview.stackexchange", "id": 43197, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, html", "url": null }
javascript, html Answer: Your for loop in setPrice has a lot of code that does not vary between iterations of the loop. The loop only needs to add or remove the relevant class property, and the other code should be outside the loop. A couple of helper functions may be useful to take care of this. function hideAll(query) { for (const element of document.querySelectorAll(query)) { element.classList.add("hidden"); } } function showAll(query) { for (const element of document.querySelectorAll(query)) { element.classList.remove("hidden"); } } For the rest of the code, write a single function that updates values taking into account the status of all checkboxes. This will be triggered whenever anything changes in the form. This may mean some very minor inefficiencies (updating the innerHTML of bcValue when it hasn't actually changed) but will dramatically simplify the code. (If your page does eventually become much more complicated, you could write some extra code to check whether relevant values have changed before updating them on the page. It will still be simpler and easier to maintain than having every tick-box trigger a different function which independently updates the same set of values.) function update() { const package = document.getElementById("package").checked ? both : single; let factor; if (document.getElementById("toggle").checked) { factor = 1; hideAll(".annual"); showAll(".month"); } else { factor = 10; showAll(".annual"); hideAll(".month"); } document.getElementById("price").innerHTML = package * factor; document.getElementById("bcValue").innerHTML = bc * factor; } It's usually better to set event listeners within javascript instead of in the HTML, making it easier to change, add more complicated behaviors, and having all of the logic in one place.
{ "domain": "codereview.stackexchange", "id": 43197, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, html", "url": null }
javascript, html document.getElementById("toggle").addEventListener("click", update); document.getElementById("package").addEventListener("click", update); for (const id of ["toggle", "package"]) { document.getElementById(id).addEventListener("click", update); }
{ "domain": "codereview.stackexchange", "id": 43197, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, html", "url": null }
c, linked-list Title: Linked-list in C without typedefs and globals? Question: I took RosettaCode's implementation and tried to create something useable (editing their wiki as I go to give-back): #include <stdlib.h> #include <stdio.h> struct elem { long data; struct elem *next; }; Insert struct elem *addToList(struct elem *node, long num) { struct elem *iter, *temp; if (node == NULL) { node = (struct elem *)malloc(sizeof(struct elem *)); node->data = num; node->next = NULL; } else { iter = node; while (iter->next != NULL) { iter = iter->next; } temp = (struct elem *)malloc(sizeof(struct elem *)); temp->data = num; temp->next = NULL; iter->next = temp; } return node; } Delete struct elem *deleteFromList(struct elem *node, size_t pos) { size_t i = 1; struct elem *temp, *iter; if (node != NULL) { iter = node; if (pos == 1) { node = node->next; iter->next = NULL; free(iter); } else { while (i++ != pos - 1) iter = iter->next; temp = iter->next; iter->next = temp->next; temp->next = NULL; free(temp); } } return node; } Print void printList(struct elem *node) { struct elem *iter; puts("List contains following elements : \n"); for (iter = node; iter != NULL; iter = iter->next) { printf("%ld ", iter->data); // access data, e.g. with iter->data } } ASans crashes @ node->next = NULL of addToList with heap-buffer-overflow. What do you think of this implementation? - How can it be improved? Answer: Special cases are bad. Eliminate them if possible. Specifically, an empty list is not all that special. Is an empty list any more special than an unexpectedly short list? Extract useful functions if possible. Appending consists of finding the end, and prepending to it, two useful functions. Do you write C or C++? In C, casting the result of malloc() is heavily frowned upon, as it means useless repetition.
{ "domain": "codereview.stackexchange", "id": 43198, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, linked-list", "url": null }
c, linked-list Avoid sizeof(TYPE). One easily gets it wrong (as you do!!), it haphazardly sprinkles unchecked duplicate information (the type) about which has to be manually verified, and it impedes refactoring. Use sizeof *target instead, which properly couples size and use. Unless you are restricted to strict C90 or earlier, you can mix declarations and instructions. Doing so limits scope and simplifies code. A pointer has a truth-value, no need to compare to a null pointer constant. Use concise but precise names. If you add to a list, where do you add it? To every element. Prepended. Appended. Behind a given node / index / value. Randomly. Arbitrarily. ... C does not have namespaces, thus the use of prefixes to avoid collisions. Consider an appropriate one. Dynamic allocation can fail. Deal with it. Applying it to the first function: struct elem **list_end(struct elem **p) { assert(p); while (*p) p = &p[0]->next; return p; } struct elem **list_prepend(struct elem **p, long v) { assert(p); struct elem *x = malloc(sizeof *x); if (!x) return NULL; /* or abort(); */ x->data = v; x->next = *p; *p = x; return &x->next; } struct elem **list_append(struct elem **p, long v) { return list_prepend(list_end(p), v); }
{ "domain": "codereview.stackexchange", "id": 43198, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, linked-list", "url": null }
java, functional-programming Title: Stream Partitioner Question: Discussion I've been trying to increase my knowledge of Java Streams and for practice, I devised up the requirement of partitioning a Stream of values into a Stream of a List of values. Implementation package data.structures.streams.utils; import java.util.ArrayList; import java.util.List; import java.util.Spliterator; import java.util.Spliterators; import java.util.function.Consumer; import java.util.stream.Stream; import java.util.stream.StreamSupport; public class Partitioner { static class PartitionSpliterator<T> extends Spliterators.AbstractSpliterator<List<T>> { private final Spliterator<T> values; private final int partitionSize; private List<T> currentPartition; public PartitionSpliterator(final Spliterator<T> values, final int partitionSize) { super( Double.valueOf(Math.ceil((double) (values.estimateSize() / partitionSize))) .intValue(), ORDERED | IMMUTABLE | SIZED | SUBSIZED ); if (1 > partitionSize) { throw new IllegalArgumentException("Size must be a positive integer"); } this.values = values; this.partitionSize = partitionSize; this.currentPartition = null; } @Override public boolean tryAdvance(Consumer<? super List<T>> action) { if (null == currentPartition) { currentPartition = new ArrayList<>(); } while (partitionSize > currentPartition.size() && values.tryAdvance(currentPartition::add)) { } if (currentPartition.isEmpty()) { return false; } action.accept(currentPartition); currentPartition = null; return true; } }
{ "domain": "codereview.stackexchange", "id": 43199, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, functional-programming", "url": null }
java, functional-programming public static <Value> Stream<List<Value>> partition(final Stream<Value> values, final int size) { if (1 > size) { throw new IllegalArgumentException("Size must be a positive integer"); } return StreamSupport.stream( new PartitionSpliterator<>(values.spliterator(), size), values.isParallel() ); } } Answer: Avoid naming generic types in such a way as they look like classes. This is confusing to readers of the code. The official convention would suggest V rather than Value. Other answers to that question provide other conventions. The code has every comparison between two values done in the opposite way as the vast majority of programmers would expect. This makes the code harder to read. When comparing a constant to a variable, by convention the variable is first. When comparing two variables, if one is iterated upwards and one is the fixed upper bound, by convention the iterated value is first. When comparing a variable to null, by convention the variable is first.
{ "domain": "codereview.stackexchange", "id": 43199, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, functional-programming", "url": null }